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
DrSmoothl b8680bbd69 chore(release): v1.14.17 2026-09-15 16:03:39 +08:00
DrSmoothl aaf1e561d1 fix(core): resolve missing doubt-friend account ids before handle
Linux list replies often omit the id that the handle packet requires,
and a cache-only lookup cannot see filtered applicants.

Fixes #457
2026-09-15 14:26:51 +08:00
DrSmoothl c88c8e7517 fix(core): resolve group album comments against the official feed
Album comments need the server feed identity before they can be written.
Look that feed up first and fail clearly if it cannot be resolved.

Refs #436
2026-09-14 22:08:03 +08:00
DrSmoothl dac3deb7bd feat(protocol): send and receive official my-device chats
Pad and phone device conversations were missing from the friend list
and arrived as empty private messages. They now show up as stable
contacts and support text send/receive.

Fixes #452
2026-09-14 19:34:42 +08:00
DrSmoothl 60c9669abd feat(core): allow custom request headers on notification channels
Operators can attach Authorization and other headers to a webhook
channel so authenticated providers work without a separate proxy.

Fixes #451
2026-09-14 19:34:29 +08:00
DrSmoothl 9ac39f480a fix(onebot): degrade unknown group essence types so one share card cannot fail the list
get_essence_msg_list used to abort the whole digest when an entry used
an unmapped content type. Unknown items now fall back to readable text
so the rest of the list still returns.

Fixes #453
2026-09-14 19:34:18 +08:00
DrSmoothl 6b66d4ab46 docs(contributing): describe pointing main at dest
Promote no longer opens a merge PR. pnpm release waits for
origin/main to match dest before tagging.
2026-09-14 14:31:58 +08:00
DrSmoothl 804b4c304c fix(ci): point main at dest instead of merge-promoting
Merge commits from dest painted the network graph.
Promote now moves the main ref when main has no unique patches.
2026-09-14 14:15:33 +08:00
wsu2059q 078900f81c feat(ci): add GHCR image registry support 2026-09-14 14:12:32 +08:00
DrSmoothl 62ab170b21 feat(onebot): add upload_video_to_qun_album
Group albums already list videos, but upload only accepted images.
Add a dedicated video action that extracts a cover and returns the new video id.

Fixed #331
2026-09-13 22:50:11 +08:00
DrSmoothl 131a309381 fix(core): write group album comments with official DoQunComment fields
Treat envelope field 1 as seq, not success, and attach the media cell plus batch id.
Empty id or a non-zero result fails the action instead of returning a blank comment.

Fixed #436
2026-09-13 22:34:09 +08:00
DrSmoothl 0a6c5b7d2a fix(protocol): attach voice waveforms on outgoing records
Private-chat clients only draw the progress track from message metadata.
Compute amplitudes when uploading a record so PC and phone show the bar.
2026-09-13 22:21:57 +08:00
DrSmoothl 7ef256c487 feat(onebot): include download urls on group notice images
_get_group_notice already returned picture ids. Add a fetchable url
on each image so callers do not need a separate action.

Fixes #440
2026-09-13 21:25:59 +08:00
DrSmoothl 201d10c534 fix(onebot): rebuild merged forwards for the target chat
Resending another chat's merged-forward card leaves an unopenable
bubble. Fetch the inner tree and upload it for the destination.

Fixes #437
2026-09-13 21:14:46 +08:00
DrSmoothl 48ce95f53e fix(onebot): keep image sources when reading bot-built forwards
get_forward_msg treated pictures inside a just-sent merge as empty.
Keep the original media source so file or url comes back.

Fixes #441
2026-09-13 21:14:41 +08:00
DrSmoothl 26fe4e5fb5 chore(release): run the full CI suite before bumping a version
A local release now has to pass the same install, tests, catalog,
typecheck, build, and lint steps as GitHub CI, so a broken tree
cannot be tagged.
2026-09-13 20:46:43 +08:00
DrSmoothl 4d6011ab04 test(protocol): match OIDB send arity without a spare timeout
Shared envelope send no longer passes an unused timeout, so the
group-search assertion should expect two arguments.
2026-09-13 20:34:06 +08:00
DrSmoothl 445aac8638 fix(protocol): omit unused timeout on shared OIDB sends
Callers that assert the exact send arguments were seeing a spare
undefined timeout after envelope send moved onto the shared helper.
2026-09-13 20:31:48 +08:00
DrSmoothl 95d4831da8 fix(protocol): keep image upload errors and PID send tests accurate
Roster warmup now talks on the first live sender, so ownership tests
only count Test.* packets. Image upload still reports a missing body
as an image failure.
2026-09-13 20:27:27 +08:00
DrSmoothl cfd8d5d651 fix(protocol): restore encoder used for uploaded image message info
The previous envelope cleanup dropped an import that still packs
outgoing image message info, so typecheck and the v1.14.16 release
preflight failed.
2026-09-13 20:21:06 +08:00
DrSmoothl 463d62507a chore(release): v1.14.16 2026-09-13 20:12:47 +08:00
DrSmoothl 6328890d34 refactor(protocol): send leftover OIDB envelopes through the shared caller
Moving a friend who is already in the target category still succeeds.
Media upload preflight now uses the same envelope success and error
rules as other OIDB calls.
2026-09-13 19:53:20 +08:00
DrSmoothl 1bb8c9f46c refactor(bridge): start roster warmup when the session can send
Friend, group, and member lists load as soon as a Bridge can send
packets, instead of waiting for OneBot database preparation. Login
history sync still waits until the instance is usable and both lists
have loaded.
2026-09-13 19:18:27 +08:00
DrSmoothl acb0e04bbf fix(webui): keep listener settings, restore, and boot on one contract
Invalid bind hosts and TLS without a certificate pair can no longer be
saved. Deleting certificates while TLS is on is rejected. A bad listener
does not start HTTP instead, and shutdown unbinds before tearing down
the hook.
2026-09-13 18:12:26 +08:00
DrSmoothl 6f278dc1da fix(identity): keep group roster accurate across restarts
Inbox groups and operator sightings are no longer treated as current
membership after a restart. Members who actually joined stay on the
roster until they leave.
2026-09-13 17:49:33 +08:00
DrSmoothl 4379e4838d fix(protocol): restore forward image media and drop file receipts
Bot-built merged forwards left hollow NT images after long-msg fetch,
so get_forward_msg returned empty file/url. Decode now rebuilds identity
from md5, ignores stubs, and forward uploads keep a legacy image sibling.

C2C offline-file download receipts were reported as the peer sending a
file. Treat downloadFlag=2 as a receipt and drop it from the chat stream.
2026-09-12 13:56:55 +08:00
DrSmoothl 455763f109 test(onebot): stop leaking runtime state into the package root
Running the suite left an untracked `packages/onebot/config/onebot_<uin>.json`
in the worktree. The manager's real session-start path materializes a default
per-UIN config, and that path is resolved against cwd — which vitest sets to the
package root. Tests that inject a fake instance still went through it, so the
file (holding a generated access token) reappeared on every run and a
`git add -A` would have committed it.

Run each forked test process from its own temp dir, and fail the file if the
package root gains an entry anyway.
2026-09-10 14:15:19 +08:00
DrSmoothl 83606270d8 fix(onebot): align private quote ids with send receipts
Quotes of bot-sent private messages used a different sequence than
the send receipt, so reply.id and send_private_msg disagreed. Resolve
those quotes to the stored send id by send time when the quoted
sequence does not match.

Fixes #433
2026-09-03 17:04:46 +08:00
DrSmoothl 47af79f9ac fix(onebot): accept async quick-operation alias
NoneBot 1 request handlers call `.handle_quick_operation_async`.
Treat that name as the existing quick-operation action so group
invites are approved instead of ignored.

Fixes #434
2026-09-03 16:54:13 +08:00
DrSmoothl 36c395a9b0 chore(deps): patch open npm Dependabot advisories
Raise patched floors for qs, fast-uri, hono, @hono/node-server,
postcss, ip-address, body-parser, and brace-expansion so the
lockfile no longer resolves vulnerable transitive versions.

Keep hono on the 4.12 line used by WebUI. Direct core ranges now
start at the patched releases; pnpm.overrides prevent lockfile
regeneration from rolling back.

Workspace typecheck is clean. Core 1085 tests and MCP 64 tests pass.
2026-09-03 16:48:06 +08:00
DrSmoothl 1bd26a906b chore(release): v1.14.15 2026-08-30 21:43:03 +08:00
DrSmoothl f327fc1276 fix(webui): explain unmet password rules after blur
The requirement list still opens only while the new-password field
is focused. After blur, unmet rules stay visible as field text, and
Save can be pressed to return focus to that field.
2026-08-30 21:31:27 +08:00
DrSmoothl f5e95fc634 fix(protocol): keep private recall ids exact
Private delete_msg could return success while the message stayed
visible. The 64-bit id sent with a private recall is now built with
integer bits so it matches the original message.

Fixes #431
2026-08-30 20:43:45 +08:00
DrSmoothl a7d293d79b fix(onebot): make the event pipeline tables type-check
A handler shared by several event kinds now types as one kind at a
time. The converter table still records which kinds are not converted,
so the compile-time check for dropped converted kinds works.
2026-08-30 16:14:56 +08:00
DrSmoothl 6cf461ef8f refactor(onebot): subscribe every event kind in the pipeline
Conversion still decides whether an event becomes OneBot JSON. The
pipeline now lists every kind as handle or drop, so a new converted
kind cannot be forgotten.
2026-08-30 16:08:35 +08:00
DrSmoothl a0f152229d refactor(protocol): decide message bubbles after decode
Live push and history now share one keep-or-drop decision. Control
signals and empty bodies stay hidden; undecodable content is kept and
logged on both paths.
2026-08-30 13:45:22 +08:00
DrSmoothl f6adadcd12 refactor(onebot): declare every action param the handler reads
Action handlers now only see fields from the param table. Extra client
keys are still ignored. Garbage values on declared numbers fail instead
of becoming zero.
2026-08-30 00:56:01 +08:00
DrSmoothl 117335166f refactor(protocol): keep custom-face list encoding with delete
Profile still turns ids into image URLs and slices the count. Asking
for ids no longer round-trips through those URLs.
2026-08-29 23:58:56 +08:00
DrSmoothl 9cdbcb0299 fix(identity): keep live group membership in sync with join and leave
A join now counts the member as in the group right away. A leave drops
them from the live roster without forgetting who they are. Other
sightings still do not mean the person is in the group.
2026-08-29 23:34:43 +08:00
DrSmoothl 9e27910885 fix(onebot): accept an empty group_id on private send_msg
Some clients fill unused group_id with an empty string when sending a
private message through send_msg. Treat that empty string as absent so
the send is a normal private chat.

Fixes #426
2026-08-29 19:11:10 +08:00
DrSmoothl d05c516ed6 fix(tools): retry a dropped release push and resume from the version commit
A failed git push after the version commit used to abort the pipeline.
Re-running the same release command now retries the push instead of
stopping as out of sync.
2026-08-28 14:44:07 +08:00
DrSmoothl 4b9921b711 chore(release): v1.14.14 2026-08-28 14:33:45 +08:00
makotowu c1a0091143 feat(onebot): expose qidian enterprise name on stranger info
When a stranger is a qidian account, attach the enterprise name from the corp data card. Non-qidian accounts keep an empty name.

Refs #404
2026-08-26 23:31:15 +08:00
makotowu e1bb9b4722 feat(onebot): expose qidian flags on group member info
Return qidian master and crew flags from group member info and member list. Ordinary accounts keep the flags at zero.

Refs #404
2026-08-26 23:30:41 +08:00
DrSmoothl ef73157c68 fix(flash-transfer): finish seconds-pass flash uploads
A fileset that already exists on the server still needs the apply step
so the share is not left waiting for upload.

Fixes #420
2026-08-26 23:14:35 +08:00
DrSmoothl d474996485 fix(flash-transfer): map flash file icons from QQ client types
PNG and other images now use the image type instead of the video type.

Fixes #421
2026-08-26 23:13:26 +08:00
DrSmoothl 0d73bb78d0 test(onebot): keep private reply ids aligned with send receipts
A quote of a bot-sent private message must resolve to the same
message_id that send_private_msg returned.

Fixes #417
2026-08-26 23:13:15 +08:00
DrSmoothl 4457dd4b4a fix(onebot): send merged forwards through send_msg
Exclusive node lists on send_msg, send_group_msg, and send_private_msg
now take the same forward path as send_forward_msg.

Fixes #415
2026-08-26 23:13:03 +08:00
DrSmoothl 5ba7c21c4b chore(release): v1.14.13 2026-08-22 20:15:29 +08:00
DrSmoothl a395577f77 fix(protocol): stop flooding logs when disk writes fail
After identity persistence is suspended, later observations were still
logged one-by-one. That filled Docker logs and made the WebUI log
stream unusable while the bot kept receiving messages. Report the skip
once, then at most once a minute with a count. Console write failures
must not throw into message handling.
2026-08-22 19:44:25 +08:00
DrSmoothl 5441203b76 fix(onebot): explain when member permission changes need the owner
Admins were getting an empty protocol error when changing group member
permissions. Report that only the group owner can make that change.

Fixes #411
2026-08-22 19:25:23 +08:00
DrSmoothl 2bd2643670 docs(onebot): document qidian flags on stranger info
Fill in the stranger-info action docs, catalog, and remaining profile
fixtures after the qidian flags landed. Ordinary accounts still
default to zero.

Refs #404
2026-08-22 12:41:47 +08:00
makotowu 83f643f01b feat(onebot): expose qidian account flags on stranger info
Return qidian master and crew flags from get_stranger_info so callers can tell a qidian account from a normal one. Ordinary accounts keep the flags at zero. Existing stranger fields are unchanged.

Refs #404
2026-08-22 12:36:22 +08:00
DrSmoothl 6782fd9cb3 fix(protocol): treat a successful group kick as success
QQ reports a per-member kick outcome in the command body. A zero
outcome means the member was removed; treat that as success instead
of a false failure. Still reject a non-zero outcome so callers do
not see success when the kick did not take effect.

Fixes #413
2026-08-22 11:12:58 +08:00
DrSmoothl 39e6b45b81 fix(onebot): restore image links inside merged forwards
get_forward_msg returned image segments with empty url and file when
the long-msg payload omitted a download path. Rebuild the URL from
the file fingerprint the payload still carries.

Fixes #412
2026-08-21 18:26:15 +08:00
DrSmoothl 6ec368f4b5 fix(onebot): restore doubt-request account ids from the native list
get_doubt_friends_add_request was rereading the uid as a number, so
uid came back empty and user_id was wrong. Keep the uid string and
the account number as separate fields.

Fixes #410
2026-08-21 18:26:02 +08:00
DrSmoothl 3045525e37 fix(onebot): restore emoji reaction users from the native list
get_msg_emoji_likes was asking the recent-used emoji catalog, so a
reacted message came back empty. Use the native reactor list and the
local reaction cache instead.

Fixes #409
2026-08-21 18:25:45 +08:00
DrSmoothl 5ff12868bf chore(mcp): refresh the Action catalog
Rebuild the generated catalog so the extension category count matches
the live action registry.
2026-08-20 14:20:39 +08:00
DrSmoothl bc070eca1c chore(release): v1.14.12 2026-08-20 14:12:53 +08:00
DrSmoothl aaaf0994f6 fix(onebot): treat a successful status change as success
set_online_status applied the new status but still failed the action
because QQ's success reply text was treated as an error.

Closes #405
2026-08-20 12:14:05 +08:00
H3CoF6 8fbddf67bf Feat: 发送图文ark卡片 (#355)
* feat(onebot): implement send tuwen ark

* test: add unit tests for send_ark action

* test(onebot): update canonical action docs count expectation to 191

* refactor(protocol,onebot): update 0xdc2_34 ark implementation and test coverage

- Rename action send_ark -> send_tuwen_ark to distinguish from structmsg and contact-share arks.
- Clarify SSO command mapping (OidbSvcTrpcTcp.0xdc2_34) and default param behavior in comments/docs.
- Adjust peerType, field3, and previewUrl to pb_optional to preserve 0/empty values during proton encoding.
- Update OneBot handler, tests, and auto-generated MCP tool catalog specs.

* style(protocol): fix indentation in rich-body-decoder tests
2026-08-20 12:12:39 +08:00
DrSmoothl 62256ee816 chore(mcp): refresh the Action catalog
Rebuild the generated catalog so the new request, profile, and
reaction actions stay in sync with the live registry.
2026-08-19 21:46:53 +08:00
DrSmoothl e6aeef02b4 fix(protocol): apply member permission updates on the native group setting command
set_group_member_permissions was still rejected after the previous
command switch. Linux QQ writes these capabilities with the same
group-detail command as the other admin settings.

Closes #392
2026-08-19 21:46:44 +08:00
DrSmoothl 4b8cc4292b fix(webui): keep debug search usable on a phone
The debug console search sat under the response pane and treated a
finger swipe as a selection. The list now stays above the response
and can be scrolled.

Closes #396
2026-08-19 21:46:20 +08:00
DrSmoothl 2b6a0ef3ff feat(onebot): list every emoji reaction on a message
Add get_msg_emoji_likes so a bot can see all reactions on one message
and the users behind each emoji, instead of querying one emoji at a
time.

Closes #399
2026-08-19 21:46:10 +08:00
DrSmoothl d8521d4345 feat(onebot): set profile gender and return stranger online status
set_qq_profile accepts sex. get_stranger_info now returns the online
status, extended status, and custom status that QQ already provides
on the user profile.

Closes #397
Closes #398
2026-08-19 21:46:03 +08:00
DrSmoothl 8fdd41ea22 fix(onebot): restore group and doubt request accounts
get_group_system_msg now keeps join and invite records, reports the
inviter, and fills a missing requester nick from the user profile.
get_doubt_friends_add_request returns the QQ number plus the request
message, source, and time that QQ actually sends.

Closes #400
Closes #401
Closes #402
Closes #403
2026-08-19 21:45:15 +08:00
DrSmoothl 5a10fc4c9c feat(onebot): report the invited account on group invite events
request.group.invite already identified the inviter. The event now
also reports the invited account when QQ provides it.

Closes #394
2026-08-19 00:23:40 +08:00
DrSmoothl 0a924634b2 fix(protocol): return group join question and answer in admin settings
get_group_admin_settings reported the join mode correctly but left the
question and answer blank. The detail request now asks for those
strings the same way the official client does.

Closes #393
2026-08-19 00:15:32 +08:00
DrSmoothl b088ffaff0 fix(protocol): apply member permission updates on the correct group setting command
set_group_member_permissions was still rejected after the privilege
flag read was corrected. Album, temporary-session, and create-group
writes use a different 0x89A variant than invite policy.

Closes #392
2026-08-18 21:57:11 +08:00
DrSmoothl d879ba1027 test(onebot): stop pinning the Action catalog to a head count
The live registry already owns the action list. A hardcoded length
only failed after a real addition, so drop the extra number.
2026-08-17 21:28:14 +08:00
355 changed files with 19049 additions and 2988 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.
+2 -8
View File
@@ -1,4 +1,5 @@
# Run the root validation commands on every pull request.
# Command list is duplicated in tools/ci-check.mjs — keep them identical.
name: CI
on:
@@ -38,14 +39,7 @@ jobs:
# catalog.json the docs site consumes). Fail if the committed snapshot
# drifted from the live specs — keeps the API docs from going stale.
- name: Verify generated action catalog is up to date
run: |
catalog_status="$(git status --porcelain=v1 --untracked-files=all -- packages/mcp/src/generated)"
if [ -n "$catalog_status" ]; then
git diff -- packages/mcp/src/generated
printf '%s\n' "$catalog_status"
echo '::error::Generated action catalog is stale. Run `pnpm --filter @snowluma/mcp gen` and commit packages/mcp/src/generated/.' >&2
exit 1
fi
run: node tools/check-action-catalog.mjs
typecheck:
runs-on: ubuntu-latest
@@ -22,6 +22,10 @@ on:
description: 'Override platforms (defaults to vars.DOCKER_PLATFORMS or linux/amd64,linux/arm64)'
required: false
default: ''
ghcr_image_override:
description: 'Override GHCR image name (defaults to vars.GHCR_IMAGE, leave empty to skip GHCR)'
required: false
default: ''
permissions:
contents: read
@@ -42,6 +46,8 @@ jobs:
SNOWLUMA_TAG: ${{ inputs.snowluma_tag }}
IMAGE_OVERRIDE: ${{ inputs.docker_image_override }}
PLATFORMS_OVERRIDE: ${{ inputs.platforms_override }}
GHCR_IMAGE: ${{ vars.GHCR_IMAGE }}
GHCR_OVERRIDE: ${{ inputs.ghcr_image_override }}
with:
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
script: |
@@ -59,6 +65,7 @@ jobs:
const platforms = process.env.PLATFORMS_OVERRIDE || process.env.DOCKER_PLATFORMS || 'linux/amd64,linux/arm64';
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
const ref = process.env.DOCKER_REF || 'main';
const ghcrImage = process.env.GHCR_OVERRIDE || process.env.GHCR_IMAGE || '';
await github.rest.actions.createWorkflowDispatch({
owner,
@@ -72,7 +79,8 @@ jobs:
platforms,
snowluma_tag: tag,
snowluma_repository: sourceRepo,
ghcr_image: ghcrImage,
},
});
core.info(`Re-dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);
core.info(`Re-dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, ghcr_image=${ghcrImage}, platforms=${platforms}).`);
@@ -0,0 +1,20 @@
name: Main PR target guard
# `main` is a pointer moved by Promote Dev to Main. Contributor and bot
# feature work lands on dev. A PR opened against main (like the GHCR
# fork PR) is what puts unique commits on main and fans the network graph.
on:
pull_request:
branches: [main]
permissions:
contents: read
jobs:
reject:
runs-on: ubuntu-latest
steps:
- name: Reject pull requests targeting main
run: |
echo '::error::Open this PR against dev, not main. main is updated only by Promote Dev to Main.'
exit 1
+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}"
+33 -128
View File
@@ -1,20 +1,13 @@
name: Promote Dev to Main
# `dev` is the working branch. `main` is a pointer to the same history, moved
# only by this workflow. Merge commits from dev → main are what painted the
# GitHub network graph; this job moves the `main` ref to `dev` instead.
on:
push:
branches: [dev]
tags: ['chore.*']
workflow_dispatch:
inputs:
auto_merge:
description: Enable auto-merge on the resulting PR
type: choice
options: ['true', 'false']
default: 'true'
merge_method:
description: Merge strategy when auto-merging
type: choice
options: ['merge', 'squash', 'rebase']
default: 'merge'
permissions:
contents: read
@@ -28,8 +21,6 @@ jobs:
runs-on: ubuntu-latest
outputs:
run: ${{ steps.check.outputs.run }}
auto_merge: ${{ steps.check.outputs.auto_merge }}
merge_method: ${{ steps.check.outputs.merge_method }}
reason: ${{ steps.check.outputs.reason }}
steps:
- name: Decide whether to promote
@@ -39,32 +30,24 @@ jobs:
REF: ${{ github.ref }}
REF_TYPE: ${{ github.ref_type }}
HEAD_COMMIT_MSG: ${{ github.event.head_commit.message }}
INPUT_AUTO_MERGE: ${{ inputs.auto_merge }}
INPUT_MERGE_METHOD: ${{ inputs.merge_method }}
run: |
set -euo pipefail
run='false'
auto_merge='true'
merge_method='merge'
reason=''
case "${EVENT_NAME}" in
workflow_dispatch)
run='true'
auto_merge="${INPUT_AUTO_MERGE:-true}"
merge_method="${INPUT_MERGE_METHOD:-merge}"
reason='Manual workflow_dispatch'
;;
push)
if [ "${REF_TYPE}" = 'tag' ]; then
run='true'
merge_method='merge'
reason="Tag push: ${REF}"
elif [ "${REF}" = 'refs/heads/dev' ]; then
msg="${HEAD_COMMIT_MSG:-}"
if printf '%s' "${msg}" | grep -qiE '^\[merge\]|^chore\(release\):'; then
run='true'
merge_method='merge'
reason='Commit message prefix on dev ([merge] or chore(release):)'
else
reason='Commit on dev without [merge] / chore(release): prefix'
@@ -80,8 +63,6 @@ jobs:
{
echo "run=${run}"
echo "auto_merge=${auto_merge}"
echo "merge_method=${merge_method}"
echo "reason=${reason}"
} >> "${GITHUB_OUTPUT}"
@@ -93,8 +74,6 @@ jobs:
echo "| Event | \`${EVENT_NAME}\` |"
echo "| Ref | \`${REF}\` |"
echo "| Run | \`${run}\` |"
echo "| Auto-merge | \`${auto_merge}\` |"
echo "| Merge method | \`${merge_method}\` |"
echo "| Reason | ${reason} |"
} >> "${GITHUB_STEP_SUMMARY}"
@@ -123,123 +102,49 @@ jobs:
owner: ${{ github.repository_owner }}
repositories: ${{ github.event.repository.name }}
- name: Resolve bot identity
id: bot
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
APP_SLUG: ${{ steps.app-token.outputs.app-slug }}
run: |
set -euo pipefail
bot_login="${APP_SLUG}[bot]"
bot_id="$(gh api "/users/${bot_login}" --jq .id)"
bot_email="${bot_id}+${bot_login}@users.noreply.github.com"
{
echo "login=${bot_login}"
echo "id=${bot_id}"
echo "email=${bot_email}"
} >> "${GITHUB_OUTPUT}"
echo "Resolved bot: ${bot_login} <${bot_email}>"
- name: Checkout main
- name: Checkout
uses: actions/checkout@v6
with:
ref: main
ref: dev
fetch-depth: 0
token: ${{ steps.app-token.outputs.token }}
- name: Compare dev to main
id: diff
run: |
set -euo pipefail
git fetch origin dev:dev
ahead="$(git rev-list --count main..dev)"
behind="$(git rev-list --count dev..main)"
dev_sha="$(git rev-parse dev)"
dev_short="$(git rev-parse --short dev)"
{
echo "ahead=${ahead}"
echo "behind=${behind}"
echo "dev_sha=${dev_sha}"
echo "dev_short=${dev_short}"
} >> "${GITHUB_OUTPUT}"
if [ "${ahead}" = '0' ]; then
echo "skip=true" >> "${GITHUB_OUTPUT}"
echo "::notice::dev has no commits ahead of main; nothing to promote."
else
echo "skip=false" >> "${GITHUB_OUTPUT}"
echo "dev is ${ahead} ahead, ${behind} behind main."
fi
- name: Ensure automation label exists
if: steps.diff.outputs.skip != 'true'
- name: Point main at dev
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
run: |
gh label create automation --color 0E8A16 --description 'Automated bot PRs' 2>/dev/null || true
- name: Create or update Pull Request
id: pr
if: steps.diff.outputs.skip != 'true'
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
DEV_SHA: ${{ steps.diff.outputs.dev_sha }}
DEV_SHORT: ${{ steps.diff.outputs.dev_short }}
AHEAD: ${{ steps.diff.outputs.ahead }}
BEHIND: ${{ steps.diff.outputs.behind }}
REASON: ${{ needs.decide.outputs.reason }}
REF: ${{ github.ref }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
title="chore: promote dev → main (${DEV_SHORT})"
git fetch origin dev main
dev_sha="$(git rev-parse origin/dev)"
main_sha="$(git rev-parse origin/main)"
dev_short="$(git rev-parse --short origin/dev)"
main_short="$(git rev-parse --short origin/main)"
if [ "${dev_sha}" = "${main_sha}" ]; then
echo "::notice::main already equals dev @ ${dev_short}; nothing to promote."
{
echo "main already equals dev @ ${dev_short}"
} >> "${GITHUB_STEP_SUMMARY}"
exit 0
fi
unique="$(git cherry origin/dev origin/main | awk '/^\+/ { print $2 }' || true)"
if [ -n "${unique}" ]; then
echo '::error::main has unique commits that dev does not. Cherry-pick them onto dev first.' >&2
git log --oneline --no-walk ${unique}
exit 1
fi
git push --force-with-lease="refs/heads/main:${main_sha}" origin "origin/dev:refs/heads/main"
echo "::notice::Updated main ${main_short} → dev@${dev_short}"
{
echo "Automated promotion of \`dev\` into \`main\`."
echo "## Promote"
echo
echo "| Key | Value |"
echo "| --- | --- |"
echo "| Source | \`dev\` @ \`${DEV_SHA}\` |"
echo "| Trigger ref | \`${REF}\` |"
echo "| Trigger reason | ${REASON} |"
echo "| \`main\` was | \`${main_sha}\` |"
echo "| \`main\` now | \`dev\` @ \`${dev_sha}\` |"
echo "| Reason | ${REASON} |"
echo "| Workflow run | ${RUN_URL} |"
echo "| Ahead / Behind | ${AHEAD} / ${BEHIND} |"
echo
echo "Created by SnowLuma Bot."
} > pr-body.md
existing="$(gh pr list --base main --head dev --state open --json number --jq '.[0].number' 2>/dev/null || true)"
if [ -n "${existing}" ]; then
gh pr edit "${existing}" --title "${title}" --body-file pr-body.md
pr_number="${existing}"
echo "Updated existing PR #${pr_number}"
else
url="$(gh pr create --base main --head dev --title "${title}" --body-file pr-body.md --label automation)"
pr_number="${url##*/}"
echo "Opened new PR #${pr_number} (${url})"
fi
echo "number=${pr_number}" >> "${GITHUB_OUTPUT}"
{
echo "## Promote PR"
echo
echo "- Number: #${pr_number}"
echo "- Source: \`dev@${DEV_SHORT}\`"
echo "- Ahead/Behind: ${AHEAD}/${BEHIND}"
} >> "${GITHUB_STEP_SUMMARY}"
- name: Enable auto-merge
if: steps.diff.outputs.skip != 'true' && needs.decide.outputs.auto_merge == 'true'
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
PR_NUMBER: ${{ steps.pr.outputs.number }}
MERGE_METHOD: ${{ needs.decide.outputs.merge_method }}
run: |
set -euo pipefail
method_flag='--merge'
case "${MERGE_METHOD}" in
squash) method_flag='--squash' ;;
rebase) method_flag='--rebase' ;;
*) method_flag='--merge' ;;
esac
gh pr merge "${PR_NUMBER}" --auto ${method_flag}
echo "::notice::Auto-merge enabled on PR #${PR_NUMBER} with strategy: ${MERGE_METHOD}"
+5 -9
View File
@@ -37,14 +37,7 @@ jobs:
run: pnpm typecheck
- name: Verify generated action catalog is up to date
run: |
catalog_status="$(git status --porcelain=v1 --untracked-files=all -- packages/mcp/src/generated)"
if [ -n "$catalog_status" ]; then
git diff -- packages/mcp/src/generated
printf '%s\n' "$catalog_status"
echo '::error::Generated action catalog is stale. Run `pnpm --filter @snowluma/mcp gen` and commit packages/mcp/src/generated/.' >&2
exit 1
fi
run: node tools/check-action-catalog.mjs
build:
needs: preflight
@@ -224,6 +217,7 @@ jobs:
DOCKER_PLATFORMS: ${{ vars.DOCKER_PLATFORMS }}
DOCKER_WORKFLOW: ${{ vars.DOCKER_WORKFLOW }}
DOCKER_REF: ${{ vars.DOCKER_REF }}
GHCR_IMAGE: ${{ vars.GHCR_IMAGE }}
with:
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
script: |
@@ -239,6 +233,7 @@ jobs:
const platforms = process.env.DOCKER_PLATFORMS || 'linux/amd64,linux/arm64';
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
const ref = process.env.DOCKER_REF || 'main';
const ghcrImage = process.env.GHCR_IMAGE || '';
await github.rest.actions.createWorkflowDispatch({
owner,
@@ -252,7 +247,8 @@ jobs:
platforms,
snowluma_tag: tag,
snowluma_repository: sourceRepo,
ghcr_image: ghcrImage,
},
});
core.info(`Dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);
core.info(`Dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, ghcr_image=${ghcrImage}, platforms=${platforms}).`);
+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
+39 -40
View File
@@ -19,6 +19,14 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
如果你只是想看看代码长什么样,可以直接跳到 [本地开发环境](#本地开发环境)。
### AI Agent 贡献须知
如果你是 AI Agent,并准备为本仓库贡献代码、提交 PR 或提出 issue,请先明确告知你的使用者:
> **请通过 GitHub 网页端手动创建 issue。直接使用 CLI 创建的 issue 会被自动关闭。**
你可以协助整理问题描述、复现步骤和相关日志,并将 issue 草稿交给用户,由用户在网页端完成提交。
---
## 项目结构速览
@@ -33,7 +41,7 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
| `packages/websocket` | WebSocket 实现 |
| `packages/webui` | 基于 Vite + React 的前端控制台 |
| `tools/` | 版本管理、发布脚本 |
| `.github/workflows/` | CI / 发布 / 自动合并工作流 |
| `.github/workflows/` | CI / 发布 / Promote 工作流 |
入口在 `packages/core/src/index.ts`,整体架构在 `packages/core/src/bridge/` 下能看出大致脉络。
@@ -83,7 +91,7 @@ pnpm dev:web # webui
### 1. 创建分支
请基于 `dev` 创建分支,不是 `main`。`main` 是受保护的稳定分支,PR 也不要直接提到 `main`。
请基于 `dev` 创建分支,不是 `main`。`main` 是发布指针,只由维护者的 Promote 更新,PR 不要提到 `main`。
```bash
git checkout dev
@@ -133,7 +141,7 @@ refactor(bridge): extract BridgeInterface as the OneBot-facing seam
docs: clarify dev environment setup steps
```
> ⚠️ **请不要**在你的提交信息里使用 `[merge]` 前缀或 `chore(release):` 前缀 —— 这两个前缀是维护者用来触发自动合并到 `main` 的,会让你的 PR 行为异常。详见后文 [维护者参考](#维护者参考release--自动合并流程)。
> ⚠️ **请不要**在你的提交信息里使用 `[merge]` 前缀或 `chore(release):` 前缀 —— 这两个前缀是维护者用来把 `main` 指到 `dev` 的,会让你的 PR 行为异常。详见后文 [维护者参考](#维护者参考release--promote)。
### 4. 推送并发起 PR
@@ -152,7 +160,7 @@ git push origin fix/onebot-mention-encoding
- 维护者会在能腾出时间时来 review。如果一周内没有任何回应,欢迎在 PR 里 @ 一下,或者去社群里提醒。
- review 意见请尽量在同一个 PR 内修改,避免反复关闭重开。
- 合并方式由维护者决定,通常是 squash merge 到 `dev`。**`main` 由维护者通过自动化工作流统一从 `dev` 合入**,你不需要操心 `main`。
- 合并方式由维护者决定,通常是 squash merge 到 `dev`。**`main` 由维护者通过 Promote 指到当时的 `dev`**,你不需要操心 `main`。
---
@@ -191,28 +199,30 @@ git push origin fix/onebot-mention-encoding
---
## 维护者参考:release & 自动合并流程
## 维护者参考:release & Promote
> 以下内容主要写给具备 `main` 推送 / 发版权限的维护者。普通贡献者只需要把 PR 提到 `dev`,不需要关心这一节。
> 以下内容主要写给具备发版权限的维护者。普通贡献者只需要把 PR 提到 `dev`,不需要关心这一节。
### 分支模型
SnowLuma 使用 **`main` + `dev`** 双分支模型:
- **`main`** — 受保护的稳定分支,仅接收来自 `dev` 的合并 PR。**禁止直接 push**。
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先合入 `dev`。
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先进入 `dev`。
- **`main`** — 发布指针,应与某次 Promote 当时的 `dev` 尖端是**同一个提交**。不要直接 push,也不要往 `main` 开 PR(CI 会拒)。
- **`native/auto-update-*`** — 由 `SnowLuma Bot` 自动创建的原生产物更新分支(来自 `SnowLumaNative`,不需要手动维护)。
### 把 `dev` 合并到 `main`
### 把 `main` 指到 `dev`
工作流 `.github/workflows/promote-dev-to-main.yml` 会以 `SnowLuma Bot` 身份开 / 更新一个 `dev → main` 的 PR,并可选地自动合并。无论用哪种触发方式,工作流都会调用 `gh pr merge --auto`:**只有 `main` 分支保护中所有 required status checks(typecheck + 各架构 build)都通过后,机器人才会真正合并**。失败的工作流会卡住合并。
工作流 `.github/workflows/promote-dev-to-main.yml` 以 `SnowLuma Bot` 身份把 `main` 指到当前 `dev` 尖端,**不再开 merge PR**。`main` 上若有 `dev` 还没有的独有改动,Promote 会失败,需要先把那些改动收回 `dev`。
推到 `dev` 仍会跑 `dev-build.yml`。Promote **不等**那组检查;发版请用下面的 `pnpm release`,它会在本地先跑完整 CI。
#### 1. 提交信息前缀(推荐日常使用)
向 `dev` push 一个提交,提交信息**以**以下任一前缀**开头**即触发(不区分大小写):
- `[merge]` — 例如 `[merge] fix: hotfix for OneBot mention`
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯。**只许用在真正的版本 bump**,不要写进普通 CI / 工具提交。
> 是**前缀**匹配,不是任意位置。`fix: something [merge]` 不会触发,必须把 `[merge]` 写在最前面。
@@ -220,38 +230,22 @@ SnowLuma 使用 **`main` + `dev`** 双分支模型:
任何符合 `chore.*` 的 tag(如 `chore.merge-20240509`、`chore.promote-v1.7.0`)被推送时也会触发:
- `chore.*` → 仅触发 `promote-dev-to-main.yml`(开 PR,自动合并)
- `chore.*` → 仅触发 `promote-dev-to-main.yml`(把 `main` 指到 `dev`)
- `v*` → 仅触发 `release.yml`(构建发布产物)
推荐流程:先用 `chore.*` tag 把 `dev` 合入 `main`,待合并完成后再在 `main` 上打 `v*` tag 触发发布。这样 `release.yml` 始终基于已过完所有检查的 `main` HEAD 构建。
推荐流程:用 `pnpm release`(或先 Promote,再确认 `origin/main` 已等于 `dev` 尖端)之后,在 `main` 上打 `v*` tag。这样 `release.yml` 始终基于当时的 `main` HEAD 构建。
#### 3. 手动触发
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。可选输入:
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。没有 merge 策略选项;跑起来就是一次指针更新。
- `auto_merge`:是否启用 auto-merge(默认 `true`)。
- `merge_method`:`merge` / `squash` / `rebase`(默认 `merge`)。
### 不要给 `main` 套「必须走 PR」
### 启用 `main` 分支保护(必做)
Promote 不通过 PR 更新 `main`。如果给 `main` 打开 **Require a pull request before merging** 或禁止更新引用,Promote 会失效。
仓库管理员需要在 GitHub 上为 `main` 配置规则集(Repository Rules)或经典分支保护,至少满足:
可以限制删除 `main`。外来 PR 必须打 `dev`;打到 `main` 的 PR 会被 `main-pr-target-guard.yml` 拒绝。
1. **Settings → Rules → Rulesets**(推荐)或 **Settings → Branches → Branch protection rules**。
2. 选择 `main` 作为目标分支。
3. 勾选:
- **Restrict deletions** — 禁止删除 `main`。
- **Require a pull request before merging** — 所有合并必须走 PR。
- **Block force pushes** — 禁止强推。
- **Require status checks to pass before merging(必勾)** — 把以下来自 `dev-build.yml` 的 check 全部加为 required:
- `typecheck`
- `build (win-x64)`
- `build (linux-x64)`
- `build (linux-arm64)`
- **Require branches to be up to date before merging** — 保证 PR 合并前已 rebase 过最新 `main`。
4. 在 **Bypass list / Allow specified actors to bypass** 中加入 `SnowLuma Bot` GitHub App。这样 `gh pr merge --auto` 才能在所有 required check 通过后由机器人自动完成合并;否则 PR 会一直卡在 auto-merge 等待人工 review。
5. **不要**把任何用户加入 push 白名单,确保「禁止向 `main` 直接提交」的约束生效。第一次设置完后,连仓库管理员也只能通过 PR 改 `main`。
效果:任何对 `dev` 的推送都会先在 `dev-build.yml` 上跑 typecheck + 三个架构的 build;只有全部成功,promote 工作流的 `--auto` 合并才会真正发生。失败时 PR 会保留在 open 状态,修复后再次推到 `dev` 即可重新触发检查。
本地若已经 checkout 过旧的 `main`,Promote 之后可能无法快进,对齐 `origin/main` 即可。
### 必需的 Secrets
@@ -260,25 +254,30 @@ SnowLuma 使用 **`main` + `dev`** 双分支模型:
- `SNOWLUMA_BOT_APP_ID` — 数字类型的 App ID。
- `SNOWLUMA_BOT_PRIVATE_KEY` — 该 App 的 PEM 私钥。
App 必须在本仓库已安装,且授予 **Contents: Read+Write**、**Pull requests: Read+Write**。
App 必须在本仓库已安装,且授予 **Contents: Read+Write**。
### 本地工作流速查(维护者)
```bash
# 把 dev 合入 main(三选一)
# 推荐:一条命令走完 bump → Promote → 等 main 跟上 → 打 v* tag
pnpm release 1.7.0
# 只要把 main 指到 dev(三选一)
# 方式 A:commit-msg 前缀
git commit -m "chore(release): v1.7.0" # 或 "[merge] fix: hotfix"
git push # → 触发 promote-dev-to-main
# 方式 B:chore.* 合并 tag(与发布 tag 解耦)
git tag chore.merge-20240509 # 或 chore.promote-v1.7.0 等
# 方式 B:chore.* tag(与发布 tag 解耦)
git tag chore.merge-20240509
git push origin chore.merge-20240509 # → 触发 promote-dev-to-main
# 方式 C:在 Actions 页面手动 Run workflow
# 合并完成后,发布版本(在 main 上打 v* tag)
git checkout main && git pull
# Promote 完成后,若要自己打发布 tag
git fetch origin
git switch main
git merge --ff-only origin/main # 对不齐就 reset 到 origin/main
git tag v1.7.0
git push origin v1.7.0 # → 仅触发 release.yml
```
+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]
+11 -2
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.14.11",
"version": "1.14.22",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -25,6 +25,7 @@
"typecheck": "pnpm -r --if-present typecheck",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"ci": "node tools/ci-check.mjs",
"start": "node dist/index.mjs",
"bump": "node tools/bump-version.mjs",
"release": "node tools/release.mjs"
@@ -50,7 +51,15 @@
},
"overrides": {
"esbuild@<0.28.1": "^0.28.1",
"@babel/core@<7.29.6": "^7.29.6"
"@babel/core@<7.29.6": "^7.29.6",
"qs@<=6.15.3": "^6.16.0",
"fast-uri@<3.1.6": "^3.1.6",
"@hono/node-server@<1.19.15": "^1.19.15",
"hono": "~4.12.34",
"postcss@<=8.5.22": "^8.5.23",
"ip-address@<=10.3.0": "^10.3.1",
"body-parser@<2.3.0": "^2.3.0",
"brace-expansion@<5.0.7": "^5.0.7"
}
},
"packageManager": "pnpm@10.28.0",
+5 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.14.11",
"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.11",
"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;
}
+7 -1
View File
@@ -506,7 +506,13 @@ class FileWriter {
}
if (!this.quota.reserve(this.file.path, bytes)) return false;
this.file.stream.write(data);
try {
this.file.stream.write(data);
} catch (error) {
this.disabled = true;
this.quota.writeFailed(this.file.path, error);
return false;
}
this.file.bytes += bytes;
return true;
}
+7 -1
View File
@@ -264,7 +264,13 @@ function emit(
// and ESC (0x1B) so multi-line records (stack traces) and ANSI color
// sequences emitted by render() pass through intact.
// eslint-disable-next-line no-control-regex
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
const consoleLine = line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n';
try {
stream.write(consoleLine);
} catch {
// A full Docker json-file log volume can make stdout/stderr throw.
// Logging must not take down message handling or the WebUI.
}
}
// File transport sees levels >= currentFileLevel (SNOWLUMA_LOG_FILE_LEVEL,
+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);
}
});
});
+7
View File
@@ -60,6 +60,13 @@ describe('logger UIN slot padding', () => {
expect(() => createLogger('Test').info('no uin')).not.toThrow();
});
it('does not throw when the console stream cannot accept the line', () => {
vi.mocked(process.stderr.write).mockImplementation(() => {
throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' });
});
expect(() => createLogger('Test').error('disk is full')).not.toThrow();
});
it('keeps structured subscriber lines plain while terminal output stays colored', () => {
const captured: LogEntry[] = [];
const unsubscribe = subscribeLogs((entry) => captured.push(entry));
+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({});
+3 -3
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.14.11",
"version": "1.14.22",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -51,11 +51,11 @@
"otpauth": "^9.5.1"
},
"devDependencies": {
"@hono/node-server": "^1.19.14",
"@hono/node-server": "^1.19.15",
"@rollup/plugin-node-resolve": "^16.0.3",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"hono": "^4.12.25",
"hono": "^4.12.34",
"tsx": "^4.21.0",
"typescript": "catalog:",
"vite": "catalog:",
+50 -13
View File
@@ -19,8 +19,13 @@ import {
} from '@snowluma/protocol/oidb-services/contacts/fetch-robot-uin-ranges';
import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile';
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
import {
fetchQidianCorpInfo as fetchQidianCorpInfoWire,
type QidianCorpInfo,
} from '@snowluma/protocol/services/qidian/fetch-corp-info';
import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark';
import { GetGroupRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-group-recommend-ark';
import { SendTuwenArk, type SendTuwenArkParams } from '@snowluma/protocol/oidb-services/contacts/send-tuwen-ark';
import { SetFriendCategory } from '@snowluma/protocol/oidb-services/contacts/set-friend-category';
import { toHex } from '@snowluma/common/hex';
import { createLogger } from '@snowluma/common/logger';
@@ -137,6 +142,11 @@ export class ContactsApi {
return GetGroupRecommendArk.invoke(this.ctx, { groupId });
}
/** Send a custom 图文 ark card to a C2C peer or group (0xdc2_34). */
sendTuwenArk(params: SendTuwenArkParams): Promise<void> {
return SendTuwenArk.invoke(this.ctx, params);
}
private async fetchFriendRoster(): Promise<FriendRoster> {
const entries: FriendListPageEntry[] = [];
const categories = new Map<number, FriendListPageCategory>();
@@ -262,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),
});
}
@@ -289,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 ?? '',
@@ -342,6 +358,12 @@ export class ContactsApi {
return info;
}
/** 企点企业资料卡(#404 后续 PR)。仅在判断命中的是企点账号后再调用。
* best-effort:非企点账号或拉取失败返回 null,不影响上层资料读取。 */
async fetchQidianCorpInfo(uin: number): Promise<QidianCorpInfo | null> {
return fetchQidianCorpInfoWire(this.ctx, uin);
}
async fetchGroupRequests(
filtered = false,
count = 50,
@@ -354,6 +376,18 @@ export class ContactsApi {
const targetUin = raw.target?.uin ?? 0;
const invitorUin = raw.invitor?.uin ?? 0;
const operatorUin = raw.operatorUser?.uin ?? 0;
const targetUid = raw.target?.uid
|| this.ctx.identity.findUidByUin(targetUin, groupId)
|| this.ctx.identity.findUidByUin(targetUin)
|| '';
const invitorUid = raw.invitor?.uid
|| this.ctx.identity.findUidByUin(invitorUin, groupId)
|| this.ctx.identity.findUidByUin(invitorUin)
|| '';
const operatorUid = raw.operatorUser?.uid
|| this.ctx.identity.findUidByUin(operatorUin, groupId)
|| this.ctx.identity.findUidByUin(operatorUin)
|| '';
const notifyType = raw.eventType ?? 0;
const operationType = groupRequestOperationType(notifyType);
const sequence = normalizeGroupRequestSequence(raw.sequence, groupId);
@@ -368,20 +402,23 @@ export class ContactsApi {
requests.push({
groupId,
groupName: raw.group?.groupName ?? '',
targetUid: this.ctx.identity.findUidByUin(targetUin, groupId)
?? this.ctx.identity.findUidByUin(targetUin)
?? '',
targetUin,
targetUid,
targetUin: targetUin
|| this.ctx.identity.findUinByUid(targetUid, groupId)
|| this.ctx.identity.findUinByUid(targetUid)
|| 0,
targetName: raw.target?.name ?? '',
invitorUid: this.ctx.identity.findUidByUin(invitorUin, groupId)
?? this.ctx.identity.findUidByUin(invitorUin)
?? '',
invitorUin,
invitorUid,
invitorUin: invitorUin
|| this.ctx.identity.findUinByUid(invitorUid, groupId)
|| this.ctx.identity.findUinByUid(invitorUid)
|| 0,
invitorName: raw.invitor?.name ?? '',
operatorUid: this.ctx.identity.findUidByUin(operatorUin, groupId)
?? this.ctx.identity.findUidByUin(operatorUin)
?? '',
operatorUin,
operatorUid,
operatorUin: operatorUin
|| this.ctx.identity.findUinByUid(operatorUid, groupId)
|| this.ctx.identity.findUinByUid(operatorUid)
|| 0,
operatorName: raw.operatorUser?.name ?? '',
sequence,
state: raw.state ?? 0,
+56 -16
View File
@@ -35,6 +35,54 @@ import { deflateSync } from 'node:zlib';
const FLASH_SLICE_SIZE = 1024 * 1024;
const FLASH_IMAGE_EXT = new Set([
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'heic', 'avif', 'tiff', 'tif', 'ico', 'dib', 'heif',
]);
const FLASH_AUDIO_EXT = new Set(['mp3', 'wav', 'aac', 'flac']);
const FLASH_VIDEO_EXT = new Set([
'mp4', 'avi', 'mkv', 'mov', '3gp', 'mpeg', 'rmvb', 'rm', 'wmv', 'flv', 'asf', 'webm', 'mpg', 'vob', 'm4v', 'f4v',
]);
const FLASH_ARCHIVE_EXT = new Set(['zip', 'rar', 'tar', 'bz2', 'xz', 'tgz', 'gz', '7z']);
const FLASH_MODEL_EXT = new Set(['pt', 'pth', 'onnx', 'model', 'mlmodel']);
/** 0x93cf f3 粗类:压缩包走 2/6,其余按媒体类 7。 */
function flashApplyTypeCode(ext: string): number {
if (ext === 'zip') return 6;
if (FLASH_ARCHIVE_EXT.has(ext)) return 2;
return 7;
}
/**
* 0x93d0 / 0x12a9 格式码。与 QQ 客户端按扩展名判定的图标类型一致:
* 图片 26、音频 1、视频 2、文档 3、压缩包 4、未知 11。
*/
function flashFormatCode(ext: string): number {
if (FLASH_IMAGE_EXT.has(ext)) return 26;
if (FLASH_AUDIO_EXT.has(ext)) return 1;
if (FLASH_VIDEO_EXT.has(ext)) return 2;
if (ext === 'doc' || ext === 'docx') return 3;
if (FLASH_ARCHIVE_EXT.has(ext)) return 4;
if (ext === 'apk') return 5;
if (ext === 'xls' || ext === 'xlsx') return 6;
if (ext === 'ppt' || ext === 'pptx') return 7;
if (ext === 'html' || ext === 'htm') return 8;
if (ext === 'pdf') return 9;
if (ext === 'txt') return 10;
if (ext === 'psd') return 12;
if (FLASH_MODEL_EXT.has(ext)) return 15;
if (ext === 'ttf' || ext === 'otf') return 16;
if (ext === 'ipa') return 17;
if (ext === 'dmg') return 23;
if (ext === 'pkg') return 24;
if (ext === 'key') return 18;
if (ext === 'note') return 19;
if (ext === 'numbers') return 20;
if (ext === 'pages') return 21;
if (ext === 'sketch') return 22;
if (ext === 'exe') return 27;
return 11;
}
/** After create returns, 0x93d4 can still omit the main-file fileId for a
* few seconds (#364). Re-query on this schedule (first lookup is immediate). */
const FLASH_FILE_ID_RETRY_DELAYS_MS = [1000, 2000, 4000, 4000] as const;
@@ -393,21 +441,13 @@ export class FlashTransferApi {
// ─────────────── 文件上传 ───────────────
/**
* 文件扩展名 → 闪传类型码映射。typeCode 用于 0x93cf f3,formatCode 用于
* 0x93d0 commit f7 与 0x12a9 filesetWrap.f7(两者同值)。mp4 → 2,rar/zip → 4。
* 未知扩展名按媒体类处理(formatCode=2),服务端按文件名扩展名判定。
* 文件扩展名 → 闪传类型码。typeCode 用于 0x93cf f3(卡片粗类:压缩包/媒体);
* formatCode 用于 0x93d0 commit f7 与 0x12a9 filesetWrap.f7,决定对端图标
* (png=26,mp4=2,zip=4,未知=11)。
*/
private static fileTypeCode(fileName: string): { typeCode: number; formatCode: number } {
const ext = fileName.toLowerCase().match(/\.([^.]+)$/)?.[1] ?? '';
switch (ext) {
case 'rar': return { typeCode: 2, formatCode: 4 };
case 'zip': return { typeCode: 6, formatCode: 4 };
case '7z': case 'gz': case 'tar': case 'bz2': return { typeCode: 2, formatCode: 4 };
case 'png': case 'jpg': case 'jpeg': case 'bmp': case 'gif': case 'webp':
case 'mp4': case 'mov': case 'avi': case 'mkv':
return { typeCode: 7, formatCode: 2 };
default: return { typeCode: 7, formatCode: 2 };
}
return { typeCode: flashApplyTypeCode(ext), formatCode: flashFormatCode(ext) };
}
/** 构造 sub=103 的 fileId(客户端生成的 protobuf,base64url 编码)。
@@ -530,7 +570,8 @@ export class FlashTransferApi {
/**
* 阶段1:流式哈希 + prepare(拿 rkey)+ apply(注册 fileId)。
* 秒传(rkey=null)返回 null,调用方跳过 sliceupload。
* 秒传时 prepare 不回 rkey,仍必须 apply,否则 fileset 会一直停在等待上传;
* 返回 null 只表示调用方跳过 sliceupload。
*/
private async prepareAndApply(
filesetUuid: string, it: StagedFlashItem,
@@ -542,13 +583,12 @@ export class FlashTransferApi {
filesetUuid, fileUuid: it.fileUuid, fileName: it.fileName, fileSize: it.fileSize,
sha1: hashes.sha1Hex, fileIndex: it.fileIndex, formatCode: it.formatCode,
});
if (rkey === null) return null; // 秒传
const fileId = FlashTransferApi.buildFileId(hashes.sha1, it.fileSize);
await ApplyUpload.invoke(this.ctx, {
filesetUuid, fileUuid: it.fileUuid, fileId, fileName: it.fileName, fileSize: it.fileSize,
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex: it.fileIndex, formatCode: it.formatCode,
});
if (rkey === null) return null;
return { rkey, sha1StateV: hashes.sha1StateV, sliceCount: hashes.sliceCount };
}
@@ -638,12 +678,12 @@ export class FlashTransferApi {
filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex,
fileIndex, formatCode: thumbFormatCode, thumbType, width, height,
});
if (rkey === null) return; // 秒传
const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize, appid);
await ApplyUpload.invoke(this.ctx, {
filesetUuid, fileUuid, fileId, fileName, fileSize,
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex, formatCode: thumbFormatCode, thumbType, width, height,
});
if (rkey === null) return;
// sliceupload(缩略图小,1 片,Sha1StateV=[标准 SHA1])
const sha1StateV = computeSha1StateV(new Uint8Array(thumbBytes), 1, fileSize);
const body: FlashSliceUploadBody = {
+26 -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],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
...cloneNodeWithElements(node, node.elements.map(cacheableForwardElement)),
groupId: node.groupId ?? groupId,
senderCard: node.senderCard,
messageType: node.messageType ?? (groupId ? 'group' : 'private'),
})));
@@ -579,17 +564,7 @@ export class ForwardApi {
const bridge = asBridge(this.ctx);
const cached = forwardResCache.get(resId);
if (cached) {
const nodes = cached.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
}));
const nodes = cloneNodes(cached);
// Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich
// on read (a no-op once names are present) and persist so later hits skip.
if (await this.enrichSenders(nodes)) forwardResCache.set(resId, cloneNodes(nodes));
@@ -854,16 +829,14 @@ export class ForwardApi {
}
}
function cacheableForwardElement(element: MessageElement): MessageElement {
if (element.type !== 'image') return element;
if (element.imageUrl || element.fileId || element.md5Hex) return element;
const source = (element.url ?? '').trim();
if (!source) return element;
return { ...element, imageUrl: source };
}
function cloneNodes(nodes: ForwardNodePayload[]): ForwardNodePayload[] {
return nodes.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
}));
return nodes.map(node => cloneNodeWithElements(node, [...node.elements]));
}
+57 -12
View File
@@ -1,4 +1,5 @@
import { createLogger } from '@snowluma/common/logger';
import { findDatalineDeviceByUin } from '@snowluma/protocol/dataline/device-contacts';
import { ApproveDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/approve-doubt-buddy-req';
import { ClearFriendRemark } from '@snowluma/protocol/oidb-services/friend/clear-friend-remark';
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
@@ -24,6 +25,9 @@ export class FriendApi {
}
async delete(userId: number, block = false): Promise<void> {
if (findDatalineDeviceByUin(userId)) {
throw new Error('this contact cannot be deleted');
}
await DeleteFriend.invoke(this.ctx, { userId, block });
// The server-side delete has already completed. A refresh failure must be
@@ -40,25 +44,66 @@ export class FriendApi {
}
}
setRemark(userId: number, remark: string): Promise<void> {
if (remark === '') {
return ClearFriendRemark.invoke(this.ctx, { userId });
async setRemark(userId: number, remark: string): Promise<void> {
if (findDatalineDeviceByUin(userId)) {
throw new Error('this contact does not support remarks');
}
return SetFriendRemark.invoke(this.ctx, { userId, remark });
if (remark === '') {
await ClearFriendRemark.invoke(this.ctx, { userId });
return;
}
await SetFriendRemark.invoke(this.ctx, { userId, remark });
}
/** List doubtful friend-add requests (可能认识的人). */
getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
return GetDoubtBuddyReq.invoke(this.ctx, { count });
async getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
const list = await GetDoubtBuddyReq.invoke(this.ctx, { count });
return Promise.all(list.map(async (item) => {
let uid = item.uid;
let userId = item.user_id;
if (userId <= 0 && uid) {
userId = this.ctx.identity.findUinByUid(uid) ?? 0;
}
// Applicants need not be friends or share a group. Use Identity's
// profile lookup when the list only supplies an account number.
if (!uid && userId > 0) {
try {
uid = await this.ctx.resolveUserUid(userId);
} catch (err: unknown) {
log.warn(
'doubt-request uid resolve failed: user=%d err=%s',
userId,
err instanceof Error ? err.message : String(err),
);
}
}
return { ...item, uid: uid || '', user_id: userId };
}));
}
/** Approve a doubtful friend-add request by its uid (the list item's flag). */
approveDoubtRequest(uid: string): Promise<void> {
return ApproveDoubtBuddyReq.invoke(this.ctx, { uid });
/** Approve a doubtful friend-add request. `uidOrFlag` is the list uid, or a digit-only account number. */
async approveDoubtRequest(uidOrFlag: string): Promise<void> {
log.trace('doubt-request approval: resolving applicant');
const uid = await this.resolveDoubtFlag(uidOrFlag);
log.trace('doubt-request approval: submitting request');
await ApproveDoubtBuddyReq.invoke(this.ctx, { uid });
log.trace('doubt-request approval: completed');
}
/** Reject (delete/decline) a doubtful friend-add request by its uid. */
rejectDoubtRequest(uid: string): Promise<void> {
return RejectDoubtBuddyReq.invoke(this.ctx, { uid });
/** Reject (delete/decline) a doubtful friend-add request. `uidOrFlag` matches `approveDoubtRequest`. */
async rejectDoubtRequest(uidOrFlag: string): Promise<void> {
return RejectDoubtBuddyReq.invoke(this.ctx, {
uid: await this.resolveDoubtFlag(uidOrFlag),
});
}
/**
* Digit-only flags are account numbers and must be translated before the
* approval/reject packet is built. A raw number in that packet is rejected
* by the server. Same rule as inbound friend-request handling.
*/
private resolveDoubtFlag(uidOrFlag: string): Promise<string> {
if (!/^\d+$/.test(uidOrFlag)) return Promise.resolve(uidOrFlag);
return this.ctx.resolveUserUid(parseInt(uidOrFlag, 10));
}
}
+52 -8
View File
@@ -31,10 +31,18 @@ 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';
import type { BridgeContext } from '../bridge-context';
/** QQ only accepts this write from the group owner (#411). */
export const MEMBER_PERMISSIONS_OWNER_ONLY =
'only the group owner can change group member permissions';
export type GroupAdminSettings = {
add_type: number;
group_question: string;
@@ -112,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,
@@ -138,12 +158,23 @@ export class GroupAdminApi {
}
private async fetchGroupPrivilegeFlag(groupId: number, setting: string, phase: string): Promise<number> {
return (await this.fetchGroupPrivilegeState(groupId, setting, phase)).privilegeFlag;
}
private async fetchGroupPrivilegeState(
groupId: number,
setting: string,
phase: string,
): Promise<{ privilegeFlag: number; ownerUid?: string }> {
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(`unable to read ${setting} ${phase} for group ${groupId}`);
}
return results.privilegeFlag ?? 0;
return {
privilegeFlag: results.privilegeFlag ?? 0,
ownerUid: results.ownerUid,
};
}
async setMemberPermissions(groupId: number, permissions: GroupMemberPermissions): Promise<void> {
@@ -156,21 +187,34 @@ export class GroupAdminApi {
throw new Error('at least one member permission must be specified');
}
let expectedPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
const before = await this.fetchGroupPrivilegeState(
groupId,
'group member permissions',
'before update',
);
const selfUid = this.ctx.identity.selfUid;
if (selfUid && before.ownerUid && selfUid !== before.ownerUid) {
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
}
let expectedPrivilegeFlag = before.privilegeFlag;
let combinedMask = 0n;
for (const [permission, allow] of updates) {
if (allow === undefined) continue;
await SetMemberPermission.invoke(this.ctx, {
groupId,
currentPrivilegeFlag: expectedPrivilegeFlag,
permission,
allow,
});
try {
await SetMemberPermission.invoke(this.ctx, {
groupId,
currentPrivilegeFlag: expectedPrivilegeFlag,
permission,
allow,
});
} catch (error) {
if (error instanceof OidbError && error.code === 1287) {
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
}
throw error;
}
expectedPrivilegeFlag = mergeGroupMemberPermission(expectedPrivilegeFlag, permission, allow);
combinedMask |= BigInt(GROUP_MEMBER_PERMISSION_MASKS[permission]);
}
+256 -47
View File
@@ -1,7 +1,11 @@
import type { JsonObject, JsonValue } from '@snowluma/common/json';
import { packetTimeoutMs } from '@snowluma/bridge/packet-timeout';
import { createLogger } from '@snowluma/common/logger';
import type {
AlbumCreator,
CommentReqBodyHeader,
CommentReqPhotoInfo,
CommentRespData,
DeleteMediasRequest,
DeleteMediasResponse,
DoQunCommentRequest,
@@ -10,19 +14,26 @@ import type {
DoQunLikeResponse,
GetAlbumListRequest,
GetAlbumListResponse,
GetQunFeedDetailRequest,
GetQunFeedDetailResponse,
GroupAlbumInfo as GroupAlbumInfoWire,
QunFeedCellCommon,
GetMediaListRequest,
GetMediaListResponse,
MediaInfo,
UrlInfo,
} from '@snowluma/proto-defs/oidb-actions/group-album';
import { uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album';
import { uploadImageToGroupAlbum, uploadVideoToGroupAlbum } from '@snowluma/protocol/web/group-album';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
const log = createLogger('Bridge.GroupAlbum');
const GET_ALBUM_LIST_CMD = 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetAlbumList';
const GET_ALBUM_LIST_SEQ = 3331;
const DO_QUN_COMMENT_CMD = 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment';
const DO_QUN_COMMENT_SEQ = 8527;
const GET_QUN_FEED_DETAIL_CMD = 'QunAlbum.trpc.qzone.webapp_qun_feeds.FeedsReader.GetQunFeedDetail';
const GET_QUN_FEED_DETAIL_COMMENT_COUNT = 20;
function uint64ToString(value: bigint | undefined): string {
return (value ?? 0n).toString();
@@ -169,7 +180,7 @@ export class GroupAlbumApi {
body.length,
);
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, 15000);
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, packetTimeoutMs());
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(
`get group album list transport failed: ${result.errorMessage || `code ${result.errorCode}`}`,
@@ -259,6 +270,13 @@ export class GroupAlbumApi {
await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin);
}
async uploadVideo(groupId: number, albumId: string, albumName: string, filePath: string): Promise<{ id: string }> {
const groupCode = groupId.toString();
const uin = this.ctx.identity.uin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return uploadVideoToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin);
}
async getMediaList(groupId: number, albumId: string, attachInfo = ''): Promise<GroupAlbumMediaResult> {
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
@@ -280,7 +298,7 @@ export class GroupAlbumApi {
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
body,
15000,
packetTimeoutMs(),
);
if (!result.success || !result.gotResponse || !result.responseData) {
@@ -305,38 +323,36 @@ export class GroupAlbumApi {
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const clientKey = Date.now().toString();
const uin = this.ctx.identity.uin;
const resolved = await this.resolveCommentMedia(groupId, albumId, lloc);
const batchId = optionalBatchId(resolved?.batchId);
if (batchId === undefined) {
throw new Error('comment album media error: media not found');
}
const mediaLloc = commentMediaLloc(resolved, lloc);
const feed = await this.getQunFeedDetail(groupId, albumId, batchId, mediaLloc);
const ownerUin = feed.ownerUin || resolved?.uploader || '';
const photoInfo = commentPhotoInfo(
feed.media,
mediaInfoForComment(resolved, mediaLloc),
albumId,
batchId,
);
const body = protobuf_encode<DoQunCommentRequest>({
field1: 8527,
field1: DO_QUN_COMMENT_SEQ,
field2: new Uint8Array(0),
field3: new Uint8Array(0),
body: {
groupId: groupId.toString(),
field3: 2,
reqBody: {
field1: { field3: 0, field4: '' },
field2: {
field1: { uin },
},
field5: {
field1: {
field2: {
field1: 0, field2: '',
lloc,
field4: '', field6: '', field7: 0, field8: 0, field9: 0, field14: 0, field15: 0, field17: 0,
},
},
albumId,
field5: 0,
},
field1: commentReqHeader(feed.cellCommon),
...(ownerUin ? { field2: { field1: { uin: ownerUin } } } : {}),
field5: photoInfo,
},
field5: {
field2: { uin },
field3: {
field1: 0,
field2: content,
field3: '', field4: '', field5: 0, field6: '',
},
user: { uin },
contents: [{ type: 0, content }],
clientKey,
},
},
@@ -344,31 +360,35 @@ export class GroupAlbumApi {
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
body,
15000,
);
const result = await this.ctx.sendRawPacket(DO_QUN_COMMENT_CMD, body, packetTimeoutMs());
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to comment on album media');
}
const resp = protobuf_decode<DoQunCommentResponse>(result.responseData);
const resCode = resp.field1;
if (resCode !== 0 && resCode !== 8527 && !resp.comment) {
throw new Error(`comment album media error: retCode ${resCode ?? 'unknown'}`);
const resultCode = resp.result ?? 0;
if (resultCode !== 0) {
throw new Error(
`comment album media error: retCode ${resultCode}`
+ (resp.errorText ? `, ${resp.errorText}` : ''),
);
}
const commentData = resp.comment?.data ?? {};
const commentData = commentFromResponse(resp);
if (!commentData.id) {
throw new Error('comment album media error: empty comment');
}
return convertBigIntToString({
id: commentData.id ?? '',
user: { uin: commentData.user?.uin ?? '' },
content: commentData.content ?? [],
id: commentData.id,
user: { uin: commentData.user?.uin || uin },
content: (commentData.content ?? [{ type: 0, content }]).map((item) => ({
type: item.type ?? 0,
content: item.content ?? '',
})),
time: commentData.time ?? '0',
clientKey: commentData.clientKey ?? '',
clientKey: commentData.clientKey || clientKey,
}) as unknown as GroupAlbumCommentResult;
}
@@ -379,12 +399,7 @@ export class GroupAlbumApi {
const type = isLike ? 2 : 1;
const status = isLike ? 0 : 1;
let id = '';
if (lloc) {
id = `421_1_0_${groupId}|${albumId}|${batchId}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`;
} else {
id = `421_1_0_${groupId}|${albumId}|${batchId}`;
}
const id = qunFeedCellId(groupId, albumId, batchId, lloc);
const body = protobuf_encode<DoQunLikeRequest>({
field1: 5495,
@@ -417,7 +432,7 @@ export class GroupAlbumApi {
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
body,
15000,
packetTimeoutMs(),
);
if (!result.success || !result.gotResponse || !result.responseData) {
@@ -456,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) {
@@ -509,6 +524,80 @@ export class GroupAlbumApi {
return { mediaId: mediaKey };
}
}
/**
* Page the album when the caller only has a lloc / video id, so the
* comment can carry the official batch id and media kind.
*/
private async resolveCommentMedia(
groupId: number,
albumId: string,
mediaKey: string,
): Promise<AlbumCommentMediaItem | undefined> {
const seenCursors = new Set<string>();
let attachInfo = '';
while (true) {
const page = await this.getMediaList(groupId, albumId, attachInfo);
const hit = findCommentMedia(page.mediaList, mediaKey);
if (hit) return hit;
const next = page.nextAttachInfo ?? '';
if (!next || seenCursors.has(next)) return undefined;
seenCursors.add(next);
attachInfo = next;
}
}
private async getQunFeedDetail(
groupId: number,
albumId: string,
batchId: bigint,
lloc: string,
): Promise<{ cellCommon: QunFeedCellCommon; ownerUin: string; media?: CommentReqPhotoInfo }> {
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const body = protobuf_encode<GetQunFeedDetailRequest>({
seq: 0,
field2: new Uint8Array(0),
field3: new Uint8Array(0),
data: {
groupId: groupId.toString(),
feedId: '',
commentCount: GET_QUN_FEED_DETAIL_COMMENT_COUNT,
attachInfo: '',
albumId,
batchId: batchId.toString(),
lloc,
},
traceId,
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(GET_QUN_FEED_DETAIL_CMD, body, packetTimeoutMs());
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to fetch album feed');
}
const resp = protobuf_decode<GetQunFeedDetailResponse>(result.responseData);
const resultCode = resp.result ?? 0;
if (resultCode !== 0) {
throw new Error(
`fetch album feed error: retCode ${resultCode}`
+ (resp.errorText ? `, ${resp.errorText}` : ''),
);
}
const feed = resp.data?.feed?.feed;
const cell = feed?.cellCommon;
const feedId = cell?.feedId ?? '';
if (!feedId) {
throw new Error('comment album media error: empty feed');
}
return {
cellCommon: cell ?? { feedId },
ownerUin: feed?.cellUserInfo?.user?.uin ?? '',
media: feed?.cellMedia,
};
}
}
interface AlbumDeleteMediaItem {
@@ -538,6 +627,126 @@ function findDeleteTarget(
return undefined;
}
interface AlbumCommentMediaItem {
type?: number;
image?: {
name?: string;
sloc?: string;
lloc?: string;
isGif?: boolean;
hasRaw?: boolean;
} | null;
video?: {
id?: string;
cover?: {
name?: string;
sloc?: string;
lloc?: string;
} | null;
} | null;
uploader?: string;
batchId?: string | number | bigint;
}
function optionalBatchId(value: unknown): bigint | undefined {
if (value === undefined || value === null || value === '') return undefined;
try {
const batchId = BigInt(value as string | number | bigint);
return batchId === 0n ? undefined : batchId;
} catch {
return undefined;
}
}
function commentMediaLloc(item: AlbumCommentMediaItem | undefined, lloc: string): string {
if (item?.video?.cover?.lloc) return item.video.cover.lloc;
if (item?.image?.lloc) return item.image.lloc;
return lloc;
}
function mediaInfoForComment(item: AlbumCommentMediaItem | undefined, lloc: string): MediaInfo {
const batchId = optionalBatchId(item?.batchId);
const shared: MediaInfo = {
...(item?.uploader ? { uploader: item.uploader } : {}),
...(batchId !== undefined ? { batchId } : {}),
};
if (item?.video) {
return {
...shared,
type: 1,
video: { cover: { lloc: item.video.cover?.lloc || lloc } },
};
}
return {
...shared,
type: 0,
image: { lloc: item?.image?.lloc || lloc },
};
}
function qunFeedCellId(
groupId: number,
albumId: string,
batchId: string | number | bigint,
lloc?: string,
): string {
const head = `421_1_0_${groupId}|${albumId}|${batchId}`;
if (!lloc) return head;
return `${head}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`;
}
function commentReqHeader(cell: QunFeedCellCommon): CommentReqBodyHeader {
return {
...(cell.time !== undefined ? { time: cell.time } : {}),
...(cell.feedId ? { feedId: cell.feedId } : {}),
};
}
function commentPhotoInfo(
feedMedia: CommentReqPhotoInfo | undefined,
fallback: MediaInfo,
albumId: string,
batchId: bigint,
): CommentReqPhotoInfo {
if (feedMedia?.medias?.length) {
return {
medias: feedMedia.medias,
albumId: feedMedia.albumId || albumId,
batchId: feedMedia.batchId ?? batchId,
};
}
return { medias: [fallback], albumId, batchId };
}
function findCommentMedia(
mediaList: ReadonlyArray<unknown>,
mediaKey: string,
): AlbumCommentMediaItem | undefined {
for (const raw of mediaList) {
if (!raw || typeof raw !== 'object') continue;
const item = raw as AlbumCommentMediaItem;
if (item.image?.lloc === mediaKey) return item;
if (item.video?.id === mediaKey || item.video?.cover?.lloc === mediaKey) return item;
}
return undefined;
}
function commentFromResponse(resp: DoQunCommentResponse): CommentRespData {
const wrapped = resp.comment;
if (!wrapped) return {};
if (wrapped.data?.id) return wrapped.data;
if (wrapped.id) {
return {
id: wrapped.id,
content: wrapped.content,
time: wrapped.time,
clientKey: wrapped.clientKey,
user: wrapped.data?.user,
};
}
return wrapped.data ?? {};
}
export interface GroupAlbumMediaResult {
mediaList: Array<JsonValue & Partial<MediaInfo>>;
nextAttachInfo: string;
+2 -9
View File
@@ -33,11 +33,7 @@ export class InteractionApi {
return SetEssence.invoke(this.ctx, { groupId, sequence, random, enable });
}
/**
* Legacy stub: see `GetEmojiLikes` namespace comment for why this
* SSO path can never surface the user list. Real data lives in
* ReactionStore on the OneBot side.
*/
/** Fetch the reactor list for one emoji on a group message. */
async getEmojiLikes(
groupId: number,
sequence: number,
@@ -54,10 +50,7 @@ export class InteractionApi {
}
/**
* Fetch the per-emoji reaction summary on a group message via
* 0x9084_1 — emoji_id + reactor count + last-reaction timestamp.
* Cross-checked against the local ReactionStore cache for callers
* that need to detect cache gaps.
* Recent-used emoji catalog (0x9084_1). Not a per-message reaction list.
*/
fetchReactionSummary(
groupId: number,
+81 -1
View File
@@ -14,6 +14,14 @@ import type {
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { assertWindowShakeSendPolicy } from '@snowluma/protocol/element-manifest';
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
import {
datalineTextFromElements,
encodeDatalineText,
} from '@snowluma/protocol/dataline/codec';
import {
findDatalineDeviceByUin,
type DatalineDeviceContact,
} from '@snowluma/protocol/dataline/device-contacts';
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
import {
fetchC2cMessageRange,
@@ -404,6 +412,14 @@ export class MessageApi {
}
const seq = response.groupSequence ?? 0;
if (seq <= 0) {
log.warn(
'group message delivery unconfirmed: group=%d random=%d result=%s sequence=%s time=%s responseBytes=%d',
groupId, random, response.result, response.groupSequence,
response.timestamp1, result.responseData.length,
);
throw new Error('group message delivery was not confirmed: QQ returned no message receipt; check the conversation before retrying');
}
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return { messageId, sequence: seq, clientSequence: 0, random, timestamp };
@@ -417,6 +433,8 @@ export class MessageApi {
* (and optionally `c2c.uid` for the media case).
*/
async sendPrivate(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
const device = findDatalineDeviceByUin(userUin);
if (device) return this.sendDatalineText(device, elements);
if (elements.length === 0) throw new Error('message is empty');
assertWindowShakeSendPolicy(
elements.filter((element) => element.type === 'poke').length,
@@ -483,6 +501,67 @@ export class MessageApi {
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
}
/**
* Send text to an official my-device contact. These peers are not
* ordinary friends — they use the same trans0x211 send path as c2c
* files, with a device-chat body instead of FileExtra.
*/
private async sendDatalineText(
device: DatalineDeviceContact,
elements: MessageElement[],
): Promise<SendMessageReceipt> {
const text = datalineTextFromElements(elements);
const selfUin = parseInt(this.ctx.identity.uin, 10);
if (!Number.isSafeInteger(selfUin) || selfUin <= 0) {
throw new Error('self uin unavailable');
}
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
const nowSec = Math.floor(Date.now() / 1000);
const request = protobuf_encode<SendMessageRequest>({
routingHead: {
trans0x211: {
toUin: BigInt(selfUin),
ccCmd: 7,
uid: device.uid,
},
},
contentHead: {
type: 1,
subType: 0,
},
messageBody: {
msgContent: encodeDatalineText({
selfUin,
dstTerType: device.terType,
text,
}),
},
clientSequence: clientSeq,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
ctrl: { msgFlag: nowSec },
multiSendSeq: 0,
});
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send device message failed: ${result.errorMessage || 'no response'}`);
}
const response = protobuf_decode<SendMessageResponse>(result.responseData);
if (!response) throw new Error('failed to decode SendMessageResponse');
if (response.result != null && response.result !== 0) {
throw new Error(`send device message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
}
const seq = response.privateSequence ?? 0;
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
}
/**
* Reply into an existing group temp session (临时会话). Wire primitive only —
* it does NOT gate; the caller verifies the session before calling. Routes
@@ -506,6 +585,7 @@ export class MessageApi {
bridge: this.ctx as unknown as Bridge,
userUid,
scene: 'group-temp',
tempGroupId: groupUin,
});
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
@@ -715,7 +795,7 @@ export class MessageApi {
info: {
clientSequence: clientSeq,
random,
messageId: BigInt((0x01000000 * 0x100000000) + random),
messageId: (0x01000000n << 32n) | BigInt(random >>> 0),
timestamp,
field5: 0,
messageSequence: msgSeq,
+25 -32
View File
@@ -1,6 +1,4 @@
import type {
FaceroamOpReq,
FaceroamOpResp,
GroupAvatarExtra,
SetStatusReq,
SetStatusResp,
@@ -8,6 +6,7 @@ import type {
import { AddCustomFace } from '@snowluma/protocol/oidb-services/custom-face/add-custom-face';
import { DeleteCustomFace } from '@snowluma/protocol/oidb-services/custom-face/delete-custom-face';
import { FetchCustomFaceDetail } from '@snowluma/protocol/oidb-services/custom-face/fetch-custom-face-detail';
import { FetchCustomFaceList } from '@snowluma/protocol/oidb-services/custom-face/fetch-custom-face-list';
import { ModifyCustomFace } from '@snowluma/protocol/oidb-services/custom-face/modify-custom-face';
import { MoveCustomFace } from '@snowluma/protocol/oidb-services/custom-face/move-custom-face';
import { OrderCustomFace } from '@snowluma/protocol/oidb-services/custom-face/order-custom-face';
@@ -76,14 +75,15 @@ export class ProfileApi {
if (!resp) {
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
}
if (resp.errCode !== undefined && resp.errCode !== 0) {
throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`);
const message = resp.errMsg ?? '';
if (message !== '' && message !== 'set status success') {
throw new Error(message);
}
}
}
setProfile(nickname?: string, personalNote?: string): Promise<void> {
return SetProfile.invoke(this.ctx, { nickname, personalNote });
setProfile(nickname?: string, personalNote?: string, sex?: number): Promise<void> {
return SetProfile.invoke(this.ctx, { nickname, personalNote, sex });
}
setSelfLongNick(longNick: string): Promise<void> {
@@ -166,28 +166,13 @@ export class ProfileApi {
}));
}
private async fetchCustomFaceIds(count: number): Promise<string[]> {
async fetchCustomFaceIds(count = 10): Promise<string[]> {
if (!Number.isInteger(count) || count < 0) {
throw new Error('custom face count must be a non-negative integer');
}
if (count === 0) return [];
const req = {
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
uin: BigInt(this.ctx.identity.uin),
field3: 1,
field6: 1,
};
const request = protobuf_encode<FaceroamOpReq>(req);
const result = await this.ctx.sendRawPacket('Faceroam.OpReq', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'fetch custom face failed');
}
const resp = protobuf_decode<FaceroamOpResp>(result.responseData);
if (!resp || (resp.retCode ?? 0) !== 0) {
throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`);
}
const faceIds = resp.item?.faceIds || [];
const faceIds = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
return faceIds.slice(0, count);
}
@@ -195,7 +180,20 @@ export class ProfileApi {
return `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${emojiId}/0`;
}
/** 删除一个收藏表情(custom face)。emoji_id 来自 fetchCustomFace 返回的 URL 路径段。 */
/** 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 });
}
@@ -210,9 +208,8 @@ export class ProfileApi {
}
/**
* 修改收藏表情(custom face)备注。emoji_id 来自 fetchCustomFace 返回的
* URL 路径段;md5 从 emoji_id 中段解析,无需调用方单独提供。desc 为空串
* 则清空备注。
* 修改收藏表情(custom face)备注。emoji_id 来自收藏列表;md5 从 emoji_id
* 中段解析,无需调用方单独提供。desc 为空串则清空备注。
*/
modifyCustomFace(emojiId: string, desc: string): Promise<void> {
return ModifyCustomFace.invoke(this.ctx, {
@@ -230,11 +227,7 @@ export class ProfileApi {
*/
async moveCustomFaceToFront(emojiId: string): Promise<void> {
// 1. fetch 当前完整列表(fetch 顺序即可,不需要 DB 显示顺序)
const urls = await this.fetchCustomFace(1000);
const ids = urls.map((url) => {
const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url);
return m ? m[1] : '';
}).filter(Boolean);
const ids = await this.fetchCustomFaceIds(1000);
const idx = ids.indexOf(emojiId);
if (idx < 0) throw new Error(`emoji_id not in list: ${emojiId}`);
// 新顺序:目标挪到第一,其余按原顺序
+4 -2
View File
@@ -10,6 +10,7 @@ import {
GROUP_NOTICE_TYPE_NEW_MEMBERS,
GROUP_NOTICE_TYPE_NORMAL,
getGroupNoticeWebAPI,
groupNoticeImageUrl,
setGroupNoticeWebAPI,
uploadGroupNoticeImage,
type SetNoticeRetSuccess,
@@ -43,8 +44,8 @@ export interface WebNoticeInfo {
publish_time: number;
message: {
text: string;
image: Array<{ id: string; height: number; width: number }>;
images: Array<{ id: string; height: number; width: number }>;
image: Array<{ id: string; url: string; height: number; width: number }>;
images: Array<{ id: string; url: string; height: number; width: number }>;
};
settings: import('@snowluma/common/json').JsonValue;
read_num: number;
@@ -104,6 +105,7 @@ function mapGroupNoticeFeed(feed: WebApiGroupNoticeFeed, sendToNewMembers: boole
}
return {
id: pic.id,
url: groupNoticeImageUrl(pic.id),
height: finiteNumber(pic.h, `feed ${feed.fid} image ${index}.h`),
width: finiteNumber(pic.w, `feed ${feed.fid} image ${index}.w`),
};
@@ -1,8 +1,15 @@
import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
import type { BridgeContext } from './bridge-context';
export interface RosterWarmupResult {
friendsLoaded: boolean;
groupsLoaded: boolean;
}
export interface BridgeInterface extends BridgeContext {
readonly activePid: number | null;
/** Settles once for this Bridge session after first-login roster fetch. */
whenRosterWarmupSettled(): Promise<RosterWarmupResult>;
/** False only when every attached QQ process has a confirmed receive or
* request-path failure. An unarmed watchdog remains true for compatibility. */
readonly receiveHealthy: boolean;
+147 -2
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';
@@ -21,10 +22,11 @@ import {
type AiVoiceCategory,
type StrangerStatus,
} from './apis/extras';
import type { BridgeInterface } from './bridge-interface';
import type { BridgeInterface, RosterWarmupResult } from './bridge-interface';
const log = createLogger('Bridge');
const runtimeLog = createLogger('Bridge.Runtime');
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
export class Bridge implements BridgeInterface {
readonly identity: IdentityService;
@@ -46,6 +48,11 @@ export class Bridge implements BridgeInterface {
// Per-account dedup for QQ NT's already-deduped system pushes (#137).
private readonly sysMsgDedup_ = new SysMsgDedup();
private onlineClients_: readonly Readonly<OnlineDeviceInfo>[] | null = null;
private disposed_ = false;
private rosterWarmupStarted_ = false;
private rosterWarmupSettled_ = false;
private rosterWarmupResult_: RosterWarmupResult | null = null;
private readonly rosterWarmupWaiters_: Array<(result: RosterWarmupResult) => void> = [];
constructor(identity: IdentityService) {
this.identity = identity;
@@ -125,6 +132,8 @@ export class Bridge implements BridgeInterface {
}
dispose(): void {
this.disposed_ = true;
this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false });
this.pids_.clear();
this.receiveHealthByPid_.clear();
this.packetClientsByPid_.clear();
@@ -149,6 +158,7 @@ export class Bridge implements BridgeInterface {
const pid = pids.length > 0 ? pids[pids.length - 1]! : null;
this.packetClientPid_ = pid;
if (pid !== null) this.packetClientsByPid_.set(pid, client);
this.maybeStartRosterWarmup();
}
registerCmd(cmd: string, parser: CmdParser): void {
@@ -188,6 +198,7 @@ export class Bridge implements BridgeInterface {
previousPid,
);
}
this.maybeStartRosterWarmup();
}
/** @internal BridgeManager lookup used when an incoming packet is the first
@@ -244,6 +255,21 @@ export class Bridge implements BridgeInterface {
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null {
return this.onlineClients_;
}
whenRosterWarmupSettled(): Promise<RosterWarmupResult> {
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
return Promise.resolve(this.rosterWarmupResult_);
}
this.maybeStartRosterWarmup();
return new Promise((resolve) => {
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
resolve(this.rosterWarmupResult_);
return;
}
this.rosterWarmupWaiters_.push(resolve);
});
}
onPacket(pkt: PacketInfo): Promise<void> {
return this.pipeline.process(pkt);
}
@@ -271,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();
@@ -357,6 +383,125 @@ export class Bridge implements BridgeInterface {
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return this.identity.resolveUid(uin, groupId);
}
private maybeStartRosterWarmup(): void {
if (this.disposed_ || this.rosterWarmupStarted_ || !this.packetClient_) return;
this.rosterWarmupStarted_ = true;
if (!this.identity.nickname) this.identity.nickname = this.identity.uin;
void this.runRosterWarmup().then(
(result) => this.settleRosterWarmup(this.disposed_ ? { friendsLoaded: false, groupsLoaded: false } : result),
(err) => {
log.warn(
'roster warmup failed: uin=%s err=%s',
this.identity.uin,
err instanceof Error ? (err.stack ?? err.message) : String(err),
);
this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false });
},
);
}
private settleRosterWarmup(result: RosterWarmupResult): void {
if (this.rosterWarmupSettled_) return;
this.rosterWarmupSettled_ = true;
this.rosterWarmupResult_ = result;
const waiters = this.rosterWarmupWaiters_.splice(0);
for (const resolve of waiters) resolve(result);
}
private stillOpen(): boolean {
return !this.disposed_;
}
private async runRosterWarmup(): Promise<RosterWarmupResult> {
const uin = this.identity.uin;
const selfUin = parseInt(uin, 10) || 0;
let selfResolved = false;
let friendsLoaded = false;
try {
const friends = await this.apis.contacts.fetchFriendList();
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
friendsLoaded = true;
log.info('friends loaded: UIN=%s count=%d', uin, friends.length);
for (const friend of friends) {
if (friend.uin === selfUin) {
this.identity.setSelfProfile({
uin: friend.uin, uid: friend.uid,
nickname: friend.nickname || uin,
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
qidianMasterFlag: 0, qidianCrewFlag: 0, qidianCrewFlag2: 0,
});
this.identity.nickname = friend.nickname || uin;
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, friend.uid, friend.nickname ?? '');
selfResolved = true;
break;
}
}
} catch (e) {
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
log.warn('failed to load friends for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
}
if (!selfResolved && selfUin > 0 && this.stillOpen()) {
try {
const profile = await this.apis.contacts.fetchUserProfile(selfUin);
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
this.identity.setSelfProfile(profile);
this.identity.nickname = profile.nickname || uin;
log.debug('self info via profile: UIN=%s uid=%s nickname=%s',
uin, profile.uid, profile.nickname);
} catch (e) {
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
log.warn('failed to load self profile for UIN %s: %s',
uin, e instanceof Error ? e.message : String(e));
}
}
let groups: { groupId: number }[] = [];
let groupsLoaded = false;
try {
groups = await this.apis.contacts.fetchGroupList();
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
groupsLoaded = true;
log.info('groups loaded: UIN=%s count=%d', uin, groups.length);
} catch (e) {
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
log.warn('failed to load groups for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
}
let loadedGroupCount = 0;
let loadedMemberCount = 0;
let failedGroupCount = 0;
for (const group of groups) {
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
try {
const members = await this.apis.contacts.fetchGroupMemberList(group.groupId);
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
loadedGroupCount += 1;
loadedMemberCount += members.length;
if (VERBOSE_WARMUP) {
log.debug('members loaded: group=%d count=%d', group.groupId, members.length);
}
} catch (e) {
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
failedGroupCount += 1;
log.warn('failed to load members for group %d: %s', group.groupId, e instanceof Error ? e.message : String(e));
}
}
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
log.info(
'member warmup completed: UIN=%s groups=%d/%d members=%d failed=%d',
uin,
loadedGroupCount,
groups.length,
loadedMemberCount,
failedGroupCount,
);
return { friendsLoaded, groupsLoaded };
}
}
export interface SendMessageReceipt {
messageId: number;
+9 -1
View File
@@ -83,18 +83,20 @@ async function main() {
const notificationManager = createNotificationManager();
notificationManager.bind(bridgeManager);
let stopWebUI: (() => Promise<void>) | undefined;
if (
(typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) ||
process.env.SNOWLUMA_DEV_WEBUI === '1'
) {
try {
const { initWebUI } = await import('./webui/server');
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager, {
const started = await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager, {
host: runtimeConfig.webuiHost,
tlsEnabled: runtimeConfig.webuiTls?.enabled,
trustProxy: runtimeConfig.trustProxy,
stateBus: stateWiring.bus,
});
stopWebUI = started.stop;
} catch (err) {
log.error('Failed to start WebUI: ', err);
}
@@ -118,6 +120,12 @@ async function main() {
exitCode = 1;
log.error('notification shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
try {
if (stopWebUI) await stopWebUI();
} catch (error) {
exitCode = 1;
log.error('WebUI shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
// Observers go deaf before Hook teardown. Hook dispose then emits the
// same disconnected → PID detach → Bridge closed path as a live drop;
// those closed edges must not look like a runtime offline.
+147 -3
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');
@@ -31,16 +32,45 @@ export const CHANNEL_ID_RE = /^[\w.-]+$/;
const CHANNEL_ID_MAX = 64;
const CHANNEL_NAME_MAX = 128;
const BODY_TEMPLATE_MAX = 8192;
const HEADER_NAME_MAX = 128;
const HEADER_VALUE_MAX = 1024;
const HEADERS_MAX = 16;
const HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
/** event ∈ {offline, online}; rendered verbatim into `{event}`. */
export type NotificationEvent = 'offline' | 'online';
export type NotificationChannelType = 'webhook' | 'email';
export interface NotificationChannel {
id: string;
name: string;
type: NotificationChannelType;
/** http(s) webhook target. Empty on email channels. */
url: string;
bodyTemplate: string;
enabled: boolean;
/** Extra outbound request headers (Authorization, etc.). Webhook only. */
headers?: Record<string, string>;
smtpHost?: string;
smtpPort?: number;
smtpSecure?: boolean;
smtpUser?: string;
smtpPass?: string;
from?: string;
to?: string;
subjectTemplate?: string;
}
export function isEmailChannel(ch: NotificationChannel): ch is NotificationChannel & {
smtpHost: string;
smtpPort: number;
smtpSecure: boolean;
from: string;
to: string;
subjectTemplate: string;
} {
return ch.type === 'email';
}
export interface NotificationsConfig {
@@ -57,6 +87,23 @@ export const DEFAULT_BODY_TEMPLATE = `{
"desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**时间**:{time}"
}`;
export const DEFAULT_SUBJECT_TEMPLATE = '账号{event}:{nickname} ({uin})';
export const DEFAULT_EMAIL_BODY_TEMPLATE = `账号状态发生了改变。
昵称:{nickname}
QQ号:{uin}
当前状态:{event}
时间:{time}`;
const SMTP_HOST_MAX = 253;
const SMTP_USER_MAX = 256;
const SMTP_PASS_MAX = 256;
const EMAIL_FIELD_MAX = 1024;
const SUBJECT_TEMPLATE_MAX = 256;
const SMTP_PORT_MIN = 1;
const SMTP_PORT_MAX = 65535;
export function defaultNotificationsConfig(): NotificationsConfig {
return {
version: NOTIFICATIONS_CONFIG_VERSION,
@@ -118,21 +165,118 @@ function isHttpUrl(value: string): boolean {
}
}
/** A channel is usable only with a valid id AND an http(s) target — anything
* else is unusable, so the whole entry is dropped (total normalize). */
function normalizeHeaders(value: unknown): Record<string, string> | undefined {
if (!isObject(value)) return undefined;
const out: Record<string, string> = {};
const seen = new Set<string>();
for (const [rawName, rawValue] of Object.entries(value)) {
if (Object.keys(out).length >= HEADERS_MAX) break;
if (typeof rawValue !== 'string') continue;
const name = rawName.trim();
if (name.length === 0 || name.length > HEADER_NAME_MAX) continue;
if (!HEADER_NAME_RE.test(name)) continue;
const folded = name.toLowerCase();
if (seen.has(folded)) continue;
const headerValue = rawValue.trim();
if (headerValue.length === 0 || headerValue.length > HEADER_VALUE_MAX) continue;
if (headerValue.includes('\r') || headerValue.includes('\n')) continue;
seen.add(folded);
out[name] = headerValue;
}
return Object.keys(out).length > 0 ? out : undefined;
}
function normalizeSmtpHost(value: unknown): string | null {
if (typeof value !== 'string') return null;
const v = value.trim();
if (!v || v.length > SMTP_HOST_MAX) return null;
if (/\s/.test(v) || v.includes('/') || v.includes('://')) return null;
return v;
}
function normalizeFrom(value: unknown): string | null {
if (typeof value !== 'string') return null;
const v = value.trim().slice(0, EMAIL_FIELD_MAX);
return extractAddress(v) ? v : null;
}
function normalizeTo(value: unknown): string | null {
if (typeof value !== 'string') return null;
const addrs = parseRecipients(value.trim().slice(0, EMAIL_FIELD_MAX));
return addrs.length > 0 ? addrs.join(', ') : null;
}
function normalizeChannelType(value: unknown): NotificationChannelType | null {
if (value === 'email') return 'email';
if (value === 'webhook' || value === undefined || value === '') return 'webhook';
return null;
}
function normalizeEmailChannel(
raw: Record<string, unknown>,
id: string,
name: string,
): NotificationChannel | null {
const smtpHost = normalizeSmtpHost(raw.smtpHost);
const from = normalizeFrom(raw.from);
const to = normalizeTo(raw.to);
if (!smtpHost || !from || !to) return null;
const portRaw = raw.smtpPort;
const portProvided = portRaw !== undefined && portRaw !== null && portRaw !== '';
const secureProvided = typeof raw.smtpSecure === 'boolean';
const port = portProvided
? clampInt(portRaw, SMTP_PORT_MIN, SMTP_PORT_MAX, 0)
: 0;
if (portProvided && port === 0) return null;
const smtpSecure = secureProvided ? Boolean(raw.smtpSecure) : port === 465 || port === 0;
const smtpPort = port === 0 ? (smtpSecure ? 465 : 587) : port;
const smtpUser = typeof raw.smtpUser === 'string' ? raw.smtpUser.trim().slice(0, SMTP_USER_MAX) : '';
const smtpPass = typeof raw.smtpPass === 'string' ? raw.smtpPass.slice(0, SMTP_PASS_MAX) : '';
return {
id,
name,
type: 'email',
url: '',
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_EMAIL_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
enabled: boolOr(raw.enabled, true),
smtpHost,
smtpPort,
smtpSecure,
...(smtpUser ? { smtpUser } : {}),
...(smtpPass ? { smtpPass } : {}),
from,
to,
subjectTemplate: strOr(raw.subjectTemplate, DEFAULT_SUBJECT_TEMPLATE, SUBJECT_TEMPLATE_MAX) || DEFAULT_SUBJECT_TEMPLATE,
};
}
/** A channel is usable only with a valid id AND a deliverable target —
* http(s) URL for webhooks, SMTP host + from/to for email. Anything else
* is dropped (total normalize). */
function normalizeChannel(raw: unknown): NotificationChannel | null {
if (!isObject(raw)) return null;
const id = normalizeChannelId(raw.id);
if (!id) return null;
const type = normalizeChannelType(raw.type);
if (!type) return null;
const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id;
if (type === 'email') return normalizeEmailChannel(raw, id, name);
const url = typeof raw.url === 'string' ? raw.url.trim() : '';
if (!isHttpUrl(url)) return null;
const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id;
const headers = normalizeHeaders(raw.headers);
return {
id,
name,
type: 'webhook',
url,
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
enabled: boolOr(raw.enabled, true),
...(headers ? { headers } : {}),
};
}
+84 -27
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 }`. */
post: (url: string, body: string) => Promise<PostResult>;
/** Webhook delivery — never throws; failures come back as `{ ok: false }`. */
post: (url: string, body: string, headers?: Record<string, string>) => Promise<PostResult>;
/** SMTP delivery — optional so webhook-only tests stay lean. */
sendMail?: (mail: MailPayload) => Promise<PostResult>;
now: () => number;
historyLimit?: number;
}
@@ -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);
} 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)), 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,12 +263,14 @@ export class NotificationManager {
/** Default outbound POST: a single attempt with a timeout, JSON content-type
* (the common case for 钉钉/Discord/飞书). Never throws. */
export function createDefaultPost(timeoutMs = DEFAULT_POST_TIMEOUT_MS): NotificationManagerDeps['post'] {
return async (url, body) => {
export function createDefaultPost(
timeoutMs = positiveIntEnv('SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS', DEFAULT_POST_TIMEOUT_MS),
): NotificationManagerDeps['post'] {
return async (url, body, headers) => {
try {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: { 'Content-Type': 'application/json', ...headers },
body,
signal: AbortSignal.timeout(timeoutMs),
});
@@ -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');
}
+2 -13
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.
@@ -18,10 +18,10 @@ import { normalizeRuntimeConfig } from '@snowluma/common/runtime';
import { isRealUin } from '@snowluma/common/uin';
import { normalizeGlobalSettings } from '@snowluma/onebot/global-config';
import { prepareOneBotConfigForRestore } from '@snowluma/onebot/config';
import { isIP } from 'node:net';
import { normalizeNotificationsConfig } from '../notifications/config';
import { prepareWebuiAuthStateForRestore } from './auth';
import { MAX_BACKGROUND_BYTES, normalizeStoredUiConfig, sniffImageMime } from './ui-config';
import { isValidBindHost } from './listener-exposure';
import { validateTlsPair } from './tls';
export const BACKUP_VERSION = 1;
@@ -450,17 +450,6 @@ function serializeJson(value: unknown): Buffer {
return Buffer.from(JSON.stringify(value, null, 2), 'utf8');
}
function isValidBindHost(value: string): boolean {
const host = value.trim();
if (!host || host !== value || host.length > 253 || /[\s/?#@]/u.test(host)) return false;
if (host.includes(':')) return isIP(host) === 6;
if (/^[\d.]+$/.test(host)) {
return isIP(host) === 4;
}
const normalized = host.endsWith('.') ? host.slice(0, -1) : host;
return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$/.test(label));
}
function validateEffectiveTls(restore: PreparedRestoreFile[], opts: PrepareRestoreOptions): void {
const byName = new Map(restore.map((file) => [file.name, file.data]));
const pairTouched = byName.has('cert.pem') || byName.has('key.pem');
@@ -0,0 +1,27 @@
import { isIP } from 'node:net';
export type ListenerExposureCheck =
| { ok: true }
| { ok: false; code: 'invalid-bind-host' | 'tls-pair-required' };
/** TCP bind-host accepted by WebUI Listener Exposure (settings, restore, boot). */
export function isValidBindHost(value: string): boolean {
const host = value.trim();
if (!host || host !== value || host.length > 253 || /[\s/?#@]/u.test(host)) return false;
if (host.includes(':')) return isIP(host) === 6;
if (/^[\d.]+$/.test(host)) {
return isIP(host) === 4;
}
const normalized = host.endsWith('.') ? host.slice(0, -1) : host;
return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$/.test(label));
}
export function checkListenerExposure(input: {
webuiHost: string;
tlsEnabled: boolean;
pairOk: boolean;
}): ListenerExposureCheck {
if (!isValidBindHost(input.webuiHost)) return { ok: false, code: 'invalid-bind-host' };
if (input.tlsEnabled && !input.pairOk) return { ok: false, code: 'tls-pair-required' };
return { ok: true };
}
+40 -15
View File
@@ -56,7 +56,8 @@ import {
resolveEnvironmentConsent,
} from './consent';
import { requireTlsContext, resolveTlsContext, validateTlsPair } from './tls';
import { coerceSettingsPatch } from './system-settings';
import { coerceSettingsPatch, evaluateSettingsSave, tlsCertDeletionBlocked } from './system-settings';
import { checkListenerExposure } from './listener-exposure';
import { buildBackup } from './backup';
import { restoreBackup, RestoreTransactionError, type RestorePhase } from './restore';
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
@@ -470,7 +471,20 @@ export async function initWebUI(
hookManager?: HookManager,
notificationManager?: NotificationManager,
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string; stateBus?: StateBus } = {},
): Promise<{ port: number }> {
): Promise<{ port: number; stop: () => Promise<void> }> {
const host = listener.host || '127.0.0.1';
const tlsEnabled = listener.tlsEnabled === true;
const bootCheck = checkListenerExposure({
webuiHost: host,
tlsEnabled,
pairOk: resolveTlsContext('config').ok,
});
if (!bootCheck.ok) {
const reason = bootCheck.code === 'invalid-bind-host'
? `bind host is not a valid TCP address: ${host}`
: 'TLS is enabled but the certificate/private-key pair is unusable';
throw new Error(`WebUI listener cannot start: ${reason}`);
}
// Resolve the client IP for per-IP rate limiting from the configured
// trust-proxy directive (runtime.json `trustProxy`, env-overridable via
// SNOWLUMA_WEBUI_TRUST_PROXY which loadRuntimeConfig already merged in).
@@ -505,10 +519,9 @@ export async function initWebUI(
// adapter detail strings at sub-second cadence wasn't required. If it
// becomes one, surface client-count as a structured field on
// AdapterStatus and include it in the comparable.
let connectionDiffLoop: ReturnType<typeof startConnectionDiffLoop> | undefined;
if (listener.stateBus) {
// Handle deliberately discarded — initWebUI has no shutdown path; the
// loop's setInterval is .unref'd so it doesn't pin the event loop.
startConnectionDiffLoop({
connectionDiffLoop = startConnectionDiffLoop({
bus: listener.stateBus,
getSnapshot: () => oneBotManager.getConnectionStatuses(),
pickComparable: comparableConnectionSnapshot,
@@ -1128,11 +1141,13 @@ export async function initWebUI(
}
const coerced = coerceSettingsPatch(body);
if (!coerced.ok) return c.json({ success: false, message: coerced.error }, 400);
// Enabling TLS without a usable cert would brick HTTPS on restart — block it.
if (coerced.patch.webuiTls?.enabled && !resolveTlsContext('config').ok) {
return c.json({ success: false, message: '启用 TLS 前请先上传有效的证书与私钥' }, 400);
}
const saved = updateRuntimeConfig(coerced.patch);
const evaluated = evaluateSettingsSave(
readRuntimeConfig(),
coerced.patch,
resolveTlsContext('config').ok,
);
if (!evaluated.ok) return c.json({ success: false, message: evaluated.error }, 400);
const saved = updateRuntimeConfig(evaluated.patch);
return c.json({
success: true,
settings: {
@@ -1201,6 +1216,9 @@ export async function initWebUI(
});
app.delete('/api/system/tls/cert', (c) => {
if (tlsCertDeletionBlocked(readRuntimeConfig().webuiTls?.enabled === true)) {
return c.json({ success: false, message: '请先关闭 TLS 再删除证书' }, 400);
}
try {
rmSync(SYSTEM_CERT_PATH, { force: true });
rmSync(SYSTEM_KEY_PATH, { force: true });
@@ -1778,7 +1796,6 @@ export async function initWebUI(
);
});
const host = listener.host || '127.0.0.1';
const finalPort = await findAvailablePort(desiredPort, { host });
if (finalPort !== desiredPort) {
log.warn('port %d is in use, using %d instead', desiredPort, finalPort);
@@ -1795,11 +1812,19 @@ export async function initWebUI(
scheme = 'https';
}
await new Promise<void>((resolve) => {
serve({ fetch: app.fetch, port: finalPort, hostname: host, ...(tlsServe ?? {}) }, (info) => {
const listeningServer = await new Promise<ReturnType<typeof serve>>((resolve) => {
const server = serve({ fetch: app.fetch, port: finalPort, hostname: host, ...(tlsServe ?? {}) }, (info) => {
log.info(`listening ${scheme}://${host}:${info.port}`);
resolve();
resolve(server);
});
});
return { port: finalPort };
return {
port: finalPort,
async stop() {
connectionDiffLoop?.dispose();
await new Promise<void>((resolve, reject) => {
listeningServer.close((err) => (err ? reject(err) : resolve()));
});
},
};
}
@@ -4,6 +4,7 @@
// nested `webuiTls.enabled`.
import type { RuntimeConfig } from '@snowluma/common/runtime';
import { checkListenerExposure } from './listener-exposure';
export type SettingsPatch = Partial<Pick<RuntimeConfig, 'webuiPort' | 'webuiHost' | 'webuiTls' | 'trustProxy'>>;
@@ -50,3 +51,25 @@ export function coerceSettingsPatch(body: unknown): CoerceResult {
return { ok: true, patch };
}
const SETTINGS_ERRORS: Record<'invalid-bind-host' | 'tls-pair-required', string> = {
'invalid-bind-host': '绑定地址不是有效的 TCP 地址',
'tls-pair-required': '启用 TLS 前请先上传有效的证书与私钥',
};
/** Validate the listener that would be persisted after applying `patch` to `current`. */
export function evaluateSettingsSave(
current: RuntimeConfig,
patch: SettingsPatch,
pairOk: boolean,
): CoerceResult {
const webuiHost = patch.webuiHost ?? current.webuiHost ?? '127.0.0.1';
const tlsEnabled = patch.webuiTls?.enabled ?? current.webuiTls?.enabled ?? false;
const check = checkListenerExposure({ webuiHost, tlsEnabled, pairOk });
if (!check.ok) return { ok: false, error: SETTINGS_ERRORS[check.code] };
return { ok: true, patch };
}
export function tlsCertDeletionBlocked(tlsEnabled: boolean): boolean {
return tlsEnabled;
}
@@ -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: {
@@ -27,7 +27,6 @@ import { describe, it, expect, vi } from 'vitest';
import { gunzipSync } from 'zlib';
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
encodeOidbEnv: vi.fn(() => new Uint8Array()),
decodeOidbEnv: vi.fn(() => ({ body: {} })),
@@ -0,0 +1,77 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import { buildApiContext, type OneBotInstanceContext } from '@snowluma/onebot/instance-context';
import { ForwardApi } from '../../src/bridge/apis/forward';
import { mockBridge } from './_helpers';
vi.mock('@snowluma/protocol/highway/image-upload', () => ({ uploadImageMsgInfo: vi.fn() }));
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ uploadPttMsgInfo: vi.fn() }));
vi.mock('@snowluma/protocol/highway/video-upload', () => ({ uploadVideoMsgInfo: vi.fn() }));
describe('forward metadata through upload and cached reads', () => {
it.each([
{ nested: false, enrich: false }, { nested: true, enrich: false },
{ nested: false, enrich: true }, { nested: true, enrich: true },
])('preserves titles and previews with nesting=$nested and enrichment=$enrich', async ({ nested, enrich }) => {
let uploadCount = 0;
const sendRawPacket = vi.fn(async () => ({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<SendLongMsgResp>({
result: { resId: `metadata-${nested}-${enrich}-${++uploadCount}` },
})),
}));
const bridge = mockBridge({ sendRawPacket });
bridge.apis.contacts.fetchGroupMemberList.mockResolvedValue([
{ uin: 111, nickname: 'resolved outer', card: '' },
]);
const forward = new ForwardApi(bridge as any);
const ctx = {
selfId: 10001,
bridge: { apis: {
forward,
message: { sendGroup: vi.fn(async () => ({
messageId: 1, sequence: 2, clientSequence: 0, random: 3, timestamp: 1700000000,
})) },
} },
messageStore: { findEvent: () => null, findMedia: () => null },
cacheMessageMeta: vi.fn(),
converterCtx: {
selfId: 10001, imageUrlResolver: null, mediaUrlResolver: null,
messageIdResolver: null, mediaSegmentSink: null,
},
} as unknown as OneBotInstanceContext;
const api = buildApiContext(ctx);
const text = [{ type: 'text', data: { text: 'hello' } }];
const preview = {
title: 'outer title', source: 'custom source', summary: 'custom summary',
prompt: 'custom prompt', news: [{ text: 'custom preview' }],
};
const { forwardId } = await api.sendGroupForwardMsg(12345, [{
type: 'node', data: {
user_id: 111, nickname: enrich ? '' : 'outer', ...preview,
content: nested
? [{ type: 'node', data: { user_id: 222, nickname: 'inner', title: 'inner title', content: text } }]
: text,
},
}]);
const first = await api.getForwardMsg(forwardId);
expect(first[0]!.sender).toMatchObject({ title: 'outer title' });
expect(first[0]!.sender).toMatchObject({ nickname: enrich ? 'resolved outer' : 'outer' });
expect((await forward.fetch(forwardId!))[0]).toMatchObject(preview);
if (nested) {
expect((await api.getForwardMsg(`metadata-true-${enrich}-1`))[0]!.sender)
.toMatchObject({ title: 'inner title' });
}
const fetched = await forward.fetch(forwardId!);
fetched[0]!.title = 'changed title';
fetched[0]!.news![0]!.text = 'changed preview';
preview.news[0]!.text = 'changed input';
const again = await forward.fetch(forwardId!);
expect(again[0]!.title).toBe('outer title');
expect(again[0]!.news).toEqual([{ text: 'custom preview' }]);
expect(sendRawPacket).toHaveBeenCalledTimes(nested ? 2 : 1);
});
});
@@ -59,7 +59,7 @@ function decodeOuterLongMsg(rawBytes: Uint8Array): LongMsgResult {
return protobuf_decode<LongMsgResult>(gunzipSync(Buffer.from(payload)));
}
function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: string; app?: string } | null {
function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: string; app?: string; news?: Array<{ text: string }>; source?: string; summary?: string } | null {
for (const body of msgBody) {
const elems: Elem[] = body.body?.richText?.elems ?? [];
for (const elem of elems) {
@@ -74,6 +74,9 @@ function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: st
app: parsed.app,
resid: parsed.meta?.detail?.resid,
uniseq: parsed.meta?.detail?.uniseq,
news: parsed.meta?.detail?.news,
source: parsed.meta?.detail?.source,
summary: parsed.meta?.detail?.summary,
};
}
} catch { /* ignore */ }
@@ -178,4 +181,86 @@ describe('forward / nested upload wire alignment', () => {
expect(outermost.action![2]!.actionCommand).not.toBe('MultiMsg');
expect(outermost.action![1]!.actionCommand).not.toBe(outermost.action![2]!.actionCommand);
});
it('inner forward bubble prefers caller-supplied node news over auto-generated lines', async () => {
const responses = ['inner-res', 'outer-res'];
const sendRawPacket = vi.fn(async () =>
uploadResponseWithResId(responses.shift()!)) as any;
const bridge = mockBridge({ sendRawPacket });
const customNews = [{ text: '自定义预览行 1' }, { text: '自定义预览行 2' }];
await new ForwardApi(bridge as any).upload([{
userUin: 111,
nickname: 'outer',
elements: [],
news: customNews,
innerForward: [
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: '会被覆盖的正文' }] },
],
}]);
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
const outerMsgBody = decodeOuterLongMsg(outerBytes).action![0]!.actionData!.msgBody!;
const preview = findLightAppJson(outerMsgBody);
expect(preview).not.toBeNull();
// Caller-supplied news wins over `inner: 会被覆盖的正文`.
expect(preview!.news).toEqual(customNews);
});
it('inner forward bubble falls back to auto-generated lines when node has no news', async () => {
const responses = ['inner-res', 'outer-res'];
const sendRawPacket = vi.fn(async () =>
uploadResponseWithResId(responses.shift()!)) as any;
const bridge = mockBridge({ sendRawPacket });
await new ForwardApi(bridge as any).upload([{
userUin: 111,
nickname: 'outer',
elements: [],
// no `news` field — auto-generate from inner nodes
innerForward: [
{ userUin: 222, nickname: '内层说话人', elements: [{ type: 'text', text: '第一句台词' }] },
],
}]);
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
const outerMsgBody = decodeOuterLongMsg(outerBytes).action![0]!.actionData!.msgBody!;
const preview = findLightAppJson(outerMsgBody);
expect(preview).not.toBeNull();
expect(preview!.news).toEqual([{ text: '内层说话人: 第一句台词' }]);
});
it('inner forward card prefers caller-supplied source/summary/prompt metadata', async () => {
const responses = ['inner-res', 'outer-res'];
const sendRawPacket = vi.fn(async () =>
uploadResponseWithResId(responses.shift()!)) as any;
const bridge = mockBridge({ sendRawPacket });
await new ForwardApi(bridge as any).upload([{
userUin: 111,
nickname: 'outer',
elements: [],
source: '万叶的手记',
summary: '共 12 条剧情消息',
prompt: '查看剧情',
innerForward: [
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] },
],
}]);
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
const outerMsgBody = decodeOuterLongMsg(outerBytes).action![0]!.actionData!.msgBody!;
const preview = findLightAppJson(outerMsgBody);
expect(preview).not.toBeNull();
// decodeOuterLongMsg → lightApp meta.detail as built by element-builder
expect(preview!.app).toBe('com.tencent.multimsg');
// The plaintext preview lines of the wire bubble.
// Caller metadata wins: source = 万叶的手记, summary used instead of
// the auto-generated `查看N条转发消息`.
expect(preview!.source).toBe('万叶的手记');
expect(preview!.summary).toBe('共 12 条剧情消息');
});
});
+23 -1
View File
@@ -1,7 +1,6 @@
import { describe, it, expect, vi } from 'vitest';
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
encodeOidbEnv: vi.fn(() => new Uint8Array()),
decodeOidbEnv: vi.fn(() => ({ body: {} })),
@@ -122,6 +121,29 @@ describe('actions/forward', () => {
])).rejects.toThrow(/missing res_id/);
});
it('cached fetch after upload keeps a usable image source (#441)', async () => {
const sendRawPacket = vi.fn(async () => uploadResponseWithResId('res-img-cache')) as any;
const bridge = mockBridge({ sendRawPacket });
const source = 'https://cdn.example/bot-built.png';
const resId = await new ForwardApi(bridge as any).upload([
{
userUin: 10001,
nickname: 'alice',
elements: [{ type: 'image', url: source }],
},
]);
const fetched = await new ForwardApi(bridge as any).fetch(resId);
expect(fetched).toHaveLength(1);
expect(fetched[0]!.elements[0]).toMatchObject({
type: 'image',
url: source,
imageUrl: source,
});
expect(sendRawPacket).toHaveBeenCalledTimes(1);
});
it('fetchForwardNodes serves from cache after a successful upload (no second sendRawPacket)', async () => {
const sendRawPacket = vi.fn(async () => uploadResponseWithResId('res-cache')) as any;
const bridge = mockBridge({ sendRawPacket });
+172
View File
@@ -1,17 +1,25 @@
import { describe, it, expect, vi } from 'vitest';
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { pb, pb_repeated, uint_32, uint_64 } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbDeleteFriend,
OidbFriendRequestAction,
OidbSetFriendRemarkResponse,
} from '@snowluma/proto-defs/oidb-actions/base';
import type {
OidbDoubtApprovalReq,
OidbDoubtDelReq,
OidbDoubtGetResp,
} from '@snowluma/proto-defs/oidb-actions/doubt-buddy';
// Post-namespace migration: FriendApi is a thin facade over the
// namespaces under @snowluma/protocol/oidb-services/friend. Tests assert
// against the bridge mock's sendRawPacket directly — no need for
// module-level bridge-oidb mocks anymore.
import { DATALINE_UIN_PAD } from '@snowluma/protocol/dataline/device-contacts';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { FriendApi } from '../../src/bridge/apis/friend';
import { mockBridge } from './_helpers';
@@ -89,10 +97,174 @@ describe('apis/friend', () => {
.toHaveBeenCalledWith('resolved-uid', 10001, 'best-friend');
});
it('refuses to delete or rename a my-device contact', async () => {
const bridge = mockBridge();
const api = new FriendApi(bridge as any);
await expect(api.delete(DATALINE_UIN_PAD)).rejects.toThrow('cannot be deleted');
await expect(api.setRemark(DATALINE_UIN_PAD, 'pad')).rejects.toThrow('does not support remarks');
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('setRemark uses the dedicated clear command for an empty remark', async () => {
const bridge = mockBridge();
await new FriendApi(bridge as any).setRemark(10001, '');
expect(bridge.sendRawPacket.mock.calls[0]![0])
.toBe('OidbSvcTrpcTcp.0x912f_0');
});
it('getDoubtRequests fills a missing uid via resolveUserUid', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: encodeNumericDoubtList([{ nick: 'Alice', uin: 12345n, reqTime: 1700000000n }]),
})),
});
const list = await new FriendApi(bridge as any).getDoubtRequests(10);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(12345);
expect(list).toEqual([
{
uid: 'resolved-uid', user_id: 12345, nick: 'Alice', source: '',
reason: '', msg: '', group_code: '', reqTime: 1700000000,
},
]);
});
it('getDoubtRequests keeps a wire uid and does not resolve', async () => {
const bridge = mockBridge({
identity: { findUinByUid: vi.fn(() => 12345) } as any,
sendRawPacket: vi.fn(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: encodeDoubtList([
{ uid: 'u_alice', nick: 'Alice', reqTime: 1700000000n },
]),
})),
});
const list = await new FriendApi(bridge as any).getDoubtRequests(10);
expect(bridge.resolveUserUid).not.toHaveBeenCalled();
expect(list[0]?.uid).toBe('u_alice');
expect(list[0]?.user_id).toBe(12345);
});
it('getDoubtRequests keeps an empty uid when resolveUserUid fails', async () => {
const bridge = mockBridge({
resolveUserUid: vi.fn(async () => { throw new Error('no mapping'); }),
sendRawPacket: vi.fn(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: encodeNumericDoubtList([{ nick: 'Alice', uin: 12345n }]),
})),
});
const captured: LogEntry[] = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.scope === 'Bridge.Friend') captured.push(entry);
});
try {
const list = await new FriendApi(bridge as any).getDoubtRequests(10);
expect(list[0]?.uid).toBe('');
expect(list[0]?.user_id).toBe(12345);
} finally {
unsubscribe();
}
expect(captured.map(({ level, message }) => ({ level, message }))).toEqual([{
level: 'warn',
message: 'doubt-request uid resolve failed: user=12345 err=no mapping',
}]);
});
it('approveDoubtRequest resolves a digit-only flag before sending', async () => {
const bridge = mockBridge();
await new FriendApi(bridge as any).approveDoubtRequest('12345');
expect(bridge.resolveUserUid).toHaveBeenCalledWith(12345);
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0xd72_0');
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
expect(env.body).toMatchObject({ selfUid: 'self-uid', targetUid: 'resolved-uid', field3: 0, field4: '' });
});
it('approveDoubtRequest forwards a uid flag without resolving', async () => {
const bridge = mockBridge();
await new FriendApi(bridge as any).approveDoubtRequest('u_abc');
expect(bridge.resolveUserUid).not.toHaveBeenCalled();
const [, bytes] = bridge.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
expect(env.body).toMatchObject({ selfUid: 'self-uid', targetUid: 'u_abc' });
});
it('approves a filtered stranger through Identity without requiring a shared roster', async () => {
const identity = new IdentityService('10001', null);
const bridge = mockBridge();
const fetchProfile = vi.fn(async (uin: number) => ({
uin, uid: uin === 10001 ? 'u_self' : 'u_stranger',
}));
identity.setFetcher({ fetchProfile: fetchProfile as any });
bridge.identity = identity as any;
bridge.resolveUserUid = vi.fn((uin: number) => identity.resolveUid(uin));
try {
await new FriendApi(bridge as any).approveDoubtRequest('12345');
expect(fetchProfile.mock.calls.map(([uin]) => uin)).toEqual([12345, 10001]);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
const [, bytes] = bridge.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
expect(env.body).toMatchObject({ selfUid: 'u_self', targetUid: 'u_stranger' });
} finally {
identity.close();
}
});
it('does not send an approval when the applicant cannot be resolved', async () => {
const bridge = mockBridge({
resolveUserUid: vi.fn(async () => { throw new Error('applicant lookup failed'); }),
});
await expect(new FriendApi(bridge as any).approveDoubtRequest('12345'))
.rejects.toThrow('applicant lookup failed');
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('rejectDoubtRequest resolves a digit-only flag before sending', async () => {
const bridge = mockBridge();
await new FriendApi(bridge as any).rejectDoubtRequest('12345');
expect(bridge.resolveUserUid).toHaveBeenCalledWith(12345);
const [, bytes] = bridge.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbDoubtDelReq>>(bytes);
expect(env.body).toMatchObject({ field1: 3, inner: { uid: 'resolved-uid' } });
});
});
function encodeDoubtList(
list: NonNullable<NonNullable<OidbDoubtGetResp['body']>['list']>,
): Buffer {
return Buffer.from(protobuf_encode<OidbBase<OidbDoubtGetResp>>({
command: 0xD69,
subCommand: 0,
body: { status: 1, body: { list } },
}));
}
interface NumericDoubtItem {
uin?: pb<1, uint_64>;
nick?: pb<2, string>;
reqTime?: pb<8, uint_64>;
}
interface NumericDoubtBody {
list?: pb_repeated<1, NumericDoubtItem>;
}
interface NumericDoubtResponse {
status?: pb<1, uint_32>;
body?: pb<2, NumericDoubtBody>;
}
function encodeNumericDoubtList(list: NumericDoubtItem[]): Buffer {
return Buffer.from(protobuf_encode<OidbBase<NumericDoubtResponse>>({
command: 0xD69,
subCommand: 0,
body: { status: 1, body: { list } },
}));
}
+146 -14
View File
@@ -11,8 +11,10 @@ import type {
Oidb0x89a_0HistoryVisibility,
Oidb0x89a_0MemberPermission,
Oidb0xf16Req,
OidbGroupDetailRequest,
OidbGroupRequestAction,
OidbKickMember,
OidbKickMemberResponse,
OidbLeaveGroup,
OidbMuteAll,
OidbMuteMember,
@@ -21,11 +23,16 @@ import type {
OidbSetAdmin,
OidbSpecialTitle,
} from '@snowluma/proto-defs/oidb-actions/base';
import type {
OidbChangeGroupCategoryTag,
OidbGetGroupCategoryTags,
OidbGetGroupCategoryTagsResp,
} from '@snowluma/proto-defs/oidb-actions/group-category-tag';
// Post-namespace migration: GroupAdminApi forwards through namespaces
// under @snowluma/protocol/oidb-services/group-admin. Tests assert
// against bridge.sendRawPacket directly — no module-level mocks.
import { GroupAdminApi } from '../../src/bridge/apis/group-admin';
import { GroupAdminApi, MEMBER_PERMISSIONS_OWNER_ONLY } from '../../src/bridge/apis/group-admin';
import { mockBridge } from './_helpers';
function packResponse(body: Uint8Array) {
@@ -35,17 +42,27 @@ function packResponse(body: Uint8Array) {
};
}
function packPrivilegeFlag(privilegeFlag?: number) {
function packPrivilegeFlag(privilegeFlag?: number, ownerUid?: string) {
return packResponse(protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
body: {
groupInfo: {
uin: 12345n,
results: privilegeFlag === undefined ? {} : { privilegeFlag },
results: {
...(privilegeFlag === undefined ? {} : { privilegeFlag }),
...(ownerUid === undefined ? {} : { ownerUid }),
},
},
},
}));
}
function packOidbFail(code: number) {
return {
success: false, gotResponse: true, errorCode: code, errorMessage: '',
responseData: Buffer.alloc(0),
};
}
function packGroupFlagExt4(groupFlagExt4?: number) {
return packResponse(protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
body: {
@@ -124,18 +141,30 @@ describe('apis/group-admin', () => {
});
});
it('kickMember rejects a server business error instead of reporting success (#298)', async () => {
it('kickMember treats a zero per-member result as success (#413)', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
Buffer.from(
'222008b960121be7bea4e4b8bbe697a0e6b395e8a2abe7a7bbe587bae7bea4e8818a',
'hex',
),
protobuf_encode<OidbBase<OidbKickMemberResponse>>({
body: { groupUin: 12345, results: [{ result: 0, uid: 'u_abcdefghijklmnopqrstuv' }] },
}),
));
await expect(
new GroupAdminApi(bridge as any).kickMember(12345, 67890, false),
).rejects.toThrow('群主无法被移出群聊');
).resolves.toBeUndefined();
});
it('kickMember rejects a server business error instead of reporting success (#298)', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbKickMemberResponse>>({
body: { groupUin: 12345, results: [{ result: 1, uid: 'u_abcdefghijklmnopqrstuv' }] },
}),
));
await expect(
new GroupAdminApi(bridge as any).kickMember(12345, 67890, false),
).rejects.toThrow('kick member failed: result=1');
});
it('kickMembers resolves each UID in parallel', async () => {
@@ -154,15 +183,14 @@ describe('apis/group-admin', () => {
it('kickMembers rejects the same command-level business error', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
Buffer.from(
'222008b960121be7bea4e4b8bbe697a0e6b395e8a2abe7a7bbe587bae7bea4e8818a',
'hex',
),
protobuf_encode<OidbBase<OidbKickMemberResponse>>({
body: { groupUin: 12345, results: [{ result: 1, uid: 'u_abcdefghijklmnopqrstuv' }] },
}),
));
await expect(
new GroupAdminApi(bridge as any).kickMembers(12345, [67890], false),
).rejects.toThrow('群主无法被移出群聊');
).rejects.toThrow('kick members failed: result=1');
});
it('leave sends 0x1097_1, emits a self group_member_leave, and forgets the group (#133)', async () => {
@@ -475,9 +503,11 @@ describe('apis/group-admin', () => {
allowMemberUploadAlbum: true,
});
expect(bridge.sendRawPacket.mock.calls[1]![0]).toBe('OidbSvcTrpcTcp.0x89a_0');
const envelope = protobuf_decode<OidbBase<Oidb0x89a_0MemberPermission>>(
bridge.sendRawPacket.mock.calls[1]![1],
);
expect(envelope.subCommand ?? 0).toBe(0);
expect(envelope.body?.settings).toEqual({
appPrivilegeFlag: 0,
appPrivilegeMask: 1,
@@ -500,6 +530,53 @@ describe('apis/group-admin', () => {
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
});
it('setMemberPermissions rejects a non-owner before writing (#411)', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packPrivilegeFlag(0x80000001, 'u_owner'));
await expect(
new GroupAdminApi(bridge as any).setMemberPermissions(12345, {
allowMemberUploadAlbum: true,
}),
).rejects.toThrow(MEMBER_PERMISSIONS_OWNER_ONLY);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x88d_0');
});
it('setMemberPermissions maps a not-owner server refusal to a readable error (#411)', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(packPrivilegeFlag(0x80000001))
.mockResolvedValueOnce(packOidbFail(1287));
await expect(
new GroupAdminApi(bridge as any).setMemberPermissions(12345, {
allowMemberUploadAlbum: true,
}),
).rejects.toThrow(MEMBER_PERMISSIONS_OWNER_ONLY);
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
'OidbSvcTrpcTcp.0x88d_0',
'OidbSvcTrpcTcp.0x89a_0',
]);
});
it('setMemberPermissions writes when the bot is the group owner', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(packPrivilegeFlag(0x80000001, 'self-uid'))
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packPrivilegeFlag(0, 'self-uid'));
await new GroupAdminApi(bridge as any).setMemberPermissions(12345, {
allowMemberUploadAlbum: true,
});
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
'OidbSvcTrpcTcp.0x88d_0',
'OidbSvcTrpcTcp.0x89a_0',
'OidbSvcTrpcTcp.0x88d_0',
]);
});
it('setMemberPermissions rejects an ack when final read-back does not match', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
@@ -568,6 +645,11 @@ describe('apis/group-admin', () => {
'OidbSvcTrpcTcp.0x88d_0',
'OidbSvcTrpcTcp.0xef0_1',
]);
const detailReq = protobuf_decode<OidbBase<OidbGroupDetailRequest>>(
bridge.sendRawPacket.mock.calls.find((call) => call[0] === 'OidbSvcTrpcTcp.0x88d_0')![1],
);
expect(detailReq.body?.config?.flags?.question).toBe('');
expect(detailReq.body?.config?.flags?.answer).toBe('');
});
it('getAdminSettings treats omitted detail/ext zeros as the default values', async () => {
@@ -628,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();
});
});
@@ -2,8 +2,13 @@ import { describe, expect, it } from 'vitest';
import type {
DeleteMediasRequest,
DeleteMediasResponse,
DoQunCommentRequest,
DoQunCommentResponse,
GetAlbumListResponse,
GetMediaListResponse,
GetQunFeedDetailRequest,
GetQunFeedDetailResponse,
QunFeedCellCommon,
} from '@snowluma/proto-defs/oidb-actions/group-album';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { GroupAlbumApi } from '../../src/bridge/apis/group-album';
@@ -563,4 +568,377 @@ describe('apis/group-album', () => {
expect(request.body?.mediaIds).toEqual(['unknown-id']);
expect(request.body?.batchIds ?? []).toEqual([]);
});
function packCommentOk(comment: DoQunCommentResponse['comment']): ReturnType<typeof packDeleteOk> {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<DoQunCommentResponse>({
field1: 8527,
comment,
})),
};
}
function packFeedDetail(
feedId = 'official-feed-id',
time = 1700000123n,
extra: {
ownerUin?: string;
cellCommon?: Omit<QunFeedCellCommon, 'time' | 'feedId'>;
cellMedia?: {
medias?: Array<{ type?: number; image?: { lloc?: string }; video?: { cover?: { lloc?: string } } }>;
albumId?: string;
batchId?: bigint;
};
} = {},
): ReturnType<typeof packDeleteOk> {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<GetQunFeedDetailResponse>({
result: 0,
data: {
feed: {
feed: {
cellCommon: { time, feedId, ...extra.cellCommon },
...(extra.ownerUin ? { cellUserInfo: { user: { uin: extra.ownerUin } } } : {}),
...(extra.cellMedia ? { cellMedia: extra.cellMedia } : {}),
},
},
},
})),
};
}
function packPhotoMedia(lloc = 'photo-lloc', batchId = 77n) {
return packMediaList({
mediaList: [{ type: 1, image: { lloc }, batchId }],
});
}
function commentMocks(
extra: (cmd: string) => ReturnType<typeof packDeleteOk> | undefined = () => undefined,
) {
return async (cmd: string) => {
const override = extra(cmd);
if (override) return override;
if (cmd.endsWith('GetMediaList')) return packPhotoMedia();
if (cmd.endsWith('GetQunFeedDetail')) {
return packFeedDetail('official-feed-id', 1700000123n, {
ownerUin: '3119936551',
cellCommon: {
type: 422,
cellId: '421_1_0_12345|album-id|77^||^421_1_0_12345|album-id|photo-lloc^||^0',
field6: 3,
},
});
}
return packCommentOk({
data: {
id: 'cmt-1',
user: { uin: '10001' },
content: [{ type: 0, content: 'hello' }],
time: 1700000000n,
clientKey: 'ck',
},
});
};
}
function commentCallBytes(bridge: ReturnType<typeof mockBridge>): Uint8Array {
const commentCall = bridge.sendRawPacket.mock.calls.find((call) =>
String(call[0]).endsWith('DoQunComment'),
);
expect(commentCall?.[0]).toBe(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
);
return commentCall![1] as Uint8Array;
}
function commentRequestOf(bridge: ReturnType<typeof mockBridge>): DoQunCommentRequest {
return protobuf_decode<DoQunCommentRequest>(commentCallBytes(bridge));
}
function feedDetailRequestOf(bridge: ReturnType<typeof mockBridge>): GetQunFeedDetailRequest {
const feedCall = bridge.sendRawPacket.mock.calls.find((call) =>
String(call[0]).endsWith('GetQunFeedDetail'),
);
expect(feedCall?.[0]).toBe(
'QunAlbum.trpc.qzone.webapp_qun_feeds.FeedsReader.GetQunFeedDetail',
);
return protobuf_decode<GetQunFeedDetailRequest>(feedCall![1] as Uint8Array);
}
it('looks up the official feed then comments with its header and slim photo cell', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks());
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
.resolves.toEqual({
id: 'cmt-1',
user: { uin: '10001' },
content: [{ type: 0, content: 'hello' }],
time: '1700000000',
clientKey: 'ck',
});
expect(feedDetailRequestOf(bridge).data).toMatchObject({
groupId: '12345',
commentCount: 20,
albumId: 'album-id',
batchId: '77',
lloc: 'photo-lloc',
});
expect(feedDetailRequestOf(bridge).data?.feedId ?? '').toBe('');
expect(feedDetailRequestOf(bridge).data?.attachInfo ?? '').toBe('');
const request = commentRequestOf(bridge);
expect(request.field1).toBe(8527);
expect(request.body).toMatchObject({
groupId: '12345',
field3: 2,
reqBody: {
field1: {
time: 1700000123n,
feedId: 'official-feed-id',
},
field2: { field1: { uin: '3119936551' } },
field5: {
albumId: 'album-id',
batchId: 77n,
medias: [{
image: { lloc: 'photo-lloc' },
}],
},
},
field5: {
user: { uin: '10001' },
contents: [{ content: 'hello' }],
},
});
expect(request.body?.reqBody?.field5?.medias?.[0]?.type ?? 0).toBe(0);
expect(Buffer.from(commentCallBytes(bridge)).subarray(0, 7).toString('hex'))
.toBe('08cf4212001a00');
});
it('falls back to the media uploader when the official feed has no owner cell', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('GetMediaList')) {
return packMediaList({
mediaList: [{ type: 1, image: { lloc: 'photo-lloc' }, batchId: 77n, uploader: '3119936551' }],
});
}
if (cmd.endsWith('GetQunFeedDetail')) return packFeedDetail();
return undefined;
}));
await new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello');
expect(commentRequestOf(bridge).body?.reqBody?.field2?.field1?.uin).toBe('3119936551');
expect(commentRequestOf(bridge).body?.field5?.user?.uin).toBe('10001');
});
it('copies the official feed media cell instead of a reconstructed lloc-only cell', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('GetQunFeedDetail')) {
return packFeedDetail('official-feed-id', 1700000123n, {
ownerUin: '3119936551',
cellMedia: {
albumId: 'feed-album',
batchId: 88n,
medias: [{
type: 0,
image: { lloc: 'feed-lloc' },
}],
},
});
}
return undefined;
}));
await new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello');
expect(commentRequestOf(bridge).body?.reqBody?.field5).toMatchObject({
albumId: 'feed-album',
batchId: 88n,
medias: [{
image: { lloc: 'feed-lloc' },
}],
});
});
it('writes only the official comment header fields even when the feed cell has extra locator data', async () => {
const cellId = '421_1_0_964445447|album-id|2147483665^||^421_1_0_964445447|album-id|photo-lloc^||^0';
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('GetQunFeedDetail')) {
return packFeedDetail('422_0_2147483665', 1789315793n, {
ownerUin: '3119936551',
cellCommon: { type: 422, cellId, field6: 3 },
});
}
return undefined;
}));
await new GroupAlbumApi(bridge as never).comment(964445447, 'album-id', 'photo-lloc', 'hello');
expect(commentRequestOf(bridge).body?.reqBody?.field1).toMatchObject({
time: 1789315793n,
feedId: '422_0_2147483665',
});
expect(commentRequestOf(bridge).body?.reqBody?.field1?.type ?? 0).toBe(0);
expect(commentRequestOf(bridge).body?.reqBody?.field1?.cellId ?? '').toBe('');
expect(commentRequestOf(bridge).body?.reqBody?.field1?.field6 ?? 0).toBe(0);
});
it('comments a video with the cover location and video media type', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('GetMediaList')) {
return packMediaList({
mediaList: [{
type: 2,
video: { id: 'video-id', cover: { lloc: 'cover-lloc' } },
batchId: 88n,
}],
});
}
return undefined;
}));
await new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'video-id', 'hello');
expect(feedDetailRequestOf(bridge).data?.lloc).toBe('cover-lloc');
expect(commentRequestOf(bridge).body?.reqBody?.field5).toMatchObject({
albumId: 'album-id',
batchId: 88n,
medias: [{
type: 1,
video: { cover: { lloc: 'cover-lloc' } },
}],
});
});
it('rejects a comment when the album media cannot be resolved', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('GetMediaList')) return packMediaList({ mediaList: [] });
return undefined;
}));
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'missing-lloc', 'hello'))
.rejects.toThrow('comment album media error: media not found');
expect(bridge.sendRawPacket.mock.calls.some((call) => String(call[0]).endsWith('DoQunComment')))
.toBe(false);
});
it('rejects a comment when the official feed lookup fails', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('GetQunFeedDetail')) {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<GetQunFeedDetailResponse>({
result: 10016,
errorText: '服务器繁忙',
})),
};
}
return undefined;
}));
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
.rejects.toThrow('fetch album feed error: retCode 10016, 服务器繁忙');
expect(bridge.sendRawPacket.mock.calls.some((call) => String(call[0]).endsWith('DoQunComment')))
.toBe(false);
});
it('rejects a comment when the official feed has no id', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('GetQunFeedDetail')) return packFeedDetail('');
return undefined;
}));
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
.rejects.toThrow('comment album media error: empty feed');
expect(bridge.sendRawPacket.mock.calls.some((call) => String(call[0]).endsWith('DoQunComment')))
.toBe(false);
});
it('rejects a seq-echo 8527 packet that has no comment body', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('DoQunComment')) {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<DoQunCommentResponse>({ field1: 8527 })),
};
}
return undefined;
}));
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
.rejects.toThrow('comment album media error: empty comment');
});
it('surfaces the album result code instead of treating seq 8527 as success', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('DoQunComment')) {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<DoQunCommentResponse>({
field1: 8527,
result: 1001,
errorText: 'permission denied',
})),
};
}
return undefined;
}));
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
.rejects.toThrow('comment album media error: retCode 1001, permission denied');
});
it('accepts a comment written directly on envelope field 4', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('DoQunComment')) {
return packCommentOk({
id: 'flat-id',
content: [{ type: 0, content: 'hello' }],
time: 123n,
clientKey: 'ck',
});
}
return undefined;
}));
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
.resolves.toMatchObject({
id: 'flat-id',
user: { uin: '10001' },
content: [{ type: 0, content: 'hello' }],
time: '123',
clientKey: 'ck',
});
});
});
@@ -7,12 +7,12 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
C2CRecallRequest,
SsoReadedReportReq,
SsoReadedReportResp,
} from '@snowluma/proto-defs/oidb-actions/base';
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
encodeOidbEnv: vi.fn(() => new Uint8Array()),
decodeOidbEnv: vi.fn(() => ({ body: {} })),
@@ -66,6 +66,17 @@ describe('apis/message — recall + markRead', () => {
expect(serviceCmd).toBe('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg');
});
it('recallPrivate keeps the 64-bit message id exact for any random', async () => {
const random = 0x1234567;
const bridge = mockBridge();
await new MessageApi(bridge as any).recallPrivate(10001, 11110, 200, random, 1700000000);
const [, body] = bridge.sendRawPacket.mock.calls[0]!;
const request = protobuf_decode<C2CRecallRequest>(body);
expect(request.info?.random).toBe(random);
expect(request.info?.messageId).toBe(0x0100000001234567n);
});
it('probes and confirms group plus private reads in the same packets', async () => {
const sendRawPacket = vi.fn()
.mockResolvedValueOnce(readReportResult({
@@ -33,7 +33,7 @@ describe('apis/interaction', () => {
it('setReaction picks _1 for set and _2 for unset', async () => {
// setReaction now forwards through the SetReaction namespace, which
// calls bridge.sendRawPacket directly (bypassing runOidb).
// calls bridge.sendRawPacket directly.
const bridge = mockBridge();
const api = new InteractionApi(bridge as any);
await api.setReaction(12345, 99, '128516', true);
@@ -51,20 +51,21 @@ describe('apis/interaction', () => {
expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']);
});
it('getEmojiLikes decodes user list, base64-encodes cookie, and reports isLast', async () => {
it('getEmojiLikes decodes user list, returns the cookie, and reports isLast', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<Oidb0x9083Resp>>({
body: {
inner: { userInfo: [{ uin: 10001n }, { uin: 20002n }] },
cookie: new Uint8Array([0xCA, 0xFE]),
} as any,
users: [{ uin: 10001n }, { uin: 20002n }],
cookie: 'next-page',
isLast: false,
},
})),
});
const out = await new InteractionApi(bridge as any).getEmojiLikes(12345, 99, '128516');
expect(out.users).toEqual([{ uin: 10001 }, { uin: 20002 }]);
expect(out.cookie).toBe(Buffer.from([0xCA, 0xFE]).toString('base64'));
expect(out.cookie).toBe('next-page');
expect(out.isLast).toBe(false);
});
@@ -0,0 +1,41 @@
import { describe, expect, it, vi } from 'vitest';
import type { BridgeContext } from '../../src/bridge/bridge-context';
import { MessageApi } from '../../src/bridge/apis/message';
import { mockBridge } from './_helpers';
function sender(responseHex: string) {
const ctx = {
...mockBridge(),
nextMessageRandom: () => 1234,
sendRawPacket: vi.fn(async () => ({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(responseHex, 'hex'),
})),
};
return { api: new MessageApi(ctx as unknown as BridgeContext), send: ctx.sendRawPacket };
}
describe('group send receipts (#492)', () => {
it('accepts the confirmed response from the issue log', async () => {
const { api } = sender('080018abb3e8d506500058844a60abb3e8d506700078df0d');
await expect(api.sendGroup(10001, [{ type: 'text', text: 'test' }])).resolves.toMatchObject({
sequence: 9476, messageId: 1234,
});
});
it.each([
['missing', '080018c9b3e8d506500060c9b3e8d5067000'],
['zero', '08005800'],
])('rejects a %s receipt without automatically resending', async (_name, response) => {
const { api, send } = sender(response);
await expect(api.sendGroup(10001, [{ type: 'text', text: 'test' }]))
.rejects.toThrow('group message delivery was not confirmed');
expect(send).toHaveBeenCalledOnce();
});
it('preserves an explicit server rejection', async () => {
const { api } = sender('0801');
await expect(api.sendGroup(10001, [{ type: 'text', text: 'test' }]))
.rejects.toThrow('send group message rejected: result=1');
});
});
+128 -9
View File
@@ -12,18 +12,12 @@ import type {
SetStatusResp,
} from '@snowluma/proto-defs/oidb-actions/base';
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
// (substituted at the call site with the inlined codec). Mocking them on
// the module object is a no-op — proton has already inlined the call.
// We mock `runOidb` (non-generic) to return real proton-encoded bytes
// that the production-side codec actually decodes.
vi.mock('@snowluma/protocol/bridge-oidb', async () => {
const actual = await vi.importActual<typeof import('@snowluma/protocol/bridge-oidb')>(
'@snowluma/protocol/bridge-oidb',
);
return {
...actual,
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
};
});
@@ -47,8 +41,6 @@ import { mockBridge } from './_helpers';
describe('apis/profile', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
vi.mocked(oidb.makeOidbEnvelope).mockClear();
vi.mocked(highwayClient.fetchHighwaySession).mockClear();
vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
@@ -87,9 +79,30 @@ describe('apis/profile', () => {
expect(decoded.batteryStatus ?? 0).toBe(0);
});
it('setOnlineStatus accepts QQ\'s success reply even when the reply code is non-zero (#405)', async () => {
const bridge = mockBridge();
const respBuf = Buffer.from(protobuf_encode<SetStatusResp>({
errCode: 1,
errMsg: 'set status success',
}));
expect(respBuf.length).toBeGreaterThan(0);
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: respBuf,
} as any);
await expect(new ProfileApi(bridge as any).setOnlineStatus(10, 0, 100)).resolves.toBeUndefined();
});
it('setOnlineStatus accepts a success-only reply body (#405)', async () => {
const bridge = mockBridge();
const respBuf = Buffer.from(protobuf_encode<SetStatusResp>({ errMsg: 'set status success' }));
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: respBuf,
} as any);
await expect(new ProfileApi(bridge as any).setOnlineStatus(10, 0)).resolves.toBeUndefined();
});
it('setDiyOnlineStatus surfaces server errors via the same path as setOnlineStatus', async () => {
const bridge = mockBridge();
// Build a response that decodes to errCode != 0.
const respBuf = Buffer.from(protobuf_encode<SetStatusResp>({ errCode: 1, errMsg: 'denied' }));
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: respBuf,
@@ -279,6 +292,112 @@ describe('apis/profile', () => {
expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]);
});
it('fetchCustomFaceIds slices the Faceroam list and skips the packet for count=0', async () => {
const bridge = mockBridge();
const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0';
const emojiB = '10001_0_0_0_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB_0_0';
bridge.sendRawPacket.mockResolvedValueOnce({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<FaceroamOpResp>({
retCode: 0,
item: { faceIds: [emojiA, emojiB] },
})),
} as any);
const api = new ProfileApi(bridge as any);
await expect(api.fetchCustomFaceIds(1)).resolves.toEqual([emojiA]);
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('Faceroam.OpReq');
await expect(api.fetchCustomFaceIds(0)).resolves.toEqual([]);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
});
it('fetchCustomFace maps ids to image urls', async () => {
const bridge = mockBridge();
const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0';
bridge.sendRawPacket.mockResolvedValueOnce({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<FaceroamOpResp>({
retCode: 0,
item: { faceIds: [emojiA] },
})),
} as any);
await expect(new ProfileApi(bridge as any).fetchCustomFace(1)).resolves.toEqual([
`https://p.qpic.cn/qq_expression/10001/${emojiA}/0`,
]);
});
it.each(['resource', 'md5'])('resolves a saved sticker by %s without fetching every description', async (kind) => {
const bridge = mockBridge();
const md5 = 'ABCDEF0123456789ABCDEF0123456789';
const emojiId = `10001_0_0_0_${md5}_0_0`;
bridge.sendRawPacket.mockResolvedValue({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<FaceroamOpResp>({ item: { faceIds: [emojiId] } })),
} as any);
const api = new ProfileApi(bridge as any);
expect(await api.resolveCustomFace(kind === 'md5' ? md5.toLowerCase() : emojiId)).toEqual({
emojiId, md5, url: `https://p.qpic.cn/qq_expression/10001/${emojiId}/0`,
});
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1);
await expect(api.resolveCustomFace('missing')).rejects.toThrow(/not in the saved sticker list/);
await expect(api.resolveCustomFace(' ')).rejects.toThrow(/identifier is empty/);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
});
it('rejects a negative custom-face count before sending', async () => {
const bridge = mockBridge();
await expect(new ProfileApi(bridge as any).fetchCustomFaceIds(-1)).rejects.toThrow(
/non-negative integer/,
);
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('moveCustomFaceToFront reorders from the id list without parsing urls', async () => {
const bridge = mockBridge();
const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0';
const emojiB = '10001_0_0_0_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB_0_0';
bridge.sendRawPacket
.mockResolvedValueOnce({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<FaceroamOpResp>({
retCode: 0,
item: { faceIds: [emojiA, emojiB] },
})),
} as any)
.mockResolvedValue({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<CustomFaceModifyResp>>({
body: { retCode: 0 },
})),
} as any);
await new ProfileApi(bridge as any).moveCustomFaceToFront(emojiB);
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
'Faceroam.OpReq',
'OidbSvcTrpcTcp.0x902f_1',
'OidbSvcTrpcTcp.0x902e_1',
]);
const moveBody = protobuf_decode<OidbBase<CustomFaceMoveBody>>(
bridge.sendRawPacket.mock.calls[2]![1],
);
expect(moveBody.body?.emojis?.map((emoji) => emoji.emojiId)).toEqual([emojiB, emojiA]);
});
it('fetchCustomFaceDetails supplements the Faceroam ids with server descriptions (#333)', async () => {
const bridge = mockBridge();
const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0';
@@ -34,6 +34,20 @@ function runtimeTrace(entries: LogEntry[]): LogEntry[] {
);
}
function testSends(sendPacket: ReturnType<typeof vi.fn>): unknown[][] {
return sendPacket.mock.calls.filter(([cmd]) => String(cmd).startsWith('Test.'));
}
function ownershipSendTrace(entries: LogEntry[]): LogEntry[] {
return runtimeTrace(entries).filter((entry) => {
if (entry.message.startsWith('bridge_sender_fact ')) return true;
if (entry.message.startsWith('bridge_send_')) {
return entry.message.includes('serviceCmd="Test.');
}
return false;
});
}
function packet(pid: number, uin: string): PacketInfo {
return {
pid,
@@ -284,8 +298,8 @@ describe('BridgeManager PID ownership', () => {
expect(bridge.activePid).toBe(202);
await bridge.sendRawPacket('Test.BeforeDisconnect', new Uint8Array([1]));
expect(second.sendPacket).toHaveBeenCalledOnce();
expect(first.sendPacket).not.toHaveBeenCalled();
expect(testSends(second.sendPacket)).toHaveLength(1);
expect(testSends(first.sendPacket)).toHaveLength(0);
manager.onPidDisconnected(202);
@@ -293,8 +307,8 @@ describe('BridgeManager PID ownership', () => {
expect(bridge.activePid).toBe(101);
expect(closed).not.toHaveBeenCalled();
await bridge.sendRawPacket('Test.AfterDisconnect', new Uint8Array([2]));
expect(first.sendPacket).toHaveBeenCalledOnce();
expect(second.sendPacket).toHaveBeenCalledOnce();
expect(testSends(first.sendPacket)).toHaveLength(1);
expect(testSends(second.sendPacket)).toHaveLength(1);
manager.onPidDisconnected(101);
expect(manager.getSession('10001')).toBeNull();
@@ -324,9 +338,7 @@ describe('BridgeManager PID ownership', () => {
manager.onPidDisconnected(101);
await bridge.sendRawPacket('Test.NoSender', new Uint8Array([0x00, 0xff]));
const sender = runtimeTrace(entries).filter((entry) =>
entry.message.startsWith('bridge_sender_fact ')
|| entry.message.startsWith('bridge_send_'));
const sender = ownershipSendTrace(entries);
expect(sender.map((entry) => entry.message)).toEqual([
'bridge_sender_fact event=selected uin="10001" pid=101 previousPid=null',
'bridge_sender_fact event=selected uin="10001" pid=202 previousPid=101',
@@ -381,17 +393,17 @@ describe('BridgeManager PID ownership', () => {
expect(started).toHaveBeenCalledOnce();
expect(bridge.activePid).toBe(101);
await bridge.sendRawPacket('Test.Rebound', new Uint8Array([1]));
expect(reboundFirst.sendPacket).toHaveBeenCalledOnce();
expect(testSends(reboundFirst.sendPacket)).toHaveLength(1);
manager.onPidDisconnected(101);
expect(bridge.activePid).toBe(303);
await bridge.sendRawPacket('Test.Fallback', new Uint8Array([2]));
expect(third.sendPacket).toHaveBeenCalledOnce();
expect(testSends(third.sendPacket)).toHaveLength(1);
manager.onPidDisconnected(303);
expect(bridge.activePid).toBe(202);
await bridge.sendRawPacket('Test.SecondFallback', new Uint8Array([3]));
expect(second.sendPacket).toHaveBeenCalledOnce();
expect(testSends(second.sendPacket)).toHaveLength(1);
});
it('applies the same ownership transition when a packet reveals a new UIN', async () => {
@@ -413,7 +425,7 @@ describe('BridgeManager PID ownership', () => {
const replacement = manager.getSession('20002')!.bridge;
expect(replacement.hasPid(101)).toBe(true);
await replacement.sendRawPacket('Test.AfterPacketRebind', new Uint8Array([1]));
expect(sender.sendPacket).toHaveBeenCalledOnce();
expect(testSends(sender.sendPacket)).toHaveLength(1);
});
it('keeps the old UIN alive when its active PID moves and a fallback remains', async () => {
@@ -437,12 +449,12 @@ describe('BridgeManager PID ownership', () => {
expect(oldBridge.hasPid(202)).toBe(false);
expect(oldBridge.activePid).toBe(101);
await oldBridge.sendRawPacket('Test.OldUinFallback', new Uint8Array([1]));
expect(fallback.sendPacket).toHaveBeenCalledOnce();
expect(testSends(fallback.sendPacket)).toHaveLength(1);
const newBridge = manager.getSession('20002')!.bridge;
expect(newBridge.activePid).toBe(202);
await newBridge.sendRawPacket('Test.NewUinSender', new Uint8Array([2]));
expect(rebound.sendPacket).toHaveBeenCalledOnce();
expect(testSends(rebound.sendPacket)).toHaveLength(1);
manager.onPidDisconnected(202);
expect(lifecycle).toEqual([
@@ -485,7 +497,7 @@ describe('BridgeManager PID ownership', () => {
manager.onPidDisconnected(101);
expect(targetBridge.activePid).toBe(202);
await targetBridge.sendRawPacket('Test.ExistingTargetFallback', new Uint8Array([1]));
expect(second.sendPacket).toHaveBeenCalledOnce();
expect(testSends(second.sendPacket)).toHaveLength(1);
expect(closed).toHaveBeenCalledOnce();
manager.onPidDisconnected(202);
@@ -47,6 +47,9 @@ function emptyProfile(uin: number, uid: string) {
sign: '',
avatar: '',
level: 0,
qidianMasterFlag: 0,
qidianCrewFlag: 0,
qidianCrewFlag2: 0,
};
}
@@ -1,8 +1,10 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { DatalineMsgBody, DatalineTextMsg } from '@snowluma/proto-defs/dataline';
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
import type { FileExtra } from '@snowluma/proto-defs/message';
import { DATALINE_UIN_PHONE } from '@snowluma/protocol/dataline/device-contacts';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbOfflineFileFinalizeResp } from '@snowluma/proto-defs/oidb-actions/media';
@@ -201,4 +203,62 @@ describe('Bridge private media routing', () => {
expect(fileExtra?.file?.fileUuid).toBe('uuid-abc-123');
expect(fileExtra?.field6 ?? undefined).toBeUndefined();
});
it('sends my-device text through trans0x211 instead of ordinary c2c', async () => {
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
override async sendRawPacket(serviceCmd: string, body: Uint8Array): Promise<SendPacketResult> {
expect(serviceCmd).toBe('MessageSvc.PbSendMsg');
this.capturedBody = body;
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<SendMessageResponse>({
result: 0,
errMsg: '',
privateSequence: 88,
timestamp1: 1710000000,
})),
};
}
}
const bridge = new TestBridge(IdentityService.memory('10000'));
await bridge.apis.message.sendPrivate(DATALINE_UIN_PHONE, [{ type: 'text', text: 'hello phone' }]);
const request = protobuf_decode<SendMessageRequest>(bridge.capturedBody as Uint8Array);
expect(request?.routingHead?.trans0x211).toMatchObject({
ccCmd: 7,
uid: 'u_Wcc5rknRRqRO8y5gxMD6sA',
toUin: 10000n,
});
expect(request?.routingHead?.c2c ?? undefined).toBeUndefined();
const body = protobuf_decode<DatalineMsgBody>(request!.messageBody!.msgContent as Uint8Array);
expect(body?.subCmd).toBe(4);
expect(body?.header).toMatchObject({
srcAppId: 1,
dstAppId: 1001,
srcTerType: 1,
dstTerType: 2,
srcUin: 10000n,
dstUin: 10000n,
});
const text = protobuf_decode<DatalineTextMsg>(body!.generic!.buf as Uint8Array);
expect(new TextDecoder().decode(text!.items![0]!.text as Uint8Array)).toBe('hello phone');
});
it('rejects non-text my-device sends', async () => {
class TestBridge extends Bridge {
override async sendRawPacket(): Promise<SendPacketResult> {
throw new Error('should not send');
}
}
const bridge = new TestBridge(IdentityService.memory('10000'));
await expect(bridge.apis.message.sendPrivate(DATALINE_UIN_PHONE, [
{ type: 'image', url: 'file:///tmp/a.png' } as any,
])).rejects.toThrow('only accepts text');
});
});
@@ -0,0 +1,120 @@
import { describe, expect, it, vi } from 'vitest';
import type { PacketSender } from '@snowluma/common/packet-sender';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/protocol/qq-info';
import { Bridge } from '../src/bridge/bridge';
const sender: PacketSender = {
sendPacket: async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.alloc(0),
}),
};
function makeFriend(uin: number, uid: string, nickname: string): FriendInfo {
return { uin, uid, nickname, remark: '' };
}
function makeGroup(groupId: number): QQGroupInfo {
return {
groupId,
groupName: 'group',
remark: '',
memberCount: 1,
memberMax: 200,
members: new Map(),
};
}
function makeMember(uin: number, uid: string): GroupMemberInfo {
return {
uin,
uid,
nickname: `nick-${uin}`,
card: '',
role: 'member',
level: 0,
title: '',
joinTime: 0,
lastSentTime: 0,
shutUpTime: 0,
};
}
function makeProfile(uin: number, uid: string, nickname: string): UserProfileInfo {
return {
uin, uid, nickname, remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
qidianMasterFlag: 0, qidianCrewFlag: 0, qidianCrewFlag2: 0,
};
}
describe('Bridge roster warmup', () => {
it('fetches friends and groups after the first sender and writes Identity', async () => {
const identity = IdentityService.memory('10001');
const bridge = new Bridge(identity);
const friends = [makeFriend(10001, 'u_self', 'me'), makeFriend(22222, 'u_friend', 'friend')];
const groups = [makeGroup(123)];
const members = [makeMember(33333, 'u_member')];
const fetchFriendList = vi.spyOn(bridge.apis.contacts, 'fetchFriendList').mockImplementation(async () => {
identity.rememberFriends(friends);
return friends;
});
vi.spyOn(bridge.apis.contacts, 'fetchGroupList').mockImplementation(async () => {
identity.rememberGroups(groups);
return groups;
});
vi.spyOn(bridge.apis.contacts, 'fetchGroupMemberList').mockImplementation(async (groupId) => {
identity.rememberGroupMembers(groupId, members);
return members;
});
bridge.bindPid(7, sender);
const result = await bridge.whenRosterWarmupSettled();
expect(result).toEqual({ friendsLoaded: true, groupsLoaded: true });
expect(fetchFriendList).toHaveBeenCalledOnce();
expect(identity.nickname).toBe('me');
expect(identity.findFriend(22222)?.uid).toBe('u_friend');
expect(identity.findGroup(123)?.groupName).toBe('group');
expect(identity.findGroupMember(123, 33333)?.uid).toBe('u_member');
bridge.dispose();
});
it('does not retry a failed friend list fetch', async () => {
const identity = IdentityService.memory('10001');
const bridge = new Bridge(identity);
const fetchFriendList = vi.spyOn(bridge.apis.contacts, 'fetchFriendList').mockRejectedValue(new Error('net'));
vi.spyOn(bridge.apis.contacts, 'fetchGroupList').mockResolvedValue([]);
vi.spyOn(bridge.apis.contacts, 'fetchUserProfile').mockResolvedValue(makeProfile(10001, 'u_self', 'me'));
bridge.bindPid(7, sender);
const result = await bridge.whenRosterWarmupSettled();
expect(result).toEqual({ friendsLoaded: false, groupsLoaded: true });
expect(fetchFriendList).toHaveBeenCalledOnce();
bridge.bindPid(8, sender);
await bridge.whenRosterWarmupSettled();
expect(fetchFriendList).toHaveBeenCalledOnce();
bridge.dispose();
});
it('discards in-flight warmup writes after dispose', async () => {
const identity = IdentityService.memory('10001');
const bridge = new Bridge(identity);
let releaseFriends!: (friends: FriendInfo[]) => void;
const friendsGate = new Promise<FriendInfo[]>((resolve) => { releaseFriends = resolve; });
vi.spyOn(bridge.apis.contacts, 'fetchFriendList').mockReturnValue(friendsGate);
vi.spyOn(bridge.apis.contacts, 'fetchGroupList').mockResolvedValue([]);
bridge.bindPid(7, sender);
const settled = bridge.whenRosterWarmupSettled();
bridge.dispose();
releaseFriends([makeFriend(22222, 'u_friend', 'friend')]);
await expect(settled).resolves.toEqual({ friendsLoaded: false, groupsLoaded: false });
expect(() => { identity.nickname = 'x'; }).toThrow(/closed/);
});
});
+135 -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])),
@@ -27,6 +28,8 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({
uploadVideoMsgInfo: vi.fn(async () => new Uint8Array([1, 2, 3])),
}));
import { protobuf_encode } from '@snowluma/proton';
import type { MsgInfo } from '@snowluma/proto-defs/element';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload';
@@ -240,6 +243,47 @@ describe('element-builder / all-message validation preflight', () => {
expect(uploadImageMsgInfo).not.toHaveBeenCalled();
});
it('emits a customFace sibling for forwardFake group images (#441)', async () => {
const md5Hex = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
const msgInfo = protobuf_encode<MsgInfo>({
msgInfoBody: [{
index: {
fileUuid: 'EhRimg',
info: {
fileHash: md5Hex,
fileName: `${md5Hex}.png`,
fileSize: 12,
width: 10,
height: 10,
type: { picFormat: 1001 },
},
},
}],
});
vi.mocked(uploadImageMsgInfo).mockResolvedValueOnce(msgInfo);
const elems = await buildSendElems(
[{ type: 'image', url: 'file:///tmp/a.png' }],
{ bridge: fakeBridge, groupId: 12345, forwardFake: true, scene: 'forward' },
);
expect(elems).toHaveLength(2);
expect(elems[0]!.commonElem).toBeDefined();
expect(elems[1]!.customFace?.filePath).toBe(`${md5Hex}.png`);
expect(elems[1]!.customFace?.md5).toHaveLength(16);
});
it('does not emit a legacy sibling on a live group image send', async () => {
vi.mocked(uploadImageMsgInfo).mockResolvedValueOnce(new Uint8Array([7, 8, 9]));
const elems = await buildSendElems(
[{ type: 'image', url: 'file:///tmp/a.png' }],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(elems).toHaveLength(1);
expect(elems[0]!.commonElem).toBeDefined();
expect(elems[0]!.customFace).toBeUndefined();
});
it('accepts a received imageUrl-only element for re-send', async () => {
vi.mocked(uploadImageMsgInfo).mockClear();
await buildSendElems(
@@ -251,6 +295,7 @@ describe('element-builder / all-message validation preflight', () => {
true,
12345,
expect.objectContaining({ imageUrl: 'https://gchat.qpic.cn/received.jpg' }),
undefined,
);
});
@@ -303,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 () => {
@@ -330,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');
@@ -340,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 () => {
@@ -196,10 +196,30 @@ describe('FlashTransferApi.createFlashTask — disk streaming (#359)', () => {
await api().createFlashTask(file);
expect(mainSlices(slices)).toHaveLength(0);
expect(ApplyUpload.invoke).toHaveBeenCalled(); // thumbs still apply
expect(ApplyUpload.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
fileName: 'hit.mp4',
}));
expect(SetFilesetStatus.invoke).toHaveBeenCalled();
});
it('commits a png as image format 26 rather than video format 2 (#421)', async () => {
const file = writeSrc('shot.png', synth(48, 5));
installSliceuploadOk();
await api().createFlashTask(file);
expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
fileName: 'shot.png',
typeCode: 7,
}));
expect(CommitFile.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
entries: [expect.objectContaining({
fileName: 'shot.png',
formatCode: 26,
})],
}));
});
it('sliceuploads a multi-megabyte file as 1 MiB disk chunks with flash Sha1StateV', async () => {
const bytes = synth(SLICE + 80, 13);
const file = writeSrc('big.mp4', bytes);
+6 -2
View File
@@ -33,8 +33,8 @@ describe('mapGroupNoticeResponse', () => {
publish_time: 1_700_000_000,
message: {
text: 'regular',
image: [{ id: 'pic', width: 640, height: 360 }],
images: [{ id: 'pic', width: 640, height: 360 }],
image: [{ id: 'pic', url: 'https://gdynamic.qpic.cn/gdynamic/pic/0', width: 640, height: 360 }],
images: [{ id: 'pic', url: 'https://gdynamic.qpic.cn/gdynamic/pic/0', width: 640, height: 360 }],
},
settings: {},
read_num: 2,
@@ -75,5 +75,9 @@ describe('mapGroupNoticeResponse', () => {
ec: 0,
feeds: [feed('bad', { msg: { text: 'bad', pics: [{ id: 'x', w: 'wide', h: 20 }] } })],
})).toThrow('image 0.w');
expect(() => mapGroupNoticeResponse({
ec: 0,
feeds: [feed('bad-id', { msg: { text: 'bad', pics: [{ id: 'a/b', w: 20, h: 20 }] } })],
})).toThrow('malformed');
});
});
@@ -302,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]' } });
});
});
@@ -488,6 +488,15 @@ describe('pipeline — finalizeMediaMsgInfo', () => {
expect(decoded.extBizInfo.pic.textSummary).toBe('[image]');
});
it('preserves a server ptt waveform on the outgoing MsgInfo', () => {
const waveform = new Uint8Array([8, 4, 18, 4, 10, 20, 30, 40]);
const out = finalizeMediaMsgInfo({
msgInfo: { msgInfoBody: [], extBizInfo: { ptt: { waveform } } },
});
const decoded: any = protobuf_decode<EncodableMediaMsgInfo>(out);
expect(decoded.extBizInfo.ptt.waveform).toEqual(waveform);
});
it('without defaultPic, leaves pic untouched when server omits it', () => {
const out = finalizeMediaMsgInfo({
msgInfo: { msgInfoBody: [], extBizInfo: {} },
+27 -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,9 +62,21 @@ 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 () => {
await uploadPttMsgInfo({} as any, true, 12345, FINGERPRINT);
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
expect((args.extBizInfo as any).ptt.waveform).toBeUndefined();
expect(pipeline.finalizeMediaMsgInfo).toHaveBeenCalledOnce();
});
it('fingerprint payload: zero bytes, fastOnlyError ready, voiceFormat defaults to 1', 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];
+147 -3
View File
@@ -589,6 +589,23 @@ describe('IdentityService', () => {
lastError: expect.stringMatching(/locked/i),
lastFailureAt: suspendedFailureAt,
});
const skipLogsBeforeBurst = seen.filter((entry) =>
/persistence write skipped/.test(entry.message),
).length;
expect(skipLogsBeforeBurst).toBe(1);
for (let i = 0; i < 50; i += 1) {
identity.rememberRequestIdentity({
uid: `u_skip_burst_${i}`,
uin: 500_000 + i,
});
}
expect(seen.filter((entry) => /persistence write skipped/.test(entry.message)))
.toHaveLength(1);
await vi.advanceTimersByTimeAsync(60_000);
identity.rememberRequestIdentity({ uid: 'u_skip_after_minute', uin: 600_000 });
const skipLogs = seen.filter((entry) => /persistence write skipped/.test(entry.message));
expect(skipLogs).toHaveLength(2);
expect(skipLogs[1]?.message).toMatch(/suppressed=50/);
releaseLock();
identity.close();
@@ -757,6 +774,9 @@ describe('IdentityService', () => {
sign: '',
avatar: '',
level: 0,
qidianMasterFlag: 0,
qidianCrewFlag: 0,
qidianCrewFlag2: 0,
};
const request = {
groupId: GROUP_ID,
@@ -789,6 +809,7 @@ describe('IdentityService', () => {
['group requests', () => identity.rememberGroupRequests([request])],
['request identity', () => identity.rememberRequestIdentity({ uid: 'u_request', uin: 88888 })],
['group member identity', () => identity.rememberGroupMemberIdentity(GROUP_ID, { uid: 'u_new', uin: 99999 })],
['group member joined', () => identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_new', uin: 99999 })],
['group member inactive', () => identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin })],
];
@@ -803,6 +824,123 @@ describe('IdentityService', () => {
expect(identity.findUinByUid('u_request')).toBeNull();
});
it('does not treat identity-only sightings as live group members', () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMemberIdentity(GROUP_ID, { uid: 'u_seen', uin: 88888 });
expect(identity.findGroupMember(GROUP_ID, 88888)).toBeNull();
expect(identity.findUinByUid('u_seen')).toBe(88888);
identity.close();
});
it('does not hydrate identity-only sightings as live members after reopen', () => {
const dbPath = tempDbPath('identity-only-not-roster');
const member = makeMember(33333, 'u_member', 'card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.rememberGroupMemberIdentity(GROUP_ID, { uid: 'u_operator', uin: 88888 });
expect(identity.findGroupMember(GROUP_ID, 88888)).toBeNull();
identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('card');
expect(identity.findGroupMember(GROUP_ID, 88888)).toBeNull();
expect(identity.findUinByUid('u_operator')).toBe(88888);
identity.close();
}
});
it('records a thin live member on join without inventing roster details', () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
const existing = makeMember(33333, 'u_existing', 'card');
identity.rememberGroupMembers(GROUP_ID, [existing]);
identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_join', uin: 44444 });
identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_join', uin: 44444 });
identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_ignored', uin: 0 });
const joined = identity.findGroupMember(GROUP_ID, 44444);
expect(joined).toMatchObject({
uin: 44444,
uid: 'u_join',
nickname: '',
card: '',
role: 'member',
});
expect(joined?.isRobot).toBeUndefined();
expect(identity.findGroupMember(GROUP_ID, 33333)?.card).toBe('card');
identity.close();
});
it('persists a thin live member on join across reopen', () => {
const dbPath = tempDbPath('join-live-roster');
const existing = makeMember(33333, 'u_existing', 'card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [existing]);
identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_join', uin: 44444 });
identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
const joined = identity.findGroupMember(GROUP_ID, 44444);
expect(joined).toMatchObject({
uin: 44444,
uid: 'u_join',
nickname: '',
card: '',
role: 'member',
});
expect(joined?.isRobot).toBeUndefined();
expect(identity.findGroupMember(GROUP_ID, 33333)?.card).toBe('card');
identity.close();
}
});
it('drops a leaver from the live roster and keeps their identity mapping', () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
const member = makeMember(33333, 'u_member', 'card');
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin });
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid);
identity.close();
});
it('keeps a leaver out of the live roster after reopen', () => {
const dbPath = tempDbPath('leave-live-roster');
const member = makeMember(33333, 'u_member', 'card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin });
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid);
identity.close();
}
});
it('marks missing members inactive only after a successful full refresh', () => {
const dbPath = tempDbPath('inactive-refresh');
const first = makeMember(33333, 'u_first');
@@ -901,7 +1039,7 @@ describe('IdentityService', () => {
expect(identity.findUidByUin(55555)).toBe('u_friend_request');
expect(identity.findUinByUid('u_friend_request')).toBe(55555);
expect(identity.findGroup(GROUP_ID)?.groupId).toBe(GROUP_ID);
expect(identity.findGroup(GROUP_ID)).toBeNull();
expect(identity.findUidByUin(66666)).toBe('u_group_request');
identity.close();
@@ -911,7 +1049,10 @@ describe('IdentityService', () => {
describe('IdentityService.resolveUid', () => {
function makeProfile(uin: number, uid: string): UserProfileInfo {
return { uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0 };
return {
uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
qidianMasterFlag: 0, qidianCrewFlag: 0, qidianCrewFlag2: 0,
};
}
it('returns the cached uid without invoking the fetcher', async () => {
@@ -976,7 +1117,10 @@ describe('IdentityService.resolveUid', () => {
describe('IdentityService inbound UID→UIN', () => {
function makeProfile(uin: number, uid: string): UserProfileInfo {
return { uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0 };
return {
uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
qidianMasterFlag: 0, qidianCrewFlag: 0, qidianCrewFlag2: 0,
};
}
it('findUinByUid treats a numeric uid as that uin without consulting maps', () => {
@@ -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,11 +135,128 @@ 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();
});
it('keeps valid request headers and drops unsafe or empty ones', () => {
const { channels } = normalizeNotificationsConfig({
channels: [{
id: 'feishu',
url: 'https://open.feishu.cn/hook',
headers: {
Authorization: 'Bearer secret',
'X-Custom': 'ok',
'Bad Name': 'x',
'': 'x',
Inject: 'line\r\nX-Evil: 1',
Empty: ' ',
NotString: 1,
} as Record<string, unknown>,
}],
});
expect(channels[0].headers).toEqual({
Authorization: 'Bearer secret',
'X-Custom': 'ok',
});
});
it('omits an empty headers object after normalize', () => {
const { channels } = normalizeNotificationsConfig({
channels: [{ id: 'c1', url: 'https://a.com', headers: { 'Bad Name': 'x' } }],
});
expect(channels[0].headers).toBeUndefined();
});
it('keeps an email channel without a webhook url and fills SMTP defaults', () => {
const { channels } = normalizeNotificationsConfig({
channels: [{
id: 'ops-mail',
type: 'email',
smtpHost: 'smtp.qq.com',
from: 'SnowLuma <bot@qq.com>',
to: 'a@example.com; b@example.com, a@example.com',
}],
});
expect(channels).toEqual([{
id: 'ops-mail',
name: 'ops-mail',
type: 'email',
url: '',
bodyTemplate: DEFAULT_EMAIL_BODY_TEMPLATE,
enabled: true,
smtpHost: 'smtp.qq.com',
smtpPort: 465,
smtpSecure: true,
from: 'SnowLuma <bot@qq.com>',
to: 'a@example.com, b@example.com',
subjectTemplate: DEFAULT_SUBJECT_TEMPLATE,
}]);
});
it('defaults port 587 when smtpSecure is explicitly false', () => {
const { channels } = normalizeNotificationsConfig({
channels: [{
id: 'relay',
type: 'email',
smtpHost: 'relay.internal',
smtpSecure: false,
from: 'bot@internal',
to: 'ops@internal',
}],
});
expect(channels[0]).toMatchObject({ smtpPort: 587, smtpSecure: false });
});
it('treats port 587 without smtpSecure as STARTTLS (secure=false)', () => {
const { channels } = normalizeNotificationsConfig({
channels: [{
id: 'gmail',
type: 'email',
smtpHost: 'smtp.gmail.com',
smtpPort: 587,
from: 'bot@gmail.com',
to: 'ops@gmail.com',
}],
});
expect(channels[0]).toMatchObject({ smtpPort: 587, smtpSecure: false });
});
it('drops email channels missing host / from / to, and unknown types', () => {
const { channels } = normalizeNotificationsConfig({
channels: [
{ id: 'no-host', type: 'email', from: 'a@b.com', to: 'c@d.com' },
{ id: 'no-from', type: 'email', smtpHost: 'smtp.example.com', to: 'c@d.com' },
{ id: 'bad-to', type: 'email', smtpHost: 'smtp.example.com', from: 'a@b.com', to: 'not-an-email' },
{ id: 'sms', type: 'sms', url: 'https://a.com' },
{ id: 'ok', type: 'email', smtpHost: 'smtp.example.com', from: 'a@b.com', to: 'c@d.com', smtpUser: 'a@b.com', smtpPass: 'p' },
],
});
expect(channels.map((c) => c.id)).toEqual(['ok']);
expect(channels[0]).toMatchObject({ smtpUser: 'a@b.com', smtpPass: 'p' });
});
it('does not keep webhook-only fields on an email channel', () => {
const { channels } = normalizeNotificationsConfig({
channels: [{
id: 'mail',
type: 'email',
url: 'https://should.be.ignored',
headers: { Authorization: 'Bearer x' },
smtpHost: 'smtp.example.com',
from: 'a@b.com',
to: 'c@d.com',
evil: 'x',
}],
});
expect(channels[0].url).toBe('');
expect(channels[0].headers).toBeUndefined();
expect(channels[0]).not.toHaveProperty('evil');
});
});
@@ -1,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' })];
@@ -57,6 +80,23 @@ describe('NotificationManager — dispatch + history', () => {
expect(posts).toEqual([{ url: 'https://hook.example/c1', body: 'offline:123:123' }]);
});
it('forwards channel request headers to the post collaborator', async () => {
const posts: { url: string; body: string; headers?: Record<string, string> }[] = [];
const { mgr } = setup({
loadConfig: () => ({
version: 1,
debounceSeconds: 30,
channels: [ch({ headers: { Authorization: 'Bearer secret' } })],
}),
post: async (url, body, headers) => {
posts.push({ url, body, headers });
return { ok: true, status: 200 };
},
});
await mgr.notify('123', 'offline');
expect(posts[0]?.headers).toEqual({ Authorization: 'Bearer secret' });
});
it('uses the nickname captured on an online/offline edge', async () => {
const { posts, mgr } = setup();
mgr.handleOnline('123', 'Alice'); // caches nickname; cold online → no post
@@ -149,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());
@@ -206,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(); }
});
});
@@ -0,0 +1,42 @@
import { describe, it, expect } from 'vitest';
import type { OneBotManager } from '@snowluma/onebot/manager';
import { checkListenerExposure, isValidBindHost } from '../src/webui/listener-exposure';
import { initWebUI } from '../src/webui/server';
describe('isValidBindHost', () => {
it('accepts loopback, all-interfaces, and IPv6 any', () => {
expect(isValidBindHost('127.0.0.1')).toBe(true);
expect(isValidBindHost('0.0.0.0')).toBe(true);
expect(isValidBindHost('::')).toBe(true);
expect(isValidBindHost('localhost')).toBe(true);
});
it('rejects spaces, underscores, and malformed IPv6 zone ids', () => {
expect(isValidBindHost('bad host')).toBe(false);
expect(isValidBindHost('not_a_host')).toBe(false);
expect(isValidBindHost('::1%bad%extra')).toBe(false);
expect(isValidBindHost(' 127.0.0.1')).toBe(false);
});
});
describe('checkListenerExposure', () => {
it('requires a usable pair only when TLS is on', () => {
expect(checkListenerExposure({ webuiHost: '127.0.0.1', tlsEnabled: false, pairOk: false })).toEqual({ ok: true });
expect(checkListenerExposure({ webuiHost: '127.0.0.1', tlsEnabled: true, pairOk: false })).toEqual({
ok: false,
code: 'tls-pair-required',
});
});
});
describe('initWebUI boot', () => {
it('fails before listen when the bind host is invalid', async () => {
await expect(initWebUI(
5099,
{} as OneBotManager,
undefined,
undefined,
{ host: 'not_a_host' },
)).rejects.toThrow(/bind host is not a valid TCP address/);
});
});
@@ -1,5 +1,10 @@
import { describe, it, expect } from 'vitest';
import { coerceSettingsPatch } from '../src/webui/system-settings';
import {
coerceSettingsPatch,
evaluateSettingsSave,
tlsCertDeletionBlocked,
} from '../src/webui/system-settings';
import type { RuntimeConfig } from '@snowluma/common/runtime';
describe('coerceSettingsPatch', () => {
it('accepts a full valid body and maps tlsEnabled → webuiTls.enabled', () => {
@@ -37,3 +42,56 @@ describe('coerceSettingsPatch', () => {
expect(coerceSettingsPatch({ trustProxy: '' })).toEqual({ ok: true, patch: { trustProxy: '' } });
});
});
describe('evaluateSettingsSave', () => {
const current: RuntimeConfig = {
webuiPort: 5099,
webuiHost: '127.0.0.1',
webuiTls: { enabled: false },
};
it('rejects an invalid bind host on the patch', () => {
const r = evaluateSettingsSave(current, { webuiHost: 'not_a_host' }, true);
expect(r.ok).toBe(false);
if (!r.ok) expect(r.error).toMatch(/TCP/);
});
it('rejects saving an unrelated field when the persisted host is invalid', () => {
const r = evaluateSettingsSave(
{ ...current, webuiHost: 'not_a_host' },
{ webuiPort: 8080 },
true,
);
expect(r.ok).toBe(false);
});
it('rejects enabling TLS without a usable certificate pair', () => {
const r = evaluateSettingsSave(current, { webuiTls: { enabled: true } }, false);
expect(r).toEqual({ ok: false, error: '启用 TLS 前请先上传有效的证书与私钥' });
});
it('rejects leaving TLS enabled when the pair is already missing', () => {
const r = evaluateSettingsSave(
{ ...current, webuiTls: { enabled: true } },
{ webuiPort: 8080 },
false,
);
expect(r.ok).toBe(false);
});
it('allows disabling TLS even without a pair', () => {
const r = evaluateSettingsSave(
{ ...current, webuiTls: { enabled: true } },
{ webuiTls: { enabled: false } },
false,
);
expect(r).toEqual({ ok: true, patch: { webuiTls: { enabled: false } } });
});
});
describe('tlsCertDeletionBlocked', () => {
it('blocks deletion while TLS is enabled and allows it when TLS is off', () => {
expect(tlsCertDeletionBlocked(true)).toBe(true);
expect(tlsCertDeletionBlocked(false)).toBe(false);
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.14.11",
"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",
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.14.11",
"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>'`.",
+4 -3
View File
@@ -4,8 +4,9 @@
// structured doc list + a Markdown view. The metadata is carried on the same
// values that drive runtime validation, so docs cannot drift from behavior.
//
// The reserved `.handle_quick_operation` raw handler deliberately has no
// ActionSpec/doc entry; every catalogued action comes from ACTION_REGISTRY.
// The reserved `.handle_quick_operation` raw handler (and its `_async` alias)
// deliberately has no ActionSpec/doc entry; every catalogued action comes
// from ACTION_REGISTRY.
//
// The serving SURFACE (WebUI panel / OpenAPI export / static markdown) is a
// deferred product decision; this module produces format-agnostic data plus a
@@ -58,7 +59,7 @@ export function renderActionDocsMarkdown(docs: readonly ActionDoc[] = collectAct
'# OneBot Actions',
'',
'> 由 `packages/onebot/src/action-docs.ts` 从各 `ActionSpec.describe()` 自动生成,请勿手改。',
'> 覆盖完整声明式 Action registry;保留的 raw `.handle_quick_operation` handler 不生成文档。',
'> 覆盖完整声明式 Action registry;保留的 raw `.handle_quick_operation` / `.handle_quick_operation_async` handler 不生成文档。',
'',
`共 ${docs.length} 个声明式 action。`,
'',
+5 -9
View File
@@ -483,11 +483,7 @@ interface ActionDef<S extends Spec> {
readOnly?: boolean;
params: S;
rules?: (r: RuleBuilders<InferParams<S>>) => readonly CrossFieldRule[];
/** `raw` is the original untouched params — an escape hatch for the
* irregular tail (alias-key fallbacks, arbitrary nested objects). Declared
* fields in `p` remain the validated path; reach for `raw` only for keys
* the spec can't express. */
run: (p: InferParams<S>, ctx: ApiActionContext, raw: JsonObject) => Promise<ApiResponse> | ApiResponse;
run: (p: InferParams<S>, ctx: ApiActionContext) => Promise<ApiResponse> | ApiResponse;
}
const wording = (e: Err): string => (e.field ? `${e.field}: ${e.reason}` : e.reason);
@@ -517,7 +513,7 @@ export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
const toHandler = (ctx: ApiActionContext): Handler => async (params: JsonObject) => {
const r = parse(params);
if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r));
return def.run(r.value, ctx, params);
return def.run(r.value, ctx);
};
return {
@@ -571,7 +567,7 @@ interface StreamActionDef<S extends Spec> {
readOnly?: boolean;
params: S;
rules?: (r: RuleBuilders<InferParams<S>>) => readonly CrossFieldRule[];
run: (p: InferParams<S>, ctx: ApiActionContext, raw: JsonObject, sink: StreamSink) => Promise<ApiResponse> | ApiResponse;
run: (p: InferParams<S>, ctx: ApiActionContext, sink: StreamSink) => Promise<ApiResponse> | ApiResponse;
}
export interface StreamActionSpec<S extends Spec> extends RegisteredActionSpec {
@@ -599,7 +595,7 @@ export function defineStreamAction<S extends Spec>(def: StreamActionDef<S>): Str
const toHandler = (ctx: ApiActionContext): Handler => async (params, sink) => {
const r = base.parse(params);
if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r));
return def.run(r.value, ctx, params, sink ?? NOOP_SINK);
return def.run(r.value, ctx, sink ?? NOOP_SINK);
};
return {
@@ -628,7 +624,7 @@ interface PresetDef<S extends Spec, Extra> {
readOnly?: boolean;
params?: S;
rules?: (r: RuleBuilders<InferParams<S> & Extra>) => readonly CrossFieldRule[];
run: (p: InferParams<S> & Extra, ctx: ApiActionContext, raw: JsonObject) => Promise<ApiResponse> | ApiResponse;
run: (p: InferParams<S> & Extra, ctx: ApiActionContext) => Promise<ApiResponse> | ApiResponse;
}
/** Pre-seeds `group_id` (uint, required). */
+258 -84
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';
@@ -6,7 +7,6 @@ import type {
GroupEssenceMessage,
} from '@snowluma/protocol/web/group-essence';
import type { ApiActionContext } from '../api-handler';
import { asNumber, asString } from '../api-handler';
import type { ForwardPreviewMeta } from '../modules/message-actions';
import {
hasAuthoritativeSequence,
@@ -14,14 +14,19 @@ import {
failedResponse,
okResponse,
type JsonObject,
type JsonValue,
type MessageMeta,
} from '../types';
import { defineAction, groupAction, groupUserAction, f } from '../action-kit';
import { defineAction, groupAction, groupUserAction, f, type Field } from '../action-kit';
import { groupInfoReturnsSchema } from './group-info';
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB
const 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',
@@ -86,6 +91,33 @@ function essenceString(value: unknown, field: string, allowEmpty: boolean): stri
return value;
}
function optionalEssenceText(value: unknown): string | undefined {
if (typeof value !== 'string') return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
/** Unknown digest types (share cards, future msg_type values) degrade to
* text so one unmapped item cannot fail the whole essence list. */
function degradeEssenceContent(content: GroupEssenceContent): JsonObject {
const brief = optionalEssenceText(content.share_brief);
const title = optionalEssenceText(content.share_title);
const summary = optionalEssenceText(content.share_summary);
const url = optionalEssenceText(content.share_url);
const text = optionalEssenceText(content.text);
const heading = brief ?? title ?? summary ?? text;
const parts: string[] = [];
if (heading) parts.push(heading);
if (title && title !== heading) parts.push(title);
if (summary && summary !== heading && summary !== title) parts.push(summary);
if (text && text !== heading) parts.push(text);
if (url) parts.push(url);
return {
type: 'text',
data: { text: parts.length > 0 ? parts.join('\n') : `[essence type ${content.msg_type}]` },
};
}
function essenceContentToSegment(content: GroupEssenceContent): JsonObject {
switch (content.msg_type) {
case 1:
@@ -136,7 +168,7 @@ function essenceContentToSegment(content: GroupEssenceContent): JsonObject {
};
}
default:
throw new Error(`unsupported group essence content type: ${content.msg_type}`);
return degradeEssenceContent(content);
}
}
@@ -262,19 +294,57 @@ async function saveDownloadBuffer(buf: Buffer, preferredName: string): Promise<s
return resolved;
}
// 从 send_*_forward_msg 的参数里提取 NapCat 兼容的转发预览元信息。四个字段都是可选的——如果没有提供,模块层会根据实际消息节点列表推断出合理的默认值。
function readForwardPreviewMeta(params: Record<string, unknown>): ForwardPreviewMeta | undefined {
const source = asString(params.source) || undefined;
const summary = asString(params.summary) || undefined;
const prompt = asString(params.prompt) || undefined;
function optionalExactString(): Field<string | undefined> {
const inner = f.string().optional();
return Object.assign(Object.create(inner) as Field<string | undefined>, {
coerce(raw: unknown, field: string) {
if (typeof raw === 'number' || typeof raw === 'boolean' || raw === null
|| (typeof raw === 'object' && raw !== null)) {
return { ok: false as const, field, reason: 'expected a string' };
}
return inner.coerce(raw as Parameters<Field<string | undefined>['coerce']>[0], field);
},
});
}
function integerFromDecimalString(value: string): number {
if (value.trim() === '') return 0;
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
function primitiveText(value: unknown): string {
if (typeof value === 'string') return value;
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
return '';
}
const forwardPreviewParams = {
source: f.string().optional(),
summary: f.string().optional(),
prompt: f.string().optional(),
news: f.raw(),
};
// NapCat-compatible forward preview. All four fields are optional — if none
// are provided, the message module infers defaults from the node list.
function readForwardPreviewMeta(p: {
source?: string;
summary?: string;
prompt?: string;
news?: JsonValue;
}): ForwardPreviewMeta | undefined {
const source = p.source || undefined;
const summary = p.summary || undefined;
const prompt = p.prompt || undefined;
let news: Array<{ text: string }> | undefined;
if (Array.isArray(params.news)) {
if (Array.isArray(p.news)) {
const collected: Array<{ text: string }> = [];
for (const item of params.news) {
for (const item of p.news) {
if (typeof item === 'string') {
collected.push({ text: item });
} else if (item && typeof item === 'object' && !Array.isArray(item)) {
const text = asString((item as Record<string, unknown>).text);
const text = primitiveText((item as Record<string, unknown>).text);
if (text) collected.push({ text });
}
}
@@ -688,7 +758,7 @@ export const actions = [
groupAction({
name: '_get_group_notice',
summary: '获取群公告',
returns: '普通公告与新成员公告的合并数组;send_to_new_members 标识后者',
returns: '普通公告与新成员公告的合并数组;send_to_new_members 标识后者;图片含 id、url、宽高',
readOnly: true,
run: async (p, ctx) => {
const notices = await ctx.bridge.apis.web.getNotice(p.group_id);
@@ -801,13 +871,10 @@ export const actions = [
required: ['text'],
},
params: {
message_id: f.string().default('').role('message_id'),
message_id: f.messageId(),
},
// `raw` so message_id works whether the client sends a number or a string.
run: async (_p, ctx, raw) => {
const messageId = asNumber(raw.message_id);
if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
return okResponse(await ctx.fetchPttText(messageId));
run: async (p, ctx) => {
return okResponse(await ctx.fetchPttText(p.message_id));
},
}),
@@ -996,12 +1063,10 @@ export const actions = [
params: {
nickname: f.string().optional(),
personal_note: f.string().optional(),
sex: f.int({ min: 0, max: 2 }).optional().describe('0 未知,1 男,2 女'),
},
run: async (p, ctx) => {
const nickname = p.nickname;
const personalNote = p.personal_note;
await ctx.bridge.apis.profile.setProfile(nickname, personalNote);
await ctx.bridge.apis.profile.setProfile(p.nickname, p.personal_note, p.sex);
return okResponse();
},
}),
@@ -1268,15 +1333,10 @@ export const actions = [
return_type: f.string().default('url'),
},
run: async (p, ctx) => {
const urls = await ctx.bridge.apis.profile.fetchCustomFace(p.count);
if (p.return_type === 'id') {
const emojiIds = urls.map((url) => {
const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url);
return m ? m[1] : '';
}).filter(Boolean);
return okResponse(emojiIds);
return okResponse(await ctx.bridge.apis.profile.fetchCustomFaceIds(p.count));
}
return okResponse(urls);
return okResponse(await ctx.bridge.apis.profile.fetchCustomFace(p.count));
},
}),
@@ -1400,6 +1460,41 @@ export const actions = [
},
}),
defineAction({
name: 'get_msg_emoji_likes',
summary: '获取一条消息的全部表情回应',
readOnly: true,
returns: '该消息上每个表情回应的编号、数量与用户列表。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
emoji_id: { type: 'string', description: '表情编号' },
emoji_type: { type: 'integer', description: '表情类型' },
count: { type: 'integer', description: '回应数量' },
last_reaction_time: { type: 'integer', description: '最近一次回应时间' },
users: {
type: 'array',
items: {
type: 'object',
properties: { user_id: { type: 'integer', description: '用户 QQ 号' } },
required: ['user_id'],
},
},
},
required: ['emoji_id', 'emoji_type', 'count', 'last_reaction_time', 'users'],
},
},
params: { message_id: f.messageId() },
run: async (p, ctx) => {
if (!ctx.fetchEmojiLikeSummary) {
return failedResponse(RETCODE.ACTION_FAILED, 'emoji reaction summary is unavailable');
}
return okResponse(await ctx.fetchEmojiLikeSummary(p.message_id));
},
}),
defineAction({
name: 'get_friends_with_category',
summary: '获取分组好友列表',
@@ -1706,6 +1801,55 @@ export const actions = [
},
}),
// send_tuwen_ark — send a custom 图文 (URL-share) ark card to a C2C peer or group (0xdc2_34).
// targetId at AppInfo[11] and Meta[2]; Meta.peerType: 0=C2C, 1=group.
// 与 send_ark_share 的区别:send_ark_share 只获取推荐联系人 JSON 不发送;
// 与 send_msg share/json 的区别:后者发送 structmsg 图文卡且有 message_id,
// 本 action 发送固定图文 ark 模板,返回 null(无法用于撤回/设精华)。
defineAction({
name: 'send_tuwen_ark',
summary: '发送图文 Ark 卡片(私聊/群聊)',
readOnly: false,
returns: 'null',
returnsSchema: { type: 'null' },
params: {
user_id: f.userId().optional(),
group_id: f.groupId().optional(),
title: f.string(),
desc: f.string(),
summary: f.string().default('[分享]'),
preview_url: f.string().default('https://tangram-1251316161.file.myqcloud.com/files/20210721/e50a8e37e08f29bf1ffc7466e1950690.png'),
jump_url: f.string(),
},
run: async (p, ctx) => {
if (p.group_id) {
await ctx.bridge.apis.contacts.sendTuwenArk({
targetId: p.group_id,
peerType: 1,
title: p.title,
desc: p.desc,
summary: p.summary,
previewUrl: p.preview_url,
jumpUrl: p.jump_url,
});
return okResponse(null);
}
if (p.user_id) {
await ctx.bridge.apis.contacts.sendTuwenArk({
targetId: p.user_id,
peerType: 0,
title: p.title,
desc: p.desc,
summary: p.summary,
previewUrl: p.preview_url,
jumpUrl: p.jump_url,
});
return okResponse(null);
}
return failedResponse(RETCODE.BAD_REQUEST, 'user_id or group_id is required');
},
}),
// share_group_ex / send_group_ark_share — group-only Ark share. NapCat uses
// a distinct kernel API (getArkJsonGroupShare) we did NOT RE; we route to
// the fully-RE'd group recommend-contact ark (0x8b7_5), the closest
@@ -1746,12 +1890,15 @@ export const actions = [
type: 'object',
properties: {
uid: { type: 'string', description: '申请人 uid(回传作 set_doubt_friends_add_request 的 flag)' },
user_id: { type: 'integer', description: '申请人 QQ 号' },
nick: { type: 'string', description: '申请人昵称' },
source: { type: 'string', description: '申请来源' },
reason: { type: 'string', description: '附加说明' },
msg: { type: 'string', description: '验证留言' },
group_code: { type: 'string', description: '来源群号,无则为空串' },
reqTime: { type: 'integer', description: '申请时间戳' },
},
required: ['uid', 'nick', 'source', 'msg', 'reqTime'],
required: ['uid', 'user_id', 'nick', 'source', 'reason', 'msg', 'group_code', 'reqTime'],
},
},
params: { count: f.int({ min: 0 }).default(50) },
@@ -1760,10 +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. 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: '处理可疑好友申请',
@@ -1772,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 {
@@ -2188,8 +2331,7 @@ export const actions = [
},
}),
// ===== 原 legacy registerAction,现并入 kit(ctx 调用与逻辑逐字保留;
// 别名键 / 原始参数透传 / 任意对象经 run 第三参 raw 或 f.raw() 表达)=====
// ===== 原 legacy registerAction,现并入 kit =====
defineAction({
name: ['get_rkey', 'nc_get_rkey'],
@@ -2327,16 +2469,22 @@ export const actions = [
name: 'send_forward_msg',
summary: '发送合并转发(按 message_type/群号自动路由)',
returns: '{ message_id, res_id, forward_id }',
// group_id/user_id 是“路由提示”而非身份字段:原实现用 asNumber + `>0` 判断,
// 占位的 0 表示“该分支不适用”、不应报错。故从 raw 读取(保持旧语义),
// 只声明 messages/message。
params: { messages: f.message().optional(), message: f.message().optional() },
run: async (p, ctx, raw) => {
const messageType = asString(raw.message_type);
const groupId = asNumber(raw.group_id);
const userId = asNumber(raw.user_id);
// group_id/user_id are routing hints, not identity: 0 means "this branch
// does not apply" and must not error. int({min:0}) optional, not groupId.
params: {
messages: f.message().optional(),
message: f.message().optional(),
message_type: f.string().optional(),
group_id: f.int({ min: 0 }).optional(),
user_id: f.int({ min: 0 }).optional(),
...forwardPreviewParams,
},
run: async (p, ctx) => {
const messageType = p.message_type ?? '';
const groupId = p.group_id ?? 0;
const userId = p.user_id ?? 0;
const messages = p.messages ?? p.message;
const meta = readForwardPreviewMeta(raw);
const meta = readForwardPreviewMeta(p);
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
if ((messageType === 'group' || groupId > 0) && ctx.sendGroupForwardMsg) {
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
@@ -2357,11 +2505,15 @@ export const actions = [
name: 'send_group_forward_msg',
summary: '发送群合并转发',
returns: '{ message_id, res_id, forward_id }',
params: { messages: f.message().optional(), message: f.message().optional() },
run: async (p, ctx, raw) => {
params: {
messages: f.message().optional(),
message: f.message().optional(),
...forwardPreviewParams,
},
run: async (p, ctx) => {
const messages = p.messages ?? p.message;
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
const result = await ctx.sendGroupForwardMsg(p.group_id, messages, readForwardPreviewMeta(raw));
const result = await ctx.sendGroupForwardMsg(p.group_id, messages, readForwardPreviewMeta(p));
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
},
}),
@@ -2370,11 +2522,16 @@ export const actions = [
name: 'send_private_forward_msg',
summary: '发送私聊合并转发',
returns: '{ message_id, res_id, forward_id }',
params: { user_id: f.userId(), messages: f.message().optional(), message: f.message().optional() },
run: async (p, ctx, raw) => {
params: {
user_id: f.userId(),
messages: f.message().optional(),
message: f.message().optional(),
...forwardPreviewParams,
},
run: async (p, ctx) => {
const messages = p.messages ?? p.message;
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
const result = await ctx.sendPrivateForwardMsg(p.user_id, messages, readForwardPreviewMeta(raw));
const result = await ctx.sendPrivateForwardMsg(p.user_id, messages, readForwardPreviewMeta(p));
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
},
}),
@@ -2391,12 +2548,11 @@ export const actions = [
},
required: ['messages'],
},
params: { id: f.string().optional() },
run: async (p, ctx, raw) => {
params: { id: f.string().optional(), message_id: f.string().optional() },
run: async (p, ctx) => {
let id = p.id || '';
if (!id) {
const rawMessageId = raw.message_id;
const numericMessageId = asNumber(rawMessageId);
if (!id && p.message_id !== undefined) {
const numericMessageId = integerFromDecimalString(p.message_id);
if (numericMessageId > 0) {
const event = ctx.getMessage(numericMessageId);
const segments = Array.isArray(event?.message) ? event.message : [];
@@ -2407,11 +2563,11 @@ export const actions = [
const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data))
? so.data as Record<string, unknown>
: null;
const candidate = asString(data?.id) || asString(data?.res_id) || asString(data?.forward_id);
const candidate = primitiveText(data?.id) || primitiveText(data?.res_id) || primitiveText(data?.forward_id);
if (candidate) { id = candidate; break; }
}
}
if (!id) id = asString(rawMessageId);
if (!id) id = p.message_id;
}
if (!id) return failedResponse(RETCODE.BAD_REQUEST, 'id or message_id is required');
const messages = await ctx.getForwardMsg(id);
@@ -2423,8 +2579,13 @@ export const actions = [
name: 'download_file',
summary: '下载文件(url 或 base64)到 data/downloads',
returns: '{ file }',
params: { url: f.string().default(''), base64: f.string().default(''), name: f.string().default('') },
run: async (p, _ctx, raw) => {
params: {
url: f.string().default(''),
base64: f.string().default(''),
name: f.string().default(''),
headers: f.raw(),
},
run: async (p) => {
const url = p.url;
const base64 = p.base64;
const name = p.name;
@@ -2436,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(raw.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);
@@ -2459,12 +2620,9 @@ export const actions = [
},
required: ['words'],
},
params: { words: f.raw() },
params: { words: f.array(f.string()) },
run: async (p, ctx) => {
const rawWords = p.words;
if (!Array.isArray(rawWords)) return failedResponse(RETCODE.BAD_REQUEST, 'invalid words array');
const words = rawWords.map((w) => String(w));
const translated = await ctx.bridge.apis.misc.translateEn2Zh(words);
const translated = await ctx.bridge.apis.misc.translateEn2Zh(p.words);
return okResponse({ words: translated });
},
}),
@@ -2472,7 +2630,7 @@ export const actions = [
defineAction({
name: 'set_self_longnick',
summary: '设置个性签名(longNick/long_nick,严格 string)',
params: { longNick: f.raw(), long_nick: f.raw() },
params: { longNick: optionalExactString(), long_nick: optionalExactString() },
run: async (p, ctx) => {
const longNick = p.longNick !== undefined ? p.longNick : p.long_nick;
if (typeof longNick !== 'string') return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick');
@@ -2485,14 +2643,22 @@ export const actions = [
name: 'get_mini_app_ark',
summary: '获取小程序卡片 ark',
readOnly: true,
params: {},
run: async (_p, ctx, raw) => {
const type = raw.type || 'bili';
const title = raw.title || '';
const desc = raw.desc || '';
const picUrl = raw.picUrl || raw.pic_url || '';
const jumpUrl = raw.jumpUrl || raw.jump_url || '';
const data = await ctx.bridge.apis.misc.getMiniAppArk(String(type), String(title), String(desc), String(picUrl), String(jumpUrl));
params: {
type: f.string().optional(),
title: f.string().optional(),
desc: f.string().optional(),
picUrl: f.string().optional(),
pic_url: f.string().optional(),
jumpUrl: f.string().optional(),
jump_url: f.string().optional(),
},
run: async (p, ctx) => {
const type = p.type || 'bili';
const title = p.title || '';
const desc = p.desc || '';
const picUrl = p.picUrl || p.pic_url || '';
const jumpUrl = p.jumpUrl || p.jump_url || '';
const data = await ctx.bridge.apis.misc.getMiniAppArk(type, title, desc, picUrl, jumpUrl);
return okResponse(data);
},
}),
@@ -2500,12 +2666,20 @@ export const actions = [
groupAction({
name: 'click_inline_keyboard_button',
summary: '点击内联键盘按钮',
params: { bot_appid: f.uint(), msg_seq: f.uint() },
run: async (p, ctx, raw) => {
const buttonId = raw.button_id;
const callbackData = raw.callback_data || '';
if (!buttonId) return failedResponse(RETCODE.BAD_REQUEST, 'missing required parameters');
const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton(p.group_id, p.bot_appid, String(buttonId), String(callbackData), p.msg_seq);
params: {
bot_appid: f.uint(),
msg_seq: f.uint(),
button_id: f.string({ allowEmpty: false }),
callback_data: f.string().default(''),
},
run: async (p, ctx) => {
const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton(
p.group_id,
p.bot_appid,
p.button_id,
p.callback_data,
p.msg_seq,
);
return okResponse(data);
},
}),
+18 -1
View File
@@ -32,18 +32,35 @@ 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: '扩展状态码' },
ext_status: { type: 'integer', description: '扩展状态码(同 extStatus)' },
batteryStatus: { type: 'integer', description: '电量状态' },
customStatus: { type: 'object', description: '自定义状态', nullable: true },
customStatusDescInfo: { type: 'string', description: '自定义状态说明' },
qidian_master_flag: { type: 'integer', description: '企点主号标志,0 或 1;普通账号为 0' },
qidian_crew_flag: { type: 'integer', description: '企点员工标志,0 或 1;普通账号为 0' },
qidian_crew_flag_2: { type: 'integer', description: '企点保留标志,0 或 1;普通账号为 0' },
qidian_enterprise_name: { type: 'string', description: '企点企业名称;非企点账号或未获取到时为空字符串' },
},
required: ['user_id', 'nickname', 'remark', 'sex', 'age', 'long_nick'],
},
+55 -1
View File
@@ -100,7 +100,7 @@ export const actions = [
groupAction({
name: 'set_group_member_permissions',
summary: '设置群成员权限',
summary: '设置群成员权限(仅群主可改)',
params: {
allow_member_upload_album: f.bool().optional(),
allow_member_temporary_session: f.bool().optional(),
@@ -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: '设置/取消管理员',
@@ -155,6 +155,28 @@ export const actions = [
},
}),
groupAction({
name: 'upload_video_to_qun_album',
summary: '上传视频到群相册',
returns: '{ id: string }',
returnsSchema: {
type: 'object',
properties: {
id: { type: 'string', description: '视频 id' },
},
required: ['id'],
},
params: {
album_id: f.string({ allowEmpty: false }).describe('相册 id'),
album_name: f.string({ allowEmpty: false }).describe('相册名称'),
file: f.video().describe('视频文件'),
},
run: async (p, ctx) => {
const result = await ctx.bridge.apis.groupAlbum.uploadVideo(p.group_id, p.album_id, p.album_name, p.file);
return okResponse(result);
},
}),
groupAction({
name: 'get_group_album_media_list',
readOnly: true,
+20 -7
View File
@@ -1,5 +1,4 @@
import { defineAction, groupAction, groupUserAction, f } from '../action-kit';
import { asString } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
import { WebHonorType } from '@snowluma/protocol/web/group-honor';
@@ -14,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: [
@@ -41,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: [
@@ -78,6 +79,7 @@ export const actions = [
group_create_time: 0,
group_level: 0,
group_memo: '',
group_description: '',
group_all_shut: 0,
};
if (ctx.getGroupInfo) {
@@ -109,12 +111,17 @@ export const actions = [
last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' },
shut_up_timestamp: { type: 'integer', description: '禁言结束时间戳(秒,未禁言时为 0)' },
level: { type: 'string', description: '群等级' },
qq_level: { type: 'integer', description: 'QQ 等级,仅在账号资料可用时返回' },
qage: { type: 'integer', description: '按注册时间计算的完整周年数(UTC),注册时间不可用时省略' },
role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' },
title: { type: 'string', description: '专属头衔' },
area: { type: 'string', description: '地区(QQ NT 不提供,恒空)' },
unfriendly: { type: 'boolean', description: '是否不良记录(QQ NT 不提供,恒 false)' },
title_expire_time: { type: 'integer', description: '头衔过期时间戳(QQ NT 不提供,恒 0)' },
card_changeable: { type: 'boolean', description: '是否可改名片(占位,恒 true)' },
qidian_master_flag: { type: 'integer', description: '企点主号标志,0 或 1;普通账号为 0' },
qidian_crew_flag: { type: 'integer', description: '企点员工标志,0 或 1;普通账号为 0' },
qidian_crew_flag_2: { type: 'integer', description: '企点保留标志,0 或 1;普通账号为 0' },
},
required: ['group_id', 'user_id', 'nickname', 'role'],
},
@@ -149,12 +156,17 @@ export const actions = [
last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' },
shut_up_timestamp: { type: 'integer', description: '禁言结束时间戳(秒,未禁言时为 0)' },
level: { type: 'string', description: '群等级' },
qq_level: { type: 'integer', description: 'QQ 等级,仅在账号资料可用时返回' },
qage: { type: 'integer', description: '按注册时间计算的完整周年数(UTC),注册时间不可用时省略' },
role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' },
title: { type: 'string', description: '专属头衔' },
area: { type: 'string', description: '地区(QQ NT 不提供,恒空)' },
unfriendly: { type: 'boolean', description: '是否不良记录(QQ NT 不提供,恒 false)' },
title_expire_time: { type: 'integer', description: '头衔过期时间戳(QQ NT 不提供,恒 0)' },
card_changeable: { type: 'boolean', description: '是否可改名片(占位,恒 true)' },
qidian_master_flag: { type: 'integer', description: '企点主号标志,0 或 1;普通账号为 0' },
qidian_crew_flag: { type: 'integer', description: '企点员工标志,0 或 1;普通账号为 0' },
qidian_crew_flag_2: { type: 'integer', description: '企点保留标志,0 或 1;普通账号为 0' },
},
required: ['group_id', 'user_id', 'nickname', 'role'],
},
@@ -171,6 +183,7 @@ export const actions = [
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
shut_up_timestamp: 0,
level: '0', role: 'member', title: '',
qidian_master_flag: 0, qidian_crew_flag: 0, qidian_crew_flag_2: 0,
});
}
return okResponse({
@@ -183,17 +196,14 @@ export const actions = [
},
}),
// `type` keeps the legacy `asString(x) || 'all'` semantics (absent / non-string
// / empty-string all collapse to 'all'), which a typed string field can't
// replicate exactly — so it stays a raw param coerced in run().
groupAction({
name: 'get_group_honor_info',
summary: '获取群荣誉信息',
readOnly: true,
params: { type: f.raw() },
params: { type: f.string().optional() },
run: async (p, ctx) => {
const groupId = p.group_id;
const typeStr = asString(p.type) || 'all';
const typeStr = p.type || 'all';
const typeValues = Object.values(WebHonorType) as string[];
if (!typeValues.includes(typeStr)) {
@@ -224,13 +234,16 @@ export const actions = [
request_id: { type: 'integer', description: '请求序列号' },
requester_uin: { type: 'integer', description: '申请人 QQ 号' },
requester_nick: { type: 'string', description: '申请人昵称' },
invitor_uin: { type: 'integer', description: '邀请人 QQ 号,无邀请时为 0' },
invitor_nick: { type: 'string', description: '邀请人昵称' },
message: { type: 'string', description: '验证留言' },
checked: { type: 'boolean', description: '是否已处理' },
flag: { type: 'string', description: '处理请求使用的规范 flag' },
},
required: [
'group_id', 'group_name', 'request_id', 'requester_uin',
'requester_nick', 'message', 'checked', 'flag',
'requester_nick', 'invitor_uin', 'invitor_nick',
'message', 'checked', 'flag',
],
},
},
+5 -3
View File
@@ -211,14 +211,14 @@ function bindActionRegistry(
for (const claim of executableNames) {
if (claim.kind === 'raw') {
const factory = rawFactories[claim.name];
const factory = rawFactories[claim.canonical];
if (!factory) {
throw new Error(
`Action registry raw factory missing: canonical "${claim.canonical}" `
+ `(name "${claim.name}", kind raw)`,
);
}
factoryNames.delete(claim.name);
factoryNames.delete(claim.canonical);
handlers.set(claim.name, Object.freeze({
handler: factory(api),
canonical: claim.canonical,
@@ -262,10 +262,12 @@ export const ACTION_GROUPS: readonly ActionGroup[] = [
{ category: '流式接口', actions: [...streamFileActions, ...streamDownloadActions] },
];
/** The sole non-ActionSpec handler; reserved in the same namespace up front. */
/** Hidden OneBot v11 quick-operation handler; `_async` is the NoneBot 1 alias. */
export const HANDLE_QUICK_OPERATION_ACTION = '.handle_quick_operation';
export const HANDLE_QUICK_OPERATION_ASYNC_ACTION = '.handle_quick_operation_async';
export const RAW_ACTION_RESERVATIONS: readonly RawActionReservation[] = [
{ name: HANDLE_QUICK_OPERATION_ACTION, canonical: HANDLE_QUICK_OPERATION_ACTION },
{ name: HANDLE_QUICK_OPERATION_ASYNC_ACTION, canonical: HANDLE_QUICK_OPERATION_ACTION },
];
/** Complete, validated runtime/docs registry. Compilation happens on import. */
+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) });
},
}),
+40 -3
View File
@@ -1,9 +1,21 @@
import { createLogger } from '@snowluma/common/logger';
import type { JsonObject, JsonValue } from '../types';
import type { ApiActionContext } from '../api-handler';
import { defineAction, groupAction, f } from '../action-kit';
import { defineAction, groupAction, f, type Field } from '../action-kit';
import { RETCODE, failedResponse, okResponse } from '../types';
/** send_msg only (#426). Some clients send `group_id: ""` on private chats.
* Treat that exact empty string as absent. Do not change `f.groupId()`. */
function sendMsgOptionalGroupId(): Field<number | undefined> {
const inner = f.groupId().optional();
return Object.assign(Object.create(inner) as Field<number | undefined>, {
coerce(raw: Parameters<Field<number | undefined>['coerce']>[0], field: string) {
if (raw === '') return { ok: true as const, value: undefined };
return inner.coerce(raw, field);
},
});
}
const log = createLogger('OneBot');
/**
@@ -36,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
@@ -47,7 +85,7 @@ export const actions = [
params: {
message: f.message(),
message_type: f.string().optional(),
group_id: f.groupId().optional(),
group_id: sendMsgOptionalGroupId(),
user_id: f.userId().optional(),
auto_escape: f.bool().default(false),
},
@@ -132,4 +170,3 @@ export const actions = [
},
}),
];
+4 -6
View File
@@ -1,5 +1,4 @@
import { defineAction, f } from '../action-kit';
import { asString } from '../api-handler';
import { okResponse } from '../types';
export const actions = [
@@ -22,15 +21,14 @@ export const actions = [
params: {
// Opaque handle from the original request event; callers must echo it.
flag: f.string({ allowEmpty: false }),
// sub_type/type pass through with a nested fallback (sub_type → type → 'add');
// kept raw so the original asString resolution is preserved verbatim.
sub_type: f.raw(),
type: f.raw(),
// sub_type → type → 'add'. Empty string is kept, not treated as missing.
sub_type: f.string().optional(),
type: f.string().optional(),
approve: f.bool().default(true),
reason: f.string().default(''),
},
run: async (p, ctx) => {
const subType = asString(p.sub_type, asString(p.type, 'add'));
const subType = p.sub_type !== undefined ? p.sub_type : (p.type !== undefined ? p.type : 'add');
await ctx.handleGroupRequest(p.flag, subType, p.approve, p.reason);
return okResponse();
},
@@ -361,7 +361,7 @@ const downloadFileStream = defineStreamAction({
summary: '以流式方式下载文件(stream 目录本地文件 / URL / 缓存媒体)',
returns: '流式帧:file_info → file_chunk* → file_complete',
params: downloadParams,
run: (p, ctx, _raw, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'auto'),
run: (p, ctx, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'auto'),
});
const downloadFileImageStream = defineStreamAction({
@@ -369,7 +369,7 @@ const downloadFileImageStream = defineStreamAction({
summary: '以流式方式下载图片(缓存图片 id / URL / stream 目录本地文件)',
returns: '流式帧:file_info → file_chunk* → file_complete',
params: downloadParams,
run: (p, ctx, _raw, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'image'),
run: (p, ctx, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'image'),
});
const downloadFileRecordStream = defineStreamAction({
@@ -377,7 +377,7 @@ const downloadFileRecordStream = defineStreamAction({
summary: '以流式方式下载语音(缓存语音 id / URL / stream 目录本地文件)',
returns: '流式帧:file_info → file_chunk* → file_complete',
params: downloadParams,
run: (p, ctx, _raw, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'record'),
run: (p, ctx, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'record'),
});
const testDownloadStream = defineStreamAction({
@@ -385,7 +385,7 @@ const testDownloadStream = defineStreamAction({
summary: '测试下载流(推送 10 个数据帧,验证流式传输,不触达 QQ)',
returns: '流式帧:data_chunk*10 → data_complete(error=true 时以 error 帧结束)',
params: { error: f.bool().default(false).describe('是否触发测试错误') },
run: async (p, _ctx, _raw, sink) => {
run: async (p, _ctx, sink) => {
for (let i = 0; i < 10; i++) {
await sink.send({ type: StreamStatus.Stream, data: `Index-> ${i + 1}`, data_type: 'data_chunk' });
}
+10 -40
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: (
@@ -91,6 +92,13 @@ export interface ApiActionContext {
serverCount: number;
complete: boolean;
}>;
fetchEmojiLikeSummary: (messageId: number) => Promise<Array<{
emoji_id: string;
emoji_type: number;
count: number;
last_reaction_time: number;
users: Array<{ user_id: number }>;
}>>;
getImageInfo: (file: string) => Promise<JsonObject | null>;
getRecordInfo: (file: string) => Promise<JsonObject | null>;
fetchPttText: (messageId: number) => Promise<{ text: string }>;
@@ -140,13 +148,13 @@ export class ApiHandler {
this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
const rawFactories: Record<string, (api: ApiHandler) => ActionHandler> = {};
for (const raw of registry.rawActions) {
if (raw.name !== HANDLE_QUICK_OPERATION_ACTION) {
if (raw.canonical !== HANDLE_QUICK_OPERATION_ACTION) {
throw new Error(
`Action registry has no factory for raw action canonical "${raw.canonical}" `
+ `(name "${raw.name}", kind raw)`,
);
}
rawFactories[raw.name] = (api) => async (params) => {
rawFactories[raw.canonical] = (api) => async (params) => {
const opContext = params.context as JsonObject | undefined;
const operation = params.operation as Record<string, unknown> | undefined;
if (!opContext || !operation) {
@@ -408,26 +416,6 @@ export function asString(value: unknown, fallback = ''): string {
return fallback;
}
export function asNumber(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
if (Number.isFinite(n)) return Math.trunc(n);
}
return 0;
}
export function asBoolean(value: unknown, fallback: boolean): boolean {
if (typeof value === 'boolean') return value;
if (typeof value === 'number') return value !== 0;
if (typeof value === 'string') {
const text = value.trim().toLowerCase();
if (text === 'true' || text === '1' || text === 'yes' || text === 'on') return true;
if (text === 'false' || text === '0' || text === 'no' || text === 'off') return false;
}
return fallback;
}
export function toJsonValue(value: unknown): JsonValue {
if (value === null) return null;
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value;
@@ -441,21 +429,3 @@ export function toJsonValue(value: unknown): JsonValue {
}
return String(value);
}
export function asMessage(value: unknown): import('./types').JsonValue | undefined {
if (value === undefined) return undefined;
if (typeof value === 'string') {
const trimmed = value.trim();
if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
try {
const parsed = JSON.parse(trimmed);
if (Array.isArray(parsed)) {
return toJsonValue(parsed);
}
} catch {
// Fallback to literal text if it just looks like an array but is invalid JSON
}
}
}
return toJsonValue(value);
}
+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;
@@ -256,10 +287,24 @@ export const ELEMENT_CODECS = {
image: {
async toSegment(element, ctx) {
const url = ctx.imageUrlResolver ? await ctx.imageUrlResolver(element, ctx.isGroup) : (element.imageUrl ?? '');
// Bot-built forwards cache the upload source on `url`. Incoming
// 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 inline = isInlineMediaSource(source);
const resolved = !inline && source && !element.imageUrl
? { ...element, imageUrl: source }
: element;
const url = inline
? ''
: ctx.imageUrlResolver
? await ctx.imageUrlResolver(resolved, ctx.isGroup)
: source;
const data: JsonObject = {
url,
file: element.fileId ?? '',
file: element.fileId
|| (element.md5Hex ? `${element.md5Hex.toLowerCase()}.png` : '')
|| (inline ? '' : source),
sub_type: element.subType ?? 0,
summary: element.summary ?? '',
};
@@ -285,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,
@@ -305,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,
@@ -498,7 +549,7 @@ export const ELEMENT_CODECS = {
async fromSegment(data) {
return {
type: 'forward',
resId: String(data.id ?? ''),
resId: String(data.id ?? data.res_id ?? data.forward_id ?? ''),
};
},
},
+4 -4
View File
@@ -39,6 +39,7 @@ export type MessageIdResolver = (
sequence: number,
eventName: string,
timestamp?: number,
replyElements?: readonly MessageElement[],
) => number;
export type MediaSegmentSink = (
@@ -71,9 +72,9 @@ type ConverterFor<K extends QQEventVariant['kind']> =
* new `QQEventVariant` kind that forgets a converter is a compile error here —
* not a silent `null` at runtime.
*/
type ConverterRegistry = { [K in QQEventVariant['kind']]: ConverterFor<K> | null };
export type ConverterRegistry = { [K in QQEventVariant['kind']]: ConverterFor<K> | null };
const CONVERTERS: ConverterRegistry = {
export const CONVERTERS = {
// Messages.
friend_message: convertFriendMessage,
group_message: convertGroupMessage,
@@ -107,7 +108,7 @@ const CONVERTERS: ConverterRegistry = {
online_devices_changed: null,
// Internal-only identity synchronization from another QQ client.
friend_remark_changed: null,
};
} satisfies ConverterRegistry;
export async function convertEvent(
ctx: ConverterContext,
@@ -120,4 +121,3 @@ export async function convertEvent(
return (converter as (ctx: ConverterContext, event: QQEventVariant) => JsonObject | Promise<JsonObject>)(ctx, event);
}
Loaded 100 of 355 files, more files were not shown because too many files have changed in this diff. Show more