Compare commits

..
Author SHA1 Message Date
MliKiowa 92a1a02dd3 Enhance bug report template for TRACE logs
Updated the bug report template to emphasize the need for original messages and complete Trace content.
2026-10-16 10:43:35 +08:00
DrSmoothl 87527cb764 chore(release): v1.14.22 2026-10-07 11:04:07 +08:00
DrSmoothl 44679bebd4 fix(protocol): keep the highway upload address
The session response address was discarded, so uploads used the default host.

Fixes #513
2026-10-06 15:20:24 +08:00
DrSmoothl f95d247e73 feat(runtime): override deploy settings from the environment
SNOWLUMA_ variables can set the factory OneBot listen ports, WebUI TLS,
packet and hook timeouts, the stream directory, file download timeout,
and notification HTTP timeout. The values apply in memory and are not
written back to saved config.
2026-10-06 00:48:34 +08:00
DrSmoothl c989c764e3 fix(onebot): allow a custom session release deadline
Operators can set SNOWLUMA_SESSION_RELEASE_DEADLINE_MS, in milliseconds.
The wait stays at 10 seconds when that variable is absent or not a positive integer.
2026-10-06 00:34:48 +08:00
DrSmoothl 940b823571 fix(onebot): bring an account back when shutdown stalls
If the previous OneBot session does not finish closing, the account now
comes back online instead of staying disconnected until QQ is restarted.

Fixes #509
2026-10-06 00:11:44 +08:00
DrSmoothl e0801ff9eb feat(sdk): type the group category tag actions
The action map now includes get_group_tags, add_group_tag, and
delete_group_tag.

Refs #506
2026-10-05 23:51:18 +08:00
DrSmoothl a71377ff17 feat(onebot): add actions for group category tags
get_group_tags lists the tags under one group category. add_group_tag
and delete_group_tag add or remove a tag by name. Callers pass the
category number as group_class. An empty name is rejected.

Refs #506
2026-10-05 23:51:18 +08:00
DrSmoothl f0203823e9 feat(protocol): read and change group category tags
A group profile category can be listed, and a tag name can be added or
removed. An empty name is rejected instead of being dropped.

Refs #506
2026-10-05 23:51:10 +08:00
DrSmoothl 914e9a004f fix(video): update ffmpeg addon so group video sends stay up
Group video sends could exit the process with no error after the file was
staged. Refresh the bundled addon from the build that covers this case.

Fixes #507
2026-10-05 23:01:55 +08:00
DrSmoothl f588f0345c docs(contributing): add guidance for coding agents
Document contributor expectations, validation steps, and manual issue submission requirements for AI-assisted contributions. Provide a shared project guide for coding agents.
2026-10-05 14:22:31 +08:00
DrSmoothl 9632b00638 chore(release): v1.14.21 2026-10-04 16:10:01 +08:00
DrSmoothl 88cb2985e2 fix(protocol): keep forward previews valid
Keep forwarded cards readable when previews contain unsupported characters
without changing the forwarded messages.

Reject invalid resource references and record affected preview fields for
troubleshooting.

Refs #467
2026-10-04 16:03:49 +08:00
DrSmoothl 063ede4c62 fix(onebot): preserve custom forward metadata
Keep custom titles and previews available when reading uploaded forwards,
including nested messages and refreshed sender names.

Reject malformed preview metadata before processing the request.

Refs #493
2026-10-04 16:03:32 +08:00
kano0222 12afae0632 fix(protocol): restore flat forward card compatibility (#467)
Restore ordinary forwarded-message cards while preserving nested forward navigation.

Refs #467
2026-10-04 15:44:31 +08:00
under-the-ocean 89275ae279 fix(onebot): support custom nested forward previews (#493)
Accept custom preview metadata on nested forward messages and carry it through card creation.

Refs #493
2026-10-04 15:44:06 +08:00
星陨 1919e16081 fix(onebot): expose group descriptions separately (#491)
Expose group descriptions without replacing the existing group memo behavior.

Fixes #490
Refs #491
2026-10-04 15:43:39 +08:00
DrSmoothl a6dfd04924 perf(onebot): reduce message history migration scans
Speed up unfinished history migration while preserving all messages and
existing processing limits.

Keep migration diagnostics under the configured logging policy and surface
preparation failures.

Fixes #462
2026-10-04 14:56:02 +08:00
DrSmoothl 99bcfca15c fix(onebot): preserve historical media independently of cache limits
Preserve message history and the media information needed for reliable
forwarding. Retain available older data during upgrades and report storage
failures explicitly.

Fixes #462
2026-10-04 14:00:30 +08:00
DrSmoothl d86e0fc7b5 fix(protocol): preserve sent media for message history
Keep media sent by the bot available for later history and forwarding,
including messages without a server echo.

Fixes #462
2026-10-04 14:00:03 +08:00
DrSmoothl 3068d3ef60 feat(onebot): expose extended account profile information
Add account identifiers, compatible level names, available registration and membership details, and documented account age for group members. Keep unavailable values absent and refresh the action documentation.

Fixes #496
2026-10-04 13:04:42 +08:00
DrSmoothl b69108e1cc fix(onebot): keep ambiguous quote previews unresolved
Avoid selecting a text message when another cached message could share its truncated or media preview. Extend the quote-context regression checks.

Fixes #502
2026-10-04 13:04:28 +08:00
DrSmoothl b9bdcec5f1 fix(onebot): disambiguate same-second private replies
Carry quoted text into receipt lookup and require a unique content match when several outgoing messages share a timestamp. Preserve sequence matches and log unresolved ambiguity.

Fixes #502
2026-10-04 12:56:25 +08:00
DrSmoothl 2c7d9b6387 fix(core): reject unconfirmed group message sends
Require a server message receipt before returning success. Log unconfirmed responses and leave retries to the caller to avoid duplicate sends.

Fixes #492
2026-10-04 12:55:41 +08:00
DrSmoothl efb32ed069 fix(protocol): resolve animation metadata for unlisted faces
Query missing system faces individually and validate their metadata before sending. Share concurrent lookups and surface lookup failures.

Fixes #488
2026-10-04 12:53:48 +08:00
DrSmoothl cf2587a58b fix(onebot): report account startup failures accurately
Preserve startup and migration error details, and stop automatic retries when account configuration is invalid.

Fixes #503
2026-10-04 12:46:55 +08:00
H3CoF6 368becd078 fix(protocol): don't send bytesGeneralFlags on private voice (#495)
Private-chat voice bubbles arrived without a waveform: the NapCat-derived
    14-byte c2c bytesGeneralFlags blob suppresses it. A/B testing that single
    field (everything else byte-identical) shows the receiver drops the shipped
    waveform while it is present and draws the bars as soon as it is gone, so c2c
    now sends no flags at all. Group voice keeps its 10-byte blob unchanged.
2026-09-30 13:55:47 +08:00
DrSmoothl 93b5c1b4bf feat(messages): support animated face results
Allow selecting animated face results and preserve received results in messages and history. Keep the default selection when no result is supplied.

Fixes #487
2026-09-27 13:44:48 +08:00
DrSmoothl 8cc5326a3a docs(mcp): document account session uptime
Include session uptime in the published status action catalog.

Fixes #486
2026-09-27 13:44:48 +08:00
DrSmoothl d610b3c90f feat(onebot): expose account session uptime
Expose account session uptime in status queries, matching the built-in status reply.

Fixes #486
2026-09-27 13:41:17 +08:00
DrSmoothl 797a4d754c fix(protocol): restore filtered friend request approvals
Correct approval handling for filtered friend requests and preserve clear failures when an account cannot be resolved or the request is rejected.

Add regression coverage for separate account identities, approval errors, and existing list and rejection behavior.

Fixes #460
2026-09-26 16:59:52 +08:00
Hypercubies 7a07119ee9 fix(onebot): restore cached reply previews (#458)
Restore readable quote previews for cached messages while preserving reply targets and message content.

Refs #458
2026-09-26 16:52:46 +08:00
DrSmoothl 1ef9a2c330 chore(release): v1.14.20 2026-09-26 16:34:14 +08:00
DrSmoothl 1914880df4 fix(protocol): support image replies in existing temp sessions
Allow image replies in existing group temporary conversations while preserving passive-only restrictions. Missing, expired, or mismatched sessions remain rejected before media processing, and sending never creates or refreshes a session.

Fixes #471
2026-09-26 16:30:54 +08:00
DrSmoothl ad360c8eba feat(sdk): preserve system face animation choices
Expose large in face builders and preserve it through CQ parsing and serialization. Reject invalid animation choices instead of silently discarding them.

Fixes #483
2026-09-26 16:20:55 +08:00
DrSmoothl 0cc06b6b5e feat(onebot): send saved custom faces with sticker presentation
Resolve saved stickers by resource ID or MD5, support group and private destinations with optional replies, and preserve presentation in upload and message metadata.

Fixes #468
2026-09-26 16:19:45 +08:00
DrSmoothl e05d3176a2 fix(protocol): preserve all system face catalog groups
Decode every group in the third face panel and allow IDs absent from the catalog to use the small-face wire format. Keep animation resources dependent on authoritative catalog metadata.

Fixes #482
2026-09-26 16:11:58 +08:00
DrSmoothl 075a27cc46 fix(protocol): classify private file subcommand receipts
Drop download acknowledgements carried by the offline-file subcommand in both push and history paths, while retaining incoming file transfers.

Fixes #477
2026-09-26 16:09:31 +08:00
DrSmoothl 805665a6d6 feat(onebot): support choosing animated system faces
Send available face animations by default and accept large=false for the small representation. Preserve the sticker business type when encoding animated faces.

Fixes #483
2026-09-26 16:06:52 +08:00
DrSmoothl 953b18b5cb fix(protocol): avoid duplicate text for animated faces
Recognize animated face compatibility labels consistently while preserving user-authored text.

Fixes #484
2026-09-26 15:59:07 +08:00
DrSmoothl 1934e4e7f7 feat(onebot): include text alongside received markdown
Preserve Markdown messages while making their content available to integrations that read text segments.

Fixes #474
2026-09-26 15:57:28 +08:00
DrSmoothl 726fbc6c67 fix(webui): hide sidebar pin controls in menu mode
Keep sidebar pinning available in desktop navigation and hide its controls when navigation uses the menu.

Fixes #485
2026-09-26 15:54:38 +08:00
DrSmoothl 0591b160fb ci: migrate npm publishing to trusted OIDC 2026-09-22 09:43:07 +08:00
DrSmoothl fe245d84bf chore(release): v1.14.19 2026-09-21 16:39:11 +08:00
DrSmoothl d0a1b0e804 fix(webui): let the dashboard page scroll while the pointer is over a card
Every tile was a nested scrollport that swallowed the wheel even when its contents already fit. Clip the card instead and leave inner lists to scroll themselves.
2026-09-21 16:27:49 +08:00
DrSmoothl 51c0ffab74 fix(webui): keep the first-run agreement panel from collapsing
Safari layout work dropped the page height that the fill wizard needs, so the agreement card shrank to a line. Restore a full-viewport column so the documents can show.
2026-09-21 16:18:18 +08:00
DrSmoothl 3e581780b3 chore(release): v1.14.18 2026-09-21 14:25:21 +08:00
DrSmoothl 173e21d80d fix(webui): drop an unused appearance-migration assignment
The first assignment was overwritten on every path, which the linter rejected.
2026-09-21 14:23:46 +08:00
DrSmoothl 5ac74ac5f5 test(onebot): format the oversize image body regression
The HTTP image-size regression failed the indent check. Keep the same coverage with the project formatter.
2026-09-21 14:23:46 +08:00
DrSmoothl 1dffb22d05 fix(core): write album comments with the official header fields
The comment packet header only needs the feed time and id. Extra locator fields from the feed cell are not part of the official write.

Refs #436
2026-09-21 14:13:16 +08:00
DrSmoothl dad2b0c5a7 fix(onebot): keep private quote ids aligned with send receipts
Quotes of bot-sent private messages could still resolve to a different id when the quote time was not an exact match. Resolve those quotes by conversation sequence or a nearby unique send time.

Fixes #465
2026-09-21 14:13:11 +08:00
Hypercubies b375e6f66e fix(onebot): accept image request bodies and return explicit size errors
HTTP POST used a body limit too small for ordinary base64 images and dropped the connection when it was exceeded.
Raise the limit and return a structured size error without destroying the socket.
2026-09-21 14:07:00 +08:00
TogetsuDo 41b92263a7 fix(protocol): decode numeric doubt request account fields
Linux doubt-request lists were returning the request time as the applicant account, so later uid lookup queried the wrong value.
Decode the account, request time, and source group from the live list layout.

Refs #460
2026-09-21 14:06:47 +08:00
DrSmoothl 6efadce2eb fix(webui): let Safari add widgets and reorder without HTML5 drag
Touch cannot reliably start a drag. Add a tap control for the
gallery, a file-input label, and handle-only reorder.
2026-09-19 16:30:11 +08:00
DrSmoothl feea35da4c fix(webui): copy and export files on Safari LAN HTTP
Clipboard APIs and instant blob downloads fail on insecure origins
and WebKit. Route every export through the shared helpers.
2026-09-19 16:30:11 +08:00
DrSmoothl 1ab14ea306 fix(webui): keep Safari forms and overlays from zooming or locking
Focus stays at 16px, a modal locks the visual viewport, and motion
that WebKit clips or flashes is dropped.
2026-09-19 16:30:11 +08:00
DrSmoothl 87e964ab95 fix(webui): keep live streams alive after Safari page hide
Safari freezes fetch SSE when the tab is backgrounded. Close the
stream on hide, reopen on show, and accept both line endings.
2026-09-19 16:30:11 +08:00
DrSmoothl b60b1a419c fix(webui): treat iPad and hybrid pointers as touch chrome
A mouse on iPad is still a coarse pointer. Use the sheet layout,
show the custom cursor only after a real mouse move, and keep
theme and wallpaper changes from hanging the page.
2026-09-19 16:30:11 +08:00
DrSmoothl 0ef9f9475c fix(webui): give Safari a shared viewport and clipboard foundation
Safari 17+ needs dynamic viewport units, a 16px field floor, and
clipboard helpers that still work on LAN HTTP.
2026-09-19 16:30:11 +08:00
DrSmoothl 555e4be95e fix(webui): widen the default sidebar and canvas contrast
The default palette kept the rail almost the same tone as the page.
Darken the rail in both light and dark so the split reads clearly.
2026-09-18 00:36:36 +08:00
DrSmoothl 4ede23980c fix(webui): drop the canvas corner when the sidebar is a menu
The top-left radius exists to meet the desktop rail. On a narrow
viewport the rail becomes a sheet, so the leftover curve sat on a
full-bleed canvas.
2026-09-18 00:34:09 +08:00
DrSmoothl b8ba8a1792 fix(webui): darken the kiosk-mode exit control
The corner exit button was too faint against the dashboard. Raise its
default contrast while keeping hover at full opacity.
2026-09-18 00:32:27 +08:00
DrSmoothl 20c31e11a8 fix(onebot): allow typecheck of media cache field folding
The persist helper assigned through a generic object type, which
TypeScript rejects. Write the sanitized copy on a plain record.
2026-09-18 00:19:18 +08:00
DrSmoothl ce050d1ba1 fix(onebot): stop storing inline image payloads in the media cache
Large base64 image sources were written into the media database as keys
and row data, which could freeze the process on slow disks. The cache
now keeps only short identifiers and metadata.

Fixes #463
2026-09-18 00:11:59 +08:00
DrSmoothl 2a515c165c fix(core): copy album feed locator into comment header
DoQunComment still came back 10016 after the owner-uin fix because the
write header only sent time + short feed id. Official cell_common also
carries the 421 locator; copy that cell, and synthesize it if omitted.

Fixes #436
2026-09-17 23:56:07 +08:00
DrSmoothl 23ebee7f20 feat(sdk): add onBotStatus for account session notices
Let bots subscribe to account up/down without using the operator notification channels.
2026-09-16 21:20:51 +08:00
DrSmoothl ad36d47cf0 feat(onebot): emit bot_status on account session edges
Give downstream bots a notice when an account comes up or goes down, so they can handle their own alerts. Operator notification channels are unchanged.
2026-09-16 17:04:06 +08:00
DrSmoothl f2d58d2f79 feat(notifications): deliver online/offline alerts over SMTP
Fixes #459
2026-09-16 10:36:04 +08:00
DrSmoothl 3cd35a76dd fix(core): write album comments as the feed owner
DoQunComment still returned 10016 after the feed lookup because we
stamped the bot onto StFeed.cellUserInfo. Official FeedWorker copies
the feed owner's uin there and only puts the bot on StComment.

Fixes #436
2026-09-16 08:30:32 +08:00
DrSmoothl 4e1cb51f98 chore(tooling): tag a release without checking out local main
Pointing main at dest leaves a stale local main that cannot
fast-forward. Tag the release commit from the current branch.
2026-09-15 16:31:27 +08:00
DrSmoothl 5b71825ce3 chore(tooling): wait for the version bump commit, not the current tip
A later tooling commit on dev made the waiter look for a SHA that
main will never match. Tag the chore(release) commit itself.
2026-09-15 16:22:05 +08:00
DrSmoothl 55dbc022c4 chore(tooling): make pnpm release safe to re-run after a mid-pipeline failure
A dropped fetch while waiting for main used to abort the whole release.
The same version command now resumes from whatever already landed:
skip CI, skip bump, skip a finished push, and keep waiting or tagging.
2026-09-15 16:14:39 +08:00
234 changed files with 9019 additions and 1418 deletions

No files matched your search

+1 -1
View File
@@ -123,7 +123,7 @@ body:
attributes:
label: TRACE 日志 / 错误堆栈
description: |
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现。
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现,务必保留原始报文和完整Trace内容。
开启 TRACE 的两种方式(任选其一):
- **WebUI(推荐)**:进入「日志」页 →「服务端日志级别」切到 `TRACE` → 显示过滤切到「开发」预设(确保 TRACE 行可见,否则导出不含 trace)→ 复现问题 → 点「导出当前视图」得到 `snowluma-logs-*.log`,拖到本输入框上传。
+30
View File
@@ -0,0 +1,30 @@
# npm Trusted Publishing
The npm publish workflows use GitHub Actions OIDC instead of a long-lived
`NPM_TOKEN`. Each package must have a matching Trusted Publisher entry on npm
before its first publish after this migration.
For each package (`@snowluma/sdk`, `@snowluma/ui`, and `@snowluma/mcp`), open
the package's npm settings and add a **GitHub Actions** trusted publisher with:
| Field | Value |
| --- | --- |
| Organization or user | `SnowLuma` |
| Repository | `SnowLuma` |
| Workflow filename | The exact filename below |
| Environment | `SnowLuma` |
| Package | Workflow filename |
| --- | --- |
| `@snowluma/sdk` | `sdk-npm-publish.yml` |
| `@snowluma/ui` | `ui-npm-publish.yml` |
| `@snowluma/mcp` | `mcp-npm-publish.yml` |
The workflow job keeps the `SnowLuma` GitHub Environment, so the environment
field must match exactly. The workflows grant `id-token: write`, use Node 24
(which provides a recent enough npm CLI), and publish with provenance. They do
not read `NPM_TOKEN`.
After all three entries are saved, rerun the failed workflow runs. Once a
successful publish is confirmed for every package, the obsolete `NPM_TOKEN`
environment secret can be removed from GitHub Actions settings.
+10 -10
View File
@@ -40,7 +40,10 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
# Node 24 ships a supported npm CLI; the application runtime stays
# pinned separately by .node-version.
node-version: '24'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
@@ -77,21 +80,17 @@ jobs:
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Validate npm token
- name: Show Trusted Publishing toolchain
if: steps.npm.outputs.already_published != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [ -z "${NODE_AUTH_TOKEN}" ]; then
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
exit 1
fi
node --version
npm --version
- name: Publish MCP to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/mcp
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
# Authentication is supplied by npm Trusted Publishing through the
# GitHub OIDC token (permissions.id-token: write above).
run: npm publish --access public --provenance
- name: Summary
@@ -106,4 +105,5 @@ jobs:
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
echo "| Environment | \`SnowLuma\` |"
echo "| Authentication | npm Trusted Publishing (GitHub OIDC) |"
} >> "${GITHUB_STEP_SUMMARY}"
+10 -10
View File
@@ -37,7 +37,10 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
# Node 24 ships a supported npm CLI; the application runtime stays
# pinned separately by .node-version.
node-version: '24'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
@@ -74,21 +77,17 @@ jobs:
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Validate npm token
- name: Show Trusted Publishing toolchain
if: steps.npm.outputs.already_published != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [ -z "${NODE_AUTH_TOKEN}" ]; then
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
exit 1
fi
node --version
npm --version
- name: Publish SDK to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/sdk
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
# Authentication is supplied by npm Trusted Publishing through the
# GitHub OIDC token (permissions.id-token: write above).
run: npm publish --access public --provenance
- name: Summary
@@ -103,4 +102,5 @@ jobs:
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
echo "| Environment | \`SnowLuma\` |"
echo "| Authentication | npm Trusted Publishing (GitHub OIDC) |"
} >> "${GITHUB_STEP_SUMMARY}"
+10 -10
View File
@@ -37,7 +37,10 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
# Node 24 ships a supported npm CLI; the application runtime stays
# pinned separately by .node-version.
node-version: '24'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
@@ -71,21 +74,17 @@ jobs:
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Validate npm token
- name: Show Trusted Publishing toolchain
if: steps.npm.outputs.already_published != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [ -z "${NODE_AUTH_TOKEN}" ]; then
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
exit 1
fi
node --version
npm --version
- name: Publish UI to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/ui
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
# Authentication is supplied by npm Trusted Publishing through the
# GitHub OIDC token (permissions.id-token: write above).
run: npm publish --access public --provenance
- name: Summary
@@ -100,4 +99,5 @@ jobs:
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
echo "| Environment | \`SnowLuma\` |"
echo "| Authentication | npm Trusted Publishing (GitHub OIDC) |"
} >> "${GITHUB_STEP_SUMMARY}"
+104
View File
@@ -0,0 +1,104 @@
# Working on SnowLuma
SnowLuma translates QQ client sessions into OneBot v11 actions and events, with a WebUI, TypeScript SDK, and MCP server. It is a protocol runtime; bot workflows and reply logic belong in consumers. This guide is for contributors and their coding agents.
## Before making changes
- Read [CONTRIBUTING.md](CONTRIBUTING.md) for contribution requirements, [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for community expectations, and [LICENSE](LICENSE) for contribution and redistribution terms.
- **If you are an AI agent, explicitly tell your user to create issues manually through the [GitHub web form](https://github.com/SnowLuma/SnowLuma/issues/new/choose). Issues created directly with a CLI will be automatically closed.** Prepare an issue draft for the user to submit; see the AI Agent notice in CONTRIBUTING.md.
- Check `git status` and preserve unrelated work. Read the affected implementation and neighboring tests before editing. Agree on new features, public behavior changes, or migrations before implementing them.
- Target PRs at `dev`. `main` is the release pointer. Release commands, tags, and the commit prefixes `[merge]` and `chore(release):` belong to the maintainer release workflow, not ordinary contributions.
## Repository map
This is a pnpm workspace. Package ownership matters more than directory names:
| Location | Responsibility |
| --- | --- |
| `packages/core` | Application entry, per-account Bridge orchestration, WebUI backend, notifications, release assembly |
| `packages/bridge` | QQ process discovery, Hook sessions, native transport lifecycle |
| `packages/protocol` | Packet decoding, typed QQ events, identity resolution, protocol requests and media transfers |
| `packages/onebot` | Action validation and dispatch, event conversion, message storage, HTTP/WebSocket adapters |
| `packages/common` | Shared logging, configuration and utilities without business dependencies |
| `packages/proto-defs` | Typed protocol schemas |
| `packages/proton` | Compile-time protobuf codecs and build integration |
| `packages/websocket` | WebSocket implementation and native binding integration |
| `packages/runtime` | Distribution manifest, launchers and supplied native artifacts |
| `packages/webui` | Vite/React management console; workspace name is `webui` |
| `packages/sdk` | Public TypeScript client |
| `packages/mcp` | MCP server and generated action catalog |
| `packages/ui` | Published UI component package |
| `tools`, `.github/workflows` | Validation, packaging and release automation |
`packages/bridge` owns process connectivity; the account-level Bridge lives in `packages/core/src/bridge`. Start at [the application entry](packages/core/src/index.ts) to follow their composition.
Read the relevant owner before changing a path:
| Change | Start here |
| --- | --- |
| Connection or account lifecycle | [Hook manager](packages/bridge/src/hook-manager.ts), [Bridge manager](packages/core/src/bridge/manager.ts), [OneBot instance](packages/onebot/src/instance.ts) |
| Incoming QQ events or identity | [Packet pipeline](packages/protocol/src/packet-pipeline.ts), [message decoders](packages/protocol/src/msg-push/index.ts), [identity service](packages/protocol/src/identity-service.ts) |
| OneBot actions or message segments | [Action definitions](packages/onebot/src/actions/index.ts), [validation helpers](packages/onebot/src/action-kit.ts), [event conversion](packages/onebot/src/event-converter/index.ts) |
| WebUI | [Interaction conventions](packages/webui/README.md), `packages/webui/src`, `packages/core/src/webui` |
| SDK or MCP | [SDK guide](packages/sdk/README.md), [SDK versioning](packages/sdk/VERSIONING.md), [MCP guide](packages/mcp/README.md) |
| Protocol codec generation | [Proton guide](packages/proton/README.md), the affected package's `vitest.config.ts` |
## Setup and validation
Use the Node version in [.node-version](.node-version) and the pnpm version in [package.json](package.json). Install with `pnpm install --frozen-lockfile`; keep the existing lockfile unless changing dependencies.
Run commands from the repository root:
```sh
pnpm typecheck # all workspace packages with a typecheck script
pnpm lint
pnpm test # all workspace packages with a test script
pnpm run build:all # release inputs and published packages
pnpm test:core # Core only; not a substitute for workspace tests
pnpm --filter @snowluma/onebot test # example: tests for the affected package
pnpm --filter webui test # the frontend package has no @snowluma/ prefix
```
Use focused tests while iterating. Before handing off a code change, run the full checks required by CONTRIBUTING.md and report anything that could not run. [PR CI](.github/workflows/ci.yml) is the reference; `pnpm run ci` reproduces its commands locally, including dependency installation and the generated-catalog check.
- **Documentation-only changes:** verify links, paths, commands and `git diff --check`; runtime tests do not validate prose.
- **Shared types or actions:** run workspace typechecking as well as behavior tests. A passing Vitest run does not prove type correctness.
- **Protocol codecs:** keep the existing Proton integration in tests so they exercise the same transformations as production. Import real implementations; do not duplicate the algorithm in the test.
- **Native coverage:** `pnpm test:native` is separate from default protocol tests and requires compatible native artifacts. A missing artifact or unavailable target is a reported limitation, not permission to bypass the check.
- **Live QQ behavior:** fixture tests and a successful API response do not prove delivery or client rendering. State what was tested locally and what still needs a real client.
`pnpm dev` starts Core and can attach to local QQ processes; use it only when runtime testing is intended. `pnpm dev:web` starts the frontend, which expects a WebUI backend. Follow the existing test fakes for isolated work rather than starting a live account unnecessarily.
## Implementation rules
- **Fix the cause.** Reproduce failures at the owning layer and add a regression test for the observable behavior. Avoid account-, filename-, or example-specific patches.
- **Make errors observable.** Do not turn exceptions into empty results or successful responses. Preserve error context and use the shared logger for important transitions and failures. If evidence is insufficient, add targeted diagnostics and describe what remains unknown.
- **Preserve account isolation.** Identity, message storage and session state belong to their account. Keep teardown ordering and in-flight work handling intact when changing lifecycle code.
- **Keep parsing separate from effects.** QQ decoders and OneBot event converters translate data. Live state updates belong to their owning pipeline or service; reading history must not mutate live membership or pending requests.
- **Use the declared interfaces.** OneBot consumes the [Bridge interface](packages/core/src/bridge/bridge-interface.ts). Reuse package exports and existing dependency injection instead of reaching into another owner's state or building a second registry.
- **Validate at inputs.** Use the existing action field and cross-field validation helpers. Preserve accepted input forms, response fields and error behavior unless the change explicitly calls for new semantics. Do not silently discard invalid outbound message content.
- **Protect persisted data.** Message history and media metadata are durable records. Do not add automatic deletion or treat them as disposable caches. Migration changes need failure and restart coverage; keep failures visible.
- **Preserve transport policy.** Retain configured bind addresses and access checks. TLS startup failure must not silently downgrade to HTTP. Distinguish saved configuration from changes actually applied to a running adapter.
- **Keep types and ownership clear.** Follow the strict TypeScript configuration, existing import style and two-space indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior.
- **Keep diagnostics safe.** Use existing sanitization when recording external input. Credentials, private keys, private account data and unredacted captures do not belong in commits, fixtures or public reports.
## Generated files and related changes
OneBot action definitions own validation and catalog metadata. After changing an action name, parameter, result description or execution mode:
1. Update the owning definition in `packages/onebot/src/actions` and its tests.
2. Run `pnpm --filter @snowluma/mcp gen`.
3. Inspect and include the corresponding changes in `packages/mcp/src/generated/catalog.ts` and `catalog.json`. Do not hand-edit generated catalog entries.
4. Check affected SDK types and callers, run their relevant tests, and run workspace typechecking.
`pnpm test` also runs the MCP catalog generator and may change these tracked snapshots. CI's `node tools/check-action-catalog.mjs` rejects a working-tree catalog diff; it is a clean-checkout drift check, not the generator itself.
SDK breaking changes also update [CHANGELOG.md](packages/sdk/CHANGELOG.md) and [VERSIONING.md](packages/sdk/VERSIONING.md). WebUI changes follow its [interaction conventions](packages/webui/README.md). Keep user-facing documentation aligned with behavior.
Edit sources rather than `dist` outputs. Native artifacts in `packages/runtime/native` are supplied build inputs; do not substitute arbitrary local binaries to make a build pass. Packaging changes must preserve the checks in [Core's build configuration](packages/core/vite.config.ts) and [the release layout validator](tools/check-release-layout.mjs).
## Handoff and instruction maintenance
Report the behavior changed, the exact validation commands and results, and any unverified runtime or platform behavior. Keep public PR and commit text focused on the contribution; omit local environment details and private research. Use English Conventional Commit messages as described in CONTRIBUTING.md.
`AGENTS.md` is the canonical contributor guide; `CLAUDE.md` is a relative symlink to it. Edit this file once. When package ownership, validation commands or contribution policy changes, update the affected instructions in the same change. Link to checked-in sources and keep the guide usable from a fresh clone without maintainer-local notes, tools or absolute paths.
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+8
View File
@@ -19,6 +19,14 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
如果你只是想看看代码长什么样,可以直接跳到 [本地开发环境](#本地开发环境)。
### AI Agent 贡献须知
如果你是 AI Agent,并准备为本仓库贡献代码、提交 PR 或提出 issue,请先明确告知你的使用者:
> **请通过 GitHub 网页端手动创建 issue。直接使用 CLI 创建的 issue 会被自动关闭。**
你可以协助整理问题描述、复现步骤和相关日志,并将 issue 草稿交给用户,由用户在网页端完成提交。
---
## 项目结构速览
+4
View File
@@ -78,6 +78,10 @@ pnpm test
贡献流程见 [`CONTRIBUTING.md`](CONTRIBUTING.md);模块边界与项目词汇见 [`CONTEXT.md`](CONTEXT.md);开发方向见 [`RoadMap.md`](RoadMap.md)。
## 引用消息预览
OneBot 发送 `reply` 段时,会将本地消息缓存中的原文附入 QQ 引用预览,保留文字、换行与引用关系。图片、语音等非文字段以类型提示显示,不重新上传媒体;原消息中的嵌套引用不递归展开。只有消息元数据而没有缓存正文时,不生成虚构的预览内容。
## 使用边界与许可
> [!IMPORTANT]
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.14.17",
"version": "1.14.22",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
+5 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.14.17",
"version": "1.14.22",
"private": true,
"type": "module",
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
@@ -24,6 +24,10 @@
"types": "./src/hook-packet-client.ts",
"default": "./src/hook-packet-client.ts"
},
"./packet-timeout": {
"types": "./src/packet-timeout.ts",
"default": "./src/packet-timeout.ts"
},
"./injector": {
"types": "./src/injector.ts",
"default": "./src/injector.ts"
+2 -1
View File
@@ -1,4 +1,5 @@
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import { packetTimeoutMs } from './packet-timeout';
import {
HookPipeRequestError,
PIPE_STATUS_CONNECTION_UNAVAILABLE,
@@ -16,7 +17,7 @@ export class HookPacketClient implements PacketSender {
private readonly onOutboundHealthChanged?: OutboundHealthListener,
) { }
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise<SendPacketResult> {
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
if (!this.client.isLoggedIn) {
return { success: false, gotResponse: false, errorCode: -1, errorMessage: 'qq_hook client is not logged in', responseData: null };
}
+8
View File
@@ -0,0 +1,8 @@
import { positiveIntEnv } from '@snowluma/common/env';
/** Default wait for a QQ reply when the caller does not pass one. */
export const DEFAULT_PACKET_TIMEOUT_MS = 15_000;
export function packetTimeoutMs(env?: NodeJS.ProcessEnv): number {
return positiveIntEnv('SNOWLUMA_PACKET_TIMEOUT_MS', DEFAULT_PACKET_TIMEOUT_MS, { env });
}
+2 -1
View File
@@ -10,6 +10,7 @@ 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;
@@ -471,7 +472,7 @@ export class QqHookClient extends EventEmitter {
private loginWaiters: Deferred<QqHookLoginState>[] = [];
constructor(pid: number, {
ackTimeoutMs = DEFAULT_ACK_TIMEOUT_MS,
ackTimeoutMs = positiveIntEnv('SNOWLUMA_HOOK_ACK_TIMEOUT_MS', DEFAULT_ACK_TIMEOUT_MS),
replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS,
runtimeDir = resolveHookRuntimeDir(pid),
}: QqHookClientOptions = {}) {
@@ -0,0 +1,30 @@
import { afterEach, describe, expect, it } from 'vitest';
import { QqHookClient } from '../src/qq-hook-client';
import { packetTimeoutMs } from '../src/packet-timeout';
const PACKET = 'SNOWLUMA_PACKET_TIMEOUT_MS';
const ACK = 'SNOWLUMA_HOOK_ACK_TIMEOUT_MS';
afterEach(() => {
delete process.env[PACKET];
delete process.env[ACK];
});
describe('packet and hook ack timeouts', () => {
it('keeps the 15 second packet default', () => {
expect(packetTimeoutMs({})).toBe(15_000);
});
it('reads SNOWLUMA_PACKET_TIMEOUT_MS', () => {
expect(packetTimeoutMs({ [PACKET]: '8000' })).toBe(8000);
expect(packetTimeoutMs({ [PACKET]: '0' })).toBe(15_000);
});
it('uses SNOWLUMA_HOOK_ACK_TIMEOUT_MS when the client is not given one', () => {
process.env[ACK] = '1200';
const client = new QqHookClient(1, { runtimeDir: '/tmp' });
expect(client.defaultAckTimeoutMs).toBe(1200);
const explicit = new QqHookClient(1, { runtimeDir: '/tmp', ackTimeoutMs: 50 });
expect(explicit.defaultAckTimeoutMs).toBe(50);
});
});
+5 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.14.17",
"version": "1.14.22",
"private": true,
"type": "module",
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
@@ -20,6 +20,10 @@
"types": "./src/coerce.ts",
"default": "./src/coerce.ts"
},
"./env": {
"types": "./src/env.ts",
"default": "./src/env.ts"
},
"./single-flight-cache": {
"types": "./src/single-flight-cache.ts",
"default": "./src/single-flight-cache.ts"
+28
View File
@@ -0,0 +1,28 @@
import { createLogger } from './logger';
const log = createLogger('Env');
/** Node's setTimeout delay is a signed 32-bit integer. */
const MAX_POSITIVE_INT = 2_147_483_647;
/** Read a positive integer environment variable.
*
* A blank value is absent and returns `fallback`. A present but unusable
* value is ignored, with a warning, and also returns `fallback`.
*/
export function positiveIntEnv(
name: string,
fallback: number,
options?: { max?: number; env?: NodeJS.ProcessEnv },
): number {
const max = options?.max ?? MAX_POSITIVE_INT;
const raw = (options?.env ?? process.env)[name];
if (typeof raw !== 'string' || !raw.trim()) return fallback;
const value = raw.trim();
const parsed = /^[1-9]\d*$/.test(value) ? Number(value) : Number.NaN;
if (!Number.isSafeInteger(parsed) || parsed > max) {
log.warn('%s=%j is ignored; expected a positive integer up to %d', name, raw, max);
return fallback;
}
return parsed;
}
+3
View File
@@ -108,6 +108,9 @@ export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<Runt
);
if (logPerUin !== undefined) out.logPerUin = logPerUin;
const webuiTls = parseRequiredBoolEnv(env.SNOWLUMA_WEBUI_TLS, 'SNOWLUMA_WEBUI_TLS');
if (webuiTls !== undefined) out.webuiTls = { enabled: webuiTls };
return out;
}
+26
View File
@@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest';
import { positiveIntEnv } from '../src/env';
describe('positiveIntEnv', () => {
it('returns the fallback when the variable is absent or blank', () => {
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: {} })).toBe(15);
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: ' ' } })).toBe(15);
});
it('reads a positive integer and honors the max', () => {
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: '2500' } })).toBe(2500);
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
max: 65535,
env: { SNOWLUMA_TEST_INT: '80' },
})).toBe(80);
});
it('ignores zero, negatives, fractions, and values above the max', () => {
for (const raw of ['0', '-5', '1.5', 'nope', '70000']) {
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
max: 65535,
env: { SNOWLUMA_TEST_INT: raw },
})).toBe(15);
}
});
});
+11
View File
@@ -124,6 +124,17 @@ describe('resolveRuntimeEnvOverrides', () => {
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
});
it('parses SNOWLUMA_WEBUI_TLS over the saved switch', () => {
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '1' })).toEqual({
webuiTls: { enabled: true },
});
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '0' })).toEqual({
webuiTls: { enabled: false },
});
expect(() => resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: 'maybe' }))
.toThrow(/SNOWLUMA_WEBUI_TLS/);
});
it('ignores an out-of-range / non-numeric port env', () => {
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({});
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.14.17",
"version": "1.14.22",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
+7 -1
View File
@@ -272,6 +272,10 @@ 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),
});
}
@@ -299,7 +303,9 @@ export class ContactsApi {
memberMax: Number(r.maxMemberCount ?? 0n),
members: new Map(),
// #197: the detail is the only source of `level`; it also carries
// createTime + the notice preview (memo).
// createTime + the notice preview (memo). `description` is deliberately
// left unset — 0x88D_0 has no description tag, so for a group the bot
// hasn't joined there is nothing to report (#490).
createTime: Number(r.createTime ?? 0n),
level: Number(r.level ?? 0n),
memo: r.noticePreview ?? '',
+18 -53
View File
@@ -233,16 +233,9 @@ function previewFromElements(elements: MessageElement[]): string {
function cloneNodeWithElements(node: ForwardNodePayload, elements: MessageElement[]): ForwardNodePayload {
return {
userUin: node.userUin,
nickname: node.nickname,
...node,
elements,
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
innerForward: node.innerForward,
news: node.news?.map(item => ({ ...item })),
};
}
@@ -478,23 +471,21 @@ export class ForwardApi {
type: 'forward',
resId: inner.resId,
forwardUuid: inner.uuid,
forwardSource: deriveInnerSource(node.innerForward, isGroup),
forwardSummary: `查看${node.innerForward.length}条转发消息`,
forwardPrompt: '[聊天记录]',
forwardNews: previewLinesFromNodes(node.innerForward),
forwardSource: node.source && node.source.length > 0
? node.source
: deriveInnerSource(node.innerForward, isGroup),
forwardSummary: node.summary && node.summary.length > 0
? node.summary
: `查看${node.innerForward.length}条转发消息`,
forwardPrompt: node.prompt && node.prompt.length > 0
? node.prompt
: '[聊天记录]',
forwardNews: node.news && node.news.length > 0 ? node.news : previewLinesFromNodes(node.innerForward),
forwardTSum: node.innerForward.length,
};
processedNodes.push({
userUin: node.userUin,
nickname: node.nickname,
elements: [previewElement],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
});
const processed = cloneNodeWithElements(node, [previewElement]);
delete processed.innerForward;
processedNodes.push(processed);
} else {
processedNodes.push(node);
}
@@ -548,14 +539,8 @@ export class ForwardApi {
}
forwardResCache.set(resId, uploadReadyNodes.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: node.elements.map(cacheableForwardElement),
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
...cloneNodeWithElements(node, node.elements.map(cacheableForwardElement)),
groupId: node.groupId ?? groupId,
senderCard: node.senderCard,
messageType: node.messageType ?? (groupId ? 'group' : 'private'),
})));
@@ -579,17 +564,7 @@ export class ForwardApi {
const bridge = asBridge(this.ctx);
const cached = forwardResCache.get(resId);
if (cached) {
const nodes = cached.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
}));
const nodes = cloneNodes(cached);
// Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich
// on read (a no-op once names are present) and persist so later hits skip.
if (await this.enrichSenders(nodes)) forwardResCache.set(resId, cloneNodes(nodes));
@@ -863,15 +838,5 @@ function cacheableForwardElement(element: MessageElement): MessageElement {
}
function cloneNodes(nodes: ForwardNodePayload[]): ForwardNodePayload[] {
return nodes.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
}));
return nodes.map(node => cloneNodeWithElements(node, [...node.elements]));
}
+7 -8
View File
@@ -64,11 +64,8 @@ export class FriendApi {
if (userId <= 0 && uid) {
userId = this.ctx.identity.findUinByUid(uid) ?? 0;
}
// Current Linux replies often omit the account id even though the
// official decoder still reads it as a string. The approval packet
// cannot accept a raw number, so fill from the same uin→uid path
// used by ordinary friend requests. Cache-only lookup is not
// enough: filtered applicants are not friends or group members.
// 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);
@@ -86,9 +83,11 @@ export class FriendApi {
/** Approve a doubtful friend-add request. `uidOrFlag` is the list uid, or a digit-only account number. */
async approveDoubtRequest(uidOrFlag: string): Promise<void> {
return ApproveDoubtBuddyReq.invoke(this.ctx, {
uid: await this.resolveDoubtFlag(uidOrFlag),
});
log.trace('doubt-request approval: resolving applicant');
const uid = await this.resolveDoubtFlag(uidOrFlag);
log.trace('doubt-request approval: submitting request');
await ApproveDoubtBuddyReq.invoke(this.ctx, { uid });
log.trace('doubt-request approval: completed');
}
/** Reject (delete/decline) a doubtful friend-add request. `uidOrFlag` matches `approveDoubtRequest`. */
@@ -31,6 +31,9 @@ import {
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';
@@ -117,6 +120,18 @@ export class GroupAdminApi {
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,
+68 -29
View File
@@ -1,7 +1,10 @@
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,
@@ -14,6 +17,7 @@ import type {
GetQunFeedDetailRequest,
GetQunFeedDetailResponse,
GroupAlbumInfo as GroupAlbumInfoWire,
QunFeedCellCommon,
GetMediaListRequest,
GetMediaListResponse,
MediaInfo,
@@ -176,7 +180,7 @@ export class GroupAlbumApi {
body.length,
);
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, 15000);
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, packetTimeoutMs());
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(
`get group album list transport failed: ${result.errorMessage || `code ${result.errorCode}`}`,
@@ -294,7 +298,7 @@ export class GroupAlbumApi {
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
body,
15000,
packetTimeoutMs(),
);
if (!result.success || !result.gotResponse || !result.responseData) {
@@ -326,7 +330,13 @@ export class GroupAlbumApi {
}
const mediaLloc = commentMediaLloc(resolved, lloc);
const feed = await this.getQunFeedDetail(groupId, albumId, batchId, mediaLloc);
const media = mediaInfoForComment(resolved, 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,
@@ -336,18 +346,9 @@ export class GroupAlbumApi {
groupId: groupId.toString(),
field3: 2,
reqBody: {
field1: {
time: feed.time,
feedId: feed.feedId,
},
field2: {
field1: { uin },
},
field5: {
medias: [media],
albumId,
batchId,
},
field1: commentReqHeader(feed.cellCommon),
...(ownerUin ? { field2: { field1: { uin: ownerUin } } } : {}),
field5: photoInfo,
},
field5: {
user: { uin },
@@ -359,7 +360,7 @@ export class GroupAlbumApi {
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(DO_QUN_COMMENT_CMD, body, 15000);
const result = await this.ctx.sendRawPacket(DO_QUN_COMMENT_CMD, body, packetTimeoutMs());
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to comment on album media');
@@ -398,12 +399,7 @@ export class GroupAlbumApi {
const type = isLike ? 2 : 1;
const status = isLike ? 0 : 1;
let id = '';
if (lloc) {
id = `421_1_0_${groupId}|${albumId}|${batchId}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`;
} else {
id = `421_1_0_${groupId}|${albumId}|${batchId}`;
}
const id = qunFeedCellId(groupId, albumId, batchId, lloc);
const body = protobuf_encode<DoQunLikeRequest>({
field1: 5495,
@@ -436,7 +432,7 @@ export class GroupAlbumApi {
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
body,
15000,
packetTimeoutMs(),
);
if (!result.success || !result.gotResponse || !result.responseData) {
@@ -475,7 +471,7 @@ export class GroupAlbumApi {
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
body,
15000,
packetTimeoutMs(),
);
if (!result.success || !result.gotResponse || !result.responseData) {
@@ -557,7 +553,7 @@ export class GroupAlbumApi {
albumId: string,
batchId: bigint,
lloc: string,
): Promise<{ time: bigint; feedId: string }> {
): Promise<{ cellCommon: QunFeedCellCommon; ownerUin: string; media?: CommentReqPhotoInfo }> {
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const body = protobuf_encode<GetQunFeedDetailRequest>({
seq: 0,
@@ -576,7 +572,7 @@ export class GroupAlbumApi {
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(GET_QUN_FEED_DETAIL_CMD, body, 15000);
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');
}
@@ -590,14 +586,16 @@ export class GroupAlbumApi {
);
}
const cell = resp.data?.feed?.feed?.cellCommon;
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 {
time: cell?.time ?? 0n,
feedId,
cellCommon: cell ?? { feedId },
ownerUin: feed?.cellUserInfo?.user?.uin ?? '',
media: feed?.cellMedia,
};
}
}
@@ -667,18 +665,59 @@ function commentMediaLloc(item: AlbumCommentMediaItem | undefined, lloc: string)
}
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,
+9
View File
@@ -412,6 +412,14 @@ export class MessageApi {
}
const seq = response.groupSequence ?? 0;
if (seq <= 0) {
log.warn(
'group message delivery unconfirmed: group=%d random=%d result=%s sequence=%s time=%s responseBytes=%d',
groupId, random, response.result, response.groupSequence,
response.timestamp1, result.responseData.length,
);
throw new Error('group message delivery was not confirmed: QQ returned no message receipt; check the conversation before retrying');
}
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return { messageId, sequence: seq, clientSequence: 0, random, timestamp };
@@ -577,6 +585,7 @@ export class MessageApi {
bridge: this.ctx as unknown as Bridge,
userUid,
scene: 'group-temp',
tempGroupId: groupUin,
});
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
+13
View File
@@ -180,6 +180,19 @@ 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 来自收藏列表。 */
deleteCustomFace(emojiId: string): Promise<void> {
return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId });
+2 -1
View File
@@ -4,6 +4,7 @@ import {
runWithTraceRequest,
} from '@snowluma/common/logger';
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import { packetTimeoutMs } from '@snowluma/bridge/packet-timeout';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
@@ -296,7 +297,7 @@ export class Bridge implements BridgeInterface {
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
return this.msgRandom_ & 0x7FFFFFFF;
}
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
if (!this.packetClient_) {
return runWithTraceRequest(() => {
const startedAt = Date.now();
+119 -4
View File
@@ -11,6 +11,7 @@ import { boolOr, clampInt, isObject } from '@snowluma/common/coerce';
import { createLogger } from '@snowluma/common/logger';
import fs from 'fs';
import path from 'path';
import { extractAddress, parseRecipients } from './smtp';
const log = createLogger('Notifications.Config');
@@ -39,14 +40,37 @@ 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.). */
/** 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 {
@@ -63,6 +87,23 @@ export const DEFAULT_BODY_TEMPLATE = `{
"desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**时间**:{time}"
}`;
export const DEFAULT_SUBJECT_TEMPLATE = '账号{event}:{nickname} ({uin})';
export const DEFAULT_EMAIL_BODY_TEMPLATE = `账号状态发生了改变。
昵称:{nickname}
QQ号:{uin}
当前状态:{event}
时间:{time}`;
const SMTP_HOST_MAX = 253;
const SMTP_USER_MAX = 256;
const SMTP_PASS_MAX = 256;
const EMAIL_FIELD_MAX = 1024;
const SUBJECT_TEMPLATE_MAX = 256;
const SMTP_PORT_MIN = 1;
const SMTP_PORT_MAX = 65535;
export function defaultNotificationsConfig(): NotificationsConfig {
return {
version: NOTIFICATIONS_CONFIG_VERSION,
@@ -124,8 +165,6 @@ function isHttpUrl(value: string): boolean {
}
}
/** A channel is usable only with a valid id AND an http(s) target — anything
* else is unusable, so the whole entry is dropped (total normalize). */
function normalizeHeaders(value: unknown): Record<string, string> | undefined {
if (!isObject(value)) return undefined;
const out: Record<string, string> = {};
@@ -147,17 +186,93 @@ function normalizeHeaders(value: unknown): Record<string, string> | undefined {
return Object.keys(out).length > 0 ? out : undefined;
}
function normalizeSmtpHost(value: unknown): string | null {
if (typeof value !== 'string') return null;
const v = value.trim();
if (!v || v.length > SMTP_HOST_MAX) return null;
if (/\s/.test(v) || v.includes('/') || v.includes('://')) return null;
return v;
}
function normalizeFrom(value: unknown): string | null {
if (typeof value !== 'string') return null;
const v = value.trim().slice(0, EMAIL_FIELD_MAX);
return extractAddress(v) ? v : null;
}
function normalizeTo(value: unknown): string | null {
if (typeof value !== 'string') return null;
const addrs = parseRecipients(value.trim().slice(0, EMAIL_FIELD_MAX));
return addrs.length > 0 ? addrs.join(', ') : null;
}
function normalizeChannelType(value: unknown): NotificationChannelType | null {
if (value === 'email') return 'email';
if (value === 'webhook' || value === undefined || value === '') return 'webhook';
return null;
}
function normalizeEmailChannel(
raw: Record<string, unknown>,
id: string,
name: string,
): NotificationChannel | null {
const smtpHost = normalizeSmtpHost(raw.smtpHost);
const from = normalizeFrom(raw.from);
const to = normalizeTo(raw.to);
if (!smtpHost || !from || !to) return null;
const portRaw = raw.smtpPort;
const portProvided = portRaw !== undefined && portRaw !== null && portRaw !== '';
const secureProvided = typeof raw.smtpSecure === 'boolean';
const port = portProvided
? clampInt(portRaw, SMTP_PORT_MIN, SMTP_PORT_MAX, 0)
: 0;
if (portProvided && port === 0) return null;
const smtpSecure = secureProvided ? Boolean(raw.smtpSecure) : port === 465 || port === 0;
const smtpPort = port === 0 ? (smtpSecure ? 465 : 587) : port;
const smtpUser = typeof raw.smtpUser === 'string' ? raw.smtpUser.trim().slice(0, SMTP_USER_MAX) : '';
const smtpPass = typeof raw.smtpPass === 'string' ? raw.smtpPass.slice(0, SMTP_PASS_MAX) : '';
return {
id,
name,
type: 'email',
url: '',
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_EMAIL_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
enabled: boolOr(raw.enabled, true),
smtpHost,
smtpPort,
smtpSecure,
...(smtpUser ? { smtpUser } : {}),
...(smtpPass ? { smtpPass } : {}),
from,
to,
subjectTemplate: strOr(raw.subjectTemplate, DEFAULT_SUBJECT_TEMPLATE, SUBJECT_TEMPLATE_MAX) || DEFAULT_SUBJECT_TEMPLATE,
};
}
/** A channel is usable only with a valid id AND a deliverable target —
* http(s) URL for webhooks, SMTP host + from/to for email. Anything else
* is dropped (total normalize). */
function normalizeChannel(raw: unknown): NotificationChannel | null {
if (!isObject(raw)) return null;
const id = normalizeChannelId(raw.id);
if (!id) return null;
const type = normalizeChannelType(raw.type);
if (!type) return null;
const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id;
if (type === 'email') return normalizeEmailChannel(raw, id, name);
const url = typeof raw.url === 'string' ? raw.url.trim() : '';
if (!isHttpUrl(url)) return null;
const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id;
const headers = normalizeHeaders(raw.headers);
return {
id,
name,
type: 'webhook',
url,
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
enabled: boolOr(raw.enabled, true),
+81 -24
View File
@@ -2,16 +2,18 @@
//
// Subscribes to BridgeManager session online/offline edges, runs a per-UIN
// debounce state machine (see debounce.ts), and on a fired transition renders
// each opted-in + enabled channel's body template and POSTs it — recording the
// each opted-in + enabled channel's template and delivers it — recording the
// outcome in a bounded in-memory history (lost on restart, by design).
//
// Side-effecting collaborators (config load, per-UIN channel ids, the outbound
// POST, the clock) are injected so the class is fully unit-testable; the real
// wiring lives in `createNotificationManager()` at the bottom.
// Side-effecting collaborators (config load, per-UIN channel ids, webhook POST,
// SMTP send, the clock) are injected so the class is fully unit-testable; the
// real wiring lives in `createNotificationManager()` at the bottom.
import { positiveIntEnv } from '@snowluma/common/env';
import { createLogger } from '@snowluma/common/logger';
import { loadOneBotConfig } from '@snowluma/onebot/config';
import type { BridgeManager } from '../bridge/manager';
import {
isEmailChannel,
loadNotificationsConfig,
renderTemplate,
type NotificationChannel,
@@ -19,6 +21,7 @@ import {
type NotificationsConfig,
} from './config';
import { DebounceMachine, type DebounceDecision } from './debounce';
import { formatSmtpError, parseRecipients, sendSmtpMail } from './smtp';
const log = createLogger('Notifications');
@@ -43,13 +46,27 @@ export interface PostResult {
error?: string;
}
export interface MailPayload {
host: string;
port: number;
secure: boolean;
user?: string;
pass?: string;
from: string;
to: string;
subject: string;
text: string;
}
export interface NotificationManagerDeps {
/** Global channel store (channels + debounceSeconds). */
loadConfig: () => NotificationsConfig;
/** The channel ids a UIN has opted into. */
loadChannelIds: (uin: string) => string[];
/** Outbound delivery — never throws; failures come back as `{ ok: false }`. */
/** Webhook delivery — never throws; failures come back as `{ ok: false }`. */
post: (url: string, body: string, headers?: Record<string, string>) => Promise<PostResult>;
/** SMTP delivery — optional so webhook-only tests stay lean. */
sendMail?: (mail: MailPayload) => Promise<PostResult>;
now: () => number;
historyLimit?: number;
}
@@ -140,7 +157,7 @@ export class NotificationManager {
}
}
/** Render + POST a transition to every opted-in, enabled channel and record
/** Render + deliver a transition to every opted-in, enabled channel and record
* the outcome. Never throws (a bad channel can't break the others). */
async notify(uin: string, event: NotificationEvent): Promise<void> {
let channels: NotificationChannel[];
@@ -162,14 +179,7 @@ export class NotificationManager {
};
for (const ch of channels) {
const body = renderTemplate(ch.bodyTemplate, vars);
let result: PostResult;
try {
result = await this.deps.post(ch.url, body, ch.headers);
} catch (err) {
// The injected post is contracted not to throw, but guard anyway.
result = { ok: false, error: errMsg(err) };
}
const result = await this.deliver(ch, vars);
this.record({
time: this.deps.now(),
uin,
@@ -185,9 +195,33 @@ export class NotificationManager {
}
}
private async deliver(ch: NotificationChannel, vars: Record<string, string>): Promise<PostResult> {
try {
if (isEmailChannel(ch)) {
const send = this.deps.sendMail;
if (!send) return { ok: false, error: 'email delivery is not configured' };
return await send({
host: ch.smtpHost,
port: ch.smtpPort,
secure: ch.smtpSecure,
user: ch.smtpUser,
pass: ch.smtpPass,
from: ch.from,
to: ch.to,
subject: renderTemplate(ch.subjectTemplate, vars),
text: renderTemplate(ch.bodyTemplate, vars),
});
}
return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers);
} catch (err) {
// Injected collaborators are contracted not to throw, but guard anyway.
return { ok: false, error: errMsg(err) };
}
}
/** Send a one-off test to a single channel by id — ignores `enabled` and the
* per-UIN opt-in (you test a channel before wiring it up), with sample
* variables. Reuses the real render+POST path; NOT recorded to history.
* variables. Reuses the real render+deliver path; NOT recorded to history.
* `found:false` means the channel id is unknown. */
async testSend(channelId: string): Promise<PostResult & { found: boolean }> {
let channel: NotificationChannel | undefined;
@@ -197,17 +231,13 @@ export class NotificationManager {
return { ok: false, found: false, error: errMsg(err) };
}
if (!channel) return { ok: false, found: false };
const body = renderTemplate(channel.bodyTemplate, {
const vars = {
uin: '10000',
nickname: '测试账号',
event: 'offline',
event: 'offline' as const,
time: new Date(this.deps.now()).toISOString(),
});
try {
return { ...(await this.deps.post(channel.url, body, channel.headers)), found: true };
} catch (err) {
return { ok: false, found: true, error: errMsg(err) };
}
};
return { ...(await this.deliver(channel, vars)), found: true };
}
private record(rec: DeliveryRecord): void {
@@ -233,7 +263,9 @@ export class NotificationManager {
/** Default outbound POST: a single attempt with a timeout, JSON content-type
* (the common case for 钉钉/Discord/飞书). Never throws. */
export function createDefaultPost(timeoutMs = DEFAULT_POST_TIMEOUT_MS): NotificationManagerDeps['post'] {
export function createDefaultPost(
timeoutMs = positiveIntEnv('SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS', DEFAULT_POST_TIMEOUT_MS),
): NotificationManagerDeps['post'] {
return async (url, body, headers) => {
try {
const res = await fetch(url, {
@@ -249,12 +281,37 @@ export function createDefaultPost(timeoutMs = DEFAULT_POST_TIMEOUT_MS): Notifica
};
}
const DEFAULT_SMTP_TIMEOUT_MS = 15_000;
/** Default SMTP send. Never throws. */
export function createDefaultSendMail(timeoutMs = DEFAULT_SMTP_TIMEOUT_MS): NonNullable<NotificationManagerDeps['sendMail']> {
return async (mail) => {
try {
await sendSmtpMail({
host: mail.host,
port: mail.port,
secure: mail.secure,
user: mail.user,
pass: mail.pass,
from: mail.from,
to: parseRecipients(mail.to),
subject: mail.subject,
body: mail.text,
}, { timeoutMs });
return { ok: true };
} catch (err) {
return { ok: false, error: formatSmtpError(err, mail.host, mail.port) };
}
};
}
/** The real, fully-wired singleton. */
export function createNotificationManager(): NotificationManager {
return new NotificationManager({
loadConfig: loadNotificationsConfig,
loadChannelIds: (uin) => loadOneBotConfig(uin).notifications?.channelIds ?? [],
post: createDefaultPost(),
sendMail: createDefaultSendMail(),
now: () => Date.now(),
});
}
+383
View File
@@ -0,0 +1,383 @@
// Minimal SMTP client for notification-channel email. Runtime ships with no
// npm dependencies, so this speaks the protocol over node:net / node:tls
// (EHLO, optional STARTTLS, AUTH PLAIN/LOGIN, DATA). No extra features.
import net from 'node:net';
import tls from 'node:tls';
const CRLF = '\r\n';
const DEFAULT_TIMEOUT_MS = 15_000;
export class SmtpError extends Error {
readonly responseCode?: number;
readonly code?: string;
constructor(message: string, opts?: { responseCode?: number; code?: string }) {
super(message);
this.name = 'SmtpError';
this.responseCode = opts?.responseCode;
this.code = opts?.code;
}
}
export interface SmtpMail {
host: string;
port: number;
secure: boolean;
user?: string;
pass?: string;
from: string;
to: string[];
subject: string;
body: string;
}
export interface SendSmtpOptions {
timeoutMs?: number;
/** Defaults true. Tests against a self-signed mock pass false. */
rejectUnauthorized?: boolean;
}
export function looksLikeEmail(value: string): boolean {
return /^[^\s<>@]+@[^\s<>@]+$/.test(value);
}
/** Address from `Name <user@host>` or a bare addr; null if neither is usable. */
export function extractAddress(value: string): string | null {
const trimmed = value.trim();
if (!trimmed) return null;
const angled = /<([^<>]+)>/.exec(trimmed);
const addr = (angled ? angled[1] : trimmed).trim();
return looksLikeEmail(addr) ? addr : null;
}
/** Split a comma / semicolon / newline list and keep unique addresses. */
export function parseRecipients(value: string): string[] {
const seen = new Set<string>();
const out: string[] = [];
for (const part of value.split(/[,;\n]+/)) {
const addr = extractAddress(part);
if (!addr) continue;
const key = addr.toLowerCase();
if (seen.has(key)) continue;
seen.add(key);
out.push(addr);
}
return out;
}
function encodeHeader(value: string): string {
if (/^[\x20-\x7E]*$/.test(value) && !/[\r\n]/.test(value)) return value;
return `=?UTF-8?B?${Buffer.from(value, 'utf8').toString('base64')}?=`;
}
function rfc5322Date(d: Date): string {
return d.toUTCString().replace(/GMT$/, '+0000');
}
function wrap76(b64: string): string {
return b64.replace(/.{1,76}/g, (line) => `${line}\r\n`).trimEnd();
}
function isHtmlBody(body: string): boolean {
return /^\s*</.test(body);
}
function dotStuff(payload: string): string {
return payload.replace(/^\./gm, '..');
}
/** Build a single-part MIME message (plain or HTML). Exported for tests. */
export function buildMimeMessage(mail: SmtpMail, now = new Date()): string {
const fromAddr = extractAddress(mail.from);
const toHeader = mail.to.join(', ');
const html = isHtmlBody(mail.body);
const id = `<${now.getTime()}.${Math.random().toString(36).slice(2, 10)}@snowluma>`;
const headers = [
`From: ${mail.from.trim() || (fromAddr ? `<${fromAddr}>` : '')}`,
`To: ${toHeader}`,
`Subject: ${encodeHeader(mail.subject)}`,
`Date: ${rfc5322Date(now)}`,
`Message-ID: ${id}`,
'MIME-Version: 1.0',
`Content-Type: ${html ? 'text/html' : 'text/plain'}; charset=UTF-8`,
'Content-Transfer-Encoding: base64',
];
const body = wrap76(Buffer.from(mail.body, 'utf8').toString('base64'));
return `${headers.join(CRLF)}${CRLF}${CRLF}${body}${CRLF}`;
}
interface SmtpReply {
code: number;
lines: string[];
text: string;
}
function consumeReply(buf: string): { reply: SmtpReply; rest: string } | null {
let offset = 0;
const lines: string[] = [];
let code = 0;
while (offset < buf.length) {
const nl = buf.indexOf('\n', offset);
if (nl === -1) return null;
const line = buf.slice(offset, nl).replace(/\r$/, '');
offset = nl + 1;
const m = /^(\d{3})([ -])(.*)$/.exec(line);
if (!m) continue;
code = Number(m[1]);
lines.push(m[3]);
if (m[2] === ' ') {
return { reply: { code, lines, text: lines.join('\n') }, rest: buf.slice(offset) };
}
}
return null;
}
type SmtpSock = net.Socket | tls.TLSSocket;
function parseCapabilities(reply: SmtpReply): { starttls: boolean; auth: Set<string> } {
const auth = new Set<string>();
let starttls = false;
for (const line of reply.lines) {
const u = line.toUpperCase();
if (u === 'STARTTLS' || u.startsWith('STARTTLS ')) starttls = true;
if (u.startsWith('AUTH ')) {
for (const mech of u.slice(5).split(/\s+/)) {
if (mech) auth.add(mech);
}
}
}
return { starttls, auth };
}
function connectSocket(
host: string,
port: number,
secure: boolean,
timeoutMs: number,
rejectUnauthorized: boolean,
): Promise<SmtpSock> {
return new Promise((resolve, reject) => {
const sock: SmtpSock = secure
? tls.connect({
host,
port,
servername: net.isIP(host) === 0 ? host : undefined,
rejectUnauthorized,
})
: net.connect({ host, port });
const fail = (err: Error) => {
sock.destroy();
reject(err);
};
sock.setTimeout(timeoutMs);
sock.once('timeout', () => fail(new SmtpError('SMTP connection timed out', { code: 'ETIMEDOUT' })));
sock.once('error', fail);
sock.once(secure ? 'secureConnect' : 'connect', () => {
sock.removeAllListeners('timeout');
sock.removeAllListeners('error');
resolve(sock);
});
});
}
function upgradeTls(
socket: net.Socket,
host: string,
timeoutMs: number,
rejectUnauthorized: boolean,
): Promise<tls.TLSSocket> {
return new Promise((resolve, reject) => {
const tlsSocket = tls.connect({
socket,
servername: net.isIP(host) === 0 ? host : undefined,
rejectUnauthorized,
}, () => resolve(tlsSocket));
tlsSocket.setTimeout(timeoutMs);
tlsSocket.once('timeout', () => {
tlsSocket.destroy();
reject(new SmtpError('SMTP STARTTLS timed out', { code: 'ETIMEDOUT' }));
});
tlsSocket.once('error', reject);
});
}
class SmtpSession {
private buf = '';
constructor(private socket: SmtpSock) {}
destroy(): void {
this.socket.destroy();
}
attachTimeout(timeoutMs: number, onTimeout: () => void): void {
this.socket.setTimeout(timeoutMs);
this.socket.once('timeout', onTimeout);
}
async read(): Promise<SmtpReply> {
const ready = consumeReply(this.buf);
if (ready) {
this.buf = ready.rest;
return ready.reply;
}
return new Promise<SmtpReply>((resolve, reject) => {
const onData = (chunk: Buffer) => {
this.buf += chunk.toString('utf8');
const got = consumeReply(this.buf);
if (!got) return;
this.buf = got.rest;
cleanup();
resolve(got.reply);
};
const onError = (err: Error) => {
cleanup();
reject(err);
};
const onClose = () => {
cleanup();
reject(new SmtpError('SMTP connection closed'));
};
const cleanup = () => {
this.socket.removeListener('data', onData);
this.socket.removeListener('error', onError);
this.socket.removeListener('close', onClose);
};
this.socket.on('data', onData);
this.socket.once('error', onError);
this.socket.once('close', onClose);
});
}
write(data: string): void {
this.socket.write(data);
}
async command(line: string, ok: (code: number) => boolean, label?: string): Promise<SmtpReply> {
this.write(line + CRLF);
const reply = await this.read();
if (!ok(reply.code)) {
const name = label ?? line.split(' ')[0] ?? 'SMTP';
throw new SmtpError(`${name} failed: ${reply.code} ${reply.text}`.trim(), {
responseCode: reply.code,
});
}
return reply;
}
replaceSocket(next: SmtpSock): void {
this.socket = next;
this.buf = '';
}
}
export function formatSmtpError(err: unknown, host: string, port: number): string {
if (err instanceof SmtpError) {
if (err.code === 'ECONNREFUSED' || err.code === 'ENOTFOUND' || err.code === 'ETIMEDOUT') {
return `无法连接 SMTP:${host}:${port}`;
}
if (err.responseCode === 535) return 'SMTP 认证失败';
return err.message;
}
if (err instanceof Error) {
const code = (err as NodeJS.ErrnoException).code;
if (code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'ETIMEDOUT') {
return `无法连接 SMTP:${host}:${port}`;
}
if (/self-signed|unable to verify/i.test(err.message)) {
return `SMTP 证书不受信任:${host}`;
}
return err.message || '邮件发送失败';
}
return '邮件发送失败';
}
export async function sendSmtpMail(mail: SmtpMail, opts: SendSmtpOptions = {}): Promise<void> {
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const rejectUnauthorized = opts.rejectUnauthorized ?? true;
const fromAddr = extractAddress(mail.from);
if (!fromAddr) throw new SmtpError('invalid from address');
if (mail.to.length === 0) throw new SmtpError('no recipients');
let sock = await connectSocket(mail.host, mail.port, mail.secure, timeoutMs, rejectUnauthorized);
const session = new SmtpSession(sock);
let finished = false;
const failTimeout = () => {
if (finished) return;
session.destroy();
};
session.attachTimeout(timeoutMs, failTimeout);
try {
const greeting = await session.read();
if (greeting.code !== 220) {
throw new SmtpError(`SMTP greeting failed: ${greeting.code} ${greeting.text}`.trim(), {
responseCode: greeting.code,
});
}
const ehlo = async () => session.command('EHLO [127.0.0.1]', (c) => c === 250);
let caps = parseCapabilities(await ehlo());
if (!mail.secure && caps.starttls) {
await session.command('STARTTLS', (c) => c === 220);
const upgraded = await upgradeTls(sock as net.Socket, mail.host, timeoutMs, rejectUnauthorized);
session.replaceSocket(upgraded);
session.attachTimeout(timeoutMs, failTimeout);
sock = upgraded;
caps = parseCapabilities(await ehlo());
}
const user = mail.user?.trim() ?? '';
if (user) {
await authenticate(session, caps.auth, user, mail.pass ?? '');
}
await session.command(`MAIL FROM:<${fromAddr}>`, (c) => c === 250);
for (const rcpt of mail.to) {
await session.command(`RCPT TO:<${rcpt}>`, (c) => c === 250 || c === 251);
}
await session.command('DATA', (c) => c === 354);
session.write(dotStuff(buildMimeMessage(mail)));
await session.command('.', (c) => c === 250, 'DATA');
try {
await session.command('QUIT', (c) => c === 221);
} catch {
// Some relays drop the socket after 250; delivery already succeeded.
}
finished = true;
} catch (err) {
finished = true;
throw err;
} finally {
session.destroy();
}
}
async function authenticate(
session: SmtpSession,
mechs: Set<string>,
user: string,
pass: string,
): Promise<void> {
const hasPlain = mechs.has('PLAIN');
const hasLogin = mechs.has('LOGIN');
if (hasPlain || !hasLogin) {
try {
const token = Buffer.from(`\0${user}\0${pass}`, 'utf8').toString('base64');
await session.command(`AUTH PLAIN ${token}`, (c) => c === 235, 'AUTH');
return;
} catch (err) {
if (hasPlain && !hasLogin) throw err;
if (err instanceof SmtpError && err.responseCode === 535) throw err;
}
}
await loginAuth(session, user, pass);
}
async function loginAuth(session: SmtpSession, user: string, pass: string): Promise<void> {
await session.command('AUTH LOGIN', (c) => c === 334, 'AUTH');
await session.command(Buffer.from(user, 'utf8').toString('base64'), (c) => c === 334, 'AUTH');
await session.command(Buffer.from(pass, 'utf8').toString('base64'), (c) => c === 235, 'AUTH');
}
+1 -1
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 may embed secrets), AND every OneBot config
// notifications.json (webhook URLs / SMTP passwords), AND every OneBot config
// (onebot.json + per-account onebot_<uin>.json) — those carry access tokens, so
// a no-credentials backup must NOT include them.
// cert.pem is public so it always travels.
@@ -249,6 +249,63 @@ 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: {
@@ -0,0 +1,77 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import { buildApiContext, type OneBotInstanceContext } from '@snowluma/onebot/instance-context';
import { ForwardApi } from '../../src/bridge/apis/forward';
import { mockBridge } from './_helpers';
vi.mock('@snowluma/protocol/highway/image-upload', () => ({ uploadImageMsgInfo: vi.fn() }));
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ uploadPttMsgInfo: vi.fn() }));
vi.mock('@snowluma/protocol/highway/video-upload', () => ({ uploadVideoMsgInfo: vi.fn() }));
describe('forward metadata through upload and cached reads', () => {
it.each([
{ nested: false, enrich: false }, { nested: true, enrich: false },
{ nested: false, enrich: true }, { nested: true, enrich: true },
])('preserves titles and previews with nesting=$nested and enrichment=$enrich', async ({ nested, enrich }) => {
let uploadCount = 0;
const sendRawPacket = vi.fn(async () => ({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<SendLongMsgResp>({
result: { resId: `metadata-${nested}-${enrich}-${++uploadCount}` },
})),
}));
const bridge = mockBridge({ sendRawPacket });
bridge.apis.contacts.fetchGroupMemberList.mockResolvedValue([
{ uin: 111, nickname: 'resolved outer', card: '' },
]);
const forward = new ForwardApi(bridge as any);
const ctx = {
selfId: 10001,
bridge: { apis: {
forward,
message: { sendGroup: vi.fn(async () => ({
messageId: 1, sequence: 2, clientSequence: 0, random: 3, timestamp: 1700000000,
})) },
} },
messageStore: { findEvent: () => null, findMedia: () => null },
cacheMessageMeta: vi.fn(),
converterCtx: {
selfId: 10001, imageUrlResolver: null, mediaUrlResolver: null,
messageIdResolver: null, mediaSegmentSink: null,
},
} as unknown as OneBotInstanceContext;
const api = buildApiContext(ctx);
const text = [{ type: 'text', data: { text: 'hello' } }];
const preview = {
title: 'outer title', source: 'custom source', summary: 'custom summary',
prompt: 'custom prompt', news: [{ text: 'custom preview' }],
};
const { forwardId } = await api.sendGroupForwardMsg(12345, [{
type: 'node', data: {
user_id: 111, nickname: enrich ? '' : 'outer', ...preview,
content: nested
? [{ type: 'node', data: { user_id: 222, nickname: 'inner', title: 'inner title', content: text } }]
: text,
},
}]);
const first = await api.getForwardMsg(forwardId);
expect(first[0]!.sender).toMatchObject({ title: 'outer title' });
expect(first[0]!.sender).toMatchObject({ nickname: enrich ? 'resolved outer' : 'outer' });
expect((await forward.fetch(forwardId!))[0]).toMatchObject(preview);
if (nested) {
expect((await api.getForwardMsg(`metadata-true-${enrich}-1`))[0]!.sender)
.toMatchObject({ title: 'inner title' });
}
const fetched = await forward.fetch(forwardId!);
fetched[0]!.title = 'changed title';
fetched[0]!.news![0]!.text = 'changed preview';
preview.news[0]!.text = 'changed input';
const again = await forward.fetch(forwardId!);
expect(again[0]!.title).toBe('outer title');
expect(again[0]!.news).toEqual([{ text: 'custom preview' }]);
expect(sendRawPacket).toHaveBeenCalledTimes(nested ? 2 : 1);
});
});
@@ -59,7 +59,7 @@ function decodeOuterLongMsg(rawBytes: Uint8Array): LongMsgResult {
return protobuf_decode<LongMsgResult>(gunzipSync(Buffer.from(payload)));
}
function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: string; app?: string } | null {
function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: string; app?: string; news?: Array<{ text: string }>; source?: string; summary?: string } | null {
for (const body of msgBody) {
const elems: Elem[] = body.body?.richText?.elems ?? [];
for (const elem of elems) {
@@ -74,6 +74,9 @@ function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: st
app: parsed.app,
resid: parsed.meta?.detail?.resid,
uniseq: parsed.meta?.detail?.uniseq,
news: parsed.meta?.detail?.news,
source: parsed.meta?.detail?.source,
summary: parsed.meta?.detail?.summary,
};
}
} catch { /* ignore */ }
@@ -178,4 +181,86 @@ describe('forward / nested upload wire alignment', () => {
expect(outermost.action![2]!.actionCommand).not.toBe('MultiMsg');
expect(outermost.action![1]!.actionCommand).not.toBe(outermost.action![2]!.actionCommand);
});
it('inner forward bubble prefers caller-supplied node news over auto-generated lines', async () => {
const responses = ['inner-res', 'outer-res'];
const sendRawPacket = vi.fn(async () =>
uploadResponseWithResId(responses.shift()!)) as any;
const bridge = mockBridge({ sendRawPacket });
const customNews = [{ text: '自定义预览行 1' }, { text: '自定义预览行 2' }];
await new ForwardApi(bridge as any).upload([{
userUin: 111,
nickname: 'outer',
elements: [],
news: customNews,
innerForward: [
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: '会被覆盖的正文' }] },
],
}]);
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
const outerMsgBody = decodeOuterLongMsg(outerBytes).action![0]!.actionData!.msgBody!;
const preview = findLightAppJson(outerMsgBody);
expect(preview).not.toBeNull();
// Caller-supplied news wins over `inner: 会被覆盖的正文`.
expect(preview!.news).toEqual(customNews);
});
it('inner forward bubble falls back to auto-generated lines when node has no news', async () => {
const responses = ['inner-res', 'outer-res'];
const sendRawPacket = vi.fn(async () =>
uploadResponseWithResId(responses.shift()!)) as any;
const bridge = mockBridge({ sendRawPacket });
await new ForwardApi(bridge as any).upload([{
userUin: 111,
nickname: 'outer',
elements: [],
// no `news` field — auto-generate from inner nodes
innerForward: [
{ userUin: 222, nickname: '内层说话人', elements: [{ type: 'text', text: '第一句台词' }] },
],
}]);
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
const outerMsgBody = decodeOuterLongMsg(outerBytes).action![0]!.actionData!.msgBody!;
const preview = findLightAppJson(outerMsgBody);
expect(preview).not.toBeNull();
expect(preview!.news).toEqual([{ text: '内层说话人: 第一句台词' }]);
});
it('inner forward card prefers caller-supplied source/summary/prompt metadata', async () => {
const responses = ['inner-res', 'outer-res'];
const sendRawPacket = vi.fn(async () =>
uploadResponseWithResId(responses.shift()!)) as any;
const bridge = mockBridge({ sendRawPacket });
await new ForwardApi(bridge as any).upload([{
userUin: 111,
nickname: 'outer',
elements: [],
source: '万叶的手记',
summary: '共 12 条剧情消息',
prompt: '查看剧情',
innerForward: [
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] },
],
}]);
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
const outerMsgBody = decodeOuterLongMsg(outerBytes).action![0]!.actionData!.msgBody!;
const preview = findLightAppJson(outerMsgBody);
expect(preview).not.toBeNull();
// decodeOuterLongMsg → lightApp meta.detail as built by element-builder
expect(preview!.app).toBe('com.tencent.multimsg');
// The plaintext preview lines of the wire bubble.
// Caller metadata wins: source = 万叶的手记, summary used instead of
// the auto-generated `查看N条转发消息`.
expect(preview!.source).toBe('万叶的手记');
expect(preview!.summary).toBe('共 12 条剧情消息');
});
});
+60 -6
View File
@@ -1,6 +1,7 @@
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,
@@ -18,6 +19,7 @@ import type {
// 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';
@@ -117,7 +119,7 @@ describe('apis/friend', () => {
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: encodeDoubtList([{ nick: 'Alice', uin: 12345n, reqTime: 1700000000n }]),
responseData: encodeNumericDoubtList([{ nick: 'Alice', uin: 12345n, reqTime: 1700000000n }]),
})),
});
const list = await new FriendApi(bridge as any).getDoubtRequests(10);
@@ -132,13 +134,14 @@ describe('apis/friend', () => {
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', uin: 12345n, reqTime: 1700000000n },
{ uid: 'u_alice', nick: 'Alice', reqTime: 1700000000n },
]),
})),
});
@@ -156,7 +159,7 @@ describe('apis/friend', () => {
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: encodeDoubtList([{ nick: 'Alice', uin: 12345n }]),
responseData: encodeNumericDoubtList([{ nick: 'Alice', uin: 12345n }]),
})),
});
const captured: LogEntry[] = [];
@@ -181,9 +184,9 @@ describe('apis/friend', () => {
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.0xd69_0');
expect(cmd).toBe('OidbSvcTrpcTcp.0xd72_0');
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
expect(env.body).toMatchObject({ uid: 'resolved-uid', targetUid: 'resolved-uid' });
expect(env.body).toMatchObject({ selfUid: 'self-uid', targetUid: 'resolved-uid', field3: 0, field4: '' });
});
it('approveDoubtRequest forwards a uid flag without resolving', async () => {
@@ -192,7 +195,37 @@ describe('apis/friend', () => {
expect(bridge.resolveUserUid).not.toHaveBeenCalled();
const [, bytes] = bridge.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
expect(env.body).toMatchObject({ uid: 'u_abc', targetUid: 'u_abc' });
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 () => {
@@ -214,3 +247,24 @@ function encodeDoubtList(
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 } },
}));
}
@@ -23,6 +23,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
@@ -705,4 +710,54 @@ describe('apis/group-admin', () => {
remain_at_all_count_for_uin: 0,
});
});
it('lists category tags and keeps category 0 on the wire', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGetGroupCategoryTagsResp>>({
body: { tags: [{ id: 7, name: '学习', type: 1 }, { name: '未编号' }] },
}),
));
const out = await new GroupAdminApi(bridge as any).listCategoryTags(0);
expect(out).toEqual({
tags: [
{ id: 7, name: '学习', type: 1 },
{ id: 0, name: '未编号', type: 0 },
],
});
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x967c_0');
const env = protobuf_decode<OidbBase<OidbGetGroupCategoryTags>>(bridge.sendRawPacket.mock.calls[0]![1]);
expect(env.command).toBe(0x967C);
expect(env.body?.groupClass).toBe(0);
});
it('returns an empty tag list when the category has none', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGetGroupCategoryTagsResp>>({ body: {} }),
));
await expect(new GroupAdminApi(bridge as any).listCategoryTags(2)).resolves.toEqual({ tags: [] });
});
it('adds and removes a category tag by its name', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).addCategoryTag(3, ' 户外 ');
await new GroupAdminApi(bridge as any).removeCategoryTag(3, '户外');
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
'OidbSvcTrpcTcp.0x967d_0',
'OidbSvcTrpcTcp.0x967e_0',
]);
const added = protobuf_decode<OidbBase<OidbChangeGroupCategoryTag>>(bridge.sendRawPacket.mock.calls[0]![1]);
expect(added.body).toMatchObject({ groupClass: 3, name: ' 户外 ' });
const removed = protobuf_decode<OidbBase<OidbChangeGroupCategoryTag>>(bridge.sendRawPacket.mock.calls[1]![1]);
expect(removed.body).toMatchObject({ groupClass: 3, name: '户外' });
});
it('refuses an empty tag name instead of sending it', async () => {
const bridge = mockBridge();
await expect(new GroupAdminApi(bridge as any).addCategoryTag(1, '')).rejects.toThrow(/must not be empty/);
await expect(new GroupAdminApi(bridge as any).removeCategoryTag(1, '')).rejects.toThrow(/must not be empty/);
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
});
+104 -5
View File
@@ -8,6 +8,7 @@ import type {
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';
@@ -584,6 +585,15 @@ describe('apis/group-album', () => {
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,
@@ -595,7 +605,9 @@ describe('apis/group-album', () => {
data: {
feed: {
feed: {
cellCommon: { time, feedId },
cellCommon: { time, feedId, ...extra.cellCommon },
...(extra.ownerUin ? { cellUserInfo: { user: { uin: extra.ownerUin } } } : {}),
...(extra.cellMedia ? { cellMedia: extra.cellMedia } : {}),
},
},
},
@@ -616,7 +628,16 @@ describe('apis/group-album', () => {
const override = extra(cmd);
if (override) return override;
if (cmd.endsWith('GetMediaList')) return packPhotoMedia();
if (cmd.endsWith('GetQunFeedDetail')) return packFeedDetail();
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',
@@ -629,14 +650,18 @@ describe('apis/group-album', () => {
};
}
function commentRequestOf(bridge: ReturnType<typeof mockBridge>): DoQunCommentRequest {
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 protobuf_decode<DoQunCommentRequest>(commentCall![1] as Uint8Array);
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 {
@@ -682,7 +707,7 @@ describe('apis/group-album', () => {
time: 1700000123n,
feedId: 'official-feed-id',
},
field2: { field1: { uin: '10001' } },
field2: { field1: { uin: '3119936551' } },
field5: {
albumId: 'album-id',
batchId: 77n,
@@ -697,6 +722,80 @@ describe('apis/group-album', () => {
},
});
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 () => {
@@ -0,0 +1,41 @@
import { describe, expect, it, vi } from 'vitest';
import type { BridgeContext } from '../../src/bridge/bridge-context';
import { MessageApi } from '../../src/bridge/apis/message';
import { mockBridge } from './_helpers';
function sender(responseHex: string) {
const ctx = {
...mockBridge(),
nextMessageRandom: () => 1234,
sendRawPacket: vi.fn(async () => ({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(responseHex, 'hex'),
})),
};
return { api: new MessageApi(ctx as unknown as BridgeContext), send: ctx.sendRawPacket };
}
describe('group send receipts (#492)', () => {
it('accepts the confirmed response from the issue log', async () => {
const { api } = sender('080018abb3e8d506500058844a60abb3e8d506700078df0d');
await expect(api.sendGroup(10001, [{ type: 'text', text: 'test' }])).resolves.toMatchObject({
sequence: 9476, messageId: 1234,
});
});
it.each([
['missing', '080018c9b3e8d506500060c9b3e8d5067000'],
['zero', '08005800'],
])('rejects a %s receipt without automatically resending', async (_name, response) => {
const { api, send } = sender(response);
await expect(api.sendGroup(10001, [{ type: 'text', text: 'test' }]))
.rejects.toThrow('group message delivery was not confirmed');
expect(send).toHaveBeenCalledOnce();
});
it('preserves an explicit server rejection', async () => {
const { api } = sender('0801');
await expect(api.sendGroup(10001, [{ type: 'text', text: 'test' }]))
.rejects.toThrow('send group message rejected: result=1');
});
});
@@ -334,6 +334,24 @@ describe('apis/profile', () => {
]);
});
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(
+92 -19
View File
@@ -16,6 +16,7 @@
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])),
@@ -294,6 +295,7 @@ describe('element-builder / all-message validation preflight', () => {
true,
12345,
expect.objectContaining({ imageUrl: 'https://gchat.qpic.cn/received.jpg' }),
undefined,
);
});
@@ -346,26 +348,25 @@ describe('element-builder / file element is no longer carried in elems[]', () =>
});
});
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.
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.
function decodeLightApp(elem: any): unknown {
return JSON.parse(inflatePrefixedPayload(elem.lightApp.data));
}
it('emits a lightApp.data blob with prefix=0x01 (deflated JSON, not XML/serviceID=35)', async () => {
it('emits a serviceID=35 richMsg XML for a flat outer forward', async () => {
const [elem] = await buildSendElems(
[{ type: 'forward', resId: 'res-XYZ' } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(elem.lightApp).toBeDefined();
expect((elem as any).richMsg).toBeUndefined();
expect(elem.lightApp!.data![0]).toBe(0x01);
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"');
});
it('places resid + uniseq inside meta.detail (and uniseq matches extra.filename)', async () => {
@@ -373,6 +374,8 @@ describe('element-builder / forward preview (com.tencent.multimsg LightApp)', ()
[{ 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');
@@ -383,17 +386,87 @@ describe('element-builder / forward preview (com.tencent.multimsg LightApp)', ()
expect(extra.filename).toBe('fixed-uuid-1234');
});
it('autogenerates a uniseq when the element omits forwardUuid (flat forward — cosmetic)', async () => {
it('autogenerates m_fileName for a flat outer forward', async () => {
const [elem] = await buildSendElems(
[{ type: 'forward', resId: 'res-flat' } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
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);
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>');
});
it('threads forwardSource / forwardSummary / forwardPrompt / forwardNews / forwardTSum verbatim', async () => {
@@ -302,6 +302,27 @@ 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 as any).pic.reserveTroop).toBeDefined();
expect((args.extBizInfo as any).pic.reserveC2c).toBeUndefined();
expect(args.extBizInfo.pic?.extData).toBeDefined();
expect(args.extBizInfo.pic?.bytesPbReserveC2c).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 as any).pic.reserveC2c).toBeDefined();
expect((args.extBizInfo as any).pic.reserveTroop).toBeUndefined();
expect(args.extBizInfo.pic?.bytesPbReserveC2c).toBeDefined();
expect(args.extBizInfo.pic?.extData).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: '[图片]' });
expect(defaultPic).toEqual({ bizType: 0, textSummary: '[图片]', extData: { subType: 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]' });
expect(defaultPic).toEqual({ bizType: 0, textSummary: '[custom-bubble]', extData: { subType: 0, textSummary: '[custom-bubble]' } });
});
});
+19 -6
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, NapCat-style
// bytesGeneralFlags, voiceFormat honouring).
// (group/c2c requestId difference, command id mapping, the group-only
// bytesGeneralFlags blob, voiceFormat honouring).
import { describe, it, expect, vi, beforeEach } from 'vitest';
@@ -30,6 +30,15 @@ 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];
@@ -45,7 +54,7 @@ describe('ptt-upload', () => {
);
});
it('c2c: 0x126D_100 + PRIVATE_PTT_CMD_ID + requestId=4 + c2c-flavored flags', async () => {
it('c2c: 0x126D_100 + PRIVATE_PTT_CMD_ID + requestId=4 + no generalFlags', async () => {
await uploadPttMsgInfo({} as any, false, 'recipient-uid', FINGERPRINT);
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
expect(args.oidbCmd).toBe(0x126D);
@@ -53,10 +62,14 @@ describe('ptt-upload', () => {
expect(args.requestId).toBe(4);
expect(args.uploads[0]!.cmdId).toBe(PRIVATE_PTT_CMD_ID);
const c2cFlags = (args.extBizInfo as any).ptt.bytesGeneralFlags;
expect(c2cFlags.length).toBe(14);
expect(c2cFlags[0]).toBe(0x9a);
// 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 () => {
@@ -49,6 +49,15 @@ 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];
@@ -5,6 +5,8 @@ import path from 'path';
import {
DEFAULT_BODY_TEMPLATE,
DEFAULT_DEBOUNCE_SECONDS,
DEFAULT_EMAIL_BODY_TEMPLATE,
DEFAULT_SUBJECT_TEMPLATE,
defaultNotificationsConfig,
normalizeNotificationsConfig,
renderTemplate,
@@ -100,6 +102,7 @@ describe('normalizeNotificationsConfig — total normalize', () => {
{
id: 'dingtalk',
name: 'DingTalk',
type: 'webhook',
url: 'https://oapi.dingtalk.com/robot/send',
bodyTemplate: '{event}',
enabled: true,
@@ -132,10 +135,11 @@ describe('normalizeNotificationsConfig — total normalize', () => {
expect(channels[0].url).toBe('https://a.com');
});
it('defaults enabled=true, name→id, and bodyTemplate→default', () => {
it('defaults enabled=true, name→id, type=webhook, 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();
});
@@ -168,6 +172,92 @@ describe('normalizeNotificationsConfig — total normalize', () => {
});
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');
});
});
describe('loadNotificationsConfig / saveNotificationsConfig (fs-backed)', () => {
@@ -1,7 +1,9 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
NotificationManager,
createDefaultPost,
selectChannels,
type MailPayload,
type NotificationManagerDeps,
type PostResult,
} from '../src/notifications/manager';
@@ -11,6 +13,7 @@ function ch(over: Partial<NotificationChannel> = {}): NotificationChannel {
return {
id: 'c1',
name: 'C1',
type: 'webhook',
url: 'https://hook.example/c1',
bodyTemplate: '{event}:{uin}:{nickname}',
enabled: true,
@@ -18,6 +21,26 @@ 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' })];
@@ -166,6 +189,82 @@ 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());
@@ -223,3 +322,28 @@ describe('NotificationManager — debounce integration (fake timers)', () => {
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]);
});
});
@@ -0,0 +1,289 @@
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');
});
});
@@ -0,0 +1,101 @@
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 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.14.17",
"version": "1.14.22",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
+323 -5
View File
@@ -440,6 +440,54 @@
},
"category": "扩展"
},
{
"name": "add_group_tag",
"aliases": [],
"summary": "向某个群分类添加资料标签",
"readOnly": false,
"params": [
{
"name": "group_class",
"type": "int",
"required": true,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
},
{
"name": "name",
"type": "string",
"required": true,
"schema": {
"type": "string",
"minLength": 1
}
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"group_class": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
"name": {
"type": "string",
"minLength": 1
}
},
"required": [
"group_class",
"name"
],
"additionalProperties": true
},
"category": "群管理"
},
{
"name": "bot_exit",
"aliases": [],
@@ -1422,6 +1470,54 @@
},
"category": "扩展"
},
{
"name": "delete_group_tag",
"aliases": [],
"summary": "从某个群分类移除资料标签",
"readOnly": false,
"params": [
{
"name": "group_class",
"type": "int",
"required": true,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
},
{
"name": "name",
"type": "string",
"required": true,
"schema": {
"type": "string",
"minLength": 1
}
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"group_class": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
"name": {
"type": "string",
"minLength": 1
}
},
"required": [
"group_class",
"name"
],
"additionalProperties": true
},
"category": "群管理"
},
{
"name": "delete_msg",
"aliases": [],
@@ -4428,6 +4524,10 @@
"type": "string",
"description": "群简介 / 公告预览"
},
"group_description": {
"type": "string",
"description": "群简介(公告不算;未加入的群为空)"
},
"group_all_shut": {
"type": "integer",
"enum": [
@@ -5036,6 +5136,10 @@
"type": "string",
"description": "群简介 / 公告预览"
},
"group_description": {
"type": "string",
"description": "群简介(公告不算;未加入的群为空)"
},
"group_all_shut": {
"type": "integer",
"enum": [
@@ -5138,6 +5242,10 @@
"type": "string",
"description": "群简介 / 公告预览"
},
"group_description": {
"type": "string",
"description": "群简介(公告不算;未加入的群为空)"
},
"group_all_shut": {
"type": "integer",
"enum": [
@@ -5241,6 +5349,10 @@
"type": "string",
"description": "群简介 / 公告预览"
},
"group_description": {
"type": "string",
"description": "群简介(公告不算;未加入的群为空)"
},
"group_all_shut": {
"type": "integer",
"enum": [
@@ -5342,6 +5454,14 @@
"type": "string",
"description": "群等级"
},
"qq_level": {
"type": "integer",
"description": "QQ 等级,仅在账号资料可用时返回"
},
"qage": {
"type": "integer",
"description": "按注册时间计算的完整周年数(UTC),注册时间不可用时省略"
},
"role": {
"type": "string",
"enum": [
@@ -5513,6 +5633,14 @@
"type": "string",
"description": "群等级"
},
"qq_level": {
"type": "integer",
"description": "QQ 等级,仅在账号资料可用时返回"
},
"qage": {
"type": "integer",
"description": "按注册时间计算的完整周年数(UTC),注册时间不可用时省略"
},
"role": {
"type": "string",
"enum": [
@@ -6075,6 +6203,75 @@
},
"category": "群信息"
},
{
"name": "get_group_tags",
"aliases": [],
"summary": "读取某个群分类下的资料标签",
"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"
]
},
"readOnly": true,
"params": [
{
"name": "group_class",
"type": "int",
"required": true,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"group_class": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
},
"required": [
"group_class"
],
"additionalProperties": true
},
"category": "群管理"
},
{
"name": "get_group_todo_list",
"aliases": [],
@@ -7548,7 +7745,7 @@
{
"name": "get_status",
"aliases": [],
"returns": "运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。",
"returns": "运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态;`time` 为当前账号服务实例运行秒数,与 #sl 同源。",
"returnsSchema": {
"type": "object",
"properties": {
@@ -7559,11 +7756,16 @@
"good": {
"type": "boolean",
"description": "收发链路健康状态;确认接收停滞或主动请求连接失效时为 false"
},
"time": {
"type": "integer",
"description": "当前账号服务实例运行秒数,与 #sl 同源;实例重建后重新计时"
}
},
"required": [
"online",
"good"
"good",
"time"
]
},
"readOnly": true,
@@ -7580,7 +7782,7 @@
"name": "get_stranger_info",
"aliases": [],
"summary": "获取陌生人信息",
"returns": "用户资料:QQ 号、昵称、好友备注、性别、年龄与个性签名,命中资料时另含等级、企点标志与企业名称。",
"returns": "用户资料,含账号标识、等级别名和可用的注册时间、会员信息。注册时间或会员信息未返回时省略对应字段;登录天数暂无可靠来源,不返回占位值。",
"returnsSchema": {
"type": "object",
"properties": {
@@ -7588,6 +7790,14 @@
"type": "integer",
"description": "QQ 号"
},
"uid": {
"type": "string",
"description": "账号唯一标识(仅查到资料时返回)"
},
"qid": {
"type": "string",
"description": "自定义账号标识(仅查到资料时返回)"
},
"nickname": {
"type": "string",
"description": "昵称"
@@ -7612,6 +7822,26 @@
"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(仅查到资料时返回)"
@@ -8798,6 +9028,94 @@
},
"category": "扩展"
},
{
"name": "send_custom_face",
"aliases": [],
"summary": "发送账号收藏表情(emoji_id 或 MD5),保留表情显示样式",
"returns": "{ message_id: number }",
"readOnly": false,
"params": [
{
"name": "emoji_id",
"type": "string",
"required": true,
"schema": {
"type": "string"
},
"desc": "当前账号收藏表情的完整 ID 或 32 位 MD5"
},
{
"name": "group_id",
"type": "uint",
"required": false,
"role": "group_id",
"schema": {
"type": "integer",
"minimum": 1
},
"desc": "目标群号;与 user_id 二选一"
},
{
"name": "user_id",
"type": "uint",
"required": false,
"role": "user_id",
"schema": {
"type": "integer",
"minimum": 1
},
"desc": "目标 QQ 号;与 group_id 二选一"
},
{
"name": "reply_to",
"type": "messageId",
"required": false,
"role": "message_id",
"schema": {
"type": "integer",
"not": {
"const": 0
}
},
"desc": "可选回复消息 ID"
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"emoji_id": {
"type": "string",
"description": "当前账号收藏表情的完整 ID 或 32 位 MD5"
},
"group_id": {
"type": "integer",
"minimum": 1,
"description": "目标群号;与 user_id 二选一",
"x-role": "group_id"
},
"user_id": {
"type": "integer",
"minimum": 1,
"description": "目标 QQ 号;与 group_id 二选一",
"x-role": "user_id"
},
"reply_to": {
"type": "integer",
"not": {
"const": 0
},
"description": "可选回复消息 ID",
"x-role": "message_id"
}
},
"required": [
"emoji_id"
],
"additionalProperties": true
},
"category": "消息"
},
{
"name": "send_flash_msg",
"aliases": [],
@@ -12989,7 +13307,7 @@
},
{
"category": "消息",
"count": 5
"count": 6
},
{
"category": "好友",
@@ -13001,7 +13319,7 @@
},
{
"category": "群管理",
"count": 18
"count": 21
},
{
"category": "群文件",
+323 -5
View File
@@ -443,6 +443,54 @@ export const ACTIONS: CatalogAction[] = [
},
"category": "扩展"
},
{
"name": "add_group_tag",
"aliases": [],
"summary": "向某个群分类添加资料标签",
"readOnly": false,
"params": [
{
"name": "group_class",
"type": "int",
"required": true,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
},
{
"name": "name",
"type": "string",
"required": true,
"schema": {
"type": "string",
"minLength": 1
}
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"group_class": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
"name": {
"type": "string",
"minLength": 1
}
},
"required": [
"group_class",
"name"
],
"additionalProperties": true
},
"category": "群管理"
},
{
"name": "bot_exit",
"aliases": [],
@@ -1425,6 +1473,54 @@ export const ACTIONS: CatalogAction[] = [
},
"category": "扩展"
},
{
"name": "delete_group_tag",
"aliases": [],
"summary": "从某个群分类移除资料标签",
"readOnly": false,
"params": [
{
"name": "group_class",
"type": "int",
"required": true,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
},
{
"name": "name",
"type": "string",
"required": true,
"schema": {
"type": "string",
"minLength": 1
}
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"group_class": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
"name": {
"type": "string",
"minLength": 1
}
},
"required": [
"group_class",
"name"
],
"additionalProperties": true
},
"category": "群管理"
},
{
"name": "delete_msg",
"aliases": [],
@@ -4431,6 +4527,10 @@ export const ACTIONS: CatalogAction[] = [
"type": "string",
"description": "群简介 / 公告预览"
},
"group_description": {
"type": "string",
"description": "群简介(公告不算;未加入的群为空)"
},
"group_all_shut": {
"type": "integer",
"enum": [
@@ -5039,6 +5139,10 @@ export const ACTIONS: CatalogAction[] = [
"type": "string",
"description": "群简介 / 公告预览"
},
"group_description": {
"type": "string",
"description": "群简介(公告不算;未加入的群为空)"
},
"group_all_shut": {
"type": "integer",
"enum": [
@@ -5141,6 +5245,10 @@ export const ACTIONS: CatalogAction[] = [
"type": "string",
"description": "群简介 / 公告预览"
},
"group_description": {
"type": "string",
"description": "群简介(公告不算;未加入的群为空)"
},
"group_all_shut": {
"type": "integer",
"enum": [
@@ -5244,6 +5352,10 @@ export const ACTIONS: CatalogAction[] = [
"type": "string",
"description": "群简介 / 公告预览"
},
"group_description": {
"type": "string",
"description": "群简介(公告不算;未加入的群为空)"
},
"group_all_shut": {
"type": "integer",
"enum": [
@@ -5345,6 +5457,14 @@ export const ACTIONS: CatalogAction[] = [
"type": "string",
"description": "群等级"
},
"qq_level": {
"type": "integer",
"description": "QQ 等级,仅在账号资料可用时返回"
},
"qage": {
"type": "integer",
"description": "按注册时间计算的完整周年数(UTC),注册时间不可用时省略"
},
"role": {
"type": "string",
"enum": [
@@ -5516,6 +5636,14 @@ export const ACTIONS: CatalogAction[] = [
"type": "string",
"description": "群等级"
},
"qq_level": {
"type": "integer",
"description": "QQ 等级,仅在账号资料可用时返回"
},
"qage": {
"type": "integer",
"description": "按注册时间计算的完整周年数(UTC),注册时间不可用时省略"
},
"role": {
"type": "string",
"enum": [
@@ -6078,6 +6206,75 @@ export const ACTIONS: CatalogAction[] = [
},
"category": "群信息"
},
{
"name": "get_group_tags",
"aliases": [],
"summary": "读取某个群分类下的资料标签",
"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"
]
},
"readOnly": true,
"params": [
{
"name": "group_class",
"type": "int",
"required": true,
"schema": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"group_class": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
},
"required": [
"group_class"
],
"additionalProperties": true
},
"category": "群管理"
},
{
"name": "get_group_todo_list",
"aliases": [],
@@ -7551,7 +7748,7 @@ export const ACTIONS: CatalogAction[] = [
{
"name": "get_status",
"aliases": [],
"returns": "运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。",
"returns": "运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态;`time` 为当前账号服务实例运行秒数,与 #sl 同源。",
"returnsSchema": {
"type": "object",
"properties": {
@@ -7562,11 +7759,16 @@ export const ACTIONS: CatalogAction[] = [
"good": {
"type": "boolean",
"description": "收发链路健康状态;确认接收停滞或主动请求连接失效时为 false"
},
"time": {
"type": "integer",
"description": "当前账号服务实例运行秒数,与 #sl 同源;实例重建后重新计时"
}
},
"required": [
"online",
"good"
"good",
"time"
]
},
"readOnly": true,
@@ -7583,7 +7785,7 @@ export const ACTIONS: CatalogAction[] = [
"name": "get_stranger_info",
"aliases": [],
"summary": "获取陌生人信息",
"returns": "用户资料:QQ 号、昵称、好友备注、性别、年龄与个性签名,命中资料时另含等级、企点标志与企业名称。",
"returns": "用户资料,含账号标识、等级别名和可用的注册时间、会员信息。注册时间或会员信息未返回时省略对应字段;登录天数暂无可靠来源,不返回占位值。",
"returnsSchema": {
"type": "object",
"properties": {
@@ -7591,6 +7793,14 @@ export const ACTIONS: CatalogAction[] = [
"type": "integer",
"description": "QQ 号"
},
"uid": {
"type": "string",
"description": "账号唯一标识(仅查到资料时返回)"
},
"qid": {
"type": "string",
"description": "自定义账号标识(仅查到资料时返回)"
},
"nickname": {
"type": "string",
"description": "昵称"
@@ -7615,6 +7825,26 @@ export const ACTIONS: CatalogAction[] = [
"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(仅查到资料时返回)"
@@ -8801,6 +9031,94 @@ export const ACTIONS: CatalogAction[] = [
},
"category": "扩展"
},
{
"name": "send_custom_face",
"aliases": [],
"summary": "发送账号收藏表情(emoji_id 或 MD5),保留表情显示样式",
"returns": "{ message_id: number }",
"readOnly": false,
"params": [
{
"name": "emoji_id",
"type": "string",
"required": true,
"schema": {
"type": "string"
},
"desc": "当前账号收藏表情的完整 ID 或 32 位 MD5"
},
{
"name": "group_id",
"type": "uint",
"required": false,
"role": "group_id",
"schema": {
"type": "integer",
"minimum": 1
},
"desc": "目标群号;与 user_id 二选一"
},
{
"name": "user_id",
"type": "uint",
"required": false,
"role": "user_id",
"schema": {
"type": "integer",
"minimum": 1
},
"desc": "目标 QQ 号;与 group_id 二选一"
},
{
"name": "reply_to",
"type": "messageId",
"required": false,
"role": "message_id",
"schema": {
"type": "integer",
"not": {
"const": 0
}
},
"desc": "可选回复消息 ID"
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"emoji_id": {
"type": "string",
"description": "当前账号收藏表情的完整 ID 或 32 位 MD5"
},
"group_id": {
"type": "integer",
"minimum": 1,
"description": "目标群号;与 user_id 二选一",
"x-role": "group_id"
},
"user_id": {
"type": "integer",
"minimum": 1,
"description": "目标 QQ 号;与 group_id 二选一",
"x-role": "user_id"
},
"reply_to": {
"type": "integer",
"not": {
"const": 0
},
"description": "可选回复消息 ID",
"x-role": "message_id"
}
},
"required": [
"emoji_id"
],
"additionalProperties": true
},
"category": "消息"
},
{
"name": "send_flash_msg",
"aliases": [],
@@ -12993,7 +13311,7 @@ export const CATEGORIES: CatalogCategory[] = [
},
{
"category": "消息",
"count": 5
"count": 6
},
{
"category": "好友",
@@ -13005,7 +13323,7 @@ export const CATEGORIES: CatalogCategory[] = [
},
{
"category": "群管理",
"count": 18
"count": 21
},
{
"category": "群文件",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.14.17",
"version": "1.14.22",
"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>'`.",
+9 -9
View File
@@ -1,3 +1,4 @@
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';
@@ -21,7 +22,11 @@ import { groupInfoReturnsSchema } from './group-info';
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB
const DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
const DEFAULT_DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
function downloadFileTimeoutMs(): number {
return positiveIntEnv('SNOWLUMA_DOWNLOAD_FILE_TIMEOUT_MS', DEFAULT_DOWNLOAD_FILE_TIMEOUT_MS);
}
const profileLikeUserSchema = {
type: 'object',
@@ -1902,11 +1907,8 @@ export const actions = [
return okResponse(list);
},
}),
// set_doubt_friends_add_request — handle a 可疑好友申请 (0xd69_0). `flag` is
// the uid from the get list, or the applicant's account number (resolved
// before the packet is built). approve → approvalDoubtBuddyReq; approve:false
// → delDoubtBuddyReq (reject/decline). NapCat only ever approves; we add the
// reject path since we RE'd delDoubtBuddyReq too.
// Accept the list UID or resolve the applicant's account number.
// Approval and rejection use their respective friend API operations.
defineAction({
name: 'set_doubt_friends_add_request',
summary: '处理可疑好友申请',
@@ -1915,8 +1917,6 @@ 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 {
@@ -2597,7 +2597,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, DOWNLOAD_FILE_TIMEOUT_MS);
buf = await fetchDownloadFile(url, parseDownloadHeaders(p.headers), DOWNLOAD_FILE_MAX_BYTES, downloadFileTimeoutMs());
}
try {
const safe = await saveDownloadBuffer(buf, name);
+8 -1
View File
@@ -32,17 +32,24 @@ export const actions = [
name: 'get_stranger_info',
summary: '获取陌生人信息',
readOnly: true,
returns: '用户资料:QQ 号、昵称、好友备注、性别、年龄与个性签名,命中资料时另含等级、企点标志与企业名称。',
returns: '用户资料,含账号标识、等级别名和可用的注册时间、会员信息。注册时间或会员信息未返回时省略对应字段;登录天数暂无可靠来源,不返回占位值。',
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: '扩展状态码' },
@@ -166,6 +166,60 @@ export const actions = [
},
}),
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: '设置/取消管理员',
@@ -13,6 +13,7 @@ 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: [
@@ -40,6 +41,7 @@ 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: [
@@ -77,6 +79,7 @@ export const actions = [
group_create_time: 0,
group_level: 0,
group_memo: '',
group_description: '',
group_all_shut: 0,
};
if (ctx.getGroupInfo) {
@@ -108,6 +111,8 @@ 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 不提供,恒空)' },
@@ -151,6 +156,8 @@ 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 不提供,恒空)' },
+4 -3
View File
@@ -27,19 +27,20 @@ export const actions = [
defineAction({
name: 'get_status',
readOnly: true,
returns: '运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。',
returns: '运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态;`time` 为当前账号服务实例运行秒数,与 #sl 同源。',
returnsSchema: {
type: 'object',
properties: {
online: { type: 'boolean', description: '是否在线' },
good: { type: 'boolean', description: '收发链路健康状态;确认接收停滞或主动请求连接失效时为 false' },
time: { type: 'integer', description: '当前账号服务实例运行秒数,与 #sl 同源;实例重建后重新计时' },
},
required: ['online', 'good'],
required: ['online', 'good', 'time'],
},
params: {},
run: (_p, ctx) => {
const online = ctx.isOnline();
return okResponse({ online, good: online && ctx.bridge.receiveHealthy });
return okResponse({ online, good: online && ctx.bridge.receiveHealthy, time: Math.floor(ctx.getUptimeMs() / 1000) });
},
}),
+26 -1
View File
@@ -48,6 +48,32 @@ 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
@@ -144,4 +170,3 @@ export const actions = [
},
}),
];
+1
View File
@@ -49,6 +49,7 @@ export interface ApiActionContext {
bridge: BridgeInterface;
getLoginInfo: () => { userId: number; nickname: string };
isOnline: () => boolean;
getUptimeMs: () => number;
getMessage: (messageId: number) => JsonObject | null;
getMessageMeta: (messageId: number) => MessageMeta | null;
cacheMessageMetas: (
+64 -1
View File
@@ -1,3 +1,4 @@
import { positiveIntEnv } from '@snowluma/common/env';
import { createLogger } from '@snowluma/common/logger';
import { isRealUin } from '@snowluma/common/uin';
import { randomBytes } from 'crypto';
@@ -110,7 +111,69 @@ export function loadOneBotConfig(uin: string, options: LoadOneBotConfigOptions =
saveOneBotConfig(uin, config, { mode: globalRaw ? 'overlay' : 'snapshot' });
}
return config;
// Listen-port overrides stay in memory. Persisting them would bake a
// machine-specific port into onebot_<uin>.json.
return applyOneBotListenPortOverrides(config);
}
const HTTP_DEFAULT_SERVER = 'http-default';
const WS_DEFAULT_SERVER = 'ws-default';
/** Override only the factory listeners. Other adapters keep their saved ports. */
export function applyOneBotListenPortOverrides(
config: OneBotConfig,
env: NodeJS.ProcessEnv = process.env,
): OneBotConfig {
const httpPort = readListenPort('SNOWLUMA_ONEBOT_HTTP_PORT', env);
const wsPort = readListenPort('SNOWLUMA_ONEBOT_WS_PORT', env);
if (httpPort === undefined && wsPort === undefined) return config;
const next = structuredClone(config);
const httpApplied = httpPort !== undefined && assignFactoryPort(
next.networks.httpServers,
HTTP_DEFAULT_SERVER,
httpPort,
'SNOWLUMA_ONEBOT_HTTP_PORT',
);
const wsApplied = wsPort !== undefined && assignFactoryPort(
next.networks.wsServers,
WS_DEFAULT_SERVER,
wsPort,
'SNOWLUMA_ONEBOT_WS_PORT',
);
if (!httpApplied && !wsApplied) return config;
try {
assertValidOneBotConfig(next);
} catch (error) {
log.warn(
'OneBot listen port override ignored: %s',
error instanceof Error ? error.message : String(error),
);
return config;
}
return next;
}
function readListenPort(name: string, env: NodeJS.ProcessEnv): number | undefined {
const raw = env[name];
if (typeof raw !== 'string' || !raw.trim()) return undefined;
const port = positiveIntEnv(name, 0, { max: 65535, env });
return port > 0 ? port : undefined;
}
function assignFactoryPort(
servers: Array<{ name: string; port: number }>,
name: string,
port: number,
envName: string,
): boolean {
const server = servers.find((entry) => entry.name === name);
if (!server) {
log.warn('%s is ignored; no %s listener', envName, name);
return false;
}
server.port = port;
return true;
}
export interface SaveOneBotConfigOptions {
@@ -118,6 +118,10 @@ export function marketFaceElement(emojiId: string, data: Record<string, unknown>
* bytes, a remote url, or a filesystem path with a separator); otherwise, if a
* real http(s) `url` accompanies it, prefer that. (issue #155)
*/
export function isInlineMediaSource(value: string): boolean {
return /^(base64:\/\/|data:)/i.test(value);
}
export function pickMediaSource(data: Record<string, unknown>): string {
const file = String(data.file ?? '').trim();
const url = String(data.url ?? '').trim();
@@ -125,7 +129,7 @@ export function pickMediaSource(data: Record<string, unknown>): string {
if (!file) return fallback;
// `file` is itself loadable: inline bytes, a remote url, or a path (anything
// carrying a `/` or `\` separator, incl. file:// and absolute/relative paths).
if (/^(base64:\/\/|data:|https?:\/\/|file:\/\/)/i.test(file) || /[\\/]/.test(file)) return file;
if (isInlineMediaSource(file) || /^(https?:\/\/|file:\/\/)/i.test(file) || /[\\/]/.test(file)) return file;
// `file` is a bare token (QQ-internal id) — fall back to a real url if present.
if (/^https?:\/\//i.test(url)) return url;
return fallback;
@@ -146,12 +150,37 @@ export const ELEMENT_CODECS = {
face: {
async toSegment(element) {
return { type: 'face', data: { id: String(element.faceId ?? 0) } };
return {
type: 'face',
data: {
id: String(element.faceId ?? 0),
...(element.resultId !== undefined ? { resultId: element.resultId } : {}),
},
};
},
async fromSegment(data) {
const id = intOr(data.id, -1);
if (id < 0) return null;
return { type: 'face', faceId: id };
const element: MessageElementOf<'face'> = { type: 'face', faceId: id };
if (data.resultId !== undefined) {
if (typeof data.resultId === 'string') {
element.resultId = data.resultId;
} else if (typeof data.resultId === 'number' && Number.isSafeInteger(data.resultId) && data.resultId >= 0) {
element.resultId = String(data.resultId);
} else {
throw new MessageElementValidationError('INVALID_FIELD', 'face.resultId must be a string or non-negative safe integer', 'face', 'resultId');
}
}
if (data.large !== undefined) {
if (data.large === true || data.large === 'true' || data.large === 1 || data.large === '1') {
element.large = true;
} else if (data.large === false || data.large === 'false' || data.large === 0 || data.large === '0') {
element.large = false;
} else {
throw new MessageElementValidationError('INVALID_FIELD', 'face.large must be a boolean');
}
}
return element;
},
},
@@ -199,6 +228,7 @@ export const ELEMENT_CODECS = {
element.replyTime && element.replyTime > 0
? element.replyTime
: Number.MAX_SAFE_INTEGER,
element.replyElements,
);
return { type: 'reply', data: { id: String(id) } };
},
@@ -232,6 +262,7 @@ export const ELEMENT_CODECS = {
element.replySenderUin = meta.senderUin;
element.replyTime = meta.time;
element.replyRandom = meta.random;
element.replyElements = meta.elements;
}
return element;
@@ -260,17 +291,20 @@ export const ELEMENT_CODECS = {
// pictures use `imageUrl`. get_forward_msg must accept either —
// otherwise a just-sent merge comes back with empty file/url (#441).
const source = (element.imageUrl || element.url || '').trim();
const resolved = source && !element.imageUrl
const inline = isInlineMediaSource(source);
const resolved = !inline && source && !element.imageUrl
? { ...element, imageUrl: source }
: element;
const url = ctx.imageUrlResolver
? await ctx.imageUrlResolver(resolved, ctx.isGroup)
: source;
const url = inline
? ''
: ctx.imageUrlResolver
? await ctx.imageUrlResolver(resolved, ctx.isGroup)
: source;
const data: JsonObject = {
url,
file: element.fileId
|| (element.md5Hex ? `${element.md5Hex.toLowerCase()}.png` : '')
|| source,
|| (inline ? '' : source),
sub_type: element.subType ?? 0,
summary: element.summary ?? '',
};
@@ -296,7 +330,10 @@ export const ELEMENT_CODECS = {
record: {
async toSegment(element, ctx) {
const url = ctx.mediaUrlResolver ? await ctx.mediaUrlResolver(element, ctx.isGroup, ctx.sessionId) : (element.url ?? '');
const rawUrl = ctx.mediaUrlResolver
? await ctx.mediaUrlResolver(element, ctx.isGroup, ctx.sessionId)
: (element.url ?? '');
const url = isInlineMediaSource(rawUrl) ? '' : rawUrl;
const data: JsonObject = {
file: element.fileName ?? element.fileId ?? '',
url,
@@ -316,7 +353,10 @@ export const ELEMENT_CODECS = {
video: {
async toSegment(element, ctx) {
const url = ctx.mediaUrlResolver ? await ctx.mediaUrlResolver(element, ctx.isGroup, ctx.sessionId) : (element.url ?? '');
const rawUrl = ctx.mediaUrlResolver
? await ctx.mediaUrlResolver(element, ctx.isGroup, ctx.sessionId)
: (element.url ?? '');
const url = isInlineMediaSource(rawUrl) ? '' : rawUrl;
const data: JsonObject = {
file: element.fileName ?? element.fileId ?? '',
url,
+1 -1
View File
@@ -39,6 +39,7 @@ export type MessageIdResolver = (
sequence: number,
eventName: string,
timestamp?: number,
replyElements?: readonly MessageElement[],
) => number;
export type MediaSegmentSink = (
@@ -120,4 +121,3 @@ export async function convertEvent(
return (converter as (ctx: ConverterContext, event: QQEventVariant) => JsonObject | Promise<JsonObject>)(ctx, event);
}
@@ -4,6 +4,7 @@ import type { ToSegmentContext } from './element-codecs';
import { getElementCodec } from './element-codecs';
import { createLogger } from '@snowluma/common/logger';
import type { ConverterContext } from './index';
import { attachMessageMedia } from '../message-media';
const log = createLogger('OneBot');
@@ -32,13 +33,24 @@ export async function elementsToOneBotSegments(
const segmentCtx = toSegmentContext(ctx, isGroup, sessionId);
const result: JsonArray = [];
for (const element of elements) {
let segment: JsonObject;
// One malformed element shouldn't drop the whole message — skip it (with a
// breadcrumb) and keep converting the rest.
try {
result.push(await elementToSegment(element, segmentCtx));
segment = await elementToSegment(element, { ...segmentCtx, mediaSegmentSink: null });
} catch (err) {
log.warn('segment convert skipped type=%s (%s)', element.type,
err instanceof Error ? err.message : String(err));
continue;
}
// Persistence failures must propagate, not masquerade as bad wire elements.
attachMessageMedia(segment, element);
if (element.type === 'image' || element.type === 'record' || element.type === 'video') {
ctx.mediaSegmentSink?.(element.type, element, segment.data as JsonObject, isGroup, sessionId);
}
result.push(segment);
if (element.type === 'markdown' && element.text) {
result.push({ type: 'text', data: { text: element.text } });
}
}
return result;
+3 -1
View File
@@ -1,5 +1,6 @@
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { MessageIdResolver } from './index';
import type { MessageElement } from '@snowluma/protocol/events';
export function parseSelfId(instanceUin: string): number {
const parsed = Number.parseInt(instanceUin, 10);
@@ -39,12 +40,13 @@ export function resolveReplyId(
resolver?: MessageIdResolver | null,
eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT,
timestamp?: number,
replyElements?: readonly MessageElement[],
): number {
const seq = Math.trunc(sequence);
if (seq === 0) return 0;
if (resolver) {
const resolved = resolver(isGroup, sessionId, seq, eventName, timestamp);
const resolved = resolver(isGroup, sessionId, seq, eventName, timestamp, replyElements);
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
}
+1 -2
View File
@@ -10,7 +10,7 @@ export function segmentToCQ(seg: JsonObject): string {
case 'text':
return cqEscape(String(data.text ?? ''));
case 'face':
return `[CQ:face,id=${data.id ?? 0}]`;
return `[CQ:face,id=${data.id ?? 0}${data.resultId !== undefined ? `,resultId=${cqEscape(String(data.resultId))}` : ''}]`;
case 'image':
return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'at':
@@ -77,4 +77,3 @@ export async function parseFromCQString(message: string, options?: ParseMessageO
return elements;
}
+2
View File
@@ -52,6 +52,7 @@ export interface OneBotInstanceContext {
converterCtx: ConverterContext;
config: OneBotConfig;
musicSignUrl?: string;
getUptimeMs(): number;
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
dispatchEvent(
event: JsonObject,
@@ -68,6 +69,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
getLoginInfo: () => getLoginInfo(ref),
isOnline: () => true,
getUptimeMs: () => ref.getUptimeMs(),
getMessage: (messageId) => messageStore.findEvent(messageId),
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
cacheMessageMetas: (entries) => messageStore.storeMetas(entries),
+55 -9
View File
@@ -15,6 +15,7 @@ import { MediaUrlResolver } from './media-url-resolver';
import {
GROUP_MESSAGE_EVENT,
PRIVATE_MESSAGE_EVENT,
PRIVATE_NT_MESSAGE_EVENT,
PRIVATE_SENT_MESSAGE_EVENT,
hashMessageIdInt32,
privateMessageEventName,
@@ -61,7 +62,7 @@ export class OneBotInstance {
private lifecycleTail: Promise<void>;
private readonly rkeyCache: RKeyCache;
private readonly ctx: OneBotInstanceContext;
/** Process-uptime baseline for the `#sl` status reply. */
/** Account-session uptime shared by the status action and `#sl`. */
private readonly startedAt = Date.now();
/** Per-conversation last-reply timestamp for the `#sl` cooldown. */
private readonly statusCommandCooldown = new Map<string, number>();
@@ -131,7 +132,7 @@ export class OneBotInstance {
: moduleLog;
this.rkeyCache = new RKeyCache(globalSettings.rkey);
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
this.mediaStore = new MediaStore(path.join('data', this.uin, 'messages.db'));
this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json'));
this.reactionStore = new ReactionStore(path.join('data', this.uin, 'reactions.db'));
const mediaUrlResolver = new MediaUrlResolver(this.bridge, this.rkeyCache);
@@ -142,7 +143,7 @@ export class OneBotInstance {
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
mediaUrlResolver: (element, isGroup, sessionId) =>
mediaUrlResolver.resolve(element, isGroup, sessionId),
messageIdResolver: (isGroup, sessionId, sequence, eventName, timestamp) => {
messageIdResolver: (isGroup, sessionId, sequence, eventName, timestamp, replyElements) => {
const resolvedEventName = eventName
|| (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT);
if (!isGroup
@@ -154,10 +155,17 @@ export class OneBotInstance {
sequence,
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
timestamp,
replyElements,
);
if (storedId !== null) return storedId;
}
return hashMessageIdInt32(sequence, sessionId, resolvedEventName);
return hashMessageIdInt32(
sequence,
sessionId,
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT
? PRIVATE_NT_MESSAGE_EVENT
: resolvedEventName,
);
},
mediaSegmentSink: (mediaType, element, data, isGroup, sessionId) =>
mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
@@ -173,6 +181,7 @@ export class OneBotInstance {
converterCtx: this.converterCtx,
config,
musicSignUrl: globalSettings.musicSignUrl,
getUptimeMs: () => Math.max(0, Date.now() - this.startedAt),
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
dispatchEvent: (event, source = 'bridge', startedAt) => this.dispatchEvent(event, source, startedAt),
};
@@ -197,6 +206,12 @@ export class OneBotInstance {
return this.networkReady;
}
/** Bridge session edge → OneBot notice. Awaited so offline can leave
* adapters before this generation is disposed. */
emitBotStatus(subType: 'online' | 'offline'): Promise<void> {
return this.dispatchEvent(makeBotStatusEvent(parseInt(this.uin, 10) || 0, subType));
}
/** Begin observing request-list-only group invitations after adapters exist. */
startGroupRequestPolling(): void {
if (this.disposeRequested) return;
@@ -258,6 +273,20 @@ export class OneBotInstance {
this.ctx.musicSignUrl = globalSettings.musicSignUrl;
}
/** Drop listeners and sockets without waiting for shutdown to finish.
* Used when dispose() does not settle and a replacement session must bind. */
forceRelease(): void {
try {
this.quiesce();
} catch (error) {
this.log.warn(
'quiesce during forced release failed: %s',
error instanceof Error ? error.message : String(error),
);
}
this.networkManager.forceRelease();
}
/** Synchronously stop every ingress seam for this instance generation.
*
* This operation is sticky and idempotent. It is intentionally separate
@@ -355,11 +384,11 @@ export class OneBotInstance {
return this.pids.size === 0;
}
private dispatchEvent(
private async dispatchEvent(
event: JsonObject,
source: 'bridge' | 'send' = 'bridge',
startedAt = Date.now(),
): void {
): Promise<void> {
if (source === 'bridge') {
this.cacheMessageEvent(event);
if (this.consumePendingSelfSentEcho(event)) {
@@ -386,9 +415,11 @@ export class OneBotInstance {
return;
}
this.traceEventHandoffTerminal(event, startedAt, 'reporting_started');
void this.networkManager.emitEvent(event).catch((err) => {
try {
await this.networkManager.emitEvent(event);
} catch (err) {
this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
});
}
}
private traceEventHandoffTerminal(
@@ -462,7 +493,7 @@ export class OneBotInstance {
version: typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev',
platform: process.platform,
arch: process.arch,
uptimeMs: Date.now() - this.startedAt,
uptimeMs: this.ctx.getUptimeMs(),
});
if (isGroup) await sendGroupMessage(this.ctx, sessionId, text, true);
else await sendPrivateMessage(this.ctx, sessionId, text, true);
@@ -654,6 +685,21 @@ export class OneBotInstance {
}
}
export function makeBotStatusEvent(
selfId: number,
subType: 'online' | 'offline',
time = Math.floor(Date.now() / 1000),
): JsonObject {
return {
time,
self_id: selfId,
post_type: 'notice',
notice_type: 'bot_status',
sub_type: subType,
user_id: selfId,
};
}
function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'string' && value.trim()) {
+138 -25
View File
@@ -1,7 +1,7 @@
import { createLogger, runWithoutRequestContext } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { BridgeManager } from '@snowluma/core/manager';
import { loadOneBotConfig } from './config';
import { loadOneBotConfig, OneBotConfigValidationError } from './config';
import { loadGlobalSettings } from './global-config';
import { OneBotInstance } from './instance';
import type { MessageStoreMigrationStatus } from './message-store-migration';
@@ -9,7 +9,7 @@ import {
createMessageStoreMigrationTask,
estimateRemainingSeconds,
} from './message-store-migration-task';
import type { AdapterStatus, NetworkApplyError } from './network';
import type { AdapterStatus, NetworkApplyError, NetworkShutdownResult } from './network';
import type { OneBotConfig } from './types';
const log = createLogger('OneBot');
@@ -43,7 +43,43 @@ export interface DatabaseMigrationTask {
cancel(): void;
}
/** A peer that never finishes a close handshake must not keep the next
* account session offline. Ten seconds covers a normal drain.
* SNOWLUMA_SESSION_RELEASE_DEADLINE_MS overrides the configured value. */
const DEFAULT_SESSION_RELEASE_DEADLINE_MS = 10_000;
const SESSION_RELEASE_DEADLINE_ENV = 'SNOWLUMA_SESSION_RELEASE_DEADLINE_MS';
const MAX_SESSION_RELEASE_DEADLINE_MS = 2_147_483_647;
/** Positive integer milliseconds, or `undefined` when the raw value is absent
* or not usable. Callers decide the fallback. */
export function parseSessionReleaseDeadlineMs(raw: string | undefined): number | undefined {
if (raw === undefined) return undefined;
const value = raw.trim();
if (!/^[1-9]\d*$/.test(value)) return undefined;
const parsed = Number(value);
if (!Number.isSafeInteger(parsed) || parsed > MAX_SESSION_RELEASE_DEADLINE_MS) return undefined;
return parsed;
}
/** Env wins over an explicit deadline. An unusable env value is ignored. */
export function resolveSessionReleaseDeadlineMs(configured?: number, envRaw?: string): number {
const fromEnv = parseSessionReleaseDeadlineMs(envRaw);
if (fromEnv !== undefined) return fromEnv;
if (
configured !== undefined
&& Number.isSafeInteger(configured)
&& configured > 0
&& configured <= MAX_SESSION_RELEASE_DEADLINE_MS
) {
return configured;
}
return DEFAULT_SESSION_RELEASE_DEADLINE_MS;
}
export interface OneBotManagerOptions {
/** How long a retiring instance may block the replacement session.
* SNOWLUMA_SESSION_RELEASE_DEADLINE_MS overrides this when it is set. */
sessionReleaseDeadlineMs?: number;
createDatabaseMigrationTask?: (uin: string) => DatabaseMigrationTask;
createInstance?: (
uin: string,
@@ -91,8 +127,21 @@ export class OneBotManager {
private readonly createInstance: NonNullable<OneBotManagerOptions['createInstance']>;
private disposePromise: Promise<void> | null = null;
private disposed = false;
private readonly sessionReleaseDeadlineMs: number;
constructor(options: OneBotManagerOptions = {}) {
const envRaw = process.env[SESSION_RELEASE_DEADLINE_ENV];
if (envRaw !== undefined && envRaw.trim() && parseSessionReleaseDeadlineMs(envRaw) === undefined) {
log.warn(
'%s=%j is ignored; expected a positive integer number of milliseconds',
SESSION_RELEASE_DEADLINE_ENV,
envRaw,
);
}
this.sessionReleaseDeadlineMs = resolveSessionReleaseDeadlineMs(
options.sessionReleaseDeadlineMs,
envRaw,
);
this.createDatabaseMigrationTask = options.createDatabaseMigrationTask
?? createMessageStoreMigrationTask;
this.createInstance = options.createInstance
@@ -269,18 +318,22 @@ export class OneBotManager {
};
this.databaseMigrations.set(uin, migration);
const startTask = (): void => {
const handleFailure = (): void => {
const handleFailure = (error: unknown, stage = 'database migration'): void => {
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) return;
const retryable = !(error instanceof OneBotConfigValidationError);
const detail = error instanceof Error ? error.message : String(error);
const label = stage === 'session startup' ? '账号启动失败' : '数据库迁移失败';
migration.state = {
...migration.state,
phase: 'failed',
usable: migration.ready,
estimatedRemainingSeconds: null,
error: '数据库迁移失败,将自动重试',
error: `${label}:${detail}${retryable ? ';将自动重试' : ';请修正配置后重启'}`,
};
log.error('database migration failed: UIN=%s', uin);
log.error('%s failed: UIN=%s retryable=%s error=%s',
stage, uin, retryable, error instanceof Error ? (error.stack ?? error.message) : String(error));
migration.task.cancel();
if (migration.retryTimer) return;
if (!retryable || migration.retryTimer) return;
migration.retryTimer = setTimeout(() => {
migration.retryTimer = null;
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) return;
@@ -298,8 +351,8 @@ export class OneBotManager {
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) return;
try {
this.startSession(uin, bridge);
} catch {
handleFailure();
} catch (error) {
handleFailure(error, 'session startup');
return;
}
migration.ready = true;
@@ -311,8 +364,8 @@ export class OneBotManager {
};
try {
migration.task.beginMigration();
} catch {
handleFailure();
} catch (error) {
handleFailure(error);
}
},
onProgress: (status, elapsedMs) => {
@@ -330,8 +383,8 @@ export class OneBotManager {
},
onFailed: handleFailure,
});
} catch {
handleFailure();
} catch (error) {
handleFailure(error);
}
};
startTask();
@@ -351,10 +404,20 @@ export class OneBotManager {
this.instances.set(uin, instance);
log.info('session started: UIN=%s', uin);
this.trackLifecycle(`network startup UIN=${uin}`, instance.waitUntilNetworkReady().then((result) => {
this.trackLifecycle(`network startup UIN=${uin}`, instance.waitUntilNetworkReady().then(async (result) => {
if (result.applied) log.info('network startup applied: UIN=%s adapters=%d', uin, result.statuses.length);
else log.warn('network startup degraded: UIN=%s failures=%d', uin, result.errors.length);
instance.startGroupRequestPolling();
if (this.disposed || this.instances.get(uin) !== instance) return;
try {
await instance.emitBotStatus('online');
} catch (error) {
log.warn(
'bot_status online failed: UIN=%s: %s',
uin,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
}
}));
void this.armLoginHistorySync(uin, instance, bridge);
}
@@ -412,29 +475,79 @@ export class OneBotManager {
this.retiringInstances.add(instance);
this.trackLifecycle(
`network shutdown UIN=${uin}`,
instance.dispose().then((result) => {
this.retirementSucceeded(instance);
return result;
}),
this.emitOfflineThenDispose(instance),
[instance],
);
log.info('session closed: UIN=%s', uin);
}
private async emitOfflineThenDispose(instance: OneBotInstance): Promise<NetworkShutdownResult> {
try {
await instance.emitBotStatus('offline');
} catch (error) {
log.warn(
'bot_status offline failed: UIN=%s: %s',
instance.uin,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
}
const result = await instance.dispose();
this.retirementSucceeded(instance);
return result;
}
private async releaseRetiringInstance(
uin: string,
pending: { bridge: BridgeInterface; cancelled: boolean },
instance: OneBotInstance,
): Promise<void> {
let timer: NodeJS.Timeout | undefined;
const timeout = new Promise<'timeout'>((resolve) => {
timer = setTimeout(() => resolve('timeout'), this.sessionReleaseDeadlineMs);
timer.unref?.();
});
// Map rejection here so a dispose() that fails after the deadline still
// has a handler. The race may already have moved on.
const releasing = instance.dispose().then(
() => 'released' as const,
(error: unknown) => ({ failed: error }),
);
try {
const outcome = await Promise.race([releasing, timeout]);
if (outcome === 'timeout') {
log.error(
'session release timed out; forcing adapters closed and starting the replacement: UIN=%s',
uin,
);
try {
instance.forceRelease?.();
} catch (error) {
log.error(
'forced session release failed: UIN=%s: %s',
uin,
error instanceof Error ? error.message : String(error),
);
}
return;
}
if (typeof outcome === 'object') {
// Do not leave this UIN permanently guarded by a failed handoff. A
// later session-start observation may retry the still-visible retire.
if (this.pendingStarts.get(uin) === pending) this.pendingStarts.delete(uin);
throw new InstanceLifecycleError(instance, outcome.failed);
}
} finally {
if (timer) clearTimeout(timer);
}
}
private async finishRetiringBeforeStart(
uin: string,
pending: { bridge: BridgeInterface; cancelled: boolean },
retiring: OneBotInstance[],
): Promise<void> {
for (const instance of retiring) {
try {
await instance.dispose();
} catch (error) {
// Do not leave this UIN permanently guarded by a failed handoff. A
// later session-start observation may retry the still-visible retire.
if (this.pendingStarts.get(uin) === pending) this.pendingStarts.delete(uin);
throw new InstanceLifecycleError(instance, error);
}
await this.releaseRetiringInstance(uin, pending, instance);
this.retirementSucceeded(instance);
}
if (this.pendingStarts.get(uin) !== pending) return;
@@ -0,0 +1,82 @@
import fs from 'node:fs';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { createLogger } from '@snowluma/common/logger';
import { openSqliteDb } from './sqlite-open';
import { foldMediaKey, MediaStore, rollbackMediaTransaction, serializeMediaInfo } from './media-store';
const log = createLogger('OneBot.MediaMigration');
const BATCH_SIZE = 200;
/** Runs in the existing database worker, before the account is marked ready.
* Copy only: leave the old database (including its WAL) intact for recovery.
* Each committed batch advances its cursor in the destination transaction.
*/
export async function migrateLegacyMedia(
messageDbPath: string,
cancelled: () => boolean = () => false,
): Promise<void> {
const store = new MediaStore(messageDbPath);
store.close();
const destination = openSqliteDb(messageDbPath);
let source: DatabaseSync | undefined;
try {
destination.exec(`CREATE TABLE IF NOT EXISTS media_migration_state (
id INTEGER PRIMARY KEY CHECK (id = 1), phase TEXT NOT NULL, cursor INTEGER NOT NULL
); INSERT OR IGNORE INTO media_migration_state VALUES (1, 'entries', 0)`);
const state = destination.prepare('SELECT phase, cursor FROM media_migration_state WHERE id = 1')
.get() as { phase: string; cursor: number };
if (state.phase === 'complete') return;
const sourcePath = path.join(path.dirname(messageDbPath), 'media.db');
if (!fs.existsSync(sourcePath)) {
destination.exec("UPDATE media_migration_state SET phase = 'complete' WHERE id = 1");
return;
}
source = new DatabaseSync(sourcePath, { readOnly: true });
log.info('preserving legacy media metadata: migration started');
const insertEntry = destination.prepare(`INSERT INTO legacy_media_entries (type, primary_key, data, last_seen)
VALUES (?, ?, ?, ?) ON CONFLICT(type, primary_key) DO NOTHING`);
const insertKey = destination.prepare(`INSERT INTO legacy_media_keys (type, key, primary_key)
VALUES (?, ?, ?) ON CONFLICT(type, key) DO NOTHING`);
const saveState = destination.prepare('UPDATE media_migration_state SET phase = ?, cursor = ? WHERE id = 1');
while (!cancelled() && state.phase !== 'complete') {
const table = state.phase === 'entries' ? 'media_entries' : 'media_keys';
const rows = source.prepare(`SELECT rowid AS migration_rowid, * FROM ${table} WHERE rowid > ? ORDER BY rowid LIMIT ?`)
.all(state.cursor, BATCH_SIZE) as Array<{
migration_rowid: number; type: string; primary_key: string; data: string; last_seen: number; key: string;
}>;
const nextPhase = rows.length === 0 ? (state.phase === 'entries' ? 'keys' : 'complete') : state.phase;
const nextCursor = rows.at(-1)?.migration_rowid ?? 0;
destination.exec('BEGIN IMMEDIATE');
try {
for (const row of rows) {
if (!['image', 'record', 'video'].includes(row.type)) {
throw new Error(`unsupported legacy media type at row ${row.migration_rowid}`);
}
if (state.phase === 'entries') {
const info: unknown = JSON.parse(row.data);
if (!info || typeof info !== 'object' || Array.isArray(info)) {
throw new Error(`invalid legacy media metadata at row ${row.migration_rowid}`);
}
insertEntry.run(row.type, foldMediaKey(row.primary_key), serializeMediaInfo(info), row.last_seen);
} else {
insertKey.run(row.type, foldMediaKey(row.key), foldMediaKey(row.primary_key));
}
}
saveState.run(nextPhase, nextCursor);
destination.exec('COMMIT');
} catch (error) {
rollbackMediaTransaction(destination, error);
}
state.phase = nextPhase;
state.cursor = nextCursor;
log.debug('preserving legacy media metadata: phase=%s cursor=%d', state.phase, state.cursor);
// Yield between committed batches so cancellation is handled by the worker.
await new Promise<void>(resolve => setTimeout(resolve, 0));
}
if (!cancelled()) log.info('preserving legacy media metadata: migration complete; source retained');
} finally {
source?.close();
destination.close();
}
}
+164 -191
View File
@@ -1,4 +1,5 @@
import type { MessageElement } from '@snowluma/protocol/events';
import { createHash } from 'node:crypto';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import { openSqliteDb } from './sqlite-open';
@@ -59,220 +60,192 @@ const TYPE_IMAGE = 'image';
const TYPE_RECORD = 'record';
const TYPE_VIDEO = 'video';
const DEFAULT_KEEP_ENTRIES = 4096;
export type MediaLookupSource = 'current' | 'legacy';
/** SQLite keys / aliases longer than this are folded to a short digest. */
export const MEDIA_KEY_MAX_CHARS = 2048;
/** Persisted JSON must stay well under a page-overflow storm. */
export const MEDIA_DATA_MAX_CHARS = 64 * 1024;
const INLINE_MEDIA_SOURCE = /^(base64:\/\/|data:)/i;
/** Durable media metadata. Production shares messages.db with MessageStore.
* Only the in-memory lookup cache is bounded; history dependencies never expire.
*/
export class MediaStore {
private readonly db: DatabaseSync;
private readonly maxEntriesPerType: number;
// Prepared statements (pay the parsing cost once at startup).
private readonly cache = new Map<string, string>();
private readonly upsertEntry: StatementSync;
private readonly upsertKey: StatementSync;
private readonly findEntryByKey: StatementSync;
private readonly findEntryByPrimary: StatementSync;
private readonly evictByType: StatementSync;
private readonly purgeOrphanKeys: StatementSync;
private readonly countByType: StatementSync;
constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) {
this.maxEntriesPerType = Math.max(64, maxEntriesPerType);
private readonly findEntry: StatementSync;
private readonly findLegacyEntry: StatementSync;
constructor(dbPath: string, private readonly maxCachedEntries = DEFAULT_KEEP_ENTRIES) {
this.db = openSqliteDb(dbPath);
this.initSchema();
this.upsertEntry = this.db.prepare(
`INSERT INTO media_entries (type, primary_key, data, last_seen)
VALUES (?, ?, ?, ?)
ON CONFLICT(type, primary_key) DO UPDATE SET
data = excluded.data,
last_seen = excluded.last_seen`,
);
this.upsertKey = this.db.prepare(
`INSERT INTO media_keys (type, key, primary_key)
VALUES (?, ?, ?)
ON CONFLICT(type, key) DO UPDATE SET primary_key = excluded.primary_key`,
);
this.findEntryByKey = this.db.prepare(
`SELECT e.data FROM media_entries e
JOIN media_keys k ON k.type = e.type AND k.primary_key = e.primary_key
WHERE k.type = ? AND k.key = ?
LIMIT 1`,
);
this.findEntryByPrimary = this.db.prepare(
`SELECT data FROM media_entries WHERE type = ? AND primary_key = ?`,
);
this.evictByType = this.db.prepare(
// `rowid DESC` makes the tiebreaker match insertion order (newest first)
// so reproducible inserts within the same `last_seen` second still get
// the most recent rows retained, regardless of how the lexicographic
// sort would have ordered the synthetic primary_key.
`DELETE FROM media_entries WHERE type = ? AND rowid IN (
SELECT rowid FROM media_entries
WHERE type = ?
ORDER BY last_seen DESC, rowid DESC
LIMIT -1 OFFSET ?
)`,
);
this.purgeOrphanKeys = this.db.prepare(
`DELETE FROM media_keys WHERE type = ? AND primary_key NOT IN (
SELECT primary_key FROM media_entries WHERE type = ?
)`,
);
this.countByType = this.db.prepare(
`SELECT COUNT(*) AS n FROM media_entries WHERE type = ?`,
);
}
close(): void {
this.db.close();
}
rememberImage(info: CachedImage): void {
const primaryKey = pickPrimary([info.file, info.fileName]);
if (!primaryKey) return;
this.upsertWithAliases(TYPE_IMAGE, primaryKey, info, [info.file, info.fileName, info.url]);
}
rememberRecord(info: CachedRecord): void {
const primaryKey = pickPrimary([info.file, info.fileName, info.fileId]);
if (!primaryKey) return;
this.upsertWithAliases(TYPE_RECORD, primaryKey, info, [info.file, info.fileName, info.fileId, info.url]);
}
rememberVideo(info: CachedVideo): void {
const primaryKey = pickPrimary([info.file, info.fileName, info.fileId]);
if (!primaryKey) return;
this.upsertWithAliases(TYPE_VIDEO, primaryKey, info, [info.file, info.fileName, info.fileId, info.url]);
}
findImage(key: string): CachedImage | null {
return this.findByAnyKey<CachedImage>(TYPE_IMAGE, key);
}
findRecord(key: string): CachedRecord | null {
return this.findByAnyKey<CachedRecord>(TYPE_RECORD, key);
}
findVideo(key: string): CachedVideo | null {
return this.findByAnyKey<CachedVideo>(TYPE_VIDEO, key);
}
updateImageUrl(key: string, url: string): void {
if (!url) return;
const cached = this.findImage(key);
if (!cached || cached.url === url) return;
this.rememberImage({ ...cached, url });
}
updateRecordUrl(key: string, url: string): void {
if (!url) return;
const cached = this.findRecord(key);
if (!cached || cached.url === url) return;
this.rememberRecord({ ...cached, url });
}
updateVideoUrl(key: string, url: string): void {
if (!url) return;
const cached = this.findVideo(key);
if (!cached || cached.url === url) return;
this.rememberVideo({ ...cached, url });
}
/** Snapshot count of distinct entries per type; mostly used by tests. */
size(): { images: number; records: number; videos: number } {
const img = this.countByType.get(TYPE_IMAGE) as { n: number } | undefined;
const rec = this.countByType.get(TYPE_RECORD) as { n: number } | undefined;
const vid = this.countByType.get(TYPE_VIDEO) as { n: number } | undefined;
return { images: img?.n ?? 0, records: rec?.n ?? 0, videos: vid?.n ?? 0 };
}
// --- internals ---
private initSchema(): void {
this.db.exec(`
CREATE TABLE IF NOT EXISTS media_entries (
type TEXT NOT NULL,
primary_key TEXT NOT NULL,
data TEXT NOT NULL,
last_seen INTEGER NOT NULL,
PRIMARY KEY (type, primary_key)
);
CREATE INDEX IF NOT EXISTS idx_media_entries_lastseen
ON media_entries(type, last_seen DESC);
CREATE TABLE IF NOT EXISTS media_keys (
type TEXT NOT NULL,
key TEXT NOT NULL,
primary_key TEXT NOT NULL,
PRIMARY KEY (type, key)
);
CREATE INDEX IF NOT EXISTS idx_media_keys_primary
ON media_keys(type, primary_key);
for (const prefix of ['', 'legacy_']) {
this.db.exec(`
CREATE TABLE IF NOT EXISTS ${prefix}media_entries (
type TEXT NOT NULL, primary_key TEXT NOT NULL, data TEXT NOT NULL,
last_seen INTEGER NOT NULL, PRIMARY KEY (type, primary_key)
);
CREATE TABLE IF NOT EXISTS ${prefix}media_keys (
type TEXT NOT NULL, key TEXT NOT NULL, primary_key TEXT NOT NULL,
PRIMARY KEY (type, key)
);
`);
}
this.upsertEntry = this.db.prepare(`
INSERT INTO media_entries (type, primary_key, data, last_seen) VALUES (?, ?, ?, ?)
ON CONFLICT(type, primary_key) DO UPDATE SET data = excluded.data, last_seen = excluded.last_seen
`);
this.upsertKey = this.db.prepare(`
INSERT INTO media_keys (type, key, primary_key) VALUES (?, ?, ?)
ON CONFLICT(type, key) DO UPDATE SET primary_key = excluded.primary_key
`);
this.findEntry = this.db.prepare(`
SELECT data FROM media_entries WHERE type = ? AND primary_key = COALESCE(
(SELECT primary_key FROM media_keys WHERE type = ? AND key = ?), ?
)
`);
this.findLegacyEntry = this.db.prepare(`
SELECT data FROM legacy_media_entries WHERE type = ? AND primary_key = COALESCE(
(SELECT primary_key FROM legacy_media_keys WHERE type = ? AND key = ?), ?
)
`);
}
private upsertWithAliases<T>(
type: string,
primaryKey: string,
info: T,
aliases: (string | undefined)[],
): void {
const data = JSON.stringify(info);
const lastSeen = Math.floor(Date.now() / 1000);
close(): void { this.cache.clear(); this.db.close(); }
// Run the writes in a transaction so concurrent readers always see a
// consistent (entry, keys) pair.
this.db.exec('BEGIN');
rememberImage(info: CachedImage): void {
this.remember(TYPE_IMAGE, info, [info.file, info.fileName, info.url]);
}
rememberRecord(info: CachedRecord): void {
this.remember(TYPE_RECORD, info, [info.file, info.fileName, info.fileId, info.url]);
}
rememberVideo(info: CachedVideo): void {
this.remember(TYPE_VIDEO, info, [info.file, info.fileName, info.fileId, info.url]);
}
findImage(key: string, source: MediaLookupSource = 'current'): CachedImage | null {
return this.find(TYPE_IMAGE, key, source);
}
findRecord(key: string, source: MediaLookupSource = 'current'): CachedRecord | null {
return this.find(TYPE_RECORD, key, source);
}
findVideo(key: string, source: MediaLookupSource = 'current'): CachedVideo | null {
return this.find(TYPE_VIDEO, key, source);
}
updateImageUrl(key: string, url: string): void { this.updateUrl(TYPE_IMAGE, key, url); }
updateRecordUrl(key: string, url: string): void { this.updateUrl(TYPE_RECORD, key, url); }
updateVideoUrl(key: string, url: string): void { this.updateUrl(TYPE_VIDEO, key, url); }
/** Counts durable records, not the bounded lookup cache. */
size(): { images: number; records: number; videos: number } {
const counts = this.db.prepare(`SELECT type, COUNT(*) AS n FROM (
SELECT type FROM media_entries UNION ALL SELECT type FROM legacy_media_entries
) GROUP BY type`)
.all() as Array<{ type: string; n: number }>;
const count = (type: string) => counts.find(row => row.type === type)?.n ?? 0;
return { images: count(TYPE_IMAGE), records: count(TYPE_RECORD), videos: count(TYPE_VIDEO) };
}
private remember(type: string, info: object, aliases: string[]): void {
const primary = pickPrimary(aliases);
if (!primary) throw new Error(`cannot store ${type} metadata without an identifier`);
const data = serializeMediaInfo(info);
this.db.exec('BEGIN IMMEDIATE');
try {
this.upsertEntry.run(type, primaryKey, data, lastSeen);
const seen = new Set<string>();
for (const raw of aliases) {
if (!raw) continue;
if (seen.has(raw)) continue;
seen.add(raw);
this.upsertKey.run(type, raw, primaryKey);
this.upsertEntry.run(type, primary, data, Math.floor(Date.now() / 1000));
for (const key of new Set(aliases.filter(Boolean).map(foldMediaKey))) {
this.upsertKey.run(type, key, primary);
}
this.db.exec('COMMIT');
} catch (err) {
try { this.db.exec('ROLLBACK'); } catch { /* ignore */ }
throw err;
} catch (error) {
rollbackMediaTransaction(this.db, error);
}
// Eager eviction. The DELETE is a no-op when row count <= cap so
// there is no measurable cost while we are below the limit.
this.evictOldEntries(type);
// Alias remapping can invalidate any cached lookup. JSON strings ensure
// callers cannot mutate the durable record through a returned object.
this.cache.clear();
}
private findByAnyKey<T>(type: string, key: string): T | null {
if (!key) return null;
const row = this.findEntryByKey.get(type, key) as { data: string } | undefined;
if (row?.data) return safeParse<T>(row.data);
// Fall back to looking up by primary_key directly so callers that pass
// the canonical identifier still hit (e.g. when the alias index is yet
// to be built for that key in this session).
const fallback = this.findEntryByPrimary.get(type, key) as { data: string } | undefined;
return fallback?.data ? safeParse<T>(fallback.data) : null;
}
private evictOldEntries(type: string): void {
try {
this.evictByType.run(type, type, this.maxEntriesPerType);
this.purgeOrphanKeys.run(type, type);
} catch {
// Best-effort eviction; don't propagate.
private find<T>(type: string, key: string, source: MediaLookupSource = 'current'): T | null {
const lookup = foldMediaKey(key);
if (!lookup) return null;
const cacheKey = `${source}:${type}:${lookup}`;
let data = this.cache.get(cacheKey);
if (data === undefined) {
// Legacy history has no per-message snapshots. Its frozen migration
// index must never resolve through a later, mutable filename alias.
const current = source === 'current' ? this.findEntry.get(type, type, lookup, lookup) : undefined;
const row = (current ?? this.findLegacyEntry.get(type, type, lookup, lookup)) as { data: string } | undefined;
if (!row) return null;
data = row.data;
}
// Parse before caching: malformed persisted metadata is an observable error.
const result: unknown = JSON.parse(data);
if (!result || typeof result !== 'object' || Array.isArray(result)) {
throw new Error(`invalid persisted ${type} metadata`);
}
this.cache.delete(cacheKey);
this.cache.set(cacheKey, data);
while (this.cache.size > Math.max(0, this.maxCachedEntries)) {
this.cache.delete(this.cache.keys().next().value!);
}
return result as T;
}
private updateUrl(type: string, key: string, url: string): void {
if (!url || mustFoldMediaKey(url)) return;
const info = this.find<Record<string, unknown>>(type, key);
if (!info || info.url === url) return;
this.remember(type, { ...info, url }, [info.file, info.fileName, info.fileId, url]
.filter((value): value is string => typeof value === 'string'));
}
}
export function serializeMediaInfo(info: object): string {
const data = JSON.stringify(persistableMediaInfo(info));
if (data.length > MEDIA_DATA_MAX_CHARS) {
throw new Error(`media metadata exceeds storage limit (${data.length} characters)`);
}
return data;
}
export function rollbackMediaTransaction(db: DatabaseSync, error: unknown): never {
try { db.exec('ROLLBACK'); }
catch (rollbackError) {
throw new AggregateError([error, rollbackError], 'media write and rollback failed', { cause: error });
}
throw error;
}
function mustFoldMediaKey(value: string): boolean {
return value.length > MEDIA_KEY_MAX_CHARS || INLINE_MEDIA_SOURCE.test(value);
}
export function foldMediaKey(value: string): string {
if (!value) return '';
if (!mustFoldMediaKey(value)) return value;
return `inline:${createHash('sha256').update(value).digest('hex')}`;
}
function persistableMediaInfo(info: object): Record<string, unknown> {
const next: Record<string, unknown> = { ...info };
for (const field of ['file', 'fileId', 'fileName'] as const) {
const value = next[field];
if (typeof value === 'string') next[field] = foldMediaKey(value);
}
for (const field of ['url', 'imageUrl'] as const) {
const value = next[field];
if (typeof value === 'string' && mustFoldMediaKey(value)) next[field] = '';
}
return next;
}
function pickPrimary(candidates: (string | undefined)[]): string {
for (const c of candidates) {
if (c && c.length > 0) return c;
if (c && c.length > 0) return foldMediaKey(c);
}
return '';
}
function safeParse<T>(json: string): T | null {
try {
return JSON.parse(json) as T;
} catch {
return null;
}
}
+95
View File
@@ -0,0 +1,95 @@
import type { MessageElement } from '@snowluma/protocol/events';
import { serializeMediaInfo } from './media-store';
import type { JsonObject } from './types';
export type MessageMedia = Extract<MessageElement, { type: 'image' | 'record' | 'video' }>;
const mediaSnapshot = Symbol('message media snapshot');
type MediaSegment = JsonObject & { [mediaSnapshot]?: MessageMedia };
export function isMessageMedia(element: MessageElement): element is MessageMedia {
return element.type === 'image' || element.type === 'record' || element.type === 'video';
}
/** Keep persistence-only metadata beside the converted segment, never on the
* public JSON wire. Capture after successful conversion so skipped elements
* cannot shift the association between a message and its media snapshots.
*/
export function attachMessageMedia(segment: JsonObject, element: MessageElement): void {
if (!isMessageMedia(element)) return;
const { type, fileId, fileName, fileSize, url, imageUrl, md5Hex, sha1Hex,
subType, summary, width, height, picFormat, duration, voiceFormat,
videoFormat, fileHash, mediaNode, flash } = element;
const snapshot = JSON.parse(serializeMediaInfo({
type, fileId, fileName, fileSize, url, imageUrl, md5Hex, sha1Hex,
subType, summary, width, height, picFormat, duration, voiceFormat,
videoFormat, fileHash, mediaNode, flash,
})) as MessageMedia;
Object.defineProperty(segment, mediaSnapshot, { value: snapshot });
}
export function serializeMessageMedia(event: JsonObject): string | null {
if (!Array.isArray(event.message)) return null;
const snapshots = event.message.flatMap(segment => {
if (!segment || typeof segment !== 'object' || Array.isArray(segment)) return [];
const snapshot = (segment as MediaSegment)[mediaSnapshot];
return snapshot ? [snapshot] : [];
});
return snapshots.length > 0 ? JSON.stringify(snapshots) : null;
}
export function parseMessageMedia(data: string): MessageMedia[] {
const parsed: unknown = JSON.parse(data);
if (!Array.isArray(parsed) || parsed.some(value => !value || typeof value !== 'object'
|| !['image', 'record', 'video'].includes(value.type))) {
throw new Error('invalid persisted message media metadata');
}
return parsed as MessageMedia[];
}
/** A repeated server representation may omit fields already learned from an
* upload or earlier receive. Preserve those fields only for the same resource;
* conflicting fingerprints or uncertain associations must not rewrite history.
*/
export function mergeMessageMedia(previous: string | null, next: string | null): string | null {
if (!previous) return next;
if (previous === next) return previous;
if (!next) throw new Error('message update is missing previously stored media metadata');
const oldMedia = parseMessageMedia(previous);
const newMedia = parseMessageMedia(next);
if (oldMedia.length !== newMedia.length) throw new Error('message media association changed');
const merged = newMedia.map((media, index) => {
const old = oldMedia[index]!;
if (old.type !== media.type) throw new Error('message media association changed');
let matched = false;
for (const field of ['md5Hex', 'sha1Hex'] as const) {
if (!old[field] || !media[field]) continue;
if (old[field].toLowerCase() !== media[field].toLowerCase()) {
throw new Error('message update has conflicting media fingerprints');
}
matched = true;
}
// Images can expose a filename as fileId, so only their fingerprints can
// prove an association. Voice/video fileId is a source resource UUID.
matched ||= media.type !== 'image' && !!old.fileId && old.fileId === media.fileId;
if (!matched && JSON.stringify(old) !== JSON.stringify(media)) {
throw new Error('message update has an unverified media association');
}
return mergeKnownMediaFields(old, media);
});
return JSON.stringify(merged);
}
function mergeKnownMediaFields(old: object, next: object): Record<string, unknown> {
const merged: Record<string, unknown> = { ...old };
for (const [key, value] of Object.entries(next)) {
// Zero dimensions, sizes and durations are incomplete observations, not
// evidence that known properties of the same resource have changed.
if (value === undefined || value === null || value === '' || value === 0) continue;
const previous = merged[key];
merged[key] = typeof value === 'object' && !Array.isArray(value)
&& previous !== null && typeof previous === 'object' && !Array.isArray(previous)
? mergeKnownMediaFields(previous, value)
: value;
}
return merged;
}
+1
View File
@@ -22,6 +22,7 @@ export interface ParseMessageOptions {
senderUin: number;
time: number;
random: number;
elements?: MessageElement[];
sequenceAuthoritative?: boolean;
} | null;
resolveMentionUid?: (targetUin: number) => string | null | Promise<string | null>;
@@ -1,6 +1,7 @@
import { createRequire } from 'node:module';
import path from 'node:path';
import { Worker, type WorkerOptions } from 'node:worker_threads';
import { createLogger } from '@snowluma/common/logger';
import type {
DatabaseMigrationCallbacks,
DatabaseMigrationTask,
@@ -29,6 +30,7 @@ export function createMessageStoreMigrationTask(
uin: string,
createWorker: CreateMigrationWorker = (filename, options) => new Worker(filename, options),
): DatabaseMigrationTask {
const log = createLogger('OneBot.MessageMigration').child({ uin: Number(uin) });
let worker: MessageStoreMigrationWorkerHandle | null = null;
let cancelled = false;
let finished = false;
@@ -59,6 +61,15 @@ export function createMessageStoreMigrationTask(
if (cancelled) return;
if (message.kind === 'ready') {
callbacks.onReady();
} else if (message.kind === 'preparation') {
const progress = message.progress;
if (progress.stage === 'started') {
log.info('preparing message history migration');
} else if (progress.stage === 'indexed') {
log.info('message history migration preparation finished in %dms', Math.round(progress.elapsedMs));
} else {
log.info('message history migration: pending=%d checked in %dms', progress.total, Math.round(progress.elapsedMs));
}
} else if (message.kind === 'progress') {
callbacks.onProgress(message.status, message.elapsedMs);
if (message.status.phase === 'complete') finished = true;
@@ -1,7 +1,9 @@
import { parentPort, workerData } from 'node:worker_threads';
import { migrateLegacyMedia } from './media-store-migration';
import {
MessageStoreMigrator,
prepareMessageStoreDatabase,
type MessageStoreMigrationPreparation,
type MessageStoreMigrationStatus,
} from './message-store-migration';
@@ -16,6 +18,7 @@ export interface MessageStoreMigrationWorkerData {
export type MessageStoreMigrationWorkerMessage =
| { kind: 'ready' }
| { kind: 'preparation'; progress: MessageStoreMigrationPreparation }
| {
kind: 'progress';
status: MessageStoreMigrationStatus;
@@ -49,10 +52,14 @@ export async function runMessageStoreMigrationWorker(
try {
prepareMessageStoreDatabase(data.dbPath);
await migrateLegacyMedia(data.dbPath, () => cancelled);
if (cancelled) return;
port.postMessage({ kind: 'ready' } satisfies MessageStoreMigrationWorkerMessage);
await startRequested;
if (cancelled) return;
migrator = new MessageStoreMigrator(data.dbPath);
migrator = new MessageStoreMigrator(data.dbPath, progress => {
port.postMessage({ kind: 'preparation', progress } satisfies MessageStoreMigrationWorkerMessage);
});
let lastProgressAt: number | null = null;
while (!cancelled) {
+62 -36
View File
@@ -2,6 +2,7 @@ import { DatabaseSync, type StatementSync } from 'node:sqlite';
import { openSqliteDb } from './sqlite-open';
const CLASSIFICATION_VERSION = 1;
const PENDING_INDEX_NAME = `idx_messages_pending_classification_v${CLASSIFICATION_VERSION}`;
const MIGRATION_NAME = 'message-classification-v1';
const LEGACY_PRIVATE_SEQUENCE_MIGRATION = 'private-nt-sequence-v1';
@@ -13,6 +14,11 @@ export interface MessageStoreMigrationStatus {
total: number;
}
export type MessageStoreMigrationPreparation =
| { stage: 'started' }
| { stage: 'indexed'; elapsedMs: number }
| { stage: 'counted'; total: number; elapsedMs: number };
interface MigrationStateRow {
phase: MessageStoreMigrationPhase;
processed: number;
@@ -39,42 +45,47 @@ export class MessageStoreMigrator {
private readonly updateState: StatementSync;
private state: MigrationStateRow;
constructor(dbPath: string) {
constructor(dbPath: string, reportPreparation?: (progress: MessageStoreMigrationPreparation) => void) {
this.db = openSqliteDb(dbPath.replace(/\.json$/, '.db'));
createMigrationStateTable(this.db);
this.state = this.loadOrCreateState();
this.selectInitialBatch = this.db.prepare(`
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
FROM messages
WHERE classification_version < ?
ORDER BY message_hash ASC
LIMIT ?
`);
this.selectNextBatch = this.db.prepare(`
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
FROM messages
WHERE classification_version < ? AND message_hash > ?
ORDER BY message_hash ASC
LIMIT ?
`);
this.updateRow = this.db.prepare(`
UPDATE messages
SET sequence_authoritative = ?, private_direction = ?, classification_version = ?
WHERE message_hash = ?
AND classification_version < ?
AND is_group = ?
AND sequence = ?
AND sequence_authoritative = ?
AND client_sequence = ?
AND private_direction = ?
AND random = ?
AND data IS ?
`);
this.updateState = this.db.prepare(`
UPDATE message_store_migration_state
SET phase = ?, processed = ?, total = ?, cursor = ?, updated_at = ?
WHERE name = ?
`);
try {
createMigrationStateTable(this.db);
this.state = this.loadOrCreateState(reportPreparation);
this.selectInitialBatch = this.db.prepare(`
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
FROM messages
WHERE classification_version < ?
ORDER BY message_hash ASC
LIMIT ?
`);
this.selectNextBatch = this.db.prepare(`
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
FROM messages
WHERE classification_version < ? AND message_hash > ?
ORDER BY message_hash ASC
LIMIT ?
`);
this.updateRow = this.db.prepare(`
UPDATE messages
SET sequence_authoritative = ?, private_direction = ?, classification_version = ?
WHERE message_hash = ?
AND classification_version < ?
AND is_group = ?
AND sequence = ?
AND sequence_authoritative = ?
AND client_sequence = ?
AND private_direction = ?
AND random = ?
AND data IS ?
`);
this.updateState = this.db.prepare(`
UPDATE message_store_migration_state
SET phase = ?, processed = ?, total = ?, cursor = ?, updated_at = ?
WHERE name = ?
`);
} catch (error) {
this.db.close();
throw error;
}
}
close(): void {
@@ -153,20 +164,32 @@ export class MessageStoreMigrator {
return this.getStatus();
}
private loadOrCreateState(): MigrationStateRow {
private loadOrCreateState(reportPreparation?: (progress: MessageStoreMigrationPreparation) => void): MigrationStateRow {
const existing = this.db.prepare(`
SELECT phase, processed, total, cursor
FROM message_store_migration_state
WHERE name = ?
`).get(MIGRATION_NAME) as MigrationStateRow | undefined;
if (existing?.phase === 'complete') return existing;
reportPreparation?.({ stage: 'started' });
const preparationStartedAt = performance.now();
this.db.exec(`
CREATE INDEX IF NOT EXISTS ${PENDING_INDEX_NAME}
ON messages(message_hash, classification_version)
WHERE classification_version < ${CLASSIFICATION_VERSION}
`);
reportPreparation?.({ stage: 'indexed', elapsedMs: Math.max(0, performance.now() - preparationStartedAt) });
if (existing) return existing;
const countStartedAt = performance.now();
const row = this.db.prepare(`
SELECT COUNT(*) AS total
FROM messages
WHERE classification_version < ?
`).get(CLASSIFICATION_VERSION) as { total: number };
const total = Number(row.total);
reportPreparation?.({ stage: 'counted', total, elapsedMs: Math.max(0, performance.now() - countStartedAt) });
const now = Math.floor(Date.now() / 1000);
const state: MigrationStateRow = {
phase: total === 0 ? 'complete' : 'migrating',
@@ -279,6 +302,9 @@ export function inspectMessageStoreMigration(dbPath: string): MessageStoreMigrat
export function prepareMessageStoreSchema(db: DatabaseSync): void {
const before = db.prepare('PRAGMA table_info(messages)').all() as Array<{ name: string }>;
const existingColumns = new Set(before.map((column) => column.name));
if (!existingColumns.has('media_data')) {
db.exec('ALTER TABLE messages ADD COLUMN media_data TEXT');
}
const existingRowsAreCurrent = existingColumns.has('sequence_authoritative')
&& existingColumns.has('private_direction')
&& hasLegacyPrivateSequenceMigration(db);
+152 -17
View File
@@ -1,7 +1,10 @@
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import { createLogger } from '@snowluma/common/logger';
import type { JsonObject, MessageMeta } from './types';
import type { MessageElement } from '@snowluma/protocol/events';
import { cqUnescape } from './helper/cq';
import { openSqliteDb } from './sqlite-open';
import { mergeMessageMedia, parseMessageMedia, serializeMessageMedia, type MessageMedia } from './message-media';
import {
createMessageStoreIndexes,
prepareMessageStoreSchema,
@@ -32,6 +35,7 @@ export class MessageStore {
private readonly stmtStoreEvent: StatementSync;
private readonly stmtStoreMeta: StatementSync;
private readonly stmtFindEvent: StatementSync;
private readonly stmtFindMedia: StatementSync;
private readonly stmtFindMeta: StatementSync;
private readonly stmtResolveReplyGroup: StatementSync;
private readonly stmtResolveReplyPrivate: StatementSync;
@@ -43,6 +47,8 @@ export class MessageStore {
private readonly stmtListIncomingC2CSessions: StatementSync;
private readonly stmtFindPrivateRecall: StatementSync;
private readonly stmtFindPrivateMessageAtTime: StatementSync;
private readonly stmtFindPrivateMessageBySequence: StatementSync;
private readonly stmtFindPrivateOutgoingNearTime: StatementSync;
private readonly stmtFindPrivateRecallTombstone: StatementSync;
private readonly stmtUpsertPrivateRecallTombstone: StatementSync;
private readonly stmtDeleteMessage: StatementSync;
@@ -57,8 +63,8 @@ export class MessageStore {
// Database instance — `close()` finalizes them automatically.
this.stmtStoreEvent = this.db.prepare(
`INSERT INTO messages
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp, data, classification_version)
VALUES (?, ?, ?, ?, ?, ?, 0, ?, 0, ?, ?, 1)
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp, data, media_data, classification_version)
VALUES (?, ?, ?, ?, ?, ?, 0, ?, 0, ?, ?, ?, 1)
ON CONFLICT(message_hash) DO UPDATE SET
is_group = excluded.is_group,
session_id = excluded.session_id,
@@ -74,6 +80,7 @@ export class MessageStore {
END,
timestamp = excluded.timestamp,
data = excluded.data,
media_data = excluded.media_data,
classification_version = CASE
WHEN excluded.is_group = 1 THEN excluded.classification_version
ELSE messages.classification_version
@@ -101,6 +108,8 @@ export class MessageStore {
'SELECT data FROM messages WHERE message_hash = ? AND data IS NOT NULL',
);
this.stmtFindMedia = this.db.prepare('SELECT media_data FROM messages WHERE message_hash = ?');
this.stmtFindMeta = this.db.prepare(
'SELECT is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp FROM messages WHERE message_hash = ?',
);
@@ -189,13 +198,28 @@ export class MessageStore {
);
this.stmtFindPrivateMessageAtTime = this.db.prepare(
`SELECT message_hash, data
FROM messages
WHERE is_group = 0 AND session_id = ? AND private_direction = ? AND timestamp = ?`,
);
this.stmtFindPrivateMessageBySequence = this.db.prepare(
`SELECT message_hash
FROM messages
WHERE is_group = 0 AND session_id = ? AND private_direction = ? AND timestamp = ?
ORDER BY sequence DESC
WHERE is_group = 0 AND session_id = ? AND sequence = ?
AND private_direction = ? AND sequence_authoritative = 1
LIMIT 1`,
);
this.stmtFindPrivateOutgoingNearTime = this.db.prepare(
`SELECT message_hash
FROM messages
WHERE is_group = 0 AND session_id = ? AND private_direction = ?
AND timestamp BETWEEN ? AND ?
ORDER BY ABS(timestamp - ?) ASC, sequence DESC
LIMIT 2`,
);
this.stmtFindPrivateRecallTombstone = this.db.prepare(
`SELECT recalled_at
FROM private_recall_tombstones
@@ -256,6 +280,8 @@ export class MessageStore {
}
}
const previous = this.stmtFindMedia.get(messageId) as { media_data: string | null } | undefined;
const media = mergeMessageMedia(previous?.media_data ?? null, serializeMessageMedia(event));
this.stmtStoreEvent.run(
messageId,
isGroup ? 1 : 0,
@@ -266,9 +292,16 @@ export class MessageStore {
privateDirection,
timestamp,
json,
media,
);
}
findMedia(messageId: number): MessageMedia[] | null {
if (!isValidMessageId(messageId)) return null;
const row = this.stmtFindMedia.get(messageId) as { media_data: string | null } | undefined;
return row?.media_data != null ? parseMessageMedia(row.media_data) : null;
}
storeMeta(messageId: number, meta: MessageMeta): void {
if (!isValidMessageId(messageId)) return;
const privateDirection = encodePrivateDirection(meta.privateDirection);
@@ -485,44 +518,88 @@ export class MessageStore {
/**
* Resolve a private quote to a stored OneBot id. Prefer the quoted
* sender-local sequence; for a self-sent target, also match the send
* receipt's timestamp because QQ's quote sequence is not the local
* client sequence recorded at send time.
* sender-local sequence, then the conversation sequence. For a
* self-sent target, also match the send receipt by time because QQ's
* quote sequence is often neither of those stored values, and the
* quote time can drift a few seconds from the send receipt.
*/
resolvePrivateReplyMessageId(
sessionId: number,
replySequence: number,
sentBySelf: boolean,
timestamp?: number,
replyElements?: readonly MessageElement[],
): number | null {
if (Number.isSafeInteger(replySequence) && replySequence > 0) {
const bySequence = this.findPrivateMessageId(
const byClientSequence = this.findPrivateMessageId(
sessionId,
replySequence,
sentBySelf,
timestamp,
);
if (bySequence !== null) return bySequence;
}
if (sentBySelf && timestamp !== undefined) {
return this.findPrivateMessageIdAtTime(sessionId, true, timestamp);
if (byClientSequence !== null) return byClientSequence;
const byConversationSequence = this.findPrivateMessageIdBySequence(
sessionId,
replySequence,
sentBySelf,
);
if (byConversationSequence !== null) return byConversationSequence;
}
if (!sentBySelf) return null;
const byExactTime = this.findPrivateMessageIdAtTime(sessionId, true, timestamp, replyElements);
if (byExactTime !== null) return byExactTime;
const byNearbyTime = this.findUniquePrivateOutgoingNearTime(sessionId, timestamp);
if (byNearbyTime !== null) return byNearbyTime;
return null;
}
findPrivateMessageIdAtTime(
sessionId: number,
sentBySelf: boolean,
timestamp: number,
timestamp?: number,
replyElements?: readonly MessageElement[],
): number | null {
if (!Number.isSafeInteger(sessionId) || sessionId <= 0) return null;
if (!Number.isSafeInteger(timestamp) || timestamp <= 0 || timestamp >= Number.MAX_SAFE_INTEGER) {
return null;
}
const row = this.stmtFindPrivateMessageAtTime.get(
if (!isUsablePrivateQuoteTime(timestamp)) return null;
const rows = this.stmtFindPrivateMessageAtTime.all(
sessionId,
sentBySelf ? 1 : 0,
timestamp,
) as { message_hash: number; data: string | null }[];
if (rows.length === 0) return null;
let matches = rows;
if (rows.length > 1) {
const text = replyElements?.length && replyElements.every(e => e.type === 'text')
? replyElements.map(e => e.text ?? '').join('')
: null;
const candidates = text ? rows.map(row => ({ row, preview: cachedQuoteText(row.data) }))
.filter(({ preview }) => preview === null || preview.text.startsWith(text)) : [];
matches = candidates.length === 1 && candidates[0]!.preview?.plain
&& candidates[0]!.preview.text === text ? [candidates[0]!.row] : [];
if (matches.length !== 1) {
log.debug('private quote time is ambiguous: peer=%d time=%d candidates=%d contentMatches=%d',
sessionId, timestamp, rows.length, matches.length);
return null;
}
}
const row = matches[0]!;
if (!isValidMessageId(row.message_hash)) {
throw new Error(`private message lookup matched invalid message id ${String(row.message_hash)}`);
}
return row.message_hash;
}
findPrivateMessageIdBySequence(
sessionId: number,
sequence: number,
sentBySelf: boolean,
): number | null {
if (!Number.isSafeInteger(sessionId) || sessionId <= 0) return null;
if (!Number.isSafeInteger(sequence) || sequence <= 0) return null;
const row = this.stmtFindPrivateMessageBySequence.get(
sessionId,
sequence,
sentBySelf ? 1 : 0,
) as { message_hash: number } | undefined;
if (!row) return null;
if (!isValidMessageId(row.message_hash)) {
@@ -531,6 +608,29 @@ export class MessageStore {
return row.message_hash;
}
findUniquePrivateOutgoingNearTime(
sessionId: number,
timestamp?: number,
): number | null {
if (!Number.isSafeInteger(sessionId) || sessionId <= 0) return null;
if (!isUsablePrivateQuoteTime(timestamp)) return null;
for (const windowSeconds of PRIVATE_REPLY_TIME_WINDOWS_SECONDS) {
const rows = this.stmtFindPrivateOutgoingNearTime.all(
sessionId,
1,
timestamp - windowSeconds,
timestamp + windowSeconds,
timestamp,
) as Array<{ message_hash: number }>;
if (rows.length !== 1) continue;
if (!isValidMessageId(rows[0].message_hash)) {
throw new Error(`private message lookup matched invalid message id ${String(rows[0].message_hash)}`);
}
return rows[0].message_hash;
}
return null;
}
listSessionEvents(
isGroup: boolean,
sessionId: number,
@@ -752,6 +852,41 @@ function eventPrivateDirection(isGroup: boolean, event: JsonObject): number {
return -1;
}
const PRIVATE_REPLY_TIME_WINDOWS_SECONDS = [5, 30] as const;
/** Unknown, truncated, and media previews remain possible competing matches. */
function cachedQuoteText(data: string | null): { text: string; plain: boolean } | null {
if (!data) return null;
const event = JSON.parse(data) as JsonObject;
if (typeof event.message === 'string') {
return event.message.includes('[CQ:') ? null : { text: cqUnescape(event.message), plain: true };
}
if (!Array.isArray(event.message) || event.message.length === 0) return null;
const segments = event.message as JsonObject[];
const labels: Record<string, string> = {
image: '[图片]', record: '[语音]', video: '[视频]', file: '[文件]',
face: '[表情]', mface: '[表情]', forward: '[聊天记录]', json: '[卡片]', xml: '[卡片]',
};
const parts: string[] = [];
let plain = true;
for (const segment of segments) {
const body = segment?.data as JsonObject | undefined;
if (segment?.type === 'text' && typeof body?.text === 'string') parts.push(body.text);
else if (typeof segment?.type === 'string' && labels[segment.type]) {
parts.push(typeof body?.summary === 'string' ? body.summary : labels[segment.type]!);
plain = false;
} else return null;
}
return { text: parts.join(''), plain };
}
function isUsablePrivateQuoteTime(timestamp: number | undefined): timestamp is number {
return timestamp !== undefined
&& Number.isSafeInteger(timestamp)
&& timestamp > 0
&& timestamp < Number.MAX_SAFE_INTEGER;
}
function validatePrivateRecallKey(
sessionId: number,
clientSequence: number,
+33 -3
View File
@@ -101,6 +101,9 @@ export async function getGroupList(
group_create_time: g.createTime ?? 0,
group_level: g.level ?? 0,
group_memo: g.memo ?? '',
// #490: the description is its own field; group_memo prefers the
// announcement, so it can't be used to recover the description.
group_description: g.description ?? '',
group_all_shut: g.allMuted ? -1 : 0,
}));
}
@@ -175,6 +178,7 @@ export async function getGroupInfo(
group_create_time: g.createTime ?? 0,
group_level: await getGroupLevel(bridge, groupId, noCache),
group_memo: g.memo ?? '',
group_description: g.description ?? '',
group_all_shut: g.allMuted ? -1 : 0,
};
}
@@ -198,6 +202,10 @@ export async function getGroupInfo(
group_create_time: detail.createTime ?? 0,
group_level: detail.level ?? 0,
group_memo: detail.memo ?? '',
// #490: always '' here — the non-member detail lookup has no
// description to read (see QQGroupInfo.description). The key is still
// returned so the response shape doesn't change with membership.
group_description: detail.description ?? '',
group_all_shut: detail.allMuted ? -1 : 0,
};
nonMemberGroupCache.set(cacheKey, { info, at: Date.now() });
@@ -256,11 +264,12 @@ export async function getGroupMemberInfo(
// 企点标志(#404 后续 PR):优先读身份缓存,无缓存时再按需拉取一次用户资料。
// 均为 best-effort —— 失败时回退为 0,不影响成员信息主流程。
let profile = cachedQidianProfile(bridge, userId);
if (!profile) {
if (noCache || !profile) {
try {
profile = await bridge.apis.contacts.fetchUserProfile(userId);
} catch {
// profile enrichment is best-effort; fall back to all-zero flags
} catch (error) {
log.warn('group member profile unavailable: group=%d member=%d error=%s',
groupId, userId, error instanceof Error ? error.message : String(error));
}
}
return formatGroupMember(groupId, m, profile ?? undefined);
@@ -304,13 +313,20 @@ export async function getGroupFiles(
function formatStrangerInfo(p: UserProfileInfo, corp?: QidianCorpInfo | null): JsonObject {
return {
user_id: p.uin,
uid: p.uid,
qid: p.qid,
nickname: p.nickname,
remark: p.remark,
sex: p.sex,
age: p.age,
long_nick: p.sign,
qq_level: p.level,
qqLevel: p.level,
level: p.level,
...(p.regTime !== undefined ? { reg_time: p.regTime } : {}),
...(p.svipFlag !== undefined ? { is_vip: p.svipFlag } : {}),
...(p.yearVipFlag !== undefined ? { is_years_vip: p.yearVipFlag } : {}),
...(p.vipLevel !== undefined ? { vip_level: p.vipLevel } : {}),
status: p.status ?? 0,
extStatus: p.extStatus ?? 0,
ext_status: p.extStatus ?? 0,
@@ -563,6 +579,7 @@ function formatGroupMember(
`group member robot classification unavailable: group=${groupId} member=${member.uin}`,
);
}
const qage = accountAge(profile?.regTime);
return {
group_id: groupId,
user_id: member.uin,
@@ -575,6 +592,8 @@ function formatGroupMember(
last_sent_time: member.lastSentTime,
shut_up_timestamp: member.shutUpTime,
level: String(member.level),
...(profile ? { qq_level: profile.level } : {}),
...(qage !== undefined ? { qage } : {}),
role: member.role,
title: member.title,
// OneBot v11 completeness (#197). QQ NT doesn't expose these, so they're
@@ -592,6 +611,17 @@ function formatGroupMember(
};
}
/** Completed UTC calendar years since registration; unavailable dates stay absent. */
function accountAge(regTime: number | undefined): number | undefined {
if (regTime === undefined || !Number.isSafeInteger(regTime) || regTime <= 0) return undefined;
const now = new Date();
const registered = new Date(regTime * 1000);
if (!Number.isFinite(registered.getTime()) || registered > now) return undefined;
const years = now.getUTCFullYear() - registered.getUTCFullYear();
registered.setUTCFullYear(now.getUTCFullYear());
return years - (registered > now ? 1 : 0);
}
/** Best-effort read of a cached user profile's qidian flags. Triggers no
* network call — only the identity cache (populated by fetchUserProfile /
* fetchUserProfileByUid). */
+2 -1
View File
@@ -42,7 +42,8 @@ export async function fetchPttText(
}
if (!file) throw new Error('消息中不包含语音');
const cached = mediaStore.findRecord(file);
const snapshot = messageStore.findMedia(messageId)?.find(element => element.type === 'record');
const cached = snapshot ? { ...snapshot, isGroup: event.message_type === 'group', sessionId: Number(event.group_id) || selfId } : mediaStore.findRecord(file, 'legacy');
if (!cached) throw new Error('语音不在缓存中,无法转写');
const isGroup = event.message_type === 'group' || cached.isGroup;
+109 -16
View File
@@ -1,3 +1,4 @@
import { isMessageMedia, type MessageMedia } from '../message-media';
import { createLogger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { findDatalineDeviceByUin } from '@snowluma/protocol/dataline/device-contacts';
@@ -26,6 +27,27 @@ import { hasAuthoritativeSequence, type JsonArray, type JsonObject, type JsonVal
const log = createLogger('OneBot');
function replyPreviewElements(message: unknown): MessageElement[] {
if (!Array.isArray(message)) return [];
const labels: Record<string, string> = {
image: '[图片]', record: '[语音]', video: '[视频]', file: '[文件]',
face: '[表情]', mface: '[表情]', forward: '[聊天记录]',
json: '[卡片]', xml: '[卡片]', markdown: '[Markdown]',
};
const parts: string[] = [];
for (const segment of message) {
if (!segment || typeof segment !== 'object') continue;
const data = segment.data;
if (!data || typeof data !== 'object') continue;
if (segment.type === 'text' && typeof data.text === 'string') parts.push(data.text);
else if (segment.type === 'at') parts.push(data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`);
else if (typeof segment.type === 'string' && labels[segment.type]) parts.push(labels[segment.type]);
}
const text = parts.join('');
return text ? [{ type: 'text', text }] : [];
}
// A video larger than QQ's Highway video ceiling can't be sent through the
// element pipeline — it must fall back to a regular file upload. The fallback
// is decided at the OneBot layer (not element-builder) because building a
@@ -840,6 +862,7 @@ export async function sendPrivateMessage(
senderUin,
time,
random: meta?.random ?? 0,
elements: replyPreviewElements(event.message),
sequenceAuthoritative: meta?.sequenceAuthoritative,
};
}
@@ -1081,6 +1104,7 @@ export async function sendGroupMessage(
? event.time
: parseInt(String(event.time || '0'), 10),
random: meta?.random ?? 0,
elements: replyPreviewElements(event.message),
sequenceAuthoritative: meta?.sequenceAuthoritative,
};
}
@@ -1264,7 +1288,7 @@ export async function forwardSingleMessage(
const parsed = await parseMessage(content, false);
if (parsed.length === 0) throw new Error('message has no content');
const elements = await prepareSingleForwardElements(ref, parsed, target);
const elements = await prepareSingleForwardElements(ref, restoreHistoricalMedia(ref, parsed, messageId), target);
let receipt;
let messageIdOut: number;
@@ -1296,7 +1320,7 @@ async function prepareSingleForwardElements(
const out: MessageElement[] = [];
for (const element of elements) {
if (element.type !== 'forward') {
out.push(enrichForForward(ref, element));
out.push(isMessageMedia(element) ? element : enrichForForward(ref, element));
continue;
}
const resId = element.resId.trim();
@@ -1372,7 +1396,29 @@ async function expandForwardNodeForTarget(
return { ...node, elements };
}
function enrichForForward(ref: OneBotInstanceContext, element: MessageElement): MessageElement {
function restoreHistoricalMedia(
ref: OneBotInstanceContext,
elements: MessageElement[],
messageId: number,
): MessageElement[] {
if (!elements.some(isMessageMedia)) return elements;
const snapshots = ref.messageStore.findMedia(messageId);
let index = 0;
const restored = elements.map(element => {
if (!isMessageMedia(element)) return element;
const snapshot = snapshots?.[index++];
if (snapshots && (!snapshot || snapshot.type !== element.type)) {
throw new Error(`historical media metadata does not match message ${messageId}`);
}
return enrichForForward(ref, element, snapshot);
});
if (snapshots && index !== snapshots.length) {
throw new Error(`historical media metadata does not match message ${messageId}`);
}
return restored;
}
function enrichForForward(ref: OneBotInstanceContext, element: MessageElement, snapshot?: MessageMedia): MessageElement {
if (element.type === 'forward') {
throw new Error('merged forward must be regenerated for the target chat');
}
@@ -1393,14 +1439,14 @@ function enrichForForward(ref: OneBotInstanceContext, element: MessageElement):
// the keys MediaStore aliases under. After parseMessage, the segment's
// `data.file` lands on `element.url` for all three types.
const lookupKey = element.url || element.fileName || element.fileId || '';
if (!lookupKey) {
if (!lookupKey && !snapshot) {
throw new Error(`forward ${element.type} missing cache key`);
}
if (element.type === 'image') {
const cached = ref.mediaStore.findImage(lookupKey);
const cached = snapshot?.type === 'image' ? snapshot : ref.mediaStore.findImage(lookupKey, 'legacy');
if (!cached || !cached.md5Hex || !cached.sha1Hex || !cached.width || !cached.height || !cached.picFormat) {
throw new Error('forward image fingerprint not cached (legacy image or expired)');
throw new Error('historical image metadata is incomplete; fetch the original message again');
}
return {
...element,
@@ -1419,9 +1465,9 @@ function enrichForForward(ref: OneBotInstanceContext, element: MessageElement):
}
if (element.type === 'record') {
const cached = ref.mediaStore.findRecord(lookupKey);
const cached = snapshot?.type === 'record' ? snapshot : ref.mediaStore.findRecord(lookupKey, 'legacy');
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
throw new Error('forward record fingerprint not cached');
throw new Error('historical voice metadata is incomplete; fetch the original message again');
}
return {
...element,
@@ -1438,9 +1484,9 @@ function enrichForForward(ref: OneBotInstanceContext, element: MessageElement):
}
if (element.type === 'video') {
const cached = ref.mediaStore.findVideo(lookupKey);
const cached = snapshot?.type === 'video' ? snapshot : ref.mediaStore.findVideo(lookupKey, 'legacy');
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
throw new Error('forward video fingerprint not cached');
throw new Error('historical video metadata is incomplete; fetch the original message again');
}
log.warn('video forward uses a fallback thumbnail (original thumb not cached)');
return {
@@ -1485,6 +1531,9 @@ export async function getForwardMessage(
nickname: node.nickname,
};
if (isGroup) sender.card = node.senderCard ?? '';
if (node.title !== undefined && node.title.length > 0) {
sender.title = node.title;
}
const message: JsonObject = {
self_id: ref.selfId,
@@ -1623,14 +1672,33 @@ function isNestedNodeArray(value: JsonValue): boolean {
return true;
}
function assertForwardNodeMetadataIsScalar(
function assertForwardNodeMetadata(
nodeData: JsonObject,
index: number,
): void {
for (const [field, value] of Object.entries(nodeData)) {
if (field === 'content' || field === 'message') continue;
if (value === undefined) continue;
if (field === 'news') {
if (isForwardNewsArray(value)) continue;
throw new MessageElementValidationError(
'INVALID_FIELD',
`forward messages[${index}].news must be an array of objects with string text`,
'node',
field,
);
}
if (field === 'title' || field === 'source' || field === 'summary' || field === 'prompt') {
if (typeof value === 'string') continue;
throw new MessageElementValidationError(
'INVALID_FIELD',
`forward messages[${index}].${field} must be a string`,
'node',
field,
);
}
if (
value === undefined || value === null || typeof value === 'string'
value === null || typeof value === 'string'
|| typeof value === 'number' || typeof value === 'boolean'
) continue;
throw new MessageElementValidationError(
@@ -1642,17 +1710,28 @@ function assertForwardNodeMetadataIsScalar(
}
}
/** Whether a value looks like OneBot preview news: `Array<{ text: string }>`. */
function isForwardNewsArray(value: JsonValue): value is Array<{ text: string }> {
if (!Array.isArray(value)) return false;
for (const item of value) {
const obj = asJsonObject(item);
if (!obj || typeof obj.text !== 'string') return false;
}
return true;
}
function assertForwardMessageInputPolicies(
ref: OneBotInstanceContext,
messages: JsonValue,
depth = 0,
): void {
if (!Array.isArray(messages) || depth >= MAX_FORWARD_DEPTH) return;
for (const item of messages) {
for (const [index, item] of messages.entries()) {
const segment = asJsonObject(item);
if (!segment) continue;
const nodeData = segment.type === 'node' ? asJsonObject(segment.data) : segment;
if (!nodeData) continue;
assertForwardNodeMetadata(nodeData, index);
const messageId = parseForwardMessageId(nodeData.id ?? nodeData.message_id);
if (messageId !== 0) {
@@ -1750,7 +1829,7 @@ async function parseForwardNodes(
'data',
);
}
assertForwardNodeMetadataIsScalar(nodeData, index);
assertForwardNodeMetadata(nodeData, index);
return { segment, nodeData };
}
@@ -1764,7 +1843,7 @@ async function parseForwardNodes(
'content',
);
}
assertForwardNodeMetadataIsScalar(segment, index);
assertForwardNodeMetadata(segment, index);
return { segment, nodeData: segment };
});
@@ -1802,7 +1881,7 @@ async function parseForwardNodes(
);
}
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
const elements = await parseMessage(content, false);
const elements = restoreHistoricalMedia(ref, await parseMessage(content, false), messageId);
if (elements.length > 0) {
const messageType = event.message_type === 'group' ? 'group' : 'private';
const groupIdValue = toPositiveInt(event.group_id);
@@ -1868,6 +1947,20 @@ async function parseForwardNodes(
}
const node: ForwardNodePayload = { userUin, nickname, elements };
// Forward optional preview news lines (OneBot `data.news`) onto the
// payload so nested-forward bubble previews can prefer caller-supplied
// lines over auto-generated ones. Only accepted when the array shape
// is valid (already asserted by assertForwardNodeMetadata).
if (isForwardNewsArray(nodeData.news)) {
node.news = nodeData.news.map(item => ({ text: item.text }));
}
// Forward optional OneBot bubble-preview metadata so nested-forward
// cards can prefer caller-supplied titles/source/summary/prompt over
// auto-derived ones (types already asserted above).
if (nodeData.title !== undefined && typeof nodeData.title === 'string') node.title = nodeData.title;
if (nodeData.source !== undefined && typeof nodeData.source === 'string') node.source = nodeData.source;
if (nodeData.summary !== undefined && typeof nodeData.summary === 'string') node.summary = nodeData.summary;
if (nodeData.prompt !== undefined && typeof nodeData.prompt === 'string') node.prompt = nodeData.prompt;
// Honour an explicit per-node display time (OneBot `data.time`, unix
// seconds) so a custom forward can set/back-date each node's timestamp
// (#209). The wire field is uint32, so reject a millisecond value or any
+5
View File
@@ -61,6 +61,11 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
abstract open(): void | Promise<void>;
abstract close(): void | Promise<void>;
/** Drop sockets and listeners without waiting for a peer handshake.
* Graceful `close()` can sit forever on a half-open connection; shutdown
* uses this so the next account session can bind the same ports. */
forceClose(): void { /* adapters that own a listener override this */ }
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
/** Report live connection health for the WebUI dashboard. */
@@ -25,6 +25,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
private server: Server | null = null;
private webSocketServer: WebSocketServer | null = null;
private listening = false;
private releaseForced = false;
private closePromise: Promise<void> | null = null;
private acceptingActions = false;
private readonly inFlightActions = new Set<Promise<void>>();
@@ -113,6 +114,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
try {
await attempt;
} catch (error) {
if (this.releaseForced) return;
if (!httpReleased && server?.listening === true) {
// A failed HTTP close callback cannot prove the listener was released.
// The upgrade handler is still attached, so the old ingress can accept
@@ -128,6 +130,26 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
}
}
override forceClose(): void {
this.releaseForced = true;
this.acceptingActions = false;
this.webSocketConnections.stopAccepting();
this.isEnabled = false;
this.listening = false;
this.webSocketConnections.terminateAll();
const webSocketServer = this.webSocketServer;
this.webSocketServer = null;
const server = this.server;
this.server = null;
if (webSocketServer) {
try { webSocketServer.destroy(); } catch { /* already dropping */ }
}
if (server) {
try { server.closeAllConnections(); } catch { /* already closed */ }
try { server.close(() => undefined); } catch { /* already closed */ }
}
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'httpServer', status: 'disabled', detail: '未启用' };
if (!this.listening) return { name: this.name, kind: 'httpServer', status: 'down', detail: '未监听(端口被占用?)' };
@@ -384,7 +406,8 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
respond(200, response);
} catch (error) {
const wording = error instanceof Error ? error.message : 'internal error';
respond(500, { status: 'failed', retcode: 1200, data: null, wording });
const tooLarge = error instanceof RequestBodyTooLargeError;
respond(tooLarge ? 413 : 500, { status: 'failed', retcode: tooLarge ? 1413 : 1200, data: null, wording });
}
}
@@ -435,15 +458,22 @@ function isAlreadyClosedError(error: Error): boolean {
return (error as NodeJS.ErrnoException).code === 'ERR_SERVER_NOT_RUNNING';
}
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
class RequestBodyTooLargeError extends Error {}
// Base64 media expands binary size by 4/3, before the JSON envelope.
function readRequestBody(req: IncomingMessage, maxBytes = 64 * 1024 * 1024): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let total = 0;
let exceeded = false;
req.on('data', (chunk: Buffer) => {
if (exceeded) return;
total += chunk.length;
if (total > maxBytes) {
reject(new Error('request body too large'));
req.destroy();
exceeded = true;
chunks.length = 0;
reject(new RequestBodyTooLargeError('request body too large'));
// Drain without retaining bytes; keep the socket alive for the 413 response.
return;
}
chunks.push(chunk);
@@ -228,6 +228,20 @@ export class OneBotNetworkManager {
return this.shutdown();
}
/** Best-effort immediate release. Does not wait for the operation queue,
* in-flight dispatches, or peer close handshakes. */
forceRelease(): void {
this.acceptingReconciles = false;
this.acceptingEvents = false;
for (const { adapter } of this.adapters.values()) {
try {
adapter.forceClose();
} catch (error) {
log.error('forced adapter release failed: %s', errMessage(error));
}
}
}
emitEvent(event: JsonObject): Promise<void> {
if (!this.acceptingEvents) {
return Promise.reject(new Error('network manager is shutting down; event dispatch rejected'));
@@ -60,6 +60,21 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
}
}
override forceClose(): void {
this.explicitlyClosed = true;
this.acceptingActions = false;
this.isEnabled = false;
this.connected = false;
this.cancelReconnect();
this.heartbeatStop?.();
this.heartbeatStop = null;
const socket = this.socket;
this.socket = null;
if (socket) {
try { socket.terminate(); } catch { /* already gone */ }
}
}
async close(): Promise<void> {
this.explicitlyClosed = true;
this.acceptingActions = false;
@@ -15,6 +15,7 @@ const moduleLog = createLogger('OneBot.WS-Server');
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
private wss: WebSocketServer | null = null;
private listening = false;
private releaseForced = false;
private closePromise: Promise<void> | null = null;
private readonly connections: WsServerConnections;
@@ -66,6 +67,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
await attempt;
if (wss && this.wss === wss) this.wss = null;
} catch (error) {
if (this.releaseForced) return;
// A failed close callback leaves release ambiguous. Retain the server
// reference and active binding state so a later shutdown can retry.
this.isEnabled = wasEnabled;
@@ -77,6 +79,19 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
}
}
override forceClose(): void {
this.releaseForced = true;
this.isEnabled = false;
this.listening = false;
this.connections.stopAccepting();
this.connections.terminateAll();
const wss = this.wss;
this.wss = null;
if (wss) {
try { wss.destroy(); } catch { /* already dropping */ }
}
}
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'wsServer', status: 'disabled', detail: '未启用' };
if (!this.listening) return { name: this.name, kind: 'wsServer', status: 'down', detail: '未监听(端口被占用?)' };
@@ -212,6 +212,17 @@ export class WsServerConnections {
this.connections.clear();
}
/** Destroy sockets immediately. A graceful close frame can leave the
* listener waiting on a peer that will never answer. */
terminateAll(): void {
this.stopAccepting();
for (const connection of this.connections.values()) {
connection.stopHeartbeat();
try { connection.socket.terminate(); } catch { /* already gone */ }
}
this.connections.clear();
}
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
const text = rawDataToString(raw);
if (!text) {
+20 -1
View File
@@ -1,7 +1,10 @@
import { createLogger } from '@snowluma/common/logger';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const log = createLogger('OneBot.Stream');
export interface StreamStorageSnapshot {
totalBytes: number;
fileCount: number;
@@ -273,7 +276,23 @@ function resolveManagedRoot(input: string): string {
return path.join(fs.realpathSync(parent), path.basename(absolute));
}
export const streamStorage = new StreamStorage(path.join(os.tmpdir(), 'onebot-stream'));
export function createStreamStorage(env: NodeJS.ProcessEnv = process.env): StreamStorage {
const fallback = path.join(os.tmpdir(), 'onebot-stream');
const raw = env.SNOWLUMA_STREAM_DIR?.trim();
if (!raw) return new StreamStorage(fallback);
try {
return new StreamStorage(raw);
} catch (error) {
log.warn(
'SNOWLUMA_STREAM_DIR=%j is ignored: %s',
raw,
error instanceof Error ? error.message : String(error),
);
return new StreamStorage(fallback);
}
}
export const streamStorage = createStreamStorage();
export const STREAM_ROOT = streamStorage.root;
export const STREAM_UPLOAD_DIR = streamStorage.uploadDir;
export const STREAM_DOWNLOAD_DIR = streamStorage.downloadDir;
@@ -40,6 +40,9 @@ const setGroupMemberInvitePolicy = requireAction('set_group_member_invite_policy
const setGroupNewMemberHistoryVisibility = requireAction('set_group_new_member_history_visibility');
const setGroupMemberPermissions = requireAction('set_group_member_permissions');
const getGroupAdminSettings = requireAction('get_group_admin_settings');
const getGroupTags = requireAction('get_group_tags');
const addGroupTag = requireAction('add_group_tag');
const deleteGroupTag = requireAction('delete_group_tag');
const setGroupAdmin = requireAction('set_group_admin');
const setGroupCard = requireAction('set_group_card');
const setGroupName = requireAction('set_group_name');
@@ -62,6 +65,9 @@ describe('group admin actions catalog', () => {
['set_group_new_member_history_visibility'],
['set_group_member_permissions'],
['get_group_admin_settings'],
['get_group_tags'],
['add_group_tag'],
['delete_group_tag'],
['set_group_admin'],
['set_group_card'],
['set_group_name'],
@@ -74,7 +80,7 @@ describe('group admin actions catalog', () => {
expect(actions.map((action) => action.kind)).toEqual([
'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal',
'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal',
'normal', 'normal', 'normal', 'normal',
'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal',
]);
});
});
@@ -1223,3 +1229,92 @@ describe('set_group_portrait toHandler', () => {
expect(setGroupAvatar).not.toHaveBeenCalled();
});
});
describe('get_group_tags parse', () => {
it('accepts category 0 and a numeric string', () => {
expect(getGroupTags.parse({ group_class: 0 })).toEqual({
ok: true,
value: { group_class: 0 },
});
expect(getGroupTags.parse({ group_class: '12' })).toEqual({
ok: true,
value: { group_class: 12 },
});
});
it('rejects a missing, negative, or oversized category', () => {
expect(getGroupTags.parse({})).toEqual({
ok: false,
field: 'group_class',
reason: 'is required',
});
expect(getGroupTags.parse({ group_class: -1 })).toEqual({
ok: false,
field: 'group_class',
reason: 'must be >= 0',
});
expect(getGroupTags.parse({ group_class: 0x1_0000_0000 })).toEqual({
ok: false,
field: 'group_class',
reason: 'must be <= 4294967295',
});
});
});
describe('get_group_tags toHandler', () => {
it('returns the tag list for the category', async () => {
const listCategoryTags = vi.fn(async () => ({
tags: [{ id: 7, name: '学习', type: 1 }],
}));
const { ctx } = adminCtx({ listCategoryTags });
await expect(getGroupTags.toHandler(ctx)({ group_class: 4 })).resolves.toEqual({
status: 'ok',
retcode: 0,
data: { tags: [{ id: 7, name: '学习', type: 1 }] },
});
expect(listCategoryTags.mock.calls).toEqual([[4]]);
});
});
describe('add_group_tag and delete_group_tag', () => {
it('rejects an empty name and does not call the bridge', async () => {
const addCategoryTag = vi.fn(async () => {});
const removeCategoryTag = vi.fn(async () => {});
const { ctx } = adminCtx({ addCategoryTag, removeCategoryTag });
await expect(addGroupTag.toHandler(ctx)({ group_class: 1, name: '' })).resolves.toEqual({
status: 'failed',
retcode: 1400,
data: null,
wording: 'name: must not be empty',
});
await expect(deleteGroupTag.toHandler(ctx)({ group_class: 1, name: '' })).resolves.toEqual({
status: 'failed',
retcode: 1400,
data: null,
wording: 'name: must not be empty',
});
expect(addCategoryTag).not.toHaveBeenCalled();
expect(removeCategoryTag).not.toHaveBeenCalled();
});
it('forwards the category and the exact name', async () => {
const addCategoryTag = vi.fn(async () => {});
const removeCategoryTag = vi.fn(async () => {});
const { ctx } = adminCtx({ addCategoryTag, removeCategoryTag });
await expect(addGroupTag.toHandler(ctx)({ group_class: 0, name: ' 户外 ' })).resolves.toEqual({
status: 'ok',
retcode: 0,
data: null,
});
await expect(deleteGroupTag.toHandler(ctx)({ group_class: '2', name: '户外' })).resolves.toEqual({
status: 'ok',
retcode: 0,
data: null,
});
expect(addCategoryTag.mock.calls).toEqual([[0, ' 户外 ']]);
expect(removeCategoryTag.mock.calls).toEqual([[2, '户外']]);
});
});
+43 -1
View File
@@ -20,8 +20,9 @@ const getMsg = requireAction('get_msg');
const deleteMsg = requireAction('delete_msg');
describe('message actions catalog', () => {
it('exports the five public message actions in source order', () => {
it('exports the public message actions in source order', () => {
expect(actions.map((entry) => entry.names[0])).toEqual([
'send_custom_face',
'send_msg',
'send_private_msg',
'send_group_msg',
@@ -39,6 +40,47 @@ describe('message actions catalog', () => {
});
});
describe('send_custom_face', () => {
const action = requireAction('send_custom_face');
const url = 'https://p.qpic.cn/qq_expression/10001/saved-sticker/0';
const image = { type: 'image', data: { file: url, sub_type: 1, summary: '[动画表情]' } };
function context() {
const resolveCustomFace = vi.fn(async () => ({ emojiId: 'saved-sticker', url, md5: 'a'.repeat(32) }));
const sendGroupMessage = vi.fn(async () => ({ messageId: 7 }));
const sendPrivateMessage = vi.fn(async () => ({ messageId: 8 }));
const ctx = asCtx({
bridge: { apis: { profile: { resolveCustomFace } } } as unknown as ApiActionContext['bridge'],
sendGroupMessage, sendPrivateMessage,
});
return { ctx, resolveCustomFace, sendGroupMessage, sendPrivateMessage };
}
it('resolves the saved id and sends a sticker with an optional reply', async () => {
const { ctx, resolveCustomFace, sendGroupMessage } = context();
expect(await action.toHandler(ctx)({ emoji_id: 'saved-sticker', group_id: 123, reply_to: -42 }))
.toMatchObject({ status: 'ok', data: { message_id: 7 } });
expect(resolveCustomFace).toHaveBeenCalledWith('saved-sticker');
expect(sendGroupMessage).toHaveBeenCalledWith(123, [{ type: 'reply', data: { id: '-42' } }, image], false);
});
it('supports a private destination and propagates lookup failures', async () => {
const { ctx, resolveCustomFace, sendPrivateMessage } = context();
expect(await action.toHandler(ctx)({ emoji_id: 'a'.repeat(32), user_id: 456 }))
.toMatchObject({ status: 'ok', data: { message_id: 8 } });
expect(sendPrivateMessage).toHaveBeenCalledWith(456, [image], false);
resolveCustomFace.mockRejectedValueOnce(new Error('sticker missing'));
await expect(action.toHandler(ctx)({ emoji_id: 'missing', user_id: 456 })).rejects.toThrow('sticker missing');
expect(sendPrivateMessage).toHaveBeenCalledTimes(1);
});
it.each([{}, { group_id: 123, user_id: 456 }])('rejects an ambiguous destination before lookup', async (target) => {
const { ctx, resolveCustomFace } = context();
expect(await action.toHandler(ctx)({ emoji_id: 'saved-sticker', ...target })).toMatchObject({ retcode: 1400 });
expect(resolveCustomFace).not.toHaveBeenCalled();
});
});
describe('send_msg parse', () => {
it('defaults auto_escape to false and leaves optional ids unset', () => {
expect(sendMsg.parse({ message: 'hello route' })).toEqual({
@@ -0,0 +1,53 @@
import { describe, expect, it } from 'vitest';
import { convertEvent, type ConverterContext } from '../src/event-converter';
import { makeBotStatusEvent } from '../src/instance';
import type { QQEventVariant } from '@snowluma/protocol/events';
describe('makeBotStatusEvent', () => {
it('emits a notice with online/offline sub_type and matching ids', () => {
const online = makeBotStatusEvent(10000, 'online', 1_710_000_000);
expect(online).toEqual({
time: 1_710_000_000,
self_id: 10000,
post_type: 'notice',
notice_type: 'bot_status',
sub_type: 'online',
user_id: 10000,
});
const offline = makeBotStatusEvent(10000, 'offline', 1_710_000_001);
expect(offline.post_type).toBe('notice');
expect(offline.notice_type).toBe('bot_status');
expect(offline.sub_type).toBe('offline');
expect(offline.self_id).toBe(10000);
expect(offline.user_id).toBe(10000);
});
});
describe('convertEvent — bot_offline (KickNT)', () => {
it('keeps notice_type bot_offline with tag and message', async () => {
const ctx: ConverterContext = {
selfId: 10001,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
};
const out = await convertEvent(ctx, {
kind: 'bot_offline',
time: 1,
selfUin: 10001,
tag: '你已离线',
message: '你的账号在其他设备登录',
} as QQEventVariant);
expect(out).toEqual({
time: 1,
self_id: 10001,
post_type: 'notice',
notice_type: 'bot_offline',
user_id: 10001,
tag: '你已离线',
message: '你的账号在其他设备登录',
});
});
});
+58
View File
@@ -640,3 +640,61 @@ describe('OneBotConfig login history sync', () => {
.toThrow(/historySync\.enabled must be a boolean/);
});
});
describe('OneBot listen port environment overrides', () => {
let tempDir = '';
let previous = '';
const saved: Record<string, string | undefined> = {};
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-onebot-port-env-'));
previous = process.cwd();
process.chdir(tempDir);
for (const name of ['SNOWLUMA_ONEBOT_HTTP_PORT', 'SNOWLUMA_ONEBOT_WS_PORT']) {
saved[name] = process.env[name];
delete process.env[name];
}
});
afterEach(() => {
for (const name of ['SNOWLUMA_ONEBOT_HTTP_PORT', 'SNOWLUMA_ONEBOT_WS_PORT']) {
if (saved[name] === undefined) delete process.env[name];
else process.env[name] = saved[name];
}
process.chdir(previous);
fs.rmSync(tempDir, { recursive: true, force: true });
});
it('overrides only the factory listeners and does not write the port back', () => {
process.env.SNOWLUMA_ONEBOT_HTTP_PORT = '3800';
process.env.SNOWLUMA_ONEBOT_WS_PORT = '3801';
const loaded = loadOneBotConfig('10001', { persistDefaults: true });
expect(loaded.networks.httpServers[0]?.port).toBe(3800);
expect(loaded.networks.wsServers[0]?.port).toBe(3801);
const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', 'onebot_10001.json'), 'utf8')) as {
networks: { httpServers: Array<{ port: number }>; wsServers: Array<{ port: number }> };
};
expect(onDisk.networks.httpServers[0]?.port).toBe(3000);
expect(onDisk.networks.wsServers[0]?.port).toBe(3001);
});
it('leaves a custom listener alone', () => {
const config = makeDefaultOneBotConfig();
config.networks.httpServers = [{
...config.networks.httpServers[0]!,
name: 'public-http',
port: 4000,
}];
saveOneBotConfig('10001', config);
process.env.SNOWLUMA_ONEBOT_HTTP_PORT = '3800';
const loaded = loadOneBotConfig('10001');
expect(loaded.networks.httpServers.map((server) => server.port)).toEqual([4000]);
});
it('keeps the saved port when the override is not a port', () => {
process.env.SNOWLUMA_ONEBOT_HTTP_PORT = 'nope';
const loaded = loadOneBotConfig('10001', { persistDefaults: true });
expect(loaded.networks.httpServers[0]?.port).toBe(3000);
});
});
@@ -228,10 +228,44 @@ describe('onebot/contact-actions / getGroupList', () => {
group_remark: '工作群',
member_count: 0, max_member_count: 500,
group_create_time: 0, group_level: 0, group_memo: '',
group_description: '',
group_all_shut: -1,
}]);
});
// #490: group_description must carry the description itself, not a copy of
// group_memo (which prefers the announcement).
it('exposes the group description separately from the memo (#490)', async () => {
const fetched = [{
...makeGroup(150, 'Both Set'),
memo: '公告正文',
description: '简介正文',
}];
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => fetched),
identity: fakeIdentity({ groups: fetched }),
});
const out = await getGroupList(bridge);
expect(out[0]).toMatchObject({
group_memo: '公告正文',
group_description: '简介正文',
});
});
it('reports an empty group_description when QQ returns no description (#490)', async () => {
const fetched = [makeGroup(160, 'No Description')];
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => fetched),
identity: fakeIdentity({ groups: fetched }),
});
const out = await getGroupList(bridge);
expect(out[0]).toMatchObject({ group_memo: '', group_description: '' });
});
it('skips fetch when cache is populated and noCache is omitted', async () => {
const cached = [makeGroup(200, 'Group B')];
const bridge = fakeBridge({
@@ -467,6 +501,24 @@ describe('onebot/contact-actions / getGroupMemberList', () => {
});
describe('onebot/contact-actions / getGroupMemberInfo', () => {
it('includes account level and completed account years without changing group level', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-10-04T00:00:00Z'));
try {
const profile = { ...makeProfile(88, 'member'), level: 64, regTime: Date.parse('2016-10-05T00:00:00Z') / 1000 };
const fetchUserProfile = vi.fn(async () => profile);
const bridge = fakeBridge({
fetchUserProfile,
identity: fakeIdentity({ findGroupMember: () => makeMember(88, 'member') }),
});
expect(await getGroupMemberInfo(bridge, 1400, 88)).toMatchObject({ level: '1', qq_level: 64, qage: 9 });
vi.setSystemTime(new Date('2026-10-05T00:00:00Z'));
expect(await getGroupMemberInfo(bridge, 1400, 88)).toMatchObject({ qage: 10 });
} finally {
vi.useRealTimers();
}
});
it('returns the cached member when present and noCache is false', async () => {
const member = makeMember(44, 'dave', 'D');
const bridge = fakeBridge({
@@ -581,6 +633,27 @@ describe('onebot/contact-actions / getGroupMemberInfo', () => {
});
describe('onebot/contact-actions / getStrangerInfo', () => {
it('exposes available compatibility fields without fabricating login days', async () => {
const bridge = fakeBridge({ fetchUserProfile: vi.fn(async () => ({
...makeProfile(55555, 'member'), qid: 'my_qid', level: 64, regTime: 1_200_000_000,
svipFlag: true, yearVipFlag: false, vipLevel: 7,
})) });
const out = await getStrangerInfo(bridge, 55555);
expect(out).toMatchObject({
uid: 'u_55555', qid: 'my_qid', qq_level: 64, qqLevel: 64, level: 64,
reg_time: 1_200_000_000, is_vip: true, is_years_vip: false, vip_level: 7,
});
expect(out).not.toHaveProperty('login_days');
});
it('omits unavailable registration and membership values', async () => {
const bridge = fakeBridge({ fetchUserProfile: vi.fn(async () => makeProfile(55555, 'member')) });
const out = await getStrangerInfo(bridge, 55555);
for (const field of ['reg_time', 'is_vip', 'is_years_vip', 'vip_level']) {
expect(out).not.toHaveProperty(field);
}
});
it('returns a fetched profile', async () => {
const bridge = fakeBridge({
fetchUserProfile: vi.fn(async () => makeProfile(
+52 -1
View File
@@ -436,6 +436,30 @@ describe('convertEvent — message elements', () => {
});
});
it('image: does not emit inline base64 as file/url (#463)', async () => {
const source = `base64://${'A'.repeat(32)}`;
const seg = await segment({ type: 'image', url: source });
expect(seg).toEqual({
type: 'image',
data: {
url: '',
file: '',
sub_type: 0,
summary: '',
},
});
});
it('image: keeps fileId when the only source is inline (#463)', async () => {
const seg = await segment({
type: 'image',
fileId: 'fid',
url: `base64://${'A'.repeat(32)}`,
});
expect((seg.data as Record<string, unknown>).file).toBe('fid');
expect((seg.data as Record<string, unknown>).url).toBe('');
});
it('image: resolver sees the upload source when only url is present (#441)', async () => {
const source = 'https://cdn.example/bot-built.png';
const seen: string[] = [];
@@ -506,7 +530,8 @@ describe('convertEvent — message elements', () => {
it('reply: self-sent private targets use the outgoing lookup namespace', async () => {
const calls: unknown[][] = [];
const seg = await segment(
{ type: 'reply', replySeq: 5, replySenderUin: SELF_ID, replyTime: 1234 },
{ type: 'reply', replySeq: 5, replySenderUin: SELF_ID, replyTime: 1234,
replyElements: [{ type: 'text', text: 'quoted text' }] },
{
messageIdResolver: (...args) => {
calls.push(args);
@@ -522,6 +547,7 @@ describe('convertEvent — message elements', () => {
5,
PRIVATE_SENT_MESSAGE_EVENT,
1234,
[{ type: 'text', text: 'quoted text' }],
]);
});
@@ -572,6 +598,31 @@ describe('convertEvent — message elements', () => {
expect(seg).toEqual({ type: 'markdown', data: { content: '# Bot answer' } });
});
it.each([true, false])('markdown: adds readable text while retaining rich content (group=%s)', async (isGroup) => {
const content = '# Bot answer\n**天气**:晴 ☀️';
const segments = await elementsToOneBotSegments(bareCtx(), [
{ type: 'at', targetUin: PEER_UIN },
{ type: 'markdown', text: content },
{ type: 'text', text: 'after' },
], isGroup, isGroup ? GROUP_ID : PEER_UIN);
expect(segments).toEqual([
{ type: 'at', data: { qq: String(PEER_UIN) } },
{ type: 'markdown', data: { content } },
{ type: 'text', data: { text: content } },
{ type: 'text', data: { text: 'after' } },
]);
expect(segments.filter((s) => typeof s === 'object' && s?.type === 'text')
.map((s) => (s as { data: { text: string } }).data.text).join('')).toBe(`${content}after`);
});
it('markdown: does not add empty text or text copies of unrelated rich elements', async () => {
const segments = await elementsToOneBotSegments(bareCtx(), [
{ type: 'markdown', text: '' },
{ type: 'json', text: '{"title":"card"}' },
], true, GROUP_ID);
expect(segments.map((s) => (s as { type: string }).type)).toEqual(['markdown', 'json']);
});
it('inline keyboard: exposes rows and actionable button metadata', async () => {
const seg = await segment({
type: 'inline_keyboard',
@@ -2162,6 +2162,16 @@ describe('extended-actions / TierB ③ share + doubt + robot-option', () => {
expect(approveDoubtRequest).not.toHaveBeenCalled();
});
it('set_doubt_friends_add_request reports an approval error without rejecting the applicant', async () => {
const approveDoubtRequest = vi.fn(async () => { throw new Error('approval denied'); });
const rejectDoubtRequest = vi.fn(async () => {});
const bridge = fakeBridge({ apis: { friend: { approveDoubtRequest, rejectDoubtRequest } } });
const res = await makeHandler(fakeCtx(bridge)).handle('set_doubt_friends_add_request', { flag: 'u_abc' });
expect(res).toMatchObject({ status: 'failed', wording: 'approval denied' });
expect(approveDoubtRequest).toHaveBeenCalledOnce();
expect(rejectDoubtRequest).not.toHaveBeenCalled();
});
it('set_group_robot_add_option forwards group + switch/examine', async () => {
const setRobotAddOption = vi.fn(async () => {});
const bridge = fakeBridge({ apis: { groupAdmin: { setRobotAddOption } } });
@@ -0,0 +1,75 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import { decodeRichBody } from '@snowluma/protocol/msg-push/rich-body-decoder';
import { convertEvent, type ConverterContext } from '../src/event-converter';
import { MessageStore } from '../src/message-store';
import { GROUP_MESSAGE_EVENT } from '../src/message-id';
import { parseMessage } from '../src/message-parser';
import { getGroupMsgHistory } from '../src/modules/message-actions';
import { segmentsToRawMessage } from '../src/helper/cq';
const ctx: ConverterContext = {
selfId: 10001,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
};
describe('face animation results', () => {
it('preserves zero from an incoming message through CQ, persistence and history', async () => {
const elements = decodeRichBody({
richText: { elems: [{ commonElem: {
serviceType: 37,
businessType: 2,
pbElem: Buffer.from('1872320130', 'hex'),
} }] },
}, true);
expect(elements).toEqual([{ type: 'face', faceId: 114, resultId: '0' }]);
const event = await convertEvent(ctx, {
kind: 'group_message',
groupId: 30001,
groupName: 'group',
senderUin: 20001,
senderNick: 'sender',
senderCard: '',
senderRole: 'member',
selfUin: 10001,
time: 1_700_000_000,
msgSeq: 42,
msgId: 10042,
elements,
});
if (!event) throw new Error('message conversion returned no event');
const message = [{ type: 'face', data: { id: '114', resultId: '0' } }];
expect(event.message).toEqual(message);
expect(event.raw_message).toBe('[CQ:face,id=114,resultId=0]');
await expect(parseMessage(String(event.raw_message), false)).resolves.toEqual(elements);
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-face-animation-'));
const dbPath = path.join(dir, 'messages.db');
let store = new MessageStore(dbPath);
try {
store.storeEvent(Number(event.message_id), true, 30001, 42, GROUP_MESSAGE_EVENT, event);
store.close();
store = new MessageStore(dbPath);
expect(store.findEvent(Number(event.message_id))?.message).toEqual(message);
const history = await getGroupMsgHistory(store, 30001, undefined, 20);
expect(history).toHaveLength(1);
expect(history[0].message).toEqual(message);
expect(history[0].raw_message).toBe(event.raw_message);
} finally {
store.close();
fs.rmSync(dir, { recursive: true, force: true });
}
});
it('escapes an opaque result identifier without changing its value', async () => {
const resultId = 'a,b&[c]';
const raw = segmentsToRawMessage([{ type: 'face', data: { id: '114', resultId } }]);
await expect(parseMessage(raw, false)).resolves.toEqual([{ type: 'face', faceId: 114, resultId }]);
});
});
+102 -3
View File
@@ -36,7 +36,7 @@ function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
uin: '10001',
selfId: 10001,
bridge,
messageStore: { findEvent: () => null } as any,
messageStore: { findMedia: () => null, findEvent: () => null } as any,
cacheMessageMeta: vi.fn(),
mediaStore: {} as any,
musicSignUrl: '',
@@ -263,6 +263,7 @@ describe('forward — nested {type:"node"} content', () => {
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
findMedia: () => null,
findEvent: () => ({
message: [{ type: 'forward', data: { id: 'OLD_RES' } }],
}),
@@ -290,6 +291,7 @@ describe('forward — nested {type:"node"} content', () => {
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
findMedia: () => null,
findEvent: () => ({
message: [{ type: 'forward', data: { id: 'OLD_RES' } }],
}),
@@ -340,6 +342,7 @@ describe('forward — nested {type:"node"} content', () => {
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
findMedia: () => null,
findEvent: () => ({
message: [{ type: 'forward', data: { id: 'OUTER' } }],
}),
@@ -361,6 +364,7 @@ describe('forward — nested {type:"node"} content', () => {
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage } } } as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
findMedia: () => null,
findEvent: () => ({
message: [
{ type: 'video', data: { file: 'cached-video-id' } },
@@ -439,6 +443,7 @@ describe('forward — nested {type:"node"} content', () => {
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
findMedia: () => null,
findEvent: () => ({
user_id: 0,
message_type: 'group',
@@ -478,7 +483,7 @@ describe('forward — nested {type:"node"} content', () => {
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = { findEvent };
(ctx as any).messageStore = { findEvent, findMedia: () => null };
await sendGroupForwardMessage(ctx, 12345, [
{ type: 'node', data: { id: -123 } },
@@ -525,7 +530,7 @@ describe('forward — nested {type:"node"} content', () => {
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = { findEvent };
(ctx as any).messageStore = { findEvent, findMedia: () => null };
await sendGroupForwardMessage(ctx, 12345, [
{ type: 'node', data: { id: 7, nickname: 'node-override' } },
@@ -610,4 +615,98 @@ describe('forward — nested {type:"node"} content', () => {
expect((nodes as any[])[0].nickname).toBe('PixivBot'); // custom nickname preserved
expect((nodes as any[])[1].userUin).toBe(10001); // omitted → self_id
});
it('accepts node metadata `news` preview arrays (OneBot ecosystem compat)', async () => {
// Upstream frameworks (NapCat / LLOneBot / AstrBot etc.) attach
// `news: [{ text }]` preview metadata to forward nodes. Only scalar
// metadata was allowed before, so a standard OneBot-style node was
// rejected with `forward messages[i].news must be a scalar value`.
const uploadForwardNodes = vi.fn(async (_nodes: any[]) => 'RESID');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
}));
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any);
const ctx = makeCtx(bridge);
const messages = [{
type: 'node',
data: {
user_id: 111,
nickname: 'outer',
news: [{ text: '预览行 1' }, { text: '预览行 2' }],
summary: '共 2 条',
content: [{ type: 'node', data: { user_id: 222, nickname: 'inner', content: [{ type: 'text', data: { text: 'hi' } }] } }],
},
}];
await sendGroupForwardMessage(ctx, 12345, messages as any);
expect(uploadForwardNodes).toHaveBeenCalledOnce();
const [nodes] = uploadForwardNodes.mock.calls[0]!;
expect((nodes as any[])[0].userUin).toBe(111);
expect((nodes as any[])[0].innerForward).toHaveLength(1);
});
it('rejects non-scalar node metadata that is not an accepted preview field', async () => {
// The news carve-out must stay narrow: any other non-scalar metadata
// (e.g. an accidental nested object) is still rejected up front.
const uploadForwardNodes = vi.fn(async (_nodes: any[]) => 'RESID');
const sendGroupMessage = vi.fn();
const bridge = fakeBridge({
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
} as any);
const ctx = makeCtx(bridge);
const messages = [{
type: 'node',
data: {
user_id: 111,
nickname: 'bad',
arbitrary: { nested: true },
content: [{ type: 'text', data: { text: 'hi' } }],
},
}];
await expect(sendGroupForwardMessage(ctx, 12345, messages as any)).rejects.toMatchObject({
code: 'INVALID_FIELD',
elementType: 'node',
field: 'arbitrary',
});
expect(uploadForwardNodes).not.toHaveBeenCalled();
expect(sendGroupMessage).not.toHaveBeenCalled();
});
it.each([
['news', 123], ['news', 'preview'], ['news', null], ['news', [{ text: false }]],
['news', [null]], ['title', 123], ['source', false], ['summary', []], ['prompt', null],
])('rejects malformed %s preview metadata before upload', async (field, value) => {
const upload = vi.fn();
const sendGroup = vi.fn();
const ctx = makeCtx(fakeBridge({ apis: { message: { sendGroup }, forward: { upload } } } as any));
await expect(sendGroupForwardMessage(ctx, 12345, [{
type: 'node', data: {
user_id: 111, nickname: 'sender', [field as string]: value,
content: [{ type: 'text', data: { text: 'hello' } }],
},
}] as any)).rejects.toMatchObject({ code: 'INVALID_FIELD', field });
expect(upload).not.toHaveBeenCalled();
expect(sendGroup).not.toHaveBeenCalled();
});
it('validates nested preview metadata before parsing an earlier contact card', async () => {
const getGroupRecommendArk = vi.fn();
const upload = vi.fn();
const sendGroup = vi.fn();
const ctx = makeCtx(fakeBridge({ apis: {
message: { sendGroup }, forward: { upload }, contacts: { getGroupRecommendArk },
} } as any));
await expect(sendGroupForwardMessage(ctx, 12345, [
{ type: 'node', data: { user_id: 111, content: [{ type: 'contact', data: { type: 'group', id: 12345 } }] } },
{ type: 'node', data: { user_id: 222, content: [
{ type: 'node', data: { user_id: 333, source: false, content: [{ type: 'text', data: { text: 'hello' } }] } },
] } },
])).rejects.toMatchObject({ code: 'INVALID_FIELD', field: 'source' });
expect(getGroupRecommendArk).not.toHaveBeenCalled();
expect(upload).not.toHaveBeenCalled();
expect(sendGroup).not.toHaveBeenCalled();
});
});
@@ -117,6 +117,23 @@ describe('group information actions', () => {
});
});
// #490: group_memo prefers the announcement, so the group description needs
// its own documented field.
it('documents the group description on both group-info results', async () => {
const infoSchema = getGroupInfo.describe().returnsSchema;
const listSchema = getGroupList.describe().returnsSchema;
expect(infoSchema?.properties).toHaveProperty('group_description');
expect(listSchema?.items?.properties).toHaveProperty('group_description');
// Never required: only the group list carries it, so a non-member lookup
// legitimately returns ''.
expect(infoSchema?.required ?? []).not.toContain('group_description');
// The no-provider fallback must still carry the key.
const response = await getGroupInfo.toHandler({} as any)({ group_id: 123456 });
expect(response).toMatchObject({ status: 'ok', data: { group_description: '' } });
});
it('documents qidian flags on both member-list and single-member results', () => {
const listSchema = getGroupMemberList.describe().returnsSchema;
const infoSchema = getGroupMemberInfo.describe().returnsSchema;
@@ -0,0 +1,256 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import type { MessageElement } from '@snowluma/protocol/events';
import { convertEvent, elementsToOneBotSegments, type ConverterContext } from '../src/event-converter';
import { MediaIndexer } from '../src/media-indexer';
import { MediaStore, MEDIA_DATA_MAX_CHARS } from '../src/media-store';
import { migrateLegacyMedia } from '../src/media-store-migration';
import { MessageStore } from '../src/message-store';
import type { OneBotInstanceContext } from '../src/instance-context';
import { forwardSingleMessage, sendGroupForwardMessage } from '../src/modules/message-actions';
const directories: string[] = [];
afterEach(() => { for (const dir of directories.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); });
function location() {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'historical-media-'));
directories.push(directory);
return { directory, dbPath: path.join(directory, 'messages.db'), legacyPath: path.join(directory, 'media.db') };
}
const image = {
file: 'same.png', fileName: 'same.png', url: '', imageUrl: '', fileSize: 120,
md5Hex: 'aa'.repeat(16), sha1Hex: 'bb'.repeat(20), width: 32, height: 24, picFormat: 1001,
subType: 0, summary: '', isGroup: true, sessionId: 123,
};
function converter(media: MediaStore): ConverterContext {
const indexer = new MediaIndexer(media);
return { selfId: 10001, imageUrlResolver: null, mediaUrlResolver: null, messageIdResolver: null,
mediaSegmentSink: (...args) => indexer.remember(...args) };
}
function context(messages: MessageStore, media: MediaStore) {
const sendGroup = vi.fn(async () => ({ sequence: 234, clientSequence: 0, random: 1, timestamp: 1700000001 }));
const upload = vi.fn(async (_nodes: unknown) => 'forward-id');
const ref = {
selfId: 10001, messageStore: messages, mediaStore: media,
converterCtx: converter(media), cacheMessageMeta: vi.fn(),
bridge: { identity: { nickname: 'self' }, apis: { message: { sendGroup }, forward: { upload } } },
} as unknown as OneBotInstanceContext;
return { ref, sendGroup, upload };
}
describe('durable historical media', () => {
it.each(['image', 'record', 'video'] as const)('forwards %s after cache churn, alias replacement and reopen', async type => {
const { dbPath } = location();
let messages = new MessageStore(dbPath);
let media = new MediaStore(dbPath, 2);
const element = { type, fileId: 'same.png', fileName: 'same.png', fileSize: 120,
md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, width: 32, height: 24,
picFormat: 1001, duration: 3, voiceFormat: 1, videoFormat: 0 } as MessageElement;
const event = await convertEvent(converter(media), {
kind: 'group_message', groupName: '', time: 1700000000, selfUin: 10001,
groupId: 123, senderUin: 456, senderNick: 'peer', senderCard: '', senderRole: 'member',
msgSeq: 10, msgId: 10, elements: [element],
});
event!.message_id = 42;
messages.storeHistoryEvent(42, true, 123, 10, 'GroupMessage', event!);
expect(JSON.stringify(event)).not.toContain('md5Hex');
expect(JSON.stringify(messages.findEvent(42))).not.toContain('sha1Hex');
// Repeated names and many new resources must not change the old message.
for (let i = 0; i < 80; i++) {
await elementsToOneBotSegments(converter(media), [{ ...element, md5Hex: 'cc'.repeat(16) }], true, 123);
media.rememberImage({ ...image, file: `other-${i}`, fileName: `other-${i}` });
media.findImage(`other-${i}`);
}
media.close(); messages.close();
messages = new MessageStore(dbPath); media = new MediaStore(dbPath, 2);
try {
const { ref, sendGroup, upload } = context(messages, media);
await forwardSingleMessage(ref, 42, { groupId: 999 });
expect(sendGroup).toHaveBeenCalledWith(999, [expect.objectContaining({
type, md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, noByteFallback: true,
})]);
await sendGroupForwardMessage(ref, 999, [{ type: 'node', data: { id: 42 } }]);
expect(upload.mock.calls[0]?.[0]).toEqual([expect.objectContaining({
elements: [expect.objectContaining({ type, md5Hex: image.md5Hex, noByteFallback: true })],
})]);
expect(messages.findEvent(42)?.message_id).toBe(42);
} finally { media.close(); messages.close(); }
});
it('stores the body and media snapshot atomically and strips inline bytes', async () => {
const { dbPath } = location();
const messages = new MessageStore(dbPath);
const media = new MediaStore(dbPath);
const db = new DatabaseSync(dbPath);
try {
const segments = await elementsToOneBotSegments(converter(media), [{ type: 'image',
...image, url: `base64://${'A'.repeat(100000)}`, imageUrl: '', fileId: 'same.png' }], true, 123);
const event = { time: 1, message: segments };
db.exec("CREATE TRIGGER fail_media BEFORE INSERT ON messages WHEN NEW.media_data IS NOT NULL BEGIN SELECT RAISE(ABORT, 'test media write failure'); END");
expect(() => messages.storeEvent(1, true, 123, 1, 'GroupMessage', event)).toThrow('test media write failure');
expect(messages.findEvent(1)).toBeNull();
db.exec('DROP TRIGGER fail_media');
messages.storeEvent(1, true, 123, 1, 'GroupMessage', event);
expect(messages.findMedia(1)?.[0].md5Hex).toBe(image.md5Hex);
expect(JSON.stringify(messages.findMedia(1))).not.toContain('base64://');
} finally { db.close(); media.close(); messages.close(); }
});
it('propagates media persistence failures instead of silently skipping segments', async () => {
const { dbPath } = location();
const media = new MediaStore(dbPath);
media.close();
await expect(elementsToOneBotSegments(converter(media), [{ type: 'image', fileId: 'test' }], true, 123))
.rejects.toThrow();
});
it('does not substitute another same-named resource for an incomplete snapshot', async () => {
const { dbPath } = location();
const messages = new MessageStore(dbPath);
const media = new MediaStore(dbPath);
try {
const segments = await elementsToOneBotSegments(converter(media), [{ type: 'image', fileId: image.file }], true, 123);
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: segments });
media.rememberImage(image);
const { ref, sendGroup } = context(messages, media);
await expect(forwardSingleMessage(ref, 42, { groupId: 999 })).rejects.toThrow('metadata is incomplete');
expect(sendGroup).not.toHaveBeenCalled();
} finally { media.close(); messages.close(); }
});
it('preserves complete metadata across an incomplete repeat and rejects conflicting resources', async () => {
const { dbPath } = location();
let messages = new MessageStore(dbPath);
let media = new MediaStore(dbPath);
const complete: MessageElement = { type: 'image', ...image, fileId: image.file };
const save = async (element: MessageElement) => {
const segments = await elementsToOneBotSegments(converter(media), [element], true, 123);
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: segments });
};
await save(complete);
await save({ type: 'image', fileId: image.file, md5Hex: image.md5Hex, width: 0, height: 0 });
await expect(save({ ...complete, md5Hex: 'cc'.repeat(16) })).rejects.toThrow('conflicting');
media.close(); messages.close();
messages = new MessageStore(dbPath); media = new MediaStore(dbPath);
try {
const { ref, sendGroup } = context(messages, media);
await forwardSingleMessage(ref, 42, { groupId: 999 });
expect(sendGroup).toHaveBeenCalledWith(999, [expect.objectContaining({
md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, width: image.width, height: image.height,
})]);
} finally { media.close(); messages.close(); }
});
it('does not combine disjoint image fingerprints merely because fileId is the same filename', async () => {
const { dbPath } = location();
const messages = new MessageStore(dbPath);
const media = new MediaStore(dbPath);
try {
const original = await elementsToOneBotSegments(converter(media), [
{ type: 'image', fileId: 'photo.jpg', md5Hex: image.md5Hex, width: 32 },
], true, 123);
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: original });
const different = await elementsToOneBotSegments(converter(media), [
{ type: 'image', fileId: 'photo.jpg', sha1Hex: image.sha1Hex, width: 64 },
], true, 123);
expect(() => messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: different }))
.toThrow('unverified media association');
expect(messages.findMedia(42)).toEqual([{ type: 'image', fileId: 'photo.jpg', md5Hex: image.md5Hex, width: 32 }]);
} finally { media.close(); messages.close(); }
});
it('rejects corrupt and oversized metadata without deleting history', () => {
const { dbPath } = location();
const media = new MediaStore(dbPath);
const db = new DatabaseSync(dbPath);
try {
expect(() => media.rememberImage({ ...image, summary: 'x'.repeat(MEDIA_DATA_MAX_CHARS) })).toThrow('storage limit');
media.rememberImage(image);
db.exec("UPDATE media_entries SET data = '{broken'");
expect(() => media.findImage(image.file)).toThrow();
db.exec("UPDATE media_entries SET data = 'null'");
expect(() => media.findImage(image.file)).toThrow('invalid persisted');
expect(media.size().images).toBe(1);
} finally { db.close(); media.close(); }
});
it.each(['image', 'record', 'video'] as const)('keeps migrated %s history independent of new same-named resources', async type => {
const { dbPath, legacyPath } = location();
const old = new MediaStore(legacyPath);
const element = { type, fileId: 'same.png', fileName: 'same.png', fileSize: 120,
md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, width: 32, height: 24,
picFormat: 1001, duration: 3, voiceFormat: 1, videoFormat: 0 } as MessageElement;
await elementsToOneBotSegments(converter(old), [element], true, 123);
old.close();
const source = fs.readFileSync(legacyPath);
const messages = new MessageStore(dbPath);
messages.storeEvent(42, true, 123, 1, 'GroupMessage', {
user_id: 456, message_id: 42, message_type: 'group',
message: [{ type, data: { file: image.file } }],
});
await migrateLegacyMedia(dbPath);
expect(fs.readFileSync(legacyPath)).toEqual(source);
fs.rmSync(legacyPath);
await migrateLegacyMedia(dbPath);
const media = new MediaStore(dbPath);
try {
await elementsToOneBotSegments(converter(media), [{ ...element, md5Hex: 'cc'.repeat(16) }], true, 123);
const { ref, sendGroup } = context(messages, media);
await forwardSingleMessage(ref, 42, { groupId: 999 });
expect(sendGroup).toHaveBeenCalledWith(999, [expect.objectContaining({ md5Hex: image.md5Hex })]);
} finally { media.close(); messages.close(); }
});
it('rolls back a failed legacy batch and resumes after the source is repaired', async () => {
const { dbPath, legacyPath } = location();
const old = new MediaStore(legacyPath); old.rememberImage(image); old.close();
const source = new DatabaseSync(legacyPath);
source.prepare("INSERT INTO media_entries VALUES ('image', 'broken', ?, 1)").run('{broken');
source.close();
await expect(migrateLegacyMedia(dbPath)).rejects.toThrow();
const destination = new MediaStore(dbPath);
expect(destination.size().images).toBe(0); destination.close();
const repaired = new DatabaseSync(legacyPath);
repaired.prepare("UPDATE media_entries SET data = ? WHERE primary_key = 'broken'").run(JSON.stringify({ ...image, file: 'broken' }));
repaired.close();
await migrateLegacyMedia(dbPath);
const reopened = new MediaStore(dbPath);
expect(reopened.size().images).toBe(2); reopened.close();
});
it('normalizes legacy inline payloads without discarding their metadata', async () => {
const { dbPath, legacyPath } = location();
const old = new MediaStore(legacyPath); old.close();
const inline = `base64://${'Z'.repeat(100000)}`;
const source = new DatabaseSync(legacyPath);
source.prepare("INSERT INTO media_entries VALUES ('image', ?, ?, 1)")
.run(inline, JSON.stringify({ ...image, file: inline, url: inline, imageUrl: inline }));
source.prepare("INSERT INTO media_keys VALUES ('image', ?, ?)").run(inline, inline);
source.close();
await migrateLegacyMedia(dbPath);
const media = new MediaStore(dbPath);
try {
expect(media.findImage(inline)).toMatchObject({ md5Hex: image.md5Hex, url: '', imageUrl: '' });
expect(JSON.stringify(media.findImage(inline))).not.toContain('base64://');
} finally { media.close(); }
});
it('resumes a cancelled migration from its committed batch cursor', async () => {
const { dbPath, legacyPath } = location();
const old = new MediaStore(legacyPath);
for (let i = 0; i < 205; i++) old.rememberImage({ ...image, file: `entry-${i}` });
old.close();
let checks = 0;
await migrateLegacyMedia(dbPath, () => ++checks > 1);
const partial = new MediaStore(dbPath);
expect(partial.size().images).toBe(200); partial.close();
await migrateLegacyMedia(dbPath);
const complete = new MediaStore(dbPath);
expect(complete.size().images).toBe(205);
expect(complete.findImage('entry-204')?.md5Hex).toBe(image.md5Hex);
complete.close();
});
});
@@ -0,0 +1,75 @@
import { afterEach, expect, it, vi } from 'vitest';
import http from 'http';
import type { AddressInfo } from 'net';
import { HttpServerAdapter } from '../src/network/http-server-adapter';
import type { JsonObject } from '../src/types';
let adapter: HttpServerAdapter | undefined;
afterEach(async () => {
await adapter?.close();
adapter = undefined;
});
it('accepts base64 images above 2 MiB, returns 413 for oversize and stays usable', async () => {
const handle = vi.fn(async () => ({ status: 'ok', retcode: 0, data: {} }));
adapter = new HttpServerAdapter(
'image-body',
{
name: 'image-body',
host: '127.0.0.1',
port: 0,
path: '/',
messageFormat: 'array',
reportSelfMessage: false,
},
{
uin: '10001',
api: { isStreamAction: () => false, handle } as never,
buildLifecycleEvent: () => ({}),
buildHeartbeatEvent: () => ({}),
},
);
await adapter.open();
const port = ((adapter as unknown as { server: http.Server }).server.address() as AddressInfo).port;
async function post(body: string): Promise<{ status: number; body: JsonObject }> {
return new Promise((resolve, reject) => {
const req = http.request({
hostname: '127.0.0.1',
port,
path: '/send_group_msg',
method: 'POST',
headers: { 'content-type': 'application/json' },
}, (res) => {
const chunks: Buffer[] = [];
res.on('data', (chunk: Buffer) => chunks.push(chunk));
res.on('end', () => {
resolve({
status: res.statusCode ?? 0,
body: JSON.parse(Buffer.concat(chunks).toString()) as JsonObject,
});
});
});
req.on('error', reject);
req.end(body);
});
}
const image = JSON.stringify({
group_id: 1,
message: [{
type: 'image',
data: { file: 'base64://' + Buffer.alloc(1_644_101).toString('base64') },
}],
});
expect((await post(image)).status).toBe(200);
expect(handle).toHaveBeenCalledTimes(1);
expect(await post(JSON.stringify({ padding: 'x'.repeat(64 * 1024 * 1024) }))).toMatchObject({
status: 413,
body: { status: 'failed', retcode: 1413 },
});
expect(handle).toHaveBeenCalledTimes(1);
expect((await post('{}')).status).toBe(200);
expect(handle).toHaveBeenCalledTimes(2);
}, 20_000);
Loaded 100 of 234 files, more files were not shown because too many files have changed in this diff. Show more