Compare commits

..

196 Commits
v1.8.2 ... 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
airline233
b441647df4 feat(http-server): support parse content-type of urlencoded 2026-05-17 15:27:43 +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
H3CoF6
b176e929b9 feat: implement upload group avatar 2026-05-14 04:09:55 +08:00
522 changed files with 34603 additions and 12757 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

@@ -110,10 +110,6 @@ jobs:
SNOWLUMA_TARGET: ${{ matrix.target }}
run: pnpm run build:all
- name: Bundle runtime dependencies
working-directory: dist
run: npm install --omit=dev
# Naming convention:
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node >= 22

1
.gitignore vendored
View File

@@ -11,6 +11,7 @@ dist/
/config/
/data/
logs/
# macOS metadata
.DS_Store

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)

View File

@@ -1,3 +1,491 @@
# V2.0.0 前计划
- [x] 统一Uid/Uin提供一个Service,并实现Sqlite持久化,群/好友/入群和好友申请 获取新Uid。
- [ ] 优化Debug体验,实现免打包Debug,同时数据目录正确。
# 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`)

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,6 +1,6 @@
{
"name": "snowluma-monorepo",
"version": "1.8.2",
"version": "1.9.2",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -15,21 +15,34 @@
"test": "pnpm --filter @snowluma/core test",
"test:watch": "pnpm --filter @snowluma/core test:watch",
"typecheck": "pnpm -r --if-present typecheck",
"lint": "pnpm -r --if-present lint",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"start": "node dist/index.mjs",
"bump": "node tools/bump-version.mjs",
"release": "node tools/release.mjs"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@vitest/coverage-istanbul": "4.1.4",
"@vitest/coverage-v8": "^4.1.4",
"cross-env": "^10.1.0",
"typescript": "catalog:"
"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": {

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

@@ -1,26 +1,40 @@
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 type { BridgeManager } from '../bridge/manager';
import type { PacketSink } from '../protocol/types';
import { createLogger, type Logger } from '../utils/logger';
import { HookSession, type HookSessionDeps } from './hook-session';
import {
injectHookProcess,
listHookProcesses,
unloadHookProcess,
type HookProcessBaseInfo,
} from './injector';
import { HookSession, type HookSessionDeps } from './hook-session';
import { PipeWatcher } from './pipe-watcher';
import { QqHookClient } from './qq-hook-client';
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
import type { HookProcessInfo } from './types';
export type { HookProcessInfo, HookProcessStatus } from './types';
export type { HookProcessBaseInfo } from './injector';
/**
* 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 = {
bridgeManager: BridgeManager;
sink: HookSink;
/** Sink for parsed packets from any live HookSession. Defaults to
* `bridgeManager.onPacket` — every packet flows straight into the
* per-UIN bridge dispatcher with no intermediate event emitter. */
* `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'];
@@ -46,7 +60,7 @@ export type HookManagerDeps = {
* Responsibilities:
* - Route user commands (load/unload/refresh) to the matching session.
* - Route watcher diff events to the matching session.
* - Forward session events ('login' / 'disconnected') to BridgeManager.
* - 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).
*
@@ -55,7 +69,7 @@ export type HookManagerDeps = {
* real QQ.exe or a native addon.
*/
export class HookManager {
private readonly bridgeManager: BridgeManager;
private readonly sink: HookSink;
private readonly onPacket: PacketSink;
private readonly injector: HookSessionDeps['injector'];
private readonly makeClient: HookSessionDeps['makeClient'];
@@ -70,8 +84,8 @@ export class HookManager {
private disposed = false;
constructor(deps: HookManagerDeps) {
this.bridgeManager = deps.bridgeManager;
this.onPacket = deps.onPacket ?? ((pkt) => deps.bridgeManager.onPacket(pkt));
this.sink = deps.sink;
this.onPacket = deps.onPacket ?? ((pkt) => deps.sink.onPacket(pkt));
this.log = deps.log ?? createLogger('Hook');
this.injector = deps.injector ?? {
@@ -147,6 +161,11 @@ export class HookManager {
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;
@@ -191,14 +210,25 @@ export class HookManager {
const session = this.sessions.get(pid);
if (session) session.onPipeDown();
});
// After every tick, retry sessions that are stuck in 'connecting'
// 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.
// 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' && this.pipeWatcher.isPipeLive(session.pid)) {
if ((session.status === 'connecting' || session.status === 'disconnected')
&& this.pipeWatcher.isPipeLive(session.pid)) {
session.onPipeUp();
}
}
@@ -219,10 +249,10 @@ export class HookManager {
session.attachProcessInfo({ name: defaultProcessName() });
session.on('login', (uin: string, sender) => {
this.bridgeManager.onHookLogin(pid, uin, sender);
this.sink.onHookLogin(pid, uin, sender);
});
session.on('disconnected', (wasLoggedIn: boolean) => {
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
if (wasLoggedIn) this.sink.onPidDisconnected(pid);
});
session.on('disposed', () => {
this.sessions.delete(pid);
@@ -280,3 +310,7 @@ export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
}
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

@@ -1,7 +1,6 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { PacketSink } from '@snowluma/common/protocol-types';
import { EventEmitter } from 'events';
import type { PacketSender } from '../protocol/packet-sender';
import type { PacketSink } from '../protocol/types';
import { createLogger, type Logger } from '../utils/logger';
import { HookPacketClient } from './hook-packet-client';
import type { HookInjectResult } from './injector';
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
@@ -14,10 +13,15 @@ export type HookSessionDeps = {
};
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. */
pipeWatcher: { isPipeLive: (pid: number) => boolean };
/** Sink for parsed packets. Called with the BridgeManager-shaped
* PacketInfo for every packet received while logged in. If omitted,
* 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;
@@ -31,7 +35,7 @@ export type HookSessionDeps = {
* promise chain so user clicks (load/unload/refresh) and watcher-driven
* events (onPipeUp/onPipeDown) never interleave.
*
* Communication: emits high-level events instead of calling BridgeManager
* Communication: emits high-level events instead of calling the sink
* directly, so HookManager forwards them and tests can attach spies.
*
* Emitted events:
@@ -254,7 +258,11 @@ export class HookSession extends EventEmitter {
this._uin = '0';
// Verify the unload took: if the pipe is still up the DLL is still
// resident. Drop back to 'connecting' and let the watcher reconnect.
// 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);
@@ -398,7 +406,7 @@ export class HookSession extends EventEmitter {
const uin = packet.uin || this._uin;
if (!isRealUin(uin)) return;
if (!this.onPacket) return;
// Re-shape the hook-client wire packet into BridgeManager's PacketInfo
// 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).

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

@@ -55,12 +55,13 @@ function defaultProcessName(): string {
function nativeSearchDirs(): string[] {
// Several layouts must be supported:
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
// 2. Repo bundled build (dist/index.mjs): __dirname=<root>/dist, native at <root>/dist/native
// 3. Dev via tsx (packages/core/src/hook/injector.ts): __dirname=<root>/packages/core/src/hook
// 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, '..', '..', '..', 'runtime', 'native'),
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
path.resolve(process.cwd(), 'dist', 'native'),
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
];

View File

@@ -1,5 +1,5 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import { EventEmitter } from 'events';
import { createLogger, type Logger } from '../utils/logger';
import type { HookProcessBaseInfo } from './injector';
const DEFAULT_INTERVAL_MS = 1500;

View File

@@ -1,8 +1,8 @@
import { EventEmitter } from 'events';
import { promises as fs } from 'fs';
import net from 'net';
import os from 'os';
import path from 'path';
import { promises as fs } from 'fs';
import { EventEmitter } from 'events';
export const PIPE_MAGIC = 0x31504851;
export const PIPE_VERSION = 1;
@@ -235,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]);
@@ -513,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;
@@ -624,7 +624,7 @@ export class QqHookClient extends EventEmitter {
else resolve();
});
}));
this.controlWriteChain = writePromise.catch(() => {});
this.controlWriteChain = writePromise.catch(() => { });
return writePromise;
}

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

@@ -1,11 +1,5 @@
import type { HookProcessBaseInfo } from './injector';
/**
* Lifecycle status of a single per-PID HookSession.
*
* Transitions live inside HookSession; this union only enumerates the
* states visible to API callers (WebUI, manager.listProcesses()).
*/
export type HookProcessStatus =
| 'available'
| 'loading'

View File

@@ -3,12 +3,12 @@ import { EventEmitter } from 'events';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { HookManager, shouldAutoLoadPid } from '../src/hook/hook-manager';
import { PipeWatcher } from '../src/hook/pipe-watcher';
import type { ManualMapHandle } from '../src/hook/injector';
import type { BridgeManager } from '../src/bridge/manager';
import type { QqHookClient } from '../src/hook/qq-hook-client';
import { createLogger } from '../src/utils/logger';
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));
@@ -37,13 +37,13 @@ function makeManager(opts: {
(c as any).close = () => { (c as any).isClosed = true; };
return c as unknown as QqHookClient;
});
const bridgeManager = {
const sink = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManager;
} as unknown as HookSink;
const manager = new HookManager({
bridgeManager,
sink,
pipeWatcher,
injector: { inject, unload },
makeClient,

View File

@@ -6,11 +6,11 @@
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookManager } from '../src/hook/hook-manager';
import { PipeWatcher } from '../src/hook/pipe-watcher';
import type { ManualMapHandle } from '../src/hook/injector';
import type { BridgeManager } from '../src/bridge/manager';
import type { QqHookClient } from '../src/hook/qq-hook-client';
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));
@@ -41,14 +41,14 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
intervalMs: 60_000, // manual ticks only
});
const bridgeManager = {
const sink = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManager;
} as unknown as HookSink;
const manager = new HookManager({
bridgeManager,
sink,
pipeWatcher,
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
@@ -82,9 +82,9 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
// The "QQ never logs in" hypothesis: BridgeManager should never have
// been told about a login or a disconnect.
expect(bridgeManager.onHookLogin).not.toHaveBeenCalled();
expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled();
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
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);

View File

@@ -17,9 +17,9 @@
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookSession } from '../src/hook/hook-session';
import type { ManualMapHandle } from '../src/hook/injector';
import type { QqHookClient } from '../src/hook/qq-hook-client';
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 };

View File

@@ -1,9 +1,9 @@
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookSession } from '../src/hook/hook-session';
import type { ManualMapHandle } from '../src/hook/injector';
import type { QqHookClient, QqHookPacket } from '../src/hook/qq-hook-client';
import type { PacketSink } from '../src/protocol/types';
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 };
@@ -254,6 +254,34 @@ describe('HookSession — 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', () => {

View File

@@ -1,8 +1,6 @@
import { describe, it, expect } from 'vitest';
import { PipeWatcher } from '../src/hook/pipe-watcher';
import type { HookProcessBaseInfo } from '../src/hook/injector';
const flush = () => new Promise<void>(r => setImmediate(r));
import { PipeWatcher } from '../src/pipe-watcher';
import type { HookProcessBaseInfo } from '../src/injector';
function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set<number> }) {
let processes = initial.processes;

View File

@@ -2,7 +2,7 @@ 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/hook/qq-hook-client';
import { listLiveLinuxPipePids } from '../src/qq-hook-client';
let tmpDir: string | null = null;

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

@@ -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,9 +8,4 @@ export interface PacketInfo {
fromClient: boolean;
body: Uint8Array;
}
/**
* Packet sink injected into HookSession / HookManager. The default
* wiring forwards to BridgeManager.onPacket, but tests inject spies.
*/
export type PacketSink = (packet: PacketInfo) => void;

View File

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

View File

@@ -1,10 +1,36 @@
{
"name": "@snowluma/core",
"version": "1.8.2",
"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",
@@ -14,6 +40,14 @@
"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": {

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

@@ -1,14 +1,6 @@
// Shared private helpers for the action modules. None of this is part
// of the public Bridge API; keeping it here avoids re-importing the
// same five-line utility from every themed file.
import type { Bridge } from '../bridge';
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
/**
* Coerce numbers, strings, and bigints to a plain integer.
* Returns 0 for anything we can't interpret — every action that
* threads this through OIDB has an explicit `<=0` validation later.
*/
export function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'bigint') {
@@ -40,7 +32,7 @@ export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown
* `selfProfile`; forward/profile actions need this fast path before
* warmup completes.
*/
export async function resolveSelfUid(bridge: Bridge): Promise<string> {
export async function resolveSelfUid(bridge: BridgeContext): Promise<string> {
let selfUid = bridge.identity.selfUid;
if (selfUid) return selfUid;

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

@@ -1,155 +0,0 @@
// Tier-2 napcat-parity actions ported as pure oidb calls. Each function
// here corresponds to one napcat PacketApi.pkt.operation.* entry; the
// schemas live in proto/oidb-action.ts. Nothing in this file touches
// the NTQQ NodeIKernel — every wire trip is one runOidb round-trip.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
OidbGroupTodoSchema,
OidbStrangerStatusReqSchema,
OidbStrangerStatusRespSchema,
OidbAiVoiceListReqSchema,
OidbAiVoiceListRespSchema,
OidbAiVoiceReqSchema,
OidbAiVoiceRespSchema,
} from '../proto/oidb-action';
import type { MediaIndexNode } from './shared';
// ─────────────── Group todo (0xF90) ───────────────
export async function setGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf90_1',
oidbCmd: 0xF90, subCmd: 1,
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
});
}
export async function completeGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf90_2',
oidbCmd: 0xF90, subCmd: 2,
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
});
}
export async function cancelGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf90_3',
oidbCmd: 0xF90, subCmd: 3,
request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } },
});
}
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
export interface StrangerStatus {
status: number;
ext_status: number;
}
/**
* Mirror napcat's GetStrangerStatus: decode the extBigInt status word.
* Values ≤10 fold into a 10×status; everything else is split into the
* high-byte / low-byte ext_status the OneBot dialect uses.
*
* Returns null on transport / decode failure rather than throwing, so
* the OneBot action can produce a clean retcode without try/catch
* gymnastics.
*/
export async function getStrangerStatus(bridge: Bridge, uin: number): Promise<StrangerStatus | null> {
try {
const resp = await runOidb<{ data?: { status?: { value?: bigint | number } } }>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
oidbCmd: 0xFE1, subCmd: 2,
request: {
schema: OidbStrangerStatusReqSchema,
value: { uin, key: [{ key: 27372 }] },
},
response: { schema: OidbStrangerStatusRespSchema },
});
const raw = resp?.data?.status?.value;
if (raw === undefined || raw === null) return null;
const extBig = typeof raw === 'bigint' ? raw : BigInt(raw);
if (extBig <= 10n) {
return { status: Number(extBig) * 10, ext_status: 0 };
}
const status = Number((extBig & 0xff00n) + ((extBig >> 16n) & 0xffn));
return { status: 10, ext_status: status };
} catch {
return null;
}
}
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
export const AiVoiceChatType = {
Unknown: 0,
Sound: 1,
Sing: 2,
} as const;
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
export interface AiVoiceItem {
voiceId: string;
voiceDisplayName: string;
voiceExampleUrl: string;
}
export interface AiVoiceCategory {
category: string;
voices: AiVoiceItem[];
}
export async function fetchAiVoiceList(
bridge: Bridge,
groupId: number,
chatType: AiVoiceChatType,
): Promise<AiVoiceCategory[]> {
const resp = await runOidb<{ content?: AiVoiceCategory[] }>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x929d_0',
oidbCmd: 0x929D, subCmd: 0,
request: { schema: OidbAiVoiceListReqSchema, value: { groupUin: groupId, chatType } },
response: { schema: OidbAiVoiceListRespSchema },
});
return resp?.content ?? [];
}
/**
* 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
* `bridge.fetchGroupPttUrlByNode`, which already handles every other
* download-URL fetch in SnowLuma.
*/
export async function fetchAiVoice(
bridge: Bridge,
groupId: number,
voiceId: string,
text: string,
chatType: AiVoiceChatType,
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 resp = await runOidb<{
statusCode?: number;
msgInfo?: { msgInfoBody?: Array<{ index?: MediaIndexNode }> };
}>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x929b_0',
oidbCmd: 0x929B, subCmd: 0,
request: {
schema: OidbAiVoiceReqSchema,
value: { groupUin: groupId, voiceId, text, chatType, session: { sessionId } },
},
response: { schema: OidbAiVoiceRespSchema },
});
const node = resp?.msgInfo?.msgInfoBody?.[0]?.index;
if (node) return node;
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
}

View File

@@ -1,241 +0,0 @@
// Forward-message upload / download via the long-message service.
// Uses gzipped protobufs over `trpc.group.long_msg_interface`.
// An in-memory cache keeps res_ids stable across rapid re-fetches
// from the same OneBot client (avoids re-decoding the same payload).
import type { Bridge } from '../bridge';
import { gunzipSync, gzipSync } from 'zlib';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { buildSendElems } from '../element-builder';
import { parseMsgPush } from '../msg-push';
import type { ForwardNodePayload } from '../events';
import type { PacketInfo } from '../../protocol/types';
import {
LongMsgResultSchema,
RecvLongMsgReqSchema,
RecvLongMsgRespSchema,
SendLongMsgReqSchema,
SendLongMsgRespSchema,
} from '../proto/longmsg';
import { PushMsgSchema } from '../proto/message';
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[]>();
async function buildForwardPushBody(
bridge: Bridge,
node: ForwardNodePayload,
groupId?: number,
): Promise<Record<string, unknown>> {
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);
const sendCtx = groupId !== undefined
? { bridge, groupId }
: { bridge };
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;
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,
},
},
};
}
export async function uploadForwardNodes(bridge: Bridge, nodes: ForwardNodePayload[], groupId?: number): Promise<string> {
if (!Array.isArray(nodes) || nodes.length === 0) {
throw new Error('forward nodes are required');
}
const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node, groupId)));
const longMsgResult = protoEncode({
action: [
{
actionCommand: 'MultiMsg',
actionData: { msgBody: msgBody as any },
},
],
}, LongMsgResultSchema);
const selfUid = await resolveSelfUid(bridge);
const info: any = {
type: groupId ? 3 : 1,
uid: { uid: groupId ? String(groupId) : selfUid },
payload: gzipSync(Buffer.from(longMsgResult)),
};
if (groupId) info.groupUin = groupId;
const request = protoEncode({
info,
settings: {
field1: 4,
field2: 1,
field3: 7,
field4: 0,
},
}, SendLongMsgReqSchema);
const result = await bridge.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 = protoDecode(result.responseData, SendLongMsgRespSchema);
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, nodes.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;
}
export async function fetchForwardNodes(bridge: Bridge, resId: string): Promise<ForwardNodePayload[]> {
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 = protoEncode({
info: {
uid: { uid: selfUid },
resId,
acquire: true,
},
settings: {
field1: 2,
field2: 0,
field3: 0,
field4: 0,
},
}, RecvLongMsgReqSchema);
const result = await bridge.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 = protoDecode(result.responseData, RecvLongMsgRespSchema);
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 = protoDecode(inflate, LongMsgResultSchema);
const action = longMsg?.action?.find((item: any) => item?.actionCommand === 'MultiMsg');
const msgBodyList = Array.isArray(action?.actionData?.msgBody) ? action.actionData.msgBody : [];
const nodes: ForwardNodePayload[] = [];
for (const msgBody of msgBodyList) {
const wrapped = protoEncode({ message: msgBody }, PushMsgSchema);
const pkt: PacketInfo = {
pid: 0,
uin: bridge.identity.uin,
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
seqId: 0,
retCode: 0,
fromClient: false,
body: wrapped,
};
const events = parseMsgPush(pkt, bridge.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') {
nodes.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') {
nodes.push({
userUin: event.senderUin,
nickname: event.senderNick,
elements: event.elements,
time: event.time,
msgId: event.msgId,
msgSeq: event.msgSeq,
messageType: 'private',
});
} else {
nodes.push({
userUin: event.senderUin,
nickname: event.senderNick,
elements: event.elements,
time: event.time,
msgSeq: event.msgSeq,
groupId: event.groupId,
messageType: 'private',
});
}
}
if (nodes.length > 0) {
forwardResCache.set(resId, nodes.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
})));
}
return nodes;
}

View File

@@ -1,64 +0,0 @@
// Friend-list operations: accept/reject add request, delete, set the
// local remark label. Each one resolves a UID first because the OIDB
// protocol uses opaque UIDs rather than QQ uin numbers.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
OidbDeleteFriendSchema,
OidbFriendRequestActionSchema,
OidbSetFriendRemarkSchema,
} from '../proto/oidb-action';
export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise<void> {
let targetUid = uidOrFlag;
if (/^\d+$/.test(uidOrFlag)) {
targetUid = await bridge.resolveUserUid(parseInt(uidOrFlag, 10));
}
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xb5d_44',
oidbCmd: 0xB5D, subCmd: 44,
request: { schema: OidbFriendRequestActionSchema, value: { accept: approve ? 3 : 5, targetUid } },
});
}
export async function deleteFriend(bridge: Bridge, userId: number, block = false): Promise<void> {
const targetUid = await bridge.resolveUserUid(userId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x126b_0',
oidbCmd: 0x126B, subCmd: 0,
request: {
schema: OidbDeleteFriendSchema,
value: {
field1: {
targetUid,
field2: {
field1: 130,
field2: 109,
field3: {
field1: 8,
field2: 8,
field3: 50,
},
},
block,
field4: false,
},
},
},
});
// 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 bridge.fetchFriendList(); } catch { /* ignore */ }
}
export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise<void> {
const uid = await bridge.resolveUserUid(userId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xb6e_2',
oidbCmd: 0xB6E, subCmd: 2,
request: { schema: OidbSetFriendRemarkSchema, value: { targetUid: uid, remark } },
});
}

View File

@@ -1,216 +0,0 @@
// Group admin actions: mute/kick/leave/role/profile + join-request approval.
// Every function ultimately routes through one OIDB schema; the function
// names match the OneBot action names (set_group_kick, set_group_ban, ...)
// so callers can grep across the two layers.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
Oidb0x89a_0AddOptionSchema,
Oidb0x89a_0SearchSchema,
Oidb0x8a0ReqSchema,
Oidb0x8a7ReqSchema,
Oidb0x8a7RespSchema,
OidbGroupRequestActionSchema,
OidbKickMemberSchema,
OidbLeaveGroupSchema,
OidbMuteAllSchema,
OidbMuteMemberSchema,
OidbRenameGroupSchema,
OidbRenameMemberSchema,
OidbSetAdminSchema,
OidbSpecialTitleSchema,
Oidb0xf16ReqSchema,
} from '../proto/oidb-action';
// ─────────────── mute / un-mute ───────────────
export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x1253_1',
oidbCmd: 0x1253, subCmd: 1,
request: {
schema: OidbMuteMemberSchema,
value: { groupUin: groupId, type: 1, body: { targetUid: uid, duration } },
},
});
}
export async function muteGroupAll(bridge: Bridge, groupId: number, enable: boolean): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: OidbMuteAllSchema,
value: { groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } },
},
});
}
// ─────────────── join-policy ───────────────
export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: Oidb0x89a_0AddOptionSchema,
value: { groupUin: BigInt(groupId), settings: { addType }, field12: 0 },
},
});
}
export async function setGroupSearch(bridge: Bridge, groupId: number): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: Oidb0x89a_0SearchSchema,
value: { groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 },
},
});
}
export async function setGroupAddRequest(
bridge: Bridge, groupId: number, sequence: number, eventType: number,
approve: boolean, reason = '', filtered = false,
): Promise<void> {
const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1';
await runOidb(bridge, {
cmd,
oidbCmd: 0x10C8, subCmd,
request: {
schema: OidbGroupRequestActionSchema,
value: { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } },
isUid: true,
},
});
}
// ─────────────── kick / leave ───────────────
export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8a0_1',
oidbCmd: 0x8A0, subCmd: 1,
request: {
schema: OidbKickMemberSchema,
value: { groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason },
},
});
}
export async function kickGroupMembers(bridge: Bridge, groupId: number, userIds: number[], reject: boolean): Promise<void> {
const targetUids = await Promise.all(userIds.map(userId => bridge.resolveUserUid(userId, groupId)));
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8a0_1',
oidbCmd: 0x8A0, subCmd: 1,
request: {
schema: Oidb0x8a0ReqSchema,
value: { groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0 },
},
});
}
export async function leaveGroup(bridge: Bridge, groupId: number): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x1097_1',
oidbCmd: 0x1097, subCmd: 1,
request: { schema: OidbLeaveGroupSchema, value: { groupUin: groupId } },
});
}
// ─────────────── role / display name ───────────────
export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x1096_1',
oidbCmd: 0x1096, subCmd: 1,
request: { schema: OidbSetAdminSchema, value: { groupUin: groupId, uid, isAdmin: enable } },
});
}
export async function setGroupCard(bridge: Bridge, groupId: number, userId: number, card: string): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8fc_3',
oidbCmd: 0x8FC, subCmd: 3,
request: {
schema: OidbRenameMemberSchema,
value: { groupUin: groupId, body: { targetUid: uid, targetName: card } },
},
});
}
export async function setGroupName(bridge: Bridge, groupId: number, name: string): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x89a_15',
oidbCmd: 0x89A, subCmd: 15,
request: { schema: OidbRenameGroupSchema, value: { groupUin: groupId, body: { targetName: name } } },
});
}
export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, userId: number, title: string): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId);
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8fc_2',
oidbCmd: 0x8FC, subCmd: 2,
request: {
schema: OidbSpecialTitleSchema,
value: { groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } },
},
});
}
// ─────────────── personal-side metadata ───────────────
// setGroupRemark is the bot's local-only label for the group; it lives
// here rather than in friend.ts because the semantic is "operate on a
// group" rather than "operate on a contact list".
export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xf16_1',
oidbCmd: 0xF16, subCmd: 1,
request: { schema: Oidb0xf16ReqSchema, value: { inner: { groupId: BigInt(groupId), remark }, field12: 0 } },
});
}
// ─────────────── group-level quota query ───────────────
export async function getGroupAtAllRemain(
bridge: Bridge,
groupId: number,
) {
const req = {
basic1: 1,
basic2: 2,
basic3: 1,
uin: BigInt(bridge.identity.uin),
groupId: BigInt(groupId),
type: 0,
};
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x8a7_0',
oidbCmd: 0x8A7, subCmd: 0,
request: { schema: Oidb0x8a7ReqSchema, value: req },
response: { schema: Oidb0x8a7RespSchema },
});
if (!result) {
throw new Error('get group at all remain result empty');
}
// Cast numbers to plain Number: the OIDB layer may surface uint32 as
// BigInt and the WebUI JSON serializer chokes on those.
return {
can_at_all: !!result.canAtAll,
remain_at_all_count_for_group: Number(result.groupRemain || 0),
remain_at_all_count_for_uin: Number(result.uinRemain || 0),
};
}

View File

@@ -1,826 +0,0 @@
// Group + private file operations: upload (with highway fast-path),
// folder management, file listing, file/media URL fetch. All upload
// paths share the same shape (resolve target → OIDB metadata exchange
// → highway HTTP PUT if the server says we must), but the OIDB schemas
// and field layouts differ enough between group and private that they
// stay as separate functions.
import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode';
import { runOidb } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils';
import {
OidbGroupFileCountViewReqSchema,
OidbGroupFileCountViewRespSchema,
OidbGroupFileFolderReqSchema,
OidbGroupFileFolderRespSchema,
OidbGroupFileReqSchema,
OidbGroupFileRespSchema,
OidbGroupFileViewReqSchema,
OidbGroupFileViewRespSchema,
OidbPrivateFileDownloadReqSchema,
OidbPrivateFileDownloadRespSchema,
OidbPrivateFileUploadReqSchema,
OidbPrivateFileUploadRespSchema,
NTV2RichMediaReqSchema,
NTV2RichMediaRespSchema,
} from '../proto/oidb-action';
import { FileUploadExtSchema } from '../proto/highway';
import { toHexUpper } from '../../utils/hex';
import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared';
// ─────────────── 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 this file is a one-stop-shop for the file API surface
// (bridge.ts imports MediaIndexNode through here for type symmetry).
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);
}
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 protoEncode({
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,
}, FileUploadExtSchema);
}
function buildPrivateFileUploadExt(
senderUin: number,
fileName: string,
fileSize: number,
md5: Uint8Array,
sha1: Uint8Array,
fileId: string,
uploadKey: Uint8Array,
uploadHost: string,
uploadPort: number,
): Uint8Array {
return protoEncode({
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,
}, FileUploadExtSchema);
}
function normalizeMediaNode(node: MediaIndexNode): Record<string, unknown> {
const fileUuid = typeof node.fileUuid === 'string' ? node.fileUuid : '';
if (!fileUuid) throw new Error('media node fileUuid is required');
const info = node.info ?? {};
const type = info.type ?? {};
return {
info: {
fileSize: toInt(info.fileSize),
fileHash: typeof info.fileHash === 'string' ? info.fileHash : '',
fileSha1: typeof info.fileSha1 === 'string' ? info.fileSha1 : '',
fileName: typeof info.fileName === 'string' ? info.fileName : '',
type: {
type: toInt(type.type),
picFormat: toInt(type.picFormat),
videoFormat: toInt(type.videoFormat),
voiceFormat: toInt(type.voiceFormat),
},
width: toInt(info.width),
height: toInt(info.height),
time: toInt(info.time),
original: toInt(info.original),
},
fileUuid,
storeId: toInt(node.storeId),
uploadTime: toInt(node.uploadTime),
ttl: toInt(node.ttl),
subType: toInt(node.subType),
};
}
async function fetchNtv2DownloadUrl(
bridge: Bridge,
serviceCmd: string,
oidbCmd: number,
payload: Record<string, unknown>,
): Promise<string> {
const resp = await runOidb<any>(bridge, {
cmd: serviceCmd,
oidbCmd, subCmd: 200,
request: { schema: NTV2RichMediaReqSchema, value: payload, isUid: true },
response: { schema: NTV2RichMediaRespSchema },
});
ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined);
const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : '';
const path = typeof resp?.download?.info?.urlPath === 'string' ? resp.download.info.urlPath : '';
const rKeyParam = typeof resp?.download?.rKeyParam === 'string' ? resp.download.rKeyParam : '';
if (!domain || !path) {
throw new Error('ntv2 download response invalid');
}
return `https://${domain}${path}${rKeyParam}`;
}
// ─────────────── file count ───────────────
export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d8_3',
oidbCmd: 0x6D8, subCmd: 3,
request: {
schema: OidbGroupFileCountViewReqSchema,
value: { count: { groupUin: groupId, appId: 7, busId: 0 } },
},
response: { schema: OidbGroupFileCountViewRespSchema },
});
return {
fileCount: toInt(resp?.count?.fileCount ?? 0),
maxCount: toInt(resp?.count?.maxCount ?? 10000),
};
}
// ─────────────── upload ───────────────
export async function uploadGroupFile(
bridge: Bridge,
groupId: number,
source: string,
name = '',
folderId = '/',
uploadFile = true,
): Promise<UploadFileResult> {
// 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 resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_0',
oidbCmd: 0x6D6, subCmd: 0,
request: {
schema: OidbGroupFileReqSchema,
value: {
file: {
groupUin: groupId,
appId: 4,
busId: 102,
entrance: 6,
targetDirectory: normalizeDirectory(folderId),
fileName,
localDirectory: `/${fileName}`,
fileSize: BigInt(loaded.bytes.length),
fileSha1: hashes.sha1,
fileSha3: new Uint8Array(0),
fileMd5: hashes.md5,
field15: true,
},
},
isUid: true,
},
response: { schema: OidbGroupFileRespSchema },
});
const upload = resp?.upload;
if (!upload) throw new Error('group file upload response missing');
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');
if (!upload.boolFileExist && uploadFile) {
const senderUin = toInt(bridge.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);
}
return { fileId };
}
export async function uploadPrivateFile(
bridge: Bridge,
userId: number,
source: string,
name = '',
uploadFile = true,
): Promise<UploadFileResult> {
// 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('private file is empty');
const targetUid = await bridge.resolveUserUid(userId);
let selfUid = bridge.identity.selfUid;
if (!selfUid) {
const selfUin = toInt(bridge.identity.uin);
if (selfUin > 0) {
selfUid = await bridge.resolveUserUid(selfUin);
}
}
if (!selfUid) throw new Error('self uid is unavailable');
const senderUin = toInt(bridge.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 resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xe37_1700',
oidbCmd: 0xE37, subCmd: 1700,
request: {
schema: OidbPrivateFileUploadReqSchema,
value: {
command: 1700,
seq: 0,
upload: {
senderUid: selfUid,
receiverUid: targetUid,
fileSize: loaded.bytes.length,
fileName,
md510MCheckSum: md5First10MB(loaded.bytes),
sha1CheckSum: hashes.sha1,
localPath: '/',
md5CheckSum: hashes.md5,
sha3CheckSum: new Uint8Array(0),
},
businessId: 3,
clientType: 1,
flagSupportMediaPlatform: 1,
},
},
response: { schema: OidbPrivateFileUploadRespSchema },
});
const upload = resp?.upload;
if (!upload) throw new Error('private file upload response missing');
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');
if (!upload.boolFileExist && uploadFile) {
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|| '';
const uploadPort = toInt(upload.uploadPort);
if (!uploadHost || uploadPort <= 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);
}
return { fileId, fileHash };
}
// ─────────────── list ───────────────
export async function fetchGroupFiles(bridge: Bridge, 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 resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d8_1',
oidbCmd: 0x6D8, subCmd: 1,
request: {
schema: OidbGroupFileViewReqSchema,
value: {
list: {
groupUin: groupId,
appId: 7,
targetDirectory,
fileCount: pageSize,
sortBy: 1,
startIndex,
field17: 2,
field18: 0,
},
},
isUid: true,
},
response: { schema: OidbGroupFileViewRespSchema },
});
const list = resp?.list;
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 = bridge.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 = bridge.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) ───────────────
export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise<string> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_2',
oidbCmd: 0x6D6, subCmd: 2,
request: {
schema: OidbGroupFileReqSchema,
value: {
download: {
groupUin: groupId,
appId: 7,
busId,
fileId,
},
},
isUid: true,
},
response: { schema: OidbGroupFileRespSchema },
});
const download = resp?.download;
if (!download) throw new Error('group file url response missing');
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}`;
}
export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise<string> {
const uid = await bridge.resolveUserUid(userId);
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xe37_1200',
oidbCmd: 0xE37, subCmd: 1200,
request: {
schema: OidbPrivateFileDownloadReqSchema,
value: {
subCommand: 1200,
field2: 1,
body: {
receiverUid: uid,
fileUuid: fileId,
type: 2,
fileHash,
t2: 0,
},
field101: 3,
field102: 103,
field200: 1,
field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]),
},
},
response: { schema: OidbPrivateFileDownloadRespSchema },
});
const result = resp?.body?.result;
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 ───────────────
export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise<void> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_3',
oidbCmd: 0x6D6, subCmd: 3,
request: {
schema: OidbGroupFileReqSchema,
value: {
delete: {
groupUin: groupId,
busId: 102,
fileId,
},
},
isUid: true,
},
response: { schema: OidbGroupFileRespSchema },
});
const result = resp?.delete;
if (!result) throw new Error('group file delete response missing');
ensureRetCodeZero('group file delete', result.retCode, result.retMsg, result.clientWording);
}
export async function moveGroupFile(
bridge: Bridge,
groupId: number,
fileId: string,
parentDirectory: string,
targetDirectory: string,
): Promise<void> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d6_5',
oidbCmd: 0x6D6, subCmd: 5,
request: {
schema: OidbGroupFileReqSchema,
value: {
move: {
groupUin: groupId,
appId: 7,
busId: 102,
fileId,
parentDirectory,
targetDirectory,
},
},
isUid: true,
},
response: { schema: OidbGroupFileRespSchema },
});
const result = resp?.move;
if (!result) throw new Error('group file move response missing');
ensureRetCodeZero('group file move', result.retCode, result.retMsg, result.clientWording);
}
// ─────────────── folders ───────────────
export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise<void> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d7_0',
oidbCmd: 0x6D7, subCmd: 0,
request: {
schema: OidbGroupFileFolderReqSchema,
value: {
create: {
groupUin: groupId,
rootDirectory: normalizeDirectory(parentId),
folderName: name,
},
},
isUid: true,
},
response: { schema: OidbGroupFileFolderRespSchema },
});
const result = resp?.create;
if (!result) throw new Error('group folder create response missing');
ensureRetCodeZero('group folder create', result.retcode, result.retMsg, result.clientWording);
}
export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise<void> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d7_1',
oidbCmd: 0x6D7, subCmd: 1,
request: {
schema: OidbGroupFileFolderReqSchema,
value: {
delete: {
groupUin: groupId,
folderId,
},
},
isUid: true,
},
response: { schema: OidbGroupFileFolderRespSchema },
});
const result = resp?.delete;
if (!result) throw new Error('group folder delete response missing');
ensureRetCodeZero('group folder delete', result.retcode, result.retMsg, result.clientWording);
}
export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise<void> {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x6d7_2',
oidbCmd: 0x6D7, subCmd: 2,
request: {
schema: OidbGroupFileFolderReqSchema,
value: {
rename: {
groupUin: groupId,
folderId,
newFolderName,
},
},
isUid: true,
},
response: { schema: OidbGroupFileFolderRespSchema },
});
const result = resp?.rename;
if (!result) throw new Error('group folder rename response missing');
ensureRetCodeZero('group folder rename', result.retcode, result.retMsg, result.clientWording);
}
// ─────────────── rich-media URL by node ───────────────
export async function fetchGroupPttUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise<string> {
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126e_200', 0x126E, {
reqHead: {
common: { requestId: 4, command: 200 },
scene: {
requestType: 1,
businessType: 3,
sceneType: 2,
group: { groupUin: groupId },
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}
export async function fetchPrivatePttUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise<string> {
const selfUid = await resolveSelfUid(bridge);
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126d_200', 0x126D, {
reqHead: {
common: { requestId: 1, command: 200 },
scene: {
requestType: 1,
businessType: 3,
sceneType: 1,
c2c: {
accountType: 2,
targetUid: selfUid,
},
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}
export async function fetchGroupVideoUrlByNode(bridge: Bridge, groupId: number, node: MediaIndexNode): Promise<string> {
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11ea_200', 0x11EA, {
reqHead: {
common: { requestId: 1, command: 200 },
scene: {
requestType: 2,
businessType: 2,
sceneType: 2,
group: { groupUin: groupId },
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}
export async function fetchPrivateVideoUrlByNode(bridge: Bridge, node: MediaIndexNode): Promise<string> {
const selfUid = await resolveSelfUid(bridge);
const normalizedNode = normalizeMediaNode(node);
return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11e9_200', 0x11E9, {
reqHead: {
common: { requestId: 1, command: 200 },
scene: {
requestType: 2,
businessType: 2,
sceneType: 1,
c2c: {
accountType: 2,
targetUid: selfUid,
},
},
client: { agentType: 2 },
},
download: {
node: normalizedNode,
download: { video: { busiType: 0, sceneType: 0 } },
},
});
}

View File

@@ -1,104 +0,0 @@
// Operations targeting an existing message: recall (group / private),
// mark-as-read (group / private), and the "essence" highlight toggle.
// All of these take a message identifier and modify server-side state
// without producing a downstream observable event.
import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode';
import { runOidb } from '../bridge-oidb';
import {
C2CRecallRequestSchema,
GroupRecallRequestSchema,
OidbEssenceSchema,
SsoReadedReportReqSchema,
} from '../proto/oidb-action';
export async function recallGroupMessage(bridge: Bridge, groupId: number, sequence: number): Promise<void> {
const request = protoEncode({
type: 1,
groupUin: groupId,
info: { sequence, random: 0, field3: 0 },
settings: { field1: 0 },
}, GroupRecallRequestSchema);
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg', request);
if (!result.success) throw new Error(result.errorMessage || 'recall group message failed');
}
export async function recallPrivateMessage(
bridge: Bridge, userUin: number, clientSeq: number,
msgSeq: number, random: number, timestamp: number,
): Promise<void> {
const targetUid = await bridge.resolveUserUid(userUin);
const request = protoEncode({
type: 1,
targetUid,
info: {
clientSequence: clientSeq,
random,
messageId: BigInt((0x01000000 * 0x100000000) + random),
timestamp,
field5: 0,
messageSequence: msgSeq,
},
settings: { field1: false, field2: false },
field6: false,
}, C2CRecallRequestSchema);
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', request);
if (!result.success) throw new Error(result.errorMessage || 'recall private message failed');
}
export async function markPrivateMessageRead(
bridge: Bridge,
userId: number,
msgSeq: number,
timestamp: number = Math.floor(Date.now() / 1000),
): Promise<void> {
const uid = await bridge.resolveUserUid(userId);
const request = protoEncode({
c2cList: [
{
uid,
lastReadTime: BigInt(timestamp),
lastReadSeq: BigInt(msgSeq),
},
],
}, SsoReadedReportReqSchema);
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
if (!result.success) {
throw new Error(result.errorMessage || 'mark private message read failed');
}
}
export async function markGroupMessageRead(
bridge: Bridge,
groupId: number,
msgSeq: number,
): Promise<void> {
const request = protoEncode({
groupList: [
{
groupUin: BigInt(groupId),
lastReadSeq: BigInt(msgSeq),
},
],
}, SsoReadedReportReqSchema);
const result = await bridge.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoReadedReport', request);
if (!result.success) {
throw new Error(result.errorMessage || 'mark group message read failed');
}
}
export async function setGroupEssence(bridge: Bridge, groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
const subCmd = enable ? 1 : 2;
const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2';
await runOidb(bridge, {
cmd,
oidbCmd: 0xEAC, subCmd,
request: { schema: OidbEssenceSchema, value: { groupUin: groupId, sequence, random } },
});
}

View File

@@ -1,86 +0,0 @@
// Lightweight social-interaction actions: poke, like, emoji reaction,
// and the related read-side "who reacted with X" query. None of these
// edit message content — they're purely social signals.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
Oidb0x9083ReqSchema,
Oidb0x9083RespSchema,
OidbGroupReactionSchema,
OidbLikeSchema,
OidbPokeSchema,
} from '../proto/oidb-action';
export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0xed3_1',
oidbCmd: 0xED3, subCmd: 1,
request: {
schema: OidbPokeSchema,
value: {
uin: targetUin ?? peerUin,
groupUin: isGroup ? peerUin : 0,
friendUin: isGroup ? 0 : peerUin,
ext: 0,
},
},
});
}
export async function sendLike(bridge: Bridge, userId: number, count: number): Promise<void> {
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x7e5_104',
oidbCmd: 0x7E5, subCmd: 104,
request: { schema: OidbLikeSchema, value: { targetUin: userId, count } },
});
}
export async function setGroupReaction(bridge: Bridge, groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
const subCmd = isSet ? 1 : 2;
const cmd = isSet ? 'OidbSvcTrpcTcp.0x9082_1' : 'OidbSvcTrpcTcp.0x9082_2';
// Same heuristic NapCat uses: QQ face ids are 1–3 digits ("76"),
// unicode codepoints are longer ("128516"). Server requires the
// type field to pick the right resolution table; omitting it makes
// unicode reactions silently fail.
const type = code.length > 3 ? 2 : 1;
await runOidb(bridge, {
cmd,
oidbCmd: 0x9082, subCmd,
request: {
schema: OidbGroupReactionSchema,
value: { groupUin: groupId, sequence, code, type },
},
});
}
export async function getEmojiLikes(
bridge: Bridge,
groupId: number,
sequence: number,
emojiId: string,
emojiType: number = 1,
count: number = 10,
cookie: string = '',
): Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }> {
const req = {
groupId: BigInt(groupId),
sequence,
emojiType,
emojiId,
cookie: cookie ? Buffer.from(cookie, 'base64') : new Uint8Array(0),
field7: 0,
count,
field12: 1,
};
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x9083_1',
oidbCmd: 0x9083, subCmd: 1,
request: { schema: Oidb0x9083ReqSchema, value: req },
response: { schema: Oidb0x9083RespSchema },
});
const uin = resp?.inner?.userInfo?.uin;
const users = uin ? [{ uin: Number(uin) }] : [];
const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : '';
return { users, cookie: respCookie, isLast: !respCookie };
}

View File

@@ -1,164 +0,0 @@
// Grab-bag: action verbs that don't share a theme with anything else.
// Kept together so the directory stays small; if any of these grow new
// related siblings, lift the whole group out into its own file.
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { runOidb } from '../bridge-oidb';
import {
MiniAppShareReqSchema,
MiniAppShareRespSchema,
Oidb0x112eReqSchema,
Oidb0x112eRespSchema,
Oidb0x990ReqSchema,
Oidb0x990RespSchema,
Oidb0xeb7ReqSchema,
Oidb0xeb7RespSchema,
} from '../proto/oidb-action';
export async function translateEn2Zh(
bridge: Bridge,
words: string[],
) {
const req = {
translateReq: {
srcLang: 'en',
dstLang: 'zh',
words: words,
},
tag10: 1,
tag12: 1,
};
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x990_2',
oidbCmd: 0x990, subCmd: 2,
request: { schema: Oidb0x990ReqSchema, value: req },
response: { schema: Oidb0x990RespSchema },
});
const resp = result?.translateResp;
if (!resp) {
throw new Error('translate response empty');
}
return resp.dstWords || [];
}
export async function getMiniAppArk(
bridge: Bridge,
type: string,
title: string,
desc: string,
picUrl: string,
jumpUrl: string,
) {
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 = protoEncode({
sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A',
body: {
appid,
title,
desc,
picUrl,
jumpUrl,
iconUrl,
},
}, MiniAppShareReqSchema);
const result = await bridge.sendRawPacket('LightAppSvc.mini_app_share.AdaptShareInfo', request);
if (!result.success || !result.responseData) {
throw new Error(result.errorMessage || 'get mini app ark failed');
}
const decoded = protoDecode(result.responseData, MiniAppShareRespSchema);
const jsonStr = decoded?.body?.jsonStr;
if (!jsonStr) {
throw new Error('mini app share json empty');
}
const parsed = JSON.parse(jsonStr);
return {
data: {
ver: parsed.ver,
prompt: parsed.prompt,
config: parsed.config,
app: parsed.appName,
view: parsed.appView,
meta: parsed.metaData,
miniappShareOrigin: 3,
miniappOpenRefer: '10002',
},
};
}
export async function clickInlineKeyboardButton(
bridge: Bridge,
groupId: number,
botAppid: number,
buttonId: string,
callbackData: string,
msgSeq: number,
) {
const req = {
botAppid: BigInt(botAppid),
msgSeq: BigInt(msgSeq),
buttonId: String(buttonId),
callbackData: String(callbackData || ''),
unknown7: 0,
groupId: BigInt(groupId),
unknown9: 1,
};
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x112e_1',
oidbCmd: 0x112E, subCmd: 1,
request: { schema: Oidb0x112eReqSchema, value: req },
response: { schema: Oidb0x112eRespSchema },
});
if (!result) {
throw new Error('click inline keyboard button result empty');
}
return {
result: Number(result.result || 0),
errMsg: result.errMsg || '',
status: 0,
promptText: result.promptText || '',
promptType: 0,
promptIcon: 0,
};
}
export async function sendGroupSign(
bridge: Bridge,
groupId: number,
) {
const req = {
signInInfo: {
uin: String(bridge.identity.uin),
groupId: String(groupId),
version: '9.0.90',
},
};
await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xEB7_1',
oidbCmd: 0xEB7, subCmd: 1,
request: { schema: Oidb0xeb7ReqSchema, value: req },
response: { schema: Oidb0xeb7RespSchema },
});
}

View File

@@ -1,313 +0,0 @@
// Operations that touch the bot's own profile / status, plus the
// related queries about my profile likes and unidirectional friends.
// All of these read/write fields on the self-uin via OIDB.
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { runOidb } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, loadBinarySource } from '../highway/utils';
import {
FaceroamOpReqSchema,
FaceroamOpRespSchema,
GroupAvatarExtraSchema,
Oidb0x112aReqSchema,
Oidb0x112aRespSchema,
Oidb0x7edReqSchema,
Oidb0x7edRespSchema,
Oidb0xcd4ReqSchema,
Oidb0xcd4RespSchema,
Oidb0xe17ReqSchema,
Oidb0xe17RespSchema,
OidbSetProfileSchema,
SetStatusReqSchema,
SetStatusRespSchema,
} from '../proto/oidb-action';
import { resolveSelfUid } from './shared';
// ─────────────── status / profile setters ───────────────
export async function setOnlineStatus(
bridge: Bridge,
status: number,
extStatus: number = 0,
batteryStatus: number = 100,
): Promise<void> {
await dispatchSetStatus(bridge, { 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.
*/
export async function setDiyOnlineStatus(
bridge: Bridge,
faceId: number,
wording: string,
faceType: number,
): Promise<void> {
await dispatchSetStatus(bridge, {
status: 10,
extStatus: 2000,
batteryStatus: 0,
customExt: { faceId, text: wording, faceType },
});
}
async function dispatchSetStatus(
bridge: Bridge,
value: {
status: number;
extStatus: number;
batteryStatus: number;
customExt?: { faceId: number; text: string; faceType: number };
},
): Promise<void> {
const request = protoEncode(value, SetStatusReqSchema);
const result = await bridge.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 = protoDecode(result.responseData, SetStatusRespSchema);
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}`);
}
}
}
export async function setProfile(
bridge: Bridge,
nickname?: string,
personalNote?: string,
): Promise<void> {
const uin = BigInt(bridge.identity.uin);
const stringProfiles: any[] = [];
const intProfiles: any[] = [];
if (nickname !== undefined) {
stringProfiles.push({ fieldId: 20002, value: nickname });
}
if (personalNote !== undefined) {
stringProfiles.push({ fieldId: 102, value: personalNote });
}
if (stringProfiles.length === 0 && intProfiles.length === 0) {
return;
}
const req = {
uin,
stringProfiles,
};
await runOidb(bridge, {
cmd: 'OidbSvcTrpcTcp.0x112a_2',
oidbCmd: 0x112A, subCmd: 2,
request: { schema: OidbSetProfileSchema, value: req },
});
}
export async function setSelfLongNick(
bridge: Bridge,
longNick: string,
) {
const req = {
uin: BigInt(bridge.identity.uin),
profile: {
tag: 102,
value: String(longNick),
},
};
await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x112a_2',
oidbCmd: 0x112A, subCmd: 2,
request: { schema: Oidb0x112aReqSchema, value: req },
response: { schema: Oidb0x112aRespSchema },
});
}
export async function setInputStatus(
bridge: Bridge,
userId: number,
eventType: number,
) {
const targetUid = await bridge.resolveUserUid(userId);
if (!targetUid) {
throw new Error('target uid not found');
}
const req = {
reqBody: {
uid: targetUid,
chatType: 0,
eventType: eventType,
},
};
await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xcd4_1',
oidbCmd: 0xCD4, subCmd: 1,
request: { schema: Oidb0xcd4ReqSchema, value: req },
response: { schema: Oidb0xcd4RespSchema },
});
}
export async function setAvatar(
bridge: Bridge,
source: string,
): Promise<void> {
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.
*/
export async function setGroupAvatar(
bridge: Bridge,
groupId: number,
source: string,
): Promise<void> {
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 = protoEncode({
type: 101,
groupUin: groupId,
field3: { field1: 1 },
field5: 3,
field6: 1,
}, GroupAvatarExtraSchema);
await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra);
}
// ─────────────── queries on me / my contacts ───────────────
export async function getProfileLike(
bridge: Bridge,
userId?: number,
start: number = 0,
limit: number = 10,
) {
const isSelf = !userId;
const targetUid = isSelf
? await resolveSelfUid(bridge)
: await bridge.resolveUserUid(userId);
if (!targetUid) {
throw new Error('target uid not found');
}
const req = {
targetUid: targetUid,
basic: 1,
vote: 1,
favorite: 1,
start: start,
limit: limit,
};
const result = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x7ed_12',
oidbCmd: 0x7ED, subCmd: 12,
request: { schema: Oidb0x7edReqSchema, value: req },
response: { schema: Oidb0x7edRespSchema },
});
const data = result?.userLikeInfos?.[0];
if (!data) {
throw new Error('get profile like info empty');
}
return {
uid: data.uid,
time: Number(data.time),
favoriteInfo: {
total_count: data.favoriteInfo?.totalCount || 0,
last_time: Number(data.favoriteInfo?.lastTime || 0),
today_count: data.favoriteInfo?.newCount || 0,
userInfos: [],
},
voteInfo: {
total_count: data.voteInfo?.totalCount || 0,
new_count: data.voteInfo?.newCount || 0,
new_nearby_count: 0,
last_visit_time: Number(data.voteInfo?.lastTime || 0),
userInfos: [],
},
};
}
export async function getUnidirectionalFriendList(
bridge: Bridge,
) {
const reqObj = {
uint64_uin: String(bridge.identity.uin),
uint64_top: 0,
uint32_req_num: 99,
bytes_cookies: '',
};
const req = {
jsonBody: JSON.stringify(reqObj),
};
const result = await runOidb<any>(bridge, {
cmd: 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0',
oidbCmd: 0xE17, subCmd: 0,
request: { schema: Oidb0xe17ReqSchema, value: req },
response: { schema: Oidb0xe17RespSchema },
});
if (!result || !result.jsonBody) {
throw new Error('get unidirectional friend list empty');
}
const parsed = JSON.parse(result.jsonBody);
return parsed.rpt_block_list || [];
}
export async function fetchCustomFace(bridge: Bridge, count: number = 10): Promise<string[]> {
const req = {
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
uin: BigInt(bridge.identity.uin),
field3: 1,
field6: 1,
};
const request = protoEncode(req, FaceroamOpReqSchema);
const result = await bridge.sendRawPacket('Faceroam.OpReq', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'fetch custom face failed');
}
const resp = protoDecode(result.responseData, FaceroamOpRespSchema);
if (!resp || (resp as any).retCode !== 0) {
throw new Error(`fetch custom face error: ${(resp as any)?.message || 'unknown'}`);
}
const faceIds = (resp as any).item?.faceIds || [];
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${bridge.identity.uin}/${id}/0`);
}

View File

@@ -1,352 +0,0 @@
// Contact / info-fetching operations extracted from Bridge.
import type { Bridge } from './bridge';
import type { DownloadRKeyInfo } from './bridge';
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { protoDecode } from '../protobuf/decode';
import { runOidb } from './bridge-oidb';
import {
OidbSvcTrpcTcp0xFD4_1ResponseSchema,
OidbSvcTrpcTcp0xFE5_2ResponseSchema,
OidbSvcTrpcTcp0xFE7_3ResponseSchema,
OidbSvcTrpcTcp0x10C0ResponseSchema,
} from './proto/oidb';
import {
OidbFriendListRequestSchema,
OidbGroupListRequestSchema,
OidbGroupMemberListRequestSchema,
OidbUserInfoRequestSchema,
OidbUserInfoResponseSchema,
AvatarInfoSchema,
OidbGroupRequestListSchema,
NTV2RichMediaReqSchema,
NTV2RichMediaRespSchema,
} from './proto/oidb-action';
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
export function buildFriendProperties(raw: any): 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';
}
}
// ---------------------------------------------------------------------------
// Friend list
// ---------------------------------------------------------------------------
export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
const friends: FriendInfo[] = [];
let nextUin: number | null = null;
do {
const body: any = {
friendCount: 300,
field4: 0,
field6: 1,
field7: 0x7FFFFFFF,
body: [
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
{ type: 4, number: { numbers: [100, 101, 102] } },
],
field10002: [13578, 13579, 13573, 13572, 13568],
field10003: 4051,
};
if (nextUin !== null) {
body.nextUin = { uin: nextUin };
}
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfd4_1',
oidbCmd: 0xFD4, subCmd: 1,
request: { schema: OidbFriendListRequestSchema, value: body },
response: { schema: OidbSvcTrpcTcp0xFD4_1ResponseSchema },
});
if (resp?.friends) {
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);
bridge.identity.rememberFriends(friends);
return friends;
}
// ---------------------------------------------------------------------------
// Group list
// ---------------------------------------------------------------------------
export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
const allTrue = true;
const body = {
config: {
config1: {
groupOwner: allTrue, field2: allTrue, memberMax: allTrue, memberCount: allTrue,
groupName: allTrue, field8: allTrue, field9: allTrue, field10: allTrue,
field11: allTrue, field12: allTrue, field13: allTrue, field14: allTrue,
field15: allTrue, field16: allTrue, field17: allTrue, field18: allTrue,
question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue,
field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue,
field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue,
field32: allTrue, field5001: allTrue, field5002: allTrue, field5003: allTrue,
},
config2: {
field1: allTrue, field2: allTrue, field3: allTrue, field4: allTrue,
field5: allTrue, field6: allTrue, field7: allTrue, field8: allTrue,
},
config3: { field5: allTrue, field6: allTrue },
},
};
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe5_2',
oidbCmd: 0xFE5, subCmd: 2,
request: { schema: OidbGroupListRequestSchema, value: body, isUid: true },
response: { schema: OidbSvcTrpcTcp0xFE5_2ResponseSchema },
});
const groups: QQGroupInfo[] = [];
if (resp?.groups) {
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(),
});
}
}
bridge.identity.rememberGroups(groups);
return groups;
}
// ---------------------------------------------------------------------------
// Group member list
// ---------------------------------------------------------------------------
export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Promise<GroupMemberInfo[]> {
const members: GroupMemberInfo[] = [];
let token = '';
do {
const body: any = {
groupUin: groupId,
field2: 5,
field3: 2,
body: {
memberName: true, memberCard: true, level: true, field13: true,
field16: true, specialTitle: true, field18: true, field20: true,
field21: true, joinTimestamp: true, lastMsgTimestamp: true,
shutUpTimestamp: true, field103: true, field104: true, field105: true,
field106: true, permission: true, field200: true, field201: true,
},
};
if (token) body.token = token;
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe7_3',
oidbCmd: 0xFE7, subCmd: 3,
request: { schema: OidbGroupMemberListRequestSchema, value: body },
response: { schema: OidbSvcTrpcTcp0xFE7_3ResponseSchema },
});
if (resp?.members) {
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);
bridge.identity.rememberGroupMembers(groupId, members);
return members;
}
// ---------------------------------------------------------------------------
// User profile
// ---------------------------------------------------------------------------
export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<UserProfileInfo> {
const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037];
const body = {
uin,
field2: 0,
keys: keys.map(k => ({ key: k })),
};
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
oidbCmd: 0xFE1, subCmd: 2,
request: { schema: OidbUserInfoRequestSchema, value: body },
response: { schema: OidbUserInfoResponseSchema },
});
if (!resp?.body) throw new Error('user info response body missing');
const info: UserProfileInfo = {
uin: resp.body.uin ?? uin,
uid: resp.body.uid ?? '',
nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
};
if (resp.body.properties) {
const bytesMap = new Map<number, Uint8Array>();
const numMap = new Map<number, number>();
for (const bp of resp.body.properties.bytesProperties ?? []) {
bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0));
}
for (const np of resp.body.properties.numberProperties ?? []) {
numMap.set(np.number1 ?? 0, np.number2 ?? 0);
}
const getString = (code: number) => {
const b = bytesMap.get(code);
return b ? Buffer.from(b).toString('utf8') : '';
};
info.nickname = getString(20002);
info.remark = getString(103);
info.qid = getString(27394);
info.sign = getString(102);
const avatarBytes = bytesMap.get(101);
if (avatarBytes) {
const av = protoDecode(avatarBytes, AvatarInfoSchema);
if (av?.url) info.avatar = av.url + '640';
}
const sexNum = numMap.get(20009) ?? 0;
info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown';
info.age = numMap.get(20037) ?? 0;
}
bridge.identity.rememberUserProfile(info);
return info;
}
// ---------------------------------------------------------------------------
// Group requests
// ---------------------------------------------------------------------------
export async function fetchGroupRequests(bridge: Bridge, filtered = false): Promise<GroupRequestInfo[]> {
const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1';
const resp = await runOidb<any>(bridge, {
cmd,
oidbCmd: 0x10C0, subCmd,
request: { schema: OidbGroupRequestListSchema, value: { count: 20, field2: 0 } },
response: { schema: OidbSvcTrpcTcp0x10C0ResponseSchema },
});
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,
});
}
bridge.identity.rememberGroupRequests(requests);
return requests;
}
// ---------------------------------------------------------------------------
// Download RKeys
// ---------------------------------------------------------------------------
export async function fetchDownloadRKeys(bridge: Bridge): Promise<DownloadRKeyInfo[]> {
const PRIVATE_IMAGE = 10;
const GROUP_IMAGE = 20;
const FALLBACK_IMAGE = 2;
const body = {
reqHead: {
common: { requestId: 1, command: 202 },
scene: { requestType: 2, businessType: 1, sceneType: 0 },
client: { agentType: 2 },
},
downloadRkey: {
types: [PRIVATE_IMAGE, GROUP_IMAGE, FALLBACK_IMAGE],
},
};
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x9067_202',
oidbCmd: 0x9067, subCmd: 202,
request: { schema: NTV2RichMediaReqSchema, value: body, isUid: true },
response: { schema: NTV2RichMediaRespSchema },
});
if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) {
throw new Error(resp.respHead.message ?? 'fetch download rkey failed');
}
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

@@ -1,147 +0,0 @@
// BridgeInterface — the surface OneBot (and any other external consumer)
// is allowed to see. The concrete Bridge class additionally exposes raw
// protocol primitives (sendRawPacket, packet dispatch, PID management)
// used by the in-tree action / contacts / highway modules; those internal
// methods deliberately do NOT appear here so that callers depending on
// the interface stay decoupled from the wire format.
//
// Every method below has a matching signature on Bridge; `Bridge
// implements BridgeInterface` is the compile-time enforcement.
import type { BridgeEventBus } from './event-bus';
import type { IdentityService } from './identity-service';
import type {
FriendInfo, QQGroupInfo, GroupMemberInfo,
UserProfileInfo, GroupRequestInfo,
} from './qq-info';
import type { MessageElement, ForwardNodePayload } from './events';
import type { GroupFilesResult } from './actions/group-file';
import type { MediaIndexNode } from './actions/shared';
import type { WebHonorType } from './web/group-honor';
import type {
SendMessageReceipt,
DownloadRKeyInfo,
ClientKeyInfo,
} from './bridge';
import type { SendPacketResult } from '../protocol/packet-sender';
export interface BridgeInterface {
// ─── Shared state ───
readonly identity: IdentityService;
readonly events: BridgeEventBus;
readonly activePid: number | null;
// ─── Resolution ───
resolveUserUid(uin: number, groupId?: number): Promise<string>;
// ─── Raw packet (deliberate escape hatch for `send_packet` action) ───
// OneBot clients use this to debug or invoke commands SnowLuma has no
// typed wrapper for. Every other method on this interface eventually
// routes through here.
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
// ─── Send (messages) ───
sendGroupMessage(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt>;
sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt>;
// ─── Fetch (contacts / profile / system) ───
fetchFriendList(): Promise<FriendInfo[]>;
fetchGroupList(): Promise<QQGroupInfo[]>;
fetchGroupMemberList(groupId: number, options?: { force?: boolean }): Promise<GroupMemberInfo[]>;
fetchUserProfile(uin: number): Promise<UserProfileInfo>;
fetchGroupRequests(filtered?: boolean): Promise<GroupRequestInfo[]>;
fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]>;
// ─── Group admin ───
muteGroupMember(groupId: number, userId: number, duration: number): Promise<void>;
muteGroupAll(groupId: number, enable: boolean): Promise<void>;
setGroupAddOption(groupId: number, addType: number): Promise<void>;
setGroupSearch(groupId: number): Promise<void>;
setGroupAddRequest(groupId: number, sequence: number, eventType: number, approve: boolean, reason?: string, filtered?: boolean): Promise<void>;
kickGroupMember(groupId: number, userId: number, reject: boolean, reason?: string): Promise<void>;
kickGroupMembers(groupId: number, userIds: number[], reject: boolean): Promise<void>;
leaveGroup(groupId: number): Promise<void>;
setGroupAdmin(groupId: number, userId: number, enable: boolean): Promise<void>;
setGroupCard(groupId: number, userId: number, card: string): Promise<void>;
setGroupName(groupId: number, name: string): Promise<void>;
setGroupSpecialTitle(groupId: number, userId: number, title: string): Promise<void>;
setGroupRemark(groupId: number, remark: string): Promise<void>;
setGroupReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void>;
setGroupEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void>;
// ─── Friend ───
setFriendAddRequest(uidOrFlag: string, approve: boolean): Promise<void>;
deleteFriend(userId: number, block?: boolean): Promise<void>;
setFriendRemark(userId: number, remark: string): Promise<void>;
// ─── Files ───
uploadGroupFile(groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>;
uploadPrivateFile(userId: number, file: string, name?: string, uploadFile?: boolean): Promise<{ fileId: string | null }>;
fetchGroupFiles(groupId: number, folderId?: string): Promise<GroupFilesResult>;
fetchGroupFileUrl(groupId: number, fileId: string, busId?: number): Promise<string>;
fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise<string>;
fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise<string>;
fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise<string>;
fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise<string>;
fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise<string>;
deleteGroupFile(groupId: number, fileId: string): Promise<void>;
moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void>;
createGroupFileFolder(groupId: number, name: string, parentId?: string): Promise<void>;
deleteGroupFileFolder(groupId: number, folderId: string): Promise<void>;
renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise<void>;
fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }>;
// ─── Forward ───
uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string>;
fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]>;
// ─── Message ops ───
recallGroupMessage(groupId: number, sequence: number): Promise<void>;
recallPrivateMessage(userUin: number, clientSeq: number, msgSeq: number, random: number, timestamp: number): Promise<void>;
markGroupMsgAsRead(groupId: number, sequence: number): Promise<void>;
markPrivateMsgAsRead(userId: number, sequence: number): Promise<void>;
// ─── Interaction ───
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void>;
sendLike(userId: number, count: number): Promise<void>;
getEmojiLikes(groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }>;
// ─── Web-backed ───
getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise<any>;
forceFetchClientKey(): Promise<ClientKeyInfo>;
getGroupEssence(groupId: number, pageStart?: number, pageLimit?: number): Promise<any>;
getGroupEssenceAll(groupId: number): Promise<any>;
sendGroupNotice(groupId: number, content: string, options?: any): Promise<any>;
getGroupNotice(groupId: number): Promise<any>;
deleteGroupNotice(groupId: number, fid: string): Promise<boolean>;
getCookiesStr(domain: string): Promise<string>;
getCsrfToken(): Promise<number>;
getCredentials(domain: string): Promise<any>;
// ─── Personal profile ───
setOnlineStatus(status: number, extStatus?: number, batteryStatus?: number): Promise<void>;
setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise<void>;
setProfile(nickname?: string, personalNote?: string): Promise<void>;
setSelfLongNick(longNick: string): Promise<any>;
setInputStatus(userId: number, eventType: number): Promise<any>;
setAvatar(source: string): Promise<void>;
setGroupAvatar(groupId: number, source: string): Promise<void>;
fetchCustomFace(count?: number): Promise<string[]>;
getProfileLike(userId?: number, start?: number, limit?: number): Promise<any>;
getUnidirectionalFriendList(): Promise<any>;
getGroupAtAllRemain(groupId: number): Promise<any>;
// ─── Misc ───
translateEn2Zh(words: string[]): Promise<any>;
getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<any>;
clickInlineKeyboardButton(groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number): Promise<any>;
sendGroupSign(groupId: number): Promise<any>;
// ─── Tier-2 napcat parity extras ───
setGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void>;
completeGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void>;
cancelGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void>;
getStrangerStatus(uin: number): Promise<{ status: number; ext_status: number } | null>;
fetchAiVoiceList(groupId: number, chatType: number): Promise<Array<{ category: string; voices: Array<{ voiceId: string; voiceDisplayName: string; voiceExampleUrl: string }> }>>;
fetchAiVoice(groupId: number, voiceId: string, text: string, chatType: number): Promise<MediaIndexNode>;
}

View File

@@ -1,90 +0,0 @@
// One deep entry point for a single OIDB round-trip: build the envelope,
// dispatch via Bridge.sendRawPacket, validate the response status, and
// optionally decode the body. Replaces the three positional helpers
// (makeOidbRequest / sendOidbAndCheck / sendOidbAndDecode) that used to
// scatter the same five-step pattern across every action file.
import type { Bridge } from './bridge';
import type { ProtoSchema } from '../protobuf/decode';
import { protoEncode, protoDecode } from '../protobuf/decode';
import { makeOidbBaseSchema } from './proto/oidb';
export interface OidbCall<TResp = void> {
/** Service-cmd string sent on the wire, e.g. 'OidbSvcTrpcTcp.0x1253_1'. */
cmd: string;
/** OIDB command number, e.g. 0x1253. */
oidbCmd: number;
/** OIDB sub-command, e.g. 1. */
subCmd: number;
request: {
schema: ProtoSchema;
value: any;
/**
* Sets the OIDB envelope `reserved` field to 1 when true. A handful
* of commands (group/friend list, rkey download) operate on
* UID-keyed data and require this flag — the wire format is
* otherwise identical.
*/
isUid?: boolean;
};
/** Omit to skip decoding the response body (fire-and-check). */
response?: {
schema: ProtoSchema;
};
}
/**
* Issue one OIDB request. Without `response`, returns void after
* verifying the envelope's retCode. With `response`, decodes the
* envelope, validates retCode, and returns the inner body.
*
* Throws on transport failure, missing response, decode failure, or any
* non-zero envelope retCode. Action modules layer their own retCode
* checks (on inner sub-replies like `upload.retCode`) on top of this.
*/
export function runOidb(bridge: Bridge, call: OidbCall<void> & { response?: undefined }): Promise<void>;
export function runOidb<TResp>(bridge: Bridge, call: OidbCall<TResp> & { response: { schema: ProtoSchema } }): Promise<TResp>;
export async function runOidb<TResp>(bridge: Bridge, call: OidbCall<TResp>): Promise<TResp | void> {
const envelope = encodeOidbEnvelope(call);
const result = await bridge.sendRawPacket(call.cmd, envelope);
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
if (call.response) {
if (!result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'no response');
}
const baseSchema = makeOidbBaseSchema(call.response.schema);
const resp = protoDecode(result.responseData, baseSchema);
if (!resp) throw new Error('failed to decode OIDB response');
throwIfOidbError(resp);
return (resp as any).body as TResp;
}
// Fire-and-check: response data is optional, but if present we still
// peek at the envelope so a server-side retCode doesn't silently slip past.
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
if (result.responseData && result.responseData.length > 0) {
const emptyBase = makeOidbBaseSchema({ _dummy: { field: 99, type: 'uint32' as const } });
const resp = protoDecode(result.responseData, emptyBase);
if (resp) throwIfOidbError(resp);
}
}
function encodeOidbEnvelope(call: OidbCall<unknown>): Uint8Array {
const baseSchema = makeOidbBaseSchema(call.request.schema);
return protoEncode({
command: call.oidbCmd,
subCommand: call.subCmd,
errorCode: 0,
body: call.request.value,
errorMsg: '',
reserved: call.request.isUid ? 1 : 0,
}, baseSchema);
}
function throwIfOidbError(resp: unknown): void {
const code = (resp as any).errorCode;
if (code && code !== 0) {
throw new Error(`OIDB error ${code}: ${(resp as any).errorMsg ?? ''}`);
}
}

View File

@@ -1,575 +0,0 @@
// Bridge — per-UIN session: handler registration, packet dispatch, event routing.
// Supports packet sending via native addon.
// Heavy OIDB / contact / action logic is split into bridge-oidb, bridge-contacts, bridge-actions.
import type { PacketInfo } from '../protocol/types';
import type { ForwardNodePayload, QQEventVariant, MessageElement } from './events';
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { MSG_PUSH_CMD, parseMsgPush } from './msg-push';
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
import { protoEncode, protoDecode } from '../protobuf/decode';
import { buildSendElems } from './element-builder';
import { IdentityService } from './identity-service';
import type { BridgeInterface } from './bridge-interface';
import { IncomingPacketPipeline, type CmdParser } from './packet-pipeline';
import { createLogger } from '../utils/logger';
import {
SendMessageRequestSchema,
SendMessageResponseSchema,
} from './proto/action';
// Delegated modules
import {
fetchFriendList as fetchFriendList_,
fetchGroupList as fetchGroupList_,
fetchGroupMemberList as fetchGroupMemberList_,
fetchUserProfile as fetchUserProfile_,
fetchGroupRequests as fetchGroupRequests_,
fetchDownloadRKeys as fetchDownloadRKeys_,
} from './bridge-contacts';
import type { WebHonorType } from './web/group-honor';
import {
muteGroupMember as muteGroupMember_,
muteGroupAll as muteGroupAll_,
setGroupAddOption as setGroupAddOption_,
setGroupSearch as setGroupSearch_,
setGroupAddRequest as setGroupAddRequest_,
kickGroupMember as kickGroupMember_,
kickGroupMembers as kickGroupMembers_,
leaveGroup as leaveGroup_,
setGroupAdmin as setGroupAdmin_,
setGroupCard as setGroupCard_,
setGroupName as setGroupName_,
setGroupSpecialTitle as setGroupSpecialTitle_,
setGroupRemark as setGroupRemark_,
getGroupAtAllRemain as getGroupAtAllRemain_,
} from './actions/group-admin';
import {
uploadGroupFile as uploadGroupFile_,
uploadPrivateFile as uploadPrivateFile_,
fetchGroupFiles as fetchGroupFiles_,
fetchGroupFileUrl as fetchGroupFileUrl_,
fetchPrivateFileUrl as fetchPrivateFileUrl_,
fetchGroupPttUrlByNode as fetchGroupPttUrlByNode_,
fetchPrivatePttUrlByNode as fetchPrivatePttUrlByNode_,
fetchGroupVideoUrlByNode as fetchGroupVideoUrlByNode_,
fetchPrivateVideoUrlByNode as fetchPrivateVideoUrlByNode_,
deleteGroupFile as deleteGroupFile_,
moveGroupFile as moveGroupFile_,
createGroupFileFolder as createGroupFileFolder_,
deleteGroupFileFolder as deleteGroupFileFolder_,
renameGroupFileFolder as renameGroupFileFolder_,
fetchGroupFileCount as fetchGroupFileCount_,
} from './actions/group-file';
import {
recallGroupMessage as recallGroupMessage_,
recallPrivateMessage as recallPrivateMessage_,
markPrivateMessageRead as markGroupMsgAsRead_,
markGroupMessageRead as markPrivateMsgAsRead_,
setGroupEssence as setGroupEssence_,
} from './actions/group-message';
import {
sendPoke as sendPoke_,
sendLike as sendLike_,
setGroupReaction as setGroupReaction_,
getEmojiLikes as getEmojiLikes_,
} from './actions/interaction';
import {
uploadForwardNodes as uploadForwardNodes_,
fetchForwardNodes as fetchForwardNodes_,
} from './actions/forward';
import {
setFriendAddRequest as setFriendAddRequest_,
deleteFriend as deleteFriend_,
setFriendRemark as setFriendRemark_,
} from './actions/friend';
import {
setOnlineStatus as setOnlineStatus_,
setDiyOnlineStatus as setDiyOnlineStatus_,
setProfile as setProfile_,
setSelfLongNick as setSelfLongNick_,
setInputStatus as setInputStatus_,
setAvatar as setAvatar_,
setGroupAvatar as setGroupAvatar_,
fetchCustomFace as fetchCustomFace_,
getProfileLike as getProfileLike_,
getUnidirectionalFriendList as getUnidirectionalFriendList_,
} from './actions/profile';
import {
translateEn2Zh as translateEn2Zh_,
getMiniAppArk as getMiniAppArk_,
clickInlineKeyboardButton as clickInlineKeyboardButton_,
sendGroupSign as sendGroupSign_,
} from './actions/misc';
import {
setGroupTodo as setGroupTodo_,
completeGroupTodo as completeGroupTodo_,
cancelGroupTodo as cancelGroupTodo_,
getStrangerStatus as getStrangerStatus_,
fetchAiVoiceList as fetchAiVoiceList_,
fetchAiVoice as fetchAiVoice_,
AiVoiceChatType,
type AiVoiceCategory,
type AiVoiceChatType as AiVoiceChatTypeT,
type StrangerStatus,
} from './actions/extras';
export { AiVoiceChatType };
export type { AiVoiceCategory, StrangerStatus };
import {
getGroupHonorInfo as getGroupHonorInfo_,
forceFetchClientKey as forceFetchClientKey_,
getGroupEssence as getGroupEssence_,
getGroupEssenceAll as getGroupEssenceAll_,
sendGroupNotice as sendGroupNotice_,
getGroupNotice as getGroupNotice_,
deleteGroupNoticeByFid as deleteGroupNotice_,
getCookiesStr as getCookiesStr_,
getCsrfToken as getCsrfToken_,
getCredentials as getCredentials_,
} from './web-actions';
import type { GroupFilesResult } from './actions/group-file';
import type { MediaIndexNode } from './actions/shared';
import { BridgeEventBus } from './event-bus';
export interface SendMessageReceipt {
messageId: number;
sequence: number;
clientSequence: number;
random: number;
timestamp: number;
}
export interface DownloadRKeyInfo {
rkey: string;
ttlSeconds: number;
storeId: number;
createTime: number;
type: number;
}
export interface ClientKeyInfo {
clientKey: string;
expireTime: string;
keyIndex: string
}
const log = createLogger('Bridge');
export class Bridge implements BridgeInterface {
private static readonly SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
readonly identity: IdentityService;
private pids_ = new Set<number>();
/**
* Per-kind event subscription. Replaces the legacy single-callback
* firehose: downstream consumers now register exactly the kinds they
* care about and the pipeline fans out in parallel.
*/
readonly events = new BridgeEventBus();
private readonly pipeline: IncomingPacketPipeline;
private packetClient_: PacketSender | null = null;
// Throttle for fetchGroupMemberList(groupId): coalesces in-flight calls
// and serves a fresh result for `kMemberListTtlMs` to all callers.
// Without this, a busy OneBot client (e.g. MaiBot calling
// get_group_member_info(no_cache=true) per inbound message) would
// trigger one OIDB 0xfe7_3 per chat message per group; sustained rate
// (>1k/h) is detected by 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[] }>();
// Sequence and random generators for outgoing messages
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
constructor(identity: IdentityService) {
this.identity = identity;
this.identity.setFetcher({
fetchProfile: (uin) => this.fetchUserProfile(uin),
fetchGroupMemberList: (gid) => this.fetchGroupMemberList(gid),
});
this.pipeline = new IncomingPacketPipeline({
identity: this.identity,
events: this.events,
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
});
this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
}
dispose(): void {
this.identity.close();
this.events.clear();
}
setPacketClient(client: PacketSender): void {
this.packetClient_ = client;
}
registerCmd(cmd: string, parser: CmdParser): void {
this.pipeline.registerCmd(cmd, parser);
}
handlesCmd(cmd: string): boolean {
return this.pipeline.handlesCmd(cmd);
}
// --- PID management ---
attachPid(pid: number): void {
this.pids_.add(pid);
}
detachPid(pid: number): void {
this.pids_.delete(pid);
}
hasPid(pid: number): boolean { return this.pids_.has(pid); }
get empty(): boolean { return this.pids_.size === 0; }
get activePid(): number | null {
for (const pid of this.pids_) return pid;
return null;
}
// --- Packet dispatch ---
onPacket(pkt: PacketInfo): void {
this.pipeline.process(pkt);
}
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
if (refreshGroupList) {
try { await this.fetchGroupList(); } catch { /* ignore */ }
}
if (!this.identity.findGroup(groupId)) return false;
await this.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
}
// --- Sequence / random generators ---
private nextClientSequence(): number {
return ++this.clientSeq_;
}
private nextMessageRandom(): number {
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
return this.msgRandom_ & 0x7FFFFFFF;
}
// --- Send packet (raw) ---
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
if (!this.packetClient_) {
return {
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'no packet sender attached', responseData: null,
};
}
return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
}
// --- Send message (high-level) ---
async sendGroupMessage(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
const protoElems = await buildSendElems(elements, { bridge: this, groupId });
const random = this.nextMessageRandom();
const request = protoEncode({
routingHead: {
grp: { groupCode: BigInt(groupId) },
} as any,
contentHead: {
type: 1,
} as any,
messageBody: {
richText: {
elems: protoElems,
},
} as any,
clientSequence: 0,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
multiSendSeq: 0,
}, SendMessageRequestSchema);
const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`);
}
const response = protoDecode(result.responseData, SendMessageResponseSchema);
if (!response) {
throw new Error('failed to decode SendMessageResponse');
}
if (response.result !== undefined && 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,
};
}
async sendPrivateMessage(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
if (elements.length === 0) throw new Error('message is empty');
// Resolve UID for media upload and the final c2c routing head.
let userUid = '';
const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video');
if (hasMedia) {
userUid = await this.resolveUserUid(userUin);
}
const protoElems = await buildSendElems(elements, { bridge: this, userUid });
const random = this.nextMessageRandom();
const clientSeq = this.nextClientSequence();
const request = protoEncode({
routingHead: {
c2c: {
uin: userUin,
...(userUid ? { uid: userUid } : {}),
},
} as any,
contentHead: {
type: 1,
subType: 0,
c2cCmd: 11,
} as any,
messageBody: {
richText: {
elems: protoElems,
},
} as any,
clientSequence: clientSeq,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
ctrl: {
msgFlag: Math.floor(Date.now() / 1000),
} as any,
multiSendSeq: 0,
}, SendMessageRequestSchema);
const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`);
}
const response = protoDecode(result.responseData, SendMessageResponseSchema);
if (!response) {
throw new Error('failed to decode SendMessageResponse');
}
if (response.result !== undefined && 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,
};
}
// --- Delegated: OIDB helpers ---
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return this.identity.resolveUid(uin, groupId);
}
// --- Delegated: Contact / info queries ---
async fetchFriendList(): Promise<FriendInfo[]> { return fetchFriendList_(this); }
async fetchGroupList(): Promise<QQGroupInfo[]> { return fetchGroupList_(this); }
async fetchGroupMemberList(groupId: number, options: { force?: boolean } = {}): Promise<GroupMemberInfo[]> {
const kMemberListTtlMs = 60_000;
const now = Date.now();
const last = this.memberListLastFetch_.get(groupId);
if (!options.force && last && now - last.at < kMemberListTtlMs) {
return last.data;
}
const inflight = this.memberListInflight_.get(groupId);
if (inflight) return inflight;
const task = (async () => {
try {
const data = await fetchGroupMemberList_(this, groupId);
this.memberListLastFetch_.set(groupId, { at: Date.now(), data });
return data;
} finally {
this.memberListInflight_.delete(groupId);
}
})();
this.memberListInflight_.set(groupId, task);
return task;
}
async fetchUserProfile(uin: number): Promise<UserProfileInfo> { return fetchUserProfile_(this, uin); }
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> { return fetchGroupRequests_(this, filtered); }
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> { return fetchDownloadRKeys_(this); }
// --- Delegated: Admin / action methods ---
async muteGroupMember(groupId: number, userId: number, duration: number): Promise<void> { return muteGroupMember_(this, groupId, userId, duration); }
async muteGroupAll(groupId: number, enable: boolean): Promise<void> { return muteGroupAll_(this, groupId, enable); }
async setGroupAddOption(groupId: number, addType: number): Promise<void> { return setGroupAddOption_(this, groupId, addType); }
async setGroupSearch(groupId: number): Promise<void> { return setGroupSearch_(this, groupId); }
async kickGroupMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> { return kickGroupMember_(this, groupId, userId, reject, reason); }
async kickGroupMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> { return kickGroupMembers_(this, groupId, userIds, reject); }
async leaveGroup(groupId: number): Promise<void> { return leaveGroup_(this, groupId); }
async setGroupAdmin(groupId: number, userId: number, enable: boolean): Promise<void> { return setGroupAdmin_(this, groupId, userId, enable); }
async setGroupCard(groupId: number, userId: number, card: string): Promise<void> { return setGroupCard_(this, groupId, userId, card); }
async setGroupName(groupId: number, name: string): Promise<void> { return setGroupName_(this, groupId, name); }
async setGroupSpecialTitle(groupId: number, userId: number, title: string): Promise<void> { return setGroupSpecialTitle_(this, groupId, userId, title); }
async setFriendAddRequest(uidOrFlag: string, approve: boolean): Promise<void> { return setFriendAddRequest_(this, uidOrFlag, approve); }
async deleteFriend(userId: number, block = false): Promise<void> { return deleteFriend_(this, userId, block); }
async uploadGroupFile(groupId: number, file: string, name = '', folderId = '/', uploadFile = true): Promise<{ fileId: string | null }> {
return uploadGroupFile_(this, groupId, file, name, folderId, uploadFile);
}
async uploadPrivateFile(userId: number, file: string, name = '', uploadFile = true): Promise<{ fileId: string | null }> {
return uploadPrivateFile_(this, userId, file, name, uploadFile);
}
async fetchGroupFiles(groupId: number, folderId = '/'): Promise<GroupFilesResult> { return fetchGroupFiles_(this, groupId, folderId); }
async fetchGroupFileUrl(groupId: number, fileId: string, busId = 102): Promise<string> { return fetchGroupFileUrl_(this, groupId, fileId, busId); }
async fetchPrivateFileUrl(userId: number, fileId: string, fileHash: string): Promise<string> { return fetchPrivateFileUrl_(this, userId, fileId, fileHash); }
async fetchGroupPttUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupPttUrlByNode_(this, groupId, node); }
async fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivatePttUrlByNode_(this, node); }
async fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupVideoUrlByNode_(this, groupId, node); }
async fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivateVideoUrlByNode_(this, node); }
async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string> { return uploadForwardNodes_(this, nodes, groupId); }
async fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]> { return fetchForwardNodes_(this, resId); }
async deleteGroupFile(groupId: number, fileId: string): Promise<void> { return deleteGroupFile_(this, groupId, fileId); }
async moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> { return moveGroupFile_(this, groupId, fileId, parentDirectory, targetDirectory); }
async createGroupFileFolder(groupId: number, name: string, parentId = '/'): Promise<void> { return createGroupFileFolder_(this, groupId, name, parentId); }
async deleteGroupFileFolder(groupId: number, folderId: string): Promise<void> { return deleteGroupFileFolder_(this, groupId, folderId); }
async renameGroupFileFolder(groupId: number, folderId: string, newFolderName: string): Promise<void> { return renameGroupFileFolder_(this, groupId, folderId, newFolderName); }
async setGroupAddRequest(groupId: number, sequence: number, eventType: number, approve: boolean, reason = '', filtered = false): Promise<void> { return setGroupAddRequest_(this, groupId, sequence, eventType, approve, reason, filtered); }
async sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> { return sendPoke_(this, isGroup, peerUin, targetUin); }
async sendLike(userId: number, count: number): Promise<void> { return sendLike_(this, userId, count); }
async setGroupEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> { return setGroupEssence_(this, groupId, sequence, random, enable); }
async setGroupReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> { return setGroupReaction_(this, groupId, sequence, code, isSet); }
async recallGroupMessage(groupId: number, sequence: number): Promise<void> { return recallGroupMessage_(this, groupId, sequence); }
async recallPrivateMessage(userUin: number, clientSeq: number, msgSeq: number, random: number, timestamp: number): Promise<void> { return recallPrivateMessage_(this, userUin, clientSeq, msgSeq, random, timestamp); }
async markGroupMsgAsRead(groupId: number, sequence: number): Promise<void> { return markGroupMsgAsRead_(this, groupId, sequence); }
async markPrivateMsgAsRead(userId: number, sequence: number): Promise<void> { return markPrivateMsgAsRead_(this, userId, sequence); }
async setFriendRemark(userId: number, remark: string): Promise<void> { return setFriendRemark_(this, userId, remark); }
async setGroupRemark(groupId: number, remark: string): Promise<void> { return setGroupRemark_(this, groupId, remark); }
async getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise<any> {
return getGroupHonorInfo_(this, groupId, type);
}
async forceFetchClientKey(): Promise<ClientKeyInfo> { return forceFetchClientKey_(this)}
async getGroupEssence(groupId: number, pageStart: number = 0, pageLimit: number = 50): Promise<any> {
return getGroupEssence_(this, groupId, pageStart, pageLimit);
}
async getGroupEssenceAll(groupId: number): Promise<any> {
return getGroupEssenceAll_(this, groupId);
}
async sendGroupNotice(groupId: number, content: string, options?: any) {
return sendGroupNotice_(this, groupId, content, options);
}
async getGroupNotice(groupId: number) {
return getGroupNotice_(this, groupId);
}
async deleteGroupNotice(groupId: number, fid: string): Promise<boolean> {
return deleteGroupNotice_(this, groupId, fid);
}
async fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { return fetchGroupFileCount_(this, groupId); }
async getGroupAtAllRemain(groupId: number) {
return getGroupAtAllRemain_(this, groupId);
}
// extend
async setOnlineStatus(status: number, extStatus: number = 0, batteryStatus: number = 100): Promise<void> {
return setOnlineStatus_(this, status, extStatus, batteryStatus);
}
async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise<void> {
return setDiyOnlineStatus_(this, faceId, wording, faceType);
}
async setProfile(nickname?: string, personalNote?: string): Promise<void> {
return setProfile_(this, nickname, personalNote);
}
async getCookiesStr(domain: string): Promise<string> { return getCookiesStr_(this, domain); }
async getCsrfToken(): Promise<number> { return getCsrfToken_(this); }
async getCredentials(domain: string) { return getCredentials_(this, domain); }
async getProfileLike(userId?: number, start?: number, limit?: number) {
return getProfileLike_(this, userId, start, limit);
}
async getUnidirectionalFriendList() {
return getUnidirectionalFriendList_(this);
}
async setSelfLongNick(longNick: string) {
return setSelfLongNick_(this, longNick);
}
async setInputStatus(userId: number, eventType: number) {
return setInputStatus_(this, userId, eventType);
}
async translateEn2Zh(words: string[]) {
return translateEn2Zh_(this, words);
}
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string) {
return getMiniAppArk_(this, type, title, desc, picUrl, jumpUrl);
}
async clickInlineKeyboardButton(groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number) {
return clickInlineKeyboardButton_(this, groupId, botAppid, buttonId, callbackData, msgSeq);
}
async sendGroupSign(groupId: number) {
return sendGroupSign_(this, groupId);
}
async setAvatar(source: string): Promise<void> {
return setAvatar_(this, source);
}
async setGroupAvatar(groupId: number, source: string): Promise<void> {
return setGroupAvatar_(this, groupId, source);
}
async fetchCustomFace(count?: number): Promise<string[]> {
return fetchCustomFace_(this, count);
}
async getEmojiLikes(groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) {
return getEmojiLikes_(this, groupId, sequence, emojiId, emojiType, count, cookie);
}
// --- Tier-2 napcat-parity extras (group todo, stranger status, AI voice) ---
async setGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void> {
return setGroupTodo_(this, groupId, BigInt(msgSeq));
}
async completeGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void> {
return completeGroupTodo_(this, groupId, BigInt(msgSeq));
}
async cancelGroupTodo(groupId: number, msgSeq: bigint | number | string): Promise<void> {
return cancelGroupTodo_(this, groupId, BigInt(msgSeq));
}
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
return getStrangerStatus_(this, uin);
}
async fetchAiVoiceList(groupId: number, chatType: AiVoiceChatTypeT): Promise<AiVoiceCategory[]> {
return fetchAiVoiceList_(this, groupId, chatType);
}
async fetchAiVoice(groupId: number, voiceId: string, text: string, chatType: AiVoiceChatTypeT) {
return fetchAiVoice_(this, groupId, voiceId, text, chatType);
}
}

View File

@@ -1,122 +0,0 @@
// BridgeManager — manages per-UIN Bridge sessions.
// onPacket() is the single entry point for parsed hook packets;
// HookManager wires it as the default packet sink for every HookSession.
// Port of src/bridge/include/bridge/manager.h + src/bridge/src/manager.cpp
import type { PacketInfo } from '../protocol/types';
import { Bridge } from './bridge';
import { IdentityService } from './identity-service';
import type { PacketSender } from '../protocol/packet-sender';
import { createLogger } from '../utils/logger';
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string) => void;
interface QQSession {
bridge: Bridge;
}
const log = createLogger('Bridge');
export class BridgeManager {
private sessions_ = new Map<string, QQSession>();
private pidToUin_ = new Map<number, string>();
private pidPacketClients_ = new Map<number, PacketSender>();
private onSessionStarted_: SessionStartedCallback | null = null;
private onSessionClosed_: SessionClosedCallback | null = null;
setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; }
setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; }
onPidDisconnected(pid: number): void {
this.pidPacketClients_.delete(pid);
const uin = this.pidToUin_.get(pid);
if (!uin) return;
this.pidToUin_.delete(pid);
const session = this.sessions_.get(uin);
if (!session) return;
session.bridge.detachPid(pid);
if (session.bridge.empty) {
this.sessions_.delete(uin);
log.debug('session closed: UIN=%s', uin);
if (this.onSessionClosed_) this.onSessionClosed_(uin);
session.bridge.dispose();
}
}
private static isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
}
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
if (!BridgeManager.isRealUin(uin)) return;
this.pidPacketClients_.set(pid, packetClient);
const { session, created } = this.ensureSession(uin);
session.bridge.attachPid(pid);
session.bridge.setPacketClient(packetClient);
this.pidToUin_.set(pid, uin);
if (created) {
log.debug('session started: UIN=%s', uin);
if (this.onSessionStarted_) {
this.onSessionStarted_(uin, session.bridge);
}
}
}
onPacket(pkt: PacketInfo): void {
if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return;
const uin = pkt.uin;
// Ensure session exists
const { session, created } = this.ensureSession(uin);
// Attach PID if known
if (pkt.pid && this.pidPacketClients_.has(pkt.pid)) {
session.bridge.attachPid(pkt.pid);
this.pidToUin_.set(pkt.pid, uin);
const client = this.pidPacketClients_.get(pkt.pid);
if (client) session.bridge.setPacketClient(client);
}
// Notify session started on first real packet
if (created) {
log.debug('session started: UIN=%s', uin);
if (this.onSessionStarted_) {
this.onSessionStarted_(uin, session.bridge);
}
}
// Dispatch packet to bridge
session.bridge.onPacket(pkt);
}
private ensureSession(uin: string): { session: QQSession; created: boolean } {
let session = this.sessions_.get(uin);
if (session) return { session, created: false };
const bridge = new Bridge(IdentityService.openForUin(uin));
session = { bridge };
this.sessions_.set(uin, session);
// Each downstream consumer (e.g. OneBotInstance) subscribes to
// `bridge.events` directly via the per-kind bus — there is no longer a
// generic firehose to wire here.
return { session, created: true };
}
getSession(uin: string): QQSession | null {
return this.sessions_.get(uin) ?? null;
}
get sessions(): Map<string, { bridge: Bridge }> {
return this.sessions_;
}
}

View File

@@ -1,73 +0,0 @@
// Handles Event0x210 wrapper (528). Internal switch on subType dispatches
// to FriendRequest (35) / FriendRecall (138) / FriendPoke (290).
import { protoDecode } from '../../../protobuf/decode';
import {
FriendRequestSchema, FriendRecallSchema, GeneralGrayTipInfoSchema,
} from '../../proto/notify';
import type {
FriendRequestEvent, FriendRecall, FriendPokeEvent, QQEventVariant,
} from '../../events';
import type { MsgPushDecoder } from '../registry';
import type { MsgPushContext } from '../context';
import { Event0x210SubType } from '../enums';
import {
resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue,
} from '../helpers';
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x210SubType) {
case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx);
case Event0x210SubType.FriendRecallNotice: return decodeFriendRecall(ctx);
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
}
return [];
};
function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] {
const request = protoDecode(ctx.content, FriendRequestSchema);
if (!request?.info) return [];
const sourceUid = request.info.newSource || request.info.sourceUid || '';
const ev: FriendRequestEvent = {
kind: 'friend_request',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
fromUin: resolveUidToUin(ctx.identity, 0, sourceUid, ctx.fromUin),
fromUid: sourceUid,
message: request.info.message ?? '',
flag: sourceUid,
};
return [ev];
}
function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] {
const recall = protoDecode(ctx.content, FriendRecallSchema);
if (!recall?.info) return [];
const ev: FriendRecall = {
kind: 'friend_recall',
time: recall.info.time ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, recall.info.fromUid ?? '', ctx.fromUin),
msgSeq: recall.info.clientSequence ?? 0,
};
return [ev];
}
function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] {
const grayTip = protoDecode(ctx.content, GeneralGrayTipInfoSchema);
if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return [];
const templates = buildTemplateMap(grayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
const target = findTemplateValue(templates, 'uin_str2');
const ev: FriendPokeEvent = {
kind: 'friend_poke',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, actor, parseU64OrZero(actor)),
targetUin: resolveUidToUin(ctx.identity, 0, target, parseU64OrZero(target)),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
}

View File

@@ -1,33 +0,0 @@
// MsgPush PkgType taxonomy. The top-level msgType field in PushMsg.contentHead
// names a QQ-protocol-defined packet shape; Event0x210 / Event0x2DC are wrapper
// PkgTypes whose payload is further dispatched by subType.
export enum PkgType {
ForwardFakePrivateMessage = 9,
PrivateMessage = 166,
GroupMessage = 82,
TempMessage = 141,
Event0x210 = 528,
Event0x2DC = 732,
PrivateRecordMessage = 208,
PrivateFileMessage = 529,
GroupRequestInvitationNotice = 525,
GroupRequestJoinNotice = 84,
GroupInviteNotice = 87,
GroupAdminChangedNotice = 44,
GroupMemberIncreaseNotice = 33,
GroupMemberDecreaseNotice = 34,
}
export enum Event0x2DCSubType {
GroupMuteNotice = 12,
GroupRecallNotice = 17,
GroupGreyTipNotice = 20,
GroupEssenceNotice = 21,
}
export enum Event0x210SubType {
FriendRequestNotice = 35,
FriendRecallNotice = 138,
FriendPokeNotice = 290,
}

View File

@@ -1,275 +0,0 @@
// Incoming packet pipeline — the chain that turns a single PacketInfo
// arriving from the hook layer into a stream of QQEventVariant
// emissions on the typed event bus. Replaces the inline orchestration
// that previously lived on Bridge.onPacket / triggerMemberCacheRefresh /
// rememberEventIdentity / dispatchAfterIdentityRefresh / etc.
//
// Stage chain per parser output:
// parse → enrich identity (sync, or async refresh)
// → side-effects (remember UID/UIN + schedule roster refresh)
// → log
// → emit on bus
//
// The pipeline owns its cmd handler map and its per-group coalesce table
// for background member-list refreshes. It does NOT own protocol calls
// — `refreshMemberCache` is injected by Bridge because it ultimately
// dispatches OIDB packets through Bridge.fetchGroupList /
// Bridge.fetchGroupMemberList.
import type { PacketInfo } from '../protocol/types';
import type { QQEventVariant } from './events';
import type { IdentityService } from './identity-service';
import type { BridgeEventBus } from './event-bus';
import { createLogger } from '../utils/logger';
const log = createLogger('Bridge');
const eventLog = createLogger('Event');
type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
export type CmdParser = (pkt: PacketInfo, identity: IdentityService) => QQEventVariant[];
export interface PacketPipelineDeps {
identity: IdentityService;
events: BridgeEventBus;
/**
* Refresh group + member roster as a side-effect. Resolves with
* whether any refresh actually ran (false when the group is unknown
* and `refreshGroupList` was false).
*/
refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean>;
}
export class IncomingPacketPipeline {
private cmdHandlers_ = new Map<string, CmdParser[]>();
private memberRefreshTasks_ = new Map<number, Promise<void>>();
constructor(private readonly deps: PacketPipelineDeps) {}
registerCmd(cmd: string, parser: CmdParser): void {
const arr = this.cmdHandlers_.get(cmd) ?? [];
arr.push(parser);
this.cmdHandlers_.set(cmd, arr);
}
handlesCmd(cmd: string): boolean {
return this.cmdHandlers_.has(cmd);
}
process(pkt: PacketInfo): void {
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
if (!handlers) return;
for (const handler of handlers) {
try {
const events = handler(pkt, this.deps.identity);
for (const event of events) {
if (this.needsPreDispatchIdentityRefresh(event)) {
void this.dispatchAfterIdentityRefresh(event);
} else {
this.handleSideEffects(event);
printEvent(event);
this.emit(event);
}
}
} catch (e) {
log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
}
}
}
private emit(event: QQEventVariant): void {
// Fire-and-forget: errors inside subscribers are surfaced via the bus's
// own onError hook so one bad listener never blocks the others.
void this.deps.events.emit(event);
}
private needsPreDispatchIdentityRefresh(event: QQEventVariant): event is Extract<QQEventVariant, { kind: 'group_member_join' }> {
return event.kind === 'group_member_join' && event.groupId > 0 && event.userUin <= 0 && Boolean(event.userUid);
}
private async dispatchAfterIdentityRefresh(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<void> {
let refreshed = false;
try {
refreshed = await this.prepareGroupMemberJoinIdentity(event);
} catch (e) {
log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e));
}
this.handleSideEffects(event, refreshed);
printEvent(event);
this.emit(event);
}
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<boolean> {
this.resolveMemberIdentityFromCache(event);
if (event.userUin > 0 || !event.userUid || event.groupId <= 0) return false;
const refreshed = await this.deps.refreshMemberCache(
event.groupId,
!this.deps.identity.findGroup(event.groupId) || this.isSelfMemberIdentity(event.userUin, event.userUid),
true,
);
this.resolveMemberIdentityFromCache(event);
return refreshed;
}
private resolveMemberIdentityFromCache(event: GroupMemberIdentityEvent): void {
if (event.groupId <= 0) return;
if (event.userUin <= 0 && event.userUid) {
const uin = this.deps.identity.findUinByUid(event.userUid, event.groupId);
if (uin !== null) event.userUin = uin;
}
if (event.operatorUin <= 0 && event.operatorUid) {
const uin = this.deps.identity.findUinByUid(event.operatorUid, event.groupId);
if (uin !== null) event.operatorUin = uin;
}
}
private isSelfMemberIdentity(uin: number, uid?: string): boolean {
const selfUin = Number(this.deps.identity.uin);
return (uin > 0 && uin === selfUin) || (Boolean(uid) && uid === this.deps.identity.selfUid);
}
private handleSideEffects(event: QQEventVariant, alreadyRefreshed = false): void {
this.rememberEventIdentity(event);
if (alreadyRefreshed) return;
let groupId = 0;
let reason = '';
let refreshGroupList = false;
switch (event.kind) {
case 'group_member_join':
groupId = event.groupId;
reason = 'group_member_join';
refreshGroupList = this.isSelfMemberIdentity(event.userUin, event.userUid);
break;
case 'group_member_leave':
groupId = event.groupId;
reason = 'group_member_leave';
break;
case 'group_admin':
groupId = event.groupId;
reason = 'group_admin';
break;
default:
return;
}
if (groupId <= 0) return;
if (this.memberRefreshTasks_.has(groupId)) return;
if (event.kind === 'group_member_join' && !this.deps.identity.findGroup(groupId)) {
refreshGroupList = true;
}
const task = (async () => {
try {
await this.deps.refreshMemberCache(groupId, refreshGroupList, false);
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
} catch (e) {
log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
groupId, reason, e instanceof Error ? e.message : String(e));
} finally {
this.memberRefreshTasks_.delete(groupId);
}
})();
this.memberRefreshTasks_.set(groupId, task);
}
private rememberEventIdentity(event: QQEventVariant): void {
switch (event.kind) {
case 'group_member_join':
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_member_leave':
this.deps.identity.markGroupMemberInactive(event.groupId, {
uid: event.userUid,
uin: event.userUin,
});
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.operatorUid,
uin: event.operatorUin,
});
break;
case 'group_admin':
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uin: event.userUin,
});
break;
case 'friend_request':
this.deps.identity.rememberRequestIdentity({
uid: event.fromUid,
uin: event.fromUin,
source: 'friend_request',
});
break;
case 'group_invite':
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid: event.fromUid,
uin: event.fromUin,
source: 'group_request',
});
break;
default:
break;
}
}
}
function formatEventUser(uin: number, uid?: string): string {
if (uin > 0) return String(uin);
return uid || '未知用户';
}
function printEvent(event: QQEventVariant): void {
switch (event.kind) {
case 'group_message':
case 'friend_message':
case 'temp_message':
// Message logging is handled by OneBot layer with message ID
break;
case 'group_recall':
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
break;
case 'friend_recall':
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
break;
case 'group_member_join':
eventLog.info('入群 %s 加入 %d', formatEventUser(event.userUin, event.userUid), event.groupId);
break;
case 'group_member_leave':
eventLog.warn('退群 %s %s %d', formatEventUser(event.userUin, event.userUid), event.isKick ? '被踢出' : '退出', event.groupId);
break;
case 'group_mute':
eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration);
break;
case 'group_admin':
eventLog.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-');
break;
case 'friend_poke':
eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin);
break;
case 'group_poke':
eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin);
break;
case 'friend_request':
eventLog.warn('好友请求 %d: %s', event.fromUin, event.message);
break;
case 'group_invite':
eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId);
break;
case 'group_essence':
eventLog.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-');
break;
}
}

View File

@@ -1,89 +0,0 @@
// Proto schemas for outgoing message actions.
// Port of src/bridge/include/bridge/proto/action.h
import type { ProtoSchema } from '../../protobuf/decode';
import { ElemSchema } from './element';
// --- Routing ---
export const RoutingC2CSchema = {
uin: { field: 1, type: 'uint32' as const },
uid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const RoutingGroupSchema = {
groupCode: { field: 1, type: 'uint64' as const },
} satisfies ProtoSchema;
export const RoutingHeadSchema = {
c2c: { field: 1, type: 'message' as const, schema: RoutingC2CSchema },
grp: { field: 2, type: 'message' as const, schema: RoutingGroupSchema },
} satisfies ProtoSchema;
// --- Content Head (for send) ---
export const SendContentHeadSchema = {
type: { field: 1, type: 'uint32' as const },
subType: { field: 2, type: 'uint32' as const },
c2cCmd: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- Message Control ---
export const MessageControlSchema = {
msgFlag: { field: 1, type: 'int32' as const },
} satisfies ProtoSchema;
// --- RichText (for send — only elems) ---
export const SendRichTextSchema = {
elems: { field: 2, type: 'repeated_message' as const, schema: ElemSchema },
} satisfies ProtoSchema;
// --- MessageBody (for send) ---
export const SendMessageBodySchema = {
richText: { field: 1, type: 'message' as const, schema: SendRichTextSchema },
} satisfies ProtoSchema;
// --- SendMessageRequest ---
export const SendMessageRequestSchema = {
routingHead: { field: 1, type: 'message' as const, schema: RoutingHeadSchema },
contentHead: { field: 2, type: 'message' as const, schema: SendContentHeadSchema },
messageBody: { field: 3, type: 'message' as const, schema: SendMessageBodySchema },
clientSequence: { field: 4, type: 'uint32' as const },
random: { field: 5, type: 'uint32' as const },
syncCookie: { field: 6, type: 'bytes' as const },
via: { field: 8, type: 'uint32' as const },
dataStatist: { field: 9, type: 'uint32' as const },
ctrl: { field: 12, type: 'message' as const, schema: MessageControlSchema },
multiSendSeq: { field: 14, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- SendMessageResponse ---
export const SendMessageResponseSchema = {
result: { field: 1, type: 'int32' as const },
errMsg: { field: 2, type: 'string' as const },
timestamp1: { field: 3, type: 'uint32' as const },
field10: { field: 10, type: 'uint32' as const },
groupSequence: { field: 11, type: 'uint32' as const },
timestamp2: { field: 12, type: 'uint32' as const },
privateSequence: { field: 14, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- MentionExtra (for building @mention text element) ---
export const MentionExtraSendSchema = {
type: { field: 3, type: 'int32' as const },
uin: { field: 4, type: 'uint32' as const },
field5: { field: 5, type: 'int32' as const },
uid: { field: 9, type: 'string' as const },
} satisfies ProtoSchema;
// --- MarkdownData ---
export const MarkdownDataSchema = {
content: { field: 1, type: 'string' as const },
} satisfies ProtoSchema;

View File

@@ -1,418 +0,0 @@
// Proto schemas for QQ message elements.
// Port of src/bridge/include/bridge/proto/element.h
import type { ProtoSchema } from '../../protobuf/decode';
// --- Nested / helper schemas ---
export const CustomFacePbReserveSchema = {
subType: { field: 1, type: 'int32' as const },
summary: { field: 9, type: 'string' as const },
} satisfies ProtoSchema;
export const NotOnlineImagePbReserve2Schema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'string' as const },
field3: { field: 3, type: 'int32' as const },
field4: { field: 4, type: 'int32' as const },
field5: { field: 5, type: 'int32' as const },
field7: { field: 7, type: 'string' as const },
} satisfies ProtoSchema;
export const NotOnlineImagePbReserveSchema = {
subType: { field: 1, type: 'int32' as const },
field3: { field: 3, type: 'int32' as const },
field4: { field: 4, type: 'int32' as const },
summary: { field: 8, type: 'string' as const },
field10: { field: 10, type: 'int32' as const },
field20: { field: 20, type: 'message' as const, schema: NotOnlineImagePbReserve2Schema },
url: { field: 30, type: 'string' as const },
md5Str: { field: 31, type: 'string' as const },
} satisfies ProtoSchema;
// --- Core element schemas ---
export const TextElemSchema = {
str: { field: 1, type: 'string' as const },
link: { field: 2, type: 'string' as const },
attr6Buf: { field: 3, type: 'bytes' as const },
attr7Buf: { field: 4, type: 'bytes' as const },
buf: { field: 11, type: 'bytes' as const },
pbReserve: { field: 12, type: 'bytes' as const },
} satisfies ProtoSchema;
export const FaceElemSchema = {
index: { field: 1, type: 'int32' as const },
oldData: { field: 2, type: 'bytes' as const },
buf: { field: 11, type: 'bytes' as const },
} satisfies ProtoSchema;
export const OnlineImageSchema = {
guid: { field: 1, type: 'bytes' as const },
filePath: { field: 2, type: 'bytes' as const },
oldVerSendFile: { field: 3, type: 'bytes' as const },
} satisfies ProtoSchema;
export const NotOnlineImageSchema = {
filePath: { field: 1, type: 'string' as const },
fileLen: { field: 2, type: 'uint32' as const },
downloadPath: { field: 3, type: 'string' as const },
oldVerSendFile: { field: 4, type: 'bytes' as const },
imgType: { field: 5, type: 'int32' as const },
previewsImage: { field: 6, type: 'bytes' as const },
picMd5: { field: 7, type: 'bytes' as const },
picHeight: { field: 8, type: 'uint32' as const },
picWidth: { field: 9, type: 'uint32' as const },
resId: { field: 10, type: 'string' as const },
flag: { field: 11, type: 'bytes' as const },
thumbUrl: { field: 12, type: 'string' as const },
original: { field: 13, type: 'int32' as const },
bigUrl: { field: 14, type: 'string' as const },
origUrl: { field: 15, type: 'string' as const },
bizType: { field: 16, type: 'int32' as const },
result: { field: 17, type: 'int32' as const },
index: { field: 18, type: 'int32' as const },
opFaceBuf: { field: 19, type: 'bytes' as const },
oldPicMd5: { field: 20, type: 'bool' as const },
thumbWidth: { field: 21, type: 'int32' as const },
thumbHeight: { field: 22, type: 'int32' as const },
fileId: { field: 23, type: 'int32' as const },
showLen: { field: 24, type: 'uint32' as const },
downloadLen: { field: 25, type: 'uint32' as const },
x400Url: { field: 26, type: 'string' as const },
x400Width: { field: 27, type: 'int32' as const },
x400Height: { field: 28, type: 'int32' as const },
pbRes: { field: 29, type: 'message' as const, schema: NotOnlineImagePbReserveSchema },
} satisfies ProtoSchema;
export const TransElemSchema = {
elemType: { field: 1, type: 'int32' as const },
elemValue: { field: 2, type: 'bytes' as const },
} satisfies ProtoSchema;
export const MarketFaceSchema = {
faceName: { field: 1, type: 'string' as const },
itemType: { field: 2, type: 'uint32' as const },
faceInfo: { field: 3, type: 'uint32' as const },
faceId: { field: 4, type: 'bytes' as const },
tabId: { field: 5, type: 'uint32' as const },
subType: { field: 6, type: 'uint32' as const },
key: { field: 7, type: 'bytes' as const },
param: { field: 8, type: 'bytes' as const },
mediaType: { field: 9, type: 'uint32' as const },
imageWidth: { field: 10, type: 'uint32' as const },
imageHeight: { field: 11, type: 'uint32' as const },
mobileParam: { field: 12, type: 'bytes' as const },
pbReserve: { field: 13, type: 'bytes' as const },
} satisfies ProtoSchema;
export const CustomFaceSchema = {
guid: { field: 1, type: 'bytes' as const },
filePath: { field: 2, type: 'string' as const },
shortcut: { field: 3, type: 'string' as const },
buffer: { field: 4, type: 'bytes' as const },
flag: { field: 5, type: 'bytes' as const },
oldData: { field: 6, type: 'bytes' as const },
fileId: { field: 7, type: 'uint32' as const },
serverIp: { field: 8, type: 'int32' as const },
serverPort: { field: 9, type: 'int32' as const },
fileType: { field: 10, type: 'int32' as const },
signature: { field: 11, type: 'bytes' as const },
useful: { field: 12, type: 'int32' as const },
md5: { field: 13, type: 'bytes' as const },
thumbUrl: { field: 14, type: 'string' as const },
bigUrl: { field: 15, type: 'string' as const },
origUrl: { field: 16, type: 'string' as const },
bizType: { field: 17, type: 'int32' as const },
repeatIndex: { field: 18, type: 'int32' as const },
repeatImage: { field: 19, type: 'int32' as const },
imageType: { field: 20, type: 'int32' as const },
index: { field: 21, type: 'int32' as const },
width: { field: 22, type: 'int32' as const },
height: { field: 23, type: 'int32' as const },
source: { field: 24, type: 'int32' as const },
size: { field: 25, type: 'uint32' as const },
origin: { field: 26, type: 'int32' as const },
thumbWidth: { field: 27, type: 'int32' as const },
thumbHeight: { field: 28, type: 'int32' as const },
showLen: { field: 29, type: 'int32' as const },
downloadLen: { field: 30, type: 'int32' as const },
x400Url: { field: 31, type: 'string' as const },
x400Width: { field: 32, type: 'int32' as const },
x400Height: { field: 33, type: 'int32' as const },
pbRes: { field: 34, type: 'message' as const, schema: CustomFacePbReserveSchema },
} satisfies ProtoSchema;
export const RichMsgSchema = {
template1: { field: 1, type: 'bytes' as const },
serviceId: { field: 2, type: 'int32' as const },
msgResId: { field: 3, type: 'bytes' as const },
rand: { field: 4, type: 'int32' as const },
seq: { field: 5, type: 'uint32' as const },
} satisfies ProtoSchema;
export const GroupFileElemSchema = {
filename: { field: 1, type: 'string' as const },
fileSize: { field: 2, type: 'uint64' as const },
fileId: { field: 3, type: 'string' as const },
batchId: { field: 4, type: 'string' as const },
fileKey: { field: 5, type: 'string' as const },
mark: { field: 6, type: 'bytes' as const },
sequence: { field: 7, type: 'uint64' as const },
batchItemId: { field: 8, type: 'bytes' as const },
feedMsgTime: { field: 9, type: 'int32' as const },
pbReserve: { field: 10, type: 'bytes' as const },
} satisfies ProtoSchema;
export const ExtraInfoSchema = {
nick: { field: 1, type: 'bytes' as const },
groupCard: { field: 2, type: 'bytes' as const },
level: { field: 3, type: 'int32' as const },
flags: { field: 4, type: 'int32' as const },
groupMask: { field: 5, type: 'int32' as const },
msgTailId: { field: 6, type: 'int32' as const },
senderTitle: { field: 7, type: 'bytes' as const },
apnsTips: { field: 8, type: 'bytes' as const },
uin: { field: 9, type: 'uint64' as const },
msgStateFlag: { field: 10, type: 'int32' as const },
apnsSoundType: { field: 11, type: 'int32' as const },
newGroupFlag: { field: 12, type: 'int32' as const },
} satisfies ProtoSchema;
export const VideoFileSchema = {
fileUuid: { field: 1, type: 'string' as const },
fileMd5: { field: 2, type: 'bytes' as const },
fileName: { field: 3, type: 'string' as const },
fileFormat: { field: 4, type: 'int32' as const },
fileTime: { field: 5, type: 'int32' as const },
fileSize: { field: 6, type: 'int32' as const },
thumbWidth: { field: 7, type: 'int32' as const },
thumbHeight: { field: 8, type: 'int32' as const },
thumbFileMd5: { field: 9, type: 'bytes' as const },
source: { field: 10, type: 'bytes' as const },
thumbFileSize:{ field: 11, type: 'int32' as const },
busiType: { field: 12, type: 'int32' as const },
fromChatType: { field: 13, type: 'int32' as const },
toChatType: { field: 14, type: 'int32' as const },
supportProgressive: { field: 15, type: 'bool' as const },
fileWidth: { field: 16, type: 'int32' as const },
fileHeight: { field: 17, type: 'int32' as const },
subBusiType: { field: 18, type: 'int32' as const },
videoAttr: { field: 19, type: 'int32' as const },
pbReserve: { field: 24, type: 'bytes' as const },
} satisfies ProtoSchema;
export const SrcMsgSchema = {
origSeqs: { field: 1, type: 'repeated_uint32' as const },
senderUin: { field: 2, type: 'uint64' as const },
time: { field: 3, type: 'int32' as const },
flag: { field: 4, type: 'int32' as const },
elemsRaw: { field: 5, type: 'repeated_bytes' as const },
type: { field: 6, type: 'int32' as const },
richMsg: { field: 7, type: 'bytes' as const },
pbReserve: { field: 8, type: 'bytes' as const },
sourceMsg: { field: 9, type: 'bytes' as const },
toUin: { field: 10, type: 'uint64' as const },
troopName: { field: 11, type: 'bytes' as const },
} satisfies ProtoSchema;
export const LightAppElemSchema = {
data: { field: 1, type: 'bytes' as const },
msgResid: { field: 2, type: 'bytes' as const },
} satisfies ProtoSchema;
export const CommonElemSchema = {
serviceType: { field: 1, type: 'int32' as const },
pbElem: { field: 2, type: 'bytes' as const },
businessType: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const GeneralFlagsSchema = {
bubbleDiyTextId: { field: 1, type: 'int32' as const },
groupFlagNew: { field: 2, type: 'int32' as const },
uin: { field: 3, type: 'uint64' as const },
longTextFlag: { field: 6, type: 'int32' as const },
longTextResId: { field: 7, type: 'string' as const },
} satisfies ProtoSchema;
// --- Elem (union of all element types) ---
export const ElemSchema = {
text: { field: 1, type: 'message' as const, schema: TextElemSchema },
face: { field: 2, type: 'message' as const, schema: FaceElemSchema },
onlineImage: { field: 3, type: 'message' as const, schema: OnlineImageSchema },
notOnlineImage: { field: 4, type: 'message' as const, schema: NotOnlineImageSchema },
transElem: { field: 5, type: 'message' as const, schema: TransElemSchema },
marketFace: { field: 6, type: 'message' as const, schema: MarketFaceSchema },
customFace: { field: 8, type: 'message' as const, schema: CustomFaceSchema },
richMsg: { field: 12, type: 'message' as const, schema: RichMsgSchema },
groupFile: { field: 13, type: 'message' as const, schema: GroupFileElemSchema },
extraInfo: { field: 16, type: 'message' as const, schema: ExtraInfoSchema },
videoFile: { field: 19, type: 'message' as const, schema: VideoFileSchema },
generalFlags: { field: 37, type: 'message' as const, schema: GeneralFlagsSchema },
srcMsg: { field: 45, type: 'message' as const, schema: SrcMsgSchema },
lightApp: { field: 51, type: 'message' as const, schema: LightAppElemSchema },
commonElem: { field: 53, type: 'message' as const, schema: CommonElemSchema },
} satisfies ProtoSchema;
// --- Extra decode types (for CommonElem.pbElem sub-messages) ---
export const MentionExtraSchema = {
type: { field: 3, type: 'int32' as const },
uin: { field: 4, type: 'uint32' as const },
field5: { field: 5, type: 'int32' as const },
uid: { field: 9, type: 'string' as const },
} satisfies ProtoSchema;
export const QFaceExtraSchema = {
packId: { field: 1, type: 'string' as const },
stickerId: { field: 2, type: 'string' as const },
qsid: { field: 3, type: 'int32' as const },
sourceType: { field: 4, type: 'int32' as const },
stickerType: { field: 5, type: 'int32' as const },
resultId: { field: 6, type: 'string' as const },
text: { field: 7, type: 'string' as const },
randomType: { field: 9, type: 'int32' as const },
} satisfies ProtoSchema;
export const QSmallFaceExtraSchema = {
faceId: { field: 1, type: 'uint32' as const },
preview: { field: 2, type: 'string' as const },
preview2: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
// --- NTQQ MsgInfo types (CommonElem service_type 48) ---
export const FileTypeSchema = {
type: { field: 1, type: 'uint32' as const },
picFormat: { field: 2, type: 'uint32' as const },
videoFormat: { field: 3, type: 'uint32' as const },
voiceFormat: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const FileInfoSchema = {
fileSize: { field: 1, type: 'uint32' as const },
fileHash: { field: 2, type: 'string' as const },
fileSha1: { field: 3, type: 'string' as const },
fileName: { field: 4, type: 'string' as const },
type: { field: 5, type: 'message' as const, schema: FileTypeSchema },
width: { field: 6, type: 'uint32' as const },
height: { field: 7, type: 'uint32' as const },
time: { field: 8, type: 'uint32' as const },
original: { field: 9, type: 'uint32' as const },
} satisfies ProtoSchema;
export const IndexNodeSchema = {
info: { field: 1, type: 'message' as const, schema: FileInfoSchema },
fileUuid: { field: 2, type: 'string' as const },
storeId: { field: 3, type: 'uint32' as const },
uploadTime: { field: 4, type: 'uint32' as const },
ttl: { field: 5, type: 'uint32' as const },
subType: { field: 6, type: 'uint32' as const },
} satisfies ProtoSchema;
export const PicUrlExtInfoSchema = {
originalParameter: { field: 1, type: 'string' as const },
bigParameter: { field: 2, type: 'string' as const },
thumbParameter: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const PictureInfoSchema = {
urlPath: { field: 1, type: 'string' as const },
ext: { field: 2, type: 'message' as const, schema: PicUrlExtInfoSchema },
domain: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const PicExtDataSchema = {
subType: { field: 1, type: 'uint32' as const },
textSummary: { field: 9, type: 'string' as const },
} satisfies ProtoSchema;
export const PicExtBizInfoSchema = {
bizType: { field: 1, type: 'uint32' as const },
textSummary: { field: 2, type: 'string' as const },
bytesPbReserveC2c: { field: 11, type: 'bytes' as const },
extData: { field: 12, type: 'message' as const, schema: PicExtDataSchema },
fromScene: { field: 1001, type: 'uint32' as const },
toScene: { field: 1002, type: 'uint32' as const },
oldFileId: { field: 1003, type: 'uint32' as const },
} satisfies ProtoSchema;
export const VideoExtBizInfoSchema = {
fromScene: { field: 1, type: 'uint32' as const },
toScene: { field: 2, type: 'uint32' as const },
bytesPbReserve: { field: 3, type: 'bytes' as const },
} satisfies ProtoSchema;
export const PttExtBizInfoSchema = {
srcUin: { field: 1, type: 'uint64' as const },
pttScene: { field: 2, type: 'uint32' as const },
pttType: { field: 3, type: 'uint32' as const },
changeVoice: { field: 4, type: 'uint32' as const },
waveform: { field: 5, type: 'bytes' as const },
autoConvertText: { field: 6, type: 'uint32' as const },
bytesReserve: { field: 11, type: 'bytes' as const },
bytesPbReserve: { field: 12, type: 'bytes' as const },
bytesGeneralFlags: { field: 13, type: 'bytes' as const },
} satisfies ProtoSchema;
export const ExtBizInfoSchema = {
pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema },
video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema },
ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema },
busiType: { field: 10, type: 'uint32' as const },
} satisfies ProtoSchema;
export const C2cSourceSchema = {
friendUid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const TroopSourceSchema = {
groupUin: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const HashSumSchema = {
bytesPbReserveC2c: { field: 201, type: 'message' as const, schema: C2cSourceSchema },
troopSource: { field: 202, type: 'message' as const, schema: TroopSourceSchema },
} satisfies ProtoSchema;
export const MsgInfoBodySchema = {
index: { field: 1, type: 'message' as const, schema: IndexNodeSchema },
picture: { field: 2, type: 'message' as const, schema: PictureInfoSchema },
fileExist: { field: 5, type: 'bool' as const },
hashSum: { field: 6, type: 'message' as const, schema: HashSumSchema },
} satisfies ProtoSchema;
export const MsgInfoSchema = {
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: MsgInfoBodySchema },
extBizInfo: { field: 2, type: 'message' as const, schema: ExtBizInfoSchema },
} satisfies ProtoSchema;
// --- GroupFileExtra (TransElem type=24) ---
export const GroupFileInfoSchema = {
busId: { field: 1, type: 'uint32' as const },
fileId: { field: 2, type: 'string' as const },
fileSize: { field: 3, type: 'uint64' as const },
fileName: { field: 4, type: 'string' as const },
fileSha: { field: 5, type: 'bytes' as const },
extInfoString: { field: 6, type: 'string' as const },
fileMd5: { field: 7, type: 'bytes' as const },
} satisfies ProtoSchema;
export const GroupFileExtraInnerSchema = {
info: { field: 2, type: 'message' as const, schema: GroupFileInfoSchema },
} satisfies ProtoSchema;
export const GroupFileExtraSchema = {
inner: { field: 7, type: 'message' as const, schema: GroupFileExtraInnerSchema },
} satisfies ProtoSchema;
// --- Preserve (for message receipt info) ---
export const PreserveSchema = {
messageId: { field: 3, type: 'uint64' as const },
senderUid: { field: 6, type: 'string' as const },
receiverUid: { field: 7, type: 'string' as const },
clientSequence: { field: 8, type: 'uint32' as const },
} satisfies ProtoSchema;

View File

@@ -1,336 +0,0 @@
// Proto schemas for highway upload protocol.
// Port of src/bridge/include/bridge/proto/highway.h + action.h (HttpConn)
import type { ProtoSchema } from '../../protobuf/decode';
import {
IndexNodeSchema,
PictureInfoSchema,
HashSumSchema,
PicExtBizInfoSchema,
VideoExtBizInfoSchema,
PttExtBizInfoSchema,
} from '../proto/element';
// --- DataHighwayHead ---
export const DataHighwayHeadSchema = {
version: { field: 1, type: 'uint32' as const },
uin: { field: 2, type: 'string' as const },
command: { field: 3, type: 'string' as const },
seq: { field: 4, type: 'uint32' as const },
retryTimes:{ field: 5, type: 'uint32' as const },
appId: { field: 6, type: 'uint32' as const },
dataFlag: { field: 7, type: 'uint32' as const },
commandId: { field: 8, type: 'uint32' as const },
} satisfies ProtoSchema;
export const SegHeadSchema = {
serviceId: { field: 1, type: 'uint32' as const },
filesize: { field: 2, type: 'uint64' as const },
dataOffset: { field: 3, type: 'uint64' as const },
dataLength: { field: 4, type: 'uint32' as const },
retCode: { field: 5, type: 'uint32' as const },
serviceTicket: { field: 6, type: 'bytes' as const },
flag: { field: 7, type: 'uint32' as const },
md5: { field: 8, type: 'bytes' as const },
fileMd5: { field: 9, type: 'bytes' as const },
cacheAddr: { field: 10, type: 'uint32' as const },
cachePort: { field: 13, type: 'uint32' as const },
} satisfies ProtoSchema;
export const LoginSigHeadSchema = {
loginSigType: { field: 1, type: 'uint32' as const },
appId: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
export const ReqDataHighwayHeadSchema = {
msgBaseHead: { field: 1, type: 'message' as const, schema: DataHighwayHeadSchema },
msgSegHead: { field: 2, type: 'message' as const, schema: SegHeadSchema },
bytesReqExtendInfo: { field: 3, type: 'bytes' as const },
timestamp: { field: 4, type: 'uint64' as const },
msgLoginSigHead: { field: 5, type: 'message' as const, schema: LoginSigHeadSchema },
} satisfies ProtoSchema;
export const RespDataHighwayHeadSchema = {
msgBaseHead: { field: 1, type: 'message' as const, schema: DataHighwayHeadSchema },
msgSegHead: { field: 2, type: 'message' as const, schema: SegHeadSchema },
errorCode: { field: 3, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- Highway extend (NTV2RichMediaHighwayExt) ---
export const HighwayDomainSchema = {
isEnable: { field: 1, type: 'bool' as const },
ip: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const HighwayIPv4Schema = {
domain: { field: 1, type: 'message' as const, schema: HighwayDomainSchema },
port: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const HighwayNetworkSchema = {
ipv4s: { field: 1, type: 'repeated_message' as const, schema: HighwayIPv4Schema },
} satisfies ProtoSchema;
export const HighwayHashSchema = {
fileSha1: { field: 1, type: 'repeated_bytes' as const },
} satisfies ProtoSchema;
export const HighwayMsgInfoBodySchema = {
index: { field: 1, type: 'message' as const, schema: IndexNodeSchema },
picture: { field: 2, type: 'message' as const, schema: PictureInfoSchema },
fileExist: { field: 5, type: 'bool' as const },
hashSum: { field: 6, type: 'message' as const, schema: HashSumSchema },
} satisfies ProtoSchema;
export const NTV2RichMediaHighwayExtSchema = {
fileUuid: { field: 1, type: 'string' as const },
uKey: { field: 2, type: 'string' as const },
network: { field: 5, type: 'message' as const, schema: HighwayNetworkSchema },
msgInfoBody: { field: 6, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema },
blockSize: { field: 10, type: 'uint32' as const },
hash: { field: 11, type: 'message' as const, schema: HighwayHashSchema },
} satisfies ProtoSchema;
// --- File upload extend (group/private file highway) ---
export const FileUploadUrlSchema = {
unknown: { field: 1, type: 'int32' as const },
host: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const FileUploadHostSchema = {
url: { field: 1, type: 'message' as const, schema: FileUploadUrlSchema },
port: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const FileUploadHostConfigSchema = {
hosts: { field: 200, type: 'repeated_message' as const, schema: FileUploadHostSchema },
} satisfies ProtoSchema;
export const FileUploadNameInfoSchema = {
fileName: { field: 100, type: 'string' as const },
} satisfies ProtoSchema;
export const FileUploadClientInfoSchema = {
clientType: { field: 100, type: 'int32' as const },
appId: { field: 200, type: 'string' as const },
terminalType: { field: 300, type: 'int32' as const },
clientVer: { field: 400, type: 'string' as const },
unknown: { field: 600, type: 'int32' as const },
} satisfies ProtoSchema;
export const FileUploadFileEntrySchema = {
fileSize: { field: 100, type: 'uint64' as const },
md5: { field: 200, type: 'bytes' as const },
checkKey: { field: 300, type: 'bytes' as const },
md5S2: { field: 400, type: 'bytes' as const },
fileId: { field: 600, type: 'string' as const },
uploadKey: { field: 700, type: 'bytes' as const },
} satisfies ProtoSchema;
export const FileUploadBusiInfoSchema = {
busId: { field: 1, type: 'int32' as const },
senderUin: { field: 100, type: 'uint64' as const },
receiverUin: { field: 200, type: 'uint64' as const },
groupCode: { field: 400, type: 'uint64' as const },
} satisfies ProtoSchema;
export const FileUploadEntrySchema = {
busiBuff: { field: 100, type: 'message' as const, schema: FileUploadBusiInfoSchema },
fileEntry: { field: 200, type: 'message' as const, schema: FileUploadFileEntrySchema },
clientInfo: { field: 300, type: 'message' as const, schema: FileUploadClientInfoSchema },
fileNameInfo: { field: 400, type: 'message' as const, schema: FileUploadNameInfoSchema },
host: { field: 500, type: 'message' as const, schema: FileUploadHostConfigSchema },
} satisfies ProtoSchema;
export const FileUploadExtSchema = {
unknown1: { field: 1, type: 'int32' as const },
unknown2: { field: 2, type: 'int32' as const },
unknown3: { field: 3, type: 'int32' as const },
entry: { field: 100, type: 'message' as const, schema: FileUploadEntrySchema },
unknown200: { field: 200, type: 'int32' as const },
} satisfies ProtoSchema;
// --- Encodable MsgInfo (for embedding in message element) ---
export const EncodableMediaExtBizInfoSchema = {
pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema },
video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema },
ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema },
busiType: { field: 10, type: 'uint32' as const },
} satisfies ProtoSchema;
export const EncodableMediaMsgInfoSchema = {
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema },
extBizInfo: { field: 2, type: 'message' as const, schema: EncodableMediaExtBizInfoSchema },
} satisfies ProtoSchema;
// --- HttpConn.0x6ff_501 (highway session) ---
export const HttpConnSchema = {
field1: { field: 1, type: 'int32' as const },
field2: { field: 2, type: 'int32' as const },
field3: { field: 3, type: 'int32' as const },
field4: { field: 4, type: 'int32' as const },
field6: { field: 6, type: 'int32' as const },
serviceTypes: { field: 7, type: 'repeated_uint32' as const },
field9: { field: 9, type: 'int32' as const },
field10: { field: 10, type: 'int32' as const },
field11: { field: 11, type: 'int32' as const },
ver: { field: 15, type: 'string' as const },
} satisfies ProtoSchema;
export const HttpConn0x6FF501RequestSchema = {
httpConn: { field: 0x501, type: 'message' as const, schema: HttpConnSchema },
} satisfies ProtoSchema;
export const ServerAddrSchema = {
type: { field: 1, type: 'uint32' as const },
ip: { field: 2, type: 'uint32' as const }, // fixed32 as uint32
port: { field: 3, type: 'uint32' as const },
area: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const ServerInfoSchema = {
serviceType: { field: 1, type: 'uint32' as const },
serverAddrs: { field: 2, type: 'repeated_message' as const, schema: ServerAddrSchema },
} satisfies ProtoSchema;
export const HttpConnResponseSchema = {
sigSession: { field: 1, type: 'bytes' as const },
sessionKey: { field: 2, type: 'bytes' as const },
serverInfos: { field: 3, type: 'repeated_message' as const, schema: ServerInfoSchema },
} satisfies ProtoSchema;
export const HttpConn0x6FF501ResponseSchema = {
httpConn: { field: 0x501, type: 'message' as const, schema: HttpConnResponseSchema },
} satisfies ProtoSchema;
// --- NTV2 Upload Request (for OIDB 0x11C4/0x11C5) ---
export const NTV2FileTypeSchema = {
type: { field: 1, type: 'uint32' as const },
picFormat: { field: 2, type: 'uint32' as const },
videoFormat: { field: 3, type: 'uint32' as const },
voiceFormat: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2FileInfoSchema = {
fileSize: { field: 1, type: 'uint32' as const },
fileHash: { field: 2, type: 'string' as const },
fileSha1: { field: 3, type: 'string' as const },
fileName: { field: 4, type: 'string' as const },
type: { field: 5, type: 'message' as const, schema: NTV2FileTypeSchema },
width: { field: 6, type: 'uint32' as const },
height: { field: 7, type: 'uint32' as const },
time: { field: 8, type: 'uint32' as const },
original: { field: 9, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2UploadInfoSchema = {
fileInfo: { field: 1, type: 'message' as const, schema: NTV2FileInfoSchema },
subFileType: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
// The NTV2 upload request + response carry the same ExtBizInfo shape that
// element-side incoming-message decoding uses. Pulling those schemas in
// directly (instead of redefining stub copies) keeps the round-trip
// `server response → finalizeMediaMsgInfo → commonElem.pbElem` from
// silently dropping fields the QQ NT server later validates against —
// the video `fromScene`/`toScene` drop was already responsible for c2c
// `result=79` rejections on `send_private_msg [{type:'video'}]`.
export const NTV2ExtBizInfoSchema = {
pic: { field: 1, type: 'message' as const, schema: PicExtBizInfoSchema },
video: { field: 2, type: 'message' as const, schema: VideoExtBizInfoSchema },
ptt: { field: 3, type: 'message' as const, schema: PttExtBizInfoSchema },
busiType: { field: 10, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2UploadReqSchema = {
uploadInfo: { field: 1, type: 'repeated_message' as const, schema: NTV2UploadInfoSchema },
tryFastUploadCompleted: { field: 2, type: 'bool' as const },
srvSendMsg: { field: 3, type: 'bool' as const },
clientRandomId: { field: 4, type: 'uint64' as const },
compatQmsgSceneType: { field: 5, type: 'uint32' as const },
extBizInfo: { field: 6, type: 'message' as const, schema: NTV2ExtBizInfoSchema },
clientSeq: { field: 7, type: 'uint32' as const },
noNeedCompatMsg: { field: 8, type: 'bool' as const },
} satisfies ProtoSchema;
export const NTV2C2CUserInfoSchema = {
accountType: { field: 1, type: 'uint32' as const },
targetUid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const NTV2GroupInfoSchema = {
groupUin: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2UploadSceneInfoSchema = {
requestType: { field: 101, type: 'uint32' as const },
businessType: { field: 102, type: 'uint32' as const },
sceneType: { field: 200, type: 'uint32' as const },
c2c: { field: 201, type: 'message' as const, schema: NTV2C2CUserInfoSchema },
group: { field: 202, type: 'message' as const, schema: NTV2GroupInfoSchema },
} satisfies ProtoSchema;
export const NTV2CommonHeadSchema = {
requestId: { field: 1, type: 'uint32' as const },
command: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2ClientMetaSchema = {
agentType: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2UploadReqHeadSchema = {
common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema },
scene: { field: 2, type: 'message' as const, schema: NTV2UploadSceneInfoSchema },
client: { field: 3, type: 'message' as const, schema: NTV2ClientMetaSchema },
} satisfies ProtoSchema;
export const NTV2UploadRichMediaReqSchema = {
reqHead: { field: 1, type: 'message' as const, schema: NTV2UploadReqHeadSchema },
upload: { field: 2, type: 'message' as const, schema: NTV2UploadReqSchema },
} satisfies ProtoSchema;
// --- NTV2 Upload Response ---
export const NTV2IPv4Schema = {
outIp: { field: 1, type: 'uint32' as const },
outPort: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NTV2SubFileInfoRespSchema = {
subType: { field: 1, type: 'uint32' as const },
uKey: { field: 2, type: 'string' as const },
uKeyTtl: { field: 3, type: 'uint32' as const },
ipv4s: { field: 4, type: 'repeated_message' as const, schema: NTV2IPv4Schema },
} satisfies ProtoSchema;
export const NTV2UploadRespMsgInfoSchema = {
msgInfoBody: { field: 1, type: 'repeated_message' as const, schema: HighwayMsgInfoBodySchema },
extBizInfo: { field: 2, type: 'message' as const, schema: NTV2ExtBizInfoSchema },
} satisfies ProtoSchema;
export const NTV2UploadRespBodySchema = {
uKey: { field: 1, type: 'string' as const },
uKeyTtl: { field: 2, type: 'uint32' as const },
ipv4s: { field: 3, type: 'repeated_message' as const, schema: NTV2IPv4Schema },
msgSeq: { field: 5, type: 'uint64' as const },
msgInfo: { field: 6, type: 'message' as const, schema: NTV2UploadRespMsgInfoSchema },
subFileInfos: { field: 10, type: 'repeated_message' as const, schema: NTV2SubFileInfoRespSchema },
} satisfies ProtoSchema;
export const NTV2UploadRespHeadSchema = {
common: { field: 1, type: 'message' as const, schema: NTV2CommonHeadSchema },
retCode: { field: 2, type: 'uint32' as const },
message: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const NTV2UploadRichMediaRespSchema = {
respHead: { field: 1, type: 'message' as const, schema: NTV2UploadRespHeadSchema },
upload: { field: 2, type: 'message' as const, schema: NTV2UploadRespBodySchema },
} satisfies ProtoSchema;

View File

@@ -1,68 +0,0 @@
import type { ProtoSchema } from '../../protobuf/decode';
import { PushMsgBodySchema } from './message';
export const LongMsgUidSchema = {
uid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const LongMsgSettingsSchema = {
field1: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
field4: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const SendLongMsgInfoSchema = {
type: { field: 1, type: 'uint32' as const },
uid: { field: 2, type: 'message' as const, schema: LongMsgUidSchema },
groupUin: { field: 3, type: 'uint32' as const },
payload: { field: 4, type: 'bytes' as const },
} satisfies ProtoSchema;
export const SendLongMsgReqSchema = {
info: { field: 2, type: 'message' as const, schema: SendLongMsgInfoSchema },
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
} satisfies ProtoSchema;
export const SendLongMsgRespResultSchema = {
resId: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const SendLongMsgRespSchema = {
result: { field: 2, type: 'message' as const, schema: SendLongMsgRespResultSchema },
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
} satisfies ProtoSchema;
export const RecvLongMsgInfoSchema = {
uid: { field: 1, type: 'message' as const, schema: LongMsgUidSchema },
resId: { field: 2, type: 'string' as const },
acquire: { field: 3, type: 'bool' as const },
} satisfies ProtoSchema;
export const RecvLongMsgReqSchema = {
info: { field: 1, type: 'message' as const, schema: RecvLongMsgInfoSchema },
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
} satisfies ProtoSchema;
export const RecvLongMsgRespResultSchema = {
resId: { field: 3, type: 'string' as const },
payload: { field: 4, type: 'bytes' as const },
} satisfies ProtoSchema;
export const RecvLongMsgRespSchema = {
result: { field: 1, type: 'message' as const, schema: RecvLongMsgRespResultSchema },
settings: { field: 15, type: 'message' as const, schema: LongMsgSettingsSchema },
} satisfies ProtoSchema;
export const LongMsgContentSchema = {
msgBody: { field: 1, type: 'repeated_message' as const, schema: PushMsgBodySchema },
} satisfies ProtoSchema;
export const LongMsgActionSchema = {
actionCommand: { field: 1, type: 'string' as const },
actionData: { field: 2, type: 'message' as const, schema: LongMsgContentSchema },
} satisfies ProtoSchema;
export const LongMsgResultSchema = {
action: { field: 2, type: 'repeated_message' as const, schema: LongMsgActionSchema },
} satisfies ProtoSchema;

View File

@@ -1,113 +0,0 @@
// Proto schemas for message envelopes (PushMsg).
// Port of src/bridge/include/bridge/proto/message.h
import type { ProtoSchema } from '../../protobuf/decode';
import { ElemSchema } from './element';
// --- ResponseHead.Grp ---
export const ResponseGrpSchema = {
groupUin: { field: 1, type: 'uint32' as const },
memberName: { field: 2, type: 'string' as const },
groupName: { field: 4, type: 'string' as const },
} satisfies ProtoSchema;
export const ResponseForwardSchema = {
friendName: { field: 6, type: 'string' as const },
} satisfies ProtoSchema;
// --- ResponseHead ---
export const ResponseHeadSchema = {
fromUin: { field: 1, type: 'uint32' as const },
fromUid: { field: 2, type: 'string' as const },
type: { field: 3, type: 'uint32' as const },
sigMap: { field: 4, type: 'uint32' as const },
toUin: { field: 5, type: 'uint32' as const },
toUid: { field: 6, type: 'string' as const },
forward: { field: 7, type: 'message' as const, schema: ResponseForwardSchema },
grp: { field: 8, type: 'message' as const, schema: ResponseGrpSchema },
} satisfies ProtoSchema;
// --- ContentHead ---
export const ContentHeadSchema = {
msgType: { field: 1, type: 'uint32' as const },
subType: { field: 2, type: 'uint32' as const },
divSeq: { field: 3, type: 'uint32' as const },
msgId: { field: 4, type: 'uint32' as const },
sequence: { field: 5, type: 'uint32' as const },
timestamp: { field: 6, type: 'uint32' as const },
field7: { field: 7, type: 'uint64' as const },
newId: { field: 12, type: 'uint64' as const },
} satisfies ProtoSchema;
// --- Ptt (voice) ---
export const PttSchema = {
fileType: { field: 1, type: 'uint32' as const },
fileId: { field: 2, type: 'uint64' as const },
fileUuid: { field: 3, type: 'bytes' as const },
fileMd5: { field: 4, type: 'bytes' as const },
fileName: { field: 5, type: 'string' as const },
fileSize: { field: 6, type: 'uint32' as const },
groupFileKey: { field: 10, type: 'string' as const },
fileKey: { field: 14, type: 'bytes' as const },
time: { field: 19, type: 'uint32' as const },
format: { field: 29, type: 'uint32' as const },
} satisfies ProtoSchema;
// --- NotOnlineFile (C2C file) ---
export const NotOnlineFileSchema = {
fileType: { field: 1, type: 'uint32' as const },
fileUuid: { field: 3, type: 'string' as const },
fileMd5: { field: 4, type: 'bytes' as const },
fileName: { field: 5, type: 'string' as const },
fileSize: { field: 6, type: 'uint64' as const },
fileHash: { field: 57, type: 'string' as const },
} satisfies ProtoSchema;
// --- RichText ---
export const RichTextSchema = {
elems: { field: 2, type: 'repeated_message' as const, schema: ElemSchema },
notOnlineFile: { field: 3, type: 'message' as const, schema: NotOnlineFileSchema },
ptt: { field: 4, type: 'message' as const, schema: PttSchema },
} satisfies ProtoSchema;
// --- MessageBody ---
export const MessageBodySchema = {
richText: { field: 1, type: 'message' as const, schema: RichTextSchema },
msgContent: { field: 2, type: 'bytes' as const },
} satisfies ProtoSchema;
// --- FileExtra (for C2C file in msg_content) ---
export const FileExtraInfoSchema = {
fileSize: { field: 1, type: 'uint64' as const },
fileName: { field: 2, type: 'string' as const },
fileMd5: { field: 3, type: 'bytes' as const },
fileUuid: { field: 4, type: 'string' as const },
fileHash: { field: 5, type: 'string' as const },
} satisfies ProtoSchema;
export const FileExtraSchema = {
file: { field: 1, type: 'message' as const, schema: FileExtraInfoSchema },
} satisfies ProtoSchema;
// --- PushMsgBody ---
export const PushMsgBodySchema = {
responseHead: { field: 1, type: 'message' as const, schema: ResponseHeadSchema },
contentHead: { field: 2, type: 'message' as const, schema: ContentHeadSchema },
body: { field: 3, type: 'message' as const, schema: MessageBodySchema },
} satisfies ProtoSchema;
// --- PushMsg (top-level) ---
export const PushMsgSchema = {
message: { field: 1, type: 'message' as const, schema: PushMsgBodySchema },
status: { field: 3, type: 'int32' as const },
} satisfies ProtoSchema;

View File

@@ -1,207 +0,0 @@
// Proto schemas for notification types.
// Port of src/bridge/include/bridge/proto/notify.h
import type { ProtoSchema } from '../../protobuf/decode';
export const OperatorField1Schema = {
uid: { field: 1, type: 'string' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'bytes' as const },
field4: { field: 4, type: 'uint32' as const },
field5: { field: 5, type: 'bytes' as const },
} satisfies ProtoSchema;
export const OperatorInfoSchema = {
operatorField: { field: 1, type: 'message' as const, schema: OperatorField1Schema },
} satisfies ProtoSchema;
export const GroupChangeSchema = {
groupUin: { field: 1, type: 'uint32' as const },
flag: { field: 2, type: 'uint32' as const },
memberUid: { field: 3, type: 'string' as const },
decreaseType: { field: 4, type: 'uint32' as const },
operatorBytes: { field: 5, type: 'bytes' as const },
increaseType: { field: 6, type: 'uint32' as const },
field7: { field: 7, type: 'bytes' as const },
} satisfies ProtoSchema;
export const GroupAdminExtraSchema = {
adminUid: { field: 1, type: 'string' as const },
isPromote: { field: 2, type: 'bool' as const },
} satisfies ProtoSchema;
export const GroupAdminBodySchema = {
extraDisable: { field: 1, type: 'message' as const, schema: GroupAdminExtraSchema },
extraEnable: { field: 2, type: 'message' as const, schema: GroupAdminExtraSchema },
} satisfies ProtoSchema;
export const GroupAdminSchema = {
groupUin: { field: 1, type: 'uint32' as const },
flag: { field: 2, type: 'uint32' as const },
isPromote: { field: 3, type: 'bool' as const },
body: { field: 4, type: 'message' as const, schema: GroupAdminBodySchema },
} satisfies ProtoSchema;
export const InvitationInnerSchema = {
groupUin: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
field4: { field: 4, type: 'uint32' as const },
targetUid: { field: 5, type: 'string' as const },
invitorUid: { field: 6, type: 'string' as const },
field7: { field: 7, type: 'uint32' as const },
field9: { field: 9, type: 'uint32' as const },
field10: { field: 10, type: 'bytes' as const },
field11: { field: 11, type: 'uint32' as const },
field12: { field: 12, type: 'string' as const },
} satisfies ProtoSchema;
export const InvitationInfoSchema = {
inner: { field: 1, type: 'message' as const, schema: InvitationInnerSchema },
} satisfies ProtoSchema;
export const GroupInvitationSchema = {
cmd: { field: 1, type: 'int32' as const },
info: { field: 2, type: 'message' as const, schema: InvitationInfoSchema },
} satisfies ProtoSchema;
export const GroupInviteSchema = {
groupUin: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
field4: { field: 4, type: 'uint32' as const },
invitorUid: { field: 5, type: 'string' as const },
hashes: { field: 6, type: 'bytes' as const },
} satisfies ProtoSchema;
export const GroupJoinSchema = {
groupUin: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
targetUid: { field: 3, type: 'string' as const },
field4: { field: 4, type: 'uint32' as const },
field6: { field: 6, type: 'uint32' as const },
field7: { field: 7, type: 'string' as const },
field8: { field: 8, type: 'uint32' as const },
field9: { field: 9, type: 'bytes' as const },
} satisfies ProtoSchema;
export const FriendRequestInfoSchema = {
targetUid: { field: 1, type: 'string' as const },
sourceUid: { field: 2, type: 'string' as const },
newSource: { field: 5, type: 'string' as const },
message: { field: 10, type: 'string' as const },
source: { field: 11, type: 'string' as const },
} satisfies ProtoSchema;
export const FriendRequestSchema = {
info: { field: 1, type: 'message' as const, schema: FriendRequestInfoSchema },
} satisfies ProtoSchema;
export const FriendRecallTipInfoSchema = {
tip: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const FriendRecallInfoSchema = {
fromUid: { field: 1, type: 'string' as const },
toUid: { field: 2, type: 'string' as const },
clientSequence: { field: 3, type: 'uint32' as const },
newId: { field: 4, type: 'uint64' as const },
time: { field: 5, type: 'uint32' as const },
random: { field: 6, type: 'uint32' as const },
pkgNum: { field: 7, type: 'uint32' as const },
pkgIndex: { field: 8, type: 'uint32' as const },
divSeq: { field: 9, type: 'uint32' as const },
tipInfo: { field: 13, type: 'message' as const, schema: FriendRecallTipInfoSchema },
} satisfies ProtoSchema;
export const FriendRecallSchema = {
info: { field: 1, type: 'message' as const, schema: FriendRecallInfoSchema },
instId: { field: 2, type: 'uint32' as const },
appId: { field: 3, type: 'uint32' as const },
longMessageFlag: { field: 4, type: 'uint32' as const },
reserved: { field: 5, type: 'bytes' as const },
} satisfies ProtoSchema;
export const GroupMuteStateSchema = {
targetUid: { field: 1, type: 'string' as const },
duration: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const GroupMuteDataSchema = {
timestamp: { field: 1, type: 'uint32' as const },
type: { field: 2, type: 'uint32' as const },
state: { field: 3, type: 'message' as const, schema: GroupMuteStateSchema },
} satisfies ProtoSchema;
export const GroupMuteSchema = {
groupUin: { field: 1, type: 'uint32' as const },
subType: { field: 2, type: 'uint32' as const },
field3: { field: 3, type: 'uint32' as const },
operatorUid: { field: 4, type: 'string' as const },
data: { field: 5, type: 'message' as const, schema: GroupMuteDataSchema },
} satisfies ProtoSchema;
export const RecallMessageSchema = {
sequence: { field: 1, type: 'uint32' as const },
time: { field: 2, type: 'uint32' as const },
random: { field: 3, type: 'uint32' as const },
type: { field: 4, type: 'uint32' as const },
flag: { field: 5, type: 'uint32' as const },
authorUid: { field: 6, type: 'string' as const },
} satisfies ProtoSchema;
export const GroupRecallTipInfoSchema = {
tip: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const GroupRecallSchema = {
operatorUid: { field: 1, type: 'string' as const },
recallMessages: { field: 3, type: 'repeated_message' as const, schema: RecallMessageSchema },
userDef: { field: 5, type: 'bytes' as const },
groupType: { field: 6, type: 'int32' as const },
opType: { field: 7, type: 'int32' as const },
tipInfo: { field: 9, type: 'message' as const, schema: GroupRecallTipInfoSchema },
} satisfies ProtoSchema;
export const TemplParamSchema = {
name: { field: 1, type: 'string' as const },
value: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const GeneralGrayTipInfoSchema = {
busiType: { field: 1, type: 'uint64' as const },
busiId: { field: 2, type: 'uint64' as const },
ctrlFlag: { field: 3, type: 'uint32' as const },
c2cType: { field: 4, type: 'uint32' as const },
serviceType: { field: 5, type: 'uint32' as const },
templId: { field: 6, type: 'uint64' as const },
msgTemplParam: { field: 7, type: 'repeated_message' as const, schema: TemplParamSchema },
content: { field: 8, type: 'string' as const },
} satisfies ProtoSchema;
export const EssenceMessageSchema = {
groupUin: { field: 1, type: 'uint32' as const },
msgSequence: { field: 2, type: 'uint32' as const },
random: { field: 3, type: 'uint32' as const },
setFlag: { field: 4, type: 'uint32' as const },
memberUin: { field: 5, type: 'uint32' as const },
operatorUin: { field: 6, type: 'uint32' as const },
timestamp: { field: 7, type: 'uint32' as const },
msgSequence2: { field: 8, type: 'uint32' as const },
operatorNickname: { field: 9, type: 'string' as const },
memberNickname: { field: 10, type: 'string' as const },
setFlag2: { field: 11, type: 'uint32' as const },
} satisfies ProtoSchema;
export const NotifyMessageBodySchema = {
type: { field: 1, type: 'uint32' as const },
groupUin: { field: 4, type: 'uint32' as const },
eventParam: { field: 5, type: 'bytes' as const },
recall: { field: 11, type: 'message' as const, schema: GroupRecallSchema },
field13: { field: 13, type: 'uint32' as const },
operatorUid: { field: 21, type: 'string' as const },
generalGrayTip: { field: 26, type: 'message' as const, schema: GeneralGrayTipInfoSchema },
essenceMessage: { field: 33, type: 'message' as const, schema: EssenceMessageSchema },
msgSequence: { field: 37, type: 'uint32' as const },
field39: { field: 39, type: 'uint32' as const },
} satisfies ProtoSchema;

File diff suppressed because it is too large Load Diff

View File

@@ -1,161 +0,0 @@
// Proto schemas for OidbSvc service types.
// Port of src/bridge/include/bridge/proto/oidb.h
import type { ProtoSchema } from '../../protobuf/decode';
// --- OidbSvcTrpcTcpBase wrapper ---
export const OidbPropertySchema = {
key: { field: 1, type: 'string' as const },
value: { field: 2, type: 'bytes' as const },
} satisfies ProtoSchema;
// Factory for OidbSvcTrpcTcpBase<T>
export function makeOidbBaseSchema(bodySchema: ProtoSchema): ProtoSchema {
return {
command: { field: 1, type: 'uint32' as const },
subCommand: { field: 2, type: 'uint32' as const },
errorCode: { field: 3, type: 'uint32' as const },
body: { field: 4, type: 'message' as const, schema: bodySchema },
errorMsg: { field: 5, type: 'string' as const },
properties: { field: 11, type: 'repeated_message' as const, schema: OidbPropertySchema },
reserved: { field: 12, type: 'int32' as const },
};
}
// --- Friend list (0xFD4_1) ---
export const OidbFriendPropertySchema = {
code: { field: 1, type: 'uint32' as const },
value: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbFriendLayer1Schema = {
properties: { field: 2, type: 'repeated_message' as const, schema: OidbFriendPropertySchema },
} satisfies ProtoSchema;
export const OidbFriendAdditionalSchema = {
type: { field: 1, type: 'uint32' as const },
layer1: { field: 2, type: 'message' as const, schema: OidbFriendLayer1Schema },
} satisfies ProtoSchema;
export const OidbFriendSchema = {
uid: { field: 1, type: 'string' as const },
customGroup:{ field: 2, type: 'uint32' as const },
uin: { field: 3, type: 'uint32' as const },
additional: { field: 10001, type: 'repeated_message' as const, schema: OidbFriendAdditionalSchema },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFD4_1ResponseUinSchema = {
uin: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFD4_1ResponseSchema = {
next: { field: 2, type: 'message' as const, schema: OidbSvcTrpcTcp0xFD4_1ResponseUinSchema },
displayFriendCount: { field: 3, type: 'uint32' as const },
timestamp: { field: 6, type: 'uint32' as const },
selfUin: { field: 7, type: 'uint32' as const },
friends: { field: 101, type: 'repeated_message' as const, schema: OidbFriendSchema },
groups: { field: 102, type: 'repeated_message' as const, schema: OidbFriendPropertySchema },
} satisfies ProtoSchema;
// --- Group list (0xFE5_2) ---
export const OidbSvcTrpcTcp0xFE5_2MemberSchema = {
uid: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE5_2GroupInfoSchema = {
groupOwner: { field: 1, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2MemberSchema },
createdTime: { field: 2, type: 'uint32' as const },
memberMax: { field: 3, type: 'uint32' as const },
memberCount: { field: 4, type: 'uint32' as const },
groupName: { field: 5, type: 'string' as const },
description: { field: 18, type: 'string' as const },
question: { field: 19, type: 'string' as const },
announcement: { field: 30, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE5_2CustomInfoSchema = {
remark: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE5_2GroupSchema = {
groupUin: { field: 3, type: 'uint32' as const },
info: { field: 4, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2GroupInfoSchema },
customInfo: { field: 5, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE5_2CustomInfoSchema },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE5_2ResponseSchema = {
groups: { field: 2, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0xFE5_2GroupSchema },
} satisfies ProtoSchema;
// --- Group member list (0xFE7_3) ---
export const OidbSvcTrpcTcp0xFE7_3UinSchema = {
uid: { field: 2, type: 'string' as const },
uin: { field: 4, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE7_3CardSchema = {
memberCard: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE7_3LevelSchema = {
infos: { field: 1, type: 'repeated_uint32' as const },
level: { field: 2, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE7_3MemberSchema = {
uin: { field: 1, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3UinSchema },
memberName: { field: 10, type: 'string' as const },
specialTitle: { field: 17, type: 'string' as const },
memberCard: { field: 11, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3CardSchema },
level: { field: 12, type: 'message' as const, schema: OidbSvcTrpcTcp0xFE7_3LevelSchema },
joinTimestamp: { field: 100, type: 'uint32' as const },
lastMsgTimestamp: { field: 101, type: 'uint32' as const },
shutUpTimestamp: { field: 102, type: 'uint32' as const },
permission: { field: 107, type: 'uint32' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0xFE7_3ResponseSchema = {
groupUin: { field: 1, type: 'uint32' as const },
members: { field: 2, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0xFE7_3MemberSchema },
field3: { field: 3, type: 'uint32' as const },
memberChangeSeq: { field: 5, type: 'uint32' as const },
memberCardChangeSeq:{ field: 6, type: 'uint32' as const },
token: { field: 15, type: 'string' as const },
} satisfies ProtoSchema;
// --- Group request (0x10C0) ---
export const OidbSvcTrpcTcp0x10C0ResponseUserSchema = {
uid: { field: 1, type: 'string' as const },
name: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0x10C0ResponseGroupSchema = {
groupUin: { field: 1, type: 'uint32' as const },
groupName: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0x10C0ResponseRequestSchema = {
sequence: { field: 1, type: 'uint64' as const },
eventType: { field: 2, type: 'uint32' as const },
state: { field: 3, type: 'uint32' as const },
group: { field: 4, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseGroupSchema },
target: { field: 5, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema },
invitor: { field: 6, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema },
operatorUser: { field: 7, type: 'message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseUserSchema },
field9: { field: 9, type: 'string' as const },
comment: { field: 10, type: 'string' as const },
} satisfies ProtoSchema;
export const OidbSvcTrpcTcp0x10C0ResponseSchema = {
requests: { field: 1, type: 'repeated_message' as const, schema: OidbSvcTrpcTcp0x10C0ResponseRequestSchema },
field2: { field: 2, type: 'uint64' as const },
newLatestSeq: { field: 3, type: 'uint64' as const },
field4: { field: 4, type: 'uint32' as const },
field5: { field: 5, type: 'uint64' as const },
field6: { field: 6, type: 'uint32' as const },
} satisfies ProtoSchema;

View File

@@ -1,155 +0,0 @@
// Web-cookie / credential primitives — every other web-action in this
// directory builds on these. Each Bridge-level web call ends up doing
// roughly: forceFetchClientKey -> ptlogin2 jump -> cookie dict ->
// thread the cookies into a qun.qq.com REST endpoint.
import type { Bridge } from '../bridge';
import { runOidb } from '../bridge-oidb';
import {
OidbClientKeyRespSchema,
OidbClientKeyReqSchema,
OidbGetPskeyReqSchema,
OidbGetPskeyRespSchema,
} from '../proto/oidb-action';
import { RequestUtil } from '../web/request-util';
export async function forceFetchClientKey(bridge: Bridge) {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x102a_1',
oidbCmd: 0x102A, subCmd: 1,
request: { schema: OidbClientKeyReqSchema, value: {} },
response: { schema: OidbClientKeyRespSchema },
});
const clientKey = resp?.clientKey || '';
// keyIndex falls back to "19" — origin unknown but the value is what
// every NapCat-derived implementation uses when the server omits it.
const keyIndex = String(resp?.keyIndex || '19');
return {
clientKey,
keyIndex,
expireTime: String(resp?.expireTime || '1800'),
};
}
export async function getPSkey(bridge: Bridge, domainList: string[]) {
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x102a_0',
oidbCmd: 0x102A, subCmd: 0,
request: { schema: OidbGetPskeyReqSchema, value: { domainList } },
response: { schema: OidbGetPskeyRespSchema },
});
const domainPskeyMap = new Map<string, string>();
if (resp?.pskeyItems && Array.isArray(resp.pskeyItems)) {
for (const item of resp.pskeyItems) {
if (item.domain && item.pskey) {
domainPskeyMap.set(item.domain, item.pskey);
}
}
}
return { domainPskeyMap };
}
export async function getCookies(bridge: Bridge, domain: string) {
const ClientKeyData = await forceFetchClientKey(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;
}
export async function getSKey(bridge: Bridge): Promise<string> {
const ClientKeyData = await forceFetchClientKey(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.
*/
export 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;
}
/** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */
export async function getCookiesStr(bridge: Bridge, domain: string): Promise<string> {
const cookieObject = await getCookies(bridge, domain);
return Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
}
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
export async function getCsrfToken(bridge: Bridge): Promise<number> {
const skey = await getSKey(bridge);
if (!skey) {
throw new Error('SKey is Empty');
}
return getBknFromSKey(skey);
}
/** Returns the OneBot `get_credentials` payload (cookie string + bkn). */
export async function getCredentials(bridge: Bridge, domain: string) {
const cookieObject = await getCookies(bridge, 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: token,
csrf_token: token,
};
}

View File

@@ -1,27 +0,0 @@
// `get_essence_msg_list` — group essence (highlighted) messages.
// Two flavors: paginated (`getGroupEssence`) and the convenience
// fetch-everything (`getGroupEssenceAll`).
import type { Bridge } from '../bridge';
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from '../web/group-essence';
import { getCookies } from './cookies';
/** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */
export async function getGroupEssence(bridge: Bridge, groupId: number, pageStart: number = 0, pageLimit: number = 50) {
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. */
export async function getGroupEssenceAll(bridge: Bridge, groupId: number) {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const essenceDataAll = await getGroupEssenceMsgAll(cookieObject, groupCode);
return essenceDataAll;
}

View File

@@ -1,45 +0,0 @@
// `get_group_honor_info` — queries the per-group honor leaderboards
// (talkative / performer / legend / emotion / strong_newbie).
// Each honor type is a separate web call; ALL fetches all four
// non-newbie lists and folds them into one response.
import type { Bridge } from '../bridge';
import { getHonorListWebAPI, WebHonorType } from '../web/group-honor';
import { getCookies } from './cookies';
export async function getGroupHonorInfo(bridge: Bridge, groupId: number, type: WebHonorType | string) {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const honorInfo: any = {
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;
}

View File

@@ -1,118 +0,0 @@
// Group notice (`群公告`) web actions: send / list / delete.
// `sendGroupNotice` can attach an optional image; when present it
// stages the bytes (HTTP URL or local file) and uploads via the
// notice-image endpoint before posting the notice itself.
import type { Bridge } from '../bridge';
import {
setGroupNoticeWebAPI,
getGroupNoticeWebAPI,
uploadGroupNoticeImage,
deleteGroupNotice,
} from '../web/group-notice';
import { getCookies } from './cookies';
export async function sendGroupNotice(
bridge: Bridge,
groupId: number,
content: string,
options?: {
image?: string; // local path, http URL, or undefined (text-only)
pinned?: number;
type?: number;
confirm_required?: number;
},
) {
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;
}
export async function getGroupNotice(bridge: Bridge, groupId: number) {
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: any[] = [];
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: image,
images: image,
},
settings: feed.settings,
read_num: feed.read_num,
});
}
}
return retNotices;
}
export async function deleteGroupNoticeByFid(bridge: Bridge, groupId: number, fid: string): Promise<boolean> {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await deleteGroupNotice(cookieObject, groupCode, fid);
}

View File

@@ -1,27 +0,0 @@
// Barrel for the web-action themed split. `bridge.ts` imports
// everything from this directory as if it were a single file; the
// per-theme files keep the implementation discoverable.
export {
forceFetchClientKey,
getPSkey,
getCookies,
getSKey,
getBknFromSKey,
getCookiesStr,
getCsrfToken,
getCredentials,
} from './cookies';
export { getGroupHonorInfo } from './group-honor';
export {
getGroupEssence,
getGroupEssenceAll,
} from './group-essence';
export {
sendGroupNotice,
getGroupNotice,
deleteGroupNoticeByFid,
} from './group-notice';

View File

@@ -1,66 +0,0 @@
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
// 定义接口返回类型
export interface GroupEssenceMsgRet {
retcode: number;
data: {
is_end: boolean;
msg_list: any[]; // 具体结构视需要补充
[key: string]: any;
};
[key: string]: any;
}
/**
* 分页获取群精华消息
*/
export async function getGroupEssenceMsg(
cookieObject: Record<string, string>,
groupCode: string,
pageStart: number = 0,
pageLimit: number = 50
): Promise<GroupEssenceMsgRet | undefined> {
const bkn = getBknFromCookie(cookieObject);
const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({
bkn: bkn,
page_start: pageStart.toString(),
page_limit: pageLimit.toString(),
group_code: groupCode,
}).toString()}`;
try {
const ret = await RequestUtil.HttpGetJson<GroupEssenceMsgRet>(
url,
'GET',
'',
{ Cookie: cookieToString(cookieObject) }
);
return ret.retcode === 0 ? ret : undefined;
} catch (e) {
return undefined;
}
}
/**
* 获取所有群精华消息 (最多循环 20 页)
*/
export async function getGroupEssenceMsgAll(
cookieObject: Record<string, string>,
groupCode: string
): Promise<GroupEssenceMsgRet[]> {
const ret: GroupEssenceMsgRet[] = [];
for (let i = 0; i < 20; i++) {
const data = await getGroupEssenceMsg(cookieObject, groupCode, i, 50);
if (!data) break;
ret.push(data);
if (data.data?.is_end) break;
}
return ret;
}

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