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
DrSmoothl 0357d136d8 chore(release): v1.14.5 2026-08-11 18:20:17 +08:00
DrSmoothl 190f156fca fix(onebot): preserve group requests with unknown senders
Deliver actionable invitations even when the sender account is unavailable instead of failing the full polling batch.

Isolate malformed records, keep sibling requests flowing, and distinguish multiple anonymous invitations by their request handles.

Add regression coverage for repeated polls, batch isolation, and anonymous-request deduplication.
2026-08-10 13:12:18 +08:00
DrSmoothl da3821ced4 feat(sdk): expose group request query options
Add typed group, pending-state, and per-inbox limit options to group-system message queries while preserving existing call sites.

Regenerate the shared action catalog so SDK and MCP consumers receive consistent validation rules and updated request-flag guidance.
2026-08-10 00:26:29 +08:00
DrSmoothl 1996192a5e feat(onebot): report web-originated group requests
Report pending group invitations through the standard OneBot request event even when their origin does not provide a live notification.

Prevent duplicate delivery when the same invitation is observed more than once, stop outstanding work with the account lifecycle, and preserve previously supported invitation behavior.

Expand group-system message queries and surface incomplete lookups instead of reporting misleading empty or not-found results.
2026-08-10 00:26:16 +08:00
DrSmoothl fe44a2f5bc fix(group-requests): normalize request retrieval and handling
Correct group-request retrieval so requester identities and action metadata remain usable across client and web-originated invitations.

Keep existing live-event behavior compatible, ensure returned requests carry the correct information for approval or rejection, and reject malformed request identifiers instead of emitting unusable flags.

Add regression coverage for both request inboxes and the supported invitation categories.
2026-08-10 00:26:01 +08:00
DrSmoothl 870e9a5fbc fix(bridge): recover stale outbound sessions
Recover invalidated native send bindings from same-account receive evidence. Track outbound connection loss in status health and refresh the six public native artifacts from native build 94f2b63.

Closes #342
2026-08-09 21:40:09 +08:00
DrSmoothl 129b091081 fix(onebot): skip unusable reply segments
Keep delivering valid message content when a reply target cannot be resolved, while retaining strict validation for all other segments.

Fixes #339
2026-08-09 17:25:48 +08:00
DrSmoothl dbf654ad57 chore(release): v1.14.4 2026-08-09 16:53:10 +08:00
DrSmoothl c08150fc0c feat(onebot): query group todo messages
Fixes #332
2026-08-09 13:36:41 +08:00
DrSmoothl 4aba81ec6b feat(onebot): decode bot markdown and keyboards
Fixes #337
2026-08-09 13:06:35 +08:00
DrSmoothl 1e0c91e74d feat(onebot): configure group member permissions
Fixes #335
2026-08-09 12:56:05 +08:00
DrSmoothl e08613062e feat(onebot): configure group history visibility
Fixes #336
2026-08-09 12:53:45 +08:00
DrSmoothl cd6fcadea4 feat(onebot): configure group invite policy
Add validated group member invite policy updates with post-write verification.

Fixes #334
2026-08-09 11:46:04 +08:00
DrSmoothl 597a4c05f3 feat(onebot): fetch custom face details
Add packet-backed custom face detail retrieval and expose the result through the OneBot action.

Fixes #333
2026-08-09 11:45:43 +08:00
DrSmoothl 49439370e1 fix(onebot): decode user status property list (#330) 2026-08-09 11:28:14 +08:00
DrSmoothl 7eea8059cc chore(release): v1.14.3 2026-08-08 19:44:58 +08:00
DrSmoothl c404974e75 fix(protocol): support cross-pack system face overlaps (#324) 2026-08-08 19:26:09 +08:00
DrSmoothl 4c385bf640 fix(release): refresh generated action catalog 2026-08-08 17:52:52 +08:00
DrSmoothl f968687a25 chore(release): v1.14.2 2026-08-08 17:46:31 +08:00
DrSmoothl 39d5a50d5f fix(protocol): accept Unicode system face identifiers (#324) 2026-08-08 17:42:14 +08:00
DrSmoothl 65683bb44d fix(onebot): accept compatible JSON card payloads (#325) 2026-08-08 10:14:39 +08:00
DrSmoothl 751217c13d perf(webui): reduce initial loading delays 2026-08-08 00:04:51 +08:00
DrSmoothl c53c6651a5 docs(readme): streamline project overview 2026-08-07 21:58:44 +08:00
DrSmoothl 005154077f fix(onebot): accept id-less custom music cards (#319) 2026-08-07 21:50:28 +08:00
DrSmoothl 1646f265ec fix(protocol): skip non-addressable system face entries 2026-08-07 21:24:05 +08:00
DrSmoothl 4d958eb984 chore(release): v1.14.1 2026-08-07 20:29:00 +08:00
DrSmoothl 810509ef58 fix: restore message sending after restart 2026-08-07 19:24:24 +08:00
DrSmoothl f1ae0736c6 build(release): enforce neutral runtime layout
Keep release files at the archive root and reject product-named directory components before CI packages artifacts.

Use neutral directories for media staging, WebUI uploads, stream storage, and MCP downloads so packaged and runtime layouts remain consistent.
2026-08-06 23:08:19 +08:00
DrSmoothl c0e73cd738 fix(protocol): handle empty group essence lists
Return an empty result when a successful, completed group essence response omits its message list instead of reporting a malformed response.

Keep upstream errors and incomplete pagination responses explicit, and cover omitted and null list variants with regression tests.

Fixes #320.
2026-08-06 22:36:05 +08:00
DrSmoothl 27c527976b fix(onebot): reject ambiguous video message combinations
Prevent ordinary messages and forwarded nodes from combining video content with visible sibling segments or additional videos. Invalid combinations now fail before parsing side effects, media work, or bridge sends, while exact empty text placeholders remain compatible with a single video.

Cover group, private, temporary-session, CQ string, nested forward, cached forward, and protocol-builder paths. Preserve the existing standalone window-shake behavior and keep valid single-video messages unchanged.
2026-08-05 23:55:55 +08:00
DrSmoothl 2ac0b92859 fix(onebot): support standard forward WebSocket routes
Accept the standard action, event, and universal paths when a forward WebSocket server listens at the root endpoint.

Keep authentication, custom endpoints, embedded listeners, and rejected-path reporting compatible while assigning each accepted connection the correct role.

Add real-listener regression coverage for standard paths, trailing slashes, query authentication, invalid paths, and existing lifecycle behavior.

Fixes #317
2026-08-05 19:39:30 +08:00
DrSmoothl 81699b839d feat(onebot): expose group member mute expiry
Return the mute expiry timestamp from group member list and detail actions, using zero when no active mute is available.

Keep the public action descriptions and generated MCP catalog aligned, and cover muted, unmuted, and unavailable member responses.

Refs #314
2026-08-05 12:28:47 +08:00
DrSmoothl 634097460c feat(onebot): expose group-wide mute status
Report whether group-wide mute is enabled through the existing group list and group information responses.

Keep standard and extended queries aligned, support explicit refreshes in the SDK, and update the generated action documentation without adding another endpoint.

Preserve established compatibility values, isolate cached non-member results by account, and add coverage across the request, mapping, action, and client layers.

Closes #313
2026-08-04 23:27:58 +08:00
DrSmoothl c6619fda0a feat(onebot): expose system face catalog queries
Add read-only actions for catalog retrieval, per-face lookup, search, and super-face classification. Publish matching SDK methods and generated MCP schemas, including valid face ID zero.
2026-08-04 23:13:51 +08:00
DrSmoothl 8e9a4d878e feat(protocol): complete system face catalog lifecycle
Persist and validate the shared system face catalog, refresh it once when the first account connects, and coalesce concurrent loads. Resolve outgoing face metadata from the catalog so startup races, unknown IDs, and incomplete entries fail before sending.
2026-08-04 23:13:32 +08:00
DrSmoothl 938975dd45 fix(onebot): report uploaded private files as sent messages
Route private file publication through the common send path so successful uploads retain their send receipt and emit a complete self-sent event.

Return action failures when publication fails while preserving upload_file=false as a non-publishing operation.
2026-08-04 18:13:22 +08:00
DrSmoothl 672802b424 fix(group-album): validate image upload inputs
Reject unsupported media with a clear error before processing begins. Existing image upload behavior remains unchanged.

Refs #310
2026-08-04 15:25:23 +08:00
DrSmoothl 185ba8353b fix(message): preserve passive temporary session context
Keep passive replies associated with the correct conversation when the same contact is shared across groups. Active temporary conversations remain unsupported.

Fixes #308
2026-08-04 00:20:56 +08:00
DrSmoothl f572be2561 chore(release): v1.14.0 2026-08-03 19:35:07 +08:00
DrSmoothl c72de4adb6 fix(runtime): improve restored session reliability
Improve compatibility for accounts restored after a restart.

Keep existing accounts working normally while restoring full availability for affected sessions.
2026-08-03 19:28:21 +08:00
DrSmoothl 198f25476f fix(webui): constrain forward message construction
Keep forward nodes out of ordinary message parameters and expose a node-only root builder for forward send and upload actions.

Lock nested forward content to one valid shape, clear stale form values when switching actions, and add regression coverage for the capability rules.
2026-08-03 13:59:39 +08:00
DrSmoothl 4b6237f24b chore(native): refresh bundled runtime files
Update the packaged runtime files from the verified release pipeline.

Align all supported platform bundles with the validated account recovery release.

Refs #305

Refs #307
2026-08-03 13:00:48 +08:00
DrSmoothl 4a0d14ce56 fix(bridge): keep account recovery non-interactive
Keep background account discovery passive and distinguish an identified account from a ready session.

Update the process dialog and regression coverage so recovery waits for authoritative readiness before exposing the account as online.
2026-08-03 12:54:48 +08:00
DrSmoothl dae486a0ad chore(native): update bundled runtime files
Refresh the bundled runtime files with outputs from the verified release pipeline.

Include the supported Linux and Windows builds for the latest startup reliability improvements.

Refs #305

Refs #307
2026-08-03 10:56:31 +08:00
DrSmoothl 8526d0c2c5 fix(bridge): restore active sessions after delayed startup
Allow SnowLuma to discover and restore accounts that were already active before startup.

Avoid reporting sessions ready before they can serve requests, preserve account changes, and keep discovery failures observable.

Add regression coverage for delayed startup, recovery, and process isolation.

Refs #305

Refs #307
2026-08-03 10:49:47 +08:00
DrSmoothl fb4d7716a1 fix(core): restore group remarks in queries
Request and retain the group remark information needed by group list and group detail queries while preserving the existing safeguards for large rosters.

Synchronize confirmed group remark changes with the local identity roster and persistent cache. Remote failures leave local state untouched, and missing roster entries remain observable without creating phantom groups.

Add regression coverage for query mapping, request scope, persistence, failed updates, unknown groups, and closed identity stores.

Fixes #304
2026-08-01 21:11:02 +08:00
DrSmoothl 6372e1479c fix(core): validate file sharing requests
Keep QQ share-code lookups on a bounded and predictable request path while preserving existing successful usage through plain codes and official links.

Reject unsupported inputs early, align operator-facing action documentation, and add regression coverage for valid links, malformed responses, and resource limits.
2026-08-01 18:27:42 +08:00
DrSmoothl 3c97e71650 fix(onebot): strengthen endpoint defaults
Use safer defaults for newly created service endpoints and guide operators toward suitable access credentials without disrupting existing deployments.

Apply the same policy at the save boundary, retain deliberate local-only setups and external client compatibility, and add regression coverage for editing, recovery, and trusted access paths.
2026-08-01 18:12:04 +08:00
DrSmoothl abe4ea80c8 fix(bridge): harden local transport handling
Strengthen validation and buffering for local process communication while preserving the established compatibility boundary.\n\nAdd regression coverage for malformed input, boundary values, fragmented delivery, combined traffic, and normal request behavior.
2026-08-01 17:37:16 +08:00
DrSmoothl ae2e894f14 fix(onebot): protect managed stream storage
Validate managed storage before stream files are created, read, or cleaned, and reject unsafe local directory state without changing the public stream actions.

Keep ordinary existing installations compatible and add regression coverage for startup, runtime replacement, ownership, permissions, and normal transfer behavior.
2026-08-01 17:23:17 +08:00
DrSmoothl 3c772df818 fix(onebot): enforce WebSocket access policy
Apply the configured access policy before server-side WebSocket sessions are established across both listener modes.

Preserve established client compatibility and runtime configuration changes, with regression coverage for accepted and rejected connections.
2026-08-01 17:09:04 +08:00
DrSmoothl 8940f8864b fix(config): protect operator credentials
Keep first-run access details confined to the active process console and remove development credentials from managed application logs.

Treat notification delivery settings as sensitive during backup and restore, preserve private file access across creation and updates, and align the WebUI guidance with the new boundary.
2026-08-01 17:02:39 +08:00
DrSmoothl ea841d929e fix(webui): make listener exposure explicit
Use a local-only default while preserving saved operator choices and keeping broader network access available from the settings panel.

Treat enabled encrypted transport as a startup requirement and present a dismissible notice when remote browser access is not protected.
2026-08-01 16:50:08 +08:00
DrSmoothl e4179ffb47 fix(webui): strengthen public session handling
Bound unauthenticated sign-in requests and require active sessions for browser-served account images.

Keep live updates authenticated without exposing session material in request URLs, and apply conservative response protections without restricting existing WebUI assets.
2026-08-01 16:36:33 +08:00
DrSmoothl 958d17ecc0 feat(webui): add developer settings tools
Expose onboarding replay and page crash testing from a dedicated settings page.\n\nKeep replay actions isolated from persisted consent and password state.
2026-08-01 00:40:44 +08:00
DrSmoothl 8080104311 refactor(webui): refine onboarding layout
Give agreement reading and password setup a calmer responsive layout.\n\nKeep existing motion behavior while aligning actions and improving mobile form ergonomics.
2026-08-01 00:40:09 +08:00
DrSmoothl 659e0bd3d0 fix(friend): verify and synchronize remark updates
Validate the service result before reporting friend remark changes as successful. Rejected, incomplete, or contradictory confirmations now reach callers instead of being reported as completed.

Keep confirmed remarks synchronized in the identity cache and consume cross-client remark updates without exposing a new OneBot event. Local cache failures remain observable without turning an already completed remote change into a retryable failure.

Preserve friend remarks exactly across restarts and add request, response, persistence, receive-pipeline, and action-level regression coverage.

Fixes #303.
2026-07-31 23:21:05 +08:00
DrSmoothl b8ccbdbf18 fix(onebot): project group essence files correctly
Treat type-four group essence entries as files and use the returned file name, identifier, size, and business metadata instead of requiring an optional thumbnail. This restores ordinary file entries without changing pagination, message identifiers, or metadata cache atomicity.

Extend the response model and cover files with and without previews, malformed file fields, and cache safety on projection failures.

Fixes #302.
2026-07-31 22:44:22 +08:00
DrSmoothl 4794f27972 chore(release): v1.13.0 2026-07-31 18:19:05 +08:00
DrSmoothl b81b060138 fix(webui): restore palette cards
Return theme palette selection to the original wrapping preview cards.

Keep segmented controls reserved for compact setting choices.
2026-07-31 18:14:15 +08:00
DrSmoothl a361ee512e feat(webui): unify first-run onboarding
Combine agreement consent and password setup into one ordered first-run flow.

Allow future steps to declare skip policy while honoring unattended deployment requirements.
2026-07-31 17:39:12 +08:00
DrSmoothl 5b68ca5bd3 feat(webui): refine interactive controls
Separate the custom context menu preference and enable it by default.

Bring dropdowns and settings choices into a consistent, responsive interaction language.
2026-07-31 17:38:51 +08:00
DrSmoothl ea39200111 feat(webui): unify dialog feedback
Move confirmations, editors, and help surfaces onto one consistent interaction model.

Preserve accessible focus handling while making destructive and in-progress actions clearer.
2026-07-31 17:38:33 +08:00
DrSmoothl 3c13838867 feat(webui): standardize content loading states
Use consistent delayed placeholders across data-backed console surfaces.
Avoid flashing loading UI for fast local responses while keeping slower transitions stable.
Keep failures visible and prevent gated content from opening on incomplete checks.
2026-07-31 16:56:44 +08:00
DrSmoothl f159b2f41a feat(webui): morph the mobile menu control
Give mobile navigation a clear transition that follows the real drawer state.
Preserve accessible open and close labels.
2026-07-31 16:56:27 +08:00
DrSmoothl f13bd72471 fix(webui): keep preference sync quiet
Keep routine layout, page, and appearance changes free of success notices.
Surface persistence failures without interrupting normal adjustments.
2026-07-31 16:56:12 +08:00
DrSmoothl da07864811 ci: strengthen pull request and release gates 2026-07-31 15:47:07 +08:00
DrSmoothl f6e2410dae fix(onebot): normalize group essence message results
Translate group essence responses into the established OneBot shape instead of exposing the upstream digest payload.

Return validated sender, operator, timestamp, message identifier, and message segment fields for text, face, image, and video entries. Retain the authoritative message metadata in one transaction so returned identifiers can be used by later essence actions without partial cache state.

Reject malformed, cross-group, incomplete, or unknown digest entries, and surface pagination or upstream failures instead of returning truncated success results.

Fixes #300.
2026-07-31 15:40:53 +08:00
DrSmoothl f066f3c89c feat(webui): strengthen password change guidance
Use consistent field labels, validation, and strength guidance in both password-change flows.

Show requirements only while the new-password field is active and surface validation failures clearly.
2026-07-31 15:35:29 +08:00
DrSmoothl b982927b4a feat(webui): improve operation feedback
Keep confirmations in dialogs while showing clear progress and results for long-running actions.

Auto-close completed notices, preserve important outcomes across reloads, and avoid noise from routine edits.
2026-07-31 15:35:03 +08:00
DrSmoothl b099dbe8cd test: unify workspace test and coverage entrypoints 2026-07-31 14:06:10 +08:00
DrSmoothl 9544aa7761 chore(repo): standardize cross-platform development
Make line endings deterministic across macOS, Windows, and Linux while preserving the native checkout format required by Windows launchers.

Pin the tested application runtime and Node type baseline, add a shared startup preflight, and keep independently published packages on their existing compatibility ranges.

Align local scripts, pull request validation, complete package builds, dependency metadata, and contributor documentation around the same Node and pnpm contract. The root test command now covers every tested workspace package while a focused Core command remains available for local iteration.
2026-07-31 13:09:02 +08:00
DrSmoothl 8dd986a565 style(repo): clear workspace lint violations
Align existing managed source with the repository lint rules so the workspace can adopt one reliable root validation command.

This normalizes the private file upload block, removes stale test suppressions, makes an error boundary explicit, and records a stable settings dependency without changing user-facing behavior.

The cleanup creates a deterministic baseline before lint becomes a required pull request gate.
2026-07-31 13:08:33 +08:00
DrSmoothl c3a1970e1c feat(webui): add trace warning and full export
Require explicit acknowledgement whenever operators enable TRACE and keep its active state visible until they restore normal logging.\n\nAdd an authenticated browser download for the complete retained logging snapshot, including runtime context and clear privacy guidance, while preserving the existing filtered-view export and memory-only TRACE boundary.\n\nCover the transition, snapshot, formatting, download, and client contracts with focused regression tests.
2026-07-31 12:40:51 +08:00
DrSmoothl a67614fa09 feat(logging): complete runtime trace diagnostics
Complete byte-level diagnostics for network, upload, runtime lifecycle, authenticated write, and background operation paths.

Preserve streaming behavior, file-storage boundaries, and default log volume while making failures, retries, cancellation, and final outcomes independently diagnosable.

Add focused regression coverage for correlation, partial data, resource context ownership, and terminal-state accuracy.
2026-07-31 11:21:12 +08:00
DrSmoothl 0ed85e7745 fix(onebot): report rejected group kick operations
Treat group member removal as successful only when QQ accepts the operation. Preserve the rejection reason so callers no longer receive a false success when a target cannot be removed.

Apply the same behavior to single-member and batch removal actions, while keeping accepted operations unchanged. Add regression coverage for both successful and rejected responses.

Fixes #298
2026-07-30 21:42:18 +08:00
DrSmoothl 0d14408b6f feat(protocol): add byte-complete packet tracing
Capture complete packet request, reply, and push payloads during temporary TRACE sessions while preserving the existing non-persistent logging boundary.

Correlate transport, parser, enrichment, drop, dispatch, timeout, and terminal outcomes with their real identifiers so exported logs can explain packet failures without relying on user descriptions.

Lock byte completeness, lazy disabled behavior, concurrency, context propagation, and truthful terminal outcomes with regression coverage.
2026-07-30 20:11:02 +08:00
DrSmoothl f9c4063fc5 feat(onebot): complete trace operation chains
Make short TRACE captures independently explain OneBot action and event lifecycles from complete input through a truthful terminal conclusion. Preserve request correlation across asynchronous work while keeping disabled TRACE paths allocation-free and lazy.

Cover shutdown rejection, stream cancellation, event conversion and suppression, reporter invocation settlement, and HTTP delivery outcomes without changing established transport or observer behavior. Add focused regression coverage for lifecycle uniqueness, context reuse, disconnect handling, and quiesce ingress boundaries.
2026-07-30 17:13:40 +08:00
DrSmoothl b9104f0a5b feat(logging): establish trace diagnostics contract
Make short-lived TRACE sessions complete and correlatable without adding a persistent trace channel or changing the existing file-log safety boundary.

Protect ordinary console, subscriber, and file logs from authentication material while preserving the one documented first-start credential notice. Keep action breadcrumbs useful through bounded summaries and a narrow diagnostic name for the emoji-like pagination offset.

Lock the contract with regressions for byte-complete rendering, lazy execution, request-context reuse, credential redaction, unredacted TRACE data, and non-persistence of TRACE records.
2026-07-30 12:07:32 +08:00
DrSmoothl 1d65623475 docs(mcp): refresh contact action metadata
Publish the group remark response field and the friend category update action to MCP clients.

Include the supported selection rules, result descriptions, and updated action totals so generated tool guidance stays aligned with the public OneBot surface.

References #294
References #297
2026-07-30 10:37:40 +08:00
DrSmoothl f0ff8da2fa feat(onebot): support moving friends between categories
Add the set_friends_category action with either an existing category ID or an exact unique category name.

Validate the current friend and category roster before applying a change, reject missing or ambiguous targets, and surface failed updates instead of reporting false success. Expose the action through the SDK types and cover validation, successful updates, repeat requests, service rejection, and registry completeness.

Closes #297
2026-07-30 10:37:16 +08:00
DrSmoothl a3b790d472 feat(onebot): expose group remarks in group queries
Include each account's saved group remark in group list and detail responses.

Keep joined-group, non-member, and fallback results shape-consistent when no remark is available. Document the field in the public response metadata and cover cached and refreshed query paths with regression tests.

Closes #294
2026-07-30 10:36:43 +08:00
DrSmoothl 655226d9d7 fix(logging): harden file level configuration
Make persisted log filtering predictable across supported startup settings while rejecting configurations that could silently retain more data than intended.

Keep the first WebUI login credential available without weakening normal log thresholds, clarify the operator-facing behavior, and strengthen regression coverage across isolated environments and explicit file-output disablement.
2026-07-30 10:27:43 +08:00
Werewolf-Wu 227a62f2ad feat(common): configure file log level
Allow operators to control how much diagnostic information is retained in file logs independently from live console output.

Document the new startup setting and add regression coverage for its default behavior, runtime independence, and unsupported configurations.
2026-07-30 10:04:52 +08:00
DrSmoothl e5f256f4dc feat(webui): report account storage update progress
Surface account storage preparation and background history progress through the existing live connection status channel. Clearly distinguish unavailable accounts from accounts that remain fully usable during maintenance.

Show processed totals, completion percentage, estimated remaining time, and retry states in both the global notice and account overview. Preserve existing connection update filtering to avoid unnecessary refreshes.
2026-07-30 09:57:31 +08:00
DrSmoothl 25e61ce5df fix(onebot): continue storage updates after account startup
Start each account as soon as its message storage is ready, then continue older history updates without delaying normal account availability. Keep already started accounts online when maintenance needs to be retried.

Handle preparation failures, stale completions, early exits, logout, and shutdown consistently. Add lifecycle coverage for startup ordering, automatic retries, cancellation, and account availability.
2026-07-30 09:57:18 +08:00
DrSmoothl caed31ca20 fix(onebot): prepare message storage without blocking startup
Prevent existing message histories from being fully updated on the account startup path. Preserve current message behavior while allowing unfinished maintenance to continue safely after restarts.

Add coverage for older databases, interrupted upgrades, new messages written during maintenance, and newly created account storage.
2026-07-30 09:57:00 +08:00
DrSmoothl b1fd5dd0fe chore(native): update runtime artifacts 2026-07-29 02:33:03 +08:00
DrSmoothl 04cbb8cbf3 fix(webui): recover stalled requests 2026-07-29 02:15:30 +08:00
DrSmoothl f97444c391 fix(bridge): bound process operations 2026-07-29 02:15:13 +08:00
DrSmoothl 5d1dbecf2e fix(protocol): scope system dedup to native routes
Derive QQ NT's peerUid_chatType_msg_seq_random identity from its reverse-engineered static routing table before event dispatch. Unknown routes and incomplete identities fail open, while C2C and group peers use their native namespaces.

Refines #266
2026-07-29 01:25:54 +08:00
DrSmoothl 5eb5aaf0a3 fix(protocol): suppress big-face compatibility text
Identify QQ's service-37 fallback by its byte-exact nested Text reserve so compatibility descriptions are removed without consuming user-authored sibling text or malformed payload fallbacks.

Fixes #289
2026-07-29 01:06:59 +08:00
DrSmoothl a93785c0a8 fix(onebot): preserve cached friend remarks
Keep get_stranger_info remarks available when profile fetching fails by falling back to the loaded friend roster.
2026-07-29 00:07:51 +08:00
DrSmoothl 3d7c4f5dc3 fix(protocol): align system message dedup identity
Match QQ NT's reverse-engineered peer, sequence, and random key so duplicate system events cannot bypass filtering through a different outer package type.

Fixes #266
2026-07-28 23:59:56 +08:00
DrSmoothl 19e3135e63 feat(onebot): expose friend remarks in stranger info
Return the already-decoded profile remark from fetched and cached get_stranger_info results, document its fallback shape, and regenerate the MCP action catalog.

Fixes #290
2026-07-28 23:59:25 +08:00
DrSmoothl eeaa5436fd fix(onebot): report private forwarded messages
Route both private forward actions through the existing self-sent echo callback while preserving the authoritative-receipt and canonical-echo guards.

Fixes #288
2026-07-28 23:58:48 +08:00
DrSmoothl 52a3c49752 fix(protocol): avoid duplicate private voice elements
Prefer a successfully decoded modern voice record over the empty legacy voice placeholder that can accompany private message pushes.

Preserve legacy-only voice messages and add a protobuf round-trip regression covering the duplicate segment reported in #291.

Fixes #291
2026-07-28 22:49:06 +08:00
DrSmoothl df3f8c5587 chore(release): v1.12.10 2026-07-26 19:29:28 +08:00
DrSmoothl 63abe98a84 fix(bridge): retry transient startup loading failures
Retry narrowly classified startup failures on later watcher ticks with a fixed attempt limit. Preserve permanent failures and record recovery, pending, and exhausted outcomes.

Add regression coverage for recovery, non-retry, and bounded exhaustion.
2026-07-26 16:04:57 +08:00
DrSmoothl d05bbe3551 fix(bridge): synchronize reconciled login state
Route recovered login state through the hook client before dependent services start. Add regression coverage to keep packet actions available after reconciliation.

Fixes #286.
2026-07-26 15:53:57 +08:00
DrSmoothl b5e10fefc2 feat(webui): configure login history backfill
Expose the per-account login history backfill switch in General settings and keep missing or legacy configuration disabled by default.

Document that changes apply on the next login, historical messages are stored locally without event replay or read-state changes, and fixed safety limits govern roster scanning, selected sessions, page size, request spacing, and retries.

Add WebUI normalization coverage so the optional setting survives save and restore without silently inheriting an enabled value. Refs #280.
2026-07-25 23:44:54 +08:00
DrSmoothl dc2ec1235a feat(onebot): backfill cloud history after login
Add an opt-in per-account login history backfill that waits for roster warmup and a 30-second grace period before silently filling local message history. The setting defaults to disabled and applies on the next account lifecycle.

Run one account at a time, prioritize known local gaps, and process at most three groups plus three friends with one 20-message page per session. Failures are logged and never retried during the same login.

Persist reconstructed history without dispatching OneBot events or changing QQ read state. Keep private metadata and event bodies atomic, honor recall tombstones, suppress live-only history side effects, avoid extra media requests, and stop queued, in-flight, or converting work when the account closes.

Share the persistence path with manual history actions and add lifecycle, cancellation, corruption, partial-failure, peer-identity, and storage-atomicity regression coverage. Refs #280.
2026-07-25 23:44:28 +08:00
DrSmoothl b71279dcc3 feat(core): add bounded login history queries
Expose a read-only cursor probe plus one-page group and private history methods for login backfill. Validate targets, ranges, response ordering, and page sizes before returning decoded events.

Serialize all history traffic through a process-wide gate. Automatic requests keep a two-second gap, accept at most 100 targets per kind and 20 sequence slots per session, and honor account cancellation before any queued network operation starts.

Keep the probe side-effect free by omitting read markers, and add focused tests for packet budgets, invalid responses, throttling, cancellation, and continued gate usability after failures. Refs #280.
2026-07-25 23:43:59 +08:00
DrSmoothl 95debcf34b fix(protocol): harden history response decoding
Share packet response validation across group and private history fetches so transport failures and empty responses cannot masquerade as empty pages.

Reject malformed group records and mismatched private-peer responses while preserving explicit QQ control-message filters. Mark fetched contexts as historical so old invite cards cannot overwrite live approval state.

Add wire-level regression coverage for failed responses, malformed entries, peer mismatches, ordering, and live-only identity observations. Refs #280.
2026-07-25 23:43:30 +08:00
DrSmoothl 5ad8027524 fix(onebot): report self-sent private files
Preserve authoritative receipts for private file sends and emit one message_sent event per actual QQ message. Split source uploads from chat publishing so failures surface instead of returning a synthetic zero-sequence receipt.

Fixes #282
2026-07-25 21:55:44 +08:00
DrSmoothl 3a7253315f feat(onebot): share HTTP listeners with WebSocket clients
Add an opt-in HTTP server setting that accepts OneBot WebSocket connections on the same port and access token while preserving standalone WebSocket server configurations.

Reuse the existing connection lifecycle for authentication, roles, events, heartbeat, streaming actions, token rotation, and shutdown. Expose the switch in WebUI and persist it through strict configuration validation and restore paths.

Refs: #281
2026-07-25 20:40:43 +08:00
DrSmoothl e16fa78b55 fix(onebot): distinguish private poke conversations
Preserve the private conversation peer separately from the poke sender and target. Emit NapCat-compatible user_id and sender_id fields while keeping group notices unchanged.

Add MsgPush and event-converter regression coverage for self-pokes across multiple friend sessions.

Fixes #285.
2026-07-25 20:28:28 +08:00
DrSmoothl 13a32a2865 fix(protocol): harden friend dress queries
Require the dress page to identify the requested account and every returned item before exposing the result. Reject malformed nested media metadata instead of silently degrading it.

Bound the HTML request to a 10-second redirect-chain deadline and a 2 MiB response body. Secure redirects by closing previous connections, stripping cross-origin credentials, rejecting cross-origin write forwarding, and surfacing malformed locations.

Replace the captured page with a minimal sanitized fixture and add protocol plus OneBot Action regression coverage for resource limits, redirect safety, response ownership, and structured failures.
2026-07-25 20:22:49 +08:00
H3CoF6 3517257aa6 feat(onebot): expose friend dress queries (#277)
Add a read-only action for querying QQ profile decorations from the authenticated web page.

Validate and classify page responses, expose structured errors, and cover parsing with a sanitized fixture.
2026-07-25 19:53:24 +08:00
H3CoF6 679756d1a7 fix(protocol): correct collection summary protobuf fields (#269)
Correct type 2 link and type 8 rich-media summary field mappings so collection responses no longer fail with unterminated groups.

Add wire-level regression coverage for both layouts.
2026-07-25 19:53:11 +08:00
DrSmoothl dff4b3b032 fix(friend): align remark and delete protocols
Route friend remark updates and clears through the commands used by current QQ clients. Emit the required delete flags and surface post-delete cache refresh failures.

Add byte-exact regression coverage for all affected requests.

Fixes #284.
2026-07-25 15:41:02 +08:00
DrSmoothl c64f9d3078 chore(release): v1.12.9 2026-07-24 14:15:51 +08:00
DrSmoothl 87a604ecbd feat(storage): add managed storage controls
Enforce a global log quota with configurable retention and observable degradation. Add authenticated storage reporting and safe cleanup controls to the settings UI. Protect active stream transfers and isolate parallel test resources.
2026-07-24 12:58:57 +08:00
DrSmoothl b884a1c479 fix(onebot): unify message segment type normalization
Keep empty-placeholder detection aligned with strict segment parsing.
2026-07-23 12:18:02 +08:00
DrSmoothl edd2ac278a fix(onebot): trace empty text placeholder normalization
Document the compatibility rule in action metadata and regenerate the MCP catalog.
2026-07-23 12:14:01 +08:00
DrSmoothl a7b9ba14fb fix(onebot): accept empty text placeholders in arrays
Fixes #273.
2026-07-23 12:08:17 +08:00
DrSmoothl 120dda1d9d fix(group-album): fetch all legacy album pages
Follow AlbumService cursors in get_group_album_list so the legacy array response contains every album instead of only the first page.

Reject missing or repeated cursors when the server reports more data, preventing silent truncation and pagination loops. Add regression coverage for multi-page aggregation and malformed cursors.

Fixes #272
2026-07-22 21:51:33 +08:00
DrSmoothl 97ab8dc393 chore(release): v1.12.8 2026-07-22 20:03:54 +08:00
DrSmoothl aed15b9a3f fix(group-album): return video media metadata
Decode the QQ group album video payload, including cover, duration, and multi-resolution URLs. Add a wire-level regression test and update generated action documentation.

Fixes #270
2026-07-22 20:00:07 +08:00
DrSmoothl 7fb8aa1d42 fix(webui): keep node dialog actions visible
Separate the node editor into fixed header and footer rows with an independently scrollable form body, so short viewports cannot push the save action out of reach.
2026-07-22 00:02:48 +08:00
DrSmoothl 622c90d418 fix(protocol): transcode QQ AI voice recordings
Normalize the observed AI SILK container marker at the shared audio transcode boundary before invoking the bundled decoder. Preserve caller-owned bytes and leave ordinary SILK, AMR, and unrelated inputs unchanged.

Add unit and packaged-addon regression coverage for MP3 conversion, payload preservation, and input immutability.

Fixes #268
2026-07-21 23:29:28 +08:00
DrSmoothl eed2e692b1 fix(onebot): expose robot status for group members
Fetch QQ's versioned robot UIN ranges, classify and persist member status, and surface is_robot from both group member actions.

Preserve unknown legacy cache entries and fail visibly when classification is unavailable.

Closes #265
2026-07-21 23:27:01 +08:00
DrSmoothl ff60221330 feat(onebot): support private window shake messages
Encode poke message segments as private window shake messages while keeping the dedicated send_poke action unchanged.

Restrict window shakes to a single ordinary private-chat segment. Reject group, temporary-session, mixed-message, and forwarded usage before identity lookup, media upload, or packet transmission.

Add full outbound request coverage, OneBot action regressions, and live private-chat verification for issue #259.

Closes #259
2026-07-21 19:28:17 +08:00
DrSmoothl d8d556eb70 docs(legal): align EULA with current license
Replace obsolete AGPL references with the source-available non-commercial terms. Clarify commercial authorization, proprietary addon restrictions, document precedence, and termination handling. Bump the bilingual EULA to version 1.1 effective 2026-07-21.
2026-07-21 11:44:52 +08:00
DrSmoothl feb7fcac0e feat(group-album): expose cover and upload metadata
Decode the verified album cover response field and expose normalized cover details and last-upload timestamps through both album list actions. Preserve the legacy numeric timestamp shape, retain string timestamps for the native response, return null when no cover exists, and avoid additional network requests.

Document the new output contracts in the OneBot and MCP catalogs. Add independent wire fixtures and action-level regression tests for the protocol mapping and public response shapes.

Refs #257
2026-07-20 23:37:41 +08:00
DrSmoothl 4aa2cd1693 fix(onebot): correct private message history (#256)
Use the C2C roam cursor and canonical NT sequence for bidirectional history. Persist direction-aware recall tombstones so recalled messages cannot reappear.
2026-07-20 22:25:13 +08:00
DrSmoothl 88216ce644 chore(release): v1.12.7 2026-07-20 15:52:49 +08:00
DrSmoothl 4ba2b27398 fix(onebot): keep synthetic sequences out of history
Distinguish QQ-authoritative message sequences from local message IDs so group files and reply placeholders cannot become history anchors or be reused by protocol actions.

Filter QQ null roam records and migrate previously stored synthetic rows.

Fixes #254
2026-07-20 15:33:28 +08:00
DrSmoothl 2c8a8af514 test(protocol): centralize nested operator fixture
Name the GroupChange.decreaseType field explicitly and reuse one wire fixture across member-increase and member-decrease coverage.
2026-07-20 14:12:10 +08:00
DrSmoothl 2dbd321ef0 fix(protocol): decode nested group operators
Recognize both raw UTF-8 UIDs and nested OperatorInfo envelopes in GroupChange pushes while keeping self-kick and voluntary-leave semantics explicit.\n\nFixes #253.
2026-07-20 14:08:50 +08:00
DrSmoothl ae6093cf23 docs(mcp): document AI voice message IDs
Regenerate the MCP Action catalog so send_group_ai_record advertises the real OneBot message_id returned after a successful AI voice send.

Keep the generic MCP tool surface unchanged while making the corrected result contract visible to agents and clients.

Refs #250
2026-07-20 14:03:32 +08:00
DrSmoothl fc80a598c0 fix(onebot): return AI voice message IDs
Build send_group_ai_record results from the canonical group-message sequence returned by the Core receipt correlator, using the same message ID mapping as normal inbound events.

Stop reporting the historical placeholder value of zero and surface receipt failures through the standard Action error path. Preserve the existing get_ai_record URL response and update the SDK result documentation without changing its public shape.

Add Action-level coverage for canonical ID generation and missing-receipt failures.

Refs #250
2026-07-20 14:03:13 +08:00
DrSmoothl 297f0428cc fix(core): correlate AI voice send receipts
Wait for the canonical self group-message event after AI voice synthesis instead of interpreting undocumented response fields as a message sequence.

Correlate receipts by exact media UUID, buffer response races, and claim each semantic message identity only once across concurrent calls and duplicate multi-process pushes. Reject missing identifiers, invalid sequences, bounded-buffer overflow, and receipt timeouts with explicit diagnostics.

Keep fetchAiVoice focused on returning the media node and add regression coverage for race ordering, unrelated events, identical concurrent audio, duplicate pushes, malformed receipts, and timeout cleanup.

Fixes #250
2026-07-20 14:02:48 +08:00
DrSmoothl 06c26dee87 fix(group-album): use native QQ album service
Replace the lossy Qzone album-list endpoint with the QQ NT AlbumService protobuf request. Preserve creator nicknames and expose native pagination for get_qun_album_list.
2026-07-20 13:03:16 +08:00
DrSmoothl 8df62d6486 fix(onebot): report API-sent private messages
Emit message_sent.private after successful friend messages sent through OneBot actions or the WebUI debug console when QQ does not provide an inbound self echo.

Keep a later QQ echo as the canonical stored event while suppressing duplicate downstream delivery across both race orders. Match echoes by conversation, sequence, message ID, and a bounded time window; leave group messages, temporary sessions, split file sends, unreliable receipts, and messages sent manually from the QQ client unchanged.

Add regression coverage for action-only reporting, both echo race orders, hash collisions, cached-but-unreported events, temporary sessions, and incomplete receipts.

Fixes #251
2026-07-20 13:02:29 +08:00
DrSmoothl 810d72fa04 feat(onebot): implement collection list retrieval
Replace the get_collection_list placeholder with authenticated, read-only collection retrieval through the existing bridge API.

Add strict binary envelope validation, bounded pagination, accurate category filtering, preserved 64-bit identifiers, and explicit ticket, transport, service, and malformed-response failures. Cap item counts, page traversal, response bytes, per-request waits, and the total operation time.

Expose the compatible response model through Core, OneBot, the SDK, and the generated MCP catalog. Cover protocol framing, cursor behavior, filtered hasMore semantics, cleanup failures, bridge ticket acquisition, and Action validation with regression tests.

Verified with the live test bot without changing native components or adding any collection write behavior.
2026-07-19 20:22:16 +08:00
DrSmoothl 4e62fdc80b chore(release): v1.12.6 2026-07-19 19:38:13 +08:00
DrSmoothl 4520687fbe docs(webui): clarify custom pointer default
State in the appearance settings that the custom cursor and context-menu system is disabled by default.
2026-07-19 19:37:49 +08:00
DrSmoothl a9b8440731 fix(webui): disable custom pointer system by default
Default new and legacy-normalized appearance configs to native cursor and context-menu behavior while preserving explicit opt-in settings.
2026-07-19 19:33:26 +08:00
DrSmoothl f3bfec04a5 feat(onebot): implement online client queries
Replace the get_online_clients placeholder with the latest QQ online-device snapshot and return stable OneBot fields for client ID, device name, and localized device category.

Fail explicitly when no snapshot has been observed or when callers request an unsupported fresh refresh, while preserving an observed empty snapshot as a successful result. Update SDK types and generated MCP schemas, and add action-level coverage for every state.
2026-07-19 19:20:28 +08:00
DrSmoothl 168f414cd9 feat(core): retain online device snapshots
Store the latest online-device snapshot for each Bridge lifecycle and expose it through the bridge contract as an immutable, owned value.

Distinguish a snapshot that has not yet been observed from a valid empty snapshot, replace state atomically on each QQ update, clear it during disposal, and cover lifecycle, immutability, and cleanup behavior with focused tests.
2026-07-19 19:20:14 +08:00
DrSmoothl b92c8ad881 feat(protocol): decode online device snapshots
Decode Event 0x210 subtype 349 into typed online-device snapshots, including QQ-compatible low-byte client type normalization and one-entry-per-device-category projection.

Keep replacement snapshots outside system-message deduplication, reject malformed device identities observably, and add wire-level regressions for complete, packed, repeated, and invalid payloads. Live verification covered mobile account switching without requiring native changes.
2026-07-19 19:19:58 +08:00
DrSmoothl e6a69b05a7 feat(onebot): expose group folder upload metadata
Decode the folder modifier metadata returned by group file listings and project it as last upload time, uploader ID, and uploader name for both folder listing actions.

Regenerate the MCP catalog and add protocol, bridge, OneBot projection, and action schema coverage for the new fields.

Closes #248
2026-07-19 18:34:53 +08:00
DrSmoothl f3e0c4e45a fix(onebot): allow clearing the self signature
Accept explicit empty strings from both longNick and long_nick when callers need to clear the bot signature. Missing and non-string values remain rejected before reaching the bridge.

Preserve the QQ-compatible clear representation by omitting the empty profile value, and add action-level and wire-level regression coverage. Live verification confirmed successful clearing and readback on the test bot.

Fixes #247
2026-07-19 18:12:48 +08:00
DrSmoothl 65e819d96e feat(onebot): expose stranger profile signatures
Return the NapCat-compatible long_nick field from get_stranger_info for both freshly fetched and cached user profiles. Keep the field present as an empty string when profile data is unavailable so callers receive a stable response shape.

Document the response contract in the Action schema and generated MCP catalog, and cover fetched, cached, and empty fallback paths with regression tests. This change reuses the existing profile signature value and does not add QQ requests or alter protocol packets.

Closes #246
2026-07-19 17:26:59 +08:00
DrSmoothl 3c2a402b8a test(bridge): make pipe-close regression deterministic
Replace the Unix socket servers with an in-memory Duplex transport so the mid-send close regression runs in restricted environments and on Windows.

Wait until the control write begins before closing the transport, assert the exact close error, and use an event-loop boundary to detect leaked promise rejections without timing sleeps.

This keeps the test on the public QqHookClient send path while removing unrelated OS socket setup and does not change production behavior.
2026-07-19 16:52:45 +08:00
DrSmoothl 78101b3512 fix(core): send group album pagination cursors
Encode the opaque media-list cursor in the protobuf page-info field while leaving the reserved field empty. This restores subsequent-page requests without changing the OneBot action or response shape.

Add an independent wire oracle so future protocol definition drift cannot make the encoder regression test pass against itself.

Fixes #245
2026-07-19 16:28:01 +08:00
DrSmoothl 613b2b1e68 fix(proton): decode extended uint32 field varints
Consume complete well-formed value varints before retaining their low 32 bits, matching QQ push behavior without relaxing tag or length parsing.

Add generator and end-to-end group reaction regressions, including truncated and malformed varint coverage. Refs #242.
2026-07-19 15:35:53 +08:00
DrSmoothl 87bab6666b fix(webui): preserve dashboard widget settings
Keep per-widget configuration when persisted overview layouts are migrated against the current widget catalogue. Account shortcuts, notes, links, filters, and other configurable widgets now retain their saved values after a page reload.

Add a WebUI Vitest entry point and regression coverage for restoring an account widget with saved configuration.

Fixes #243.
2026-07-19 15:26:22 +08:00
DrSmoothl 605b5d1104 feat(webui): expose custom pointer controls
Add a single appearance setting for SnowLuma's adaptive cursor and custom context menu, enabled by default for existing and new installations.

Turning the setting off immediately removes both interaction layers and restores the browser's native cursor and context menu. The preference remains synchronized through the existing server-backed appearance configuration.
2026-07-18 23:39:06 +08:00
DrSmoothl d40c803ed9 feat(webui): add adaptive pointer interactions
Introduce a CSS-driven adaptive cursor that morphs for controls, text editing, dragging, resizing, busy states, and other native pointer semantics on desktop devices.

Add a themed context menu for editing, selections, links, images, and page navigation while preserving explicit native-menu escape paths. Store a default-on interaction preference through the normalized appearance model and cover its migration and opt-out behavior.
2026-07-18 23:38:43 +08:00
DrSmoothl c15625dbd8 feat(webui): add spring-based range sliders
Replace native range inputs with an accessible Radix-backed control that preserves keyboard and assistive-technology semantics.

Reproduce the elastic handle, track stretch, tick visibility, and reduced-motion behavior while keeping SnowLuma theme tokens. Adopt the component for interface scale and background image controls.
2026-07-18 23:38:00 +08:00
693 changed files with 98469 additions and 9217 deletions

No files matched your search

+8 -2
View File
@@ -2,7 +2,7 @@ root = true
[*]
charset = utf-8
end_of_line = crlf
end_of_line = lf
indent_style = space
indent_size = 2
insert_final_newline = true
@@ -11,5 +11,11 @@ trim_trailing_whitespace = true
[*.{json,yml,yaml,md}]
indent_size = 2
[*.py]
indent_size = 4
[*.bat]
end_of_line = crlf
[*.md]
trim_trailing_whitespace = false
trim_trailing_whitespace = false
+14
View File
@@ -0,0 +1,14 @@
* text=auto eol=lf
*.bat text eol=crlf
*.node binary
*.dll binary
*.so binary
*.dylib binary
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.woff2 binary
+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.
+68 -16
View File
@@ -1,12 +1,5 @@
# Run the full workspace test suite on every pull request.
#
# The repo previously had no PR test gate, so broken tests could land on `dev`
# unnoticed — and did (protocol's oidb-service rejection path, plus an external
# contributor PR). This gates every PR on the whole suite.
#
# `pnpm -r --no-bail --if-present test` runs each package's `test` script
# (skipping packages without one); --no-bail means one failing package still
# reports the rest, and the run as a whole still fails if any package fails.
# Run the root validation commands on every pull request.
# Command list is duplicated in tools/ci-check.mjs — keep them identical.
name: CI
on:
@@ -33,21 +26,80 @@ jobs:
- uses: actions/setup-node@v6
with:
node-version: '22'
node-version-file: '.node-version'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Run all package tests
run: pnpm -r --no-bail --if-present test
run: pnpm test
# The MCP test suite regenerates the action catalog (catalog.ts + the
# 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: |
if ! git diff --exit-code -- packages/mcp/src/generated; then
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
steps:
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Type check all packages
run: pnpm typecheck
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build release inputs
run: pnpm run build:all
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Lint managed source files
run: pnpm lint
+6 -3
View File
@@ -78,7 +78,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
node-version-file: '.node-version'
cache: 'pnpm'
- name: Install dependencies
@@ -121,7 +121,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
node-version-file: '.node-version'
cache: 'pnpm'
- name: Install dependencies
@@ -143,9 +143,12 @@ jobs:
working-directory: dist
run: npm install --omit=dev
- name: Verify release layout
run: pnpm check:release-layout
# Naming convention:
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node >= 22
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+)
- name: Package (windows)
if: matrix.os == 'windows-latest'
shell: pwsh
@@ -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: '22'
# 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}"
+41 -4
View File
@@ -9,7 +9,38 @@ permissions:
contents: write
jobs:
preflight:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Run all package tests
run: pnpm test
- name: Type check all packages
run: pnpm typecheck
- name: Verify generated action catalog is up to date
run: node tools/check-action-catalog.mjs
build:
needs: preflight
strategy:
fail-fast: false
matrix:
@@ -39,7 +70,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
node-version-file: '.node-version'
cache: 'pnpm'
- name: Install dependencies
@@ -58,9 +89,12 @@ jobs:
working-directory: dist
run: npm install --omit=dev
- name: Verify release layout
run: pnpm check:release-layout
# Naming convention:
# SnowLuma-<tag>-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node >= 22
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+)
- name: Package (windows)
if: matrix.os == 'windows-latest'
shell: pwsh
@@ -127,7 +161,7 @@ jobs:
## 选择下载
| 平台 | 完整版(内置 Node.js,推荐) | Lite(需 Node.js 22+) |
| 平台 | 完整版(内置 Node.js,推荐) | Lite(Node.js 22.13+;23 系需 23.4+) |
| --- | --- | --- |
| Windows x64 | \`SnowLuma-${tag}-win-x64.zip\` | \`SnowLuma-${tag}-win-x64-lite.zip\` |
| Linux x64 | \`SnowLuma-${tag}-linux-x64.tar.gz\` | \`SnowLuma-${tag}-linux-x64-lite.tar.gz\` |
@@ -183,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: |
@@ -198,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,
@@ -211,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: '22'
# 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}"
+1 -1
View File
@@ -38,7 +38,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
node-version-file: '.node-version'
cache: 'pnpm'
- name: Install dependencies
+10 -10
View File
@@ -37,7 +37,10 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
# 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}"
+1
View File
@@ -0,0 +1 @@
22.13.0
+1 -10
View File
@@ -1,13 +1,4 @@
registry=https://registry.npmmirror.com/
@moonrepo:registry=https://registry.npmmirror.com/
# Mirrors for binary downloads (sharp, esbuild, swc, electron etc.)
disturl=https://npmmirror.com/dist
electron_mirror=https://npmmirror.com/mirrors/electron/
sass_binary_site=https://npmmirror.com/mirrors/node-sass/
sharp_binary_host=https://npmmirror.com/mirrors/sharp
sharp_libvips_binary_host=https://npmmirror.com/mirrors/sharp-libvips
puppeteer_download_host=https://npmmirror.com/mirrors
auto-install-peers=true
strict-peer-dependencies=false
engine-strict=true
+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
+53 -47
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/` 下能看出大致脉络。
@@ -43,10 +51,14 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
### 系统要求
- **Node.js ≥ 22**(`engines` 字段强制,低版本会报错)
- **pnpm 10.28.0+**(项目通过 `packageManager` 字段锁定,建议用 `corepack enable` 安装匹配版本)
- **Node.js 22.13+(23 系需 23.4+)**(项目使用默认启用的 `node:sqlite`)
- **pnpm 10.28.0**(项目通过 `packageManager` 与 CI 统一版本)
- macOS / Linux / Windows 均可。如果要构建原生产物,需要对应平台的工具链。
如果系统提供 Corepack,可执行 `corepack enable pnpm`;没有 Corepack 时可执行
`npm install -g pnpm@10.28.0`。进入仓库后,`node --version` 与
`pnpm --version` 应满足上述版本要求,否则安装会直接失败。
### 拉代码、装依赖、跑起来
```bash
@@ -57,13 +69,13 @@ cd SnowLuma
# 2. 切到 dev 分支(所有开发都基于 dev,不是 main)
git checkout dev
# 3. 安装依赖
pnpm install
# 3. 按锁文件安装依赖
pnpm install --frozen-lockfile
# 4. 跑类型检查,确认环境 OK
pnpm typecheck
# 5. 跑测试
# 5. 跑全工作区测试
pnpm test
# 6. 启动开发模式
@@ -79,7 +91,7 @@ pnpm dev:web # webui
### 1. 创建分支
请基于 `dev` 创建分支,不是 `main`。`main` 是受保护的稳定分支,PR 也不要直接提到 `main`。
请基于 `dev` 创建分支,不是 `main`。`main` 是发布指针,只由维护者的 Promote 更新,PR 不要提到 `main`。
```bash
git checkout dev
@@ -96,14 +108,17 @@ git checkout -b fix/onebot-mention-encoding
- **写测试**:修 bug 时优先写一个能复现该 bug 的测试,确认它会 fail,再让它 pass。新增功能至少补上 happy path 的测试。
- **不要添加无意义的注释**:标识符已经说清楚的事情不需要再写一遍。注释应当解释"为什么",而不是"做了什么"。
提交之前请本地跑一遍:
提交之前请运行与 PR CI 相同的验证入口:
```bash
pnpm typecheck
pnpm lint
pnpm test
pnpm run build:all
```
CI 上跑的是同一套检查,本地通过几乎能保证 CI 通过。
`pnpm test` 会运行所有声明了测试脚本的工作区包;只验证 Core 时可使用
`pnpm test:core`。CI 会重新执行上述完整检查。
### 3. 提交信息
@@ -126,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
@@ -145,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`。
---
@@ -184,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]` 写在最前面。
@@ -213,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
@@ -253,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
```
+22 -20
View File
@@ -1,7 +1,7 @@
# SnowLuma 最终用户许可协议(EULA)/ End-User License Agreement
- **生效日期 / Effective date:** 2026-06-19
- **版本 / Version:** 1.0
- **生效日期 / Effective date:** 2026-07-21
- **版本 / Version:** 1.1
- **许可方 / Licensor:** SnowLumaDevs(联系方式 / Contact: motricseven@foxmail.com)
> 本协议以中文与英文两种语言提供。如两版本有冲突,**以中文版本为准**。
@@ -17,14 +17,15 @@
1.3 下载、安装、运行或使用本软件,即表示您已阅读、理解并同意受本协议约束。**若您不同意本协议,请勿使用本软件并删除其全部副本。**
### 2. 授权范围
2.1 本软件的**源代码**依据 GNU Affero General Public License 第 3 版(AGPL-3.0)及其第 7 条附加许可(原生模块链接例外)授权,详见随附的 `LICENSE` 文件。
2.2 本协议是针对**发行包(二进制)**的补充条款,就 AGPL 未涵盖之事项(接受方式、可接受使用、免责、专有组件、争议解决等)作出约定。
2.3 **本协议不减损 AGPL 授予您的任何权利。** 对于您依 AGPL 单独获取、使用、修改或分发源代码的行为,本协议不附加任何限制。
2.4 专有组件(见第 5 条)不属于 AGPL 授权范围,依其各自条款授权。
2.1 本软件的**源代码与资源**(不含第 5 条所述专有组件及第三方组件)依据随附的 [`LICENSE`](LICENSE)——**SnowLuma 源码可见非商业许可(SnowLuma Source-Available Non-Commercial License)**——授权。
2.2 `LICENSE` 仅授予其中明确列明的权利,包括查看、学习、个人或其他非商业使用、非商业自托管,以及在规定条件下进行修改或再分发。**任何商业使用,以及公开发布修改版或衍生版,均须事先取得著作权人的书面授权。**
2.3 本协议是针对**官方发行包(二进制)**的补充条款,就接受方式、可接受使用、免责、专有组件、终止及争议解决等事项作出约定;本协议不扩大、替代或暗示授予 `LICENSE` 未明确授予的权利。
2.4 专有组件(见第 5 条)不属于源码许可范围,仅按 `LICENSE` 第 5 条及本协议允许的方式使用。
2.5 就源代码与资源的许可范围而言,以 `LICENSE` 为准;就官方发行包中的专有组件及二进制特有事项而言,以本协议为准。另行签署或出具的书面商业授权,仅在其明确约定的主体、用途、范围、数量及期限内优先适用。
### 3. 免责声明
3.1 **非官方、无隶属**:本软件是独立的第三方互操作性项目,与腾讯公司(Tencent)及 QQ **无任何隶属、合作、授权或背书关系**。"QQ""腾讯"等名称及标识为其各自所有者的商标。
3.2 **用途**:本软件**仅供学习、研究与技术互操作之目的**提供。
3.2 **用途**:除非事先取得书面商业授权,本软件仅供 `LICENSE` 允许的**个人或其他非商业用途**使用,包括学习、研究、技术互操作与非商业自托管。
3.3 **合规义务**:您须自行确保对本软件的使用符合一切适用法律法规,以及您所接入平台的规定(包括但不限于《QQ 用户协议》与相关服务条款)。
3.4 **按"现状"提供**:本软件按"**现状(AS-IS)**"及"**现有(AS-AVAILABLE)**"提供,不附带任何明示或默示的担保,包括但不限于对适销性、特定用途适用性、不侵权、可用性、准确性或不中断的担保。
3.5 **责任限制**:在适用法律允许的最大范围内,对于因使用或无法使用本软件而导致的任何直接、间接、偶然、特殊、惩罚性或后果性损害(包括但不限于账号封禁或限制、数据丢失、利润或业务损失、服务中断),SnowLumaDevs **概不承担责任**。
@@ -34,13 +35,13 @@
您**不得**将本软件用于:(a) 任何违法犯罪活动;(b) 未经授权访问、干扰或破坏任何系统或网络;(c) 发送垃圾信息、实施骚扰、欺诈或传播恶意内容;(d) 侵犯他人隐私、知识产权或其他合法权益;(e) 任何违反所接入平台服务条款的行为。
### 5. 专有组件
5.1 本软件可能包含或依赖**非开源的专有组件**,包括但不限于 **SnowLuma 原生模块**(`snowluma-*.node`),以及其中可能包含的任何授权、激活或技术保护措施。
5.2 此类专有组件的**源代码不依 AGPL 提供**,受本条款约束。
5.1 本软件可能包含或依赖**专有组件**,包括但不限于 SnowLuma 原生附加组件(如 `snowluma-*.node`、`snowluma-*.dll`、`snowluma-*.so`),以及其中可能包含的授权、激活或技术保护措施。
5.2 此类专有组件不属于 `LICENSE` 所授权的源代码与资源,仅以随本软件提供的预编译形式按本条款授权使用;本协议不授予其源代码权利。
5.3 除适用法律强制性规定明确允许外,您不得对专有组件进行逆向工程、反编译或反汇编,亦不得规避、破解或绕过其授权或激活机制。
5.4 `LICENSE` 第 7 条的链接例外仅允许将本软件与该原生模块**组合并分发**,**并不**向您授予该原生模块本身的源代码权利。
5.4 除事先取得著作权人的书面授权外,您仅可为 `LICENSE` 允许的非商业用途,以专有组件随本软件提供的形式运行该组件;不得复制、修改、单独再分发或再许可该组件。将其并入第三方安装包或 Docker 镜像、通过自动化脚本部署,或者将其用于任何商业用途,均须事先取得书面授权。
### 6. 终止
若您违反本协议任何条款,本协议项下授予您的权利(**不含**您依 AGPL 单独享有的权利)将自动终止。终止后,您应停止使用并删除发行包中的专有组件。
若您违反本协议或适用的 `LICENSE` 条款,相关授权将依各自的终止条款自动终止。终止后,您应停止使用官方发行包并删除其中的专有组件;源代码与资源的后续处理依 `LICENSE` 执行。任何单独书面商业授权的终止及终止后处理,以该授权文件的明确约定为准。
### 7. 适用法律与争议解决
本协议的订立、效力、解释、履行及争议解决,均适用**中华人民共和国大陆地区法律**(不含其冲突法规则)。因本协议引起或与之相关的任何争议,双方应首先友好协商解决;协商不成的,任何一方可向**有管辖权的人民法院**提起诉讼。
@@ -58,14 +59,15 @@ SnowLumaDevs 可不时更新本协议。更新后的版本将随发行包发布
1.3 By downloading, installing, running, or using the Software, you acknowledge that you have read, understood, and agree to be bound by this Agreement. **If you do not agree, do not use the Software and delete all copies.**
### 2. Scope of License
2.1 The **source code** of the Software is licensed under the GNU Affero General Public License version 3 (AGPL-3.0) together with its Section 7 additional permission (the native-addon linking exception); see the accompanying `LICENSE` file.
2.2 This Agreement provides **supplemental terms for the binary distribution packages**, addressing matters not covered by the AGPL (acceptance, acceptable use, disclaimers, proprietary components, dispute resolution).
2.3 **This Agreement does not diminish any rights granted to you under the AGPL.** It imposes no additional restriction on your acquisition, use, modification, or distribution of the source code under the AGPL.
2.4 Proprietary Components (Section 5) are outside the scope of the AGPL and are licensed under their own terms.
2.1 The **source code and assets** of the Software (excluding the Proprietary Components described in Section 5 and third-party components) are licensed under the accompanying [`LICENSE`](LICENSE), the **SnowLuma Source-Available Non-Commercial License**.
2.2 The `LICENSE` grants only the rights expressly stated in it, including viewing, studying, personal or other Non-Commercial use, Non-Commercial self-hosting, and modification or redistribution subject to its conditions. **Any Commercial Use, and any public release of a modified or derivative version, requires the copyright holder's prior written authorization.**
2.3 This Agreement provides **supplemental terms for official binary distribution packages**, addressing acceptance, acceptable use, disclaimers, Proprietary Components, termination, and dispute resolution. It does not expand, replace, or imply any right not expressly granted by the `LICENSE`.
2.4 Proprietary Components (Section 5) are outside the scope of the source license and may be used only as permitted by Section 5 of the `LICENSE` and this Agreement.
2.5 The `LICENSE` controls the scope of rights in the source code and assets; this Agreement controls Proprietary Components in official distribution packages and matters specific to those binaries. A separate written commercial authorization controls only within the licensee, purpose, scope, quantity, and term that it expressly identifies.
### 3. Disclaimers
3.1 **Not official; no affiliation.** The Software is an independent, third-party interoperability project and has **no affiliation, partnership, authorization, or endorsement relationship** with Tencent or QQ. "QQ", "Tencent", and related marks belong to their respective owners.
3.2 **Purpose.** The Software is provided **solely for learning, research, and technical interoperability**.
3.2 **Purpose.** Unless prior written commercial authorization has been obtained, the Software may be used only for **personal or other Non-Commercial purposes** permitted by the `LICENSE`, including study, research, technical interoperability, and Non-Commercial self-hosting.
3.3 **Compliance.** You are responsible for ensuring that your use complies with all applicable laws and with the terms of any platform you connect to (including the QQ User Agreement and related terms of service).
3.4 **AS-IS.** The Software is provided "**AS IS**" and "**AS AVAILABLE**", without warranties of any kind, express or implied, including merchantability, fitness for a particular purpose, non-infringement, availability, accuracy, or uninterrupted operation.
3.5 **Limitation of liability.** To the maximum extent permitted by law, SnowLumaDevs shall **not be liable** for any direct, indirect, incidental, special, punitive, or consequential damages (including account suspension or restriction, data loss, lost profits or business, or service interruption) arising from use of or inability to use the Software.
@@ -75,13 +77,13 @@ SnowLumaDevs 可不时更新本协议。更新后的版本将随发行包发布
You shall **not** use the Software for: (a) any unlawful activity; (b) unauthorized access to, interference with, or disruption of any system or network; (c) spam, harassment, fraud, or malicious content; (d) infringement of others' privacy, intellectual-property, or other lawful rights; or (e) any conduct that violates the terms of service of a connected platform.
### 5. Proprietary Components
5.1 The Software may include or depend on **non-free proprietary components**, including but not limited to the **SnowLuma native addon** (`snowluma-*.node`) and any licensing, activation, or technical-protection measures it may contain.
5.2 The **source code of such components is not provided under the AGPL** and is governed by these terms.
5.1 The Software may include or depend on **Proprietary Components**, including but not limited to SnowLuma native addons such as `snowluma-*.node`, `snowluma-*.dll`, and `snowluma-*.so`, and any licensing, activation, or technical-protection measures they may contain.
5.2 Such Proprietary Components are outside the source code and assets licensed by the `LICENSE` and are provided only in precompiled form with the Software for use under this Section. This Agreement grants no right to their source code.
5.3 Except to the extent expressly permitted by mandatory applicable law, you may not reverse engineer, decompile, or disassemble the Proprietary Components, nor circumvent, crack, or bypass their licensing or activation mechanisms.
5.4 The Section 7 linking exception in `LICENSE` permits only the **combination and distribution** of the Software with the SnowLuma native addon; it does **not** grant you rights to that addon's own source code.
5.4 Unless the copyright holder has given prior written authorization, you may run a Proprietary Component only as supplied with the Software and only for Non-Commercial use permitted by the `LICENSE`; you may not reproduce, modify, redistribute it separately, or relicense it. Incorporating it into a third-party installer or Docker image, deploying it through an automated script, or using it for any Commercial Use requires prior written authorization.
### 6. Termination
If you breach any term of this Agreement, the rights granted to you hereunder (**excluding** rights you hold separately under the AGPL) terminate automatically. Upon termination you must cease use of and delete the Proprietary Components from the distribution package.
If you breach this Agreement or the applicable `LICENSE`, the relevant rights terminate automatically under their respective termination provisions. Upon termination, you must cease using the official distribution package and delete its Proprietary Components; further handling of the source code and assets is governed by the `LICENSE`. Termination of any separate written commercial authorization, and the parties' post-termination rights and obligations, are governed by that authorization's express terms.
### 7. Governing Law and Disputes
This Agreement is governed by the laws of the **mainland of the People's Republic of China** (excluding its conflict-of-laws rules). Any dispute arising out of or relating to this Agreement shall first be resolved through good-faith negotiation; failing that, either party may bring an action before a **court of competent jurisdiction**.
+38 -87
View File
@@ -12,19 +12,26 @@
<p align="center">
<a href="#快速开始">快速开始</a> ·
<a href="#运行链路">运行链路</a> ·
<a href="./docs/onebot-actions.md">动作参考</a> ·
<a href="./packages/sdk/README.md">SDK</a> ·
<a href="./packages/mcp/README.md">MCP</a> ·
<a href="https://github.com/SnowLuma/SnowLuma/issues">问题反馈</a>
</p>
SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时。它把 QQ 原生会话转换为 [OneBot v11](https://github.com/botuniverse/onebot-11) 动作与事件,并通过 WebSocket、HTTP、WebUI、SDK 和 MCP 提供统一入口;每个账号拥有独立会话,适合机器人开发、自动化与协议研究。
SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时,将 QQ 原生会话转换为 [OneBot v11](https://github.com/botuniverse/onebot-11) 动作与事件,并通过 WebSocket、HTTP、WebUI、SDK 和 MCP 提供统一入口。
> [!CAUTION]
> **使用边界**:SnowLuma 是独立的第三方互操作项目,**与腾讯 / QQ 无任何隶属或授权关系**。本项目仅供学习与技术研究,请遵守《QQ 用户协议》及适用法律;软件按“现状”提供、不附带任何担保,使用风险自负。详见 [`EULA.md`](EULA.md)。
> SnowLuma 是独立的第三方项目,与腾讯 / QQ 无隶属或授权关系。项目仅供学习与技术研究,请遵守《QQ 用户协议》及适用法律;软件按“现状”提供,使用风险自负。详见 [`EULA.md`](EULA.md)。
>
> **Disclaimer**: SnowLuma is an independent third-party interoperability project with no affiliation with or endorsement by Tencent / QQ. It is provided for study and research only, “as is” and without warranty. See [`EULA.md`](EULA.md).
> **Disclaimer:** SnowLuma is independent of Tencent / QQ and is provided for study and research only, “as is” and without warranty.
## 核心能力
| 场景 | 能力 |
| --- | --- |
| OneBot 接入 | OneBot v11 动作与事件;WebSocket 服务端 / 客户端及 HTTP 服务端 / 上报 |
| 消息与媒体 | 文本、图片、语音、视频、文件、回复、提及、转发及常见卡片 |
| 多账号运行 | 各账号独立维护会话、身份映射、消息存储和网络配置 |
| WebUI 管理 | 账号状态、实时日志、连接配置、动作调试和存储管理 |
| 开发者工具 | [`@snowluma/sdk`](packages/sdk/README.md) 与 [`@snowluma/mcp`](packages/mcp/README.md) |
## 运行链路
@@ -32,120 +39,64 @@ SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时。它把 QQ 原
<img src="./assets/readme/runtime-map.svg" width="100%" alt="QQ 会话经过协议桥接与 OneBot 标准化后连接到 WebSocket、HTTP、WebUI、SDK 和 MCP" />
</p>
SnowLuma 将会话接入、协议解析、身份映射、OneBot 转换和网络适配拆成清晰边界。多个 QQ 账号可以并行运行,同时保持独立状态、日志与连接配置。
## 核心能力
| 场景 | SnowLuma 提供 |
| --- | --- |
| OneBot 接入 | OneBot v11 动作与事件,支持 WebSocket 服务端 / 客户端及 HTTP 服务端 / 上报 |
| 消息与媒体 | 文本、图片、语音、视频、文件、回复、提及、转发及 JSON / XML 卡片等常见消息元素 |
| 多账号运行 | 每个 QQ 账号独立维护会话、身份映射、消息存储与网络适配器 |
| WebUI 管理 | 账号状态、实时日志、连接配置、动作调试、密码管理与可定制总览 |
| 开发者工具 | 提供 [`@snowluma/sdk`](packages/sdk/README.md) 与 [`@snowluma/mcp`](packages/mcp/README.md) |
| 可观察错误 | 关键解析与执行失败会留下明确上下文,不以静默丢弃掩盖问题 |
会话接入、协议解析、身份映射、OneBot 转换和网络适配保持独立边界;多个 QQ 账号可并行运行。
## 快速开始
### 1. 选择发行包
1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载对应平台的完整发行包并解压。Lite 版需 Node.js 22.13+(23 系需 23.4+)。
2. Windows 运行 `launcher.bat`;Linux 执行:
前往 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载与你的平台匹配的版本:
```bash
chmod +x launcher.sh
./launcher.sh
```
| 平台 | 完整版(内置 Node.js,推荐) | Lite(需要 Node.js 22+) |
| --- | --- | --- |
| Windows x64 | `SnowLuma-vX.Y.Z-win-x64.zip` | `SnowLuma-vX.Y.Z-win-x64-lite.zip` |
| Linux x64 | `SnowLuma-vX.Y.Z-linux-x64.tar.gz` | `SnowLuma-vX.Y.Z-linux-x64-lite.tar.gz` |
| Linux arm64 | `SnowLuma-vX.Y.Z-linux-arm64.tar.gz` | `SnowLuma-vX.Y.Z-linux-arm64-lite.tar.gz` |
3. 打开 [`http://localhost:5099`](http://localhost:5099),使用启动日志中的初始密码登录 WebUI,按引导接入 QQ 进程并配置 OneBot 连接。
完整版适合直接解压运行;Lite 版只移除了内置 Node.js,其余运行时依赖与 WebUI 静态资源保持一致。
## 接入与文档
### 2. 启动 SnowLuma
| 入口 | 文档 |
| --- | --- |
| WebSocket / HTTP | [OneBot 动作参考](docs/onebot-actions.md) |
| TypeScript SDK | [`packages/sdk/README.md`](packages/sdk/README.md) |
| MCP | [`packages/mcp/README.md`](packages/mcp/README.md) |
Windows 运行 `launcher.bat`。Linux 在解压目录执行:
JSON 消息段接受标准的 `data.data` 字符串,也兼容 `data.data` 非数组对象和 `{ type: "json", data: "..." }` 简写;`data` 必填,最终内容必须是 JSON 对象。
```bash
chmod +x launcher.sh
./launcher.sh
```
## 开发
### 3. 打开 WebUI
浏览器访问 [`http://localhost:5099`](http://localhost:5099)。初始账号为 `admin`,随机密码会显示在启动日志中;登录后即可接入已启动的 QQ 进程并配置 OneBot 连接。
<details>
<summary><strong>无人值守部署:通过环境变量确认协议</strong></summary>
同时设置以下两个变量可跳过 WebUI 的协议确认页面:
```bash
SNOWLUMA_ACCEPT_EULA=1
SNOWLUMA_ACCEPT_PRIVACY=1
```
两项必须同时设置,且环境变量确认不会写入持久化同意记录。设置变量即表示运营者已阅读并同意 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md)。
</details>
## 选择接入方式
| 入口 | 适合场景 | 参考 |
| --- | --- | --- |
| WebSocket / HTTP | 对接现有 OneBot 机器人框架 | [OneBot 动作参考](docs/onebot-actions.md) |
| TypeScript SDK | 编写类型安全的客户端与消息逻辑 | [`packages/sdk`](packages/sdk/README.md) |
| MCP | 让支持 MCP 的工具查询或调用 SnowLuma 动作 | [`packages/mcp`](packages/mcp/README.md) |
| WebUI | 管理运行状态、日志、账号与连接 | 启动后访问 `http://localhost:5099` |
## 开发与贡献
本地开发需要 Node.js 22+ 与项目锁定版本的 pnpm。所有日常开发基于 `dev` 分支:
需要 Node.js 22.13+(23 系需 23.4+)与 pnpm 10.28.0,日常开发基于 `dev` 分支:
```bash
git clone https://github.com/SnowLuma/SnowLuma.git
cd SnowLuma
git checkout dev
pnpm install
pnpm install --frozen-lockfile
pnpm typecheck
pnpm test
```
- 先读 [`CONTEXT.md`](CONTEXT.md) 了解模块边界与项目词汇。
- 提交代码前阅读 [`CONTRIBUTING.md`](CONTRIBUTING.md) 与 [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md)。
- 开发方向与已完成事项见 [`RoadMap.md`](RoadMap.md)。
贡献流程见 [`CONTRIBUTING.md`](CONTRIBUTING.md);模块边界与项目词汇见 [`CONTEXT.md`](CONTEXT.md);开发方向见 [`RoadMap.md`](RoadMap.md)。
<details>
<summary><strong>主要目录</strong></summary>
## 引用消息预览
| 路径 | 作用 |
| --- | --- |
| `packages/protocol` | QQ 协议定义、数据包解析、消息推送与 OIDB 服务 |
| `packages/onebot` | OneBot 动作执行、事件转换与网络适配 |
| `packages/core` | 运行时编排、QQ 会话桥接与 WebUI 服务端 |
| `packages/webui` | React 管理界面 |
| `packages/sdk` | 对外发布的 TypeScript SDK |
| `packages/mcp` | 面向 MCP 客户端的动作目录与执行入口 |
</details>
OneBot 发送 `reply` 段时,会将本地消息缓存中的原文附入 QQ 引用预览,保留文字、换行与引用关系。图片、语音等非文字段以类型提示显示,不重新上传媒体;原消息中的嵌套引用不递归展开。只有消息元数据而没有缓存正文时,不生成虚构的预览内容。
## 使用边界与许可
> [!IMPORTANT]
> SnowLuma 使用 **源码可见非商业许可**,**不是 OSI 开源许可**。源码可用于查看、学习、非商业自托管及私下修改;任何商业使用,以及公开发布修改版或衍生版,均需事先取得书面授权。
> SnowLuma 使用**源码可见非商业许可**,不是 OSI 开源许可。源码可用于查看、学习、非商业自托管及私下修改;商业使用,以及公开发布修改版或衍生版,均需事先取得书面授权。
- 完整条款见 [`LICENSE`](LICENSE)。
- 随附的原生附加组件为专有组件,不在源码许可范围内。
- 二进制发行包另受 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md) 约束。
- 商业授权请联系 `motricseven@foxmail.com`。
完整条款见 [`LICENSE`](LICENSE);二进制发行包另受 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md) 约束;商业授权请联系 `motricseven@foxmail.com`。随附的原生附加组件为专有组件,不在源码许可范围内。
SnowLuma is source-available for study and non-commercial self-hosting, but it is **not OSI open source**. Commercial use and public distribution of modified or derivative versions require prior written permission. Bundled native components are proprietary and excluded from the source license.
SnowLuma is source-available for study and non-commercial self-hosting, but it is not OSI open source. Commercial use and public distribution of modified or derivative versions require prior written permission.
## 社区与支持
## 社区与鸣谢
- [提交问题](https://github.com/SnowLuma/SnowLuma/issues)
- [QQ 群](https://qm.qq.com/q/g3UMLpWALe)
- [Telegram](https://t.me/napcatqq)
## 鸣谢
项目参考了 [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。
<p align="center">
+3
View File
@@ -14,9 +14,12 @@ export default defineConfig([
'**/coverage/**',
'**/.turbo/**',
'**/.vite/**',
'.claude/**',
'dev/**',
'**/*.tsbuildinfo',
'**/test/fixtures/**',
'packages/runtime/native/**',
'packages/mcp/src/generated/**',
]),
{
files: ['**/*.{js,mjs,cjs,ts,tsx}'],
+20 -11
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.12.5",
"version": "1.14.22",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -10,19 +10,22 @@
"build:sdk": "pnpm --filter @snowluma/sdk build",
"build:webui": "pnpm --filter webui build",
"build:mcp": "pnpm --filter @snowluma/mcp build",
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter @snowluma/mcp build && pnpm --filter webui build",
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter @snowluma/mcp build && pnpm --filter @snowluma/ui build && pnpm --filter webui build",
"check:release-layout": "node tools/check-release-layout.mjs",
"dev": "pnpm --filter @snowluma/core dev",
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
"dev:web": "pnpm --filter webui dev",
"test": "pnpm --filter @snowluma/core test",
"test": "pnpm --filter=\"./packages/**\" -r --no-bail --if-present test",
"test:core": "pnpm --filter @snowluma/core test",
"test:watch": "pnpm --filter @snowluma/core test:watch",
"test:common": "pnpm --filter @snowluma/common test",
"test:all": "pnpm -r --if-present test",
"test:native": "pnpm -r --if-present test:native",
"coverage": "pnpm --filter @snowluma/common test -- --coverage",
"test:all": "pnpm test",
"test:native": "pnpm --filter=\"./packages/**\" -r --if-present test:native",
"coverage": "node tools/coverage.mjs",
"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"
@@ -46,16 +49,22 @@
"eslint-plugin-react-hooks>eslint": "10"
}
},
"onlyBuiltDependencies": [
"better-sqlite3"
],
"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",
"engines": {
"node": ">=22"
"node": "^22.13.0 || >=23.4.0",
"pnpm": "10.28.0"
}
}
+6 -2
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.12.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"
@@ -53,7 +57,7 @@
"@snowluma/common": "workspace:*"
},
"devDependencies": {
"@types/node": "^24.12.2",
"@types/node": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "^4.1.4"
+174 -19
View File
@@ -1,4 +1,9 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import {
createLogger,
runWithTraceRequest,
type Logger,
} from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketInfo, PacketSink } from '@snowluma/common/protocol-types';
import fs from 'fs';
@@ -16,7 +21,12 @@ import { QqHookClient } from './qq-hook-client';
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
import type { HookProcessInfo } from './types';
const AUTO_LOAD_MAX_ATTEMPTS = 3;
type AutoLoadAttempt = {
attempts: number;
inFlight: boolean;
};
/**
* Sink that the hook layer calls back into when it observes a new login,
@@ -50,7 +60,9 @@ export type HookManagerDeps = {
listProcesses?: () => HookProcessBaseInfo[];
/** When true, every newly-discovered QQ process is auto-injected (fires
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
* Failed loads are logged and leave the session in the 'error' state. */
* Failed loads are logged and leave the session in the 'error' state.
* A narrowly-classified early-process mapping race is retried on later
* watcher ticks with a fixed attempt limit. */
autoLoadOnDiscovery?: boolean;
/** Optional hook fired whenever the set of HookProcessInfo observable to
* `listProcesses()` changes — new process discovered, process gone, or
@@ -69,9 +81,11 @@ export type HookManagerDeps = {
* Responsibilities:
* - Route user commands (load/unload/refresh) to the matching session.
* - Route watcher diff events to the matching session.
* - Forward session events ('login' / 'disconnected' / receive health) to BridgeManager.
* - Forward session events ('login' / 'disconnected' / transport health) to BridgeManager.
* - Retry stuck-in-connecting sessions on every watcher tick (so a
* failed connect eventually recovers without a manual refresh).
* - Retry the bounded early-process auto-load race without retrying
* permanent injector errors.
*
* The native injector, native pipe-client, and native process/pipe
* listings are all swappable dependencies so tests can run without a
@@ -95,6 +109,7 @@ export class HookManager {
private readonly onSessionsChangedRaw?: () => void;
private readonly log: Logger;
private readonly sessions = new Map<number, HookSession>();
private readonly autoLoadAttempts = new Map<number, AutoLoadAttempt>();
private readonly startPromise: Promise<void>;
private disposed = false;
@@ -145,7 +160,7 @@ export class HookManager {
} else {
this.pipeWatcher = new PipeWatcher({
listProcesses: this.enumerate,
listLivePipes: () => QqHookClient.listLivePipes(),
listLivePipes: processes => QqHookClient.listLivePipes(processes.map(({ pid }) => pid)),
intervalMs: deps.watcherIntervalMs,
log: this.log,
});
@@ -180,6 +195,7 @@ export class HookManager {
async loadProcess(pid: number): Promise<HookProcessInfo> {
this.assertValidPid(pid);
await this.startPromise;
this.autoLoadAttempts.delete(pid);
const session = this.ensureSession(pid);
const info = await session.load();
// Pull the next tick forward so a freshly-injected pipe gets noticed
@@ -191,6 +207,7 @@ export class HookManager {
async unloadProcess(pid: number): Promise<HookProcessInfo> {
this.assertValidPid(pid);
await this.startPromise;
this.autoLoadAttempts.delete(pid);
const session = this.ensureSession(pid);
return session.unload();
}
@@ -214,6 +231,7 @@ export class HookManager {
session.dispose();
}
this.sessions.clear();
this.autoLoadAttempts.clear();
this.enumerator?.dispose();
if (this.ownsPipeWatcher) {
this.pipeWatcher.dispose();
@@ -225,24 +243,38 @@ export class HookManager {
private bindWatcher(): void {
this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => {
if (this.disposed) return;
const session = this.ensureSession(info.pid);
session.attachProcessInfo(info);
// Headless/Docker deployments enable autoLoadOnDiscovery so QQ gets
// injected without a human clicking "Load" in WebUI. Fire-and-forget:
// failures are already captured inside loadInternal and surfaced via
// the session's status field.
if (this.autoLoadOnDiscovery && shouldAutoLoadPid(info.pid, this.log)) {
void session.load().catch((err) => {
this.log.warn('auto-load failed: PID=%d err=%s', info.pid, errMsg(err));
});
}
this.notifySessionsChanged();
runWithTraceRequest(() => {
const session = this.ensureSession(info.pid);
session.attachProcessInfo(info);
this.log.trace(() => [
'hook_manager_fact event=process_discovered pid=%d info=%s autoLoad=%s',
info.pid,
renderParamsVerbose(info),
this.autoLoadOnDiscovery,
]);
// Headless/Docker deployments enable autoLoadOnDiscovery so QQ gets
// injected without a human clicking "Load" in WebUI. Fire-and-forget:
// failures are already captured inside loadInternal and surfaced via
// the session's status field.
if (this.autoLoadOnDiscovery && shouldAutoLoadPid(info.pid, this.log)) {
this.runAutoLoad(session);
}
this.notifySessionsChanged();
});
});
this.pipeWatcher.on('process-gone', (pid: number) => {
if (this.disposed) return;
const session = this.sessions.get(pid);
if (session) session.notifyProcessGone();
this.notifySessionsChanged();
runWithTraceRequest(() => {
this.autoLoadAttempts.delete(pid);
const session = this.sessions.get(pid);
this.log.trace(
'hook_manager_fact event=process_gone pid=%d tracked=%s',
pid,
session !== undefined,
);
if (session) session.notifyProcessGone();
this.notifySessionsChanged();
});
});
this.pipeWatcher.on('pipe-up', (pid: number) => {
if (this.disposed) return;
@@ -271,6 +303,12 @@ export class HookManager {
this.pipeWatcher.on('tick', () => {
if (this.disposed) return;
for (const session of this.sessions.values()) {
const autoLoad = this.autoLoadAttempts.get(session.pid);
if (autoLoad && !autoLoad.inFlight && session.status === 'error'
&& isTransientLibcMappingError(session.error)) {
this.runAutoLoad(session, autoLoad);
continue;
}
if ((session.status === 'connecting' || session.status === 'disconnected')
&& this.pipeWatcher.isPipeLive(session.pid)) {
session.onPipeUp();
@@ -279,6 +317,119 @@ export class HookManager {
});
}
private runAutoLoad(session: HookSession, existing?: AutoLoadAttempt): void {
if (this.disposed || session.isDisposed) return;
const state = existing ?? { attempts: 0, inFlight: false };
if (state.inFlight || state.attempts >= AUTO_LOAD_MAX_ATTEMPTS) return;
state.attempts += 1;
state.inFlight = true;
this.autoLoadAttempts.set(session.pid, state);
const attempt = state.attempts;
void runWithTraceRequest(async () => {
const startedAt = Date.now();
this.log.trace(
'hook_autoload_start pid=%d attempt=%d maxAttempts=%d',
session.pid,
attempt,
AUTO_LOAD_MAX_ATTEMPTS,
);
try {
const info = await session.load();
if (this.autoLoadAttempts.get(session.pid) !== state) {
this.log.trace(
'hook_autoload_terminal pid=%d attempt=%d outcome=dropped reason=superseded elapsedMs=%d',
session.pid,
attempt,
Date.now() - startedAt,
);
return;
}
state.inFlight = false;
if (info.status !== 'error') {
this.autoLoadAttempts.delete(session.pid);
const reason = attempt > 1 ? 'recovered' : 'loaded';
this.log.trace(() => [
'hook_autoload_terminal pid=%d attempt=%d outcome=completed reason=%s state=%s elapsedMs=%d',
session.pid,
attempt,
reason,
renderParamsVerbose(info),
Date.now() - startedAt,
]);
if (attempt > 1) {
this.log.info(
'auto-load recovered: PID=%d attempt=%d/%d',
session.pid,
attempt,
AUTO_LOAD_MAX_ATTEMPTS,
);
}
return;
}
if (!isTransientLibcMappingError(info.error)) {
this.autoLoadAttempts.delete(session.pid);
this.log.trace(
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=permanent_failure error=%j elapsedMs=%d',
session.pid,
attempt,
info.error,
Date.now() - startedAt,
);
return;
}
if (attempt >= AUTO_LOAD_MAX_ATTEMPTS) {
this.autoLoadAttempts.delete(session.pid);
this.log.trace(
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=retry_exhausted error=%j elapsedMs=%d',
session.pid,
attempt,
info.error,
Date.now() - startedAt,
);
this.log.warn(
'auto-load retry exhausted: PID=%d attempts=%d err=%s',
session.pid,
attempt,
info.error,
);
return;
}
this.log.trace(
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=retry_pending error=%j elapsedMs=%d',
session.pid,
attempt,
info.error,
Date.now() - startedAt,
);
this.log.warn(
'auto-load retry pending: PID=%d attempt=%d/%d err=%s',
session.pid,
attempt,
AUTO_LOAD_MAX_ATTEMPTS,
info.error,
);
} catch (err) {
if (this.autoLoadAttempts.get(session.pid) === state) {
this.autoLoadAttempts.delete(session.pid);
}
this.log.trace(
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=unexpected_failure error=%j elapsedMs=%d',
session.pid,
attempt,
errMsg(err),
Date.now() - startedAt,
);
this.log.warn('auto-load failed: PID=%d err=%s', session.pid, errMsg(err));
}
});
}
private ensureSession(pid: number): HookSession {
let session = this.sessions.get(pid);
if (session) return session;
@@ -341,6 +492,10 @@ function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
function isTransientLibcMappingError(error: string): boolean {
return /^target process does not map \S*\/libc\.so\.6 while resolving mmap$/.test(error);
}
/**
* Filter for auto-load only. Returns false for Linux Electron child
* processes (zygote/renderer/gpu/utility), which the native enumerator
+27 -3
View File
@@ -1,10 +1,23 @@
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import { QqHookClient, type QqHookSendReply } from './qq-hook-client';
import { packetTimeoutMs } from './packet-timeout';
import {
HookPipeRequestError,
PIPE_STATUS_CONNECTION_UNAVAILABLE,
QqHookClient,
type QqHookSendReply,
} from './qq-hook-client';
export type OutboundHealthListener = (healthy: boolean) => void;
export class HookPacketClient implements PacketSender {
constructor(private readonly client: QqHookClient) { }
private outboundHealthy = true;
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise<SendPacketResult> {
constructor(
private readonly client: QqHookClient,
private readonly onOutboundHealthChanged?: OutboundHealthListener,
) { }
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
if (!this.client.isLoggedIn) {
return { success: false, gotResponse: false, errorCode: -1, errorMessage: 'qq_hook client is not logged in', responseData: null };
}
@@ -14,6 +27,7 @@ export class HookPacketClient implements PacketSender {
wantReply: true,
replyTimeoutMs: timeoutMs,
}) as QqHookSendReply;
this.setOutboundHealthy(true);
return {
success: reply.error === 0,
gotResponse: true,
@@ -22,6 +36,10 @@ export class HookPacketClient implements PacketSender {
responseData: reply.body,
};
} catch (error) {
if (error instanceof HookPipeRequestError
&& error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE) {
this.setOutboundHealthy(false);
}
return {
success: false,
gotResponse: false,
@@ -31,4 +49,10 @@ export class HookPacketClient implements PacketSender {
};
}
}
private setOutboundHealthy(healthy: boolean): void {
if (this.outboundHealthy === healthy) return;
this.outboundHealthy = healthy;
this.onOutboundHealthChanged?.(healthy);
}
}
+130
View File
@@ -0,0 +1,130 @@
import { readFileSync } from 'fs';
import os from 'os';
import path from 'path';
export interface HookRuntimeDirDeps {
platform?: NodeJS.Platform;
env?: NodeJS.ProcessEnv;
ownUid?: number;
readText?: (file: string) => string;
}
function configuredDirectory(value: string | undefined, variable: string): string | null {
if (!value) return null;
if (!path.isAbsolute(value)) {
throw new Error(`${variable} must be an absolute path`);
}
return value;
}
function parseProcessEnvironment(raw: string): NodeJS.ProcessEnv {
const result: NodeJS.ProcessEnv = {};
for (const entry of raw.split('\0')) {
if (!entry) continue;
const separator = entry.indexOf('=');
if (separator <= 0) continue;
result[entry.slice(0, separator)] = entry.slice(separator + 1);
}
return result;
}
function parseRealUid(status: string): number | null {
const match = /^Uid:\s+(\d+)/m.exec(status);
if (!match) return null;
const uid = Number(match[1]);
return Number.isSafeInteger(uid) && uid >= 0 ? uid : null;
}
function isProcessGoneError(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
return code === 'ENOENT' || code === 'ESRCH';
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function ownRuntimeDir(
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv,
ownUid: number,
): string {
const explicit = configuredDirectory(
env.SNOWLUMA_HOOK_RUNTIME_DIR,
'SNOWLUMA_HOOK_RUNTIME_DIR',
);
if (explicit) return explicit;
const xdg = configuredDirectory(env.XDG_RUNTIME_DIR, 'XDG_RUNTIME_DIR');
if (xdg) return xdg;
if (platform === 'darwin') {
const tmpdir = configuredDirectory(env.TMPDIR, 'TMPDIR');
if (tmpdir) return path.join(tmpdir, 'snowluma-hook');
}
return `/tmp/snowluma-${ownUid}`;
}
/**
* Resolve the socket directory for the target QQ process. The supervisor may
* run under a different user, so its own runtime directory is not authoritative.
*/
export function resolveHookRuntimeDir(
targetPid?: number,
deps: HookRuntimeDirDeps = {},
): string {
const platform = deps.platform ?? process.platform;
const env = deps.env ?? process.env;
const ownUid = deps.ownUid
?? (typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid);
const readText = deps.readText ?? ((file: string) => readFileSync(file, 'utf8'));
if (platform !== 'linux' || !Number.isSafeInteger(targetPid) || targetPid! <= 0) {
return ownRuntimeDir(platform, env, ownUid);
}
let environError: unknown;
try {
const targetEnv = parseProcessEnvironment(readText(`/proc/${targetPid}/environ`));
const explicit = configuredDirectory(
targetEnv.SNOWLUMA_HOOK_RUNTIME_DIR,
`QQ process ${targetPid} SNOWLUMA_HOOK_RUNTIME_DIR`,
);
if (explicit) return explicit;
const xdg = configuredDirectory(
targetEnv.XDG_RUNTIME_DIR,
`QQ process ${targetPid} XDG_RUNTIME_DIR`,
);
if (xdg) return xdg;
environError = new Error('runtime directory is not present');
} catch (error) {
// An invalid explicit path is configuration corruption and must remain
// visible. Permission/race failures are expected when /proc disappears;
// the status-file fallback below can still recover the target uid.
if (error instanceof Error && error.message.includes('must be an absolute path')) {
throw error;
}
environError = error;
}
let statusError: unknown;
try {
const uid = parseRealUid(readText(`/proc/${targetPid}/status`));
if (uid !== null) return `/tmp/snowluma-${uid}`;
statusError = new Error('real uid is not available');
} catch (error) {
statusError = error;
}
if (isProcessGoneError(statusError)
&& (isProcessGoneError(environError)
|| (environError instanceof Error
&& environError.message === 'runtime directory is not present'))) {
return ownRuntimeDir(platform, env, ownUid);
}
throw new Error(
`cannot resolve hook runtime directory for PID ${targetPid}: `
+ `environment=${errorMessage(environError)}; status=${errorMessage(statusError)}`,
);
}
+353 -80
View File
@@ -1,4 +1,10 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import {
createLogger,
runWithoutRequestContext,
runWithTraceRequest,
type Logger,
} from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import type { PacketSink } from '@snowluma/common/protocol-types';
import { isRealUin } from '@snowluma/common/uin';
import { EventEmitter } from 'events';
@@ -9,10 +15,12 @@ import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
import { statusFor } from './hook-status';
import type { HookProcessInfo, HookProcessStatus } from './types';
/** How often to actively re-probe QQ's login state while connected but not yet
* logged in — the safety net for a login the native hook never pushed (Docker
* auto-login races/bypasses the pushed loginState frame). */
/** How often to re-check account identity while the connection is not ready.
* Identity alone never proves that requests can be served. */
const LOGIN_RECONCILE_INTERVAL_MS = 3000;
const LOGIN_IDENTITY_OBSERVE_INTERVAL_MS = 30_000;
const LOGIN_HINT_MAX_ATTEMPTS = 3;
const LOGIN_HINT_RETRY_DELAYS_MS = [3000, 9000] as const;
/** QQ emits this response periodically while its MSF receive path is healthy.
* Seeing it once arms the watchdog; before that, silence is UNKNOWN rather
@@ -24,7 +32,7 @@ const RECEIVE_STALE_CONFIRM_MS = 15_000;
export type HookSessionDeps = {
injector: {
inject: (pid: number) => HookInjectResult;
inject: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
unload: (pid: number, handle: HookInjectResult['handle']) => void;
};
makeClient: (pid: number) => QqHookClient;
@@ -60,8 +68,10 @@ export type HookSessionDeps = {
*
* Emitted events:
* 'login' (uin, packetSender) — real-UIN login detected
* 'disconnected' (wasLoggedIn) — connection dropped or torn down
* 'receive-health-changed' (healthy) — receive path confirmed stale/recovered
* 'disconnected' (wasLoggedIn) — connection dropped, torn down, or
* dispose() of a logged-in session
* (process shutdown uses this path)
* 'receive-health-changed' (healthy) — combined receive/request path health changed
* 'status-changed' (status, error) — status field mutated
* 'disposed' () — session stopped tracking this PID
*/
@@ -93,7 +103,13 @@ export class HookSession extends EventEmitter {
private disposed = false;
private loginProbeTimer: ReturnType<typeof setInterval> | null = null;
private probing = false;
private acceptedLoginHintUin = '';
private loginHintAttemptUin = '';
private loginHintAttempts = 0;
private nextLoginHintAt = 0;
private nextLoginIdentityObservationAt = 0;
private _receiveHealthy = true;
private _outboundHealthy = true;
private receiveWatchUin = '';
private receiveWatchArmed = false;
private receiveWatchTimer: ReturnType<typeof setTimeout> | null = null;
@@ -117,7 +133,9 @@ export class HookSession extends EventEmitter {
get uin(): string { return this._uin; }
get method(): string { return this._method; }
get isDisposed(): boolean { return this.disposed; }
get receiveHealthy(): boolean { return this._receiveHealthy; }
get receiveHealthy(): boolean {
return this._receiveHealthy && this._outboundHealthy;
}
attachProcessInfo(info: { name?: string; path?: string }): void {
if (info.name) this._name = info.name;
@@ -142,15 +160,15 @@ export class HookSession extends EventEmitter {
// ─────────────── user-facing commands ───────────────
load(): Promise<HookProcessInfo> {
return this.serialize(() => this.loadInternal());
return this.traceCommand('load', () => this.loadInternal());
}
unload(): Promise<HookProcessInfo> {
return this.serialize(() => this.unloadInternal());
return this.traceCommand('unload', () => this.unloadInternal());
}
refresh(): Promise<HookProcessInfo> {
return this.serialize(() => this.refreshInternal());
return this.traceCommand('refresh', () => this.refreshInternal());
}
// ─────────────── watcher-driven events (called by manager) ───────────────
@@ -180,28 +198,111 @@ export class HookSession extends EventEmitter {
if (this.disposed) return;
void this.serialize(async () => {
if (this.disposed) return;
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.injected = false;
this.injectResult = null;
this._method = '';
this.setStatus('available', '');
if (wasLoggedIn) this.emit('disconnected', true);
this.disposed = true;
this.emit('disposed');
this.removeAllListeners();
runWithTraceRequest(() => {
const startedAt = Date.now();
const wasLoggedIn = this.loggedIn;
this.log.trace(() => [
'hook_session_process_start pid=%d event=process_gone state=%s',
this.pid,
renderParamsVerbose(this.toInfo()),
]);
this.tearDownClient();
this.injected = false;
this.injectResult = null;
this._method = '';
this.setStatus('available', '');
try {
if (wasLoggedIn) this.emit('disconnected', true);
this.disposed = true;
this.emit('disposed');
this.log.trace(() => [
'hook_session_process_terminal pid=%d outcome=completed reason=process_gone wasLoggedIn=%s state=%s elapsedMs=%d',
this.pid,
wasLoggedIn,
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
this.removeAllListeners();
} catch (error) {
this.log.trace(() => [
'hook_session_process_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
this.pid,
errMsg(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
throw error;
}
});
}).catch(err => this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)));
}
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();
}
// ─────────────── per-session serialization ───────────────
private traceCommand(
operation: 'load' | 'unload' | 'refresh',
command: () => Promise<HookProcessInfo>,
): Promise<HookProcessInfo> {
return runWithTraceRequest(async () => {
const startedAt = Date.now();
this.log.trace(() => [
'hook_session_start pid=%d operation=%s state=%s',
this.pid,
operation,
renderParamsVerbose(this.toInfo()),
]);
try {
const info = await this.serialize(command);
const outcome = info.status === 'error'
|| (operation === 'unload' && info.status !== 'available')
? 'failed'
: 'completed';
let reason: string;
if (operation === 'unload' && info.status === 'connecting') {
reason = 'unload_verification_failed';
} else if (outcome === 'failed') {
reason = `${operation}_failed`;
} else {
reason = `${operation}_settled`;
}
this.log.trace(() => [
'hook_session_terminal pid=%d operation=%s outcome=%s reason=%s%s state=%s elapsedMs=%d',
this.pid,
operation,
outcome,
reason,
info.error ? ` error=${JSON.stringify(info.error)}` : '',
renderParamsVerbose(info),
Date.now() - startedAt,
]);
return info;
} catch (error) {
this.log.trace(() => [
'hook_session_terminal pid=%d operation=%s outcome=failed reason=%s error=%j state=%s elapsedMs=%d',
this.pid,
operation,
`${operation}_threw`,
errMsg(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
throw error;
}
});
}
private serialize<T>(op: () => Promise<T>): Promise<T> {
const previous = this.opChain;
let release!: () => void;
@@ -230,11 +331,25 @@ export class HookSession extends EventEmitter {
if (this.pipeWatcher.isPipeLive(this.pid)) {
this.injected = true;
this._method = this._method || 'reconnect';
this.log.trace(
'hook_session_branch pid=%d operation=load branch=existing_pipe method=%j',
this.pid,
this._method,
);
this.log.info('PID=%d already has SnowLuma pipe; will reconnect', this.pid);
} else {
this.injectResult = this.injector.inject(this.pid);
this.log.trace(
'hook_session_branch pid=%d operation=load branch=inject_begin',
this.pid,
);
this.injectResult = await this.injector.inject(this.pid);
this.injected = true;
this._method = this.injectResult.method;
this.log.trace(
'hook_session_branch pid=%d operation=load branch=inject_completed method=%j',
this.pid,
this._method,
);
}
}
this.applyStatus();
@@ -348,52 +463,102 @@ export class HookSession extends EventEmitter {
if (this.injected) this.applyStatus(this.loggedIn, this._error);
return;
}
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.applyStatus(wasLoggedIn);
if (wasLoggedIn) this.emit('disconnected', true);
runWithTraceRequest(() => {
const startedAt = Date.now();
const wasLoggedIn = this.loggedIn;
this.log.trace(() => [
'hook_session_disconnect_start pid=%d reason=pipe_down state=%s',
this.pid,
renderParamsVerbose(this.toInfo()),
]);
this.tearDownClient();
this.applyStatus(wasLoggedIn);
try {
if (wasLoggedIn) this.emit('disconnected', true);
this.log.trace(() => [
'hook_session_disconnect_terminal pid=%d outcome=completed reason=pipe_down wasLoggedIn=%s state=%s elapsedMs=%d',
this.pid,
wasLoggedIn,
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
} catch (error) {
this.log.trace(() => [
'hook_session_disconnect_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
this.pid,
errMsg(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
throw error;
}
});
}
// ─────────────── client plumbing ───────────────
private async attemptConnect(): Promise<void> {
if (this.connected) return;
if (this.client?.isClosed) this.tearDownClient();
if (!this.client) {
this.client = this.makeClient(this.pid);
this.sender = new HookPacketClient(this.client);
this.bound = false;
}
if (!this.bound) {
this.bindClient(this.client);
this.bound = true;
}
const client = this.client;
try {
await client.connectAll({ recv: true });
this.connected = true;
const loginState = client.getLoginState();
// handleLoginState owns the connected+loggedIn → 'online' (+ login
// emit) transition; defer to it so the status is set once. Otherwise
// we're connected-but-not-logged-in → 'loaded'.
if (loginState.loggedIn) {
this.handleLoginState(loginState);
} else {
this.applyStatus();
// The native hook only PUSHES a loginState frame on the login edge;
// if QQ logged in before/around connect (Docker auto-login) that edge
// is missed and we'd wait forever. Actively re-probe until logged in.
this.startLoginReconcile();
return runWithTraceRequest(async () => {
const startedAt = Date.now();
this.log.trace(() => [
'hook_session_connect_start pid=%d state=%s',
this.pid,
renderParamsVerbose(this.toInfo()),
]);
if (this.client?.isClosed) this.tearDownClient();
if (!this.client) {
this.client = this.makeClient(this.pid);
this.sender = new HookPacketClient(
this.client,
healthy => this.setOutboundHealthy(healthy),
);
this.bound = false;
}
this.log.info('pipe connected: PID=%d', this.pid);
} catch (error) {
this._error = errMsg(error);
// Drop the client so the next attempt builds a fresh socket pair.
// A failed connect was never logged in → 'connecting' (or 'available').
this.tearDownClient();
this.applyStatus(false, this._error);
}
if (!this.bound) {
this.bindClient(this.client);
this.bound = true;
}
const client = this.client;
try {
await client.connectAll({ recv: true });
this.connected = true;
const loginState = client.getLoginState();
// handleLoginState owns the connected+loggedIn → 'online' (+ login
// emit) transition; defer to it so the status is set once. Otherwise
// we're connected-but-not-logged-in → 'loaded'.
if (loginState.loggedIn) {
this.handleLoginState(loginState);
} else {
this.applyStatus();
// The native hook only PUSHES a loginState frame on the login edge;
// if QQ logged in before/around connect (Docker auto-login) that edge
// is missed and we'd wait forever. Actively re-probe until logged in.
runWithoutRequestContext(() => this.startLoginReconcile());
}
this.log.info('pipe connected: PID=%d', this.pid);
this.log.trace(() => [
'hook_session_connect_terminal pid=%d outcome=completed reason=connect_settled state=%s elapsedMs=%d',
this.pid,
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
} catch (error) {
this._error = errMsg(error);
// Drop the client so the next attempt builds a fresh socket pair.
// A failed connect was never logged in → 'connecting' (or 'available').
this.tearDownClient();
this.applyStatus(false, this._error);
this.log.trace(() => [
'hook_session_connect_terminal pid=%d outcome=failed reason=connect_failed error=%j state=%s elapsedMs=%d',
this.pid,
this._error,
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
}
});
}
private bindClient(client: QqHookClient): void {
@@ -430,6 +595,8 @@ export class HookSession extends EventEmitter {
this.bound = false;
this.connected = false;
this.loggedIn = false;
this._outboundHealthy = true;
this.resetLoginHint();
}
private handleLoginState(state: QqHookLoginState): void {
@@ -437,15 +604,18 @@ export class HookSession extends EventEmitter {
const previousUin = this._uin;
this._uin = state.uin || state.uinNumber.toString();
this.loggedIn = state.loggedIn && isRealUin(this._uin);
// However login was observed (pushed frame or the active probe), the
// safety net's job is done.
// Login readiness has now been confirmed, so identity probing is done.
if (this.loggedIn) {
this.stopLoginReconcile();
// A PID can switch accounts without an intermediate logout edge. Never
// carry the previous account's heartbeat deadline into the new epoch.
if (this.receiveWatchUin !== this._uin) this.resetReceiveWatch(this._uin);
if (this.receiveWatchUin !== this._uin) {
this.resetReceiveWatch(this._uin);
this._outboundHealthy = true;
}
} else {
this.resetReceiveWatch();
this._outboundHealthy = true;
}
// Only the connected/logged-in states are ours to set here; when fully
@@ -461,18 +631,42 @@ export class HookSession extends EventEmitter {
if (!this.loggedIn || !this.sender) return;
if (wasLoggedIn && previousUin === this._uin) return;
this.emit('login', this._uin, this.sender);
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
runWithTraceRequest(() => {
const startedAt = Date.now();
this.log.trace(
'hook_session_login_start pid=%d previousUin=%j uin=%j',
this.pid,
previousUin,
this._uin,
);
try {
this.emit('login', this._uin, this.sender!);
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
this.log.trace(() => [
'hook_session_login_terminal pid=%d outcome=completed reason=login_detected previousUin=%j uin=%j state=%s elapsedMs=%d',
this.pid,
previousUin,
this._uin,
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
} catch (error) {
this.log.trace(() => [
'hook_session_login_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
this.pid,
errMsg(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
throw error;
}
});
}
// ─────────────── login reconcile (Docker auto-login safety net) ───────────
// The hook's loginState frame is edge-triggered (pushed only when the native
// observes the login transition). When that edge is missed — QQ auto-logged
// in before connect, or a silent session-restore path the hook doesn't
// intercept — we'd sit at 'loaded'/'connecting' forever. So while connected
// but not logged in, actively re-probe QQ's own ports and synthesize the
// login once it reports a real uin. Idempotent with the pushed-frame path
// (handleLoginState's wasLoggedIn guard dedups the 'login' emit).
// The local endpoint can identify an auto-restored account before the
// runtime is ready. Forward identity for reconciliation, but never synthesize
// online state from the probe.
private startLoginReconcile(): void {
if (this.loginProbeTimer || this.disposed) return;
@@ -493,27 +687,85 @@ export class HookSession extends EventEmitter {
// slow probe never stacks concurrent subprocess-spawning scans.
if (this.probing) return;
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
if (Date.now() < this.nextLoginIdentityObservationAt) return;
this.probing = true;
try {
let info: QqPortLoginInfo | null;
try {
info = await this.probeLogin(this.pid);
} catch {
} catch (error) {
this.log.trace(
'login identity probe failed: PID=%d err=%s',
this.pid,
errMsg(error),
);
return; // best-effort; the interval retries
}
// The await yielded — re-check we still want this before mutating state.
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
if (info?.loggedIn && isRealUin(info.uin)) {
this.log.info('login reconciled via active probe: PID=%d UIN=%s', this.pid, info.uin);
// isRealUin guarantees a pure non-empty digit string, so BigInt() here
// cannot throw (keep that contract if isRealUin's regex is ever changed).
this.handleLoginState({ loggedIn: true, uin: info.uin, uinNumber: BigInt(info.uin) });
if (info?.identityKnown && isRealUin(info.uin)) {
const client = this.client;
if (!client) return;
if (this.acceptedLoginHintUin === info.uin) {
this.nextLoginIdentityObservationAt = Date.now()
+ LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
return;
}
if (this.loginHintAttemptUin !== info.uin) {
this.loginHintAttemptUin = info.uin;
this.loginHintAttempts = 0;
this.nextLoginHintAt = 0;
this.nextLoginIdentityObservationAt = 0;
}
if (this.loginHintAttempts >= LOGIN_HINT_MAX_ATTEMPTS
|| Date.now() < this.nextLoginHintAt) return;
const attempt = ++this.loginHintAttempts;
this.log.info('login identity discovered: PID=%d UIN=%s; awaiting readiness', this.pid, info.uin);
try {
await client.reconcileLoginIdentity(info.uin);
if (this.client !== client || this.disposed || !this.connected || this.loggedIn) return;
this.acceptedLoginHintUin = info.uin;
this.nextLoginIdentityObservationAt = Date.now()
+ LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
} catch (error) {
if (this.client !== client || this.disposed) return;
if (attempt >= LOGIN_HINT_MAX_ATTEMPTS) {
this.log.warn(
'login identity reconciliation failed: PID=%d UIN=%s attempts=%d err=%s',
this.pid,
info.uin,
attempt,
errMsg(error),
);
this.nextLoginIdentityObservationAt = Date.now()
+ LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
} else {
this.nextLoginHintAt = Date.now()
+ LOGIN_HINT_RETRY_DELAYS_MS[attempt - 1]!;
this.log.trace(
'login identity hint failed: PID=%d UIN=%s attempt=%d err=%s',
this.pid,
info.uin,
attempt,
errMsg(error),
);
}
}
}
} finally {
this.probing = false;
}
}
private resetLoginHint(): void {
this.acceptedLoginHintUin = '';
this.loginHintAttemptUin = '';
this.loginHintAttempts = 0;
this.nextLoginHintAt = 0;
this.nextLoginIdentityObservationAt = 0;
}
private handlePacket(packet: QqHookPacket): void {
if (!this.loggedIn) return;
const uin = packet.uin || this._uin;
@@ -610,8 +862,29 @@ export class HookSession extends EventEmitter {
private setReceiveHealthy(healthy: boolean): void {
if (this._receiveHealthy === healthy) return;
const previous = this.receiveHealthy;
this._receiveHealthy = healthy;
this.emit('receive-health-changed', healthy);
if (previous !== this.receiveHealthy) {
this.emit('receive-health-changed', this.receiveHealthy);
}
}
private setOutboundHealthy(healthy: boolean): void {
if (this._outboundHealthy === healthy) return;
const previous = this.receiveHealthy;
this._outboundHealthy = healthy;
if (previous !== this.receiveHealthy) {
this.emit('receive-health-changed', this.receiveHealthy);
}
if (healthy) {
this.log.info('request path recovered: PID=%d UIN=%s', this.pid, this._uin);
} else {
this.log.warn(
'request path unavailable: PID=%d UIN=%s; reporting good=false',
this.pid,
this._uin,
);
}
}
private resetReceiveWatch(uin = ''): void {
+3 -3
View File
@@ -15,7 +15,7 @@ export interface ManualMapHandle {
interface NativeHookAddon {
getAllMainProcess(): number[];
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle;
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>;
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
}
@@ -119,7 +119,7 @@ export function listHookProcesses(): HookProcessBaseInfo[] {
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
}
export function injectHookProcess(pid: number): HookInjectResult {
export async function injectHookProcess(pid: number): Promise<HookInjectResult> {
const addon = getNativeHookAddon();
if (!addon) {
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
@@ -129,7 +129,7 @@ export function injectHookProcess(pid: number): HookInjectResult {
if (!dllPath) {
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
}
return { method: 'loadModuleManual', handle: addon.loadModuleManual(pid, dllPath) };
return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) };
}
export function unloadHookProcess(pid: number, handle: ManualMapHandle): void {
+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 });
}
+19 -10
View File
@@ -11,8 +11,9 @@ export type PipeWatcherDeps = {
* case this tick keeps the prior process+pipe state instead of treating the
* missing data as "everything disappeared" (issue #158). */
listProcesses: () => HookProcessBaseInfo[] | null | Promise<HookProcessBaseInfo[] | null>;
/** Native: PIDs that currently have a live SnowLuma named pipe. */
listLivePipes: () => Promise<Set<number>>;
/** Native: PIDs that currently have a live SnowLuma named pipe. The current
* process snapshot lets Linux inspect each target user's runtime directory. */
listLivePipes: (processes: readonly HookProcessBaseInfo[]) => Promise<Set<number>>;
/** Polling interval in ms. Defaults to 1500, floored to 250. */
intervalMs?: number;
log?: Logger;
@@ -158,12 +159,12 @@ export class PipeWatcher extends EventEmitter {
this.emit('tick');
return;
}
let livePipes: Set<number>;
let livePipes: Set<number> | null;
try {
livePipes = await this.listLivePipes();
livePipes = await this.listLivePipes(processes);
} catch (error) {
this.log.warn('listLivePipes failed: %s', errMsg(error));
livePipes = new Set();
livePipes = null;
}
const newKnownPids = new Set<number>();
@@ -179,11 +180,19 @@ export class PipeWatcher extends EventEmitter {
// 2. Pipes that came up. Ignore pipes for processes we don't know
// about (would race against an out-of-order tick).
const newLivePipes = new Set<number>();
for (const pid of livePipes) {
if (!newKnownPids.has(pid)) continue;
newLivePipes.add(pid);
if (!this.livePipes.has(pid)) {
this.emit('pipe-up', pid);
if (livePipes === null) {
// Keep the last known pipe state for processes that still exist, while
// allowing confirmed process exits to complete their normal teardown.
for (const pid of this.livePipes) {
if (newKnownPids.has(pid)) newLivePipes.add(pid);
}
} else {
for (const pid of livePipes) {
if (!newKnownPids.has(pid)) continue;
newLivePipes.add(pid);
if (!this.livePipes.has(pid)) {
this.emit('pipe-up', pid);
}
}
}
+404 -122
View File
@@ -1,15 +1,33 @@
import { EventEmitter } from 'events';
import {
createLogger,
renderTraceBytes,
runWithoutRequestContext,
runWithTraceRequest,
} from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import { isRealUin } from '@snowluma/common/uin';
import { readdirSync, promises as fs } from 'fs';
import net from 'net';
import os from 'os';
import path from 'path';
import { positiveIntEnv } from '@snowluma/common/env';
import { resolveHookRuntimeDir } from './hook-runtime-dir';
export const PIPE_MAGIC = 0x31504851;
export const PIPE_VERSION = 1;
export const HEADER_SIZE = 40;
// Keep these byte limits in lockstep with nnphook's pipe_protocol.hpp. The
// native readers already enforce them; mirroring them here prevents the JS
// endpoint from buffering frames that the peer can never accept.
export const MAX_PIPE_CMD_BYTES = 4096;
export const MAX_PIPE_MSG_BYTES = 65536;
export const MAX_PIPE_BODY_BYTES = 16 * 1024 * 1024;
export const DEFAULT_ACK_TIMEOUT_MS = 5000;
export const DEFAULT_REPLY_TIMEOUT_MS = 30000;
export const PIPE_STATUS_CONNECTION_UNAVAILABLE = -39;
const DEFAULT_PIPE_PROBE_TIMEOUT_MS = 250;
const packetLog = createLogger('QQHook.Packet');
const runtimeLog = createLogger('QQHook.Runtime');
export enum PipeOp {
hello = 1,
@@ -19,6 +37,7 @@ export enum PipeOp {
error = 5,
recvPacket = 6,
loginState = 7,
loginIdentityHint = 17,
}
const PipeFlagWantReply = 1 << 0;
@@ -54,6 +73,7 @@ export interface QqHookSendReply {
export interface QqHookClientOptions {
ackTimeoutMs?: number;
replyTimeoutMs?: number;
runtimeDir?: string;
}
export interface QqHookSendOptions {
@@ -85,6 +105,20 @@ interface PendingAck {
wantReply: boolean;
}
function isMissingDirectoryError(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
return code === 'ENOENT' || code === 'ENOTDIR';
}
function isUnavailableSocketError(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
return code === 'ENOENT'
|| code === 'ENOTDIR'
|| code === 'ENOTSOCK'
|| code === 'ECONNREFUSED'
|| code === 'ECONNRESET';
}
/**
* Sync directory scan for `mojo.<pid>.control.sock` socket files in the
* runtime dir, returning the pid set. Used by the darwin path of
@@ -99,14 +133,15 @@ interface PendingAck {
* variant still gates the subsequent `pipe-up` emit via a real connect.
*/
export function listSnowlumaPipePidsSync(
runtimeDir = linuxRuntimeDir(),
runtimeDir = resolveHookRuntimeDir(),
): Set<number> {
const result = new Set<number>();
let names: string[];
try {
names = readdirSync(runtimeDir);
} catch {
return result;
} catch (error) {
if (isMissingDirectoryError(error)) return result;
throw error;
}
for (const name of names) {
const m = /^mojo\.(\d+)\.control\.sock$/i.exec(name);
@@ -117,37 +152,11 @@ export function listSnowlumaPipePidsSync(
return result;
}
function linuxRuntimeDir(): string {
// Name kept for historical reasons (the function predates the macOS port);
// applies to every non-win32 platform. The fallback order mirrors each
// platform hook's runtime_dir(): explicit override first, then the OS-
// native ephemeral-dir convention.
const explicit = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
if (explicit && explicit.length > 0) return explicit;
const xdg = process.env.XDG_RUNTIME_DIR;
if (xdg && xdg.length > 0) return xdg;
// macOS: dylib defaults to "$TMPDIR/snowluma-hook" (apps/qq/macos/
// qq_hook_dylib.cpp's runtime_dir()). $TMPDIR is per-user on macOS
// (under /var/folders/.../T) so this is the right place — Linux's
// /tmp/snowluma-<uid> doesn't exist on a stock Mac.
if (process.platform === 'darwin') {
const tmpdir = process.env.TMPDIR;
if (tmpdir && tmpdir.length > 0) {
const trimmed = tmpdir.endsWith('/') ? tmpdir.slice(0, -1) : tmpdir;
return path.join(trimmed, 'snowluma-hook');
}
}
// Linux fallback: mirrors hook_stub.cpp runtime_dir() last-resort.
// process.geteuid is POSIX-only; cast to allow non-Linux type checks.
const uid = typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid;
return `/tmp/snowluma-${uid}`;
}
function mojoPipeName(pid: number, suffix: string): string {
function mojoPipeName(pid: number, suffix: string, runtimeDir = resolveHookRuntimeDir(pid)): string {
if (process.platform === 'win32') {
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
}
return path.join(linuxRuntimeDir(), `mojo.${pid}.${suffix}.sock`);
return path.join(runtimeDir, `mojo.${pid}.${suffix}.sock`);
}
type LinuxPipeProbe = (socketPath: string) => Promise<boolean>;
@@ -156,16 +165,18 @@ async function isConnectableUnixSocket(socketPath: string): Promise<boolean> {
try {
const stat = await fs.stat(socketPath);
if (!stat.isSocket()) return false;
} catch {
return false;
} catch (error) {
if (isUnavailableSocketError(error)) return false;
throw error;
}
return new Promise<boolean>((resolve) => {
return new Promise<boolean>((resolve, reject) => {
let socket: net.Socket;
try {
socket = net.createConnection(socketPath);
} catch {
resolve(false);
} catch (error) {
if (isUnavailableSocketError(error)) resolve(false);
else reject(error);
return;
}
let done = false;
@@ -180,20 +191,31 @@ async function isConnectableUnixSocket(socketPath: string): Promise<boolean> {
};
timer = setTimeout(() => finish(false), DEFAULT_PIPE_PROBE_TIMEOUT_MS);
socket.once('connect', () => finish(true));
socket.once('error', () => finish(false));
socket.once('error', error => {
if (isUnavailableSocketError(error)) finish(false);
else {
if (done) return;
done = true;
clearTimeout(timer);
socket.removeAllListeners();
socket.destroy();
reject(error);
}
});
});
}
export async function listLiveLinuxPipePids(
runtimeDir = linuxRuntimeDir(),
runtimeDir = resolveHookRuntimeDir(),
probe: LinuxPipeProbe = isConnectableUnixSocket,
): Promise<Set<number>> {
const result = new Set<number>();
let names: string[];
try {
names = await fs.readdir(runtimeDir);
} catch {
return result;
} catch (error) {
if (isMissingDirectoryError(error)) return result;
throw error;
}
await Promise.all(names.map(async (name) => {
@@ -225,11 +247,21 @@ function createDeferred<T>(): Deferred<T> {
return { promise, resolve, reject };
}
class OperationTimeoutError extends Error {
constructor(
readonly label: string,
timeoutMs: number,
) {
super(`${label} timed out after ${timeoutMs} ms`);
this.name = 'OperationTimeoutError';
}
}
function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
if (!timeoutMs || timeoutMs <= 0) return promise;
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(`${label} timed out after ${timeoutMs} ms`));
reject(new OperationTimeoutError(label, timeoutMs));
}, timeoutMs);
promise.then(
value => {
@@ -243,6 +275,29 @@ function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string):
});
}
export class HookPipeRequestError extends Error {
constructor(
message: string,
readonly status: number,
readonly requestId: number,
) {
super(message);
this.name = 'HookPipeRequestError';
}
}
function packetFailureReason(
error: unknown,
requestId: number,
): 'ack_timeout' | 'reply_timeout' | 'request_failed' | 'transport_failure' {
if (error instanceof HookPipeRequestError) return 'request_failed';
if (error instanceof OperationTimeoutError) {
if (error.label === `send ack ${requestId}`) return 'ack_timeout';
if (error.label === `send reply ${requestId}`) return 'reply_timeout';
}
return 'transport_failure';
}
function encodeFrame({
op,
requestId = 0,
@@ -265,6 +320,7 @@ function encodeFrame({
const cmdBuf = Buffer.from(cmd, 'utf8');
const msgBuf = Buffer.from(msg, 'utf8');
const bodyBuf = toBuffer(body);
validatePipeFrameLengths(cmdBuf.length, msgBuf.length, bodyBuf.length);
const header = Buffer.alloc(HEADER_SIZE);
header.writeUInt32LE(PIPE_MAGIC, 0);
header.writeUInt16LE(PIPE_VERSION, 4);
@@ -279,45 +335,115 @@ function encodeFrame({
return Buffer.concat([header, cmdBuf, msgBuf, bodyBuf]);
}
function validatePipeFrameLengths(cmdLen: number, msgLen: number, bodyLen: number): void {
const lengths = [
['command', cmdLen, MAX_PIPE_CMD_BYTES],
['message', msgLen, MAX_PIPE_MSG_BYTES],
['body', bodyLen, MAX_PIPE_BODY_BYTES],
] as const;
for (const [name, length, limit] of lengths) {
if (length > limit) {
throw new Error(`pipe frame ${name} length ${length} exceeds limit ${limit}`);
}
}
}
interface PendingPipeFrame {
op: number;
requestId: number;
status: number;
flags: number;
value0: bigint;
cmdLen: number;
msgLen: number;
bodyLen: number;
payload: Buffer;
received: number;
}
class FrameReader {
private buffer = Buffer.alloc(0);
private readonly header = Buffer.alloc(HEADER_SIZE);
private headerBytes = 0;
private pending: PendingPipeFrame | null = null;
constructor(private readonly onFrame: (frame: PipeFrame) => void) { }
push(chunk: Buffer): void {
this.buffer = Buffer.concat([this.buffer, chunk]);
while (this.buffer.length >= HEADER_SIZE) {
const magic = this.buffer.readUInt32LE(0);
const version = this.buffer.readUInt16LE(4);
if (magic !== PIPE_MAGIC || version !== PIPE_VERSION) {
throw new Error(`bad frame header magic=0x${magic.toString(16)} version=${version}`);
let chunkOffset = 0;
while (chunkOffset < chunk.length) {
if (!this.pending) {
const headerBytes = Math.min(HEADER_SIZE - this.headerBytes, chunk.length - chunkOffset);
chunk.copy(
this.header,
this.headerBytes,
chunkOffset,
chunkOffset + headerBytes,
);
this.headerBytes += headerBytes;
chunkOffset += headerBytes;
if (this.headerBytes < HEADER_SIZE) return;
this.headerBytes = 0;
const magic = this.header.readUInt32LE(0);
const version = this.header.readUInt16LE(4);
if (magic !== PIPE_MAGIC || version !== PIPE_VERSION) {
throw new Error(`bad frame header magic=0x${magic.toString(16)} version=${version}`);
}
const cmdLen = this.header.readUInt32LE(20);
const msgLen = this.header.readUInt32LE(24);
const bodyLen = this.header.readUInt32LE(28);
validatePipeFrameLengths(cmdLen, msgLen, bodyLen);
const payloadLength = cmdLen + msgLen + bodyLen;
this.pending = {
op: this.header.readUInt16LE(6),
requestId: this.header.readUInt32LE(8),
status: this.header.readInt32LE(12),
flags: this.header.readUInt32LE(16),
value0: this.header.readBigUInt64LE(32),
cmdLen,
msgLen,
bodyLen,
payload: payloadLength === 0 ? Buffer.alloc(0) : Buffer.allocUnsafe(payloadLength),
received: 0,
};
}
const cmdLen = this.buffer.readUInt32LE(20);
const msgLen = this.buffer.readUInt32LE(24);
const bodyLen = this.buffer.readUInt32LE(28);
const total = HEADER_SIZE + cmdLen + msgLen + bodyLen;
if (this.buffer.length < total) return;
const pending = this.pending;
const payloadBytes = Math.min(
pending.payload.length - pending.received,
chunk.length - chunkOffset,
);
if (payloadBytes > 0) {
chunk.copy(
pending.payload,
pending.received,
chunkOffset,
chunkOffset + payloadBytes,
);
pending.received += payloadBytes;
chunkOffset += payloadBytes;
}
if (pending.received < pending.payload.length) return;
this.pending = null;
const frame: PipeFrame = {
op: this.buffer.readUInt16LE(6),
requestId: this.buffer.readUInt32LE(8),
status: this.buffer.readInt32LE(12),
flags: this.buffer.readUInt32LE(16),
value0: this.buffer.readBigUInt64LE(32),
op: pending.op,
requestId: pending.requestId,
status: pending.status,
flags: pending.flags,
value0: pending.value0,
cmd: '',
msg: '',
body: Buffer.alloc(0),
};
let offset = HEADER_SIZE;
frame.cmd = this.buffer.subarray(offset, offset + cmdLen).toString('utf8');
offset += cmdLen;
frame.msg = this.buffer.subarray(offset, offset + msgLen).toString('utf8');
offset += msgLen;
frame.body = Buffer.from(this.buffer.subarray(offset, offset + bodyLen));
this.buffer = this.buffer.subarray(total);
let offset = 0;
frame.cmd = pending.payload.subarray(offset, offset + pending.cmdLen).toString('utf8');
offset += pending.cmdLen;
frame.msg = pending.payload.subarray(offset, offset + pending.msgLen).toString('utf8');
offset += pending.msgLen;
frame.body = Buffer.from(pending.payload.subarray(offset, offset + pending.bodyLen));
this.onFrame(frame);
}
}
@@ -325,6 +451,7 @@ class FrameReader {
export class QqHookClient extends EventEmitter {
readonly pid: number;
readonly runtimeDir: string;
readonly defaultAckTimeoutMs: number;
readonly defaultReplyTimeoutMs: number;
@@ -345,11 +472,13 @@ export class QqHookClient extends EventEmitter {
private loginWaiters: Deferred<QqHookLoginState>[] = [];
constructor(pid: number, {
ackTimeoutMs = DEFAULT_ACK_TIMEOUT_MS,
ackTimeoutMs = positiveIntEnv('SNOWLUMA_HOOK_ACK_TIMEOUT_MS', DEFAULT_ACK_TIMEOUT_MS),
replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS,
runtimeDir = resolveHookRuntimeDir(pid),
}: QqHookClientOptions = {}) {
super();
this.pid = pid;
this.runtimeDir = runtimeDir;
this.defaultAckTimeoutMs = ackTimeoutMs;
this.defaultReplyTimeoutMs = replyTimeoutMs;
}
@@ -374,6 +503,17 @@ export class QqHookClient extends EventEmitter {
return { ...this.loginState };
}
/**
* Forward an observed account identity for reconciliation. This does not
* change login state; readiness still requires peer confirmation.
*/
async reconcileLoginIdentity(uin: string): Promise<void> {
if (!isRealUin(uin)) {
throw new Error(`invalid QQ login identity hint: ${JSON.stringify(uin)}`);
}
await this.sendAckOnly(PipeOp.loginIdentityHint, BigInt(uin), 'login identity hint');
}
async waitForLogin({ timeoutMs = 0 } = {}): Promise<QqHookLoginState> {
await this.connect();
if (this.loginState.loggedIn) {
@@ -384,12 +524,12 @@ export class QqHookClient extends EventEmitter {
return withTimeout(deferred.promise, timeoutMs, 'waitForLogin');
}
static controlPipeName(pid: number): string {
return mojoPipeName(pid, 'control');
static controlPipeName(pid: number, runtimeDir = resolveHookRuntimeDir(pid)): string {
return mojoPipeName(pid, 'control', runtimeDir);
}
static recvPipeName(pid: number): string {
return mojoPipeName(pid, 'recv');
static recvPipeName(pid: number, runtimeDir = resolveHookRuntimeDir(pid)): string {
return mojoPipeName(pid, 'recv', runtimeDir);
}
/**
@@ -398,7 +538,7 @@ export class QqHookClient extends EventEmitter {
* opening the pipe, so probing cannot disturb the first real client connect.
*/
static async probePipe(pid: number): Promise<boolean> {
const live = await QqHookClient.listLivePipes();
const live = await QqHookClient.listLivePipes([pid]);
return live.has(pid);
}
@@ -407,20 +547,24 @@ export class QqHookClient extends EventEmitter {
* in a single filesystem listing. The HookManager's pipe-watcher uses this
* to drive connect/reconnect decisions without per-PID stat calls.
*/
static async listLivePipes(): Promise<Set<number>> {
static async listLivePipes(pids: readonly number[] = []): Promise<Set<number>> {
const result = new Set<number>();
try {
if (process.platform === 'win32') {
const names = await fs.readdir('\\\\.\\pipe\\');
for (const name of names) {
const m = /^mojo\.(\d+)\.control$/i.exec(name);
if (m) result.add(Number(m[1]));
}
if (process.platform === 'win32') {
const names = await fs.readdir('\\\\.\\pipe\\');
for (const name of names) {
const m = /^mojo\.(\d+)\.control$/i.exec(name);
if (m) result.add(Number(m[1]));
}
} else {
const runtimeDirs = new Set<string>();
if (pids.length === 0) {
runtimeDirs.add(resolveHookRuntimeDir());
} else {
return await listLiveLinuxPipePids();
for (const pid of pids) runtimeDirs.add(resolveHookRuntimeDir(pid));
}
for (const runtimeDir of runtimeDirs) {
for (const pid of await listLiveLinuxPipePids(runtimeDir)) result.add(pid);
}
} catch {
/* directory missing or inaccessible — treat as no live pipes */
}
return result;
}
@@ -435,14 +579,7 @@ export class QqHookClient extends EventEmitter {
if (this.controlConnectPromise) {
return this.controlConnectPromise;
}
this.controlConnectPromise = (async () => {
this.controlSocket = await this.connectSocket(
QqHookClient.controlPipeName(this.pid),
'control',
frame => this.handleControlFrame(frame));
this.controlHello = await this.waitForHello(false);
return this.controlHello;
})();
this.controlConnectPromise = this.connectPipe('control');
try {
return await this.controlConnectPromise;
} finally {
@@ -463,14 +600,7 @@ export class QqHookClient extends EventEmitter {
if (this.recvConnectPromise) {
return this.recvConnectPromise;
}
this.recvConnectPromise = (async () => {
this.recvSocket = await this.connectSocket(
QqHookClient.recvPipeName(this.pid),
'recv',
frame => this.handleRecvFrame(frame));
this.recvHello = await this.waitForHello(true);
return this.recvHello;
})();
this.recvConnectPromise = this.connectPipe('recv');
try {
return await this.recvConnectPromise;
} finally {
@@ -491,25 +621,23 @@ export class QqHookClient extends EventEmitter {
}: QqHookSendOptions = {}): Promise<QqHookSendReply | { requestId: number }> {
await this.connect();
// Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would
// misbehave once the integer exceeds Number.MAX_SAFE_INTEGER (the
// postfix increment loses precision before the shift), letting two
// distinct requests collide on the same id. Skip 0 because zero is
// used as a sentinel by the wire protocol.
let requestId = this.nextRequestId;
while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) {
requestId = (requestId + 1) >>> 0;
if (requestId === 0) requestId = 1;
}
this.nextRequestId = (requestId + 1) >>> 0;
if (this.nextRequestId === 0) this.nextRequestId = 1;
const requestId = this.allocateRequestId();
const startedAt = Date.now();
const bodyBytes = toBuffer(body);
const payload = encodeFrame({
op: PipeOp.sendRequest,
requestId,
flags: wantReply ? PipeFlagWantReply : 0,
cmd,
body,
body: bodyBytes,
});
packetLog.trace(() => [
'packet_send serviceCmd=%j requestId=%d length=%d body=%s',
cmd,
requestId,
bodyBytes.length,
renderTraceBytes(bodyBytes),
]);
const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>();
// Always attach a handler so a rejection can never become "unhandled" (which
@@ -535,15 +663,50 @@ export class QqHookClient extends EventEmitter {
await this.writeControl(payload);
await withTimeout(ackDeferred.promise, ackTimeoutMs, `send ack ${requestId}`);
if (!wantReply) {
packetLog.trace(() => [
'packet_terminal serviceCmd=%j requestId=%d outcome=ok reason=ack_received elapsedMs=%d',
cmd,
requestId,
Date.now() - startedAt,
]);
return { requestId };
}
return await withTimeout(
const reply = await withTimeout(
replyDeferred!.promise,
replyTimeoutMs,
`send reply ${requestId}`);
packetLog.trace(() => [
'packet_recv serviceCmd=%j requestId=%d error=%d message=%j length=%d body=%s',
cmd,
requestId,
reply.error,
reply.message,
reply.body.length,
renderTraceBytes(reply.body),
]);
packetLog.trace(() => [
'packet_terminal serviceCmd=%j requestId=%d outcome=%s reason=%s error=%d elapsedMs=%d',
cmd,
requestId,
reply.error === 0 ? 'ok' : 'failed',
reply.error === 0 ? 'reply_received' : 'reply_error',
reply.error,
Date.now() - startedAt,
]);
return reply;
} catch (error) {
this.pendingAcks.delete(requestId);
this.pendingReplies.delete(requestId);
const reason = packetFailureReason(error, requestId);
packetLog.trace(() => [
'packet_terminal serviceCmd=%j requestId=%d outcome=%s reason=%s error=%j elapsedMs=%d',
cmd,
requestId,
reason.endsWith('_timeout') ? 'timeout' : 'failed',
reason,
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
]);
throw error;
}
}
@@ -682,6 +845,97 @@ export class QqHookClient extends EventEmitter {
return writePromise;
}
private allocateRequestId(): number {
// Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would lose
// precision past Number.MAX_SAFE_INTEGER. Zero remains the wire sentinel.
let requestId = this.nextRequestId;
while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) {
requestId = (requestId + 1) >>> 0;
if (requestId === 0) requestId = 1;
}
this.nextRequestId = (requestId + 1) >>> 0;
if (this.nextRequestId === 0) this.nextRequestId = 1;
return requestId;
}
private async sendAckOnly(op: PipeOp, value0: bigint, label: string): Promise<number> {
await this.connect();
const requestId = this.allocateRequestId();
const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>();
ackDeferred.promise.catch(() => { /* observed by the await below */ });
this.pendingAcks.set(requestId, {
resolve: ackDeferred.resolve,
reject: ackDeferred.reject,
wantReply: false,
});
try {
await this.writeControl(encodeFrame({ op, requestId, value0 }));
await withTimeout(
ackDeferred.promise,
this.defaultAckTimeoutMs,
`${label} ack ${requestId}`,
);
return requestId;
} catch (error) {
this.pendingAcks.delete(requestId);
throw error;
}
}
private async connectPipe(kind: 'control' | 'recv'): Promise<QqHookHello> {
return runWithTraceRequest(async () => {
const startedAt = Date.now();
const pipeName = kind === 'control'
? QqHookClient.controlPipeName(this.pid, this.runtimeDir)
: QqHookClient.recvPipeName(this.pid, this.runtimeDir);
let phase: 'connect' | 'hello' = 'connect';
runtimeLog.trace(
'hook_pipe_start pid=%d kind=%s pipeName=%j',
this.pid,
kind,
pipeName,
);
try {
const socket = await runWithoutRequestContext(() => this.connectSocket(
pipeName,
kind,
kind === 'control'
? frame => this.handleControlFrame(frame)
: frame => this.handleRecvFrame(frame),
));
if (kind === 'control') this.controlSocket = socket;
else this.recvSocket = socket;
runtimeLog.trace(
'hook_pipe_branch pid=%d kind=%s branch=socket_connected',
this.pid,
kind,
);
phase = 'hello';
const hello = await this.waitForHello(kind === 'recv');
if (kind === 'control') this.controlHello = hello;
else this.recvHello = hello;
runtimeLog.trace(() => [
'hook_pipe_terminal pid=%d kind=%s outcome=completed reason=hello_received hello=%s elapsedMs=%d',
this.pid,
kind,
renderParamsVerbose(hello),
Date.now() - startedAt,
]);
return hello;
} catch (error) {
runtimeLog.trace(() => [
'hook_pipe_terminal pid=%d kind=%s outcome=failed reason=%s error=%j elapsedMs=%d',
this.pid,
kind,
phase === 'connect' ? 'connect_failed' : 'hello_failed',
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
]);
throw error;
}
});
}
private connectSocket(pipeName: string, kind: 'control' | 'recv', onFrame: (frame: PipeFrame) => void): Promise<net.Socket> {
return new Promise((resolve, reject) => {
const socket = net.createConnection(pipeName);
@@ -695,15 +949,17 @@ export class QqHookClient extends EventEmitter {
reader.push(chunk);
} catch (error) {
this.emit('error', error);
socket.destroy(error instanceof Error ? error : undefined);
socket.destroy();
}
});
socket.on('error', error => {
this.emit('error', error);
});
socket.on('close', () => {
this.handleSocketClose(kind);
this.emit('close', kind);
runWithTraceRequest(() => {
this.handleSocketClose(kind);
this.emit('close', kind);
});
});
resolve(socket);
});
@@ -733,6 +989,13 @@ export class QqHookClient extends EventEmitter {
}
private handleSocketClose(kind: 'control' | 'recv'): void {
runtimeLog.trace(
'hook_runtime_fact pid=%d event=pipe_closed kind=%s loggedIn=%s uin=%j',
this.pid,
kind,
this.loginState.loggedIn,
this.loginState.uin,
);
if (kind === 'control') {
this.controlSocket = null;
this.controlHello = null;
@@ -750,17 +1013,32 @@ export class QqHookClient extends EventEmitter {
const loggedIn = flaggedLoggedIn || statusLoggedIn;
const uinNumber = BigInt(frame.value0);
const uin = frame.msg || uinNumber.toString();
this.applyLoginState({ loggedIn, uin, uinNumber });
}
private applyLoginState(next: QqHookLoginState): void {
const previous = this.loginState;
const next = { loggedIn, uin, uinNumber };
this.loginState = next;
this.emit('loginState', next);
if (previous.loggedIn !== next.loggedIn || previous.uin !== next.uin) {
if (previous.loggedIn === next.loggedIn && previous.uin === next.uin) {
this.emit('loginState', next);
return;
}
runWithTraceRequest(() => {
runtimeLog.trace(
'hook_runtime_fact pid=%d event=login_state_changed previousLoggedIn=%s previousUin=%j loggedIn=%s uin=%j',
this.pid,
previous.loggedIn,
previous.uin,
next.loggedIn,
next.uin,
);
this.emit('loginState', next);
if (next.loggedIn) {
const waiters = this.loginWaiters;
this.loginWaiters = [];
for (const waiter of waiters) waiter.resolve({ ...next });
}
}
});
}
private handleControlFrame(frame: PipeFrame): void {
@@ -792,7 +1070,11 @@ export class QqHookClient extends EventEmitter {
return;
}
if (frame.op === PipeOp.error) {
const error = new Error(frame.msg || `pipe error ${frame.status}`);
const error = new HookPipeRequestError(
frame.msg || `pipe error ${frame.status}`,
frame.status,
frame.requestId,
);
const ack = this.pendingAcks.get(frame.requestId);
if (ack) {
this.pendingAcks.delete(frame.requestId);
+43 -115
View File
@@ -1,15 +1,16 @@
import { createLogger } from '@snowluma/common/logger';
import { exec } from 'child_process';
import net from 'net';
import http from 'http';
import https from 'https';
import { promisify } from 'util';
const execAsync = promisify(exec);
const log = createLogger('LoginProbe');
const PORT_RANGE_START = 9210;
const PORT_RANGE_END = 9219;
const PROBE_TIMEOUT_MS = 1000;
const CONNECTION_TIMEOUT_MS = 500;
const COMMAND_TIMEOUT_MS = 1500;
const OVERALL_PROBE_TIMEOUT_MS = 5000;
const EXEC_OPTIONS = { timeout: COMMAND_TIMEOUT_MS, killSignal: 'SIGKILL' as const };
// QQ's Ptlogin quick-login ports plus its main process mean a single
// logged-in client surfaces roughly this many processes. When no usable
// probe port is found, a count BELOW this implies the target PID is still at
@@ -23,102 +24,11 @@ export interface QqPortLoginInfo {
uin: string;
uid?: string;
nickName?: string;
loggedIn: boolean;
/** The local QQ endpoint exposed an account identity. This does not prove
* the native protocol session is ready to send or receive packets. */
identityKnown: boolean;
}
interface JwtPayload {
errCode: number;
errMsg: string;
port: number;
uin?: string;
uid?: string;
nickName?: string;
data?: {
uin?: string;
url?: string;
};
iat: number;
}
function decodeJwt(token: string): JwtPayload | null {
try {
const parts = token.split('.');
if (parts.length !== 3) return null;
const payload = Buffer.from(parts[1], 'base64').toString('utf8');
return JSON.parse(payload);
} catch {
return null;
}
}
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
return new Promise((resolve) => {
const client = new net.Socket();
const link = 'tencent://';
const payload = `POST /tencent HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\nContent-Length: ${link.length}\r\n\r\n${link}`;
let responseData = '';
let timer: NodeJS.Timeout;
const cleanup = () => {
clearTimeout(timer);
client.removeAllListeners();
client.destroy();
};
timer = setTimeout(() => {
cleanup();
resolve(null);
}, PROBE_TIMEOUT_MS);
client.setTimeout(CONNECTION_TIMEOUT_MS);
client.connect(port, '127.0.0.1', () => {
client.write(payload);
});
client.on('data', (data) => {
responseData += data.toString();
});
client.on('close', () => {
cleanup();
const jwtMatch = responseData.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/);
if (!jwtMatch) {
resolve(null);
return;
}
const decoded = decodeJwt(jwtMatch[0]);
if (!decoded || decoded.errCode !== 0) {
resolve(null);
return;
}
const uin = decoded.uin || decoded.data?.uin || '';
resolve({
port,
uin,
uid: decoded.uid,
nickName: decoded.nickName,
loggedIn: uin.length > 0,
});
});
client.on('error', () => {
cleanup();
resolve(null);
});
client.on('timeout', () => {
cleanup();
resolve(null);
});
});
}
/** One entry of the Ptlogin `pt_get_uins` JSONP array. Only the fields the
* probe reads are modelled; QQ sends more but they're irrelevant here. */
interface PtloginUin {
@@ -189,7 +99,7 @@ async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallba
port,
uin: String(account.uin || account.account || ''),
nickName: account.nickname || '',
loggedIn: true,
identityKnown: true,
};
}
@@ -200,10 +110,13 @@ async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallba
async function getQqProcessCount(): Promise<number> {
try {
if (process.platform === 'win32') {
const { stdout } = await execAsync('tasklist /fi "imagename eq QQ.exe" /nh');
const { stdout } = await execAsync(
'tasklist /fi "imagename eq QQ.exe" /nh',
EXEC_OPTIONS,
);
return stdout.toLowerCase().split('\n').filter(line => line.includes('qq.exe')).length;
} else {
const { stdout } = await execAsync('pgrep -c qq');
const { stdout } = await execAsync('pgrep -c qq', EXEC_OPTIONS);
return parseInt(stdout.trim(), 10) || 0;
}
} catch {
@@ -213,10 +126,10 @@ async function getQqProcessCount(): Promise<number> {
}
}
async function getProcessPorts(pid: number): Promise<number[]> {
async function getProcessPorts(pid: number): Promise<number[] | null> {
try {
if (process.platform === 'win32') {
const { stdout } = await execAsync(`netstat -ano | findstr ${pid}`);
const { stdout } = await execAsync('netstat -ano', EXEC_OPTIONS);
const ports = new Set<number>();
const lines = stdout.split('\n');
for (const line of lines) {
@@ -232,10 +145,11 @@ async function getProcessPorts(pid: number): Promise<number[]> {
}
return Array.from(ports);
} else {
const { stdout } = await execAsync(`ss -tlnp | grep pid=${pid}`);
const { stdout } = await execAsync('ss -tlnp', EXEC_OPTIONS);
const ports = new Set<number>();
const lines = stdout.split('\n');
for (const line of lines) {
if (!line.includes(`pid=${pid},`) && !line.includes(`pid=${pid})`)) continue;
const match = line.match(/:(\d+)\s/);
if (match) {
ports.add(Number(match[1]));
@@ -244,18 +158,18 @@ async function getProcessPorts(pid: number): Promise<number[]> {
return Array.from(ports);
}
} catch {
return [];
return null;
}
}
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo | null> {
const ports = await getProcessPorts(pid);
if (ports === null) return null;
if (ports.length === 0) {
const totalPids = await getQqProcessCount();
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
return { port: 0, uin: '', loggedIn: false };
return { port: 0, uin: '', identityKnown: false };
}
return null;
}
@@ -285,16 +199,30 @@ export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | n
return {
port: ports[0] || 0,
uin: '',
loggedIn: false,
identityKnown: false,
};
}
}
const deepLinkPorts = ports.filter(p => p >= PORT_RANGE_START && p <= PORT_RANGE_END);
for (const port of deepLinkPorts) {
const info = await probePort(port);
if (info) return info;
}
// Background discovery must remain passive. Interactive application
// endpoints are deliberately excluded from automatic probing.
return null;
}
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
let timer: ReturnType<typeof setTimeout> | undefined;
let timedOut = false;
const timeout = new Promise<null>(resolve => {
timer = setTimeout(() => {
timedOut = true;
resolve(null);
}, OVERALL_PROBE_TIMEOUT_MS);
});
try {
const result = await Promise.race([probeQqLoginInfoInternal(pid), timeout]);
if (timedOut) log.warn('login check timed out: PID=%d', pid);
return result;
} finally {
if (timer) clearTimeout(timer);
}
}
+249 -3
View File
@@ -5,21 +5,39 @@ import os from 'os';
import path from 'path';
import { HookManager, shouldAutoLoadPid } from '../src/hook-manager';
import { PipeWatcher } from '../src/pipe-watcher';
import type { ManualMapHandle } from '../src/injector';
import type { HookInjectResult, ManualMapHandle } from '../src/injector';
import type { BridgeManagerSink } from '../src/hook-manager';
import type { QqHookClient } from '../src/qq-hook-client';
import { createLogger } from '@snowluma/common/logger';
import {
createLogger,
getLogLevel,
setLogLevel,
subscribeLogs,
type LogEntry,
} from '@snowluma/common/logger';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
const flush = () => new Promise<void>(r => setImmediate(r));
const previousLogLevel = getLogLevel();
function managerTrace(entries: LogEntry[]): LogEntry[] {
return entries.filter(
(entry) => entry.level === 'trace' && entry.scope === 'Hook',
);
}
function makeManager(opts: {
autoLoadOnDiscovery?: boolean;
processes?: number[];
onSessionsChanged?: () => void;
inject?: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
}) {
let pids = opts.processes ?? [];
const live = new Set<number>();
const inject = vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE }));
const inject = vi.fn(opts.inject ?? (() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})));
const unload = vi.fn();
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
@@ -48,6 +66,7 @@ function makeManager(opts: {
injector: { inject, unload },
makeClient,
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
onSessionsChanged: opts.onSessionsChanged,
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
});
return {
@@ -58,6 +77,173 @@ function makeManager(opts: {
};
}
afterEach(() => {
setLogLevel(previousLogLevel);
});
describe('HookManager runtime TRACE', () => {
it('records discovery and process-gone facts while unchanged ticks stay silent', async () => {
const entries: LogEntry[] = [];
const sessionsChanged = vi.fn();
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({
autoLoadOnDiscovery: false,
processes: [],
onSessionsChanged: sessionsChanged,
});
try {
await ctx.pipeWatcher.start();
const baseline = managerTrace(entries).length;
await ctx.pipeWatcher.tickNow();
await ctx.pipeWatcher.tickNow();
expect(managerTrace(entries)).toHaveLength(baseline);
ctx.setProcesses([4242]);
await ctx.pipeWatcher.tickNow();
ctx.setProcesses([]);
await ctx.pipeWatcher.tickNow();
await flush();
const facts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_manager_fact '),
);
expect(facts.map((entry) => entry.message)).toEqual([
expect.stringContaining('hook_manager_fact event=process_discovered pid=4242'),
'hook_manager_fact event=process_gone pid=4242 tracked=true',
]);
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
it('records bounded transient retries and recovery as separate attempts', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject
.mockImplementationOnce(() => {
throw new Error(
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
);
})
.mockImplementationOnce(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
}));
try {
await ctx.pipeWatcher.start();
await flush();
await flush();
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
const attempts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_'),
);
expect(attempts.map((entry) => entry.message)).toEqual([
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=1 outcome=failed reason=retry_pending error=.*elapsedMs=\d+$/),
'hook_autoload_start pid=4242 attempt=2 maxAttempts=3',
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=2 outcome=completed reason=recovered state=.*elapsedMs=\d+$/),
]);
expect(attempts[0]!.req).toBe(attempts[1]!.req);
expect(attempts[2]!.req).toBe(attempts[3]!.req);
expect(attempts[0]!.req).not.toBe(attempts[2]!.req);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
it('ends an in-flight auto-load as dropped when a manual load supersedes it', async () => {
const entries: LogEntry[] = [];
let resolveInjection!: (result: HookInjectResult) => void;
const injection = new Promise<HookInjectResult>((resolve) => {
resolveInjection = resolve;
});
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({
autoLoadOnDiscovery: true,
processes: [4242],
inject: () => injection,
});
try {
await ctx.pipeWatcher.start();
await flush();
const manualLoad = ctx.manager.loadProcess(4242);
resolveInjection({ method: 'loadModuleManual', handle: DUMMY_HANDLE });
await manualLoad;
await flush();
const attempts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_'),
);
expect(attempts.map((entry) => entry.message)).toEqual([
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
expect.stringMatching(
/^hook_autoload_terminal pid=4242 attempt=1 outcome=dropped reason=superseded elapsedMs=\d+$/,
),
]);
expect(attempts[0]!.req).toBe(attempts[1]!.req);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
it.each([
{
name: 'permanent failure',
error: 'ptrace denied',
ticks: 1,
attempts: 1,
reason: 'permanent_failure',
},
{
name: 'retry exhaustion',
error: 'target process does not map /lib/libc.so.6 while resolving mmap',
ticks: 4,
attempts: 3,
reason: 'retry_exhausted',
},
])('records $name terminal', async ({ error, ticks, attempts, reason }) => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementation(() => { throw new Error(error); });
try {
await ctx.pipeWatcher.start();
await flush();
await flush();
for (let tick = 0; tick < ticks; tick += 1) {
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
}
const starts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_start '),
);
const terminals = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_terminal '),
);
expect(starts).toHaveLength(attempts);
expect(terminals).toHaveLength(attempts);
expect(terminals.at(-1)!.message).toContain(`reason=${reason}`);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
});
describe('HookManager.autoLoadOnDiscovery', () => {
it('does NOT inject on process-discovered when flag is off', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
@@ -105,6 +291,66 @@ describe('HookManager.autoLoadOnDiscovery', () => {
ctx.manager.dispose();
});
it('retries a transient libc mapping failure on the next watcher tick', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementationOnce(() => {
throw new Error(
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
);
});
await ctx.pipeWatcher.start();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(1);
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(2);
expect(ctx.inject).toHaveBeenLastCalledWith(4242);
ctx.manager.dispose();
});
it('does not retry permanent auto-load errors', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementation(() => { throw new Error('ptrace denied'); });
await ctx.pipeWatcher.start();
await flush();
await flush();
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(1);
ctx.manager.dispose();
});
it('stops retrying a transient libc mapping failure after three attempts', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementation(() => {
throw new Error(
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
);
});
await ctx.pipeWatcher.start();
await flush();
await flush();
for (let tick = 0; tick < 4; tick += 1) {
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
}
expect(ctx.inject).toHaveBeenCalledTimes(3);
ctx.manager.dispose();
});
});
// `shouldAutoLoadPid` reads /proc/<pid>/cmdline directly, so we point
@@ -0,0 +1,60 @@
import { describe, expect, it, vi } from 'vitest';
import { HookPacketClient } from '../src/hook-packet-client';
import {
HookPipeRequestError,
PIPE_STATUS_CONNECTION_UNAVAILABLE,
type QqHookClient,
} from '../src/qq-hook-client';
function fakeClient(send: QqHookClient['send']): QqHookClient {
return {
isLoggedIn: true,
send,
} as unknown as QqHookClient;
}
describe('HookPacketClient outbound health', () => {
it('reports native connection loss once and recovers after a successful request', async () => {
const healthChanged = vi.fn();
const send = vi
.fn<QqHookClient['send']>()
.mockRejectedValueOnce(new HookPipeRequestError(
'The QQ connection changed. Please restart QQ and try again.',
PIPE_STATUS_CONNECTION_UNAVAILABLE,
1,
))
.mockRejectedValueOnce(new HookPipeRequestError(
'The QQ connection changed. Please restart QQ and try again.',
PIPE_STATUS_CONNECTION_UNAVAILABLE,
2,
))
.mockResolvedValueOnce({
requestId: 3,
error: 0,
message: '',
body: Buffer.from('ok'),
});
const sender = new HookPacketClient(fakeClient(send), healthChanged);
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
.resolves.toMatchObject({ success: false, gotResponse: false });
await sender.sendPacket('Test.Command', Buffer.alloc(0));
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
.resolves.toMatchObject({ success: true, gotResponse: true });
expect(healthChanged.mock.calls).toEqual([[false], [true]]);
});
it('does not classify ordinary request rejection as connection loss', async () => {
const healthChanged = vi.fn();
const send = vi.fn<QqHookClient['send']>().mockRejectedValue(
new HookPipeRequestError('This request is not valid.', -38, 1),
);
const sender = new HookPacketClient(fakeClient(send), healthChanged);
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
.resolves.toMatchObject({ success: false, gotResponse: false });
expect(healthChanged).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,67 @@
import { describe, expect, it } from 'vitest';
import { resolveHookRuntimeDir } from '../src/hook-runtime-dir';
function procReader(files: Record<string, string>) {
return (file: string): string => {
const value = files[file];
if (value === undefined) throw new Error(`missing fixture: ${file}`);
return value;
};
}
describe('resolveHookRuntimeDir — Linux target process ownership', () => {
it('uses the QQ process runtime directory instead of the supervisor user directory', () => {
expect(resolveHookRuntimeDir(46301, {
platform: 'linux',
env: { XDG_RUNTIME_DIR: '/run/user/0' },
ownUid: 0,
readText: procReader({
'/proc/46301/environ': 'HOME=/home/rikka\0XDG_RUNTIME_DIR=/run/user/1000\0',
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
}),
})).toBe('/run/user/1000');
});
it('falls back to the QQ process uid when its environment has no runtime directory', () => {
expect(resolveHookRuntimeDir(46301, {
platform: 'linux',
env: { XDG_RUNTIME_DIR: '/run/user/0' },
ownUid: 0,
readText: procReader({
'/proc/46301/environ': 'HOME=/home/rikka\0',
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
}),
})).toBe('/tmp/snowluma-1000');
});
it('fails visibly when target ownership cannot be determined', () => {
expect(() => resolveHookRuntimeDir(46301, {
platform: 'linux',
env: { XDG_RUNTIME_DIR: '/run/user/0' },
ownUid: 0,
readText: () => { throw new Error('permission denied'); },
})).toThrow(/cannot resolve hook runtime directory.*permission denied/);
});
it('uses the current convention when the target disappears during discovery', () => {
const gone = Object.assign(new Error('process disappeared'), { code: 'ENOENT' });
expect(resolveHookRuntimeDir(46301, {
platform: 'linux',
env: { XDG_RUNTIME_DIR: '/run/user/0' },
ownUid: 0,
readText: () => { throw gone; },
})).toBe('/run/user/0');
});
it('honours an explicit runtime directory inherited by the QQ process', () => {
expect(resolveHookRuntimeDir(46301, {
platform: 'linux',
env: {},
ownUid: 0,
readText: procReader({
'/proc/46301/environ': 'SNOWLUMA_HOOK_RUNTIME_DIR=/srv/snowluma-hook\0',
'/proc/46301/status': 'Uid:\t1000\t1000\t1000\t1000\n',
}),
})).toBe('/srv/snowluma-hook');
});
});
+483 -24
View File
@@ -1,10 +1,34 @@
import { describe, it, expect, vi } from 'vitest';
import { afterEach, describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookSession } from '../src/hook-session';
import type { ManualMapHandle } from '../src/injector';
import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client';
import {
HookPipeRequestError,
PIPE_STATUS_CONNECTION_UNAVAILABLE,
type QqHookClient,
type QqHookPacket,
} from '../src/qq-hook-client';
import type { QqPortLoginInfo } from '../src/qq-port-probe';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketSink } from '@snowluma/common/protocol-types';
import {
getLogLevel,
setLogLevel,
subscribeLogs,
type LogEntry,
} from '@snowluma/common/logger';
const previousLogLevel = getLogLevel();
function sessionTrace(entries: LogEntry[]): LogEntry[] {
return entries.filter(
(entry) => entry.level === 'trace' && entry.scope === 'HookSession',
);
}
afterEach(() => {
setLogLevel(previousLogLevel);
});
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
@@ -14,6 +38,11 @@ class FakeClient extends EventEmitter {
isClosed = false;
isLoggedIn = false;
shouldFailConnect = false;
nativeReadyOnIdentityHint = false;
identityHintFailures = 0;
sendError: Error | null = null;
readonly sentPackets: Array<{ serviceCmd: string; body: Buffer }> = [];
readonly loginIdentityHints: string[] = [];
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
async connectAll(_opts: { recv: boolean }): Promise<void> {
@@ -21,6 +50,29 @@ class FakeClient extends EventEmitter {
if (this.isClosed) throw new Error('client is closed');
}
getLoginState() { return { ...this.loginState }; }
reconcileLoginState(state: { loggedIn: boolean; uin: string; uinNumber: bigint }): void {
this.isLoggedIn = state.loggedIn;
this.loginState = { ...state };
this.emit('loginState', { ...this.loginState });
}
async reconcileLoginIdentity(uin: string): Promise<void> {
this.loginIdentityHints.push(uin);
if (this.identityHintFailures > 0) {
this.identityHintFailures--;
throw new Error('identity hint unavailable');
}
if (this.nativeReadyOnIdentityHint) this.fireLogin(uin);
}
async send(serviceCmd: string, body: Buffer) {
if (this.sendError) throw this.sendError;
this.sentPackets.push({ serviceCmd, body: Buffer.from(body) });
return {
requestId: this.sentPackets.length,
error: 0,
message: '',
body: Buffer.from('reply'),
};
}
close(): void {
if (this.isClosed) return;
this.isClosed = true;
@@ -28,9 +80,7 @@ class FakeClient extends EventEmitter {
}
fireLogin(uin: string): void {
this.isLoggedIn = true;
this.loginState = { loggedIn: true, uin, uinNumber: BigInt(uin) };
this.emit('loginState', { ...this.loginState });
this.reconcileLoginState({ loggedIn: true, uin, uinNumber: BigInt(uin) });
}
firePacket(packet: QqHookPacket): void {
@@ -44,6 +94,8 @@ function makeSession(opts: {
clientFailsConnect?: boolean;
onPacket?: PacketSink;
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
nativeReadyOnIdentityHint?: boolean;
identityHintFailures?: number;
} = {}) {
const pid = opts.pid ?? 1234;
let pipeLive = opts.pipeLive ?? false;
@@ -52,15 +104,17 @@ function makeSession(opts: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
};
// Default probe reports "not logged in" so the reconcile safety net is inert
// unless a test opts into a logged-in probe (never hits the real port scan).
const probeLogin = opts.probeLogin ?? (async () => ({ port: 0, uin: '', loggedIn: false }));
// Default probe exposes no identity so the reconcile safety net is inert
// unless a test opts into a known account.
const probeLogin = opts.probeLogin ?? (async () => ({ port: 0, uin: '', identityKnown: false }));
const session = new HookSession(pid, {
injector,
makeClient: () => {
const c = new FakeClient();
if (opts.clientFailsConnect) c.shouldFailConnect = true;
c.nativeReadyOnIdentityHint = opts.nativeReadyOnIdentityHint ?? false;
c.identityHintFailures = opts.identityHintFailures ?? 0;
clients.push(c);
// Cast: FakeClient mirrors only the surface HookSession touches.
return c as unknown as QqHookClient;
@@ -81,6 +135,185 @@ function makeSession(opts: {
const flush = () => new Promise<void>(r => setImmediate(r));
describe('HookSession — runtime TRACE', () => {
it('records injection and existing-pipe load branches with unique terminals', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const injected = makeSession({ pid: 7101, pipeLive: false });
const reconnect = makeSession({ pid: 7102, pipeLive: true });
await injected.session.load();
await reconnect.session.load();
const messages = sessionTrace(entries).map((entry) => entry.message);
expect(messages).toEqual(expect.arrayContaining([
expect.stringContaining('hook_session_start pid=7101 operation=load'),
'hook_session_branch pid=7101 operation=load branch=inject_begin',
'hook_session_branch pid=7101 operation=load branch=inject_completed method="loadModuleManual"',
expect.stringMatching(/^hook_session_terminal pid=7101 operation=load outcome=completed reason=load_settled state=.*elapsedMs=\d+$/),
expect.stringContaining('hook_session_start pid=7102 operation=load'),
'hook_session_branch pid=7102 operation=load branch=existing_pipe method="reconnect"',
expect.stringMatching(/^hook_session_terminal pid=7102 operation=load outcome=completed reason=load_settled state=.*elapsedMs=\d+$/),
]));
for (const pid of [7101, 7102]) {
expect(messages.filter(
(message) => message.startsWith(`hook_session_terminal pid=${pid} operation=load `),
)).toHaveLength(1);
}
} finally {
unsubscribe();
}
});
it('records load and connection failures with truthful settled state', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const injector = {
inject: vi.fn(() => { throw new Error('fixture inject failure'); }),
unload: vi.fn(),
};
const failedLoad = new HookSession(7103, {
injector,
makeClient: () => new FakeClient() as unknown as QqHookClient,
pipeWatcher: { isPipeLive: () => false },
});
await failedLoad.load();
const failedConnect = makeSession({
pid: 7104,
pipeLive: true,
clientFailsConnect: true,
});
await failedConnect.session.load();
failedConnect.session.onPipeUp();
await flush();
const messages = sessionTrace(entries).map((entry) => entry.message);
expect(messages).toEqual(expect.arrayContaining([
expect.stringMatching(/^hook_session_terminal pid=7103 operation=load outcome=failed reason=load_failed error="fixture inject failure" state=.*elapsedMs=\d+$/),
expect.stringContaining('hook_session_connect_start pid=7104'),
expect.stringMatching(/^hook_session_connect_terminal pid=7104 outcome=failed reason=connect_failed error="connect failed" state=.*elapsedMs=\d+$/),
]));
expect(messages.filter(
(message) => message.startsWith('hook_session_connect_terminal pid=7104 '),
)).toHaveLength(1);
} finally {
unsubscribe();
}
});
it('records login, disconnect, and process-gone only when state changes', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeSession({ pid: 7105, pipeLive: true });
try {
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
ctx.currentClient().fireLogin('10001');
ctx.session.onPipeDown();
await flush();
ctx.session.onPipeDown();
await flush();
ctx.session.notifyProcessGone();
await flush();
const messages = sessionTrace(entries).map((entry) => entry.message);
expect(messages.filter(
(message) => message.startsWith('hook_session_login_terminal pid=7105 '),
)).toHaveLength(1);
expect(messages.filter(
(message) => message.startsWith('hook_session_disconnect_terminal pid=7105 '),
)).toHaveLength(1);
expect(messages.filter(
(message) => message.startsWith('hook_session_process_terminal pid=7105 '),
)).toHaveLength(1);
expect(messages).toEqual(expect.arrayContaining([
expect.stringMatching(/^hook_session_login_terminal pid=7105 outcome=completed reason=login_detected previousUin="0" uin="10001" state=.*elapsedMs=\d+$/),
expect.stringMatching(/^hook_session_disconnect_terminal pid=7105 outcome=completed reason=pipe_down wasLoggedIn=true state=.*elapsedMs=\d+$/),
expect.stringMatching(/^hook_session_process_terminal pid=7105 outcome=completed reason=process_gone wasLoggedIn=false state=.*elapsedMs=\d+$/),
]));
} finally {
unsubscribe();
ctx.session.dispose();
}
});
it('records failed terminals when lifecycle listeners throw', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const login = makeSession({ pid: 7107, pipeLive: true });
const disconnect = makeSession({ pid: 7108, pipeLive: true });
const processGone = makeSession({ pid: 7109, pipeLive: true });
try {
await login.session.load();
login.session.onPipeUp();
await flush();
login.session.on('login', () => { throw new Error('login listener boom'); });
expect(() => login.currentClient().fireLogin('10001')).toThrow('login listener boom');
await disconnect.session.load();
disconnect.session.onPipeUp();
await flush();
disconnect.currentClient().fireLogin('10002');
disconnect.session.on('disconnected', () => { throw new Error('disconnect listener boom'); });
disconnect.session.onPipeDown();
await flush();
processGone.session.on('disposed', () => { throw new Error('dispose listener boom'); });
processGone.session.notifyProcessGone();
await flush();
const messages = sessionTrace(entries).map((entry) => entry.message);
expect(messages.filter((message) =>
message.startsWith('hook_session_login_terminal pid=7107 '))).toEqual([
expect.stringMatching(/^hook_session_login_terminal pid=7107 outcome=failed reason=listener_failed error="login listener boom" state=.*elapsedMs=\d+$/),
]);
expect(messages.filter((message) =>
message.startsWith('hook_session_disconnect_terminal pid=7108 '))).toEqual([
expect.stringMatching(/^hook_session_disconnect_terminal pid=7108 outcome=failed reason=listener_failed error="disconnect listener boom" state=.*elapsedMs=\d+$/),
]);
expect(messages.filter((message) =>
message.startsWith('hook_session_process_terminal pid=7109 '))).toEqual([
expect.stringMatching(/^hook_session_process_terminal pid=7109 outcome=failed reason=listener_failed error="dispose listener boom" state=.*elapsedMs=\d+$/),
]);
} finally {
unsubscribe();
login.session.dispose();
disconnect.session.dispose();
processGone.session.dispose();
}
});
it('records unload verification failure as a failed terminal', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeSession({ pid: 7106, pipeLive: false });
try {
await ctx.session.load();
ctx.setPipeLive(true);
await ctx.session.unload();
const terminals = sessionTrace(entries).filter(
(entry) => entry.message.startsWith('hook_session_terminal pid=7106 operation=unload '),
);
expect(terminals).toHaveLength(1);
expect(terminals[0]!.message).toMatch(
/^hook_session_terminal pid=7106 operation=unload outcome=failed reason=unload_verification_failed error=.*state=.*elapsedMs=\d+$/,
);
} finally {
unsubscribe();
}
});
});
describe('HookSession — load', () => {
it('with no live pipe: injects, status → connecting, method from inject result', async () => {
const { session, injector } = makeSession({ pipeLive: false });
@@ -102,6 +335,33 @@ describe('HookSession — load', () => {
expect(info.status).toBe('connecting');
});
it('keeps loading pending until asynchronous component loading completes', async () => {
let finishLoading!: (result: { method: 'loadModuleManual'; handle: ManualMapHandle }) => void;
const loading = new Promise<{ method: 'loadModuleManual'; handle: ManualMapHandle }>(resolve => {
finishLoading = resolve;
});
const injector = {
inject: vi.fn(() => loading),
unload: vi.fn(),
};
const session = new HookSession(1234, {
injector,
makeClient: () => new FakeClient() as unknown as QqHookClient,
pipeWatcher: { isPipeLive: () => false },
});
const load = session.load();
await flush();
expect(session.status).toBe('loading');
finishLoading({ method: 'loadModuleManual', handle: DUMMY_HANDLE });
await expect(load).resolves.toMatchObject({
status: 'connecting',
method: 'loadModuleManual',
injected: true,
});
});
it('inject failure → status error, error message captured', async () => {
const injector = {
inject: vi.fn(() => { throw new Error('inject boom'); }),
@@ -116,6 +376,37 @@ describe('HookSession — load', () => {
expect(info.status).toBe('error');
expect(info.error).toBe('inject boom');
});
it('can retry after asynchronous component loading fails', async () => {
const injector = {
inject: vi
.fn()
.mockRejectedValueOnce(new Error('component loading timed out'))
.mockResolvedValueOnce({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
}),
unload: vi.fn(),
};
const session = new HookSession(1234, {
injector,
makeClient: () => new FakeClient() as unknown as QqHookClient,
pipeWatcher: { isPipeLive: () => false },
});
await expect(session.load()).resolves.toMatchObject({
status: 'error',
error: 'component loading timed out',
injected: false,
});
await expect(session.load()).resolves.toMatchObject({
status: 'connecting',
method: 'loadModuleManual',
injected: true,
error: '',
});
expect(injector.inject).toHaveBeenCalledTimes(2);
});
});
describe('HookSession — pipe up/down → connect lifecycle', () => {
@@ -353,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
@@ -541,13 +866,42 @@ describe('HookSession — packet forwarding', () => {
});
describe('HookSession — login reconcile (Docker auto-login safety net)', () => {
it('reconciles login via the active probe when the pushed frame is missed', async () => {
// Probe reports logged-in; the FakeClient never fires a loginState frame
// (the missed-edge Docker case). The immediate reconcile probe must detect
// it and emit "login".
it('keeps the packet sender usable only after native readiness confirms the identity hint', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }),
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
nativeReadyOnIdentityHint: true,
});
let sender: PacketSender | undefined;
ctx.session.on('login', (_uin: string, nextSender: PacketSender) => {
sender = nextSender;
});
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
await flush();
expect(sender).toBeDefined();
const result = await sender!.sendPacket('Test.LoginReady', Buffer.from('request'));
expect(result).toMatchObject({
success: true,
gotResponse: true,
errorCode: 0,
responseData: Buffer.from('reply'),
});
expect(ctx.currentClient().sentPackets).toEqual([
{ serviceCmd: 'Test.LoginReady', body: Buffer.from('request') },
]);
});
it('treats a port-probed account as an identity hint, not native login proof', async () => {
// Account identity does not prove request readiness. The bridge must wait
// for a login-state confirmation instead of synthesizing one.
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -555,18 +909,89 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); // connect (not logged in via frame) → starts reconcile
await flush(); // immediate probe resolves → handleLoginState
await flush(); // immediate probe resolves → forwards identity hint
expect(loginSpy).toHaveBeenCalledOnce();
expect(loginSpy.mock.calls[0]![0]).toBe('10001');
expect(ctx.session.status).toBe('online');
expect(ctx.session.uin).toBe('10001');
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
expect(loginSpy).not.toHaveBeenCalled();
expect(ctx.session.status).toBe('loaded');
expect(ctx.session.uin).toBe('0');
});
it('forwards the same identity at most once per pipe connection', async () => {
vi.useFakeTimers();
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
});
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
await vi.advanceTimersByTimeAsync(9000);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
} finally {
ctx.session.dispose();
vi.useRealTimers();
}
});
it('keeps observing identity after acknowledgement and forwards an account change', async () => {
vi.useFakeTimers();
let uin = '10001';
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin, identityKnown: true }),
});
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
uin = '20002';
await vi.advanceTimersByTimeAsync(29_999);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
await vi.advanceTimersByTimeAsync(1);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '20002']);
} finally {
ctx.session.dispose();
vi.useRealTimers();
}
});
it('retries identity forwarding failures with a strict bound', async () => {
vi.useFakeTimers();
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
identityHintFailures: 3,
});
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
await vi.advanceTimersByTimeAsync(3000);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001']);
await vi.advanceTimersByTimeAsync(9000);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001', '10001']);
await vi.advanceTimersByTimeAsync(30_000);
expect(ctx.currentClient().loginIdentityHints).toHaveLength(3);
} finally {
ctx.session.dispose();
vi.useRealTimers();
}
});
it('does not log in when the probe reports not-logged-in', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 0, uin: '', loggedIn: false }),
probeLogin: async () => ({ port: 0, uin: '', identityKnown: false }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -581,7 +1006,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
it('ignores a probe with a non-real uin (0)', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '0', loggedIn: true }),
probeLogin: async () => ({ port: 4301, uin: '0', identityKnown: true }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -610,10 +1035,11 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
it('detects a login that lands on a LATER interval probe', async () => {
vi.useFakeTimers();
try {
let loggedIn = false;
let identityKnown = false;
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn }),
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown }),
nativeReadyOnIdentityHint: true,
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -623,7 +1049,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (not logged in yet)
expect(loginSpy).not.toHaveBeenCalled();
loggedIn = true; // QQ finishes auto-login
identityKnown = true; // QQ exposes the restored identity
await vi.advanceTimersByTimeAsync(3000); // next interval probe picks it up
expect(loginSpy).toHaveBeenCalledOnce();
@@ -636,7 +1062,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
it('does not double-emit when the pushed frame logs in first', async () => {
// Pushed-frame login wins; a subsequent probe with the same uin must not
// re-emit (handleLoginState dedups), and the reconcile timer is stopped.
const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', loggedIn: true }));
const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', identityKnown: true }));
const ctx = makeSession({ pipeLive: true, probeLogin });
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -676,6 +1102,39 @@ describe('HookSession — end-to-end receive health (#233)', () => {
ctx.currentClient().firePacket({ seq, error: 0, cmd, uin, body: Buffer.alloc(0) });
}
it('reports native outbound loss as unhealthy and recovers on the next successful request', async () => {
const { ctx, healthChanges } = await startReceiveSession();
let sender: PacketSender | undefined;
ctx.session.on('login', (_uin: string, nextSender: PacketSender) => {
sender = nextSender;
});
try {
// Re-emit on a new account epoch so the test captures the session sender.
ctx.currentClient().fireLogin('20002');
ctx.currentClient().sendError = new HookPipeRequestError(
'The QQ connection changed. Please restart QQ and try again.',
PIPE_STATUS_CONNECTION_UNAVAILABLE,
1,
);
await sender!.sendPacket('Test.Command', Buffer.alloc(0));
expect(ctx.session.receiveHealthy).toBe(false);
expect(healthChanges).toEqual([false]);
// Incoming traffic alone must not conceal a still-broken send path.
firePacket(ctx, HEARTBEAT_CMD, '20002');
expect(ctx.session.receiveHealthy).toBe(false);
ctx.currentClient().sendError = null;
await sender!.sendPacket('Test.Command', Buffer.alloc(0));
expect(ctx.session.receiveHealthy).toBe(true);
expect(healthChanges).toEqual([false, true]);
} finally {
ctx.session.dispose();
}
});
it('becomes unhealthy only after an observed QQ heartbeat stays silent, then recovers on the next packet', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
const { ctx, healthChanges } = await startReceiveSession();
+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);
});
});
@@ -30,6 +30,27 @@ function captureEvents(watcher: PipeWatcher): EventRow[] {
}
describe('PipeWatcher', () => {
it('passes the current process snapshot to pipe discovery', async () => {
const processes = [
{ pid: 1234, name: 'qq', path: '/opt/QQ/qq' },
{ pid: 5678, name: 'qq', path: '/opt/QQ/qq' },
];
let observed: readonly HookProcessBaseInfo[] | undefined;
const watcher = new PipeWatcher({
listProcesses: () => processes,
listLivePipes: async current => {
observed = current;
return new Set();
},
intervalMs: 60_000,
});
await watcher.start();
expect(observed).toEqual(processes);
watcher.stop();
});
it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
@@ -193,6 +214,38 @@ describe('PipeWatcher', () => {
watcher.stop();
});
it('preserves live sessions when pipe discovery temporarily fails', async () => {
let processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
let failPipeDiscovery = false;
const watcher = new PipeWatcher({
listProcesses: () => processes,
listLivePipes: async () => {
if (failPipeDiscovery) throw new Error('permission denied');
return new Set([1234]);
},
intervalMs: 60_000,
});
await watcher.start();
expect(watcher.isPipeLive(1234)).toBe(true);
const events = captureEvents(watcher);
failPipeDiscovery = true;
await watcher.tickNow();
expect(events).toEqual([]);
expect(watcher.isProcessAlive(1234)).toBe(true);
expect(watcher.isPipeLive(1234)).toBe(true);
processes = [];
await watcher.tickNow();
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
expect(watcher.isProcessAlive(1234)).toBe(false);
expect(watcher.isPipeLive(1234)).toBe(false);
watcher.stop();
});
it('UNKNOWN (null) enumeration keeps prior state — no false process-gone (issue #158)', async () => {
let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }];
let live = new Set<number>([1234]);
+771 -18
View File
@@ -2,17 +2,123 @@ import net from 'net';
import { mkdtemp, rm, writeFile } from 'fs/promises';
import os from 'os';
import path from 'path';
import { Duplex } from 'stream';
import {
currentRequestId,
getLogLevel,
runWithRequestId,
setLogLevel,
subscribeLogs,
type LogEntry,
} from '@snowluma/common/logger';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { listLiveLinuxPipePids, QqHookClient } from '../src/qq-hook-client';
import {
HEADER_SIZE,
listLiveLinuxPipePids,
MAX_PIPE_BODY_BYTES,
MAX_PIPE_CMD_BYTES,
MAX_PIPE_MSG_BYTES,
PIPE_MAGIC,
PIPE_VERSION,
PipeOp,
QqHookClient,
} from '../src/qq-hook-client';
let tmpDir: string | null = null;
const previousLogLevel = getLogLevel();
async function makeRuntimeDir(): Promise<string> {
tmpDir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-hook-'));
return tmpDir;
}
function pipeFrame({
op,
requestId = 0,
status = 0,
value0 = 0n,
cmd = '',
message = '',
body = Buffer.alloc(0),
}: {
op: PipeOp;
requestId?: number;
status?: number;
value0?: bigint;
cmd?: string;
message?: string;
body?: Buffer;
}): Buffer {
const cmdBytes = Buffer.from(cmd);
const messageBytes = Buffer.from(message);
const header = Buffer.alloc(HEADER_SIZE);
header.writeUInt32LE(PIPE_MAGIC, 0);
header.writeUInt16LE(PIPE_VERSION, 4);
header.writeUInt16LE(op, 6);
header.writeUInt32LE(requestId, 8);
header.writeInt32LE(status, 12);
header.writeUInt32LE(cmdBytes.length, 20);
header.writeUInt32LE(messageBytes.length, 24);
header.writeUInt32LE(body.length, 28);
header.writeBigUInt64LE(value0, 32);
return Buffer.concat([header, cmdBytes, messageBytes, body]);
}
function readSendFrame(payload: Buffer): {
requestId: number;
cmd: string;
body: Buffer;
} {
const cmdLength = payload.readUInt32LE(20);
const messageLength = payload.readUInt32LE(24);
const bodyLength = payload.readUInt32LE(28);
const cmdStart = HEADER_SIZE;
const bodyStart = cmdStart + cmdLength + messageLength;
return {
requestId: payload.readUInt32LE(8),
cmd: payload.subarray(cmdStart, cmdStart + cmdLength).toString(),
body: Buffer.from(payload.subarray(bodyStart, bodyStart + bodyLength)),
};
}
function mockControlPipe(
pid: number,
onWrite: (socket: net.Socket, payload: Buffer) => void,
): ReturnType<typeof vi.spyOn> {
return vi.spyOn(net, 'createConnection').mockImplementation((() => {
const socket = new Duplex({
read() { /* peer data is injected with emit('data') */ },
write(chunk, _encoding, callback) {
onWrite(socket, Buffer.from(chunk));
callback();
},
}) as net.Socket;
queueMicrotask(() => {
socket.emit('connect');
queueMicrotask(() => socket.emit('data', pipeFrame({
op: PipeOp.hello,
value0: BigInt(pid),
})));
});
return socket;
}) as typeof net.createConnection);
}
function traceMessages(entries: LogEntry[]): string[] {
return entries
.filter((entry) => entry.level === 'trace' && entry.scope === 'QQHook.Packet')
.map((entry) => entry.message);
}
function runtimeTrace(entries: LogEntry[]): LogEntry[] {
return entries.filter(
(entry) => entry.level === 'trace' && entry.scope === 'QQHook.Runtime',
);
}
afterEach(async () => {
setLogLevel(previousLogLevel);
vi.restoreAllMocks();
if (!tmpDir) return;
await rm(tmpDir, { recursive: true, force: true });
tmpDir = null;
@@ -44,7 +150,648 @@ describe('listLiveLinuxPipePids', () => {
});
});
describe.skipIf(process.platform === 'win32')('QqHookClient — pipe close mid-send', () => {
describe('QqHookClient — pipe frame limits', () => {
it('forwards a probed account as a native identity hint without changing login state', async () => {
const pid = 778819;
const writes: Buffer[] = [];
const connection = mockControlPipe(pid, (socket, payload) => {
writes.push(Buffer.from(payload));
const requestId = payload.readUInt32LE(8);
queueMicrotask(() => socket.emit('data', pipeFrame({
op: PipeOp.sendAck,
requestId,
})));
});
const client = new QqHookClient(pid);
try {
await client.reconcileLoginIdentity('10001');
expect(writes).toHaveLength(1);
expect(writes[0]!.readUInt16LE(6)).toBe(PipeOp.loginIdentityHint);
expect(writes[0]!.readBigUInt64LE(32)).toBe(10001n);
expect(client.getLoginState()).toEqual({
loggedIn: false,
uin: '0',
uinNumber: 0n,
});
} finally {
client.close();
connection.mockRestore();
}
});
it.each([
['command', 20, MAX_PIPE_CMD_BYTES],
['message', 24, MAX_PIPE_MSG_BYTES],
['body', 28, MAX_PIPE_BODY_BYTES],
] as const)(
'rejects an oversized inbound %s before waiting for its payload',
async (name, lengthOffset, limit) => {
const pid = 778830;
let socket: net.Socket | null = null;
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
socket = new Duplex({ read() { /* peer data is injected with emit('data') */ } }) as net.Socket;
queueMicrotask(() => {
socket!.emit('connect');
const header = Buffer.alloc(HEADER_SIZE);
header.writeUInt32LE(PIPE_MAGIC, 0);
header.writeUInt16LE(PIPE_VERSION, 4);
header.writeUInt16LE(PipeOp.hello, 6);
header.writeUInt32LE(limit + 1, lengthOffset);
socket!.emit('data', header);
});
return socket;
}) as typeof net.createConnection);
const client = new QqHookClient(pid);
const connecting = client.connect().catch(() => undefined);
try {
const error = await new Promise<Error>((resolve, reject) => {
const timer = setTimeout(
() => reject(new Error('oversized frame was not rejected')),
100,
);
client.once('error', (reason: unknown) => {
clearTimeout(timer);
resolve(reason instanceof Error ? reason : new Error(String(reason)));
});
});
expect(error.message).toBe(
`pipe frame ${name} length ${limit + 1} exceeds limit ${limit}`,
);
expect(socket?.destroyed).toBe(true);
} finally {
client.close();
await connecting;
createConnection.mockRestore();
}
});
it('rejects an oversized outbound command before writing to the pipe', async () => {
const pid = 778831;
const onWrite = vi.fn();
const connection = mockControlPipe(pid, onWrite);
const client = new QqHookClient(pid);
try {
await client.connect();
await expect(client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES + 1), Buffer.alloc(0), {
ackTimeoutMs: 25,
})).rejects.toThrow(
`pipe frame command length ${MAX_PIPE_CMD_BYTES + 1} exceeds limit ${MAX_PIPE_CMD_BYTES}`,
);
expect(onWrite).not.toHaveBeenCalled();
} finally {
client.close();
connection.mockRestore();
}
});
it('rejects an oversized outbound body before writing to the pipe', async () => {
const pid = 778832;
const onWrite = vi.fn();
const connection = mockControlPipe(pid, onWrite);
const client = new QqHookClient(pid);
try {
await client.connect();
await expect(client.sendNoReply(
'test.command',
Buffer.alloc(MAX_PIPE_BODY_BYTES + 1),
)).rejects.toThrow(
`pipe frame body length ${MAX_PIPE_BODY_BYTES + 1} exceeds limit ${MAX_PIPE_BODY_BYTES}`,
);
expect(onWrite).not.toHaveBeenCalled();
} finally {
client.close();
connection.mockRestore();
}
});
it('accepts values exactly at the command limit', async () => {
const pid = 778833;
const connection = mockControlPipe(pid, (socket, payload) => {
const requestId = payload.readUInt32LE(8);
queueMicrotask(() => socket.emit('data', pipeFrame({
op: PipeOp.sendAck,
requestId,
})));
});
const client = new QqHookClient(pid);
try {
await expect(client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES), Buffer.alloc(0)))
.resolves.toMatchObject({ requestId: 1 });
} finally {
client.close();
connection.mockRestore();
}
});
it('parses fragmented and coalesced frames without losing boundaries', async () => {
const pid = 778834;
const states: string[] = [];
const wire = Buffer.concat([
pipeFrame({ op: PipeOp.hello, value0: BigInt(pid), message: 'control' }),
pipeFrame({ op: PipeOp.loginState, status: 1, value0: 10001n, message: '10001' }),
pipeFrame({ op: PipeOp.loginState, status: 1, value0: 10002n, message: '10002' }),
]);
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
const socket = new Duplex({ read() { /* peer data is injected with emit('data') */ } }) as net.Socket;
queueMicrotask(() => {
socket.emit('connect');
queueMicrotask(() => {
const cuts = [1, 7, 39, 40, 44, 83, wire.length - 1, wire.length];
let offset = 0;
for (const end of cuts) {
if (end > offset) socket.emit('data', wire.subarray(offset, end));
offset = end;
}
});
});
return socket;
}) as typeof net.createConnection);
const client = new QqHookClient(pid);
client.on('loginState', state => states.push(state.uin));
try {
const hello = await client.connect();
expect(hello).toMatchObject({ pipeName: 'control', pid });
expect(states).toEqual(['10001', '10002']);
} finally {
client.close();
createConnection.mockRestore();
}
});
it('accepts an inbound message exactly at the native limit', async () => {
const pid = 778835;
const message = 'x'.repeat(MAX_PIPE_MSG_BYTES);
const frame = pipeFrame({ op: PipeOp.hello, value0: BigInt(pid), message });
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
const socket = new Duplex({ read() { /* peer data is injected with emit('data') */ } }) as net.Socket;
queueMicrotask(() => {
socket.emit('connect');
queueMicrotask(() => {
for (let offset = 0; offset < frame.length; offset += 1024) {
socket.emit('data', frame.subarray(offset, offset + 1024));
}
});
});
return socket;
}) as typeof net.createConnection);
const client = new QqHookClient(pid);
try {
await expect(client.connect()).resolves.toMatchObject({ pipeName: message, pid });
} finally {
client.close();
createConnection.mockRestore();
}
});
});
describe('QqHookClient — runtime TRACE', () => {
it('records control and receive pipe hello lifecycles under the parent request', async () => {
const pid = 778820;
const entries: LogEntry[] = [];
let connectionIndex = 0;
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
const kind = connectionIndex === 0 ? 'control' : 'recv';
connectionIndex += 1;
const socket = new Duplex({
read() { /* peer data is injected with emit('data') */ },
}) as net.Socket;
queueMicrotask(() => {
socket.emit('connect');
queueMicrotask(() => socket.emit('data', pipeFrame({
op: PipeOp.hello,
value0: BigInt(pid),
message: `${kind}-fixture`,
})));
});
return socket;
}) as typeof net.createConnection);
const client = new QqHookClient(pid);
try {
await runWithRequestId(4201, () => client.connectAll());
const trace = runtimeTrace(entries);
expect(trace).toHaveLength(6);
expect(trace.every((entry) => entry.req === 4201)).toBe(true);
expect(trace.map((entry) => entry.message)).toEqual([
expect.stringMatching(/^hook_pipe_start pid=778820 kind=control pipeName=.*$/),
expect.stringMatching(/^hook_pipe_branch pid=778820 kind=control branch=socket_connected$/),
expect.stringMatching(/^hook_pipe_terminal pid=778820 kind=control outcome=completed reason=hello_received hello=\{pipeName:"control-fixture",pid:778820,recvPipe:false\} elapsedMs=\d+$/),
expect.stringMatching(/^hook_pipe_start pid=778820 kind=recv pipeName=.*$/),
expect.stringMatching(/^hook_pipe_branch pid=778820 kind=recv branch=socket_connected$/),
expect.stringMatching(/^hook_pipe_terminal pid=778820 kind=recv outcome=completed reason=hello_received hello=\{pipeName:"recv-fixture",pid:778820,recvPipe:true\} elapsedMs=\d+$/),
]);
} finally {
unsubscribe();
client.close();
createConnection.mockRestore();
}
});
it('records a pre-request connection failure without a pipe request id', async () => {
const pid = 778821;
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
const socket = new Duplex({ read() { /* no peer */ } }) as net.Socket;
queueMicrotask(() => socket.emit('error', new Error('fixture connect failure')));
return socket;
}) as typeof net.createConnection);
const client = new QqHookClient(pid);
try {
await expect(client.connect()).rejects.toThrow('fixture connect failure');
const trace = runtimeTrace(entries);
expect(trace).toHaveLength(2);
expect(trace.every((entry) => entry.req !== undefined)).toBe(true);
expect(trace[0]!.req).toBe(trace[1]!.req);
expect(trace.map((entry) => entry.message)).toEqual([
expect.stringMatching(/^hook_pipe_start pid=778821 kind=control pipeName=.*$/),
expect.stringMatching(/^hook_pipe_terminal pid=778821 kind=control outcome=failed reason=connect_failed error="fixture connect failure" elapsedMs=\d+$/),
]);
expect(trace.map((entry) => entry.message).join('\n')).not.toContain('requestId=');
} finally {
unsubscribe();
client.close();
createConnection.mockRestore();
}
});
it('assigns fresh request contexts to material login and close events only', async () => {
const pid = 778822;
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const connection = mockControlPipe(pid, () => { /* no packet writes */ });
const client = new QqHookClient(pid);
const eventRequestIds: Array<{ event: 'login' | 'close'; req: number | undefined }> = [];
client.on('loginState', () => {
eventRequestIds.push({ event: 'login', req: currentRequestId() });
});
client.on('close', () => {
eventRequestIds.push({ event: 'close', req: currentRequestId() });
});
try {
await runWithRequestId(4202, () => client.connect());
const controlSocket = connection.mock.results[0]!.value as net.Socket;
controlSocket.emit('data', pipeFrame({
op: PipeOp.loginState,
status: 1,
value0: 123456n,
message: '123456',
}));
controlSocket.emit('data', pipeFrame({
op: PipeOp.loginState,
status: 1,
value0: 123456n,
message: '123456',
}));
controlSocket.destroy();
await new Promise<void>((resolve) => setImmediate(resolve));
const facts = runtimeTrace(entries).filter(
(entry) => entry.message.startsWith('hook_runtime_fact pid=778822 '),
);
expect(facts).toHaveLength(2);
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
expect(facts[0]!.req).not.toBe(facts[1]!.req);
expect(facts.map((entry) => entry.message)).toEqual([
'hook_runtime_fact pid=778822 event=login_state_changed previousLoggedIn=false previousUin="0" loggedIn=true uin="123456"',
'hook_runtime_fact pid=778822 event=pipe_closed kind=control loggedIn=true uin="123456"',
]);
expect(eventRequestIds).toEqual([
{ event: 'login', req: facts[0]!.req },
{ event: 'login', req: undefined },
{ event: 'close', req: facts[1]!.req },
]);
} finally {
unsubscribe();
client.close();
connection.mockRestore();
}
});
});
describe('QqHookClient — packet TRACE', () => {
it('records complete request and reply bodies with the real pipe request id', async () => {
const pid = 778810;
const requestBody = Buffer.from([
0x00, 0xff, ...Array.from({ length: 160 }, (_, index) => index & 0xff),
]);
const replyBody = Buffer.from([0xff, 0x00, 0x7f]);
const entries: LogEntry[] = [];
const writes: Buffer[] = [];
let traceCountAtWrite = 0;
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const connection = mockControlPipe(pid, (socket, payload) => {
const frame = readSendFrame(payload);
writes.push(payload);
traceCountAtWrite = traceMessages(entries).length;
queueMicrotask(() => {
socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId: frame.requestId }));
socket.emit('data', pipeFrame({
op: PipeOp.sendReply,
requestId: frame.requestId,
status: 27,
message: 'fixture reply',
body: replyBody,
}));
});
});
const client = new QqHookClient(pid);
try {
const reply = await runWithRequestId(
4101,
() => client.sendAndWait('OidbSvcTrpcTcp.0x1234_1', requestBody),
);
const sent = readSendFrame(writes[0]);
expect(sent).toMatchObject({
requestId: 1,
cmd: 'OidbSvcTrpcTcp.0x1234_1',
body: requestBody,
});
expect(reply).toMatchObject({
requestId: 1,
error: 27,
message: 'fixture reply',
body: replyBody,
});
expect(traceCountAtWrite).toBe(1);
expect(entries.filter((entry) => entry.scope === 'QQHook.Packet'))
.toEqual(expect.arrayContaining([
expect.objectContaining({
req: 4101,
message: `packet_send serviceCmd="OidbSvcTrpcTcp.0x1234_1" requestId=1 length=${requestBody.length} body=${requestBody.toString('hex')}`,
}),
expect.objectContaining({
req: 4101,
message: `packet_recv serviceCmd="OidbSvcTrpcTcp.0x1234_1" requestId=1 error=27 message="fixture reply" length=${replyBody.length} body=${replyBody.toString('hex')}`,
}),
expect.objectContaining({
req: 4101,
message: expect.stringMatching(/^packet_terminal serviceCmd="OidbSvcTrpcTcp\.0x1234_1" requestId=1 outcome=failed reason=reply_error error=27 elapsedMs=\d+$/),
}),
]));
for (const message of traceMessages(entries)) expect(message).not.toContain('...');
} finally {
unsubscribe();
client.close();
connection.mockRestore();
}
});
it('records empty request and reply bodies exactly', async () => {
const pid = 778811;
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const connection = mockControlPipe(pid, (socket, payload) => {
const { requestId } = readSendFrame(payload);
queueMicrotask(() => {
socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId }));
socket.emit('data', pipeFrame({ op: PipeOp.sendReply, requestId }));
});
});
const client = new QqHookClient(pid);
try {
await client.sendAndWait('Empty.Command', Buffer.alloc(0));
expect(traceMessages(entries)).toEqual([
'packet_send serviceCmd="Empty.Command" requestId=1 length=0 body=',
'packet_recv serviceCmd="Empty.Command" requestId=1 error=0 message="" length=0 body=',
expect.stringMatching(/^packet_terminal serviceCmd="Empty\.Command" requestId=1 outcome=ok reason=reply_received error=0 elapsedMs=\d+$/),
]);
} finally {
unsubscribe();
client.close();
connection.mockRestore();
}
});
it('records no-reply acknowledgement as the terminal outcome', async () => {
const pid = 778812;
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const connection = mockControlPipe(pid, (socket, payload) => {
const { requestId } = readSendFrame(payload);
queueMicrotask(() => {
socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId }));
});
});
const client = new QqHookClient(pid);
try {
await client.sendNoReply('NoReply.Command', Buffer.from([0x00, 0xff]));
expect(traceMessages(entries)).toEqual([
'packet_send serviceCmd="NoReply.Command" requestId=1 length=2 body=00ff',
expect.stringMatching(/^packet_terminal serviceCmd="NoReply\.Command" requestId=1 outcome=ok reason=ack_received elapsedMs=\d+$/),
]);
} finally {
unsubscribe();
client.close();
connection.mockRestore();
}
});
it('records reply timeout and transport failure with their real request ids', async () => {
vi.useFakeTimers();
const pid = 778813;
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
let writeCount = 0;
const connection = mockControlPipe(pid, (socket, payload) => {
const { requestId } = readSendFrame(payload);
writeCount += 1;
if (writeCount === 1) {
queueMicrotask(() => {
socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId }));
});
return;
}
queueMicrotask(() => socket.destroy());
});
const client = new QqHookClient(pid);
client.on('error', () => { /* expected transport failure */ });
try {
const timedOut = client.sendAndWait('Timeout.Command', Buffer.from([0xff]), {
ackTimeoutMs: 50,
replyTimeoutMs: 50,
});
const timedOutOutcome = timedOut.then(
() => null,
(error: unknown) => error,
);
await vi.advanceTimersByTimeAsync(50);
const timeoutError = await timedOutOutcome;
expect(timeoutError).toBeInstanceOf(Error);
expect((timeoutError as Error).message).toBe('send reply 1 timed out after 50 ms');
const failed = client.sendAndWait('Closed.Command', Buffer.from([0x00]), {
ackTimeoutMs: 50,
replyTimeoutMs: 50,
});
await expect(failed).rejects.toThrow('control pipe closed');
expect(traceMessages(entries)).toEqual(expect.arrayContaining([
expect.stringMatching(/^packet_terminal serviceCmd="Timeout\.Command" requestId=1 outcome=timeout reason=reply_timeout error="send reply 1 timed out after 50 ms" elapsedMs=\d+$/),
expect.stringMatching(/^packet_terminal serviceCmd="Closed\.Command" requestId=2 outcome=failed reason=transport_failure error="control pipe closed" elapsedMs=\d+$/),
]));
} finally {
unsubscribe();
client.close();
connection.mockRestore();
vi.useRealTimers();
}
});
it('classifies acknowledgement timeout and pipe request failure', async () => {
vi.useFakeTimers();
const pid = 778815;
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
let writeCount = 0;
const connection = mockControlPipe(pid, (socket, payload) => {
const { requestId } = readSendFrame(payload);
writeCount += 1;
if (writeCount === 2) {
queueMicrotask(() => socket.emit('data', pipeFrame({
op: PipeOp.error,
requestId,
status: 12,
message: 'send ack 2 timed out after 25 ms',
})));
}
});
const client = new QqHookClient(pid);
try {
const timedOut = client.sendNoReply('Ack.Timeout', Buffer.from([0x00]), {
ackTimeoutMs: 25,
});
const timedOutOutcome = timedOut.then(
() => null,
(error: unknown) => error,
);
await vi.advanceTimersByTimeAsync(25);
expect(await timedOutOutcome).toMatchObject({
message: 'send ack 1 timed out after 25 ms',
});
const requestError = await client.sendAndWait(
'Pipe.Error',
Buffer.from([0xff]),
).then(
() => null,
(error: unknown) => error,
);
expect(requestError).toMatchObject({
name: 'HookPipeRequestError',
message: 'send ack 2 timed out after 25 ms',
status: 12,
requestId: 2,
});
expect(traceMessages(entries)).toEqual(expect.arrayContaining([
expect.stringMatching(/^packet_terminal serviceCmd="Ack\.Timeout" requestId=1 outcome=timeout reason=ack_timeout error="send ack 1 timed out after 25 ms" elapsedMs=\d+$/),
expect.stringMatching(/^packet_terminal serviceCmd="Pipe\.Error" requestId=2 outcome=failed reason=request_failed error="send ack 2 timed out after 25 ms" elapsedMs=\d+$/),
]));
} finally {
unsubscribe();
client.close();
connection.mockRestore();
vi.useRealTimers();
}
});
it('keeps concurrent packet records atomic with distinct real request ids', async () => {
const pid = 778816;
const entries: LogEntry[] = [];
const writes: Array<ReturnType<typeof readSendFrame>> = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const connection = mockControlPipe(pid, (socket, payload) => {
writes.push(readSendFrame(payload));
if (writes.length !== 2) return;
queueMicrotask(() => {
for (const frame of [...writes].reverse()) {
socket.emit('data', pipeFrame({
op: PipeOp.sendAck,
requestId: frame.requestId,
}));
socket.emit('data', pipeFrame({
op: PipeOp.sendReply,
requestId: frame.requestId,
body: Buffer.from(frame.body).reverse(),
}));
}
});
});
const client = new QqHookClient(pid);
const firstBody = Buffer.from([0x00, 0xff]);
const secondBody = Buffer.from(
Array.from({ length: 160 }, (_, index) => index & 0xff),
);
try {
const [first, second] = await Promise.all([
client.sendAndWait('First\nCommand', firstBody),
client.sendAndWait('Second.Command', secondBody),
]);
expect([first.requestId, second.requestId]).toEqual([1, 2]);
expect(writes.map((frame) => frame.requestId)).toEqual([1, 2]);
const messages = traceMessages(entries);
expect(messages).toHaveLength(6);
expect(messages.every((message) => !message.includes('\n'))).toBe(true);
expect(messages).toEqual(expect.arrayContaining([
`packet_send serviceCmd="First\\nCommand" requestId=1 length=2 body=${firstBody.toString('hex')}`,
`packet_recv serviceCmd="First\\nCommand" requestId=1 error=0 message="" length=2 body=${Buffer.from(firstBody).reverse().toString('hex')}`,
`packet_send serviceCmd="Second.Command" requestId=2 length=${secondBody.length} body=${secondBody.toString('hex')}`,
`packet_recv serviceCmd="Second.Command" requestId=2 error=0 message="" length=${secondBody.length} body=${Buffer.from(secondBody).reverse().toString('hex')}`,
]));
expect(messages.filter((message) => message.startsWith('packet_terminal'))).toHaveLength(2);
} finally {
unsubscribe();
client.close();
connection.mockRestore();
}
});
it('does not evaluate packet TRACE producers while TRACE is disabled', async () => {
const pid = 778814;
setLogLevel('debug');
const byteLength = vi.spyOn(Buffer.prototype, 'toString');
const connection = mockControlPipe(pid, (socket, payload) => {
const { requestId } = readSendFrame(payload);
queueMicrotask(() => {
socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId }));
socket.emit('data', pipeFrame({ op: PipeOp.sendReply, requestId }));
});
});
const client = new QqHookClient(pid);
try {
await client.sendAndWait('Disabled.Command', Buffer.from([0x00, 0xff]));
expect(byteLength).not.toHaveBeenCalledWith('hex');
} finally {
client.close();
connection.mockRestore();
byteLength.mockRestore();
}
});
});
describe('QqHookClient — pipe close mid-send', () => {
// Regression: when the control pipe closes while a send() is awaiting its
// ack, rejectControlPending() rejects BOTH the ack and reply deferreds. The
// reply is only `await`ed after the ack, so if the ack rejects first the
@@ -54,10 +801,6 @@ describe.skipIf(process.platform === 'win32')('QqHookClient — pipe close mid-s
// guard on each deferred prevents it; without the guard this test trips the
// unhandledRejection assertion below.
it('does not raise an unhandled rejection', async () => {
const dir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-pipe-'));
const prevRuntimeDir = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
process.env.SNOWLUMA_HOOK_RUNTIME_DIR = dir;
const PID = 778899;
const helloFrame = (): Buffer => {
const h = Buffer.alloc(40);
@@ -69,10 +812,23 @@ describe.skipIf(process.platform === 'win32')('QqHookClient — pipe close mid-s
};
let controlConn: net.Socket | null = null;
const controlServer = net.createServer((sock) => { controlConn = sock; sock.write(helloFrame()); });
const recvServer = net.createServer((sock) => { sock.write(helloFrame()); });
await new Promise<void>((r) => controlServer.listen(path.join(dir, `mojo.${PID}.control.sock`), () => r()));
await new Promise<void>((r) => recvServer.listen(path.join(dir, `mojo.${PID}.recv.sock`), () => r()));
let signalControlWrite!: () => void;
const controlWriteStarted = new Promise<void>((resolve) => { signalControlWrite = resolve; });
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
const socket = new Duplex({
read() { /* peer data is injected with emit('data') */ },
write(_chunk, _encoding, callback) {
signalControlWrite();
callback();
},
}) as net.Socket;
controlConn = socket;
queueMicrotask(() => {
socket.emit('connect');
queueMicrotask(() => socket.emit('data', helloFrame()));
});
return socket;
}) as typeof net.createConnection);
const unhandled: unknown[] = [];
const onUnhandled = (reason: unknown): void => { unhandled.push(reason); };
@@ -81,28 +837,25 @@ describe.skipIf(process.platform === 'win32')('QqHookClient — pipe close mid-s
const client = new QqHookClient(PID);
client.on('error', () => { /* socket reset on destroy — ignore */ });
try {
await client.connectAll({ recv: true });
await client.connect();
// Start a reply-expecting send, let it reach the in-flight (awaiting-ack)
// state, then have the "hook" drop the pipe before it answers.
const sent = client.send('noop', null, { wantReply: true, ackTimeoutMs: 1000, replyTimeoutMs: 1000 })
.then(() => 'resolved' as const, (e: unknown) => e);
await new Promise((r) => setTimeout(r, 30));
await controlWriteStarted;
controlConn?.destroy();
const outcome = await sent;
await new Promise((r) => setTimeout(r, 50)); // let Node surface any unhandled rejection
await new Promise<void>((resolve) => setImmediate(resolve));
expect(outcome).toBeInstanceOf(Error);
expect((outcome as Error).message).toBe('control pipe closed');
expect(unhandled, `unhandled rejections leaked: ${unhandled.map(String).join(', ')}`).toHaveLength(0);
} finally {
process.off('unhandledRejection', onUnhandled);
client.close();
await new Promise<void>((r) => controlServer.close(() => r()));
await new Promise<void>((r) => recvServer.close(() => r()));
if (prevRuntimeDir === undefined) delete process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
else process.env.SNOWLUMA_HOOK_RUNTIME_DIR = prevRuntimeDir;
await rm(dir, { recursive: true, force: true });
createConnection.mockRestore();
}
});
});
@@ -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();
});
});
@@ -0,0 +1,63 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const execMock = vi.hoisted(() => vi.fn());
const socketCtorMock = vi.hoisted(() => vi.fn(function MockSocket() {
throw new Error('interactive QQ probe must not run');
}));
vi.mock('child_process', () => ({ exec: execMock }));
vi.mock('net', () => ({
default: { Socket: socketCtorMock },
Socket: socketCtorMock,
}));
import { probeQqLoginInfo } from '../src/qq-port-probe';
describe('probeQqLoginInfo — bounded execution', () => {
beforeEach(() => {
vi.useFakeTimers();
execMock.mockReset();
socketCtorMock.mockClear();
});
afterEach(() => {
vi.useRealTimers();
});
it('allows a later probe after a timed-out attempt', async () => {
execMock.mockImplementation(() => undefined);
const first = probeQqLoginInfo(4242);
await vi.advanceTimersByTimeAsync(10_000);
await expect(first).resolves.toBeNull();
execMock
.mockImplementationOnce((_command, _options, callback) => {
callback(null, { stdout: '', stderr: '' });
})
.mockImplementationOnce((_command, _options, callback) => {
callback(null, { stdout: '1\n', stderr: '' });
});
await expect(probeQqLoginInfo(4242)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
});
it('keeps background identity discovery passive', async () => {
execMock
.mockImplementationOnce((_command, _options, callback) => {
callback(null, {
stdout: 'LISTEN 0 128 127.0.0.1:9218 0.0.0.0:* users:(("qq",pid=4242,fd=12))\n',
stderr: '',
});
})
.mockImplementationOnce((_command, _options, callback) => {
callback(null, { stdout: '8\n', stderr: '' });
});
await expect(probeQqLoginInfo(4242)).resolves.toBeNull();
expect(socketCtorMock).not.toHaveBeenCalled();
});
});
+15 -2
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.12.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"
@@ -63,6 +67,10 @@
"./uin": {
"types": "./src/uin.ts",
"default": "./src/uin.ts"
},
"./access-token": {
"types": "./src/access-token.ts",
"default": "./src/access-token.ts"
}
},
"scripts": {
@@ -70,8 +78,13 @@
"test": "vitest run"
},
"devDependencies": {
"@types/node": "^24.12.2",
"@types/node": "catalog:",
"typescript": "catalog:",
"vitest": "^4.1.4"
},
"dependencies": {
"@zxcvbn-ts/core": "^4.1.2",
"@zxcvbn-ts/language-common": "^4.1.3",
"@zxcvbn-ts/language-en": "^4.1.1"
}
}
+58
View File
@@ -0,0 +1,58 @@
import { ZxcvbnFactory } from '@zxcvbn-ts/core';
import { adjacencyGraphs, dictionary } from '@zxcvbn-ts/language-common';
import { translations } from '@zxcvbn-ts/language-en';
export const ACCESS_TOKEN_MIN_LENGTH = 16;
export const ACCESS_TOKEN_MIN_SCORE = 3;
export type AccessTokenAssessmentReason =
| 'empty'
| 'too-short'
| 'guessable'
| 'acceptable';
export interface AccessTokenAssessment {
acceptable: boolean;
reason: AccessTokenAssessmentReason;
score: number;
}
const checker = new ZxcvbnFactory({
translations,
graphs: adjacencyGraphs,
dictionary,
});
function normalizeUserInputs(values: readonly (string | number)[]): Array<string | number> {
const unique = new Set<string | number>(['SnowLuma', 'OneBot']);
for (const value of values) {
if (typeof value === 'number') {
if (Number.isFinite(value)) unique.add(value);
continue;
}
const trimmed = value.trim();
if (trimmed) unique.add(trimmed.slice(0, 256));
}
return [...unique].slice(0, 24);
}
/**
* Evaluate a newly chosen OneBot access token against the shared product
* policy. Callers decide whether an empty token is permitted in their own
* trust context; an empty value is never considered strong here.
*/
export function assessAccessToken(
token: string,
userInputs: readonly (string | number)[] = [],
): AccessTokenAssessment {
if (!token) return { acceptable: false, reason: 'empty', score: 0 };
if (token.length < ACCESS_TOKEN_MIN_LENGTH) {
return { acceptable: false, reason: 'too-short', score: 0 };
}
const score = checker.check(token, normalizeUserInputs(userInputs)).score;
if (score < ACCESS_TOKEN_MIN_SCORE) {
return { acceptable: false, reason: 'guessable', score };
}
return { acceptable: true, reason: 'acceptable', score };
}
+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;
}
File diff suppressed because it is too large. Load diff
+246 -51
View File
@@ -1,7 +1,39 @@
const MAX_FIELD = 40;
const MAX_TOTAL = 200;
const SENSITIVE_SEGMENTS = new Set([
'authorization',
'cookie',
'credential',
'credentials',
'password',
'passwd',
'secret',
'token',
'apikey',
'privatekey',
'sessionkey',
]);
function valueRepr(v: unknown): string {
function isSensitiveKey(key: string): boolean {
const segments = key
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
.split(/[-_.\s]+/)
.filter(Boolean)
.map((segment) => segment.toLowerCase());
return segments.some((segment, index) => {
if (SENSITIVE_SEGMENTS.has(segment)) return true;
const next = segments[index + 1];
return next === 'key' && (
segment === 'api'
|| segment === 'private'
|| segment === 'session'
);
});
}
function valueRepr(v: unknown, key?: string): string {
if (key !== undefined && isSensitiveKey(key)) return '"***"';
if (v === null) return 'null';
if (v === undefined) return 'undefined';
switch (typeof v) {
@@ -31,83 +63,246 @@ export function summarizeParams(params: unknown): string {
if (params === null || params === undefined) return '{}';
if (typeof params !== 'object') {
const s = String(params);
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL)}...` : s;
return s.length > MAX_TOTAL
? `${s.slice(0, MAX_TOTAL - 3)}...`
: s;
}
if (Array.isArray(params)) return `[len=${params.length}]`;
const out: string[] = [];
let total = 0;
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
const entry = `${k}=${valueRepr(v)}`;
// +1 accounts for the separating space we'd insert when joining.
if (total > 0 && total + entry.length + 1 > MAX_TOTAL) {
out.push('...');
break;
const entry = `${k}=${valueRepr(v, k)}`;
const separatorLength = out.length > 0 ? 1 : 0;
if (total + separatorLength + entry.length > MAX_TOTAL) {
if (out.length === 0) {
return `${entry.slice(0, MAX_TOTAL - 3)}...`;
}
const rendered = out.join(' ');
return rendered.length + 4 <= MAX_TOTAL
? `${rendered} ...`
: `${rendered.slice(0, MAX_TOTAL - 3)}...`;
}
out.push(entry);
total += entry.length + (out.length > 1 ? 1 : 0);
total += separatorLength + entry.length;
}
return out.join(' ');
}
const VERBOSE_STRING_MAX = 200;
const VERBOSE_TOTAL_MAX = 1500;
// Keys whose values must never be rendered — tokens, passwords, secrets.
const REDACT_KEY = /^(.*[-_])?(token|password|passwd|secret|access[-_]?token)([-_].*)?$/i;
const ASSIGNMENT_START = /(^|[^A-Za-z0-9_-])(["']?)([-_]*(?=[A-Za-z0-9_.-]*[A-Za-z])[A-Za-z0-9][A-Za-z0-9_.-]*)\2(\s*[:=]\s*)/gi;
const AUTHORIZATION_BOUNDARY_SEGMENTS = new Set([
'authorization',
'cookie',
'password',
'passwd',
'secret',
'token',
'apikey',
'privatekey',
'sessionkey',
]);
function keySegments(key: string): string[] {
return key
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
.split(/[-_.\s]+/)
.filter(Boolean)
.map((segment) => segment.toLowerCase());
}
function isKeyKind(key: string, kind: 'authorization' | 'cookie'): boolean {
return keySegments(key).includes(kind);
}
function isAuthorizationBoundaryKey(key: string): boolean {
const segments = keySegments(key);
return segments.some((segment, index) => {
if (AUTHORIZATION_BOUNDARY_SEGMENTS.has(segment)) return true;
const next = segments[index + 1];
return next === 'key' && (
segment === 'api'
|| segment === 'private'
|| segment === 'session'
);
});
}
function quotedValueEnd(message: string, start: number): number | undefined {
const quote = message[start];
if (quote !== '"' && quote !== "'") return undefined;
for (let index = start + 1; index < message.length; index += 1) {
if (message[index] === '\\') {
index += 1;
} else if (message[index] === quote) {
return index + 1;
}
}
return message.length;
}
function cookieValueEnd(message: string, start: number): number {
const initialQuotedEnd = quotedValueEnd(message, start);
let end: number;
if (initialQuotedEnd !== undefined) {
end = initialQuotedEnd;
} else {
end = start;
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
end += 1;
}
}
while (end < message.length) {
let semicolon: number = end;
while (message[semicolon] === ' ' || message[semicolon] === '\t') {
semicolon += 1;
}
if (message[semicolon] !== ';') break;
let nameStart = semicolon + 1;
while (message[nameStart] === ' ' || message[nameStart] === '\t') {
nameStart += 1;
}
let nameEnd = nameStart;
while (/[A-Za-z0-9_-]/.test(message[nameEnd] ?? '')) nameEnd += 1;
if (nameEnd === nameStart) break;
end = nameEnd;
if (message[end] !== '=') continue;
const attribute = message.slice(nameStart, nameEnd).toLowerCase();
const valueStart = end + 1;
const quotedEnd = quotedValueEnd(message, valueStart);
if (quotedEnd !== undefined) {
end = quotedEnd;
continue;
}
if (attribute !== 'expires') {
end = valueStart;
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
end += 1;
}
continue;
}
end = valueStart;
while (end < message.length && !/[;}\]&\r\n]/.test(message[end]!)) {
end += 1;
}
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
assignments.lastIndex = valueStart;
const nextField = assignments.exec(message);
if (nextField && nextField.index < end) end = nextField.index;
}
return end;
}
function genericValueEnd(message: string, start: number): number {
const quotedEnd = quotedValueEnd(message, start);
if (quotedEnd !== undefined) return quotedEnd;
let end = start;
while (end < message.length && !/[\s,}\]&\r\n]/.test(message[end]!)) {
end += 1;
}
return end;
}
function authorizationValueEnd(
message: string,
start: number,
query: boolean,
): number {
const quotedEnd = quotedValueEnd(message, start);
if (quotedEnd !== undefined) return quotedEnd;
if (query) {
const queryEnd = message.indexOf('&', start);
return queryEnd >= 0 ? queryEnd : message.length;
}
let end = message.length;
const structural = message.slice(start).search(/[\r\n}\]]/);
if (structural >= 0) end = start + structural;
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
const remaining = message.slice(start, end);
for (let match = assignments.exec(remaining); match; match = assignments.exec(remaining)) {
if (isAuthorizationBoundaryKey(match[3]!)) {
end = start + match.index;
break;
}
}
return end;
}
/** Redact explicit authentication assignments in ordinary formatted logs. */
export function redactLogMessage(message: string): string {
let out = '';
let cursor = 0;
ASSIGNMENT_START.lastIndex = 0;
for (let match = ASSIGNMENT_START.exec(message); match; match = ASSIGNMENT_START.exec(message)) {
const key = match[3]!;
if (!isSensitiveKey(key)) {
ASSIGNMENT_START.lastIndex = Math.max(
match.index + 1,
ASSIGNMENT_START.lastIndex - 1,
);
continue;
}
const valueStart = ASSIGNMENT_START.lastIndex;
const valueEnd = isKeyKind(key, 'authorization')
? authorizationValueEnd(
message,
valueStart,
match[1] === '?' || match[1] === '&',
)
: isKeyKind(key, 'cookie')
? cookieValueEnd(message, valueStart)
: genericValueEnd(message, valueStart);
out += message.slice(cursor, valueStart) + '***';
cursor = valueEnd;
ASSIGNMENT_START.lastIndex = valueEnd;
}
return out + message.slice(cursor);
}
/**
* Deep, debug-grade render of a params object for the `trace` level: shows the
* full nested structure (message segments, nested objects) so a reproduction
* is legible — unlike {@link summarizeParams}, which collapses nested values.
*
* Three guards keep it safe and bounded:
* - per-string cap (long values like base64 image data become `"…<N B>"`),
* - total output budget (so a giant payload can't flood the buffer),
* - key-based redaction (token / password / secret → `"***"`).
* Lossless nested renderer for explicit TRACE diagnostics. TRACE is an
* operator-enabled, memory-only mode and intentionally leaves values
* unredacted so a reproduction contains the complete business input.
*/
export function renderParamsVerbose(params: unknown): string {
const seen = new WeakSet<object>();
let budget = VERBOSE_TOTAL_MAX;
const walk = (value: unknown, key?: string): string => {
if (budget <= 0) return '…';
if (key !== undefined && REDACT_KEY.test(key)) return '"***"';
const walk = (value: unknown): string => {
if (value === null) return 'null';
if (value === undefined) return 'undefined';
switch (typeof value) {
case 'string': {
const truncated =
value.length > VERBOSE_STRING_MAX
? `${value.slice(0, VERBOSE_STRING_MAX)}…<${value.length}B>`
: value;
const out = JSON.stringify(truncated);
budget -= out.length;
return out;
}
case 'string':
return JSON.stringify(value);
case 'number':
case 'boolean':
case 'bigint': {
const out = String(value);
budget -= out.length;
return out;
}
case 'bigint':
return String(value);
case 'object': {
if (seen.has(value as object)) return '"[circular]"';
seen.add(value as object);
const parts: string[] = [];
if (Array.isArray(value)) {
for (const item of value) {
if (budget <= 0) { parts.push('…'); break; }
parts.push(walk(item));
}
return `[${parts.join(',')}]`;
}
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
if (budget <= 0) { parts.push('…'); break; }
parts.push(`${k}:${walk(v, k)}`);
}
return `{${parts.join(',')}}`;
const out = Array.isArray(value)
? `[${value.map((item) => walk(item)).join(',')}]`
: `{${Object.entries(value as Record<string, unknown>)
.map(([key, item]) => `${key}:${walk(item)}`)
.join(',')}}`;
seen.delete(value as object);
return out;
}
default:
return typeof value;
+109 -37
View File
@@ -1,9 +1,16 @@
import { format } from 'util';
import { getFileTransport } from './log-file-transport';
import { redactLogMessage } from './log-summary';
import { sanitizeLogLine } from './log-sanitize';
import { currentRequestId } from './request-context';
import {
currentRequestId,
nextRequestId,
runWithoutRequestContext,
runWithRequestId,
} from './request-context';
type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
type FileLogLevel = Exclude<LogLevel, 'trace'>;
export interface LogEntry {
id: number;
@@ -114,27 +121,48 @@ function resolveMinLevel(): LogLevel {
return 'info';
}
function resolveFileMinLevel(): FileLogLevel {
const raw = process.env.SNOWLUMA_LOG_FILE_LEVEL;
if (raw === undefined || raw.trim() === '') return 'debug';
const normalized = raw.trim().toLowerCase();
if (normalized === 'debug' || normalized === 'info' || normalized === 'success' ||
normalized === 'warn' || normalized === 'error') {
return normalized;
}
throw new TypeError(
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
);
}
// Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but
// setLogLevel() lets WebUI / SDK callers flip it without a restart.
// Only governs console + ring buffer + subscribers; the file
// transport always sees debug-and-up regardless.
// Only governs console + ring buffer + subscribers;
// the file transport level is seeded independently from
// SNOWLUMA_LOG_FILE_LEVEL (default debug)
// and is not affected by setLogLevel().
let currentLevel: LogLevel = resolveMinLevel();
const currentFileLevel: FileLogLevel = resolveFileMinLevel();
function shouldLog(level: LogLevel): boolean {
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
}
function shouldLogToFile(level: LogLevel): boolean {
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentFileLevel];
}
export const LOG_LEVELS: readonly LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
export function getLogLevel(): LogLevel {
return currentLevel;
}
/**
* Change the console / subscriber level at runtime. Invalid input is
* a no-op (returns false). File transport is unaffected — it always
* sees every level so post-mortems remain useful.
*/
// Change the console / subscriber level at runtime.
// Invalid input is a no-op (returns false).
// Does not affect the file transport log level.
export function setLogLevel(level: string): boolean {
const lower = String(level).toLowerCase();
if (!LOG_LEVELS.includes(lower as LogLevel)) return false;
@@ -159,8 +187,7 @@ function currentTime(): string {
return `${hh}:${mm}:${ss}`;
}
function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: number): string {
const message = format(...args);
function render(level: LogLevel, options: LogOptions, message: string, reqId?: number): string {
const ts = currentTime();
const label = LEVEL_LABEL[level].padEnd(5, ' ');
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
@@ -183,16 +210,23 @@ function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: n
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
}
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
// Console / subscriber level filter. File output is debug-and-up always;
// see log-file-transport.ts.
function emit(
level: LogLevel,
options: LogOptions,
args: unknown[],
): void {
// Console / subscriber and file filters are independent. If no destination
// accepts the record, stop before formatting or building a LogEntry.
const passesConsole = shouldLog(level);
const passesFile = level !== 'trace'
&& shouldLogToFile(level);
if (!passesConsole && !passesFile) return;
// `trace` never touches disk and is the high-volume full-chain stream. When
// it won't reach the console/memory buffer either (level not dialed to
// trace), bail BEFORE format/render AND before evaluating any lazy producer
// — this is what keeps full-chain tracing ~free at the default level even
// with hundreds of groups.
// `trace` is the high-volume full-chain diagnostic stream, intentionally
// excluded from disk to avoid I/O saturation. When console is not dialed
// to trace, the early return below skips format/render/disk entirely.
// Set SNOWLUMA_LOG_LEVEL=trace to inspect trace output in console/memory;
// trace never reaches disk regardless.
if (level === 'trace' && !passesConsole) return;
// Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer
@@ -203,8 +237,11 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
}
const reqId = currentRequestId();
const message = format(...realArgs);
const line = render(level, options, realArgs, reqId);
const formattedMessage = format(...realArgs);
const message = level === 'trace'
? formattedMessage
: redactLogMessage(formattedMessage);
const line = render(level, options, message, reqId);
const entry: LogEntry = {
id: nextLogId++,
time: new Date().toISOString(),
@@ -227,14 +264,22 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
// 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 debug-and-up for post-mortem value; `trace` is
// memory / WebUI only (omitted here to avoid huge on-disk volume). ANSI
// stripping happens inside the transport. UIN routes the line to its
// per-account sub-file in addition to the shared one.
if (level !== 'trace') getFileTransport().write(line, options.uin);
// File transport sees levels >= currentFileLevel (SNOWLUMA_LOG_FILE_LEVEL,
// default debug). `trace` is memory / WebUI only (omitted here to avoid huge
// on-disk volume). ANSI stripping happens inside the transport. UIN routes
// the line to its per-account sub-file in addition to the shared one.
if (passesFile) {
getFileTransport().write(line, options.uin);
}
}
/**
@@ -247,15 +292,19 @@ export function closeLogger(): Promise<void> {
return getFileTransport().close();
}
export function getRecentLogs(limit = 300): LogEntry[] {
const n = Math.max(1, Math.trunc(limit));
// Merge the normal + trace rings by id (ids are monotonic, so id order is
// chronological). The trace ring is empty unless trace level is/was active,
// so the common case is just the normal ring with no sort.
const merged = traceRing.size > 0
function mergeLogRings(): LogEntry[] {
return traceRing.size > 0
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
: logRing.toArray();
return merged.slice(-n);
}
export function getLogSnapshot(): LogEntry[] {
return mergeLogRings();
}
export function getRecentLogs(limit = 300): LogEntry[] {
const n = Math.max(1, Math.trunc(limit));
return mergeLogRings().slice(-n);
}
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
@@ -310,7 +359,30 @@ export function createLogger(scope: string): Logger {
return makeLogger({ scope });
}
// Request-correlation helpers live alongside the logger since `[req#N]`
// stamping is a logging concern. Re-exported here so callers import the
// whole logging surface from one place.
export { nextRequestId, runWithRequestId, currentRequestId } from './request-context';
export function renderTraceBytes(body: Uint8Array): string {
return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString('hex');
}
export function runWithTraceRequest<T>(fn: () => T): T {
if (currentRequestId() !== undefined || currentLevel !== 'trace') return fn();
return runWithRequestId(nextRequestId(), fn);
}
export function logInitialWebuiCredentials(password: string): void {
// This is deliberately not a LogEntry: application logs can be retained on
// disk, exported through WebUI, and delivered to subscribers. First-run
// credentials must only cross the process terminal boundary.
const line = render(
'info',
{ scope: 'WebUI' },
format('initial credentials: user=admin password=%s', password),
);
// Keep the same terminal control-character policy as regular console logs.
// eslint-disable-next-line no-control-regex
process.stdout.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
}
// Request-correlation primitives remain available for callers that already own
// an explicit request id. New semantic entrypoints should prefer
// runWithTraceRequest() so disabled TRACE does not allocate one.
export { nextRequestId, runWithoutRequestContext, runWithRequestId, currentRequestId };
+6 -1
View File
@@ -4,7 +4,7 @@ interface RequestStore {
id: number;
}
const storage = new AsyncLocalStorage<RequestStore>();
const storage = new AsyncLocalStorage<RequestStore | undefined>();
let counter = 0;
/**
@@ -29,6 +29,11 @@ export function runWithRequestId<T>(id: number, fn: () => T): T {
return storage.run({ id }, fn);
}
/** Run `fn` without inheriting an ambient request id. */
export function runWithoutRequestContext<T>(fn: () => T): T {
return storage.run(undefined, fn);
}
/** The request id bound to the current async context, or undefined outside one. */
export function currentRequestId(): number | undefined {
return storage.getStore()?.id;
+141 -4
View File
@@ -7,8 +7,8 @@ export interface RuntimeConfig {
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
* Defaults to false; the Docker image flips it on in supervisord.conf. */
hookAutoLoad?: boolean;
/** WebUI listener bind address. '0.0.0.0' = all interfaces (default),
* '127.0.0.1' = localhost-only. Listener-level: change needs a restart. */
/** WebUI listener bind address. '127.0.0.1' = localhost-only (default),
* '0.0.0.0' = all IPv4 interfaces. Listener-level: change needs a restart. */
webuiHost?: string;
/** WebUI TLS. Cert/key live in config/cert.pem + config/key.pem; this
* only flips serving on/off. Listener-level: change needs a restart. */
@@ -16,13 +16,26 @@ export interface RuntimeConfig {
/** Raw trust-proxy directive (same domain as SNOWLUMA_WEBUI_TRUST_PROXY),
* consumed by the WebUI's client-ip resolver. '' = trust nobody. */
trustProxy?: string;
/** Aggregate cap for every managed file below the log root. */
logMaxTotalMb?: number;
/** Calendar-day retention. Zero disables date-based deletion. */
logRetainDays?: number;
/** Duplicate UIN-scoped lines into logs/<uin>/ in addition to the shared log. */
logPerUin?: boolean;
}
const CONFIG_DIR = 'config';
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
const DEFAULT_WEBUI_PORT = 5099;
const DEFAULT_WEBUI_HOST = '0.0.0.0';
const DEFAULT_WEBUI_HOST = '127.0.0.1';
export const DEFAULT_LOG_MAX_TOTAL_MB = 1024;
export const DEFAULT_LOG_RETAIN_DAYS = 7;
export const DEFAULT_LOG_PER_UIN = false;
export const MAX_LOG_TOTAL_MB = Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024));
export const MAX_LOG_RETAIN_DAYS = Math.floor(
Number.MAX_SAFE_INTEGER / (24 * 60 * 60 * 1000),
);
/**
* Pure on-disk-object → typed config normalization (defaults + validation,
@@ -36,6 +49,21 @@ export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
webuiHost: normalizeHost(obj.webuiHost),
webuiTls: { enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false },
trustProxy: typeof obj.trustProxy === 'string' ? obj.trustProxy : '',
logMaxTotalMb: normalizeRequiredInteger(
obj.logMaxTotalMb,
DEFAULT_LOG_MAX_TOTAL_MB,
1,
MAX_LOG_TOTAL_MB,
'logMaxTotalMb',
),
logRetainDays: normalizeRequiredInteger(
obj.logRetainDays,
DEFAULT_LOG_RETAIN_DAYS,
0,
MAX_LOG_RETAIN_DAYS,
'logRetainDays',
),
logPerUin: normalizeRequiredBool(obj.logPerUin, DEFAULT_LOG_PER_UIN, 'logPerUin'),
};
}
@@ -58,6 +86,31 @@ export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<Runt
const tp = env.SNOWLUMA_WEBUI_TRUST_PROXY;
if (typeof tp === 'string') out.trustProxy = tp;
const logMaxTotalMb = parseRequiredIntegerEnv(
env.SNOWLUMA_LOG_MAX_TOTAL_MB,
1,
MAX_LOG_TOTAL_MB,
'SNOWLUMA_LOG_MAX_TOTAL_MB',
);
if (logMaxTotalMb !== undefined) out.logMaxTotalMb = logMaxTotalMb;
const logRetainDays = parseRequiredIntegerEnv(
env.SNOWLUMA_LOG_RETAIN_DAYS,
0,
MAX_LOG_RETAIN_DAYS,
'SNOWLUMA_LOG_RETAIN_DAYS',
);
if (logRetainDays !== undefined) out.logRetainDays = logRetainDays;
const logPerUin = parseRequiredBoolEnv(
env.SNOWLUMA_LOG_PER_UIN,
'SNOWLUMA_LOG_PER_UIN',
);
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;
}
@@ -109,7 +162,23 @@ function tryLoadRuntimeConfig(): Record<string, unknown> | null {
}
function saveRuntimeConfig(config: RuntimeConfig): void {
fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
const temporaryPath = `${RUNTIME_CONFIG_PATH}.tmp-${String(process.pid)}`;
try {
fs.writeFileSync(temporaryPath, JSON.stringify(config, null, 2), 'utf8');
fs.renameSync(temporaryPath, RUNTIME_CONFIG_PATH);
} catch (error) {
try {
fs.unlinkSync(temporaryPath);
} catch (cleanupError) {
if (!isErrnoCode(cleanupError, 'ENOENT')) {
throw new AggregateError(
[error, cleanupError],
'failed to persist runtime config and remove its temporary file',
);
}
}
throw error;
}
}
/** True when the raw on-disk object already matches the normalized config
@@ -122,6 +191,9 @@ function sameRuntimeConfig(parsed: Record<string, unknown>, n: RuntimeConfig): b
&& parsed.webuiHost === n.webuiHost
&& parsedTls === n.webuiTls?.enabled
&& parsed.trustProxy === n.trustProxy
&& parsed.logMaxTotalMb === n.logMaxTotalMb
&& parsed.logRetainDays === n.logRetainDays
&& parsed.logPerUin === n.logPerUin
);
}
@@ -155,6 +227,37 @@ function normalizePort(value: unknown, fallback: number): number {
return fallback;
}
function normalizeRequiredInteger(
value: unknown,
fallback: number,
min: number,
max: number,
field: string,
): number {
if (value === undefined) return fallback;
const n = typeof value === 'string' && value.trim() ? Number(value.trim()) : value;
if (
typeof n === 'number'
&& Number.isSafeInteger(n)
&& n >= min
&& n <= max
) {
return n;
}
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
}
function normalizeRequiredBool(
value: unknown,
fallback: boolean,
field: string,
): boolean {
if (value === undefined) return fallback;
const parsed = parseBoolValue(value);
if (parsed !== undefined) return parsed;
throw new TypeError(`${field} must be a boolean`);
}
function normalizeBool(value: unknown, fallback: boolean): boolean {
if (typeof value === 'boolean') return value;
if (typeof value === 'number') return value !== 0;
@@ -166,6 +269,40 @@ function normalizeBool(value: unknown, fallback: boolean): boolean {
return fallback;
}
function parseRequiredIntegerEnv(
raw: unknown,
min: number,
max: number,
field: string,
): number | undefined {
if (typeof raw !== 'string' || !raw.trim()) return undefined;
const n = Number(raw.trim());
if (Number.isSafeInteger(n) && n >= min && n <= max) return n;
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
}
function parseRequiredBoolEnv(raw: unknown, field: string): boolean | undefined {
if (typeof raw !== 'string' || !raw.trim()) return undefined;
const parsed = parseBoolValue(raw);
if (parsed !== undefined) return parsed;
throw new TypeError(`${field} must be a boolean`);
}
function parseBoolValue(raw: unknown): boolean | undefined {
if (typeof raw === 'boolean') return raw;
if (raw === 1) return true;
if (raw === 0) return false;
if (typeof raw !== 'string') return undefined;
const value = raw.trim().toLowerCase();
if (value === 'true' || value === '1' || value === 'yes' || value === 'on') return true;
if (value === 'false' || value === '0' || value === 'no' || value === 'off') return false;
return undefined;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isErrnoCode(error: unknown, code: string): boolean {
return error instanceof Error && 'code' in error && error.code === code;
}
@@ -0,0 +1,28 @@
import { describe, expect, it } from 'vitest';
import {
ACCESS_TOKEN_MIN_LENGTH,
ACCESS_TOKEN_MIN_SCORE,
assessAccessToken,
} from '../src/access-token';
describe('access token strength', () => {
it('requires the configured minimum length', () => {
expect(assessAccessToken('a'.repeat(ACCESS_TOKEN_MIN_LENGTH - 1))).toMatchObject({
acceptable: false,
reason: 'too-short',
});
});
it('scores system and user-specific words as guessable', () => {
expect(assessAccessToken('SnowLumaSnowLuma', ['SnowLuma', 'OneBot', '10001']))
.toMatchObject({ acceptable: false, reason: 'guessable' });
});
it('accepts a sufficiently long, hard-to-guess token', () => {
const result = assessAccessToken('E5xqVb7_9pLt2QwR4M8kZ1nY', ['SnowLuma', 'OneBot']);
expect(result.acceptable).toBe(true);
expect(result.reason).toBe('acceptable');
expect(result.score).toBeGreaterThanOrEqual(ACCESS_TOKEN_MIN_SCORE);
});
});
+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
+185 -12
View File
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest';
import { renderParamsVerbose, summarizeParams } from '../src/log-summary';
import {
redactLogMessage,
renderParamsVerbose,
summarizeParams,
} from '../src/log-summary';
describe('summarizeParams', () => {
it('renders null/undefined as {}', () => {
@@ -24,29 +28,191 @@ describe('summarizeParams', () => {
.toBe(`s="${'x'.repeat(40)}..."`);
});
it('redacts authentication fields without exposing their values', () => {
const out = summarizeParams({
token: 'token-value',
Cookie: 'cookie-value',
Authorization: 'Bearer authorization-value',
user_password: 'password-value',
apiKey: 'key-value',
group_id: 12345,
});
expect(out).toContain('token="***"');
expect(out).toContain('Cookie="***"');
expect(out).toContain('Authorization="***"');
expect(out).toContain('user_password="***"');
expect(out).toContain('apiKey="***"');
expect(out).toContain('group_id=12345');
expect(out).not.toMatch(
/token-value|cookie-value|authorization-value|password-value|key-value/,
);
});
it('does not treat sensitive substrings inside ordinary keys as credentials', () => {
expect(summarizeParams({
retoken: 'visible',
cookietown: 'visible',
myauthorization: 'visible',
})).toBe(
'retoken="visible" cookietown="visible" myauthorization="visible"',
);
});
it('caps total output and appends "..." on overflow', () => {
const big: Record<string, number> = {};
for (let i = 0; i < 60; i++) big['key' + i] = i;
const out = summarizeParams(big);
expect(out.startsWith('key0=0')).toBe(true);
expect(out.endsWith('...')).toBe(true);
expect(out.length).toBeLessThanOrEqual(200);
});
it('caps a single oversized first key and top-level primitive', () => {
const oversizedKey = 'k'.repeat(300);
const objectOut = summarizeParams({ [oversizedKey]: 'value' });
const primitiveOut = summarizeParams('x'.repeat(300));
expect(objectOut).toHaveLength(200);
expect(objectOut.endsWith('...')).toBe(true);
expect(primitiveOut).toHaveLength(200);
expect(primitiveOut.endsWith('...')).toBe(true);
});
});
describe('redactLogMessage', () => {
it('redacts explicit authentication assignments without changing prose', () => {
const out = redactLogMessage(
'password=secret Authorization: Bearer bearer-secret cookie="cookie secret" password change required',
);
expect(out).toBe(
'password=*** Authorization: *** cookie=*** password change required',
);
});
it('redacts quoted object keys, Basic auth, and complete Cookie values', () => {
const out = redactLogMessage(
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
);
const expires = redactLogMessage(
'Cookie=session=expires-secret; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Path=/; HttpOnly safe=visible',
);
expect(out).toContain('json={"authorization":***}');
expect(out).toContain("object={ 'api-key': *** }");
expect(out).toContain('Authorization: *** Cookie=***');
expect(expires).toBe('Cookie=*** safe=visible');
expect(out).not.toMatch(/json-auth|api-secret|header-auth|cookie-secret|Path=|HttpOnly/);
expect(expires).not.toMatch(/expires-secret|Expires|21 Oct|Path=|HttpOnly/);
});
it('redacts complete multi-parameter Authorization values', () => {
const out = redactLogMessage(
'Authorization: Digest username="alice", realm="qq", response="digest-secret"\n'
+ 'authorization=AWS4-HMAC-SHA256 Credential=AKID/20260730/cn/service/aws4_request, '
+ 'SignedHeaders=host;x-date, Signature=aws-secret\n'
+ 'Authorization: Bearer bearer-secret Cookie=session=cookie-secret; Path=/',
);
expect(out).toBe(
'Authorization: ***\nauthorization=***\nAuthorization: *** Cookie=***',
);
expect(out).not.toMatch(
/alice|realm|digest-secret|AKID|SignedHeaders|aws-secret|bearer-secret|cookie-secret|Path=/,
);
});
it('redacts camelCase authentication keys without matching larger words', () => {
const out = redactLogMessage(
`authToken=auth-secret idToken=id-secret clientSecret=client-secret {"userPassword":"password-secret"}`,
);
expect(out).toBe(
`authToken=*** idToken=*** clientSecret=*** {"userPassword":***}`,
);
expect(out).not.toMatch(
/auth-secret|id-secret|client-secret|password-secret/,
);
expect(redactLogMessage(
'retoken=value cookietown=value myauthorization=value',
)).toBe('retoken=value cookietown=value myauthorization=value');
});
it('redacts leading separator and numeric authentication keys without matching larger words', () => {
expect(redactLogMessage(
'_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret retoken=visible',
)).toBe('_token=*** --password=*** 2faToken=*** retoken=visible');
});
it('redacts nested assignments inside non-sensitive wrapper values', () => {
expect(redactLogMessage(
'params=authToken=auth-secret params=cookie="cookie-secret"',
)).toBe('params=authToken=*** params=cookie=***');
});
it('redacts the entire Authorization value when it starts with a marker', () => {
expect(redactLogMessage('Authorization: *** secret-value'))
.toBe('Authorization: ***');
});
it('redacts property paths and URL query authentication values', () => {
const out = redactLogMessage(
'headers.authorization=Basic dXNlcjpwYXNz '
+ 'request.token=plain-token '
+ 'GET /callback?access_token=query-secret&x=1 '
+ 'url=https://host/?api_key=url-secret',
);
expect(out).toContain('headers.authorization=***');
expect(out).toContain('request.token=***');
expect(out).toContain('/callback?access_token=***&x=1');
expect(out).toContain('https://host/?api_key=***');
expect(out).not.toMatch(/dXNlcjpwYXNz|plain-token|query-secret|url-secret/);
});
it('redacts prefixed authentication keys without matching larger words', () => {
const redacted = redactLogMessage(
'x-api-key=api-secret user_password=password-secret '
+ 'headers.authorization=Basic auth-secret '
+ 'x-cookie="session=cookie-secret"; Path=/; HttpOnly',
);
expect(redacted).toContain('x-api-key=***');
expect(redacted).toContain('user_password=***');
expect(redacted).toContain('headers.authorization=***');
expect(redacted).toContain('x-cookie=***');
expect(redacted).not.toMatch(/api-secret|password-secret|auth-secret|cookie-secret|Path=|HttpOnly/);
expect(redactLogMessage(
'retoken=value cookietown=value myauthorization=value',
)).toBe('retoken=value cookietown=value myauthorization=value');
});
});
describe('renderParamsVerbose', () => {
it('redacts token / password / secret keys at any depth', () => {
const out = renderParamsVerbose({ token: 'abc', password: 'p', nested: { secret: 's' }, ok: 'v' });
expect(out).toContain('token:"***"');
expect(out).toContain('password:"***"');
expect(out).toContain('secret:"***"');
expect(out).toContain('ok:"v"');
it('keeps authentication fields unredacted for complete TRACE diagnostics', () => {
const out = renderParamsVerbose({
token: 'token-value',
Cookie: 'cookie-value',
password: 'password-value',
apiKey: 'key-value',
});
expect(out).toContain('token:"token-value"');
expect(out).toContain('Cookie:"cookie-value"');
expect(out).toContain('password:"password-value"');
expect(out).toContain('apiKey:"key-value"');
expect(out).not.toContain('"***"');
});
it('truncates long strings with a Unicode ellipsis + byte count (not ASCII dots)', () => {
// The reported change-request: the marker is `…<N B>` (U+2026), not `...<N B>`.
const out = renderParamsVerbose({ blob: 'a'.repeat(500) });
expect(out).toContain('…<500B>');
expect(out).not.toContain('...<500B>');
it('does not truncate TRACE values or their enclosing object', () => {
const unicodeValue = '雪'.repeat(800);
const out = renderParamsVerbose({ blob: unicodeValue, tail: 'complete' });
expect(out).toContain(`blob:${JSON.stringify(unicodeValue)}`);
expect(out).toContain('tail:"complete"');
expect(out).not.toMatch(/…<\d+B>|\.\.\./);
});
it('guards against circular references', () => {
@@ -55,6 +221,13 @@ describe('renderParamsVerbose', () => {
expect(renderParamsVerbose(o)).toContain('"[circular]"');
});
it('renders shared non-cyclic references in every branch', () => {
const shared = { value: 1 };
expect(renderParamsVerbose({ left: shared, right: shared }))
.toBe('{left:{value:1},right:{value:1}}');
});
it('renders nested structure with primitives intact', () => {
expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}');
});
+268 -4
View File
@@ -1,11 +1,28 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
// The file transport writes to disk; stub it so the test has no side effects.
const { externalFileLevel, externalLogLevel, fileWriteSpy } = vi.hoisted(() => {
const savedFileLevel = process.env.SNOWLUMA_LOG_FILE_LEVEL;
const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL;
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
delete process.env.SNOWLUMA_LOG_LEVEL;
return {
externalFileLevel: savedFileLevel,
externalLogLevel: savedLogLevel,
fileWriteSpy: vi.fn(),
};
});
// Capture file transport writes via a spy so tests can assert on what reaches
// the file.
vi.mock('../src/log-file-transport', () => ({
getFileTransport: () => ({ write: () => {} }),
getFileTransport: () => ({ write: fileWriteSpy, close: async () => {} }),
}));
import { createLogger, subscribeLogs, type LogEntry } from '../src/logger';
import {
createLogger,
subscribeLogs,
type LogEntry,
} from '../src/logger';
// Regression for issue #162: a hook-reported garbage UIN (13-digit, timestamp
// shaped) produced a `[…]` tag wider than the fixed UIN slot, and the colored
@@ -43,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));
@@ -55,3 +79,243 @@ describe('logger UIN slot padding', () => {
expect(process.stdout.write).toHaveBeenCalledWith(expect.stringContaining('\x1b['));
});
});
// ─── Independent file-level filtering ─────────────────────────────────────
const SAVED_FILE_LEVEL = externalFileLevel;
async function loadLoggerForFileLevel(level?: string) {
if (level === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
else process.env.SNOWLUMA_LOG_FILE_LEVEL = level;
vi.resetModules();
fileWriteSpy.mockClear();
return import('../src/logger');
}
afterEach(() => {
if (SAVED_FILE_LEVEL === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
else process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
vi.resetModules();
fileWriteSpy.mockClear();
});
afterAll(() => {
if (SAVED_FILE_LEVEL === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
else process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
if (externalLogLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL;
else process.env.SNOWLUMA_LOG_LEVEL = externalLogLevel;
});
describe('file output gating', () => {
const cases = [
{ level: undefined, expected: ['debug', 'info', 'success', 'warn', 'error'] },
{ level: 'debug', expected: ['debug', 'info', 'success', 'warn', 'error'] },
{ level: 'info', expected: ['info', 'success', 'warn', 'error'] },
{ level: 'success', expected: ['success', 'warn', 'error'] },
{ level: 'warn', expected: ['warn', 'error'] },
{ level: 'error', expected: ['error'] },
] as const;
for (const testCase of cases) {
it(`writes exactly the enabled levels for ${testCase.level ?? 'the default'}`, async () => {
const fresh = await loadLoggerForFileLevel(testCase.level);
const log = fresh.createLogger('Test');
fresh.setLogLevel('trace');
log.trace('trace');
log.debug('debug');
log.info('info');
log.success('success');
log.warn('warn');
log.error('error');
const messages = fileWriteSpy.mock.calls.map(([line]) => String(line).split('] ').at(-1));
expect(messages).toEqual(testCase.expected);
});
}
it('accepts surrounding whitespace and mixed case', async () => {
const fresh = await loadLoggerForFileLevel(' INFO ');
const log = fresh.createLogger('Test');
log.debug('debug');
log.info('info');
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
expect(fileWriteSpy).toHaveBeenCalledWith(expect.stringContaining('info'), undefined);
});
it.each(['trace', 'verbose', 'erorr'])(
'rejects unsupported file level %s at startup',
async (level) => {
await expect(loadLoggerForFileLevel(level)).rejects.toThrow(
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
);
expect(fileWriteSpy).not.toHaveBeenCalled();
},
);
it('does not let the runtime console level change file output', async () => {
const fresh = await loadLoggerForFileLevel('info');
const log = fresh.createLogger('Test');
fresh.setLogLevel('error');
log.info('persisted-info');
fresh.setLogLevel('trace');
log.debug('filtered-debug');
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
expect(fileWriteSpy).toHaveBeenCalledWith(
expect.stringContaining('persisted-info'),
undefined,
);
});
it('skips rendering when both console and file filters reject a record', async () => {
const fresh = await loadLoggerForFileLevel('error');
fresh.setLogLevel('error');
const rendered = vi.fn(() => 'expensive');
const value = { [Symbol.toPrimitive]: rendered };
fresh.createLogger('Test').debug('value=%s', value);
expect(rendered).not.toHaveBeenCalled();
expect(fileWriteSpy).not.toHaveBeenCalled();
});
it('keeps trace out of files in an explicit file-threshold check', async () => {
const fresh = await loadLoggerForFileLevel('debug');
fresh.setLogLevel('trace');
fresh.createLogger('Test').trace('full chain');
expect(fileWriteSpy).not.toHaveBeenCalled();
});
it('redacts authentication assignments from ordinary logs but not TRACE', async () => {
const fresh = await loadLoggerForFileLevel('debug');
fresh.setLogLevel('trace');
const entries: LogEntry[] = [];
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
const log = fresh.createLogger('Test');
log.info(
'password=%s Authorization: Bearer %s Cookie=%s token=%s safe=%s',
'ordinary-password',
'ordinary-authorization',
'ordinary-cookie',
'ordinary-token',
'visible',
);
log.trace(
'password=%s Authorization: Bearer %s Cookie=%s token=%s',
'trace-password',
'trace-authorization',
'trace-cookie',
'trace-token',
);
log.info(
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
);
log.info(
'headers.authorization=Basic dotted-auth request.token=dotted-token '
+ 'GET /callback?access_token=query-secret&x=1 '
+ 'url=https://host/?api_key=url-secret',
);
log.info(
'Authorization: Digest username="alice", response="digest-secret"\n'
+ 'authorization=AWS4-HMAC-SHA256 Credential=AKID, Signature=aws-secret',
);
log.info(
'authToken=camel-auth idToken=camel-id clientSecret=camel-client '
+ `json={"userPassword":"camel-password"}`,
);
log.info('_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret');
log.info('Authorization: *** marker-secret');
log.trace(
`json={"authorization":"Basic trace-json-auth"} Authorization: Basic trace-header-auth Cookie=session=trace-cookie; Path=/`,
);
unsubscribe();
const ordinaryEntries = entries.filter((entry) => entry.level === 'info');
const ordinary = ordinaryEntries.map((entry) => entry.message).join('\n');
expect(ordinary).toContain('password=***');
expect(ordinary).toContain('Authorization: ***');
expect(ordinary).toContain('Cookie=***');
expect(ordinary).toContain('token=***');
expect(ordinary).toContain('headers.authorization=***');
expect(ordinary).toContain('request.token=***');
expect(ordinary).toContain('/callback?access_token=***&x=1');
expect(ordinary).toContain('https://host/?api_key=***');
expect(ordinary).toContain('Authorization: ***\nauthorization=***');
expect(ordinary).toContain('authToken=***');
expect(ordinary).toContain('idToken=***');
expect(ordinary).toContain('clientSecret=***');
expect(ordinary).toContain(`json={"userPassword":***}`);
expect(ordinary).toContain('_token=***');
expect(ordinary).toContain('--password=***');
expect(ordinary).toContain('2faToken=***');
expect(ordinary).toContain('Authorization: ***');
expect(ordinary).toContain('safe=visible');
expect(ordinary).not.toMatch(
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|camel-auth|camel-id|camel-client|camel-password|underscore-secret|cli-secret|two-factor-secret|marker-secret/,
);
const trace = entries.filter((entry) => entry.level === 'trace')
.map((entry) => entry.message)
.join('\n');
expect(trace).toContain('trace-password');
expect(trace).toContain('trace-authorization');
expect(trace).toContain('trace-cookie');
expect(trace).toContain('trace-token');
expect(trace).toContain('trace-json-auth');
expect(trace).toContain('trace-header-auth');
const persisted = fileWriteSpy.mock.calls.map(([line]) => String(line)).join('\n');
expect(persisted).not.toMatch(
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|trace-password|trace-json-auth/,
);
});
it('returns the complete retained normal and TRACE snapshot in record order', async () => {
const fresh = await loadLoggerForFileLevel('debug');
const log = fresh.createLogger('Export');
fresh.setLogLevel('trace');
log.info('normal-before');
log.trace('trace-hex=001122aabbcc');
log.warn('normal-after');
expect(fresh.getRecentLogs(1).map((entry) => entry.message)).toEqual([
'normal-after',
]);
expect(fresh.getLogSnapshot().map((entry) => entry.message)).toEqual([
'normal-before',
'trace-hex=001122aabbcc',
'normal-after',
]);
});
it('prints bootstrap credentials only to the current process terminal', async () => {
const fresh = await loadLoggerForFileLevel('error');
fresh.setLogLevel('error');
const entries: LogEntry[] = [];
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
const snapshotBefore = fresh.getLogSnapshot();
const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true);
try {
fresh.logInitialWebuiCredentials('secret');
expect(stdout).toHaveBeenCalledWith(
expect.stringContaining('initial credentials: user=admin password=secret'),
);
expect(entries).toEqual([]);
expect(fresh.getLogSnapshot()).toEqual(snapshotBefore);
expect(fileWriteSpy).not.toHaveBeenCalled();
} finally {
unsubscribe();
stdout.mockRestore();
}
});
});
+91 -6
View File
@@ -1,4 +1,6 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { normalizeRuntimeConfig, resolveRuntimeEnvOverrides } from '../src/runtime';
describe('normalizeRuntimeConfig', () => {
@@ -6,9 +8,12 @@ describe('normalizeRuntimeConfig', () => {
expect(normalizeRuntimeConfig({})).toEqual({
webuiPort: 5099,
hookAutoLoad: false,
webuiHost: '0.0.0.0',
webuiHost: '127.0.0.1',
webuiTls: { enabled: false },
trustProxy: '',
logMaxTotalMb: 1024,
logRetainDays: 7,
logPerUin: false,
});
});
@@ -19,12 +24,18 @@ describe('normalizeRuntimeConfig', () => {
webuiHost: '127.0.0.1',
webuiTls: { enabled: true },
trustProxy: '1',
logMaxTotalMb: 2048,
logRetainDays: 0,
logPerUin: true,
})).toEqual({
webuiPort: 8080,
hookAutoLoad: true,
webuiHost: '127.0.0.1',
webuiTls: { enabled: true },
trustProxy: '1',
logMaxTotalMb: 2048,
logRetainDays: 0,
logPerUin: true,
});
});
@@ -36,19 +47,34 @@ describe('normalizeRuntimeConfig', () => {
trustProxy: 5, // non-string → default
});
expect(out.webuiPort).toBe(5099);
expect(out.webuiHost).toBe('0.0.0.0');
expect(out.webuiHost).toBe('127.0.0.1');
expect(out.webuiTls).toEqual({ enabled: false });
expect(out.trustProxy).toBe('');
});
it('fails fast on invalid persisted log settings', () => {
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: 0 }))
.toThrow(/logMaxTotalMb/);
expect(() => normalizeRuntimeConfig({ logRetainDays: -1 }))
.toThrow(/logRetainDays/);
expect(() => normalizeRuntimeConfig({ logPerUin: 'maybe' }))
.toThrow(/logPerUin/);
expect(() => normalizeRuntimeConfig({ logPerUin: '' }))
.toThrow(/logPerUin/);
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: Number.MAX_SAFE_INTEGER }))
.toThrow(/logMaxTotalMb/);
expect(() => normalizeRuntimeConfig({ logRetainDays: Number.MAX_SAFE_INTEGER }))
.toThrow(/logRetainDays/);
});
it('coerces webuiTls.enabled loosely and trims a blank host to default', () => {
expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({ enabled: true });
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('0.0.0.0');
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('127.0.0.1');
});
it('rejects a non-object input back to full defaults', () => {
expect(normalizeRuntimeConfig(null).webuiPort).toBe(5099);
expect(normalizeRuntimeConfig('nope').webuiHost).toBe('0.0.0.0');
expect(normalizeRuntimeConfig('nope').webuiHost).toBe('127.0.0.1');
});
});
@@ -65,6 +91,50 @@ describe('resolveRuntimeEnvOverrides', () => {
})).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' });
});
it('parses log storage overrides including retainDays=0', () => {
expect(resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_MAX_TOTAL_MB: '4096',
SNOWLUMA_LOG_RETAIN_DAYS: '0',
SNOWLUMA_LOG_PER_UIN: '1',
})).toEqual({
logMaxTotalMb: 4096,
logRetainDays: 0,
logPerUin: true,
});
});
it('fails fast on invalid log storage overrides', () => {
expect(() => resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_MAX_TOTAL_MB: '0',
})).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
expect(() => resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_RETAIN_DAYS: '-1',
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
expect(() => resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_PER_UIN: 'maybe',
})).toThrow(/SNOWLUMA_LOG_PER_UIN/);
});
it('fails fast when converted log storage overrides would be unsafe', () => {
expect(() => resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_MAX_TOTAL_MB: String(Number.MAX_SAFE_INTEGER),
})).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
expect(() => resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_RETAIN_DAYS: String(Number.MAX_SAFE_INTEGER),
})).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({});
@@ -88,11 +158,11 @@ describe('updateRuntimeConfig (fs)', () => {
delete process.env.SNOWLUMA_WEBUI_PORT;
});
afterEach(async () => {
const fs = await import('fs');
process.chdir(prevCwd);
if (prevPortEnv === undefined) delete process.env.SNOWLUMA_WEBUI_PORT;
else process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv;
fs.rmSync(dir, { recursive: true, force: true });
vi.restoreAllMocks();
});
it('merges a patch over on-disk values and persists normalized', async () => {
@@ -114,4 +184,19 @@ describe('updateRuntimeConfig (fs)', () => {
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
expect(onDisk.webuiPort).toBe(5099); // default on-disk, NOT the env 9999
});
it('keeps the previous runtime file intact when atomic replacement fails', async () => {
const { updateRuntimeConfig } = await import('../src/runtime');
updateRuntimeConfig({ logRetainDays: 7 });
const runtimePath = path.join('config', 'runtime.json');
const before = fs.readFileSync(runtimePath, 'utf8');
vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
throw Object.assign(new Error('disk replacement failed'), { code: 'EIO' });
});
expect(() => updateRuntimeConfig({ logRetainDays: 0 }))
.toThrow(/disk replacement failed/);
expect(fs.readFileSync(runtimePath, 'utf8')).toBe(before);
expect(fs.readdirSync('config').filter((name) => name.includes('.tmp-'))).toEqual([]);
});
});
@@ -0,0 +1,117 @@
import { afterEach, describe, expect, it } from 'vitest';
import {
createLogger,
currentRequestId,
getLogLevel,
nextRequestId,
renderTraceBytes,
runWithoutRequestContext,
runWithRequestId,
runWithTraceRequest,
setLogLevel,
} from '../src/logger';
const originalLevel = getLogLevel();
afterEach(() => {
setLogLevel(originalLevel);
});
describe('TRACE diagnostics contract', () => {
it('renders every byte as continuous lowercase hexadecimal', () => {
expect(renderTraceBytes(new Uint8Array())).toBe('');
expect(renderTraceBytes(new Uint8Array([0x00, 0x01, 0x0f, 0x10, 0xff])))
.toBe('00010f10ff');
});
it('renders only the addressed Uint8Array view', () => {
const backing = new Uint8Array([0xaa, 0x00, 0x0f, 0xff, 0xbb]);
expect(renderTraceBytes(backing.subarray(1, 4))).toBe('000fff');
expect(renderTraceBytes(Buffer.from(backing.buffer).subarray(2, 4))).toBe('0fff');
});
it('does not render bytes while TRACE is disabled', () => {
setLogLevel('info');
let rendered = false;
createLogger('Trace.Contract').trace(() => {
rendered = true;
return ['body=%s', renderTraceBytes(new Uint8Array([0xff]))];
});
expect(rendered).toBe(false);
});
it('creates distinct request contexts that survive asynchronous work', async () => {
setLogLevel('info');
const beforeDisabled = nextRequestId();
expect(runWithTraceRequest(() => currentRequestId())).toBeUndefined();
const afterDisabled = nextRequestId();
expect(afterDisabled).toBe(beforeDisabled + 1);
setLogLevel('trace');
const observeContext = () => runWithTraceRequest(async () => {
const before = currentRequestId();
await Promise.resolve();
const after = currentRequestId();
expect(after).toBe(before);
return after;
});
const first = await observeContext();
expect(currentRequestId()).toBeUndefined();
const second = await observeContext();
expect(currentRequestId()).toBeUndefined();
expect(first).toEqual(expect.any(Number));
expect(first).toBeGreaterThan(0);
expect(second).toEqual(expect.any(Number));
expect(second).toBeGreaterThan(0);
expect(second).not.toBe(first);
});
it('allocates once for nested TRACE contexts and reuses the request id', () => {
setLogLevel('trace');
const before = nextRequestId();
const observed = runWithTraceRequest(() => {
const outer = currentRequestId();
const inner = runWithTraceRequest(() => currentRequestId());
return { outer, inner };
});
const after = nextRequestId();
expect(observed.outer).toEqual(expect.any(Number));
expect(observed.inner).toBe(observed.outer);
expect(observed.outer).toBe(before + 1);
expect(after).toBe(before + 2);
expect(currentRequestId()).toBeUndefined();
});
it('detaches long-lived resources from the current request context', async () => {
await runWithRequestId(4243, async () => {
expect(currentRequestId()).toBe(4243);
const detached = await runWithoutRequestContext(async () => {
expect(currentRequestId()).toBeUndefined();
await Promise.resolve();
return currentRequestId();
});
expect(detached).toBeUndefined();
expect(currentRequestId()).toBe(4243);
});
expect(currentRequestId()).toBeUndefined();
});
it('reuses an existing request context even while TRACE is disabled', async () => {
setLogLevel('info');
await runWithRequestId(4242, async () => {
const observed = await runWithTraceRequest(async () => {
await Promise.resolve();
return currentRequestId();
});
expect(observed).toBe(4242);
});
});
});
+7 -6
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.12.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": "^24.12.2",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"hono": "^4.12.25",
"hono": "^4.12.34",
"tsx": "^4.21.0",
"typescript": "catalog:",
"vite": "catalog:",
@@ -0,0 +1,28 @@
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
import {
getCollectionList,
type CollectionListResult,
} from '@snowluma/protocol/web/collection';
import type { BridgeContext } from '../bridge-context';
const COLLECTION_DOMAIN = 'weiyun.com';
/** Read-only access to the account's QQ collection list. */
export class CollectionApi {
constructor(private readonly ctx: BridgeContext) {}
async list(category = 0, count = 50): Promise<CollectionListResult> {
const { domainPskeyMap } = await GetPskey.invoke(this.ctx, {
domainList: [COLLECTION_DOMAIN],
});
const pskey = domainPskeyMap.get(COLLECTION_DOMAIN);
if (!pskey) throw new Error(`QQ did not return a p_skey for ${COLLECTION_DOMAIN}`);
return getCollectionList({
uin: this.ctx.identity.uin,
pskey,
category,
count,
});
}
}
+289 -96
View File
@@ -1,13 +1,32 @@
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
import { FetchFriendListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
import {
FetchFriendListPage,
type FriendListPageCategory,
type FriendListPageEntry,
} from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
import { FetchGroupDetail } from '@snowluma/protocol/oidb-services/contacts/fetch-group-detail';
import { FetchGroupList } from '@snowluma/protocol/oidb-services/contacts/fetch-group-list';
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
import { FetchGroupRequests } from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
import {
FetchGroupRequests,
FetchGroupRequestsByUid,
groupRequestOperationType,
} from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
import {
FetchRobotUinRanges,
type RobotUinRange,
type RobotUinRangeSnapshot,
} 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';
import { createSingleFlightCache, type SingleFlightCache } from '@snowluma/common/single-flight-cache';
@@ -24,54 +43,41 @@ 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 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 interface SetFriendCategoryParams {
uin: number;
categoryId?: number;
categoryName?: string;
}
export function permissionToRole(permission: number): string {
switch (permission) {
case 1: return 'owner';
case 2: return 'admin';
default: return 'member';
export function isRobotUin(uin: number, ranges: readonly RobotUinRange[]): boolean {
return Number.isInteger(uin)
&& uin > 0
&& ranges.some(({ minUin, maxUin }) => uin >= minUin && uin <= maxUin);
}
function normalizeGroupRequestSequence(
rawSequence: bigint | number | undefined,
groupId: number,
): number {
const sequence = Number(rawSequence ?? 0);
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
throw new Error(
`invalid group-request sequence: group=${groupId} sequence=${String(rawSequence ?? 0)}`,
);
}
return sequence;
}
const MEMBER_LIST_TTL_MS = 60_000;
@@ -91,9 +97,41 @@ export class ContactsApi {
ttlMs: MEMBER_LIST_TTL_MS,
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) { }
private fetchRobotUinRanges(groupId: number): Promise<RobotUinRangeSnapshot> {
if (this.robotUinRangesPromise_) return this.robotUinRangesPromise_;
const pending = FetchRobotUinRanges.invoke(this.ctx).then((snapshot) => {
log.info(
'loaded robot UIN ranges uin=%s version=%d count=%d',
this.ctx.identity.uin,
snapshot.version,
snapshot.ranges.length,
);
return snapshot;
});
this.robotUinRangesPromise_ = pending;
// A failed first load must be observable and retryable. Keep the rejection
// visible to the caller instead of converting every member to false.
void pending.catch((err: unknown) => {
if (this.robotUinRangesPromise_ === pending) this.robotUinRangesPromise_ = null;
log.error(
'failed to load robot UIN ranges: uin=%s group=%d err=%s',
this.ctx.identity.uin,
groupId,
err instanceof Error ? (err.stack ?? err.message) : String(err),
);
});
return pending;
}
/** Server-built ARK share card (JSON string) recommending a friend. */
getBuddyRecommendArk(userId: number, phoneNumber = ''): Promise<string> {
return GetBuddyRecommendArk.invoke(this.ctx, { userId, phoneNumber });
@@ -104,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)) {
@@ -185,6 +211,52 @@ export class ContactsApi {
});
}
async setFriendCategory(params: SetFriendCategoryParams): Promise<void> {
const selectorCount = Number(params.categoryId !== undefined)
+ Number(params.categoryName !== undefined);
if (selectorCount !== 1) {
throw new Error('exactly one of categoryId or categoryName is required');
}
const categories = await this.fetchFriendCategories();
const friendCategory = categories.find(category =>
category.friends.some(friend => friend.uin === params.uin));
const friend = friendCategory?.friends.find(entry => entry.uin === params.uin);
if (!friend) {
throw new Error(`friend ${params.uin} is not in the live roster`);
}
if (!friend.uid) {
throw new Error(`friend ${params.uin} has no UID in the live roster`);
}
let target: FriendCategoryInfo | undefined;
if (params.categoryId !== undefined) {
target = categories.find(category => category.categoryId === params.categoryId);
if (!target) {
throw new Error(`friend category ${params.categoryId} does not exist`);
}
} else {
const matches = categories.filter(category => category.categoryName === params.categoryName);
if (matches.length === 0) {
throw new Error(`friend category name "${params.categoryName}" does not exist`);
}
if (matches.length > 1) {
throw new Error(`friend category name "${params.categoryName}" is ambiguous`);
}
target = matches[0]!;
}
await SetFriendCategory.invoke(this.ctx, {
uid: friend.uid,
categoryId: target.categoryId,
});
log.info(
'friend category updated: uin=%s friend=%d category=%d',
this.ctx.identity.uin,
params.uin,
target.categoryId,
);
}
async fetchGroupList(): Promise<QQGroupInfo[]> {
const resp = await FetchGroupList.invoke(this.ctx);
const groups: QQGroupInfo[] = [];
@@ -200,6 +272,11 @@ export class ContactsApi {
// is not in the list (0x88D_0 detail only), so it stays undefined here.
createTime: raw.info?.createdTime ?? 0,
memo: raw.info?.announcement || raw.info?.description || '',
// #490: expose the description alongside `memo`. QQ fills in either
// field alone, so folding both into `memo` made the description
// unreachable whenever an announcement was also set.
description: raw.info?.description ?? '',
allMuted: isGroupAllMuted(raw.info?.shutUpAllTimestamp),
});
}
this.ctx.identity.rememberGroups(groups);
@@ -226,10 +303,13 @@ export class ContactsApi {
memberMax: Number(r.maxMemberCount ?? 0n),
members: new Map(),
// #197: the detail is the only source of `level`; it also carries
// createTime + the notice preview (memo).
// createTime + the notice preview (memo). `description` is deliberately
// left unset — 0x88D_0 has no description tag, so for a group the bot
// hasn't joined there is nothing to report (#490).
createTime: Number(r.createTime ?? 0n),
level: Number(r.level ?? 0n),
memo: r.noticePreview ?? '',
allMuted: isGroupAllMuted(r.shutUpAllTimestamp),
};
}
@@ -241,27 +321,23 @@ export class ContactsApi {
}
private async fetchGroupMemberListUncached(groupId: number): Promise<GroupMemberInfo[]> {
// QQ's native group service obtains the robot classification separately
// from 0xFE7_3. Start both reads together so the metadata adds no serial
// round trip to paginated member fetches.
const robotSnapshotPromise = this.fetchRobotUinRanges(groupId);
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 ?? '',
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;
for (const member of members) {
member.isRobot = isRobotUin(member.uin, robotSnapshot.ranges);
}
this.ctx.identity.rememberGroupMembers(groupId, members);
return members;
}
@@ -282,44 +358,161 @@ export class ContactsApi {
return info;
}
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> {
const resp = await FetchGroupRequests.invoke(this.ctx, { filtered });
/** 企点企业资料卡(#404 后续 PR)。仅在判断命中的是企点账号后再调用。
* best-effort:非企点账号或拉取失败返回 null,不影响上层资料读取。 */
async fetchQidianCorpInfo(uin: number): Promise<QidianCorpInfo | null> {
return fetchQidianCorpInfoWire(this.ctx, uin);
}
async fetchGroupRequests(
filtered = false,
count = 50,
cursor = 0n,
): Promise<GroupRequestInfo[]> {
const resp = await FetchGroupRequests.invoke(this.ctx, { filtered, count, cursor });
const requests: GroupRequestInfo[] = [];
for (const raw of resp.requests ?? []) {
const groupId = raw.group?.groupUin ?? 0;
const targetUin = raw.target?.uin ?? 0;
const invitorUin = raw.invitor?.uin ?? 0;
const operatorUin = raw.operatorUser?.uin ?? 0;
const targetUid = raw.target?.uid
|| this.ctx.identity.findUidByUin(targetUin, groupId)
|| this.ctx.identity.findUidByUin(targetUin)
|| '';
const invitorUid = raw.invitor?.uid
|| this.ctx.identity.findUidByUin(invitorUin, groupId)
|| this.ctx.identity.findUidByUin(invitorUin)
|| '';
const operatorUid = raw.operatorUser?.uid
|| this.ctx.identity.findUidByUin(operatorUin, groupId)
|| this.ctx.identity.findUidByUin(operatorUin)
|| '';
const notifyType = raw.eventType ?? 0;
const operationType = groupRequestOperationType(notifyType);
const sequence = normalizeGroupRequestSequence(raw.sequence, groupId);
if (operationType === null) {
log.warn(
'unsupported group-request notification type: group=%d sequence=%s type=%d',
groupId,
String(raw.sequence ?? 0n),
notifyType,
);
}
requests.push({
groupId: raw.group?.groupUin ?? 0,
groupId,
groupName: raw.group?.groupName ?? '',
targetUid: raw.target?.uid ?? '',
targetUin: 0,
targetUid,
targetUin: targetUin
|| this.ctx.identity.findUinByUid(targetUid, groupId)
|| this.ctx.identity.findUinByUid(targetUid)
|| 0,
targetName: raw.target?.name ?? '',
invitorUid: raw.invitor?.uid ?? '',
invitorUin: 0,
invitorUid,
invitorUin: invitorUin
|| this.ctx.identity.findUinByUid(invitorUid, groupId)
|| this.ctx.identity.findUinByUid(invitorUid)
|| 0,
invitorName: raw.invitor?.name ?? '',
operatorUid: raw.operatorUser?.uid ?? '',
operatorUin: 0,
operatorUid,
operatorUin: operatorUin
|| this.ctx.identity.findUinByUid(operatorUid, groupId)
|| this.ctx.identity.findUinByUid(operatorUid)
|| 0,
operatorName: raw.operatorUser?.name ?? '',
sequence: Number(raw.sequence ?? 0),
sequence,
state: raw.state ?? 0,
eventType: raw.eventType ?? 0,
notifyType,
eventType: operationType ?? 0,
comment: raw.comment ?? '',
filtered,
operateTransInfo: raw.operateTransInfo && raw.operateTransInfo.length > 0
? raw.operateTransInfo
: undefined,
});
}
this.ctx.identity.rememberGroupRequests(requests);
return requests;
}
/** UID-form request list retained for correlating incoming UID-only pushes.
* Explicit list/actions use fetchGroupRequests(), which matches QQ's native
* numeric-account path and does not need profile lookups. */
async fetchGroupRequestsByUid(
filtered = false,
count = 50,
cursor = 0n,
): Promise<GroupRequestInfo[]> {
const resp = await FetchGroupRequestsByUid.invoke(this.ctx, { filtered, count, cursor });
const requests: GroupRequestInfo[] = [];
for (const raw of resp.requests ?? []) {
const groupId = raw.group?.groupUin ?? 0;
const targetUid = raw.target?.uid ?? '';
const invitorUid = raw.invitor?.uid ?? '';
const operatorUid = raw.operatorUser?.uid ?? '';
const notifyType = raw.eventType ?? 0;
const operationType = groupRequestOperationType(notifyType);
const sequence = normalizeGroupRequestSequence(raw.sequence, groupId);
if (operationType === null) {
log.warn(
'unsupported group-request notification type: group=%d sequence=%s type=%d',
groupId,
String(raw.sequence ?? 0n),
notifyType,
);
}
requests.push({
groupId,
groupName: raw.group?.groupName ?? '',
targetUid,
targetUin: this.ctx.identity.findUinByUid(targetUid, groupId)
?? this.ctx.identity.findUinByUid(targetUid)
?? 0,
targetName: raw.target?.name ?? '',
invitorUid,
invitorUin: this.ctx.identity.findUinByUid(invitorUid, groupId)
?? this.ctx.identity.findUinByUid(invitorUid)
?? 0,
invitorName: raw.invitor?.name ?? '',
operatorUid,
operatorUin: this.ctx.identity.findUinByUid(operatorUid, groupId)
?? this.ctx.identity.findUinByUid(operatorUid)
?? 0,
operatorName: raw.operatorUser?.name ?? '',
sequence,
state: raw.state ?? 0,
notifyType,
eventType: operationType ?? 0,
comment: raw.comment ?? '',
filtered,
operateTransInfo: raw.operateTransInfo && raw.operateTransInfo.length > 0
? raw.operateTransInfo
: undefined,
});
}
this.ctx.identity.rememberGroupRequests(requests);
return requests;
}
/** Live observation write. IncomingPacketPipeline and tests only. */
rememberGroupInviteCardSequence(groupUin: number, sequence: number): void {
if (groupUin > 0 && sequence > 0) this.groupInviteCardSeqs_.set(groupUin, sequence);
}
/** The approval msgseq captured from a private "qun.invite" card for this
* group, or undefined if none was seen. `set_group_add_request` uses it to
* approve a bot self-invite via 0x10c8 (eventType=2). See issue #125. */
getGroupInviteCardSequence(groupId: number): number | undefined {
return this.ctx.identity.getGroupInviteCardSequence(groupId);
return this.groupInviteCardSeqs_.get(groupId);
}
/** Resolve the group for a private invite-card msgseq. Numeric OneBot flags
* use this path because the card sequence is absent from 0x10C0. */
findGroupInviteCardGroupBySequence(sequence: number): number | undefined {
return this.ctx.identity.findGroupInviteCardGroupBySequence(sequence);
for (const [groupUin, rememberedSequence] of this.groupInviteCardSeqs_) {
if (rememberedSequence === sequence) return groupUin;
}
return undefined;
}
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
+171 -9
View File
@@ -4,10 +4,15 @@ import {
type AiVoiceCategory as NamespaceAiVoiceCategory,
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
import {
GetGroupTodoList,
type GroupTodoListItem as NamespaceGroupTodoListItem,
} from '@snowluma/protocol/oidb-services/extras/get-group-todo-list';
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
import { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon';
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
import { createLogger } from '@snowluma/common/logger';
import type { QQEventVariant } from '@snowluma/protocol/events';
import type { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
@@ -34,6 +39,7 @@ export interface PttTransInput {
// ─────────────── public types (re-exported from bridge.ts as before) ───
export type StrangerStatus = NamespaceStrangerStatus;
export type GroupTodoListItem = NamespaceGroupTodoListItem;
export const AiVoiceChatType = {
Unknown: 0,
@@ -49,12 +55,50 @@ export interface AiVoiceItem {
voiceExampleUrl: string;
}
export interface AiVoiceSendReceipt {
sequence: number;
}
const log = createLogger('Bridge.Extras');
const AI_VOICE_RECEIPT_TIMEOUT_MS = 5_000;
const AI_VOICE_CANDIDATE_LIMIT = 64;
const AI_VOICE_CLAIM_LIMIT = 256;
type GroupMessageEvent = Extract<QQEventVariant, { kind: 'group_message' }>;
function normalizeMediaUuid(value: unknown): string {
return typeof value === 'string' ? value.trim() : '';
}
function matchesAiVoiceEvent(node: MediaIndexNode, event: GroupMessageEvent): boolean {
const expectedUuid = normalizeMediaUuid(node.fileUuid);
if (!expectedUuid) return false;
for (const element of event.elements) {
if (element.type !== 'record') continue;
const actualUuid = normalizeMediaUuid(element.mediaNode?.fileUuid || element.fileId);
if (actualUuid === expectedUuid) return true;
}
return false;
}
function describeAiVoiceFingerprint(node: MediaIndexNode): string {
const uuid = normalizeMediaUuid(node.fileUuid);
if (uuid) return `uuid:${uuid.slice(-12)}`;
return 'missing';
}
export class ExtrasApi {
private readonly claimedAiVoiceReceiptKeys = new Set<string>();
constructor(private readonly ctx: BridgeContext) { }
// ─────────────── Group todo (0xF90) ───────────────
// ─────────────── Group todo query / mutations (0x9474 / 0xF90) ───────────────
async getGroupTodoList(groupId: number): Promise<GroupTodoListItem[]> {
const items = await GetGroupTodoList.invoke(this.ctx, { groupId });
log.debug('group todo list fetched group=%d count=%d', groupId, items.length);
return items;
}
setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' });
@@ -71,14 +115,20 @@ export class ExtrasApi {
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
/**
* Returns `null` on transport / decode failure rather than throwing,
* so the OneBot action can produce a clean retcode without try/catch
* gymnastics. Namespace throws on transport failure → swallow here.
* Keeps the action response user-safe while retaining the underlying
* failure in the service log for diagnosis.
*/
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
try {
return await GetStrangerStatus.invoke(this.ctx, { uin });
} catch {
const status = await GetStrangerStatus.invoke(this.ctx, { uin });
if (!status) log.warn('user status query returned no status target=%d', uin);
return status;
} catch (error) {
log.warn(
'user status query failed target=%d: %s',
uin,
error instanceof Error ? error.message : String(error),
);
return null;
}
}
@@ -94,9 +144,11 @@ export class ExtrasApi {
* the render is in-flight; we retry until a node materialises or the
* cap is hit. napcat uses the same 30-retry budget.
*
* The returned MediaIndexNode plugs directly into
* The returned node plugs directly into
* `apis.groupFile.getPttUrl`, which already handles every other
* download-URL fetch in SnowLuma.
* download-URL fetch in SnowLuma. The synthesis response does not contain a
* reliable message sequence; callers that need one must use `sendAiVoice`,
* which correlates the subsequent self-message receipt.
*/
async fetchAiVoice(
groupId: number,
@@ -109,11 +161,121 @@ export class ExtrasApi {
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
for (let i = 0; i < maxRetries; i++) {
const node = await FetchAiVoice.invoke(this.ctx, { groupId, voiceId, text, chatType, sessionId });
if (node) return node as MediaIndexNode;
if (node) {
log.debug(
'AI voice synthesis completed group=%d media=%s polls=%d',
groupId,
describeAiVoiceFingerprint(node),
i + 1,
);
return node as MediaIndexNode;
}
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
}
/**
* Publish an AI voice and wait for QQ's canonical self-message receipt.
*
* The 0x929B completion response carries the media node but, on live QQ,
* omits the group message sequence. Subscribe before publishing so an echo
* that wins the response race is buffered, then correlate by the exact media
* UUID. Never guess from content hashes or "the next voice in the group":
* concurrent requests can legitimately render byte-identical audio.
*/
async sendAiVoice(
groupId: number,
voiceId: string,
text: string,
chatType: AiVoiceChatType | number,
receiptTimeoutMs = AI_VOICE_RECEIPT_TIMEOUT_MS,
): Promise<AiVoiceSendReceipt> {
const candidates: GroupMessageEvent[] = [];
let candidatesOverflowed = false;
let expectedNode: MediaIndexNode | null = null;
let receiptSettled = false;
let resolveReceipt: ((event: GroupMessageEvent) => void) | null = null;
const receiptPromise = new Promise<GroupMessageEvent>((resolve) => {
resolveReceipt = resolve;
});
const claim = (event: GroupMessageEvent): boolean => {
if (receiptSettled) return false;
const key = `${event.groupId}:${event.msgSeq}:${event.msgId}`;
if (this.claimedAiVoiceReceiptKeys.has(key)) return false;
this.claimedAiVoiceReceiptKeys.add(key);
if (this.claimedAiVoiceReceiptKeys.size > AI_VOICE_CLAIM_LIMIT) {
const oldest = this.claimedAiVoiceReceiptKeys.values().next().value;
if (oldest !== undefined) this.claimedAiVoiceReceiptKeys.delete(oldest);
}
receiptSettled = true;
return true;
};
const accept = (event: GroupMessageEvent): void => {
if (event.groupId !== groupId || event.senderUin !== event.selfUin) return;
if (!event.elements.some(element => element.type === 'record')) return;
if (expectedNode && matchesAiVoiceEvent(expectedNode, event) && claim(event)) {
resolveReceipt?.(event);
return;
}
candidates.push(event);
if (candidates.length > AI_VOICE_CANDIDATE_LIMIT) {
candidates.shift();
candidatesOverflowed = true;
}
};
const unsubscribe = this.ctx.events.on('group_message', accept);
let timeout: ReturnType<typeof setTimeout> | null = null;
try {
const node = await this.fetchAiVoice(groupId, voiceId, text, chatType);
expectedNode = node;
const fingerprint = describeAiVoiceFingerprint(node);
if (fingerprint === 'missing') {
throw new Error('AI voice was published but QQ returned no exact media identifier for receipt correlation');
}
const buffered = candidates.find(event => matchesAiVoiceEvent(node, event) && claim(event));
if (!buffered && candidatesOverflowed) {
throw new Error(
`AI voice was published but receipt correlation overflowed after ${AI_VOICE_CANDIDATE_LIMIT} `
+ `unmatched self voice messages (group=${groupId} media=${fingerprint})`,
);
}
const event = buffered ?? await Promise.race([
receiptPromise,
new Promise<never>((_resolve, reject) => {
timeout = setTimeout(() => {
reject(new Error(
`AI voice was published but no matching group-message receipt arrived within ${receiptTimeoutMs}ms `
+ `(group=${groupId} media=${fingerprint})`,
));
}, receiptTimeoutMs);
timeout.unref?.();
}),
]);
if (!Number.isInteger(event.msgSeq) || event.msgSeq <= 0) {
throw new Error(`AI voice receipt carried invalid message sequence: ${event.msgSeq}`);
}
log.debug(
'AI voice receipt matched group=%d media=%s sequence=%d random=%d',
groupId,
fingerprint,
event.msgSeq,
event.msgId,
);
return {
sequence: event.msgSeq,
};
} finally {
if (timeout) clearTimeout(timeout);
unsubscribe();
}
}
// ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ───────────────
/**
+359 -113
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;
@@ -49,6 +152,99 @@ function entryToInfo(e: FlashFileEntry): FlashFileInfo {
};
}
const QFILE_SHARE_ORIGIN = 'https://qfile.qq.com';
const QFILE_SHARE_PAGE_MAX_BYTES = 2 * 1024 * 1024;
const QFILE_SHARE_TIMEOUT_MS = 20_000;
function officialQfileShareUrl(input: string): string {
const value = input.trim();
if (!value) throw new Error('get_fileset_id: share code is empty');
let code = value;
if (/^[a-z][a-z\d+.-]*:/i.test(value) || value.startsWith('//')) {
let parsed: URL;
try {
parsed = new URL(value);
} catch (error) {
throw new Error('get_fileset_id: expected an official QQ share URL', { cause: error });
}
if (
parsed.protocol !== 'https:'
|| parsed.hostname !== 'qfile.qq.com'
|| parsed.port !== ''
|| parsed.username !== ''
|| parsed.password !== ''
) {
throw new Error('get_fileset_id: expected an official QQ share URL');
}
const match = /^\/q\/([^/]+)\/?$/.exec(parsed.pathname);
if (!match) throw new Error('get_fileset_id: expected an official QQ share URL');
try {
code = decodeURIComponent(match[1]);
} catch (error) {
throw new Error('get_fileset_id: expected an official QQ share URL', { cause: error });
}
}
const hasForbiddenCharacter = Array.from(code).some((char) => {
const codePoint = char.codePointAt(0) ?? 0;
return codePoint <= 0x20 || codePoint === 0x7f || '/\\?#'.includes(char);
});
if (code.length > 256 || hasForbiddenCharacter) {
throw new Error('get_fileset_id: invalid share code');
}
return `${QFILE_SHARE_ORIGIN}/q/${encodeURIComponent(code)}`;
}
async function rejectShareResponse(response: Response, error: Error): Promise<never> {
try {
await response.body?.cancel(error);
} catch (cleanupError) {
throw new AggregateError([error, cleanupError], error.message);
}
throw error;
}
async function readSharePage(response: Response): Promise<string> {
const declaredLength = response.headers.get('content-length');
if (declaredLength !== null) {
if (!/^\d+$/.test(declaredLength)) {
await rejectShareResponse(response, new Error('get_fileset_id: invalid response length'));
}
if (Number(declaredLength) > QFILE_SHARE_PAGE_MAX_BYTES) {
await rejectShareResponse(response, new Error('get_fileset_id: share page too large'));
}
}
if (!response.body) throw new Error('get_fileset_id: share page response has no body');
const reader = response.body.getReader();
const decoder = new TextDecoder();
let total = 0;
let html = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (!value) continue;
total += value.byteLength;
if (total > QFILE_SHARE_PAGE_MAX_BYTES) {
const error = new Error('get_fileset_id: share page too large');
try {
await reader.cancel(error);
} catch (cleanupError) {
throw new AggregateError([error, cleanupError], error.message);
}
throw error;
}
html += decoder.decode(value, { stream: true });
}
html += decoder.decode();
return html;
} finally {
reader.releaseLock();
}
}
// 手写 PNG 编码(zlib 压缩,避免引入图像库)。缩略图用随机纯色,每次 SHA1 不同,
// 避免命中服务端秒传缓存。
const CRC_TABLE: Uint32Array = (() => {
@@ -123,21 +319,30 @@ export class FlashTransferApi {
* 多文件时每条 f6=序号、f14=主文件 fileId),按 fileIndex 选中后走 0x12a9 sub=200
* 拿主文件直链。0x93d3/0x93d4 的 downloadUrl 字段是缩略图(appid=14903/14902),
* 主文件必须走 0x12a9 sub=200。
*
* create 刚返回时 f14 可能还是空的(#364)。fileId 空则按
* FLASH_FILE_ID_RETRY_DELAYS_MS 再问 0x93d4;已经有 fileId 后 0x12a9 只打一枪。
*/
private async getFileDownload(
filesetUuid: string, fileIndex: number = 1,
): Promise<{ url: string; fileName: string; fileSize: number } | null> {
const metas = await GetDownloadUrl.invoke(this.ctx, { filesetUuid });
const meta = metas.find((m) => m.fileIndex === fileIndex);
if (!meta || !meta.fileId) return null;
const url = await GetFlashDownload.invoke(this.ctx, {
filesetUuid: meta.filesetUuid,
fileUuid: meta.fileUuid,
fileId: meta.fileId,
fileName: meta.fileName,
});
if (!url) return null;
return { url, fileName: meta.fileName, fileSize: meta.fileSize };
for (let attempt = 0; ; attempt++) {
const metas = await GetDownloadUrl.invoke(this.ctx, { filesetUuid });
const meta = metas.find((m) => m.fileIndex === fileIndex);
if (meta?.fileId) {
const url = await GetFlashDownload.invoke(this.ctx, {
filesetUuid: meta.filesetUuid,
fileUuid: meta.fileUuid,
fileId: meta.fileId,
fileName: meta.fileName,
});
if (!url) return null;
return { url, fileName: meta.fileName, fileSize: meta.fileSize };
}
const delay = FLASH_FILE_ID_RETRY_DELAYS_MS[attempt];
if (delay === undefined) return null;
await new Promise<void>((resolve) => setTimeout(resolve, delay));
}
}
/**
@@ -207,10 +412,26 @@ export class FlashTransferApi {
* 接口数据),直接 GET + 正则提取即可,无需复刻带签名的 trpc 调用。
*/
async getFilesetIdByCode(shareCode: string): Promise<string> {
const url = /^https?:\/\//i.test(shareCode) ? shareCode : `https://qfile.qq.com/q/${shareCode}`;
const resp = await fetch(url);
if (!resp.ok) throw new Error(`get_fileset_id: HTTP ${resp.status}`);
const html = await resp.text();
const url = officialQfileShareUrl(shareCode);
let resp: Response;
try {
resp = await fetch(url, {
redirect: 'manual',
signal: AbortSignal.timeout(QFILE_SHARE_TIMEOUT_MS),
});
} catch (error) {
if (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {
throw new Error('get_fileset_id: share page request timed out', { cause: error });
}
throw error;
}
if (resp.status >= 300 && resp.status < 400) {
await rejectShareResponse(resp, new Error('get_fileset_id: share page redirect is not allowed'));
}
if (!resp.ok) {
await rejectShareResponse(resp, new Error(`get_fileset_id: HTTP ${resp.status}`));
}
const html = await readSharePage(resp);
// 网页里 fileset_id 以 JSON 嵌入(引号可能被转义为 \"),正则兼容两种形态。
const m = /fileset_id\\?"\s*:\s*\\?"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/.exec(html);
if (!m) throw new Error('get_fileset_id: fileset_id not found in share page');
@@ -220,21 +441,13 @@ export class FlashTransferApi {
// ─────────────── 文件上传 ───────────────
/**
* 文件扩展名 → 闪传类型码映射。typeCode 用于 0x93cf f3,formatCode 用于
* 0x93d0 commit f7 与 0x12a9 filesetWrap.f7(两者同值)。mp4 → 2,rar/zip → 4。
* 未知扩展名按媒体类处理(formatCode=2),服务端按文件名扩展名判定。
* 文件扩展名 → 闪传类型码。typeCode 用于 0x93cf f3(卡片粗类:压缩包/媒体);
* formatCode 用于 0x93d0 commit f7 与 0x12a9 filesetWrap.f7,决定对端图标
* (png=26,mp4=2,zip=4,未知=11)。
*/
private static fileTypeCode(fileName: string): { typeCode: number; formatCode: number } {
const ext = fileName.toLowerCase().match(/\.([^.]+)$/)?.[1] ?? '';
switch (ext) {
case 'rar': return { typeCode: 2, formatCode: 4 };
case 'zip': return { typeCode: 6, formatCode: 4 };
case '7z': case 'gz': case 'tar': case 'bz2': return { typeCode: 2, formatCode: 4 };
case 'png': case 'jpg': case 'jpeg': case 'bmp': case 'gif': case 'webp':
case 'mp4': case 'mov': case 'avi': case 'mkv':
return { typeCode: 7, formatCode: 2 };
default: return { typeCode: 7, formatCode: 2 };
}
return { typeCode: flashApplyTypeCode(ext), formatCode: flashFormatCode(ext) };
}
/** 构造 sub=103 的 fileId(客户端生成的 protobuf,base64url 编码)。
@@ -268,11 +481,21 @@ export class FlashTransferApi {
* 多文件:0x93d0 的 f4 是 repeated,一个 commit 请求同时携带 fileset 内所有文件
* 条目,每条 f6=文件序号(1,2,3...)。commit 在上传前只发一次,之后 complete →
* 逐个 prepare/apply/sliceupload。prepare/apply 的 filesetWrap.f4 必须与 commit
* 的 f6 一致,否则文件不计入 fileset。多文件时 ApplyFileset 的 fileName 用
* 「<首文件名>等N个文件」、fileSize 用总和——服务端据此判定 fileset 为多文件。
* 的 f6 一致,否则文件不计入 fileset。ApplyFileset 的 fileName 是 fileset 显示名
* (卡片标题):有 name 用 name,否则单文件用首文件名、多文件用「<首文件名>等N个文件」。
* fileSize 用总和——服务端据此判定 fileset 为多文件。各文件在 commit 里用
* 条目上的 name(若有),否则用路径 basename。
*
* 源文件经 stageSourceToDisk 落到本地路径后流式哈希 / 分片读取,不再经
* loadBinarySource 整文件进内存。本地与 HTTP 上限与群文件相同(4 GiB);
* 内联 base64 仍按 1 GiB 封顶,因为 stage 解码时会占用等量 RAM。
*/
async createFlashTask(files: string | string[], _name?: string, _thumbPath?: string): Promise<{ filesetId: string }> {
const fileList = Array.isArray(files) ? files : [files];
async createFlashTask(
files: FlashTaskFileInput | FlashTaskFileInput[],
name?: string,
_thumbPath?: string,
): Promise<{ filesetId: string }> {
const fileList = normalizeFlashTaskInputs(files);
if (fileList.length === 0) throw new Error('create_flash_task: files is empty');
const uploader = {
uin: this.ctx.identity.uin,
@@ -281,104 +504,127 @@ export class FlashTransferApi {
// uid drops the fileset if this runs before warmup populated selfUid.
uid: await resolveSelfUid(this.ctx),
};
// 读取所有文件,每个分配 fileUuid + 序号 + formatCode
const items: { bytes: Uint8Array; fileName: string; fileUuid: string; fileIndex: number; formatCode: number }[] = [];
for (let i = 0; i < fileList.length; i++) {
const { bytes, fileName } = await loadBinarySource(fileList[i], 'flash-transfer');
const { formatCode } = FlashTransferApi.fileTypeCode(fileName);
items.push({ bytes: new Uint8Array(bytes), fileName, fileUuid: randomUUID(), fileIndex: i + 1, formatCode });
const items: StagedFlashItem[] = [];
try {
for (let i = 0; i < fileList.length; i++) {
const source = fileList[i]!.file;
if (!source) throw new Error('create_flash_task: files is empty');
const staged = await stageSourceToDisk(source, flashStageMaxBytes(source));
const fileName = flashFileDisplayName(fileList[i]!.name, staged.fileName);
const { formatCode } = FlashTransferApi.fileTypeCode(fileName);
items.push({
filePath: staged.filePath,
fileSize: staged.fileSize,
fileName,
fileUuid: randomUUID(),
fileIndex: i + 1,
formatCode,
guardStat: await fsp.stat(staged.filePath),
cleanup: () => staged.cleanup(),
});
if (staged.fileSize === 0) throw new Error('create_flash_task: file is empty');
}
// 申请 fileset。fileName 是卡片/面板上的 fileset 标题;各文件真实名走 commit。
// 未指定 name 时,多文件用「<首文件名>等N个文件」、fileSize 用总和,
// 服务端据此判定 fileset 为多文件,commit 的后续 entry 才会被计入。
const first = items[0];
const { typeCode } = FlashTransferApi.fileTypeCode(first.fileName);
const isMulti = items.length > 1;
const filesetName = name?.trim()
|| (isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName);
const totalSize = items.reduce((s, it) => s + it.fileSize, 0);
const apply = await ApplyFileset.invoke(this.ctx, {
fileName: filesetName, origName: filesetName,
fileSize: totalSize, typeCode, uploader,
});
const filesetUuid = apply.filesetUuid;
if (!filesetUuid) throw new Error('apply fileset failed: missing uuid');
// 一次性 commit 所有文件元数据(f4 repeated,每条 f6=序号)
const commitEntries = items.map((it) => ({
fileUuid: it.fileUuid, fileName: it.fileName, origName: it.fileName,
fileSize: it.fileSize, formatCode: it.formatCode, fileIndex: it.fileIndex,
}));
await CommitFile.invoke(this.ctx, { filesetUuid, entries: commitEntries });
await CompleteFileset.invoke(this.ctx, { filesetUuid });
// 两阶段上传:先全部 prepare+apply 注册 fileId,再全部 sliceupload 落盘。
const prepared: { it: StagedFlashItem; rkey: string; sha1StateV: Uint8Array[]; sliceCount: number }[] = [];
for (const it of items) {
const p = await this.prepareAndApply(filesetUuid, it);
if (p) prepared.push({ it, ...p });
}
for (const p of prepared) {
await assertUnchanged(p.it.filePath, p.it.guardStat);
await this.sliceuploadFile(
p.it.filePath, p.it.fileSize, p.rkey, p.sha1StateV, p.sliceCount, p.it.fileName,
);
}
// fileset 级缩略图(序号在主文件之后递增),主文件下载入口需要缩略图关联
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'png', items.length + 1);
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'jpg', items.length + 2);
await SetFilesetStatus.invoke(this.ctx, { filesetUuid });
return { filesetId: filesetUuid };
} finally {
await Promise.all(items.map((it) => it.cleanup()));
}
// 申请 fileset。多文件时 fileName 用「<首文件名>等N个文件」、fileSize 用总和,
// 服务端据此判定 fileset 为多文件,commit 的后续 entry 才会被计入。
const first = items[0];
const { typeCode } = FlashTransferApi.fileTypeCode(first.fileName);
const isMulti = items.length > 1;
const filesetName = isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName;
const totalSize = items.reduce((s, it) => s + it.bytes.length, 0);
const apply = await ApplyFileset.invoke(this.ctx, {
fileName: filesetName, origName: filesetName,
fileSize: totalSize, typeCode, uploader,
});
const filesetUuid = apply.filesetUuid;
if (!filesetUuid) throw new Error('apply fileset failed: missing uuid');
// 一次性 commit 所有文件元数据(f4 repeated,每条 f6=序号)
const commitEntries = items.map((it) => ({
fileUuid: it.fileUuid, fileName: it.fileName, origName: it.fileName,
fileSize: it.bytes.length, formatCode: it.formatCode, fileIndex: it.fileIndex,
}));
await CommitFile.invoke(this.ctx, { filesetUuid, entries: commitEntries });
await CompleteFileset.invoke(this.ctx, { filesetUuid });
// 两阶段上传:先全部 prepare+apply 注册 fileId,再全部 sliceupload 落盘。
const prepared: { it: typeof items[0]; rkey: string; sha1StateV: Uint8Array[]; sliceCount: number }[] = [];
for (const it of items) {
const p = await this.prepareAndApply(filesetUuid, it.bytes, it.fileName, it.fileUuid, it.fileIndex, it.formatCode);
if (p) prepared.push({ it, ...p });
}
for (const p of prepared) {
await this.sliceuploadFile(p.it.bytes, p.rkey, p.sha1StateV, p.sliceCount, p.it.fileName);
}
// fileset 级缩略图(序号在主文件之后递增),主文件下载入口需要缩略图关联
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'png', items.length + 1);
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'jpg', items.length + 2);
await SetFilesetStatus.invoke(this.ctx, { filesetUuid });
return { filesetId: filesetUuid };
}
/**
* 阶段1:prepare(拿 rkey)+ apply(注册 fileId)。返回 sliceupload 所需的 rkey/sha1state。
* 秒传(rkey=null)返回 null,调用方跳过 sliceupload。
* 阶段1:流式哈希 + prepare(拿 rkey)+ apply(注册 fileId)。
* 秒传时 prepare 不回 rkey,仍必须 apply,否则 fileset 会一直停在等待上传;
* 返回 null 只表示调用方跳过 sliceupload。
*/
private async prepareAndApply(
filesetUuid: string, bytes: Uint8Array, fileName: string, fileUuid: string, fileIndex: number, formatCode: number,
filesetUuid: string, it: StagedFlashItem,
): Promise<{ rkey: string; sha1StateV: Uint8Array[]; sliceCount: number } | null> {
const fileSize = bytes.length;
const hashes = computeHashes(bytes);
const SLICE_SIZE = 1024 * 1024;
const sliceCount = Math.ceil(fileSize / SLICE_SIZE);
const sha1StateV = computeSha1StateV(bytes, sliceCount, SLICE_SIZE);
const hashes = await hashFlashFileStreaming(it.filePath);
await assertUnchanged(it.filePath, it.guardStat);
const rkey = await PrepareUpload.invoke(this.ctx, {
filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex, fileIndex, formatCode,
filesetUuid, fileUuid: it.fileUuid, fileName: it.fileName, fileSize: it.fileSize,
sha1: hashes.sha1Hex, fileIndex: it.fileIndex, formatCode: it.formatCode,
});
if (rkey === null) return null; // 秒传
const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize);
const fileId = FlashTransferApi.buildFileId(hashes.sha1, it.fileSize);
await ApplyUpload.invoke(this.ctx, {
filesetUuid, fileUuid, fileId, fileName, fileSize,
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex, formatCode,
filesetUuid, fileUuid: it.fileUuid, fileId, fileName: it.fileName, fileSize: it.fileSize,
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex: it.fileIndex, formatCode: it.formatCode,
});
return { rkey, sha1StateV, sliceCount };
if (rkey === null) return null;
return { rkey, sha1StateV: hashes.sha1StateV, sliceCount: hashes.sliceCount };
}
/**
* 阶段2:sliceupload 分片上传(所有文件 prepare+apply 完成后调用)。
* 阶段2:从磁盘按 1 MiB 切片 POST sliceupload(所有文件 prepare+apply 完成后调用)。
*/
private async sliceuploadFile(
bytes: Uint8Array, rkey: string, sha1StateV: Uint8Array[], sliceCount: number, fileName: string,
filePath: string, fileSize: number, rkey: string,
sha1StateV: Uint8Array[], sliceCount: number, fileName: string,
): Promise<void> {
const fileSize = bytes.length;
const SLICE_SIZE = 1024 * 1024;
for (let i = 0; i < sliceCount; i++) {
const start = i * SLICE_SIZE;
const chunk = bytes.subarray(start, Math.min(start + SLICE_SIZE, fileSize));
const chunkLen = chunk.length;
const chunkSha1 = new Uint8Array(createHash('sha1').update(Buffer.from(chunk)).digest());
const body: FlashSliceUploadBody = {
field1: 0,
appid: 14901,
field3: 2,
payload: {
field1: {},
rkey,
start,
end: start + chunkLen - 1,
sha1: chunkSha1,
sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) },
chunk: new Uint8Array(chunk),
},
};
const bodyBytes = protobuf_encode<FlashSliceUploadBody>(body);
await this.postSliceupload(bodyBytes, `${fileName} slice ${i}`);
const src = await FileChunkSource.open(filePath, fileSize);
try {
for (let i = 0; i < sliceCount; i++) {
const start = i * FLASH_SLICE_SIZE;
const chunkLen = Math.min(FLASH_SLICE_SIZE, fileSize - start);
const chunk = await src.read(start, chunkLen);
const chunkSha1 = new Uint8Array(createHash('sha1').update(Buffer.from(chunk)).digest());
const body: FlashSliceUploadBody = {
field1: 0,
appid: 14901,
field3: 2,
payload: {
field1: {},
rkey,
start,
end: start + chunkLen - 1,
sha1: chunkSha1,
sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) },
chunk: new Uint8Array(chunk),
},
};
const bodyBytes = protobuf_encode<FlashSliceUploadBody>(body);
await this.postSliceupload(bodyBytes, `${fileName} slice ${i}`);
}
} finally {
await src.close();
}
}
@@ -432,12 +678,12 @@ export class FlashTransferApi {
filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex,
fileIndex, formatCode: thumbFormatCode, thumbType, width, height,
});
if (rkey === null) return; // 秒传
const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize, appid);
await ApplyUpload.invoke(this.ctx, {
filesetUuid, fileUuid, fileId, fileName, fileSize,
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex, formatCode: thumbFormatCode, thumbType, width, height,
});
if (rkey === null) return;
// sliceupload(缩略图小,1 片,Sha1StateV=[标准 SHA1])
const sha1StateV = computeSha1StateV(new Uint8Array(thumbBytes), 1, fileSize);
const body: FlashSliceUploadBody = {
+47 -57
View File
@@ -11,7 +11,10 @@ import type {
import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { ForwardNodePayload, MessageElement, MessageElementOf } from '@snowluma/protocol/events';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
import {
assertWindowShakeSendPolicy,
MessageElementValidationError,
} from '@snowluma/protocol/element-manifest';
import { parseMsgPush } from '@snowluma/protocol/msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { randomUUID } from 'crypto';
@@ -106,10 +109,10 @@ async function buildForwardPushBody(
// long-msg upload service stores the bytes verbatim and the
// receiver decodes them through the normal msg-push path.
const sendCtx = groupId !== undefined
? { bridge, groupId, forwardFake: true }
? { bridge, groupId, forwardFake: true, scene: 'forward' as const }
: userUid
? { bridge, userUid, forwardFake: true }
: { bridge, forwardFake: true };
? { bridge, userUid, forwardFake: true, scene: 'forward' as const }
: { bridge, forwardFake: true, scene: 'forward' as const };
const elems = await buildSendElems(node.elements, sendCtx);
const now = Math.floor(Date.now() / 1000);
const random = Math.floor(Math.random() * 0x7fffffff) >>> 0;
@@ -230,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 })),
};
}
@@ -282,10 +278,24 @@ function assertPrivateForwardFileCapacity(nodes: ForwardNodePayload[]): void {
}
}
function assertNoWindowShakeInForward(nodes: ForwardNodePayload[]): void {
for (const node of nodes) {
assertWindowShakeSendPolicy(
node.elements.filter((element) => element.type === 'poke').length,
node.elements.length,
'forward',
);
if (node.innerForward) assertNoWindowShakeInForward(node.innerForward);
}
}
export class ForwardApi {
constructor(private readonly ctx: BridgeContext) { }
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
// Reject the complete recursive tree before identity resolution, media
// upload, or long-message upload. Window shake has no forward wire form.
assertNoWindowShakeInForward(nodes);
// A c2c RichText owns exactly one msgContent/FileExtra payload. Validate
// the entire recursive tree before any file/media/long-message upload so a
// second file cannot be uploaded and then silently discarded.
@@ -461,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);
}
@@ -531,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'),
})));
@@ -562,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));
@@ -837,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]));
}
+74 -14
View File
@@ -1,4 +1,7 @@
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';
import { GetDoubtBuddyReq, type DoubtBuddyRequest } from '@snowluma/protocol/oidb-services/friend/get-doubt-buddy-req';
import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request';
@@ -8,6 +11,8 @@ import type { BridgeContext } from '../bridge-context';
export type { DoubtBuddyRequest };
const log = createLogger('Bridge.Friend');
export class FriendApi {
constructor(private readonly ctx: BridgeContext) { }
@@ -20,30 +25,85 @@ 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 });
// Refresh friend cache after deletion so subsequent reads don't
// surface a ghost entry. Best-effort: a transient OIDB hiccup here
// shouldn't make the delete itself look failed.
try { await this.ctx.apis.contacts.fetchFriendList(); } catch { /* ignore */ }
// The server-side delete has already completed. A refresh failure must be
// visible, but throwing here would misreport the delete itself as failed
// and encourage callers to repeat a destructive request.
try {
await this.ctx.apis.contacts.fetchFriendList();
} catch (err: unknown) {
log.warn(
'friend-list refresh failed after deleting user=%d: %s',
userId,
err instanceof Error ? err.message : String(err),
);
}
}
setRemark(userId: number, remark: string): Promise<void> {
return SetFriendRemark.invoke(this.ctx, { userId, remark });
async setRemark(userId: number, remark: string): Promise<void> {
if (findDatalineDeviceByUin(userId)) {
throw new Error('this contact does not support remarks');
}
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));
}
}
+214 -3
View File
@@ -1,4 +1,5 @@
import { GetAtAllRemain } from '@snowluma/protocol/oidb-services/group-admin/get-at-all-remain';
import { FetchGroupDetail } from '@snowluma/protocol/oidb-services/contacts/fetch-group-detail';
import { KickMember } from '@snowluma/protocol/oidb-services/group-admin/kick-member';
import { KickMembers } from '@snowluma/protocol/oidb-services/group-admin/kick-members';
import { LeaveGroup } from '@snowluma/protocol/oidb-services/group-admin/leave-group';
@@ -10,11 +11,59 @@ import { SetAdmin } from '@snowluma/protocol/oidb-services/group-admin/set-admin
import { SetGroupName } from '@snowluma/protocol/oidb-services/group-admin/set-group-name';
import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set-group-remark';
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
import { FetchGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/get-group-ext-info';
import {
decodeMemberInvitePolicy,
MEMBER_INVITE_PRIVILEGE_MASK,
mergeMemberInvitePrivilegeFlag,
SetMemberInvitePolicy,
type GroupMemberInvitePolicy,
} from '@snowluma/protocol/oidb-services/group-admin/set-member-invite-policy';
import {
decodeGroupHistoryVisibility,
SetNewMemberHistoryVisibility,
} from '@snowluma/protocol/oidb-services/group-admin/set-new-member-history-visibility';
import {
decodeGroupMemberPermissions,
GROUP_MEMBER_PERMISSION_MASKS,
mergeGroupMemberPermission,
SetMemberPermission,
type GroupMemberPermission,
} from '@snowluma/protocol/oidb-services/group-admin/set-member-permission';
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
import { GetGroupCategoryTags } from '@snowluma/protocol/oidb-services/group-admin/get-group-category-tags';
import { AddGroupCategoryTag } from '@snowluma/protocol/oidb-services/group-admin/add-group-category-tag';
import { DeleteGroupCategoryTag } from '@snowluma/protocol/oidb-services/group-admin/delete-group-category-tag';
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
import { ModifyGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/modify-group-ext-info';
import { OidbError } from '@snowluma/protocol/oidb-service';
import type { BridgeContext } from '../bridge-context';
/** QQ only accepts this write from the group owner (#411). */
export const MEMBER_PERMISSIONS_OWNER_ONLY =
'only the group owner can change group member permissions';
export type GroupAdminSettings = {
add_type: number;
group_question: string;
group_answer: string;
robot_member_switch: number;
robot_member_examine: number;
member_invite_policy: GroupMemberInvitePolicy;
allow_member_upload_album: boolean;
allow_member_temporary_session: boolean;
allow_member_create_group: boolean;
new_member_history_visible: boolean;
no_finger_open: number;
no_code_finger_open: number;
};
export interface GroupMemberPermissions {
allowMemberUploadAlbum?: boolean;
allowMemberTemporarySession?: boolean;
allowMemberCreateGroup?: boolean;
}
export class GroupAdminApi {
constructor(private readonly ctx: BridgeContext) { }
@@ -23,6 +72,33 @@ export class GroupAdminApi {
return ModifyGroupExtInfo.invoke(this.ctx, { groupId, robotMemberSwitch, robotMemberExamine });
}
async getAdminSettings(groupId: number): Promise<GroupAdminSettings> {
const [detail, robot] = await Promise.all([
FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }),
FetchGroupExtInfo.invoke(this.ctx, { groupId }),
]);
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(`unable to read group admin settings for group ${groupId}`);
}
const privilegeFlag = results.privilegeFlag ?? 0;
const permissions = decodeGroupMemberPermissions(privilegeFlag);
return {
add_type: results.addType ?? 0,
group_question: results.question ?? '',
group_answer: results.answer ?? '',
robot_member_switch: robot.robotMemberSwitch,
robot_member_examine: robot.robotMemberExamine,
member_invite_policy: decodeMemberInvitePolicy(privilegeFlag),
allow_member_upload_album: permissions.allowMemberUploadAlbum,
allow_member_temporary_session: permissions.allowMemberTemporarySession,
allow_member_create_group: permissions.allowMemberCreateGroup,
new_member_history_visible: decodeGroupHistoryVisibility(results.groupFlagExt4 ?? 0),
no_finger_open: results.noFingerOpen ?? 0,
no_code_finger_open: results.noCodeFingerOpen ?? 0,
};
}
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
}
@@ -31,19 +107,154 @@ export class GroupAdminApi {
return MuteAll.invoke(this.ctx, { groupId, enable });
}
setAddOption(groupId: number, addType: number): Promise<void> {
return SetAddOption.invoke(this.ctx, { groupId, addType });
setAddOption(
groupId: number,
addType: number,
groupQuestion?: string,
groupAnswer?: string,
): Promise<void> {
return SetAddOption.invoke(this.ctx, { groupId, addType, groupQuestion, groupAnswer });
}
setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise<void> {
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
}
listCategoryTags(groupClass: number): Promise<{ tags: { id: number; name: string; type: number }[] }> {
return GetGroupCategoryTags.invoke(this.ctx, { groupClass });
}
addCategoryTag(groupClass: number, name: string): Promise<void> {
return AddGroupCategoryTag.invoke(this.ctx, { groupClass, name });
}
removeCategoryTag(groupClass: number, name: string): Promise<void> {
return DeleteGroupCategoryTag.invoke(this.ctx, { groupClass, name });
}
async setMemberInvitePolicy(groupId: number, policy: GroupMemberInvitePolicy): Promise<void> {
const currentPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
groupId,
'group member invite policy',
'before update',
);
const expectedPrivilegeFlag = mergeMemberInvitePrivilegeFlag(currentPrivilegeFlag, policy);
await SetMemberInvitePolicy.invoke(this.ctx, {
groupId,
currentPrivilegeFlag,
policy,
});
const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
groupId,
'group member invite policy',
'after update',
);
const mask = BigInt(MEMBER_INVITE_PRIVILEGE_MASK);
if ((BigInt(actualPrivilegeFlag) & mask) !== (BigInt(expectedPrivilegeFlag) & mask)) {
throw new Error(`group member invite policy was not applied for group ${groupId}`);
}
}
private async fetchGroupPrivilegeFlag(groupId: number, setting: string, phase: string): Promise<number> {
return (await this.fetchGroupPrivilegeState(groupId, setting, phase)).privilegeFlag;
}
private async fetchGroupPrivilegeState(
groupId: number,
setting: string,
phase: string,
): Promise<{ privilegeFlag: number; ownerUid?: string }> {
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(`unable to read ${setting} ${phase} for group ${groupId}`);
}
return {
privilegeFlag: results.privilegeFlag ?? 0,
ownerUid: results.ownerUid,
};
}
async setMemberPermissions(groupId: number, permissions: GroupMemberPermissions): Promise<void> {
const updates: ReadonlyArray<readonly [GroupMemberPermission, boolean | undefined]> = [
['upload_album', permissions.allowMemberUploadAlbum],
['temporary_session', permissions.allowMemberTemporarySession],
['create_group', permissions.allowMemberCreateGroup],
];
if (!updates.some(([, allow]) => allow !== undefined)) {
throw new Error('at least one member permission must be specified');
}
const before = await this.fetchGroupPrivilegeState(
groupId,
'group member permissions',
'before update',
);
const selfUid = this.ctx.identity.selfUid;
if (selfUid && before.ownerUid && selfUid !== before.ownerUid) {
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
}
let expectedPrivilegeFlag = before.privilegeFlag;
let combinedMask = 0n;
for (const [permission, allow] of updates) {
if (allow === undefined) continue;
try {
await SetMemberPermission.invoke(this.ctx, {
groupId,
currentPrivilegeFlag: expectedPrivilegeFlag,
permission,
allow,
});
} catch (error) {
if (error instanceof OidbError && error.code === 1287) {
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
}
throw error;
}
expectedPrivilegeFlag = mergeGroupMemberPermission(expectedPrivilegeFlag, permission, allow);
combinedMask |= BigInt(GROUP_MEMBER_PERMISSION_MASKS[permission]);
}
const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
groupId,
'group member permissions',
'after update',
);
if ((BigInt(actualPrivilegeFlag) & combinedMask) !== (BigInt(expectedPrivilegeFlag) & combinedMask)) {
throw new Error(`group member permissions were not applied for group ${groupId}`);
}
}
async setNewMemberHistoryVisibility(groupId: number, visible: boolean): Promise<void> {
await SetNewMemberHistoryVisibility.invoke(this.ctx, { groupId, visible });
const actualGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'after update');
if (decodeGroupHistoryVisibility(actualGroupFlagExt4) !== visible) {
throw new Error(`new-member history visibility was not applied for group ${groupId}`);
}
}
private async fetchGroupFlagExt4(groupId: number, phase: string): Promise<number> {
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(`unable to read new-member history visibility ${phase} for group ${groupId}`);
}
return results.groupFlagExt4 ?? 0;
}
setAddRequest(
groupId: number, sequence: number, eventType: number,
approve: boolean, reason = '', filtered = false,
operateTransInfo?: Uint8Array,
): Promise<void> {
return SetAddRequest.invoke(this.ctx, { groupId, sequence, eventType, approve, reason, filtered });
return SetAddRequest.invoke(this.ctx, {
groupId, sequence, eventType, approve, reason, filtered, operateTransInfo,
});
}
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
+630 -56
View File
@@ -1,19 +1,145 @@
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,
DoQunCommentResponse,
DoQunLikeRequest,
DoQunLikeResponse,
GetAlbumListRequest,
GetAlbumListResponse,
GetQunFeedDetailRequest,
GetQunFeedDetailResponse,
GroupAlbumInfo as GroupAlbumInfoWire,
QunFeedCellCommon,
GetMediaListRequest,
GetMediaListResponse,
MediaInfo,
UrlInfo,
} from '@snowluma/proto-defs/oidb-actions/group-album';
import { getGroupAlbumList, 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();
}
function uint64ToSafeNumber(value: bigint | undefined, fieldName: string): number {
const normalized = value ?? 0n;
if (normalized > BigInt(Number.MAX_SAFE_INTEGER)) {
throw new Error(`group album ${fieldName} exceeds Number.MAX_SAFE_INTEGER: ${normalized}`);
}
return Number(normalized);
}
function normalizeAlbumCreator(creator: AlbumCreator | undefined): QunAlbumCreator | undefined {
if (!creator) return undefined;
return {
uid: creator.uid ?? '',
nick: creator.nick ?? '',
is_sweet: creator.isSweet ?? false,
is_special: creator.isSpecial ?? false,
is_super_like: creator.isSuperLike ?? false,
custom_id: creator.customId ?? '',
poly_id: creator.polyId ?? '',
portrait: creator.portrait ?? '',
can_follow: creator.canFollow ?? 0,
isfollowed: creator.isFollowed ?? 0,
uin: creator.uin ?? '',
ditto_uin: creator.dittoUin ?? '',
};
}
function normalizeCoverUrl(url: UrlInfo | null | undefined): QunAlbumCoverUrl | null {
if (!url) return null;
return {
url: url.url ?? '',
width: url.width ?? 0,
height: url.height ?? 0,
};
}
function normalizeAlbumCover(cover: MediaInfo | undefined): QunAlbumCover | null {
if (!cover) return null;
const image = cover.image;
return {
type: cover.type ?? 0,
image: image ? {
name: image.name ?? '',
sloc: image.sloc ?? '',
lloc: image.lloc ?? '',
photoUrls: (image.photoUrls ?? []).map((photoUrl) => ({
spec: photoUrl.spec ?? 0,
url: normalizeCoverUrl(photoUrl.url),
})),
defaultUrl: normalizeCoverUrl(image.defaultUrl),
isGif: image.isGif ?? false,
hasRaw: image.hasRaw ?? false,
} : null,
};
}
function normalizeQunAlbum(album: GroupAlbumInfoWire): QunAlbumInfo {
const normalized: QunAlbumInfo = {
album_id: album.albumId ?? '',
owner: album.owner ?? '',
name: album.name ?? '',
desc: album.description ?? '',
create_time: uint64ToString(album.createTime),
modify_time: uint64ToString(album.modifyTime),
last_upload_time: uint64ToString(album.lastUploadTime),
upload_number: uint64ToString(album.uploadNumber),
cover: normalizeAlbumCover(album.cover),
top_flag: uint64ToString(album.topFlag),
busi_type: album.busiType ?? 0,
status: album.status ?? 0,
allow_share: album.allowShare ?? false,
is_subscribe: album.isSubscribe ?? false,
bitmap: album.bitmap ?? '',
is_share_album: album.isShareAlbum ?? false,
qz_album_type: album.qzAlbumType ?? 0,
cover_type: album.coverType ?? 0,
default_desc: album.defaultDesc ?? '',
sort_type: album.sortType ?? 0,
};
const creator = normalizeAlbumCreator(album.creator);
if (creator) normalized.creator = creator;
return normalized;
}
function toLegacyAlbum(album: GroupAlbumInfoWire): GroupAlbumInfo {
const creator = normalizeAlbumCreator(album.creator);
return {
id: album.albumId ?? '',
name: album.name ?? '',
picNum: uint64ToSafeNumber(album.uploadNumber, 'upload_number'),
createTime: uint64ToSafeNumber(album.createTime, 'create_time'),
desc: album.description ?? '',
owner: album.owner ?? '',
createuin: creator?.uin || album.owner || creator?.uid || '',
// QQ NT's AlbumService returns this as a normal UTF-8 protobuf string.
// Unlike the legacy Qzone HTTP endpoint, it does not rewrite Unicode
// emoji into ambiguous [em]...[/em] tags.
createnickname: creator?.nick ?? '',
last_upload_time: uint64ToSafeNumber(album.lastUploadTime, 'last_upload_time'),
cover: normalizeAlbumCover(album.cover),
};
}
function convertBigIntToString(obj: unknown): JsonValue {
if (obj === null || obj === undefined) return null;
@@ -33,13 +159,107 @@ function convertBigIntToString(obj: unknown): JsonValue {
export class GroupAlbumApi {
constructor(private readonly ctx: BridgeContext) { }
// 列出群相册(基于 qzone.qq.com 的 HTTP Cookie)。
private async fetchAlbumList(groupId: number, attachInfo: string): Promise<GroupAlbumWireResult> {
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const body = protobuf_encode<GetAlbumListRequest>({
seq: GET_ALBUM_LIST_SEQ,
field2: new Uint8Array(0),
field3: new Uint8Array(0),
data: {
groupId: groupId.toString(),
attachInfo,
},
traceId,
extMap: [{ key: 'fc-appid', value: '100' }],
});
log.debug(
'get album list request: group=%d cursorChars=%d requestBytes=%d',
groupId,
attachInfo.length,
body.length,
);
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}`}`,
);
}
const response = protobuf_decode<GetAlbumListResponse>(result.responseData);
const resultCode = response.result ?? 0;
if (resultCode !== 0) {
throw new Error(
`get group album list failed: result=${resultCode}, error=${response.errorText || 'unknown'}`,
);
}
const normalized: GroupAlbumWireResult = {
albumList: response.data?.albumList ?? [],
attachInfo: response.data?.attachInfo ?? '',
hasMore: response.data?.hasMore ?? false,
};
log.debug(
'get album list response: group=%d albums=%d hasMore=%s cursorChars=%d responseBytes=%d',
groupId,
normalized.albumList.length,
String(normalized.hasMore),
normalized.attachInfo.length,
result.responseData.length,
);
return normalized;
}
/** QQ NT AlbumService-backed list, including its pagination cursor. */
async listQun(groupId: number, attachInfo = ''): Promise<QunAlbumListResult> {
const result = await this.fetchAlbumList(groupId, attachInfo);
return {
albumList: result.albumList.map(normalizeQunAlbum),
attachInfo: result.attachInfo,
hasMore: result.hasMore,
};
}
// OneBot compatibility shape used by get_group_album_list.
async list(groupId: number): Promise<GroupAlbumList> {
const groupCode = groupId.toString();
const uin = this.ctx.identity.uin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
const albumData = await getGroupAlbumList(cookieObject, groupCode, uin);
return albumData?.album || [];
const albumList: GroupAlbumList = [];
const seenCursors = new Set<string>();
let attachInfo = '';
let page = 0;
while (true) {
const result = await this.fetchAlbumList(groupId, attachInfo);
page += 1;
albumList.push(...result.albumList.map(toLegacyAlbum));
if (!result.hasMore) {
log.debug(
'get complete album list: group=%d pages=%d albums=%d',
groupId,
page,
albumList.length,
);
return albumList;
}
const nextAttachInfo = result.attachInfo;
if (!nextAttachInfo) {
throw new Error(
`get group album list pagination failed: group=${groupId} page=${page} `
+ 'hasMore=true but cursor is empty',
);
}
if (seenCursors.has(nextAttachInfo)) {
throw new Error(
`get group album list pagination failed: group=${groupId} repeated cursor at page ${page}`,
);
}
seenCursors.add(nextAttachInfo);
attachInfo = nextAttachInfo;
}
}
// 上传图片到现有相册(HTTP 分片上传)。
@@ -50,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)}`;
@@ -61,8 +288,8 @@ export class GroupAlbumApi {
groupId: groupId.toString(),
albumId,
field3: 0,
attachInfo,
field5: '',
field4: '',
pageInfo: attachInfo,
},
traceId,
extMap: [{ key: 'fc-appid', value: '100' }],
@@ -71,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) {
@@ -96,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,
},
},
@@ -135,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;
}
@@ -170,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,
@@ -208,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) {
@@ -226,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)}`;
@@ -236,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' }],
@@ -245,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) {
@@ -263,13 +489,361 @@ 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;
}
export type GroupAlbumList = NonNullable<Awaited<ReturnType<typeof getGroupAlbumList>>>['album'];
interface GroupAlbumWireResult {
albumList: GroupAlbumInfoWire[];
attachInfo: string;
hasMore: boolean;
}
export interface GroupAlbumInfo {
id: string;
name: string;
picNum: number;
createTime: number;
desc: string;
owner: string;
createuin: string;
createnickname: string;
last_upload_time: number;
cover: QunAlbumCover | null;
[key: string]: JsonValue;
}
export type GroupAlbumList = GroupAlbumInfo[];
export interface QunAlbumCreator {
uid: string;
nick: string;
is_sweet: boolean;
is_special: boolean;
is_super_like: boolean;
custom_id: string;
poly_id: string;
portrait: string;
can_follow: number;
isfollowed: number;
uin: string;
ditto_uin: string;
}
export interface QunAlbumCoverUrl extends JsonObject {
url: string;
width: number;
height: number;
}
export interface QunAlbumCoverPhotoUrl extends JsonObject {
spec: number;
url: QunAlbumCoverUrl | null;
}
export interface QunAlbumCoverImage extends JsonObject {
name: string;
sloc: string;
lloc: string;
photoUrls: QunAlbumCoverPhotoUrl[];
defaultUrl: QunAlbumCoverUrl | null;
isGif: boolean;
hasRaw: boolean;
}
export interface QunAlbumCover extends JsonObject {
type: number;
image: QunAlbumCoverImage | null;
}
export interface QunAlbumInfo {
album_id: string;
owner: string;
name: string;
desc: string;
create_time: string;
modify_time: string;
last_upload_time: string;
upload_number: string;
cover: QunAlbumCover | null;
creator?: QunAlbumCreator;
top_flag: string;
busi_type: number;
status: number;
allow_share: boolean;
is_subscribe: boolean;
bitmap: string;
is_share_album: boolean;
qz_album_type: number;
cover_type: number;
default_desc: string;
sort_type: number;
}
export interface QunAlbumListResult {
albumList: QunAlbumInfo[];
attachInfo: string;
hasMore: boolean;
}
export interface GroupAlbumCommentResult {
id: string;
+128 -144
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';
@@ -58,6 +57,9 @@ export interface GroupFolderInfo {
creator: number;
creatorName: string;
totalFileCount: number;
lastUploadTime: number;
lastUploader: number;
lastUploaderName: string;
}
export interface GroupFilesResult {
@@ -80,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)
@@ -393,51 +390,51 @@ export class GroupFileApi {
// md510MCheckSum in the same single pass.
const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES);
try {
if (staged.fileSize === 0) throw new Error('private file is empty');
if (staged.fileSize === 0) throw new Error('private file is empty');
const targetUid = await this.ctx.resolveUserUid(userId);
const selfUid = await resolveSelfUid(this.ctx);
const targetUid = await this.ctx.resolveUserUid(userId);
const selfUid = await resolveSelfUid(this.ctx);
const senderUin = toInt(this.ctx.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
const senderUin = toInt(this.ctx.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
const fileName = normalizeUploadFileName(name, staged.fileName);
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
const hashes = await hashFileStreaming(staged.filePath, { headLimit: MD5_HEAD_LIMIT });
const fileName = normalizeUploadFileName(name, staged.fileName);
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
const hashes = await hashFileStreaming(staged.filePath, { headLimit: MD5_HEAD_LIMIT });
const upload = await UploadPrivateFileRequest.invoke(this.ctx, {
senderUid: selfUid,
receiverUid: targetUid,
fileName,
fileSize: staged.fileSize,
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
md510MCheckSum: hashes.headMd5!,
});
ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined);
const upload = await UploadPrivateFileRequest.invoke(this.ctx, {
senderUid: selfUid,
receiverUid: targetUid,
fileName,
fileSize: staged.fileSize,
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
md510MCheckSum: hashes.headMd5!,
});
ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined);
const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null;
const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null;
if (!fileId) throw new Error('private file upload response missing file_id');
const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null;
const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null;
if (!fileId) throw new Error('private file upload response missing file_id');
// Cache the metadata so a later `send_private_msg` carrying just
// `{type:'file', file_id}` can resurrect the full c2c-file packet
// (NotOnlineFile { fileSize, fileMd5, fileName, fileHash }). Without
// this the recipient sees a 0-byte file because the OneBot send path
// has no way to recover those fields from the file_id alone.
this.ctx.rememberUploadedFile({
fileId,
scope: 'private',
userId,
fileName,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
fileHash: fileHash ?? '',
rememberedAt: Date.now(),
});
// Cache the metadata so a later `send_private_msg` carrying just
// `{type:'file', file_id}` can resurrect the full c2c-file packet
// (NotOnlineFile { fileSize, fileMd5, fileName, fileHash }). Without
// this the recipient sees a 0-byte file because the OneBot send path
// has no way to recover those fields from the file_id alone.
this.ctx.rememberUploadedFile({
fileId,
scope: 'private',
userId,
fileName,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
fileHash: fileHash ?? '',
rememberedAt: Date.now(),
});
if (!upload.boolFileExist && uploadFile) {
if (!upload.boolFileExist && uploadFile) {
// Host selection.
//
// Current QQ-NT server rollout has stopped populating the legacy
@@ -459,93 +456,93 @@ export class GroupFileApi {
// uploadDns), so we fall through to those after rtpMediaPlatform.
// Pair an HTTPS-flavored host with `uploadHttpsPort` if that's
// what we picked.
const rtpFirst = (Array.isArray(upload.rtpMediaPlatformUploadAddress)
const rtpFirst = (Array.isArray(upload.rtpMediaPlatformUploadAddress)
&& upload.rtpMediaPlatformUploadAddress[0])
? upload.rtpMediaPlatformUploadAddress[0] : null;
const rtpInIP = rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0
? int32ToIpv4Dotted(rtpFirst.inIP) : '';
const rtpInPort = rtpFirst && typeof rtpFirst.inPort === 'number'
? rtpFirst.inPort : 0;
const ipListFirst = (Array.isArray(upload.uploadIpList) && upload.uploadIpList[0])
? upload.uploadIpList[0] : '';
const uploadHost = (rtpInIP)
? upload.rtpMediaPlatformUploadAddress[0] : null;
const rtpInIP = rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0
? int32ToIpv4Dotted(rtpFirst.inIP) : '';
const rtpInPort = rtpFirst && typeof rtpFirst.inPort === 'number'
? rtpFirst.inPort : 0;
const ipListFirst = (Array.isArray(upload.uploadIpList) && upload.uploadIpList[0])
? upload.uploadIpList[0] : '';
const uploadHost = (rtpInIP)
|| (typeof upload.uploadIp === 'string' && upload.uploadIp)
|| (typeof upload.uploadDomain === 'string' && upload.uploadDomain)
|| (ipListFirst)
|| (typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain)
|| (typeof upload.uploadDns === 'string' && upload.uploadDns)
|| '';
const httpsHostUsed = !rtpInIP && !upload.uploadIp && !upload.uploadDomain && !ipListFirst
const httpsHostUsed = !rtpInIP && !upload.uploadIp && !upload.uploadDomain && !ipListFirst
&& typeof upload.uploadHttpsDomain === 'string' && !!upload.uploadHttpsDomain;
const uploadPort = rtpInIP && rtpInPort > 0
? rtpInPort
: httpsHostUsed && toInt(upload.uploadHttpsPort) > 0
? toInt(upload.uploadHttpsPort)
: toInt(upload.uploadPort);
if (!uploadHost || uploadPort <= 0) {
const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress)
? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e) => ({
outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort,
iPType: e.iPType,
})))
: '[]';
log.warn(
'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s',
rtpDump,
upload.uploadIp ?? '', upload.uploadDomain ?? '',
JSON.stringify(upload.uploadIpList ?? []),
upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '',
upload.uploadLanip ?? '', upload.uploadPort ?? 0,
upload.uploadHttpsPort ?? 0,
);
throw new Error('private file upload host is invalid');
}
const uploadPort = rtpInIP && rtpInPort > 0
? rtpInPort
: httpsHostUsed && toInt(upload.uploadHttpsPort) > 0
? toInt(upload.uploadHttpsPort)
: toInt(upload.uploadPort);
if (!uploadHost || uploadPort <= 0) {
const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress)
? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e) => ({
outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort,
iPType: e.iPType,
})))
: '[]';
log.warn(
'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s',
rtpDump,
upload.uploadIp ?? '', upload.uploadDomain ?? '',
JSON.stringify(upload.uploadIpList ?? []),
upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '',
upload.uploadLanip ?? '', upload.uploadPort ?? 0,
upload.uploadHttpsPort ?? 0,
);
throw new Error('private file upload host is invalid');
}
const ext = buildPrivateFileUploadExt(
senderUin,
fileName,
staged.fileSize,
hashes.md5,
hashes.sha1,
fileId,
upload.mediaPlatformUploadKey instanceof Uint8Array
? upload.mediaPlatformUploadKey
: (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)),
uploadHost,
uploadPort,
);
// Fail cleanly if the source changed since hashing, then stream the PUT
// from disk. Session BEFORE opening the handle so uploadHighwayHttp (the
// handle's owner) is the next call and always closes it.
await assertUnchanged(staged.filePath, guardStat);
const session = await fetchHighwaySession(bridge);
const chunkSource = await FileChunkSource.open(staged.filePath, staged.fileSize);
await uploadHighwayHttp(bridge, session, 95, chunkSource, hashes.md5, ext);
}
// Stage 3: publish the file as a c2c chat message. C2C files use
// `RichText.notOnlineFile` (parallel to `elems`), so we go through
// the dedicated `sendC2cFile` on MessageApi instead of `sendPrivate`
// which only knows about elems[]. NapCat does the same atomic
// upload+send dance — without it the file sits on the server and
// the recipient sees nothing.
if (publishFile) {
try {
await this.ctx.apis.message.sendC2cFile(userId, targetUid, {
fileId,
const ext = buildPrivateFileUploadExt(
senderUin,
fileName,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileHash: fileHash ?? '',
});
} catch (err) {
log.warn('private file uploaded (fileId=%s) but chat post failed: %s',
fileId, err instanceof Error ? err.message : String(err));
}
}
staged.fileSize,
hashes.md5,
hashes.sha1,
fileId,
upload.mediaPlatformUploadKey instanceof Uint8Array
? upload.mediaPlatformUploadKey
: (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)),
uploadHost,
uploadPort,
);
return { fileId, fileHash };
// Fail cleanly if the source changed since hashing, then stream the PUT
// from disk. Session BEFORE opening the handle so uploadHighwayHttp (the
// handle's owner) is the next call and always closes it.
await assertUnchanged(staged.filePath, guardStat);
const session = await fetchHighwaySession(bridge);
const chunkSource = await FileChunkSource.open(staged.filePath, staged.fileSize);
await uploadHighwayHttp(bridge, session, 95, chunkSource, hashes.md5, ext);
}
// Stage 3: publish the file as a c2c chat message. C2C files use
// `RichText.notOnlineFile` (parallel to `elems`), so we go through
// the dedicated `sendC2cFile` on MessageApi instead of `sendPrivate`
// which only knows about elems[]. NapCat does the same atomic
// upload+send dance — without it the file sits on the server and
// the recipient sees nothing.
if (publishFile) {
try {
await this.ctx.apis.message.sendC2cFile(userId, targetUid, {
fileId,
fileName,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileHash: fileHash ?? '',
});
} catch (err) {
log.warn('private file uploaded (fileId=%s) but chat post failed: %s',
fileId, err instanceof Error ? err.message : String(err));
}
}
return { fileId, fileHash };
} finally {
await staged.cleanup();
}
@@ -565,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;
@@ -592,6 +588,8 @@ export class GroupFileApi {
const folder = item.folderInfo;
const creator = toInt(folder.creatorUin);
const cached = this.ctx.identity.findGroupMember(groupId, creator);
const lastUploader = toInt(folder.modifierUin);
const lastUploaderCached = this.ctx.identity.findGroupMember(groupId, lastUploader);
folders.push({
folderId: typeof folder.folderId === 'string' ? folder.folderId : '',
folderName: typeof folder.folderName === 'string' ? folder.folderName : '',
@@ -602,6 +600,12 @@ export class GroupFileApi {
|| cached?.nickname
|| '',
totalFileCount: toInt(folder.totalFileCount),
lastUploadTime: toInt(folder.modifiedTime),
lastUploader,
lastUploaderName: (typeof folder.modifierName === 'string' && folder.modifierName)
|| lastUploaderCached?.card
|| lastUploaderCached?.nickname
|| '',
});
}
}
@@ -616,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 ───────────────
@@ -0,0 +1,108 @@
export interface HistoryRequestGateClock {
now(): number;
sleep(ms: number, signal?: AbortSignal): Promise<void>;
}
const SYSTEM_CLOCK: HistoryRequestGateClock = {
now: () => Date.now(),
sleep: (ms, signal) => abortableSleep(ms, signal),
};
/**
* Process-wide history request gate.
*
* The gate owns the network operation, not just a preceding delay. This keeps
* concurrent history callers serialized and preserves the stricter spacing on
* both sides of an automatic history-sync request.
*/
export class HistoryRequestGate {
private tail: Promise<void> = Promise.resolve();
private lastStartedAt: number | null = null;
private nextAllowedAt = 0;
constructor(private readonly clock: HistoryRequestGateClock = SYSTEM_CLOCK) {}
run<T>(
minimumGapMs: number,
operation: () => Promise<T>,
signal?: AbortSignal,
): Promise<T> {
if (!Number.isSafeInteger(minimumGapMs) || minimumGapMs < 0) {
return Promise.reject(new Error(`history request gap is invalid: ${String(minimumGapMs)}`));
}
let operationStarted = false;
const result = this.tail.then(async () => {
throwIfAborted(signal);
const now = this.clock.now();
const requestedBoundary = this.lastStartedAt === null
? now
: this.lastStartedAt + minimumGapMs;
const wait = Math.max(this.nextAllowedAt, requestedBoundary) - now;
if (wait > 0) await this.clock.sleep(wait, signal);
throwIfAborted(signal);
const startedAt = this.clock.now();
this.lastStartedAt = startedAt;
this.nextAllowedAt = startedAt + minimumGapMs;
operationStarted = true;
return operation();
});
this.tail = result.then(
() => undefined,
() => undefined,
);
return signal
? rejectWhileQueuedOnAbort(result, signal, () => operationStarted)
: result;
}
}
function throwIfAborted(signal?: AbortSignal): void {
if (signal?.aborted) {
throw signal.reason ?? new Error('history request aborted');
}
}
function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
throwIfAborted(signal);
if (!signal) {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
signal.removeEventListener('abort', onAbort);
resolve();
}, ms);
const onAbort = () => {
clearTimeout(timer);
signal.removeEventListener('abort', onAbort);
reject(signal.reason ?? new Error('history request aborted'));
};
signal.addEventListener('abort', onAbort, { once: true });
});
}
function rejectWhileQueuedOnAbort<T>(
result: Promise<T>,
signal: AbortSignal,
hasStarted: () => boolean,
): Promise<T> {
if (signal.aborted && !hasStarted()) {
return Promise.reject(signal.reason ?? new Error('history request aborted'));
}
return new Promise<T>((resolve, reject) => {
const onAbort = () => {
if (!hasStarted()) {
reject(signal.reason ?? new Error('history request aborted'));
}
};
signal.addEventListener('abort', onAbort);
result.then(resolve, reject).finally(() => {
signal.removeEventListener('abort', onAbort);
});
});
}
+18 -2
View File
@@ -1,4 +1,5 @@
import type { BridgeContext } from '../bridge-context';
import { CollectionApi } from './collection';
import { ContactsApi } from './contacts';
import { ExtrasApi } from './extras';
import { FlashTransferApi } from './flash-transfer';
@@ -13,8 +14,11 @@ import { MiscApi } from './misc';
import { ProfileApi } from './profile';
import { QzoneApi } from './qzone';
import { WebApi } from './web';
import { SystemFaceApi } from './system-face';
export interface ApiHub {
/** Personal QQ collections: authenticated list retrieval and pagination. */
readonly collection: CollectionApi;
/** Send/recall/markRead operations across c2c + group + c2c-file. */
readonly message: MessageApi;
/** Friend / group / member roster + user-profile + group-request-list + download-rkey. */
@@ -43,6 +47,8 @@ export interface ApiHub {
readonly extras: ExtrasApi;
/** Cookie-backed HTTP: essence / honor / notice / client-key / csrf-token. */
readonly web: WebApi;
/** QQ system-face directory: durable catalog, id lookup, and search. */
readonly systemFace: SystemFaceApi;
}
/**
@@ -55,6 +61,7 @@ export interface ApiHub {
*/
export function buildApiHub(ctx: BridgeContext): ApiHub {
return {
collection: new CollectionApi(ctx),
message: new MessageApi(ctx),
contacts: new ContactsApi(ctx),
groupAdmin: new GroupAdminApi(ctx),
@@ -69,6 +76,7 @@ export function buildApiHub(ctx: BridgeContext): ApiHub {
misc: new MiscApi(ctx),
extras: new ExtrasApi(ctx),
web: new WebApi(ctx),
systemFace: new SystemFaceApi(ctx),
};
}
@@ -76,6 +84,7 @@ export function buildApiHub(ctx: BridgeContext): ApiHub {
// `import type { MessageApi } from '@snowluma/core/.../apis'` for
// signature use. Concrete instances always come from `bridge.apis.*`.
export { ContactsApi } from './contacts';
export { CollectionApi } from './collection';
export { ExtrasApi } from './extras';
export { ForwardApi } from './forward';
export { FriendApi } from './friend';
@@ -83,10 +92,17 @@ export { GroupAdminApi } from './group-admin';
export { GroupAlbumApi } from './group-album';
export { GroupFileApi } from './group-file';
export { InteractionApi } from './interaction';
export { MessageApi } from './message';
export {
MessageApi,
LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS,
type GroupHistorySyncState,
type HistorySyncPrivateTarget,
type HistorySyncState,
type PrivateHistorySyncState,
} from './message';
export { MiscApi } from './misc';
export { ProfileApi } from './profile';
export { QzoneApi } from './qzone';
export { FlashTransferApi, type FlashFileInfo } from './flash-transfer';
export { WebApi } from './web';
export { SystemFaceApi } from './system-face';
+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,
+589 -47
View File
@@ -12,9 +12,22 @@ import type {
SsoReadedReportResp,
} from '@snowluma/proto-defs/oidb-actions/base';
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, fetchGroupMessageRange } from '@snowluma/protocol/msg-push';
import {
fetchC2cMessageRange,
fetchC2cRoamMessagePage,
fetchGroupMessageRange,
} from '@snowluma/protocol/msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
@@ -29,10 +42,16 @@ import { resolveSelfUid } from './shared';
// At runtime `ctx` IS the Bridge instance that constructed this
// MessageApi — `buildApiHub(ctx)` passes the Bridge itself.
import type { Bridge, SendMessageReceipt } from '../bridge';
import { HistoryRequestGate } from './history-request-gate';
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
const READ_REPORT_CMD = 'trpc.msg.msg_svc.MsgService.SsoReadedReport';
const READ_REPORT_BATCH_SIZE = 100;
export const LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS = {
maxTargetsPerKind: READ_REPORT_BATCH_SIZE,
maxMessagesPerSession: 20,
minimumGapMs: 2_000,
} as const;
const log = createLogger('Bridge.Message');
@@ -63,6 +82,28 @@ interface C2CReadTarget {
uid: string;
}
export interface HistorySyncPrivateTarget {
userId: number;
uid: string;
}
export interface GroupHistorySyncState {
groupId: number;
readSeq: number;
latestSeq: number;
}
export interface PrivateHistorySyncState extends HistorySyncPrivateTarget {
readSeq: number;
latestSeq: number;
lastMsgTime: number;
}
export interface HistorySyncState {
groups: GroupHistorySyncState[];
privateUsers: PrivateHistorySyncState[];
}
interface ReadResponseItem {
resultCode?: number;
errorMessage?: string;
@@ -83,6 +124,45 @@ function uniqueSessionIds(ids: readonly number[], label: string): number[] {
return result;
}
function uniqueHistorySyncPrivateTargets(
targets: readonly HistorySyncPrivateTarget[],
): HistorySyncPrivateTarget[] {
const result: HistorySyncPrivateTarget[] = [];
const userToUid = new Map<number, string>();
const uidToUser = new Map<string, number>();
for (const target of targets) {
if (!Number.isSafeInteger(target.userId) || target.userId <= 0) {
throw new Error(`invalid private history sync target ${String(target.userId)}`);
}
if (typeof target.uid !== 'string' || target.uid.trim().length === 0) {
throw new Error(`private history sync target ${target.userId} has no uid`);
}
const uid = target.uid.trim();
const knownUid = userToUid.get(target.userId);
if (knownUid !== undefined) {
if (knownUid !== uid) {
throw new Error(
`private history sync target ${target.userId} maps to conflicting uids`,
);
}
continue;
}
const knownUser = uidToUser.get(uid);
if (knownUser !== undefined && knownUser !== target.userId) {
throw new Error(`private history sync uid ${uid} maps to conflicting users`);
}
userToUid.set(target.userId, uid);
uidToUser.set(uid, target.userId);
result.push({ userId: target.userId, uid });
}
return result;
}
function requireReadResponseItem<T extends ReadResponseItem>(
items: readonly T[] | undefined,
index: number,
@@ -114,6 +194,30 @@ function requirePositiveSequence(value: bigint | null | undefined, label: string
return sequence;
}
function readSafeSequence(value: bigint | null | undefined, label: string): number {
const sequence = readUnsignedSequence(value, label);
if (sequence > BigInt(Number.MAX_SAFE_INTEGER)) {
throw new Error(`${label} exceeds the safe integer range`);
}
return Number(sequence);
}
function validateHistorySyncRange(startSeq: number, endSeq: number, label: string): void {
if (!Number.isSafeInteger(startSeq) || startSeq <= 0) {
throw new Error(`${label} start sequence is invalid: ${String(startSeq)}`);
}
if (!Number.isSafeInteger(endSeq) || endSeq < startSeq || endSeq > HISTORY_MAX_SEQUENCE) {
throw new Error(`${label} end sequence is invalid: ${String(endSeq)}`);
}
const slots = endSeq - startSeq + 1;
if (slots > LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.maxMessagesPerSession) {
throw new Error(
`${label} may request at most `
+ `${LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.maxMessagesPerSession} sequence slots`,
);
}
}
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
@@ -125,21 +229,10 @@ const HISTORY_MAX_REQUESTS = 12; // bound the walk-back loop
const HISTORY_MIN_GAP_MS = 300; // minimum spacing between SsoGetGroupMsg sends
const HISTORY_MAX_SEQUENCE = 0xffff_ffff; // sequence fields are protobuf uint32
// Serialized throttle gate: chains so concurrent callers queue, and enforces
// at least HISTORY_MIN_GAP_MS between actual sends (the first send isn't
// penalized). Process-wide — shared across all groups AND accounts in this
// process — so no client can make us flood the server regardless of fan-out.
let historyLastSendAt = 0;
let historyGate: Promise<void> = Promise.resolve();
function throttleHistory(): Promise<void> {
const run = historyGate.then(async () => {
const wait = historyLastSendAt + HISTORY_MIN_GAP_MS - Date.now();
if (wait > 0) await new Promise<void>((resolve) => setTimeout(resolve, wait));
historyLastSendAt = Date.now();
});
historyGate = run.catch(() => undefined);
return run;
}
// Process-wide across every account and every history caller. Automatic login
// sync requests use a stricter gap; the gate preserves that gap even when a
// normal history action is queued immediately before or after them.
const historyRequestGate = new HistoryRequestGate();
/**
* Shared walk-back loop for group + c2c history: pull HISTORY_CHUNK_SEQ-wide
@@ -152,6 +245,7 @@ async function walkBackHistory<T extends { msgSeq: number }>(
endSeq: number,
count: number,
fetchWindow: (startSeq: number, endSeq: number) => Promise<T[]>,
sequenceOf: (event: T) => number = (event) => event.msgSeq,
): Promise<T[]> {
if (!(endSeq > 0)) return [];
const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT);
@@ -160,20 +254,26 @@ async function walkBackHistory<T extends { msgSeq: number }>(
let curEnd = endSeq;
for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want && curEnd >= 1; i++) {
const start = Math.max(1, curEnd - HISTORY_CHUNK_SEQ + 1);
await throttleHistory();
const batch = await fetchWindow(start, curEnd);
const batch = await historyRequestGate.run(
HISTORY_MIN_GAP_MS,
() => fetchWindow(start, curEnd),
);
if (batch.length > 0) {
let minSeq = curEnd;
for (const ev of batch) {
collected.set(ev.msgSeq, ev);
if (ev.msgSeq < minSeq) minSeq = ev.msgSeq;
const sequence = sequenceOf(ev);
if (!Number.isInteger(sequence) || sequence < start || sequence > curEnd) {
throw new Error(`history response sequence is outside requested range ${start}-${curEnd}`);
}
collected.set(sequence, ev);
if (sequence < minSeq) minSeq = sequence;
}
curEnd = minSeq - 1; // strictly below the oldest returned (covers short caps)
} else {
curEnd = start - 1; // empty window (recalled/absent seqs) — skip past it
}
}
const all = [...collected.values()].sort((a, b) => a.msgSeq - b.msgSeq);
const all = [...collected.values()].sort((a, b) => sequenceOf(a) - sequenceOf(b));
return all.slice(-want); // newest `want`, oldest→newest
}
@@ -186,6 +286,7 @@ async function walkForwardHistory<T extends { msgSeq: number }>(
startSeq: number,
count: number,
fetchWindow: (startSeq: number, endSeq: number) => Promise<T[]>,
sequenceOf: (event: T) => number = (event) => event.msgSeq,
): Promise<T[]> {
if (!(startSeq > 0) || startSeq > HISTORY_MAX_SEQUENCE) return [];
const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT);
@@ -195,13 +296,13 @@ async function walkForwardHistory<T extends { msgSeq: number }>(
let curStart = startSeq;
while (budget.remaining > 0 && collected.size < want && curStart <= HISTORY_MAX_SEQUENCE) {
const end = Math.min(HISTORY_MAX_SEQUENCE, curStart + HISTORY_CHUNK_SEQ - 1);
const window = await fetchForwardWindow(curStart, end, budget, fetchWindow);
for (const event of window.messages) collected.set(event.msgSeq, event);
const window = await fetchForwardWindow(curStart, end, budget, fetchWindow, sequenceOf);
for (const event of window.messages) collected.set(sequenceOf(event), event);
if (!window.complete || end === HISTORY_MAX_SEQUENCE) break;
curStart = end + 1;
}
const all = [...collected.values()].sort((a, b) => a.msgSeq - b.msgSeq);
const all = [...collected.values()].sort((a, b) => sequenceOf(a) - sequenceOf(b));
return all.slice(0, want);
}
@@ -222,25 +323,35 @@ async function fetchForwardWindow<T extends { msgSeq: number }>(
endSeq: number,
budget: { remaining: number },
fetchWindow: (startSeq: number, endSeq: number) => Promise<T[]>,
sequenceOf: (event: T) => number,
): Promise<ForwardWindowResult<T>> {
if (budget.remaining <= 0) return { messages: [], complete: false };
budget.remaining--;
await throttleHistory();
const batch = await fetchWindow(startSeq, endSeq);
const batch = await historyRequestGate.run(
HISTORY_MIN_GAP_MS,
() => fetchWindow(startSeq, endSeq),
);
if (batch.length === 0) return { messages: [], complete: true };
const messages = [...new Map(batch.map((event) => [event.msgSeq, event])).values()]
.sort((a, b) => a.msgSeq - b.msgSeq);
const messages = [...new Map(batch.map((event) => [sequenceOf(event), event])).values()]
.sort((a, b) => sequenceOf(a) - sequenceOf(b));
for (const message of messages) {
if (!Number.isInteger(message.msgSeq) || message.msgSeq < startSeq || message.msgSeq > endSeq) {
const sequence = sequenceOf(message);
if (!Number.isInteger(sequence) || sequence < startSeq || sequence > endSeq) {
throw new Error(`history response sequence is outside requested range ${startSeq}-${endSeq}`);
}
}
const firstSequence = messages[0]!.msgSeq;
const firstSequence = sequenceOf(messages[0]!);
if (firstSequence === startSeq) return { messages, complete: true };
const prefix = await fetchForwardWindow(startSeq, firstSequence - 1, budget, fetchWindow);
const prefix = await fetchForwardWindow(
startSeq,
firstSequence - 1,
budget,
fetchWindow,
sequenceOf,
);
if (!prefix.complete) return prefix;
return { messages: [...prefix.messages, ...messages], complete: true };
}
@@ -262,7 +373,11 @@ export class MessageApi {
async sendGroup(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, groupId });
const protoElems = await buildSendElems(elements, {
bridge: this.ctx as unknown as Bridge,
groupId,
scene: 'group',
});
const random = this.ctx.nextMessageRandom();
const request = protobuf_encode<SendMessageRequest>({
@@ -297,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 };
@@ -310,7 +433,14 @@ 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,
elements.length,
'direct-private',
);
let userUid = '';
const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video');
@@ -318,7 +448,11 @@ export class MessageApi {
userUid = await this.ctx.resolveUserUid(userUin);
}
const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, userUid });
const protoElems = await buildSendElems(elements, {
bridge: this.ctx as unknown as Bridge,
userUid,
scene: 'direct-private',
});
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
@@ -367,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
@@ -379,9 +574,19 @@ export class MessageApi {
elements: MessageElement[],
): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
assertWindowShakeSendPolicy(
elements.filter((element) => element.type === 'poke').length,
elements.length,
'group-temp',
);
const userUid = await this.ctx.resolveUserUid(userUin);
const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, userUid });
const protoElems = await buildSendElems(elements, {
bridge: this.ctx as unknown as Bridge,
userUid,
scene: 'group-temp',
tempGroupId: groupUin,
});
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
@@ -590,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,
@@ -662,7 +867,12 @@ export class MessageApi {
log.debug('mark-read complete: groups=%d c2c=%d', groups.length, c2cTargets.length);
}
private async sendReadReport(request: SsoReadedReportReq, label: string): Promise<SsoReadedReportResp> {
private async sendReadReport(
request: SsoReadedReportReq,
label: string,
minimumGapMs = HISTORY_MIN_GAP_MS,
signal?: AbortSignal,
): Promise<SsoReadedReportResp> {
log.debug(
'%s send: groups=%d c2c=%d',
label,
@@ -670,7 +880,11 @@ export class MessageApi {
request.c2cList?.length ?? 0,
);
const payload = protobuf_encode<SsoReadedReportReq>(request);
const result = await this.ctx.sendRawPacket(READ_REPORT_CMD, payload);
const result = await historyRequestGate.run(
minimumGapMs,
() => this.ctx.sendRawPacket(READ_REPORT_CMD, payload),
signal,
);
const response = decodeReadReportResponse(result, label);
log.debug(
'%s response: groups=%d c2c=%d',
@@ -681,6 +895,99 @@ export class MessageApi {
return response;
}
/**
* Read the server's current read/latest cursors without advancing any read
* marker. The zero-valued report fields are omitted on the wire by protobuf,
* matching QQ NT's read-only probe. Automatic login sync is deliberately
* limited to one probe with at most 100 group and 100 private targets.
*/
async probeHistorySyncState(
groupIds: readonly number[],
privateTargets: readonly HistorySyncPrivateTarget[],
signal?: AbortSignal,
): Promise<HistorySyncState> {
const groups = uniqueSessionIds(groupIds, 'group');
const privateUsers = uniqueHistorySyncPrivateTargets(privateTargets);
const maxTargets = LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.maxTargetsPerKind;
if (groups.length > maxTargets) {
throw new Error(`history sync probe accepts at most ${maxTargets} group targets`);
}
if (privateUsers.length > maxTargets) {
throw new Error(`history sync probe accepts at most ${maxTargets} private targets`);
}
if (groups.length === 0 && privateUsers.length === 0) {
return { groups: [], privateUsers: [] };
}
const label = 'login history sync probe';
const response = await this.sendReadReport({
groupList: groups.map(groupId => ({ groupUin: BigInt(groupId), lastReadSeq: 0n })),
c2cList: privateUsers.map(target => ({
uid: target.uid,
lastReadTime: 0n,
lastReadSeq: 0n,
})),
}, label, LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.minimumGapMs, signal);
const groupState = groups.map((groupId, index): GroupHistorySyncState => {
const item = this.groupReadResponse(response, groupId, index, label);
const readSeq = readSafeSequence(
item.readSeq,
`${label} group ${groupId} read sequence`,
);
const latestSeq = readSafeSequence(
item.latestSeq,
`${label} group ${groupId} latest sequence`,
);
if (latestSeq < readSeq) {
throw new Error(
`${label} group ${groupId} latest sequence ${latestSeq} `
+ `is before read sequence ${readSeq}`,
);
}
return { groupId, readSeq, latestSeq };
});
const privateState = privateUsers.map((target, index): PrivateHistorySyncState => {
const item = this.c2cReadResponse(response, target, index, label);
const targetUin = readSafeSequence(
item.targetUin,
`${label} private user ${target.userId} target uin`,
);
if (targetUin !== 0 && targetUin !== target.userId) {
throw new Error(
`${label} private user ${target.userId} response target ${targetUin} does not match`,
);
}
const readSeq = readSafeSequence(
item.readSeq,
`${label} private user ${target.userId} read sequence`,
);
const latestSeq = readSafeSequence(
item.latestSeq,
`${label} private user ${target.userId} latest sequence`,
);
if (latestSeq < readSeq) {
throw new Error(
`${label} private user ${target.userId} latest sequence ${latestSeq} `
+ `is before read sequence ${readSeq}`,
);
}
return {
...target,
readSeq,
latestSeq,
lastMsgTime: readSafeSequence(
item.lastMsgTime,
`${label} private user ${target.userId} last message time`,
),
};
});
return { groups: groupState, privateUsers: privateState };
}
private groupReadResponse(
response: SsoReadedReportResp,
groupId: number,
@@ -810,6 +1117,43 @@ export class MessageApi {
: walkForwardHistory(anchorSeq, count, fetchWindow);
}
/**
* Fetch exactly one bounded group-history window for automatic login sync.
* Unlike the public history action this method never paginates or retries.
*/
async getGroupHistorySyncPage(
groupUin: number,
startSeq: number,
endSeq: number,
selfUin = 0,
signal?: AbortSignal,
): Promise<GroupMessage[]> {
if (!Number.isSafeInteger(groupUin) || groupUin <= 0) {
throw new Error(`group history sync target is invalid: ${String(groupUin)}`);
}
validateHistorySyncRange(startSeq, endSeq, `group ${groupUin} history sync`);
const messages = await historyRequestGate.run(
LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.minimumGapMs,
() => fetchGroupMessageRange(
this.ctx,
this.ctx.identity,
selfUin,
groupUin,
startSeq,
endSeq,
),
signal,
);
return this.validateHistorySyncPage(
messages,
message => message.msgSeq,
startSeq,
endSeq,
`group ${groupUin} history sync`,
);
}
/**
* Fetch real private history from the server (`SsoGetC2cMsg`), including the
* anchor in the requested direction. It shares the group variant's throttle
@@ -825,9 +1169,164 @@ export class MessageApi {
if (!friendUid) return [];
const fetchWindow = (start: number, end: number) =>
fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, start, end);
const serverSequence = (message: FriendMessage) => message.ntMsgSeq ?? 0;
return reverseOrder
? walkBackHistory(anchorSeq, count, fetchWindow)
: walkForwardHistory(anchorSeq, count, fetchWindow);
? walkBackHistory(anchorSeq, count, fetchWindow, serverSequence)
: walkForwardHistory(anchorSeq, count, fetchWindow, serverSequence);
}
/**
* Fetch exactly one bounded private-history sequence window for automatic
* login sync. Sender-local message-head sequences are not valid here.
*/
async getC2cHistorySyncPage(
friendUid: string,
startSeq: number,
endSeq: number,
selfUin = 0,
signal?: AbortSignal,
): Promise<FriendMessage[]> {
if (!friendUid.trim()) throw new Error('private history sync uid is required');
validateHistorySyncRange(startSeq, endSeq, `private ${friendUid} history sync`);
const messages = await historyRequestGate.run(
LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.minimumGapMs,
() => fetchC2cMessageRange(
this.ctx,
this.ctx.identity,
selfUin,
friendUid,
startSeq,
endSeq,
),
signal,
);
return this.validateHistorySyncPage(
messages,
message => message.ntMsgSeq ?? 0,
startSeq,
endSeq,
`private ${friendUid} history sync`,
);
}
/**
* Fetch one latest private roaming page for a session without a local
* authoritative sequence. No cursor loop or retry is permitted.
*/
async getC2cLatestHistorySyncPage(
friendUid: string,
count: number,
selfUin = 0,
beforeTime = Math.floor(Date.now() / 1000) + 1,
signal?: AbortSignal,
): Promise<FriendMessage[]> {
if (!friendUid.trim()) throw new Error('private history sync uid is required');
const maxMessages = LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.maxMessagesPerSession;
if (!Number.isSafeInteger(count) || count < 1 || count > maxMessages) {
throw new Error(`private history sync may request at most ${maxMessages} messages`);
}
const page = await historyRequestGate.run(
LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.minimumGapMs,
() => fetchC2cRoamMessagePage(
this.ctx,
this.ctx.identity,
selfUin,
friendUid,
beforeTime,
count,
0,
),
signal,
);
const messages = [...new Map(page.messages.map((message) => {
const sequence = message.ntMsgSeq ?? 0;
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
throw new Error(
`private ${friendUid} history sync returned invalid NT sequence ${String(sequence)}`,
);
}
return [sequence, message] as const;
})).values()]
.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0) || a.time - b.time);
if (messages.length > count) {
throw new Error(
`private ${friendUid} history sync returned ${messages.length} messages `
+ `for a ${count}-message request`,
);
}
return messages;
}
/**
* Fetch the latest private history page without relying on a locally cached
* sequence. C2C field-5 sequences are sender-local, so only SsoGetRoamMsg's
* timestamp cursor can safely bootstrap an unanchored conversation.
*/
async getC2cLatestHistory(
friendUid: string,
count: number,
selfUin = 0,
beforeTime = Math.floor(Date.now() / 1000) + 1,
): Promise<FriendMessage[]> {
if (!friendUid) return [];
const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT);
const collected = new Map<number, FriendMessage>();
let cursor = { time: beforeTime, random: 0 };
const seenCursors = new Set<string>([`${cursor.time}:${cursor.random}`]);
let reachedEnd = false;
for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want; i++) {
const page = await historyRequestGate.run(
HISTORY_MIN_GAP_MS,
() => fetchC2cRoamMessagePage(
this.ctx,
this.ctx.identity,
selfUin,
friendUid,
cursor.time,
want - collected.size,
cursor.random,
),
);
for (const message of page.messages) {
const sequence = message.ntMsgSeq ?? 0;
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
throw new Error(`private roam history returned invalid NT sequence ${String(sequence)}`);
}
collected.set(sequence, message);
}
if (collected.size >= want) break;
if (page.cursor.time === 0 && page.cursor.random === 0) {
reachedEnd = true;
break;
}
const nextCursorKey = `${page.cursor.time}:${page.cursor.random}`;
if (seenCursors.has(nextCursorKey)) {
if (page.messages.length === 0) {
reachedEnd = true;
break;
}
throw new Error(
`private roam history cursor did not advance from ${cursor.time}/${cursor.random}`,
);
}
seenCursors.add(nextCursorKey);
cursor = page.cursor;
}
if (collected.size < want && !reachedEnd) {
throw new Error(
`private roam history request budget exhausted after ${HISTORY_MAX_REQUESTS} pages `
+ `(requested=${want}, collected=${collected.size})`,
);
}
return [...collected.values()]
.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0) || a.time - b.time)
.slice(-want);
}
/**
@@ -838,9 +1337,18 @@ export class MessageApi {
*/
async getGroupMessageBySeq(groupUin: number, seq: number, selfUin = 0): Promise<GroupMessage | null> {
if (!(groupUin > 0) || !(seq > 0)) return null;
await throttleHistory();
try {
const batch = await fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, seq, seq);
const batch = await historyRequestGate.run(
HISTORY_MIN_GAP_MS,
() => fetchGroupMessageRange(
this.ctx,
this.ctx.identity,
selfUin,
groupUin,
seq,
seq,
),
);
return batch.find((m) => m.msgSeq === seq) ?? null;
} catch {
return null;
@@ -848,18 +1356,52 @@ export class MessageApi {
}
/**
* Fetch a single c2c message by its exact sequence — `SsoGetC2cMsg` over a
* 1-wide `[seq, seq]` range, through the same throttle gate. `friendUid` is the
* conversation peer. Returns the matching `friend_message`, or null.
* Fetch a single c2c message by its exact conversation-wide NT sequence —
* `SsoGetC2cMsg` over a 1-wide `[seq, seq]` range, through the same throttle
* gate. Sender-local reply/recall sequences must not be passed here.
*/
async getC2cMessageBySeq(friendUid: string, seq: number, selfUin = 0): Promise<FriendMessage | null> {
if (!friendUid || !(seq > 0)) return null;
await throttleHistory();
try {
const batch = await fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, seq, seq);
return batch.find((m) => m.msgSeq === seq) ?? null;
const batch = await historyRequestGate.run(
HISTORY_MIN_GAP_MS,
() => fetchC2cMessageRange(
this.ctx,
this.ctx.identity,
selfUin,
friendUid,
seq,
seq,
),
);
return batch.find((m) => m.ntMsgSeq === seq) ?? null;
} catch {
return null;
}
}
private validateHistorySyncPage<T>(
messages: readonly T[],
sequenceOf: (message: T) => number,
startSeq: number,
endSeq: number,
label: string,
): T[] {
const bySequence = new Map<number, T>();
for (const message of messages) {
const sequence = sequenceOf(message);
if (
!Number.isSafeInteger(sequence)
|| sequence < startSeq
|| sequence > endSeq
) {
throw new Error(
`${label} returned sequence ${String(sequence)} outside `
+ `requested range ${startSeq}-${endSeq}`,
);
}
bySequence.set(sequence, message);
}
return [...bySequence.values()].sort((a, b) => sequenceOf(a) - sequenceOf(b));
}
}
+67 -32
View File
@@ -1,12 +1,12 @@
import type {
FaceroamOpReq,
FaceroamOpResp,
GroupAvatarExtra,
SetStatusReq,
SetStatusResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { AddCustomFace } from '@snowluma/protocol/oidb-services/custom-face/add-custom-face';
import { DeleteCustomFace } from '@snowluma/protocol/oidb-services/custom-face/delete-custom-face';
import { FetchCustomFaceDetail } from '@snowluma/protocol/oidb-services/custom-face/fetch-custom-face-detail';
import { FetchCustomFaceList } from '@snowluma/protocol/oidb-services/custom-face/fetch-custom-face-list';
import { ModifyCustomFace } from '@snowluma/protocol/oidb-services/custom-face/modify-custom-face';
import { MoveCustomFace } from '@snowluma/protocol/oidb-services/custom-face/move-custom-face';
import { OrderCustomFace } from '@snowluma/protocol/oidb-services/custom-face/order-custom-face';
@@ -23,6 +23,13 @@ import type { BridgeContext } from '../bridge-context';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
export interface CustomFaceDetail {
emojiId: string;
url: string;
md5: string;
desc: string;
}
export class ProfileApi {
constructor(private readonly ctx: BridgeContext) { }
@@ -68,14 +75,15 @@ export class ProfileApi {
if (!resp) {
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
}
if (resp.errCode !== undefined && resp.errCode !== 0) {
throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`);
const message = resp.errMsg ?? '';
if (message !== '' && message !== 'set status success') {
throw new Error(message);
}
}
}
setProfile(nickname?: string, personalNote?: string): Promise<void> {
return SetProfile.invoke(this.ctx, { nickname, personalNote });
setProfile(nickname?: string, personalNote?: string, sex?: number): Promise<void> {
return SetProfile.invoke(this.ctx, { nickname, personalNote, sex });
}
setSelfLongNick(longNick: string): Promise<void> {
@@ -134,26 +142,58 @@ export class ProfileApi {
}
async fetchCustomFace(count = 10): Promise<string[]> {
const req = {
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
uin: BigInt(this.ctx.identity.uin),
field3: 1,
field6: 1,
};
const request = protobuf_encode<FaceroamOpReq>(req);
const result = await this.ctx.sendRawPacket('Faceroam.OpReq', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'fetch custom face failed');
}
const resp = protobuf_decode<FaceroamOpResp>(result.responseData);
if (!resp || resp.retCode !== 0) {
throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`);
}
const faceIds = resp.item?.faceIds || [];
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${id}/0`);
const faceIds = await this.fetchCustomFaceIds(count);
return faceIds.map((id) => this.customFaceUrl(id));
}
/** 删除一个收藏表情(custom face)。emoji_id 来自 fetchCustomFace 返回的 URL 路径段。 */
async fetchCustomFaceDetails(count = 10): Promise<CustomFaceDetail[]> {
const faceIds = await this.fetchCustomFaceIds(count);
if (faceIds.length === 0) return [];
const emojis = faceIds.map((emojiId) => ({
emojiId,
md5: md5FromEmojiId(emojiId),
}));
const details = await FetchCustomFaceDetail.invoke(this.ctx, { emojis });
const descriptions = new Map(details.map((detail) => [detail.emojiId, detail.desc]));
return emojis.map(({ emojiId, md5 }) => ({
emojiId,
url: this.customFaceUrl(emojiId),
md5,
// The detail response may omit entries which have never had a remark.
desc: descriptions.get(emojiId) ?? '',
}));
}
async fetchCustomFaceIds(count = 10): Promise<string[]> {
if (!Number.isInteger(count) || count < 0) {
throw new Error('custom face count must be a non-negative integer');
}
if (count === 0) return [];
const faceIds = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
return faceIds.slice(0, count);
}
private customFaceUrl(emojiId: string): string {
return `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${emojiId}/0`;
}
/** Resolve an existing saved sticker by its resource id or content MD5. */
async resolveCustomFace(identifier: string): Promise<Pick<CustomFaceDetail, 'emojiId' | 'url' | 'md5'>> {
const wanted = identifier.trim();
if (!wanted) throw new Error('custom face identifier is empty');
const ids = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
const byMd5 = /^[a-fA-F0-9]{32}$/.test(wanted);
const emojiId = ids.find((id) => byMd5
? md5FromEmojiId(id).toLowerCase() === wanted.toLowerCase()
: id === wanted);
if (!emojiId) throw new Error('custom face is not in the saved sticker list');
return { emojiId, url: this.customFaceUrl(emojiId), md5: md5FromEmojiId(emojiId) };
}
/** 删除一个收藏表情(custom face)。emoji_id 来自收藏列表。 */
deleteCustomFace(emojiId: string): Promise<void> {
return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId });
}
@@ -168,9 +208,8 @@ export class ProfileApi {
}
/**
* 修改收藏表情(custom face)备注。emoji_id 来自 fetchCustomFace 返回的
* URL 路径段;md5 从 emoji_id 中段解析,无需调用方单独提供。desc 为空串
* 则清空备注。
* 修改收藏表情(custom face)备注。emoji_id 来自收藏列表;md5 从 emoji_id
* 中段解析,无需调用方单独提供。desc 为空串则清空备注。
*/
modifyCustomFace(emojiId: string, desc: string): Promise<void> {
return ModifyCustomFace.invoke(this.ctx, {
@@ -188,11 +227,7 @@ export class ProfileApi {
*/
async moveCustomFaceToFront(emojiId: string): Promise<void> {
// 1. fetch 当前完整列表(fetch 顺序即可,不需要 DB 显示顺序)
const urls = await this.fetchCustomFace(1000);
const ids = urls.map((url) => {
const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url);
return m ? m[1] : '';
}).filter(Boolean);
const ids = await this.fetchCustomFaceIds(1000);
const idx = ids.indexOf(emojiId);
if (idx < 0) throw new Error(`emoji_id not in list: ${emojiId}`);
// 新顺序:目标挪到第一,其余按原顺序
-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.
@@ -0,0 +1,35 @@
import {
sysFaceStore,
type SysFaceEntry,
type SysFacePackEntry,
} from '@snowluma/protocol/sys-face-store';
import { isSuperFaceEntry } from '@snowluma/protocol/oidb-services/sys-faces/fetch-sys-faces';
import type { BridgeContext } from '../bridge-context';
/** QQ's account-independent system-face directory. The shared store owns
* persistence and refresh coalescing; this API binds it to one live sender. */
export class SystemFaceApi {
constructor(private readonly ctx: BridgeContext) {}
fetchCatalog(refresh = false): Promise<SysFacePackEntry[]> {
return sysFaceStore.getCatalog(this.ctx, refresh);
}
async fetchFace(faceId: number, refresh = false): Promise<SysFaceEntry | null> {
if (refresh) {
await sysFaceStore.refresh(this.ctx);
return sysFaceStore.lookup(faceId);
}
return sysFaceStore.resolve(this.ctx, faceId);
}
async search(query: string): Promise<SysFaceEntry[]> {
await sysFaceStore.ensureReady(this.ctx);
return sysFaceStore.search(query);
}
async isSuper(faceId: number, refresh = false): Promise<boolean> {
const face = await this.fetchFace(faceId, refresh);
return face !== null && isSuperFaceEntry(face);
}
}
+16 -2
View File
@@ -2,6 +2,7 @@ import { loadBinarySource } from '@snowluma/protocol/highway/utils';
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence';
import { getFriendDressWebAPI, type WebFriendDress } from '@snowluma/protocol/web/friend-dress';
import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/protocol/web/group-honor';
import { getDaySignedListWebAPI, type SignedListMember } from '@snowluma/protocol/web/group-signin';
import {
@@ -9,6 +10,7 @@ import {
GROUP_NOTICE_TYPE_NEW_MEMBERS,
GROUP_NOTICE_TYPE_NORMAL,
getGroupNoticeWebAPI,
groupNoticeImageUrl,
setGroupNoticeWebAPI,
uploadGroupNoticeImage,
type SetNoticeRetSuccess,
@@ -42,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;
@@ -103,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`),
};
@@ -417,4 +420,15 @@ export class WebApi {
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await deleteGroupNoticeHttp(cookieObject, groupCode, fid);
}
// ─────────────── friend dress (好友装扮) ───────────────
/** 查某人正在用的好友装扮(挂件/名片/来电/输入状态等)。走 vip.qq.com 域,
* 纯 cookie 鉴权、抓 SSR HTML。「查到但没装扮」返回空 items;网络/未登录态/
* 风控/页面改版/串号数据抛 FriendDressError(kind 区分具体环节)。 */
async getFriendDress(targetUin: number): Promise<WebFriendDress> {
const bridge = asBridge(this.ctx);
const cookieObject = await getCookies(bridge, 'vip.qq.com');
return getFriendDressWebAPI(cookieObject, targetUin.toString());
}
}
+13 -2
View File
@@ -1,8 +1,19 @@
import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
import type { BridgeContext } from './bridge-context';
export interface RosterWarmupResult {
friendsLoaded: boolean;
groupsLoaded: boolean;
}
export interface BridgeInterface extends BridgeContext {
readonly activePid: number | null;
/** False only when every attached QQ process is confirmed stale.
* An unarmed watchdog remains true for compatibility. */
/** Settles once for this Bridge session after first-login roster fetch. */
whenRosterWarmupSettled(): Promise<RosterWarmupResult>;
/** False only when every attached QQ process has a confirmed receive or
* request-path failure. An unarmed watchdog remains true for compatibility. */
readonly receiveHealthy: boolean;
/** Latest device snapshot observed on this Bridge lifecycle. `null` means
* QQ has not emitted its cache notification since SnowLuma attached. */
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null;
}
+238 -32
View File
@@ -1,20 +1,32 @@
import { createLogger } from '@snowluma/common/logger';
import {
createLogger,
renderTraceBytes,
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';
import { MSG_PUSH_CMD, parseMsgPush, SysMsgDedup } from '@snowluma/protocol/msg-push';
import {
MSG_PUSH_CMD,
parseMsgPushOrThrow,
SysMsgDedup,
} from '@snowluma/protocol/msg-push';
import { KICK_NT_CMD, parseKickNT } from '@snowluma/protocol/kick-nt';
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
import { buildApiHub, type ApiHub } from './apis';
import {
AiVoiceChatType,
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;
@@ -35,32 +47,34 @@ export class Bridge implements BridgeInterface {
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
// Per-account dedup for QQ NT's already-deduped system pushes (#137).
private readonly sysMsgDedup_ = new SysMsgDedup();
private onlineClients_: readonly Readonly<OnlineDeviceInfo>[] | null = null;
private disposed_ = false;
private rosterWarmupStarted_ = false;
private rosterWarmupSettled_ = false;
private rosterWarmupResult_: RosterWarmupResult | null = null;
private readonly rosterWarmupWaiters_: Array<(result: RosterWarmupResult) => void> = [];
constructor(identity: IdentityService) {
this.identity = identity;
this.apis = buildApiHub(this);
this.identity.setFetcher({
fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin),
fetchProfileByUid: (uid) => this.apis.contacts.fetchUserProfileByUid(uid),
fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid),
});
this.pipeline = new IncomingPacketPipeline({
identity: this.identity,
events: this.events,
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
resolveStrangerProfile: async (uid) => {
try {
const p = await this.apis.contacts.fetchUserProfileByUid(uid);
if (p.uin <= 0) return null;
return { uin: p.uin, nickname: p.nickname };
} catch {
return null;
}
fetchGroupList: async () => {
await this.apis.contacts.fetchGroupList();
},
fetchGroupMemberList: async (groupId) => {
await this.apis.contacts.fetchGroupMemberList(groupId);
},
resolveGroupJoinRequest: async (groupId, uid, subType) => {
const [main, filtered] = await Promise.allSettled([
this.apis.contacts.fetchGroupRequests(false),
this.apis.contacts.fetchGroupRequests(true),
this.apis.contacts.fetchGroupRequestsByUid(false),
this.apis.contacts.fetchGroupRequestsByUid(true),
]);
if (main.status === 'rejected') {
log.warn('group-request enrichment main inbox failed: group=%d uid=%s err=%s',
@@ -77,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;
@@ -91,17 +109,37 @@ 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, (pkt, identity) => parseMsgPush(pkt, identity, this.sysMsgDedup_));
this.pipeline.registerCmd(
MSG_PUSH_CMD,
(pkt, identity) => parseMsgPushOrThrow(
pkt,
identity,
this.sysMsgDedup_,
),
);
this.pipeline.registerCmd(KICK_NT_CMD, parseKickNT);
this.events.on('online_devices_changed', (event) => {
const snapshot = event.devices.map((device) => Object.freeze({ ...device }));
this.onlineClients_ = Object.freeze(snapshot);
log.debug('online-device snapshot updated: uin=%s clients=%d types=%s',
this.identity.uin, snapshot.length,
snapshot.map((device) => device.clientType).join(','));
});
}
dispose(): void {
this.disposed_ = true;
this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false });
this.pids_.clear();
this.receiveHealthByPid_.clear();
this.packetClientsByPid_.clear();
this.packetClient_ = null;
this.packetClientPid_ = null;
this.onlineClients_ = null;
try {
this.identity.close();
} finally {
@@ -120,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 {
@@ -145,10 +184,21 @@ export class Bridge implements BridgeInterface {
/** Atomically attach a process and make its sender the active sender.
* Set insertion order is the recency order used for fallback. */
bindPid(pid: number, client: PacketSender): void {
const previousPid = this.packetClientPid_;
const previousClient = this.packetClient_;
this.attachPid(pid);
this.packetClientsByPid_.set(pid, client);
this.packetClient_ = client;
this.packetClientPid_ = pid;
if (previousPid !== pid || previousClient !== client) {
runtimeLog.trace(
'bridge_sender_fact event=selected uin=%j pid=%d previousPid=%j',
this.identity.uin,
pid,
previousPid,
);
}
this.maybeStartRosterWarmup();
}
/** @internal BridgeManager lookup used when an incoming packet is the first
@@ -202,18 +252,28 @@ export class Bridge implements BridgeInterface {
}
this.receiveHealthByPid_.set(pid, healthy);
}
onPacket(pkt: PacketInfo): void {
this.pipeline.process(pkt);
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null {
return this.onlineClients_;
}
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
if (refreshGroupList) {
try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ }
whenRosterWarmupSettled(): Promise<RosterWarmupResult> {
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
return Promise.resolve(this.rosterWarmupResult_);
}
if (!this.identity.findGroup(groupId)) return false;
await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
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);
}
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) return;
if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) {
@@ -237,13 +297,34 @@ 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_) {
log.warn('packet %s dropped: no packet sender attached', serviceCmd);
return {
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'no packet sender attached', responseData: null,
};
return runWithTraceRequest(() => {
const startedAt = Date.now();
runtimeLog.trace(() => [
'bridge_send_start serviceCmd=%j uin=%j activePid=%j timeoutMs=%d length=%d body=%s',
serviceCmd,
this.identity.uin,
this.activePid,
timeoutMs,
body.byteLength,
renderTraceBytes(body),
]);
log.warn('packet %s dropped: no packet sender attached', serviceCmd);
runtimeLog.trace(() => [
'bridge_send_terminal serviceCmd=%j uin=%j activePid=%j outcome=dropped reason=no_sender length=%d body=%s elapsedMs=%d',
serviceCmd,
this.identity.uin,
this.activePid,
body.byteLength,
renderTraceBytes(body),
Date.now() - startedAt,
]);
return {
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'no packet sender attached', responseData: null,
};
});
}
const startedAt = Date.now();
const result = await this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
@@ -273,6 +354,12 @@ export class Bridge implements BridgeInterface {
this.packetClient_ = fallback;
this.packetClientPid_ = fallbackPid;
runtimeLog.trace(
'bridge_sender_fact event=fallback uin=%j detachedPid=%d fallbackPid=%d',
this.identity.uin,
detachedPid,
fallbackPid,
);
log.debug(
'packet sender fallback: UIN=%s detached PID=%d fallback PID=%d',
this.identity.uin,
@@ -296,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;
+190 -23
View File
@@ -1,4 +1,8 @@
import { createLogger } from '@snowluma/common/logger';
import {
createLogger,
renderTraceBytes,
runWithTraceRequest,
} from '@snowluma/common/logger';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { isRealUin } from '@snowluma/common/uin';
@@ -13,6 +17,8 @@ interface QQSession {
}
const log = createLogger('Bridge');
const packetLog = createLogger('Bridge.Packet');
const runtimeLog = createLogger('Bridge.Runtime');
export class BridgeManager {
private sessions_ = new Map<string, QQSession>();
@@ -57,7 +63,42 @@ export class BridgeManager {
const uin = this.pidToUin_.get(pid);
if (!uin) return;
this.detachPidFromSession(pid, uin);
runWithTraceRequest(() => {
const startedAt = Date.now();
runtimeLog.trace(
'bridge_detach_start pid=%d uin=%j',
pid,
uin,
);
try {
const closed = this.detachPidFromSession(pid, uin);
const activePid = this.sessions_.get(uin)?.bridge.activePid ?? null;
if (closed) {
runtimeLog.trace(
'bridge_detach_branch pid=%d uin=%j branch=session_closed',
pid,
uin,
);
}
runtimeLog.trace(
'bridge_detach_terminal pid=%d uin=%j outcome=completed reason=%s activePid=%j elapsedMs=%d',
pid,
uin,
closed ? 'session_closed' : 'pid_detached',
activePid,
Date.now() - startedAt,
);
} catch (error) {
runtimeLog.trace(
'bridge_detach_terminal pid=%d uin=%j outcome=failed reason=invariant_violation error=%j elapsedMs=%d',
pid,
uin,
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
throw error;
}
});
}
onPidReceiveHealthChanged(pid: number, healthy: boolean): void {
@@ -80,34 +121,159 @@ export class BridgeManager {
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
if (!isRealUin(uin)) return;
const { session, created } = this.bindPid(pid, uin, packetClient, 'login');
runWithTraceRequest(() => {
const startedAt = Date.now();
const previousUin = this.pidToUin_.get(pid) ?? null;
runtimeLog.trace(
'bridge_binding_start pid=%d uin=%j source=login previousUin=%j',
pid,
uin,
previousUin,
);
if (created) {
log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge);
}
try {
const { session, created } = this.bindPid(pid, uin, packetClient, 'login');
if (previousUin && previousUin !== uin) {
runtimeLog.trace(
'bridge_binding_branch pid=%d uin=%j branch=account_rebind previousUin=%j',
pid,
uin,
previousUin,
);
const previousSession = this.sessions_.get(previousUin);
runtimeLog.trace(
'bridge_binding_branch pid=%d uin=%j branch=%s previousUin=%j activePid=%j',
pid,
uin,
previousSession ? 'previous_session_retained' : 'previous_session_closed',
previousUin,
previousSession?.bridge.activePid ?? null,
);
}
if (created) {
runtimeLog.trace(
'bridge_binding_branch pid=%d uin=%j branch=session_created',
pid,
uin,
);
log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge);
}
runtimeLog.trace(
'bridge_binding_terminal pid=%d uin=%j source=login outcome=completed reason=%s created=%s activePid=%j elapsedMs=%d',
pid,
uin,
previousUin && previousUin !== uin ? 'rebound' : 'bound',
created,
session.bridge.activePid,
Date.now() - startedAt,
);
} catch (error) {
runtimeLog.trace(
'bridge_binding_terminal pid=%d uin=%j source=login outcome=failed reason=binding_failed error=%j elapsedMs=%d',
pid,
uin,
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
throw error;
}
});
}
onPacket(pkt: PacketInfo): void {
if (!pkt.uin || !isRealUin(pkt.uin)) return;
runWithTraceRequest(() => this.onPacketInContext(pkt));
}
private onPacketInContext(pkt: PacketInfo): void {
const startedAt = Date.now();
packetLog.trace(() => [
'packet_push serviceCmd=%j seqId=%d retCode=%d fromClient=%s pid=%d uin=%j length=%d body=%s',
pkt.serviceCmd,
pkt.seqId,
pkt.retCode,
pkt.fromClient,
pkt.pid,
pkt.uin,
pkt.body.byteLength,
renderTraceBytes(pkt.body),
]);
if (!pkt.uin || !isRealUin(pkt.uin)) {
packetLog.trace(() => [
'packet_terminal serviceCmd=%j seqId=%d outcome=dropped reason=invalid_uin events=0 dispatched=0 elapsedMs=%d',
pkt.serviceCmd,
pkt.seqId,
Date.now() - startedAt,
]);
return;
}
const uin = pkt.uin;
// A packet may be the first trustworthy observation that a live PID moved
// to another UIN. Apply the exact same ownership transition as login so a
// PID can never remain attached to two Bridges.
const client = pkt.pid > 0 ? this.packetClientForPid(pkt.pid) : null;
const { session, created } = client
? this.bindPid(pkt.pid, uin, client, 'packet')
: this.ensureSession(uin);
let completion: Promise<void>;
let handedToPipeline = false;
try {
// A packet may be the first trustworthy observation that a live PID moved
// to another UIN. Apply the exact same ownership transition as login so a
// PID can never remain attached to two Bridges.
const client = pkt.pid > 0 ? this.packetClientForPid(pkt.pid) : null;
const { session, created } = client
? this.bindPid(pkt.pid, uin, client, 'packet')
: this.ensureSession(uin);
// Notify session started on first real packet
if (created) {
log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge);
// Notify session started on first real packet
if (created) {
log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge);
}
// Dispatch packet to bridge. The pipeline preserves synchronous parsing and
// dispatch; its promise only marks completion of any async enrichment.
handedToPipeline = true;
completion = session.bridge.onPacket(pkt);
} catch (error) {
this.tracePacketFailure(
pkt,
startedAt,
handedToPipeline
? 'pipeline_failed'
: 'routing_failed',
error,
);
throw error;
}
void completion.catch((error) => {
this.tracePacketFailure(
pkt,
startedAt,
'pipeline_failed',
error,
);
});
}
// Dispatch packet to bridge
session.bridge.onPacket(pkt);
private tracePacketFailure(
pkt: PacketInfo,
startedAt: number,
reason: 'routing_failed' | 'pipeline_failed',
error: unknown,
): void {
packetLog.trace(() => [
'packet_terminal serviceCmd=%j seqId=%d outcome=failed reason=%s error=%j events=0 dispatched=0 elapsedMs=%d',
pkt.serviceCmd,
pkt.seqId,
reason,
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
]);
log.error(
'packet %s failed for %s: %s',
reason === 'routing_failed'
? 'routing'
: 'pipeline',
pkt.serviceCmd,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
}
/** Bind PID + sender as one state transition. If the PID changed accounts,
@@ -156,7 +322,7 @@ export class BridgeManager {
throw new Error(message);
}
private detachPidFromSession(pid: number, uin: string): void {
private detachPidFromSession(pid: number, uin: string): boolean {
const mappedUin = this.pidToUin_.get(pid);
if (mappedUin !== uin) {
const message = `BridgeManager invariant violated: PID=${pid} detach expected UIN=${uin}, mapped UIN=${mappedUin ?? 'none'}`;
@@ -186,13 +352,14 @@ export class BridgeManager {
// invariant is known to hold, so a fail-fast error preserves the evidence.
this.pidToUin_.delete(pid);
session.bridge.detachPid(pid);
if (!session.bridge.empty) return;
if (!session.bridge.empty) return false;
this.sessions_.delete(uin);
log.debug('session closed: UIN=%s', uin);
// Fire before dispose() so listeners can still read bridge.identity.
this.fireSessionClosed(uin, session.bridge);
session.bridge.dispose();
return true;
}
private ensureSession(uin: string): { session: QQSession; created: boolean } {
+63 -25
View File
@@ -1,33 +1,52 @@
import { HookManager } from '@snowluma/bridge';
import { configureFileTransport } from '@snowluma/common/log-file-transport';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import { loadRuntimeConfig } from '@snowluma/common/runtime';
import {
DEFAULT_LOG_MAX_TOTAL_MB,
DEFAULT_LOG_PER_UIN,
DEFAULT_LOG_RETAIN_DAYS,
loadRuntimeConfig,
} from '@snowluma/common/runtime';
import { OneBotManager } from '@snowluma/onebot/manager';
import { migrateGlobalSettings } from '@snowluma/onebot/global-config';
import { cleanupInvalidPerUinConfigs } from '@snowluma/onebot/config';
import {
isMessageStoreMigrationWorkerData,
runMessageStoreMigrationWorker,
} from '@snowluma/onebot/message-store-migration-worker';
import { workerData } from 'node:worker_threads';
import { BridgeManager } from './bridge/manager';
import { createNotificationManager } from './notifications/manager';
import { createStateWiring } from './webui/state-wiring';
import { bindSystemFaceCatalog } from './sys-face-catalog';
const runtimeConfig = loadRuntimeConfig();
const log = createLogger('App');
// Last-resort process guards. This is a long-running daemon: a hooked QQ pipe
// can drop at any moment, and a stray rejection on a detached callback (or a
// throw that escapes one) must NOT take the whole process down — otherwise
// Docker restarts it (dropping every session) and a bare Windows run just dies
// ("connection pipe closed", bot offline). Log and keep serving; the bridge's
// own watcher reconnects the dropped pipe. Targeted handlers still cover the
// known paths (e.g. the hook-client send deferreds) — these only catch what
// slips through, and surface its stack so the real source can be fixed.
process.on('unhandledRejection', (reason) => {
log.error('unhandledRejection (kept alive): %s',
reason instanceof Error ? (reason.stack ?? reason.message) : String(reason));
});
process.on('uncaughtException', (error) => {
log.error('uncaughtException (kept alive): %s', error.stack ?? error.message);
});
function installProcessGuards(): void {
// Last-resort process guards. This is a long-running daemon: a hooked QQ pipe
// can drop at any moment, and a stray rejection on a detached callback (or a
// throw that escapes one) must NOT take the whole process down — otherwise
// Docker restarts it (dropping every session) and a bare Windows run just dies
// ("connection pipe closed", bot offline). Log and keep serving; the bridge's
// own watcher reconnects the dropped pipe. Targeted handlers still cover the
// known paths (e.g. the hook-client send deferreds) — these only catch what
// slips through, and surface its stack so the real source can be fixed.
process.on('unhandledRejection', (reason) => {
log.error('unhandledRejection (kept alive): %s',
reason instanceof Error ? (reason.stack ?? reason.message) : String(reason));
});
process.on('uncaughtException', (error) => {
log.error('uncaughtException (kept alive): %s', error.stack ?? error.message);
});
}
async function main() {
const runtimeConfig = loadRuntimeConfig();
await configureFileTransport({
maxTotalMb: runtimeConfig.logMaxTotalMb ?? DEFAULT_LOG_MAX_TOTAL_MB,
retainDays: runtimeConfig.logRetainDays ?? DEFAULT_LOG_RETAIN_DAYS,
perUinEnabled: runtimeConfig.logPerUin ?? DEFAULT_LOG_PER_UIN,
});
log.info('SnowLuma starting');
// One-shot: lift a legacy per-UIN musicSignUrl into the global store before
@@ -39,6 +58,7 @@ async function main() {
cleanupInvalidPerUinConfigs();
const bridgeManager = new BridgeManager();
bindSystemFaceCatalog(bridgeManager);
const oneBotManager = new OneBotManager();
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
@@ -63,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);
}
@@ -98,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);
};
@@ -123,8 +154,15 @@ function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
return fromConfig === true;
}
main().catch(async (error) => {
log.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
await closeLogger();
process.exit(1);
});
if (isMessageStoreMigrationWorkerData(workerData)) {
runMessageStoreMigrationWorker(workerData).catch(() => {
process.exitCode = 1;
});
} else {
installProcessGuards();
main().catch(async (error) => {
log.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
await closeLogger();
process.exit(1);
});
}
+165 -6
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 } : {}),
};
}
@@ -170,11 +314,22 @@ function ensureConfigDir(): void {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
function enforceSensitiveFileMode(file: string): void {
// POSIX mode bits do not model Windows ACLs; on Windows the inherited ACL
// remains authoritative. Avoid pretending chmod provides equivalent policy.
if (process.platform !== 'win32') fs.chmodSync(file, 0o600);
}
function atomicWrite(config: NotificationsConfig): void {
ensureConfigDir();
const tmp = NOTIFICATIONS_CONFIG_PATH + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), 'utf8');
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), {
encoding: 'utf8',
mode: 0o600,
});
enforceSensitiveFileMode(tmp);
fs.renameSync(tmp, NOTIFICATIONS_CONFIG_PATH);
enforceSensitiveFileMode(NOTIFICATIONS_CONFIG_PATH);
}
let cached: NotificationsConfig | null = null;
@@ -195,6 +350,10 @@ export function loadNotificationsConfig(): NotificationsConfig {
return fresh;
}
// Webhook URLs commonly embed credentials. Repair older permissive files
// before reading them into memory so upgrades close the exposure promptly.
enforceSensitiveFileMode(NOTIFICATIONS_CONFIG_PATH);
try {
const raw = fs.readFileSync(NOTIFICATIONS_CONFIG_PATH, 'utf8');
const parsed = JSON.parse(raw) as unknown;
@@ -203,8 +362,8 @@ export function loadNotificationsConfig(): NotificationsConfig {
if (JSON.stringify(parsed) !== JSON.stringify(normalized)) {
try {
atomicWrite(normalized);
} catch {
/* best-effort self-heal */
} catch (err) {
log.warn('failed to normalize notifications.json on disk: %s', err instanceof Error ? err.message : String(err));
}
}
cached = normalized;
+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');
}
+40
View File
@@ -0,0 +1,40 @@
import path from 'node:path';
import { createLogger } from '@snowluma/common/logger';
import {
SysFaceStore,
sysFaceStore,
type SysFaceCatalogStorage,
} from '@snowluma/protocol/sys-face-store';
import { JsonSysFaceCatalogStorage } from '@snowluma/protocol/sys-face-storage';
import type { BridgeManager } from './bridge/manager';
const log = createLogger('SysFace');
export interface SystemFaceCatalogBindingOptions {
store?: SysFaceStore;
storage?: SysFaceCatalogStorage;
dataRoot?: string;
}
/** Attach the shared system-face catalog to Bridge login edges. The first
* account restores + refreshes it; later accounts reuse the same result. */
export function bindSystemFaceCatalog(
manager: BridgeManager,
options: SystemFaceCatalogBindingOptions = {},
): void {
const store = options.store ?? sysFaceStore;
const storage = options.storage ?? new JsonSysFaceCatalogStorage(
path.join(options.dataRoot ?? 'data', 'sys-face-catalog.json'),
);
store.configureStorage(storage);
manager.addSessionStartedListener((uin, bridge) => {
void store.prewarm(bridge).catch((error) => {
log.error(
'system face catalog login prewarm failed: uin=%s error=%s',
uin,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
});
});
}
+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;
}
}
+7 -18
View File
@@ -4,9 +4,10 @@
// can't leak and an import can't path-traverse.
//
// Credentials are gated by a toggle on both export and import. The credential
// set is: webui.json (password hash), key.pem (TLS private key), AND every
// OneBot config (onebot.json + per-account onebot_<uin>.json) — those carry the
// OneBot access token, so a no-credentials backup must NOT include them.
// set is: webui.json (password hash), key.pem (TLS private key),
// notifications.json (webhook URLs / SMTP passwords), AND every OneBot config
// (onebot.json + per-account onebot_<uin>.json) — those carry access tokens, so
// a no-credentials backup must NOT include them.
// cert.pem is public so it always travels.
//
// Pure functions here own bundle validation and semantic preflight. Filesystem
@@ -17,10 +18,10 @@ import { normalizeRuntimeConfig } from '@snowluma/common/runtime';
import { isRealUin } from '@snowluma/common/uin';
import { normalizeGlobalSettings } from '@snowluma/onebot/global-config';
import { prepareOneBotConfigForRestore } from '@snowluma/onebot/config';
import { isIP } from 'node:net';
import { normalizeNotificationsConfig } from '../notifications/config';
import { prepareWebuiAuthStateForRestore } from './auth';
import { MAX_BACKGROUND_BYTES, normalizeStoredUiConfig, sniffImageMime } from './ui-config';
import { isValidBindHost } from './listener-exposure';
import { validateTlsPair } from './tls';
export const BACKUP_VERSION = 1;
@@ -39,9 +40,8 @@ export interface BackupFileSpec {
export const BACKUP_FILES: readonly BackupFileSpec[] = [
{ name: 'runtime.json', binary: false, credential: false },
{ name: 'ui.json', binary: false, credential: false },
{ name: 'notifications.json', binary: false, credential: false },
// Global all-accounts SnowLuma settings (rkey fallback servers, …). Same
// class as notifications.json: global, opt-in, non-credential.
{ name: 'notifications.json', binary: false, credential: true },
// Global all-accounts SnowLuma settings (rkey fallback servers, …).
{ name: 'snowluma.json', binary: false, credential: false },
{ name: 'cert.pem', binary: false, credential: false },
{ name: 'ui-assets/background', binary: true, credential: false },
@@ -450,17 +450,6 @@ function serializeJson(value: unknown): Buffer {
return Buffer.from(JSON.stringify(value, null, 2), 'utf8');
}
function isValidBindHost(value: string): boolean {
const host = value.trim();
if (!host || host !== value || host.length > 253 || /[\s/?#@]/u.test(host)) return false;
if (host.includes(':')) return isIP(host) === 6;
if (/^[\d.]+$/.test(host)) {
return isIP(host) === 4;
}
const normalized = host.endsWith('.') ? host.slice(0, -1) : host;
return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$/.test(label));
}
function validateEffectiveTls(restore: PreparedRestoreFile[], opts: PrepareRestoreOptions): void {
const byName = new Map(restore.map((file) => [file.name, file.data]));
const pairTouched = byName.has('cert.pem') || byName.has('key.pem');
+29 -12
View File
@@ -28,15 +28,23 @@ export function describeTrustProxy(mode: TrustProxyMode): string {
}
}
function isLoopback(ip: string): boolean {
return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
export function isLoopbackClientIp(ip: string): boolean {
const normalized = ip.trim().toLowerCase();
if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') return true;
if (normalized.startsWith('::ffff:')) {
return isLoopbackClientIp(normalized.slice('::ffff:'.length));
}
const octets = normalized.split('.');
return octets.length === 4
&& octets[0] === '127'
&& octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
}
function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean {
switch (mode.kind) {
case 'none': return false;
case 'all': return true;
case 'loopback': return isLoopback(socketIp);
case 'loopback': return isLoopbackClientIp(socketIp);
case 'ip-list': return mode.ips.has(socketIp);
}
}
@@ -45,11 +53,15 @@ export function pickClientIp(
c: Pick<Context, 'req'>,
mode: TrustProxyMode,
getSocketIp: () => string,
fallbackIp = '127.0.0.1',
): string {
const socketIp = (() => {
try { return getSocketIp() || '127.0.0.1'; }
catch { return '127.0.0.1'; }
})();
let socketIp: string;
try {
socketIp = getSocketIp();
} catch {
return fallbackIp;
}
if (!socketIp) return fallbackIp;
if (!shouldTrustHeaders(mode, socketIp)) return socketIp;
@@ -64,9 +76,14 @@ export function pickClientIp(
}
/** Convenience binding for the live server: read socket via getConnInfo. */
export function makeClientIpResolver(mode: TrustProxyMode): (c: Context) => string {
return (c) => pickClientIp(c, mode, () => {
try { return getConnInfo(c).remote.address ?? '127.0.0.1'; }
catch { return '127.0.0.1'; }
});
export function makeClientIpResolver(
mode: TrustProxyMode,
fallbackIp = '127.0.0.1',
): (c: Context) => string {
return (c) => pickClientIp(
c,
mode,
() => getConnInfo(c).remote.address ?? fallbackIp,
fallbackIp,
);
}
@@ -11,8 +11,15 @@
* something update.
*/
import {
createLogger,
runWithTraceRequest,
} from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import type { StateBus } from './state-bus';
const log = createLogger('WebUI.Connections');
export interface ConnectionDiffLoopOptions {
bus: StateBus;
/** Read the current adapter-status snapshot for every live UIN. */
@@ -43,6 +50,7 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
// a shape regression would otherwise wedge the baseline silently — no
// publishes, no log, no symptom besides "the dashboard's connections
// card stops updating". Surface it ONCE so the failure is visible.
let warnedSnapshotThrew = false;
let warnedProjectorThrew = false;
const tick = (): void => {
@@ -50,7 +58,19 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
let snap: unknown;
try {
snap = opts.getSnapshot();
} catch {
} catch (err) {
if (!warnedSnapshotThrew) {
warnedSnapshotThrew = true;
runWithTraceRequest(() => {
const startedAt = Date.now();
log.trace('connection_diff_start phase=snapshot_read');
log.trace(
'connection_diff_terminal outcome=failed reason=snapshot_failed error=%j elapsedMs=%d',
err instanceof Error ? err.message : String(err),
Date.now() - startedAt,
);
});
}
// Snapshot read failed (e.g. mid-shutdown). Skip this tick; the
// next one will retry. Don't reset the baseline so we don't
// spuriously republish when the snapshot starts working again.
@@ -65,10 +85,22 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
// so an operator can find it without re-running the loop locally.
if (!warnedProjectorThrew) {
warnedProjectorThrew = true;
// Static logger import avoided to keep the loop self-contained;
// stderr is good enough for a once-per-process latch.
// eslint-disable-next-line no-console
console.error('[connection-diff-loop] pickComparable threw — connections SSE diff will wedge until restart:', err);
log.error(
'connection snapshot projector failed; updates may be stale: %s',
err instanceof Error ? err.message : String(err),
);
runWithTraceRequest(() => {
const startedAt = Date.now();
log.trace(() => [
'connection_diff_start phase=project snapshot=%s',
renderParamsVerbose(snap),
]);
log.trace(
'connection_diff_terminal outcome=failed reason=projector_failed error=%j elapsedMs=%d',
err instanceof Error ? err.message : String(err),
Date.now() - startedAt,
);
});
}
return;
}
@@ -84,7 +116,19 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
}
if (serialized === lastSerialized) return;
lastSerialized = serialized;
opts.bus.publish('connections');
runWithTraceRequest(() => {
const startedAt = Date.now();
log.trace(() => [
'connection_diff_start snapshot=%s',
renderParamsVerbose(snap),
]);
log.trace('connection_diff_branch branch=publish resource=connections');
opts.bus.publish('connections');
log.trace(
'connection_diff_terminal outcome=completed reason=published elapsedMs=%d',
Date.now() - startedAt,
);
});
};
const timer = setInterval(tick, intervalMs);
@@ -0,0 +1,28 @@
import type { AccountConnections } from '@snowluma/onebot/manager';
export function comparableConnectionSnapshot(snapshot: unknown): unknown {
if (!Array.isArray(snapshot)) return snapshot;
return (snapshot as AccountConnections[]).map((account) => ({
uin: account.uin,
nickname: account.nickname,
adapters: Array.isArray(account.adapters)
? account.adapters.map((adapter) => ({
name: adapter.name,
kind: adapter.kind,
status: adapter.status,
lastErrorAt: adapter.lastErrorAt,
}))
: [],
databaseMigration: account.databaseMigration
? {
phase: account.databaseMigration.phase,
usable: account.databaseMigration.usable,
processed: account.databaseMigration.processed,
total: account.databaseMigration.total,
progress: account.databaseMigration.progress,
estimatedRemainingSeconds: account.databaseMigration.estimatedRemainingSeconds,
error: account.databaseMigration.error,
}
: undefined,
}));
}
+5 -2
View File
@@ -19,10 +19,11 @@ import { mkdir, readdir, rm, stat } from 'fs/promises';
import os from 'os';
import path from 'path';
import { randomBytes } from 'crypto';
import { traceWebuiMutationRequestChunk } from './mutation-trace';
/** Temp dir for browser→server uploads. Siblings the Stream API's temp root but
* kept distinct so the two cleanup stories don't entangle. */
export const DEBUG_UPLOAD_DIR = path.join(os.tmpdir(), 'snowluma-debug-upload');
export const DEBUG_UPLOAD_DIR = path.join(os.tmpdir(), 'webui-upload');
/** Hard ceiling on a single upload. Mirrors the Stream API's upload cap. */
export const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
@@ -38,7 +39,7 @@ export function safeUploadName(raw: string | undefined): string {
// `../` / absolute prefix is discarded regardless of host platform.
const base = path.basename(String(raw ?? '').replace(/\\/g, '/'));
const cleaned = base
.replace(/[^\w.\-]+/g, '_') // collapse anything exotic to underscore
.replace(/[^\w.-]+/g, '_') // collapse anything exotic to underscore
.replace(/^\.+/, '') // no leading dots (no hidden / '..' names)
.slice(0, 120);
return cleaned || 'file';
@@ -88,7 +89,9 @@ export async function streamUploadToDisk(
const { done, value } = await Promise.race([errored, reader.read()]);
if (done) break;
if (!value || value.byteLength === 0) continue;
const offset = size;
size += value.byteLength;
traceWebuiMutationRequestChunk(value, offset);
if (size > maxBytes) throw new Error('上传超出大小上限');
// Respect the write stream's backpressure (but never hang on an error).
if (!out.write(value)) {
@@ -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 };
}
+69
View File
@@ -0,0 +1,69 @@
import type { LogEntry } from '@snowluma/common/logger';
export interface FullTraceExportMetadata {
version: string;
operatingSystem: string;
architecture: string;
nodeVersion: string;
logLevel: LogEntry['level'];
exportedAt: string;
}
const PRIVACY_WARNING = 'WARNING: This export may contain unredacted private data and credentials. Sanitize it before submission.';
export interface FullTraceDownload {
body: string;
headers: {
'Content-Type': string;
'Content-Disposition': string;
'Cache-Control': string;
};
}
export function buildFullTraceDownload(
entries: readonly LogEntry[],
metadata: FullTraceExportMetadata,
): FullTraceDownload {
const timestamp = metadata.exportedAt
.slice(0, 19)
.replace(/[:.]/g, '-');
return {
body: formatFullTraceExport(entries, metadata),
headers: {
'Content-Type': 'text/plain; charset=utf-8',
'Content-Disposition': `attachment; filename="snowluma-trace-${timestamp}.log"`,
'Cache-Control': 'no-store',
},
};
}
export function formatFullTraceExport(
entries: readonly LogEntry[],
metadata: FullTraceExportMetadata,
): string {
const lines = [
'SnowLuma full TRACE export',
'==========================',
`SnowLuma version: ${metadata.version}`,
`Operating system: ${metadata.operatingSystem}`,
`Architecture: ${metadata.architecture}`,
`Node.js version: ${metadata.nodeVersion}`,
`Current log level: ${metadata.logLevel.toUpperCase()}`,
`Export time: ${metadata.exportedAt}`,
`Retained records: ${entries.length}`,
'',
PRIVACY_WARNING,
'This is a snapshot of the normal and TRACE records still retained in memory; records already evicted cannot be recovered.',
'',
'Logs',
'----',
];
if (entries.length === 0) {
lines.push('(No log records are currently retained.)');
} else {
lines.push(...entries.map((entry) => entry.line));
}
return `${lines.join('\n')}\n`;
}
+297
View File
@@ -0,0 +1,297 @@
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import {
createLogger,
currentRequestId,
getLogLevel,
renderTraceBytes,
runWithRequestId,
runWithTraceRequest,
} from '@snowluma/common/logger';
const log = createLogger('WebUI.Mutation');
const READ_ONLY_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
const STREAMED_REQUEST_PATHS = new Set(['/api/debug/upload']);
const STREAMED_RESPONSE_PATHS = new Set(['/api/debug/invoke-stream']);
// This route can disable TRACE while its own operation is in flight; its
// existing WebUI info record is the authoritative result.
const TRACE_EXCLUDED_PATHS = new Set([
'/api/auth/check-strength',
'/api/logs/level',
]);
interface CapturedBody {
bytes: Uint8Array;
text: string;
}
function shouldTraceMutation(request: Request): boolean {
if (getLogLevel() !== 'trace') return false;
if (READ_ONLY_METHODS.has(request.method.toUpperCase())) return false;
return !TRACE_EXCLUDED_PATHS.has(new URL(request.url).pathname);
}
async function captureBody(message: Request | Response): Promise<CapturedBody> {
const bytes = new Uint8Array(await message.arrayBuffer());
return {
bytes,
text: new TextDecoder().decode(bytes),
};
}
function traceBody(
branch: 'request_body' | 'response',
body: CapturedBody,
response?: Response,
): void {
log.trace(() => [
'webui_mutation_branch branch=%s%s length=%d text=%j body=%s',
branch,
response
? ` status=${response.status} statusText=${JSON.stringify(response.statusText)} headers=${renderParamsVerbose([...response.headers.entries()])}`
: '',
body.bytes.byteLength,
body.text,
renderTraceBytes(body.bytes),
]);
}
function traceStreamChunk(
branch: 'request_body_chunk' | 'response_chunk',
chunk: Uint8Array,
offset: number,
): void {
log.trace(() => [
'webui_mutation_branch branch=%s offset=%d length=%d body=%s',
branch,
offset,
chunk.byteLength,
renderTraceBytes(chunk),
]);
}
export function traceWebuiMutationRequestChunk(chunk: Uint8Array, offset: number): void {
traceStreamChunk('request_body_chunk', chunk, offset);
}
function traceStreamedResponse(
response: Response,
requestBody: Promise<CapturedBody> | null,
startedAt: number,
): Response {
if (!response.body) {
void settleMutation(
requestBody,
Promise.resolve({ bytes: new Uint8Array(), text: '' }),
response,
startedAt,
false,
);
return response;
}
const reader = response.body.getReader();
const requestId = currentRequestId();
const inContext = <T>(fn: () => T): T => requestId === undefined
? fn()
: runWithRequestId(requestId, fn);
let offset = 0;
let settled = false;
const terminal = (outcome: 'completed' | 'failed' | 'cancelled', reason: string, error?: unknown) => {
if (settled) return;
settled = true;
void inContext(() => traceRequestBody(requestBody)).then(() => {
inContext(() => log.trace(
'webui_mutation_terminal outcome=%s reason=%s status=%d%s elapsedMs=%d',
outcome,
reason,
response.status,
error === undefined ? '' : ` error=${JSON.stringify(error instanceof Error ? error.message : String(error))}`,
Date.now() - startedAt,
));
});
};
const body = new ReadableStream<Uint8Array>({
async pull(controller) {
try {
const result = await reader.read();
if (result.done) {
terminal(response.ok ? 'completed' : 'failed', response.ok ? 'response_completed' : 'http_status');
controller.close();
return;
}
const chunk = result.value;
inContext(() => traceStreamChunk('response_chunk', chunk, offset));
offset += chunk.byteLength;
controller.enqueue(chunk);
} catch (error) {
terminal(error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'failed',
error instanceof Error && error.name === 'AbortError' ? 'body_cancelled' : 'body_read_failed', error);
controller.error(error);
}
},
async cancel(reason) {
terminal('cancelled', 'body_cancelled', reason);
await reader.cancel(reason);
},
}, { highWaterMark: 0 });
return new Response(body, response);
}
async function traceRequestBody(requestBody: Promise<CapturedBody> | null): Promise<void> {
if (!requestBody) return;
try {
traceBody('request_body', await requestBody);
} catch (error) {
log.trace(
'webui_mutation_branch branch=request_body_failed error=%j',
error instanceof Error ? error.message : String(error),
);
}
}
async function settleMutation(
requestBody: Promise<CapturedBody> | null,
responseBody: Promise<CapturedBody>,
response: Response,
startedAt: number,
requestCancelled: boolean,
): Promise<void> {
const results = await Promise.allSettled([
requestBody ?? Promise.resolve<CapturedBody>({ bytes: new Uint8Array(), text: '' }),
responseBody,
]);
const [requestResult, responseResult] = results;
if (requestBody && requestResult.status === 'fulfilled') traceBody('request_body', requestResult.value);
if (requestBody && requestResult.status === 'rejected') {
log.trace('webui_mutation_branch branch=request_body_failed error=%j',
requestResult.reason instanceof Error ? requestResult.reason.message : String(requestResult.reason));
}
if (responseResult.status === 'fulfilled') traceBody('response', responseResult.value, response);
else {
log.trace(() => [
'webui_mutation_branch branch=response_body_failed status=%d statusText=%j headers=%s error=%j',
response.status,
response.statusText,
renderParamsVerbose([...response.headers.entries()]),
responseResult.reason instanceof Error ? responseResult.reason.message : String(responseResult.reason),
]);
}
const error = responseResult.status === 'rejected'
? responseResult.reason
: requestResult.status === 'rejected'
? requestResult.reason
: undefined;
if (error === undefined) {
if (requestCancelled) {
log.trace(
'webui_mutation_terminal outcome=cancelled reason=request_cancelled status=%d elapsedMs=%d',
response.status,
Date.now() - startedAt,
);
return;
}
log.trace(
'webui_mutation_terminal outcome=%s reason=%s status=%d elapsedMs=%d',
response.ok ? 'completed' : 'failed',
response.ok ? 'response_completed' : 'http_status',
response.status,
Date.now() - startedAt,
);
return;
}
log.trace(
'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d',
error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'failed',
error instanceof Error && error.name === 'AbortError' ? 'body_cancelled' : 'body_read_failed',
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
}
function failureOutcome(error: unknown): {
outcome: 'failed' | 'timeout' | 'cancelled';
reason: string;
} {
if (error instanceof Error && error.name === 'TimeoutError') {
return { outcome: 'timeout', reason: 'handler_timeout' };
}
if (error instanceof Error && error.name === 'AbortError') {
return { outcome: 'cancelled', reason: 'handler_cancelled' };
}
return { outcome: 'failed', reason: 'handler_threw' };
}
/** Trace one authenticated WebUI write without consuming its live streams. */
export function traceAuthenticatedWebuiMutation(
request: Request,
next: () => Promise<Response>,
): Promise<Response> {
if (!shouldTraceMutation(request)) return next();
return runWithTraceRequest(async () => {
const startedAt = Date.now();
const requestHeaders = [...request.headers.entries()];
const pathname = new URL(request.url).pathname;
let requestBody: Promise<CapturedBody> | null = null;
log.trace(() => [
'webui_mutation_start method=%j url=%j headers=%s',
request.method,
request.url,
renderParamsVerbose(requestHeaders),
]);
if (!STREAMED_REQUEST_PATHS.has(pathname)) {
try {
requestBody = captureBody(request.clone());
} catch (error) {
log.trace(
'webui_mutation_terminal outcome=failed reason=request_clone_failed error=%j elapsedMs=%d',
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
return next();
}
}
try {
const response = await next();
if (STREAMED_RESPONSE_PATHS.has(pathname)) {
return traceStreamedResponse(response, requestBody, startedAt);
}
let responseBody: Promise<CapturedBody>;
try {
responseBody = captureBody(response.clone());
} catch (error) {
void traceRequestBody(requestBody).then(() => {
log.trace(
'webui_mutation_terminal outcome=failed reason=response_clone_failed error=%j elapsedMs=%d',
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
});
return response;
}
void settleMutation(
requestBody,
responseBody,
response,
startedAt,
STREAMED_REQUEST_PATHS.has(pathname) && request.signal.aborted,
);
return response;
} catch (error) {
await traceRequestBody(requestBody);
const failure = failureOutcome(error);
log.trace(
'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d',
failure.outcome,
failure.reason,
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
throw error;
}
});
}
@@ -0,0 +1,88 @@
import { assessAccessToken } from '@snowluma/common/access-token';
import type { OneBotConfig } from '@snowluma/onebot/types';
import { isLoopbackClientIp } from './client-ip';
function isLoopbackBindHost(host: string | undefined): boolean {
const value = host?.trim().toLowerCase().replace(/^\[|\]$/gu, '').replace(/\.$/u, '') ?? '';
if (!value) return false;
if (value === 'localhost' || value.endsWith('.localhost')) return true;
return isLoopbackClientIp(value);
}
export class OneBotAccessTokenPolicyError extends Error {
constructor(message: string) {
super(message);
this.name = 'OneBotAccessTokenPolicyError';
}
}
export interface OneBotAccessTokenPolicyOptions {
clientIp: string;
uin: string;
}
type InboundKind = 'httpServers' | 'wsServers';
const INBOUND_KINDS: readonly InboundKind[] = ['httpServers', 'wsServers'];
function sameTokenAtPreviousIdentity(
previous: OneBotConfig['networks'][InboundKind],
next: OneBotConfig['networks'][InboundKind],
nextName: string,
nextToken: string,
index: number,
): boolean {
const named = previous.find((adapter) => adapter.name === nextName);
if (named && (named.accessToken ?? '') === nextToken) return true;
// Preserve a legacy token when the operator only renames the same list item.
// Reordering keeps names stable and is covered by the lookup above.
const sameIndex = previous[index];
return sameIndex !== undefined
&& !next.some((adapter) => adapter.name === sameIndex.name)
&& (sameIndex.accessToken ?? '') === nextToken;
}
export function validateOneBotAccessTokenChanges(
previous: OneBotConfig | null,
next: OneBotConfig,
options: OneBotAccessTokenPolicyOptions,
): void {
const allowEmptyFromClient = isLoopbackClientIp(options.clientIp);
for (const kind of INBOUND_KINDS) {
const previousList = previous?.networks[kind] ?? [];
const nextList = next.networks[kind];
for (let index = 0; index < nextList.length; index += 1) {
const adapter = nextList[index];
const token = adapter.accessToken ?? '';
if (sameTokenAtPreviousIdentity(previousList, nextList, adapter.name, token, index)) continue;
if (!token) {
if (!allowEmptyFromClient && !isLoopbackBindHost(adapter.host)) {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”未绑定本机地址,远程保存必须填写令牌;请生成令牌或将主机改为 127.0.0.1。`,
);
}
continue;
}
const host = adapter.host ?? '0.0.0.0';
const assessment = assessAccessToken(token, [
options.uin,
adapter.name,
kind,
host,
adapter.port,
]);
if (assessment.reason === 'too-short') {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”的令牌至少需要 16 个字符;请重新生成或继续补充。`,
);
}
if (!assessment.acceptable) {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”的令牌容易被猜中;请重新生成随机令牌。`,
);
}
}
}
}
+7 -3
View File
@@ -1,6 +1,6 @@
import net from 'net';
function isPortAvailable(port: number, host = '0.0.0.0'): Promise<boolean> {
function isPortAvailable(port: number, host = '127.0.0.1'): Promise<boolean> {
return new Promise((resolve) => {
const server = net.createServer();
let settled = false;
@@ -27,11 +27,15 @@ function isPortAvailable(port: number, host = '0.0.0.0'): Promise<boolean> {
* Find an available TCP port starting from `start`, advancing by 1 up to `maxTries` attempts.
* Skips reserved/invalid port numbers.
*/
export async function findAvailablePort(start: number, maxTries = 50): Promise<number> {
export async function findAvailablePort(
start: number,
options: { maxTries?: number; host?: string } = {},
): Promise<number> {
const { maxTries = 50, host = '127.0.0.1' } = options;
let port = Math.max(1, Math.min(65535, Math.trunc(start)));
for (let i = 0; i < maxTries; i++) {
if (port > 65535) break;
if (await isPortAvailable(port)) return port;
if (await isPortAvailable(port, host)) return port;
port += 1;
}
throw new Error(`No available TCP port found near ${start}`);
@@ -0,0 +1,65 @@
import { bodyLimit } from 'hono/body-limit';
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
import type { Context, Hono, MiddlewareHandler } from 'hono';
export const LOGIN_BODY_LIMIT_BYTES = 16 * 1024;
const AVATAR_SESSION_COOKIE = 'snowluma_avatar_session';
const AVATAR_SESSION_MAX_AGE_SECONDS = 24 * 60 * 60;
function isJsonMediaType(value: string | undefined): boolean {
const mediaType = value?.split(';', 1)[0]?.trim().toLowerCase() ?? '';
return mediaType === 'application/json' || mediaType.endsWith('+json');
}
/** Install guards before the login route is registered. */
export function registerLoginRequestSecurity(app: Hono): void {
app.use('/api/login', bodyLimit({
maxSize: LOGIN_BODY_LIMIT_BYTES,
onError: (c) => c.json({ success: false, message: '请求体过大' }, 413),
}));
app.use('/api/login', async (c, next) => {
if (!isJsonMediaType(c.req.header('content-type'))) {
return c.json({ success: false, message: 'Content-Type 必须为 application/json' }, 415);
}
return next();
});
}
/** Minimal response policy that does not restrict the current script/style bundle. */
export const webuiSecurityHeaders: MiddlewareHandler = async (c, next) => {
await next();
c.res.headers.set('X-Frame-Options', 'DENY');
c.res.headers.set('X-Content-Type-Options', 'nosniff');
c.res.headers.set('Referrer-Policy', 'no-referrer');
c.res.headers.set(
'Content-Security-Policy',
"frame-ancestors 'none'; base-uri 'self'; object-src 'none'",
);
};
export function extractBearerToken(request: Request): string {
const authorization = request.headers.get('authorization');
return authorization?.startsWith('Bearer ') ? authorization.slice(7) : '';
}
const avatarCookieOptions = (secure: boolean) => ({
httpOnly: true,
sameSite: 'Strict' as const,
secure,
path: '/avatar',
});
export function setAvatarSessionCookie(c: Context, token: string, secure: boolean): void {
setCookie(c, AVATAR_SESSION_COOKIE, token, {
...avatarCookieOptions(secure),
maxAge: AVATAR_SESSION_MAX_AGE_SECONDS,
});
}
export function clearAvatarSessionCookie(c: Context, secure: boolean): void {
deleteCookie(c, AVATAR_SESSION_COOKIE, avatarCookieOptions(secure));
}
export function readAvatarSessionToken(c: Context): string {
return getCookie(c, AVATAR_SESSION_COOKIE) ?? '';
}
+421 -80
View File
@@ -1,14 +1,33 @@
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
import {
clearManagedLogs,
configureFileTransport,
getLogStorageStatus,
} from '@snowluma/common/log-file-transport';
import {
createLogger,
getLogLevel,
getLogSnapshot,
getRecentLogs,
logInitialWebuiCredentials,
LOG_LEVELS,
setLogLevel,
subscribeLogs,
} from '@snowluma/common/logger';
import {
assertValidOneBotConfig,
loadOneBotConfig,
OneBotConfigValidationError,
saveOneBotConfig,
} from '@snowluma/onebot/config';
import { loadGlobalSettings, saveGlobalSettings } from '@snowluma/onebot/global-config';
import type { OneBotManager } from '@snowluma/onebot/manager';
import {
clearInactiveStreamStorage,
snapshotStreamStorage,
} from '@snowluma/onebot/stream-storage';
import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/onebot/types';
import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime';
import { execSync } from 'child_process';
@@ -20,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,
@@ -29,8 +55,9 @@ import {
recordConsent,
resolveEnvironmentConsent,
} from './consent';
import { resolveTlsContext, validateTlsPair } from './tls';
import { coerceSettingsPatch } from './system-settings';
import { requireTlsContext, resolveTlsContext, validateTlsPair } from './tls';
import { coerceSettingsPatch, evaluateSettingsSave, tlsCertDeletionBlocked } from './system-settings';
import { checkListenerExposure } from './listener-exposure';
import { buildBackup } from './backup';
import { restoreBackup, RestoreTransactionError, type RestorePhase } from './restore';
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
@@ -40,7 +67,13 @@ import { sseResponse } from './sse-response';
import { bindStateStream } from './state-stream';
import type { StateBus, StateResource } from './state-bus';
import { startConnectionDiffLoop } from './connection-diff-loop';
import { comparableConnectionSnapshot } from './connection-snapshot';
import { traceAuthenticatedWebuiMutation } from './mutation-trace';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
import {
OneBotAccessTokenPolicyError,
validateOneBotAccessTokenChanges,
} from './onebot-token-policy';
import { findAvailablePort } from './port';
import {
clearBackgroundImage,
@@ -52,9 +85,21 @@ import {
sniffImageMime,
writeBackgroundImage,
} from './ui-config';
import { getUpdateInfo } from './update-check';
import { currentVersion, getUpdateInfo } from './update-check';
import { buildFullTraceDownload } from './log-export';
import { loadNotificationsConfig, saveNotificationsConfig } from '../notifications/config';
import type { NotificationManager } from '../notifications/manager';
import { StorageManagementService } from './storage-management';
import { registerStorageRoutes } from './storage-routes';
import { LogStorageSettingsManager } from './storage-settings';
import {
clearAvatarSessionCookie,
extractBearerToken,
readAvatarSessionToken,
registerLoginRequestSecurity,
setAvatarSessionCookie,
webuiSecurityHeaders,
} from './request-security';
const log = createLogger('WebUI');
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -66,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;
@@ -175,21 +228,6 @@ const CONSENT_ALLOWLIST = new Set([
'/api/logout',
]);
// Endpoints that may authenticate via `?token=` query parameter. Reserved
// for SSE streams: EventSource cannot set custom headers, so these MUST
// accept the token via query. All other endpoints use the Authorization
// header so tokens never leak into access logs / Referer / browser history.
//
// Exported so the regression test can lock the invariant — a missing entry
// here silently 401s the EventSource and the whole push channel goes dark,
// which has happened (see /api/state/stream's first cut).
export const SSE_TOKEN_QUERY_PATHS: ReadonlySet<string> = new Set([
'/api/logs/stream',
'/api/debug/stream',
'/api/state/stream',
]);
const TOKEN_QUERY_ALLOWLIST = SSE_TOKEN_QUERY_PATHS;
// uin = QQ number; 5–10 digits (real QQ UINs fit in uint32, max 4294967295).
// Used to construct config file paths, so we MUST refuse anything else (path
// traversal, NUL bytes, etc.) — and the 10-digit cap also rejects the garbage
@@ -207,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';
}
@@ -418,13 +471,30 @@ export async function initWebUI(
hookManager?: HookManager,
notificationManager?: NotificationManager,
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string; stateBus?: StateBus } = {},
): Promise<{ port: number }> {
): Promise<{ port: number; stop: () => Promise<void> }> {
const host = listener.host || '127.0.0.1';
const tlsEnabled = listener.tlsEnabled === true;
const bootCheck = checkListenerExposure({
webuiHost: host,
tlsEnabled,
pairOk: resolveTlsContext('config').ok,
});
if (!bootCheck.ok) {
const reason = bootCheck.code === 'invalid-bind-host'
? `bind host is not a valid TCP address: ${host}`
: 'TLS is enabled but the certificate/private-key pair is unusable';
throw new Error(`WebUI listener cannot start: ${reason}`);
}
// Resolve the client IP for per-IP rate limiting from the configured
// trust-proxy directive (runtime.json `trustProxy`, env-overridable via
// SNOWLUMA_WEBUI_TRUST_PROXY which loadRuntimeConfig already merged in).
// Default ('') = trust the TCP socket peer only (cannot be spoofed).
const trustProxyMode = parseTrustProxy(listener.trustProxy);
const getClientIp = makeClientIpResolver(trustProxyMode);
// Security decisions must not silently turn an unreadable socket peer into
// localhost. The regular resolver keeps its compatibility fallback for
// rate-limit bucketing; this resolver fails closed with an empty address.
const getSecurityClientIp = makeClientIpResolver(trustProxyMode, '');
// Connection-status diff loop: OneBot adapters don't emit events for
// listening/connected/client-count changes, so we poll the snapshot at
@@ -449,28 +519,12 @@ 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: (snap) => {
if (!Array.isArray(snap)) return snap;
return (snap as Array<{ uin: string; nickname?: string; adapters?: unknown[] }>).map((acc) => ({
uin: acc.uin,
nickname: acc.nickname,
// Empty fallback when `adapters` is not an array — never the
// raw value, which could re-introduce volatile fields verbatim
// if the snapshot shape ever drifts.
adapters: Array.isArray(acc.adapters)
? acc.adapters.map((a: unknown) => {
const o = a as { name?: string; kind?: string; status?: string; lastErrorAt?: number };
return { name: o.name, kind: o.kind, status: o.status, lastErrorAt: o.lastErrorAt };
})
: [],
}));
},
pickComparable: comparableConnectionSnapshot,
intervalMs: 500,
});
}
@@ -482,7 +536,7 @@ export async function initWebUI(
const auth = WebuiAuth.load();
const initialPassword = auth.takeInitialPassword();
if (auth.isDevMode()) {
log.warn('dev mode enabled: password=%s', WebuiAuth.devPassword);
log.warn('dev mode enabled with the configured development credential');
log.warn('dev mode skips config/webui.json and password rotation');
} else if (initialPassword) {
log.info('════════════════════════════════════════════════════════════════');
@@ -491,7 +545,7 @@ export async function initWebUI(
log.info(' 若跳过初始改密,下次启动将自动生成新的随机密码。');
log.info(' Log in and change the password now; it will not be shown again.');
log.info('────────────────────────────────────────────────────────────────');
log.info('initial credentials: user=admin password=%s', initialPassword);
logInitialWebuiCredentials(initialPassword);
log.info('════════════════════════════════════════════════════════════════');
} else if (auth.mustChangePassword()) {
log.warn('password change is still required');
@@ -524,6 +578,29 @@ export async function initWebUI(
}
const app = new Hono();
app.use('*', webuiSecurityHeaders);
registerLoginRequestSecurity(app);
const storageManagement = new StorageManagementService({
dataDir: 'data',
getLogStatus: getLogStorageStatus,
clearLogs: clearManagedLogs,
temporary: {
snapshot: snapshotStreamStorage,
clearInactive: clearInactiveStreamStorage,
},
// Connection statuses include active and still-retiring generations.
// A retiring instance may still hold SQLite handles after disappearing
// from getInstances(), so it must continue to block destructive cleanup.
listOnlineAccounts: () => oneBotManager.getConnectionStatuses()
.map((account) => ({ uin: account.uin, nickname: account.nickname })),
});
const logStorageSettings = new LogStorageSettingsManager({
readPersisted: readRuntimeConfig,
readEnvOverrides: () => resolveRuntimeEnvOverrides(process.env),
readEffective: getLogStorageStatus,
persist: updateRuntimeConfig,
apply: configureFileTransport,
});
// ─── Anti-indexing ───────────────────────────────────────────────────────
// The WebUI is an admin surface that has no business showing up in
@@ -553,10 +630,7 @@ export async function initWebUI(
// nothing sensitive (no layout, no secrets) — see ui-config.ts.
if (reqPath === '/api/login' || reqPath === '/api/ui/public') return next();
const authHeader = c.req.header('Authorization');
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : '';
const queryToken = TOKEN_QUERY_ALLOWLIST.has(reqPath) ? (c.req.query('token') ?? '') : '';
const token = bearerToken || queryToken;
const token = extractBearerToken(c.req.raw);
if (!token) return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
const info = sessionTokens.get(token);
@@ -580,7 +654,10 @@ export async function initWebUI(
}
c.set('sessionToken' as never, token);
await next();
c.res = await traceAuthenticatedWebuiMutation(c.req.raw, async () => {
await next();
return c.res;
});
});
// Periodic janitor — keeps sessionTokens / loginAttempts from growing
@@ -598,31 +675,48 @@ export async function initWebUI(
return c.json({ success: false, message: `登录尝试过多,请 ${waitSec} 秒后重试` }, 429);
}
let body: { password?: unknown };
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const password = typeof body.password === 'string' ? body.password : '';
if (!auth.verify(password)) {
const result = completeWebuiLogin(auth, body, now);
if (result.kind === 'bad-request') {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
if (result.kind === 'bad-password' || result.kind === 'bad-second-factor') {
const current = loginAttempts.get(ip) ?? { count: 0, resetAt: now + LOGIN_LOCKOUT_MS };
current.count += 1;
if (current.count === 1) current.resetAt = now + LOGIN_LOCKOUT_MS;
loginAttempts.set(ip, current);
return c.json({ success: false, message: '密码错误' }, 401);
const message = result.kind === 'bad-second-factor' ? '验证码不正确' : '密码错误';
return c.json({ success: false, message }, 401);
}
if (result.kind === 'needs-totp') {
return c.json({ success: false, needsTotp: true });
}
loginAttempts.delete(ip);
if (result.totpState) {
try {
auth.persistTotp(result.totpState);
} catch (err) {
log.warn('persist totp after login failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '登录失败' }, 500);
}
}
const token = randomBytes(32).toString('hex');
const mustChange = auth.mustChangePassword();
sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange });
return c.json({ success: true, token, mustChangePassword: mustChange });
sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: result.mustChangePassword });
setAvatarSessionCookie(c, token, listener.tlsEnabled === true);
return c.json({ success: true, token, mustChangePassword: result.mustChangePassword });
});
app.post('/api/logout', (c) => {
const token = c.get('sessionToken' as never) as string | undefined;
if (token) sessionTokens.delete(token);
clearAvatarSessionCookie(c, listener.tlsEnabled === true);
return c.json({ success: true });
});
@@ -667,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);
@@ -676,10 +770,172 @@ export async function initWebUI(
// password was compromised, the attacker may already hold the current
// token; rotating credentials must rotate sessions too.
sessionTokens.clear();
clearAvatarSessionCookie(c, listener.tlsEnabled === true);
log.info('password updated; all sessions invalidated');
return c.json({ success: true, requireRelogin: true });
});
const totpDisabledInDev = () => auth.isDevMode();
app.get('/api/auth/totp', (c) => {
if (totpDisabledInDev()) {
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
}
return c.json(auth.totpStatus());
});
app.post('/api/auth/totp/begin', async (c) => {
if (totpDisabledInDev()) {
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
}
if (auth.totpEnabled()) {
return c.json({ success: false, message: '2FA 已开启' }, 409);
}
const token = c.get('sessionToken' as never) as string;
let body: Record<string, unknown> = {};
try {
const parsed = await c.req.json();
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
body = parsed as Record<string, unknown>;
}
} catch {
body = {};
}
const issuer = sanitizeTotpLabelPart(body.issuer, DEFAULT_TOTP_ISSUER);
const accountName = sanitizeTotpLabelPart(body.accountName, defaultTotpAccountName());
const now = Date.now();
const existing = totpEnrollments.get(token);
const secret = existing && existing.expiresAt > now ? existing.secret : undefined;
const enrollment = beginTotpEnrollment({ issuer, accountName, secret });
totpEnrollments.set(token, {
secret: enrollment.secret,
issuer,
accountName,
expiresAt: now + TOTP_ENROLL_TTL_MS,
});
return c.json({
success: true,
secret: enrollment.secret,
otpauthUrl: enrollment.otpauthUrl,
issuer: enrollment.issuer,
accountName: enrollment.accountName,
});
});
app.post('/api/auth/totp/confirm', async (c) => {
if (totpDisabledInDev()) {
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
}
if (auth.totpEnabled()) {
return c.json({ success: false, message: '2FA 已开启' }, 409);
}
const token = c.get('sessionToken' as never) as string;
let body: { password?: unknown; code?: unknown };
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const password = typeof body.password === 'string' ? body.password : '';
const code = typeof body.code === 'string' ? body.code : '';
if (!auth.verify(password)) {
return c.json({ success: false, message: '当前密码不正确' }, 401);
}
const pending = totpEnrollments.get(token);
if (!pending || pending.expiresAt <= Date.now()) {
totpEnrollments.delete(token);
return c.json({ success: false, message: '请先开始绑定' }, 400);
}
try {
const enabled = confirmTotpEnrollment({
password,
secret: pending.secret,
code,
label: `${pending.issuer} (${pending.accountName})`,
atMs: Date.now(),
});
auth.persistTotp(enabled.state);
totpEnrollments.delete(token);
invalidateOtherSessions(sessionTokens, token);
log.info('webui 2FA enabled; other sessions invalidated');
return c.json({ success: true, recoveryCodes: enabled.recoveryCodes });
} catch (err) {
log.warn('totp confirm failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '验证码不正确' }, 401);
}
});
app.post('/api/auth/totp/disable', async (c) => {
if (totpDisabledInDev()) {
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
}
if (!auth.totpEnabled()) {
return c.json({ success: false, message: '2FA 未开启' }, 400);
}
const token = c.get('sessionToken' as never) as string;
let body: { password?: unknown; totp?: unknown; recoveryCode?: unknown };
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const password = typeof body.password === 'string' ? body.password : '';
if (!auth.verify(password)) {
return c.json({ success: false, message: '当前密码不正确' }, 401);
}
const decision = decideSecondFactorLogin({
totpEnabled: true,
state: auth.totpState(),
password,
totp: typeof body.totp === 'string' ? body.totp : undefined,
recoveryCode: typeof body.recoveryCode === 'string' ? body.recoveryCode : undefined,
atMs: Date.now(),
});
if (decision.kind !== 'ok') {
return c.json({ success: false, message: '验证码不正确' }, 401);
}
auth.persistTotp(undefined);
totpEnrollments.delete(token);
invalidateOtherSessions(sessionTokens, token);
log.info('webui 2FA disabled; other sessions invalidated');
return c.json({ success: true });
});
app.post('/api/auth/totp/recovery-codes', async (c) => {
if (totpDisabledInDev()) {
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
}
const state = auth.totpState();
if (!state) {
return c.json({ success: false, message: '2FA 未开启' }, 400);
}
let body: { password?: unknown; totp?: unknown };
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const password = typeof body.password === 'string' ? body.password : '';
const totp = typeof body.totp === 'string' ? body.totp : '';
if (!auth.verify(password)) {
return c.json({ success: false, message: '当前密码不正确' }, 401);
}
try {
const next = regenerateRecoveryCodes({
password,
state,
totp,
atMs: Date.now(),
});
auth.persistTotp(next.state);
log.info('webui 2FA recovery codes regenerated');
return c.json({ success: true, recoveryCodes: next.recoveryCodes });
} catch (err) {
log.warn('totp recovery regenerate failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '验证码不正确' }, 401);
}
});
// ─── EULA / PRIVACY consent ──────────────────────────────────────────────
// Both are bearer-gated (consent is collected AFTER login) and live in the
// consent + must-change allowlists so they're reachable during onboarding.
@@ -717,6 +973,12 @@ export async function initWebUI(
// ─── Avatar proxy (uin validated) ────────────────────────────────────────
app.get('/avatar/:uin', async (c) => {
const sessionToken = readAvatarSessionToken(c);
const session = sessionTokens.get(sessionToken);
if (!session || Date.now() > session.expiresAt) {
if (sessionToken) sessionTokens.delete(sessionToken);
return c.text('unauthorized', 401);
}
const uin = c.req.param('uin');
if (!UIN_REGEX.test(uin)) return c.text('invalid uin', 400);
@@ -735,7 +997,8 @@ export async function initWebUI(
return new Response(cached.body, {
headers: {
'Content-Type': cached.contentType,
'Cache-Control': `public, max-age=${AVATAR_BROWSER_CACHE_SECONDS}, immutable`,
'Cache-Control': `private, max-age=${AVATAR_BROWSER_CACHE_SECONDS}, immutable`,
Vary: 'Cookie',
},
});
});
@@ -760,7 +1023,13 @@ export async function initWebUI(
});
// ─── Read-only API ───────────────────────────────────────────────────────
app.get('/api/status', (c) => c.json({ status: 'running' }));
app.get('/api/status', (c) => {
// Refresh the path-scoped avatar cookie for a still-valid localStorage
// session (for example after upgrading from a version without the cookie).
const token = c.get('sessionToken' as never) as string;
setAvatarSessionCookie(c, token, listener.tlsEnabled === true);
return c.json({ status: 'running' });
});
// Advisory update check — compares the running build against the latest
// GitHub stable release and links the user to it. Read-only: SnowLuma
@@ -872,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: {
@@ -889,6 +1160,30 @@ export async function initWebUI(
});
});
registerStorageRoutes(app, {
storage: storageManagement,
settings: logStorageSettings,
audit: (event) => {
log.info(
'storage cleanup scope=%s accountScope=%s category=%s uin=%s deletedFiles=%d freedBytes=%d failures=%d',
event.scope,
event.accountScope,
event.category ?? '-',
event.uin ?? '-',
event.deletedFiles,
event.freedBytes,
event.failureCount,
);
},
reportError: (operation, error) => {
log.error(
'%s failed: %s',
operation,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
},
});
app.post('/api/system/tls/cert', async (c) => {
let body: unknown;
try {
@@ -921,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 });
@@ -1128,6 +1426,22 @@ export async function initWebUI(
return c.json({ list: getRecentLogs(limit) });
});
app.get('/api/logs/export/trace', (c) => {
const exportedAt = new Date().toISOString();
const download = buildFullTraceDownload(getLogSnapshot(), {
version: currentVersion(),
operatingSystem: os.platform(),
architecture: os.arch(),
nodeVersion: process.version,
logLevel: getLogLevel(),
exportedAt,
});
for (const [name, value] of Object.entries(download.headers)) {
c.header(name, value);
}
return c.body(download.body);
});
app.get('/api/logs/level', (c) => {
return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] });
});
@@ -1214,11 +1528,36 @@ export async function initWebUI(
return c.json({ success: false, saved: false, applied: false, message: '请求格式错误' }, 400);
}
let nextConfig: OneBotConfig;
try {
saveOneBotConfig(uin, body as OneBotConfig);
assertValidOneBotConfig(body);
nextConfig = body;
let previousConfig: OneBotConfig | null = null;
try {
previousConfig = loadOneBotConfig(uin);
} catch (err) {
// A damaged existing file must not strand the recovery UI. Treat the
// submitted endpoints as new, apply the full policy, and let the
// subsequent atomic save either repair the file or fail visibly.
log.warn(
'could not read prior OneBot config for uin=%s before save: %s',
uin,
err instanceof Error ? err.message : String(err),
);
}
validateOneBotAccessTokenChanges(previousConfig, nextConfig, {
clientIp: getSecurityClientIp(c),
uin,
});
saveOneBotConfig(uin, nextConfig);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
if (err instanceof OneBotConfigValidationError) {
if (
err instanceof OneBotConfigValidationError
|| err instanceof OneBotAccessTokenPolicyError
) {
log.warn('reject invalid config for uin=%s: %s', uin, message);
return c.json({ success: false, saved: false, applied: false, message }, 400);
}
@@ -1230,7 +1569,7 @@ export async function initWebUI(
// Apply the exact validated value that was persisted above. Re-reading
// the path here would race concurrent POSTs (request A could load B and
// falsely report that A was applied).
const apply = await oneBotManager.reloadConfig(uin, body as OneBotConfig);
const apply = await oneBotManager.reloadConfig(uin, nextConfig);
const message = !apply.online
? '配置保存成功,当前会话未在线,将在下次连接时生效。'
: apply.applied
@@ -1457,33 +1796,35 @@ export async function initWebUI(
);
});
const finalPort = await findAvailablePort(desiredPort);
const finalPort = await findAvailablePort(desiredPort, { host });
if (finalPort !== desiredPort) {
log.warn('port %d is in use, using %d instead', desiredPort, finalPort);
}
boundPort = finalPort;
const host = listener.host || '0.0.0.0';
// TLS: only when explicitly enabled AND the on-disk cert/key load. A bad
// or missing cert must never brick the WebUI — fall back to HTTP + warn.
// TLS is an explicit transport promise. Once enabled, an unusable pair must
// abort startup instead of silently exposing the listener over plaintext.
let tlsServe: { createServer: typeof createHttpsServer; serverOptions: { cert: Buffer; key: Buffer } } | undefined;
let scheme = 'http';
if (listener.tlsEnabled) {
const tls = resolveTlsContext('config');
if (tls.ok && tls.cert && tls.key) {
tlsServe = { createServer: createHttpsServer, serverOptions: { cert: tls.cert, key: tls.key } };
scheme = 'https';
} else {
log.warn('TLS enabled but cert/key unusable (%s) — serving over HTTP instead', tls.reason);
}
const tls = requireTlsContext('config');
tlsServe = { createServer: createHttpsServer, serverOptions: tls };
scheme = 'https';
}
await new Promise<void>((resolve) => {
serve({ fetch: app.fetch, port: finalPort, hostname: host, ...(tlsServe ?? {}) }, (info) => {
const listeningServer = await new Promise<ReturnType<typeof serve>>((resolve) => {
const server = serve({ fetch: app.fetch, port: finalPort, hostname: host, ...(tlsServe ?? {}) }, (info) => {
log.info(`listening ${scheme}://${host}:${info.port}`);
resolve();
resolve(server);
});
});
return { port: finalPort };
return {
port: finalPort,
async stop() {
connectionDiffLoop?.dispose();
await new Promise<void>((resolve, reject) => {
listeningServer.close((err) => (err ? reject(err) : resolve()));
});
},
};
}
+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';
@@ -0,0 +1,333 @@
import fs from 'node:fs';
import path from 'node:path';
import type {
LogCleanupResult,
LogStorageStatus,
} from '@snowluma/common/log-file-transport';
import { isRealUin } from '@snowluma/common/uin';
export interface TemporaryStorageSnapshot {
totalBytes: number;
fileCount: number;
activeItemCount: number;
}
export interface TemporaryCleanupResult {
deletedFiles: number;
freedBytes: number;
skippedActiveItems: number;
failures: Array<{ item: string; message: string }>;
}
export interface TemporaryStorageAdapter {
snapshot(): TemporaryStorageSnapshot;
clearInactive(): TemporaryCleanupResult;
}
export interface OnlineStorageAccount {
uin: string;
nickname: string;
}
export interface AccountStorageSnapshot {
uin: string;
nickname?: string;
online: boolean;
messagesBytes: number;
mediaBytes: number;
reactionsBytes: number;
totalBytes: number;
}
export type PublicLogStorageStatus = Omit<LogStorageStatus, 'directory'>;
export function publicLogStorageStatus(status: LogStorageStatus): PublicLogStorageStatus {
const { directory, ...publicStatus } = status;
if (!publicStatus.lastError) return publicStatus;
return {
...publicStatus,
lastError: redactFilesystemPath(publicStatus.lastError, directory, '[日志目录]'),
};
}
export interface PublicLogCleanupResult extends Omit<LogCleanupResult, 'status'> {
status: PublicLogStorageStatus;
}
export interface StorageSnapshot {
logs: PublicLogStorageStatus;
temporary: TemporaryStorageSnapshot;
accounts: AccountStorageSnapshot[];
totals: {
logsBytes: number;
temporaryBytes: number;
accountDataBytes: number;
managedBytes: number;
};
}
export type AccountStorageCategory = 'messages' | 'media' | 'reactions';
export interface AccountDataCleanupResult {
category: AccountStorageCategory;
uins: string[];
deletedFiles: number;
freedBytes: number;
failures: Array<{ uin: string; file: string; message: string }>;
}
export class StorageManagementInputError extends Error {
constructor(message: string) {
super(message);
this.name = 'StorageManagementInputError';
}
}
export class StorageAccountOnlineError extends Error {
constructor(readonly uins: string[]) {
super(`account data cleanup requires offline accounts: ${uins.join(', ')}`);
this.name = 'StorageAccountOnlineError';
}
}
export interface StorageManagementDependencies {
dataDir: string;
getLogStatus(): LogStorageStatus;
clearLogs(): Promise<LogCleanupResult>;
temporary: TemporaryStorageAdapter;
listOnlineAccounts(): OnlineStorageAccount[];
}
const DATABASE_FILES = {
messages: ['messages.db', 'messages.db-wal', 'messages.db-shm', 'messages.db-journal'],
media: ['media.db', 'media.db-wal', 'media.db-shm', 'media.db-journal'],
reactions: ['reactions.db', 'reactions.db-wal', 'reactions.db-shm', 'reactions.db-journal'],
} as const;
export class StorageManagementService {
constructor(private readonly deps: StorageManagementDependencies) {}
snapshot(): StorageSnapshot {
const logStatus = this.deps.getLogStatus();
const logs = publicLogStorageStatus(logStatus);
const temporary = this.deps.temporary.snapshot();
const accounts = this.accountSnapshots();
const accountDataBytes = accounts.reduce((sum, account) => sum + account.totalBytes, 0);
return {
logs,
temporary,
accounts,
totals: {
logsBytes: logs.totalBytes,
temporaryBytes: temporary.totalBytes,
accountDataBytes,
managedBytes: logs.totalBytes + temporary.totalBytes + accountDataBytes,
},
};
}
async clearLogs(): Promise<PublicLogCleanupResult> {
const result = await this.deps.clearLogs();
return {
...result,
failures: result.failures.map((failure) => ({
...failure,
message: redactFilesystemPath(
failure.message,
result.status.directory,
'[日志目录]',
),
})),
status: publicLogStorageStatus(result.status),
};
}
clearTemporary(): TemporaryCleanupResult {
return this.deps.temporary.clearInactive();
}
clearAccountData(category: string, uin: string): AccountDataCleanupResult {
const validatedCategory = validateAccountStorageCategory(category);
if (!isRealUin(uin)) {
throw new StorageManagementInputError(`invalid UIN: ${uin}`);
}
return this.clearAccountDataForUins(validatedCategory, [uin]);
}
clearAllAccountData(category: string): AccountDataCleanupResult {
const validatedCategory = validateAccountStorageCategory(category);
const uins = listDirectoryNames(this.deps.dataDir)
.filter((name) => isRealUin(name))
.sort((a, b) => Number(a) - Number(b));
return this.clearAccountDataForUins(validatedCategory, uins);
}
private clearAccountDataForUins(
category: AccountStorageCategory,
uins: string[],
): AccountDataCleanupResult {
const hasManagedRoot = assertManagedDataRootOrMissing(this.deps.dataDir);
const onlineUins = new Set(
this.deps.listOnlineAccounts()
.map((account) => account.uin)
.filter((uin) => isRealUin(uin)),
);
const blockedUins = uins.filter((uin) => onlineUins.has(uin));
if (blockedUins.length > 0) throw new StorageAccountOnlineError(blockedUins);
const failures: AccountDataCleanupResult['failures'] = [];
let deletedFiles = 0;
let freedBytes = 0;
if (!hasManagedRoot) {
return { category, uins, deletedFiles, freedBytes, failures };
}
for (const uin of uins) {
const dir = path.join(this.deps.dataDir, uin);
if (!isManagedDirectory(dir)) continue;
for (const name of DATABASE_FILES[category]) {
const filePath = path.join(dir, name);
let bytes: number;
try {
const stat = fs.lstatSync(filePath);
if (!stat.isFile()) continue;
bytes = stat.size;
} catch (error) {
if (isMissing(error)) continue;
failures.push({
uin,
file: name,
message: redactFilesystemPath(
errorMessage(error),
filePath,
'[账号数据库]',
),
});
continue;
}
try {
fs.unlinkSync(filePath);
deletedFiles += 1;
freedBytes += bytes;
} catch (error) {
if (isMissing(error)) continue;
failures.push({
uin,
file: name,
message: redactFilesystemPath(
errorMessage(error),
filePath,
'[账号数据库]',
),
});
}
}
}
return { category, uins, deletedFiles, freedBytes, failures };
}
private accountSnapshots(): AccountStorageSnapshot[] {
const online = new Map(
this.deps.listOnlineAccounts()
.filter((account) => isRealUin(account.uin))
.map((account) => [account.uin, account.nickname]),
);
const uins = new Set(online.keys());
for (const name of listDirectoryNames(this.deps.dataDir)) {
if (isRealUin(name)) uins.add(name);
}
return [...uins]
.sort((a, b) => Number(a) - Number(b))
.map((uin) => {
const dir = path.join(this.deps.dataDir, uin);
const managedDirectory = isManagedDirectory(dir);
const messagesBytes = managedDirectory
? sumAllowlistedFiles(dir, DATABASE_FILES.messages)
: 0;
const mediaBytes = managedDirectory
? sumAllowlistedFiles(dir, DATABASE_FILES.media)
: 0;
const reactionsBytes = managedDirectory
? sumAllowlistedFiles(dir, DATABASE_FILES.reactions)
: 0;
const nickname = online.get(uin);
return {
uin,
...(nickname ? { nickname } : {}),
online: online.has(uin),
messagesBytes,
mediaBytes,
reactionsBytes,
totalBytes: messagesBytes + mediaBytes + reactionsBytes,
};
});
}
}
function listDirectoryNames(dir: string): string[] {
if (!assertManagedDataRootOrMissing(dir)) return [];
try {
return fs.readdirSync(dir, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name);
} catch (error) {
if (isMissing(error)) return [];
throw error;
}
}
function assertManagedDataRootOrMissing(dir: string): boolean {
try {
const stat = fs.lstatSync(dir);
if (!stat.isDirectory()) {
throw new Error('managed data root must be a real directory');
}
return true;
} catch (error) {
if (isMissing(error)) return false;
throw error;
}
}
function sumAllowlistedFiles(dir: string, names: readonly string[]): number {
let total = 0;
for (const name of names) {
const filePath = path.join(dir, name);
try {
const stat = fs.lstatSync(filePath);
if (stat.isFile()) total += stat.size;
} catch (error) {
if (!isMissing(error)) throw error;
}
}
return total;
}
function isMissing(error: unknown): boolean {
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
}
function isManagedDirectory(dir: string): boolean {
try {
return fs.lstatSync(dir).isDirectory();
} catch (error) {
if (isMissing(error)) return false;
throw error;
}
}
function validateAccountStorageCategory(value: string): AccountStorageCategory {
if (value === 'messages' || value === 'media' || value === 'reactions') return value;
throw new StorageManagementInputError(`unsupported account storage category: ${value}`);
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function redactFilesystemPath(message: string, filePath: string, label: string): string {
const absolute = path.resolve(filePath);
return message
.split(absolute).join(label)
.split(filePath).join(label);
}
+317
View File
@@ -0,0 +1,317 @@
import { isRealUin } from '@snowluma/common/uin';
import type { Hono } from 'hono';
import {
StorageAccountOnlineError,
StorageManagementInputError,
type AccountDataCleanupResult,
type AccountStorageCategory,
type PublicLogCleanupResult,
type StorageManagementService,
type StorageSnapshot,
type TemporaryCleanupResult,
} from './storage-management';
import {
StorageSettingsInputError,
StorageSettingsLockedError,
StorageSettingsTransactionError,
type LogStorageSettingsManager,
} from './storage-settings';
export const ALL_ACCOUNTS_CONFIRMATION = '清理全部账号';
type StorageCleanupRequest =
| { scope: 'logs' }
| { scope: 'temporary' }
| { scope: 'account'; category: AccountStorageCategory; uin: string }
| {
scope: 'allAccounts';
category: AccountStorageCategory;
confirmation: typeof ALL_ACCOUNTS_CONFIRMATION;
};
type StorageCleanupResult =
| PublicLogCleanupResult
| TemporaryCleanupResult
| AccountDataCleanupResult;
export interface StorageCleanupAuditEvent {
scope: StorageCleanupRequest['scope'];
accountScope: 'global' | 'single' | 'all';
category?: AccountStorageCategory;
uin?: string;
deletedFiles: number;
freedBytes: number;
failureCount: number;
}
export interface LastStorageCleanup extends StorageCleanupAuditEvent {
at: string;
skippedActiveItems?: number;
failures: Array<{ item: string; message: string }>;
}
export interface StorageRouteDependencies {
storage: Pick<
StorageManagementService,
'snapshot'
| 'clearLogs'
| 'clearTemporary'
| 'clearAccountData'
| 'clearAllAccountData'
>;
settings: Pick<LogStorageSettingsManager, 'read' | 'update'>;
audit(event: StorageCleanupAuditEvent): void;
reportError(operation: string, error: unknown): void;
now?: () => Date;
}
export function registerStorageRoutes(app: Hono, deps: StorageRouteDependencies): void {
let lastCleanup: LastStorageCleanup | null = null;
let mutationQueue: Promise<void> = Promise.resolve();
const serializeMutation = <T>(operation: () => Promise<T>): Promise<T> => {
const result = mutationQueue.then(operation);
mutationQueue = result.then(
() => undefined,
() => undefined,
);
return result;
};
app.get('/api/system/storage', (c) => {
try {
return c.json({
settings: deps.settings.read(),
snapshot: deps.storage.snapshot(),
lastCleanup,
});
} catch (error) {
deps.reportError('read storage snapshot', error);
return c.json({ success: false, message: '读取存储信息失败,请检查服务器日志' }, 500);
}
});
app.post('/api/system/storage/settings', async (c) => {
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
let result: Awaited<ReturnType<LogStorageSettingsManager['update']>>;
try {
result = await serializeMutation(() => deps.settings.update(body));
} catch (error) {
if (error instanceof StorageSettingsInputError) {
return c.json({ success: false, message: error.message }, 400);
}
if (error instanceof StorageSettingsLockedError) {
return c.json({
success: false,
message: '这些设置已由环境变量锁定',
lockedFields: error.fields,
}, 409);
}
deps.reportError('update log storage settings', error);
if (error instanceof StorageSettingsTransactionError) {
deps.reportError('update log storage settings operation', error.operationError);
error.rollbackErrors.forEach((rollbackError, index) => {
deps.reportError(
`rollback log storage settings step=${String(index + 1)}`,
rollbackError,
);
});
return c.json({
success: false,
message: error.rollbackErrors.length > 0
? '保存失败且回滚不完整,请立即检查服务器日志'
: '保存失败,原设置已恢复',
}, 500);
}
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
}
try {
return c.json({
success: true,
settings: result.settings,
status: result.status,
snapshot: deps.storage.snapshot(),
});
} catch (error) {
deps.reportError('refresh storage snapshot after settings update', error);
return c.json({
success: false,
message: '设置已生效,但刷新存储统计失败,请检查服务器日志',
settings: result.settings,
status: result.status,
}, 500);
}
});
app.post('/api/system/storage/cleanup', async (c) => {
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
let request: StorageCleanupRequest;
try {
request = parseCleanupRequest(body);
} catch (error) {
const message = error instanceof Error ? error.message : '请求格式错误';
return c.json({ success: false, message }, 400);
}
let cleanup: StorageCleanupResult;
try {
cleanup = await serializeMutation(() => executeCleanup(deps.storage, request));
} catch (error) {
if (error instanceof StorageAccountOnlineError) {
return c.json({
success: false,
message: '账号在线,必须先下线后才能清理数据库',
onlineUins: error.uins,
}, 409);
}
if (error instanceof StorageManagementInputError) {
return c.json({ success: false, message: error.message }, 400);
}
deps.reportError(`clean storage scope=${request.scope}`, error);
return c.json({ success: false, message: '清理失败,请检查服务器日志' }, 500);
}
const auditEvent: StorageCleanupAuditEvent = {
scope: request.scope,
accountScope: accountScope(request),
...('category' in request ? { category: request.category } : {}),
...(request.scope === 'account' ? { uin: request.uin } : {}),
deletedFiles: cleanup.deletedFiles,
freedBytes: cleanup.freedBytes,
failureCount: cleanup.failures.length,
};
deps.audit(auditEvent);
for (const failure of cleanup.failures) {
deps.reportError(
`clean storage scope=${request.scope} item=${cleanupFailureItem(failure)}`,
new Error(failure.message),
);
}
lastCleanup = {
at: (deps.now?.() ?? new Date()).toISOString(),
...auditEvent,
...('skippedActiveItems' in cleanup
? { skippedActiveItems: cleanup.skippedActiveItems }
: {}),
failures: cleanup.failures.map((failure) => ({
item: cleanupFailureItem(failure),
message: failure.message,
})),
};
let snapshot: StorageSnapshot;
try {
snapshot = deps.storage.snapshot();
} catch (error) {
deps.reportError(`refresh storage snapshot after cleanup scope=${request.scope}`, error);
return c.json({
success: false,
message: '清理已执行,但刷新存储统计失败,请检查服务器日志',
scope: request.scope,
cleanup,
lastCleanup,
}, 500);
}
const success = cleanup.failures.length === 0;
return c.json({
success,
...(success ? {} : { message: '部分文件清理失败,请检查失败明细' }),
scope: request.scope,
cleanup,
snapshot,
lastCleanup,
}, success ? 200 : 500);
});
}
function parseCleanupRequest(body: unknown): StorageCleanupRequest {
if (!isObject(body) || typeof body.scope !== 'string') {
throw new StorageManagementInputError('scope is required');
}
if (body.scope === 'logs' || body.scope === 'temporary') {
assertExactKeys(body, ['scope']);
return { scope: body.scope };
}
if (body.scope === 'account') {
assertExactKeys(body, ['scope', 'category', 'uin']);
const category = parseCategory(body.category);
if (typeof body.uin !== 'string' || !isRealUin(body.uin)) {
throw new StorageManagementInputError('invalid UIN');
}
return { scope: 'account', category, uin: body.uin };
}
if (body.scope === 'allAccounts') {
assertExactKeys(body, ['scope', 'category', 'confirmation']);
const category = parseCategory(body.category);
if (body.confirmation !== ALL_ACCOUNTS_CONFIRMATION) {
throw new StorageManagementInputError('all-account cleanup requires confirmation');
}
return {
scope: 'allAccounts',
category,
confirmation: ALL_ACCOUNTS_CONFIRMATION,
};
}
throw new StorageManagementInputError(`unsupported cleanup scope: ${body.scope}`);
}
async function executeCleanup(
storage: StorageRouteDependencies['storage'],
request: StorageCleanupRequest,
): Promise<StorageCleanupResult> {
if (request.scope === 'logs') return storage.clearLogs();
if (request.scope === 'temporary') return storage.clearTemporary();
if (request.scope === 'account') {
return storage.clearAccountData(request.category, request.uin);
}
return storage.clearAllAccountData(request.category);
}
function parseCategory(value: unknown): AccountStorageCategory {
if (value === 'messages' || value === 'media' || value === 'reactions') return value;
throw new StorageManagementInputError('unsupported account storage category');
}
function assertExactKeys(body: Record<string, unknown>, allowed: string[]): void {
const allowedSet = new Set(allowed);
const unknown = Object.keys(body).filter((key) => !allowedSet.has(key));
const missing = allowed.filter((key) => !(key in body));
if (unknown.length > 0 || missing.length > 0) {
throw new StorageManagementInputError('cleanup request has unexpected or missing fields');
}
}
function accountScope(request: StorageCleanupRequest): StorageCleanupAuditEvent['accountScope'] {
if (request.scope === 'account') return 'single';
if (request.scope === 'allAccounts') return 'all';
return 'global';
}
function cleanupFailureItem(
failure: StorageCleanupResult['failures'][number],
): string {
if ('uin' in failure) return `${failure.uin}/${failure.file}`;
if ('file' in failure) return failure.file;
return failure.item;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
Loaded 100 of 693 files, more files were not shown because too many files have changed in this diff. Show more