Compare commits

..
Author SHA1 Message Date
DrSmoothl adf6b6a3b4 test(protocol): isolate upload staging fixtures
Give cleanup tests a dedicated staging directory so they cannot remove files used by parallel upload tests.

Refs #520
2026-10-13 10:08:20 +08:00
DrSmoothl 5a0b26648c test(onebot): use async connections in migration fixtures
Use the production SQLite driver for concurrent migration checks while preserving history, index, and restart assertions.

Refs #520
2026-10-13 10:08:15 +08:00
DrSmoothl a50df4e526 style(webui): preserve hook lint suppression after formatting
Keep the existing dependency annotation on the line checked by ESLint.
2026-10-13 10:00:55 +08:00
DrSmoothl 505b4772d6 test(core): align lock fixtures with async persistence
Exercise persistence failures and retries with the production database connection, and finish fixture writes before acquiring test locks.

Refs #520
2026-10-13 10:00:55 +08:00
DrSmoothl 927e03d435 test(sqlite): verify real lock contention across platforms
Use consistent database connections and prove write contention before checking event-loop responsiveness. Keep cleanup deterministic when an assertion fails.

Refs #520
2026-10-13 09:57:25 +08:00
DrSmoothl 056188d63d chore: resolve async SQLite merge conflicts
Integrate the current development branch, preserve the album comment fixes, and align the changes with repository formatting and dependency tooling.
2026-10-13 09:55:16 +08:00
DrSmoothl 20f48d11ec fix(core): accept large integers in album responses
Allow valid album responses with large integer values to reach the comment request and add regression coverage.

Refs #508
2026-10-13 09:48:00 +08:00
辉龙曦继 ceb8387ea6 fix(core): restore group album comments (#508)
Restore group album comments accepted by QQ and preserve server error reporting.

Refs #436
2026-10-13 09:47:24 +08:00
手瓜一十雪 e699351f90 feat: adopt async SQLite and improve messaging and runtime diagnostics 2026-10-12 15:44:55 +08:00
DrSmoothl 7c0519f75f lint 2026-10-12 15:43:34 +08:00
DrSmoothl effeb66554 feat(bridge): connect when a pipe is already up after load fails
A failed load used to stay in the error state. If the pipe is already
listening, connect instead, and keep retrying that case on later checks.
2026-10-10 10:44:15 +08:00
DrSmoothl 7496479782 feat(core): record runtime status while waiting to sign in
Refresh the bundled runtime binaries.
2026-10-09 15:30:35 +08:00
DrSmoothl 6ceb2a3900 feat(core): include runtime status in the log view
Refresh the bundled runtime binaries.
2026-10-09 11:13:25 +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
986 changed files with 105791 additions and 20400 deletions

No files matched your search

+3
View File
@@ -11,6 +11,9 @@ trim_trailing_whitespace = true
[*.{json,yml,yaml,md}]
indent_size = 2
[*.{ts,tsx,mts,cts}]
indent_size = 4
[*.py]
indent_size = 4
+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.
+6 -12
View File
@@ -1,4 +1,5 @@
# Run the root validation commands on every pull request.
# Command list is duplicated in tools/ci-check.mjs — keep them identical.
name: CI
on:
@@ -20,7 +21,7 @@ jobs:
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- uses: actions/setup-node@v6
@@ -38,14 +39,7 @@ jobs:
# catalog.json the docs site consumes). Fail if the committed snapshot
# drifted from the live specs — keeps the API docs from going stale.
- name: Verify generated action catalog is up to date
run: |
catalog_status="$(git status --porcelain=v1 --untracked-files=all -- packages/mcp/src/generated)"
if [ -n "$catalog_status" ]; then
git diff -- packages/mcp/src/generated
printf '%s\n' "$catalog_status"
echo '::error::Generated action catalog is stale. Run `pnpm --filter @snowluma/mcp gen` and commit packages/mcp/src/generated/.' >&2
exit 1
fi
run: node tools/check-action-catalog.mjs
typecheck:
runs-on: ubuntu-latest
@@ -54,7 +48,7 @@ jobs:
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- uses: actions/setup-node@v6
@@ -75,7 +69,7 @@ jobs:
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- uses: actions/setup-node@v6
@@ -96,7 +90,7 @@ jobs:
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- uses: actions/setup-node@v6
+3 -3
View File
@@ -72,7 +72,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
@@ -115,7 +115,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
@@ -148,7 +148,7 @@ jobs:
# Naming convention:
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+)
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node 24+
- 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
+11 -11
View File
@@ -34,13 +34,16 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
# Node 24 ships a supported npm CLI; the application runtime stays
# pinned separately by .node-version.
node-version: '24'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
@@ -77,21 +80,17 @@ jobs:
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Validate npm token
- name: Show Trusted Publishing toolchain
if: steps.npm.outputs.already_published != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [ -z "${NODE_AUTH_TOKEN}" ]; then
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
exit 1
fi
node --version
npm --version
- name: Publish MCP to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/mcp
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
# Authentication is supplied by npm Trusted Publishing through the
# GitHub OIDC token (permissions.id-token: write above).
run: npm publish --access public --provenance
- name: Summary
@@ -106,4 +105,5 @@ jobs:
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
echo "| Environment | \`SnowLuma\` |"
echo "| Authentication | npm Trusted Publishing (GitHub OIDC) |"
} >> "${GITHUB_STEP_SUMMARY}"
+33 -128
View File
@@ -1,20 +1,13 @@
name: Promote Dev to Main
# `dev` is the working branch. `main` is a pointer to the same history, moved
# only by this workflow. Merge commits from dev → main are what painted the
# GitHub network graph; this job moves the `main` ref to `dev` instead.
on:
push:
branches: [dev]
tags: ['chore.*']
workflow_dispatch:
inputs:
auto_merge:
description: Enable auto-merge on the resulting PR
type: choice
options: ['true', 'false']
default: 'true'
merge_method:
description: Merge strategy when auto-merging
type: choice
options: ['merge', 'squash', 'rebase']
default: 'merge'
permissions:
contents: read
@@ -28,8 +21,6 @@ jobs:
runs-on: ubuntu-latest
outputs:
run: ${{ steps.check.outputs.run }}
auto_merge: ${{ steps.check.outputs.auto_merge }}
merge_method: ${{ steps.check.outputs.merge_method }}
reason: ${{ steps.check.outputs.reason }}
steps:
- name: Decide whether to promote
@@ -39,32 +30,24 @@ jobs:
REF: ${{ github.ref }}
REF_TYPE: ${{ github.ref_type }}
HEAD_COMMIT_MSG: ${{ github.event.head_commit.message }}
INPUT_AUTO_MERGE: ${{ inputs.auto_merge }}
INPUT_MERGE_METHOD: ${{ inputs.merge_method }}
run: |
set -euo pipefail
run='false'
auto_merge='true'
merge_method='merge'
reason=''
case "${EVENT_NAME}" in
workflow_dispatch)
run='true'
auto_merge="${INPUT_AUTO_MERGE:-true}"
merge_method="${INPUT_MERGE_METHOD:-merge}"
reason='Manual workflow_dispatch'
;;
push)
if [ "${REF_TYPE}" = 'tag' ]; then
run='true'
merge_method='merge'
reason="Tag push: ${REF}"
elif [ "${REF}" = 'refs/heads/dev' ]; then
msg="${HEAD_COMMIT_MSG:-}"
if printf '%s' "${msg}" | grep -qiE '^\[merge\]|^chore\(release\):'; then
run='true'
merge_method='merge'
reason='Commit message prefix on dev ([merge] or chore(release):)'
else
reason='Commit on dev without [merge] / chore(release): prefix'
@@ -80,8 +63,6 @@ jobs:
{
echo "run=${run}"
echo "auto_merge=${auto_merge}"
echo "merge_method=${merge_method}"
echo "reason=${reason}"
} >> "${GITHUB_OUTPUT}"
@@ -93,8 +74,6 @@ jobs:
echo "| Event | \`${EVENT_NAME}\` |"
echo "| Ref | \`${REF}\` |"
echo "| Run | \`${run}\` |"
echo "| Auto-merge | \`${auto_merge}\` |"
echo "| Merge method | \`${merge_method}\` |"
echo "| Reason | ${reason} |"
} >> "${GITHUB_STEP_SUMMARY}"
@@ -123,123 +102,49 @@ jobs:
owner: ${{ github.repository_owner }}
repositories: ${{ github.event.repository.name }}
- name: Resolve bot identity
id: bot
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
APP_SLUG: ${{ steps.app-token.outputs.app-slug }}
run: |
set -euo pipefail
bot_login="${APP_SLUG}[bot]"
bot_id="$(gh api "/users/${bot_login}" --jq .id)"
bot_email="${bot_id}+${bot_login}@users.noreply.github.com"
{
echo "login=${bot_login}"
echo "id=${bot_id}"
echo "email=${bot_email}"
} >> "${GITHUB_OUTPUT}"
echo "Resolved bot: ${bot_login} <${bot_email}>"
- name: Checkout main
- name: Checkout
uses: actions/checkout@v6
with:
ref: main
ref: dev
fetch-depth: 0
token: ${{ steps.app-token.outputs.token }}
- name: Compare dev to main
id: diff
run: |
set -euo pipefail
git fetch origin dev:dev
ahead="$(git rev-list --count main..dev)"
behind="$(git rev-list --count dev..main)"
dev_sha="$(git rev-parse dev)"
dev_short="$(git rev-parse --short dev)"
{
echo "ahead=${ahead}"
echo "behind=${behind}"
echo "dev_sha=${dev_sha}"
echo "dev_short=${dev_short}"
} >> "${GITHUB_OUTPUT}"
if [ "${ahead}" = '0' ]; then
echo "skip=true" >> "${GITHUB_OUTPUT}"
echo "::notice::dev has no commits ahead of main; nothing to promote."
else
echo "skip=false" >> "${GITHUB_OUTPUT}"
echo "dev is ${ahead} ahead, ${behind} behind main."
fi
- name: Ensure automation label exists
if: steps.diff.outputs.skip != 'true'
- name: Point main at dev
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
run: |
gh label create automation --color 0E8A16 --description 'Automated bot PRs' 2>/dev/null || true
- name: Create or update Pull Request
id: pr
if: steps.diff.outputs.skip != 'true'
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
DEV_SHA: ${{ steps.diff.outputs.dev_sha }}
DEV_SHORT: ${{ steps.diff.outputs.dev_short }}
AHEAD: ${{ steps.diff.outputs.ahead }}
BEHIND: ${{ steps.diff.outputs.behind }}
REASON: ${{ needs.decide.outputs.reason }}
REF: ${{ github.ref }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
title="chore: promote dev → main (${DEV_SHORT})"
git fetch origin dev main
dev_sha="$(git rev-parse origin/dev)"
main_sha="$(git rev-parse origin/main)"
dev_short="$(git rev-parse --short origin/dev)"
main_short="$(git rev-parse --short origin/main)"
if [ "${dev_sha}" = "${main_sha}" ]; then
echo "::notice::main already equals dev @ ${dev_short}; nothing to promote."
{
echo "Automated promotion of \`dev\` into \`main\`."
echo "main already equals dev @ ${dev_short}"
} >> "${GITHUB_STEP_SUMMARY}"
exit 0
fi
unique="$(git cherry origin/dev origin/main | awk '/^\+/ { print $2 }' || true)"
if [ -n "${unique}" ]; then
echo '::error::main has unique commits that dev does not. Cherry-pick them onto dev first.' >&2
git log --oneline --no-walk ${unique}
exit 1
fi
git push --force-with-lease="refs/heads/main:${main_sha}" origin "origin/dev:refs/heads/main"
echo "::notice::Updated main ${main_short} → dev@${dev_short}"
{
echo "## Promote"
echo
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}"
+9 -13
View File
@@ -18,7 +18,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
@@ -37,14 +37,7 @@ jobs:
run: pnpm typecheck
- name: Verify generated action catalog is up to date
run: |
catalog_status="$(git status --porcelain=v1 --untracked-files=all -- packages/mcp/src/generated)"
if [ -n "$catalog_status" ]; then
git diff -- packages/mcp/src/generated
printf '%s\n' "$catalog_status"
echo '::error::Generated action catalog is stale. Run `pnpm --filter @snowluma/mcp gen` and commit packages/mcp/src/generated/.' >&2
exit 1
fi
run: node tools/check-action-catalog.mjs
build:
needs: preflight
@@ -71,7 +64,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
@@ -101,7 +94,7 @@ jobs:
# Naming convention:
# SnowLuma-<tag>-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+)
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node 24+
- name: Package (windows)
if: matrix.os == 'windows-latest'
shell: pwsh
@@ -168,7 +161,7 @@ jobs:
## 选择下载
| 平台 | 完整版(内置 Node.js,推荐) | Lite(Node.js 22.13+;23 系需 23.4+) |
| 平台 | 完整版(内置 Node.js,推荐) | Lite(Node.js 24+) |
| --- | --- | --- |
| 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\` |
@@ -224,6 +217,7 @@ jobs:
DOCKER_PLATFORMS: ${{ vars.DOCKER_PLATFORMS }}
DOCKER_WORKFLOW: ${{ vars.DOCKER_WORKFLOW }}
DOCKER_REF: ${{ vars.DOCKER_REF }}
GHCR_IMAGE: ${{ vars.GHCR_IMAGE }}
with:
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
script: |
@@ -239,6 +233,7 @@ jobs:
const platforms = process.env.DOCKER_PLATFORMS || 'linux/amd64,linux/arm64';
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
const ref = process.env.DOCKER_REF || 'main';
const ghcrImage = process.env.GHCR_IMAGE || '';
await github.rest.actions.createWorkflowDispatch({
owner,
@@ -252,7 +247,8 @@ jobs:
platforms,
snowluma_tag: tag,
snowluma_repository: sourceRepo,
ghcr_image: ghcrImage,
},
});
core.info(`Dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);
core.info(`Dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, ghcr_image=${ghcrImage}, platforms=${platforms}).`);
+11 -11
View File
@@ -31,13 +31,16 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
# Node 24 ships a supported npm CLI; the application runtime stays
# pinned separately by .node-version.
node-version: '24'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
@@ -74,21 +77,17 @@ jobs:
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Validate npm token
- name: Show Trusted Publishing toolchain
if: steps.npm.outputs.already_published != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [ -z "${NODE_AUTH_TOKEN}" ]; then
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
exit 1
fi
node --version
npm --version
- name: Publish SDK to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/sdk
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
# Authentication is supplied by npm Trusted Publishing through the
# GitHub OIDC token (permissions.id-token: write above).
run: npm publish --access public --provenance
- name: Summary
@@ -103,4 +102,5 @@ jobs:
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
echo "| Environment | \`SnowLuma\` |"
echo "| Authentication | npm Trusted Publishing (GitHub OIDC) |"
} >> "${GITHUB_STEP_SUMMARY}"
+1 -1
View File
@@ -32,7 +32,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
+11 -11
View File
@@ -31,13 +31,16 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
# Node 24 ships a supported npm CLI; the application runtime stays
# pinned separately by .node-version.
node-version: '24'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
@@ -71,21 +74,17 @@ jobs:
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Validate npm token
- name: Show Trusted Publishing toolchain
if: steps.npm.outputs.already_published != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [ -z "${NODE_AUTH_TOKEN}" ]; then
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
exit 1
fi
node --version
npm --version
- name: Publish UI to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/ui
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
# Authentication is supplied by npm Trusted Publishing through the
# GitHub OIDC token (permissions.id-token: write above).
run: npm publish --access public --provenance
- name: Summary
@@ -100,4 +99,5 @@ jobs:
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
echo "| Environment | \`SnowLuma\` |"
echo "| Authentication | npm Trusted Publishing (GitHub OIDC) |"
} >> "${GITHUB_STEP_SUMMARY}"
+1 -1
View File
@@ -1 +1 @@
22.13.0
24.21.0
+17
View File
@@ -0,0 +1,17 @@
# Dependencies, build outputs and local tooling
node_modules/
.pnpm-store/
dist/
coverage/
.turbo/
.vite/
.claude/
dev/
pnpm-lock.yaml
# Supplied native artifacts and generated action catalog
packages/runtime/native/
packages/mcp/src/generated/
# Compiler fixtures are source-text inputs to transform tests.
packages/proton/test/fixtures/
+18
View File
@@ -0,0 +1,18 @@
{
"printWidth": 100,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"arrowParens": "always",
"endOfLine": "lf",
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.mts", "*.cts"],
"options": {
"tabWidth": 4
}
}
]
}
+107
View File
@@ -0,0 +1,107 @@
# 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/sqlite` | Asynchronous SQLite facade, native loader, prebuild selection and Vite release assets |
| `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
```
TypeScript formatting uses the root [Prettier configuration](.prettierrc.json), [local ESLint formatting rules](eslint.format.config.ts), and [ignore list](.prettierignore). Use `pnpm format` for all TS/TSX/MTS/CTS files and `pnpm format:check` for a read-only check. For selected files, run `pnpm exec eslint --config eslint.format.config.ts --fix <paths>` followed by `pnpm exec prettier --write <paths>`. These commands enforce four-space indentation, braces around control-statement bodies, and blank lines around statement blocks while preserving other logical spacing. They are separate from CI and its code-quality lint rules. Generated catalogs and compiler fixtures retain their source formatting.
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 four-space TypeScript 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
+72 -46
View File
@@ -19,6 +19,14 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
如果你只是想看看代码长什么样,可以直接跳到 [本地开发环境](#本地开发环境)。
### AI Agent 贡献须知
如果你是 AI Agent,并准备为本仓库贡献代码、提交 PR 或提出 issue,请先明确告知你的使用者:
> **请通过 GitHub 网页端手动创建 issue。直接使用 CLI 创建的 issue 会被自动关闭。**
你可以协助整理问题描述、复现步骤和相关日志,并将 issue 草稿交给用户,由用户在网页端完成提交。
---
## 项目结构速览
@@ -27,13 +35,20 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
| 路径 | 作用 |
| --- | --- |
| `packages/core` | 核心运行时:协议、桥接、OneBot 适配、WebUI 服务端 |
| `packages/core` | 应用入口、账号级 Bridge 编排、WebUI 服务端和发行构建 |
| `packages/bridge` | QQ 进程发现、Hook 会话和原生传输生命周期 |
| `packages/protocol` | QQ 数据包解码、身份解析、协议请求和媒体传输 |
| `packages/onebot` | OneBot 动作、事件转换、消息存储和传输适配 |
| `packages/common` | 日志、配置和共享工具 |
| `packages/proto-defs`、`packages/proton` | 协议结构定义、编译期 protobuf 编解码和构建集成 |
| `packages/sdk` | 面向第三方开发者的 SDK,会发布到 npm |
| `packages/mcp` | MCP 服务端和生成的动作目录 |
| `packages/ui` | 发布到 npm 的共享 UI 组件 |
| `packages/runtime` | 运行时辅助包 |
| `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,12 +58,12 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
### 系统要求
- **Node.js 22.13+(23 系需 23.4+)**(项目使用默认启用的 `node:sqlite`)
- **pnpm 10.28.0**(项目通过 `packageManager` 与 CI 统一版本)
- **Node.js 24+**
- **pnpm 11.25.0**(项目通过 `packageManager` 与 CI 统一版本)
- macOS / Linux / Windows 均可。如果要构建原生产物,需要对应平台的工具链。
如果系统提供 Corepack,可执行 `corepack enable pnpm`;没有 Corepack 时可执行
`npm install -g pnpm@10.28.0`。进入仓库后,`node --version` 与
`npm install -g pnpm@11.25.0`。进入仓库后,`node --version` 与
`pnpm --version` 应满足上述版本要求,否则安装会直接失败。
### 拉代码、装依赖、跑起来
@@ -83,7 +98,7 @@ pnpm dev:web # webui
### 1. 创建分支
请基于 `dev` 创建分支,不是 `main`。`main` 是受保护的稳定分支,PR 也不要直接提到 `main`。
请基于 `dev` 创建分支,不是 `main`。`main` 是发布指针,只由维护者的 Promote 更新,PR 不要提到 `main`。
```bash
git checkout dev
@@ -96,7 +111,7 @@ git checkout -b fix/onebot-mention-encoding
### 2. 写代码
- **保持改动聚焦**:一个 PR 只做一件事。顺手发现的其他问题请单独开 issue 或新 PR。
- **跟随既有风格**:不要为了你个人偏好引入大规模格式化或重命名。
- **跟随既有风格**:TypeScript 排版以仓库 Prettier 配置为准;普通功能或修复 PR 只格式化涉及的文件,避免混入无关的大规模格式化或重命名。
- **写测试**:修 bug 时优先写一个能复现该 bug 的测试,确认它会 fail,再让它 pass。新增功能至少补上 happy path 的测试。
- **不要添加无意义的注释**:标识符已经说清楚的事情不需要再写一遍。注释应当解释"为什么",而不是"做了什么"。
@@ -133,7 +148,7 @@ refactor(bridge): extract BridgeInterface as the OneBot-facing seam
docs: clarify dev environment setup steps
```
> ⚠️ **请不要**在你的提交信息里使用 `[merge]` 前缀或 `chore(release):` 前缀 —— 这两个前缀是维护者用来触发自动合并到 `main` 的,会让你的 PR 行为异常。详见后文 [维护者参考](#维护者参考release--自动合并流程)。
> ⚠️ **请不要**在你的提交信息里使用 `[merge]` 前缀或 `chore(release):` 前缀 —— 这两个前缀是维护者用来把 `main` 指到 `dev` 的,会让你的 PR 行为异常。详见后文 [维护者参考](#维护者参考release--promote)。
### 4. 推送并发起 PR
@@ -152,7 +167,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`。
---
@@ -161,15 +176,35 @@ git push origin fix/onebot-mention-encoding
### 代码风格
- TypeScript 严格模式,按 `tsconfig.base.json` 配置。
- TypeScript 使用四空格缩进,控制语句始终带大括号。排版由根目录 [`.prettierrc.json`](./.prettierrc.json) 和独立的本地 [ESLint 格式规则](./eslint.format.config.ts) 管理;普通 `pnpm lint` 负责代码质量检查。
- 优先用现有抽象,不要为"假想的未来需求"提前抽象。
- 不要给内部函数加防御性的参数校验,除非是系统边界(用户输入、外部 API)。
- 不要保留死代码、被注释掉的代码或者 `// TODO` 没有具体上下文的占位。
从仓库根目录运行本地格式化命令:
```bash
pnpm format # 为全部 TS/TSX/MTS/CTS 补大括号、空行并排版
pnpm format:check # 检查上述规则,不修改文件
# 只格式化指定文件:先处理控制语句与空行,再排版
pnpm exec eslint --config eslint.format.config.ts --fix packages/core/src/index.ts
pnpm exec prettier --write packages/core/src/index.ts
```
格式化范围排除 [`.prettierignore`](./.prettierignore) 中的构建产物、生成文件和编译器测试夹具;普通源码与测试都参与格式化。这两个命令供本地使用,不接入 CI。
空行采用保守规则:在语句块前后留空行,保留已有逻辑分段,不强行拆开连续声明或普通调用,也不在每条 `return`、`break` 前插空行;共用同一分支的连续 `case` 标签保持相邻。JSON、YAML 等文件继续使用原有缩进。
编辑器请选择项目本地安装的 Prettier 并读取仓库配置。VS Code 可安装
`esbenp.prettier-vscode`,将 TypeScript / TypeScript React 的默认格式化器设为
Prettier,并按需开启保存时格式化。
### 测试
- 单测放在被测代码同包的 `tests/` 或同目录的 `*.test.ts`,按既有风格走。
- 测试要描述行为,不要测实现细节。`it('should call internal foo')` 这种是反例。
- 涉及 IO / 时序 / 外部进程的,用现有的 fake/stub 模式,参考 `packages/core/src/onebot/` 下的 `fake-bridge` 类测试。
- 涉及 IO / 时序 / 外部进程的,用现有的 fake/stub 模式,参考 `packages/onebot/tests/` 中的 Bridge 测试替身。
### 文档
@@ -191,28 +226,30 @@ git push origin fix/onebot-mention-encoding
---
## 维护者参考:release & 自动合并流程
## 维护者参考:release & Promote
> 以下内容主要写给具备 `main` 推送 / 发版权限的维护者。普通贡献者只需要把 PR 提到 `dev`,不需要关心这一节。
> 以下内容主要写给具备发版权限的维护者。普通贡献者只需要把 PR 提到 `dev`,不需要关心这一节。
### 分支模型
SnowLuma 使用 **`main` + `dev`** 双分支模型:
- **`main`** — 受保护的稳定分支,仅接收来自 `dev` 的合并 PR。**禁止直接 push**。
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先合入 `dev`。
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先进入 `dev`。
- **`main`** — 发布指针,应与某次 Promote 当时的 `dev` 尖端是**同一个提交**。不要直接 push,也不要往 `main` 开 PR(CI 会拒)。
- **`native/auto-update-*`** — 由 `SnowLuma Bot` 自动创建的原生产物更新分支(来自 `SnowLumaNative`,不需要手动维护)。
### 把 `dev` 合并到 `main`
### 把 `main` 指到 `dev`
工作流 `.github/workflows/promote-dev-to-main.yml` 会以 `SnowLuma Bot` 身份开 / 更新一个 `dev → main` 的 PR,并可选地自动合并。无论用哪种触发方式,工作流都会调用 `gh pr merge --auto`:**只有 `main` 分支保护中所有 required status checks(typecheck + 各架构 build)都通过后,机器人才会真正合并**。失败的工作流会卡住合并。
工作流 `.github/workflows/promote-dev-to-main.yml` 以 `SnowLuma Bot` 身份把 `main` 指到当前 `dev` 尖端,**不再开 merge PR**。`main` 上若有 `dev` 还没有的独有改动,Promote 会失败,需要先把那些改动收回 `dev`。
推到 `dev` 仍会跑 `dev-build.yml`。Promote **不等**那组检查;发版请用下面的 `pnpm release`,它会在本地先跑完整 CI。
#### 1. 提交信息前缀(推荐日常使用)
向 `dev` push 一个提交,提交信息**以**以下任一前缀**开头**即触发(不区分大小写):
- `[merge]` — 例如 `[merge] fix: hotfix for OneBot mention`
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯。**只许用在真正的版本 bump**,不要写进普通 CI / 工具提交。
> 是**前缀**匹配,不是任意位置。`fix: something [merge]` 不会触发,必须把 `[merge]` 写在最前面。
@@ -220,38 +257,22 @@ SnowLuma 使用 **`main` + `dev`** 双分支模型:
任何符合 `chore.*` 的 tag(如 `chore.merge-20240509`、`chore.promote-v1.7.0`)被推送时也会触发:
- `chore.*` → 仅触发 `promote-dev-to-main.yml`(开 PR,自动合并)
- `chore.*` → 仅触发 `promote-dev-to-main.yml`(把 `main` 指到 `dev`)
- `v*` → 仅触发 `release.yml`(构建发布产物)
推荐流程:先用 `chore.*` tag 把 `dev` 合入 `main`,待合并完成后再在 `main` 上打 `v*` tag 触发发布。这样 `release.yml` 始终基于已过完所有检查的 `main` HEAD 构建。
推荐流程:用 `pnpm release`(或先 Promote,再确认 `origin/main` 已等于 `dev` 尖端)之后,在 `main` 上打 `v*` tag。这样 `release.yml` 始终基于当时的 `main` HEAD 构建。
#### 3. 手动触发
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。可选输入:
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。没有 merge 策略选项;跑起来就是一次指针更新。
- `auto_merge`:是否启用 auto-merge(默认 `true`)。
- `merge_method`:`merge` / `squash` / `rebase`(默认 `merge`)。
### 不要给 `main` 套「必须走 PR」
### 启用 `main` 分支保护(必做)
Promote 不通过 PR 更新 `main`。如果给 `main` 打开 **Require a pull request before merging** 或禁止更新引用,Promote 会失效。
仓库管理员需要在 GitHub 上为 `main` 配置规则集(Repository Rules)或经典分支保护,至少满足:
可以限制删除 `main`。外来 PR 必须打 `dev`;打到 `main` 的 PR 会被 `main-pr-target-guard.yml` 拒绝。
1. **Settings → Rules → Rulesets**(推荐)或 **Settings → Branches → Branch protection rules**。
2. 选择 `main` 作为目标分支。
3. 勾选:
- **Restrict deletions** — 禁止删除 `main`。
- **Require a pull request before merging** — 所有合并必须走 PR。
- **Block force pushes** — 禁止强推。
- **Require status checks to pass before merging(必勾)** — 把以下来自 `dev-build.yml` 的 check 全部加为 required:
- `typecheck`
- `build (win-x64)`
- `build (linux-x64)`
- `build (linux-arm64)`
- **Require branches to be up to date before merging** — 保证 PR 合并前已 rebase 过最新 `main`。
4. 在 **Bypass list / Allow specified actors to bypass** 中加入 `SnowLuma Bot` GitHub App。这样 `gh pr merge --auto` 才能在所有 required check 通过后由机器人自动完成合并;否则 PR 会一直卡在 auto-merge 等待人工 review。
5. **不要**把任何用户加入 push 白名单,确保「禁止向 `main` 直接提交」的约束生效。第一次设置完后,连仓库管理员也只能通过 PR 改 `main`。
效果:任何对 `dev` 的推送都会先在 `dev-build.yml` 上跑 typecheck + 三个架构的 build;只有全部成功,promote 工作流的 `--auto` 合并才会真正发生。失败时 PR 会保留在 open 状态,修复后再次推到 `dev` 即可重新触发检查。
本地若已经 checkout 过旧的 `main`,Promote 之后可能无法快进,对齐 `origin/main` 即可。
### 必需的 Secrets
@@ -260,25 +281,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
```
+12
View File
@@ -78,6 +78,18 @@ pnpm test
贡献流程见 [`CONTRIBUTING.md`](CONTRIBUTING.md);模块边界与项目词汇见 [`CONTEXT.md`](CONTEXT.md);开发方向见 [`RoadMap.md`](RoadMap.md)。
## 引用消息预览
OneBot 发送 `reply` 段时,会将本地消息缓存中的原文附入 QQ 引用预览,保留文字、换行与引用关系。图片、语音等非文字段以类型提示显示,不重新上传媒体;原消息中的嵌套引用不递归展开。只有消息元数据而没有缓存正文时,不生成虚构的预览内容。
## 媒体读取与归档
`get_msg` 逐个尝试刷新图片、语音和视频的下载地址:获取到新地址就用于本次响应,刷新失败或缺少资源元数据时保留该段原地址,并继续处理其他资源。原地址为空时仍保持为空,单个资源失败不影响整条消息返回。地址更新时同步响应中的 `raw_message`,不改写保存的消息;保留的旧地址仍可能已经过期。
`get_record` 单独向 QQ 获取语音的当前下载地址,资源元数据缺失或远端获取失败时动作返回错误,不使用旧地址或发送时的本地文件兜底。历史记录若没有保存资源引用,无法仅凭文件名恢复下载地址。
SnowLuma 不为这些查询长期保存媒体文件或 Base64 内容,本地保留的是消息及资源元数据;上传、转码仍会使用临时文件。下载地址和 QQ 远端资源都有可用性限制,需要长期归档的消费端应及时下载并自行保存。
## 使用边界与许可
> [!IMPORTANT]
+11 -7
View File
@@ -1,14 +1,17 @@
import js from '@eslint/js';
import eslintConfigPrettier from 'eslint-config-prettier/flat';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import { defineConfig, globalIgnores } from 'eslint/config';
import globals from 'globals';
import tseslint from 'typescript-eslint';
const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(/^\/(.:\/)/, '$1');
const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(
/^\/(.:\/)/,
'$1',
);
export default defineConfig([
globalIgnores([
export const sourceIgnores = globalIgnores([
'**/dist/**',
'**/node_modules/**',
'**/coverage/**',
@@ -20,7 +23,10 @@ export default defineConfig([
'**/test/fixtures/**',
'packages/runtime/native/**',
'packages/mcp/src/generated/**',
]),
]);
export default defineConfig([
sourceIgnores,
{
files: ['**/*.{js,mjs,cjs,ts,tsx}'],
extends: [js.configs.recommended],
@@ -33,7 +39,6 @@ export default defineConfig([
},
},
rules: {
'indent': ['error', 2, { SwitchCase: 1 }],
'no-unused-vars': 'off',
'no-useless-assignment': 'off',
'prefer-const': 'off',
@@ -49,7 +54,6 @@ export default defineConfig([
},
},
rules: {
'indent': ['error', 2, { SwitchCase: 1 }],
'prefer-const': 'off',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-empty-object-type': 'off',
@@ -99,10 +103,10 @@ export default defineConfig([
},
},
rules: {
'indent': ['error', 2, { SwitchCase: 1 }],
'prefer-const': 'off',
'react-refresh/only-export-components': 'off',
'react-hooks/set-state-in-effect': 'off',
},
},
eslintConfigPrettier,
]);
+39
View File
@@ -0,0 +1,39 @@
import stylistic from '@stylistic/eslint-plugin';
import { defineConfig } from 'eslint/config';
import reactHooks from 'eslint-plugin-react-hooks';
import tseslint from 'typescript-eslint';
import { sourceIgnores } from './eslint.config.ts';
// Local formatting only; CI continues to use eslint.config.ts for code quality.
export default defineConfig([
sourceIgnores,
{
// Preserve quality-rule suppressions when running only formatting rules.
linterOptions: { reportUnusedDisableDirectives: 'off' },
},
{
files: ['**/*.{ts,tsx,mts,cts}'],
languageOptions: {
parser: tseslint.parser,
},
plugins: {
'@stylistic': stylistic,
'@typescript-eslint': tseslint.plugin,
'react-hooks': reactHooks,
},
rules: {
curly: ['error', 'all'],
'@stylistic/padding-line-between-statements': [
'error',
{ blankLine: 'always', prev: '*', next: 'block-like' },
{ blankLine: 'always', prev: 'block-like', next: '*' },
// Stacked case labels share a branch and must stay adjacent.
{
blankLine: 'never',
prev: { selector: 'SwitchCase[consequent.length=0]' },
next: ['case', 'default'],
},
],
},
},
]);
+10 -15
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.14.4",
"version": "1.14.22",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -25,37 +25,32 @@
"typecheck": "pnpm -r --if-present typecheck",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "eslint --config eslint.format.config.ts --fix \"**/*.{ts,tsx,mts,cts}\" && prettier --write \"**/*.{ts,tsx,mts,cts}\"",
"format:check": "eslint --config eslint.format.config.ts \"**/*.{ts,tsx,mts,cts}\" && prettier --check \"**/*.{ts,tsx,mts,cts}\"",
"ci": "node tools/ci-check.mjs",
"start": "node dist/index.mjs",
"bump": "node tools/bump-version.mjs",
"release": "node tools/release.mjs"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@stylistic/eslint-plugin": "5.10.0",
"@vitest/coverage-istanbul": "4.1.4",
"@vitest/coverage-v8": "^4.1.4",
"cross-env": "^10.1.0",
"eslint": "^10.2.0",
"eslint-config-prettier": "10.1.8",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.5.0",
"jiti": "^2.6.1",
"prettier": "3.9.10",
"typescript": "catalog:",
"typescript-eslint": "^8.58.2"
},
"pnpm": {
"peerDependencyRules": {
"allowedVersions": {
"eslint-plugin-react-hooks>eslint": "10"
}
},
"overrides": {
"esbuild@<0.28.1": "^0.28.1",
"@babel/core@<7.29.6": "^7.29.6"
}
},
"packageManager": "pnpm@10.28.0",
"packageManager": "pnpm@11.25.0",
"engines": {
"node": "^22.13.0 || >=23.4.0",
"pnpm": "10.28.0"
"node": ">=24",
"pnpm": "11.25.0"
}
}
+8 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.14.4",
"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"
@@ -57,5 +61,8 @@
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "^4.1.4"
},
"engines": {
"node": ">=24"
}
}
+114 -34
View File
@@ -1,8 +1,4 @@
import {
createLogger,
runWithTraceRequest,
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';
@@ -81,7 +77,7 @@ 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
@@ -123,7 +119,10 @@ export class HookManager {
this.injector = deps.injector ?? {
inject: injectHookProcess,
unload: (pid, handle) => {
if (!handle) return;
if (!handle) {
return;
}
unloadHookProcess(pid, handle);
},
};
@@ -136,6 +135,7 @@ export class HookManager {
if (deps.listProcesses) {
const lister = deps.listProcesses;
this.enumerator = null;
this.enumerate = async () => {
try {
return await lister();
@@ -160,7 +160,8 @@ export class HookManager {
} else {
this.pipeWatcher = new PipeWatcher({
listProcesses: this.enumerate,
listLivePipes: processes => QqHookClient.listLivePipes(processes.map(({ pid }) => pid)),
listLivePipes: (processes) =>
QqHookClient.listLivePipes(processes.map(({ pid }) => pid)),
intervalMs: deps.watcherIntervalMs,
log: this.log,
});
@@ -176,19 +177,21 @@ export class HookManager {
async listProcesses(): Promise<HookProcessInfo[]> {
await this.startPromise;
const processes = await this.enumerate();
if (processes === null) {
// Enumeration timed out / failed — report the last-known sessions rather
// than an empty list (which the WebUI would render as "no QQ").
return [...this.sessions.values()]
.map((s) => s.toInfo())
.sort((a, b) => a.pid - b.pid);
return [...this.sessions.values()].map((s) => s.toInfo()).sort((a, b) => a.pid - b.pid);
}
const result: HookProcessInfo[] = [];
for (const proc of processes) {
const session = this.ensureSession(proc.pid);
session.attachProcessInfo(proc);
result.push(session.toInfo());
}
return result.sort((a, b) => a.pid - b.pid);
}
@@ -225,14 +228,20 @@ export class HookManager {
}
dispose(): void {
if (this.disposed) return;
if (this.disposed) {
return;
}
this.disposed = true;
for (const session of this.sessions.values()) {
session.dispose();
}
this.sessions.clear();
this.autoLoadAttempts.clear();
this.enumerator?.dispose();
if (this.ownsPipeWatcher) {
this.pipeWatcher.dispose();
}
@@ -242,7 +251,10 @@ export class HookManager {
private bindWatcher(): void {
this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => {
if (this.disposed) return;
if (this.disposed) {
return;
}
runWithTraceRequest(() => {
const session = this.ensureSession(info.pid);
session.attachProcessInfo(info);
@@ -252,6 +264,7 @@ export class HookManager {
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
@@ -259,11 +272,15 @@ export class HookManager {
if (this.autoLoadOnDiscovery && shouldAutoLoadPid(info.pid, this.log)) {
this.runAutoLoad(session);
}
this.notifySessionsChanged();
});
});
this.pipeWatcher.on('process-gone', (pid: number) => {
if (this.disposed) return;
if (this.disposed) {
return;
}
runWithTraceRequest(() => {
this.autoLoadAttempts.delete(pid);
const session = this.sessions.get(pid);
@@ -272,19 +289,35 @@ export class HookManager {
pid,
session !== undefined,
);
if (session) session.notifyProcessGone();
if (session) {
session.notifyProcessGone();
}
this.notifySessionsChanged();
});
});
this.pipeWatcher.on('pipe-up', (pid: number) => {
if (this.disposed) return;
if (this.disposed) {
return;
}
const session = this.sessions.get(pid);
if (session) session.onPipeUp();
if (session) {
session.onPipeUp();
}
});
this.pipeWatcher.on('pipe-down', (pid: number) => {
if (this.disposed) return;
if (this.disposed) {
return;
}
const session = this.sessions.get(pid);
if (session) session.onPipeDown();
if (session) {
session.onPipeDown();
}
});
// After every tick, retry sessions that are stuck in 'connecting' OR
// 'disconnected' while the pipe is up. Mirrors the original
@@ -301,16 +334,29 @@ export class HookManager {
// for a while then stops" with logs `pipe error: read EPIPE` →
// `session closed: UIN=…`.
this.pipeWatcher.on('tick', () => {
if (this.disposed) return;
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)) {
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)) {
if (
(session.status === 'connecting' ||
session.status === 'disconnected' ||
session.status === 'error') &&
this.pipeWatcher.isPipeLive(session.pid)
) {
session.onPipeUp();
}
}
@@ -318,9 +364,15 @@ export class HookManager {
}
private runAutoLoad(session: HookSession, existing?: AutoLoadAttempt): void {
if (this.disposed || session.isDisposed) return;
if (this.disposed || session.isDisposed) {
return;
}
const state = existing ?? { attempts: 0, inFlight: false };
if (state.inFlight || state.attempts >= AUTO_LOAD_MAX_ATTEMPTS) return;
if (state.inFlight || state.attempts >= AUTO_LOAD_MAX_ATTEMPTS) {
return;
}
state.attempts += 1;
state.inFlight = true;
@@ -335,8 +387,10 @@ export class HookManager {
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',
@@ -346,6 +400,7 @@ export class HookManager {
);
return;
}
state.inFlight = false;
if (info.status !== 'error') {
@@ -359,6 +414,7 @@ export class HookManager {
renderParamsVerbose(info),
Date.now() - startedAt,
]);
if (attempt > 1) {
this.log.info(
'auto-load recovered: PID=%d attempt=%d/%d',
@@ -367,6 +423,7 @@ export class HookManager {
AUTO_LOAD_MAX_ATTEMPTS,
);
}
return;
}
@@ -418,6 +475,7 @@ export class HookManager {
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,
@@ -432,7 +490,10 @@ export class HookManager {
private ensureSession(pid: number): HookSession {
let session = this.sessions.get(pid);
if (session) return session;
if (session) {
return session;
}
session = new HookSession(pid, {
injector: this.injector,
@@ -447,7 +508,9 @@ export class HookManager {
this.bridgeManager.onHookLogin(pid, uin, sender);
});
session.on('disconnected', (wasLoggedIn: boolean) => {
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
if (wasLoggedIn) {
this.bridgeManager.onPidDisconnected(pid);
}
});
session.on('receive-health-changed', (healthy: boolean) => {
this.bridgeManager.onPidReceiveHealthChanged(pid, healthy);
@@ -470,8 +533,14 @@ export class HookManager {
* A throwing subscriber must not abort the watcher's emit loop or break
* a HookSession event handler in flight. */
private notifySessionsChanged(): void {
if (this.disposed) return;
if (!this.onSessionsChangedRaw) return;
if (this.disposed) {
return;
}
if (!this.onSessionsChangedRaw) {
return;
}
try {
this.onSessionsChangedRaw();
} catch (err) {
@@ -480,7 +549,9 @@ export class HookManager {
}
private assertValidPid(pid: number): void {
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
if (!Number.isInteger(pid) || pid <= 0) {
throw new Error('invalid pid');
}
}
}
@@ -510,12 +581,18 @@ function isTransientLibcMappingError(error: string): boolean {
* for picking the right PID from WebUI.
*/
export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
if (process.platform !== 'linux') return true;
if (process.platform !== 'linux') {
return true;
}
// Escape hatch: operators who explicitly want auto-load on every
// enumerated PID can set this to opt out of the filter.
if (process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL === '1') return true;
if (process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL === '1') {
return true;
}
let cmdline: string;
try {
cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
} catch {
@@ -524,13 +601,16 @@ export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
// will fail with a clear error.
return true;
}
if (cmdline.includes('--type=')) {
const type = (/--type=([^\0\s]+)/.exec(cmdline)?.[1]) ?? 'unknown';
const type = /--type=([^\0\s]+)/.exec(cmdline)?.[1] ?? 'unknown';
log.info('auto-load skip: PID=%d is an Electron child process (--type=%s)', pid, type);
return false;
}
return true;
}
export type { HookProcessBaseInfo } from './injector';
export type { QqPortLoginInfo } from './qq-port-probe';
export type { HookProcessInfo, HookProcessStatus } from './types';
+46 -6
View File
@@ -1,19 +1,43 @@
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 };
return {
success: false,
gotResponse: false,
errorCode: -1,
errorMessage: 'qq_hook client is not logged in',
responseData: null,
};
}
try {
const reply = await this.client.send(serviceCmd, body, {
const reply = (await this.client.send(serviceCmd, body, {
wantReply: true,
replyTimeoutMs: timeoutMs,
}) as QqHookSendReply;
})) as QqHookSendReply;
this.setOutboundHealthy(true);
return {
success: reply.error === 0,
gotResponse: true,
@@ -22,6 +46,13 @@ 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 +62,13 @@ export class HookPacketClient implements PacketSender {
};
}
}
private setOutboundHealthy(healthy: boolean): void {
if (this.outboundHealthy === healthy) {
return;
}
this.outboundHealthy = healthy;
this.onOutboundHealthChanged?.(healthy);
}
}
+65 -27
View File
@@ -10,27 +10,44 @@ export interface HookRuntimeDirDeps {
}
function configuredDirectory(value: string | undefined, variable: string): string | null {
if (!value) return 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;
if (!entry) {
continue;
}
const separator = entry.indexOf('=');
if (separator <= 0) continue;
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;
if (!match) {
return null;
}
const uid = Number(match[1]);
return Number.isSafeInteger(uid) && uid >= 0 ? uid : null;
}
@@ -44,24 +61,30 @@ function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function ownRuntimeDir(
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv,
ownUid: number,
): string {
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;
if (explicit) {
return explicit;
}
const xdg = configuredDirectory(env.XDG_RUNTIME_DIR, 'XDG_RUNTIME_DIR');
if (xdg) return xdg;
if (xdg) {
return xdg;
}
if (platform === 'darwin') {
const tmpdir = configuredDirectory(env.TMPDIR, 'TMPDIR');
if (tmpdir) return path.join(tmpdir, 'snowluma-hook');
if (tmpdir) {
return path.join(tmpdir, 'snowluma-hook');
}
}
return `/tmp/snowluma-${ownUid}`;
}
@@ -69,14 +92,12 @@ function ownRuntimeDir(
* 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 {
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 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) {
@@ -84,18 +105,27 @@ export function resolveHookRuntimeDir(
}
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;
if (explicit) {
return explicit;
}
const xdg = configuredDirectory(
targetEnv.XDG_RUNTIME_DIR,
`QQ process ${targetPid} XDG_RUNTIME_DIR`,
);
if (xdg) return xdg;
if (xdg) {
return xdg;
}
environError = new Error('runtime directory is not present');
} catch (error) {
// An invalid explicit path is configuration corruption and must remain
@@ -104,27 +134,35 @@ export function resolveHookRuntimeDir(
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}`;
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'))) {
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)}`,
`cannot resolve hook runtime directory for PID ${targetPid}: ` +
`environment=${errorMessage(environError)}; status=${errorMessage(statusError)}`,
);
}
+361 -88
View File
@@ -68,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
*/
@@ -101,12 +103,14 @@ export class HookSession extends EventEmitter {
private disposed = false;
private loginProbeTimer: ReturnType<typeof setInterval> | null = null;
private probing = false;
private lastProbeFailure = '';
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;
@@ -125,16 +129,33 @@ export class HookSession extends EventEmitter {
// ─────────────── readonly public surface ───────────────
get status(): HookProcessStatus { return this._status; }
get error(): string { return this._error; }
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 status(): HookProcessStatus {
return this._status;
}
get error(): string {
return this._error;
}
get uin(): string {
return this._uin;
}
get method(): string {
return this._method;
}
get isDisposed(): boolean {
return this.disposed;
}
get receiveHealthy(): boolean {
return this._receiveHealthy && this._outboundHealthy;
}
attachProcessInfo(info: { name?: string; path?: string }): void {
if (info.name) this._name = info.name;
if (info.path) this._path = info.path;
if (info.name) {
this._name = info.name;
}
if (info.path) {
this._path = info.path;
}
}
toInfo(): HookProcessInfo {
@@ -172,27 +193,45 @@ export class HookSession extends EventEmitter {
* attempts and adopts pre-existing hooks. Idempotent; safe to call on
* every watcher tick where the pipe is live. */
onPipeUp(): void {
if (this.disposed) return;
if (this.disposed) {
return;
}
void this.serialize(async () => {
if (this.disposed) return;
if (this.disposed) {
return;
}
await this.reconcilePipeUp();
}).catch(err => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
}).catch((err) => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
}
onPipeDown(): void {
if (this.disposed) return;
if (this.disposed) {
return;
}
void this.serialize(async () => {
if (this.disposed) return;
if (this.disposed) {
return;
}
this.reconcilePipeDown();
}).catch(err => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err)));
}).catch((err) => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err)));
}
/** Called by the manager when the watcher reports the QQ.exe process is
* gone. Cleans up and signals the manager to remove this session. */
notifyProcessGone(): void {
if (this.disposed) return;
if (this.disposed) {
return;
}
void this.serialize(async () => {
if (this.disposed) return;
if (this.disposed) {
return;
}
runWithTraceRequest(() => {
const startedAt = Date.now();
const wasLoggedIn = this.loggedIn;
@@ -206,8 +245,12 @@ export class HookSession extends EventEmitter {
this.injectResult = null;
this._method = '';
this.setStatus('available', '');
try {
if (wasLoggedIn) this.emit('disconnected', true);
if (wasLoggedIn) {
this.emit('disconnected', true);
}
this.disposed = true;
this.emit('disposed');
this.log.trace(() => [
@@ -229,13 +272,27 @@ export class HookSession extends EventEmitter {
throw error;
}
});
}).catch(err => this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)));
}).catch((err) =>
this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)),
);
}
dispose(): void {
if (this.disposed) return;
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();
}
@@ -253,13 +310,16 @@ export class HookSession extends EventEmitter {
operation,
renderParamsVerbose(this.toInfo()),
]);
try {
const info = await this.serialize(command);
const outcome = info.status === 'error'
|| (operation === 'unload' && info.status !== 'available')
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') {
@@ -267,6 +327,7 @@ export class HookSession extends EventEmitter {
} 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,
@@ -296,7 +357,9 @@ export class HookSession extends EventEmitter {
private serialize<T>(op: () => Promise<T>): Promise<T> {
const previous = this.opChain;
let release!: () => void;
const completion = new Promise<void>(resolve => { release = resolve; });
const completion = new Promise<void>((resolve) => {
release = resolve;
});
this.opChain = previous.then(() => completion);
return (async () => {
try {
@@ -313,6 +376,7 @@ export class HookSession extends EventEmitter {
private async loadInternal(): Promise<HookProcessInfo> {
this._error = '';
this.setStatus('loading', '');
try {
if (!this.injected) {
// Fast path: a previous SnowLuma run may have left the hook DLL
@@ -342,23 +406,40 @@ export class HookSession extends EventEmitter {
);
}
}
this.applyStatus();
} catch (error) {
this._error = errMsg(error);
this.setStatus('error', this._error);
this.log.error('load failed: PID=%d err=%s', this.pid, this._error);
// The module can already be listening even when this call returns
// failure: another load left it resident, or it came up after the
// call returned. A live pipe still has the account state, so connect
// instead of staying on the failed load.
await this.pipeWatcher.tickNow?.();
if (!this.disposed && this.pipeWatcher.isPipeLive(this.pid)) {
this.log.info('PID=%d load failed but pipe is up; connecting', this.pid);
await this.reconcilePipeUp();
}
}
return this.toInfo();
}
private async unloadInternal(): Promise<HookProcessInfo> {
this._error = '';
try {
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
if (wasLoggedIn) this.emit('disconnected', true);
if (wasLoggedIn) {
this.emit('disconnected', true);
}
const handle = this.injectResult?.handle;
if (this.injected && handle) {
this.injector.unload(this.pid, handle);
this.log.info('SnowLuma unloaded from PID=%d', this.pid);
@@ -375,6 +456,7 @@ export class HookSession extends EventEmitter {
// a successful unload reads as "pipe still live" until the next
// background tick runs and we'd report a spurious failure.
await this.pipeWatcher.tickNow?.();
if (this.pipeWatcher.isPipeLive(this.pid)) {
this._error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连';
this.setStatus('connecting', this._error);
@@ -387,11 +469,13 @@ export class HookSession extends EventEmitter {
this.setStatus('error', this._error);
this.log.error('unload failed: PID=%d err=%s', this.pid, this._error);
}
return this.toInfo();
}
private async refreshInternal(): Promise<HookProcessInfo> {
this._error = '';
try {
// Same pipe-up / pipe-down reconcilers the watcher drives, chosen by
// a fresh poll. This collapses what used to be a hand-copied pair of
@@ -407,6 +491,7 @@ export class HookSession extends EventEmitter {
this.setStatus(this.injected ? 'disconnected' : 'error', this._error);
this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error);
}
return this.toInfo();
}
@@ -416,12 +501,15 @@ export class HookSession extends EventEmitter {
* defaults to the current `loggedIn`; callers that just tore the client
* down pass the value captured *before* teardown (teardown clears it). */
private applyStatus(wasLoggedIn: boolean = this.loggedIn, error = ''): void {
this.setStatus(statusFor({
this.setStatus(
statusFor({
injected: this.injected,
connected: this.connected,
loggedIn: this.loggedIn,
wasLoggedIn,
}), error);
}),
error,
);
}
/** Pipe is up: adopt a DLL that survived a SnowLuma restart, drop a
@@ -430,9 +518,16 @@ export class HookSession extends EventEmitter {
private async reconcilePipeUp(): Promise<void> {
if (!this.injected) {
this.injected = true;
if (!this._method) this._method = 'reconnect';
if (!this._method) {
this._method = 'reconnect';
}
if (this.client?.isClosed) this.tearDownClient();
}
if (this.client?.isClosed) {
this.tearDownClient();
}
if (!this.connected) {
await this.attemptConnect();
} else {
@@ -450,9 +545,13 @@ export class HookSession extends EventEmitter {
// a disconnect, and we must NOT clobber a diagnostic the failed
// connect/load already set — settle the status keeping `_error`, or
// (when not even injected) leave the status untouched entirely.
if (this.injected) this.applyStatus(this.loggedIn, this._error);
if (this.injected) {
this.applyStatus(this.loggedIn, this._error);
}
return;
}
runWithTraceRequest(() => {
const startedAt = Date.now();
const wasLoggedIn = this.loggedIn;
@@ -463,8 +562,12 @@ export class HookSession extends EventEmitter {
]);
this.tearDownClient();
this.applyStatus(wasLoggedIn);
try {
if (wasLoggedIn) this.emit('disconnected', true);
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,
@@ -488,7 +591,10 @@ export class HookSession extends EventEmitter {
// ─────────────── client plumbing ───────────────
private async attemptConnect(): Promise<void> {
if (this.connected) return;
if (this.connected) {
return;
}
return runWithTraceRequest(async () => {
const startedAt = Date.now();
this.log.trace(() => [
@@ -496,22 +602,31 @@ export class HookSession extends EventEmitter {
this.pid,
renderParamsVerbose(this.toInfo()),
]);
if (this.client?.isClosed) this.tearDownClient();
if (this.client?.isClosed) {
this.tearDownClient();
}
if (!this.client) {
this.client = this.makeClient(this.pid);
this.sender = new HookPacketClient(this.client);
this.sender = new HookPacketClient(this.client, (healthy) =>
this.setOutboundHealthy(healthy),
);
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'.
@@ -524,6 +639,7 @@ export class HookSession extends EventEmitter {
// 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',
@@ -549,23 +665,37 @@ export class HookSession extends EventEmitter {
}
private bindClient(client: QqHookClient): void {
client.on('packet', packet => this.handlePacket(packet));
client.on('loginState', state => this.handleLoginState(state));
client.on('error', error => {
client.on('packet', (packet) => this.handlePacket(packet));
client.on('loginState', (state) => this.handleLoginState(state));
client.on('error', (error) => {
const msg = errMsg(error);
this._error = msg;
this.log.warn('pipe error: PID=%d err=%s', this.pid, msg);
});
client.on('close', () => {
if (this.disposed) return;
if (this.disposed) {
return;
}
// Only the currently-registered client should drive a reconcile;
// listeners may fire for an already-replaced client.
if (this.client !== client) return;
if (this.client !== client) {
return;
}
void this.serialize(async () => {
if (this.disposed) return;
if (this.client !== client) return;
if (this.disposed) {
return;
}
if (this.client !== client) {
return;
}
this.reconcilePipeDown();
}).catch(err => this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)));
}).catch((err) =>
this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)),
);
});
}
@@ -573,15 +703,23 @@ export class HookSession extends EventEmitter {
this.stopLoginReconcile();
this.resetReceiveWatch();
const client = this.client;
if (client) {
client.removeAllListeners();
try { client.close(); } catch { /* ignore */ }
try {
client.close();
} catch {
/* ignore */
}
}
this.client = null;
this.sender = null;
this.bound = false;
this.connected = false;
this.loggedIn = false;
this._outboundHealthy = true;
this.resetLoginHint();
}
@@ -590,14 +728,20 @@ export class HookSession extends EventEmitter {
const previousUin = this._uin;
this._uin = state.uin || state.uinNumber.toString();
this.loggedIn = state.loggedIn && isRealUin(this._uin);
// 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
@@ -610,8 +754,13 @@ export class HookSession extends EventEmitter {
this.applyStatus(wasLoggedIn, this.loggedIn ? '' : this._error);
}
if (!this.loggedIn || !this.sender) return;
if (wasLoggedIn && previousUin === this._uin) return;
if (!this.loggedIn || !this.sender) {
return;
}
if (wasLoggedIn && previousUin === this._uin) {
return;
}
runWithTraceRequest(() => {
const startedAt = Date.now();
@@ -621,6 +770,7 @@ export class HookSession extends EventEmitter {
previousUin,
this._uin,
);
try {
this.emit('login', this._uin, this.sender!);
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
@@ -651,9 +801,16 @@ export class HookSession extends EventEmitter {
// online state from the probe.
private startLoginReconcile(): void {
if (this.loginProbeTimer || this.disposed) return;
if (this.loginProbeTimer || this.disposed) {
return;
}
this.log.info('awaiting login: PID=%d', this.pid);
void this.probeLoginOnce(); // immediate — catch already-logged-in fast
this.loginProbeTimer = setInterval(() => void this.probeLoginOnce(), LOGIN_RECONCILE_INTERVAL_MS);
this.loginProbeTimer = setInterval(
() => void this.probeLoginOnce(),
LOGIN_RECONCILE_INTERVAL_MS,
);
this.loginProbeTimer.unref?.();
}
@@ -667,51 +824,98 @@ export class HookSession extends EventEmitter {
private async probeLoginOnce(): Promise<void> {
// A port-scan probe can outlast the interval; skip overlapping ticks so a
// 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;
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 (error) {
this.log.trace(
'login identity probe failed: PID=%d err=%s',
this.pid,
errMsg(error),
);
const message = errMsg(error);
const note = `${this.pid}:${message}`;
if (this.lastProbeFailure !== note) {
this.lastProbeFailure = note;
this.log.warn('login probe failed: PID=%d err=%s', this.pid, message);
}
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?.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;
if (this.disposed || !this.connected || this.loggedIn) {
this.stopLoginReconcile();
return;
}
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;
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);
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;
if (
this.client !== client ||
this.disposed ||
!this.connected ||
this.loggedIn
) {
return;
}
this.acceptedLoginHintUin = info.uin;
this.nextLoginIdentityObservationAt = Date.now()
+ LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
this.nextLoginIdentityObservationAt =
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
} catch (error) {
if (this.client !== client || this.disposed) return;
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',
@@ -720,11 +924,11 @@ export class HookSession extends EventEmitter {
attempt,
errMsg(error),
);
this.nextLoginIdentityObservationAt = Date.now()
+ LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
this.nextLoginIdentityObservationAt =
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
} else {
this.nextLoginHintAt = Date.now()
+ LOGIN_HINT_RETRY_DELAYS_MS[attempt - 1]!;
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,
@@ -746,18 +950,32 @@ export class HookSession extends EventEmitter {
this.loginHintAttempts = 0;
this.nextLoginHintAt = 0;
this.nextLoginIdentityObservationAt = 0;
this.lastProbeFailure = '';
}
private handlePacket(packet: QqHookPacket): void {
if (!this.loggedIn) return;
if (!this.loggedIn) {
return;
}
const uin = packet.uin || this._uin;
// Routing requires a real UIN, but even a frame carrying UIN=0 proves the
// receive hook is alive. Attribute that evidence to the current epoch
// without forwarding the malformed packet into BridgeManager.
const receiveUin = isRealUin(uin) ? uin : (this.receiveWatchUin || this._uin);
if (isRealUin(receiveUin)) this.noteReceiveActivity(packet.cmd, receiveUin);
if (!isRealUin(uin)) return;
if (!this.onPacket) return;
const receiveUin = isRealUin(uin) ? uin : this.receiveWatchUin || this._uin;
if (isRealUin(receiveUin)) {
this.noteReceiveActivity(packet.cmd, receiveUin);
}
if (!isRealUin(uin)) {
return;
}
if (!this.onPacket) {
return;
}
// Re-shape the hook-client wire packet into BridgeManager's PacketInfo
// shape. Used to live in the deleted NtqqHandler.onHookPacket; field
// renaming was that module's entire purpose, so it lives at the source
@@ -774,7 +992,10 @@ export class HookSession extends EventEmitter {
}
private setStatus(status: HookProcessStatus, error: string): void {
if (this._status === status && this._error === error) return;
if (this._status === status && this._error === error) {
return;
}
this._status = status;
this._error = error;
this.emit('status-changed', status, error);
@@ -783,12 +1004,21 @@ export class HookSession extends EventEmitter {
private noteReceiveActivity(cmd: string, uin: string): void {
// BridgeManager treats packet.uin as authoritative and may move this PID
// before the next loginState edge. Keep the watchdog on that same epoch.
if (this.receiveWatchUin !== uin) this.resetReceiveWatch(uin);
if (this.receiveWatchUin !== uin) {
this.resetReceiveWatch(uin);
}
if (!this.receiveWatchArmed) {
if (cmd !== QQ_RECV_HEARTBEAT_CMD) return;
if (cmd !== QQ_RECV_HEARTBEAT_CMD) {
return;
}
this.receiveWatchArmed = true;
this.log.debug('receive health armed by QQ heartbeat: PID=%d UIN=%s', this.pid, this.receiveWatchUin);
this.log.debug(
'receive health armed by QQ heartbeat: PID=%d UIN=%s',
this.pid,
this.receiveWatchUin,
);
}
const now = Date.now();
@@ -808,22 +1038,34 @@ export class HookSession extends EventEmitter {
}
private scheduleReceiveStaleCheck(): void {
if (this.receiveWatchTimer) clearTimeout(this.receiveWatchTimer);
if (this.receiveWatchTimer) {
clearTimeout(this.receiveWatchTimer);
}
this.receiveWatchTimer = setTimeout(() => {
this.receiveWatchTimer = null;
if (!this.shouldWatchReceive()) return;
if (!this.shouldWatchReceive()) {
return;
}
// A delayed event loop (notably system sleep/resume) lands here long
// after the nominal 90s deadline. Do not flip health immediately: give
// the real QQ heartbeat one short confirmation window to arrive.
this.receiveWatchTimer = setTimeout(() => {
this.receiveWatchTimer = null;
if (!this.shouldWatchReceive()) return;
if (!this.shouldWatchReceive()) {
return;
}
const silentForMs = Date.now() - this.lastReceiveAt;
if (silentForMs < RECEIVE_STALE_AFTER_MS + RECEIVE_STALE_CONFIRM_MS) {
this.scheduleReceiveStaleCheck();
return;
}
this.setReceiveHealthy(false);
this.log.warn(
'receive path stale: PID=%d UIN=%s lastRecvAt=%s silentFor=%dms; reporting good=false',
@@ -843,9 +1085,39 @@ export class HookSession extends EventEmitter {
}
private setReceiveHealthy(healthy: boolean): void {
if (this._receiveHealthy === healthy) return;
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 {
@@ -853,6 +1125,7 @@ export class HookSession extends EventEmitter {
clearTimeout(this.receiveWatchTimer);
this.receiveWatchTimer = null;
}
this.receiveWatchUin = uin;
this.receiveWatchArmed = false;
this.lastReceiveAt = 0;
+8 -2
View File
@@ -25,7 +25,13 @@ export interface HookFlags {
* here.
*/
export function statusFor(flags: HookFlags): HookProcessStatus {
if (!flags.injected) return 'available';
if (flags.connected) return flags.loggedIn ? 'online' : 'loaded';
if (!flags.injected) {
return 'available';
}
if (flags.connected) {
return flags.loggedIn ? 'online' : 'loaded';
}
return flags.wasLoggedIn ? 'disconnected' : 'connecting';
}
+12 -3
View File
@@ -1,5 +1,14 @@
export {
HookManager, type BridgeManagerSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
type HookProcessStatus, type QqPortLoginInfo
HookManager,
type BridgeManagerSink,
type HookManagerDeps,
type HookProcessBaseInfo,
type HookProcessInfo,
type HookProcessStatus,
type QqPortLoginInfo,
} from './hook-manager';
export {
getRuntimeIntegrity,
hasLowProcessIntegrity,
type RuntimeIntegrity,
} from './runtime-integrity';
+32 -7
View File
@@ -14,6 +14,7 @@ export interface ManualMapHandle {
}
interface NativeHookAddon {
getRuntimeIntegrity?(): unknown;
getAllMainProcess(): number[];
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>;
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
@@ -42,7 +43,10 @@ function loadNativeAddon(addonPath: string): NativeHookAddon {
type HookBinaryExt = 'node' | 'dll' | 'so';
function platformBinaryName(ext: HookBinaryExt): string {
if (process.platform === 'win32' && process.arch === 'x64') return `snowluma-win32-x64.${ext}`;
if (process.platform === 'win32' && process.arch === 'x64') {
return `snowluma-win32-x64.${ext}`;
}
return `snowluma-${process.platform}-${process.arch}.${ext}`;
}
@@ -71,20 +75,30 @@ function nativeSearchDirs(): string[] {
export function resolveHookNativePath(ext: HookBinaryExt): string | null {
const fileName = platformBinaryName(ext);
for (const dir of nativeSearchDirs()) {
const fullPath = path.join(dir, fileName);
if (existsSync(fullPath)) return fullPath;
if (existsSync(fullPath)) {
return fullPath;
}
}
return null;
}
export function getNativeHookAddon(): NativeHookAddon | null {
if (nativeAddon) return nativeAddon;
if (nativeAddon) {
return nativeAddon;
}
const addonPath = resolveHookNativePath('node');
if (!addonPath) {
nativeLoadError = `No hook native addon found for ${process.platform}-${process.arch}`;
return null;
}
try {
nativeAddon = loadNativeAddon(addonPath);
nativeLoadError = null;
@@ -109,33 +123,44 @@ export function listHookProcesses(): HookProcessBaseInfo[] {
if (process.platform === 'darwin') {
return [...listSnowlumaPipePidsSync()]
.sort((a, b) => a - b)
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
.map((pid) => ({ pid, name: defaultProcessName(), path: '' }));
}
const addon = getNativeHookAddon();
if (!addon) return [];
if (!addon) {
return [];
}
return [...new Set(addon.getAllMainProcess())]
.filter(pid => Number.isInteger(pid) && pid > 0)
.filter((pid) => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b)
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
.map((pid) => ({ pid, name: defaultProcessName(), path: '' }));
}
export async function injectHookProcess(pid: number): Promise<HookInjectResult> {
const addon = getNativeHookAddon();
if (!addon) {
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
}
const injectableExt = platformInjectableExt();
const dllPath = resolveHookNativePath(injectableExt);
if (!dllPath) {
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
}
return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) };
}
export function unloadHookProcess(pid: number, handle: ManualMapHandle): void {
const addon = getNativeHookAddon();
if (!addon) {
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
}
addon.unloadModuleManual(pid, handle);
}
+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 });
}
+42 -9
View File
@@ -76,7 +76,10 @@ export class PipeWatcher extends EventEmitter {
* and begin the polling loop. Idempotent.
*/
start(): Promise<void> {
if (this.startPromise) return this.startPromise;
if (this.startPromise) {
return this.startPromise;
}
this.startPromise = (async () => {
try {
await this.tickOnce();
@@ -89,7 +92,10 @@ export class PipeWatcher extends EventEmitter {
/** Pull the next scheduled tick forward to the next event-loop turn. */
wake(): void {
if (this.stopped) return;
if (this.stopped) {
return;
}
this.scheduleNext(0);
}
@@ -100,6 +106,7 @@ export class PipeWatcher extends EventEmitter {
stop(): void {
this.stopped = true;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
@@ -112,15 +119,22 @@ export class PipeWatcher extends EventEmitter {
}
private scheduleNext(delayMs: number): void {
if (this.stopped) return;
if (this.stopped) {
return;
}
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(() => {
this.timer = setTimeout(
() => {
this.timer = null;
void this.tickAndReschedule();
}, Math.max(0, delayMs));
},
Math.max(0, delayMs),
);
}
private async tickAndReschedule(): Promise<void> {
@@ -140,15 +154,19 @@ export class PipeWatcher extends EventEmitter {
this.pendingWake = true;
return;
}
this.ticking = true;
try {
let processes: HookProcessBaseInfo[] | null;
try {
processes = await this.listProcesses();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
processes = null;
}
// UNKNOWN (timeout / failure): keep the prior process + pipe snapshot.
// Treating missing data as "everything disappeared" would fire
// process-gone for every live PID and dispose healthy sessions — the
@@ -159,7 +177,9 @@ export class PipeWatcher extends EventEmitter {
this.emit('tick');
return;
}
let livePipes: Set<number> | null;
try {
livePipes = await this.listLivePipes(processes);
} catch (error) {
@@ -168,7 +188,10 @@ export class PipeWatcher extends EventEmitter {
}
const newKnownPids = new Set<number>();
for (const proc of processes) newKnownPids.add(proc.pid);
for (const proc of processes) {
newKnownPids.add(proc.pid);
}
// 1. Newly discovered processes.
for (const proc of processes) {
@@ -180,16 +203,23 @@ 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>();
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);
if (newKnownPids.has(pid)) {
newLivePipes.add(pid);
}
}
} else {
for (const pid of livePipes) {
if (!newKnownPids.has(pid)) continue;
if (!newKnownPids.has(pid)) {
continue;
}
newLivePipes.add(pid);
if (!this.livePipes.has(pid)) {
this.emit('pipe-up', pid);
}
@@ -216,10 +246,13 @@ export class PipeWatcher extends EventEmitter {
this.emit('tick');
} finally {
this.ticking = false;
if (this.pendingWake) {
this.pendingWake = false;
// Defer to break sync recursion if a listener calls wake().
setImmediate(() => { void this.tickOnce(); });
setImmediate(() => {
void this.tickOnce();
});
}
}
}
+68 -15
View File
@@ -110,7 +110,9 @@ export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): Proce
return null;
}
},
dispose() { /* nothing to tear down */ },
dispose() {
/* nothing to tear down */
},
};
}
@@ -127,41 +129,67 @@ export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): Proce
const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } });
worker = w;
w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => {
if (msg.type === 'ready') return;
if (msg.type === 'ready') {
return;
}
if (msg.type === 'fatal') {
// The addon won't load off-thread — give up on isolation for good and
// fall back to the synchronous path from here on. Resolve any in-flight
// request now (UNKNOWN) so it doesn't sit waiting for the timeout.
log.warn('process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration', msg.error ?? '');
log.warn(
'process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration',
msg.error ?? '',
);
isolationBroken = true;
for (const { resolve } of pending.values()) resolve(null);
for (const { resolve } of pending.values()) {
resolve(null);
}
pending.clear();
teardownWorker();
return;
}
if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') {
const entry = pending.get(msg.id);
if (!entry) return;
if (!entry) {
return;
}
pending.delete(msg.id);
entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null);
}
});
w.on('error', (err) => {
log.warn('enumeration worker error: %s', errMsg(err));
if (worker === w) teardownWorker();
if (worker === w) {
teardownWorker();
}
});
};
const teardownWorker = (): void => {
const w = worker;
worker = null;
if (!w) return;
if (!w) {
return;
}
// terminate() can't preempt a thread blocked in the native call; it takes
// effect once the call returns. Track it as an orphan until it actually
// exits so we can bound how many we let pile up.
orphans += 1;
w.once('exit', () => { orphans = Math.max(0, orphans - 1); });
void w.terminate().catch(() => { /* already gone */ });
w.once('exit', () => {
orphans = Math.max(0, orphans - 1);
});
void w.terminate().catch(() => {
/* already gone */
});
};
const syncFallback = (): HookProcessBaseInfo[] | null => {
@@ -175,7 +203,9 @@ export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): Proce
return {
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
if (disposed || isolationBroken) return syncFallback();
if (disposed || isolationBroken) {
return syncFallback();
}
if (!worker) {
if (orphans >= maxOrphans) {
@@ -183,15 +213,21 @@ export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): Proce
// don't spawn more; report UNKNOWN and let them drain.
return null;
}
spawnWorker();
}
const w = worker;
if (!w) return syncFallback();
if (!w) {
return syncFallback();
}
const id = ++seq;
const resultPromise = new Promise<number[] | null>((resolve) => {
pending.set(id, { resolve });
});
try {
w.postMessage({ type: 'enumerate', id });
} catch (err) {
@@ -206,29 +242,46 @@ export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): Proce
timer = setTimeout(() => resolve('timeout'), timeoutMs);
});
const outcome = await Promise.race([resultPromise, timeout]);
if (timer) clearTimeout(timer);
if (timer) {
clearTimeout(timer);
}
if (outcome === 'timeout') {
pending.delete(id);
log.warn('process enumeration timed out after %dms (worker abandoned) — keeping prior process set', timeoutMs);
log.warn(
'process enumeration timed out after %dms (worker abandoned) — keeping prior process set',
timeoutMs,
);
teardownWorker();
return null;
}
if (outcome === null) {
// Native call threw inside the worker — treat as a transient failure,
// keep prior state rather than nuking every session.
return null;
}
return mapPids(outcome, deps.processName);
},
dispose() {
disposed = true;
for (const { resolve } of pending.values()) resolve(null);
for (const { resolve } of pending.values()) {
resolve(null);
}
pending.clear();
const w = worker;
worker = null;
if (w) void w.terminate().catch(() => { /* ignore */ });
if (w) {
void w.terminate().catch(() => {
/* ignore */
});
}
},
};
}
+372 -107
View File
@@ -10,6 +10,7 @@ import { isRealUin } from '@snowluma/common/uin';
import { readdirSync, promises as fs } from 'fs';
import net from 'net';
import path from 'path';
import { positiveIntEnv } from '@snowluma/common/env';
import { resolveHookRuntimeDir } from './hook-runtime-dir';
export const PIPE_MAGIC = 0x31504851;
@@ -23,6 +24,7 @@ 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');
@@ -110,11 +112,13 @@ function isMissingDirectoryError(error: unknown): boolean {
function isUnavailableSocketError(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
return code === 'ENOENT'
|| code === 'ENOTDIR'
|| code === 'ENOTSOCK'
|| code === 'ECONNREFUSED'
|| code === 'ECONNRESET';
return (
code === 'ENOENT' ||
code === 'ENOTDIR' ||
code === 'ENOTSOCK' ||
code === 'ECONNREFUSED' ||
code === 'ECONNRESET'
);
}
/**
@@ -130,30 +134,46 @@ function isUnavailableSocketError(error: unknown): boolean {
* sufficient signal for "process exists with our dylib mapped". The async
* variant still gates the subsequent `pipe-up` emit via a real connect.
*/
export function listSnowlumaPipePidsSync(
runtimeDir = resolveHookRuntimeDir(),
): Set<number> {
export function listSnowlumaPipePidsSync(runtimeDir = resolveHookRuntimeDir()): Set<number> {
const result = new Set<number>();
let names: string[];
try {
names = readdirSync(runtimeDir);
} catch (error) {
if (isMissingDirectoryError(error)) return result;
throw error;
}
for (const name of names) {
const m = /^mojo\.(\d+)\.control\.sock$/i.exec(name);
if (!m) continue;
const pid = Number(m[1]);
if (Number.isInteger(pid) && pid > 0) result.add(pid);
}
if (isMissingDirectoryError(error)) {
return result;
}
function mojoPipeName(pid: number, suffix: string, runtimeDir = resolveHookRuntimeDir(pid)): string {
throw error;
}
for (const name of names) {
const m = /^mojo\.(\d+)\.control\.sock$/i.exec(name);
if (!m) {
continue;
}
const pid = Number(m[1]);
if (Number.isInteger(pid) && pid > 0) {
result.add(pid);
}
}
return result;
}
function mojoPipeName(
pid: number,
suffix: string,
runtimeDir = resolveHookRuntimeDir(pid),
): string {
if (process.platform === 'win32') {
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
}
return path.join(runtimeDir, `mojo.${pid}.${suffix}.sock`);
}
@@ -162,37 +182,58 @@ type LinuxPipeProbe = (socketPath: string) => Promise<boolean>;
async function isConnectableUnixSocket(socketPath: string): Promise<boolean> {
try {
const stat = await fs.stat(socketPath);
if (!stat.isSocket()) return false;
if (!stat.isSocket()) {
return false;
}
} catch (error) {
if (isUnavailableSocketError(error)) return false;
if (isUnavailableSocketError(error)) {
return false;
}
throw error;
}
return new Promise<boolean>((resolve, reject) => {
let socket: net.Socket;
try {
socket = net.createConnection(socketPath);
} catch (error) {
if (isUnavailableSocketError(error)) resolve(false);
else reject(error);
if (isUnavailableSocketError(error)) {
resolve(false);
} else {
reject(error);
}
return;
}
let done = false;
let timer: NodeJS.Timeout;
const finish = (ok: boolean) => {
if (done) return;
if (done) {
return;
}
done = true;
clearTimeout(timer);
socket.removeAllListeners();
socket.destroy();
resolve(ok);
};
timer = setTimeout(() => finish(false), DEFAULT_PIPE_PROBE_TIMEOUT_MS);
socket.once('connect', () => finish(true));
socket.once('error', error => {
if (isUnavailableSocketError(error)) finish(false);
else {
if (done) return;
socket.once('error', (error) => {
if (isUnavailableSocketError(error)) {
finish(false);
} else {
if (done) {
return;
}
done = true;
clearTimeout(timer);
socket.removeAllListeners();
@@ -209,29 +250,57 @@ export async function listLiveLinuxPipePids(
): Promise<Set<number>> {
const result = new Set<number>();
let names: string[];
try {
names = await fs.readdir(runtimeDir);
} catch (error) {
if (isMissingDirectoryError(error)) return result;
if (isMissingDirectoryError(error)) {
return result;
}
throw error;
}
await Promise.all(names.map(async (name) => {
await Promise.all(
names.map(async (name) => {
const m = /^mojo\.(\d+)\.control\.sock$/.exec(name);
if (!m) return;
if (!m) {
return;
}
const pid = Number(m[1]);
if (!Number.isInteger(pid) || pid <= 0) return;
if (await probe(path.join(runtimeDir, name))) result.add(pid);
}));
if (!Number.isInteger(pid) || pid <= 0) {
return;
}
if (await probe(path.join(runtimeDir, name))) {
result.add(pid);
}
}),
);
return result;
}
function toBuffer(body: Buffer | Uint8Array | string | null | undefined): Buffer {
if (Buffer.isBuffer(body)) return body;
if (body instanceof Uint8Array) return Buffer.from(body);
if (typeof body === 'string') return Buffer.from(body, 'utf8');
if (body == null) return Buffer.alloc(0);
if (Buffer.isBuffer(body)) {
return body;
}
if (body instanceof Uint8Array) {
return Buffer.from(body);
}
if (typeof body === 'string') {
return Buffer.from(body, 'utf8');
}
if (body == null) {
return Buffer.alloc(0);
}
throw new TypeError('body must be Buffer, Uint8Array, string, or null');
}
@@ -256,25 +325,33 @@ class OperationTimeoutError extends Error {
}
function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
if (!timeoutMs || timeoutMs <= 0) return promise;
if (!timeoutMs || timeoutMs <= 0) {
return promise;
}
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new OperationTimeoutError(label, timeoutMs));
}, timeoutMs);
promise.then(
value => {
(value) => {
clearTimeout(timer);
resolve(value);
},
error => {
(error) => {
clearTimeout(timer);
reject(error);
});
},
);
});
}
class HookPipeRequestError extends Error {
constructor(message: string) {
export class HookPipeRequestError extends Error {
constructor(
message: string,
readonly status: number,
readonly requestId: number,
) {
super(message);
this.name = 'HookPipeRequestError';
}
@@ -284,11 +361,20 @@ 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';
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';
}
@@ -335,6 +421,7 @@ function validatePipeFrameLengths(cmdLen: number, msgLen: number, bodyLen: numbe
['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}`);
@@ -364,24 +451,29 @@ class FrameReader {
push(chunk: Buffer): void {
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,
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;
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}`);
throw new Error(
`bad frame header magic=0x${magic.toString(16)} version=${version}`,
);
}
const cmdLen = this.header.readUInt32LE(20);
@@ -398,7 +490,8 @@ class FrameReader {
cmdLen,
msgLen,
bodyLen,
payload: payloadLength === 0 ? Buffer.alloc(0) : Buffer.allocUnsafe(payloadLength),
payload:
payloadLength === 0 ? Buffer.alloc(0) : Buffer.allocUnsafe(payloadLength),
received: 0,
};
}
@@ -408,6 +501,7 @@ class FrameReader {
pending.payload.length - pending.received,
chunk.length - chunkOffset,
);
if (payloadBytes > 0) {
chunk.copy(
pending.payload,
@@ -418,7 +512,10 @@ class FrameReader {
pending.received += payloadBytes;
chunkOffset += payloadBytes;
}
if (pending.received < pending.payload.length) return;
if (pending.received < pending.payload.length) {
return;
}
this.pending = null;
const frame: PipeFrame = {
@@ -465,11 +562,14 @@ export class QqHookClient extends EventEmitter {
private loginState: QqHookLoginState = { loggedIn: false, uin: '0', uinNumber: 0n };
private loginWaiters: Deferred<QqHookLoginState>[] = [];
constructor(pid: number, {
ackTimeoutMs = DEFAULT_ACK_TIMEOUT_MS,
constructor(
pid: number,
{
ackTimeoutMs = positiveIntEnv('SNOWLUMA_HOOK_ACK_TIMEOUT_MS', DEFAULT_ACK_TIMEOUT_MS),
replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS,
runtimeDir = resolveHookRuntimeDir(pid),
}: QqHookClientOptions = {}) {
}: QqHookClientOptions = {},
) {
super();
this.pid = pid;
this.runtimeDir = runtimeDir;
@@ -505,14 +605,17 @@ export class QqHookClient extends EventEmitter {
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) {
return this.getLoginState();
}
const deferred = createDeferred<QqHookLoginState>();
this.loginWaiters.push(deferred);
return withTimeout(deferred.promise, timeoutMs, 'waitForLogin');
@@ -543,23 +646,35 @@ export class QqHookClient extends EventEmitter {
*/
static async listLivePipes(pids: readonly number[] = []): Promise<Set<number>> {
const result = new Set<number>();
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 (m) {
result.add(Number(m[1]));
}
}
} else {
const runtimeDirs = new Set<string>();
if (pids.length === 0) {
runtimeDirs.add(resolveHookRuntimeDir());
} else {
for (const pid of pids) runtimeDirs.add(resolveHookRuntimeDir(pid));
for (const pid of pids) {
runtimeDirs.add(resolveHookRuntimeDir(pid));
}
}
for (const runtimeDir of runtimeDirs) {
for (const pid of await listLiveLinuxPipePids(runtimeDir)) result.add(pid);
for (const pid of await listLiveLinuxPipePids(runtimeDir)) {
result.add(pid);
}
}
}
return result;
}
@@ -567,13 +682,17 @@ export class QqHookClient extends EventEmitter {
if (this.closed) {
throw new Error('qq_hook client is closed');
}
if (this.controlSocket && this.controlHello) {
return this.controlHello;
}
if (this.controlConnectPromise) {
return this.controlConnectPromise;
}
this.controlConnectPromise = this.connectPipe('control');
try {
return await this.controlConnectPromise;
} finally {
@@ -585,16 +704,21 @@ export class QqHookClient extends EventEmitter {
if (this.closed) {
throw new Error('qq_hook client is closed');
}
if (typeof onPacket === 'function') {
this.on('packet', onPacket);
}
if (this.recvSocket && this.recvHello) {
return this.recvHello;
}
if (this.recvConnectPromise) {
return this.recvConnectPromise;
}
this.recvConnectPromise = this.connectPipe('recv');
try {
return await this.recvConnectPromise;
} finally {
@@ -602,17 +726,24 @@ export class QqHookClient extends EventEmitter {
}
}
async connectAll({ recv = true } = {}): Promise<{ control: QqHookHello; recv: QqHookHello | null }> {
async connectAll({ recv = true } = {}): Promise<{
control: QqHookHello;
recv: QqHookHello | null;
}> {
const control = await this.connect();
const recvInfo = recv ? await this.startRecv() : null;
return { control, recv: recvInfo };
}
async send(cmd: string, body: Buffer | Uint8Array | string | null | undefined, {
async send(
cmd: string,
body: Buffer | Uint8Array | string | null | undefined,
{
wantReply = true,
ackTimeoutMs = this.defaultAckTimeoutMs,
replyTimeoutMs = this.defaultReplyTimeoutMs,
}: QqHookSendOptions = {}): Promise<QqHookSendReply | { requestId: number }> {
}: QqHookSendOptions = {},
): Promise<QqHookSendReply | { requestId: number }> {
await this.connect();
const requestId = this.allocateRequestId();
@@ -639,7 +770,9 @@ export class QqHookClient extends EventEmitter {
// pending deferred — but the reply is only `await`ed AFTER the ack, so if the
// ack fails first the reply promise is rejected with NO awaiter. The real
// `await` below still observes the value/rejection (a separate continuation).
ackDeferred.promise.catch(() => { /* observed by the await, or harmless */ });
ackDeferred.promise.catch(() => {
/* observed by the await, or harmless */
});
this.pendingAcks.set(requestId, {
resolve: ackDeferred.resolve,
reject: ackDeferred.reject,
@@ -647,15 +780,19 @@ export class QqHookClient extends EventEmitter {
});
let replyDeferred: Deferred<QqHookSendReply> | null = null;
if (wantReply) {
replyDeferred = createDeferred<QqHookSendReply>();
replyDeferred.promise.catch(() => { /* see note above — prevents unhandled rejection */ });
replyDeferred.promise.catch(() => {
/* see note above — prevents unhandled rejection */
});
this.pendingReplies.set(requestId, replyDeferred);
}
try {
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',
@@ -665,10 +802,12 @@ export class QqHookClient extends EventEmitter {
]);
return { requestId };
}
const reply = await withTimeout(
replyDeferred!.promise,
replyTimeoutMs,
`send reply ${requestId}`);
`send reply ${requestId}`,
);
packetLog.trace(() => [
'packet_recv serviceCmd=%j requestId=%d error=%d message=%j length=%d body=%s',
cmd,
@@ -705,20 +844,39 @@ export class QqHookClient extends EventEmitter {
}
}
async sendNoReply(cmd: string, body: Buffer | Uint8Array | string | null | undefined, options: Omit<QqHookSendOptions, 'wantReply'> = {}): Promise<{ requestId: number }> {
return this.send(cmd, body, { ...options, wantReply: false }) as Promise<{ requestId: number }>;
async sendNoReply(
cmd: string,
body: Buffer | Uint8Array | string | null | undefined,
options: Omit<QqHookSendOptions, 'wantReply'> = {},
): Promise<{ requestId: number }> {
return this.send(cmd, body, { ...options, wantReply: false }) as Promise<{
requestId: number;
}>;
}
async sendAndWait(cmd: string, body: Buffer | Uint8Array | string | null | undefined, options: Omit<QqHookSendOptions, 'wantReply'> = {}): Promise<QqHookSendReply> {
async sendAndWait(
cmd: string,
body: Buffer | Uint8Array | string | null | undefined,
options: Omit<QqHookSendOptions, 'wantReply'> = {},
): Promise<QqHookSendReply> {
return this.send(cmd, body, { ...options, wantReply: true }) as Promise<QqHookSendReply>;
}
async sendMany(items: Array<{ cmd: string; body?: Buffer | Uint8Array | string | null; wantReply?: boolean; ackTimeoutMs?: number; replyTimeoutMs?: number }>, {
async sendMany(
items: Array<{
cmd: string;
body?: Buffer | Uint8Array | string | null;
wantReply?: boolean;
ackTimeoutMs?: number;
replyTimeoutMs?: number;
}>,
{
concurrency = 64,
wantReply = true,
ackTimeoutMs = this.defaultAckTimeoutMs,
replyTimeoutMs = this.defaultReplyTimeoutMs,
}: QqHookSendOptions & { concurrency?: number } = {}): Promise<Array<QqHookSendReply | { requestId: number }>> {
}: QqHookSendOptions & { concurrency?: number } = {},
): Promise<Array<QqHookSendReply | { requestId: number }>> {
const results = new Array<QqHookSendReply | { requestId: number }>(items.length);
let nextIndex = 0;
const workerCount = Math.max(1, Math.min(concurrency | 0, items.length || 1));
@@ -727,7 +885,11 @@ export class QqHookClient extends EventEmitter {
for (;;) {
const index = nextIndex;
nextIndex += 1;
if (index >= items.length) return;
if (index >= items.length) {
return;
}
const item = items[index];
const itemWantReply = item.wantReply ?? wantReply;
results[index] = await this.send(item.cmd, item.body, {
@@ -742,19 +904,28 @@ export class QqHookClient extends EventEmitter {
return results;
}
waitForPacket(predicate: (packet: QqHookPacket) => boolean = () => true, { timeoutMs = 0 } = {}): Promise<QqHookPacket> {
waitForPacket(
predicate: (packet: QqHookPacket) => boolean = () => true,
{ timeoutMs = 0 } = {},
): Promise<QqHookPacket> {
return new Promise((resolve, reject) => {
let timer: NodeJS.Timeout | null = null;
const cleanup = () => {
this.off('packet', onPacket);
if (timer) {
clearTimeout(timer);
timer = null;
}
};
const onPacket = (packet: QqHookPacket) => {
try {
if (!predicate(packet)) return;
if (!predicate(packet)) {
return;
}
cleanup();
resolve(packet);
} catch (error) {
@@ -762,7 +933,9 @@ export class QqHookClient extends EventEmitter {
reject(error);
}
};
this.on('packet', onPacket);
if (timeoutMs > 0) {
timer = setTimeout(() => {
cleanup();
@@ -773,7 +946,10 @@ export class QqHookClient extends EventEmitter {
}
close(): void {
if (this.closed) return;
if (this.closed) {
return;
}
this.closed = true;
this.rejectControlPending(new Error('qq_hook client closed'));
this.rejectRecvPending(new Error('qq_hook client closed'));
@@ -783,10 +959,12 @@ export class QqHookClient extends EventEmitter {
this.controlSocket.destroy();
this.controlSocket = null;
}
if (this.recvSocket) {
this.recvSocket.destroy();
this.recvSocket = null;
}
this.controlHello = null;
this.recvHello = null;
this.controlWriteChain = Promise.resolve();
@@ -795,18 +973,24 @@ export class QqHookClient extends EventEmitter {
private rejectLoginWaiters(error: Error): void {
const waiters = this.loginWaiters;
this.loginWaiters = [];
for (const waiter of waiters) waiter.reject(error);
for (const waiter of waiters) {
waiter.reject(error);
}
}
private rejectControlPending(error: Error): void {
for (const pending of this.pendingAcks.values()) {
pending.reject(error);
}
for (const pending of this.pendingReplies.values()) {
pending.reject(error);
}
this.pendingAcks.clear();
this.pendingReplies.clear();
if (this.controlHelloResolver) {
this.controlHelloResolver.reject(error);
this.controlHelloResolver = null;
@@ -822,19 +1006,28 @@ export class QqHookClient extends EventEmitter {
private writeControl(payload: Buffer): Promise<void> {
const socket = this.controlSocket;
if (!socket || socket.destroyed) {
return Promise.reject(new Error('control pipe is not connected'));
}
const writePromise = this.controlWriteChain.then(() => new Promise<void>((resolve, reject) => {
const writePromise = this.controlWriteChain.then(
() =>
new Promise<void>((resolve, reject) => {
if (!this.controlSocket || this.controlSocket.destroyed) {
reject(new Error('control pipe is not connected'));
return;
}
socket.write(payload, error => {
if (error) reject(error);
else resolve();
socket.write(payload, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
}));
}),
);
this.controlWriteChain = writePromise.catch(() => {});
return writePromise;
}
@@ -843,12 +1036,21 @@ export class QqHookClient extends EventEmitter {
// 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;
if (requestId === 0) {
requestId = 1;
}
}
this.nextRequestId = (requestId + 1) >>> 0;
if (this.nextRequestId === 0) this.nextRequestId = 1;
if (this.nextRequestId === 0) {
this.nextRequestId = 1;
}
return requestId;
}
@@ -856,12 +1058,15 @@ export class QqHookClient extends EventEmitter {
await this.connect();
const requestId = this.allocateRequestId();
const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>();
ackDeferred.promise.catch(() => { /* observed by the await below */ });
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(
@@ -879,7 +1084,8 @@ export class QqHookClient extends EventEmitter {
private async connectPipe(kind: 'control' | 'recv'): Promise<QqHookHello> {
return runWithTraceRequest(async () => {
const startedAt = Date.now();
const pipeName = kind === 'control'
const pipeName =
kind === 'control'
? QqHookClient.controlPipeName(this.pid, this.runtimeDir)
: QqHookClient.recvPipeName(this.pid, this.runtimeDir);
let phase: 'connect' | 'hello' = 'connect';
@@ -889,16 +1095,24 @@ export class QqHookClient extends EventEmitter {
kind,
pipeName,
);
try {
const socket = await runWithoutRequestContext(() => this.connectSocket(
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;
? (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,
@@ -906,8 +1120,13 @@ export class QqHookClient extends EventEmitter {
);
phase = 'hello';
const hello = await this.waitForHello(kind === 'recv');
if (kind === 'control') this.controlHello = hello;
else this.recvHello = hello;
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,
@@ -930,7 +1149,11 @@ export class QqHookClient extends EventEmitter {
});
}
private connectSocket(pipeName: string, kind: 'control' | 'recv', onFrame: (frame: PipeFrame) => void): Promise<net.Socket> {
private connectSocket(
pipeName: string,
kind: 'control' | 'recv',
onFrame: (frame: PipeFrame) => void,
): Promise<net.Socket> {
return new Promise((resolve, reject) => {
const socket = net.createConnection(pipeName);
const reader = new FrameReader(onFrame);
@@ -938,7 +1161,7 @@ export class QqHookClient extends EventEmitter {
socket.once('error', onInitialError);
socket.once('connect', () => {
socket.off('error', onInitialError);
socket.on('data', chunk => {
socket.on('data', (chunk) => {
try {
reader.push(chunk);
} catch (error) {
@@ -946,7 +1169,7 @@ export class QqHookClient extends EventEmitter {
socket.destroy();
}
});
socket.on('error', error => {
socket.on('error', (error) => {
this.emit('error', error);
});
socket.on('close', () => {
@@ -962,19 +1185,29 @@ export class QqHookClient extends EventEmitter {
private waitForHello(recvPipe: boolean): Promise<QqHookHello> {
const deferred = createDeferred<QqHookHello>();
if (recvPipe) {
this.recvHelloResolver = deferred;
} else {
this.controlHelloResolver = deferred;
}
return deferred.promise;
}
private resolveHello(frame: PipeFrame, recvPipe: boolean): void {
const resolver = recvPipe ? this.recvHelloResolver : this.controlHelloResolver;
if (!resolver) return;
if (recvPipe) this.recvHelloResolver = null;
else this.controlHelloResolver = null;
if (!resolver) {
return;
}
if (recvPipe) {
this.recvHelloResolver = null;
} else {
this.controlHelloResolver = null;
}
resolver.resolve({
pipeName: frame.msg,
pid: Number(frame.value0),
@@ -990,12 +1223,14 @@ export class QqHookClient extends EventEmitter {
this.loginState.loggedIn,
this.loginState.uin,
);
if (kind === 'control') {
this.controlSocket = null;
this.controlHello = null;
this.rejectControlPending(new Error('control pipe closed'));
return;
}
this.recvSocket = null;
this.recvHello = null;
this.rejectRecvPending(new Error('recv pipe closed'));
@@ -1013,10 +1248,12 @@ export class QqHookClient extends EventEmitter {
private applyLoginState(next: QqHookLoginState): void {
const previous = this.loginState;
this.loginState = next;
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',
@@ -1027,10 +1264,14 @@ export class QqHookClient extends EventEmitter {
next.uin,
);
this.emit('loginState', next);
if (next.loggedIn) {
const waiters = this.loginWaiters;
this.loginWaiters = [];
for (const waiter of waiters) waiter.resolve({ ...next });
for (const waiter of waiters) {
waiter.resolve({ ...next });
}
}
});
}
@@ -1040,20 +1281,31 @@ export class QqHookClient extends EventEmitter {
this.resolveHello(frame, false);
return;
}
if (frame.op === PipeOp.loginState) {
this.applyLoginStateFrame(frame);
return;
}
if (frame.op === PipeOp.sendAck) {
const pending = this.pendingAcks.get(frame.requestId);
if (!pending) return;
if (!pending) {
return;
}
this.pendingAcks.delete(frame.requestId);
pending.resolve({ requestId: frame.requestId, wantReply: pending.wantReply });
return;
}
if (frame.op === PipeOp.sendReply) {
const pending = this.pendingReplies.get(frame.requestId);
if (!pending) return;
if (!pending) {
return;
}
this.pendingReplies.delete(frame.requestId);
pending.resolve({
requestId: frame.requestId,
@@ -1063,14 +1315,22 @@ export class QqHookClient extends EventEmitter {
});
return;
}
if (frame.op === PipeOp.error) {
const error = new HookPipeRequestError(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);
ack.reject(error);
}
const reply = this.pendingReplies.get(frame.requestId);
if (reply) {
this.pendingReplies.delete(frame.requestId);
reply.reject(error);
@@ -1083,11 +1343,16 @@ export class QqHookClient extends EventEmitter {
this.resolveHello(frame, true);
return;
}
if (frame.op === PipeOp.loginState) {
this.applyLoginStateFrame(frame);
return;
}
if (frame.op !== PipeOp.recvPacket) return;
if (frame.op !== PipeOp.recvPacket) {
return;
}
this.emit('packet', {
seq: Number(frame.value0),
error: frame.status,
+87 -22
View File
@@ -6,6 +6,19 @@ import { promisify } from 'util';
const execAsync = promisify(exec);
const log = createLogger('LoginProbe');
const probeNotes = new Map<number, string>();
function noteProbe(pid: number, result: string, ports: number, processes: number | null): void {
const processText = processes === null ? '' : ` processes=${processes}`;
const message = `login probe: PID=${pid} result=${result} ports=${ports}${processText}`;
if (probeNotes.get(pid) === message) {
return;
}
probeNotes.set(pid, message);
log.info(message);
}
const CONNECTION_TIMEOUT_MS = 500;
const COMMAND_TIMEOUT_MS = 1500;
@@ -15,8 +28,7 @@ const EXEC_OPTIONS = { timeout: COMMAND_TIMEOUT_MS, killSignal: 'SIGKILL' as con
// 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
// the login screen; AT/ABOVE it the environment is ambiguous (multiple or
// unrelated `qq` processes), so we fall through to deep-link probing rather
// than guess "logged out".
// unrelated `qq` processes), so the passive probe returns no conclusion.
const LOGGED_OUT_PROCESS_COUNT_MAX = 6;
export interface QqPortLoginInfo {
@@ -43,7 +55,7 @@ interface PtloginUin {
* the port could not be reached / the body was not a usable pt_get_uins
* response (connect refused, timeout, unparseable). Callers MUST distinguish
* the two: `[]` feeds the logged-in/out decision, `null` means "network
* problem, no answer" and should fall through to the deep-link fallback.
* problem, no answer". Neither outcome triggers interactive probing.
*/
async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin[] | null> {
return new Promise((resolve) => {
@@ -58,7 +70,9 @@ async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin
const handleResponse = (res: http.IncomingMessage) => {
let text = '';
res.on('data', (chunk) => { text += chunk.toString(); });
res.on('data', (chunk) => {
text += chunk.toString();
});
res.on('end', () => {
try {
const inner = text.split('[')[1].split(']')[0];
@@ -71,7 +85,11 @@ async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin
};
const req = useHttps
? https.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS, rejectUnauthorized: false }, handleResponse)
? https.get(
url,
{ headers, timeout: CONNECTION_TIMEOUT_MS, rejectUnauthorized: false },
handleResponse,
)
: http.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS }, handleResponse);
req.on('error', () => resolve(null));
@@ -82,13 +100,15 @@ async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin
});
}
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallback'> {
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | null> {
const useHttps = port % 2 !== 0;
const res1 = await fetchPtlogin(port, useHttps);
const res2 = await fetchPtlogin(port, useHttps);
if (res1 === null && res2 === null) return 'fallback';
if (res1 === null && res2 === null) {
return null;
}
const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null);
const target = usable.reduce((a, b) => (a.length <= b.length ? a : b));
@@ -103,10 +123,9 @@ async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallba
};
}
return 'fallback';
return null;
}
async function getQqProcessCount(): Promise<number> {
try {
if (process.platform === 'win32') {
@@ -114,7 +133,10 @@ async function getQqProcessCount(): Promise<number> {
'tasklist /fi "imagename eq QQ.exe" /nh',
EXEC_OPTIONS,
);
return stdout.toLowerCase().split('\n').filter(line => line.includes('qq.exe')).length;
return stdout
.toLowerCase()
.split('\n')
.filter((line) => line.includes('qq.exe')).length;
} else {
const { stdout } = await execAsync('pgrep -c qq', EXEC_OPTIONS);
return parseInt(stdout.trim(), 10) || 0;
@@ -132,29 +154,48 @@ async function getProcessPorts(pid: number): Promise<number[] | null> {
const { stdout } = await execAsync('netstat -ano', EXEC_OPTIONS);
const ports = new Set<number>();
const lines = stdout.split('\n');
for (const line of lines) {
const parts = line.trim().split(/\s+/);
if (parts.length < 5) continue;
if (parts.length < 5) {
continue;
}
const owningPid = parts[parts.length - 1];
if (owningPid !== String(pid)) continue;
if (owningPid !== String(pid)) {
continue;
}
const localAddr = parts[1];
const portMatch = localAddr.match(/:(\d+)$/);
if (!portMatch) continue;
if (!portMatch) {
continue;
}
ports.add(Number(portMatch[1]));
}
return Array.from(ports);
} else {
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;
if (!line.includes(`pid=${pid},`) && !line.includes(`pid=${pid})`)) {
continue;
}
const match = line.match(/:(\d+)\s/);
if (match) {
ports.add(Number(match[1]));
}
}
return Array.from(ports);
}
} catch {
@@ -164,22 +205,32 @@ async function getProcessPorts(pid: number): Promise<number[] | null> {
async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo | null> {
const ports = await getProcessPorts(pid);
if (ports === null) return null;
if (ports === null) {
noteProbe(pid, 'unavailable', 0, null);
return null;
}
if (ports.length === 0) {
const totalPids = await getQqProcessCount();
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
noteProbe(pid, 'no-ports', 0, totalPids);
return { port: 0, uin: '', identityKnown: false };
}
noteProbe(pid, 'inconclusive', 0, totalPids);
return null;
}
const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309];
const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310];
const matchedOddPorts = ports.filter(p => ODD_PT_PORTS.includes(p));
const matchedEvenPorts = ports.filter(p => EVEN_PT_PORTS.includes(p));
const matchedOddPorts = ports.filter((p) => ODD_PT_PORTS.includes(p));
const matchedEvenPorts = ports.filter((p) => EVEN_PT_PORTS.includes(p));
let ptPortsToTry: number[] = [];
if (matchedOddPorts.length > 0) {
ptPortsToTry = matchedOddPorts;
} else if (matchedEvenPorts.length > 0) {
@@ -189,40 +240,54 @@ async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo |
if (ptPortsToTry.length > 0) {
for (const port of ptPortsToTry) {
const ptResult = await tryPtloginMethod(port);
if (ptResult !== 'fallback') {
if (ptResult !== null) {
return ptResult;
}
}
} else {
const totalPids = await getQqProcessCount();
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
noteProbe(pid, 'no-ports', ports.length, totalPids);
return {
port: ports[0] || 0,
port: ports[0],
uin: '',
identityKnown: false,
};
}
noteProbe(pid, 'inconclusive', ports.length, totalPids);
return null;
}
// Background discovery must remain passive. Interactive application
// endpoints are deliberately excluded from automatic probing.
noteProbe(pid, 'no-match', ptPortsToTry.length, null);
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 => {
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);
if (timedOut) {
log.warn('login check timed out: PID=%d', pid);
}
return result;
} finally {
if (timer) clearTimeout(timer);
if (timer) {
clearTimeout(timer);
}
}
}
+123
View File
@@ -0,0 +1,123 @@
import { getNativeHookAddon, getNativeHookLoadError } from './injector';
export interface IntegrityReadError {
status: 'error';
operation: string;
code: number;
}
export interface NativeRuntimeIntegrity {
pid: number;
executablePath: string | null;
process: { status: 'ok'; rid: number } | IntegrityReadError;
file:
| {
status: 'ok';
label: { rid: number; inherited: boolean; policy: number } | null;
}
| IntegrityReadError;
}
export type RuntimeIntegrity =
| { status: 'unsupported' }
| { status: 'unavailable'; error: string }
| ({ status: 'available' } & NativeRuntimeIntegrity);
/** File labels can change after startup; only the actual token decides the warning. */
export function hasLowProcessIntegrity(integrity: RuntimeIntegrity): boolean {
return (
integrity.status === 'available' &&
integrity.process.status === 'ok' &&
integrity.process.rid < 8192
);
}
function record(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function uint32(value: unknown): value is number {
return (
typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 0xffff_ffff
);
}
function readError(value: Record<string, unknown>): boolean {
return value.status === 'error' && typeof value.operation === 'string' && uint32(value.code);
}
function isNativeRuntimeIntegrity(value: unknown): value is NativeRuntimeIntegrity {
if (
!record(value) ||
value.pid !== process.pid ||
!(typeof value.executablePath === 'string' || value.executablePath === null) ||
!record(value.process) ||
!record(value.file)
) {
return false;
}
if (!(
readError(value.process) ||
(value.process.status === 'ok' && uint32(value.process.rid))
)) {
return false;
}
const file = value.file;
return (
readError(file) ||
(file.status === 'ok' &&
(file.label === null ||
(record(file.label) &&
uint32(file.label.rid) &&
typeof file.label.inherited === 'boolean' &&
uint32(file.label.policy))))
);
}
let cached: RuntimeIntegrity | undefined;
/** One startup snapshot, shared by the startup log and the WebUI warning. */
export function getRuntimeIntegrity(): RuntimeIntegrity {
if (process.platform !== 'win32') {
return { status: 'unsupported' };
}
if (cached) {
return cached;
}
try {
const addon = getNativeHookAddon();
if (!addon) {
throw new Error(getNativeHookLoadError() ?? '原生组件不可用');
}
if (typeof addon.getRuntimeIntegrity !== 'function') {
throw new Error('当前原生组件不支持完整性诊断,请更新原生组件');
}
const result = addon.getRuntimeIntegrity();
if (!isNativeRuntimeIntegrity(result)) {
throw new Error('原生完整性诊断返回了无效数据');
}
cached = {
status: 'available',
pid: result.pid,
executablePath: result.executablePath,
process: result.process,
file: result.file,
};
} catch (error) {
cached = {
status: 'unavailable',
error: error instanceof Error ? error.message : String(error),
};
}
return cached;
}
+1 -7
View File
@@ -1,13 +1,7 @@
import type { HookProcessBaseInfo } from './injector';
export type HookProcessStatus =
| 'available'
| 'loading'
| 'connecting'
| 'loaded'
| 'online'
| 'error'
| 'disconnected';
'available' | 'loading' | 'connecting' | 'loaded' | 'online' | 'error' | 'disconnected';
/** Public-facing snapshot of a per-PID HookSession. */
export interface HookProcessInfo extends HookProcessBaseInfo {
@@ -13,7 +13,7 @@ import type { QqHookClient } from '../src/qq-hook-client';
// browser without REST polling.
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
const flush = () => new Promise<void>(r => setImmediate(r));
const flush = () => new Promise<void>((r) => setImmediate(r));
interface Harness {
manager: HookManager;
@@ -29,7 +29,7 @@ function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}):
let pids = opts.processes ?? [];
let live = new Set<number>(opts.livePipes ?? []);
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
});
@@ -38,8 +38,15 @@ function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}):
(c as any).isClosed = false;
(c as any).isLoggedIn = false;
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
(c as any).connectAll = async () => { /* succeed without doing anything */ };
(c as any).close = () => { (c as any).isClosed = true; };
(c as any).connectAll = async () => {
/* succeed without doing anything */
};
(c as any).close = () => {
(c as any).isClosed = true;
};
return c as unknown as QqHookClient;
});
const bridgeManager = {
@@ -57,7 +64,7 @@ function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}):
unload: vi.fn(),
},
makeClient: clientFactory,
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
onSessionsChanged,
});
return {
@@ -66,8 +73,12 @@ function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}):
bridgeManager,
onSessionsChanged,
clientFactory,
setProcesses: (next) => { pids = next; },
setLivePipes: (next) => { live = new Set(next); },
setProcesses: (next) => {
pids = next;
},
setLivePipes: (next) => {
live = new Set(next);
},
};
}
@@ -120,7 +131,9 @@ describe('HookManager.onSessionsChanged', () => {
it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => {
const ctx = makeManager({ processes: [] });
ctx.onSessionsChanged.mockImplementation(() => { throw new Error('listener boom'); });
ctx.onSessionsChanged.mockImplementation(() => {
throw new Error('listener boom');
});
await ctx.pipeWatcher.start();
ctx.setProcesses([4242]);
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
@@ -139,7 +152,7 @@ describe('HookManager.onSessionsChanged', () => {
it('is OPTIONAL — omitting it leaves the manager fully functional', async () => {
const pids = [4242];
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(),
intervalMs: 60_000,
});
@@ -151,18 +164,26 @@ describe('HookManager.onSessionsChanged', () => {
} as unknown as BridgeManagerSink,
pipeWatcher,
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
inject: vi.fn(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(),
},
makeClient: vi.fn(() => {
const c = new EventEmitter() as any;
c.isClosed = false; c.isLoggedIn = false;
c.isClosed = false;
c.isLoggedIn = false;
c.getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
c.connectAll = async () => undefined;
c.close = () => { c.isClosed = true; };
c.close = () => {
c.isClosed = true;
};
return c;
}),
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
// onSessionsChanged deliberately omitted
});
await pipeWatcher.start();
@@ -187,6 +208,7 @@ describe('HookManager receive-health wiring (#233)', () => {
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
try {
client.emit('packet', {
seq: 1,
@@ -206,7 +228,10 @@ describe('HookManager receive-health wiring (#233)', () => {
uin: '10001',
body: Buffer.alloc(0),
});
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenLastCalledWith(4242, true);
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenLastCalledWith(
4242,
true,
);
} finally {
vi.useRealTimers();
ctx.manager.dispose();
+74 -31
View File
@@ -17,13 +17,11 @@ import {
} 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 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',
);
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Hook');
}
function makeManager(opts: {
@@ -34,13 +32,16 @@ function makeManager(opts: {
}) {
let pids = opts.processes ?? [];
const live = new Set<number>();
const inject = vi.fn(opts.inject ?? (() => ({
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: '' })),
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live),
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
});
@@ -51,8 +52,15 @@ function makeManager(opts: {
(c as any).isClosed = false;
(c as any).isLoggedIn = false;
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
(c as any).connectAll = async () => { throw new Error('test: never really connect'); };
(c as any).close = () => { (c as any).isClosed = true; };
(c as any).connectAll = async () => {
throw new Error('test: never really connect');
};
(c as any).close = () => {
(c as any).isClosed = true;
};
return c as unknown as QqHookClient;
});
const bridgeManager = {
@@ -67,13 +75,15 @@ function makeManager(opts: {
makeClient,
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
onSessionsChanged: opts.onSessionsChanged,
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
});
return {
manager,
inject,
pipeWatcher,
setProcesses: (next: number[]) => { pids = next; },
setProcesses: (next: number[]) => {
pids = next;
},
};
}
@@ -92,6 +102,7 @@ describe('HookManager runtime TRACE', () => {
processes: [],
onSessionsChanged: sessionsChanged,
});
try {
await ctx.pipeWatcher.start();
const baseline = managerTrace(entries).length;
@@ -105,8 +116,8 @@ describe('HookManager runtime TRACE', () => {
await ctx.pipeWatcher.tickNow();
await flush();
const facts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_manager_fact '),
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'),
@@ -134,6 +145,7 @@ describe('HookManager runtime TRACE', () => {
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
}));
try {
await ctx.pipeWatcher.start();
await flush();
@@ -142,14 +154,18 @@ describe('HookManager runtime TRACE', () => {
await flush();
await flush();
const attempts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_'),
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+$/),
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.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);
@@ -173,6 +189,7 @@ describe('HookManager runtime TRACE', () => {
processes: [4242],
inject: () => injection,
});
try {
await ctx.pipeWatcher.start();
await flush();
@@ -181,8 +198,8 @@ describe('HookManager runtime TRACE', () => {
await manualLoad;
await flush();
const attempts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_'),
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',
@@ -217,22 +234,26 @@ describe('HookManager runtime TRACE', () => {
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementation(() => { throw new Error(error); });
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 starts = managerTrace(entries).filter((entry) =>
entry.message.startsWith('hook_autoload_start '),
);
const terminals = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_terminal '),
const terminals = managerTrace(entries).filter((entry) =>
entry.message.startsWith('hook_autoload_terminal '),
);
expect(starts).toHaveLength(attempts);
expect(terminals).toHaveLength(attempts);
@@ -276,7 +297,9 @@ describe('HookManager.autoLoadOnDiscovery', () => {
it('swallows inject errors so the watcher keeps running', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementationOnce(() => { throw new Error('ptrace denied'); });
ctx.inject.mockImplementationOnce(() => {
throw new Error('ptrace denied');
});
await ctx.pipeWatcher.start();
await flush();
await flush();
@@ -316,7 +339,9 @@ describe('HookManager.autoLoadOnDiscovery', () => {
it('does not retry permanent auto-load errors', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementation(() => { throw new Error('ptrace denied'); });
ctx.inject.mockImplementation(() => {
throw new Error('ptrace denied');
});
await ctx.pipeWatcher.start();
await flush();
@@ -347,6 +372,7 @@ describe('HookManager.autoLoadOnDiscovery', () => {
await flush();
await flush();
}
expect(ctx.inject).toHaveBeenCalledTimes(3);
ctx.manager.dispose();
@@ -368,11 +394,19 @@ describe('shouldAutoLoadPid', () => {
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
// Redirect readFileSync('/proc/<pid>/cmdline') to the tmp dir.
(fs.readFileSync as unknown as typeof fs.readFileSync) = ((p: string, ...rest: unknown[]) => {
(fs.readFileSync as unknown as typeof fs.readFileSync) = ((
p: string,
...rest: unknown[]
) => {
const match = /^\/proc\/(\d+)\/cmdline$/.exec(p);
if (match) {
return originalReadFileSync(path.join(tmpProc, match[1], 'cmdline'), ...(rest as [BufferEncoding]));
return originalReadFileSync(
path.join(tmpProc, match[1], 'cmdline'),
...(rest as [BufferEncoding]),
);
}
return originalReadFileSync(p, ...(rest as [BufferEncoding]));
}) as typeof fs.readFileSync;
});
@@ -380,8 +414,13 @@ describe('shouldAutoLoadPid', () => {
afterEach(() => {
(fs.readFileSync as unknown as typeof fs.readFileSync) = originalReadFileSync;
Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
if (originalAutoLoadAll === undefined) delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
else process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll;
if (originalAutoLoadAll === undefined) {
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
} else {
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll;
}
fs.rmSync(tmpProc, { recursive: true, force: true });
});
@@ -404,7 +443,11 @@ describe('shouldAutoLoadPid', () => {
it('rejects renderer/gpu/utility children', () => {
writeCmdline(70, ['/opt/QQ/qq', '--type=renderer']);
writeCmdline(71, ['/opt/QQ/qq', '--type=gpu-process']);
writeCmdline(72, ['/opt/QQ/qq', '--type=utility', '--utility-sub-type=network.mojom.NetworkService']);
writeCmdline(72, [
'/opt/QQ/qq',
'--type=utility',
'--utility-sub-type=network.mojom.NetworkService',
]);
expect(shouldAutoLoadPid(70, log)).toBe(false);
expect(shouldAutoLoadPid(71, log)).toBe(false);
expect(shouldAutoLoadPid(72, log)).toBe(false);
@@ -0,0 +1,70 @@
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();
});
});
@@ -13,17 +13,24 @@ import type { BridgeManagerSink } from '../src/hook-manager';
import type { QqHookClient } from '../src/qq-hook-client';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
const flush = () => new Promise<void>(r => setImmediate(r));
const flush = () => new Promise<void>((r) => setImmediate(r));
class FakeClient extends EventEmitter {
isClosed = false;
isLoggedIn = false;
async connectAll(_opts: { recv: boolean }) {
if (this.isClosed) throw new Error('client is closed');
if (this.isClosed) {
throw new Error('client is closed');
}
}
getLoginState() {
return { loggedIn: false, uin: '0', uinNumber: 0n };
}
getLoginState() { return { loggedIn: false, uin: '0', uinNumber: 0n }; }
close() {
if (this.isClosed) return;
if (this.isClosed) {
return;
}
this.isClosed = true;
this.emit('close');
}
@@ -51,7 +58,10 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
bridgeManager,
pipeWatcher,
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
inject: vi.fn(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(),
},
makeClient: () => {
@@ -71,6 +81,7 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
// Drive 50 pipe up/down cycles with the QQ process staying alive but
// the pipe (= QQ control socket) bouncing every "tick".
const CYCLES = 50;
for (let i = 0; i < CYCLES; i++) {
liveSet.delete(PID);
await pipeWatcher.tickNow();
@@ -87,8 +98,11 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
// Hook layer should hold at most one live client.
const alive = clients.filter(c => !c.isClosed);
expect(alive.length, `live clients after ${CYCLES} cycles: ${alive.length}`).toBeLessThanOrEqual(1);
const alive = clients.filter((c) => !c.isClosed);
expect(
alive.length,
`live clients after ${CYCLES} cycles: ${alive.length}`,
).toBeLessThanOrEqual(1);
// Total clients minted = roughly one per up cycle. Sanity bound:
// we must have actually exercised the reconnect path.
@@ -29,11 +29,18 @@ class FakeClient extends EventEmitter {
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
async connectAll(_opts: { recv: boolean }): Promise<void> {
if (this.isClosed) throw new Error('client is closed');
if (this.isClosed) {
throw new Error('client is closed');
}
}
getLoginState() {
return { ...this.loginState };
}
getLoginState() { return { ...this.loginState }; }
close(): void {
if (this.isClosed) return;
if (this.isClosed) {
return;
}
this.isClosed = true;
this.emit('close');
}
@@ -43,7 +50,7 @@ function totalListenerCount(emitter: EventEmitter): number {
return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0);
}
const flush = () => new Promise<void>(r => setImmediate(r));
const flush = () => new Promise<void>((r) => setImmediate(r));
describe('HookSession — pipe reconnect with QQ never logging in', () => {
it('does not accumulate live FakeClient instances across N pipe up/down cycles', async () => {
@@ -51,7 +58,10 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
const clients: FakeClient[] = [];
const session = new HookSession(61, {
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
inject: vi.fn(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(),
},
makeClient: () => {
@@ -67,6 +77,7 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
await flush();
const CYCLES = 50;
for (let i = 0; i < CYCLES; i++) {
pipeLive = false;
session.onPipeDown();
@@ -76,10 +87,12 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
await flush();
}
const alive = clients.filter(c => !c.isClosed);
const alive = clients.filter((c) => !c.isClosed);
expect.soft(clients.length).toBeGreaterThan(1);
expect(alive.length, `expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`)
.toBeLessThanOrEqual(1);
expect(
alive.length,
`expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`,
).toBeLessThanOrEqual(1);
});
it('drops all listeners from each torn-down client', async () => {
@@ -87,7 +100,10 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
const clients: FakeClient[] = [];
const session = new HookSession(61, {
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
inject: vi.fn(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(),
},
makeClient: () => {
@@ -103,6 +119,7 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
await flush();
const CYCLES = 20;
for (let i = 0; i < CYCLES; i++) {
pipeLive = false;
session.onPipeDown();
@@ -116,8 +133,10 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
// (HookSession.tearDownClient does client.removeAllListeners().)
for (let i = 0; i < clients.length - 1; i++) {
const lc = totalListenerCount(clients[i]);
expect(lc, `client #${i} of ${clients.length} still has ${lc} listeners after teardown`)
.toBe(0);
expect(
lc,
`client #${i} of ${clients.length} still has ${lc} listeners after teardown`,
).toBe(0);
}
});
});
+31 -13
View File
@@ -4,14 +4,19 @@ 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}`);
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, {
expect(
resolveHookRuntimeDir(46301, {
platform: 'linux',
env: { XDG_RUNTIME_DIR: '/run/user/0' },
ownUid: 0,
@@ -19,11 +24,13 @@ describe('resolveHookRuntimeDir — Linux target process ownership', () => {
'/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');
}),
).toBe('/run/user/1000');
});
it('falls back to the QQ process uid when its environment has no runtime directory', () => {
expect(resolveHookRuntimeDir(46301, {
expect(
resolveHookRuntimeDir(46301, {
platform: 'linux',
env: { XDG_RUNTIME_DIR: '/run/user/0' },
ownUid: 0,
@@ -31,30 +38,40 @@ describe('resolveHookRuntimeDir — Linux target process ownership', () => {
'/proc/46301/environ': 'HOME=/home/rikka\0',
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
}),
})).toBe('/tmp/snowluma-1000');
}),
).toBe('/tmp/snowluma-1000');
});
it('fails visibly when target ownership cannot be determined', () => {
expect(() => resolveHookRuntimeDir(46301, {
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/);
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, {
expect(
resolveHookRuntimeDir(46301, {
platform: 'linux',
env: { XDG_RUNTIME_DIR: '/run/user/0' },
ownUid: 0,
readText: () => { throw gone; },
})).toBe('/run/user/0');
readText: () => {
throw gone;
},
}),
).toBe('/run/user/0');
});
it('honours an explicit runtime directory inherited by the QQ process', () => {
expect(resolveHookRuntimeDir(46301, {
expect(
resolveHookRuntimeDir(46301, {
platform: 'linux',
env: {},
ownUid: 0,
@@ -62,6 +79,7 @@ describe('resolveHookRuntimeDir — Linux target process ownership', () => {
'/proc/46301/environ': 'SNOWLUMA_HOOK_RUNTIME_DIR=/srv/snowluma-hook\0',
'/proc/46301/status': 'Uid:\t1000\t1000\t1000\t1000\n',
}),
})).toBe('/srv/snowluma-hook');
}),
).toBe('/srv/snowluma-hook');
});
});
+306 -80
View File
@@ -2,23 +2,21 @@ 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';
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',
);
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'HookSession');
}
afterEach(() => {
@@ -35,15 +33,23 @@ class FakeClient extends EventEmitter {
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> {
if (this.shouldFailConnect) throw new Error('connect failed');
if (this.isClosed) throw new Error('client is closed');
if (this.shouldFailConnect) {
throw new Error('connect failed');
}
if (this.isClosed) {
throw new Error('client is closed');
}
}
getLoginState() {
return { ...this.loginState };
}
getLoginState() { return { ...this.loginState }; }
reconcileLoginState(state: { loggedIn: boolean; uin: string; uinNumber: bigint }): void {
this.isLoggedIn = state.loggedIn;
this.loginState = { ...state };
@@ -51,13 +57,21 @@ class FakeClient extends EventEmitter {
}
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);
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,
@@ -67,7 +81,10 @@ class FakeClient extends EventEmitter {
};
}
close(): void {
if (this.isClosed) return;
if (this.isClosed) {
return;
}
this.isClosed = true;
this.emit('close');
}
@@ -81,7 +98,8 @@ class FakeClient extends EventEmitter {
}
}
function makeSession(opts: {
function makeSession(
opts: {
pid?: number;
pipeLive?: boolean;
clientFailsConnect?: boolean;
@@ -89,7 +107,8 @@ function makeSession(opts: {
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
nativeReadyOnIdentityHint?: boolean;
identityHintFailures?: number;
} = {}) {
} = {},
) {
const pid = opts.pid ?? 1234;
let pipeLive = opts.pipeLive ?? false;
const clients: FakeClient[] = [];
@@ -99,13 +118,18 @@ function makeSession(opts: {
};
// 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 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;
if (opts.clientFailsConnect) {
c.shouldFailConnect = true;
}
c.nativeReadyOnIdentityHint = opts.nativeReadyOnIdentityHint ?? false;
c.identityHintFailures = opts.identityHintFailures ?? 0;
clients.push(c);
@@ -122,17 +146,20 @@ function makeSession(opts: {
injector,
clients,
currentClient: () => clients[clients.length - 1]!,
setPipeLive: (v: boolean) => { pipeLive = v; },
setPipeLive: (v: boolean) => {
pipeLive = v;
},
};
}
const flush = () => new Promise<void>(r => setImmediate(r));
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 });
@@ -140,19 +167,28 @@ describe('HookSession — runtime TRACE', () => {
await reconnect.session.load();
const messages = sessionTrace(entries).map((entry) => entry.message);
expect(messages).toEqual(expect.arrayContaining([
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.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+$/),
]));
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);
expect(
messages.filter((message) =>
message.startsWith(`hook_session_terminal pid=${pid} operation=load `),
),
).toHaveLength(1);
}
} finally {
unsubscribe();
@@ -163,9 +199,12 @@ describe('HookSession — runtime TRACE', () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const injector = {
inject: vi.fn(() => { throw new Error('fixture inject failure'); }),
inject: vi.fn(() => {
throw new Error('fixture inject failure');
}),
unload: vi.fn(),
};
const failedLoad = new HookSession(7103, {
@@ -185,24 +224,62 @@ describe('HookSession — runtime TRACE', () => {
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(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);
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('connects when load fails but the pipe is already up', async () => {
let pipeLive = false;
const clients: FakeClient[] = [];
const session = new HookSession(7108, {
injector: {
inject: () => {
pipeLive = true;
throw new Error('component loading failed [COMPONENT_LOAD_FAILED]');
},
unload: () => undefined,
},
makeClient: () => {
const client = new FakeClient();
client.fireLogin('10001');
clients.push(client);
return client as unknown as QqHookClient;
},
pipeWatcher: {
isPipeLive: () => pipeLive,
tickNow: async () => undefined,
},
});
const info = await session.load();
expect(info.status).toBe('online');
expect(info.uin).toBe('10001');
expect(info.connected).toBe(true);
expect(clients).toHaveLength(1);
});
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();
@@ -217,20 +294,34 @@ describe('HookSession — runtime TRACE', () => {
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+$/),
]));
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();
@@ -244,37 +335,59 @@ describe('HookSession — runtime TRACE', () => {
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'); });
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.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.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_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_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+$/),
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();
@@ -289,13 +402,14 @@ describe('HookSession — runtime TRACE', () => {
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 '),
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(
@@ -329,10 +443,15 @@ describe('HookSession — load', () => {
});
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 => {
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(),
@@ -357,7 +476,9 @@ describe('HookSession — load', () => {
it('inject failure → status error, error message captured', async () => {
const injector = {
inject: vi.fn(() => { throw new Error('inject boom'); }),
inject: vi.fn(() => {
throw new Error('inject boom');
}),
unload: vi.fn(),
};
const session = new HookSession(1234, {
@@ -553,11 +674,16 @@ describe('HookSession — unload', () => {
// the snapshot first and verification correctly sees the pipe down.
const pid = 5555;
let pipeLive = true; // initial cached state: pipe is live
const tickNow = vi.fn(async () => { pipeLive = false; }); // OS poll says: gone now
const tickNow = vi.fn(async () => {
pipeLive = false;
}); // OS poll says: gone now
const session = new HookSession(pid, {
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
inject: vi.fn(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(),
},
makeClient: () => new FakeClient() as unknown as QqHookClient,
@@ -637,6 +763,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
@@ -706,7 +866,9 @@ describe('HookSession — pipe-down must not clobber a settled error', () => {
it('onPipeDown after a failed load leaves the error status intact', async () => {
const injector = {
inject: vi.fn(() => { throw new Error('inject boom'); }),
inject: vi.fn(() => {
throw new Error('inject boom');
}),
unload: vi.fn(),
};
const session = new HookSession(1234, {
@@ -771,7 +933,11 @@ describe('HookSession — packet forwarding', () => {
ctx.currentClient().fireLogin('10001');
ctx.currentClient().firePacket({
seq: 1, error: 0, cmd: 'foo', uin: '', body: Buffer.alloc(0),
seq: 1,
error: 0,
cmd: 'foo',
uin: '',
body: Buffer.alloc(0),
});
expect(onPacket.mock.calls[0]![0].uin).toBe('10001');
@@ -786,7 +952,11 @@ describe('HookSession — packet forwarding', () => {
// No login fired yet.
ctx.currentClient().firePacket({
seq: 1, error: 0, cmd: 'foo', uin: '10001', body: Buffer.alloc(0),
seq: 1,
error: 0,
cmd: 'foo',
uin: '10001',
body: Buffer.alloc(0),
});
expect(onPacket).not.toHaveBeenCalled();
@@ -804,7 +974,11 @@ describe('HookSession — packet forwarding', () => {
// Force a bad uin via the packet AND null out session uin by simulating
// a logout? Simpler: send a packet with uin '42' (numeric but <5 chars).
ctx.currentClient().firePacket({
seq: 1, error: 0, cmd: 'foo', uin: '42', body: Buffer.alloc(0),
seq: 1,
error: 0,
cmd: 'foo',
uin: '42',
body: Buffer.alloc(0),
});
expect(onPacket).not.toHaveBeenCalled();
@@ -819,7 +993,11 @@ describe('HookSession — packet forwarding', () => {
// Should not throw / crash.
ctx.currentClient().firePacket({
seq: 1, error: 0, cmd: 'foo', uin: '10001', body: Buffer.from([7]),
seq: 1,
error: 0,
cmd: 'foo',
uin: '10001',
body: Buffer.from([7]),
});
});
});
@@ -882,6 +1060,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
});
try {
await ctx.session.load();
ctx.session.onPipeUp();
@@ -902,6 +1081,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin, identityKnown: true }),
});
try {
await ctx.session.load();
ctx.session.onPipeUp();
@@ -927,6 +1107,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
identityHintFailures: 3,
});
try {
await ctx.session.load();
ctx.session.onPipeUp();
@@ -956,7 +1137,8 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); await flush();
await flush();
await flush();
expect(loginSpy).not.toHaveBeenCalled();
expect(ctx.session.status).toBe('loaded');
@@ -971,7 +1153,8 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); await flush();
await flush();
await flush();
expect(loginSpy).not.toHaveBeenCalled();
});
@@ -979,13 +1162,16 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
it('tolerates a throwing probe (best-effort, no crash/login)', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => { throw new Error('port scan failed'); },
probeLogin: async () => {
throw new Error('port scan failed');
},
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); await flush();
await flush();
await flush();
expect(loginSpy).not.toHaveBeenCalled();
expect(ctx.session.status).toBe('loaded');
@@ -993,6 +1179,7 @@ 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 identityKnown = false;
const ctx = makeSession({
@@ -1061,6 +1248,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();
@@ -1197,10 +1417,16 @@ describe('HookSession — end-to-end receive health (#233)', () => {
describe('HookSession — login reconcile does not stack concurrent probes', () => {
it('skips overlapping ticks while a slow probe is in flight', async () => {
vi.useFakeTimers();
try {
// A probe that never resolves — simulates a slow port scan spanning
// multiple intervals. The in-flight guard must call it only once.
const probeLogin = vi.fn(() => new Promise<never>(() => { /* pending */ }));
const probeLogin = vi.fn(
() =>
new Promise<never>(() => {
/* pending */
}),
);
const ctx = makeSession({ pipeLive: true, probeLogin });
await ctx.session.load();
+16 -4
View File
@@ -3,14 +3,20 @@ import { statusFor, type HookFlags } from '../src/hook-status';
import type { HookProcessStatus } from '../src/types';
const F = (o: Partial<HookFlags>): HookFlags => ({
injected: false, connected: false, loggedIn: false, wasLoggedIn: false, ...o,
injected: false,
connected: false,
loggedIn: false,
wasLoggedIn: false,
...o,
});
describe('statusFor — settled HookProcessStatus derivation', () => {
it('not injected → available (regardless of other flags)', () => {
expect(statusFor(F({ injected: false }))).toBe('available');
// !injected dominates: stale connected/loggedIn bits must not leak through.
expect(statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true }))).toBe('available');
expect(
statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true })),
).toBe('available');
});
it('injected, connected, loggedIn → online', () => {
@@ -22,11 +28,15 @@ describe('statusFor — settled HookProcessStatus derivation', () => {
});
it('injected, not connected, had logged in → disconnected', () => {
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe('disconnected');
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe(
'disconnected',
);
});
it('injected, not connected, never logged in → connecting', () => {
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe('connecting');
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe(
'connecting',
);
});
it('disconnected vs connecting differ ONLY by wasLoggedIn (same injected+!connected)', () => {
@@ -37,6 +47,7 @@ describe('statusFor — settled HookProcessStatus derivation', () => {
it('covers exactly the five settled states across the flag space', () => {
const seen = new Set<HookProcessStatus>();
for (const injected of [false, true]) {
for (const connected of [false, true]) {
for (const loggedIn of [false, true]) {
@@ -46,6 +57,7 @@ describe('statusFor — settled HookProcessStatus derivation', () => {
}
}
}
expect([...seen].sort()).toEqual(
['available', 'connecting', 'disconnected', 'loaded', 'online'].sort(),
);
+415
View File
@@ -0,0 +1,415 @@
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);
});
});
+46 -16
View File
@@ -13,8 +13,12 @@ function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set<num
});
return {
watcher,
setProcesses: (p: HookProcessBaseInfo[]) => { processes = p; },
setLive: (s: Set<number>) => { live = s; },
setProcesses: (p: HookProcessBaseInfo[]) => {
processes = p;
},
setLive: (s: Set<number>) => {
live = s;
},
};
}
@@ -22,10 +26,12 @@ type EventRow = [string, unknown];
function captureEvents(watcher: PipeWatcher): EventRow[] {
const events: EventRow[] = [];
watcher.on('process-discovered', info => events.push(['discovered', (info as HookProcessBaseInfo).pid]));
watcher.on('process-gone', pid => events.push(['gone', pid]));
watcher.on('pipe-up', pid => events.push(['up', pid]));
watcher.on('pipe-down', pid => events.push(['down', pid]));
watcher.on('process-discovered', (info) =>
events.push(['discovered', (info as HookProcessBaseInfo).pid]),
);
watcher.on('process-gone', (pid) => events.push(['gone', pid]));
watcher.on('pipe-up', (pid) => events.push(['up', pid]));
watcher.on('pipe-down', (pid) => events.push(['down', pid]));
return events;
}
@@ -38,7 +44,7 @@ describe('PipeWatcher', () => {
let observed: readonly HookProcessBaseInfo[] | undefined;
const watcher = new PipeWatcher({
listProcesses: () => processes,
listLivePipes: async current => {
listLivePipes: async (current) => {
observed = current;
return new Set();
},
@@ -131,11 +137,18 @@ describe('PipeWatcher', () => {
ctx.setLive(new Set());
await ctx.watcher.tickNow();
expect(events).toEqual([['up', 1234], ['down', 1234]]);
expect(events).toEqual([
['up', 1234],
['down', 1234],
]);
ctx.setLive(new Set([1234]));
await ctx.watcher.tickNow();
expect(events).toEqual([['up', 1234], ['down', 1234], ['up', 1234]]);
expect(events).toEqual([
['up', 1234],
['down', 1234],
['up', 1234],
]);
ctx.watcher.stop();
});
@@ -158,7 +171,9 @@ describe('PipeWatcher', () => {
it('emits "tick" after every poll', async () => {
const ctx = setupWatcher({ processes: [], live: new Set() });
let ticks = 0;
ctx.watcher.on('tick', () => { ticks++; });
ctx.watcher.on('tick', () => {
ticks++;
});
await ctx.watcher.start();
expect(ticks).toBe(1);
@@ -179,7 +194,7 @@ describe('PipeWatcher', () => {
// Wait on 'tick' rather than guessing how many event-loop turns
// setTimeout(0) needs (it's clamped to ~1ms and races setImmediate).
const nextTick = new Promise<void>(resolve => ctx.watcher.once('tick', () => resolve()));
const nextTick = new Promise<void>((resolve) => ctx.watcher.once('tick', () => resolve()));
ctx.setLive(new Set([1234]));
ctx.watcher.wake();
await nextTick;
@@ -194,7 +209,10 @@ describe('PipeWatcher', () => {
let shouldThrow = true;
const watcher = new PipeWatcher({
listProcesses: () => {
if (shouldThrow) throw new Error('boom');
if (shouldThrow) {
throw new Error('boom');
}
return processes;
},
listLivePipes: async () => new Set(live),
@@ -210,7 +228,10 @@ describe('PipeWatcher', () => {
const events = captureEvents(watcher);
await watcher.tickNow();
expect(events).toEqual([['discovered', 1234], ['up', 1234]]);
expect(events).toEqual([
['discovered', 1234],
['up', 1234],
]);
watcher.stop();
});
@@ -220,7 +241,10 @@ describe('PipeWatcher', () => {
const watcher = new PipeWatcher({
listProcesses: () => processes,
listLivePipes: async () => {
if (failPipeDiscovery) throw new Error('permission denied');
if (failPipeDiscovery) {
throw new Error('permission denied');
}
return new Set([1234]);
},
intervalMs: 60_000,
@@ -240,7 +264,10 @@ describe('PipeWatcher', () => {
processes = [];
await watcher.tickNow();
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
expect(events).toEqual([
['down', 1234],
['gone', 1234],
]);
expect(watcher.isProcessAlive(1234)).toBe(false);
expect(watcher.isPipeLive(1234)).toBe(false);
watcher.stop();
@@ -278,7 +305,10 @@ describe('PipeWatcher', () => {
result = [];
live = new Set();
await watcher.tickNow();
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
expect(events).toEqual([
['down', 1234],
['gone', 1234],
]);
watcher.stop();
});
});
@@ -19,7 +19,9 @@ describe('createNativeProcessEnumerator', () => {
it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => {
const en = createNativeProcessEnumerator({
addonPath: null,
fallbackSync: () => { throw new Error('boom'); },
fallbackSync: () => {
throw new Error('boom');
},
processName: 'qq',
});
expect(await en.enumerate()).toBeNull();
+247 -88
View File
@@ -87,7 +87,9 @@ function mockControlPipe(
): ReturnType<typeof vi.spyOn> {
return vi.spyOn(net, 'createConnection').mockImplementation((() => {
const socket = new Duplex({
read() { /* peer data is injected with emit('data') */ },
read() {
/* peer data is injected with emit('data') */
},
write(chunk, _encoding, callback) {
onWrite(socket, Buffer.from(chunk));
callback();
@@ -95,10 +97,15 @@ function mockControlPipe(
}) as net.Socket;
queueMicrotask(() => {
socket.emit('connect');
queueMicrotask(() => socket.emit('data', pipeFrame({
queueMicrotask(() =>
socket.emit(
'data',
pipeFrame({
op: PipeOp.hello,
value0: BigInt(pid),
})));
}),
),
);
});
return socket;
}) as typeof net.createConnection);
@@ -111,15 +118,17 @@ function traceMessages(entries: LogEntry[]): string[] {
}
function runtimeTrace(entries: LogEntry[]): LogEntry[] {
return entries.filter(
(entry) => entry.level === 'trace' && entry.scope === 'QQHook.Runtime',
);
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'QQHook.Runtime');
}
afterEach(async () => {
setLogLevel(previousLogLevel);
vi.restoreAllMocks();
if (!tmpDir) return;
if (!tmpDir) {
return;
}
await rm(tmpDir, { recursive: true, force: true });
tmpDir = null;
});
@@ -142,7 +151,9 @@ describe('listLiveLinuxPipePids', () => {
await writeFile(path.join(runtimeDir, 'mojo.56.recv.sock'), '');
await writeFile(path.join(runtimeDir, 'mojo.not-a-pid.control.sock'), '');
const probe = vi.fn(async (socketPath: string) => socketPath.endsWith('mojo.56.control.sock'));
const probe = vi.fn(async (socketPath: string) =>
socketPath.endsWith('mojo.56.control.sock'),
);
const pids = await listLiveLinuxPipePids(runtimeDir, probe);
expect([...pids]).toEqual([56]);
@@ -157,12 +168,18 @@ describe('QqHookClient — pipe frame limits', () => {
const connection = mockControlPipe(pid, (socket, payload) => {
writes.push(Buffer.from(payload));
const requestId = payload.readUInt32LE(8);
queueMicrotask(() => socket.emit('data', pipeFrame({
queueMicrotask(() =>
socket.emit(
'data',
pipeFrame({
op: PipeOp.sendAck,
requestId,
})));
}),
),
);
});
const client = new QqHookClient(pid);
try {
await client.reconcileLoginIdentity('10001');
@@ -190,7 +207,11 @@ describe('QqHookClient — pipe frame limits', () => {
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;
socket = new Duplex({
read() {
/* peer data is injected with emit('data') */
},
}) as net.Socket;
queueMicrotask(() => {
socket!.emit('connect');
const header = Buffer.alloc(HEADER_SIZE);
@@ -204,6 +225,7 @@ describe('QqHookClient — pipe frame limits', () => {
}) 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(
@@ -225,19 +247,23 @@ describe('QqHookClient — pipe frame limits', () => {
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), {
await expect(
client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES + 1), Buffer.alloc(0), {
ackTimeoutMs: 25,
})).rejects.toThrow(
}),
).rejects.toThrow(
`pipe frame command length ${MAX_PIPE_CMD_BYTES + 1} exceeds limit ${MAX_PIPE_CMD_BYTES}`,
);
expect(onWrite).not.toHaveBeenCalled();
@@ -252,13 +278,13 @@ describe('QqHookClient — pipe frame limits', () => {
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(
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();
@@ -272,15 +298,22 @@ describe('QqHookClient — pipe frame limits', () => {
const pid = 778833;
const connection = mockControlPipe(pid, (socket, payload) => {
const requestId = payload.readUInt32LE(8);
queueMicrotask(() => socket.emit('data', pipeFrame({
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 });
await expect(
client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES), Buffer.alloc(0)),
).resolves.toMatchObject({ requestId: 1 });
} finally {
client.close();
connection.mockRestore();
@@ -296,14 +329,22 @@ describe('QqHookClient — pipe frame limits', () => {
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;
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));
if (end > offset) {
socket.emit('data', wire.subarray(offset, end));
}
offset = end;
}
});
@@ -311,7 +352,8 @@ describe('QqHookClient — pipe frame limits', () => {
return socket;
}) as typeof net.createConnection);
const client = new QqHookClient(pid);
client.on('loginState', state => states.push(state.uin));
client.on('loginState', (state) => states.push(state.uin));
try {
const hello = await client.connect();
@@ -328,7 +370,11 @@ describe('QqHookClient — pipe frame limits', () => {
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;
const socket = new Duplex({
read() {
/* peer data is injected with emit('data') */
},
}) as net.Socket;
queueMicrotask(() => {
socket.emit('connect');
queueMicrotask(() => {
@@ -340,6 +386,7 @@ describe('QqHookClient — pipe frame limits', () => {
return socket;
}) as typeof net.createConnection);
const client = new QqHookClient(pid);
try {
await expect(client.connect()).resolves.toMatchObject({ pipeName: message, pid });
} finally {
@@ -360,19 +407,27 @@ describe('QqHookClient — runtime TRACE', () => {
const kind = connectionIndex === 0 ? 'control' : 'recv';
connectionIndex += 1;
const socket = new Duplex({
read() { /* peer data is injected with emit('data') */ },
read() {
/* peer data is injected with emit('data') */
},
}) as net.Socket;
queueMicrotask(() => {
socket.emit('connect');
queueMicrotask(() => socket.emit('data', pipeFrame({
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());
@@ -381,11 +436,19 @@ describe('QqHookClient — runtime TRACE', () => {
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_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+$/),
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();
@@ -400,11 +463,16 @@ describe('QqHookClient — runtime TRACE', () => {
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;
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');
@@ -414,7 +482,9 @@ describe('QqHookClient — runtime TRACE', () => {
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.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 {
@@ -429,7 +499,9 @@ describe('QqHookClient — runtime TRACE', () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const connection = mockControlPipe(pid, () => { /* no packet writes */ });
const connection = mockControlPipe(pid, () => {
/* no packet writes */
});
const client = new QqHookClient(pid);
const eventRequestIds: Array<{ event: 'login' | 'close'; req: number | undefined }> = [];
client.on('loginState', () => {
@@ -438,26 +510,33 @@ describe('QqHookClient — runtime TRACE', () => {
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({
controlSocket.emit(
'data',
pipeFrame({
op: PipeOp.loginState,
status: 1,
value0: 123456n,
message: '123456',
}));
controlSocket.emit('data', pipeFrame({
}),
);
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 '),
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);
@@ -483,7 +562,9 @@ 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),
0x00,
0xff,
...Array.from({ length: 160 }, (_, index) => index & 0xff),
]);
const replyBody = Buffer.from([0xff, 0x00, 0x7f]);
const entries: LogEntry[] = [];
@@ -497,20 +578,23 @@ describe('QqHookClient — packet TRACE', () => {
traceCountAtWrite = traceMessages(entries).length;
queueMicrotask(() => {
socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId: frame.requestId }));
socket.emit('data', pipeFrame({
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 reply = await runWithRequestId(4101, () =>
client.sendAndWait('OidbSvcTrpcTcp.0x1234_1', requestBody),
);
const sent = readSendFrame(writes[0]);
@@ -526,8 +610,8 @@ describe('QqHookClient — packet TRACE', () => {
body: replyBody,
});
expect(traceCountAtWrite).toBe(1);
expect(entries.filter((entry) => entry.scope === 'QQHook.Packet'))
.toEqual(expect.arrayContaining([
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')}`,
@@ -538,10 +622,16 @@ describe('QqHookClient — packet TRACE', () => {
}),
expect.objectContaining({
req: 4101,
message: expect.stringMatching(/^packet_terminal serviceCmd="OidbSvcTrpcTcp\.0x1234_1" requestId=1 outcome=failed reason=reply_error error=27 elapsedMs=\d+$/),
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('...');
]),
);
for (const message of traceMessages(entries)) {
expect(message).not.toContain('...');
}
} finally {
unsubscribe();
client.close();
@@ -562,13 +652,16 @@ describe('QqHookClient — packet TRACE', () => {
});
});
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+$/),
expect.stringMatching(
/^packet_terminal serviceCmd="Empty\.Command" requestId=1 outcome=ok reason=reply_received error=0 elapsedMs=\d+$/,
),
]);
} finally {
unsubscribe();
@@ -589,12 +682,15 @@ describe('QqHookClient — packet TRACE', () => {
});
});
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+$/),
expect.stringMatching(
/^packet_terminal serviceCmd="NoReply\.Command" requestId=1 outcome=ok reason=ack_received elapsedMs=\d+$/,
),
]);
} finally {
unsubscribe();
@@ -613,16 +709,21 @@ describe('QqHookClient — packet TRACE', () => {
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 */ });
client.on('error', () => {
/* expected transport failure */
});
try {
const timedOut = client.sendAndWait('Timeout.Command', Buffer.from([0xff]), {
ackTimeoutMs: 50,
@@ -643,10 +744,16 @@ describe('QqHookClient — packet TRACE', () => {
});
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+$/),
]));
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();
@@ -665,16 +772,23 @@ describe('QqHookClient — packet TRACE', () => {
const connection = mockControlPipe(pid, (socket, payload) => {
const { requestId } = readSendFrame(payload);
writeCount += 1;
if (writeCount === 2) {
queueMicrotask(() => socket.emit('data', pipeFrame({
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,
@@ -688,15 +802,27 @@ describe('QqHookClient — packet TRACE', () => {
message: 'send ack 1 timed out after 25 ms',
});
await expect(client.sendAndWait(
'Pipe.Error',
Buffer.from([0xff]),
)).rejects.toThrow('send ack 2 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+$/),
]));
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();
@@ -713,26 +839,35 @@ describe('QqHookClient — packet TRACE', () => {
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const connection = mockControlPipe(pid, (socket, payload) => {
writes.push(readSendFrame(payload));
if (writes.length !== 2) return;
if (writes.length !== 2) {
return;
}
queueMicrotask(() => {
for (const frame of [...writes].reverse()) {
socket.emit('data', pipeFrame({
socket.emit(
'data',
pipeFrame({
op: PipeOp.sendAck,
requestId: frame.requestId,
}));
socket.emit('data', pipeFrame({
}),
);
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),
);
const secondBody = Buffer.from(Array.from({ length: 160 }, (_, index) => index & 0xff));
try {
const [first, second] = await Promise.all([
client.sendAndWait('First\nCommand', firstBody),
@@ -744,13 +879,17 @@ describe('QqHookClient — packet TRACE', () => {
const messages = traceMessages(entries);
expect(messages).toHaveLength(6);
expect(messages.every((message) => !message.includes('\n'))).toBe(true);
expect(messages).toEqual(expect.arrayContaining([
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);
]),
);
expect(
messages.filter((message) => message.startsWith('packet_terminal')),
).toHaveLength(2);
} finally {
unsubscribe();
client.close();
@@ -770,6 +909,7 @@ describe('QqHookClient — packet TRACE', () => {
});
});
const client = new QqHookClient(pid);
try {
await client.sendAndWait('Disabled.Command', Buffer.from([0x00, 0xff]));
@@ -793,6 +933,7 @@ describe('QqHookClient — pipe close mid-send', () => {
// unhandledRejection assertion below.
it('does not raise an unhandled rejection', async () => {
const PID = 778899;
const helloFrame = (): Buffer => {
const h = Buffer.alloc(40);
h.writeUInt32LE(0x31504851, 0); // PIPE_MAGIC
@@ -804,10 +945,14 @@ describe('QqHookClient — pipe close mid-send', () => {
let controlConn: net.Socket | null = null;
let signalControlWrite!: () => void;
const controlWriteStarted = new Promise<void>((resolve) => { signalControlWrite = resolve; });
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') */ },
read() {
/* peer data is injected with emit('data') */
},
write(_chunk, _encoding, callback) {
signalControlWrite();
callback();
@@ -822,18 +967,29 @@ describe('QqHookClient — pipe close mid-send', () => {
}) as typeof net.createConnection);
const unhandled: unknown[] = [];
const onUnhandled = (reason: unknown): void => { unhandled.push(reason); };
const onUnhandled = (reason: unknown): void => {
unhandled.push(reason);
};
process.on('unhandledRejection', onUnhandled);
const client = new QqHookClient(PID);
client.on('error', () => { /* socket reset on destroy — ignore */ });
client.on('error', () => {
/* socket reset on destroy — ignore */
});
try {
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);
const sent = client
.send('noop', null, { wantReply: true, ackTimeoutMs: 1000, replyTimeoutMs: 1000 })
.then(
() => 'resolved' as const,
(e: unknown) => e,
);
await controlWriteStarted;
controlConn?.destroy();
@@ -842,7 +998,10 @@ describe('QqHookClient — pipe close mid-send', () => {
expect(outcome).toBeInstanceOf(Error);
expect((outcome as Error).message).toBe('control pipe closed');
expect(unhandled, `unhandled rejections leaked: ${unhandled.map(String).join(', ')}`).toHaveLength(0);
expect(
unhandled,
`unhandled rejections leaked: ${unhandled.map(String).join(', ')}`,
).toHaveLength(0);
} finally {
process.off('unhandledRejection', onUnhandled);
client.close();
@@ -0,0 +1,724 @@
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,
});
await probeQqLoginInfo(9002);
expect(warnings).toEqual(['login probe: PID=9002 result=no-ports ports=0 processes=2']);
} 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();
});
});
+19 -5
View File
@@ -1,9 +1,11 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const execMock = vi.hoisted(() => vi.fn());
const socketCtorMock = vi.hoisted(() => vi.fn(function MockSocket() {
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', () => ({
@@ -35,7 +37,10 @@ describe('probeQqLoginInfo — bounded execution', () => {
callback(null, { stdout: '', stderr: '' });
})
.mockImplementationOnce((_command, _options, callback) => {
callback(null, { stdout: '1\n', stderr: '' });
callback(null, {
stdout: process.platform === 'win32' ? 'QQ.exe 4242 Console 1 1234 K\n' : '1\n',
stderr: '',
});
});
await expect(probeQqLoginInfo(4242)).resolves.toEqual({
@@ -49,12 +54,21 @@ describe('probeQqLoginInfo — bounded execution', () => {
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',
stdout:
process.platform === 'win32'
? 'TCP 127.0.0.1:9218 0.0.0.0:0 LISTENING 4242\n'
: '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: '' });
callback(null, {
stdout:
process.platform === 'win32'
? 'QQ.exe 4242 Console 1 1234 K\n'.repeat(8)
: '8\n',
stderr: '',
});
});
await expect(probeQqLoginInfo(4242)).resolves.toBeNull();
@@ -0,0 +1,152 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { hasLowProcessIntegrity, type NativeRuntimeIntegrity } from '../src/runtime-integrity';
const native = vi.hoisted(() => ({ load: vi.fn(), error: vi.fn() }));
vi.mock('../src/injector', () => ({
getNativeHookAddon: native.load,
getNativeHookLoadError: native.error,
}));
const platform = process.platform;
const sample = (): NativeRuntimeIntegrity => ({
pid: process.pid,
executablePath: process.execPath,
process: { status: 'ok', rid: 8192 },
file: { status: 'ok', label: null },
});
beforeEach(() => {
vi.resetModules();
vi.resetAllMocks();
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
});
afterEach(() => {
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
});
describe('runtime integrity diagnostics', () => {
it('warns only for a successfully read process token below Medium', () => {
const available = { ...sample(), status: 'available' as const };
for (const rid of [0, 4096]) {
expect(hasLowProcessIntegrity({ ...available, process: { status: 'ok', rid } })).toBe(
true,
);
}
for (const rid of [8192, 8448, 12288, 16384]) {
expect(
hasLowProcessIntegrity({
...available,
process: { status: 'ok', rid },
file: { status: 'ok', label: { rid: 4096, inherited: true, policy: 1 } },
}),
).toBe(false);
}
expect(hasLowProcessIntegrity({ status: 'unsupported' })).toBe(false);
expect(hasLowProcessIntegrity({ status: 'unavailable', error: 'unavailable' })).toBe(false);
expect(
hasLowProcessIntegrity({
...available,
process: { status: 'error', operation: 'OpenProcessToken', code: 5 },
}),
).toBe(false);
});
it('keeps one startup snapshot for logging and all WebUI polls', async () => {
const read = vi.fn().mockReturnValue(sample());
native.load.mockReturnValue({ getRuntimeIntegrity: read });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
const first = getRuntimeIntegrity();
expect(first).toMatchObject({
status: 'available',
process: { rid: 8192 },
file: { label: null },
});
read.mockReturnValue({
...sample(),
file: { status: 'ok', label: { rid: 4096, inherited: true, policy: 1 } },
});
expect(getRuntimeIntegrity()).toBe(first);
expect(read).toHaveBeenCalledTimes(1);
});
it.each(['process', 'file'])(
'retains %s query errors and the other successful result',
async (field) => {
native.load.mockReturnValue({
getRuntimeIntegrity: () => ({
...sample(),
[field]: { status: 'error', operation: 'Win32Query', code: 5 },
}),
});
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toMatchObject({
status: 'available',
[field]: { status: 'error', operation: 'Win32Query', code: 5 },
});
},
);
it('reports old addons as unavailable rather than Medium', async () => {
native.load.mockReturnValue({});
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toMatchObject({
status: 'unavailable',
error: expect.stringContaining('不支持'),
});
});
it('retains the loader error for the startup log', async () => {
native.load.mockReturnValue(null);
native.error.mockReturnValue('dlopen failed: incompatible binary');
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toMatchObject({
status: 'unavailable',
error: 'dlopen failed: incompatible binary',
});
});
it.each([
null,
{ ...sample(), pid: process.pid + 1 },
{ ...sample(), process: { status: 'ok', rid: -1 } },
{ ...sample(), file: { status: 'ok', label: { rid: 4096, inherited: 'yes', policy: 1 } } },
])('rejects malformed or wrong-process native results', async (result) => {
native.load.mockReturnValue({ getRuntimeIntegrity: () => result });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toMatchObject({
status: 'unavailable',
error: expect.stringContaining('无效数据'),
});
});
it('preserves thrown errors without repeatedly probing on WebUI polls', async () => {
const read = vi
.fn()
.mockImplementationOnce(() => {
throw new Error('allocation failed');
})
.mockReturnValue(sample());
native.load.mockReturnValue({ getRuntimeIntegrity: read });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toMatchObject({
status: 'unavailable',
error: 'allocation failed',
});
expect(getRuntimeIntegrity()).toMatchObject({
status: 'unavailable',
error: 'allocation failed',
});
expect(read).toHaveBeenCalledTimes(1);
});
it('does not load the addon on non-Windows hosts', async () => {
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toEqual({ status: 'unsupported' });
expect(native.load).not.toHaveBeenCalled();
});
});
+8 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.14.4",
"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"
@@ -82,5 +86,8 @@
"@zxcvbn-ts/core": "^4.1.2",
"@zxcvbn-ts/language-common": "^4.1.3",
"@zxcvbn-ts/language-en": "^4.1.1"
},
"engines": {
"node": ">=24"
}
}
+18 -8
View File
@@ -5,11 +5,7 @@ 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 type AccessTokenAssessmentReason = 'empty' | 'too-short' | 'guessable' | 'acceptable';
export interface AccessTokenAssessment {
acceptable: boolean;
@@ -25,14 +21,23 @@ const checker = new ZxcvbnFactory({
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);
if (Number.isFinite(value)) {
unique.add(value);
}
continue;
}
const trimmed = value.trim();
if (trimmed) unique.add(trimmed.slice(0, 256));
if (trimmed) {
unique.add(trimmed.slice(0, 256));
}
}
return [...unique].slice(0, 24);
}
@@ -45,14 +50,19 @@ export function assessAccessToken(
token: string,
userInputs: readonly (string | number)[] = [],
): AccessTokenAssessment {
if (!token) return { acceptable: false, reason: 'empty', score: 0 };
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 };
}
+5 -1
View File
@@ -20,7 +20,11 @@ export function boolOr(value: unknown, fallback: boolean): boolean {
* the fallback. Fractional precision is preserved — use `clampInt` to floor. */
export function clampNum(value: unknown, min: number, max: number, fallback: number): number {
const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
if (!Number.isFinite(n)) return fallback;
if (!Number.isFinite(n)) {
return fallback;
}
return Math.min(max, Math.max(min, n));
}
+6 -1
View File
@@ -18,10 +18,15 @@ export async function mapWithConcurrency<T, R>(
): Promise<R[]> {
const limit = Math.max(1, Math.trunc(concurrency));
const results = new Array<R>(items.length);
for (let i = 0; i < items.length; i += limit) {
const batch = items.slice(i, i + limit);
const settled = await Promise.all(batch.map((item, j) => fn(item, i + j)));
for (let j = 0; j < settled.length; j++) results[i + j] = settled[j]!;
for (let j = 0; j < settled.length; j++) {
results[i + j] = settled[j]!;
}
}
return results;
}
+34
View File
@@ -0,0 +1,34 @@
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;
}
+10 -1
View File
@@ -3,19 +3,23 @@ const HEX_CHARS_UPPER = '0123456789ABCDEF';
export function toHex(data: Uint8Array | Buffer): string {
let h = '';
for (const b of data) {
h += HEX_CHARS[b >> 4];
h += HEX_CHARS[b & 0xf];
}
return h;
}
export function toHexUpper(data: Uint8Array | Buffer): string {
let h = '';
for (const b of data) {
h += HEX_CHARS_UPPER[b >> 4];
h += HEX_CHARS_UPPER[b & 0xf];
}
return h;
}
@@ -26,10 +30,15 @@ export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string {
}
export function fromHex(hex: string): Buffer {
if (hex.length % 2 !== 0) throw new Error('Invalid hex string length');
if (hex.length % 2 !== 0) {
throw new Error('Invalid hex string length');
}
const buf = Buffer.alloc(hex.length / 2);
for (let i = 0; i < buf.length; i++) {
buf[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
}
return buf;
}
+381 -125
View File
@@ -1,10 +1,7 @@
import fs from 'node:fs';
import path from 'node:path';
import { sanitizeLogLine } from './log-sanitize';
import {
MAX_LOG_RETAIN_DAYS,
MAX_LOG_TOTAL_MB,
} from './runtime';
import { MAX_LOG_RETAIN_DAYS, MAX_LOG_TOTAL_MB } from './runtime';
const DEFAULT_DIR = 'logs';
const DEFAULT_MAX_MB = 50;
@@ -50,12 +47,20 @@ function parseNonNegativeInt(
max: number,
field?: string,
): number {
if (value === undefined || value.trim() === '') return fallback;
if (value === undefined || value.trim() === '') {
return fallback;
}
const parsed = Number(value.trim());
if (Number.isSafeInteger(parsed) && parsed >= 0 && parsed <= max) return parsed;
if (Number.isSafeInteger(parsed) && parsed >= 0 && parsed <= max) {
return parsed;
}
if (field) {
throw new RangeError(`${field} must be an integer in 0..${String(max)}`);
}
return fallback;
}
@@ -65,21 +70,34 @@ function parseRequiredPositiveInt(
max: number,
field: string,
): number {
if (value === undefined || value.trim() === '') return fallback;
if (value === undefined || value.trim() === '') {
return fallback;
}
const parsed = Number(value.trim());
if (Number.isSafeInteger(parsed) && parsed > 0 && parsed <= max) return parsed;
if (Number.isSafeInteger(parsed) && parsed > 0 && parsed <= max) {
return parsed;
}
throw new RangeError(`${field} must be an integer in 1..${String(max)}`);
}
function parseRequiredBool(
value: string | undefined,
fallback: boolean,
field: string,
): boolean {
if (value === undefined || value.trim() === '') return fallback;
function parseRequiredBool(value: string | undefined, fallback: boolean, field: string): boolean {
if (value === undefined || value.trim() === '') {
return fallback;
}
const normalized = value.trim().toLowerCase();
if (['1', 'true', 'yes', 'on'].includes(normalized)) return true;
if (['0', 'false', 'no', 'off'].includes(normalized)) return false;
if (['1', 'true', 'yes', 'on'].includes(normalized)) {
return true;
}
if (['0', 'false', 'no', 'off'].includes(normalized)) {
return false;
}
throw new TypeError(`${field} must be a boolean`);
}
@@ -132,6 +150,7 @@ class LogQuota {
maintainOnLoad = true,
) {
this.loadManagedFiles();
if (maintainOnLoad) {
this.cleanupExpired();
this.ensureCapacity(0);
@@ -141,12 +160,15 @@ class LogQuota {
activate(filePath: string): number | null {
const normalized = path.resolve(filePath);
const known = this.files.get(normalized);
if (known) {
this.active.add(normalized);
return known.bytes;
}
let bytes = 0;
let mtimeMs = Date.now();
try {
const stat = fs.statSync(normalized);
bytes = stat.size;
@@ -159,6 +181,7 @@ class LogQuota {
return null;
}
}
const date = FILE_RE.exec(path.basename(normalized))?.[1] ?? todayString();
this.files.set(normalized, { path: normalized, bytes, mtimeMs, date });
this.usedBytes += bytes;
@@ -168,26 +191,38 @@ class LogQuota {
deactivate(filePath: string): void {
this.active.delete(path.resolve(filePath));
if (this.maintenanceSuspensions > 0) return;
if (this.maintenanceSuspensions > 0) {
return;
}
this.maintainAfterClose();
}
suspendMaintenance(): () => void {
this.maintenanceSuspensions += 1;
let resumed = false;
return () => {
if (resumed) return;
if (resumed) {
return;
}
resumed = true;
this.maintenanceSuspensions = Math.max(0, this.maintenanceSuspensions - 1);
};
}
reserve(filePath: string, bytes: number): boolean {
if (bytes <= 0) return true;
if (bytes <= 0) {
return true;
}
if (this.degraded && !this.retry(false)) {
this.droppedLines += 1;
return false;
}
if (!this.ensureCapacity(bytes)) {
this.droppedLines += 1;
return false;
@@ -195,13 +230,16 @@ class LogQuota {
const normalized = path.resolve(filePath);
const file = this.files.get(normalized);
if (!file) {
if (this.activate(normalized) === null) {
this.droppedLines += 1;
return false;
}
return this.reserve(normalized, bytes);
}
file.bytes += bytes;
file.mtimeMs = Date.now();
this.usedBytes += bytes;
@@ -216,7 +254,10 @@ class LogQuota {
this.enterDegraded(`${operation}: ${errorMessage(error)}`);
}
snapshot(): Omit<LogStorageStatus, 'directory' | 'maxTotalBytes' | 'retainDays' | 'perUinEnabled'> {
snapshot(): Omit<
LogStorageStatus,
'directory' | 'maxTotalBytes' | 'retainDays' | 'perUinEnabled'
> {
return {
state: this.degraded ? 'degraded' : this.lastError ? 'warning' : 'healthy',
totalBytes: this.usedBytes,
@@ -233,6 +274,7 @@ class LogQuota {
this.degraded = false;
this.lastError = null;
this.nextRetryAt = 0;
try {
this.refreshClosedFiles();
this.cleanupExpired();
@@ -251,8 +293,10 @@ class LogQuota {
const candidates = [...this.files.values()]
.filter((file) => !this.active.has(file.path))
.sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path));
for (const file of candidates) {
const bytes = file.bytes;
if (this.deleteManagedFile(file, 'capacity')) {
deletedFiles += 1;
freedBytes += bytes;
@@ -263,28 +307,38 @@ class LogQuota {
});
}
}
if (failures.length === 0) {
this.degraded = false;
this.lastError = null;
this.nextRetryAt = 0;
} else if (this.usedBytes > this.maxTotalBytes) {
this.enterDegraded(
`managed logs still use ${String(this.usedBytes)} bytes after manual cleanup, `
+ `exceeding the ${String(this.maxTotalBytes)} byte limit`,
`managed logs still use ${String(this.usedBytes)} bytes after manual cleanup, ` +
`exceeding the ${String(this.maxTotalBytes)} byte limit`,
);
}
this.ensureCapacity(0);
return { deletedFiles, freedBytes, failures };
}
private retry(force: boolean): boolean {
if (!force && Date.now() < this.nextRetryAt) return false;
if (!force && Date.now() < this.nextRetryAt) {
return false;
}
this.degraded = false;
this.lastError = null;
try {
this.refreshClosedFiles();
const recovered = this.ensureCapacity(0);
if (recovered) this.nextRetryAt = 0;
if (recovered) {
this.nextRetryAt = 0;
}
return recovered;
} catch (error) {
this.enterDegraded(`failed to refresh managed logs: ${errorMessage(error)}`);
@@ -296,28 +350,45 @@ class LogQuota {
try {
this.refreshClosedFiles();
this.cleanupExpired();
if (this.degraded) this.retry(true);
else this.ensureCapacity(0);
if (this.degraded) {
this.retry(true);
} else {
this.ensureCapacity(0);
}
} catch (error) {
this.enterDegraded(`failed to maintain managed logs after rotation: ${errorMessage(error)}`);
this.enterDegraded(
`failed to maintain managed logs after rotation: ${errorMessage(error)}`,
);
}
}
private ensureCapacity(incomingBytes: number): boolean {
if (this.usedBytes + incomingBytes <= this.maxTotalBytes) return true;
if (this.usedBytes + incomingBytes <= this.maxTotalBytes) {
return true;
}
const candidates = [...this.files.values()]
.filter((file) => !this.active.has(file.path))
.sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path));
for (const file of candidates) {
if (this.usedBytes + incomingBytes <= this.maxTotalBytes) break;
if (!this.deleteManagedFile(file, 'capacity')) break;
if (this.usedBytes + incomingBytes <= this.maxTotalBytes) {
break;
}
if (!this.deleteManagedFile(file, 'capacity')) {
break;
}
}
if (this.usedBytes + incomingBytes <= this.maxTotalBytes) {
return true;
}
if (this.usedBytes + incomingBytes <= this.maxTotalBytes) return true;
this.enterDegraded(
`managed logs require ${String(this.usedBytes + incomingBytes)} bytes, `
+ `exceeding the ${String(this.maxTotalBytes)} byte limit; no closed log can be reclaimed`,
`managed logs require ${String(this.usedBytes + incomingBytes)} bytes, ` +
`exceeding the ${String(this.maxTotalBytes)} byte limit; no closed log can be reclaimed`,
);
return false;
}
@@ -327,19 +398,26 @@ class LogQuota {
this.degraded = true;
this.lastError = message;
this.nextRetryAt = Date.now() + QUOTA_RETRY_MS;
if (shouldReport) reportStorageError(message);
if (shouldReport) {
reportStorageError(message);
}
}
private cleanupExpired(): void {
if (this.retainDays === 0) return;
if (this.retainDays === 0) {
return;
}
const cutoff = Date.now() - this.retainDays * 24 * 60 * 60 * 1000;
const expired = [...this.files.values()]
.filter(
(file) => !this.active.has(file.path) && dateOf(file.date).getTime() < cutoff,
)
.filter((file) => !this.active.has(file.path) && dateOf(file.date).getTime() < cutoff)
.sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path));
for (const file of expired) {
if (!this.deleteManagedFile(file, 'retention')) break;
if (!this.deleteManagedFile(file, 'retention')) {
break;
}
}
}
@@ -350,8 +428,7 @@ class LogQuota {
this.usedBytes = Math.max(0, this.usedBytes - file.bytes);
return true;
} catch (error) {
this.lastError =
`${reason} cleanup failed for ${file.path}: ${error instanceof Error ? error.message : String(error)}`;
this.lastError = `${reason} cleanup failed for ${file.path}: ${error instanceof Error ? error.message : String(error)}`;
reportStorageError(this.lastError);
return false;
}
@@ -368,10 +445,15 @@ class LogQuota {
* may be newer than fs.stat while the WriteStream buffer is still flushing. */
private refreshClosedFiles(): void {
const disk = new Map(listManagedLogFiles(this.root).map((file) => [file.path, file]));
for (const [filePath, file] of this.files) {
if (this.active.has(filePath)) continue;
if (this.active.has(filePath)) {
continue;
}
const next = disk.get(filePath);
this.usedBytes -= file.bytes;
if (next) {
this.files.set(filePath, next);
this.usedBytes += next.bytes;
@@ -380,8 +462,12 @@ class LogQuota {
this.files.delete(filePath);
}
}
for (const file of disk.values()) {
if (this.files.has(file.path)) continue;
if (this.files.has(file.path)) {
continue;
}
this.files.set(file.path, file);
this.usedBytes += file.bytes;
}
@@ -390,23 +476,35 @@ class LogQuota {
function listManagedLogFiles(root: string): ManagedLogFile[] {
const out: ManagedLogFile[] = [];
const readDirectory = (dir: string): fs.Dirent[] | null => {
try {
return fs.readdirSync(dir, { withFileTypes: true });
} catch (error) {
if (isMissing(error)) return null;
throw new Error(
`failed to read managed log directory ${dir}: ${errorMessage(error)}`,
{ cause: error },
);
if (isMissing(error)) {
return null;
}
throw new Error(`failed to read managed log directory ${dir}: ${errorMessage(error)}`, {
cause: error,
});
}
};
const visit = (dir: string, entries: fs.Dirent[]): void => {
for (const entry of entries) {
if (!entry.isFile()) continue;
if (!entry.isFile()) {
continue;
}
const match = FILE_RE.exec(entry.name);
if (!match) continue;
if (!match) {
continue;
}
const filePath = path.resolve(dir, entry.name);
try {
const stat = fs.statSync(filePath);
out.push({
@@ -416,25 +514,36 @@ function listManagedLogFiles(root: string): ManagedLogFile[] {
date: match[1]!,
});
} catch (error) {
if (isMissing(error)) continue;
throw new Error(
`failed to stat managed log ${filePath}: ${errorMessage(error)}`,
{ cause: error },
);
if (isMissing(error)) {
continue;
}
throw new Error(`failed to stat managed log ${filePath}: ${errorMessage(error)}`, {
cause: error,
});
}
}
};
const rootEntries = readDirectory(root);
if (!rootEntries) return out;
if (!rootEntries) {
return out;
}
visit(root, rootEntries);
for (const entry of rootEntries) {
if (entry.isDirectory() && ACCOUNT_DIR_RE.test(entry.name)) {
const accountDir = path.join(root, entry.name);
const accountEntries = readDirectory(accountDir);
if (accountEntries) visit(accountDir, accountEntries);
if (accountEntries) {
visit(accountDir, accountEntries);
}
}
}
return out;
}
@@ -477,36 +586,59 @@ class FileWriter {
async prepare(): Promise<void> {
this.ensureForToday(todayString());
const stream = this.file?.stream;
if (!stream) {
throw new Error(`failed to prepare log writer in ${this.dir}`);
}
await new Promise<void>((resolve, reject) => {
const opened = () => {
stream.off('error', failed);
resolve();
};
const failed = (error: Error) => {
stream.off('open', opened);
reject(error);
};
stream.once('open', opened);
stream.once('error', failed);
});
}
write(data: string, bytes: number): boolean {
if (this.disabled) return false;
if (this.disabled) {
return false;
}
const today = todayString();
this.ensureForToday(today);
if (!this.file) return false;
if (!this.file) {
return false;
}
if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) {
this.rotateBySize();
if (!this.file) return false;
if (!this.file) {
return false;
}
}
if (!this.quota.reserve(this.file.path, bytes)) return false;
if (!this.quota.reserve(this.file.path, bytes)) {
return false;
}
try {
this.file.stream.write(data);
} catch (error) {
this.disabled = true;
this.quota.writeFailed(this.file.path, error);
return false;
}
this.file.bytes += bytes;
return true;
}
@@ -517,7 +649,9 @@ class FileWriter {
}
private ensureForToday(today: string): void {
if (this.file && this.file.date === today) return;
if (this.file && this.file.date === today) {
return;
}
if (this.file) {
this.closeCurrent();
@@ -526,30 +660,48 @@ class FileWriter {
// Resume from the highest existing split index for today (so two
// process starts on the same day share files / don't clobber).
let idx = 0;
while (fs.existsSync(this.pathFor(today, idx + 1))) idx++;
while (fs.existsSync(this.pathFor(today, idx + 1))) {
idx++;
}
this.file = this.openFile(today, idx);
}
private rotateBySize(): void {
if (!this.file) return;
if (!this.file) {
return;
}
const date = this.file.date;
const previousIndex = this.file.splitIndex;
this.closeCurrent();
let next = previousIndex + 1;
while (fs.existsSync(this.pathFor(date, next))) next++;
while (fs.existsSync(this.pathFor(date, next))) {
next++;
}
this.file = this.openFile(date, next);
}
private closeCurrent(): void {
const file = this.file;
this.file = null;
if (!file) return;
if (!file) {
return;
}
let finish!: () => void;
const closed = new Promise<void>((resolve) => {
let settled = false;
finish = () => {
if (settled) return;
if (settled) {
return;
}
settled = true;
this.quota.deactivate(file.path);
resolve();
@@ -559,6 +711,7 @@ class FileWriter {
void closed.finally(() => this.pendingCloses.delete(closed));
file.stream.once('error', finish);
try {
file.stream.end(finish);
} catch (error) {
@@ -570,12 +723,20 @@ class FileWriter {
private openFile(date: string, splitIndex: number): OpenFile | null {
const p = this.pathFor(date, splitIndex);
const existingBytes = this.quota.activate(p);
if (existingBytes === null) return null;
if (existingBytes === null) {
return null;
}
try {
const stream = fs.createWriteStream(p, { flags: 'a' });
stream.on('error', (err) => {
this.disabled = true;
if (this.file?.stream === stream) this.file = null;
if (this.file?.stream === stream) {
this.file = null;
}
this.quota.deactivate(p);
this.quota.writeFailed(p, err);
});
@@ -608,7 +769,10 @@ export class FileTransport {
private perUin = new Map<number, FileWriter>();
constructor(policy?: LogStoragePolicy) {
if (policy) validatePolicy(policy);
if (policy) {
validatePolicy(policy);
}
this.dir = path.resolve(process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR);
this.maxBytes =
parseRequiredPositiveInt(
@@ -616,31 +780,35 @@ export class FileTransport {
DEFAULT_MAX_MB,
MAX_LOG_TOTAL_MB,
'SNOWLUMA_LOG_MAX_MB',
) * 1024 * 1024;
) *
1024 *
1024;
this.maxTotalBytes =
(policy?.maxTotalMb
?? parseRequiredPositiveInt(
(policy?.maxTotalMb ??
parseRequiredPositiveInt(
process.env.SNOWLUMA_LOG_MAX_TOTAL_MB,
DEFAULT_MAX_TOTAL_MB,
MAX_LOG_TOTAL_MB,
'SNOWLUMA_LOG_MAX_TOTAL_MB',
)) * 1024 * 1024;
this.retainDays = policy?.retainDays
?? parseNonNegativeInt(
)) *
1024 *
1024;
this.retainDays =
policy?.retainDays ??
parseNonNegativeInt(
process.env.SNOWLUMA_LOG_RETAIN_DAYS,
DEFAULT_RETAIN_DAYS,
MAX_LOG_RETAIN_DAYS,
'SNOWLUMA_LOG_RETAIN_DAYS',
);
this.enabled = process.env.SNOWLUMA_LOG_FILE !== '0';
this.perUinEnabled = policy?.perUinEnabled
?? parseRequiredBool(
process.env.SNOWLUMA_LOG_PER_UIN,
false,
'SNOWLUMA_LOG_PER_UIN',
);
this.perUinEnabled =
policy?.perUinEnabled ??
parseRequiredBool(process.env.SNOWLUMA_LOG_PER_UIN, false, 'SNOWLUMA_LOG_PER_UIN');
if (this.enabled) this.initialize();
if (this.enabled) {
this.initialize();
}
}
/** True when no file output will happen (env disable or init failure). */
@@ -673,6 +841,7 @@ export class FileTransport {
...(this.initializationError ? { lastError: this.initializationError } : {}),
};
}
return {
...this.quota.snapshot(),
directory: this.dir,
@@ -689,20 +858,29 @@ export class FileTransport {
const disablingPerUin = this.perUinEnabled && !policy.perUinEnabled;
this.perUinEnabled = policy.perUinEnabled;
if (disablingPerUin) {
const writers = [...this.perUin.values()];
this.perUin.clear();
await Promise.all(writers.map((writer) => writer.close()));
}
if (this.quota) this.quota.updatePolicy(this.maxTotalBytes, this.retainDays);
if (this.quota) {
this.quota.updatePolicy(this.maxTotalBytes, this.retainDays);
}
if (this.enabled && (!this.quota || !this.shared || this.shared.isDisabled)) {
await this.recoverSharedWriter(true);
}
return this.getStorageStatus();
}
async clearManagedLogs(): Promise<LogCleanupResult> {
if (!this.enabled) return this.clearLogsWhileDisabled();
if (!this.enabled) {
return this.clearLogsWhileDisabled();
}
if (!this.quota) {
try {
this.quota = new LogQuota(this.dir, this.maxTotalBytes, this.retainDays);
@@ -710,6 +888,7 @@ export class FileTransport {
this.recordWriterRecoveryFailure(error);
}
}
if (!this.quota) {
return {
deletedFiles: 0,
@@ -723,13 +902,11 @@ export class FileTransport {
const quota = this.quota;
const accountUins = [...this.perUin.keys()];
const writers = [
...(this.shared ? [this.shared] : []),
...this.perUin.values(),
];
const writers = [...(this.shared ? [this.shared] : []), ...this.perUin.values()];
this.shared = null;
this.perUin.clear();
const resumeMaintenance = quota.suspendMaintenance();
try {
await Promise.all(writers.map((writer) => writer.close()));
} finally {
@@ -739,6 +916,7 @@ export class FileTransport {
const result = quota.clearClosedFiles();
const shared = new FileWriter(this.dir, this.maxBytes, quota);
try {
await shared.prepare();
this.shared = shared;
@@ -751,15 +929,27 @@ export class FileTransport {
message: this.initializationError ?? 'failed to reopen the shared log writer',
});
}
if (this.perUinEnabled) {
for (const uin of accountUins) {
const writer = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, quota);
if (writer.isDisabled) continue;
const writer = new FileWriter(
path.join(this.dir, String(uin)),
this.maxBytes,
quota,
);
if (writer.isDisabled) {
continue;
}
try {
await writer.prepare();
this.perUin.set(uin, writer);
} catch (error) {
quota.storageFailed(`failed to reopen account log writer for ${String(uin)}`, error);
quota.storageFailed(
`failed to reopen account log writer for ${String(uin)}`,
error,
);
result.failures.push({
file: String(uin),
message: `failed to reopen account log writer: ${errorMessage(error)}`,
@@ -772,11 +962,20 @@ export class FileTransport {
}
write(line: string, uin?: number): void {
if (!this.enabled) return;
if (!this.shared || this.shared.isDisabled) {
if (!this.recoverSharedWriterForWrite()) return;
if (!this.enabled) {
return;
}
if (!this.shared) return;
if (!this.shared || this.shared.isDisabled) {
if (!this.recoverSharedWriterForWrite()) {
return;
}
}
if (!this.shared) {
return;
}
const data = sanitizeLogLine(line) + '\n';
const bytes = Buffer.byteLength(data, 'utf8');
@@ -785,53 +984,86 @@ export class FileTransport {
this.shared = null;
this.nextWriterRetryAt = Date.now() + QUOTA_RETRY_MS;
}
return;
}
if (uin !== undefined && this.perUinEnabled && this.quota) {
let w = this.perUin.get(uin);
if (w?.isDisabled) {
this.perUin.delete(uin);
w = undefined;
}
if (!w) {
w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.quota);
if (w.isDisabled) return;
if (w.isDisabled) {
return;
}
this.perUin.set(uin, w);
}
w.write(data, bytes);
}
}
async close(): Promise<void> {
const closes: Promise<void>[] = [];
if (this.shared) closes.push(this.shared.close());
for (const w of this.perUin.values()) closes.push(w.close());
if (this.shared) {
closes.push(this.shared.close());
}
for (const w of this.perUin.values()) {
closes.push(w.close());
}
this.shared = null;
this.perUin.clear();
await Promise.all(closes);
}
private async recoverSharedWriter(force: boolean): Promise<void> {
if (!this.enabled) return;
if (!this.enabled) {
return;
}
if (!force && Date.now() < this.nextWriterRetryAt) {
throw new Error(this.initializationError ?? 'log writer retry is rate-limited');
}
if (this.shared?.isDisabled) this.shared = null;
if (!this.quota) this.initialize();
if (this.shared?.isDisabled) {
this.shared = null;
}
if (!this.quota) {
this.initialize();
}
if (!this.shared && this.quota) {
const writer = new FileWriter(this.dir, this.maxBytes, this.quota);
if (!writer.isDisabled) this.shared = writer;
if (!writer.isDisabled) {
this.shared = writer;
}
}
const writer = this.shared;
if (!writer) {
throw new Error(this.initializationError ?? 'failed to create the shared log writer');
}
try {
await writer.prepare();
if (writer.isDisabled || !writer.currentPath) {
throw new Error('the shared log writer did not open a file');
}
this.initializationError = null;
this.nextWriterRetryAt = 0;
} catch (error) {
@@ -842,18 +1074,32 @@ export class FileTransport {
}
private recoverSharedWriterForWrite(): boolean {
if (!this.enabled || Date.now() < this.nextWriterRetryAt) return false;
if (this.shared?.isDisabled) this.shared = null;
if (!this.quota) this.initialize();
if (!this.enabled || Date.now() < this.nextWriterRetryAt) {
return false;
}
if (this.shared?.isDisabled) {
this.shared = null;
}
if (!this.quota) {
this.initialize();
}
if (!this.shared && this.quota) {
const writer = new FileWriter(this.dir, this.maxBytes, this.quota);
if (!writer.isDisabled) this.shared = writer;
if (!writer.isDisabled) {
this.shared = writer;
}
}
if (this.shared) {
this.initializationError = null;
this.nextWriterRetryAt = 0;
return true;
}
return false;
}
@@ -897,8 +1143,7 @@ export class FileTransport {
}
private recordWriterRecoveryFailure(error: unknown): void {
this.initializationError =
`failed to initialize log storage ${this.dir}: ${errorMessage(error)}`;
this.initializationError = `failed to initialize log storage ${this.dir}: ${errorMessage(error)}`;
this.nextWriterRetryAt = Date.now() + QUOTA_RETRY_MS;
reportStorageError(this.initializationError);
}
@@ -908,9 +1153,11 @@ export class FileTransport {
fs.mkdirSync(this.dir, { recursive: true });
const quota = new LogQuota(this.dir, this.maxTotalBytes, this.retainDays);
const writer = new FileWriter(this.dir, this.maxBytes, quota);
if (writer.isDisabled) {
throw new Error(`failed to create shared log writer in ${this.dir}`);
}
this.quota = quota;
this.shared = writer;
this.initializationError = null;
@@ -925,23 +1172,21 @@ export class FileTransport {
function validatePolicy(policy: LogStoragePolicy): void {
if (
!Number.isSafeInteger(policy.maxTotalMb)
|| policy.maxTotalMb <= 0
|| policy.maxTotalMb > MAX_LOG_TOTAL_MB
!Number.isSafeInteger(policy.maxTotalMb) ||
policy.maxTotalMb <= 0 ||
policy.maxTotalMb > MAX_LOG_TOTAL_MB
) {
throw new RangeError(
`maxTotalMb must be an integer in 1..${String(MAX_LOG_TOTAL_MB)}`,
);
throw new RangeError(`maxTotalMb must be an integer in 1..${String(MAX_LOG_TOTAL_MB)}`);
}
if (
!Number.isSafeInteger(policy.retainDays)
|| policy.retainDays < 0
|| policy.retainDays > MAX_LOG_RETAIN_DAYS
!Number.isSafeInteger(policy.retainDays) ||
policy.retainDays < 0 ||
policy.retainDays > MAX_LOG_RETAIN_DAYS
) {
throw new RangeError(
`retainDays must be an integer in 0..${String(MAX_LOG_RETAIN_DAYS)}`,
);
throw new RangeError(`retainDays must be an integer in 0..${String(MAX_LOG_RETAIN_DAYS)}`);
}
if (typeof policy.perUinEnabled !== 'boolean') {
throw new TypeError('perUinEnabled must be a boolean');
}
@@ -951,15 +1196,23 @@ let singleton: FileTransport | null = null;
let configuredPolicy: LogStoragePolicy | null = null;
export function getFileTransport(): FileTransport {
if (!singleton) singleton = new FileTransport(configuredPolicy ?? undefined);
if (!singleton) {
singleton = new FileTransport(configuredPolicy ?? undefined);
}
return singleton;
}
export async function configureFileTransport(policy: LogStoragePolicy): Promise<LogStorageStatus> {
validatePolicy(policy);
configuredPolicy = { ...policy };
if (!singleton) singleton = new FileTransport(configuredPolicy);
else await singleton.updatePolicy(configuredPolicy);
if (!singleton) {
singleton = new FileTransport(configuredPolicy);
} else {
await singleton.updatePolicy(configuredPolicy);
}
return singleton.getStorageStatus();
}
@@ -973,7 +1226,10 @@ export function clearManagedLogs(): Promise<LogCleanupResult> {
/** Reset state between tests. Closes all active file handles. */
export async function _resetFileTransportForTesting(): Promise<void> {
if (singleton) await singleton.close();
if (singleton) {
await singleton.close();
}
singleton = null;
configuredPolicy = null;
}
+42 -8
View File
@@ -8,37 +8,66 @@ const C1_STRING_STARTERS = new Set([0x90, 0x98, 0x9e, 0x9f]);
function skipCsi(line: string, start: number): number {
for (let i = start; i < line.length; i += 1) {
const code = line.charCodeAt(i);
if (code >= 0x40 && code <= 0x7e) return i + 1;
if (code >= 0x40 && code <= 0x7e) {
return i + 1;
}
}
return line.length;
}
function skipControlString(line: string, start: number, allowBell: boolean): number {
for (let i = start; i < line.length; i += 1) {
const code = line.charCodeAt(i);
if (allowBell && code === BEL) return i + 1;
if (code === C1_ST) return i + 1;
if (code === ESC && line.charCodeAt(i + 1) === 0x5c) return i + 2;
if (allowBell && code === BEL) {
return i + 1;
}
if (code === C1_ST) {
return i + 1;
}
if (code === ESC && line.charCodeAt(i + 1) === 0x5c) {
return i + 2;
}
}
return line.length;
}
function skipEscSequence(line: string, start: number): number {
if (start >= line.length) return line.length;
if (start >= line.length) {
return line.length;
}
const first = line.charCodeAt(start);
if (first === 0x5b) return skipCsi(line, start + 1);
if (first === 0x5d) return skipControlString(line, start + 1, true);
if (first === 0x5b) {
return skipCsi(line, start + 1);
}
if (first === 0x5d) {
return skipControlString(line, start + 1, true);
}
if (first === 0x50 || first === 0x58 || first === 0x5e || first === 0x5f) {
return skipControlString(line, start + 1, false);
}
let i = start;
while (i < line.length) {
const code = line.charCodeAt(i);
if (code < 0x20 || code > 0x2f) break;
if (code < 0x20 || code > 0x2f) {
break;
}
i += 1;
}
const final = line.charCodeAt(i);
return final >= 0x30 && final <= 0x7e ? i + 1 : start;
}
@@ -54,6 +83,7 @@ function skipEscSequence(line: string, start: number): number {
*/
export function sanitizeLogLine(line: string): string {
let plain = '';
for (let i = 0; i < line.length;) {
const code = line.charCodeAt(i);
@@ -61,14 +91,17 @@ export function sanitizeLogLine(line: string): string {
i = skipEscSequence(line, i + 1);
continue;
}
if (code === C1_CSI) {
i = skipCsi(line, i + 1);
continue;
}
if (code === C1_OSC || C1_STRING_STARTERS.has(code)) {
i = skipControlString(line, i + 1, code === C1_OSC);
continue;
}
if ((code < 0x20 && code !== 0x09 && code !== 0x0a) || (code >= 0x7f && code <= 0x9f)) {
i += 1;
continue;
@@ -77,5 +110,6 @@ export function sanitizeLogLine(line: string): string {
plain += line[i];
i += 1;
}
return plain;
}
+117 -47
View File
@@ -22,20 +22,30 @@ function isSensitiveKey(key: string): boolean {
.map((segment) => segment.toLowerCase());
return segments.some((segment, index) => {
if (SENSITIVE_SEGMENTS.has(segment)) return true;
if (SENSITIVE_SEGMENTS.has(segment)) {
return true;
}
const next = segments[index + 1];
return next === 'key' && (
segment === 'api'
|| segment === 'private'
|| segment === 'session'
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';
if (key !== undefined && isSensitiveKey(key)) {
return '"***"';
}
if (v === null) {
return 'null';
}
if (v === undefined) {
return 'undefined';
}
switch (typeof v) {
case 'string':
return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`;
@@ -44,7 +54,10 @@ function valueRepr(v: unknown, key?: string): string {
case 'bigint':
return String(v);
case 'object':
if (Array.isArray(v)) return `[len=${v.length}]`;
if (Array.isArray(v)) {
return `[len=${v.length}]`;
}
return '{...}';
default:
return typeof v;
@@ -60,20 +73,26 @@ function valueRepr(v: unknown, key?: string): string {
* replaced with `...` so the next field doesn't get half-rendered.
*/
export function summarizeParams(params: unknown): string {
if (params === null || params === undefined) return '{}';
if (params === null || params === undefined) {
return '{}';
}
if (typeof params !== 'object') {
const s = String(params);
return s.length > MAX_TOTAL
? `${s.slice(0, MAX_TOTAL - 3)}...`
: s;
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL - 3)}...` : s;
}
if (Array.isArray(params)) {
return `[len=${params.length}]`;
}
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, 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)}...`;
@@ -84,13 +103,16 @@ export function summarizeParams(params: unknown): string {
? `${rendered} ...`
: `${rendered.slice(0, MAX_TOTAL - 3)}...`;
}
out.push(entry);
total += separatorLength + entry.length;
}
return out.join(' ');
}
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 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',
@@ -118,19 +140,23 @@ function isKeyKind(key: string, kind: 'authorization' | 'cookie'): boolean {
function isAuthorizationBoundaryKey(key: string): boolean {
const segments = keySegments(key);
return segments.some((segment, index) => {
if (AUTHORIZATION_BOUNDARY_SEGMENTS.has(segment)) return true;
if (AUTHORIZATION_BOUNDARY_SEGMENTS.has(segment)) {
return true;
}
const next = segments[index + 1];
return next === 'key' && (
segment === 'api'
|| segment === 'private'
|| segment === 'session'
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;
if (quote !== '"' && quote !== "'") {
return undefined;
}
for (let index = start + 1; index < message.length; index += 1) {
if (message[index] === '\\') {
@@ -139,16 +165,19 @@ function quotedValueEnd(message: string, start: number): number | undefined {
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;
}
@@ -156,25 +185,41 @@ function cookieValueEnd(message: string, start: number): number {
while (end < message.length) {
let semicolon: number = end;
while (message[semicolon] === ' ' || message[semicolon] === '\t') {
semicolon += 1;
}
if (message[semicolon] !== ';') break;
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;
while (/[A-Za-z0-9_-]/.test(message[nameEnd] ?? '')) {
nameEnd += 1;
}
if (nameEnd === nameStart) {
break;
}
end = nameEnd;
if (message[end] !== '=') continue;
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;
@@ -182,42 +227,54 @@ function cookieValueEnd(message: string, start: number): number {
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;
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;
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 {
function authorizationValueEnd(message: string, start: number, query: boolean): number {
const quotedEnd = quotedValueEnd(message, start);
if (quotedEnd !== undefined) return quotedEnd;
if (quotedEnd !== undefined) {
return quotedEnd;
}
if (query) {
const queryEnd = message.indexOf('&', start);
@@ -226,16 +283,21 @@ function authorizationValueEnd(
let end = message.length;
const structural = message.slice(start).search(/[\r\n}\]]/);
if (structural >= 0) end = start + structural;
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;
}
@@ -245,23 +307,21 @@ export function redactLogMessage(message: string): string {
let cursor = 0;
ASSIGNMENT_START.lastIndex = 0;
for (let match = ASSIGNMENT_START.exec(message); match; match = ASSIGNMENT_START.exec(message)) {
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,
);
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] === '&',
)
? authorizationValueEnd(message, valueStart, match[1] === '?' || match[1] === '&')
: isKeyKind(key, 'cookie')
? cookieValueEnd(message, valueStart)
: genericValueEnd(message, valueStart);
@@ -283,8 +343,13 @@ export function renderParamsVerbose(params: unknown): string {
const seen = new WeakSet<object>();
const walk = (value: unknown): string => {
if (value === null) return 'null';
if (value === undefined) return 'undefined';
if (value === null) {
return 'null';
}
if (value === undefined) {
return 'undefined';
}
switch (typeof value) {
case 'string':
@@ -293,8 +358,12 @@ export function renderParamsVerbose(params: unknown): string {
case 'boolean':
case 'bigint':
return String(value);
case 'object': {
if (seen.has(value as object)) return '"[circular]"';
if (seen.has(value as object)) {
return '"[circular]"';
}
seen.add(value as object);
const out = Array.isArray(value)
? `[${value.map((item) => walk(item)).join(',')}]`
@@ -304,6 +373,7 @@ export function renderParamsVerbose(params: unknown): string {
seen.delete(value as object);
return out;
}
default:
return typeof value;
}
+81 -26
View File
@@ -73,6 +73,7 @@ function resolveTraceBufferMax(): number {
const raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10);
return Number.isFinite(raw) && raw >= 100 ? raw : 5000;
}
const TRACE_BUFFER_MAX = resolveTraceBufferMax();
/**
@@ -89,15 +90,23 @@ class RingBuffer<T> {
push(item: T): void {
const end = (this.start + this.count) % this.cap;
this.buf[end] = item;
if (this.count < this.cap) this.count += 1;
else this.start = (this.start + 1) % this.cap; // full → overwrite oldest
if (this.count < this.cap) {
this.count += 1;
} else {
this.start = (this.start + 1) % this.cap;
} // full → overwrite oldest
}
/** Most recent `n` items, oldest→newest. */
recent(n: number): T[] {
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
const out: T[] = new Array<T>(take);
const first = this.start + (this.count - take);
for (let i = 0; i < take; i += 1) out[i] = this.buf[(first + i) % this.cap]!;
for (let i = 0; i < take; i += 1) {
out[i] = this.buf[(first + i) % this.cap]!;
}
return out;
}
toArray(): T[] {
@@ -115,21 +124,40 @@ let nextLogId = 1;
function resolveMinLevel(): LogLevel {
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
if (raw === 'trace' || raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
if (
raw === 'trace' ||
raw === 'debug' ||
raw === 'info' ||
raw === 'success' ||
raw === 'warn' ||
raw === 'error'
) {
return raw;
}
return 'info';
}
function resolveFileMinLevel(): FileLogLevel {
const raw = process.env.SNOWLUMA_LOG_FILE_LEVEL;
if (raw === undefined || raw.trim() === '') return 'debug';
if (raw === undefined || raw.trim() === '') {
return 'debug';
}
const normalized = raw.trim().toLowerCase();
if (normalized === 'debug' || normalized === 'info' || normalized === 'success' ||
normalized === 'warn' || normalized === 'error') {
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',
);
@@ -152,26 +180,39 @@ 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 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).
// 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;
if (!LOG_LEVELS.includes(lower as LogLevel)) {
return false;
}
currentLevel = lower as LogLevel;
return true;
}
function useColor(): boolean {
if (process.env.NO_COLOR === '1') return false;
if (process.env.NO_COLOR === '1') {
return false;
}
return Boolean(process.stdout.isTTY);
}
@@ -210,37 +251,36 @@ function render(level: LogLevel, options: LogOptions, message: string, reqId?: n
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
}
function emit(
level: LogLevel,
options: LogOptions,
args: unknown[],
): void {
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;
const passesFile = level !== 'trace' && shouldLogToFile(level);
if (!passesConsole && !passesFile) {
return;
}
// `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;
if (level === 'trace' && !passesConsole) {
return;
}
// Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer
// (and its expensive deep render) only runs now that trace is confirmed live.
let realArgs = args;
if (level === 'trace' && args.length === 1 && typeof args[0] === 'function') {
realArgs = (args[0] as () => unknown[])();
}
const reqId = currentRequestId();
const formattedMessage = format(...realArgs);
const message = level === 'trace'
? formattedMessage
: redactLogMessage(formattedMessage);
const message = level === 'trace' ? formattedMessage : redactLogMessage(formattedMessage);
const line = render(level, options, message, reqId);
const entry: LogEntry = {
id: nextLogId++,
@@ -256,7 +296,11 @@ function emit(
if (passesConsole) {
// Trace gets its own ring so its volume never evicts the normal log buffer.
(level === 'trace' ? traceRing : logRing).push(entry);
for (const subscriber of logSubscribers) subscriber(entry);
for (const subscriber of logSubscribers) {
subscriber(entry);
}
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
// Strip ASCII control characters before writing to terminal to prevent
// BEL (0x07) in user-provided strings (e.g. group member names) from
@@ -264,7 +308,14 @@ function emit(
// and ESC (0x1B) so multi-line records (stack traces) and ANSI color
// sequences emitted by render() pass through intact.
// eslint-disable-next-line no-control-regex
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
const consoleLine = line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n';
try {
stream.write(consoleLine);
} catch {
// A full Docker json-file log volume can make stdout/stderr throw.
// Logging must not take down message handling or the WebUI.
}
}
// File transport sees levels >= currentFileLevel (SNOWLUMA_LOG_FILE_LEVEL,
@@ -303,6 +354,7 @@ export function getRecentLogs(limit = 300): LogEntry[] {
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
logSubscribers.add(callback);
return () => {
logSubscribers.delete(callback);
};
@@ -358,7 +410,10 @@ export function renderTraceBytes(body: Uint8Array): string {
}
export function runWithTraceRequest<T>(fn: () => T): T {
if (currentRequestId() !== undefined || currentLevel !== 'trace') return fn();
if (currentRequestId() !== undefined || currentLevel !== 'trace') {
return fn();
}
return runWithRequestId(nextRequestId(), fn);
}
+5 -1
View File
@@ -14,7 +14,11 @@ let counter = 0;
*/
export function nextRequestId(): number {
counter = (counter + 1) >>> 0;
if (counter === 0) counter = 1;
if (counter === 0) {
counter = 1;
}
return counter;
}
+156 -60
View File
@@ -1,5 +1,6 @@
import fs from 'fs';
import path from 'path';
import { isObject } from './coerce';
export interface RuntimeConfig {
webuiPort?: number;
@@ -33,9 +34,7 @@ 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),
);
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,
@@ -47,7 +46,9 @@ export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT),
hookAutoLoad: normalizeBool(obj.hookAutoLoad, false),
webuiHost: normalizeHost(obj.webuiHost),
webuiTls: { enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false },
webuiTls: {
enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false,
},
trustProxy: typeof obj.trustProxy === 'string' ? obj.trustProxy : '',
logMaxTotalMb: normalizeRequiredInteger(
obj.logMaxTotalMb,
@@ -76,15 +77,24 @@ export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<Runt
const out: Partial<RuntimeConfig> = {};
const port = parsePortString(env.SNOWLUMA_WEBUI_PORT);
if (port !== undefined) out.webuiPort = port;
if (port !== undefined) {
out.webuiPort = port;
}
const host = env.SNOWLUMA_WEBUI_HOST;
if (typeof host === 'string' && host.trim()) out.webuiHost = host.trim();
if (typeof host === 'string' && host.trim()) {
out.webuiHost = host.trim();
}
// Present-but-"0"/"off" is a deliberate override (trust nobody), distinct
// from "absent" — so gate on key presence, not truthiness.
const tp = env.SNOWLUMA_WEBUI_TRUST_PROXY;
if (typeof tp === 'string') out.trustProxy = tp;
if (typeof tp === 'string') {
out.trustProxy = tp;
}
const logMaxTotalMb = parseRequiredIntegerEnv(
env.SNOWLUMA_LOG_MAX_TOTAL_MB,
@@ -92,7 +102,10 @@ export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<Runt
MAX_LOG_TOTAL_MB,
'SNOWLUMA_LOG_MAX_TOTAL_MB',
);
if (logMaxTotalMb !== undefined) out.logMaxTotalMb = logMaxTotalMb;
if (logMaxTotalMb !== undefined) {
out.logMaxTotalMb = logMaxTotalMb;
}
const logRetainDays = parseRequiredIntegerEnv(
env.SNOWLUMA_LOG_RETAIN_DAYS,
@@ -100,13 +113,22 @@ export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<Runt
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;
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;
}
@@ -149,7 +171,10 @@ export function updateRuntimeConfig(patch: Partial<RuntimeConfig>): RuntimeConfi
}
function tryLoadRuntimeConfig(): Record<string, unknown> | null {
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) {
return null;
}
try {
const parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown;
return isObject(parsed) ? parsed : null;
@@ -160,6 +185,7 @@ function tryLoadRuntimeConfig(): Record<string, unknown> | null {
function saveRuntimeConfig(config: RuntimeConfig): void {
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);
@@ -174,6 +200,7 @@ function saveRuntimeConfig(config: RuntimeConfig): void {
);
}
}
throw error;
}
}
@@ -183,44 +210,68 @@ function saveRuntimeConfig(config: RuntimeConfig): void {
function sameRuntimeConfig(parsed: Record<string, unknown>, n: RuntimeConfig): boolean {
const parsedTls = isObject(parsed.webuiTls) ? parsed.webuiTls.enabled : undefined;
return (
parsed.webuiPort === n.webuiPort
&& parsed.hookAutoLoad === n.hookAutoLoad
&& parsed.webuiHost === n.webuiHost
&& parsedTls === n.webuiTls?.enabled
&& parsed.trustProxy === n.trustProxy
&& parsed.logMaxTotalMb === n.logMaxTotalMb
&& parsed.logRetainDays === n.logRetainDays
&& parsed.logPerUin === n.logPerUin
parsed.webuiPort === n.webuiPort &&
parsed.hookAutoLoad === n.hookAutoLoad &&
parsed.webuiHost === n.webuiHost &&
parsedTls === n.webuiTls?.enabled &&
parsed.trustProxy === n.trustProxy &&
parsed.logMaxTotalMb === n.logMaxTotalMb &&
parsed.logRetainDays === n.logRetainDays &&
parsed.logPerUin === n.logPerUin
);
}
function parsePortString(raw: unknown): number | undefined {
if (typeof raw !== 'string' || !raw.trim()) return undefined;
if (typeof raw !== 'string' || !raw.trim()) {
return undefined;
}
const n = Number(raw.trim());
if (!Number.isFinite(n)) return undefined;
if (!Number.isFinite(n)) {
return undefined;
}
const port = Math.trunc(n);
if (port <= 0 || port > 65535) return undefined;
if (port <= 0 || port > 65535) {
return undefined;
}
return port;
}
function normalizeHost(value: unknown): string {
if (typeof value === 'string' && value.trim()) return value.trim();
if (typeof value === 'string' && value.trim()) {
return value.trim();
}
return DEFAULT_WEBUI_HOST;
}
function normalizePort(value: unknown, fallback: number): number {
if (typeof value === 'number' && Number.isFinite(value)) {
const n = Math.trunc(value);
if (n > 0 && n <= 65535) return n;
if (n > 0 && n <= 65535) {
return n;
}
return fallback;
}
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
if (Number.isFinite(n)) {
const port = Math.trunc(n);
if (port > 0 && port <= 65535) return port;
if (port > 0 && port <= 65535) {
return port;
}
}
}
return fallback;
}
@@ -231,38 +282,54 @@ function normalizeRequiredInteger(
max: number,
field: string,
): number {
if (value === undefined) return fallback;
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
) {
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;
function normalizeRequiredBool(value: unknown, fallback: boolean, field: string): boolean {
if (value === undefined) {
return fallback;
}
const parsed = parseBoolValue(value);
if (parsed !== undefined) return parsed;
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;
if (typeof value === 'boolean') {
return value;
}
if (typeof value === 'number') {
return value !== 0;
}
if (typeof value === 'string') {
const v = value.trim().toLowerCase();
if (v === 'true' || v === '1' || v === 'yes' || v === 'on') return true;
if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') return false;
if (v === 'true' || v === '1' || v === 'yes' || v === 'on') {
return true;
}
if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') {
return false;
}
}
return fallback;
}
@@ -272,32 +339,61 @@ function parseRequiredIntegerEnv(
max: number,
field: string,
): number | undefined {
if (typeof raw !== 'string' || !raw.trim()) return undefined;
if (typeof raw !== 'string' || !raw.trim()) {
return undefined;
}
const n = Number(raw.trim());
if (Number.isSafeInteger(n) && n >= min && n <= max) return n;
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;
if (typeof raw !== 'string' || !raw.trim()) {
return undefined;
}
const parsed = parseBoolValue(raw);
if (parsed !== undefined) return parsed;
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;
if (typeof raw === 'boolean') {
return raw;
}
if (raw === 1) {
return true;
}
if (raw === 0) {
return false;
}
if (typeof raw !== 'string') {
return undefined;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
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 isErrnoCode(error: unknown, code: string): boolean {
+21 -10
View File
@@ -58,19 +58,30 @@ export class SingleFlightCache<K, V> {
get(key: K, opts: { force?: boolean } = {}): Promise<V> {
if (!opts.force) {
const hit = this.fresh.get(key);
if (hit && this.now() - hit.at < this.ttlMs) return Promise.resolve(hit.value);
if (hit && this.now() - hit.at < this.ttlMs) {
return Promise.resolve(hit.value);
}
}
const existing = this.inflight.get(key);
if (existing) return existing;
const task = (async () => {
try {
const value = await this.load(key);
if (this.shouldCache(value)) this.fresh.set(key, { at: this.now(), value });
return value;
} finally {
this.inflight.delete(key);
if (existing) {
return existing;
}
})();
const task = (async () => {
const value = await this.load(key);
if (this.shouldCache(value)) {
this.fresh.set(key, { at: this.now(), value });
}
return value;
})().finally(() => {
// Run after registration even when load throws synchronously.
this.inflight.delete(key);
});
this.inflight.set(key, task);
return task;
}
+6 -2
View File
@@ -14,8 +14,12 @@ describe('access token strength', () => {
});
it('scores system and user-specific words as guessable', () => {
expect(assessAccessToken('SnowLumaSnowLuma', ['SnowLuma', 'OneBot', '10001']))
.toMatchObject({ acceptable: false, reason: 'guessable' });
expect(
assessAccessToken('SnowLumaSnowLuma', ['SnowLuma', 'OneBot', '10001']),
).toMatchObject({
acceptable: false,
reason: 'guessable',
});
});
it('accepts a sufficiently long, hard-to-guess token', () => {
+18 -5
View File
@@ -43,9 +43,14 @@ describe('mapWithConcurrency', () => {
});
it('runs everything in one batch when concurrency >= length', async () => {
let peak = 0, inFlight = 0;
let peak = 0,
inFlight = 0;
const out = await mapWithConcurrency([1, 2, 3], 10, async (n) => {
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
inFlight++;
peak = Math.max(peak, inFlight);
await tick();
inFlight--;
return n;
});
expect(out).toEqual([1, 2, 3]);
expect(peak).toBe(3);
@@ -53,15 +58,23 @@ describe('mapWithConcurrency', () => {
it('returns [] for an empty input without calling fn', async () => {
let called = 0;
const out = await mapWithConcurrency([], 4, async (n) => { called++; return n; });
const out = await mapWithConcurrency([], 4, async (n) => {
called++;
return n;
});
expect(out).toEqual([]);
expect(called).toBe(0);
});
it('treats concurrency < 1 as 1 (fully serial)', async () => {
let peak = 0, inFlight = 0;
let peak = 0,
inFlight = 0;
await mapWithConcurrency([1, 2, 3], 0, async (n) => {
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
inFlight++;
peak = Math.max(peak, inFlight);
await tick();
inFlight--;
return n;
});
expect(peak).toBe(1);
});
+34
View File
@@ -0,0 +1,34 @@
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
+3 -3
View File
@@ -7,9 +7,9 @@ describe('sanitizeLogLine', () => {
});
it('removes OSC hyperlinks without removing their visible label', () => {
expect(
sanitizeLogLine('\x1b]8;;https://example.com\x07visible\x1b]8;;\x07'),
).toBe('visible');
expect(sanitizeLogLine('\x1b]8;;https://example.com\x07visible\x1b]8;;\x07')).toBe(
'visible',
);
});
it('removes terminal control-string payloads', () => {
+47 -51
View File
@@ -1,9 +1,5 @@
import { describe, expect, it } from 'vitest';
import {
redactLogMessage,
renderParamsVerbose,
summarizeParams,
} from '../src/log-summary';
import { redactLogMessage, renderParamsVerbose, summarizeParams } from '../src/log-summary';
describe('summarizeParams', () => {
it('renders null/undefined as {}', () => {
@@ -22,10 +18,10 @@ describe('summarizeParams', () => {
});
it('quotes string fields, collapses nested values, truncates long strings', () => {
expect(summarizeParams({ a: 1, b: 'x', c: { d: 1 }, e: [1, 2] }))
.toBe('a=1 b="x" c={...} e=[len=2]');
expect(summarizeParams({ s: 'x'.repeat(50) }))
.toBe(`s="${'x'.repeat(40)}..."`);
expect(summarizeParams({ a: 1, b: 'x', c: { d: 1 }, e: [1, 2] })).toBe(
'a=1 b="x" c={...} e=[len=2]',
);
expect(summarizeParams({ s: 'x'.repeat(50) })).toBe(`s="${'x'.repeat(40)}..."`);
});
it('redacts authentication fields without exposing their values', () => {
@@ -50,18 +46,22 @@ describe('summarizeParams', () => {
});
it('does not treat sensitive substrings inside ordinary keys as credentials', () => {
expect(summarizeParams({
expect(
summarizeParams({
retoken: 'visible',
cookietown: 'visible',
myauthorization: 'visible',
})).toBe(
'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;
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);
@@ -87,9 +87,7 @@ describe('redactLogMessage', () => {
'password=secret Authorization: Bearer bearer-secret cookie="cookie secret" password change required',
);
expect(out).toBe(
'password=*** Authorization: *** cookie=*** password change required',
);
expect(out).toBe('password=*** Authorization: *** cookie=*** password change required');
});
it('redacts quoted object keys, Basic auth, and complete Cookie values', () => {
@@ -110,15 +108,13 @@ describe('redactLogMessage', () => {
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=/',
'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).toBe('Authorization: ***\nauthorization=***\nAuthorization: *** Cookie=***');
expect(out).not.toMatch(
/alice|realm|digest-secret|AKID|SignedHeaders|aws-secret|bearer-secret|cookie-secret|Path=/,
);
@@ -129,40 +125,37 @@ describe('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(
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',
)).toBe('retoken=value cookietown=value myauthorization=value');
);
});
it('redacts leading separator and numeric authentication keys without matching larger words', () => {
expect(redactLogMessage(
expect(
redactLogMessage(
'_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret retoken=visible',
)).toBe('_token=*** --password=*** 2faToken=*** 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=***');
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: ***');
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',
'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=***');
@@ -174,19 +167,21 @@ describe('redactLogMessage', () => {
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',
'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(
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',
)).toBe('retoken=value cookietown=value myauthorization=value');
);
});
});
@@ -224,8 +219,9 @@ describe('renderParamsVerbose', () => {
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}}');
expect(renderParamsVerbose({ left: shared, right: shared })).toBe(
'{left:{value:1},right:{value:1}}',
);
});
it('renders nested structure with primitives intact', () => {
+51 -27
View File
@@ -18,11 +18,7 @@ vi.mock('../src/log-file-transport', () => ({
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
@@ -44,8 +40,13 @@ describe('logger UIN slot padding', () => {
afterEach(() => {
(process.stdout as unknown as { isTTY: boolean | undefined }).isTTY = prevTTY;
if (prevNoColor === undefined) delete process.env.NO_COLOR;
else process.env.NO_COLOR = prevNoColor;
if (prevNoColor === undefined) {
delete process.env.NO_COLOR;
} else {
process.env.NO_COLOR = prevNoColor;
}
vi.restoreAllMocks();
});
@@ -60,6 +61,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));
@@ -78,25 +86,40 @@ describe('logger UIN slot padding', () => {
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;
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;
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;
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', () => {
@@ -122,7 +145,9 @@ describe('file output gating', () => {
log.warn('warn');
log.error('error');
const messages = fileWriteSpy.mock.calls.map(([line]) => String(line).split('] ').at(-1));
const messages = fileWriteSpy.mock.calls.map(([line]) =>
String(line).split('] ').at(-1),
);
expect(messages).toEqual(testCase.expected);
});
}
@@ -211,17 +236,17 @@ describe('file output gating', () => {
`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',
'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',
'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"}`,
'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');
@@ -254,7 +279,8 @@ describe('file output gating', () => {
/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')
const trace = entries
.filter((entry) => entry.level === 'trace')
.map((entry) => entry.message)
.join('\n');
expect(trace).toContain('trace-password');
@@ -279,9 +305,7 @@ describe('file output gating', () => {
log.trace('trace-hex=001122aabbcc');
log.warn('normal-after');
expect(fresh.getRecentLogs(1).map((entry) => entry.message)).toEqual([
'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',
+75 -37
View File
@@ -18,7 +18,8 @@ describe('normalizeRuntimeConfig', () => {
});
it('passes through valid values', () => {
expect(normalizeRuntimeConfig({
expect(
normalizeRuntimeConfig({
webuiPort: 8080,
hookAutoLoad: true,
webuiHost: '127.0.0.1',
@@ -27,7 +28,8 @@ describe('normalizeRuntimeConfig', () => {
logMaxTotalMb: 2048,
logRetainDays: 0,
logPerUin: true,
})).toEqual({
}),
).toEqual({
webuiPort: 8080,
hookAutoLoad: true,
webuiHost: '127.0.0.1',
@@ -53,22 +55,22 @@ describe('normalizeRuntimeConfig', () => {
});
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/);
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({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({
enabled: true,
});
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('127.0.0.1');
});
@@ -84,19 +86,23 @@ describe('resolveRuntimeEnvOverrides', () => {
});
it('parses port / host / trustProxy from env', () => {
expect(resolveRuntimeEnvOverrides({
expect(
resolveRuntimeEnvOverrides({
SNOWLUMA_WEBUI_PORT: '6700',
SNOWLUMA_WEBUI_HOST: '127.0.0.1',
SNOWLUMA_WEBUI_TRUST_PROXY: '1',
})).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' });
}),
).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' });
});
it('parses log storage overrides including retainDays=0', () => {
expect(resolveRuntimeEnvOverrides({
expect(
resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_MAX_TOTAL_MB: '4096',
SNOWLUMA_LOG_RETAIN_DAYS: '0',
SNOWLUMA_LOG_PER_UIN: '1',
})).toEqual({
}),
).toEqual({
logMaxTotalMb: 4096,
logRetainDays: 0,
logPerUin: true,
@@ -104,24 +110,46 @@ describe('resolveRuntimeEnvOverrides', () => {
});
it('fails fast on invalid log storage overrides', () => {
expect(() => resolveRuntimeEnvOverrides({
expect(() =>
resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_MAX_TOTAL_MB: '0',
})).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
expect(() => resolveRuntimeEnvOverrides({
}),
).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
expect(() =>
resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_RETAIN_DAYS: '-1',
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
expect(() => resolveRuntimeEnvOverrides({
}),
).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
expect(() =>
resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_PER_UIN: 'maybe',
})).toThrow(/SNOWLUMA_LOG_PER_UIN/);
}),
).toThrow(/SNOWLUMA_LOG_PER_UIN/);
});
it('fails fast when converted log storage overrides would be unsafe', () => {
expect(() => resolveRuntimeEnvOverrides({
expect(() =>
resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_MAX_TOTAL_MB: String(Number.MAX_SAFE_INTEGER),
})).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
expect(() => resolveRuntimeEnvOverrides({
}),
).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
expect(() =>
resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_RETAIN_DAYS: String(Number.MAX_SAFE_INTEGER),
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
}),
).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', () => {
@@ -130,7 +158,9 @@ describe('resolveRuntimeEnvOverrides', () => {
});
it('treats trustProxy="0"/"off" as a real override (not absent)', () => {
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({ trustProxy: '0' });
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({
trustProxy: '0',
});
});
});
@@ -139,7 +169,9 @@ describe('updateRuntimeConfig (fs)', () => {
let dir: string;
let prevPortEnv: string | undefined;
beforeEach(async () => {
const fs = await import('fs'); const os = await import('os'); const path = await import('path');
const fs = await import('fs');
const os = await import('os');
const path = await import('path');
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-rt-'));
prevCwd = process.cwd();
process.chdir(dir);
@@ -148,15 +180,21 @@ describe('updateRuntimeConfig (fs)', () => {
});
afterEach(async () => {
process.chdir(prevCwd);
if (prevPortEnv === undefined) delete process.env.SNOWLUMA_WEBUI_PORT;
else process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv;
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 () => {
const { updateRuntimeConfig } = await import('../src/runtime');
const fs = await import('fs'); const path = await import('path');
const fs = await import('fs');
const path = await import('path');
const out = updateRuntimeConfig({ webuiHost: '127.0.0.1', webuiTls: { enabled: true } });
expect(out.webuiHost).toBe('127.0.0.1');
expect(out.webuiTls).toEqual({ enabled: true });
@@ -167,7 +205,8 @@ describe('updateRuntimeConfig (fs)', () => {
it('does NOT bake an env-overridden port into the persisted file', async () => {
const { updateRuntimeConfig } = await import('../src/runtime');
const fs = await import('fs'); const path = await import('path');
const fs = await import('fs');
const path = await import('path');
process.env.SNOWLUMA_WEBUI_PORT = '9999';
updateRuntimeConfig({ webuiHost: '127.0.0.1' });
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
@@ -183,8 +222,7 @@ describe('updateRuntimeConfig (fs)', () => {
throw Object.assign(new Error('disk replacement failed'), { code: 'EIO' });
});
expect(() => updateRuntimeConfig({ logRetainDays: 0 }))
.toThrow(/disk replacement failed/);
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([]);
});
@@ -5,7 +5,10 @@ import { createSingleFlightCache } from '../src/single-flight-cache';
function deferred<T>() {
let resolve!: (v: T) => void;
let reject!: (e: unknown) => void;
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
@@ -13,7 +16,11 @@ describe('SingleFlightCache', () => {
it('caches within the TTL and reloads once expired', async () => {
let clock = 1000;
const load = vi.fn(async (k: string) => `${k}@${clock}`);
const cache = createSingleFlightCache<string, string>({ ttlMs: 100, load, now: () => clock });
const cache = createSingleFlightCache<string, string>({
ttlMs: 100,
load,
now: () => clock,
});
expect(await cache.get('a')).toBe('a@1000');
clock = 1050; // still fresh (< 100)
@@ -51,7 +58,11 @@ describe('SingleFlightCache', () => {
it('force bypasses the freshness check but still joins an in-flight load', async () => {
let clock = 0;
const load = vi.fn(async (k: string) => `${k}@${clock}`);
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load, now: () => clock });
const cache = createSingleFlightCache<string, string>({
ttlMs: 10_000,
load,
now: () => clock,
});
expect(await cache.get('a')).toBe('a@0'); // 1 load, cached fresh
clock = 5; // still fresh
@@ -71,7 +82,11 @@ describe('SingleFlightCache', () => {
it('shouldCache=false leaves the entry uncached (next call reloads) but still de-dupes in-flight', async () => {
let n = 0;
const load = vi.fn(async () => ({ error: true as boolean, n: ++n }));
const cache = createSingleFlightCache({ ttlMs: 10_000, load, shouldCache: (v) => !v.error });
const cache = createSingleFlightCache({
ttlMs: 10_000,
load,
shouldCache: (v) => !v.error,
});
// concurrent callers still share one load...
const [a, b] = await Promise.all([cache.get('k'), cache.get('k')]);
@@ -95,7 +110,11 @@ describe('SingleFlightCache', () => {
let attempt = 0;
const load = vi.fn(async () => {
attempt++;
if (attempt === 1) throw new Error('boom');
if (attempt === 1) {
throw new Error('boom');
}
return 'ok';
});
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
@@ -128,4 +147,18 @@ describe('SingleFlightCache', () => {
await cache.get('b');
expect(load).toHaveBeenCalledTimes(5);
});
it('allows retry when a loader throws before returning its promise', async () => {
const load = vi
.fn<() => Promise<string>>()
.mockImplementationOnce(() => {
throw new Error('failed before request');
})
.mockResolvedValue('recovered');
const cache = createSingleFlightCache({ ttlMs: 1000, load });
await expect(cache.get('key')).rejects.toThrow('failed before request');
await expect(cache.get('key')).resolves.toBe('recovered');
expect(load).toHaveBeenCalledTimes(2);
});
});
+3 -3
View File
@@ -20,8 +20,7 @@ afterEach(() => {
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');
expect(renderTraceBytes(new Uint8Array([0x00, 0x01, 0x0f, 0x10, 0xff]))).toBe('00010f10ff');
});
it('renders only the addressed Uint8Array view', () => {
@@ -51,7 +50,8 @@ describe('TRACE diagnostics contract', () => {
expect(afterDisabled).toBe(beforeDisabled + 1);
setLogLevel('trace');
const observeContext = () => runWithTraceRequest(async () => {
const observeContext = () =>
runWithTraceRequest(async () => {
const before = currentRequestId();
await Promise.resolve();
const after = currentRequestId();
+11 -6
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.14.4",
"version": "1.14.22",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -44,21 +44,26 @@
"@snowluma/bridge": "workspace:*",
"@snowluma/common": "workspace:*",
"@snowluma/onebot": "workspace:*",
"@snowluma/protocol": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/protocol": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/websocket": "workspace:*"
"@snowluma/websocket": "workspace:*",
"otpauth": "^9.5.1"
},
"devDependencies": {
"@hono/node-server": "^1.19.14",
"@hono/node-server": "^1.19.15",
"@rollup/plugin-node-resolve": "^16.0.3",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"hono": "^4.12.25",
"hono": "^4.12.34",
"tsx": "^4.21.0",
"typescript": "catalog:",
"vite": "catalog:",
"vite-plugin-cp": "^6.0.3",
"vitest": "^4.1.4"
"vitest": "^4.1.4",
"@snowluma/sqlite": "workspace:*"
},
"engines": {
"node": ">=24"
}
}
+5 -5
View File
@@ -1,8 +1,5 @@
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
import {
getCollectionList,
type CollectionListResult,
} from '@snowluma/protocol/web/collection';
import { getCollectionList, type CollectionListResult } from '@snowluma/protocol/web/collection';
import type { BridgeContext } from '../bridge-context';
const COLLECTION_DOMAIN = 'weiyun.com';
@@ -16,7 +13,10 @@ export class CollectionApi {
domainList: [COLLECTION_DOMAIN],
});
const pskey = domainPskeyMap.get(COLLECTION_DOMAIN);
if (!pskey) throw new Error(`QQ did not return a p_skey for ${COLLECTION_DOMAIN}`);
if (!pskey) {
throw new Error(`QQ did not return a p_skey for ${COLLECTION_DOMAIN}`);
}
return getCollectionList({
uin: this.ctx.identity.uin,
+294 -126
View File
@@ -1,9 +1,17 @@
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,
@@ -11,12 +19,23 @@ import {
} from '@snowluma/protocol/oidb-services/contacts/fetch-robot-uin-ranges';
import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile';
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
import {
fetchQidianCorpInfo as fetchQidianCorpInfoWire,
type QidianCorpInfo,
} from '@snowluma/protocol/services/qidian/fetch-corp-info';
import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark';
import { GetGroupRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-group-recommend-ark';
import {
SendTuwenArk,
type SendTuwenArkParams,
} from '@snowluma/protocol/oidb-services/contacts/send-tuwen-ark';
import { SetFriendCategory } from '@snowluma/protocol/oidb-services/contacts/set-friend-category';
import { toHex } from '@snowluma/common/hex';
import { createLogger } from '@snowluma/common/logger';
import { createSingleFlightCache, type SingleFlightCache } from '@snowluma/common/single-flight-cache';
import {
createSingleFlightCache,
type SingleFlightCache,
} from '@snowluma/common/single-flight-cache';
import type {
FriendCategoryInfo,
FriendInfo,
@@ -30,35 +49,16 @@ import type { BridgeContext } from '../bridge-context';
const log = createLogger('Bridge.Contacts');
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
type FriendPropertySource = {
additional?: Array<{
type?: number;
layer1?: {
properties?: Array<{
code?: number;
value?: string;
}>;
};
}>;
};
interface FriendRosterEntry {
friend: FriendInfo;
categoryId: number;
}
interface FriendCategoryMeta {
categoryId: number;
categoryName: string;
memberCount: number;
sortId: number;
// Official client stores group mute as an expire timestamp (internal 60027 /
// JS groupShutupExpireTime): 0 = off, 0xFFFFFFFF = permanent, otherwise unix
// seconds. `> 0` is wrong — a leftover past expire still looks "on".
function isGroupAllMuted(expireTs?: number, nowSec = Math.floor(Date.now() / 1000)): boolean {
return (expireTs ?? 0) > nowSec;
}
interface FriendRoster {
entries: FriendRosterEntry[];
categories: FriendCategoryMeta[];
entries: FriendListPageEntry[];
categories: FriendListPageCategory[];
}
export interface SetFriendCategoryParams {
@@ -67,29 +67,27 @@ export interface SetFriendCategoryParams {
categoryName?: string;
}
export function buildFriendProperties(raw: FriendPropertySource): Map<number, string> {
const props = new Map<number, string>();
for (const additional of raw.additional ?? []) {
if ((additional.type ?? 0) !== 1 || !additional.layer1) continue;
for (const property of additional.layer1.properties ?? []) {
props.set(property.code ?? 0, property.value ?? '');
}
}
return props;
}
export function permissionToRole(permission: number): string {
switch (permission) {
case 1: return 'owner';
case 2: return 'admin';
default: return 'member';
}
}
export function isRobotUin(uin: number, ranges: readonly RobotUinRange[]): boolean {
return Number.isInteger(uin)
&& uin > 0
&& ranges.some(({ minUin, maxUin }) => uin >= minUin && uin <= maxUin);
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;
@@ -110,11 +108,16 @@ export class ContactsApi {
load: (groupId) => this.fetchGroupMemberListUncached(groupId),
});
private robotUinRangesPromise_: Promise<RobotUinRangeSnapshot> | null = null;
/** groupUin → approval msgseq from a private qun.invite card. Written
* only by IncomingPacketPipeline (and tests). OneBot reads get/find. */
private readonly groupInviteCardSeqs_ = new Map<number, number>();
constructor(private readonly ctx: BridgeContext) {}
private fetchRobotUinRanges(groupId: number): Promise<RobotUinRangeSnapshot> {
if (this.robotUinRangesPromise_) return this.robotUinRangesPromise_;
if (this.robotUinRangesPromise_) {
return this.robotUinRangesPromise_;
}
const pending = FetchRobotUinRanges.invoke(this.ctx).then((snapshot) => {
log.info(
@@ -130,7 +133,10 @@ export class ContactsApi {
// 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;
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,
@@ -151,75 +157,73 @@ 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) ?? '',
},
});
const page = await FetchFriendListPage.invoke(this.ctx, { cookie });
entries.push(...page.entries);
for (const category of page.categories) {
categories.set(category.categoryId, category);
}
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 next = page.cookie;
if (!next?.length) {
break;
}
const next = resp.cookie;
if (!next?.length) break;
const key = toHex(next);
if (seenCookies.has(key)) {
throw new Error(`repeated friend-list cookie ${key}`);
}
seenCookies.add(key);
cookie = next;
}
const friends = entries.map(entry => entry.friend);
const friends = entries.map((entry) => entry.friend);
this.ctx.identity.rememberFriends(friends);
return { entries, categories: [...categories.values()] };
}
async fetchFriendList(): Promise<FriendInfo[]> {
const roster = await this.fetchFriendRoster();
return roster.entries.map(entry => entry.friend);
return roster.entries.map((entry) => entry.friend);
}
async fetchFriendCategories(): Promise<FriendCategoryInfo[]> {
const roster = await this.fetchFriendRoster();
const buckets = new Map(
roster.categories.map(category => [category.categoryId, [] as FriendInfo[]]),
roster.categories.map((category) => [category.categoryId, [] as FriendInfo[]]),
);
for (const entry of roster.entries) {
const bucket = buckets.get(entry.categoryId);
if (!bucket) {
throw new Error(
`friend roster references missing category ${entry.categoryId} `
+ `(${roster.entries.length} friends total)`,
`friend roster references missing category ${entry.categoryId} ` +
`(${roster.entries.length} friends total)`,
);
}
bucket.push(entry.friend);
}
return roster.categories.map(category => {
return roster.categories.map((category) => {
const friends = buckets.get(category.categoryId)!;
if (friends.length !== category.memberCount) {
log.warn(
'friend category member count mismatch category=%d server=%d assembled=%d',
@@ -228,41 +232,54 @@ export class ContactsApi {
friends.length,
);
}
return { ...category, friends };
});
}
async setFriendCategory(params: SetFriendCategoryParams): Promise<void> {
const selectorCount = Number(params.categoryId !== undefined)
+ Number(params.categoryName !== undefined);
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);
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);
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);
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]!;
}
@@ -281,6 +298,7 @@ export class ContactsApi {
async fetchGroupList(): Promise<QQGroupInfo[]> {
const resp = await FetchGroupList.invoke(this.ctx);
const groups: QQGroupInfo[] = [];
for (const raw of resp.groups ?? []) {
groups.push({
groupId: raw.groupUin ?? 0,
@@ -293,9 +311,14 @@ export class ContactsApi {
// is not in the list (0x88D_0 detail only), so it stays undefined here.
createTime: raw.info?.createdTime ?? 0,
memo: raw.info?.announcement || raw.info?.description || '',
allMuted: (raw.info?.shutUpAllTimestamp ?? 0) > 0,
// #490: expose the description alongside `memo`. QQ fills in either
// field alone, so folding both into `memo` made the description
// unreachable whenever an announcement was also set.
description: raw.info?.description ?? '',
allMuted: isGroupAllMuted(raw.info?.shutUpAllTimestamp),
});
}
this.ctx.identity.rememberGroups(groups);
return groups;
}
@@ -308,10 +331,17 @@ export class ContactsApi {
* joined-groups roster / get_group_list.
*/
async fetchGroupDetail(groupId: number): Promise<QQGroupInfo | null> {
if (!(groupId > 0)) return null;
if (!(groupId > 0)) {
return null;
}
const resp = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
const r = resp.groupInfo?.results;
if (!r) return null;
if (!r) {
return null;
}
return {
groupId,
groupName: r.name ?? '',
@@ -320,11 +350,13 @@ export class ContactsApi {
memberMax: Number(r.maxMemberCount ?? 0n),
members: new Map(),
// #197: the detail is the only source of `level`; it also carries
// createTime + the notice preview (memo).
// createTime + the notice preview (memo). `description` is deliberately
// left unset — 0x88D_0 has no description tag, so for a group the bot
// hasn't joined there is nothing to report (#490).
createTime: Number(r.createTime ?? 0n),
level: Number(r.level ?? 0n),
memo: r.noticePreview ?? '',
allMuted: (r.shutUpAllTimestamp ?? 0) > 0,
allMuted: isGroupAllMuted(r.shutUpAllTimestamp),
};
}
@@ -342,27 +374,15 @@ export class ContactsApi {
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 ?? '',
isRobot: false,
role: permissionToRole(raw.permission ?? 0),
level: raw.level?.level ?? 0,
title: raw.specialTitle ?? '',
joinTime: raw.joinTimestamp ?? 0,
lastSentTime: raw.lastMsgTimestamp ?? 0,
shutUpTime: raw.shutUpTimestamp ?? 0,
});
}
token = resp.token ?? '';
const page = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token });
members.push(...page.members);
token = page.token;
} while (token);
const robotSnapshot = await robotSnapshotPromise;
for (const member of members) {
member.isRobot = isRobotUin(member.uin, robotSnapshot.ranges);
}
@@ -383,57 +403,204 @@ export class ContactsApi {
* .Create(targetUid)` path. */
async fetchUserProfileByUid(uid: string): Promise<UserProfileInfo> {
const info = await FetchUserProfileByUid.invoke(this.ctx, { uid });
if (info.uin > 0) this.ctx.identity.rememberUserProfile(info);
if (info.uin > 0) {
this.ctx.identity.rememberUserProfile(info);
}
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[]> {
const resp = await FetchDownloadRkeys.invoke(this.ctx);
const result: DownloadRKeyInfo[] = [];
for (const entry of resp.downloadRkey?.rkeys ?? []) {
const rkey = entry.rkey ?? '';
const type = entry.type ?? 0;
if (rkey && type) {
result.push({
rkey,
@@ -444,6 +611,7 @@ export class ContactsApi {
});
}
}
return result;
}
}
+130 -39
View File
@@ -3,7 +3,10 @@ import {
FetchAiVoiceList,
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 {
GetStrangerStatus,
type StrangerStatus as NamespaceStrangerStatus,
} from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
import {
GetGroupTodoList,
type GroupTodoListItem as NamespaceGroupTodoListItem,
@@ -46,7 +49,7 @@ export const AiVoiceChatType = {
Sound: 1,
Sing: 2,
} as const;
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
export type AiVoiceChatType = (typeof AiVoiceChatType)[keyof typeof AiVoiceChatType];
export type AiVoiceCategory = NamespaceAiVoiceCategory;
export interface AiVoiceItem {
@@ -72,18 +75,33 @@ function normalizeMediaUuid(value: unknown): string {
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;
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)}`;
if (uuid) {
return `uuid:${uuid.slice(-12)}`;
}
return 'missing';
}
@@ -121,7 +139,11 @@ export class ExtrasApi {
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
try {
const status = await GetStrangerStatus.invoke(this.ctx, { uin });
if (!status) log.warn('user status query returned no status target=%d', uin);
if (!status) {
log.warn('user status query returned no status target=%d', uin);
}
return status;
} catch (error) {
log.warn(
@@ -135,7 +157,10 @@ export class ExtrasApi {
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise<AiVoiceCategory[]> {
fetchAiVoiceList(
groupId: number,
chatType: AiVoiceChatType | number,
): Promise<AiVoiceCategory[]> {
return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType });
}
@@ -158,9 +183,17 @@ export class ExtrasApi {
maxRetries = 30,
): Promise<MediaIndexNode> {
// Random 32-bit session id — server uses this to deduplicate polls.
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
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 });
const node = await FetchAiVoice.invoke(this.ctx, {
groupId,
voiceId,
text,
chatType,
sessionId,
});
if (node) {
log.debug(
'AI voice synthesis completed group=%d media=%s polls=%d',
@@ -171,6 +204,7 @@ export class ExtrasApi {
return node as MediaIndexNode;
}
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
}
@@ -200,26 +234,46 @@ export class ExtrasApi {
});
const claim = (event: GroupMessageEvent): boolean => {
if (receiptSettled) return false;
if (receiptSettled) {
return false;
}
const key = `${event.groupId}:${event.msgSeq}:${event.msgId}`;
if (this.claimedAiVoiceReceiptKeys.has(key)) return false;
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);
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 (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;
@@ -228,36 +282,50 @@ export class ExtrasApi {
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) {
if (fingerprint === 'missing') {
throw new Error(
`AI voice was published but receipt correlation overflowed after ${AI_VOICE_CANDIDATE_LIMIT} `
+ `unmatched self voice messages (group=${groupId} media=${fingerprint})`,
'AI voice was published but QQ returned no exact media identifier for receipt correlation',
);
}
const event = buffered ?? await Promise.race([
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})`,
));
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}`);
throw new Error(
`AI voice receipt carried invalid message sequence: ${event.msgSeq}`,
);
}
log.debug(
@@ -271,7 +339,10 @@ export class ExtrasApi {
sequence: event.msgSeq,
};
} finally {
if (timeout) clearTimeout(timeout);
if (timeout) {
clearTimeout(timeout);
}
unsubscribe();
}
}
@@ -295,38 +366,58 @@ export class ExtrasApi {
? {
type: 1,
groupItem: {
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), groupUin: BigInt(input.peerUin),
fileId: input.fileId ?? 0, md5, duration: input.duration, size: input.size,
format: input.format, uuid: input.uuid,
msgId: BigInt(input.msgId),
senderUin: BigInt(input.senderUin),
groupUin: BigInt(input.peerUin),
fileId: input.fileId ?? 0,
md5,
duration: input.duration,
size: input.size,
format: input.format,
uuid: input.uuid,
},
}
: {
type: 2,
c2cItem: {
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), receiverUin: BigInt(input.peerUin),
uuid: input.uuid, duration: input.duration, size: input.size, format: input.format, md5,
msgId: BigInt(input.msgId),
senderUin: BigInt(input.senderUin),
receiverUin: BigInt(input.peerUin),
uuid: input.uuid,
duration: input.duration,
size: input.size,
format: input.format,
md5,
},
};
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'ptt translate request failed');
}
const resp = protobuf_decode<PttTransResp>(result.responseData);
const item = input.isGroup ? resp?.groupResult : resp?.c2cResult;
if (item?.errCode) {
// Diagnostic (#165 备选): correlate QQ's errCode with the request fields we
// sourced from cache, to tell a server-side ASR failure apart from our own
// missing/zero field (md5/format/uuid). Behaviour unchanged — still throws.
log.warn(
'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d',
item.errCode, input.isGroup,
item.errCode,
input.isGroup,
input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY',
input.format, input.uuid ? 'set' : 'EMPTY', input.duration, input.size,
input.format,
input.uuid ? 'set' : 'EMPTY',
input.duration,
input.size,
);
throw new Error(`ptt translate failed: error=${item.errCode}`);
}
return item?.text ?? ''; // '' = transcribing async; caller awaits the push
}
+551 -102
View File
@@ -17,13 +17,226 @@ 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 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;
@@ -55,27 +268,38 @@ 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');
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 !== ''
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');
if (!match) {
throw new Error('get_fileset_id: expected an official QQ share URL');
}
try {
code = decodeURIComponent(match[1]);
} catch (error) {
@@ -87,9 +311,11 @@ function officialQfileShareUrl(input: string): string {
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)}`;
}
@@ -99,42 +325,64 @@ async function rejectShareResponse(response: Response, error: Error): Promise<ne
} 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'));
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');
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;
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 {
@@ -146,18 +394,28 @@ async function readSharePage(response: Response): Promise<string> {
// 避免命中服务端秒传缓存。
const CRC_TABLE: Uint32Array = (() => {
const table = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
for (let k = 0; k < 8; k++) {
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
}
table[n] = c >>> 0;
}
return table;
})();
function crc32(buf: Buffer): number {
let c = 0xFFFFFFFF;
for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xFF] ^ (c >>> 8);
return (c ^ 0xFFFFFFFF) >>> 0;
let c = 0xffffffff;
for (let i = 0; i < buf.length; i++) {
c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
}
return (c ^ 0xffffffff) >>> 0;
}
function pngChunk(type: string, data: Buffer): Buffer {
@@ -177,24 +435,34 @@ function generatePng(width: number, height: number): Buffer {
const b = Math.floor(Math.random() * 256);
const rowLen = 1 + width * 3;
const raw = Buffer.alloc(rowLen * height);
for (let y = 0; y < height; y++) {
const off = y * rowLen;
raw[off] = 0; // filter none
for (let x = 0; x < width; x++) {
raw[off + 1 + x * 3] = r;
raw[off + 1 + x * 3 + 1] = g;
raw[off + 1 + x * 3 + 2] = b;
}
}
const compressed = deflateSync(raw);
const sig = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
const sig = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(width, 0);
ihdr.writeUInt32BE(height, 4);
ihdr[8] = 8; // bit depth
ihdr[9] = 2; // color type RGB
ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0;
return Buffer.concat([sig, pngChunk('IHDR', ihdr), pngChunk('IDAT', compressed), pngChunk('IEND', Buffer.alloc(0))]);
ihdr[10] = 0;
ihdr[11] = 0;
ihdr[12] = 0;
return Buffer.concat([
sig,
pngChunk('IHDR', ihdr),
pngChunk('IDAT', compressed),
pngChunk('IEND', Buffer.alloc(0)),
]);
}
export class FlashTransferApi {
@@ -216,23 +484,43 @@ 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,
filesetUuid: string,
fileIndex: number = 1,
): Promise<{ url: string; fileName: string; fileSize: number } | null> {
for (let attempt = 0; ; attempt++) {
const metas = await GetDownloadUrl.invoke(this.ctx, { filesetUuid });
const meta = metas.find((m) => m.fileIndex === fileIndex);
if (!meta || !meta.fileId) return null;
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;
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));
}
}
/**
* 获取闪传文件下载链接(get_flash_file_url)。主文件直链走 0x12a9 sub=200
* (0x93d3 的 downloadUrl 是缩略图 appid=14903,非主文件)。多文件 fileset 用
@@ -240,7 +528,11 @@ export class FlashTransferApi {
*/
async getFlashFileUrl(filesetUuid: string, fileIndex: number = 1): Promise<string> {
const dl = await this.getFileDownload(filesetUuid, fileIndex);
if (!dl || !dl.url) throw new Error('get_flash_file_url: no download url available');
if (!dl || !dl.url) {
throw new Error('get_flash_file_url: no download url available');
}
return dl.url;
}
@@ -253,7 +545,11 @@ export class FlashTransferApi {
opts?: { fileName?: string; fileIndex?: number },
): Promise<{ url: string; fileName: string; fileSize: number }> {
const dl = await this.getFileDownload(filesetUuid, opts?.fileIndex ?? 1);
if (!dl || !dl.url) throw new Error('download_fileset: no download url available');
if (!dl || !dl.url) {
throw new Error('download_fileset: no download url available');
}
return dl;
}
@@ -283,13 +579,21 @@ export class FlashTransferApi {
* 发送闪传文件(send_flash_msg,0x93d7)。私聊:user_id→uid;群聊:group_id 直接用。
* 0x93d7 响应无 message_id(分享 fileset,非传统消息),OneBot 层 message_id 由 action 返回 0。
*/
async sendFlashMsg(filesetUuid: string, target: { userId?: number; groupId?: number }): Promise<void> {
async sendFlashMsg(
filesetUuid: string,
target: { userId?: number; groupId?: number },
): Promise<void> {
if (target.groupId) {
await SendFlashMsg.invoke(this.ctx, { groupId: target.groupId, filesetUuid });
return;
}
const userId = target.userId;
if (!userId) throw new Error('send_flash_msg: user_id or group_id is required');
if (!userId) {
throw new Error('send_flash_msg: user_id or group_id is required');
}
const targetUid = await this.ctx.identity.resolveUid(userId);
await SendFlashMsg.invoke(this.ctx, { targetUid, filesetUuid });
}
@@ -302,48 +606,58 @@ export class FlashTransferApi {
async getFilesetIdByCode(shareCode: string): Promise<string> {
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')) {
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'));
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');
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');
}
return m[1];
}
// ─────────────── 文件上传 ───────────────
/**
* 文件扩展名 → 闪传类型码映射。typeCode 用于 0x93cf f3,formatCode 用于
* 0x93d0 commit f7 与 0x12a9 filesetWrap.f7(两者同值)。mp4 → 2,rar/zip → 4。
* 未知扩展名按媒体类处理(formatCode=2),服务端按文件名扩展名判定。
* 文件扩展名 → 闪传类型码。typeCode 用于 0x93cf f3(卡片粗类:压缩包/媒体);
* formatCode 用于 0x93d0 commit f7 与 0x12a9 filesetWrap.f7,决定对端图标
* (png=26,mp4=2,zip=4,未知=11)。
*/
private static fileTypeCode(fileName: string): { typeCode: number; formatCode: number } {
const ext = fileName.toLowerCase().match(/\.([^.]+)$/)?.[1] ?? '';
switch (ext) {
case 'rar': return { typeCode: 2, formatCode: 4 };
case 'zip': return { typeCode: 6, formatCode: 4 };
case '7z': case 'gz': case 'tar': case 'bz2': return { typeCode: 2, formatCode: 4 };
case 'png': case 'jpg': case 'jpeg': case 'bmp': case 'gif': case 'webp':
case 'mp4': case 'mov': case 'avi': case 'mkv':
return { typeCode: 7, formatCode: 2 };
default: return { typeCode: 7, formatCode: 2 };
}
return { typeCode: flashApplyTypeCode(ext), formatCode: flashFormatCode(ext) };
}
/** 构造 sub=103 的 fileId(客户端生成的 protobuf,base64url 编码)。
@@ -377,12 +691,26 @@ 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];
if (fileList.length === 0) throw new Error('create_flash_task: files is empty');
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,
nickname: this.ctx.identity.nickname,
@@ -390,88 +718,169 @@ 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 }[] = [];
const items: StagedFlashItem[] = [];
try {
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 source = fileList[i]!.file;
if (!source) {
throw new Error('create_flash_task: files is empty');
}
// 申请 fileset。多文件时 fileName 用「<首文件名>等N个文件」、fileSize 用总和,
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 = isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName;
const totalSize = items.reduce((s, it) => s + it.bytes.length, 0);
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,
fileName: filesetName,
origName: filesetName,
fileSize: totalSize,
typeCode,
uploader,
});
const filesetUuid = apply.filesetUuid;
if (!filesetUuid) throw new Error('apply fileset failed: missing uuid');
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,
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: typeof items[0]; rkey: string; sha1StateV: Uint8Array[]; sliceCount: number }[] = [];
const prepared: {
it: StagedFlashItem;
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 });
const p = await this.prepareAndApply(filesetUuid, it);
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);
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()));
}
}
/**
* 阶段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;
const src = await FileChunkSource.open(filePath, fileSize);
try {
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 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,
@@ -489,6 +898,9 @@ export class FlashTransferApi {
const bodyBytes = protobuf_encode<FlashSliceUploadBody>(body);
await this.postSliceupload(bodyBytes, `${fileName} slice ${i}`);
}
} finally {
await src.close();
}
}
/**
@@ -497,21 +909,27 @@ export class FlashTransferApi {
*/
private async postSliceupload(bodyBytes: Uint8Array, label: string): Promise<void> {
const resp = await fetch('https://multimedia.qfile.qq.com/sliceupload', {
method: 'POST', body: bodyBytes,
method: 'POST',
body: bodyBytes,
headers: {
Accept: '*/*', Connection: 'Keep-Alive',
Accept: '*/*',
Connection: 'Keep-Alive',
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)',
Pragma: 'no-cache', 'Cache-Control': 'no-cache',
Pragma: 'no-cache',
'Cache-Control': 'no-cache',
'Content-Length': String(bodyBytes.length),
'X-Retried-Times': '1',
},
});
if (!resp.ok) {
const errBody = await resp.text().catch(() => '');
throw new Error(`${label} failed: HTTP ${resp.status} ${errBody.slice(0, 300)}`);
}
const respBuf = new Uint8Array(await resp.arrayBuffer());
const sliceResp = protobuf_decode<FlashSliceUploadResp>(respBuf);
if (sliceResp.status !== 'success') {
throw new Error(`${label} failed: ${sliceResp.status || 'no status in response'}`);
}
@@ -524,36 +942,67 @@ export class FlashTransferApi {
* fileIndex 为缩略图在 fileset 内的序号(主文件之后递增),与 commit f6 对齐。
*/
private async uploadThumbnail(
filesetUuid: string, mainFileUuid: string, thumbType: 'png' | 'jpg', fileIndex: number,
filesetUuid: string,
mainFileUuid: string,
thumbType: 'png' | 'jpg',
fileIndex: number,
): Promise<void> {
// 526x360 是 QQ 客户端缩略图尺寸;1x1 会被服务端拒(HTTP 400,宽高太小)。
const width = 526, height = 360;
const width = 526,
height = 360;
const thumbBytes = generatePng(width, height); // 随机纯色,SHA1 不同避免秒传
const appid = thumbType === 'png' ? 14903 : 14902; // png=14903, jpg=14902
const fileUuid = thumbType === 'png' ? randomUUID() : mainFileUuid; // png 独立,jpg 挂主文件
const fileName = thumbType === 'png'
const fileName =
thumbType === 'png'
? `${randomUUID().slice(0, 8)}_one.png`
: `${createHash('md5').update(thumbBytes).digest('hex').slice(0, 32)}.jpg`;
const hashes = computeHashes(new Uint8Array(thumbBytes));
const fileSize = thumbBytes.length;
const thumbFormatCode = thumbType === 'png' ? 26 : 2; // png缩略图=26, jpg缩略图=2
const rkey = await PrepareUpload.invoke(this.ctx, {
filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex,
fileIndex, formatCode: thumbFormatCode, thumbType, width, height,
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,
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 = {
field1: 0, appid, field3: 2,
field1: 0,
appid,
field3: 2,
payload: {
field1: {}, rkey,
start: 0, end: fileSize - 1,
field1: {},
rkey,
start: 0,
end: fileSize - 1,
sha1: new Uint8Array(hashes.sha1),
sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) },
chunk: new Uint8Array(thumbBytes),
+343 -127
View File
@@ -10,7 +10,11 @@ import type {
} from '@snowluma/proto-defs/longmsg';
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 type {
ForwardNodePayload,
MessageElement,
MessageElementOf,
} from '@snowluma/protocol/events';
import {
assertWindowShakeSendPolicy,
MessageElementValidationError,
@@ -23,7 +27,9 @@ import type { Bridge } from '../bridge';
import type { BridgeContext, UploadedFileMeta } from '../bridge-context';
import { resolveSelfUid, toInt } from './shared';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
function asBridge(ctx: BridgeContext): Bridge {
return ctx as unknown as Bridge;
}
// Module-scoped cache, keyed by res_id. Survives only for the lifetime
// of the process — that's enough because OneBot clients typically
@@ -77,12 +83,18 @@ interface ForwardUploadResult {
// module just for one call. Mirrors `highway/pipeline.ts::hexToBytes`.
function hexToBytesLocal(hex: string): Uint8Array {
const s = hex.trim();
if (!s) return new Uint8Array(0);
if (!s) {
return new Uint8Array(0);
}
const len = s.length >> 1;
const out = new Uint8Array(len);
for (let i = 0; i < len; i++) {
out[i] = parseInt(s.substr(i * 2, 2), 16);
}
return out;
}
@@ -93,7 +105,10 @@ async function buildForwardPushBody(
userUid?: string,
): Promise<PushMsgBody> {
const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin);
if (fromUin <= 0) throw new Error('forward node user uin is invalid');
if (fromUin <= 0) {
throw new Error('forward node user uin is invalid');
}
const nickname = node.nickname.trim() || String(fromUin);
// image/record/video upload inside a forward node must be scoped to the
@@ -108,7 +123,8 @@ async function buildForwardPushBody(
// result=79; notOnlineFile via PbSendMsg doesn't render), but the
// long-msg upload service stores the bytes verbatim and the
// receiver decodes them through the normal msg-push path.
const sendCtx = groupId !== undefined
const sendCtx =
groupId !== undefined
? { bridge, groupId, forwardFake: true, scene: 'forward' as const }
: userUid
? { bridge, userUid, forwardFake: true, scene: 'forward' as const }
@@ -130,8 +146,10 @@ async function buildForwardPushBody(
// a live c2c send. Group nodes ignore this branch entirely (the
// transElem(24) elems[] entry above covers them).
let msgContent: Uint8Array | undefined;
if (groupId === undefined) {
const fileEl = node.elements.find(e => e.type === 'file' && e.fileId);
const fileEl = node.elements.find((e) => e.type === 'file' && e.fileId);
if (fileEl) {
// Honour inline segment fields first; fall back to the upload
// metadata cache (populated by upload_private_file). Without
@@ -198,20 +216,29 @@ async function buildForwardPushBody(
function deriveInnerSource(innerNodes: ForwardNodePayload[], isGroup: boolean): string {
const nicks: string[] = [];
const seen = new Set<string>();
for (const node of innerNodes) {
const name = (node.nickname ?? '').trim();
if (name && !seen.has(name)) {
seen.add(name);
nicks.push(name);
}
if (nicks.length >= 4) break;
if (nicks.length >= 4) {
break;
}
if (nicks.length === 0) return isGroup ? '群聊的聊天记录' : '聊天记录';
}
if (nicks.length === 0) {
return isGroup ? '群聊的聊天记录' : '聊天记录';
}
return `${nicks.join('和')}的聊天记录`;
}
function previewLinesFromNodes(innerNodes: ForwardNodePayload[]): Array<{ text: string }> {
return innerNodes.slice(0, 4).map(node => {
return innerNodes.slice(0, 4).map((node) => {
const name = (node.nickname ?? '').trim() || String(node.userUin || 'QQ用户');
const previewText = previewFromElements(node.elements);
return { text: previewText ? `${name}: ${previewText}` : name };
@@ -220,29 +247,46 @@ function previewLinesFromNodes(innerNodes: ForwardNodePayload[]): Array<{ text:
function previewFromElements(elements: MessageElement[]): string {
for (const elem of elements) {
if (elem.type === 'text' && elem.text) return elem.text.slice(0, 30);
if (elem.type === 'image') return '[图片]';
if (elem.type === 'record') return '[语音]';
if (elem.type === 'video') return '[视频]';
if (elem.type === 'file') return '[文件]';
if (elem.type === 'forward') return '[聊天记录]';
if (elem.type === 'face') return '[表情]';
if (elem.type === 'text' && elem.text) {
return elem.text.slice(0, 30);
}
if (elem.type === 'image') {
return '[图片]';
}
if (elem.type === 'record') {
return '[语音]';
}
if (elem.type === 'video') {
return '[视频]';
}
if (elem.type === 'file') {
return '[文件]';
}
if (elem.type === 'forward') {
return '[聊天记录]';
}
if (elem.type === 'face') {
return '[表情]';
}
}
return '';
}
function cloneNodeWithElements(node: ForwardNodePayload, elements: MessageElement[]): ForwardNodePayload {
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 })),
};
}
@@ -257,13 +301,18 @@ function isCachedFileUsableInTarget(
groupId?: number,
userId?: number,
): boolean {
if (!cached) return true;
if (!cached) {
return true;
}
if (groupId !== undefined) {
return cached.scope === 'group' && cached.groupId === groupId;
}
if (userId !== undefined) {
return cached.scope === 'private' && cached.userId === userId;
}
return true;
}
@@ -274,6 +323,7 @@ function fileNameForUpload(element: MessageElement, cached?: UploadedFileMeta):
function assertPrivateForwardFileCapacity(nodes: ForwardNodePayload[]): void {
for (const node of nodes) {
const fileCount = node.elements.filter((element) => element.type === 'file').length;
if (fileCount > 1) {
throw new MessageElementValidationError(
'UNSENDABLE_TYPE',
@@ -281,7 +331,10 @@ function assertPrivateForwardFileCapacity(nodes: ForwardNodePayload[]): void {
'file',
);
}
if (node.innerForward) assertPrivateForwardFileCapacity(node.innerForward);
if (node.innerForward) {
assertPrivateForwardFileCapacity(node.innerForward);
}
}
}
@@ -292,7 +345,10 @@ function assertNoWindowShakeInForward(nodes: ForwardNodePayload[]): void {
node.elements.length,
'forward',
);
if (node.innerForward) assertNoWindowShakeInForward(node.innerForward);
if (node.innerForward) {
assertNoWindowShakeInForward(node.innerForward);
}
}
}
@@ -303,10 +359,14 @@ export class ForwardApi {
// 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.
if (groupId === undefined) assertPrivateForwardFileCapacity(nodes);
if (groupId === undefined) {
assertPrivateForwardFileCapacity(nodes);
}
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
return resId;
}
@@ -315,10 +375,18 @@ export class ForwardApi {
if (cached.scope === 'group' && cached.groupId !== undefined) {
return this.ctx.apis.groupFile.getUrl(cached.groupId, cached.fileId);
}
if (cached.scope === 'private' && cached.userId !== undefined && cached.fileHash) {
return this.ctx.apis.groupFile.getPrivateUrl(cached.userId, cached.fileId, cached.fileHash);
return this.ctx.apis.groupFile.getPrivateUrl(
cached.userId,
cached.fileId,
cached.fileHash,
);
}
throw new Error('forward file_id belongs to another scope; pass file/base64/url so SnowLuma can re-upload it');
throw new Error(
'forward file_id belongs to another scope; pass file/base64/url so SnowLuma can re-upload it',
);
}
private async uploadForwardFileSource(
@@ -328,21 +396,50 @@ export class ForwardApi {
userId?: number,
): Promise<MessageElementOf<'file'>> {
if (groupId !== undefined) {
const uploaded = await this.ctx.apis.groupFile.upload(groupId, source, name, '/', true, false);
if (!uploaded.fileId) throw new Error('forward group file upload returned no file_id');
const uploaded = await this.ctx.apis.groupFile.upload(
groupId,
source,
name,
'/',
true,
false,
);
if (!uploaded.fileId) {
throw new Error('forward group file upload returned no file_id');
}
const cached = this.ctx.recallUploadedFile(uploaded.fileId);
const element: MessageElement = {
type: 'file',
fileId: uploaded.fileId,
};
const fileName = cached?.fileName || name;
if (fileName) element.fileName = fileName;
if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize;
if (fileName) {
element.fileName = fileName;
}
if (cached?.fileSize !== undefined) {
element.fileSize = cached.fileSize;
}
return element;
}
if (userId !== undefined) {
const uploaded = await this.ctx.apis.groupFile.uploadPrivate(userId, source, name, true, false);
if (!uploaded.fileId) throw new Error('forward private file upload returned no file_id');
const uploaded = await this.ctx.apis.groupFile.uploadPrivate(
userId,
source,
name,
true,
false,
);
if (!uploaded.fileId) {
throw new Error('forward private file upload returned no file_id');
}
const cached = this.ctx.recallUploadedFile(uploaded.fileId);
const element: MessageElement = {
type: 'file',
@@ -350,11 +447,22 @@ export class ForwardApi {
};
const fileName = cached?.fileName || name;
const fileHash = uploaded.fileHash ?? cached?.fileHash ?? '';
if (fileName) element.fileName = fileName;
if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize;
if (fileHash) element.fileHash = fileHash;
if (fileName) {
element.fileName = fileName;
}
if (cached?.fileSize !== undefined) {
element.fileSize = cached.fileSize;
}
if (fileHash) {
element.fileHash = fileHash;
}
return element;
}
throw new Error('forward file source requires group_id or user_id');
}
@@ -363,11 +471,19 @@ export class ForwardApi {
groupId?: number,
userId?: number,
): Promise<MessageElement> {
if (element.type !== 'file') return element;
if (element.type !== 'file') {
return element;
}
const source = (element.url ?? '').trim();
if (source && !element.fileId) {
const uploaded = await this.uploadForwardFileSource(source, fileNameForUpload(element), groupId, userId);
const uploaded = await this.uploadForwardFileSource(
source,
fileNameForUpload(element),
groupId,
userId,
);
return {
...stripFileSource(element),
...uploaded,
@@ -376,7 +492,11 @@ export class ForwardApi {
if (element.fileId) {
const cached = this.ctx.recallUploadedFile(element.fileId);
if (isCachedFileUsableInTarget(cached, groupId, userId)) return element;
if (isCachedFileUsableInTarget(cached, groupId, userId)) {
return element;
}
const sourceFromCache = await this.downloadSourceFromCachedFile(cached!);
const uploaded = await this.uploadForwardFileSource(
sourceFromCache,
@@ -398,12 +518,16 @@ export class ForwardApi {
groupId?: number,
userId?: number,
): Promise<ForwardNodePayload[]> {
return Promise.all(nodes.map(async (node) => {
const elements = await Promise.all(node.elements.map(
element => this.prepareForwardFileElement(element, groupId, userId),
));
return Promise.all(
nodes.map(async (node) => {
const elements = await Promise.all(
node.elements.map((element) =>
this.prepareForwardFileElement(element, groupId, userId),
),
);
return cloneNodeWithElements(node, elements);
}));
}),
);
}
/**
@@ -437,12 +561,22 @@ export class ForwardApi {
// for text-only forwards). Also need it when a node is itself a nested
// forward — the inner upload uses the same scene.
let userUid: string | undefined;
if (groupId === undefined && userId !== undefined && userId > 0) {
const needsUid = nodes.some(node => !!node.innerForward
|| node.elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video'));
const needsUid = nodes.some(
(node) =>
!!node.innerForward ||
node.elements.some(
(e) => e.type === 'image' || e.type === 'record' || e.type === 'video',
),
);
if (needsUid) {
const resolved = await this.ctx.resolveUserUid(userId);
if (resolved) userUid = resolved;
if (resolved) {
userUid = resolved;
}
}
}
@@ -461,6 +595,7 @@ export class ForwardApi {
const myInnerActions: ForwardInnerAction[] = [];
const processedNodes: ForwardNodePayload[] = [];
const isGroup = groupId !== undefined;
for (const node of nodes) {
if (node.innerForward && node.innerForward.length > 0) {
const inner = await this.uploadRecursive(node.innerForward, groupId, userId);
@@ -478,23 +613,25 @@ 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);
}
@@ -503,15 +640,15 @@ export class ForwardApi {
const uploadReadyNodes = await this.prepareForwardFiles(processedNodes, groupId, userId);
// Encode this level's msgBody.
const msgBody = await Promise.all(uploadReadyNodes.map(
node => buildForwardPushBody(bridge, node, groupId, userUid),
));
const msgBody = await Promise.all(
uploadReadyNodes.map((node) => buildForwardPushBody(bridge, node, groupId, userUid)),
);
// Compose the action list: own MultiMsg + piggybacked inner actions.
const longMsgResult = protobuf_encode<LongMsgResult>({
action: [
{ actionCommand: 'MultiMsg', actionData: { msgBody } },
...myInnerActions.map(a => ({
...myInnerActions.map((a) => ({
actionCommand: a.uuid,
actionData: { msgBody: a.msgBody },
})),
@@ -524,7 +661,10 @@ export class ForwardApi {
uid: { uid: groupId ? String(groupId) : selfUid },
payload: gzipSync(Buffer.from(longMsgResult)),
};
if (groupId) info.groupUin = groupId;
if (groupId) {
info.groupUin = groupId;
}
const request = protobuf_encode<SendLongMsgReq>({
info,
@@ -536,28 +676,30 @@ export class ForwardApi {
},
});
const result = await this.ctx.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', request);
const result = await this.ctx.sendRawPacket(
'trpc.group.long_msg_interface.MsgService.SsoSendLongMsg',
request,
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'upload forward message failed');
}
const resp = protobuf_decode<SendLongMsgResp>(result.responseData);
const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : '';
if (!resId) {
throw new Error('upload forward message response missing res_id');
}
forwardResCache.set(resId, uploadReadyNodes.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
forwardResCache.set(
resId,
uploadReadyNodes.map((node) => ({
...cloneNodeWithElements(node, node.elements.map(cacheableForwardElement)),
groupId: node.groupId ?? groupId,
senderCard: node.senderCard,
messageType: node.messageType ?? (groupId ? 'group' : 'private'),
})));
})),
);
return {
resId,
@@ -578,21 +720,16 @@ export class ForwardApi {
async fetch(resId: string): Promise<ForwardNodePayload[]> {
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));
if (await this.enrichSenders(nodes)) {
forwardResCache.set(resId, cloneNodes(nodes));
}
return nodes;
}
@@ -611,18 +748,24 @@ export class ForwardApi {
},
});
const result = await this.ctx.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg', request);
const result = await this.ctx.sendRawPacket(
'trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg',
request,
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'download forward message failed');
}
const resp = protobuf_decode<RecvLongMsgResp>(result.responseData);
const payload = resp?.result?.payload;
if (!(payload instanceof Uint8Array) || payload.length === 0) {
throw new Error('download forward message payload is empty');
}
let inflate: Buffer;
try {
inflate = gunzipSync(Buffer.from(payload), {
maxOutputLength: FORWARD_LONG_MSG_MAX_OUTPUT_BYTES,
@@ -643,10 +786,13 @@ export class ForwardApi {
{ cause },
);
}
const longMsg = protobuf_decode<LongMsgResult>(inflate);
const actions = Array.isArray(longMsg?.action) ? longMsg!.action! : [];
const mainAction = actions.find(item => item?.actionCommand === 'MultiMsg');
const msgBodyList = Array.isArray(mainAction?.actionData?.msgBody) ? mainAction!.actionData!.msgBody : [];
const mainAction = actions.find((item) => item?.actionCommand === 'MultiMsg');
const msgBodyList = Array.isArray(mainAction?.actionData?.msgBody)
? mainAction!.actionData!.msgBody
: [];
// Piggyback index: any non-`MultiMsg` action carries an inner
// layer keyed by the uuid the sender baked into its forward
@@ -655,9 +801,14 @@ export class ForwardApi {
// server roundtrip — matches the sender-side piggyback emitted in
// `uploadRecursive` above.
const piggybackByUuid = new Map<string, PushMsgBody[]>();
for (const action of actions) {
const cmd = action?.actionCommand;
if (!cmd || cmd === 'MultiMsg') continue;
if (!cmd || cmd === 'MultiMsg') {
continue;
}
const body = Array.isArray(action.actionData?.msgBody) ? action.actionData.msgBody : [];
piggybackByUuid.set(cmd, body);
}
@@ -681,6 +832,7 @@ export class ForwardApi {
if (nodes.length > 0) {
forwardResCache.set(resId, cloneNodes(nodes));
}
return nodes;
}
@@ -697,13 +849,18 @@ export class ForwardApi {
* placeholder rather than failing the whole forward. Returns true if any
* node was changed (so callers can persist the enriched cache). */
private async enrichSenders(nodes: ForwardNodePayload[]): Promise<boolean> {
const pending = nodes.filter(n => this.needsName(n));
if (pending.length === 0) return false;
const pending = nodes.filter((n) => this.needsName(n));
if (pending.length === 0) {
return false;
}
let changed = false;
// L3 — group member lists (one fetch resolves every sender from that group).
const byGroup = new Map<number, ForwardNodePayload[]>();
const residue: ForwardNodePayload[] = [];
for (const n of pending) {
if (n.messageType === 'group' && n.groupId) {
const arr = byGroup.get(n.groupId) ?? [];
@@ -713,20 +870,26 @@ export class ForwardApi {
residue.push(n);
}
}
for (const [groupId, groupNodes] of byGroup) {
let byUin: Map<number, { nickname: string; card: string }>;
try {
const members = await this.ctx.apis.contacts.fetchGroupMemberList(groupId);
byUin = new Map(members.map(m => [m.uin, { nickname: m.nickname, card: m.card }]));
byUin = new Map(
members.map((m) => [m.uin, { nickname: m.nickname, card: m.card }]),
);
} catch {
// Member list (one cheap, cached call) failed — keep the placeholder
// rather than fanning the whole group out to per-uin profile lookups.
// That error path is exactly what would amplify into a rate-limit ban.
continue;
}
for (const n of groupNodes) {
const m = byUin.get(n.userUin);
const name = m?.card || m?.nickname;
if (name) {
n.senderCard = m!.card || n.senderCard || '';
n.nickname = name;
@@ -742,22 +905,45 @@ export class ForwardApi {
// Tencent rate-limits these hard (see ContactsApi's member-list note), so:
// dedupe by uin, CAP the count (drop the rest to placeholder), and resolve
// in small concurrency-limited batches. Best-effort.
const uins = [...new Set(residue.filter(n => this.needsName(n)).map(n => n.userUin))]
.slice(0, FORWARD_PROFILE_MAX);
const uins = [
...new Set(residue.filter((n) => this.needsName(n)).map((n) => n.userUin)),
].slice(0, FORWARD_PROFILE_MAX);
if (uins.length > 0) {
const byUin = new Map<number, string>();
const results = await mapWithConcurrency(uins, FORWARD_PROFILE_CONCURRENCY,
const results = await mapWithConcurrency(
uins,
FORWARD_PROFILE_CONCURRENCY,
async (uin): Promise<readonly [number, string]> => {
try { return [uin, (await this.ctx.apis.contacts.fetchUserProfile(uin)).nickname] as const; }
catch { return [uin, ''] as const; }
});
for (const [uin, nick] of results) byUin.set(uin, nick);
try {
return [
uin,
(await this.ctx.apis.contacts.fetchUserProfile(uin)).nickname,
] as const;
} catch {
return [uin, ''] as const;
}
},
);
for (const [uin, nick] of results) {
byUin.set(uin, nick);
}
for (const n of residue) {
if (!this.needsName(n)) continue;
if (!this.needsName(n)) {
continue;
}
const nick = byUin.get(n.userUin);
if (nick) { n.nickname = nick; changed = true; }
if (nick) {
n.nickname = nick;
changed = true;
}
}
}
return changed;
}
@@ -766,6 +952,7 @@ export class ForwardApi {
* so both the outer + piggyback decode paths share one implementation. */
private decodeMsgBodiesToNodes(msgBodyList: PushMsgBody[]): ForwardNodePayload[] {
const out: ForwardNodePayload[] = [];
for (const msgBody of msgBodyList) {
const wrapped = protobuf_encode<PushMsg>({ message: msgBody });
const pkt: PacketInfo = {
@@ -778,9 +965,16 @@ export class ForwardApi {
body: wrapped,
};
const events = parseMsgPush(pkt, this.ctx.identity);
const event = events.find(e =>
e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message');
if (!event) continue;
const event = events.find(
(e) =>
e.kind === 'friend_message' ||
e.kind === 'group_message' ||
e.kind === 'temp_message',
);
if (!event) {
continue;
}
if (event.kind === 'group_message') {
// [#201] The merged-forward sender name now comes through the group
@@ -819,6 +1013,7 @@ export class ForwardApi {
});
}
}
return out;
}
@@ -834,15 +1029,27 @@ export class ForwardApi {
piggybackByUuid: Map<string, PushMsgBody[]>,
): void {
const seen = new Set<string>();
const visit = (chain: ForwardNodePayload[]): void => {
for (const node of chain) {
for (const elem of node.elements) {
if (elem.type !== 'forward') continue;
if (elem.type !== 'forward') {
continue;
}
const uuid = elem.forwardUuid;
const innerResId = elem.resId;
if (!uuid || !innerResId || seen.has(uuid)) continue;
if (!uuid || !innerResId || seen.has(uuid)) {
continue;
}
const body = piggybackByUuid.get(uuid);
if (!body) continue;
if (!body) {
continue;
}
seen.add(uuid);
const innerNodes = this.decodeMsgBodiesToNodes(body);
forwardResCache.set(innerResId, cloneNodes(innerNodes));
@@ -850,20 +1057,29 @@ export class ForwardApi {
}
}
};
visit(nodes);
}
}
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]));
}
+72 -13
View File
@@ -1,8 +1,12 @@
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 {
GetDoubtBuddyReq,
type DoubtBuddyRequest,
} from '@snowluma/protocol/oidb-services/friend/get-doubt-buddy-req';
import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request';
import { RejectDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/reject-doubt-buddy-req';
import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark';
@@ -24,6 +28,10 @@ export class FriendApi {
}
async delete(userId: number, block = false): Promise<void> {
if (findDatalineDeviceByUin(userId)) {
throw new Error('this contact cannot be deleted');
}
await DeleteFriend.invoke(this.ctx, { userId, block });
// The server-side delete has already completed. A refresh failure must be
@@ -40,25 +48,76 @@ export class FriendApi {
}
}
setRemark(userId: number, remark: string): Promise<void> {
if (remark === '') {
return ClearFriendRemark.invoke(this.ctx, { userId });
async setRemark(userId: number, remark: string): Promise<void> {
if (findDatalineDeviceByUin(userId)) {
throw new Error('this contact does not support remarks');
}
return SetFriendRemark.invoke(this.ctx, { userId, remark });
if (remark === '') {
await ClearFriendRemark.invoke(this.ctx, { userId });
return;
}
await SetFriendRemark.invoke(this.ctx, { userId, remark });
}
/** List doubtful friend-add requests (可能认识的人). */
getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
return GetDoubtBuddyReq.invoke(this.ctx, { count });
async getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
const list = await GetDoubtBuddyReq.invoke(this.ctx, { count });
return Promise.all(
list.map(async (item) => {
let uid = item.uid;
let userId = item.user_id;
if (userId <= 0 && uid) {
userId = this.ctx.identity.findUinByUid(uid) ?? 0;
}
/** 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 });
// 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),
);
}
}
/** Reject (delete/decline) a doubtful friend-add request by its uid. */
rejectDoubtRequest(uid: string): Promise<void> {
return RejectDoubtBuddyReq.invoke(this.ctx, { uid });
return { ...item, uid: uid || '', user_id: userId };
}),
);
}
/** 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. `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));
}
}
+175 -35
View File
@@ -11,28 +11,53 @@ import { SetAdmin } from '@snowluma/protocol/oidb-services/group-admin/set-admin
import { SetGroupName } from '@snowluma/protocol/oidb-services/group-admin/set-group-name';
import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set-group-remark';
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
import { FetchGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/get-group-ext-info';
import {
decodeMemberInvitePolicy,
MEMBER_INVITE_PRIVILEGE_MASK,
mergeMemberInvitePrivilegeFlag,
SetMemberInvitePolicy,
type GroupMemberInvitePolicy,
} from '@snowluma/protocol/oidb-services/group-admin/set-member-invite-policy';
import {
GROUP_HISTORY_VISIBILITY_MASK,
mergeGroupHistoryVisibility,
decodeGroupHistoryVisibility,
SetNewMemberHistoryVisibility,
} from '@snowluma/protocol/oidb-services/group-admin/set-new-member-history-visibility';
import {
decodeGroupMemberPermissions,
GROUP_MEMBER_PERMISSION_MASKS,
mergeGroupMemberPermission,
SetMemberPermission,
type GroupMemberPermission,
} from '@snowluma/protocol/oidb-services/group-admin/set-member-permission';
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
import { GetGroupCategoryTags } from '@snowluma/protocol/oidb-services/group-admin/get-group-category-tags';
import { AddGroupCategoryTag } from '@snowluma/protocol/oidb-services/group-admin/add-group-category-tag';
import { DeleteGroupCategoryTag } from '@snowluma/protocol/oidb-services/group-admin/delete-group-category-tag';
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
import { ModifyGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/modify-group-ext-info';
import { OidbError } from '@snowluma/protocol/oidb-service';
import type { BridgeContext } from '../bridge-context';
/** QQ only accepts this write from the group owner (#411). */
export const MEMBER_PERMISSIONS_OWNER_ONLY =
'only the group owner can change group member permissions';
export type GroupAdminSettings = {
add_type: number;
group_question: string;
group_answer: string;
robot_member_switch: number;
robot_member_examine: number;
member_invite_policy: GroupMemberInvitePolicy;
allow_member_upload_album: boolean;
allow_member_temporary_session: boolean;
allow_member_create_group: boolean;
new_member_history_visible: boolean;
no_finger_open: number;
no_code_finger_open: number;
};
export interface GroupMemberPermissions {
allowMemberUploadAlbum?: boolean;
allowMemberTemporarySession?: boolean;
@@ -43,8 +68,45 @@ export class GroupAdminApi {
constructor(private readonly ctx: BridgeContext) {}
/** Set the group's robot-add option (switch / examine) via group ext-info. */
setRobotAddOption(groupId: number, robotMemberSwitch?: number, robotMemberExamine?: number): Promise<void> {
return ModifyGroupExtInfo.invoke(this.ctx, { groupId, robotMemberSwitch, robotMemberExamine });
setRobotAddOption(
groupId: number,
robotMemberSwitch?: number,
robotMemberExamine?: number,
): Promise<void> {
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> {
@@ -55,14 +117,33 @@ 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,
@@ -83,46 +164,91 @@ export class GroupAdminApi {
'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> {
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
const privilegeFlag = detail.groupInfo?.results?.privilegeFlag;
if (typeof privilegeFlag !== 'number') {
throw new Error(`unable to read ${setting} ${phase} for group ${groupId}`);
}
return privilegeFlag;
private async fetchGroupPrivilegeFlag(
groupId: number,
setting: string,
phase: string,
): Promise<number> {
return (await this.fetchGroupPrivilegeState(groupId, setting, phase)).privilegeFlag;
}
async setMemberPermissions(groupId: number, permissions: GroupMemberPermissions): Promise<void> {
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');
}
let expectedPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
const before = await this.fetchGroupPrivilegeState(
groupId,
'group member permissions',
'before update',
);
const selfUid = this.ctx.identity.selfUid;
if (selfUid && before.ownerUid && selfUid !== before.ownerUid) {
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
}
let expectedPrivilegeFlag = before.privilegeFlag;
let combinedMask = 0n;
for (const [permission, allow] of updates) {
if (allow === undefined) continue;
if (allow === undefined) {
continue;
}
try {
await SetMemberPermission.invoke(this.ctx, {
groupId,
currentPrivilegeFlag: expectedPrivilegeFlag,
permission,
allow,
});
expectedPrivilegeFlag = mergeGroupMemberPermission(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]);
}
@@ -131,42 +257,56 @@ export class GroupAdminApi {
'group member permissions',
'after update',
);
if ((BigInt(actualPrivilegeFlag) & combinedMask) !== (BigInt(expectedPrivilegeFlag) & combinedMask)) {
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> {
const currentGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'before update');
const expectedGroupFlagExt4 = mergeGroupHistoryVisibility(currentGroupFlagExt4, visible);
await SetNewMemberHistoryVisibility.invoke(this.ctx, {
groupId,
currentGroupFlagExt4,
visible,
});
await SetNewMemberHistoryVisibility.invoke(this.ctx, { groupId, visible });
const actualGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'after update');
const mask = BigInt(GROUP_HISTORY_VISIBILITY_MASK);
if ((BigInt(actualGroupFlagExt4) & mask) !== (BigInt(expectedGroupFlagExt4) & mask)) {
if (decodeGroupHistoryVisibility(actualGroupFlagExt4) !== visible) {
throw new Error(`new-member history visibility was not applied for group ${groupId}`);
}
}
private async fetchGroupFlagExt4(groupId: number, phase: string): Promise<number> {
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
const groupFlagExt4 = detail.groupInfo?.results?.groupFlagExt4;
if (typeof groupFlagExt4 !== 'number') {
throw new Error(`unable to read new-member history visibility ${phase} for group ${groupId}`);
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(
`unable to read new-member history visibility ${phase} for group ${groupId}`,
);
}
return groupFlagExt4;
return results.groupFlagExt4 ?? 0;
}
setAddRequest(
groupId: number, sequence: number, eventType: number,
approve: boolean, reason = '', filtered = false,
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> {
+609 -65
View File
@@ -1,7 +1,12 @@
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,
CommentReqBodyUserWrap,
CommentReqPhotoInfo,
CommentRespData,
DeleteMediasRequest,
DeleteMediasResponse,
DoQunCommentRequest,
@@ -10,19 +15,29 @@ import type {
DoQunLikeResponse,
GetAlbumListRequest,
GetAlbumListResponse,
GetQunFeedDetailRequest,
GetQunFeedDetailResponse,
GroupAlbumInfo as GroupAlbumInfoWire,
QunFeedCellCommon,
GetMediaListRequest,
GetMediaListResponse,
MediaInfo,
UrlInfo,
} from '@snowluma/proto-defs/oidb-actions/group-album';
import { uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album';
import {
uploadImageToGroupAlbum,
uploadVideoToGroupAlbum,
} from '@snowluma/protocol/web/group-album';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
const log = createLogger('Bridge.GroupAlbum');
const GET_ALBUM_LIST_CMD = 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetAlbumList';
const GET_ALBUM_LIST_SEQ = 3331;
const DO_QUN_COMMENT_CMD = 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment';
const DO_QUN_COMMENT_SEQ = 8527;
const GET_QUN_FEED_DETAIL_CMD = 'QunAlbum.trpc.qzone.webapp_qun_feeds.FeedsReader.GetQunFeedDetail';
const GET_QUN_FEED_DETAIL_COMMENT_COUNT = 20;
function uint64ToString(value: bigint | undefined): string {
return (value ?? 0n).toString();
@@ -30,14 +45,19 @@ function uint64ToString(value: bigint | undefined): string {
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;
if (!creator) {
return undefined;
}
return {
uid: creator.uid ?? '',
nick: creator.nick ?? '',
@@ -55,7 +75,10 @@ function normalizeAlbumCreator(creator: AlbumCreator | undefined): QunAlbumCreat
}
function normalizeCoverUrl(url: UrlInfo | null | undefined): QunAlbumCoverUrl | null {
if (!url) return null;
if (!url) {
return null;
}
return {
url: url.url ?? '',
width: url.width ?? 0,
@@ -64,11 +87,15 @@ function normalizeCoverUrl(url: UrlInfo | null | undefined): QunAlbumCoverUrl |
}
function normalizeAlbumCover(cover: MediaInfo | undefined): QunAlbumCover | null {
if (!cover) return null;
if (!cover) {
return null;
}
const image = cover.image;
return {
type: cover.type ?? 0,
image: image ? {
image: image
? {
name: image.name ?? '',
sloc: image.sloc ?? '',
lloc: image.lloc ?? '',
@@ -79,7 +106,8 @@ function normalizeAlbumCover(cover: MediaInfo | undefined): QunAlbumCover | null
defaultUrl: normalizeCoverUrl(image.defaultUrl),
isGif: image.isGif ?? false,
hasRaw: image.hasRaw ?? false,
} : null,
}
: null,
};
}
@@ -107,7 +135,11 @@ function normalizeQunAlbum(album: GroupAlbumInfoWire): QunAlbumInfo {
sort_type: album.sortType ?? 0,
};
const creator = normalizeAlbumCreator(album.creator);
if (creator) normalized.creator = creator;
if (creator) {
normalized.creator = creator;
}
return normalized;
}
@@ -131,24 +163,42 @@ function toLegacyAlbum(album: GroupAlbumInfoWire): GroupAlbumInfo {
}
function convertBigIntToString(obj: unknown): JsonValue {
if (obj === null || obj === undefined) return null;
if (typeof obj === 'bigint') return obj.toString();
if (Array.isArray(obj)) return obj.map(convertBigIntToString);
if (obj === null || obj === undefined) {
return null;
}
if (typeof obj === 'bigint') {
return obj.toString();
}
if (Array.isArray(obj)) {
return obj.map(convertBigIntToString);
}
if (typeof obj === 'object') {
const result: JsonObject = {};
for (const [key, value] of Object.entries(obj)) {
result[key] = convertBigIntToString(value);
}
return result;
}
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') return obj;
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') {
return obj;
}
return null;
}
export class GroupAlbumApi {
constructor(private readonly ctx: BridgeContext) {}
private async fetchAlbumList(groupId: number, attachInfo: string): Promise<GroupAlbumWireResult> {
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,
@@ -169,7 +219,8 @@ export class GroupAlbumApi {
body.length,
);
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, 15000);
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, packetTimeoutMs());
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(
`get group album list transport failed: ${result.errorMessage || `code ${result.errorCode}`}`,
@@ -178,6 +229,7 @@ export class GroupAlbumApi {
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'}`,
@@ -234,12 +286,14 @@ export class GroupAlbumApi {
}
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',
`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}`,
@@ -252,14 +306,35 @@ export class GroupAlbumApi {
}
// 上传图片到现有相册(HTTP 分片上传)。
async upload(groupId: number, albumId: string, albumName: string, filePath: string): Promise<void> {
async upload(
groupId: number,
albumId: string,
albumName: string,
filePath: string,
): Promise<void> {
const groupCode = groupId.toString();
const uin = this.ctx.identity.uin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin);
}
async getMediaList(groupId: number, albumId: string, attachInfo = ''): Promise<GroupAlbumMediaResult> {
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)}`;
const body = protobuf_encode<GetMediaListRequest>({
@@ -280,7 +355,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) {
@@ -290,6 +365,7 @@ export class GroupAlbumApi {
const resp = protobuf_decode<GetMediaListResponse>(result.responseData);
const retCode = resp.field1 ?? 0;
if (retCode !== 0) {
throw new Error(`fetch album media list error: retCode ${retCode}`);
}
@@ -298,45 +374,66 @@ export class GroupAlbumApi {
const mediaList = data.mediaList ?? [];
const nextAttachInfo = data.nextAttachInfo ?? '';
return convertBigIntToString({ mediaList, nextAttachInfo }) as unknown as GroupAlbumMediaResult;
return convertBigIntToString({
mediaList,
nextAttachInfo,
}) as unknown as GroupAlbumMediaResult;
}
async comment(groupId: number, albumId: string, lloc: string, content: string): Promise<GroupAlbumCommentResult> {
async comment(
groupId: number,
albumId: string,
lloc: string,
content: string,
): Promise<GroupAlbumCommentResult> {
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 headerBytes =
feed.rawCellCommon ??
protobuf_encode<CommentReqBodyHeader>(commentReqHeader(feed.cellCommon));
const userBytes =
feed.rawCellUser ??
(ownerUin
? protobuf_encode<CommentReqBodyUserWrap>({ field1: { uin: ownerUin } })
: undefined);
const mediaBytes = feed.rawCellMedia ?? protobuf_encode<CommentReqPhotoInfo>(photoInfo);
const commenterUinNum = numericUin(uin);
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 },
field1: headerBytes,
...(userBytes ? { field2: userBytes } : {}),
field5: mediaBytes,
},
field5: {
field1: {
field2: {
field1: 0, field2: '',
lloc,
field4: '', field6: '', field7: 0, field8: 0, field9: 0, field14: 0, field15: 0, field17: 0,
},
},
albumId,
field5: 0,
},
},
field5: {
field2: { uin },
field3: {
field1: 0,
field2: content,
field3: '', field4: '', field5: 0, field6: '',
user: {
uin,
...(commenterUinNum !== undefined ? { uinNum: commenterUinNum } : {}),
},
contents: [{ type: 0, content }],
clientKey,
},
},
@@ -344,47 +441,54 @@ 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 resultCode = resp.result ?? 0;
const resCode = resp.field1;
if (resCode !== 0 && resCode !== 8527 && !resp.comment) {
throw new Error(`comment album media error: retCode ${resCode ?? 'unknown'}`);
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;
}
async like(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise<JsonValue> {
async like(
groupId: number,
albumId: string,
batchId: string,
lloc: string | undefined,
isLike: boolean,
): Promise<JsonValue> {
const uin = this.ctx.identity.uin;
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const type = isLike ? 2 : 1;
const status = isLike ? 0 : 1;
let id = '';
if (lloc) {
id = `421_1_0_${groupId}|${albumId}|${batchId}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`;
} else {
id = `421_1_0_${groupId}|${albumId}|${batchId}`;
}
const id = qunFeedCellId(groupId, albumId, batchId, lloc);
const body = protobuf_encode<DoQunLikeRequest>({
field1: 5495,
@@ -417,7 +521,7 @@ export class GroupAlbumApi {
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
body,
15000,
packetTimeoutMs(),
);
if (!result.success || !result.gotResponse || !result.responseData) {
@@ -435,6 +539,7 @@ export class GroupAlbumApi {
}
async delete(groupId: number, albumId: string, lloc: string): Promise<{ success: true }> {
const target = await this.resolveDeleteTarget(groupId, albumId, lloc);
const uin = this.ctx.identity.uin;
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
@@ -445,7 +550,8 @@ export class GroupAlbumApi {
body: {
groupId: groupId.toString(),
albumId,
lloc,
mediaIds: [target.mediaId],
...(target.batchId ? { batchIds: [target.batchId] } : {}),
},
traceId: clientKey,
extMap: [{ key: 'fc-appid', value: '100' }],
@@ -454,7 +560,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) {
@@ -467,12 +573,450 @@ export class GroupAlbumApi {
const errMsg = resp.field3;
if (resCode !== 8694 || errCode) {
throw new Error(`delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`);
throw new Error(
`delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`,
);
}
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;
rawCellCommon?: Uint8Array;
rawCellUser?: Uint8Array;
rawCellMedia?: Uint8Array;
}> {
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');
}
const responseBytes = toBytes(result.responseData);
return {
cellCommon: cell ?? { feedId },
ownerUin: feed?.cellUserInfo?.user?.uin ?? '',
media: feed?.cellMedia,
rawCellCommon: nonemptyBytes(protobufSubmessage(responseBytes, [4, 2, 1, 1])),
rawCellUser: nonemptyBytes(protobufSubmessage(responseBytes, [4, 2, 1, 2])),
rawCellMedia: nonemptyBytes(protobufSubmessage(responseBytes, [4, 2, 1, 5])),
};
}
}
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 toBytes(value: Uint8Array): Uint8Array {
return value instanceof Uint8Array ? value : new Uint8Array(value);
}
function nonemptyBytes(value: Uint8Array | undefined): Uint8Array | undefined {
return value && value.byteLength > 0 ? value : undefined;
}
function numericUin(uin: string): bigint | undefined {
if (!/^\d+$/.test(uin)) {
return undefined;
}
try {
return BigInt(uin);
} catch {
return undefined;
}
}
function readProtobufVarint(buf: Uint8Array, offset: number): { value: number; next: number } {
let value = 0;
let shift = 0;
let next = offset;
while (next < buf.length && shift <= 28) {
const byte = buf[next++];
value += (byte & 0x7f) * 2 ** shift;
if ((byte & 0x80) === 0) {
return { value, next };
}
shift += 7;
}
throw new Error('truncated protobuf varint');
}
function skipProtobufVarint(buf: Uint8Array, offset: number): number {
for (let index = 0; index < 10 && offset < buf.length; index++) {
const byte = buf[offset++];
if (index === 9 && byte > 1) {
throw new Error('protobuf varint exceeds 64 bits');
}
if ((byte & 0x80) === 0) {
return offset;
}
}
throw new Error('truncated protobuf varint');
}
function protobufSubmessage(buf: Uint8Array, path: readonly number[]): Uint8Array | undefined {
let current: Uint8Array | undefined = buf;
for (const fieldNo of path) {
if (!current) {
return undefined;
}
current = firstLengthDelimitedField(current, fieldNo);
}
return current;
}
function firstLengthDelimitedField(buf: Uint8Array, fieldNo: number): Uint8Array | undefined {
let offset = 0;
while (offset < buf.length) {
const key = readProtobufVarint(buf, offset);
offset = key.next;
const field = Math.floor(key.value / 8);
const wire = key.value % 8;
if (wire === 0) {
offset = skipProtobufVarint(buf, offset);
} else if (wire === 1) {
offset += 8;
} else if (wire === 5) {
offset += 4;
} else if (wire === 2) {
const len = readProtobufVarint(buf, offset);
offset = len.next;
const end = offset + len.value;
if (end > buf.length) {
return undefined;
}
if (field === fieldNo) {
return buf.slice(offset, end);
}
offset = end;
} else {
return undefined;
}
}
return undefined;
}
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;
+195 -113
View File
@@ -1,13 +1,15 @@
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';
import {
FileChunkSource,
fetchHighwaySession,
uploadHighwayHttp,
} from '@snowluma/protocol/highway';
import { FILE_UPLOAD_MAX_BYTES } from '@snowluma/protocol/highway/utils';
import { stageSourceToDisk } from '@snowluma/protocol/highway/stage';
import { hashFileStreaming } from '@snowluma/protocol/highway/hash-file';
import { protobuf_encode } from '@snowluma/proton';
import { promises as fsp } from 'fs';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid, toInt, type MediaIndexNode } from './shared';
@@ -27,15 +29,16 @@ import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-
import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file';
import { RenameGroupFile } from '@snowluma/protocol/oidb-services/group-file/rename-group-file';
import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder';
import { TransGroupFile, type TransGroupFileResult } from '@snowluma/protocol/oidb-services/group-file/trans-group-file';
import {
TransGroupFile,
type TransGroupFileResult,
} from '@snowluma/protocol/oidb-services/group-file/trans-group-file';
import { UploadGroupFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-group-file-request';
import { UploadPrivateFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-private-file-request';
import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared';
const log = createLogger('GroupFile');
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
// ─────────────── public result types ───────────────
export interface GroupFileInfo {
@@ -79,13 +82,11 @@ export type { MediaIndexNode } from './shared';
// ─────────────── file-specific helpers ───────────────
function normalizeDirectory(dir?: string): string {
if (!dir || !dir.trim()) return '/';
return dir;
if (!dir || !dir.trim()) {
return '/';
}
function bytesToHexUpper(data: unknown): string {
if (!(data instanceof Uint8Array) || data.length === 0) return '';
return toHexUpper(data);
return dir;
}
// Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives
@@ -94,16 +95,20 @@ function bytesToHexUpper(data: unknown): string {
// rendering correctly — JS `>>` is arithmetic and would turn 0xFF000000
// into a negative number.
function int32ToIpv4Dotted(value: number): string {
const b1 = value & 0xFF;
const b2 = (value >>> 8) & 0xFF;
const b3 = (value >>> 16) & 0xFF;
const b4 = (value >>> 24) & 0xFF;
const b1 = value & 0xff;
const b2 = (value >>> 8) & 0xff;
const b3 = (value >>> 16) & 0xff;
const b4 = (value >>> 24) & 0xff;
return `${b1}.${b2}.${b3}.${b4}`;
}
function normalizeUploadFileName(name: string, fallback: string): string {
const trimmed = name.trim();
if (trimmed) return trimmed;
if (trimmed) {
return trimmed;
}
const safeFallback = fallback.trim();
return safeFallback || 'file.bin';
}
@@ -117,8 +122,12 @@ const MD5_HEAD_LIMIT = 10002432;
/** Fail cleanly if the staged file changed since the streaming hash pass (a
* local source mutated mid-send). The server's per-chunk md5 during the PUT is
* the backstop; this is the cheap early check. */
async function assertUnchanged(filePath: string, baseline: { size: number; mtimeMs: number }): Promise<void> {
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)');
}
@@ -247,12 +256,18 @@ export class GroupFileApi {
// ─────────────── publish (group file → chat) ───────────────
publish(groupId: number, fileId: string): Promise<void> {
if (!fileId) throw new Error('publish requires fileId');
if (!fileId) {
throw new Error('publish requires fileId');
}
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
}
trans(groupId: number, fileId: string): Promise<TransGroupFileResult> {
if (!fileId) throw new Error('trans requires fileId');
if (!fileId) {
throw new Error('trans requires fileId');
}
return TransGroupFile.invoke(this.ctx, { groupId, fileId });
}
@@ -276,14 +291,17 @@ export class GroupFileApi {
uploadFile = true,
publishFile = uploadFile,
): Promise<UploadFileResult> {
const bridge = asBridge(this.ctx);
const bridge = this.ctx;
// Group/private files may legitimately be up to 4 GiB on QQ's wire, so
// override the default 1 GiB cap with the protocol ceiling. Stage onto a
// local disk path and stream-hash it — the (up to 4 GiB) file is never
// buffered in RAM.
const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES);
try {
if (staged.fileSize === 0) throw new Error('group file is empty');
if (staged.fileSize === 0) {
throw new Error('group file is empty');
}
const fileName = normalizeUploadFileName(name, staged.fileName);
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
@@ -297,10 +315,19 @@ export class GroupFileApi {
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
});
ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
ensureRetCodeZero(
'group file upload',
upload.retCode,
upload.retMsg,
upload.clientWording,
);
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
if (!fileId) throw new Error('group file upload response missing file_id');
const fileId =
typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
if (!fileId) {
throw new Error('group file upload response missing file_id');
}
// Remember the upload so a later `send_group_msg` carrying just the
// file_id can route via `publish` without forcing the OneBot caller
@@ -321,12 +348,17 @@ export class GroupFileApi {
if (!upload.boolFileExist && uploadFile) {
const senderUin = toInt(this.ctx.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|| (typeof upload.serverDns === 'string' && upload.serverDns)
|| '';
if (senderUin <= 0) {
throw new Error('invalid self uin for group file upload');
}
const uploadHost =
(typeof upload.uploadIp === 'string' && upload.uploadIp) ||
(typeof upload.serverDns === 'string' && upload.serverDns) ||
'';
const uploadPort = toInt(upload.uploadPort);
if (!uploadHost || uploadPort <= 0) {
throw new Error('group file upload host is invalid');
}
@@ -372,8 +404,11 @@ export class GroupFileApi {
// fail loud but don't lose the upload result the action handler
// committed to returning. Callers can still resolve the file by
// id; they'll just have to re-publish it themselves.
log.warn('group file uploaded (fileId=%s) but chat post failed: %s',
fileId, err instanceof Error ? err.message : String(err));
log.warn(
'group file uploaded (fileId=%s) but chat post failed: %s',
fileId,
err instanceof Error ? err.message : String(err),
);
}
}
@@ -390,19 +425,25 @@ export class GroupFileApi {
uploadFile = true,
publishFile = uploadFile,
): Promise<UploadFileResult> {
const bridge = asBridge(this.ctx);
const bridge = this.ctx;
// Stage onto a local disk path + stream-hash — the (up to 4 GiB) file is
// never buffered in RAM. headLimit = MD5_HEAD_LIMIT yields the offline-file
// 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 senderUin = toInt(this.ctx.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
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
@@ -420,8 +461,12 @@ export class GroupFileApi {
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 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
@@ -462,43 +507,65 @@ 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)
&& 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)
|| (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
&& typeof upload.uploadHttpsDomain === 'string' && !!upload.uploadHttpsDomain;
const uploadPort = rtpInIP && rtpInPort > 0
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 ||
(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 &&
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,
? 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 ?? '',
upload.uploadIp ?? '',
upload.uploadDomain ?? '',
JSON.stringify(upload.uploadIpList ?? []),
upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '',
upload.uploadLanip ?? '', upload.uploadPort ?? 0,
upload.uploadHttpsDomain ?? '',
upload.uploadDns ?? '',
upload.uploadLanip ?? '',
upload.uploadPort ?? 0,
upload.uploadHttpsPort ?? 0,
);
throw new Error('private file upload host is invalid');
@@ -513,7 +580,9 @@ export class GroupFileApi {
fileId,
upload.mediaPlatformUploadKey instanceof Uint8Array
? upload.mediaPlatformUploadKey
: (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)),
: upload.uploadKey instanceof Uint8Array
? upload.uploadKey
: new Uint8Array(0),
uploadHost,
uploadPort,
);
@@ -543,8 +612,11 @@ export class GroupFileApi {
fileHash: fileHash ?? '',
});
} catch (err) {
log.warn('private file uploaded (fileId=%s) but chat post failed: %s',
fileId, err instanceof Error ? err.message : String(err));
log.warn(
'private file uploaded (fileId=%s) but chat post failed: %s',
fileId,
err instanceof Error ? err.message : String(err),
);
}
}
@@ -563,15 +635,22 @@ export class GroupFileApi {
const pageSize = 20;
let startIndex = 0;
for (let page = 0; page < 200; page++) {
const list = await ListGroupFilesPage.invoke(this.ctx, {
groupId, targetDirectory, startIndex, pageSize,
groupId,
targetDirectory,
startIndex,
pageSize,
});
if (!list) break;
ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording);
for (const item of list.items ?? []) {
if (!list) {
break;
}
for (const item of list.items) {
const type = toInt(item?.type);
if (type === 1 && item?.fileInfo) {
const file = item.fileInfo;
const uploader = toInt(file.uploaderUin);
@@ -586,38 +665,47 @@ export class GroupFileApi {
modifyTime: toInt(file.modifiedTime),
downloadTimes: toInt(file.downloadedTimes),
uploader,
uploaderName: (typeof file.uploaderName === 'string' && file.uploaderName)
|| cached?.card
|| cached?.nickname
|| '',
uploaderName:
(typeof file.uploaderName === 'string' && file.uploaderName) ||
cached?.card ||
cached?.nickname ||
'',
});
} else if (type === 2 && item?.folderInfo) {
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);
const lastUploaderCached = this.ctx.identity.findGroupMember(
groupId,
lastUploader,
);
folders.push({
folderId: typeof folder.folderId === 'string' ? folder.folderId : '',
folderName: typeof folder.folderName === 'string' ? folder.folderName : '',
createTime: toInt(folder.createTime),
creator,
creatorName: (typeof folder.creatorName === 'string' && folder.creatorName)
|| cached?.card
|| cached?.nickname
|| '',
creatorName:
(typeof folder.creatorName === 'string' && folder.creatorName) ||
cached?.card ||
cached?.nickname ||
'',
totalFileCount: toInt(folder.totalFileCount),
lastUploadTime: toInt(folder.modifiedTime),
lastUploader,
lastUploaderName: (typeof folder.modifierName === 'string' && folder.modifierName)
|| lastUploaderCached?.card
|| lastUploaderCached?.nickname
|| '',
lastUploaderName:
(typeof folder.modifierName === 'string' && folder.modifierName) ||
lastUploaderCached?.card ||
lastUploaderCached?.nickname ||
'',
});
}
}
if (list.isEnd) break;
if (list.isEnd) {
break;
}
startIndex += pageSize;
}
@@ -627,34 +715,13 @@ 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);
const selfUid = await resolveSelfUid(this.ctx);
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 ───────────────
@@ -663,11 +730,26 @@ export class GroupFileApi {
return DeleteGroupFile.invoke(this.ctx, { groupId, fileId });
}
move(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> {
return MoveGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, targetDirectory });
move(
groupId: number,
fileId: string,
parentDirectory: string,
targetDirectory: string,
): Promise<void> {
return MoveGroupFile.invoke(this.ctx, {
groupId,
fileId,
parentDirectory,
targetDirectory,
});
}
rename(groupId: number, fileId: string, parentDirectory: string, newFileName: string): Promise<void> {
rename(
groupId: number,
fileId: string,
parentDirectory: string,
newFileName: string,
): Promise<void> {
return RenameGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, newFileName });
}
@@ -675,7 +757,9 @@ export class GroupFileApi {
createFolder(groupId: number, name: string, parentId = '/'): Promise<CreateGroupFolder.Result> {
return CreateGroupFolder.invoke(this.ctx, {
groupId, parentId: normalizeDirectory(parentId), folderName: name,
groupId,
parentId: normalizeDirectory(parentId),
folderName: name,
});
}
@@ -694,8 +778,7 @@ export class GroupFileApi {
}
async getPrivatePttUrl(node: MediaIndexNode): Promise<string> {
const bridge = asBridge(this.ctx);
const selfUid = await resolveSelfUid(bridge);
const selfUid = await resolveSelfUid(this.ctx);
return GetPrivatePttUrl.invoke(this.ctx, { selfUid, node });
}
@@ -704,8 +787,7 @@ export class GroupFileApi {
}
async getPrivateVideoUrl(node: MediaIndexNode): Promise<string> {
const bridge = asBridge(this.ctx);
const selfUid = await resolveSelfUid(bridge);
const selfUid = await resolveSelfUid(this.ctx);
return GetPrivateVideoUrl.invoke(this.ctx, { selfUid, node });
}
}
@@ -22,24 +22,24 @@ export class HistoryRequestGate {
constructor(private readonly clock: HistoryRequestGateClock = SYSTEM_CLOCK) {}
run<T>(
minimumGapMs: number,
operation: () => Promise<T>,
signal?: AbortSignal,
): Promise<T> {
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)}`));
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 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);
if (wait > 0) {
await this.clock.sleep(wait, signal);
}
throwIfAborted(signal);
const startedAt = this.clock.now();
@@ -53,9 +53,7 @@ export class HistoryRequestGate {
() => undefined,
() => undefined,
);
return signal
? rejectWhileQueuedOnAbort(result, signal, () => operationStarted)
: result;
return signal ? rejectWhileQueuedOnAbort(result, signal, () => operationStarted) : result;
}
}
@@ -67,6 +65,7 @@ function throwIfAborted(signal?: AbortSignal): void {
function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
throwIfAborted(signal);
if (!signal) {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
@@ -76,11 +75,13 @@ function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
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 });
});
}
@@ -100,6 +101,7 @@ function rejectWhileQueuedOnAbort<T>(
reject(signal.reason ?? new Error('history request aborted'));
}
};
signal.addEventListener('abort', onAbort);
result.then(resolve, reject).finally(() => {
signal.removeEventListener('abort', onAbort);
+13 -11
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,
@@ -47,22 +43,28 @@ export class InteractionApi {
cookie = '',
): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> {
try {
return await GetEmojiLikes.invoke(this.ctx, { groupId, sequence, emojiId, emojiType, count, cookie });
return await GetEmojiLikes.invoke(this.ctx, {
groupId,
sequence,
emojiId,
emojiType,
count,
cookie,
});
} catch {
return { users: [], cookie: '', isLast: true };
}
}
/**
* 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,
sequence: number,
): Promise<Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }>> {
): Promise<
Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }>
> {
return FetchReactionSummary.invoke(this.ctx, { groupId, sequence });
}
}
File diff suppressed because it is too large. Load diff
+33 -11
View File
@@ -1,8 +1,5 @@
import type { JsonObject, JsonValue } from '@snowluma/common/json';
import type {
MiniAppShareReq,
MiniAppShareResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { MiniAppShareReq, MiniAppShareResp } from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
// Migrated OIDB cmds — facade methods are one-line forwarders.
@@ -23,13 +20,21 @@ export class MiscApi {
return ImageOcr.invoke(this.ctx, { imageUrl });
}
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<JsonObject> {
async getMiniAppArk(
type: string,
title: string,
desc: string,
picUrl: string,
jumpUrl: string,
): Promise<JsonObject> {
let appid = '1109937557'; // default: bilibili
let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
let iconUrl =
'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
if (type === 'weibo') {
appid = '1109224783';
iconUrl = 'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg';
iconUrl =
'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg';
} else if (type !== 'bili') {
throw new Error(`unsupported type: ${type}, only support bili and weibo`);
}
@@ -39,7 +44,10 @@ export class MiscApi {
body: { appid, title, desc, picUrl, jumpUrl, iconUrl },
});
const result = await this.ctx.sendRawPacket('LightAppSvc.mini_app_share.AdaptShareInfo', request);
const result = await this.ctx.sendRawPacket(
'LightAppSvc.mini_app_share.AdaptShareInfo',
request,
);
if (!result.success || !result.responseData) {
throw new Error(result.errorMessage || 'get mini app ark failed');
@@ -52,7 +60,10 @@ export class MiscApi {
throw new Error('mini app share json empty');
}
const parsed = JSON.parse(jsonStr) as Record<string, JsonObject | string | number | boolean | null>;
const parsed = JSON.parse(jsonStr) as Record<
string,
JsonObject | string | number | boolean | null
>;
return {
data: {
@@ -75,7 +86,13 @@ export class MiscApi {
callbackData: string,
msgSeq: number,
): Promise<JsonValue> {
return ClickInlineKeyboardButton.invoke(this.ctx, { groupId, botAppid, buttonId, callbackData, msgSeq });
return ClickInlineKeyboardButton.invoke(this.ctx, {
groupId,
botAppid,
buttonId,
callbackData,
msgSeq,
});
}
sendGroupSign(groupId: number): Promise<void> {
@@ -84,12 +101,17 @@ export class MiscApi {
async getDecryptKey(dbSalt: string): Promise<string> {
const result = await RequestDbKey.invoke(this.ctx, { db_salt: dbSalt });
if (!result.success) {
throw new Error(result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`);
throw new Error(
result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`,
);
}
if (!result.dbKey) {
throw new Error('Decrypt key is empty');
}
return result.dbKey;
}
}
+91 -42
View File
@@ -1,6 +1,4 @@
import type {
FaceroamOpReq,
FaceroamOpResp,
GroupAvatarExtra,
SetStatusReq,
SetStatusResp,
@@ -8,13 +6,21 @@ import type {
import { AddCustomFace } from '@snowluma/protocol/oidb-services/custom-face/add-custom-face';
import { DeleteCustomFace } from '@snowluma/protocol/oidb-services/custom-face/delete-custom-face';
import { FetchCustomFaceDetail } from '@snowluma/protocol/oidb-services/custom-face/fetch-custom-face-detail';
import { FetchCustomFaceList } from '@snowluma/protocol/oidb-services/custom-face/fetch-custom-face-list';
import { ModifyCustomFace } from '@snowluma/protocol/oidb-services/custom-face/modify-custom-face';
import { MoveCustomFace } from '@snowluma/protocol/oidb-services/custom-face/move-custom-face';
import { OrderCustomFace } from '@snowluma/protocol/oidb-services/custom-face/order-custom-face';
import { BufferChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
import {
BufferChunkSource,
fetchHighwaySession,
uploadHighwayHttp,
} from '@snowluma/protocol/highway';
import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils';
import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like';
import { GetUnidirectionalFriendList, type UnidirectionalFriendEntry } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
import {
GetUnidirectionalFriendList,
type UnidirectionalFriendEntry,
} from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-input-status';
import { SetProfile } from '@snowluma/protocol/oidb-services/profile/set-profile';
import { SetSelfLongNick } from '@snowluma/protocol/oidb-services/profile/set-self-long-nick';
@@ -22,7 +28,9 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
function asBridge(ctx: BridgeContext): Bridge {
return ctx as unknown as Bridge;
}
export interface CustomFaceDetail {
emojiId: string;
@@ -73,17 +81,23 @@ export class ProfileApi {
if (result.responseData && result.responseData.length > 0) {
const resp = protobuf_decode<SetStatusResp>(result.responseData);
if (!resp) {
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
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> {
@@ -97,11 +111,21 @@ export class ProfileApi {
async setAvatar(source: string): Promise<void> {
const bridge = asBridge(this.ctx);
const loaded = await loadBinarySource(source, 'avatar');
if (!loaded.bytes.length) throw new Error('avatar file is empty');
if (!loaded.bytes.length) {
throw new Error('avatar file is empty');
}
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 90, new BufferChunkSource(loaded.bytes), hashes.md5, new Uint8Array(0));
await uploadHighwayHttp(
bridge,
session,
90,
new BufferChunkSource(loaded.bytes),
hashes.md5,
new Uint8Array(0),
);
}
/**
@@ -117,7 +141,10 @@ export class ProfileApi {
async setGroupAvatar(groupId: number, source: string): Promise<void> {
const bridge = asBridge(this.ctx);
const loaded = await loadBinarySource(source, 'group-avatar');
if (!loaded.bytes.length) throw new Error('group avatar file is empty');
if (!loaded.bytes.length) {
throw new Error('group avatar file is empty');
}
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
@@ -128,7 +155,14 @@ export class ProfileApi {
field5: 3,
field6: 1,
});
await uploadHighwayHttp(bridge, session, 3000, new BufferChunkSource(loaded.bytes), hashes.md5, extra);
await uploadHighwayHttp(
bridge,
session,
3000,
new BufferChunkSource(loaded.bytes),
hashes.md5,
extra,
);
}
// ─────────────── queries on me / my contacts ───────────────
@@ -148,7 +182,10 @@ export class ProfileApi {
async fetchCustomFaceDetails(count = 10): Promise<CustomFaceDetail[]> {
const faceIds = await this.fetchCustomFaceIds(count);
if (faceIds.length === 0) return [];
if (faceIds.length === 0) {
return [];
}
const emojis = faceIds.map((emojiId) => ({
emojiId,
@@ -166,28 +203,16 @@ export class ProfileApi {
}));
}
private async fetchCustomFaceIds(count: number): Promise<string[]> {
async fetchCustomFaceIds(count = 10): Promise<string[]> {
if (!Number.isInteger(count) || count < 0) {
throw new Error('custom face count must be a non-negative integer');
}
if (count === 0) return [];
const req = {
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
uin: BigInt(this.ctx.identity.uin),
field3: 1,
field6: 1,
};
const request = protobuf_encode<FaceroamOpReq>(req);
const result = await this.ctx.sendRawPacket('Faceroam.OpReq', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'fetch custom face failed');
if (count === 0) {
return [];
}
const resp = protobuf_decode<FaceroamOpResp>(result.responseData);
if (!resp || (resp.retCode ?? 0) !== 0) {
throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`);
}
const faceIds = resp.item?.faceIds || [];
const faceIds = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
return faceIds.slice(0, count);
}
@@ -195,7 +220,30 @@ export class ProfileApi {
return `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${emojiId}/0`;
}
/** 删除一个收藏表情(custom face)。emoji_id 来自 fetchCustomFace 返回的 URL 路径段。 */
/** Resolve an existing saved sticker by its resource id or content MD5. */
async resolveCustomFace(
identifier: string,
): Promise<Pick<CustomFaceDetail, 'emojiId' | 'url' | 'md5'>> {
const wanted = identifier.trim();
if (!wanted) {
throw new Error('custom face identifier is empty');
}
const ids = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
const byMd5 = /^[a-fA-F0-9]{32}$/.test(wanted);
const emojiId = ids.find((id) =>
byMd5 ? md5FromEmojiId(id).toLowerCase() === wanted.toLowerCase() : id === wanted,
);
if (!emojiId) {
throw new Error('custom face is not in the saved sticker list');
}
return { emojiId, url: this.customFaceUrl(emojiId), md5: md5FromEmojiId(emojiId) };
}
/** 删除一个收藏表情(custom face)。emoji_id 来自收藏列表。 */
deleteCustomFace(emojiId: string): Promise<void> {
return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId });
}
@@ -210,9 +258,8 @@ export class ProfileApi {
}
/**
* 修改收藏表情(custom face)备注。emoji_id 来自 fetchCustomFace 返回的
* URL 路径段;md5 从 emoji_id 中段解析,无需调用方单独提供。desc 为空串
* 则清空备注。
* 修改收藏表情(custom face)备注。emoji_id 来自收藏列表;md5 从 emoji_id
* 中段解析,无需调用方单独提供。desc 为空串则清空备注。
*/
modifyCustomFace(emojiId: string, desc: string): Promise<void> {
return ModifyCustomFace.invoke(this.ctx, {
@@ -230,13 +277,13 @@ 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}`);
if (idx < 0) {
throw new Error(`emoji_id not in list: ${emojiId}`);
}
// 新顺序:目标挪到第一,其余按原顺序
const reordered = ids.slice();
reordered.splice(idx, 1);
@@ -259,8 +306,10 @@ function md5FromEmojiId(emojiId: string): string {
const parts = emojiId.split('_');
// 期望形如 `<uin>_0_0_0_<md5>_0_0`,共 7 段,md5 在 index 4。
const md5 = parts[4];
if (!md5 || md5.length !== 32 || !/^[0-9a-fA-F]{32}$/.test(md5)) {
throw new Error(`invalid emoji_id (cannot extract md5): ${emojiId}`);
}
return md5.toUpperCase();
}
+20 -3
View File
@@ -68,7 +68,15 @@ export class QzoneApi {
targetUins?: string,
): Promise<QzonePublishResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content, richType, richval, ugcRight, targetUins);
return publishQzoneMsg(
cookieObject,
this.ctx.identity.uin,
content,
richType,
richval,
ugcRight,
targetUins,
);
}
/** 删除机器人自己空间的一条说说(按 tid)。 */
@@ -81,7 +89,11 @@ export class QzoneApi {
* 修改机器人自己空间一条已发说说的查看权限(按 tid)。
* `ugcRight` / `targetUins` 含义同 publish(16/128 时 targetUins 必填)。
*/
async updateRight(tid: string, ugcRight: number, targetUins?: string): Promise<QzoneUpdateRightResult> {
async updateRight(
tid: string,
ugcRight: number,
targetUins?: string,
): Promise<QzoneUpdateRightResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return updateQzoneMsgRight(cookieObject, this.ctx.identity.uin, tid, ugcRight, targetUins);
}
@@ -90,7 +102,12 @@ export class QzoneApi {
* 给一条说说点赞/取消赞。`targetUin` 省略时点赞机器人自己空间的说说;
* 点赞好友说说时传好友 uin(tid 来自 get_qzone_feeds / get_qzone_msg_list)。
*/
async like(tid: string, targetUin: number | undefined, like: boolean, abstime = 0): Promise<void> {
async like(
tid: string,
targetUin: number | undefined,
like: boolean,
abstime = 0,
): Promise<void> {
const selfUin = this.ctx.identity.uin;
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
+1 -25
View File
@@ -1,28 +1,4 @@
export function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'bigint') {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
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}`);
}
export { toInt } from '@snowluma/protocol/oidb-services/shared';
// 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
@@ -20,6 +20,7 @@ export class SystemFaceApi {
await sysFaceStore.refresh(this.ctx);
return sysFaceStore.lookup(faceId);
}
return sysFaceStore.resolve(this.ctx, faceId);
}
+103 -33
View File
@@ -1,15 +1,27 @@
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
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 {
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 {
getHonorListWebAPI,
WebHonorType,
type WebHonorItem,
} from '@snowluma/protocol/web/group-honor';
import { getDaySignedListWebAPI, type SignedListMember } from '@snowluma/protocol/web/group-signin';
import {
deleteGroupNotice as deleteGroupNoticeHttp,
GROUP_NOTICE_TYPE_NEW_MEMBERS,
GROUP_NOTICE_TYPE_NORMAL,
getGroupNoticeWebAPI,
groupNoticeImageUrl,
setGroupNoticeWebAPI,
uploadGroupNoticeImage,
type SetNoticeRetSuccess,
@@ -21,7 +33,9 @@ import { RequestUtil } from '@snowluma/protocol/web/request-util';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
function asBridge(ctx: BridgeContext): Bridge {
return ctx as unknown as Bridge;
}
export type ClientKeyInfo = NamespaceClientKeyInfo;
@@ -43,8 +57,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;
@@ -65,10 +79,17 @@ export interface SendNoticeOptions {
}
function finiteNumber(value: unknown, field: string): number {
const parsed = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN;
const parsed =
typeof value === 'number'
? value
: typeof value === 'string' && value.trim() !== ''
? Number(value)
: Number.NaN;
if (!Number.isFinite(parsed)) {
throw new Error(`invalid group notice response: ${field} must be a finite number`);
}
return parsed;
}
@@ -76,11 +97,18 @@ function collectionValues(
collection: WebApiGroupNoticeCollection | undefined,
field: 'feeds' | 'inst',
): WebApiGroupNoticeFeed[] {
if (collection === undefined) return [];
if (Array.isArray(collection)) return collection;
if (collection === undefined) {
return [];
}
if (Array.isArray(collection)) {
return collection;
}
if (collection === null || typeof collection !== 'object') {
throw new Error(`invalid group notice response: ${field} must be an array or object`);
}
return Object.values(collection);
}
@@ -88,28 +116,38 @@ function mapGroupNoticeFeed(feed: WebApiGroupNoticeFeed, sendToNewMembers: boole
if (!feed || typeof feed !== 'object') {
throw new Error('invalid group notice response: feed must be an object');
}
if (typeof feed.fid !== 'string' || feed.fid.length === 0) {
throw new Error('invalid group notice response: feed.fid must be a non-empty string');
}
if (!feed.msg || typeof feed.msg !== 'object' || typeof feed.msg.text !== 'string') {
throw new Error(`invalid group notice response: feed ${feed.fid} has no message text`);
}
if (feed.settings === undefined) {
throw new Error(`invalid group notice response: feed ${feed.fid} has no settings`);
}
const image = (feed.msg.pics ?? []).map((pic, index) => {
if (!pic || typeof pic !== 'object' || typeof pic.id !== 'string') {
throw new Error(`invalid group notice response: feed ${feed.fid} image ${index} is malformed`);
throw new Error(
`invalid group notice response: feed ${feed.fid} image ${index} is malformed`,
);
}
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`),
};
});
const responseType = feed.type === undefined
? sendToNewMembers ? GROUP_NOTICE_TYPE_NEW_MEMBERS : GROUP_NOTICE_TYPE_NORMAL
const responseType =
feed.type === undefined
? sendToNewMembers
? GROUP_NOTICE_TYPE_NEW_MEMBERS
: GROUP_NOTICE_TYPE_NORMAL
: finiteNumber(feed.type, `feed ${feed.fid}.type`);
return {
@@ -124,7 +162,8 @@ function mapGroupNoticeFeed(feed: WebApiGroupNoticeFeed, sendToNewMembers: boole
settings: feed.settings,
read_num: finiteNumber(feed.read_num, `feed ${feed.fid}.read_num`),
type: responseType,
pinned: feed.pinned === undefined ? 0 : finiteNumber(feed.pinned, `feed ${feed.fid}.pinned`),
pinned:
feed.pinned === undefined ? 0 : finiteNumber(feed.pinned, `feed ${feed.fid}.pinned`),
send_to_new_members: sendToNewMembers || responseType === GROUP_NOTICE_TYPE_NEW_MEMBERS,
};
}
@@ -137,10 +176,16 @@ export function mapGroupNoticeResponse(ret: WebApiGroupNoticeRet): WebNoticeInfo
const notices: WebNoticeInfo[] = [];
const indexByNoticeId = new Map<string, number>();
const append = (collection: WebApiGroupNoticeCollection | undefined, sendToNewMembers: boolean, field: 'feeds' | 'inst') => {
const append = (
collection: WebApiGroupNoticeCollection | undefined,
sendToNewMembers: boolean,
field: 'feeds' | 'inst',
) => {
for (const feed of collectionValues(collection, field)) {
const mapped = mapGroupNoticeFeed(feed, sendToNewMembers);
const existingIndex = indexByNoticeId.get(mapped.notice_id);
if (existingIndex === undefined) {
indexByNoticeId.set(mapped.notice_id, notices.length);
notices.push(mapped);
@@ -163,7 +208,10 @@ function forceFetchClientKeyInner(bridge: Bridge): Promise<ClientKeyInfo> {
return ForceFetchClientKey.invoke(bridge);
}
function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
function getPSkey(
bridge: Bridge,
domainList: string[],
): Promise<{ domainPskeyMap: Map<string, string> }> {
return GetPskey.invoke(bridge, { domainList });
}
@@ -173,9 +221,17 @@ async function getCookies(bridge: Bridge, domain: string): Promise<Record<string
// Build the ptlogin2 jump URL: this is the canonical way for the
// bot to swap its clientKey for cookie-jar entries on a given
// qq.com subdomain.
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
const requestUrl =
'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' +
bridge.identity.uin +
'&clientkey=' +
ClientKeyData.clientKey +
'&u1=https%3A%2F%2F' +
domain +
'%2F' +
bridge.identity.uin +
'%2Finfocenter&keyindex=' +
ClientKeyData.keyIndex;
const data = await RequestUtil.HttpsGetCookies(requestUrl);
@@ -186,6 +242,7 @@ async function getCookies(bridge: Bridge, domain: string): Promise<Record<string
try {
const pskeyData = await getPSkey(bridge, [domain]);
const pskey = pskeyData.domainPskeyMap.get(domain);
if (pskey) {
data['p_skey'] = pskey;
}
@@ -204,12 +261,19 @@ async function getSKey(bridge: Bridge): Promise<string> {
throw new Error('getClientKey Error: clientKey is empty');
}
const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0');
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
'&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=' + u1 +
'&keyindex=' + ClientKeyData.keyIndex;
const u1 = encodeURIComponent(
'https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0',
);
const requestUrl =
'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
'&clientuin=' +
bridge.identity.uin +
'&clientkey=' +
ClientKeyData.clientKey +
'&u1=' +
u1 +
'&keyindex=' +
ClientKeyData.keyIndex;
const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
const skey = cookies['skey'];
@@ -227,9 +291,11 @@ async function getSKey(bridge: Bridge): Promise<string> {
*/
function getBknFromSKey(skey: string): number {
let hash = 5381;
for (let i = 0; i < skey.length; i++) {
hash += (hash << 5) + skey.charCodeAt(i);
}
return hash & 2147483647;
}
@@ -259,14 +325,18 @@ export class WebApi {
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
async getCsrfToken(): Promise<number> {
const skey = await getSKey(asBridge(this.ctx));
if (!skey) {
throw new Error('SKey is Empty');
}
return getBknFromSKey(skey);
}
/** Returns the OneBot `get_credentials` payload (cookie string + bkn). */
async getCredentials(domain: string): Promise<{ cookies: string; token: number; csrf_token: number }> {
async getCredentials(
domain: string,
): Promise<{ cookies: string; token: number; csrf_token: number }> {
const cookieObject = await getCookies(asBridge(this.ctx), domain);
const cookiesStr = Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
@@ -320,6 +390,7 @@ export class WebApi {
if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) {
const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1);
if (talkativeList.length > 0) {
honorInfo.current_talkative = talkativeList[0];
honorInfo.talkative_list = talkativeList;
@@ -348,7 +419,11 @@ export class WebApi {
async getSignedList(groupId: number): Promise<SignedListMember[]> {
const bridge = asBridge(this.ctx);
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return getDaySignedListWebAPI(cookieObject, groupId.toString(), bridge.identity.uin.toString());
return getDaySignedListWebAPI(
cookieObject,
groupId.toString(),
bridge.identity.uin.toString(),
);
}
// ─────────────── group notice ───────────────
@@ -379,11 +454,7 @@ export class WebApi {
imgHeight = picInfo.height;
}
const ret = await setGroupNoticeWebAPI(
cookieObject,
groupCode,
content,
{
const ret = await setGroupNoticeWebAPI(cookieObject, groupCode, content, {
pinned: options?.pinned,
type: options?.type,
sendToNewMembers: options?.sendToNewMembers,
@@ -393,8 +464,7 @@ export class WebApi {
picId,
imgWidth,
imgHeight,
},
);
});
if (ret.ec !== 0) {
throw new Error(`设置群公告失败: ec=${ret.ec ?? 'missing'}, em=${ret.em ?? 'missing'}`);
@@ -5,4 +5,3 @@ export interface BridgeContext extends BaseBridgeContext {
readonly apis: ApiHub;
}
export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context';
+9 -2
View File
@@ -1,10 +1,17 @@
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. */
+395 -79
View File
@@ -1,30 +1,20 @@
import {
createLogger,
renderTraceBytes,
runWithTraceRequest,
} 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,
parseMsgPushOrThrow,
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 { AiVoiceChatType, type AiVoiceCategory, type StrangerStatus } from './apis/extras';
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;
@@ -42,99 +32,140 @@ export class Bridge implements BridgeInterface {
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
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 disposePromise_: Promise<void> | null = null;
private readonly pendingPackets_ = new Set<Promise<void>>();
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',
groupId, uid, main.reason instanceof Error ? main.reason.message : String(main.reason));
log.warn(
'group-request enrichment main inbox failed: group=%d uid=%s err=%s',
groupId,
uid,
main.reason instanceof Error ? main.reason.message : String(main.reason),
);
}
if (filtered.status === 'rejected') {
log.warn('group-request enrichment filtered inbox failed: group=%d uid=%s err=%s',
groupId, uid, filtered.reason instanceof Error ? filtered.reason.message : String(filtered.reason));
log.warn(
'group-request enrichment filtered inbox failed: group=%d uid=%s err=%s',
groupId,
uid,
filtered.reason instanceof Error
? filtered.reason.message
: String(filtered.reason),
);
}
if (main.status === 'rejected' && filtered.status === 'rejected') {
throw new Error('failed to fetch group requests from both inboxes');
}
const requests = [
...(main.status === 'fulfilled' ? main.value : []),
...(filtered.status === 'fulfilled' ? filtered.value : []),
];
return requests.find(r => {
if (r.groupId !== groupId) return false;
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;
do {
const sequence = this.apis.contacts.getGroupInviteCardSequence(groupId);
if (sequence) return sequence;
await new Promise(resolve => setTimeout(resolve, 25));
if (sequence) {
return sequence;
}
await new Promise((resolve) => setTimeout(resolve, 25));
} while (Date.now() < deadline);
return null;
},
rememberGroupInviteCardSequence: (groupUin, sequence) => {
this.apis.contacts.rememberGroupInviteCardSequence(groupUin, sequence);
},
});
this.pipeline.registerCmd(
MSG_PUSH_CMD,
(pkt, identity) => parseMsgPushOrThrow(
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(','));
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 {
dispose(): Promise<void> {
if (this.disposePromise_) {
return this.disposePromise_;
}
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;
this.disposePromise_ = (async () => {
try {
this.identity.close();
await Promise.allSettled(this.pendingPackets_);
await this.identity.close();
} finally {
// A close failure must remain visible to the caller, but must not leave
// event subscribers attached to a Bridge that Manager already removed.
this.events.clear();
}
})();
return this.disposePromise_;
}
/** Legacy two-step setter retained for external compatibility. It assigns
@@ -145,7 +176,12 @@ export class Bridge implements BridgeInterface {
const pids = [...this.pids_];
const pid = pids.length > 0 ? pids[pids.length - 1]! : null;
this.packetClientPid_ = pid;
if (pid !== null) this.packetClientsByPid_.set(pid, client);
if (pid !== null) {
this.packetClientsByPid_.set(pid, client);
}
this.maybeStartRosterWarmup();
}
registerCmd(cmd: string, parser: CmdParser): void {
@@ -177,6 +213,7 @@ export class Bridge implements BridgeInterface {
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',
@@ -185,6 +222,8 @@ export class Bridge implements BridgeInterface {
previousPid,
);
}
this.maybeStartRosterWarmup();
}
/** @internal BridgeManager lookup used when an incoming packet is the first
@@ -206,65 +245,103 @@ export class Bridge implements BridgeInterface {
this.packetClient_ = null;
this.packetClientPid_ = null;
}
return;
}
this.selectFallbackPacketClient(pid);
}
hasPid(pid: number): boolean { return this.pids_.has(pid); }
get empty(): boolean { return this.pids_.size === 0; }
hasPid(pid: number): boolean {
return this.pids_.has(pid);
}
get empty(): boolean {
return this.pids_.size === 0;
}
get activePid(): number | null {
if (this.packetClientPid_ !== null && this.pids_.has(this.packetClientPid_)) {
return this.packetClientPid_;
}
const pids = [...this.pids_];
return pids.length > 0 ? pids[pids.length - 1]! : null;
}
get receiveHealthy(): boolean {
for (const pid of this.pids_) {
const healthy = this.receiveHealthByPid_.get(pid);
if (healthy === undefined) {
const message = `Bridge receive-health invariant violated: PID=${pid} has no health state`;
log.error(message);
throw new Error(message);
}
if (healthy) return true;
if (healthy) {
return true;
}
}
return false;
}
setPidReceiveHealthy(pid: number, healthy: boolean): void {
if (!this.pids_.has(pid)) {
throw new Error(`Bridge receive-health invariant violated: PID=${pid} is not attached`);
}
this.receiveHealthByPid_.set(pid, healthy);
}
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null {
return this.onlineClients_;
}
onPacket(pkt: PacketInfo): Promise<void> {
return this.pipeline.process(pkt);
whenRosterWarmupSettled(): Promise<RosterWarmupResult> {
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
return Promise.resolve(this.rosterWarmupResult_);
}
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
if (refreshGroupList) {
try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ }
this.maybeStartRosterWarmup();
return new Promise((resolve) => {
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
resolve(this.rosterWarmupResult_);
return;
}
if (!this.identity.findGroup(groupId)) return false;
await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
this.rosterWarmupWaiters_.push(resolve);
});
}
onPacket(pkt: PacketInfo): Promise<void> {
if (this.disposed_) {
return Promise.reject(new Error('Bridge is disposed'));
}
const work = this.identity.initialization.then(() => this.pipeline.process(pkt));
this.pendingPackets_.add(work);
void work.finally(() => this.pendingPackets_.delete(work)).catch(() => undefined);
return work;
}
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) return;
if (!meta.fileId) {
return;
}
if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) {
// Map iteration order is insertion order — drop the oldest.
const oldest = this.uploadedFileMeta_.keys().next().value;
if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest);
if (oldest !== undefined) {
this.uploadedFileMeta_.delete(oldest);
}
}
this.uploadedFileMeta_.set(meta.fileId, meta);
}
recallUploadedFile(fileId: string): UploadedFileMeta | undefined {
if (!fileId) return undefined;
if (!fileId) {
return undefined;
}
return this.uploadedFileMeta_.get(fileId);
}
@@ -273,10 +350,14 @@ export class Bridge implements BridgeInterface {
}
nextMessageRandom(): number {
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
return this.msgRandom_ & 0x7FFFFFFF;
this.msgRandom_ = (this.msgRandom_ + 0x9e3779b9) >>> 0;
return this.msgRandom_ & 0x7fffffff;
}
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
async sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs = packetTimeoutMs(),
): Promise<SendPacketResult> {
if (!this.packetClient_) {
return runWithTraceRequest(() => {
const startedAt = Date.now();
@@ -300,36 +381,59 @@ export class Bridge implements BridgeInterface {
Date.now() - startedAt,
]);
return {
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'no packet sender attached', responseData: null,
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);
const result = await this.packetClient_.sendPacket(
serviceCmd,
Buffer.from(body),
timeoutMs,
);
const elapsed = Date.now() - startedAt;
const respLen = result.responseData ? result.responseData.length : 0;
if (!result.success || result.errorCode !== 0) {
// QQ-side rejection or transport failure — the usual root cause when an
// action misbehaves. Warn (persisted) with cmd + code so a user's log
// shows exactly where the chain broke.
log.warn('packet %s failed: code=%d gotResponse=%s %s (uin=%s, %dB, %dms)',
serviceCmd, result.errorCode, result.gotResponse,
result.errorMessage ?? '', this.identity.uin, body.length, elapsed);
log.warn(
'packet %s failed: code=%d gotResponse=%s %s (uin=%s, %dB, %dms)',
serviceCmd,
result.errorCode,
result.gotResponse,
result.errorMessage ?? '',
this.identity.uin,
body.length,
elapsed,
);
} else {
// Happy path — memory-only trace so the full chain shows under the
// request's [req#N] when debugging, without flooding disk.
log.trace(() => [`packet ${serviceCmd} ok (${body.length}B⇄${respLen}B, ${elapsed}ms)`]);
log.trace(() => [
`packet ${serviceCmd} ok (${body.length}B⇄${respLen}B, ${elapsed}ms)`,
]);
}
return result;
}
private selectFallbackPacketClient(detachedPid: number): void {
const pids = [...this.pids_];
for (let index = pids.length - 1; index >= 0; index -= 1) {
const fallbackPid = pids[index]!;
const fallback = this.packetClientsByPid_.get(fallbackPid);
if (!fallback) continue;
if (!fallback) {
continue;
}
this.packetClient_ = fallback;
this.packetClientPid_ = fallbackPid;
@@ -350,6 +454,7 @@ export class Bridge implements BridgeInterface {
this.packetClient_ = null;
this.packetClientPid_ = null;
if (this.pids_.size > 0) {
log.warn(
'packet sender unavailable after PID detach: UIN=%s detached PID=%d remaining PIDs=%d',
@@ -362,6 +467,217 @@ 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> {
await this.identity.initialization;
if (this.disposed_) {
return { friendsLoaded: false, groupsLoaded: false };
}
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;
@@ -399,7 +715,7 @@ export interface DownloadRKeyInfo {
export interface ClientKeyInfo {
clientKey: string;
expireTime: string;
keyIndex: string
keyIndex: string;
}
export { AiVoiceChatType };
export type { AiVoiceCategory, StrangerStatus };
+95 -32
View File
@@ -1,8 +1,4 @@
import {
createLogger,
renderTraceBytes,
runWithTraceRequest,
} 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';
@@ -23,6 +19,44 @@ const runtimeLog = createLogger('Bridge.Runtime');
export class BridgeManager {
private sessions_ = new Map<string, QQSession>();
private pidToUin_ = new Map<number, string>();
private readonly closingSessions_ = new Map<string, Promise<void>>();
private readonly closeErrors_: unknown[] = [];
/** Hook callbacks remain synchronous; shutdown awaits every detached account. */
async dispose(): Promise<void> {
for (const [uin, session] of this.sessions_) {
this.closeSession(uin, session.bridge);
}
this.sessions_.clear();
this.pidToUin_.clear();
await Promise.allSettled(this.closingSessions_.values());
if (this.closeErrors_.length) {
throw new AggregateError(this.closeErrors_, 'Bridge persistence shutdown failed');
}
}
private closeSession(uin: string, bridge: Bridge): void {
const previous = this.closingSessions_.get(uin);
const closing = Promise.all([previous, bridge.dispose()]).then(() => undefined);
this.closingSessions_.set(uin, closing);
void closing.then(
() => {
if (this.closingSessions_.get(uin) === closing) {
this.closingSessions_.delete(uin);
}
},
(error) => {
this.closeErrors_.push(error);
log.error(
'identity close failed: UIN=%s err=%s',
uin,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
},
);
}
private sessionStartedListeners_: SessionStartedCallback[] = [];
private sessionClosedListeners_: SessionClosedCallback[] = [];
@@ -44,7 +78,10 @@ export class BridgeManager {
try {
cb(uin, bridge);
} catch (err) {
log.warn('session-started listener threw: %s', err instanceof Error ? err.message : String(err));
log.warn(
'session-started listener threw: %s',
err instanceof Error ? err.message : String(err),
);
}
}
}
@@ -54,25 +91,29 @@ export class BridgeManager {
try {
cb(uin, bridge);
} catch (err) {
log.warn('session-closed listener threw: %s', err instanceof Error ? err.message : String(err));
log.warn(
'session-closed listener threw: %s',
err instanceof Error ? err.message : String(err),
);
}
}
}
onPidDisconnected(pid: number): void {
const uin = this.pidToUin_.get(pid);
if (!uin) return;
if (!uin) {
return;
}
runWithTraceRequest(() => {
const startedAt = Date.now();
runtimeLog.trace(
'bridge_detach_start pid=%d uin=%j',
pid,
uin,
);
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',
@@ -80,6 +121,7 @@ export class BridgeManager {
uin,
);
}
runtimeLog.trace(
'bridge_detach_terminal pid=%d uin=%j outcome=completed reason=%s activePid=%j elapsedMs=%d',
pid,
@@ -103,6 +145,7 @@ export class BridgeManager {
onPidReceiveHealthChanged(pid: number, healthy: boolean): void {
const uin = this.pidToUin_.get(pid);
if (!uin) {
const message = `BridgeManager invariant violated: receive health for unmapped PID=${pid}`;
log.error(message);
@@ -110,16 +153,20 @@ export class BridgeManager {
}
const session = this.sessions_.get(uin);
if (!session || !session.bridge.hasPid(pid)) {
const message = `BridgeManager invariant violated: receive health PID=${pid} is not owned by UIN=${uin}`;
log.error(message);
throw new Error(message);
}
session.bridge.setPidReceiveHealthy(pid, healthy);
}
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
if (!isRealUin(uin)) return;
if (!isRealUin(uin)) {
return;
}
runWithTraceRequest(() => {
const startedAt = Date.now();
@@ -133,6 +180,7 @@ export class BridgeManager {
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',
@@ -160,6 +208,7 @@ export class BridgeManager {
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,
@@ -199,6 +248,7 @@ export class BridgeManager {
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',
@@ -208,10 +258,12 @@ export class BridgeManager {
]);
return;
}
const uin = pkt.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
@@ -235,20 +287,14 @@ export class BridgeManager {
this.tracePacketFailure(
pkt,
startedAt,
handedToPipeline
? 'pipeline_failed'
: 'routing_failed',
handedToPipeline ? 'pipeline_failed' : 'routing_failed',
error,
);
throw error;
}
void completion.catch((error) => {
this.tracePacketFailure(
pkt,
startedAt,
'pipeline_failed',
error,
);
this.tracePacketFailure(pkt, startedAt, 'pipeline_failed', error);
});
}
@@ -268,9 +314,7 @@ export class BridgeManager {
]);
log.error(
'packet %s failed for %s: %s',
reason === 'routing_failed'
? 'routing'
: 'pipeline',
reason === 'routing_failed' ? 'routing' : 'pipeline',
pkt.serviceCmd,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
@@ -286,6 +330,7 @@ export class BridgeManager {
source: 'login' | 'packet',
): { session: QQSession; created: boolean } {
const previousUin = this.pidToUin_.get(pid);
if (previousUin && previousUin !== uin) {
log.warn(
'PID ownership changed: PID=%d UIN=%s -> UIN=%s source=%s',
@@ -305,9 +350,13 @@ export class BridgeManager {
private packetClientForPid(pid: number): PacketSender | null {
const uin = this.pidToUin_.get(pid);
if (!uin) return null;
if (!uin) {
return null;
}
const session = this.sessions_.get(uin);
if (!session) {
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
log.error(message);
@@ -315,7 +364,10 @@ export class BridgeManager {
}
const packetClient = session.bridge.packetClientForPid(pid);
if (packetClient) return packetClient;
if (packetClient) {
return packetClient;
}
const message = `BridgeManager invariant violated: PID=${pid} has no sender in UIN=${uin} session`;
log.error(message);
@@ -324,6 +376,7 @@ export class BridgeManager {
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'}`;
log.error(message);
@@ -331,6 +384,7 @@ export class BridgeManager {
}
const session = this.sessions_.get(uin);
if (!session) {
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
log.error(message);
@@ -342,6 +396,7 @@ export class BridgeManager {
log.error(message);
throw new Error(message);
}
if (!session.bridge.packetClientForPid(pid)) {
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge has no sender for the PID`;
log.error(message);
@@ -352,21 +407,29 @@ 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 false;
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();
this.closeSession(uin, session.bridge);
return true;
}
private ensureSession(uin: string): { session: QQSession; created: boolean } {
let session = this.sessions_.get(uin);
if (session) return { session, created: false };
const bridge = new Bridge(IdentityService.openForUin(uin));
if (session) {
return { session, created: false };
}
const bridge = new Bridge(
IdentityService.openForUin(uin, 'data', this.closingSessions_.get(uin)),
);
session = { bridge };
this.sessions_.set(uin, session);
+106 -15
View File
@@ -1,4 +1,4 @@
import { HookManager } from '@snowluma/bridge';
import { getRuntimeIntegrity, HookManager } from '@snowluma/bridge';
import { configureFileTransport } from '@snowluma/common/log-file-transport';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import {
@@ -19,6 +19,8 @@ import { BridgeManager } from './bridge/manager';
import { createNotificationManager } from './notifications/manager';
import { createStateWiring } from './webui/state-wiring';
import { bindSystemFaceCatalog } from './sys-face-catalog';
import { readAppVersion, startNativeStageSync, tempStagePath } from './native-stage-sync';
import { logRuntimeIntegrity } from './runtime-integrity-log';
const log = createLogger('App');
@@ -32,8 +34,10 @@ function installProcessGuards(): void {
// 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));
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);
@@ -48,6 +52,12 @@ async function main() {
perUinEnabled: runtimeConfig.logPerUin ?? DEFAULT_LOG_PER_UIN,
});
log.info('SnowLuma starting');
logRuntimeIntegrity(getRuntimeIntegrity());
const stopNativeStageSync = startNativeStageSync({
version: readAppVersion(import.meta.url),
dataDir: 'data',
tempPath: tempStagePath(),
});
// One-shot: lift a legacy per-UIN musicSignUrl into the global store before
// any session (and thus any per-UIN config rewrite) can drop it.
@@ -71,6 +81,7 @@ async function main() {
autoLoadOnDiscovery,
onSessionsChanged: stateWiring.onSessionsChanged,
});
if (autoLoadOnDiscovery) {
log.info('hook auto-load enabled: every discovered QQ process will be injected');
}
@@ -83,18 +94,27 @@ 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);
}
@@ -103,43 +123,114 @@ async function main() {
// Graceful shutdown: dispose managers, await log flush, then exit.
// SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path.
let shutdownStarted = false;
const shutdown = (signal: string) => async () => {
if (shutdownStarted) return;
if (shutdownStarted) {
return;
}
shutdownStarted = true;
log.warn(`Shutting down (${signal})...`);
let exitCode = 0;
try {
await oneBotManager.dispose();
} catch (error) {
exitCode = 1;
log.error('OneBot shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
log.error(
'OneBot shutdown failed: %s',
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
}
try { notificationManager.dispose(); } catch (error) {
try {
notificationManager.dispose();
} catch (error) {
exitCode = 1;
log.error('notification shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
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),
);
}
try { stateWiring.dispose(); } catch (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));
log.error(
'state wiring shutdown failed: %s',
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
}
try {
stopNativeStageSync.stop();
} catch (error) {
exitCode = 1;
log.error(
'stage sync shutdown failed: %s',
error instanceof Error ? error.message : String(error),
);
}
try {
hookManager.dispose();
} catch (error) {
exitCode = 1;
log.error(
'hook shutdown failed: %s',
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
}
try {
await bridgeManager.dispose();
} catch (error) {
exitCode = 1;
log.error(
'bridge shutdown failed: %s',
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
}
await closeLogger();
process.exit(exitCode);
};
process.on('SIGINT', shutdown('SIGINT'));
process.on('SIGTERM', shutdown('SIGTERM'));
}
function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
const envRaw = process.env.SNOWLUMA_HOOK_AUTOLOAD;
if (typeof envRaw === 'string' && envRaw.trim()) {
const v = envRaw.trim().toLowerCase();
if (v === '1' || v === 'true' || v === 'yes' || v === 'on') return true;
if (v === '0' || v === 'false' || v === 'no' || v === 'off') return false;
if (v === '1' || v === 'true' || v === 'yes' || v === 'on') {
return true;
}
if (v === '0' || v === 'false' || v === 'no' || v === 'off') {
return false;
}
}
return fromConfig === true;
}
Loaded 100 of 986 files, more files were not shown because too many files have changed in this diff. Show more