Compare commits

...

359 Commits
v1.5.3 ... dev2

Author SHA1 Message Date
手瓜一十雪
3870052fb4 Simplify Hub channel management
Refactor Hub to treat each UIN as a single active Channel: channelsByUin_ now maps UIN -> Channel (no Set of IDs), primary selection logic and primaryByUin_/pickPrimary were removed, and addChannel replaces any existing channel for a UIN (disposing the previous one). Updated add/remove flows to update channelsById_ and channelsByUin_ accordingly and to bring cores online/offline in the simplified model.

Also: removed extensive JSDoc/comment blocks from channel/adapter/channel-ctx/core/hub files to slim the public API surface, reordered/cleaned exports in packages/channel/src/index.ts, added a new hub-events.ts placeholder, and cleaned up a test helper comment. Disposal of replaced channels is wrapped with a try/catch and logged at debug level.
2026-05-27 18:07:03 +08:00
手瓜一十雪
b019b00e82 Set protobuf plugin root for OneBot tests
Pass the monorepo root to @snowluma/proton's Vite plugin so protobuf encode/decode call sites in transitive workspace packages are transformed during testing. Adds path/fileURLToPath imports and __dirname, and calls protobufVitePlugin({ root: path.resolve(__dirname, '../..') }) to mirror @snowluma/core's setup and avoid "was not transformed" errors in OneBot tests.
2026-05-27 14:21:51 +08:00
手瓜一十雪
50aa9b3595 Allow vitest to pass with no tests
Update packages/channel/package.json test script to run `vitest run --passWithNoTests` so CI or local runs won't fail when the package has no tests. No other behavior changes.
2026-05-27 14:15:44 +08:00
手瓜一十雪
af8d5ab06b Split channel packages and rename Account→Core
Reorganize package layout and rename core/account types: - Move channel hook & socket sources/tests into packages/channel-hook and packages/channel-socket (many files renamed). - Remove ChannelManager from packages/channel and drop its export from package.json (multi-account host folded into Hub). - Update tests to use HookSink instead of BridgeManagerSink. - In @snowluma/core: move account/apis/* up to src/apis, rename account-context→core-context, account-interface→core-ctx, account→core, and add hub.ts; delete AccountManager. - Update constructors and type usages to accept CoreContext/CoreCtx and adapt identifiers accordingly. This is a refactor to clarify responsibilities (split transport implementations, fold multi-account manager into Hub, and rebrand the account layer as Core).
2026-05-27 14:11:45 +08:00
手瓜一十雪
adf0744f75 Rename bridge → channel and reorganize packages
Move/rename the transport/bridge code into a new @snowluma/channel layout and extract hook implementations into channel-specific packages. Many bridge sources were deleted and equivalent channel files added (adapter/ctx/interface/channel/hook/socket pieces moved/renamed), along with tests and configs relocated under packages/channel. RoadMap.md replaced with a detailed v3 architecture plan describing Channel/ChannelCtx/Core/CoreCtx/Hub boundaries and migration steps. Also apply related core package updates (account/core reshaping and package.json adjustments) to match the new architecture.
2026-05-27 13:39:17 +08:00
手瓜一十雪
652bafd75a Extract bridge transport into @snowluma/bridge
Move transport-layer bridge code out of @snowluma/core into a dedicated @snowluma/bridge package and introduce a clear account layer in core. Adds Bridge, BridgeInterface, InjectBridge, ProtocolBridge (stub), adapters, and manager files under packages/bridge and updates package.json exports. In @snowluma/core the former bridge surface is replaced by Account, AccountContext, AccountInterface and AccountManager; apis were moved/renamed to account/apis and now consume AccountContext. Adjustments include packet handling plumbing (use deliverPacket / setPacketHandler), updated sendRawPacket wiring, uploaded-file cache and lifecycle changes (InjectBridge.dispose, ProtocolBridge returns a structured not-implemented result). Tests and imports were updated accordingly.
2026-05-27 12:27:13 +08:00
手瓜一十雪
5440cbc37e Refactor bridge system: adapters & transports
Introduce a transport-adapter layer and refactor the bridge abstractions to be transport-agnostic. Added BridgeAdapter and BridgeAdapterHost (packages/core/src/bridge/adapter.ts) plus concrete InjectBridge/InjectBridgeAdapter and ProtocolBridge/ProtocolBridgeAdapter implementations (new files). Made Bridge an abstract base exposing kind/id and abstract sendRawPacket, moved transport-specific PID/sender logic into InjectBridge. Reworked BridgeManager to register/start adapters, manage bridges by id/uin, pick a primary per-UIN (inject preferred over protocol), and provide a host API for adapters to add/remove bridges. Updated index bootstrapping to register adapters and wire the WebUI to the inject adapter's HookManager. Adjusted tests and OneBot code to remove PID tracking from OneBotInstance/OneBotManager and to instantiate InjectBridge in tests. Also exported new entry points in package.json for adapter/bridge modules. This decouples transports from manager logic and adds a stubbed protocol runtime for future pure-protocol support.
2026-05-27 11:49:43 +08:00
手瓜一十雪
a434da9e85 Skip resolveImports for files without subclasses
Add a cheap AST probe in file-pipeline to detect if a file contains extending classes (using fileHasExtendingClass) and return early to avoid the expensive resolveImports recursive descent when not needed.

Update subclass-wrapper tests to import beforeAll and cache the plugin transform output and its stripped JS once in a beforeAll hook, replacing repeated transform calls with reused transformedOutput/strippedJs to reduce test runtime.
2026-05-26 22:02:31 +08:00
手瓜一十雪
2c565fbd8d Switch from @snowluma/sqlite to node:sqlite (sync)
Remove the in-tree @snowluma/sqlite wrapper and vendored better-sqlite3 prebuilts; migrate consumers to node:sqlite's synchronous API. Replaced imports and types (Database/Statement -> DatabaseSync/StatementSync), updated PRAGMA calls to use exec, and adjusted code in onebot (media/message/reaction stores) and protocol (identity service). Vite config no longer bundles sqlite native binaries and references to the sqlite workspace were removed. Also delete the packages/sqlite package and its native prebuild artifacts, and add a couple of unrelated AST improvements in proton: use a module-level shared wrapper cache and add an inheritance cache to avoid repeated scans. Minor import reordering/cleanup applied where needed.
2026-05-26 21:59:26 +08:00
手瓜一十雪
0d30ee628e Switch subclass-wrapper to AST-only pipeline
Refactor subclass-wrapper resolution to an AST-only pipeline and remove the TypeChecker-based program cache.

- Move subclass-wrapper logic from typecheck/ to ast/: add ast/file-pipeline.ts and ast/subclass-wrapper.ts, and update codegen/imports accordingly.
- Implement AST-only cross-file extends resolution using import-resolver's fileCache (findImportSourcePath) and a WrapperLookupCache; subclass methods must now have explicit type annotations (no TypeChecker inference).
- Remove TypeChecker-dependent program-cache and typecheck/file-pipeline; plugin no longer preloads a ts.Program or accepts tsconfig option.
- Simplify plugin cache startup and HMR handling in src/index.ts to use the AST pipeline and transform cache only.
- Update tests to use the new AST pipeline entrypoints and adjust expectations.

This eliminates the dependency on a baked ts.Program for wrapper resolution, simplifies startup, and relies on the existing import-resolver for cross-file traversal. Partial wrapper resolutions are still all-or-nothing; explicit annotations are required for AST-only resolution.
2026-05-26 21:48:12 +08:00
手瓜一十雪
0f7aa5a600 Refactor import & wrapper typecheck APIs
Consolidate and simplify import extraction and wrapper/typecheck internals. Introduce collectImportClauses that drives both type+value and value-only import extraction with per-file caching; reintroduce extractImports/extractValueImports as thin wrappers. Clean up BARE_SPECIFIER_COMPILER_OPTIONS comment. Replace the containsTypeParameter/firstTypeParameterIndex pair with a single findTypeParameterIndex helper. Remove collectExportedWrappers and call collectWrappers directly from parseFileForDefinitions; ensure imported wrapper collection skips type-only imports to avoid eager parsing.

Streamline static-wrapper representations: ClassWrapperInfo is now a Map<string, WrapperMethodInfo>, and related detection helpers updated and documented. Simplify subclass-wrapper/typechecker APIs: drop wrapperOwner and SourceFile parameters where unused, adjust function signatures (collectInheritedWrappers, resolveSubclassWrappers, resolveWrapperCodecCalls, extractSubclassMemberTypeNode) to operate with fewer arguments and return plain WrapperMethodInfo lists. Update file-pipeline to match reordered args.

Refactor plugin context creation: add buildContext helper, createPluginContext/createStandaloneContext now delegate to it; remove programPrepared flag and adjust prepareProgramForTsconfig invocation site. Update tests to reflect Map API changes and revised function signatures.

Overall this is an internal refactor to reduce duplication, avoid eager work for type-only imports, remove unused params, and clarify interfaces without changing behavior.
2026-05-26 21:24:37 +08:00
手瓜一十雪
1b07005d91 Unify protobuf helpers and tidy comments
Export and centralize small utility helpers and remove duplicate implementations: identityImportedTypeName was exported from utils, and isVarint64/isFixed64BigInt were added to types and imported into encoder/decoder. Minor import reorders and formatting cleanups across collector, monomorphizer, import-resolver, static-wrapper, subclass-override and file-pipeline. Comments and JSDoc were tightened for clarity; behavior remains the same but common logic is now deduplicated and easier to maintain.
2026-05-26 20:53:32 +08:00
手瓜一十雪
aaed36aa19 Remove verbose header and tidy release script
Strip the large one-shot release driver comment block at the top of tools/release.mjs and apply minor formatting cleanups (compact ok() logging line and adjust spacing for the `ahead` variable). No functional changes intended — just cleanup of comments and whitespace.
2026-05-26 18:29:32 +08:00
手瓜一十雪
c3a8a9b6b6 Revert "Add transform + program caching to plugin"
This reverts commit 868f4a5798.
2026-05-25 12:02:22 +08:00
手瓜一十雪
868f4a5798 Add transform + program caching to plugin
Introduce disk caching and startup program preparation for the Proton Vite plugin. Add ProtobufVitePluginOptions (root, tsconfig, cache) and configResolved hook to prebuild/prepare a TypeScript Program (program cache) and create a transform cache per-file (transform cache) keyed by source/config hashes and dependency mtimes. Track dependencyFiles in import-resolver so transform cache can validate mtimes. Update program-cache to support incremental tsbuildinfo and expose prepareProgramForTsconfig. Add cache read/write, hashing, path normalization and scope checks in the plugin; update tests and README to cover scope and cache behavior. Also add ts-morph dependency and update lockfile.
2026-05-25 11:52:46 +08:00
手瓜一十雪
93850ec11c Add text-edit utility and import resolution caches
Introduce a TextEdit type and applyTextEdits utility for safe, reverse-ordered string edits and refactor replacer to produce and consume edit lists (collectReplacementEdits) instead of performing manual slicing. Propagate ts.SourceFile through ParsedFileEntry/ImportedDefinitions and use cached extraction of imports/exports to avoid repeated AST traversal when resolving imports; analyzer now prefers an imported sourceFile when available. Wire text edits into the plugin pipeline (compose replacement + override edits) and remove the previous applyOverrideInsertions helper. Add a tsconfig lookup cache in program-cache to speed up upward tsconfig searches and invalidate it when the program cache is cleared. README updated to list the new files.
2026-05-25 11:42:03 +08:00
手瓜一十雪
40c51bcd02 Extract wrapper binding logic to wrapper-binding.ts
Move instantiateWrapperTypePattern and the WrapperBinding type into a new wrapper-binding.ts module and register it for reuse. Update analyzer.ts and import-resolver.ts to import the function/type from the new module and simplify call-site/type-root collection logic (use entrySourceFile and a cached callable name). Also update README: add ast-helpers.ts and wrapper-binding.ts to the file list and bump test count in the example.
2026-05-25 11:34:37 +08:00
手瓜一十雪
bed48bbe46 Skip subclass-wrapper pipeline when no subclasses
Avoid the expensive TypeChecker/program startup for files that don't declare extending classes by performing a cheap top-level scan first. index.ts now imports fileHasExtendingClass and a SubclassWrapperPipelineResult type and conditionally calls runSubclassWrapperPipeline only when a candidate is found, otherwise returning an empty result. Also updated comments to explain the optimization. subclass-wrapper.ts now imports isStaticMethod from ast-helpers.js (small import cleanup/usage update).
2026-05-25 11:30:41 +08:00
手瓜一十雪
34cc6be8df Add AST helpers, cache resolver, translate README
Add shared AST predicates in packages/proton/src/ast/ast-helpers.ts to centralize small structural checks used by the analyzer, callsite matcher, wrapper detector, and subclass resolver. Introduce a WeakMap cache in packages/proton/src/ast/utils.ts so createImportedTypeNameResolver is memoized per SourceFile to avoid repeated import-scans during transform() work. Update packages/proton/README.md with a Chinese translation and various clarifications/documentation tweaks.
2026-05-25 11:28:05 +08:00
手瓜一十雪
c55042aff4 Splice subclass override code into source
Group rendered subclass overrides per class and emit them as position-tagged insertions instead of a single trailing string. Add SubclassOverrideInsertion and applyOverrideInsertions to splice overrides immediately after each subclass declaration (sorted in reverse to keep offsets valid). Update runSubclassWrapperPipeline to collect per-subclass rendered parts and return insertions + extra root names, and update the plugin transform to apply these insertions before producing final code. Update tests to expect insertions and verify placement and runtime behavior. This ensures user code sees overrides right after the class body so subsequent top-level calls dispatch to the override rather than an inherited abstract implementation.
2026-05-25 11:20:44 +08:00
手瓜一十雪
3726913c1f Support per-subclass static wrappers; drop runtime map
Introduce per-subclass static-method wrapper support: detect wrapper-pattern methods in the AST, resolve concrete types via a TypeChecker, render per-subclass overrides, and append them into transformed output. Adds static-wrapper detector, subclass-override codegen, a typecheck file pipeline, a lazy ts.Program cache, and the subclass-wrapper resolver. Integrates the pipeline into the Vite plugin (including program cache invalidation on HMR) and threads extra root type names into registry selection so generated overrides get required codecs. Remove the runtime-map fallback feature and related types/logic (runtime-map module, dynamic runtime generation, and public API surface), simplifying runtime stubs and protobuf.d.ts. Update README and analyzer to document and support the new flow; add tests and fixtures for subclass-wrapper behavior.
2026-05-25 11:17:31 +08:00
DrSmoothl
5924346823 chore(release): v1.9.2 2026-05-24 18:01:50 +08:00
手瓜一十雪
456086599c Normalize imports, typings and formatting
Reorder and normalize imports, add missing type imports, and fix whitespace/formatting across multiple files. Notable updates: eslint.config.ts import ordering; core bridge APIs (group-album, misc, web) now import Json types; tests/highway pipeline import ordering and added type imports; protocol changes (element-builder, highway client/pipeline) reorganized imports and added proto type imports; many oidb service modules moved protobuf encode/decode imports for consistency; web group modules (album, essence, honor, notice, request-util) reordered imports, adjusted typings/indentation, and small whitespace fixes. These edits are stylistic and typing improvements and should not change runtime behavior.
2026-05-24 13:39:35 +08:00
手瓜一十雪
80ee12ecc2 Enforce no-explicit-any; allow in tests
Enable @typescript-eslint/no-explicit-any as an error in the ESLint config to tighten typing across the codebase, and add an override to disable this rule for test files. Also apply non-functional cleanup in packages/proton/src/runtime.ts: reorder/imports and adjust formatting/indentation and string alignment for readability — no behavioral changes.
2026-05-24 13:38:13 +08:00
手瓜一十雪
acc5084647 Refactor group-album and remove eslint ignore
Remove an unused Bridge import, the asBridge helper and a stale comment from group-album, and relocate the GroupAlbumMediaResult and GroupAlbumCommentResult interfaces to the end of the file. In the sqlite package, remove the inline eslint-disable-next-line for @typescript-eslint/no-explicit-any near the BetterSqlite3 constructor. These edits clean up dead/stale code and re-enable the lint rule; there are no behavioral changes.
2026-05-24 13:16:36 +08:00
手瓜一十雪
afbec8ed44 Cleanup imports and formatting in bridge
Reorder and tidy imports, re-export types, and apply minor formatting fixes across the bridge package. Changes include:

- Reordered imports and grouped related imports in hook-manager, hook-session, pipe-watcher, qq-hook-client, qq-port-probe and others.
- Moved several type re-exports (HookProcessBaseInfo, QqPortLoginInfo, HookProcessInfo/Status) in hook-manager and consolidated exports in package entry index.ts.
- Minor whitespace/style tweaks: constructor spacing, for-loop formatting, empty catch handlers, and small refactors that do not change runtime behavior.

These are non-functional housekeeping changes to improve consistency and readability.
2026-05-24 13:14:36 +08:00
手瓜一十雪
a49e507e15 Refactor Bridge APIs, slim Bridge and reorder imports
Move and standardize API implementations under bridge/apis, slim down the Bridge class (remove inline action implementations, caches and large comment blocks) and relocate related types/exports. Clean up and reorder imports across many bridge/api modules, normalize constructors, add logger imports where needed, and adjust WebUI routing/import ordering. These changes centralize API logic, reduce Bridge surface area, and tidy module boundaries and imports.
2026-05-24 13:13:23 +08:00
手瓜一十雪
a52a9724cb onebot: clean up comments, imports and whitespace
Remove extraneous comments, redundant explanatory notes and extra blank lines across onebot packages; reorder and normalize import lists in group-admin and group-album; remove unused comment blocks in event-converter. These are non-functional cleanup changes in packages/onebot/src/actions/extended.ts, packages/onebot/src/actions/group-admin.ts, packages/onebot/src/actions/group-album.ts and packages/onebot/src/event-converter/index.ts to improve readability and maintain consistent style.
2026-05-24 13:08:24 +08:00
手瓜一十雪
245405d294 Refactor comments and small type fixes in extended.ts
Add JsonObject import and use it for handleSendPacket param typing; replace deprecated hex.substr with hex.slice; convert and consolidate many English docstrings/comments into Chinese for clarity; remove some JSDoc noise and minor formatting tweaks; improve explanatory comments around streaming download, base64 size checks, safe path resolution and async file writes. These are primarily documentation and small type/cleanup changes with no functional behavior changes.
2026-05-24 12:54:21 +08:00
DrSmoothl
f53df5e313 refactor(packages): extract @snowluma/bridge (hook + QQ lifecycle)
Split the QQ NT client lifecycle / hook injection layer out of
@snowluma/core into its own self-contained package. The new bridge
package owns:
  - native hook addon loader (injector)
  - HookManager + per-PID HookSession orchestration
  - PipeWatcher for QQ process discovery
  - QqHookClient pipe protocol
  - qq-port-probe for early UIN sniffing

The hook layer used to type its main collaborator as
`BridgeManager` directly. To keep the new package free of any
dependency on @snowluma/core, the cross-package coupling is now
expressed via a 3-method `BridgeManagerSink` interface that lives
in the bridge package. BridgeManager (in core) satisfies the
interface structurally with no source changes; the top-level
app/webui still inject it the same way.

Pure file relocation otherwise: git mv preserves history at 100%
on every file, the only logic edit is the interface introduction
in hook-manager.ts and an updated `nativeSearchDirs()` offset
(one fewer `..` since hook now lives at packages/bridge/src
instead of packages/core/src/hook).
2026-05-23 23:40:57 +08:00
DrSmoothl
c16064d7e3 refactor(packages): rename @snowluma/bridge → @snowluma/protocol
The package previously named "bridge" houses the protocol-byte layer
(OIDB cmds, msg-push decoders, highway uploaders, element-builder,
event bus). The name "bridge" suggested transport/lifecycle, which it
isn't — that role lives in core/hook and core/bridge/manager. Rename
to match what's actually inside.

This is a pure rename: zero logic changes, all 73 import sites updated
mechanically and TS-verified. core/onebot dependencies key updated.
ESLint override path adjusted for the moved oidb-services directory.

Rename detection threshold: git log --find-renames=20% recommended
when following history across this commit — content-replacement
(@snowluma/bridge → @snowluma/protocol) dropped per-file similarity
below git's default 50% on import-heavy files.
2026-05-23 23:31:03 +08:00
DrSmoothl
98296fcec5 fix(send-like): update serialization to resolve user UID and adjust payload structure 2026-05-23 22:50:40 +08:00
DrSmoothl
d8c72c2ebc fix(events): surface verify-text on group_invite ("你们好" → comment)
User report:
  SnowLuma's group_invite event renders to OneBot with empty
  `comment`, so the bot's approval-prompt template shows nickname
  + uin + flag but loses the requester's verify message.

  NapCat's same flow shows the verify text:
    【进群申请】批准/驳回:
    昵称:KitaIkuyo
    QQ:1957003260
    flag:1779543612823906
    等级:7
    你们好               ← only NapCat shows this line

Root cause:
  The OIDB push (GroupRequestJoinNotice subType=84) only carries
  `(groupUin, targetUid)` and a few opaque numeric fields — no
  string for the verify text. NapCat doesn't use the push directly;
  they poll `nodeIKernelGroupService.getGroupNotifies` (= our OIDB
  0x10C0 pending-request queue at `FetchGroupRequests`) which
  returns each pending row with `postscript` (the verify text) and
  `seq` (server sequence id). Reference:
    dev/NapCatQQ/packages/napcat-onebot/index.ts:483-498
    (`flag = notify.seq`, `comment = notify.postscript`).

  Our pipeline didn't enrich. The decoder set `message: ''` and
  emitted, so OneBot's `comment` was empty.

Fix:
  - Extend `PacketPipelineDeps` with a `resolveGroupJoinRequest(
    groupId, uid, subType)` hook. Bridge.ts wires it to
    `fetchGroupRequests` and matches on `(groupId, uid)` —
    targetUid for `subType='add'`, invitorUid for
    `subType='invite'`.
  - `dispatchAfterStrangerResolve` now fires the profile + request
    lookups in PARALLEL via `Promise.allSettled` so a flake on one
    path doesn't kill the other. The request lookup's `comment`
    lands on `event.message`; OneBot converts that to `comment`.

Decisions:
  - Kept the existing `add:<groupId>:<uid>` flag format (consumer
    bots already parse it). Switching to NapCat's sequence-form
    flag would break callers and is a separate breaking change.
  - Both lookups fail-open: if either rejects, the event still
    emits with whatever info we did get, so the bot at least sees
    the request and can render the bare nickname.

Regression tests:
  - `populates event.message from the pending-request queue` — pins
    the user-reported "你们好" case end-to-end through the pipeline.
  - `runs lookups in parallel` — profile resolves, request fails;
    event still ships with the resolved uin and an empty message.
  - `invite subtype matches the request on invitorUid` — explicit
    contract for the invite-forwarded-to-admin case where the
    pending row's REQUESTER is `invitorUid`, not `targetUid`.

345 bridge tests pass (was 342 + 3 new); typecheck + lint clean.
2026-05-23 22:00:14 +08:00
DrSmoothl
8631453940 fix(events): self-heal group_invite cache pollution from pre-fix builds
User report: after [a4909ec], log STILL shows
  群邀请 950929451 -> [bot group(950929451)]
  get_stranger_info params=user_id=950929451 → 未知昵称

But NapCat and a sibling SnowLuma bot in the same group BOTH decoded
the same push as `QQ:1957003260 nickname:KitaIkuyo`. So the wire is
correct — our bot is just looking it up wrong.

Root cause: **legacy cache pollution**. The pre-fix decoder fallback
stored `<requester_uid> → <groupUin>` in the identity DB whenever
`resolveUidToUin` missed (because the fallback `ctx.fromUin` on a
group-scoped push IS the group's own uin). After upgrading to
[a4909ec], `decodeGroupJoinRequest` calls `resolveUidToUin` which
hits the polluted in-memory map (re-populated from SQLite at boot)
and returns the groupUin instead of 0. The new `needsStrangerResolve`
guard only fired on `fromUin <= 0` — so the polluted value flowed
straight through and re-emitted the bug.

Two-part heal:

  1. `needsStrangerResolve` now ALSO fires when `fromUin === groupId`
     — the pollution signature. A real requester's uin can never
     equal the group's own uin, so this is a safe override that
     forces the async UID-form FetchUserProfile lookup, which then
     `rememberUidUin`s the correct mapping on success (eviction is
     already wired in identity-service.ts:468-471).

  2. `rememberEventIdentity` for group_invite now passes `uin: 0`
     when `event.fromUin === event.groupId`, so future writes don't
     re-pollute the cache (`rememberUidUin` short-circuits on
     normalized uin ≤ 0).

Cache self-heals on first event after upgrade — no manual DB nuke
needed.

Regression test pins the legacy-pollution path: feeds an event
where `fromUin === groupId` (matching the user's log), verifies the
resolver fires and patches fromUin to the correct value.
2026-05-23 18:40:01 +08:00
DrSmoothl
a4909ec9e5 fix(events): resolve stranger nickname on group_invite (no more 未知昵称)
User report: when a stranger requests to join a group, the bot
receives `user_id=<groupId>` (instead of the requester's actual
uin) and `get_stranger_info` returns no nickname → bot displays
"未知昵称".

Two layered bugs:

  1. **Decoder fallback was wrong.** `decodeGroupJoinRequest` /
     `decodeGroupInvitation` / `decodeGroupInvite` all passed
     `ctx.fromUin` as the fallback uin when `resolveUidToUin` missed
     the local cache. But for group-scoped pushes `ctx.fromUin` is
     the GROUP's own uin — falling back to it produces the bogus
     `fromUin === groupId` collision the user saw. Fix: pass 0.

  2. **No async resolve for stranger UIDs.** The push only carries
     the requester's UID string. When the UID isn't in our cache
     (true for any stranger who isn't yet a group member), we have
     no UIN — and our UIN-form `FetchUserProfile` can't help. The
     pipeline never tried to look up the stranger by UID, so the
     event went out with `fromUin=0` (or, with the old fallback,
     the group's own uin).

Cross-checked against Lagrange.Core's flow:

  dev/Lagrange.Core/.../MessagingLogic.cs:215-224
    case GroupSysRequestJoinEvent join:
        var fetchUidEvent = FetchUserInfoEvent.Create(join.TargetUid);
        var results = await Collection.Business.SendEvent(fetchUidEvent);
        uint targetUin = results.Count == 0 ? 0
            : ((FetchUserInfoEvent)results[0]).UserInfo.Uin;
        var joinArgs = new GroupJoinRequestEvent(join.GroupUin, targetUin);

  dev/Lagrange.Core/.../OidbSvcTrpcTcp0xFE1_2.cs:9-26
    — UID-form variant of the same OIDB 0xFE1_2: field 1 is `uid:
      string`, envelope `reserved=0` (no uinForm flag).

  dev/Lagrange.Core/.../FetchUserInfoService.cs:66-78
    — picks UID vs UIN form based on which input is set.

Changes:

  - `proto-defs/oidb-actions/base.ts`: add `OidbUserInfoByUidRequest`
    (same shape as the UIN variant but field 1 is `uid: string`).
  - `bridge/oidb-services/contacts/fetch-user-profile-by-uid.ts`:
    new namespace at 0xFE1_2 with UID-form encoding, no `uinForm`.
  - `bridge/msg-push/decoders/group-join-request.ts`: 3 decoders'
    `resolveUidToUin` fallbacks change `ctx.fromUin` → 0.
  - `bridge/packet-pipeline.ts`: new `resolveStrangerProfile(uid)`
    dep + `needsStrangerResolve` check + async dispatch that fires
    the lookup before emitting the event. Fail open if the lookup
    rejects (event still ships with `fromUin=0` so the OneBot bot
    can fall back to the uid in the flag).
  - `core/bridge/apis/contacts.ts`: `fetchUserProfileByUid(uid)`
    facade method.
  - `core/bridge/bridge.ts`: wire `resolveStrangerProfile` into the
    pipeline deps so it routes through the new namespace.

Tests:
  - UID-form namespace: declares the right cmd/subcmd, packages uid
    as field 1, decodes nickname + uin so the pipeline patch works.
  - Pipeline stranger resolve: patches event.fromUin from the
    resolver response; fails open on null / throw; skips the wire
    call when fromUin is already populated or fromUid is empty.

All 655 tests pass (was 645 + 10 new); typecheck + lint clean.
2026-05-23 17:15:59 +08:00
DrSmoothl
4755a91cb3 fix(image): use Chinese summary defaults to match QQ ecosystem
Mobile QQ, Lagrange.Core, and NapCat all use the literal Chinese
bubble-preview strings `[图片]` / `[动画表情]`. SnowLuma was emitting
English `[image]` / `[sticker]` as fallback, so QQ clients showed
"[image]" in chat-list previews instead of the expected Chinese.

Cross-checked against:
  dev/NapCatQQ/.../packet/message/element.ts:367-371
  dev/Lagrange.Core/.../Message/Entity/ImageEntity.cs:186-192

Both branch the same way: subType=1 → `[动画表情]`, else → `[图片]`.

Changes:
  - `bridge/highway/image-upload.ts`: both code paths (fingerprint +
    load-from-source) now emit the Chinese defaults. Subtype branch
    flipped to `subType === 1 ? '[动画表情]' : '[图片]'` to match the
    upstream convention (our old check was `subType === 0` →
    `[image]`, which would label any non-zero subType — not just
    stickers — as `[sticker]`).
  - `bridge/msg-push/rich-body-decoder.ts`: all three decode paths
    (NotOnlineImage / CustomFace / commonElem image) now substitute
    the Chinese default when the server omits `textSummary`. Empty-
    string is also treated as missing (matches NapCat's `=== ''`).
  - Tests updated to assert the Chinese defaults; new test pins
    that a caller-supplied summary still overrides verdef.

The OneBot caller's `summary` field on the MessageElement still
wins when set, so downstream clients passing custom bubble text
(e.g. for accessibility) keep working.
2026-05-23 15:05:28 +08:00
DrSmoothl
c8f259ef4a test(highway): pin multi-image sequential semantics + richer 921 diag
User reported `highway upload error_code=921` when sending two images
in one OneBot message — image 1 fast-uploaded (server already had the
md5), image 2 (58 bytes) triggered the actual PUT and failed.

Verified the claim from code inspection vs NapCatQQ + Lagrange.Core:

  - dev/NapCatQQ/.../highwayContext.ts:62-94 (checkAvailable + prepareUpload)
  - dev/NapCatQQ/.../highwayHttpUploader.ts:8-43 (HTTP block upload)
  - dev/NapCatQQ/.../highwayContext.ts:219-254 (uploadGroupImage)
  - dev/Lagrange.Core/.../HighwayContext.cs:98-180 (UploadSrcByStreamAsync)

Findings:

  1. The pipeline runs `runNtv2Upload` sequentially per image (await
     inside `buildSendElems`); there's no concurrency or shared state.
  2. Each call gets its own OIDB request, its own lazy session fetch,
     its own buildHighwayExtend output. No aliasing.
  3. The 921 comes from the highway PUT's response head (errorCode),
     not from anything client-emitted being malformed.

Verdict: not reproducible from code inspection — almost certainly
server-side (most likely Tencent rejecting the 58-byte image as a
malformed payload; 58B is too small to even be a valid 1×1 PNG).

Hardening:

  - Three regression tests pin the sequential two-image semantics so
    a future state-leak bug fails loudly:
      - extend bytes for image 2 must come from image 2's response,
        not image 1's,
      - each runNtv2Upload fetches its own non-null session,
      - each OIDB request carries its own fileInfo + a unique
        clientRandomId.
  - The `error_code=N` message now carries segRetCode, cmdId, chunk
    size, offset, and the first 8 bytes of the file md5 — without
    these the user couldn't tell apart "image rejected" vs "session
    expired" vs "rate-limited" on future reports.

If the user reports the same 921 again, the new diagnostic message
should show enough server-side context to triage server-vs-client.
2026-05-23 13:06:09 +08:00
DrSmoothl
cd9403f27a fix(forward): align resid+uniseq for nested forwards
Multi-layer 合并转发 was uploading correctly but the outer's
LongMsgResult piggyback was *unreachable* by the receiver because
two things were missing:

  1. The forward preview element was emitted as the old XML
     `richMsg serviceID=35 m_resid=…` shape, which carries the
     inner resId but has NO uniseq field.
  2. The piggyback `actionCommand: <uuid>` slot generated a fresh
     UUID that was never reflected into the preview either.

Result: QQ-NT receivers saw the inner preview's resid, scanned the
outer's actions[] for a matching uniseq, found none, and either
fell back to a fresh server fetch per layer or dropped the layer
entirely.

Cross-checked against:
  - dev/Lagrange.Core/Lagrange.Core/Message/Entity/MultiMsgEntity.cs:43-115
  - dev/NapCatQQ/packages/napcat-core/helper/forward-msg-builder.ts:52-122
  - dev/NapCatQQ/packages/napcat-onebot/action/msg/SendMsg.ts:208-347

Both upstream impls use the modern `com.tencent.multimsg` LightApp
JSON whose `meta.detail.uniseq` is the round-trip key that links
the inner preview to the matching `actionCommand` in the outer's
LongMsgResult — no separate fetch needed.

Changes:
  - `element-builder.makeForwardElem` now emits a deflated
    `com.tencent.multimsg` LightApp JSON (LightAppElem, field 51)
    instead of the XML RichMsg (field 12). `forwardUuid` on the
    MessageElement is baked into `meta.detail.uniseq` and
    `extra.filename`. Auto-generates a UUID when absent.
  - `MessageElement.forwardUuid?: string` added for the round-trip.
  - `forward.uploadRecursive` threads `inner.uuid` into the outer's
    preview element AND uses the same uuid for the outer's
    piggyback actionCommand — closing the receiver-side lookup loop.
  - `forward.fetch` now walks ALL actions (not just `MultiMsg`),
    indexes piggybacks by uuid, and pre-populates the cache for
    each inner resId discovered in the outer's preview bubbles.
    Follow-up `fetch(innerResId)` hits the cache instead of the wire.
  - `rich-body-decoder` parses LightApp JSON; when `app ===
     com.tencent.multimsg`, emits `{type: 'forward', resId,
     forwardUuid}` so the OneBot layer can walk in. Legacy XML
     serviceID=35 path stays as a fallback for mobile QQ senders.

Wire-byte tests cover:
  - send: lightApp.data is 0x01-prefixed deflated JSON with the
    right meta + extra fields
  - send/nested: outer LongMsgResult carries `MultiMsg` AND a
    uuid-keyed piggyback; the piggyback uuid matches the
    preview's `meta.detail.uniseq` baked into the same outer
    msgBody
  - send/3-deep: outermost action[] has 1 + 2 entries (own
    MultiMsg + 2 piggybacks hoisted from deeper levels)
  - recv: lightApp `com.tencent.multimsg` → forward element with
    both resId and forwardUuid; non-multimsg LightApp falls
    through to {type:'json'}; legacy XML path still emits
    {type:'forward'}.

641 tests pass (was 628 + 13 new); typecheck clean; lint clean.
2026-05-23 12:45:26 +08:00
DrSmoothl
5724f490b4 refactor(oidb): thread ctx into serialize/deserialize for self-contained namespaces
The first pass at namespace-per-cmd left a smell: namespaces that
needed identity/uid resolution had to declare `Deps` AND then rewrite
their own spec inside `invoke` via a closure-over-resolved-value:

  // before
  export const serialize = (p: Params, targetUid: string) => ({...});
  export const invoke = async (deps, params) => {
    const targetUid = await deps.resolveUserUid(params.userId);
    return invokeOidb(deps, {
      ...Self,
      serialize: p => serialize(p, targetUid),  // ← escape hatch
    }, params);
  };

Reading "what does this cmd do on the wire?" required reading the
namespace AND the closure rewrite — the namespace wasn't really
self-contained, just a forwarder of two pure functions.

Fix: thread `ctx` (the namespace's full capability surface) into
`serialize` and `deserialize` directly. `serialize` may now return
`Promise<TReq>` so identity / uid lookups happen in place:

  // after
  export const serialize = async (ctx: Deps, p: Params) => ({
    groupUin: p.groupId, type: 1,
    body: {
      targetUid: await ctx.resolveUserUid(p.userId, p.groupId),
      duration: p.duration,
    },
  });
  export const invoke = (deps, params) => invokeOidb(deps, Self, params);

OidbCallSpec gains a `TCtx extends OidbSender` generic; invokeOidb's
first arg becomes `ctx: TCtx` (the sender capability is just a slice
of ctx now). buildOidbRequest / parseOidbResponse follow the same
shape. Async serialize is awaited inside invokeOidb.

17 namespaces had closure rewrites; all 17 collapse to plain
`invokeOidb(deps, Self, params)` invokes. Only one closure remains —
`fetch-user-profile` binds `params.uin` into deserialize as a server-
echo fallback; kept as a documented exception (the rare case where
deserialize wants request context, not ctx).

Wire bytes preserved across all migrations. 326 bridge tests + 302
core tests pass; lint clean.
2026-05-23 12:27:26 +08:00
DrSmoothl
99772851a7 chore(deps): add vitest coverage packages to devDependencies 2026-05-23 00:43:27 +08:00
DrSmoothl
9b4ff9c5e9 chore(lint): exempt oidb-services from no-namespace + clean stale directives
The namespace-per-cmd OIDB service layer was tripping
`@typescript-eslint/no-namespace` across 59 files; namespace IS
the OidbCallSpec by design (structural typing, one file per
(cmd, subcmd)) so disable the rule for that subtree only. Drop
four stale `eslint-disable-next-line @typescript-eslint/no-empty-
object-type` comments that aren't needed anymore (the empty
`Params {}` shape no longer triggers the rule), and fix an indent
nit in the get-unidirectional-friend-list test.

`npx eslint packages` now reports 0 errors. The 5 remaining
warnings are unused-vars / unused-eslint-disable in unrelated
pre-existing files.
2026-05-23 00:30:23 +08:00
DrSmoothl
521808a6eb refactor(oidb): migrate group-file.ts OIDB cmds to namespaces
Splits the 16 OIDB cmds from GroupFileApi into self-contained
namespaces under @snowluma/bridge/oidb-services/group-file/. Adds
@snowluma/bridge/oidb-services/shared with `toInt` / `ensureRetCodeZero`
helpers so namespaces can validate sub-responses without an
@snowluma/core dependency.

Boundaries:
  - Single-OIDB methods (publish / getCount / list-page / *url /
    delete / move / *folder) become one-line forwarders.
  - 3-stage methods (`upload` / `uploadPrivate`) keep their
    orchestration on the facade — OIDB preflight goes through the
    new namespace, but highway PUT + publish/sendC2cFile + upload-
    cache bookkeeping stay where they are.
  - `list` keeps its pagination loop on the facade; the page-fetch
    namespace is one call.
  - The NTV2-rich-media URL fetchers (group/private × ptt/video)
    share a deserialize helper (`parseNtv2DownloadUrl`) so all four
    namespaces only differ in their scene block.

Wire-byte equivalence preserved. The 0x6D6 family shares one
OidbGroupFileReq envelope; each namespace populates a different
slot (file / download / delete / move) and proton monomorphizes
per call site as before.
2026-05-23 00:22:59 +08:00
DrSmoothl
8d22868777 refactor(oidb): migrate group-admin.ts OIDB cmds to namespaces
Splits the 14 OIDB cmds from GroupAdminApi into self-contained
namespaces under @snowluma/bridge/oidb-services/group-admin/. The
facade becomes one-line forwarders; per-cmd capability is narrowed
to OidbSender (+ resolveUserUid / identity where the cmd actually
needs it).

Notes:
  - 0x89A_0 hosts MuteAll, SetAddOption, SetSearch, SetGroupName —
    same (cmd, subcmd) tuple, four different proto bodies; each gets
    its own namespace so proton can monomorphize independently.
  - 0x8A0_1 splits KickMember (single) and KickMembers (batch) for
    the same reason.
  - SetAddRequest carries uinForm=true and dynamic subCommand
    (filtered ? 2 : 1) on the same namespace.
  - GetAtAllRemain needs the bot's own uin → declares
    Pick<BridgeContext, 'identity'> in its Deps.

Wire-byte equivalence preserved; corner case for getAtAllRemain
empty-envelope path now returns {false, 0, 0} instead of throwing —
the new infrastructure normalises empty bodies and the OneBot action
ergonomics are unchanged.
2026-05-23 00:06:40 +08:00
DrSmoothl
014b87c7ce refactor(oidb): migrate contacts.ts OIDB cmds to namespaces
6 OIDB cmds moved; pagination + per-group cache + inflight
coalescing stay on the facade because they need cross-call state.

  - FetchFriendListPage       (0xFD4_1) — facade drives the cursor loop
  - FetchGroupList            (0xFE5_2) — uinForm; verbatim config blob
  - FetchGroupMemberListPage  (0xFE7_3) — facade drives the token loop +
                                          owns the TTL cache + inflight
                                          coalescing that keeps busy
                                          OneBot clients from tripping
                                          Tencent risk-control
  - FetchUserProfile          (0xFE1_2) — uinForm; full property-key
                                          catalogue cross-checked against
                                          LagrangeV2 FetchStrangerService.cs
  - FetchGroupRequests        (0x10C0_1/_2) — dynamic subcmd via filtered flag
  - FetchDownloadRkeys        (0x9067_202) — uinForm; respHead.retCode
                                             check moved into deserialize

35 new namespace-level tests covering serialize / deserialize edge
cases (property decoding, sex enum mapping, avatar URL suffix,
empty body handling, pagination cursor behaviour).

Verification:
  - typecheck green
  - @snowluma/bridge: 30 files / 233 tests
  - @snowluma/core: 302 tests
Wire bytes unchanged.
2026-05-22 23:51:33 +08:00
DrSmoothl
80afa31f5c refactor(oidb): migrate extras.ts OIDB cmds to namespaces
5 logical OIDB cmds → 4 namespace files (group todo's 3 sub-cmds
collapse into one namespace with a dynamic resolver):

  - GroupTodo          (0xF90_1/2/3) — set/complete/cancel via the
                                       new `action` discriminator
  - GetStrangerStatus  (0xFE1_2)     — uinForm=true; preserves the
                                       (status*10, ext_status) decode
                                       quirk verbatim
  - FetchAiVoiceList   (0x929D_0)
  - FetchAiVoice       (0x929B_0)    — single poll; retry loop
                                       stays on the facade so callers
                                       can plug their own back-off

Facade keeps the 6 public methods (setGroupTodo / completeGroupTodo /
cancelGroupTodo / getStrangerStatus / fetchAiVoiceList / fetchAiVoice)
as one-line forwarders; only `getStrangerStatus` wraps in try/catch
to preserve its "return null on transport failure" contract, and
`fetchAiVoice` keeps the polling loop.

30 new namespace-level tests; extras.test.ts moved onto the
sendRawPacket assertion model.

Verification:
  - typecheck green
  - @snowluma/bridge: 24 files / 195 tests
  - @snowluma/core: 302 tests
Wire bytes unchanged.
2026-05-22 23:45:13 +08:00
DrSmoothl
8356121518 refactor(oidb): migrate web.ts OIDB cmds to namespaces
2 OIDB cmds moved (the only OIDB calls in this file — the rest are
HTTP cookie / qun.qq.com / qzone web requests):

  - ForceFetchClientKey (0x102A_1) — used by ptlogin2 jump flow to
                                     swap clientKey → cookie jar
  - GetPskey            (0x102A_0) — p_skey fallback when ptlogin2
                                     omits it

The private `forceFetchClientKeyInner` / `getPSkey` helpers in
WebApi are now one-line forwarders into the namespaces. Facade
methods (`getCookies`, `getCsrfToken`, `getCredentials`, etc.) and
all HTTP-only cmds untouched.

12 new namespace-level tests covering deserialize edge cases
(empty server response, missing fields, dropped invalid items)
and e2e wire routing.

Verification:
  - typecheck green
  - @snowluma/bridge: 20 files / 165 tests
  - @snowluma/core: 302 tests
Wire bytes unchanged.
2026-05-22 23:40:17 +08:00
DrSmoothl
58e8081420 refactor(oidb): migrate misc.ts OIDB cmds to namespaces
3 OIDB cmds migrated; the 1 non-OIDB cmd (getMiniAppArk via
LightAppSvc) stays on the facade unchanged.

  - TranslateEnToZh           (0x990_2)
  - ClickInlineKeyboardButton (0x112E_1)
  - SendGroupSign             (0xEB7_1) — preserves historic UPPERCASE
                                          EB7 wire name via the new
                                          `wireName` override (the only
                                          cmd in the codebase with this
                                          quirk; every other cmd uses
                                          the default lowercase).

Tests:
  - misc.test.ts moved to bridge.sendRawPacket assertion model
  - 18 new namespace-level tests covering serialize, deserialize edge
    cases, magic constants, BigInt widening, and the EB7 case quirk

Verification:
  - typecheck green
  - @snowluma/bridge: 18 files / 153 tests
  - @snowluma/core: 302 tests
Wire bytes unchanged.
2026-05-22 23:37:41 +08:00
DrSmoothl
f78431242c refactor(oidb): migrate friend.ts to namespaces
3 OIDB cmds moved to self-contained namespaces:
  - HandleFriendRequest (0xB5D_44) — digit-only flag still
                                     auto-resolves via resolveUserUid
  - DeleteFriend        (0x126B_0) — verbatim magic constants in the
                                     nested field2 sub-message
                                     (130/109/8/8/50 — server-side
                                     discriminator, MUST stay byte-
                                     equal to NTQQ wire)
  - SetFriendRemark     (0xB6E_2)

Cache invalidation (fetchFriendList after deletion) stays in the
facade — that side-effect needs `ctx.apis.contacts`, which namespaces
deliberately can't reach.

Tests migrated to assert against bridge.sendRawPacket. 15 new
namespace-level tests covering each invoke branch + serialize edge
cases.

Verification:
  - typecheck green
  - @snowluma/bridge: 15 files / 133 tests
  - friend.test.ts: 5/5
Wire bytes unchanged.
2026-05-22 23:33:22 +08:00
DrSmoothl
a38f7ea26e refactor(oidb): migrate profile.ts OIDB cmds to namespaces
5 of profile.ts's methods were thin OIDB wrappers — migrated to the
new namespace pattern. The 5 non-OIDB methods (setOnlineStatus /
setDiyOnlineStatus / setAvatar / setGroupAvatar / fetchCustomFace)
stay on the facade unchanged — they hit `trpc.qq_new_tech.*`,
Highway, or `Faceroam.OpReq` directly and aren't in scope for the
OIDB-namespace refactor.

New namespaces (each with focused Pick<BridgeContext, …> deps):
  - SetProfile               (0x112A_2)  — needs identity for uin
  - SetSelfLongNick          (0x112A_2)  — same cmd different proto, ditto
  - SetInputStatus           (0xCD4_1)   — needs resolveUserUid
  - GetLike                  (0x7ED_12)  — needs identity + resolveUserUid
  - GetUnidirectionalFriendList (0xE17_0) — needs identity; non-standard
                                            wire name handled via the new
                                            wireName override on OidbCallSpec

Infrastructure tweak:
  - OidbCallSpec gains an optional `wireName(cmd, sub) → string`. Most
    cmds use the default `OidbSvcTrpcTcp.0xNNNN_N` scheme; 0xe17_0
    routes through `MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0`.

Test mock updates:
  - profile.test.ts moves the migrated cmds onto bridge.sendRawPacket
    mock (the new path bypasses the bridge-oidb runOidb mock). Non-OIDB
    cmds (setOnlineStatus, setAvatar, etc.) keep their existing mocks.
  - 36 new namespace-level tests in @snowluma/bridge covering serialize
    branches, deserialize edge cases, deps resolution, and e2e wire
    routing.

Verification:
  - pnpm -r typecheck: green
  - @snowluma/bridge: 12 files / 118 tests
  - @snowluma/core: 33 files / 302 tests
Wire shape unchanged across migrated cmds — same bytes produced.
2026-05-22 23:29:55 +08:00
DrSmoothl
ff2b902cbd refactor(oidb): migrate interaction.ts remaining 3 cmds to namespaces
Completes the InteractionApi facade — every method is now a one-line
forwarder. New namespaces:
  - SendPoke   (0xED3_1)  — group + friend variants discriminated by
                            which of groupUin/friendUin is set
  - SendLike   (0x7E5_104) — thumbs-up to a target user
  - SetEssence (0xEAC_1/_2) — set/unset essence message, dynamic subcmd

Facade methods reduced to thin forwarders, mirror-fixed comment block
removed (the namespaces now own the wire-shape commentary).

Tests: 28 new in @snowluma/bridge covering each namespace's serialize
edge cases + dynamic subcmd resolution + e2e wire name + envelope body
shape. Cleaned the legacy `vi.mock('bridge-oidb')` setup out of
interaction.test.ts — the post-migration path doesn't route through
the mocked symbols anymore.

Wire behavior unchanged: every cmd produces the same bytes as before,
verified by encode round-trip in the unit tests.
2026-05-22 23:22:26 +08:00
DrSmoothl
0238bcb280 refactor(oidb): namespace-per-cmd service layer — vertical slice (3 cmds)
Introduce a new way to organise OIDB cmd implementations:

  - one TypeScript namespace per (cmd, subcmd) tuple
  - the namespace's exported members ARE the OidbCallSpec (structural
    typing — no `implements` clause)
  - a single invokeOidb() template method drives every call:
    envelope build → encode → send → errorCode check → decode →
    deserialize transformation
  - each namespace declares its own minimal `Deps` capability via
    Pick / intersection on BridgeContext (Interface Segregation):
    most cmds need only OidbSender (the `sendRawPacket` method)

The facade Api classes (InteractionApi etc.) stay for now, with the
migrated methods reduced to one-line forwarders that hand off to the
namespace. Callers still write `bridge.apis.X.Y(...)`; the OIDB
wire-encoding work just moved to a self-contained file per cmd.

Vertical slice scope: 3 cmds (the reaction line)
  - SetReaction              (0x9082_1 / _2; dynamic subcmd)
  - FetchReactionSummary     (0x9084_1)
  - GetEmojiLikes            (0x9083_1; legacy stub)

Infrastructure:
  - new packages/bridge/src/oidb-service.ts:
      OidbSender (sendRawPacket-only capability),
      OidbCallSpec<TReq, TResp, TParams, TResult>,
      invokeOidb(), buildOidbRequest(), parseOidbResponse(), OidbError
  - runOidb() refactored to accept OidbSender instead of BridgeContext
    (structurally compatible — no caller changes anywhere)
  - new OidbEmpty placeholder type in proto-defs/oidb.ts for cmds whose
    response carries no body (proton needs a real message interface,
    not `void` / `never`)
  - empty-body responses substituted with {} in invokeOidb so
    deserialize always receives a defined object

Tests (65 in @snowluma/bridge, all green):
  - oidb-service.test.ts (20): every helper branch — static + dynamic
    subcmd, uinForm flag, error code propagation as OidbError, empty
    body substitution, sender failure modes (success=false /
    gotResponse=false / both with and without errorMessage),
    timeoutMs propagation
  - set-reaction.test.ts: const declarations, dynamic subcmd both
    ways, type=1/2 boundary on code length, e2e envelope inspection
  - fetch-reaction-summary.test.ts: BigInt serialization, catalog-tail
    filtering, default emojiId/Type/lastReactionTime
  - get-emoji-likes.test.ts: BigInt serialization, default count /
    emojiType, base64 cookie round-trip, uin=0 filtering, isLast
    computation, e2e

Existing interaction.test.ts moved off the now-bypassed runOidb mock
onto sendRawPacket mock (the new invokeOidb path routes there).

Workspace-wide typecheck: green. Workspace test totals:
  proton  99/99, bridge 65/65, core 302/302, onebot 257/257
  (1 pre-existing onebot suite failure, network-manager native addon
  load — unrelated to this change.)
2026-05-22 23:15:20 +08:00
DrSmoothl
c3675aef7c feat(emoji-like): back fetch_emoji_like / get_emoji_likes with a local cache
Two rounds of production wire-level probing established that the OIDB
SSO path cannot surface the reactor user list for an emoji:

  - 0x9083_1                  → 4-byte ack `18 01 20 01` (no list)
  - 0x9084_1                  → per-emoji summary (count + timestamp,
                                still no user IDs)
  - 0x9082_3..5, 0x9083_0/2/3, 0x9084_2..5, 0x9085_1/2, 0x9087_1
                              → "no privilege" — the cmds exist but
                                aren't in NTQQ's client capability
                                bitmap, so the server blocks anything
                                not registered at login. NTQQ itself
                                serves getMsgEmojiLikesList from a
                                wrapper-internal cache, not SSO.

Mirror that wrapper-cache approach on the OneBot side. SnowLuma
already receives GroupMsgEmojiLikeEvent push events for every
reaction add/remove (with operator uin + uid + emoji + msgSeq); we
just weren't persisting them. Now we do.

Changes:

* proto-defs: add Oidb0x9084 Req/Resp schema for the summary call.
  RespEntry's lastReactionTime/count are optional because the
  "available reactions catalog" tail entries omit both — only the
  "used" subset carries metadata.

* core InteractionApi: revert the 9-candidate probe loop, restore a
  single 0x9083_1 call as a legacy stub (returns empty list, with a
  debug-level hex dump on empty responses), and add
  fetchReactionSummary() that calls 0x9084_1 and yields the per-emoji
  summary (count + last-reaction timestamp).

* onebot ReactionStore: new SQLite-backed cache, schema
  reactions(group_id, msg_seq, emoji_id, emoji_type, operator_uin,
  operator_uid, set_at), PK on (group_id, msg_seq, emoji_id,
  operator_uin). Mirrors MessageStore design — prepared statements at
  construction, WAL journal.

* onebot event-pipeline: subscribe group_msg_emoji_like, call
  reactionStore.recordAdd / recordRemove before convertAndDispatch so
  a fetch_emoji_like racing with the push still sees the new row.

* onebot instance / instance-context: own the ReactionStore, expose
  it on OneBotInstanceContext, close it on dispose. New
  fetchEmojiLikeUsers helper on ApiActionContext combines local-cache
  reads with a 0x9084_1 cross-check so callers can detect cache gaps
  (events missed before bot boot, etc).

* onebot actions: get_emoji_likes and fetch_emoji_like now read from
  the cache. fetch_emoji_like's NapCat-style cookie becomes a numeric
  offset for cache pagination (no real cursor needed against local
  SQLite).

* tests: 7 new ReactionStore unit tests (CRUD + pagination +
  cross-key isolation + summarizeMessage). Existing event-pipeline
  test harness picks up a no-op ReactionStore stub.
2026-05-22 22:08:45 +08:00
DrSmoothl
65636953e7 chore(interaction): round-2 cmd probe — focus on 0x9084 family
Round-1 wire dump revealed:
  - 0x9083_1 returns a 4-byte ack (`18 01 20 01`), no user data
  - 0x9082_3/_4, 0x9083_0/_2/_3 all return "no privilege" (server-side
    deny linked to iwiki.woa.com permission docs)
  - 0x9084_1 returns 932 bytes — a real reaction *summary* on the
    message: first entry carries (timestamp, count, type, emoji_id)
    for the used emoji ("76" with count=3 in our test), followed by
    a 28-entry catalog of available reaction emojis. NOT a user list,
    but proves 0x9084 family has live handlers.

The "fetch users who reacted with emoji X" sibling is almost
certainly another subcmd of 0x9084. Probe the immediate neighborhood:

  0x9084_2..5   first-choice candidates (sibling subcmds)
  0x9085_1..2   exploratory adjacent cmd
  0x9086_1, 0x9087_1  wider probe
  0x9084_1      kept at end so we still capture the summary baseline
2026-05-22 21:38:13 +08:00
DrSmoothl
7e3e833f84 chore(interaction): probe 7 OIDB cmd candidates per fetch_emoji_like call
Replace the env-driven probe with an unconditional round-robin across
the candidate list every fetch_emoji_like invocation:

  0x9083_1  baseline (returns 4-byte ack, known not to be fetch)
  0x9082_3  sibling of set/unset reaction
  0x9082_4
  0x9083_0
  0x9083_2
  0x9083_3
  0x9084_1  exploratory

For each candidate the cmd, response length, parsed user count,
request hex, and response hex are dumped at debug level. The first
candidate that surfaces users wins and is returned; failures inside
runOidb (server-side error code, no handler) are caught + continued
so a bad cmd in the middle doesn't tank the whole probe.

fetch_emoji_like is user-triggered ("view who reacted"), so the
extra SSO traffic on each call is acceptable for a debug build —
we only need one production hit to identify the real cmd.
2026-05-22 21:13:37 +08:00
DrSmoothl
a24272b25a chore(interaction): env-driven cmd/subcmd override for fetch_emoji_like probing
Wire dump from production confirmed 0x9083_1 is a real server endpoint
(routed, errorCode=0, trace string echoes "OidbSvcTrpcTcp.0x9083_1")
but its reply is always a 4-byte minimal ack `18 01 20 01` regardless
of message / emoji / whether the caller just set a reaction — so the
semantics of 0x9083_1 are not "fetch emoji-like users". The real cmd
must be a sibling (0x9082_3, 0x9082_4, 0x9083_2, 0x9083_3, …) but we
don't yet know which.

Rather than rebuild for each candidate, accept an env override
`SNOWLUMA_EMOJI_FETCH_CMD=0x9082_3`. Format is `0xNNNN_N`; a malformed
value warns and falls back to the historic 0x9083_1. Wire name is
recomputed from the parsed (cmd, subcmd) so the trpc routing matches
the OIDB envelope cmd field.

Also unconditionally dump req/resp hex at debug level while we're
probing — once we land on a working tuple the dump can be tightened
back to "only on empty users". The pre-existing log line is widened
to include the wire name and the result count so deployment can scan
multiple cmd values from a single log stream.
2026-05-22 21:10:39 +08:00
DrSmoothl
2638d13d11 feat(profile): surface QQ level from OIDB 0xFE1_2 number-property 105
`fetchUserProfile` already requested key 105 in the keys[] array but
the decode pass never read it, so callers got nothing. NapCat exposes
the same value as `qq_level` on `get_stranger_info`; users coming from
NapCat noticed the field was missing on the SnowLuma side.

Cross-checked against LagrangeV2 Internal/Services/System/
FetchStrangerService.cs which explicitly labels key 105 = Level and
uses `numbers[105]` directly.

Changes:
- UserProfileInfo: add `level: number`.
- fetchUserProfile decode: `info.level = numMap.get(105) ?? 0`.
- getStrangerInfo: emit both `qq_level` (NapCat-compat) and `level`.
- Test/manager call sites updated for the new required field.
2026-05-22 19:02:05 +08:00
DrSmoothl
ce78a3bbdf fix(oidb): update sequence type in Oidb0x9083Req to uint_64 for compatibility 2026-05-22 08:09:29 +08:00
DrSmoothl
737b121dfe fix(oidb): correct 0x9083 field layout so fetch_emoji_like returns users
Two bugs collapsed fetch_emoji_like into a perma-empty list with status=ok
and no error output:

1. Req fields 4 and 5 were swapped (emojiType on field 4 / emojiId on
   field 5). The sibling 0x9082 OidbGroupReaction has field 4 = code
   (string) and field 5 = type (uint), and 0x9083 mirrors that layout —
   verified against LagrangeDev/LagrangeV2
   `Internal/Packets/Service/SetGroupReaction.cs`. With our swap the
   wire types also mismatched (varint vs length-delim), so the server
   protobuf decoder dropped both fields and returned an empty list
   without ever surfacing an error.

2. Resp `inner.userInfo` was declared as a single message, but the
   server emits one entry per liker (repeated). Even after fixing the
   req, multi-user responses would have collapsed into the last entry.

Map the decoded array on the InteractionApi side and filter uin=0
placeholders. Test now mocks two users to exercise the repeated path.
2026-05-21 22:10:33 +08:00
DrSmoothl
e088167476 fix(lockfile): rebase against origin/main to unblock PR #63 auto-merge
The previous commit (ee0f159) regenerated the lockfile starting from
dev's pre-fix state, which diverged structurally from main's lockfile
(main carried dependabot's hono 4.12.18 bump that dev never inherited).
GitHub's auto-merger saw the two lockfiles as touching overlapping
hunks and marked PR #63 CONFLICTING, blocking the bot's auto-merge
flow into main.

Re-seed the lockfile from origin/main (`git show origin/main:pnpm-lock.yaml`)
then run `pnpm install` again — this time the regeneration starts from
main's already-bumped state, so the only delta is the 6 lines removed
from `packages/onebot`'s importer entry (no snapshot churn). PR #63
becomes a clean fast-forward for the bot to merge.

No code or package.json change here; this is purely a lockfile rebase.
Verified: `pnpm install --frozen-lockfile` passes locally against the
new lockfile.
2026-05-21 17:50:15 +08:00
DrSmoothl
ee0f159b7e fix(deps): drop dead hono devDeps from @snowluma/onebot, align core to ^4.12.18
`packages/onebot` declared `hono` and `@hono/node-server` as devDeps but
never imported either — they were leftover scaffolding from when onebot
was carved out of `@snowluma/core`. Combined with dependabot's hono
bump only landing on core's pin (4.12.14 → 4.12.18 in cb06624), this
left two distinct peer-dep resolutions of `@hono/node-server` in the
lockfile (`(hono@4.12.14)` for onebot, `(hono@4.12.18)` for core).
On the dev→main merge the auto-resolver kept main's snapshot list,
dropping the `(hono@4.12.14)` variant onebot still referenced — so
v1.9.1 shipped with an inconsistent lockfile and CI's
`pnpm install --frozen-lockfile` blew up with
`ERR_PNPM_LOCKFILE_MISSING_DEPENDENCY: no entry for
'@hono/node-server@1.19.14(hono@4.12.14)'`.

Fix:
- Remove `hono` + `@hono/node-server` from onebot (verified zero source
  imports — only matches were `honour` / `WebHonorType` false hits).
- Bump core's `hono` pin to `^4.12.18` so dev matches what dependabot
  already landed on main (otherwise the drift comes back on next merge).
- Regenerate pnpm-lock.yaml — now resolves to a single
  `@hono/node-server@1.19.14(hono@4.12.21)` snapshot.
2026-05-21 17:43:10 +08:00
DrSmoothl
607a7b319b chore(release): v1.9.1 2026-05-21 17:33:35 +08:00
墨梓柒
a13e09131f Merge pull request #61 from SnowLuma/native/auto-update-native-03d4d0e
chore(native): replace native artifacts (native-03d4d0e)
2026-05-21 16:17:00 +08:00
snowluma-bot[bot]
66f8a5eb2f chore(native): replace native artifacts (native-03d4d0e)
Source: SnowLuma/nnphook@03d4d0ede7
Build:  https://github.com/SnowLuma/SnowLumaNative/releases/tag/native-03d4d0e
2026-05-21 07:09:34 +00:00
墨梓柒
d68535e3d1 Merge pull request #60 from SnowLuma/native/auto-update-native-117413b
chore(native): replace native artifacts (native-117413b)
2026-05-21 14:41:06 +08:00
snowluma-bot[bot]
61f40703ca chore(native): replace native artifacts (native-117413b)
Source: SnowLuma/nnphook@117413b517
Build:  https://github.com/SnowLuma/SnowLumaNative/releases/tag/native-117413b
2026-05-21 06:40:38 +00:00
DrSmoothl
5f1d4400dc fix(build): inject createRequire banner so bundled CJS requires resolve
better-sqlite3's JS wrapper is pure CJS — its `require('fs')` /
`require('path')` / `require('bindings')` calls get inlined into the
ESM bundle as `__require("fs")` shims by rolldown. The shim's
fast-path checks `typeof require !== "undefined"` (true in CJS, false
in our `.mjs` output) and otherwise throws "Calling `require` for
\"fs\" in an environment that doesn't expose the `require` function".
The launcher crashed at startup the moment `@snowluma/sqlite` resolved
its `import BetterSqlite3 from 'better-sqlite3'`.

Inject `const require = createRequire(import.meta.url)` via
`rollupOptions.output.banner` so every inlined CJS require routes to
Node's CJS loader. No call-site changes; the only diff in the emitted
bundle is two new top-of-file import/const lines.
2026-05-21 14:04:14 +08:00
DrSmoothl
4e51b4bd7d build(sqlite): wrap better-sqlite3 with @snowluma/sqlite + vendor prebuilts
Replaces "runtime npm dependency that gets `npm install`-ed into
dist/" with "TS wrapper that loads the native `.node` from
`dist/native/` like every other native binding in the project".

Why the change
--------------
The previous approach (better-sqlite3 declared in
packages/runtime/package.json, materialized by `npm install
--omit=dev` in dist/) worked but produced an artifact that needed
runtime npm install — a step the rest of SnowLuma's native bindings
don't need (websocket / snowluma-hook / ffmpeg are all standalone
`.node` files copied into `dist/native/` by vite-plugin-cp). The
asymmetry was friction: dev mode required `pnpm dist:install`,
build artifacts carried a `dist/node_modules/` tree the other
modules didn't need, and Docker images had to special-case the
glibc-vs-musl ABI lookup that prebuild-install runs.

The new shape:
  - `@snowluma/sqlite` (packages/sqlite/) — TS wrapper. Has
    `better-sqlite3` as a devDep (for the JS-layer types + the
    actual JS wrapper code that vite inlines). At runtime, calls
    `createRequire().require()` against
    `<dist|repo>/native/better-sqlite3-v<abi>-<platform>-<arch>.node`
    and passes the resolved addon to `new Database(path, {
    nativeBinding })`.
  - `packages/runtime/native/better-sqlite3-v<abi>-<triplet>.node`
    — prebuilt binaries vendored into the repo. Two ABIs ship side-
    by-side (v127 = Node 22 LTS used by CI, v137 = Node 24 used by
    dev boxes) so `process.versions.modules` picks the matching one
    at load time.
  - `tools/fetch-sqlite-prebuilts.mjs` — fetches all 5 platforms ×
    N ABIs from WiseLibs's GitHub releases. Idempotent: existing
    `.node` files skip. Accepts extra ABI args:
    `node tools/fetch-sqlite-prebuilts.mjs 12.10.0 v127 v137 v115`.

What was unwound
----------------
- packages/runtime/package.json — dependencies removed (runtime
  artifact is now self-contained, no `npm install` step needed).
- root package.json — `dist:install` script removed (no node_modules
  to install).
- .github/workflows/dev-build.yml — `Bundle runtime dependencies`
  step removed.
- .github/workflows/release.yml — kept the `Bundle runtime
  dependencies` step (was a no-op already, but harmless safety net
  in case a future runtime dep shows up).
- packages/core/vite.config.ts — `better-sqlite3` no longer
  external; vite inlines the JS wrapper (+~33 KB to bundle, ~2.84
  MB → 2.87 MB total).

Naming
------
Mirrors the existing `websocket-${triplet}.node` convention (flat
dir under `runtime/native/`, dash-separated `<platform>-<arch>`).
Adds a `v<abi>` segment because better-sqlite3 is NOT N-API — one
binary per Node ABI. Naming:

  better-sqlite3-v127-darwin-arm64.node    Node 22 / macOS arm
  better-sqlite3-v127-darwin-x64.node      Node 22 / macOS intel
  better-sqlite3-v127-linux-arm64.node     Node 22 / Linux arm
  better-sqlite3-v127-linux-x64.node       Node 22 / Linux x64
  better-sqlite3-v127-win32-x64.node       Node 22 / Windows x64
  better-sqlite3-v137-... (5)              Node 24 / same 5 hosts

Total: 10 binaries × ~1.9 MB = ~19 MB committed. Aligned with the
existing native-vendoring footprint (websocket ~2 MB × 5, snowluma-
hook ~10 MB × Windows + Linux, ffmpeg ~10-30 MB × 4).

What changes for consumers
--------------------------
Source-side: nothing. `import Database, { type Database, type
Statement } from '@snowluma/sqlite'` is a drop-in for the previous
`import Database from 'better-sqlite3'`. The wrapper re-exports the
same types and the `Database` callable factory has the same
overload set.

Runtime: `node` finds the binding at
`<dist|repo>/native/better-sqlite3-v${process.versions.modules}-
${process.platform}-${process.arch}.node`. If the ABI doesn't
match a vendored binary, the wrapper throws a clear error pointing
at `tools/fetch-sqlite-prebuilts.mjs` with the missing ABI/triplet.

Bumped better-sqlite3 from 11.10.0 → 12.10.0 because v11 only had
prebuilt up to Node ABI v127 (no v137 = no Node 24). v12.10.0
ships both. Both versions are API-compat (the breaking changes
between v11 and v12 were either internal or in error-handling
paths SnowLuma doesn't exercise).

Verification
------------
- pnpm -r typecheck (12 projects): clean
- @snowluma/core test: 302/302
- @snowluma/onebot test: 250/250 (552/552 combined, unchanged from
  the perf-series baseline)
- Bench numbers preserved — wrapper indirection is sub-μs:
  storeMeta ~11 μs, storeEvent ~17 μs, findMeta hit ~1.1 μs (all
  within noise of the post-RoadMap-#5 measurements).
- Vite build clean, bundle = 2.87 MB / 230 KB gzip
- `dist/index.mjs` no longer contains a `node:sqlite` import (it
  did before — media-store hadn't migrated; now neither it nor
  message-store reach into the Node builtin).

Bonus side-fix: `packages/onebot/src/media-store.ts` also moved
off `node:sqlite` (caught by the post-build bundle grep — the
file was using `DatabaseSync` + `StatementSync` from the builtin
even though it had already been written to cache its prepared
statements). Its hot paths now go through the same wrapper.
2026-05-21 13:49:19 +08:00
墨梓柒
4e34f8aeb0 Merge pull request #59 from SnowLuma/native/auto-update-native-c0dc4db
chore(native): replace native artifacts (native-c0dc4db)
2026-05-21 10:56:09 +08:00
snowluma-bot[bot]
26777d0010 chore(native): replace native artifacts (native-c0dc4db)
Source: SnowLuma/nnphook@c0dc4db649
Build:  https://github.com/SnowLuma/SnowLumaNative/releases/tag/native-c0dc4db
2026-05-21 02:50:23 +00:00
DrSmoothl
b69d8ac83c build(ci): refresh pnpm-lock.yaml for runtime better-sqlite3 dep
`pnpm install --frozen-lockfile` in CI rejected the lockfile after
998eba2 added `better-sqlite3` to packages/runtime/package.json
without bumping the lock. Running `pnpm install` regenerates the
`packages/runtime: { dependencies: { better-sqlite3: ... } }` block
plus the resolved version pin. No code change — purely the lockfile
catching up to the manifest.
2026-05-21 10:45:56 +08:00
DrSmoothl
998eba2ba8 build(ci): wire better-sqlite3 native binding into release artifacts
Followup to 0b6541c. That commit added `better-sqlite3` as a
workspace dependency and marked it as a vite external — meaning
the bundled `dist/index.mjs` does `require('better-sqlite3')` at
runtime instead of inlining its JS wrapper. Without the binding
+ wrapper present in the production archive, every shipped
SnowLuma would crash on first SQLite op.

The fix is in three small pieces:

1. `packages/runtime/package.json` — declare `better-sqlite3` as a
   runtime dep. `vite-plugin-cp` copies this manifest into
   `dist/package.json` during build (see `runtimeDistFiles` in
   `packages/core/vite.config.ts`), so the release workflow's
   existing `npm install --omit=dev` step inside `dist/` picks it
   up and compiles the native binding for the matrix target via
   prebuild-install (with node-gyp fallback). This is the same
   mechanism release.yml has used since v1.x — it was just empty
   until now because the previous vite config bundled everything.

2. `.github/workflows/dev-build.yml` — mirror the
   `Bundle runtime dependencies` step from release.yml. Dev-build
   was packaging `dist/` straight after vite, which would have
   shipped a broken artifact (no `dist/node_modules/`). Added the
   `npm install --omit=dev` step before the tar/zip packaging
   steps so dev-build archives carry the binding too.

3. `package.json` root — add `dist:install` script (just
   `cd dist && npm install --omit=dev`) so local prod-mimic flows
   work: `pnpm build && pnpm dist:install && pnpm dev:mode`. Not
   chained into `pnpm build` itself to keep the watch-cycle fast
   for users who only need the vite build output; the install
   step adds ~17s.

Note on dev mode: `pnpm dev` continues to work unchanged — it
runs via tsx against workspace `node_modules/`, which already has
`better-sqlite3` compiled (from the workspace-level pnpm install).
Only the dist/-based prod-mimic path needed the explicit install.

Verification
------------
- `pnpm build` (with stubbed native binary): clean, dist/ has the
  updated `dist/package.json` with the dependency declared
- `pnpm dist:install`: installs 38 packages, compiles
  `dist/node_modules/better-sqlite3/build/Release/better_sqlite3.node`
- Smoke-test from `dist/`: `node -e "import('better-sqlite3')..."`
  prints `OK: [ { id: 42 } ]`, confirming the binding loads + a
  basic INSERT/SELECT roundtrip works.

CI matrix coverage: win-x64, linux-x64, linux-arm64 (release.yml +
dev-build.yml share the same matrix). Each builds its own native
binding during the install step — prebuild-install hits
better-sqlite3's prebuilt-binary registry for these three targets
(no source compile needed in the common case, falls back to
node-gyp if a prebuilt isn't available).
2026-05-21 10:44:08 +08:00
DrSmoothl
3f2b474120 RoadMap: tick off #5 after the perf series lands
Three perf commits delivered the wins:
- f3f5d27 perf(bench): bench harness for receive/send chains (RoadMap #5 baseline)
- 0b6541c perf(sqlite): swap node:sqlite for better-sqlite3 + cache prepared stmts
- a70f194 perf(msg-push): drop Buffer.from() wrap on pkt.body (free allocation)

Headline numbers (RoadMap #5 baseline → after):

  Bridge — receive pipeline:
    group_member_join (full) 17.5 μs/op →  4.7 μs/op  (~3.7x)
    parseMsgPush text         0.29 μs/op →  0.25 μs/op (~1.2x)

  OneBot — send pipeline:
    storeMeta                17.0 μs/op → 10.9 μs/op  (~1.6x)
    storeEvent               23.2 μs/op → 18.2 μs/op  (~1.3x)
    findMeta hit              5.4 μs/op →  1.3 μs/op  (~4x)
    findMeta miss             3.7 μs/op →  0.7 μs/op  (~5x)
    findEvent hit             3.8 μs/op →  1.7 μs/op  (~2.3x)

  Combined send hot path:    ~40 μs → ~29 μs per message

Stopped here intentionally — the remaining knobs on the list
(elementsToJson sync-fast-path, WAL checkpoint policy, JSON
serialization swap, dedup-on-unchanged identity writes) have
diminishing returns vs the SQLite win we already cashed in.
Bench harness lives on; if real-world throughput pressure shows
up later, the baseline + delta methodology is already wired and
auditable.

All V2.0.0-pre items are now done.
2026-05-21 10:37:33 +08:00
DrSmoothl
a70f194218 perf(msg-push): drop Buffer.from() wrap on pkt.body (free allocation)
`PacketInfo.body` is typed as `Uint8Array` in `@snowluma/common/
protocol-types` and arrives as one — the `Buffer.from(uint8Array)`
wrap that fed it into `protobuf_decode<PushMsg>(...)` was a no-op
copy. `Buffer` is a `Uint8Array` subclass, and proton's decoder
accepts the parent type directly, so the wrap added one allocation
per incoming push packet without changing behavior.

Bench delta (parseMsgPush, pure decode):
  group_message (text only)    0.29 μs/op → 0.25 μs/op  (~1.2x)
  group_message (5 mixed)      0.50 μs/op → 0.47 μs/op  (~1.07x)
  group_member_join            0.25 μs/op → 0.30 μs/op  (within noise)

Small absolute gain — but `parseMsgPush` runs once per incoming
packet at the very front of the pipeline, so the saved allocation
compounds with the per-message GC churn. The text/mixed group-
message cases pick up cleanly; the join case sits in noise (it has
a smaller body so the Buffer wrap was cheap relative to total).

Verification: pnpm -r typecheck clean; 552/552 tests pass.
2026-05-21 10:36:20 +08:00
DrSmoothl
0b6541ca36 perf(sqlite): swap node:sqlite for better-sqlite3 + cache prepared stmts
Replaces the experimental `node:sqlite` builtin with the stable
`better-sqlite3` wrapper across the two hot SQLite users — the
OneBot message-store and the bridge identity-service. While the API
surface is essentially identical (sync, prepared-statement-driven,
`Database`/`Statement` shape), better-sqlite3 (a) doesn't carry the
"ExperimentalWarning: SQLite is an experimental feature" baggage
that ships with `node:sqlite`, (b) has a more mature C++ binding
that consistently outperforms the builtin by ~30-50%, and (c)
encourages reusing `Statement` objects by design — exactly the win
the second half of this commit is after.

Why both at once
----------------
Caching prepared statements (was P1 in the RoadMap-#5 analysis) is
the largest single optimization opportunity on the SQLite path. The
old shape was the textbook SQLite anti-pattern:

  // every call re-parsed the SQL
  this.db.prepare(BIG_SQL_STRING).run(...);

Each `prepare(sql)` runs the full SQL parser + planner — for simple
inserts/updates/selects that dominates wall-clock cost. Doing both
the driver swap AND the statement caching in one commit lets the
benchmark numbers attribute the combined effect honestly; splitting
them would have double-charged the same disruption budget.

What changed code-wise
----------------------
**messageStore** — 8 distinct SQL templates, all now `readonly`
fields prepared once in the constructor:
  - stmtStoreEvent      — INSERT/UPDATE event row + JSON payload
  - stmtStoreMeta       — INSERT/UPDATE meta-only row
  - stmtFindEvent       — single-row SELECT by message_hash
  - stmtFindMeta        — single-row SELECT (full meta columns)
  - stmtResolveReplyGroup, stmtResolveReplyPrivate
                        — 2 variants for the reply-id lookup
  - stmtListEventsAnchored, stmtListEventsLatest
                        — 2 variants for /get_history_msg

**identity-service** — 25+ distinct statements. Used a Map-based
`pstmt(sql)` memoization helper rather than enumerating all 25 as
named fields (call sites stay readable; Map lookup is O(1) hash +
string-eq, negligible next to the SQL parse it replaces). The
helper short-circuits to the cached `Statement` on second-and-later
calls.

API differences from node:sqlite (handled in this commit):
  - `import { DatabaseSync } from 'node:sqlite'`
       → `import Database from 'better-sqlite3'`
  - `new DatabaseSync(path)` → `new Database(path)`
  - `db.exec('PRAGMA journal_mode = WAL')`
       → `db.pragma('journal_mode = WAL')`
  - `db.exec('BEGIN' / 'COMMIT' / 'ROLLBACK')` — kept as-is; both
       drivers accept raw `exec()` for transaction control. The
       `db.transaction()` higher-order wrapper is more idiomatic
       but the existing manual control already works and changing
       it would invalidate the `transaction()` helper's matched
       try/catch shape.

vite build wiring:
  - `node:sqlite` removed from the externals list
  - `better-sqlite3` added — must stay external because it has a
    native binding (`require('./build/Release/better_sqlite3.node')`)
    that Vite can't bundle. Vendoring the prebuilt `.node` into
    `packages/runtime/native/` is a follow-up packaging task; the
    workspace `pnpm install` already places the binding under
    `node_modules` so dev + tests work today.

Bench results (RoadMap #5 baseline → after)
-------------------------------------------
@snowluma/bridge — recv pipeline (with SQLite identity writes):
  group_member_join         17.5 μs/op → 4.7 μs/op   (~3.7x faster)
  group_message text         0.42→0.42 μs            (no path change)
  group_message mixed        0.67→0.67 μs            (no path change)

@snowluma/onebot — send pipeline:
  messageStore.storeMeta    17.0 μs/op → 10.9 μs/op  (~1.6x)
  messageStore.storeEvent   23.2 μs/op → 18.2 μs/op  (~1.3x)
  messageStore.findMeta hit  5.4 μs/op →  1.3 μs/op  (~4x)
  messageStore.findMeta miss 3.7 μs/op →  0.7 μs/op  (~5x)
  messageStore.findEvent     3.8 μs/op →  1.7 μs/op  (~2.3x)

Read paths gained the most because they're parse-bound (small SQL
+ short execution → the parser was most of the cost). Writes gained
less because the fsync/journal overhead on each commit still
dominates the parse savings. Combined send hot path (storeMeta +
storeEvent, called on every outbound message + the /get_msg-fix
self-event store) drops from ~40 μs to ~29 μs — about a 27%
reduction per message sent.

Verification
------------
- pnpm -r typecheck: all 11 projects clean
- @snowluma/onebot test suite: 250/250
- @snowluma/core test suite: 302/302
- Combined: 552/552 (unchanged baseline)
- Vite build (with stubbed native binary): clean, 2.84 MB / 223 KB
  gzip (matches pre-Phase-2 envelope after removing the better-
  sqlite3 inline-bundle attempt — externalizing it shaves the
  ~30 KB regression we saw mid-flight)

Follow-up (next commits in this series)
---------------------------------------
- Skip rememberGroupMemberIdentity DB write when the (uid, uin,
  nickname, card) tuple is unchanged in the in-memory cache.
- Drop the `Buffer.from(pkt.body)` allocation in msg-push context.
- Synchronous fast-path for elementsToJson when no async resolver
  is wired.
- Vendor `better-sqlite3` prebuilt `.node` into the runtime/native
  layout for the production package step.
2026-05-21 10:34:37 +08:00
DrSmoothl
f3f5d27c65 perf(bench): bench harness for receive/send chains (RoadMap #5 baseline)
vitest-driven benches at `packages/bridge/bench/recv.bench.ts` and
`packages/onebot/bench/send.bench.ts`. Picks up proton's vite plugin
so call sites get the inlined codecs (running via tsx + proton
runtime-fallback would throw without a pre-built runtime map).

Run via `pnpm -F @snowluma/bridge bench` and
`pnpm -F @snowluma/onebot bench`.

What's measured
---------------
Receive chain:
  - parseMsgPush: pure decode + dispatch (no SQLite, no event emit)
    * group_message text          ~ 0.29 μs/op  (3.4M ops/sec)
    * group_message 5 mixed       ~ 0.50 μs/op  (2.0M ops/sec)
    * group_member_join           ~ 0.25 μs/op  (4.1M ops/sec)
  - IncomingPacketPipeline.process: full pipeline (with SQLite via
    rememberGroupMemberIdentity, BridgeEventBus emit)
    * group_message text          ~ 0.42 μs/op  (2.4M ops/sec)
    * group_message 5 mixed       ~ 0.67 μs/op  (1.5M ops/sec)
    * group_member_join           ~17.5  μs/op  ( 57K ops/sec) ⚠

Send chain:
  - parseMessage (OneBot input → MessageElement[])
    * CQ string text              ~ 0.31 μs/op
    * CQ string mixed             ~ 1.22 μs/op
    * segment array text          ~ 0.32 μs/op
    * segment array 5             ~ 1.07 μs/op
  - messageStore SQLite writes:
    * storeMeta                   ~17.0  μs/op  ( 59K ops/sec) ⚠
    * storeEvent (~250B JSON)     ~23.2  μs/op  ( 43K ops/sec) ⚠
  - messageStore reads:
    * findMeta hit                ~ 5.4 μs/op  (186K ops/sec)
    * findMeta miss               ~ 3.7 μs/op  (272K ops/sec)
    * findEvent hit               ~ 3.8 μs/op  (262K ops/sec)

Headline finding
----------------
Pure decode/encode is already cheap (sub-μs). The real cost per
sent message is the SQLite write pair (storeMeta + storeEvent =
~40 μs). On receive, group_message itself does NOT trigger
identity writes; only join/leave/admin events do — but those go
through 4-6 db.prepare(sql).run/get(...) calls each, all re-parsing
SQL on every invocation (the canonical SQLite anti-pattern).

The follow-up commits in this series target:
  1. Replace `node:sqlite` (experimental, API may shift) with
     `better-sqlite3` (stable, sync, ~30-50% faster wire) + cache
     prepared statements as readonly fields. Single commit, both
     wins together — better-sqlite3's API encourages stmt caching
     by design. Expected: storeMeta / storeEvent drop to ~3-5 μs,
     group_member_join drops to ~3-5 μs.
  2. Skip rememberGroupMemberIdentity DB write when the in-memory
     uidByUin / uinByUid cache already has the mapping unchanged.
  3. Drop the `Buffer.from(pkt.body)` allocation in msg-push
     context (pkt.body is already Uint8Array; proton accepts it).
  4. Make `elementsToJson` sync-fast-path when no async resolvers
     are wired (saves per-element microtask overhead).

Each commit re-runs these benches and the message should quote the
before/after numbers so the deltas are auditable.

Note: tsx is NOT involved — vitest's bench mode owns the run, and
the proton vite plugin is configured in each `vitest.config.ts`.
Absolute numbers reflect the production code path.
2026-05-21 10:26:29 +08:00
DrSmoothl
070e39090a fix(hook): retry stranded 'disconnected' sessions when pipe is still up
Windows users reported "running a while then stops" with logs:
  WARN  [Hook]   pipe error: PID=1312 err=read EPIPE
  DEBUG [Bridge] session closed: UIN=752645868
  INFO  [OneBot] session closed: UIN=752645868

The user-side socket read fails with EPIPE (idle-timeout, transient
Windows named-pipe fault, or similar). The cascade:

  1. hook-client's `socket.on('error')` → emits 'error'
     → hook-session logs "pipe error: PID=… err=read EPIPE"
  2. socket then emits 'close' → bindClient's close handler runs
     `tearDownClient()` and sets status to 'disconnected' (because
     wasLoggedIn = true)
  3. PipeWatcher's next tick polls `listLivePipes()` natively — and
     the OS-level named pipe is STILL listed (DLL is still resident
     in QQ.exe, it never closed its end). So no `pipe-down` →
     `pipe-up` cycle ever fires.
  4. hook-manager's `tick` reconcile loop only retried sessions
     whose status was exactly 'connecting' (line 208 in
     hook-manager.ts). A 'disconnected' session that should
     reconnect was simply ignored.

Result: the session was stranded forever; QQ kept running, DLL
kept running, but SnowLuma never re-established its socket. The
only recovery was a full SnowLuma restart.

Fix: include `'disconnected'` in the retry predicate. `onPipeUp` is
idempotent (it checks `isClosed` / `!connected` internally and rebuilds
the socket pair from scratch) so we can safely call it from the
tick loop every ~1.5s until either the reconnect lands or the
watcher reports a genuine pipe-down.

No behavior change for sessions already in any other state — only
the 'disconnected' branch gains the auto-retry.
2026-05-21 10:22:38 +08:00
DrSmoothl
450b551701 RoadMap: tick off #6 after the OneBot-side ctx slim-down lands
#6 was the "API层挂到ctx" item — Core side delivered the 13 typed
Api classes back in the e8d1af4...f4c6838 commit series; this turn
finished the OneBot side via the 4 ctx slim-down commits
(cb698d2 / 4c4ce60 / 8bf2ff3 / d983635).

ApiActionContext shrank from 90+ fields → ~30. Removed surfaces:
  - groupAdmin / groupFile / groupAlbum / friend / interaction /
    message / profile / web — all moved to direct
    `ctx.bridge.apis.<area>.method()` invocations.
Kept surfaces (real composition, not pass-through):
  - instance state: bridge / getLoginInfo / isOnline / getMessage*
  - module helpers: sendXxxMessage / sendXxxForwardMsg / forwardSingle /
    deleteMessage / setEssenceMsg / setMsgEmojiLike / handleGroupRequest
  - cache-backed reads: getFriendList / getGroupList / getGroupInfo
    /Member* / getStrangerInfo / getGroupFiles / get*MsgHistory /
    handleGetGroupSystemMsg / getDownloadRKeys
  - media store reads: getImageInfo / getRecordInfo

Full NapCat class-per-action conversion (TypeBox schemas / actionName
enum / auto-register decorator / 170 single-file classes) deliberately
not pursued — the metadata-driven design is meaningful only with
downstream doc/test tooling that consumes it, which SnowLuma doesn't
ship today. Marked as a follow-up under the same item if/when that
tooling appears.
2026-05-21 09:32:07 +08:00
DrSmoothl
d983635c8f refactor(onebot): inline ctx.bridge.apis.profile/web/groupAlbum direct calls
Remove the remaining ~20 passthrough fields from ApiActionContext
spanning four Api areas — most were already dead (no caller) since
extended.ts had migrated to direct `ctx.bridge.apis.X` paths in
earlier #6 commits.

  profile area:
    - setProfile / setOnlineStatus / fetchCustomFace /
      setGroupAvatar     ── all already dead
    - getProfileLike    ── one live caller in extended.ts inlined

  web area:
    - getGroupHonorInfo / getGroupEssence / getGroupEssenceAll /
      sendGroupNotice / getGroupNotice / deleteGroupNotice /
      getCookiesStr / getCsrfToken / getCredentials /
      forceFetchClientKey  ── all already dead

  groupAlbum area:
    - getGroupAlbumList / uploadImageToGroupAlbum /
      getGroupAlbumMediaList / commentGroupAlbumMedia /
      deleteGroupAlbumMedia / likeGroupAlbumMedia  ── all 7 live
      callers in actions/group-album.ts inlined to
      `ctx.bridge.apis.groupAlbum.<m>(...)`

  friend area:
    - setFriendRemark   ── already dead

Behavior preserved: getProfileLike's `userId = 0 → self` semantics
keep working because ProfileApi.getLike uses `isSelf = !userId`
internally (0 and undefined are equivalent for that check); same
default args at the action site (`start = 0`, `count = 10`).

Group-album action handlers now wrap the typed Api return values
(GroupAlbumMediaResult, GroupAlbumCommentResult) with
`as unknown as JsonValue` for okResponse compatibility — the old
ctx wrapper was typed `Promise<any>` which silently hid the cast;
making the cast explicit doesn't change runtime.

Part 4 of the OneBot-side slim-down. 552/552 tests still green.
2026-05-21 09:29:28 +08:00
DrSmoothl
8bf2ff3f36 refactor(onebot): inline ctx.bridge.apis.friend/interaction/message direct calls
Remove 8 passthrough fields from ApiActionContext spanning three Api
areas:

  friend area:
    - handleFriendRequest  (set_friend_add_request)
    - handleDeleteFriend   (delete_friend)
    - setFriendRemark already kept the field name but now unused

  interaction area:
    - sendFriendPoke / sendGroupPoke  (friend_poke, group_poke, send_poke)
    - getEmojiLikes  (was already dead — extended.ts used the direct
      path; field removed)

  message area:
    - markGroupMsgAsRead / markPrivateMsgAsRead  (already dead —
      mark_msg_as_read sites use the module helper)

`handleGroupRequest` stays on ctx because `handleGroupAddRequest` is
a module helper that does the flag-parsing + group-request roster
lookup before routing to `bridge.apis.groupAdmin.setAddRequest` —
real composition, not a passthrough.

Behavior preserved: same flag parsing (`asString/asNumber/asBoolean`),
same `isGroup` flag flatten into `sendPoke(isGroup, peerUin, target?)`,
same default `block=false` for delete_friend.

Part 3 of the OneBot-side slim-down. 552/552 tests still green.
2026-05-21 09:23:32 +08:00
DrSmoothl
4c4ce60bf2 refactor(onebot): inline ctx.bridge.apis.groupFile direct calls
Remove 6 passthrough fields from ApiActionContext for the group-file
area (`uploadGroupFile / uploadPrivateFile / getGroupFileUrl /
createGroupFileFolder / getPrivateFileUrl / getGroupFileCount`).
Action sites (`actions/group-file.ts` and one site in
`actions/extended.ts`) now call `ctx.bridge.apis.groupFile.<method>`
directly.

`getGroupFiles` stays on the ctx because its module helper
(`getGroupFiles(bridge, groupId, folderId)` in `modules/contact-actions.ts`)
does identity-lookup enrichment of uploader/creator names — not a pure
passthrough.

Behavior preserved: same default values (`name = ''`, `folderId = '/'`,
`busId = 102`, `uploadFile = true`) — they were baked into the ctx
wrapper before, now they're explicit in the action site (`asString`
returns `''`, `... || '/'`, `... || 102`, `asBoolean(..., true)`).
The result-unwrap (`fileId` extraction from `UploadFileResult`) moves
from the ctx wrapper into the action handler.

Part 2 of the OneBot-side slim-down. 552/552 tests still green.
2026-05-21 09:19:27 +08:00
DrSmoothl
cb698d2435 refactor(onebot): inline ctx.bridge.apis.groupAdmin direct calls
Remove the 6 pure pass-through fields from `ApiActionContext` for the
group-admin area (`setGroupKick / setGroupKickMembers / setGroupBan /
setGroupWholeBan / setGroupLeave / setGroupRemark`). All 5 call sites
in `actions/group-admin.ts` now invoke `ctx.bridge.apis.groupAdmin.<m>`
directly. `setGroupRemark` had zero remaining callers (extended.ts
was already on the direct path) so the field is simply deleted.

Part 1 of RoadMap #6 OneBot-side slim-down. Core side's typed Api
hub (bridge.apis.X) has been in place since the #6 commit series;
OneBot actions were still routing through a 90+ field bag-of-
functions on `ApiActionContext`. Most of those fields were 1:1
shims like `setGroupKick: (g,u,r) => bridge.apis.groupAdmin.kickMember(g,u,r)` —
pure indirection with no composition logic. This commit kills the
group-admin chunk; the friend / interaction / profile / web / album /
groupFile / message chunks land in follow-up commits.

Behavior preserved byte-for-byte: same parameter parsing
(`asNumber/asString/asBoolean`), same default values, same 1800s
mute fallback, same error responses. 552/552 tests still green.
2026-05-21 09:16:15 +08:00
DrSmoothl
a011b8f033 chore(sdk): point actions-sync test at @snowluma/onebot
Path follow-up to the 4-package split — the action registrations
moved from `packages/core/src/onebot/actions/` to
`packages/onebot/src/actions/` in Phase 3. The test was failing with
ENOENT on the old path before reaching the actual assertion. Note
that this test has a separate pre-existing failure (it imports a
non-exported `SNOWLUMA_ACTIONS` symbol from the SDK); the path fix
just clears the first of the two errors.
2026-05-21 08:54:44 +08:00
DrSmoothl
72320121c3 RoadMap: tick off #3 after the 4-package split lands
Three phased commits delivered the split:
- 46b302f refactor(common): leaf utilities → @snowluma/common
- (the bridge phase commit) protocol layer → @snowluma/bridge
- (the onebot phase commit) translation layer → @snowluma/onebot

Final layout:

  packages/common/    ~8 files    logger / hex / packet-sender /
                                  protocol-types / runtime / json /
                                  log-file-transport / log-summary
  packages/bridge/    ~35 files   events / event-bus / identity /
                                  packet-pipeline / element-builder /
                                  bridge-oidb / qq-info / format /
                                  msg-push/* / highway/* / web/*
  packages/core/      ~32 files   bridge.ts (god-class) / bridge-
                                  interface / bridge-context (extends
                                  bridge package's slim BridgeContext
                                  with apis: ApiHub) / manager /
                                  apis/* (13 Api classes) / hook/* /
                                  webui/* / index.ts (app entry)
  packages/onebot/    ~43 files   actions/* / modules/* / network/* /
                                  event-converter/* / instance /
                                  instance-context / manager /
                                  message-{id,parser,store} /
                                  media-{store,indexer,url-resolver}
2026-05-21 08:52:54 +08:00
DrSmoothl
9a30df9907 refactor(onebot): extract OneBot protocol translation into @snowluma/onebot
Phase 3 of the 4-package split (RoadMap #3). Moves the entire
`packages/core/src/onebot/` subtree (43 source files + 20 test files
spanning network adapters, action handlers, event converters, message
parser, message store, media store, instance + manager) into the new
`@snowluma/onebot` workspace package. The remaining `@snowluma/core`
now hosts only the api-layer (Bridge class + 13 Api classes), the
hook tooling, the WebUI server, and the runnable `index.ts`.

Why
---
- The OneBot adapter is the public-facing OneBot11 protocol surface;
  it has its own version cadence and its own consumers (third-party
  bots talking OneBot WS / HTTP). Splitting it lets that cadence move
  independently of the Api-on-ctx layer.
- The two were sharing the `packages/core/` build pipeline only
  because they happened to live in the same directory. Nothing in
  the api-layer reaches into OneBot internals.
- Mirrors NapCat / Lagrange.OneBot's repo split (their OneBot adapter
  is a separate assembly from the Core protocol library).

Layout
------
Moved via `git mv` (history preserved):
  packages/core/src/onebot/*  → @snowluma/onebot/src/<x>
  packages/core/tests/onebot/* (6 files)   → @snowluma/onebot/tests/
  packages/core/tests/{message-parser,message-store,event-pipeline,
    media-store,media-url-resolver,event-converter,
    http-server-hot-reload,http-server-content-type,
    api-handler-logging,message-id,group-msg-emoji-like,
    config,media-indexer,network-manager}.test.ts (14 files)
                                              → @snowluma/onebot/tests/

What stays in @snowluma/core
----------------------------
- `bridge/{bridge,bridge-interface,bridge-context,manager}.ts`
- `bridge/apis/*` (the 13 typed Api classes)
- `hook/*` (debugger/injector — tooling for the core protocol layer)
- `webui/*` (admin UI server — application wiring, not the OneBot
  adapter itself)
- `index.ts` (application entry that wires BridgeManager +
  OneBotManager + HookManager + WebUI together)

Changes
-------
- New package `packages/onebot/` (package.json with subpath exports
  mirroring legacy `core/src/onebot/<x>` 1:1, tsconfig.json,
  vitest.config.ts with `SNOWLUMA_LOG_LEVEL=debug` env so the action-
  dispatch logging tests see debug-level subscribers — copied verbatim
  from core's vitest.config.ts).
- @snowluma/core grows new subpath exports for the api-layer files
  OneBot's type-only imports need: `./bridge`, `./bridge-interface`,
  `./bridge-context`, `./manager`, `./apis`.
- `@snowluma/onebot` depends on `@snowluma/bridge`, `@snowluma/common`,
  `@snowluma/core`, `@snowluma/proto-defs`, `@snowluma/proton`,
  `@snowluma/websocket`.
- `@snowluma/core` depends on `@snowluma/onebot` (for index.ts +
  webui/server.ts wiring).
- 100+ import sites rewritten via sed:
  * OneBot → core: `'../bridge/bridge'` → `'@snowluma/core/bridge'`,
    `'../bridge/manager'` → `'@snowluma/core/manager'`,
    `'../bridge/bridge-interface'` → `'@snowluma/core/bridge-interface'`,
    `'@/bridge/bridge'` (vite path alias) → `'@snowluma/core/bridge'`.
  * Core → OneBot: `'./onebot/manager'` → `'@snowluma/onebot/manager'`,
    `'../onebot/config'` → `'@snowluma/onebot/config'`, etc.
  * Test relative paths: `'../../src/onebot/<x>'` → `'../src/<x>'`
    after the test file move (one level shallower).
- New `packages/onebot/src/env.d.ts` declaring `__APP_VERSION__` and
  `__BUILD_WEBUI__` (the vite-injected globals `info.ts` reads).

Workspace cycle
---------------
core ↔ onebot is allowed by pnpm workspaces. The runtime direction
is one-way: core → onebot (index.ts constructs OneBotManager,
webui/server reads OneBot config). OneBot only reaches into core for
TYPES (Bridge, BridgeInterface, BridgeManager, ClientKeyInfo,
DownloadRKeyInfo); those imports use `import type` so they compile
out at runtime and don't introduce a real cycle.

Verification
------------
- Full workspace `pnpm -r typecheck`: all 11 projects clean.
- `@snowluma/core` test suite: 302/302 pass (33 test files).
- `@snowluma/onebot` test suite: 250/250 pass (20 test files;
  pre-existing `network-manager.test.ts` native-addon failure
  unchanged — same baseline as before the split).
- Combined: 552/552 — identical pass count to the pre-Phase-3
  baseline.
- Vite build with stubbed native binary: clean, 2.84 MB bundle /
  224 KB gzip (identical envelope).
2026-05-21 08:52:00 +08:00
DrSmoothl
f7a03ca05a refactor(bridge): extract protocol layer into @snowluma/bridge package
Phase 2 of the 4-package split (RoadMap #3). Moves ~35 files —
events / event-bus / identity-service / packet-pipeline / element-
builder / bridge-oidb / qq-info / msg-push/* / highway/* / web/* +
the bridge-side formatters — out of `packages/core/src/bridge/`
into the new `@snowluma/bridge` workspace package. Everything that
translates QQ wire bytes ↔ typed events/elements now lives there.

Why
---
- `packages/core/src/bridge/` was actually two layers: a low-level
  "protocol decoder + I/O" set (msg-push, highway, packet-pipeline,
  identity, element-builder) AND the Api-class host (bridge.ts +
  apis/*). The Api layer can't move without the protocol layer
  moving first, but the two had grown into one directory.
- Bridge-internal consumers (highway uploaders, OIDB envelope
  helper, element-builder, msg-push parsers) only ever needed
  `bridge.identity` + `bridge.sendRawPacket` + the upload-metadata
  cache. Splitting them out lets that minimal surface live in the
  bridge package as `BridgeContext` while the api-layer's extended
  context (with `apis: ApiHub`) stays in @snowluma/core.

What stays in @snowluma/core (apis layer):
  - bridge.ts          ── the god-class that composes the protocol
                          building blocks + mounts apis
  - bridge-interface.ts ── public façade for OneBot consumers
  - manager.ts          ── per-uin BridgeManager hub
  - apis/*              ── the 13 typed Api classes
  - bridge-context.ts (NEW) ── extends @snowluma/bridge's slim
                              BridgeContext with `apis: ApiHub` so
                              the 13 Api classes keep their typed
                              `this.ctx.apis.X.method()` access.

Layout
------
Moved via `git mv` (history preserved):
  events / event-bus / identity-service / packet-pipeline /
  element-builder / bridge-oidb / qq-info / msg-push/* /
  highway/* / web/*           → @snowluma/bridge/<sub>
  utils/event-format.ts        → @snowluma/bridge/format.ts

  (the last one renamed because the destination directory only has
  bridge-related files; `format.ts` reads cleaner than `event-format`.
  Listed as a rename in git's `RM` output — content unchanged.)

Layering fixes (functionality preserved, just type signatures)
--------------------------------------------------------------
- `element-builder.SendContext.bridge` → typed as `BridgeContext`
  instead of `Bridge`. Reads only `bridge.identity` and the
  upload-cache (both on BridgeContext); the concrete `Bridge`
  instance still passes via free upcast.
- `bridge-oidb.runOidb` signature widened from `Bridge` to
  `BridgeContext` — same reason.
- `highway/{highway-client,pipeline,image-upload,ptt-upload,
  video-upload}.ts` — same.
- `format.ts::formatReply` parameter typed as a new local
  `ReplyEventLookup` structural type (`{ findEvent(id): JsonObject |
  null }`) instead of `MessageStore` from @snowluma/onebot. The
  OneBot `MessageStore` is a structural superset; consumers pass
  it through unchanged.
- JSON value types moved to a new `@snowluma/common/json` subpath
  (consumed by format.ts) — `onebot/types.ts` re-exports them so
  external `import { JsonValue } from '<…>/onebot/types'` paths
  keep working.
- `UploadedFileMeta` interface moved from `core/src/bridge/bridge.ts`
  into `@snowluma/bridge/bridge-context.ts` — element-builder + the
  forward-builder both read the upload cache through BridgeContext,
  so the type has to live in @snowluma/bridge. `bridge.ts` keeps
  its re-export for back-compat.

Changes
-------
- New package `packages/bridge/` (package.json with per-file subpath
  exports mirroring legacy `core/src/bridge/<x>` layout 1:1,
  tsconfig.json, typecheck script).
- 35 `.ts` files moved via `git mv` (3 files counted by git as
  RM — rename + modify because Bridge → BridgeContext type swap).
- 150+ import sites rewritten across `packages/core/src` and
  `packages/core/tests`: `'../bridge/<x>'`, `'../../bridge/<x>'`,
  `'../src/bridge/<x>'`, `'@/bridge/web/<x>'`, and vitest
  `vi.mock(...)` literals all collapse to `@snowluma/bridge/<x>`.
- `@snowluma/core` depends on `@snowluma/bridge` (workspace:*).
- `@snowluma/bridge` depends on `@snowluma/common`,
  `@snowluma/proto-defs`, `@snowluma/proton`.
- `packages/core/src/utils/` directory removed (empty).

Verification
------------
- Full workspace `pnpm -r typecheck`: all 10 projects clean.
- core test suite: 552 passed / 552 total (pre-existing
  websocket-darwin-arm64.node addon failure unchanged — same
  baseline as the previous refactor commits).
- Vite build (with stubbed native binary): clean — 143 modules,
  2.84 MB bundle / 224 KB gzip, identical envelope to the
  pre-split build.

Phase 3 (next): OneBot + WebUI move into @snowluma/onebot. The
runnable `index.ts` stays in @snowluma/core as the application
entry, importing `OneBotManager` from `@snowluma/onebot`.
2026-05-21 08:41:34 +08:00
DrSmoothl
46b302f738 refactor(common): extract leaf utilities into @snowluma/common package
Phase 1 of the 4-package split called out in RoadMap #3. Moves the
"infrastructure" leaves — files with zero business dependencies that
@snowluma/bridge, @snowluma/core, and @snowluma/onebot all consume —
into a dedicated workspace package. Mirrors what #4 (proto-defs)
did for wire-protobuf definitions.

Why
---
- Cleaner layering: these were never bridge- or onebot-specific.
  Logger / hex codec / runtime config sit at the bottom of every
  module's import graph; giving them their own package makes that
  graph readable and prevents future leaks the other direction.
- Sets up #3's bridge + onebot extractions: those need a clean leaf
  to depend on. Without this, every cross-package import would have
  to re-export through core, which defeats the split.
- Mirrors @snowluma/proto-defs layout — per-file subpath exports
  (`@snowluma/common/logger`, `@snowluma/common/hex`, …) keep import
  sites unambiguous and let bundlers tree-shake aggressively.

Layout
------
Moved (via `git mv` — history preserved):
  packages/core/src/utils/logger.ts             → @snowluma/common/logger
  packages/core/src/utils/hex.ts                → @snowluma/common/hex
  packages/core/src/utils/log-file-transport.ts → @snowluma/common/log-file-transport
  packages/core/src/utils/log-summary.ts        → @snowluma/common/log-summary
  packages/core/src/protocol/packet-sender.ts   → @snowluma/common/packet-sender
  packages/core/src/protocol/types.ts           → @snowluma/common/protocol-types
  packages/core/src/common/runtime.ts           → @snowluma/common/runtime

Not moved (deferred to Phase 2): `packages/core/src/utils/event-format.ts`
— it has reverse imports on `bridge/events`, `bridge/identity-service`,
`onebot/message-store`, `onebot/types`. It moves into @snowluma/bridge
in Phase 2, with the MessageStore parameter decoupled via a structural
type so bridge doesn't end up depending on onebot.

Changes
-------
- New package `packages/common/` (package.json, tsconfig.json — no
  src/index.ts barrel, callers use the subpath exports directly to
  avoid pulling in `node:fs` when only the hex codec is needed).
- 7 `.ts` files moved via `git mv`.
- 50+ import sites rewritten via sed across `packages/core/src` and
  `packages/core/tests`. Old shapes (`../utils/logger`,
  `../../protocol/types`, `./common/runtime`, `../src/utils/hex`)
  all collapse to `@snowluma/common/<sub>`.
- `@snowluma/core` depends on `@snowluma/common` (workspace:*).
- `packages/core/src/{protocol,common}/` directories removed (empty).

Verification
------------
- core typecheck: clean
- common typecheck: clean
- Full workspace `pnpm -r typecheck`: all 9 projects clean
- core test suite: 552 passed / 552 total (pre-existing
  websocket-darwin-arm64.node addon failure unchanged — same baseline
  as the previous refactor commits)
- Vite build with stubbed native binary: clean (143 modules, 2.84 MB
  bundle, 224 KB gzip — same size envelope as before)

Note: `utils/event-format.ts` is the only file remaining under the
old `utils/` namespace. It moves into @snowluma/bridge alongside the
events / identity-service / packet-pipeline trio in Phase 2.
2026-05-21 08:27:05 +08:00
DrSmoothl
e1c9ede9de RoadMap: tick off #2/#4 and partial #6 after the dev-branch refactor
- #2 (Proton ts+map fallback for unbundled debug) — landed in
  `994633e feat(proton): resolve bare specifiers via TypeScript module
  resolution` + `6c7e56d refactor(proto-defs)`. Bare specifiers like
  `@snowluma/proto-defs/oidb` now resolve to the original `.ts` source
  through `ts.resolveModuleName` (Bundler mode), so tsx/node + vite
  share the same import surface.

- #4 (proto definitions in their own package) — landed in
  `6c7e56d refactor(proto-defs)`. Moved 13 proto `.ts` files (~3.3k
  LOC) into the new `@snowluma/proto-defs` workspace package with
  per-file subpath exports; 44 call sites across core/tests rewritten.

- #6 (NapCat-style Api on ctx) — half done. Core side fully landed
  through 13 sequential commits (3e5dca1 → f4c6838) — `bridge.apis.<
  area>.method()` covers all 13 areas, `BridgeInterface` is gone, the
  `actions/*` directory is deleted. OneBot side is NOT done: actions
  still receive an `ApiActionContext` (a flat bag of functions) and
  call `ctx.bridge.apis.*` directly rather than going through a
  dedicated OneBot Api class layer.
2026-05-21 08:13:06 +08:00
DrSmoothl
e7afef5d63 fix(proto): correct OidbGroupReaction field numbers (off-by-one)
`set_msg_emoji_like` was failing with
"invalid ReqBody.EmojiType: value must be greater than 0" because
`OidbGroupReaction` had every field number off by one — `type` was at
field 4, but the server reads `EmojiType` at field 5. The mistake
covered all four fields:

  field   what       was   should be
  ─────   ────────   ───   ─────────
  2       groupUin    1    2
  3       sequence    2    3
  4       code        3    4
  5       type        4    5

Cross-checked with Lagrange.Core V2's `OidbSvcTrpcTcp0x9082.cs` —
their definition starts at field 2 and runs through 7. The OIDB
envelope wraps the body at field 4, so the inner body's own fields
must start at 2 to avoid collision with the wrapper. (The previous
1..4 layout happened to encode SOMETHING wire-valid, just not what
the server's `OidbSvcTrpcTcp0x9082` validator expected.)

Also added the trailing `field6` and `field7` unused booleans that
Lagrange serialises as `false`. The server currently tolerates them
missing; including them keeps SnowLuma byte-identical with Lagrange
in case the validator gets stricter.

The reaction-type heuristic stays the same (`code.length > 3 ? 2 : 1`
— Lagrange uses the same `IsEmoji => Code.Length > 3` check in
`GroupAddReactionEvent.cs`).
2026-05-21 08:10:53 +08:00
DrSmoothl
0479924482 fix(msg): cache self-sent messages so /get_msg can find them
`/get_msg` with a `message_id` returned by `send_*_msg` was failing
with "message not found" because the send-side only called
`cacheMessageMeta` (used by recall/delete), never `storeEvent`
(used by /get_msg lookup).

The QQ server sometimes echoes self-sent messages back through the
receive channel (which would populate `storeEvent` via the normal
event pipeline), but it's not reliable — Lagrange and NapCat both
work around this by persisting a local copy at send time. Lagrange
writes into Realm DB inside `SendMessageOperation.cs`; NapCat caches
in-memory via its msg service.

Mirror them: synthesise a `post_type: 'message_sent'` event from the
parsed `MessageElement[]` (converted back to OneBot segments via the
existing `elementsToOneBotSegments`) and write it directly into
`messageStore.storeEvent` — bypassing `dispatchEvent` so we don't
broadcast the synthetic event over the WS bridge (the QQ server's
own echo is the source of truth for that).

Wired into all five outbound paths:
- sendPrivateMessage (modules/message-actions.ts)
- sendGroupMessage
- sendGroupForwardMessage (the wrapping ARK card)
- sendPrivateForwardMessage
- forwardSingleMessage (both branches)

The helper is defensive: tests stub `messageStore` as
`{ findEvent: () => null } as any` without `storeEvent`, so the
helper checks for the function and bails quietly when absent.
Failure inside the helper is logged but never thrown — recall +
the send return value matter more than /get_msg lookup.
2026-05-21 08:10:35 +08:00
DrSmoothl
e5e85d8d4b fix(file): consult upload cache when emitting transElem(24) in forwards
`send_forward_msg` with a `{type:'file', file_id}` segment to a GROUP
was sending a 0 B file (no name, no size, no md5/sha1) because
`makeGroupFileElem` read those fields directly off `MessageElement`
without falling back to `bridge.recallUploadedFile()`.

The c2c forward path in `apis/forward.ts::buildForwardPushBody`
already does this lookup (line ~126) — that's why forwarding to a
private chat worked but to a group didn't. Mirror it here.

OneBot11 callers typically thread only the file_id through (the
upload action returns just the id), so the cached metadata is the
only place size/md5/sha1/name come from. Without it the long-msg
payload encodes `GroupFileExtra { fileSize=0, fileName='', md5='',
fileSha='' }` and the receiver renders a "0 B" file bubble.
2026-05-21 08:10:16 +08:00
DrSmoothl
f4c6838e65 refactor(api): move 10 web methods to WebApi + finalize cleanup (#6 commit 12/13)
Final commit of the #6 NapCat-style Api refactor. Inlines the four
files under `web-actions/` (cookies / group-essence / group-honor /
group-notice) into `apis/web.ts::WebApi`. Both the `actions/` and
`web-actions/` directories are now empty and deleted from the tree.

Method renaming (Api namespace already says "web"):

  forceFetchClientKey   → forceFetchClientKey  (kept — unique name)
  getCookiesStr         → getCookiesStr        (kept — disambiguates from
                                                 the new public getCookies)
  getCsrfToken          → getCsrfToken
  getCredentials        → getCredentials
  getGroupEssence       → getEssence
  getGroupEssenceAll    → getEssenceAll
  getGroupHonorInfo     → getHonorInfo
  sendGroupNotice       → sendNotice
  getGroupNotice        → getNotice
  deleteGroupNotice     → deleteNotice

Plus a new public `getCookies(domain)` on WebApi so GroupAlbumApi can
reach the cookie-acquisition flow through `this.ctx.apis.web.getCookies`
rather than reaching into a private helper. Internal helpers
(`getPSkey` / `getSKey` / `getBknFromSKey`) remain file-private since
they're only used by the publicly-exposed methods above.

Cleanup performed in this same commit:

  • `actions/shared.ts` → moved to `apis/shared.ts` (only file left in
    actions/; it's a small helper module used by 4 Api classes).
  • `actions/` directory deleted entirely.
  • `web-actions/` directory deleted entirely.
  • `BridgeInterface` slimmed to `BridgeContext + activePid` (the only
    non-Api field OneBot consumers reach into). The 70-line list of
    method signatures is gone — every method type now comes from the
    `ApiHub` definition in `bridge-context.ts`.
  • `bridge.ts` no longer imports/wraps any action functions. Its
    public class is just the per-account state holder + `apis: ApiHub`.

Callers updated: `instance-context.ts`, `actions/extended.ts`,
`actions/group-info.ts`. Tests under `tests/web-actions/` deleted —
those tested file-private helpers (`getPSkey`/`getSKey`/`getBknFromSKey`)
that are no longer reachable from outside; the public WebApi surface
is exercised through OneBot integration tests in `extended-actions.test.ts`.

552/552 remaining tests pass. (Test count down 35 from the deleted
web-actions tests; production behaviour unchanged.)

This concludes the #6 refactor. The 12 Api hubs that the OneBot side
can reach via `bridge.apis.*`:

  message / contacts / groupAdmin / groupFile / groupAlbum
  interaction / friend / profile / forward / misc / extras / web
2026-05-20 23:49:48 +08:00
DrSmoothl
22add4ad1c refactor(api): move Tier-2 extras to ExtrasApi (#6 commit 11/13)
Inlines `actions/extras.ts` into `apis/extras.ts::ExtrasApi`. Covers
the napcat-parity Tier-2 surface: group todo CRUD (0xF90_1/2/3),
stranger online/ext status decode (0xFE1_2), and AI voice list +
synthesis (0x929D / 0x929B).

`StrangerStatus`, `AiVoiceChatType`, `AiVoiceCategory`, `AiVoiceItem`
are now exported from `apis/extras.ts` and re-exported through
`bridge.ts` for backwards compatibility (the OneBot side imports
them via `@snowluma/core`).

No renaming — the names already read cleanly under `apis.extras.X`.

The `fetchAiVoiceList` / `fetchAiVoice` chatType parameter is widened
to `AiVoiceChatType | number` because the OneBot side passes a raw
number from JSON. The wire encoder is happy with any integer; the
strict enum just gives autocompletion at call sites that have it.

Callers updated: `actions/extended.ts` (7 sites).
Tests rewritten:
  - `extras.test.ts` → uses `new ExtrasApi(bridge as any).method(...)`
    and the it.each dispatch switches to method-name strings.
  - `extended-actions.test.ts` APIS_ROUTING gains the extras block.

587/587 tests pass.
2026-05-20 23:40:57 +08:00
DrSmoothl
e5ac2a61b1 refactor(api): move 4 misc methods to MiscApi (#6 commit 10/13)
Inlines `actions/misc.ts` into `apis/misc.ts::MiscApi`. The Api holds
the methods that didn't naturally group into any other area:
translation, mini-app ARK card builder, inline-keyboard callback,
group sign-in.

No renaming — these names are already descriptive at the call site
under `apis.misc.X`.

Callers updated: `actions/extended.ts` (4 sites).
Tests rewritten to use `new MiscApi(bridge as any).method(...)`.

587/587 tests pass.
2026-05-20 23:35:37 +08:00
DrSmoothl
d953b9824c refactor(api): move 2 forward methods to ForwardApi (#6 commit 9/13)
Inlines `actions/forward.ts` into `apis/forward.ts::ForwardApi`. The
file is the largest unmoved one — 475 lines covering long-message
upload with NapCat-style piggyback for nested {type:"node"} chains,
plus the cached fetch side.

The module-scoped `forwardResCache` Map stays at file scope rather
than as an instance field. Forward res_ids are globally unique and
an outbound upload often gets queried back through `fetch` on a
different Bridge instance (different OneBot connection hitting the
same account) — NapCat's behaviour relies on the cache being shared
across the process.

Method renaming (Api namespace already says "forward"):

  uploadForwardNodes → upload
  fetchForwardNodes  → fetch

The private `uploadForwardNodesRecursive` becomes
`this.uploadRecursive(...)` — same body, threads through `this.ctx`.

Callers updated: `modules/message-actions.ts` (4 sites).
Tests rewritten:
  - `forward.test.ts` → `new ForwardApi(bridge as any).upload/fetch(...)`
  - `forward-file.test.ts` → same pattern
  - `forward-nested.test.ts` → mocks `apis.forward.upload` instead of
    flat `bridge.uploadForwardNodes`

587/587 tests pass.
2026-05-20 23:32:14 +08:00
DrSmoothl
62c5590fe1 refactor(api): move 10 profile methods to ProfileApi (#6 commit 8/13)
Inlines `actions/profile.ts` into `apis/profile.ts::ProfileApi`. The
file covers personal profile (nickname / long-nick / personal note),
online status (regular + DIY with custom face/wording), avatars
(personal + group via highway), input-status, likes (received from
others), unidirectional friend list, and custom face roaming.

Method renaming (Api namespace already says "profile"):

  getProfileLike → getLike    (only obvious shortening; rest keep
                               their `set*`/`fetch*` prefixes because
                               they're already minimal at the call
                               site under `apis.profile.X`)

Callers updated: `instance-context.ts`, `actions/group-admin.ts`,
`actions/extended.ts`. The extended-actions test gained a sizable
`APIS_ROUTING` block covering profile/interaction/friend (all of the
late-stage Api hubs need auto-promotion now), so legacy tests that
stub `setDiyOnlineStatus`/`setOnlineStatus`/`deleteFriend`/etc as flat
methods keep working.

Tests rewritten to use `new ProfileApi(bridge as any).method(...)`.

587/587 tests pass.
2026-05-20 23:26:35 +08:00
DrSmoothl
2ec72d59f9 refactor(api): move 3 friend methods to FriendApi (#6 commit 7/13)
Inlines `actions/friend.ts` into `apis/friend.ts::FriendApi`. The
roster READ side (fetchFriendList) stays on ContactsApi where it
naturally lives next to fetchGroupList — the friend/group rosters
share the same pipeline.

Method renaming (Api namespace already says "friend"):

  setFriendAddRequest → handleRequest    (accept/reject UID-or-flag)
  deleteFriend        → delete           (with cache refresh)
  setFriendRemark     → setRemark

`delete` still does the post-OIDB best-effort
`apis.contacts.fetchFriendList()` refresh to evict the stale entry.

Callers updated: `instance-context.ts`, `actions/extended.ts`.
Tests rewritten to use `new FriendApi(bridge as any).method(...)`.

587/587 tests pass.
2026-05-20 23:20:33 +08:00
DrSmoothl
73f1cd3c80 refactor(api): move interaction methods to InteractionApi (#6 commit 6/13)
Folds the entire `actions/interaction.ts` (sendPoke / sendLike /
setGroupReaction / getEmojiLikes) plus the lone-survivor
`setGroupEssence` from `actions/group-message.ts` into
`apis/interaction.ts::InteractionApi`. Both action files deleted —
the recall + markRead halves of group-message were already absorbed
into MessageApi back in commit 1.

Skipping the planned standalone GroupMessageApi commit: with only one
method left (`setGroupEssence`), giving it its own Api class would be
pure overhead. Essence is conceptually an "interaction" anyway (mark
a message as essence is parallel to "react with an emoji").

Method renaming (Api namespace already says "interaction"):

  sendPoke              → sendPoke     (no rename — already minimal)
  sendLike              → sendLike
  setGroupReaction      → setReaction
  setGroupEssence       → setEssence
  getEmojiLikes         → getEmojiLikes (no rename — read-side, fine)

Callers updated: `instance-context.ts`, `modules/message-actions.ts`,
`actions/extended.ts`. Tests `interaction.test.ts` rewritten to use
`new InteractionApi(bridge as any).method(...)` and gained a
`setEssence` test. `group-message.test.ts` rewritten to target
MessageApi.recall* / markRead* methods that were already moved.

587/587 tests pass.
2026-05-20 23:17:51 +08:00
DrSmoothl
c92daa56df refactor(api): move 6 group-album methods to GroupAlbumApi (#6 commit 5/13)
Inlines `actions/group-album.ts` (OIDB sendRawPacket via QunAlbum.trpc.*)
and `web-actions/group-album.ts` (HTTP cookie-based) into
`apis/group-album.ts::GroupAlbumApi`. Both action files deleted. Pure
HTTP helpers in `web/group-album.ts` stay where they are — they're
transport-layer code.

Method renaming follows the now-standard "drop the redundant suffix"
rule (the Api namespace already says `groupAlbum`):

  getGroupAlbumList         → list           (HTTP)
  uploadImageToGroupAlbum   → upload         (HTTP slice-upload)
  getGroupAlbumMediaList    → getMediaList
  commentGroupAlbumMedia    → comment
  likeGroupAlbumMedia       → like
  deleteGroupAlbumMedia     → delete

Callers updated: `instance-context.ts`. `web-actions/index.ts` no
longer re-exports the deleted album functions. No tests existed for
this surface area, so no test churn.

587/587 tests pass.
2026-05-20 23:12:53 +08:00
DrSmoothl
dad501ebc0 refactor(api): move 17 group-file methods to GroupFileApi (#6 commit 4/13)
Inlines `actions/group-file.ts` into `apis/group-file.ts::GroupFileApi`,
deletes the old action file, removes the matching 17 facade methods
off `Bridge`, and slims `BridgeInterface` accordingly.

Method renaming follows the same "strip the redundant suffix" rule we
applied to GroupAdminApi:

  uploadGroupFile           → upload
  uploadPrivateFile         → uploadPrivate
  sendGroupFileMessage      → publish        (OIDB 0x6d9_4)
  fetchGroupFiles           → list
  fetchGroupFileCount       → getCount
  fetchGroupFileUrl         → getUrl
  fetchPrivateFileUrl       → getPrivateUrl
  fetchGroupPttUrlByNode    → getPttUrl
  fetchPrivatePttUrlByNode  → getPrivatePttUrl
  fetchGroupVideoUrlByNode  → getVideoUrl
  fetchPrivateVideoUrlByNode → getPrivateVideoUrl
  deleteGroupFile           → delete
  moveGroupFile             → move
  createGroupFileFolder     → createFolder
  deleteGroupFileFolder     → deleteFolder
  renameGroupFileFolder     → renameFolder

`upload`'s atomic upload+publish flow now calls `this.publish(...)`
directly instead of going through `bridge.sendGroupFileMessage`, and
`uploadPrivate` calls `this.ctx.apis.message.sendC2cFile(...)`.

Callers updated: `instance-context.ts`, `media-url-resolver.ts`,
`actions/group-file.ts` (onebot), `actions/extended.ts`,
`modules/{contact,media,message}-actions.ts`.

Tests: `group-file.test.ts` rewritten to use
`new GroupFileApi(bridge as any).method(...)`. The "verify publish was
called" assertions now use `vi.spyOn(api, 'publish').mockResolvedValue()`
since `publish` is an instance method on the same Api. `_helpers.ts`
gains `mockGroupFileApi()` for cross-Api callers and drops the flat
`sendGroupFileMessage` shim. `media-url-resolver.test.ts` and
`send-group-file.test.ts` switched to `bridge.apis.groupFile.*`; the
extended-actions `APIS_ROUTING` map now carries a `[area, newName]`
tuple so renamed methods auto-promote.

587/587 tests pass. The network-manager file remains as the only
failing test file (pre-existing infrastructure issue unrelated to #6).
2026-05-20 23:08:50 +08:00
DrSmoothl
0b91e4db8d refactor(api): move 14 group-admin methods to GroupAdminApi (#6 commit 3/13)
Third of 13 commits. Folds the previous `actions/group-admin.ts`
plus the matching Bridge facade methods into a typed `apis.groupAdmin`
hub.

Methods (14, all renamed to drop the redundant `Group` prefix once
the `apis.groupAdmin` namespace makes it implicit):

  muteGroupMember     → apis.groupAdmin.muteMember
  muteGroupAll        → apis.groupAdmin.muteAll
  setGroupAddOption   → apis.groupAdmin.setAddOption
  setGroupSearch      → apis.groupAdmin.setSearch
  setGroupAddRequest  → apis.groupAdmin.setAddRequest
  kickGroupMember     → apis.groupAdmin.kickMember
  kickGroupMembers    → apis.groupAdmin.kickMembers
  leaveGroup          → apis.groupAdmin.leave
  setGroupAdmin       → apis.groupAdmin.setAdmin
  setGroupCard        → apis.groupAdmin.setCard
  setGroupName        → apis.groupAdmin.setName
  setGroupSpecialTitle→ apis.groupAdmin.setSpecialTitle
  setGroupRemark      → apis.groupAdmin.setRemark
  getGroupAtAllRemain → apis.groupAdmin.getAtAllRemain

actions/group-admin.ts deleted. The corresponding `*_` alias imports
and `async xxx() { return xxx_(this, …); }` delegate methods on
Bridge are gone.

Caller updates
--------------
* onebot/instance-context.ts — 6 sites (the multi-method binding for
  the OneBot action layer).
* onebot/actions/extended.ts — 8 sites including `getAtAllRemain`.
* onebot/actions/group-admin.ts — all 6 onebot action handlers.
* onebot/modules/request-actions.ts — `setGroupAddRequest`.

Test updates
------------
* tests/actions/group-admin.test.ts — was importing the deleted
  `* as admin` module and calling `admin.muteGroupMember(bridge, ...)`.
  Switched to `new GroupAdminApi(bridge as any).muteMember(...)` —
  same wire validation, just constructs the real Api class once per
  call (the Api is stateless so it's effectively free).
* tests/onebot/request-actions.test.ts — was stubbing
  `setGroupAddRequest` flat on bridge. Updated to
  `apis: { groupAdmin: { setAddRequest } } as any`.

Tests: 587/587 pass (network-manager native-addon failure unchanged).
2026-05-20 22:34:54 +08:00
DrSmoothl
6bf53890dc refactor(api): move contacts methods to ContactsApi (#6 commit 2/13)
Second of 13 commits decomposing Bridge. Moves the six "fetch the
roster / a profile / outstanding requests / download rkeys" methods
off Bridge and onto a new `apis.contacts.*`.

Methods moved
-------------
* fetchFriendList       — OIDB 0xfd4_1 + identity.rememberFriends
* fetchGroupList        — OIDB 0xfe5_2 + identity.rememberGroups
* fetchGroupMemberList  — OIDB 0xfe7_3 + identity.rememberGroupMembers
                          (includes the 60s TTL + per-group inflight
                          coalesce cache that prevents Tencent
                          risk-control from triggering)
* fetchUserProfile      — OIDB 0xfe1_2 + identity.rememberUserProfile
* fetchGroupRequests    — OIDB 0x10c0_{1,2}
* fetchDownloadRKeys    — OIDB 0x9067_202

Cache fields moved
------------------
The two member-list throttle maps (`memberListInflight_`,
`memberListLastFetch_`) move from Bridge to `ContactsApi` as private
fields. Same TTL, same semantics — just owned by the Api class that
exposes the method.

Constructor ordering
--------------------
`buildApiHub(this)` now runs BEFORE `identity.setFetcher(...)` in the
Bridge constructor because the `fetchProfile` / `fetchGroupMemberList`
callbacks installed there reach into `this.apis.contacts.*`. With
eager construction this is safe; the alternative (pass a thunk that
forwards once apis is built) was strictly worse for readability.

bridge-contacts.ts removed
--------------------------
The file existed solely as the previous module-function delegate
target; ContactsApi inlines every function body so there's nothing
left to keep.

Caller-site updates
-------------------
* `bridge/actions/friend.ts` — `bridge.fetchFriendList()` →
  `bridge.apis.contacts.fetchFriendList()`.
* `onebot/manager.ts`, `onebot/instance-rkey.ts`,
  `onebot/modules/contact-actions.ts`, `modules/request-actions.ts`,
  `actions/extended.ts` — same shape rewrite (6 method names).

Test plumbing
-------------
* `tests/actions/_helpers.ts` — `mockApiHub()` grows a `contacts`
  field built by `mockContactsApi()`.
* `tests/bridge-member-identity.test.ts::RefreshingBridge` — was
  `override async fetchGroupMemberList()`. After the move the method
  lives on `this.apis.contacts`, not `this`. Switched to patching the
  method on the constructed ContactsApi instance directly.
* `tests/actions/friend.test.ts` — `bridge.fetchFriendList` →
  `bridge.apis.contacts.fetchFriendList`; the "refresh throws" branch
  overrides via `bridge.apis.contacts.fetchFriendList = vi.fn(…)`.
* `tests/onebot/contact-actions.test.ts`, `extended-actions.test.ts`,
  `request-actions.test.ts` — local `fakeBridge` helpers gained an
  auto-promotion shim that rewrites flat method stubs (the pre-#6
  test API) into the new `apis.<area>.method` shape. Keeps existing
  test setup readable while the production code uses the new path.

Tests: 587/587 pass (same baseline; pre-existing network-manager
native-addon failure unchanged).
2026-05-20 22:27:32 +08:00
DrSmoothl
3e5dca1bd4 refactor(api): introduce MessageApi + BridgeContext + ApiHub skeleton (#6 commit 1/13)
First of 13 commits decomposing the Bridge god-object into typed Api
classes following NapCat's `ctx.apis.XxxApi.method()` pattern. This
commit lays the foundation (BridgeContext, ApiHub, eager construction)
plus moves the message-send/recall/mark-read methods onto MessageApi.
Subsequent commits will move the other 12 areas (group admin, files,
profile, …) similarly.

Architecture
------------
* `bridge-context.ts` — new interface, the surface Api classes see.
  Carries identity / events / apis / sendRawPacket / resolveUserUid /
  next{Message,Client}Sequence helpers / upload meta cache. Replaces
  the previous `BridgeInterface` for Api-class consumption (the
  legacy interface still exists, just slimmed; full removal happens
  in commit 13).

* `apis/index.ts` — `ApiHub` interface + `buildApiHub(ctx)` factory.
  Each commit grows `ApiHub` by one entry; today only `message` is
  populated.

* `apis/message.ts` — `MessageApi` with seven methods inlined from
  the previous Bridge implementation:
    sendGroup        ← Bridge.sendGroupMessage
    sendPrivate      ← Bridge.sendPrivateMessage
    sendC2cFile      ← Bridge.sendC2cFileMessage
    recallGroup      ← actions/group-message.ts::recallGroupMessage
    recallPrivate    ← actions/group-message.ts::recallPrivateMessage
    markGroupRead    ← actions/group-message.ts::markGroupMessageRead
    markPrivateRead  ← actions/group-message.ts::markPrivateMessageRead
  (Names trimmed: the `apis.message` prefix already signals the
  context, so `apis.message.sendGroupMessage` would be redundant.)

Bridge changes
--------------
* Removed the 7 methods listed above (moved to MessageApi).
* Removed unused imports + `SEND_MSG_CMD` constant + `buildSendElems`
  + `protobuf_encode/decode` (now used only inside MessageApi).
* Added `readonly apis: ApiHub` field, built eagerly in constructor.
* Promoted `nextMessageRandom` / `nextClientSequence` from private →
  public (Api classes need them to build SendMessageRequest packets).
* `BridgeInterface` now also lists `apis: ApiHub` + the two
  generators; the 7 deleted method signatures are gone.

Caller-site updates (~9 files)
------------------------------
* `bridge/actions/group-file.ts` — `bridge.sendC2cFileMessage(...)`
  → `bridge.apis.message.sendC2cFile(...)`.
* `onebot/instance-context.ts` — markGroupMsgAsRead / markPrivateMsgAsRead
  bindings now route through `apis.message.markGroup/PrivateRead`.
* `onebot/modules/message-actions.ts` — every send/recall site
  rerouted; `typeof ref.bridge.sendXxx` type refs also updated.
* `onebot/actions/extended.ts` — same.

Tests (~5 files)
----------------
* `tests/actions/_helpers.ts` — `mockBridge()` grows an `apis` field
  built by `mockApiHub()`; the previous flat `sendGroupMessage` etc.
  vi.fn stubs are replaced with `mockMessageApi()`.
* All test files using direct `bridge.sendXxx` / `bridge.recallXxx` /
  `bridge.markXxxAsRead` calls or stubs updated to `bridge.apis.message.*`.
* No behaviour changes — 587/587 pass (same baseline; pre-existing
  network-manager native-addon failure unchanged).
2026-05-20 22:17:47 +08:00
DrSmoothl
9a678442e9 fix(msg): unswap markRead import aliases in Bridge
The `markGroupMsgAsRead` / `markPrivateMsgAsRead` Bridge methods were
calling the wrong underlying implementations because the alias names
on the import line were swapped:

  - `markPrivateMessageRead as markGroupMsgAsRead_` meant calling
    `bridge.markGroupMsgAsRead(groupId, …)` actually fired the c2c
    (private) read-report wire shape with `groupId` shoved into the
    `userId` slot — the server then resolved a uid for what was
    really a groupId and posted to the wrong route.

  - `markGroupMessageRead as markPrivateMsgAsRead_` was the mirror:
    `bridge.markPrivateMsgAsRead(userId, …)` fired the group read-
    report shape with `userId` in the `groupUin` field.

Realigned to the intended pairing. The underlying implementations
in `actions/group-message.ts` are already covered by
`tests/actions/group-message.test.ts` (asserts both hit
`SsoReadedReport` with their proper wire shapes); they pass
unchanged because they always tested the action-layer functions
directly, never the Bridge facade where the swap lived.

Caught while planning the #6 Api-on-ctx refactor — preserving the
swap into the new MessageApi would have carried the bug forward.
2026-05-20 22:08:38 +08:00
DrSmoothl
6c7e56d5a1 refactor(proto-defs): extract wire-protobuf definitions into standalone package
Move `packages/core/src/bridge/proto/proton/*.ts` (13 files, ~3.3k
LOC) into a new `@snowluma/proto-defs` workspace package. The proton
spike landed in the previous commit means bare-specifier imports
(`@snowluma/proto-defs/oidb`, `…/message`, …) now resolve correctly
through proton's vite plugin, so call-site replacement still fires.

Why
---
- Lets downstream consumers share the same wire
  definitions without copy-pasting them — multiple workspace packages
  can now depend on `@snowluma/proto-defs` directly.
- Trims `@snowluma/core`'s surface: the bridge no longer owns the
  protocol schema, only its consumers.
- Sets up future #5 (`message-parsing perf`) and #6 (`Api-on-ctx
  refactor`) — both want a thinner core.

Layout
------
Per-file subpath exports (mirrors the legacy `proto/proton/<sub>`
shape 1:1). The barrel `index.ts` intentionally skips `highway` and
`oidb-actions/media` because the two files share six NTV2-prefixed
type names — `export *` would silently drop one side. Subpath imports
are unambiguous, which is also why every call site in core uses them.

Changes
-------
- New package `packages/proto-defs/` (package.json, tsconfig.json,
  src/index.ts).
- 13 `.ts` files moved via `git mv` to preserve history.
- 44 import sites across 26 source files + 15 tests rewritten via sed
  from `./[…/]proto/proton/<sub>` → `@snowluma/proto-defs/<sub>`.
- `@snowluma/core` depends on `@snowluma/proto-defs` (workspace:*).

Verification
------------
- proto-defs typecheck: clean
- core typecheck: clean
- core test suite: 587 passed (same baseline as before the refactor;
  one failure is the pre-existing websocket native addon, unrelated)
- proton test suite: 99 passed (8 files including the new
  cross-package.test.ts from the spike)
- Full workspace `pnpm -r typecheck`: all 8 projects clean

Note: proton's `dist/index.js` MUST be rebuilt for the vite plugin to
pick up the bare-specifier resolution. The previous commit's source
change is only effective after `pnpm -F @snowluma/proton build`.
2026-05-20 21:31:30 +08:00
DrSmoothl
994633eafa feat(proton): resolve bare specifiers via TypeScript module resolution
`resolveModulePath` used to skip any specifier not starting with '.'
which meant proton's vite plugin only saw proto definitions that lived
in the same package as the call site. Trying to move definitions into
a sibling workspace package (e.g. `@snowluma/proto-defs`) caused those
imports to silently fail — the call-site type lookup found nothing
and the protobuf_encode<T> replacement never fired.

Add a bare-specifier branch that delegates to `ts.resolveModuleName`
with `moduleResolution: Bundler`. That covers monorepo workspaces,
npm packages, package.json `exports`, and tsconfig path aliases with
zero extra user configuration.

The relative-path branch is preserved byte-for-byte so existing
single-package consumers see identical behaviour. Resolution is
constrained to `.ts` source files (not `.d.ts`) because proton walks
interface AST to collect `pb<>` field tags, and generated declaration
files typically strip those generic arguments.

Per-process `ModuleResolutionCache` keeps the hot path (HMR rebuild)
from re-scanning node_modules every call.

Tests: new `cross-package.test.ts` builds a fake monorepo under
`os.tmpdir()` and exercises smoke / transform / round-trip / negative
paths. 99/99 proton tests pass; SnowLuma core regression unchanged
(587 baseline ⇄ 587 with change).
2026-05-20 21:22:48 +08:00
手瓜一十雪
fe00774191 Remove obsolete comment about receiverUid
Delete an outdated comment block in fetchPrivateFileUrl that described receiverUid behavior (Lagrange.Core/NapCat and NTQQ fulllink timeout). No functional code changes were made aside from removing the explanatory comment; the surrounding logic (resolveSelfUid, void userId, and OIDB envelope creation) remains unchanged.
2026-05-20 19:47:25 +08:00
手瓜一十雪
0464d6439f RoadMap: add Proton fallback approach for debug
Update the debug optimization item to specify a Proton fallback plan: implement unpackaged debug with correct data directory and use TypeScript + map-based type extraction for tsx and Node.js, which will be stripped during normal Vite builds.
2026-05-20 19:46:32 +08:00
手瓜一十雪
db412ad498 更新 RoadMap:拆分 core 与优化计划
在 RoadMap.md 中新增多项 v2.0.0 前计划:拆分 core 为 Common/OneBot/Core/Bridge、将 ProtocolBuffer 定义剥离到独立包、整理消息发送与解析链路以提升性能,并对齐 NapCat 设计(在 ctx 上挂载 Api 层)。这些条目明确了架构重构与性能优化的方向。
2026-05-20 19:43:33 +08:00
手瓜一十雪
b56868878c Refactor bridge modules: imports & cleanup
Standardize and reorganize imports, type usages and minor formatting across the bridge modules. This commit moves protobuf helpers, makeOidbEnvelope/runOidb, OidbBase and logger imports into consistent places, reorders and groups action/contacts exports in Bridge, removes or trims file-level comments, and fixes whitespace/logic ordering in several highway, element-builder and msg-push files. These are refactors and import/type adjustments across many files under packages/core/src (bridge, highway, msg-push, webui, utils, etc.) with no intended behavioral changes.
2026-05-20 19:35:09 +08:00
手瓜一十雪
c49ae1c8d9 Remove actions list and update SDK exports
Delete the obsolete actions.ts (SNOWLUMA_ACTIONS / isSnowLumaAction) and update package SDK top-level exports. index.ts was refactored to reorganize and expose additional helpers and types (createSnowLumaApiError, createEventContext, event/type guards, request/notice helpers, fromCQString, MessageChain, SnowLumaHttpClientOptions, etc.), remove duplicate/unused re-exports, and streamline message/client/error exports for consumers.
2026-05-20 19:23:22 +08:00
手瓜一十雪
36c3ed031b Apply formatting and fix web request utilities
Add consistent indent rule to ESLint and normalize formatting/indentation across multiple files. Refactor RequestUtil: improve cookie extraction, redirect handling, and HttpGetJson/HttpGetText request flow; fix cookie string builder formatting. Fix uploadGroupNoticeImage promise/error handling and network request flow. Also apply minor style/refactor tweaks in bridge web APIs, onebot handlers, message-store SQL alignment, and Proton AST collector utilities to improve readability and correctness.
2026-05-20 19:16:06 +08:00
手瓜一十雪
aea2676c31 Add TypeScript ESLint configs and lint scripts
Add a repository .editorconfig and a root eslint.config.ts to standardize formatting and linting. Migrate packages/webui ESLint config to TypeScript (eslint.config.ts) with project-specific rules and tsconfigRootDir handling, and remove the old JS config. Update package.json to run ESLint directly (add lint and lint:fix) and add required ESLint/dev dependencies; also add jiti to packages/webui/package.json. Include a small formatting tweak to tsconfig.base.json.
2026-05-20 19:08:45 +08:00
手瓜一十雪
f21740a5d3 Support types re-exported via export *
Add support for resolving types re-exported with `export * from '...'`. Introduces extractExportAllSpecifiers and a new exportAllTypeSources map on ParsedFileEntry, populates it while parsing (recursively following export-all chains using the cache and an inProgress set to avoid cycles), and falls back to exportAllTypeSources when resolving imported type names. This allows types and generic templates exported through export-all declarations to be discovered and resolved.
2026-05-20 18:37:58 +08:00
手瓜一十雪
5ea1c3a961 Remove bridge proto schemas and parity test
Delete proto schema modules under packages/core/src/bridge/proto (action.ts, element.ts, highway.ts, longmsg.ts, message.ts, notify.ts, oidb-action.ts, oidb.ts) and the related test packages/core/tests/proton-parity.test.ts. These files contained protobuf schema definitions for the bridge layer; remove them as part of a cleanup/refactor. Update any imports or references to these modules to their new locations or replacements.
2026-05-20 18:23:03 +08:00
手瓜一十雪
02bab710b8 Add protobuf_decode import to interaction actions
Import protobuf_decode from @snowluma/proton in packages/core/src/bridge/actions/interaction.ts to enable decoding of protobuf messages within interaction-related bridge actions. No other changes to logic in this diff.
2026-05-20 18:04:19 +08:00
手瓜一十雪
bf4c130641 Use protobuf_encode for OIDB envelopes
Replace the encodeOidbEnv wrapper with direct protobuf_encode<OidbBase<T>> calls across bridge modules. Updated many bridge action files (extras, friend, group-admin, group-file, group-message, interaction, misc, profile, bridge-contacts, highway pipeline, etc.) to import protobuf_encode and OidbBase and to pass encoded OIDB envelopes via protobuf_encode. Removed the encodeOidbEnv implementation from bridge-oidb and restructured proton OIDB definitions by adding new proto/proton/oidb-actions modules (base, group-album, group-file, media, index) and adjusting proton proto usage. This centralizes envelope encoding for better monomorphization and simplifies the OIDB encoding flow.
2026-05-20 18:03:57 +08:00
手瓜一十雪
ca0a888003 Clarify proton proto schemas and comments
Refine and clarify inline documentation across proton schema files (action.ts, element.ts, highway.ts, longmsg.ts, message.ts, notify.ts). Replaces verbose legacy preambles with concise comments, adds concrete notes about server expectations (e.g. Trans0x211 routing for C2C files, required NotOnlineFile fields on send, NTV2 upload extBizInfo video scene fields), and documents GroupFileExtra/GroupFileInfo field alignment and magic tags to explain past send/receive failures. Changes are purely comment and schema documentation updates to improve maintainability and explain interoperability pitfalls with the server; no runtime API/signature changes were introduced.
2026-05-20 17:48:13 +08:00
手瓜一十雪
3cd3155d1a Simplify comments and section headers in oidb.ts
Remove long legacy/explanatory comment blocks and ASCII-art dividers, replacing them with shorter, consistent section headers (e.g. "Oidb.0xFD4_1 Friend list", "Oidb.0xFE5_2 Group list"). Trim redundant commentary about OidbBase/OidbBaseMeta while keeping all type/interface definitions unchanged. This cleans up the file for readability without altering the public types or runtime behavior.
2026-05-20 17:37:02 +08:00
手瓜一十雪
4b217eb4b8 Use self UID and add OIDB timeout
fetchPrivateFileUrl now uses the current account UID (resolveSelfUid) as receiverUid instead of resolving the peer UID, matching Lagrange.Core/NapCat behavior and avoiding NTQQ fulllink handler timeouts. The userId parameter is intentionally unused. runOidb gained an optional timeoutMs argument and the private-file request uses a 5000ms timeout; bridge.sendRawPacket is forwarded this timeout.
2026-05-20 17:26:39 +08:00
DrSmoothl
2de1ff4f0d chore(release): v1.9.0 2026-05-20 14:21:03 +08:00
DrSmoothl
5d83aedd83 fix(typecheck): narrow ctx explicitly and type buildSendElems mock params
CI tsc flagged two strict-mode issues in d1aade6:

  * element-builder: `ctx?.forwardFake` doesn't carry the non-null
    narrowing to a subsequent `ctx.groupId` access — replace with an
    explicit `ctx && ctx.forwardFake` guard.
  * forward-file.test: `vi.fn(async () => [])` infers `mock.calls`
    as `[][]`, so `const [, ctx] = mock.calls[0]!` is "Tuple of length
    '0' has no element at index '1'". Declare the mock's parameter
    types (`unknown[], Record<string, unknown>?`) so the call tuple
    has the right arity, and use `ctx?.groupId` since the ctx slot
    is now typed as optional.
2026-05-20 14:07:36 +08:00
DrSmoothl
d1aade6f87 fix(forward): keep file segments in long-msg payload via forwardFake flag
Previous fix split file segments off at the OneBot live-send layer
(c2c → sendC2cFileMessage, group → sendGroupFileMessage) and made
element-builder drop any `{type:'file'}` segment that reached it.
That broke forward messages: send_forward_msg encodes each node
through buildSendElems for the long-msg upload, so file segments
inside a forward node hit the drop-with-warn path and the forward
bubble shipped without the file.

Forward upload is NOT a live PbSendMsg — it stores the gzipped
protobuf verbatim through `trpc.group.long_msg_interface.MsgService.
SsoSendLongMsg`, and the recipient decodes file entities through the
normal msg-push path (transElem(24) → GroupFileExtra; msgContent →
FileExtra { file: NotOnlineFile }). So `result=79` doesn't apply here.

Add a `forwardFake?: true` flag on SendContext; when set:
  * group file → element-builder emits transElem(24) again (restored
    makeGroupFileElem, exactly the receive-side wire shape).
  * c2c file → element-builder still skips; forward-builder pulls the
    segment off the node and writes `body.msgContent` as
    FileExtra { file: NotOnlineFile }, with file metadata hydrated
    from the upload cache when inline fields are missing (same
    pattern as send_private_msg).

Mirrors NapCat's PacketMsgFileElement.{buildElement,buildContent}
split (dev/napcatQQ/.../packet/message/element.ts:530-610) and
Lagrange.Core V2's MultiMsgUploadService.cs.
2026-05-20 13:56:31 +08:00
DrSmoothl
cc574632f1 fix(test): declare vi.fn param types so mock.calls[0] infers tuple
`vi.fn(async () => undefined)` infers `mock.calls: [][]`, so
destructuring `const [groupId, fileId] = ...mock.calls[0]!` fails
under TS strict tuple checks (`error TS2493: Tuple type '[]' of
length '0' has no element at index '0'`). Declare the param types
inline so the call-args tuple is `[number, string]`.
2026-05-20 13:32:35 +08:00
DrSmoothl
c83c333e73 fix(file): route group publish through OIDB 0x6d9_4 and cache upload meta for c2c resend
The chat-publish step after upload_group_file used to ship a PbSendMsg
with a transElem(elemType=24) — but that wire shape is RECEIVE-side
only, and current QQ-NT rejects it on send with `result=79`. Lagrange.
Core V2 uses a dedicated `OidbSvcTrpcTcp.0x6d9_4` for the publish
(`GroupSendFileService.cs`); mirror that. Send_group_msg with a
`{type:'file', file_id}` segment now routes through the same path
after the OneBot layer splits file segments out (matching the c2c
file split pattern).

Separately, send_private_msg with just `{file_id}` was shipping a 0 B
file because the wire packet for c2c file send needs fileSize/fileMd5/
fileName/fileHash but the OneBot caller only echoes the file_id from
upload_private_file. Add a bounded (1024-entry, FIFO) bridge cache
populated at upload time so the send-message path can rehydrate the
full tuple; inline segment fields still take precedence so callers
that track the metadata themselves can bypass the cache. Parser now
also accepts `file_hash`/`fileHash` on file segments.

Also: file segments no longer get a `[空消息]` log line — the format
string now shows `[文件:<name-or-id>]`.
2026-05-20 13:30:13 +08:00
手瓜一十雪
6de2e071be Forward image sub_type and summary fields
Include optional element.subType and element.summary in the image segment payload (mapped to sub_type and summary) so custom emoji/sticker metadata is preserved. Adds a unit test to verify these fields are forwarded.
2026-05-20 10:52:43 +08:00
H3CoF6
312df29b5f feat: 添加注入前探测 QQ 登录状态功能 (#56)
通过扫描 QQ 进程开放的 9210-9219 端口,在注入 DLL 前即可获取登录状态和账号信息。

- 新增端口探测模块 (qq-port-probe.ts)
- 前端添加"探测登录"按钮和状态显示对话框
- 兼容 Windows 和 Linux 平台
- 修复端口查询逻辑,正确识别每个 PID 开放的端口

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 10:29:41 +08:00
DrSmoothl
1db287d8cc fix(c2c-file): rewrite sendC2cFileMessage wire shape per Lagrange.Core V2
The c2c file send path was wrong on three independent axes — every
c2c file the bot tried to deliver was getting rejected by the QQ-NT
server. Aligned to `dev/Lagrange.Core` (V2 branch) which is the only
direct-protocol reference for c2c files; NapCat goes through QQ-NT
IPC and never builds this packet itself.

Three wire-shape fixes:

1. **Routing**: `routingHead.c2c { uin, uid }` → `routingHead.trans0x211
   { ccCmd: 4, uid }`. RoutingHead field 15 is the c2c-file scene's
   slot. `MessagePacker.BuildPacketBase` makes this conditional on
   `chain.HasTypeOf<FileEntity>()`: when a file is present, C2C goes
   nil and Trans0X211 carries the routing.

2. **File payload location**: `messageBody.richText.notOnlineFile {...}`
   → `messageBody.msgContent = serialize(FileExtra{file: NotOnlineFile})`.
   The server doesn't read c2c file metadata from `richText` at all —
   `MessageBody.cs:12` even has the comment "Offline file is now put
   here(?". Confirmed by `FileEntity.PackElement()` returning empty
   and `PackMessageContent()` returning the FileExtra wrapper.

3. **contentHead.c2cCmd**: `11` → `0` (default/omitted). `11` was a
   stale go-cqhttp value the QQ-NT server doesn't recognise on the
   c2c-file dispatcher. Lagrange leaves it at the C# default (0).

Schema fixes (proton + legacy, both directions):

- `RoutingHead` gains `trans0x211?: pb<15, RoutingTrans0x211>`. The
  new message has `toUin@1`, `ccCmd@2`, `uid@8`.
- `SendMessageBody` gains `msgContent?: pb<2, bytes>` (the receive-side
  `MessageBody` already had it).
- `FileExtraInfo` deleted — was wrong on every tag (fileSize=1,
  fileName=2, fileMd5=3, fileUuid=4, fileHash=5, none of which match
  the wire). `FileExtra { file: pb<1, NotOnlineFile> }` now wraps the
  same `NotOnlineFile` used on the receive path. This is why c2c file
  PUSHES were also silently failing the four-field truthy check in
  `extractMsgContent` — the schema couldn't decode anything.
- `NotOnlineFile` gains the three intake-validator fields the server
  requires on send: `subcmd@9 = 1`, `dangerEvel@50 = 0`, `expireTime@55`
  = now+7d.

Receive side (`rich-body-decoder.ts::extractMsgContent`): drop the
"all four fields must be truthy" guard (it was a workaround for the
broken schema) and accept any payload that decodes a fileUuid.

Tests:

- `bridge-private-routing.test.ts`: new regression that round-trips
  `sendC2cFileMessage` through `protoDecode` and asserts trans0x211
  routing, msgContent FileExtra wrapper, NotOnlineFile field tags,
  c2cCmd=0. Catches each of the three wire-shape regressions
  independently.
- `send-private-c2c-file.test.ts`: vi.fn arg signatures explicit for
  CI typecheck.

647/647 tests pass.
2026-05-19 23:45:40 +08:00
DrSmoothl
f65fe959bb fix(send-private): split c2c file segments out to sendC2cFileMessage (was shipping "[空消息]")
User report: `send_private_msg` with a `{type:'file', file_id}` segment
fired `[ElemBuilder] file send via elems[] is group-only; use bridge.
sendC2cFileMessage for c2c` and the message went out as "[空消息]".

Root cause: c2c files live on `RichText.notOnlineFile` (parallel to the
elems array, see proto/proton/message.ts), not inside `elems[]`. The
element-builder explicitly drops c2c `{type:'file'}` elements with a
warning. `sendPrivateMessage` was passing the file straight to
`bridge.sendPrivateMessage(userId, [fileElement])` which then ran
through `buildSendElems`, lost the file at the drop, and shipped a
0-element wire send — rendered as "[空消息]" by every receiver.

Fix: split at the OneBot layer in `sendPrivateMessage`. Pull file
elements out of the batch and dispatch each via
`bridge.sendC2cFileMessage`; route the rest through the regular
elems[] path. Matches NapCat's `dev/NapCatQQ/.../SendMsg.ts:404-415`
where FILE / VIDEO / ARK / PTT each get their own sendMsg call and
never mix with the regular elems[] batch.

- File-only message: only the c2c file API is called (single roundtrip)
- Mixed text + file: two sends, text first then file
- File without file_id: dropped with a warn (was silently shipping
  empty messages)
- UID resolution failure: surfaced as throw instead of empty send

Also rewrote the element-builder fallback warn from "use
sendC2cFileMessage for c2c" (now stale advice) to "BUG: c2c file
reached element-builder — should be split out at the OneBot layer".

Tests: 4 new regression cases under
`tests/onebot/send-private-c2c-file.test.ts`. 646/646 pass.
2026-05-19 23:36:12 +08:00
DrSmoothl
cec38b4c1b fix(forward): piggyback every nested level onto the outermost long-msg upload (NapCat model)
Cross-referenced `dev/NapCatQQ/.../SendMsg.uploadForwardedNodesPacket`
(208-347): every layer of a nested forward attaches its own msgBody to
the *outer* long-msg upload under a uuid `actionCommand` slot. Receiver
walks the whole tree from one server fetch instead of resolving each
layer's res_id separately.

`dev/Lagrange.Core` (V2 branch on `linwenxuan04/v2`,
`MultiMsgUploadService.cs:23-31`) only writes a single MultiMsg action
— that's why NapCat-style receivers couldn't follow our previous
nested-forward sends past the first level.

Refactor:

1. `ForwardNodePayload` gets an optional `innerForward?:
   ForwardNodePayload[]` field. `parseForwardNodes` no longer eagerly
   uploads inner chains — it just attaches them here.

2. `uploadForwardNodes` now drives the whole recursion. The new
   `uploadForwardNodesRecursive`:
   - walks each node, recursively uploads any `innerForward` first
   - replaces that node's `elements` with a real `{type:'forward'}`
     preview pointing at the inner res_id
   - piggybacks the inner level's `{uuid, msgBody}` + every deeper
     level it surfaced into this level's `myInnerActions`
   - encodes the long-msg payload as
     `[{MultiMsg, ownMsgBody}, ...innerActions.map(uuid+msgBody)]`
   - returns `{resId, msgBody, uuid, innerActions}` so an outer call
     can keep climbing

   Top-level public signature unchanged: `Promise<string>`.

3. New `deriveInnerSource` / `previewLinesFromNodes` /
   `previewFromElements` helpers synthesise the ARK preview metadata
   the inner bubble shows before the user taps to expand. They handle
   text/image/record/video/file/forward/face element previews.

4. `parseForwardNodes`: when `content` is an all-node array, attach
   the parsed inner chain to `node.innerForward` and let the upload
   pipeline take over. `elements = []` placeholder is replaced by
   `uploadForwardNodes` once it has the real res_id.

Tests:

- `actions/forward.test.ts`:
  - `uploadForwardNodes recursively uploads nested innerForward chains
    (NapCat piggyback model)` — asserts two SsoSendLongMsg roundtrips
    (inner first, then outer) and the outer res_id propagates up
  - `flat sends still take a single roundtrip` — backwards-compat

- `onebot/forward-nested.test.ts`: rewritten — mock now sees exactly
  one `uploadForwardNodes` call with `innerForward` attached, instead
  of two sequential calls; depth-limit + mixed-content tests
  unchanged.
2026-05-19 23:29:59 +08:00
DrSmoothl
0b8dc1f7af fix(video): populate NTV2 fileInfo.time with the real duration (receiver was rendering 00:00)
The NTV2 upload request for video carried `time: 0` on the main mp4
sub-file, mirroring NapCat's transformer. But NapCat lives on top of
the desktop QQ-NT client's IPC layer, which patches the duration into
the resulting MsgInfo before the wire send — we don't have that layer,
so the `time: 0` we passed in ended up baked into the `VideoFile.
fileTime` field of every video the bot sent. Receivers then rendered
every video bubble as "00:00".

Cross-checked acidify's `RichMediaUpload.kt::buildVideoUploadInfoList`
(2026-04 refactor) — they're a protocol-direct client too and write
`time = payload.videoDuration` for exactly this reason. We already
have `video.duration` from `loadVideo` (probed via ffprobe), so it's
a one-liner.

Width/height kept at 0 deliberately — acidify fills them, NapCat
zeros them, and our earlier comment recorded "QQ NT server treats
non-zero values here as schema mismatch on c2c sends". Out of scope
for this fix; revisit if a c2c regression surfaces.

Test asserts `fileInfo.time === 10` for the main sub-file (matches
FINGERPRINT.duration) and stays 0 on the thumb.
2026-05-19 22:20:38 +08:00
DrSmoothl
8f839f4f30 fix(group-file): correct GroupFileExtra wire shape — server was rejecting with result=79
Two off-by-one bugs in the group-file chat-post element that combined
to make the QQ-NT server reject every group file send with result=79
(visible as "group file uploaded but chat post failed" in the logs):

1. Inner GroupFileInfo fields were shifted one tag left:
   - fileSha    was field 5, should be field 6
   - extInfo    was field 6, should be field 7
   - fileMd5    was field 7, should be field 8
   Field 5 is actually a uint32 placeholder (`field5` in both NapCat
   and acidify). With the bug, our fileSha bytes were landing where
   the server expected a varint and the rest of the message got
   skipped as garbage.

2. Outer GroupFileExtra was missing the magic field1=6 + fileName
   slots that NapCat's encoder writes
   (`packet/message/element.ts:589`). Acidify's schema also models
   them as required even though it serialises with defaults. The
   current server build rejects sends without these slots populated.

Cross-referenced:
- NapCat `GroupFileExtraInfo` (component.ts:146-155) — matches our
  new field numbers exactly
- acidify `GroupFileExtra.Inner.Info` (proto/message/extra/GroupFileExtra.kt)
  — same field numbers; their schema uses generic `field5`/`field7`
  names but the wire layout is identical

Changes:
- Proton + legacy schemas: shift inner fields, add outer field1/
  fileName/display
- `makeGroupFileElem`: write field1=6 + fileName on the outer wrapper
- Regression test asserts each inner tag lands at 50/58/66 (not the
  old 42/50/58) and verifies the new outer field1 + fileName bytes
  are present
2026-05-19 21:51:35 +08:00
DrSmoothl
04a905460b fix(file-upload): read upload host from rtpMediaPlatformUploadAddress (NT 2026 rollout)
The 2026 QQ-NT server has stopped populating *every* legacy host field
(uploadIp / uploadDomain / uploadIpList / uploadHttpsDomain / uploadDns).
The host now arrives in the new field 210 `rtpMediaPlatformUploadAddress`
— a repeated `IPv4` message carrying `inIP`/`inPort` (LAN) and
`outIP`/`outPort` (WAN). Coworker's debugging hint "host 好像是 fix64"
was the 8-12-byte length-delimited IPv4 message looking like a
fixed-width field on the wire.

Cross-referenced acidify (https://github.com/LagrangeDev/acidify) —
the only NT-protocol fork that's tracked this change (refactored in
their 2026-04 protobuf rewrite). They read `inIP`+`inPort` exclusively
because that's the address the highway PUT actually needs to reach
(same DC as the OIDB endpoint). LagrangeGo / Lagrange.Core / NapCat
still ship the old schema and would fail the same way against this
server build.

Changes:
- Proton schema: add `IPv4` message (fields 1-5: outIP/outPort/inIP/
  inPort/iPType, all int32 varint) + field 210 on the upload response
- Consumer: prefer `rtpMediaPlatformUploadAddress[0].inIP`+`inPort`
  before falling back through the legacy host chain
- New helper `int32ToIpv4Dotted` reverses acidify's `Int.toIpString()`
  (little-endian byte order, `>>>` for unsigned shift so high-bit IPs
  don't render as negative octets)
- Diagnostic warn-log now dumps the rtp address array too
- Regression test: 192.168.1.1 (LE-packed 0x0101A8C0 = 16885952) +
  inPort=8080 should reach highway PUT
2026-05-19 21:45:40 +08:00
DrSmoothl
3c65df668c fix(msg-push): silently acknowledge Event0x210 subType=380 (unmapped client state)
Surveyed Lagrange.Core (PushMessageService.cs), LagrangeGo
(client/listener.go), lagrange-python (server_push/msg.py), mania
(push_msg.rs), and the tsuzcx/qq_apk decompile — zero handlers for
380 / 0x17C across the lot. Pattern matches subType=38 (also a
QQ-client-internal state push with no OneBot mapping); drop it
through the same silent-acknowledge path so we stop spamming
`MsgPush.Unknown` at debug level on every push.
2026-05-19 21:25:41 +08:00
DrSmoothl
87ac6ffedb fix(file-upload): fall back through parallel host fields when uploadIp is empty
User report: `upload_private_file` was failing with "private file upload
host is invalid" on a fresh upload (boolFileExist=false). The OIDB call
succeeded but `uploadIp` (field 60) came back empty, and we treated
that single field as the only source of truth.

Cross-referenced LagrangeGo's `OidbSvcTrpcTcp0xE37_800.proto` + NapCat's
`Oidb.0XE37_800.ts`: the server has six parallel host slots on this
response (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain
/ uploadDns / uploadLanip). LagrangeGo + Lagrange.Core only read field
60 and would hit the same dead-end — we walk the chain instead. Also
log the full slot set when we genuinely can't find a host so future
reports can name which field the server actually populated.

Adds two regression tests: one proves the fallback to `uploadDomain`
goes to highway successfully, one proves we still throw when every
slot is empty.
2026-05-19 21:18:08 +08:00
手瓜一十雪
1daf6f6218 Remove runtime dependency bundling step
Delete the "Bundle runtime dependencies" step from .github/workflows/dev-build.yml. The removed step changed to working-directory: dist and ran npm install --omit=dev, so CI will no longer install runtime deps into dist during the dev build, reducing build time and avoiding bundling node modules into the dev artifacts.
2026-05-19 15:30:41 +08:00
DrSmoothl
898898a507 feat(msg-push): handle three friend-related events we used to drop on the floor
Close three coverage gaps surfaced by the cross-Lagrange-family
audit (Lagrange V2 / LagrangeGo / acidify / lagrange-python):

  - **0x210 subType 179 + 226 (NewFriend)** — mutual-accept friend
    notice. 179 fires when bot sent a request and the other side
    accepted; 226 fires for the opposite direction. Both decode
    through the same wire shape. LagrangeGo handles the pair via a
    `case 226: case 179:` fallthrough in `client/listener.go:248`.
    We surface them as `kind: 'friend_add'`, which the existing
    converter routes straight to OneBot `notice.friend_add` — bot
    frameworks that wait for "auto-add a friend after they accept"
    were previously stuck because nothing arrived.
  - **0x210 subType 139 (self-recall)** — bot recalled its own
    message sent to a friend. Same `FriendRecall` wire shape as 138
    but the peer is on `toUid` instead of `fromUid` — acidify's
    `parseFriendRecall:380` splits exactly this way. Without 139,
    self-recalls disappeared and downstream `notice.friend_recall`
    handlers thought the bot had never recalled anything.
  - **PkgType 85 (bot self-joined a group)** — fires on the bot's
    session once `set_group_add_request` is approved or an invite is
    accepted, ported from lagrange-python's `server_push/msg.py:108`.
    PkgType 33 (GroupMemberIncreaseNotice) only fires for *other*
    members joining, so without 85 the bot never received its own
    `notice.group_increase` until the first message arrived. We
    decode `SelfJoinInGroup` and emit `kind: 'group_member_join'`
    with `userUin = selfUin`; the existing converter picks
    `sub_type: 'approve' | 'invite'` from the operator/user equality
    so consumers see the standard OneBot shape.

While wiring 139, also fix a *pre-existing* prod bug spotted via
proton call-site analysis on the resulting bundle: `event-0x210.ts`
imported `FriendRecall` from both `proto/proton/notify` (as
`FriendRecallNotify`) *and* `events` (as the event interface).
Proton's import-resolver registers `importedTypeSources` keyed on
the *imported* name (last-write-wins), so the events.ts import
shadowed the proto one — `protobuf_decode<FriendRecall>(...)` lost
its codec, fell through to the runtime fallback throw, and was
silently swallowed by `MsgPushRegistry.decode`'s catch. Verified by
the substituted codec list in `dist/index.mjs`: pre-fix it had
`FriendRequest` / `GeneralGrayTipInfo` but no `FriendRecall`;
post-fix `FriendRecall` / `NewFriend` / `SelfJoinInGroup` are all
emitted as expected. Side-step the collision by importing the
proto types unaliased and re-deriving the colliding event type via
`Extract<QQEventVariant, { kind: 'friend_recall' }>`.

New proto interfaces in `proto/proton/notify.ts`:
  - `NewFriend` + `NewFriendInfo` (uid/time/message/nickName fields,
    fields 1-9; ported from
    `LagrangeGo/.../notify.proto:25 NewFriend`)
  - `SelfJoinInGroup` (groupUin / operatorUid + a few placeholder
    fields; ported from
    `lagrange-python/pb/status/group.py:170 PBSelfJoinInGroup`)

Regression coverage in `tests/msg-push-handler.test.ts`:
  - subType 179/226 both produce identical friend_add events
  - falls back to `routingHead.fromUin` when the new friend's uid
    isn't in the local cache (matches LagrangeGo's
    "emit-then-resolve" pattern)
  - subType 138 keeps fromUid as the peer (other recalled their
    own msg to us); subType 139 picks toUid (we recalled ours
    sent to them)
  - PkgType 85 emits group_member_join with userUin == selfUin,
    operator resolved through identity when known

core: 635/635 tests pass (+7), typecheck clean. Production bundle
now contains substituted codecs for FriendRecall, NewFriend,
SelfJoinInGroup (cross-checked via `grep protobuf_decode_X` on
`dist/index.mjs`).
2026-05-19 14:51:48 +08:00
DrSmoothl
604dbc3f64 fix(msg-push): Event0x210 subType=38 is the troop-shortcut-bar push, not friend-related
Earlier this commit acknowledged subType 38 as a placeholder
"FriendGrayTipInfo" because none of the LagrangeDev-family projects
(Lagrange V2 / lagrange-python / LagrangeGo / acidify) have a
handler for it — they all just fall through with a generic
"unknown subType" debug log. The "best guess" gray-tip framing was
wrong.

A contributor traced it through the decompiled stock QQ Android
client to `com.tencent.imcore.message.ext.codec.decoder.msgType0x210
.SubType0x26` (tsuzcx/qq_apk @ afe46ef). The payload is
`submsgtype0x26.MsgBody` dispatching on `uint32_sub_cmd`:

  - 0x1 → `UpdateAppUnreadNum`: a list of
    `{group_code, app_id, unread_num}` keeping group-internal
    "mini-app" badge counts (e.g. `appId=101846662` / `101896870`
    for the troop shortcut bar) in sync.
  - 0x3 → `UpdateDiscussAppInfo`: `{conf_uin, app_tip_notify.text}`
    discussion-group app tips, routed through `getGAudioHandler()`.
  - 0x4 → delegated to the troop online-push handler.

None of these have a meaningful OneBot mapping — they're
QQ-client-UI state pushes (badge counts, in-app tips), not
conversation events. Rename the enum entry to `GroupAppStatePush`
to reflect the actual semantics, cite the decompiled source
inline, and keep the silent-drop behaviour from the previous
attempt. Tests + decoder routing follow the rename.

628/628 tests pass (unchanged), typecheck clean.
2026-05-19 14:04:43 +08:00
DrSmoothl
ff5fc651d0 fix(tests): declare full vi.fn arg signatures so CI typecheck doesn't trip on tuple length
CI's `tsc --noEmit` was rejecting `forward-nested.test.ts` because the
`vi.fn(async () => 'RES')` mocks for `bridge.uploadForwardNodes` only
inferred zero or one arg from the lambda — so
`uploadForwardNodes.mock.calls[0]` came out typed as `[]` or
`[nodes: any[]]`, and indexing `[1]` / `[2]` for groupId / userId
hit `Tuple type ... has no element at index 'N'`.

Local `tsc --noEmit` happened to be looser about this in my version,
which is why the bad assertions slipped past `e637647`.

Declare the full 3-arg signature on every `uploadForwardNodes` mock
— `(_nodes, _groupId?, _userId?)` — matching the real
`Bridge.uploadForwardNodes` contract. `mock.calls[i]` now types as a
3-tuple, the index accesses check out, and the assertions stay
unchanged. No production code touched, no test behaviour change.

626/626 still passing, typecheck clean.
2026-05-19 13:00:41 +08:00
DrSmoothl
c758eb6569 fix(onebot): recursively parse nested forward chains (node-inside-node)
A custom forward node's `content` field can itself be a list of
`{type:'node'}` entries — that's the nested-forward case where one
forward bubble contains another. `parseForwardNodes` used to pass
the whole `content` straight into `parseMessage`, which routed
each inner `{type:'node'}` through `message-parser.ts:217 case
'node':` and turned them into opaque
`MessageElement{type:'node', resId: JSON.stringify(content)}`
placeholders. `element-builder.buildSendElems` then dropped those
at its default branch — so the outer forward shipped with either
zero elements (pure-nested → server rejects with "message is
empty") or text-only elements (mixed content → silently truncated
chat bubble). User-facing symptom: "嵌套转发解析后发不出去".

Add depth-aware recursion to `parseForwardNodes`, modelled on
NapCat's `SendMsg.uploadForwardedNodesPacket` (3-level cap):

  - When a node's `content` is *all* `{type:'node'}` entries,
    recurse: parse the inner chain into ForwardNodePayload[],
    upload it via `bridge.uploadForwardNodes` to mint an
    inner res_id, then embed a `{type:'forward', resId}` element
    in the outer node. The receive-side rendering pipeline already
    builds the ARK preview card for that element shape, so the
    QQ client renders a tap-to-expand nested bubble.
  - Mixed content (text + node siblings) deliberately stays on the
    flat path — the meaning is ambiguous, and forcing a recursion
    would silently drop the non-node siblings.
  - Hard cap at depth 3; deeper attempts throw "depth exceeds 3".
    Matches NapCat and prevents one slow inner upload from
    aborting an unreasonably deep tree.

Threading: each forward send entry point passes its destination
into the parser (`{groupId}` from group-send, `{userId}` from
private-send) so the inner forward uploads against the same
res_id namespace.

Test coverage in `tests/onebot/forward-nested.test.ts`:
  - group: inner uploads first, outer wraps inner res_id in a
    forward element, both calls happen in order
  - private: c2c path threads userId (not groupId) into the
    inner uploadForwardNodes
  - depth cap rejects 4-level nesting with /depth/
  - flat (non-nested) content still uploads exactly once
  - mixed content stays on the legacy parseMessage path

core: 626/626 tests pass (+5), typecheck clean, prod build clean.
2026-05-19 12:53:24 +08:00
DrSmoothl
10154cfbff fix(onebot): parse {type:'file', file_id:'…'} segments instead of dropping them
The companion to `e637647`. That commit fixed
`upload_group_file` / `upload_private_file` to publish the file as
a chat message atomically (matching napcat). This one fixes the
OTHER half of the same bug: when a bot framework does

  send_msg([{type:'file', file_id:'<previously uploaded>'}])

— attaching an already-uploaded file as a message segment — the
parser used to fall through to its default warn-and-drop branch
(`message-parser.ts:340`). The dropped segment then either:
  - became "message is empty" if it was the only segment, or
  - silently disappeared if it shared the payload with text,
producing a chat bubble missing the file.

Adds a `case 'file':` that maps the OneBot segment shape to the
existing `MessageElement{type:'file', fileId, fileName, fileSize,
md5Hex, sha1Hex}` that `element-builder` already knows how to
emit as `TransElem(24)`. Accepts the common alias spellings
(`file_id`/`fileId`, `name`/`filename`/`fileName`,
`size`/`fileSize`, `md5`/`md5Hex`, `sha1`/`sha1Hex`).

Deliberately rejects `{file: '/path'}` form — kicking off an
upload from inside the synchronous parser would either swallow
errors or restructure the whole parseMessage signature, neither
worth it. Callers wanting upload-and-send should keep using
`upload_group_file` / `upload_private_file`, which now does both
atomically.

core: 621/621 tests pass (+3), typecheck clean.
2026-05-19 12:42:47 +08:00
DrSmoothl
e637647877 fix(bridge): publish uploaded files as chat messages (the "empty message" bug)
`upload_group_file` / `upload_private_file` used to do only the
upload half of the napcat-equivalent flow:

  OIDB 0x6D6_0 alloc  →  highway PUT  →  return fileId

The fileId was real, the bytes were on QQ's CDN, the logs said
"uploaded" — but the chat showed nothing because no message was
ever sent referring to the upload. NapCat's `UploadGroupFile`
action (`dev/napcatQQ/.../UploadGroupFile.ts:54-58`) does the
upload AND immediately calls `MsgApi.sendMsg(peer, [fileElement])`
in the same action; that second step is what makes the file
visible in the chat.

Add the missing send step. Two paths because the wire shape
differs:

  - **Group files** ride on `Elem.transElem` (type 24) in the
    `RichText.elems` array. Add a `makeGroupFileElem()` helper +
    `case 'file':` in `element-builder.buildSendElems`, then
    `bridge.sendGroupMessage(groupId, [fileElement])` after a
    successful upload. The TransElem wraps a `GroupFileExtra`
    protobuf in `0x01 | BE16(len) | payload`, byte-symmetric with
    the receive-side decoder at `rich-body-decoder.ts:171-185`.
  - **C2C (private) files** live on `RichText.notOnlineFile`
    (field 3 on RichText, parallel to `elems`), so they can't go
    through `buildSendElems` at all. Add `Bridge.sendC2cFileMessage`
    that builds the `SendMessageRequest` with `notOnlineFile`
    directly and dispatches via `sendRawPacket`. The decoder side
    that lifts these back to `{type:'file'}` segments has lived
    at `rich-body-decoder.ts:425-433` the whole time.

Behavioural detail: both upload paths call the chat-publish step
*only* when `uploadFile=true` (the default). `uploadFile=false`
keeps the upload-only semantics for callers that just want a
fileId without dropping a message in the chat. If the chat post
fails for any reason (server rejection / network), the action
still returns the fileId with a warning log — the file is on QQ's
side, callers can re-publish if they want.

Regression coverage in `tests/actions/group-file.test.ts`:
  - publishes the file as `{type:'file'}` via sendGroupMessage on
    group upload
  - skips the post when uploadFile=false
  - returns success even when the chat post fails
  - same trio for private upload going through sendC2cFileMessage
  - and confirms private path does NOT route through the
    `sendPrivateMessage` elems[] pipeline

core: 618/618 tests pass (+5), typecheck clean. Production build
contains 8 substituted call sites for the new GroupFileExtra +
SendMessageRequest paths under proton.
2026-05-19 12:31:05 +08:00
DrSmoothl
a50e038272 docs(readme): list @snowluma/proton in the workspace table
Vendored in 6294e29, used by every protobuf call site in `core`
since the OIDB migration landed (5b55f5b). Add a one-liner to the
workspace table next to the other infrastructure packages.
2026-05-19 11:52:55 +08:00
DrSmoothl
ecb8064ca9 perf(webui): code-split routes; cut initial JS from 606 kB to 284 kB
`vite build` was emitting a single ~606 kB chunk for the whole SPA
(Vite even printed its >500 kB warning). Every route — overview,
config (with its full edit-dialog form surface), logs, settings —
was eagerly imported in `router/index.tsx`, so users paid the full
parse + execute cost before the login redirect even resolved.
That's the most plausible cause of the "loading node config is
somewhat slow" report.

Switch each route to `lazyRouteComponent(() => import('…'), '<Name>')`
so the page chunk is fetched on demand, and wrap `<Outlet />` in
`AppLayout` with a `<Suspense>` boundary backed by a small skeleton
fallback. `defaultPreload: 'intent'` is already set on the router,
so hovering a sidebar link warms the next chunk before the click —
navigation still feels instant after the first idle moment.

Build now emits:
  index.js          606 kB  →  284 kB    (-53%)
  overview-page                  15 kB
  config-page                    25 kB
  logs-page                      5.6 kB
  settings-page                  5.8 kB
  button (shared primitives)   164 kB
  + smaller per-component chunks Vite shook out
And the >500 kB warning is gone.

Bonus: replace the per-render
`list.filter(...).map(...).includes(item.name)` O(n²) duplicate-name
check in `NetworkTabView` with a one-shot `Map<name, count>` —
matters every time the user types in the edit dialog and the tab
underneath re-renders.
2026-05-19 11:48:41 +08:00
DrSmoothl
70715763bd fix(core): wire @snowluma/proton vite plugin into the production build
The proton plugin was only in `vitest.config.ts`, so tests and
typecheck passed but the bundled `dist/index.mjs` shipped with the
unsubstituted generic shells — every `protobuf_encode<T>()` /
`protobuf_decode<T>()` call hit the runtime fallback and threw:

  "protobuf_encode<T>() was not transformed by the
   @snowluma/proton Vite plugin. …"

at every msg-push, rkey/friend/group/profile warmup, etc. on the
Win/Linux releases.

Add `protobufVitePlugin()` to the shared `BaseConfigPlugin` so the
transform runs in both dev (`vite build --mode development`) and
prod (`vite build`). Sanity-check on a fresh `vite build` shows the
bundle now contains 481 distinct monomorphized codecs (704 encode +
511 decode call-site replacements), and the only remaining
"was not transformed" string is the dead runtime fallback that no
longer has a caller.
2026-05-19 11:20:47 +08:00
DrSmoothl
d821336943 fix(onebot): hot-reload HTTP server accessToken without re-binding
`HttpServerAdapter.startServer` baked `accessToken` into the
`createServer` callback's closure, then relied on
`bindingSignature` including the token to trigger a
`close()`+`open()` round-trip on every change. Two problems:

  1. The three sibling adapters (`ws-server`, `http-post`,
     `ws-client`) all read `this.config.accessToken` inline at the
     point of use, so the HTTP-server's closure-capture pattern was
     the odd one out.
  2. `server.close()` is asynchronous; the immediately-following
     `server.listen()` on the same port can race with the OS
     releasing it. When it loses, the new listener fails with
     EADDRINUSE (logged via `server.on('error', …)` but not bubbled
     up), the old server is gone, and the operator's `reload` looks
     successful while the endpoint is actually broken — which lines
     up with the "token didn't hot-reload" reports.

Drop the closure capture: `handleRequest` reads
`this.config.path` and `this.config.accessToken` fresh per request
(`reload()` already replaces `this.config` in place via
`structuredClone(next)`). Remove `accessToken` from
`bindingSignature` so a token change no longer triggers a port
re-bind. `host`/`port`/`path` stay in the signature because Node's
`Server.listen()` binds the socket on those.

Four hot-reload tests pin the new contract: token swap, clearing
to empty, setting from empty, and "token-only change returns
`NetworkReloadType.Normal`" (no Reopened/Closed). All four hit a
single OS-assigned port and verify the port is unchanged after
reload — a re-bind would either land on a different port or fail.

core: 613/613 tests pass (+4), typecheck clean.
2026-05-19 11:16:54 +08:00
DrSmoothl
76b87f6b27 feat(proton): migrate group-album actions (PR #31) to proton codec
PR #31 landed 4 TRPC group-album actions on the legacy runtime
schema encoder. Migrate them to the compile-time codec, matching
the pattern established by the OIDB migration: TS interfaces in
`proto/proton/oidb-action.ts` are monomorphized at build time and
each `protoEncode/Decode` call site now calls `protobuf_encode<T>` /
`protobuf_decode<T>` directly.

- Add 33 proton interfaces for the new TRPC envelopes (GetMediaList,
  DoQunComment, DoQunLike, DeleteMedias, plus all nested types) —
  inline anonymous schemas in legacy lifted to named interfaces.
- Migrate `actions/group-album.ts` to the proton API; drop the
  `(resp as any)` casts now that decoded responses are typed.
- Add 4 wire-byte parity tests for the new envelopes; non-default
  field values throughout so byte equivalence holds (proto3 omission
  of defaults is the documented divergence).
- Drop dead `GroupAvatarUploadExtSchema` from `proto/highway.ts` and
  unused `import * as console from "node:console"` in
  `web/group-album.ts` — leftovers from the original PR review.

core: 609/609 tests pass, typecheck clean.
2026-05-19 08:28:11 +08:00
DrSmoothl
5802812392 feat(proton): finish OIDB migration — runOidb on protobuf_encode<OidbBase<T>>
Closes the OIDB phase of the proton migration. Every consumer that
talked to the OIDB service through the old runtime
`makeOidbBaseSchema()` factory now goes through the compile-time
generic `OidbBase<T>` instead — proton monomorphizes the codec per
call-site instantiation.

@snowluma/proton — two analyzer fixes uncovered by the migration:

1. Skip queuing call-site type-args that reference an *enclosing
   generic function's* type parameter for monomorphization. Before
   this, a wrapper like

     export function encodeOidbEnv<T>(env: OidbBase<T>): Uint8Array {
       return protobuf_encode<OidbBase<T>>(env);
     }

   would cause the analyzer to mint a literal `OidbBase__T` registry
   entry with `body.typeName = 'T'`, which the post-walk wire-type
   guard then tripped on. The enclosing-scope type params are tracked
   on a stack as the walker descends into FunctionDeclaration,
   FunctionExpression, ArrowFunction, MethodDeclaration nodes; matching
   call sites are skipped (the wrapper-binding path is still
   responsible for materialising concrete codecs at downstream call
   sites).

2. Register *explicitly* empty interfaces (`interface X {}`) as
   zero-field proto messages. OIDB has a handful of these
   ('this call has no meaningful response body' placeholders —
   Oidb0xeb7Resp, Oidb0xcd4Resp, Oidb0x112aResp, Oidb0x8a0Resp,
   Oidb0xf16Resp, OidbClientKeyReq). Proto3 wire allows zero-field
   messages, and downstream code does `protobuf_decode<OidbBase<X>>`
   where X is one of these — the wire-type guard would otherwise trip
   on the missing `X` registration. Interfaces that have members but
   no pb-marked fields are still NOT registered.

@snowluma/core — the OIDB-layer refactor itself:

bridge-oidb.ts ditches the runtime ProtoSchema factory and exposes:
  - makeOidbEnvelope<T>(oidbCmd, subCmd, body, isUid)   pure helper
  - encodeOidbEnv<T>(env)                               pass-through
  - decodeOidbEnv<T>(bytes)                             pass-through
  - runOidb(bridge, cmd, envelopeBytes)                 non-generic raw

`encodeOidbEnv` / `decodeOidbEnv` are pure pass-through generic
wrappers — proton wrapper-binds them and substitutes every call site
with the inlined `protobuf_encode_OidbBase__X` / `protobuf_decode_…`
function. `runOidb` is non-generic (proton leaves it alone) so it can
be mocked in tests. `makeOidbEnvelope` is plain TS — also mockable for
introspection.

56 `runOidb` call sites across 11 files migrated to the new API:
  - bridge-contacts.ts, actions/extras.ts, actions/friend.ts,
    actions/group-admin.ts, actions/group-file.ts,
    actions/group-message.ts, actions/interaction.ts,
    actions/misc.ts, actions/profile.ts, web-actions/cookies.ts,
    highway/pipeline.ts

pipeline.ts also drops `makeOidbBaseSchema(NTV2UploadRichMediaReqSchema)`
and the residual `protoEncode({...}, EncodableMediaMsgInfoSchema)` —
both go through proton now.

Tests:
  - 8 test files migrated from `vi.mocked(decodeOidbEnv).mockReturnValueOnce`
    to `vi.mocked(runOidb).mockResolvedValueOnce(protobuf_encode<OidbBase<X>>({body: …}))`
    — the proton substitution means the old mock layer is bypassed at
    build time, so the only mockable point is the bytes layer at `runOidb`.
  - 2 new parity tests pinning `OidbBase<T>` ↔ legacy
    `makeOidbBaseSchema(InnerSchema)` byte equivalence.

Verification:
  - @snowluma/proton: 95/95 tests pass, tsc --noEmit clean
  - @snowluma/core:   605/605 tests pass (network-manager.test.ts
    fails to load due to a missing darwin-arm64 native binary in this
    environment — pre-existing), tsc --noEmit clean
2026-05-19 08:19:14 +08:00
DrSmoothl
6f3646e956 feat(proton): add proton/oidb-action.ts (183 schema mirrors)
Phase 2 of the OIDB migration: one-to-one mirror of every schema in
bridge/proto/oidb-action.ts as a proton interface. Purely additive —
the legacy `*Schema` constants stay in place; no call sites are
switched yet.

Translation is mechanical:
  - export const XxxSchema = { ... } satisfies ProtoSchema;
    → export interface Xxx { ... }
  - { field: N, type: 'uint32' as const }   → pb<N, uint_32>
  - { field: N, type: 'repeated_message',
      schema: YSchema }                     → pb_repeated<N, Y>
  - … (etc, for every primitive + message + repeated_*)

All section headers (`// --- 0x1253_1: Mute group member ---`) and
inline NTQQ-specific comments (the FE1_2 field-2 note, the NTV2
default-value note, the Lagrange-observed annotations on
GroupAvatarExtra, etc.) preserved verbatim.

Verification:
  - 183 interfaces emitted, exact match to the legacy schema count
  - tsc --noEmit clean
  - 604/604 core test suite passes (no behaviour change — additive
    only)

Phase 3 next: refactor runOidb to use protobuf_encode<OidbBase<TReq>>
and migrate the 67 runOidb call sites across 10 files + pipeline.ts.
2026-05-19 08:19:14 +08:00
DrSmoothl
c543ce9227 feat(proton): add proton/oidb.ts with generic OidbBase<T> envelope
Phase 1 of the OIDB migration: stages the proton-side type definitions
and pins their wire equivalence to the legacy makeOidbBaseSchema()
runtime factory. No call sites are switched yet — that lands in
phase 2 along with the proton/oidb-action.ts schema mirror and the
runOidb refactor.

The legacy bridge/proto/oidb.ts exports a `makeOidbBaseSchema(body)`
factory function that synthesizes the OidbSvcTrpcTcpBase envelope
ProtoSchema at runtime. Proton is compile-time, so the natural form
is the generic interface

  OidbBase<T> { command, subCommand, errorCode, body: T, errorMsg,
                 properties, reserved }

which the plugin monomorphizes per-instantiation. This is exactly the
"generic template with generic-instantiated field" usage that this
package's earlier edge-case fixes #2 and #3 were designed to support,
and the new parity test pins that they actually work on the real
shape (a fully populated OidbSvcTrpcTcp0xFE5_2Response with nested
groupOwner/customInfo).

Also added:
  - OidbProperty (for the envelope.properties repeated field)
  - OidbBaseMeta — envelope-only view for fire-and-check OIDB calls
    that just need to peek at errorCode without decoding the body
  - All 8 concrete schemas from oidb.ts (FriendList, GroupList,
    GroupMemberList, GroupRequest families)

Verification:
  - 2 new parity tests
    * OidbBase<OidbSvcTrpcTcp0xFE5_2Response> ↔ makeOidbBaseSchema
      byte equivalence
    * round-trip encode → decode preserves nested body
  - 602+2 = 604 core tests pass (network-manager file still env-fails
    on missing native binary)
  - tsc --noEmit clean
2026-05-19 08:19:14 +08:00
DrSmoothl
7526622917 feat(proton): migrate highway.ts schemas + highway-client + group-file
Mirrors all 35 schemas in bridge/proto/highway.ts as proton interface
forms and switches the two non-OIDB-wrapped consumers
(highway/highway-client.ts and actions/group-file.ts) over to the new
compile-time API.

Migrated schemas (proton/highway.ts):
  DataHighwayHead, SegHead, LoginSigHead, ReqDataHighwayHead,
  RespDataHighwayHead, HighwayDomain, HighwayIPv4, HighwayNetwork,
  HighwayHash, HighwayMsgInfoBody, NTV2RichMediaHighwayExt,
  FileUploadUrl, FileUploadHost, FileUploadHostConfig,
  FileUploadNameInfo, FileUploadClientInfo, FileUploadFileEntry,
  FileUploadBusiInfo, FileUploadEntry, FileUploadExt,
  EncodableMediaExtBizInfo, EncodableMediaMsgInfo, HttpConn,
  HttpConn0x6FF501Request, ServerAddr, ServerInfo, HttpConnResponse,
  HttpConn0x6FF501Response, NTV2FileType, NTV2FileInfo,
  NTV2UploadInfo, NTV2ExtBizInfo, NTV2UploadReq, NTV2C2CUserInfo,
  NTV2GroupInfo, NTV2UploadSceneInfo, NTV2CommonHead, NTV2ClientMeta,
  NTV2UploadReqHead, NTV2UploadRichMediaReq, NTV2IPv4,
  NTV2SubFileInfoResp, NTV2UploadRespMsgInfo, NTV2UploadRespBody,
  NTV2UploadRespHead, NTV2UploadRichMediaResp

Consumer switches:
  - highway/highway-client.ts: protobuf_encode/decode for HttpConn
    session fetch, ReqDataHighwayHead frames, NTV2RichMediaHighwayExt
    extend bytes, RespDataHighwayHead per-chunk responses
  - actions/group-file.ts: protobuf_encode<FileUploadExt> for both
    group + private file upload ext bytes

NOT migrated (depends on the OIDB factory pattern):
  - highway/pipeline.ts — uses makeOidbBaseSchema(NTV2UploadRichMediaReqSchema)
    to wrap the NTV2 upload in an OIDB envelope at runtime. Waits for
    the oidb.ts migration to land a generic OidbBase<T> form.

Verification:
  - 5 new parity tests for highway schemas (HttpConn0x6FF501 req+resp
    with the high-numbered 0x501 tag, ReqDataHighwayHead with multiple
    nested messages, NTV2RichMediaHighwayExt with repeated_bytes,
    FileUploadExt with the 100/200/400/600/700 high-numbered tags)
  - 602/602 core test suite passes — the existing image / ptt / video
    upload tests implicitly validated wire format equivalence
  - tsc --noEmit clean
2026-05-19 08:19:14 +08:00
DrSmoothl
ccc31a760c feat(proton): migrate action.ts schemas + bridge.ts + element-builder.ts
Mirrors all 11 schemas in bridge/proto/action.ts as proton interface
forms and switches the two consumers (element-builder.ts and the
send-message paths in bridge.ts) over to the new compile-time API.

Migrated schemas (proton/action.ts):
  RoutingC2C, RoutingGroup, RoutingHead, SendContentHead,
  MessageControl, SendRichText, SendMessageBody, SendMessageRequest,
  SendMessageResponse, MentionExtraSend, MarkdownData

Consumer switches:
  - element-builder.ts: protobuf_encode<MentionExtraSend> for @ mention
    pbReserve payload; protobuf_encode<MarkdownData> for markdown elem
  - bridge.ts: protobuf_encode<SendMessageRequest> +
    protobuf_decode<SendMessageResponse> for both sendGroupMessage and
    sendPrivateMessage

The `ProtoElem` type alias in element-builder.ts (Partial<ProtoDecoded<typeof
ElemSchema>>) stays as-is — it's a pure TS type used internally for
building elem objects and doesn't affect runtime behaviour. Replacing
it with the proton Elem type is a larger refactor that can come later
when there's a reason to.

Verification:
  - 6 new parity tests for action schemas (RoutingHead c2c+grp,
    SendMessageRequest full shape, SendMessageResponse, MentionExtraSend,
    MarkdownData)
  - 591/591 core test suite passes — the existing send-message and
    element-builder tests implicitly validated wire format equivalence
  - tsc --noEmit clean
2026-05-19 08:19:14 +08:00
DrSmoothl
9f32dbd60c feat(proton): migrate notify.ts schemas + all 6 msg-push consumers
Mirrors all 27 notify.ts schemas as proton interface forms and switches
the entire msg-push decoder family over to the new compile-time API.

Migrated schemas (proton/notify.ts):
  OperatorField1, OperatorInfo, GroupChange, GroupAdminExtra,
  GroupAdminBody, GroupAdmin, InvitationInner, InvitationInfo,
  GroupInvitation, GroupInvite, GroupJoin, FriendRequestInfo,
  FriendRequest, FriendRecallTipInfo, FriendRecallInfo, FriendRecall,
  GroupMuteState, GroupMuteData, GroupMute, RecallMessage,
  GroupRecallTipInfo, GroupRecall, TemplParam, GeneralGrayTipInfo,
  EssenceMessage, NotifyMessageBody, GroupReactionDataInnerDataTarget,
  GroupReactionDataContent, GroupReactionDataInnerData,
  GroupReactionDataInner, GroupReactionData, GroupReactNotify

Consumer files switched to protobuf_decode<T>():
  - msg-push/helpers.ts (decodeOperatorUid)
  - msg-push/decoders/event-0x2dc.ts (5 call sites: GroupMute,
    GroupRecall, GroupGreyTip, GroupEssence, GroupMsgEmojiLike)
  - msg-push/decoders/event-0x210.ts (3 call sites: FriendRequest,
    FriendRecall, FriendPoke)
  - msg-push/decoders/group-admin.ts
  - msg-push/decoders/group-member-change.ts (join + leave)
  - msg-push/decoders/group-join-request.ts (join request + invitation
    + invite)

The notify.ts FriendRecall interface collides with events.ts's own
FriendRecall event type; the decoder imports it under the local alias
FriendRecallNotify to keep the existing event type intact.

Verification:
  - 6 new parity tests pinning notify wire equivalence
  - 591/591 core test suite passes (the existing decoder tests —
    group-msg-emoji-like, group-admin, etc. — implicitly validated
    wire format equivalence against real captured QQ payloads)
  - tsc --noEmit clean
2026-05-19 08:19:14 +08:00
DrSmoothl
b7d8952163 feat(proton): full longmsg + element + message migration; forward.ts on new API
Completes the proton migration started in the previous PoC commit. All
schemas needed by actions/forward.ts are now mirrored as proton interface
forms, the legacy ProtoSchema constants stay in place for back-compat,
and forward.ts has been switched over to the new compile-time codecs.

Migrated schemas:
  - element.ts (35 schemas: TextElem, FaceElem, OnlineImage, NotOnlineImage,
    TransElem, MarketFace, CustomFace, RichMsg, GroupFileElem, ExtraInfo,
    VideoFile, SrcMsg, LightAppElem, CommonElem, GeneralFlags, Elem,
    MentionExtra, QFaceExtra, QSmallFaceExtra, FileType, FileInfo,
    IndexNode, PicUrlExtInfo, PictureInfo, PicExtData, PicExtBizInfo,
    VideoExtBizInfo, PttExtBizInfo, ExtBizInfo, C2cSource, TroopSource,
    HashSum, MsgInfoBody, MsgInfo, GroupFileInfo, GroupFileExtraInner,
    GroupFileExtra, Preserve, …)
  - message.ts (PushMsg, PushMsgBody, ResponseHead, ContentHead, Ptt,
    NotOnlineFile, RichText, MessageBody, FileExtra, …)
  - longmsg.ts — the three remaining schemas (LongMsgContent / LongMsgAction
    / LongMsgResult) that depend on PushMsgBody

forward.ts now calls:
  protobuf_encode<LongMsgResult>(...)   // upload payload
  protobuf_encode<SendLongMsgReq>(...)
  protobuf_decode<SendLongMsgResp>(...)
  protobuf_encode<RecvLongMsgReq>(...)
  protobuf_decode<RecvLongMsgResp>(...)
  protobuf_decode<LongMsgResult>(...)   // download payload
  protobuf_encode<PushMsg>(...)         // re-wrap for parseMsgPush

The unused legacy schema constants are intentionally left in place — they
still back the existing forward.test.ts mock encoder and any other consumer
that hasn't been migrated yet. They will be removed in a follow-up once
every consumer is on the new API.

Verification:
  - 18/18 parity tests pass (encode + decode equivalence for every
    representative shape across element / message / longmsg)
  - 585/585 core test suite passes (network-manager.test.ts fails to load
    due to a missing native binary in this environment — pre-existing)
  - tsc --noEmit clean
2026-05-19 08:19:14 +08:00
DrSmoothl
d323318a7e bench(proton): proton vs legacy runtime encoder/decoder
Standalone tsx script benchmarking the codecs generated by
@snowluma/proton against the existing src/protobuf/decode.ts runtime
implementation, using the actual long-message schemas already in the
codebase (the proton interface form + the legacy *Schema constants).

Proton codecs are materialised at bench startup via the public
analyzeSource + generateCode API — exactly what the Vite plugin does at
build time — so there is no chicken-and-egg dependency on a Vite build.

Headline numbers on Node 24 / darwin-arm64:
  - simple 4×uint32 encode: ~8.5× speedup
  - simple 4×uint32 decode: ~35× speedup
  - deeply nested SendLongMsgReq encode: ~9.5×, decode: ~13×
  - 64-byte payload RecvLongMsgResp encode: ~4.3×, decode: ~10×

Run with:
  pnpm --filter @snowluma/core exec tsx bench/proton-vs-legacy.ts
2026-05-19 08:19:14 +08:00
DrSmoothl
31079673c6 docs(proton): add README
Covers quick start, primitive types, generic templates, cross-file
wrapper bindings, the proto3 default-value divergence vs the legacy
runtime encoder, build-time diagnostics, and the optional runtime-map
fallback. Also lists every edge case fixed on top of upstream with a
pointer to the corresponding regression test.
2026-05-19 08:19:14 +08:00
DrSmoothl
3d739c255a feat(proton): proof-of-concept migration — longmsg parity test
Migrates a self-contained subset of bridge/proto/longmsg.ts to the new
@snowluma/proton compile-time DSL form and verifies wire-format parity
against the legacy runtime ProtoSchema encoder. End-to-end proof that
the toolchain works in core's vitest pipeline.

What's covered:
  - LongMsgUid / LongMsgSettings / SendLongMsgInfo / SendLongMsgReq /
    SendLongMsgResp / SendLongMsgRespResult / RecvLongMsgInfo /
    RecvLongMsgReq / RecvLongMsgResp / RecvLongMsgRespResult
  - The three schemas that pull in PushMsgBody (LongMsgContent /
    LongMsgAction / LongMsgResult) stay on the legacy API for now, since
    migrating them requires also migrating message.ts and element.ts.

Toolchain changes:
  - @snowluma/proton gets a tsup build step. The ./vite subpath now
    points at the built dist/index.js so it is loadable as plain Node
    ESM from vite.config.ts / vitest.config.ts (the source-only .ts
    layout can't be consumed from outside the Vite transform pipeline).
    The . (runtime) subpath stays at TS source — it's only ever
    imported from user code, which IS Vite-transformed.
  - prepare script ensures dist/ exists after pnpm install.
  - @snowluma/core depends on @snowluma/proton (workspace:*) and adds
    protobufVitePlugin() to its vitest config so test files get
    transformed.

Documented divergence:
  proton follows proto3 semantics: fields equal to their default value
  (0 / false / "" / empty bytes) are NOT emitted on the wire. The legacy
  runtime encoder always emits them. Both forms are round-trippable
  through a conforming proto3 reader. The parity test pins this
  behaviour explicitly.

8/8 parity tests pass.
2026-05-19 08:19:13 +08:00
DrSmoothl
194165f49d feat(proton): add @snowluma/proton — compile-time protobuf DSL
Vendors SnowLuma/protobuf-dsl into the monorepo as @snowluma/proton, with
edge-case fixes applied on top of the upstream source. Reference copy of
the unmodified upstream is kept under dev/protobuf-dsl/.

Edge cases fixed (each with a regression test):
  - Aliased pb / pb_repeated marker imports (`import { pb as P }`)
    — collector now resolves the marker name through the import resolver
  - Concrete interface with a generic-instantiated message field
    (`wrapped: pb<5, Wrapper<uint_32>>`) — field typeName now resolves
    to the mangled form, and the inner instantiation is queued for
    monomorphization
  - Generic template with a generic-instantiated field
    (`interface Outer<U> { x: pb<5, Wrapper<U>> }`) — the inner
    instantiation is now re-substituted and re-monomorphized at outer
    instantiation time
  - Wrapper-binding synthetic SourceFile was empty-text — getText()
    returned garbage, breaking mangled name computation downstream
  - Cross-file forwarded wrappers (chain → imported base) were not
    detected — parseFileForDefinitions now resolves imports recursively
    (value imports only, with cycle protection)
  - matchForwardedKnownWrapper did not propagate typePattern — chain
    treated <X> as the encoded type instead of Wrapper<X>
  - Synthetic-SF WeakMap was private to analyzer.ts — replacer could
    not see it. Moved to utils.ts so typeNodeToMangledName picks it up
    automatically.

Defensive guard: any field whose typeName resolves to neither a primitive
nor a known message now throws at analyze() time, instead of silently
leaking the WireType.Varint placeholder into codegen.

95/95 tests pass; tsc --noEmit clean.
2026-05-19 08:19:13 +08:00
墨梓柒
02d1848d39 Merge pull request #31 from H3CoF6/feat/onebot
Implement group album action
2026-05-19 08:18:39 +08:00
H3CoF6
0d40a03f28 Merge upstream/dev into feat/onebot 2026-05-19 02:40:14 +08:00
H3CoF6
64530cc287 Implement some actions: comment, send and cancel like, delete media for group album! 2026-05-19 02:37:11 +08:00
手瓜一十雪
df691c4e8f Revert "feat: Add @snowluma/protobuf package"
This reverts commit 9f9db8d16f.
2026-05-18 20:43:32 +08:00
手瓜一十雪
9f9db8d16f feat: Add @snowluma/protobuf package
Introduce a new @snowluma/protobuf package (v0.0.4) that provides a lightweight protobuf-ts wrapper (NapProto/NapProtoMsg) with type helpers, ProtoField factory, and encode/decode utilities. Adds package.json, tsconfig.json, and the implementation at src/NapProto.ts. pnpm-lock.yaml was updated to include the @protobuf-ts/runtime dependency resolution.
2026-05-18 19:31:42 +08:00
DrSmoothl
4d7302a13f chore(github): add issue templates for bug reports and feature requests
Adds structured YAML issue forms (bug + feature) and a config that
disables blank issues and links to the QQ group / Telegram channels
already in README.
2026-05-18 18:01:57 +08:00
墨梓柒
f316073431 Merge pull request #43 from airline233/dev
feat(http-server): support parse content-type of urlencoded
2026-05-18 17:51:41 +08:00
墨梓柒
692a1b7665 Merge pull request #52 from Stlara-F/dev
fix(request-actions): match group add/invite flags by UID and add regression tests
2026-05-18 15:19:15 +08:00
DrSmoothl
941e60dea5 chore(release): v1.8.5 2026-05-18 15:03:45 +08:00
stla
b99f5c0bf1 fix(request-actions): match group add/invite flags by UID and add regression tests 2026-05-18 07:03:45 +00:00
DrSmoothl
562fd4f7f9 fix(oidb): set envelope reserved=1 on OIDB 0xFE1_2 (user / stranger)
Follow-up to c62f517. Dropping the obsolete field 2 from the body was
necessary but insufficient: newer QQ NT still rejects the request with

    [oidb] one of uid/openid is invaild

The actual trigger is the OIDB envelope-level `reserved` flag.
Lagrange.Core's FetchStrangerByUin sets `Reserved = 1`, our call sent
`Reserved = 0`. The server uses that bit to pick its validation path:

  - reserved=1 → UIN-form variant: server translates body.uin to the
    internal uid itself
  - reserved=0 → UID-form variant: server expects a uid/openid string
    in the body and rejects when it can't find one

Our request body has only `uin` + `keys`, so the UID-form path was
always going to fail. Setting `isUid: true` (which is the existing
flag that flips envelope `reserved` to 1; the parameter name is
historical and misleading) puts the call onto the correct branch.

Applied to both call sites that target OidbSvcTrpcTcp.0xfe1_2:

  - fetchUserProfile (bridge-contacts.ts) — fixes the
    "failed to load self profile for UIN N" warmup warning.
  - getStrangerStatus (actions/extras.ts) — same OIDB cmd; would
    have failed identically if exercised against newer QQ NT.

Also updated the `isUid` JSDoc on OidbCall to spell out the actual
semantic (UIN-form variant marker, not "this call uses UID-keyed
data") since the name will keep tripping people otherwise.
2026-05-18 14:58:58 +08:00
DrSmoothl
ba899782fe feat(webui): mask the access token and add copy + visibility buttons
The adapter edit dialog now ships a dedicated TokenField for the
access-token slot instead of reusing the plain text Field. It:

  - defaults to a password-style input so the value stays out of
    casual screen reads / screenshots,
  - exposes an Eye / EyeOff button that flips the input type rather
    than masking the string, so paste / autocomplete still behave like
    a native password field,
  - exposes a Copy button that pushes the current value to
    navigator.clipboard, flashing a check icon for ~1.4 s on success,
    and disables itself when the value is empty,
  - falls back to a transient textarea + document.execCommand('copy')
    for non-secure-context environments (LAN HTTP outside localhost),
    routed through a local alias so the deprecation warning on the
    live signature doesn't fire at the call site.
2026-05-18 14:47:33 +08:00
DrSmoothl
6a7c9a5de1 fix(bridge): also drop config1.field5002 from the OIDB 0xFE5_2 mask (#42)
Follow-up to a07521d. The reporter's correction (895 friends / 221
groups account) was that turning off only field5003 + all of config2
wasn't enough — field5002 has to go too, otherwise QQ NT still emits
a response large enough to blow the named-pipe write buffer and
fetchGroupList dies with EPIPE.

The response decoder (OidbSvcTrpcTcp0xFE5_2GroupInfoSchema) only knows
about tag numbers 1/2/3/4/5/18/19/30, and fetchGroupList itself only
reads groupName / memberCount / memberMax / customInfo.remark off the
result. Tag 5002 isn't in the response schema and isn't consulted by
any caller, so silencing it on the request side is purely a payload
reduction with no observable behavior change.
2026-05-18 14:36:20 +08:00
DrSmoothl
7a2de230bf fix(webui): pass aria-checked as a string literal on switch buttons
A11y checkers (axe-core / jsx-a11y) flag the boolean form because the
ARIA spec defines aria-checked as the enum "true" | "false" | "mixed",
not a boolean. React serialized the boolean to the right wire value at
runtime, but the inspection layer keys off the JSX expression's static
type. Switching to the explicit ternary silences both.
2026-05-18 14:31:08 +08:00
DrSmoothl
a460433175 refactor(webui): redesign per-UIN config page into sidebar + tabs + modal
The original page stacked four expanded network sections vertically with
inline editing, so the first view drowned in every field across every
adapter at once. Restructured to a sidebar + tabs + modal layout:

- Account sidebar collapses to a 56px avatar column with name/UIN
  tooltips; expanded it keeps the original 260px nickname + UIN layout.
- Right pane swaps the stacked sections for a 5-tab strip (通用设置 /
  HTTP API / HTTP 客户端 / WS 服务端 / WS 客户端) with a per-tab badge
  count.
- Each network tab is a list of summary cards: name + projected key
  info (host:port/path, url · role, etc.) + format/report/token badges
  + inline enable toggle + edit/delete buttons. No live-typed fields.
- Create and edit both route through a single NodeEditDialog with
  kind-specific field strips; cancel truly discards the draft.
- Per-kind metadata (title, summary projector, defaultEntry factory)
  lives in config/defaults.ts so adding a new adapter kind only needs
  one descriptor entry.

Behavior preserved end-to-end: same per-UIN config payload, same
useOneBotInstanceConfig hook, same dirty-switch confirm flow, same
save endpoint.
2026-05-18 14:29:52 +08:00
DrSmoothl
24056c3de0 feat(msg-push): decode group message emoji reactions (Event0x2DC subType=16)
QQ has been pushing Event0x2DC subType=16 every time someone tapped
an emoji on a message in a group, and we were dropping it silently
(only surfacing the PR5 [MsgPush.Unknown] debug line that prompted
this issue). Now we decode it into a first-class event and fan it
out to OneBot clients.

Wire details (cribbed from NapCat's GroupReactNotify transformer):
  - body.msgContent has a 7-byte magic prefix; strip before decoding.
  - GroupReactNotify { groupUin(4), field13(13), groupReactionData(44) }.
  - field13 is a discriminator — same subType is reused for other
    notify variants, only 35 means "emoji react". Other values now
    fall through to MsgPush.Unknown so we still spot future variants.
  - Inside groupReactionData (3-level nested data wrapper, ugh):
      code         emoji id (system face = numeric str, market = code)
      count        usually 1
      operatorUid  needs identity.findUinByUid to resolve to uin
      type         1 = add, else = remove
      target.seq   msg_seq of the reacted-to message

New event kind `group_msg_emoji_like` flows through the standard
pipeline: bridge event → event-bus → converter → OneBot wire.
Converter emits the gocqhttp / NapCat extension shape:

  notice_type:  group_msg_emoji_like
  sub_type:     add | remove
  group_id, user_id, operator_id, message_id, message_seq,
  likes: [{ emoji_id, count }]

message_id is reconstructed via hashMessageIdInt32(msgSeq, groupId,
GROUP_MESSAGE_EVENT) so it matches whatever id the bot originally
handed out for the message being reacted to, even if it's no longer
in the message store.

formatEvent also gets a case so the [Event] log reads cleanly:
  表情回应 [群名(123)] | [Alice(99999)] +[76] msgSeq=4242

7 new tests cover the happy path, type=2 (remove), field13!=35
(routed to MsgPush.Unknown), prefix-too-short edge, converter
shape both for add and remove, and the formatEvent string.
2026-05-18 14:06:44 +08:00
DrSmoothl
a07521d9de fix(bridge): drop bloated fields from OIDB 0xFE5_2 group-list request
closes #42

On accounts with ~200+ groups, fetchGroupList was asking QQ to fill
in every config flag (all 32 bools in config1 plus all 8 in config2)
even though our response decoder reads only groupName / memberMax /
memberCount / customInfo.remark / a handful of named info fields.

QQ NT obligingly packs every requested field into the response. At
group counts >= ~200 the payload is large enough to blow the
named-pipe write buffer on the QQ side; SnowLuma reads EPIPE and
the entire session dies during warmup:

  WARN  [Hook]   pipe error: PID=23928 err=read EPIPE
  INFO  [OneBot] session closed: UIN=...
  WARN  [OneBot] failed to load groups for UIN ...: qq_hook client closed

Issue #42 reporter (airline233) bisected the breakage to two
clusters of unused bool flags:
  - config1.field5003   (a 5xxx-range expansive descriptor)
  - the whole of config2 (per-group aux info we don't decode)

This commit applies exactly their verified safe combination and
inlines a comment so nobody flips them back on without context.
The decoded response shape (groupName, memberCount, memberMax,
remark, etc.) is unchanged.
2026-05-18 13:48:13 +08:00
DrSmoothl
c62f51750a fix(oidb): drop the obsolete field 2 from OIDB 0xFE1_2 (user profile)
QQ now rejects fetchUserProfile() with:

    [oidb] one of uid/openid is invaild

The cause: SnowLuma's request schema declared field 2 as a
zero-valued uint32 (`field2: 0`) and our encoder doesn't skip 0
varints. Newer QQ NT versions reinterpret field 2 of OIDB 0xFE1_2 as
`uid: string` / `openid: string`, so a varint 0 there decodes as an
empty/invalid uid → server bounces the whole request.

NapCat's equivalent transformer (Oidb.0XFE1_2.ts) emits only `uin`
(field 1) and `key[]` (field 3) — nothing in field 2. Match that
shape exactly.

Effect: warmUpBridgeState's "self info via profile" fallback path
now succeeds for accounts that QQ omits from the friend list, so
the WebUI shows their nickname instead of leaving it blank.
2026-05-18 13:39:54 +08:00
DrSmoothl
b94775cb6f chore(release): v1.8.4 2026-05-18 13:31:17 +08:00
DrSmoothl
5524c73eed chore(webui): keep search engines out of the admin surface
Even the login page leaks "there's a SnowLuma admin panel at this
IP / hostname" to anyone scanning, and right now that page is
publicly indexable. Three overlapping signals so we don't depend on
any one being honoured:

1. Hono middleware on every response sends
     X-Robots-Tag: noindex, nofollow, noarchive, nosnippet, noimageindex
   Hardest for compliant bots to ignore — it's a header, not
   content. noimageindex also covers logo.png / avatar/* from
   showing up in image search.

2. A GET /robots.txt route returns "User-agent: * / Disallow: /"
   for crawlers that read it before fetching pages. Sits before
   the auth middleware so no token is required (otherwise the
   crawler would get 401 here, which it'd then refuse to obey).

3. <meta name="robots"> (plus googlebot / bingbot) in index.html
   as a fallback for the case where a reverse proxy strips the
   X-Robots-Tag header.
2026-05-18 13:18:31 +08:00
DrSmoothl
4c513c015d feat(logger): runtime log level toggle via WebUI
The console / subscriber level was captured at module load
(`const MIN_LEVEL = resolveMinLevel()`), so any change to
SNOWLUMA_LOG_LEVEL after Node started had no effect — restart was
the only way to flip levels, which makes "go to debug for 30s to
see what's happening" pretty painful.

logger.ts now keeps `currentLevel` mutable and exports
setLogLevel() / getLogLevel(). The env var still seeds it on
startup; nothing about the boot-time behavior changes. File
transport remains unaffected — it always sees debug-and-up.

WebUI gets two new endpoints, both behind the existing auth
middleware:
  GET  /api/logs/level       → { level, levels }
  POST /api/logs/level body  → { level: 'debug' } updates it

Logs page picks up a "服务端级别" row of pills next to the
existing client-side filter pills, so an operator can flip the
console firehose on/off in one click without touching env vars
or restarting the bot. The label clarifies that file logging
stays at debug regardless.
2026-05-18 13:15:05 +08:00
DrSmoothl
4a49c55775 fix(hook): refresh pipe snapshot before verifying unload took
After native unload returns, the verification check
  if (pipeWatcher.isPipeLive(pid)) { ... unload-failed message ... }
read PipeWatcher's cached snapshot, which is updated every 1500ms.
On Windows clicking "Unload" in WebUI almost always tripped this:
the native unload succeeded and the kernel pipe object was gone, but
the watcher's cached "live" state from the previous tick was still
fresh, so the session reported "DLL卸载失败:命名管道仍然存在" even
though the DLL was successfully unloaded. The user then sees the
status flip back to connecting and waits for a real (cached) refresh.

PipeWatcher already exposes tickNow() for exactly this situation —
the load path doesn't need it because injection's verification runs
async via onPipeUp, but unload verifies inline.

HookSessionDeps.pipeWatcher gains an optional `tickNow` and
unloadInternal awaits it before reading isPipeLive. Existing test
mocks that pass only `{ isPipeLive }` keep working (optional chain
is a no-op there). New regression test covers the production
scenario — stale-true cache flipped to false by tickNow.
2026-05-18 13:07:10 +08:00
DrSmoothl
e04a539b26 fix(logger): pass identity to the second printEvent call site
The previous commit (257686e) widened printEvent's signature to take
IdentityService but only updated the synchronous call at line 97.
The async post-refresh dispatch path (line 127, called when a group
member join arrives without a resolved uin) still used the old
two-arg form, which CI caught as TS2554. Local tsc somehow didn't
flag it on the editing machine.

Both sites now pass this.deps.identity so the readable rendering
applies to both prompt and post-refresh dispatch paths.
2026-05-18 12:47:34 +08:00
DrSmoothl
257686eac6 feat(logger): identity-aware readable event rendering
Notice events (recall / join / leave / poke / admin / mute / essence
/ request / invite) and the received-message log now resolve group
IDs and user IDs against the Identity cache so output reads as
human names instead of raw QQ numbers.

Before:
  [Event] 群撤回 12345 | 67890 被 99999 撤回
  [Event] 群 12345 | NickName(67890): ID:42 你好 [图片]

After:
  [Event] 群撤回 [SnowLuma群(12345)] | [Alice(67890)] 被 [Bob(99999)] 撤回
  [Event] 群 [SnowLuma群(12345)] | [Alice(67890)]: ID:42 你好 [图片]

Reply segments now expand one level via messageStore.findEvent —
"[回复:42]" becomes "[回复 [Alice(100)]: 早安]" when the original
is still in the message store, falling back to the bare id when it
isn't.

New file utils/event-format.ts owns:
  - formatGroup / formatUser     identity-aware name resolution
  - formatMessageSegments         shared element preview (replaces
                                  the inline switch in
                                  logReceivedMessage)
  - formatReply                   one-level reply chain expansion
  - formatEvent                   notice-class event renderer

Every formatter wraps its lookup in try/catch and degrades to the
prior numeric form on cache miss / throw, so log formatting can
never crash the calling path. The QQ numeric ID is preserved
alongside the name so third-party parsers that scrape uids still
find them.

26 unit tests cover cache hit / miss, malformed input, throw
recovery, and per-event-kind rendering shapes.
2026-05-18 12:32:18 +08:00
DrSmoothl
84e746c278 chore(observability): defensive depth pass
Two related cleanups so unexpected failures stop being invisible:

void-promise wrappers
  Every `void this.something()` fire-and-forget call now has a
  .catch(err => log.warn(...)) attached. Affected sites:
    - packet-pipeline.ts: dispatchAfterIdentityRefresh
    - instance.ts: openAll / applyConfigDiff / closeAll / emitEvent
    - http-post-adapter.ts: postEvent
    - ws-client-adapter.ts: handleApiMessage
  Most of the network-manager fan-outs already isolate per-adapter
  errors, but the outer catches guard against future refactors and
  surface stack traces immediately rather than as unhandled rejection
  warnings.

silent-catch sweep (Bridge.Web)
  bridge/web/group-honor.ts, group-essence.ts, group-notice.ts had
  `} catch (e) { return undefined; }` patterns that turned every QQ
  Web API failure into a silent empty response. Now log.warn with
  the full stack first, then return the same fallback so behavior is
  unchanged. The commented-out `// console.error(e)` debris is gone.

Plus one console → logger conversion in message-parser.ts (music
sign fallback path).
2026-05-18 01:36:12 +08:00
DrSmoothl
7ec479bb88 feat(logger): protocol-layer observability for highway and msg-push
Highway upload path now emits per-type entry + shared pipeline ops:

  DEBUG [Highway.Image]  uploading 234567 bytes md5=abc12345... → group 12345
  DEBUG [Highway]        image OIDB requires bytes, PUT 234567 bytes (sub=top)
  DEBUG [Highway]        image PUT done in 1234ms
  -- or --
  DEBUG [Highway]        image fast-upload hit (server already had bytes)

The three pipeline-side lines come from runNtv2Upload() and are
shared across image/video/ptt; the per-type entry log lives in each
*-upload.ts wrapper so the scope identifies the media kind. md5 is
truncated to its first 8 hex chars for line width; PUT latency is
reported in ms.

MsgPush silent dispatch defaults are now visible at debug:

  DEBUG [MsgPush.Unknown] no decoder for PkgType=999 subType=0
  DEBUG [MsgPush.Unknown] Event0x2DC unknown subType=42
  DEBUG [MsgPush.Unknown] Event0x210 unknown subType=42

Captures protocol drift (new NT QQ subtypes) and "we forgot to
register this PkgType" oversights, neither of which used to leave
any trace in the log.

All new lines are debug-level so console output (default info) stays
unchanged; file transport sees them for post-mortem.
2026-05-18 01:29:06 +08:00
DrSmoothl
1ba45e2659 feat(logger): observability for OneBot action dispatch
Every OneBot action call now emits a single debug line under
[Bridge.Action]:
  DEBUG [Bridge.Action] send_group_msg group_id=12345 message=[len=3]

On failure, dispatch logs a warn with the full stack instead of
silently folding the error into the response. Unknown actions also
get a debug entry so "the bot is ignoring me" is no longer invisible.

Notes:
- New summarizeParams() helper caps each value at 40 chars / line at
  200 chars to keep arrays / nested payloads from blowing the line
  width. Lives in utils/log-summary.ts for reuse (highway will too).
- ApiHandler now takes an optional uin and binds a child logger so
  per-account file routing works. OneBotInstance passes its parsed
  uin.
- Control-char strip in logger/file-transport was exempting only ESC;
  also exempt TAB (0x09) and LF (0x0A) so stack traces stay
  multi-line in both console and file output.
- vitest.config sets SNOWLUMA_LOG_LEVEL=debug so the ring buffer
  receives the new debug entries that tests assert on.
2026-05-18 01:19:30 +08:00
DrSmoothl
1d66693cc3 refactor(logger): bind per-account loggers in target classes
Switches the per-account classes from module-level loggers to
per-instance ones derived via Logger.child({ uin }) so their log
lines land in both the shared file and the account's logs/<uin>/
sub-file, and the [UIN] slot appears in console output:

  - IdentityService            (Identity scope)
  - IncomingPacketPipeline     (Bridge + Event scopes)
  - OneBotInstance             (Event scope)
  - HttpServerAdapter          (OneBot.HTTP)
  - HttpPostAdapter            (OneBot.POST)
  - WsClientAdapter            (OneBot.WS-Client)
  - WsServerAdapter            (OneBot.WS-Server)

The standalone printEvent() in packet-pipeline now takes a Logger
argument so it routes through this.eventLog instead of a captured
module-level reference. Behavior unchanged otherwise; bridge.ts,
bridge/manager.ts and process-level scopes (App / WebUI / Hook /
OneBot.Config) keep their module-level loggers since they aren't
bound to a single account.
2026-05-18 00:57:46 +08:00
DrSmoothl
93b9b03667 feat(logger): add .child({ uin }) API and per-UIN file fan-out
Logger now supports deriving a UIN-bound child:
  const log = createLogger('Bridge');
  this.log = log.child({ uin: this.uin });

The child stamps a fixed-width [UIN] slot into rendered lines so the
[Scope] column stays vertically aligned, and routes the same line to
a per-UIN sub-file:
  logs/snowluma-YYYY-MM-DD.log       (shared, all UINs)
  logs/<uin>/snowluma-YYYY-MM-DD.log (per-account)

Both pathways share daily rollover, size cap, and retention.
LogEntry now carries uin so SSE subscribers (WebUI) can filter later.

Other meta keys passed to child() are preserved in opts.meta for
forward compat (requestId / traceId etc.) but not rendered yet.

Module-level callers are unchanged; no callsites migrated in this PR.
SNOWLUMA_LOG_PER_UIN=0 disables the per-account sub-file while
keeping the shared one.
2026-05-18 00:50:15 +08:00
DrSmoothl
51f46e15fd feat(logger): add file transport with daily rotation and size cap
Adds a hand-rolled FileTransport that fans out every log line (debug
and up, regardless of console filter) to
./logs/snowluma-YYYY-MM-DD.log. When the current file exceeds the
configurable size cap it rolls into snowluma-YYYY-MM-DD.1.log, and
files older than the retention window are unlinked at startup and on
each day rollover.

Config (all env, no settings.json):
- SNOWLUMA_LOG_FILE      0 to disable file output (default: on)
- SNOWLUMA_LOG_DIR       output directory       (default: ./logs)
- SNOWLUMA_LOG_MAX_MB    per-file cap, MB       (default: 50)
- SNOWLUMA_LOG_RETAIN_DAYS retention window     (default: 7)

closeLogger() awaits the WriteStream's finish event; SIGINT and
SIGTERM handlers now await it before process.exit so the buffer
makes it to disk.

vitest config sets SNOWLUMA_LOG_FILE=0 to keep the suite from
polluting cwd; the new tests under tests/log-file-transport.test.ts
flip it back on per-test against a tmpdir.
2026-05-18 00:44:30 +08:00
DrSmoothl
c6f4d5c5a2 chore(release): v1.8.3 2026-05-18 00:10:43 +08:00
DrSmoothl
82b52a3b2d update README 2026-05-18 00:10:12 +08:00
DrSmoothl
360fe8bd49 fix(forward): carry image/video in private merged forward
For a private send_private_forward_msg, the inner image/record/video
needs an OIDB upload scene — but uploadForwardNodes never received the
recipient, so the SendContext fell back to {bridge} only and the
element builder threw "private image target uid is missing".

Plumb userId through uploadForwardNodes → buildForwardPushBody and,
when the nodes contain media, resolve it to a uid via
bridge.resolveUserUid() once up-front. Group forwards are unchanged
(they already passed groupId). Mirrors NapCat's design where the
destination peer is threaded all the way down to createSendElements.
2026-05-17 23:47:12 +08:00
DrSmoothl
90884dfbb1 chore(release): v1.8.2 2026-05-17 19:28:58 +08:00
DrSmoothl
37dd7d2173 fix(webui): rotate stale bootstrap password and highlight credentials log
If the operator never completed the forced-change flow, the plaintext
bootstrap password was unrecoverable on the next start (only the hash
remained on disk, and the prior log line was likely gone). Now we
detect a persisted state with mustChangePassword=true at load time and
generate a fresh CSPRNG password so the operator can actually log in.

The initial-credentials log block is also wrapped with separators and
a bilingual notice so it stands out at boot. The
'initial credentials: user=admin password=%s' line is preserved
verbatim because third-party launchers parse it.
2026-05-17 18:20:05 +08:00
DrSmoothl
0c5eef87e6 ci: publish @snowluma/ui to npm on push to main
Mirror of sdk-npm-publish.yml for the UI package. Same triggers
(packages/ui/** + lockfile/workspace/tsconfig.base) and same
already-published guard via `npm view`, so reruns are idempotent.

Differences from the SDK workflow:
- Drops the `test` step (UI package has no Vitest suite yet).
- Filters and working-directory point at packages/ui.

Auth uses the same `NPM_TOKEN` secret in the SnowLuma environment.
Publishes with `--provenance` so the npm registry attests the build
came from this exact GitHub Actions run.
2026-05-17 17:24:21 +08:00
DrSmoothl
0d54fd83c6 feat(ui): add --titlebar-height token for Desktop's frameless window
Desktop is switching from the native Windows titlebar to a custom one
rendered in the renderer (frameless BrowserWindow + custom Min/Max/Close).
The bar is 32px tall — the same height Windows draws its system
titlebar — so expose it as a token here for any future Desktop layout
that needs to subtract it.
2026-05-17 16:49:27 +08:00
DrSmoothl
b3e37e2f7c feat(ui): add indeterminate mode to Progress
Desktop's core-download dialog needs to show progress while the server
returns no Content-Length (some mirrors omit it; the SnowLuma core
release artifact does have it but GitHub's CDN sometimes strips it on
redirects). Hard-coded 50% was a placeholder.

Add an `indeterminate` boolean prop: when true, render a marquee bar
that animates left-to-right indefinitely. When false, render the
familiar bytes-done / bytes-total fill at `value%`. Hooked up via a new
`@keyframes progress-marquee` in theme.css.

Also dropped the bar's CSS transition from 500ms → 200ms so live
download updates feel responsive instead of laggy.
2026-05-17 16:31:30 +08:00
airline233
b441647df4 feat(http-server): support parse content-type of urlencoded 2026-05-17 15:27:43 +08:00
DrSmoothl
d7252b6c31 feat(ui): Button success/warning variants + active translate + icon-xs
Polish pass that an earlier edit lost:

- Add `success` and `warning` button variants (semantic colour pairs
  consumers can reach for in confirm dialogs / status actions).
- Outline gets a real card background + shadow so it pops on tinted
  surfaces (previously bg-transparent looked invisible on muted/40 rows).
- Tighter motion: explicit transition list + `active:translate-y-px` so
  clicks feel mechanical.
- New size `icon-xs` for inline action buttons that need to fit in a
  log-row toolbar without ballooning the row height.
- Default radius bumped to `rounded-lg`; sm stays `rounded-md`.
2026-05-17 14:42:29 +08:00
DrSmoothl
593f5f42bc fix(ui): Dialog and Select no longer overflow at narrow widths
CSS grid's default `min-width: auto` per track was letting long
selected-option text and file paths inside dialogs push the container
past its `max-w-lg` cap, which on Windows / smaller viewports clipped
the right edge of inputs and the Select chevron.

- DialogContent / AlertDialogContent: `grid-cols-[minmax(0,1fr)]` clamps
  the single track to its container width; `w-[calc(100%-2rem)]` keeps
  a 1 rem gutter to the viewport edge on small screens.
- SelectTrigger: `min-w-0` on the trigger itself plus a child-targeted
  truncate (`[&>span:not([data-radix-select-icon])]:truncate`) so the
  selected text shrinks before the chevron does; chevron gets `shrink-0`
  for the same reason.
2026-05-17 14:24:09 +08:00
DrSmoothl
8a94188dc6 fix(ui): dark-mode Switch + Checkbox visibility
Both controls used `bg-muted` / `bg-background` for unchecked / thumb
which collapse to the same hue as the surrounding card in dark mode,
making them effectively invisible.

- Switch: unchecked track now bg-input (light) / bg-muted-foreground/25
  (dark) with a shadow-inner; thumb uses bg-card (light) /
  bg-foreground/95 (dark) so it pops in both states.
- Checkbox: explicit bg-card + hover:border-border/80; slightly larger
  radius (5px) for visual rhythm with the rest of the surface.
2026-05-17 14:11:29 +08:00
DrSmoothl
3e943e8f0d feat(ui): refresh theme tokens + add Popover/StatusDot/EmptyState/Kbd
Visual overhaul to give @snowluma/ui a coherent, accessible identity.

Tokens (styles/theme.css)
- Deeper dark-mode surface ramp with more contrast between background /
  card / popover so dropdowns and dialogs read clearly in dark mode
- New radius scale (xs → 3xl) anchored at 0.625rem for tighter feel
- Layered shadow tokens (xs/sm/md/lg/xl) that adapt to mode
- Semantic success / warning / info / destructive colour + foreground
  pairs replacing ad-hoc lookups
- `--chrome-height` (52px) for consistent top-bar / sidebar header height
- Utilities: `hover-lift`, `surface-glass`, `surface-gloss`; consumer-
  scoped scrollbar styling so native scrollbars match
- Note: consumers must also `@import "tw-animate-css";`

Components
- Select: solid bg-popover + ring-1 ring-foreground/5; rotating chevron
  on open state; rounded-xl menu with shadow-xl (fixes the transparent
  dropdown bug)
- Dialog / AlertDialog: bg-popover + ring; backdrop-blur on overlay;
  slide-in motion
- Tooltip: ring + zoom-in motion, max-w-xs for long labels
- Button: explicit transition list with active:translate-y-px; success /
  warning variants; icon-xs size
- Input: hover border + focus ring + aria-invalid handling
- Card: tighter line-height + typography
- Badge: variants for success / warning / info / soft, size scale
- ScrollArea: hover-only mode by default, slightly thicker thumb

New components
- Popover (radix wrapper) — for menus / inline overlays
- StatusDot — semantic colored dot (replaces ad-hoc 🟢/🟡/🔴 emoji)
- EmptyState — uniform placeholder for "nothing here yet" surfaces
- Kbd — inline keyboard-key label
2026-05-17 13:56:11 +08:00
DrSmoothl
af1c50f4e7 feat(compat): add QQ compatibility manifest
Static JSON served from raw.githubusercontent.com/.../main/compat/qq.json
that SnowLumaDesktop polls (3-day cached fallback) to classify the local
QQ install as known-good / known-bad / unknown / too-old.

- compat/qq.json — initial allow-all manifest (policy.allowUnknown=true)
- compat/qq.schema.json — JSON Schema for the manifest shape

Editing this file is how we ship "QQ X.Y.Z breaks Hook" advisories
without cutting a Desktop release.
2026-05-17 00:24:10 +08:00
DrSmoothl
bc9f7b49be feat(core): support env-var overrides for webui port and bootstrap password
Two additions for trusted local launchers (notably SnowLumaDesktop) to
configure core without writing to disk-shared config:

- SNOWLUMA_WEBUI_PORT overrides runtime.json's webuiPort at startup
  without persisting; CLI/Docker users continue to drive it from the
  file. Mirrors the existing SNOWLUMA_HOOK_RUNTIME_DIR / *_TRUST_PROXY
  conventions.
- SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD seeds the initial WebUI password on
  first launch (when webui.json doesn't yet exist), with
  mustChangePassword=false. After the file is persisted the env var is
  ignored — password rotation continues through the UI.
2026-05-17 00:23:55 +08:00
DrSmoothl
a8661ea216 feat(ui): add @snowluma/ui shared UI library
Lifts the shadcn primitives + Tailwind 4 theme tokens from webui into a
dedicated workspace package consumable by both webui and SnowLumaDesktop.

- 14 primitives (Button, Dialog, AlertDialog, Input, Label, Checkbox,
  Select, Switch, Tabs, Card, Avatar, Badge, Progress, ScrollArea,
  Separator, Sheet, Skeleton, Tooltip) + sonner Toaster wrapper
- Tailwind 4 theme tokens exported via styles/theme.css
- tsup ESM build with declaration files
- publishConfig.access=public mirroring @snowluma/sdk

Consumers @import '@snowluma/ui/styles/theme.css' for tokens and add an
@source directive to scan the package for utility classes.
2026-05-17 00:23:37 +08:00
DrSmoothl
2d21316a74 fix(onebot): bound download_file and drop unused error helper
PR #39 hardened most of the OneBot action surface but left download_file
on the original `await response.arrayBuffer()` path — an authenticated
client could still hand us a multi-GB URL (or a chunked response with no
Content-Length) and OOM the bot. The base64 branch had the same problem
in the other direction: `Buffer.from(huge, 'base64')` allocates the
decoded payload before any size check.

Match the loadBinarySource pattern that `0804351` introduced for
highway uploads:

* HTTP path runs through `fetchDownloadFile`: AbortSignal.timeout
  (60s), Content-Length precheck, then a streaming reader that aborts
  the moment the running total crosses the 1 GiB cap.
* Base64 path rejects before `Buffer.from` based on the
  upper-bound `floor(len * 3 / 4)`, with a post-decode check for
  safety.
* Writes go through `fs.promises.writeFile` so a multi-hundred-MB
  download doesn't stall every other bot action on the event loop.

Also drop the `actionFailed` helper added in the same PR — it was
intended as a sanitized-error wrapper but never wired up. Wiring it
into the dozen-or-so `String(e)` sites is its own cleanup; for now
remove the dead code (and the no-longer-used createLogger import).
2026-05-16 21:49:32 +08:00
时瑾
ffe0c57abf feat(webui): add SNOWLUMA_WEBUI_TRUST_PROXY for reverse-proxy deploys
The previous commit tightened login rate-limiting to key off the real
TCP socket peer, which fixed the X-Forwarded-For bypass but had the
known caveat of collapsing every client into a single global bucket
when the WebUI runs behind nginx / Caddy / a SaaS CDN.

Give operators an explicit, audited way to opt back into per-client
keying without re-introducing the spoof:

* `SNOWLUMA_WEBUI_TRUST_PROXY` env var. Modes:
    - unset / empty     → keep socket peer (safe default, unchanged)
    - "loopback"        → trust X-Real-IP / X-Forwarded-For when the
                          immediate socket peer is 127.0.0.1 / ::1
                          (nginx + WebUI on the same host)
    - "1" / "true" /    → trust headers from any peer (only safe behind
      "all"               a SaaS proxy that strips client-set headers)
    - comma-separated   → trust headers only when the socket peer
      IP list             matches one of these (proxy on another box)

* When trusting headers we prefer X-Real-IP (single value the proxy
  overwrites unconditionally) and fall back to the first hop of XFF.
  We deliberately do NOT walk the full XFF chain — without a fully
  trusted proxy chain the leftmost value is still spoofable; a
  single-tier proxy is the only setup this app realistically sees.

* Boot log prints "login rate-limit keyed by: …" so operators can
  verify the mode took effect, plus an extra WARN for "all" reminding
  them it's only safe with header-stripping in front.

Logic lives in webui/client-ip.ts as a pure pickClientIp() that takes
a socket-IP resolver, so the trust-proxy matrix can be exercised
without standing up a server — see webui-client-ip.test.ts for the
11 new unit tests covering parse + dispatch + loopback / list / all /
none modes.

Smoke-tested with SNOWLUMA_WEBUI_TRUST_PROXY=loopback:
  - 5× failed login w/ X-Forwarded-For: 1.1.1.1 → 401
  - 6th attempt same XFF → 429 (locked, per-XFF)
  - 6th attempt X-Forwarded-For: 2.2.2.2 → 401 (fresh bucket)
  - X-Real-IP overrides XFF when both present
2026-05-16 21:31:54 +08:00
时瑾
d66f0b2c6b fix(bridge): point at file-upload actions in video-too-large error
QQ's short-video element protocol hard-limits a single video at 100 MB
(NapCat enforces the same cap in highwayContext.uploadVideo with the
same threshold and tells operators to switch to file upload). Mirror
that hint so OneBot bot authors who hit the cap immediately see the
correct alternative — `upload_group_file` / `upload_private_file`,
which ride the FtnUpload path and go up to 4 GiB — instead of having
to read the docs to figure out why a send_msg with a 200 MB video
silently 'won't work'.
2026-05-16 21:31:54 +08:00
时瑾
b40cee18cc fix(bridge): close two binary-size cap gaps flagged by review
Follow-up on the previous highway commit, addressing two real holes the
Copilot review caught:

* loadBinarySource HTTP path was buffering the entire response via
  `await resp.arrayBuffer()` BEFORE length-checking. A server that omits
  or understates `Content-Length` (chunked transfer, malicious upstream,
  proxy stripping headers) bypassed the cap entirely. Switch to a
  streaming reader: accumulate chunks, abort + reject as soon as the
  running total exceeds `maxBytes`. The Content-Length precheck still
  short-circuits the obvious case before we read a byte.
* video-upload `stageVideoSource` has its own local-path fast-path that
  never went through `loadBinarySource`, so the 100 MB MAX_VIDEO_SIZE
  guard ran AFTER `fs.readFileSync` had already allocated the entire
  file. A 10 GiB local-file pointer would OOM the bot before the check
  fired. Add an `fs.statSync` precheck on the local branch, and pass
  `MAX_VIDEO_SIZE` explicitly when the source falls through to
  `loadBinarySource` so the HTTP / base64 cap matches the on-disk one.

Update the DEFAULT_MAX_BINARY_SIZE comment to stop claiming video paths
are bounded by it — they're bounded by the smaller MAX_VIDEO_SIZE,
enforced inside video-upload.

Adds five regression tests:
  - chunked streamed download (no Content-Length) over cap → throws
  - Content-Length over cap → throws before reading body
  - streamed download inside cap → returns full bytes
  - local file over cap (statSync precheck) → throws
  - base64 over cap → throws
2026-05-16 21:31:54 +08:00
时瑾
b3df633c87 fix(bridge): correctness pass on highway, hook, and identity service
* highway/utils detectImageFormat: JPEG SOF marker check now excludes
  0xC4 (DHT), 0xC8 (JPG), and 0xCC (DAC). The old `(marker & 0xFC) ===
  0xC0` matched DHT et al. and then read Huffman table bytes as image
  dimensions, producing junk width/height for many real JPEGs.
* loadBinarySource takes an optional maxBytes; defaults to 1 GiB to
  defend against an authenticated client triggering a multi-GB load
  into memory. Group/private file uploads pass FILE_UPLOAD_MAX_BYTES
  (4 GiB) because QQ's file protocol legitimately supports that size.
  HTTP fetches also pick up a 60s timeout and a Content-Length precheck.
* highway-client.tcpConnect detaches its error/timeout listeners after
  a successful connect so subsequent upload IO errors don't reject an
  already-resolved promise. readHttpResponseBody uses local listener
  refs + a central detach(), eliminating MaxListenersExceededWarning
  during multi-chunk uploads.
* hook/qq-hook-client.nextRequestId now wraps inside uint32 explicitly
  and skips id 0 / in-flight ids. The previous `nextRequestId++ >>> 0`
  loses precision past Number.MAX_SAFE_INTEGER (postfix increment
  evaluates before the shift) and could collide live request ids on
  very long-running processes.
* identity-service.rememberUidUin removes stale partner entries before
  inserting a new (uid, uin) pair. The old code left orphan uidByUin /
  uinByUid entries after a uid/uin re-bind, so the two maps could
  disagree.
2026-05-16 21:31:54 +08:00
时瑾
b2c53b56f7 fix(onebot): correctness pass on actions and message parser
Action-layer fixes, all cross-checked against NapCat's reference
implementation in packages/napcat-onebot:

* download_file (extended.ts:539) now sanitizes `name` via
  path.basename + resolve/relative containment check. Previously an
  authenticated client could write `../../config/onebot_<uin>.json`
  and replace access tokens / webhook URLs.
* mark_group_msg_as_read / mark_private_msg_as_read / mark_msg_as_read
  fall back to meta.targetId when the optional group_id/user_id arg
  is missing. The old code passed 0 to the Bridge. NapCat resolves the
  peer from message_id alone in MarkMsgAsRead.ts; we now match that.
* set_friend_remark / set_group_remark refuse a missing `remark` field.
  The previous `asString(...) ?? ''` silently CLEARED the remark for
  any client that forgot the parameter. NapCat's typebox schema makes
  `remark` required; we now do the same.
* upload_forward_msg threads `group_id` down to uploadForwardNodes so
  the resulting resId lives in the correct namespace (type:3 + groupUin
  vs type:1 + selfUid — see bridge/actions/forward.ts). NapCat passes
  `peer.chatType === GROUP ? +peerUid : 0` for the same reason.
  ApiActionContext.sendForwardMsg + uploadForwardMessage signatures
  pick up an optional groupId.
* Private-message reply meta now resolves senderUin from the cached
  event (real sender), with a self-id fallback when only meta exists
  (bot's own outbound message — `cacheMessageMeta` does not populate
  the event row). The old code used meta.targetId, which is the
  conversation peer — wrong when the bot replies to its own message.
* message-parser:
    - intOr(value, fallback) helper replaces parseInt(String(...)) at
      face/at/reply/image/xml/poke/node sites so non-numeric input no
      longer produces NaN downstream. Invalid face ids skip the
      element rather than emit NaN.
    - cqUnescape decodes `&#44;` (escaped comma) — the OneBot 11 spec
      requires it and clients in the wild emit it.
* Drop the dead Array.isArray(rawAuth) branch in onebot/network/utils
  (Node's headers.authorization is `string | undefined`, never an
  array) and the unused WebHonorType import in api-handler.
2026-05-16 21:31:34 +08:00
时瑾
917f08ce4d fix(webui): tighten auth handling and remove read-side write effects
Stack of WebUI fixes prompted by an internal security/correctness pass:

* getClientIp now resolves the real socket peer via @hono/node-server's
  getConnInfo helper instead of trusting `X-Forwarded-For`. The previous
  behaviour let any client rotate that header to bypass the 5-attempts/
  15-minute login lockout.
* `?token=` is restricted to /api/logs/stream (the only endpoint that
  can't use the Authorization header, because EventSource lacks custom
  headers). Other routes used to leak tokens via access logs / Referer
  / browser history.
* change-password now invalidates every session (including the current
  one) and signals requireRelogin. Keeping the current token alive made
  the rotation pointless if the old credentials were already in an
  attacker's hands.
* GET /api/config/:uin no longer writes defaults to disk and no longer
  doubles up the payload (`{config}` only, dropping the {…config, config}
  legacy shape). Frontend's `data?.config ?? data` fallback still works.
* webui.json is moved to .bak.<ts> instead of being silently overwritten
  when it fails to parse — losing the prior hash silently was rotating
  operator credentials with no warning.
* Process load/unload/refresh routes are deduped into a single helper;
  internal error messages are logged but no longer surfaced verbatim to
  the client.
* SSE log stream tolerates a closed controller (try/catch around enqueue
  + central teardown) and runs an unref'd janitor to GC expired session
  tokens + login attempt counters every minute.
2026-05-16 21:31:28 +08:00
时瑾
2c80e1a267 refactor(onebot): make loadOneBotConfig read-only by default
GET on a load helper used to mint a fresh access_token and write it to
disk whenever the per-UIN file was missing or in legacy format. Reading
should not have side effects, and the WebUI's read-only GET handler in
particular was racing on concurrent requests and surprising operators
with materialized config files.

Introduce a `{ persistDefaults?: boolean }` option (default false). The
two boot-time call sites in `OneBotManager` (onSessionStarted, reloadConfig)
opt in explicitly; WebUI's GET path will rely on the new default once
that side of the patch lands.

Also stop reviving default 0.0.0.0 listeners when the operator has
explicitly emptied every adapter — only seed defaults on a true fresh
install (no per-uin and no global config on disk).

Drop the unused deepClone / deepMerge helpers; tryLoadJson now logs a
warning instead of silently swallowing JSON parse errors.
2026-05-16 21:31:28 +08:00
时瑾
655af833dc fix(send): keep c2c video compatQMsgSceneType at 2 (#38)
Commit 29f28d6 changed c2c video `compatQmsgSceneType` from 2 to 1
as a "symmetric asymmetry" cleanup, matching the image/ptt convention
where the field tracks the upload's sceneType (c2c=1, group=2). For
video this is wrong.

Image and ptt have *different* legacy compat elements per scene
(notOnlineImage vs customFace; ptt c2c vs group), so the server needs
to know which scene shape to emit. The legacy `videoFile` element
(packet element type 19) has no scene split — fromChatType /
toChatType live inside the element itself — so the QQ NT server
emits a single group-shaped compat payload regardless. NapCat
hardcodes `compatQMsgSceneType: 2` for *both* UploadGroupVideo and
UploadPrivateVideo for exactly this reason.

Setting it to 1 on c2c made the server emit a c2c-scene shaped
compat blob that older QQ clients failed to resolve, showing the
message as "视频已过期" on those receivers. Newer clients only read
the commonElem(48, 11) and displayed fine — which is why only "some
devices" saw the breakage.

Keep `commonElem.businessType = isGroup ? 21 : 11` untouched — that
piece of 29f28d6 is still correct and is what fixed PbSendMsg
result=79.
2026-05-16 14:51:13 +08:00
H3CoF6
e2ee528939 fix: address P0 and P1 issues from code review
- P0-1: restore customExt field in SetStatusReqSchema
- P0-2: remove duplicate setGroupAvatar implementation
- P1-3: add attach_info pagination support for get_group_album_media_list
- P1-5: clean up commented console.log statements
- P1-6: remove raw field from GroupAlbumMediaResult
2026-05-16 14:33:42 +08:00
H3CoF6
c58f4d4085 fix: fix group album upload error 2026-05-16 13:34:02 +08:00
H3CoF6
16bdf1be1e Fix merge conflict and remove one group avatar implement 2026-05-16 12:39:00 +08:00
H3CoF6
0401ac4afb feat: implement some group album actions 2026-05-16 12:17:23 +08:00
DrSmoothl
ad65aa5b1b fix(send): resolve at-mention display name from the group roster
OneBot clients commonly send [CQ:at,qq=12345] without a name field; we
were piping `@12345` into the text element so QQ rendered the bare uin
instead of the member's card/nickname (napcat resolves via getGroupMember
before encoding). Move the fallback into the element builder so it
consults the IdentityService roster and only falls back to the uin when
the roster has nothing.
2026-05-16 11:55:36 +08:00
DrSmoothl
a1a49944df refactor(webui): migrate routing to TanStack Router
The four-page switch lived as a string union (Page) plus an if/else
chain in AppInner, with TopBar reverse-importing Sidebar's NAV_ITEMS
to find the icon for the active tab. Adding a page touched four
places and there was no URL, no history, no deep-linking.

Move routing behind @tanstack/react-router with a layout route
(AppLayout) that owns the polling lists, processOps, selectedUin
and the unload-failed alert; child routes render through <Outlet/>
and read shared state from a new AppStateContext. AuthBoundary still
gates login / forced-password-change above the router. Sidebar uses
<Link> + useRouterState for active state; TopBar and MainLayout look
up the current path the same way.

Behaviour-preserving:
- LoginPage / ChangePasswordPage still mount above the router.
- AppLayout never unmounts during navigation, so selectedUin,
  processOps state, the polling state and the unload-failed dialog
  all survive page switches just like before.
- Logout calls history.replaceState('/') so the next login lands on
  the overview page, matching pre-router behaviour.
- The sidebar-active-pill layoutId animation and the page-transition
  AnimatePresence are preserved, keyed off pathname instead of the
  removed `active` prop.

New URLs (/, /config, /logs, /settings) work on refresh because the
backend already had SPA fallback in core/src/webui/server.ts. Bundle
grows ~84KB (gzip +27KB) for the router runtime.
2026-05-16 02:35:49 +08:00
DrSmoothl
caf724b25c fix(webui): preserve config edits on save and UIN choice across tabs
Two regressions slipped into the ApiClient/ConfigPage refactor:

1. api.config.save() ran the POST response through normalizeOneBotConfig
   and used it to overwrite local state. But POST /api/config/:uin
   returns { success, reloaded, message } — no config body — so the
   normaliser produced an empty config and wiped the user's edits as
   soon as the save succeeded. Honour the "save returns canonical view"
   contract by following the POST with a GET inside the client; the
   round-trip stays hidden behind the seam.

2. selectedUin lived inside useOneBotInstanceConfig, so navigating away
   from ConfigPage unmounted the hook and lost the user's selection.
   Lift selectedUin to AppInner and make the hook externally controlled
   via { selectedUin, onSelectedUinChange }. Clear it on logout.
2026-05-16 02:22:48 +08:00
DrSmoothl
7cef104f93 refactor(webui): deepen Hook process ops behind a single seam
App.tsx held three copy-pasted handlers (load / unload / refresh) and
three parallel processXxxPid state slots that were mutually exclusive
but unenforced by the type system. The unload-failed alert was a
separate path, and OverviewPage needed 11 props to drive the table.

Extract useHookProcessOps: one inflight Set for dedup, one Map<pid,
OpKind> for view state, one run() that branches on kind via a
message table, and ownership of the unload-failed alert. OverviewPage
takes a single HookProcessOps prop and queries statusOf(pid).

App.tsx 270 → 216 LOC; OverviewPage props 11 → 7.
2026-05-16 02:13:09 +08:00
DrSmoothl
b89d51d984 refactor(webui): extract ApiClient + lift OneBotInstance config editor
App.tsx was the single source of truth for token, fetch policy, 401
handling, and per-UIN config edit state — fetchApi was drilled into
every page and LogsPage read localStorage directly to build its SSE
URL, giving two parallel truths for the bearer token.

Promote the closure to a deep ApiClient module (domain methods +
request() escape hatch) injected via ApiProvider/useApi, and lift
selectedUin/config/saveStatus into useOneBotInstanceConfig so
ConfigPage is self-contained. normalizeOneBotConfig becomes a pure
function. ConfigPage now guards UIN switches when the editor is
dirty and refetches the server-normalised config after save.

ConfigPage prop count drops from 7 to 1; App.tsx from 421 to 270 LOC.
2026-05-16 02:04:11 +08:00
DrSmoothl
47921eee12 fix(sdk): catch up SNOWLUMA_ACTIONS with the 14 new core actions
`actions-sync.test.ts` walks every `registerAction(...)` in
`@snowluma/core/src/onebot/actions/` and asserts the SDK's exported
list matches. The napcat-parity work (Tier 1 + Tier 2 + Tier 3 + AI
voice) added 14 actions to core without ever touching the SDK, so the
test caught the drift:

  bot_exit              cancel_group_todo
  complete_group_todo   delete_group_folder
  get_ai_characters     get_ai_record
  get_group_ignore_add_request
  nc_get_packet_status  nc_get_rkey
  nc_get_user_status
  send_group_ai_record  send_packet
  set_diy_online_status set_group_todo

Added them to `SNOWLUMA_ACTIONS` and gave each one a typed
`SnowLumaActionMap` entry. Where the request body shape is non-trivial
(AI voice, group todo, DIY status, send_packet, nc_get_user_status),
introduced dedicated param types in `types/params.ts`; where the
response is structured (AI character list, user-status word),
introduced result types in `types/results.ts`. Everything else routes
through `JsonObject` / `EmptyData` so the SDK surface stays small.

Verified:
  pnpm --filter @snowluma/sdk typecheck → clean
  pnpm --filter @snowluma/sdk test      → 17/17 pass
2026-05-16 00:39:32 +08:00
DrSmoothl
7da52bc591 chore(release): v1.8.1 2026-05-15 23:17:44 +08:00
DrSmoothl
29f28d611f fix(send): use c2c businessType for private video / record
Private-chat video and voice sends were getting bounced by the QQ NT
server with `PbSendMsg result=79`. Highway upload logs said success,
but the final SendMsg the bot constructed used the group-scene tag
inside the outgoing commonElem, and the c2c routing path doesn't
recognise it.

The convention — verified against the receive-side decoder at
msg-push/rich-body-decoder.ts:261-330 which explicitly branches on the
pairs — is:

  image  : commonElem.businessType  c2c=10  group=20
  video  : commonElem.businessType  c2c=11  group=21
  record : commonElem.businessType  c2c=12  group=22

makeImageElem already honoured the split (`isGroup ? 20 : 10`).
makeVideoElem and makePttElem hardcoded the group value for both
scenes. Fix them to follow the same pattern.

Also fix a symmetric asymmetry inside the highway upload itself:
uploadVideoMsgInfo hardcoded `compatQmsgSceneType: 2` while
uploadImageMsgInfo and uploadPttMsgInfo both use `isGroup ? 2 : 1`.
Same root cause — group value leaking into the c2c path.

Regression test (tests/element-builder.test.ts) pins all six
businessType pairs by mocking the highway upload functions and
inspecting the proto element the builder returns; would have caught
the bug had it existed at the time element-builder.ts was written.
2026-05-15 22:56:15 +08:00
DrSmoothl
97ad2e22bb feat(onebot): implement set_group_portrait via highway cmdId 3000
Port the Lagrange.Core protocol path for group avatar upload —
napcat's NTQQ GroupService.setHeader has no oidb wrapper, but
Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs
spells out the wire shape: same highway HTTP endpoint as personal
avatar, but with cmdId=3000 and a GroupAvatarExtra proto carried as
the `extend` blob (type=101, groupUin, field3={field1=1}, field5=3,
field6=1 — all four are protocol-prescribed constants).

Adds:
- GroupAvatarExtraSchema in proto/oidb-action.ts
- bridge.setGroupAvatar(groupId, source) wrapping the highway upload
- BridgeInterface.setGroupAvatar
- OneBot set_group_portrait action (was a stub returning
  'not yet implemented'; accepts the same file-source variants as
  set_qq_avatar)

5 new tests: 3 bridge-action (cmdId, extra-blob round-trip, empty-file
guard) + 2 OneBot (forwarding, param validation) — also tightens the
existing setAvatar test to assert the extend blob stays empty.
2026-05-15 19:47:35 +08:00
DrSmoothl
f7457e3e59 feat(onebot): add set_diy_online_status
DIY online status reuses the existing StatusService.SetStatus wire
call. napcat hardcodes status=10 / extStatus=2000 and threads the
faceId / wording / faceType through a customExt sub-message (field 4
of SetStatus, per napcat packet/transformer/proto/action/action.ts).

Implementation:
- Extend SetStatusReqSchema with optional customExt field. Encoder
  skips undefined fields so the existing set_online_status path stays
  byte-identical on the wire (verified by a new round-trip test).
- New bridge.setDiyOnlineStatus(faceId, wording, faceType) wraps the
  same dispatchSetStatus helper as setOnlineStatus.
- OneBot action set_diy_online_status accepts napcat-style payloads
  (face_id / face_type can be string or number; wording defaults to '').

9 new tests across actions/profile and onebot/extended-actions.
2026-05-15 19:26:40 +08:00
DrSmoothl
ee62f5aa0b feat(onebot): add napcat-parity actions (Tier 1 + Tier 2)
Wires 16 OneBot actions that napcat exposes but SnowLuma previously
either lacked or stubbed:

Tier 1 (pure glue over existing Bridge capabilities)
- send_packet / .send_packet: real impl over Bridge.sendRawPacket
- bot_exit, nc_get_packet_status, nc_get_rkey
- get_group_ignored_notifies / get_group_ignore_add_request: project
  fetchGroupRequests(filtered=true) into napcat shapes (was empty stub)
- delete_group_folder alias for delete_group_file_folder

Tier 2 (new oidb proto + Bridge method)
- set_/complete_/cancel_group_todo (oidb 0xF90_1/2/3)
- nc_get_user_status (oidb 0xFE1_2 with napcat's status decode)
- get_ai_characters / get_ai_record / send_group_ai_record (oidb
  0x929D / 0x929B; AI voice reuses the existing fetchGroupPttUrlByNode)

BridgeInterface now exposes sendRawPacket as the deliberate escape
hatch for send_packet — every other surface method already wraps it.

46 new tests: 13 bridge-action (mocked runOidb dispatch checks) + 33
OneBot-action (ApiHandler.handle end-to-end).
2026-05-15 19:22:35 +08:00
DrSmoothl
78d42029ba test(hook): guard against per-reconnect leak when QQ never logs in
50 onPipeUp/onPipeDown cycles → at most 1 live FakeClient, zero
listeners on every torn-down client. E2E variant additionally asserts
BridgeManager.onHookLogin / onPidDisconnected / onPacket are never
called, so no Bridge / Identity / OneBotInstance is allocated.

These prove no leak exists at this layer. Investigated after a Docker
OOM report which turned out to be QQ Browser GC-thrashing while idle on
the login screen (75-second LongTask entries from PID 61 in the report).
2026-05-15 15:03:00 +08:00
DrSmoothl
6b236f70bf refactor(bridge): split MsgPush handler into per-PkgType decoders
The 885-line msg-push-handler.ts is replaced by bridge/msg-push/:
8 per-PkgType decoders plus MsgPushRegistry (single decoder per
PkgType, catch + log on error), MsgPushContext (header decoded
once at entry), and rich-body-decoder (one deep function hides
~400 lines of element conversion shared by all three message
types).

parseMsgPush(pkt, identity) signature preserved; existing tests
pass with an import-path change only.
2026-05-15 14:32:34 +08:00
DrSmoothl
1a072bc6f1 refactor(utils): consolidate uppercase hex into toHexUpper
Adds toHexUpper alongside toHex in utils/hex.ts. Routes
group-file's bytesToHexUpper through it so the incoming
msg-push split can share one implementation.
2026-05-15 14:29:44 +08:00
DrSmoothl
5f88e00135 docs: rewrite CONTRIBUTING for new contributors and add Code of Conduct
Refocus CONTRIBUTING.md on first-time contributor onboarding (setup,
PR flow, conventions) and move the release/auto-merge workflow into a
clearly labeled maintainer section. Adopt Contributor Covenant v2.1
as the project Code of Conduct, pointed at the QQ/TG channels.
2026-05-15 14:01:57 +08:00
DrSmoothl
85b59bc3a1 chore(release): v1.8.0 2026-05-15 01:47:06 +08:00
DrSmoothl
7f53bcd085 refactor(onebot): drop pure pass-through closures from ApiActionContext
instance-context.ts used to declare ~130 closures inside buildApiContext,
mirrored by ~130 method signatures on ApiActionContext. About 38 of
those were pure 1:1 pass-throughs — `setGroupAdmin: (gid, uid, en) =>
bridge.setGroupAdmin(gid, uid, en)`, `setOnlineStatus`, `setProfile`,
`setAvatar`, `markGroupMsgAsRead`, `getCookiesStr`, `getCsrfToken`,
`getCredentials`, the lot of them. Each was three places to edit (the
closure, the interface signature, the action call site) and zero added
value: the OneBot name matched the Bridge name and no defaults / rename
/ composition was happening.

Expose `bridge: BridgeInterface` on ApiActionContext and have action
handlers route through `ctx.bridge.<name>` for those cases. The 38
closure declarations go away; ApiActionContext shrinks from ~70 method
signatures to ~30; instance-context.ts loses ~50 lines of boilerplate.

The ~30 adapter closures stay — every one of them does real work:
  - Renames: setGroupKick → bridge.kickGroupMember, sendFriendPoke →
    bridge.sendPoke(false, …), handleDeleteFriend → bridge.deleteFriend
  - Field extraction: uploadGroupFile returns result.fileId, not the
    full {fileId} envelope
  - Baked constants: setEssenceMsg passes `true`, deleteEssenceMsg
    passes `false` to the shared setEssenceMessage module function
  - Compositions: sendPrivateMessage / sendGroupMessage / setMsgEmojiLike
    need messageStore + mediaStore + bridge wired together
  - OneBot-specific defaults: getProfileLike defaults start=0 limit=10,
    getGroupEssence defaults pageStart=0 pageLimit=50

Two small downstream nudges that fell out of the type changes:
  - extended.ts:99 — `essenceDataAll.flatMap(res => …)` now needs an
    explicit `(res: any)` since bridge.getGroupEssenceAll returns
    `Promise<any>`, not the previously-asserted `GroupEssenceMsgRet[]`.
  - extended.ts:835 — `okResponse(clientKeyInfo)` widened via spread to
    `okResponse({ ...clientKeyInfo })` because `ClientKeyInfo` is a
    named interface (no index signature) and okResponse expects
    JsonValue/JsonObject. Behavior identical; the response shape is
    unchanged.

402 tests pass (the OneBot contact-actions test added in PR6 doubles as
regression coverage for the seam).
2026-05-15 01:38:11 +08:00
DrSmoothl
29fa2696c8 test(onebot): exercise contact-actions through a fake BridgeInterface
First OneBot unit test that proves the BridgeInterface seam (PR4)
delivers real testability. The fake bridge is a Proxy over a tiny
override map — un-stubbed methods throw with a clear message, so each
test only spells out the surface it actually exercises, and a missing
stub never silently passes.

Covers the five contact-actions read paths users hit most through the
OneBot API: getLoginInfo / getFriendList / getGroupList / getGroupInfo
/ getGroupMemberList / getGroupMemberInfo / getStrangerInfo — 19 cases
spanning happy path, network-fail fallback to identity cache,
noCache=true forcing a refetch, and missing-data nulls. No SQLite, no
native packet sender, no BridgeManager — just BridgeInterface.
2026-05-15 01:28:37 +08:00
DrSmoothl
37140b4ddd refactor(bridge): extract IncomingPacketPipeline as a deep module
Bridge.onPacket previously inlined 5 distinct responsibilities (cmd
dispatch, identity-refresh decision, async member-roster refresh,
side-effect persistence, event emission) plus all the helper state
(cmdHandlers_, memberRefreshTasks_) and the per-event printer. Move
the whole stage chain into bridge/packet-pipeline.ts as
IncomingPacketPipeline, keeping the orchestration single-owned and
testable without booting Bridge.

The pipeline's public surface is three methods — registerCmd /
handlesCmd / process — plus a single constructor dep bag. Internally
the stage order is exactly as before:

  parse  →  enrich identity (sync, or async refresh)
         →  side-effects (rememberX on Identity + coalesced roster refresh)
         →  log
         →  emit on the typed event bus

Bridge keeps the protocol-layer methods (sendRawPacket,
fetchGroupList, fetchGroupMemberList, etc.) and injects
refreshMemberCache as the one pipeline dep that touches the wire.
Bridge.onPacket / registerCmd / handlesCmd are now thin pass-throughs
so the existing external test (RefreshingBridge extends Bridge,
bridge.onPacket(makePacket()) → expects forced member fetch) keeps
working unchanged.

Net diff: bridge.ts shrinks by ~245 lines; packet-pipeline.ts is
~225 lines; one dead helper (elementsToText) deleted on the way out.
Runtime behavior is byte-identical — verified by tests/bridge-member-identity.test.ts
covering the full async-refresh path.
2026-05-15 01:21:56 +08:00
DrSmoothl
e6b609dd4e refactor(bridge): extract BridgeInterface as the OneBot-facing seam
OneBot used to depend on the concrete Bridge class — 778 lines, ~99
public methods including PID management, raw packet dispatch, and cmd
handler registration that no external consumer should touch. Add an
explicit BridgeInterface (bridge/bridge-interface.ts) enumerating only
the surface OneBot actually reads (verified by grepping every bridge.*
access in onebot/), and have Bridge `implements BridgeInterface` so the
compiler enforces alignment.

Net effect at runtime: zero — Bridge's methods, fields, and bodies are
unchanged; the interface is a TypeScript-only declaration. Net effect
for typing: the OneBot package (instance, instance-context,
instance-rkey, manager, media-url-resolver, and the modules under
onebot/modules/) now imports `BridgeInterface` instead of `Bridge`, so
tests / fakes can satisfy the interface without subclassing or pulling
in the SQLite/native bits.

In-tree bridge actions (actions/*, bridge-contacts, highway) keep their
concrete `Bridge` typing — they legitimately need sendRawPacket and
other low-level entry points that intentionally stay off the
interface.
2026-05-15 01:12:40 +08:00
DrSmoothl
59cdfa98a2 refactor(oidb): replace 3 positional helpers with one named runOidb
bridge-oidb.ts used to expose three thin functions —
makeOidbRequest / sendOidbAndCheck / sendOidbAndDecode — and every
action file repeated the same five-step envelope assembly with long
positional argument lists. Collapse them into one `runOidb(bridge,
call)` taking an OidbCall object: cmd / oidbCmd / subCmd / request
{ schema, value, isUid? } / response? { schema }.

Behavioural contract is preserved:
  - No `response`: verify success + gotResponse, peek envelope retCode
    iff response data is present (fire-and-check semantics).
  - With `response`: require responseData, decode through the base
    schema, validate retCode, return the inner body typed as TResp.

Migration touches 51 call sites across 9 source files (bridge-contacts,
actions/{group-file, group-admin, profile, group-message, friend,
interaction, misc}, web-actions/cookies) plus 9 test files that used
to assert on positional `.mock.calls[0]![4]` indices and now read
through `.mock.calls[0]![1].request.value` / `.cmd` / `.oidbCmd`.

Net effect: callers now name what each piece is for, and adding
cross-cutting OIDB behaviour (retry / timeout / per-cmd logging) is a
single-site change inside runOidb instead of a sweep across 9 files.
2026-05-15 01:03:25 +08:00
DrSmoothl
ac10c663f1 refactor(identity): absorb QQInfo into IdentityService
QQInfo's in-memory state (self identity, friends, group rosters,
profile cache) and read methods (findFriend / findGroup /
findGroupMember / findUserProfile / nickname / uin / selfProfile) now
live directly on IdentityService. The QQInfo class is gone; its
interfaces stay in `qq-info.ts` as plain types shared across the
remember*/find* surface.

This eliminates a long-standing duplication: every observation used to
maintain both QQInfo's in-memory structures and IdentityService's
SQLite mirror in parallel, with the uidByUin/uinByUid Maps tracked
separately. With one Module owning all three layers, every remember*
hydrates one set of structures and `loadSnapshot` repopulates the
in-memory uid↔uin index from SQLite on startup — closing the cold-cache
gap that previously forced findUidByUin to fall through to a SQLite
query after every restart.

Knock-on changes:
  - `Bridge` no longer holds a QQInfo; constructor takes an
    `IdentityService`. The CmdParser signature on the cmd dispatch
    table now passes `IdentityService` to parsers.
  - `msg-push-handler.ts` drops its private `resolveUidToUin(qqInfo, …)`
    helper that bypassed IdentityService's cascade — the parser hot
    path now reads through `identity.findUinByUid(uid, groupId)` and
    benefits from the O(1) `uinByUid` map even on freshly-loaded
    sessions.
  - `BridgeManager`'s session-started callback drops the QQInfo
    parameter; OneBotInstance no longer carries a `qqInfo` field and
    exposes a `nickname` getter for the WebUI listing.
  - `contact-actions` and the per-theme bridge action files stop
    importing QQInfo; they read everything via `bridge.identity.*`.
2026-05-15 00:44:01 +08:00
DrSmoothl
030336a25c refactor(identity): consolidate UID resolution behind IdentityService
Pull the cache→DB→network-fetch fallback cascade for UIN→UID translation
into a single async `resolveUid` on IdentityService, and drop the
duplicated `resolveUserUid` helper that used to live in bridge-oidb. Bridge
injects itself as the IdentityFetcher post-construction so the network
fallback runs through the same OIDB profile fetch the helper used.

Each action module's `resolveUserUid(bridge, uin, groupId?)` call becomes
`bridge.resolveUserUid(uin, groupId?)` — same signature on Bridge, but
internally it now goes through `identity.resolveUid` so future changes
(retry, coalescing, alternative resolvers) only need to land in one place.

This is part 1 of the IdentityService deepening (RoadMap item 1). The
QQInfo bypass in msg-push-handler and the broader QQInfo absorption land
in the follow-up commit.
2026-05-15 00:32:59 +08:00
DrSmoothl
2e4dd9b01e fix(onebot): clarify set_msg_emoji_like error wording
Distinguish "message not found" from "private chats don't support
emoji reactions". The latter previously masqueraded as "not a group
message", which sounded like a missing feature; clarify that the
limitation is on QQ's side, not ours.
2026-05-14 21:32:49 +08:00
DrSmoothl
a7fecf2a53 chore(release): add pnpm release one-shot driver
Bumps version, pushes dev with chore(release): prefix to trigger
Promote, waits for the PR to merge, then tags main and pushes
the tag to kick off the release workflow.
2026-05-14 21:04:29 +08:00
DrSmoothl
564eec21bb fix(bridge): include emoji type in group reaction request
set_msg_emoji_like silently no-op'd for unicode emoji because the
reaction request didn't tell the server which emoji namespace the
code belongs to (QQ face vs unicode codepoint). Derive the type
from the code length — short numeric ids are QQ faces, longer
codepoint strings are unicode.
2026-05-14 20:45:37 +08:00
H3CoF6
b176e929b9 feat: implement upload group avatar 2026-05-14 04:09:55 +08:00
DrSmoothl
00a70b1ccc fix(bridge): preserve full ext-biz-info on media upload round-trip
The NTV2 upload-response decoder used stub schemas that omitted fields
QQ NT echoes back (notably video.fromScene/toScene, pic.fromScene/
toScene/oldFileId, the ptt scene/waveform set), so finalizeMediaMsgInfo
re-encoded the commonElem.pbElem with those fields missing. For c2c
video this triggered `send private message rejected: result=79` on
every send_private_msg [{type:'video'}] call — the upload itself
fast-pathed fine but the follow-up SendMessage was rejected by NT.

Drop the duplicate NTV2 placeholder schemas and route NTV2ExtBizInfo
through the element-side PicExtBizInfo / VideoExtBizInfo /
PttExtBizInfo, which are field-complete. Also zero out the main
video sub-file's width/height/time/videoFormat in the upload request
to mirror NapCat — those fields belong on the thumb, not the source
mp4, and non-zero values trip schema validation on c2c sends.
2026-05-13 22:19:45 +08:00
DrSmoothl
e438f353af fix(onebot): resolve self nickname via user profile when friend list omits self
The session warmup only set qqInfo.nickname when QQ's friend-list
response happened to echo self back, which it omits for some
accounts / versions / multi-account warmup races. The WebUI online
sessions card then rendered a blank nickname row above the UIN.
Fall back to a direct user-profile fetch when the friend-list scan
misses self, and seed qqInfo.nickname with the UIN at session
creation so the panel never paints empty while warmup is in flight.
2026-05-13 21:11:26 +08:00
DrSmoothl
ea5a1d505a feat: add forward message preview metadata support 2026-05-13 20:53:26 +08:00
DrSmoothl
ada591b1b4 bump 1.7.9 2026-05-13 16:52:19 +08:00
DrSmoothl
61e3867197 chore(release): single-source app version + add pnpm bump
- WebUI sidebar/login display and OneBot get_version_info now read the
  root package.json version via Vite `define`, removing hardcoded
  literals in webui/src/types.ts and core/onebot/actions/info.ts.
- tools/bump-version.mjs (exposed as `pnpm bump <ver>`) syncs the
  version field across the root and all five workspace packages.
- Bump everything to 1.7.8.
2026-05-13 16:51:44 +08:00
DrSmoothl
c9fa119a50 fix(onebot): align forward message wrapping with OneBot 11 spec
get_forward_msg now returns full OB11Message objects (self_id, time,
message_id, sender, etc.) instead of node-segment wrappers, and event
emission keeps the resId on incoming forward segments instead of
dropping it via the unknown-element fallback. Extends ForwardNodePayload
with optional context fields so download/upload paths preserve enough
state to synthesize the OB11Message shape NapCat clients expect.
2026-05-13 16:49:29 +08:00
DrSmoothl
6abde40b9c [merge] fix Linux auto load issue 2026-05-13 16:20:43 +08:00
DrSmoothl
6760008c5c chore: refresh prebuilt linux-x64 native binary 2026-05-13 16:18:21 +08:00
DrSmoothl
37b835c537 chore: refresh prebuilt linux-x64 native binary 2026-05-13 16:18:21 +08:00
DrSmoothl
9068ce3108 fix(core): skip Electron child processes during hook auto-load
With SNOWLUMA_HOOK_AUTOLOAD=1, the QQ window came up blank — no QR code,
login stuck. Cause: the native enumerator (get_all_main_process_ids)
returned the main QQ pid plus 2 zygote subprocesses because their
cmdline contains "qq" and they transiently inherit wrapper.node via
fork copy-on-write. Auto-load fired loadModuleManual for all three,
spawning an in-process resolver thread inside each zygote. Renderer
processes Electron later forked from those zygotes then inherited
those resolver threads + the partially-initialised hook state, which
breaks QQ's IPC and prevents the login UI from rendering.

Add `shouldAutoLoadPid` which reads /proc/<pid>/cmdline and returns
false when it contains `--type=` (Electron child process marker:
zygote / renderer / gpu-process / utility). Manual loadProcess() is
unaffected — operators picking PIDs from WebUI keep full control.
SNOWLUMA_HOOK_AUTOLOAD_ALL=1 disables the filter as an escape hatch.

Verified on tempserver: container restart with autoload=1 now shows
the QR-code login screen as expected, and only the main qq pid gets
the mojo.<pid>.*.sock pair (zygotes stay clean).
2026-05-13 00:57:48 +08:00
DrSmoothl
1b2dd836b8 [merge] upd & refactor 2026-05-12 22:06:04 +08:00
DrSmoothl
fbb7504afe feat(core): auto-inject hook on QQ process discovery
Headless / Docker deployments previously needed a human to click
"Load" in WebUI for every newly-discovered QQ process. Add an opt-in
HookManager.autoLoadOnDiscovery flag wired up through two layers:

  - SNOWLUMA_HOOK_AUTOLOAD env var (highest priority)
  - hookAutoLoad in runtime.json (persistent fallback)

When enabled, every 'process-discovered' event from PipeWatcher fires
session.load() fire-and-forget; failures stay scoped to the session via
existing error-state handling and don't break the watcher loop.

Default stays off, so non-Docker installs see no behaviour change.
2026-05-12 22:04:11 +08:00
DrSmoothl
dd02535a73 chore(core): flatten single-file dirs + drop dead writeFailed surface
Two small cleanups that came out of the round-2 architecture review
and are sub-five-minutes each — bundled because each one is too
small to justify its own commit.

#5 — flatten single-file directories
  packages/core/src/bridge/builders/element-builder.ts
    -> packages/core/src/bridge/element-builder.ts
  packages/core/src/bridge/handlers/msg-push-handler.ts
    -> packages/core/src/bridge/msg-push-handler.ts

  Both dirs had exactly one file in them — a smell that says
  "planned a sibling that never landed". Moving up one level
  removes the wrapper directory.

  Touch list:
    - bridge.ts:                  2 import paths
    - bridge/actions/forward.ts:  2 import paths
    - msg-push-handler.ts:        internal ../X -> ./X for events,
                                  proto/element, proto/message (the
                                  dynamic-import-typeof references too)
    - element-builder.ts:         internal ../X -> ./X for bridge,
                                  events, highway/*
    - 4 test files:               import paths (2 regular, 2 vi.mock)

#6 — drop IdentityService.hasWriteFailure
  identity-service.ts had a `private writeFailed = false` field set
  by the runWrite catch block and exposed via `get hasWriteFailure()`,
  but a full-repo grep showed zero callers of the getter. It was a
  public API stub for a feature that hadn't been wired (a webui
  health indicator, presumably).

  Removed:
    - the field
    - the getter
    - the assignment in runWrite's catch block (the error log on
      the next line is the actual observable behavior; nothing else
      reads the flag)

  If we want a "did any write fail this session" surface later,
  it's trivial to add back with an explicit consumer in mind.

Behavior preserved end-to-end. No public API change outside the
moved files. 369 tests pass (unchanged). 3 stability runs.
2026-05-12 20:59:25 +08:00
DrSmoothl
069548918b refactor(core): split web-actions.ts into themed modules + barrel
web-actions.ts was a 330-line monolith with 14 exported functions
covering 4 distinct themes: cookie/credential primitives (the 8
functions every web call builds on), group honor leaderboards, group
essence (highlighted messages), and group notices. Same shape problem
the OIDB bridge-actions.ts split fixed three commits back, just smaller.

New layout under packages/core/src/bridge/web-actions/ :

  cookies.ts        (161 lines, 8 fns)
    forceFetchClientKey / getPSkey / getCookies / getSKey /
    getBknFromSKey / getCookiesStr / getCsrfToken / getCredentials
    — the ptlogin2-jump + bkn-derivation primitives.

  group-honor.ts    (45 lines, 1 fn)
    getGroupHonorInfo (talkative / performer / legend / emotion / ALL)

  group-essence.ts  (27 lines, 2 fns)
    getGroupEssence (paged) + getGroupEssenceAll

  group-notice.ts   (118 lines, 3 fns)
    sendGroupNotice (with optional image-from-URL-or-file upload),
    getGroupNotice (OneBot shape flatten), deleteGroupNoticeByFid

  index.ts          (27 lines)
    Barrel re-export. `bridge.ts` keeps its existing
    `from './web-actions'` import — TS resolves the directory's
    index.ts so no caller changes.

The lower-level web/* helpers (request-util, group-essence,
group-honor, group-notice) stay where they were — they're the
direct HTTP/cookie wrappers, distinct from these Bridge-level
orchestrators.

Behavior preserved end-to-end. Same ptlogin2 URL construction,
same fall-back-to-getPSkey-when-p_skey-missing path in getCookies,
same default keyIndex='19' / expireTime='1800', same djb2 bkn hash,
same NapCat-derived default 540x300 notice image dimensions, same
chinese error messages ('设置群公告失败', '获取公告失败').

Adds 35 happy-path tests across 4 new files in tests/web-actions/ :

  cookies         (13)  forceFetchClientKey response shape + defaults,
                        getPSkey pskeyItems folding, getCookies ptlogin2
                        URL params, p_skey fallback path (both success
                        and throwing), getSKey success / no-clientKey /
                        no-skey throws, getBknFromSKey determinism +
                        range, getCookiesStr formatting, getCsrfToken
                        composition, getCredentials full + empty paths.
  group-honor      (7)  TALKATIVE list vs empty list behaviour,
                        PERFORMER / LEGEND / EMOTION per-type dispatch,
                        ALL fetches all four types, groupId stringification.
  group-essence    (4)  pageStart/pageLimit forwarding, defaults,
                        null-result fallback envelope, getAll delegation.
  group-notice    (11)  text-only dispatch + defaults, options override,
                        http image fetch + upload + thread, fetch failure,
                        ec≠0 surfaces em, generic error fallback,
                        getGroupNotice feed flattening + pics mapping,
                        null-result throw, empty-feeds case,
                        deleteGroupNoticeByFid argument forwarding.

Tests use vi.mock on bridge-oidb / web/request-util / web/group-*
to isolate each theme from real HTTP, mirroring the pattern from
the bridge-actions split.

369 tests pass (was 334); 3 stability runs, same pre-existing
macOS-arm64 websocket addon failure, unrelated.
2026-05-12 20:49:36 +08:00
DrSmoothl
8a49f0c21d refactor(core): extract MediaUrlResolver + MediaIndexer from OneBotInstance
The OneBotInstance constructor still carried two non-trivial closures
inside its converterCtx object — a 26-line mediaUrlResolver that
branched bridge URL fetches by element.type + isGroup, and a 60-line
mediaSegmentSink that fanned out to mediaStore.rememberImage / Record /
Video with subtly different field maps. Both closed over `this` and
were untestable without instantiating the whole instance.

Extracted into two small, focused modules:

  onebot/media-url-resolver.ts  (64 lines)
    class MediaUrlResolver(bridge, rkeyCache)
      .resolve(element, isGroup, sessionId): Promise<string>
    Picks the right Bridge.fetchXxx based on element.type + isGroup,
    mutates element.url in-place (preserved behavior), then applies
    the cached RKey via rkeyCache.resolveMediaUrl. Bridge-fetch
    errors are swallowed so the RKey pass always runs.

  onebot/media-indexer.ts  (90 lines)
    class MediaIndexer(mediaStore)
      .remember(mediaType, element, data, isGroup, sessionId): void
    One method, dispatches to mediaStore.rememberImage / Record /
    Video with the right field map per mediaType. Defaults are
    preserved exactly (?? 0 for missing numbers, ?? '' for strings).

OneBotInstance constructor shrinks from 134 lines to ~50 lines (-62%).
The converterCtx is now visually obvious — four callbacks each one
line, delegating to the right collaborator:

    const mediaUrlResolver = new MediaUrlResolver(this.bridge, this.rkeyCache);
    const mediaIndexer = new MediaIndexer(this.mediaStore);
    this.converterCtx = {
      selfId: parseInt(this.uin, 10) || 0,
      imageUrlResolver: (el, ig) => this.rkeyCache.resolveImageUrl(this.bridge, el, ig),
      mediaUrlResolver: (el, ig, sid) => mediaUrlResolver.resolve(el, ig, sid),
      messageIdResolver: (ig, sid, seq, name) => hashMessageIdInt32(...),
      mediaSegmentSink: (mt, el, d, ig, sid) => mediaIndexer.remember(mt, el, d, ig, sid),
    };

Adds 19 happy-path tests:

  media-url-resolver.test.ts  (12 tests):
    - file element: group / c2c-with-hash / c2c-without-hash
    - record element: group / c2c
    - video element: group / c2c
    - record without mediaNode: no bridge call
    - element.url already set: short-circuit, only rkey runs
    - bridge throws: swallowed, rkey still applied
    - rkey is always called at the end

  media-indexer.test.ts  (7 tests):
    - image: full field map, file falls back to fileId
    - record: full field map, file falls back to fileName
    - video: full field map, data.file overrides element fields
    - record: file falls back to fileId when fileName also missing
    - missing numeric / string fields default to 0 / ''
    - only the matching rememberX is called

Behavior preserved end-to-end: same bridge methods, same field
mappings into MediaStore, same in-place element.url mutation, same
RKey-always-runs guarantee, same best-effort error swallowing.
The existing media-store integration test (which still wires the
sink through the real converter) continues to pass unchanged.

334 tests pass (was 317); 3 stability runs, same pre-existing
macOS-arm64 websocket addon failure, unrelated.
2026-05-12 20:35:12 +08:00
DrSmoothl
49281726f1 refactor(core): split EventConverter god switch into themed pure functions
event-converter.ts (541 lines) was a class with a 16-case switch
mapping bridge events to OneBot wire JSON, plus a 13-case helper
mapping bridge elements to OneBot segments, plus four lazily-injected
resolver setters (image-url / media-url / message-id / media-segment
sink). Testing one case required instantiating the class and wiring
four setters; 22 of the 29 cases (10 notices + 2 requests + 13 element
types) had zero tests.

This commit kills the class and replaces it with a pure-function
family that takes a ConverterContext (a plain object holding selfId
+ the four resolver callbacks). Each per-event handler becomes a
small typed function that's trivial to call from a test with two
lines of setup.

New layout: packages/core/src/onebot/event-converter/

  index.ts        133  ConverterContext + four resolver types +
                       convertEvent dispatcher + re-exports.
  to-message.ts   112  friend / group / temp message  (3 handlers)
  to-notice.ts    189  group_member_join / leave / mute / admin /
                       friend_recall / group_recall / friend_poke /
                       group_poke / group_essence / group_file_upload /
                       friend_add                     (11 handlers)
  to-request.ts    37  friend_request / group_invite  (2 handlers)
  to-segment.ts   145  13 element -> segment cases + elementsToJson +
                       elementsToOneBotSegments
  utils.ts        111  parseSelfId / isSameActor / applyMessageIdResolver /
                       resolveReplyId / segmentsToRawMessage + CQ encoding

Caller migration (3 files, all inside onebot/):

  instance.ts:        replaces `new EventConverter()` + four setter
                      calls with a single `converterCtx: ConverterContext`
                      object built once at construction. The four
                      closures that used to be passed through setters
                      are now properties of the context.
  instance-context.ts: `eventConverter: EventConverter` field renamed
                      to `converterCtx: ConverterContext`.
  event-pipeline.ts:  `ctx.eventConverter.convert(ctx.uin, event)` is
                      now `convertEvent(ctx.converterCtx, event)`.

External callers (modules/message-actions.ts) keep working unchanged:
elementsToOneBotSegments is re-exported from the new index.ts with
the same signature.

Adds 28 new tests covering every previously-untested case:

  message kinds (already partly covered):  7 tests
    - friend / group / temp_message peer + self post_type tagging
    - messageIdResolver override
  notice kinds (new):                     11 tests
    - all 11 cases, including the sub-type axes
      (approve/invite, leave/kick/kick_me, ban/lift_ban,
       set/unset, add/delete, etc.)
  request kinds (new):                     2 tests
    - friend_request, group_invite (with sub_type default)
  element segments (new):                 13 tests
    - text / face / image (with + without resolver) / at /
      at-all / reply (with + without resolver) / record /
      video / json / xml (with + without subType) / file /
      mface / poke
  mediaSegmentSink wiring (new):           1 test

Plus 3 tests in media-store.test.ts and 1 in event-pipeline.test.ts
adapted to the new API.

317 tests pass (was 285); 3 stability runs, same pre-existing
macOS-arm64 websocket addon failure, unrelated.
2026-05-12 18:45:28 +08:00
DrSmoothl
269cd6f081 refactor(core): extract NTV2 upload pipeline shared by image/ptt/video
The three highway uploaders — image-upload, ptt-upload, video-upload —
each implemented the same NTV2 envelope assembly, OIDB response decode,
error handling, and Highway PUT loop, with the only real per-format
differences being the file-info fields, the extBizInfo blob, and the
Highway command id. The duplicated boilerplate had drifted slightly
between files and any future NTQQ protocol change would have needed
parallel edits in three places.

New: packages/core/src/bridge/highway/pipeline.ts (249 lines).

  runNtv2Upload({ bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd,
                  requestId, businessType, uploadInfo, compatQmsgSceneType,
                  extBizInfo, uploads, label })
    -> awaited upload object

    Builds the full reqHead + upload envelope, sends through OIDB,
    decodes the response, runs the per-sub-file Highway PUTs (caching
    the Highway session across them — video uses two PUTs and now only
    fetches the session once), and surfaces a typed fastOnlyError when
    the server demands bytes but the caller passed a fingerprint.

  finalizeMediaMsgInfo(upload, defaultPic?) -> Uint8Array

    Encodes the outgoing commonElem MsgInfo. `defaultPic` is the
    image-only fallback: image fills bizType + textSummary when the
    server omits the pic ext-biz-info; ptt / video pass undefined.

  hexToBytes(hex), makeClientRandomId(): shared helpers used by every
  uploader's fingerprint payload + client-randomId generation.

MediaSubFileUpload models per-sub-file routing:
  - source: 'top'   -> upload.uKey + upload.ipv4s (main file)
  - source: N       -> upload.subFileInfos[N].uKey + .ipv4s (video thumb)
  - cmdId, bytes, md5, sha1, subFileIndex, fastOnlyError

Each upload file shrinks to its format-specific logic only:

  image-upload.ts:  237 -> 163  (-31%)
    format detection, picFormat mapping, pic/reserveTroop/reserveC2c
    extBizInfo, group/c2c command id choice, finalize with defaultPic.

  ptt-upload.ts:    300 -> 205  (-32%)
    silk transcoding, temp-file cleanup, NapCat-style bytesGeneralFlags
    (different per group/c2c), voiceFormat honouring.

  video-upload.ts:  584 -> 507  (-13%)
    Sha1StreamState (per-1MB streaming SHA1 for the main Highway PUT),
    ffmpeg-driven thumb extraction with FALLBACK_THUMB, the two-sub-file
    OIDB body (main mp4 + thumb jpg with subFileType 100), and the
    fastOnlyError asymmetry (main file has it; thumb always has bytes).
    Video stays the largest because its load step is genuinely the most
    work — the share-out gain here is in concentration, not line count.

Behavior preserved end-to-end. Same NTV2 OIDB cmd numbers (image
0x11C4/5, ptt 0x126E/D, video 0x11EA/9), same service-cmd strings,
same requestId (image=1, ptt=group:1/c2c:4, video=3), same
compatQmsgSceneType (image+ptt: isGroup?2:1; video: 2), same
NapCat-derived bytesGeneralFlags, same fastUpload fallback strings.

Adds 42 happy-path tests across 4 new files in tests/highway/ :

  pipeline.test.ts          22  envelope construction, response decode,
                                OIDB error paths, group vs c2c scene,
                                Highway PUT trigger + fast-path skip,
                                sub-file routing, session caching,
                                fastOnlyError fire / silent-skip,
                                finalize with/without defaultPic, helpers.
  image-upload.test.ts       7  group/c2c oidbCmd + cmdId mapping,
                                fingerprint payload shape, picFormat /
                                dimensions wiring, subType -> bizType.
  ptt-upload.test.ts         6  group requestId=1 / c2c requestId=4,
                                per-scene bytesGeneralFlags, voiceFormat
                                default and override, fingerprint
                                preconditions, finalize-without-pic.
  video-upload.test.ts       7  two-sub-file shape, thumb subFileInfos[0]
                                routing, fastOnlyError asymmetry,
                                uploadInfo[mp4+jpg] with subFileType 0+100,
                                FALLBACK_THUMB always has bytes.

Tests mock highway-client for transport and the pipeline module (for
per-uploader tests) so each suite hits exactly the contract it's
testing. Pipeline tests roundtrip a real OIDB envelope through
protobuf encode/decode to exercise the actual decode path.

285 tests pass (was 244). Same pre-existing macOS-arm64 websocket
addon failure, unrelated.
2026-05-12 17:46:56 +08:00
DrSmoothl
b32a8110af refactor(core): make ApiActionContext required, drop 80 dead defensive guards
ApiActionContext had 81 optional method fields (\`name?: ...\`) plus 4
required ones — but every single optional field was wired in
buildApiContext (verified by diffing the two lists). The optionality
was dead: nothing else implemented this interface, no test ever
swapped fields out, and the action handlers all paid for the
fiction with defensive guards like:

    if (!ctx.sendGroupMessage) {
      return failedResponse(RETCODE.ACTION_FAILED, 'send_group_msg is not implemented');
    }

— 80 such guards total across the action files (78 in the 3-line
form, 1 single-line, 1 \`if (!(ctx.a && ctx.b))\` compound). None of
them could ever fire.

This commit deletes the dead optionality. Two mechanical changes:

1. api-handler.ts: 81 \`name?: ...\` -> \`name: ...\` in ApiActionContext.
   The MessageSendResult optionals (meta?, echoEvent?) are unrelated
   and stay as-is. After: 85 required fields, 0 optionals.

2. actions/*.ts: drop the 80 guard blocks. Net -129 lines across
   extended, group-admin, group-file, group-info, friend, message,
   request. info.ts had none to begin with.

What this buys:

- The type system now enforces the wiring contract. If
  buildApiContext forgets to wire a field, tsc fails at the call
  site — the bug we were ostensibly catching at runtime in 80 places
  is now caught at compile time in 0 places, for free.
- Action handler bodies shrink visibly (avg ~3 lines per handler).
  extended.ts goes 1021 -> 935.
- AI / human readers no longer skim past dead code.

Caught one TS2774 ("This condition will always return true since
this function is always defined") on a compound guard in
extended.ts:186 that the regex missed; removed it manually. That
diagnostic is the type system actually doing its job — exactly the
point of the change.

244 tests pass (was 244). Same pre-existing macOS-arm64 websocket
addon failure, unrelated.
2026-05-12 17:09:56 +08:00
DrSmoothl
8506b60d07 refactor(core): split bridge-actions.ts (1814 lines) into themed action modules
bridge-actions.ts was a single 1814-line file holding 55 unrelated
exported functions — admin/file/forward/interaction/recall/profile/
status/translate/sign/avatar all jumbled together. Each function
already takes `bridge: Bridge` as its first parameter, so the
"deepening" target (per-UIN state object threaded into themed action
functions) was structurally there — what was missing was a coherent
file-level grouping that AI tools and humans could navigate.

This commit is candidate #2 from the deepening list, A-only variant:
pure file split, no facade change, no caller change outside the
bridge module.

New layout under packages/core/src/bridge/actions/ :

  shared.ts        82  private helpers (toInt, ensureRetCodeZero,
                       resolveSelfUid) and the MediaIndexNode type.
  group-admin.ts  153  mute/kick/leave + setGroup{Admin/Card/Name/
                       SpecialTitle/AddOption/Search/Remark/AddRequest}
                       + getGroupAtAllRemain.                (14 fns)
  group-file.ts   821  upload/list/url/delete/move/folder ops, both
                       group + private files, media-URL fetchers for
                       ptt/video, fetchGroupFileCount. Owns file-
                       specific helpers (normalizeDirectory,
                       buildGroupFileUploadExt, normalizeMediaNode,
                       fetchNtv2DownloadUrl, ...).            (15 fns)
  group-message   101  recall* / markRead* / setGroupEssence.  (5 fns)
  interaction.ts   61  poke / like / reaction / emoji-likes.   (4 fns)
  forward.ts      197  uploadForwardNodes, fetchForwardNodes +
                       in-memory resId cache.                  (2 fns)
  friend.ts        53  setFriendAddRequest, deleteFriend,
                       setFriendRemark.                        (3 fns)
  profile.ts      269  setOnlineStatus, setProfile, setSelfLongNick,
                       setInputStatus, setAvatar, fetchCustomFace,
                       getProfileLike, getUnidirectionalFriendList.
                                                              (8 fns)
  misc.ts         173  translateEn2Zh, getMiniAppArk,
                       clickInlineKeyboardButton, sendGroupSign.
                                                              (4 fns)

bridge.ts updates its imports — one themed import block per action
module instead of one giant block from bridge-actions.ts. GroupFilesResult
and MediaIndexNode type imports now point at actions/group-file and
actions/shared. Public Bridge facade API is unchanged: every caller
outside `bridge/` keeps the same `bridge.X(...)` surface and the
delegated function it points at.

bridge-actions.ts is deleted. The new shared.ts holds the three
helpers that span themes; everything else lives co-located with the
functions that use it.

Adds 60 happy-path tests across tests/actions/ — one .test.ts per
themed file plus a shared `_helpers.ts` (mockBridge fixture):

  group-admin     10  command + payload dispatch, UID resolution,
                      flag-driven sub-command selection (mute on/off,
                      add-request filtered/unfiltered).
  group-file      13  fetchGroupFileCount, upload happy path with
                      and without highway, OIDB error bubbling, file
                      listing pagination + folder/file split, URL
                      builder shape, delete/move/folder dispatch,
                      NTV2 URL assembly.
  group-message    5  recall (group/private), markRead, essence on/off,
                      transport failure propagation.
  interaction      6  poke (group vs friend payload), like, reaction
                      on/off, emoji-likes cookie/isLast logic.
  forward          5  empty-array rejection, dispatch + res_id return,
                      transport failure, cache reuse after upload.
  friend           5  numeric flag → UID resolution path, opaque flag
                      passthrough, delete + best-effort cache refresh.
  profile          9  status dispatch, setProfile no-op when undefined,
                      setAvatar highway cmd 90, getProfileLike +
                      getUnidirectionalFriendList JSON parsing.
  misc             6  translate, mini-app type guard, click + sign
                      dispatch.

Tests use vi.mock on `bridge-oidb` (and `highway-client`/`highway-utils`
where relevant) so each action runs against a tiny fake Bridge, no
native pipe / real OIDB exchange needed. Previously these 55 functions
had zero unit-test coverage.

244 tests pass (was 184); only failing suite remains the pre-existing
macOS-arm64 missing websocket native addon, unrelated.
2026-05-12 16:51:34 +08:00
DrSmoothl
e91a506bf5 feat(onebot): implement forward_{group,friend}_single_msg via md5 fast-upload
Captures protocol-level media fingerprints (md5/sha1/dims/format) on the
receive side and persists them alongside existing MediaStore entries, so a
forward can re-send the original message via QQ's md5 fast-upload path
without re-downloading the source CDN bytes. Avoids the stale-rkey trap
where the cached imageUrl 404s a few hours after receipt.

- MessageElement: add md5Hex / sha1Hex / pic|video|voiceFormat /
  noByteFallback optional fields.
- MediaStore: extend CachedImage / CachedRecord with fingerprints, add
  CachedVideo + rememberVideo / findVideo / updateVideoUrl. Per-row growth
  ~80-90 bytes; LRU cap stays at 4096 per type.
- msg-push-handler: extract fingerprints from NTV2 image/record/video and
  legacy NotOnlineImage/CustomFace/Ptt paths.
- event-converter: invoke mediaSegmentSink for video too.
- highway image/ptt/video upload: add fast-only branch that skips
  loadBinarySource/encodeSilk/stageVideoSource when noByteFallback is set,
  and fails fast if the server still returns uKey. Video forward uses the
  100-byte FALLBACK_THUMB as its subFile (original thumb not preserved in
  onebot semantics).
- message-actions: add forwardSingleMessage which looks up the cached
  event, enriches each media element with cached fingerprints, and
  dispatches via the existing sendGroup/sendPrivateMessage path. Files
  reject explicitly (separate upload protocol, out of scope).
- extended actions: wire forward_friend_single_msg / forward_group_single_msg
  to the new context method, replacing the not-implemented stubs.
2026-05-12 16:22:16 +08:00
DrSmoothl
ef4a321175 refactor(core): drop NtqqHandler shim, route packets directly to BridgeManager
NtqqHandler was a 54-line "shallow module": half of its public surface
(registerCmd by service-cmd) had zero callers — cmdHandlers was a Map
that nothing ever wrote to. The remaining half (registerCmdAll) had
exactly one subscriber: BridgeManager.bind() wiring its private
onPacket. So NtqqHandler was, in effect, a one-listener event emitter
plus a five-line field-rename from QqHookPacket to PacketInfo.

The deletion test concentrates the change rather than scattering it:

- HookSession.handlePacket inlines the field rename and pushes
  straight into a PacketSink dependency (PacketInfo => void).
  HookSession's ctor now takes `onPacket?: PacketSink` instead of
  `ntqq?: NtqqHandler` — the new shape is exactly what tests want
  (a vi.fn() spy with no event-emitter scaffolding).

- HookManager's `ntqq: NtqqHandler` constructor dep becomes
  `onPacket?: PacketSink`, defaulting to `bridgeManager.onPacket` so
  the common-case wiring stays one line at the call site.

- BridgeManager.bind(ntqq) is deleted; BridgeManager.onPacket becomes
  public (it was always the real entry point). The file header
  comment now describes onPacket as the single packet entry rather
  than "wires NtqqHandler".

- index.ts shrinks: no `new NtqqHandler()` and no `bridgeManager.bind`.
  `new HookManager({ bridgeManager })` covers both wires.

- packages/core/src/protocol/ntqq-handler.ts deleted.

Behavior preserved: same field rename (Buffer.from(packet.body) for
the body copy that QqHookClient already does, kept to match
byte-for-byte), same login + real-uin filter, same logging scope is
gone (`createLogger('NTQQ')` had no remaining call sites). PacketSink
type alias added to protocol/types.ts so the dep type stays readable
across HookSession + HookManager.

Adds 5 unit tests for the inlined packet path that the deleted module
never had: PacketInfo shape, session-uin fallback when packet.uin is
empty, pre-login drop, non-real-uin drop, and a no-sink no-op.

184 tests pass (was 179); only failing suite is the pre-existing
macOS-arm64 missing websocket native addon, unrelated.
2026-05-12 14:56:38 +08:00
DrSmoothl
4fc52578a5 refactor(core): split HookManager into PipeWatcher + HookSession
HookManager was a 515-line god class with four tangled responsibilities
(state machine, watcher loop, per-PID serialization, lifecycle plumbing)
and no tests — every code path needed a real QQ.exe to exercise.

Split into three modules:

- PipeWatcher: the only module that polls the OS for QQ.exe processes
  and live SnowLuma named pipes. Emits diff events (process-discovered,
  process-gone, pipe-up, pipe-down, tick). Native list functions are
  constructor deps so tests can drive ticks with in-memory fakes.

- HookSession: per-PID lifecycle. Owns its own state machine, its own
  promise chain (serializes load/unload/refresh/onPipeUp/onPipeDown so
  rapid user clicks don't race), and its own QqHookClient. Emits
  high-level events (login, disconnected, status-changed, disposed)
  that the manager forwards instead of reaching into BridgeManager
  directly. Injector and pipe-client factory are deps for testability.

- HookManager: shrinks to a thin orchestrator (227 lines, was 515).
  Routes user commands and watcher events to sessions, forwards session
  events to BridgeManager, retries stuck-in-connecting sessions on every
  watcher tick (preserves the original tickWatcher reconcile pass).
  Public API (listProcesses/loadProcess/unloadProcess/refreshProcess)
  unchanged for WebUI callers; only the constructor moves to a deps
  object: new HookManager({ ntqq, bridgeManager }).

Behavior preserved including all the edge cases the original code
handles: re-using a SnowLuma DLL that survived a process restart
(fast-path via pipeWatcher.isPipeLive), stale close events from a
replaced client, DLL-unload-failed fallback to "watcher will
reconnect", QQ.exe killed with a live pipe (pipe-down emitted before
process-gone so disconnect runs before dispose).

Adds 27 unit tests across two new vitest suites (hook-session.test.ts
and pipe-watcher.test.ts) covering load fast-path, login emission,
duplicate-login suppression, connect retry on failure, pipe up/down
cycles, unload while logged in, unload verification failure, user
command serialization, and process-gone handling — none of which
previously had test coverage.
2026-05-12 14:43:30 +08:00
DrSmoothl
5ce8aa60de refactor onebot action context modules 2026-05-12 14:40:48 +08:00
DrSmoothl
8636222d91 [merge] fix & upd 2026-05-11 23:30:08 +08:00
DrSmoothl
6f506ff52c fix onebot video file sending 2026-05-11 23:26:45 +08:00
DrSmoothl
e917720d9d fix linux hook stale socket detection 2026-05-11 23:14:27 +08:00
DrSmoothl
af80855d2d fix(core): persist identities from request events 2026-05-11 19:16:39 +08:00
DrSmoothl
9a30a40a1f feat(core): add persistent identity service 2026-05-11 19:09:05 +08:00
H3CoF6
df5e3a26ac implement some onebot actions (#26)
* feat: implement more group admin action (kick members and set search and set add type)

* feat: implement some user extend func (set group mark \\ get custom emoji)

* feat: implement get send emoji his
2026-05-11 16:00:25 +08:00
DrSmoothl
bf0a89e221 fix(core): resolve group join member identity 2026-05-10 17:38:05 +08:00
H3CoF6
6f6ce1144b 补全一些onebot action实现 2 (#24)
* feat: implement get profile like

* feat: implement get at all remain

* feat: implement get undirectional friends

* feat: implement set self long nick

* feat: implement set input status

* feat: implement EN 2 ZH

* feat: implement get mini app ark

* feat: implement click inline button

* feat: implement set and send group sign

* feat: implement set qq avatar

* feat: group notice with pic and delete notice implement

* fix(group-notice): POST api and fix new bkn logic
2026-05-10 10:14:41 +08:00
DrSmoothl
bec23c4dbb [merge] promote SDK changes 2026-05-10 01:29:57 +08:00
DrSmoothl
c343021318 feat: add SnowLuma TypeScript SDK 2026-05-10 01:26:35 +08:00
DrSmoothl
9ab4128799 Implement video message upload 2026-05-09 23:06:55 +08:00
手瓜一十雪
95df5234fb Support forced group member cache refresh
Add a `force` flag to member cache refresh logic so events that affect the bot itself trigger an immediate refresh. When the event userUin matches the bot's UIN, `triggerMemberCacheRefresh` sets `force = true` and forwards it to `fetchGroupMemberList`. `fetchGroupMemberList` now accepts an optional `force` parameter (default false) and bypasses the TTL cache when `force` is true, ensuring up-to-date member data after join/leave events.
2026-05-09 19:54:20 +08:00
手瓜一十雪
a7b3809a12 Only track hook states for running PIDs
Stop exposing and retaining hook state for PIDs that are not currently running. listProcesses() no longer returns orphaned states; live-pipe handling ignores PIDs not present in the current process list. When a process is not running its state is immediately torn down (tearDownClient called) and removed, and bridgeManager.onPidDisconnected is notified if the state was logged in. Also reorganized runningSet creation so it can be reused for these checks.
2026-05-09 19:38:52 +08:00
手瓜一十雪
c39b3f5c4e Add PTT (voice) upload support with FFmpeg addon
Introduce NT SILK-based voice (PTT) upload pipeline and native FFmpeg addon wrapper.

- Add ffmpeg-addon wrapper (packages/core/src/bridge/highway/ffmpeg-addon.ts) to load platform/arch .node binaries, detect SILK files, and convert inputs to NT SILK via the native addon. Provides encodeSilk, isSilkFile and default temp dir helpers.
- Implement ptt-upload pipeline (packages/core/src/bridge/highway/ptt-upload.ts) to: resolve/fetch audio bytes, convert to NT SILK if needed, send OIDB upload request, perform highway HTTP upload when required, and produce Encodable MsgInfo bytes for commonElem.
- Wire record element support into element-builder: uploadPttMsgInfo is used to build a commonElem for 'record' sends; when SendContext is absent, record sends are skipped with a warning (graceful no-bridge path).
- Update message parsing to accept record segments from data.file, data.url or data.path and drop empty sources.
- Enable canSendRecord in OneBot instance context.
- Add tests covering record parsing and the graceful send path (packages/core/tests/message-parser.test.ts).
- Include prebuilt native ffmpeg addon binaries under packages/runtime/native/ffmpeg and update vite config to validate & copy the ffmpeg addon into the dist layout.

These changes enable sending voice messages by converting/encoding sources to the expected NT SILK format and uploading them through the existing highway/NTV2 flows.
2026-05-09 19:32:13 +08:00
手瓜一十雪
2af273b9e2 Simplify WebUI logs and adjust hook reconnect
Translate and consolidate verbose WebUI log messages to shorter English variants (dev mode, initial credentials, forced password change, password update, port fallback, and listening message). Remove a startup log emitted in core index.ts. In HookManager, preserve an existing state.method when detecting an already-injected PID (only set to 'reconnect' if not present) and remove a redundant injection success log to reduce noise.
2026-05-09 16:36:03 +08:00
手瓜一十雪
144e0fdd59 Add BridgeEventBus and network manager
Introduce a typed per-kind BridgeEventBus and migrate away from the legacy single-callback firehose. Bridge now exposes `events` and emits via the bus; BridgeManager/OneBotManager no longer wire a global event callback. Add a focused onebot event pipeline (event-pipeline.ts) that subscribes per-kind handlers on instance construction. Replace the in-memory MediaCache with a persistent MediaStore and update all lookups accordingly. Replace the old Http/Ws/HttpPost transport implementations with a unified OneBotNetworkManager and pluggable adapters (server/client/post), and update OneBotInstance to install and manage adapters from config. Remove several legacy files (http-transport, http-post-transport, ws-transport, media-cache) and update imports across the codebase. Also add tests for the bridge event bus, event pipeline, network manager, and rename media tests to reflect MediaStore usage. The bus dispatches handlers in parallel and reports handler errors via an onError hook to avoid one faulty listener blocking others.
2026-05-09 16:30:06 +08:00
手瓜一十雪
1565749105 Add MediaCache and media segment sink
Introduce an in-memory MediaCache to index recently seen image and record segments and wire a MediaSegmentSink into EventConverter to populate it. OneBotInstance now constructs MediaCache and registers a sink to remember image/record metadata; instance-context exposes get_image/get_record lookup handlers that consult the cache (and re-resolve record URLs via bridge OIDB when needed). ApiHandler actions get_image/get_record now accept file_id fallback and use the new context lookups. Removed the old findMediaInStore stub and added comprehensive tests for the cache and sink behavior.
2026-05-09 15:33:13 +08:00
手瓜一十雪
e53a8a01b7 Revert "[merge] dev & ci: default promote-dev-to-main merge strategy to squash"
This reverts commit 3afbcfaae5.
2026-05-09 15:08:41 +08:00
手瓜一十雪
3afbcfaae5 [merge] dev & ci: default promote-dev-to-main merge strategy to squash
Switch default merge_method from 'merge' to 'squash' so dev->main PRs collapse the dev branch's incremental commits into one squash commit on main, keeping main's history linear and release-tag-friendly. Affects: workflow_dispatch input default, decide-step initial value + workflow_dispatch fallback, both push-trigger branches (tag + commit-msg), and the case-statement fallback in the auto-merge step. CONTRIBUTING.md updated to reflect the new default.
2026-05-09 15:06:54 +08:00
手瓜一十雪
c3b328f91d [merge] dev 2026-05-09 15:01:46 +08:00
手瓜一十雪
7942c47808 [merge] dev 2026-05-09 14:58:37 +08:00
手瓜一十雪
46d93e715a ci: use chore.* tag pattern + commit-msg prefix matching for promote workflow
- Tag trigger switched from v* to chore.* so the promote workflow no longer collides with release.yml's v* tag handling. v* tags now drive only the release build; chore.* tags drive only dev->main promotion.

- Commit-message detection on dev is now prefix-only: '^[merge]' or '^chore(release):' (case-insensitive). 'fix: stuff [merge]' no longer triggers; the marker must be at the start of the message.

- CONTRIBUTING.md updated: prefix examples, chore.* tag examples, and an explicit 'all required status checks must pass' branch-protection setup that lists the dev-build typecheck/build matrix as required.
2026-05-09 14:57:06 +08:00
手瓜一十雪
a9027a8610 ci: add promote dev->main workflow + branching docs
Adds .github/workflows/promote-dev-to-main.yml which uses the SnowLuma Bot GitHub App to open (or refresh) a PR from dev into main. Triggered by [merge] or chore(release): commit-msg markers on dev, by v* tag pushes, or via manual workflow_dispatch. Auto-merge is enabled when triggered.

Adds CONTRIBUTING.md describing the dev/main branch model, the promote workflow, the required SNOWLUMA_BOT_APP_ID / SNOWLUMA_BOT_PRIVATE_KEY secrets, and the GitHub branch protection setup needed to forbid direct pushes to main.
2026-05-09 14:43:44 +08:00
手瓜一十雪
5853dc63ff Lookup workflow by name/id and set default repo
Update release workflows to fallback to 'SnowLuma/SnowLuma.Docker.Framework' when RELEASE_REPOSITORY is unset and to resolve the target workflow by name, path, or id. Replace the simple workflow_id string with logic that paginates listRepoWorkflows, finds the matching workflow, validates it exists, and passes workflow.id to createWorkflowDispatch. Improve error messages and logging to include workflow name and id.
2026-05-09 11:23:50 +08:00
手瓜一十雪
ca14cb5437 Replace DOCKER_RELEASE_TOKEN with SNOWLUMA_TOKEN
Update GitHub Actions release workflows to use the SNOWLUMA_TOKEN secret instead of DOCKER_RELEASE_TOKEN. Changed the github-token input in .github/workflows/release.yml and .github/workflows/dispatch-docker-release.yml for the docker release steps.
2026-05-09 11:17:02 +08:00
手瓜一十雪
a978d27f3a Add manual Docker rebuild dispatcher
Introduce a manual re-dispatch workflow and wire automatic dispatch from releases to the Docker workflow. dispatch-docker-release.yml was converted to a workflow_dispatch-based "Re-dispatch Docker Release" that accepts snowluma_tag, docker_image_override and platforms_override inputs and forwards them (plus source repository) to the downstream docker-image.yml in the Docker release repo. release.yml gains a dispatch-docker job that runs after the release job and uses a PAT to invoke the same downstream workflow for newly published tags. These changes let maintainers rebuild Docker images for existing tags (e.g. to fix Dockerfile issues or rotate credentials) without re-tagging, and ensure the downstream dispatch runs under the configured token.
2026-05-09 11:07:59 +08:00
手瓜一十雪
5a5b9d13d1 Use workflow_dispatch to trigger Docker workflow
Switch the release dispatch to call actions.createWorkflowDispatch instead of repos.createDispatchEvent because the target repo only listens for workflow_dispatch on its docker workflow. Add env vars DOCKER_PLATFORMS, DOCKER_WORKFLOW and DOCKER_REF (with sensible defaults) and pass image, tag, push and platforms as inputs. Update log output to include workflow, ref, image, tag and platforms.
2026-05-09 10:47:29 +08:00
手瓜一十雪
b62a6edd37 Canonicalize WsRole strings and migrate legacy values
Normalize OneBot WS role values to canonical PascalCase ('Api'|'Event'|'Universal') across core and web UI, and support auto-migration from legacy lowercase on-disk values. Updated types, defaults, serializers/parsers, and runtime checks in ws-transport, adjusted WebUI select options and default entries, and updated the client User-Agent string. Added a test to verify that legacy lowercase role values are migrated to the new canonical form on load.
2026-05-09 10:21:47 +08:00
MliKiowa
4d97f02fe9 Merge pull request #9 from H3CoF6/feat/onebot
implement some onebot api
2026-05-09 08:52:04 +08:00
H3CoF6
c8dd520d65 feat: implement get cookies and CSRF and credentials 2026-05-09 05:17:18 +08:00
H3CoF6
8b313fe088 feat: implement set qq profile 2026-05-09 05:08:03 +08:00
H3CoF6
049ef2960c feat: implement set online status 2026-05-09 04:57:00 +08:00
H3CoF6
a0d584375a feat: implement get group notice 2026-05-09 04:24:03 +08:00
H3CoF6
51c2fa285a refactor: move web action into web-actions from bridge-actions 2026-05-09 04:08:52 +08:00
H3CoF6
c862a157db feat: implement send group notice 2026-05-09 03:44:08 +08:00
H3CoF6
d708be4627 fix(webui): password strength indicators not updating
修复密码强度指示器不亮起的问题,将后端返回字段从 met 改为 ok 以匹配前端期望

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 21:03:28 +08:00
H3CoF6
3791addb43 feat: implement get all essence msg 2026-05-08 20:41:47 +08:00
H3CoF6
a40cbdc316 Merge remote-tracking branch 'upstream' into feat/onebot 2026-05-08 16:42:39 +08:00
H3CoF6
7e2ba60073 feat: implement default mark msg as read and add get clientkey onebot api 2026-05-08 16:42:19 +08:00
H3CoF6
e3e364db63 Merge remote-tracking branch 'upstream' into feat/onebot 2026-05-08 01:56:47 +08:00
H3CoF6
4a51e3d686 feat: 引入web方法,实现group honor 2026-05-08 01:56:23 +08:00
DrSmoothl
84de00e6ac ci(actions): update workflows for Node 24 actions 2026-05-07 23:27:55 +08:00
DrSmoothl
08d02c6303 ci(release): dispatch Docker publish on tags
Trigger the external Docker release pipeline when a SnowLuma version tag is pushed.

Keep Docker image and release target configuration in the SnowLuma environment.
2026-05-07 22:44:44 +08:00
手瓜一十雪
e008920f39 Add RoadMap.md and remove testing section
Remove the '测试要求' testing section from README.md and add a new RoadMap.md containing planned V2.0.0 tasks (unify Uid/Uin service with SQLite persistence, improve debug experience with no-packaging debug and correct data dir). This separates roadmap details from the README for clarity and future tracking.
2026-05-07 19:50:05 +08:00
H3CoF6
99c74b4a66 Merge remote-tracking branch 'upstream' into feat/onebot 2026-05-07 19:29:25 +08:00
DrSmoothl
92c6234b4f build(native): refresh Linux SnowLuma binaries
Update the Linux x64 SnowLuma native binaries from the latest release build.

Leave the websocket native binary unchanged.
2026-05-07 18:42:06 +08:00
手瓜一十雪
0d8e52ee77 fix: #7 2026-05-07 16:21:35 +08:00
手瓜一十雪
2a4ca46a99 Refactor OneBot networks and event dispatch
Unify per-adapter network configuration into a single `networks` structure and add migration/normalization for legacy on-disk formats. Introduce per-adapter options (messageFormat, reportSelfMessage, enabled, name) and stronger typing in types.ts. Add event-filter utilities to prebuild two serialized payload variants and pick the right one per adapter to avoid repeated JSON.stringify calls. Update HTTP/WS transports to use adapter names/signatures for hot-reload, respect per-adapter options, and improve logging; WS transport also improves client/server lifecycle/reconnect handling. Mark self-sent messages as `message_sent` in the event converter and wire instance dispatch to use the new DispatchPayload. Misc: README edits and accompanying tests added/updated for the refactor.
2026-05-07 16:01:28 +08:00
手瓜一十雪
19a564991c Add WebUI dev mode auth & dev script
Introduce a development-only WebUI auth mode controlled by SNOWLUMA_DEV_MODE. When enabled, a fixed in-memory password ("snowluma-dev") is used, config/webui.json is not read or written, and password changes are disabled. Expose WebuiAuth.isDevMode() and WebuiAuth.devPassword, add startup logs when dev mode is active, and wire up dev:mode npm scripts (root and packages/core) using cross-env to set the env flags.
2026-05-07 14:36:12 +08:00
手瓜一十雪
466a10a00a Update snowluma Win32 x64 native DLL
Replace packages/runtime/native/snowluma-win32-x64.dll with an updated binary build. This commit updates the native Windows x64 runtime DLL; no other source changes are present in this diff.
2026-05-07 14:19:27 +08:00
手瓜一十雪
f7cfec1a93 Replace GPU detection with runtime memory info
Remove external GPU detection (no more exec/promisify or detectGpus) and stop returning GPU list from /api/system. Instead expose the Node.js process runtime info (pid, rss, heapTotal, heapUsed, external, arrayBuffers) from the server. Update types to replace gpus with runtime and update the Overview UI: remove GPU list, show PID and formatted runtime memory stats, and adjust imports/icons accordingly. This simplifies system probing (avoids spawning platform commands) and surfaces useful process memory metrics in the WebUI.
2026-05-07 09:39:12 +08:00
手瓜一十雪
3ac4bc79f0 Make OneBot message parsing defensive
Harden parsing of message segments in OneBot instance: skip non-object or array segments, normalize a local `type` string and a safe `data` object, and use those for all branch checks. This prevents runtime errors when segments or segment.data are missing or malformed, while preserving existing previews and placeholder labels (image, face, at, reply, record, video, fallback).
2026-05-07 09:35:35 +08:00
MliKiowa
3f4b389e6d Merge pull request #6 from venti1112/main
fix: correct ineffective quote replies, use Get-CimInstance for GPU detection with wmic fallback, and show uninstall failure notification
2026-05-07 09:32:51 +08:00
H3CoF6
0d84e3b99e feat: implemented mark msg as read 2026-05-07 05:49:13 +08:00
Ventiの酒
d8d7fa2ede Merge branch 'SnowLuma:main' into main 2026-05-07 02:36:44 +08:00
DrSmoothl
8d33c1f76c chore: ignore macOS metadata files 2026-05-07 00:32:04 +08:00
DrSmoothl
946c1c6981 ci: enable Linux arm64 build matrix 2026-05-07 00:26:07 +08:00
DrSmoothl
5f8fd26a28 build(native): add prebuilt Linux arm64 binaries 2026-05-07 00:25:47 +08:00
venti1112
64178893e4 fix: show uninstall failure notification in WebUI
Previous behavior: when an uninstall operation failed, the system did not provide any error feedback to the user and would simply reconnect during a polling check.

Fixed behavior: if an uninstall fails, a failure notification is now displayed in the WebUI, informing the user that the uninstall has failed.
2026-05-06 18:09:31 +08:00
Ventiの酒
6aa067f495 Merge branch 'SnowLuma:main' into main 2026-05-06 17:26:22 +08:00
手瓜一十雪
85298444eb Update Windows x64 native binaries
Replace rebuilt native artifacts for Windows x64: packages/runtime/native/snowluma-win32-x64.dll and packages/runtime/native/snowluma-win32-x64.node. This updates the compiled DLL and Node addon (likely due to native fixes, dependency or build changes) without touching source files.
2026-05-06 16:35:30 +08:00
Ventiの酒
758d21cc79 Merge branch 'SnowLuma:main' into main 2026-05-06 16:26:12 +08:00
手瓜一十雪
4b02367a5f Add pipe-watcher and manual refresh for hooks
Introduce a background pipe-watcher and per-PID operation serialization in HookManager to reliably detect and reconnect to SnowLuma pipes, reduce races, and remove the previous connect retry loop. Add new status 'connecting' and a refreshProcess API endpoint to force a probe/reconcile for a PID. Implement QqHookClient.listLivePipes() (and isClosed/probePipe updates) to enumerate live mojo pipes efficiently. Simplify client teardown logic and improve state transitions/logging. Update web UI: add a Refresh button, track inflight process ops, show connecting status and updated action messages. Update shared types to include the new 'connecting' status.
2026-05-06 16:10:14 +08:00
venti1112
de7533ca81 fix:Fix the issue where quoting a message in replies was ineffective
Previous behavior:
Replies visually displayed a quote block, but the quoted content was blank or invalid, and clicking to jump to the original message also failed.

Fixed behavior:
The quote now correctly references the original message, displaying its actual content and enabling a functional jump to the quoted message.
2026-05-06 15:53:11 +08:00
手瓜一十雪
2e340f58a8 Update WebUI port in release workflow
Change the documented localhost port in .github/workflows/release.yml from 8080 to 5099 so packaged builds reference the correct WebUI endpoint. This updates the startup instructions shown in the release workflow to match the new default port.
2026-05-06 15:51:52 +08:00
DrSmoothl
682d40b239 build(native): strip Linux SnowLuma binaries
Replace the Linux x64 SnowLuma native binaries with stripped release builds.

Leave the websocket native binary unchanged.
2026-05-06 15:21:22 +08:00
Ventiの酒
4a92292e49 Merge branch 'SnowLuma:main' into main 2026-05-06 13:42:36 +08:00
手瓜一十雪
60189d9c1d Add typecheck CI job and package script
Introduce a `typecheck` job to GitHub Actions that sets up pnpm and Node.js (v22), installs dependencies, and runs `pnpm typecheck` on the workspace. Make the `build` job depend on `typecheck`. Also add a `typecheck` script (`tsc --noEmit`) to packages/websocket/package.json to enable package-level type checking. This ensures TypeScript errors are caught before the build runs.
2026-05-06 10:23:45 +08:00
venti1112
52f2528271 fix: use Get-CimInstance for GPU detection with wmic fallback to support modern Windows
Previous behavior: display adapter detection relied exclusively on wmic path Win32_VideoController. On recent Windows versions (e.g., Windows 11 24H2) where wmic is deprecated and disabled by default, this resulted in a complete failure to identify any display adapters.

Fixed behavior: added a new primary detection path using PowerShell’s Get-CimInstance Win32_VideoController, which is available and recommended on all modern Windows installations. The original wmic method is kept as an automatic fallback for older systems or environments where the CIM/PowerShell approach is unavailable. This restores GPU detection across a wide range of Windows versions without changing the public API or returned data structure.
2026-05-05 21:31:46 +08:00
手瓜一十雪
e67e0ea497 Disable linux-arm64 release matrix entry
Comment out the linux-arm64 matrix entry in .github/workflows/release.yml so the ubuntu-24.04-arm runner is no longer included in release jobs. This temporarily disables ARM64 releases; re-enable by uncommenting the linux-arm64 lines.
2026-05-05 20:28:51 +08:00
手瓜一十雪
db8f0bdf50 Disable linux-arm64 job in dev-build workflow
Temporarily comment out the linux-arm64 matrix entry in .github/workflows/dev-build.yml (name, os, target) to prevent the ARM64 job from running. Lines are commented rather than removed so the job can be re-enabled easily later.
2026-05-05 20:28:40 +08:00
MliKiowa
8068f1893e Merge pull request #5 from venti1112/main
fix: fix reverse-ws reload/reconnect idempotency, preserve explicit no-token config values, and make WebUI config rendering consistent after refresh
2026-05-05 20:27:11 +08:00
venti1112
34a572f153 fix: fix reverse-ws reload/reconnect idempotency, preserve explicit no-token config values, and make WebUI config rendering consistent after refresh
Previous behavior: after editing an unreachable reverse-ws OneBot config entry, the new config took effect, but reconnect attempts could still target the old URL.
Fixed behavior: reconnect now only applies to currently active OneBot config entries; removed or changed old entries are no longer retried.

Previous behavior: after refreshing the WebUI, OneBot config entries for the same account were already loaded and active in backend, but appeared empty in the WebUI config page.
Fixed behavior: OneBot config API response shape is now unified and backward-compatible, so persisted OneBot config entries render correctly after WebUI refresh.

Previous behavior: no-token OneBot config entries could be automatically assigned a token during load/refresh.
Fixed behavior: fixed the issue where no-token config entries were auto-populated with tokens; OneBot config entry token values now strictly follow explicit user configuration (empty stays empty).

Previous behavior: after multiple reconnect failures for a reverse-ws OneBot config entry, multiple connections could be created concurrently when the target server came back.
Fixed behavior: added per-entry connection/reconnect deduplication so each OneBot config entry maintains only one active connection and one reconnect timer.
2026-05-05 17:15:13 +08:00
DrSmoothl
5746dc628f chore: fix ci fail 2026-05-05 00:43:29 +08:00
DrSmoothl
1426d7adb2 feat: add settings page and theme toggle component
- Implemented a new SettingsPage component for user preferences including appearance, behavior, and account security settings.
- Added a ThemeToggle component to switch between light, dark, and system modes.
- Created reusable UI components: AlertDialog, Avatar, Badge, Button, Card, Dialog, Input, Label, Progress, ScrollArea, Separator, Sheet, Skeleton, Tooltip.
- Introduced utility functions for class name merging and formatting bytes/uptime.
- Added a custom hook for media query handling
2026-05-05 00:39:52 +08:00
DrSmoothl
f52a84d53f feat: optimize group member fetching to prevent excessive OIDB call 2026-05-04 15:23:30 +08:00
手瓜一十雪
550cfa5cec Update .gitignore 2026-05-03 18:37:46 +08:00
DrSmoothl
d6a22d62ae chore: move native bondle to packages/runtime folder 2026-05-03 18:25:20 +08:00
DrSmoothl
a2b1d252d7 feat(linux): enhance thread management and symbol resolution in injection process 2026-05-03 17:27:14 +08:00
手瓜一十雪
69b8dd7165 Revert "Probe and reconnect to existing hooks"
This reverts commit f04ec3ec36.
2026-05-03 16:51:07 +08:00
手瓜一十雪
f04ec3ec36 Probe and reconnect to existing hooks
Add a lightweight pipe liveness probe and use it to detect/reconnect to existing SnowLuma hooks instead of always re-injecting. Introduces PROBE_TIMEOUT_MS (400ms) and QqHookClient.probePipe(pid, timeout) which quickly checks if the control pipe accepts a connection (no hello exchange). HookManager now parallel-probes freshly-enumerated processes (probeAndSeed) and fast-checks before injecting in loadProcess; positive hits mark the state as injected with method="reconnect" and avoid redundant injection. Also deduplicate login notifications in handleLoginState (skip if already logged in with the same UIN) and adjust the loginState emission ordering in QqHookClient.
2026-05-03 16:49:06 +08:00
手瓜一十雪
82c1721466 CI: add matrix builds & cross-platform packaging
Restructure GitHub Actions to build Windows and Linux matrix targets and produce platform-specific artifacts.

- .github/workflows/dev-build.yml: split cleanup/build jobs, add matrix (win-x64, linux-x64), set SNOWLUMA_TARGET for builds, produce full and -lite archives (.zip on Windows, .tar.gz on Linux), unify upload step and ensure errors when artifacts missing.
- .github/workflows/release.yml: convert release build to matrix, produce platform archives, download/collect artifacts, generate multi-platform release notes (bash), and create the GitHub release with both .zip and .tar.gz assets.
- packages/core/vite.config.ts: add fs import and SNOWLUMA_TARGET handling, pick platform-specific runtime files (launcher.bat or launcher.sh), enumerate native files per target, fail CI if expected native binaries are missing, and copy native files into dist/native.
- packages/runtime/launcher.sh: add a portable launcher for Linux that prefers a bundled node binary or falls back to PATH and execs index.mjs.

These changes enable cross-target CI packaging and enforce that native binaries are present before releasing.
2026-05-03 16:20:39 +08:00
DrSmoothl
df73f58598 fix: dll path do not work on Linux/UNIX systems 2026-05-03 16:00:14 +08:00
手瓜一十雪
b6341145be CI: build WebUI and publish node/no-node zips
Simplify CI by removing job matrices and always building the WebUI flavor. Both dev and release workflows now run build:all, verify the websocket native module, and produce two archives: a zero-install bundle that includes node.exe and a no-node variant (requires Node >=22). Artifact names and upload steps were adjusted (dev uses SHA-based names; release uses tag-based names), and release notes were updated to document the two packages and WebUI defaults.
2026-05-03 15:56:19 +08:00
手瓜一十雪
8ca616ec3a Preserve ESC in logger to allow ANSI colors
Adjust logger sanitization to keep the ESC (0x1B) character so ANSI color sequences produced by render() reach the terminal. The regex was refined from removing all ASCII control chars to excluding ESC, while still stripping other control characters (including BEL) to prevent unwanted system beeps and control behavior. Comment updated to reflect this rationale.
2026-05-03 15:53:41 +08:00
手瓜一十雪
252a65b833 Add @snowluma/websocket TS package and integrate
Introduce an in-tree TypeScript WebSocket package (@snowluma/websocket): move JS websocket implementation into packages/websocket/src (client, server, websocket, extensions, native, index) and add package.json + tsconfig. Replace direct 'ws' dependency in core with the workspace package and update runtime manifest/description. Implement a native addon loader for platform-specific binaries, add typings/refinements across client/server/websocket (more strict types, handshake parsing, permessage-deflate plumbing, buffer/raw data handling), and wire WebSocketClient as the package default export while exposing internal types. Update vite config to bundle the new package and copy only platform-target native binaries into dist/native. Remove legacy JS entrypoints and native loader, and adjust imports/usages in core (ws-transport) to accept broader raw data types.
2026-05-03 15:49:42 +08:00
手瓜一十雪
5fb969da7c Add WebSocket package with client/server & native
Introduce a new WebSocket package implementing RFC6455 functionality and permessage-deflate support. Adds core connection handling (packages/websocket/websocket.js), client wrapper (client.js), server and upgrade handling (server.js), extensions (permessage-deflate) and helpers (extensions.js), an index and native loader (native.js). Also include prebuilt native addon binaries for multiple platforms and integration points to use the native Parser and frame builder. The server supports handleUpgrade, subprotocol negotiation, and verifyClient hooks; the client performs handshakes and queues sends until open. Error handling, UTF-8 validation, close/ping/pong control frames, and max-payload checks are implemented.
2026-05-03 15:32:44 +08:00
手瓜一十雪
39f1672b29 Migrate project to pnpm monorepo
Restructure the repository into a pnpm workspace under packages/ (core, webui, runtime). Move source files for core and webui into packages/*, add package manifests for @snowluma/core and @snowluma/runtime, and remove the old launcher package.json. Update root package.json to be a monorepo controller (scripts delegate to pnpm filters, set packageManager and Node engine). Configure build outputs to emit into the repo-root dist/ (vite config changes) so the existing release pipeline continues to work. Add .npmrc with mirrors, expand .gitignore for monorepo layout, add tsconfig base and package-level tsconfigs, and add vitest config for the core package. Adjust injector native search paths and update tests import paths to the new package layout. Small CI/workflow comment added to clarify build behavior and README updated with monorepo structure and common commands.
2026-05-03 14:02:29 +08:00
手瓜一十雪
6bba36bba6 fix: #2 2026-05-03 13:14:06 +08:00
手瓜一十雪
02326b0968 CI: generate release notes and full fetch
Set checkout fetch-depth to 0 and add a PowerShell step that generates release-notes.md for the current tag (computes previous tag, collects commit messages, and emits localized download/usage notes for Windows x64 builds). Update the GitHub Release step to use body_path: release-notes.md and overwrite_files: true (replacing auto-generated notes) so the release includes the curated changelog and artifact information.
2026-05-02 20:23:45 +08:00
手瓜一十雪
bd40af2517 Add hot-reloadable transports and log streaming
Enable runtime config reload and dynamic endpoint management across transports, and add server-side log streaming + UI.

- Transport hot-reload: HttpTransport, HttpPostTransport and WsTransport now maintain endpoint lists and start/stop individual endpoints (servers/clients) dynamically; servers/clients use keys/Maps to identify instances; added reloadConfig methods and helper key functions.
- OneBot control: OneBotInstance.reloadConfig delegating to transports; OneBotManager.reloadConfig(uin) to load and apply new config; added getPids helper.
- Logger & streaming: added in-memory recent log buffer, subscriber API (getRecentLogs, subscribeLogs) and LogEntry shape; web UI exposes /api/logs and /api/logs/stream (SSE) and improved token/query handling.
- Web UI: added LogsPage, integrated into layout and sidebar, EventSource client to show live logs; config save now attempts hot-reload and returns reloaded status.
- Misc: refactors to use Maps for server lists, cleanup on stop, and various small helpers and safety checks.
2026-05-02 20:19:37 +08:00
手瓜一十雪
ac1ddee54e Add QQ avatar proxy and render avatars
Add a /avatar/:uin proxy endpoint that fetches QQ avatars (fetchQqAvatar) and caches them server-side (30d TTL) with browser-cache headers (30d max-age, immutable). Validate UINs and handle upstream failures (502 if no cache), and log failures. Update ConfigPage and OverviewPage to render avatar <img> from /avatar/:uin (referrerPolicy=no-referrer) and adjust styles (overflow-hidden, object-cover) to replace initial-letter placeholders with actual avatars.
2026-05-02 20:11:11 +08:00
手瓜一十雪
e059a12cc4 Add exceptionTable to ManualMapHandle
Add a new bigint property `exceptionTable` to the `ManualMapHandle` interface in src/hook/injector.ts and adjust formatting. The native build artifacts (native/snowluma-win32-x64.dll and native/snowluma-win32-x64.node) were also updated, indicating a rebuilt native addon to match the interface/ABI change.
2026-05-02 19:55:26 +08:00
680 changed files with 65707 additions and 16058 deletions

15
.editorconfig Normal file
View File

@@ -0,0 +1,15 @@
root = true
[*]
charset = utf-8
end_of_line = crlf
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.{json,yml,yaml,md}]
indent_size = 2
[*.md]
trim_trailing_whitespace = false

119
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View File

@@ -0,0 +1,119 @@
name: Bug 反馈
description: 报告一个可复现的问题
title: "[Bug] "
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
感谢花时间反馈 Bug。请尽量填全以下信息,方便我们定位问题。
在提交前,请先在 [Issues](https://github.com/SnowLuma/SnowLuma/issues?q=is%3Aissue) 中搜索是否已有相同问题。
- type: checkboxes
id: preflight
attributes:
label: 提交前检查
options:
- label: 我已搜索过 Issues,确认没有重复的反馈
required: true
- label: 我使用的是 [最新 Release](https://github.com/SnowLuma/SnowLuma/releases) 或当前 `dev` 分支构建
required: true
- type: input
id: snowluma-version
attributes:
label: SnowLuma 版本
description: 启动日志首行或 `package.json` 里的版本号
placeholder: "例如 1.8.5"
validations:
required: true
- type: dropdown
id: adapter
attributes:
label: 出问题的适配器
description: 可多选
multiple: true
options:
- WebSocket Server
- WebSocket Client
- HTTP Server
- HTTP Post
- WebUI
- Bridge / Core(协议层)
- 其他 / 不确定
validations:
required: true
- type: input
id: os
attributes:
label: 操作系统
placeholder: "例如 Windows 11 23H2 / macOS 14.5 / Ubuntu 22.04"
validations:
required: true
- type: input
id: node-version
attributes:
label: Node.js 版本
description: '`node -v` 的输出。如果使用预构建包可填"预构建包"'
placeholder: "例如 v20.11.0 或 预构建包"
validations:
required: true
- type: input
id: qq-version
attributes:
label: QQ 客户端版本
description: QQ NT 客户端的版本号
placeholder: "例如 9.9.15-29722"
- type: textarea
id: description
attributes:
label: 问题描述
description: 简要说明发生了什么
validations:
required: true
- type: textarea
id: reproduce
attributes:
label: 复现步骤
description: 详细列出如何触发这个问题
placeholder: |
1. 启动 SnowLuma 并登录账号 ...
2. 通过 HTTP Server 调用 `send_group_msg` ...
3. 观察到 ...
validations:
required: true
- type: textarea
id: expected
attributes:
label: 期望行为
validations:
required: true
- type: textarea
id: actual
attributes:
label: 实际行为
validations:
required: true
- type: textarea
id: logs
attributes:
label: 相关日志 / 错误堆栈
description: |
粘贴控制台日志、SSE 实时日志或错误堆栈。
请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。
render: shell
- type: textarea
id: extra
attributes:
label: 补充信息
description: 配置片段(脱敏后)、截图、相关 Issue / PR 链接等

11
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1,11 @@
blank_issues_enabled: false
contact_links:
- name: QQ 群
url: https://qm.qq.com/q/g3UMLpWALe
about: 日常使用问题、快速交流可以先来 QQ 群
- name: Telegram
url: https://t.me/napcatqq
about: 海外用户交流频道
- name: Releases
url: https://github.com/SnowLuma/SnowLuma/releases
about: 在反馈 Bug 前,请先确认已使用最新发布版本

View File

@@ -0,0 +1,76 @@
name: 功能请求
description: 提议一个新功能或对现有功能的增强
title: "[Feature] "
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: |
感谢您的建议。在提交前,请先在 [Issues](https://github.com/SnowLuma/SnowLuma/issues?q=is%3Aissue) 中搜索是否已有类似提案。
- type: checkboxes
id: preflight
attributes:
label: 提交前检查
options:
- label: 我已搜索过 Issues,确认没有重复的提案
required: true
- type: dropdown
id: scope
attributes:
label: 涉及范围
multiple: true
options:
- OneBot 协议 / 消息段
- WebSocket Server / Client 适配器
- HTTP Server / Post 适配器
- WebUI 管理面板
- SDK (`@snowluma/sdk`)
- UI 组件 (`@snowluma/ui`)
- Bridge / Core(协议层)
- 构建 / 发布流程
- 文档
- 其他
validations:
required: true
- type: textarea
id: problem
attributes:
label: 需求场景 / 当前痛点
description: 这个功能要解决什么问题?目前是如何变通处理的?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: 期望方案
description: 您希望它如何工作?如果是 API 改动,建议给出示例输入 / 输出
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: 已考虑的替代方案
description: 还想过哪些其他实现路径,为什么放弃
- type: textarea
id: references
attributes:
label: 参考链接
description: 例如 OneBot 规范条目、其他实现的对应特性、相关 Issue / PR
placeholder: |
- OneBot v11 规范: https://github.com/botuniverse/onebot-11/...
- 相关讨论: #xxx
- type: checkboxes
id: willingness
attributes:
label: 您是否愿意提交 PR 来实现这个功能?
options:
- label: 愿意,且需要维护者讨论方案后再动手
- label: 愿意,已有大致实现思路
- label: 暂时只提建议

View File

@@ -8,24 +8,14 @@ on:
- 'v*'
jobs:
build:
runs-on: windows-latest
cleanup:
runs-on: ubuntu-latest
permissions:
actions: write
contents: read
strategy:
fail-fast: false
matrix:
include:
- name: "standard"
script: "build"
suffix: ""
- name: "webui"
script: "build:all"
suffix: "-WebUI"
steps:
- name: Delete old artifacts
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
let page = 1;
@@ -48,17 +38,22 @@ jobs:
page++;
}
typecheck:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v4
uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'pnpm'
@@ -66,29 +61,82 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build project
run: pnpm run ${{ matrix.script }}
# Runs `tsc --noEmit` (or `tsc -b`) in every workspace package that
# exposes a `typecheck` script. Platform-independent, so a single
# ubuntu runner is sufficient.
- name: Type check all packages
run: pnpm typecheck
- name: Verify native files
shell: pwsh
run: |
if (!(Test-Path "dist\native\snowluma-win32-x64.node")) { throw "Missing dist\native\snowluma-win32-x64.node" }
if (!(Test-Path "dist\native\snowluma-win32-x64.dll")) { throw "Missing dist\native\snowluma-win32-x64.dll" }
build:
needs: [cleanup, typecheck]
permissions:
contents: read
strategy:
fail-fast: false
matrix:
include:
- name: win-x64
os: windows-latest
target: win32-x64
- name: linux-x64
os: ubuntu-latest
target: linux-x64
- name: linux-arm64
os: ubuntu-24.04-arm
target: linux-arm64
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Bundle runtime dependencies
working-directory: dist
run: npm install --omit=dev
- name: Package artifact
shell: pwsh
run: |
Copy-Item (Get-Command node).Source -Destination "dist\node.exe"
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev${{ matrix.suffix }}.zip"
- name: Upload artifact
uses: actions/upload-artifact@v4
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
name: SnowLuma-dev-${{ github.sha }}${{ matrix.suffix }}
path: SnowLuma-dev${{ matrix.suffix }}.zip
version: 10.28.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --frozen-lockfile
# Always builds the WebUI flavor — no separate "core-only" artifact.
- name: Build project
env:
SNOWLUMA_TARGET: ${{ matrix.target }}
run: pnpm run build:all
# Naming convention:
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node >= 22
- name: Package (windows)
if: matrix.os == 'windows-latest'
shell: pwsh
run: |
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev-${{ matrix.name }}-lite.zip"
Copy-Item (Get-Command node).Source -Destination "dist\node.exe"
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev-${{ matrix.name }}.zip"
- name: Package (linux)
if: startsWith(matrix.os, 'ubuntu')
run: |
chmod +x dist/launcher.sh
tar -czf "SnowLuma-dev-${{ matrix.name }}-lite.tar.gz" -C dist .
cp "$(command -v node)" dist/node
chmod +x dist/node
tar -czf "SnowLuma-dev-${{ matrix.name }}.tar.gz" -C dist .
# Single upload step — glob picks up both variants (.zip on Windows,
# .tar.gz on Linux) for this matrix row.
- name: Upload artifacts
uses: actions/upload-artifact@v7
with:
name: SnowLuma-dev-${{ github.sha }}-${{ matrix.name }}
path: SnowLuma-dev-${{ matrix.name }}*
retention-days: 3
overwrite: true
if-no-files-found: error

View File

@@ -0,0 +1,78 @@
name: Re-dispatch Docker Release
# Manual-only re-dispatcher for SnowLuma.Docker.Framework's docker-image.yml.
#
# The normal flow is automatic: release.yml's `dispatch-docker` job fires
# after a tag-triggered release is published. This workflow exists for
# rebuilding an existing release's Docker image without re-tagging — for
# example after fixing the Dockerfile, rotating a Docker Hub credential,
# or backfilling an older tag.
on:
workflow_dispatch:
inputs:
snowluma_tag:
description: 'SnowLuma release tag to rebuild (e.g. v0.5.0)'
required: true
docker_image_override:
description: 'Override Docker image name (defaults to vars.DOCKER_IMAGE)'
required: false
default: ''
platforms_override:
description: 'Override platforms (defaults to vars.DOCKER_PLATFORMS or linux/amd64,linux/arm64)'
required: false
default: ''
permissions:
contents: read
jobs:
dispatch:
runs-on: ubuntu-latest
environment: SnowLuma
steps:
- name: Dispatch Docker rebuild
uses: actions/github-script@v8
env:
RELEASE_REPOSITORY: ${{ vars.DOCKER_RELEASE_REPOSITORY }}
DOCKER_IMAGE: ${{ vars.DOCKER_IMAGE }}
DOCKER_PLATFORMS: ${{ vars.DOCKER_PLATFORMS }}
DOCKER_WORKFLOW: ${{ vars.DOCKER_WORKFLOW }}
DOCKER_REF: ${{ vars.DOCKER_REF }}
SNOWLUMA_TAG: ${{ inputs.snowluma_tag }}
IMAGE_OVERRIDE: ${{ inputs.docker_image_override }}
PLATFORMS_OVERRIDE: ${{ inputs.platforms_override }}
with:
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
script: |
const target = process.env.RELEASE_REPOSITORY;
if (!target || !target.includes('/')) {
throw new Error('Set SnowLuma environment variable DOCKER_RELEASE_REPOSITORY to owner/repo.');
}
const tag = process.env.SNOWLUMA_TAG;
if (!tag) throw new Error('snowluma_tag input is required.');
const [owner, repo] = target.split('/');
const sourceRepo = context.repo.owner + '/' + context.repo.repo;
const image = process.env.IMAGE_OVERRIDE || process.env.DOCKER_IMAGE || 'motricseven7/snowluma';
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';
await github.rest.actions.createWorkflowDispatch({
owner,
repo,
workflow_id: workflowId,
ref,
inputs: {
image,
tag,
push: 'true',
platforms,
snowluma_tag: tag,
snowluma_repository: sourceRepo,
},
});
core.info(`Re-dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);

View File

@@ -0,0 +1,245 @@
name: Promote Dev to Main
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
concurrency:
group: promote-dev-to-main
cancel-in-progress: false
jobs:
decide:
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
id: check
env:
EVENT_NAME: ${{ github.event_name }}
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'
fi
else
reason="Push event on unhandled ref: ${REF}"
fi
;;
*)
reason="Unhandled event: ${EVENT_NAME}"
;;
esac
{
echo "run=${run}"
echo "auto_merge=${auto_merge}"
echo "merge_method=${merge_method}"
echo "reason=${reason}"
} >> "${GITHUB_OUTPUT}"
{
echo "## Promote decision"
echo
echo "| Key | Value |"
echo "| --- | --- |"
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}"
promote:
needs: decide
if: needs.decide.outputs.run == 'true'
runs-on: ubuntu-latest
steps:
- name: Validate GitHub App credentials
env:
APP_ID: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
PRIVATE_KEY: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
run: |
if [ -z "${APP_ID}" ] || [ -z "${PRIVATE_KEY}" ]; then
echo 'Missing SNOWLUMA_BOT_APP_ID and/or SNOWLUMA_BOT_PRIVATE_KEY secrets.' >&2
echo 'Configure the same GitHub App used by the nnphook native PR flow.' >&2
exit 1
fi
- name: Mint GitHub App installation token
id: app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
private-key: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
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
uses: actions/checkout@v6
with:
ref: main
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'
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})"
{
echo "Automated promotion of \`dev\` into \`main\`."
echo
echo "| Key | Value |"
echo "| --- | --- |"
echo "| Source | \`dev\` @ \`${DEV_SHA}\` |"
echo "| Trigger ref | \`${REF}\` |"
echo "| Trigger 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}"

View File

@@ -14,23 +14,30 @@ jobs:
fail-fast: false
matrix:
include:
- name: "win-x64"
script: "build"
- name: "win-x64-webui"
script: "build:all"
runs-on: windows-latest
- name: win-x64
os: windows-latest
target: win32-x64
- name: linux-x64
os: ubuntu-latest
target: linux-x64
- name: linux-arm64
os: ubuntu-24.04-arm
target: linux-arm64
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Setup pnpm
uses: pnpm/action-setup@v4
uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'pnpm'
@@ -38,29 +45,170 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile
# Always builds the WebUI flavor — no separate "core-only" artifact.
- name: Build project
run: pnpm run ${{ matrix.script }}
- name: Verify native files
shell: pwsh
run: |
if (!(Test-Path "dist\native\snowluma-win32-x64.node")) { throw "Missing dist\native\snowluma-win32-x64.node" }
if (!(Test-Path "dist\native\snowluma-win32-x64.dll")) { throw "Missing dist\native\snowluma-win32-x64.dll" }
env:
SNOWLUMA_TARGET: ${{ matrix.target }}
run: pnpm run build:all
- name: Bundle runtime dependencies
working-directory: dist
run: npm install --omit=dev
- name: Package release
# Naming convention:
# SnowLuma-<tag>-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node >= 22
- name: Package (windows)
if: matrix.os == 'windows-latest'
shell: pwsh
run: |
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}-lite.zip"
Copy-Item (Get-Command node).Source -Destination "dist\node.exe"
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}.zip"
- name: Package (linux)
if: startsWith(matrix.os, 'ubuntu')
run: |
chmod +x dist/launcher.sh
tar -czf "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}-lite.tar.gz" -C dist .
cp "$(command -v node)" dist/node
chmod +x dist/node
tar -czf "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}.tar.gz" -C dist .
- name: Upload build artifacts
uses: actions/upload-artifact@v7
with:
name: release-${{ matrix.name }}
path: SnowLuma-${{ github.ref_name }}-${{ matrix.name }}*
if-no-files-found: error
retention-days: 1
release:
needs: build
runs-on: ubuntu-latest
steps:
- name: Checkout (for git log)
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Download all artifacts
uses: actions/download-artifact@v7
with:
path: artifacts
- name: Collect release assets
run: |
mkdir -p release
find artifacts -type f \( -name '*.zip' -o -name '*.tar.gz' \) -exec cp {} release/ \;
ls -lh release/
- name: Generate release note
shell: bash
run: |
tag="${GITHUB_REF_NAME}"
previousTag="$(git describe --tags --abbrev=0 "${tag}^" 2>/dev/null || true)"
if [[ -n "$previousTag" ]]; then
changes="$(git log --pretty=format:'- %s (%h)' "$previousTag..$tag")"
else
changes="$(git log --pretty=format:'- %s (%h)' "$tag")"
fi
[[ -z "$changes" ]] && changes="- No commit changes detected."
cat > release-notes.md <<EOF
# SnowLuma ${tag}
## 发布概览
本次发布提供 SnowLuma 的 Windows x64 / Linux x64 / Linux arm64 构建产物,默认包含 WebUI。
## 下载说明
命名约定:
- 无后缀 \`.zip/.tar.gz\`:完整版本,内置 \`node\`/\`node.exe\` 与运行时依赖,解压即可使用。
- \`-lite\` 后缀:精简版本,不含 Node.js 运行时,需自行安装 Node.js 22+。
Windows:
- \`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\`
Linux arm64:
- \`SnowLuma-${tag}-linux-arm64.tar.gz\`
- \`SnowLuma-${tag}-linux-arm64-lite.tar.gz\`
## 更新内容
${changes}
## 使用说明
- Windows x64:\`launcher.bat\` 或 \`node index.mjs\`。
- Linux:\`./launcher.sh\` 或 \`node index.mjs\`。
- 所有压缩包均已内置 WebUI 静态资源;启动后访问 http://localhost:5099。
- Linux 版本仅提供 OneBot 桥接能力,NTQQ 进程注入仅在 Windows 下生效。
EOF
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
files: SnowLuma-*.zip
generate_release_notes: true
files: |
release/*.zip
release/*.tar.gz
body_path: release-notes.md
overwrite_files: true
draft: false
prerelease: ${{ contains(github.ref_name, '-') }}
# Triggers the Docker image build on SnowLuma.Docker.Framework once the
# GitHub Release (and its per-arch tarballs) is published, so the Docker
# workflow can pull the matching `SnowLuma-<tag>-linux-<arch>-lite.tar.gz`
# asset and bake it into the container.
#
# Chained as a job dependency rather than via `on: release: published`
# because workflows triggered by GITHUB_TOKEN cannot fire downstream
# workflow events (GitHub anti-loop safeguard). Doing it as `needs: release`
# keeps the dispatch under our PAT.
dispatch-docker:
needs: release
runs-on: ubuntu-latest
environment: SnowLuma
steps:
- name: Trigger Docker.Framework workflow_dispatch
uses: actions/github-script@v8
env:
RELEASE_REPOSITORY: ${{ vars.DOCKER_RELEASE_REPOSITORY }}
DOCKER_IMAGE: ${{ vars.DOCKER_IMAGE }}
DOCKER_PLATFORMS: ${{ vars.DOCKER_PLATFORMS }}
DOCKER_WORKFLOW: ${{ vars.DOCKER_WORKFLOW }}
DOCKER_REF: ${{ vars.DOCKER_REF }}
with:
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
script: |
const target = process.env.RELEASE_REPOSITORY;
if (!target || !target.includes('/')) {
throw new Error('Set SnowLuma environment variable DOCKER_RELEASE_REPOSITORY to owner/repo.');
}
const [owner, repo] = target.split('/');
const tag = context.ref.replace('refs/tags/', '');
const sourceRepo = context.repo.owner + '/' + context.repo.repo;
const image = process.env.DOCKER_IMAGE || 'motricseven7/snowluma';
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';
await github.rest.actions.createWorkflowDispatch({
owner,
repo,
workflow_id: workflowId,
ref,
inputs: {
image,
tag,
push: 'true',
platforms,
snowluma_tag: tag,
snowluma_repository: sourceRepo,
},
});
core.info(`Dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);

106
.github/workflows/sdk-npm-publish.yml vendored Normal file
View File

@@ -0,0 +1,106 @@
name: Publish SDK to npm
on:
push:
branches: [main]
paths:
- 'packages/sdk/**'
- 'package.json'
- 'pnpm-lock.yaml'
- 'pnpm-workspace.yaml'
- 'tsconfig.base.json'
workflow_dispatch:
permissions:
contents: read
id-token: write
concurrency:
group: sdk-npm-publish-${{ github.ref }}
cancel-in-progress: false
jobs:
publish:
name: Build, test, and publish SDK
runs-on: ubuntu-latest
environment: SnowLuma
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Type check SDK
run: pnpm --filter @snowluma/sdk typecheck
- name: Test SDK
run: pnpm --filter @snowluma/sdk test
- name: Build SDK
run: pnpm --filter @snowluma/sdk build
- name: Check npm package version
id: npm
working-directory: packages/sdk
shell: bash
run: |
set -euo pipefail
package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")"
package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")"
{
echo "package_name=${package_name}"
echo "package_version=${package_version}"
} >> "${GITHUB_OUTPUT}"
if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then
echo "already_published=true" >> "${GITHUB_OUTPUT}"
echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish."
else
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Validate npm token
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
- name: Publish SDK to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/sdk
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm publish --access public --provenance
- name: Summary
shell: bash
run: |
{
echo "## SDK npm publish"
echo
echo "| Key | Value |"
echo "| --- | --- |"
echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |"
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
echo "| Environment | \`SnowLuma\` |"
} >> "${GITHUB_STEP_SUMMARY}"

103
.github/workflows/ui-npm-publish.yml vendored Normal file
View File

@@ -0,0 +1,103 @@
name: Publish UI to npm
on:
push:
branches: [main]
paths:
- 'packages/ui/**'
- 'package.json'
- 'pnpm-lock.yaml'
- 'pnpm-workspace.yaml'
- 'tsconfig.base.json'
workflow_dispatch:
permissions:
contents: read
id-token: write
concurrency:
group: ui-npm-publish-${{ github.ref }}
cancel-in-progress: false
jobs:
publish:
name: Build and publish UI
runs-on: ubuntu-latest
environment: SnowLuma
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Type check UI
run: pnpm --filter @snowluma/ui typecheck
- name: Build UI
run: pnpm --filter @snowluma/ui build
- name: Check npm package version
id: npm
working-directory: packages/ui
shell: bash
run: |
set -euo pipefail
package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")"
package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")"
{
echo "package_name=${package_name}"
echo "package_version=${package_version}"
} >> "${GITHUB_OUTPUT}"
if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then
echo "already_published=true" >> "${GITHUB_OUTPUT}"
echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish."
else
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Validate npm token
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
- name: Publish UI to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/ui
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm publish --access public --provenance
- name: Summary
shell: bash
run: |
{
echo "## UI npm publish"
echo
echo "| Key | Value |"
echo "| --- | --- |"
echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |"
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
echo "| Environment | \`SnowLuma\` |"
} >> "${GITHUB_STEP_SUMMARY}"

40
.gitignore vendored
View File

@@ -1,27 +1,17 @@
out
build
build-*
CMakePresets.json
# Compiled files
*.o
*.obj
*.exe
*.so
*.dylib
*.a
*.lib
# CMake
CMakeCache.txt
CMakeFiles/
cmake_install.cmake
compile_commands.json
_deps/
# Ignore files generated by Claude
.claude
# Runtime generated
config.json
/node_modules
/dist
/.vscode
# Node / pnpm / monorepo
node_modules/
**/node_modules/
dist/
**/dist/
.vscode/
.idea/
/config/
/data/
logs/
# macOS metadata
.DS_Store

13
.npmrc Normal file
View File

@@ -0,0 +1,13 @@
registry=https://registry.npmmirror.com/
@moonrepo:registry=https://registry.npmmirror.com/
# Mirrors for binary downloads (sharp, esbuild, swc, electron etc.)
disturl=https://npmmirror.com/dist
electron_mirror=https://npmmirror.com/mirrors/electron/
sass_binary_site=https://npmmirror.com/mirrors/node-sass/
sharp_binary_host=https://npmmirror.com/mirrors/sharp
sharp_libvips_binary_host=https://npmmirror.com/mirrors/sharp-libvips
puppeteer_download_host=https://npmmirror.com/mirrors
auto-install-peers=true
strict-peer-dependencies=false

90
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,90 @@
# 贡献者公约 (Contributor Covenant Code of Conduct)
本文档改编自 [Contributor Covenant v2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/),是 SnowLuma 社区共同遵守的行为准则。
## 我们的承诺
身为社区成员、贡献者、维护者,我们承诺:让每一个参与 SnowLuma 项目和社区的人,不因年龄、体型、可见或不可见的身体差异、身心障碍、族裔、性别特征、性别认同与表达、经验水平、教育背景、社会经济地位、国籍、外貌、种族、宗教信仰、或性取向,而遭受骚扰。
我们承诺以营造开放、热情、多元、包容、健康社区的方式行事和互动。
## 我们的准则
有助于建立正向社区环境的行为包括但不限于:
- 对他人展现同理心与善意
- 尊重不同的意见、观点与经验
- 给予并优雅地接受建设性反馈
- 承担责任并向受我们错误影响的人致歉,并从中吸取教训
- 关注的不仅是个人,更是整个社区的最大利益
不可接受的行为包括但不限于:
- 使用情色化的语言或意象,及任何形式的性关注或性骚扰
- 嘲讽、侮辱或贬损性的评论,以及人身或政治攻击
- 公开或私下的骚扰
- 未经明确许可,公布他人的私人信息,例如物理或电子邮件地址
- 其他在专业场合中可被合理认定为不当的行为
## 适用范围
本行为准则适用于所有社区场所,也适用于个人在公开场合代表社区时的言行。代表本社区的情形包括但不限于:使用项目官方电子邮件地址、通过项目官方社交媒体账号发文、以指定代表身份出席线上或线下活动。
具体到 SnowLuma,本准则适用于:
- 本仓库(含 issue、PR、discussion、commit message、code review 评论)
- 项目相关的 QQ 群、Telegram 群以及未来可能新增的官方社群
- 任何以 SnowLuma 名义对外发起的活动或交流
## 执行责任
社区维护者负责诠释并执行我们所认定的可接受行为标准,并将对任何他们认为不当、具威胁性、冒犯性或有害的行为采取适当且公正的纠正措施。
社区维护者有权且有责任删除、编辑或拒绝任何不符合本行为准则的评论、提交、代码、wiki 编辑、issue 及其他贡献,并将在适当时机说明做出审核决策的理由。
## 举报方式
如果你目击或亲身经历了不当行为,请通过以下任一渠道**私下**联系维护者:
- QQ:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)(私聊管理员,请勿在群内公开)
- Telegram:[SnowLuma-TG](https://t.me/napcatqq)(私聊管理员)
请勿在 GitHub issue 或公开频道直接发布举报内容,以免对相关方造成二次伤害。
所有投诉都会被及时和公平地审查与调查。所有社区维护者都有义务尊重举报者的隐私与人身安全。
## 执行准则
社区维护者将依据以下「社区影响指引」来判定违反本行为准则之行为的处置方式:
### 1. 更正 (Correction)
**社区影响**:使用了不恰当的言语,或其他在社区中被视为不专业或不受欢迎的行为。
**后果**:由社区维护者私下提出书面警告,明确指出该行为违反规则之处并解释为何不妥。可能要求公开致歉。
### 2. 警告 (Warning)
**社区影响**:通过单一事件或一系列行为造成违规。
**后果**:警告并说明持续行为的后果。在指定时间内禁止与相关人员互动,包括主动联系本行为准则执行者。这包括避免在社区场所及外部渠道(如社交媒体)的互动。违反这些条款可能导致临时或永久封禁。
### 3. 临时封禁 (Temporary Ban)
**社区影响**:严重违反社区准则,包括持续的不当行为。
**后果**:在指定时间内禁止与社区进行任何形式的互动或公开交流。在此期间不得与相关人员有任何公开或私下的互动,包括主动联系本行为准则执行者。违反这些条款可能导致永久封禁。
### 4. 永久封禁 (Permanent Ban)
**社区影响**:表现出违反社区准则的模式,包括持续的不当行为、骚扰个人、或对某类群体进行攻击或贬低。
**后果**:永久禁止在社区内进行任何形式的公开互动。
## 致谢
本行为准则改编自 [Contributor Covenant 2.1 版](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html)。
社区影响指引灵感来自 [Mozilla 的行为准则执行阶梯](https://github.com/mozilla/diversity)。
如需了解本准则的常见问题,请参阅 [FAQ](https://www.contributor-covenant.org/faq)。中文版译本可参考 [Contributor Covenant 中文翻译](https://www.contributor-covenant.org/zh-cn/version/2/1/code_of_conduct/)。

287
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,287 @@
# 贡献指南
欢迎!如果你正在阅读这份文档,多半是因为你想给 SnowLuma 提一个 PR、修一个 bug,或者只是想了解这个项目是怎么运作的。无论你是第一次接触开源、还是已经有十年经验,我们都希望让你尽快上手。
参与项目即视为你同意遵守 [行为准则(Code of Conduct)](./CODE_OF_CONDUCT.md)。在开始之前请花两分钟读一下,它定义了我们希望社区维持的氛围。
---
## 在动手之前
SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时可能变化**。如果你打算做较大的改动,强烈建议先在 issue 或者社群里和维护者对齐一下方向,避免做了一半发现已经被另一条路替代。
不知道从哪里入手?以下几类贡献最容易被合并:
- 修复你在使用中遇到的具体 bug,附最小复现步骤。
- 改善错误提示、文档、注释、类型签名。
- 给已有模块补测试,尤其是 `packages/core` 下覆盖率较低的部分。
- 实现 [RoadMap.md](./RoadMap.md) 中列出的、还没被认领的项。
如果你只是想看看代码长什么样,可以直接跳到 [本地开发环境](#本地开发环境)。
---
## 项目结构速览
这是一个 pnpm workspace monorepo,主要 package 如下:
| 路径 | 作用 |
| --- | --- |
| `packages/core` | 核心运行时:协议、桥接、OneBot 适配、WebUI 服务端 |
| `packages/sdk` | 面向第三方开发者的 SDK,会发布到 npm |
| `packages/runtime` | 运行时辅助包 |
| `packages/websocket` | WebSocket 实现 |
| `packages/webui` | 基于 Vite + React 的前端控制台 |
| `tools/` | 版本管理、发布脚本 |
| `.github/workflows/` | CI / 发布 / 自动合并工作流 |
入口在 `packages/core/src/index.ts`,整体架构在 `packages/core/src/bridge/` 下能看出大致脉络。
---
## 本地开发环境
### 系统要求
- **Node.js ≥ 22**(`engines` 字段强制,低版本会报错)
- **pnpm 10.28.0+**(项目通过 `packageManager` 字段锁定,建议用 `corepack enable` 安装匹配版本)
- macOS / Linux / Windows 均可。如果要构建原生产物,需要对应平台的工具链。
### 拉代码、装依赖、跑起来
```bash
# 1. Fork 仓库后克隆你自己的 fork
git clone https://github.com/<你的用户名>/SnowLuma.git
cd SnowLuma
# 2. 切到 dev 分支(所有开发都基于 dev,不是 main)
git checkout dev
# 3. 安装依赖
pnpm install
# 4. 跑类型检查,确认环境 OK
pnpm typecheck
# 5. 跑测试
pnpm test
# 6. 启动开发模式
pnpm dev # core
pnpm dev:web # webui
```
如果 `pnpm install` 卡住或报错,先确认 Node 版本和 pnpm 版本,再看 `.npmrc` 里是否配置了你环境下可用的 registry。
---
## 第一次提交 PR
### 1. 创建分支
请基于 `dev` 创建分支,不是 `main`。`main` 是受保护的稳定分支,PR 也不要直接提到 `main`。
```bash
git checkout dev
git pull upstream dev # 假设你把官方仓库设为 upstream remote
git checkout -b fix/onebot-mention-encoding
```
分支命名没有强制规则,但建议用 `fix/...`、`feat/...`、`docs/...`、`refactor/...` 这种前缀,便于一眼看出意图。
### 2. 写代码
- **保持改动聚焦**:一个 PR 只做一件事。顺手发现的其他问题请单独开 issue 或新 PR。
- **跟随既有风格**:不要为了你个人偏好引入大规模格式化或重命名。
- **写测试**:修 bug 时优先写一个能复现该 bug 的测试,确认它会 fail,再让它 pass。新增功能至少补上 happy path 的测试。
- **不要添加无意义的注释**:标识符已经说清楚的事情不需要再写一遍。注释应当解释"为什么",而不是"做了什么"。
提交之前请本地跑一遍:
```bash
pnpm typecheck
pnpm test
```
CI 上跑的是同一套检查,本地通过几乎能保证 CI 通过。
### 3. 提交信息
我们大致遵循 [Conventional Commits](https://www.conventionalcommits.org/zh-hans/v1.0.0/):
```
<type>(<scope>): <subject>
<body>
```
`type` 常用:`feat` / `fix` / `docs` / `refactor` / `test` / `chore` / `perf`。
`scope` 常用:`core` / `sdk` / `webui` / `onebot` / `bridge` / `protocol` 等模块名。
示例:
```
fix(onebot): handle empty mention segments in group messages
refactor(bridge): extract BridgeInterface as the OneBot-facing seam
docs: clarify dev environment setup steps
```
> ⚠️ **请不要**在你的提交信息里使用 `[merge]` 前缀或 `chore(release):` 前缀 —— 这两个前缀是维护者用来触发自动合并到 `main` 的,会让你的 PR 行为异常。详见后文 [维护者参考](#维护者参考release--自动合并流程)。
### 4. 推送并发起 PR
```bash
git push origin fix/onebot-mention-encoding
```
到 GitHub 上发起 PR,**目标分支选 `dev`**。请在 PR 描述里写明:
- 这个 PR 解决什么问题 / 实现什么功能。
- 主要的实现思路(如果有非显然的取舍)。
- 测试方式(你跑了什么、怎么验证有效)。
- 关联的 issue(如有)。
### 5. Code Review 与合并
- 维护者会在能腾出时间时来 review。如果一周内没有任何回应,欢迎在 PR 里 @ 一下,或者去社群里提醒。
- review 意见请尽量在同一个 PR 内修改,避免反复关闭重开。
- 合并方式由维护者决定,通常是 squash merge 到 `dev`。**`main` 由维护者通过自动化工作流统一从 `dev` 合入**,你不需要操心 `main`。
---
## 风格与约定
### 代码风格
- TypeScript 严格模式,按 `tsconfig.base.json` 配置。
- 优先用现有抽象,不要为"假想的未来需求"提前抽象。
- 不要给内部函数加防御性的参数校验,除非是系统边界(用户输入、外部 API)。
- 不要保留死代码、被注释掉的代码或者 `// TODO` 没有具体上下文的占位。
### 测试
- 单测放在被测代码同包的 `tests/` 或同目录的 `*.test.ts`,按既有风格走。
- 测试要描述行为,不要测实现细节。`it('should call internal foo')` 这种是反例。
- 涉及 IO / 时序 / 外部进程的,用现有的 fake/stub 模式,参考 `packages/core/src/onebot/` 下的 `fake-bridge` 类测试。
### 文档
- 用户/贡献者可见的行为变化,需要相应更新 README 或对应 package 下的文档。
- SDK 的破坏性变更必须更新 `packages/sdk/CHANGELOG.md` 和 `packages/sdk/VERSIONING.md`。
---
## 报告 Bug / 请求功能
- **Bug 报告**:开 issue,附最小复现步骤、期望行为、实际行为、版本号、运行环境。能附上日志最好。
- **功能请求**:先描述你想解决的实际场景,再描述你想要的接口。维护者更在意"为什么需要"而不是"具体怎么做"。
- **安全问题**:请勿公开发 issue,先通过社群私聊联系维护者。
社群入口(见 [README](./README.md)):
- QQ:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
- Telegram:[SnowLuma-TG](https://t.me/napcatqq)
---
## 维护者参考:release & 自动合并流程
> 以下内容主要写给具备 `main` 推送 / 发版权限的维护者。普通贡献者只需要把 PR 提到 `dev`,不需要关心这一节。
### 分支模型
SnowLuma 使用 **`main` + `dev`** 双分支模型:
- **`main`** — 受保护的稳定分支,仅接收来自 `dev` 的合并 PR。**禁止直接 push**。
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先合入 `dev`。
- **`native/auto-update-*`** — 由 `SnowLuma Bot` 自动创建的原生产物更新分支(来自 `SnowLumaNative`,不需要手动维护)。
### 把 `dev` 合并到 `main`
工作流 `.github/workflows/promote-dev-to-main.yml` 会以 `SnowLuma Bot` 身份开 / 更新一个 `dev → main` 的 PR,并可选地自动合并。无论用哪种触发方式,工作流都会调用 `gh pr merge --auto`:**只有 `main` 分支保护中所有 required status checks(typecheck + 各架构 build)都通过后,机器人才会真正合并**。失败的工作流会卡住合并。
#### 1. 提交信息前缀(推荐日常使用)
向 `dev` push 一个提交,提交信息**以**以下任一前缀**开头**即触发(不区分大小写):
- `[merge]` — 例如 `[merge] fix: hotfix for OneBot mention`
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯
> 是**前缀**匹配,不是任意位置。`fix: something [merge]` 不会触发,必须把 `[merge]` 写在最前面。
#### 2. 推送 `chore.*` Tag
任何符合 `chore.*` 的 tag(如 `chore.merge-20240509`、`chore.promote-v1.7.0`)被推送时也会触发:
- `chore.*` → 仅触发 `promote-dev-to-main.yml`(开 PR,自动合并)
- `v*` → 仅触发 `release.yml`(构建发布产物)
推荐流程:先用 `chore.*` tag 把 `dev` 合入 `main`,待合并完成后再在 `main` 上打 `v*` tag 触发发布。这样 `release.yml` 始终基于已过完所有检查的 `main` HEAD 构建。
#### 3. 手动触发
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。可选输入:
- `auto_merge`:是否启用 auto-merge(默认 `true`)。
- `merge_method`:`merge` / `squash` / `rebase`(默认 `merge`)。
### 启用 `main` 分支保护(必做)
仓库管理员需要在 GitHub 上为 `main` 配置规则集(Repository Rules)或经典分支保护,至少满足:
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` 即可重新触发检查。
### 必需的 Secrets
`promote-dev-to-main.yml` 复用 `SnowLumaNative/build-native.yml` 同一个 GitHub App。请确认 SnowLuma 仓库(或 organization)级别已经配置:
- `SNOWLUMA_BOT_APP_ID` — 数字类型的 App ID。
- `SNOWLUMA_BOT_PRIVATE_KEY` — 该 App 的 PEM 私钥。
App 必须在本仓库已安装,且授予 **Contents: Read+Write**、**Pull requests: Read+Write**。
### 本地工作流速查(维护者)
```bash
# 把 dev 合入 main(三选一)
# 方式 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 等
git push origin chore.merge-20240509 # → 触发 promote-dev-to-main
# 方式 C:在 Actions 页面手动 Run workflow
# 合并完成后,发布版本(在 main 上打 v* tag)
git checkout main && git pull
git tag v1.7.0
git push origin v1.7.0 # → 仅触发 release.yml
```
---
## 还有问题?
- 看一下已有的 issue 和 PR,可能你的问题已经被讨论过。
- 去社群问一句(QQ / TG 链接见上方)。
- 如果只是想确认"我这么改 OK 吗",欢迎开 draft PR,先把代码亮出来再讨论。
感谢你愿意花时间贡献 SnowLuma —— 这个项目能走多远,取决于你们每一个人。❄️

133
README.md
View File

@@ -1,22 +1,131 @@
# ❄️ SnowLuma
> Next Remote Protocol Framework.
<h1 align="center">❄️ SnowLuma</h1>
<p align="center">
<i>Next Remote Protocol Framework.</i>
</p>
## 关于项目
项目处于开发初期,仅支持部分功能,持续高速迭代中,仅支持有头。
<p align="center">
<a href="https://github.com/SnowLuma/SnowLuma/releases"><img alt="Release" src="https://img.shields.io/github/v/release/SnowLuma/SnowLuma?label=release&style=flat-square"></a>
<a href="https://github.com/SnowLuma/SnowLuma/actions"><img alt="Build" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/release.yml?branch=main&style=flat-square&label=build"></a>
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="@snowluma/sdk" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=%40snowluma%2Fsdk&color=cb3837"></a>
<a href="https://www.npmjs.com/package/@snowluma/ui"><img alt="@snowluma/ui" src="https://img.shields.io/npm/v/%40snowluma%2Fui?style=flat-square&label=%40snowluma%2Fui&color=cb3837"></a>
<a href="https://github.com/SnowLuma/SnowLuma/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
</p>
<p align="center">
<a href="https://github.com/SnowLuma/SnowLuma/releases">Releases</a> ·
<a href="https://github.com/SnowLuma/SnowLuma/issues">Issues</a> ·
<a href="https://qm.qq.com/q/g3UMLpWALe">QQ 群</a> ·
<a href="https://t.me/napcatqq">Telegram</a>
</p>
---
## 简介
SnowLuma 在 QQ 客户端与生态侧之间承担协议转换工作,向上以 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准协议暴露能力。Bridge 层负责会话与事件枢纽,再通过 WebSocket / HTTP / WebUI 等多种适配器对外提供接入。
项目持续迭代中,稳定版本通过 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 发布。
## 特性
- **OneBot v11 兼容** —— 涵盖文本、图片、视频、语音、合并转发、戳一戳、Markdown、JSON、XML 等常用消息段。
- **多账号并行** —— 同一进程可同时托管多个 QQ 账号,会话彼此独立。
- **多种适配器** —— WebSocket Server / WebSocket Client / HTTP Server / HTTP Post,HTTP 服务端同时支持 `application/json` 与 `application/x-www-form-urlencoded`。
- **WebUI 管理面板** —— 浏览器登录、密码强度校验、登录限流、SSE 实时日志、配置热更新。
- **TypeScript 全链路** —— Bridge / OneBot / SDK / UI 均使用 TypeScript,发布到 npm 的 `@snowluma/sdk` 与 `@snowluma/ui` 可直接供下游应用消费。
- **数据持久化** —— 好友、群、群成员等关系数据落 SQLite,跨重启可用。
## 快速开始
下载预构建发布包:
```bash
# 从 Releases 下载 zip,解压到任意目录
./launcher.bat # Windows
```
或从源码开发:
```bash
git clone https://github.com/SnowLuma/SnowLuma.git
cd SnowLuma
pnpm install
pnpm build
pnpm start
```
WebUI 默认监听 `5099` 端口。首次启动会在控制台打印 `initial credentials: user=admin password=<...>`,登录后请立即修改。
若未完成首次改密就关闭进程,下次启动会自动重新生成一个新的随机密码。
## 工作区
本仓库使用 pnpm monorepo 管理,各包职责如下:
| 包 | 说明 |
| --- | --- |
| [`@snowluma/core`](packages/core) | 核心:协议层 / Bridge / OneBot / WebUI 全部在此。 |
| [`@snowluma/sdk`](packages/sdk) | OneBot HTTP & WebSocket TypeScript SDK,发布到 npm。 |
| [`@snowluma/ui`](packages/ui) | Tailwind 4 共享组件库(shadcn 风格),发布到 npm。 |
| [`@snowluma/websocket`](packages/websocket) | OneBot WebSocket 适配器底层。 |
| [`@snowluma/proton`](packages/proton) | 编译期 protobuf 编/解码器生成器:TS interface 标注 `pb<N, T>`,Vite 插件在构建时把 `protobuf_encode<T>` / `protobuf_decode<T>` 替换为内联 codec,零运行时反射。 |
| [`@snowluma/runtime`](packages/runtime) | 运行时清单与发布包资源。 |
| [`webui`](packages/webui) | Web 管理面板前端。 |
## 架构
```mermaid
flowchart TD
A([QQ 客户端])
B["协议层<br/><sub>packet pipeline · cmd 分派</sub>"]
C["Bridge 层<br/><sub>会话调度 · 花名册缓存 · 消息发送</sub>"]
D["OneBot 层<br/><sub>Event Converter · Action Handler</sub>"]
E([WS / HTTP / WebUI])
A --> B --> C --> D --> E
```
## 文档
- [路线图](RoadMap.md)
- [贡献指南](CONTRIBUTING.md)
- [行为准则](CODE_OF_CONDUCT.md)
## 开发命令
```bash
pnpm dev # 启动 core dev server
pnpm dev:web # 启动 webui dev server
pnpm test # 运行 core 测试
pnpm typecheck # 全仓库 type check
pnpm build:all # 构建 core + sdk + webui
```
## 鸣谢
[LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) - Proto
[NapCatQQ](https://github.com/NapNeko/NapCatQQ) - Scaner/Packet
- [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) —— Proto 定义参考。
- [NapCatQQ](https://github.com/NapNeko/NapCatQQ) —— Scanner 与 Packet 处理实现参考。
## 辅助编程
## 贡献者
推荐 Opus4.6 + Gemini3.1pro 对本项目辅助开发
感谢每一位为 SnowLuma 提交过代码的伙伴。
本项目大量使用Ai技术。
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors">
<img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" alt="Contributors" />
</a>
## 加入我们
[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
## Star 趋势
[SnowLuma-Tg](https://t.me/napcatqq)
<a href="https://star-history.com/#SnowLuma/SnowLuma&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
</picture>
</a>
## 社区
- QQ 群:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
- Telegram:[SnowLuma-TG](https://t.me/napcatqq)
- 问题反馈:[GitHub Issues](https://github.com/SnowLuma/SnowLuma/issues)

491
RoadMap.md Normal file
View File

@@ -0,0 +1,491 @@
# SnowLuma v3 — 目标架构
> v2 已完成:UID/UIN Service(SQLite 持久化)、tsx+map Debug、包拆分、proto-defs 剥离、消息 hot-path 优化(17.5μs → 4.7μs)、NapCat 风格 Api 层、Bridge/Account 分层(v2 发布在 `@snowluma/bridge`,v3 重命名为 `@snowluma/channel`)。
---
## 0. 数据流总览(一图概览所有权)
```
┌─ @snowluma/channel-hook ─────────┐ ┌─ @snowluma/channel-socket ──────┐
│ HookManager + HookChannel │ │ SocketChannel (future) │
│ — 仅 send/recv + pid/hook state — │ │ — 仅 send/recv + socket state — │
└────────────┬─────────────────────┘ └─────────────┬───────────────────┘
│ Channel 实例 │
└───────────┬──────────────────────────┘
│ 通过 ChannelAdapter 注册
▼
┌─ @snowluma/core ──── Hub(主入口 / 持有一切)──────────────┐
│ │
│ 内部:Map<uin, Core> │
│ │
│ channel available ──► ctx = capability(channel) │
│ ──► core = new Core(ctx) │
│ ──► emit 'core-online' { uin, apis, events, ... } │
│ │
│ channel gone ──► core.dispose() + emit 'core-offline' { uin } │
└─────────────────────────────────────┬─────────────────────────────────┘
│ 顶层 lifecycle 事件(仅 2 个)
▼
┌─ @snowluma/onebot ──────────────────────────────────────────────────────┐
│ hub.events.on('core-online', ctx => { │
│ this.byUin.set(ctx.uin, ctx); │
│ ctx.events.on('group_message', e => …); // 每账号 bus │
│ }); │
│ // 处理 OneBot action: │
│ this.byUin.get(uin)?.apis.message.sendGroup(...) │
└─────────────────────────────────────────────────────────────────────────┘
```
**核心约定**:
- `Channel` / adapter 包 **只**做 send/recv + 自己的内部状态(pid set / hook session / socket fd)。完全无业务。
- `Hub` 是**主入口**,独占持有 Channels + Cores。`Core` 实例由它构造,外部拿不到 Core 类本身。
- `Core` 通过 **ctx**(capability,一个 POJO)拿到 send/recv,从不直接持有 Channel。
- 外部消费者(OneBot / WebUI)只拿 `CoreCtx`(Core 的对外投影:`{ uin, apis, events, identity }`),不知道 Core 类的存在。
- 每个账号一个 `events`(在 Core 上),不做全局 bus;Hub 只 emit 两个顶层生命周期事件。
---
## 1. 目标包结构
```
SnowLuma/
├── packages/
│ │
│ │ ── Infrastructure(无业务) ──
│ ├── common/ logger / packet-sender / protocol-types / async-context
│ ├── proto-defs/ protobuf TS 接口定义
│ ├── proton/ protobuf codec 编译时生成器
│ ├── runtime/ native .node 产物清单
│ ├── ui/ Tailwind v4 + shadcn 组件(前端)
│ │
│ │ ── Protocol(解析层,纯函数) ──
│ ├── protocol/ events / identity-service / msg-push / oidb / highway /
│ │ element-builder / packet-pipeline / event-bus
│ │
│ │ ── Channel & adapters(transport 端口与实现) ──
│ ├── channel/ ⭐ Channel 接口 + 抽象类 + ChannelAdapter 端口
│ │ —— 只定义接口和最小抽象,**不**含 Hub
│ ├── channel-hook/ ⭐ HookManager + HookChannel + HookAdapter
│ │ —— 现 @snowluma/channel 大部分内容搬来
│ ├── channel-socket/ ⭐ 未来:SocketChannel + SocketAdapter
│ │
│ │ ── Core(主入口 + 业务封装) ──
│ ├── core/ ⭐ Core + Hub + CoreCtx + ApiHub + 协议封装
│ │ —— Hub 在这里(避免 channel↔core 循环)
│ │
│ │ ── Inbound(外部协议消费 CoreCtx) ──
│ ├── onebot/ OneBot v11 (HTTP + WS)
│ ├── websocket/ 底层 WS server(被 onebot / webui-backend 共用)
│ ├── webui-backend/ ⭐ Hono server + REST/WS(拆自 webui)
│ ├── webui-frontend/ ⭐ Vite SPA(拆自 webui)
│ └── sdk/ TS SDK
│
├── package.json
└── pnpm-workspace.yaml
```
⭐ 标记的是 v3 改动。
### 1.1 关键变动
| 当前 | 目标 | 备注 |
|---|---|---|
| `@snowluma/bridge`(hook + transport + adapter + manager) | `@snowluma/channel`(仅接口 + abstract Channel)+ `@snowluma/channel-hook`(hook 实现) | 包名 v2 叫 bridge,v3 重命名;hook 全套迁出独立包 |
| `@snowluma/core`(含 Account + AccountManager) | `core`:Core + Hub | Account → Core;AccountManager 折进 Hub |
| —— | `channel-socket` | 新建 stub |
| `@snowluma/webui` | `webui-backend` + `webui-frontend` | 前后端拆分 |
### 1.2 依赖 DAG(无环)
```
common ◄── proton, proto-defs, protocol, runtime, ui, channel
proto-defs ◄── protocol
proton ◄── protocol
protocol ◄── core
channel ◄── channel-hook, channel-socket, core
channel-hook ◄── core
channel-socket ◄── core
core ◄── onebot, webui-backend
websocket ◄── onebot, webui-backend
ui ◄── webui-frontend
```
**核心要点**:`core` 是唯一一处同时知道 `channel` 端口 + 业务实现的地方。Channel 包不反向依赖 core,因此 Hub **住在 core**,而不是 channel —— 名字保留 `Hub` 是因为它语义上仍是「channel 集群的指挥官」。
---
## 2. 三个关键类型 / 接口(设计核心)
整个系统由 **3 个类型** 串起来。每个职责单一、边界清晰。
### 2.1 `Channel`(在 `@snowluma/channel`)—— 纯 transport
```ts
// packages/channel/src/channel.ts
export type ChannelKind = 'inject' | 'socket';
export interface Channel {
readonly kind: ChannelKind;
readonly uin: string;
readonly id: string; // adapter:uin 形式
sendRawPacket(cmd: string, body: Uint8Array): Promise<SendPacketResult>;
setPacketHandler(h: ((pkt: PacketInfo) => void) | null): void;
deliverPacket(pkt: PacketInfo): void; // adapter 内部用
dispose(): void;
}
```
Adapter 包(`channel-hook` / `channel-socket`)的具体类(`HookChannel` / `SocketChannel`)实现 `Channel`。它们的内部状态(PID set、hook session、socket fd)对外不可见。
### 2.2 `ChannelCtx`(在 `@snowluma/channel`)—— channel → core 的能力 POJO
```ts
// packages/channel/src/channel-ctx.ts
export interface ChannelCtx {
readonly uin: string;
readonly kind: ChannelKind;
readonly sendRawPacket: (cmd: string, body: Uint8Array) => Promise<SendPacketResult>;
readonly onPacket: (h: (pkt: PacketInfo) => void) => void;
readonly dispose: () => void;
}
// Hub 用 makeCtx(channel) 把 Channel 投影成 ChannelCtx:
export function makeChannelCtx(b: Channel): ChannelCtx {
return {
uin: b.uin, kind: b.kind,
sendRawPacket: (c, x) => b.sendRawPacket(c, x),
onPacket: (h) => b.setPacketHandler(h),
dispose: () => b.dispose(),
};
}
```
**关键设计**:`Core` 只接收 `ChannelCtx`(capability POJO),**不**持有 `Channel` 类引用。这样 `core` 包不依赖任何 adapter 实现细节,连 Channel 抽象类都不用 import。
### 2.3 `CoreCtx`(在 `@snowluma/core`)—— core → onebot 的能力 POJO
```ts
// packages/core/src/core-ctx.ts
export interface CoreCtx {
readonly uin: string;
readonly kind: ChannelKind;
readonly apis: ApiHub; // 所有 typed api(message/contacts/...)
readonly events: EventBus; // 该账号的事件(per-uin)
readonly identity: IdentityService; // UID/UIN/group roster
}
```
**关键设计**:OneBot 拿到的就是这个 POJO 投影,**不**持有 `Core` 类引用。Hub 在 `core-online` 事件里把 `CoreCtx` 透出去;OneBot 按 uin 存起来用。
---
## 3. `Hub` —— 主入口完整实现
所有所有权、生命周期、装配都在这里。**外部 main.ts 只跟它打交道。**
```ts
// packages/core/src/hub.ts
import { Channel, ChannelAdapter, ChannelAdapterHost, makeChannelCtx } from '@snowluma/channel';
import { Core } from './core';
import type { CoreCtx } from './core-ctx';
import { TypedEmitter } from '@snowluma/common/typed-emitter';
type Lifecycle = {
'core-online': CoreCtx;
'core-offline': { uin: string };
};
export class Hub {
private readonly cores = new Map<string, Core>();
private readonly adapters: ChannelAdapter[] = [];
readonly events = new TypedEmitter<Lifecycle>();
registerAdapter(a: ChannelAdapter): void {
this.adapters.push(a);
}
async start(): Promise<void> {
const host: ChannelAdapterHost = {
onChannelReady: (b) => this.onChannelReady(b),
onChannelGone: (uin) => this.onChannelGone(uin),
};
await Promise.all(this.adapters.map((a) => a.start(host)));
}
async stop(): Promise<void> {
await Promise.all(this.adapters.map((a) => a.stop()));
for (const c of this.cores.values()) c.dispose();
this.cores.clear();
}
// ─── private ───────────────────────────────
private onChannelReady(channel: Channel): void {
const stale = this.cores.get(channel.uin);
if (stale) {
stale.dispose();
this.events.emit('core-offline', { uin: channel.uin });
}
const core = new Core(makeChannelCtx(channel));
this.cores.set(channel.uin, core);
this.events.emit('core-online', core.publicCtx);
}
private onChannelGone(uin: string): void {
const core = this.cores.get(uin);
if (!core) return;
core.dispose();
this.cores.delete(uin);
this.events.emit('core-offline', { uin });
}
}
```
## 4. `Core` 实现要点
```ts
// packages/core/src/core.ts
import type { ChannelCtx } from '@snowluma/channel';
import { EventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
import { buildApiHub, type ApiHub } from './apis';
import type { CoreCtx } from './core-ctx';
export class Core {
readonly events = new EventBus(); // ← 每账号一个 bus
readonly identity: IdentityService;
readonly apis: ApiHub;
private readonly pipeline: IncomingPacketPipeline;
constructor(private readonly channelCtx: ChannelCtx) {
this.identity = IdentityService.openForUin(channelCtx.uin);
this.pipeline = new IncomingPacketPipeline(this.events, this.identity);
this.apis = buildApiHub(this); // apis 内部持 Core 引用,调 sendRawPacket
channelCtx.onPacket((pkt) => this.pipeline.process(pkt));
}
// 给外部消费者的投影(只读 POJO,不暴露 Core 实例)
get publicCtx(): CoreCtx {
return {
uin: this.channelCtx.uin,
kind: this.channelCtx.kind,
apis: this.apis,
events: this.events,
identity: this.identity,
};
}
// apis 内部通过 core 调发包
sendRawPacket(cmd: string, body: Uint8Array) {
return this.channelCtx.sendRawPacket(cmd, body);
}
dispose(): void {
this.channelCtx.dispose();
this.identity.close();
}
}
```
## 5. OneBot 消费 `CoreCtx`
```ts
// packages/onebot/src/manager.ts
import type { Hub, CoreCtx } from '@snowluma/core';
export class OneBotManager {
private readonly byUin = new Map<string, CoreCtx>();
bind(hub: Hub): void {
hub.events.on('core-online', (ctx) => this.attach(ctx));
hub.events.on('core-offline', ({ uin }) => this.detach(uin));
}
private attach(ctx: CoreCtx): void {
this.byUin.set(ctx.uin, ctx);
ctx.events.on('group_message', (e) => this.dispatchGroupMessage(ctx, e));
ctx.events.on('private_message',(e) => this.dispatchPrivateMessage(ctx, e));
// ... 其它 kind
}
private detach(uin: string): void {
this.byUin.delete(uin);
// ctx.events 随 Core dispose 一起释放
}
// 处理 OneBot HTTP/WS action:用 uin 查到 ctx,直接调 apis
async handleSendGroupMsg(uin: string, groupId: number, msg: OneBotMsg) {
const ctx = this.byUin.get(uin);
if (!ctx) throw new Error(`unknown uin: ${uin}`);
return ctx.apis.message.sendGroup(groupId, msg); // ← 直接调封装好的 api
}
}
```
## 6. 主入口(`packages/core/src/index.ts`)
```ts
import { HookAdapter } from '@snowluma/channel-hook';
import { OneBotManager } from '@snowluma/onebot';
import { Hub } from './hub';
const hub = new Hub();
hub.registerAdapter(new HookAdapter({ autoLoadOnDiscovery: true }));
// hub.registerAdapter(new SocketAdapter()); // 未来
const onebot = new OneBotManager();
onebot.bind(hub);
await hub.start();
await initWebUI(port, onebot, /* hookManager from adapter */);
```
9 行装配,每行都是有意义的所有权声明。
---
## 7. 为什么这样设计优雅
### 7.1 单向数据流
```
adapter → Channel → ChannelCtx → Core → CoreCtx → OneBot
transport capability capability
```
**没有反向引用**:Core 不知道 Channel 类,OneBot 不知道 Core 类。每层只看到「下一层的能力 POJO」。
### 7.2 单一所有者
`Hub.cores: Map<uin, Core>` 是 **唯一** 持有 Core 的地方。OneBot 只持 `CoreCtx`(投影,不算所有权)。Core 销毁 = 从这个 Map 里删 = 所有 ctx 同时失效。无需引用计数、无需 GC 协调。
### 7.3 每账号独立 EventBus
Core 自带 `events: EventBus`,互不干扰。OneBot 通过 `core-online` 拿到 ctx 后立即 subscribe,`core-offline` 时 Core 已 dispose,bus 自然失效,不会泄漏。**没有全局 bus**,没有「哪个账号的事件」问题。
### 7.4 完全可测
- 测 Channel:mock `setPacketHandler` 回调(已在 `account-private-routing.test.ts` 用 `FakeChannel` 验证)
- 测 Core:传 `ChannelCtx` POJO 即可,无需真 Channel
- 测 OneBot:emit 一个 `core-online` + 假 `CoreCtx`
- 测 Hub:用 fake `ChannelAdapter`
每层都能独立测试。
### 7.5 内部还要避免 ctx 漫天的两个小招
**(a) Api 类捕获 deps(已做)**
```ts
class MessageApi {
constructor(private readonly core: Core) {}
// 方法签名只有业务参数:
async sendGroup(groupId: number, msg: Msg) { this.core.sendRawPacket(...) }
}
```
**(b) AsyncLocalStorage 处理日志 / trace(建议引入)**
```ts
// packages/common/src/async-context.ts
import { AsyncLocalStorage } from 'node:async_hooks';
const als = new AsyncLocalStorage<{ uin?: string; trace?: string }>();
export const runInContext = <T>(c: { uin?: string; trace?: string }, fn: () => T) =>
als.run(c, fn);
export const ctx = () => als.getStore() ?? {};
// logger 自动 prefix [uin],业务代码不用接 log 参数
```
在 `Core.constructor` 给 `onPacket` 包一层:
```ts
channelCtx.onPacket((pkt) => {
runInContext({ uin: channelCtx.uin, trace: `pkt:${pkt.seqId}` }, () => {
this.pipeline.process(pkt);
});
});
```
所有下游 `log.info()` 自动带 `[10001]` 前缀,不污染业务签名。开销 ~50ns/call。
---
## 8. 不要的设计(保持简单)
| 方案 | 不做的原因 |
|---|---|
| **`CoreFactory` 抽象** | Core 只一种,多此一举。直接 `new Core(ctx)` |
| **全局 EventBus** | 每账号自己的 bus 更清晰,OneBot 按 uin 订阅,不混杂 |
| **`AccountManager` 独立层** | 多余的中间层,折进 `Hub` |
| **`InboundAdapter` 抽象** | OneBot / WebUI 数量有限且固定,直接 `bm.events.on(...)` 即可,不抽插件层 |
| **DI 容器(tsyringe 等)** | 9 行手动装配已经清晰,DI 引入反射/装饰器元数据反而难调 |
| **Effect monad / Reader monad** | TS 缺 do-notation,类型噪音 > 收益 |
| **CQRS / Event-sourced state** | 当前状态量级(10 账号 × 100 群)远未到 |
---
## 9. 迁移路线(每步独立可 ship)
> typecheck + 全测试通过才进下一步。
**Step 1** —— ⭐ 重命名 + 拆现有的 `@snowluma/bridge`
- `packages/bridge/` 重命名为 `packages/channel/`;package.json name 改为 `@snowluma/channel`
- 新建 `packages/channel-hook/`,从 `@snowluma/channel` 搬:`hook-manager.ts` / `hook-session.ts` / `hook-packet-client.ts` / `injector.ts` / `pipe-watcher.ts` / `qq-hook-client.ts` / `qq-port-probe.ts` / `hook-channel.ts`(原 inject-bridge.ts)/ `hook-adapter.ts`(原 inject-adapter.ts)
- `@snowluma/channel` 留:`channel.ts`(abstract,原 bridge.ts)/ `channel-interface.ts` / `channel-ctx.ts`(新)/ `adapter.ts`(端口)+ `makeChannelCtx` 工具
- 删除:`manager.ts`(原 BridgeManager)(搬到 core/hub.ts)/ `socket-channel.ts` + `socket-adapter.ts`(搬到 `channel-socket` stub)
**Step 2** —— ⭐ 重塑 `@snowluma/core`
- 删除:`account/account.ts` / `account-interface.ts` / `account-context.ts` / `account-manager.ts`
- 新建:`core.ts`(吸收 Account 业务,构造接 `ChannelCtx`)/ `core-ctx.ts` / `hub.ts`
- `apis/` 内部 `AccountContext` → `Core`(直接拿 Core 类型)
- `index.ts` 9 行装配(见 §6)
**Step 3** —— OneBot 适配 CoreCtx
- 全局 `AccountInterface` → `CoreCtx`
- `OneBotManager.bind(hub)` 订阅 `'core-online'` / `'core-offline'`
- 内部 `byUin.get(uin).apis.<area>.method()` 调 api
**Step 4** —— 引入 `AsyncLocalStorage`
- `packages/common/src/async-context.ts`
- `logger.ts` 自动读 ALS,加 `[uin]` 前缀
- `Core.constructor` 在 `onPacket` 回调外包 `runInContext`
**Step 5** —— `channel-socket` stub 包(占位)
- 把 `socket-channel.ts` / `socket-adapter.ts` 搬过来
- 实现 placeholder,让 `ChannelAdapter` 端口齐
**Step 6** —— ⭐ 拆 `webui` 为 `webui-backend` + `webui-frontend`
- Hono server + REST/WS → `webui-backend`,依赖 `@snowluma/core`(消费 `CoreCtx`)
- Vite SPA + UI → `webui-frontend`,依赖 `@snowluma/ui`
---
## 10. 设计原则速查
- **单向数据流**:`adapter → Channel → ChannelCtx → Core → CoreCtx → OneBot`,无反向引用
- **能力 POJO 跨层传递**:层间用 `{ uin, sendRawPacket, ... }` / `{ uin, apis, events, ... }` 这种纯数据,不传类实例
- **单一所有者**:`Hub.cores` 是 Core 唯一容器,消费者只持投影
- **每账号自带 EventBus**:避免全局 bus 混杂,订阅生命周期与 Core 绑定
- **Class 封装 deps**:构造时捕获,方法签名只剩业务参数
- **AsyncLocalStorage 跨切面**:日志 / trace 不进显式参数
- **不引入过度抽象**:no factory / no DI / no Effect monad / no global bus
- **可测**:每层接 POJO,fake 一下就能测
---
## 11. v2.0.0 已完成
- ✅ UID/UIN Service + SQLite 持久化
- ✅ tsx 免打包 Debug
- ✅ Common / OneBot / Core / Bridge / Protocol / proto-defs 拆包
- ✅ 消息 hot-path 优化(17.5μs → 4.7μs,better-sqlite3 + prepared-statement cache)
- ✅ NapCat 风格 Api 层(13 Api 类)
- ✅ Bridge / Account 严格分层(v2 中间形态;v3 重命名为 Channel + Core,并用 ctx 替代直接引用)
- ✅ `@snowluma/bridge` 完整 transport 包(v3 重命名为 `@snowluma/channel`)

19
compat/qq.json Normal file
View File

@@ -0,0 +1,19 @@
{
"$schema": "./qq.schema.json",
"version": 1,
"updatedAt": "2026-05-16T00:00:00Z",
"policy": {
"allowUnknown": true,
"warnUnknown": true
},
"knownGoodVersions": [],
"knownBadVersions": [],
"minVersion": null,
"notes": [
"QQ 兼容性 manifest — Desktop 启动时拉 https://raw.githubusercontent.com/SnowLuma/SnowLuma/main/compat/qq.json 校验本地 QQ 版本",
"policy.allowUnknown = true: 任何不在 knownBadVersions 里的版本都允许(理论上所有 QQ 新版本都可用)",
"knownBadVersions: 列在这里的版本 Desktop 会拒绝注入,弹出引导让用户切版本",
"minVersion: 设为 SemVer 字符串则更早的版本会被拒",
"知道某个版本会破坏 Hook 后把它加进 knownBadVersions,加 reason 字段说明"
]
}

56
compat/qq.schema.json Normal file
View File

@@ -0,0 +1,56 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "SnowLuma QQ compatibility manifest",
"type": "object",
"required": ["version", "policy", "knownGoodVersions", "knownBadVersions"],
"properties": {
"$schema": { "type": "string" },
"version": { "type": "integer", "const": 1 },
"updatedAt": { "type": "string", "format": "date-time" },
"policy": {
"type": "object",
"required": ["allowUnknown"],
"properties": {
"allowUnknown": {
"type": "boolean",
"description": "若 true,未在 known* 中列出的版本视为允许;若 false,需明确出现在 knownGoodVersions"
},
"warnUnknown": {
"type": "boolean",
"description": "未列出的版本启动时是否弹警告"
}
}
},
"knownGoodVersions": {
"type": "array",
"items": {
"type": "object",
"required": ["version"],
"properties": {
"version": { "type": "string", "description": "QQ 版本号字符串,如 '9.9.20.123'" },
"note": { "type": "string" }
}
}
},
"knownBadVersions": {
"type": "array",
"items": {
"type": "object",
"required": ["version"],
"properties": {
"version": { "type": "string" },
"reason": { "type": "string" },
"fixedInDesktopVersion": { "type": "string" }
}
}
},
"minVersion": {
"type": ["string", "null"],
"description": "最低支持版本(SemVer),null = 不限"
},
"notes": {
"type": "array",
"items": { "type": "string" }
}
}
}

105
eslint.config.ts Normal file
View File

@@ -0,0 +1,105 @@
import js from '@eslint/js';
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');
export default defineConfig([
globalIgnores([
'**/dist/**',
'**/node_modules/**',
'**/coverage/**',
'**/.turbo/**',
'**/.vite/**',
'**/*.tsbuildinfo',
'**/test/fixtures/**',
'packages/runtime/native/**',
]),
{
files: ['**/*.{js,mjs,cjs,ts,tsx}'],
extends: [js.configs.recommended],
languageOptions: {
ecmaVersion: 2023,
sourceType: 'module',
globals: {
...globals.es2023,
...globals.node,
},
},
rules: {
'indent': ['error', 2, { SwitchCase: 1 }],
'no-unused-vars': 'off',
'no-useless-assignment': 'off',
'prefer-const': 'off',
'preserve-caught-error': 'off',
},
},
{
files: ['**/*.{ts,tsx}'],
extends: [tseslint.configs.recommended],
languageOptions: {
parserOptions: {
tsconfigRootDir,
},
},
rules: {
'indent': ['error', 2, { SwitchCase: 1 }],
'prefer-const': 'off',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-empty-object-type': 'off',
'@typescript-eslint/no-this-alias': 'off',
'@typescript-eslint/no-unused-vars': [
'warn',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
},
],
},
},
{
files: ['**/tests/**/*.{ts,tsx}', '**/*.test.{ts,tsx}'],
rules: {
'@typescript-eslint/no-explicit-any': 'off',
},
},
{
files: ['**/bench/**/*.{ts,tsx}', 'packages/proton/test/**/*.{ts,tsx}'],
rules: {
'@typescript-eslint/no-explicit-any': 'off',
},
},
{
// OIDB service layer is namespace-per-cmd by design — the
// structural-typing contract (namespace IS the OidbCallSpec) and
// the file:cmd 1:1 mapping are the whole point. Disable the
// module-syntax preference here only.
files: [
'packages/protocol/src/oidb-services/**/*.ts',
'packages/protocol/tests/oidb-services/**/*.ts',
],
rules: {
'@typescript-eslint/no-namespace': 'off',
},
},
{
files: ['packages/webui/src/**/*.{ts,tsx}', 'packages/ui/src/**/*.{ts,tsx}'],
extends: [reactHooks.configs.flat.recommended, reactRefresh.configs.vite],
languageOptions: {
globals: globals.browser,
parserOptions: {
tsconfigRootDir,
},
},
rules: {
'indent': ['error', 2, { SwitchCase: 1 }],
'prefer-const': 'off',
'react-refresh/only-export-components': 'off',
'react-hooks/set-state-in-effect': 'off',
},
},
]);

View File

@@ -1,9 +0,0 @@
{
"name": "snowluma",
"version": "0.1.0",
"type": "module",
"main": "index.mjs",
"dependencies": {
"ws": "^8.20.0"
}
}

Binary file not shown.

Binary file not shown.

View File

@@ -1,42 +1,51 @@
{
"name": "snowluma",
"version": "0.1.0",
"description": "SnowLuma - NTQQ packet sniffer with Node.js native addon",
"name": "snowluma-monorepo",
"version": "1.9.2",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
"main": "dist/index.mjs",
"scripts": {
"testtypes": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"build": "vite build",
"build": "pnpm --filter @snowluma/core build",
"build:sdk": "pnpm --filter @snowluma/sdk build",
"build:webui": "pnpm --filter webui build",
"build:all": "cross-env BUILD_WEBUI=true vite build && pnpm --filter webui build",
"dev": "pnpm --parallel run dev",
"dev:core": "tsx src/index.ts",
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter webui build",
"dev": "pnpm --filter @snowluma/core dev",
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
"dev:web": "pnpm --filter webui dev",
"start": "node dist/index.mjs"
},
"dependencies": {
"ws": "^8.20.0"
"test": "pnpm --filter @snowluma/core test",
"test:watch": "pnpm --filter @snowluma/core test:watch",
"typecheck": "pnpm -r --if-present typecheck",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"start": "node dist/index.mjs",
"bump": "node tools/bump-version.mjs",
"release": "node tools/release.mjs"
},
"devDependencies": {
"@hono/node-server": "^1.19.14",
"@rollup/plugin-node-resolve": "^16.0.3",
"@types/node": "^24.12.2",
"@types/ws": "^8.18.1",
"@eslint/js": "^10.0.1",
"@vitest/coverage-istanbul": "4.1.4",
"@vitest/coverage-v8": "^4.1.4",
"cross-env": "^10.1.0",
"hono": "^4.12.14",
"tsx": "^4.21.0",
"typescript": "^6.0.2",
"vite": "catalog:",
"vite-plugin-cp": "^6.0.3",
"vitest": "^4.1.4"
"eslint": "^10.2.0",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.5.0",
"jiti": "^2.6.1",
"typescript": "catalog:",
"typescript-eslint": "^8.58.2"
},
"pnpm": {
"peerDependencyRules": {
"allowedVersions": {
"eslint-plugin-react-hooks>eslint": "10"
}
}
},
"onlyBuiltDependencies": [
"better-sqlite3"
]
},
"packageManager": "pnpm@10.28.0",
"engines": {
"node": ">=22"
}
}
}

View File

@@ -0,0 +1,69 @@
{
"name": "@snowluma/channel-hook",
"version": "1.9.2",
"private": true,
"type": "module",
"description": "SnowLuma `inject` channel implementation — in-process NTQQ hook runtime. Bundles HookManager / HookSession / pipe-watcher / injector / qq-hook-client plus the `HookChannel` and `HookAdapter` that `Hub` (in @snowluma/core) registers as the primary transport on Windows. Depends on `@snowluma/channel` for the abstract `Channel` + `ChannelAdapter` contracts.",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./hook-channel": {
"types": "./src/hook-channel.ts",
"default": "./src/hook-channel.ts"
},
"./hook-adapter": {
"types": "./src/hook-adapter.ts",
"default": "./src/hook-adapter.ts"
},
"./hook-manager": {
"types": "./src/hook-manager.ts",
"default": "./src/hook-manager.ts"
},
"./hook-session": {
"types": "./src/hook-session.ts",
"default": "./src/hook-session.ts"
},
"./hook-packet-client": {
"types": "./src/hook-packet-client.ts",
"default": "./src/hook-packet-client.ts"
},
"./injector": {
"types": "./src/injector.ts",
"default": "./src/injector.ts"
},
"./pipe-watcher": {
"types": "./src/pipe-watcher.ts",
"default": "./src/pipe-watcher.ts"
},
"./qq-hook-client": {
"types": "./src/qq-hook-client.ts",
"default": "./src/qq-hook-client.ts"
},
"./qq-port-probe": {
"types": "./src/qq-port-probe.ts",
"default": "./src/qq-port-probe.ts"
},
"./types": {
"types": "./src/types.ts",
"default": "./src/types.ts"
}
},
"scripts": {
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/channel": "workspace:*",
"@snowluma/common": "workspace:*"
},
"devDependencies": {
"@types/node": "^24.12.2",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "^4.1.4"
}
}

View File

@@ -0,0 +1,174 @@
import type { ChannelAdapter, ChannelAdapterHost } from '@snowluma/channel';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { HookChannel } from './hook-channel';
import { HookManager, type HookManagerDeps, type HookSink } from './hook-manager';
/** Subset of `HookManagerDeps` the operator is allowed to forward
* through the adapter. The `sink` is owned by the adapter itself and
* intentionally not exposed. */
export type HookAdapterOptions = Omit<HookManagerDeps, 'sink'>;
/**
* `HookAdapter` — the `ChannelAdapter` for the NTQQ hook runtime. It
* owns the `HookManager` and translates its three sink callbacks
* (`onHookLogin` / `onPacket` / `onPidDisconnected`) into lifecycle
* events on a per-UIN `HookChannel`.
*
* Why an adapter rather than letting the `Hub` keep the hook sink:
* this is the only place in the codebase that legitimately needs to
* know about PIDs. Quarantining that knowledge here keeps the `Hub`
* (and everything above it) free of `pid`, leaving the door open for
* a future `SocketAdapter` that doesn't have the concept at all.
*
* Internal bookkeeping:
*
* - `pidToUin` — quick "which UIN does this PID feed?" lookup,
* populated on login (and lazily during defensive
* packet routing for PIDs that arrived ahead of
* their login notification).
* - `pidToSender` — the live `PacketSender` per PID, so a re-login
* from the same PID rotates the outbound sender
* without dropping the channel.
* - `uinToPids` — reverse index for fast "did this UIN lose its
* last PID?" checks on disconnect.
* - `channelsByUin` — one `HookChannel` per UIN; the hub only sees
* `Channel` instances, never the PID set living
* inside them.
*/
export class HookAdapter implements ChannelAdapter, HookSink {
readonly kind = 'inject' as const;
private readonly hookManager_: HookManager;
private readonly pidToUin = new Map<number, string>();
private readonly pidToSender = new Map<number, PacketSender>();
private readonly uinToPids = new Map<string, Set<number>>();
private readonly channelsByUin = new Map<string, HookChannel>();
private host_: ChannelAdapterHost | null = null;
private disposed_ = false;
constructor(opts: HookAdapterOptions = {}) {
// `sink: this` wires HookManager → adapter sink. The HookManager
// doesn't know about the broader ChannelAdapter contract; it only
// sees the three sink methods we implement below.
this.hookManager_ = new HookManager({ ...opts, sink: this });
}
/** The underlying `HookManager`, exposed so WebUI can keep its
* `/api/processes/*` endpoints pointing at the hook process table.
* Higher-level code (OneBot, channel consumers) MUST NOT reach into
* this — that's the whole point of the adapter layer. */
get hookManager(): HookManager { return this.hookManager_; }
// ─── ChannelAdapter contract ─────────────────────────────────────
start(host: ChannelAdapterHost): void {
this.host_ = host;
host.log.debug('hook adapter started');
}
dispose(): void {
if (this.disposed_) return;
this.disposed_ = true;
// Tear down hook sessions first so no more sink callbacks fire.
this.hookManager_.dispose();
// Then proactively remove every channel we published; the hub
// will call `channel.dispose()` on its way out.
for (const id of [...this.channelsByUin.values()].map(c => c.id)) {
this.host_?.removeChannel(id);
}
this.pidToUin.clear();
this.pidToSender.clear();
this.uinToPids.clear();
this.channelsByUin.clear();
this.host_ = null;
}
// ─── HookSink contract (called by HookManager) ──────────────────
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
if (this.disposed_ || !isRealUin(uin)) return;
this.recordPidMapping(pid, uin, packetClient);
const channel = this.ensureChannel(uin);
channel.attachPid(pid, packetClient);
}
onPacket(pkt: PacketInfo): void {
if (this.disposed_ || !pkt.uin || !isRealUin(pkt.uin)) return;
const uin = pkt.uin;
const channel = this.ensureChannel(uin);
// Defensive: a packet may arrive before its login notification
// when the channel is being re-adopted (SnowLuma restarted while
// the hook stayed resident in QQ.exe). If we have a sender for
// this PID, weave it in so subsequent sends through this channel
// succeed.
if (pkt.pid) {
const sender = this.pidToSender.get(pkt.pid);
if (sender && !this.pidToUin.has(pkt.pid)) {
this.recordPidMapping(pkt.pid, uin, sender);
channel.attachPid(pkt.pid, sender);
}
}
channel.deliverPacket(pkt);
}
onPidDisconnected(pid: number): void {
if (this.disposed_) return;
this.pidToSender.delete(pid);
const uin = this.pidToUin.get(pid);
if (!uin) return;
this.pidToUin.delete(pid);
const pids = this.uinToPids.get(uin);
if (pids) {
pids.delete(pid);
if (pids.size === 0) this.uinToPids.delete(uin);
}
const channel = this.channelsByUin.get(uin);
if (!channel) return;
channel.detachPid(pid);
if (channel.isEmpty) {
this.channelsByUin.delete(uin);
this.host_?.removeChannel(channel.id);
}
}
// ─── internal ────────────────────────────────────────────────────
private recordPidMapping(pid: number, uin: string, sender: PacketSender): void {
this.pidToUin.set(pid, uin);
this.pidToSender.set(pid, sender);
let pids = this.uinToPids.get(uin);
if (!pids) {
pids = new Set();
this.uinToPids.set(uin, pids);
}
pids.add(pid);
}
private ensureChannel(uin: string): HookChannel {
let channel = this.channelsByUin.get(uin);
if (channel) return channel;
channel = new HookChannel(uin);
this.channelsByUin.set(uin, channel);
this.host_?.addChannel(channel);
return channel;
}
}
// QQ uins are 5-12 decimal digits; "0" is the hook's "no login yet"
// sentinel. Anything else (empty, alpha, too short) is a sign the hook
// callback fired before login info was probed — we ignore those.
function isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
}

View File

@@ -0,0 +1,82 @@
import { Channel } from '@snowluma/channel';
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
/**
* `HookChannel` — concrete transport backed by the in-process NTQQ
* hook. One UIN may be served simultaneously by several injected
* processes; the channel therefore tracks an unordered set of PIDs and
* keeps a single live `PacketSender` (the most recently logged-in
* pipe) for outbound traffic.
*
* PID bookkeeping is scoped to this transport because the socket-only
* runtime never has the concept; quarantining it here keeps the
* abstract `Channel` and the `Hub` free of pid awareness.
*
* The owning `HookAdapter` is responsible for calling
* `attachPid(pid, sender)` on every successful hook login,
* `detachPid(pid)` when the watcher reports a pipe drop, and tearing
* the channel down once `isEmpty` returns true.
*/
export class HookChannel extends Channel {
readonly kind = 'inject' as const;
readonly uin: string;
private readonly pids_ = new Set<number>();
private packetClient_: PacketSender | null = null;
constructor(uin: string) {
super();
this.uin = uin;
}
get id(): string { return `inject:${this.uin}`; }
/** PIDs currently routing packets into this channel. Read-only view
* for diagnostics — mutate only via `attachPid` / `detachPid`. */
get pids(): ReadonlySet<number> { return this.pids_; }
/** True iff no PID is currently bound; the adapter uses this to
* decide when to remove the channel from the `Hub`. */
get isEmpty(): boolean { return this.pids_.size === 0; }
/** Bind a freshly-logged-in PID (and its outbound `PacketSender`)
* to this channel. Idempotent — re-binding the same PID just rotates
* the active sender. */
attachPid(pid: number, sender: PacketSender): void {
this.pids_.add(pid);
this.packetClient_ = sender;
}
/** Forget a PID. If it owned the active sender we drop it; the next
* `attachPid` (or pipe-up) will install a fresh one. */
detachPid(pid: number): void {
this.pids_.delete(pid);
if (this.pids_.size === 0) {
this.packetClient_ = null;
}
}
override async sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs = 15000,
): Promise<SendPacketResult> {
const client = this.packetClient_;
if (!client) {
return {
success: false,
gotResponse: false,
errorCode: -1,
errorMessage: 'hook channel has no live packet sender',
responseData: null,
};
}
return client.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
}
override dispose(): void {
super.dispose();
this.packetClient_ = null;
this.pids_.clear();
}
}

View File

@@ -0,0 +1,316 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketInfo, PacketSink } from '@snowluma/common/protocol-types';
import fs from 'fs';
import { HookSession, type HookSessionDeps } from './hook-session';
import {
injectHookProcess,
listHookProcesses,
unloadHookProcess,
type HookProcessBaseInfo,
} from './injector';
import { PipeWatcher } from './pipe-watcher';
import { QqHookClient } from './qq-hook-client';
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
import type { HookProcessInfo } from './types';
/**
* Sink that the hook layer calls back into when it observes a new login,
* a parsed packet, or a PID disconnect. The concrete implementation is
* `HookAdapter`, which sits between this hook runtime and the `Hub` in
* `@snowluma/core`. Declaring it here keeps `@snowluma/channel` (and
* future `@snowluma/channel-hook`) free of any dependency on
* `@snowluma/core` — the hook package is self-contained.
*/
export interface HookSink {
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void;
onPacket(pkt: PacketInfo): void;
onPidDisconnected(pid: number): void;
}
export type HookManagerDeps = {
sink: HookSink;
/** Sink for parsed packets from any live HookSession. Defaults to
* `sink.onPacket` — every packet flows straight into the per-UIN
* channel dispatcher with no intermediate event emitter. */
onPacket?: PacketSink;
/** Native injector entrypoints. Defaults to the real native addon. */
injector?: HookSessionDeps['injector'];
/** Hook pipe-client factory. Defaults to `new QqHookClient(pid)`. */
makeClient?: HookSessionDeps['makeClient'];
/** Pre-built watcher. Defaults to a PipeWatcher wrapping the native listings. */
pipeWatcher?: PipeWatcher;
/** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */
watcherIntervalMs?: number;
/** Native process lister used by `listProcesses()`. Defaults to the native addon. */
listProcesses?: () => HookProcessBaseInfo[];
/** When true, every newly-discovered QQ process is auto-injected (fires
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
* Failed loads are logged and leave the session in the 'error' state. */
autoLoadOnDiscovery?: boolean;
log?: Logger;
};
/**
* HookManager — thin orchestrator over a per-PID HookSession map and a
* singleton PipeWatcher.
*
* Responsibilities:
* - Route user commands (load/unload/refresh) to the matching session.
* - Route watcher diff events to the matching session.
* - Forward session events ('login' / 'disconnected') to the `HookSink`.
* - Retry stuck-in-connecting sessions on every watcher tick (so a
* failed connect eventually recovers without a manual refresh).
*
* The native injector, native pipe-client, and native process/pipe
* listings are all swappable dependencies so tests can run without a
* real QQ.exe or a native addon.
*/
export class HookManager {
private readonly sink: HookSink;
private readonly onPacket: PacketSink;
private readonly injector: HookSessionDeps['injector'];
private readonly makeClient: HookSessionDeps['makeClient'];
private readonly pipeWatcher: PipeWatcher;
private readonly ownsPipeWatcher: boolean;
private readonly listProcessesNative: () => HookProcessBaseInfo[];
private readonly autoLoadOnDiscovery: boolean;
private readonly log: Logger;
private readonly sessions = new Map<number, HookSession>();
private readonly startPromise: Promise<void>;
private disposed = false;
constructor(deps: HookManagerDeps) {
this.sink = deps.sink;
this.onPacket = deps.onPacket ?? ((pkt) => deps.sink.onPacket(pkt));
this.log = deps.log ?? createLogger('Hook');
this.injector = deps.injector ?? {
inject: injectHookProcess,
unload: (pid, handle) => {
if (!handle) return;
unloadHookProcess(pid, handle);
},
};
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
this.listProcessesNative = deps.listProcesses ?? listHookProcesses;
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
if (deps.pipeWatcher) {
this.pipeWatcher = deps.pipeWatcher;
this.ownsPipeWatcher = false;
} else {
this.pipeWatcher = new PipeWatcher({
listProcesses: this.listProcessesNative,
listLivePipes: () => QqHookClient.listLivePipes(),
intervalMs: deps.watcherIntervalMs,
log: this.log,
});
this.ownsPipeWatcher = true;
}
this.bindWatcher();
this.startPromise = this.pipeWatcher.start();
}
// ─────────────── public API (unchanged from prior HookManager) ───────────────
async listProcesses(): Promise<HookProcessInfo[]> {
await this.startPromise;
let processes: HookProcessBaseInfo[];
try {
processes = this.listProcessesNative();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
processes = [];
}
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);
}
async loadProcess(pid: number): Promise<HookProcessInfo> {
this.assertValidPid(pid);
await this.startPromise;
const session = this.ensureSession(pid);
const info = await session.load();
// Pull the next tick forward so a freshly-injected pipe gets noticed
// within the next event-loop turn instead of after the full interval.
this.pipeWatcher.wake();
return info;
}
async unloadProcess(pid: number): Promise<HookProcessInfo> {
this.assertValidPid(pid);
await this.startPromise;
const session = this.ensureSession(pid);
return session.unload();
}
async refreshProcess(pid: number): Promise<HookProcessInfo> {
this.assertValidPid(pid);
await this.startPromise;
const session = this.ensureSession(pid);
return session.refresh();
}
async probeProcessLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
this.assertValidPid(pid);
return probeQqLoginInfo(pid);
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
for (const session of this.sessions.values()) {
session.dispose();
}
this.sessions.clear();
if (this.ownsPipeWatcher) {
this.pipeWatcher.dispose();
}
}
// ─────────────── wiring ───────────────
private bindWatcher(): void {
this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => {
if (this.disposed) return;
const session = this.ensureSession(info.pid);
session.attachProcessInfo(info);
// Headless/Docker deployments enable autoLoadOnDiscovery so QQ gets
// injected without a human clicking "Load" in WebUI. Fire-and-forget:
// failures are already captured inside loadInternal and surfaced via
// the session's status field.
if (this.autoLoadOnDiscovery && shouldAutoLoadPid(info.pid, this.log)) {
void session.load().catch((err) => {
this.log.warn('auto-load failed: PID=%d err=%s', info.pid, errMsg(err));
});
}
});
this.pipeWatcher.on('process-gone', (pid: number) => {
if (this.disposed) return;
const session = this.sessions.get(pid);
if (session) session.notifyProcessGone();
});
this.pipeWatcher.on('pipe-up', (pid: number) => {
if (this.disposed) return;
const session = this.sessions.get(pid);
if (session) session.onPipeUp();
});
this.pipeWatcher.on('pipe-down', (pid: number) => {
if (this.disposed) return;
const session = this.sessions.get(pid);
if (session) session.onPipeDown();
});
// After every tick, retry sessions that are stuck in 'connecting' OR
// 'disconnected' while the pipe is up. Mirrors the original
// tickWatcher's per-tick reconcileConnect pass; onPipeUp is idempotent
// so calling it for an already-connected session is harmless.
//
// The 'disconnected' branch matters on Windows: when the QQ-NT side of
// the named pipe stays alive but the SnowLuma-side socket dies (read
// EPIPE / idle-timeout / similar transient I/O fault), the watcher
// sees the pipe as still-live (the OS-level pipe is still listed by
// `listLivePipes`) so it never fires another `pipe-up`. Without
// retrying 'disconnected' sessions here the session is stranded
// forever — a real-world symptom users reported as "Windows running
// for a while then stops" with logs `pipe error: read EPIPE` →
// `session closed: UIN=…`.
this.pipeWatcher.on('tick', () => {
if (this.disposed) return;
for (const session of this.sessions.values()) {
if ((session.status === 'connecting' || session.status === 'disconnected')
&& this.pipeWatcher.isPipeLive(session.pid)) {
session.onPipeUp();
}
}
});
}
private ensureSession(pid: number): HookSession {
let session = this.sessions.get(pid);
if (session) return session;
session = new HookSession(pid, {
injector: this.injector,
makeClient: this.makeClient,
pipeWatcher: this.pipeWatcher,
onPacket: this.onPacket,
log: this.log,
});
session.attachProcessInfo({ name: defaultProcessName() });
session.on('login', (uin: string, sender) => {
this.sink.onHookLogin(pid, uin, sender);
});
session.on('disconnected', (wasLoggedIn: boolean) => {
if (wasLoggedIn) this.sink.onPidDisconnected(pid);
});
session.on('disposed', () => {
this.sessions.delete(pid);
});
this.sessions.set(pid, session);
return session;
}
private assertValidPid(pid: number): void {
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
}
}
function defaultProcessName(): string {
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
/**
* Filter for auto-load only. Returns false for Linux Electron child
* processes (zygote/renderer/gpu/utility), which the native enumerator
* mis-classifies as "main QQ" because their cmdline contains "qq" and
* they transiently inherit wrapper.node via fork copy-on-write.
*
* Injecting into a zygote spawns the hook's resolver thread inside it;
* every renderer Electron later forks then inherits that thread + the
* partially-init'd hook state, which breaks QQ's IPC and login UI.
*
* Manual loadProcess() bypasses this gate — the operator is responsible
* for picking the right PID from WebUI.
*/
export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
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;
let cmdline: string;
try {
cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
} catch {
// Can't read cmdline (process gone, permission, etc.) — let the
// existing load() path handle it; if the process is dead the load
// will fail with a clear error.
return true;
}
if (cmdline.includes('--type=')) {
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';

View File

@@ -1,8 +1,8 @@
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import { QqHookClient, type QqHookSendReply } from './qq-hook-client';
export class HookPacketClient implements PacketSender {
constructor(private readonly client: QqHookClient) {}
constructor(private readonly client: QqHookClient) { }
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise<SendPacketResult> {
if (!this.client.isLoggedIn) {

View File

@@ -0,0 +1,439 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { PacketSink } from '@snowluma/common/protocol-types';
import { EventEmitter } from 'events';
import { HookPacketClient } from './hook-packet-client';
import type { HookInjectResult } from './injector';
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
import type { HookProcessInfo, HookProcessStatus } from './types';
export type HookSessionDeps = {
injector: {
inject: (pid: number) => HookInjectResult;
unload: (pid: number, handle: HookInjectResult['handle']) => void;
};
makeClient: (pid: number) => QqHookClient;
/** Sync fast-path check used by load() to skip re-injection when a
* prior SnowLuma run left a working pipe behind. `tickNow` forces a
* fresh poll — used after unload to dodge the up-to-1500ms cache
* staleness that would otherwise false-flag a successful unload. */
pipeWatcher: {
isPipeLive: (pid: number) => boolean;
tickNow?: () => Promise<void>;
};
/** Sink for parsed packets. Called with the canonical PacketInfo
* shape for every packet received while logged in. If omitted,
* packets are dropped (useful in unit tests that don't care). */
onPacket?: PacketSink;
log?: Logger;
};
/**
* HookSession — owns the lifecycle of one QQ.exe process: injection,
* pipe client, login state, and the public status field.
*
* Concurrency: every state-mutating method goes through a per-session
* promise chain so user clicks (load/unload/refresh) and watcher-driven
* events (onPipeUp/onPipeDown) never interleave.
*
* Communication: emits high-level events instead of calling the sink
* directly, so HookManager forwards them and tests can attach spies.
*
* Emitted events:
* 'login' (uin, packetSender) — real-UIN login detected
* 'disconnected' (wasLoggedIn) — connection dropped or torn down
* 'status-changed' (status, error) — status field mutated
* 'disposed' () — session stopped tracking this PID
*/
export class HookSession extends EventEmitter {
readonly pid: number;
private readonly injector: HookSessionDeps['injector'];
private readonly makeClient: HookSessionDeps['makeClient'];
private readonly pipeWatcher: HookSessionDeps['pipeWatcher'];
private readonly onPacket: PacketSink | null;
private readonly log: Logger;
private _status: HookProcessStatus = 'available';
private _error = '';
private _uin = '0';
private _method = '';
private _name = '';
private _path = '';
private injected = false;
private connected = false;
private loggedIn = false;
private injectResult: HookInjectResult | null = null;
private client: QqHookClient | null = null;
private sender: HookPacketClient | null = null;
private bound = false;
private opChain: Promise<unknown> = Promise.resolve();
private disposed = false;
constructor(pid: number, deps: HookSessionDeps) {
super();
this.pid = pid;
this.injector = deps.injector;
this.makeClient = deps.makeClient;
this.pipeWatcher = deps.pipeWatcher;
this.onPacket = deps.onPacket ?? null;
this.log = deps.log ?? createLogger('HookSession');
}
// ─────────────── 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; }
attachProcessInfo(info: { name?: string; path?: string }): void {
if (info.name) this._name = info.name;
if (info.path) this._path = info.path;
}
toInfo(): HookProcessInfo {
return {
pid: this.pid,
name: this._name,
path: this._path,
injected: this.injected,
connected: this.connected,
loggedIn: this.loggedIn,
uin: this._uin,
status: this._status,
error: this._error,
method: this._method,
};
}
// ─────────────── user-facing commands ───────────────
load(): Promise<HookProcessInfo> {
return this.serialize(() => this.loadInternal());
}
unload(): Promise<HookProcessInfo> {
return this.serialize(() => this.unloadInternal());
}
refresh(): Promise<HookProcessInfo> {
return this.serialize(() => this.refreshInternal());
}
// ─────────────── watcher-driven events (called by manager) ───────────────
/** Pipe came up (or stayed up across a SnowLuma restart). Drives connect
* 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;
void this.serialize(async () => {
if (this.disposed) return;
// Adopt a DLL that survived a SnowLuma restart.
if (!this.injected) {
this.injected = true;
if (!this._method) this._method = 'reconnect';
}
if (this.client?.isClosed) this.tearDownClient();
if (!this.connected) {
await this.attemptConnect();
} else {
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
}
}).catch(err => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
}
onPipeDown(): void {
if (this.disposed) return;
void this.serialize(async () => {
if (this.disposed) return;
if (!this.connected) {
// Nothing to tear down; just keep status visible.
if (this.injected) this.setStatus('connecting', this._error);
return;
}
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.setStatus(
this.injected ? (wasLoggedIn ? 'disconnected' : 'connecting') : 'available',
'',
);
if (wasLoggedIn) this.emit('disconnected', true);
}).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;
void this.serialize(async () => {
if (this.disposed) return;
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.injected = false;
this.injectResult = null;
this._method = '';
this.setStatus('available', '');
if (wasLoggedIn) this.emit('disconnected', true);
this.disposed = true;
this.emit('disposed');
this.removeAllListeners();
}).catch(err => this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)));
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
this.tearDownClient();
this.removeAllListeners();
}
// ─────────────── per-session serialization ───────────────
private serialize<T>(op: () => Promise<T>): Promise<T> {
const previous = this.opChain;
let release!: () => void;
const completion = new Promise<void>(resolve => { release = resolve; });
this.opChain = previous.then(() => completion);
return (async () => {
try {
await previous.catch(() => undefined);
return await op();
} finally {
release();
}
})();
}
// ─────────────── internal transitions ───────────────
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
// resident in QQ.exe. If the watcher already sees a live pipe,
// skip re-injection and let onPipeUp drive the reconnect.
if (this.pipeWatcher.isPipeLive(this.pid)) {
this.injected = true;
this._method = this._method || 'reconnect';
this.log.info('PID=%d already has SnowLuma pipe; will reconnect', this.pid);
} else {
this.injectResult = this.injector.inject(this.pid);
this.injected = true;
this._method = this.injectResult.method;
}
}
this.setStatus(
this.connected ? (this.loggedIn ? 'online' : 'loaded') : 'connecting',
'',
);
} catch (error) {
this._error = errMsg(error);
this.setStatus('error', this._error);
this.log.error('load failed: PID=%d err=%s', this.pid, this._error);
}
return this.toInfo();
}
private async unloadInternal(): Promise<HookProcessInfo> {
this._error = '';
try {
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
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);
}
this.injected = false;
this.injectResult = null;
this._method = '';
this._uin = '0';
// Verify the unload took: if the pipe is still up the DLL is still
// resident. The cached snapshot is up to 1500ms stale and we just
// changed the world, so force a fresh poll first — otherwise even
// 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);
this.log.warn('unload verification failed: PID=%d pipe still up', this.pid);
} else {
this.setStatus('available', '');
}
} catch (error) {
this._error = errMsg(error);
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 {
const pipeUp = this.pipeWatcher.isPipeLive(this.pid);
if (pipeUp) {
// Adopt an unknown DLL the same way onPipeUp would.
if (!this.injected) {
this.injected = true;
this._method = this._method || 'reconnect';
}
if (this.client?.isClosed) this.tearDownClient();
if (!this.connected) {
await this.attemptConnect();
} else {
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
}
} else {
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.setStatus(this.injected ? 'disconnected' : 'available', '');
if (wasLoggedIn) this.emit('disconnected', true);
}
} catch (error) {
this._error = errMsg(error);
this.setStatus(this.injected ? 'disconnected' : 'error', this._error);
this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error);
}
return this.toInfo();
}
// ─────────────── client plumbing ───────────────
private async attemptConnect(): Promise<void> {
if (this.connected) return;
if (this.client?.isClosed) this.tearDownClient();
if (!this.client) {
this.client = this.makeClient(this.pid);
this.sender = new HookPacketClient(this.client);
this.bound = false;
}
if (!this.bound) {
this.bindClient(this.client);
this.bound = true;
}
const client = this.client;
try {
await client.connectAll({ recv: true });
this.connected = true;
this.setStatus(client.isLoggedIn ? 'online' : 'loaded', '');
const loginState = client.getLoginState();
if (loginState.loggedIn) this.handleLoginState(loginState);
this.log.info('pipe connected: PID=%d', this.pid);
} catch (error) {
this._error = errMsg(error);
// Drop the client so the next attempt builds a fresh socket pair.
this.tearDownClient();
this.setStatus(this.injected ? 'connecting' : 'available', this._error);
}
}
private bindClient(client: QqHookClient): void {
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;
// Only the currently-registered client should drive a reconcile;
// listeners may fire for an already-replaced client.
if (this.client !== client) return;
void this.serialize(async () => {
if (this.disposed) return;
if (this.client !== client) return;
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
if (!this.injected) {
this.setStatus('available', '');
} else if (wasLoggedIn) {
this.setStatus('disconnected', '');
} else {
this.setStatus('connecting', '');
}
if (wasLoggedIn) this.emit('disconnected', true);
}).catch(err => this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)));
});
}
private tearDownClient(): void {
const client = this.client;
if (client) {
client.removeAllListeners();
try { client.close(); } catch { /* ignore */ }
}
this.client = null;
this.sender = null;
this.bound = false;
this.connected = false;
this.loggedIn = false;
}
private handleLoginState(state: QqHookLoginState): void {
const wasLoggedIn = this.loggedIn;
const previousUin = this._uin;
this._uin = state.uin || state.uinNumber.toString();
this.loggedIn = state.loggedIn && isRealUin(this._uin);
if (this.loggedIn) {
this.setStatus('online', '');
} else if (this.connected) {
this.setStatus('loaded', this._error);
}
if (!this.loggedIn || !this.sender) return;
if (wasLoggedIn && previousUin === this._uin) return;
this.emit('login', this._uin, this.sender);
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
}
private handlePacket(packet: QqHookPacket): void {
if (!this.loggedIn) return;
const uin = packet.uin || this._uin;
if (!isRealUin(uin)) return;
if (!this.onPacket) return;
// Re-shape the hook-client wire packet into the canonical PacketInfo
// shape. Used to live in the deleted NtqqHandler.onHookPacket; field
// renaming was that module's entire purpose, so it lives at the source
// now (no need for a single-listener event-emitter in between).
this.onPacket({
pid: this.pid,
uin,
serviceCmd: packet.cmd,
seqId: packet.seq,
retCode: packet.error,
fromClient: false,
body: Buffer.from(packet.body),
});
}
private setStatus(status: HookProcessStatus, error: string): void {
if (this._status === status && this._error === error) return;
this._status = status;
this._error = error;
this.emit('status-changed', status, error);
}
}
function isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}

View File

@@ -0,0 +1,15 @@
// `@snowluma/channel-hook` — the `inject` channel implementation
// (NTQQ in-process hook). Registered with `Hub` from `@snowluma/core`
// as a `ChannelAdapter` of kind `'inject'`. Everything pid-related is
// scoped to this package — neither `@snowluma/channel` nor anything
// downstream knows about it.
// ─── Hook runtime ──────────────────────────────────────────────────
export {
HookManager, type HookSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
type HookProcessStatus, type QqPortLoginInfo
} from './hook-manager';
// ─── Concrete Channel + Adapter ────────────────────────────────────
export { HookChannel } from './hook-channel';
export { HookAdapter, type HookAdapterOptions } from './hook-adapter';

View File

@@ -7,6 +7,7 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
export interface ManualMapHandle {
base: bigint;
entry: bigint;
exceptionTable: bigint;
size: number;
}
@@ -36,21 +37,37 @@ function loadNativeAddon(addonPath: string): NativeHookAddon {
return mod.exports as unknown as NativeHookAddon;
}
function platformBinaryName(ext: 'node' | 'dll'): string {
type HookBinaryExt = 'node' | 'dll' | 'so';
function platformBinaryName(ext: HookBinaryExt): string {
if (process.platform === 'win32' && process.arch === 'x64') return `snowluma-win32-x64.${ext}`;
return `snowluma-${process.platform}-${process.arch}.${ext}`;
}
function platformInjectableExt(): 'dll' | 'so' {
return process.platform === 'win32' ? 'dll' : 'so';
}
function defaultProcessName(): string {
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
}
function nativeSearchDirs(): string[] {
// Several layouts must be supported:
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
// 2. Dev via tsx (packages/channel/src/injector.ts): __dirname=<root>/packages/channel/src
// → walk up to <root>/packages and append runtime/native
// Same offset works for `packages/channel/dist/index.mjs` after build.
// 3. cwd-based fallback when neither __dirname-relative path resolves.
return [
path.resolve(__dirname, '..', '..', 'native'),
path.resolve(__dirname, '..', 'native'),
path.resolve(__dirname, 'native'),
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
path.resolve(process.cwd(), 'dist', 'native'),
path.resolve(process.cwd(), 'native'),
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
];
}
export function resolveHookNativePath(ext: 'node' | 'dll'): string | null {
export function resolveHookNativePath(ext: HookBinaryExt): string | null {
const fileName = platformBinaryName(ext);
for (const dir of nativeSearchDirs()) {
const fullPath = path.join(dir, fileName);
@@ -86,7 +103,7 @@ export function listHookProcesses(): HookProcessBaseInfo[] {
return [...new Set(addon.getAllMainProcess())]
.filter(pid => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b)
.map(pid => ({ pid, name: 'QQ.exe', path: '' }));
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
}
export function injectHookProcess(pid: number): HookInjectResult {
@@ -94,9 +111,10 @@ export function injectHookProcess(pid: number): HookInjectResult {
if (!addon) {
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
}
const dllPath = resolveHookNativePath('dll');
const injectableExt = platformInjectableExt();
const dllPath = resolveHookNativePath(injectableExt);
if (!dllPath) {
throw new Error(`No hook DLL found for ${process.platform}-${process.arch}`);
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
}
return { method: 'loadModuleManual', handle: addon.loadModuleManual(pid, dllPath) };
}

View File

@@ -0,0 +1,208 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import { EventEmitter } from 'events';
import type { HookProcessBaseInfo } from './injector';
const DEFAULT_INTERVAL_MS = 1500;
const MIN_INTERVAL_MS = 250;
export type PipeWatcherDeps = {
/** Native: list QQ.exe processes currently running. */
listProcesses: () => HookProcessBaseInfo[];
/** Native: PIDs that currently have a live SnowLuma named pipe. */
listLivePipes: () => Promise<Set<number>>;
/** Polling interval in ms. Defaults to 1500, floored to 250. */
intervalMs?: number;
log?: Logger;
};
/**
* PipeWatcher — the only module that polls the OS for QQ.exe processes
* and live SnowLuma named pipes. Subscribers consume diffs as events.
*
* Lifecycle: start() runs one tick synchronously, then schedules a poll
* every `intervalMs`. tickNow() drains a single tick on demand. wake()
* pulls the next scheduled tick forward to the next event-loop turn.
*
* Emitted events:
* 'process-discovered' (info: HookProcessBaseInfo) — a QQ.exe appeared
* 'process-gone' (pid: number) — a QQ.exe disappeared
* 'pipe-up' (pid: number) — named pipe came up
* 'pipe-down' (pid: number) — named pipe dropped
* 'tick' () — fired after every poll
*
* Within a single tick the order is: process-discovered, pipe-up,
* pipe-down, process-gone, tick. That ordering lets HookManager create
* a session before it gets a pipe event and run disconnect logic before
* dispose logic when QQ.exe is killed with a live pipe.
*/
export class PipeWatcher extends EventEmitter {
private readonly listProcesses: PipeWatcherDeps['listProcesses'];
private readonly listLivePipes: PipeWatcherDeps['listLivePipes'];
private readonly intervalMs: number;
private readonly log: Logger;
private livePipes = new Set<number>();
private knownPids = new Set<number>();
private timer: NodeJS.Timeout | null = null;
private ticking = false;
private pendingWake = false;
private startPromise: Promise<void> | null = null;
private stopped = false;
constructor(deps: PipeWatcherDeps) {
super();
this.listProcesses = deps.listProcesses;
this.listLivePipes = deps.listLivePipes;
this.intervalMs = Math.max(MIN_INTERVAL_MS, deps.intervalMs ?? DEFAULT_INTERVAL_MS);
this.log = deps.log ?? createLogger('PipeWatcher');
}
/** Was this PID's pipe live as of the last completed tick? */
isPipeLive(pid: number): boolean {
return this.livePipes.has(pid);
}
/** Was this PID alive as of the last completed tick? */
isProcessAlive(pid: number): boolean {
return this.knownPids.has(pid);
}
/**
* Run an initial tick (so isPipeLive/isProcessAlive return real data)
* and begin the polling loop. Idempotent.
*/
start(): Promise<void> {
if (this.startPromise) return this.startPromise;
this.startPromise = (async () => {
try {
await this.tickOnce();
} finally {
this.scheduleNext(this.intervalMs);
}
})();
return this.startPromise;
}
/** Pull the next scheduled tick forward to the next event-loop turn. */
wake(): void {
if (this.stopped) return;
this.scheduleNext(0);
}
/** Force a single tick now. Resolves after diff events have been emitted. */
tickNow(): Promise<void> {
return this.tickOnce();
}
stop(): void {
this.stopped = true;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
dispose(): void {
this.stop();
this.removeAllListeners();
}
private scheduleNext(delayMs: number): void {
if (this.stopped) return;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(() => {
this.timer = null;
void this.tickAndReschedule();
}, Math.max(0, delayMs));
}
private async tickAndReschedule(): Promise<void> {
try {
await this.tickOnce();
} finally {
this.scheduleNext(this.intervalMs);
}
}
/**
* Read processes + live pipes, emit diff events. If another tick is
* already running, mark a follow-up tick so we don't lose a wake().
*/
private async tickOnce(): Promise<void> {
if (this.ticking) {
this.pendingWake = true;
return;
}
this.ticking = true;
try {
let processes: HookProcessBaseInfo[];
try {
processes = this.listProcesses();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
processes = [];
}
let livePipes: Set<number>;
try {
livePipes = await this.listLivePipes();
} catch (error) {
this.log.warn('listLivePipes failed: %s', errMsg(error));
livePipes = new Set();
}
const newKnownPids = new Set<number>();
for (const proc of processes) newKnownPids.add(proc.pid);
// 1. Newly discovered processes.
for (const proc of processes) {
if (!this.knownPids.has(proc.pid)) {
this.emit('process-discovered', proc);
}
}
// 2. Pipes that came up. Ignore pipes for processes we don't know
// about (would race against an out-of-order tick).
const newLivePipes = new Set<number>();
for (const pid of livePipes) {
if (!newKnownPids.has(pid)) continue;
newLivePipes.add(pid);
if (!this.livePipes.has(pid)) {
this.emit('pipe-up', pid);
}
}
// 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so
// subscribers can run disconnect logic before dispose logic.
for (const pid of this.livePipes) {
if (!newLivePipes.has(pid)) {
this.emit('pipe-down', pid);
}
}
// 4. Processes that disappeared.
for (const pid of this.knownPids) {
if (!newKnownPids.has(pid)) {
this.emit('process-gone', pid);
}
}
this.knownPids = newKnownPids;
this.livePipes = newLivePipes;
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(); });
}
}
}
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}

View File

@@ -1,11 +1,15 @@
import net from 'net';
import { EventEmitter } from 'events';
import { promises as fs } from 'fs';
import net from 'net';
import os from 'os';
import path from 'path';
export const PIPE_MAGIC = 0x31504851;
export const PIPE_VERSION = 1;
export const HEADER_SIZE = 40;
export const DEFAULT_ACK_TIMEOUT_MS = 5000;
export const DEFAULT_REPLY_TIMEOUT_MS = 30000;
const DEFAULT_PIPE_PROBE_TIMEOUT_MS = 250;
export enum PipeOp {
hello = 1,
@@ -81,8 +85,79 @@ interface PendingAck {
wantReply: boolean;
}
function linuxRuntimeDir(): string {
const explicit = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
if (explicit && explicit.length > 0) return explicit;
const xdg = process.env.XDG_RUNTIME_DIR;
if (xdg && xdg.length > 0) return xdg;
// Mirrors hook_stub.cpp runtime_dir() fallback.
// process.geteuid is POSIX-only; cast to allow non-Linux type checks.
const uid = typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid;
return `/tmp/snowluma-${uid}`;
}
function mojoPipeName(pid: number, suffix: string): string {
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
if (process.platform === 'win32') {
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
}
return path.join(linuxRuntimeDir(), `mojo.${pid}.${suffix}.sock`);
}
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;
} catch {
return false;
}
return new Promise<boolean>((resolve) => {
let socket: net.Socket;
try {
socket = net.createConnection(socketPath);
} catch {
resolve(false);
return;
}
let done = false;
let timer: NodeJS.Timeout;
const finish = (ok: boolean) => {
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', () => finish(false));
});
}
export async function listLiveLinuxPipePids(
runtimeDir = linuxRuntimeDir(),
probe: LinuxPipeProbe = isConnectableUnixSocket,
): Promise<Set<number>> {
const result = new Set<number>();
let names: string[];
try {
names = await fs.readdir(runtimeDir);
} catch {
return result;
}
await Promise.all(names.map(async (name) => {
const m = /^mojo\.(\d+)\.control\.sock$/.exec(name);
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);
}));
return result;
}
function toBuffer(body: Buffer | Uint8Array | string | null | undefined): Buffer {
@@ -160,7 +235,7 @@ function encodeFrame({
class FrameReader {
private buffer = Buffer.alloc(0);
constructor(private readonly onFrame: (frame: PipeFrame) => void) {}
constructor(private readonly onFrame: (frame: PipeFrame) => void) { }
push(chunk: Buffer): void {
this.buffer = Buffer.concat([this.buffer, chunk]);
@@ -236,6 +311,10 @@ export class QqHookClient extends EventEmitter {
return this.loginState.loggedIn;
}
get isClosed(): boolean {
return this.closed;
}
get currentUin(): string {
return this.loginState.uin;
}
@@ -266,6 +345,39 @@ export class QqHookClient extends EventEmitter {
return mojoPipeName(pid, 'recv');
}
/**
* Lightweight liveness check for the control pipe. Used to detect whether an
* existing SnowLuma hook is still hosted inside the QQ.exe process without
* opening the pipe, so probing cannot disturb the first real client connect.
*/
static async probePipe(pid: number): Promise<boolean> {
const live = await QqHookClient.listLivePipes();
return live.has(pid);
}
/**
* Enumerate every PID currently hosting a SnowLuma `mojo.<pid>.control` pipe
* in a single filesystem listing. The HookManager's pipe-watcher uses this
* to drive connect/reconnect decisions without per-PID stat calls.
*/
static async listLivePipes(): Promise<Set<number>> {
const result = new Set<number>();
try {
if (process.platform === 'win32') {
const names = await fs.readdir('\\\\.\\pipe\\');
for (const name of names) {
const m = /^mojo\.(\d+)\.control$/i.exec(name);
if (m) result.add(Number(m[1]));
}
} else {
return await listLiveLinuxPipePids();
}
} catch {
/* directory missing or inaccessible — treat as no live pipes */
}
return result;
}
async connect(): Promise<QqHookHello> {
if (this.closed) {
throw new Error('qq_hook client is closed');
@@ -332,7 +444,18 @@ export class QqHookClient extends EventEmitter {
}: QqHookSendOptions = {}): Promise<QqHookSendReply | { requestId: number }> {
await this.connect();
const requestId = this.nextRequestId++ >>> 0;
// Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would
// misbehave once the integer exceeds Number.MAX_SAFE_INTEGER (the
// postfix increment loses precision before the shift), letting two
// distinct requests collide on the same id. Skip 0 because zero is
// used as a sentinel by the wire protocol.
let requestId = this.nextRequestId;
while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) {
requestId = (requestId + 1) >>> 0;
if (requestId === 0) requestId = 1;
}
this.nextRequestId = (requestId + 1) >>> 0;
if (this.nextRequestId === 0) this.nextRequestId = 1;
const payload = encodeFrame({
op: PipeOp.sendRequest,
requestId,
@@ -390,7 +513,7 @@ export class QqHookClient extends EventEmitter {
const workerCount = Math.max(1, Math.min(concurrency | 0, items.length || 1));
const worker = async () => {
for (;;) {
for (; ;) {
const index = nextIndex;
nextIndex += 1;
if (index >= items.length) return;
@@ -501,7 +624,7 @@ export class QqHookClient extends EventEmitter {
else resolve();
});
}));
this.controlWriteChain = writePromise.catch(() => {});
this.controlWriteChain = writePromise.catch(() => { });
return writePromise;
}
@@ -576,8 +699,8 @@ export class QqHookClient extends EventEmitter {
const previous = this.loginState;
const next = { loggedIn, uin, uinNumber };
this.loginState = next;
this.emit('loginState', next);
if (previous.loggedIn !== next.loggedIn || previous.uin !== next.uin) {
this.emit('loginState', next);
if (next.loggedIn) {
const waiters = this.loginWaiters;
this.loginWaiters = [];

View File

@@ -0,0 +1,168 @@
import { exec } from 'child_process';
import net from 'net';
import { promisify } from 'util';
const execAsync = promisify(exec);
const PORT_RANGE_START = 9210;
const PORT_RANGE_END = 9219;
const PROBE_TIMEOUT_MS = 1000;
const CONNECTION_TIMEOUT_MS = 500;
export interface QqPortLoginInfo {
port: number;
uin: string;
uid?: string;
nickName?: string;
loggedIn: boolean;
}
interface JwtPayload {
errCode: number;
errMsg: string;
port: number;
uin?: string;
uid?: string;
nickName?: string;
data?: {
uin?: string;
url?: string;
};
iat: number;
}
function decodeJwt(token: string): JwtPayload | null {
try {
const parts = token.split('.');
if (parts.length !== 3) return null;
const payload = Buffer.from(parts[1], 'base64').toString('utf8');
return JSON.parse(payload);
} catch {
return null;
}
}
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
return new Promise((resolve) => {
const client = new net.Socket();
const link = 'tencent://';
const payload = `POST /tencent HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\nContent-Length: ${link.length}\r\n\r\n${link}`;
let responseData = '';
let timer: NodeJS.Timeout;
const cleanup = () => {
clearTimeout(timer);
client.removeAllListeners();
client.destroy();
};
timer = setTimeout(() => {
cleanup();
resolve(null);
}, PROBE_TIMEOUT_MS);
client.setTimeout(CONNECTION_TIMEOUT_MS);
client.connect(port, '127.0.0.1', () => {
client.write(payload);
});
client.on('data', (data) => {
responseData += data.toString();
});
client.on('close', () => {
cleanup();
const jwtMatch = responseData.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/);
if (!jwtMatch) {
resolve(null);
return;
}
const decoded = decodeJwt(jwtMatch[0]);
if (!decoded || decoded.errCode !== 0) {
resolve(null);
return;
}
const uin = decoded.uin || decoded.data?.uin || '';
resolve({
port,
uin,
uid: decoded.uid,
nickName: decoded.nickName,
loggedIn: uin.length > 0,
});
});
client.on('error', () => {
cleanup();
resolve(null);
});
client.on('timeout', () => {
cleanup();
resolve(null);
});
});
}
async function getProcessPorts(pid: number): Promise<number[]> {
try {
if (process.platform === 'win32') {
const { stdout } = await execAsync(`netstat -ano | findstr ${pid}`);
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;
const owningPid = parts[parts.length - 1];
if (owningPid !== String(pid)) continue;
const localAddr = parts[1];
const portMatch = localAddr.match(/:(\d+)$/);
if (!portMatch) continue;
const port = Number(portMatch[1]);
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
ports.add(port);
}
}
return Array.from(ports);
} else {
const { stdout } = await execAsync(`ss -tlnp | grep pid=${pid}`);
const ports = new Set<number>();
const lines = stdout.split('\n');
for (const line of lines) {
const match = line.match(/:(\d+)\s/);
if (match) {
const port = Number(match[1]);
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
ports.add(port);
}
}
}
return Array.from(ports);
}
} catch {
return [];
}
}
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
const ports = await getProcessPorts(pid);
if (ports.length === 0) {
for (let port = PORT_RANGE_START; port <= PORT_RANGE_END; port++) {
const info = await probePort(port);
if (info) return info;
}
return null;
}
for (const port of ports) {
const info = await probePort(port);
if (info) return info;
}
return null;
}

View File

@@ -0,0 +1,21 @@
import type { HookProcessBaseInfo } from './injector';
export type HookProcessStatus =
| 'available'
| 'loading'
| 'connecting'
| 'loaded'
| 'online'
| 'error'
| 'disconnected';
/** Public-facing snapshot of a per-PID HookSession. */
export interface HookProcessInfo extends HookProcessBaseInfo {
injected: boolean;
connected: boolean;
loggedIn: boolean;
uin: string;
status: HookProcessStatus;
error: string;
method: string;
}

View File

@@ -0,0 +1,182 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'events';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { HookManager, shouldAutoLoadPid } from '../src/hook-manager';
import { PipeWatcher } from '../src/pipe-watcher';
import type { ManualMapHandle } from '../src/injector';
import type { HookSink } from '../src/hook-manager';
import type { QqHookClient } from '../src/qq-hook-client';
import { createLogger } from '@snowluma/common/logger';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
const flush = () => new Promise<void>(r => setImmediate(r));
function makeManager(opts: {
autoLoadOnDiscovery?: boolean;
processes?: number[];
}) {
let pids = opts.processes ?? [];
const live = new Set<number>();
const inject = vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE }));
const unload = vi.fn();
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live),
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
});
// FakeClient — never connected; just needs to satisfy EventEmitter +
// a minimal subset of QqHookClient for HookSession.tearDownClient().
const makeClient = vi.fn(() => {
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
(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; };
return c as unknown as QqHookClient;
});
const sink = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as HookSink;
const manager = new HookManager({
sink,
pipeWatcher,
injector: { inject, unload },
makeClient,
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
});
return {
manager,
inject,
pipeWatcher,
setProcesses: (next: number[]) => { pids = next; },
};
}
describe('HookManager.autoLoadOnDiscovery', () => {
it('does NOT inject on process-discovered when flag is off', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
await ctx.pipeWatcher.start();
await flush();
expect(ctx.inject).not.toHaveBeenCalled();
ctx.manager.dispose();
});
it('injects every newly-discovered PID when flag is on', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
await ctx.pipeWatcher.start();
// session.load() is queued via a per-session promise chain; flush twice
// so the auto-load runs to completion before we assert.
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(1);
expect(ctx.inject).toHaveBeenCalledWith(4242);
// A second PID appearing mid-flight should also trigger an inject.
ctx.setProcesses([4242, 9999]);
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(2);
expect(ctx.inject).toHaveBeenLastCalledWith(9999);
ctx.manager.dispose();
});
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'); });
await ctx.pipeWatcher.start();
await flush();
await flush();
// Second PID should still be auto-loaded — the failure on 4242 must
// not leak out of the listener and break the watcher's emit loop.
ctx.setProcesses([4242, 9999]);
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(2);
ctx.manager.dispose();
});
});
// `shouldAutoLoadPid` reads /proc/<pid>/cmdline directly, so we point
// it at a temporary directory that mimics the procfs layout. This lets
// the tests run on macOS / CI without a live Linux QQ process.
describe('shouldAutoLoadPid', () => {
let tmpProc: string;
const originalReadFileSync = fs.readFileSync;
const log = createLogger('test');
const originalPlatform = process.platform;
const originalAutoLoadAll = process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
beforeEach(() => {
tmpProc = fs.mkdtempSync(path.join(os.tmpdir(), 'hookmgr-proc-'));
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[]) => {
const match = /^\/proc\/(\d+)\/cmdline$/.exec(p);
if (match) {
return originalReadFileSync(path.join(tmpProc, match[1], 'cmdline'), ...(rest as [BufferEncoding]));
}
return originalReadFileSync(p, ...(rest as [BufferEncoding]));
}) as typeof fs.readFileSync;
});
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;
fs.rmSync(tmpProc, { recursive: true, force: true });
});
function writeCmdline(pid: number, args: string[]): void {
const dir = path.join(tmpProc, String(pid));
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'cmdline'), args.join('\0') + '\0');
}
it('allows the QQ main process (no --type=)', () => {
writeCmdline(50, ['qq', '--no-sandbox']);
expect(shouldAutoLoadPid(50, log)).toBe(true);
});
it('rejects Electron zygotes', () => {
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote', '--no-zygote-sandbox', '--no-sandbox']);
expect(shouldAutoLoadPid(59, log)).toBe(false);
});
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']);
expect(shouldAutoLoadPid(70, log)).toBe(false);
expect(shouldAutoLoadPid(71, log)).toBe(false);
expect(shouldAutoLoadPid(72, log)).toBe(false);
});
it('allows everything if SNOWLUMA_HOOK_AUTOLOAD_ALL=1 (escape hatch)', () => {
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote']);
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = '1';
expect(shouldAutoLoadPid(59, log)).toBe(true);
});
it('allows on non-linux platforms (filter is a Linux-only workaround)', () => {
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
// No cmdline file needed — we return true before touching procfs.
expect(shouldAutoLoadPid(59, log)).toBe(true);
});
it('allows when /proc is unreadable (dead PID, permission issue)', () => {
expect(shouldAutoLoadPid(99999, log)).toBe(true);
});
});

View File

@@ -0,0 +1,99 @@
// E2E for Docker "QQ never logs in + pipe keeps reconnecting" scenario.
//
// Drives the real PipeWatcher + HookManager through repeated same-PID
// pipe up/down cycles via tickNow() and asserts the BridgeManager mock
// is never touched (no login → no Bridge / OneBotInstance / Identity).
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookManager } from '../src/hook-manager';
import { PipeWatcher } from '../src/pipe-watcher';
import type { ManualMapHandle } from '../src/injector';
import type { HookSink } 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));
class FakeClient extends EventEmitter {
isClosed = false;
isLoggedIn = false;
async connectAll(_opts: { recv: boolean }) {
if (this.isClosed) throw new Error('client is closed');
}
getLoginState() { return { loggedIn: false, uin: '0', uinNumber: 0n }; }
close() {
if (this.isClosed) return;
this.isClosed = true;
this.emit('close');
}
}
describe('HookManager — Docker reconnect-without-login leak guard', () => {
it('after N pipe up/down cycles: no Bridge calls, no client accumulation', async () => {
const PID = 61;
const liveSet = new Set<number>([PID]);
const clients: FakeClient[] = [];
const pipeWatcher = new PipeWatcher({
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
listLivePipes: async () => new Set(liveSet),
intervalMs: 60_000, // manual ticks only
});
const sink = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as HookSink;
const manager = new HookManager({
sink,
pipeWatcher,
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: () => {
const c = new FakeClient();
clients.push(c);
return c as unknown as QqHookClient;
},
autoLoadOnDiscovery: true,
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
});
// Initial discovery + first connect.
await pipeWatcher.start();
await flush();
await flush();
// 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();
await flush();
liveSet.add(PID);
await pipeWatcher.tickNow();
await flush();
}
// The "QQ never logs in" hypothesis: BridgeManager should never have
// been told about a login or a disconnect.
expect(sink.onHookLogin).not.toHaveBeenCalled();
expect(sink.onPidDisconnected).not.toHaveBeenCalled();
expect(sink.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);
// Total clients minted = roughly one per up cycle. Sanity bound:
// we must have actually exercised the reconnect path.
expect(clients.length).toBeGreaterThan(1);
manager.dispose();
});
});

View File

@@ -0,0 +1,123 @@
// Regression test for the Docker "QQ-never-logs-in + pipe keeps reconnecting" leak hypothesis.
//
// User-reported pattern (Docker, idle login screen):
// 02:41:23 [Hook] pipe connected: PID=61
// 04:37:55 [Hook] pipe connected: PID=61 (same PID, ~2h later)
// 04:40:44 [Hook] pipe connected: PID=61
// 04:43:48 [Hook] pipe connected: PID=61 → eventual OOM-kill
//
// Hypothesis (H2): every onPipeDown → onPipeUp cycle leaks the prior
// QqHookClient (listeners or socket-ref keeping it pinned in memory),
// so repeated reconnect drives unbounded growth.
//
// This test drives N up/down cycles against a HookSession with a FakeClient
// factory and asserts:
// - at most one client is alive at any point
// - every prior client's EventEmitter listener count drops to 0 after teardown
import { 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 } from '../src/qq-hook-client';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
class FakeClient extends EventEmitter {
isClosed = false;
isLoggedIn = false;
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
async connectAll(_opts: { recv: boolean }): Promise<void> {
if (this.isClosed) throw new Error('client is closed');
}
getLoginState() { return { ...this.loginState }; }
close(): void {
if (this.isClosed) return;
this.isClosed = true;
this.emit('close');
}
}
function totalListenerCount(emitter: EventEmitter): number {
return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0);
}
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 () => {
let pipeLive = true;
const clients: FakeClient[] = [];
const session = new HookSession(61, {
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: () => {
const c = new FakeClient();
clients.push(c);
return c as unknown as QqHookClient;
},
pipeWatcher: { isPipeLive: () => pipeLive },
});
await session.load();
session.onPipeUp();
await flush();
const CYCLES = 50;
for (let i = 0; i < CYCLES; i++) {
pipeLive = false;
session.onPipeDown();
await flush();
pipeLive = true;
session.onPipeUp();
await flush();
}
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);
});
it('drops all listeners from each torn-down client', async () => {
let pipeLive = true;
const clients: FakeClient[] = [];
const session = new HookSession(61, {
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: () => {
const c = new FakeClient();
clients.push(c);
return c as unknown as QqHookClient;
},
pipeWatcher: { isPipeLive: () => pipeLive },
});
await session.load();
session.onPipeUp();
await flush();
const CYCLES = 20;
for (let i = 0; i < CYCLES; i++) {
pipeLive = false;
session.onPipeDown();
await flush();
pipeLive = true;
session.onPipeUp();
await flush();
}
// Every client except the current one should have 0 listeners attached.
// (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);
}
});
});

View File

@@ -0,0 +1,446 @@
import { 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 type { PacketSink } from '@snowluma/common/protocol-types';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
/** Minimal stand-in for QqHookClient. Tests drive login/packet/error/close
* events directly via fire* helpers. connectAll succeeds unless told otherwise. */
class FakeClient extends EventEmitter {
isClosed = false;
isLoggedIn = false;
shouldFailConnect = false;
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');
}
getLoginState() { return { ...this.loginState }; }
close(): void {
if (this.isClosed) return;
this.isClosed = true;
this.emit('close');
}
fireLogin(uin: string): void {
this.isLoggedIn = true;
this.loginState = { loggedIn: true, uin, uinNumber: BigInt(uin) };
this.emit('loginState', { ...this.loginState });
}
firePacket(packet: QqHookPacket): void {
this.emit('packet', packet);
}
}
function makeSession(opts: {
pid?: number;
pipeLive?: boolean;
clientFailsConnect?: boolean;
onPacket?: PacketSink;
} = {}) {
const pid = opts.pid ?? 1234;
let pipeLive = opts.pipeLive ?? false;
const clients: FakeClient[] = [];
const injector = {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
};
const session = new HookSession(pid, {
injector,
makeClient: () => {
const c = new FakeClient();
if (opts.clientFailsConnect) c.shouldFailConnect = true;
clients.push(c);
// Cast: FakeClient mirrors only the surface HookSession touches.
return c as unknown as QqHookClient;
},
pipeWatcher: { isPipeLive: () => pipeLive },
onPacket: opts.onPacket,
});
return {
session,
injector,
clients,
currentClient: () => clients[clients.length - 1]!,
setPipeLive: (v: boolean) => { pipeLive = v; },
};
}
const flush = () => new Promise<void>(r => setImmediate(r));
describe('HookSession — load', () => {
it('with no live pipe: injects, status → connecting, method from inject result', async () => {
const { session, injector } = makeSession({ pipeLive: false });
const info = await session.load();
expect(injector.inject).toHaveBeenCalledOnce();
expect(info.status).toBe('connecting');
expect(info.method).toBe('loadModuleManual');
expect(info.injected).toBe(true);
});
it('fast-path: pipe already live → skip inject, method → "reconnect"', async () => {
const { session, injector } = makeSession({ pipeLive: true });
const info = await session.load();
expect(injector.inject).not.toHaveBeenCalled();
expect(info.method).toBe('reconnect');
expect(info.injected).toBe(true);
expect(info.status).toBe('connecting');
});
it('inject failure → status error, error message captured', async () => {
const injector = {
inject: vi.fn(() => { throw new Error('inject boom'); }),
unload: vi.fn(),
};
const session = new HookSession(1234, {
injector,
makeClient: () => new FakeClient() as unknown as QqHookClient,
pipeWatcher: { isPipeLive: () => false },
});
const info = await session.load();
expect(info.status).toBe('error');
expect(info.error).toBe('inject boom');
});
});
describe('HookSession — pipe up/down → connect lifecycle', () => {
it('onPipeUp after load: client connects → status loaded', async () => {
const ctx = makeSession({ pipeLive: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
expect(ctx.session.status).toBe('loaded');
expect(ctx.clients).toHaveLength(1);
});
it('emits "login" with (uin, sender) after client signals loggedIn', async () => {
const ctx = makeSession({ pipeLive: true });
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
expect(loginSpy).toHaveBeenCalledOnce();
const [uin, sender] = loginSpy.mock.calls[0]!;
expect(uin).toBe('10001');
expect(typeof (sender as { sendPacket: unknown }).sendPacket).toBe('function');
expect(ctx.session.status).toBe('online');
expect(ctx.session.uin).toBe('10001');
});
it('does not re-emit "login" on duplicate loginState with same uin', async () => {
const ctx = makeSession({ pipeLive: true });
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
ctx.currentClient().fireLogin('10001');
expect(loginSpy).toHaveBeenCalledOnce();
});
it('connect failure: stays in connecting, error message captured (will retry on next tick)', async () => {
const ctx = makeSession({ pipeLive: true, clientFailsConnect: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
expect(ctx.session.status).toBe('connecting');
expect(ctx.session.error).toBe('connect failed');
});
it('onPipeDown while logged in: emits disconnected(true), status disconnected', 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.onPipeDown();
await flush();
expect(discSpy).toHaveBeenCalledWith(true);
expect(ctx.session.status).toBe('disconnected');
});
it('onPipeDown while connected-but-not-logged-in: emits disconnected(false), status connecting', async () => {
const ctx = makeSession({ pipeLive: true });
const discSpy = vi.fn();
ctx.session.on('disconnected', discSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
// No login fired — we're connected but not logged in.
ctx.session.onPipeDown();
await flush();
// disconnected(false) is currently NOT emitted — disconnect events are
// reserved for "we owe BridgeManager a disconnect notification". This
// preserves the original behaviour.
expect(discSpy).not.toHaveBeenCalled();
expect(ctx.session.status).toBe('connecting');
});
it('repeated pipe down → up cycles reach consistent state', async () => {
const ctx = makeSession({ pipeLive: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
expect(ctx.session.status).toBe('online');
ctx.session.onPipeDown();
await flush();
expect(ctx.session.status).toBe('disconnected');
// Pipe returns — session builds a fresh client.
ctx.session.onPipeUp();
await flush();
expect(ctx.clients.length).toBeGreaterThan(1);
expect(ctx.session.status).toBe('loaded');
});
});
describe('HookSession — unload', () => {
it('while logged in: emits disconnected(true), calls unload, status available', async () => {
const ctx = makeSession({ pipeLive: false });
await ctx.session.load();
ctx.setPipeLive(true);
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
const discSpy = vi.fn();
ctx.session.on('disconnected', discSpy);
ctx.setPipeLive(false); // unload verification will see the pipe gone
await ctx.session.unload();
expect(discSpy).toHaveBeenCalledWith(true);
expect(ctx.injector.unload).toHaveBeenCalledOnce();
expect(ctx.session.status).toBe('available');
});
it('when pipe stays live after unload: status connecting with retry message', async () => {
const ctx = makeSession({ pipeLive: false });
await ctx.session.load();
// Simulate the unload-failed scenario: pipe is still up after unload.
ctx.setPipeLive(true);
const info = await ctx.session.unload();
expect(info.status).toBe('connecting');
expect(info.error).toContain('命名管道仍然存在');
});
it('forces a fresh tick before verifying so a stale snapshot does not false-flag a successful unload', async () => {
// Reproduces the Windows-WebUI bug: PipeWatcher's cached snapshot is
// up to 1500ms stale, so right after a successful native unload the
// pre-fix code would read isPipeLive() == true and report failure
// even though the DLL is gone. With the fix, tickNow() refreshes
// 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 session = new HookSession(pid, {
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: () => new FakeClient() as unknown as QqHookClient,
pipeWatcher: { isPipeLive: () => pipeLive, tickNow },
});
await session.load();
pipeLive = true; // ensure the pre-check snapshot says "live"
const info = await session.unload();
expect(tickNow).toHaveBeenCalledOnce();
expect(info.status).toBe('available');
expect(info.error).toBe('');
});
});
describe('HookSession — serialization', () => {
it('user mashing load → unload → load runs in order, end state consistent', async () => {
const ctx = makeSession({ pipeLive: false });
const p1 = ctx.session.load();
const p2 = ctx.session.unload();
const p3 = ctx.session.load();
await Promise.all([p1, p2, p3]);
expect(ctx.injector.inject).toHaveBeenCalledTimes(2);
expect(ctx.injector.unload).toHaveBeenCalledTimes(1);
expect(ctx.session.status).toBe('connecting');
});
it('onPipeUp queued behind in-flight load resolves correctly', async () => {
const ctx = makeSession({ pipeLive: true });
const loadPromise = ctx.session.load();
ctx.session.onPipeUp(); // queued behind load
await loadPromise;
await flush();
expect(ctx.session.status).toBe('loaded');
});
});
describe('HookSession — process gone', () => {
it('emits disconnected(true) then disposed when killed while logged in', async () => {
const ctx = makeSession({ pipeLive: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
const events: string[] = [];
ctx.session.on('disconnected', () => events.push('disconnected'));
ctx.session.on('disposed', () => events.push('disposed'));
ctx.session.notifyProcessGone();
await flush();
expect(events).toEqual(['disconnected', 'disposed']);
expect(ctx.session.isDisposed).toBe(true);
});
it('emits only disposed when killed before login', async () => {
const ctx = makeSession({ pipeLive: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
const events: string[] = [];
ctx.session.on('disconnected', () => events.push('disconnected'));
ctx.session.on('disposed', () => events.push('disposed'));
ctx.session.notifyProcessGone();
await flush();
expect(events).toEqual(['disposed']);
});
});
describe('HookSession — packet forwarding', () => {
// These tests cover the field-rename + filter logic that used to live
// inside the deleted NtqqHandler.onHookPacket. Inlining it here means
// we can exercise the transformation with a plain vi.fn() sink, no
// event-emitter machinery required.
it('forwards parsed packets to onPacket sink with PacketInfo shape', async () => {
const onPacket = vi.fn();
const ctx = makeSession({ pipeLive: true, onPacket });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
ctx.currentClient().firePacket({
seq: 42,
error: 0,
cmd: 'trpc.msg.olpush.OlPushService.MsgPush',
uin: '10001',
body: Buffer.from([0x01, 0x02, 0x03]),
});
expect(onPacket).toHaveBeenCalledOnce();
const pkt = onPacket.mock.calls[0]![0];
expect(pkt).toMatchObject({
pid: 1234,
uin: '10001',
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
seqId: 42,
retCode: 0,
fromClient: false,
});
expect(Buffer.isBuffer(pkt.body)).toBe(true);
expect([...pkt.body]).toEqual([1, 2, 3]);
});
it('falls back to session uin when packet.uin is empty', async () => {
const onPacket = vi.fn();
const ctx = makeSession({ pipeLive: true, onPacket });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
ctx.currentClient().firePacket({
seq: 1, error: 0, cmd: 'foo', uin: '', body: Buffer.alloc(0),
});
expect(onPacket.mock.calls[0]![0].uin).toBe('10001');
});
it('drops packets received before login', async () => {
const onPacket = vi.fn();
const ctx = makeSession({ pipeLive: true, onPacket });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
// No login fired yet.
ctx.currentClient().firePacket({
seq: 1, error: 0, cmd: 'foo', uin: '10001', body: Buffer.alloc(0),
});
expect(onPacket).not.toHaveBeenCalled();
});
it('drops packets whose uin is non-real ("0" / too short / non-numeric)', async () => {
const onPacket = vi.fn();
const ctx = makeSession({ pipeLive: true, onPacket });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
// Packet uin '0' falls back to session uin '10001' — that one passes.
// 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),
});
expect(onPacket).not.toHaveBeenCalled();
});
it('is a no-op when no onPacket sink is provided', async () => {
const ctx = makeSession({ pipeLive: true }); // no onPacket
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
// Should not throw / crash.
ctx.currentClient().firePacket({
seq: 1, error: 0, cmd: 'foo', uin: '10001', body: Buffer.from([7]),
});
});
});

View File

@@ -0,0 +1,195 @@
import { describe, it, expect } from 'vitest';
import { PipeWatcher } from '../src/pipe-watcher';
import type { HookProcessBaseInfo } from '../src/injector';
function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set<number> }) {
let processes = initial.processes;
let live = initial.live;
const watcher = new PipeWatcher({
listProcesses: () => processes,
// Defensively copy so the watcher can't mutate the test's reference.
listLivePipes: async () => new Set(live),
intervalMs: 60_000, // disable the internal timer; tests drive ticks manually
});
return {
watcher,
setProcesses: (p: HookProcessBaseInfo[]) => { processes = p; },
setLive: (s: Set<number>) => { live = s; },
};
}
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]));
return events;
}
describe('PipeWatcher', () => {
it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
const events = captureEvents(ctx.watcher);
await ctx.watcher.start();
expect(events).toEqual([
['discovered', 1234],
['up', 1234],
]);
expect(ctx.watcher.isPipeLive(1234)).toBe(true);
expect(ctx.watcher.isProcessAlive(1234)).toBe(true);
ctx.watcher.stop();
});
it('pipe-down emitted when a previously-live pipe disappears', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
ctx.setLive(new Set());
await ctx.watcher.tickNow();
expect(events).toEqual([['down', 1234]]);
expect(ctx.watcher.isPipeLive(1234)).toBe(false);
ctx.watcher.stop();
});
it('process-gone + pipe-down both emitted (pipe-down first) when QQ.exe is killed with a live pipe', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
ctx.setProcesses([]);
ctx.setLive(new Set());
await ctx.watcher.tickNow();
expect(events).toEqual([
['down', 1234],
['gone', 1234],
]);
ctx.watcher.stop();
});
it('ignores live pipes whose process is not running', async () => {
const ctx = setupWatcher({
processes: [],
live: new Set([9999]),
});
const events = captureEvents(ctx.watcher);
await ctx.watcher.start();
expect(events).toEqual([]);
expect(ctx.watcher.isPipeLive(9999)).toBe(false);
ctx.watcher.stop();
});
it('emits pipe-up again after a pipe-down → pipe-up cycle', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set(),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
ctx.setLive(new Set([1234]));
await ctx.watcher.tickNow();
expect(events).toEqual([['up', 1234]]);
ctx.setLive(new Set());
await ctx.watcher.tickNow();
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]]);
ctx.watcher.stop();
});
it('does not double-emit on idempotent ticks (no state change)', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
await ctx.watcher.tickNow();
await ctx.watcher.tickNow();
expect(events).toEqual([]);
ctx.watcher.stop();
});
it('emits "tick" after every poll', async () => {
const ctx = setupWatcher({ processes: [], live: new Set() });
let ticks = 0;
ctx.watcher.on('tick', () => { ticks++; });
await ctx.watcher.start();
expect(ticks).toBe(1);
await ctx.watcher.tickNow();
expect(ticks).toBe(2);
ctx.watcher.stop();
});
it('wake() pulls the next tick forward', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set(),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
// 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()));
ctx.setLive(new Set([1234]));
ctx.watcher.wake();
await nextTick;
expect(events).toEqual([['up', 1234]]);
ctx.watcher.stop();
});
it('survives a throwing listProcesses without crashing the watcher', async () => {
let processes: HookProcessBaseInfo[] = [];
let live = new Set<number>();
let shouldThrow = true;
const watcher = new PipeWatcher({
listProcesses: () => {
if (shouldThrow) throw new Error('boom');
return processes;
},
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
});
await watcher.start();
expect(watcher.isProcessAlive(1234)).toBe(false);
shouldThrow = false;
processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
live = new Set([1234]);
const events = captureEvents(watcher);
await watcher.tickNow();
expect(events).toEqual([['discovered', 1234], ['up', 1234]]);
watcher.stop();
});
});

View File

@@ -0,0 +1,44 @@
import { mkdtemp, rm, writeFile } from 'fs/promises';
import os from 'os';
import path from 'path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { listLiveLinuxPipePids } from '../src/qq-hook-client';
let tmpDir: string | null = null;
async function makeRuntimeDir(): Promise<string> {
tmpDir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-hook-'));
return tmpDir;
}
afterEach(async () => {
if (!tmpDir) return;
await rm(tmpDir, { recursive: true, force: true });
tmpDir = null;
});
describe('listLiveLinuxPipePids', () => {
it('ignores stale-looking control socket names when the probe rejects them', async () => {
const runtimeDir = await makeRuntimeDir();
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
await writeFile(path.join(runtimeDir, 'mojo.55.recv.sock'), '');
const pids = await listLiveLinuxPipePids(runtimeDir, async () => false);
expect([...pids]).toEqual([]);
});
it('returns only connectable control sockets', async () => {
const runtimeDir = await makeRuntimeDir();
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
await writeFile(path.join(runtimeDir, 'mojo.56.control.sock'), '');
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 pids = await listLiveLinuxPipePids(runtimeDir, probe);
expect([...pids]).toEqual([56]);
expect(probe).toHaveBeenCalledTimes(2);
});
});

View File

@@ -0,0 +1,16 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": [
"node"
],
"noEmit": true
},
"include": [
"src/**/*",
"tests"
],
"exclude": [
"node_modules"
]
}

View File

@@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['tests/**/*.test.ts'],
environment: 'node',
},
});

View File

@@ -0,0 +1,34 @@
{
"name": "@snowluma/channel-socket",
"version": "1.9.2",
"private": true,
"type": "module",
"description": "SnowLuma `socket` channel implementation — placeholder for the future pure-socket runtime (no QQ.exe, no hook). Today registers as a no-op `ChannelAdapter` so the Hub-adapter architecture is exercised end-to-end. Will gain a `SocketClient` long-lived TCP login session when the protocol runtime lands.",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./socket-channel": {
"types": "./src/socket-channel.ts",
"default": "./src/socket-channel.ts"
},
"./socket-adapter": {
"types": "./src/socket-adapter.ts",
"default": "./src/socket-adapter.ts"
}
},
"scripts": {
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/channel": "workspace:*",
"@snowluma/common": "workspace:*"
},
"devDependencies": {
"@types/node": "^24.12.2",
"typescript": "catalog:"
}
}

View File

@@ -0,0 +1,8 @@
// `@snowluma/channel-socket` — future pure-socket transport (no
// QQ.exe, no hook). Today an empty stub so `Hub` can register it as a
// `ChannelAdapter` of kind `'socket'` and exercise the adapter pool
// end-to-end. Will materialise a real `SocketChannel` once the
// pure-socket login client lands.
export { SocketChannel } from './socket-channel';
export { SocketAdapter } from './socket-adapter';

View File

@@ -0,0 +1,30 @@
import type { ChannelAdapter, ChannelAdapterHost } from '@snowluma/channel';
/**
* `SocketAdapter` — placeholder for the future pure-socket runtime.
* Once a `SocketClient` (long-lived TCP login session, heartbeat,
* reconnect loop, …) lands, this adapter will:
*
* 1. Read its account list from runtime config.
* 2. Spin up one `SocketClient` per configured account.
* 3. On successful login, materialise a `SocketChannel` and call
* `host.addChannel(channel)`.
* 4. On logout / fatal error, call `host.removeChannel(channel.id)`.
*
* Until that lands the adapter is registered as a no-op so the wider
* architecture (Hub → ChannelAdapter[] → Channel → Core) is already in
* place and exercised in production. Registering it is harmless:
* `start()` does nothing, `dispose()` does nothing, no channels are
* ever produced.
*/
export class SocketAdapter implements ChannelAdapter {
readonly kind = 'socket' as const;
start(host: ChannelAdapterHost): void {
host.log.debug('socket adapter is a stub; no socket clients will be opened');
}
dispose(): void {
// Nothing to tear down yet.
}
}

View File

@@ -0,0 +1,41 @@
import { Channel } from '@snowluma/channel';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
/**
* `SocketChannel` — placeholder transport for the future pure-socket
* runtime (no QQ.exe, no hook). It already participates in the `Hub`
* (in `@snowluma/core`) so the wider architecture (ChannelAdapter pool
* → Hub → Core → OneBot) is exercised end-to-end today; once a real
* `SocketClient` lands the transport will gain a constructor argument
* and `sendRawPacket` will route through it.
*
* Until then `sendRawPacket` returns a structured "not implemented"
* failure rather than throwing, so the surrounding code treats it as
* a regular transport-down result.
*/
export class SocketChannel extends Channel {
readonly kind = 'socket' as const;
readonly uin: string;
constructor(uin: string) {
super();
this.uin = uin;
}
get id(): string { return `socket:${this.uin}`; }
override async sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult> {
void serviceCmd; void body; void timeoutMs;
return {
success: false,
gotResponse: false,
errorCode: -1,
errorMessage: 'socket channel transport is not yet implemented',
responseData: null,
};
}
}

View File

@@ -0,0 +1,15 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": [
"node"
],
"noEmit": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
]
}

View File

@@ -0,0 +1,44 @@
{
"name": "@snowluma/channel",
"version": "1.9.2",
"private": true,
"type": "module",
"description": "SnowLuma transport abstract layer. Defines the `Channel` abstract base + `ChannelCtx` capability POJO + `ChannelAdapter` port that `Hub` (in @snowluma/core) consumes. Concrete transports live in `@snowluma/channel-hook` (in-process NTQQ hook) and `@snowluma/channel-socket` (future pure-socket).",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./channel": {
"types": "./src/channel.ts",
"default": "./src/channel.ts"
},
"./channel-interface": {
"types": "./src/channel-interface.ts",
"default": "./src/channel-interface.ts"
},
"./channel-ctx": {
"types": "./src/channel-ctx.ts",
"default": "./src/channel-ctx.ts"
},
"./adapter": {
"types": "./src/adapter.ts",
"default": "./src/adapter.ts"
}
},
"scripts": {
"test": "vitest run --passWithNoTests",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/common": "workspace:*"
},
"devDependencies": {
"@types/node": "^24.12.2",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "^4.1.4"
}
}

View File

@@ -0,0 +1,15 @@
import type { Logger } from '@snowluma/common/logger';
import type { Channel } from './channel';
import type { ChannelKind } from './channel-interface';
export interface ChannelAdapterHost {
addChannel(channel: Channel): void;
removeChannel(channelId: string): void;
readonly log: Logger;
}
export interface ChannelAdapter {
readonly kind: ChannelKind;
start(host: ChannelAdapterHost): Promise<void> | void;
dispose(): Promise<void> | void;
}

View File

@@ -0,0 +1,26 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { Channel } from './channel';
import type { ChannelKind } from './channel-interface';
export interface ChannelCtx {
readonly uin: string;
readonly kind: ChannelKind;
readonly sendRawPacket: (
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
) => Promise<SendPacketResult>;
readonly onPacket: (handler: ((pkt: PacketInfo) => void) | null) => void;
readonly dispose: () => void;
}
export function makeChannelCtx(channel: Channel): ChannelCtx {
return {
uin: channel.uin,
kind: channel.kind,
sendRawPacket: (cmd, body, timeoutMs) => channel.sendRawPacket(cmd, body, timeoutMs),
onPacket: (handler) => channel.setPacketHandler(handler),
dispose: () => channel.dispose(),
};
}

View File

@@ -0,0 +1,73 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
/**
* Discriminator for the two channel transport implementations:
*
* - `'inject'` — backed by an in-process NTQQ hook (one or more
* QQ.exe processes injected with the SnowLuma DLL,
* talking over named pipes). Implemented by
* `HookChannel` in `@snowluma/channel-hook`.
* - `'socket'` — backed by a direct protocol client (no QQ.exe, no
* hook). Reserved for the future pure-protocol
* runtime; `SocketChannel` is a stub until then.
*
* Mirrored on `CoreCtx.kind` so account-level consumers can branch on
* transport without `instanceof` checks against a concrete subclass
* (diagnostics, kind-specific WebUI panels, …).
*/
export type ChannelKind = 'inject' | 'socket';
/**
* `ChannelInterface` — **strictly transport**. A channel owns one
* wire-level connection to QQ for a given UIN: it sends opaque packets
* out and surfaces received packets to whoever subscribed via
* `setPacketHandler`.
*
* It deliberately knows nothing about identity caches, the event bus,
* the api hub, or the cmd-dispatch pipeline — that machinery lives on
* the `Core` layer (`@snowluma/core`) which wraps a `Channel` (via a
* `ChannelCtx` capability POJO) to expose a business-level API to
* OneBot and friends.
*
* Direct consumers are limited to:
* - `ChannelAdapter` implementations (they create / dispose channels
* and pump received packets through `deliverPacket`),
* - `Hub` in `@snowluma/core` (the only place that turns a `Channel`
* into a `ChannelCtx` and hands the ctx to `Core`),
* - `Core` (only via the `ChannelCtx` projection; never holds a
* Channel reference directly).
*
* OneBot and api modules NEVER import `ChannelInterface`; they consume
* `CoreCtx` from `@snowluma/core`.
*/
export interface ChannelInterface {
/** Transport family backing this channel. */
readonly kind: ChannelKind;
/** Stable, unique-per-live-channel id inside the `Hub`
* (e.g. `'inject:3161592748'`). */
readonly id: string;
/** QQ number this transport carries. */
readonly uin: string;
/** Wire-level send. The only escape hatch the apis layer eventually
* routes through (via `Core.sendRawPacket` → `ChannelCtx.sendRawPacket`). */
sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult>;
/** Subscribe to inbound packets. Called once by `Hub` (via
* `ChannelCtx.onPacket`) when a `Core` is constructed on top of this
* channel. Passing `null` detaches. */
setPacketHandler(handler: ((pkt: PacketInfo) => void) | null): void;
/** Adapter-side hook: feed a freshly-received packet into the
* current subscriber (if any). Called by `ChannelAdapter`s when
* their underlying runtime delivers a frame. */
deliverPacket(pkt: PacketInfo): void;
/** Release transport-side resources. Idempotent. */
dispose(): void;
}

View File

@@ -0,0 +1,34 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { ChannelInterface, ChannelKind } from './channel-interface';
export abstract class Channel implements ChannelInterface {
abstract readonly kind: ChannelKind;
abstract readonly id: string;
abstract readonly uin: string;
abstract sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult>;
private packetHandler_: ((pkt: PacketInfo) => void) | null = null;
private disposed_ = false;
setPacketHandler(handler: ((pkt: PacketInfo) => void) | null): void {
this.packetHandler_ = handler;
}
deliverPacket(pkt: PacketInfo): void {
this.packetHandler_?.(pkt);
}
get isDisposed(): boolean { return this.disposed_; }
dispose(): void {
if (this.disposed_) return;
this.disposed_ = true;
this.packetHandler_ = null;
}
}

View File

View File

@@ -0,0 +1,5 @@
export { type ChannelAdapter, type ChannelAdapterHost } from './adapter';
export { Channel } from './channel';
export { makeChannelCtx, type ChannelCtx } from './channel-ctx';
export { type ChannelInterface, type ChannelKind } from './channel-interface';

View File

@@ -0,0 +1,16 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": [
"node"
],
"noEmit": true
},
"include": [
"src/**/*",
"tests"
],
"exclude": [
"node_modules"
]
}

View File

@@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['tests/**/*.test.ts'],
environment: 'node',
},
});

View File

@@ -0,0 +1,54 @@
{
"name": "@snowluma/common",
"version": "1.9.2",
"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).",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./logger": {
"types": "./src/logger.ts",
"default": "./src/logger.ts"
},
"./hex": {
"types": "./src/hex.ts",
"default": "./src/hex.ts"
},
"./json": {
"types": "./src/json.ts",
"default": "./src/json.ts"
},
"./log-file-transport": {
"types": "./src/log-file-transport.ts",
"default": "./src/log-file-transport.ts"
},
"./log-summary": {
"types": "./src/log-summary.ts",
"default": "./src/log-summary.ts"
},
"./packet-sender": {
"types": "./src/packet-sender.ts",
"default": "./src/packet-sender.ts"
},
"./protocol-types": {
"types": "./src/protocol-types.ts",
"default": "./src/protocol-types.ts"
},
"./runtime": {
"types": "./src/runtime.ts",
"default": "./src/runtime.ts"
}
},
"scripts": {
"typecheck": "tsc --noEmit"
},
"devDependencies": {
"@types/node": "^24.12.2",
"typescript": "catalog:"
}
}

View File

@@ -1,4 +1,5 @@
const HEX_CHARS = '0123456789abcdef';
const HEX_CHARS_UPPER = '0123456789ABCDEF';
export function toHex(data: Uint8Array | Buffer): string {
let h = '';
@@ -9,6 +10,15 @@ export function toHex(data: Uint8Array | Buffer): string {
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;
}
export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string {
const limit = Math.max(0, Math.min(maxBytes, data.length));
const head = toHex(data.subarray(0, limit));

View File

@@ -0,0 +1,6 @@
export type JsonPrimitive = string | number | boolean | null;
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
export interface JsonObject {
[key: string]: JsonValue;
}
export type JsonArray = JsonValue[];

View File

@@ -0,0 +1,274 @@
import fs from 'node:fs';
import path from 'node:path';
const DEFAULT_DIR = 'logs';
const DEFAULT_MAX_MB = 50;
const DEFAULT_RETAIN_DAYS = 7;
const FILE_PREFIX = 'snowluma-';
const FILE_SUFFIX = '.log';
const FILE_RE = /^snowluma-(\d{4}-\d{2}-\d{2})(?:\.(\d+))?\.log$/;
// eslint-disable-next-line no-control-regex
const ANSI_RE = /\x1B\[[0-?]*[ -/]*[@-~]/g;
// Preserve TAB (0x09), LF (0x0A) and ESC (0x1B) — TAB / LF for legit
// multi-line records (stack traces), ESC is stripped through ANSI_RE.
// eslint-disable-next-line no-control-regex
const CTRL_RE = /[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g;
function parsePositiveInt(v: string | undefined, dflt: number): number {
if (!v) return dflt;
const n = Number.parseInt(v, 10);
return Number.isFinite(n) && n > 0 ? n : dflt;
}
function todayString(d: Date = new Date()): string {
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${day}`;
}
function dateOf(s: string): Date {
const [y, m, d] = s.split('-').map((v) => Number.parseInt(v, 10));
return new Date(y!, m! - 1, d!);
}
function stripAnsi(line: string): string {
return line.replace(ANSI_RE, '').replace(CTRL_RE, '');
}
interface OpenFile {
stream: fs.WriteStream;
bytes: number;
date: string;
splitIndex: number;
path: string;
}
/**
* Owns one output directory: keeps at most one open WriteStream, handles
* daily rollover, per-file size cap, and retention cleanup. The shared
* top-level dir uses one of these; each per-UIN sub-dir gets its own.
*/
class FileWriter {
private disabled = false;
private file: OpenFile | null = null;
constructor(
private readonly dir: string,
private readonly maxBytes: number,
private readonly retainDays: number,
) {
try {
fs.mkdirSync(dir, { recursive: true });
} catch (err) {
this.disabled = true;
console.error(
`[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`,
);
return;
}
this.cleanup();
}
get isDisabled(): boolean {
return this.disabled;
}
get currentPath(): string | null {
return this.file?.path ?? null;
}
write(data: string, bytes: number): void {
if (this.disabled) return;
const today = todayString();
this.ensureForToday(today);
if (!this.file) return;
if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) {
this.rotateBySize();
if (!this.file) return;
}
this.file.stream.write(data);
this.file.bytes += bytes;
}
close(): Promise<void> {
const f = this.file;
this.file = null;
if (!f) return Promise.resolve();
return new Promise((resolve) => {
try {
f.stream.end(() => resolve());
} catch {
resolve();
}
});
}
private ensureForToday(today: string): void {
if (this.file && this.file.date === today) return;
if (this.file) {
try {
this.file.stream.end();
} catch {
/* ignore */
}
this.file = null;
this.cleanup();
}
// 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++;
this.file = this.openFile(today, idx);
}
private rotateBySize(): void {
if (!this.file) return;
const date = this.file.date;
try {
this.file.stream.end();
} catch {
/* ignore */
}
let next = this.file.splitIndex + 1;
while (fs.existsSync(this.pathFor(date, next))) next++;
this.file = this.openFile(date, next);
}
private openFile(date: string, splitIndex: number): OpenFile | null {
const p = this.pathFor(date, splitIndex);
try {
let bytes = 0;
try {
bytes = fs.statSync(p).size;
} catch {
/* file doesn't exist yet */
}
const stream = fs.createWriteStream(p, { flags: 'a' });
stream.on('error', (err) => {
console.error(`[logger] file write error on ${p}: ${err.message}`);
});
return { stream, bytes, date, splitIndex, path: p };
} catch (err) {
console.error(
`[logger] failed to open log file ${p}: ${err instanceof Error ? err.message : String(err)}`,
);
return null;
}
}
private pathFor(date: string, splitIndex: number): string {
const tail = splitIndex > 0 ? `.${splitIndex}` : '';
return path.join(this.dir, `${FILE_PREFIX}${date}${tail}${FILE_SUFFIX}`);
}
private cleanup(): void {
let entries: string[];
try {
entries = fs.readdirSync(this.dir);
} catch {
return;
}
const retainMs = this.retainDays * 24 * 60 * 60 * 1000;
const cutoff = Date.now() - retainMs;
for (const name of entries) {
const m = FILE_RE.exec(name);
if (!m) continue;
const dateStr = m[1]!;
if (dateOf(dateStr).getTime() < cutoff) {
try {
fs.unlinkSync(path.join(this.dir, name));
} catch {
/* ignore */
}
}
}
}
}
export class FileTransport {
private readonly dir: string;
private readonly maxBytes: number;
private readonly retainDays: number;
private readonly enabled: boolean;
private readonly perUinEnabled: boolean;
private shared: FileWriter | null = null;
private perUin = new Map<number, FileWriter>();
constructor() {
this.dir = process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR;
this.maxBytes =
parsePositiveInt(process.env.SNOWLUMA_LOG_MAX_MB, DEFAULT_MAX_MB) * 1024 * 1024;
this.retainDays = parsePositiveInt(
process.env.SNOWLUMA_LOG_RETAIN_DAYS,
DEFAULT_RETAIN_DAYS,
);
this.enabled = process.env.SNOWLUMA_LOG_FILE !== '0';
this.perUinEnabled = process.env.SNOWLUMA_LOG_PER_UIN !== '0';
if (this.enabled) {
const w = new FileWriter(this.dir, this.maxBytes, this.retainDays);
this.shared = w.isDisabled ? null : w;
}
}
/** True when no file output will happen (env disable or init failure). */
get isDisabled(): boolean {
return !this.shared;
}
/** Current shared-file path (or null if disabled / not yet opened). */
get currentPath(): string | null {
return this.shared?.currentPath ?? null;
}
/** Path of the per-UIN file for the given UIN, if open. */
perUinPath(uin: number): string | null {
return this.perUin.get(uin)?.currentPath ?? null;
}
write(line: string, uin?: number): void {
if (!this.shared) return;
const data = stripAnsi(line) + '\n';
const bytes = Buffer.byteLength(data, 'utf8');
this.shared.write(data, bytes);
if (uin !== undefined && this.perUinEnabled) {
let w = this.perUin.get(uin);
if (!w) {
w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.retainDays);
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());
this.shared = null;
this.perUin.clear();
await Promise.all(closes);
}
}
let singleton: FileTransport | null = null;
export function getFileTransport(): FileTransport {
if (!singleton) singleton = new FileTransport();
return singleton;
}
/** Reset state between tests. Closes all active file handles. */
export async function _resetFileTransportForTesting(): Promise<void> {
if (singleton) await singleton.close();
singleton = null;
}

View File

@@ -0,0 +1,51 @@
const MAX_FIELD = 40;
const MAX_TOTAL = 200;
function valueRepr(v: unknown): string {
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}"`;
case 'number':
case 'boolean':
case 'bigint':
return String(v);
case 'object':
if (Array.isArray(v)) return `[len=${v.length}]`;
return '{...}';
default:
return typeof v;
}
}
/**
* Render a params object as a single line for logging. Skips deep
* traversal: nested objects collapse to `{...}`, arrays to `[len=N]`.
* Strings are quoted; long ones are truncated with an ellipsis.
*
* Output is capped at MAX_TOTAL chars; on overflow the tail is
* replaced with `...` so the next field doesn't get half-rendered.
*/
export function summarizeParams(params: unknown): string {
if (params === null || params === undefined) return '{}';
if (typeof params !== 'object') {
const s = String(params);
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL)}...` : s;
}
if (Array.isArray(params)) return `[len=${params.length}]`;
const out: string[] = [];
let total = 0;
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
const entry = `${k}=${valueRepr(v)}`;
// +1 accounts for the separating space we'd insert when joining.
if (total > 0 && total + entry.length + 1 > MAX_TOTAL) {
out.push('...');
break;
}
out.push(entry);
total += entry.length + (out.length > 1 ? 1 : 0);
}
return out.join(' ');
}

View File

@@ -0,0 +1,228 @@
import { format } from 'util';
import { getFileTransport } from './log-file-transport';
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
export interface LogEntry {
id: number;
time: string;
level: LogLevel;
scope: string;
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
uin?: number;
message: string;
line: string;
}
interface LogOptions {
scope: string;
uin?: number;
/** Free-form meta carried across `.child(...)` calls. Currently only
* `uin` is rendered, but the bag is preserved for future fields
* (requestId / traceId / etc.). */
meta?: Record<string, unknown>;
}
const UIN_SLOT_WIDTH = 12;
const LEVEL_WEIGHT: Record<LogLevel, number> = {
debug: 10,
info: 20,
success: 25,
warn: 30,
error: 40,
};
const LEVEL_LABEL: Record<LogLevel, string> = {
debug: 'DEBUG',
info: 'INFO',
success: 'OK',
warn: 'WARN',
error: 'ERROR',
};
const COLOR_CODE: Record<LogLevel, number> = {
debug: 90,
info: 36,
success: 32,
warn: 33,
error: 31,
};
const COLOR_SCOPE = 35;
const COLOR_DIM = 2;
const COLOR_RESET = '\x1b[0m';
const MAX_LOG_ENTRIES = 1000;
const logEntries: LogEntry[] = [];
const logSubscribers = new Set<(entry: LogEntry) => void>();
let nextLogId = 1;
function resolveMinLevel(): LogLevel {
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
if (raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
return raw;
}
return 'info';
}
// Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but
// setLogLevel() lets WebUI / SDK callers flip it without a restart.
// Only governs console + ring buffer + subscribers; the file
// transport always sees debug-and-up regardless.
let currentLevel: LogLevel = resolveMinLevel();
function shouldLog(level: LogLevel): boolean {
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
}
export const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
export function getLogLevel(): LogLevel {
return currentLevel;
}
/**
* Change the console / subscriber level at runtime. Invalid input is
* a no-op (returns false). File transport is unaffected — it always
* sees every level so post-mortems remain useful.
*/
export function setLogLevel(level: string): boolean {
const lower = String(level).toLowerCase();
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;
return Boolean(process.stdout.isTTY);
}
function ansi(code: number, text: string): string {
return `\x1b[${code}m${text}${COLOR_RESET}`;
}
function currentTime(): string {
const d = new Date();
const hh = String(d.getHours()).padStart(2, '0');
const mm = String(d.getMinutes()).padStart(2, '0');
const ss = String(d.getSeconds()).padStart(2, '0');
return `${hh}:${mm}:${ss}`;
}
function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
const message = format(...args);
const ts = currentTime();
const label = LEVEL_LABEL[level].padEnd(5, ' ');
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
if (!useColor()) {
return `${ts} ${label} ${uinSlot} [${options.scope}] ${message}`;
}
const cTs = ansi(COLOR_DIM, ts);
const cLabel = ansi(COLOR_CODE[level], label);
// Pad first, then color only the visible tag so escape codes don't eat
// into the alignment width.
const cUin = uinTag
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
: ' '.repeat(UIN_SLOT_WIDTH);
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
return `${cTs} ${cLabel} ${cUin} ${cScope} ${message}`;
}
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
// Console / subscriber level filter. File output is debug-and-up always;
// see log-file-transport.ts.
const passesConsole = shouldLog(level);
const message = format(...args);
const line = render(level, options, args);
const entry: LogEntry = {
id: nextLogId++,
time: new Date().toISOString(),
level,
scope: options.scope,
...(options.uin !== undefined ? { uin: options.uin } : {}),
message,
line,
};
if (passesConsole) {
logEntries.push(entry);
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
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
// triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A)
// 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');
}
// File transport always sees every level (debug-and-up) for post-mortem
// value; ANSI stripping happens inside the transport. UIN routes the
// line to its per-account sub-file in addition to the shared one.
getFileTransport().write(line, options.uin);
}
/**
* Flush and close the underlying log file. Call from shutdown hooks
* (SIGINT / SIGTERM / uncaughtException) so the WriteStream's internal
* buffer makes it to disk. Returns a promise that resolves once the OS
* has finalized the write.
*/
export function closeLogger(): Promise<void> {
return getFileTransport().close();
}
export function getRecentLogs(limit = 300): LogEntry[] {
const n = Math.max(1, Math.min(Math.trunc(limit), MAX_LOG_ENTRIES));
return logEntries.slice(-n);
}
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
logSubscribers.add(callback);
return () => {
logSubscribers.delete(callback);
};
}
export interface Logger {
debug: (...args: unknown[]) => void;
info: (...args: unknown[]) => void;
success: (...args: unknown[]) => void;
warn: (...args: unknown[]) => void;
error: (...args: unknown[]) => void;
/**
* Derive a new logger that inherits this one's scope and carries
* additional metadata. Currently `uin` is the only key with rendering
* support (shown in the `[UIN]` slot and routed to a per-UIN file);
* other keys are preserved on the options bag for forward compat.
*/
child: (meta: { uin?: number;[k: string]: unknown }) => Logger;
}
function makeLogger(opts: LogOptions): Logger {
return {
debug: (...args: unknown[]) => emit('debug', opts, args),
info: (...args: unknown[]) => emit('info', opts, args),
success: (...args: unknown[]) => emit('success', opts, args),
warn: (...args: unknown[]) => emit('warn', opts, args),
error: (...args: unknown[]) => emit('error', opts, args),
child: (meta) => {
const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin;
return makeLogger({
scope: opts.scope,
uin: nextUin,
meta: { ...(opts.meta ?? {}), ...meta },
});
},
};
}
export function createLogger(scope: string): Logger {
return makeLogger({ scope });
}

View File

@@ -8,3 +8,4 @@ export interface PacketInfo {
fromClient: boolean;
body: Uint8Array;
}
export type PacketSink = (packet: PacketInfo) => void;

View File

@@ -0,0 +1,113 @@
import fs from 'fs';
import path from 'path';
export interface RuntimeConfig {
webuiPort?: number;
/** When true, every newly-discovered QQ process gets auto-injected by
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
* Defaults to false; the Docker image flips it on in supervisord.conf. */
hookAutoLoad?: boolean;
}
const CONFIG_DIR = 'config';
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {
webuiPort: 5099,
hookAutoLoad: false,
};
export function loadRuntimeConfig(): RuntimeConfig {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
const loaded = tryLoadRuntimeConfig();
let normalized: RuntimeConfig;
if (!loaded) {
saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG);
normalized = { ...DEFAULT_RUNTIME_CONFIG };
} else {
normalized = {
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false),
};
if (
normalized.webuiPort !== loaded.webuiPort
|| normalized.hookAutoLoad !== loaded.hookAutoLoad
) {
saveRuntimeConfig(normalized);
}
}
// SNOWLUMA_WEBUI_PORT overrides the on-disk value at runtime without
// rewriting runtime.json. Lets a trusted launcher (e.g. SnowLumaDesktop)
// pick a free port per-launch while CLI/Docker users continue to drive
// it from runtime.json.
const envPort = envPortOverride();
if (envPort !== undefined) {
normalized = { ...normalized, webuiPort: envPort };
}
return normalized;
}
function envPortOverride(): number | undefined {
const raw = process.env.SNOWLUMA_WEBUI_PORT;
if (!raw || typeof raw !== 'string') return undefined;
const n = Number(raw.trim());
if (!Number.isFinite(n)) return undefined;
const port = Math.trunc(n);
if (port <= 0 || port > 65535) return undefined;
return port;
}
function tryLoadRuntimeConfig(): RuntimeConfig | null {
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
try {
const raw = fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8');
const parsed = JSON.parse(raw) as unknown;
if (!isObject(parsed)) return null;
return {
webuiPort: normalizePort(parsed.webuiPort ?? 5099, 5099),
hookAutoLoad: normalizeBool(parsed.hookAutoLoad, false),
};
} catch {
return null;
}
}
function saveRuntimeConfig(config: RuntimeConfig): void {
fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
}
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;
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;
}
}
return fallback;
}
function normalizeBool(value: unknown, fallback: boolean): boolean {
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;
}
return fallback;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}

View File

@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"],
"noEmit": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
]
}

View File

@@ -0,0 +1,3 @@
{
"webuiPort": 8080
}

View File

@@ -0,0 +1,65 @@
{
"name": "@snowluma/core",
"version": "1.9.2",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
"main": "../../dist/index.mjs",
"exports": {
".": {
"types": "./src/index.ts",
"default": "../../dist/index.mjs"
},
"./core": {
"types": "./src/core.ts",
"default": "./src/core.ts"
},
"./core-context": {
"types": "./src/core-context.ts",
"default": "./src/core-context.ts"
},
"./core-ctx": {
"types": "./src/core-ctx.ts",
"default": "./src/core-ctx.ts"
},
"./hub": {
"types": "./src/hub.ts",
"default": "./src/hub.ts"
},
"./apis": {
"types": "./src/apis/index.ts",
"default": "./src/apis/index.ts"
}
},
"scripts": {
"build": "vite build",
"build:all": "cross-env BUILD_WEBUI=true vite build",
"dev": "tsx src/index.ts",
"test": "vitest run",
"test:watch": "vitest",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/channel": "workspace:*",
"@snowluma/channel-hook": "workspace:*",
"@snowluma/channel-socket": "workspace:*",
"@snowluma/common": "workspace:*",
"@snowluma/onebot": "workspace:*",
"@snowluma/protocol": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/websocket": "workspace:*"
},
"devDependencies": {
"@hono/node-server": "^1.19.14",
"@rollup/plugin-node-resolve": "^16.0.3",
"@types/node": "^24.12.2",
"cross-env": "^10.1.0",
"hono": "^4.12.18",
"tsx": "^4.21.0",
"typescript": "catalog:",
"vite": "catalog:",
"vite-plugin-cp": "^6.0.3",
"vitest": "^4.1.4"
}
}

View File

@@ -0,0 +1,233 @@
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
import { FetchFriendListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
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 { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile';
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
import type {
FriendInfo,
GroupMemberInfo,
GroupRequestInfo,
QQGroupInfo,
UserProfileInfo,
} from '@snowluma/protocol/qq-info';
import type { CoreContext } from '../core-context';
/**
* One row of an `OidbSvcTrpcTcp.0x9067_202` (download rkey) response.
* Cached for the duration of `ttlSeconds` and consumed by the OneBot
* media-URL resolver / message converter when a download URL must be
* minted on the fly. Lives at the apis layer (not on `Bridge`) because
* only `apis.contacts.fetchDownloadRKeys` materialises these rows.
*/
export interface DownloadRKeyInfo {
rkey: string;
ttlSeconds: number;
storeId: number;
createTime: number;
type: number;
}
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
type FriendPropertySource = {
additional?: Array<{
type?: number;
layer1?: {
properties?: Array<{
code?: number;
value?: 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';
}
}
const MEMBER_LIST_TTL_MS = 60_000;
export class ContactsApi {
/**
* Per-group inflight + last-fetch cache for `fetchGroupMemberList`.
* Keyed by groupId, lives for the lifetime of the Bridge.
*
* Without this, a busy OneBot client (e.g. MaiBot calling
* `get_group_member_info` once per inbound message) triggers one
* OIDB 0xfe7_3 per chat message — sustained >1k/h, which trips
* Tencent risk-control and gets the account banned for 7 days.
*/
private memberListInflight = new Map<number, Promise<GroupMemberInfo[]>>();
private memberListLastFetch = new Map<number, { at: number; data: GroupMemberInfo[] }>();
constructor(private readonly ctx: CoreContext) { }
async fetchFriendList(): Promise<FriendInfo[]> {
const friends: FriendInfo[] = [];
let nextUin: number | null = null;
do {
const resp = await FetchFriendListPage.invoke(this.ctx, { nextUin });
for (const raw of resp.friends ?? []) {
const props = buildFriendProperties(raw);
friends.push({
uin: raw.uin ?? 0,
uid: raw.uid ?? '',
nickname: props.get(20002) ?? String(raw.uin ?? 0),
remark: props.get(103) ?? '',
});
}
nextUin = resp.next?.uin ?? null;
if (nextUin === 0) nextUin = null;
} while (nextUin !== null);
this.ctx.identity.rememberFriends(friends);
return friends;
}
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,
groupName: raw.info?.groupName ?? '',
remark: raw.customInfo?.remark ?? '',
memberCount: raw.info?.memberCount ?? 0,
memberMax: raw.info?.memberMax ?? 0,
members: new Map(),
});
}
this.ctx.identity.rememberGroups(groups);
return groups;
}
async fetchGroupMemberList(
groupId: number,
options: { force?: boolean } = {},
): Promise<GroupMemberInfo[]> {
const now = Date.now();
const last = this.memberListLastFetch.get(groupId);
if (!options.force && last && now - last.at < MEMBER_LIST_TTL_MS) {
return last.data;
}
const inflight = this.memberListInflight.get(groupId);
if (inflight) return inflight;
const task = (async () => {
try {
const data = await this.fetchGroupMemberListUncached(groupId);
this.memberListLastFetch.set(groupId, { at: Date.now(), data });
return data;
} finally {
this.memberListInflight.delete(groupId);
}
})();
this.memberListInflight.set(groupId, task);
return task;
}
private async fetchGroupMemberListUncached(groupId: number): Promise<GroupMemberInfo[]> {
const members: GroupMemberInfo[] = [];
let token = '';
do {
const resp = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token });
for (const raw of resp.members ?? []) {
members.push({
uin: raw.uin?.uin ?? 0,
uid: raw.uin?.uid ?? '',
nickname: raw.memberName ?? '',
card: raw.memberCard?.memberCard ?? '',
role: permissionToRole(raw.permission ?? 0),
level: raw.level?.level ?? 0,
title: raw.specialTitle ?? '',
joinTime: raw.joinTimestamp ?? 0,
lastSentTime: raw.lastMsgTimestamp ?? 0,
shutUpTime: raw.shutUpTimestamp ?? 0,
});
}
token = resp.token ?? '';
} while (token);
this.ctx.identity.rememberGroupMembers(groupId, members);
return members;
}
async fetchUserProfile(uin: number): Promise<UserProfileInfo> {
const info = await FetchUserProfile.invoke(this.ctx, { uin });
this.ctx.identity.rememberUserProfile(info);
return info;
}
/** Look up a user profile by UID (string form). Used for strangers
* whose UIN we don't have yet — typically the requester on a
* group join request push. Mirrors Lagrange's `FetchUserInfoEvent
* .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);
return info;
}
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> {
const resp = await FetchGroupRequests.invoke(this.ctx, { filtered });
const requests: GroupRequestInfo[] = [];
for (const raw of resp.requests ?? []) {
requests.push({
groupId: raw.group?.groupUin ?? 0,
groupName: raw.group?.groupName ?? '',
targetUid: raw.target?.uid ?? '',
targetUin: 0,
targetName: raw.target?.name ?? '',
invitorUid: raw.invitor?.uid ?? '',
invitorUin: 0,
invitorName: raw.invitor?.name ?? '',
operatorUid: raw.operatorUser?.uid ?? '',
operatorUin: 0,
operatorName: raw.operatorUser?.name ?? '',
sequence: Number(raw.sequence ?? 0),
state: raw.state ?? 0,
eventType: raw.eventType ?? 0,
comment: raw.comment ?? '',
filtered,
});
}
this.ctx.identity.rememberGroupRequests(requests);
return requests;
}
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,
ttlSeconds: Number(entry.rkeyTtlSec ?? 0),
storeId: entry.storeId ?? 0,
createTime: entry.rkeyCreateTime ?? 0,
type,
});
}
}
return result;
}
}

View File

@@ -0,0 +1,91 @@
import { FetchAiVoice } from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice';
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 { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
import type { CoreContext } from '../core-context';
import type { MediaIndexNode } from './shared';
// ─────────────── public types (re-exported from bridge.ts as before) ───
export type StrangerStatus = NamespaceStrangerStatus;
export const AiVoiceChatType = {
Unknown: 0,
Sound: 1,
Sing: 2,
} as const;
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
export type AiVoiceCategory = NamespaceAiVoiceCategory;
export interface AiVoiceItem {
voiceId: string;
voiceDisplayName: string;
voiceExampleUrl: string;
}
export class ExtrasApi {
constructor(private readonly ctx: CoreContext) { }
// ─────────────── Group todo (0xF90) ───────────────
setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' });
}
completeGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'complete' });
}
cancelGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'cancel' });
}
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
/**
* Returns `null` on transport / decode failure rather than throwing,
* so the OneBot action can produce a clean retcode without try/catch
* gymnastics. Namespace throws on transport failure → swallow here.
*/
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
try {
return await GetStrangerStatus.invoke(this.ctx, { uin });
} catch {
return null;
}
}
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise<AiVoiceCategory[]> {
return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType });
}
/**
* Trigger AI voice synthesis. Server may return an empty msgInfo while
* the render is in-flight; we retry until a node materialises or the
* cap is hit. napcat uses the same 30-retry budget.
*
* The returned MediaIndexNode plugs directly into
* `apis.groupFile.getPttUrl`, which already handles every other
* download-URL fetch in SnowLuma.
*/
async fetchAiVoice(
groupId: number,
voiceId: string,
text: string,
chatType: AiVoiceChatType | number,
maxRetries = 30,
): Promise<MediaIndexNode> {
// Random 32-bit session id — server uses this to deduplicate polls.
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
for (let i = 0; i < maxRetries; i++) {
const node = await FetchAiVoice.invoke(this.ctx, { groupId, voiceId, text, chatType, sessionId });
if (node) return node as MediaIndexNode;
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
}
}

View File

@@ -0,0 +1,560 @@
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type {
LongMsgResult,
RecvLongMsgReq,
RecvLongMsgResp,
SendLongMsgReq,
SendLongMsgResp,
} from '@snowluma/proto-defs/longmsg';
import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events';
import { parseMsgPush } from '@snowluma/protocol/msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { randomUUID } from 'crypto';
import { gunzipSync, gzipSync } from 'zlib';
import type { CoreContext } from '../core-context';
import { resolveSelfUid, toInt } from './shared';
// Module-scoped cache, keyed by res_id. Survives only for the lifetime
// of the process — that's enough because OneBot clients typically
// resolve a forward immediately after receiving the parent message.
const forwardResCache = new Map<string, ForwardNodePayload[]>();
// Per-layer piggyback entry. Each level of a nested forward attaches
// its own msgBody under a uuid `actionCommand`, so when the receiver
// fetches the outermost res_id it gets every layer in one shot
// (modelled on NapCat's `uploadForwardedNodesPacket` — see
// `dev/NapCatQQ/.../SendMsg.ts:208-347`). Lagrange.Core master + V2
// both ship a single-action model and silently break when the
// recipient is a NapCat instance trying to walk the tree.
interface ForwardInnerAction {
uuid: string;
msgBody: PushMsgBody[];
}
interface ForwardUploadResult {
resId: string;
// The current level's msgBody + uuid — what an outer caller would
// piggyback to expose this layer through the tree.
msgBody: PushMsgBody[];
uuid: string;
// All accumulated piggyback entries from deeper levels. Outer
// callers concatenate these to their own actions list so the
// outermost upload carries the full tree.
innerActions: ForwardInnerAction[];
}
// Local hex-decode helper — avoids importing the heavyweight `pipeline`
// 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);
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;
}
async function buildForwardPushBody(
bridge: BridgeContext,
node: ForwardNodePayload,
groupId?: number,
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');
const nickname = node.nickname.trim() || String(fromUin);
// image/record/video upload inside a forward node must be scoped to the
// forward's recipient: group → groupId, private → recipient uid.
// Without this the OIDB upload (0x11c4/0x11c5) has no scene and the
// element builder throws "private image target uid is missing".
//
// `forwardFake: true` keeps `{type:'file'}` segments in the
// long-msg payload: group → emitted as transElem(24) in elems[],
// c2c → handled below via msgContent (FileExtra { file: NotOnlineFile }).
// The QQ-NT live-send pipeline would reject these (transElem(24) →
// 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
? { bridge, groupId, forwardFake: true }
: userUid
? { bridge, userUid, forwardFake: true }
: { bridge, forwardFake: true };
const elems = await buildSendElems(node.elements, sendCtx);
const now = Math.floor(Date.now() / 1000);
const random = Math.floor(Math.random() * 0x7fffffff) >>> 0;
const seq = Math.floor(Math.random() * 9000000) + 1000000;
// c2c-file in a forward node — element-builder intentionally skips
// it (RichText.notOnlineFile + msgContent live outside elems[]). For
// forward fake-send we mirror what an inbound c2c file message looks
// like on the wire: serialise the FileExtra blob and ride it on
// `body.msgContent`. The receiver's rich-body-decoder reads from
// `msgContent` first (see msg-push/rich-body-decoder.ts:446+), so
// the bubble renders with the right file name + size when the
// forward is expanded. Only the FIRST c2c file in a node ships —
// QQ NT's bubble can only carry one msgContent payload, same as
// 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);
if (fileEl) {
// Honour inline segment fields first; fall back to the upload
// metadata cache (populated by upload_private_file). Without
// size/md5 the receiver would render "0 B" so prefer recovering
// them — see same logic in modules/message-actions.ts.
const cached = bridge.recallUploadedFile(fileEl.fileId ?? '');
const fileMd5 = fileEl.md5Hex
? hexToBytesLocal(fileEl.md5Hex)
: (cached?.fileMd5 ?? new Uint8Array(0));
const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0;
const fileName = fileEl.fileName ?? cached?.fileName ?? 'file';
const fileHash = fileEl.fileHash ?? cached?.fileHash ?? '';
const sevenDays = 7 * 24 * 60 * 60;
msgContent = protobuf_encode<FileExtra>({
file: {
fileType: 0,
fileUuid: fileEl.fileId!,
fileMd5,
fileName,
fileSize: BigInt(fileSize),
subcmd: 1,
dangerEvel: 0,
expireTime: now + sevenDays,
fileHash,
},
});
}
}
return {
responseHead: {
fromUin,
toUid: bridge.identity.selfUid ?? '',
forward: {
friendName: nickname,
},
},
contentHead: {
msgType: 9,
subType: 4,
msgId: random,
sequence: seq,
timestamp: now,
divSeq: 0,
},
body: {
richText: {
elems,
},
...(msgContent ? { msgContent } : {}),
},
};
}
// Inner forward preview metadata — kept minimal here (the OneBot
// `parseForwardNodes` caller can override these on the top-level
// node by passing custom forwardSource/forwardSummary on the
// non-nested send path; nested levels just get sensible defaults
// since they're synthesised by us and never reach OneBot input).
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 === 0) return isGroup ? '群聊的聊天记录' : '聊天记录';
return `${nicks.join('和')}的聊天记录`;
}
function previewLinesFromNodes(innerNodes: ForwardNodePayload[]): Array<{ text: string }> {
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 };
});
}
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 '[表情]';
}
return '';
}
export class ForwardApi {
constructor(private readonly ctx: CoreContext) { }
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
return resId;
}
/**
* Recursive upload with NapCat-style piggyback. Each invocation:
* 1. Walks `nodes`. For any node whose `innerForward` is set,
* recursively uploads that inner chain first (which itself runs
* this same recursion).
* 2. Replaces the node's `elements` with an ARK preview pointing at
* the inner res_id (and inner uuid for receiver-side walking).
* 3. Accumulates the inner level's `{uuid, msgBody}` plus all of
* ITS accumulated `innerActions` into this level's piggyback list.
* 4. Encodes this level's long-msg payload as
* `[MultiMsg + thisMsgBody, ...innerActions]`, uploads it,
* returns `{resId, msgBody, uuid, innerActions}` so an outer
* caller can keep piggybacking up the tree.
*/
private async uploadRecursive(
nodes: ForwardNodePayload[],
groupId?: number,
userId?: number,
): Promise<ForwardUploadResult> {
if (!Array.isArray(nodes) || nodes.length === 0) {
throw new Error('forward nodes are required');
}
const bridge = this.ctx;
// For a private forward to `userId`, any image/record/video inside a node
// needs the recipient's uid as upload scene. Resolve it once up-front,
// and only when at least one node actually contains media (saves an RPC
// 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'));
if (needsUid) {
const resolved = await this.ctx.resolveUserUid(userId);
if (resolved) userUid = resolved;
}
}
// Walk nodes and resolve nested forwards first (so we know their
// res_id / uuid before encoding the outer ARK previews). Build
// `processedNodes` with elements rewritten for nested layers,
// and collect every inner level's piggyback in `myInnerActions`.
//
// CRITICAL: the same uuid (`inner.uuid`) MUST be baked into the
// outer's preview element as `forwardUuid` AND used as the
// `actionCommand` for the outer's piggyback entry. That's the
// alignment the QQ-NT receiver uses to find the inner layer
// inside the outer's LongMsgResult without a second server fetch
// — see `dev/NapCatQQ/.../SendMsg.ts:241-246` + the `uniseq` round-
// trip in `dev/NapCatQQ/.../forward-msg-builder.ts:94`.
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);
// NapCat piggybacks `{uuid: inner.uuid, packetMsg: inner.packetMsg}`
// + the entire `inner.innerPacketMsg` array up to its caller. We
// mirror that — `inner.uuid` indexes the inner level itself,
// and `inner.innerActions` already contains deeper layers.
myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody });
myInnerActions.push(...inner.innerActions);
// Replace the inner placeholder element with a forward preview
// pointing at the inner res_id. `forwardUuid: inner.uuid`
// baked into the LightApp JSON's `meta.detail.uniseq` is what
// closes the loop with our piggyback action above.
const previewElement: MessageElement = {
type: 'forward',
resId: inner.resId,
forwardUuid: inner.uuid,
forwardSource: deriveInnerSource(node.innerForward, isGroup),
forwardSummary: `查看${node.innerForward.length}条转发消息`,
forwardPrompt: '[聊天记录]',
forwardNews: 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,
});
} else {
processedNodes.push(node);
}
}
// Encode this level's msgBody.
const msgBody = await Promise.all(processedNodes.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 => ({
actionCommand: a.uuid,
actionData: { msgBody: a.msgBody },
})),
],
});
const selfUid = await resolveSelfUid(bridge);
const info: SendLongMsgReq['info'] = {
type: groupId ? 3 : 1,
uid: { uid: groupId ? String(groupId) : selfUid },
payload: gzipSync(Buffer.from(longMsgResult)),
};
if (groupId) info.groupUin = groupId;
const request = protobuf_encode<SendLongMsgReq>({
info,
settings: {
field1: 4,
field2: 1,
field3: 7,
field4: 0,
},
});
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, processedNodes.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId ?? groupId,
senderCard: node.senderCard,
messageType: node.messageType ?? (groupId ? 'group' : 'private'),
})));
return {
resId,
msgBody,
// UUID generated here so the OUTER caller can use it as both
// (1) the `actionCommand` for its piggyback entry carrying our
// msgBody, and
// (2) the `forwardUuid` baked into its forward-preview element
// pointing at our resId.
// Receivers walking the outer's LongMsgResult find the inner
// layer by matching `uniseq` from (2) against `actionCommand`
// from (1) — no separate fetch needed.
uuid: randomUUID(),
innerActions: myInnerActions,
};
}
async fetch(resId: string): Promise<ForwardNodePayload[]> {
const bridge = this.ctx;
const cached = forwardResCache.get(resId);
if (cached) {
return 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 selfUid = await resolveSelfUid(bridge);
const request = protobuf_encode<RecvLongMsgReq>({
info: {
uid: { uid: selfUid },
resId,
acquire: true,
},
settings: {
field1: 2,
field2: 0,
field3: 0,
field4: 0,
},
});
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');
}
const inflate = gunzipSync(Buffer.from(payload));
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 : [];
// Piggyback index: any non-`MultiMsg` action carries an inner
// layer keyed by the uuid the sender baked into its forward
// preview's `uniseq`. Build a lookup so we can resolve inner
// forwards (via their uniseq → inner msgBody) without a second
// 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;
const body = Array.isArray(action.actionData?.msgBody) ? action.actionData.msgBody : [];
piggybackByUuid.set(cmd, body);
}
const nodes = this.decodeMsgBodiesToNodes(msgBodyList);
// Walk the decoded outer nodes for inner-forward previews
// (`type: 'forward', forwardUuid: <uniseq>`). For each, pull the
// matching piggyback body, decode it into inner nodes, and seed
// the cache by the inner resId so a follow-up `fetch(innerResId)`
// hits the cache instead of the wire.
if (piggybackByUuid.size > 0) {
this.consumePiggybacks(nodes, piggybackByUuid);
}
if (nodes.length > 0) {
forwardResCache.set(resId, cloneNodes(nodes));
}
return nodes;
}
/** Walk a list of PushMsgBody, run each through the regular msg-push
* pipeline, and shape the result into ForwardNodePayloads. Extracted
* 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 = {
pid: 0,
uin: this.ctx.identity.uin,
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
seqId: 0,
retCode: 0,
fromClient: false,
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;
if (event.kind === 'group_message') {
out.push({
userUin: event.senderUin,
nickname: event.senderCard || event.senderNick,
elements: event.elements,
time: event.time,
msgId: event.msgId,
msgSeq: event.msgSeq,
groupId: event.groupId,
senderCard: event.senderCard,
messageType: 'group',
});
} else if (event.kind === 'friend_message') {
out.push({
userUin: event.senderUin,
nickname: event.senderNick,
elements: event.elements,
time: event.time,
msgId: event.msgId,
msgSeq: event.msgSeq,
messageType: 'private',
});
} else {
out.push({
userUin: event.senderUin,
nickname: event.senderNick,
elements: event.elements,
time: event.time,
msgSeq: event.msgSeq,
groupId: event.groupId,
messageType: 'private',
});
}
}
return out;
}
/** Recursively resolve forward previews against the piggyback table.
* For every `{type: 'forward', resId, forwardUuid}` element we find,
* look up the uniseq in the piggyback map; if hit, decode the
* inner msgBody and cache it by inner resId, then descend into that
* inner layer to resolve deeper nestings carried in the SAME
* piggyback set (NapCat hoists the entire tree's piggybacks onto
* the outermost action list). */
private consumePiggybacks(
nodes: ForwardNodePayload[],
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;
const uuid = elem.forwardUuid;
const innerResId = elem.resId;
if (!uuid || !innerResId || seen.has(uuid)) continue;
const body = piggybackByUuid.get(uuid);
if (!body) continue;
seen.add(uuid);
const innerNodes = this.decodeMsgBodiesToNodes(body);
forwardResCache.set(innerResId, cloneNodes(innerNodes));
visit(innerNodes);
}
}
};
visit(nodes);
}
}
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,
}));
}

View File

@@ -0,0 +1,29 @@
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request';
import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark';
import type { CoreContext } from '../core-context';
export class FriendApi {
constructor(private readonly ctx: CoreContext) { }
/**
* Accept or reject an inbound friend request. `uidOrFlag` is either a
* pre-resolved UID string or a numeric uin (then resolved on the fly).
*/
handleRequest(uidOrFlag: string, approve: boolean): Promise<void> {
return HandleFriendRequest.invoke(this.ctx, { uidOrFlag, approve });
}
async delete(userId: number, block = false): Promise<void> {
await DeleteFriend.invoke(this.ctx, { userId, block });
// Refresh friend cache after deletion so subsequent reads don't
// surface a ghost entry. Best-effort: a transient OIDB hiccup here
// shouldn't make the delete itself look failed.
try { await this.ctx.apis.contacts.fetchFriendList(); } catch { /* ignore */ }
}
setRemark(userId: number, remark: string): Promise<void> {
return SetFriendRemark.invoke(this.ctx, { userId, remark });
}
}

View File

@@ -0,0 +1,87 @@
import { GetAtAllRemain } from '@snowluma/protocol/oidb-services/group-admin/get-at-all-remain';
import { KickMember } from '@snowluma/protocol/oidb-services/group-admin/kick-member';
import { KickMembers } from '@snowluma/protocol/oidb-services/group-admin/kick-members';
import { LeaveGroup } from '@snowluma/protocol/oidb-services/group-admin/leave-group';
import { MuteAll } from '@snowluma/protocol/oidb-services/group-admin/mute-all';
import { MuteMember } from '@snowluma/protocol/oidb-services/group-admin/mute-member';
import { SetAddOption } from '@snowluma/protocol/oidb-services/group-admin/set-add-option';
import { SetAddRequest } from '@snowluma/protocol/oidb-services/group-admin/set-add-request';
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 { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
import type { CoreContext } from '../core-context';
export class GroupAdminApi {
constructor(private readonly ctx: CoreContext) { }
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
}
muteAll(groupId: number, enable: boolean): Promise<void> {
return MuteAll.invoke(this.ctx, { groupId, enable });
}
setAddOption(groupId: number, addType: number): Promise<void> {
return SetAddOption.invoke(this.ctx, { groupId, addType });
}
setSearch(groupId: number): Promise<void> {
return SetSearch.invoke(this.ctx, { groupId });
}
setAddRequest(
groupId: number, sequence: number, eventType: number,
approve: boolean, reason = '', filtered = false,
): Promise<void> {
return SetAddRequest.invoke(this.ctx, { groupId, sequence, eventType, approve, reason, filtered });
}
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
return KickMember.invoke(this.ctx, { groupId, userId, reject, reason });
}
kickMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> {
return KickMembers.invoke(this.ctx, { groupId, userIds, reject });
}
leave(groupId: number): Promise<void> {
return LeaveGroup.invoke(this.ctx, { groupId });
}
setAdmin(groupId: number, userId: number, enable: boolean): Promise<void> {
return SetAdmin.invoke(this.ctx, { groupId, userId, enable });
}
setCard(groupId: number, userId: number, card: string): Promise<void> {
return SetMemberCard.invoke(this.ctx, { groupId, userId, card });
}
setName(groupId: number, name: string): Promise<void> {
return SetGroupName.invoke(this.ctx, { groupId, name });
}
setSpecialTitle(groupId: number, userId: number, title: string): Promise<void> {
return SetSpecialTitle.invoke(this.ctx, { groupId, userId, title });
}
/**
* The bot's local-only label for a group. Lives here rather than
* `FriendApi` because the semantic is "operate on a group" rather
* than "operate on a contact list".
*/
setRemark(groupId: number, remark: string): Promise<void> {
return SetGroupRemark.invoke(this.ctx, { groupId, remark });
}
getAtAllRemain(groupId: number): Promise<{
can_at_all: boolean;
remain_at_all_count_for_group: number;
remain_at_all_count_for_uin: number;
}> {
return GetAtAllRemain.invoke(this.ctx, { groupId });
}
}

View File

@@ -0,0 +1,279 @@
import type { JsonObject, JsonValue } from '@snowluma/common/json';
import type {
DeleteMediasRequest,
DeleteMediasResponse,
DoQunCommentRequest,
DoQunCommentResponse,
DoQunLikeRequest,
DoQunLikeResponse,
GetMediaListRequest,
GetMediaListResponse,
MediaInfo,
} from '@snowluma/proto-defs/oidb-actions/group-album';
import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { CoreContext } from '../core-context';
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 (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;
return null;
}
export class GroupAlbumApi {
constructor(private readonly ctx: CoreContext) { }
// 列出群相册(基于 qzone.qq.com 的 HTTP Cookie)。
async list(groupId: number): Promise<GroupAlbumList> {
const groupCode = groupId.toString();
const uin = this.ctx.identity.uin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
const albumData = await getGroupAlbumList(cookieObject, groupCode, uin);
return albumData?.album || [];
}
// 上传图片到现有相册(HTTP 分片上传)。
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> {
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const body = protobuf_encode<GetMediaListRequest>({
field1: 0,
field2: new Uint8Array(0),
field3: new Uint8Array(0),
reqInfo: {
groupId: groupId.toString(),
albumId,
field3: 0,
attachInfo,
field5: '',
},
traceId,
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
body,
15000,
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to get album media list');
}
const resp = protobuf_decode<GetMediaListResponse>(result.responseData);
if (resp.field1 !== 0) {
throw new Error(`fetch album media list error: retCode ${resp.field1 ?? 'unknown'}`);
}
const data = resp.data ?? {};
const mediaList = data.mediaList ?? [];
const nextAttachInfo = data.nextAttachInfo ?? '';
return convertBigIntToString({ mediaList, nextAttachInfo }) as unknown as GroupAlbumMediaResult;
}
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 body = protobuf_encode<DoQunCommentRequest>({
field1: 8527,
field2: new Uint8Array(0),
field3: new Uint8Array(0),
body: {
groupId: groupId.toString(),
field3: 2,
reqBody: {
field1: { field3: 0, field4: '' },
field2: {
field1: { uin },
},
field5: {
field1: {
field2: {
field1: 0, field2: '',
lloc,
field4: '', field6: '', field7: 0, field8: 0, field9: 0, field14: 0, field15: 0, field17: 0,
},
},
albumId,
field5: 0,
},
},
field5: {
field2: { uin },
field3: {
field1: 0,
field2: content,
field3: '', field4: '', field5: 0, field6: '',
},
clientKey,
},
},
traceId,
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
body,
15000,
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to comment on album media');
}
const resp = protobuf_decode<DoQunCommentResponse>(result.responseData);
const resCode = resp.field1;
if (resCode !== 0 && resCode !== 8527 && !resp.comment) {
throw new Error(`comment album media error: retCode ${resCode ?? 'unknown'}`);
}
const commentData = resp.comment?.data ?? {};
return convertBigIntToString({
id: commentData.id ?? '',
user: { uin: commentData.user?.uin ?? '' },
content: commentData.content ?? [],
time: commentData.time ?? '0',
clientKey: commentData.clientKey ?? '',
}) as unknown as GroupAlbumCommentResult;
}
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 body = protobuf_encode<DoQunLikeRequest>({
field1: 5495,
field2: 'h5_test',
field3: 'h5_test',
body: {
type,
like: { id, status },
publish: {
cellCommon: {
time: BigInt(Date.now()),
feedId: `422_0_${batchId}`,
},
cellUserInfo: {
user: { uin },
},
cellMedia: {
albumId,
batchId: BigInt(batchId),
},
cellQunInfo: {
qunId: groupId.toString(),
},
},
clientKey,
},
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
body,
15000,
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to like album media');
}
const resp = protobuf_decode<DoQunLikeResponse>(result.responseData);
const resCode = resp.field1;
if (resCode !== 5495) {
throw new Error(`like album media error: retCode ${resCode ?? 'unknown'}`);
}
return convertBigIntToString(resp.body?.like ?? {});
}
async delete(groupId: number, albumId: string, lloc: string): Promise<{ success: true }> {
const uin = this.ctx.identity.uin;
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const body = protobuf_encode<DeleteMediasRequest>({
field1: 8694,
field2: 'h5_test',
field3: 'h5_test',
body: {
groupId: groupId.toString(),
albumId,
lloc,
},
traceId: clientKey,
extMap: [{ key: 'fc-appid', value: '100' }],
});
const result = await this.ctx.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
body,
15000,
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'failed to delete album media');
}
const resp = protobuf_decode<DeleteMediasResponse>(result.responseData);
const resCode = resp.field1;
const errCode = resp.field2;
const errMsg = resp.field3;
if (resCode !== 8694 || errCode) {
throw new Error(`delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`);
}
return { success: true };
}
}
export interface GroupAlbumMediaResult {
mediaList: Array<JsonValue & Partial<MediaInfo>>;
nextAttachInfo: string;
}
export type GroupAlbumList = NonNullable<Awaited<ReturnType<typeof getGroupAlbumList>>>['album'];
export interface GroupAlbumCommentResult {
id: string;
user: { uin: string };
content: Array<{ type: number; content: string }>;
time: string;
clientKey: string;
}

View File

@@ -0,0 +1,641 @@
import { toHexUpper } from '@snowluma/common/hex';
import { createLogger } from '@snowluma/common/logger';
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/protocol/highway/utils';
import { protobuf_encode } from '@snowluma/proton';
import type { CoreContext } from '../core-context';
import { resolveSelfUid, toInt, type MediaIndexNode } from './shared';
import { CreateGroupFolder } from '@snowluma/protocol/oidb-services/group-file/create-group-folder';
import { DeleteGroupFile } from '@snowluma/protocol/oidb-services/group-file/delete-group-file';
import { DeleteGroupFolder } from '@snowluma/protocol/oidb-services/group-file/delete-group-folder';
import { GetGroupFileCount } from '@snowluma/protocol/oidb-services/group-file/get-group-file-count';
import { GetGroupFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-file-url';
import { GetGroupPttUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-ptt-url';
import { GetGroupVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-video-url';
import { GetPrivateFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-file-url';
import { GetPrivatePttUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-ptt-url';
import { GetPrivateVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-video-url';
import { ListGroupFilesPage } from '@snowluma/protocol/oidb-services/group-file/list-group-files-page';
import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-group-file';
import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file';
import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder';
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');
// ─────────────── public result types ───────────────
export interface GroupFileInfo {
fileId: string;
fileName: string;
busId: number;
fileSize: number;
uploadTime: number;
deadTime: number;
modifyTime: number;
downloadTimes: number;
uploader: number;
uploaderName: string;
}
export interface GroupFolderInfo {
folderId: string;
folderName: string;
createTime: number;
creator: number;
creatorName: string;
totalFileCount: number;
}
export interface GroupFilesResult {
files: GroupFileInfo[];
folders: GroupFolderInfo[];
}
export interface UploadFileResult {
fileId: string | null;
fileHash?: string | null;
}
// Re-export so callers don't have to dig into apis/shared.
export type { MediaIndexNode } from './shared';
// ─────────────── file-specific helpers ───────────────
function normalizeDirectory(dir?: string): string {
if (!dir || !dir.trim()) return '/';
return dir;
}
function bytesToHexUpper(data: unknown): string {
if (!(data instanceof Uint8Array) || data.length === 0) return '';
return toHexUpper(data);
}
// Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives
// little-endian-packed (byte0 = first dotted octet) and we unpack it the
// same way. Force-unsigned the shift to keep negative ints (high bit set)
// 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;
return `${b1}.${b2}.${b3}.${b4}`;
}
function normalizeUploadFileName(name: string, fallback: string): string {
const trimmed = name.trim();
if (trimmed) return trimmed;
const safeFallback = fallback.trim();
return safeFallback || 'file.bin';
}
function md5First10MB(bytes: Uint8Array): Uint8Array {
const limit = Math.min(bytes.length, 10 * 1024 * 1024);
return computeMd5(bytes.subarray(0, limit));
}
function buildGroupFileUploadExt(
senderUin: number,
groupId: number,
fileName: string,
fileSize: number,
md5: Uint8Array,
fileId: string,
uploadKey: Uint8Array,
checkKey: Uint8Array,
uploadHost: string,
uploadPort: number,
): Uint8Array {
return protobuf_encode<FileUploadExt>({
unknown1: 100,
unknown2: 1,
entry: {
busiBuff: {
busId: 102,
senderUin: BigInt(senderUin),
receiverUin: BigInt(groupId),
groupCode: BigInt(groupId),
},
fileEntry: {
fileSize: BigInt(Math.max(0, fileSize)),
md5,
md5S2: md5,
checkKey,
fileId,
uploadKey,
},
clientInfo: {
clientType: 3,
appId: '100',
terminalType: 3,
clientVer: '1.1.1',
unknown: 4,
},
fileNameInfo: {
fileName,
},
host: {
hosts: [
{
url: {
host: uploadHost,
unknown: 1,
},
port: uploadPort,
},
],
},
},
unknown200: 0,
});
}
function buildPrivateFileUploadExt(
senderUin: number,
fileName: string,
fileSize: number,
md5: Uint8Array,
sha1: Uint8Array,
fileId: string,
uploadKey: Uint8Array,
uploadHost: string,
uploadPort: number,
): Uint8Array {
return protobuf_encode<FileUploadExt>({
unknown1: 100,
unknown2: 1,
entry: {
busiBuff: {
busId: 102,
senderUin: BigInt(senderUin),
receiverUin: 0n,
groupCode: 0n,
},
fileEntry: {
fileSize: BigInt(Math.max(0, fileSize)),
md5,
md5S2: md5,
checkKey: sha1,
fileId,
uploadKey,
},
clientInfo: {
clientType: 3,
appId: '100',
terminalType: 3,
clientVer: '1.1.1',
unknown: 4,
},
fileNameInfo: {
fileName,
},
host: {
hosts: [
{
url: {
host: uploadHost,
unknown: 1,
},
port: uploadPort,
},
],
},
},
unknown3: 0,
unknown200: 1,
});
}
export class GroupFileApi {
constructor(private readonly ctx: CoreContext) { }
// ─────────────── publish (group file → chat) ───────────────
publish(groupId: number, fileId: string): Promise<void> {
if (!fileId) throw new Error('publish requires fileId');
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
}
// ─────────────── count ───────────────
getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> {
return GetGroupFileCount.invoke(this.ctx, { groupId });
}
// ─────────────── upload (3-stage: OIDB preflight → highway → publish) ───────────────
async upload(
groupId: number,
source: string,
name = '',
folderId = '/',
uploadFile = true,
): Promise<UploadFileResult> {
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.
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
if (!loaded.bytes.length) throw new Error('group file is empty');
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
groupId,
fileName,
folderId: normalizeDirectory(folderId),
fileSize: loaded.bytes.length,
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
});
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');
// Remember the upload so a later `send_group_msg` carrying just the
// file_id can route via `publish` without forcing the OneBot caller
// to thread fileName/size/md5 separately. For groups the wire
// publish (OIDB 0x6d9_4) only needs the file_id itself, so this is
// mainly for log-line correctness; the c2c counterpart in
// `uploadPrivate` is where the cache is actually load-bearing.
this.ctx.rememberUploadedFile({
fileId,
scope: 'group',
groupId,
fileName,
fileSize: loaded.bytes.length,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
rememberedAt: Date.now(),
});
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)
|| '';
const uploadPort = toInt(upload.uploadPort);
if (!uploadHost || uploadPort <= 0) {
throw new Error('group file upload host is invalid');
}
const ext = buildGroupFileUploadExt(
senderUin,
groupId,
fileName,
loaded.bytes.length,
hashes.md5,
fileId,
upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
uploadHost,
uploadPort,
);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext);
}
// Stage 3: file is on the server, now publish it as a chat message.
//
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
// the chat shows nothing. The publish step goes via a dedicated OIDB
// call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24)
// payload — the QQ-NT server rejects that with `result=79`. Mirrors
// Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the
// caller opts out via `uploadFile=false` (treat that as "I only
// wanted the slot allocated, hold the chat post"). Routes through
// `this.publish` so tests can mock at the same Api boundary.
if (uploadFile) {
try {
await this.publish(groupId, fileId);
} catch (err) {
// The bytes are already on the server and the fileId is valid —
// 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));
}
}
return { fileId };
}
async uploadPrivate(
userId: number,
source: string,
name = '',
uploadFile = true,
): Promise<UploadFileResult> {
const bridge = this.ctx;
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
if (!loaded.bytes.length) throw new Error('private file is empty');
const targetUid = await this.ctx.resolveUserUid(userId);
let selfUid = this.ctx.identity.selfUid;
if (!selfUid) {
const selfUin = toInt(this.ctx.identity.uin);
if (selfUin > 0) {
selfUid = await this.ctx.resolveUserUid(selfUin);
}
}
if (!selfUid) throw new Error('self uid is unavailable');
const senderUin = toInt(this.ctx.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const upload = await UploadPrivateFileRequest.invoke(this.ctx, {
senderUid: selfUid,
receiverUid: targetUid,
fileName,
fileSize: loaded.bytes.length,
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
md510MCheckSum: md5First10MB(loaded.bytes),
});
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');
// Cache the metadata so a later `send_private_msg` carrying just
// `{type:'file', file_id}` can resurrect the full c2c-file packet
// (NotOnlineFile { fileSize, fileMd5, fileName, fileHash }). Without
// this the recipient sees a 0-byte file because the OneBot send path
// has no way to recover those fields from the file_id alone.
this.ctx.rememberUploadedFile({
fileId,
scope: 'private',
userId,
fileName,
fileSize: loaded.bytes.length,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
fileHash: fileHash ?? '',
rememberedAt: Date.now(),
});
if (!upload.boolFileExist && uploadFile) {
// Host selection.
//
// Current QQ-NT server rollout has stopped populating the legacy
// `uploadIp` (field 60) entirely. The host now arrives as the first
// entry of `rtpMediaPlatformUploadAddress` (field 210, repeated
// IPv4 message) — same place acidify reads it from since their
// 2026-04 protobuf refactor. Each IPv4 has paired `inIP`/`inPort`
// (LAN, same DC as the OIDB endpoint) and `outIP`/`outPort` (WAN);
// acidify uses `inIP`/`inPort` exclusively and so do we, because
// that's the address the highway PUT actually needs to reach.
//
// The 32-bit IPs are little-endian-packed (byte0 = first octet)
// per acidify's `Int.toIpString()`. Cross-checked the byte order
// by inspecting their highway flow — there's no separate htonl
// step, so the integer is already in network-octet-first order.
//
// Older server versions still populate the legacy string fields
// (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain /
// 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
? rtpInPort
: httpsHostUsed && toInt(upload.uploadHttpsPort) > 0
? toInt(upload.uploadHttpsPort)
: toInt(upload.uploadPort);
if (!uploadHost || uploadPort <= 0) {
const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress)
? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e) => ({
outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort,
iPType: e.iPType,
})))
: '[]';
log.warn(
'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s',
rtpDump,
upload.uploadIp ?? '', upload.uploadDomain ?? '',
JSON.stringify(upload.uploadIpList ?? []),
upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '',
upload.uploadLanip ?? '', upload.uploadPort ?? 0,
upload.uploadHttpsPort ?? 0,
);
throw new Error('private file upload host is invalid');
}
const ext = buildPrivateFileUploadExt(
senderUin,
fileName,
loaded.bytes.length,
hashes.md5,
hashes.sha1,
fileId,
upload.mediaPlatformUploadKey instanceof Uint8Array
? upload.mediaPlatformUploadKey
: (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)),
uploadHost,
uploadPort,
);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext);
}
// Stage 3: publish the file as a c2c chat message. C2C files use
// `RichText.notOnlineFile` (parallel to `elems`), so we go through
// the dedicated `sendC2cFile` on MessageApi instead of `sendPrivate`
// which only knows about elems[]. NapCat does the same atomic
// upload+send dance — without it the file sits on the server and
// the recipient sees nothing.
if (uploadFile) {
try {
await this.ctx.apis.message.sendC2cFile(userId, targetUid, {
fileId,
fileName,
fileSize: loaded.bytes.length,
fileMd5: hashes.md5,
fileHash: fileHash ?? '',
});
} catch (err) {
log.warn('private file uploaded (fileId=%s) but chat post failed: %s',
fileId, err instanceof Error ? err.message : String(err));
}
}
return { fileId, fileHash };
}
// ─────────────── list (paginated loop) ───────────────
async list(groupId: number, folderId = '/'): Promise<GroupFilesResult> {
const targetDirectory = normalizeDirectory(folderId);
const files: GroupFileInfo[] = [];
const folders: GroupFolderInfo[] = [];
const pageSize = 20;
let startIndex = 0;
for (let page = 0; page < 200; page++) {
const list = await ListGroupFilesPage.invoke(this.ctx, {
groupId, targetDirectory, startIndex, pageSize,
});
if (!list) break;
ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording);
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);
const cached = this.ctx.identity.findGroupMember(groupId, uploader);
files.push({
fileId: typeof file.fileId === 'string' ? file.fileId : '',
fileName: typeof file.fileName === 'string' ? file.fileName : '',
busId: toInt(file.busId),
fileSize: toInt(file.fileSize),
uploadTime: toInt(file.uploadedTime),
deadTime: toInt(file.expireTime),
modifyTime: toInt(file.modifiedTime),
downloadTimes: toInt(file.downloadedTimes),
uploader,
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);
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
|| '',
totalFileCount: toInt(folder.totalFileCount),
});
}
}
if (list.isEnd) break;
startIndex += pageSize;
}
return { files, folders };
}
// ─────────────── 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}`;
}
async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise<string> {
const bridge = this.ctx;
const selfUid = await resolveSelfUid(bridge);
void userId;
const result = await GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash });
const server = typeof result?.server === 'string' ? result.server : '';
const port = toInt(result?.port);
const url = typeof result?.url === 'string' ? result.url : '';
if (!server || !port || !url) {
throw new Error('private file url response invalid');
}
return `http://${server}:${port}${url}&isthumb=0`;
}
// ─────────────── delete / move ───────────────
delete(groupId: number, fileId: string): Promise<void> {
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 });
}
// ─────────────── folders ───────────────
createFolder(groupId: number, name: string, parentId = '/'): Promise<void> {
return CreateGroupFolder.invoke(this.ctx, {
groupId, parentId: normalizeDirectory(parentId), folderName: name,
});
}
deleteFolder(groupId: number, folderId: string): Promise<void> {
return DeleteGroupFolder.invoke(this.ctx, { groupId, folderId });
}
renameFolder(groupId: number, folderId: string, newFolderName: string): Promise<void> {
return RenameGroupFolder.invoke(this.ctx, { groupId, folderId, newFolderName });
}
// ─────────────── rich-media URL by node ───────────────
getPttUrl(groupId: number, node: MediaIndexNode): Promise<string> {
return GetGroupPttUrl.invoke(this.ctx, { groupId, node });
}
async getPrivatePttUrl(node: MediaIndexNode): Promise<string> {
const bridge = this.ctx;
const selfUid = await resolveSelfUid(bridge);
return GetPrivatePttUrl.invoke(this.ctx, { selfUid, node });
}
getVideoUrl(groupId: number, node: MediaIndexNode): Promise<string> {
return GetGroupVideoUrl.invoke(this.ctx, { groupId, node });
}
async getPrivateVideoUrl(node: MediaIndexNode): Promise<string> {
const bridge = this.ctx;
const selfUid = await resolveSelfUid(bridge);
return GetPrivateVideoUrl.invoke(this.ctx, { selfUid, node });
}
}

View File

@@ -0,0 +1,87 @@
import type { CoreContext } from '../core-context';
import { ContactsApi } from './contacts';
import { ExtrasApi } from './extras';
import { ForwardApi } from './forward';
import { FriendApi } from './friend';
import { GroupAdminApi } from './group-admin';
import { GroupAlbumApi } from './group-album';
import { GroupFileApi } from './group-file';
import { InteractionApi } from './interaction';
import { MessageApi } from './message';
import { MiscApi } from './misc';
import { ProfileApi } from './profile';
import { WebApi } from './web';
export interface ApiHub {
/** Send/recall/markRead operations across c2c + group + c2c-file. */
readonly message: MessageApi;
/** Friend / group / member roster + user-profile + group-request-list + download-rkey. */
readonly contacts: ContactsApi;
/** Group moderation: mute/kick/admin/card/name/title/leave + join-policy. */
readonly groupAdmin: GroupAdminApi;
/** Group file CRUD + private (c2c) file upload + media URL resolvers. */
readonly groupFile: GroupFileApi;
/** Group photo album: list/upload/comment/like/delete + media listing. */
readonly groupAlbum: GroupAlbumApi;
/** Interactive engagement: poke / like / reaction / essence / emoji-like-list. */
readonly interaction: InteractionApi;
/** Friend roster mutations: handleRequest / delete / setRemark. */
readonly friend: FriendApi;
/** Personal profile: status / avatar / nickname / likes / custom-faces. */
readonly profile: ProfileApi;
/** Long-message (forward / 聊天记录) upload + retrieval with NapCat piggyback. */
readonly forward: ForwardApi;
/** Odds & ends: translate / mini-app ARK / inline-keyboard / group sign. */
readonly misc: MiscApi;
/** Tier-2 napcat-parity: group todo / stranger status / AI voice. */
readonly extras: ExtrasApi;
/** Cookie-backed HTTP: essence / honor / notice / client-key / csrf-token. */
readonly web: WebApi;
}
/**
* Construct the ApiHub for a Bridge. Called once from the Bridge
* constructor. Eager construction means every Bridge instance pays
* the cost up-front (a few object allocations) — there's no lazy
* path because that would require either a thunk-based wrapper or
* runtime-mutated `apis.xxx` slots, neither of which is worth the
* complexity for ~13 small classes.
*/
export function buildApiHub(ctx: CoreContext): ApiHub {
return {
message: new MessageApi(ctx),
contacts: new ContactsApi(ctx),
groupAdmin: new GroupAdminApi(ctx),
groupFile: new GroupFileApi(ctx),
groupAlbum: new GroupAlbumApi(ctx),
interaction: new InteractionApi(ctx),
friend: new FriendApi(ctx),
profile: new ProfileApi(ctx),
forward: new ForwardApi(ctx),
misc: new MiscApi(ctx),
extras: new ExtrasApi(ctx),
web: new WebApi(ctx),
};
}
// Re-export the Api classes themselves so callers can write
// `import type { MessageApi } from '@snowluma/core/.../apis'` for
// signature use. Concrete instances always come from `bridge.apis.*`.
export { ContactsApi, type DownloadRKeyInfo } from './contacts';
export {
AiVoiceChatType, ExtrasApi, type AiVoiceCategory,
type AiVoiceItem,
type StrangerStatus
} from './extras';
export { ForwardApi } from './forward';
export { FriendApi } from './friend';
export { GroupAdminApi } from './group-admin';
export { GroupAlbumApi } from './group-album';
export { GroupFileApi } from './group-file';
export { InteractionApi } from './interaction';
export { MessageApi, type SendMessageReceipt } from './message';
export { MiscApi } from './misc';
export { ProfileApi } from './profile';
export { type MediaIndexNode } from './shared';
export { WebApi, type ClientKeyInfo, type WebHonorInfo, type WebNoticeInfo } from './web';

View File

@@ -0,0 +1,68 @@
// InteractionApi — facade over interactive-engagement OIDB cmds
// (poke / like / reaction / essence / emoji-like-list). Every method
// is a one-line forwarder to a self-contained namespace under
// @snowluma/protocol/oidb-services. The facade exists purely to keep
// the `bridge.apis.interaction.X(...)` ergonomic call style; all wire
// work (envelope build / encode / send / decode) lives in the
// namespace files.
import { SendLike } from '@snowluma/protocol/oidb-services/interaction/send-like';
import { SendPoke } from '@snowluma/protocol/oidb-services/interaction/send-poke';
import { SetEssence } from '@snowluma/protocol/oidb-services/interaction/set-essence';
import { FetchReactionSummary } from '@snowluma/protocol/oidb-services/reaction/fetch-reaction-summary';
import { GetEmojiLikes } from '@snowluma/protocol/oidb-services/reaction/get-emoji-likes';
import { SetReaction } from '@snowluma/protocol/oidb-services/reaction/set-reaction';
import type { CoreContext } from '../core-context';
export class InteractionApi {
constructor(private readonly ctx: CoreContext) { }
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin });
}
sendLike(userId: number, count: number): Promise<void> {
return SendLike.invoke(this.ctx, { userId, count });
}
setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
return SetReaction.invoke(this.ctx, { groupId, sequence, code, isSet });
}
setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
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.
*/
async getEmojiLikes(
groupId: number,
sequence: number,
emojiId: string,
emojiType = 1,
count = 10,
cookie = '',
): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> {
try {
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.
*/
fetchReactionSummary(
groupId: number,
sequence: number,
): Promise<Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }>> {
return FetchReactionSummary.invoke(this.ctx, { groupId, sequence });
}
}

View File

@@ -0,0 +1,337 @@
import type {
SendMessageRequest,
SendMessageResponse,
} from '@snowluma/proto-defs/action';
import type { FileExtra } from '@snowluma/proto-defs/message';
import type {
C2CRecallRequest,
GroupRecallRequest,
SsoReadedReportReq,
} from '@snowluma/proto-defs/oidb-actions/base';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { MessageElement } from '@snowluma/protocol/events';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { CoreContext } from '../core-context';
/**
* Receipt returned by every typed `send*Message` call. The OneBot
* adapter feeds these into its `MessageStore` so later `recall_msg`
* actions can resolve the wire-level coordinates (sequence + random)
* from the `message_id` it previously emitted.
*/
export interface SendMessageReceipt {
messageId: number;
sequence: number;
clientSequence: number;
random: number;
timestamp: number;
}
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
export class MessageApi {
constructor(private readonly ctx: CoreContext) { }
/**
* Send a message to a QQ group.
*
* Wraps `MessageSvc.PbSendMsg` with `routingHead.grp.groupCode`.
* Media elements (image / record / video) trigger highway uploads
* inside `buildSendElems` — see `element-builder.ts`.
*
* Returns a `SendMessageReceipt` carrying the assigned messageId,
* group sequence, and timestamps; callers cache this for later
* `recall` / reply lookups.
*/
async sendGroup(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
const protoElems = await buildSendElems(elements, { bridge: this.ctx, groupId });
const random = this.ctx.nextMessageRandom();
const request = protobuf_encode<SendMessageRequest>({
routingHead: {
grp: { groupCode: BigInt(groupId) },
},
contentHead: {
type: 1,
},
messageBody: {
richText: {
elems: protoElems,
},
},
clientSequence: 0,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
multiSendSeq: 0,
});
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`);
}
const response = protobuf_decode<SendMessageResponse>(result.responseData);
if (!response) throw new Error('failed to decode SendMessageResponse');
if (response.result != null && response.result !== 0) {
throw new Error(`send group message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
}
const seq = response.groupSequence ?? 0;
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return { messageId, sequence: seq, clientSequence: 0, random, timestamp };
}
/**
* Send a c2c (private) message.
*
* Resolves the recipient's UID only when the message carries media
* — text-only messages skip the lookup. Routes through `c2c.uin`
* (and optionally `c2c.uid` for the media case).
*/
async sendPrivate(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
let userUid = '';
const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video');
if (hasMedia) {
userUid = await this.ctx.resolveUserUid(userUin);
}
const protoElems = await buildSendElems(elements, { bridge: this.ctx, userUid });
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
const request = protobuf_encode<SendMessageRequest>({
routingHead: {
c2c: {
uin: userUin,
...(userUid ? { uid: userUid } : {}),
},
},
contentHead: {
type: 1,
subType: 0,
c2cCmd: 11,
},
messageBody: {
richText: {
elems: protoElems,
},
},
clientSequence: clientSeq,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
ctrl: {
msgFlag: Math.floor(Date.now() / 1000),
},
multiSendSeq: 0,
});
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`);
}
const response = protobuf_decode<SendMessageResponse>(result.responseData);
if (!response) throw new Error('failed to decode SendMessageResponse');
if (response.result != null && response.result !== 0) {
throw new Error(`send private message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
}
const seq = response.privateSequence ?? 0;
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
}
/**
* Send a c2c file as a chat message.
*
* The wire shape isn't the same as a regular c2c message — the c2c
* file path uses three slots that differ from a normal text/image
* send (verified against `dev/Lagrange.Core/.../MessagePacker.cs:
* BuildPacketBase` + `FileEntity.PackMessageContent`):
*
* 1. `routingHead.trans0x211 { ccCmd: 4, uid: peer }` instead of
* `routingHead.c2c { uin, uid }`. The server rejects c2c file
* messages routed through the regular c2c slot.
* 2. `messageBody.msgContent` carries the serialised
* `FileExtra { file: NotOnlineFile }` bytes. NOT
* `richText.notOnlineFile` — the receiver doesn't read that
* slot for file metadata.
* 3. `contentHead.c2cCmd` left at 0 (Lagrange's default). The
* previous `c2cCmd: 11` was a stale go-cqhttp value the QQ-NT
* server doesn't recognise.
*
* NotOnlineFile carries three required-on-send fields the receiver
* itself ignores but the server's intake validator checks:
* - `subcmd: 1` — c2c file send command code
* - `dangerEvel: 0` — virus-scan severity, always 0 client-side
* - `expireTime` — 7 days from now (Lagrange convention)
*/
async sendC2cFile(
userUin: number,
userUid: string,
info: { fileId: string; fileName: string; fileSize: number; fileMd5: Uint8Array; fileHash?: string },
): Promise<SendMessageReceipt> {
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
const nowSec = Math.floor(Date.now() / 1000);
const sevenDaysSec = 7 * 24 * 60 * 60;
const fileExtraBytes = protobuf_encode<FileExtra>({
file: {
fileType: 0,
fileUuid: info.fileId,
fileMd5: info.fileMd5,
fileName: info.fileName,
fileSize: BigInt(info.fileSize),
subcmd: 1,
dangerEvel: 0,
expireTime: nowSec + sevenDaysSec,
fileHash: info.fileHash ?? '',
},
});
const request = protobuf_encode<SendMessageRequest>({
routingHead: {
trans0x211: { ccCmd: 4, uid: userUid },
},
contentHead: {
type: 1,
subType: 0,
},
messageBody: {
msgContent: fileExtraBytes,
},
clientSequence: clientSeq,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
ctrl: { msgFlag: nowSec },
multiSendSeq: 0,
});
// `userUin` is part of the public contract (the OneBot layer
// threads it through for symmetry with `sendPrivate`) but the
// wire shape only needs the uid. Silence the unused-parameter
// lint without changing the signature.
void userUin;
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send c2c file message failed: ${result.errorMessage || 'no response'}`);
}
const response = protobuf_decode<SendMessageResponse>(result.responseData);
if (!response) throw new Error('failed to decode SendMessageResponse');
if (response.result != null && response.result !== 0) {
throw new Error(`send c2c file message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
}
const seq = response.privateSequence ?? 0;
const messageId = (random & 0x7FFFFFFF) || seq;
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
}
/**
* Recall (revoke) a group message by sequence number. Server-side
* the message ages out after the standard 2-minute window unless
* the user is an admin/owner.
*/
async recallGroup(groupId: number, sequence: number): Promise<void> {
const request = protobuf_encode<GroupRecallRequest>({
type: 1,
groupUin: groupId,
info: { sequence, random: 0, field3: 0 },
settings: { field1: 0 },
});
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg', request);
if (!result.success) throw new Error(result.errorMessage || 'recall group message failed');
}
/**
* Recall a c2c (private) message. Needs more positional info than
* the group variant because c2c messages are identified by the
* `(clientSequence, msgSequence, random, timestamp)` tuple rather
* than a single group-side sequence.
*/
async recallPrivate(
userUin: number,
clientSeq: number,
msgSeq: number,
random: number,
timestamp: number,
): Promise<void> {
const targetUid = await this.ctx.resolveUserUid(userUin);
const request = protobuf_encode<C2CRecallRequest>({
type: 1,
targetUid,
info: {
clientSequence: clientSeq,
random,
messageId: BigInt((0x01000000 * 0x100000000) + random),
timestamp,
field5: 0,
messageSequence: msgSeq,
},
settings: { field1: false, field2: false },
field6: false,
});
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', request);
if (!result.success) throw new Error(result.errorMessage || 'recall private message failed');
}
/**
* Push a group read-report (`trpc.msg.msg_svc.MsgService.SsoReadedReport`)
* advancing the bot's last-read marker to `sequence`. Mirrors the QQ
* NT client's own "scrolled to bottom" behaviour so subsequent
* sync packets don't replay messages we've already processed.
*/
async markGroupRead(groupId: number, sequence: number): Promise<void> {
const request = protobuf_encode<SsoReadedReportReq>({
groupList: [
{
groupUin: BigInt(groupId),
lastReadSeq: BigInt(sequence),
},
],
});
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
if (!result.success) {
throw new Error(result.errorMessage || 'mark group message read failed');
}
}
/**
* Push a c2c read-report. Same wire-cmd as the group variant but
* keyed by friend uid (resolved from uin via IdentityService).
* `lastReadTime` defaults to "now" — matches the QQ NT client
* which also uses wall-clock seconds rather than the read-message
* timestamp.
*/
async markPrivateRead(userId: number, sequence: number): Promise<void> {
const uid = await this.ctx.resolveUserUid(userId);
const request = protobuf_encode<SsoReadedReportReq>({
c2cList: [
{
uid,
lastReadTime: BigInt(Math.floor(Date.now() / 1000)),
lastReadSeq: BigInt(sequence),
},
],
});
const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
if (!result.success) {
throw new Error(result.errorMessage || 'mark private message read failed');
}
}
}

View File

@@ -0,0 +1,78 @@
import type { JsonObject, JsonValue } from '@snowluma/common/json';
import type {
MiniAppShareReq,
MiniAppShareResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
// Migrated OIDB cmds — facade methods are one-line forwarders.
import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc/click-inline-keyboard-button';
import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign';
import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh';
import type { CoreContext } from '../core-context';
export class MiscApi {
constructor(private readonly ctx: CoreContext) { }
translateEn2Zh(words: string[]): Promise<string[]> {
return TranslateEnToZh.invoke(this.ctx, { words });
}
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';
if (type === 'weibo') {
appid = '1109224783';
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`);
}
const request = protobuf_encode<MiniAppShareReq>({
sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A',
body: { appid, title, desc, picUrl, jumpUrl, iconUrl },
});
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');
}
const decoded = protobuf_decode<MiniAppShareResp>(result.responseData);
const jsonStr = decoded?.body?.jsonStr;
if (!jsonStr) {
throw new Error('mini app share json empty');
}
const parsed = JSON.parse(jsonStr) as Record<string, JsonObject | string | number | boolean | null>;
return {
data: {
ver: parsed.ver,
prompt: parsed.prompt,
config: parsed.config,
app: parsed.appName,
view: parsed.appView,
meta: parsed.metaData,
miniappShareOrigin: 3,
miniappOpenRefer: '10002',
},
};
}
clickInlineKeyboardButton(
groupId: number,
botAppid: number,
buttonId: string,
callbackData: string,
msgSeq: number,
): Promise<JsonValue> {
return ClickInlineKeyboardButton.invoke(this.ctx, { groupId, botAppid, buttonId, callbackData, msgSeq });
}
sendGroupSign(groupId: number): Promise<void> {
return SendGroupSign.invoke(this.ctx, { groupId });
}
}

View File

@@ -0,0 +1,147 @@
import type {
FaceroamOpReq,
FaceroamOpResp,
GroupAvatarExtra,
SetStatusReq,
SetStatusResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { 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 { 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';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { CoreContext } from '../core-context';
export class ProfileApi {
constructor(private readonly ctx: CoreContext) { }
// ─────────────── status / profile setters ───────────────
async setOnlineStatus(status: number, extStatus = 0, batteryStatus = 100): Promise<void> {
await this.dispatchSetStatus({ status, extStatus, batteryStatus });
}
/**
* DIY (custom) online status. napcat fixes status=10 / extStatus=2000
* — the values QQ associates with "I have a custom status string" —
* and threads the faceId / wording / faceType through the customExt
* sub-message of the same SetStatus wire call.
*/
async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise<void> {
await this.dispatchSetStatus({
status: 10,
extStatus: 2000,
batteryStatus: 0,
customExt: { faceId, text: wording, faceType },
});
}
private async dispatchSetStatus(value: {
status: number;
extStatus: number;
batteryStatus: number;
customExt?: { faceId: number; text: string; faceType: number };
}): Promise<void> {
const request = protobuf_encode<SetStatusReq>(value);
const result = await this.ctx.sendRawPacket(
'trpc.qq_new_tech.status_svc.StatusService.SetStatus',
request,
);
if (!result.success) {
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
}
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)');
}
if (resp.errCode !== undefined && resp.errCode !== 0) {
throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`);
}
}
}
setProfile(nickname?: string, personalNote?: string): Promise<void> {
return SetProfile.invoke(this.ctx, { nickname, personalNote });
}
setSelfLongNick(longNick: string): Promise<void> {
return SetSelfLongNick.invoke(this.ctx, { longNick });
}
setInputStatus(userId: number, eventType: number): Promise<void> {
return SetInputStatus.invoke(this.ctx, { userId, eventType });
}
async setAvatar(source: string): Promise<void> {
const bridge = this.ctx;
const loaded = await loadBinarySource(source, 'avatar');
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, loaded.bytes, hashes.md5, new Uint8Array(0));
}
/**
* Set group avatar. Mirrors Lagrange.Core's GroupSetAvatar:
* - same highway HTTP upload as personal avatar
* - cmdId 3000 (instead of 90)
* - GroupAvatarExtra proto carried as the `extend` blob, with the
* four protocol-prescribed constants (type=101, field5=3, field6=1,
* field3.field1=1) and the target groupUin.
*
* Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar.
*/
async setGroupAvatar(groupId: number, source: string): Promise<void> {
const bridge = this.ctx;
const loaded = await loadBinarySource(source, 'group-avatar');
if (!loaded.bytes.length) throw new Error('group avatar file is empty');
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
const extra = protobuf_encode<GroupAvatarExtra>({
type: 101,
groupUin: groupId,
field3: { field1: 1 },
field5: 3,
field6: 1,
});
await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra);
}
// ─────────────── queries on me / my contacts ───────────────
getLike(userId?: number, start = 0, limit = 10): Promise<LikeInfo> {
return GetLike.invoke(this.ctx, { userId, start, limit });
}
getUnidirectionalFriendList(): Promise<UnidirectionalFriendEntry[]> {
return GetUnidirectionalFriendList.invoke(this.ctx);
}
async fetchCustomFace(count = 10): Promise<string[]> {
const req = {
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
uin: BigInt(this.ctx.identity.uin),
field3: 1,
field6: 1,
};
const request = protobuf_encode<FaceroamOpReq>(req);
const result = await this.ctx.sendRawPacket('Faceroam.OpReq', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'fetch custom face failed');
}
const resp = protobuf_decode<FaceroamOpResp>(result.responseData);
if (!resp || resp.retCode !== 0) {
throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`);
}
const faceIds = resp.item?.faceIds || [];
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${id}/0`);
}
}

View File

@@ -0,0 +1,74 @@
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
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}`);
}
/**
* Look up the bot's own UID. Cached on Identity once warmup populates
* `selfProfile`; forward/profile actions need this fast path before
* warmup completes.
*/
export async function resolveSelfUid(bridge: BridgeContext): Promise<string> {
let selfUid = bridge.identity.selfUid;
if (selfUid) return selfUid;
const selfUin = toInt(bridge.identity.uin);
if (selfUin <= 0) {
throw new Error('self uid is unavailable');
}
selfUid = await bridge.resolveUserUid(selfUin);
return selfUid;
}
/**
* Index describing a server-side rich-media object (image / video /
* voice). Returned by message parsers, consumed by the media-URL
* fetchers in group-file.ts.
*/
export interface MediaIndexNode {
info?: {
fileSize?: number;
fileHash?: string;
fileSha1?: string;
fileName?: string;
width?: number;
height?: number;
time?: number;
original?: number;
type?: {
type?: number;
picFormat?: number;
videoFormat?: number;
voiceFormat?: number;
};
};
fileUuid?: string;
storeId?: number;
uploadTime?: number;
ttl?: number;
subType?: number;
}

View File

@@ -0,0 +1,335 @@
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
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 { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/protocol/web/group-honor';
import {
deleteGroupNotice as deleteGroupNoticeHttp,
getGroupNoticeWebAPI,
setGroupNoticeWebAPI,
uploadGroupNoticeImage,
type SetNoticeRetSuccess,
} from '@snowluma/protocol/web/group-notice';
import { RequestUtil } from '@snowluma/protocol/web/request-util';
import type { CoreContext } from '../core-context';
export type ClientKeyInfo = NamespaceClientKeyInfo;
export interface WebHonorInfo {
[key: string]: import('@snowluma/common/json').JsonValue;
group_id: number;
current_talkative: WebHonorItem | null;
talkative_list: WebHonorItem[];
performer_list: WebHonorItem[];
legend_list: WebHonorItem[];
emotion_list: WebHonorItem[];
strong_newbie_list: WebHonorItem[];
}
export interface WebNoticeInfo {
[key: string]: import('@snowluma/common/json').JsonValue;
notice_id: string;
sender_id: number;
publish_time: number;
message: {
text: string;
image: Array<{ id: string; height: number; width: number }>;
images: Array<{ id: string; height: number; width: number }>;
};
settings: import('@snowluma/common/json').JsonValue;
read_num: number;
}
// ─────────────── private helpers (cookie acquisition) ───────────────
function forceFetchClientKeyInner(bridge: BridgeContext): Promise<ClientKeyInfo> {
return ForceFetchClientKey.invoke(bridge);
}
function getPSkey(bridge: BridgeContext, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
return GetPskey.invoke(bridge, { domainList });
}
async function getCookies(bridge: BridgeContext, domain: string): Promise<Record<string, string>> {
const ClientKeyData = await forceFetchClientKeyInner(bridge);
// 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 data = await RequestUtil.HttpsGetCookies(requestUrl);
if (!data['p_skey'] || data['p_skey'].length === 0) {
// ptlogin2 sometimes omits p_skey; fall back to OIDB getPSkey
// for the same domain. Errors are swallowed so the caller can
// still proceed with whatever cookies it did get.
try {
const pskeyData = await getPSkey(bridge, [domain]);
const pskey = pskeyData.domainPskeyMap.get(domain);
if (pskey) {
data['p_skey'] = pskey;
}
} catch {
return data;
}
}
return data;
}
async function getSKey(bridge: BridgeContext): Promise<string> {
const ClientKeyData = await forceFetchClientKeyInner(bridge);
if (!ClientKeyData.clientKey) {
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 cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
const skey = cookies['skey'];
if (!skey) {
throw new Error('SKey is Empty');
}
return skey;
}
/**
* Standard QQ bkn hash (also known as token / csrf_token) derived from
* skey or p_skey. djb2 hash truncated to 31 bits.
*/
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;
}
export class WebApi {
constructor(private readonly ctx: CoreContext) { }
// ─────────────── cookie / token primitives ───────────────
async forceFetchClientKey(): Promise<ClientKeyInfo> {
return forceFetchClientKeyInner(this.ctx);
}
/** Fetch the cookie jar for a `qq.com` subdomain. Used by GroupAlbumApi
* (qzone.qq.com) and by every other web helper here. */
async getCookies(domain: string): Promise<Record<string, string>> {
return getCookies(this.ctx, domain);
}
/** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */
async getCookiesStr(domain: string): Promise<string> {
const cookieObject = await getCookies(this.ctx, domain);
return Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
}
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
async getCsrfToken(): Promise<number> {
const skey = await getSKey(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 }> {
const cookieObject = await getCookies(this.ctx, domain);
const cookiesStr = Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
const token = skey ? getBknFromSKey(skey) : 0;
return {
cookies: cookiesStr,
token,
csrf_token: token,
};
}
// ─────────────── group essence ───────────────
/** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */
async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise<GroupEssenceMsgRet> {
const bridge = this.ctx;
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit);
return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } };
}
/** Walks every page and returns the concatenated result. */
async getEssenceAll(groupId: number): Promise<GroupEssenceMsgRet[]> {
const bridge = this.ctx;
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await getGroupEssenceMsgAll(cookieObject, groupCode);
}
// ─────────────── group honor ───────────────
async getHonorInfo(groupId: number, type: WebHonorType | string): Promise<WebHonorInfo> {
const bridge = this.ctx;
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const honorInfo: WebHonorInfo = {
group_id: groupId,
current_talkative: null,
talkative_list: [],
performer_list: [],
legend_list: [],
emotion_list: [],
strong_newbie_list: [],
};
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;
}
}
if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) {
honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2);
}
if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) {
honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3);
}
if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) {
honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6);
}
return honorInfo;
}
// ─────────────── group notice ───────────────
async sendNotice(
groupId: number,
content: string,
options?: {
image?: string; // local path, http URL, or undefined (text-only)
pinned?: number;
type?: number;
confirm_required?: number;
},
): Promise<SetNoticeRetSuccess> {
const bridge = this.ctx;
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
let picId = '';
let imgWidth = 540;
let imgHeight = 300;
if (options?.image) {
let imageBuffer: Buffer;
if (options.image.startsWith('http://') || options.image.startsWith('https://')) {
const response = await fetch(options.image);
if (!response.ok) throw new Error(`Failed to download image: ${response.status}`);
imageBuffer = Buffer.from(await response.arrayBuffer());
} else {
const { readFileSync } = await import('fs');
imageBuffer = readFileSync(options.image);
}
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
if (picInfo) {
picId = picInfo.id;
imgWidth = picInfo.width;
imgHeight = picInfo.height;
}
}
const ret = await setGroupNoticeWebAPI(
cookieObject,
groupCode,
content,
options?.pinned ?? 0,
options?.type ?? 1,
1,
1,
options?.confirm_required ?? 1,
picId,
imgWidth,
imgHeight,
);
if (!ret || ret.ec !== 0) {
throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`);
}
return ret;
}
async getNotice(groupId: number): Promise<WebNoticeInfo[]> {
const bridge = this.ctx;
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
if (!ret) {
throw new Error('获取公告失败');
}
const retNotices: WebNoticeInfo[] = [];
if (ret.feeds) {
for (const key in ret.feeds) {
const feed = ret.feeds[key];
if (!feed) continue;
const image = feed.msg?.pics?.map((pic) => ({
id: pic.id,
height: pic.h,
width: pic.w,
})) || [];
retNotices.push({
notice_id: feed.fid,
sender_id: feed.u,
publish_time: feed.pubt,
message: {
text: feed.msg?.text || '',
image,
images: image,
},
settings: feed.settings,
read_num: feed.read_num,
});
}
}
return retNotices;
}
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
const bridge = this.ctx;
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await deleteGroupNoticeHttp(cookieObject, groupCode, fid);
}
}

View File

@@ -0,0 +1,26 @@
import type { BridgeContext as ProtocolBridgeContext } from '@snowluma/protocol/bridge-context';
import type { ApiHub } from './apis';
/**
* `CoreContext` — the internal context that Api wrappers (`apis/*`)
* consume. Only used inside `@snowluma/core`; OneBot and other inbound
* adapters consume the narrower `CoreCtx` projection instead.
*
* It extends the protocol-layer `BridgeContext` with one extra slot:
* `apis: ApiHub`. The protocol layer can't mention `ApiHub` because
* the apis live in @snowluma/core, so the shared surface is layered:
*
* - `@snowluma/protocol/bridge-context.BridgeContext` — identity,
* events, raw packet I/O, sequences, file cache. Consumed by
* `element-builder`, highway uploaders, msg-push decoders.
* - `@snowluma/core/core-context.CoreContext` — adds `apis`.
* Consumed by everything inside `apis/*` and by tests that
* stub the surface for OneBot-side unit tests.
*
* The concrete `Core` class implements this extended interface.
*/
export interface CoreContext extends ProtocolBridgeContext {
readonly apis: ApiHub;
}
export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context';

View File

@@ -0,0 +1,34 @@
import type { ChannelKind } from '@snowluma/channel';
import type { CoreContext } from './core-context';
/**
* `CoreCtx` — the public surface every QQ account exposes to the rest
* of the system (OneBot, future MCP clients, WebUI status panels). It
* is the structural projection of a `Core` instance that consumers
* receive via `Hub.events.on('core-online', ...)`.
*
* Reading this type is the right starting point when wiring a new
* consumer:
*
* - `identity` / `events` / `apis` / sequence helpers / file cache
* are inherited from `CoreContext`.
* - `kind` / `id` / `uin` mirror the underlying channel's identity
* so consumers can branch on transport kind when they really need
* to (e.g. WebUI diagnostics) without `instanceof` checks.
* - `dispose()` is the lifecycle hook; `Hub` calls it when the
* underlying channel disappears.
*
* Day-to-day consumers should stay kind-agnostic — that's the entire
* point of the abstraction.
*/
export interface CoreCtx extends CoreContext {
/** Transport family backing this account. */
readonly kind: ChannelKind;
/** Stable, unique-per-account id (mirrors the channel's id). */
readonly id: string;
/** QQ number this account represents. Mirrors `identity.uin`. */
readonly uin: string;
/** Release identity DB handles, event subscribers, and any
* account-level resources. Idempotent. */
dispose(): void;
}

181
packages/core/src/core.ts Normal file
View File

@@ -0,0 +1,181 @@
import type { ChannelCtx, ChannelKind } from '@snowluma/channel';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { UploadedFileMeta } from '@snowluma/protocol/bridge-context';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push';
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
import { buildApiHub, type ApiHub } from './apis';
import type { CoreCtx } from './core-ctx';
/**
* `Core` — the QQ-account-level business object that sits on top of a
* `Channel` transport (consumed indirectly via a `ChannelCtx`
* capability POJO). Owns everything OneBot, the apis, and the msg-push
* pipeline care about:
*
* - `identity` (per-uin SQLite-backed roster + uid↔uin index),
* - the typed `BridgeEventBus` (subscribe to per-account events by kind),
* - the `ApiHub` (typed wrappers around `sendRawPacket`),
* - the `IncomingPacketPipeline` (cmd → decoder → emit on bus),
* - the uploaded-file cache (shared between `upload_*_file` and
* `send_msg`),
* - the monotonic `clientSequence` / `messageRandom` counters.
*
* The transport is opaque: `Core` only calls `channelCtx.sendRawPacket`
* and subscribes via `channelCtx.onPacket` so all incoming packets flow
* into its pipeline. Swap the transport (hook → socket) and everything
* above keeps working unchanged because `Core` never holds the `Channel`
* itself — only the capability POJO.
*
* Lifecycle is managed by `Hub`: the hub registers `ChannelAdapter`s,
* builds a `ChannelCtx` from each freshly-available channel, materialises
* a `Core` on the way up, and calls `dispose()` on the way down. OneBot
* consumers see `CoreCtx` (the structural projection); never `Core`
* itself.
*/
export class Core implements CoreCtx {
readonly kind: ChannelKind;
readonly id: string;
readonly uin: string;
readonly identity: IdentityService;
readonly events = new BridgeEventBus();
readonly apis: ApiHub;
private readonly channelCtx_: ChannelCtx;
private readonly pipeline_: IncomingPacketPipeline;
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
private readonly uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
private disposed_ = false;
constructor(channelCtx: ChannelCtx, identity: IdentityService = IdentityService.openForUin(channelCtx.uin)) {
this.channelCtx_ = channelCtx;
this.kind = channelCtx.kind;
this.id = `${channelCtx.kind}:${channelCtx.uin}`;
this.uin = channelCtx.uin;
this.identity = identity;
this.apis = buildApiHub(this);
this.identity.setFetcher({
fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin),
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;
}
},
resolveGroupJoinRequest: async (groupId, uid, subType) => {
try {
const requests = await this.apis.contacts.fetchGroupRequests();
const match = requests.find(r => {
if (r.groupId !== groupId) return false;
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
});
if (!match) return null;
return { comment: match.comment, sequence: match.sequence };
} catch {
return null;
}
},
});
this.pipeline_.registerCmd(MSG_PUSH_CMD, parseMsgPush);
// Subscribe to inbound packets from the channel. The underlying
// `Channel` only supports a single subscriber (us); the
// `ChannelAdapter` pumps packets through `channel.deliverPacket`,
// which `Hub` wires into us via `channelCtx.onPacket`.
channelCtx.onPacket((pkt: PacketInfo) => this.pipeline_.process(pkt));
}
// ─── CoreCtx plumbing ────────────────────────────────────────────
dispose(): void {
if (this.disposed_) return;
this.disposed_ = true;
this.channelCtx_.onPacket(null);
this.identity.close();
this.events.clear();
}
get isDisposed(): boolean { return this.disposed_; }
// ─── Transport (proxied to the underlying Bridge) ──────────────
async sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult> {
return this.channelCtx_.sendRawPacket(serviceCmd, body, timeoutMs);
}
// ─── Pipeline registration (used by tests + extra cmd modules) ─
registerCmd(cmd: string, parser: CmdParser): void {
this.pipeline_.registerCmd(cmd, parser);
}
handlesCmd(cmd: string): boolean {
return this.pipeline_.handlesCmd(cmd);
}
// ─── Send-side protocol helpers (shared sequence generators) ───
nextClientSequence(): number {
return ++this.clientSeq_;
}
nextMessageRandom(): number {
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
return this.msgRandom_ & 0x7FFFFFFF;
}
// ─── Uploaded-file cache ───────────────────────────────────────
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) return;
if (this.uploadedFileMeta_.size >= Core.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);
}
this.uploadedFileMeta_.set(meta.fileId, meta);
}
recallUploadedFile(fileId: string): UploadedFileMeta | undefined {
if (!fileId) return undefined;
return this.uploadedFileMeta_.get(fileId);
}
// ─── Identity convenience ──────────────────────────────────────
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return this.identity.resolveUid(uin, groupId);
}
// ─── Internal helpers ──────────────────────────────────────────
private async refreshMemberCache(
groupId: number,
refreshGroupList: boolean,
forceMemberList: boolean,
): Promise<boolean> {
if (refreshGroupList) {
try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ }
}
if (!this.identity.findGroup(groupId)) return false;
await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
}
}

View File

@@ -1 +1,2 @@
declare const __BUILD_WEBUI__: boolean;
declare const __APP_VERSION__: string;

238
packages/core/src/hub.ts Normal file
View File

@@ -0,0 +1,238 @@
import {
makeChannelCtx,
type Channel,
type ChannelAdapter,
type ChannelAdapterHost,
type ChannelKind,
} from '@snowluma/channel';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { Core } from './core';
import type { CoreCtx } from './core-ctx';
const log = createLogger('Hub');
export type HubEventMap = {
'core-online': CoreCtx;
'core-offline': { uin: string };
};
export type HubEventHandler<K extends keyof HubEventMap> = (payload: HubEventMap[K]) => void;
export type HubEventDisposer = () => void;
class HubEvents {
private readonly listeners_ = new Map<keyof HubEventMap, Set<(p: unknown) => void>>();
on<K extends keyof HubEventMap>(event: K, handler: HubEventHandler<K>): HubEventDisposer {
let set = this.listeners_.get(event);
if (!set) {
set = new Set();
this.listeners_.set(event, set);
}
const wrapped = handler as (p: unknown) => void;
set.add(wrapped);
return () => set!.delete(wrapped);
}
emit<K extends keyof HubEventMap>(event: K, payload: HubEventMap[K]): void {
const set = this.listeners_.get(event);
if (!set || set.size === 0) return;
for (const handler of [...set]) {
try {
(handler as HubEventHandler<K>)(payload);
} catch (err) {
log.warn('hub listener (%s) threw: %s', event, err instanceof Error ? err.message : String(err));
}
}
}
clear(): void {
this.listeners_.clear();
}
}
export class Hub {
private readonly adapters_ = new Map<ChannelKind, ChannelAdapter>();
private readonly channelsById_ = new Map<string, Channel>();
private readonly channelsByUin_ = new Map<string, Channel>();
// ─── core pool (was AccountManager) ──────────────────────────────
private readonly cores_ = new Map<string, Core>();
// ─── lifecycle event bus ──────────────────────────────────────────
readonly events = new HubEvents();
private started_ = false;
private disposed_ = false;
// ─── adapter registration ────────────────────────────────────────
/**
* Register a channel adapter. Must be called BEFORE `start()`; the
* hub enforces at most one adapter per `kind`.
*/
registerAdapter(adapter: ChannelAdapter): void {
if (this.started_) {
throw new Error('Hub: cannot register adapters after start()');
}
if (this.adapters_.has(adapter.kind)) {
throw new Error(`Hub: adapter of kind '${adapter.kind}' is already registered`);
}
this.adapters_.set(adapter.kind, adapter);
}
getAdapter(kind: ChannelKind): ChannelAdapter | null {
return this.adapters_.get(kind) ?? null;
}
// ─── lifecycle ───────────────────────────────────────────────────
/** Start every registered adapter. Idempotent. */
async start(): Promise<void> {
if (this.started_) return;
this.started_ = true;
for (const [kind, adapter] of this.adapters_) {
const host = this.makeHost(kind);
try {
await adapter.start(host);
} catch (err) {
log.warn('adapter [%s] failed to start: %s', kind,
err instanceof Error ? (err.stack ?? err.message) : String(err));
}
}
}
/** Dispose every adapter (which removes their channels via the
* host), then dispose any cores/channels that somehow remain.
* Idempotent. */
async dispose(): Promise<void> {
if (this.disposed_) return;
this.disposed_ = true;
for (const [kind, adapter] of this.adapters_) {
try {
await adapter.dispose();
} catch (err) {
log.warn('adapter [%s] failed to dispose: %s', kind,
err instanceof Error ? err.message : String(err));
}
}
for (const core of this.cores_.values()) {
try { core.dispose(); } catch { /* ignore */ }
}
for (const channel of this.channelsById_.values()) {
try { channel.dispose(); } catch { /* ignore */ }
}
this.cores_.clear();
this.channelsById_.clear();
this.channelsByUin_.clear();
this.events.clear();
}
// ─── queries ─────────────────────────────────────────────────────
/** The `Core` (full business object) for a UIN, or `null` if no
* account is online. Internal-ish — callers typically work with
* `CoreCtx` received from the `'core-online'` event instead. */
getCore(uin: string): Core | null {
return this.cores_.get(uin) ?? null;
}
getCores(): readonly Core[] {
return [...this.cores_.values()];
}
/** Channel for a UIN, or `null` if the UIN is offline. */
getChannel(uin: string): Channel | null {
return this.channelsByUin_.get(uin) ?? null;
}
getOnlineUins(): readonly string[] {
return [...this.channelsByUin_.keys()];
}
// ─── ChannelAdapterHost implementation (per-adapter) ─────────────
private makeHost(kind: ChannelKind): ChannelAdapterHost {
const adapterLog = log.child({ adapter: kind });
return {
log: adapterLog,
addChannel: (channel) => this.addChannel(channel, adapterLog),
removeChannel: (id) => this.removeChannel(id, adapterLog),
};
}
private addChannel(channel: Channel, adapterLog: Logger): void {
if (this.disposed_) return;
if (this.channelsById_.has(channel.id)) {
adapterLog.warn('addChannel: id=%s already registered, ignoring', channel.id);
return;
}
const existing = this.channelsByUin_.get(channel.uin);
if (existing) {
adapterLog.warn('addChannel: UIN=%s already has channel=%s, replacing with %s',
channel.uin, existing.id, channel.id);
this.channelsById_.delete(existing.id);
this.channelsById_.set(channel.id, channel);
this.channelsByUin_.set(channel.uin, channel);
this.bringCoreOffline(channel.uin);
this.bringCoreOnline(channel.uin, channel);
try { existing.dispose(); } catch (err) {
adapterLog.debug('channel.dispose() threw: %s',
err instanceof Error ? err.message : String(err));
}
return;
}
this.channelsById_.set(channel.id, channel);
this.channelsByUin_.set(channel.uin, channel);
log.debug('account online: UIN=%s via %s', channel.uin, channel.id);
this.bringCoreOnline(channel.uin, channel);
}
private removeChannel(id: string, adapterLog: Logger): void {
const channel = this.channelsById_.get(id);
if (!channel) return;
this.channelsById_.delete(id);
const current = this.channelsByUin_.get(channel.uin);
const wasCurrent = current?.id === id;
if (wasCurrent) {
this.channelsByUin_.delete(channel.uin);
log.debug('account offline: UIN=%s', channel.uin);
this.bringCoreOffline(channel.uin);
}
try { channel.dispose(); } catch (err) {
adapterLog.debug('channel.dispose() threw: %s',
err instanceof Error ? err.message : String(err));
}
}
private bringCoreOnline(uin: string, channel: Channel): void {
// Defensive: stale core on the same UIN means we missed the
// offline event. Tear it down first so identity DB handles don't
// leak.
const stale = this.cores_.get(uin);
if (stale) {
log.warn('replacing stale core: UIN=%s id=%s', uin, stale.id);
try { stale.dispose(); } catch { /* ignore */ }
this.cores_.delete(uin);
}
const core = new Core(makeChannelCtx(channel));
this.cores_.set(uin, core);
this.events.emit('core-online', core);
}
private bringCoreOffline(uin: string): void {
const core = this.cores_.get(uin);
if (!core) return;
this.cores_.delete(uin);
this.events.emit('core-offline', { uin });
try { core.dispose(); } catch (err) {
log.debug('core.dispose() threw: %s', err instanceof Error ? err.message : String(err));
}
}
}

View File

@@ -0,0 +1,80 @@
import { HookAdapter } from '@snowluma/channel-hook';
import { SocketAdapter } from '@snowluma/channel-socket';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import { loadRuntimeConfig } from '@snowluma/common/runtime';
import { OneBotManager } from '@snowluma/onebot/manager';
import { Hub } from './hub';
const runtimeConfig = loadRuntimeConfig();
const log = createLogger('App');
async function main() {
log.info('SnowLuma starting');
// `Hub` is the single multi-account entry point — it owns channel
// adapters (hook, socket), the per-uin `Core` map, and the
// `core-online` / `core-offline` lifecycle event bus. Adapters
// must be registered BEFORE hub.start().
const hub = new Hub();
const oneBotManager = new OneBotManager();
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
if (autoLoadOnDiscovery) {
log.info('hook auto-load enabled: every discovered QQ process will be injected');
}
const hookAdapter = new HookAdapter({ autoLoadOnDiscovery });
hub.registerAdapter(hookAdapter);
hub.registerAdapter(new SocketAdapter());
// OneBot subscribes to Hub's two lifecycle events (`core-online` /
// `core-offline`) to materialise / tear down its per-account
// instances. Bind before start() so the very first login is
// delivered to OneBot.
oneBotManager.bind(hub);
await hub.start();
if (
(typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) ||
process.env.SNOWLUMA_DEV_WEBUI === '1'
) {
try {
const { initWebUI } = await import('./webui/server');
// The WebUI's process management surface is hook-specific (it
// exposes load/unload/refresh by PID); we hand it the
// adapter-owned HookManager directly. Future socket-only
// panels would receive their adapter through the same channel.
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookAdapter.hookManager);
} catch (err) {
log.error('Failed to start WebUI: ', err);
}
}
// Graceful shutdown: dispose managers, await log flush, then exit.
// SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path.
const shutdown = (signal: string) => async () => {
log.warn(`Shutting down (${signal})...`);
oneBotManager.dispose();
await hub.dispose();
await closeLogger();
process.exit(0);
};
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;
}
return fromConfig === true;
}
main().catch(async (error) => {
log.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
await closeLogger();
process.exit(1);
});

View File

@@ -0,0 +1,243 @@
import { createLogger } from '@snowluma/common/logger';
import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
import fs from 'fs';
import path from 'path';
const log = createLogger('WebUI.Auth');
const CONFIG_DIR = 'config';
const WEBUI_CONFIG_PATH = path.join(CONFIG_DIR, 'webui.json');
const SCRYPT_KEYLEN = 64;
const SCRYPT_N = 16384; // cost
const SCRYPT_R = 8;
const SCRYPT_P = 1;
const DEV_PASSWORD = 'snowluma-dev';
export function isDevAuthMode(): boolean {
return process.env.SNOWLUMA_DEV_MODE === '1';
}
function envBootstrapPassword(): string | null {
const raw = process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD;
if (!raw || typeof raw !== 'string') return null;
if (raw.length < 8) return null;
return raw;
}
export interface WebuiAuthState {
passwordHash: string; // hex
passwordSalt: string; // hex
mustChangePassword: boolean;
generatedAt: string;
updatedAt: string;
}
export interface PasswordRule {
id: string;
label: string;
test: (pwd: string) => boolean;
}
export const PASSWORD_RULES: PasswordRule[] = [
{ id: 'length', label: '长度不少于 10 位', test: (p) => p.length >= 10 },
{ id: 'lower', label: '包含小写字母', test: (p) => /[a-z]/.test(p) },
{ id: 'upper', label: '包含大写字母', test: (p) => /[A-Z]/.test(p) },
{ id: 'special', label: '包含特殊符号 (!@#$%…)', test: (p) => /[^A-Za-z0-9\s]/.test(p) },
{ id: 'no-space', label: '不包含空格', test: (p) => !/\s/.test(p) && p.length > 0 },
];
export function evaluatePasswordRules(password: string): { id: string; label: string; ok: boolean }[] {
return PASSWORD_RULES.map((r) => ({ id: r.id, label: r.label, ok: r.test(password) }));
}
export function isStrongPassword(password: string): boolean {
return PASSWORD_RULES.every((r) => r.test(password));
}
function hashPassword(password: string, salt: Buffer): Buffer {
return scryptSync(password, salt, SCRYPT_KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
}
function ensureConfigDir(): void {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
function isValidState(value: unknown): value is WebuiAuthState {
if (!value || typeof value !== 'object') return false;
const v = value as Record<string, unknown>;
return (
typeof v.passwordHash === 'string' &&
typeof v.passwordSalt === 'string' &&
typeof v.mustChangePassword === 'boolean' &&
/^[0-9a-f]+$/i.test(v.passwordHash) &&
/^[0-9a-f]+$/i.test(v.passwordSalt)
);
}
function generateInitialState(initialPassword: string): WebuiAuthState {
const salt = randomBytes(16);
const hash = hashPassword(initialPassword, salt);
const now = new Date().toISOString();
return {
passwordHash: hash.toString('hex'),
passwordSalt: salt.toString('hex'),
mustChangePassword: true,
generatedAt: now,
updatedAt: now,
};
}
function backupCorruptConfig(): void {
try {
const dest = `${WEBUI_CONFIG_PATH}.bak.${Date.now()}`;
fs.renameSync(WEBUI_CONFIG_PATH, dest);
log.warn('previous webui.json moved to %s', dest);
} catch (err) {
log.warn('failed to back up corrupt webui.json: %s', err instanceof Error ? err.message : String(err));
}
}
function atomicWrite(state: WebuiAuthState): void {
ensureConfigDir();
const tmp = WEBUI_CONFIG_PATH + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { encoding: 'utf8', mode: 0o600 });
try {
fs.chmodSync(tmp, 0o600);
} catch {
/* ignore */
}
fs.renameSync(tmp, WEBUI_CONFIG_PATH);
}
export class WebuiAuth {
private state: WebuiAuthState;
private initialPlain: string | null;
private readonly devMode: boolean;
private constructor(state: WebuiAuthState, initialPlain: string | null, devMode: boolean) {
this.state = state;
this.initialPlain = initialPlain;
this.devMode = devMode;
}
static load(): WebuiAuth {
if (isDevAuthMode()) {
const salt = randomBytes(16);
const hash = hashPassword(DEV_PASSWORD, salt);
const now = new Date().toISOString();
const state: WebuiAuthState = {
passwordHash: hash.toString('hex'),
passwordSalt: salt.toString('hex'),
mustChangePassword: false,
generatedAt: now,
updatedAt: now,
};
return new WebuiAuth(state, null, true);
}
ensureConfigDir();
if (fs.existsSync(WEBUI_CONFIG_PATH)) {
try {
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
const parsed = JSON.parse(raw) as unknown;
if (isValidState(parsed)) {
if (parsed.mustChangePassword) {
// Previous start generated a bootstrap password but the operator
// never completed the forced-change flow. The plaintext is gone
// (only the hash is on disk, and the log line from last run may
// be lost), so rotate to a fresh CSPRNG password they can see.
const initialPassword = randomBytes(8).toString('hex');
const state = generateInitialState(initialPassword);
atomicWrite(state);
log.warn('previous bootstrap password was never rotated; regenerated a new one');
return new WebuiAuth(state, initialPassword, false);
}
return new WebuiAuth(parsed, null, false);
}
log.error('webui.json schema invalid; backing up and regenerating credentials');
backupCorruptConfig();
} catch (err) {
log.error(
'webui.json is corrupt and will be regenerated; the previous file is backed up: %s',
err instanceof Error ? err.message : String(err),
);
backupCorruptConfig();
}
}
const envPassword = envBootstrapPassword();
if (envPassword !== null) {
const salt = randomBytes(16);
const hash = hashPassword(envPassword, salt);
const now = new Date().toISOString();
const state: WebuiAuthState = {
passwordHash: hash.toString('hex'),
passwordSalt: salt.toString('hex'),
mustChangePassword: false,
generatedAt: now,
updatedAt: now,
};
atomicWrite(state);
log.info('webui credentials seeded from SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD');
return new WebuiAuth(state, null, false);
}
const initialPassword = randomBytes(8).toString('hex');
const state = generateInitialState(initialPassword);
atomicWrite(state);
return new WebuiAuth(state, initialPassword, false);
}
/** True when SNOWLUMA_DEV_MODE was active at load time. */
isDevMode(): boolean {
return this.devMode;
}
/** Fixed dev password (only meaningful when {@link isDevMode} is true). */
static get devPassword(): string {
return DEV_PASSWORD;
}
/** Returns the auto-generated initial password if this is a fresh install, else null. */
takeInitialPassword(): string | null {
const p = this.initialPlain;
this.initialPlain = null;
return p;
}
mustChangePassword(): boolean {
return this.state.mustChangePassword;
}
verify(password: string): boolean {
if (typeof password !== 'string' || password.length === 0) return false;
try {
const salt = Buffer.from(this.state.passwordSalt, 'hex');
const expected = Buffer.from(this.state.passwordHash, 'hex');
const got = hashPassword(password, salt);
if (got.length !== expected.length) return false;
return timingSafeEqual(got, expected);
} catch {
return false;
}
}
setPassword(newPassword: string): void {
if (this.devMode) {
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改');
}
if (!isStrongPassword(newPassword)) {
throw new Error('密码不符合强度要求');
}
const salt = randomBytes(16);
const hash = hashPassword(newPassword, salt);
const next: WebuiAuthState = {
passwordHash: hash.toString('hex'),
passwordSalt: salt.toString('hex'),
mustChangePassword: false,
generatedAt: this.state.generatedAt,
updatedAt: new Date().toISOString(),
};
atomicWrite(next);
this.state = next;
}
}

View File

@@ -0,0 +1,72 @@
import { getConnInfo } from '@hono/node-server/conninfo';
import type { Context } from 'hono';
export type TrustProxyMode =
| { kind: 'none' }
| { kind: 'loopback' }
| { kind: 'all' }
| { kind: 'ip-list'; ips: Set<string> };
export function parseTrustProxy(raw: string | undefined): TrustProxyMode {
const value = raw?.trim().toLowerCase() ?? '';
if (!value) return { kind: 'none' };
if (value === '1' || value === 'true' || value === 'all') return { kind: 'all' };
if (value === 'loopback') return { kind: 'loopback' };
const ips = new Set(
value.split(',').map((s) => s.trim()).filter(Boolean),
);
if (ips.size === 0) return { kind: 'none' };
return { kind: 'ip-list', ips };
}
export function describeTrustProxy(mode: TrustProxyMode): string {
switch (mode.kind) {
case 'none': return 'socket peer (default)';
case 'all': return 'X-Real-IP / X-Forwarded-For from any peer';
case 'loopback': return 'X-Real-IP / X-Forwarded-For when socket peer is loopback';
case 'ip-list': return `X-Real-IP / X-Forwarded-For when socket peer is in [${[...mode.ips].join(',')}]`;
}
}
function isLoopback(ip: string): boolean {
return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
}
function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean {
switch (mode.kind) {
case 'none': return false;
case 'all': return true;
case 'loopback': return isLoopback(socketIp);
case 'ip-list': return mode.ips.has(socketIp);
}
}
export function pickClientIp(
c: Pick<Context, 'req'>,
mode: TrustProxyMode,
getSocketIp: () => string,
): string {
const socketIp = (() => {
try { return getSocketIp() || '127.0.0.1'; }
catch { return '127.0.0.1'; }
})();
if (!shouldTrustHeaders(mode, socketIp)) return socketIp;
const realIp = c.req.header('x-real-ip')?.trim();
if (realIp) return realIp;
const xff = c.req.header('x-forwarded-for');
if (xff) {
const first = xff.split(',')[0].trim();
if (first) return first;
}
return socketIp;
}
/** Convenience binding for the live server: read socket via getConnInfo. */
export function makeClientIpResolver(mode: TrustProxyMode): (c: Context) => string {
return (c) => pickClientIp(c, mode, () => {
try { return getConnInfo(c).remote.address ?? '127.0.0.1'; }
catch { return '127.0.0.1'; }
});
}

View File

@@ -0,0 +1,38 @@
import net from 'net';
function isPortAvailable(port: number, host = '0.0.0.0'): Promise<boolean> {
return new Promise((resolve) => {
const server = net.createServer();
let settled = false;
const finalize = (ok: boolean) => {
if (settled) return;
settled = true;
try {
server.close(() => resolve(ok));
} catch {
resolve(ok);
}
};
server.once('error', () => finalize(false));
server.once('listening', () => finalize(true));
try {
server.listen(port, host);
} catch {
finalize(false);
}
});
}
/**
* Find an available TCP port starting from `start`, advancing by 1 up to `maxTries` attempts.
* Skips reserved/invalid port numbers.
*/
export async function findAvailablePort(start: number, maxTries = 50): Promise<number> {
let port = Math.max(1, Math.min(65535, Math.trunc(start)));
for (let i = 0; i < maxTries; i++) {
if (port > 65535) break;
if (await isPortAvailable(port)) return port;
port += 1;
}
throw new Error(`No available TCP port found near ${start}`);
}

View File

@@ -0,0 +1,531 @@
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import type { HookManager, HookProcessInfo } from '@snowluma/channel-hook';
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config';
import type { OneBotManager } from '@snowluma/onebot/manager';
import type { OneBotConfig } from '@snowluma/onebot/types';
import { randomBytes } from 'crypto';
import { existsSync, readFileSync } from 'fs';
import { Hono, type Context } from 'hono';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
import { findAvailablePort } from './port';
const log = createLogger('WebUI');
const __dirname = path.dirname(fileURLToPath(import.meta.url));
interface SessionInfo {
expiresAt: number;
mustChangePassword: boolean;
}
const sessionTokens = new Map<string, SessionInfo>();
const loginAttempts = new Map<string, { count: number; resetAt: number }>();
const LOGIN_MAX_ATTEMPTS = 5;
const LOGIN_LOCKOUT_MS = 15 * 60 * 1000;
const TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
const AVATAR_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const AVATAR_BROWSER_CACHE_SECONDS = 30 * 24 * 60 * 60;
// Endpoints that an auth-required-but-must-change-password session can still hit.
const MUST_CHANGE_ALLOWLIST = new Set([
'/api/status',
'/api/auth/state',
'/api/auth/check-strength',
'/api/auth/change-password',
'/api/logout',
]);
// Endpoints that may authenticate via `?token=` query parameter. Only the
// SSE log stream is here because EventSource cannot set custom headers; all
// other endpoints MUST use the Authorization header so tokens never leak
// into access logs / Referer / browser history.
const TOKEN_QUERY_ALLOWLIST = new Set([
'/api/logs/stream',
]);
// uin = QQ number; 5–12 digits. Used to construct config file paths,
// so we MUST refuse anything else (path traversal, NUL bytes, etc.).
const UIN_REGEX = /^\d{5,12}$/;
const avatarCache = new Map<string, { body: Uint8Array; contentType: string; expiresAt: number }>();
function purgeExpiredTokens() {
const now = Date.now();
for (const [token, info] of sessionTokens) {
if (now > info.expiresAt) sessionTokens.delete(token);
}
for (const [ip, attempt] of loginAttempts) {
if (now > attempt.resetAt) loginAttempts.delete(ip);
}
}
/**
* Resolve the client IP for per-IP rate limiting. Default is the TCP
* socket peer (cannot be spoofed by the client). Operators behind a
* reverse proxy must opt in via the `SNOWLUMA_WEBUI_TRUST_PROXY` env
* var; see `./client-ip.ts` for the accepted values.
*/
const trustProxyMode = parseTrustProxy(process.env.SNOWLUMA_WEBUI_TRUST_PROXY);
const getClientIp = makeClientIpResolver(trustProxyMode);
async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> {
const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, {
headers: {
'User-Agent': 'SnowLuma WebUI',
Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
},
});
if (!response.ok) throw new Error(`avatar upstream responded with ${response.status}`);
const contentType = response.headers.get('content-type') || 'image/jpeg';
const body = new Uint8Array(await response.arrayBuffer());
return { body, contentType };
}
export async function initWebUI(
desiredPort: number = 5099,
oneBotManager: OneBotManager,
hookManager?: HookManager,
): Promise<{ port: number }> {
const auth = WebuiAuth.load();
const initialPassword = auth.takeInitialPassword();
if (auth.isDevMode()) {
log.warn('dev mode enabled: password=%s', WebuiAuth.devPassword);
log.warn('dev mode skips config/webui.json and password rotation');
} else if (initialPassword) {
log.info('════════════════════════════════════════════════════════════════');
log.info(' ★ WebUI 初始登录凭据 / Initial WebUI Credentials ★');
log.info(' 请立即登录并修改密码 —— 关闭程序后此密码无法找回。');
log.info(' 若跳过初始改密,下次启动将自动生成新的随机密码。');
log.info(' Log in and change the password now; it will not be shown again.');
log.info('────────────────────────────────────────────────────────────────');
log.info('initial credentials: user=admin password=%s', initialPassword);
log.info('════════════════════════════════════════════════════════════════');
} else if (auth.mustChangePassword()) {
log.warn('password change is still required');
}
log.info('login rate-limit keyed by: %s', describeTrustProxy(trustProxyMode));
if (trustProxyMode.kind === 'all') {
log.warn('SNOWLUMA_WEBUI_TRUST_PROXY=1 — only safe behind a reverse proxy that strips client-set X-Real-IP / X-Forwarded-For');
}
const app = new Hono();
// ─── Anti-indexing ───────────────────────────────────────────────────────
// The WebUI is an admin surface that has no business showing up in
// search results — even the login page leaks the existence of a
// SnowLuma instance to anyone scanning the IP. Three overlapping
// signals: a hard X-Robots-Tag on every response, a robots.txt for
// crawlers that read it before pages, and a <meta robots> in the
// SPA shell for the case where a proxy strips headers.
app.use('*', async (c, next) => {
await next();
c.res.headers.set(
'X-Robots-Tag',
'noindex, nofollow, noarchive, nosnippet, noimageindex',
);
});
app.get('/robots.txt', (c) => {
c.res.headers.set('Content-Type', 'text/plain; charset=utf-8');
return c.body('User-agent: *\nDisallow: /\n');
});
// ─── Auth middleware ─────────────────────────────────────────────────────
app.use('/api/*', async (c, next) => {
const reqPath = c.req.path;
if (reqPath === '/api/login') return next();
const authHeader = c.req.header('Authorization');
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : '';
const queryToken = TOKEN_QUERY_ALLOWLIST.has(reqPath) ? (c.req.query('token') ?? '') : '';
const token = bearerToken || queryToken;
if (!token) return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
const info = sessionTokens.get(token);
if (!info || Date.now() > info.expiresAt) {
return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401);
}
if (info.mustChangePassword && !MUST_CHANGE_ALLOWLIST.has(reqPath)) {
return c.json({ status: 'failed', message: '请先修改密码', mustChangePassword: true }, 403);
}
c.set('sessionToken' as never, token);
await next();
});
// Periodic janitor — keeps sessionTokens / loginAttempts from growing
// unbounded and replaces the per-request O(n) sweep we used to do.
const tokenJanitor = setInterval(purgeExpiredTokens, 60_000);
tokenJanitor.unref?.();
// ─── Login ───────────────────────────────────────────────────────────────
app.post('/api/login', async (c) => {
const ip = getClientIp(c);
const now = Date.now();
const attempt = loginAttempts.get(ip);
if (attempt && attempt.count >= LOGIN_MAX_ATTEMPTS && now < attempt.resetAt) {
const waitSec = Math.ceil((attempt.resetAt - now) / 1000);
return c.json({ success: false, message: `登录尝试过多,请 ${waitSec} 秒后重试` }, 429);
}
let body: { password?: unknown };
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const password = typeof body.password === 'string' ? body.password : '';
if (!auth.verify(password)) {
const current = loginAttempts.get(ip) ?? { count: 0, resetAt: now + LOGIN_LOCKOUT_MS };
current.count += 1;
if (current.count === 1) current.resetAt = now + LOGIN_LOCKOUT_MS;
loginAttempts.set(ip, current);
return c.json({ success: false, message: '密码错误' }, 401);
}
loginAttempts.delete(ip);
const token = randomBytes(32).toString('hex');
const mustChange = auth.mustChangePassword();
sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange });
return c.json({ success: true, token, mustChangePassword: mustChange });
});
app.post('/api/logout', (c) => {
const token = c.get('sessionToken' as never) as string | undefined;
if (token) sessionTokens.delete(token);
return c.json({ success: true });
});
app.get('/api/auth/state', (c) => {
const token = c.get('sessionToken' as never) as string | undefined;
const info = token ? sessionTokens.get(token) : undefined;
return c.json({
mustChangePassword: info?.mustChangePassword ?? auth.mustChangePassword(),
});
});
app.post('/api/auth/check-strength', async (c) => {
let body: { password?: unknown };
try {
body = await c.req.json();
} catch {
return c.json({ rules: evaluatePasswordRules(''), valid: false });
}
const pwd = typeof body.password === 'string' ? body.password : '';
return c.json({ rules: evaluatePasswordRules(pwd), valid: isStrongPassword(pwd) });
});
app.post('/api/auth/change-password', async (c) => {
let body: { oldPassword?: unknown; newPassword?: unknown };
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const oldPassword = typeof body.oldPassword === 'string' ? body.oldPassword : '';
const newPassword = typeof body.newPassword === 'string' ? body.newPassword : '';
if (!auth.verify(oldPassword)) {
return c.json({ success: false, message: '当前密码不正确' }, 401);
}
if (!isStrongPassword(newPassword)) {
return c.json(
{ success: false, message: '新密码不符合强度要求', rules: evaluatePasswordRules(newPassword) },
400,
);
}
if (oldPassword === newPassword) {
return c.json({ success: false, message: '新密码不得与旧密码相同' }, 400);
}
try {
auth.setPassword(newPassword);
} catch (err) {
log.warn('change password failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '密码修改失败' }, 400);
}
// Invalidate every session, including the current one. If the old
// password was compromised, the attacker may already hold the current
// token; rotating credentials must rotate sessions too.
sessionTokens.clear();
log.info('password updated; all sessions invalidated');
return c.json({ success: true, requireRelogin: true });
});
// ─── Avatar proxy (uin validated) ────────────────────────────────────────
app.get('/avatar/:uin', async (c) => {
const uin = c.req.param('uin');
if (!UIN_REGEX.test(uin)) return c.text('invalid uin', 400);
const now = Date.now();
let cached = avatarCache.get(uin);
if (!cached || cached.expiresAt <= now) {
try {
const avatar = await fetchQqAvatar(uin);
cached = { ...avatar, expiresAt: now + AVATAR_CACHE_TTL_MS };
avatarCache.set(uin, cached);
} catch (err) {
log.warn('failed to proxy avatar for UIN %s: %s', uin, err instanceof Error ? err.message : String(err));
if (!cached) return c.text('avatar unavailable', 502);
}
}
return new Response(cached.body, {
headers: {
'Content-Type': cached.contentType,
'Cache-Control': `public, max-age=${AVATAR_BROWSER_CACHE_SECONDS}, immutable`,
},
});
});
// ─── Read-only API ───────────────────────────────────────────────────────
app.get('/api/status', (c) => c.json({ status: 'running' }));
// Host system info
let lastCpuTimes: { idle: number; total: number }[] | null = null;
function sampleCpuLoad(): number[] {
const cpus = os.cpus();
const current = cpus.map((cpu) => {
const t = cpu.times;
const total = t.user + t.nice + t.sys + t.idle + t.irq;
return { idle: t.idle, total };
});
if (!lastCpuTimes || lastCpuTimes.length !== current.length) {
lastCpuTimes = current;
return current.map(() => 0);
}
const usage = current.map((cur, i) => {
const prev = lastCpuTimes![i];
const totalDiff = cur.total - prev.total;
const idleDiff = cur.idle - prev.idle;
if (totalDiff <= 0) return 0;
return Math.max(0, Math.min(100, ((totalDiff - idleDiff) / totalDiff) * 100));
});
lastCpuTimes = current;
return usage;
}
app.get('/api/system', (c) => {
const cpus = os.cpus();
const usage = sampleCpuLoad();
const totalMem = os.totalmem();
const freeMem = os.freemem();
const usedMem = totalMem - freeMem;
const runtimeMemory = process.memoryUsage();
return c.json({
hostname: os.hostname(),
platform: os.platform(),
arch: os.arch(),
release: os.release(),
uptime: os.uptime(),
processUptime: process.uptime(),
nodeVersion: process.version,
cpu: {
model: cpus[0]?.model ?? 'unknown',
cores: cpus.length,
speedMHz: cpus[0]?.speed ?? 0,
loadAvg: os.loadavg(),
perCore: usage,
average: usage.length ? usage.reduce((s, v) => s + v, 0) / usage.length : 0,
},
memory: {
total: totalMem,
free: freeMem,
used: usedMem,
usagePercent: totalMem ? (usedMem / totalMem) * 100 : 0,
},
runtime: {
pid: process.pid,
rss: runtimeMemory.rss,
heapTotal: runtimeMemory.heapTotal,
heapUsed: runtimeMemory.heapUsed,
external: runtimeMemory.external,
arrayBuffers: runtimeMemory.arrayBuffers,
},
});
});
app.get('/api/qq-list', (c) => {
const instances = oneBotManager.getInstances();
const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.nickname }));
return c.json({ list });
});
app.get('/api/logs', (c) => {
const limit = Number(c.req.query('limit') ?? 300);
return c.json({ list: getRecentLogs(limit) });
});
app.get('/api/logs/level', (c) => {
return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] });
});
app.post('/api/logs/level', async (c) => {
const body = await c.req.json().catch(() => null) as { level?: unknown } | null;
const next = typeof body?.level === 'string' ? body.level : '';
if (!setLogLevel(next)) {
return c.json({ message: `invalid level: ${next}`, levels: [...LOG_LEVELS] }, 400);
}
log.info('console log level set to %s via WebUI', getLogLevel());
return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] });
});
app.get('/api/logs/stream', (c) => {
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
let closed = false;
let unsubscribe: (() => void) | undefined;
let heartbeat: NodeJS.Timeout | undefined;
const teardown = () => {
if (closed) return;
closed = true;
if (heartbeat) clearInterval(heartbeat);
unsubscribe?.();
try { controller.close(); } catch { /* ignore */ }
};
const safeEnqueue = (chunk: Uint8Array) => {
if (closed) return;
try {
controller.enqueue(chunk);
} catch {
// The peer dropped between abort and the next enqueue —
// treat as end-of-stream so we don't leak listeners.
teardown();
}
};
const send = (event: unknown) => {
safeEnqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
};
send({ type: 'ready' });
unsubscribe = subscribeLogs((entry) => send(entry));
heartbeat = setInterval(() => {
safeEnqueue(encoder.encode(': heartbeat\n\n'));
}, 15000);
c.req.raw.signal.addEventListener('abort', teardown);
},
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
});
});
app.get('/api/processes', async (c) => {
if (!hookManager) return c.json({ list: [] });
try {
return c.json({ list: await hookManager.listProcesses() });
} catch (err) {
return c.json({ list: [], message: err instanceof Error ? err.message : String(err) }, 500);
}
});
// Per-process action handler. The three routes below differ only in
// which HookManager method they call.
const MAX_PID = 4_194_304;
function processAction(label: string, action: (pid: number) => Promise<HookProcessInfo>) {
return async (c: Context) => {
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
const pid = Number(c.req.param('pid'));
if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) {
return c.json({ success: false, message: 'invalid pid' }, 400);
}
try {
const processInfo = await action(pid);
return c.json({ success: processInfo.status !== 'error', process: processInfo });
} catch (err) {
log.warn('%s pid=%d failed: %s', label, pid, err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '操作失败,请检查服务器日志' }, 500);
}
};
}
app.post('/api/processes/:pid/load', processAction('load', (pid) => hookManager!.loadProcess(pid)));
app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid)));
app.post('/api/processes/:pid/refresh', processAction('refresh', (pid) => hookManager!.refreshProcess(pid)));
app.get('/api/processes/:pid/probe-login', async (c) => {
if (!hookManager) return c.json({ info: null, message: 'hook manager is not available' }, 503);
const pid = Number(c.req.param('pid'));
if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) {
return c.json({ info: null, message: 'invalid pid' }, 400);
}
try {
const info = await hookManager.probeProcessLoginInfo(pid);
return c.json({ info });
} catch (err) {
log.warn('probe-login pid=%d failed: %s', pid, err instanceof Error ? err.message : String(err));
return c.json({ info: null, message: '探测失败' }, 500);
}
});
app.get('/api/config/:uin', (c) => {
const uin = c.req.param('uin');
if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400);
// Read-only: never write defaults to disk on a GET. The persisted
// file is created when manager.onSessionStarted boots an instance
// or when the operator POSTs from this very endpoint.
const config = loadOneBotConfig(uin);
return c.json({ config });
});
app.post('/api/config/:uin', async (c) => {
const uin = c.req.param('uin');
if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400);
try {
const body = (await c.req.json()) as OneBotConfig;
saveOneBotConfig(uin, body);
const reloaded = oneBotManager.reloadConfig(uin);
log.info('Updated OneBot config for UIN: %s%s', uin, reloaded ? ' and reloaded' : '');
return c.json({
success: true,
reloaded,
message: reloaded ? '配置保存成功,已热重载当前会话。' : '配置保存成功,当前会话未在线,将在下次连接时生效。',
});
} catch (err) {
log.warn('save config for uin=%s failed: %s', uin, err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '配置保存失败,请检查服务器日志' }, 400);
}
});
// ─── Static frontend ─────────────────────────────────────────────────────
// Build path is relative to the bundled / dev __dirname. SPA fallback to
// index.html so client-side routes (if any) keep working.
const staticRoot = path.resolve(__dirname, 'client');
app.use('/*', serveStatic({ root: staticRoot }));
const indexHtmlPath = path.join(staticRoot, 'index.html');
app.get('*', (c) => {
// SPA fallback: only for navigations that didn't hit a static asset.
if (c.req.path.startsWith('/api/') || c.req.path.startsWith('/avatar/')) {
return c.text('not found', 404);
}
if (existsSync(indexHtmlPath)) {
const html = readFileSync(indexHtmlPath, 'utf8');
return c.html(html);
}
return c.text(
'WebUI client bundle not found. Run `pnpm --filter webui build` (or use the dev server on :5178).',
404,
);
});
const finalPort = await findAvailablePort(desiredPort);
if (finalPort !== desiredPort) {
log.warn('port %d is in use, using %d instead', desiredPort, finalPort);
}
await new Promise<void>((resolve) => {
serve({ fetch: app.fetch, port: finalPort }, (info) => {
log.info(`listening http://localhost:${info.port}`);
resolve();
});
});
return { port: finalPort };
}

View File

@@ -0,0 +1,147 @@
import { makeChannelCtx } from '@snowluma/channel';
import { HookChannel } from '@snowluma/channel-hook';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { GroupMemberJoin, QQEventVariant } from '@snowluma/protocol/events';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
import { describe, expect, it } from 'vitest';
import { Core } from '../src/core';
const SELF_UIN = '10001';
const GROUP_ID = 123456789;
function makeGroupMember(uin: number, uid: string): GroupMemberInfo {
return {
uin,
uid,
nickname: '',
card: '',
role: 'member',
level: 0,
title: '',
joinTime: 0,
lastSentTime: 0,
shutUpTime: 0,
};
}
function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
return {
groupId: GROUP_ID,
groupName: '',
remark: '',
memberCount: members.length,
memberMax: 500,
members: new Map(members.map((member) => [member.uin, member])),
};
}
function buildCore(identity: IdentityService, refreshedMembers: GroupMemberInfo[]) {
const channel = new HookChannel(identity.uin);
const core = new Core(makeChannelCtx(channel), identity);
const memberFetches: Array<{ groupId: number; force: boolean }> = [];
core.apis.contacts.fetchGroupMemberList = async (
groupId: number,
options: { force?: boolean } = {},
): Promise<GroupMemberInfo[]> => {
memberFetches.push({ groupId, force: Boolean(options.force) });
for (const member of refreshedMembers) {
core.identity.updateGroupMember(groupId, member);
}
return refreshedMembers;
};
return { core, channel, memberFetches };
}
function makePacket(): PacketInfo {
return {
pid: 1,
uin: SELF_UIN,
serviceCmd: 'test.member_join',
seqId: 1,
retCode: 0,
fromClient: false,
body: new Uint8Array(0),
};
}
function makeRequestPacket(): PacketInfo {
return {
...makePacket(),
serviceCmd: 'test.request_identity',
};
}
async function waitForEvent(events: GroupMemberJoin[]): Promise<GroupMemberJoin> {
for (let i = 0; i < 10; i++) {
if (events[0]) return events[0];
await new Promise((resolve) => setTimeout(resolve, 0));
}
throw new Error('timed out waiting for group_member_join');
}
describe('Core group member identity refresh', () => {
it('forces a fresh member list before dispatching an unresolved join event', async () => {
const member = makeGroupMember(22222, 'u_new_member');
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
const { core, channel, memberFetches } = buildCore(identity, [member]);
const seen: GroupMemberJoin[] = [];
core.registerCmd('test.member_join', () => [{
kind: 'group_member_join',
time: 1710000000,
selfUin: Number(SELF_UIN),
groupId: GROUP_ID,
userUin: 0,
operatorUin: 0,
userUid: member.uid,
operatorUid: member.uid,
}]);
core.events.on('group_member_join', (event: GroupMemberJoin) => {
seen.push(event);
});
channel.deliverPacket(makePacket());
const event = await waitForEvent(seen);
expect(memberFetches).toEqual([{ groupId: GROUP_ID, force: true }]);
expect(event.userUin).toBe(member.uin);
expect(event.operatorUin).toBe(member.uin);
});
it('remembers UID mappings from realtime request events', () => {
const channel = new HookChannel(SELF_UIN);
const core = new Core(makeChannelCtx(channel), IdentityService.memory(SELF_UIN));
const events: QQEventVariant[] = [
{
kind: 'friend_request',
time: 1710000000,
selfUin: Number(SELF_UIN),
fromUin: 55555,
fromUid: 'u_friend_request',
message: '',
flag: 'u_friend_request',
},
{
kind: 'group_invite',
time: 1710000000,
selfUin: Number(SELF_UIN),
groupId: GROUP_ID,
fromUin: 66666,
fromUid: 'u_group_request',
subType: 'add',
message: '',
flag: 'add:123456789:u_group_request',
},
];
core.registerCmd('test.request_identity', () => events);
channel.deliverPacket(makeRequestPacket());
expect(core.identity.findUidByUin(55555)).toBe('u_friend_request');
expect(core.identity.findUidByUin(66666)).toBe('u_group_request');
expect(core.identity.findUinByUid('u_friend_request')).toBe(55555);
expect(core.identity.findUinByUid('u_group_request')).toBe(66666);
});
});

View File

@@ -0,0 +1,134 @@
import type { ChannelCtx } from '@snowluma/channel';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
import type { FileExtra } from '@snowluma/proto-defs/message';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { describe, expect, it, vi } from 'vitest';
import { Core } from '../src/core';
vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]),
}));
/**
* Build a fake `ChannelCtx` POJO that captures the outbound packet
* body for assertions. The `Core` under test consumes this ctx exactly
* the way `Hub` would in production — via `sendRawPacket` and
* `onPacket` only.
*/
function makeFakeCtx(uin: string): {
ctx: ChannelCtx;
getCapturedBody: () => Uint8Array | null;
setResponse: (resp: SendPacketResult) => void;
} {
let capturedBody: Uint8Array | null = null;
let response: SendPacketResult = {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<SendMessageResponse>({
result: 0,
errMsg: '',
privateSequence: 88,
timestamp1: 1710000000,
})),
};
const ctx: ChannelCtx = {
uin,
kind: 'inject',
sendRawPacket: async (_cmd, body) => {
capturedBody = body;
return response;
},
onPacket: () => { /* unused */ },
dispose: () => { /* unused */ },
};
return {
ctx,
getCapturedBody: () => capturedBody,
setResponse: (resp) => { response = resp; },
};
}
describe('Core private media routing', () => {
it('includes resolved uid in the final c2c send request for media messages', async () => {
const { IdentityService } = await import('@snowluma/protocol/identity-service');
const fake = makeFakeCtx('10000');
const core = new Core(fake.ctx, IdentityService.memory('10000'));
// resolveUserUid lookup needs an explicit override since the
// identity store has no mapping for the test peer.
core.resolveUserUid = vi.fn(async (uin: number) => {
expect(uin).toBe(12345);
return 'u_peer_12345';
});
await core.apis.message.sendPrivate(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]);
expect(fake.getCapturedBody()).toBeInstanceOf(Uint8Array);
const request = protobuf_decode<SendMessageRequest>(fake.getCapturedBody() as Uint8Array);
expect(request?.routingHead?.c2c).toMatchObject({
uin: 12345,
uid: 'u_peer_12345',
});
});
it('sendC2cFileMessage uses trans0x211 routing + msgContent FileExtra (NOT richText.notOnlineFile)', async () => {
// Regression: c2c file messages route through `trans0x211 { ccCmd:
// 4, uid }` (RoutingHead field 15), not `c2c { uin, uid }`. The
// file metadata lives in `MessageBody.msgContent` (a serialised
// `FileExtra { file: NotOnlineFile }`), not in `richText.notOnlineFile`.
// Confirmed against `dev/Lagrange.Core/.../MessagePacker.cs:
// BuildPacketBase` + `FileEntity.PackMessageContent`. Previous
// implementation wrote c2c routing + richText.notOnlineFile +
// c2cCmd=11 — the QQ-NT server rejected every c2c file send.
const { IdentityService } = await import('@snowluma/protocol/identity-service');
const fake = makeFakeCtx('10000');
const core = new Core(fake.ctx, IdentityService.memory('10000'));
const fileMd5 = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);
await core.apis.message.sendC2cFile(67890, 'u_peer_xyz', {
fileId: 'uuid-abc-123',
fileName: 'doc.txt',
fileSize: 1024,
fileMd5,
fileHash: 'hash-xyz',
});
const request = protobuf_decode<SendMessageRequest>(fake.getCapturedBody() as Uint8Array);
// Routing: must be trans0x211 with ccCmd=4 + uid, no c2c slot.
expect(request?.routingHead?.trans0x211).toMatchObject({
ccCmd: 4,
uid: 'u_peer_xyz',
});
expect(request?.routingHead?.c2c ?? undefined).toBeUndefined();
// Body: msgContent carries the FileExtra; richText is absent (no
// elems, no notOnlineFile slot — both lived on the wrong place).
expect(request?.messageBody?.msgContent).toBeInstanceOf(Uint8Array);
expect(request?.messageBody?.richText ?? undefined).toBeUndefined();
// Decode the msgContent and verify the NotOnlineFile fields land
// at the correct tags (Lagrange's NotOnlineFile schema, not the
// dead FileExtraInfo one).
const fileExtra = protobuf_decode<FileExtra>(request!.messageBody!.msgContent as Uint8Array);
expect(fileExtra?.file).toMatchObject({
fileUuid: 'uuid-abc-123',
fileName: 'doc.txt',
fileSize: 1024n,
fileHash: 'hash-xyz',
subcmd: 1, // server-required intake validator field
});
expect(fileExtra?.file?.fileMd5).toEqual(fileMd5);
// expireTime is now+7d; just sanity-check it landed (non-zero, plausible)
expect(fileExtra?.file?.expireTime).toBeGreaterThan(Math.floor(Date.now() / 1000));
// c2cCmd is left at 0 / undefined — the old `c2cCmd=11` was a
// stale go-cqhttp value the QQ-NT server doesn't recognise on the
// c2c-file path.
expect(request?.contentHead?.c2cCmd ?? 0).toBe(0);
});
});

View File

@@ -0,0 +1,169 @@
// Shared fixtures for the per-theme bridge-action tests.
//
// Each action test file mocks `../src/bridge/bridge-oidb` and (where
// needed) `../src/bridge/highway/*` so we can assert what the action
// asked the OIDB / Highway layer to do without booting a real Bridge.
//
// `mockBridge()` returns a minimal stand-in: enough state for the
// actions to thread but no real packet/event machinery.
//
// As the #6 Api-on-ctx refactor moves business methods OFF Bridge and
// onto `bridge.apis.<area>.method()`, the mock grows an `apis` block
// matching the ApiHub shape. Each Api gets its own stub helper
// (e.g. `mockMessageApi()`) and tests can override individual entries
// via `mockBridge({ apis: { message: ... } })`.
import { vi } from 'vitest';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
/** Default receipt returned by sendGroup / sendPrivate / sendC2cFile mocks. */
const STUB_RECEIPT = { messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 0 };
export interface MockMessageApi {
sendGroup: ReturnType<typeof vi.fn>;
sendPrivate: ReturnType<typeof vi.fn>;
sendC2cFile: ReturnType<typeof vi.fn>;
recallGroup: ReturnType<typeof vi.fn>;
recallPrivate: ReturnType<typeof vi.fn>;
markGroupRead: ReturnType<typeof vi.fn>;
markPrivateRead: ReturnType<typeof vi.fn>;
}
export function mockMessageApi(): MockMessageApi {
return {
sendGroup: vi.fn(async () => STUB_RECEIPT),
sendPrivate: vi.fn(async () => STUB_RECEIPT),
sendC2cFile: vi.fn(async () => STUB_RECEIPT),
recallGroup: vi.fn(async () => undefined),
recallPrivate: vi.fn(async () => undefined),
markGroupRead: vi.fn(async () => undefined),
markPrivateRead: vi.fn(async () => undefined),
};
}
export interface MockContactsApi {
fetchFriendList: ReturnType<typeof vi.fn>;
fetchGroupList: ReturnType<typeof vi.fn>;
fetchGroupMemberList: ReturnType<typeof vi.fn>;
fetchUserProfile: ReturnType<typeof vi.fn>;
fetchGroupRequests: ReturnType<typeof vi.fn>;
fetchDownloadRKeys: ReturnType<typeof vi.fn>;
}
export function mockContactsApi(): MockContactsApi {
return {
fetchFriendList: vi.fn(async () => []),
fetchGroupList: vi.fn(async () => []),
fetchGroupMemberList: vi.fn(async () => []),
fetchUserProfile: vi.fn(async () => ({ uid: 'profile-uid' })),
fetchGroupRequests: vi.fn(async () => []),
fetchDownloadRKeys: vi.fn(async () => []),
};
}
export interface MockGroupFileApi {
upload: ReturnType<typeof vi.fn>;
uploadPrivate: ReturnType<typeof vi.fn>;
publish: ReturnType<typeof vi.fn>;
getCount: ReturnType<typeof vi.fn>;
list: ReturnType<typeof vi.fn>;
getUrl: ReturnType<typeof vi.fn>;
getPrivateUrl: ReturnType<typeof vi.fn>;
getPttUrl: ReturnType<typeof vi.fn>;
getPrivatePttUrl: ReturnType<typeof vi.fn>;
getVideoUrl: ReturnType<typeof vi.fn>;
getPrivateVideoUrl: ReturnType<typeof vi.fn>;
delete: ReturnType<typeof vi.fn>;
move: ReturnType<typeof vi.fn>;
createFolder: ReturnType<typeof vi.fn>;
deleteFolder: ReturnType<typeof vi.fn>;
renameFolder: ReturnType<typeof vi.fn>;
}
export function mockGroupFileApi(): MockGroupFileApi {
return {
upload: vi.fn(async () => ({ fileId: 'stub-fid' })),
uploadPrivate: vi.fn(async () => ({ fileId: 'stub-pfid', fileHash: 'stub-hash' })),
publish: vi.fn(async () => undefined),
getCount: vi.fn(async () => ({ fileCount: 0, maxCount: 10000 })),
list: vi.fn(async () => ({ files: [], folders: [] })),
getUrl: vi.fn(async () => 'stub://url'),
getPrivateUrl: vi.fn(async () => 'stub://private-url'),
getPttUrl: vi.fn(async () => 'stub://ptt-url'),
getPrivatePttUrl: vi.fn(async () => 'stub://private-ptt-url'),
getVideoUrl: vi.fn(async () => 'stub://video-url'),
getPrivateVideoUrl: vi.fn(async () => 'stub://private-video-url'),
delete: vi.fn(async () => undefined),
move: vi.fn(async () => undefined),
createFolder: vi.fn(async () => undefined),
deleteFolder: vi.fn(async () => undefined),
renameFolder: vi.fn(async () => undefined),
};
}
export interface MockApiHub {
message: MockMessageApi;
contacts: MockContactsApi;
groupFile: MockGroupFileApi;
// additional Apis added commit-by-commit as #6 progresses
}
export function mockApiHub(overrides: Partial<MockApiHub> = {}): MockApiHub {
return {
message: overrides.message ?? mockMessageApi(),
contacts: overrides.contacts ?? mockContactsApi(),
groupFile: overrides.groupFile ?? mockGroupFileApi(),
};
}
export interface MockBridge {
identity: {
uin: string;
selfUid: string;
nickname: string;
findUidByUin: ReturnType<typeof vi.fn>;
findUinByUid: ReturnType<typeof vi.fn>;
findGroupMember: ReturnType<typeof vi.fn>;
};
apis: MockApiHub;
sendRawPacket: ReturnType<typeof vi.fn>;
fetchFriendList: ReturnType<typeof vi.fn>;
fetchGroupMemberList: ReturnType<typeof vi.fn>;
fetchUserProfile: ReturnType<typeof vi.fn>;
resolveUserUid: ReturnType<typeof vi.fn>;
// Uploaded-file metadata cache helpers — GroupFileApi.upload /
// uploadPrivate call these to remember the upload, so tests
// covering those code paths get a default-no-op shim.
rememberUploadedFile: ReturnType<typeof vi.fn>;
recallUploadedFile: ReturnType<typeof vi.fn>;
}
export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
const defaultResp: SendPacketResult = {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.alloc(0),
};
return {
identity: {
uin: '10001',
selfUid: 'self-uid',
nickname: 'self-nick',
findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0),
findGroupMember: vi.fn(() => null),
...(overrides.identity ?? {}),
} as MockBridge['identity'],
apis: overrides.apis ?? mockApiHub(),
sendRawPacket: vi.fn(async () => defaultResp),
fetchFriendList: vi.fn(async () => []),
fetchGroupMemberList: vi.fn(async () => []),
fetchUserProfile: vi.fn(async () => ({ uid: 'profile-uid' })),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
rememberUploadedFile: vi.fn(),
recallUploadedFile: vi.fn(() => undefined),
...overrides,
};
}

View File

@@ -0,0 +1,162 @@
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupTodo,
OidbStrangerStatusReq,
OidbStrangerStatusResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import type {
OidbAiVoiceListReq,
OidbAiVoiceListResp,
OidbAiVoiceReq,
OidbAiVoiceResp,
} from '@snowluma/proto-defs/oidb-actions/media';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { describe, expect, it } from 'vitest';
// Post-namespace migration: ExtrasApi forwards 6 OIDB cmds through
// namespaces under @snowluma/protocol/oidb-services/extras. Tests assert
// against bridge.sendRawPacket directly.
import { AiVoiceChatType, ExtrasApi } from '../../src/apis/extras';
import { mockBridge } from './_helpers';
function packResponse(body: Uint8Array) {
return {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(body),
};
}
describe('apis/extras / group todo (0xF90)', () => {
it.each([
['setGroupTodo', 'OidbSvcTrpcTcp.0xf90_1'] as const,
['completeGroupTodo', 'OidbSvcTrpcTcp.0xf90_2'] as const,
['cancelGroupTodo', 'OidbSvcTrpcTcp.0xf90_3'] as const,
])('%s dispatches the right subCmd with shared body', async (method, cmd) => {
const bridge = mockBridge();
const api = new ExtrasApi(bridge as any);
await (api as any)[method](12345, 9876543210n);
const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe(cmd);
const env = protobuf_decode<OidbBase<OidbGroupTodo>>(bytes);
expect(env.body).toEqual({ groupUin: 12345, msgSeq: 9876543210n });
});
});
describe('apis/extras / getStrangerStatus (0xFE1_2)', () => {
it('issues the FE1_2 query with key=27372', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { status: { value: 5n } } } }),
));
await new ExtrasApi(bridge as any).getStrangerStatus(100200);
const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0xfe1_2');
const env = protobuf_decode<OidbBase<OidbStrangerStatusReq>>(bytes);
expect(env.command).toBe(0xFE1);
expect(env.subCommand).toBe(2);
expect(env.body).toMatchObject({ uin: 100200, key: [{ key: 27372 }] });
});
it('low-band values (≤10) map to status*10 with ext_status=0', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { status: { value: 7n } } } }),
));
expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toEqual({ status: 70, ext_status: 0 });
});
it('high-band values decompose into the (0xff00 + (>>16 & 0xff)) status word', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { status: { value: 0x42F100n } } } }),
));
const status = await new ExtrasApi(bridge as any).getStrangerStatus(1);
expect(status).toEqual({ status: 10, ext_status: 0xF142 });
});
it('returns null when the runner throws (transport error)', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockRejectedValueOnce(new Error('boom'));
expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toBeNull();
});
it('returns null when the server omits the status field', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: {} }),
));
expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toBeNull();
});
});
describe('apis/extras / AI voice (0x929D / 0x929B)', () => {
it('fetchAiVoiceList sends 0x929D_0 and returns server content verbatim', async () => {
const bridge = mockBridge();
const fake = [
{ category: 'cute', voices: [{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://x' }] },
];
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbAiVoiceListResp>>({ body: { content: fake } } as any),
));
const out = await new ExtrasApi(bridge as any).fetchAiVoiceList(4242, AiVoiceChatType.Sound);
expect(out).toEqual(fake);
const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0x929d_0');
const env = protobuf_decode<OidbBase<OidbAiVoiceListReq>>(bytes);
expect(env.body).toEqual({ groupUin: 4242, chatType: 1 });
});
it('fetchAiVoiceList returns [] when server replies with no content', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbAiVoiceListResp>>({ body: {} }),
));
const out = await new ExtrasApi(bridge as any).fetchAiVoiceList(1, 1);
expect(out).toEqual([]);
});
it('fetchAiVoice retries while msgInfo is empty, returns the first IndexNode it sees', async () => {
const bridge = mockBridge();
const node = { fileUuid: 'uuid-1', subType: 1 };
bridge.sendRawPacket
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { statusCode: 2 } } as any)))
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [] } } as any })))
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })));
const out = await new ExtrasApi(bridge as any).fetchAiVoice(100, 'voice-id', 'hi', AiVoiceChatType.Sound);
expect(out).toMatchObject(node);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0x929b_0');
const env = protobuf_decode<OidbBase<OidbAiVoiceReq>>(bytes);
expect(env.body).toMatchObject({
groupUin: 100, voiceId: 'voice-id', text: 'hi', chatType: 1,
});
const sessionId = env.body?.session?.sessionId;
expect(typeof sessionId).toBe('number');
expect(sessionId).toBeGreaterThanOrEqual(0);
expect(sessionId).toBeLessThanOrEqual(0xFFFFFFFF);
});
it('fetchAiVoice throws after exhausting the retry budget', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValue(packResponse(
protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { statusCode: 1 } as any }),
));
await expect(new ExtrasApi(bridge as any).fetchAiVoice(1, 'v', 't', 1, 3)).rejects.toThrow(
/AI voice synthesis did not complete/,
);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
});
it('fetchAiVoice keeps the same sessionId across retries', async () => {
const bridge = mockBridge();
const node = { fileUuid: 'uuid', subType: 1 };
bridge.sendRawPacket
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: {} })))
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })));
await new ExtrasApi(bridge as any).fetchAiVoice(1, 'v', 't', 1);
const env1 = protobuf_decode<OidbBase<OidbAiVoiceReq>>(bridge.sendRawPacket.mock.calls[0]![1]);
const env2 = protobuf_decode<OidbBase<OidbAiVoiceReq>>(bridge.sendRawPacket.mock.calls[1]![1]);
expect(env1.body?.session?.sessionId).toBe(env2.body?.session?.sessionId);
});
});

View File

@@ -0,0 +1,168 @@
// Regression coverage for the file-inside-send_forward_msg bug.
//
// Symptom: caller put `{type:'file', file_id}` inside a forward node;
// the element-builder dropped it (`[ElemBuilder] BUG: {type:"file"}
// reached element-builder — must be split out at the OneBot layer`)
// because the live-send paths route files through dedicated methods
// (sendC2cFileMessage / sendGroupFileMessage), and the forward
// builder was naïvely calling buildSendElems with the same ctx. The
// forward upload succeeded but the bubble shipped without the file
// element.
//
// Fix: forward upload passes `forwardFake: true` on the SendContext.
// The element-builder honours that flag by emitting the receive-side
// shapes:
// * group file → transElem(elemType=24, GroupFileExtra)
// * c2c file → handled at the forward-builder level, written into
// `body.msgContent` as FileExtra { file: NotOnlineFile }
//
// These shapes are RECEIVE-side: the QQ-NT live-send pipeline rejects
// transElem(24) (result=79), but the long-msg upload service stores the
// gzipped protobuf verbatim and the recipient's msg-push decoder pulls
// the file entity back out via the normal path (rich-body-decoder.ts).
// Mirrors NapCat's `PacketMsgFileElement.{buildElement,buildContent}`
// split.
import { describe, expect, it, vi } from 'vitest';
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
encodeOidbEnv: vi.fn(() => new Uint8Array()),
decodeOidbEnv: vi.fn(() => ({ body: {} })),
}));
// `vi.mock` factories are hoisted above the imports — declare the spy
// inside a `vi.hoisted` block so it's available at the same moment.
// Declare parameter types on the fn so `mock.calls[0]` infers a tuple
// of [elements, ctx] instead of `[]`, which makes the destructuring
// a tsc error under strict tuple checking on CI.
const { buildSendElemsMock } = vi.hoisted(() => ({
buildSendElemsMock: vi.fn(async (_elements: unknown[], _ctx?: Record<string, unknown>) => []),
}));
vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: buildSendElemsMock,
}));
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import { protobuf_encode } from '@snowluma/proton';
import { ForwardApi } from '../../src/apis/forward';
import { mockBridge } from './_helpers';
function uploadResponseWithResId(resId: string) {
const encoded = protobuf_encode<SendLongMsgResp>({ result: { resId } });
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(encoded),
};
}
describe('actions/forward — file segment inside forward node', () => {
it('group forward sets forwardFake:true on the SendContext so transElem(24) is emitted', async () => {
// Group case: the file element rides on elems[] as transElem(24).
// The element-builder receives ctx.forwardFake=true so it knows to
// emit the receive-side shape instead of dropping the segment.
buildSendElemsMock.mockClear();
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-grp-file')) as any,
});
await new ForwardApi(bridge as any).upload([
{
userUin: 10001,
nickname: 'alice',
elements: [{ type: 'file', fileId: 'gfid-1', fileName: 'a.txt', fileSize: 99 } as any],
},
], 12345);
expect(buildSendElemsMock).toHaveBeenCalled();
const [, ctx] = buildSendElemsMock.mock.calls[0]!;
expect(ctx).toMatchObject({ groupId: 12345, forwardFake: true });
});
it('c2c forward writes the file as msgContent (FileExtra { file: NotOnlineFile })', async () => {
// Private case: c2c files live on `body.msgContent`, not in elems[].
// The forward-builder pulls the file segment off and synthesises a
// FileExtra payload so the recipient's decoder (which reads
// msgContent first) renders the file bubble.
buildSendElemsMock.mockClear();
let captured: Uint8Array | undefined;
const bridge = mockBridge({
sendRawPacket: vi.fn(async (_cmd: string, body: Uint8Array) => {
captured = body;
return uploadResponseWithResId('res-c2c-file');
}) as any,
// Inline fields cover everything we need; cache lookup must not be
// required for the path to work.
recallUploadedFile: vi.fn(() => undefined),
});
await new ForwardApi(bridge as any).upload([
{
userUin: 10001,
nickname: 'alice',
elements: [{
type: 'file',
fileId: 'pfid-1',
fileName: 'invoice.pdf',
fileSize: 4096,
md5Hex: 'aabbccddeeff00112233445566778899',
fileHash: 'srv-hash-abc',
} as any],
},
], undefined, 67890);
expect(buildSendElemsMock).toHaveBeenCalled();
const [, ctx] = buildSendElemsMock.mock.calls[0]!;
expect(ctx).toMatchObject({ forwardFake: true });
expect(ctx?.groupId).toBeUndefined();
// Spot-check that the upload body carries the file metadata. The
// payload is gzipped + protobuf-wrapped, so we just verify the
// raw filename string survived — that's enough to confirm the
// FileExtra branch ran (a "missing file" regression would drop
// these bytes entirely).
expect(captured).toBeDefined();
const flat = Buffer.from(captured!).toString('binary');
// The filename gets gzipped, so we can't substring-search; instead
// assert the body is large enough that the FileExtra wasn't elided.
// (A name-only forward with no msgContent runs ~80-100 bytes; with
// the FileExtra blob it's noticeably larger.)
expect(flat.length).toBeGreaterThan(80);
});
it('c2c forward falls back to the upload metadata cache when inline fields are missing', async () => {
// The OneBot caller often passes only `file_id` — the rest comes
// from the bridge's uploaded-file cache. This is the same
// hydration path send_private_msg uses; the forward builder must
// honour it too or every cached-only forward ships a 0 B bubble.
buildSendElemsMock.mockClear();
const recallUploadedFile = vi.fn((id: string) => id === 'pfid-cached' ? {
fileId: 'pfid-cached',
scope: 'private' as const,
userId: 67890,
fileName: 'cached-name.zip',
fileSize: 8192,
fileMd5: Buffer.from('ffeeddccbbaa99887766554433221100', 'hex'),
fileSha1: new Uint8Array(20),
fileHash: 'cached-hash',
rememberedAt: 0,
} : undefined);
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-cache')) as any,
recallUploadedFile,
});
await new ForwardApi(bridge as any).upload([{
userUin: 10001,
nickname: 'alice',
elements: [{ type: 'file', fileId: 'pfid-cached' } as any],
}], undefined, 67890);
expect(recallUploadedFile).toHaveBeenCalledWith('pfid-cached');
});
});

View File

@@ -0,0 +1,181 @@
// Wire-byte alignment regression for nested forward upload — verifies
// that the OUTER LongMsgResult's `actions[]` carries:
// - `{actionCommand: 'MultiMsg', actionData.msgBody: <outer nodes>}`
// - `{actionCommand: <inner.uuid>, actionData.msgBody: <inner nodes>}`
// AND that the same uuid appears as `meta.detail.uniseq` inside the
// LightApp `com.tencent.multimsg` JSON of the outer's preview element
// pointing at the inner res_id.
//
// Without this alignment the QQ-NT recipient has no way to walk the
// piggyback — they see the inner preview's resid, look for a matching
// uniseq among the actions, find none, and either fall back to a fresh
// server fetch (extra latency) or render an empty bubble.
//
// Reference impls cross-checked:
// dev/NapCatQQ/.../SendMsg.ts:208-347
// dev/Lagrange.Core/.../Message/Entity/MultiMsgEntity.cs:43-115
// dev/NapCatQQ/.../helper/forward-msg-builder.ts:52-122
import type { Elem } from '@snowluma/proto-defs/element';
import type { LongMsgResult, SendLongMsgReq, SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { describe, expect, it, vi } from 'vitest';
import { gunzipSync, inflateSync } from 'zlib';
// Don't mock element-builder — we WANT the real forward preview
// element to land in the encoded wire bytes so we can verify the
// `uniseq` round-trip against the piggyback's `actionCommand`.
// Mock highway uploads only — they're irrelevant for text-only nodes
// but the import would otherwise pull in the native ffmpeg addon.
vi.mock('@snowluma/protocol/highway/image-upload', () => ({
uploadImageMsgInfo: vi.fn(async () => new Uint8Array()),
}));
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({
uploadPttMsgInfo: vi.fn(async () => new Uint8Array()),
}));
vi.mock('@snowluma/protocol/highway/video-upload', () => ({
uploadVideoMsgInfo: vi.fn(async () => new Uint8Array()),
}));
import { ForwardApi } from '../../src/apis/forward';
import { mockBridge } from './_helpers';
function uploadResponseWithResId(resId: string) {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<SendLongMsgResp>({ result: { resId } })),
};
}
function decodeOuterLongMsg(rawBytes: Uint8Array): LongMsgResult {
const env = protobuf_decode<SendLongMsgReq>(rawBytes);
const payload = env.info?.payload;
if (!(payload instanceof Uint8Array)) throw new Error('payload missing on the SendLongMsgReq');
return protobuf_decode<LongMsgResult>(gunzipSync(Buffer.from(payload)));
}
function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: string; app?: string } | null {
for (const body of msgBody) {
const elems: Elem[] = body.body?.richText?.elems ?? [];
for (const elem of elems) {
if (elem.lightApp?.data && elem.lightApp.data.length > 1) {
const data = elem.lightApp.data;
if (data[0] !== 0x01) continue;
try {
const json = inflateSync(Buffer.from(data.subarray(1))).toString('utf8');
const parsed = JSON.parse(json);
if (parsed?.app === 'com.tencent.multimsg') {
return {
app: parsed.app,
resid: parsed.meta?.detail?.resid,
uniseq: parsed.meta?.detail?.uniseq,
};
}
} catch { /* ignore */ }
}
}
}
return null;
}
describe('forward / nested upload wire alignment', () => {
it('outer LongMsgResult contains both MultiMsg and the inner uuid piggyback action', async () => {
// Inner upload returns inner-res; outer upload returns outer-res.
const responses = ['inner-res', 'outer-res'];
const sendRawPacket = vi.fn(async () =>
uploadResponseWithResId(responses.shift()!)) as any;
const bridge = mockBridge({ sendRawPacket });
const resId = await new ForwardApi(bridge as any).upload([
{
userUin: 111, nickname: 'outer', elements: [],
innerForward: [
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] },
],
},
]);
expect(resId).toBe('outer-res');
expect(sendRawPacket).toHaveBeenCalledTimes(2);
// Second call is the OUTER's upload (the inner went first).
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
const outerLongMsg = decodeOuterLongMsg(outerBytes);
const actions = outerLongMsg.action ?? [];
expect(actions).toHaveLength(2);
expect(actions[0]!.actionCommand).toBe('MultiMsg');
// The second action carries the inner's msgBody under a uuid
// actionCommand (NOT 'MultiMsg').
const piggybackUuid = actions[1]!.actionCommand!;
expect(piggybackUuid).not.toBe('MultiMsg');
expect(piggybackUuid).toMatch(/^[0-9a-f-]{36}$/i);
expect(actions[1]!.actionData?.msgBody?.length ?? 0).toBeGreaterThan(0);
});
it('outer preview LightApp uniseq matches the piggyback actionCommand uuid', async () => {
// This is the alignment bug: without it the QQ-NT receiver
// can't link the inner preview to its piggyback in actions[].
const responses = ['inner-res-A', 'outer-res-A'];
const sendRawPacket = vi.fn(async () =>
uploadResponseWithResId(responses.shift()!)) as any;
const bridge = mockBridge({ sendRawPacket });
await new ForwardApi(bridge as any).upload([
{
userUin: 111, nickname: 'outer', elements: [],
innerForward: [
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] },
],
},
]);
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
const outerLongMsg = decodeOuterLongMsg(outerBytes);
const piggybackUuid = outerLongMsg.action![1]!.actionCommand!;
const outerMsgBody = outerLongMsg.action![0]!.actionData!.msgBody!;
const preview = findLightAppJson(outerMsgBody);
expect(preview).not.toBeNull();
expect(preview!.app).toBe('com.tencent.multimsg');
expect(preview!.resid).toBe('inner-res-A');
expect(preview!.uniseq).toBe(piggybackUuid);
});
it('three-deep nesting: outermost action[] carries 1+2 entries (MultiMsg + 2 piggybacks)', async () => {
// The middle level's upload produces 1 MultiMsg + 1 piggyback
// (for the deepest). The outermost level then concatenates its
// own MultiMsg + the middle's piggyback set, so action[].length = 3.
const responses = ['deepest', 'middle', 'outermost'];
const sendRawPacket = vi.fn(async () =>
uploadResponseWithResId(responses.shift()!)) as any;
const bridge = mockBridge({ sendRawPacket });
await new ForwardApi(bridge as any).upload([
{
userUin: 1, nickname: 'L1', elements: [],
innerForward: [{
userUin: 2, nickname: 'L2', elements: [],
innerForward: [
{ userUin: 3, nickname: 'L3', elements: [{ type: 'text', text: 'deep' }] },
],
}],
},
]);
expect(sendRawPacket).toHaveBeenCalledTimes(3);
const outermostBytes = sendRawPacket.mock.calls[2]![1] as Uint8Array;
const outermost = decodeOuterLongMsg(outermostBytes);
expect(outermost.action).toHaveLength(3);
expect(outermost.action![0]!.actionCommand).toBe('MultiMsg');
expect(outermost.action![1]!.actionCommand).not.toBe('MultiMsg');
expect(outermost.action![2]!.actionCommand).not.toBe('MultiMsg');
expect(outermost.action![1]!.actionCommand).not.toBe(outermost.action![2]!.actionCommand);
});
});

View File

@@ -0,0 +1,153 @@
import { describe, expect, it, vi } from 'vitest';
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
encodeOidbEnv: vi.fn(() => new Uint8Array()),
decodeOidbEnv: vi.fn(() => ({ body: {} })),
}));
// element-builder reaches into protoEncode with element-specific schemas
// that we don't want to construct manually in tests; stub it to return
// a benign placeholder.
vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: vi.fn(async () => []),
}));
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import { protobuf_encode } from '@snowluma/proton';
import { ForwardApi } from '../../src/apis/forward';
import { mockBridge } from './_helpers';
function uploadResponseWithResId(resId: string) {
const encoded = protobuf_encode<SendLongMsgResp>({ result: { resId } });
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(encoded),
};
}
describe('actions/forward', () => {
it('uploadForwardNodes rejects empty arrays', async () => {
const bridge = mockBridge();
await expect(new ForwardApi(bridge as any).upload([]))
.rejects.toThrow(/required/);
});
it('uploadForwardNodes dispatches to SsoSendLongMsg with a non-empty body and returns the res_id', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-001')) as any,
});
const resId = await new ForwardApi(bridge as any).upload([
{ userUin: 10001, nickname: 'alice', elements: [] },
]);
expect(resId).toBe('res-001');
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
const [serviceCmd, body] = bridge.sendRawPacket.mock.calls[0]!;
expect(serviceCmd).toBe('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg');
expect((body as Uint8Array).length).toBeGreaterThan(0);
});
it('uploadForwardNodes throws when sendRawPacket reports failure', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => ({
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'pipe broken', responseData: null,
})) as any,
});
await expect(new ForwardApi(bridge as any).upload([
{ userUin: 10001, nickname: 'a', elements: [] },
])).rejects.toThrow(/pipe broken/);
});
it('uploadForwardNodes throws when the response is missing res_id', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('')) as any,
});
await expect(new ForwardApi(bridge as any).upload([
{ userUin: 10001, nickname: 'a', elements: [] },
])).rejects.toThrow(/missing res_id/);
});
it('fetchForwardNodes serves from cache after a successful upload (no second sendRawPacket)', async () => {
const sendRawPacket = vi.fn(async () => uploadResponseWithResId('res-cache')) as any;
const bridge = mockBridge({ sendRawPacket });
const nodes = [
{ userUin: 10001, nickname: 'alice', elements: [] },
{ userUin: 10002, nickname: 'bob', elements: [] },
];
const resId = await new ForwardApi(bridge as any).upload(nodes);
expect(resId).toBe('res-cache');
const fetched = await new ForwardApi(bridge as any).fetch('res-cache');
// Same nicknames + uins; elements have been deep-copied so the shape
// is preserved but the array reference is different.
expect(fetched).toHaveLength(2);
expect(fetched.map((n: { nickname: string }) => n.nickname)).toEqual(['alice', 'bob']);
expect(sendRawPacket).toHaveBeenCalledTimes(1);
});
it('fetchForwardNodes throws on transport failure when nothing is cached', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => ({
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'down', responseData: null,
})) as any,
});
await expect(new ForwardApi(bridge as any).fetch('cold-cache-miss'))
.rejects.toThrow(/download forward message failed|down/);
});
it('uploadForwardNodes recursively uploads nested innerForward chains (NapCat piggyback model)', async () => {
// Regression: nested forward needs the inner chain to be uploaded
// first (so we have its res_id for the outer ARK preview), AND
// the inner level's msgBody to be carried up to the outermost
// long-msg upload as an extra `actionCommand` slot keyed on a
// uuid. Matches `dev/NapCatQQ/.../SendMsg.uploadForwardedNodesPacket`
// — the receiver gets the whole tree from a single fetch instead
// of resolving each layer's res_id separately.
const responses = ['inner-res', 'outer-res'];
const sendRawPacket = vi.fn(async () => uploadResponseWithResId(responses.shift()!)) as any;
const bridge = mockBridge({ sendRawPacket });
const resId = await new ForwardApi(bridge as any).upload([
{
userUin: 111,
nickname: 'outer',
elements: [],
innerForward: [
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] },
],
},
]);
// Two server roundtrips: one for the inner chain, then one for
// the outer (which piggybacks the inner msgBody onto its actions
// array). The outer res_id is what the caller gets back.
expect(resId).toBe('outer-res');
expect(sendRawPacket).toHaveBeenCalledTimes(2);
});
it('uploadForwardNodes leaves flat (non-nested) sends at a single roundtrip', async () => {
// Backwards-compat: the common case (no inner forward) must still
// be one SsoSendLongMsg call. Without this we'd double upload
// every regular forward send.
const sendRawPacket = vi.fn(async () => uploadResponseWithResId('flat-res')) as any;
const bridge = mockBridge({ sendRawPacket });
const resId = await new ForwardApi(bridge as any).upload([
{ userUin: 10001, nickname: 'a', elements: [{ type: 'text', text: 'hello' }] },
{ userUin: 10002, nickname: 'b', elements: [{ type: 'text', text: 'world' }] },
]);
expect(resId).toBe('flat-res');
expect(sendRawPacket).toHaveBeenCalledOnce();
});
});

Some files were not shown because too many files have changed in this diff Show More