Compare commits

..
Author SHA1 Message Date
snowluma-bot[bot] 3c9f2ab1eb Merge pull request #379 from SnowLuma/dev
chore: promote dev → main (9772d4f)
2026-08-16 13:58:28 +00:00
snowluma-bot[bot] 8a82d28b80 Merge pull request #378 from SnowLuma/dev
chore: promote dev → main (fea1996)
2026-08-16 07:18:55 +00:00
snowluma-bot[bot] f4c2ed5794 Merge pull request #368 from SnowLuma/dev
chore: promote dev → main (401f32d)
2026-08-14 06:55:54 +00:00
snowluma-bot[bot] 4b9fe71380 Merge pull request #360 from SnowLuma/dev
chore: promote dev → main (d46d8e4)
2026-08-13 11:47:51 +00:00
snowluma-bot[bot] f72c0da4fc Merge pull request #357 from SnowLuma/dev
chore: promote dev → main (d26aef8)
2026-08-13 04:52:47 +00:00
snowluma-bot[bot] 180573e581 Merge pull request #347 from SnowLuma/dev
chore: promote dev → main (0357d13)
2026-08-11 10:20:44 +00:00
snowluma-bot[bot] eaf56896ce Merge pull request #338 from SnowLuma/dev
chore: promote dev → main (dbf654a)
2026-08-09 08:53:42 +00:00
snowluma-bot[bot] 81a898087c Merge pull request #328 from SnowLuma/dev
chore: promote dev → main (7eea805)
2026-08-08 11:45:26 +00:00
snowluma-bot[bot] 74964b3667 Merge pull request #327 from SnowLuma/dev
chore: promote dev → main (4c385bf)
2026-08-08 09:53:49 +00:00
snowluma-bot[bot] 3248fb6ffb Merge pull request #326 from SnowLuma/dev
chore: promote dev → main (f968687)
2026-08-08 09:46:59 +00:00
snowluma-bot[bot] 2c8b1cc382 Merge pull request #323 from SnowLuma/dev
chore: promote dev → main (4d958eb)
2026-08-07 12:29:30 +00:00
snowluma-bot[bot] ebbe90be7e Merge pull request #309 from SnowLuma/dev
chore: promote dev → main (f572be2)
2026-08-03 11:35:41 +00:00
snowluma-bot[bot] 28b3518502 Merge pull request #301 from SnowLuma/dev
chore: promote dev → main (4794f27)
2026-07-31 10:19:37 +00:00
snowluma-bot[bot] 7fd07f9170 Merge pull request #287 from SnowLuma/dev
chore: promote dev → main (df3f8c5)
2026-07-26 11:29:53 +00:00
snowluma-bot[bot] e1cd0176ca Merge pull request #278 from SnowLuma/dev
chore: promote dev → main (c64f9d3)
2026-07-24 06:16:20 +00:00
snowluma-bot[bot] eac81f8b19 Merge pull request #271 from SnowLuma/dev
chore: promote dev → main (97ab8dc)
2026-07-22 12:04:17 +00:00
snowluma-bot[bot] ccd46aafb3 Merge pull request #255 from SnowLuma/dev
chore: promote dev → main (88216ce)
2026-07-20 07:53:18 +00:00
snowluma-bot[bot] 179d1efe01 Merge pull request #249 from SnowLuma/dev
chore: promote dev → main (4e62fdc)
2026-07-19 11:38:38 +00:00
snowluma-bot[bot] fb451ff3e8 Merge pull request #240 from SnowLuma/dev
chore: promote dev → main (4391b45)
2026-07-17 10:48:17 +00:00
snowluma-bot[bot] 2f8b1c8e68 Merge pull request #238 from SnowLuma/dev
chore: promote dev → main (6a1042e)
2026-07-16 12:29:24 +00:00
snowluma-bot[bot] 383f6aa818 Merge pull request #235 from SnowLuma/dev
chore: promote dev → main (ebd02c3)
2026-07-15 13:32:32 +00:00
snowluma-bot[bot] 06106d2bd3 Merge pull request #224 from SnowLuma/dev
chore: promote dev → main (a3467a8)
2026-07-13 23:57:45 +00:00
snowluma-bot[bot] da04381436 Merge pull request #214 from SnowLuma/dev
chore: promote dev → main (c04864d)
2026-07-10 06:01:06 +00:00
snowluma-bot[bot] fbc2aa052b Merge pull request #210 from SnowLuma/dev
chore: promote dev → main (b6fb5bd)
2026-07-07 14:38:33 +00:00
snowluma-bot[bot] 8a7b2413f4 Merge pull request #204 from SnowLuma/dev
chore: promote dev → main (d35e276)
2026-07-06 07:05:23 +00:00
snowluma-bot[bot] 18d8273f5c Merge pull request #202 from SnowLuma/dev
chore: promote dev → main (0e6e2ec)
2026-07-05 06:26:33 +00:00
snowluma-bot[bot] 5f01c6ab5f Merge pull request #198 from SnowLuma/dev
chore: promote dev → main (6cb7f2c)
2026-07-04 05:39:20 +00:00
snowluma-bot[bot] a11c684dfd Merge pull request #183 from SnowLuma/dev
chore: promote dev → main (72aedbc)
2026-07-01 14:15:29 +00:00
snowluma-bot[bot] b807825a09 Merge pull request #175 from SnowLuma/dev
chore: promote dev → main (48e2777)
2026-06-30 12:39:05 +00:00
snowluma-bot[bot] 688402814c Merge pull request #159 from SnowLuma/dev
chore: promote dev → main (7ec74f2)
2026-06-28 14:48:25 +00:00
snowluma-bot[bot] a60385c376 Merge pull request #150 from SnowLuma/dev
chore: promote dev → main (351db57)
2026-06-26 11:50:10 +00:00
snowluma-bot[bot] 157cc90397 Merge pull request #132 from SnowLuma/dev
chore: promote dev → main (1bd1265)
2026-06-22 13:31:34 +00:00
snowluma-bot[bot] f470b7a10c Merge pull request #122 from SnowLuma/dev
chore: promote dev → main (8b87f80)
2026-06-21 17:45:50 +00:00
snowluma-bot[bot] 7f391e065e Merge pull request #117 from SnowLuma/dev
chore: promote dev → main (9efe162)
2026-06-21 12:23:09 +00:00
snowluma-bot[bot] 261d6596dc Merge pull request #109 from SnowLuma/dev
chore: promote dev → main (dfb6aa5)
2026-06-18 09:16:43 +00:00
snowluma-bot[bot] 5d08fc8471 Merge pull request #103 from SnowLuma/dev
chore: promote dev → main (16920b4)
2026-06-16 14:00:12 +00:00
snowluma-bot[bot] e5e6d50f2f Merge pull request #101 from SnowLuma/dev
chore: promote dev → main (7e59dbf)
2026-06-15 05:58:03 +00:00
snowluma-bot[bot] 7d90820e19 Merge pull request #100 from SnowLuma/dev
chore: promote dev → main (ee8eb92)
2026-06-14 08:29:02 +00:00
snowluma-bot[bot] 69195ced93 Merge pull request #95 from SnowLuma/dev
chore: promote dev → main (a3a3671)
2026-06-11 08:42:47 +00:00
snowluma-bot[bot] d2c56d565b Merge pull request #92 from SnowLuma/dev
chore: promote dev → main (d508814)
2026-06-09 06:23:12 +00:00
snowluma-bot[bot] cc27cd1f43 Merge pull request #89 from SnowLuma/dev
chore: promote dev → main (515bac4)
2026-06-07 14:30:05 +00:00
snowluma-bot[bot] 40c65c87bd Merge pull request #88 from SnowLuma/dev
chore: promote dev → main (174150c)
2026-06-07 13:20:48 +00:00
381 changed files with 3073 additions and 20957 deletions

No files matched your search

+1 -1
View File
@@ -123,7 +123,7 @@ body:
attributes:
label: TRACE 日志 / 错误堆栈
description: |
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现,务必保留原始报文和完整Trace内容。
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现。
开启 TRACE 的两种方式(任选其一):
- **WebUI(推荐)**:进入「日志」页 →「服务端日志级别」切到 `TRACE` → 显示过滤切到「开发」预设(确保 TRACE 行可见,否则导出不含 trace)→ 复现问题 → 点「导出当前视图」得到 `snowluma-logs-*.log`,拖到本输入框上传。
-30
View File
@@ -1,30 +0,0 @@
# 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.
+8 -2
View File
@@ -1,5 +1,4 @@
# Run the root validation commands on every pull request.
# Command list is duplicated in tools/ci-check.mjs — keep them identical.
name: CI
on:
@@ -39,7 +38,14 @@ 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: node tools/check-action-catalog.mjs
run: |
catalog_status="$(git status --porcelain=v1 --untracked-files=all -- packages/mcp/src/generated)"
if [ -n "$catalog_status" ]; then
git diff -- packages/mcp/src/generated
printf '%s\n' "$catalog_status"
echo '::error::Generated action catalog is stale. Run `pnpm --filter @snowluma/mcp gen` and commit packages/mcp/src/generated/.' >&2
exit 1
fi
typecheck:
runs-on: ubuntu-latest
@@ -22,10 +22,6 @@ 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
@@ -46,8 +42,6 @@ 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: |
@@ -65,7 +59,6 @@ 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,
@@ -79,8 +72,7 @@ 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}, ghcr_image=${ghcrImage}, platforms=${platforms}).`);
core.info(`Re-dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);
@@ -1,20 +0,0 @@
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
+10 -10
View File
@@ -40,10 +40,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v6
with:
# 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'
node-version-file: '.node-version'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
@@ -80,17 +77,21 @@ jobs:
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Show Trusted Publishing toolchain
- name: Validate npm token
if: steps.npm.outputs.already_published != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
node --version
npm --version
if [ -z "${NODE_AUTH_TOKEN}" ]; then
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
exit 1
fi
- name: Publish MCP to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/mcp
# Authentication is supplied by npm Trusted Publishing through the
# GitHub OIDC token (permissions.id-token: write above).
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm publish --access public --provenance
- name: Summary
@@ -105,5 +106,4 @@ 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}"
+128 -33
View File
@@ -1,13 +1,20 @@
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
@@ -21,6 +28,8 @@ 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
@@ -30,24 +39,32 @@ 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'
@@ -63,6 +80,8 @@ jobs:
{
echo "run=${run}"
echo "auto_merge=${auto_merge}"
echo "merge_method=${merge_method}"
echo "reason=${reason}"
} >> "${GITHUB_OUTPUT}"
@@ -74,6 +93,8 @@ 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}"
@@ -102,49 +123,123 @@ jobs:
owner: ${{ github.repository_owner }}
repositories: ${{ github.event.repository.name }}
- name: Checkout
- 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
uses: actions/checkout@v6
with:
ref: dev
ref: main
fetch-depth: 0
token: ${{ steps.app-token.outputs.token }}
- name: Point main at dev
- 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'
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
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)"
title="chore: promote dev → main (${DEV_SHORT})"
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 "## Promote"
echo "Automated promotion of \`dev\` into \`main\`."
echo
echo "| Key | Value |"
echo "| --- | --- |"
echo "| \`main\` was | \`${main_sha}\` |"
echo "| \`main\` now | \`dev\` @ \`${dev_sha}\` |"
echo "| Reason | ${REASON} |"
echo "| Source | \`dev\` @ \`${DEV_SHA}\` |"
echo "| Trigger ref | \`${REF}\` |"
echo "| Trigger 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}"
+9 -5
View File
@@ -37,7 +37,14 @@ jobs:
run: pnpm typecheck
- name: Verify generated action catalog is up to date
run: node tools/check-action-catalog.mjs
run: |
catalog_status="$(git status --porcelain=v1 --untracked-files=all -- packages/mcp/src/generated)"
if [ -n "$catalog_status" ]; then
git diff -- packages/mcp/src/generated
printf '%s\n' "$catalog_status"
echo '::error::Generated action catalog is stale. Run `pnpm --filter @snowluma/mcp gen` and commit packages/mcp/src/generated/.' >&2
exit 1
fi
build:
needs: preflight
@@ -217,7 +224,6 @@ 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: |
@@ -233,7 +239,6 @@ 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,
@@ -247,8 +252,7 @@ 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}, ghcr_image=${ghcrImage}, platforms=${platforms}).`);
core.info(`Dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);
+10 -10
View File
@@ -37,10 +37,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v6
with:
# 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'
node-version-file: '.node-version'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
@@ -77,17 +74,21 @@ jobs:
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Show Trusted Publishing toolchain
- name: Validate npm token
if: steps.npm.outputs.already_published != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
node --version
npm --version
if [ -z "${NODE_AUTH_TOKEN}" ]; then
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
exit 1
fi
- name: Publish SDK to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/sdk
# Authentication is supplied by npm Trusted Publishing through the
# GitHub OIDC token (permissions.id-token: write above).
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm publish --access public --provenance
- name: Summary
@@ -102,5 +103,4 @@ 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}"
+10 -10
View File
@@ -37,10 +37,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v6
with:
# 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'
node-version-file: '.node-version'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
@@ -74,17 +71,21 @@ jobs:
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Show Trusted Publishing toolchain
- name: Validate npm token
if: steps.npm.outputs.already_published != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
node --version
npm --version
if [ -z "${NODE_AUTH_TOKEN}" ]; then
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
exit 1
fi
- name: Publish UI to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/ui
# Authentication is supplied by npm Trusted Publishing through the
# GitHub OIDC token (permissions.id-token: write above).
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm publish --access public --provenance
- name: Summary
@@ -99,5 +100,4 @@ 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}"
-104
View File
@@ -1,104 +0,0 @@
# 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.
-1
View File
@@ -1 +0,0 @@
AGENTS.md
+40 -39
View File
@@ -19,14 +19,6 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
如果你只是想看看代码长什么样,可以直接跳到 [本地开发环境](#本地开发环境)。
### AI Agent 贡献须知
如果你是 AI Agent,并准备为本仓库贡献代码、提交 PR 或提出 issue,请先明确告知你的使用者:
> **请通过 GitHub 网页端手动创建 issue。直接使用 CLI 创建的 issue 会被自动关闭。**
你可以协助整理问题描述、复现步骤和相关日志,并将 issue 草稿交给用户,由用户在网页端完成提交。
---
## 项目结构速览
@@ -41,7 +33,7 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
| `packages/websocket` | WebSocket 实现 |
| `packages/webui` | 基于 Vite + React 的前端控制台 |
| `tools/` | 版本管理、发布脚本 |
| `.github/workflows/` | CI / 发布 / Promote 工作流 |
| `.github/workflows/` | CI / 发布 / 自动合并工作流 |
入口在 `packages/core/src/index.ts`,整体架构在 `packages/core/src/bridge/` 下能看出大致脉络。
@@ -91,7 +83,7 @@ pnpm dev:web # webui
### 1. 创建分支
请基于 `dev` 创建分支,不是 `main`。`main` 是发布指针,只由维护者的 Promote 更新,PR 不要提到 `main`。
请基于 `dev` 创建分支,不是 `main`。`main` 是受保护的稳定分支,PR 也不要直接提到 `main`。
```bash
git checkout dev
@@ -141,7 +133,7 @@ refactor(bridge): extract BridgeInterface as the OneBot-facing seam
docs: clarify dev environment setup steps
```
> ⚠️ **请不要**在你的提交信息里使用 `[merge]` 前缀或 `chore(release):` 前缀 —— 这两个前缀是维护者用来把 `main` 指到 `dev` 的,会让你的 PR 行为异常。详见后文 [维护者参考](#维护者参考release--promote)。
> ⚠️ **请不要**在你的提交信息里使用 `[merge]` 前缀或 `chore(release):` 前缀 —— 这两个前缀是维护者用来触发自动合并到 `main` 的,会让你的 PR 行为异常。详见后文 [维护者参考](#维护者参考release--自动合并流程)。
### 4. 推送并发起 PR
@@ -160,7 +152,7 @@ git push origin fix/onebot-mention-encoding
- 维护者会在能腾出时间时来 review。如果一周内没有任何回应,欢迎在 PR 里 @ 一下,或者去社群里提醒。
- review 意见请尽量在同一个 PR 内修改,避免反复关闭重开。
- 合并方式由维护者决定,通常是 squash merge 到 `dev`。**`main` 由维护者通过 Promote 指到当时的 `dev`**,你不需要操心 `main`。
- 合并方式由维护者决定,通常是 squash merge 到 `dev`。**`main` 由维护者通过自动化工作流统一从 `dev` 合入**,你不需要操心 `main`。
---
@@ -199,30 +191,28 @@ git push origin fix/onebot-mention-encoding
---
## 维护者参考:release & Promote
## 维护者参考:release & 自动合并流程
> 以下内容主要写给具备发版权限的维护者。普通贡献者只需要把 PR 提到 `dev`,不需要关心这一节。
> 以下内容主要写给具备 `main` 推送 / 发版权限的维护者。普通贡献者只需要把 PR 提到 `dev`,不需要关心这一节。
### 分支模型
SnowLuma 使用 **`main` + `dev`** 双分支模型:
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先进入 `dev`。
- **`main`** — 发布指针,应与某次 Promote 当时的 `dev` 尖端是**同一个提交**。不要直接 push,也不要往 `main` 开 PR(CI 会拒)。
- **`main`** — 受保护的稳定分支,仅接收来自 `dev` 的合并 PR。**禁止直接 push**。
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先合入 `dev`。
- **`native/auto-update-*`** — 由 `SnowLuma Bot` 自动创建的原生产物更新分支(来自 `SnowLumaNative`,不需要手动维护)。
### 把 `main` 指到 `dev`
### 把 `dev` 合并到 `main`
工作流 `.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。
工作流 `.github/workflows/promote-dev-to-main.yml` 会以 `SnowLuma Bot` 身份开 / 更新一个 `dev → main` 的 PR,并可选地自动合并。无论用哪种触发方式,工作流都会调用 `gh pr merge --auto`:**只有 `main` 分支保护中所有 required status checks(typecheck + 各架构 build)都通过后,机器人才会真正合并**。失败的工作流会卡住合并。
#### 1. 提交信息前缀(推荐日常使用)
向 `dev` push 一个提交,提交信息**以**以下任一前缀**开头**即触发(不区分大小写):
- `[merge]` — 例如 `[merge] fix: hotfix for OneBot mention`
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯。**只许用在真正的版本 bump**,不要写进普通 CI / 工具提交。
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯
> 是**前缀**匹配,不是任意位置。`fix: something [merge]` 不会触发,必须把 `[merge]` 写在最前面。
@@ -230,22 +220,38 @@ SnowLuma 使用 **`main` + `dev`** 双分支模型:
任何符合 `chore.*` 的 tag(如 `chore.merge-20240509`、`chore.promote-v1.7.0`)被推送时也会触发:
- `chore.*` → 仅触发 `promote-dev-to-main.yml`(把 `main` 指到 `dev`)
- `chore.*` → 仅触发 `promote-dev-to-main.yml`(开 PR,自动合并)
- `v*` → 仅触发 `release.yml`(构建发布产物)
推荐流程:用 `pnpm release`(或先 Promote,再确认 `origin/main` 已等于 `dev` 尖端)之后,在 `main` 上打 `v*` tag。这样 `release.yml` 始终基于当时的 `main` HEAD 构建。
推荐流程:先用 `chore.*` tag 把 `dev` 合入 `main`,待合并完成后再在 `main` 上打 `v*` tag 触发发布。这样 `release.yml` 始终基于已过完所有检查的 `main` HEAD 构建。
#### 3. 手动触发
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。没有 merge 策略选项;跑起来就是一次指针更新。
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。可选输入:
### 不要给 `main` 套「必须走 PR」
- `auto_merge`:是否启用 auto-merge(默认 `true`)。
- `merge_method`:`merge` / `squash` / `rebase`(默认 `merge`)。
Promote 不通过 PR 更新 `main`。如果给 `main` 打开 **Require a pull request before merging** 或禁止更新引用,Promote 会失效。
### 启用 `main` 分支保护(必做)
可以限制删除 `main`。外来 PR 必须打 `dev`;打到 `main` 的 PR 会被 `main-pr-target-guard.yml` 拒绝。
仓库管理员需要在 GitHub 上为 `main` 配置规则集(Repository Rules)或经典分支保护,至少满足:
本地若已经 checkout 过旧的 `main`,Promote 之后可能无法快进,对齐 `origin/main` 即可。
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` 即可重新触发检查。
### 必需的 Secrets
@@ -254,30 +260,25 @@ Promote 不通过 PR 更新 `main`。如果给 `main` 打开 **Require a pull re
- `SNOWLUMA_BOT_APP_ID` — 数字类型的 App ID。
- `SNOWLUMA_BOT_PRIVATE_KEY` — 该 App 的 PEM 私钥。
App 必须在本仓库已安装,且授予 **Contents: Read+Write**。
App 必须在本仓库已安装,且授予 **Contents: Read+Write**、**Pull requests: Read+Write**。
### 本地工作流速查(维护者)
```bash
# 推荐:一条命令走完 bump → Promote → 等 main 跟上 → 打 v* tag
pnpm release 1.7.0
# 只要把 main 指到 dev(三选一)
# 把 dev 合入 main(三选一)
# 方式 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
# 方式 B:chore.* 合并 tag(与发布 tag 解耦)
git tag chore.merge-20240509 # 或 chore.promote-v1.7.0 等
git push origin chore.merge-20240509 # → 触发 promote-dev-to-main
# 方式 C:在 Actions 页面手动 Run workflow
# Promote 完成后,若要自己打发布 tag
git fetch origin
git switch main
git merge --ff-only origin/main # 对不齐就 reset 到 origin/main
# 合并完成后,发布版本(在 main 上打 v* tag)
git checkout main && git pull
git tag v1.7.0
git push origin v1.7.0 # → 仅触发 release.yml
```
-4
View File
@@ -78,10 +78,6 @@ pnpm test
贡献流程见 [`CONTRIBUTING.md`](CONTRIBUTING.md);模块边界与项目词汇见 [`CONTEXT.md`](CONTEXT.md);开发方向见 [`RoadMap.md`](RoadMap.md)。
## 引用消息预览
OneBot 发送 `reply` 段时,会将本地消息缓存中的原文附入 QQ 引用预览,保留文字、换行与引用关系。图片、语音等非文字段以类型提示显示,不重新上传媒体;原消息中的嵌套引用不递归展开。只有消息元数据而没有缓存正文时,不生成虚构的预览内容。
## 使用边界与许可
> [!IMPORTANT]
+2 -11
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.14.22",
"version": "1.14.10",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -25,7 +25,6 @@
"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"
@@ -51,15 +50,7 @@
},
"overrides": {
"esbuild@<0.28.1": "^0.28.1",
"@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"
"@babel/core@<7.29.6": "^7.29.6"
}
},
"packageManager": "pnpm@10.28.0",
+1 -5
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.14.22",
"version": "1.14.10",
"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,10 +24,6 @@
"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"
+1 -2
View File
@@ -1,5 +1,4 @@
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import { packetTimeoutMs } from './packet-timeout';
import {
HookPipeRequestError,
PIPE_STATUS_CONNECTION_UNAVAILABLE,
@@ -17,7 +16,7 @@ export class HookPacketClient implements PacketSender {
private readonly onOutboundHealthChanged?: OutboundHealthListener,
) { }
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise<SendPacketResult> {
if (!this.client.isLoggedIn) {
return { success: false, gotResponse: false, errorCode: -1, errorMessage: 'qq_hook client is not logged in', responseData: null };
}
+1 -8
View File
@@ -68,9 +68,7 @@ export type HookSessionDeps = {
*
* Emitted events:
* 'login' (uin, packetSender) — real-UIN login detected
* 'disconnected' (wasLoggedIn) — connection dropped, torn down, or
* dispose() of a logged-in session
* (process shutdown uses this path)
* 'disconnected' (wasLoggedIn) — connection dropped or torn down
* 'receive-health-changed' (healthy) — combined receive/request path health changed
* 'status-changed' (status, error) — status field mutated
* 'disposed' () — session stopped tracking this PID
@@ -239,13 +237,8 @@ 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();
}
-8
View File
@@ -1,8 +0,0 @@
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 });
}
+1 -2
View File
@@ -10,7 +10,6 @@ import { isRealUin } from '@snowluma/common/uin';
import { readdirSync, promises as fs } from 'fs';
import net from 'net';
import path from 'path';
import { positiveIntEnv } from '@snowluma/common/env';
import { resolveHookRuntimeDir } from './hook-runtime-dir';
export const PIPE_MAGIC = 0x31504851;
@@ -472,7 +471,7 @@ export class QqHookClient extends EventEmitter {
private loginWaiters: Deferred<QqHookLoginState>[] = [];
constructor(pid: number, {
ackTimeoutMs = positiveIntEnv('SNOWLUMA_HOOK_ACK_TIMEOUT_MS', DEFAULT_ACK_TIMEOUT_MS),
ackTimeoutMs = DEFAULT_ACK_TIMEOUT_MS,
replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS,
runtimeDir = resolveHookRuntimeDir(pid),
}: QqHookClientOptions = {}) {
@@ -644,40 +644,6 @@ 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
@@ -1,30 +0,0 @@
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);
});
});
+1 -5
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.14.22",
"version": "1.14.10",
"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,10 +20,6 @@
"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"
-28
View File
@@ -1,28 +0,0 @@
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;
}
+1 -7
View File
@@ -506,13 +506,7 @@ class FileWriter {
}
if (!this.quota.reserve(this.file.path, bytes)) return false;
try {
this.file.stream.write(data);
} catch (error) {
this.disabled = true;
this.quota.writeFailed(this.file.path, error);
return false;
}
this.file.stream.write(data);
this.file.bytes += bytes;
return true;
}
+1 -7
View File
@@ -264,13 +264,7 @@ 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
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.
}
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
}
// File transport sees levels >= currentFileLevel (SNOWLUMA_LOG_FILE_LEVEL,
-3
View File
@@ -108,9 +108,6 @@ 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;
}
-26
View File
@@ -1,26 +0,0 @@
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);
}
});
});
-7
View File
@@ -60,13 +60,6 @@ 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));
-11
View File
@@ -124,17 +124,6 @@ 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({});
+3 -3
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.14.22",
"version": "1.14.10",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -51,11 +51,11 @@
"otpauth": "^9.5.1"
},
"devDependencies": {
"@hono/node-server": "^1.19.15",
"@hono/node-server": "^1.19.14",
"@rollup/plugin-node-resolve": "^16.0.3",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"hono": "^4.12.34",
"hono": "^4.12.25",
"tsx": "^4.21.0",
"typescript": "catalog:",
"vite": "catalog:",
+13 -56
View File
@@ -19,13 +19,8 @@ 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';
@@ -142,11 +137,6 @@ 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: FriendListPageEntry[] = [];
const categories = new Map<number, FriendListPageCategory>();
@@ -272,10 +262,6 @@ 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),
});
}
@@ -303,9 +289,7 @@ 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). `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 + the notice preview (memo).
createTime: Number(r.createTime ?? 0n),
level: Number(r.level ?? 0n),
memo: r.noticePreview ?? '',
@@ -358,12 +342,6 @@ export class ContactsApi {
return info;
}
/** 企点企业资料卡(#404 后续 PR)。仅在判断命中的是企点账号后再调用。
* best-effort:非企点账号或拉取失败返回 null,不影响上层资料读取。 */
async fetchQidianCorpInfo(uin: number): Promise<QidianCorpInfo | null> {
return fetchQidianCorpInfoWire(this.ctx, uin);
}
async fetchGroupRequests(
filtered = false,
count = 50,
@@ -376,18 +354,6 @@ export class ContactsApi {
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);
@@ -402,23 +368,20 @@ export class ContactsApi {
requests.push({
groupId,
groupName: raw.group?.groupName ?? '',
targetUid,
targetUin: targetUin
|| this.ctx.identity.findUinByUid(targetUid, groupId)
|| this.ctx.identity.findUinByUid(targetUid)
|| 0,
targetUid: this.ctx.identity.findUidByUin(targetUin, groupId)
?? this.ctx.identity.findUidByUin(targetUin)
?? '',
targetUin,
targetName: raw.target?.name ?? '',
invitorUid,
invitorUin: invitorUin
|| this.ctx.identity.findUinByUid(invitorUid, groupId)
|| this.ctx.identity.findUinByUid(invitorUid)
|| 0,
invitorUid: this.ctx.identity.findUidByUin(invitorUin, groupId)
?? this.ctx.identity.findUidByUin(invitorUin)
?? '',
invitorUin,
invitorName: raw.invitor?.name ?? '',
operatorUid,
operatorUin: operatorUin
|| this.ctx.identity.findUinByUid(operatorUid, groupId)
|| this.ctx.identity.findUinByUid(operatorUid)
|| 0,
operatorUid: this.ctx.identity.findUidByUin(operatorUin, groupId)
?? this.ctx.identity.findUidByUin(operatorUin)
?? '',
operatorUin,
operatorName: raw.operatorUser?.name ?? '',
sequence,
state: raw.state ?? 0,
@@ -426,9 +389,6 @@ export class ContactsApi {
eventType: operationType ?? 0,
comment: raw.comment ?? '',
filtered,
operateTransInfo: raw.operateTransInfo && raw.operateTransInfo.length > 0
? raw.operateTransInfo
: undefined,
});
}
this.ctx.identity.rememberGroupRequests(requests);
@@ -485,9 +445,6 @@ export class ContactsApi {
eventType: operationType ?? 0,
comment: raw.comment ?? '',
filtered,
operateTransInfo: raw.operateTransInfo && raw.operateTransInfo.length > 0
? raw.operateTransInfo
: undefined,
});
}
this.ctx.identity.rememberGroupRequests(requests);
+16 -56
View File
@@ -35,54 +35,6 @@ 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;
@@ -441,13 +393,21 @@ export class FlashTransferApi {
// ─────────────── 文件上传 ───────────────
/**
* 文件扩展名 → 闪传类型码。typeCode 用于 0x93cf f3(卡片粗类:压缩包/媒体);
* formatCode 用于 0x93d0 commit f7 与 0x12a9 filesetWrap.f7,决定对端图标
* (png=26,mp4=2,zip=4,未知=11)。
* 文件扩展名 → 闪传类型码映射。typeCode 用于 0x93cf f3,formatCode 用于
* 0x93d0 commit f7 与 0x12a9 filesetWrap.f7(两者同值)。mp4 → 2,rar/zip → 4。
* 未知扩展名按媒体类处理(formatCode=2),服务端按文件名扩展名判定。
*/
private static fileTypeCode(fileName: string): { typeCode: number; formatCode: number } {
const ext = fileName.toLowerCase().match(/\.([^.]+)$/)?.[1] ?? '';
return { typeCode: flashApplyTypeCode(ext), formatCode: flashFormatCode(ext) };
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 };
}
}
/** 构造 sub=103 的 fileId(客户端生成的 protobuf,base64url 编码)。
@@ -570,8 +530,7 @@ export class FlashTransferApi {
/**
* 阶段1:流式哈希 + prepare(拿 rkey)+ apply(注册 fileId)。
* 秒传时 prepare 不回 rkey,仍必须 apply,否则 fileset 会一直停在等待上传;
* 返回 null 只表示调用方跳过 sliceupload。
* 秒传(rkey=null)返回 null,调用方跳过 sliceupload。
*/
private async prepareAndApply(
filesetUuid: string, it: StagedFlashItem,
@@ -583,12 +542,13 @@ export class FlashTransferApi {
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, it.fileSize);
await ApplyUpload.invoke(this.ctx, {
filesetUuid, fileUuid: it.fileUuid, fileId, fileName: it.fileName, fileSize: it.fileSize,
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex: it.fileIndex, formatCode: it.formatCode,
});
if (rkey === null) return null;
return { rkey, sha1StateV: hashes.sha1StateV, sliceCount: hashes.sliceCount };
}
@@ -678,12 +638,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 = {
+53 -26
View File
@@ -233,9 +233,16 @@ function previewFromElements(elements: MessageElement[]): string {
function cloneNodeWithElements(node: ForwardNodePayload, elements: MessageElement[]): ForwardNodePayload {
return {
...node,
userUin: node.userUin,
nickname: node.nickname,
elements,
news: node.news?.map(item => ({ ...item })),
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
innerForward: node.innerForward,
};
}
@@ -471,21 +478,23 @@ export class ForwardApi {
type: 'forward',
resId: inner.resId,
forwardUuid: inner.uuid,
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),
forwardSource: deriveInnerSource(node.innerForward, isGroup),
forwardSummary: `查看${node.innerForward.length}条转发消息`,
forwardPrompt: '[聊天记录]',
forwardNews: previewLinesFromNodes(node.innerForward),
forwardTSum: node.innerForward.length,
};
const processed = cloneNodeWithElements(node, [previewElement]);
delete processed.innerForward;
processedNodes.push(processed);
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,
});
} else {
processedNodes.push(node);
}
@@ -539,8 +548,14 @@ export class ForwardApi {
}
forwardResCache.set(resId, uploadReadyNodes.map(node => ({
...cloneNodeWithElements(node, node.elements.map(cacheableForwardElement)),
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId ?? groupId,
senderCard: node.senderCard,
messageType: node.messageType ?? (groupId ? 'group' : 'private'),
})));
@@ -564,7 +579,17 @@ export class ForwardApi {
const bridge = asBridge(this.ctx);
const cached = forwardResCache.get(resId);
if (cached) {
const nodes = cloneNodes(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,
}));
// 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));
@@ -829,14 +854,16 @@ 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 => cloneNodeWithElements(node, [...node.elements]));
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,
}));
}
+11 -56
View File
@@ -1,5 +1,4 @@
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';
@@ -25,9 +24,6 @@ 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
@@ -44,66 +40,25 @@ export class FriendApi {
}
}
async setRemark(userId: number, remark: string): Promise<void> {
if (findDatalineDeviceByUin(userId)) {
throw new Error('this contact does not support remarks');
}
setRemark(userId: number, remark: string): Promise<void> {
if (remark === '') {
await ClearFriendRemark.invoke(this.ctx, { userId });
return;
return ClearFriendRemark.invoke(this.ctx, { userId });
}
await SetFriendRemark.invoke(this.ctx, { userId, remark });
return SetFriendRemark.invoke(this.ctx, { userId, remark });
}
/** List doubtful friend-add requests (可能认识的人). */
async getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
const list = await GetDoubtBuddyReq.invoke(this.ctx, { count });
return Promise.all(list.map(async (item) => {
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 };
}));
getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
return GetDoubtBuddyReq.invoke(this.ctx, { count });
}
/** 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');
/** 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 });
}
/** 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));
/** Reject (delete/decline) a doubtful friend-add request by its uid. */
rejectDoubtRequest(uid: string): Promise<void> {
return RejectDoubtBuddyReq.invoke(this.ctx, { uid });
}
}
+28 -116
View File
@@ -11,53 +11,28 @@ 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,
GROUP_HISTORY_VISIBILITY_MASK,
mergeGroupHistoryVisibility,
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;
@@ -72,33 +47,6 @@ 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 });
}
@@ -107,31 +55,14 @@ export class GroupAdminApi {
return MuteAll.invoke(this.ctx, { groupId, enable });
}
setAddOption(
groupId: number,
addType: number,
groupQuestion?: string,
groupAnswer?: string,
): Promise<void> {
return SetAddOption.invoke(this.ctx, { groupId, addType, groupQuestion, groupAnswer });
setAddOption(groupId: number, addType: number): Promise<void> {
return SetAddOption.invoke(this.ctx, { groupId, addType });
}
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,
@@ -158,23 +89,12 @@ export class GroupAdminApi {
}
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) {
const privilegeFlag = detail.groupInfo?.results?.privilegeFlag;
if (typeof privilegeFlag !== 'number') {
throw new Error(`unable to read ${setting} ${phase} for group ${groupId}`);
}
return {
privilegeFlag: results.privilegeFlag ?? 0,
ownerUid: results.ownerUid,
};
return privilegeFlag;
}
async setMemberPermissions(groupId: number, permissions: GroupMemberPermissions): Promise<void> {
@@ -187,34 +107,21 @@ export class GroupAdminApi {
throw new Error('at least one member permission must be specified');
}
const before = await this.fetchGroupPrivilegeState(
let expectedPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
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;
}
await SetMemberPermission.invoke(this.ctx, {
groupId,
currentPrivilegeFlag: expectedPrivilegeFlag,
permission,
allow,
});
expectedPrivilegeFlag = mergeGroupMemberPermission(expectedPrivilegeFlag, permission, allow);
combinedMask |= BigInt(GROUP_MEMBER_PERMISSION_MASKS[permission]);
}
@@ -230,31 +137,36 @@ export class GroupAdminApi {
}
async setNewMemberHistoryVisibility(groupId: number, visible: boolean): Promise<void> {
await SetNewMemberHistoryVisibility.invoke(this.ctx, { groupId, visible });
const currentGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'before update');
const expectedGroupFlagExt4 = mergeGroupHistoryVisibility(currentGroupFlagExt4, visible);
await SetNewMemberHistoryVisibility.invoke(this.ctx, {
groupId,
currentGroupFlagExt4,
visible,
});
const actualGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'after update');
if (decodeGroupHistoryVisibility(actualGroupFlagExt4) !== visible) {
const mask = BigInt(GROUP_HISTORY_VISIBILITY_MASK);
if ((BigInt(actualGroupFlagExt4) & mask) !== (BigInt(expectedGroupFlagExt4) & mask)) {
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) {
const groupFlagExt4 = detail.groupInfo?.results?.groupFlagExt4;
if (typeof groupFlagExt4 !== 'number') {
throw new Error(`unable to read new-member history visibility ${phase} for group ${groupId}`);
}
return results.groupFlagExt4 ?? 0;
return groupFlagExt4;
}
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, operateTransInfo,
});
return SetAddRequest.invoke(this.ctx, { groupId, sequence, eventType, approve, reason, filtered });
}
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
+48 -322
View File
@@ -1,11 +1,7 @@
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,
@@ -14,26 +10,19 @@ 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, uploadVideoToGroupAlbum } from '@snowluma/protocol/web/group-album';
import { uploadImageToGroupAlbum } 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();
@@ -180,7 +169,7 @@ export class GroupAlbumApi {
body.length,
);
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, packetTimeoutMs());
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, 15000);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(
`get group album list transport failed: ${result.errorMessage || `code ${result.errorCode}`}`,
@@ -270,13 +259,6 @@ 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)}`;
@@ -298,7 +280,7 @@ export class GroupAlbumApi {
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
body,
packetTimeoutMs(),
15000,
);
if (!result.success || !result.gotResponse || !result.responseData) {
@@ -323,36 +305,38 @@ 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: DO_QUN_COMMENT_SEQ,
field1: 8527,
field2: new Uint8Array(0),
field3: new Uint8Array(0),
body: {
groupId: groupId.toString(),
field3: 2,
reqBody: {
field1: commentReqHeader(feed.cellCommon),
...(ownerUin ? { field2: { field1: { uin: ownerUin } } } : {}),
field5: photoInfo,
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,
},
},
field5: {
user: { uin },
contents: [{ type: 0, content }],
field2: { uin },
field3: {
field1: 0,
field2: content,
field3: '', field4: '', field5: 0, field6: '',
},
clientKey,
},
},
@@ -360,35 +344,31 @@ export class GroupAlbumApi {
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(DO_QUN_COMMENT_CMD, body, packetTimeoutMs());
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
body,
15000,
);
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 resultCode = resp.result ?? 0;
if (resultCode !== 0) {
throw new Error(
`comment album media error: retCode ${resultCode}`
+ (resp.errorText ? `, ${resp.errorText}` : ''),
);
const resCode = resp.field1;
if (resCode !== 0 && resCode !== 8527 && !resp.comment) {
throw new Error(`comment album media error: retCode ${resCode ?? 'unknown'}`);
}
const commentData = commentFromResponse(resp);
if (!commentData.id) {
throw new Error('comment album media error: empty comment');
}
const commentData = resp.comment?.data ?? {};
return convertBigIntToString({
id: commentData.id,
user: { uin: commentData.user?.uin || uin },
content: (commentData.content ?? [{ type: 0, content }]).map((item) => ({
type: item.type ?? 0,
content: item.content ?? '',
})),
id: commentData.id ?? '',
user: { uin: commentData.user?.uin ?? '' },
content: commentData.content ?? [],
time: commentData.time ?? '0',
clientKey: commentData.clientKey || clientKey,
clientKey: commentData.clientKey ?? '',
}) as unknown as GroupAlbumCommentResult;
}
@@ -399,7 +379,12 @@ export class GroupAlbumApi {
const type = isLike ? 2 : 1;
const status = isLike ? 0 : 1;
const id = qunFeedCellId(groupId, albumId, batchId, lloc);
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 body = protobuf_encode<DoQunLikeRequest>({
field1: 5495,
@@ -432,7 +417,7 @@ export class GroupAlbumApi {
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
body,
packetTimeoutMs(),
15000,
);
if (!result.success || !result.gotResponse || !result.responseData) {
@@ -450,7 +435,6 @@ 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)}`;
@@ -461,8 +445,7 @@ export class GroupAlbumApi {
body: {
groupId: groupId.toString(),
albumId,
mediaIds: [target.mediaId],
...(target.batchId ? { batchIds: [target.batchId] } : {}),
lloc,
},
traceId: clientKey,
extMap: [{ key: 'fc-appid', value: '100' }],
@@ -471,7 +454,7 @@ export class GroupAlbumApi {
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
body,
packetTimeoutMs(),
15000,
);
if (!result.success || !result.gotResponse || !result.responseData) {
@@ -489,264 +472,7 @@ 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;
+9 -2
View File
@@ -33,7 +33,11 @@ export class InteractionApi {
return SetEssence.invoke(this.ctx, { groupId, sequence, random, enable });
}
/** Fetch the reactor list for one emoji on a group message. */
/**
* 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.
*/
async getEmojiLikes(
groupId: number,
sequence: number,
@@ -50,7 +54,10 @@ export class InteractionApi {
}
/**
* Recent-used emoji catalog (0x9084_1). Not a per-message reaction list.
* 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.
*/
fetchReactionSummary(
groupId: number,
+1 -81
View File
@@ -14,14 +14,6 @@ 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,
@@ -412,14 +404,6 @@ 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 };
@@ -433,8 +417,6 @@ 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,
@@ -501,67 +483,6 @@ 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
@@ -585,7 +506,6 @@ 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();
@@ -795,7 +715,7 @@ export class MessageApi {
info: {
clientSequence: clientSeq,
random,
messageId: (0x01000000n << 32n) | BigInt(random >>> 0),
messageId: BigInt((0x01000000 * 0x100000000) + random),
timestamp,
field5: 0,
messageSequence: msgSeq,
+32 -25
View File
@@ -1,4 +1,6 @@
import type {
FaceroamOpReq,
FaceroamOpResp,
GroupAvatarExtra,
SetStatusReq,
SetStatusResp,
@@ -6,7 +8,6 @@ import type {
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';
@@ -75,15 +76,14 @@ export class ProfileApi {
if (!resp) {
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
}
const message = resp.errMsg ?? '';
if (message !== '' && message !== 'set status success') {
throw new Error(message);
if (resp.errCode !== undefined && resp.errCode !== 0) {
throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`);
}
}
}
setProfile(nickname?: string, personalNote?: string, sex?: number): Promise<void> {
return SetProfile.invoke(this.ctx, { nickname, personalNote, sex });
setProfile(nickname?: string, personalNote?: string): Promise<void> {
return SetProfile.invoke(this.ctx, { nickname, personalNote });
}
setSelfLongNick(longNick: string): Promise<void> {
@@ -166,13 +166,28 @@ export class ProfileApi {
}));
}
async fetchCustomFaceIds(count = 10): Promise<string[]> {
private async fetchCustomFaceIds(count: number): 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 });
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) !== 0) {
throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`);
}
const faceIds = resp.item?.faceIds || [];
return faceIds.slice(0, count);
}
@@ -180,20 +195,7 @@ export class ProfileApi {
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 来自收藏列表。 */
/** 删除一个收藏表情(custom face)。emoji_id 来自 fetchCustomFace 返回的 URL 路径段。 */
deleteCustomFace(emojiId: string): Promise<void> {
return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId });
}
@@ -208,8 +210,9 @@ export class ProfileApi {
}
/**
* 修改收藏表情(custom face)备注。emoji_id 来自收藏列表;md5 从 emoji_id
* 中段解析,无需调用方单独提供。desc 为空串则清空备注。
* 修改收藏表情(custom face)备注。emoji_id 来自 fetchCustomFace 返回的
* URL 路径段;md5 从 emoji_id 中段解析,无需调用方单独提供。desc 为空串
* 则清空备注。
*/
modifyCustomFace(emojiId: string, desc: string): Promise<void> {
return ModifyCustomFace.invoke(this.ctx, {
@@ -227,7 +230,11 @@ export class ProfileApi {
*/
async moveCustomFaceToFront(emojiId: string): Promise<void> {
// 1. fetch 当前完整列表(fetch 顺序即可,不需要 DB 显示顺序)
const ids = await this.fetchCustomFaceIds(1000);
const urls = await this.fetchCustomFace(1000);
const ids = urls.map((url) => {
const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url);
return m ? m[1] : '';
}).filter(Boolean);
const idx = ids.indexOf(emojiId);
if (idx < 0) throw new Error(`emoji_id not in list: ${emojiId}`);
// 新顺序:目标挪到第一,其余按原顺序
+2 -4
View File
@@ -10,7 +10,6 @@ import {
GROUP_NOTICE_TYPE_NEW_MEMBERS,
GROUP_NOTICE_TYPE_NORMAL,
getGroupNoticeWebAPI,
groupNoticeImageUrl,
setGroupNoticeWebAPI,
uploadGroupNoticeImage,
type SetNoticeRetSuccess,
@@ -44,8 +43,8 @@ export interface WebNoticeInfo {
publish_time: number;
message: {
text: string;
image: Array<{ id: string; url: string; height: number; width: number }>;
images: Array<{ id: string; url: string; height: number; width: number }>;
image: Array<{ id: string; height: number; width: number }>;
images: Array<{ id: string; height: number; width: number }>;
};
settings: import('@snowluma/common/json').JsonValue;
read_num: number;
@@ -105,7 +104,6 @@ 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,15 +1,8 @@
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;
/** 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;
+14 -159
View File
@@ -4,7 +4,6 @@ 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';
@@ -22,11 +21,10 @@ import {
type AiVoiceCategory,
type StrangerStatus,
} from './apis/extras';
import type { BridgeInterface, RosterWarmupResult } from './bridge-interface';
import type { BridgeInterface } 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;
@@ -48,11 +46,6 @@ 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;
@@ -65,12 +58,8 @@ export class Bridge implements BridgeInterface {
this.pipeline = new IncomingPacketPipeline({
identity: this.identity,
events: this.events,
fetchGroupList: async () => {
await this.apis.contacts.fetchGroupList();
},
fetchGroupMemberList: async (groupId) => {
await this.apis.contacts.fetchGroupMemberList(groupId);
},
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
resolveGroupJoinRequest: async (groupId, uid, subType) => {
const [main, filtered] = await Promise.allSettled([
this.apis.contacts.fetchGroupRequestsByUid(false),
@@ -91,14 +80,10 @@ export class Bridge implements BridgeInterface {
...(main.status === 'fulfilled' ? main.value : []),
...(filtered.status === 'fulfilled' ? filtered.value : []),
];
const matches = requests.filter((r) => {
return requests.find(r => {
if (r.groupId !== groupId) return false;
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
});
if (subType === 'invite') {
return matches.find((r) => r.notifyType === 1) ?? matches[0] ?? null;
}
return matches.find((r) => r.notifyType === 7) ?? matches[0] ?? null;
}) ?? null;
},
resolveGroupInviteCardSequence: async (groupId) => {
const deadline = Date.now() + 1_000;
@@ -132,8 +117,6 @@ 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();
@@ -158,7 +141,6 @@ 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 {
@@ -198,7 +180,6 @@ export class Bridge implements BridgeInterface {
previousPid,
);
}
this.maybeStartRosterWarmup();
}
/** @internal BridgeManager lookup used when an incoming packet is the first
@@ -255,25 +236,18 @@ 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) {
@@ -297,7 +271,7 @@ export class Bridge implements BridgeInterface {
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
return this.msgRandom_ & 0x7FFFFFFF;
}
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
if (!this.packetClient_) {
return runWithTraceRequest(() => {
const startedAt = Date.now();
@@ -383,125 +357,6 @@ 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;
+5 -16
View File
@@ -83,20 +83,18 @@ 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');
const started = await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager, {
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);
}
@@ -120,23 +118,14 @@ async function main() {
exitCode = 1;
log.error('notification shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
try {
if (stopWebUI) await stopWebUI();
} catch (error) {
exitCode = 1;
log.error('WebUI shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
// Observers go deaf before Hook teardown. Hook dispose then emits the
// same disconnected → PID detach → Bridge closed path as a live drop;
// those closed edges must not look like a runtime offline.
try { stateWiring.dispose(); } catch (error) {
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));
}
try { stateWiring.dispose(); } catch (error) {
exitCode = 1;
log.error('state wiring shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
await closeLogger();
process.exit(exitCode);
};
+3 -147
View File
@@ -11,7 +11,6 @@ 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');
@@ -32,45 +31,16 @@ 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 {
@@ -87,23 +57,6 @@ 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,
@@ -165,118 +118,21 @@ function isHttpUrl(value: string): boolean {
}
}
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). */
/** 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 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 headers = normalizeHeaders(raw.headers);
const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id;
return {
id,
name,
type: 'webhook',
url,
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
enabled: boolOr(raw.enabled, true),
...(headers ? { headers } : {}),
};
}
+27 -89
View File
@@ -2,18 +2,16 @@
//
// 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 template and delivers it — recording the
// each opted-in + enabled channel's body template and POSTs it — recording the
// outcome in a bounded in-memory history (lost on restart, by design).
//
// 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';
// 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.
import { createLogger } from '@snowluma/common/logger';
import { loadOneBotConfig } from '@snowluma/onebot/config';
import type { BridgeManager } from '../bridge/manager';
import {
isEmailChannel,
loadNotificationsConfig,
renderTemplate,
type NotificationChannel,
@@ -21,7 +19,6 @@ import {
type NotificationsConfig,
} from './config';
import { DebounceMachine, type DebounceDecision } from './debounce';
import { formatSmtpError, parseRecipients, sendSmtpMail } from './smtp';
const log = createLogger('Notifications');
@@ -46,27 +43,13 @@ 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[];
/** 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>;
/** Outbound delivery — never throws; failures come back as `{ ok: false }`. */
post: (url: string, body: string) => Promise<PostResult>;
now: () => number;
historyLimit?: number;
}
@@ -91,7 +74,6 @@ 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;
@@ -106,13 +88,11 @@ 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()));
}
@@ -157,7 +137,7 @@ export class NotificationManager {
}
}
/** Render + deliver a transition to every opted-in, enabled channel and record
/** Render + POST 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[];
@@ -179,7 +159,14 @@ export class NotificationManager {
};
for (const ch of channels) {
const result = await this.deliver(ch, vars);
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) };
}
this.record({
time: this.deps.now(),
uin,
@@ -195,33 +182,9 @@ 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+deliver path; NOT recorded to history.
* variables. Reuses the real render+POST 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;
@@ -231,13 +194,17 @@ export class NotificationManager {
return { ok: false, found: false, error: errMsg(err) };
}
if (!channel) return { ok: false, found: false };
const vars = {
const body = renderTemplate(channel.bodyTemplate, {
uin: '10000',
nickname: '测试账号',
event: 'offline' as const,
event: 'offline',
time: new Date(this.deps.now()).toISOString(),
};
return { ...(await this.deliver(channel, vars)), found: true };
});
try {
return { ...(await this.deps.post(channel.url, body)), found: true };
} catch (err) {
return { ok: false, found: true, error: errMsg(err) };
}
}
private record(rec: DeliveryRecord): void {
@@ -254,8 +221,6 @@ export class NotificationManager {
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
for (const timer of this.timers.values()) clearTimeout(timer);
this.timers.clear();
}
@@ -263,14 +228,12 @@ 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 = positiveIntEnv('SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS', DEFAULT_POST_TIMEOUT_MS),
): NotificationManagerDeps['post'] {
return async (url, body, headers) => {
export function createDefaultPost(timeoutMs = DEFAULT_POST_TIMEOUT_MS): NotificationManagerDeps['post'] {
return async (url, body) => {
try {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...headers },
headers: { 'Content-Type': 'application/json' },
body,
signal: AbortSignal.timeout(timeoutMs),
});
@@ -281,37 +244,12 @@ export function createDefaultPost(
};
}
const DEFAULT_SMTP_TIMEOUT_MS = 15_000;
/** Default SMTP send. Never throws. */
export function createDefaultSendMail(timeoutMs = DEFAULT_SMTP_TIMEOUT_MS): NonNullable<NotificationManagerDeps['sendMail']> {
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(),
});
}
-383
View File
@@ -1,383 +0,0 @@
// 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');
}
+13 -2
View File
@@ -5,7 +5,7 @@
//
// Credentials are gated by a toggle on both export and import. The credential
// set is: webui.json (password hash), key.pem (TLS private key),
// notifications.json (webhook URLs / SMTP passwords), AND every OneBot config
// notifications.json (webhook URLs may embed secrets), 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.
@@ -18,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;
@@ -450,6 +450,17 @@ 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');
@@ -1,27 +0,0 @@
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 };
}
+15 -40
View File
@@ -56,8 +56,7 @@ import {
resolveEnvironmentConsent,
} from './consent';
import { requireTlsContext, resolveTlsContext, validateTlsPair } from './tls';
import { coerceSettingsPatch, evaluateSettingsSave, tlsCertDeletionBlocked } from './system-settings';
import { checkListenerExposure } from './listener-exposure';
import { coerceSettingsPatch } from './system-settings';
import { buildBackup } from './backup';
import { restoreBackup, RestoreTransactionError, type RestorePhase } from './restore';
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
@@ -471,20 +470,7 @@ export async function initWebUI(
hookManager?: HookManager,
notificationManager?: NotificationManager,
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string; stateBus?: StateBus } = {},
): 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}`);
}
): Promise<{ port: number }> {
// 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).
@@ -519,9 +505,10 @@ 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) {
connectionDiffLoop = startConnectionDiffLoop({
// Handle deliberately discarded — initWebUI has no shutdown path; the
// loop's setInterval is .unref'd so it doesn't pin the event loop.
startConnectionDiffLoop({
bus: listener.stateBus,
getSnapshot: () => oneBotManager.getConnectionStatuses(),
pickComparable: comparableConnectionSnapshot,
@@ -1141,13 +1128,11 @@ export async function initWebUI(
}
const coerced = coerceSettingsPatch(body);
if (!coerced.ok) return c.json({ success: false, message: coerced.error }, 400);
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);
// 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);
return c.json({
success: true,
settings: {
@@ -1216,9 +1201,6 @@ 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 });
@@ -1796,6 +1778,7 @@ export async function initWebUI(
);
});
const host = listener.host || '127.0.0.1';
const finalPort = await findAvailablePort(desiredPort, { host });
if (finalPort !== desiredPort) {
log.warn('port %d is in use, using %d instead', desiredPort, finalPort);
@@ -1812,19 +1795,11 @@ export async function initWebUI(
scheme = 'https';
}
const listeningServer = await new Promise<ReturnType<typeof serve>>((resolve) => {
const server = serve({ fetch: app.fetch, port: finalPort, hostname: host, ...(tlsServe ?? {}) }, (info) => {
await new Promise<void>((resolve) => {
serve({ fetch: app.fetch, port: finalPort, hostname: host, ...(tlsServe ?? {}) }, (info) => {
log.info(`listening ${scheme}://${host}:${info.port}`);
resolve(server);
resolve();
});
});
return {
port: finalPort,
async stop() {
connectionDiffLoop?.dispose();
await new Promise<void>((resolve, reject) => {
listeningServer.close((err) => (err ? reject(err) : resolve()));
});
},
};
return { port: finalPort };
}
+2 -3
View File
@@ -14,9 +14,8 @@
* listeners directly so `qq-list` + `connections` invalidate at the right
* moment without modifying BridgeManager.
*
* `dispose()` sets a latch and neuters the bus. BridgeManager listeners stay
* attached; further session edges publish nothing. Process shutdown disposes
* this wiring before Hook teardown so exit-time closed is not a WebUI invalidate.
* `dispose()` unwires everything so a test (or a future hot-reload) can
* recreate the wiring without leaking listeners.
*/
import { StateBus } from './state-bus';
@@ -4,7 +4,6 @@
// 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'>>;
@@ -51,25 +50,3 @@ 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;
}
@@ -249,63 +249,6 @@ describe('apis/contacts / group roster', () => {
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: {
@@ -27,6 +27,7 @@ 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: {} })),
@@ -1,77 +0,0 @@
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; news?: Array<{ text: string }>; source?: string; summary?: string } | null {
function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: string; app?: string } | null {
for (const body of msgBody) {
const elems: Elem[] = body.body?.richText?.elems ?? [];
for (const elem of elems) {
@@ -74,9 +74,6 @@ 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 */ }
@@ -181,86 +178,4 @@ 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 -23
View File
@@ -1,6 +1,7 @@
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: {} })),
@@ -121,29 +122,6 @@ 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 });
-172
View File
@@ -1,25 +1,17 @@
import { describe, it, expect, vi } from 'vitest';
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
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';
@@ -97,174 +89,10 @@ describe('apis/friend', () => {
.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 () => {
const bridge = mockBridge();
await new FriendApi(bridge as any).setRemark(10001, '');
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 } },
}));
}
+31 -357
View File
@@ -1,7 +1,6 @@
import { describe, it, expect, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
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,
@@ -11,10 +10,8 @@ import type {
Oidb0x89a_0HistoryVisibility,
Oidb0x89a_0MemberPermission,
Oidb0xf16Req,
OidbGroupDetailRequest,
OidbGroupRequestAction,
OidbKickMember,
OidbKickMemberResponse,
OidbLeaveGroup,
OidbMuteAll,
OidbMuteMember,
@@ -23,16 +20,11 @@ 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, MEMBER_PERMISSIONS_OWNER_ONLY } from '../../src/bridge/apis/group-admin';
import { GroupAdminApi } from '../../src/bridge/apis/group-admin';
import { mockBridge } from './_helpers';
function packResponse(body: Uint8Array) {
@@ -42,27 +34,17 @@ function packResponse(body: Uint8Array) {
};
}
function packPrivilegeFlag(privilegeFlag?: number, ownerUid?: string) {
function packPrivilegeFlag(privilegeFlag?: number) {
return packResponse(protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
body: {
groupInfo: {
uin: 12345n,
results: {
...(privilegeFlag === undefined ? {} : { privilegeFlag }),
...(ownerUid === undefined ? {} : { ownerUid }),
},
results: privilegeFlag === undefined ? {} : { privilegeFlag },
},
},
}));
}
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: {
@@ -74,26 +56,6 @@ function packGroupFlagExt4(groupFlagExt4?: number) {
}));
}
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();
@@ -141,30 +103,18 @@ describe('apis/group-admin', () => {
});
});
it('kickMember treats a zero per-member result as success (#413)', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbKickMemberResponse>>({
body: { groupUin: 12345, results: [{ result: 0, uid: 'u_abcdefghijklmnopqrstuv' }] },
}),
));
await expect(
new GroupAdminApi(bridge as any).kickMember(12345, 67890, false),
).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' }] },
}),
Buffer.from(
'222008b960121be7bea4e4b8bbe697a0e6b395e8a2abe7a7bbe587bae7bea4e8818a',
'hex',
),
));
await expect(
new GroupAdminApi(bridge as any).kickMember(12345, 67890, false),
).rejects.toThrow('kick member failed: result=1');
).rejects.toThrow('群主无法被移出群聊');
});
it('kickMembers resolves each UID in parallel', async () => {
@@ -183,14 +133,15 @@ describe('apis/group-admin', () => {
it('kickMembers rejects the same command-level business error', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbKickMemberResponse>>({
body: { groupUin: 12345, results: [{ result: 1, uid: 'u_abcdefghijklmnopqrstuv' }] },
}),
Buffer.from(
'222008b960121be7bea4e4b8bbe697a0e6b395e8a2abe7a7bbe587bae7bea4e8818a',
'hex',
),
));
await expect(
new GroupAdminApi(bridge as any).kickMembers(12345, [67890], false),
).rejects.toThrow('kick members failed: result=1');
).rejects.toThrow('群主无法被移出群聊');
});
it('leave sends 0x1097_1, emits a self group_member_leave, and forgets the group (#133)', async () => {
@@ -259,24 +210,11 @@ 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);
@@ -326,32 +264,9 @@ describe('apis/group-admin', () => {
});
});
it('setMemberInvitePolicy treats an omitted privilege flag as zero', async () => {
it('setMemberInvitePolicy fails before mutation when the current flag is absent', 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 } },
}),
));
bridge.sendRawPacket.mockResolvedValueOnce(packPrivilegeFlag());
await expect(
new GroupAdminApi(bridge as any).setMemberInvitePolicy(12345, 'require_approval'),
@@ -372,83 +287,53 @@ describe('apis/group-admin', () => {
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
});
it('setNewMemberHistoryVisibility accepts a 0/1 history-visible read-back (#387)', async () => {
it('setNewMemberHistoryVisibility reads, merges, writes, and verifies the extended flag (#336)', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(packGroupFlagExt4(0x80000001))
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packGroupFlagExt4(1));
.mockResolvedValueOnce(packGroupFlagExt4(0x80000005));
await new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, true);
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
'OidbSvcTrpcTcp.0x88d_0',
'OidbSvcTrpcTcp.0x89a_0',
'OidbSvcTrpcTcp.0x88d_0',
]);
const envelope = protobuf_decode<OidbBase<Oidb0x89a_0HistoryVisibility>>(
bridge.sendRawPacket.mock.calls[0]![1],
bridge.sendRawPacket.mock.calls[1]![1],
);
expect(envelope.body).toMatchObject({
groupUin: 12345n,
settings: {
groupFlagExt4: 0x4,
groupFlagExt4: 0x80000005,
groupFlagExt4Mask: 0x4,
},
});
});
it('setNewMemberHistoryVisibility clears visibility when read-back is the off flag', async () => {
it('setNewMemberHistoryVisibility fails before mutation when the current flag is absent', 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 } },
}),
));
bridge.sendRawPacket.mockResolvedValueOnce(packGroupFlagExt4());
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);
).rejects.toThrow(/unable to read new-member history visibility before update/);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
});
it('setNewMemberHistoryVisibility rejects an ack when read-back stays hidden', async () => {
it('setNewMemberHistoryVisibility rejects an ack when read-back does not match', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(packGroupFlagExt4(0x80000001))
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packGroupFlagExt4(0));
.mockResolvedValueOnce(packGroupFlagExt4(0x80000001));
await expect(
new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, true),
).rejects.toThrow(/was not applied/);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
});
it('setMemberPermissions applies supplied switches separately and verifies the combined result (#335)', async () => {
@@ -492,35 +377,9 @@ describe('apis/group-admin', () => {
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('setMemberPermissions treats an omitted privilege flag as all-allowed (#388)', async () => {
it('setMemberPermissions fails before mutation when the current flag is absent', 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 } },
}),
));
bridge.sendRawPacket.mockResolvedValueOnce(packPrivilegeFlag());
await expect(
new GroupAdminApi(bridge as any).setMemberPermissions(12345, {
@@ -530,53 +389,6 @@ describe('apis/group-admin', () => {
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
@@ -607,94 +419,6 @@ 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 `{}`
@@ -710,54 +434,4 @@ 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,14 +1,7 @@
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';
@@ -444,501 +437,4 @@ 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',
});
});
});
@@ -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,17 +66,6 @@ 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.
// calls bridge.sendRawPacket directly (bypassing runOidb).
const bridge = mockBridge();
const api = new InteractionApi(bridge as any);
await api.setReaction(12345, 99, '128516', true);
@@ -51,21 +51,20 @@ describe('apis/interaction', () => {
expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']);
});
it('getEmojiLikes decodes user list, returns the cookie, and reports isLast', async () => {
it('getEmojiLikes decodes user list, base64-encodes 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: {
users: [{ uin: 10001n }, { uin: 20002n }],
cookie: 'next-page',
isLast: false,
},
inner: { userInfo: [{ uin: 10001n }, { uin: 20002n }] },
cookie: new Uint8Array([0xCA, 0xFE]),
} as any,
})),
});
const out = await new InteractionApi(bridge as any).getEmojiLikes(12345, 99, '128516');
expect(out.users).toEqual([{ uin: 10001 }, { uin: 20002 }]);
expect(out.cookie).toBe('next-page');
expect(out.cookie).toBe(Buffer.from([0xCA, 0xFE]).toString('base64'));
expect(out.isLast).toBe(false);
});
@@ -1,41 +0,0 @@
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');
});
});
+9 -128
View File
@@ -12,12 +12,18 @@ 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 })),
};
});
@@ -41,6 +47,8 @@ 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();
@@ -79,30 +87,9 @@ 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,
@@ -292,112 +279,6 @@ describe('apis/profile', () => {
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';
@@ -34,20 +34,6 @@ 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,
@@ -298,8 +284,8 @@ describe('BridgeManager PID ownership', () => {
expect(bridge.activePid).toBe(202);
await bridge.sendRawPacket('Test.BeforeDisconnect', new Uint8Array([1]));
expect(testSends(second.sendPacket)).toHaveLength(1);
expect(testSends(first.sendPacket)).toHaveLength(0);
expect(second.sendPacket).toHaveBeenCalledOnce();
expect(first.sendPacket).not.toHaveBeenCalled();
manager.onPidDisconnected(202);
@@ -307,8 +293,8 @@ describe('BridgeManager PID ownership', () => {
expect(bridge.activePid).toBe(101);
expect(closed).not.toHaveBeenCalled();
await bridge.sendRawPacket('Test.AfterDisconnect', new Uint8Array([2]));
expect(testSends(first.sendPacket)).toHaveLength(1);
expect(testSends(second.sendPacket)).toHaveLength(1);
expect(first.sendPacket).toHaveBeenCalledOnce();
expect(second.sendPacket).toHaveBeenCalledOnce();
manager.onPidDisconnected(101);
expect(manager.getSession('10001')).toBeNull();
@@ -338,7 +324,9 @@ describe('BridgeManager PID ownership', () => {
manager.onPidDisconnected(101);
await bridge.sendRawPacket('Test.NoSender', new Uint8Array([0x00, 0xff]));
const sender = ownershipSendTrace(entries);
const sender = runtimeTrace(entries).filter((entry) =>
entry.message.startsWith('bridge_sender_fact ')
|| entry.message.startsWith('bridge_send_'));
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',
@@ -393,17 +381,17 @@ describe('BridgeManager PID ownership', () => {
expect(started).toHaveBeenCalledOnce();
expect(bridge.activePid).toBe(101);
await bridge.sendRawPacket('Test.Rebound', new Uint8Array([1]));
expect(testSends(reboundFirst.sendPacket)).toHaveLength(1);
expect(reboundFirst.sendPacket).toHaveBeenCalledOnce();
manager.onPidDisconnected(101);
expect(bridge.activePid).toBe(303);
await bridge.sendRawPacket('Test.Fallback', new Uint8Array([2]));
expect(testSends(third.sendPacket)).toHaveLength(1);
expect(third.sendPacket).toHaveBeenCalledOnce();
manager.onPidDisconnected(303);
expect(bridge.activePid).toBe(202);
await bridge.sendRawPacket('Test.SecondFallback', new Uint8Array([3]));
expect(testSends(second.sendPacket)).toHaveLength(1);
expect(second.sendPacket).toHaveBeenCalledOnce();
});
it('applies the same ownership transition when a packet reveals a new UIN', async () => {
@@ -425,7 +413,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(testSends(sender.sendPacket)).toHaveLength(1);
expect(sender.sendPacket).toHaveBeenCalledOnce();
});
it('keeps the old UIN alive when its active PID moves and a fallback remains', async () => {
@@ -449,12 +437,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(testSends(fallback.sendPacket)).toHaveLength(1);
expect(fallback.sendPacket).toHaveBeenCalledOnce();
const newBridge = manager.getSession('20002')!.bridge;
expect(newBridge.activePid).toBe(202);
await newBridge.sendRawPacket('Test.NewUinSender', new Uint8Array([2]));
expect(testSends(rebound.sendPacket)).toHaveLength(1);
expect(rebound.sendPacket).toHaveBeenCalledOnce();
manager.onPidDisconnected(202);
expect(lifecycle).toEqual([
@@ -497,7 +485,7 @@ describe('BridgeManager PID ownership', () => {
manager.onPidDisconnected(101);
expect(targetBridge.activePid).toBe(202);
await targetBridge.sendRawPacket('Test.ExistingTargetFallback', new Uint8Array([1]));
expect(testSends(second.sendPacket)).toHaveLength(1);
expect(second.sendPacket).toHaveBeenCalledOnce();
expect(closed).toHaveBeenCalledOnce();
manager.onPidDisconnected(202);
@@ -47,9 +47,6 @@ function emptyProfile(uin: number, uid: string) {
sign: '',
avatar: '',
level: 0,
qidianMasterFlag: 0,
qidianCrewFlag: 0,
qidianCrewFlag2: 0,
};
}
@@ -1,10 +1,8 @@
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';
@@ -203,62 +201,4 @@ 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');
});
});
@@ -1,120 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
import type { PacketSender } from '@snowluma/common/packet-sender';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/protocol/qq-info';
import { Bridge } from '../src/bridge/bridge';
const sender: PacketSender = {
sendPacket: async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.alloc(0),
}),
};
function makeFriend(uin: number, uid: string, nickname: string): FriendInfo {
return { uin, uid, nickname, remark: '' };
}
function makeGroup(groupId: number): QQGroupInfo {
return {
groupId,
groupName: 'group',
remark: '',
memberCount: 1,
memberMax: 200,
members: new Map(),
};
}
function makeMember(uin: number, uid: string): GroupMemberInfo {
return {
uin,
uid,
nickname: `nick-${uin}`,
card: '',
role: 'member',
level: 0,
title: '',
joinTime: 0,
lastSentTime: 0,
shutUpTime: 0,
};
}
function makeProfile(uin: number, uid: string, nickname: string): UserProfileInfo {
return {
uin, uid, nickname, remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
qidianMasterFlag: 0, qidianCrewFlag: 0, qidianCrewFlag2: 0,
};
}
describe('Bridge roster warmup', () => {
it('fetches friends and groups after the first sender and writes Identity', async () => {
const identity = IdentityService.memory('10001');
const bridge = new Bridge(identity);
const friends = [makeFriend(10001, 'u_self', 'me'), makeFriend(22222, 'u_friend', 'friend')];
const groups = [makeGroup(123)];
const members = [makeMember(33333, 'u_member')];
const fetchFriendList = vi.spyOn(bridge.apis.contacts, 'fetchFriendList').mockImplementation(async () => {
identity.rememberFriends(friends);
return friends;
});
vi.spyOn(bridge.apis.contacts, 'fetchGroupList').mockImplementation(async () => {
identity.rememberGroups(groups);
return groups;
});
vi.spyOn(bridge.apis.contacts, 'fetchGroupMemberList').mockImplementation(async (groupId) => {
identity.rememberGroupMembers(groupId, members);
return members;
});
bridge.bindPid(7, sender);
const result = await bridge.whenRosterWarmupSettled();
expect(result).toEqual({ friendsLoaded: true, groupsLoaded: true });
expect(fetchFriendList).toHaveBeenCalledOnce();
expect(identity.nickname).toBe('me');
expect(identity.findFriend(22222)?.uid).toBe('u_friend');
expect(identity.findGroup(123)?.groupName).toBe('group');
expect(identity.findGroupMember(123, 33333)?.uid).toBe('u_member');
bridge.dispose();
});
it('does not retry a failed friend list fetch', async () => {
const identity = IdentityService.memory('10001');
const bridge = new Bridge(identity);
const fetchFriendList = vi.spyOn(bridge.apis.contacts, 'fetchFriendList').mockRejectedValue(new Error('net'));
vi.spyOn(bridge.apis.contacts, 'fetchGroupList').mockResolvedValue([]);
vi.spyOn(bridge.apis.contacts, 'fetchUserProfile').mockResolvedValue(makeProfile(10001, 'u_self', 'me'));
bridge.bindPid(7, sender);
const result = await bridge.whenRosterWarmupSettled();
expect(result).toEqual({ friendsLoaded: false, groupsLoaded: true });
expect(fetchFriendList).toHaveBeenCalledOnce();
bridge.bindPid(8, sender);
await bridge.whenRosterWarmupSettled();
expect(fetchFriendList).toHaveBeenCalledOnce();
bridge.dispose();
});
it('discards in-flight warmup writes after dispose', async () => {
const identity = IdentityService.memory('10001');
const bridge = new Bridge(identity);
let releaseFriends!: (friends: FriendInfo[]) => void;
const friendsGate = new Promise<FriendInfo[]>((resolve) => { releaseFriends = resolve; });
vi.spyOn(bridge.apis.contacts, 'fetchFriendList').mockReturnValue(friendsGate);
vi.spyOn(bridge.apis.contacts, 'fetchGroupList').mockResolvedValue([]);
bridge.bindPid(7, sender);
const settled = bridge.whenRosterWarmupSettled();
bridge.dispose();
releaseFriends([makeFriend(22222, 'u_friend', 'friend')]);
await expect(settled).resolves.toEqual({ friendsLoaded: false, groupsLoaded: false });
expect(() => { identity.nickname = 'x'; }).toThrow(/closed/);
});
});
+19 -135
View File
@@ -16,7 +16,6 @@
import { describe, expect, it, vi } from 'vitest';
import { inflateSync } from 'zlib';
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
vi.mock('@snowluma/protocol/highway/image-upload', () => ({
uploadImageMsgInfo: vi.fn(async () => new Uint8Array([7, 8, 9])),
@@ -28,8 +27,6 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({
uploadVideoMsgInfo: vi.fn(async () => new Uint8Array([1, 2, 3])),
}));
import { protobuf_encode } from '@snowluma/proton';
import type { MsgInfo } from '@snowluma/proto-defs/element';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload';
@@ -243,47 +240,6 @@ describe('element-builder / all-message validation preflight', () => {
expect(uploadImageMsgInfo).not.toHaveBeenCalled();
});
it('emits a customFace sibling for forwardFake group images (#441)', async () => {
const md5Hex = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
const msgInfo = protobuf_encode<MsgInfo>({
msgInfoBody: [{
index: {
fileUuid: 'EhRimg',
info: {
fileHash: md5Hex,
fileName: `${md5Hex}.png`,
fileSize: 12,
width: 10,
height: 10,
type: { picFormat: 1001 },
},
},
}],
});
vi.mocked(uploadImageMsgInfo).mockResolvedValueOnce(msgInfo);
const elems = await buildSendElems(
[{ type: 'image', url: 'file:///tmp/a.png' }],
{ bridge: fakeBridge, groupId: 12345, forwardFake: true, scene: 'forward' },
);
expect(elems).toHaveLength(2);
expect(elems[0]!.commonElem).toBeDefined();
expect(elems[1]!.customFace?.filePath).toBe(`${md5Hex}.png`);
expect(elems[1]!.customFace?.md5).toHaveLength(16);
});
it('does not emit a legacy sibling on a live group image send', async () => {
vi.mocked(uploadImageMsgInfo).mockResolvedValueOnce(new Uint8Array([7, 8, 9]));
const elems = await buildSendElems(
[{ type: 'image', url: 'file:///tmp/a.png' }],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(elems).toHaveLength(1);
expect(elems[0]!.commonElem).toBeDefined();
expect(elems[0]!.customFace).toBeUndefined();
});
it('accepts a received imageUrl-only element for re-send', async () => {
vi.mocked(uploadImageMsgInfo).mockClear();
await buildSendElems(
@@ -295,7 +251,6 @@ describe('element-builder / all-message validation preflight', () => {
true,
12345,
expect.objectContaining({ imageUrl: 'https://gchat.qpic.cn/received.jpg' }),
undefined,
);
});
@@ -348,25 +303,26 @@ describe('element-builder / file element is no longer carried in elems[]', () =>
});
});
describe('element-builder / forward preview', () => {
// Flat outer forwards use the serviceID=35 RichMsg shape accepted by NTQQ.
// Nested previews keep the modern LightApp JSON because their
// meta.detail.uniseq must match an actionCommand piggyback in the outer
// LongMsgResult.
describe('element-builder / forward preview (com.tencent.multimsg LightApp)', () => {
// The forward preview is the bubble the recipient renders in chat
// before tapping to expand. It MUST be the modern LightApp /
// `com.tencent.multimsg` JSON (not the older `richMsg serviceID=35`
// XML) because nested forwards rely on `meta.detail.uniseq` to link
// each inner preview to the matching `actionCommand` piggyback on
// the outer's LongMsgResult — without uniseq the QQ-NT client has
// no way to walk the tree and has to re-fetch each inner resId.
function decodeLightApp(elem: any): unknown {
return JSON.parse(inflatePrefixedPayload(elem.lightApp.data));
}
it('emits a serviceID=35 richMsg XML for a flat outer forward', async () => {
it('emits a lightApp.data blob with prefix=0x01 (deflated JSON, not XML/serviceID=35)', async () => {
const [elem] = await buildSendElems(
[{ type: 'forward', resId: 'res-XYZ' } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(elem.richMsg?.serviceId).toBe(35);
expect(elem.lightApp).toBeUndefined();
const xml = inflatePrefixedPayload(elem.richMsg!.template1!);
expect(xml).toContain('action="viewMultiMsg"');
expect(xml).toContain('m_resid="res-XYZ"');
expect(elem.lightApp).toBeDefined();
expect((elem as any).richMsg).toBeUndefined();
expect(elem.lightApp!.data![0]).toBe(0x01);
});
it('places resid + uniseq inside meta.detail (and uniseq matches extra.filename)', async () => {
@@ -374,8 +330,6 @@ describe('element-builder / forward preview', () => {
[{ type: 'forward', resId: 'res-XYZ', forwardUuid: 'fixed-uuid-1234' } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(elem.lightApp).toBeDefined();
expect(elem.richMsg).toBeUndefined();
const json = decodeLightApp(elem) as any;
expect(json.app).toBe('com.tencent.multimsg');
expect(json.meta.detail.resid).toBe('res-XYZ');
@@ -386,87 +340,17 @@ describe('element-builder / forward preview', () => {
expect(extra.filename).toBe('fixed-uuid-1234');
});
it('autogenerates m_fileName for a flat outer forward', async () => {
it('autogenerates a uniseq when the element omits forwardUuid (flat forward — cosmetic)', async () => {
const [elem] = await buildSendElems(
[{ type: 'forward', resId: 'res-flat' } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
const xml = inflatePrefixedPayload(elem.richMsg!.template1!);
expect(xml).toContain('m_resid="res-flat"');
expect(xml).toMatch(/m_fileName="[0-9a-f-]{36}"/i);
});
it('escapes dynamic XML fields in a flat outer forward', async () => {
const [elem] = await buildSendElems(
[{
type: 'forward',
resId: 'res&<>"\'',
forwardSource: 'Alice & <Bob>',
forwardSummary: 'summary "quoted" & more',
forwardPrompt: '[A & B]',
forwardNews: [
{ text: 'Alice: <hello>' },
{ text: 'Bob: it\'s "ok"' },
],
forwardTSum: 2,
} as any],
{ bridge: fakeBridge, groupId: 12345 },
);
const xml = inflatePrefixedPayload(elem.richMsg!.template1!);
expect(xml).toContain('m_resid="res&amp;&lt;&gt;&quot;&apos;"');
expect(xml).toContain('brief="[A &amp; B]"');
expect(xml).toContain('Alice &amp; &lt;Bob&gt;');
expect(xml).toContain('summary &quot;quoted&quot; &amp; more');
expect(xml).toContain('Alice: &lt;hello&gt;');
expect(xml).toContain('Bob: it&apos;s &quot;ok&quot;');
expect(xml).toContain('tSum="2"');
});
it('normalizes only unsupported preview characters and records the affected fields', async () => {
const logs: LogEntry[] = [];
const unsubscribe = subscribeLogs(entry => logs.push(entry));
const element = {
type: 'forward' as const,
resId: 'preview-controls',
forwardSource: 'source\u0000',
forwardSummary: 'summary\uFFFE',
forwardPrompt: 'prompt\uFFFF',
forwardNews: [{ text: 'a\u0001b\u000Bc\u001Fd\uD800e\uDC00f😀中文\t\n\r' }],
};
const original = structuredClone(element);
try {
const [elem] = await buildSendElems([element], { bridge: fakeBridge, groupId: 12345 });
const xml = inflatePrefixedPayload(elem.richMsg!.template1!);
expect(xml).toContain('brief="prompt�"');
expect(xml).toContain('source�</title>');
expect(xml).toContain('summary�</summary>');
expect(xml).toContain('a�b�c�d�e�f😀中文&#x9;&#xA;&#xD;</title>');
expect(element).toEqual(original);
expect(logs.filter(entry => entry.message.startsWith('forward preview characters normalized:'))
.map(entry => entry.message)).toEqual([
'forward preview characters normalized: field=source',
'forward preview characters normalized: field=news[0]',
'forward preview characters normalized: field=prompt',
'forward preview characters normalized: field=summary',
]);
} finally {
unsubscribe();
}
});
it('rejects an unrepresentable resource reference instead of rewriting its identity', async () => {
await expect(buildSendElems([{ type: 'forward', resId: 'res\u0001id' }], {
bridge: fakeBridge, groupId: 12345,
})).rejects.toMatchObject({ code: 'INVALID_FIELD', elementType: 'forward', field: 'resId' });
});
it('preserves valid Unicode boundaries and whitespace in preview text', async () => {
const text = '\u0009\u000A\u000D\u0020\uD7FF\uE000\uFFFD\u{10000}\u{10FFFF}';
const [elem] = await buildSendElems([{ type: 'forward', resId: 'valid-unicode', forwardNews: [{ text }] }], {
bridge: fakeBridge, groupId: 12345,
});
expect(inflatePrefixedPayload(elem.richMsg!.template1!))
.toContain('&#x9;&#xA;&#xD; \uD7FF\uE000\uFFFD\u{10000}\u{10FFFF}</title>');
const json = decodeLightApp(elem) as any;
expect(json.meta.detail.resid).toBe('res-flat');
// Auto-generated UUID — non-empty, non-trivial.
expect(json.meta.detail.uniseq).toMatch(/^[0-9a-f-]{36}$/i);
const extra = JSON.parse(json.extra);
expect(extra.filename).toBe(json.meta.detail.uniseq);
});
it('threads forwardSource / forwardSummary / forwardPrompt / forwardNews / forwardTSum verbatim', async () => {
@@ -196,30 +196,10 @@ describe('FlashTransferApi.createFlashTask — disk streaming (#359)', () => {
await api().createFlashTask(file);
expect(mainSlices(slices)).toHaveLength(0);
expect(ApplyUpload.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
fileName: 'hit.mp4',
}));
expect(ApplyUpload.invoke).toHaveBeenCalled(); // thumbs still apply
expect(SetFilesetStatus.invoke).toHaveBeenCalled();
});
it('commits a png as image format 26 rather than video format 2 (#421)', async () => {
const file = writeSrc('shot.png', synth(48, 5));
installSliceuploadOk();
await api().createFlashTask(file);
expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
fileName: 'shot.png',
typeCode: 7,
}));
expect(CommitFile.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
entries: [expect.objectContaining({
fileName: 'shot.png',
formatCode: 26,
})],
}));
});
it('sliceuploads a multi-megabyte file as 1 MiB disk chunks with flash Sha1StateV', async () => {
const bytes = synth(SLICE + 80, 13);
const file = writeSrc('big.mp4', bytes);
+2 -6
View File
@@ -33,8 +33,8 @@ describe('mapGroupNoticeResponse', () => {
publish_time: 1_700_000_000,
message: {
text: 'regular',
image: [{ id: 'pic', url: 'https://gdynamic.qpic.cn/gdynamic/pic/0', width: 640, height: 360 }],
images: [{ id: 'pic', url: 'https://gdynamic.qpic.cn/gdynamic/pic/0', width: 640, height: 360 }],
image: [{ id: 'pic', width: 640, height: 360 }],
images: [{ id: 'pic', width: 640, height: 360 }],
},
settings: {},
read_num: 2,
@@ -75,9 +75,5 @@ describe('mapGroupNoticeResponse', () => {
ec: 0,
feeds: [feed('bad', { msg: { text: 'bad', pics: [{ id: 'x', w: 'wide', h: 20 }] } })],
})).toThrow('image 0.w');
expect(() => mapGroupNoticeResponse({
ec: 0,
feeds: [feed('bad-id', { msg: { text: 'bad', pics: [{ id: 'a/b', w: 20, h: 20 }] } })],
})).toThrow('malformed');
});
});
@@ -302,27 +302,6 @@ describe('fetchHighwaySession trace lifecycle', () => {
}
});
it('keeps a server address encoded as a fixed 32-bit field', async () => {
// Address field 2 is four raw bytes. The fixture is not produced by the
// schema encoder, so a varint declaration cannot hide itself.
const responseData = Buffer.from('8a50150a02aabb1201cc1a0c08011208150102030418903f', 'hex');
const bridge = {
identity: { uin: '10001' },
sendRawPacket: vi.fn(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData,
})),
} as unknown as BridgeContext;
const session = await fetchHighwaySession(bridge);
expect(session.host).toBe('1.2.3.4');
expect(session.port).toBe(8080);
});
it('records a thrown control request as one failed terminal', async () => {
const bridge = {
identity: { uin: '10001' },
@@ -45,8 +45,8 @@ describe('image-upload', () => {
expect(args.businessType).toBe(1);
expect(args.compatQmsgSceneType).toBe(2);
expect(args.uploads[0]!.cmdId).toBe(GROUP_IMAGE_CMD_ID);
expect(args.extBizInfo.pic?.extData).toBeDefined();
expect(args.extBizInfo.pic?.bytesPbReserveC2c).toBeUndefined();
expect((args.extBizInfo as any).pic.reserveTroop).toBeDefined();
expect((args.extBizInfo as any).pic.reserveC2c).toBeUndefined();
});
it('c2c: uses 0x11C5_100 + PRIVATE_IMAGE_CMD_ID and tags scene as c2c', async () => {
@@ -56,8 +56,8 @@ describe('image-upload', () => {
expect(args.serviceCmd).toBe('OidbSvcTrpcTcp.0x11c5_100');
expect(args.compatQmsgSceneType).toBe(1);
expect(args.uploads[0]!.cmdId).toBe(PRIVATE_IMAGE_CMD_ID);
expect(args.extBizInfo.pic?.bytesPbReserveC2c).toBeDefined();
expect(args.extBizInfo.pic?.extData).toBeUndefined();
expect((args.extBizInfo as any).pic.reserveC2c).toBeDefined();
expect((args.extBizInfo as any).pic.reserveTroop).toBeUndefined();
});
it('uses receive-side imageUrl when url/fileId are absent', async () => {
@@ -110,7 +110,7 @@ describe('image-upload', () => {
await uploadImageMsgInfo({} as any, true, 12345, { url: 'http://x', subType: 0 } as any);
expect(pipeline.finalizeMediaMsgInfo).toHaveBeenCalledOnce();
const [, defaultPic] = vi.mocked(pipeline.finalizeMediaMsgInfo).mock.calls[0]!;
expect(defaultPic).toEqual({ bizType: 0, textSummary: '[图片]', extData: { subType: 0, textSummary: '[图片]' } });
expect(defaultPic).toEqual({ bizType: 0, textSummary: '[图片]' });
});
it('caller-supplied summary wins over the Chinese default', async () => {
@@ -120,6 +120,6 @@ describe('image-upload', () => {
url: 'http://x', subType: 0, summary: '[custom-bubble]',
} as any);
const [, defaultPic] = vi.mocked(pipeline.finalizeMediaMsgInfo).mock.calls[0]!;
expect(defaultPic).toEqual({ bizType: 0, textSummary: '[custom-bubble]', extData: { subType: 0, textSummary: '[custom-bubble]' } });
expect(defaultPic).toEqual({ bizType: 0, textSummary: '[custom-bubble]' });
});
});
@@ -488,15 +488,6 @@ describe('pipeline — finalizeMediaMsgInfo', () => {
expect(decoded.extBizInfo.pic.textSummary).toBe('[image]');
});
it('preserves a server ptt waveform on the outgoing MsgInfo', () => {
const waveform = new Uint8Array([8, 4, 18, 4, 10, 20, 30, 40]);
const out = finalizeMediaMsgInfo({
msgInfo: { msgInfoBody: [], extBizInfo: { ptt: { waveform } } },
});
const decoded: any = protobuf_decode<EncodableMediaMsgInfo>(out);
expect(decoded.extBizInfo.ptt.waveform).toEqual(waveform);
});
it('without defaultPic, leaves pic untouched when server omits it', () => {
const out = finalizeMediaMsgInfo({
msgInfo: { msgInfoBody: [], extBizInfo: {} },
+6 -27
View File
@@ -2,8 +2,8 @@
// regular load path goes through ffmpeg's silk encoder + the OS temp
// directory, which we don't want to exercise in a unit test. The
// fingerprint path covers most of what makes ptt-upload distinct
// (group/c2c requestId difference, command id mapping, the group-only
// bytesGeneralFlags blob, voiceFormat honouring).
// (group/c2c requestId difference, command id mapping, NapCat-style
// bytesGeneralFlags, voiceFormat honouring).
import { describe, it, expect, vi, beforeEach } from 'vitest';
@@ -30,15 +30,6 @@ describe('ptt-upload', () => {
vi.mocked(pipeline.finalizeMediaMsgInfo).mockClear();
});
it('retains successful upload metadata for self-sent history', async () => {
const node = { fileUuid: 'uploaded-resource', storeId: 1, info: { fileSize: 1234 } };
vi.mocked(pipeline.runNtv2Upload).mockResolvedValueOnce({ msgInfo: { msgInfoBody: [{ index: node }] } } as any);
const element = { ...FINGERPRINT };
await uploadPttMsgInfo({} as any, true, 12345, element);
expect(element).toMatchObject({ fileId: 'uploaded-resource', mediaNode: node, md5Hex: 'aa', sha1Hex: 'bb' });
expect(element.fileName).toBeTruthy();
});
it('group: 0x126E_100 + GROUP_PTT_CMD_ID + group-flavored bytesGeneralFlags', async () => {
await uploadPttMsgInfo({} as any, true, 12345, FINGERPRINT);
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
@@ -54,7 +45,7 @@ describe('ptt-upload', () => {
);
});
it('c2c: 0x126D_100 + PRIVATE_PTT_CMD_ID + requestId=4 + no generalFlags', async () => {
it('c2c: 0x126D_100 + PRIVATE_PTT_CMD_ID + requestId=4 + c2c-flavored flags', async () => {
await uploadPttMsgInfo({} as any, false, 'recipient-uid', FINGERPRINT);
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
expect(args.oidbCmd).toBe(0x126D);
@@ -62,21 +53,9 @@ describe('ptt-upload', () => {
expect(args.requestId).toBe(4);
expect(args.uploads[0]!.cmdId).toBe(PRIVATE_PTT_CMD_ID);
// Private voice must not carry a generalFlags blob: with the NapCat c2c
// one present the receiver drops the progress bar even though the waveform
// is in the payload. Group keeps its 10-byte blob (covered above).
expect((args.extBizInfo as any).ptt.bytesGeneralFlags).toBeUndefined();
expect((args.extBizInfo as any).ptt.waveform).toBeUndefined();
// Reserve stays the bare legacy 4 bytes, same as group voice.
expect([...(args.extBizInfo as any).ptt.bytesReserve]).toEqual([0x08, 0x00, 0x38, 0x00]);
});
it('fingerprint path does not invent a waveform', async () => {
await uploadPttMsgInfo({} as any, true, 12345, FINGERPRINT);
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
expect((args.extBizInfo as any).ptt.waveform).toBeUndefined();
expect(pipeline.finalizeMediaMsgInfo).toHaveBeenCalledOnce();
const c2cFlags = (args.extBizInfo as any).ptt.bytesGeneralFlags;
expect(c2cFlags.length).toBe(14);
expect(c2cFlags[0]).toBe(0x9a);
});
it('fingerprint payload: zero bytes, fastOnlyError ready, voiceFormat defaults to 1', async () => {
@@ -49,15 +49,6 @@ describe('video-upload', () => {
vi.mocked(pipeline.finalizeMediaMsgInfo).mockClear();
});
it('retains successful upload metadata for self-sent history', async () => {
const node = { fileUuid: 'uploaded-resource', storeId: 1, info: { fileSize: 1234 } };
vi.mocked(pipeline.runNtv2Upload).mockResolvedValueOnce({ msgInfo: { msgInfoBody: [{ index: node }] } } as any);
const element = { ...FINGERPRINT };
await uploadVideoMsgInfo({} as any, true, 12345, element);
expect(element).toMatchObject({ fileId: 'uploaded-resource', mediaNode: node, md5Hex: 'aa', sha1Hex: 'bb' });
expect(element.fileName).toBeTruthy();
});
it('group: 0x11EA_100 + GROUP_VIDEO_CMD_ID for main, GROUP_VIDEO_THUMB_CMD_ID for thumb', async () => {
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
+3 -147
View File
@@ -589,23 +589,6 @@ describe('IdentityService', () => {
lastError: expect.stringMatching(/locked/i),
lastFailureAt: suspendedFailureAt,
});
const skipLogsBeforeBurst = seen.filter((entry) =>
/persistence write skipped/.test(entry.message),
).length;
expect(skipLogsBeforeBurst).toBe(1);
for (let i = 0; i < 50; i += 1) {
identity.rememberRequestIdentity({
uid: `u_skip_burst_${i}`,
uin: 500_000 + i,
});
}
expect(seen.filter((entry) => /persistence write skipped/.test(entry.message)))
.toHaveLength(1);
await vi.advanceTimersByTimeAsync(60_000);
identity.rememberRequestIdentity({ uid: 'u_skip_after_minute', uin: 600_000 });
const skipLogs = seen.filter((entry) => /persistence write skipped/.test(entry.message));
expect(skipLogs).toHaveLength(2);
expect(skipLogs[1]?.message).toMatch(/suppressed=50/);
releaseLock();
identity.close();
@@ -774,9 +757,6 @@ describe('IdentityService', () => {
sign: '',
avatar: '',
level: 0,
qidianMasterFlag: 0,
qidianCrewFlag: 0,
qidianCrewFlag2: 0,
};
const request = {
groupId: GROUP_ID,
@@ -809,7 +789,6 @@ describe('IdentityService', () => {
['group requests', () => identity.rememberGroupRequests([request])],
['request identity', () => identity.rememberRequestIdentity({ uid: 'u_request', uin: 88888 })],
['group member identity', () => identity.rememberGroupMemberIdentity(GROUP_ID, { uid: 'u_new', uin: 99999 })],
['group member joined', () => identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_new', uin: 99999 })],
['group member inactive', () => identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin })],
];
@@ -824,123 +803,6 @@ describe('IdentityService', () => {
expect(identity.findUinByUid('u_request')).toBeNull();
});
it('does not treat identity-only sightings as live group members', () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMemberIdentity(GROUP_ID, { uid: 'u_seen', uin: 88888 });
expect(identity.findGroupMember(GROUP_ID, 88888)).toBeNull();
expect(identity.findUinByUid('u_seen')).toBe(88888);
identity.close();
});
it('does not hydrate identity-only sightings as live members after reopen', () => {
const dbPath = tempDbPath('identity-only-not-roster');
const member = makeMember(33333, 'u_member', 'card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.rememberGroupMemberIdentity(GROUP_ID, { uid: 'u_operator', uin: 88888 });
expect(identity.findGroupMember(GROUP_ID, 88888)).toBeNull();
identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('card');
expect(identity.findGroupMember(GROUP_ID, 88888)).toBeNull();
expect(identity.findUinByUid('u_operator')).toBe(88888);
identity.close();
}
});
it('records a thin live member on join without inventing roster details', () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
const existing = makeMember(33333, 'u_existing', 'card');
identity.rememberGroupMembers(GROUP_ID, [existing]);
identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_join', uin: 44444 });
identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_join', uin: 44444 });
identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_ignored', uin: 0 });
const joined = identity.findGroupMember(GROUP_ID, 44444);
expect(joined).toMatchObject({
uin: 44444,
uid: 'u_join',
nickname: '',
card: '',
role: 'member',
});
expect(joined?.isRobot).toBeUndefined();
expect(identity.findGroupMember(GROUP_ID, 33333)?.card).toBe('card');
identity.close();
});
it('persists a thin live member on join across reopen', () => {
const dbPath = tempDbPath('join-live-roster');
const existing = makeMember(33333, 'u_existing', 'card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [existing]);
identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_join', uin: 44444 });
identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
const joined = identity.findGroupMember(GROUP_ID, 44444);
expect(joined).toMatchObject({
uin: 44444,
uid: 'u_join',
nickname: '',
card: '',
role: 'member',
});
expect(joined?.isRobot).toBeUndefined();
expect(identity.findGroupMember(GROUP_ID, 33333)?.card).toBe('card');
identity.close();
}
});
it('drops a leaver from the live roster and keeps their identity mapping', () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
const member = makeMember(33333, 'u_member', 'card');
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin });
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid);
identity.close();
});
it('keeps a leaver out of the live roster after reopen', () => {
const dbPath = tempDbPath('leave-live-roster');
const member = makeMember(33333, 'u_member', 'card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin });
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid);
identity.close();
}
});
it('marks missing members inactive only after a successful full refresh', () => {
const dbPath = tempDbPath('inactive-refresh');
const first = makeMember(33333, 'u_first');
@@ -1039,7 +901,7 @@ describe('IdentityService', () => {
expect(identity.findUidByUin(55555)).toBe('u_friend_request');
expect(identity.findUinByUid('u_friend_request')).toBe(55555);
expect(identity.findGroup(GROUP_ID)).toBeNull();
expect(identity.findGroup(GROUP_ID)?.groupId).toBe(GROUP_ID);
expect(identity.findUidByUin(66666)).toBe('u_group_request');
identity.close();
@@ -1049,10 +911,7 @@ describe('IdentityService', () => {
describe('IdentityService.resolveUid', () => {
function makeProfile(uin: number, uid: string): UserProfileInfo {
return {
uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
qidianMasterFlag: 0, qidianCrewFlag: 0, qidianCrewFlag2: 0,
};
return { uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0 };
}
it('returns the cached uid without invoking the fetcher', async () => {
@@ -1117,10 +976,7 @@ describe('IdentityService.resolveUid', () => {
describe('IdentityService inbound UID→UIN', () => {
function makeProfile(uin: number, uid: string): UserProfileInfo {
return {
uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
qidianMasterFlag: 0, qidianCrewFlag: 0, qidianCrewFlag2: 0,
};
return { uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0 };
}
it('findUinByUid treats a numeric uid as that uin without consulting maps', () => {
+2 -4
View File
@@ -494,8 +494,7 @@ describe('parseMsgPush Event0x210 subType=364 (friend remark synchronization)',
const pipeline = new IncomingPacketPipeline({
identity,
events: new BridgeEventBus(),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
refreshMemberCache: vi.fn(async () => false),
resolveGroupJoinRequest: vi.fn(async () => null),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
@@ -943,8 +942,7 @@ describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache
const pipeline = new IncomingPacketPipeline({
identity,
events: new BridgeEventBus(),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
refreshMemberCache: vi.fn(async () => false),
resolveGroupJoinRequest: vi.fn(async () => null),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
@@ -5,8 +5,6 @@ import path from 'path';
import {
DEFAULT_BODY_TEMPLATE,
DEFAULT_DEBOUNCE_SECONDS,
DEFAULT_EMAIL_BODY_TEMPLATE,
DEFAULT_SUBJECT_TEMPLATE,
defaultNotificationsConfig,
normalizeNotificationsConfig,
renderTemplate,
@@ -102,7 +100,6 @@ describe('normalizeNotificationsConfig — total normalize', () => {
{
id: 'dingtalk',
name: 'DingTalk',
type: 'webhook',
url: 'https://oapi.dingtalk.com/robot/send',
bodyTemplate: '{event}',
enabled: true,
@@ -135,128 +132,11 @@ describe('normalizeNotificationsConfig — total normalize', () => {
expect(channels[0].url).toBe('https://a.com');
});
it('defaults enabled=true, name→id, type=webhook, and bodyTemplate→default', () => {
it('defaults enabled=true, name→id, and bodyTemplate→default', () => {
const { channels } = normalizeNotificationsConfig({ channels: [{ id: 'c1', url: 'https://a.com' }] });
expect(channels[0].enabled).toBe(true);
expect(channels[0].name).toBe('c1');
expect(channels[0].type).toBe('webhook');
expect(channels[0].bodyTemplate).toBe(DEFAULT_BODY_TEMPLATE);
expect(channels[0].headers).toBeUndefined();
});
it('keeps valid request headers and drops unsafe or empty ones', () => {
const { channels } = normalizeNotificationsConfig({
channels: [{
id: 'feishu',
url: 'https://open.feishu.cn/hook',
headers: {
Authorization: 'Bearer secret',
'X-Custom': 'ok',
'Bad Name': 'x',
'': 'x',
Inject: 'line\r\nX-Evil: 1',
Empty: ' ',
NotString: 1,
} as Record<string, unknown>,
}],
});
expect(channels[0].headers).toEqual({
Authorization: 'Bearer secret',
'X-Custom': 'ok',
});
});
it('omits an empty headers object after normalize', () => {
const { channels } = normalizeNotificationsConfig({
channels: [{ id: 'c1', url: 'https://a.com', headers: { 'Bad Name': 'x' } }],
});
expect(channels[0].headers).toBeUndefined();
});
it('keeps an email channel without a webhook url and fills SMTP defaults', () => {
const { channels } = normalizeNotificationsConfig({
channels: [{
id: 'ops-mail',
type: 'email',
smtpHost: 'smtp.qq.com',
from: 'SnowLuma <bot@qq.com>',
to: 'a@example.com; b@example.com, a@example.com',
}],
});
expect(channels).toEqual([{
id: 'ops-mail',
name: 'ops-mail',
type: 'email',
url: '',
bodyTemplate: DEFAULT_EMAIL_BODY_TEMPLATE,
enabled: true,
smtpHost: 'smtp.qq.com',
smtpPort: 465,
smtpSecure: true,
from: 'SnowLuma <bot@qq.com>',
to: 'a@example.com, b@example.com',
subjectTemplate: DEFAULT_SUBJECT_TEMPLATE,
}]);
});
it('defaults port 587 when smtpSecure is explicitly false', () => {
const { channels } = normalizeNotificationsConfig({
channels: [{
id: 'relay',
type: 'email',
smtpHost: 'relay.internal',
smtpSecure: false,
from: 'bot@internal',
to: 'ops@internal',
}],
});
expect(channels[0]).toMatchObject({ smtpPort: 587, smtpSecure: false });
});
it('treats port 587 without smtpSecure as STARTTLS (secure=false)', () => {
const { channels } = normalizeNotificationsConfig({
channels: [{
id: 'gmail',
type: 'email',
smtpHost: 'smtp.gmail.com',
smtpPort: 587,
from: 'bot@gmail.com',
to: 'ops@gmail.com',
}],
});
expect(channels[0]).toMatchObject({ smtpPort: 587, smtpSecure: false });
});
it('drops email channels missing host / from / to, and unknown types', () => {
const { channels } = normalizeNotificationsConfig({
channels: [
{ id: 'no-host', type: 'email', from: 'a@b.com', to: 'c@d.com' },
{ id: 'no-from', type: 'email', smtpHost: 'smtp.example.com', to: 'c@d.com' },
{ id: 'bad-to', type: 'email', smtpHost: 'smtp.example.com', from: 'a@b.com', to: 'not-an-email' },
{ id: 'sms', type: 'sms', url: 'https://a.com' },
{ id: 'ok', type: 'email', smtpHost: 'smtp.example.com', from: 'a@b.com', to: 'c@d.com', smtpUser: 'a@b.com', smtpPass: 'p' },
],
});
expect(channels.map((c) => c.id)).toEqual(['ok']);
expect(channels[0]).toMatchObject({ smtpUser: 'a@b.com', smtpPass: 'p' });
});
it('does not keep webhook-only fields on an email channel', () => {
const { channels } = normalizeNotificationsConfig({
channels: [{
id: 'mail',
type: 'email',
url: 'https://should.be.ignored',
headers: { Authorization: 'Bearer x' },
smtpHost: 'smtp.example.com',
from: 'a@b.com',
to: 'c@d.com',
evil: 'x',
}],
});
expect(channels[0].url).toBe('');
expect(channels[0].headers).toBeUndefined();
expect(channels[0]).not.toHaveProperty('evil');
});
});
@@ -1,9 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
NotificationManager,
createDefaultPost,
selectChannels,
type MailPayload,
type NotificationManagerDeps,
type PostResult,
} from '../src/notifications/manager';
@@ -13,7 +11,6 @@ function ch(over: Partial<NotificationChannel> = {}): NotificationChannel {
return {
id: 'c1',
name: 'C1',
type: 'webhook',
url: 'https://hook.example/c1',
bodyTemplate: '{event}:{uin}:{nickname}',
enabled: true,
@@ -21,26 +18,6 @@ function ch(over: Partial<NotificationChannel> = {}): NotificationChannel {
};
}
function emailCh(over: Partial<NotificationChannel> = {}): NotificationChannel {
return {
id: 'mail',
name: 'Mail',
type: 'email',
url: '',
bodyTemplate: '{event}:{uin}:{nickname}',
enabled: true,
smtpHost: 'smtp.example.com',
smtpPort: 465,
smtpSecure: true,
smtpUser: 'bot@example.com',
smtpPass: 'secret',
from: 'bot@example.com',
to: 'ops@example.com',
subjectTemplate: '{event} {uin}',
...over,
};
}
describe('selectChannels (pure)', () => {
it('keeps only enabled channels the UIN opted into, in config order', () => {
const channels = [ch({ id: 'a' }), ch({ id: 'b', enabled: false }), ch({ id: 'c' })];
@@ -80,23 +57,6 @@ describe('NotificationManager — dispatch + history', () => {
expect(posts).toEqual([{ url: 'https://hook.example/c1', body: 'offline:123:123' }]);
});
it('forwards channel request headers to the post collaborator', async () => {
const posts: { url: string; body: string; headers?: Record<string, string> }[] = [];
const { mgr } = setup({
loadConfig: () => ({
version: 1,
debounceSeconds: 30,
channels: [ch({ headers: { Authorization: 'Bearer secret' } })],
}),
post: async (url, body, headers) => {
posts.push({ url, body, headers });
return { ok: true, status: 200 };
},
});
await mgr.notify('123', 'offline');
expect(posts[0]?.headers).toEqual({ Authorization: 'Bearer secret' });
});
it('uses the nickname captured on an online/offline edge', async () => {
const { posts, mgr } = setup();
mgr.handleOnline('123', 'Alice'); // caches nickname; cold online → no post
@@ -189,82 +149,6 @@ describe('NotificationManager.testSend', () => {
});
});
describe('NotificationManager — email channels', () => {
it('sends mail instead of POSTing, with rendered subject and body', async () => {
const posts: unknown[] = [];
const mails: MailPayload[] = [];
const mgr = new NotificationManager({
loadConfig: () => ({ version: 1, debounceSeconds: 30, channels: [emailCh()] }),
loadChannelIds: () => ['mail'],
post: async (url, body) => {
posts.push({ url, body });
return { ok: true, status: 200 };
},
sendMail: async (mail) => {
mails.push(mail);
return { ok: true };
},
now: () => 1000,
});
await mgr.notify('123', 'offline');
expect(posts).toEqual([]);
expect(mails).toEqual([{
host: 'smtp.example.com',
port: 465,
secure: true,
user: 'bot@example.com',
pass: 'secret',
from: 'bot@example.com',
to: 'ops@example.com',
subject: 'offline 123',
text: 'offline:123:123',
}]);
});
it('records a failed sendMail without calling post', async () => {
const mgr = new NotificationManager({
loadConfig: () => ({ version: 1, debounceSeconds: 30, channels: [emailCh()] }),
loadChannelIds: () => ['mail'],
post: async () => {
throw new Error('webhook must not run');
},
sendMail: async () => ({ ok: false, error: 'SMTP 认证失败' }),
now: () => 1000,
});
await mgr.notify('123', 'offline');
expect(mgr.getRecent()[0]).toMatchObject({ ok: false, error: 'SMTP 认证失败', channelId: 'mail' });
});
it('fails closed when sendMail is not wired', async () => {
const mgr = new NotificationManager({
loadConfig: () => ({ version: 1, debounceSeconds: 30, channels: [emailCh()] }),
loadChannelIds: () => ['mail'],
post: async () => ({ ok: true, status: 200 }),
now: () => 1000,
});
await mgr.notify('123', 'offline');
expect(mgr.getRecent()[0]).toMatchObject({ ok: false, error: 'email delivery is not configured' });
});
it('testSend uses sendMail and still skips history', async () => {
const mails: MailPayload[] = [];
const mgr = new NotificationManager({
loadConfig: () => ({ version: 1, debounceSeconds: 30, channels: [emailCh({ enabled: false })] }),
loadChannelIds: () => [],
post: async () => ({ ok: true, status: 200 }),
sendMail: async (mail) => {
mails.push(mail);
return { ok: true };
},
now: () => 1000,
});
expect(await mgr.testSend('mail')).toMatchObject({ found: true, ok: true });
expect(mails[0]?.subject).toBe('offline 10000');
expect(mails[0]?.text).toBe('offline:10000:测试账号');
expect(mgr.getRecent()).toEqual([]);
});
});
describe('NotificationManager — debounce integration (fake timers)', () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
@@ -312,38 +196,4 @@ describe('NotificationManager — debounce integration (fake timers)', () => {
await vi.advanceTimersByTimeAsync(0);
expect(events).toEqual(['offline']);
});
it('ignores online/offline after dispose so process exit is not a runtime drop', async () => {
const { events, mgr } = setup(0);
mgr.dispose();
mgr.handleOnline('123', 'Bob');
mgr.handleOffline('123', 'Bob');
await vi.advanceTimersByTimeAsync(0);
expect(events).toEqual([]);
});
});
describe('createDefaultPost timeout', () => {
const name = 'SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS';
const saved = process.env[name];
afterEach(() => {
if (saved === undefined) delete process.env[name];
else process.env[name] = saved;
vi.unstubAllGlobals();
});
it('uses SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS', async () => {
process.env[name] = '1234';
const seen: number[] = [];
const timeout = AbortSignal.timeout.bind(AbortSignal);
vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms: number) => {
seen.push(ms);
return timeout(50);
});
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200 })));
const post = createDefaultPost();
await post('http://127.0.0.1/hook', '{}');
expect(seen).toEqual([1234]);
});
});
@@ -1,289 +0,0 @@
import { afterEach, describe, expect, it } from 'vitest';
import net from 'node:net';
import tls from 'node:tls';
import {
buildMimeMessage,
extractAddress,
formatSmtpError,
parseRecipients,
sendSmtpMail,
SmtpError,
} from '../src/notifications/smtp';
// Same throwaway pair as webui-tls.test.ts (CN=snowluma-test).
const CERT = `-----BEGIN CERTIFICATE-----
MIIDETCCAfmgAwIBAgIUNiu66PmcO6Do6cUaB92UKD8j3qYwDQYJKoZIhvcNAQEL
BQAwGDEWMBQGA1UEAwwNc25vd2x1bWEtdGVzdDAeFw0yNjA2MTgwNjIwMTZaFw0z
NjA2MTUwNjIwMTZaMBgxFjAUBgNVBAMMDXNub3dsdW1hLXRlc3QwggEiMA0GCSqG
SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCm0sVJhqlG75gOFJVsUJOfR+oqvb9eSq4t
k5QItuwXr85E2mrzuKFnSzVVbi3VqqyN8t4otL11mGll2ANSjusmWN4hzpaOBBdX
bP4UNX/YA7oHId+QKbVicxJgxDE18aPTwaWullyw23LsMsij8T4nLk4eHiOkeRfi
uLinG1COe3gUGkCK4uyyMT4Vz+y+5Oj9dvoXYL/A/KmcNtq7JrX7F7qYnYsJKLZZ
aZeFyIGSE8ihb0k53iyJ3agWY+rMUD+p5J7pgIZzBd5dcZuI+KwixVKZgapG5n5R
ghrnN2ZAQFz13yTRXYmDYy42m4Ue73hMmmt1xVXyf+WVhvrD6pphAgMBAAGjUzBR
MB0GA1UdDgQWBBRW/HP12nj9fYMYNxa3jyqmnUigvTAfBgNVHSMEGDAWgBRW/HP1
2nj9fYMYNxa3jyqmnUigvTAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUA
A4IBAQCijzVQ/jHNoqu6stvkkigUv2lTKrd1EHcTZLfzwQkmNv/hfY2EMobO/Qxs
FhmITreKFALJ/dUwTt0UTO00LV9whEgr2of4x8wwjZ9wRstY6uyRYBP85QC8+8mZ
zWlcf611HugrmpOWjWfEVmmxdI1m26YWTn52nZFPnJqDWg2+RlLJWl55lVotbXEZ
Fvas4Vcf2KOk0QwBQKvpt0BISeTIQhbT4GnducxSxyoXGeBQOjQNYb/vTpMn4F9U
IAxSsfs9WVoHKXOabK8GV89BCxWoRk4UaSahTq/2Vnbgt86tWibt3lA4y49+XhA2
6z7n9HgJAUKqhsDrYvZmM7/VZ2d5
-----END CERTIFICATE-----
`;
const KEY = `-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCm0sVJhqlG75gO
FJVsUJOfR+oqvb9eSq4tk5QItuwXr85E2mrzuKFnSzVVbi3VqqyN8t4otL11mGll
2ANSjusmWN4hzpaOBBdXbP4UNX/YA7oHId+QKbVicxJgxDE18aPTwaWullyw23Ls
Msij8T4nLk4eHiOkeRfiuLinG1COe3gUGkCK4uyyMT4Vz+y+5Oj9dvoXYL/A/Kmc
Ntq7JrX7F7qYnYsJKLZZaZeFyIGSE8ihb0k53iyJ3agWY+rMUD+p5J7pgIZzBd5d
cZuI+KwixVKZgapG5n5RghrnN2ZAQFz13yTRXYmDYy42m4Ue73hMmmt1xVXyf+WV
hvrD6pphAgMBAAECggEAJ13+u4qhIMHCnrQBzPU42PImEt8DLXOvJcc5PFM6ZJ6S
rRHkAk60HAWV+OqOu2jS3o6NGYsJWJpWaPewVQev+zUmelDfm3TgsztfvBIh8K50
dGFsef81tB1WnWo++K1kzUBZ4ljOV9f5hz62tWVlFubo/Vd8bsA6wEB6Jskd2fls
ZOO0hJCb/M6IIwe3cWw4sb/YFTTLMUnVHM0aJfnQ/QH+uraRwecJMv118d0YBYVG
DsNmYqrv9TYNBh4P9mKv6/0x8zaKsJZVLAMwHztILHItOXBfxCbSDivGWVUGiDq2
NxEuBOgxzOelxEYzUzf7B6sjHoEeIL5wIKQbwUbmfwKBgQDZRLhucrMZPw7ous1t
igkO32p1ku7FRxm0/JAskc66oX61KLIYbZFM9N7nTXAEs8ZGhzUkdSgxNcdHWIdK
RI+6pd2FhhcKU1feEohlOHvZTXXEMhm61phWnN391GZXfwMKSpscqsu9kIix2jtw
4YrzKLx82EDDHcLfBh9AtArKywKBgQDEj+7UJp5wuqz9hj+gogXeq4Buv9be1u4u
HCJZMZzLCwVjvoqYw0n1afXP3057v8hQPGsBaxzQpOg7i1lYGGfuZ9T6T8fFrtqw
m/LJLHhMQxeyCEQi1/EoNewvVGSwBJkLOuOs8T2WmMXmOgdHbEYdzkKtT71jst6y
TeJ15hVuAwKBgBMK4t9LTkc4L6ZWOQsQvhp/mmUTq7m+sZIbUMeXP/c7kE9wcauS
btm/3ImJT/gZiZdE4nN/kTY+8GhgafsoZzCEuRWq2vocs+bS2QGGIdS55Uh826R0
ioWM2igVJaMljq6oO1AX6COFN3XfGraaDgOh3mNS0NpJEXtangKdxRRhAoGAP9SF
t/r6hJz6RDHuQ5mZ0l9bC5vciOy+19ZnCRPlWMIxc9ySYV05jSplmqVndSQoRnX4
QbOo3dBPYda0orj6Nx8cuFRkCTvo5GUgCFgakJlQ/o1UowQA2g/4rL35HHfBwzXS
bXzBhUADM+owJu9wLYmneWRlmhSh4MEOAz8+QkUCgYAw0fA1Im2/ftrA2Z2IENTi
U4cLXqeUeGJfXjIBklUmXhc4qrd/9V9eEHjackI/JI7Qhp/QfPWMXLudlSrppnNJ
+s3dVevEKosiZbf4qtTtlmR/IifuTKjK5O94KlBT+evxNsL4Hv0b0oTsVNnEfOOl
OUsvSYNSnfvl87tyLIxYLA==
-----END PRIVATE KEY-----
`;
interface MockOptions {
secure?: boolean;
starttls?: boolean;
mechs?: string;
failAuth?: boolean;
}
interface MockSmtp {
port: number;
commands: string[];
data: string;
close: () => Promise<void>;
}
const closers: Array<() => Promise<void>> = [];
afterEach(async () => {
while (closers.length > 0) {
const close = closers.pop();
if (close) await close();
}
});
function attachSession(
socket: net.Socket | tls.TLSSocket,
opts: MockOptions,
sink: MockSmtp,
greet = true,
): void {
let buf = '';
let mode: 'cmd' | 'data' = 'cmd';
let loginStep = 0;
const write = (s: string) => socket.write(s);
if (greet) write('220 mock ESMTP\r\n');
socket.on('data', (chunk) => {
buf += chunk.toString('utf8');
if (mode === 'data') {
const end = buf.indexOf('\r\n.\r\n');
if (end === -1) return;
sink.data = buf.slice(0, end);
buf = buf.slice(end + 5);
mode = 'cmd';
write('250 OK\r\n');
return;
}
while (true) {
const nl = buf.indexOf('\n');
if (nl === -1) break;
const line = buf.slice(0, nl).replace(/\r$/, '');
buf = buf.slice(nl + 1);
if (loginStep > 0 && /^[A-Za-z0-9+/=]+$/.test(line)) {
sink.commands.push('(b64)');
} else if (line.startsWith('AUTH PLAIN ')) {
sink.commands.push('AUTH PLAIN');
} else {
sink.commands.push(line);
}
if (line.toUpperCase().startsWith('EHLO')) {
const extra = opts.starttls ? '250-STARTTLS\r\n' : '';
write(`250-mock\r\n${extra}250 AUTH ${opts.mechs ?? 'PLAIN LOGIN'}\r\n`);
} else if (line.toUpperCase() === 'STARTTLS' && opts.starttls && socket instanceof net.Socket) {
write('220 Go ahead\r\n');
socket.removeAllListeners('data');
const tlsSock = new tls.TLSSocket(socket, { isServer: true, cert: CERT, key: KEY });
attachSession(tlsSock, { ...opts, starttls: false }, sink, false);
return;
} else if (line.toUpperCase() === 'AUTH LOGIN') {
loginStep = 1;
write('334 VXNlcm5hbWU6\r\n');
} else if (line.toUpperCase().startsWith('AUTH PLAIN')) {
write(opts.failAuth ? '535 5.7.8 auth failed\r\n' : '235 2.7.0 OK\r\n');
} else if (loginStep === 1 && /^[A-Za-z0-9+/=]+$/.test(line)) {
loginStep = 2;
write('334 UGFzc3dvcmQ6\r\n');
} else if (loginStep === 2 && /^[A-Za-z0-9+/=]+$/.test(line)) {
loginStep = 0;
write(opts.failAuth ? '535 5.7.8 auth failed\r\n' : '235 2.7.0 OK\r\n');
} else if (line.toUpperCase().startsWith('MAIL FROM:')) {
write('250 OK\r\n');
} else if (line.toUpperCase().startsWith('RCPT TO:')) {
write('250 OK\r\n');
} else if (line.toUpperCase() === 'DATA') {
mode = 'data';
write('354 End data with <CR><LF>.<CR><LF>\r\n');
} else if (line.toUpperCase() === 'QUIT') {
write('221 bye\r\n');
socket.end();
} else {
write('250 OK\r\n');
}
}
});
}
function listenMock(opts: MockOptions = {}): Promise<MockSmtp> {
return new Promise((resolve, reject) => {
const sink: MockSmtp = { port: 0, commands: [], data: '', close: async () => undefined };
const onConn = (socket: net.Socket | tls.TLSSocket) => attachSession(socket, opts, sink);
const server = opts.secure
? tls.createServer({ cert: CERT, key: KEY }, onConn)
: net.createServer(onConn);
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
const addr = server.address();
if (!addr || typeof addr === 'string') {
reject(new Error('no port'));
return;
}
sink.port = addr.port;
sink.close = () => new Promise((res) => server.close(() => res()));
closers.push(sink.close);
resolve(sink);
});
});
}
describe('address helpers', () => {
it('extracts a bare or angled address and rejects junk', () => {
expect(extractAddress('bot@qq.com')).toBe('bot@qq.com');
expect(extractAddress('SnowLuma <bot@qq.com>')).toBe('bot@qq.com');
expect(extractAddress('not-an-email')).toBeNull();
expect(extractAddress('')).toBeNull();
});
it('parses unique recipients from mixed separators', () => {
expect(parseRecipients('a@x.com; b@x.com, a@x.com\nc@x.com')).toEqual([
'a@x.com',
'b@x.com',
'c@x.com',
]);
expect(parseRecipients('nope, also nope')).toEqual([]);
});
});
describe('buildMimeMessage', () => {
const base = {
host: 'smtp.example.com',
port: 465,
secure: true,
from: 'SnowLuma <bot@example.com>',
to: ['ops@example.com'],
subject: '账号offline:Alice (1)',
body: 'hello',
};
it('encodes a non-ASCII subject and a plain body as base64', () => {
const raw = buildMimeMessage(base, new Date('2026-09-16T01:00:00Z'));
expect(raw).toContain('Content-Type: text/plain; charset=UTF-8');
expect(raw).toContain('Subject: =?UTF-8?B?');
expect(raw).toContain(Buffer.from('hello', 'utf8').toString('base64'));
expect(raw).toContain('From: SnowLuma <bot@example.com>');
});
it('marks a body that starts with < as HTML', () => {
const raw = buildMimeMessage({ ...base, body: '<p>hi</p>' });
expect(raw).toContain('Content-Type: text/html; charset=UTF-8');
});
});
describe('formatSmtpError', () => {
it('maps connect failures and 535 without leaking the exception class name only', () => {
expect(formatSmtpError(new SmtpError('x', { code: 'ECONNREFUSED' }), 'smtp.qq.com', 465))
.toBe('无法连接 SMTP:smtp.qq.com:465');
expect(formatSmtpError(new SmtpError('AUTH failed: 535', { responseCode: 535 }), 'h', 25))
.toBe('SMTP 认证失败');
expect(formatSmtpError(new SmtpError('MAIL FROM failed: 550 denied', { responseCode: 550 }), 'h', 25))
.toBe('MAIL FROM failed: 550 denied');
});
});
describe('sendSmtpMail — live mock', () => {
const mail = {
host: '127.0.0.1',
from: 'bot@example.com',
to: ['ops@example.com'],
subject: 'offline',
body: '账号下线',
user: 'bot@example.com',
pass: 'secret',
};
it('delivers over AUTH PLAIN on a plaintext socket', async () => {
const mock = await listenMock({ mechs: 'PLAIN' });
await sendSmtpMail({ ...mail, port: mock.port, secure: false });
expect(mock.commands).toContain('AUTH PLAIN');
expect(mock.commands.some((c) => c.startsWith('MAIL FROM:<bot@example.com>'))).toBe(true);
expect(mock.commands.some((c) => c.startsWith('RCPT TO:<ops@example.com>'))).toBe(true);
expect(mock.data).toContain('Subject: offline');
expect(mock.data).toContain(Buffer.from('账号下线', 'utf8').toString('base64'));
expect(mock.commands.join('\n')).not.toContain('secret');
});
it('falls back to AUTH LOGIN when PLAIN is not advertised', async () => {
const mock = await listenMock({ mechs: 'LOGIN' });
await sendSmtpMail({ ...mail, port: mock.port, secure: false });
expect(mock.commands).toContain('AUTH LOGIN');
expect(mock.data).toContain('Subject: offline');
});
it('rejects 535 without sending DATA', async () => {
const mock = await listenMock({ mechs: 'PLAIN', failAuth: true });
await expect(sendSmtpMail({ ...mail, port: mock.port, secure: false }))
.rejects.toMatchObject({ name: 'SmtpError', responseCode: 535 });
expect(mock.data).toBe('');
});
it('upgrades via STARTTLS then authenticates', async () => {
const mock = await listenMock({ starttls: true, mechs: 'PLAIN' });
await sendSmtpMail(
{ ...mail, port: mock.port, secure: false },
{ rejectUnauthorized: false },
);
expect(mock.commands).toContain('STARTTLS');
expect(mock.commands).toContain('AUTH PLAIN');
expect(mock.data).toContain('Subject: offline');
});
it('speaks implicit TLS when secure=true', async () => {
const mock = await listenMock({ secure: true, mechs: 'PLAIN' });
await sendSmtpMail(
{ ...mail, port: mock.port, secure: true },
{ rejectUnauthorized: false },
);
expect(mock.commands).toContain('AUTH PLAIN');
expect(mock.data).toContain('Subject: offline');
});
});
@@ -1,101 +0,0 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { RoutingHead, SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { NTV2C2CUserInfo, NTV2UploadRichMediaReq, NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { describe, expect, it, vi } from 'vitest';
import { Bridge } from '../src/bridge/bridge';
const png = 'base64://iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jFZkAAAAASUVORK5CYII=';
function fixture(rejectUpload = false) {
const requests: Array<{ command: string; body: Uint8Array }> = [];
class TestBridge extends Bridge {
override async resolveUserUid(): Promise<string> { return 'u_peer'; }
override async sendRawPacket(command: string, body: Uint8Array): Promise<SendPacketResult> {
requests.push({ command, body });
let response: Uint8Array;
if (command === 'OidbSvcTrpcTcp.0x11c5_100') {
response = protobuf_encode<OidbBase<NTV2UploadRichMediaResp>>({
command: 0x11c5, subCommand: 100,
errorCode: rejectUpload ? 170019003 : 0,
errorMsg: rejectUpload ? 'verify identify fail' : '',
body: { upload: { msgInfo: { msgInfoBody: [{ index: { fileUuid: 'cached-image' } }] } } },
});
} else if (command === 'MessageSvc.PbSendMsg') {
response = protobuf_encode<SendMessageResponse>({ result: 0, privateSequence: 88 });
} else {
throw new Error(`unexpected packet: ${command}`);
}
return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.from(response) };
}
}
return { bridge: new TestBridge(IdentityService.memory('10000')), requests };
}
describe('passive temp-session image wire request (#471)', () => {
it('uses the same existing-session route for image upload and the final message', async () => {
const { bridge, requests } = fixture();
await bridge.apis.message.sendGroupTempMessage(1001, 700, [
{ type: 'text', text: 'reply' },
{ type: 'image', url: png },
]);
expect(requests.map((r) => r.command)).toEqual([
'OidbSvcTrpcTcp.0x11c5_100', 'MessageSvc.PbSendMsg',
]);
const upload = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(requests[0]!.body).body!;
expect(upload.reqHead?.scene).toMatchObject({
sceneType: 1, businessType: 1, c2c: { accountType: 2, targetUid: 'u_peer' },
});
expect(upload.reqHead?.scene?.group ?? undefined).toBeUndefined();
const route = upload.reqHead!.scene!.c2c!.routingHead!;
expect(Array.from(route)).toEqual([
0x1a, 0x0b, 0x18, 0xbc, 0x05, 0x22, 0x06, 0x75, 0x5f, 0x70, 0x65, 0x65, 0x72,
]);
expect(Array.from(protobuf_encode<NTV2C2CUserInfo>(upload.reqHead!.scene!.c2c!))).toEqual([
0x08, 0x02, 0x12, 0x06, 0x75, 0x5f, 0x70, 0x65, 0x65, 0x72,
0x1a, 0x0d, 0x1a, 0x0b, 0x18, 0xbc, 0x05, 0x22, 0x06, 0x75, 0x5f, 0x70, 0x65, 0x65, 0x72,
]);
const sent = protobuf_decode<SendMessageRequest>(requests[1]!.body);
expect(protobuf_decode<RoutingHead>(route)).toEqual(sent.routingHead);
expect(sent.routingHead?.grpTmp).toEqual({ groupUin: 700n, toUid: 'u_peer' });
expect(sent.messageBody?.richText?.elems).toEqual([
expect.objectContaining({ text: expect.objectContaining({ str: 'reply' }) }),
expect.objectContaining({ commonElem: expect.objectContaining({ serviceType: 48, businessType: 10 }) }),
]);
});
it('keeps normal private image uploads free of temp-session context', async () => {
const { bridge, requests } = fixture();
await bridge.apis.message.sendPrivate(1001, [{ type: 'image', url: png }]);
const upload = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(requests[0]!.body).body!;
expect(upload.reqHead?.scene?.c2c?.routingHead ?? undefined).toBeUndefined();
const sent = protobuf_decode<SendMessageRequest>(requests[1]!.body);
expect(sent.routingHead?.grpTmp ?? undefined).toBeUndefined();
});
it('propagates upload rejection without sending text or retrying as another conversation', async () => {
const { bridge, requests } = fixture(true);
await expect(bridge.apis.message.sendGroupTempMessage(1001, 700, [
{ type: 'text', text: 'must not be sent separately' },
{ type: 'image', url: png },
])).rejects.toThrow('verify identify fail');
expect(requests.map((r) => r.command)).toEqual(['OidbSvcTrpcTcp.0x11c5_100']);
});
it('rejects missing source context before reading the image or sending any packet', async () => {
const { bridge, requests } = fixture();
const fetch = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('must not download image'));
try {
await expect(buildSendElems([{ type: 'image', url: 'https://must-not-fetch.invalid/image.png' }], {
bridge, scene: 'group-temp', userUid: 'u_peer',
})).rejects.toThrow('temp-session image source group is missing');
expect(fetch).not.toHaveBeenCalled();
expect(requests).toEqual([]);
} finally { fetch.mockRestore(); }
});
});
@@ -1,42 +0,0 @@
import { describe, it, expect } from 'vitest';
import type { OneBotManager } from '@snowluma/onebot/manager';
import { checkListenerExposure, isValidBindHost } from '../src/webui/listener-exposure';
import { initWebUI } from '../src/webui/server';
describe('isValidBindHost', () => {
it('accepts loopback, all-interfaces, and IPv6 any', () => {
expect(isValidBindHost('127.0.0.1')).toBe(true);
expect(isValidBindHost('0.0.0.0')).toBe(true);
expect(isValidBindHost('::')).toBe(true);
expect(isValidBindHost('localhost')).toBe(true);
});
it('rejects spaces, underscores, and malformed IPv6 zone ids', () => {
expect(isValidBindHost('bad host')).toBe(false);
expect(isValidBindHost('not_a_host')).toBe(false);
expect(isValidBindHost('::1%bad%extra')).toBe(false);
expect(isValidBindHost(' 127.0.0.1')).toBe(false);
});
});
describe('checkListenerExposure', () => {
it('requires a usable pair only when TLS is on', () => {
expect(checkListenerExposure({ webuiHost: '127.0.0.1', tlsEnabled: false, pairOk: false })).toEqual({ ok: true });
expect(checkListenerExposure({ webuiHost: '127.0.0.1', tlsEnabled: true, pairOk: false })).toEqual({
ok: false,
code: 'tls-pair-required',
});
});
});
describe('initWebUI boot', () => {
it('fails before listen when the bind host is invalid', async () => {
await expect(initWebUI(
5099,
{} as OneBotManager,
undefined,
undefined,
{ host: 'not_a_host' },
)).rejects.toThrow(/bind host is not a valid TCP address/);
});
});
@@ -43,7 +43,7 @@ describe('createStateWiring', () => {
expect(sub).toHaveBeenNthCalledWith(2, 'connections');
});
it('dispose() latches so later Hook/Bridge edges publish nothing', () => {
it('dispose() unwires onSessionsChanged + BridgeManager listeners (no further publishes)', () => {
const wiring = createStateWiring();
const bm = new BridgeManager();
wiring.bindBridgeManager(bm);
@@ -1,10 +1,5 @@
import { describe, it, expect } from 'vitest';
import {
coerceSettingsPatch,
evaluateSettingsSave,
tlsCertDeletionBlocked,
} from '../src/webui/system-settings';
import type { RuntimeConfig } from '@snowluma/common/runtime';
import { coerceSettingsPatch } from '../src/webui/system-settings';
describe('coerceSettingsPatch', () => {
it('accepts a full valid body and maps tlsEnabled → webuiTls.enabled', () => {
@@ -42,56 +37,3 @@ describe('coerceSettingsPatch', () => {
expect(coerceSettingsPatch({ trustProxy: '' })).toEqual({ ok: true, patch: { trustProxy: '' } });
});
});
describe('evaluateSettingsSave', () => {
const current: RuntimeConfig = {
webuiPort: 5099,
webuiHost: '127.0.0.1',
webuiTls: { enabled: false },
};
it('rejects an invalid bind host on the patch', () => {
const r = evaluateSettingsSave(current, { webuiHost: 'not_a_host' }, true);
expect(r.ok).toBe(false);
if (!r.ok) expect(r.error).toMatch(/TCP/);
});
it('rejects saving an unrelated field when the persisted host is invalid', () => {
const r = evaluateSettingsSave(
{ ...current, webuiHost: 'not_a_host' },
{ webuiPort: 8080 },
true,
);
expect(r.ok).toBe(false);
});
it('rejects enabling TLS without a usable certificate pair', () => {
const r = evaluateSettingsSave(current, { webuiTls: { enabled: true } }, false);
expect(r).toEqual({ ok: false, error: '启用 TLS 前请先上传有效的证书与私钥' });
});
it('rejects leaving TLS enabled when the pair is already missing', () => {
const r = evaluateSettingsSave(
{ ...current, webuiTls: { enabled: true } },
{ webuiPort: 8080 },
false,
);
expect(r.ok).toBe(false);
});
it('allows disabling TLS even without a pair', () => {
const r = evaluateSettingsSave(
{ ...current, webuiTls: { enabled: true } },
{ webuiTls: { enabled: false } },
false,
);
expect(r).toEqual({ ok: true, patch: { webuiTls: { enabled: false } } });
});
});
describe('tlsCertDeletionBlocked', () => {
it('blocks deletion while TLS is enabled and allows it when TLS is off', () => {
expect(tlsCertDeletionBlocked(true)).toBe(true);
expect(tlsCertDeletionBlocked(false)).toBe(false);
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.14.22",
"version": "1.14.10",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.14.22",
"version": "1.14.10",
"private": true,
"type": "module",
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
+3 -4
View File
@@ -4,9 +4,8 @@
// structured doc list + a Markdown view. The metadata is carried on the same
// values that drive runtime validation, so docs cannot drift from behavior.
//
// The reserved `.handle_quick_operation` raw handler (and its `_async` alias)
// deliberately has no ActionSpec/doc entry; every catalogued action comes
// from ACTION_REGISTRY.
// The reserved `.handle_quick_operation` raw handler deliberately has no
// ActionSpec/doc entry; every catalogued action comes from ACTION_REGISTRY.
//
// The serving SURFACE (WebUI panel / OpenAPI export / static markdown) is a
// deferred product decision; this module produces format-agnostic data plus a
@@ -59,7 +58,7 @@ export function renderActionDocsMarkdown(docs: readonly ActionDoc[] = collectAct
'# OneBot Actions',
'',
'> 由 `packages/onebot/src/action-docs.ts` 从各 `ActionSpec.describe()` 自动生成,请勿手改。',
'> 覆盖完整声明式 Action registry;保留的 raw `.handle_quick_operation` / `.handle_quick_operation_async` handler 不生成文档。',
'> 覆盖完整声明式 Action registry;保留的 raw `.handle_quick_operation` handler 不生成文档。',
'',
`共 ${docs.length} 个声明式 action。`,
'',
+9 -5
View File
@@ -483,7 +483,11 @@ interface ActionDef<S extends Spec> {
readOnly?: boolean;
params: S;
rules?: (r: RuleBuilders<InferParams<S>>) => readonly CrossFieldRule[];
run: (p: InferParams<S>, ctx: ApiActionContext) => Promise<ApiResponse> | ApiResponse;
/** `raw` is the original untouched params — an escape hatch for the
* irregular tail (alias-key fallbacks, arbitrary nested objects). Declared
* fields in `p` remain the validated path; reach for `raw` only for keys
* the spec can't express. */
run: (p: InferParams<S>, ctx: ApiActionContext, raw: JsonObject) => Promise<ApiResponse> | ApiResponse;
}
const wording = (e: Err): string => (e.field ? `${e.field}: ${e.reason}` : e.reason);
@@ -513,7 +517,7 @@ export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
const toHandler = (ctx: ApiActionContext): Handler => async (params: JsonObject) => {
const r = parse(params);
if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r));
return def.run(r.value, ctx);
return def.run(r.value, ctx, params);
};
return {
@@ -567,7 +571,7 @@ interface StreamActionDef<S extends Spec> {
readOnly?: boolean;
params: S;
rules?: (r: RuleBuilders<InferParams<S>>) => readonly CrossFieldRule[];
run: (p: InferParams<S>, ctx: ApiActionContext, sink: StreamSink) => Promise<ApiResponse> | ApiResponse;
run: (p: InferParams<S>, ctx: ApiActionContext, raw: JsonObject, sink: StreamSink) => Promise<ApiResponse> | ApiResponse;
}
export interface StreamActionSpec<S extends Spec> extends RegisteredActionSpec {
@@ -595,7 +599,7 @@ export function defineStreamAction<S extends Spec>(def: StreamActionDef<S>): Str
const toHandler = (ctx: ApiActionContext): Handler => async (params, sink) => {
const r = base.parse(params);
if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r));
return def.run(r.value, ctx, sink ?? NOOP_SINK);
return def.run(r.value, ctx, params, sink ?? NOOP_SINK);
};
return {
@@ -624,7 +628,7 @@ interface PresetDef<S extends Spec, Extra> {
readOnly?: boolean;
params?: S;
rules?: (r: RuleBuilders<InferParams<S> & Extra>) => readonly CrossFieldRule[];
run: (p: InferParams<S> & Extra, ctx: ApiActionContext) => Promise<ApiResponse> | ApiResponse;
run: (p: InferParams<S> & Extra, ctx: ApiActionContext, raw: JsonObject) => Promise<ApiResponse> | ApiResponse;
}
/** Pre-seeds `group_id` (uint, required). */
+84 -258
View File
@@ -1,4 +1,3 @@
import { positiveIntEnv } from '@snowluma/common/env';
import { readFile } from 'node:fs/promises';
import { FriendDressError } from '@snowluma/protocol/web/friend-dress';
import { formatGroupRequestFlag } from '@snowluma/protocol/qq-info';
@@ -7,6 +6,7 @@ import type {
GroupEssenceMessage,
} from '@snowluma/protocol/web/group-essence';
import type { ApiActionContext } from '../api-handler';
import { asNumber, asString } from '../api-handler';
import type { ForwardPreviewMeta } from '../modules/message-actions';
import {
hasAuthoritativeSequence,
@@ -14,19 +14,14 @@ import {
failedResponse,
okResponse,
type JsonObject,
type JsonValue,
type MessageMeta,
} from '../types';
import { defineAction, groupAction, groupUserAction, f, type Field } from '../action-kit';
import { defineAction, groupAction, groupUserAction, f } from '../action-kit';
import { groupInfoReturnsSchema } from './group-info';
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB
const DEFAULT_DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
function downloadFileTimeoutMs(): number {
return positiveIntEnv('SNOWLUMA_DOWNLOAD_FILE_TIMEOUT_MS', DEFAULT_DOWNLOAD_FILE_TIMEOUT_MS);
}
const DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
const profileLikeUserSchema = {
type: 'object',
@@ -91,33 +86,6 @@ function essenceString(value: unknown, field: string, allowEmpty: boolean): stri
return value;
}
function optionalEssenceText(value: unknown): string | undefined {
if (typeof value !== 'string') return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
/** Unknown digest types (share cards, future msg_type values) degrade to
* text so one unmapped item cannot fail the whole essence list. */
function degradeEssenceContent(content: GroupEssenceContent): JsonObject {
const brief = optionalEssenceText(content.share_brief);
const title = optionalEssenceText(content.share_title);
const summary = optionalEssenceText(content.share_summary);
const url = optionalEssenceText(content.share_url);
const text = optionalEssenceText(content.text);
const heading = brief ?? title ?? summary ?? text;
const parts: string[] = [];
if (heading) parts.push(heading);
if (title && title !== heading) parts.push(title);
if (summary && summary !== heading && summary !== title) parts.push(summary);
if (text && text !== heading) parts.push(text);
if (url) parts.push(url);
return {
type: 'text',
data: { text: parts.length > 0 ? parts.join('\n') : `[essence type ${content.msg_type}]` },
};
}
function essenceContentToSegment(content: GroupEssenceContent): JsonObject {
switch (content.msg_type) {
case 1:
@@ -168,7 +136,7 @@ function essenceContentToSegment(content: GroupEssenceContent): JsonObject {
};
}
default:
return degradeEssenceContent(content);
throw new Error(`unsupported group essence content type: ${content.msg_type}`);
}
}
@@ -294,57 +262,19 @@ async function saveDownloadBuffer(buf: Buffer, preferredName: string): Promise<s
return resolved;
}
function optionalExactString(): Field<string | undefined> {
const inner = f.string().optional();
return Object.assign(Object.create(inner) as Field<string | undefined>, {
coerce(raw: unknown, field: string) {
if (typeof raw === 'number' || typeof raw === 'boolean' || raw === null
|| (typeof raw === 'object' && raw !== null)) {
return { ok: false as const, field, reason: 'expected a string' };
}
return inner.coerce(raw as Parameters<Field<string | undefined>['coerce']>[0], field);
},
});
}
function integerFromDecimalString(value: string): number {
if (value.trim() === '') return 0;
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
function primitiveText(value: unknown): string {
if (typeof value === 'string') return value;
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
return '';
}
const forwardPreviewParams = {
source: f.string().optional(),
summary: f.string().optional(),
prompt: f.string().optional(),
news: f.raw(),
};
// NapCat-compatible forward preview. All four fields are optional — if none
// are provided, the message module infers defaults from the node list.
function readForwardPreviewMeta(p: {
source?: string;
summary?: string;
prompt?: string;
news?: JsonValue;
}): ForwardPreviewMeta | undefined {
const source = p.source || undefined;
const summary = p.summary || undefined;
const prompt = p.prompt || undefined;
// 从 send_*_forward_msg 的参数里提取 NapCat 兼容的转发预览元信息。四个字段都是可选的——如果没有提供,模块层会根据实际消息节点列表推断出合理的默认值。
function readForwardPreviewMeta(params: Record<string, unknown>): ForwardPreviewMeta | undefined {
const source = asString(params.source) || undefined;
const summary = asString(params.summary) || undefined;
const prompt = asString(params.prompt) || undefined;
let news: Array<{ text: string }> | undefined;
if (Array.isArray(p.news)) {
if (Array.isArray(params.news)) {
const collected: Array<{ text: string }> = [];
for (const item of p.news) {
for (const item of params.news) {
if (typeof item === 'string') {
collected.push({ text: item });
} else if (item && typeof item === 'object' && !Array.isArray(item)) {
const text = primitiveText((item as Record<string, unknown>).text);
const text = asString((item as Record<string, unknown>).text);
if (text) collected.push({ text });
}
}
@@ -758,7 +688,7 @@ export const actions = [
groupAction({
name: '_get_group_notice',
summary: '获取群公告',
returns: '普通公告与新成员公告的合并数组;send_to_new_members 标识后者;图片含 id、url、宽高',
returns: '普通公告与新成员公告的合并数组;send_to_new_members 标识后者',
readOnly: true,
run: async (p, ctx) => {
const notices = await ctx.bridge.apis.web.getNotice(p.group_id);
@@ -871,10 +801,13 @@ export const actions = [
required: ['text'],
},
params: {
message_id: f.messageId(),
message_id: f.string().default('').role('message_id'),
},
run: async (p, ctx) => {
return okResponse(await ctx.fetchPttText(p.message_id));
// `raw` so message_id works whether the client sends a number or a string.
run: async (_p, ctx, raw) => {
const messageId = asNumber(raw.message_id);
if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
return okResponse(await ctx.fetchPttText(messageId));
},
}),
@@ -1063,10 +996,12 @@ export const actions = [
params: {
nickname: f.string().optional(),
personal_note: f.string().optional(),
sex: f.int({ min: 0, max: 2 }).optional().describe('0 未知,1 男,2 女'),
},
run: async (p, ctx) => {
await ctx.bridge.apis.profile.setProfile(p.nickname, p.personal_note, p.sex);
const nickname = p.nickname;
const personalNote = p.personal_note;
await ctx.bridge.apis.profile.setProfile(nickname, personalNote);
return okResponse();
},
}),
@@ -1333,10 +1268,15 @@ export const actions = [
return_type: f.string().default('url'),
},
run: async (p, ctx) => {
const urls = await ctx.bridge.apis.profile.fetchCustomFace(p.count);
if (p.return_type === 'id') {
return okResponse(await ctx.bridge.apis.profile.fetchCustomFaceIds(p.count));
const emojiIds = urls.map((url) => {
const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url);
return m ? m[1] : '';
}).filter(Boolean);
return okResponse(emojiIds);
}
return okResponse(await ctx.bridge.apis.profile.fetchCustomFace(p.count));
return okResponse(urls);
},
}),
@@ -1460,41 +1400,6 @@ export const actions = [
},
}),
defineAction({
name: 'get_msg_emoji_likes',
summary: '获取一条消息的全部表情回应',
readOnly: true,
returns: '该消息上每个表情回应的编号、数量与用户列表。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
emoji_id: { type: 'string', description: '表情编号' },
emoji_type: { type: 'integer', description: '表情类型' },
count: { type: 'integer', description: '回应数量' },
last_reaction_time: { type: 'integer', description: '最近一次回应时间' },
users: {
type: 'array',
items: {
type: 'object',
properties: { user_id: { type: 'integer', description: '用户 QQ 号' } },
required: ['user_id'],
},
},
},
required: ['emoji_id', 'emoji_type', 'count', 'last_reaction_time', 'users'],
},
},
params: { message_id: f.messageId() },
run: async (p, ctx) => {
if (!ctx.fetchEmojiLikeSummary) {
return failedResponse(RETCODE.ACTION_FAILED, 'emoji reaction summary is unavailable');
}
return okResponse(await ctx.fetchEmojiLikeSummary(p.message_id));
},
}),
defineAction({
name: 'get_friends_with_category',
summary: '获取分组好友列表',
@@ -1801,55 +1706,6 @@ export const actions = [
},
}),
// send_tuwen_ark — send a custom 图文 (URL-share) ark card to a C2C peer or group (0xdc2_34).
// targetId at AppInfo[11] and Meta[2]; Meta.peerType: 0=C2C, 1=group.
// 与 send_ark_share 的区别:send_ark_share 只获取推荐联系人 JSON 不发送;
// 与 send_msg share/json 的区别:后者发送 structmsg 图文卡且有 message_id,
// 本 action 发送固定图文 ark 模板,返回 null(无法用于撤回/设精华)。
defineAction({
name: 'send_tuwen_ark',
summary: '发送图文 Ark 卡片(私聊/群聊)',
readOnly: false,
returns: 'null',
returnsSchema: { type: 'null' },
params: {
user_id: f.userId().optional(),
group_id: f.groupId().optional(),
title: f.string(),
desc: f.string(),
summary: f.string().default('[分享]'),
preview_url: f.string().default('https://tangram-1251316161.file.myqcloud.com/files/20210721/e50a8e37e08f29bf1ffc7466e1950690.png'),
jump_url: f.string(),
},
run: async (p, ctx) => {
if (p.group_id) {
await ctx.bridge.apis.contacts.sendTuwenArk({
targetId: p.group_id,
peerType: 1,
title: p.title,
desc: p.desc,
summary: p.summary,
previewUrl: p.preview_url,
jumpUrl: p.jump_url,
});
return okResponse(null);
}
if (p.user_id) {
await ctx.bridge.apis.contacts.sendTuwenArk({
targetId: p.user_id,
peerType: 0,
title: p.title,
desc: p.desc,
summary: p.summary,
previewUrl: p.preview_url,
jumpUrl: p.jump_url,
});
return okResponse(null);
}
return failedResponse(RETCODE.BAD_REQUEST, 'user_id or group_id is required');
},
}),
// share_group_ex / send_group_ark_share — group-only Ark share. NapCat uses
// a distinct kernel API (getArkJsonGroupShare) we did NOT RE; we route to
// the fully-RE'd group recommend-contact ark (0x8b7_5), the closest
@@ -1890,15 +1746,12 @@ export const actions = [
type: 'object',
properties: {
uid: { type: 'string', description: '申请人 uid(回传作 set_doubt_friends_add_request 的 flag)' },
user_id: { type: 'integer', description: '申请人 QQ 号' },
nick: { type: 'string', description: '申请人昵称' },
source: { type: 'string', description: '申请来源' },
reason: { type: 'string', description: '附加说明' },
msg: { type: 'string', description: '验证留言' },
group_code: { type: 'string', description: '来源群号,无则为空串' },
reqTime: { type: 'integer', description: '申请时间戳' },
},
required: ['uid', 'user_id', 'nick', 'source', 'reason', 'msg', 'group_code', 'reqTime'],
required: ['uid', 'nick', 'source', 'msg', 'reqTime'],
},
},
params: { count: f.int({ min: 0 }).default(50) },
@@ -1907,8 +1760,10 @@ export const actions = [
return okResponse(list);
},
}),
// Accept the list UID or resolve the applicant's account number.
// Approval and rejection use their respective friend API operations.
// set_doubt_friends_add_request — handle a 可疑好友申请 (0xd69_0). `flag` is
// the uid from the get list. approve → approvalDoubtBuddyReq; approve:false
// → delDoubtBuddyReq (reject/decline). NapCat only ever approves; we add the
// reject path since we RE'd delDoubtBuddyReq too.
defineAction({
name: 'set_doubt_friends_add_request',
summary: '处理可疑好友申请',
@@ -1917,6 +1772,8 @@ export const actions = [
approve: f.bool().default(true),
},
run: async (p, ctx) => {
// approve → approvalDoubtBuddyReq (0xd69_0); reject → delDoubtBuddyReq
// (also 0xd69_0, distinct body) — both RE'd from the binary.
if (p.approve) {
await ctx.bridge.apis.friend.approveDoubtRequest(p.flag);
} else {
@@ -2331,7 +2188,8 @@ export const actions = [
},
}),
// ===== 原 legacy registerAction,现并入 kit =====
// ===== 原 legacy registerAction,现并入 kit(ctx 调用与逻辑逐字保留;
// 别名键 / 原始参数透传 / 任意对象经 run 第三参 raw 或 f.raw() 表达)=====
defineAction({
name: ['get_rkey', 'nc_get_rkey'],
@@ -2469,22 +2327,16 @@ export const actions = [
name: 'send_forward_msg',
summary: '发送合并转发(按 message_type/群号自动路由)',
returns: '{ message_id, res_id, forward_id }',
// group_id/user_id are routing hints, not identity: 0 means "this branch
// does not apply" and must not error. int({min:0}) optional, not groupId.
params: {
messages: f.message().optional(),
message: f.message().optional(),
message_type: f.string().optional(),
group_id: f.int({ min: 0 }).optional(),
user_id: f.int({ min: 0 }).optional(),
...forwardPreviewParams,
},
run: async (p, ctx) => {
const messageType = p.message_type ?? '';
const groupId = p.group_id ?? 0;
const userId = p.user_id ?? 0;
// group_id/user_id 是“路由提示”而非身份字段:原实现用 asNumber + `>0` 判断,
// 占位的 0 表示“该分支不适用”、不应报错。故从 raw 读取(保持旧语义),
// 只声明 messages/message。
params: { messages: f.message().optional(), message: f.message().optional() },
run: async (p, ctx, raw) => {
const messageType = asString(raw.message_type);
const groupId = asNumber(raw.group_id);
const userId = asNumber(raw.user_id);
const messages = p.messages ?? p.message;
const meta = readForwardPreviewMeta(p);
const meta = readForwardPreviewMeta(raw);
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
if ((messageType === 'group' || groupId > 0) && ctx.sendGroupForwardMsg) {
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
@@ -2505,15 +2357,11 @@ export const actions = [
name: 'send_group_forward_msg',
summary: '发送群合并转发',
returns: '{ message_id, res_id, forward_id }',
params: {
messages: f.message().optional(),
message: f.message().optional(),
...forwardPreviewParams,
},
run: async (p, ctx) => {
params: { messages: f.message().optional(), message: f.message().optional() },
run: async (p, ctx, raw) => {
const messages = p.messages ?? p.message;
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
const result = await ctx.sendGroupForwardMsg(p.group_id, messages, readForwardPreviewMeta(p));
const result = await ctx.sendGroupForwardMsg(p.group_id, messages, readForwardPreviewMeta(raw));
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
},
}),
@@ -2522,16 +2370,11 @@ export const actions = [
name: 'send_private_forward_msg',
summary: '发送私聊合并转发',
returns: '{ message_id, res_id, forward_id }',
params: {
user_id: f.userId(),
messages: f.message().optional(),
message: f.message().optional(),
...forwardPreviewParams,
},
run: async (p, ctx) => {
params: { user_id: f.userId(), messages: f.message().optional(), message: f.message().optional() },
run: async (p, ctx, raw) => {
const messages = p.messages ?? p.message;
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
const result = await ctx.sendPrivateForwardMsg(p.user_id, messages, readForwardPreviewMeta(p));
const result = await ctx.sendPrivateForwardMsg(p.user_id, messages, readForwardPreviewMeta(raw));
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
},
}),
@@ -2548,11 +2391,12 @@ export const actions = [
},
required: ['messages'],
},
params: { id: f.string().optional(), message_id: f.string().optional() },
run: async (p, ctx) => {
params: { id: f.string().optional() },
run: async (p, ctx, raw) => {
let id = p.id || '';
if (!id && p.message_id !== undefined) {
const numericMessageId = integerFromDecimalString(p.message_id);
if (!id) {
const rawMessageId = raw.message_id;
const numericMessageId = asNumber(rawMessageId);
if (numericMessageId > 0) {
const event = ctx.getMessage(numericMessageId);
const segments = Array.isArray(event?.message) ? event.message : [];
@@ -2563,11 +2407,11 @@ export const actions = [
const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data))
? so.data as Record<string, unknown>
: null;
const candidate = primitiveText(data?.id) || primitiveText(data?.res_id) || primitiveText(data?.forward_id);
const candidate = asString(data?.id) || asString(data?.res_id) || asString(data?.forward_id);
if (candidate) { id = candidate; break; }
}
}
if (!id) id = p.message_id;
if (!id) id = asString(rawMessageId);
}
if (!id) return failedResponse(RETCODE.BAD_REQUEST, 'id or message_id is required');
const messages = await ctx.getForwardMsg(id);
@@ -2579,13 +2423,8 @@ export const actions = [
name: 'download_file',
summary: '下载文件(url 或 base64)到 data/downloads',
returns: '{ file }',
params: {
url: f.string().default(''),
base64: f.string().default(''),
name: f.string().default(''),
headers: f.raw(),
},
run: async (p) => {
params: { url: f.string().default(''), base64: f.string().default(''), name: f.string().default('') },
run: async (p, _ctx, raw) => {
const url = p.url;
const base64 = p.base64;
const name = p.name;
@@ -2597,7 +2436,7 @@ export const actions = [
buf = Buffer.from(base64, 'base64');
if (buf.length > DOWNLOAD_FILE_MAX_BYTES) return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`);
} else {
buf = await fetchDownloadFile(url, parseDownloadHeaders(p.headers), DOWNLOAD_FILE_MAX_BYTES, downloadFileTimeoutMs());
buf = await fetchDownloadFile(url, parseDownloadHeaders(raw.headers), DOWNLOAD_FILE_MAX_BYTES, DOWNLOAD_FILE_TIMEOUT_MS);
}
try {
const safe = await saveDownloadBuffer(buf, name);
@@ -2620,9 +2459,12 @@ export const actions = [
},
required: ['words'],
},
params: { words: f.array(f.string()) },
params: { words: f.raw() },
run: async (p, ctx) => {
const translated = await ctx.bridge.apis.misc.translateEn2Zh(p.words);
const rawWords = p.words;
if (!Array.isArray(rawWords)) return failedResponse(RETCODE.BAD_REQUEST, 'invalid words array');
const words = rawWords.map((w) => String(w));
const translated = await ctx.bridge.apis.misc.translateEn2Zh(words);
return okResponse({ words: translated });
},
}),
@@ -2630,7 +2472,7 @@ export const actions = [
defineAction({
name: 'set_self_longnick',
summary: '设置个性签名(longNick/long_nick,严格 string)',
params: { longNick: optionalExactString(), long_nick: optionalExactString() },
params: { longNick: f.raw(), long_nick: f.raw() },
run: async (p, ctx) => {
const longNick = p.longNick !== undefined ? p.longNick : p.long_nick;
if (typeof longNick !== 'string') return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick');
@@ -2643,22 +2485,14 @@ export const actions = [
name: 'get_mini_app_ark',
summary: '获取小程序卡片 ark',
readOnly: true,
params: {
type: f.string().optional(),
title: f.string().optional(),
desc: f.string().optional(),
picUrl: f.string().optional(),
pic_url: f.string().optional(),
jumpUrl: f.string().optional(),
jump_url: f.string().optional(),
},
run: async (p, ctx) => {
const type = p.type || 'bili';
const title = p.title || '';
const desc = p.desc || '';
const picUrl = p.picUrl || p.pic_url || '';
const jumpUrl = p.jumpUrl || p.jump_url || '';
const data = await ctx.bridge.apis.misc.getMiniAppArk(type, title, desc, picUrl, jumpUrl);
params: {},
run: async (_p, ctx, raw) => {
const type = raw.type || 'bili';
const title = raw.title || '';
const desc = raw.desc || '';
const picUrl = raw.picUrl || raw.pic_url || '';
const jumpUrl = raw.jumpUrl || raw.jump_url || '';
const data = await ctx.bridge.apis.misc.getMiniAppArk(String(type), String(title), String(desc), String(picUrl), String(jumpUrl));
return okResponse(data);
},
}),
@@ -2666,20 +2500,12 @@ export const actions = [
groupAction({
name: 'click_inline_keyboard_button',
summary: '点击内联键盘按钮',
params: {
bot_appid: f.uint(),
msg_seq: f.uint(),
button_id: f.string({ allowEmpty: false }),
callback_data: f.string().default(''),
},
run: async (p, ctx) => {
const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton(
p.group_id,
p.bot_appid,
p.button_id,
p.callback_data,
p.msg_seq,
);
params: { bot_appid: f.uint(), msg_seq: f.uint() },
run: async (p, ctx, raw) => {
const buttonId = raw.button_id;
const callbackData = raw.callback_data || '';
if (!buttonId) return failedResponse(RETCODE.BAD_REQUEST, 'missing required parameters');
const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton(p.group_id, p.bot_appid, String(buttonId), String(callbackData), p.msg_seq);
return okResponse(data);
},
}),
+1 -18
View File
@@ -32,35 +32,18 @@ export const actions = [
name: 'get_stranger_info',
summary: '获取陌生人信息',
readOnly: true,
returns: '用户资料,含账号标识、等级别名和可用的注册时间、会员信息。注册时间或会员信息未返回时省略对应字段;登录天数暂无可靠来源,不返回占位值。',
returns: '用户资料:QQ 号、昵称、好友备注、性别、年龄与个性签名,命中资料时另含等级。',
returnsSchema: {
type: 'object',
properties: {
user_id: { type: 'integer', description: 'QQ 号' },
uid: { type: 'string', description: '账号唯一标识(仅查到资料时返回)' },
qid: { type: 'string', description: '自定义账号标识(仅查到资料时返回)' },
nickname: { type: 'string', description: '昵称' },
remark: { type: 'string', description: '好友备注;非好友或未设置时为空字符串' },
sex: { type: 'string', description: '性别(male/female/unknown)' },
age: { type: 'integer', description: '年龄' },
long_nick: { type: 'string', description: '个性签名' },
qq_level: { type: 'integer', description: 'QQ 等级(仅查到资料时返回)' },
qqLevel: { type: 'integer', description: 'QQ 等级,同 qq_level' },
reg_time: { type: 'integer', description: '注册时间戳(秒),不可用时省略' },
is_vip: { type: 'boolean', description: '超级会员状态,兼容 NapCat;不可用时省略' },
is_years_vip: { type: 'boolean', description: '年费会员状态,不可用时省略' },
vip_level: { type: 'integer', description: '会员等级,不可用时省略' },
level: { type: 'integer', description: 'QQ 等级,同 qq_level(仅查到资料时返回)' },
status: { type: 'integer', description: '在线状态码' },
extStatus: { type: 'integer', description: '扩展状态码' },
ext_status: { type: 'integer', description: '扩展状态码(同 extStatus)' },
batteryStatus: { type: 'integer', description: '电量状态' },
customStatus: { type: 'object', description: '自定义状态', nullable: true },
customStatusDescInfo: { type: 'string', description: '自定义状态说明' },
qidian_master_flag: { type: 'integer', description: '企点主号标志,0 或 1;普通账号为 0' },
qidian_crew_flag: { type: 'integer', description: '企点员工标志,0 或 1;普通账号为 0' },
qidian_crew_flag_2: { type: 'integer', description: '企点保留标志,0 或 1;普通账号为 0' },
qidian_enterprise_name: { type: 'string', description: '企点企业名称;非企点账号或未获取到时为空字符串' },
},
required: ['user_id', 'nickname', 'remark', 'sex', 'age', 'long_nick'],
},
+3 -108
View File
@@ -45,15 +45,9 @@ export const actions = [
groupAction({
name: 'set_group_add_option',
summary: '设置加群选项',
params: {
add_type: f.int({ min: 0 }).default(0),
group_question: f.string().optional(),
group_answer: f.string().optional(),
},
params: { add_type: f.int({ min: 0 }).default(0) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setAddOption(
p.group_id, p.add_type, p.group_question, p.group_answer,
);
await ctx.bridge.apis.groupAdmin.setAddOption(p.group_id, p.add_type);
return okResponse();
},
}),
@@ -100,7 +94,7 @@ export const actions = [
groupAction({
name: 'set_group_member_permissions',
summary: '设置群成员权限(仅群主可改)',
summary: '设置群成员权限',
params: {
allow_member_upload_album: f.bool().optional(),
allow_member_temporary_session: f.bool().optional(),
@@ -121,105 +115,6 @@ export const actions = [
},
}),
groupAction({
name: 'get_group_admin_settings',
summary: '获取群管理设置的当前值',
readOnly: true,
returns: '与对应设置接口字段对齐的当前群管理设置。',
returnsSchema: {
type: 'object',
properties: {
add_type: { type: 'integer', description: '加群选项(同 set_group_add_option.add_type)' },
group_question: { type: 'string', description: '加群问题(同 set_group_add_option.group_question)' },
group_answer: { type: 'string', description: '加群答案(同 set_group_add_option.group_answer)' },
robot_member_switch: { type: 'integer', description: '机器人加群开关(同 set_group_robot_add_option)' },
robot_member_examine: { type: 'integer', description: '机器人加群审核(同 set_group_robot_add_option)' },
member_invite_policy: {
type: 'string',
enum: ['disabled', 'require_approval', 'no_approval', 'no_approval_under_100'],
description: '成员邀请策略(同 set_group_member_invite_policy.policy)',
},
allow_member_upload_album: { type: 'boolean', description: '是否允许成员上传相册' },
allow_member_temporary_session: { type: 'boolean', description: '是否允许成员发起临时会话' },
allow_member_create_group: { type: 'boolean', description: '是否允许成员创建群聊' },
new_member_history_visible: { type: 'boolean', description: '新成员是否可查看历史消息' },
no_finger_open: { type: 'integer', description: '是否关闭群指纹/关键词搜索(0 开 1 关)' },
no_code_finger_open: { type: 'integer', description: '是否关闭群号搜索(0 开 1 关)' },
},
required: [
'add_type',
'group_question',
'group_answer',
'robot_member_switch',
'robot_member_examine',
'member_invite_policy',
'allow_member_upload_album',
'allow_member_temporary_session',
'allow_member_create_group',
'new_member_history_visible',
'no_finger_open',
'no_code_finger_open',
],
},
run: async (p, ctx) => {
return okResponse(await ctx.bridge.apis.groupAdmin.getAdminSettings(p.group_id));
},
}),
defineAction({
name: 'get_group_tags',
summary: '读取某个群分类下的资料标签',
readOnly: true,
returns: '该分类下的资料标签列表。',
returnsSchema: {
type: 'object',
properties: {
tags: {
type: 'array',
description: '资料标签',
items: {
type: 'object',
properties: {
id: { type: 'integer', description: '标签编号' },
name: { type: 'string', description: '标签名' },
type: { type: 'integer', description: '标签类型' },
},
required: ['id', 'name', 'type'],
},
},
},
required: ['tags'],
},
params: { group_class: f.int({ min: 0, max: 0xFFFFFFFF }) },
run: async (p, ctx) => okResponse(await ctx.bridge.apis.groupAdmin.listCategoryTags(p.group_class)),
}),
defineAction({
name: 'add_group_tag',
summary: '向某个群分类添加资料标签',
params: {
group_class: f.int({ min: 0, max: 0xFFFFFFFF }),
name: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.addCategoryTag(p.group_class, p.name);
return okResponse();
},
}),
defineAction({
name: 'delete_group_tag',
summary: '从某个群分类移除资料标签',
params: {
group_class: f.int({ min: 0, max: 0xFFFFFFFF }),
name: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.removeCategoryTag(p.group_class, p.name);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_admin',
summary: '设置/取消管理员',
+1 -24
View File
@@ -155,28 +155,6 @@ export const actions = [
},
}),
groupAction({
name: 'upload_video_to_qun_album',
summary: '上传视频到群相册',
returns: '{ id: string }',
returnsSchema: {
type: 'object',
properties: {
id: { type: 'string', description: '视频 id' },
},
required: ['id'],
},
params: {
album_id: f.string({ allowEmpty: false }).describe('相册 id'),
album_name: f.string({ allowEmpty: false }).describe('相册名称'),
file: f.video().describe('视频文件'),
},
run: async (p, ctx) => {
const result = await ctx.bridge.apis.groupAlbum.uploadVideo(p.group_id, p.album_id, p.album_name, p.file);
return okResponse(result);
},
}),
groupAction({
name: 'get_group_album_media_list',
readOnly: true,
@@ -245,10 +223,9 @@ export const actions = [
groupAction({
name: 'del_group_album_media',
summary: '删除群相册图片或视频',
params: {
album_id: f.string({ allowEmpty: false }),
lloc: f.string({ allowEmpty: false }).describe('图片长定位标识,或视频 id'),
lloc: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
const res = await ctx.bridge.apis.groupAlbum.delete(p.group_id, p.album_id, p.lloc);
+7 -20
View File
@@ -1,4 +1,5 @@
import { defineAction, groupAction, groupUserAction, f } from '../action-kit';
import { asString } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
import { WebHonorType } from '@snowluma/protocol/web/group-honor';
@@ -13,7 +14,6 @@ export const groupInfoReturnsSchema = {
group_create_time: { type: 'integer', description: '建群时间戳(秒)' },
group_level: { type: 'integer', description: '群等级' },
group_memo: { type: 'string', description: '群简介 / 公告预览' },
group_description: { type: 'string', description: '群简介(公告不算;未加入的群为空)' },
group_all_shut: { type: 'integer', enum: [-1, 0], description: '是否开启全员禁言(-1 开启,0 关闭)' },
},
required: [
@@ -41,7 +41,6 @@ export const actions = [
group_create_time: { type: 'integer', description: '建群时间戳(秒)' },
group_level: { type: 'integer', description: '群等级(列表批量场景恒 0,详见 get_group_info)' },
group_memo: { type: 'string', description: '群简介 / 公告预览' },
group_description: { type: 'string', description: '群简介(公告不算;未加入的群为空)' },
group_all_shut: { type: 'integer', enum: [-1, 0], description: '是否开启全员禁言(-1 开启,0 关闭)' },
},
required: [
@@ -79,7 +78,6 @@ export const actions = [
group_create_time: 0,
group_level: 0,
group_memo: '',
group_description: '',
group_all_shut: 0,
};
if (ctx.getGroupInfo) {
@@ -111,17 +109,12 @@ export const actions = [
last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' },
shut_up_timestamp: { type: 'integer', description: '禁言结束时间戳(秒,未禁言时为 0)' },
level: { type: 'string', description: '群等级' },
qq_level: { type: 'integer', description: 'QQ 等级,仅在账号资料可用时返回' },
qage: { type: 'integer', description: '按注册时间计算的完整周年数(UTC),注册时间不可用时省略' },
role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' },
title: { type: 'string', description: '专属头衔' },
area: { type: 'string', description: '地区(QQ NT 不提供,恒空)' },
unfriendly: { type: 'boolean', description: '是否不良记录(QQ NT 不提供,恒 false)' },
title_expire_time: { type: 'integer', description: '头衔过期时间戳(QQ NT 不提供,恒 0)' },
card_changeable: { type: 'boolean', description: '是否可改名片(占位,恒 true)' },
qidian_master_flag: { type: 'integer', description: '企点主号标志,0 或 1;普通账号为 0' },
qidian_crew_flag: { type: 'integer', description: '企点员工标志,0 或 1;普通账号为 0' },
qidian_crew_flag_2: { type: 'integer', description: '企点保留标志,0 或 1;普通账号为 0' },
},
required: ['group_id', 'user_id', 'nickname', 'role'],
},
@@ -156,17 +149,12 @@ export const actions = [
last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' },
shut_up_timestamp: { type: 'integer', description: '禁言结束时间戳(秒,未禁言时为 0)' },
level: { type: 'string', description: '群等级' },
qq_level: { type: 'integer', description: 'QQ 等级,仅在账号资料可用时返回' },
qage: { type: 'integer', description: '按注册时间计算的完整周年数(UTC),注册时间不可用时省略' },
role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' },
title: { type: 'string', description: '专属头衔' },
area: { type: 'string', description: '地区(QQ NT 不提供,恒空)' },
unfriendly: { type: 'boolean', description: '是否不良记录(QQ NT 不提供,恒 false)' },
title_expire_time: { type: 'integer', description: '头衔过期时间戳(QQ NT 不提供,恒 0)' },
card_changeable: { type: 'boolean', description: '是否可改名片(占位,恒 true)' },
qidian_master_flag: { type: 'integer', description: '企点主号标志,0 或 1;普通账号为 0' },
qidian_crew_flag: { type: 'integer', description: '企点员工标志,0 或 1;普通账号为 0' },
qidian_crew_flag_2: { type: 'integer', description: '企点保留标志,0 或 1;普通账号为 0' },
},
required: ['group_id', 'user_id', 'nickname', 'role'],
},
@@ -183,7 +171,6 @@ export const actions = [
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
shut_up_timestamp: 0,
level: '0', role: 'member', title: '',
qidian_master_flag: 0, qidian_crew_flag: 0, qidian_crew_flag_2: 0,
});
}
return okResponse({
@@ -196,14 +183,17 @@ export const actions = [
},
}),
// `type` keeps the legacy `asString(x) || 'all'` semantics (absent / non-string
// / empty-string all collapse to 'all'), which a typed string field can't
// replicate exactly — so it stays a raw param coerced in run().
groupAction({
name: 'get_group_honor_info',
summary: '获取群荣誉信息',
readOnly: true,
params: { type: f.string().optional() },
params: { type: f.raw() },
run: async (p, ctx) => {
const groupId = p.group_id;
const typeStr = p.type || 'all';
const typeStr = asString(p.type) || 'all';
const typeValues = Object.values(WebHonorType) as string[];
if (!typeValues.includes(typeStr)) {
@@ -234,16 +224,13 @@ export const actions = [
request_id: { type: 'integer', description: '请求序列号' },
requester_uin: { type: 'integer', description: '申请人 QQ 号' },
requester_nick: { type: 'string', description: '申请人昵称' },
invitor_uin: { type: 'integer', description: '邀请人 QQ 号,无邀请时为 0' },
invitor_nick: { type: 'string', description: '邀请人昵称' },
message: { type: 'string', description: '验证留言' },
checked: { type: 'boolean', description: '是否已处理' },
flag: { type: 'string', description: '处理请求使用的规范 flag' },
},
required: [
'group_id', 'group_name', 'request_id', 'requester_uin',
'requester_nick', 'invitor_uin', 'invitor_nick',
'message', 'checked', 'flag',
'requester_nick', 'message', 'checked', 'flag',
],
},
},
+3 -5
View File
@@ -211,14 +211,14 @@ function bindActionRegistry(
for (const claim of executableNames) {
if (claim.kind === 'raw') {
const factory = rawFactories[claim.canonical];
const factory = rawFactories[claim.name];
if (!factory) {
throw new Error(
`Action registry raw factory missing: canonical "${claim.canonical}" `
+ `(name "${claim.name}", kind raw)`,
);
}
factoryNames.delete(claim.canonical);
factoryNames.delete(claim.name);
handlers.set(claim.name, Object.freeze({
handler: factory(api),
canonical: claim.canonical,
@@ -262,12 +262,10 @@ export const ACTION_GROUPS: readonly ActionGroup[] = [
{ category: '流式接口', actions: [...streamFileActions, ...streamDownloadActions] },
];
/** Hidden OneBot v11 quick-operation handler; `_async` is the NoneBot 1 alias. */
/** The sole non-ActionSpec handler; reserved in the same namespace up front. */
export const HANDLE_QUICK_OPERATION_ACTION = '.handle_quick_operation';
export const HANDLE_QUICK_OPERATION_ASYNC_ACTION = '.handle_quick_operation_async';
export const RAW_ACTION_RESERVATIONS: readonly RawActionReservation[] = [
{ name: HANDLE_QUICK_OPERATION_ACTION, canonical: HANDLE_QUICK_OPERATION_ACTION },
{ name: HANDLE_QUICK_OPERATION_ASYNC_ACTION, canonical: HANDLE_QUICK_OPERATION_ACTION },
];
/** Complete, validated runtime/docs registry. Compilation happens on import. */
+3 -4
View File
@@ -27,20 +27,19 @@ export const actions = [
defineAction({
name: 'get_status',
readOnly: true,
returns: '运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态;`time` 为当前账号服务实例运行秒数,与 #sl 同源。',
returns: '运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。',
returnsSchema: {
type: 'object',
properties: {
online: { type: 'boolean', description: '是否在线' },
good: { type: 'boolean', description: '收发链路健康状态;确认接收停滞或主动请求连接失效时为 false' },
time: { type: 'integer', description: '当前账号服务实例运行秒数,与 #sl 同源;实例重建后重新计时' },
},
required: ['online', 'good', 'time'],
required: ['online', 'good'],
},
params: {},
run: (_p, ctx) => {
const online = ctx.isOnline();
return okResponse({ online, good: online && ctx.bridge.receiveHealthy, time: Math.floor(ctx.getUptimeMs() / 1000) });
return okResponse({ online, good: online && ctx.bridge.receiveHealthy });
},
}),
+3 -40
View File
@@ -1,21 +1,9 @@
import { createLogger } from '@snowluma/common/logger';
import type { JsonObject, JsonValue } from '../types';
import type { ApiActionContext } from '../api-handler';
import { defineAction, groupAction, f, type Field } from '../action-kit';
import { defineAction, groupAction, f } from '../action-kit';
import { RETCODE, failedResponse, okResponse } from '../types';
/** send_msg only (#426). Some clients send `group_id: ""` on private chats.
* Treat that exact empty string as absent. Do not change `f.groupId()`. */
function sendMsgOptionalGroupId(): Field<number | undefined> {
const inner = f.groupId().optional();
return Object.assign(Object.create(inner) as Field<number | undefined>, {
coerce(raw: Parameters<Field<number | undefined>['coerce']>[0], field: string) {
if (raw === '') return { ok: true as const, value: undefined };
return inner.coerce(raw, field);
},
});
}
const log = createLogger('OneBot');
/**
@@ -48,32 +36,6 @@ async function refreshStoredImageUrls(event: JsonObject, ctx: ApiActionContext):
}
export const actions = [
defineAction({
name: 'send_custom_face',
summary: '发送账号收藏表情(emoji_id 或 MD5),保留表情显示样式',
returns: '{ message_id: number }',
params: {
emoji_id: f.string().describe('当前账号收藏表情的完整 ID 或 32 位 MD5'),
group_id: f.groupId().optional().describe('目标群号;与 user_id 二选一'),
user_id: f.userId().optional().describe('目标 QQ 号;与 group_id 二选一'),
reply_to: f.messageId().optional().describe('可选回复消息 ID'),
},
run: async (p, ctx) => {
if ((p.group_id === undefined) === (p.user_id === undefined)) {
return failedResponse(RETCODE.BAD_REQUEST, 'exactly one of group_id and user_id is required');
}
if (!p.emoji_id.trim()) return failedResponse(RETCODE.BAD_REQUEST, 'emoji_id is required');
const face = await ctx.bridge.apis.profile.resolveCustomFace(p.emoji_id);
const message: JsonObject[] = [];
if (p.reply_to !== undefined) message.push({ type: 'reply', data: { id: String(p.reply_to) } });
message.push({ type: 'image', data: { file: face.url, sub_type: 1, summary: '[动画表情]' } });
const result = p.group_id !== undefined
? await ctx.sendGroupMessage(p.group_id, message, false)
: await ctx.sendPrivateMessage(p.user_id!, message, false);
return okResponse({ message_id: result.messageId });
},
}),
// send_msg routes on message_type / group_id presence, so the *required*
// id is conditional — that branch stays in run(). The fields themselves
// (message required; group_id/user_id valid uints when present) are
@@ -85,7 +47,7 @@ export const actions = [
params: {
message: f.message(),
message_type: f.string().optional(),
group_id: sendMsgOptionalGroupId(),
group_id: f.groupId().optional(),
user_id: f.userId().optional(),
auto_escape: f.bool().default(false),
},
@@ -170,3 +132,4 @@ export const actions = [
},
}),
];
+6 -4
View File
@@ -1,4 +1,5 @@
import { defineAction, f } from '../action-kit';
import { asString } from '../api-handler';
import { okResponse } from '../types';
export const actions = [
@@ -21,14 +22,15 @@ export const actions = [
params: {
// Opaque handle from the original request event; callers must echo it.
flag: f.string({ allowEmpty: false }),
// sub_type → type → 'add'. Empty string is kept, not treated as missing.
sub_type: f.string().optional(),
type: f.string().optional(),
// sub_type/type pass through with a nested fallback (sub_type → type → 'add');
// kept raw so the original asString resolution is preserved verbatim.
sub_type: f.raw(),
type: f.raw(),
approve: f.bool().default(true),
reason: f.string().default(''),
},
run: async (p, ctx) => {
const subType = p.sub_type !== undefined ? p.sub_type : (p.type !== undefined ? p.type : 'add');
const subType = asString(p.sub_type, asString(p.type, 'add'));
await ctx.handleGroupRequest(p.flag, subType, p.approve, p.reason);
return okResponse();
},
Loaded 100 of 381 files, more files were not shown because too many files have changed in this diff. Show more