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
DrSmoothl 3e31fe90dc test(onebot): count the new group admin settings action
The compiled Action list grew by one when the matching getter was added.
2026-08-17 21:17:46 +08:00
DrSmoothl c86982610f chore(release): v1.14.11 2026-08-17 21:11:05 +08:00
DrSmoothl 29e6baac72 fix(protocol): drop leftover picture copies in robot messages
Some group-bot pictures arrive twice: one working download and one
unusable leftover for older clients. Only the working picture is kept.

Fixes #389
2026-08-17 20:08:48 +08:00
DrSmoothl 86669d9451 fix(core): apply member permissions from the current privilege flag
set_group_member_permissions now writes only the member-capability
bits. An omitted privilege value is treated as all allowed.

Fixes #388
2026-08-17 20:00:11 +08:00
DrSmoothl b3bd68d48d fix(protocol): read group privilege from the matching detail field
Member invite and capability bits come from a different group-detail
field than the history-visibility switch. Reading the wrong one made
later writes carry leftover bits the server rejects.
2026-08-17 20:00:11 +08:00
DrSmoothl 096ad0acfa fix(core): accept history visibility when the read-back flag matches
Setting new members to see history no longer fails after the server
has already applied it.

Fixes #387
2026-08-17 19:40:22 +08:00
DrSmoothl cc517080be fix(protocol): treat history visibility replies as an on/off flag
The group-detail reply reports whether new members can see history as
a simple yes/no value. The write still flips that setting; the read
no longer expects a multi-bit field.
2026-08-17 19:40:22 +08:00
DrSmoothl b63c3c370b feat(onebot): delete group album videos by video id
del_group_album_media accepts a photo id or a video id in lloc.

Fixes #384
2026-08-17 19:22:59 +08:00
DrSmoothl 25a40f4ab6 feat(protocol): resolve album video ids before delete
Deleting a group album video now looks up the matching item and uses
the identifier the server expects, instead of sending the video id as
a photo id.
2026-08-17 19:22:59 +08:00
DrSmoothl cd6ada0caa feat(onebot): accept join question and answer on set_group_add_option
add_type 4 takes group_question and group_answer. add_type 5 (and 55)
takes group_question. get_group_admin_settings also returns both.

Fixes #383
2026-08-17 19:12:43 +08:00
DrSmoothl 3cb3024b39 feat(protocol): write join question and answer with add option
Question-and-answer join mode now sends the question and answer;
question-only mode sends the question and clears the answer.
2026-08-17 19:12:43 +08:00
DrSmoothl b1fa11ca05 feat(onebot): add get_group_admin_settings
Bots can now read the current join option, robot-add option, member
invite policy, member permissions, history visibility, and search
settings that previously only had setters.

Fixes #385
2026-08-17 19:06:14 +08:00
DrSmoothl cfe61abce6 feat(protocol): read current group admin settings
Group detail and ext-info can now return the join option, search flags,
invite/permission/history bits, and robot-add switch so setters have a
matching read path.
2026-08-17 19:06:03 +08:00
DrSmoothl aec0c781b3 fix(onebot): approve pending group join requests that were rejected as gone
Closes #380.

An empty reject reason and a stale request type could make the server treat a still-pending join as already handled.
2026-08-17 18:40:08 +08:00
DrSmoothl 618dd52f46 fix(protocol): set group robot-add options when values are off
Closes #386.

Turning the options off no longer produces an empty request the server rejects.
2026-08-17 18:25:13 +08:00
DrSmoothl d5f1e35c31 fix(core): close Bridges on exit without a fake offline 2026-08-17 00:08:21 +08:00
DrSmoothl 27284fd79b fix(linux): restore live session selection 2026-08-16 23:59:39 +08:00
DrSmoothl ecf0efc5e2 refactor(protocol): keep hasDecodableContent next to decodeRichBody
Move the body-shape predicate into RichBody so admission no longer
mirrors decode slots. C2C control stays a header check.
2026-08-16 23:22:28 +08:00
DrSmoothl 206727f823 refactor(protocol): move roster refresh into the packet pipeline
Replace the shallow refreshMemberCache adapter with fetchGroupList
and fetchGroupMemberList ports. Skip, swallow, and coalesce stay
next to the join/leave/admin trigger.
2026-08-16 23:18:04 +08:00
DrSmoothl 9772d4f0bf chore(release): v1.14.10 2026-08-16 21:57:59 +08:00
DrSmoothl 55a2a24fc2 refactor(protocol): compose group-file URLs in the OIDB namespaces
Move retCode checks and URL assembly into GetGroupFileUrl,
GetPrivateFileUrl, and ListGroupFilesPage so GroupFileApi only
loops pages and resolves display names.
2026-08-16 21:56:21 +08:00
DrSmoothl 3fc521fb8b fix(linux): restore sending and receiving on ARM 2026-08-16 21:49:36 +08:00
DrSmoothl 3941c825b5 refactor(onebot): convert segments through ConverterContext
The receive path already collapsed resolvers into ConverterContext,
but elementsToOneBotSegments still took an 8-arg splat. Callers
could drop message-id or media sinks without a type error.

The public function now takes ConverterContext. Self-sent events
pass explicit null resolvers. get_forward_msg uses the instance ctx.
2026-08-16 21:44:30 +08:00
DrSmoothl 30f0ae8571 refactor(onebot): compile a sealed Action handler bind
The registry already froze names, kinds, and raw reservations, but
handlers were a second mutable map filled through registerAction.

bind(ctx, api, rawFactories) now returns the complete name-to-handler
table. Stream actions expose toHandler. ApiHandler only installs and
dispatches. The public register ports are gone.
2026-08-16 21:30:10 +08:00
DrSmoothl b1730d74cd test(core): add resolveUin to the group-file identity mock
MockBridge.identity gained resolveUin for the like-list Identity
cascade. The uploadPrivate fixture listed every identity field and
failed core typecheck in CI.
2026-08-16 21:15:40 +08:00
DrSmoothl eee3c49f2d refactor(protocol): map friend and member pages to domain types
FetchFriendListPage and FetchGroupMemberListPage deserialized as
identity functions and leaked Oidb property codes into ContactsApi.

Each page now returns a domain page. Contacts keeps pagination,
category assembly, member cache, and robot classification.
2026-08-16 21:12:59 +08:00
DrSmoothl 23352dcad4 refactor(protocol): resolve like-list UINs through Identity
GetLike already filled cached UINs in deserialize. ProfileApi then
opened a second Contacts hop and threw on fetch failure.

Misses now go through Identity.resolveUin after invokeOidb, coalesced
by uid. ProfileApi.getLike is invoke-only. Unresolved rows stay
uin=0 and no longer fail the action.
2026-08-16 19:23:44 +08:00
DrSmoothl 226b48fd7a refactor(protocol): keep Decoder a pure parse of MsgPush events
Decoder used to write Identity: decodeGroupAdmin patched member roles
and decodeFriendMessage stashed invite-card msgseq. That split
observation with IncomingPacketPipeline.rememberEventIdentity and put
pending-application state on Identity.

Decoder now only returns events. Invite-card groupUin/msgseq ride on
FriendMessage; the live pipeline writes them to ContactsApi through
an optional port. Role self-heal for #93 stays in
rememberEventIdentity. History and forward decode do not write.
Identity no longer stores invite-card sequences.

Live #93 and #125 behavior is unchanged.
2026-08-16 18:22:41 +08:00
DrSmoothl fea1996e46 chore(release): v1.14.9 2026-08-16 15:18:30 +08:00
DrSmoothl 94a8bf8609 fix(flash-transfer): retry get_flash_file_url until the download id appears
create_flash_task can return before the file is downloadable, so an immediate get_flash_file_url failed with no download url (#364).
2026-08-16 15:16:12 +08:00
DrSmoothl 44bbaaa1bb fix(windows): restore sending on current QQ builds 2026-08-16 15:00:20 +08:00
DrSmoothl 8583afaf2c fix(onebot): resolve signed-int32 reply ids
Reply segments treated negative message_id hashes as invalid, so quotes against those events were dropped.
2026-08-16 13:20:35 +08:00
DrSmoothl 6da412ab96 fix(onebot): keep real sender nick on forward nodes that cite a message id
Empty group cards were treated as a name, so get_forward_msg showed the QQ number instead of the stored nickname (#372).
2026-08-16 13:11:53 +08:00
DrSmoothl 401f32d6b2 chore(release): v1.14.8 2026-08-14 14:55:28 +08:00
DrSmoothl d014d6c379 feat(flash-transfer): let create_flash_task set per-file names
upload_file_stream now returns file_name with the original name.
create_flash_task accepts { file, name } so a streamed path can
keep the real filename on the fileset.

Fixes #361
2026-08-14 14:17:58 +08:00
DrSmoothl 925d9c0ac7 feat(flash-file): expose cover URL as flash_file.thumb
Incoming flash cards already carry a cover link; map it to
flash_file.data.thumb. Older cards without a cover leave it empty.

Fixes #367
2026-08-14 14:00:18 +08:00
DrSmoothl 8e9e228a0f fix(flash-transfer): honor create_flash_task name as the card title
create_flash_task already accepted `name`, but the flash card still
showed the first filename. Use a non-empty name as the fileset title
and keep the real filenames on the files themselves.

Fixes #363
2026-08-14 13:34:58 +08:00
DrSmoothl 7ae0fa3c0e fix(windows): refresh bundled native so sending stays up 2026-08-14 13:21:17 +08:00
DrSmoothl 52f0f2d24b test(websocket): cover WebSocket client handshake and close paths 2026-08-14 12:10:18 +08:00
DrSmoothl 69a6148f75 test(websocket): cover extensions, native loader, and upgrade errors 2026-08-14 11:09:22 +08:00
DrSmoothl e59f5e7c5b test(protocol): cover event and reply formatting 2026-08-14 11:09:22 +08:00
DrSmoothl 91f0eb3b7e test(onebot): cover request actions and message-store migration worker 2026-08-14 11:09:22 +08:00
DrSmoothl a70a63343d test(core): cover WebUI port probe and update-check versions 2026-08-14 11:09:21 +08:00
DrSmoothl 2bbd98e90a test(common): cover log file rotation, retention, and reopen 2026-08-14 11:09:21 +08:00
DrSmoothl c02c21c46b test(websocket): cover shared WebSocket framing helpers 2026-08-14 10:57:17 +08:00
DrSmoothl 2e2c1266ac test(core): cover WebUI auth password and TOTP restore 2026-08-14 10:57:17 +08:00
DrSmoothl 31bd8ea77b test(protocol): cover highway streaming hash and upload staging 2026-08-14 10:57:17 +08:00
DrSmoothl 4c994dbd20 test(onebot): cover group admin, message, media, and quick-operation paths 2026-08-14 10:57:17 +08:00
DrSmoothl 8004e9af9d test(sdk): cover API client, chain, emitter, guards, and segments 2026-08-14 10:57:16 +08:00
DrSmoothl 80f34ca720 test(bridge): cover injector lookup and QQ login port probe 2026-08-14 10:57:16 +08:00
DrSmoothl d46d8e4002 chore(release): v1.14.7 2026-08-13 19:47:25 +08:00
DrSmoothl 5a012fe0c8 fix(webui): allow empty OneBot tokens on loopback bind hosts
Empty inbound tokens were gated on the WebUI page hostname / client IP,
so a remote panel visit blocked clearing the token even when the
listener was 127.0.0.1. Trust the bind host as well: loopback listeners
are not reachable from outside, while 0.0.0.0 still requires a local
WebUI session.
2026-08-13 19:45:11 +08:00
DrSmoothl b8b9be83c3 feat(core): stream flash-transfer uploads from disk
create_flash_task loaded every fileset file through loadBinarySource
and kept the bytes through hash, commit, and sliceupload, so a single
file over 1 GiB could not be sent. Stage to disk like group files,
stream MD5/SHA1/Sha1StateV, then POST 1 MiB chunks from FileChunkSource.

Do not reuse video sha1Blocks as Sha1StateV: an exact N-MiB file would
ship an extra un-finalized last-slice state. Local/HTTP sources use the
4 GiB group-file ceiling; inline base64 stays at 1 GiB because stage
still decodes it in RAM. Protocol order, seconds-pass, and multi-file
commit are unchanged.

Fixes #359
2026-08-13 18:34:27 +08:00
DrSmoothl e7322e2e72 fix(protocol): decode current NT flash-transfer cards
Current clients put fileset identity on markdown extInfo and the
open_fileset scheme, not data.fileSetId. Empty message arrays were
the old scraper missing those fields.

Fixes #358
2026-08-13 18:18:56 +08:00
DrSmoothl 9e0dd5d75c chore(native): refresh bundled runtime files 2026-08-13 17:27:54 +08:00
DrSmoothl 7d5ca5523b refactor(protocol): own inbound UID-to-UIN resolution in Identity
Inbound person lookup used to be split across decoders, the packet
pipeline, and Bridge closures. Missing identities were filled from
unrelated packet headers, and "who is this person" was coupled to
roster refresh and pending-request enrichment.

Identity now owns both directions of resolution. The hot path stays
synchronous and emits unresolved events on a miss. Only the paths
that already waited before dispatch perform a network lookup, and
that lookup is a profile fetch by UID rather than a member-list
refresh. Pending-request comments and approval flags stay outside
Identity.

Decoders no longer invent a UIN from a group routing header. Private
chat routing still uses a hop's own wire UIN when the hop is named
that way. Inbound misses stay availability-first: they do not throw
and do not mark Identity degraded.
2026-08-13 14:37:56 +08:00
DrSmoothl d26aef86d8 chore(release): v1.14.6 2026-08-13 12:52:21 +08:00
DrSmoothl f100faaeb6 fix(protocol): read group mute expire from official proto tags (#356)
get_group_info / get_group_list mapped FE5 tag 31 and 88D tag 59 as
shutUpAllTimestamp, then treated any >0 value as muted. Official
wrapper.node maps those tags to internal 60259; the real expire
(60027 / groupShutupExpireTime) is FE5 tag 10 and 88D tag 45
(request mask 45). After a group had been muted, 60259 often stayed
nonzero so group_all_shut stuck at -1. Read the 60027 tags and treat
all-mute as expire > now (0xFFFFFFFF is permanent).

Fixes #356
2026-08-13 12:44:56 +08:00
DrSmoothl 2f5065545a fix(onebot): percent-decode file URL basenames on upload (#354)
send_group_msg / send_private_msg with a file segment that only has
file:// (no name/filename) used url.split('/').pop() as the upload
name, so percent-encoded CJK paths uploaded as
%E6%B5%8B%E8%AF%95%E6%96%87%E4%BB%B6.xlsx. Derive the fallback through
guessFileNameFromUrl, which decodeURIComponent's the path basename
(invalid encodings are left as-is). An explicit name still wins.

Fixes #354
2026-08-13 11:02:02 +08:00
DrSmoothl 5c2f620c54 feat(webui): add optional TOTP 2FA for operator login (#351)
WebUI access was a single shared password. This adds optional
Authenticator TOTP as a second factor, with one-time recovery codes
and SSH as the last-resort disable path.

Login stays two HTTP posts with no pending token: a correct password
and enabled 2FA without a second factor returns { needsTotp: true };
the client then resubmits { password, totp } or { password, recoveryCode }.
The TOTP secret is wrapped with a password-derived AES-256-GCM key.
Eight XXXX-XXXX recovery codes are stored as SHA-256 hashes and each
code is consumed once. Enabling or disabling 2FA invalidates other
sessions; disabling still requires password plus TOTP or a recovery
code. SNOWLUMA_DEV_MODE hides the feature.

The login page uses a dedicated second-factor screen (Interior OTP
cells for the 6-digit code; the same cell UI for recovery codes,
grouped as XXXX-XXXX). Settings expose enroll/confirm/disable and
one-time recovery-code display.

Fixes #351
2026-08-13 01:33:57 +08:00
DrSmoothl 679f3b5b9f fix(highway): delay-retry 102902 instead of aborting the upload (#352)
upload_group_file of ~2 GiB files failed after a highway idle timeout
because the next decoded error_code=102902 was treated as a fatal
server reject. QQ's own BDH client (multi_uploader.cc NeedDelayRetry)
treats 102902 / 302902 as backpressure: wait, switch sender, and
re-PUT the same offset. Mirror that — drop the socket, wait 250 ms,
increment retryTimes, and retry the chunk up to 8 times. Definitive
codes such as 921 still fail immediately.

Fixes #352
2026-08-13 00:20:40 +08:00
DrSmoothl 8ded1065d4 fix(onebot): return profile like user details
Restore the interaction user lists returned by get_profile_like and keep self and other-user lookups consistent with the current client behavior.

Resolve missing account identities when needed, surface lookup failures, and update the public action catalog with the completed response shape. Add regression coverage for request selection, response decoding, identity enrichment, and malformed results.

Fixes #349
2026-08-11 23:46:46 +08:00
DrSmoothl b38db6715f chore(native): refresh bundled runtime files 2026-08-11 23:23:08 +08:00
DrSmoothl 58f1a1fc50 fix(release): make main synchronization deterministic
Fetch and fast-forward the remote main branch without inheriting user pull settings. Verify both refs match before tagging and keep manual recovery instructions aligned with the automated flow.
2026-08-11 18:38:07 +08:00
458 changed files with 43426 additions and 4116 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.5",
"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.5",
"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 -1
View File
@@ -68,7 +68,9 @@ export type HookSessionDeps = {
*
* Emitted events:
* 'login' (uin, packetSender) — real-UIN login detected
* 'disconnected' (wasLoggedIn) — connection dropped or torn down
* 'disconnected' (wasLoggedIn) — connection dropped, torn down, or
* dispose() of a logged-in session
* (process shutdown uses this path)
* 'receive-health-changed' (healthy) — combined receive/request path health changed
* 'status-changed' (status, error) — status field mutated
* 'disposed' () — session stopped tracking this PID
@@ -237,8 +239,13 @@ export class HookSession extends EventEmitter {
dispose(): void {
if (this.disposed) return;
const wasLoggedIn = this.loggedIn;
this.disposed = true;
this.tearDownClient();
// Process shutdown must take the same PID-detach path as a live drop.
// tearDownClient strips the pipe client first, so this emit is the only
// disconnected edge HookManager will see.
if (wasLoggedIn) this.emit('disconnected', true);
this.removeAllListeners();
}
+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 = {}) {
@@ -644,6 +644,40 @@ describe('HookSession — process gone', () => {
});
});
describe('HookSession — dispose', () => {
it('emits disconnected(true) while logged in so BridgeManager can detach the PID', async () => {
const ctx = makeSession({ pipeLive: true });
const discSpy = vi.fn();
ctx.session.on('disconnected', discSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
ctx.session.dispose();
expect(discSpy).toHaveBeenCalledOnce();
expect(discSpy).toHaveBeenCalledWith(true);
expect(ctx.session.isDisposed).toBe(true);
});
it('does not emit disconnected when disposed before login', async () => {
const ctx = makeSession({ pipeLive: true });
const discSpy = vi.fn();
ctx.session.on('disconnected', discSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.session.dispose();
expect(discSpy).not.toHaveBeenCalled();
expect(ctx.session.isDisposed).toBe(true);
});
});
describe('HookSession — refresh drift fix', () => {
// refresh while the pipe is down on a connected-but-never-logged-in
// session now reports 'connecting' (matching what onPipeDown gives for the
+402
View File
@@ -0,0 +1,402 @@
import path from 'path';
import { fileURLToPath } from 'url';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const { existsSyncMock, listPidsMock } = vi.hoisted(() => ({
existsSyncMock: vi.fn<(target: string) => boolean>(() => false),
listPidsMock: vi.fn(() => new Set<number>()),
}));
vi.mock('fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('fs')>();
return {
...actual,
existsSync: (target: Parameters<typeof actual.existsSync>[0]) =>
existsSyncMock(String(target)),
};
});
vi.mock('../src/qq-hook-client', () => ({
listSnowlumaPipePidsSync: listPidsMock,
}));
const INJECTOR_DIR = path.dirname(fileURLToPath(new URL('../src/injector.ts', import.meta.url)));
const ORIGINAL_PLATFORM = process.platform;
const ORIGINAL_ARCH = process.arch;
const HANDLE = {
base: 0x7fff0000n,
entry: 0x7fff1234n,
exceptionTable: 0x7fff5678n,
size: 8192,
};
function setPlatform(platform: NodeJS.Platform, arch: string): void {
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
Object.defineProperty(process, 'arch', { value: arch, configurable: true });
}
function restorePlatform(): void {
Object.defineProperty(process, 'platform', { value: ORIGINAL_PLATFORM, configurable: true });
Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true });
}
function nativeSearchDirs(cwd = process.cwd()): string[] {
return [
path.resolve(INJECTOR_DIR, 'native'),
path.resolve(INJECTOR_DIR, '..', '..', 'runtime', 'native'),
path.resolve(cwd, 'dist', 'native'),
path.resolve(cwd, 'packages', 'runtime', 'native'),
];
}
function nativeCandidate(fileName: string, dirIndex: number, cwd = process.cwd()): string {
return path.join(nativeSearchDirs(cwd)[dirIndex]!, fileName);
}
function allowExisting(paths: readonly string[]): void {
const allowed = new Set(paths);
existsSyncMock.mockImplementation((target) => allowed.has(target));
}
function fakeAddon(overrides: {
getAllMainProcess?: number[];
loadModuleManual?: (pid: number, dylibPath: string) => unknown;
unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void;
} = {}) {
return {
getAllMainProcess: vi.fn(() => overrides.getAllMainProcess ?? []),
loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)),
unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)),
};
}
function installDlopen(addon: object) {
return vi.spyOn(process, 'dlopen').mockImplementation((mod) => {
(mod as { exports: object }).exports = addon;
});
}
async function loadInjector() {
return import('../src/injector');
}
beforeEach(() => {
existsSyncMock.mockReset();
existsSyncMock.mockReturnValue(false);
listPidsMock.mockReset();
listPidsMock.mockReturnValue(new Set());
vi.resetModules();
});
afterEach(() => {
restorePlatform();
vi.restoreAllMocks();
});
describe('resolveHookNativePath', () => {
it('returns null after probing every search directory', async () => {
setPlatform('linux', 'x64');
const probed: string[] = [];
existsSyncMock.mockImplementation((target) => {
probed.push(target);
return false;
});
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('node')).toBeNull();
expect(probed).toEqual([
nativeCandidate('snowluma-linux-x64.node', 0),
nativeCandidate('snowluma-linux-x64.node', 1),
nativeCandidate('snowluma-linux-x64.node', 2),
nativeCandidate('snowluma-linux-x64.node', 3),
]);
});
it('returns the first existing candidate and stops scanning', async () => {
setPlatform('linux', 'x64');
const winner = nativeCandidate('snowluma-linux-x64.node', 0);
const later = nativeCandidate('snowluma-linux-x64.node', 1);
const probed: string[] = [];
existsSyncMock.mockImplementation((target) => {
probed.push(target);
return target === winner || target === later;
});
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('node')).toBe(winner);
expect(probed).toEqual([winner]);
});
it('skips missing earlier directories for the injectable .so', async () => {
setPlatform('linux', 'arm64');
const winner = nativeCandidate('snowluma-linux-arm64.so', 2);
allowExisting([winner]);
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('so')).toBe(winner);
});
it('resolves snowluma-win32-x64.dll on win32 x64', async () => {
setPlatform('win32', 'x64');
const winner = nativeCandidate('snowluma-win32-x64.dll', 3);
allowExisting([winner]);
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('dll')).toBe(winner);
});
it('uses the generic platform-arch name on win32 arm64', async () => {
setPlatform('win32', 'arm64');
const winner = nativeCandidate('snowluma-win32-arm64.node', 1);
allowExisting([winner]);
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('node')).toBe(winner);
});
it('re-reads process.cwd() for the dist/native fallback', async () => {
setPlatform('darwin', 'arm64');
vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd');
const winner = path.join('/tmp/sl-injector-cwd', 'dist', 'native', 'snowluma-darwin-arm64.node');
allowExisting([winner]);
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('node')).toBe(winner);
});
});
describe('getNativeHookAddon / getNativeHookLoadError', () => {
it('starts with a null load error before any probe', async () => {
const { getNativeHookLoadError } = await loadInjector();
expect(getNativeHookLoadError()).toBeNull();
});
it('returns null and records a missing-binary error', async () => {
setPlatform('linux', 'x64');
const dlopen = vi.spyOn(process, 'dlopen');
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
expect(getNativeHookAddon()).toBeNull();
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
expect(dlopen).not.toHaveBeenCalled();
});
it('dlopens the resolved .node once and caches the addon', async () => {
setPlatform('linux', 'x64');
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
allowExisting([nodePath]);
const addon = fakeAddon();
const dlopen = installDlopen(addon);
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
const first = getNativeHookAddon();
const second = getNativeHookAddon();
expect(first).toBe(addon);
expect(second).toBe(addon);
expect(getNativeHookLoadError()).toBeNull();
expect(dlopen).toHaveBeenCalledTimes(1);
expect(dlopen.mock.calls[0]![1]).toBe(nodePath);
});
it('stores Error.message when process.dlopen throws', async () => {
setPlatform('darwin', 'arm64');
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
vi.spyOn(process, 'dlopen').mockImplementation(() => {
throw new Error('not a valid Node addon');
});
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
expect(getNativeHookAddon()).toBeNull();
expect(getNativeHookLoadError()).toBe('not a valid Node addon');
});
it('stringifies a non-Error dlopen failure', async () => {
setPlatform('linux', 'x64');
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
vi.spyOn(process, 'dlopen').mockImplementation(() => {
throw 42;
});
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
expect(getNativeHookAddon()).toBeNull();
expect(getNativeHookLoadError()).toBe('42');
});
it('retries after a failed load when a binary later appears', async () => {
setPlatform('linux', 'x64');
const nodePath = nativeCandidate('snowluma-linux-x64.node', 1);
const addon = fakeAddon();
installDlopen(addon);
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
expect(getNativeHookAddon()).toBeNull();
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
allowExisting([nodePath]);
expect(getNativeHookAddon()).toBe(addon);
expect(getNativeHookLoadError()).toBeNull();
});
});
describe('listHookProcesses', () => {
it('on darwin maps sorted pipe pids without opening the native addon', async () => {
setPlatform('darwin', 'arm64');
listPidsMock.mockReturnValue(new Set([42, 7, 15]));
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
const dlopen = installDlopen(fakeAddon({ getAllMainProcess: [99] }));
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([
{ pid: 7, name: 'qq', path: '' },
{ pid: 15, name: 'qq', path: '' },
{ pid: 42, name: 'qq', path: '' },
]);
expect(listPidsMock).toHaveBeenCalledTimes(1);
expect(dlopen).not.toHaveBeenCalled();
});
it('on darwin returns an empty list when no control sockets exist', async () => {
setPlatform('darwin', 'arm64');
listPidsMock.mockReturnValue(new Set());
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([]);
});
it('on non-darwin returns [] when the addon cannot be loaded', async () => {
setPlatform('linux', 'x64');
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([]);
});
it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => {
setPlatform('linux', 'x64');
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
allowExisting([nodePath]);
installDlopen(fakeAddon({
getAllMainProcess: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2],
}));
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([
{ pid: 2, name: 'qq', path: '' },
{ pid: 8, name: 'qq', path: '' },
]);
});
it('on win32 names processes QQ.exe', async () => {
setPlatform('win32', 'x64');
allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]);
installDlopen(fakeAddon({ getAllMainProcess: [9] }));
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([
{ pid: 9, name: 'QQ.exe', path: '' },
]);
});
});
describe('injectHookProcess', () => {
it('throws the missing-addon load error', async () => {
setPlatform('linux', 'x64');
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(4242)).rejects.toThrow('No hook native addon found for linux-x64');
});
it('throws when the addon exists but the injectable is missing', async () => {
setPlatform('linux', 'x64');
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
installDlopen(fakeAddon());
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64');
});
it('awaits a thenable loadModuleManual handle', async () => {
setPlatform('linux', 'x64');
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
const soPath = nativeCandidate('snowluma-linux-x64.so', 0);
allowExisting([nodePath, soPath]);
const addon = fakeAddon({
loadModuleManual: () => Promise.resolve(HANDLE),
});
installDlopen(addon);
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(4242)).resolves.toEqual({
method: 'loadModuleManual',
handle: HANDLE,
});
expect(addon.loadModuleManual).toHaveBeenCalledTimes(1);
expect(addon.loadModuleManual).toHaveBeenCalledWith(4242, soPath);
});
it('accepts a synchronous loadModuleManual return value', async () => {
setPlatform('darwin', 'arm64');
const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 2);
const soPath = nativeCandidate('snowluma-darwin-arm64.so', 3);
allowExisting([nodePath, soPath]);
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
installDlopen(addon);
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(77)).resolves.toEqual({
method: 'loadModuleManual',
handle: HANDLE,
});
expect(addon.loadModuleManual).toHaveBeenCalledWith(77, soPath);
});
it('injects snowluma-win32-x64.dll on win32 x64', async () => {
setPlatform('win32', 'x64');
const nodePath = nativeCandidate('snowluma-win32-x64.node', 0);
const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0);
allowExisting([nodePath, dllPath]);
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
installDlopen(addon);
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(5150)).resolves.toEqual({
method: 'loadModuleManual',
handle: HANDLE,
});
expect(addon.loadModuleManual).toHaveBeenCalledWith(5150, dllPath);
});
it('propagates a rejected loadModuleManual', async () => {
setPlatform('linux', 'x64');
allowExisting([
nativeCandidate('snowluma-linux-x64.node', 0),
nativeCandidate('snowluma-linux-x64.so', 0),
]);
installDlopen(fakeAddon({
loadModuleManual: () => Promise.reject(new Error('map failed')),
}));
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(7)).rejects.toThrow('map failed');
});
});
describe('unloadHookProcess', () => {
it('throws the missing-addon load error', async () => {
setPlatform('linux', 'x64');
const { unloadHookProcess } = await loadInjector();
expect(() => unloadHookProcess(4242, HANDLE)).toThrow('No hook native addon found for linux-x64');
});
it('forwards pid and handle to unloadModuleManual', async () => {
setPlatform('linux', 'x64');
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
const addon = fakeAddon();
installDlopen(addon);
const { unloadHookProcess } = await loadInjector();
expect(unloadHookProcess(4242, HANDLE)).toBeUndefined();
expect(addon.unloadModuleManual).toHaveBeenCalledTimes(1);
expect(addon.unloadModuleManual).toHaveBeenCalledWith(4242, HANDLE);
});
});
@@ -0,0 +1,30 @@
import { afterEach, describe, expect, it } from 'vitest';
import { QqHookClient } from '../src/qq-hook-client';
import { packetTimeoutMs } from '../src/packet-timeout';
const PACKET = 'SNOWLUMA_PACKET_TIMEOUT_MS';
const ACK = 'SNOWLUMA_HOOK_ACK_TIMEOUT_MS';
afterEach(() => {
delete process.env[PACKET];
delete process.env[ACK];
});
describe('packet and hook ack timeouts', () => {
it('keeps the 15 second packet default', () => {
expect(packetTimeoutMs({})).toBe(15_000);
});
it('reads SNOWLUMA_PACKET_TIMEOUT_MS', () => {
expect(packetTimeoutMs({ [PACKET]: '8000' })).toBe(8000);
expect(packetTimeoutMs({ [PACKET]: '0' })).toBe(15_000);
});
it('uses SNOWLUMA_HOOK_ACK_TIMEOUT_MS when the client is not given one', () => {
process.env[ACK] = '1200';
const client = new QqHookClient(1, { runtimeDir: '/tmp' });
expect(client.defaultAckTimeoutMs).toBe(1200);
const explicit = new QqHookClient(1, { runtimeDir: '/tmp', ackTimeoutMs: 50 });
expect(explicit.defaultAckTimeoutMs).toBe(50);
});
});
@@ -0,0 +1,695 @@
import { EventEmitter } from 'events';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getLogLevel, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
const execMock = vi.hoisted(() => vi.fn());
const httpGetMock = vi.hoisted(() => vi.fn());
const httpsGetMock = vi.hoisted(() => vi.fn());
vi.mock('child_process', () => ({ exec: execMock }));
vi.mock('http', () => ({
default: { get: httpGetMock },
get: httpGetMock,
}));
vi.mock('https', () => ({
default: { get: httpsGetMock },
get: httpsGetMock,
}));
import { probeQqLoginInfo } from '../src/qq-port-probe';
const originalPlatform = process.platform;
const EXEC_OPTIONS = { timeout: 1500, killSignal: 'SIGKILL' };
const PTLOGIN_HEADERS = {
Host: 'localhost.ptlogin2.qq.com',
Referer: 'https://xui.ptlogin2.qq.com/',
Cookie: 'pt_local_token=0',
};
type ExecCallback = (error: Error | null, result?: { stdout: string; stderr: string }) => void;
type RequestLike = EventEmitter & { destroy: ReturnType<typeof vi.fn> };
function setPlatform(platform: string): void {
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
}
function mockExec(replies: Record<string, string | Error>): void {
execMock.mockImplementation((command: string, _options: unknown, callback: ExecCallback) => {
const reply = replies[command];
if (reply === undefined) {
callback(new Error(`unexpected command ${command}`));
return;
}
if (reply instanceof Error) {
callback(reply);
return;
}
callback(null, { stdout: reply, stderr: '' });
});
}
function execCommands(): string[] {
return execMock.mock.calls.map((call) => String(call[0]));
}
function ssLine(port: number, pid: number, owner: 'comma' | 'paren' = 'comma'): string {
const tag = owner === 'comma' ? `pid=${pid},fd=9` : `pid=${pid}`;
return `LISTEN 0 128 127.0.0.1:${port} 0.0.0.0:* users:(("qq",${tag}))`;
}
function netstatLine(localAddr: string, pid: number): string {
return ` TCP ${localAddr} 0.0.0.0:0 LISTENING ${pid}`;
}
function jsonp(accounts: unknown[]): string {
return `ptui_getuins_CB(${JSON.stringify(accounts)});`;
}
function requestStub(): RequestLike {
const req = new EventEmitter() as RequestLike;
req.destroy = vi.fn();
return req;
}
function replyBody(body: string | ReadonlyArray<string | Buffer>) {
return (_url: string, _options: unknown, onResponse: (res: EventEmitter) => void): RequestLike => {
const req = requestStub();
const res = new EventEmitter();
onResponse(res);
const chunks = typeof body === 'string' ? [body] : body;
for (const chunk of chunks) res.emit('data', chunk);
res.emit('end');
return req;
};
}
function replyError(error: Error) {
return (): RequestLike => {
const req = requestStub();
queueMicrotask(() => req.emit('error', error));
return req;
};
}
beforeEach(() => {
execMock.mockReset();
httpGetMock.mockReset();
httpsGetMock.mockReset();
setPlatform('linux');
});
afterEach(() => {
setPlatform(originalPlatform);
vi.useRealTimers();
});
describe('probeQqLoginInfo — unix listing', () => {
it('returns null when ss cannot list sockets', async () => {
mockExec({ 'ss -tlnp': new Error('ss: not found') });
await expect(probeQqLoginInfo(3310)).resolves.toBeNull();
expect(execCommands()).toEqual(['ss -tlnp']);
expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS);
expect(httpGetMock).not.toHaveBeenCalled();
expect(httpsGetMock).not.toHaveBeenCalled();
});
it('reports a logged-out identity when the PID has no sockets and pgrep is below 6', async () => {
mockExec({
'ss -tlnp': 'State Recv-Q Send-Q Local Address:Port Peer Address:Port\n',
'pgrep -c qq': '5\n',
});
await expect(probeQqLoginInfo(3311)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
expect(execCommands()).toEqual(['ss -tlnp', 'pgrep -c qq']);
expect(execMock.mock.calls[1]?.[1]).toEqual(EXEC_OPTIONS);
});
it('treats a pgrep count of 0 as logged out', async () => {
mockExec({
'ss -tlnp': '',
'pgrep -c qq': '0\n',
});
await expect(probeQqLoginInfo(3312)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
});
it('treats a non-numeric pgrep count as 0 and therefore logged out', async () => {
mockExec({
'ss -tlnp': '',
'pgrep -c qq': 'qq: no process found\n',
});
await expect(probeQqLoginInfo(3313)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
});
it('returns null when there are no sockets and pgrep is 6 or higher', async () => {
mockExec({
'ss -tlnp': '',
'pgrep -c qq': '6\n',
});
await expect(probeQqLoginInfo(3314)).resolves.toBeNull();
mockExec({
'ss -tlnp': '',
'pgrep -c qq': '9\n',
});
await expect(probeQqLoginInfo(3315)).resolves.toBeNull();
});
it('does not treat a failed pgrep as logged out', async () => {
mockExec({
'ss -tlnp': '',
'pgrep -c qq': new Error('pgrep: exit 1'),
});
await expect(probeQqLoginInfo(3316)).resolves.toBeNull();
});
it('uses the first listening port as a logged-out hint when no Ptlogin port is present', async () => {
mockExec({
'ss -tlnp': [
ssLine(9218, 4410),
ssLine(18000, 4410),
].join('\n'),
'pgrep -c qq': ' 4 \n',
});
await expect(probeQqLoginInfo(4410)).resolves.toEqual({
port: 9218,
uin: '',
identityKnown: false,
});
expect(httpGetMock).not.toHaveBeenCalled();
expect(httpsGetMock).not.toHaveBeenCalled();
});
it('returns null for non-Ptlogin ports when the QQ process count is ambiguous', async () => {
mockExec({
'ss -tlnp': ssLine(9218, 4411),
'pgrep -c qq': '7\n',
});
await expect(probeQqLoginInfo(4411)).resolves.toBeNull();
expect(httpGetMock).not.toHaveBeenCalled();
expect(httpsGetMock).not.toHaveBeenCalled();
});
it('collects unique ports from ss lines that name the PID with either pid=N, or pid=N)', async () => {
mockExec({
'ss -tlnp': [
'LISTEN 0 128 127.0.0.1:4301users:(("qq",pid=4412,fd=1))',
ssLine(4301, 4412, 'comma'),
ssLine(4301, 4412, 'comma'),
ssLine(4305, 4412, 'paren'),
ssLine(4305, 9999, 'comma'),
'ESTAB 0 0 127.0.0.1:4307 127.0.0.1:443 users:(("qq",pid=4412,fd=4))',
].join('\n'),
});
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '10001', nickname: 'Ada' }])));
await expect(probeQqLoginInfo(4412)).resolves.toEqual({
port: 4301,
uin: '10001',
nickName: 'Ada',
identityKnown: true,
});
expect(httpsGetMock).toHaveBeenCalledTimes(2);
expect(httpsGetMock.mock.calls[0]?.[0]).toBe(
'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
);
});
});
describe('probeQqLoginInfo — Ptlogin identity', () => {
it('reads a single account from an odd Ptlogin port over https', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5501) });
httpsGetMock.mockImplementation(replyBody(jsonp([{
uin: 319427101,
account: 1,
nickname: 'Snow',
extra: 'ignored',
}])));
await expect(probeQqLoginInfo(5501)).resolves.toEqual({
port: 4301,
uin: '319427101',
nickName: 'Snow',
identityKnown: true,
});
expect(httpGetMock).not.toHaveBeenCalled();
expect(httpsGetMock).toHaveBeenCalledTimes(2);
expect(httpsGetMock.mock.calls[0]?.[1]).toEqual({
headers: PTLOGIN_HEADERS,
timeout: 500,
rejectUnauthorized: false,
});
});
it('reads a single account from an even Ptlogin port over http', async () => {
mockExec({ 'ss -tlnp': ssLine(4302, 5502) });
httpGetMock.mockImplementation(replyBody(jsonp([{
account: '2880036470',
}])));
await expect(probeQqLoginInfo(5502)).resolves.toEqual({
port: 4302,
uin: '2880036470',
nickName: '',
identityKnown: true,
});
expect(httpsGetMock).not.toHaveBeenCalled();
expect(httpGetMock).toHaveBeenCalledTimes(2);
expect(httpGetMock.mock.calls[0]?.[0]).toBe(
'http://127.0.0.1:4302/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
);
expect(httpGetMock.mock.calls[0]?.[1]).toEqual({
headers: PTLOGIN_HEADERS,
timeout: 500,
});
});
it('probes every documented odd Ptlogin port over https', async () => {
for (const port of [4301, 4303, 4305, 4307, 4309]) {
execMock.mockReset();
httpsGetMock.mockReset();
httpGetMock.mockReset();
mockExec({ 'ss -tlnp': ssLine(port, 5510) });
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '70001', nickname: 'Odd' }])));
await expect(probeQqLoginInfo(5510)).resolves.toEqual({
port,
uin: '70001',
nickName: 'Odd',
identityKnown: true,
});
expect(httpGetMock).not.toHaveBeenCalled();
expect(String(httpsGetMock.mock.calls[0]?.[0])).toBe(
`https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`,
);
}
});
it('probes every documented even Ptlogin port over http when no odd port is listening', async () => {
for (const port of [4302, 4304, 4306, 4308, 4310]) {
execMock.mockReset();
httpsGetMock.mockReset();
httpGetMock.mockReset();
mockExec({ 'ss -tlnp': ssLine(port, 5511) });
httpGetMock.mockImplementation(replyBody(jsonp([{ uin: '70002', nickname: 'Even' }])));
await expect(probeQqLoginInfo(5511)).resolves.toEqual({
port,
uin: '70002',
nickName: 'Even',
identityKnown: true,
});
expect(httpsGetMock).not.toHaveBeenCalled();
expect(String(httpGetMock.mock.calls[0]?.[0])).toBe(
`http://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`,
);
}
});
it('prefers odd Ptlogin ports and never falls through to even ones', async () => {
mockExec({
'ss -tlnp': [ssLine(4302, 5520), ssLine(4301, 5520)].join('\n'),
});
httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED')));
await expect(probeQqLoginInfo(5520)).resolves.toBeNull();
expect(httpsGetMock).toHaveBeenCalled();
expect(httpGetMock).not.toHaveBeenCalled();
expect(execCommands()).toEqual(['ss -tlnp']);
});
it('tries the next odd Ptlogin port after the first one fails', async () => {
mockExec({
'ss -tlnp': [ssLine(4301, 5521), ssLine(4305, 5521)].join('\n'),
});
httpsGetMock
.mockImplementationOnce(replyBody('<html>nope</html>'))
.mockImplementationOnce(replyBody('<html>nope</html>'))
.mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }])))
.mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }])));
await expect(probeQqLoginInfo(5521)).resolves.toEqual({
port: 4305,
uin: '188888',
nickName: 'Next',
identityKnown: true,
});
expect(httpsGetMock.mock.calls.map((call) => call[0])).toEqual([
'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
]);
});
it('stops after the first Ptlogin port that yields a single account', async () => {
mockExec({
'ss -tlnp': [ssLine(4303, 5522), ssLine(4309, 5522)].join('\n'),
});
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '42', nickname: 'First' }])));
await expect(probeQqLoginInfo(5522)).resolves.toEqual({
port: 4303,
uin: '42',
nickName: 'First',
identityKnown: true,
});
expect(httpsGetMock).toHaveBeenCalledTimes(2);
});
it('uses account when uin is missing or empty, including a numeric 0 uin', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5530) });
httpsGetMock
.mockImplementationOnce(replyBody(jsonp([{ uin: 0, account: 314159, nickname: 'Zero' }])))
.mockImplementationOnce(replyBody(jsonp([{ uin: '', account: '314159', nickname: 'Zero' }])));
await expect(probeQqLoginInfo(5530)).resolves.toEqual({
port: 4301,
uin: '314159',
nickName: 'Zero',
identityKnown: true,
});
});
it('returns an empty uin when the single account has neither uin nor account', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5531) });
httpsGetMock.mockImplementation(replyBody('[{"nickname":"Anon"}]'));
await expect(probeQqLoginInfo(5531)).resolves.toEqual({
port: 4301,
uin: '',
nickName: 'Anon',
identityKnown: true,
});
});
it('keeps the shorter of the two pt_get_uins snapshots', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5540) });
httpsGetMock
.mockImplementationOnce(replyBody(jsonp([
{ uin: '11', nickname: 'A' },
{ uin: '22', nickname: 'B' },
])))
.mockImplementationOnce(replyBody(jsonp([{ uin: '33', nickname: 'Cora' }])));
await expect(probeQqLoginInfo(5540)).resolves.toEqual({
port: 4301,
uin: '33',
nickName: 'Cora',
identityKnown: true,
});
});
it('keeps the first snapshot when both pt_get_uins calls have one account', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5541) });
httpsGetMock
.mockImplementationOnce(replyBody(jsonp([{ uin: '100', nickname: 'Left' }])))
.mockImplementationOnce(replyBody(jsonp([{ uin: '200', nickname: 'Right' }])));
await expect(probeQqLoginInfo(5541)).resolves.toEqual({
port: 4301,
uin: '100',
nickName: 'Left',
identityKnown: true,
});
});
it('accepts a single account from the second fetch when the first fetch is unusable', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5542) });
httpsGetMock
.mockImplementationOnce(replyError(new Error('ECONNRESET')))
.mockImplementationOnce(replyBody(jsonp([{ uin: '9090', nickname: 'Retry' }])));
await expect(probeQqLoginInfo(5542)).resolves.toEqual({
port: 4301,
uin: '9090',
nickName: 'Retry',
identityKnown: true,
});
});
it('returns null for an empty pt_get_uins array and does not consult pgrep', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5550) });
httpsGetMock.mockImplementation(replyBody('ptui_getuins_CB([]);'));
await expect(probeQqLoginInfo(5550)).resolves.toBeNull();
expect(execCommands()).toEqual(['ss -tlnp']);
});
it('returns null when both snapshots have more than one account', async () => {
mockExec({ 'ss -tlnp': ssLine(4304, 5551) });
httpGetMock.mockImplementation(replyBody(jsonp([
{ uin: '1' },
{ uin: '2' },
])));
await expect(probeQqLoginInfo(5551)).resolves.toBeNull();
});
it('returns null when both fetches fail to parse a pt_get_uins body', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5552) });
httpsGetMock.mockImplementation(replyBody('not-jsonp'));
await expect(probeQqLoginInfo(5552)).resolves.toBeNull();
});
it('returns null when both fetches error', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5553) });
httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED')));
await expect(probeQqLoginInfo(5553)).resolves.toBeNull();
});
it('destroys the request and returns null when both fetches time out', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5554) });
const seen: RequestLike[] = [];
httpsGetMock.mockImplementation(() => {
const req = requestStub();
seen.push(req);
queueMicrotask(() => req.emit('timeout'));
return req;
});
await expect(probeQqLoginInfo(5554)).resolves.toBeNull();
expect(seen).toHaveLength(2);
expect(seen[0]?.destroy).toHaveBeenCalledTimes(1);
expect(seen[1]?.destroy).toHaveBeenCalledTimes(1);
});
it('joins chunked pt_get_uins bodies including Buffer pieces', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5560) });
httpsGetMock.mockImplementation(replyBody([
'ptui_getuins_CB([',
Buffer.from('{"uin":"10001","nickname":"Ada"}'),
']);',
]));
await expect(probeQqLoginInfo(5560)).resolves.toEqual({
port: 4301,
uin: '10001',
nickName: 'Ada',
identityKnown: true,
});
});
it('treats a nickname that closes the JSONP array early as unusable', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5561) });
httpsGetMock.mockImplementation(replyBody('ptui_getuins_CB([{"nickname":"a]b","uin":"1"}]);'));
await expect(probeQqLoginInfo(5561)).resolves.toBeNull();
});
});
describe('probeQqLoginInfo — win32 listing', () => {
beforeEach(() => {
setPlatform('win32');
});
it('returns null when netstat cannot list sockets', async () => {
mockExec({ 'netstat -ano': new Error('netstat: access denied') });
await expect(probeQqLoginInfo(6610)).resolves.toBeNull();
expect(execCommands()).toEqual(['netstat -ano']);
expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS);
});
it('counts QQ.exe rows from tasklist when netstat lists no sockets for the PID', async () => {
mockExec({
'netstat -ano': [
'Active Connections',
'',
' Proto Local Address Foreign Address State PID',
netstatLine('127.0.0.1:4301', 1),
].join('\n'),
'tasklist /fi "imagename eq QQ.exe" /nh': [
'QQ.exe 100 Console 1 10,000 K',
'QQ.exe 101 Console 1 11,000 K',
'explorer.exe 200 Console 1 9,000 K',
].join('\n'),
});
await expect(probeQqLoginInfo(6611)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
expect(execCommands()).toEqual([
'netstat -ano',
'tasklist /fi "imagename eq QQ.exe" /nh',
]);
});
it('returns null when tasklist reports 6 or more QQ.exe rows and the PID has no sockets', async () => {
mockExec({
'netstat -ano': '',
'tasklist /fi "imagename eq QQ.exe" /nh': [
'QQ.exe 1',
'QQ.exe 2',
'QQ.exe 3',
'qq.exe 4',
'QQ.EXE 5',
'QQ.exe 6',
].join('\n'),
});
await expect(probeQqLoginInfo(6612)).resolves.toBeNull();
});
it('does not treat a failed tasklist as logged out', async () => {
mockExec({
'netstat -ano': '',
'tasklist /fi "imagename eq QQ.exe" /nh': new Error('tasklist: exit 1'),
});
await expect(probeQqLoginInfo(6613)).resolves.toBeNull();
});
it('parses netstat rows for the owning PID and skips short or portless lines', async () => {
mockExec({
'netstat -ano': [
'Active Connections',
' TCP 127.0.0.1:4301 LISTENING',
' TCP 127.0.0.1 0.0.0.0:0 LISTENING 6620',
netstatLine('10.0.0.8:18000', 1),
netstatLine('127.0.0.1:4303', 6620),
netstatLine('[::1]:4303', 6620),
netstatLine('127.0.0.1:9218', 6620),
].join('\n'),
});
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '20002', nickname: 'Win' }])));
await expect(probeQqLoginInfo(6620)).resolves.toEqual({
port: 4303,
uin: '20002',
nickName: 'Win',
identityKnown: true,
});
expect(httpsGetMock).toHaveBeenCalledTimes(2);
expect(httpsGetMock.mock.calls[0]?.[0]).toBe(
'https://127.0.0.1:4303/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
);
});
it('uses the first netstat port as a logged-out hint when no Ptlogin port is present', async () => {
mockExec({
'netstat -ano': [
netstatLine('127.0.0.1:18000', 6630),
netstatLine('127.0.0.1:18001', 6630),
].join('\n'),
'tasklist /fi "imagename eq QQ.exe" /nh': 'QQ.exe 100\n',
});
await expect(probeQqLoginInfo(6630)).resolves.toEqual({
port: 18000,
uin: '',
identityKnown: false,
});
expect(httpGetMock).not.toHaveBeenCalled();
expect(httpsGetMock).not.toHaveBeenCalled();
});
});
describe('probeQqLoginInfo — overall deadline', () => {
it('returns null and warns after 5000ms if listing never finishes', async () => {
vi.useFakeTimers();
execMock.mockImplementation(() => undefined);
const previousLevel = getLogLevel();
setLogLevel('info');
const warnings: string[] = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.scope === 'LoginProbe' && entry.level === 'warn') {
warnings.push(entry.message);
}
});
try {
const pending = probeQqLoginInfo(9001);
let settled: unknown = 'pending';
void pending.then((value) => {
settled = value;
});
await vi.advanceTimersByTimeAsync(4999);
expect(settled).toBe('pending');
await vi.advanceTimersByTimeAsync(1);
await expect(pending).resolves.toBeNull();
expect(warnings).toEqual(['login check timed out: PID=9001']);
} finally {
unsubscribe();
setLogLevel(previousLevel);
}
});
it('does not warn when the probe finishes before the deadline', async () => {
mockExec({
'ss -tlnp': '',
'pgrep -c qq': '2\n',
});
const previousLevel = getLogLevel();
setLogLevel('info');
const warnings: string[] = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.scope === 'LoginProbe') warnings.push(entry.message);
});
try {
await expect(probeQqLoginInfo(9002)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
expect(warnings).toEqual([]);
} finally {
unsubscribe();
setLogLevel(previousLevel);
}
});
it('abandons a hung Ptlogin fetch at the overall deadline', async () => {
vi.useFakeTimers();
mockExec({ 'ss -tlnp': ssLine(4301, 9003) });
httpsGetMock.mockImplementation(() => requestStub());
const pending = probeQqLoginInfo(9003);
await vi.advanceTimersByTimeAsync(5000);
await expect(pending).resolves.toBeNull();
});
});
+5 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.14.5",
"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);
}
});
});
File diff suppressed because it is too large. Load diff
+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({});
+6 -5
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.14.5",
"version": "1.14.22",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -44,17 +44,18 @@
"@snowluma/bridge": "workspace:*",
"@snowluma/common": "workspace:*",
"@snowluma/onebot": "workspace:*",
"@snowluma/protocol": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/protocol": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/websocket": "workspace:*"
"@snowluma/websocket": "workspace:*",
"otpauth": "^9.5.1"
},
"devDependencies": {
"@hono/node-server": "^1.19.14",
"@hono/node-server": "^1.19.15",
"@rollup/plugin-node-resolve": "^16.0.3",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"hono": "^4.12.25",
"hono": "^4.12.34",
"tsx": "^4.21.0",
"typescript": "catalog:",
"vite": "catalog:",
+93 -104
View File
@@ -1,5 +1,9 @@
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
import { FetchFriendListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
import {
FetchFriendListPage,
type FriendListPageCategory,
type FriendListPageEntry,
} from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
import { FetchGroupDetail } from '@snowluma/protocol/oidb-services/contacts/fetch-group-detail';
import { FetchGroupList } from '@snowluma/protocol/oidb-services/contacts/fetch-group-list';
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
@@ -15,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';
@@ -34,35 +43,16 @@ import type { BridgeContext } from '../bridge-context';
const log = createLogger('Bridge.Contacts');
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
type FriendPropertySource = {
additional?: Array<{
type?: number;
layer1?: {
properties?: Array<{
code?: number;
value?: string;
}>;
};
}>;
};
interface FriendRosterEntry {
friend: FriendInfo;
categoryId: number;
}
interface FriendCategoryMeta {
categoryId: number;
categoryName: string;
memberCount: number;
sortId: number;
// Official client stores group mute as an expire timestamp (internal 60027 /
// JS groupShutupExpireTime): 0 = off, 0xFFFFFFFF = permanent, otherwise unix
// seconds. `> 0` is wrong — a leftover past expire still looks "on".
function isGroupAllMuted(expireTs?: number, nowSec = Math.floor(Date.now() / 1000)): boolean {
return (expireTs ?? 0) > nowSec;
}
interface FriendRoster {
entries: FriendRosterEntry[];
categories: FriendCategoryMeta[];
entries: FriendListPageEntry[];
categories: FriendListPageCategory[];
}
export interface SetFriendCategoryParams {
@@ -71,25 +61,6 @@ export interface SetFriendCategoryParams {
categoryName?: string;
}
export function buildFriendProperties(raw: FriendPropertySource): Map<number, string> {
const props = new Map<number, string>();
for (const additional of raw.additional ?? []) {
if ((additional.type ?? 0) !== 1 || !additional.layer1) continue;
for (const property of additional.layer1.properties ?? []) {
props.set(property.code ?? 0, property.value ?? '');
}
}
return props;
}
export function permissionToRole(permission: number): string {
switch (permission) {
case 1: return 'owner';
case 2: return 'admin';
default: return 'member';
}
}
export function isRobotUin(uin: number, ranges: readonly RobotUinRange[]): boolean {
return Number.isInteger(uin)
&& uin > 0
@@ -127,6 +98,9 @@ export class ContactsApi {
load: (groupId) => this.fetchGroupMemberListUncached(groupId),
});
private robotUinRangesPromise_: Promise<RobotUinRangeSnapshot> | null = null;
/** groupUin → approval msgseq from a private qun.invite card. Written
* only by IncomingPacketPipeline (and tests). OneBot reads get/find. */
private readonly groupInviteCardSeqs_ = new Map<number, number>();
constructor(private readonly ctx: BridgeContext) { }
@@ -168,37 +142,25 @@ export class ContactsApi {
return GetGroupRecommendArk.invoke(this.ctx, { groupId });
}
/** Send a custom 图文 ark card to a C2C peer or group (0xdc2_34). */
sendTuwenArk(params: SendTuwenArkParams): Promise<void> {
return SendTuwenArk.invoke(this.ctx, params);
}
private async fetchFriendRoster(): Promise<FriendRoster> {
const entries: FriendRosterEntry[] = [];
const categories = new Map<number, FriendCategoryMeta>();
const entries: FriendListPageEntry[] = [];
const categories = new Map<number, FriendListPageCategory>();
const seenCookies = new Set<string>();
let cookie: Uint8Array | undefined;
for (;;) {
const resp = await FetchFriendListPage.invoke(this.ctx, { cookie });
for (const raw of resp.friends ?? []) {
const props = buildFriendProperties(raw);
entries.push({
categoryId: raw.customGroup ?? 0,
friend: {
uin: raw.uin ?? 0,
uid: raw.uid ?? '',
nickname: props.get(20002) ?? String(raw.uin ?? 0),
remark: props.get(103) ?? '',
},
});
}
for (const raw of resp.categories ?? []) {
const categoryId = raw.categoryId ?? 0;
categories.set(categoryId, {
categoryId,
categoryName: raw.categoryName ?? '',
memberCount: raw.memberCount ?? 0,
sortId: raw.sortId ?? 0,
});
const page = await FetchFriendListPage.invoke(this.ctx, { cookie });
entries.push(...page.entries);
for (const category of page.categories) {
categories.set(category.categoryId, category);
}
const next = resp.cookie;
const next = page.cookie;
if (!next?.length) break;
const key = toHex(next);
if (seenCookies.has(key)) {
@@ -310,7 +272,11 @@ export class ContactsApi {
// is not in the list (0x88D_0 detail only), so it stays undefined here.
createTime: raw.info?.createdTime ?? 0,
memo: raw.info?.announcement || raw.info?.description || '',
allMuted: (raw.info?.shutUpAllTimestamp ?? 0) > 0,
// #490: expose the description alongside `memo`. QQ fills in either
// field alone, so folding both into `memo` made the description
// unreachable whenever an announcement was also set.
description: raw.info?.description ?? '',
allMuted: isGroupAllMuted(raw.info?.shutUpAllTimestamp),
});
}
this.ctx.identity.rememberGroups(groups);
@@ -337,11 +303,13 @@ export class ContactsApi {
memberMax: Number(r.maxMemberCount ?? 0n),
members: new Map(),
// #197: the detail is the only source of `level`; it also carries
// createTime + the notice preview (memo).
// createTime + the notice preview (memo). `description` is deliberately
// left unset — 0x88D_0 has no description tag, so for a group the bot
// hasn't joined there is nothing to report (#490).
createTime: Number(r.createTime ?? 0n),
level: Number(r.level ?? 0n),
memo: r.noticePreview ?? '',
allMuted: (r.shutUpAllTimestamp ?? 0) > 0,
allMuted: isGroupAllMuted(r.shutUpAllTimestamp),
};
}
@@ -360,23 +328,9 @@ export class ContactsApi {
const members: GroupMemberInfo[] = [];
let token = '';
do {
const resp = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token });
for (const raw of resp.members ?? []) {
members.push({
uin: raw.uin?.uin ?? 0,
uid: raw.uin?.uid ?? '',
nickname: raw.memberName ?? '',
card: raw.memberCard?.memberCard ?? '',
isRobot: false,
role: permissionToRole(raw.permission ?? 0),
level: raw.level?.level ?? 0,
title: raw.specialTitle ?? '',
joinTime: raw.joinTimestamp ?? 0,
lastSentTime: raw.lastMsgTimestamp ?? 0,
shutUpTime: raw.shutUpTimestamp ?? 0,
});
}
token = resp.token ?? '';
const page = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token });
members.push(...page.members);
token = page.token;
} while (token);
const robotSnapshot = await robotSnapshotPromise;
@@ -404,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,
@@ -416,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);
@@ -430,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,
@@ -451,6 +426,9 @@ export class ContactsApi {
eventType: operationType ?? 0,
comment: raw.comment ?? '',
filtered,
operateTransInfo: raw.operateTransInfo && raw.operateTransInfo.length > 0
? raw.operateTransInfo
: undefined,
});
}
this.ctx.identity.rememberGroupRequests(requests);
@@ -507,23 +485,34 @@ export class ContactsApi {
eventType: operationType ?? 0,
comment: raw.comment ?? '',
filtered,
operateTransInfo: raw.operateTransInfo && raw.operateTransInfo.length > 0
? raw.operateTransInfo
: undefined,
});
}
this.ctx.identity.rememberGroupRequests(requests);
return requests;
}
/** Live observation write. IncomingPacketPipeline and tests only. */
rememberGroupInviteCardSequence(groupUin: number, sequence: number): void {
if (groupUin > 0 && sequence > 0) this.groupInviteCardSeqs_.set(groupUin, sequence);
}
/** The approval msgseq captured from a private "qun.invite" card for this
* group, or undefined if none was seen. `set_group_add_request` uses it to
* approve a bot self-invite via 0x10c8 (eventType=2). See issue #125. */
getGroupInviteCardSequence(groupId: number): number | undefined {
return this.ctx.identity.getGroupInviteCardSequence(groupId);
return this.groupInviteCardSeqs_.get(groupId);
}
/** Resolve the group for a private invite-card msgseq. Numeric OneBot flags
* use this path because the card sequence is absent from 0x10C0. */
findGroupInviteCardGroupBySequence(sequence: number): number | undefined {
return this.ctx.identity.findGroupInviteCardGroupBySequence(sequence);
for (const [groupUin, rememberedSequence] of this.groupInviteCardSeqs_) {
if (rememberedSequence === sequence) return groupUin;
}
return undefined;
}
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
+246 -109
View File
@@ -17,13 +17,116 @@ import { SetFilesetStatus } from '@snowluma/protocol/oidb-services/flash-transfe
import { ApplyUpload } from '@snowluma/protocol/oidb-services/flash-transfer/apply-upload';
import { PrepareUpload } from '@snowluma/protocol/oidb-services/flash-transfer/prepare-upload';
import { SendFlashMsg } from '@snowluma/protocol/oidb-services/flash-transfer/send-flash';
import { loadBinarySource, computeHashes } from '@snowluma/protocol/highway/utils';
import { FileChunkSource } from '@snowluma/protocol/highway';
import {
computeHashes,
inlineBase64Payload,
FLASH_TRANSFER_MAX_BYTES,
FLASH_TRANSFER_INLINE_MAX_BYTES,
} from '@snowluma/protocol/highway/utils';
import { stageSourceToDisk } from '@snowluma/protocol/highway/stage';
import { hashFlashFileStreaming } from '@snowluma/protocol/highway/hash-file';
import { computeSha1StateV } from '@snowluma/protocol/highway/sha1-stream';
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
import type { FlashSliceUploadBody, FlashSliceUploadResp, FlashFileId } from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { randomUUID, randomBytes, createHash } from 'node:crypto';
import { promises as fsp } from 'node:fs';
import { deflateSync } from 'node:zlib';
const FLASH_SLICE_SIZE = 1024 * 1024;
const FLASH_IMAGE_EXT = new Set([
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'heic', 'avif', 'tiff', 'tif', 'ico', 'dib', 'heif',
]);
const FLASH_AUDIO_EXT = new Set(['mp3', 'wav', 'aac', 'flac']);
const FLASH_VIDEO_EXT = new Set([
'mp4', 'avi', 'mkv', 'mov', '3gp', 'mpeg', 'rmvb', 'rm', 'wmv', 'flv', 'asf', 'webm', 'mpg', 'vob', 'm4v', 'f4v',
]);
const FLASH_ARCHIVE_EXT = new Set(['zip', 'rar', 'tar', 'bz2', 'xz', 'tgz', 'gz', '7z']);
const FLASH_MODEL_EXT = new Set(['pt', 'pth', 'onnx', 'model', 'mlmodel']);
/** 0x93cf f3 粗类:压缩包走 2/6,其余按媒体类 7。 */
function flashApplyTypeCode(ext: string): number {
if (ext === 'zip') return 6;
if (FLASH_ARCHIVE_EXT.has(ext)) return 2;
return 7;
}
/**
* 0x93d0 / 0x12a9 格式码。与 QQ 客户端按扩展名判定的图标类型一致:
* 图片 26、音频 1、视频 2、文档 3、压缩包 4、未知 11。
*/
function flashFormatCode(ext: string): number {
if (FLASH_IMAGE_EXT.has(ext)) return 26;
if (FLASH_AUDIO_EXT.has(ext)) return 1;
if (FLASH_VIDEO_EXT.has(ext)) return 2;
if (ext === 'doc' || ext === 'docx') return 3;
if (FLASH_ARCHIVE_EXT.has(ext)) return 4;
if (ext === 'apk') return 5;
if (ext === 'xls' || ext === 'xlsx') return 6;
if (ext === 'ppt' || ext === 'pptx') return 7;
if (ext === 'html' || ext === 'htm') return 8;
if (ext === 'pdf') return 9;
if (ext === 'txt') return 10;
if (ext === 'psd') return 12;
if (FLASH_MODEL_EXT.has(ext)) return 15;
if (ext === 'ttf' || ext === 'otf') return 16;
if (ext === 'ipa') return 17;
if (ext === 'dmg') return 23;
if (ext === 'pkg') return 24;
if (ext === 'key') return 18;
if (ext === 'note') return 19;
if (ext === 'numbers') return 20;
if (ext === 'pages') return 21;
if (ext === 'sketch') return 22;
if (ext === 'exe') return 27;
return 11;
}
/** After create returns, 0x93d4 can still omit the main-file fileId for a
* few seconds (#364). Re-query on this schedule (first lookup is immediate). */
const FLASH_FILE_ID_RETRY_DELAYS_MS = [1000, 2000, 4000, 4000] as const;
/** Fail cleanly if the staged file changed since the streaming hash pass. */
async function assertUnchanged(filePath: string, baseline: { size: number; mtimeMs: number }): Promise<void> {
const now = await fsp.stat(filePath);
if (now.size !== baseline.size || now.mtimeMs !== baseline.mtimeMs) {
throw new Error('file source changed during send (mutated between hashing and upload)');
}
}
function flashStageMaxBytes(source: string): number {
return inlineBase64Payload(source) !== null
? FLASH_TRANSFER_INLINE_MAX_BYTES
: FLASH_TRANSFER_MAX_BYTES;
}
interface StagedFlashItem {
filePath: string;
fileSize: number;
fileName: string;
fileUuid: string;
fileIndex: number;
formatCode: number;
guardStat: { size: number; mtimeMs: number };
cleanup(): Promise<void>;
}
/** One create_flash_task source: a path/URL, or a path plus a display name. */
export type FlashTaskFileInput = string | { file: string; name?: string };
function flashFileDisplayName(override: string | undefined, fallback: string): string {
const cleaned = (override ?? '').replace(/[/\\]/g, '_').trim();
return cleaned || fallback;
}
function normalizeFlashTaskInputs(
files: FlashTaskFileInput | FlashTaskFileInput[],
): { file: string; name?: string }[] {
const list = Array.isArray(files) ? files : [files];
return list.map((item) => (typeof item === 'string' ? { file: item } : item));
}
/** 闪传文件信息(业务层,从 FlashFileEntry 转换)。 */
export interface FlashFileInfo {
filesetUuid: string;
@@ -216,21 +319,30 @@ export class FlashTransferApi {
* 多文件时每条 f6=序号、f14=主文件 fileId),按 fileIndex 选中后走 0x12a9 sub=200
* 拿主文件直链。0x93d3/0x93d4 的 downloadUrl 字段是缩略图(appid=14903/14902),
* 主文件必须走 0x12a9 sub=200。
*
* create 刚返回时 f14 可能还是空的(#364)。fileId 空则按
* FLASH_FILE_ID_RETRY_DELAYS_MS 再问 0x93d4;已经有 fileId 后 0x12a9 只打一枪。
*/
private async getFileDownload(
filesetUuid: string, fileIndex: number = 1,
): Promise<{ url: string; fileName: string; fileSize: number } | null> {
const metas = await GetDownloadUrl.invoke(this.ctx, { filesetUuid });
const meta = metas.find((m) => m.fileIndex === fileIndex);
if (!meta || !meta.fileId) return null;
const url = await GetFlashDownload.invoke(this.ctx, {
filesetUuid: meta.filesetUuid,
fileUuid: meta.fileUuid,
fileId: meta.fileId,
fileName: meta.fileName,
});
if (!url) return null;
return { url, fileName: meta.fileName, fileSize: meta.fileSize };
for (let attempt = 0; ; attempt++) {
const metas = await GetDownloadUrl.invoke(this.ctx, { filesetUuid });
const meta = metas.find((m) => m.fileIndex === fileIndex);
if (meta?.fileId) {
const url = await GetFlashDownload.invoke(this.ctx, {
filesetUuid: meta.filesetUuid,
fileUuid: meta.fileUuid,
fileId: meta.fileId,
fileName: meta.fileName,
});
if (!url) return null;
return { url, fileName: meta.fileName, fileSize: meta.fileSize };
}
const delay = FLASH_FILE_ID_RETRY_DELAYS_MS[attempt];
if (delay === undefined) return null;
await new Promise<void>((resolve) => setTimeout(resolve, delay));
}
}
/**
@@ -329,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 编码)。
@@ -377,11 +481,21 @@ export class FlashTransferApi {
* 多文件:0x93d0 的 f4 是 repeated,一个 commit 请求同时携带 fileset 内所有文件
* 条目,每条 f6=文件序号(1,2,3...)。commit 在上传前只发一次,之后 complete →
* 逐个 prepare/apply/sliceupload。prepare/apply 的 filesetWrap.f4 必须与 commit
* 的 f6 一致,否则文件不计入 fileset。多文件时 ApplyFileset 的 fileName 用
* 「<首文件名>等N个文件」、fileSize 用总和——服务端据此判定 fileset 为多文件。
* 的 f6 一致,否则文件不计入 fileset。ApplyFileset 的 fileName 是 fileset 显示名
* (卡片标题):有 name 用 name,否则单文件用首文件名、多文件用「<首文件名>等N个文件」。
* fileSize 用总和——服务端据此判定 fileset 为多文件。各文件在 commit 里用
* 条目上的 name(若有),否则用路径 basename。
*
* 源文件经 stageSourceToDisk 落到本地路径后流式哈希 / 分片读取,不再经
* loadBinarySource 整文件进内存。本地与 HTTP 上限与群文件相同(4 GiB);
* 内联 base64 仍按 1 GiB 封顶,因为 stage 解码时会占用等量 RAM。
*/
async createFlashTask(files: string | string[], _name?: string, _thumbPath?: string): Promise<{ filesetId: string }> {
const fileList = Array.isArray(files) ? files : [files];
async createFlashTask(
files: FlashTaskFileInput | FlashTaskFileInput[],
name?: string,
_thumbPath?: string,
): Promise<{ filesetId: string }> {
const fileList = normalizeFlashTaskInputs(files);
if (fileList.length === 0) throw new Error('create_flash_task: files is empty');
const uploader = {
uin: this.ctx.identity.uin,
@@ -390,104 +504,127 @@ export class FlashTransferApi {
// uid drops the fileset if this runs before warmup populated selfUid.
uid: await resolveSelfUid(this.ctx),
};
// 读取所有文件,每个分配 fileUuid + 序号 + formatCode
const items: { bytes: Uint8Array; fileName: string; fileUuid: string; fileIndex: number; formatCode: number }[] = [];
for (let i = 0; i < fileList.length; i++) {
const { bytes, fileName } = await loadBinarySource(fileList[i], 'flash-transfer');
const { formatCode } = FlashTransferApi.fileTypeCode(fileName);
items.push({ bytes: new Uint8Array(bytes), fileName, fileUuid: randomUUID(), fileIndex: i + 1, formatCode });
const items: StagedFlashItem[] = [];
try {
for (let i = 0; i < fileList.length; i++) {
const source = fileList[i]!.file;
if (!source) throw new Error('create_flash_task: files is empty');
const staged = await stageSourceToDisk(source, flashStageMaxBytes(source));
const fileName = flashFileDisplayName(fileList[i]!.name, staged.fileName);
const { formatCode } = FlashTransferApi.fileTypeCode(fileName);
items.push({
filePath: staged.filePath,
fileSize: staged.fileSize,
fileName,
fileUuid: randomUUID(),
fileIndex: i + 1,
formatCode,
guardStat: await fsp.stat(staged.filePath),
cleanup: () => staged.cleanup(),
});
if (staged.fileSize === 0) throw new Error('create_flash_task: file is empty');
}
// 申请 fileset。fileName 是卡片/面板上的 fileset 标题;各文件真实名走 commit。
// 未指定 name 时,多文件用「<首文件名>等N个文件」、fileSize 用总和,
// 服务端据此判定 fileset 为多文件,commit 的后续 entry 才会被计入。
const first = items[0];
const { typeCode } = FlashTransferApi.fileTypeCode(first.fileName);
const isMulti = items.length > 1;
const filesetName = name?.trim()
|| (isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName);
const totalSize = items.reduce((s, it) => s + it.fileSize, 0);
const apply = await ApplyFileset.invoke(this.ctx, {
fileName: filesetName, origName: filesetName,
fileSize: totalSize, typeCode, uploader,
});
const filesetUuid = apply.filesetUuid;
if (!filesetUuid) throw new Error('apply fileset failed: missing uuid');
// 一次性 commit 所有文件元数据(f4 repeated,每条 f6=序号)
const commitEntries = items.map((it) => ({
fileUuid: it.fileUuid, fileName: it.fileName, origName: it.fileName,
fileSize: it.fileSize, formatCode: it.formatCode, fileIndex: it.fileIndex,
}));
await CommitFile.invoke(this.ctx, { filesetUuid, entries: commitEntries });
await CompleteFileset.invoke(this.ctx, { filesetUuid });
// 两阶段上传:先全部 prepare+apply 注册 fileId,再全部 sliceupload 落盘。
const prepared: { it: StagedFlashItem; rkey: string; sha1StateV: Uint8Array[]; sliceCount: number }[] = [];
for (const it of items) {
const p = await this.prepareAndApply(filesetUuid, it);
if (p) prepared.push({ it, ...p });
}
for (const p of prepared) {
await assertUnchanged(p.it.filePath, p.it.guardStat);
await this.sliceuploadFile(
p.it.filePath, p.it.fileSize, p.rkey, p.sha1StateV, p.sliceCount, p.it.fileName,
);
}
// fileset 级缩略图(序号在主文件之后递增),主文件下载入口需要缩略图关联
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'png', items.length + 1);
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'jpg', items.length + 2);
await SetFilesetStatus.invoke(this.ctx, { filesetUuid });
return { filesetId: filesetUuid };
} finally {
await Promise.all(items.map((it) => it.cleanup()));
}
// 申请 fileset。多文件时 fileName 用「<首文件名>等N个文件」、fileSize 用总和,
// 服务端据此判定 fileset 为多文件,commit 的后续 entry 才会被计入。
const first = items[0];
const { typeCode } = FlashTransferApi.fileTypeCode(first.fileName);
const isMulti = items.length > 1;
const filesetName = isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName;
const totalSize = items.reduce((s, it) => s + it.bytes.length, 0);
const apply = await ApplyFileset.invoke(this.ctx, {
fileName: filesetName, origName: filesetName,
fileSize: totalSize, typeCode, uploader,
});
const filesetUuid = apply.filesetUuid;
if (!filesetUuid) throw new Error('apply fileset failed: missing uuid');
// 一次性 commit 所有文件元数据(f4 repeated,每条 f6=序号)
const commitEntries = items.map((it) => ({
fileUuid: it.fileUuid, fileName: it.fileName, origName: it.fileName,
fileSize: it.bytes.length, formatCode: it.formatCode, fileIndex: it.fileIndex,
}));
await CommitFile.invoke(this.ctx, { filesetUuid, entries: commitEntries });
await CompleteFileset.invoke(this.ctx, { filesetUuid });
// 两阶段上传:先全部 prepare+apply 注册 fileId,再全部 sliceupload 落盘。
const prepared: { it: typeof items[0]; rkey: string; sha1StateV: Uint8Array[]; sliceCount: number }[] = [];
for (const it of items) {
const p = await this.prepareAndApply(filesetUuid, it.bytes, it.fileName, it.fileUuid, it.fileIndex, it.formatCode);
if (p) prepared.push({ it, ...p });
}
for (const p of prepared) {
await this.sliceuploadFile(p.it.bytes, p.rkey, p.sha1StateV, p.sliceCount, p.it.fileName);
}
// fileset 级缩略图(序号在主文件之后递增),主文件下载入口需要缩略图关联
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'png', items.length + 1);
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'jpg', items.length + 2);
await SetFilesetStatus.invoke(this.ctx, { filesetUuid });
return { filesetId: filesetUuid };
}
/**
* 阶段1:prepare(拿 rkey)+ apply(注册 fileId)。返回 sliceupload 所需的 rkey/sha1state。
* 秒传(rkey=null)返回 null,调用方跳过 sliceupload。
* 阶段1:流式哈希 + prepare(拿 rkey)+ apply(注册 fileId)。
* 秒传时 prepare 不回 rkey,仍必须 apply,否则 fileset 会一直停在等待上传;
* 返回 null 只表示调用方跳过 sliceupload。
*/
private async prepareAndApply(
filesetUuid: string, bytes: Uint8Array, fileName: string, fileUuid: string, fileIndex: number, formatCode: number,
filesetUuid: string, it: StagedFlashItem,
): Promise<{ rkey: string; sha1StateV: Uint8Array[]; sliceCount: number } | null> {
const fileSize = bytes.length;
const hashes = computeHashes(bytes);
const SLICE_SIZE = 1024 * 1024;
const sliceCount = Math.ceil(fileSize / SLICE_SIZE);
const sha1StateV = computeSha1StateV(bytes, sliceCount, SLICE_SIZE);
const hashes = await hashFlashFileStreaming(it.filePath);
await assertUnchanged(it.filePath, it.guardStat);
const rkey = await PrepareUpload.invoke(this.ctx, {
filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex, fileIndex, formatCode,
filesetUuid, fileUuid: it.fileUuid, fileName: it.fileName, fileSize: it.fileSize,
sha1: hashes.sha1Hex, fileIndex: it.fileIndex, formatCode: it.formatCode,
});
if (rkey === null) return null; // 秒传
const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize);
const fileId = FlashTransferApi.buildFileId(hashes.sha1, it.fileSize);
await ApplyUpload.invoke(this.ctx, {
filesetUuid, fileUuid, fileId, fileName, fileSize,
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex, formatCode,
filesetUuid, fileUuid: it.fileUuid, fileId, fileName: it.fileName, fileSize: it.fileSize,
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex: it.fileIndex, formatCode: it.formatCode,
});
return { rkey, sha1StateV, sliceCount };
if (rkey === null) return null;
return { rkey, sha1StateV: hashes.sha1StateV, sliceCount: hashes.sliceCount };
}
/**
* 阶段2:sliceupload 分片上传(所有文件 prepare+apply 完成后调用)。
* 阶段2:从磁盘按 1 MiB 切片 POST sliceupload(所有文件 prepare+apply 完成后调用)。
*/
private async sliceuploadFile(
bytes: Uint8Array, rkey: string, sha1StateV: Uint8Array[], sliceCount: number, fileName: string,
filePath: string, fileSize: number, rkey: string,
sha1StateV: Uint8Array[], sliceCount: number, fileName: string,
): Promise<void> {
const fileSize = bytes.length;
const SLICE_SIZE = 1024 * 1024;
for (let i = 0; i < sliceCount; i++) {
const start = i * SLICE_SIZE;
const chunk = bytes.subarray(start, Math.min(start + SLICE_SIZE, fileSize));
const chunkLen = chunk.length;
const chunkSha1 = new Uint8Array(createHash('sha1').update(Buffer.from(chunk)).digest());
const body: FlashSliceUploadBody = {
field1: 0,
appid: 14901,
field3: 2,
payload: {
field1: {},
rkey,
start,
end: start + chunkLen - 1,
sha1: chunkSha1,
sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) },
chunk: new Uint8Array(chunk),
},
};
const bodyBytes = protobuf_encode<FlashSliceUploadBody>(body);
await this.postSliceupload(bodyBytes, `${fileName} slice ${i}`);
const src = await FileChunkSource.open(filePath, fileSize);
try {
for (let i = 0; i < sliceCount; i++) {
const start = i * FLASH_SLICE_SIZE;
const chunkLen = Math.min(FLASH_SLICE_SIZE, fileSize - start);
const chunk = await src.read(start, chunkLen);
const chunkSha1 = new Uint8Array(createHash('sha1').update(Buffer.from(chunk)).digest());
const body: FlashSliceUploadBody = {
field1: 0,
appid: 14901,
field3: 2,
payload: {
field1: {},
rkey,
start,
end: start + chunkLen - 1,
sha1: chunkSha1,
sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) },
chunk: new Uint8Array(chunk),
},
};
const bodyBytes = protobuf_encode<FlashSliceUploadBody>(body);
await this.postSliceupload(bodyBytes, `${fileName} slice ${i}`);
}
} finally {
await src.close();
}
}
@@ -541,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));
}
}
+116 -28
View File
@@ -11,28 +11,53 @@ import { SetAdmin } from '@snowluma/protocol/oidb-services/group-admin/set-admin
import { SetGroupName } from '@snowluma/protocol/oidb-services/group-admin/set-group-name';
import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set-group-remark';
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
import { FetchGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/get-group-ext-info';
import {
decodeMemberInvitePolicy,
MEMBER_INVITE_PRIVILEGE_MASK,
mergeMemberInvitePrivilegeFlag,
SetMemberInvitePolicy,
type GroupMemberInvitePolicy,
} from '@snowluma/protocol/oidb-services/group-admin/set-member-invite-policy';
import {
GROUP_HISTORY_VISIBILITY_MASK,
mergeGroupHistoryVisibility,
decodeGroupHistoryVisibility,
SetNewMemberHistoryVisibility,
} from '@snowluma/protocol/oidb-services/group-admin/set-new-member-history-visibility';
import {
decodeGroupMemberPermissions,
GROUP_MEMBER_PERMISSION_MASKS,
mergeGroupMemberPermission,
SetMemberPermission,
type GroupMemberPermission,
} from '@snowluma/protocol/oidb-services/group-admin/set-member-permission';
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
import { GetGroupCategoryTags } from '@snowluma/protocol/oidb-services/group-admin/get-group-category-tags';
import { AddGroupCategoryTag } from '@snowluma/protocol/oidb-services/group-admin/add-group-category-tag';
import { DeleteGroupCategoryTag } from '@snowluma/protocol/oidb-services/group-admin/delete-group-category-tag';
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
import { ModifyGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/modify-group-ext-info';
import { OidbError } from '@snowluma/protocol/oidb-service';
import type { BridgeContext } from '../bridge-context';
/** QQ only accepts this write from the group owner (#411). */
export const MEMBER_PERMISSIONS_OWNER_ONLY =
'only the group owner can change group member permissions';
export type GroupAdminSettings = {
add_type: number;
group_question: string;
group_answer: string;
robot_member_switch: number;
robot_member_examine: number;
member_invite_policy: GroupMemberInvitePolicy;
allow_member_upload_album: boolean;
allow_member_temporary_session: boolean;
allow_member_create_group: boolean;
new_member_history_visible: boolean;
no_finger_open: number;
no_code_finger_open: number;
};
export interface GroupMemberPermissions {
allowMemberUploadAlbum?: boolean;
allowMemberTemporarySession?: boolean;
@@ -47,6 +72,33 @@ export class GroupAdminApi {
return ModifyGroupExtInfo.invoke(this.ctx, { groupId, robotMemberSwitch, robotMemberExamine });
}
async getAdminSettings(groupId: number): Promise<GroupAdminSettings> {
const [detail, robot] = await Promise.all([
FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }),
FetchGroupExtInfo.invoke(this.ctx, { groupId }),
]);
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(`unable to read group admin settings for group ${groupId}`);
}
const privilegeFlag = results.privilegeFlag ?? 0;
const permissions = decodeGroupMemberPermissions(privilegeFlag);
return {
add_type: results.addType ?? 0,
group_question: results.question ?? '',
group_answer: results.answer ?? '',
robot_member_switch: robot.robotMemberSwitch,
robot_member_examine: robot.robotMemberExamine,
member_invite_policy: decodeMemberInvitePolicy(privilegeFlag),
allow_member_upload_album: permissions.allowMemberUploadAlbum,
allow_member_temporary_session: permissions.allowMemberTemporarySession,
allow_member_create_group: permissions.allowMemberCreateGroup,
new_member_history_visible: decodeGroupHistoryVisibility(results.groupFlagExt4 ?? 0),
no_finger_open: results.noFingerOpen ?? 0,
no_code_finger_open: results.noCodeFingerOpen ?? 0,
};
}
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
}
@@ -55,14 +107,31 @@ export class GroupAdminApi {
return MuteAll.invoke(this.ctx, { groupId, enable });
}
setAddOption(groupId: number, addType: number): Promise<void> {
return SetAddOption.invoke(this.ctx, { groupId, addType });
setAddOption(
groupId: number,
addType: number,
groupQuestion?: string,
groupAnswer?: string,
): Promise<void> {
return SetAddOption.invoke(this.ctx, { groupId, addType, groupQuestion, groupAnswer });
}
setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise<void> {
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
}
listCategoryTags(groupClass: number): Promise<{ tags: { id: number; name: string; type: number }[] }> {
return GetGroupCategoryTags.invoke(this.ctx, { groupClass });
}
addCategoryTag(groupClass: number, name: string): Promise<void> {
return AddGroupCategoryTag.invoke(this.ctx, { groupClass, name });
}
removeCategoryTag(groupClass: number, name: string): Promise<void> {
return DeleteGroupCategoryTag.invoke(this.ctx, { groupClass, name });
}
async setMemberInvitePolicy(groupId: number, policy: GroupMemberInvitePolicy): Promise<void> {
const currentPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
groupId,
@@ -89,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 privilegeFlag = detail.groupInfo?.results?.privilegeFlag;
if (typeof privilegeFlag !== 'number') {
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(`unable to read ${setting} ${phase} for group ${groupId}`);
}
return privilegeFlag;
return {
privilegeFlag: results.privilegeFlag ?? 0,
ownerUid: results.ownerUid,
};
}
async setMemberPermissions(groupId: number, permissions: GroupMemberPermissions): Promise<void> {
@@ -107,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]);
}
@@ -137,36 +230,31 @@ export class GroupAdminApi {
}
async setNewMemberHistoryVisibility(groupId: number, visible: boolean): Promise<void> {
const currentGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'before update');
const expectedGroupFlagExt4 = mergeGroupHistoryVisibility(currentGroupFlagExt4, visible);
await SetNewMemberHistoryVisibility.invoke(this.ctx, {
groupId,
currentGroupFlagExt4,
visible,
});
await SetNewMemberHistoryVisibility.invoke(this.ctx, { groupId, visible });
const actualGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'after update');
const mask = BigInt(GROUP_HISTORY_VISIBILITY_MASK);
if ((BigInt(actualGroupFlagExt4) & mask) !== (BigInt(expectedGroupFlagExt4) & mask)) {
if (decodeGroupHistoryVisibility(actualGroupFlagExt4) !== visible) {
throw new Error(`new-member history visibility was not applied for group ${groupId}`);
}
}
private async fetchGroupFlagExt4(groupId: number, phase: string): Promise<number> {
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
const groupFlagExt4 = detail.groupInfo?.results?.groupFlagExt4;
if (typeof groupFlagExt4 !== 'number') {
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(`unable to read new-member history visibility ${phase} for group ${groupId}`);
}
return groupFlagExt4;
return results.groupFlagExt4 ?? 0;
}
setAddRequest(
groupId: number, sequence: number, eventType: number,
approve: boolean, reason = '', filtered = false,
operateTransInfo?: Uint8Array,
): Promise<void> {
return SetAddRequest.invoke(this.ctx, { groupId, sequence, eventType, approve, reason, filtered });
return SetAddRequest.invoke(this.ctx, {
groupId, sequence, eventType, approve, reason, filtered, operateTransInfo,
});
}
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
+322 -48
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) {
@@ -435,6 +450,7 @@ export class GroupAlbumApi {
}
async delete(groupId: number, albumId: string, lloc: string): Promise<{ success: true }> {
const target = await this.resolveDeleteTarget(groupId, albumId, lloc);
const uin = this.ctx.identity.uin;
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
@@ -445,7 +461,8 @@ export class GroupAlbumApi {
body: {
groupId: groupId.toString(),
albumId,
lloc,
mediaIds: [target.mediaId],
...(target.batchId ? { batchIds: [target.batchId] } : {}),
},
traceId: clientKey,
extMap: [{ key: 'fc-appid', value: '100' }],
@@ -454,7 +471,7 @@ export class GroupAlbumApi {
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
body,
15000,
packetTimeoutMs(),
);
if (!result.success || !result.gotResponse || !result.responseData) {
@@ -472,7 +489,264 @@ export class GroupAlbumApi {
return { success: true };
}
/**
* Official delete uses a photo lloc, or a video's cover lloc plus batch id.
* Callers may pass either an image lloc or a video id; resolve the latter.
*/
private async resolveDeleteTarget(
groupId: number,
albumId: string,
mediaKey: string,
): Promise<{ mediaId: string; batchId?: string }> {
try {
const seenCursors = new Set<string>();
let attachInfo = '';
while (true) {
const page = await this.getMediaList(groupId, albumId, attachInfo);
const hit = findDeleteTarget(page.mediaList, mediaKey);
if (hit) return hit;
const next = page.nextAttachInfo ?? '';
if (!next || seenCursors.has(next)) {
return { mediaId: mediaKey };
}
seenCursors.add(next);
attachInfo = next;
}
} catch (err) {
log.debug(
'resolve album delete target failed, using raw id: group=%d album=%s err=%s',
groupId,
albumId,
err instanceof Error ? err.message : String(err),
);
return { mediaId: mediaKey };
}
}
/**
* Page the album when the caller only has a lloc / video id, so the
* comment can carry the official batch id and media kind.
*/
private async resolveCommentMedia(
groupId: number,
albumId: string,
mediaKey: string,
): Promise<AlbumCommentMediaItem | undefined> {
const seenCursors = new Set<string>();
let attachInfo = '';
while (true) {
const page = await this.getMediaList(groupId, albumId, attachInfo);
const hit = findCommentMedia(page.mediaList, mediaKey);
if (hit) return hit;
const next = page.nextAttachInfo ?? '';
if (!next || seenCursors.has(next)) return undefined;
seenCursors.add(next);
attachInfo = next;
}
}
private async getQunFeedDetail(
groupId: number,
albumId: string,
batchId: bigint,
lloc: string,
): Promise<{ cellCommon: QunFeedCellCommon; ownerUin: string; media?: CommentReqPhotoInfo }> {
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const body = protobuf_encode<GetQunFeedDetailRequest>({
seq: 0,
field2: new Uint8Array(0),
field3: new Uint8Array(0),
data: {
groupId: groupId.toString(),
feedId: '',
commentCount: GET_QUN_FEED_DETAIL_COMMENT_COUNT,
attachInfo: '',
albumId,
batchId: batchId.toString(),
lloc,
},
traceId,
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(GET_QUN_FEED_DETAIL_CMD, body, packetTimeoutMs());
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to fetch album feed');
}
const resp = protobuf_decode<GetQunFeedDetailResponse>(result.responseData);
const resultCode = resp.result ?? 0;
if (resultCode !== 0) {
throw new Error(
`fetch album feed error: retCode ${resultCode}`
+ (resp.errorText ? `, ${resp.errorText}` : ''),
);
}
const feed = resp.data?.feed?.feed;
const cell = feed?.cellCommon;
const feedId = cell?.feedId ?? '';
if (!feedId) {
throw new Error('comment album media error: empty feed');
}
return {
cellCommon: cell ?? { feedId },
ownerUin: feed?.cellUserInfo?.user?.uin ?? '',
media: feed?.cellMedia,
};
}
}
interface AlbumDeleteMediaItem {
image?: { lloc?: string } | null;
video?: { id?: string; cover?: { lloc?: string } | null } | null;
batchId?: string | number;
}
function findDeleteTarget(
mediaList: ReadonlyArray<unknown>,
mediaKey: string,
): { mediaId: string; batchId?: string } | undefined {
for (const raw of mediaList) {
if (!raw || typeof raw !== 'object') continue;
const item = raw as AlbumDeleteMediaItem;
const batchId = item.batchId === undefined || item.batchId === ''
? undefined
: String(item.batchId);
if (item.image?.lloc === mediaKey) {
return { mediaId: mediaKey, batchId };
}
const coverLloc = item.video?.cover?.lloc;
if (item.video?.id === mediaKey || coverLloc === mediaKey) {
return { mediaId: coverLloc || mediaKey, batchId };
}
}
return undefined;
}
interface AlbumCommentMediaItem {
type?: number;
image?: {
name?: string;
sloc?: string;
lloc?: string;
isGif?: boolean;
hasRaw?: boolean;
} | null;
video?: {
id?: string;
cover?: {
name?: string;
sloc?: string;
lloc?: string;
} | null;
} | null;
uploader?: string;
batchId?: string | number | bigint;
}
function optionalBatchId(value: unknown): bigint | undefined {
if (value === undefined || value === null || value === '') return undefined;
try {
const batchId = BigInt(value as string | number | bigint);
return batchId === 0n ? undefined : batchId;
} catch {
return undefined;
}
}
function commentMediaLloc(item: AlbumCommentMediaItem | undefined, lloc: string): string {
if (item?.video?.cover?.lloc) return item.video.cover.lloc;
if (item?.image?.lloc) return item.image.lloc;
return lloc;
}
function mediaInfoForComment(item: AlbumCommentMediaItem | undefined, lloc: string): MediaInfo {
const batchId = optionalBatchId(item?.batchId);
const shared: MediaInfo = {
...(item?.uploader ? { uploader: item.uploader } : {}),
...(batchId !== undefined ? { batchId } : {}),
};
if (item?.video) {
return {
...shared,
type: 1,
video: { cover: { lloc: item.video.cover?.lloc || lloc } },
};
}
return {
...shared,
type: 0,
image: { lloc: item?.image?.lloc || lloc },
};
}
function qunFeedCellId(
groupId: number,
albumId: string,
batchId: string | number | bigint,
lloc?: string,
): string {
const head = `421_1_0_${groupId}|${albumId}|${batchId}`;
if (!lloc) return head;
return `${head}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`;
}
function commentReqHeader(cell: QunFeedCellCommon): CommentReqBodyHeader {
return {
...(cell.time !== undefined ? { time: cell.time } : {}),
...(cell.feedId ? { feedId: cell.feedId } : {}),
};
}
function commentPhotoInfo(
feedMedia: CommentReqPhotoInfo | undefined,
fallback: MediaInfo,
albumId: string,
batchId: bigint,
): CommentReqPhotoInfo {
if (feedMedia?.medias?.length) {
return {
medias: feedMedia.medias,
albumId: feedMedia.albumId || albumId,
batchId: feedMedia.batchId ?? batchId,
};
}
return { medias: [fallback], albumId, batchId };
}
function findCommentMedia(
mediaList: ReadonlyArray<unknown>,
mediaKey: string,
): AlbumCommentMediaItem | undefined {
for (const raw of mediaList) {
if (!raw || typeof raw !== 'object') continue;
const item = raw as AlbumCommentMediaItem;
if (item.image?.lloc === mediaKey) return item;
if (item.video?.id === mediaKey || item.video?.cover?.lloc === mediaKey) return item;
}
return undefined;
}
function commentFromResponse(resp: DoQunCommentResponse): CommentRespData {
const wrapped = resp.comment;
if (!wrapped) return {};
if (wrapped.data?.id) return wrapped.data;
if (wrapped.id) {
return {
id: wrapped.id,
content: wrapped.content,
time: wrapped.time,
clientKey: wrapped.clientKey,
user: wrapped.data?.user,
};
}
return wrapped.data ?? {};
}
export interface GroupAlbumMediaResult {
mediaList: Array<JsonValue & Partial<MediaInfo>>;
nextAttachInfo: string;
+3 -30
View File
@@ -1,4 +1,3 @@
import { toHexUpper } from '@snowluma/common/hex';
import { createLogger } from '@snowluma/common/logger';
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
import { FileChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
@@ -83,11 +82,6 @@ function normalizeDirectory(dir?: string): string {
return dir;
}
function bytesToHexUpper(data: unknown): string {
if (!(data instanceof Uint8Array) || data.length === 0) return '';
return toHexUpper(data);
}
// Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives
// little-endian-packed (byte0 = first dotted octet) and we unpack it the
// same way. Force-unsigned the shift to keep negative ints (high bit set)
@@ -568,9 +562,8 @@ export class GroupFileApi {
groupId, targetDirectory, startIndex, pageSize,
});
if (!list) break;
ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording);
for (const item of list.items ?? []) {
for (const item of list.items) {
const type = toInt(item?.type);
if (type === 1 && item?.fileInfo) {
const file = item.fileInfo;
@@ -627,34 +620,14 @@ export class GroupFileApi {
// ─────────────── url fetch (group / private files) ───────────────
async getUrl(groupId: number, fileId: string, busId = 102): Promise<string> {
const download = await GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId });
ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording);
const dns = (typeof download.downloadDns === 'string' && download.downloadDns)
|| (typeof download.downloadIp === 'string' && download.downloadIp)
|| '';
const hexUrl = bytesToHexUpper(download.downloadUrl);
if (!dns || !hexUrl) {
throw new Error('group file url response invalid');
}
// Keep the same behavior as Lagrange: append file_id after ?fname=
return `https://${dns}/ftn_handler/${hexUrl}/?fname=${fileId}`;
return GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId });
}
async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise<string> {
const bridge = asBridge(this.ctx);
const selfUid = await resolveSelfUid(bridge);
void userId;
const result = await GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash });
const server = typeof result?.server === 'string' ? result.server : '';
const port = toInt(result?.port);
const url = typeof result?.url === 'string' ? result.url : '';
if (!server || !port || !url) {
throw new Error('private file url response invalid');
}
return `http://${server}:${port}${url}&isthumb=0`;
return GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash });
}
// ─────────────── delete / move ───────────────
+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}`);
// 新顺序:目标挪到第一,其余按原顺序
-13
View File
@@ -11,19 +11,6 @@ export function toInt(value: unknown): number {
return 0;
}
/**
* Standard OIDB response check: throw a typed Error if retCode != 0.
* Prefers `wording` over `msg` for the human-facing message, falling
* back to a generic string. All themed action modules use this for
* their OIDB error-path uniformity.
*/
export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown, wording: unknown): void {
const retCode = toInt(code);
if (retCode === 0) return;
const text = (typeof wording === 'string' && wording) || (typeof msg === 'string' && msg) || 'unknown error';
throw new Error(`${operation} failed: code=${retCode} msg=${text}`);
}
// The bot's-own-UID resolver is the single source of truth in @snowluma/protocol
// (a Bridge satisfies its BridgeContext slice). Re-exported here so the existing
// `resolveSelfUid(bridge)` call sites in this package keep importing from shared.
+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;
+162 -22
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,27 +48,28 @@ export class Bridge implements BridgeInterface {
// Per-account dedup for QQ NT's already-deduped system pushes (#137).
private readonly sysMsgDedup_ = new SysMsgDedup();
private onlineClients_: readonly Readonly<OnlineDeviceInfo>[] | null = null;
private disposed_ = false;
private rosterWarmupStarted_ = false;
private rosterWarmupSettled_ = false;
private rosterWarmupResult_: RosterWarmupResult | null = null;
private readonly rosterWarmupWaiters_: Array<(result: RosterWarmupResult) => void> = [];
constructor(identity: IdentityService) {
this.identity = identity;
this.apis = buildApiHub(this);
this.identity.setFetcher({
fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin),
fetchProfileByUid: (uid) => this.apis.contacts.fetchUserProfileByUid(uid),
fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid),
});
this.pipeline = new IncomingPacketPipeline({
identity: this.identity,
events: this.events,
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
resolveStrangerProfile: async (uid) => {
try {
const p = await this.apis.contacts.fetchUserProfileByUid(uid);
if (p.uin <= 0) return null;
return { uin: p.uin, nickname: p.nickname };
} catch {
return null;
}
fetchGroupList: async () => {
await this.apis.contacts.fetchGroupList();
},
fetchGroupMemberList: async (groupId) => {
await this.apis.contacts.fetchGroupMemberList(groupId);
},
resolveGroupJoinRequest: async (groupId, uid, subType) => {
const [main, filtered] = await Promise.allSettled([
@@ -88,10 +91,14 @@ export class Bridge implements BridgeInterface {
...(main.status === 'fulfilled' ? main.value : []),
...(filtered.status === 'fulfilled' ? filtered.value : []),
];
return requests.find(r => {
const matches = requests.filter((r) => {
if (r.groupId !== groupId) return false;
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
}) ?? null;
});
if (subType === 'invite') {
return matches.find((r) => r.notifyType === 1) ?? matches[0] ?? null;
}
return matches.find((r) => r.notifyType === 7) ?? matches[0] ?? null;
},
resolveGroupInviteCardSequence: async (groupId) => {
const deadline = Date.now() + 1_000;
@@ -102,6 +109,9 @@ export class Bridge implements BridgeInterface {
} while (Date.now() < deadline);
return null;
},
rememberGroupInviteCardSequence: (groupUin, sequence) => {
this.apis.contacts.rememberGroupInviteCardSequence(groupUin, sequence);
},
});
this.pipeline.registerCmd(
MSG_PUSH_CMD,
@@ -122,6 +132,8 @@ export class Bridge implements BridgeInterface {
}
dispose(): void {
this.disposed_ = true;
this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false });
this.pids_.clear();
this.receiveHealthByPid_.clear();
this.packetClientsByPid_.clear();
@@ -146,6 +158,7 @@ export class Bridge implements BridgeInterface {
const pid = pids.length > 0 ? pids[pids.length - 1]! : null;
this.packetClientPid_ = pid;
if (pid !== null) this.packetClientsByPid_.set(pid, client);
this.maybeStartRosterWarmup();
}
registerCmd(cmd: string, parser: CmdParser): void {
@@ -185,6 +198,7 @@ export class Bridge implements BridgeInterface {
previousPid,
);
}
this.maybeStartRosterWarmup();
}
/** @internal BridgeManager lookup used when an incoming packet is the first
@@ -241,18 +255,25 @@ export class Bridge implements BridgeInterface {
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null {
return this.onlineClients_;
}
whenRosterWarmupSettled(): Promise<RosterWarmupResult> {
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
return Promise.resolve(this.rosterWarmupResult_);
}
this.maybeStartRosterWarmup();
return new Promise((resolve) => {
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
resolve(this.rosterWarmupResult_);
return;
}
this.rosterWarmupWaiters_.push(resolve);
});
}
onPacket(pkt: PacketInfo): Promise<void> {
return this.pipeline.process(pkt);
}
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
if (refreshGroupList) {
try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ }
}
if (!this.identity.findGroup(groupId)) return false;
await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
}
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) return;
if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) {
@@ -276,7 +297,7 @@ export class Bridge implements BridgeInterface {
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
return this.msgRandom_ & 0x7FFFFFFF;
}
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
if (!this.packetClient_) {
return runWithTraceRequest(() => {
const startedAt = Date.now();
@@ -362,6 +383,125 @@ export class Bridge implements BridgeInterface {
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return this.identity.resolveUid(uin, groupId);
}
private maybeStartRosterWarmup(): void {
if (this.disposed_ || this.rosterWarmupStarted_ || !this.packetClient_) return;
this.rosterWarmupStarted_ = true;
if (!this.identity.nickname) this.identity.nickname = this.identity.uin;
void this.runRosterWarmup().then(
(result) => this.settleRosterWarmup(this.disposed_ ? { friendsLoaded: false, groupsLoaded: false } : result),
(err) => {
log.warn(
'roster warmup failed: uin=%s err=%s',
this.identity.uin,
err instanceof Error ? (err.stack ?? err.message) : String(err),
);
this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false });
},
);
}
private settleRosterWarmup(result: RosterWarmupResult): void {
if (this.rosterWarmupSettled_) return;
this.rosterWarmupSettled_ = true;
this.rosterWarmupResult_ = result;
const waiters = this.rosterWarmupWaiters_.splice(0);
for (const resolve of waiters) resolve(result);
}
private stillOpen(): boolean {
return !this.disposed_;
}
private async runRosterWarmup(): Promise<RosterWarmupResult> {
const uin = this.identity.uin;
const selfUin = parseInt(uin, 10) || 0;
let selfResolved = false;
let friendsLoaded = false;
try {
const friends = await this.apis.contacts.fetchFriendList();
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
friendsLoaded = true;
log.info('friends loaded: UIN=%s count=%d', uin, friends.length);
for (const friend of friends) {
if (friend.uin === selfUin) {
this.identity.setSelfProfile({
uin: friend.uin, uid: friend.uid,
nickname: friend.nickname || uin,
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
qidianMasterFlag: 0, qidianCrewFlag: 0, qidianCrewFlag2: 0,
});
this.identity.nickname = friend.nickname || uin;
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, friend.uid, friend.nickname ?? '');
selfResolved = true;
break;
}
}
} catch (e) {
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
log.warn('failed to load friends for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
}
if (!selfResolved && selfUin > 0 && this.stillOpen()) {
try {
const profile = await this.apis.contacts.fetchUserProfile(selfUin);
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
this.identity.setSelfProfile(profile);
this.identity.nickname = profile.nickname || uin;
log.debug('self info via profile: UIN=%s uid=%s nickname=%s',
uin, profile.uid, profile.nickname);
} catch (e) {
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
log.warn('failed to load self profile for UIN %s: %s',
uin, e instanceof Error ? e.message : String(e));
}
}
let groups: { groupId: number }[] = [];
let groupsLoaded = false;
try {
groups = await this.apis.contacts.fetchGroupList();
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
groupsLoaded = true;
log.info('groups loaded: UIN=%s count=%d', uin, groups.length);
} catch (e) {
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
log.warn('failed to load groups for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
}
let loadedGroupCount = 0;
let loadedMemberCount = 0;
let failedGroupCount = 0;
for (const group of groups) {
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
try {
const members = await this.apis.contacts.fetchGroupMemberList(group.groupId);
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
loadedGroupCount += 1;
loadedMemberCount += members.length;
if (VERBOSE_WARMUP) {
log.debug('members loaded: group=%d count=%d', group.groupId, members.length);
}
} catch (e) {
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
failedGroupCount += 1;
log.warn('failed to load members for group %d: %s', group.groupId, e instanceof Error ? e.message : String(e));
}
}
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
log.info(
'member warmup completed: UIN=%s groups=%d/%d members=%d failed=%d',
uin,
loadedGroupCount,
groups.length,
loadedMemberCount,
failedGroupCount,
);
return { friendsLoaded, groupsLoaded };
}
}
export interface SendMessageReceipt {
messageId: number;
+14 -3
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,14 +120,23 @@ async function main() {
exitCode = 1;
log.error('notification shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
try { hookManager.dispose(); } catch (error) {
try {
if (stopWebUI) await stopWebUI();
} catch (error) {
exitCode = 1;
log.error('hook shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
log.error('WebUI shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
// Observers go deaf before Hook teardown. Hook dispose then emits the
// same disconnected → PID detach → Bridge closed path as a live drop;
// those closed edges must not look like a runtime offline.
try { stateWiring.dispose(); } catch (error) {
exitCode = 1;
log.error('state wiring shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
try { hookManager.dispose(); } catch (error) {
exitCode = 1;
log.error('hook shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
await closeLogger();
process.exit(exitCode);
};
+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 } : {}),
};
}
+89 -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;
}
@@ -74,6 +91,7 @@ export class NotificationManager {
private readonly nicknames = new Map<string, string>();
private readonly history: DeliveryRecord[] = [];
private readonly historyLimit: number;
private disposed = false;
constructor(deps: NotificationManagerDeps) {
this.deps = deps;
@@ -88,11 +106,13 @@ export class NotificationManager {
}
handleOnline(uin: string, nickname?: string): void {
if (this.disposed) return;
if (nickname) this.nicknames.set(uin, nickname);
this.apply(uin, this.machine.onOnline(uin));
}
handleOffline(uin: string, nickname?: string): void {
if (this.disposed) return;
if (nickname) this.nicknames.set(uin, nickname);
this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds()));
}
@@ -137,7 +157,7 @@ export class NotificationManager {
}
}
/** Render + POST a transition to every opted-in, enabled channel and record
/** Render + deliver a transition to every opted-in, enabled channel and record
* the outcome. Never throws (a bad channel can't break the others). */
async notify(uin: string, event: NotificationEvent): Promise<void> {
let channels: NotificationChannel[];
@@ -159,14 +179,7 @@ export class NotificationManager {
};
for (const ch of channels) {
const body = renderTemplate(ch.bodyTemplate, vars);
let result: PostResult;
try {
result = await this.deps.post(ch.url, body);
} catch (err) {
// The injected post is contracted not to throw, but guard anyway.
result = { ok: false, error: errMsg(err) };
}
const result = await this.deliver(ch, vars);
this.record({
time: this.deps.now(),
uin,
@@ -182,9 +195,33 @@ export class NotificationManager {
}
}
private async deliver(ch: NotificationChannel, vars: Record<string, string>): Promise<PostResult> {
try {
if (isEmailChannel(ch)) {
const send = this.deps.sendMail;
if (!send) return { ok: false, error: 'email delivery is not configured' };
return await send({
host: ch.smtpHost,
port: ch.smtpPort,
secure: ch.smtpSecure,
user: ch.smtpUser,
pass: ch.smtpPass,
from: ch.from,
to: ch.to,
subject: renderTemplate(ch.subjectTemplate, vars),
text: renderTemplate(ch.bodyTemplate, vars),
});
}
return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers);
} catch (err) {
// Injected collaborators are contracted not to throw, but guard anyway.
return { ok: false, error: errMsg(err) };
}
}
/** Send a one-off test to a single channel by id — ignores `enabled` and the
* per-UIN opt-in (you test a channel before wiring it up), with sample
* variables. Reuses the real render+POST path; NOT recorded to history.
* variables. Reuses the real render+deliver path; NOT recorded to history.
* `found:false` means the channel id is unknown. */
async testSend(channelId: string): Promise<PostResult & { found: boolean }> {
let channel: NotificationChannel | undefined;
@@ -194,17 +231,13 @@ export class NotificationManager {
return { ok: false, found: false, error: errMsg(err) };
}
if (!channel) return { ok: false, found: false };
const body = renderTemplate(channel.bodyTemplate, {
const vars = {
uin: '10000',
nickname: '测试账号',
event: 'offline',
event: 'offline' as const,
time: new Date(this.deps.now()).toISOString(),
});
try {
return { ...(await this.deps.post(channel.url, body)), found: true };
} catch (err) {
return { ok: false, found: true, error: errMsg(err) };
}
};
return { ...(await this.deliver(channel, vars)), found: true };
}
private record(rec: DeliveryRecord): void {
@@ -221,6 +254,8 @@ export class NotificationManager {
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
for (const timer of this.timers.values()) clearTimeout(timer);
this.timers.clear();
}
@@ -228,12 +263,14 @@ export class NotificationManager {
/** Default outbound POST: a single attempt with a timeout, JSON content-type
* (the common case for 钉钉/Discord/飞书). Never throws. */
export function createDefaultPost(timeoutMs = DEFAULT_POST_TIMEOUT_MS): NotificationManagerDeps['post'] {
return async (url, body) => {
export function createDefaultPost(
timeoutMs = positiveIntEnv('SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS', DEFAULT_POST_TIMEOUT_MS),
): NotificationManagerDeps['post'] {
return async (url, body, headers) => {
try {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: { 'Content-Type': 'application/json', ...headers },
body,
signal: AbortSignal.timeout(timeoutMs),
});
@@ -244,12 +281,37 @@ export function createDefaultPost(timeoutMs = DEFAULT_POST_TIMEOUT_MS): Notifica
};
}
const DEFAULT_SMTP_TIMEOUT_MS = 15_000;
/** Default SMTP send. Never throws. */
export function createDefaultSendMail(timeoutMs = DEFAULT_SMTP_TIMEOUT_MS): NonNullable<NotificationManagerDeps['sendMail']> {
return async (mail) => {
try {
await sendSmtpMail({
host: mail.host,
port: mail.port,
secure: mail.secure,
user: mail.user,
pass: mail.pass,
from: mail.from,
to: parseRecipients(mail.to),
subject: mail.subject,
body: mail.text,
}, { timeoutMs });
return { ok: true };
} catch (err) {
return { ok: false, error: formatSmtpError(err, mail.host, mail.port) };
}
};
}
/** The real, fully-wired singleton. */
export function createNotificationManager(): NotificationManager {
return new NotificationManager({
loadConfig: loadNotificationsConfig,
loadChannelIds: (uin) => loadOneBotConfig(uin).notifications?.channelIds ?? [],
post: createDefaultPost(),
sendMail: createDefaultSendMail(),
now: () => Date.now(),
});
}
+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');
}
+74 -10
View File
@@ -2,6 +2,12 @@ import { createLogger } from '@snowluma/common/logger';
import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
import fs from 'fs';
import path from 'path';
import {
parseTotpStateLenient,
prepareTotpStateForRestore,
rewrapTotpSecret,
type TotpPersistedState,
} from './totp';
const log = createLogger('WebUI.Auth');
@@ -32,6 +38,7 @@ export interface WebuiAuthState {
mustChangePassword: boolean;
generatedAt: string;
updatedAt: string;
totp?: TotpPersistedState;
}
export interface PasswordRule {
@@ -91,24 +98,43 @@ export function prepareWebuiAuthStateForRestore(value: unknown): WebuiAuthState
if (typeof v.updatedAt !== 'string' || !Number.isFinite(Date.parse(v.updatedAt))) {
throw new Error('updatedAt must be a valid timestamp');
}
const allowed = new Set(['passwordHash', 'passwordSalt', 'mustChangePassword', 'generatedAt', 'updatedAt']);
const allowed = new Set(['passwordHash', 'passwordSalt', 'mustChangePassword', 'generatedAt', 'updatedAt', 'totp']);
const unknown = Object.keys(v).find((key) => !allowed.has(key));
if (unknown) throw new Error(`unknown field $.${unknown}`);
return {
const state: WebuiAuthState = {
passwordHash: v.passwordHash,
passwordSalt: v.passwordSalt,
mustChangePassword: v.mustChangePassword,
generatedAt: v.generatedAt,
updatedAt: v.updatedAt,
};
if (!Object.prototype.hasOwnProperty.call(v, 'totp') || v.totp === undefined) {
return state;
}
state.totp = prepareTotpStateForRestore(v.totp);
return state;
}
function isValidState(value: unknown): value is WebuiAuthState {
function parseLiveAuthState(value: unknown): WebuiAuthState | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
const v = value as Record<string, unknown>;
const totpValue = v.totp;
const withoutTotp = { ...v };
delete withoutTotp.totp;
try {
prepareWebuiAuthStateForRestore(value);
return true;
const state = prepareWebuiAuthStateForRestore(
Object.prototype.hasOwnProperty.call(v, 'totp')
? withoutTotp
: value,
);
const totp = parseTotpStateLenient(totpValue);
if (Object.prototype.hasOwnProperty.call(v, 'totp') && totpValue !== undefined && !totp) {
log.warn('webui.json totp field is invalid and will be ignored; password credentials are unchanged');
}
if (totp) state.totp = totp;
return state;
} catch {
return false;
return null;
}
}
@@ -177,8 +203,9 @@ export class WebuiAuth {
try {
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
const parsed = JSON.parse(raw) as unknown;
if (isValidState(parsed)) {
if (parsed.mustChangePassword) {
const live = parseLiveAuthState(parsed);
if (live) {
if (live.mustChangePassword) {
// Previous start generated a bootstrap password but the operator
// never completed the forced-change flow. The plaintext is gone
// (only the hash is on disk, and the log line from last run may
@@ -189,7 +216,7 @@ export class WebuiAuth {
log.warn('previous bootstrap password was never rotated; regenerated a new one');
return new WebuiAuth(state, initialPassword, false);
}
return new WebuiAuth(parsed, null, false);
return new WebuiAuth(live, null, false);
}
log.error('webui.json schema invalid; backing up and regenerating credentials');
backupCorruptConfig();
@@ -257,13 +284,20 @@ export class WebuiAuth {
}
}
setPassword(newPassword: string): void {
setPassword(newPassword: string, currentPassword?: string): void {
if (this.devMode) {
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改');
}
if (!isStrongPassword(newPassword)) {
throw new Error('密码不符合强度要求');
}
let totp = this.state.totp;
if (totp) {
if (typeof currentPassword !== 'string' || currentPassword.length === 0) {
throw new Error('修改密码需要当前密码以重新保护 2FA 密钥');
}
totp = rewrapTotpSecret(currentPassword, newPassword, totp);
}
const salt = randomBytes(16);
const hash = hashPassword(newPassword, salt);
const next: WebuiAuthState = {
@@ -272,8 +306,38 @@ export class WebuiAuth {
mustChangePassword: false,
generatedAt: this.state.generatedAt,
updatedAt: new Date().toISOString(),
...(totp ? { totp } : {}),
};
atomicWrite(next);
this.state = next;
}
totpEnabled(): boolean {
return this.state.totp !== undefined;
}
totpStatus(): { enabled: false } | { enabled: true; remainingRecoveryCodes: number; label: string } {
const totp = this.state.totp;
if (!totp) return { enabled: false };
return {
enabled: true,
remainingRecoveryCodes: totp.recoveryCodeHashes.length,
label: totp.label,
};
}
totpState(): TotpPersistedState | undefined {
return this.state.totp;
}
persistTotp(totp: TotpPersistedState | undefined): void {
if (this.devMode) {
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用 2FA');
}
const next: WebuiAuthState = { ...this.state, updatedAt: new Date().toISOString() };
if (totp) next.totp = totp;
else delete next.totp;
atomicWrite(next);
this.state = next;
}
}
+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 };
}
+10 -3
View File
@@ -2,6 +2,13 @@ import { assessAccessToken } from '@snowluma/common/access-token';
import type { OneBotConfig } from '@snowluma/onebot/types';
import { isLoopbackClientIp } from './client-ip';
function isLoopbackBindHost(host: string | undefined): boolean {
const value = host?.trim().toLowerCase().replace(/^\[|\]$/gu, '').replace(/\.$/u, '') ?? '';
if (!value) return false;
if (value === 'localhost' || value.endsWith('.localhost')) return true;
return isLoopbackClientIp(value);
}
export class OneBotAccessTokenPolicyError extends Error {
constructor(message: string) {
super(message);
@@ -40,7 +47,7 @@ export function validateOneBotAccessTokenChanges(
next: OneBotConfig,
options: OneBotAccessTokenPolicyOptions,
): void {
const allowEmpty = isLoopbackClientIp(options.clientIp);
const allowEmptyFromClient = isLoopbackClientIp(options.clientIp);
for (const kind of INBOUND_KINDS) {
const previousList = previous?.networks[kind] ?? [];
const nextList = next.networks[kind];
@@ -50,9 +57,9 @@ export function validateOneBotAccessTokenChanges(
if (sameTokenAtPreviousIdentity(previousList, nextList, adapter.name, token, index)) continue;
if (!token) {
if (!allowEmpty) {
if (!allowEmptyFromClient && !isLoopbackBindHost(adapter.host)) {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”仅能从本机页面保存无令牌配置;请生成令牌后重试。`,
`节点“${adapter.name}”未绑定本机地址,远程保存必须填写令牌;请生成令牌或将主机改为 127.0.0.1。`,
);
}
continue;
+254 -23
View File
@@ -39,6 +39,13 @@ import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth';
import { completeWebuiLogin, invalidateOtherSessions } from './webui-login';
import {
beginTotpEnrollment,
confirmTotpEnrollment,
decideSecondFactorLogin,
regenerateRecoveryCodes,
} from './totp';
import {
EULA_ACCEPT_ENV,
getAgreementsPayload,
@@ -49,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';
@@ -103,10 +111,18 @@ interface SessionInfo {
const sessionTokens = new Map<string, SessionInfo>();
const loginAttempts = new Map<string, { count: number; resetAt: number }>();
const totpEnrollments = new Map<string, {
secret: string;
issuer: string;
accountName: string;
expiresAt: number;
}>();
const LOGIN_MAX_ATTEMPTS = 5;
const LOGIN_LOCKOUT_MS = 15 * 60 * 1000;
const TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
const TOTP_ENROLL_TTL_MS = 10 * 60 * 1000;
const DEFAULT_TOTP_ISSUER = 'SnowLuma';
const AVATAR_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const AVATAR_BROWSER_CACHE_SECONDS = 30 * 24 * 60 * 60;
@@ -229,6 +245,21 @@ function purgeExpiredTokens() {
for (const [ip, attempt] of loginAttempts) {
if (now > attempt.resetAt) loginAttempts.delete(ip);
}
for (const [token, enrollment] of totpEnrollments) {
if (now > enrollment.expiresAt) totpEnrollments.delete(token);
}
}
function sanitizeTotpLabelPart(value: unknown, fallback: string): string {
if (typeof value !== 'string') return fallback;
const trimmed = value.replace(/[\r\n\t]/g, '').trim();
if (!trimmed) return fallback;
return trimmed.slice(0, 64);
}
function defaultTotpAccountName(): string {
const host = os.hostname().trim();
return host || 'admin';
}
@@ -440,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).
@@ -475,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,
@@ -632,27 +675,42 @@ export async function initWebUI(
return c.json({ success: false, message: `登录尝试过多,请 ${waitSec} 秒后重试` }, 429);
}
let body: { password?: unknown };
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const password = typeof body.password === 'string' ? body.password : '';
if (!auth.verify(password)) {
const result = completeWebuiLogin(auth, body, now);
if (result.kind === 'bad-request') {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
if (result.kind === 'bad-password' || result.kind === 'bad-second-factor') {
const current = loginAttempts.get(ip) ?? { count: 0, resetAt: now + LOGIN_LOCKOUT_MS };
current.count += 1;
if (current.count === 1) current.resetAt = now + LOGIN_LOCKOUT_MS;
loginAttempts.set(ip, current);
return c.json({ success: false, message: '密码错误' }, 401);
const message = result.kind === 'bad-second-factor' ? '验证码不正确' : '密码错误';
return c.json({ success: false, message }, 401);
}
if (result.kind === 'needs-totp') {
return c.json({ success: false, needsTotp: true });
}
loginAttempts.delete(ip);
if (result.totpState) {
try {
auth.persistTotp(result.totpState);
} catch (err) {
log.warn('persist totp after login failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '登录失败' }, 500);
}
}
const token = randomBytes(32).toString('hex');
const mustChange = auth.mustChangePassword();
sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange });
sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: result.mustChangePassword });
setAvatarSessionCookie(c, token, listener.tlsEnabled === true);
return c.json({ success: true, token, mustChangePassword: mustChange });
return c.json({ success: true, token, mustChangePassword: result.mustChangePassword });
});
app.post('/api/logout', (c) => {
@@ -703,7 +761,7 @@ export async function initWebUI(
return c.json({ success: false, message: '新密码不得与旧密码相同' }, 400);
}
try {
auth.setPassword(newPassword);
auth.setPassword(newPassword, oldPassword);
} catch (err) {
log.warn('change password failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '密码修改失败' }, 400);
@@ -717,6 +775,167 @@ export async function initWebUI(
return c.json({ success: true, requireRelogin: true });
});
const totpDisabledInDev = () => auth.isDevMode();
app.get('/api/auth/totp', (c) => {
if (totpDisabledInDev()) {
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
}
return c.json(auth.totpStatus());
});
app.post('/api/auth/totp/begin', async (c) => {
if (totpDisabledInDev()) {
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
}
if (auth.totpEnabled()) {
return c.json({ success: false, message: '2FA 已开启' }, 409);
}
const token = c.get('sessionToken' as never) as string;
let body: Record<string, unknown> = {};
try {
const parsed = await c.req.json();
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
body = parsed as Record<string, unknown>;
}
} catch {
body = {};
}
const issuer = sanitizeTotpLabelPart(body.issuer, DEFAULT_TOTP_ISSUER);
const accountName = sanitizeTotpLabelPart(body.accountName, defaultTotpAccountName());
const now = Date.now();
const existing = totpEnrollments.get(token);
const secret = existing && existing.expiresAt > now ? existing.secret : undefined;
const enrollment = beginTotpEnrollment({ issuer, accountName, secret });
totpEnrollments.set(token, {
secret: enrollment.secret,
issuer,
accountName,
expiresAt: now + TOTP_ENROLL_TTL_MS,
});
return c.json({
success: true,
secret: enrollment.secret,
otpauthUrl: enrollment.otpauthUrl,
issuer: enrollment.issuer,
accountName: enrollment.accountName,
});
});
app.post('/api/auth/totp/confirm', async (c) => {
if (totpDisabledInDev()) {
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
}
if (auth.totpEnabled()) {
return c.json({ success: false, message: '2FA 已开启' }, 409);
}
const token = c.get('sessionToken' as never) as string;
let body: { password?: unknown; code?: unknown };
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const password = typeof body.password === 'string' ? body.password : '';
const code = typeof body.code === 'string' ? body.code : '';
if (!auth.verify(password)) {
return c.json({ success: false, message: '当前密码不正确' }, 401);
}
const pending = totpEnrollments.get(token);
if (!pending || pending.expiresAt <= Date.now()) {
totpEnrollments.delete(token);
return c.json({ success: false, message: '请先开始绑定' }, 400);
}
try {
const enabled = confirmTotpEnrollment({
password,
secret: pending.secret,
code,
label: `${pending.issuer} (${pending.accountName})`,
atMs: Date.now(),
});
auth.persistTotp(enabled.state);
totpEnrollments.delete(token);
invalidateOtherSessions(sessionTokens, token);
log.info('webui 2FA enabled; other sessions invalidated');
return c.json({ success: true, recoveryCodes: enabled.recoveryCodes });
} catch (err) {
log.warn('totp confirm failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '验证码不正确' }, 401);
}
});
app.post('/api/auth/totp/disable', async (c) => {
if (totpDisabledInDev()) {
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
}
if (!auth.totpEnabled()) {
return c.json({ success: false, message: '2FA 未开启' }, 400);
}
const token = c.get('sessionToken' as never) as string;
let body: { password?: unknown; totp?: unknown; recoveryCode?: unknown };
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const password = typeof body.password === 'string' ? body.password : '';
if (!auth.verify(password)) {
return c.json({ success: false, message: '当前密码不正确' }, 401);
}
const decision = decideSecondFactorLogin({
totpEnabled: true,
state: auth.totpState(),
password,
totp: typeof body.totp === 'string' ? body.totp : undefined,
recoveryCode: typeof body.recoveryCode === 'string' ? body.recoveryCode : undefined,
atMs: Date.now(),
});
if (decision.kind !== 'ok') {
return c.json({ success: false, message: '验证码不正确' }, 401);
}
auth.persistTotp(undefined);
totpEnrollments.delete(token);
invalidateOtherSessions(sessionTokens, token);
log.info('webui 2FA disabled; other sessions invalidated');
return c.json({ success: true });
});
app.post('/api/auth/totp/recovery-codes', async (c) => {
if (totpDisabledInDev()) {
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
}
const state = auth.totpState();
if (!state) {
return c.json({ success: false, message: '2FA 未开启' }, 400);
}
let body: { password?: unknown; totp?: unknown };
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const password = typeof body.password === 'string' ? body.password : '';
const totp = typeof body.totp === 'string' ? body.totp : '';
if (!auth.verify(password)) {
return c.json({ success: false, message: '当前密码不正确' }, 401);
}
try {
const next = regenerateRecoveryCodes({
password,
state,
totp,
atMs: Date.now(),
});
auth.persistTotp(next.state);
log.info('webui 2FA recovery codes regenerated');
return c.json({ success: true, recoveryCodes: next.recoveryCodes });
} catch (err) {
log.warn('totp recovery regenerate failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '验证码不正确' }, 401);
}
});
// ─── EULA / PRIVACY consent ──────────────────────────────────────────────
// Both are bearer-gated (consent is collected AFTER login) and live in the
// consent + must-change allowlists so they're reachable during onboarding.
@@ -922,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: {
@@ -995,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 });
@@ -1572,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);
@@ -1589,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()));
});
},
};
}
+3 -2
View File
@@ -14,8 +14,9 @@
* listeners directly so `qq-list` + `connections` invalidate at the right
* moment without modifying BridgeManager.
*
* `dispose()` unwires everything so a test (or a future hot-reload) can
* recreate the wiring without leaking listeners.
* `dispose()` sets a latch and neuters the bus. BridgeManager listeners stay
* attached; further session edges publish nothing. Process shutdown disposes
* this wiring before Hook teardown so exit-time closed is not a WebUI invalidate.
*/
import { StateBus } from './state-bus';
@@ -4,6 +4,7 @@
// nested `webuiTls.enabled`.
import type { RuntimeConfig } from '@snowluma/common/runtime';
import { checkListenerExposure } from './listener-exposure';
export type SettingsPatch = Partial<Pick<RuntimeConfig, 'webuiPort' | 'webuiHost' | 'webuiTls' | 'trustProxy'>>;
@@ -50,3 +51,25 @@ export function coerceSettingsPatch(body: unknown): CoerceResult {
return { ok: true, patch };
}
const SETTINGS_ERRORS: Record<'invalid-bind-host' | 'tls-pair-required', string> = {
'invalid-bind-host': '绑定地址不是有效的 TCP 地址',
'tls-pair-required': '启用 TLS 前请先上传有效的证书与私钥',
};
/** Validate the listener that would be persisted after applying `patch` to `current`. */
export function evaluateSettingsSave(
current: RuntimeConfig,
patch: SettingsPatch,
pairOk: boolean,
): CoerceResult {
const webuiHost = patch.webuiHost ?? current.webuiHost ?? '127.0.0.1';
const tlsEnabled = patch.webuiTls?.enabled ?? current.webuiTls?.enabled ?? false;
const check = checkListenerExposure({ webuiHost, tlsEnabled, pairOk });
if (!check.ok) return { ok: false, error: SETTINGS_ERRORS[check.code] };
return { ok: true, patch };
}
export function tlsCertDeletionBlocked(tlsEnabled: boolean): boolean {
return tlsEnabled;
}
+337
View File
@@ -0,0 +1,337 @@
import { createCipheriv, createDecipheriv, createHash, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
import * as OTPAuth from 'otpauth';
const TOTP_PERIOD_SECONDS = 30;
const TOTP_WINDOW = 1;
const TOTP_DIGITS = 6;
const RECOVERY_CODE_COUNT = 8;
const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const WRAP_SALT_BYTES = 16;
const WRAP_IV_BYTES = 12;
const WRAP_KEY_BYTES = 32;
const SCRYPT_N = 16384;
const SCRYPT_R = 8;
const SCRYPT_P = 1;
export interface WrappedTotpSecret {
wrapSalt: string;
iv: string;
ciphertext: string;
authTag: string;
}
export interface TotpPersistedState extends WrappedTotpSecret {
recoveryCodeHashes: string[];
lastUsedStep: number;
label: string;
}
export interface TotpEnrollment {
secret: string;
otpauthUrl: string;
issuer: string;
accountName: string;
}
function totpFromSecret(secretBase32: string, issuer = '', accountName = 'admin'): OTPAuth.TOTP {
return new OTPAuth.TOTP({
issuer,
label: accountName,
algorithm: 'SHA1',
digits: TOTP_DIGITS,
period: TOTP_PERIOD_SECONDS,
secret: OTPAuth.Secret.fromBase32(secretBase32),
});
}
export function verifyTotpCode(
secretBase32: string,
code: string,
atMs: number,
lastUsedStep?: number,
): { ok: true; step: number } | { ok: false } {
const token = code.replace(/\s/g, '');
if (!/^\d{6}$/.test(token)) return { ok: false };
let totp: OTPAuth.TOTP;
try {
totp = totpFromSecret(secretBase32);
} catch {
return { ok: false };
}
const delta = totp.validate({ token, timestamp: atMs, window: TOTP_WINDOW });
if (delta === null) return { ok: false };
const step = totp.counter({ timestamp: atMs }) + delta;
if (lastUsedStep !== undefined && step === lastUsedStep) return { ok: false };
return { ok: true, step };
}
function deriveWrapKey(password: string, salt: Buffer): Buffer {
return scryptSync(password, salt, WRAP_KEY_BYTES, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
}
export function wrapTotpSecret(password: string, secret: string): WrappedTotpSecret {
const wrapSalt = randomBytes(WRAP_SALT_BYTES);
const iv = randomBytes(WRAP_IV_BYTES);
const key = deriveWrapKey(password, wrapSalt);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const ciphertext = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]);
return {
wrapSalt: wrapSalt.toString('hex'),
iv: iv.toString('hex'),
ciphertext: ciphertext.toString('hex'),
authTag: cipher.getAuthTag().toString('hex'),
};
}
export function unwrapTotpSecret(password: string, wrapped: WrappedTotpSecret): string | null {
try {
const wrapSalt = Buffer.from(wrapped.wrapSalt, 'hex');
const iv = Buffer.from(wrapped.iv, 'hex');
const ciphertext = Buffer.from(wrapped.ciphertext, 'hex');
const authTag = Buffer.from(wrapped.authTag, 'hex');
if (wrapSalt.length !== WRAP_SALT_BYTES || iv.length !== WRAP_IV_BYTES || authTag.length !== 16) {
return null;
}
const key = deriveWrapKey(password, wrapSalt);
const decipher = createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(authTag);
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
} catch {
return null;
}
}
function randomRecoveryChunk(): string {
const bytes = randomBytes(4);
let chunk = '';
for (let i = 0; i < 4; i++) {
chunk += RECOVERY_ALPHABET[bytes[i]! % RECOVERY_ALPHABET.length];
}
return chunk;
}
export function generateRecoveryCodes(): string[] {
const codes = new Set<string>();
while (codes.size < RECOVERY_CODE_COUNT) {
codes.add(`${randomRecoveryChunk()}-${randomRecoveryChunk()}`);
}
return [...codes];
}
export function normalizeRecoveryCode(code: string): string {
return code.replace(/[-\s]/g, '').toUpperCase();
}
export function hashRecoveryCode(code: string): string {
return createHash('sha256').update(normalizeRecoveryCode(code), 'utf8').digest('hex');
}
function hashesEqual(left: string, right: string): boolean {
const a = Buffer.from(left, 'hex');
const b = Buffer.from(right, 'hex');
if (a.length !== b.length || a.length === 0) return false;
return timingSafeEqual(a, b);
}
export function consumeRecoveryCode(
code: string,
hashes: readonly string[],
): { ok: true; remainingHashes: string[] } | { ok: false } {
const candidate = hashRecoveryCode(code);
const index = hashes.findIndex((hash) => hashesEqual(hash, candidate));
if (index < 0) return { ok: false };
return { ok: true, remainingHashes: hashes.filter((_, i) => i !== index) };
}
export function beginTotpEnrollment(options: {
issuer: string;
accountName: string;
secret?: string;
}): TotpEnrollment {
const secret = options.secret ?? new OTPAuth.Secret({ size: 20 }).base32;
const totp = totpFromSecret(secret, options.issuer, options.accountName);
return {
secret,
otpauthUrl: totp.toString(),
issuer: options.issuer,
accountName: options.accountName,
};
}
export function confirmTotpEnrollment(options: {
password: string;
secret: string;
code: string;
label: string;
atMs: number;
}): { state: TotpPersistedState; recoveryCodes: string[] } {
const verified = verifyTotpCode(options.secret, options.code, options.atMs);
if (!verified.ok) {
throw new Error('验证码不正确');
}
const recoveryCodes = generateRecoveryCodes();
return {
recoveryCodes,
state: {
...wrapTotpSecret(options.password, options.secret),
recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode),
lastUsedStep: verified.step,
label: options.label,
},
};
}
export function verifySecondFactor(options: {
password: string;
state: TotpPersistedState;
atMs: number;
totp?: string;
recoveryCode?: string;
}): { ok: true; state: TotpPersistedState } | { ok: false } {
if (typeof options.recoveryCode === 'string' && options.recoveryCode.length > 0) {
const consumed = consumeRecoveryCode(options.recoveryCode, options.state.recoveryCodeHashes);
if (!consumed.ok) return { ok: false };
return { ok: true, state: { ...options.state, recoveryCodeHashes: consumed.remainingHashes } };
}
if (typeof options.totp !== 'string') return { ok: false };
const secret = unwrapTotpSecret(options.password, options.state);
if (secret === null) return { ok: false };
const checked = verifyTotpCode(secret, options.totp, options.atMs, options.state.lastUsedStep);
if (!checked.ok) return { ok: false };
return { ok: true, state: { ...options.state, lastUsedStep: checked.step } };
}
export type SecondFactorDecision =
| { kind: 'needs-totp' }
| { kind: 'bad-second-factor' }
| { kind: 'ok'; state?: TotpPersistedState };
export function decideSecondFactorLogin(options: {
totpEnabled: boolean;
state?: TotpPersistedState;
password: string;
totp?: string;
recoveryCode?: string;
atMs: number;
}): SecondFactorDecision {
if (!options.totpEnabled) return { kind: 'ok' };
if (!options.state) return { kind: 'bad-second-factor' };
const totp = typeof options.totp === 'string' && options.totp.trim().length > 0
? options.totp.trim()
: undefined;
const recoveryCode = typeof options.recoveryCode === 'string' && options.recoveryCode.trim().length > 0
? options.recoveryCode.trim()
: undefined;
if (!totp && !recoveryCode) return { kind: 'needs-totp' };
const result = verifySecondFactor({
password: options.password,
state: options.state,
atMs: options.atMs,
totp,
recoveryCode,
});
if (!result.ok) return { kind: 'bad-second-factor' };
return { kind: 'ok', state: result.state };
}
export function regenerateRecoveryCodes(options: {
password: string;
state: TotpPersistedState;
totp: string;
atMs: number;
}): { state: TotpPersistedState; recoveryCodes: string[] } {
const verified = verifySecondFactor({
password: options.password,
state: options.state,
totp: options.totp,
atMs: options.atMs,
});
if (!verified.ok) {
throw new Error('验证码不正确');
}
const recoveryCodes = generateRecoveryCodes();
return {
recoveryCodes,
state: {
...verified.state,
recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode),
},
};
}
export function rewrapTotpSecret(
oldPassword: string,
newPassword: string,
state: TotpPersistedState,
): TotpPersistedState {
const secret = unwrapTotpSecret(oldPassword, state);
if (secret === null) {
throw new Error('无法使用当前密码解开 2FA 密钥');
}
return {
...state,
...wrapTotpSecret(newPassword, secret),
};
}
const HEX = /^[0-9a-f]+$/i;
function isWrappedShape(value: Record<string, unknown>): value is WrappedTotpSecret & Record<string, unknown> {
return typeof value.wrapSalt === 'string'
&& HEX.test(value.wrapSalt)
&& value.wrapSalt.length === WRAP_SALT_BYTES * 2
&& typeof value.iv === 'string'
&& HEX.test(value.iv)
&& value.iv.length === WRAP_IV_BYTES * 2
&& typeof value.ciphertext === 'string'
&& HEX.test(value.ciphertext)
&& value.ciphertext.length > 0
&& value.ciphertext.length % 2 === 0
&& typeof value.authTag === 'string'
&& HEX.test(value.authTag)
&& value.authTag.length === 32;
}
export function prepareTotpStateForRestore(value: unknown): TotpPersistedState {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new Error('totp state must be an object');
}
const v = value as Record<string, unknown>;
if (!isWrappedShape(v)) {
throw new Error('totp wrapped secret fields are invalid');
}
if (!Array.isArray(v.recoveryCodeHashes)
|| v.recoveryCodeHashes.length > RECOVERY_CODE_COUNT
|| v.recoveryCodeHashes.some((hash) => typeof hash !== 'string' || !/^[0-9a-f]{64}$/i.test(hash))) {
throw new Error('totp recoveryCodeHashes must be SHA-256 hex strings');
}
if (typeof v.lastUsedStep !== 'number' || !Number.isInteger(v.lastUsedStep) || v.lastUsedStep < 0) {
throw new Error('totp lastUsedStep must be a non-negative integer');
}
if (typeof v.label !== 'string' || v.label.length === 0 || v.label.length > 128) {
throw new Error('totp label must be a non-empty string');
}
const allowed = new Set(['wrapSalt', 'iv', 'ciphertext', 'authTag', 'recoveryCodeHashes', 'lastUsedStep', 'label']);
const unknown = Object.keys(v).find((key) => !allowed.has(key));
if (unknown) throw new Error(`unknown totp field $.${unknown}`);
return {
wrapSalt: v.wrapSalt.toLowerCase(),
iv: v.iv.toLowerCase(),
ciphertext: v.ciphertext.toLowerCase(),
authTag: v.authTag.toLowerCase(),
recoveryCodeHashes: v.recoveryCodeHashes.map((hash) => (hash as string).toLowerCase()),
lastUsedStep: v.lastUsedStep,
label: v.label,
};
}
export function parseTotpStateLenient(value: unknown): TotpPersistedState | undefined {
if (value === undefined || value === null) return undefined;
try {
return prepareTotpStateForRestore(value);
} catch {
return undefined;
}
}
+51
View File
@@ -0,0 +1,51 @@
import { decideSecondFactorLogin, type TotpPersistedState } from './totp';
export interface WebuiLoginAuth {
verify(password: string): boolean;
totpEnabled(): boolean;
totpState(): TotpPersistedState | undefined;
mustChangePassword(): boolean;
}
export type WebuiLoginResult =
| { kind: 'bad-request' }
| { kind: 'bad-password' }
| { kind: 'needs-totp' }
| { kind: 'bad-second-factor' }
| { kind: 'ok'; mustChangePassword: boolean; totpState?: TotpPersistedState };
function readString(value: unknown): string {
return typeof value === 'string' ? value : '';
}
export function completeWebuiLogin(auth: WebuiLoginAuth, body: unknown, atMs: number): WebuiLoginResult {
if (!body || typeof body !== 'object' || Array.isArray(body)) {
return { kind: 'bad-request' };
}
const record = body as Record<string, unknown>;
const password = readString(record.password);
if (!auth.verify(password)) {
return { kind: 'bad-password' };
}
const decision = decideSecondFactorLogin({
totpEnabled: auth.totpEnabled(),
state: auth.totpState(),
password,
totp: readString(record.totp) || undefined,
recoveryCode: readString(record.recoveryCode) || undefined,
atMs,
});
if (decision.kind === 'needs-totp') return { kind: 'needs-totp' };
if (decision.kind === 'bad-second-factor') return { kind: 'bad-second-factor' };
return {
kind: 'ok',
mustChangePassword: auth.mustChangePassword(),
...(decision.state ? { totpState: decision.state } : {}),
};
}
export function invalidateOtherSessions<T>(sessions: Map<string, T>, keepToken: string): void {
for (const token of sessions.keys()) {
if (token !== keepToken) sessions.delete(token);
}
}
+2
View File
@@ -127,6 +127,7 @@ export interface MockBridge {
nickname: string;
findUidByUin: ReturnType<typeof vi.fn>;
findUinByUid: ReturnType<typeof vi.fn>;
resolveUin: ReturnType<typeof vi.fn>;
findGroupMember: ReturnType<typeof vi.fn>;
updateFriendRemark: ReturnType<typeof vi.fn>;
updateGroupRemark: ReturnType<typeof vi.fn>;
@@ -161,6 +162,7 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
nickname: 'self-nick',
findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0),
resolveUin: vi.fn(async () => null),
findGroupMember: vi.fn(() => null),
updateFriendRemark: vi.fn(() => true),
updateGroupRemark: vi.fn(() => true),
@@ -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: {
@@ -269,6 +326,25 @@ describe('apis/contacts / group roster', () => {
allMuted: true,
}));
});
it('treats a past group-mute expire as unmuted (#356)', async () => {
const sendRawPacket = vi.fn(async () => groupListPacket({
groups: [{
groupUin: 123456789,
info: {
groupName: 'Was Muted',
shutUpAllTimestamp: 1_700_000_000,
},
}],
}));
const api = new ContactsApi({
sendRawPacket,
identity: { rememberGroups: vi.fn() },
} as any);
const groups = await api.fetchGroupList();
expect(groups[0]?.allMuted).toBe(false);
});
});
describe('apis/contacts / group requests', () => {
@@ -604,3 +680,18 @@ describe('apis/contacts / robot group-member classification', () => {
expect(rememberGroupMembers).toHaveBeenCalledOnce();
});
});
describe('apis/contacts / invite-card pending application', () => {
it('remembers, reads, and reverse-looks-up a card sequence', () => {
const api = new ContactsApi({ identity: { uin: '10001' } } as any);
expect(api.getGroupInviteCardSequence(12345)).toBeUndefined();
api.rememberGroupInviteCardSequence(12345, 778899);
api.rememberGroupInviteCardSequence(0, 1);
api.rememberGroupInviteCardSequence(1, 0);
expect(api.getGroupInviteCardSequence(12345)).toBe(778899);
expect(api.findGroupInviteCardGroupBySequence(778899)).toBe(12345);
expect(api.findGroupInviteCardGroupBySequence(1)).toBeUndefined();
});
});
@@ -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 } },
}));
}
+358 -32
View File
@@ -1,6 +1,7 @@
import { describe, it, expect, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbSvcTrpcTcp0x88D_0Response } from '@snowluma/proto-defs/oidb';
import type { OidbGetGroupExtResp } from '@snowluma/proto-defs/oidb-actions/group-ext';
import type {
Oidb0x8a0Req,
Oidb0x8a7Resp,
@@ -10,8 +11,10 @@ import type {
Oidb0x89a_0HistoryVisibility,
Oidb0x89a_0MemberPermission,
Oidb0xf16Req,
OidbGroupDetailRequest,
OidbGroupRequestAction,
OidbKickMember,
OidbKickMemberResponse,
OidbLeaveGroup,
OidbMuteAll,
OidbMuteMember,
@@ -20,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) {
@@ -34,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: {
@@ -56,6 +74,26 @@ function packGroupFlagExt4(groupFlagExt4?: number) {
}));
}
function packAdminDetail(results: NonNullable<NonNullable<OidbSvcTrpcTcp0x88D_0Response['groupInfo']>['results']>) {
return packResponse(protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
body: { groupInfo: { uin: 12345n, results } },
}));
}
function packRobotExt(robotMemberSwitch?: number, robotMemberExamine?: number) {
return packResponse(protobuf_encode<OidbBase<OidbGetGroupExtResp>>({
body: {
items: [{
groupCode: 12345n,
ext: {
inviteRobotMemberSwitch: robotMemberSwitch,
inviteRobotMemberExamine: robotMemberExamine,
},
}],
},
}));
}
describe('apis/group-admin', () => {
it('muteMember resolves UID and dispatches 0x1253_1', async () => {
const bridge = mockBridge();
@@ -103,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 () => {
@@ -133,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 () => {
@@ -210,11 +259,24 @@ describe('apis/group-admin', () => {
const addOptEnv = protobuf_decode<OidbBase<Oidb0x89a_0AddOption>>(bridge.sendRawPacket.mock.calls[4]![1]);
expect(addOptEnv.body).toMatchObject({ groupUin: 1n, settings: { addType: 2 } });
expect(addOptEnv.body?.settings?.groupQuestion ?? undefined).toBeUndefined();
const searchEnv = protobuf_decode<OidbBase<Oidb0x89a_0Search>>(bridge.sendRawPacket.mock.calls[5]![1]);
expect(searchEnv.body?.groupUin).toBe(1n);
});
it('setAddOption forwards question and answer for type 4', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).setAddOption(12345, 4, 'how', '42');
const envelope = protobuf_decode<OidbBase<Oidb0x89a_0AddOption>>(
bridge.sendRawPacket.mock.calls[0]![1],
);
expect(envelope.body).toMatchObject({
groupUin: 12345n,
settings: { addType: 4, groupQuestion: 'how', groupAnswer: '42' },
});
});
it('setAddRequest picks _1 / _2 based on filtered flag', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).setAddRequest(12345, 5, 1, true, 'ok', false);
@@ -264,9 +326,32 @@ describe('apis/group-admin', () => {
});
});
it('setMemberInvitePolicy fails before mutation when the current flag is absent', async () => {
it('setMemberInvitePolicy treats an omitted privilege flag as zero', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packPrivilegeFlag());
bridge.sendRawPacket
.mockResolvedValueOnce(packPrivilegeFlag())
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packPrivilegeFlag(0));
await new GroupAdminApi(bridge as any).setMemberInvitePolicy(12345, 'require_approval');
const env = protobuf_decode<OidbBase<Oidb0x89a_0InvitePolicy>>(
bridge.sendRawPacket.mock.calls[1]![1],
);
expect(env.body?.settings).toEqual({
appPrivilegeFlag: 0,
appPrivilegeMask: 0x06100000,
allowMemberInvite: 1,
});
});
it('setMemberInvitePolicy fails when group detail has no results block', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
body: { groupInfo: { uin: 12345n } },
}),
));
await expect(
new GroupAdminApi(bridge as any).setMemberInvitePolicy(12345, 'require_approval'),
@@ -287,53 +372,83 @@ describe('apis/group-admin', () => {
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
});
it('setNewMemberHistoryVisibility reads, merges, writes, and verifies the extended flag (#336)', async () => {
it('setNewMemberHistoryVisibility accepts a 0/1 history-visible read-back (#387)', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(packGroupFlagExt4(0x80000001))
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packGroupFlagExt4(0x80000005));
.mockResolvedValueOnce(packGroupFlagExt4(1));
await new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, true);
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
'OidbSvcTrpcTcp.0x88d_0',
'OidbSvcTrpcTcp.0x89a_0',
'OidbSvcTrpcTcp.0x88d_0',
]);
const envelope = protobuf_decode<OidbBase<Oidb0x89a_0HistoryVisibility>>(
bridge.sendRawPacket.mock.calls[1]![1],
bridge.sendRawPacket.mock.calls[0]![1],
);
expect(envelope.body).toMatchObject({
groupUin: 12345n,
settings: {
groupFlagExt4: 0x80000005,
groupFlagExt4: 0x4,
groupFlagExt4Mask: 0x4,
},
});
});
it('setNewMemberHistoryVisibility fails before mutation when the current flag is absent', async () => {
it('setNewMemberHistoryVisibility clears visibility when read-back is the off flag', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packGroupFlagExt4());
bridge.sendRawPacket
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packGroupFlagExt4(0));
await new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, false);
const envelope = protobuf_decode<OidbBase<Oidb0x89a_0HistoryVisibility>>(
bridge.sendRawPacket.mock.calls[0]![1],
);
expect(envelope.body?.settings).toEqual({
groupFlagExt4: 0,
groupFlagExt4Mask: 0x4,
});
});
it('setNewMemberHistoryVisibility treats an omitted history flag as hidden', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packGroupFlagExt4());
await new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, false);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
});
it('setNewMemberHistoryVisibility fails when group detail has no results block', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
body: { groupInfo: { uin: 12345n } },
}),
));
await expect(
new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, true),
).rejects.toThrow(/unable to read new-member history visibility before update/);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
).rejects.toThrow(/unable to read new-member history visibility after update/);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
});
it('setNewMemberHistoryVisibility rejects an ack when read-back does not match', async () => {
it('setNewMemberHistoryVisibility rejects an ack when read-back stays hidden', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(packGroupFlagExt4(0x80000001))
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packGroupFlagExt4(0x80000001));
.mockResolvedValueOnce(packGroupFlagExt4(0));
await expect(
new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, true),
).rejects.toThrow(/was not applied/);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
});
it('setMemberPermissions applies supplied switches separately and verifies the combined result (#335)', async () => {
@@ -377,9 +492,35 @@ describe('apis/group-admin', () => {
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('setMemberPermissions fails before mutation when the current flag is absent', async () => {
it('setMemberPermissions treats an omitted privilege flag as all-allowed (#388)', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packPrivilegeFlag());
bridge.sendRawPacket
.mockResolvedValueOnce(packPrivilegeFlag())
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packPrivilegeFlag(0));
await new GroupAdminApi(bridge as any).setMemberPermissions(12345, {
allowMemberUploadAlbum: true,
});
expect(bridge.sendRawPacket.mock.calls[1]![0]).toBe('OidbSvcTrpcTcp.0x89a_0');
const envelope = protobuf_decode<OidbBase<Oidb0x89a_0MemberPermission>>(
bridge.sendRawPacket.mock.calls[1]![1],
);
expect(envelope.subCommand ?? 0).toBe(0);
expect(envelope.body?.settings).toEqual({
appPrivilegeFlag: 0,
appPrivilegeMask: 1,
});
});
it('setMemberPermissions fails when group detail has no results block', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
body: { groupInfo: { uin: 12345n } },
}),
));
await expect(
new GroupAdminApi(bridge as any).setMemberPermissions(12345, {
@@ -389,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
@@ -419,6 +607,94 @@ describe('apis/group-admin', () => {
});
});
it('getAdminSettings composes detail and ext-info into setter-aligned fields (#385)', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
if (cmd === 'OidbSvcTrpcTcp.0x88d_0') {
return packAdminDetail({
addType: 2,
question: 'how',
answer: '42',
privilegeFlag: 0x84018001,
groupFlagExt4: 1,
noFingerOpen: 1,
});
}
if (cmd === 'OidbSvcTrpcTcp.0xef0_1') {
return packRobotExt(1, 2);
}
return packResponse(Buffer.alloc(0));
});
const out = await new GroupAdminApi(bridge as any).getAdminSettings(12345);
expect(out).toEqual({
add_type: 2,
group_question: 'how',
group_answer: '42',
robot_member_switch: 1,
robot_member_examine: 2,
member_invite_policy: 'disabled',
allow_member_upload_album: false,
allow_member_temporary_session: false,
allow_member_create_group: false,
new_member_history_visible: true,
no_finger_open: 1,
no_code_finger_open: 0,
});
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0]).sort()).toEqual([
'OidbSvcTrpcTcp.0x88d_0',
'OidbSvcTrpcTcp.0xef0_1',
]);
const detailReq = protobuf_decode<OidbBase<OidbGroupDetailRequest>>(
bridge.sendRawPacket.mock.calls.find((call) => call[0] === 'OidbSvcTrpcTcp.0x88d_0')![1],
);
expect(detailReq.body?.config?.flags?.question).toBe('');
expect(detailReq.body?.config?.flags?.answer).toBe('');
});
it('getAdminSettings treats omitted detail/ext zeros as the default values', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
if (cmd === 'OidbSvcTrpcTcp.0x88d_0') {
return packAdminDetail({});
}
if (cmd === 'OidbSvcTrpcTcp.0xef0_1') {
return packRobotExt();
}
return packResponse(Buffer.alloc(0));
});
await expect(new GroupAdminApi(bridge as any).getAdminSettings(12345)).resolves.toEqual({
add_type: 0,
group_question: '',
group_answer: '',
robot_member_switch: 0,
robot_member_examine: 0,
member_invite_policy: 'require_approval',
allow_member_upload_album: true,
allow_member_temporary_session: true,
allow_member_create_group: true,
new_member_history_visible: false,
no_finger_open: 0,
no_code_finger_open: 0,
});
});
it('getAdminSettings fails when group detail has no results block', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
if (cmd === 'OidbSvcTrpcTcp.0x88d_0') {
return packResponse(protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
body: { groupInfo: { uin: 12345n } },
}));
}
return packRobotExt(0, 0);
});
await expect(new GroupAdminApi(bridge as any).getAdminSettings(12345))
.rejects.toThrow(/unable to read group admin settings/);
});
it('getAtAllRemain falls back to zero / false when the response is empty', async () => {
const bridge = mockBridge();
// Empty OidbBase envelope (no body) — invokeOidb substitutes `{}`
@@ -434,4 +710,54 @@ describe('apis/group-admin', () => {
remain_at_all_count_for_uin: 0,
});
});
it('lists category tags and keeps category 0 on the wire', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGetGroupCategoryTagsResp>>({
body: { tags: [{ id: 7, name: '学习', type: 1 }, { name: '未编号' }] },
}),
));
const out = await new GroupAdminApi(bridge as any).listCategoryTags(0);
expect(out).toEqual({
tags: [
{ id: 7, name: '学习', type: 1 },
{ id: 0, name: '未编号', type: 0 },
],
});
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x967c_0');
const env = protobuf_decode<OidbBase<OidbGetGroupCategoryTags>>(bridge.sendRawPacket.mock.calls[0]![1]);
expect(env.command).toBe(0x967C);
expect(env.body?.groupClass).toBe(0);
});
it('returns an empty tag list when the category has none', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGetGroupCategoryTagsResp>>({ body: {} }),
));
await expect(new GroupAdminApi(bridge as any).listCategoryTags(2)).resolves.toEqual({ tags: [] });
});
it('adds and removes a category tag by its name', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).addCategoryTag(3, ' 户外 ');
await new GroupAdminApi(bridge as any).removeCategoryTag(3, '户外');
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
'OidbSvcTrpcTcp.0x967d_0',
'OidbSvcTrpcTcp.0x967e_0',
]);
const added = protobuf_decode<OidbBase<OidbChangeGroupCategoryTag>>(bridge.sendRawPacket.mock.calls[0]![1]);
expect(added.body).toMatchObject({ groupClass: 3, name: ' 户外 ' });
const removed = protobuf_decode<OidbBase<OidbChangeGroupCategoryTag>>(bridge.sendRawPacket.mock.calls[1]![1]);
expect(removed.body).toMatchObject({ groupClass: 3, name: '户外' });
});
it('refuses an empty tag name instead of sending it', async () => {
const bridge = mockBridge();
await expect(new GroupAdminApi(bridge as any).addCategoryTag(1, '')).rejects.toThrow(/must not be empty/);
await expect(new GroupAdminApi(bridge as any).removeCategoryTag(1, '')).rejects.toThrow(/must not be empty/);
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
});
@@ -1,7 +1,14 @@
import { describe, expect, it } from 'vitest';
import type {
DeleteMediasRequest,
DeleteMediasResponse,
DoQunCommentRequest,
DoQunCommentResponse,
GetAlbumListResponse,
GetMediaListResponse,
GetQunFeedDetailRequest,
GetQunFeedDetailResponse,
QunFeedCellCommon,
} from '@snowluma/proto-defs/oidb-actions/group-album';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { GroupAlbumApi } from '../../src/bridge/apis/group-album';
@@ -437,4 +444,501 @@ describe('apis/group-album', () => {
nextAttachInfo: 'next-video-page',
});
});
function packDeleteOk() {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<DeleteMediasResponse>({ field1: 8694 })),
};
}
function packMediaList(body: GetMediaListResponse['data']) {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<GetMediaListResponse>({ data: body })),
};
}
it('deletes a photo by lloc and includes the batch id', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
if (cmd.endsWith('GetMediaList')) {
return packMediaList({
mediaList: [{ type: 1, image: { lloc: 'photo-lloc' }, batchId: 77n }],
});
}
return packDeleteOk();
});
await expect(new GroupAlbumApi(bridge as never).delete(12345, 'album-id', 'photo-lloc'))
.resolves.toEqual({ success: true });
const deleteCall = bridge.sendRawPacket.mock.calls.find((call) =>
String(call[0]).endsWith('DeleteMedias'),
);
expect(deleteCall?.[0]).toBe('QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias');
const request = protobuf_decode<DeleteMediasRequest>(deleteCall![1] as Uint8Array);
expect(request.body).toMatchObject({
groupId: '12345',
albumId: 'album-id',
mediaIds: ['photo-lloc'],
batchIds: ['77'],
});
});
it('deletes a video by video id using the cover lloc', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
if (cmd.endsWith('GetMediaList')) {
return packMediaList({
mediaList: [{
type: 2,
video: { id: 'video-id', cover: { lloc: 'cover-large' } },
batchId: 88n,
}],
});
}
return packDeleteOk();
});
await expect(new GroupAlbumApi(bridge as never).delete(12345, 'album-id', 'video-id'))
.resolves.toEqual({ success: true });
const deleteCall = bridge.sendRawPacket.mock.calls.find((call) =>
String(call[0]).endsWith('DeleteMedias'),
);
const request = protobuf_decode<DeleteMediasRequest>(deleteCall![1] as Uint8Array);
expect(request.body?.mediaIds).toEqual(['cover-large']);
expect(request.body?.batchIds).toEqual(['88']);
});
it('pages the media list until the video is found', async () => {
const bridge = mockBridge();
let pages = 0;
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
if (cmd.endsWith('GetMediaList')) {
pages += 1;
if (pages === 1) {
return packMediaList({
mediaList: [{ type: 1, image: { lloc: 'other' }, batchId: 1n }],
nextAttachInfo: 'page-2',
});
}
return packMediaList({
mediaList: [{
type: 2,
video: { id: 'video-id', cover: { lloc: 'cover-2' } },
batchId: 2n,
}],
});
}
return packDeleteOk();
});
await new GroupAlbumApi(bridge as never).delete(12345, 'album-id', 'video-id');
expect(pages).toBe(2);
const deleteCall = bridge.sendRawPacket.mock.calls.find((call) =>
String(call[0]).endsWith('DeleteMedias'),
);
const request = protobuf_decode<DeleteMediasRequest>(deleteCall![1] as Uint8Array);
expect(request.body?.mediaIds).toEqual(['cover-2']);
expect(request.body?.batchIds).toEqual(['2']);
});
it('falls back to the raw id when the media list has no match', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
if (cmd.endsWith('GetMediaList')) {
return packMediaList({ mediaList: [] });
}
return packDeleteOk();
});
await new GroupAlbumApi(bridge as never).delete(12345, 'album-id', 'unknown-id');
const deleteCall = bridge.sendRawPacket.mock.calls.find((call) =>
String(call[0]).endsWith('DeleteMedias'),
);
const request = protobuf_decode<DeleteMediasRequest>(deleteCall![1] as Uint8Array);
expect(request.body?.mediaIds).toEqual(['unknown-id']);
expect(request.body?.batchIds ?? []).toEqual([]);
});
function packCommentOk(comment: DoQunCommentResponse['comment']): ReturnType<typeof packDeleteOk> {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<DoQunCommentResponse>({
field1: 8527,
comment,
})),
};
}
function packFeedDetail(
feedId = 'official-feed-id',
time = 1700000123n,
extra: {
ownerUin?: string;
cellCommon?: Omit<QunFeedCellCommon, 'time' | 'feedId'>;
cellMedia?: {
medias?: Array<{ type?: number; image?: { lloc?: string }; video?: { cover?: { lloc?: string } } }>;
albumId?: string;
batchId?: bigint;
};
} = {},
): ReturnType<typeof packDeleteOk> {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<GetQunFeedDetailResponse>({
result: 0,
data: {
feed: {
feed: {
cellCommon: { time, feedId, ...extra.cellCommon },
...(extra.ownerUin ? { cellUserInfo: { user: { uin: extra.ownerUin } } } : {}),
...(extra.cellMedia ? { cellMedia: extra.cellMedia } : {}),
},
},
},
})),
};
}
function packPhotoMedia(lloc = 'photo-lloc', batchId = 77n) {
return packMediaList({
mediaList: [{ type: 1, image: { lloc }, batchId }],
});
}
function commentMocks(
extra: (cmd: string) => ReturnType<typeof packDeleteOk> | undefined = () => undefined,
) {
return async (cmd: string) => {
const override = extra(cmd);
if (override) return override;
if (cmd.endsWith('GetMediaList')) return packPhotoMedia();
if (cmd.endsWith('GetQunFeedDetail')) {
return packFeedDetail('official-feed-id', 1700000123n, {
ownerUin: '3119936551',
cellCommon: {
type: 422,
cellId: '421_1_0_12345|album-id|77^||^421_1_0_12345|album-id|photo-lloc^||^0',
field6: 3,
},
});
}
return packCommentOk({
data: {
id: 'cmt-1',
user: { uin: '10001' },
content: [{ type: 0, content: 'hello' }],
time: 1700000000n,
clientKey: 'ck',
},
});
};
}
function commentCallBytes(bridge: ReturnType<typeof mockBridge>): Uint8Array {
const commentCall = bridge.sendRawPacket.mock.calls.find((call) =>
String(call[0]).endsWith('DoQunComment'),
);
expect(commentCall?.[0]).toBe(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
);
return commentCall![1] as Uint8Array;
}
function commentRequestOf(bridge: ReturnType<typeof mockBridge>): DoQunCommentRequest {
return protobuf_decode<DoQunCommentRequest>(commentCallBytes(bridge));
}
function feedDetailRequestOf(bridge: ReturnType<typeof mockBridge>): GetQunFeedDetailRequest {
const feedCall = bridge.sendRawPacket.mock.calls.find((call) =>
String(call[0]).endsWith('GetQunFeedDetail'),
);
expect(feedCall?.[0]).toBe(
'QunAlbum.trpc.qzone.webapp_qun_feeds.FeedsReader.GetQunFeedDetail',
);
return protobuf_decode<GetQunFeedDetailRequest>(feedCall![1] as Uint8Array);
}
it('looks up the official feed then comments with its header and slim photo cell', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks());
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
.resolves.toEqual({
id: 'cmt-1',
user: { uin: '10001' },
content: [{ type: 0, content: 'hello' }],
time: '1700000000',
clientKey: 'ck',
});
expect(feedDetailRequestOf(bridge).data).toMatchObject({
groupId: '12345',
commentCount: 20,
albumId: 'album-id',
batchId: '77',
lloc: 'photo-lloc',
});
expect(feedDetailRequestOf(bridge).data?.feedId ?? '').toBe('');
expect(feedDetailRequestOf(bridge).data?.attachInfo ?? '').toBe('');
const request = commentRequestOf(bridge);
expect(request.field1).toBe(8527);
expect(request.body).toMatchObject({
groupId: '12345',
field3: 2,
reqBody: {
field1: {
time: 1700000123n,
feedId: 'official-feed-id',
},
field2: { field1: { uin: '3119936551' } },
field5: {
albumId: 'album-id',
batchId: 77n,
medias: [{
image: { lloc: 'photo-lloc' },
}],
},
},
field5: {
user: { uin: '10001' },
contents: [{ content: 'hello' }],
},
});
expect(request.body?.reqBody?.field5?.medias?.[0]?.type ?? 0).toBe(0);
expect(Buffer.from(commentCallBytes(bridge)).subarray(0, 7).toString('hex'))
.toBe('08cf4212001a00');
});
it('falls back to the media uploader when the official feed has no owner cell', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('GetMediaList')) {
return packMediaList({
mediaList: [{ type: 1, image: { lloc: 'photo-lloc' }, batchId: 77n, uploader: '3119936551' }],
});
}
if (cmd.endsWith('GetQunFeedDetail')) return packFeedDetail();
return undefined;
}));
await new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello');
expect(commentRequestOf(bridge).body?.reqBody?.field2?.field1?.uin).toBe('3119936551');
expect(commentRequestOf(bridge).body?.field5?.user?.uin).toBe('10001');
});
it('copies the official feed media cell instead of a reconstructed lloc-only cell', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('GetQunFeedDetail')) {
return packFeedDetail('official-feed-id', 1700000123n, {
ownerUin: '3119936551',
cellMedia: {
albumId: 'feed-album',
batchId: 88n,
medias: [{
type: 0,
image: { lloc: 'feed-lloc' },
}],
},
});
}
return undefined;
}));
await new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello');
expect(commentRequestOf(bridge).body?.reqBody?.field5).toMatchObject({
albumId: 'feed-album',
batchId: 88n,
medias: [{
image: { lloc: 'feed-lloc' },
}],
});
});
it('writes only the official comment header fields even when the feed cell has extra locator data', async () => {
const cellId = '421_1_0_964445447|album-id|2147483665^||^421_1_0_964445447|album-id|photo-lloc^||^0';
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('GetQunFeedDetail')) {
return packFeedDetail('422_0_2147483665', 1789315793n, {
ownerUin: '3119936551',
cellCommon: { type: 422, cellId, field6: 3 },
});
}
return undefined;
}));
await new GroupAlbumApi(bridge as never).comment(964445447, 'album-id', 'photo-lloc', 'hello');
expect(commentRequestOf(bridge).body?.reqBody?.field1).toMatchObject({
time: 1789315793n,
feedId: '422_0_2147483665',
});
expect(commentRequestOf(bridge).body?.reqBody?.field1?.type ?? 0).toBe(0);
expect(commentRequestOf(bridge).body?.reqBody?.field1?.cellId ?? '').toBe('');
expect(commentRequestOf(bridge).body?.reqBody?.field1?.field6 ?? 0).toBe(0);
});
it('comments a video with the cover location and video media type', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('GetMediaList')) {
return packMediaList({
mediaList: [{
type: 2,
video: { id: 'video-id', cover: { lloc: 'cover-lloc' } },
batchId: 88n,
}],
});
}
return undefined;
}));
await new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'video-id', 'hello');
expect(feedDetailRequestOf(bridge).data?.lloc).toBe('cover-lloc');
expect(commentRequestOf(bridge).body?.reqBody?.field5).toMatchObject({
albumId: 'album-id',
batchId: 88n,
medias: [{
type: 1,
video: { cover: { lloc: 'cover-lloc' } },
}],
});
});
it('rejects a comment when the album media cannot be resolved', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('GetMediaList')) return packMediaList({ mediaList: [] });
return undefined;
}));
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'missing-lloc', 'hello'))
.rejects.toThrow('comment album media error: media not found');
expect(bridge.sendRawPacket.mock.calls.some((call) => String(call[0]).endsWith('DoQunComment')))
.toBe(false);
});
it('rejects a comment when the official feed lookup fails', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('GetQunFeedDetail')) {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<GetQunFeedDetailResponse>({
result: 10016,
errorText: '服务器繁忙',
})),
};
}
return undefined;
}));
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
.rejects.toThrow('fetch album feed error: retCode 10016, 服务器繁忙');
expect(bridge.sendRawPacket.mock.calls.some((call) => String(call[0]).endsWith('DoQunComment')))
.toBe(false);
});
it('rejects a comment when the official feed has no id', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('GetQunFeedDetail')) return packFeedDetail('');
return undefined;
}));
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
.rejects.toThrow('comment album media error: empty feed');
expect(bridge.sendRawPacket.mock.calls.some((call) => String(call[0]).endsWith('DoQunComment')))
.toBe(false);
});
it('rejects a seq-echo 8527 packet that has no comment body', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('DoQunComment')) {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<DoQunCommentResponse>({ field1: 8527 })),
};
}
return undefined;
}));
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
.rejects.toThrow('comment album media error: empty comment');
});
it('surfaces the album result code instead of treating seq 8527 as success', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('DoQunComment')) {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<DoQunCommentResponse>({
field1: 8527,
result: 1001,
errorText: 'permission denied',
})),
};
}
return undefined;
}));
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
.rejects.toThrow('comment album media error: retCode 1001, permission denied');
});
it('accepts a comment written directly on envelope field 4', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
if (cmd.endsWith('DoQunComment')) {
return packCommentOk({
id: 'flat-id',
content: [{ type: 0, content: 'hello' }],
time: 123n,
clientKey: 'ck',
});
}
return undefined;
}));
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
.resolves.toMatchObject({
id: 'flat-id',
user: { uin: '10001' },
content: [{ type: 0, content: 'hello' }],
time: '123',
clientKey: 'ck',
});
});
});
@@ -327,6 +327,7 @@ describe('apis/group-file', () => {
nickname: 'self-nick',
findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0),
resolveUin: vi.fn(async () => null),
findGroupMember: vi.fn(() => null),
updateFriendRemark: vi.fn(() => true),
updateGroupRemark: vi.fn(() => true),
@@ -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');
});
});
+198 -12
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,
@@ -173,22 +186,35 @@ describe('apis/profile', () => {
it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => {
const bridge = mockBridge();
bridge.identity.findUinByUid.mockImplementation(
(uid: string) => uid === 'liker-uid' ? 20002 : 0,
);
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<Oidb0x7edResp>>({
body: {
userLikeInfos: [{
uid: 'u',
time: 1700000000n,
favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 },
voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n },
time: 1700000000,
favoriteInfo: { totalCount: 5, lastTime: 1, todayCount: 1 },
voteInfo: {
totalCount: 7,
newCount: 2,
newNearbyCount: 1,
lastVisitTime: 2,
userInfos: [{ uid: 'liker-uid', nick: '点赞者', count: 3 }],
},
}],
} as any,
})),
});
const out = await new ProfileApi(bridge as any).getLike();
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x7ed_13');
expect(out.favoriteInfo.total_count).toBe(5);
expect(out.voteInfo.total_count).toBe(7);
expect(out.voteInfo.userInfos).toEqual([
expect.objectContaining({ uid: 'liker-uid', uin: 20002, nick: '点赞者', count: 3 }),
]);
});
it('getProfileLike throws on empty result', async () => {
@@ -200,6 +226,60 @@ describe('apis/profile', () => {
await expect(new ProfileApi(bridge as any).getLike()).rejects.toThrow(/empty/);
});
it('getProfileLike resolves uncached liker uins through Identity.resolveUin', async () => {
const bridge = mockBridge();
bridge.identity.findUinByUid.mockReturnValue(null);
bridge.identity.resolveUin.mockImplementation(async (uid: string) => (
uid === 'stranger-uid' ? 30003 : null
));
const fetchUserProfileByUid = vi.fn();
(bridge.apis.contacts as any).fetchUserProfileByUid = fetchUserProfileByUid;
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<Oidb0x7edResp>>({
body: {
userLikeInfos: [{
uid: 'self-uid',
voteInfo: { userInfos: [{ uid: 'stranger-uid', nick: '陌生点赞者' }] },
}],
},
})),
});
const out = await new ProfileApi(bridge as any).getLike();
expect(bridge.identity.resolveUin).toHaveBeenCalledOnce();
expect(bridge.identity.resolveUin).toHaveBeenCalledWith('stranger-uid');
expect(fetchUserProfileByUid).not.toHaveBeenCalled();
expect(out.voteInfo.userInfos[0]?.uin).toBe(30003);
});
it('getProfileLike keeps uin=0 when Identity.resolveUin misses', async () => {
const bridge = mockBridge();
bridge.identity.findUinByUid.mockReturnValue(null);
bridge.identity.resolveUin.mockResolvedValue(null);
const fetchUserProfileByUid = vi.fn(async () => {
throw new Error('profile lookup failed');
});
(bridge.apis.contacts as any).fetchUserProfileByUid = fetchUserProfileByUid;
bridge.sendRawPacket.mockResolvedValueOnce({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<Oidb0x7edResp>>({
body: {
userLikeInfos: [{
uid: 'self-uid',
voteInfo: { userInfos: [{ uid: 'stranger-uid' }] },
}],
},
})),
});
const out = await new ProfileApi(bridge as any).getLike();
expect(out.voteInfo.userInfos[0]?.uin).toBe(0);
expect(fetchUserProfileByUid).not.toHaveBeenCalled();
});
it('getUnidirectionalFriendList parses the embedded JSON body', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce({
@@ -212,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);
@@ -35,28 +35,22 @@ function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
};
}
class RefreshingBridge extends Bridge {
readonly memberFetches: Array<{ groupId: number; force: boolean }> = [];
constructor(identity: IdentityService, private readonly refreshedMembers: GroupMemberInfo[]) {
super(identity);
// `fetchGroupMemberList` moved from Bridge onto `apis.contacts`
// under the #6 refactor — patch the method on the constructed
// ContactsApi instance to intercept calls + record them for
// assertions. (Direct property assignment works because the
// method is just an own property on the Api instance, not on
// its prototype.)
this.apis.contacts.fetchGroupMemberList = async (
groupId: number,
options: { force?: boolean } = {},
): Promise<GroupMemberInfo[]> => {
this.memberFetches.push({ groupId, force: Boolean(options.force) });
for (const member of this.refreshedMembers) {
this.identity.updateGroupMember(groupId, member);
}
return this.refreshedMembers;
};
}
function emptyProfile(uin: number, uid: string) {
return {
uin,
uid,
nickname: '',
remark: '',
qid: '',
sex: 'unknown',
age: 0,
sign: '',
avatar: '',
level: 0,
qidianMasterFlag: 0,
qidianCrewFlag: 0,
qidianCrewFlag2: 0,
};
}
function makePacket(): PacketInfo {
@@ -87,11 +81,21 @@ async function waitForEvent(events: GroupMemberJoin[]): Promise<GroupMemberJoin>
}
describe('Bridge group member identity refresh', () => {
it('forces a fresh member list before dispatching an unresolved join event', async () => {
it('resolves an unresolved join UIN via inbound profile before dispatch', async () => {
const member = makeGroupMember(22222, 'u_new_member');
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
const bridge = new RefreshingBridge(identity, [member]);
const bridge = new Bridge(identity);
const profileFetches: string[] = [];
const memberFetches: Array<{ groupId: number; force: boolean }> = [];
bridge.apis.contacts.fetchUserProfileByUid = async (uid) => {
profileFetches.push(uid);
return emptyProfile(member.uin, uid);
};
bridge.apis.contacts.fetchGroupMemberList = async (groupId, options = {}) => {
memberFetches.push({ groupId, force: Boolean(options.force) });
return [];
};
const seen: GroupMemberJoin[] = [];
bridge.registerCmd('test.member_join', () => [{
@@ -111,9 +115,9 @@ describe('Bridge group member identity refresh', () => {
bridge.onPacket(makePacket());
const event = await waitForEvent(seen);
expect(bridge.memberFetches).toEqual([{ groupId: GROUP_ID, force: true }]);
expect(profileFetches).toEqual([member.uid]);
expect(memberFetches.some((fetch) => fetch.force)).toBe(false);
expect(event.userUin).toBe(member.uin);
expect(event.operatorUin).toBe(member.uin);
});
it('remembers UID mappings from realtime request events', () => {
@@ -1,8 +1,10 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { DatalineMsgBody, DatalineTextMsg } from '@snowluma/proto-defs/dataline';
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
import type { FileExtra } from '@snowluma/proto-defs/message';
import { DATALINE_UIN_PHONE } from '@snowluma/protocol/dataline/device-contacts';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbOfflineFileFinalizeResp } from '@snowluma/proto-defs/oidb-actions/media';
@@ -201,4 +203,62 @@ describe('Bridge private media routing', () => {
expect(fileExtra?.file?.fileUuid).toBe('uuid-abc-123');
expect(fileExtra?.field6 ?? undefined).toBeUndefined();
});
it('sends my-device text through trans0x211 instead of ordinary c2c', async () => {
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
override async sendRawPacket(serviceCmd: string, body: Uint8Array): Promise<SendPacketResult> {
expect(serviceCmd).toBe('MessageSvc.PbSendMsg');
this.capturedBody = body;
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<SendMessageResponse>({
result: 0,
errMsg: '',
privateSequence: 88,
timestamp1: 1710000000,
})),
};
}
}
const bridge = new TestBridge(IdentityService.memory('10000'));
await bridge.apis.message.sendPrivate(DATALINE_UIN_PHONE, [{ type: 'text', text: 'hello phone' }]);
const request = protobuf_decode<SendMessageRequest>(bridge.capturedBody as Uint8Array);
expect(request?.routingHead?.trans0x211).toMatchObject({
ccCmd: 7,
uid: 'u_Wcc5rknRRqRO8y5gxMD6sA',
toUin: 10000n,
});
expect(request?.routingHead?.c2c ?? undefined).toBeUndefined();
const body = protobuf_decode<DatalineMsgBody>(request!.messageBody!.msgContent as Uint8Array);
expect(body?.subCmd).toBe(4);
expect(body?.header).toMatchObject({
srcAppId: 1,
dstAppId: 1001,
srcTerType: 1,
dstTerType: 2,
srcUin: 10000n,
dstUin: 10000n,
});
const text = protobuf_decode<DatalineTextMsg>(body!.generic!.buf as Uint8Array);
expect(new TextDecoder().decode(text!.items![0]!.text as Uint8Array)).toBe('hello phone');
});
it('rejects non-text my-device sends', async () => {
class TestBridge extends Bridge {
override async sendRawPacket(): Promise<SendPacketResult> {
throw new Error('should not send');
}
}
const bridge = new TestBridge(IdentityService.memory('10000'));
await expect(bridge.apis.message.sendPrivate(DATALINE_UIN_PHONE, [
{ type: 'image', url: 'file:///tmp/a.png' } as any,
])).rejects.toThrow('only accepts text');
});
});
@@ -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 () => {
@@ -0,0 +1,374 @@
// createFlashTask stages each source to disk and streams hash + sliceupload
// (#359). OIDB / sliceupload HTTP are mocked; the file bytes and Sha1StateV
// on the wire must still match the buffered flash helpers.
import { afterEach, beforeAll, afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { promises as fsp } from 'fs';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { createHash } from 'node:crypto';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { FlashSliceUploadBody, FlashSliceUploadResp } from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { ApplyFileset } from '@snowluma/protocol/oidb-services/flash-transfer/apply-fileset';
import { CommitFile } from '@snowluma/protocol/oidb-services/flash-transfer/commit-file';
import { CompleteFileset } from '@snowluma/protocol/oidb-services/flash-transfer/complete-fileset';
import { PrepareUpload } from '@snowluma/protocol/oidb-services/flash-transfer/prepare-upload';
import { ApplyUpload } from '@snowluma/protocol/oidb-services/flash-transfer/apply-upload';
import { SetFilesetStatus } from '@snowluma/protocol/oidb-services/flash-transfer/set-status';
import { computeSha1StateV } from '@snowluma/protocol/highway/sha1-stream';
import {
computeHashes,
FLASH_TRANSFER_INLINE_MAX_BYTES,
FLASH_TRANSFER_MAX_BYTES,
} from '@snowluma/protocol/highway/utils';
import * as stageMod from '@snowluma/protocol/highway/stage';
import * as hashMod from '@snowluma/protocol/highway/hash-file';
import { FlashTransferApi } from '../src/bridge/apis/flash-transfer';
import { mockBridge } from './actions/_helpers';
const FILESET = '8e40afa1-829d-498b-852f-092394ddb31f';
const SLICE_URL = 'https://multimedia.qfile.qq.com/sliceupload';
const SLICE = 1024 * 1024;
const originalFetch = globalThis.fetch;
let dir: string;
beforeAll(async () => {
dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-flash-create-'));
});
afterAll(async () => {
await fsp.rm(dir, { recursive: true, force: true });
});
afterEach(() => {
globalThis.fetch = originalFetch;
vi.restoreAllMocks();
});
function writeSrc(name: string, bytes: Uint8Array): string {
const file = path.join(dir, name);
fs.writeFileSync(file, bytes);
return file;
}
function synth(size: number, seed = 7): Uint8Array {
const b = new Uint8Array(size);
for (let i = 0; i < size; i++) b[i] = (i * 131 + seed) & 0xff;
return b;
}
function toU8(body: unknown): Uint8Array {
if (body instanceof Uint8Array) return body;
if (Buffer.isBuffer(body)) return new Uint8Array(body);
throw new Error(`unexpected fetch body: ${typeof body}`);
}
function installSliceuploadOk(): FlashSliceUploadBody[] {
const calls: FlashSliceUploadBody[] = [];
globalThis.fetch = vi.fn(async (input, init) => {
const url = String(input);
if (url !== SLICE_URL) throw new Error(`unexpected fetch ${url}`);
calls.push(protobuf_decode<FlashSliceUploadBody>(toU8(init?.body)));
return new Response(
Buffer.from(protobuf_encode<FlashSliceUploadResp>({ status: 'success' })),
{ status: 200 },
);
}) as typeof fetch;
return calls;
}
function mainSlices(calls: FlashSliceUploadBody[]): FlashSliceUploadBody[] {
return calls.filter((c) => c.appid === 14901);
}
function stubOidb(): void {
vi.spyOn(ApplyFileset, 'invoke').mockResolvedValue({ filesetUuid: FILESET });
vi.spyOn(CommitFile, 'invoke').mockResolvedValue({});
vi.spyOn(CompleteFileset, 'invoke').mockResolvedValue(undefined);
vi.spyOn(PrepareUpload, 'invoke').mockResolvedValue('rkey-main');
vi.spyOn(ApplyUpload, 'invoke').mockResolvedValue(undefined);
vi.spyOn(SetFilesetStatus, 'invoke').mockResolvedValue(undefined);
}
function api(): FlashTransferApi {
return new FlashTransferApi(mockBridge() as never);
}
describe('FlashTransferApi.createFlashTask — disk streaming (#359)', () => {
beforeEach(() => {
stubOidb();
});
it('stages a local file, commits metadata, and sliceuploads the disk bytes with flash Sha1StateV', async () => {
const bytes = synth(200);
const file = writeSrc('clip.mp4', bytes);
const hashes = computeHashes(bytes);
const sha1StateV = computeSha1StateV(bytes, 1, SLICE);
const stageSpy = vi.spyOn(stageMod, 'stageSourceToDisk');
const slices = installSliceuploadOk();
await expect(api().createFlashTask(file)).resolves.toEqual({ filesetId: FILESET });
expect(stageSpy).toHaveBeenCalledWith(file, FLASH_TRANSFER_MAX_BYTES);
expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
fileName: 'clip.mp4',
origName: 'clip.mp4',
fileSize: 200,
typeCode: 7,
uploader: { uin: '10001', nickname: 'self-nick', uid: 'self-uid' },
}));
expect(CommitFile.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
filesetUuid: FILESET,
entries: [expect.objectContaining({
fileName: 'clip.mp4',
fileSize: 200,
fileIndex: 1,
formatCode: 2,
})],
}));
expect(CompleteFileset.invoke).toHaveBeenCalledWith(expect.anything(), { filesetUuid: FILESET });
const uploaded = mainSlices(slices);
expect(uploaded).toHaveLength(1);
expect(uploaded[0]!.payload?.rkey).toBe('rkey-main');
expect(uploaded[0]!.payload?.start).toBe(0);
expect(uploaded[0]!.payload?.end).toBe(199);
expect(Buffer.from(uploaded[0]!.payload!.chunk!).equals(Buffer.from(bytes))).toBe(true);
expect(Buffer.from(uploaded[0]!.payload!.sha1!).equals(
createHash('sha1').update(Buffer.from(bytes)).digest(),
)).toBe(true);
expect(uploaded[0]!.payload!.sha1StateV!.state).toHaveLength(1);
expect(Buffer.from(uploaded[0]!.payload!.sha1StateV!.state![0]!).equals(Buffer.from(sha1StateV[0]!))).toBe(true);
expect(Buffer.from(uploaded[0]!.payload!.sha1StateV!.state![0]!).equals(Buffer.from(hashes.sha1))).toBe(true);
expect(SetFilesetStatus.invoke).toHaveBeenCalledWith(expect.anything(), { filesetUuid: FILESET });
});
it('caps inline base64 at the RAM-decode ceiling, not the 4 GiB disk ceiling', async () => {
const bytes = synth(32, 9);
const source = `base64://${Buffer.from(bytes).toString('base64')}`;
const stageSpy = vi.spyOn(stageMod, 'stageSourceToDisk');
installSliceuploadOk();
await api().createFlashTask(source);
expect(stageSpy).toHaveBeenCalledWith(source, FLASH_TRANSFER_INLINE_MAX_BYTES);
});
it('rejects an empty file before applying a fileset and still releases the stage', async () => {
const file = writeSrc('empty.bin', new Uint8Array(0));
const cleanups: Array<ReturnType<typeof vi.fn>> = [];
const actualStage = stageMod.stageSourceToDisk;
vi.spyOn(stageMod, 'stageSourceToDisk').mockImplementation(async (source, maxBytes) => {
const staged = await actualStage(source, maxBytes);
const cleanup = vi.fn(async () => staged.cleanup());
cleanups.push(cleanup);
return { ...staged, cleanup };
});
await expect(api().createFlashTask(file)).rejects.toThrow(/empty/i);
expect(ApplyFileset.invoke).not.toHaveBeenCalled();
expect(cleanups[0]).toHaveBeenCalled();
});
it('releases staged temps when apply-fileset fails', async () => {
const file = writeSrc('fail.mp4', synth(40, 3));
const cleanups: Array<ReturnType<typeof vi.fn>> = [];
const actualStage = stageMod.stageSourceToDisk;
vi.spyOn(stageMod, 'stageSourceToDisk').mockImplementation(async (source, maxBytes) => {
const staged = await actualStage(source, maxBytes);
const cleanup = vi.fn(async () => staged.cleanup());
cleanups.push(cleanup);
return { ...staged, cleanup };
});
vi.mocked(ApplyFileset.invoke).mockRejectedValueOnce(new Error('oidb down'));
await expect(api().createFlashTask(file)).rejects.toThrow('oidb down');
expect(cleanups[0]).toHaveBeenCalled();
});
it('skips sliceupload when prepare-upload reports a seconds-pass', async () => {
const file = writeSrc('hit.mp4', synth(80, 11));
vi.mocked(PrepareUpload.invoke).mockImplementation(async (_ctx, p) => (
p.thumbType ? 'thumb-rkey' : null
));
const slices = installSliceuploadOk();
await api().createFlashTask(file);
expect(mainSlices(slices)).toHaveLength(0);
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);
const sha1StateV = computeSha1StateV(bytes, 2, SLICE);
const slices = installSliceuploadOk();
await api().createFlashTask(file);
const uploaded = mainSlices(slices);
expect(uploaded).toHaveLength(2);
expect(uploaded[0]!.payload?.start).toBe(0);
expect(uploaded[0]!.payload?.end).toBe(SLICE - 1);
expect(uploaded[1]!.payload?.start).toBe(SLICE);
expect(uploaded[1]!.payload?.end).toBe(SLICE + 79);
expect(Buffer.from(uploaded[0]!.payload!.chunk!).equals(Buffer.from(bytes.subarray(0, SLICE)))).toBe(true);
expect(Buffer.from(uploaded[1]!.payload!.chunk!).equals(Buffer.from(bytes.subarray(SLICE)))).toBe(true);
expect(uploaded[0]!.payload!.sha1StateV!.state).toHaveLength(2);
expect(Buffer.from(uploaded[0]!.payload!.sha1StateV!.state![0]!).equals(Buffer.from(sha1StateV[0]!))).toBe(true);
expect(Buffer.from(uploaded[0]!.payload!.sha1StateV!.state![1]!).equals(Buffer.from(sha1StateV[1]!))).toBe(true);
expect(Buffer.from(uploaded[1]!.payload!.sha1StateV!.state![1]!).equals(
createHash('sha1').update(Buffer.from(bytes)).digest(),
)).toBe(true);
});
it('commits every fileset entry once, then sliceuploads each file from disk', async () => {
const a = synth(50, 1);
const b = synth(70, 2);
const fileA = writeSrc('a.mp4', a);
const fileB = writeSrc('b.zip', b);
const slices = installSliceuploadOk();
await api().createFlashTask([fileA, fileB]);
expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
fileName: 'a.mp4等2个文件',
fileSize: 120,
}));
const commit = vi.mocked(CommitFile.invoke).mock.calls[0]![1];
expect(commit.entries).toHaveLength(2);
expect(commit.entries[0]).toEqual(expect.objectContaining({
fileName: 'a.mp4', fileSize: 50, fileIndex: 1, formatCode: 2,
}));
expect(commit.entries[1]).toEqual(expect.objectContaining({
fileName: 'b.zip', fileSize: 70, fileIndex: 2, formatCode: 4,
}));
const uploaded = mainSlices(slices);
expect(uploaded).toHaveLength(2);
expect(Buffer.from(uploaded[0]!.payload!.chunk!).equals(Buffer.from(a))).toBe(true);
expect(Buffer.from(uploaded[1]!.payload!.chunk!).equals(Buffer.from(b))).toBe(true);
});
it('uses the optional name as the fileset title and keeps real file names on commit (#363)', async () => {
const file = writeSrc('clip.mp4', synth(40, 3));
installSliceuploadOk();
await api().createFlashTask(file, '自定义名称');
expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
fileName: '自定义名称',
origName: '自定义名称',
fileSize: 40,
}));
expect(CommitFile.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
entries: [expect.objectContaining({ fileName: 'clip.mp4', fileSize: 40 })],
}));
});
it('uses the optional name as the multi-file fileset title (#363)', async () => {
const fileA = writeSrc('a.mp4', synth(50, 1));
const fileB = writeSrc('b.zip', synth(70, 2));
installSliceuploadOk();
await api().createFlashTask([fileA, fileB], '相册');
expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
fileName: '相册',
origName: '相册',
fileSize: 120,
}));
const commit = vi.mocked(CommitFile.invoke).mock.calls[0]![1];
expect(commit.entries[0]).toEqual(expect.objectContaining({ fileName: 'a.mp4' }));
expect(commit.entries[1]).toEqual(expect.objectContaining({ fileName: 'b.zip' }));
});
it('uses a per-file name on commit and keeps the fileset title separate (#361)', async () => {
const file = writeSrc('uuid__clip.mp4', synth(40, 3));
installSliceuploadOk();
await api().createFlashTask({ file, name: 'clip.mp4' }, '自定义名称');
expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
fileName: '自定义名称',
origName: '自定义名称',
}));
expect(CommitFile.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
entries: [expect.objectContaining({ fileName: 'clip.mp4', origName: 'clip.mp4', fileSize: 40 })],
}));
});
it('uses per-file names in a mixed files list (#361)', async () => {
const fileA = writeSrc('a-id__a.mp4', synth(50, 1));
const fileB = writeSrc('b.zip', synth(70, 2));
installSliceuploadOk();
await api().createFlashTask([{ file: fileA, name: 'a.mp4' }, fileB]);
expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
fileName: 'a.mp4等2个文件',
fileSize: 120,
}));
const commit = vi.mocked(CommitFile.invoke).mock.calls[0]![1];
expect(commit.entries[0]).toEqual(expect.objectContaining({ fileName: 'a.mp4' }));
expect(commit.entries[1]).toEqual(expect.objectContaining({ fileName: 'b.zip' }));
});
it('falls back to the path basename when the per-file name is blank (#361)', async () => {
const file = writeSrc('clip.mp4', synth(32, 9));
installSliceuploadOk();
await api().createFlashTask({ file, name: ' ' });
expect(CommitFile.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
entries: [expect.objectContaining({ fileName: 'clip.mp4' })],
}));
});
it('falls back to the filename title when name is blank (#363)', async () => {
const file = writeSrc('clip.mp4', synth(32, 9));
installSliceuploadOk();
await api().createFlashTask(file, ' ');
expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
fileName: 'clip.mp4',
origName: 'clip.mp4',
}));
});
it('rejects a source that mutates between hashing and upload', async () => {
const file = writeSrc('mut.mp4', synth(90, 5));
const actualHash = hashMod.hashFlashFileStreaming;
vi.spyOn(hashMod, 'hashFlashFileStreaming').mockImplementation(async (filePath) => {
const hashes = await actualHash(filePath);
await fsp.appendFile(filePath, Buffer.from([0xff]));
return hashes;
});
installSliceuploadOk();
await expect(api().createFlashTask(file)).rejects.toThrow(/changed during send/i);
});
});
@@ -0,0 +1,99 @@
// Regression for #364: create_flash_task can return before 0x93d4 fills
// the main-file fileId. get_flash_file_url / download_fileset poll 0x93d4
// while that field is empty, then take the normal 0x12a9 sub=200 path.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { GetDownloadUrl } from '@snowluma/protocol/oidb-services/flash-transfer/get-download-url';
import { GetFlashDownload } from '@snowluma/protocol/oidb-services/flash-transfer/get-flash-download';
import { FlashTransferApi } from '../src/bridge/apis/flash-transfer';
const FILESET = '8982c4b5-195c-49e2-a3ab-478b32af234c';
const FILE_ID = 'main-file-id';
const URL = 'https://multimedia.qfile.qq.com/download?appid=14901&fileid=main-file-id';
function meta(fileId: string, fileIndex = 1): GetDownloadUrl.FileMeta {
return {
fileIndex,
fileId,
filesetUuid: FILESET,
fileUuid: 'file-uuid',
fileName: 'sl364-hitpass.txt',
fileSize: 41,
};
}
function api(): FlashTransferApi {
return new FlashTransferApi({} as never);
}
describe('FlashTransferApi.getFlashFileUrl — empty fileId poll (#364)', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
it('does not wait when 0x93d4 already has the main-file fileId', async () => {
const lookup = vi.spyOn(GetDownloadUrl, 'invoke').mockResolvedValue([meta(FILE_ID)]);
const download = vi.spyOn(GetFlashDownload, 'invoke').mockResolvedValue(URL);
await expect(api().getFlashFileUrl(FILESET)).resolves.toBe(URL);
expect(lookup).toHaveBeenCalledOnce();
expect(download).toHaveBeenCalledOnce();
expect(download.mock.calls[0]![1]).toMatchObject({ fileId: FILE_ID, filesetUuid: FILESET });
});
it('re-queries 0x93d4 after an empty fileId and then takes the download path', async () => {
const lookup = vi.spyOn(GetDownloadUrl, 'invoke')
.mockResolvedValueOnce([meta('')])
.mockResolvedValueOnce([meta(FILE_ID)]);
const download = vi.spyOn(GetFlashDownload, 'invoke').mockResolvedValue(URL);
const pending = api().getFlashFileUrl(FILESET);
await vi.advanceTimersByTimeAsync(1000);
await expect(pending).resolves.toBe(URL);
expect(lookup).toHaveBeenCalledTimes(2);
expect(download).toHaveBeenCalledOnce();
expect(download.mock.calls[0]![1]).toMatchObject({ fileId: FILE_ID });
});
it('shares the same poll for download_fileset', async () => {
vi.spyOn(GetDownloadUrl, 'invoke')
.mockResolvedValueOnce([meta('')])
.mockResolvedValueOnce([meta(FILE_ID)]);
vi.spyOn(GetFlashDownload, 'invoke').mockResolvedValue(URL);
const pending = api().downloadFileset(FILESET);
await vi.advanceTimersByTimeAsync(1000);
await expect(pending).resolves.toEqual({
url: URL,
fileName: 'sl364-hitpass.txt',
fileSize: 41,
});
});
it('keeps the original error when fileId stays empty through the budget', async () => {
const lookup = vi.spyOn(GetDownloadUrl, 'invoke').mockResolvedValue([meta('')]);
const download = vi.spyOn(GetFlashDownload, 'invoke').mockResolvedValue(URL);
const pending = api().getFlashFileUrl(FILESET);
const expectFailed = expect(pending).rejects.toThrow('get_flash_file_url: no download url available');
await vi.advanceTimersByTimeAsync(20_000);
await expectFailed;
expect(lookup.mock.calls.length).toBeGreaterThan(1);
expect(download).not.toHaveBeenCalled();
});
it('does not re-query 0x93d4 when fileId is present but 0x12a9 returns no url', async () => {
const lookup = vi.spyOn(GetDownloadUrl, 'invoke').mockResolvedValue([meta(FILE_ID)]);
vi.spyOn(GetFlashDownload, 'invoke').mockResolvedValue(null);
await expect(api().getFlashFileUrl(FILESET)).rejects.toThrow('get_flash_file_url: no download url available');
expect(lookup).toHaveBeenCalledOnce();
});
});
+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');
});
});
+11 -1
View File
@@ -3,7 +3,7 @@ import os from 'os';
import path from 'path';
import { pathToFileURL } from 'url';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { loadBinarySource, resolveLocalFilePath } from '@snowluma/protocol/highway/utils';
import { guessFileNameFromUrl, loadBinarySource, resolveLocalFilePath } from '@snowluma/protocol/highway/utils';
describe('highway source paths', () => {
it('normalizes file URLs with an extra leading slash on POSIX', () => {
@@ -12,6 +12,16 @@ describe('highway source paths', () => {
.toBe('/AstrBot/data/plugin/cache/BV-test.mp4');
});
it('percent-decodes a URL basename used as the upload filename (#354)', () => {
expect(guessFileNameFromUrl(
'file:///D:/test/%E6%B5%8B%E8%AF%95%E6%96%87%E4%BB%B6.xlsx',
)).toBe('测试文件.xlsx');
expect(guessFileNameFromUrl('https://cdn.example/a/%E4%B8%AD%E6%96%87.png?x=1'))
.toBe('中文.png');
expect(guessFileNameFromUrl('https://cdn.example/plain.bin')).toBe('plain.bin');
expect(guessFileNameFromUrl('https://cdn.example/%ZZ.xlsx')).toBe('%ZZ.xlsx');
});
it('loads encoded file URLs from the local filesystem', async () => {
const filePath = path.join(os.tmpdir(), `snowluma video ${process.pid}-${Date.now()}.txt`);
fs.writeFileSync(filePath, 'ok');
+65 -1
View File
@@ -11,8 +11,9 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
import { randomUUID } from 'crypto';
import { hashFileStreaming } from '@snowluma/protocol/highway/hash-file';
import { hashFileStreaming, hashFlashFileStreaming } from '@snowluma/protocol/highway/hash-file';
import { computeHashes, computeMd5 } from '@snowluma/protocol/highway/utils';
import { computeSha1StateV } from '@snowluma/protocol/highway/sha1-stream';
import { computeVideoSha1Blocks } from '@snowluma/protocol/highway/video-upload';
const MB = 1024 * 1024;
@@ -90,3 +91,66 @@ describe('hashFileStreaming ≡ buffered computeHashes + computeVideoSha1Blocks
expect(eq(streamed.headMd5!, computeMd5(new Uint8Array(0)))).toBe(true);
});
});
// Flash sliceupload Sha1StateV is NOT video sha1Blocks. Both snapshot
// un-finalized SHA1 at 1 MiB boundaries, but flash omits the un-finalized
// snapshot of the last full slice — that slot is the finalized whole-file
// SHA1. Reusing sha1Blocks when size % 1 MiB === 0 ships an extra state
// and the server rejects the upload.
describe('hashFlashFileStreaming ≡ buffered computeHashes + computeSha1StateV', () => {
let dir: string;
beforeAll(async () => { dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-flash-hash-')); });
afterAll(async () => { await fsp.rm(dir, { recursive: true, force: true }); });
const SIZES = [0, 1, 63, 64, 65, MB - 1, MB, MB + 1, 2 * MB, 2 * MB + 123];
for (const size of SIZES) {
it(`size=${size}: md5 / sha1 / Sha1StateV match the buffered flash helpers`, async () => {
const data = synth(size);
const file = path.join(dir, `${randomUUID()}.bin`);
fs.writeFileSync(file, data);
const streamed = await hashFlashFileStreaming(file);
const buffered = computeHashes(data);
const sliceCount = Math.ceil(size / MB);
const refState = computeSha1StateV(data, sliceCount, MB);
expect(eq(streamed.md5, buffered.md5)).toBe(true);
expect(eq(streamed.sha1, buffered.sha1)).toBe(true);
expect(streamed.md5Hex).toBe(buffered.md5Hex);
expect(streamed.sha1Hex).toBe(buffered.sha1Hex);
expect(streamed.sliceCount).toBe(sliceCount);
expect(streamed.sha1StateV.length).toBe(refState.length);
for (let i = 0; i < refState.length; i++) {
expect(eq(streamed.sha1StateV[i]!, refState[i]!)).toBe(true);
}
});
}
it('exact 1 MiB is not video sha1Blocks (no extra un-finalized last-slice state)', async () => {
const data = synth(MB);
const file = path.join(dir, `${randomUUID()}.bin`);
fs.writeFileSync(file, data);
const flash = await hashFlashFileStreaming(file);
const video = await hashFileStreaming(file);
expect(flash.sha1StateV.length).toBe(1);
expect(video.sha1Blocks.length).toBe(2);
expect(eq(flash.sha1StateV[0]!, video.sha1Blocks[1]!)).toBe(true);
expect(eq(flash.sha1StateV[0]!, video.sha1Blocks[0]!)).toBe(false);
});
it('exact 2 MiB: flash has 2 states, video sha1Blocks has 3', async () => {
const data = synth(2 * MB);
const file = path.join(dir, `${randomUUID()}.bin`);
fs.writeFileSync(file, data);
const flash = await hashFlashFileStreaming(file);
const video = await hashFileStreaming(file);
expect(flash.sliceCount).toBe(2);
expect(flash.sha1StateV.length).toBe(2);
expect(video.sha1Blocks.length).toBe(3);
expect(eq(flash.sha1StateV[0]!, video.sha1Blocks[0]!)).toBe(true);
expect(eq(flash.sha1StateV[1]!, video.sha1Blocks[2]!)).toBe(true);
});
});
@@ -2,10 +2,12 @@
//
// 方案 3(#211):单连接、按 offset 顺序、流水线上传,跨 chunk 复用同一个
// TCP 连接(HTTP keep-alive)。要点:
// - 顺序发送 → 天然保序,避开 QQ highway 对乱序块的 error_code=102902;
// - 顺序发送 → 减少 QQ highway 对重叠块的 NeedDelayRetry(error_code=102902);
// - 复用连接 → TCP 拥塞窗口全程保持,省掉每块新建连接的 slow-start。
// 边缘节点可能在响应后 FIN(#118);此时自适应地丢弃 socket + 重连 + 重发
// 同一块(重发幂等),最坏退化成“每块一连接”,不比旧实现差,且仍然保序。
// 102902 / 302902 不是致命拒绝(#352):官方 BDH 走 NeedDelayRetry,延迟后
// 换连接重发同一 offset。
//
// 本测试用两种 mock 服务端行为锁定这套自适应逻辑:
// - keepalive:每个 POST 回一个响应,连接保持 → 整个文件 1 个连接;
@@ -36,10 +38,21 @@ function buildEmptyHighwayResponseFrame(): Buffer {
return frame;
}
// errorCode 帧:RespDataHighwayHead.field3 (errorCode) = 921。tag(field3,
// varint)=0x18,varint(921)=0x99 0x07。定义即拒绝(不重试)。
function buildErrorCodeFrame(): Buffer {
const head = Buffer.from([0x18, 0x99, 0x07]);
function encodeVarint(n: number): number[] {
const bytes: number[] = [];
let value = n >>> 0;
while (value > 0x7f) {
bytes.push((value & 0x7f) | 0x80);
value >>>= 7;
}
bytes.push(value);
return bytes;
}
// errorCode 帧:RespDataHighwayHead.field3 (errorCode)。tag(field3, varint)=0x18。
// 921 是定义即拒绝;102902 / 302902 是 QQ BDH 的 NeedDelayRetry(#352)。
function buildErrorCodeFrame(errorCode = 921): Buffer {
const head = Buffer.from([0x18, ...encodeVarint(errorCode)]);
const frame = Buffer.alloc(9 + head.length + 1);
frame[0] = 0x28;
frame.writeUInt32BE(head.length, 1);
@@ -75,6 +88,7 @@ class FakeSocket extends EventEmitter {
private readonly failOnPost = -1,
private readonly truncateOnPost = -1,
private readonly errorAfterPartialOnPost = -1,
private readonly frameOnPost: Readonly<Record<number, Buffer>> = {},
) {
super();
}
@@ -135,7 +149,7 @@ class FakeSocket extends EventEmitter {
this.emit('close');
return;
}
this.emit('data', httpWrap(this.responseFrame));
this.emit('data', httpWrap(this.frameOnPost[thisPost] ?? this.responseFrame));
if (this.mode === 'closeafter') {
this.readableEnded = true;
this.writable = false;
@@ -288,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' },
@@ -660,4 +695,69 @@ describe('uploadHighwayHttp single-connection pipelined upload (#211)', () => {
// Definitive reject on block 0 → stop immediately, don't PUT later blocks.
expect(source.reads.length).toBeLessThan(3);
});
it('delay-retries 102902 on the same offset, then completes (#352)', async () => {
// QQ BDH NeedDelayRetry: 102902 is backpressure, not a fatal reject.
// Official client delays, switches sender, and re-PUTs the same piece.
installFactory((idx) => idx === 0
? new FakeSocket(buildErrorCodeFrame(102902), 'keepalive')
: new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'));
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE));
await uploadHighwayHttp(
makeBridge(), makeSession(), 71, new BufferChunkSource(bytes),
new Uint8Array(16), new Uint8Array(0),
);
expect(createConnectionMock).toHaveBeenCalledTimes(2);
const messages = highwayTrace(entries).map((entry) => entry.message);
expect(messages).toEqual(expect.arrayContaining([
expect.stringContaining('branch=chunk_delay_retry offset=0'),
expect.stringContaining('errorCode=102902'),
expect.stringContaining('outcome=completed reason=upload_complete'),
]));
} finally {
unsubscribe();
}
});
it('delay-retries 302902 the same way as 102902', async () => {
installFactory((idx) => idx === 0
? new FakeSocket(buildErrorCodeFrame(302902), 'keepalive')
: new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'));
await uploadHighwayHttp(
makeBridge(), makeSession(), 71,
new BufferChunkSource(new Uint8Array(512 * 1024)),
new Uint8Array(16), new Uint8Array(0),
);
expect(createConnectionMock).toHaveBeenCalledTimes(2);
});
it('delay-retries 102902 on a later in-order block after keep-alive was already warm (#352 shape)', async () => {
// Mirrors the report: sequential upload is healthy, then a later offset
// returns 102902. Recovery must re-PUT that offset, not abort the file.
installFactory((idx) => idx === 0
? new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive', -1, -1, -1, {
3: buildErrorCodeFrame(102902),
})
: new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'));
const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE)); // 3 blocks
await uploadHighwayHttp(
makeBridge(), makeSession(), 71, new BufferChunkSource(bytes),
new Uint8Array(16), new Uint8Array(0),
);
expect(createConnectionMock).toHaveBeenCalledTimes(2);
});
it('exhausts delay-retries when 102902 keeps coming back', async () => {
installFactory(() => new FakeSocket(buildErrorCodeFrame(102902), 'keepalive'));
await expect(uploadHighwayHttp(
makeBridge(), makeSession(), 71,
new BufferChunkSource(new Uint8Array(16)),
new Uint8Array(16), new Uint8Array(0),
)).rejects.toThrow(/error_code=102902/);
expect(createConnectionMock.mock.calls.length).toBeGreaterThan(1);
});
});
@@ -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];
+289 -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,
@@ -786,10 +806,10 @@ describe('IdentityService', () => {
['forget group', () => identity.forgetGroup(GROUP_ID)],
['group members', () => identity.rememberGroupMembers(GROUP_ID, [])],
['user profile', () => identity.rememberUserProfile(profile)],
['group invite sequence', () => identity.rememberGroupInviteCardSequence(GROUP_ID, 123)],
['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 })],
];
@@ -804,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');
@@ -902,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();
@@ -912,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 () => {
@@ -974,3 +1114,149 @@ describe('IdentityService.resolveUid', () => {
expect(fetchProfile).not.toHaveBeenCalled();
});
});
describe('IdentityService inbound UID→UIN', () => {
function makeProfile(uin: number, uid: string): UserProfileInfo {
return {
uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
qidianMasterFlag: 0, qidianCrewFlag: 0, qidianCrewFlag2: 0,
};
}
it('findUinByUid treats a numeric uid as that uin without consulting maps', () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberRequestIdentity({ uid: '22999', uin: 11111 });
expect(identity.findUinByUid('22999')).toBe(22999);
expect(identity.findUinByUid('0')).toBeNull();
expect(identity.findUinByUid('')).toBeNull();
});
it('returns the cached uin without invoking fetchProfileByUid', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberRequestIdentity({ uid: 'u_known', uin: 12345 });
const fetchProfileByUid = vi.fn(async () => makeProfile(999, 'should-not-be-used'));
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid,
});
await expect(identity.resolveUin('u_known')).resolves.toBe(12345);
expect(fetchProfileByUid).not.toHaveBeenCalled();
});
it('does not call fetchProfileByUid for a numeric uid', async () => {
const identity = IdentityService.memory(SELF_UIN);
const fetchProfileByUid = vi.fn(async () => makeProfile(1, '1'));
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid,
});
await expect(identity.resolveUin('22999')).resolves.toBe(22999);
expect(fetchProfileByUid).not.toHaveBeenCalled();
});
it('falls back to fetchProfileByUid on miss and returns the profile uin', async () => {
const identity = IdentityService.memory(SELF_UIN);
const fetchProfileByUid = vi.fn(async (uid: string) => {
identity.rememberUserProfile(makeProfile(88888, uid));
return makeProfile(88888, uid);
});
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid,
});
await expect(identity.resolveUin('u_stranger')).resolves.toBe(88888);
expect(fetchProfileByUid).toHaveBeenCalledWith('u_stranger');
});
it('returns the profile uin even when the fetcher forgets to remember', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid: async () => makeProfile(77777, 'u_forgetful'),
});
await expect(identity.resolveUin('u_forgetful')).resolves.toBe(77777);
});
it('does not pull a group member list even when groupId is provided', async () => {
const identity = IdentityService.memory(SELF_UIN);
const fetchGroupMemberList = vi.fn(async () => []);
const fetchProfileByUid = vi.fn(async () => makeProfile(66666, 'u_invitee'));
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid,
fetchGroupMemberList,
});
await expect(identity.resolveUin('u_invitee', GROUP_ID)).resolves.toBe(66666);
expect(fetchGroupMemberList).not.toHaveBeenCalled();
expect(fetchProfileByUid).toHaveBeenCalledWith('u_invitee');
});
it('does not pull a group member list when the inbound fetcher is absent', async () => {
const identity = IdentityService.memory(SELF_UIN);
const fetchGroupMemberList = vi.fn(async () => []);
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchGroupMemberList,
});
await expect(identity.resolveUin('u_none', GROUP_ID)).resolves.toBeNull();
expect(fetchGroupMemberList).not.toHaveBeenCalled();
});
it('uses a mapping remembered before the inbound fetcher throws', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid: async (uid: string) => {
identity.rememberUserProfile(makeProfile(55555, uid));
throw new Error('transport reset after remember');
},
});
await expect(identity.resolveUin('u_remembered')).resolves.toBe(55555);
});
it('returns null on miss, fetcher error, empty profile, or missing inbound fetcher', async () => {
const identity = IdentityService.memory(SELF_UIN);
await expect(identity.resolveUin('u_none')).resolves.toBeNull();
identity.setFetcher({ fetchProfile: async () => makeProfile(0, '') });
await expect(identity.resolveUin('u_none')).resolves.toBeNull();
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid: async () => makeProfile(0, 'u_none'),
});
await expect(identity.resolveUin('u_none')).resolves.toBeNull();
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid: async () => {
throw new Error('oidb down');
},
});
await expect(identity.resolveUin('u_none')).resolves.toBeNull();
});
it('does not enter Identity degraded when the inbound fetcher throws', async () => {
const dbPath = tempDbPath('inbound-fetch-throw');
const identity = new IdentityService(SELF_UIN, dbPath);
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid: async () => {
throw new Error('oidb down');
},
});
await expect(identity.resolveUin('u_none')).resolves.toBeNull();
expect(identity.persistenceStatus.state).toBe('healthy');
expect(identity.persistenceStatus.pendingWrites).toBe(0);
identity.close();
});
});
+33 -16
View File
@@ -494,8 +494,8 @@ describe('parseMsgPush Event0x210 subType=364 (friend remark synchronization)',
const pipeline = new IncomingPacketPipeline({
identity,
events: new BridgeEventBus(),
refreshMemberCache: vi.fn(async () => false),
resolveStrangerProfile: vi.fn(async () => null),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
@@ -917,11 +917,8 @@ describe('parseMsgPush PkgType 85 (bot self-joined a group)', () => {
});
describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache fresh', () => {
// Regression for #93: a member promoted to admin kept reading back as
// `member` via get_group_member_info because the admin-change push only
// emitted the notice and never patched the cached role — and that API
// serves straight from the cache (no per-read refetch, on purpose, to
// dodge risk-control). The decoder now mirrors the role into the cache.
// Regression for #93: get_group_member_info serves the cache. Role
// patch is IncomingPacketPipeline observation, not Decoder.
function makeGroupAdminPacket(adminUid: string, set: boolean, fromUin = GROUP_ID): PacketInfo {
const extra = { adminUid };
const content = protobuf_encode<GroupAdmin>({
@@ -942,7 +939,19 @@ describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache
};
}
it('promotes a cached member to admin in the identity cache (and emits set=true)', () => {
async function processAdmin(identity: IdentityService, packet: PacketInfo): Promise<void> {
const pipeline = new IncomingPacketPipeline({
identity,
events: new BridgeEventBus(),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
await pipeline.process(packet);
}
it('Decoder emits the event without writing Identity', () => {
const member = makeGroupMember(22222, 'u_member');
const identity = makeIdentity([member]);
@@ -951,36 +960,44 @@ describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache
expect(event.kind).toBe('group_admin');
expect(event.userUin).toBe(member.uin);
expect(event.set).toBe(true);
expect(identity.findGroupMember(GROUP_ID, member.uin)?.role).toBe('member');
});
it('promotes a cached member to admin at the packet-pipeline boundary', async () => {
const member = makeGroupMember(22222, 'u_member');
const identity = makeIdentity([member]);
await processAdmin(identity, makeGroupAdminPacket(member.uid, true));
expect(identity.findGroupMember(GROUP_ID, member.uin)?.role).toBe('admin');
});
it('demotes a cached admin back to member on an unset push', () => {
it('demotes a cached admin back to member on an unset push', async () => {
const admin = { ...makeGroupMember(22222, 'u_admin'), role: 'admin' };
const identity = makeIdentity([admin]);
const [event] = parseMsgPush(makeGroupAdminPacket(admin.uid, false), identity) as GroupAdminEvent[];
await processAdmin(identity, makeGroupAdminPacket(admin.uid, false));
expect(event.set).toBe(false);
expect(identity.findGroupMember(GROUP_ID, admin.uin)?.role).toBe('member');
});
it('never downgrades the owner', () => {
it('never downgrades the owner', async () => {
const owner = { ...makeGroupMember(22222, 'u_owner'), role: 'owner' };
const identity = makeIdentity([owner]);
parseMsgPush(makeGroupAdminPacket(owner.uid, false), identity);
await processAdmin(identity, makeGroupAdminPacket(owner.uid, false));
expect(identity.findGroupMember(GROUP_ID, owner.uin)?.role).toBe('owner');
});
it('is a no-op (no throw, no phantom member) when the target is not cached', () => {
it('is a no-op (no throw, no phantom member) when the target is not cached', async () => {
const identity = makeIdentity();
const [event] = parseMsgPush(makeGroupAdminPacket('u_unknown', true), identity) as GroupAdminEvent[];
await processAdmin(identity, makeGroupAdminPacket('u_unknown', true));
expect(event.kind).toBe('group_admin');
// fromUin (the group id) is the resolve fallback — it must not be
// confused for a real, promotable member.
expect(event.userUin).toBe(0);
expect(identity.findGroupMember(GROUP_ID, GROUP_ID)).toBeNull();
});
});
@@ -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());
@@ -196,4 +312,38 @@ describe('NotificationManager — debounce integration (fake timers)', () => {
await vi.advanceTimersByTimeAsync(0);
expect(events).toEqual(['offline']);
});
it('ignores online/offline after dispose so process exit is not a runtime drop', async () => {
const { events, mgr } = setup(0);
mgr.dispose();
mgr.handleOnline('123', 'Bob');
mgr.handleOffline('123', 'Bob');
await vi.advanceTimersByTimeAsync(0);
expect(events).toEqual([]);
});
});
describe('createDefaultPost timeout', () => {
const name = 'SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS';
const saved = process.env[name];
afterEach(() => {
if (saved === undefined) delete process.env[name];
else process.env[name] = saved;
vi.unstubAllGlobals();
});
it('uses SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS', async () => {
process.env[name] = '1234';
const seen: number[] = [];
const timeout = AbortSignal.timeout.bind(AbortSignal);
vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms: number) => {
seen.push(ms);
return timeout(50);
});
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200 })));
const post = createDefaultPost();
await post('http://127.0.0.1/hook', '{}');
expect(seen).toEqual([1234]);
});
});
@@ -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');
});
});
@@ -14,17 +14,46 @@ function validate(
}
describe('OneBot access token save policy', () => {
it('rejects clearing an inbound token from a non-loopback client', () => {
it('rejects clearing an inbound token from a non-loopback client when the bind host is public', () => {
const previous = makeDefaultOneBotConfig();
const next = structuredClone(previous);
next.networks.httpServers[0].host = '0.0.0.0';
next.networks.httpServers[0].accessToken = undefined;
expect(() => validate(previous, next, '192.0.2.10')).toThrow(OneBotAccessTokenPolicyError);
expect(() => validate(previous, next, '192.0.2.10')).toThrow(/令牌/);
});
it('allows a remote client to clear a token when the inbound host is loopback', () => {
const previous = makeDefaultOneBotConfig();
const next = structuredClone(previous);
next.networks.httpServers[0].host = '127.0.0.1';
next.networks.httpServers[0].accessToken = undefined;
expect(() => validate(previous, next, '192.0.2.10')).not.toThrow();
});
it('treats localhost as a loopback bind host for empty inbound tokens', () => {
const previous = makeDefaultOneBotConfig();
const next = structuredClone(previous);
next.networks.wsServers[0].host = 'localhost';
next.networks.wsServers[0].accessToken = undefined;
expect(() => validate(previous, next, '192.0.2.10')).not.toThrow();
});
it('does not treat a missing bind host as loopback', () => {
const previous = makeDefaultOneBotConfig();
const next = structuredClone(previous);
next.networks.httpServers[0].host = undefined;
next.networks.httpServers[0].accessToken = undefined;
expect(() => validate(previous, next, '192.0.2.10')).toThrow(OneBotAccessTokenPolicyError);
expect(() => validate(previous, next, '192.0.2.10')).toThrow(/本机/);
});
it('treats every inbound token as new when no readable prior config exists', () => {
const next = makeDefaultOneBotConfig();
next.networks.httpServers[0].host = '0.0.0.0';
next.networks.httpServers[0].accessToken = undefined;
expect(() => validate(null, next, '192.0.2.10')).toThrow(OneBotAccessTokenPolicyError);
@@ -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(); }
});
});
+519
View File
@@ -0,0 +1,519 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {
evaluatePasswordRules,
isDevAuthMode,
isStrongPassword,
PASSWORD_RULES,
prepareWebuiAuthStateForRestore,
WebuiAuth,
} from '../src/webui/auth';
import { confirmTotpEnrollment, unwrapTotpSecret, type TotpPersistedState } from '../src/webui/totp';
const TS = '2026-06-18T00:00:00.000Z';
const HASH = 'ab'.repeat(64);
const SALT = 'cd'.repeat(16);
const STRONG = 'Correct-Horse-1!';
const STRONG_NEXT = 'Correct-Horse-2!';
const RFC_SECRET = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ';
const T59_MS = 59_000;
const T59_CODE = '287082';
const VALID_TOTP: TotpPersistedState = {
wrapSalt: '11'.repeat(16),
iv: '22'.repeat(12),
ciphertext: '33'.repeat(10),
authTag: '44'.repeat(16),
recoveryCodeHashes: ['55'.repeat(32), '66'.repeat(32)],
lastUsedStep: 7,
label: 'SnowLuma (testhost)',
};
const AUTH_ENV = ['SNOWLUMA_DEV_MODE', 'SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD'] as const;
const savedEnv: Record<string, string | undefined> = {};
beforeEach(() => {
for (const key of AUTH_ENV) {
savedEnv[key] = process.env[key];
delete process.env[key];
}
});
afterEach(() => {
for (const key of AUTH_ENV) {
if (savedEnv[key] === undefined) delete process.env[key];
else process.env[key] = savedEnv[key];
}
});
describe('PASSWORD_RULES / evaluatePasswordRules / isStrongPassword', () => {
it('exposes the five published rule ids and labels in order', () => {
expect(PASSWORD_RULES.map((rule) => ({ id: rule.id, label: rule.label }))).toEqual([
{ id: 'length', label: '长度不少于 10 位' },
{ id: 'lower', label: '包含小写字母' },
{ id: 'upper', label: '包含大写字母' },
{ id: 'special', label: '包含特殊符号 (!@#$%…)' },
{ id: 'no-space', label: '不包含空格' },
]);
});
it('marks every rule ok for a 10-character mixed password with a symbol', () => {
expect(evaluatePasswordRules('Abcdefghi!')).toEqual([
{ id: 'length', label: '长度不少于 10 位', ok: true },
{ id: 'lower', label: '包含小写字母', ok: true },
{ id: 'upper', label: '包含大写字母', ok: true },
{ id: 'special', label: '包含特殊符号 (!@#$%…)', ok: true },
{ id: 'no-space', label: '不包含空格', ok: true },
]);
expect(isStrongPassword('Abcdefghi!')).toBe(true);
});
it('fails only length when the password is 9 characters', () => {
expect(evaluatePasswordRules('Abcdefgh!')).toEqual([
{ id: 'length', label: '长度不少于 10 位', ok: false },
{ id: 'lower', label: '包含小写字母', ok: true },
{ id: 'upper', label: '包含大写字母', ok: true },
{ id: 'special', label: '包含特殊符号 (!@#$%…)', ok: true },
{ id: 'no-space', label: '不包含空格', ok: true },
]);
expect(isStrongPassword('Abcdefgh!')).toBe(false);
});
it('fails only lower when every letter is uppercase', () => {
expect(evaluatePasswordRules('ABCDEFGHI!')).toEqual([
{ id: 'length', label: '长度不少于 10 位', ok: true },
{ id: 'lower', label: '包含小写字母', ok: false },
{ id: 'upper', label: '包含大写字母', ok: true },
{ id: 'special', label: '包含特殊符号 (!@#$%…)', ok: true },
{ id: 'no-space', label: '不包含空格', ok: true },
]);
expect(isStrongPassword('ABCDEFGHI!')).toBe(false);
});
it('fails only upper when every letter is lowercase', () => {
expect(evaluatePasswordRules('abcdefghi!')).toEqual([
{ id: 'length', label: '长度不少于 10 位', ok: true },
{ id: 'lower', label: '包含小写字母', ok: true },
{ id: 'upper', label: '包含大写字母', ok: false },
{ id: 'special', label: '包含特殊符号 (!@#$%…)', ok: true },
{ id: 'no-space', label: '不包含空格', ok: true },
]);
expect(isStrongPassword('abcdefghi!')).toBe(false);
});
it('fails only special when the password is letters and digits', () => {
expect(evaluatePasswordRules('Abcdefgh12')).toEqual([
{ id: 'length', label: '长度不少于 10 位', ok: true },
{ id: 'lower', label: '包含小写字母', ok: true },
{ id: 'upper', label: '包含大写字母', ok: true },
{ id: 'special', label: '包含特殊符号 (!@#$%…)', ok: false },
{ id: 'no-space', label: '不包含空格', ok: true },
]);
expect(isStrongPassword('Abcdefgh12')).toBe(false);
});
it('fails special and no-space when the only extra character is a space', () => {
expect(evaluatePasswordRules('Abcdefgh i')).toEqual([
{ id: 'length', label: '长度不少于 10 位', ok: true },
{ id: 'lower', label: '包含小写字母', ok: true },
{ id: 'upper', label: '包含大写字母', ok: true },
{ id: 'special', label: '包含特殊符号 (!@#$%…)', ok: false },
{ id: 'no-space', label: '不包含空格', ok: false },
]);
expect(isStrongPassword('Abcdefgh i')).toBe(false);
});
it('fails every rule for an empty string, including no-space', () => {
expect(evaluatePasswordRules('')).toEqual([
{ id: 'length', label: '长度不少于 10 位', ok: false },
{ id: 'lower', label: '包含小写字母', ok: false },
{ id: 'upper', label: '包含大写字母', ok: false },
{ id: 'special', label: '包含特殊符号 (!@#$%…)', ok: false },
{ id: 'no-space', label: '不包含空格', ok: false },
]);
expect(isStrongPassword('')).toBe(false);
});
});
describe('isDevAuthMode', () => {
it('is true only when SNOWLUMA_DEV_MODE is the string 1', () => {
expect(isDevAuthMode()).toBe(false);
process.env.SNOWLUMA_DEV_MODE = '';
expect(isDevAuthMode()).toBe(false);
process.env.SNOWLUMA_DEV_MODE = '0';
expect(isDevAuthMode()).toBe(false);
process.env.SNOWLUMA_DEV_MODE = 'true';
expect(isDevAuthMode()).toBe(false);
process.env.SNOWLUMA_DEV_MODE = '1';
expect(isDevAuthMode()).toBe(true);
});
});
describe('prepareWebuiAuthStateForRestore', () => {
const base = {
passwordHash: HASH,
passwordSalt: SALT,
mustChangePassword: false,
generatedAt: TS,
updatedAt: TS,
};
it('accepts a complete credential object and omits totp when it is absent or undefined', () => {
expect(prepareWebuiAuthStateForRestore(base)).toEqual({
passwordHash: HASH,
passwordSalt: SALT,
mustChangePassword: false,
generatedAt: TS,
updatedAt: TS,
});
expect(prepareWebuiAuthStateForRestore({ ...base, totp: undefined })).toEqual({
passwordHash: HASH,
passwordSalt: SALT,
mustChangePassword: false,
generatedAt: TS,
updatedAt: TS,
});
});
it('keeps mixed-case hash and salt hex and attaches a valid totp object', () => {
const mixedHash = 'AB'.repeat(64);
const mixedSalt = 'CD'.repeat(16);
expect(prepareWebuiAuthStateForRestore({
passwordHash: mixedHash,
passwordSalt: mixedSalt,
mustChangePassword: true,
generatedAt: TS,
updatedAt: '2026-06-19T12:34:56.000Z',
totp: VALID_TOTP,
})).toEqual({
passwordHash: mixedHash,
passwordSalt: mixedSalt,
mustChangePassword: true,
generatedAt: TS,
updatedAt: '2026-06-19T12:34:56.000Z',
totp: {
wrapSalt: '11'.repeat(16),
iv: '22'.repeat(12),
ciphertext: '33'.repeat(10),
authTag: '44'.repeat(16),
recoveryCodeHashes: ['55'.repeat(32), '66'.repeat(32)],
lastUsedStep: 7,
label: 'SnowLuma (testhost)',
},
});
});
it('rejects a non-object credential state', () => {
expect(() => prepareWebuiAuthStateForRestore(null)).toThrow('credential state must be an object');
expect(() => prepareWebuiAuthStateForRestore(undefined)).toThrow('credential state must be an object');
expect(() => prepareWebuiAuthStateForRestore([])).toThrow('credential state must be an object');
expect(() => prepareWebuiAuthStateForRestore('x')).toThrow('credential state must be an object');
});
it('rejects a passwordHash that is not exactly 128 hexadecimal characters', () => {
expect(() => prepareWebuiAuthStateForRestore({ ...base, passwordHash: 'ab'.repeat(63) }))
.toThrow('passwordHash must be exactly 128 hexadecimal characters');
expect(() => prepareWebuiAuthStateForRestore({ ...base, passwordHash: `${HASH}0` }))
.toThrow('passwordHash must be exactly 128 hexadecimal characters');
expect(() => prepareWebuiAuthStateForRestore({ ...base, passwordHash: 'gg'.repeat(64) }))
.toThrow('passwordHash must be exactly 128 hexadecimal characters');
expect(() => prepareWebuiAuthStateForRestore({ ...base, passwordHash: 1 }))
.toThrow('passwordHash must be exactly 128 hexadecimal characters');
});
it('rejects a passwordSalt that is not exactly 32 hexadecimal characters', () => {
expect(() => prepareWebuiAuthStateForRestore({ ...base, passwordSalt: 'cd'.repeat(15) }))
.toThrow('passwordSalt must be exactly 32 hexadecimal characters');
expect(() => prepareWebuiAuthStateForRestore({ ...base, passwordSalt: 'zz'.repeat(16) }))
.toThrow('passwordSalt must be exactly 32 hexadecimal characters');
});
it('rejects a non-boolean mustChangePassword', () => {
expect(() => prepareWebuiAuthStateForRestore({ ...base, mustChangePassword: 'false' }))
.toThrow('mustChangePassword must be a boolean');
});
it('rejects generatedAt or updatedAt that are not parseable timestamps', () => {
expect(() => prepareWebuiAuthStateForRestore({ ...base, generatedAt: 'not-a-timestamp' }))
.toThrow('generatedAt must be a valid timestamp');
expect(() => prepareWebuiAuthStateForRestore({ ...base, generatedAt: 0 }))
.toThrow('generatedAt must be a valid timestamp');
expect(() => prepareWebuiAuthStateForRestore({ ...base, updatedAt: '' }))
.toThrow('updatedAt must be a valid timestamp');
expect(() => prepareWebuiAuthStateForRestore({ ...base, updatedAt: 'Invalid Date' }))
.toThrow('updatedAt must be a valid timestamp');
});
it('rejects an unknown top-level field', () => {
expect(() => prepareWebuiAuthStateForRestore({ ...base, note: 'x' })).toThrow('unknown field $.note');
});
it('rejects a malformed totp object and a null totp value', () => {
expect(() => prepareWebuiAuthStateForRestore({ ...base, totp: { wrapSalt: 'zz' } }))
.toThrow('totp wrapped secret fields are invalid');
expect(() => prepareWebuiAuthStateForRestore({ ...base, totp: null }))
.toThrow('totp state must be an object');
});
});
describe('WebuiAuth', () => {
const configPath = path.join('config', 'webui.json');
let tmp: string;
let prevCwd: string;
beforeEach(() => {
prevCwd = process.cwd();
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-webui-auth-'));
process.chdir(tmp);
});
afterEach(() => {
process.chdir(prevCwd);
fs.rmSync(tmp, { recursive: true, force: true });
});
function readAuthFile(): Record<string, unknown> {
return JSON.parse(fs.readFileSync(configPath, 'utf8')) as Record<string, unknown>;
}
function writeAuthFile(value: string | Record<string, unknown>): void {
fs.mkdirSync('config', { recursive: true });
fs.writeFileSync(configPath, typeof value === 'string' ? value : JSON.stringify(value, null, 2));
}
function backupNames(): string[] {
if (!fs.existsSync('config')) return [];
return fs.readdirSync('config').filter((name) => name.startsWith('webui.json.bak.')).sort();
}
it('publishes the fixed dev password', () => {
expect(WebuiAuth.devPassword).toBe('snowluma-dev');
});
it('creates config/webui.json with a one-shot hex bootstrap password', () => {
const auth = WebuiAuth.load();
const initial = auth.takeInitialPassword();
expect(initial).toMatch(/^[0-9a-f]{16}$/);
expect(auth.takeInitialPassword()).toBeNull();
expect(auth.mustChangePassword()).toBe(true);
expect(auth.isDevMode()).toBe(false);
expect(auth.verify(initial!)).toBe(true);
expect(auth.verify('wrong-password')).toBe(false);
expect(auth.verify('')).toBe(false);
expect(auth.verify(undefined as unknown as string)).toBe(false);
expect(auth.totpEnabled()).toBe(false);
expect(auth.totpStatus()).toEqual({ enabled: false });
expect(auth.totpState()).toBeUndefined();
const disk = readAuthFile();
expect(disk.mustChangePassword).toBe(true);
expect(disk.totp).toBeUndefined();
expect(disk.passwordHash).toMatch(/^[0-9a-f]{128}$/);
expect(disk.passwordSalt).toMatch(/^[0-9a-f]{32}$/);
expect(disk.generatedAt).toBe(disk.updatedAt);
expect(Number.isFinite(Date.parse(disk.generatedAt as string))).toBe(true);
if (process.platform !== 'win32') {
expect(fs.statSync(configPath).mode & 0o777).toBe(0o600);
}
});
it('rotates a leftover must-change bootstrap password on the next load', () => {
const first = WebuiAuth.load();
const oldPassword = first.takeInitialPassword();
expect(oldPassword).toMatch(/^[0-9a-f]{16}$/);
const second = WebuiAuth.load();
const rotated = second.takeInitialPassword();
expect(rotated).toMatch(/^[0-9a-f]{16}$/);
expect(rotated).not.toBe(oldPassword);
expect(second.mustChangePassword()).toBe(true);
expect(second.verify(oldPassword!)).toBe(false);
expect(second.verify(rotated!)).toBe(true);
});
it('seeds credentials from SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD when it is at least 8 characters', () => {
process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = '12345678';
const auth = WebuiAuth.load();
expect(auth.takeInitialPassword()).toBeNull();
expect(auth.mustChangePassword()).toBe(false);
expect(auth.verify('12345678')).toBe(true);
expect(readAuthFile().mustChangePassword).toBe(false);
});
it('ignores a bootstrap env value shorter than 8 characters', () => {
process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = '1234567';
const auth = WebuiAuth.load();
expect(auth.mustChangePassword()).toBe(true);
expect(auth.verify('1234567')).toBe(false);
expect(auth.takeInitialPassword()).toMatch(/^[0-9a-f]{16}$/);
});
it('reloads an already-rotated file without regenerating', () => {
process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = 'seed-pass';
WebuiAuth.load();
delete process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD;
const again = WebuiAuth.load();
expect(again.takeInitialPassword()).toBeNull();
expect(again.mustChangePassword()).toBe(false);
expect(again.verify('seed-pass')).toBe(true);
expect(backupNames()).toEqual([]);
});
it('backs up invalid JSON and regenerates credentials', () => {
writeAuthFile('{not-json');
const auth = WebuiAuth.load();
const names = backupNames();
expect(names).toEqual([expect.stringMatching(/^webui\.json\.bak\.\d+$/)]);
expect(fs.readFileSync(path.join('config', names[0]!), 'utf8')).toBe('{not-json');
expect(auth.takeInitialPassword()).toMatch(/^[0-9a-f]{16}$/);
expect(auth.mustChangePassword()).toBe(true);
});
it('backs up a schema-invalid object and can reseed from the bootstrap env', () => {
writeAuthFile({ passwordHash: 'zz', passwordSalt: '00', mustChangePassword: false });
process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = 'env-password';
const auth = WebuiAuth.load();
expect(backupNames()).toHaveLength(1);
expect(auth.takeInitialPassword()).toBeNull();
expect(auth.mustChangePassword()).toBe(false);
expect(auth.verify('env-password')).toBe(true);
});
it('keeps password credentials when the live totp field is invalid', () => {
process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = STRONG;
WebuiAuth.load();
delete process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD;
const disk = readAuthFile();
writeAuthFile({ ...disk, totp: { wrapSalt: 'zz' } });
const auth = WebuiAuth.load();
expect(auth.verify(STRONG)).toBe(true);
expect(auth.mustChangePassword()).toBe(false);
expect(auth.totpEnabled()).toBe(false);
expect(auth.totpStatus()).toEqual({ enabled: false });
expect(auth.totpState()).toBeUndefined();
expect(backupNames()).toEqual([]);
});
it('loads a persisted totp object from disk', () => {
process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = STRONG;
const first = WebuiAuth.load();
delete process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD;
first.persistTotp(VALID_TOTP);
const auth = WebuiAuth.load();
expect(auth.totpEnabled()).toBe(true);
expect(auth.totpStatus()).toEqual({
enabled: true,
remainingRecoveryCodes: 2,
label: 'SnowLuma (testhost)',
});
expect(auth.totpState()).toEqual({
wrapSalt: '11'.repeat(16),
iv: '22'.repeat(12),
ciphertext: '33'.repeat(10),
authTag: '44'.repeat(16),
recoveryCodeHashes: ['55'.repeat(32), '66'.repeat(32)],
lastUsedStep: 7,
label: 'SnowLuma (testhost)',
});
});
it('setPassword writes a new hash, clears must-change, and keeps generatedAt', () => {
const auth = WebuiAuth.load();
const initial = auth.takeInitialPassword()!;
const generatedAt = readAuthFile().generatedAt;
expect(() => auth.setPassword('too-weak')).toThrow('密码不符合强度要求');
auth.setPassword(STRONG);
expect(auth.mustChangePassword()).toBe(false);
expect(auth.verify(initial)).toBe(false);
expect(auth.verify(STRONG)).toBe(true);
const disk = readAuthFile();
expect(disk.mustChangePassword).toBe(false);
expect(disk.generatedAt).toBe(generatedAt);
expect(disk.updatedAt).not.toBe(generatedAt);
expect(disk.totp).toBeUndefined();
});
it('setPassword rewraps totp with the current password', () => {
process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = STRONG;
const auth = WebuiAuth.load();
delete process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD;
const enabled = confirmTotpEnrollment({
password: STRONG,
secret: RFC_SECRET,
code: T59_CODE,
label: 'SnowLuma (testhost)',
atMs: T59_MS,
});
auth.persistTotp(enabled.state);
expect(() => auth.setPassword(STRONG_NEXT)).toThrow('修改密码需要当前密码以重新保护 2FA 密钥');
expect(() => auth.setPassword(STRONG_NEXT, '')).toThrow('修改密码需要当前密码以重新保护 2FA 密钥');
expect(() => auth.setPassword(STRONG_NEXT, 'Wrong-Password-3!')).toThrow('无法使用当前密码解开 2FA 密钥');
auth.setPassword(STRONG_NEXT, STRONG);
expect(auth.verify(STRONG)).toBe(false);
expect(auth.verify(STRONG_NEXT)).toBe(true);
expect(auth.totpEnabled()).toBe(true);
expect(unwrapTotpSecret(STRONG_NEXT, auth.totpState()!)).toBe(RFC_SECRET);
expect(unwrapTotpSecret(STRONG, auth.totpState()!)).toBeNull();
});
it('persistTotp writes, reports, and then removes 2FA state', () => {
process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = STRONG;
const auth = WebuiAuth.load();
delete process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD;
auth.persistTotp(VALID_TOTP);
expect(auth.totpEnabled()).toBe(true);
expect(auth.totpStatus()).toEqual({
enabled: true,
remainingRecoveryCodes: 2,
label: 'SnowLuma (testhost)',
});
expect(auth.totpState()).toEqual(VALID_TOTP);
expect(readAuthFile().totp).toEqual(VALID_TOTP);
auth.persistTotp(undefined);
expect(auth.totpEnabled()).toBe(false);
expect(auth.totpStatus()).toEqual({ enabled: false });
expect(auth.totpState()).toBeUndefined();
expect(Object.prototype.hasOwnProperty.call(readAuthFile(), 'totp')).toBe(false);
});
it('uses the in-memory dev password and never reads or writes webui.json', () => {
writeAuthFile('should-not-be-read');
process.env.SNOWLUMA_DEV_MODE = '1';
const auth = WebuiAuth.load();
delete process.env.SNOWLUMA_DEV_MODE;
expect(isDevAuthMode()).toBe(false);
expect(auth.isDevMode()).toBe(true);
expect(auth.mustChangePassword()).toBe(false);
expect(auth.takeInitialPassword()).toBeNull();
expect(auth.verify('snowluma-dev')).toBe(true);
expect(auth.verify(STRONG)).toBe(false);
expect(auth.totpEnabled()).toBe(false);
expect(() => auth.setPassword(STRONG)).toThrow('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改');
expect(() => auth.persistTotp(VALID_TOTP)).toThrow('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用 2FA');
expect(fs.readFileSync(configPath, 'utf8')).toBe('should-not-be-read');
});
it('does not create config/webui.json when loading in dev mode on a fresh directory', () => {
process.env.SNOWLUMA_DEV_MODE = '1';
WebuiAuth.load();
expect(fs.existsSync('config')).toBe(false);
});
});
@@ -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/);
});
});
+88
View File
@@ -0,0 +1,88 @@
import { describe, expect, it } from 'vitest';
import { confirmTotpEnrollment } from '../src/webui/totp';
import { completeWebuiLogin, invalidateOtherSessions, type WebuiLoginAuth } from '../src/webui/webui-login';
const RFC_SECRET = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ';
const T59_MS = 59_000;
const T59_CODE = '287082';
const PASSWORD = 'Correct-Horse-1!';
function authWithoutTotp(): WebuiLoginAuth {
return {
verify: (password) => password === PASSWORD,
totpEnabled: () => false,
totpState: () => undefined,
mustChangePassword: () => false,
};
}
describe('completeWebuiLogin', () => {
it('rejects a wrong password without mentioning TOTP', () => {
expect(completeWebuiLogin(authWithoutTotp(), { password: 'nope' }, T59_MS)).toEqual({
kind: 'bad-password',
});
});
it('logs in with only a password when 2FA is off', () => {
expect(completeWebuiLogin(authWithoutTotp(), { password: PASSWORD }, T59_MS)).toEqual({
kind: 'ok',
mustChangePassword: false,
});
});
it('asks for TOTP after a correct password when 2FA is on', () => {
const enabled = confirmTotpEnrollment({
password: PASSWORD,
secret: RFC_SECRET,
code: T59_CODE,
label: 'SnowLuma (testhost)',
atMs: T59_MS,
});
const auth: WebuiLoginAuth = {
verify: (password) => password === PASSWORD,
totpEnabled: () => true,
totpState: () => enabled.state,
mustChangePassword: () => false,
};
expect(completeWebuiLogin(auth, { password: PASSWORD }, T59_MS)).toEqual({
kind: 'needs-totp',
});
});
it('accepts password plus TOTP and returns the updated totp state', () => {
const enabled = confirmTotpEnrollment({
password: PASSWORD,
secret: RFC_SECRET,
code: T59_CODE,
label: 'SnowLuma (testhost)',
atMs: T59_MS,
});
const auth: WebuiLoginAuth = {
verify: (password) => password === PASSWORD,
totpEnabled: () => true,
totpState: () => enabled.state,
mustChangePassword: () => true,
};
const result = completeWebuiLogin(
auth,
{ password: PASSWORD, totp: '081804' },
1_111_111_109_000,
);
expect(result.kind).toBe('ok');
if (result.kind !== 'ok') return;
expect(result.mustChangePassword).toBe(true);
expect(result.totpState?.lastUsedStep).toBeGreaterThan(enabled.state.lastUsedStep);
});
});
describe('invalidateOtherSessions', () => {
it('keeps the current session and drops the rest', () => {
const sessions = new Map([
['keep', { n: 1 }],
['drop-a', { n: 2 }],
['drop-b', { n: 3 }],
]);
invalidateOtherSessions(sessions, 'keep');
expect([...sessions.keys()]).toEqual(['keep']);
});
});
Loaded 100 of 458 files, more files were not shown because too many files have changed in this diff. Show more