Commit Graph
1068 Commits
Author SHA1 Message Date
DrSmoothl d2097f77c8 test(sdk): remove obsolete actions-sync guard
c49ae1c removed the SDK's hardcoded action-name list (src/actions.ts / SNOWLUMA_ACTIONS) and updated exports, but left the test that guarded it. The test imports SNOWLUMA_ACTIONS from ../src -- now undefined ("not iterable") -- and its registerAction('...') enumeration of onebot is itself stale after the declarative action-kit migration. Nothing else references SNOWLUMA_ACTIONS; the list it kept in sync no longer exists, so the guard is dead. Removing it makes the sdk suite green (16 tests).
2026-06-03 22:17:58 +08:00
DrSmoothl 4fcaba2f3e chore(release): v1.9.5 2026-06-03 21:55:37 +08:00
DrSmoothl 4427ecd569 docs(mcp): document execution mode (modes, env, read/write safety)
Covers the docs vs execution split, the four SNOWLUMA_MCP_* env vars, the query_action / invoke_action tools, read/write-mode example client configs, and the per-action safety model (default-write classification, the enforced mode gate, unknown-action rejection, envelope passthrough, and the readOnly/destructive annotations).
2026-06-03 21:55:05 +08:00
DrSmoothl 6d92a28e2b feat(mcp): execution mode — query/invoke OneBot actions with a read/write safety gate
@snowluma/mcp gains execution alongside the read-only catalog: when SNOWLUMA_MCP_ENDPOINT is set it exposes query_action (read-only actions, readOnlyHint) and, in write mode, invoke_action (any known action, destructiveHint), proxied to a running OneBot instance over HTTP. Without an endpoint it degrades to docs-only. SNOWLUMA_MCP_MODE (docs|read|write) gates tool visibility AND is re-checked in execute(), so an unlisted tool cannot be called; unknown/legacy actions are non-invokable.

Read vs write is classified precisely at the source: defineAction/preset gain readOnly (default false = write, the safe default), flowed through describe() into the generated catalog snapshot. 58 actions are marked read-only by what their run() actually does -- name-traps like get_ai_record (publishes to the group), request_decrypt_key (returns a DB key), and download_file (arbitrary URL + disk write) stay writes.

The HTTP call is a ~20-line fetch bridge rather than @snowluma/sdk: the SDK's published dist is bundler-only ESM (extensionless imports) that native node cannot load, and the bin stays a plain tsc build.

onebot 332 tests pass (readOnly is metadata-only, no behavior change); mcp gains 21 tests for mode gating / read-write routing / envelope passthrough / error mapping. Full workspace typecheck clean; native node smoke verified.
2026-06-03 21:53:02 +08:00
DrSmoothl 18f7d847ac refactor(onebot): lift the network adapter reload state machine into the base class
The four NetworkAdapters each carried a byte-identical reload() state machine (sigChanged/wasEnabled -> Reopened/Closed/Opened/Normal). Lift it into IOneBotNetworkAdapter as a template method; per-adapter variation is now expressed via three hooks: bindingSignature(), willEnable() (default enabled!==false; clients add && !!url), and onConfigReplaced() (post-swap side effects).

Also delete four redundant 'override get isActive()' (identical to the base getter), lift the duplicated uin-logger setup into the base ctor, and drop http-post's now-redundant signature_ cache.

NetworkReloadType is a test-observability seam -- the sole production caller (instance.applyConfigDiff) discards it -- so a new base-level test exercises all transitions directly. Behaviour-preserving: +94/-157 in src, full workspace typecheck clean, 332 onebot tests pass.
2026-06-03 20:53:36 +08:00
游手好闲的言柒 d3092a1806 fix(onebot): support inline file url/path in send_group/private_msg (#80)
file 段现接受 file/url/path(无需先 upload_group_file/upload_private_file);群走 groupFile.upload()、私聊走 uploadPrivate()(内部已 publish/sendC2c),file_id 老路径不变。含 parser 与群/私聊文件发送测试。
2026-06-03 20:00:58 +08:00
DrSmoothl 69c8960ea9 feat(mcp): @snowluma/mcp — read-only MCP server for the OneBot action catalog
A new published package that exposes every OneBot action's docs + a ready-to-use
JSON Schema to LLM clients over stdio. Tools: list_actions / get_action /
search_actions / list_categories, plus the whole catalog as a resource.

The catalog is a build-time snapshot generated from @snowluma/onebot's live
action specs (collectActionDocs()) — so it auto-tracks action add/remove and the
published package carries zero runtime dependency on the private onebot package.

action-kit enrichment (the data source):
- Field.toJsonSchema() per coercer (uint→integer/minimum:1, messageId→integer/
  not-const-0, int→min/max, string→minLength/maxLength, array→items, enum→enum).
- describe() composes a per-action inputSchema; ActionDoc gains inputSchema +
  category. action-docs.ts tags each doc with its domain category.

Wiring: onebot exports ./action-kit + ./action-docs; root build:all includes mcp;
mcp-npm-publish.yml mirrors the sdk/ui publish workflows (triggers on changes
under packages/mcp/** or packages/onebot/**, since the catalog derives from it).

onebot typecheck + 318 tests green; mcp typecheck/build/smoke green; the 142
registered OneBot action names are unchanged.
2026-06-02 22:45:30 +08:00
DrSmoothl fc21d87a9b feat(onebot): fetch_ptt_text via async 0x210/61 result push (#79)
Live testing showed the voice-to-text text is delivered by an async push
(Event 0x210 subType 61), not the request response — so the previous
poll-by-resend never got it. Captured a real push and decoded its protobuf:
outer { f1, f2:item }; the item echoes the request msgId at field 1 (the
correlation key) and the recognised text at field 8.

- proto-defs: PttTransPush / PttTransPushItem (live-verified).
- protocol: Event0x210SubType.PttTransResult = 61 + decoder → internal
  `ptt_trans_result` event { msgId, text } (replaces the temp hex dump).
- core: translatePttToText now sends ONE trigger and returns the inline text
  only if present (already-transcribed); empty = pending.
- onebot: ptt-trans-waiter (keyed by selfUin:msgId), event-pipeline subscribes
  `ptt_trans_result` to resolve it; fetch_ptt_text registers the waiter,
  fires the trigger, and awaits the push (20s timeout).

Decoded one real push as text "12311123。" end to end.
2026-06-02 22:01:07 +08:00
DrSmoothl e036e70acc chore(protocol): temp-dump 0x210 subType-61 ptt-trans push body (#79)
Live testing showed the voice-to-text text is delivered via an async push
Event 0x210 subType 61 (0x3D), not the sync pttTrans.TransC2CPttReq response
(which is a fixed ~137B ack). That push has no static sys_msg_0x210_0x3d
handler — its protobuf is registered dynamically by the ptt-trans subsystem,
so RE through the std::function callback chain is impractical.

Dump the raw subType-61 body (fromUin + len + hex) once so the wire format
can be decoded from ground truth, then implement the real decoder +
request/await correlation. Temporary — to be replaced by the actual decoder.
2026-06-02 21:28:44 +08:00
DrSmoothl 92cfaf24b8 feat(log): trace the inbound receive chain (symmetric to outbound)
Sending got full-chain trace via the api-handler chokepoint; receiving had
none. Wrap convertAndDispatch — the single path every inbound message/notice
takes (decode → convert → dispatch) — as the receive-side mirror:

- When trace is live, run the chain inside a request id so the whole receive
  (incl. any rkey-fetch packets the conversion triggers) is correlated under
  one [req#N]; otherwise skip the wrap entirely (zero overhead).
- trace the raw inbound event on entry (deep render) and the converted
  post_type + elapsed on exit (or "dropped").

Reuses the existing trace/ALS/renderParamsVerbose machinery; no new mechanism.
2026-06-02 21:15:12 +08:00
DrSmoothl 15e4e261c5 feat(log): memory-only trace level + request correlation + chokepoint tracing
Debugging from user-supplied logs was impossible: a successful action left
one terse, over-summarized debug line and nothing about what it sent QQ or
what QQ returned. Add full-chain tracing that stays off disk so it scales to
hundreds of groups.

common:
- New `trace` level (below debug). Never written to file — it lives only in
  an in-memory ring + the WebUI stream, so the high-volume full chain costs no
  disk. `emit` early-returns for trace before format/render (and before any
  lazy producer) when trace isn't active → ~free at the default level.
- Dedicated O(1) circular ring for trace (default 5000, SNOWLUMA_TRACE_BUFFER),
  separate from the normal 1000-entry buffer (also switched off array .shift);
  getRecentLogs merges both by id.
- request-context.ts: AsyncLocalStorage request id. The logger auto-stamps
  `[req#N]` on every line in a request's async chain — across packages, zero
  signature threading — and records it on the entry.
- log-summary.renderParamsVerbose: deep render of params (nested structure,
  per-string cap, total budget, token/password/secret redaction).

chokepoints (auto-cover every action without touching 100+ handlers):
- onebot api-handler: wrap each action in a request id (only when trace is
  live); trace the full params on entry and status+elapsed on exit; the terse
  debug breadcrumb still persists to file, failures still warn.
- core bridge.sendRawPacket: trace on success (cmd, sizes, elapsed); warn on
  errorCode!=0 / no response (cmd, code, message) so disk keeps real problems.
- protocol highway: fold the bare console.log lines into the logger (trace).

webui: trace as the lowest filterable level; render the `[req#N]` tag and let
search match it. Server needs no change — LOG_LEVELS, getRecentLogs and the
SSE stream carry it through.
2026-06-02 21:01:19 +08:00
DrSmoothl 7336352cd3 feat(onebot): voice-to-text action fetch_ptt_text (#79)
Adds NapCat-compatible voice-to-text. New `fetch_ptt_text` action (aliases
`get_ptt_text` / `get_record_text`) takes a message_id, resolves the cached
`record` fingerprint (uuid + md5 + duration/size/format), drives QQ's native
`pttTrans.TransC2CPttReq` / `pttTrans.TransGroupPttReq`, and returns { text }.

The response carries the text inline once transcription is done; an empty
text means the server is still transcribing (there is no dedicated push
command — confirmed via RE), so the bridge re-sends with a short backoff
until the text lands, mirroring NapCat's fire-then-re-read shape.

Layers:
- proto-defs/ptt-trans: PttTransReq/Resp + per-scene items.
- core ExtrasApi.translatePttToText: encode -> sendRawPacket -> decode -> poll.
- onebot media-actions.fetchPttText + api-handler/instance-context wiring.
- onebot extended: register the action + aliases.

The commands + request/response field tags were reverse-engineered from
QQ-NT wrapper.node (im_core/msg/ptt/ptt_trans_worker.cc). The numeric tags
are solid; the length-delimited fields (uuid/md5) and the response text tag
are RE-derived and want one live capture to confirm before relying on them.
2026-06-02 20:47:06 +08:00
DrSmoothl 9b92f3825d refactor(onebot): declarative action-kit for param coercion + validation
Introduce packages/onebot/src/action-kit.ts — a zero-dependency,
type-inferring declarative layer for OneBot action params. Each action
declares its param contract (f.* coercers + optional cross-field rules)
and a `run` handler that receives typed, already-validated params.
Validation failures now return BAD_REQUEST naming the offending field
instead of falling through to ApiHandler's INTERNAL_ERROR catch.

- 141/142 actions migrated to defineAction/groupAction/groupUserAction
  across info/message/friend/group-*/request/extended; only
  .handle_quick_operation stays legacy (it needs the ApiHandler instance,
  which run() does not receive).
- f.messageId() distinguishes signed/non-zero message ids from positive
  group/user ids (f.uint()); int({min:0}).default(1800) fixes duration=0
  (unmute), which the old `|| 1800` silently swallowed.
- run(p, ctx, raw) exposes the raw params as an escape hatch for the
  irregular tail (alias-key fallbacks, arbitrary objects).
- action-docs.ts renders self-generated API docs from describe().
- ApiHandler dispatch / try-catch / response-wrapping unchanged (narrow seam).

Registered action name set is byte-identical before/after (142, verified
by runtime enumeration). Typecheck clean; onebot suite green (the
pre-existing websocket native-addon test failure is unrelated).
2026-06-02 15:21:46 +08:00
DrSmoothl a1f372bc9d chore(release): v1.9.4 2026-06-01 16:21:54 +08:00
DrSmoothl b23607d51d feat(webui): add About tab to settings with Star CTA
New "关于" mini-tab in the settings page showcasing SnowLuma: logo +
name + version badge (__APP_VERSION__) + tagline, a short blurb, and a
prominent GitHub Star call-to-action linking to SnowLuma/SnowLuma, plus
secondary links (repo / releases / issues).

Static CTA — no GitHub API fetch, so no rate-limit / loading state.
Reuses /logo.png (same asset as sidebar/login) and the existing Card +
motion + accent-color design language; responsive centered layout.
2026-06-01 16:07:49 +08:00
墨梓柒 a51bf60d9a Merge pull request #76 from tt-P607/fix/highway-multi-chunk-keepalive
fix(protocol): one TCP connection per highway chunk
2026-06-01 15:04:05 +08:00
DrSmoothl 003e8c2deb feat(onebot): built-in #sl status command (toggleable, non-plugin)
A hardcoded `#sl` status command — deliberately NOT a plugin system.
Matched at the instance dispatch choke point: a pure-text message equal
to `#sl` (exact, trimmed, case-insensitive — no startsWith) replies with
SnowLuma version / platform / uptime in the same conversation.

- Anyone can trigger; the per-UIN `statusCommand.enabled` toggle is the
  only gate (default on). Per-conversation cooldown (default 5s,
  configurable) prevents flood/风控 from repeated triggers.
- `swallow` (default false / pass-through): when set, a matched `#sl` is
  not forwarded to downstream adapters — still cached, logged, replied.
- Config on OneBotConfig.statusCommand (per-UIN): defaulted + clamped in
  config.ts, mirrored/normalized in the WebUI; edits hot-reload via the
  shared instance context.
- WebUI: a "内置命令" section in the 通用设置 tab (enable / swallow /
  cooldown). Node enable toggle extracted into a shared ui/ToggleSwitch.

Pure matcher / cooldown / uptime / text helpers live in
modules/status-command with unit tests; config defaults + clamp covered.
2026-06-01 14:58:13 +08:00
tt-P607 118bcbe83c fix(protocol): one TCP connection per highway chunk
Highway 上传超过 1 MiB 的载荷(多 chunk 场景)会失败,OneBot 侧表现
为 retcode=1200 / `connection closed before response`。

根因:`uploadHighwayHttp` 用同一个 TCP socket,靠 HTTP keep-alive 把
每个 1 MiB chunk 依次 POST 出去。但 QQ highway 的边缘节点(以及链
路上的代理/NAT)经常在第一次响应之后立刻 FIN 关闭连接,第二个 chunk
的 POST 写到一个已被对端 close 的 socket 上,`readHttpResponseBody`
立刻收到 `close` 事件并抛出 `connection closed before response`。

为什么之前看起来像网络问题:≤1 MiB 的载荷(文本、PTT、小图)只发一
次 POST,永远不会触发;但凡跨过 `HIGHWAY_BLOCK_SIZE = 1 MiB`,第二
个 chunk 路径必然失败。改 Clash MTU、关 TUN、加直连规则都没用,因
为问题不在网络层。

改动:
- `uploadHighwayHttp`:每个 chunk 都新开一个 TCP 连接,`finally` 里
  `destroy()`。建连开销相对 1 MiB chunk 的传输时间可以忽略,行为也
  和 NapCat / Lagrange 在大文件上传时的连接生命周期一致。
- `readHttpResponseBody`:报错信息带上 `received=NB, headerSeen=
  true|false`,方便后续区分 “连接刚握手就被关” 和 “响应读到一半被
  截断” 两种情况。

测试:`packages/core/tests/highway/highway-client.test.ts` 三个用例
(0.5 MiB 单 chunk / 1.5 MiB 两 chunk —— 即本次 bug 复现 / 2.5 MiB
三 chunk),断言 `net.createConnection` 被调用的次数等于
`ceil(size / HIGHWAY_BLOCK_SIZE)`,并且每个用过的 socket 在下一次
建连之前都被 destroy。

线上验证:之前每次发 1 MB 以上图片必出 retcode=1200 的账号,打补丁
后通过 OneBot HTTP 已能正常发出图片。
2026-06-01 14:35:57 +08:00
DrSmoothl 0d63bf7415 fix(onebot): sign forward-msg media + pick image rkey by appid (#74)
/get_forward_msg returned raw, rkey-less image/media URLs because
getForwardMessage converted forward nodes WITHOUT the URL resolvers the
normal receive path (to-message.ts) uses. Wire imageUrlResolver +
mediaUrlResolver into it so forwarded images/voice/video get signed
download URLs — exactly issue #74 (image url 缺少 rkey).

Also derive the image rkey scene from the appid baked into the URL
(1406 -> private, 1407 -> group) instead of the carrying message's
group/private context, falling back to isGroup only when the URL has no
recognised appid. A c2c image forwarded into a group keeps its original
c2c appid, so the old isGroup-based pick signed it with the group rkey ->
`invalid rkey` on download. Mirrors NapCat's getImageUrlFromParsedUrl;
Lagrange/NapCat both reuse one unified converter so this never drifts.

Fix the self-contradictory `c2c images` rkey test (its fixture used the
group appid 1407) and add cross-tests asserting appid outranks isGroup
both ways, plus the no-appid fallback.
2026-05-31 23:50:08 +08:00
DrSmoothl f9252fb26d fix(bridge): type Ptlogin probe + de-magic process threshold (PR #73 follow-up)
PR #73's login-state probe shipped with issues:
- `fetchPtlogin` returned `Promise<any[]>`, tripping the repo's
  `@typescript-eslint/no-explicit-any` (error) and breaking `pnpm lint`.
  Modelled the read fields as a `PtloginUin` interface and cast the parsed
  JSONP to it.
- `tryPtloginMethod` had a dead `if` whose two branches both returned
  'fallback'; collapsed to a single return with a comment.
- The `< 6` QQ-process-count heuristic was a bare magic number (one copy
  annotated only with "13579 5个端口全部用光"). Extracted to
  `LOGGED_OUT_PROCESS_COUNT_MAX` with an explanation and reused in all three
  sites (incl. the error fallback).

Behaviour-preserving: the probing logic (Ptlogin parse, deep-link fallback,
PID port discovery) is unchanged — only typing and the magic constant.
2026-05-31 22:33:22 +08:00
H3CoF6 b3749560c8 New implement for QQ status detection 2026-05-31 04:51:54 +08:00
DrSmoothl c3803e4ba8 feat(proto): implement deflated payload for JSON and XML elements in message builder 2026-05-30 22:52:15 +08:00
DrSmoothl ad081e2149 chore(release): v1.9.3 2026-05-30 20:53:45 +08:00
DrSmoothl 0e4b881f76 feat(webui): add live connection status for OneBot adapters in dashboard 2026-05-30 18:02:01 +08:00
DrSmoothl 90f26ca4f4 fix(proto): emit state=0 on whole-ban unmute via new pb_optional marker
set_group_whole_ban false (unmute) failed with `OIDB error 1007` while
enabling worked (issue #70). OIDB (0x89A, 0) is shared by several commands
(SetSearch / SetAddOption / mute-all) disambiguated by body shape. Unmute
sends muteState.state=0, but proton omits zero scalars (proto3), leaving an
empty `muteState` the server can't classify. Enable sends 0xFFFFFFFF, which
is non-zero and survives — hence the asymmetry.

Add a `pb_optional<N, T>` marker (proto3 explicit presence): a scalar so
marked serialises even at its zero/default value. It is opt-in per field via
a NEW `explicitPresence` flag set ONLY by this marker — never reused from the
TS-`?`-derived `isOptional` (true for nearly every field). The encoder routes
explicit-presence scalars to a dedicated block; every `pb<>` / `pb_repeated<>`
field takes the untouched branches, so existing wire output is byte-identical
(proton's 99 existing tests, incl. byte-level round-trips, stay green).

Mark OidbMuteAllState.state `pb_optional<17, uint_32>` so unmute now puts
field 17 (=0) on the wire. New tests: proton pb_optional encode/round-trip
(incl. that sibling pb<> fields still omit zero), and a byte-level assertion
that mute-all unmute carries the state field.

Note: proton ships as a built Vite plugin (dist, gitignored); rebuild it
(`pnpm --filter @snowluma/proton build`) for the change to reach consumers.
2026-05-30 17:55:23 +08:00
DrSmoothl c4413dabb5 fix(proto): correct 0x8FC body/targetName field tags (set_group_card)
set_group_card always failed with `OIDB error 1007 on 0x8fc_3` (issue #70).
The 0x8FC request protos put the body wrapper at tag 2 and the member card
name at tag 2, but QQ-NT expects body at tag 3 and targetName at tag 8, so
the server found neither and rejected the request.

Cross-checked byte-for-byte against two working references:
  - Lagrange.Core OidbSvcTrpcTcp0x8FC: Body=ProtoMember(3), TargetName=8
  - NapCat Oidb.0x8FC_2: body=ProtoField(3), targetName=8

Fixes OidbRenameMember (0x8FC_3 set card) and the same latent bug in
OidbSpecialTitle (0x8FC_2 set special title), whose body was also at tag 2.
Send-only protos (empty deserialize); existing tests assert the command
name, not field tags, so they're unaffected.
2026-05-30 17:29:17 +08:00
DrSmoothl 71be3ae2e1 feat(webui): split overview into a processes page + mobile/ultrawide pass
The homepage was doing double duty — monitoring + injection control. Split it:

- New /processes page ("进程注入", sidebar #2) owns the QQ-process control
  surface (load / unload / refresh / probe-login + its dialogs). Overview is
  now a read-only dashboard: stats, host metrics, online accounts, plus a
  read-only injection-summary tile (online / loadable, links to /processes)
  and a first-run CTA that points at /processes while nothing is online.
  Route + AppPath + nav item wired; state/polling stay layout-owned.

Responsive + a11y pass:
- Mobile sidebar Sheet gets an sr-only title + description, fixing the Radix
  "DialogContent requires a DialogTitle" accessibility error.
- Log rows stack on phones (meta line + full-width message) instead of a
  ~40px column that broke every few chars; time parses defensively so a
  non-ISO value never renders "Invalid Date".
- Process cards stack on phones (info row + actions row) so name / PID / path
  stop collapsing to "Q.."; the status badge no longer wraps.
- Config tab strip scrolls horizontally on phones instead of wrapping to
  three rows; account strip defaults collapsed ≤lg; header buttons wrap.
- Dialogs keep a 1rem gutter on tiny screens via w-[calc(100vw-2rem)].
- Content widens to 1600px on ≥2xl; account/process grids gain a column at
  2xl so >1700px screens aren't mostly empty gutter.
2026-05-30 16:56:34 +08:00
DrSmoothl 76c6ebc700 feat(webui): settings tabs, password dialog, instant node save, error pages
Five WebUI changes:

1. Settings page rebuilt around mini tabs (外观 / 数据刷新 / 账号安全)
   instead of three stacked cards; content and behaviour unchanged.

2. "修改访问密码" now opens an independent ChangePasswordDialog modal
   rather than swapping the whole page for the forced-change screen. The
   form is extracted to a shared ChangePasswordForm used by both the modal
   and the forced full-screen ChangePasswordPage — behaviour identical.

3. Node config: creating / editing / deleting / enable-toggling an
   HTTP/WS endpoint now persists immediately — clicking 保存 in the editor
   dialog IS the save. Previously it only marked the config dirty until you
   also hit the top-right 保存, which silently cost many users their token
   edits. `save()` takes an explicit config so it persists the freshly
   computed value, not the stale closed-over state. The general-settings
   tab keeps its explicit top-right save.

4. Forced first-time change-password no longer renders an old-password
   field: it carries the password the user just logged in with. Browsers
   (Edge/Chrome) were autofilling that field on upgrade, so users thought
   the old password was pre-filled correctly and could never save. A
   returning already-authed session (no fresh login) still shows the field.

5. Added default error + 404 screens (status-screens.tsx), wired into the
   TanStack router via defaultErrorComponent / defaultNotFoundComponent.
2026-05-30 13:34:41 +08:00
DrSmoothl 74b6fe97e5 build(core): externalize node:sqlite instead of SSR-bundling
Addresses MliKiowa's review on PR #68 ("单独排除 sqlite 就行了"). That PR
fixed the `DatabaseSync is not a constructor` crash by switching the core
bundle to SSR mode (build.ssr + ssr.noExternal + target node22 + a
catch-all isNodeBuiltin external fn). The root cause was narrower: on
Node 22.x `node:sqlite` is experimental and absent from `builtinModules`,
so the `nodeModules` sweep didn't externalize it and Vite swapped in a
browser shell. The SSR switch also self-inflicted the @hono/node-server
MODULE_NOT_FOUND it then had to paper over with noExternal — the original
config already bundled all non-builtin deps.

Revert vite.config.ts to the pre-PR state and just add 'node:sqlite'
(+ bare 'sqlite') to the external list. Verified: `SNOWLUMA_TARGET=linux-x64
vite build` succeeds and dist/index.mjs now carries a real
`import { DatabaseSync } from "node:sqlite"` rather than a shimmed shell.
2026-05-29 20:22:06 +08:00
DrSmoothl 4a0626f00b fix(onebot): re-sign image rkey on get_image / get_msg lookups
get_image and get_msg returned the URL baked into the message store when
the message first arrived. That URL's rkey expires, so a client fetching
it later (or re-querying after the original push) got
`{"retcode":-5503010,"retmsg":"invalid rkey"}`.

Re-sign at lookup time from the raw unsigned `imageUrl` the media store
already keeps alongside the signed `url` (plus `isGroup`): getImageInfo
now takes the image rkey resolver and mints a current rkey, and get_msg
walks its segment array refreshing each image URL through it. Both are
best-effort — a resolver miss/throw or a non-array message body falls
back to the stored URL untouched. Mirrors NapCat re-signing on every
getImageUrl call instead of handing back a stale baked URL.

The resolver is reused from converterCtx (no new rkeyCache wiring); a
cache-hit re-sign is a string concat, only an expired rkey awaits the
already-deduped/cooled-down/timeout-bounded refresh.
2026-05-29 20:14:21 +08:00
墨梓柒 ba19cee07d Merge pull request #68 from H3CoF6/Dev
Fix SSR bundle and node:sqlite resolution in Vite config
2026-05-29 20:14:11 +08:00
DrSmoothl 624959f099 fix(onebot): await a fresh rkey before signing media URLs
Image/video/record download URLs are signed at receive-time with an rkey
(OIDB 0x9067_202, TTL-bounded). RKeyCache resolved synchronously: on a
cache miss or inside the expiry skew it returned the URL *without* an
rkey and only kicked off a fire-and-forget refresh (plus a 30s cooldown).
So during the expire→refresh window — and whenever the OIDB hiccuped —
SnowLuma emitted unsigned URLs, which the CDN rejects with
`{"retcode":-5503010,"retmsg":"invalid rkey"}`. Intermittent by nature.

Mirror NapCat's getImageUrl (`if (isExpired()) await refreshRkey()`):
make resolveImageUrl/resolveMediaUrl async and block on one refresh when
the cache can't serve a still-valid rkey. The refresh coalesces
concurrent callers onto a single OIDB round-trip, backs off for 30s after
a failure, and is bounded by a 5s timeout so a stuck packet send never
wedges message conversion (it degrades to whatever the cache holds).

Widen ImageUrlResolver to `string | Promise<string>` and await it in
to-segment so the image path can resolve asynchronously like media.
2026-05-29 17:56:39 +08:00
DrSmoothl 0110b71dd3 fix(protocol): send browser UA + Referer retry on media downloads
loadBinarySource issued a header-less fetch(source) for remote media.
Anti-hotlink / anti-bot front-ends reset such requests, surfacing as
undici `TypeError: fetch failed` (not a clean 403) — so quoting a
command and sending an image/GIF whose source is a guarded URL bounced
with send_group_msg retcode 1200 "fetch failed".

Mirror NapCat's download path: send a browser User-Agent on every
request and retry once with a Referer pointing at the resource when the
first attempt is refused (network error or 403/4xx). Size-limit
rejections are tagged noRetry so an oversized body isn't re-downloaded.
Also route set_group_notice's image fetch through loadBinarySource so it
inherits the same hardening (plus http/file/base64 handling).
2026-05-29 17:37:10 +08:00
H3CoF6 00ca582f1a feat(protocol): implement OIDB 0xcde_2 (RequestDbKey) (#69) 2026-05-28 15:18:06 +08:00
H3CoF6 bf932477dd build(core): fix SSR bundle and node:sqlite resolution in Vite config 2026-05-28 02:02:29 +08:00
手瓜一十雪 f2b7ef0056 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-27 20:02:40 +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