Compare commits

...

180 Commits

Author SHA1 Message Date
snowluma-bot[bot]
18d8273f5c Merge pull request #202 from SnowLuma/dev
chore: promote dev → main (0e6e2ec)
2026-07-05 06:26:33 +00:00
DrSmoothl
0e6e2ec51d chore(release): v1.11.3 2026-07-05 14:26:10 +08:00
DrSmoothl
007dfaf6e2 fix(group): self-heal member group card from message field 4
A member's cached group card could stay stale for the lifetime of a long-running
bot: nothing refreshes it on a card change (no push), and the member-list refetch
only fires on join/leave/admin events (+60s TTL), never periodically — so a quiet
group freezes at warmup. get_group_msg_history / live events then showed an empty
or outdated sender.card even though the current card was in the message.

Every group message carries the sender's current display name in grp.memberCard
(field 4 = group card if set, else base nickname). The group decoder now prefers
it over the possibly-stale cache when it differs from the base nickname (a real
group card); and packet-pipeline self-heals it back into the in-memory member
cache, gated so it writes only on an actual change. This keeps active members'
cards fresh for all cache consumers off message traffic alone — no extra fetch,
no rate-limit exposure. Verified on-target: a member's card change now reflects
in the next message without a member-list refetch.

Known, accepted edge: a member changing only their base nickname (no card) is
mislabeled as a card until the next member-list refetch corrects it — field 4
alone can't distinguish the two, and the mislabeled value is still the member's
own current name.
2026-07-05 14:20:36 +08:00
DrSmoothl
8dde7ef8e2 fix(onebot): seed self nickname on synthetic self-sent events
get_msg / get_group_msg_history returned an empty sender.nickname for the bot's
own group file / video sends. Those publish via OIDB (0x6d9_4 / c2c finalize)
rather than PbSendMsg, so the QQ server never echoes them back — and the echo is
what normally overwrites the synthetic self-sent store's placeholder nickname.
For a plain text send the echo arrives and fills it, which is why only file/video
surfaced empty.

Seed the synthetic event's sender.nickname from the bot's own
identity.nickname (we are the sender, so we know it). A normal text send's echo
still overwrites it with the same value. Verified on-target: a self-sent group
video now shows the bot nickname in history.
2026-07-05 14:20:36 +08:00
DrSmoothl
5f90cc9b6e fix(forward): preserve group merged-forward sender nickname (#201)
get_forward_msg returned empty sender.nickname for group merged-forward nodes.
The reporter blamed a mis-parsed group_id + a failing member-list enrichment
(0xfe7_3 0x899_AUTHORITY_FAIL), but on-target capture shows a mislabeled proto
field: the group response-head's sender display name lives in field 4, which we
had labeled `groupName`. It's populated on live pushes ("星屿" / the group card
"墨梓柒111") AND on merged-forward nodes (per-node sender name), while field 2
(`memberName`) is empty on live/forward and only set by the group-history fetch,
and the real group name is field 7. Lagrange labels field 4 `MemberName`.

Relabel ResponseGrp: field 4 `memberCard` (sender display name = card||nick),
field 7 `groupName` (the real group name); keep field 2 `memberName` for the
group-history slot. The group decoder now resolves the sender name by priority:
field-2 name → local member cache (clean nick/card split) → field-4 memberCard.
The last step is what lets a forward node from a group the bot isn't in keep its
per-node sender name with no member-list lookup, so the forward-specific fallback
and the AUTHORITY_FAIL enrichment path are no longer needed for the common case.

Verified on-target across scenarios: live message senderNick unchanged; a plain
forward, a forward from a never-joined group (placeholder uin 1094950020, four
distinct senders 金橘雪梨/Crel/503/Xiing0), and a nested forward all keep their
nicknames; no member-list call fires. group_id stays the payload's value.
2026-07-05 14:20:36 +08:00
DrSmoothl
a4ab4e92b5 fix(forward): preserve group merged-forward sender nickname (#201)
get_forward_msg returned empty sender.nickname/card for group merged-forward
nodes. The reporter blamed a mis-parsed group_id + a failing member-list
enrichment (0xfe7_3 0x899_AUTHORITY_FAIL on a placeholder source group), but
on-target capture shows the sender display name IS in the payload: a
merged-forward node leaves `grp.memberName` null and instead carries the sender
name in `grp.groupName` (field 4) — QQ repurposes the group-name slot per node.
parseMsgPush only reads memberName (correct for live messages), so the name was
dropped and the code fell through to the member-list enrichment, which can't
resolve a group the bot isn't in.

Fix: in the forward-node decode, fall back to `grp.groupName` for the sender
nickname (scoped to the forward path — live-message decoding is untouched). This
also makes the AUTHORITY_FAIL enrichment fetch unnecessary for the common case.
Verified on a real forward (fromUin 1787882683 ↔ grp.groupName "墨梓柒"):
nickname now populated, no member-list call. group_id stays the payload's value
(genuinely a placeholder/source group, not a mis-parse).
2026-07-05 04:30:44 +08:00
DrSmoothl
1b968b9126 feat(file): stream group + offline file uploads from disk (phase 5)
Wire the streaming primitives into the group-file and private/offline-file
upload paths. Both now stage the source onto a local disk path
(stageSourceToDisk — hardlink/download), hash it in one streaming pass
(hashFileStreaming; the offline-file md510MCheckSum comes from the same pass via
headLimit=MD5_HEAD_LIMIT), and PUT the file through a FileChunkSource — so a file
up to the 4 GiB protocol ceiling never holds more than one 1 MiB chunk in RAM.
The old readFileSync/loadBinarySource + computeHashes + md5First10MB buffered
path is removed.

The highway session is resolved before the file handle is opened (the handle's
owner, uploadHighwayHttp, must be the next call so its finally-close always
runs); a size+mtime guard re-checks the staged file before the PUT so a source
mutated mid-send fails cleanly; and the staged temp is released in a finally on
every exit. The OIDB preflight fields, the remembered-upload cache, the ext
blobs, and the publish steps (group 0x6D9_4 / private sendC2cFile) are byte-for-
byte unchanged. Tests re-mock at the stage/hash seams and assert the streamed
FileChunkSource + cleanup for both group and c2c uploads.
2026-07-05 03:42:16 +08:00
DrSmoothl
e83eb80f2c feat(video): stream video uploads from disk instead of buffering (phase 4)
Wire the streaming primitives into the video send path. `loadVideo` now stages
the source onto a local disk path (stageSourceToDisk — hardlink/download),
hashes it in one streaming pass (hashFileStreaming), and returns a `fileSource`
instead of a full in-memory buffer; the main video sub-file PUTs through a
`FileChunkSource`, so a multi-GiB video never holds more than one 1 MiB chunk in
RAM. The thumbnail and the fingerprint (noByteFallback) fast path stay
byte-based and unchanged.

`runPuts` now sizes its fast-path / fast-only checks off `fileSource ?? bytes`
and resolves the highway session before opening the file handle (the handle's
owner, uploadHighwayHttp, must be the next call so its finally-close always
runs). A size+mtime guard re-checks the staged file before the PUT so a source
mutated mid-send fails cleanly rather than shipping bytes that disagree with the
already-sent hashes. The staged temp is released in every exit path.

Output is byte-identical to the buffered path (the OIDB fileInfo md5/sha1/size
and the uploaded bytes are unchanged); the old readFileSync-based
stageVideoSource is removed. Tests cover the disk path (fileSource not bytes,
streamed hash == buffered hash), cleanup on upload failure, and empty sources.
2026-07-05 03:23:19 +08:00
DrSmoothl
0e4d958b5f feat(highway): add stageSourceToDisk + shared HTTP downloader (phase 3)
Stage any upload source onto a local disk path so the uploader can stream it
without buffering the whole file. `stageSourceToDisk(source, maxBytes)` unifies:
local file:// / raw path → hardlink into an owned stage dir (O(1); the inode
link pins the bytes against a caller-side unlink/retention), streamed-copy
fallback on any link() failure; http(s):// → stream to a .part file; base64://
→ maxBytes-checked decode to a .part file. Temps are finalized atomically
(fsync file → rename → fsync dir); a TTL reaper reaps crash-orphaned temps while
an in-use `active` set protects live uploads (a hardlink keeps the source's old
mtime, so the staged path is reserved in `active` before it appears on disk).

To avoid divergence, the existing `loadBinarySource` HTTP transport is extracted
into a shared `downloadHttp(source, name, maxBytes, makeSink)` engine (browser
UA, redirect, timeout, Referer retry, declared + streamed size caps, noRetry);
`loadBinarySource` now drives it with an in-memory sink — behavior unchanged.

Additive only — not yet wired into video/file uploads. Tests cover the
retention race (hardlink survives the original's deletion), the reaper's
active-set protection, size caps, symlink resolution, the copy fallback, the
Referer retry reusing the .part, and streamed-overflow .part cleanup.
2026-07-05 03:01:10 +08:00
DrSmoothl
631cc982a0 feat(ci): build & push a rolling dev Docker image on every dev commit
On push to `dev`, dispatch SnowLuma.Docker.Framework/docker-image.yml to build
and push motricseven7/snowluma:dev (rolling) + :dev-<12sha> (immutable) from
this run's workflow artifact — no GitHub Release involved. also_latest=false so
dev never touches the stable :latest; the downstream job prunes old dev-<sha>
tags (keep newest 5). The dispatch job writes source SHA / run id / downstream
run URL to the job summary.

Supporting changes:
- Bundle production node_modules (npm install --omit=dev) before packaging so
  the lite tarball the image bakes is actually runnable — mirrors release.yml.
- Add a deterministic-name hand-off artifact (snowluma-dev-docker-linux-x64,
  dev-only) that the cross-repo Docker build downloads by name.
- Concurrency: only `dev` shares a self-cancelling group; every other branch
  keeps a unique per-run group, so their behavior is unchanged.
- Age-gate the artifact cleanup (delete >24h, collect-then-delete) so it can't
  race-delete an in-flight dev hand-off artifact.
2026-07-05 02:41:03 +08:00
DrSmoothl
7b91903f80 feat(highway): add streaming file hasher hashFileStreaming (phase 2)
Single-pass, disk-streaming replacement for the buffered
`computeHashes` + `computeVideoSha1Blocks` (+ offline-file head md5): reads the
file 1 MiB at a time so hashing a multi-GiB upload never buffers the whole file.
Reproduces the buffered helpers exactly — whole-file md5/sha1, the per-1 MiB
intermediate SHA1 state snapshots plus the finalized whole-file SHA1, and an
optional md5 over the first N bytes (`headLimit`, for `md510MCheckSum`).

Additive only — not wired into any caller yet; the old helpers stay in place.
Lands in a new leaf module to avoid a utils↔highway-client import cycle. A
byte-oracle test asserts identity vs the buffered functions across sizes around
the 1 MiB block boundary (empty, sub-block, exact multiples, ±1, multi-block +
tail) and head limits across chunk boundaries.
2026-07-05 02:37:56 +08:00
DrSmoothl
5324e2f014 refactor(highway): introduce ChunkSource for uploadHighwayHttp (phase 1)
Prep for streaming large media uploads from disk instead of buffering the
whole file in RAM. Add a `ChunkSource` abstraction — `BufferChunkSource`
(in-memory, byte-for-byte the old path) and `FileChunkSource` (disk-backed,
reads exact-length chunks via a FileHandle, loops on short reads, throws on
unexpected EOF) — and change `uploadHighwayHttp` to consume a `ChunkSource`
instead of a `Uint8Array`. The uploader now owns the source and closes it once
in `finally` (best-effort; never masks a primary upload error).

Pure structural refactor: no streaming is wired yet. All five call sites
(pipeline runPuts, group + private file upload, personal + group avatar) wrap
their bytes in `BufferChunkSource`, so behavior is unchanged. Adds a
byte-oracle test proving FileChunkSource ≡ BufferChunkSource across block
boundaries, plus short-read/EOF/empty-input coverage.
2026-07-05 02:29:13 +08:00
DrSmoothl
c236bc86ee feat(video): raise video-path size limit to 1.5 GiB (#145)
The 100 MB cap that re-routed larger videos to the file-upload pipeline
was a workaround for the width/height=0 → 已过期 bug (fixed in the prior
commit), not a real QQ size limit. Real-machine verified on tempserver:
88 MB / 149 MB / 299 MB / 497 MB videos all upload, render and play as
normal videos in a group. Raise MAX_VIDEO_SIZE to 1.5 GiB (matching the
file-upload ceiling); only videos above that still fall back to the file
path. Collapse the redundant MAX_VIDEO_SIZE_HARD (was also 1.5 GiB) into
the single constant and drop the now-dead 100 MB warn branches.

Note: the whole video is buffered in RAM for the Highway upload, so a
1.5 GiB send costs ~1.5 GiB+ of process memory — that, not a QQ limit,
is what bounds the ceiling.
2026-07-04 23:45:36 +08:00
DrSmoothl
9a6c17cb27 fix(video): carry real width/height on group video sends (#145)
A group video uploaded with fileInfo width/height = 0x0 reaches receivers
as 文件已过期 even though the resource is fresh and downloadable: QQ-NT
clients (Android especially) can't lay out the video tile without real
dimensions, so they render the expired placeholder. iOS is lenient — it
shows the expired badge but still opens the video, which is exactly the
"iOS 显示过期可以点开、安卓过期点不开" split users reported.

Real-machine capture on tempserver confirmed a working QQ group video's
MsgInfo carries real dimensions (e.g. 296x640) while ours sent 0x0. Fill
width/height from the probed video for group sends; c2c stays at 0 because
the QQ-NT server rejects non-zero dimensions there with a schema mismatch
(no c2c regression coverage yet). Verified end-to-end: a fresh 11 MB group
video that rendered 已过期 now displays and plays.
2026-07-04 23:15:03 +08:00
DrSmoothl
efac547d6a feat(webui): redesign CPU & memory overview cards
CPU 使用率: replace the flat per-core bar row with an adaptive heatmap
grid — auto-fill square cells whose color maps to per-core load — so it
reads cleanly from a few cores up to many-core (64/128) hosts instead of
squashing into an unreadable strip.

内存使用: replace the single usage bar with a segmented
本进程 / 其他已用 / 空闲 breakdown bar plus a legend, surfacing the
SnowLuma process's own RSS footprint (systemInfo.runtime.rss) that the
card never exposed before.

Removed the now-unused bestGrid() helper. All motion uses transform
(scale) rather than width/height to avoid layout thrash.
2026-07-04 22:10:38 +08:00
DrSmoothl
770b224d58 feat(onebot): decode incoming 闪传 flash-file messages (#199/#200)
Older QQ clients (≤9.9.30) deliver a 闪传 (flash transfer) file as a richui
markdown commonElem (svc=45, busId=FlashTransfer); SnowLuma had no decoder for
it, so the message decoded to 0 elements and was reported empty. (Newer
clients ≥9.9.31 send a plain text+link message that already decodes fine.)

Decode svc=45 markdown → parse the FlashTransfer card JSON → emit a flash_file
element, surfaced as the segment the issue asked for:
  { type: "flash_file", data: { title, file_set_id, scene_type } }

- Field names (fileSetId / sceneType / title) confirmed against QQ NT's
  flash-transfer manager in wrapper.node.i64. The card is built by the
  sender's client so the exact JSON nesting is unknown — values are pulled by
  a bounded recursive search rather than a pinned path (handles either shape).
- Non-FlashTransfer markdown is ignored; missing fields default (never empty).
- Manifest: D/S = yes, P/W = by-design-no (receive-only; sending is the
  existing send_flash_msg action). Log preview shows [闪传文件:title].
- Tests: card decode (nested + alias + defaults + non-flash) and the
  element→segment mapping.

Note: not end-to-end verified on a live message — the svc=45 format only comes
from ≤9.9.30 senders and no such client was available (every test sender here
is ≥9.9.31 → text format). Logic + field names are unit-tested / IDA-confirmed.

typecheck 12 包; protocol 596 / onebot 529 green.
2026-07-04 19:02:47 +08:00
H3CoF6
0d03b00643 Fix(Qzone) -10000风控修复 && Fix(port-probe) PID探测多pid逻辑修复和偶数端口 (#192)
* fix(protocol): retry qzone msglist via user.qzone route on -10000

emotion_cgi_msglist_v6 through the legacy h5.qzone.qq.com →
taotao.qzone.qq.com gateway can be rejected with `-10000 使用人数过多`
for some accounts (issue #182). Real-device captures show the same CGI
via user.qzone.qq.com → taotao.qq.com is not rate-limited, so retry once
through that route when the legacy route returns -10000.

Behaviour-preserving for accounts the legacy route already serves: the
retry only fires on a -10000 envelope; all other codes, transport
errors, and the missing-msglist case are unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(port-probe): fix port probe logic (parse accounts more than 2) and add description for 4302-4310 port.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 14:33:02 +08:00
Airline233
d3eb3bae14 feat(qzone,onebot): add set_qzone_ban action for qzone blacklist management (#193)
* feat(onebot,qzone): add set_qzone_ban action for qzone blacklist management

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-07-04 14:32:40 +08:00
snowluma-bot[bot]
5f01c6ab5f Merge pull request #198 from SnowLuma/dev
chore: promote dev → main (6cb7f2c)
2026-07-04 05:39:20 +00:00
DrSmoothl
6cb7f2c6d0 chore(release): v1.11.2 2026-07-04 13:39:00 +08:00
DrSmoothl
07c08ed74d feat(onebot): enrich group/member info fields (#197)
Round out the OneBot v11 group-profile fields the issue asked for.

Group (get_group_info / get_group_list, inherited by get_group_info_ex /
get_group_detail_info):
- group_create_time + group_memo come free from the 0xFE5_2 list
  (createdTime / announcement), verified live (createdTime=1729505343,
  announcement populated).
- group_level lives only in the 0x88D_0 detail; get_group_info fetches it
  (memoized 5min) so a joined group doesn't hit the detail every call.
  get_group_list leaves it 0 — a per-group detail fetch across the whole
  list would be far too costly.

Member (get_group_member_info / get_group_member_list):
- Add area / unfriendly / title_expire_time / card_changeable. QQ NT does
  not expose these, so they're fixed placeholders ('' / false / 0 / true),
  matching go-cqhttp / NapCat. sex/age stay unknown/0 (real values need a
  per-member profile fetch — out of scope here).

typecheck 12 packages; onebot 523 / core 472 green.
2026-07-04 13:04:32 +08:00
DrSmoothl
b20ed12761 fix(onebot): approve group requests from the filtered inbox too (#197)
set_group_add_request could fail with "matching group request not found"
for a request SnowLuma had itself just reported. handleGroupAddRequest only
fetched the main inbox (0x10C8 subCommand 1); a spam-filtered join/invite
lives in the filtered inbox (subCommand 2) and was never searched, so its
flag couldn't be resolved to a sequence.

Fetch both inboxes and search the union. Each request keeps the `filtered`
flag its approval subCommand needs, so a filtered request is approved
through subCommand 2. A failing inbox fetch degrades to the other instead
of aborting. Regular MSF invite pushes don't carry the approval msgseq
(only the private-card path does, #125), so the fetch is the only source.

Regression tests: filtered-only request is found + approved via subCommand
2; "not found" only when neither inbox has it.
2026-07-04 12:48:06 +08:00
DrSmoothl
c027161a64 fix(protocol): get_group_file_system_info returns real counts + space (#196)
file_count 恒为 0(且 used_space/limit_count/total_space 是占位/写死值)。根因:
0x6D8 view 命令分三个 subcommand(1=List, 2=Count, 3=Space),但 getCount 错发到
**subCommand 3(Space)** 且 busId=0,并从 pb<1>/pb<2> 读计数——服务端根本没返回
Count 块,于是恒 0。

真机 RE(bot 在测试群传/删文件核对):
- Count 走 **0x6D8_2 + busId=6**,响应 Count 块里 fileCount=**field 4**、maxCount(文件
  数上限,如 1500)=**field 6**(旧 pb<1>/pb<2> 全落空)。
- Space 走 **0x6D8_3**,响应 Space 块 totalSpace=**field 4**、usedSpace=**field 5**(64 位)。
- 实测:fileCount=4、limitCount=1500、usedSpace=20103729、totalSpace=10737418240。

修复:改 GetGroupFileCount 到 subCommand 2 + busId 6 + 正确 tag;新增 GetGroupFileSpace
(0x6D8_3);action 并发查两者,四个字段全返回**服务端实际值**(优于 NapCat 的写死占位)。
含 count/space 编解码回归测试。catalog regen。

typecheck 12 包;protocol 591 / onebot 521 / core 472 全绿。
2026-07-04 01:59:52 +08:00
DrSmoothl
95b5878456 feat(onebot): return new folder info from create_group_file_folder (#195)
create_group_file_folder 之前只回 data:null,拿不到新建文件夹的 folderId。现对齐
NapCat 返回结构,data 带回文件夹信息:
  { result: { retCode, retMsg }, groupItem: { folderInfo: { folderId, folderName,
    folderPath, createTime, modifyTime, createUin, modifyUin } } }

- 0x6D7_0 创建响应本就在 field 4 携带 folderInfo,SnowLuma 旧 proto 没解(只读
  retcode/retMsg/clientWording)。补上 OidbGroupFileFolderInfoResp 并让 create 的
  deserialize / bridge / action 一路把它带出来。
- 真机验证(bot 在测试群建夹→读回 folderId→删除清理):确认 folderInfo 存在,且
  **modifyUin 在 field 9 而非 Lagrange proto 标注的 field 7**——按真机 wire 修正。
- 新增两个解码回归测试(带 folderInfo / 缺 folderInfo 兜底)。catalog regen。

typecheck 12 包;protocol 587 / onebot 521 / core 472 全绿。
2026-07-04 01:25:14 +08:00
DrSmoothl
f127e3dc59 fix(webui): meet WCAG AA for log-level text on light theme
The log-level accent colors (info/success/warn/error) are tuned as fills;
as small text on the light canvas they fell below WCAG AA (info 2.6:1,
success 2.4:1, warn 2.0:1, error 4.3:1, trace 2.5:1). Add dedicated
--log-* text tokens that are darkened in light mode (>=4.5:1) while
keeping the bright, already-passing values in dark mode, so the app-wide
accent is untouched. trace moves from /60 to /90 to clear AA yet stay the
faintest level. Applied to both the logs page and overview RecentAlerts.
2026-07-04 00:08:30 +08:00
DrSmoothl
7b93eb2716 fix(webui): treat ?token= URL param as the login password (#194)
abef797 misread the request and seeded the value as a bearer session token
(which the operator would have to dig out of localStorage). The intent is
simpler: `?token=<你的WebUI登录密码>` — the value is the plain WebUI login
password, so the link is trivially constructable from something the operator
already knows.

- Revert the client-constructor bearer seeding from abef797.
- AuthBoundary: when no stored token already authed us and the URL carries
  ?token=, run it through client.login() (the normal password path). A correct
  password lands on the home page; a wrong one falls through to the login page
  (server-verified, no bypass). The password is carried into the forced
  change-password gate, matching the interactive login flow.
- The param is consumed once and stripped from the URL (replaceState) before
  the login call — a password in the address bar leaks via history / logs /
  Referer.

typecheck 12 包干净。
2026-07-03 19:41:25 +08:00
DrSmoothl
abef7973d9 feat(webui): auto-login via ?token= URL query param (#194)
登录页每次手输密码很繁琐。支持在 URL 带 `?token=<accessToken>` 直接免密进入:
API client 构造时读取该参数作为 bearer token,交由既有 /api/status 门校验——
有效则直达主页,无效/过期则照常落登录页(无安全降级,服务端仍校验)。

安全处理:token 读取后**立即从 URL 剥离**(history.replaceState)——凭据留在地址栏
会经浏览器历史 / 服务端访问日志 / Referer 头泄露。同时持久化到 tokenStore,
使随后刷新(URL 已无参数)仍保持登录。URL token 优先于已存 token。

只做 token(不做 password)——token 就是实际 bearer 凭据,无需额外登录往返、
也比明文密码更适合放链接。
2026-07-03 19:30:53 +08:00
DrSmoothl
7744e24af2 fix(protocol): make set_group_search actually apply search flags (#191)
旧实现走 OIDB 0x89a_0 但 settings 发空字节 → 服务端返 ok 却 no-op;action 也只收
group_id,没有设置搜索方式的参数(报告属实)。

真机 RE 定稿(tempserver,bot 为管理员的实群逐字段扫描 + GET 读回):
- 修改命令 = 0x89a_0(全量抓包确认,与 MuteAll 同命令,靠 body 形状区分)。结构
  = {1:groupUin, 2: 只含被改字段的 GroupDetailInfo modify 子消息}。这是与 0x88D_0
  群详情 GET **不同的消息域**(mute/shutUpTime 在此=tag17,在 GET 里却是字符串),
  所以标签不能照搬 GET。
- 在 modify 子消息里逐 tag 试写、经 0x88D_0 GET 读回效果,定位:
  noFingerOpen(关键词/群指纹搜索)=tag 35,noCodeFingerOpen(群号搜索/总开关)=tag 36;
  再对照客户端「被搜索方式」三选下拉(私密/群号/群号+关键词)核实语义与 0/1 取值。
- proto-defs:settings 改为 Oidb0x89a_0SearchSettings 子消息,两 flag 用 pb_optional
  (显式存在)——否则 proto3 丢 0 值,导致关闭(=0)被静默忽略。undefined 仍省略。
- set-search/bridge/action:透传 no_finger_open / no_code_finger_open;只下发提供的
  字段(同 NapCat filter 机制、与 modify-group-ext-info 一致)。catalog regen。
- 编码测试锁定:0 值必发 tag 35/36、未提供则省略、命令为 0x89a_0。

typecheck 12 包干净;protocol 585 / onebot 521 / core 472 全绿。
2026-07-03 17:37:55 +08:00
Airline233
884db940df feat(qzone): add set_qzone_msg_right to change a feed's visibility (#186)
* feat(qzone): add set_qzone_msg_right to change a feed's visibility

Add updateQzoneMsgRight in the protocol layer, porting php-qzone's
updateRight: fetch the feed via emotion_cgi_msgdetail_v6, rebuild the
full publish-shaped payload (richval/pic_bo/con), then override
ugc_right/allow_uins and POST to emotion_cgi_update. Expose it through
QzoneApi.updateRight and the OneBot set_qzone_msg_right action, with the
same ugc_right/target_uins validation as send_qzone_msg. Covered by
protocol, core and onebot tests.

* fix(qzone): make qzoneParse more stable and fixed a test example
2026-07-02 22:38:05 +08:00
DrSmoothl
3e99d3bb5a fix(webui): guard async polling against re-entrant overlap
三个 setInterval 轮询(列表 reconcile、systemInfo 快刷、6h 更新检查)调度的都是 async
tick,但 setInterval 不感知 Promise 完成——当某次请求慢于轮询间隔时,下一次 tick 会在
上一次未完成时又发起,导致同类请求并发堆叠、越积越慢。

每个 tick 加在途 running 互斥:上一次刷新还在飞就跳过本次,完成(try/finally,含出错)后
恢复调度。保留已有的 document.hidden 门控与变可见补刷。慢 tick 只是被跳过、完成后自愈,
不会永久停摆。

(引 non-overlapping-poll 工具 + 给 webui 新增测试基建对 3 个轮询点属过度工程,故就地加
互斥。)
2026-07-02 21:04:35 +08:00
DrSmoothl
b5ede95772 test(core): fake timers for group-history walk-back to skip send-gap waits
The walk-back loop enforces a real ~300ms gap between each SsoGetGroupMsg send
(a deliberate process-wide anti-flood throttle). The test paid that gap for
real — up to 300ms x 12 sends per case — making the file ~5.2s.

Install vitest fake timers and drain the queued send-gap timers via
runAllTimersAsync, so the loop/cursor logic runs instantly. The production
throttle is untouched (only the test file changes).

Walk-back test body ~5237ms -> ~4ms; full core suite ~21s -> ~4.4s.
2026-07-02 19:55:50 +08:00
DrSmoothl
1f2bf4d3f2 chore(deps): patch low-severity esbuild + @babel/core advisories
两个构建/测试期工具链的 transitive 依赖存在低危「任意文件读」告警(非运行时产物):
- esbuild 0.27.7 → 0.28.1(dev server 任意文件读,vite 接受 ^0.28.0,兼容)
- @babel/core 7.29.0 → 7.29.7(sourceMappingURL 任意文件读)

pnpm.overrides 钉住修复版下限(esbuild@<0.28.1 / @babel/core@<7.29.6),防止后续
lockfile 重生回退。全 12 包 typecheck 干净、webui vite build 通过、protocol 572 测试
全绿,工具链未受影响。
2026-07-02 15:16:40 +08:00
DrSmoothl
c85c510c0b perf(webui): trim debug-view rendering cost (json-tree, activity, tester)
- json-tree:折叠节点不再枚举子项(改用 count),整棵树的 JSON.stringify 从每次渲染
  改为点击复制时才算。
- live-activity:搜索命中串在入队时预生成,过滤不再对每行 JSON.stringify(300 行 ×
  每次击键)。
- action-tester:流式帧封顶 2000,长/失控流不再无限增长数组与 DOM。

均行为保持(或纯改善),对抗性 Agent 逐条核验无回归。
2026-07-02 15:02:13 +08:00
DrSmoothl
99547e847e perf(webui): gate list/system polling on tab visibility
两个兜底轮询(列表 reconcile、systemInfo 快轮询)的 tick 在 document.hidden 时跳过,
并监听 visibilitychange 在切回时立即补一次。后台标签页不再空转 fetch;实时状态本就
走 SSE(未门控),切回时立即刷新无空态闪烁。
2026-07-02 15:02:13 +08:00
DrSmoothl
d17381a221 perf(webui): batch log SSE into ~80ms flushes instead of per-line setState
日志页每收到一条日志就 setLogs(prev => [...prev.filter(id≠), entry].slice(-cap)),
高日志速率下是每条一次 O(n) 过滤+复制 + 一次 React commit。改为入队到 pending、
每 ~80ms 批量 flush:一次 O(n) 合并(Map 去重、last wins)+ 一次 commit。去重(重连
重放同 id)与 maxLines 上限语义保持不变,卸载时 dispose + 清 timer。
2026-07-02 15:02:13 +08:00
snowluma-bot[bot]
a11c684dfd Merge pull request #183 from SnowLuma/dev
chore: promote dev → main (72aedbc)
2026-07-01 14:15:29 +00:00
DrSmoothl
72aedbc612 chore(release): v1.11.1 2026-07-01 22:15:01 +08:00
DrSmoothl
63ab7a1846 fix(protocol): parse Qzone feeds without eval + stop getCookies hanging (#182)
真机抓包定位到 get_qzone_feeds 的两个问题:

1) feeds3_html_more 的响应体是**JS 对象字面量**(键无引号、单引号字符串、\xNN
   转义、数组含 undefined),不是 JSON → JSON.parse 报 "Expected property name
   at position 66"(报告者看到的「响应结构问题」)。实测调参数(outputhtmlfeed/
   format)改不掉这个格式,且 feeds 是纯远程 H5(native i64 里无相关 CGI),没有
   干净 JSON 端点。改用**非执行的递归下降解析器** parseJsLiteral 把它当数据解析——
   绝不 eval 远程内容(vm 沙箱不是安全边界,被篡改的响应可逃逸到 RCE)。解析器只认
   对象/数组/字符串/数字/true|false|null|undefined,丢弃 __proto__ 键防原型污染;
   mapFeeds 过滤数组尾部的 undefined 洞。

2) getCookies 卡死:HttpsGetCookies 无超时、无深度上限地递归跟随 302;当某跳目标
   不可达(数据中心/Docker 上 qzone.qq.com 裸域超时)→ 永久挂死所有 cookie-backed
   web 动作。加 8s 超时 + 深度上限(5) + 失败/超时保留已收集 cookie(不再 reject)。

两处修复均在 tempserver 真机验证:getCookies 从卡死 3 分钟变正常返回;抓到的真实
feeds 响应体做成测试 fixture,非执行解析器正确解出 uin/nickname/html(\x3C→<)。
读接口加了 TRACE 原始体日志 + 结构失败错误带响应片段,方便后续排查。
(msglist 的 -10000「使用人数过多」判定为 taotao 服务端风控——同 cookie 下 feeds
能成功、msglist 单独挂,非代码 bug,代码已正确透传。)

protocol 572 全绿、typecheck 干净;两轮对抗性 Agent:先揪出 vm 版可 RCE 逼我换非执行
解析器,再确认新解析器构造上不执行代码、无原型污染、真机数据解析正确。
2026-07-01 21:56:28 +08:00
DrSmoothl
3932958c39 fix(bridge,common,onebot): reject phantom hook UINs + never crash logging (#162)
注入的竞态窗口里,native hook 偶发上报 13 位垃圾 UIN(时间戳型,读到 QQ 尚未落定
的内存)。TS 层防御缺失,导致两个连锁问题:

1) 幽灵账号:isRealUin 只查「纯数字且 ≥5 位」、无上限,垃圾值通过后建会话并把
   config/onebot_<垃圾>.json 落盘 → OneBot 节点配置里出现随机幽灵账号(跨重启残留)。
2) 进程崩溃:logger 彩色路径 ' '.repeat(SLOT - tagLen),UIN tag(含方括号)超宽 →
   负数 → RangeError: Invalid count value → uncaughtException。

跨平台(Win DLL / Linux .so 同逻辑)+「更新 QQ 后消失」都印证是 native 读到那块内存
的偶发垃圾;根修在 SnowLumaNative,此处补齐 TS 防御:

- 抽出唯一的 @snowluma/common/uin::isRealUin = /^\d{5,10}$/(真实 QQ ≤ uint32 →
  10 位)。删除 bridge/core 两处重复副本(重复正是这次漏加上限的温床)。等价旧逻辑,
  仅新增拒 11+ 位。
- logger.ts 加 Math.max(0, …),日志永不崩进程(独立健壮化)。
- 收紧 WebUI UIN_REGEX /^\d{5,12}$/ → /^\d{5,10}$/ 保持一致。
- 启动时 cleanupInvalidPerUinConfigs() 清掉已落盘的幽灵 onebot_<uin>.json(只删
  UIN 不合法的,绝不碰合法账号/全局配置)。

测试:common +8(uin 6 / logger 2)、onebot +3(cleanup)。typecheck 12 包干净;
common 58 / onebot 519 / core 471 / bridge 73 全绿。对抗性 Agent 逐输入核验等价性、
三层 gate 堵死幽灵入口、cleanup 安全时序,无回归。
2026-07-01 20:37:02 +08:00
DrSmoothl
ade76d3d2f refactor(protocol): reuse tested Sha1Stream in video block-sha1 (drop dup)
video-upload.ts 有一份 ~110 行手写、**无测试**的流式 SHA1(Sha1StreamState),与
sha1-stream.ts 里已充分测试的 Sha1Stream 逐字节相同(transform 数学等价、中间 state
小端)。删掉该重复,computeVideoSha1Blocks 改用 Sha1Stream 做 1MB 块的中间 state、
Node crypto 做整文件 final(与受测的 computeSha1StateV 同一套路;已实测旧 final() ===
Node crypto 整文件 sha1)。

- 新增 video-sha1-blocks.test.ts(4 例):golden 值从**旧实现**抓取,锁定重写 byte-
  identical(两个 1MB 中间 state + overall),并给这个原本无测试的函数永久覆盖。
- 删掉的 tail-update 只影响旧自实现 final,不动任何中间块(tail<64B 不触发 1MB 边界)。

protocol 565 全绿、typecheck 干净;对抗性 Agent 独立复现旧实现确认 golden 逐字节
相同、transform 数学等价无精度问题、无残留引用。
2026-07-01 20:14:55 +08:00
DrSmoothl
c822c5dab6 refactor(webui): extract useFlashMessage hook for settings panels
三个 settings 面板各手写同一套 flash-message 状态机(msg state + setTimeout 自动
消失 + 卸载清 timer)。global-config / notifications 是完整版(逐字相同);
system-panel 是退化版(无 timer ref、无 cleanup、rapid flash 累积 timer、卸载后可能
stale setMsg)。抽 useFlashMessage(durationMs=2400) → { msg, flash, setMsg }。

- global-config / notifications:迁移后行为不变(2400ms;flash 瞬时 + setMsg 持久
  错误保留)。
- system-panel:保留 4000ms(useFlashMessage(4000)),顺带补上 prior-timer 取消 +
  卸载 cleanup(修 timer 泄漏,现代 React 里无害的小改善)。

webui typecheck(tsc -b) + vite build 干净;对抗性 Agent 逐行核对确认 hook 等价、
两面板行为不变、无依赖/import 回归。
2026-07-01 20:03:58 +08:00
DrSmoothl
a8f24b8f13 refactor(onebot): converge self-sent message tail into finalizeSend
send/forward 路径里「记录自发消息」的尾巴(hashMessageIdInt32 + cacheMessageMeta +
cacheSelfSentMessage)逐字复制 6 份(sendPrivate/sendGroup/两个 forward/forwardSingle
的 group+private 分支),每处独立手工配对 isGroup ↔ eventName ↔ hash 事件常量——
漏改一处会静默产生错 message_id / 错 event 归属。抽 finalizeSend(ref, isGroup,
targetId, receipt, elements),由 isGroup 单点派生 eventName + 常量。

6 处塌成 6 行调用;forwardSingle 的 group/private if/else 只剩 send API 本身不同。
receipt 用结构类型覆盖所有调用点(含 line 630 合成的 fallback)。

行为严格不变:onebot 516 全绿、typecheck 干净;对抗性 Agent 逐字对比 HEAD 确认
6 处等价、参数/返回正确。
2026-07-01 19:55:21 +08:00
DrSmoothl
f111ba7129 fix(core): resolve self uid instead of shipping an empty one (forward/flash)
阶段 2:修 self-uid 收口暴露的 2 处静默空串 bug。warmup 未完成时 identity.selfUid
为 null,原 `?? ''` 会把空 uid 放进出网包:

- forward.ts:154 responseHead.toUid(转发广播消息坏包)
- flash-transfer.ts:279 fileset uploader.uid(空 uid 会被服务端 drop fileset)

均改为 `await resolveSelfUid(...)`:正常路径(selfUid 有值,几乎总是)命中缓存、取值
完全不变;仅在身份未就绪的极端情况从「静默发坏包」变成「明确报错」(fail-loud)。
两处外层函数本就 async。group-admin.ts:64 的 ?? '' 是合成本地事件、best-effort、
非出网,保留不动。

core 471 全绿、typecheck 干净;对抗性 Agent 确认正常路径不变、无测试回归。
2026-07-01 19:18:10 +08:00
DrSmoothl
3db89d0bd0 refactor(protocol,core): converge self-uid resolution to one impl
「取自己 uid」原本散成 5 份、3 种错误文案:core/apis/shared.ts::resolveSelfUid、
group-file/message 各内联手抄一份、get-like 跨包再抄一份。收敛成 protocol 单一
resolveSelfUid(ctx: Pick<BridgeContext,'identity'|'resolveUserUid'>)。

阶段 1(行为不变):
- 新增 protocol/self-uid.ts(依赖方向 core→protocol 要求权威实现下沉 protocol;
  Bridge 与 OIDB service Deps 都满足 Pick 切片)。
- core/apis/shared.ts 改为 re-export 它(现有 resolveSelfUid(bridge) 调用点不变)。
- get-like/group-file/message 三处内联手抄 → 全调权威实现。
- 唯一副作用:message 的错误文案统一为 'self uid is unavailable'(无测试依赖旧文案)。

flash-transfer/forward 的 ?? '' 空串 bug 留待阶段 2;group-admin 合成本地事件保持不动。
全仓 12 包 typecheck Done、protocol/core(471)/onebot(516) 全绿;对抗性 Agent 确认
toInt/Number 边界无实际差异(identity.uin 恒为正整数串)、5 处等价。
2026-07-01 19:12:05 +08:00
DrSmoothl
298d174640 refactor(webui): extract openSseChannel for the three EventSource openers
stateStream / openLogStream / openDebugStream 三个 EventSource opener 近乎逐字重复
(token 守卫 → EventSource → onopen/onerror → onmessage try-parse-catch → close
disposer),token/reconnect/畸形帧-跳过 语义各写一遍、易漂。

- 新增私有 openSseChannel<T>(path, onMessage, onStatus?) 收敛骨架;各 opener 塌成
  一行调用,consumer 逻辑作为 onMessage 传入(保持「回调在 try 内、抛错当畸形帧
  吞掉」语义)。logs 的控制帧过滤(`'type' in parsed`)留在其 onMessage 回调里。
- StreamStatus 提到顶部 import,删掉 openDebugStream 的 inline import。

行为严格不变、对外签名不变:webui typecheck(tsc -b) + vite build 干净;对抗性 Agent
逐字对比 HEAD 确认三 opener 等价、onMessage-在-try-内 语义保留、无漏并入。
2026-07-01 18:58:22 +08:00
DrSmoothl
29a792cfdf refactor(core): extract sseResponse helper for the three WebUI SSE endpoints
/api/debug/stream、/api/state/stream、/api/logs/stream 各自逐字复制同一套 ~40 行
SSE 生命周期骨架(TextEncoder + closed 守卫 + 15s heartbeat + teardown + safe
enqueue + abort listener + event-stream headers);改一处 heartbeat 间隔/teardown
顺序/headers 要同步改三处,漏一处会 listener 泄漏。

- 新增 webui/sse-response.ts:sseResponse(c, start) 封装传输壳,给 start 回调一个
  channel { raw, encode, send, onClose, isClosed, desiredSize }。各端点特有的订阅/
  背压 framePusher/初始快照留在回调里。
- 三端点收敛:debug/state 用 createFramePusher(背压丢帧) + onClose 注册订阅;logs
  直接 ch.send;state 的 503 守卫留在 helper 外。
- 新增 sse-response.test.ts(4 例)为这三个原本无生命周期测试的端点建立安全网。

行为严格不变:core 471 全绿、typecheck 干净;对抗性 Agent 逐字对比 HEAD 确认
helper 骨架与三端点等价、无时序/守卫回归。
2026-07-01 18:53:34 +08:00
DrSmoothl
c1d27c5055 refactor(protocol): converge packet-pipeline dispatch tail into finishDispatch
process() 的 sync 分支、dispatchAfterIdentityRefresh、dispatchGroupInvite 三处逐字
重复同一段收尾(handleSideEffects → printEvent → emit);再加一种需 pre-dispatch
富化的入站事件就得原样抄这三行,漏一行会静默丢日志或丢事件发射。抽 finishDispatch
收敛为一处。

- finishDispatch(event, alreadyRefreshed=false):默认 false 使 sync/group-invite
  两路的 finishDispatch(event) 等价于原 handleSideEffects(event);identity-refresh
  路透传 refreshed。与 CONTEXT 里已做的 reconcilePipeUp/Down 收敛同构。

行为严格不变:protocol 561 + core 467 全绿、typecheck 干净;对抗性 Agent 逐字对比
HEAD 确认三处等价、透传正确、三条路径均有测试覆盖。
2026-07-01 18:43:20 +08:00
DrSmoothl
85ca207279 refactor(onebot): extract openSqliteDb helper for the three stores
message/media/reaction store 构造器各自逐字复制同一段引导(mkdir 父目录 + 打开
DatabaseSync + PRAGMA journal_mode=WAL + PRAGMA synchronous=NORMAL),改一处 PRAGMA
要改三处。抽 openSqliteDb(dbPath) 收敛,schema init 与路径改写留在各调用方。

- message-store 的 .json→.db 改写保留(改写后同目录,mkdir 目标不变,等价)。
- 三文件删掉不再使用的 fs/path import。

行为严格不变:onebot 516 全绿、typecheck 干净;对抗性 Agent 逐字对比 HEAD 确认
三处引导等价、路径细节无边角、无回归。
2026-07-01 18:37:42 +08:00
DrSmoothl
d89b095af5 refactor(protocol,proto-defs): fold 1:1 subpath exports into wildcards
protocol/package.json 有 273 行专给 91 个 oidb-service(每个 3 行 1:1);加一个
service 忘改 package.json → build 期解析失败。把所有严格 1:1 的目录组折叠成通配符
(moduleResolution:"bundler" 原生支持),消除永久手同步负担。

- protocol:./oidb-services/*(91) + ./highway/*(7) + ./web/*(7) + ./msg-push/*(3);
  bare ./msg-push / ./highway(exact)与单文件 export 原样保留。
- proto-defs:./oidb-actions/*(10)。
- 净 -467/+15 行;两包均 private:true,通配新暴露的少量内部文件无害(exports 只
  gate 跨包解析、无外部消费者、无副作用)。

零源码/import 改动。全套工具链验证:12 包 typecheck Done、protocol/onebot(516)/
core(467)/mcp(22) 测试全绿;对抗性 Agent 端到端解析 136 个真实深导入全部命中、
确认 exact/wildcard 共存正确。
2026-07-01 18:30:45 +08:00
DrSmoothl
15a6fe3785 refactor(onebot): make event converter dispatch an exhaustive registry
阶段 2(零行为改动):把 convertEvent 的 17-arm switch 换成
CONVERTERS: { [K in QQEventVariant['kind']]: ConverterFor<K> | null } 表。mapped
type 对事件类型联合 total——新增一个 kind 却漏写 converter 会**编译报错**,而非
像原 switch 那样静默走 default: return null。

- ptt_trans_result(内部语音转文字事件,不对外)在表里显式标 null,与原 default
  行为等价。
- 派发一次 localized cast 解 correlated-union,纯类型层、运行时等价。
- 护栏实测有效:删任一 kind 条目即 TS2741 编译失败。

onebot 516 全绿、typecheck 干净;对抗性 Agent 逐一核对 17 映射、独立复现护栏报错。
2026-07-01 18:03:02 +08:00
DrSmoothl
ae17bc0cf5 refactor(onebot): extract event envelope builders; collapse message triplets
阶段 1(零行为改动):消掉 17 个 converter 各手搓的 time/self_id/post_type 信封,
合并 message 三胞胎。

- 新增 event-converter/envelope.ts:notice/request/message 三个信封 builder,
  converter 只供应各自 post_type 的字段。
- to-notice(12)/to-request(2) 改用 notice()/request()。
- to-message:friend+temp 合成 convertPrivateMessage(subType)(仅 sub_type 差),
  group 独立;新增 toSegments 收敛 7 参 elementsToJson splat。导出名不变。

行为 byte 级不变(测试 toEqual 顺序无关,key 集合与值逐一保持):event-converter
48 + onebot 全量 516 全绿、typecheck 干净;对抗性 Agent 逐 converter 对比 HEAD 确认
16 个输出等价、无字段增减/值变、无运行时循环。
2026-07-01 17:58:49 +08:00
DrSmoothl
891a197335 refactor(onebot): collapse action registration into a single barrel
加一个 action 文件原本要同步改三处手写清单:ApiHandler 的 12 个 register import +
12 行构造调用、各文件的 register footer、action-docs 的 13 import + GROUPS。现收敛
成一个 actions/index.ts barrel 作为「文件→动作 + 分类」的单一真相。

- action-kit:抽 RegisteredActionSpec(describe+register),ActionSpec/
  StreamActionSpec extends 它,registerActions 参数放宽到 RegisteredActionSpec[]
  (它只调 .register),于是 stream 动作也能并入统一注册。
- 新增 actions/index.ts:ACTION_GROUPS(11 组含分类,stream 合并)+ ALL_ACTIONS。
- api-handler:12 import+12 调用 → registerActions(this, context, ALL_ACTIONS);
  .handle_quick_operation(唯一非 ActionSpec 的裸 handler,需要 h 本身)从
  extended 搬进构造器一处显式注册。
- action-docs:改用 barrel 的 ACTION_GROUPS,删本地 GROUPS + 13 import。
- 删 12 个 register footer + 清理因此变 unused 的 ApiHandler/ApiActionContext import。

行为严格不变:注册的动作集合、.handle_quick_operation、文档分类/计数均一致。
onebot 516 全绿、全仓 12 包 typecheck Done;对抗性 Agent 逐条对比 HEAD 确认等价。
2026-07-01 17:49:07 +08:00
DrSmoothl
b6cde5101d refactor(common,core): extract mapWithConcurrency util; use in forward enrich
阶段 2:把「限量+并发分批」的手写循环收进一个 common util。此形状已被复制进
私有 SLE(friend.ts),是已发生的复制漂移;抽出后堵住它、并给未来的富化点一个
现成原语(cap + 并发批 + best-effort 是防 Tencent 风控封号的标准配方)。

- 新增 common/concurrency.ts:mapWithConcurrency(items, concurrency, fn),批处理
  语义(每批 Promise.all 等齐再下一批,非 rolling pool,保持 forward 现有行为),
  结果按输入顺序返回。7 个单测覆盖顺序/绝对index/峰值≤limit+跨批serialize/
  不整除/单批/空/concurrency<1。
- 迁移 forward.ts residue 昵称富化的并发批循环;cap(slice MAX)/dedup(Set)/
  best-effort(fn 内 try/catch) 保留在 callsite。行为严格不变。

对抗性 Agent 逐条对比 HEAD 确认等价。common 50 / core 467 全绿、typecheck 干净。
2026-07-01 17:29:25 +08:00
DrSmoothl
9d67630396 refactor(common,core): extract single-flight+TTL cache primitive
阶段 1:把手写多份的「单飞+TTL 记忆化」收进一个 common 原语,消除各处
各自实现「TTL 判定 / inflight 去重 / finally 清理」的漂移风险(底层都是 Tencent
风控:忙碌客户端会为每条消息发一次未缓存 OIDB 拉取,持续爆发触发封号)。

- 新增 common/single-flight-cache.ts:createSingleFlightCache<K,V>({ ttlMs, load,
  shouldCache?, now? }).get(key, {force});shouldCache 容纳「错误结果不缓存以便
  重试」,now 可注入便于测 TTL。7 个单测覆盖新鲜命中/单飞去重/force/TTL 过期/
  shouldCache/错误传播/invalidate。
- 迁移 contacts.fetchGroupMemberList(key=groupId, ttl 60s, 默认 shouldCache)与
  update-check.getUpdateInfo(全局 key, ttl 6h, shouldCache=!error)。行为严格不变。

对抗性 Agent 逐条对比 HEAD 确认两处等价(含 update-check 时间戳来源毫秒级微差、
对 6h TTL 可忽略)。common 43 / core 467 全绿、typecheck 干净。
2026-07-01 17:25:04 +08:00
DrSmoothl
6f6f372337 refactor(onebot): drop 55 redundant ACTION_FAILED try/catch in extended actions
阶段 2b:从 extended.ts 删除 55 个「纯兜底」try/catch(catch 体恰为单条
return failedResponse(ACTION_FAILED, String(e)/e.message)),让抛错落到唯一 seam
runAction(已统一 100 + error.message)。retcode 不变(这些本就是 100),去的是
冗余包装。

- 保留:try/finally、带前缀的 catch(获取精华消息失败 / 语音转码失败)、
  download_file 保存失败的 BAD_REQUEST catch、fetchFilteredGroupRequests 的
  catch{return []} 吞值——均原样未动。
- 唯一文案变化:约 30 个原用 String(e) 的 catch,其 wording 由 "Error: X" 变为
  seam 的裸 "X"(丢类名前缀,retcode 不变;OidbError 的服务器码仍在 message 内)
  ——一致化改善,无测试/契约依赖该前缀。
- onebot 全量 516 全绿、typecheck 干净;对抗性 Agent 逐块比对 HEAD 确认等价、
  结构正确、无误删漏改。
2026-07-01 16:30:00 +08:00
DrSmoothl
5be852f394 refactor(onebot): drop redundant per-action try/catch in qzone/album/admin
阶段 2a:删除 qzone(7)、group-album(8)、group-admin(1) 共 16 个「纯兜底再包一层」
的 try/catch,让抛错自然落到唯一 seam runAction(阶段 1 已统一为 ACTION_FAILED 100
+ error.message)。qzone/album 原返回 1200 → 归一 100(本任务有意);group-admin
原本就是 100,仅去冗余包装。

- 保留:qzone helper uploadQzoneImages 的带前缀 re-throw catch、group-info 的
  honor-info 前缀 catch、message 的吞值 catch(best-effort 保留旧 URL)——均未动。
- 清理三文件不再使用的 RETCODE/failedResponse import。
- qzone-actions 测试断言 1200 → 100(wording 前缀经 seam 仍保留)。
- onebot 全量 516 全绿、typecheck 干净;对抗性 Agent 逐个对比 HEAD 确认纯兜底、
  无其它漂移、无误删漏改。
2026-07-01 16:20:26 +08:00
DrSmoothl
ab45667fdf refactor(onebot): unify action-error retcode at the runAction seam
将「动作抛错返回什么错误码」从各处不一致(100 / 1200 / 漏包→1200)收敛到唯一
兜底处 ApiHandler.runAction,统一为 ACTION_FAILED(100) + error.message。

阶段 1(改 seam 本身):
- runAction catch:默认码 1200 → 100;文案 'internal error' 兜底改为 String(error)。
  OidbError.message 本就含 QQ 服务端 code,无需特判。
- 新增 3 个测试锁定策略:抛 Error→100+message;抛 OidbError→100 且 wording 含
  code+server msg;抛非 Error→100+String()。
- rename_group_file 那个原断言 1200 的测试(未包裹动作、落 runAction)改为 100。

各 action 里多余的 try/catch(qzone/group-album 等仍返回 1200)留待后续阶段删除,
在此之前其失败不经此 seam。onebot 全量 516 全绿、typecheck 干净。
2026-07-01 16:11:49 +08:00
DrSmoothl
ab40f086ee refactor(protocol): dedup NTV2 record/video mediaNode builder in decoder
阶段 3(零行为改动):record(bizType 12/22) 与 video(bizType 11/21) 解码分支里
各写一份、逐字完全相同的 23 行 `mediaNode:{ fileUuid,storeId,uploadTime,ttl,
subType,info:{…} }` 块,抽成共享 helper buildMediaNode(idx, fi),消除这对并行拷贝
的漂移风险(改一处忘另一处)。

- VideoFile / Ptt 两处的 mediaNode 来源变量与 shape 不同,正确保持独立、未误并。
- 逐字提取,行为 byte 级不变:typecheck 干净、protocol 全量 561 全绿;对抗性
  Agent byte-diff 确认原两份完全相同、helper body 与之逐字一致。

注:计划中的 poke faceId→subType 字段对齐已主动撤销——poke 不能当消息段发送,
且自身消息回显路径会读 element.subType 使该改动可观测,违反"重构行为不变"。
2026-07-01 15:56:43 +08:00
DrSmoothl
8e173cf7d7 refactor(onebot): merge element toSegment/fromSegment into one codec table
阶段 2(零行为改动):把「同一种消息元素」的两个 onebot 方向——收·转
(to-segment) 与 发·解(message-parser)——从两个文件各写各的分支,合并到一张
按元素类型索引的 ELEMENT_CODECS 表,每种类型一条 { toSegment?, fromSegment? }。

- 新增 event-converter/element-codecs.ts:13 类 toSegment + 14 类 fromSegment
  逐字平移自原实现;私有 helper intOr/marketFaceElement/pickMediaSource 移来并导出。
- to-segment.ts:elementToSegment 改查表 + 保留原 default 透传兜底。
- message-parser.ts:segmentToElement 保留 9 个纯输入糖 case 作前置 normalize,
  真实类型改查表,末尾保留原 unsupported warn。
- onebot 对账测试升级为按表键核对 S/P(比正则更硬),并断言真实类型 case 不再
  残留于 parser、输入糖仍在。

行为 byte 级不变:onebot 全量 513 全绿、typecheck 干净;对抗性 Agent 逐字比对
确认无漂移、无运行时循环依赖。
2026-07-01 15:48:04 +08:00
DrSmoothl
f4170b014a refactor(protocol,onebot): add message-element four-direction reconciliation manifest
消息元素散在 4 处派发(收·解 / 收·转 / 发·解 / 发·打包),历史上各写各的、
无对账,导致字段名对不上、漏写方向走 default 静默失败。

阶段 1(零行为改动):立一份权威清单 element-manifest + 两道架构护栏测试。
- element-manifest.ts:每种元素类型 × 四向支持('yes'/'no'/'by-design-no')
  + 字段契约 + typesForDirection() + 输入糖白名单。清单逐字反映当前行为。
- 两道对账测试(因包边界拆两处、共用清单):正则扫 4 处派发代码,比对清单。
  谁增删一个方向却不同步清单,测试当场报红,不再运行时静默。
- 取值域用 [A-Za-z0-9_]+,避免未来驼峰/下划线类型名被静默漏抓致护栏失效。
- poke 的 W=by-design-no:QQ 不允许戳一戳当消息段发送,缺席正确。

对抗性 Agent 两轮复审通过。
2026-07-01 15:48:04 +08:00
囧囧JOJO
f424454422 fix(webui): align debug account picker styling (#181) 2026-07-01 14:43:29 +08:00
DrSmoothl
5d6ce86b66 refactor(onebot): give trans_group_file semantic param roles
Follow-up to #161: trans_group_file's group_id/file_id used plain
f.uint()/f.string(); switch them to f.groupId()/f.fileId() (identical
coercion) so the WebUI debug console renders a group picker + file-id
control for the new action and the catalog carries the roles. Catalog
regenerated.
2026-07-01 02:27:35 +08:00
Airline233
9ca64bed10 feat(core,onebot): implement trans_group_file action (#161) 2026-07-01 02:13:35 +08:00
Airline233
2f374ea8c9 feat(qzone): support post visibility rights when publishing qzone posts (#178)
Add ugc_right and target_uins to the qzone publish path across protocol,
bridge, and the send_qzone_msg OneBot action, regenerate the MCP catalog,
and cover restricted visibility (16/128) with validation tests.
2026-06-30 23:57:39 +08:00
DrSmoothl
c90a3954e4 fix(bridge): self-heal login detection when the hook misses the edge
Docker SnowLuma could hang forever at "等待登录" after QQ had already
logged in. Root cause: login detection is edge-triggered — it only learns
the state from a loginState frame the native hook PUSHES when it observes
the login transition. `getLoginState()` is a cached value read once at
connect; after that the session waits passively. Desktop attaches the
hook before the user logs in, so it catches the edge. In Docker, QQ
auto-logs-in from a persisted session — fast on startup — so the
transition lands before the recv pipe is connected (frames aren't
replayed) or via a silent restore path the hook doesn't intercept. The
edge is missed and the cached state stays not-logged-in.

Fix: while connected but not logged in, actively re-probe QQ's own
ptlogin/deeplink ports via probeQqLoginInfo (level-triggered, pipe-
independent — the same call the workaround used) and synthesize the login
once it reports a real uin. Immediate probe on connect + a 3s interval;
stopped on login / teardown / dispose, with an in-flight guard so a slow
port scan can't stack concurrent probes. Idempotent with the pushed-frame
path. 7 tests cover detect-via-probe, the later-interval case, the
not-logged-in / non-real-uin / throwing-probe guards, no double-emit, and
no concurrent stacking. probeLogin is injectable for tests.
2026-06-30 23:29:51 +08:00
DrSmoothl
397087dc74 test(core): hoist Bridge import to fix flaky 5s timeout
bridge-private-routing.test.ts loaded the Bridge dependency tree via
`await import(...)` INSIDE each `it`, so the first test paid the whole
~3.8s module-eval cost against its 5000ms per-test budget — fine locally
but tipping over on slower CI runners (surfaced as a timeout on an
unrelated PR). Moved the Bridge / IdentityService imports to top-level
statics (vi.mock is hoisted above them, so element-builder stays mocked):
the heavy load now happens once at file collection, not against a test
timeout. Per-test execution dropped from ~3.8s to ~7ms.
2026-06-30 23:09:21 +08:00
snowluma-bot[bot]
b807825a09 Merge pull request #175 from SnowLuma/dev
chore: promote dev → main (48e2777)
2026-06-30 12:39:05 +00:00
DrSmoothl
48e2777bc3 chore(release): v1.11.0 2026-06-30 20:38:37 +08:00
DrSmoothl
a8307891fa fix(core): backfill forward-msg sender nickname/card (#174)
get_forward_msg nodes came back with empty or "QQ用户" sender names: the
SsoRecvLongMsg payload doesn't always populate the member name, and the
sync decode only consulted the L1 identity cache. So a sender absent from
that cache (just-started bot, inactive member) had no name.

ForwardApi.enrichSenders() now backfills nameless nodes on both fetch
paths (wire + cache-hit, with write-back so seeded inner caches enrich on
first read):
- L3: one fetchGroupMemberList per distinct group (inflight+TTL cached)
  resolves every in-group sender at once; card preferred over nickname,
  matching the existing wire-decode convention.
- L4: per-uin fetchUserProfile only for the residue (members who left the
  group, private nodes).

Best-effort: a failed lookup keeps the placeholder, never failing fetch.

Adversarially reviewed — fixed the one High it found: the L4 fallback was
an unbounded Promise.all of un-cached OIDB 0xFE1_2 lookups, which a
high-churn group's historical forward (many since-left senders) or a
flaky member-list call could amplify into a rate-limit ban (the very risk
ContactsApi's own cache note warns about). Now: member-list failure keeps
the placeholder instead of fanning out, and the residue is capped
(FORWARD_PROFILE_MAX) and resolved in small concurrency-limited batches.
2026-06-30 20:32:49 +08:00
DrSmoothl
b6c476390f ci: auto-close non-template issues from non-write-access users
blank_issues_enabled: false only hides the chooser link — the CLI / API /
direct URLs still create template-less issues (e.g. #174 by a CONTRIBUTOR).
This workflow enforces the policy: an issue opened by someone without write
access that carries no template label (bug / enhancement) is commented on and
closed as not-planned. Proper bug reports / feature requests and write-access
users are unaffected.

Takes effect only once on the default branch (main).
2026-06-30 20:16:59 +08:00
DrSmoothl
fc4d3a9c5d fix(protocol): set_group_name body tag 3, not 1 (#173, OIDB 1006)
set_group_name (OIDB 0x89a_15) always failed with OIDB error 1006 even
with admin rights. The group name in the body sits at tag 3, but we had
it at tag 1 — so the server rejected the malformed request structure
before ever checking permission. Confirmed against Lagrange's
OidbSvcTrpcTcp0x89A_15Body (ProtoMember(3) TargetName).

The reporter had tried tag 1 and tag 2 (both still 1006) — the answer was
tag 3. Live-verified on tempserver: with the fix the error changes from
1006 (structure rejected) to 1328 (permission — the test bot is only a
member), proving the request structure is now accepted; an admin bot will
succeed.
2026-06-30 20:14:20 +08:00
DrSmoothl
1f23e6e9f0 fix(protocol): ptt-trans md5 must be a hex string, not raw bytes (#165)
fetch_ptt_text failed for every voice with QQ errCode -1079 ("ptt
translate failed"). RE'd the cause in wrapper.linux.node: EncodeTroopPtt /
EncodeC2CPtt (ptt_trans_worker.cc) run the md5 through a bytes→hex helper
(sub_7A02D80, the 000102…ff table) before putting it in the request — so
the md5 field is a 32-char lowercase HEX STRING, but we were sending the
raw 16 bytes (hexToBytes(md5Hex)). Wrong length + encoding → server reject.

All other fields matched QQ NT exactly (verified field-by-field against
the two encoders): group {1=msg,2=sender,3=group,4=fileId,5=md5,6=dur,
7=size,8=format,9=uuid,10=event}, c2c {…,9=md5}, type 1=group/2=c2c.

Fix: md5 field is `string` (the lowercased hex), not `bytes`. Live-
verified on tempserver — errCode -1079 is gone and a real voice now
returns ASR text. (The "Live-verified end to end" claim in the old
comment was wrong; c2c had the same latent bug.)
2026-06-30 20:02:07 +08:00
DrSmoothl
0cf9cdd0d7 chore(core): diagnose ptt translate failures (#165 备选)
When QQ's ASR returns a non-zero errCode, log the request fields we
sourced from cache (md5 length / format / uuid presence / duration /
size) alongside the errCode, so a server-side ASR failure can be told
apart from our own missing/zero field. Behaviour unchanged — still
throws. Helps diagnose the "ptt translate failed" instability reported
in #165 before deciding whether it's our bug.
2026-06-30 19:31:20 +08:00
DrSmoothl
90456def2e feat(onebot): get_record out_format — server-side voice transcode (#165)
#165: get_record gains an optional `out_format` (mp3/amr/wma/m4a/spx/ogg/
wav/flac, mirroring NapCat). When set, the QQ voice (SILK/AMR) is
transcoded server-side and the result is attached as `data.base64`; the
original info (file/url/file_size) is preserved. Absent ⇒ behaviour
unchanged. This spares ASR consumers from shipping a SILK decoder.

- protocol: convertAudioBytes(bytes, format, deps?) drives the bundled
  SILK-capable ffmpeg addon's convertFile through temp files (always
  cleaned up), with a format allowlist and an output-size cap. Pure/
  injectable, unit-tested with a fake addon (6 cases).
- core: ExtrasApi.convertRecord(source, format) = loadBinarySource (64 MiB
  cap) → convertAudioBytes.
- onebot: get_record wires out_format; transcode failure (incl. an addon
  lacking SILK decode) degrades to ACTION_FAILED, never crashes.

Adversarially reviewed: no path traversal (format allowlisted), no SSRF
(source is the cached CDN url, not user input), cleanup covers every path,
graceful degradation confirmed. Catalog regenerated. Real-machine e2e
(does the shipped .node actually decode SILK?) is Phase 2.
2026-06-30 19:25:40 +08:00
DrSmoothl
8fc5917b3b fix(webui): align message composer/builder (Apple-HIG)
Two alignment fixes in the 消息构建 tab:
- MessageBuilder is now a bounded "compose canvas" (always bordered) so the
  empty hint reads as an intentional empty state inside a defined input
  region, instead of a stray centered line floating in the left-aligned
  form.
- The 账号 / 目标 label rows are pinned to a fixed h-8 (== the 群聊/私聊
  segmented control's height) so both labels and the selectors beneath them
  share a baseline — min-h-7 wasn't enough since the segmented is ~32px.
2026-06-30 18:57:54 +08:00
DrSmoothl
65195abbe0 fix(mcp): add role/stream to Catalog types to match generated catalog
Phase 0 added `role` to FieldDoc and `stream` to ActionDoc and regenerated
catalog.ts, but the mcp package's own CatalogParam/CatalogAction types
(intentionally decoupled from onebot per ADR-0005) weren't updated — so
`tsc --noEmit` failed on the generated catalog.ts (TS2353, unknown
properties role/stream). The mcp vitest suite passed because esbuild
doesn't type-check the generated snapshot, which is why this slipped.

CatalogParam gains role?: string (loose, to stay decoupled from onebot's
FieldRole union); CatalogAction gains stream?: boolean. `pnpm typecheck`
is green across all packages.
2026-06-30 18:45:34 +08:00
DrSmoothl
d5fbd6fa06 feat(webui): multi-tab debug console + embedded API browser
Phase 6 of the debug-console expansion — the four pieces become one
console: 测试台 / 消息构建 / 实时活动 / API 浏览器, behind an Apple-HIG
sliding-indicator tab bar.

- ApiBrowser: a searchable, category-grouped reference for every
  declarative action (~520), straight from /api/debug/actions — params /
  returns / invariants / role + readOnly + stream badges. Each row's 试一下
  prefills the tester and switches to it (ActionTester gains a
  presetAction prop keyed by nonce).
- Tester / compose / activity stay MOUNTED and toggle via CSS, so the
  live feed's SSE never drops — it keeps capturing events fired while you
  invoke from the tester tab (the invoke-then-observe loop) — and
  in-progress params/messages survive a peek at another tab. The API
  browser, heavy and stateless, mounts on demand.

Adversarially reviewed: no crash / leak / mis-trigger; the review caught
that conditional-mounting silently dropped cross-tab live events and
discarded in-progress work — fixed by keeping the stateful panels mounted.
2026-06-30 17:40:04 +08:00
DrSmoothl
383ddb0a5d feat(webui): visual message builder + composer (nested forward)
Phase 5 of the debug-console expansion. A drag-reorderable segment
builder so you never hand-write a OneBot message array: common segments
first-class (text / @ / image / face / reply / record / video), advanced
folded (file / mface / poke / json / xml / markdown / forward-node), with
`node` nesting a full builder (merged forward, depth-capped). @ uses the
group member picker via the sibling group context; media via FileSource.
Each segment carries a stable `_id` key so editing a field never remounts
the row.

- MessageBuilder + toOneBot() serialise to the exact OneBot v11 shapes
  SnowLuma's parser reads (verified field-by-field).
- MessageComposer (the 消息构建 tab): pick target, build, preview, send —
  routing through send_*_forward_msg when the message has nodes, else
  send_*_msg. Refuses a mixed node/non-node forward (the backend would
  silently drop the stray segments) and validates incomplete segments
  before sending.
- ParamField renders the builder for message-type params in the tester
  (raw-text escape hatch kept), emitting the serialized array as the
  string value.

Adversarially reviewed: serialization contract and React key/focus both
verified clean (no _id leakage); fixed the mixed-forward silent-drop,
added pre-send segment validation, and made the drag boundary explicit.
2026-06-30 17:31:51 +08:00
DrSmoothl
11866caa2f feat(webui): role-driven action tester with streaming + history
Phase 4 of the debug-console expansion — the tester no longer makes you
hand-write JSON. Each param renders the right smart control from its
semantic role: group/friend/member pickers (member linked to the sibling
group_id), FileSource for media, FaceGrid, datetime for timestamps,
switch for bool, select for enum — with the raw-JSON escape hatch kept.

- Read-only actions badge green, side-effecting amber; a name-pattern set
  of destructive actions (kick/ban/recall/delete/…) confirms first.
- Stream API actions invoke over /api/debug/invoke-stream and render
  frames live, tracked in the app-level task registry with progress; a
  clean success requires the terminal response frame, and a failed frame
  shows its reason (not just the {type:'error'} marker).
- Every call lands in capped localStorage history with one-click replay;
  responses render in a collapsible JsonTree.
- Extracted LiveActivity (filter / search / export) and the Segmented
  control into their own components; debug-page is now a thin host.

Adversarially reviewed: stream terminal-frame judging, member/group
linkage, and contract shapes verified; fixed the failed-stream-frame
reason being hidden, a latent required-enum controlled-select trap, stale
member value on group change, and several low UX edges.
2026-06-30 17:17:15 +08:00
DrSmoothl
c5611ed622 feat(webui): debug-console shared primitives, data layer, task manager
Phase 3 of the debug-console expansion — the Apple-HIG foundation the
new tabs build on (reusing the existing ui kit; new controls match its
idiom, no browser-native widgets).

API client + types:
- debug.invokeStream() reads /api/debug/invoke-stream via fetch + a body
  reader, parsing data:<json> SSE frames (header auth, cancellable).
- debug.upload() streams a file via XHR for real upload progress.
- DebugActionParam.role, DebugActionDoc.stream/invariants, FieldRole,
  DebugStreamFrame, DebugUploadResult.

Primitives:
- Tabs (sliding indicator + roving tabindex), Picker (searchable,
  windowed combobox with a raw-value escape hatch), JsonTree (collapsible
  response viewer, image-url preview, copy w/ http fallback, node cap),
  FileSource (URL / server-path / browser-upload tri-state), FaceGrid.

Infra:
- DebugTaskProvider + TaskBadge: app-level registry of in-flight upload/
  stream tasks so they survive in-app tab switches, with a global
  progress chip and a beforeunload guard; eviction never drops a running
  task. Wired into App.
- use-debug-contacts: lazy friend/group/member data layer, shared module
  cache + localStorage (version-stamped, avatars stripped to dodge quota)
  + TTL + request-id race guard, degrading to raw input on error.

Adversarially reviewed (no automated component tests): virtualization
math and SSE framing verified correct; fixed the stale-contacts-on-switch
member-selection hazard, the quota-kills-persistence issue, and several
low UX edges (active-row clamp, filter scroll reset, copy fallback).
2026-06-30 16:53:43 +08:00
DrSmoothl
a7667f1cd5 feat(core,onebot): debug-console stream-invoke + upload endpoints
Phase 2 of the debug-console expansion. Two backend endpoints under the
existing /api/* bearer auth:

- POST /api/debug/invoke-stream — drive a Stream API action (#163) and
  relay every frame to the browser over an SSE body. The frontend reads
  it with fetch()+a stream reader (header auth), so it needs no SSE
  query-token allowlist entry. Frames are NEVER dropped: backpressure is
  handled by waiting for the consumer to drain, not by discarding (a lost
  chunk corrupts a transfer). Non-stream actions emit a single frame.
- POST /api/debug/upload — stream a browser-selected file to a temp path
  on THIS server (the bot runs server-side, not on the operator's
  machine), so the path can feed a send action's file/image/record/video
  param. Raw bytes in the body (no multipart buffering), ?filename= for a
  readable suffix, streamed to disk under os.tmpdir()/snowluma-debug-
  upload with a 4 GiB cap and a 24h TTL sweep.

instance.invokeStream() delegates to ApiHandler.processStreamRequest.

Pure logic (filename sanitisation, fenced size-capped disk sink, the
stream-invoke Response builder) lives in debug-tools.ts with 12 unit
tests. Adversarially reviewed: path traversal is robust (19 hostile
filenames all fenced), frames provably never dropped, auth runs before
any disk write. Fixed a High found in review — the write stream had no
'error' listener (an async ENOSPC/EIO during flush would crash the whole
process) and a late-open race could leak a partial file; both now raced
into the awaits and cleaned up after 'close'.
2026-06-30 16:19:59 +08:00
DrSmoothl
c839121fdb fix(protocol): send super/new faces with the right wire encoding (#168)
A face was always built as a legacy FaceElem (face.index). QQ-NT only renders
classic small faces that way; newer 'super'/animated faces sent as face.index
are silently remapped by the server (e.g. 424→168) or shown as a placeholder.

Classify each face id off QQ's own system-face catalog (0x9154_1, ported from
SLE/Lagrange) and pick the matching wire form:
  - super (animated, aniSticker pack ≠ (1,1)) → CommonElem 37 + QFaceExtra
  - other id ≥ 260                            → CommonElem 33 + QSmallFaceExtra
  - classic id < 260                          → legacy FaceElem

The catalog is fetched once (shared, lazy-warmed off the first face send) and
classify falls back to an id-range guess until it lands. Data-driven so all 66
non-(1,1) super faces encode correctly, not just a hardcoded few.

Verified on a live account: 424→424 (was 168), super 392→392, classic 14→14.
2026-06-30 16:09:28 +08:00
DrSmoothl
f9900053b0 feat(onebot): backfill semantic roles across action params
Phase 1 of the debug-console expansion. Sweeps the 8 action files,
swapping bare coercion primitives for the role-stamped equivalents from
Phase 0 (or appending `.role()` where a `.default()`/`.optional()` field
must keep its exact coercion). Coercion is byte-for-byte unchanged; the
only intentional bound change is face_id min 1→0 (QQ face 0 is valid).

Classification (verified against each run()):
- group_id → f.groupId() everywhere.
- user_id → f.userId() for any-user / friend / stranger / private-route
  targets (send_private, friend poke, friend add/remove, stranger info,
  private file transfer, forward-to-friend, share-contact).
- user_id → f.memberId() only when it's a member of a sibling group_id
  (batch kick elements; the groupUserAction preset already injects it).
- media file/image/record + file_id → f.file()/image()/record()/fileId()
  (or .role() when defaulted/optional); message_id/timestamp/duration via
  the constructor or .role() hatch as coercion requires.

Polymorphic ids left as bare uint on purpose (no single role can honestly
describe them): mark_msg_as_read.target_id (group# or uin), bot_appid,
msg_seq, fileset_id, folder_id, chunk indices, stream_id.

Catalog regenerated: 71 group_id / 25 user_id / 9 member_id / 19
message_id / 11 file_id / 7 image / 6 file roles surfaced. Done by 4
parallel agents; adversarially reviewed — zero coercion regressions,
zero member/user misclassifications.
2026-06-30 16:00:21 +08:00
DrSmoothl
14a61f4ce8 feat(onebot): add semantic role field + stream flag to action metadata
Phase 0 of the debug-console expansion. Introduces a closed `FieldRole`
union (group_id/user_id/member_id/message_id/file_id/file/image/record/
video/duration/timestamp/face_id) orthogonal to `type` (which governs
coercion), so the WebUI debug console can render semantic pickers instead
of forcing hand-written JSON.

- FieldDoc gains `role?`; Field gains a `.role()` modifier (survives
  optional/default/describe). toJsonSchema emits it as `x-role`.
- Semantic constructors f.groupId/userId/memberId/fileId/file/image/
  record/video/duration/timestamp/faceId wrap the coercion primitives and
  stamp a role (messageId backfilled). Media sources reject '' to preserve
  the empty-string guard they replace. faceId allows 0 (valid QQ face id).
- Extracted stringCore so f.string() and string-valued roles share it.
- ActionDoc gains `stream?`; defineStreamAction sets stream:true.
- Presets: groupAction injects f.groupId(); groupUserAction injects
  f.groupId() + f.memberId() (a group action's user_id is a member of
  that group). Backfills role onto 56 group_id / 7 member_id sites.
- Regenerated MCP catalog (79 x-role, 5 stream).

Adversarially reviewed: no coercion regression, member_id stamping has
zero false positives across all 7 groupUserAction sites, x-role is inert
to MCP consumers.
2026-06-30 15:42:25 +08:00
DrSmoothl
7285db1e37 feat(onebot,mcp): catalog the Stream API actions (#163 phase 4)
Surface the six Stream API actions in the self-generated docs catalog under
a new 流式接口 category: export each module's specs as an `actions` array
(register now iterates it) and widen the doc collector's spec type to anything
carrying describe() so defineStreamAction results qualify alongside
defineAction. Regenerated the MCP catalog snapshot.

End-to-end verified on a live account over HTTP: test_download_stream (10
frames + terminal), an upload_file_stream round-trip (200 KB chunked in →
sent as a c2c file → download_file_stream back out, byte- and sha256-exact),
and the SSRF guard rejecting a cloud-metadata URL.
2026-06-30 14:40:39 +08:00
DrSmoothl
369dea582c feat(onebot): download stream actions (#163 phase 3)
NapCat-compatible server-push download: one request answered by a file_info
header, N base64 file_chunk frames, then a terminal file_complete. Bytes come
from a local file under the stream temp root, an http(s) URL, or a cached
image/voice id resolved to its QQ CDN URL. test_download_stream pushes 10
canned frames so a client can validate the transport without touching QQ.

Actions: download_file_stream / download_file_image_stream /
download_file_record_stream / test_download_stream.

Hardened beyond the NapCat original (which streams any local path and follows
redirects to anywhere), per three adversarial review passes:
- arbitrary-file-read: local reads are fenced inside the stream temp root,
  realpath-resolved so a symlink can't point out.
- SSRF: every URL (incl. each redirect hop, followed manually) is guarded —
  http(s) only, and neither the literal host nor any resolved address may be
  private/loopback/link-local; IPv6 is byte-parsed so normalized v4-mapped
  literals (::ffff:a9fe:a9fe) can't slip past. (DNS rebinding remains a
  documented residual — needs connect-time peer-IP validation.)
- robustness: TTFB-only connect timeout (doesn't cut a large body mid-stream)
  plus a per-chunk idle watchdog that aborts a stalled source so a hung
  upstream can't pin a socket; total size capped; non-2xx bodies cancelled;
  client disconnect aborts via the sink.

501 onebot tests green.
2026-06-30 14:40:39 +08:00
DrSmoothl
4f0a0f89ae feat(onebot): upload_file_stream + clean_stream_temp_file (#163 phase 2)
NapCat-compatible chunked upload: a client pushes a file in base64 chunks
across repeated upload_file_stream calls keyed by stream_id; the bot
reassembles them into a local temp file and returns its path for a normal
send. Sidesteps the 2 MB HTTP body cap and the shared-filesystem assumption
of file:// sends.

Reassembly streams chunk-by-chunk to disk (no whole-file Buffer.concat) so
an arbitrarily large upload won't OOM. clean_stream_temp_file wipes only the
stream temp dirs.

Hardened well past the NapCat original (which has all of these holes), per
two adversarial review passes:
- stream_id is allowlist-validated + every derived path fenced inside the
  upload dir — no path traversal (the original lets stream_id write/delete
  arbitrary paths).
- total_chunks / concurrent streams / per-chunk + per-stream bytes are all
  bounded — no single-request OOM or disk/fd exhaustion.
- chunk indices are claimed synchronously and only counted complete once
  flushed — no double-count race, no truncated-read-on-concurrent-complete.
- state + temp dirs are namespaced per account.

494 onebot tests green.
2026-06-30 14:40:39 +08:00
DrSmoothl
01ef98abb6 feat(onebot): Stream API transport plumbing (#163 phase 1)
Foundation for NapCat-compatible Stream API actions (chunked file
upload/download): a single request answered by many response frames.

- streaming.ts: StreamSink + frame wrappers (wrapStreamFrame /
  wrapStreamTerminal) matching NapCat's wire — each frame an OB11 envelope
  with stream:'stream-action', data.type ∈ stream/response/error, and
  message mirrored into wording.
- ApiHandler: registerStreamAction / isStreamAction; handle() threads a
  sink; processStreamRequest drives WS multi-frame dispatch with optional
  liveness-based abort; dead processRequest removed.
- action-kit: defineStreamAction (sink-aware run, registers as a stream
  action) reusing defineAction's parse/describe.
- adapters: HTTP server streams chunked \r\n\r\n-delimited frames (no
  Content-Length, no false application/json), aborting on client
  disconnect; WS server/client use a backpressure-aware safeSendAsync and
  abort a stream once the socket closes.

No stream actions are registered yet — those land in the next phases.
Verified by two adversarial review passes. 480 onebot tests green.
2026-06-30 14:40:39 +08:00
Airline233
62eb8fd763 feat: Qzone支持上传图片(发说说、评论附图) (#152)
* feat(core,onebot,protocol): support publish shuoshuo and comment with image

* Fix: Accidentally changed notes
2026-06-30 01:47:21 +08:00
DrSmoothl
547640bbfd fix(onebot): route oversized videos to the file path up front (#145)
A video larger than MAX_VIDEO_SIZE (~100 MB, QQ's video-resource cap)
uploads "successfully" — the server accepts the Highway bytes — but the
receiver sees 视频已过期 because no valid video resource is ever produced.

The existing large-video → file fallback only fired from the send catch
block, i.e. when the upload threw. An oversized upload doesn't throw, so
the fallback never triggered. Add a proactive split before the send: any
video whose source size is known to exceed MAX_VIDEO_SIZE is re-routed to
the file pipeline up front (mirrored for private and group sends). Smaller
videos (verified up to ~49 MB) are unaffected and still send as videos.

This pairs with the c2c-file fix (f8caa92): the re-routed video now rides
the now-working offline-file path and downloads correctly.
2026-06-30 01:24:00 +08:00
DrSmoothl
f8caa92333 fix(core): make c2c files >5MiB downloadable — drop stale busId, fix md5-head magic
Private (c2c) files larger than a few MiB uploaded fine but the receiver
always got "download failed" (#157). Two independent bugs in the offline-
file upload (OidbSvcTrpcTcp.0xe37 + highway cmdId 95), both confirmed on a
live account and against a plaintext packet capture of the real QQ client:

1. FileUploadExt.busiBuff carried a stale `busId: 102`. NapCat, Lagrange and
   the QQ client all emit busiBuff with senderUin only. The extra busId let
   the server accept the highway upload but never finalise it as a
   downloadable offline file once the payload passed ~5 MiB.

2. md510MCheckSum used `10 * 1024 * 1024` (10485760) as the "first 10 MB"
   limit. QQ's magic number is 0x98A000 = 10002432. With the wrong limit the
   server's first-block verification failed for any file larger than
   0x98A000, so files >~10 MB uploaded but never finalised either.

With both fixed, c2c files of arbitrary size (verified up to ~20 MB; the
general highway path has no inherent size cap) download correctly.
2026-06-30 00:13:34 +08:00
DrSmoothl
57ff0e69d8 fix(core): make c2c file 0xE37_800 finalize best-effort, not fatal (#157)
Real-machine retest showed a plain c2c file send (NotOnlineFile only, no
field6) is already downloadable — the original #157 'fix' made the 0xE37_800
finalize a hard dependency, so any finalize error would now fail a send that
would otherwise succeed (a regression, same speculative-NapCat-parity trap as
the #145 force-full).

Wrap the finalize in try/catch: on success we still attach field6 (extra
download routing that mirrors NapCat and may help some receiver clients); on
failure we log and send without it. field6 is now enrichment, not a
requirement.

Adds a regression test: a failing 0xE37_800 still produces a PbSendMsg with
the file and no field6.
2026-06-29 16:08:20 +08:00
DrSmoothl
053137669a fix(protocol): drop the ineffective video force-full-on-fast-path retry (#145)
forceFullOnFastPath re-issued the NTV2 upload with tryFastUploadCompleted:
false to try to refresh a possibly-expired video resource. Real-machine
testing on a live account + RE of the QQ NT kernel (wrapper.node) proved it
never works:
- the server's fast-path is driven by md5-metadata existence and ignores
  the flag (proton omits a false bool anyway); the retry re-fast-paths
- the kernel itself does no validity check — HandleRspUploadV3 trusts the
  response's fileExist and goes straight to SendUploadSuccFTN

So an expired-but-still-indexed video resource is a platform-level
limitation, not something the upload flow can refresh. Removing the retry
drops two wasted OIDB round-trips per cached-video re-send. The underlying
#145 (receiver '资源已过期' for a server-expired resource) remains a
platform issue, tracked separately.

Tests updated to assert the single-request behaviour.
2026-06-29 15:32:57 +08:00
DrSmoothl
37f768dd33 fix(bridge): isolate process enumeration so a blocked native call can't freeze the loop (#158)
QQ's silent hot-update churns the process table; the watcher's synchronous
native getAllMainProcess() (/proc walk reading cmdline/maps) blocks while a
process is mid-exec(). Running on the main event loop, that froze the whole
bot — OneBot stopped responding, the watcher stopped ticking, the supervisor
saw it 'alive' so never restarted it (silent death until manual restart).

- run the native enumeration in a worker_threads worker, raced against a
  deadline on the main thread; a blocked call no longer stalls the loop
- on timeout/failure return an UNKNOWN sentinel (null); PipeWatcher keeps the
  prior process+pipe snapshot instead of treating missing data as 'all QQ
  gone' (which would dispose live sessions and tear down a healthy hook)
- graceful fallback to in-loop enumeration when the addon can't load in a
  worker or there's no addon (macOS); custom listers (tests) bypass the worker
- bounded orphan workers across a sustained hang

Tests: PipeWatcher null-sentinel (no false process-gone, recovers); enumerator
sync-fallback + broken-isolation paths. Native /proc-walk hardening rides in
the nnphook repo separately.
2026-06-28 23:30:10 +08:00
DrSmoothl
5dc3ec88d4 fix(webui): smooth sidebar collapse — no reflow, centered icons, pin button
The hover-rail flipped its content to a collapsed layout instantly while the
width animated, so on every expand/collapse icons jumped toward the top-left and
labels flashed in, wrapped super-tall, then settled — and the collapsed rail
leaked the first glyph of every label plus hard-clipped highlight bars.

Lay the rail content out at a fixed width and let the aside clip it: nothing
reflows during the width animation. Icons live in a fixed centered column (never
move); labels stay mounted with nowrap and just fade out when collapsed (no
wrap, no leak); the active pill and update banner render their background as an
absolute layer that becomes a centered squircle on the rail instead of a
hard-clipped bar.

Adds the promised pin toggle to the sidebar footer (desktop) — mirrors the
「钉住侧栏展开」 appearance setting: pinned keeps the rail open, unpinned returns
to hover-to-peek.
2026-06-28 23:29:25 +08:00
snowluma-bot[bot]
688402814c Merge pull request #159 from SnowLuma/dev
chore: promote dev → main (7ec74f2)
2026-06-28 14:48:25 +00:00
DrSmoothl
7ec74f2928 chore(release): v1.10.4 2026-06-28 22:48:00 +08:00
DrSmoothl
2b15bc6710 feat(webui): group Settings sidebar into 控制台 / SnowLuma / 平台
The flat tab strip mixed three domains — the dashboard itself, the all-accounts
SnowLuma protocol runtime, and the host/platform. Regroup into 3 labelled
sections (macOS System-Settings idiom): section headers show on the desktop
rail; the mobile strip stays a flat wrap via display:contents. Each group is a
role=group + aria-labelledby; the nav gains an aria-label.

This gives '全局配置' (and future global protocol knobs) a principled home and
ends the mixing. Phase 4 (final) of the global-settings split.
2026-06-28 22:25:39 +08:00
DrSmoothl
196f98e97c feat(webui): global-config settings tab + /api/global-config
Adds a '全局配置' Settings tab that edits config/snowluma.json — the rkey
fallback-server list and the deployment-wide musicSignUrl — backed by a new
bearer-gated GET/POST /api/global-config (load/saveGlobalSettings, then
oneBotManager.reloadGlobalSettings to hot-apply to live instances).

The panel reuses the established settings-panel idiom (Input/Button/Label,
debounced auto-save, flash); rkey servers are an inline add/remove list with
client-side http(s) validation hints. It deliberately does not reconcile inputs
from the server's normalized response (would erase a half-typed URL); a
load-failure shows an error+retry, and the save toast says '无效项已忽略' when
the server would drop an entry.

Removes the now-dead per-UIN musicSignUrl form (moved to global in Phase 2).
Phase 3 of the global-settings split (nav grouping is Phase 4).
2026-06-28 22:16:07 +08:00
DrSmoothl
ea1c5ff9eb feat(onebot): migrate musicSignUrl from per-UIN to global config
musicSignUrl is a deployment-wide signing-service endpoint (same for every
account), so it belongs in the global config/snowluma.json next to rkey, not in
per-UIN onebot_<uin>.json.

- GlobalSettings gains musicSignUrl (http(s)-validated, '' = built-in default);
  consumption switches to globalSettings.musicSignUrl and hot-reloads via
  applyGlobalSettings.
- One-shot copy-up at boot (migrateGlobalSettings, called first in main()):
  lifts the first VALID legacy value from any config/onebot*.json into the
  global store. Idempotent via a key-PRESENCE guard, so an intentional
  clear-to-'' is never reverted by a stale legacy value.
- Remove musicSignUrl from per-UIN OneBotConfig (type + parse/serialize).

Phase 2 of the global-settings split. (WebUI form follows in Phase 3.)
2026-06-28 21:38:32 +08:00
DrSmoothl
659970077a refactor(onebot): move rkey fallback from per-UIN to a global config store
The rkey fallback endpoint is deployment infra (one self-hosted server serves
all accounts; fallback rkeys are fungible), so it doesn't belong in per-UIN
onebot_<uin>.json. Introduce config/snowluma.json — a generic home for small
all-accounts SnowLuma settings — and move rkey.fallbackServers there.

- New onebot/global-config.ts: load/save/normalize with section-merge + atomic
  write; http(s)+host URL validation; default [] (off). Lives in onebot (not
  core) because the onebot manager constructs instances and must not depend on
  core.
- OneBotInstance takes globalSettings; manager loads it on session start and
  exposes reloadGlobalSettings() to hot-push edits to every live instance via
  applyGlobalSettings → RKeyCache.setFallbackServers.
- Remove rkey from per-UIN OneBotConfig + the WebUI per-UIN round-trip (never
  released, so no migration). Register snowluma.json in the backup allowlist.

Reworks the per-UIN rkey from 12b0190. Phase 1 of the global-settings split.
2026-06-28 20:52:07 +08:00
DrSmoothl
5d39cf5782 fix(core): finalize c2c file upload so the recipient can download (#157)
Private (c2c) file sends uploaded the bytes (apply 0xE37_1700 + Highway)
and PbSendMsg returned ok, but the receiver saw "文件传输失败": the message
carried only FileExtra.file (metadata) and not the server-issued download
routing. Group files use a different element, hence c2c-only.

Port NapCat's upload→finalize→send sequence:
- add 0xE37_800 (FinalizeOfflineFile) OIDB service, run after the Highway
  PUT to fetch the download metadata (field30)
- extend FileExtra with field6 (PrivateFileExtra.field2) and populate it
  from that metadata in sendC2cFile; covers both the url-upload and the
  file_id-resend send paths (both funnel through sendC2cFile)

Tests: byte-oracle locks the 0xE37_800 request + FileExtra.field6 tags;
core routing test now asserts finalize runs and field6 is populated.
Needs real-machine verification (send a private file, confirm download).
2026-06-28 20:11:17 +08:00
DrSmoothl
12b01907bc feat(onebot): opt-in remote rkey fallback server (#156)
On accounts where the native OIDB 0x9067_202 rkey fetch persistently returns
nothing, every image was served as a bare multimedia.nt.qq.com.cn URL the CDN
rejects with invalid rkey — SnowLuma had no fallback, unlike NapCat.

Add config.rkey.fallbackServers (default []: OFF; no third-party server is
contacted unless the operator configures one). When the native fetch leaves the
cache without a usable image rkey, each configured HTTP endpoint is tried in
turn for { group_rkey, private_rkey, expired_time } (NapCat rkey-server format;
an OneBot { retcode, data } wrapper is also accepted), populating the group/
private image rkey types. Values keep any leading &rkey=/?rkey= since
resolveImageUrl strips before re-appending.

WebUI has no form yet but round-trips rkey.fallbackServers verbatim so a hand-
edited value survives an unrelated config save. Part B of #156 (cooldown is A).
2026-06-28 01:37:58 +08:00
DrSmoothl
219d60410a fix(onebot): prefer real url over unresolvable file id in media segments
When a bot framework echoes a received image/voice/video, it resends the
original `file=<md5>.ext` (a QQ-internal media id) together with the
download `url`. The parser collapsed sources as `file ?? url ?? ...`, so
`file` won and the send path statSync'd the id as a local path → ENOENT
(retcode 1200). Reported in #155 for images via Yunzai复读.

Add pickMediaSource(): keep `file` when it is directly loadable (inline
base64/data bytes, a remote url, or a path with a separator); otherwise
fall back to a sibling http(s) `url`. Applied to image/record/video.

Tests cover the #155 echo case plus the path/base64-wins guards.
2026-06-28 01:33:07 +08:00
DrSmoothl
182df4b0e2 fix(onebot): retry rkey fetch eagerly while cache holds none (#156)
When the OIDB 0x9067_202 rkey fetch returns empty or fails, the cache stays
empty and resolveImageUrl hands out a bare multimedia.nt.qq.com.cn URL the CDN
rejects with {retcode:-5503010, invalid rkey}. The 30s refresh cooldown then
blacked out every image for 30s+ after each empty/failed fetch.

Use a short RKEY_EMPTY_COOLDOWN (10s) whenever no usable image rkey is cached,
keeping the 30s steady-state backoff only once we actually hold one — so a
transient empty fetch self-heals in seconds instead of 30s. (Part A of #156;
remote-server fallback follows.)
2026-06-28 01:25:19 +08:00
DrSmoothl
6c2a3fc325 fix(ci): strip ANSI before matching TRACE in needs-logs bot
The needs-logs workflow tested /\bTRACE\b/i against the raw issue body.
Pasted terminal logs wrap the level in ANSI color codes (\x1b[90mTRACE\x1b[0m);
the trailing 'm' of the color code abuts 'TRACE', so the leading \b never
matches and a log that clearly contains TRACE is wrongly flagged needs-logs
(e.g. #156). Strip ANSI escapes first, and measure the too-short heuristic on
the cleaned text too.
2026-06-28 01:25:03 +08:00
DrSmoothl
5eaac0870c feat(webui): scale notification-channel opt-in to large lists
The per-account 上下线通知渠道 picker rendered every global channel as a
flat toggle row, so 40+ channels produced an unbounded, messy wall inside
通用设置. Rework it into a collapsible control:

- collapsed: one-line summary — selected count badge + selected channels
  as removable chips (cap 8, then "+N 更多")
- expanded: description + name/url search filter + 全选/清空 bulk actions
  + a height-bounded ScrollArea list (max-h-64) so it never blows up
- globally-disabled channels stay locked off; data flow unchanged

Reuses Badge / ScrollArea / ToggleSwitch / Input.
2026-06-28 01:23:12 +08:00
DrSmoothl
04591517fa feat(webui): redesign adapter edit dialog (Apple-HIG) + custom dropdown
Rework the OneBot adapter create/edit modal into an iOS grouped-list
layout matching the debug-page language: captioned soft-card sections,
a per-kind icon chip, settings rows, and staggered motion entrance.

- reportSelfMessage: segmented control -> shared ToggleSwitch
- messageFormat (+ WS role): segmented/native select -> new custom
  DropdownSelect (accessible listbox, keyboard nav, spring popover)
- enable toggle promoted to a prominent top card
- new components/ui/dropdown-select.tsx (zero new deps, hand-rolled)

Presentation-only; draft/validation/data flow unchanged.
2026-06-28 01:14:37 +08:00
DrSmoothl
e1f5267764 fix(onebot): make group large-video file fallback actually fire
#153 added a video→file fallback but the group side was dead code: it
lived in element-builder behind `isGroup && element.fileId`, and a video
sent by url/path has no fileId, so oversize group videos just rethrew the
raw Highway error (real bot: `error_code=323` on a 1.4 GB group send).

Move the fallback to the OneBot layer for groups, mirroring the private
path: on a failed Highway send, re-route oversize videos through
groupFile.upload. Verified on a live bot — a 1.4 GB group video now lands
as `[文件:video.mp4]` instead of failing.

Extract the shared heuristic (isHighwaySizeError / videoNeedsFileFallback
/ splitVideoFileFallback) so private and group stay in sync, and drop the
now-unreachable element-builder video catch. Adds send-video-fallback
tests covering both the known-oversize and remote-error-heuristic paths.
2026-06-27 16:27:33 +08:00
stla
85182795b5 feat(protocol,onebot): raise video size limit with Highway-first fallback (#153)
Round 3: fix hardcoded 4096 MB in error messages
- Use MAX_VIDEO_SIZE_HARD constant instead of hardcoded 4096 MB
- Both throw sites now derive limit from the same constant
2026-06-27 16:10:25 +08:00
DrSmoothl
70fd40e34c chore(mcp): regenerate catalog after returnsSchema backfill 2026-06-26 23:08:38 +08:00
DrSmoothl
0e8a194d4f feat(onebot): backfill returnsSchema on remaining read-only actions (c2: source-proven only) 2026-06-26 23:05:52 +08:00
DrSmoothl
d2490787ae feat(onebot): backfill returnsSchema on info/group-info read-only actions 2026-06-26 22:44:10 +08:00
DrSmoothl
0163af979a fix(ci): robust catalog sync (untracked-file guard, mkdir, rebase) + stale-catalog gate 2026-06-26 22:03:42 +08:00
DrSmoothl
75f14540c8 ci: sync action catalog.json to SnowLumaDocs via bot on release 2026-06-26 22:03:42 +08:00
DrSmoothl
5e0d2db8b2 feat(mcp): emit catalog.json twin + carry returnsSchema in catalog 2026-06-26 22:03:42 +08:00
DrSmoothl
18014fb3c5 feat(onebot): backfill returnsSchema on representative read-only actions 2026-06-26 22:03:42 +08:00
DrSmoothl
355cce1e52 feat(onebot): add optional returnsSchema to action doc metadata 2026-06-26 22:03:42 +08:00
游手好闲的言柒
04a9016a7d fix(onebot): strip at segments from private messages (#151)
* fix(onebot): support inline file url/path in send_group/private_msg

* test(onebot): update file segment parser test for inline url/path support

* fix(onebot): strip at segments from private messages
2026-06-26 21:08:01 +08:00
DrSmoothl
cf7de9f7bd chore: update vite version to ^8.0.16 in pnpm-workspace.yaml 2026-06-26 19:59:58 +08:00
snowluma-bot[bot]
a60385c376 Merge pull request #150 from SnowLuma/dev
chore: promote dev → main (351db57)
2026-06-26 11:50:10 +00:00
DrSmoothl
351db573d8 chore(release): v1.10.3 2026-06-26 19:49:41 +08:00
DrSmoothl
3b023b3275 fix(protocol): collapse ark/card messages structurally, not by string match (#146)
Follow-up to the previous #146 fix, which dropped QQ's compat fallback text by
content-matching the "版本不支持 … 升级" family. RE of the QQ kernel
(wrapper.linux.node) showed that is not how QQ does it:
- the receiver binary contains NONE of these fallback strings, so QQ cannot be
  matching by content;
- the on-target wire is [lightApp, text(compat), generalFlags, extraInfo] and the
  text element has no distinguishing marker (no pbReserve / attr6Buf);
- QQ NT's kernel codec (msg_codec_mgr) collapses the message to a single ark
  element — the sibling text is never emitted. NapCat maps kernel elements 1:1
  with no ark-aware skip yet still surfaces only the card, confirming the kernel
  drops it upstream.

Switch to that structural rule: when a lightApp/richMsg card is present, drop
sibling plain text outright. It is version/locale-proof (won't break when Tencent
rewords the string) and matches QQ NT + NapCat output exactly. @ mentions /
replies / faces are not plain text and survive; QQ clients can't attach a caption
to a card anyway, so no QQ-origin message loses real text.

Verified live on a logged-in build: get_msg returns a single json segment.
2026-06-26 18:31:43 +08:00
DrSmoothl
319c7d607d fix(protocol): drop QQ ark-compat fallback text beside mini-app cards (#146)
A QQ mini-program / ark share (B站 video, QQ 小程序, …) arrives on the wire
as a lightApp/richMsg ark element followed by a plain text element carrying
QQ's graceful-degradation compat string "当前QQ版本不支持此应用,请升级". That
text is meant only for protocol-old clients that can't render the card; QQ NT
and the kernel-backed bridges (NapCat) surface just the card.

On-target capture (test group) confirmed the text element has no distinguishing
wire marker (no pbReserve / attr6Buf) — it is a bare text sibling of the ark.
SnowLuma was decoding both, so every mini-app card came through as the card
plus a spurious "当前QQ版本不支持" text segment.

Drop the compat string when it sits beside a card, matched narrowly (the
"版本不支持 … 升级/更新" family, <=40 chars) so genuine user captions sent
alongside a card are preserved.

Verified live on a logged-in build: get_msg now returns a single json segment.
2026-06-26 18:08:26 +08:00
DrSmoothl
9de12db447 fix(onebot): align file-url actions with NapCat param tolerance (#147)
get_private_file_url required file_hash (and user_id), but NapCat needs
only file_id — it re-derives the hash from its composite file_id. Make
user_id and file_hash optional; the empty hash is accepted on the wire
(SnowLuma's private file_id already carries the md5 prefix). Verified
live: only-file_id returns a working URL (148237B download matches).

get_group_file_url rejected a present non-numeric busid with
`expected an integer` after the f.int().default(102) refactor, while
NapCat/LLBot omit busid entirely and ignore any value. Restore the
legacy `asNumber(busid) || 102` tolerance via f.raw()+busidOr102.
Verified live: null/"102"/omitted/"abc" all return a working URL.
2026-06-26 17:34:16 +08:00
DrSmoothl
ecea72df40 test(onebot): expect forced full video upload retry on stale fast-path
The NTV2 fast-upload video test still asserted a single sendRawPacket
call, but #145 (forceFullOnFastPath) re-issues the OIDB request with
fast-upload disabled when a flagged main file carrying real bytes is
fast-pathed by the server. The stale assertion was never caught because
the dev push workflow doesn't run the suite — only the PR gate (ci.yml)
does, so it first surfaced on #149.

Assert two packets go out and that the second round drops
tryFastUploadCompleted, locking #145's behavior at the onebot layer.
2026-06-26 17:09:18 +08:00
DrSmoothl
214287da28 ci(issues): auto-close stale needs-logs reports
Daily stale sweep over issues still labeled needs-logs: mark stale after
7 days of inactivity, close (not_planned) after another 7. Issues that
get valid logs lose the needs-logs label and are skipped by only-labels.
PRs are excluded.
2026-06-26 17:05:50 +08:00
DrSmoothl
81969a4590 ci(issues): enforce TRACE logs on bug reports via github-script
Form validation can only force a field non-empty, not validate content.
On bug issue opened/edited, parse the TRACE-log section: if empty, missing
a TRACE marker, or too short, label needs-logs + post a one-time guide
comment; auto-remove the label once the reporter edits in valid logs.
2026-06-26 17:05:50 +08:00
DrSmoothl
860848a310 feat(issue-template): require TRACE-level logs in bug reports
- Make the logs textarea required so a bug report can't be submitted empty.
- Document how to enable TRACE: WebUI server log-level switch (+ '开发'
  preset so the export actually contains trace lines) or SNOWLUMA_LOG_LEVEL=trace.
- Add a required preflight checkbox attesting TRACE logs are attached.
2026-06-26 17:05:50 +08:00
Airline233
39338c3f1d fix(protocol,onebot): generate and send ark of contact cards correctly (#149) 2026-06-26 17:04:40 +08:00
Airline233
02de2acea4 fix(core): support file sources in forwarded messages (#144)
Pre-upload file/url/base64 segments for forwarded message nodes into the
target scope, re-upload cached file_ids when crossing private/group scope,
and suppress standalone file-message publishing during forward preparation.
2026-06-25 20:55:39 +08:00
DrSmoothl
3eba2a677c fix(highway): force full video upload when server fast-paths a stale resource (#145)
Group/c2c video resources expire server-side. When the bot re-sends a
video whose md5 the server already cached, the NTV2 OIDB returns no uKey
for the main file (fast-upload hit) and SnowLuma trusted it — the send
"succeeds" but the receiver sees 资源已过期, because the reused object had
expired. Confirmed by the reporter: same MP4 fast-paths and breaks, but
mutating one byte (new md5) forces a full upload and plays fine.

Add a per-sub `forceFullOnFastPath` flag on MediaSubFileUpload. When a
flagged sub-file (video main) carries real bytes but the server fast-paths
it, runNtv2Upload re-issues the OIDB request with tryFastUploadCompleted
disabled (proton drops a `false` bool, which the server reads as "no
fast-upload"), forcing a fresh resource + full PUT. The thumb stays
fast-path-OK so a cached thumb never re-pushes the main video; forwarding
paths carry no bytes so they never trigger the retry.

Also fixes the observability gap the reporter hit: the main file being
silently skipped on a fast-path now logs explicitly, and so does the
forced-retry, instead of only the thumb PUT showing up.

Note: the retry relies on the server treating an absent
tryFastUploadCompleted as "no fast-upload" — needs real-device
confirmation that the forced round actually returns a uKey.
2026-06-25 20:52:11 +08:00
stla
78b0e1a124 feat(webui): auto-compress per-core density grid to fixed container (#140) (#141)
Replace fixed grid-cols-8 per-core bar display with dynamically
computed square grid that fills a fixed-height (80px) container.

- Adds bestGrid() utility that finds optimal (cols,rows) partition
  by minimizing empty cells and aspect balance
- Grid uses grid-template-rows: repeat(N, 1fr) for equal row height
- Empty cells filled with hidden divs for stable layout
- Preserves existing color tokens (bg-muted, bg-primary/70, rounded-sm)
- No scrollbar regardless of core count (tested up to 256)

Closes #140

Co-authored-by: SnowLuma Dev <dev@snowluma.local>
2026-06-25 20:46:16 +08:00
DrSmoothl
feaa94bec7 build(core,runtime): native websocket-darwin-arm64.node + drop build hatch
WebSocket native is now built for darwin-arm64 — source is at
github.com/SnowLuma/snowluma-websocket (cmake-js + node-addon-api,
clones to dev/snowluma-websocket and builds with `npm install`).

  npm install in dev/snowluma-websocket → build/Release/snowluma_ws.node
  cp → packages/runtime/native/websocket-darwin-arm64.node (102 KB)

Reverts the SNOWLUMA_BUILD_SKIP_NATIVES escape hatch in vite.config.ts
that 67f8bf3 added — no longer needed; the darwin native binary is
present. Keeps `packages/core/config/.gitignore` (independently useful
runtime-state hygiene). vite build now runs clean on darwin with no
env overrides; the runtime SNOWLUMA_DEV_NO_NATIVE=1 stub also becomes
optional (only needed if the operator wants to bypass WebSocket I/O
specifically).

Existing native binaries unchanged. CI invariant restored: every
release build must include every platform's native set.
2026-06-25 16:25:56 +08:00
DrSmoothl
67f8bf3941 build(core): SNOWLUMA_BUILD_SKIP_NATIVES=1 escape hatch for darwin dev
Two architectural cleanups that complement the bridge darwin support in
7343ae6, both opt-in / default-safe:

1) `vite.config.ts` — gate the missing-native build error behind
   `SNOWLUMA_BUILD_SKIP_NATIVES=1`. Default behaviour (no env) still
   throws as before, so the CI invariant "release builds must carry the
   full native set" is untouched. Darwin developers without prebuilt
   `websocket-darwin-arm64.node` (source lives in a separate private
   build repo) can now run `SNOWLUMA_BUILD_SKIP_NATIVES=1 pnpm build`
   and pair it with the runtime `SNOWLUMA_DEV_NO_NATIVE=1` stub at
   `node dist/index.mjs` boot. The qq-hook path (separate addon) is
   independent and unaffected.

2) `packages/core/config/.gitignore` — `runtime.json` is the only
   tracked deploy-time override file in that dir; every other config
   file is per-instance runtime state written by the daemon/dev server
   (admin password hash, EULA consent, per-uin OneBot binding, WebUI
   layout). Previously they showed up as 5 untracked files after every
   `pnpm dev:mode`, polluting `git status` and risking accidental
   commit of local creds via `git add -A`. Pattern: ignore everything
   except `runtime.json` (and the .gitignore itself).

No code paths changed; both are operator-experience fixes for running
SnowLuma on darwin against the nnphook DYLD_INSERT hook.
2026-06-25 14:27:59 +08:00
DrSmoothl
7343ae6372 feat(bridge): darwin support — DYLD_INSERT-style hook discovery
Adds the missing macOS branch so HookManager + PipeWatcher discover QQ
processes when the dylib is injected via DYLD_INSERT_LIBRARIES (the
in-process injection model used by apps/qq/macos/qq_hook_dylib.cpp in
the nnphook private repo, vs Linux's out-of-process ptrace + N-API
addon model and Windows's manual-PE-loader injection).

Two small changes:

1. `linuxRuntimeDir()` (qq-hook-client.ts) — name kept for callsite
   stability; the function now applies to every non-win32 platform.
   New darwin branch prefers `$TMPDIR/snowluma-hook/` to match the
   dylib's `runtime_dir()` (apps/qq/macos/qq_hook_dylib.cpp). The
   Linux `/tmp/snowluma-<uid>` fallback stays as the last resort.
   $TMPDIR is per-user under /var/folders/ on stock macOS, which is
   the right place — /tmp/snowluma-<uid> doesn't exist by default.

2. `listSnowlumaPipePidsSync()` (qq-hook-client.ts) + darwin branch
   in `listHookProcesses()` (injector.ts) — on macOS there is no
   native enumerate-QQ-processes addon (DYLD_INSERT obviates the
   need; the dylib is already mapped in QQ when SnowLuma launches).
   The watcher's `listProcesses` dep is sync, so we provide a sync
   directory scan that returns the pids encoded in mojo.<pid>.control.sock
   filenames. The subsequent async `listLivePipes()` still gates the
   pipe-up emit via a real connect probe — a dangling socket file
   from a force-killed previous run can't drive a false connect.

Without these two changes, `pipe-watcher.tickOnce()` filtered out our
QQ pid at line 170 (`if (!newKnownPids.has(pid)) continue;`) because
`listProcessesNative()` returned []. The pipe stayed live (verified
by our nnphook recv hook firing), but the bridge never emitted
'pipe-up', HookManager never auto-loaded the session, and the WebUI
showed an empty process list.

Verified end-to-end against the resigned QQ 6.9.96-49738 + nnphook
gpt54 branch dylib on macOS 26.5.1 (Tahoe) arm64:

  * Direct HookManager harness picks up PID=16032 in <2.5s,
    fast-paths to 'reconnect' (the live-pipe-skip-injection branch
    in hook-session.ts:200), pipe connected, status=loaded
  * `pnpm dev` (SNOWLUMA_DEV_NO_NATIVE=1 for the websocket stub):
    /api/processes returns the live QQ entry with method=reconnect,
    connected=true, awaiting login

The websocket darwin-arm64.node native addon is still missing — set
SNOWLUMA_DEV_NO_NATIVE=1 to dev-mode boot with the existing stub
fallback. That's a separate runtime artifact and not in scope here.

`shouldAutoLoadPid()` returns true on non-linux without further checks
(no Electron-child-process scanning needed on darwin), and the
`hook-session.ts` "pipe already live → reconnect" fast path means
the bridge never tries to invoke the non-existent darwin native
injector. Auto-load on a freshly discovered macOS QQ is therefore
safe with or without `SNOWLUMA_HOOK_AUTOLOAD=1`.

Tests: bridge typecheck + 62 unit tests still pass.
2026-06-25 02:53:44 +08:00
stla
41bad7f24c feat: make #sl status command trigger configurable (exact match, max 32 char) (#138)
* feat: make #sl status command trigger configurable (exact match, max 32 char)

The trigger word for the built-in #sl status command is now configurable
via statusCommand.trigger, with exact case-insensitive matching preserved.

* chore: reject control chars in trigger + add sync assertion
2026-06-25 01:02:17 +08:00
DrSmoothl
19c03eb0ba chore(gitignore): ignore per-package runtime data dirs (**/data/)
The root /data/ rule is anchored to the repo root and missed
packages/<pkg>/data/<uin>/*.db that IdentityService writes to cwd during
tests. Add a recursive **/data/ so those test artifacts stay untracked.
2026-06-25 00:21:21 +08:00
DrSmoothl
fbc5a3c981 refactor(core): use @snowluma/common/coerce in config normalizers
Phase 2. notifications/config and webui/ui-config dropped their verbatim-
duplicated isObject/boolOr/clampInt (+ ui-config clampNum) in favor of the
shared @snowluma/common/coerce. Pure delete-and-import: the shared
primitives are byte-identical to the originals (adversarially verified),
so behavior is unchanged.

Kept local: strOr (notifications-only), oneOf/isFiniteNum/hexOr
(ui-specific). notifications-config suite green (21), core+common
typecheck clean.
2026-06-25 00:05:46 +08:00
DrSmoothl
1ce7385d1e feat(common): add zero-dep scalar coercion primitives (coerce)
Phase 1 of de-duplicating config normalization. isObject/boolOr/clampNum/
clampInt were copied verbatim across notifications/config and webui/
ui-config; give them a single home as @snowluma/common/coerce (new
per-file subpath export, zero deps — fits common's leaf-utility charter).

Byte-identical to both originals (adversarially verified), so the phase-2
migration is a pure delete-and-import. clampInt is clamp-then-trunc;
10 table tests pin types, numeric-string coercion, non-finite→fallback,
bounds, and the clamp/trunc order. Not yet wired into consumers.
2026-06-25 00:01:39 +08:00
DrSmoothl
3a4af38842 refactor(onebot): lift bootstrap-meta framing into the network adapter base
Phase 1. The connect/enable/heartbeat bootstrap triplet was built +
shaped + stringified + null-dropped identically in WsServerAdapter and
WsClientAdapter. Lift that into IOneBotNetworkAdapter:

- metaFrame(event, options): string|null  — shape via shapeEventForAdapter
  then JSON.stringify, or null when the shaper drops it
- bootstrapMetaFrames(options): string[]  — the 3 bootstrap events,
  framed and null-filtered

Both ws adapters' sendBootstrapMetaEvents become one-liners over
bootstrapMetaFrames (ws-client keeps its role guard at the call site);
ws-server's close() disable broadcast reuses metaFrame. Base now owns
the shape+serialize policy, adapters own only the transport — same
shape as ADR-0009's reload template method.

Behavior-preserving (adversarially verified byte-for-byte); the two ws
adapters drop their now-unused shapeEventForAdapter import. Safety net
(network-bootstrap-meta, 9 tests) green.
2026-06-24 23:40:31 +08:00
DrSmoothl
e11601bfec test(onebot): characterize network bootstrap-meta behavior (safety net)
Phase 0 of the bootstrap-meta deepening. No production code; pins the
observable behavior the phase-1 base-class lift must preserve:

- shapeEventForAdapter shaping policy (meta passthrough, message_sent
  drop under !reportSelfMessage, string-format raw collapse)
- ws-client emits [connect,enable,heartbeat] on open, role-guarded,
  and skips a frame that shapes to null (options genuinely threaded)
- ws-server sends the triplet to an Event connection and broadcasts a
  single disable on close(), skipping Api connections on both paths

Adversarially hardened: two gaps (null-drop/options-threading, close
Api-skip) were found via surviving mutations and closed. 9/9 green.
2026-06-24 23:35:07 +08:00
DrSmoothl
a305afbc76 fix(webui): observable projector wedge + tighten non-array fallback
Round-2 follow-up. Two small holes flagged by the adversarial review of
the connection-diff-loop projector:

- A projector that starts throwing only after a shape regression would
  wedge the diff baseline silently — no publishes, no log, the only
  symptom is the dashboard's connections card freezing until restart.
  Latch a one-shot console.error on the first throw so the failure is
  visible without re-running the loop locally.

- The non-array fallback at the projector site in server.ts returned
  `acc.adapters` verbatim, which would re-introduce volatile fields if
  the snapshot shape ever drifts. Tighten to `[]`.

Also documented the deliberate trade-off: per-second adapter `detail`
rotation (client count, last-delivery HH:MM:SS) refreshes on the next
SSE push or the 30s REST reconcile rather than in real time. The user's
original bugs were about process/account edges (which DO push
instantly); detail-string freshness was not in scope. If it becomes one,
surface client-count as a structured AdapterStatus field instead of
parsing the localised `detail`.

437/437 core green.
2026-06-24 23:17:26 +08:00
DrSmoothl
84cdd99868 fix(webui): dropped-frame reconcile + split systemInfo cadence + diff-loop unref
Three findings from the adversarial review, all in the WebUI integration:

D: SSE {kind:'dropped'} now triggers a one-shot REST refresh of
   qq-list/processes/connections instead of being silently ignored.
   Reasoning: when createFramePusher drops frames under backpressure, the
   NEXT delivered frame is per-resource (only the resource whose debounce
   timer next fires) — NOT a refresh of all 3. If the dropped frame was
   the only update for a slow-changing resource (e.g. connections stable
   afterwards), the WebUI stays stale until the 30s reconcile. The
   refresh is fire-and-forget; each refresh helper already swallows errors.

E: systemInfo gets its own fast useEffect on the user's pollInterval
   (default 3s). The earlier commit slowed it to 30s claiming the data was
   'daily cadence', but SystemInfo carries live values (uptime,
   cpu.loadAvg, memory.usagePercent, runtime.heapUsed) that the overview
   widget animates — 30s is a visible regression. The other 3 resources
   stay on the 30s SSE-reconcile fallback.

F: connection-diff-loop's setInterval is now .unref()'d (mirrors the
   tokenJanitor pattern at server.ts:462). The discarded handle is now
   commented as intentional — initWebUI has no shutdown path, so the
   handle has no consumer; unref is the right cleanup primitive.

WebUI typecheck clean. 437/437 core suite (no behavior change in core
tests — only the diff-loop file's timer.unref?.() call is new and is
optional-chained so vitest's fake timers don't crash).
2026-06-24 23:05:25 +08:00
DrSmoothl
bae9f8edb0 fix(webui): connection-diff-loop compares ONLY level — strip detail timestamps
Adversarial review caught: HttpPostAdapter.describeStatus() embeds
HH:MM:SS in 'detail' (e.g. "上次推送 14:53:01"). Every webhook delivery
rotates that string every second under any active push — and the diff
loop's raw JSON.stringify compared everything, so it published on every
500ms tick under any non-idle webhook. Net effect: SSE pushed a full
connections frame at 2 Hz, exactly the polling the loop was meant to
replace, just on the push channel.

Add an optional pickComparable projector. server.ts caller passes one
that returns { uin, nickname, adapters[{ name, kind, status }] } — the
LEVEL only, not the live-rendered detail string. The SSE handler still
ships the FULL snapshot (including detail) to the WebUI; only the diff
key is pruned.

2 new tests pin the invariant: 10 detail-only ticks → ZERO publishes; a
real status-level transition publishes exactly once. Plus a throwing-
projector isolation test. 7/7 diff-loop tests green.
2026-06-24 22:55:51 +08:00
DrSmoothl
f9ce49ac7e fix(webui): single-flight per resource in bindStateStream — ordering safety
Adversarial review caught: uneven snapshot latency can deliver a STALE
final frame. Concrete repro added as a test:
  - publish('processes') @ T=0 → flush A starts a slow snapshot (200ms)
  - publish('processes') @ T=60 → flush B fires at T=110 with a fast (10ms)
    snapshot → send B at T=120
  - flush A's slow snapshot resolves at T=250 → send A with snapshot data
    captured BEFORE B → client's LAST frame is stale.

Fix: at most one in-flight flush per resource. While a flush is pending,
new publishes set a  flag instead of starting an overlapping
flush; on completion the flag re-arms the debounce timer for exactly one
follow-up flush. Sustained publish streams therefore produce at most one
frame per (debounceMs + flushLatency).

Test 'serialises overlapping flushes' fails on the pre-fix code (last
frame = 'snap-T0' stale), passes on the fix (last frame = 'snap-T60'
fresh). Test 'coalesces N publishes during in-flight' verifies the
pending flag is set-like (5 publishes → 1 follow-up, not 5).

9/9 state-stream tests green; 432/432 core suite.
2026-06-24 22:44:09 +08:00
DrSmoothl
bb752b13a1 fix(webui): add /api/state/stream to SSE token-query allowlist
Adversarial review caught: EventSource cannot set custom headers, so every
SSE endpoint MUST appear in the TOKEN_QUERY_ALLOWLIST or the auth
middleware at server.ts:404 computes queryToken='' and 401s every connect.

Without this fix the entire phase-3 SSE endpoint is dead on arrival:
clients silently fall back to the 30s REST reconcile and the original
"WebUI must refresh to see new state" bug is unfixed.

Export the allowlist as SSE_TOKEN_QUERY_PATHS so a regression test can
lock the invariant — a missing entry has no error log, the only symptom
is the silent stream failure.
2026-06-24 22:36:40 +08:00
DrSmoothl
a9f5f277f1 feat(core): connection-status diff loop — publish 'connections' on change
Phase 4b. OneBot adapters expose no event-emitter for connection-state edges
(listening / connected / client-count / last-delivery), so the SSE handler
can't subscribe — without this loop a connection change would only reach the
WebUI on the 30s REST reconcile fallback.

startConnectionDiffLoop polls getConnectionStatuses() at 500ms, compares
JSON-serialised snapshots, and publishes 'connections' through the StateBus
when (and only when) it actually moves. The first SUCCESSFUL observation is
treated as a baseline (no publish): the SSE handler's sendAllInitial has
already shipped the initial snapshot to every connected client on connect.
Snapshot exceptions are isolated — the loop retries on the next tick without
clobbering the baseline.

Started once per initWebUI lifetime; lives until process exit (consistent
with the other heartbeat-style intervals like the SSE 15s keepalives).

431/431 core suite green (5 new tests cover stable=silent, change=publish,
first-observation=baseline, dispose stops, snapshot-throw isolation).
2026-06-24 22:09:13 +08:00
DrSmoothl
de3bb4817d feat(webui): subscribe to /api/state/stream — push-driven dashboard state
Phase 4 of the SSE migration. The dashboard's three live resources now
update the moment the backend sees a change instead of within 0-3000ms of
the next polling tick.

- New api.stateStream({ onEvent, onStatus }) in lib/api/client.ts mirrors
  the existing openLogStream / openDebugStream EventSource pattern: token in
  the query string (EventSource can't set headers), single onerror →
  'reconnecting' status, source.close() on dispose, JSON.parse with skip-
  malformed isolation. Browser-native EventSource auto-reconnect covers
  transport drops with no manual retry timer.

- StateStreamEvent union covers the three resource frames plus the two
  control frames ('ready' on connect, 'dropped' on backpressure). The
  resource frames carry typed HookProcessInfo[] / QQInfo[] /
  AccountConnections[] payloads.

- AppLayout now subscribes on mount, applies pushed snapshots to the same
  setProcessList / setQqList / setConnections React state slots the polling
  tick used to drive. The REST polling tick is RETAINED but slowed to
  max(pollInterval × 10, 10s) (default 3s → 30s) so it acts as a silent-
  drop reconcile rather than the primary update path. systemInfo isn't on
  the SSE feed — it stays on the slow REST loop.

Resolves the two reported bugs:
  1. new QQ.exe not showing in WebUI until manual refresh → process-
     discovered now publishes 'processes' through the StateBus → frame
     arrives within 50ms.
  2. injection panel stuck at "waiting for connection" after a successful
     hook (group messages arriving) → HookSession 'status-changed' now
     publishes 'processes' → 'online' status frame arrives within 50ms.

WebUI typecheck clean. No unit tests in packages/webui (consistent with the
existing openLogStream/openDebugStream which also have no client tests).
2026-06-24 21:51:35 +08:00
DrSmoothl
a7522deb82 feat(webui): /api/state/stream SSE — push processes/qq-list/connections
Phase 3 of switching the three dashboard resources from REST polling to
SSE push.

- New pure helper packages/core/src/webui/state-stream.ts owns the
  debounce/snapshot/fan-out logic, decoupled from Hono so it's unit-testable
  with fake timers (7 tests cover initial-snapshot, single-publish coalesce,
  per-resource independent debounce, dispose-cancels-pending, snapshot
  rejection isolation, send() throw isolation).

- /api/state/stream handler in server.ts mirrors the /api/debug/stream
  pattern: ReadableStream + createFramePusher (drop-under-backpressure with
  the same {kind:'dropped'} marker), 15s heartbeats, abort-signal teardown.
  On connect: one frame per resource. After: a fresh-snapshot frame per
  StateBus invalidation, 50ms per-resource debounce.

- The endpoint 503s when stateBus is absent (build without state-wiring),
  so clients can still fall back to the REST endpoints; the existing
  GET /api/processes etc remain in place for initial fetch + reconcile.

44 test files, 426/426 core suite green.
2026-06-24 21:44:28 +08:00
DrSmoothl
53f68b3945 feat(core): wire HookManager/BridgeManager edges into the StateBus
Phase 2 of switching processes/qq-list/connections from REST polling to SSE
push. Sinks the three publisher edges into a fresh StateBus:

- HookManager grows an OPTIONAL `onSessionsChanged: () => void` dep; called
  from pipe-watcher process-discovered/process-gone and from the previously
  unsubscribed HookSession 'status-changed' event (login/disconnected reach
  it transitively via applyStatus, so a single subscription covers every
  transition the WebUI processes view cares about). Throwing subscribers are
  caught + logged so the watcher loop is never aborted.

- New packages/core/src/webui/state-wiring.ts owns the coupling: produces the
  bus + the `onSessionsChanged` callback to feed HookManager, and registers
  BridgeManager session-started / session-closed listeners that publish
  'qq-list' + 'connections' (in source-of-truth order: account first, then
  adapters).

- index.ts threads stateWiring.bus into initWebUI so the phase-3 SSE handler
  has something to subscribe to; dispose runs on SIGINT/SIGTERM.

Bridge: 62/62 (was 57). Core: 419/419 (was 414). 10 new tests cover all
publish points + exception isolation + the optional-dep contract.
2026-06-24 21:35:27 +08:00
DrSmoothl
5302341dfc feat(core): StateBus — pure pub/sub for WebUI state invalidations
Phase 1 of switching processes/qq-list/connections from 3s REST polling to
SSE-pushed snapshots. The bus is a frozen-snapshot fan-out (subscribers added
during a publish() see only the next one, peer unsubscribes mid-fan-out don't
skip survivors) with exception isolation per listener.

Pure pub/sub by design — debounce and snapshot reads belong with the
subscriber (the /api/state/stream handler in phase 3) so different consumers
can coalesce on their own cadence.

8 unit tests, 414/414 core suite green.
2026-06-24 21:10:53 +08:00
DrSmoothl
fb7675f3cb test(bridge): lock HookSession refresh drift fix
Two tests pinning the one intended behavior change from the status-
machine deepening: refresh while the pipe is down on a connected-but-
never-logged-in session now reports 'connecting' (matching onPipeDown),
not the old spurious 'disconnected'; and a session that HAD logged in
still settles to 'disconnected' + emits disconnected(true), proving the
flip is scoped to the never-logged-in case.

Verified against the pre-refactor baseline: test (1) fails on old code
(produced 'disconnected'), so it locks the flip rather than restating it.
2026-06-24 19:49:21 +08:00
DrSmoothl
1d2a56bcdb refactor(bridge): wire HookSession status through statusFor + shared reconcilers
Phase 2. Migrate the ~6 hand-copied status ternaries to the pure
statusFor() and collapse the pipe up/down orchestration into two shared
private reconcilers:

- reconcilePipeUp  ← onPipeUp + refresh's pipe-up branch
- reconcilePipeDown ← onPipeDown + refresh's pipe-down branch + the
  client 'close' handler (4 call sites, all were near-duplicates)

applyStatus() pushes the statusFor-derived status; loading/error stay
explicit. refreshInternal collapses to a one-line pipe poll. Behavior-
preserving except the intended drift fix (refresh-while-down + never
logged in now reports 'connecting', matching onPipeDown, not the old
spurious 'disconnected').

reconcilePipeDown short-circuits when !connected so a pipe-down tick
can't clobber a diagnostic error or emit a spurious status-changed on a
failed-connect/failed-load session — covered by two new regression
tests (caught in adversarial review). 55/55 green.
2026-06-24 19:42:59 +08:00
DrSmoothl
74c7e086c7 refactor(bridge): extract pure statusFor for HookSession status derivation
Phase 1 of deepening the HookSession status machine. The 5 settled
HookProcessStatus values (available/connecting/loaded/online/disconnected)
were hand-derived from (injected,connected,loggedIn,wasLoggedIn) at ~6
call sites in hook-session.ts. Extract that truth table into a pure
statusFor() in hook-status.ts so it has one source of truth and a
mutation-tight exhaustive table test. loading/error stay out-of-band.

Not yet wired into hook-session (phase 2).
2026-06-24 19:23:00 +08:00
DrSmoothl
9ad37d4ada chore(github): add PR template, bug-report deploy field, feature-request willingness dropdown 2026-06-24 00:46:15 +08:00
DrSmoothl
1bdb8a40c4 fix(protocol): dedup duplicate system pushes (#137 official-robot double group_increase)
Inviting an official robot (e.g. 2854207029) into a group made QQ push the
group_member_increase notice twice, so SnowLuma emitted two
notice.group_increase events; a normal member produced one.

Root cause (RE of wrapper.linux.node): QQ NT dedups every received system
message in sys_msg_mgr.cc::ProcessRecvSysMsg (sub_37BADE0) by a global_key
`{peerUid}_{chatType}_{msg_seq}_{random}` (sub_37BC4E0) — an already-seen key
is dropped ("ignore dup msg") before any listener sees it. The per-message
discriminators msg_seq (attr 40003 = contentHead field 5) and random (attr
40002 = contentHead field 4) are exactly head.sequence and head.msgId
(msg_header_codec_helper.cc sub_37C8AD0). Kernel-based bots (NapCat/LLOneBot)
receive events after this dedup; SnowLuma reads the raw OlPush before it.

Mirror it: SysMsgDedup, a per-account bounded ring that drops a duplicate
system push by (msgType, subType, fromUin, sequence, msgId). Push-level (drops
the whole duplicate like NT), live path only (Bridge owns the tracker; the
forward re-parse passes none), system kinds only (chat messages excluded), and
never dedups a push lacking a server identity (sequence or msgId 0).
2026-06-23 20:36:24 +08:00
DrSmoothl
4e0ec92c23 fix(core): emit group_decrease + drop cache on set_group_leave (#133)
The server never pushes a member-decrease back to the member that left of its
own accord, so set_group_leave produced no notice.group_decrease — downstream
kept a 'zombie' group in its cache, and a later set_group_add_request failed
with 'matching group request not found'.

bridge.leave() now, after the 0x1097_1 OIDB succeeds, synthesizes a self
group_member_leave (user_id = operator_id = self, sub_type 'leave') through the
event bus — converted to notice.group_decrease by the existing path — and
calls identity.forgetGroup() so get_group_list / member lookups drop it
immediately (in-memory + DB inactive).

Kick / disband already arrive via the GroupMemberDecrease push (PkgType 34).
Limitation: a MANUAL leave in the NTQQ client isn't covered — SL is packet-
based with no kernel callback, and a voluntary self-leave isn't pushed back;
only kernel-based clients (NapCat/LLOneBot) catch that.

Validated by unit tests (bridge leave emits the event + forgets the group).
2026-06-22 23:07:44 +08:00
DrSmoothl
2b3d1c67c2 test(common): cover hex/log-summary/request-context; fix Utf8Validator dead code (#84, #85)
Reimplements PR #86 independently (author abandoned it after change-requests),
with the review feedback applied — the original tests asserted behavior the
code never had.

#84 — add @snowluma/common unit tests:
- hex: toHex/toHexUpper/hexPreview boundary + fromHex round-trip & odd-length throw
- log-summary: summarizeParams (top-level primitive is String()'d WITHOUT quotes;
  fields quoted; nested collapsed; total cap) and renderParamsVerbose (redaction,
  long-string marker is the Unicode ellipsis '…<N B>' not ASCII '...', circular guard)
- request-context: nextRequestId monotonic; runWithRequestId sync/async + nested scopes
- root scripts test:common/test:all/coverage; coverage/ gitignored

#85 — Utf8Validator: the second surrogate check was unreachable (within the
0x80–0xBF continuation-byte guard, 'b & 0x20' is true iff 'b >= 0xA0'); merge to
one check. No behavior change.

common suite green (26 tests).
2026-06-22 22:53:21 +08:00
DrSmoothl
b918450483 fix(protocol): set_group_special_title — send uinName so the title actually applies
The 0x8FC_2 body omitted uinName (tag 7), so the server accepted the request
(errorCode 0) but silently never applied the title — looking like the feature
was unsupported. Both NapCat (Oidb.0x8FC_2: uinName=title) and Lagrange
(0x8FC body @7 UinName=title) set it; mirror them by sending uinName = title.

No RE needed — two independent packet-based implementations agree on the field.

Note: setting a special title is group-owner-only, so on-target validation
requires a group the bot owns.
2026-06-22 21:53:33 +08:00
snowluma-bot[bot]
157cc90397 Merge pull request #132 from SnowLuma/dev
chore: promote dev → main (1bd1265)
2026-06-22 13:31:34 +00:00
DrSmoothl
1bd126562f chore(release): v1.10.2 2026-06-22 21:31:06 +08:00
DrSmoothl
e160837f8b feat(onebot): tiered reply backfill + quoted-file recovery for get_msg (#128)
Harvests the sound ideas from PR #128 while KEEPING origSeqs[0] as the c2c
reply sequence (on-target capture in #114/#124 proved origSeqs[0] == the quoted
message's head.sequence; pbReserve.friendSequence is a small unrelated counter
that makes reply.id miss). The PR's friendSequence override is intentionally
NOT taken.

- rich-body-decoder: enrich the reply element with replySenderUin/replyTime and
  the quoted message's own decoded elements (SrcMsg.elems, field 5); recover a
  c2c quoted FILE from sourceMsg (field 9 -> RichText.notOnlineFile) when elems
  carried none, so a quoted file survives into get_msg (#124).
- backfillReplyTarget: tiered fallback — Tier 0 local store, Tier 1 server fetch
  (correct seq = origSeqs[0]), Tier 2 reconstruct from the embedded quoted
  elements (no round-trip), Tier 3 minimal '[引用消息]' placeholder so get_msg
  never returns 'message not found'.
- to-segment: per-element try/catch (logged, not silent) so one bad element
  doesn't drop the whole message.
- actions/message: log get_msg misses.
- tests: fix request-actions getGroupInviteCardSequence mock (gap from #125);
  cover backfill Tier 2 (reconstruct) + Tier 3 (placeholder); flip the stale
  c2c reply test to assert origSeqs[0] (was asserting the disproven
  friendSequence).

Validated on-target (Docker): get_msg on group reply, private text reply, and a
private quoted FILE all return correct content (file with name/size/id); full
onebot + protocol suites green.
2026-06-22 21:25:05 +08:00
DrSmoothl
4593ba3340 fix(protocol): strip reply auto-mention on receive; align send to uin=0 (#127)
A QQ NT reply carries the replied sender as a structural auto-mention
(MentionExtra.type=2, uin=0) right after srcMsg, plus a blank separator
text. SnowLuma reported both as a real [CQ:at] + empty/space segment, so
downstreams saw a phantom @ (#127). A real user @ carries a non-zero
MentionExtra.uin, so it is preserved.

- receive (rich-body-decoder): after a reply, drop a type=2/uin=0 mention
  and the blank text that follows it; keep non-zero-uin mentions.
- send (element-builder, #129 follow-up): the reply auto-mention added for
  reply+@ now uses uin=0 (real uid stays in `uid`) to match QQ's native wire
  shape, so the bot's own replies are stripped the same way by receivers and
  don't surface a phantom @ either.

Validated on-target (Docker, group): reply w/o @ -> [reply, text] (no
phantom @/empty); reply w/ @ -> [reply, at(real), text]; bot reply+@ still
delivers the @ (uin=0).
2026-06-22 20:53:10 +08:00
DrSmoothl
45aae92af5 fix(protocol): group reply+at — emit replied-sender mention after srcMsg (#129)
When a group message combined a reply with a user @ , the @ showed but
never notified (no blue link, no ping). On-target capture showed SnowLuma
sent [srcMsg, @target(mention), text] — the @ lands directly in the reply's
mention slot right after srcMsg, which the QQ NT group server does not honor.

Mirror Lagrange's ForwardEntity.PackElement: when a reply and an @ coexist
in a group message, emit the replied sender as a trailing mention element
right after srcMsg, so the user's @ is no longer the first post-srcMsg
element and is honored. Gated to the reply+@ case so plain replies are
unchanged.

Validated on-target (Docker, group send): baseline reply+at -> @ not
delivered; fixed -> @ delivered (blue link + notification).
2026-06-22 20:37:19 +08:00
DrSmoothl
839de51519 fix(protocol): c2c reply uses origSeqs[0], not friendSequence (#114, #124)
A private (c2c) reply resolved to srcMsg.reserve.friendSequence, but a
received message's message_id is hashed from its head.sequence. On-target
capture showed origSeqs[0] == head.sequence (e.g. 12709) while friendSequence
is a small friend-relationship counter (e.g. 25) — so reply.id != the quoted
message_id. Downstream get_msg(reply_id) then missed:

- #114: reported reply id didn't match the quoted message's real id.
- #124: replying to a File message returned empty quoted content (AstrBot
  relies on get_msg(reply_id) to learn the quote was a file; text replies
  appeared fine because they read the inline follow-up text instead).

Drop the c2c friendSequence override (reverting cf8e62d's premise, which was
backwards) so both group and c2c replies use origSeqs[0].

Validated on-target (Docker): file message id == reply.id, and
get_msg(reply_id) -> retcode 0, message [{type:file}].
2026-06-22 16:07:36 +08:00
DrSmoothl
11e7584d1c fix(onebot): approve bot self-invite via private card msgseq (#125)
When the bot is invited to a group via a private-chat "qun.invite" ark
card, set_group_add_request failed: handleGroupAddRequest re-derived the
approval tuple from fetchGroupRequests (0x10c8_2), but for a self-invite the
only sequence the server accepts at 0x10c8_1 is the msgseq embedded in the
card's mqqapi://group/invite_join jumpUrl, applied with eventType=2 /
filtered=false. The MSF invite push (PkgType 87) never carries that msgseq,
so approval returned 120161001 'handle async message fail'.

- friend-message decoder: parse the private invite card's jumpUrl and stash
  groupUin -> msgseq on the per-instance IdentityService.
- ContactsApi.getGroupInviteCardSequence(groupId) exposes it.
- handleGroupAddRequest: for an invite flag, if a card msgseq is cached,
  approve with setAddRequest(groupId, msgseq, 2, approve, reason, false);
  otherwise fall back to the existing fetchGroupRequests path.

Validated on-target (Docker): private invite card -> set_group_add_request
approve -> 0x10c8_1 ok -> bot joined the group (get_group_member_info shows
role=member, fresh join_time); no 120161001.
2026-06-22 15:25:28 +08:00
snowluma-bot[bot]
f470b7a10c Merge pull request #122 from SnowLuma/dev
chore: promote dev → main (8b87f80)
2026-06-21 17:45:50 +00:00
DrSmoothl
8b87f80951 chore(release): v1.10.1 2026-06-22 01:45:25 +08:00
DrSmoothl
b135752577 fix(highway): retry chunk upload on transient transport errors (#118)
Large private files (e.g. 48 MB .flac via send_private_msg) failed with
"connection closed before response (received 0 bytes, headerSeen=false)".
uploadHighwayHttp sends one fresh TCP connection per 1 MB chunk with no
retry, so a 48 MB file is ~48 sequential connections and a single transient
peer-FIN / reset among them aborted the entire upload. Small files (1 chunk)
always worked; NapCat is unaffected because it delegates to QQ's native
highway client, which retries.

Wrap each chunk's connect + POST in a bounded retry (3 attempts, 300 ms ×
attempt backoff, fresh connection each time). Re-sending the same offset
range is idempotent server-side. Only transport failures retry; a decoded
highway error_code is a definitive server reject and is not retried.
2026-06-22 01:45:12 +08:00
snowluma-bot[bot]
fd2345b772 chore(native): replace native artifacts (native-latest) (#121)
Build: https://github.com/SnowLuma/SnowLumaNative/releases/tag/native-latest

Co-authored-by: snowluma-bot[bot] <283088347+snowluma-bot[bot]@users.noreply.github.com>
2026-06-22 01:41:50 +08:00
snowluma-bot[bot]
7f391e065e Merge pull request #117 from SnowLuma/dev
chore: promote dev → main (9efe162)
2026-06-21 12:23:09 +00:00
snowluma-bot[bot]
261d6596dc Merge pull request #109 from SnowLuma/dev
chore: promote dev → main (dfb6aa5)
2026-06-18 09:16:43 +00:00
snowluma-bot[bot]
5d08fc8471 Merge pull request #103 from SnowLuma/dev
chore: promote dev → main (16920b4)
2026-06-16 14:00:12 +00:00
snowluma-bot[bot]
e5e6d50f2f Merge pull request #101 from SnowLuma/dev
chore: promote dev → main (7e59dbf)
2026-06-15 05:58:03 +00:00
snowluma-bot[bot]
7d90820e19 Merge pull request #100 from SnowLuma/dev
chore: promote dev → main (ee8eb92)
2026-06-14 08:29:02 +00:00
snowluma-bot[bot]
69195ced93 Merge pull request #95 from SnowLuma/dev
chore: promote dev → main (a3a3671)
2026-06-11 08:42:47 +00:00
snowluma-bot[bot]
d2c56d565b Merge pull request #92 from SnowLuma/dev
chore: promote dev → main (d508814)
2026-06-09 06:23:12 +00:00
snowluma-bot[bot]
cc27cd1f43 Merge pull request #89 from SnowLuma/dev
chore: promote dev → main (515bac4)
2026-06-07 14:30:05 +00:00
snowluma-bot[bot]
40c65c87bd Merge pull request #88 from SnowLuma/dev
chore: promote dev → main (174150c)
2026-06-07 13:20:48 +00:00
282 changed files with 33412 additions and 4436 deletions

View File

@@ -18,13 +18,15 @@ body:
required: true
- label: 我使用的是 [最新 Release](https://github.com/SnowLuma/SnowLuma/releases) 或当前 `dev` 分支构建
required: true
- label: 我已将日志级别调到 TRACE,并在下方「TRACE 日志」一栏附上了复现期间的完整日志
required: true
- type: input
id: snowluma-version
attributes:
label: SnowLuma 版本
description: 启动日志首行或 `package.json` 里的版本号
placeholder: "例如 1.8.5"
placeholder: "例如 1.10.2"
validations:
required: true
@@ -53,6 +55,19 @@ body:
validations:
required: true
- type: dropdown
id: deploy
attributes:
label: 部署方式
description: 如何运行 SnowLuma
options:
- 源码运行(pnpm dev / start)
- 预构建包
- Docker
- 其他 / 不确定
validations:
required: true
- type: input
id: node-version
attributes:
@@ -106,11 +121,21 @@ body:
- type: textarea
id: logs
attributes:
label: 相关日志 / 错误堆栈
label: TRACE 日志 / 错误堆栈
description: |
粘贴控制台日志、SSE 实时日志或错误堆栈。
请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现。
开启 TRACE 的两种方式(任选其一):
- **WebUI(推荐)**:进入「日志」页 →「服务端日志级别」切到 `TRACE` → 显示过滤切到「开发」预设(确保 TRACE 行可见,否则导出不含 trace)→ 复现问题 → 点「导出当前视图」得到 `snowluma-logs-*.log`,拖到本输入框上传。
- **环境变量**:启动前设置 `SNOWLUMA_LOG_LEVEL=trace` 再运行,复现后复制控制台输出。
贴出的日志里应当能看到 `TRACE` 字样。请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。
placeholder: |
[2026-06-26 12:00:00.000] TRACE [core] ...
[2026-06-26 12:00:00.001] DEBUG [bridge] ...
render: shell
validations:
required: true
- type: textarea
id: extra

View File

@@ -66,11 +66,13 @@ body:
- OneBot v11 规范: https://github.com/botuniverse/onebot-11/...
- 相关讨论: #xxx
- type: checkboxes
- type: dropdown
id: willingness
attributes:
label: 您是否愿意提交 PR 来实现这个功能?
options:
- label: 愿意,且需要维护者讨论方案后再动手
- label: 愿意,已有大致实现思路
- label: 暂时只提建议
- 愿意,但需要维护者讨论方案后再动手
- 愿意,已有大致实现思路
- 暂时只提建议
validations:
required: true

17
.github/pull_request_template.md vendored Normal file
View File

@@ -0,0 +1,17 @@
<!-- 感谢贡献。请填写以下内容,方便评审。 -->
## 关联 Issue
<!-- 例如 Closes #123。若无关联 issue,请说明这个 PR 解决什么问题、为何现在做。 -->
## 变更说明
<!-- 简述本 PR 做了什么、为什么这样做。 -->
## 提交前检查
- [ ] 本 PR 聚焦单一目标,未夹带无关改动
- [ ] 已通过 `pnpm lint` 与 `pnpm typecheck`
- [ ] 已补充/更新相关测试,且 `pnpm test` 通过
- [ ] 文件行尾为 LF(未引入 CRLF)
- [ ] PR 描述与实际实现一致

View File

@@ -41,3 +41,13 @@ jobs:
- name: Run all package tests
run: pnpm -r --no-bail --if-present test
# The MCP test suite regenerates the action catalog (catalog.ts + the
# catalog.json the docs site consumes). Fail if the committed snapshot
# drifted from the live specs — keeps the API docs from going stale.
- name: Verify generated action catalog is up to date
run: |
if ! git diff --exit-code -- packages/mcp/src/generated; then
echo '::error::Generated action catalog is stale. Run `pnpm --filter @snowluma/mcp gen` and commit packages/mcp/src/generated/.' >&2
exit 1
fi

View File

@@ -7,6 +7,15 @@ on:
tags-ignore:
- 'v*'
# Only `dev` gets a shared, self-cancelling group so a newer dev commit
# supersedes the in-flight one (and its Docker dispatch) before it publishes.
# Every other branch falls back to a unique per-run group (github.run_id), so
# their concurrency behavior is unchanged — no shared-group pending-run
# replacement, no accidental serialization.
concurrency:
group: ${{ github.ref == 'refs/heads/dev' && format('{0}-{1}', github.workflow, github.ref) || github.run_id }}
cancel-in-progress: ${{ github.ref == 'refs/heads/dev' }}
jobs:
cleanup:
runs-on: ubuntu-latest
@@ -14,10 +23,20 @@ jobs:
actions: write
contents: read
steps:
# Delete only artifacts older than 24h. The dev Docker hand-off relies on
# this run's fresh `snowluma-dev-docker-*` artifact still existing when the
# downstream (cross-repo) Docker build downloads it; a blanket "delete all"
# here — which also runs on every other branch's push — could race-delete
# an in-flight hand-off artifact. Age-gating keeps recent ones safe while
# still reaping the backlog.
- name: Delete old artifacts
uses: actions/github-script@v8
with:
script: |
const cutoff = Date.now() - 24 * 60 * 60 * 1000;
// Collect every artifact first, THEN delete — deleting mid-pagination
// shifts the list and would skip ~a page of old artifacts per delete.
const all = [];
let page = 1;
while (true) {
const { data: { artifacts } } = await github.rest.actions.listArtifactsForRepo({
@@ -27,16 +46,20 @@ jobs:
page,
});
if (artifacts.length === 0) break;
for (const artifact of artifacts) {
await github.rest.actions.deleteArtifact({
owner: context.repo.owner,
repo: context.repo.repo,
artifact_id: artifact.id,
});
console.log(`Deleted artifact: ${artifact.name}`);
}
all.push(...artifacts);
page++;
}
for (const artifact of all) {
if (new Date(artifact.created_at).getTime() >= cutoff) {
continue; // keep recent artifacts (may be in-flight dev hand-offs)
}
await github.rest.actions.deleteArtifact({
owner: context.repo.owner,
repo: context.repo.repo,
artifact_id: artifact.id,
});
console.log(`Deleted artifact: ${artifact.name}`);
}
typecheck:
runs-on: ubuntu-latest
@@ -110,6 +133,13 @@ jobs:
SNOWLUMA_TARGET: ${{ matrix.target }}
run: pnpm run build:all
# Bundle production node_modules into dist/ before packaging — mirrors
# release.yml. Without this the `-lite` tarball has no runtime deps and the
# Docker image (which bakes the lite tarball) can't start.
- 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
@@ -140,3 +170,110 @@ jobs:
retention-days: 3
overwrite: true
if-no-files-found: error
# Deterministic-name hand-off artifact consumed by the cross-repo dev
# Docker build (SnowLuma.Docker.Framework/docker-image.yml downloads it by
# this exact name). linux-x64 only — dev images are amd64-only. Just the
# lite tarball; the container already ships its own Node runtime.
- name: Upload dev Docker hand-off artifact
if: matrix.name == 'linux-x64' && github.ref == 'refs/heads/dev'
uses: actions/upload-artifact@v7
with:
name: snowluma-dev-docker-linux-x64
path: SnowLuma-dev-linux-x64-lite.tar.gz
retention-days: 3
overwrite: true
if-no-files-found: error
# Fire the "latest dev" Docker build on SnowLuma.Docker.Framework — but only
# for `dev`. Mirrors release.yml's dispatch-docker, parameterized for dev:
# tag=dev (rolling) + sha_tag=dev-<12sha> (immutable), also_latest=false so it
# never touches the stable :latest, platforms=amd64, and artifact_run_id so the
# downstream build pulls THIS run's hand-off artifact instead of a Release.
dispatch-dev-docker:
needs: [build]
if: github.ref == 'refs/heads/dev'
runs-on: ubuntu-latest
environment: SnowLuma
permissions:
contents: read
steps:
- name: Compute short SHA
id: sha
run: echo "short=${GITHUB_SHA:0:12}" >> "$GITHUB_OUTPUT"
- name: Dispatch dev Docker build
uses: actions/github-script@v8
env:
RELEASE_REPOSITORY: ${{ vars.DOCKER_RELEASE_REPOSITORY }}
DOCKER_IMAGE: ${{ vars.DOCKER_IMAGE }}
DOCKER_WORKFLOW: ${{ vars.DOCKER_WORKFLOW }}
DOCKER_REF: ${{ vars.DOCKER_REF }}
SHA_TAG: dev-${{ steps.sha.outputs.short }}
ARTIFACT_RUN_ID: ${{ github.run_id }}
with:
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
script: |
const target = process.env.RELEASE_REPOSITORY;
if (!target || !target.includes('/')) {
throw new Error('Set SnowLuma environment variable DOCKER_RELEASE_REPOSITORY to owner/repo.');
}
const [owner, repo] = target.split('/');
const sourceRepo = context.repo.owner + '/' + context.repo.repo;
const image = process.env.DOCKER_IMAGE || 'motricseven7/snowluma';
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
const ref = process.env.DOCKER_REF || 'main';
const runId = String(process.env.ARTIFACT_RUN_ID);
const shaTag = process.env.SHA_TAG;
await github.rest.actions.createWorkflowDispatch({
owner,
repo,
workflow_id: workflowId,
ref,
inputs: {
image,
tag: 'dev',
push: 'true',
platforms: 'linux/amd64',
also_latest: 'false',
snowluma_repository: sourceRepo,
artifact_run_id: runId,
sha_tag: shaTag,
},
});
core.info(`Dispatched ${workflowId}@${ref} on ${target} for dev (image=${image}:dev + :${shaTag}, src run ${runId}).`);
// Best-effort: resolve the dispatched run by its unique run-name
// marker so the summary links straight to it (every dev dispatch is
// tag=dev, so we key on the source run id, not the tag).
const marker = `(src-run ${runId})`;
let runUrl = '';
for (let i = 0; i < 6 && !runUrl; i++) {
await new Promise((r) => setTimeout(r, 5000));
try {
const { data } = await github.rest.actions.listWorkflowRuns({
owner,
repo,
workflow_id: workflowId,
event: 'workflow_dispatch',
per_page: 30,
});
const hit = data.workflow_runs.find(
(r) => (r.display_title || r.name || '').includes(marker),
);
if (hit) runUrl = hit.html_url;
} catch (e) {
core.warning(`Downstream run lookup failed: ${e.message}`);
}
}
const workflowUrl = `https://github.com/${owner}/${repo}/actions/workflows/${workflowId}`;
await core.summary
.addHeading('dev Docker dispatch', 3)
.addList([
`source SHA: ${context.sha}`,
`source run id: ${runId}`,
`image: ${image}:dev + ${image}:${shaTag}`,
`downstream run: ${runUrl || `(not resolved yet — see ${workflowUrl}, look for ${marker})`}`,
])
.write();

View File

@@ -0,0 +1,94 @@
name: 校验 Bug 反馈日志
# 表单只能强制「非空」,强制不了「内容真的是 TRACE 级别」。
# 这个 workflow 在 bug issue 打开/编辑时解析正文里的 TRACE 日志小节,
# 缺日志就打 needs-logs 标签 + 评论,补齐后自动移除标签。
on:
issues:
types: [opened, edited]
permissions:
issues: write
jobs:
require-trace-logs:
runs-on: ubuntu-latest
# 只校验 Bug 反馈(表单会自动打 bug 标签)
if: contains(join(github.event.issue.labels.*.name, ','), 'bug')
steps:
- uses: actions/github-script@v7
with:
script: |
const NEEDS = 'needs-logs';
const MARKER = '<!-- needs-logs-bot -->';
const { owner, repo } = context.repo;
const issue = context.payload.issue;
const number = issue.number;
const body = issue.body || '';
// 抽取「TRACE 日志 / 错误堆栈」小节(issue form 渲染成 ### 标题)
const m = body.match(/###\s*TRACE 日志[^\n]*\n([\s\S]*?)(?:\n###\s|$)/);
const section = (m ? m[1] : '').trim();
// 粘贴的终端日志常带 ANSI 颜色码(如 \x1b[90mTRACE\x1b[0m),
// 颜色码结尾的 'm' 紧贴 TRACE 会吃掉 \b 单词边界,先剥掉再判定。
const clean = section.replace(/\x1b\[[0-9;]*m/g, '');
const empty = section === '' || /^_no response_$/i.test(section);
const hasTrace = /\bTRACE\b/i.test(clean);
// 去掉代码围栏后过短,基本等于没给
const stripped = clean.replace(/```[a-z]*|```|`/gi, '').trim();
const tooShort = stripped.length < 40;
const ok = !empty && hasTrace && !tooShort;
const hasLabel = (issue.labels || []).some((l) => (l.name || l) === NEEDS);
if (ok) {
if (hasLabel) {
try {
await github.rest.issues.removeLabel({ owner, repo, issue_number: number, name: NEEDS });
} catch (e) { /* 已被手动移除则忽略 */ }
}
return;
}
// 确保标签存在再添加(addLabels 不会自动建标签)
try {
await github.rest.issues.getLabel({ owner, repo, name: NEEDS });
} catch (e) {
try {
await github.rest.issues.createLabel({
owner, repo, name: NEEDS, color: 'd93f0b',
description: '缺少有效的 TRACE 日志',
});
} catch (e2) { /* 并发下可能已被建出 */ }
}
await github.rest.issues.addLabels({ owner, repo, issue_number: number, labels: [NEEDS] });
// 已经提示过就不再刷屏
const comments = await github.paginate(github.rest.issues.listComments, {
owner, repo, issue_number: number,
});
if (comments.some((c) => (c.body || '').includes(MARKER))) return;
const reasons = [];
if (empty) reasons.push('- 日志字段为空');
else if (!hasTrace) reasons.push('- 日志里没有 `TRACE` 字样(默认级别 `info` 不输出 TRACE,需先开启)');
else if (tooShort) reasons.push('- 日志内容过短,疑似未提供完整日志');
const comment = [
MARKER,
`@${issue.user.login} 这条反馈缺少有效的 **TRACE 级别日志**,已标记为 \`${NEEDS}\`:`,
'',
reasons.join('\n'),
'',
'请按以下任一方式开启 TRACE 后复现,再 **编辑本 issue** 把完整日志补到「TRACE 日志 / 错误堆栈」一栏:',
'',
'- **WebUI**:「日志」页 → 服务端日志级别切到 `TRACE` → 显示过滤用「开发」预设 → 复现 → 导出当前视图。',
'- **环境变量**:`SNOWLUMA_LOG_LEVEL=trace` 启动后复现。',
'',
'补齐后机器人会自动移除该标记。若你以附件形式上传了 `.log` 文件,请在正文里也贴一段关键日志(机器人只能识别正文)。',
].join('\n');
await github.rest.issues.createComment({ owner, repo, issue_number: number, body: comment });

View File

@@ -0,0 +1,65 @@
name: Issue template guard
# Blank / free-form issues bypass `blank_issues_enabled: false` (it only hides
# the chooser link — the CLI, API and direct URLs still create template-less
# issues). This guard enforces the policy after the fact: an issue opened by
# someone WITHOUT write access that did not go through a template (no template
# label) is commented on and closed. Properly-filed bug reports / feature
# requests (which carry `bug` / `enhancement`) and anyone with write access are
# left alone.
#
# Note: workflows for `issues` events run from the file on the DEFAULT branch,
# so this only takes effect once it lands on `main`.
on:
issues:
types: [opened]
permissions:
issues: write
jobs:
guard:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v7
with:
script: |
const issue = context.payload.issue;
// Write-access roles are exempt.
const privileged = ['OWNER', 'MEMBER', 'COLLABORATOR'];
if (privileged.includes(issue.author_association)) {
core.info(`author_association=${issue.author_association} — allowed`);
return;
}
// A template was used iff it stamped its label.
const TEMPLATE_LABELS = ['bug', 'enhancement'];
const labels = (issue.labels || []).map((l) => (typeof l === 'string' ? l : l.name));
if (labels.some((l) => TEMPLATE_LABELS.includes(l))) {
core.info('template label present — allowed');
return;
}
// Non-privileged + no template → guide and close.
const { owner, repo } = context.repo;
const chooser = `https://github.com/${owner}/${repo}/issues/new/choose`;
const body = [
'感谢你的反馈。',
'',
'本仓库的 issue 需要通过模板提交:请使用 **Bug 反馈** 或 **功能请求** 模板重新创建,',
'以便我们准确、高效地处理。直接创建的空白 / 自定义 issue 会被自动关闭。',
'',
`- 重新创建:${chooser}`,
'- 日常使用、快速交流类问题,可先到 README 中的 QQ 群',
'',
'本 issue 将自动关闭,感谢理解。',
].join('\n');
await github.rest.issues.createComment({ owner, repo, issue_number: issue.number, body });
await github.rest.issues.update({
owner, repo, issue_number: issue.number,
state: 'closed', state_reason: 'not_planned',
});
core.info(`closed #${issue.number} (author_association=${issue.author_association}, no template label)`);

34
.github/workflows/stale-needs-logs.yml vendored Normal file
View File

@@ -0,0 +1,34 @@
name: 关闭长期缺日志的反馈
# needs-logs 的 issue 若长期不补 TRACE 日志,先标 stale,再自动关闭。
# 补齐日志后 issue-require-logs 会移除 needs-logs,这里 only-labels 过滤即跳过。
on:
schedule:
- cron: '0 2 * * *'
workflow_dispatch:
permissions:
issues: write
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
only-labels: 'needs-logs'
days-before-stale: 7
days-before-close: 7
stale-issue-label: 'stale'
close-issue-reason: 'not_planned'
ascending: true
# 不处理 PR
days-before-pr-stale: -1
days-before-pr-close: -1
stale-issue-message: >
这条反馈因长期缺少有效的 TRACE 日志被标记为 `stale`。
若 7 天内仍未补充日志,将自动关闭。补充后请编辑 issue 贴上日志或留言。
close-issue-message: >
因长期缺少定位所需的 TRACE 日志,已自动关闭。
如果问题仍然存在,欢迎补齐 TRACE 日志后重新打开本 issue 或新开一个。

114
.github/workflows/sync-docs-catalog.yml vendored Normal file
View File

@@ -0,0 +1,114 @@
name: Sync action catalog to docs
# Regenerates the OneBot action catalog from @snowluma/onebot's specs and commits
# the plain-JSON twin (catalog.json) into the SnowLumaDocs repo, where the docs
# build turns it into the API Reference pages. Runs on main (the release/promote
# target) so the published docs always describe shipped behavior. Uses the same
# SnowLuma bot GitHub App as the promote-dev-to-main flow.
on:
push:
branches: [main]
paths:
- 'packages/onebot/src/actions/**'
- 'packages/onebot/src/action-kit.ts'
- 'packages/onebot/src/action-docs.ts'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: sync-docs-catalog
cancel-in-progress: true
jobs:
sync:
runs-on: ubuntu-latest
steps:
- name: Checkout SnowLuma
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Generate catalog.json
run: pnpm --filter @snowluma/mcp gen
- name: Validate GitHub App credentials
env:
APP_ID: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
PRIVATE_KEY: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
run: |
if [ -z "${APP_ID}" ] || [ -z "${PRIVATE_KEY}" ]; then
echo 'Missing SNOWLUMA_BOT_APP_ID and/or SNOWLUMA_BOT_PRIVATE_KEY secrets.' >&2
echo 'Configure the same GitHub App used by the promote-dev-to-main flow.' >&2
exit 1
fi
- name: Mint GitHub App installation token (scoped to SnowLumaDocs)
id: app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
private-key: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
repositories: SnowLumaDocs
- name: Resolve bot identity
id: bot
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
APP_SLUG: ${{ steps.app-token.outputs.app-slug }}
run: |
set -euo pipefail
bot_login="${APP_SLUG}[bot]"
bot_id="$(gh api "/users/${bot_login}" --jq .id)"
bot_email="${bot_id}+${bot_login}@users.noreply.github.com"
{
echo "login=${bot_login}"
echo "email=${bot_email}"
} >> "${GITHUB_OUTPUT}"
- name: Commit catalog.json to docs repo
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
BOT_LOGIN: ${{ steps.bot.outputs.login }}
BOT_EMAIL: ${{ steps.bot.outputs.email }}
OWNER: ${{ github.repository_owner }}
run: |
set -euo pipefail
src="$(pwd)/packages/mcp/src/generated/catalog.json"
tmp="$(mktemp -d)"
git clone --depth 1 \
"https://x-access-token:${GH_TOKEN}@github.com/${OWNER}/SnowLumaDocs.git" "$tmp"
mkdir -p "$tmp/docs/public/api"
cp "$src" "$tmp/docs/public/api/catalog.json"
cd "$tmp"
git config user.name "${BOT_LOGIN}"
git config user.email "${BOT_EMAIL}"
# Stage first: `git diff --quiet` ignores UNTRACKED files, so on the
# initial sync (catalog.json not yet in the docs repo) the index diff
# is the only reliable change check.
git add docs/public/api/catalog.json
if git diff --cached --quiet; then
echo "::notice::catalog.json unchanged; nothing to sync."
exit 0
fi
git commit -m "chore(api): sync action catalog from SnowLuma@${GITHUB_SHA::7}"
# Single writer, but guard against a concurrent docs commit racing the
# shallow clone: rebase onto the latest main before pushing.
git pull --rebase --depth 1 origin main
git push origin HEAD:main

6
.gitignore vendored
View File

@@ -11,7 +11,13 @@ dist/
/config/
/data/
# per-package runtime data dirs (e.g. packages/core/data/<uin>/*.db written by
# IdentityService during tests) — not just the root /data/
**/data/
logs/
# macOS metadata
.DS_Store
# test coverage output
coverage/

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.10.0",
"version": "1.11.3",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -16,6 +16,9 @@
"dev:web": "pnpm --filter webui dev",
"test": "pnpm --filter @snowluma/core test",
"test:watch": "pnpm --filter @snowluma/core test:watch",
"test:common": "pnpm --filter @snowluma/common test",
"test:all": "pnpm -r --if-present test",
"coverage": "pnpm --filter @snowluma/common test -- --coverage",
"typecheck": "pnpm -r --if-present typecheck",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
@@ -44,7 +47,11 @@
},
"onlyBuiltDependencies": [
"better-sqlite3"
]
],
"overrides": {
"esbuild@<0.28.1": "^0.28.1",
"@babel/core@<7.29.6": "^7.29.6"
}
},
"packageManager": "pnpm@10.28.0",
"engines": {

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.10.0",
"version": "1.11.3",
"private": true,
"type": "module",
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",

View File

@@ -6,10 +6,12 @@ import { HookSession, type HookSessionDeps } from './hook-session';
import {
injectHookProcess,
listHookProcesses,
resolveHookNativePath,
unloadHookProcess,
type HookProcessBaseInfo,
} from './injector';
import { PipeWatcher } from './pipe-watcher';
import { createNativeProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
import { QqHookClient } from './qq-hook-client';
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
import type { HookProcessInfo } from './types';
@@ -49,6 +51,13 @@ export type HookManagerDeps = {
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
* Failed loads are logged and leave the session in the 'error' state. */
autoLoadOnDiscovery?: boolean;
/** Optional hook fired whenever the set of HookProcessInfo observable to
* `listProcesses()` changes — new process discovered, process gone, or
* any session's status mutated. Used by the WebUI SSE wiring to push a
* fresh processes snapshot to connected clients without REST polling.
* Exceptions thrown by the callback are caught and logged; they do not
* break the watcher / session event loops. */
onSessionsChanged?: () => void;
log?: Logger;
};
@@ -74,8 +83,15 @@ export class HookManager {
private readonly makeClient: HookSessionDeps['makeClient'];
private readonly pipeWatcher: PipeWatcher;
private readonly ownsPipeWatcher: boolean;
private readonly listProcessesNative: () => HookProcessBaseInfo[];
/** Watcher/API process enumeration — isolated + timeout-bounded by default
* so a blocked native /proc walk can't freeze the loop (issue #158).
* Resolves to `null` (UNKNOWN) on timeout/failure. */
private readonly enumerate: () => Promise<HookProcessBaseInfo[] | null>;
/** The owned enumerator (worker lifecycle), or null when a custom lister was
* injected (tests) — nothing to tear down in that case. */
private readonly enumerator: ProcessEnumerator | null;
private readonly autoLoadOnDiscovery: boolean;
private readonly onSessionsChangedRaw?: () => void;
private readonly log: Logger;
private readonly sessions = new Map<number, HookSession>();
private readonly startPromise: Promise<void>;
@@ -85,6 +101,7 @@ export class HookManager {
constructor(deps: HookManagerDeps) {
this.bridgeManager = deps.bridgeManager;
this.onPacket = deps.onPacket ?? ((pkt) => deps.bridgeManager.onPacket(pkt));
this.onSessionsChangedRaw = deps.onSessionsChanged;
this.log = deps.log ?? createLogger('Hook');
this.injector = deps.injector ?? {
@@ -95,15 +112,38 @@ export class HookManager {
},
};
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
this.listProcessesNative = deps.listProcesses ?? listHookProcesses;
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
// A custom lister (tests) is used directly — no worker, no isolation, just
// an async wrap that maps a throw to the UNKNOWN sentinel. The default path
// wraps the native enumerator in a worker with a timeout.
if (deps.listProcesses) {
const lister = deps.listProcesses;
this.enumerator = null;
this.enumerate = async () => {
try {
return await lister();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
return null;
}
};
} else {
this.enumerator = createNativeProcessEnumerator({
addonPath: resolveHookNativePath('node'),
fallbackSync: listHookProcesses,
processName: defaultProcessName(),
log: this.log,
});
this.enumerate = () => this.enumerator!.enumerate();
}
if (deps.pipeWatcher) {
this.pipeWatcher = deps.pipeWatcher;
this.ownsPipeWatcher = false;
} else {
this.pipeWatcher = new PipeWatcher({
listProcesses: this.listProcessesNative,
listProcesses: this.enumerate,
listLivePipes: () => QqHookClient.listLivePipes(),
intervalMs: deps.watcherIntervalMs,
log: this.log,
@@ -119,12 +159,13 @@ export class HookManager {
async listProcesses(): Promise<HookProcessInfo[]> {
await this.startPromise;
let processes: HookProcessBaseInfo[];
try {
processes = this.listProcessesNative();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
processes = [];
const processes = await this.enumerate();
if (processes === null) {
// Enumeration timed out / failed — report the last-known sessions rather
// than an empty list (which the WebUI would render as "no QQ").
return [...this.sessions.values()]
.map((s) => s.toInfo())
.sort((a, b) => a.pid - b.pid);
}
const result: HookProcessInfo[] = [];
for (const proc of processes) {
@@ -172,6 +213,7 @@ export class HookManager {
session.dispose();
}
this.sessions.clear();
this.enumerator?.dispose();
if (this.ownsPipeWatcher) {
this.pipeWatcher.dispose();
}
@@ -193,11 +235,13 @@ export class HookManager {
this.log.warn('auto-load failed: PID=%d err=%s', info.pid, errMsg(err));
});
}
this.notifySessionsChanged();
});
this.pipeWatcher.on('process-gone', (pid: number) => {
if (this.disposed) return;
const session = this.sessions.get(pid);
if (session) session.notifyProcessGone();
this.notifySessionsChanged();
});
this.pipeWatcher.on('pipe-up', (pid: number) => {
if (this.disposed) return;
@@ -253,6 +297,12 @@ export class HookManager {
session.on('disconnected', (wasLoggedIn: boolean) => {
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
});
// status-changed fires on EVERY internal status mutation, including the
// ones reached via login / disconnected / refresh — subscribing here
// alone covers every transition the WebUI processes view cares about.
session.on('status-changed', () => {
this.notifySessionsChanged();
});
session.on('disposed', () => {
this.sessions.delete(pid);
});
@@ -261,6 +311,19 @@ export class HookManager {
return session;
}
/** Fire the optional sessions-changed hook with exceptions isolated.
* A throwing subscriber must not abort the watcher's emit loop or break
* a HookSession event handler in flight. */
private notifySessionsChanged(): void {
if (this.disposed) return;
if (!this.onSessionsChangedRaw) return;
try {
this.onSessionsChangedRaw();
} catch (err) {
this.log.warn('onSessionsChanged threw: %s', errMsg(err));
}
}
private assertValidPid(pid: number): void {
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
}

View File

@@ -1,17 +1,29 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { PacketSink } from '@snowluma/common/protocol-types';
import { isRealUin } from '@snowluma/common/uin';
import { EventEmitter } from 'events';
import { HookPacketClient } from './hook-packet-client';
import type { HookInjectResult } from './injector';
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
import { statusFor } from './hook-status';
import type { HookProcessInfo, HookProcessStatus } from './types';
/** How often to actively re-probe QQ's login state while connected but not yet
* logged in — the safety net for a login the native hook never pushed (Docker
* auto-login races/bypasses the pushed loginState frame). */
const LOGIN_RECONCILE_INTERVAL_MS = 3000;
export type HookSessionDeps = {
injector: {
inject: (pid: number) => HookInjectResult;
unload: (pid: number, handle: HookInjectResult['handle']) => void;
};
makeClient: (pid: number) => QqHookClient;
/** Active, pipe-independent login probe (reads QQ's ptlogin/deeplink ports).
* Drives the login-reconcile safety net; injectable for tests. Defaults to
* `probeQqLoginInfo`. */
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
/** Sync fast-path check used by load() to skip re-injection when a
* prior SnowLuma run left a working pipe behind. `tickNow` forces a
* fresh poll — used after unload to dodge the up-to-1500ms cache
@@ -49,6 +61,7 @@ export class HookSession extends EventEmitter {
private readonly injector: HookSessionDeps['injector'];
private readonly makeClient: HookSessionDeps['makeClient'];
private readonly probeLogin: (pid: number) => Promise<QqPortLoginInfo | null>;
private readonly pipeWatcher: HookSessionDeps['pipeWatcher'];
private readonly onPacket: PacketSink | null;
private readonly log: Logger;
@@ -69,12 +82,15 @@ export class HookSession extends EventEmitter {
private bound = false;
private opChain: Promise<unknown> = Promise.resolve();
private disposed = false;
private loginProbeTimer: ReturnType<typeof setInterval> | null = null;
private probing = false;
constructor(pid: number, deps: HookSessionDeps) {
super();
this.pid = pid;
this.injector = deps.injector;
this.makeClient = deps.makeClient;
this.probeLogin = deps.probeLogin ?? probeQqLoginInfo;
this.pipeWatcher = deps.pipeWatcher;
this.onPacket = deps.onPacket ?? null;
this.log = deps.log ?? createLogger('HookSession');
@@ -131,17 +147,7 @@ export class HookSession extends EventEmitter {
if (this.disposed) return;
void this.serialize(async () => {
if (this.disposed) return;
// Adopt a DLL that survived a SnowLuma restart.
if (!this.injected) {
this.injected = true;
if (!this._method) this._method = 'reconnect';
}
if (this.client?.isClosed) this.tearDownClient();
if (!this.connected) {
await this.attemptConnect();
} else {
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
}
await this.reconcilePipeUp();
}).catch(err => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
}
@@ -149,18 +155,7 @@ export class HookSession extends EventEmitter {
if (this.disposed) return;
void this.serialize(async () => {
if (this.disposed) return;
if (!this.connected) {
// Nothing to tear down; just keep status visible.
if (this.injected) this.setStatus('connecting', this._error);
return;
}
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.setStatus(
this.injected ? (wasLoggedIn ? 'disconnected' : 'connecting') : 'available',
'',
);
if (wasLoggedIn) this.emit('disconnected', true);
this.reconcilePipeDown();
}).catch(err => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err)));
}
@@ -227,10 +222,7 @@ export class HookSession extends EventEmitter {
this._method = this.injectResult.method;
}
}
this.setStatus(
this.connected ? (this.loggedIn ? 'online' : 'loaded') : 'connecting',
'',
);
this.applyStatus();
} catch (error) {
this._error = errMsg(error);
this.setStatus('error', this._error);
@@ -281,24 +273,14 @@ export class HookSession extends EventEmitter {
private async refreshInternal(): Promise<HookProcessInfo> {
this._error = '';
try {
const pipeUp = this.pipeWatcher.isPipeLive(this.pid);
if (pipeUp) {
// Adopt an unknown DLL the same way onPipeUp would.
if (!this.injected) {
this.injected = true;
this._method = this._method || 'reconnect';
}
if (this.client?.isClosed) this.tearDownClient();
if (!this.connected) {
await this.attemptConnect();
} else {
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
}
// Same pipe-up / pipe-down reconcilers the watcher drives, chosen by
// a fresh poll. This collapses what used to be a hand-copied pair of
// onPipeUp/onPipeDown bodies — and fixes the drift where the down
// branch reported 'disconnected' even for a never-logged-in session.
if (this.pipeWatcher.isPipeLive(this.pid)) {
await this.reconcilePipeUp();
} else {
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.setStatus(this.injected ? 'disconnected' : 'available', '');
if (wasLoggedIn) this.emit('disconnected', true);
this.reconcilePipeDown();
}
} catch (error) {
this._error = errMsg(error);
@@ -308,6 +290,55 @@ export class HookSession extends EventEmitter {
return this.toInfo();
}
// ─────────────── settled-status reconcilers ───────────────
/** Push the settled status derived from the live flags. `wasLoggedIn`
* defaults to the current `loggedIn`; callers that just tore the client
* down pass the value captured *before* teardown (teardown clears it). */
private applyStatus(wasLoggedIn: boolean = this.loggedIn, error = ''): void {
this.setStatus(statusFor({
injected: this.injected,
connected: this.connected,
loggedIn: this.loggedIn,
wasLoggedIn,
}), error);
}
/** Pipe is up: adopt a DLL that survived a SnowLuma restart, drop a
* stale client, then (re)connect if needed or just settle the status.
* Shared by onPipeUp and refresh's pipe-up branch. */
private async reconcilePipeUp(): Promise<void> {
if (!this.injected) {
this.injected = true;
if (!this._method) this._method = 'reconnect';
}
if (this.client?.isClosed) this.tearDownClient();
if (!this.connected) {
await this.attemptConnect();
} else {
this.applyStatus();
}
}
/** Pipe is down (or the client closed): tear down, settle the status,
* and emit the disconnect notification iff we owed BridgeManager one
* (i.e. we had reached login). Shared by onPipeDown, refresh's pipe-down
* branch, and the client 'close' handler. */
private reconcilePipeDown(): void {
if (!this.connected) {
// Nothing live to tear down. A session that never connected can't owe
// a disconnect, and we must NOT clobber a diagnostic the failed
// connect/load already set — settle the status keeping `_error`, or
// (when not even injected) leave the status untouched entirely.
if (this.injected) this.applyStatus(this.loggedIn, this._error);
return;
}
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.applyStatus(wasLoggedIn);
if (wasLoggedIn) this.emit('disconnected', true);
}
// ─────────────── client plumbing ───────────────
private async attemptConnect(): Promise<void> {
@@ -327,15 +358,26 @@ export class HookSession extends EventEmitter {
try {
await client.connectAll({ recv: true });
this.connected = true;
this.setStatus(client.isLoggedIn ? 'online' : 'loaded', '');
const loginState = client.getLoginState();
if (loginState.loggedIn) this.handleLoginState(loginState);
// handleLoginState owns the connected+loggedIn → 'online' (+ login
// emit) transition; defer to it so the status is set once. Otherwise
// we're connected-but-not-logged-in → 'loaded'.
if (loginState.loggedIn) {
this.handleLoginState(loginState);
} else {
this.applyStatus();
// The native hook only PUSHES a loginState frame on the login edge;
// if QQ logged in before/around connect (Docker auto-login) that edge
// is missed and we'd wait forever. Actively re-probe until logged in.
this.startLoginReconcile();
}
this.log.info('pipe connected: PID=%d', this.pid);
} catch (error) {
this._error = errMsg(error);
// Drop the client so the next attempt builds a fresh socket pair.
// A failed connect was never logged in → 'connecting' (or 'available').
this.tearDownClient();
this.setStatus(this.injected ? 'connecting' : 'available', this._error);
this.applyStatus(false, this._error);
}
}
@@ -355,21 +397,13 @@ export class HookSession extends EventEmitter {
void this.serialize(async () => {
if (this.disposed) return;
if (this.client !== client) return;
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
if (!this.injected) {
this.setStatus('available', '');
} else if (wasLoggedIn) {
this.setStatus('disconnected', '');
} else {
this.setStatus('connecting', '');
}
if (wasLoggedIn) this.emit('disconnected', true);
this.reconcilePipeDown();
}).catch(err => this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)));
});
}
private tearDownClient(): void {
this.stopLoginReconcile();
const client = this.client;
if (client) {
client.removeAllListeners();
@@ -387,11 +421,18 @@ export class HookSession extends EventEmitter {
const previousUin = this._uin;
this._uin = state.uin || state.uinNumber.toString();
this.loggedIn = state.loggedIn && isRealUin(this._uin);
// However login was observed (pushed frame or the active probe), the
// safety net's job is done.
if (this.loggedIn) this.stopLoginReconcile();
if (this.loggedIn) {
this.setStatus('online', '');
} else if (this.connected) {
this.setStatus('loaded', this._error);
// Only the connected/logged-in states are ours to set here; when fully
// down we leave the status the teardown path already settled.
// Load-bearing invariant: `loggedIn ⇒ connected` (login can only be
// observed on a live client, and teardown clears `loggedIn` before
// `connected`), so statusFor lands 'online' here rather than the
// disconnected/connecting branch.
if (this.connected || this.loggedIn) {
this.applyStatus(wasLoggedIn, this.loggedIn ? '' : this._error);
}
if (!this.loggedIn || !this.sender) return;
@@ -401,6 +442,55 @@ export class HookSession extends EventEmitter {
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
}
// ─────────────── login reconcile (Docker auto-login safety net) ───────────
// The hook's loginState frame is edge-triggered (pushed only when the native
// observes the login transition). When that edge is missed — QQ auto-logged
// in before connect, or a silent session-restore path the hook doesn't
// intercept — we'd sit at 'loaded'/'connecting' forever. So while connected
// but not logged in, actively re-probe QQ's own ports and synthesize the
// login once it reports a real uin. Idempotent with the pushed-frame path
// (handleLoginState's wasLoggedIn guard dedups the 'login' emit).
private startLoginReconcile(): void {
if (this.loginProbeTimer || this.disposed) return;
void this.probeLoginOnce(); // immediate — catch already-logged-in fast
this.loginProbeTimer = setInterval(() => void this.probeLoginOnce(), LOGIN_RECONCILE_INTERVAL_MS);
this.loginProbeTimer.unref?.();
}
private stopLoginReconcile(): void {
if (this.loginProbeTimer) {
clearInterval(this.loginProbeTimer);
this.loginProbeTimer = null;
}
}
private async probeLoginOnce(): Promise<void> {
// A port-scan probe can outlast the interval; skip overlapping ticks so a
// slow probe never stacks concurrent subprocess-spawning scans.
if (this.probing) return;
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
this.probing = true;
try {
let info: QqPortLoginInfo | null;
try {
info = await this.probeLogin(this.pid);
} catch {
return; // best-effort; the interval retries
}
// The await yielded — re-check we still want this before mutating state.
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
if (info?.loggedIn && isRealUin(info.uin)) {
this.log.info('login reconciled via active probe: PID=%d UIN=%s', this.pid, info.uin);
// isRealUin guarantees a pure non-empty digit string, so BigInt() here
// cannot throw (keep that contract if isRealUin's regex is ever changed).
this.handleLoginState({ loggedIn: true, uin: info.uin, uinNumber: BigInt(info.uin) });
}
} finally {
this.probing = false;
}
}
private handlePacket(packet: QqHookPacket): void {
if (!this.loggedIn) return;
const uin = packet.uin || this._uin;
@@ -429,11 +519,6 @@ export class HookSession extends EventEmitter {
}
}
function isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}

View File

@@ -0,0 +1,31 @@
import type { HookProcessStatus } from './types';
/**
* The flags that fully determine a HookSession's *settled* status.
* `wasLoggedIn` carries the one bit of history the derivation needs:
* on ANY injected-but-not-connected path (connect failure, pipe close,
* refresh-while-down), the session reads `disconnected` only if it had
* reached login, otherwise it's still `connecting`. Capture it from
* `loggedIn` *before* tearing the client down, since teardown clears it.
*/
export interface HookFlags {
injected: boolean;
connected: boolean;
loggedIn: boolean;
wasLoggedIn: boolean;
}
/**
* Single source of truth for the five *settled* HookProcessStatus values
* — `available` / `connecting` / `loaded` / `online` / `disconnected`.
*
* Pure: status is a function of the flags alone. The two *out-of-band*
* states `loading` (injection in flight) and `error` (carries a message)
* are set explicitly by HookSession and are deliberately NOT derivable
* here.
*/
export function statusFor(flags: HookFlags): HookProcessStatus {
if (!flags.injected) return 'available';
if (flags.connected) return flags.loggedIn ? 'online' : 'loaded';
return flags.wasLoggedIn ? 'disconnected' : 'connecting';
}

View File

@@ -2,6 +2,8 @@ import { existsSync } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { listSnowlumaPipePidsSync } from './qq-hook-client';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export interface ManualMapHandle {
@@ -98,6 +100,17 @@ export function getNativeHookLoadError(): string | null {
}
export function listHookProcesses(): HookProcessBaseInfo[] {
// macOS: no native enumerate-QQ addon. The DYLD_INSERT injection model
// means QQ ran with our dylib already mapped, so the dylib's listener
// socket IS the discovery signal. Treat every `mojo.<pid>.control.sock`
// in the runtime dir as a known process (the watcher's subsequent
// connectable-probe gates the pipe-up emit, so a stale dangling socket
// here doesn't drive a false connect).
if (process.platform === 'darwin') {
return [...listSnowlumaPipePidsSync()]
.sort((a, b) => a - b)
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
}
const addon = getNativeHookAddon();
if (!addon) return [];
return [...new Set(addon.getAllMainProcess())]

View File

@@ -6,8 +6,11 @@ const DEFAULT_INTERVAL_MS = 1500;
const MIN_INTERVAL_MS = 250;
export type PipeWatcherDeps = {
/** Native: list QQ.exe processes currently running. */
listProcesses: () => HookProcessBaseInfo[];
/** Native: list QQ.exe processes currently running. May be async and may
* return `null` (UNKNOWN) when enumeration timed out / failed — in which
* case this tick keeps the prior process+pipe state instead of treating the
* missing data as "everything disappeared" (issue #158). */
listProcesses: () => HookProcessBaseInfo[] | null | Promise<HookProcessBaseInfo[] | null>;
/** Native: PIDs that currently have a live SnowLuma named pipe. */
listLivePipes: () => Promise<Set<number>>;
/** Polling interval in ms. Defaults to 1500, floored to 250. */
@@ -138,12 +141,22 @@ export class PipeWatcher extends EventEmitter {
}
this.ticking = true;
try {
let processes: HookProcessBaseInfo[];
let processes: HookProcessBaseInfo[] | null;
try {
processes = this.listProcesses();
processes = await this.listProcesses();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
processes = [];
processes = null;
}
// UNKNOWN (timeout / failure): keep the prior process + pipe snapshot.
// Treating missing data as "everything disappeared" would fire
// process-gone for every live PID and dispose healthy sessions — the
// freeze-then-teardown footgun behind issue #158. Still emit 'tick' so
// the manager's per-tick reconnect retries keep running off last-known
// live pipes.
if (processes === null) {
this.emit('tick');
return;
}
let livePipes: Set<number>;
try {

View File

@@ -0,0 +1,238 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import { Worker } from 'worker_threads';
import type { HookProcessBaseInfo } from './injector';
/**
* Isolated, timeout-bounded wrapper around the native `getAllMainProcess()`
* enumeration.
*
* Why this exists (issue #158): the watcher polls QQ processes every ~1.5s by
* calling the synchronous native enumerator, which walks `/proc` and reads each
* candidate's `cmdline`/`maps`. Those reads go through the target's mm and
* BLOCK while a process is mid-`exec()` — exactly what happens when QQ runs a
* silent hot-update and the process table churns. A blocked synchronous native
* call freezes the whole Node event loop: OneBot stops responding, the watcher
* stops ticking, reconnect logic never runs. The process stays "alive" so the
* supervisor never restarts it — the bot just goes silent.
*
* The only way to put a real timeout on a synchronous native call is to run it
* off the main thread. We run it in a worker; the main thread races the result
* against a deadline. On timeout the main loop keeps going (it returns the
* UNKNOWN sentinel `null`, which the watcher treats as "no fresh data, keep
* prior state" — crucially NOT "all processes gone"). The blocked worker is
* abandoned (a fresh one is spawned next time); it exits on its own once the
* native call finally returns.
*
* Graceful degradation: if the native addon can't be loaded in a worker (e.g.
* it isn't context-aware) or there's no addon at all (macOS reads sockets, not
* `/proc`), we fall back to calling `fallbackSync` on the main thread — i.e.
* exactly today's behaviour, no worse.
*/
export interface ProcessEnumerator {
/** Resolve to the process list, or `null` (UNKNOWN) when enumeration timed
* out / failed and the caller should keep its prior state. */
enumerate(): Promise<HookProcessBaseInfo[] | null>;
dispose(): void;
}
export interface NativeEnumeratorDeps {
/** Resolved path to the hook `.node` addon, or null when there is none
* (macOS / missing) — in which case we never spawn a worker. */
addonPath: string | null;
/** Synchronous lister used when worker isolation is unavailable. Returns
* today's value (and may itself block — that's the no-worse-than-before
* fallback). */
fallbackSync: () => HookProcessBaseInfo[];
/** Display name stamped on each returned process (e.g. 'qq' / 'QQ.exe'). */
processName: string;
/** Per-enumeration deadline. Default 4000ms — comfortably above a healthy
* enumeration (single-digit ms) but well under a human "is it dead?". */
timeoutMs?: number;
/** Cap on abandoned (blocked) workers before we stop spawning more and just
* return UNKNOWN until they drain. Bounds thread growth across a long
* hot-update window. Default 4. */
maxOrphans?: number;
log?: Logger;
}
const DEFAULT_TIMEOUT_MS = 4000;
const DEFAULT_MAX_ORPHANS = 4;
// Worker body (CommonJS — eval workers default to CJS so `require` is available;
// `process.dlopen` is a global and needs no module system). Loads the addon
// handed in via workerData, then answers each 'enumerate' with the raw pid list
// from the blocking native call. All the cheap post-processing stays on main.
const WORKER_SOURCE = `
const { parentPort, workerData } = require('node:worker_threads');
let addon = null;
try {
const mod = { exports: {} };
process.dlopen(mod, workerData.addonPath);
addon = mod.exports;
} catch (e) {
parentPort.postMessage({ type: 'fatal', error: String((e && e.message) || e) });
}
if (addon) {
parentPort.on('message', (msg) => {
if (!msg || msg.type !== 'enumerate') return;
try {
const pids = addon.getAllMainProcess();
parentPort.postMessage({ type: 'result', id: msg.id, pids: Array.from(pids) });
} catch (e) {
parentPort.postMessage({ type: 'error', id: msg.id, error: String((e && e.message) || e) });
}
});
parentPort.postMessage({ type: 'ready' });
}
`;
function mapPids(pids: number[], processName: string): HookProcessBaseInfo[] {
return [...new Set(pids)]
.filter((pid) => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b)
.map((pid) => ({ pid, name: processName, path: '' }));
}
export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): ProcessEnumerator {
const log = deps.log ?? createLogger('ProcessEnumerator');
const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS;
// No addon to isolate (macOS / missing) → never spawn a worker; the sync
// fallback there is a cheap socket read, not a /proc walk.
if (!deps.addonPath) {
return {
async enumerate() {
try {
return deps.fallbackSync();
} catch (err) {
log.warn('enumerate fallback failed: %s', errMsg(err));
return null;
}
},
dispose() { /* nothing to tear down */ },
};
}
const addonPath = deps.addonPath;
let worker: Worker | null = null;
/** Set once we learn the addon can't load in a worker — permanent fallback. */
let isolationBroken = false;
let orphans = 0;
let seq = 0;
const pending = new Map<number, { resolve: (pids: number[] | null) => void }>();
let disposed = false;
const spawnWorker = (): void => {
const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } });
worker = w;
w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => {
if (msg.type === 'ready') return;
if (msg.type === 'fatal') {
// The addon won't load off-thread — give up on isolation for good and
// fall back to the synchronous path from here on. Resolve any in-flight
// request now (UNKNOWN) so it doesn't sit waiting for the timeout.
log.warn('process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration', msg.error ?? '');
isolationBroken = true;
for (const { resolve } of pending.values()) resolve(null);
pending.clear();
teardownWorker();
return;
}
if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') {
const entry = pending.get(msg.id);
if (!entry) return;
pending.delete(msg.id);
entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null);
}
});
w.on('error', (err) => {
log.warn('enumeration worker error: %s', errMsg(err));
if (worker === w) teardownWorker();
});
};
const teardownWorker = (): void => {
const w = worker;
worker = null;
if (!w) return;
// terminate() can't preempt a thread blocked in the native call; it takes
// effect once the call returns. Track it as an orphan until it actually
// exits so we can bound how many we let pile up.
orphans += 1;
w.once('exit', () => { orphans = Math.max(0, orphans - 1); });
void w.terminate().catch(() => { /* already gone */ });
};
const syncFallback = (): HookProcessBaseInfo[] | null => {
try {
return deps.fallbackSync();
} catch (err) {
log.warn('enumerate sync fallback failed: %s', errMsg(err));
return null;
}
};
return {
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
if (disposed || isolationBroken) return syncFallback();
if (!worker) {
if (orphans >= maxOrphans) {
// Too many blocked workers already piling up (a sustained hang) —
// don't spawn more; report UNKNOWN and let them drain.
return null;
}
spawnWorker();
}
const w = worker;
if (!w) return syncFallback();
const id = ++seq;
const resultPromise = new Promise<number[] | null>((resolve) => {
pending.set(id, { resolve });
});
try {
w.postMessage({ type: 'enumerate', id });
} catch (err) {
pending.delete(id);
log.warn('failed to post enumerate request: %s', errMsg(err));
teardownWorker();
return syncFallback();
}
let timer: NodeJS.Timeout | undefined;
const timeout = new Promise<'timeout'>((resolve) => {
timer = setTimeout(() => resolve('timeout'), timeoutMs);
});
const outcome = await Promise.race([resultPromise, timeout]);
if (timer) clearTimeout(timer);
if (outcome === 'timeout') {
pending.delete(id);
log.warn('process enumeration timed out after %dms (worker abandoned) — keeping prior process set', timeoutMs);
teardownWorker();
return null;
}
if (outcome === null) {
// Native call threw inside the worker — treat as a transient failure,
// keep prior state rather than nuking every session.
return null;
}
return mapPids(outcome, deps.processName);
},
dispose() {
disposed = true;
for (const { resolve } of pending.values()) resolve(null);
pending.clear();
const w = worker;
worker = null;
if (w) void w.terminate().catch(() => { /* ignore */ });
},
};
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}

View File

@@ -1,5 +1,5 @@
import { EventEmitter } from 'events';
import { promises as fs } from 'fs';
import { readdirSync, promises as fs } from 'fs';
import net from 'net';
import os from 'os';
import path from 'path';
@@ -85,12 +85,59 @@ interface PendingAck {
wantReply: boolean;
}
/**
* Sync directory scan for `mojo.<pid>.control.sock` socket files in the
* runtime dir, returning the pid set. Used by the darwin path of
* `listHookProcesses()` — on macOS the DYLD_INSERT injection model means
* there is no native enumerate-QQ-processes addon; the existence of our
* dylib's listener socket IS the proof that a QQ process is hooked. The
* sync variant is needed because the watcher's `listProcesses` dep is sync.
*
* Mirrors `listLiveLinuxPipePids` (the async + connectable-probe variant)
* but skips the connectable probe — the existence of the socket file is
* sufficient signal for "process exists with our dylib mapped". The async
* variant still gates the subsequent `pipe-up` emit via a real connect.
*/
export function listSnowlumaPipePidsSync(
runtimeDir = linuxRuntimeDir(),
): Set<number> {
const result = new Set<number>();
let names: string[];
try {
names = readdirSync(runtimeDir);
} catch {
return result;
}
for (const name of names) {
const m = /^mojo\.(\d+)\.control\.sock$/i.exec(name);
if (!m) continue;
const pid = Number(m[1]);
if (Number.isInteger(pid) && pid > 0) result.add(pid);
}
return result;
}
function linuxRuntimeDir(): string {
// Name kept for historical reasons (the function predates the macOS port);
// applies to every non-win32 platform. The fallback order mirrors each
// platform hook's runtime_dir(): explicit override first, then the OS-
// native ephemeral-dir convention.
const explicit = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
if (explicit && explicit.length > 0) return explicit;
const xdg = process.env.XDG_RUNTIME_DIR;
if (xdg && xdg.length > 0) return xdg;
// Mirrors hook_stub.cpp runtime_dir() fallback.
// macOS: dylib defaults to "$TMPDIR/snowluma-hook" (apps/qq/macos/
// qq_hook_dylib.cpp's runtime_dir()). $TMPDIR is per-user on macOS
// (under /var/folders/.../T) so this is the right place — Linux's
// /tmp/snowluma-<uid> doesn't exist on a stock Mac.
if (process.platform === 'darwin') {
const tmpdir = process.env.TMPDIR;
if (tmpdir && tmpdir.length > 0) {
const trimmed = tmpdir.endsWith('/') ? tmpdir.slice(0, -1) : tmpdir;
return path.join(trimmed, 'snowluma-hook');
}
}
// Linux fallback: mirrors hook_stub.cpp runtime_dir() last-resort.
// process.geteuid is POSIX-only; cast to allow non-Linux type checks.
const uid = typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid;
return `/tmp/snowluma-${uid}`;

View File

@@ -1,5 +1,6 @@
import { exec } from 'child_process';
import net from 'net';
import http from 'http';
import https from 'https';
import { promisify } from 'util';
@@ -126,51 +127,61 @@ interface PtloginUin {
nickname?: string;
}
async function fetchPtlogin(port: number): Promise<PtloginUin[]> {
/**
* One `pt_get_uins` call. Returns the parsed account array (possibly empty —
* an EMPTY array is a real answer: "0 accounts", NOT an error) or `null` when
* the port could not be reached / the body was not a usable pt_get_uins
* response (connect refused, timeout, unparseable). Callers MUST distinguish
* the two: `[]` feeds the logged-in/out decision, `null` means "network
* problem, no answer" and should fall through to the deep-link fallback.
*/
async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin[] | null> {
return new Promise((resolve) => {
const url = `https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`;
const protocol = useHttps ? 'https' : 'http';
const url = `${protocol}://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`;
const req = https.get(
url,
{
headers: {
Host: 'localhost.ptlogin2.qq.com',
Referer: 'https://xui.ptlogin2.qq.com/',
Cookie: 'pt_local_token=0',
},
rejectUnauthorized: false, // 忽略本地自签证书报错
timeout: CONNECTION_TIMEOUT_MS,
},
(res) => {
let text = '';
res.on('data', (chunk) => { text += chunk.toString(); });
res.on('end', () => {
try {
// 100% 复刻 Python 切片逻辑:获取两个方括号中间的字符串,再包装成数组
const inner = text.split('[')[1].split(']')[0];
const data = JSON.parse('[' + inner + ']') as PtloginUin[];
resolve(data);
} catch {
resolve([]);
}
});
}
);
const headers = {
Host: 'localhost.ptlogin2.qq.com',
Referer: 'https://xui.ptlogin2.qq.com/',
Cookie: 'pt_local_token=0',
};
req.on('error', () => resolve([]));
const handleResponse = (res: http.IncomingMessage) => {
let text = '';
res.on('data', (chunk) => { text += chunk.toString(); });
res.on('end', () => {
try {
const inner = text.split('[')[1].split(']')[0];
const data = JSON.parse('[' + inner + ']') as PtloginUin[];
resolve(data);
} catch {
resolve(null);
}
});
};
const req = useHttps
? https.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS, rejectUnauthorized: false }, handleResponse)
: http.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS }, handleResponse);
req.on('error', () => resolve(null));
req.on('timeout', () => {
req.destroy();
resolve([]);
resolve(null);
});
});
}
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallback'> {
// 抽象的 QQNT
const res1 = await fetchPtlogin(port);
const res2 = await fetchPtlogin(port);
const useHttps = port % 2 !== 0;
const target = res1.length < res2.length ? res1 : res2;
const res1 = await fetchPtlogin(port, useHttps);
const res2 = await fetchPtlogin(port, useHttps);
if (res1 === null && res2 === null) return 'fallback';
const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null);
const target = usable.reduce((a, b) => (a.length <= b.length ? a : b));
if (target.length === 1) {
const account = target[0];
@@ -182,8 +193,6 @@ async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallba
};
}
// Any non-1 result — the 2+0 alternation, both-2, both-empty, etc. — is
// inconclusive; hand off to the deep-link / process-count fallback.
return 'fallback';
}
@@ -250,12 +259,21 @@ export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | n
}
return null;
}
const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309];
const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310];
const PT_PORTS = [4301, 4303, 4305, 4307, 4309];
const matchedPtPorts = ports.filter(p => PT_PORTS.includes(p));
const matchedOddPorts = ports.filter(p => ODD_PT_PORTS.includes(p));
const matchedEvenPorts = ports.filter(p => EVEN_PT_PORTS.includes(p));
if (matchedPtPorts.length > 0) {
for (const port of matchedPtPorts) {
let ptPortsToTry: number[] = [];
if (matchedOddPorts.length > 0) {
ptPortsToTry = matchedOddPorts;
} else if (matchedEvenPorts.length > 0) {
ptPortsToTry = matchedEvenPorts;
}
if (ptPortsToTry.length > 0) {
for (const port of ptPortsToTry) {
const ptResult = await tryPtloginMethod(port);
if (ptResult !== 'fallback') {
return ptResult;

View File

@@ -0,0 +1,173 @@
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookManager } from '../src/hook-manager';
import { PipeWatcher } from '../src/pipe-watcher';
import type { ManualMapHandle } from '../src/injector';
import type { BridgeManagerSink } from '../src/hook-manager';
import type { QqHookClient } from '../src/qq-hook-client';
// Regression cover for the WebUI SSE wiring: HookManager must call its
// optional `onSessionsChanged` callback every time the observable set of
// HookProcessInfo (what `listProcesses()` would return) changes, so the
// /api/state/stream handler can push a fresh processes snapshot to the
// browser without REST polling.
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
const flush = () => new Promise<void>(r => setImmediate(r));
interface Harness {
manager: HookManager;
pipeWatcher: PipeWatcher;
setProcesses: (next: number[]) => void;
setLivePipes: (next: number[]) => void;
onSessionsChanged: ReturnType<typeof vi.fn>;
clientFactory: ReturnType<typeof vi.fn>;
}
function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}): Harness {
let pids = opts.processes ?? [];
let live = new Set<number>(opts.livePipes ?? []);
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
});
const clientFactory = vi.fn(() => {
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
(c as any).isClosed = false;
(c as any).isLoggedIn = false;
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
(c as any).connectAll = async () => { /* succeed without doing anything */ };
(c as any).close = () => { (c as any).isClosed = true; };
return c as unknown as QqHookClient;
});
const bridgeManager = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManagerSink;
const onSessionsChanged = vi.fn();
const manager = new HookManager({
bridgeManager,
pipeWatcher,
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: clientFactory,
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
onSessionsChanged,
});
return {
manager,
pipeWatcher,
onSessionsChanged,
clientFactory,
setProcesses: (next) => { pids = next; },
setLivePipes: (next) => { live = new Set(next); },
};
}
describe('HookManager.onSessionsChanged', () => {
it('fires when the watcher discovers a new QQ process', async () => {
const ctx = makeManager({ processes: [] });
await ctx.pipeWatcher.start();
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
ctx.setProcesses([4242]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('fires when the watcher reports a process is gone', async () => {
const ctx = makeManager({ processes: [4242] });
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
ctx.setProcesses([]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('fires when the watcher reports the pipe came up (status: connecting → loaded)', async () => {
const ctx = makeManager({ processes: [4242] });
await ctx.pipeWatcher.start();
await flush();
// Inject so the session is in 'connecting' state; the next pipe-up
// makes attemptConnect succeed and status flips to 'loaded'.
await ctx.manager.loadProcess(4242);
await flush();
ctx.onSessionsChanged.mockClear();
ctx.setLivePipes([4242]);
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => {
const ctx = makeManager({ processes: [] });
ctx.onSessionsChanged.mockImplementation(() => { throw new Error('listener boom'); });
await ctx.pipeWatcher.start();
ctx.setProcesses([4242]);
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
await flush();
// A second tick still fires the callback — it wasn't unregistered by
// the prior throw.
ctx.onSessionsChanged.mockClear();
ctx.setProcesses([4242, 5555]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('is OPTIONAL — omitting it leaves the manager fully functional', async () => {
const pids = [4242];
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(),
intervalMs: 60_000,
});
const manager = new HookManager({
bridgeManager: {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManagerSink,
pipeWatcher,
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: vi.fn(() => {
const c = new EventEmitter() as any;
c.isClosed = false; c.isLoggedIn = false;
c.getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
c.connectAll = async () => undefined;
c.close = () => { c.isClosed = true; };
return c;
}),
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
// onSessionsChanged deliberately omitted
});
await pipeWatcher.start();
await pipeWatcher.tickNow();
await flush();
const list = await manager.listProcesses();
expect(list).toHaveLength(1);
expect(list[0].pid).toBe(4242);
manager.dispose();
});
});

View File

@@ -3,6 +3,7 @@ import { EventEmitter } from 'events';
import { HookSession } from '../src/hook-session';
import type { ManualMapHandle } from '../src/injector';
import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client';
import type { QqPortLoginInfo } from '../src/qq-port-probe';
import type { PacketSink } from '@snowluma/common/protocol-types';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
@@ -42,6 +43,7 @@ function makeSession(opts: {
pipeLive?: boolean;
clientFailsConnect?: boolean;
onPacket?: PacketSink;
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
} = {}) {
const pid = opts.pid ?? 1234;
let pipeLive = opts.pipeLive ?? false;
@@ -50,6 +52,9 @@ function makeSession(opts: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
};
// Default probe reports "not logged in" so the reconcile safety net is inert
// unless a test opts into a logged-in probe (never hits the real port scan).
const probeLogin = opts.probeLogin ?? (async () => ({ port: 0, uin: '', loggedIn: false }));
const session = new HookSession(pid, {
injector,
@@ -60,6 +65,7 @@ function makeSession(opts: {
// Cast: FakeClient mirrors only the surface HookSession touches.
return c as unknown as QqHookClient;
},
probeLogin,
pipeWatcher: { isPipeLive: () => pipeLive },
onPacket: opts.onPacket,
});
@@ -347,6 +353,95 @@ describe('HookSession — process gone', () => {
});
});
describe('HookSession — refresh drift fix', () => {
// refresh while the pipe is down on a connected-but-never-logged-in
// session now reports 'connecting' (matching what onPipeDown gives for the
// same state), not the old spurious 'disconnected'. Pre-refactor, refresh's
// down branch ignored wasLoggedIn and always reported 'disconnected'.
it('refresh-while-down + never logged in → connecting (not disconnected), no disconnect emit', async () => {
const ctx = makeSession({ pipeLive: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
expect(ctx.session.status).toBe('loaded'); // connected, never logged in
const discSpy = vi.fn();
ctx.session.on('disconnected', discSpy);
ctx.setPipeLive(false);
const info = await ctx.session.refresh();
expect(info.status).toBe('connecting'); // drift fix: was 'disconnected'
expect(discSpy).not.toHaveBeenCalled(); // never logged in ⇒ nothing owed
});
it('refresh-while-down after login still → disconnected + emits disconnected(true)', async () => {
// The flip is scoped to the never-logged-in case; a real session that
// had reached login must still settle to 'disconnected' and notify.
const ctx = makeSession({ pipeLive: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
expect(ctx.session.status).toBe('online');
const discSpy = vi.fn();
ctx.session.on('disconnected', discSpy);
ctx.setPipeLive(false);
const info = await ctx.session.refresh();
expect(info.status).toBe('disconnected');
expect(discSpy).toHaveBeenCalledWith(true);
});
});
describe('HookSession — pipe-down must not clobber a settled error', () => {
// Regression net for the phase-2 reconcilePipeDown !connected short-circuit:
// a pipe-down tick on a session that never reached a live connection must
// not wipe a diagnostic error or emit a spurious status-changed.
it('onPipeDown after a failed connect keeps the error and does not re-emit', async () => {
const ctx = makeSession({ pipeLive: true, clientFailsConnect: true });
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
expect(ctx.session.status).toBe('connecting');
expect(ctx.session.error).toBe('connect failed');
const statusSpy = vi.fn();
ctx.session.on('status-changed', statusSpy);
ctx.session.onPipeDown();
await flush();
expect(ctx.session.status).toBe('connecting');
expect(ctx.session.error).toBe('connect failed'); // not wiped to ''
expect(statusSpy).not.toHaveBeenCalled(); // no spurious emit
});
it('onPipeDown after a failed load leaves the error status intact', async () => {
const injector = {
inject: vi.fn(() => { throw new Error('inject boom'); }),
unload: vi.fn(),
};
const session = new HookSession(1234, {
injector,
makeClient: () => new FakeClient() as unknown as QqHookClient,
pipeWatcher: { isPipeLive: () => false },
});
await session.load();
expect(session.status).toBe('error');
expect(session.error).toBe('inject boom');
session.onPipeDown();
await flush();
expect(session.status).toBe('error'); // not flipped to 'available'
expect(session.error).toBe('inject boom'); // not wiped
});
});
describe('HookSession — packet forwarding', () => {
// These tests cover the field-rename + filter logic that used to live
// inside the deleted NtqqHandler.onHookPacket. Inlining it here means
@@ -444,3 +539,136 @@ describe('HookSession — packet forwarding', () => {
});
});
});
describe('HookSession — login reconcile (Docker auto-login safety net)', () => {
it('reconciles login via the active probe when the pushed frame is missed', async () => {
// Probe reports logged-in; the FakeClient never fires a loginState frame
// (the missed-edge Docker case). The immediate reconcile probe must detect
// it and emit "login".
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); // connect (not logged in via frame) → starts reconcile
await flush(); // immediate probe resolves → handleLoginState
expect(loginSpy).toHaveBeenCalledOnce();
expect(loginSpy.mock.calls[0]![0]).toBe('10001');
expect(ctx.session.status).toBe('online');
expect(ctx.session.uin).toBe('10001');
});
it('does not log in when the probe reports not-logged-in', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 0, uin: '', loggedIn: false }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); await flush();
expect(loginSpy).not.toHaveBeenCalled();
expect(ctx.session.status).toBe('loaded');
});
it('ignores a probe with a non-real uin (0)', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '0', loggedIn: true }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); await flush();
expect(loginSpy).not.toHaveBeenCalled();
});
it('tolerates a throwing probe (best-effort, no crash/login)', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => { throw new Error('port scan failed'); },
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); await flush();
expect(loginSpy).not.toHaveBeenCalled();
expect(ctx.session.status).toBe('loaded');
});
it('detects a login that lands on a LATER interval probe', async () => {
vi.useFakeTimers();
try {
let loggedIn = false;
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (not logged in yet)
expect(loginSpy).not.toHaveBeenCalled();
loggedIn = true; // QQ finishes auto-login
await vi.advanceTimersByTimeAsync(3000); // next interval probe picks it up
expect(loginSpy).toHaveBeenCalledOnce();
expect(ctx.session.status).toBe('online');
} finally {
vi.useRealTimers();
}
});
it('does not double-emit when the pushed frame logs in first', async () => {
// Pushed-frame login wins; a subsequent probe with the same uin must not
// re-emit (handleLoginState dedups), and the reconcile timer is stopped.
const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', loggedIn: true }));
const ctx = makeSession({ pipeLive: true, probeLogin });
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001'); // pushed-frame login first
await flush();
expect(loginSpy).toHaveBeenCalledOnce();
expect(ctx.session.status).toBe('online');
});
});
describe('HookSession — login reconcile does not stack concurrent probes', () => {
it('skips overlapping ticks while a slow probe is in flight', async () => {
vi.useFakeTimers();
try {
// A probe that never resolves — simulates a slow port scan spanning
// multiple intervals. The in-flight guard must call it only once.
const probeLogin = vi.fn(() => new Promise<never>(() => { /* pending */ }));
const ctx = makeSession({ pipeLive: true, probeLogin });
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (starts, stays pending)
await vi.advanceTimersByTimeAsync(9000); // 3 more interval ticks
expect(probeLogin).toHaveBeenCalledTimes(1); // not stacked
} finally {
vi.useRealTimers();
}
});
});

View File

@@ -0,0 +1,56 @@
import { describe, it, expect } from 'vitest';
import { statusFor, type HookFlags } from '../src/hook-status';
import type { HookProcessStatus } from '../src/types';
const F = (o: Partial<HookFlags>): HookFlags => ({
injected: false, connected: false, loggedIn: false, wasLoggedIn: false, ...o,
});
describe('statusFor — settled HookProcessStatus derivation', () => {
it('not injected → available (regardless of other flags)', () => {
expect(statusFor(F({ injected: false }))).toBe('available');
// !injected dominates: stale connected/loggedIn bits must not leak through.
expect(statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true }))).toBe('available');
});
it('injected, connected, loggedIn → online', () => {
expect(statusFor(F({ injected: true, connected: true, loggedIn: true }))).toBe('online');
});
it('injected, connected, not loggedIn → loaded', () => {
expect(statusFor(F({ injected: true, connected: true, loggedIn: false }))).toBe('loaded');
});
it('injected, not connected, had logged in → disconnected', () => {
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe('disconnected');
});
it('injected, not connected, never logged in → connecting', () => {
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe('connecting');
});
it('disconnected vs connecting differ ONLY by wasLoggedIn (same injected+!connected)', () => {
const base = { injected: true, connected: false, loggedIn: false };
expect(statusFor(F({ ...base, wasLoggedIn: true }))).toBe('disconnected');
expect(statusFor(F({ ...base, wasLoggedIn: false }))).toBe('connecting');
});
it('covers exactly the five settled states across the flag space', () => {
const seen = new Set<HookProcessStatus>();
for (const injected of [false, true]) {
for (const connected of [false, true]) {
for (const loggedIn of [false, true]) {
for (const wasLoggedIn of [false, true]) {
seen.add(statusFor({ injected, connected, loggedIn, wasLoggedIn }));
}
}
}
}
expect([...seen].sort()).toEqual(
['available', 'connecting', 'disconnected', 'loaded', 'online'].sort(),
);
// The two out-of-band states are never produced by the pure derivation.
expect(seen.has('loading')).toBe(false);
expect(seen.has('error')).toBe(false);
});
});

View File

@@ -192,4 +192,40 @@ describe('PipeWatcher', () => {
expect(events).toEqual([['discovered', 1234], ['up', 1234]]);
watcher.stop();
});
it('UNKNOWN (null) enumeration keeps prior state — no false process-gone (issue #158)', async () => {
let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }];
let live = new Set<number>([1234]);
const watcher = new PipeWatcher({
listProcesses: () => result,
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
});
await watcher.start();
expect(watcher.isProcessAlive(1234)).toBe(true);
expect(watcher.isPipeLive(1234)).toBe(true);
const events = captureEvents(watcher);
// Enumeration goes UNKNOWN (e.g. native /proc walk timed out during a QQ
// hot-update). Prior process + pipe state MUST be preserved — no teardown.
result = null;
await watcher.tickNow();
expect(events).toEqual([]);
expect(watcher.isProcessAlive(1234)).toBe(true);
expect(watcher.isPipeLive(1234)).toBe(true);
// Enumeration recovers with the same set → still no churn.
result = [{ pid: 1234, name: 'qq', path: '' }];
await watcher.tickNow();
expect(events).toEqual([]);
// A REAL disappearance (empty list, not null) still fires the teardown.
result = [];
live = new Set();
await watcher.tickNow();
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
watcher.stop();
});
});

View File

@@ -0,0 +1,55 @@
import { describe, it, expect, vi } from 'vitest';
import { createNativeProcessEnumerator } from '../src/process-enumerator';
import type { HookProcessBaseInfo } from '../src/injector';
const QQ = (pid: number): HookProcessBaseInfo => ({ pid, name: 'qq', path: '' });
describe('createNativeProcessEnumerator', () => {
describe('no addon (macOS / missing) → synchronous fallback, never a worker', () => {
it('returns the sync lister result', async () => {
const en = createNativeProcessEnumerator({
addonPath: null,
fallbackSync: () => [QQ(10), QQ(20)],
processName: 'qq',
});
expect(await en.enumerate()).toEqual([QQ(10), QQ(20)]);
en.dispose();
});
it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => {
const en = createNativeProcessEnumerator({
addonPath: null,
fallbackSync: () => { throw new Error('boom'); },
processName: 'qq',
});
expect(await en.enumerate()).toBeNull();
en.dispose();
});
});
describe('worker isolation that cannot load the addon → permanent fallback', () => {
it('falls back to the sync lister after the worker reports a fatal load error', async () => {
const fallback = vi.fn(() => [QQ(7)]);
const en = createNativeProcessEnumerator({
// A path that exists nowhere → process.dlopen throws in the worker →
// the worker posts 'fatal' → isolation is abandoned for good.
addonPath: '/nonexistent/snowluma-test.node',
fallbackSync: fallback,
processName: 'qq',
timeoutMs: 200,
});
// First call spawns the worker; the fatal message drains it to UNKNOWN.
const first = await en.enumerate();
expect(first).toBeNull();
// Give the 'fatal' message a moment to flip isolationBroken if it hadn't
// already, then subsequent calls take the synchronous fallback.
await new Promise((r) => setTimeout(r, 50));
const second = await en.enumerate();
expect(second).toEqual([QQ(7)]);
expect(fallback).toHaveBeenCalled();
en.dispose();
});
});
});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.10.0",
"version": "1.11.3",
"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).",
@@ -16,6 +16,18 @@
"types": "./src/logger.ts",
"default": "./src/logger.ts"
},
"./coerce": {
"types": "./src/coerce.ts",
"default": "./src/coerce.ts"
},
"./single-flight-cache": {
"types": "./src/single-flight-cache.ts",
"default": "./src/single-flight-cache.ts"
},
"./concurrency": {
"types": "./src/concurrency.ts",
"default": "./src/concurrency.ts"
},
"./hex": {
"types": "./src/hex.ts",
"default": "./src/hex.ts"
@@ -43,6 +55,10 @@
"./runtime": {
"types": "./src/runtime.ts",
"default": "./src/runtime.ts"
},
"./uin": {
"types": "./src/uin.ts",
"default": "./src/uin.ts"
}
},
"scripts": {

View File

@@ -0,0 +1,30 @@
// Scalar coercion primitives for normalizing untrusted JSON config into
// typed values with fallbacks. Zero dependencies — these were duplicated
// verbatim across notifications/config and webui/ui-config; this is their
// single home. Input tolerance is deliberate (numeric strings coerce), but
// validity is strict (a wrong type yields the caller's fallback, never a
// silent 0/'' — except where the primitive's contract says otherwise).
/** True only for a plain, non-null, non-array object. */
export function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
/** The value when it is a real boolean, else the fallback. Strings/numbers
* are NOT coerced — `'true'` and `1` both yield the fallback. */
export function boolOr(value: unknown, fallback: boolean): boolean {
return typeof value === 'boolean' ? value : fallback;
}
/** A finite number (numeric strings coerced) clamped to `[min, max]`, else
* the fallback. Fractional precision is preserved — use `clampInt` to floor. */
export function clampNum(value: unknown, min: number, max: number, fallback: number): number {
const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
if (!Number.isFinite(n)) return fallback;
return Math.min(max, Math.max(min, n));
}
/** `clampNum` truncated toward zero — clamp first, then drop the fraction. */
export function clampInt(value: unknown, min: number, max: number, fallback: number): number {
return Math.trunc(clampNum(value, min, max, fallback));
}

View File

@@ -0,0 +1,27 @@
/**
* Map `items` through `fn` in sequential batches of at most `concurrency`
* items, awaiting each batch (`Promise.all`) before starting the next.
* Results come back in input order.
*
* Batched, not a rolling pool: every item in a batch must settle before the
* next batch starts. This caps peak parallelism — used to keep rate-limited
* fan-out (e.g. the per-uin OIDB profile fetches during forward-node
* enrichment) from bursting past a safe width and tripping Tencent
* risk-control. Pair it with a cap on `items` (slice) and per-item error
* handling inside `fn` for a fully bounded, best-effort enrichment — the
* shape that was previously hand-rolled at each such call site.
*/
export async function mapWithConcurrency<T, R>(
items: readonly T[],
concurrency: number,
fn: (item: T, index: number) => Promise<R>,
): Promise<R[]> {
const limit = Math.max(1, Math.trunc(concurrency));
const results = new Array<R>(items.length);
for (let i = 0; i < items.length; i += limit) {
const batch = items.slice(i, i + limit);
const settled = await Promise.all(batch.map((item, j) => fn(item, i + j)));
for (let j = 0; j < settled.length; j++) results[i + j] = settled[j]!;
}
return results;
}

View File

@@ -175,7 +175,7 @@ function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: n
// 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)
? ansi(COLOR_DIM, uinTag) + ' '.repeat(Math.max(0, UIN_SLOT_WIDTH - uinTag.length))
: ' '.repeat(UIN_SLOT_WIDTH);
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';

View File

@@ -0,0 +1,93 @@
/**
* Single-flight + TTL memoization.
*
* Concentrates the "don't refetch what's fresh, and don't stampede the same
* key with concurrent loads" pattern that was hand-rolled (slightly
* differently each time) across the codebase — e.g. `ContactsApi`'s group
* member-list cache and the WebUI update-check. Each copy re-implemented the
* same fiddly trio: a TTL freshness check, an in-flight promise map to
* de-dupe concurrent callers, and `finally`-cleanup of that map. Getting any
* of the three subtly wrong (forgetting the `finally`, caching an error,
* racing the timestamp) is a real hazard — so it lives in one place.
*
* The underlying concern is Tencent risk-control: a busy OneBot client can
* fan out one uncached OIDB fetch per inbound message, and sustained bursts
* trip a ban. TTL + single-flight collapse that fan-out.
*/
export interface SingleFlightCacheOptions<K, V> {
/** Freshness window in ms. A cached entry older than this is reloaded. */
ttlMs: number;
/** Load the value for a key. Rejections propagate and are never cached. */
load: (key: K) => Promise<V>;
/**
* Decide whether a resolved value should be cached. Default: always.
* Return `false` to leave an entry uncached (e.g. an error-shaped result the
* next call should retry) while still de-duping concurrent in-flight callers.
*/
shouldCache?: (value: V) => boolean;
/** Clock, injectable for tests. Defaults to `Date.now`. */
now?: () => number;
}
export class SingleFlightCache<K, V> {
private readonly ttlMs: number;
private readonly load: (key: K) => Promise<V>;
private readonly shouldCache: (value: V) => boolean;
private readonly now: () => number;
private readonly fresh = new Map<K, { at: number; value: V }>();
private readonly inflight = new Map<K, Promise<V>>();
constructor(opts: SingleFlightCacheOptions<K, V>) {
this.ttlMs = opts.ttlMs;
this.load = opts.load;
this.shouldCache = opts.shouldCache ?? (() => true);
this.now = opts.now ?? Date.now;
}
/**
* Get the value for `key`.
*
* - Returns a fresh cached value when the last load was within `ttlMs`.
* - Otherwise de-dupes concurrent callers onto a single `load()` and caches
* the result (subject to `shouldCache`). A rejected `load` propagates to
* every joined caller, clears the in-flight slot, and is not cached.
* - `force` bypasses the freshness check but still joins an in-flight load
* rather than starting a second one.
*/
get(key: K, opts: { force?: boolean } = {}): Promise<V> {
if (!opts.force) {
const hit = this.fresh.get(key);
if (hit && this.now() - hit.at < this.ttlMs) return Promise.resolve(hit.value);
}
const existing = this.inflight.get(key);
if (existing) return existing;
const task = (async () => {
try {
const value = await this.load(key);
if (this.shouldCache(value)) this.fresh.set(key, { at: this.now(), value });
return value;
} finally {
this.inflight.delete(key);
}
})();
this.inflight.set(key, task);
return task;
}
/** Drop a cached entry. Does not abort an in-flight load. */
invalidate(key: K): void {
this.fresh.delete(key);
}
/** Drop all cached entries. Does not abort in-flight loads. */
clear(): void {
this.fresh.clear();
}
}
export function createSingleFlightCache<K, V>(
opts: SingleFlightCacheOptions<K, V>,
): SingleFlightCache<K, V> {
return new SingleFlightCache(opts);
}

View File

@@ -0,0 +1,11 @@
// Shared QQ UIN validity check. A "real" UIN is a live QQ account number, not
// a garbage value the native hook can emit during the probe→inject race — e.g.
// a 13-digit millisecond timestamp read from not-yet-populated QQ memory
// (issue #162). No real QQ UIN exceeds 10 digits (they fit in uint32, max
// 4294967295), so a pure digit string of 5..10 chars is the accept window.
//
// Callers rely on a `true` result guaranteeing a BigInt()-safe pure-digit
// string. Keep that contract if the pattern ever changes.
export function isRealUin(uin: string): boolean {
return /^\d{5,10}$/.test(uin);
}

View File

@@ -0,0 +1,78 @@
import { describe, it, expect } from 'vitest';
import { isObject, boolOr, clampNum, clampInt } from '../src/coerce';
describe('isObject', () => {
it('is true only for plain non-null non-array objects', () => {
expect(isObject({})).toBe(true);
expect(isObject({ a: 1 })).toBe(true);
expect(isObject(null)).toBe(false);
expect(isObject([])).toBe(false);
expect(isObject('x')).toBe(false);
expect(isObject(42)).toBe(false);
expect(isObject(undefined)).toBe(false);
});
});
describe('boolOr', () => {
it('returns the value only when it is a real boolean, else the fallback', () => {
expect(boolOr(true, false)).toBe(true);
expect(boolOr(false, true)).toBe(false);
expect(boolOr('true', false)).toBe(false); // strings are NOT coerced
expect(boolOr(1, false)).toBe(false);
expect(boolOr(undefined, true)).toBe(true);
expect(boolOr(null, true)).toBe(true);
});
});
describe('clampNum', () => {
it('passes finite numbers through, clamped to [min,max]', () => {
expect(clampNum(5, 0, 10, -1)).toBe(5);
expect(clampNum(-3, 0, 10, -1)).toBe(0); // below min
expect(clampNum(99, 0, 10, -1)).toBe(10); // above max
});
it('coerces numeric strings', () => {
expect(clampNum('7', 0, 10, -1)).toBe(7);
expect(clampNum('7.5', 0, 10, -1)).toBe(7.5); // NOT truncated (that is clampInt)
});
it('falls back on non-finite / non-numeric input', () => {
expect(clampNum('abc', 0, 10, 3)).toBe(3);
expect(clampNum(NaN, 0, 10, 3)).toBe(3);
expect(clampNum(Infinity, 0, 10, 3)).toBe(3);
expect(clampNum(undefined, 0, 10, 3)).toBe(3);
expect(clampNum(null, 0, 10, 3)).toBe(3);
expect(clampNum({}, 0, 10, 3)).toBe(3);
});
it('preserves fractional precision within bounds', () => {
expect(clampNum(0.42, 0, 1, 0)).toBe(0.42);
});
});
describe('clampInt', () => {
it('is clampNum truncated toward zero', () => {
expect(clampInt(7.9, 0, 10, -1)).toBe(7);
expect(clampInt('7.9', 0, 10, -1)).toBe(7);
expect(clampInt(5, 0, 10, -1)).toBe(5);
});
it('clamps before truncating', () => {
expect(clampInt(99.9, 0, 10, -1)).toBe(10);
expect(clampInt(-3.5, 0, 10, -1)).toBe(0);
});
it('clamp-then-trunc ordering: a fractional lower bound is crossed by the clamp, not the trunc', () => {
// Distinguishes clamp→trunc (this contract) from trunc→clamp: input 2.4
// with min 2.5 → clamp lifts to 2.5, then trunc → 2. A trunc-first impl
// would floor to 2 then clamp up to 2.5. Pins the order for the shared
// primitive (future callers may use fractional bounds).
expect(clampInt(2.4, 2.5, 10, 0)).toBe(2);
});
it('falls back on non-finite input', () => {
expect(clampInt('abc', 0, 10, 4)).toBe(4);
expect(clampInt(NaN, 0, 10, 4)).toBe(4);
expect(clampInt(undefined, 0, 10, 4)).toBe(4);
});
});

View File

@@ -0,0 +1,68 @@
import { describe, it, expect } from 'vitest';
import { mapWithConcurrency } from '../src/concurrency';
const tick = () => new Promise<void>((r) => setTimeout(r, 0));
describe('mapWithConcurrency', () => {
it('returns results in input order', async () => {
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 2, async (n) => n * 10);
expect(out).toEqual([10, 20, 30, 40, 50]);
});
it('passes the absolute index (across batch boundaries)', async () => {
const seen: Array<[number, number]> = [];
await mapWithConcurrency(['a', 'b', 'c', 'd', 'e'], 2, async (item, i) => {
seen.push([i, item.charCodeAt(0)]);
return i;
});
expect(seen.map(([i]) => i).sort((x, y) => x - y)).toEqual([0, 1, 2, 3, 4]);
});
it('never runs more than `concurrency` at once (batched), and serializes across batches', async () => {
let inFlight = 0;
let peak = 0;
const order: number[] = [];
await mapWithConcurrency([0, 1, 2, 3, 4, 5, 6], 3, async (n) => {
inFlight++;
peak = Math.max(peak, inFlight);
await tick();
order.push(n);
inFlight--;
return n;
});
expect(peak).toBeLessThanOrEqual(3);
// batched: first 3 (0,1,2) settle before the next batch (3,4,5) starts.
expect(order.slice(0, 3).sort((a, b) => a - b)).toEqual([0, 1, 2]);
expect(order.slice(3, 6).sort((a, b) => a - b)).toEqual([3, 4, 5]);
expect(order[6]).toBe(6);
});
it('handles a length not divisible by concurrency (short final batch)', async () => {
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 3, async (n) => n);
expect(out).toEqual([1, 2, 3, 4, 5]);
});
it('runs everything in one batch when concurrency >= length', async () => {
let peak = 0, inFlight = 0;
const out = await mapWithConcurrency([1, 2, 3], 10, async (n) => {
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
});
expect(out).toEqual([1, 2, 3]);
expect(peak).toBe(3);
});
it('returns [] for an empty input without calling fn', async () => {
let called = 0;
const out = await mapWithConcurrency([], 4, async (n) => { called++; return n; });
expect(out).toEqual([]);
expect(called).toBe(0);
});
it('treats concurrency < 1 as 1 (fully serial)', async () => {
let peak = 0, inFlight = 0;
await mapWithConcurrency([1, 2, 3], 0, async (n) => {
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
});
expect(peak).toBe(1);
});
});

View File

@@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest';
import { fromHex, hexPreview, toHex, toHexUpper } from '../src/hex';
describe('hex', () => {
it('toHex / toHexUpper render bytes as zero-padded hex', () => {
const b = Uint8Array.from([0x00, 0x0f, 0xa0, 0xff]);
expect(toHex(b)).toBe('000fa0ff');
expect(toHexUpper(b)).toBe('000FA0FF');
expect(toHex(Uint8Array.of())).toBe('');
});
it('hexPreview appends "..." only past maxBytes', () => {
const b = Uint8Array.from([1, 2, 3, 4, 5]);
expect(hexPreview(b)).toBe('0102030405'); // under the default 64-byte cap
expect(hexPreview(b, 5)).toBe('0102030405'); // exactly at the cap → no ellipsis
expect(hexPreview(b, 2)).toBe('0102...'); // truncated
expect(hexPreview(b, 0)).toBe('...'); // nothing shown, but bytes remain
});
it('fromHex round-trips toHex and rejects odd-length input', () => {
const b = Buffer.from([0xde, 0xad, 0xbe, 0xef]);
expect(fromHex(toHex(b)).equals(b)).toBe(true);
expect(toHex(fromHex('00ffa0'))).toBe('00ffa0');
expect(() => fromHex('abc')).toThrow();
});
});

View File

@@ -0,0 +1,61 @@
import { describe, expect, it } from 'vitest';
import { renderParamsVerbose, summarizeParams } from '../src/log-summary';
describe('summarizeParams', () => {
it('renders null/undefined as {}', () => {
expect(summarizeParams(null)).toBe('{}');
expect(summarizeParams(undefined)).toBe('{}');
});
it('renders a top-level non-object via String() WITHOUT quotes', () => {
// The reported change-request: a top-level primitive is NOT JSON-quoted.
expect(summarizeParams('hello')).toBe('hello');
expect(summarizeParams(123)).toBe('123');
});
it('collapses a top-level array to [len=N]', () => {
expect(summarizeParams([1, 2, 3])).toBe('[len=3]');
});
it('quotes string fields, collapses nested values, truncates long strings', () => {
expect(summarizeParams({ a: 1, b: 'x', c: { d: 1 }, e: [1, 2] }))
.toBe('a=1 b="x" c={...} e=[len=2]');
expect(summarizeParams({ s: 'x'.repeat(50) }))
.toBe(`s="${'x'.repeat(40)}..."`);
});
it('caps total output and appends "..." on overflow', () => {
const big: Record<string, number> = {};
for (let i = 0; i < 60; i++) big['key' + i] = i;
const out = summarizeParams(big);
expect(out.startsWith('key0=0')).toBe(true);
expect(out.endsWith('...')).toBe(true);
});
});
describe('renderParamsVerbose', () => {
it('redacts token / password / secret keys at any depth', () => {
const out = renderParamsVerbose({ token: 'abc', password: 'p', nested: { secret: 's' }, ok: 'v' });
expect(out).toContain('token:"***"');
expect(out).toContain('password:"***"');
expect(out).toContain('secret:"***"');
expect(out).toContain('ok:"v"');
});
it('truncates long strings with a Unicode ellipsis + byte count (not ASCII dots)', () => {
// The reported change-request: the marker is `…<N B>` (U+2026), not `...<N B>`.
const out = renderParamsVerbose({ blob: 'a'.repeat(500) });
expect(out).toContain('…<500B>');
expect(out).not.toContain('...<500B>');
});
it('guards against circular references', () => {
const o: Record<string, unknown> = { a: 1 };
o.self = o;
expect(renderParamsVerbose(o)).toContain('"[circular]"');
});
it('renders nested structure with primitives intact', () => {
expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}');
});
});

View File

@@ -0,0 +1,45 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
// The file transport writes to disk; stub it so the test has no side effects.
vi.mock('../src/log-file-transport', () => ({
getFileTransport: () => ({ write: () => {} }),
}));
import { createLogger } from '../src/logger';
// Regression for issue #162: a hook-reported garbage UIN (13-digit, timestamp
// shaped) produced a `[…]` tag wider than the fixed UIN slot, and the colored
// render path did `' '.repeat(slot - tagLen)` → RangeError: Invalid count value
// → uncaughtException. The padding must clamp at zero.
describe('logger UIN slot padding', () => {
let prevTTY: boolean | undefined;
let prevNoColor: string | undefined;
beforeEach(() => {
prevTTY = process.stdout.isTTY;
prevNoColor = process.env.NO_COLOR;
// Force the colored render path (the only one that used .repeat()).
(process.stdout as unknown as { isTTY: boolean }).isTTY = true;
delete process.env.NO_COLOR;
vi.spyOn(process.stdout, 'write').mockReturnValue(true);
vi.spyOn(process.stderr, 'write').mockReturnValue(true);
});
afterEach(() => {
(process.stdout as unknown as { isTTY: boolean | undefined }).isTTY = prevTTY;
if (prevNoColor === undefined) delete process.env.NO_COLOR;
else process.env.NO_COLOR = prevNoColor;
vi.restoreAllMocks();
});
it('does not throw when the UIN tag exceeds the slot width', () => {
const log = createLogger('Test').child({ uin: '1701414379536' }); // 13-digit → [..] = 15 chars
expect(() => log.info('phantom account line')).not.toThrow();
expect(() => log.error('phantom error line')).not.toThrow();
});
it('still renders a normal-width UIN and a no-UIN logger', () => {
expect(() => createLogger('Test').child({ uin: '10001' }).info('ok')).not.toThrow();
expect(() => createLogger('Test').info('no uin')).not.toThrow();
});
});

View File

@@ -0,0 +1,34 @@
import { describe, expect, it } from 'vitest';
import { currentRequestId, nextRequestId, runWithRequestId } from '../src/request-context';
describe('request-context', () => {
it('nextRequestId increments monotonically and stays a positive integer', () => {
const a = nextRequestId();
const b = nextRequestId();
expect(a).toBeGreaterThan(0);
expect(b).toBe(a + 1);
});
it('runWithRequestId binds the id across sync + async, with nested scopes restoring', async () => {
expect(currentRequestId()).toBeUndefined();
runWithRequestId(42, () => {
expect(currentRequestId()).toBe(42);
runWithRequestId(99, () => {
expect(currentRequestId()).toBe(99);
});
expect(currentRequestId()).toBe(42); // outer scope restored after the nested one
});
expect(currentRequestId()).toBeUndefined(); // cleared outside any scope
await runWithRequestId(7, async () => {
await Promise.resolve();
expect(currentRequestId()).toBe(7); // survives awaits in the same async chain
});
});
it('returns the callback result', () => {
expect(runWithRequestId(1, () => 'value')).toBe('value');
});
});

View File

@@ -0,0 +1,131 @@
import { describe, it, expect, vi } from 'vitest';
import { createSingleFlightCache } from '../src/single-flight-cache';
/** A promise whose resolve/reject is exposed, for driving single-flight races. */
function deferred<T>() {
let resolve!: (v: T) => void;
let reject!: (e: unknown) => void;
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
return { promise, resolve, reject };
}
describe('SingleFlightCache', () => {
it('caches within the TTL and reloads once expired', async () => {
let clock = 1000;
const load = vi.fn(async (k: string) => `${k}@${clock}`);
const cache = createSingleFlightCache<string, string>({ ttlMs: 100, load, now: () => clock });
expect(await cache.get('a')).toBe('a@1000');
clock = 1050; // still fresh (< 100)
expect(await cache.get('a')).toBe('a@1000');
expect(load).toHaveBeenCalledTimes(1);
clock = 1101; // 101ms since store → expired
expect(await cache.get('a')).toBe('a@1101');
expect(load).toHaveBeenCalledTimes(2);
});
it('de-dupes concurrent callers onto a single load (single-flight)', async () => {
const d = deferred<string>();
const load = vi.fn(() => d.promise);
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
const p1 = cache.get('k');
const p2 = cache.get('k');
const p3 = cache.get('k');
expect(load).toHaveBeenCalledTimes(1); // only one load in flight
d.resolve('v');
expect(await Promise.all([p1, p2, p3])).toEqual(['v', 'v', 'v']);
expect(load).toHaveBeenCalledTimes(1);
});
it('keys independently — different keys load separately', async () => {
const load = vi.fn(async (k: number) => k * 2);
const cache = createSingleFlightCache<number, number>({ ttlMs: 1000, load });
expect(await cache.get(1)).toBe(2);
expect(await cache.get(2)).toBe(4);
expect(load).toHaveBeenCalledTimes(2);
});
it('force bypasses the freshness check but still joins an in-flight load', async () => {
let clock = 0;
const load = vi.fn(async (k: string) => `${k}@${clock}`);
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load, now: () => clock });
expect(await cache.get('a')).toBe('a@0'); // 1 load, cached fresh
clock = 5; // still fresh
expect(await cache.get('a', { force: true })).toBe('a@5'); // force → reload despite fresh
expect(load).toHaveBeenCalledTimes(2);
// force still single-flights: two concurrent forced gets share one load.
const d = deferred<string>();
load.mockImplementationOnce(() => d.promise);
const p1 = cache.get('a', { force: true });
const p2 = cache.get('a', { force: true });
expect(load).toHaveBeenCalledTimes(3); // not 4
d.resolve('shared');
expect(await Promise.all([p1, p2])).toEqual(['shared', 'shared']);
});
it('shouldCache=false leaves the entry uncached (next call reloads) but still de-dupes in-flight', async () => {
let n = 0;
const load = vi.fn(async () => ({ error: true as boolean, n: ++n }));
const cache = createSingleFlightCache({ ttlMs: 10_000, load, shouldCache: (v) => !v.error });
// concurrent callers still share one load...
const [a, b] = await Promise.all([cache.get('k'), cache.get('k')]);
expect(a).toEqual({ error: true, n: 1 });
expect(b).toEqual({ error: true, n: 1 });
expect(load).toHaveBeenCalledTimes(1);
// ...but nothing was cached, so the next call reloads.
expect(await cache.get('k')).toEqual({ error: true, n: 2 });
expect(load).toHaveBeenCalledTimes(2);
// a good result IS cached.
load.mockImplementationOnce(async () => ({ error: false, n: ++n }));
const good = await cache.get('k');
expect(good).toEqual({ error: false, n: 3 });
expect(await cache.get('k')).toEqual({ error: false, n: 3 }); // served from cache
expect(load).toHaveBeenCalledTimes(3);
});
it('a rejected load propagates to all joined callers, is not cached, and clears in-flight', async () => {
let attempt = 0;
const load = vi.fn(async () => {
attempt++;
if (attempt === 1) throw new Error('boom');
return 'ok';
});
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
const p1 = cache.get('k');
const p2 = cache.get('k');
await expect(p1).rejects.toThrow('boom');
await expect(p2).rejects.toThrow('boom'); // same in-flight, same rejection
expect(load).toHaveBeenCalledTimes(1);
// in-flight cleared + not cached → next call retries and succeeds.
expect(await cache.get('k')).toBe('ok');
expect(load).toHaveBeenCalledTimes(2);
});
it('invalidate drops a cached entry; clear drops all', async () => {
const load = vi.fn(async (k: string) => k.toUpperCase());
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
await cache.get('a');
await cache.get('b');
expect(load).toHaveBeenCalledTimes(2);
cache.invalidate('a');
await cache.get('a'); // reloads
await cache.get('b'); // still cached
expect(load).toHaveBeenCalledTimes(3);
cache.clear();
await cache.get('a');
await cache.get('b');
expect(load).toHaveBeenCalledTimes(5);
});
});

View File

@@ -0,0 +1,40 @@
import { describe, expect, it } from 'vitest';
import { isRealUin } from '../src/uin';
describe('isRealUin', () => {
it('accepts real QQ UINs (5..10 digits)', () => {
expect(isRealUin('10001')).toBe(true); // 5-digit floor
expect(isRealUin('123456789')).toBe(true);
expect(isRealUin('4294967295')).toBe(true); // uint32 max, 10 digits
});
it('rejects the empty string and "0"', () => {
expect(isRealUin('')).toBe(false);
expect(isRealUin('0')).toBe(false);
});
it('rejects too-short UINs (< 5 digits)', () => {
expect(isRealUin('1')).toBe(false);
expect(isRealUin('1234')).toBe(false);
});
it('rejects the garbage timestamp-shaped UINs from issue #162 (11+ digits)', () => {
expect(isRealUin('1701414379536')).toBe(false); // 13-digit ms timestamp
expect(isRealUin('1614019567632')).toBe(false);
expect(isRealUin('2014024115056')).toBe(false);
expect(isRealUin('12345678901')).toBe(false); // 11 digits — first rejected width
});
it('rejects non-digit strings (path traversal / injection guards)', () => {
expect(isRealUin('12345a')).toBe(false);
expect(isRealUin('12 345')).toBe(false);
expect(isRealUin('../etc')).toBe(false);
expect(isRealUin('123456\n')).toBe(false);
});
it('guarantees a BigInt-safe pure-digit string on accept', () => {
const uin = '123456789';
expect(isRealUin(uin)).toBe(true);
expect(() => BigInt(uin)).not.toThrow();
});
});

16
packages/core/config/.gitignore vendored Normal file
View File

@@ -0,0 +1,16 @@
# Per-instance runtime state written by the dev server / production daemon.
# `runtime.json` is the only tracked file (the deploy-time overrides for
# webuiPort, hookAutoLoad, etc); everything else here is operator-private:
# * webui.json — admin password hash + rotation state
# * consent.json — EULA/PRIVACY acceptance per agreement version
# * notifications.json — per-account webhook destinations
# * onebot_<uin>.json — per-uin OneBot transport binding (HTTP/WS ports etc)
# * ui.json — WebUI panel layout per operator
#
# Without this ignore file, every `pnpm dev:mode` / `node dist/index.mjs`
# leaves a 5-file untracked surface in `packages/core/config/` that pollutes
# `git status` and would accidentally commit local creds if `git add -A` is used.
*
!.gitignore
!runtime.json

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.10.0",
"version": "1.11.3",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -54,7 +54,7 @@
"@rollup/plugin-node-resolve": "^16.0.3",
"@types/node": "^24.12.2",
"cross-env": "^10.1.0",
"hono": "^4.12.21",
"hono": "^4.12.25",
"tsx": "^4.21.0",
"typescript": "catalog:",
"vite": "catalog:",

View File

@@ -8,6 +8,7 @@ import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetc
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark';
import { GetGroupRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-group-recommend-ark';
import { createSingleFlightCache, type SingleFlightCache } from '@snowluma/common/single-flight-cache';
import type {
FriendInfo,
GroupMemberInfo,
@@ -55,16 +56,19 @@ 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.
* Per-group TTL + single-flight cache for `fetchGroupMemberList`, keyed by
* groupId, living 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[] }>();
private readonly memberListCache: SingleFlightCache<number, GroupMemberInfo[]> =
createSingleFlightCache({
ttlMs: MEMBER_LIST_TTL_MS,
load: (groupId) => this.fetchGroupMemberListUncached(groupId),
});
constructor(private readonly ctx: BridgeContext) { }
@@ -111,6 +115,10 @@ export class ContactsApi {
memberCount: raw.info?.memberCount ?? 0,
memberMax: raw.info?.memberMax ?? 0,
members: new Map(),
// #197: the list already carries these — no extra fetch needed. `level`
// is not in the list (0x88D_0 detail only), so it stays undefined here.
createTime: raw.info?.createdTime ?? 0,
memo: raw.info?.announcement || raw.info?.description || '',
});
}
this.ctx.identity.rememberGroups(groups);
@@ -136,31 +144,19 @@ export class ContactsApi {
memberCount: Number(r.memberCount ?? 0n),
memberMax: Number(r.maxMemberCount ?? 0n),
members: new Map(),
// #197: the detail is the only source of `level`; it also carries
// createTime + the notice preview (memo).
createTime: Number(r.createTime ?? 0n),
level: Number(r.level ?? 0n),
memo: r.noticePreview ?? '',
};
}
async fetchGroupMemberList(
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;
return this.memberListCache.get(groupId, { force: options.force });
}
private async fetchGroupMemberListUncached(groupId: number): Promise<GroupMemberInfo[]> {
@@ -232,6 +228,13 @@ export class ContactsApi {
return requests;
}
/** The approval msgseq captured from a private "qun.invite" card for this
* group, or undefined if none was seen. `set_group_add_request` uses it to
* approve a bot self-invite via 0x10c8 (eventType=2). See issue #125. */
getGroupInviteCardSequence(groupId: number): number | undefined {
return this.ctx.identity.getGroupInviteCardSequence(groupId);
}
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
const resp = await FetchDownloadRkeys.invoke(this.ctx);

View File

@@ -5,6 +5,9 @@ import {
} 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 { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon';
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
import { createLogger } from '@snowluma/common/logger';
import type { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
@@ -28,15 +31,6 @@ export interface PttTransInput {
fileId?: number;
}
function hexToBytes(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;
}
// ─────────────── public types (re-exported from bridge.ts as before) ───
export type StrangerStatus = NamespaceStrangerStatus;
@@ -55,6 +49,8 @@ export interface AiVoiceItem {
voiceExampleUrl: string;
}
const log = createLogger('Bridge.Extras');
export class ExtrasApi {
constructor(private readonly ctx: BridgeContext) { }
@@ -126,10 +122,13 @@ export class ExtrasApi {
* already-transcribed case). For a freshly-received voice the response is an
* empty ack and the text is delivered later via the async Event 0x210
* subType-61 push — callers should treat `''` as "pending" and wait for the
* `ptt_trans_result` event (correlated by msgId). Live-verified end to end.
* `ptt_trans_result` event (correlated by msgId).
*/
async translatePttToText(input: PttTransInput): Promise<string> {
const md5 = hexToBytes(input.md5Hex);
// QQ NT sends the md5 as a 32-char lowercase HEX STRING, not the raw 16
// bytes (RE'd from wrapper.linux.node EncodeTroopPtt/EncodeC2CPtt: the md5
// field goes through a bytes→hex helper). Sending raw bytes → errCode -1079.
const md5 = input.md5Hex.toLowerCase();
const req: PttTransReq = input.isGroup
? {
type: 1,
@@ -154,7 +153,32 @@ export class ExtrasApi {
}
const resp = protobuf_decode<PttTransResp>(result.responseData);
const item = input.isGroup ? resp?.groupResult : resp?.c2cResult;
if (item?.errCode) throw new Error(`ptt translate failed: error=${item.errCode}`);
if (item?.errCode) {
// Diagnostic (#165 备选): correlate QQ's errCode with the request fields we
// sourced from cache, to tell a server-side ASR failure apart from our own
// missing/zero field (md5/format/uuid). Behaviour unchanged — still throws.
log.warn(
'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d',
item.errCode, input.isGroup,
input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY',
input.format, input.uuid ? 'set' : 'EMPTY', input.duration, input.size,
);
throw new Error(`ptt translate failed: error=${item.errCode}`);
}
return item?.text ?? ''; // '' = transcribing async; caller awaits the push
}
/**
* Transcode a voice record (`get_record out_format`, #165). `source` is a
* URL / local path / `base64://…` (the record's download URL in practice);
* it is loaded then transcoded to `format` via the bundled SILK-capable
* ffmpeg addon. Returns base64 + size. Throws on unsupported format or a
* failed conversion.
*/
async convertRecord(source: string, format: string): Promise<{ base64: string; size: number }> {
// Voices are tiny — cap the download well below loadBinarySource's 1 GiB
// default so a tampered/oversized source can't be pulled in.
const { bytes } = await loadBinarySource(source, 'record', 64 * 1024 * 1024);
return convertAudioBytes(bytes, format);
}
}

View File

@@ -2,6 +2,7 @@
// 复用 OIDB 基础设施(invokeOidb),协议层在 @snowluma/protocol/oidb-services/flash-transfer/。
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid } from './shared';
import type { FlashFileEntry } from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { GetFilesetDetail } from '@snowluma/protocol/oidb-services/flash-transfer/get-fileset-detail';
import { ListFilesets } from '@snowluma/protocol/oidb-services/flash-transfer/list-filesets';
@@ -276,7 +277,9 @@ export class FlashTransferApi {
const uploader = {
uin: this.ctx.identity.uin,
nickname: this.ctx.identity.nickname,
uid: this.ctx.identity.selfUid ?? '',
// Resolve our own uid rather than ship an empty one — a blank uploader
// uid drops the fileset if this runs before warmup populated selfUid.
uid: await resolveSelfUid(this.ctx),
};
// 读取所有文件,每个分配 fileUuid + 序号 + formatCode
const items: { bytes: Uint8Array; fileName: string; fileUuid: string; fileIndex: number; formatCode: number }[] = [];

View File

@@ -1,4 +1,5 @@
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { mapWithConcurrency } from '@snowluma/common/concurrency';
import type {
LongMsgResult,
RecvLongMsgReq,
@@ -14,7 +15,7 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { randomUUID } from 'crypto';
import { gunzipSync, gzipSync } from 'zlib';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
import type { BridgeContext, UploadedFileMeta } from '../bridge-context';
import { resolveSelfUid, toInt } from './shared';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
@@ -24,6 +25,17 @@ function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge;
// resolve a forward immediately after receiving the parent message.
const forwardResCache = new Map<string, ForwardNodePayload[]>();
/** QQ's placeholder when it doesn't hand back a real sender name — treated as
* "missing" so #174's enrichment resolves the real nickname. */
const FORWARD_NAME_PLACEHOLDER = 'QQ用户';
/** Bounds on the L4 (per-uin profile) fallback when enriching forward senders.
* Profile lookups are un-cached single-point OIDB calls Tencent rate-limits
* aggressively, so cap how many distinct uins one forward resolves and how
* many run at once — the rest keep the placeholder. */
const FORWARD_PROFILE_MAX = 20;
const FORWARD_PROFILE_CONCURRENCY = 4;
// 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
@@ -139,7 +151,9 @@ async function buildForwardPushBody(
return {
responseHead: {
fromUin,
toUid: bridge.identity.selfUid ?? '',
// Resolve our own uid rather than ship an empty one — a blank toUid is a
// broken packet if this runs before warmup populated selfUid.
toUid: await resolveSelfUid(bridge),
forward: {
friendName: nickname,
},
@@ -202,6 +216,46 @@ function previewFromElements(elements: MessageElement[]): string {
return '';
}
function cloneNodeWithElements(node: ForwardNodePayload, elements: MessageElement[]): ForwardNodePayload {
return {
userUin: node.userUin,
nickname: node.nickname,
elements,
time: node.time,
msgId: node.msgId,
msgSeq: node.msgSeq,
groupId: node.groupId,
senderCard: node.senderCard,
messageType: node.messageType,
innerForward: node.innerForward,
};
}
function stripFileSource(element: MessageElement): MessageElement {
const next: MessageElement = { ...element };
delete next.url;
return next;
}
function isCachedFileUsableInTarget(
cached: UploadedFileMeta | undefined,
groupId?: number,
userId?: number,
): boolean {
if (!cached) return true;
if (groupId !== undefined) {
return cached.scope === 'group' && cached.groupId === groupId;
}
if (userId !== undefined) {
return cached.scope === 'private' && cached.userId === userId;
}
return true;
}
function fileNameForUpload(element: MessageElement, cached?: UploadedFileMeta): string {
return (element.fileName ?? cached?.fileName ?? '').trim();
}
export class ForwardApi {
constructor(private readonly ctx: BridgeContext) { }
@@ -210,6 +264,101 @@ export class ForwardApi {
return resId;
}
private async downloadSourceFromCachedFile(cached: UploadedFileMeta): Promise<string> {
if (cached.scope === 'group' && cached.groupId !== undefined) {
return this.ctx.apis.groupFile.getUrl(cached.groupId, cached.fileId);
}
if (cached.scope === 'private' && cached.userId !== undefined && cached.fileHash) {
return this.ctx.apis.groupFile.getPrivateUrl(cached.userId, cached.fileId, cached.fileHash);
}
throw new Error('forward file_id belongs to another scope; pass file/base64/url so SnowLuma can re-upload it');
}
private async uploadForwardFileSource(
source: string,
name: string,
groupId?: number,
userId?: number,
): Promise<MessageElement> {
if (groupId !== undefined) {
const uploaded = await this.ctx.apis.groupFile.upload(groupId, source, name, '/', true, false);
if (!uploaded.fileId) throw new Error('forward group file upload returned no file_id');
const cached = this.ctx.recallUploadedFile(uploaded.fileId);
const element: MessageElement = {
type: 'file',
fileId: uploaded.fileId,
};
const fileName = cached?.fileName || name;
if (fileName) element.fileName = fileName;
if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize;
return element;
}
if (userId !== undefined) {
const uploaded = await this.ctx.apis.groupFile.uploadPrivate(userId, source, name, true, false);
if (!uploaded.fileId) throw new Error('forward private file upload returned no file_id');
const cached = this.ctx.recallUploadedFile(uploaded.fileId);
const element: MessageElement = {
type: 'file',
fileId: uploaded.fileId,
};
const fileName = cached?.fileName || name;
const fileHash = uploaded.fileHash ?? cached?.fileHash ?? '';
if (fileName) element.fileName = fileName;
if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize;
if (fileHash) element.fileHash = fileHash;
return element;
}
throw new Error('forward file source requires group_id or user_id');
}
private async prepareForwardFileElement(
element: MessageElement,
groupId?: number,
userId?: number,
): Promise<MessageElement> {
if (element.type !== 'file') return element;
const source = (element.url ?? '').trim();
if (source && !element.fileId) {
const uploaded = await this.uploadForwardFileSource(source, fileNameForUpload(element), groupId, userId);
return {
...stripFileSource(element),
...uploaded,
};
}
if (element.fileId) {
const cached = this.ctx.recallUploadedFile(element.fileId);
if (isCachedFileUsableInTarget(cached, groupId, userId)) return element;
const sourceFromCache = await this.downloadSourceFromCachedFile(cached!);
const uploaded = await this.uploadForwardFileSource(
sourceFromCache,
fileNameForUpload(element, cached),
groupId,
userId,
);
return {
...stripFileSource(element),
...uploaded,
};
}
return element;
}
private async prepareForwardFiles(
nodes: ForwardNodePayload[],
groupId?: number,
userId?: number,
): Promise<ForwardNodePayload[]> {
return Promise.all(nodes.map(async (node) => {
const elements = await Promise.all(node.elements.map(
element => this.prepareForwardFileElement(element, groupId, userId),
));
return cloneNodeWithElements(node, elements);
}));
}
/**
* Recursive upload with NapCat-style piggyback. Each invocation:
* 1. Walks `nodes`. For any node whose `innerForward` is set,
@@ -304,8 +453,10 @@ export class ForwardApi {
}
}
const uploadReadyNodes = await this.prepareForwardFiles(processedNodes, groupId, userId);
// Encode this level's msgBody.
const msgBody = await Promise.all(processedNodes.map(
const msgBody = await Promise.all(uploadReadyNodes.map(
node => buildForwardPushBody(bridge, node, groupId, userUid),
));
@@ -349,7 +500,7 @@ export class ForwardApi {
throw new Error('upload forward message response missing res_id');
}
forwardResCache.set(resId, processedNodes.map(node => ({
forwardResCache.set(resId, uploadReadyNodes.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
@@ -381,7 +532,7 @@ export class ForwardApi {
const bridge = asBridge(this.ctx);
const cached = forwardResCache.get(resId);
if (cached) {
return cached.map(node => ({
const nodes = cached.map(node => ({
userUin: node.userUin,
nickname: node.nickname,
elements: [...node.elements],
@@ -392,6 +543,10 @@ export class ForwardApi {
senderCard: node.senderCard,
messageType: node.messageType,
}));
// Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich
// on read (a no-op once names are present) and persist so later hits skip.
if (await this.enrichSenders(nodes)) forwardResCache.set(resId, cloneNodes(nodes));
return nodes;
}
const selfUid = await resolveSelfUid(bridge);
@@ -451,12 +606,94 @@ export class ForwardApi {
this.consumePiggybacks(nodes, piggybackByUuid);
}
// Fill sender nickname/card for nodes the SsoRecvLongMsg payload left empty
// or stamped with the "QQ用户" placeholder (#174) — the long-msg member name
// isn't always populated, and the sync decode only consults the L1 cache.
await this.enrichSenders(nodes);
if (nodes.length > 0) {
forwardResCache.set(resId, cloneNodes(nodes));
}
return nodes;
}
/** A node whose display name the server didn't give us (empty or the QQ
* placeholder) and that we can resolve (has a uin). */
private needsName(n: ForwardNodePayload): boolean {
return !!n.userUin && (!n.nickname || n.nickname === FORWARD_NAME_PLACEHOLDER);
}
/** Backfill sender nickname/card on forward nodes the long-msg payload left
* nameless. Resolves group senders via one member-list fetch per group (L3,
* inflight+TTL cached in ContactsApi), then any residue + private nodes via
* the user-profile lookup (L4). Best-effort: a failed lookup keeps the
* placeholder rather than failing the whole forward. Returns true if any
* node was changed (so callers can persist the enriched cache). */
private async enrichSenders(nodes: ForwardNodePayload[]): Promise<boolean> {
const pending = nodes.filter(n => this.needsName(n));
if (pending.length === 0) return false;
let changed = false;
// L3 — group member lists (one fetch resolves every sender from that group).
const byGroup = new Map<number, ForwardNodePayload[]>();
const residue: ForwardNodePayload[] = [];
for (const n of pending) {
if (n.messageType === 'group' && n.groupId) {
const arr = byGroup.get(n.groupId) ?? [];
arr.push(n);
byGroup.set(n.groupId, arr);
} else {
residue.push(n);
}
}
for (const [groupId, groupNodes] of byGroup) {
let byUin: Map<number, { nickname: string; card: string }>;
try {
const members = await this.ctx.apis.contacts.fetchGroupMemberList(groupId);
byUin = new Map(members.map(m => [m.uin, { nickname: m.nickname, card: m.card }]));
} catch {
// Member list (one cheap, cached call) failed — keep the placeholder
// rather than fanning the whole group out to per-uin profile lookups.
// That error path is exactly what would amplify into a rate-limit ban.
continue;
}
for (const n of groupNodes) {
const m = byUin.get(n.userUin);
const name = m?.card || m?.nickname;
if (name) {
n.senderCard = m!.card || n.senderCard || '';
n.nickname = name;
changed = true;
} else {
residue.push(n); // in-group sender that left the group → profile fallback
}
}
}
// L4 — user profile for the residue (members who left the group, private
// nodes). fetchUserProfile is an un-cached single-point OIDB 0xFE1_2, and
// Tencent rate-limits these hard (see ContactsApi's member-list note), so:
// dedupe by uin, CAP the count (drop the rest to placeholder), and resolve
// in small concurrency-limited batches. Best-effort.
const uins = [...new Set(residue.filter(n => this.needsName(n)).map(n => n.userUin))]
.slice(0, FORWARD_PROFILE_MAX);
if (uins.length > 0) {
const byUin = new Map<number, string>();
const results = await mapWithConcurrency(uins, FORWARD_PROFILE_CONCURRENCY,
async (uin): Promise<readonly [number, string]> => {
try { return [uin, (await this.ctx.apis.contacts.fetchUserProfile(uin)).nickname] as const; }
catch { return [uin, ''] as const; }
});
for (const [uin, nick] of results) byUin.set(uin, nick);
for (const n of residue) {
if (!this.needsName(n)) continue;
const nick = byUin.get(n.userUin);
if (nick) { n.nickname = nick; changed = true; }
}
}
return changed;
}
/** 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. */
@@ -479,6 +716,9 @@ export class ForwardApi {
if (!event) continue;
if (event.kind === 'group_message') {
// [#201] The merged-forward sender name now comes through the group
// decoder (event.senderNick), which reads grp.memberCard (field 4) when
// there's no member cache — exactly the forward-node case.
out.push({
userUin: event.senderUin,
nickname: event.senderCard || event.senderNick,

View File

@@ -35,8 +35,8 @@ export class GroupAdminApi {
return SetAddOption.invoke(this.ctx, { groupId, addType });
}
setSearch(groupId: number): Promise<void> {
return SetSearch.invoke(this.ctx, { groupId });
setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise<void> {
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
}
setAddRequest(
@@ -54,8 +54,26 @@ export class GroupAdminApi {
return KickMembers.invoke(this.ctx, { groupId, userIds, reject });
}
leave(groupId: number): Promise<void> {
return LeaveGroup.invoke(this.ctx, { groupId });
async leave(groupId: number): Promise<void> {
await LeaveGroup.invoke(this.ctx, { groupId });
// The server doesn't push a member-decrease back to the member who left of
// its own accord, so synthesize the self group_member_leave here — otherwise
// downstream never sees notice.group_decrease and keeps a "zombie" group in
// its cache (#133). Also drop the group from our own roster.
const selfUin = Number(this.ctx.identity.uin) || 0;
const selfUid = this.ctx.identity.selfUid ?? '';
await this.ctx.events.emit({
kind: 'group_member_leave',
time: Math.floor(Date.now() / 1000),
selfUin,
groupId,
userUin: selfUin,
operatorUin: selfUin,
userUid: selfUid,
operatorUid: selfUid,
leaveType: 'leave',
});
this.ctx.identity.forgetGroup(groupId);
}
setAdmin(groupId: number, userId: number, enable: boolean): Promise<void> {

View File

@@ -1,9 +1,12 @@
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 { FileChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
import { FILE_UPLOAD_MAX_BYTES } from '@snowluma/protocol/highway/utils';
import { stageSourceToDisk } from '@snowluma/protocol/highway/stage';
import { hashFileStreaming } from '@snowluma/protocol/highway/hash-file';
import { protobuf_encode } from '@snowluma/proton';
import { promises as fsp } from 'fs';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid, toInt, type MediaIndexNode } from './shared';
@@ -12,6 +15,7 @@ import { CreateGroupFolder } from '@snowluma/protocol/oidb-services/group-file/c
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 { GetGroupFileSpace } from '@snowluma/protocol/oidb-services/group-file/get-group-file-space';
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';
@@ -23,6 +27,7 @@ import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-
import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file';
import { RenameGroupFile } from '@snowluma/protocol/oidb-services/group-file/rename-group-file';
import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder';
import { TransGroupFile, type TransGroupFileResult } from '@snowluma/protocol/oidb-services/group-file/trans-group-file';
import { 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';
@@ -100,9 +105,20 @@ function normalizeUploadFileName(name: string, fallback: string): string {
return safeFallback || 'file.bin';
}
function md5First10MB(bytes: Uint8Array): Uint8Array {
const limit = Math.min(bytes.length, 10 * 1024 * 1024);
return computeMd5(bytes.subarray(0, limit));
// QQ's "first 10 MB" checksum uses the magic limit 0x98A000 (10002432) —
// NOT 10*1024*1024 and not 10^7. Using the wrong limit makes the server's
// first-block verification fail for files larger than 0x98A000, so the
// offline file uploads but never finalises as downloadable (#157).
const MD5_HEAD_LIMIT = 10002432;
/** Fail cleanly if the staged file changed since the streaming hash pass (a
* local source mutated mid-send). The server's per-chunk md5 during the PUT is
* the backstop; this is the cheap early check. */
async function assertUnchanged(filePath: string, baseline: { size: number; mtimeMs: number }): Promise<void> {
const now = await fsp.stat(filePath);
if (now.size !== baseline.size || now.mtimeMs !== baseline.mtimeMs) {
throw new Error('file source changed during send (mutated between hashing and upload)');
}
}
function buildGroupFileUploadExt(
@@ -177,7 +193,12 @@ function buildPrivateFileUploadExt(
unknown2: 1,
entry: {
busiBuff: {
busId: 102,
// #157: NapCat/Lagrange (and the QQ client, confirmed by packet
// capture) emit a busiBuff with ONLY senderUin — no busId. A stale
// busId:102 here made the offline-file server accept the highway
// upload but never finalise it as downloadable once the file got
// big (>5 MiB): the receiver saw the file but every download failed.
// (The other half of that bug was the wrong md5-head limit above.)
senderUin: BigInt(senderUin),
receiverUin: 0n,
groupCode: 0n,
@@ -227,12 +248,21 @@ export class GroupFileApi {
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
}
trans(groupId: number, fileId: string): Promise<TransGroupFileResult> {
if (!fileId) throw new Error('trans requires fileId');
return TransGroupFile.invoke(this.ctx, { groupId, fileId });
}
// ─────────────── count ───────────────
getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> {
return GetGroupFileCount.invoke(this.ctx, { groupId });
}
getSpace(groupId: number): Promise<{ usedSpace: number; totalSpace: number }> {
return GetGroupFileSpace.invoke(this.ctx, { groupId });
}
// ─────────────── upload (3-stage: OIDB preflight → highway → publish) ───────────────
async upload(
@@ -241,99 +271,113 @@ export class GroupFileApi {
name = '',
folderId = '/',
uploadFile = true,
publishFile = uploadFile,
): Promise<UploadFileResult> {
const bridge = asBridge(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');
// Group/private files may legitimately be up to 4 GiB on QQ's wire, so
// override the default 1 GiB cap with the protocol ceiling. Stage onto a
// local disk path and stream-hash it — the (up to 4 GiB) file is never
// buffered in RAM.
const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES);
try {
if (staged.fileSize === 0) throw new Error('group file is empty');
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const fileName = normalizeUploadFileName(name, staged.fileName);
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
const hashes = await hashFileStreaming(staged.filePath);
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,
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
groupId,
fileName,
loaded.bytes.length,
hashes.md5,
folderId: normalizeDirectory(folderId),
fileSize: staged.fileSize,
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,
upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
uploadHost,
uploadPort,
);
scope: 'group',
groupId,
fileName,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
rememberedAt: Date.now(),
});
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext);
}
if (!upload.boolFileExist && uploadFile) {
const senderUin = toInt(this.ctx.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
// 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));
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,
staged.fileSize,
hashes.md5,
fileId,
upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
uploadHost,
uploadPort,
);
// Fail cleanly if the source changed since hashing, then stream the PUT
// from disk. Fetch the session BEFORE opening the handle so
// uploadHighwayHttp (the handle's owner) is the next call and always
// closes it.
await assertUnchanged(staged.filePath, guardStat);
const session = await fetchHighwaySession(bridge);
const chunkSource = await FileChunkSource.open(staged.filePath, staged.fileSize);
await uploadHighwayHttp(bridge, session, 71, chunkSource, hashes.md5, ext);
}
}
return { fileId };
// 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 a
// caller only needs a valid file_id embedded elsewhere, e.g. a
// forward-message long-msg payload. Routes through `this.publish` so
// tests can mock at the same Api boundary.
if (publishFile) {
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 };
} finally {
await staged.cleanup();
}
}
async uploadPrivate(
@@ -341,35 +385,34 @@ export class GroupFileApi {
source: string,
name = '',
uploadFile = true,
publishFile = uploadFile,
): Promise<UploadFileResult> {
const bridge = asBridge(this.ctx);
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
if (!loaded.bytes.length) throw new Error('private file is empty');
// Stage onto a local disk path + stream-hash — the (up to 4 GiB) file is
// never buffered in RAM. headLimit = MD5_HEAD_LIMIT yields the offline-file
// md510MCheckSum in the same single pass.
const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES);
try {
if (staged.fileSize === 0) throw new Error('private file is empty');
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 selfUid = await resolveSelfUid(this.ctx);
const senderUin = toInt(this.ctx.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const fileName = normalizeUploadFileName(name, staged.fileName);
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
const hashes = await hashFileStreaming(staged.filePath, { headLimit: MD5_HEAD_LIMIT });
const upload = await UploadPrivateFileRequest.invoke(this.ctx, {
senderUid: selfUid,
receiverUid: targetUid,
fileName,
fileSize: loaded.bytes.length,
fileSize: staged.fileSize,
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
md510MCheckSum: md5First10MB(loaded.bytes),
md510MCheckSum: hashes.headMd5!,
});
ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined);
@@ -387,7 +430,7 @@ export class GroupFileApi {
scope: 'private',
userId,
fileName,
fileSize: loaded.bytes.length,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
fileHash: fileHash ?? '',
@@ -461,7 +504,7 @@ export class GroupFileApi {
const ext = buildPrivateFileUploadExt(
senderUin,
fileName,
loaded.bytes.length,
staged.fileSize,
hashes.md5,
hashes.sha1,
fileId,
@@ -472,8 +515,13 @@ export class GroupFileApi {
uploadPort,
);
// Fail cleanly if the source changed since hashing, then stream the PUT
// from disk. Session BEFORE opening the handle so uploadHighwayHttp (the
// handle's owner) is the next call and always closes it.
await assertUnchanged(staged.filePath, guardStat);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext);
const chunkSource = await FileChunkSource.open(staged.filePath, staged.fileSize);
await uploadHighwayHttp(bridge, session, 95, chunkSource, hashes.md5, ext);
}
// Stage 3: publish the file as a c2c chat message. C2C files use
@@ -482,12 +530,12 @@ export class GroupFileApi {
// 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) {
if (publishFile) {
try {
await this.ctx.apis.message.sendC2cFile(userId, targetUid, {
fileId,
fileName,
fileSize: loaded.bytes.length,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileHash: fileHash ?? '',
});
@@ -498,6 +546,9 @@ export class GroupFileApi {
}
return { fileId, fileHash };
} finally {
await staged.cleanup();
}
}
// ─────────────── list (paginated loop) ───────────────
@@ -611,7 +662,7 @@ export class GroupFileApi {
// ─────────────── folders ───────────────
createFolder(groupId: number, name: string, parentId = '/'): Promise<void> {
createFolder(groupId: number, name: string, parentId = '/'): Promise<CreateGroupFolder.Result> {
return CreateGroupFolder.invoke(this.ctx, {
groupId, parentId: normalizeDirectory(parentId), folderName: name,
});

View File

@@ -9,10 +9,13 @@ import type {
SsoReadedReportReq,
} from '@snowluma/proto-defs/oidb-actions/base';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol/msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid } from './shared';
// `Bridge` is imported as a type only so we can narrow `ctx` back to
// the concrete Bridge instance when passing it to `buildSendElems`
// (which still takes `Bridge` because the highway upload helpers it
@@ -25,6 +28,8 @@ import type { Bridge, SendMessageReceipt } from '../bridge';
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
const log = createLogger('Bridge.Message');
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
@@ -238,6 +243,12 @@ export class MessageApi {
* - `subcmd: 1` — c2c file send command code
* - `dangerEvel: 0` — virus-scan severity, always 0 client-side
* - `expireTime` — 7 days from now (Lagrange convention)
*
* `FileExtra.file` alone makes the file downloadable (verified on a live
* account). We ALSO attach `FileExtra.field6` — extra server-issued download
* routing from a best-effort 0xE37_800 finalize that mirrors NapCat and may
* help some receiver clients. The finalize is non-fatal: if it fails we send
* without field6 rather than failing the send (issue #157).
*/
async sendC2cFile(
userUin: number,
@@ -247,9 +258,35 @@ export class MessageApi {
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
// Resolve our own uid — needed both for the 0xE37_800 finalize and the
// `field6` download-routing the receiver reads.
const selfUid = await resolveSelfUid(this.ctx);
// The file is already downloadable from the `NotOnlineFile` reference
// alone — verified on a live account: a plain c2c file send (no field6)
// downloads fine. `field6` is EXTRA server-issued download routing (from
// the 0xE37_800 finalize) that mirrors NapCat and may help some receiver
// clients. So fetch it BEST-EFFORT: if the finalize fails, send without
// field6 rather than failing the whole send. (issue #157 — the finalize
// was originally fatal, which could regress a send that would otherwise
// succeed.)
const fileHash = info.fileHash ?? '';
let meta: Awaited<ReturnType<typeof FinalizeOfflineFile.invoke>> | null = null;
try {
meta = await FinalizeOfflineFile.invoke(this.ctx, {
senderUid: selfUid,
receiverUid: userUid,
fileUuid: info.fileId,
fileHash,
});
} catch (err) {
log.warn('c2c file finalize (0xE37_800) failed, sending without field6: %s',
err instanceof Error ? err.message : String(err));
}
const nowSec = Math.floor(Date.now() / 1000);
const sevenDaysSec = 7 * 24 * 60 * 60;
const fileExtraBytes = protobuf_encode<FileExtra>({
const fileExtra: FileExtra = {
file: {
fileType: 0,
fileUuid: info.fileId,
@@ -259,9 +296,26 @@ export class MessageApi {
subcmd: 1,
dangerEvel: 0,
expireTime: nowSec + sevenDaysSec,
fileHash: info.fileHash ?? '',
fileHash,
},
});
};
if (meta) {
fileExtra.field6 = {
field2: {
field1: meta.field110,
fileUuid: info.fileId,
fileName: info.fileName,
field6: meta.field3,
field7: meta.field101,
field8: meta.field100,
timestamp1: meta.timestamp1,
fileHash,
selfUid,
destUid: userUid,
},
};
}
const fileExtraBytes = protobuf_encode<FileExtra>(fileExtra);
const request = protobuf_encode<SendMessageRequest>({
routingHead: {

View File

@@ -10,7 +10,7 @@ import { DeleteCustomFace } from '@snowluma/protocol/oidb-services/custom-face/d
import { ModifyCustomFace } from '@snowluma/protocol/oidb-services/custom-face/modify-custom-face';
import { MoveCustomFace } from '@snowluma/protocol/oidb-services/custom-face/move-custom-face';
import { OrderCustomFace } from '@snowluma/protocol/oidb-services/custom-face/order-custom-face';
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
import { BufferChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils';
import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like';
import { GetUnidirectionalFriendList, type UnidirectionalFriendEntry } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
@@ -93,7 +93,7 @@ export class ProfileApi {
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0));
await uploadHighwayHttp(bridge, session, 90, new BufferChunkSource(loaded.bytes), hashes.md5, new Uint8Array(0));
}
/**
@@ -120,7 +120,7 @@ export class ProfileApi {
field5: 3,
field6: 1,
});
await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra);
await uploadHighwayHttp(bridge, session, 3000, new BufferChunkSource(loaded.bytes), hashes.md5, extra);
}
// ─────────────── queries on me / my contacts ───────────────

View File

@@ -4,19 +4,24 @@ import {
getQzoneFeeds,
getQzoneMsgList,
publishQzoneMsg,
setQzoneBlack,
setQzoneLike,
updateQzoneMsgRight,
uploadQzoneImageFromSource,
type QzoneCommentResult,
type QzoneFeedsResult,
type QzoneMsgListResult,
type QzonePublishResult,
type QzoneUpdateRightResult,
type QzoneUploadImageResult,
} from '@snowluma/protocol/web/qzone';
import type { BridgeContext } from '../bridge-context';
/**
* Personal QQ-Zone (个人空间) web API: 说说 (feed) read/write, likes,
* comments — all over the cookie-backed qzone.qq.com CGIs, reusing the same
* `getCookies('qzone.qq.com')` plumbing as GroupAlbumApi. Distinct from the
* group-album surface, which lives on GroupAlbumApi.
* comments, image upload — all over the cookie-backed qzone.qq.com CGIs,
* reusing the same `getCookies('qzone.qq.com')` plumbing as GroupAlbumApi.
* Distinct from the group-album surface, which lives on GroupAlbumApi.
*/
export class QzoneApi {
constructor(private readonly ctx: BridgeContext) { }
@@ -40,10 +45,30 @@ export class QzoneApi {
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count);
}
/** 发表一条纯文字说说,返回新说说的 tid。始终发到机器人自己的空间。 */
async publish(content: string): Promise<QzonePublishResult> {
/**
* 从来源上传图片到 QQ 空间。
* `source` 支持: file:// 本地路径 | http(s):// URL | base64:// base64数据
*/
async uploadImageFromSource(source: string): Promise<QzoneUploadImageResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content);
return uploadQzoneImageFromSource(cookieObject, this.ctx.identity.uin, source);
}
/**
* 发表说说,返回新说说的 tid。始终发到机器人自己的空间。
* `richType` / `richval`: 带图说说时传 richType=1 和 richval 字符串
* (多图用 `\t` 连接多个 richval)。纯文字说说省略这两个参数。
* `ugcRight` / `targetUins`: 查看权限及其作用名单(ugcRight=16/128 时必填)。
*/
async publish(
content: string,
richType?: number,
richval?: string,
ugcRight = 1,
targetUins?: string,
): Promise<QzonePublishResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content, richType, richval, ugcRight, targetUins);
}
/** 删除机器人自己空间的一条说说(按 tid)。 */
@@ -52,6 +77,15 @@ export class QzoneApi {
await deleteQzoneMsg(cookieObject, this.ctx.identity.uin, tid);
}
/**
* 修改机器人自己空间一条已发说说的查看权限(按 tid)。
* `ugcRight` / `targetUins` 含义同 publish(16/128 时 targetUins 必填)。
*/
async updateRight(tid: string, ugcRight: number, targetUins?: string): Promise<QzoneUpdateRightResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return updateQzoneMsgRight(cookieObject, this.ctx.identity.uin, tid, ugcRight, targetUins);
}
/**
* 给一条说说点赞/取消赞。`targetUin` 省略时点赞机器人自己空间的说说;
* 点赞好友说说时传好友 uin(tid 来自 get_qzone_feeds / get_qzone_msg_list)。
@@ -66,11 +100,29 @@ export class QzoneApi {
/**
* 评论一条说说。`targetUin` 为说说所属 QQ 号(省略=机器人自己空间);
* 始终以机器人身份发表评论。返回新评论 id(尽力而为)。
* `richType` / `richval`: 带图评论时传 richType=1 和图片直链 URL
* (从 uploadImageFromSource 的 url 字段获取)。
*/
async comment(tid: string, content: string, targetUin: number | undefined): Promise<QzoneCommentResult> {
async comment(
tid: string,
content: string,
targetUin: number | undefined,
richType?: number,
richval?: string,
): Promise<QzoneCommentResult> {
const selfUin = this.ctx.identity.uin;
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content);
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content, richType, richval);
}
/**
* 拉黑或解除拉黑某人(修改机器人自身 QQ 空间黑名单)。
* `ban=true` 拉黑,`ban=false` 解除拉黑。
*/
async setBlack(targetUin: number, ban: boolean): Promise<void> {
const selfUin = this.ctx.identity.uin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
await setQzoneBlack(cookieObject, selfUin, targetUin.toString(), ban);
}
}

View File

@@ -1,5 +1,3 @@
import type { Bridge } from '../bridge';
export function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'bigint') {
@@ -26,22 +24,10 @@ export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown
throw new Error(`${operation} failed: code=${retCode} msg=${text}`);
}
/**
* Look up the bot's own UID. Cached on Identity once warmup populates
* `selfProfile`; forward/profile actions need this fast path before
* warmup completes.
*/
export async function resolveSelfUid(bridge: Bridge): Promise<string> {
let selfUid = bridge.identity.selfUid;
if (selfUid) return selfUid;
const selfUin = toInt(bridge.identity.uin);
if (selfUin <= 0) {
throw new Error('self uid is unavailable');
}
selfUid = await bridge.resolveUserUid(selfUin);
return selfUid;
}
// The bot's-own-UID resolver is the single source of truth in @snowluma/protocol
// (a Bridge satisfies its BridgeContext slice). Re-exported here so the existing
// `resolveSelfUid(bridge)` call sites in this package keep importing from shared.
export { resolveSelfUid } from '@snowluma/protocol/self-uid';
/**
* Index describing a server-side rich-media object (image / video /

View File

@@ -3,7 +3,7 @@ import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sen
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push';
import { MSG_PUSH_CMD, parseMsgPush, SysMsgDedup } from '@snowluma/protocol/msg-push';
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
import { buildApiHub, type ApiHub } from './apis';
import {
@@ -26,6 +26,8 @@ export class Bridge implements BridgeInterface {
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
// Per-account dedup for QQ NT's already-deduped system pushes (#137).
private readonly sysMsgDedup_ = new SysMsgDedup();
constructor(identity: IdentityService) {
this.identity = identity;
@@ -62,7 +64,7 @@ export class Bridge implements BridgeInterface {
}
},
});
this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) => parseMsgPush(pkt, identity, this.sysMsgDedup_));
}
dispose(): void {

View File

@@ -1,6 +1,7 @@
import { createLogger } from '@snowluma/common/logger';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { isRealUin } from '@snowluma/common/uin';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { Bridge } from './bridge';
@@ -72,13 +73,8 @@ export class BridgeManager {
}
}
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;
if (!isRealUin(uin)) return;
this.pidPacketClients_.set(pid, packetClient);
@@ -94,7 +90,7 @@ export class BridgeManager {
}
onPacket(pkt: PacketInfo): void {
if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return;
if (!pkt.uin || !isRealUin(pkt.uin)) return;
const uin = pkt.uin;
// Ensure session exists

View File

@@ -2,8 +2,11 @@ import { HookManager } from '@snowluma/bridge';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import { loadRuntimeConfig } from '@snowluma/common/runtime';
import { OneBotManager } from '@snowluma/onebot/manager';
import { migrateGlobalSettings } from '@snowluma/onebot/global-config';
import { cleanupInvalidPerUinConfigs } from '@snowluma/onebot/config';
import { BridgeManager } from './bridge/manager';
import { createNotificationManager } from './notifications/manager';
import { createStateWiring } from './webui/state-wiring';
const runtimeConfig = loadRuntimeConfig();
const log = createLogger('App');
@@ -27,15 +30,33 @@ process.on('uncaughtException', (error) => {
async function main() {
log.info('SnowLuma starting');
// One-shot: lift a legacy per-UIN musicSignUrl into the global store before
// any session (and thus any per-UIN config rewrite) can drop it.
migrateGlobalSettings();
// One-shot: purge any persisted phantom accounts (onebot_<garbage>.json) the
// native hook may have created with a timestamp-shaped UIN (issue #162).
cleanupInvalidPerUinConfigs();
const bridgeManager = new BridgeManager();
const oneBotManager = new OneBotManager();
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
const hookManager = new HookManager({ bridgeManager, autoLoadOnDiscovery });
// WebUI state-push wiring: HookManager + BridgeManager edges publish
// `processes` / `qq-list` / `connections` invalidations into a bus the
// /api/state/stream SSE handler subscribes to (no REST polling required).
const stateWiring = createStateWiring();
const hookManager = new HookManager({
bridgeManager,
autoLoadOnDiscovery,
onSessionsChanged: stateWiring.onSessionsChanged,
});
if (autoLoadOnDiscovery) {
log.info('hook auto-load enabled: every discovered QQ process will be injected');
}
oneBotManager.bind(bridgeManager);
stateWiring.bindBridgeManager(bridgeManager);
// Global notification subsystem (account up/down → webhook). Bound AFTER
// OneBotManager so the nickname fallback is already populated when it observes.
@@ -52,6 +73,7 @@ async function main() {
host: runtimeConfig.webuiHost,
tlsEnabled: runtimeConfig.webuiTls?.enabled,
trustProxy: runtimeConfig.trustProxy,
stateBus: stateWiring.bus,
});
} catch (err) {
log.error('Failed to start WebUI: ', err);
@@ -65,6 +87,7 @@ async function main() {
oneBotManager.dispose();
notificationManager.dispose();
hookManager.dispose();
stateWiring.dispose();
await closeLogger();
process.exit(0);
};

View File

@@ -7,6 +7,7 @@
//
// Channels are GLOBAL (defined once here); each UIN opts into a subset via
// `OneBotConfig.notifications.channelIds` (see packages/onebot/src/config.ts).
import { boolOr, clampInt, isObject } from '@snowluma/common/coerce';
import { createLogger } from '@snowluma/common/logger';
import fs from 'fs';
import path from 'path';
@@ -92,21 +93,9 @@ export function renderTemplate(template: string, vars: Record<string, string>):
});
}
// ─── Normalization helpers (replicated from ui-config conventions) ──────────
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function boolOr(value: unknown, fallback: boolean): boolean {
return typeof value === 'boolean' ? value : fallback;
}
function clampInt(value: unknown, min: number, max: number, fallback: number): number {
const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
if (!Number.isFinite(n)) return fallback;
return Math.trunc(Math.min(max, Math.max(min, n)));
}
// ─── Normalization helpers ──────────────────────────────────────────────────
// isObject / boolOr / clampInt come from @snowluma/common/coerce. strOr is
// notifications-only (string truncation to maxLen), so it stays here.
function strOr(value: unknown, fallback: string, maxLen: number): string {
return typeof value === 'string' ? value.slice(0, maxLen) : fallback;

View File

@@ -28,6 +28,9 @@ export const BACKUP_FILES: readonly BackupFileSpec[] = [
{ name: 'runtime.json', binary: false, credential: false },
{ name: 'ui.json', binary: false, credential: false },
{ name: 'notifications.json', binary: false, credential: false },
// Global all-accounts SnowLuma settings (rkey fallback servers, …). Same
// class as notifications.json: global, opt-in, non-credential.
{ name: 'snowluma.json', binary: false, credential: false },
{ name: 'cert.pem', binary: false, credential: false },
{ name: 'ui-assets/background', binary: true, credential: false },
{ name: 'webui.json', binary: false, credential: true },

View File

@@ -0,0 +1,104 @@
/**
* Connection-status diff loop. OneBot adapters don't have an internal
* event-emitter for connection state (listening / connected / client-count
* changes), so this loop polls `getConnectionStatuses()` and publishes
* `connections` to the StateBus when the JSON-serialised snapshot changes
* vs the previous tick.
*
* Cheap (500ms default cadence, 1-3 accounts, ~hundreds of bytes), only
* fires the StateBus when state actually moves — so the SSE handler only
* pushes a fresh `connections` frame when the user would actually see
* something update.
*/
import type { StateBus } from './state-bus';
export interface ConnectionDiffLoopOptions {
bus: StateBus;
/** Read the current adapter-status snapshot for every live UIN. */
getSnapshot: () => unknown;
/** Optional projector — return the "comparable" subset of the snapshot.
* The full snapshot is what the SSE handler ships to the WebUI; this
* projection is what the diff loop compares between ticks. Use it to
* strip volatile fields (e.g. HH:MM:SS timestamps embedded in adapter
* `detail` strings) that would otherwise produce a publish every tick
* under any active webhook — defeating the loop's whole purpose.
* Default: identity. */
pickComparable?: (snapshot: unknown) => unknown;
/** Poll cadence in milliseconds; default 500. */
intervalMs?: number;
}
export interface ConnectionDiffLoopHandle {
/** Stop the loop. Subsequent snapshot mutations produce nothing. */
dispose(): void;
}
export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): ConnectionDiffLoopHandle {
const intervalMs = opts.intervalMs ?? 500;
let lastSerialized = '';
let haveBaseline = false;
let disposed = false;
// One-shot diagnostic latch: a projector that starts throwing only after
// a shape regression would otherwise wedge the baseline silently — no
// publishes, no log, no symptom besides "the dashboard's connections
// card stops updating". Surface it ONCE so the failure is visible.
let warnedProjectorThrew = false;
const tick = (): void => {
if (disposed) return;
let snap: unknown;
try {
snap = opts.getSnapshot();
} catch {
// Snapshot read failed (e.g. mid-shutdown). Skip this tick; the
// next one will retry. Don't reset the baseline so we don't
// spuriously republish when the snapshot starts working again.
return;
}
let comparable: unknown;
try {
comparable = opts.pickComparable ? opts.pickComparable(snap) : snap;
} catch (err) {
// A buggy projector must not crash the diff loop or wedge baseline.
// But silent wedge is its own bug class — log the FIRST occurrence
// so an operator can find it without re-running the loop locally.
if (!warnedProjectorThrew) {
warnedProjectorThrew = true;
// Static logger import avoided to keep the loop self-contained;
// stderr is good enough for a once-per-process latch.
// eslint-disable-next-line no-console
console.error('[connection-diff-loop] pickComparable threw — connections SSE diff will wedge until restart:', err);
}
return;
}
const serialized = JSON.stringify(comparable);
if (!haveBaseline) {
// First successful observation. The SSE handler's sendAllInitial
// already shipped a `connections` frame to every connected client
// on connect, so the baseline is what they already have — emitting
// it again would be a duplicate. Just store it.
lastSerialized = serialized;
haveBaseline = true;
return;
}
if (serialized === lastSerialized) return;
lastSerialized = serialized;
opts.bus.publish('connections');
};
const timer = setInterval(tick, intervalMs);
// Don't pin the Node event loop: the loop is permanent for the server
// lifetime by design, but tests / a future hot-reload scenario must be
// able to exit cleanly without an outstanding interval ref. Mirrors the
// tokenJanitor pattern in server.ts.
timer.unref?.();
return {
dispose(): void {
if (disposed) return;
disposed = true;
clearInterval(timer);
},
};
}

View File

@@ -0,0 +1,197 @@
// debug-tools — backend for the debug console's two heavier endpoints
// (Phase 2 of the debug-console expansion):
//
// • POST /api/debug/invoke-stream — drive a Stream API action and relay every
// frame to the browser over an SSE body. Unlike the live-activity stream
// (debug-stream.ts), this MUST NOT drop frames: a file transfer that loses a
// chunk is corrupt. So backpressure is handled by *waiting* for the consumer
// to drain, never by dropping.
// • POST /api/debug/upload — stream a browser-selected file to a temp path on
// the SERVER (the bot runs on the server, not the user's machine), so the
// returned path can be fed to a send action. Streamed straight to disk with a
// byte cap — never buffered whole, so large videos don't blow up memory.
//
// The pure pieces live here (path sanitisation, the size-capped disk sink, the
// stream-invoke Response builder) so they are unit-testable away from Hono.
import { createWriteStream } from 'fs';
import { mkdir, readdir, rm, stat } from 'fs/promises';
import os from 'os';
import path from 'path';
import { randomBytes } from 'crypto';
/** Temp dir for browser→server uploads. Siblings the Stream API's temp root but
* kept distinct so the two cleanup stories don't entangle. */
export const DEBUG_UPLOAD_DIR = path.join(os.tmpdir(), 'snowluma-debug-upload');
/** Hard ceiling on a single upload. Mirrors the Stream API's upload cap. */
export const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
/** Uploads older than this are swept on the next upload (best-effort). */
const UPLOAD_TTL_MS = 24 * 60 * 60 * 1000;
/** Reduce a client-supplied filename to a safe basename (extension preserved),
* with no path separators or traversal. The client path is NEVER trusted for
* placement — this is only used to keep the stored name human-readable. */
export function safeUploadName(raw: string | undefined): string {
// Treat both separators as path delimiters, then take the basename so any
// `../` / absolute prefix is discarded regardless of host platform.
const base = path.basename(String(raw ?? '').replace(/\\/g, '/'));
const cleaned = base
.replace(/[^\w.\-]+/g, '_') // collapse anything exotic to underscore
.replace(/^\.+/, '') // no leading dots (no hidden / '..' names)
.slice(0, 120);
return cleaned || 'file';
}
/** Unguessable destination path under DEBUG_UPLOAD_DIR for a sanitised name.
* Throws if the composed path would escape the dir (defence in depth — it
* can't, given the random id + basename, but we assert anyway). */
export function uploadDestPath(safeName: string): string {
const id = randomBytes(12).toString('hex');
const dest = path.join(DEBUG_UPLOAD_DIR, `${id}__${safeName}`);
const rel = path.relative(DEBUG_UPLOAD_DIR, dest);
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
throw new Error('invalid upload path');
}
return dest;
}
/** Stream raw request-body bytes to a temp file under DEBUG_UPLOAD_DIR, enforcing
* a byte cap. Returns the final server path + byte size. On overflow or any
* error the partial file is removed and the call rejects. Never buffers the
* whole body. */
export async function streamUploadToDisk(
body: ReadableStream<Uint8Array> | null,
filename: string | undefined,
opts: { maxBytes?: number } = {},
): Promise<{ path: string; size: number }> {
if (!body) throw new Error('empty body');
const maxBytes = opts.maxBytes ?? MAX_UPLOAD_BYTES;
await mkdir(DEBUG_UPLOAD_DIR, { recursive: true });
void sweepOldUploads(); // fire-and-forget TTL cleanup
const dest = uploadDestPath(safeUploadName(filename));
const out = createWriteStream(dest, { mode: 0o600 });
// A WriteStream emits 'error' ASYNCHRONOUSLY (ENOSPC / EIO / quota) during a
// background flush — typically while we're parked at reader.read() or waiting
// on 'drain'. An unhandled 'error' event would crash the whole process, and a
// backpressured error would leave 'drain' to never fire (a forever-hung await
// + leaked fd). So turn it into a rejection and race it into every await; the
// catch below then destroys + unlinks the partial.
const errored = new Promise<never>((_, rej) => out.once('error', rej));
errored.catch(() => { /* swallow a late error after success (still raced below) */ });
let size = 0;
try {
const reader = body.getReader();
for (;;) {
const { done, value } = await Promise.race([errored, reader.read()]);
if (done) break;
if (!value || value.byteLength === 0) continue;
size += value.byteLength;
if (size > maxBytes) throw new Error('上传超出大小上限');
// Respect the write stream's backpressure (but never hang on an error).
if (!out.write(value)) {
await Promise.race([errored, new Promise<void>((res) => out.once('drain', res))]);
}
}
await Promise.race([errored, new Promise<void>((res, rej) => out.end((err?: Error | null) => (err ? rej(err) : res())))]);
if (size === 0) throw new Error('empty body');
return { path: dest, size };
} catch (err) {
// Wait for the stream to fully close BEFORE unlinking: createWriteStream
// opens the fd asynchronously, so a fast failure can reach `rm` before the
// file even exists on disk — then the late open would re-create it and leak
// the partial. 'close' guarantees the fd is settled and no more writes land.
out.destroy();
if (!out.closed) await new Promise<void>((res) => out.once('close', () => res()));
await rm(dest, { force: true }).catch(() => { /* best-effort */ });
throw err;
}
}
/** Remove upload temp files older than the TTL. Best-effort; never throws. */
export async function sweepOldUploads(now: number = Date.now()): Promise<number> {
let removed = 0;
try {
const names = await readdir(DEBUG_UPLOAD_DIR);
await Promise.all(
names.map(async (n) => {
const p = path.join(DEBUG_UPLOAD_DIR, n);
try {
const s = await stat(p);
if (now - s.mtimeMs > UPLOAD_TTL_MS) {
await rm(p, { force: true, recursive: true });
removed += 1;
}
} catch { /* racing cleanup / vanished file */ }
}),
);
} catch { /* dir absent yet */ }
return removed;
}
/** Drives a stream-capable action and relays its frames. The driver is the
* instance's `invokeStream` (which itself handles non-stream actions by emitting
* a single frame). */
export type StreamInvokeDriver = (
rawRequest: string,
emit: (json: string) => Promise<void>,
isAlive: () => boolean,
) => Promise<void>;
/** How long emit() will wait for a backed-up consumer to drain before it gives
* up waiting and enqueues anyway (the request abort / action idle-watchdog are
* the real stall guards). */
const DRAIN_WAIT_MS = 20;
const DRAIN_MAX_SPINS = 3000; // 3000 * 20ms ≈ 60s
/** Build the SSE `Response` for `/api/debug/invoke-stream`: each relayed frame
* is one `data: <json>\n\n` event; no frame is ever dropped. A driver error
* becomes a terminal `failed` frame. Closing the request (signal abort) stops
* delivery. `delay` is injectable for tests. */
export function buildStreamInvokeResponse(
driver: StreamInvokeDriver,
rawRequest: string,
signal: AbortSignal,
delay: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
): Response {
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
let closed = false;
const onAbort = () => { closed = true; };
signal.addEventListener('abort', onAbort);
const isAlive = () => !closed && !signal.aborted;
const emit = async (json: string): Promise<void> => {
if (!isAlive()) throw new Error('stream transport closed');
// Backpressure WITHOUT dropping: wait for the consumer to catch up.
let spins = 0;
while (isAlive() && (controller.desiredSize ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) {
await delay(DRAIN_WAIT_MS);
spins += 1;
}
if (!isAlive()) throw new Error('stream transport closed');
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
};
try {
await driver(rawRequest, emit, isAlive);
} catch (err) {
if (isAlive()) {
const msg = err instanceof Error ? err.message : 'stream error';
try {
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`));
} catch { /* controller already torn down */ }
}
} finally {
signal.removeEventListener('abort', onAbort);
try { controller.close(); } catch { /* already closed */ }
}
},
});
return new Response(stream, {
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
});
}

View File

@@ -3,6 +3,7 @@ import { serveStatic } from '@hono/node-server/serve-static';
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config';
import { loadGlobalSettings, saveGlobalSettings } from '@snowluma/onebot/global-config';
import type { OneBotManager } from '@snowluma/onebot/manager';
import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/onebot/types';
import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime';
@@ -21,6 +22,11 @@ import { coerceSettingsPatch } from './system-settings';
import { buildBackup, planRestore, validateBackup } from './backup';
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
import { createFramePusher } from './debug-stream';
import { buildStreamInvokeResponse, streamUploadToDisk } from './debug-tools';
import { sseResponse } from './sse-response';
import { bindStateStream } from './state-stream';
import type { StateBus, StateResource } from './state-bus';
import { startConnectionDiffLoop } from './connection-diff-loop';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
import { findAvailablePort } from './port';
import {
@@ -80,18 +86,27 @@ const CONSENT_ALLOWLIST = new Set([
'/api/logout',
]);
// Endpoints that may authenticate via `?token=` query parameter. Only the
// SSE log stream is here because EventSource cannot set custom headers; all
// other endpoints MUST use the Authorization header so tokens never leak
// into access logs / Referer / browser history.
const TOKEN_QUERY_ALLOWLIST = new Set([
// Endpoints that may authenticate via `?token=` query parameter. Reserved
// for SSE streams: EventSource cannot set custom headers, so these MUST
// accept the token via query. All other endpoints use the Authorization
// header so tokens never leak into access logs / Referer / browser history.
//
// Exported so the regression test can lock the invariant — a missing entry
// here silently 401s the EventSource and the whole push channel goes dark,
// which has happened (see /api/state/stream's first cut).
export const SSE_TOKEN_QUERY_PATHS: ReadonlySet<string> = new Set([
'/api/logs/stream',
'/api/debug/stream',
'/api/state/stream',
]);
const TOKEN_QUERY_ALLOWLIST = SSE_TOKEN_QUERY_PATHS;
// uin = QQ number; 5–12 digits. Used to construct config file paths,
// so we MUST refuse anything else (path traversal, NUL bytes, etc.).
const UIN_REGEX = /^\d{5,12}$/;
// uin = QQ number; 5–10 digits (real QQ UINs fit in uint32, max 4294967295).
// Used to construct config file paths, so we MUST refuse anything else (path
// traversal, NUL bytes, etc.) — and the 10-digit cap also rejects the garbage
// timestamp-shaped UINs the native hook can emit (issue #162). Mirrors
// isRealUin in @snowluma/common/uin.
const UIN_REGEX = /^\d{5,10}$/;
const avatarCache = new Map<string, { body: Uint8Array; contentType: string; expiresAt: number }>();
@@ -313,7 +328,7 @@ export async function initWebUI(
oneBotManager: OneBotManager,
hookManager?: HookManager,
notificationManager?: NotificationManager,
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string } = {},
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string; stateBus?: StateBus } = {},
): Promise<{ port: number }> {
// Resolve the client IP for per-IP rate limiting from the configured
// trust-proxy directive (runtime.json `trustProxy`, env-overridable via
@@ -322,6 +337,54 @@ export async function initWebUI(
const trustProxyMode = parseTrustProxy(listener.trustProxy);
const getClientIp = makeClientIpResolver(trustProxyMode);
// Connection-status diff loop: OneBot adapters don't emit events for
// listening/connected/client-count changes, so we poll the snapshot at
// 500ms and publish 'connections' to the StateBus when it actually
// moves. One loop per server lifetime, lives until process exit (the
// setInterval is .unref'd inside the loop so it doesn't pin the event
// loop on shutdown).
//
// `pickComparable` strips `adapter.detail` — that's a localised human
// string assembled with HH:MM:SS timestamps from the last webhook
// delivery; including it in the diff would make every webhook event
// produce a publish (defeating the diff). We compare ONLY name + kind +
// status, which captures every transition the dashboard actually
// renders differently. The SSE handler still ships the FULL snapshot
// (with `detail`) — it's only the diff key that's pruned.
//
// Trade-off: the rendered detail string (e.g. "3 个客户端", "上次推送
// 14:53:01") only refreshes on the next SSE push or on the 30s REST
// reconcile — not in real time. The user's original reported bugs were
// about process / account edges (which DO push instantly); refreshing
// adapter detail strings at sub-second cadence wasn't required. If it
// becomes one, surface client-count as a structured field on
// AdapterStatus and include it in the comparable.
if (listener.stateBus) {
// Handle deliberately discarded — initWebUI has no shutdown path; the
// loop's setInterval is .unref'd so it doesn't pin the event loop.
startConnectionDiffLoop({
bus: listener.stateBus,
getSnapshot: () => oneBotManager.getConnectionStatuses(),
pickComparable: (snap) => {
if (!Array.isArray(snap)) return snap;
return (snap as Array<{ uin: string; nickname?: string; adapters?: unknown[] }>).map((acc) => ({
uin: acc.uin,
nickname: acc.nickname,
// Empty fallback when `adapters` is not an array — never the
// raw value, which could re-introduce volatile fields verbatim
// if the snapshot shape ever drifts.
adapters: Array.isArray(acc.adapters)
? acc.adapters.map((a: unknown) => {
const o = a as { name?: string; kind?: string; status?: string };
return { name: o.name, kind: o.kind, status: o.status };
})
: [],
}));
},
intervalMs: 500,
});
}
// Actual bound port (set just before serve; findAvailablePort may bump it).
// Read by GET /api/system/settings so the panel shows what's really live.
let boundPort = desiredPort;
@@ -871,48 +934,60 @@ export async function initWebUI(
return c.json(result);
});
// Invoke a Stream API action (or any action) and relay every frame to the
// browser over an SSE body. The frontend reads this with fetch()+a stream
// reader (Bearer auth in the header), so — unlike /api/debug/stream — it does
// NOT need a query-token allowlist entry. Frames are never dropped.
app.post('/api/debug/invoke-stream', async (c) => {
let body: unknown;
try { body = await c.req.json(); } catch { return c.json({ status: 'failed', message: '请求格式错误' }, 400); }
const { uin, action, params } = (body ?? {}) as { uin?: unknown; action?: unknown; params?: unknown };
if (typeof uin !== 'string' || !UIN_REGEX.test(uin)) return c.json({ status: 'failed', message: '无效的账号' }, 400);
if (typeof action !== 'string' || !action) return c.json({ status: 'failed', message: 'action 必填' }, 400);
if (params !== undefined && (typeof params !== 'object' || params === null || Array.isArray(params))) {
return c.json({ status: 'failed', message: 'params 必须是对象' }, 400);
}
const inst = oneBotManager.getInstance(uin);
if (!inst) return c.json({ status: 'failed', message: '账号不在线' }, 404);
const rawRequest = JSON.stringify({ action, params: params ?? {} });
return buildStreamInvokeResponse(
(rq, emit, alive) => inst.invokeStream(rq, emit, alive),
rawRequest,
c.req.raw.signal,
);
});
// Stream a browser-selected file to a temp path on THIS server (the bot runs
// here, not on the operator's machine), so the returned path can be fed to a
// send action's file/image/record/video param. Raw bytes in the body,
// `?filename=` for a human-readable suffix; streamed to disk with a byte cap.
app.post('/api/debug/upload', async (c) => {
try {
const result = await streamUploadToDisk(c.req.raw.body as ReadableStream<Uint8Array> | null, c.req.query('filename'));
return c.json({ status: 'ok', path: result.path, size: result.size });
} catch (err) {
return c.json({ status: 'failed', message: err instanceof Error ? err.message : '上传失败' }, 400);
}
});
// Live merged SSE of OneBot events + action calls across all accounts. Taps
// are attached only while a client is connected (on-demand). A slow client is
// dropped (not back-pressured onto the bot) with a periodic drop marker.
app.get('/api/debug/stream', (c) => {
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
let closed = false;
const offs: Array<() => void> = [];
let heartbeat: NodeJS.Timeout | undefined;
const teardown = () => {
if (closed) return;
closed = true;
if (heartbeat) clearInterval(heartbeat);
for (const off of offs) { try { off(); } catch { /* ignore */ } }
try { controller.close(); } catch { /* ignore */ }
};
const raw = (chunk: Uint8Array) => {
if (closed) return;
try { controller.enqueue(chunk); } catch { teardown(); }
};
// Drop-under-backpressure framing (unit-tested in debug-stream.ts).
const pushFrame = createFramePusher({
desiredSize: () => controller.desiredSize,
enqueue: raw,
encode: (s) => encoder.encode(s),
});
const send = (payload: unknown) => { if (!closed) pushFrame(payload); };
send({ kind: 'ready' });
for (const inst of oneBotManager.getInstances()) {
const uin = inst.uin;
offs.push(inst.subscribeDebugEvents((event) => send({ kind: 'event', uin, event })));
offs.push(inst.observeActions((rec) => send({ kind: 'action', uin, ...rec })));
}
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
c.req.raw.signal.addEventListener('abort', teardown);
},
app.get('/api/debug/stream', (c) => sseResponse(c, (ch) => {
// Drop-under-backpressure framing (unit-tested in debug-stream.ts).
const pushFrame = createFramePusher({
desiredSize: ch.desiredSize,
enqueue: ch.raw,
encode: ch.encode,
});
return new Response(stream, {
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
});
});
const send = (payload: unknown) => { if (!ch.isClosed()) pushFrame(payload); };
send({ kind: 'ready' });
for (const inst of oneBotManager.getInstances()) {
const uin = inst.uin;
ch.onClose(inst.subscribeDebugEvents((event) => send({ kind: 'event', uin, event })));
ch.onClose(inst.observeActions((rec) => send({ kind: 'action', uin, ...rec })));
}
}));
app.get('/api/qq-list', (c) => {
const instances = oneBotManager.getInstances();
@@ -926,6 +1001,55 @@ export async function initWebUI(
return c.json({ list: oneBotManager.getConnectionStatuses() });
});
// Combined SSE feed for the dashboard's three live resources — processes,
// qq-list, connections. Replaces the 3s REST polling tick in
// app-layout.tsx; the REST endpoints above stay for the initial fetch
// before SSE connects and for the slow (30s) reconciliation fallback.
//
// On connect: one frame per resource with the current snapshot. After
// that: a fresh snapshot per resource only when the StateBus signals a
// change (HookSession status-changed, BridgeManager session edges, the
// connection-status diff loop). 50ms per-resource debounce coalesces a
// burst (e.g. multiple HookSessions flipping status simultaneously).
const stateBus = listener.stateBus;
app.get('/api/state/stream', (c) => {
if (!stateBus) {
// Build without state-wiring (e.g. a future headless mode) — clients
// fall back to the REST endpoints. Treat as endpoint-not-here.
return c.text('state stream not configured', 503);
}
const liveBus = stateBus;
return sseResponse(c, (ch) => {
const pushFrame = createFramePusher({
desiredSize: ch.desiredSize,
enqueue: ch.raw,
encode: ch.encode,
});
const send = (payload: unknown) => { if (!ch.isClosed()) pushFrame(payload); };
send({ kind: 'ready' });
const handle = bindStateStream({
bus: liveBus,
snapshot: async (resource: StateResource): Promise<unknown> => {
if (resource === 'processes') {
if (!hookManager) return [];
return hookManager.listProcesses();
}
if (resource === 'qq-list') {
return oneBotManager.getInstances().map((inst) => ({ uin: inst.uin, nickname: inst.nickname }));
}
return oneBotManager.getConnectionStatuses();
},
send: (frame) => send(frame),
debounceMs: 50,
});
ch.onClose(() => handle.dispose());
// Prime with the initial snapshot; if the client never sees the
// bus publish (idle system) it still has the current state.
void handle.sendAllInitial();
});
});
app.get('/api/logs', (c) => {
const limit = Number(c.req.query('limit') ?? 300);
return c.json({ list: getRecentLogs(limit) });
@@ -945,49 +1069,10 @@ export async function initWebUI(
return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] });
});
app.get('/api/logs/stream', (c) => {
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
let closed = false;
let unsubscribe: (() => void) | undefined;
let heartbeat: NodeJS.Timeout | undefined;
const teardown = () => {
if (closed) return;
closed = true;
if (heartbeat) clearInterval(heartbeat);
unsubscribe?.();
try { controller.close(); } catch { /* ignore */ }
};
const safeEnqueue = (chunk: Uint8Array) => {
if (closed) return;
try {
controller.enqueue(chunk);
} catch {
// The peer dropped between abort and the next enqueue —
// treat as end-of-stream so we don't leak listeners.
teardown();
}
};
const send = (event: unknown) => {
safeEnqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
};
send({ type: 'ready' });
unsubscribe = subscribeLogs((entry) => send(entry));
heartbeat = setInterval(() => {
safeEnqueue(encoder.encode(': heartbeat\n\n'));
}, 15000);
c.req.raw.signal.addEventListener('abort', teardown);
},
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
});
});
app.get('/api/logs/stream', (c) => sseResponse(c, (ch) => {
ch.send({ type: 'ready' });
ch.onClose(subscribeLogs((entry) => ch.send(entry)));
}));
app.get('/api/processes', async (c) => {
if (!hookManager) return c.json({ list: [] });
@@ -1119,6 +1204,32 @@ export async function initWebUI(
});
});
// ─── Global deployment config (config/snowluma.json) ─────────────────────
// All-accounts SnowLuma knobs (rkey fallback servers + musicSignUrl). Saving
// section-merges + normalizes server-side, then hot-reloads every instance.
app.get('/api/global-config', (c) => c.json({ config: loadGlobalSettings() }));
app.post('/api/global-config', async (c) => {
const declaredLen = Number(c.req.header('content-length'));
if (Number.isFinite(declaredLen) && declaredLen > 512 * 1024) {
return c.json({ success: false, message: '配置过大' }, 413);
}
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
try {
const config = saveGlobalSettings(body);
oneBotManager.reloadGlobalSettings();
return c.json({ success: true, config });
} catch (err) {
log.warn('save global config failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
}
});
// ─── WebUI customization config (config/ui.json) ─────────────────────────
// Appearance (A) + layout (C). The full config is bearer-gated; only the
// cosmetic appearance subset is exposed unauthenticated for the login page.

View File

@@ -0,0 +1,69 @@
import { type Context } from 'hono';
/**
* The per-connection channel handed to an SSE endpoint's `start` callback.
* Everything the endpoint needs to talk to the client, without owning the
* transport lifecycle (heartbeat / teardown / abort / headers).
*/
export interface SseChannel {
/** Enqueue a raw chunk. Tears the stream down if the peer is already gone. */
raw(chunk: Uint8Array): void;
/** Encode a string to bytes (shared TextEncoder). */
encode(s: string): Uint8Array;
/** Convenience: enqueue one `data: <json>\n\n` frame. */
send(payload: unknown): void;
/** Register a cleanup to run once on teardown (unsubscribe / dispose). */
onClose(fn: () => void): void;
/** True after teardown — guard sends from late subscription callbacks. */
isClosed(): boolean;
/** Underlying controller backpressure signal, for `createFramePusher`. */
desiredSize(): number | null;
}
/**
* The SSE HTTP transport shell shared by the WebUI's live endpoints. Owns the
* TextEncoder, a `closed` guard, a 15s `: heartbeat` keep-alive, teardown
* (clear heartbeat → run registered cleanups → close the controller), safe
* enqueue (a throw means the peer dropped → teardown), the abort listener, and
* the `text/event-stream` headers. `start` wires up the endpoint-specific
* subscription + initial sends via the channel.
*
* Each of `/api/debug/stream`, `/api/state/stream`, `/api/logs/stream`
* previously hand-copied this ~40-line skeleton; a heartbeat-interval /
* teardown-order / header change had to be kept in sync across all three.
*/
export function sseResponse(c: Context, start: (ch: SseChannel) => void): Response {
const stream = new ReadableStream<Uint8Array>({
start(controller) {
const encoder = new TextEncoder();
let closed = false;
let heartbeat: ReturnType<typeof setInterval> | undefined;
const cleanups: Array<() => void> = [];
const teardown = () => {
if (closed) return;
closed = true;
if (heartbeat) clearInterval(heartbeat);
for (const fn of cleanups) { try { fn(); } catch { /* ignore */ } }
try { controller.close(); } catch { /* ignore */ }
};
const raw = (chunk: Uint8Array) => {
if (closed) return;
try { controller.enqueue(chunk); } catch { teardown(); }
};
const ch: SseChannel = {
raw,
encode: (s) => encoder.encode(s),
send: (payload) => raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`)),
onClose: (fn) => { cleanups.push(fn); },
isClosed: () => closed,
desiredSize: () => controller.desiredSize,
};
start(ch);
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
c.req.raw.signal.addEventListener('abort', teardown);
},
});
return new Response(stream, {
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
});
}

View File

@@ -0,0 +1,67 @@
/**
* StateBus — pure pub/sub for WebUI state-resource invalidations.
*
* Three resources are tracked: `processes`, `qq-list`, `connections`. A
* publisher (HookSession status change, BridgeManager session start/close,
* the connection-status diff loop) calls `publish(resource)` to signal "the
* snapshot for THIS resource is stale; whoever cares should re-read". The
* `/api/state/stream` SSE handler subscribes, debounces, and pushes fresh
* snapshots to connected WebUI clients.
*
* Intentionally pure pub/sub (no debounce, no snapshot caching): debounce
* and snapshot reads live with the subscriber so different consumers can
* coalesce on different cadences. Snapshot semantics on fan-out: the
* subscriber set is FROZEN at the start of each publish, so a listener
* that subscribes during the fan-out only sees the FOLLOWING publish, and
* a listener that unsubscribes mid-fan-out does not prevent its peers
* from completing.
*/
export type StateResource = 'processes' | 'qq-list' | 'connections';
export type StateListener = (resource: StateResource) => void;
export class StateBus {
private readonly listeners = new Set<StateListener>();
private disposed = false;
/** Subscribe to every publish; returns an unsubscribe handle. Calling
* the handle more than once is a no-op. */
subscribe(listener: StateListener): () => void {
if (this.disposed) return () => undefined;
this.listeners.add(listener);
let active = true;
return () => {
if (!active) return;
active = false;
this.listeners.delete(listener);
};
}
/** Notify every CURRENTLY-subscribed listener that `resource` is stale.
* Iterates a frozen snapshot of the subscriber set so add/remove during
* the emit don't change which listeners see THIS publish; subscriber
* exceptions are isolated and do not abort the fan-out. */
publish(resource: StateResource): void {
if (this.disposed) return;
// Snapshot the current subscribers — any subscribe()/unsubscribe()
// called by a listener during the fan-out takes effect only for the
// NEXT publish, not this one.
const snapshot = [...this.listeners];
for (const fn of snapshot) {
try {
fn(resource);
} catch {
// Subscriber-internal failure is its own problem. The bus's job
// is to keep delivery moving — surfacing an error here would
// partially abort the fan-out and create skip-the-listener bugs.
}
}
}
/** Drop every subscriber and refuse future subscribes / publishes. */
dispose(): void {
this.disposed = true;
this.listeners.clear();
}
}

View File

@@ -0,0 +1,128 @@
/**
* Bind a StateBus to an SSE-friendly `send` callback: every publish becomes
* a debounced fresh-snapshot frame, and `sendAllInitial()` primes a new
* connection with one frame per resource.
*
* Decoupled from the HTTP layer so the route handler in server.ts can drop
* its responsibility down to "open a ReadableStream, hand its enqueue to
* bindStateStream, abort tears it down". Pure logic = unit-testable with
* fake timers; no Response/controller mocking needed.
*
* Per-resource debounce, not global: an 'qq-list' churn during a slow
* 'processes' burst must not delay the qq-list frame, and a 'connections'
* diff loop running at 500ms must not coalesce 10 unrelated processes
* events into one. Each resource is its own timer.
*/
import type { StateBus, StateResource } from './state-bus';
export interface StateStreamFrame {
resource: StateResource;
data: unknown;
}
export interface BindStateStreamOptions {
bus: StateBus;
/** Read the current snapshot for one resource. May be sync or async. */
snapshot: (resource: StateResource) => unknown | Promise<unknown>;
/** Receive a fresh frame; called once per debounced publish.
* Exceptions are caught — a dead controller must not abort the bus
* subscription or break sibling resources. */
send: (frame: StateStreamFrame) => void;
/** Coalesce window in milliseconds; default 50. */
debounceMs?: number;
}
export interface StateStreamHandle {
/** Emit one frame per resource using the current snapshot. Use on connect. */
sendAllInitial(): Promise<void>;
/** Stop subscribing + cancel pending timers. Subsequent bus publishes
* produce nothing through this binding. */
dispose(): void;
}
const ALL_RESOURCES: readonly StateResource[] = ['processes', 'qq-list', 'connections'];
export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle {
const debounceMs = opts.debounceMs ?? 50;
const timers = new Map<StateResource, ReturnType<typeof setTimeout>>();
// Single-flight per resource: at most one in-flight flush per resource so
// an uneven snapshot latency cannot interleave sends out of order (a slow
// earlier snapshot landing AFTER a later one, leaving the client's last
// observed frame stale). Publishes arriving while a flush is in flight
// mark `pending` and rearm the debounce timer once the flush completes.
const inFlight = new Set<StateResource>();
const pending = new Set<StateResource>();
let disposed = false;
const flush = async (resource: StateResource): Promise<void> => {
if (disposed) return;
inFlight.add(resource);
try {
let data: unknown;
try {
data = await opts.snapshot(resource);
} catch {
// Per-resource snapshot failure (e.g. listProcesses threw): skip
// this frame so siblings keep flowing. The next publish for the
// same resource gets a fresh attempt.
return;
}
if (disposed) return;
try {
opts.send({ resource, data });
} catch {
// Downstream consumer (e.g. closed SSE controller) — same isolation
// contract as snapshot failures.
}
} finally {
inFlight.delete(resource);
// If a publish arrived during the in-flight window, schedule one
// follow-up flush. Re-uses the debounce so a sustained publish
// stream produces at most one frame per (debounceMs + flushLatency),
// not back-to-back frames.
if (!disposed && pending.has(resource)) {
pending.delete(resource);
schedule(resource);
}
}
};
const schedule = (resource: StateResource): void => {
if (disposed) return;
if (inFlight.has(resource)) {
// Defer to the post-flush re-arm; no new timer until the in-flight
// send completes. This is the load-bearing invariant for ordering.
pending.add(resource);
return;
}
const existing = timers.get(resource);
if (existing) clearTimeout(existing);
const t = setTimeout(() => {
timers.delete(resource);
void flush(resource);
}, debounceMs);
timers.set(resource, t);
};
const unsubscribe = opts.bus.subscribe(schedule);
return {
async sendAllInitial(): Promise<void> {
if (disposed) return;
// Fire all three in parallel. Each resource's snapshot is independent
// so a slow listProcesses() doesn't gate qq-list/connections. Each
// call goes through the single-flight gate so a concurrent bus
// publish during this initial fan-out coalesces correctly.
await Promise.all(ALL_RESOURCES.map((r) => flush(r)));
},
dispose(): void {
if (disposed) return;
disposed = true;
unsubscribe();
for (const t of timers.values()) clearTimeout(t);
timers.clear();
pending.clear();
},
};
}

View File

@@ -0,0 +1,73 @@
/**
* State-wiring — couples the publisher edges (HookManager session events,
* BridgeManager session-started / session-closed) to a fresh StateBus so the
* `/api/state/stream` SSE handler can push snapshot invalidations to the
* WebUI without REST polling.
*
* Decoupling rationale:
* - HookManager owns the per-process state-machine; it knows when a
* session's `listProcesses()` view changes. We feed it `onSessionsChanged`
* (callable from outside the bridge package) so this file is the ONLY
* place that imports both the bus and HookManager's dep shape.
* - BridgeManager fires `session-started` / `session-closed` listeners on
* account edges (the OneBot instance list mutates around these). We add
* listeners directly so `qq-list` + `connections` invalidate at the right
* moment without modifying BridgeManager.
*
* `dispose()` unwires everything so a test (or a future hot-reload) can
* recreate the wiring without leaking listeners.
*/
import { StateBus } from './state-bus';
import type { BridgeManager } from '../bridge/manager';
export interface StateWiring {
/** The bus the SSE handler subscribes to. */
readonly bus: StateBus;
/** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */
onSessionsChanged: () => void;
/** Hook into a BridgeManager so its session edges publish 'qq-list' and
* 'connections'. Can be called at most once per wiring (subsequent calls
* add duplicate listeners). */
bindBridgeManager(bm: BridgeManager): void;
/** Drop every listener + neuter the bus so further publishes do nothing. */
dispose(): void;
}
export function createStateWiring(): StateWiring {
const bus = new StateBus();
let disposed = false;
const publish = (resource: Parameters<StateBus['publish']>[0]): void => {
if (disposed) return;
bus.publish(resource);
};
return {
bus,
onSessionsChanged: () => publish('processes'),
bindBridgeManager(bm: BridgeManager): void {
// Account appeared: the qq-list response gains an entry and the
// connections response gains the new account's adapter row. Two
// distinct resource invalidations, in source-of-truth order
// (account exists → only then can adapters be enumerated for it).
bm.addSessionStartedListener(() => {
publish('qq-list');
publish('connections');
});
// Account disappeared: same two resources shrink, same order so a
// racy WebUI receiving both events independently sees the qq-list
// shrink before it tries to render connections for a uin that's
// about to vanish.
bm.addSessionClosedListener(() => {
publish('qq-list');
publish('connections');
});
},
dispose(): void {
if (disposed) return;
disposed = true;
bus.dispose();
},
};
}

View File

@@ -1,3 +1,4 @@
import { boolOr, clampInt, clampNum, isObject } from '@snowluma/common/coerce';
import { createLogger } from '@snowluma/common/logger';
import fs from 'fs';
import path from 'path';
@@ -308,10 +309,8 @@ function defaultPages(): UiPages {
}
// ─── Normalization helpers ─────────────────────────────────────────────────
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
// isObject / boolOr / clampNum / clampInt come from @snowluma/common/coerce.
// oneOf (enum), isFiniteNum, and hexOr (CSS color) are ui-specific and stay.
function oneOf<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
return typeof value === 'string' && (allowed as readonly string[]).includes(value)
@@ -319,25 +318,11 @@ function oneOf<T extends string>(value: unknown, allowed: readonly T[], fallback
: fallback;
}
function clampNum(value: unknown, min: number, max: number, fallback: number): number {
const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
if (!Number.isFinite(n)) return fallback;
return Math.min(max, Math.max(min, n));
}
function clampInt(value: unknown, min: number, max: number, fallback: number): number {
return Math.trunc(clampNum(value, min, max, fallback));
}
function isFiniteNum(value: unknown): boolean {
if (typeof value === 'number') return Number.isFinite(value);
return typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value));
}
function boolOr(value: unknown, fallback: boolean): boolean {
return typeof value === 'boolean' ? value : fallback;
}
const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
function hexOr(value: unknown, fallback: string): string {
return typeof value === 'string' && HEX_RE.test(value.trim()) ? value.trim() : fallback;

View File

@@ -11,6 +11,7 @@
// "无法检查更新" rather than nagging).
import { createLogger } from '@snowluma/common/logger';
import { createSingleFlightCache } from '@snowluma/common/single-flight-cache';
const log = createLogger('Update');
@@ -79,8 +80,22 @@ export function compareVersions(a: string, b: string): number {
return pa.pre < pb.pre ? -1 : 1;
}
let cache: UpdateCheckResult | null = null;
let inflight: Promise<UpdateCheckResult> | null = null;
// TTL + single-flight: cache good results for CACHE_TTL_MS (well under GitHub's
// 60 req/hr limit) and collapse concurrent checks onto one fetch. Error results
// are intentionally not cached (shouldCache) so the next check retries.
const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
ttlMs: CACHE_TTL_MS,
shouldCache: (r) => !r.error,
load: async (current) => {
const result = await fetchLatest(current);
if (result.error) {
log.debug('update check failed: %s', result.error);
} else if (result.hasUpdate) {
log.info('a newer release is available: v%s (running v%s)', result.latest, current);
}
return result;
},
});
async function fetchLatest(current: string): Promise<UpdateCheckResult> {
const base: UpdateCheckResult = {
@@ -133,21 +148,7 @@ export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
if (!isEnabled()) {
return { ...emptyResult(current), error: 'disabled' };
}
if (!force && cache && Date.now() - cache.checkedAt < CACHE_TTL_MS) return cache;
if (inflight) return inflight;
inflight = (async () => {
const result = await fetchLatest(current);
if (result.error) {
log.debug('update check failed: %s', result.error);
} else {
cache = result; // only cache good results so transient errors retry
if (result.hasUpdate) log.info('a newer release is available: v%s (running v%s)', result.latest, current);
}
return result;
})().finally(() => {
inflight = null;
});
return inflight;
return updateCache.get(current, { force });
}
function emptyResult(current: string): UpdateCheckResult {

View File

@@ -65,6 +65,7 @@ export interface MockGroupFileApi {
upload: ReturnType<typeof vi.fn>;
uploadPrivate: ReturnType<typeof vi.fn>;
publish: ReturnType<typeof vi.fn>;
trans: ReturnType<typeof vi.fn>;
getCount: ReturnType<typeof vi.fn>;
list: ReturnType<typeof vi.fn>;
getUrl: ReturnType<typeof vi.fn>;
@@ -85,6 +86,7 @@ export function mockGroupFileApi(): MockGroupFileApi {
upload: vi.fn(async () => ({ fileId: 'stub-fid' })),
uploadPrivate: vi.fn(async () => ({ fileId: 'stub-pfid', fileHash: 'stub-hash' })),
publish: vi.fn(async () => undefined),
trans: vi.fn(async () => ({ saveBusId: 102, saveFilePath: '/stub-path' })),
getCount: vi.fn(async () => ({ fileCount: 0, maxCount: 10000 })),
list: vi.fn(async () => ({ files: [], folders: [] })),
getUrl: vi.fn(async () => 'stub://url'),
@@ -124,7 +126,9 @@ export interface MockBridge {
findUidByUin: ReturnType<typeof vi.fn>;
findUinByUid: ReturnType<typeof vi.fn>;
findGroupMember: ReturnType<typeof vi.fn>;
forgetGroup: ReturnType<typeof vi.fn>;
};
events: { emit: ReturnType<typeof vi.fn> };
apis: MockApiHub;
sendRawPacket: ReturnType<typeof vi.fn>;
fetchFriendList: ReturnType<typeof vi.fn>;
@@ -154,8 +158,10 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0),
findGroupMember: vi.fn(() => null),
forgetGroup: vi.fn(),
...(overrides.identity ?? {}),
} as MockBridge['identity'],
events: overrides.events ?? { emit: vi.fn(async () => undefined) },
apis: overrides.apis ?? mockApiHub(),
sendRawPacket: vi.fn(async () => defaultResp),
fetchFriendList: vi.fn(async () => []),

View File

@@ -24,6 +24,7 @@
// split.
import { describe, it, expect, vi } from 'vitest';
import { gunzipSync } from 'zlib';
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
@@ -44,8 +45,9 @@ vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: buildSendElemsMock,
}));
import { protobuf_encode } from '@snowluma/proton';
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { LongMsgResult, SendLongMsgReq, SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import type { FileExtra } from '@snowluma/proto-defs/message';
import { ForwardApi } from '../../src/bridge/apis/forward';
import { mockBridge } from './_helpers';
@@ -60,6 +62,13 @@ function uploadResponseWithResId(resId: string) {
};
}
function decodeLongMsgRequest(rawBytes: Uint8Array): LongMsgResult {
const env = protobuf_decode<SendLongMsgReq>(rawBytes);
const payload = env.info?.payload;
if (!(payload instanceof Uint8Array)) throw new Error('payload missing on SendLongMsgReq');
return protobuf_decode<LongMsgResult>(gunzipSync(Buffer.from(payload)));
}
describe('actions/forward — file segment inside forward node', () => {
it('group forward sets forwardFake:true on the SendContext so transElem(24) is emitted', async () => {
// Group case: the file element rides on elems[] as transElem(24).
@@ -120,18 +129,19 @@ describe('actions/forward — file segment inside forward node', () => {
expect(ctx).toMatchObject({ forwardFake: true });
expect(ctx?.groupId).toBeUndefined();
// Spot-check that the upload body carries the file metadata. The
// payload is gzipped + protobuf-wrapped, so we just verify the
// raw filename string survived — that's enough to confirm the
// FileExtra branch ran (a "missing file" regression would drop
// these bytes entirely).
expect(captured).toBeDefined();
const flat = Buffer.from(captured!).toString('binary');
// The filename gets gzipped, so we can't substring-search; instead
// assert the body is large enough that the FileExtra wasn't elided.
// (A name-only forward with no msgContent runs ~80-100 bytes; with
// the FileExtra blob it's noticeably larger.)
expect(flat.length).toBeGreaterThan(80);
const longMsg = decodeLongMsgRequest(captured!);
const body = longMsg.action?.[0]?.actionData?.msgBody?.[0]?.body;
expect(body?.msgContent).toBeInstanceOf(Uint8Array);
expect(body?.richText?.notOnlineFile ?? undefined).toBeUndefined();
const fileExtra = protobuf_decode<FileExtra>(body!.msgContent as Uint8Array);
expect(fileExtra.file).toMatchObject({
fileUuid: 'pfid-1',
fileName: 'invoice.pdf',
fileHash: 'srv-hash-abc',
});
expect(fileExtra.file?.fileSize).toBe(4096n);
});
it('c2c forward falls back to the upload metadata cache when inline fields are missing', async () => {
@@ -165,4 +175,190 @@ describe('actions/forward — file segment inside forward node', () => {
expect(recallUploadedFile).toHaveBeenCalledWith('pfid-cached');
});
it('group forward pre-uploads file sources into the target group without publishing a separate file message', async () => {
buildSendElemsMock.mockClear();
const upload = vi.fn(async () => ({ fileId: 'gfid-from-base64' }));
const publish = vi.fn();
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-grp-source')) as any,
apis: {
...mockBridge().apis,
groupFile: {
...mockBridge().apis.groupFile,
upload,
publish,
},
},
recallUploadedFile: vi.fn((id: string) => id === 'gfid-from-base64' ? {
fileId: 'gfid-from-base64',
scope: 'group' as const,
groupId: 12345,
fileName: 'note.txt',
fileSize: 3,
fileMd5: new Uint8Array(16),
fileSha1: new Uint8Array(20),
rememberedAt: 0,
} : undefined),
});
await new ForwardApi(bridge as any).upload([{
userUin: 10001,
nickname: 'alice',
elements: [{ type: 'file', url: 'base64://AQID', fileName: 'note.txt' } as any],
}], 12345);
expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false);
expect(publish).not.toHaveBeenCalled();
const [elements] = buildSendElemsMock.mock.calls[0]!;
expect(elements).toEqual([expect.objectContaining({
type: 'file',
fileId: 'gfid-from-base64',
fileName: 'note.txt',
fileSize: 3,
})]);
});
it('private forward pre-uploads file sources without sending a standalone c2c file message', async () => {
buildSendElemsMock.mockClear();
const uploadPrivate = vi.fn(async () => ({ fileId: 'pfid-from-base64', fileHash: 'phash' }));
const sendC2cFile = vi.fn();
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-c2c-source')) as any,
apis: {
...mockBridge().apis,
message: {
...mockBridge().apis.message,
sendC2cFile,
},
groupFile: {
...mockBridge().apis.groupFile,
uploadPrivate,
},
},
recallUploadedFile: vi.fn((id: string) => id === 'pfid-from-base64' ? {
fileId: 'pfid-from-base64',
scope: 'private' as const,
userId: 67890,
fileName: 'note.txt',
fileSize: 3,
fileMd5: new Uint8Array(16),
fileSha1: new Uint8Array(20),
fileHash: 'phash',
rememberedAt: 0,
} : undefined),
});
await new ForwardApi(bridge as any).upload([{
userUin: 10001,
nickname: 'alice',
elements: [{ type: 'file', url: 'base64://AQID', fileName: 'note.txt' } as any],
}], undefined, 67890);
expect(uploadPrivate).toHaveBeenCalledWith(67890, 'base64://AQID', 'note.txt', true, false);
expect(sendC2cFile).not.toHaveBeenCalled();
const [elements] = buildSendElemsMock.mock.calls[0]!;
expect(elements).toEqual([expect.objectContaining({
type: 'file',
fileId: 'pfid-from-base64',
fileName: 'note.txt',
fileSize: 3,
fileHash: 'phash',
})]);
});
it('private file forward keeps the long-msg upload under the self uid namespace', async () => {
buildSendElemsMock.mockClear();
let captured: Uint8Array | undefined;
const bridge = mockBridge({
sendRawPacket: vi.fn(async (_cmd: string, body: Uint8Array) => {
captured = body;
return uploadResponseWithResId('res-c2c-target-uid');
}) as any,
resolveUserUid: vi.fn(async () => 'target-uid'),
recallUploadedFile: vi.fn((id: string) => id === 'pfid-1' ? {
fileId: 'pfid-1',
scope: 'private' as const,
userId: 67890,
fileName: 'invoice.pdf',
fileSize: 4096,
fileMd5: new Uint8Array(16),
fileSha1: new Uint8Array(20),
fileHash: 'srv-hash',
rememberedAt: 0,
} : undefined),
});
await new ForwardApi(bridge as any).upload([{
userUin: 10001,
nickname: 'alice',
elements: [{ type: 'file', fileId: 'pfid-1' } as any],
}], undefined, 67890);
expect(bridge.resolveUserUid).not.toHaveBeenCalled();
expect(captured).toBeDefined();
const request = protobuf_decode<SendLongMsgReq>(captured!);
expect(request.info?.uid?.uid).toBe('self-uid');
});
it('group forward re-uploads a cached private file_id into the target group scope', async () => {
buildSendElemsMock.mockClear();
const getPrivateUrl = vi.fn(async () => 'https://download.test/private-file');
const upload = vi.fn(async () => ({ fileId: 'gfid-reuploaded' }));
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-cross-scope')) as any,
apis: {
...mockBridge().apis,
groupFile: {
...mockBridge().apis.groupFile,
getPrivateUrl,
upload,
},
},
recallUploadedFile: vi.fn((id: string) => {
if (id === 'pfid-cached') {
return {
fileId: 'pfid-cached',
scope: 'private' as const,
userId: 67890,
fileName: 'cached.txt',
fileSize: 5,
fileMd5: new Uint8Array(16),
fileSha1: new Uint8Array(20),
fileHash: 'cached-hash',
rememberedAt: 0,
};
}
if (id === 'gfid-reuploaded') {
return {
fileId: 'gfid-reuploaded',
scope: 'group' as const,
groupId: 12345,
fileName: 'cached.txt',
fileSize: 5,
fileMd5: new Uint8Array(16),
fileSha1: new Uint8Array(20),
rememberedAt: 1,
};
}
return undefined;
}),
});
await new ForwardApi(bridge as any).upload([{
userUin: 10001,
nickname: 'alice',
elements: [{ type: 'file', fileId: 'pfid-cached' } as any],
}], 12345);
expect(getPrivateUrl).toHaveBeenCalledWith(67890, 'pfid-cached', 'cached-hash');
expect(upload).toHaveBeenCalledWith(12345, 'https://download.test/private-file', 'cached.txt', '/', true, false);
const [elements] = buildSendElemsMock.mock.calls[0]!;
expect(elements).toEqual([expect.objectContaining({
type: 'file',
fileId: 'gfid-reuploaded',
fileName: 'cached.txt',
fileSize: 5,
})]);
});
});

View File

@@ -14,8 +14,10 @@ vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: vi.fn(async () => []),
}));
import { gzipSync } from 'zlib';
import { protobuf_encode } from '@snowluma/proton';
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import type { SendLongMsgResp, LongMsgResult, RecvLongMsgResp } from '@snowluma/proto-defs/longmsg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import { ForwardApi } from '../../src/bridge/apis/forward';
import { mockBridge } from './_helpers';
@@ -30,6 +32,16 @@ function uploadResponseWithResId(resId: string) {
};
}
/** Build an SsoRecvLongMsg response wrapping the given forward nodes. */
function recvLongMsgResp(bodies: PushMsgBody[]) {
const longMsg: LongMsgResult = {
action: [{ actionCommand: 'MultiMsg', actionData: { msgBody: bodies } }],
};
const gz = gzipSync(Buffer.from(protobuf_encode<LongMsgResult>(longMsg)));
const resp = protobuf_encode<RecvLongMsgResp>({ result: { payload: new Uint8Array(gz) } });
return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.from(resp) };
}
describe('actions/forward', () => {
it('uploadForwardNodes rejects empty arrays', async () => {
const bridge = mockBridge();
@@ -94,6 +106,26 @@ describe('actions/forward', () => {
expect(sendRawPacket).toHaveBeenCalledTimes(1);
});
it('[#201] fills a group forward node nickname from grp.groupName when memberName is empty', async () => {
// Real merged-forward nodes leave grp.memberName (field 2) null and carry the
// sender display name in grp.memberCard (field 4). Verified on-target: fromUin
// 1787882683 ↔ grp.memberCard "墨梓柒". Before the fix the node nickname came
// back "" and enrichSenders 0x899-AUTHORITY_FAIL'd on the placeholder group.
const node: PushMsgBody = {
responseHead: { fromUin: 1787882683, fromUid: 'u_x', grp: { groupUin: 284840486, memberCard: '墨梓柒' } },
contentHead: { msgType: 82, sequence: 1, timestamp: 100 }, // 82 = PkgType.GroupMessage
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
};
const bridge = mockBridge({ sendRawPacket: vi.fn(async () => recvLongMsgResp([node])) as any });
const nodes = await new ForwardApi(bridge as any).fetch('res-201');
expect(nodes).toHaveLength(1);
expect(nodes[0]!.userUin).toBe(1787882683);
expect(nodes[0]!.nickname).toBe('墨梓柒'); // was '' before the fix
expect(nodes[0]!.groupId).toBe(284840486);
// The nickname is present, so no group-member-list enrichment fetch fires.
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1);
});
it('fetchForwardNodes throws on transport failure when nothing is cached', async () => {
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => ({
@@ -151,3 +183,71 @@ describe('actions/forward', () => {
expect(sendRawPacket).toHaveBeenCalledOnce();
});
});
describe('actions/forward — sender name enrichment (#174)', () => {
function apiWith(contacts: { fetchGroupMemberList: any; fetchUserProfile: any }) {
return new ForwardApi({ apis: { contacts } } as any);
}
it('fills empty / "QQ用户" names via the group member list (L3), card preferred', async () => {
const fetchGroupMemberList = vi.fn(async () => [
{ uin: 10001, nickname: 'AliceNick', card: 'AliceCard' },
{ uin: 10002, nickname: 'BobNick', card: '' },
]);
const fetchUserProfile = vi.fn(async (uin: number) => ({ uin, nickname: 'Stranger' }));
const api = apiWith({ fetchGroupMemberList, fetchUserProfile });
const nodes: any[] = [
{ userUin: 10001, nickname: '', groupId: 700, messageType: 'group', elements: [] },
{ userUin: 10002, nickname: 'QQ用户', groupId: 700, messageType: 'group', elements: [] },
{ userUin: 10003, nickname: '', groupId: 700, messageType: 'group', elements: [] }, // not in list
{ userUin: 10009, nickname: '', messageType: 'private', elements: [] }, // private
{ userUin: 10005, nickname: 'KeepMe', groupId: 700, messageType: 'group', elements: [] },
];
const changed = await (api as any).enrichSenders(nodes);
expect(changed).toBe(true);
expect(nodes[0].nickname).toBe('AliceCard'); // card preferred over nick
expect(nodes[0].senderCard).toBe('AliceCard');
expect(nodes[1].nickname).toBe('BobNick'); // card empty → nickname
expect(nodes[2].nickname).toBe('Stranger'); // not in member list → L4 profile
expect(nodes[3].nickname).toBe('Stranger'); // private node → L4 profile
expect(nodes[4].nickname).toBe('KeepMe'); // already named → untouched
expect(fetchGroupMemberList).toHaveBeenCalledTimes(1); // one fetch covers the whole group
});
it('is a no-op (no fetch) when every node already has a name', async () => {
const fetchGroupMemberList = vi.fn();
const fetchUserProfile = vi.fn();
const api = apiWith({ fetchGroupMemberList, fetchUserProfile });
const nodes: any[] = [{ userUin: 1, nickname: 'has-name', groupId: 7, messageType: 'group', elements: [] }];
expect(await (api as any).enrichSenders(nodes)).toBe(false);
expect(fetchGroupMemberList).not.toHaveBeenCalled();
});
it('keeps the placeholder and never throws when resolution fails', async () => {
const api = apiWith({
fetchGroupMemberList: vi.fn(async () => { throw new Error('net down'); }),
fetchUserProfile: vi.fn(async () => { throw new Error('net down'); }),
});
const nodes: any[] = [{ userUin: 10001, nickname: 'QQ用户', groupId: 700, messageType: 'group', elements: [] }];
await expect((api as any).enrichSenders(nodes)).resolves.toBe(false);
expect(nodes[0].nickname).toBe('QQ用户');
});
it('does NOT fan a member-list failure out to per-uin profile lookups (rate-limit guard)', async () => {
const fetchUserProfile = vi.fn(async (uin: number) => ({ uin, nickname: 'X' }));
const api = apiWith({
fetchGroupMemberList: vi.fn(async () => { throw new Error('net'); }),
fetchUserProfile,
});
// 5 distinct group senders whose member list errors → must keep placeholder,
// NOT trigger 5 profile calls.
const nodes: any[] = Array.from({ length: 5 }, (_, i) => ({
userUin: 20000 + i, nickname: '', groupId: 700, messageType: 'group', elements: [],
}));
expect(await (api as any).enrichSenders(nodes)).toBe(false);
expect(fetchUserProfile).not.toHaveBeenCalled();
expect(nodes.every((n) => n.nickname === '')).toBe(true);
});
});

View File

@@ -88,13 +88,24 @@ describe('apis/group-admin', () => {
expect(env.body?.rejectAddRequest ?? 0).toBe(0);
});
it('leave sends 0x1097_1 with the groupUin', async () => {
it('leave sends 0x1097_1, emits a self group_member_leave, and forgets the group (#133)', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).leave(12345);
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x1097_1');
const env = protobuf_decode<OidbBase<OidbLeaveGroup>>(bytes);
expect(env.body).toMatchObject({ groupUin: 12345 });
// The server never pushes a member-decrease for our own voluntary leave, so
// the bridge synthesizes it (self user_id/operator_id) and drops the group.
expect(bridge.events.emit).toHaveBeenCalledWith(expect.objectContaining({
kind: 'group_member_leave',
groupId: 12345,
userUin: 10001,
operatorUin: 10001,
leaveType: 'leave',
}));
expect(bridge.identity.forgetGroup).toHaveBeenCalledWith(12345);
});
it('setAdmin resolves UID and sends 0x1096_1', async () => {

View File

@@ -1,4 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
@@ -8,6 +8,7 @@ import type {
OidbGroupFileViewResp,
OidbGroupFileFolderResp,
OidbGroupSendFileReq,
OidbGroupSendFileResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type {
OidbPrivateFileUploadResp,
@@ -25,19 +26,32 @@ import type {
vi.mock('@snowluma/protocol/highway', () => ({
fetchHighwaySession: vi.fn(async () => ({})),
uploadHighwayHttp: vi.fn(async () => undefined),
FileChunkSource: { open: vi.fn(async () => ({ size: 3, read: vi.fn(), close: vi.fn(async () => undefined) })) },
}));
vi.mock('@snowluma/protocol/highway/utils', () => ({
loadBinarySource: vi.fn(async (_src: string, fallback: string) => ({
bytes: new Uint8Array([1, 2, 3]),
fileName: `${fallback}.bin`,
})),
computeHashes: vi.fn(() => ({ md5: new Uint8Array(16), sha1: new Uint8Array(20) })),
computeMd5: vi.fn(() => new Uint8Array(16)),
FILE_UPLOAD_MAX_BYTES: 4 * 1024 * 1024 * 1024,
}));
// The upload path now stages the source to disk + stream-hashes it; mock those
// two seams. stageSourceToDisk's filePath must be a REAL file so the mutation
// guard's fsp.stat succeeds (configured per-test in beforeEach → STAGED_FILE).
vi.mock('@snowluma/protocol/highway/stage', () => ({
stageSourceToDisk: vi.fn(),
}));
vi.mock('@snowluma/protocol/highway/hash-file', () => ({
hashFileStreaming: vi.fn(async () => ({
md5: new Uint8Array(16), sha1: new Uint8Array(20),
md5Hex: '00'.repeat(16), sha1Hex: '00'.repeat(20),
sha1Blocks: [], headMd5: new Uint8Array(16),
})),
}));
import fs from 'fs';
import os from 'os';
import path from 'path';
import * as highwayClient from '@snowluma/protocol/highway';
import * as stageMod from '@snowluma/protocol/highway/stage';
import { GroupFileApi } from '../../src/bridge/apis/group-file';
import { mockBridge } from './_helpers';
@@ -48,10 +62,23 @@ function packResponse(body: Uint8Array) {
};
}
let STAGED_FILE: string;
describe('apis/group-file', () => {
beforeAll(() => {
STAGED_FILE = path.join(os.tmpdir(), `sl-gf-staged-${process.pid}.bin`);
fs.writeFileSync(STAGED_FILE, Buffer.from([1, 2, 3])); // real 3-byte file for the guard stat
});
afterAll(() => { try { fs.unlinkSync(STAGED_FILE); } catch { /* ignore */ } });
beforeEach(() => {
vi.mocked(highwayClient.fetchHighwaySession).mockClear();
vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
vi.mocked(highwayClient.FileChunkSource.open).mockClear();
vi.mocked(stageMod.stageSourceToDisk).mockResolvedValue({
filePath: STAGED_FILE, fileSize: 3, fileName: 'file.bin',
cleanup: vi.fn(async () => undefined),
} as any);
});
it('getCount returns { fileCount, maxCount } from the OIDB response', async () => {
@@ -117,6 +144,32 @@ describe('apis/group-file', () => {
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
});
it('[stream] PUTs from the staged disk file via FileChunkSource and releases the temp', async () => {
const cleanup = vi.fn(async () => undefined);
vi.mocked(stageMod.stageSourceToDisk).mockResolvedValueOnce({
filePath: STAGED_FILE, fileSize: 3, fileName: 'file.bin', cleanup,
} as any);
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
upload: {
fileId: 'fid-xyz', uploadIp: '1.2.3.4', uploadPort: 8080,
fileKey: new Uint8Array([9]), checkKey: new Uint8Array([8]),
},
} as any,
}),
));
const api = new GroupFileApi(bridge as any);
vi.spyOn(api, 'publish').mockResolvedValue();
await api.upload(12345, '/path/file.bin');
// Main file streamed from the staged path (not buffered), and the temp is
// released afterward.
expect(highwayClient.FileChunkSource.open).toHaveBeenCalledWith(STAGED_FILE, 3);
expect(vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]![3]).toBeDefined();
expect(cleanup).toHaveBeenCalled();
});
it('upload throws on missing upload response', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
@@ -170,6 +223,28 @@ describe('apis/group-file', () => {
expect(publishSpy).not.toHaveBeenCalled();
});
it('upload can PUT bytes without publishing a separate group file message', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
upload: {
fileId: 'fid-forward',
uploadIp: '127.0.0.1',
uploadPort: 443,
fileKey: new Uint8Array([1]),
checkKey: new Uint8Array([2]),
} as any,
},
}),
));
const api = new GroupFileApi(bridge as any);
const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue();
await api.upload(12345, 'base64://AQID', 'forward.txt', '/', true, false);
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
expect(publishSpy).not.toHaveBeenCalled();
});
it('upload returns success even when the chat post fails (file is still uploaded)', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
@@ -224,6 +299,26 @@ describe('apis/group-file', () => {
});
});
it('trans hits OIDB 0x6d9_0 and returns the saved path metadata', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupSendFileResp>>({
body: { transFile: { saveBusId: 102, saveFilePath: '/saved/path' } },
}),
));
const out = await new GroupFileApi(bridge as any).trans(12345, 'fid-trans');
expect(out).toEqual({ saveBusId: 102, saveFilePath: '/saved/path' });
const [wire, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x6d9_0');
const env = protobuf_decode<OidbBase<OidbGroupSendFileReq>>(bytes);
expect(env.body?.transFile).toMatchObject({
groupUin: 12345n,
appId: 7,
busId: 102,
fileId: 'fid-trans',
});
});
it('uploadPrivate resolves both target + self UID before OIDB call', async () => {
const bridge = mockBridge({
identity: {
@@ -233,6 +328,7 @@ describe('apis/group-file', () => {
findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0),
findGroupMember: vi.fn(() => null),
forgetGroup: vi.fn(),
},
});
vi.mocked(bridge.resolveUserUid)
@@ -297,6 +393,54 @@ describe('apis/group-file', () => {
expect(bridge.apis.message.sendC2cFile).not.toHaveBeenCalled();
});
it('uploadPrivate can PUT bytes without publishing a separate c2c file message', async () => {
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: {
upload: {
uuid: 'pfid-forward',
fileAddon: 'phash-forward',
rtpMediaPlatformUploadAddress: [
{ outIP: 0, outPort: 0, inIP: 16885952, inPort: 8080, iPType: 1 },
],
mediaPlatformUploadKey: new Uint8Array([1, 2, 3]),
} as any,
},
}),
));
await new GroupFileApi(bridge as any).uploadPrivate(67890, 'base64://AQID', 'forward.txt', true, false);
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
expect(bridge.apis.message.sendC2cFile).not.toHaveBeenCalled();
});
it('[stream] uploadPrivate PUTs from the staged disk file via FileChunkSource and releases the temp', async () => {
const cleanup = vi.fn(async () => undefined);
vi.mocked(stageMod.stageSourceToDisk).mockResolvedValueOnce({
filePath: STAGED_FILE, fileSize: 3, fileName: 'file.bin', cleanup,
} as any);
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: {
upload: {
uuid: 'pfid-stream', fileAddon: 'phash',
rtpMediaPlatformUploadAddress: [
{ outIP: 0, outPort: 0, inIP: 16885952, inPort: 8080, iPType: 1 },
],
mediaPlatformUploadKey: new Uint8Array([1, 2, 3]),
} as any,
},
}),
));
await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file', 'doc.pdf', true, false);
expect(highwayClient.FileChunkSource.open).toHaveBeenCalledWith(STAGED_FILE, 3);
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
expect(cleanup).toHaveBeenCalled();
});
it('uploadPrivate reads host from rtpMediaPlatformUploadAddress[0].inIP when populated', async () => {
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');

View File

@@ -28,6 +28,7 @@ vi.mock('@snowluma/protocol/bridge-oidb', async () => {
vi.mock('@snowluma/protocol/highway', () => ({
fetchHighwaySession: vi.fn(async () => ({})),
uploadHighwayHttp: vi.fn(async () => undefined),
BufferChunkSource: class BufferChunkSource { constructor(readonly bytes: Uint8Array) {} },
}));
vi.mock('@snowluma/protocol/highway/utils', () => ({

View File

@@ -49,16 +49,65 @@ describe('apis/qzone', () => {
expect(feedsSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 3, 20);
});
it('publish posts to the bot\'s own space with the given content', async () => {
it('uploadImageFromSource uploads from file:// http:// base64:// and returns richval + url', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK', skey: 'SK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const uploadSpy = vi.spyOn(qzoneWeb, 'uploadQzoneImageFromSource').mockResolvedValue({
richval: ',12345,abc,abc,22,800,600,,800,600',
url: 'https://example.com/img.jpg',
albumid: '12345',
lloc: 'abc',
type: 22,
width: 600,
height: 800,
});
const out = await new QzoneApi(bridge as never).uploadImageFromSource('file:///path/to/image.jpg');
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(uploadSpy).toHaveBeenCalledWith({ p_skey: 'PSK', skey: 'SK' }, '10001', 'file:///path/to/image.jpg');
expect(out.richval).toBe(',12345,abc,abc,22,800,600,,800,600');
expect(out.url).toBe('https://example.com/img.jpg');
});
it('publish posts to the bot\'s own space with the given content (text-only)', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T', time: 1 });
const out = await new QzoneApi(bridge as never).publish('hello');
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello');
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello', undefined, undefined, 1, undefined);
expect(out).toEqual({ tid: 'T', time: 1 });
});
it('publish posts with richtype and richval for image post', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T2', time: 2 });
const richval = ',12345,abc,abc,22,800,600,,800,600';
const out = await new QzoneApi(bridge as never).publish('look at this', 1, richval);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'look at this', 1, richval, 1, undefined);
expect(out).toEqual({ tid: 'T2', time: 2 });
});
it('publish posts with multiple images (richval joined with tab)', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T3', time: 3 });
const richval = ',12345,a,a,22,800,600,,800,600\t,12346,b,b,22,1024,768,,1024,768';
const out = await new QzoneApi(bridge as never).publish('two images', 1, richval);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'two images', 1, richval, 1, undefined);
expect(out).toEqual({ tid: 'T3', time: 3 });
});
it('publish threads qzone visibility params', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T', time: 1 });
await new QzoneApi(bridge as never).publish('hello', undefined, undefined, 16, '10002|10003');
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello', undefined, undefined, 16, '10002|10003');
});
it('delete removes a feed by tid from the bot\'s own space', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
@@ -68,6 +117,16 @@ describe('apis/qzone', () => {
expect(delSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'TID9');
});
it('updateRight changes a feed\'s visibility on the bot\'s own space', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const updSpy = vi.spyOn(qzoneWeb, 'updateQzoneMsgRight').mockResolvedValue({ ugc_right: 16 });
const out = await new QzoneApi(bridge as never).updateRight('TID9', 16, '10002|10003');
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(updSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'TID9', 16, '10002|10003');
expect(out).toEqual({ ugc_right: 16 });
});
it('like defaults the feed owner to self and passes opUin=self + like flag', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
@@ -92,7 +151,7 @@ describe('apis/qzone', () => {
const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '1' });
const out = await new QzoneApi(bridge as never).comment('TIDX', 'nice', undefined);
// selfUin='10001' commenter; owner defaults to self
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice');
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice', undefined, undefined);
expect(out).toEqual({ comment_id: '1' });
});
@@ -101,6 +160,15 @@ describe('apis/qzone', () => {
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '2' });
await new QzoneApi(bridge as never).comment('TIDX', 'nice', 20002);
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '20002', 'TIDX', 'nice');
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '20002', 'TIDX', 'nice', undefined, undefined);
});
it('comment with images (richType=1, richval=direct URLs joined with tab)', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '3' });
const richval = 'https://example.com/a.jpg\thttps://example.com/b.jpg';
await new QzoneApi(bridge as never).comment('TIDX', 'nice pic', undefined, 1, richval);
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice pic', 1, richval);
});
});

View File

@@ -3,15 +3,22 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
import type { FileExtra } from '@snowluma/proto-defs/message';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbOfflineFileFinalizeResp } from '@snowluma/proto-defs/oidb-actions/media';
vi.mock('@snowluma/protocol/element-builder', () => ({
buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]),
}));
// Imported statically (not via `await import` inside each `it`) so the heavy
// Bridge dependency-tree load happens once at file collection — not against a
// single test's 5s timeout, which tipped over on slower CI runners. vi.mock is
// hoisted above these by vitest, so element-builder is still mocked.
import { Bridge } from '../src/bridge/bridge';
import { IdentityService } from '@snowluma/protocol/identity-service';
describe('Bridge private media routing', () => {
it('includes resolved uid in the final c2c send request for media messages', async () => {
const { Bridge } = await import('../src/bridge/bridge');
const { IdentityService } = await import('@snowluma/protocol/identity-service');
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
@@ -59,12 +66,26 @@ describe('Bridge private media routing', () => {
// BuildPacketBase` + `FileEntity.PackMessageContent`. Previous
// implementation wrote c2c routing + richText.notOnlineFile +
// c2cCmd=11 — the QQ-NT server rejected every c2c file send.
const { Bridge } = await import('../src/bridge/bridge');
const { IdentityService } = await import('@snowluma/protocol/identity-service');
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
override async sendRawPacket(_cmd: string, body: Uint8Array): Promise<SendPacketResult> {
finalizeCmd: string | null = null;
override async resolveUserUid(uin: number): Promise<string> {
return uin === 10000 ? 'u_self' : `u_${uin}`;
}
override async sendRawPacket(cmd: string, body: Uint8Array): Promise<SendPacketResult> {
// The c2c file send first runs the 0xE37_800 finalize, then PbSendMsg.
if (cmd.includes('0xe37_800')) {
this.finalizeCmd = cmd;
return {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<OidbOfflineFileFinalizeResp>>({
body: { body: { metadata: { field3: 11, field100: new Uint8Array([1]), field101: new Uint8Array([2]), field110: 22, timestamp1: 1710000123 } } },
})),
};
}
this.capturedBody = body;
return {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
@@ -118,9 +139,66 @@ describe('Bridge private media routing', () => {
// expireTime is now+7d; just sanity-check it landed (non-zero, plausible)
expect(fileExtra?.file?.expireTime).toBeGreaterThan(Math.floor(Date.now() / 1000));
// issue #157: when the 0xE37_800 finalize succeeds, its download routing
// rides along in field6 (best-effort enrichment on top of the always-
// present NotOnlineFile).
expect(bridge.finalizeCmd).toBe('OidbSvcTrpcTcp.0xe37_800');
expect(fileExtra?.field6?.field2).toMatchObject({
fileUuid: 'uuid-abc-123',
fileName: 'doc.txt',
fileHash: 'hash-xyz',
selfUid: 'u_self',
destUid: 'u_peer_xyz',
field1: 22, // ← finalize metadata.field110
field6: 11, // ← finalize metadata.field3
timestamp1: 1710000123,
});
expect(fileExtra?.field6?.field2?.field7).toEqual(new Uint8Array([2])); // ← metadata.field101
expect(fileExtra?.field6?.field2?.field8).toEqual(new Uint8Array([1])); // ← metadata.field100
// c2cCmd is left at 0 / undefined — the old `c2cCmd=11` was a
// stale go-cqhttp value the QQ-NT server doesn't recognise on the
// c2c-file path.
expect(request?.contentHead?.c2cCmd ?? 0).toBe(0);
});
it('c2c file send survives a failing 0xE37_800 finalize — sends without field6 (#157 best-effort)', async () => {
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
override async resolveUserUid(uin: number): Promise<string> {
return uin === 10000 ? 'u_self' : `u_${uin}`;
}
override async sendRawPacket(cmd: string, body: Uint8Array): Promise<SendPacketResult> {
// Finalize fails (server error → OidbError). The send must NOT fail
// because of it.
if (cmd.includes('0xe37_800')) {
return { success: false, gotResponse: true, errorCode: 9999, errorMessage: 'finalize boom', responseData: Buffer.alloc(0) };
}
this.capturedBody = body;
return {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<SendMessageResponse>({
result: 0, errMsg: '', privateSequence: 88, timestamp1: 1710000000,
})),
};
}
}
const bridge = new TestBridge(IdentityService.memory('10000'));
// Should resolve (not throw) despite the finalize error.
await bridge.apis.message.sendC2cFile(67890, 'u_peer_xyz', {
fileId: 'uuid-abc-123', fileName: 'doc.txt', fileSize: 1024,
fileMd5: new Uint8Array([1, 2, 3, 4]), fileHash: 'hash-xyz',
});
// PbSendMsg still went out, carrying the file but NO field6.
expect(bridge.capturedBody).toBeInstanceOf(Uint8Array);
const request = protobuf_decode<SendMessageRequest>(bridge.capturedBody as Uint8Array);
const fileExtra = protobuf_decode<FileExtra>(request!.messageBody!.msgContent as Uint8Array);
expect(fileExtra?.file?.fileUuid).toBe('uuid-abc-123');
expect(fileExtra?.field6 ?? undefined).toBeUndefined();
});
});

View File

@@ -3,7 +3,7 @@
// so this exercises the loop/cursor logic, not the wire decode (covered in
// packages/protocol/tests/msg-push/fetch-group-history.test.ts).
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('@snowluma/protocol/msg-push', async (importOriginal) => {
const actual = await importOriginal<typeof import('@snowluma/protocol/msg-push')>();
@@ -27,7 +27,22 @@ function gm(seq: number): any {
const ctx = { identity: {}, sendRawPacket: vi.fn() } as any;
describe('MessageApi.getGroupHistory walk-back', () => {
beforeEach(() => mockFetch.mockReset());
// The walk-back loop enforces a real ~300ms gap between each SsoGetGroupMsg
// send (a deliberate anti-flood throttle, unchanged in production). Fake the
// clock so the test exercises the loop/cursor logic instantly instead of
// waiting out 300ms × up-to-12 real sends.
beforeEach(() => {
mockFetch.mockReset();
vi.useFakeTimers();
});
afterEach(() => vi.useRealTimers());
// Drives a throttled getGroupHistory to completion under fake timers: kick it
// off, flush the queued send-gap timers, then await the result.
async function runHistory<T>(promise: Promise<T>): Promise<T> {
await vi.runAllTimersAsync();
return promise;
}
it('walks back across short-capped windows, dedups, returns newest `want` ascending', async () => {
// Server caps every window to its newest 10 sequences → forces walk-back.
@@ -37,7 +52,7 @@ describe('MessageApi.getGroupHistory walk-back', () => {
return out;
});
const res = await new MessageApi(ctx).getGroupHistory(9999, 200, 50);
const res = await runHistory(new MessageApi(ctx).getGroupHistory(9999, 200, 50));
expect(res).toHaveLength(50);
expect(res[0].msgSeq).toBe(151); // newest 50 ending at 200 → 151..200
@@ -54,7 +69,7 @@ describe('MessageApi.getGroupHistory walk-back', () => {
return out;
});
const res = await new MessageApi(ctx).getGroupHistory(9999, 20, 100); // only seq 1..20 exist
const res = await runHistory(new MessageApi(ctx).getGroupHistory(9999, 20, 100)); // only seq 1..20 exist
expect(res.map((m) => m.msgSeq)).toEqual(Array.from({ length: 20 }, (_, i) => i + 1));
});
@@ -65,7 +80,7 @@ describe('MessageApi.getGroupHistory walk-back', () => {
return [gm(end)]; // one message per window → never reaches a large `want`
});
const res = await new MessageApi(ctx).getGroupHistory(9999, 100_000, 9999);
const res = await runHistory(new MessageApi(ctx).getGroupHistory(9999, 100_000, 9999));
expect(calls).toBeLessThanOrEqual(12); // HISTORY_MAX_REQUESTS
expect(res.length).toBeLessThanOrEqual(200); // HISTORY_MAX_COUNT
});

View File

@@ -0,0 +1,103 @@
// ChunkSource is the buffer-or-disk abstraction the highway PUT loop reads
// through (#stream-upload). The whole streaming refactor rests on one
// invariant: a FileChunkSource must yield BYTE-FOR-BYTE the same chunks as a
// BufferChunkSource over the same file, at every (offset, length) the uploader
// asks for. These tests are that byte-oracle.
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { promises as fsp } from 'fs';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { randomUUID } from 'crypto';
import { BufferChunkSource, FileChunkSource } from '@snowluma/protocol/highway';
// Mirrors highway-client's HIGHWAY_BLOCK_SIZE chunk walk without the network:
// step through [0,size) in `block` strides, last chunk short by construction.
async function collectChunks(src: { size: number; read(o: number, l: number): Promise<Uint8Array> }, block: number) {
const chunks: Uint8Array[] = [];
let offset = 0;
while (offset < src.size) {
const len = Math.min(block, src.size - offset);
chunks.push(new Uint8Array(await src.read(offset, len)));
offset += len;
}
return chunks;
}
describe('ChunkSource — FileChunkSource ≡ BufferChunkSource', () => {
let dir: string;
beforeAll(async () => { dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-chunk-')); });
afterAll(async () => { await fsp.rm(dir, { recursive: true, force: true }); });
// Sizes chosen around block boundaries: exact multiple, +1, -1, tiny, empty.
for (const [label, size, block] of [
['empty', 0, 7],
['tiny (< block)', 5, 7],
['exact multiple', 21, 7],
['one past a boundary', 22, 7],
['one before a boundary', 20, 7],
['single full block', 7, 7],
] as const) {
it(`${label}: chunks + size are byte-identical (size=${size}, block=${block})`, async () => {
const data = new Uint8Array(size);
for (let i = 0; i < size; i++) data[i] = (i * 31 + 7) & 0xff;
const file = path.join(dir, `${randomUUID()}.bin`);
fs.writeFileSync(file, data);
const buf = new BufferChunkSource(data);
const fch = await FileChunkSource.open(file, size);
try {
expect(fch.size).toBe(buf.size);
expect(fch.size).toBe(size);
const a = await collectChunks(buf, block);
const b = await collectChunks(fch, block);
expect(b.length).toBe(a.length);
for (let i = 0; i < a.length; i++) {
expect(Buffer.from(b[i]!).equals(Buffer.from(a[i]!))).toBe(true);
}
// Reassembled stream equals the original bytes exactly.
expect(Buffer.concat(b.map((c) => Buffer.from(c))).equals(Buffer.from(data))).toBe(true);
} finally {
await fch.close();
}
});
}
it('FileChunkSource.read returns EXACTLY the requested length (no short read leaks)', async () => {
const data = new Uint8Array(1000).map((_, i) => (i * 13) & 0xff);
const file = path.join(dir, `${randomUUID()}.bin`);
fs.writeFileSync(file, data);
const fch = await FileChunkSource.open(file, data.length);
try {
for (const [off, len] of [[0, 1], [0, 1000], [37, 200], [999, 1], [500, 500]] as const) {
const got = await fch.read(off, len);
expect(got.length).toBe(len);
expect(Buffer.from(got).equals(Buffer.from(data.subarray(off, off + len)))).toBe(true);
}
} finally {
await fch.close();
}
});
it('FileChunkSource.read throws on unexpected EOF (request past end)', async () => {
const data = new Uint8Array(10);
const file = path.join(dir, `${randomUUID()}.bin`);
fs.writeFileSync(file, data);
const fch = await FileChunkSource.open(file, 10);
try {
await expect(fch.read(5, 20)).rejects.toThrow(/unexpected EOF/);
} finally {
await fch.close();
}
});
it('BufferChunkSource.close and FileChunkSource.close both resolve (idempotent contract)', async () => {
const buf = new BufferChunkSource(new Uint8Array(3));
await expect(buf.close()).resolves.toBeUndefined();
const file = path.join(dir, `${randomUUID()}.bin`);
fs.writeFileSync(file, new Uint8Array(3));
const fch = await FileChunkSource.open(file, 3);
await expect(fch.close()).resolves.toBeUndefined();
});
});

View File

@@ -0,0 +1,92 @@
// hashFileStreaming is the streaming replacement for the buffered
// `computeHashes` + `computeVideoSha1Blocks` (+ head-md5) used before an
// upload. The refactor's whole promise is byte-for-byte identity, so this
// test IS the oracle: for a spread of sizes around the 1 MiB block boundary
// (and a spread of head limits around chunk boundaries) it asserts the
// streaming result equals the buffered functions over the same bytes.
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { promises as fsp } from 'fs';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { randomUUID } from 'crypto';
import { hashFileStreaming } from '@snowluma/protocol/highway/hash-file';
import { computeHashes, computeMd5 } from '@snowluma/protocol/highway/utils';
import { computeVideoSha1Blocks } from '@snowluma/protocol/highway/video-upload';
const MB = 1024 * 1024;
function synth(size: number): Uint8Array {
const b = new Uint8Array(size);
for (let i = 0; i < size; i++) b[i] = (i * 131 + 7) & 0xff;
return b;
}
function eq(a: Uint8Array, b: Uint8Array): boolean {
return Buffer.from(a).equals(Buffer.from(b));
}
describe('hashFileStreaming ≡ buffered computeHashes + computeVideoSha1Blocks + head-md5', () => {
let dir: string;
beforeAll(async () => { dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-hash-')); });
afterAll(async () => { await fsp.rm(dir, { recursive: true, force: true }); });
// Sizes chosen around the 1 MiB block boundary + sub-block + multi-block.
const SIZES = [0, 1, 63, 64, 65, MB - 1, MB, MB + 1, 2 * MB, 2 * MB + 123];
for (const size of SIZES) {
it(`size=${size}: md5 / sha1 / sha1Blocks match the buffered helpers`, async () => {
const data = synth(size);
const file = path.join(dir, `${randomUUID()}.bin`);
fs.writeFileSync(file, data);
const streamed = await hashFileStreaming(file);
const buffered = computeHashes(data);
const refBlocks = computeVideoSha1Blocks(data);
expect(eq(streamed.md5, buffered.md5)).toBe(true);
expect(eq(streamed.sha1, buffered.sha1)).toBe(true);
expect(streamed.md5Hex).toBe(buffered.md5Hex);
expect(streamed.sha1Hex).toBe(buffered.sha1Hex);
expect(streamed.headMd5).toBeUndefined();
// sha1Blocks must match exactly — same count, same bytes, same order.
expect(streamed.sha1Blocks.length).toBe(refBlocks.length);
for (let i = 0; i < refBlocks.length; i++) {
expect(eq(streamed.sha1Blocks[i]!, refBlocks[i]!)).toBe(true);
}
});
}
it('headMd5 matches computeMd5(first N bytes) across boundaries (±1, block edge, ≥size)', async () => {
const size = 2 * MB + 500;
const data = synth(size);
const file = path.join(dir, `${randomUUID()}.bin`);
fs.writeFileSync(file, data);
// head limits: empty, tiny, mid-first-block, exact block boundary ±1,
// and past the end (must clamp to size).
const limits = [0, 1, 1000, MB - 1, MB, MB + 1, size - 1, size, size + 1];
for (const L of limits) {
const streamed = await hashFileStreaming(file, { headLimit: L });
const ref = computeMd5(data.subarray(0, Math.min(data.length, L)));
expect(streamed.headMd5).toBeDefined();
expect(eq(streamed.headMd5!, ref)).toBe(true);
// The rest of the digests are unaffected by headLimit.
expect(streamed.md5Hex).toBe(computeHashes(data).md5Hex);
}
});
it('empty file: md5/sha1 of nothing, single finalized sha1 block, headMd5 of empty', async () => {
const file = path.join(dir, `${randomUUID()}.bin`);
fs.writeFileSync(file, new Uint8Array(0));
const streamed = await hashFileStreaming(file, { headLimit: 10 });
const buffered = computeHashes(new Uint8Array(0));
expect(streamed.md5Hex).toBe(buffered.md5Hex);
expect(streamed.sha1Hex).toBe(buffered.sha1Hex);
expect(streamed.sha1Blocks.length).toBe(1); // just the finalized whole-file sha1
expect(eq(streamed.sha1Blocks[0]!, buffered.sha1)).toBe(true);
expect(eq(streamed.headMd5!, computeMd5(new Uint8Array(0)))).toBe(true);
});
});

View File

@@ -88,7 +88,7 @@ vi.mock('net', () => ({
createConnection: createConnectionMock,
}));
import { uploadHighwayHttp, type HighwaySession } from '@snowluma/protocol/highway';
import { uploadHighwayHttp, BufferChunkSource, type HighwaySession } from '@snowluma/protocol/highway';
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
@@ -130,7 +130,7 @@ describe('uploadHighwayHttp connection lifecycle', () => {
// 0.5 MiB → 1 chunk。覆盖 PTT / 小图的常见场景。
const bytes = new Uint8Array(512 * 1024);
await uploadHighwayHttp(
makeBridge(), makeSession(), 1003, bytes, new Uint8Array(16), new Uint8Array(0),
makeBridge(), makeSession(), 1003, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0),
);
expect(createConnectionMock).toHaveBeenCalledTimes(1);
expect(createdSockets[0]!.destroyed).toBe(true);
@@ -142,7 +142,7 @@ describe('uploadHighwayHttp connection lifecycle', () => {
// 关闭,新实现必须为每个 chunk 各开一个 socket。
const bytes = new Uint8Array(Math.floor(1.5 * HIGHWAY_BLOCK_SIZE));
await uploadHighwayHttp(
makeBridge(), makeSession(), 1003, bytes, new Uint8Array(16), new Uint8Array(0),
makeBridge(), makeSession(), 1003, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0),
);
expect(createConnectionMock).toHaveBeenCalledTimes(2);
expect(createdSockets).toHaveLength(2);
@@ -154,8 +154,15 @@ describe('uploadHighwayHttp connection lifecycle', () => {
it('opens N connections for N chunks (3 chunks here)', async () => {
const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE));
await uploadHighwayHttp(
makeBridge(), makeSession(), 1004, bytes, new Uint8Array(16), new Uint8Array(0),
makeBridge(), makeSession(), 1004, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0),
);
expect(createConnectionMock).toHaveBeenCalledTimes(3);
});
it('a zero-length source opens ZERO connections (empty-input invariant)', async () => {
await uploadHighwayHttp(
makeBridge(), makeSession(), 1003, new BufferChunkSource(new Uint8Array(0)), new Uint8Array(16), new Uint8Array(0),
);
expect(createConnectionMock).not.toHaveBeenCalled();
});
});

View File

@@ -153,9 +153,12 @@ describe('runNtv2Upload — two images in one message (sequential)', () => {
// The PUT receives image-2's bytes, image-2's md5, and the
// image-2-derived extend (NOT image-1's data).
const [, , cmdId, putBytes, putMd5, putExtend] = vi.mocked(highway.uploadHighwayHttp).mock.calls[0]!;
const [, , cmdId, putSource, putMd5, putExtend] = vi.mocked(highway.uploadHighwayHttp).mock.calls[0]!;
expect(cmdId).toBe(1004);
expect(putBytes).toBe(image2Bytes);
// The PUT source is a ChunkSource wrapping image-2's bytes — verify it
// yields image-2 exactly (not image-1) through its public read().
expect(putSource.size).toBe(image2Bytes.length);
expect(Buffer.from(await putSource.read(0, putSource.size)).equals(Buffer.from(image2Bytes))).toBe(true);
expect(putMd5).toBe(image2Md5);
// Decode the extend bytes; uKey + fileUuid must come from image-2's

View File

@@ -12,6 +12,7 @@ vi.mock('@snowluma/protocol/highway', () => ({
fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })),
uploadHighwayHttp: vi.fn(async () => undefined),
buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])),
BufferChunkSource: class BufferChunkSource { constructor(readonly bytes: Uint8Array) {} },
PRIVATE_IMAGE_CMD_ID: 1003,
GROUP_IMAGE_CMD_ID: 1004,
}));
@@ -283,6 +284,11 @@ describe('pipeline — runNtv2Upload', () => {
}))).rejects.toThrow(/image fast-upload not available/);
});
// (Removed the forceFullOnFastPath retry tests with the feature itself — real-
// machine testing + kernel RE proved the tryFastUploadCompleted:false retry
// never forces a fresh upload; expired-but-indexed video resources are a
// platform limitation. See #145.)
it('silently skips a sub-file with empty bytes when no fastOnlyError is configured', async () => {
// This mirrors the video-thumb path where bytes are always synthesised
// (FALLBACK_THUMB) so we don't expect the check to fire even if the

View File

@@ -0,0 +1,214 @@
// stageSourceToDisk unifies every upload source onto a local disk path so the
// streaming uploader never buffers a whole file. These tests cover the three
// source kinds, the crash-safety contract (hardlink survives caller-side
// deletion — the retention race Codex flagged), size caps, symlink resolution,
// cleanup, and the orphan reaper's active-set safety.
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { promises as fsp } from 'fs';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { randomUUID } from 'crypto';
import { stageSourceToDisk, sweepStagedUploads, STAGE_DIR } from '@snowluma/protocol/highway/stage';
import { pathToFileURL } from 'url';
const originalFetch = globalThis.fetch;
let scratch: string;
async function readStaged(p: string): Promise<Buffer> {
return fsp.readFile(p);
}
beforeEach(async () => { scratch = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-stage-src-')); });
afterEach(async () => {
globalThis.fetch = originalFetch;
await fsp.rm(scratch, { recursive: true, force: true });
});
describe('stageSourceToDisk — base64', () => {
it('stages base64 bytes to disk', async () => {
const data = Buffer.from('hello base64 world');
const staged = await stageSourceToDisk(`base64://${data.toString('base64')}`, 1024);
try {
expect(staged.fileSize).toBe(data.length);
expect(staged.fileName).toBe('');
expect((await readStaged(staged.filePath)).equals(data)).toBe(true);
expect(staged.filePath.startsWith(STAGE_DIR)).toBe(true);
} finally { await staged.cleanup(); }
});
it('rejects oversized base64 on decoded length (before allocation) and leaves no temp', async () => {
const big = Buffer.alloc(4096).toString('base64');
await expect(stageSourceToDisk(`base64://${big}`, 64)).rejects.toThrow(/too large/);
const parts = (await fsp.readdir(STAGE_DIR).catch(() => [] as string[])).filter((n) => n.endsWith('.part'));
expect(parts).toEqual([]);
});
});
describe('stageSourceToDisk — http', () => {
it('streams an http download to disk with the URL basename', async () => {
const body = new Uint8Array([9, 8, 7, 6, 5]);
globalThis.fetch = (async () => new Response(body, { status: 200 })) as typeof fetch;
const staged = await stageSourceToDisk('https://example.test/clip.mp4', 1024);
try {
expect(staged.fileName).toBe('clip.mp4');
expect(staged.fileSize).toBe(body.length);
expect((await readStaged(staged.filePath)).equals(Buffer.from(body))).toBe(true);
} finally { await staged.cleanup(); }
});
it('rejects an oversized http download and cleans up the .part', async () => {
globalThis.fetch = (async () => new Response(new Uint8Array(4096), {
status: 200, headers: { 'content-length': '4096' },
})) as typeof fetch;
await expect(stageSourceToDisk('https://example.test/big.bin', 64)).rejects.toThrow(/too large/);
const leftover = (await fsp.readdir(STAGE_DIR).catch(() => [] as string[])).filter((n) => n.endsWith('.part'));
expect(leftover).toEqual([]);
});
it('rejects a STREAMED overflow (no Content-Length) after the sink+.part exist, then cleans up', async () => {
// No content-length → the size cap only trips mid-stream, AFTER fileSink has
// opened the .part. This exercises fileSink.discard()'s close-before-unlink.
const stream = new ReadableStream<Uint8Array>({
start(c) { for (let i = 0; i < 8; i++) c.enqueue(new Uint8Array(4096)); c.close(); },
});
globalThis.fetch = (async () => new Response(stream, { status: 200 })) as typeof fetch;
await expect(stageSourceToDisk('https://example.test/stream.bin', 4 * 1024)).rejects.toThrow(/too large/);
const parts = (await fsp.readdir(STAGE_DIR).catch(() => [] as string[])).filter((n) => n.endsWith('.part'));
expect(parts).toEqual([]);
});
it('retries with a Referer after a network failure and stages the retry body cleanly (no attempt-1 leftovers)', async () => {
const body = new Uint8Array([1, 2, 3, 4, 5, 6, 7]);
let n = 0;
globalThis.fetch = (async () => {
n += 1;
if (n === 1) throw new TypeError('fetch failed'); // anti-bot RST on attempt 1
return new Response(body, { status: 200 });
}) as typeof fetch;
const staged = await stageSourceToDisk('https://example.test/r.mp4', 1024);
try {
expect(n).toBe(2);
expect(staged.fileSize).toBe(body.length);
expect((await readStaged(staged.filePath)).equals(Buffer.from(body))).toBe(true);
} finally { await staged.cleanup(); }
});
});
describe('stageSourceToDisk — local files', () => {
it('hardlinks a local file:// source and survives caller-side deletion (retention race)', async () => {
const src = path.join(scratch, 'video.mp4');
const data = Buffer.from('the caller-owned temp that retention will delete');
fs.writeFileSync(src, data);
const staged = await stageSourceToDisk(pathToFileURL(src).href, 1 << 20);
try {
expect(staged.fileName).toBe('video.mp4');
expect(staged.fileSize).toBe(data.length);
// Simulate upload_file_stream's retention timer unlinking the original
// BETWEEN the hash pass and the upload pass.
await fsp.unlink(src);
// The hardlink kept the inode alive — the staged path is still fully readable.
expect((await readStaged(staged.filePath)).equals(data)).toBe(true);
} finally { await staged.cleanup(); }
});
it('accepts a raw local path and preserves its basename', async () => {
const src = path.join(scratch, 'doc.bin');
fs.writeFileSync(src, Buffer.from([1, 2, 3, 4]));
const staged = await stageSourceToDisk(src, 1 << 20);
try {
expect(staged.fileName).toBe('doc.bin');
expect(staged.fileSize).toBe(4);
} finally { await staged.cleanup(); }
});
it('resolves a symlink to its target but keeps the symlink basename', async () => {
const target = path.join(scratch, 'real-xyz.tmp');
const linkPath = path.join(scratch, 'friendly.mp4');
const data = Buffer.from('symlinked content');
fs.writeFileSync(target, data);
fs.symlinkSync(target, linkPath);
const staged = await stageSourceToDisk(linkPath, 1 << 20);
try {
expect(staged.fileName).toBe('friendly.mp4'); // original basename, not the target's
expect((await readStaged(staged.filePath)).equals(data)).toBe(true);
} finally { await staged.cleanup(); }
});
it('falls back to a streamed copy when hardlink fails (e.g. cross-filesystem EXDEV)', async () => {
const src = path.join(scratch, 'xfs.mp4');
const data = Buffer.from('content that must copy when link() is refused');
fs.writeFileSync(src, data);
const linkSpy = vi.spyOn(fsp, 'link').mockRejectedValueOnce(Object.assign(new Error('EXDEV'), { code: 'EXDEV' }));
try {
const staged = await stageSourceToDisk(src, 1 << 20);
try {
expect(linkSpy).toHaveBeenCalledOnce();
expect(staged.fileName).toBe('xfs.mp4');
expect(staged.fileSize).toBe(data.length);
expect((await readStaged(staged.filePath)).equals(data)).toBe(true);
// The copy is an independent file — deleting the source leaves it intact.
await fsp.unlink(src);
expect((await readStaged(staged.filePath)).equals(data)).toBe(true);
} finally { await staged.cleanup(); }
} finally { linkSpy.mockRestore(); }
});
it('rejects a non-regular file (directory)', async () => {
await expect(stageSourceToDisk(scratch, 1 << 20)).rejects.toThrow(/not a regular file/);
});
it('rejects an oversized local file before staging', async () => {
const src = path.join(scratch, 'huge.bin');
fs.writeFileSync(src, Buffer.alloc(200));
await expect(stageSourceToDisk(src, 64)).rejects.toThrow(/too large: 200 > 64/);
});
});
describe('stageSourceToDisk — cleanup + reaper', () => {
it('cleanup removes the staged temp and is idempotent', async () => {
const src = path.join(scratch, 'c.bin');
fs.writeFileSync(src, Buffer.from([1]));
const staged = await stageSourceToDisk(src, 1 << 20);
expect(fs.existsSync(staged.filePath)).toBe(true);
await staged.cleanup();
expect(fs.existsSync(staged.filePath)).toBe(false);
await expect(staged.cleanup()).resolves.toBeUndefined(); // idempotent, no throw
});
it('reaper removes an old ORPHAN temp but NEVER an in-flight (active) staged file', async () => {
await fsp.mkdir(STAGE_DIR, { recursive: true });
const old = Date.now() - 60 * 60 * 1000; // 1h ago
// Orphan: a temp NOT tracked in `active` (as a crash would leave), aged out.
const orphan = path.join(STAGE_DIR, `stage-${randomUUID()}.orphan`);
fs.writeFileSync(orphan, Buffer.from('crash leftover'));
fs.utimesSync(orphan, new Date(old), new Date(old));
// In-flight: a real staged file (registered in `active`), also aged out —
// the active-set must protect it from the age sweep.
const src = path.join(scratch, 'inflight.bin');
fs.writeFileSync(src, Buffer.from('being uploaded'));
const staged = await stageSourceToDisk(src, 1 << 20);
fs.utimesSync(staged.filePath, new Date(old), new Date(old)); // read-only upload → stale mtime
const removed = await sweepStagedUploads(Date.now());
expect(fs.existsSync(orphan)).toBe(false); // orphan reaped
expect(fs.existsSync(staged.filePath)).toBe(true); // active file preserved
expect(removed).toBeGreaterThanOrEqual(1);
await staged.cleanup();
});
it('reaper leaves a recent orphan alone', async () => {
await fsp.mkdir(STAGE_DIR, { recursive: true });
const recent = path.join(STAGE_DIR, `stage-${randomUUID()}.recent`);
fs.writeFileSync(recent, Buffer.from('fresh'));
try {
await sweepStagedUploads(Date.now());
expect(fs.existsSync(recent)).toBe(true);
} finally { await fsp.rm(recent, { force: true }); }
});
});

View File

@@ -10,6 +10,12 @@
// always provides bytes), and the video-specific OIDB fields.
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { promises as fsp } from 'fs';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { pathToFileURL } from 'url';
import { computeHashes } from '@snowluma/protocol/highway/utils';
vi.mock('@snowluma/protocol/highway/pipeline', () => ({
runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })),
@@ -80,6 +86,16 @@ describe('video-upload', () => {
expect(uploads[1]!.fastOnlyError).toBeUndefined();
});
it('does NOT set a force-full retry flag on the main file (#145 — proven ineffective)', async () => {
// The old forceFullOnFastPath retry was removed: real-machine + kernel RE
// showed it never forces a fresh upload (the server fast-paths by md5
// metadata regardless of tryFastUploadCompleted). An expired-but-indexed
// video resource is a platform limitation, not an upload-flow fix.
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const uploads = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploads;
expect((uploads[0] as unknown as Record<string, unknown>).forceFullOnFastPath).toBeUndefined();
});
it('uploadInfo carries TWO entries (main mp4 + thumb jpg) with subFileType 0 and 100', async () => {
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const uploadInfo = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploadInfo;
@@ -90,6 +106,23 @@ describe('video-upload', () => {
expect((uploadInfo[1] as any).fileInfo.type.type).toBe(1); // pic (thumb)
});
it('[#145] group video carries real width/height; c2c stays 0/0', async () => {
// A real QQ group video's MsgInfo has real dimensions (e.g. 296x640);
// sending 0x0 makes QQ-NT receivers render 文件已过期 even though the
// resource is fresh (verified on tempserver: 0x0 → expired, real dims →
// renders). c2c is left at 0 — the server rejects non-zero dims there.
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
const groupInfo = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploadInfo;
expect((groupInfo[0] as any).fileInfo.width).toBe(320); // FINGERPRINT.width
expect((groupInfo[0] as any).fileInfo.height).toBe(240); // FINGERPRINT.height
vi.mocked(pipeline.runNtv2Upload).mockClear();
await uploadVideoMsgInfo({} as any, false, 'recipient-uid', FINGERPRINT);
const c2cInfo = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploadInfo;
expect((c2cInfo[0] as any).fileInfo.width).toBe(0);
expect((c2cInfo[0] as any).fileInfo.height).toBe(0);
});
it('main video carries the real `time` (duration in seconds) — regression: was 0', async () => {
// NTV2 server bakes the `time` field into the resulting MsgInfo
// bytes that ride along as `commonElem.pbElem`; the receiver
@@ -131,3 +164,69 @@ describe('video-upload', () => {
expect(args[1]).toBeUndefined();
});
});
describe('video-upload — streaming path (real on-disk source)', () => {
beforeEach(() => { vi.mocked(pipeline.runNtv2Upload).mockClear(); });
it('stages + stream-hashes the source and PUTs via fileSource, never buffering bytes', async () => {
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-vidstream-'));
const file = path.join(dir, 'clip.mp4');
const data = Buffer.alloc(3 * 1024 * 1024 + 77); // multi-1MiB-block + tail
for (let i = 0; i < data.length; i++) data[i] = (i * 37 + 5) & 0xff;
fs.writeFileSync(file, data);
try {
const bridge = { identity: { uin: '10001' } } as any;
await uploadVideoMsgInfo(bridge, true, 12345, { type: 'video', url: pathToFileURL(file).href } as any);
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls.at(-1)![0];
const main = args.uploads[0]!;
// Main file streams from disk — fileSource set, no in-memory bytes.
expect(main.fileSource).toBeDefined();
expect(main.fileSource!.fileSize).toBe(data.length);
expect(main.bytes.length).toBe(0);
// The OIDB fileInfo carries the STREAMED hashes/size — must equal the
// buffered hash of the same bytes (byte-identical guarantee end-to-end).
const fi = (args.uploadInfo[0] as any).fileInfo;
expect(fi.fileSize).toBe(data.length);
expect(fi.fileHash).toBe(computeHashes(data).md5Hex);
expect(fi.fileSha1).toBe(computeHashes(data).sha1Hex);
// The staged temp is a copy/hardlink under the stage dir (NOT the source)
// and is cleaned up after the send.
expect(main.fileSource!.filePath).not.toBe(file);
expect(fs.existsSync(main.fileSource!.filePath)).toBe(false);
} finally {
await fsp.rm(dir, { recursive: true, force: true });
}
});
it('cleans up the staged temp even when the upload throws', async () => {
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-vidfail-'));
const file = path.join(dir, 'clip.mp4');
fs.writeFileSync(file, Buffer.alloc(2048, 7));
try {
vi.mocked(pipeline.runNtv2Upload).mockRejectedValueOnce(new Error('upload boom'));
await expect(
uploadVideoMsgInfo({ identity: { uin: '1' } } as any, true, 12345, { type: 'video', url: pathToFileURL(file).href } as any),
).rejects.toThrow(/upload boom/);
// The staged temp created in loadVideo must be removed by the finally.
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls.at(-1)![0];
const stagedPath = args.uploads[0]!.fileSource!.filePath;
expect(fs.existsSync(stagedPath)).toBe(false);
} finally {
await fsp.rm(dir, { recursive: true, force: true });
}
});
it('rejects an empty video source (0 bytes)', async () => {
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-vidempty-'));
const file = path.join(dir, 'empty.mp4');
fs.writeFileSync(file, new Uint8Array(0));
try {
await expect(
uploadVideoMsgInfo({ identity: { uin: '1' } } as any, true, 12345, { type: 'video', url: pathToFileURL(file).href } as any),
).rejects.toThrow(/empty/);
} finally {
await fsp.rm(dir, { recursive: true, force: true });
}
});
});

View File

@@ -17,6 +17,7 @@ vi.mock('@snowluma/protocol/highway', () => ({
fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })),
uploadHighwayHttp: vi.fn(async () => undefined),
buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])),
BufferChunkSource: class BufferChunkSource { constructor(readonly bytes: Uint8Array) {} },
PRIVATE_IMAGE_CMD_ID: 1003,
GROUP_IMAGE_CMD_ID: 1004,
}));

View File

@@ -0,0 +1,62 @@
import { describe, it, expect, vi } from 'vitest';
import { sseResponse } from '../src/webui/sse-response';
// A minimal hono-Context stand-in: sseResponse only reads c.req.raw.signal.
function fakeCtx(signal: AbortSignal): Parameters<typeof sseResponse>[0] {
return { req: { raw: { signal } } } as unknown as Parameters<typeof sseResponse>[0];
}
describe('sseResponse', () => {
it('returns an event-stream Response with the SSE headers', () => {
const ac = new AbortController();
const res = sseResponse(fakeCtx(ac.signal), () => { /* no-op */ });
expect(res.headers.get('Content-Type')).toBe('text/event-stream');
expect(res.headers.get('Cache-Control')).toBe('no-cache');
expect(res.headers.get('Connection')).toBe('keep-alive');
ac.abort(); // clear the heartbeat timer
});
it('ch.send frames JSON as `data: …` and ch.raw enqueues verbatim', async () => {
const ac = new AbortController();
const res = sseResponse(fakeCtx(ac.signal), (ch) => {
ch.send({ type: 'ready' });
ch.raw(ch.encode(': heartbeat\n\n'));
});
const reader = res.body!.getReader();
const dec = new TextDecoder();
expect(dec.decode((await reader.read()).value)).toBe('data: {"type":"ready"}\n\n');
expect(dec.decode((await reader.read()).value)).toBe(': heartbeat\n\n');
ac.abort();
await reader.cancel();
});
it('abort runs registered cleanups exactly once, flips isClosed, and closes the stream', async () => {
const ac = new AbortController();
const cleanupA = vi.fn();
const cleanupB = vi.fn();
let channel!: Parameters<Parameters<typeof sseResponse>[1]>[0];
const res = sseResponse(fakeCtx(ac.signal), (ch) => {
channel = ch;
ch.onClose(cleanupA);
ch.onClose(cleanupB);
});
expect(channel.isClosed()).toBe(false);
ac.abort();
expect(cleanupA).toHaveBeenCalledTimes(1);
expect(cleanupB).toHaveBeenCalledTimes(1);
expect(channel.isClosed()).toBe(true);
const r = await res.body!.getReader().read();
expect(r.done).toBe(true);
});
it('send after teardown is a silent no-op', () => {
const ac = new AbortController();
let channel!: Parameters<Parameters<typeof sseResponse>[1]>[0];
sseResponse(fakeCtx(ac.signal), (ch) => { channel = ch; });
ac.abort();
expect(() => channel.send({ x: 1 })).not.toThrow();
expect(channel.isClosed()).toBe(true);
});
});

View File

@@ -0,0 +1,168 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { StateBus } from '../src/webui/state-bus';
import { startConnectionDiffLoop } from '../src/webui/connection-diff-loop';
describe('startConnectionDiffLoop', () => {
beforeEach(() => { vi.useFakeTimers(); });
afterEach(() => { vi.useRealTimers(); });
it('does NOT publish when the snapshot is stable tick after tick', () => {
const bus = new StateBus();
const seen: string[] = [];
bus.subscribe((r) => seen.push(r));
const handle = startConnectionDiffLoop({
bus,
getSnapshot: () => [{ uin: '12345', nickname: 'me', adapters: [] }],
intervalMs: 500,
});
vi.advanceTimersByTime(2_000); // 4 ticks
expect(seen).toEqual([]);
handle.dispose();
});
it('first tick baselines the snapshot (no publish); only the second tick with a different value publishes', () => {
const bus = new StateBus();
const seen: string[] = [];
bus.subscribe((r) => seen.push(r));
let snap = [{ uin: '12345', nickname: 'me', adapters: [{ kind: 'http', status: 'listening' }] }];
const handle = startConnectionDiffLoop({
bus,
getSnapshot: () => snap,
intervalMs: 500,
});
vi.advanceTimersByTime(500); // first observation — baseline, no publish
expect(seen).toEqual([]);
snap = [{ uin: '12345', nickname: 'me', adapters: [{ kind: 'http', status: 'connected' }] }];
vi.advanceTimersByTime(500);
expect(seen).toEqual(['connections']);
// Next tick: stable again → no extra publish.
vi.advanceTimersByTime(500);
expect(seen).toEqual(['connections']);
handle.dispose();
});
it('publishes once per CHANGE, not once per tick the snapshot differs from initial', () => {
const bus = new StateBus();
const seen: string[] = [];
bus.subscribe((r) => seen.push(r));
const versions = [
[{ uin: '1', nickname: 'a', adapters: [] }], // baseline (no publish on first observation)
[{ uin: '1', nickname: 'a', adapters: [{ kind: 'http', status: 'listening' }] }],
[{ uin: '1', nickname: 'a', adapters: [{ kind: 'http', status: 'listening' }] }],
[{ uin: '1', nickname: 'a', adapters: [{ kind: 'http', status: 'connected' }] }],
];
let i = 0;
const handle = startConnectionDiffLoop({
bus,
getSnapshot: () => versions[Math.min(i, versions.length - 1)] ?? [],
intervalMs: 500,
});
vi.advanceTimersByTime(500); // i=0 baseline
i = 1; vi.advanceTimersByTime(500); // change #1
i = 2; vi.advanceTimersByTime(500); // stable vs i=1
i = 3; vi.advanceTimersByTime(500); // change #2
expect(seen).toEqual(['connections', 'connections']);
handle.dispose();
});
it('dispose() stops further ticks, no publish even after a change', () => {
const bus = new StateBus();
const seen: string[] = [];
bus.subscribe((r) => seen.push(r));
let snap: object[] = [];
const handle = startConnectionDiffLoop({
bus,
getSnapshot: () => snap,
intervalMs: 500,
});
handle.dispose();
snap = [{ uin: '1', nickname: 'a', adapters: [] }];
vi.advanceTimersByTime(5_000);
expect(seen).toEqual([]);
});
it('pickComparable() strips volatile fields so detail-only changes do NOT publish', () => {
const bus = new StateBus();
const seen: string[] = [];
bus.subscribe((r) => seen.push(r));
// Reproduces the real-world bug: HttpPostAdapter.describeStatus()
// embeds HH:MM:SS in `detail`; every webhook delivery rotates that
// string every second. WITHOUT pickComparable, the loop would publish
// every tick under any active webhook. WITH it (stripping `detail`),
// only level changes publish.
let snap = [{ uin: '1', adapters: [{ kind: 'httpClient', status: 'ok', detail: '上次推送 14:00:00' }] }];
const handle = startConnectionDiffLoop({
bus,
getSnapshot: () => snap,
pickComparable: (s) => {
if (!Array.isArray(s)) return s;
return (s as Array<{ uin: string; adapters?: unknown[] }>).map((acc) => ({
uin: acc.uin,
adapters: Array.isArray(acc.adapters)
? acc.adapters.map((a: unknown) => {
const o = a as { name?: string; kind?: string; status?: string };
return { name: o.name, kind: o.kind, status: o.status };
})
: acc.adapters,
}));
},
intervalMs: 500,
});
vi.advanceTimersByTime(500); // baseline
expect(seen).toEqual([]);
// detail changes every second; raw JSON differs each tick.
for (let t = 1; t <= 10; t++) {
snap = [{ uin: '1', adapters: [{ kind: 'httpClient', status: 'ok', detail: `上次推送 14:00:${String(t).padStart(2, '0')}` }] }];
vi.advanceTimersByTime(500);
}
expect(seen).toEqual([]); // ZERO publishes — detail is not comparable
// Now a REAL state change (status level) → publish exactly once.
snap = [{ uin: '1', adapters: [{ kind: 'httpClient', status: 'down', detail: '连接失败' }] }];
vi.advanceTimersByTime(500);
expect(seen).toEqual(['connections']);
handle.dispose();
});
it('a throwing pickComparable() is isolated — loop keeps ticking, no publish', () => {
const bus = new StateBus();
const seen: string[] = [];
bus.subscribe((r) => seen.push(r));
const handle = startConnectionDiffLoop({
bus,
getSnapshot: () => [{ uin: '1' }],
pickComparable: () => { throw new Error('projector boom'); },
intervalMs: 500,
});
vi.advanceTimersByTime(2_000);
expect(seen).toEqual([]);
handle.dispose();
});
it('survives a throwing snapshot() — keeps trying on the next tick', () => {
const bus = new StateBus();
const seen: string[] = [];
bus.subscribe((r) => seen.push(r));
let mode: 'throw' | 'stable' | 'changed' = 'throw';
const handle = startConnectionDiffLoop({
bus,
getSnapshot: () => {
if (mode === 'throw') throw new Error('getConnectionStatuses failed');
if (mode === 'stable') return [{ uin: '1', adapters: [] }];
return [{ uin: '1', adapters: [{ kind: 'ws', status: 'connected' }] }];
},
intervalMs: 500,
});
vi.advanceTimersByTime(500); // throws — skipped, no publish
expect(seen).toEqual([]);
mode = 'stable';
vi.advanceTimersByTime(500); // first SUCCESSFUL read — baseline, no publish
expect(seen).toEqual([]);
mode = 'changed';
vi.advanceTimersByTime(500); // real change → publish
expect(seen).toEqual(['connections']);
handle.dispose();
});
});

View File

@@ -0,0 +1,151 @@
import { afterAll, describe, expect, it } from 'vitest';
import { readdir, readFile, rm } from 'fs/promises';
import path from 'path';
import {
buildStreamInvokeResponse,
DEBUG_UPLOAD_DIR,
safeUploadName,
streamUploadToDisk,
uploadDestPath,
} from '../src/webui/debug-tools';
const written: string[] = [];
afterAll(async () => {
await Promise.all(written.map((p) => rm(p, { force: true }).catch(() => {})));
});
function streamOf(...chunks: Uint8Array[]): ReadableStream<Uint8Array> {
let i = 0;
return new ReadableStream<Uint8Array>({
pull(controller) {
if (i < chunks.length) controller.enqueue(chunks[i++]);
else controller.close();
},
});
}
async function readSse(res: Response): Promise<string[]> {
const text = await res.text();
return text.split('\n\n').filter((s) => s.startsWith('data: ')).map((s) => s.slice('data: '.length));
}
describe('safeUploadName', () => {
it('strips path traversal and separators to a bare basename', () => {
expect(safeUploadName('../../etc/passwd')).toBe('passwd');
expect(safeUploadName('/abs/secret.key')).toBe('secret.key');
expect(safeUploadName('a\\b\\c.png')).toBe('c.png');
expect(safeUploadName('..')).toBe('file'); // leading dots stripped → empty → fallback
expect(safeUploadName('...hidden')).toBe('hidden');
});
it('collapses exotic chars and falls back for empties', () => {
expect(safeUploadName('my pic!@#.jpg')).toBe('my_pic_.jpg');
expect(safeUploadName('')).toBe('file');
expect(safeUploadName(undefined)).toBe('file');
});
it('keeps the extension and caps length', () => {
const long = 'x'.repeat(500) + '.mp4';
const out = safeUploadName(long);
expect(out.length).toBeLessThanOrEqual(120);
expect(out.startsWith('x')).toBe(true);
});
});
describe('uploadDestPath', () => {
it('produces a unique path inside the upload dir', () => {
const a = uploadDestPath('pic.png');
const b = uploadDestPath('pic.png');
expect(a).not.toBe(b); // random id prefix
expect(path.dirname(a)).toBe(DEBUG_UPLOAD_DIR);
expect(a.endsWith('__pic.png')).toBe(true);
const rel = path.relative(DEBUG_UPLOAD_DIR, a);
expect(rel.startsWith('..')).toBe(false);
expect(path.isAbsolute(rel)).toBe(false);
});
});
describe('streamUploadToDisk', () => {
it('streams bytes to disk and reports the size', async () => {
const data = new TextEncoder().encode('hello debug upload');
const res = await streamUploadToDisk(streamOf(data.slice(0, 5), data.slice(5)), 'note.txt');
written.push(res.path);
expect(res.size).toBe(data.byteLength);
expect(path.dirname(res.path)).toBe(DEBUG_UPLOAD_DIR);
expect(await readFile(res.path, 'utf8')).toBe('hello debug upload');
});
it('rejects and removes the partial file when the cap is exceeded', async () => {
const big = new Uint8Array(64);
await expect(
streamUploadToDisk(streamOf(big, big), 'big.bin', { maxBytes: 100 }),
).rejects.toThrow(/大小上限/);
// the partial must not survive — no leftover `__big.bin` in the dir
const names = await readdir(DEBUG_UPLOAD_DIR).catch(() => [] as string[]);
expect(names.filter((n) => n.endsWith('__big.bin'))).toEqual([]);
});
it('rejects an empty body', async () => {
await expect(streamUploadToDisk(null, 'x')).rejects.toThrow(/empty/);
await expect(streamUploadToDisk(streamOf(), 'x')).rejects.toThrow(/empty/);
});
it('propagates a mid-transfer source error and removes the partial', async () => {
const failing = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new TextEncoder().encode('partial-bytes'));
controller.error(new Error('source aborted'));
},
});
await expect(streamUploadToDisk(failing, 'oops.bin')).rejects.toThrow(/source aborted/);
const names = await readdir(DEBUG_UPLOAD_DIR).catch(() => [] as string[]);
expect(names.filter((n) => n.endsWith('__oops.bin'))).toEqual([]);
});
});
describe('buildStreamInvokeResponse', () => {
const noDelay = async () => {};
it('relays each emitted frame as one SSE event, in order', async () => {
const ac = new AbortController();
const driver = async (_rq: string, emit: (j: string) => Promise<void>) => {
await emit(JSON.stringify({ data: { type: 'stream', i: 1 } }));
await emit(JSON.stringify({ data: { type: 'stream', i: 2 } }));
await emit(JSON.stringify({ status: 'ok', data: { type: 'response' } }));
};
const res = buildStreamInvokeResponse(driver, '{"action":"x"}', ac.signal, noDelay);
const frames = (await readSse(res)).map((s) => JSON.parse(s));
expect(frames).toHaveLength(3);
expect(frames[0].data.i).toBe(1);
expect(frames[2].data.type).toBe('response');
});
it('turns a driver error into a terminal failed frame', async () => {
const ac = new AbortController();
const driver = async (_rq: string, emit: (j: string) => Promise<void>) => {
await emit(JSON.stringify({ data: { type: 'stream' } }));
throw new Error('disk exploded');
};
const res = buildStreamInvokeResponse(driver, '{}', ac.signal, noDelay);
const frames = (await readSse(res)).map((s) => JSON.parse(s));
expect(frames).toHaveLength(2);
expect(frames[1].status).toBe('failed');
expect(frames[1].message).toMatch(/disk exploded/);
});
it('passes the raw request through to the driver', async () => {
const ac = new AbortController();
let seen = '';
const driver = async (rq: string, emit: (j: string) => Promise<void>) => {
seen = rq;
await emit('{"data":{"type":"response"}}');
};
const res = buildStreamInvokeResponse(driver, '{"action":"test_download_stream"}', ac.signal, noDelay);
await readSse(res);
expect(seen).toBe('{"action":"test_download_stream"}');
});
it('exposes an SSE content-type', () => {
const ac = new AbortController();
const res = buildStreamInvokeResponse(async () => {}, '{}', ac.signal, noDelay);
expect(res.headers.get('Content-Type')).toBe('text/event-stream');
});
});

View File

@@ -0,0 +1,24 @@
import { describe, expect, it } from 'vitest';
import { SSE_TOKEN_QUERY_PATHS } from '../src/webui/server';
// Regression lock for a class of bug that has bricked an SSE endpoint
// before: EventSource cannot set Authorization headers, so every SSE
// path MUST appear in this allowlist or the auth middleware computes
// `queryToken = ''` and 401s every connect. A missing entry is silent —
// the only symptom is "live updates don't work, refresh fixes it" — so
// keep this list short and verified.
describe('SSE_TOKEN_QUERY_PATHS', () => {
it('contains every SSE stream the WebUI subscribes to', () => {
expect(SSE_TOKEN_QUERY_PATHS.has('/api/logs/stream')).toBe(true);
expect(SSE_TOKEN_QUERY_PATHS.has('/api/debug/stream')).toBe(true);
expect(SSE_TOKEN_QUERY_PATHS.has('/api/state/stream')).toBe(true);
});
it('does NOT carry any non-stream endpoint — token-via-query is reserved for SSE', () => {
// The auth middleware accepts `?token=...` for these paths only; any
// bearer-only endpoint listed here would leak tokens via access logs.
for (const path of SSE_TOKEN_QUERY_PATHS) {
expect(path.endsWith('/stream')).toBe(true);
}
});
});

View File

@@ -0,0 +1,119 @@
import { describe, expect, it, vi } from 'vitest';
import { StateBus, type StateResource } from '../src/webui/state-bus';
describe('StateBus', () => {
it('delivers a publish to a single subscriber with the resource kind', () => {
const bus = new StateBus();
const seen: StateResource[] = [];
bus.subscribe((r) => seen.push(r));
bus.publish('processes');
bus.publish('qq-list');
bus.publish('connections');
expect(seen).toEqual(['processes', 'qq-list', 'connections']);
});
it('fans out one publish to every subscriber', () => {
const bus = new StateBus();
const a = vi.fn();
const b = vi.fn();
const c = vi.fn();
bus.subscribe(a);
bus.subscribe(b);
bus.subscribe(c);
bus.publish('processes');
expect(a).toHaveBeenCalledExactlyOnceWith('processes');
expect(b).toHaveBeenCalledExactlyOnceWith('processes');
expect(c).toHaveBeenCalledExactlyOnceWith('processes');
});
it('returns an unsubscribe handle that stops future emits without touching the others', () => {
const bus = new StateBus();
const a = vi.fn();
const b = vi.fn();
const unsubA = bus.subscribe(a);
bus.subscribe(b);
bus.publish('processes');
unsubA();
bus.publish('qq-list');
expect(a).toHaveBeenCalledExactlyOnceWith('processes');
expect(b).toHaveBeenCalledTimes(2);
expect(b.mock.calls).toEqual([['processes'], ['qq-list']]);
});
it('is idempotent on double-unsubscribe', () => {
const bus = new StateBus();
const a = vi.fn();
const unsubA = bus.subscribe(a);
unsubA();
unsubA();
bus.publish('processes');
expect(a).not.toHaveBeenCalled();
});
it('isolates subscriber exceptions — one throwing listener does not block the others or future publishes', () => {
const bus = new StateBus();
const before = vi.fn();
const thrower = vi.fn(() => { throw new Error('boom'); });
const after = vi.fn();
bus.subscribe(before);
bus.subscribe(thrower);
bus.subscribe(after);
expect(() => bus.publish('processes')).not.toThrow();
expect(before).toHaveBeenCalledExactlyOnceWith('processes');
expect(after).toHaveBeenCalledExactlyOnceWith('processes');
bus.publish('qq-list');
expect(before).toHaveBeenCalledTimes(2);
expect(after).toHaveBeenCalledTimes(2);
});
it('dispose() drops every subscriber and silently swallows further publishes', () => {
const bus = new StateBus();
const a = vi.fn();
bus.subscribe(a);
bus.dispose();
bus.publish('processes');
expect(a).not.toHaveBeenCalled();
});
it('a subscriber that subscribes a second time inside its own callback observes the FOLLOWING publish, not this one', () => {
const bus = new StateBus();
const second = vi.fn();
const first = vi.fn(() => { bus.subscribe(second); });
bus.subscribe(first);
bus.publish('processes');
expect(first).toHaveBeenCalledExactlyOnceWith('processes');
// The just-added subscriber must not receive the in-flight publish — that
// would surprise SSE handlers that subscribe lazily during an emit fan-out.
expect(second).not.toHaveBeenCalled();
bus.publish('qq-list');
expect(second).toHaveBeenCalledExactlyOnceWith('qq-list');
});
it('a subscriber that unsubscribes a peer mid-emit lets the survivor still receive THIS publish', () => {
const bus = new StateBus();
const order: string[] = [];
let unsubB!: () => void;
bus.subscribe(() => { order.push('a'); unsubB(); });
unsubB = bus.subscribe(() => { order.push('b'); });
bus.subscribe(() => { order.push('c'); });
bus.publish('processes');
// Snapshot semantics: the fan-out iterates a copy, so peer-unsubscribe
// does not skip any other listener that was attached when publish started.
expect(order).toEqual(['a', 'b', 'c']);
order.length = 0;
bus.publish('qq-list');
expect(order).toEqual(['a', 'c']);
});
});

View File

@@ -0,0 +1,249 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { StateBus, type StateResource } from '../src/webui/state-bus';
import { bindStateStream } from '../src/webui/state-stream';
interface CapturedFrame {
resource: StateResource;
data: unknown;
}
function makeSnapshotFn(table: Partial<Record<StateResource, unknown>>) {
return vi.fn(async (resource: StateResource): Promise<unknown> => table[resource]);
}
describe('bindStateStream', () => {
beforeEach(() => { vi.useFakeTimers(); });
afterEach(() => { vi.useRealTimers(); });
it('sendAllInitial emits one frame per resource with the snapshot data', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
const snapshot = makeSnapshotFn({
'processes': [{ pid: 4242, name: 'qq', status: 'available' }],
'qq-list': [{ uin: '12345', nickname: 'me' }],
'connections': [{ uin: '12345', nickname: 'me', adapters: [] }],
});
const handle = bindStateStream({
bus,
snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
await handle.sendAllInitial();
expect(snapshot).toHaveBeenCalledTimes(3);
expect(new Set(sent.map((f) => f.resource))).toEqual(new Set(['processes', 'qq-list', 'connections']));
const procFrame = sent.find((f) => f.resource === 'processes');
expect(procFrame?.data).toEqual([{ pid: 4242, name: 'qq', status: 'available' }]);
handle.dispose();
});
it('a single bus publish reaches send() exactly once after debounceMs', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
const snapshot = makeSnapshotFn({ 'processes': [{ pid: 9999 }] });
const handle = bindStateStream({
bus,
snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
bus.publish('processes');
expect(sent).toHaveLength(0); // still debounced
await vi.advanceTimersByTimeAsync(49);
expect(sent).toHaveLength(0);
await vi.advanceTimersByTimeAsync(2);
expect(sent).toEqual([{ resource: 'processes', data: [{ pid: 9999 }] }]);
handle.dispose();
});
it('coalesces a burst of publishes for the SAME resource into one send', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
const snapshot = makeSnapshotFn({ 'processes': 'fresh' });
const handle = bindStateStream({
bus, snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
for (let i = 0; i < 20; i++) bus.publish('processes');
await vi.advanceTimersByTimeAsync(51);
expect(sent).toEqual([{ resource: 'processes', data: 'fresh' }]);
// Snapshot was only invoked once for the whole burst.
expect(snapshot).toHaveBeenCalledExactlyOnceWith('processes');
handle.dispose();
});
it('each resource has its own independent debounce timer', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
const snapshot = makeSnapshotFn({
'processes': 'p',
'qq-list': 'q',
'connections': 'c',
});
const handle = bindStateStream({
bus, snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
bus.publish('processes');
await vi.advanceTimersByTimeAsync(30);
bus.publish('qq-list');
await vi.advanceTimersByTimeAsync(25); // processes fires at t=50 (5ms after this), qq-list pending till t=80
expect(sent.map((f) => f.resource)).toEqual(['processes']);
await vi.advanceTimersByTimeAsync(30);
expect(sent.map((f) => f.resource)).toEqual(['processes', 'qq-list']);
bus.publish('connections');
await vi.advanceTimersByTimeAsync(51);
expect(sent.map((f) => f.resource)).toEqual(['processes', 'qq-list', 'connections']);
handle.dispose();
});
it('dispose() stops further sends, both pending and future', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
const snapshot = makeSnapshotFn({ 'processes': 'x' });
const handle = bindStateStream({
bus, snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
bus.publish('processes');
handle.dispose();
await vi.advanceTimersByTimeAsync(200);
expect(sent).toEqual([]);
// Subsequent publishes are dead too.
bus.publish('processes');
await vi.advanceTimersByTimeAsync(200);
expect(sent).toEqual([]);
});
it('snapshot() rejection is isolated — the failed resource is skipped and others keep flowing', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
const snapshot = vi.fn(async (resource: StateResource): Promise<unknown> => {
if (resource === 'processes') throw new Error('listProcesses failed');
if (resource === 'qq-list') return [{ uin: '1' }];
return [];
});
const handle = bindStateStream({
bus, snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
bus.publish('processes');
bus.publish('qq-list');
await vi.advanceTimersByTimeAsync(60);
// qq-list went through; processes didn't (snapshot threw).
expect(sent.find((f) => f.resource === 'qq-list')?.data).toEqual([{ uin: '1' }]);
expect(sent.find((f) => f.resource === 'processes')).toBeUndefined();
handle.dispose();
});
it('serialises overlapping flushes for the same resource — the LAST sent frame reflects the LATEST publish (no stale overwrite)', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
// Variable-latency snapshot: 1st call sleeps 200ms (slow), 2nd call
// sleeps 10ms (fast). Without single-flight, the second publish would
// race-overlap and send BEFORE the first, leaving the client's last
// observed frame as the older snapshot.
let call = 0;
const versions = ['snap-T0', 'snap-T60'];
const snapshot = vi.fn(async (_resource: StateResource): Promise<unknown> => {
const i = call++;
const sleep = i === 0 ? 200 : 10;
await new Promise<void>((r) => setTimeout(r, sleep));
return versions[i] ?? `snap-#${i}`;
});
const handle = bindStateStream({
bus, snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
bus.publish('processes'); // schedules timer1 → fires at 50, snapshot A (200ms)
await vi.advanceTimersByTimeAsync(60);
bus.publish('processes'); // arrives WHILE flush A is mid-snapshot
await vi.advanceTimersByTimeAsync(60); // hits 120: timer2 should have fired, flush B observed_after A completes
await vi.advanceTimersByTimeAsync(300); // settle everything
// Exactly two frames; the LAST one must reflect the most recent snapshot.
expect(sent).toHaveLength(2);
expect(sent[sent.length - 1]).toEqual({ resource: 'processes', data: 'snap-T60' });
// For single-flight: snapshot is called once per flush (no overlap),
// so the SECOND snapshot read sees the latest state.
expect(call).toBe(2);
handle.dispose();
});
it('multiple publishes during an in-flight flush coalesce into ONE follow-up flush, not N', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
let call = 0;
const snapshot = vi.fn(async (_resource: StateResource): Promise<unknown> => {
call++;
await new Promise<void>((r) => setTimeout(r, 100));
return `snap-#${call}`;
});
const handle = bindStateStream({
bus, snapshot,
send: (f) => sent.push(f),
debounceMs: 50,
});
bus.publish('processes');
await vi.advanceTimersByTimeAsync(55);
// flush A in flight (100ms more). Send 5 publishes during the in-flight window.
for (let i = 0; i < 5; i++) bus.publish('processes');
await vi.advanceTimersByTimeAsync(200);
await vi.advanceTimersByTimeAsync(200);
// 1 initial flush + 1 coalesced follow-up = 2 frames, NOT 6.
expect(sent).toHaveLength(2);
expect(call).toBe(2);
handle.dispose();
});
it('send() throw is isolated — the next publish still reaches a healthy send()', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
let mode: 'throw' | 'ok' = 'throw';
const snapshot = makeSnapshotFn({ 'processes': 'x' });
const handle = bindStateStream({
bus, snapshot,
send: (f) => {
if (mode === 'throw') throw new Error('controller dead');
sent.push(f);
},
debounceMs: 50,
});
bus.publish('processes');
await vi.advanceTimersByTimeAsync(60);
expect(sent).toEqual([]);
mode = 'ok';
bus.publish('processes');
await vi.advanceTimersByTimeAsync(60);
expect(sent).toEqual([{ resource: 'processes', data: 'x' }]);
handle.dispose();
});
});

View File

@@ -0,0 +1,82 @@
import { describe, expect, it, vi } from 'vitest';
import { StateBus } from '../src/webui/state-bus';
import { createStateWiring } from '../src/webui/state-wiring';
import { BridgeManager } from '../src/bridge/manager';
describe('createStateWiring', () => {
it('provides a fresh StateBus and an onSessionsChanged that publishes "processes"', () => {
const wiring = createStateWiring();
expect(wiring.bus).toBeInstanceOf(StateBus);
const sub = vi.fn();
wiring.bus.subscribe(sub);
wiring.onSessionsChanged();
expect(sub).toHaveBeenCalledExactlyOnceWith('processes');
});
it('binds a BridgeManager so session-started publishes both "qq-list" and "connections"', () => {
const wiring = createStateWiring();
const bm = new BridgeManager();
wiring.bindBridgeManager(bm);
const seen: string[] = [];
wiring.bus.subscribe((r) => seen.push(r));
// Real onHookLogin path — fires the session-started listener internally
// exactly once (per uin).
bm.onHookLogin(4242, '12345', {} as never);
expect(seen).toEqual(['qq-list', 'connections']);
});
it('publishes "qq-list" + "connections" on session-closed', () => {
const wiring = createStateWiring();
const bm = new BridgeManager();
wiring.bindBridgeManager(bm);
bm.onHookLogin(4242, '12345', {} as never);
const sub = vi.fn();
wiring.bus.subscribe(sub);
bm.onPidDisconnected(4242);
// Order is qq-list first (account list shrinks) then connections
// (adapter status list shrinks). Two distinct resource invalidations.
expect(sub).toHaveBeenCalledTimes(2);
expect(sub).toHaveBeenNthCalledWith(1, 'qq-list');
expect(sub).toHaveBeenNthCalledWith(2, 'connections');
});
it('dispose() unwires onSessionsChanged + BridgeManager listeners (no further publishes)', () => {
const wiring = createStateWiring();
const bm = new BridgeManager();
wiring.bindBridgeManager(bm);
const sub = vi.fn();
wiring.bus.subscribe(sub);
wiring.dispose();
// onSessionsChanged becomes a no-op.
wiring.onSessionsChanged();
expect(sub).not.toHaveBeenCalled();
// BridgeManager listener fires nothing into a disposed bus.
bm.onHookLogin(4242, '12345', {} as never);
expect(sub).not.toHaveBeenCalled();
});
it('survives a BridgeManager listener throw — the OTHER listeners on the same BridgeManager keep working', () => {
const wiring = createStateWiring();
const bm = new BridgeManager();
wiring.bindBridgeManager(bm);
// A peer subscriber (e.g. OneBotManager) added AFTER state-wiring throws.
const peer = vi.fn(() => { throw new Error('peer down'); });
bm.addSessionStartedListener(peer);
const sub = vi.fn();
wiring.bus.subscribe(sub);
expect(() => bm.onHookLogin(4242, '12345', {} as never)).not.toThrow();
// The state-wiring listener still ran (BridgeManager isolates exceptions
// per listener).
expect(sub).toHaveBeenCalledWith('qq-list');
expect(sub).toHaveBeenCalledWith('connections');
});
});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.10.0",
"version": "1.11.3",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",

View File

@@ -29,4 +29,11 @@ it('generates src/generated/catalog.ts from the live action specs', () => {
const dir = new URL('../src/generated/', import.meta.url);
mkdirSync(dir, { recursive: true });
writeFileSync(new URL('../src/generated/catalog.ts', import.meta.url), body);
// Plain-JSON twin of the catalog, consumed by the docs site (SnowLumaDocs)
// via the sync-docs-catalog workflow. Same data as catalog.ts.
writeFileSync(
new URL('../src/generated/catalog.json', import.meta.url),
JSON.stringify({ actions, categories }, null, 2) + '\n',
);
});

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -11,6 +11,11 @@ export interface CatalogParam {
default?: unknown;
desc?: string;
values?: ReadonlyArray<string | number>;
/** Semantic role (group_id / user_id / member_id / image / face_id / …),
* orthogonal to `type`; drives smart-widget selection in the WebUI console.
* Kept as a loose string here so the package stays decoupled from onebot's
* FieldRole union. */
role?: string;
/** JSON Schema fragment for this single field. */
schema?: Record<string, unknown>;
}
@@ -21,10 +26,15 @@ export interface CatalogAction {
category?: string;
summary?: string;
returns?: string;
/** JSON Schema for the action's `data` payload (absent when undocumented). */
returnsSchema?: Record<string, unknown>;
/** True only for pure data-fetch actions (no side effects). Drives the
* read/write tool routing: read-only → query_action, else → invoke_action.
* Classified at the source spec by what the action's `run` actually does. */
readOnly: boolean;
/** True for Stream API actions (multi-frame transport). Absent ⇒ ordinary
* single-response action. */
stream?: boolean;
params: CatalogParam[];
/** Cross-field invariants, e.g. "exactly one of: message_id | (group_id+user_id)". */
invariants: string[];

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.10.0",
"version": "1.11.3",
"private": true,
"type": "module",
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
@@ -40,6 +40,10 @@
"types": "./src/config.ts",
"default": "./src/config.ts"
},
"./global-config": {
"types": "./src/global-config.ts",
"default": "./src/global-config.ts"
},
"./types": {
"types": "./src/types.ts",
"default": "./src/types.ts"

View File

@@ -12,44 +12,19 @@
// deferred product decision; this module produces format-agnostic data plus a
// Markdown default. Point any renderer at `collectActionDocs()`.
import type { ActionDoc, ActionSpec, Field } from './action-kit';
import { actions as infoActions } from './actions/info';
import { actions as messageActions } from './actions/message';
import { actions as friendActions } from './actions/friend';
import { actions as groupInfoActions } from './actions/group-info';
import { actions as groupAdminActions } from './actions/group-admin';
import { actions as groupFileActions } from './actions/group-file';
import { actions as requestActions } from './actions/request';
import { actions as extendedActions } from './actions/extended';
import { actions as groupAlbumActions } from './actions/group-album';
import { actions as qzoneActions } from './actions/qzone';
type AnySpec = ActionSpec<Record<string, Field<unknown>>>;
// Source file = domain category. Each doc is tagged so the MCP / UI can group.
const GROUPS: ReadonlyArray<{ category: string; specs: readonly AnySpec[] }> = [
{ category: '信息', specs: infoActions },
{ category: '消息', specs: messageActions },
{ category: '好友', specs: friendActions },
{ category: '群信息', specs: groupInfoActions },
{ category: '群管理', specs: groupAdminActions },
{ category: '群文件', specs: groupFileActions },
{ category: '请求', specs: requestActions },
{ category: '扩展', specs: extendedActions },
{ category: '群相册', specs: groupAlbumActions },
{ category: '空间', specs: qzoneActions },
];
import type { ActionDoc } from './action-kit';
import { ACTION_GROUPS } from './actions';
/** Every declarative action's doc (with category), sorted by name. */
export function collectActionDocs(): ActionDoc[] {
return GROUPS
.flatMap(({ category, specs }) => specs.map((s) => ({ ...s.describe(), category })))
return ACTION_GROUPS
.flatMap(({ category, actions }) => actions.map((s) => ({ ...s.describe(), category })))
.sort((a, b) => a.name.localeCompare(b.name));
}
/** Distinct categories with action counts. */
export function collectCategories(): Array<{ category: string; count: number }> {
return GROUPS.map(({ category, specs }) => ({ category, count: specs.length }));
return ACTION_GROUPS.map(({ category, actions }) => ({ category, count: actions.length }));
}
function paramRow(p: ActionDoc['params'][number]): string {

View File

@@ -21,6 +21,7 @@
import { RETCODE, failedResponse } from './types';
import type { ApiResponse, JsonObject, JsonValue } from './types';
import type { ApiActionContext, ApiHandler } from './api-handler';
import { type StreamSink, NOOP_SINK } from './streaming';
// ─────────────────────────── result currency ───────────────────────────
@@ -43,12 +44,33 @@ type Raw = JsonValue | typeof MISSING;
* them into an action's `inputSchema` (consumed by docs / the MCP). */
export type JsonSchema = Record<string, unknown>;
/** Semantic role of a param, orthogonal to `type` (which governs coercion).
* Two `uint` fields `group_id` and `user_id` coerce identically but mean
* different things — `role` is what a UI keys its picker/widget off of.
* Closed set: consumers (the WebUI debug console) switch on it exhaustively
* and fall back to the plain typed control for anything unrecognised. */
export type FieldRole =
| 'group_id'
| 'user_id'
| 'member_id' // a group member's uin — its picker depends on a sibling group_id
| 'message_id'
| 'file_id'
| 'file'
| 'image'
| 'record'
| 'video'
| 'duration'
| 'timestamp'
| 'face_id';
export interface FieldDoc {
type: string;
required: boolean;
default?: JsonValue;
desc?: string;
values?: readonly (string | number)[];
/** Semantic role driving UI widget selection; orthogonal to `type`. */
role?: FieldRole;
/** JSON Schema fragment for this field's value (constraints only; presence
* and default are applied at the object level by `describe()`). */
schema?: JsonSchema;
@@ -64,6 +86,10 @@ export interface Field<T> {
* numeric field is an error, not a silent fallback). */
default(value: T): Field<T>;
describe(text: string): Field<T>;
/** Stamp a semantic role (escape hatch for params whose name lies, or to
* override a preset). Most call sites use the `f.groupId()`-style semantic
* constructors instead. */
role(role: FieldRole): Field<T>;
/** Complete JSON Schema for this field's value (constraints + description +
* default). Object-level required-ness is handled by `describe()`. */
toJsonSchema(): JsonSchema;
@@ -103,10 +129,15 @@ class FieldImpl<T> implements Field<T> {
return new FieldImpl<T>(this.core, { ...this.doc, desc: text });
}
role(role: FieldRole): Field<T> {
return new FieldImpl<T>(this.core, { ...this.doc, role });
}
toJsonSchema(): JsonSchema {
const out: JsonSchema = { ...(this.doc.schema ?? {}) };
if (this.doc.desc) out.description = this.doc.desc;
if (this.doc.default !== undefined) out.default = this.doc.default;
if (this.doc.role) out['x-role'] = this.doc.role;
return out;
}
}
@@ -147,6 +178,21 @@ function strSchema(opts: StrOpts): JsonSchema {
return s;
}
/** Coerce to string (numbers/booleans stringify; matches legacy `asString`),
* then apply emptiness / length bounds. Shared by `f.string()` and the
* string-valued semantic constructors. */
function stringCore(opts: StrOpts): Core<string> {
return (raw, field) => {
let s: string;
if (typeof raw === 'string') s = raw;
else if (typeof raw === 'number' || typeof raw === 'boolean') s = String(raw);
else return err(field, 'expected a string');
if (opts.allowEmpty === false && s === '') return err(field, 'must not be empty');
if (opts.maxLen !== undefined && s.length > opts.maxLen) return err(field, `must be <= ${opts.maxLen} chars`);
return ok(s);
};
}
function arrayField<E>(el: Field<E>, mustBeNonEmpty: boolean): Field<E[]> & { nonEmpty(): Field<E[]> } {
const core: Core<E[]> = (raw, field) => {
if (!Array.isArray(raw)) return err(field, 'expected an array');
@@ -180,7 +226,59 @@ export const f = {
/** OneBot message id: a non-zero integer. NEGATIVES ARE VALID (ids are a
* signed int32 hash) — do NOT use `uint()` for message_id. */
messageId(): Field<number> {
return new FieldImpl<number>(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true, schema: intSchema({ nonZero: true }) });
return new FieldImpl<number>(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true, role: 'message_id', schema: intSchema({ nonZero: true }) });
},
// ── Semantic constructors (role-stamped) ──
// Each wraps a coercion primitive and stamps a `role` so the WebUI debug
// console renders the right picker. The Agent backfill replaces a bare
// `f.uint()` named `group_id` with `f.groupId()`, etc. — purely additive to
// coercion (a groupId still coerces exactly like a uint).
/** Group number (uint) → group picker. */
groupId(): Field<number> {
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, role: 'group_id', schema: intSchema({ min: 1 }) });
},
/** Friend / stranger uin (uint) → friend picker. */
userId(): Field<number> {
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, role: 'user_id', schema: intSchema({ min: 1 }) });
},
/** Group member's uin (uint) → member picker, linked to a sibling group_id. */
memberId(): Field<number> {
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, role: 'member_id', schema: intSchema({ min: 1 }) });
},
/** Opaque file id (string) → file picker / history. */
fileId(): Field<string> {
return new FieldImpl<string>(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'file_id', schema: strSchema({ allowEmpty: false }) });
},
// Media sources reject '' (an empty path/URL is meaningless) — this matches
// the `f.string({ allowEmpty: false })` they replace during backfill, so the
// swap preserves the empty-string guard.
/** Local path / URL / base64 of a generic file → FileSource control. */
file(): Field<string> {
return new FieldImpl<string>(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'file', schema: strSchema({ allowEmpty: false }) });
},
/** Image source (path / URL / base64) → FileSource control. */
image(): Field<string> {
return new FieldImpl<string>(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'image', schema: strSchema({ allowEmpty: false }) });
},
/** Voice/record source → FileSource control. */
record(): Field<string> {
return new FieldImpl<string>(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'record', schema: strSchema({ allowEmpty: false }) });
},
/** Video source → FileSource control. */
video(): Field<string> {
return new FieldImpl<string>(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'video', schema: strSchema({ allowEmpty: false }) });
},
/** Seconds (int ≥ 0) → duration control. */
duration(): Field<number> {
return new FieldImpl<number>(intCore('an integer', { min: 0 }), { type: 'int', required: true, role: 'duration', schema: intSchema({ min: 0 }) });
},
/** Unix timestamp (int ≥ 0) → datetime control. */
timestamp(): Field<number> {
return new FieldImpl<number>(intCore('an integer', { min: 0 }), { type: 'int', required: true, role: 'timestamp', schema: intSchema({ min: 0 }) });
},
/** QQ face id (non-negative int; face 0 is valid) → face grid. */
faceId(): Field<number> {
return new FieldImpl<number>(intCore('a non-negative integer', { min: 0 }), { type: 'int', required: true, role: 'face_id', schema: intSchema({ min: 0 }) });
},
/** Finite number (fractions allowed). */
number(): Field<number> {
@@ -193,15 +291,7 @@ export const f = {
/** String. Numbers/booleans stringify (matches legacy `asString`). Empty
* allowed by default; `{ allowEmpty: false }` rejects ''. */
string(opts: StrOpts = {}): Field<string> {
return new FieldImpl<string>((raw, field) => {
let s: string;
if (typeof raw === 'string') s = raw;
else if (typeof raw === 'number' || typeof raw === 'boolean') s = String(raw);
else return err(field, 'expected a string');
if (opts.allowEmpty === false && s === '') return err(field, 'must not be empty');
if (opts.maxLen !== undefined && s.length > opts.maxLen) return err(field, `must be <= ${opts.maxLen} chars`);
return ok(s);
}, { type: 'string', required: true, schema: strSchema(opts) });
return new FieldImpl<string>(stringCore(opts), { type: 'string', required: true, schema: strSchema(opts) });
},
/** true/1/yes/on ⇒ true; false/0/no/off ⇒ false (matches legacy `asBoolean`). */
bool(): Field<boolean> {
@@ -331,9 +421,17 @@ export interface ActionDoc {
category?: string;
summary?: string;
returns?: string;
/** JSON Schema for the `data` payload inside the OneBot envelope (NOT the
* whole envelope). Optional + authored incrementally; absent ⇒ data shape
* is documented only by the prose `returns`. */
returnsSchema?: JsonSchema;
/** True only for pure data-fetch actions (no side effects). Drives the MCP's
* read/write tool routing; defaults to false (treated as a write). */
readOnly: boolean;
/** True for Stream API actions (`defineStreamAction`) — they push multiple
* frames through a sink, so a caller must use the streaming transport rather
* than a single request/response. Absent ⇒ ordinary single-response action. */
stream?: boolean;
params: ParamDoc[];
invariants: string[];
/** Composed JSON Schema for the whole params object (properties + required). */
@@ -342,22 +440,32 @@ export interface ActionDoc {
type Handler = (params: JsonObject) => Promise<ApiResponse>;
export interface ActionSpec<S extends Spec> {
/**
* The narrow shape both `ActionSpec` and `StreamActionSpec` share — enough to
* register a spec onto an `ApiHandler` and to collect its docs. The action
* registry barrel (`actions/index.ts`) is typed against this so it can hold
* both kinds in one flat list without coupling to either concrete generic.
*/
export interface RegisteredActionSpec {
describe(): ActionDoc;
register(h: ApiHandler, ctx: ApiActionContext): void;
}
export interface ActionSpec<S extends Spec> extends RegisteredActionSpec {
readonly names: string[];
readonly params: S;
/** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
/** Bind ctx and produce the `(params) => ApiResponse` for `registerAction`. */
toHandler(ctx: ApiActionContext): Handler;
/** Doc metadata (D4); a renderer walks this. */
describe(): ActionDoc;
register(h: ApiHandler, ctx: ApiActionContext): void;
}
interface ActionDef<S extends Spec> {
name: string | readonly [string, ...string[]];
summary?: string;
returns?: string;
/** JSON Schema for the `data` payload (NOT the envelope). See ActionDoc. */
returnsSchema?: JsonSchema;
/** Mark true ONLY for pure data-fetch actions with no side effects. Default
* false = write. Surfaced via describe() into the catalog for the MCP's
* read/write routing. Classify by what `run` actually does, not the name. */
@@ -425,6 +533,7 @@ export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
aliases: names.slice(1),
summary: def.summary,
returns: def.returns,
returnsSchema: def.returnsSchema,
readOnly: def.readOnly ?? false,
params: entries.map(([name, field]) => ({ name, ...field.doc })),
invariants: rules.map((rule) => rule.doc),
@@ -438,6 +547,61 @@ export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
};
}
// ─────────────────────────── defineStreamAction ───────────────────────────
// A Stream API action (#163): same param contract + doc machinery as
// `defineAction`, but `run` additionally receives a `StreamSink` to push
// intermediate frames, and it registers via `registerStreamAction` so the
// network adapter streams its output. The handler's return value is still the
// terminal `ApiResponse` (the final frame). Reuses `defineAction` for
// parse/describe so the two stay in lock-step.
interface StreamActionDef<S extends Spec> {
name: string | readonly [string, ...string[]];
summary?: string;
returns?: string;
returnsSchema?: JsonSchema;
readOnly?: boolean;
params: S;
rules?: (r: RuleBuilders<InferParams<S>>) => readonly CrossFieldRule[];
run: (p: InferParams<S>, ctx: ApiActionContext, raw: JsonObject, sink: StreamSink) => Promise<ApiResponse> | ApiResponse;
}
export interface StreamActionSpec<S extends Spec> extends RegisteredActionSpec {
readonly names: string[];
readonly params: S;
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
}
export function defineStreamAction<S extends Spec>(def: StreamActionDef<S>): StreamActionSpec<S> {
// Borrow defineAction's parse + describe (run is never invoked — register
// below installs the sink-aware handler instead).
const base = defineAction<S>({
name: def.name,
summary: def.summary,
returns: def.returns,
returnsSchema: def.returnsSchema,
readOnly: def.readOnly,
params: def.params,
rules: def.rules,
run: () => failedResponse(RETCODE.INTERNAL_ERROR, 'stream action dispatched without a sink'),
});
return {
names: base.names,
params: def.params,
parse: base.parse,
describe: () => ({ ...base.describe(), stream: true }),
register: (h, ctx) => {
const handler = async (params: JsonObject, sink?: StreamSink): Promise<ApiResponse> => {
const r = base.parse(params);
if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r));
return def.run(r.value, ctx, params, sink ?? NOOP_SINK);
};
for (const name of base.names) h.registerStreamAction(name, handler);
},
};
}
// ─────────────────────────── presets ───────────────────────────
// `group_id` appears in 61/142 actions, `user_id` in 27 — these collapse the
// dominant shape. The injected fields are surfaced in `describe()` so docs
@@ -450,6 +614,7 @@ interface PresetDef<S extends Spec, Extra> {
name: string | readonly [string, ...string[]];
summary?: string;
returns?: string;
returnsSchema?: JsonSchema;
readOnly?: boolean;
params?: S;
rules?: (r: RuleBuilders<InferParams<S> & Extra>) => readonly CrossFieldRule[];
@@ -458,7 +623,7 @@ interface PresetDef<S extends Spec, Extra> {
/** Pre-seeds `group_id` (uint, required). */
export function groupAction<S extends Spec>(def: PresetDef<S, { group_id: number }>): ActionSpec<WithGroup<S>> {
const params = { group_id: f.uint().describe('群号'), ...(def.params ?? {}) } as WithGroup<S>;
const params = { group_id: f.groupId().describe('群号'), ...(def.params ?? {}) } as WithGroup<S>;
return defineAction({ ...def, params } as unknown as ActionDef<WithGroup<S>>);
}
@@ -467,8 +632,10 @@ export function groupUserAction<S extends Spec>(
def: PresetDef<S, { group_id: number; user_id: number }>,
): ActionSpec<WithGroupUser<S>> {
const params = {
group_id: f.uint().describe('群号'),
user_id: f.uint().describe('QQ 号'),
group_id: f.groupId().describe('群号'),
// In a group action, the user_id is a member of *that* group — so its
// picker links to the sibling group_id (member_id role, not user_id).
user_id: f.memberId().describe('QQ 号'),
...(def.params ?? {}),
} as WithGroupUser<S>;
return defineAction({ ...def, params } as unknown as ActionDef<WithGroupUser<S>>);
@@ -478,6 +645,6 @@ export function groupUserAction<S extends Spec>(
/** Register many specs onto an ApiHandler. Coexists with legacy
* `h.registerAction(name, fn)` in the same `register(h, ctx)`. */
export function registerActions(h: ApiHandler, ctx: ApiActionContext, specs: ReadonlyArray<ActionSpec<Spec>>): void {
export function registerActions(h: ApiHandler, ctx: ApiActionContext, specs: ReadonlyArray<RegisteredActionSpec>): void {
for (const spec of specs) spec.register(h, ctx);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,4 @@
import { defineAction, registerActions, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { defineAction, f } from '../action-kit';
import { okResponse } from '../types';
export const actions = [
@@ -7,6 +6,19 @@ export const actions = [
name: 'get_friend_list',
summary: '获取好友列表',
readOnly: true,
returns: '好友列表数组,每项含 QQ 号、昵称与备注。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
user_id: { type: 'integer', description: '好友 QQ 号' },
nickname: { type: 'string', description: '好友昵称' },
remark: { type: 'string', description: '好友备注' },
},
required: ['user_id', 'nickname', 'remark'],
},
},
params: {},
run: async (_p, ctx) => {
if (ctx.getFriendList) {
@@ -20,7 +32,20 @@ export const actions = [
name: 'get_stranger_info',
summary: '获取陌生人信息',
readOnly: true,
params: { user_id: f.uint().describe('QQ 号') },
returns: '陌生人资料:QQ 号、昵称、性别、年龄,命中资料时另含等级。',
returnsSchema: {
type: 'object',
properties: {
user_id: { type: 'integer', description: 'QQ 号' },
nickname: { type: 'string', description: '昵称' },
sex: { type: 'string', description: '性别(male/female/unknown)' },
age: { type: 'integer', description: '年龄' },
qq_level: { type: 'integer', description: 'QQ 等级(仅查到资料时返回)' },
level: { type: 'integer', description: 'QQ 等级,同 qq_level(仅查到资料时返回)' },
},
required: ['user_id', 'nickname', 'sex', 'age'],
},
params: { user_id: f.userId().describe('QQ 号') },
run: async (p, ctx) => {
const userId = p.user_id;
if (ctx.getStrangerInfo) {
@@ -34,7 +59,7 @@ export const actions = [
defineAction({
name: 'delete_friend',
summary: '删除好友',
params: { user_id: f.uint().describe('QQ 号'), block: f.bool().default(false) },
params: { user_id: f.userId().describe('QQ 号'), block: f.bool().default(false) },
run: async (p, ctx) => {
await ctx.bridge.apis.friend.delete(p.user_id, p.block);
return okResponse();
@@ -42,6 +67,3 @@ export const actions = [
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}

View File

@@ -1,6 +1,5 @@
import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
import { defineAction, groupAction, groupUserAction, f } from '../action-kit';
import { okResponse } from '../types';
export const actions = [
groupUserAction({
@@ -16,7 +15,7 @@ export const actions = [
groupAction({
name: 'set_group_kick_members',
summary: '批量踢出群成员',
params: { user_id: f.array(f.uint()).nonEmpty(), reject_add_request: f.bool().default(false) },
params: { user_id: f.array(f.memberId()).nonEmpty(), reject_add_request: f.bool().default(false) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.kickMembers(p.group_id, p.user_id, p.reject_add_request);
return okResponse();
@@ -26,7 +25,7 @@ export const actions = [
groupUserAction({
name: 'set_group_ban',
summary: '禁言群成员(duration=0 解除)',
params: { duration: f.int({ min: 0 }).default(1800) },
params: { duration: f.duration().default(1800) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.muteMember(p.group_id, p.user_id, p.duration);
return okResponse();
@@ -55,9 +54,13 @@ export const actions = [
groupAction({
name: 'set_group_search',
summary: '允许群被搜索',
summary: '设置群被搜索方式(群指纹 / 群号搜索开关)',
params: {
no_finger_open: f.int({ min: 0 }).optional(),
no_code_finger_open: f.int({ min: 0 }).optional(),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setSearch(p.group_id);
await ctx.bridge.apis.groupAdmin.setSearch(p.group_id, p.no_finger_open, p.no_code_finger_open);
return okResponse();
},
}),
@@ -118,18 +121,11 @@ export const actions = [
groupAction({
name: 'set_group_portrait',
summary: '设置群头像',
params: { file: f.string({ allowEmpty: false }) },
params: { file: f.image() },
run: async (p, ctx) => {
try {
await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file);
return okResponse();
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file);
return okResponse();
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}

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