The adapter edit dialog now ships a dedicated TokenField for the
access-token slot instead of reusing the plain text Field. It:
- defaults to a password-style input so the value stays out of
casual screen reads / screenshots,
- exposes an Eye / EyeOff button that flips the input type rather
than masking the string, so paste / autocomplete still behave like
a native password field,
- exposes a Copy button that pushes the current value to
navigator.clipboard, flashing a check icon for ~1.4 s on success,
and disables itself when the value is empty,
- falls back to a transient textarea + document.execCommand('copy')
for non-secure-context environments (LAN HTTP outside localhost),
routed through a local alias so the deprecation warning on the
live signature doesn't fire at the call site.
Follow-up to a07521d. The reporter's correction (895 friends / 221
groups account) was that turning off only field5003 + all of config2
wasn't enough — field5002 has to go too, otherwise QQ NT still emits
a response large enough to blow the named-pipe write buffer and
fetchGroupList dies with EPIPE.
The response decoder (OidbSvcTrpcTcp0xFE5_2GroupInfoSchema) only knows
about tag numbers 1/2/3/4/5/18/19/30, and fetchGroupList itself only
reads groupName / memberCount / memberMax / customInfo.remark off the
result. Tag 5002 isn't in the response schema and isn't consulted by
any caller, so silencing it on the request side is purely a payload
reduction with no observable behavior change.
A11y checkers (axe-core / jsx-a11y) flag the boolean form because the
ARIA spec defines aria-checked as the enum "true" | "false" | "mixed",
not a boolean. React serialized the boolean to the right wire value at
runtime, but the inspection layer keys off the JSX expression's static
type. Switching to the explicit ternary silences both.
The original page stacked four expanded network sections vertically with
inline editing, so the first view drowned in every field across every
adapter at once. Restructured to a sidebar + tabs + modal layout:
- Account sidebar collapses to a 56px avatar column with name/UIN
tooltips; expanded it keeps the original 260px nickname + UIN layout.
- Right pane swaps the stacked sections for a 5-tab strip (通用设置 /
HTTP API / HTTP 客户端 / WS 服务端 / WS 客户端) with a per-tab badge
count.
- Each network tab is a list of summary cards: name + projected key
info (host:port/path, url · role, etc.) + format/report/token badges
+ inline enable toggle + edit/delete buttons. No live-typed fields.
- Create and edit both route through a single NodeEditDialog with
kind-specific field strips; cancel truly discards the draft.
- Per-kind metadata (title, summary projector, defaultEntry factory)
lives in config/defaults.ts so adding a new adapter kind only needs
one descriptor entry.
Behavior preserved end-to-end: same per-UIN config payload, same
useOneBotInstanceConfig hook, same dirty-switch confirm flow, same
save endpoint.
QQ has been pushing Event0x2DC subType=16 every time someone tapped
an emoji on a message in a group, and we were dropping it silently
(only surfacing the PR5 [MsgPush.Unknown] debug line that prompted
this issue). Now we decode it into a first-class event and fan it
out to OneBot clients.
Wire details (cribbed from NapCat's GroupReactNotify transformer):
- body.msgContent has a 7-byte magic prefix; strip before decoding.
- GroupReactNotify { groupUin(4), field13(13), groupReactionData(44) }.
- field13 is a discriminator — same subType is reused for other
notify variants, only 35 means "emoji react". Other values now
fall through to MsgPush.Unknown so we still spot future variants.
- Inside groupReactionData (3-level nested data wrapper, ugh):
code emoji id (system face = numeric str, market = code)
count usually 1
operatorUid needs identity.findUinByUid to resolve to uin
type 1 = add, else = remove
target.seq msg_seq of the reacted-to message
New event kind `group_msg_emoji_like` flows through the standard
pipeline: bridge event → event-bus → converter → OneBot wire.
Converter emits the gocqhttp / NapCat extension shape:
notice_type: group_msg_emoji_like
sub_type: add | remove
group_id, user_id, operator_id, message_id, message_seq,
likes: [{ emoji_id, count }]
message_id is reconstructed via hashMessageIdInt32(msgSeq, groupId,
GROUP_MESSAGE_EVENT) so it matches whatever id the bot originally
handed out for the message being reacted to, even if it's no longer
in the message store.
formatEvent also gets a case so the [Event] log reads cleanly:
表情回应 [群名(123)] | [Alice(99999)] +[76] msgSeq=4242
7 new tests cover the happy path, type=2 (remove), field13!=35
(routed to MsgPush.Unknown), prefix-too-short edge, converter
shape both for add and remove, and the formatEvent string.
closes#42
On accounts with ~200+ groups, fetchGroupList was asking QQ to fill
in every config flag (all 32 bools in config1 plus all 8 in config2)
even though our response decoder reads only groupName / memberMax /
memberCount / customInfo.remark / a handful of named info fields.
QQ NT obligingly packs every requested field into the response. At
group counts >= ~200 the payload is large enough to blow the
named-pipe write buffer on the QQ side; SnowLuma reads EPIPE and
the entire session dies during warmup:
WARN [Hook] pipe error: PID=23928 err=read EPIPE
INFO [OneBot] session closed: UIN=...
WARN [OneBot] failed to load groups for UIN ...: qq_hook client closed
Issue #42 reporter (airline233) bisected the breakage to two
clusters of unused bool flags:
- config1.field5003 (a 5xxx-range expansive descriptor)
- the whole of config2 (per-group aux info we don't decode)
This commit applies exactly their verified safe combination and
inlines a comment so nobody flips them back on without context.
The decoded response shape (groupName, memberCount, memberMax,
remark, etc.) is unchanged.
QQ now rejects fetchUserProfile() with:
[oidb] one of uid/openid is invaild
The cause: SnowLuma's request schema declared field 2 as a
zero-valued uint32 (`field2: 0`) and our encoder doesn't skip 0
varints. Newer QQ NT versions reinterpret field 2 of OIDB 0xFE1_2 as
`uid: string` / `openid: string`, so a varint 0 there decodes as an
empty/invalid uid → server bounces the whole request.
NapCat's equivalent transformer (Oidb.0XFE1_2.ts) emits only `uin`
(field 1) and `key[]` (field 3) — nothing in field 2. Match that
shape exactly.
Effect: warmUpBridgeState's "self info via profile" fallback path
now succeeds for accounts that QQ omits from the friend list, so
the WebUI shows their nickname instead of leaving it blank.
Even the login page leaks "there's a SnowLuma admin panel at this
IP / hostname" to anyone scanning, and right now that page is
publicly indexable. Three overlapping signals so we don't depend on
any one being honoured:
1. Hono middleware on every response sends
X-Robots-Tag: noindex, nofollow, noarchive, nosnippet, noimageindex
Hardest for compliant bots to ignore — it's a header, not
content. noimageindex also covers logo.png / avatar/* from
showing up in image search.
2. A GET /robots.txt route returns "User-agent: * / Disallow: /"
for crawlers that read it before fetching pages. Sits before
the auth middleware so no token is required (otherwise the
crawler would get 401 here, which it'd then refuse to obey).
3. <meta name="robots"> (plus googlebot / bingbot) in index.html
as a fallback for the case where a reverse proxy strips the
X-Robots-Tag header.
The console / subscriber level was captured at module load
(`const MIN_LEVEL = resolveMinLevel()`), so any change to
SNOWLUMA_LOG_LEVEL after Node started had no effect — restart was
the only way to flip levels, which makes "go to debug for 30s to
see what's happening" pretty painful.
logger.ts now keeps `currentLevel` mutable and exports
setLogLevel() / getLogLevel(). The env var still seeds it on
startup; nothing about the boot-time behavior changes. File
transport remains unaffected — it always sees debug-and-up.
WebUI gets two new endpoints, both behind the existing auth
middleware:
GET /api/logs/level → { level, levels }
POST /api/logs/level body → { level: 'debug' } updates it
Logs page picks up a "服务端级别" row of pills next to the
existing client-side filter pills, so an operator can flip the
console firehose on/off in one click without touching env vars
or restarting the bot. The label clarifies that file logging
stays at debug regardless.
After native unload returns, the verification check
if (pipeWatcher.isPipeLive(pid)) { ... unload-failed message ... }
read PipeWatcher's cached snapshot, which is updated every 1500ms.
On Windows clicking "Unload" in WebUI almost always tripped this:
the native unload succeeded and the kernel pipe object was gone, but
the watcher's cached "live" state from the previous tick was still
fresh, so the session reported "DLL卸载失败:命名管道仍然存在" even
though the DLL was successfully unloaded. The user then sees the
status flip back to connecting and waits for a real (cached) refresh.
PipeWatcher already exposes tickNow() for exactly this situation —
the load path doesn't need it because injection's verification runs
async via onPipeUp, but unload verifies inline.
HookSessionDeps.pipeWatcher gains an optional `tickNow` and
unloadInternal awaits it before reading isPipeLive. Existing test
mocks that pass only `{ isPipeLive }` keep working (optional chain
is a no-op there). New regression test covers the production
scenario — stale-true cache flipped to false by tickNow.
The previous commit (257686e) widened printEvent's signature to take
IdentityService but only updated the synchronous call at line 97.
The async post-refresh dispatch path (line 127, called when a group
member join arrives without a resolved uin) still used the old
two-arg form, which CI caught as TS2554. Local tsc somehow didn't
flag it on the editing machine.
Both sites now pass this.deps.identity so the readable rendering
applies to both prompt and post-refresh dispatch paths.
Notice events (recall / join / leave / poke / admin / mute / essence
/ request / invite) and the received-message log now resolve group
IDs and user IDs against the Identity cache so output reads as
human names instead of raw QQ numbers.
Before:
[Event] 群撤回 12345 | 67890 被 99999 撤回
[Event] 群 12345 | NickName(67890): ID:42 你好 [图片]
After:
[Event] 群撤回 [SnowLuma群(12345)] | [Alice(67890)] 被 [Bob(99999)] 撤回
[Event] 群 [SnowLuma群(12345)] | [Alice(67890)]: ID:42 你好 [图片]
Reply segments now expand one level via messageStore.findEvent —
"[回复:42]" becomes "[回复 [Alice(100)]: 早安]" when the original
is still in the message store, falling back to the bare id when it
isn't.
New file utils/event-format.ts owns:
- formatGroup / formatUser identity-aware name resolution
- formatMessageSegments shared element preview (replaces
the inline switch in
logReceivedMessage)
- formatReply one-level reply chain expansion
- formatEvent notice-class event renderer
Every formatter wraps its lookup in try/catch and degrades to the
prior numeric form on cache miss / throw, so log formatting can
never crash the calling path. The QQ numeric ID is preserved
alongside the name so third-party parsers that scrape uids still
find them.
26 unit tests cover cache hit / miss, malformed input, throw
recovery, and per-event-kind rendering shapes.
Two related cleanups so unexpected failures stop being invisible:
void-promise wrappers
Every `void this.something()` fire-and-forget call now has a
.catch(err => log.warn(...)) attached. Affected sites:
- packet-pipeline.ts: dispatchAfterIdentityRefresh
- instance.ts: openAll / applyConfigDiff / closeAll / emitEvent
- http-post-adapter.ts: postEvent
- ws-client-adapter.ts: handleApiMessage
Most of the network-manager fan-outs already isolate per-adapter
errors, but the outer catches guard against future refactors and
surface stack traces immediately rather than as unhandled rejection
warnings.
silent-catch sweep (Bridge.Web)
bridge/web/group-honor.ts, group-essence.ts, group-notice.ts had
`} catch (e) { return undefined; }` patterns that turned every QQ
Web API failure into a silent empty response. Now log.warn with
the full stack first, then return the same fallback so behavior is
unchanged. The commented-out `// console.error(e)` debris is gone.
Plus one console → logger conversion in message-parser.ts (music
sign fallback path).
Highway upload path now emits per-type entry + shared pipeline ops:
DEBUG [Highway.Image] uploading 234567 bytes md5=abc12345... → group 12345
DEBUG [Highway] image OIDB requires bytes, PUT 234567 bytes (sub=top)
DEBUG [Highway] image PUT done in 1234ms
-- or --
DEBUG [Highway] image fast-upload hit (server already had bytes)
The three pipeline-side lines come from runNtv2Upload() and are
shared across image/video/ptt; the per-type entry log lives in each
*-upload.ts wrapper so the scope identifies the media kind. md5 is
truncated to its first 8 hex chars for line width; PUT latency is
reported in ms.
MsgPush silent dispatch defaults are now visible at debug:
DEBUG [MsgPush.Unknown] no decoder for PkgType=999 subType=0
DEBUG [MsgPush.Unknown] Event0x2DC unknown subType=42
DEBUG [MsgPush.Unknown] Event0x210 unknown subType=42
Captures protocol drift (new NT QQ subtypes) and "we forgot to
register this PkgType" oversights, neither of which used to leave
any trace in the log.
All new lines are debug-level so console output (default info) stays
unchanged; file transport sees them for post-mortem.
Every OneBot action call now emits a single debug line under
[Bridge.Action]:
DEBUG [Bridge.Action] send_group_msg group_id=12345 message=[len=3]
On failure, dispatch logs a warn with the full stack instead of
silently folding the error into the response. Unknown actions also
get a debug entry so "the bot is ignoring me" is no longer invisible.
Notes:
- New summarizeParams() helper caps each value at 40 chars / line at
200 chars to keep arrays / nested payloads from blowing the line
width. Lives in utils/log-summary.ts for reuse (highway will too).
- ApiHandler now takes an optional uin and binds a child logger so
per-account file routing works. OneBotInstance passes its parsed
uin.
- Control-char strip in logger/file-transport was exempting only ESC;
also exempt TAB (0x09) and LF (0x0A) so stack traces stay
multi-line in both console and file output.
- vitest.config sets SNOWLUMA_LOG_LEVEL=debug so the ring buffer
receives the new debug entries that tests assert on.
Switches the per-account classes from module-level loggers to
per-instance ones derived via Logger.child({ uin }) so their log
lines land in both the shared file and the account's logs/<uin>/
sub-file, and the [UIN] slot appears in console output:
- IdentityService (Identity scope)
- IncomingPacketPipeline (Bridge + Event scopes)
- OneBotInstance (Event scope)
- HttpServerAdapter (OneBot.HTTP)
- HttpPostAdapter (OneBot.POST)
- WsClientAdapter (OneBot.WS-Client)
- WsServerAdapter (OneBot.WS-Server)
The standalone printEvent() in packet-pipeline now takes a Logger
argument so it routes through this.eventLog instead of a captured
module-level reference. Behavior unchanged otherwise; bridge.ts,
bridge/manager.ts and process-level scopes (App / WebUI / Hook /
OneBot.Config) keep their module-level loggers since they aren't
bound to a single account.
Logger now supports deriving a UIN-bound child:
const log = createLogger('Bridge');
this.log = log.child({ uin: this.uin });
The child stamps a fixed-width [UIN] slot into rendered lines so the
[Scope] column stays vertically aligned, and routes the same line to
a per-UIN sub-file:
logs/snowluma-YYYY-MM-DD.log (shared, all UINs)
logs/<uin>/snowluma-YYYY-MM-DD.log (per-account)
Both pathways share daily rollover, size cap, and retention.
LogEntry now carries uin so SSE subscribers (WebUI) can filter later.
Other meta keys passed to child() are preserved in opts.meta for
forward compat (requestId / traceId etc.) but not rendered yet.
Module-level callers are unchanged; no callsites migrated in this PR.
SNOWLUMA_LOG_PER_UIN=0 disables the per-account sub-file while
keeping the shared one.
Adds a hand-rolled FileTransport that fans out every log line (debug
and up, regardless of console filter) to
./logs/snowluma-YYYY-MM-DD.log. When the current file exceeds the
configurable size cap it rolls into snowluma-YYYY-MM-DD.1.log, and
files older than the retention window are unlinked at startup and on
each day rollover.
Config (all env, no settings.json):
- SNOWLUMA_LOG_FILE 0 to disable file output (default: on)
- SNOWLUMA_LOG_DIR output directory (default: ./logs)
- SNOWLUMA_LOG_MAX_MB per-file cap, MB (default: 50)
- SNOWLUMA_LOG_RETAIN_DAYS retention window (default: 7)
closeLogger() awaits the WriteStream's finish event; SIGINT and
SIGTERM handlers now await it before process.exit so the buffer
makes it to disk.
vitest config sets SNOWLUMA_LOG_FILE=0 to keep the suite from
polluting cwd; the new tests under tests/log-file-transport.test.ts
flip it back on per-test against a tmpdir.
For a private send_private_forward_msg, the inner image/record/video
needs an OIDB upload scene — but uploadForwardNodes never received the
recipient, so the SendContext fell back to {bridge} only and the
element builder threw "private image target uid is missing".
Plumb userId through uploadForwardNodes → buildForwardPushBody and,
when the nodes contain media, resolve it to a uid via
bridge.resolveUserUid() once up-front. Group forwards are unchanged
(they already passed groupId). Mirrors NapCat's design where the
destination peer is threaded all the way down to createSendElements.
If the operator never completed the forced-change flow, the plaintext
bootstrap password was unrecoverable on the next start (only the hash
remained on disk, and the prior log line was likely gone). Now we
detect a persisted state with mustChangePassword=true at load time and
generate a fresh CSPRNG password so the operator can actually log in.
The initial-credentials log block is also wrapped with separators and
a bilingual notice so it stands out at boot. The
'initial credentials: user=admin password=%s' line is preserved
verbatim because third-party launchers parse it.
Mirror of sdk-npm-publish.yml for the UI package. Same triggers
(packages/ui/** + lockfile/workspace/tsconfig.base) and same
already-published guard via `npm view`, so reruns are idempotent.
Differences from the SDK workflow:
- Drops the `test` step (UI package has no Vitest suite yet).
- Filters and working-directory point at packages/ui.
Auth uses the same `NPM_TOKEN` secret in the SnowLuma environment.
Publishes with `--provenance` so the npm registry attests the build
came from this exact GitHub Actions run.
Desktop is switching from the native Windows titlebar to a custom one
rendered in the renderer (frameless BrowserWindow + custom Min/Max/Close).
The bar is 32px tall — the same height Windows draws its system
titlebar — so expose it as a token here for any future Desktop layout
that needs to subtract it.
Desktop's core-download dialog needs to show progress while the server
returns no Content-Length (some mirrors omit it; the SnowLuma core
release artifact does have it but GitHub's CDN sometimes strips it on
redirects). Hard-coded 50% was a placeholder.
Add an `indeterminate` boolean prop: when true, render a marquee bar
that animates left-to-right indefinitely. When false, render the
familiar bytes-done / bytes-total fill at `value%`. Hooked up via a new
`@keyframes progress-marquee` in theme.css.
Also dropped the bar's CSS transition from 500ms → 200ms so live
download updates feel responsive instead of laggy.
Polish pass that an earlier edit lost:
- Add `success` and `warning` button variants (semantic colour pairs
consumers can reach for in confirm dialogs / status actions).
- Outline gets a real card background + shadow so it pops on tinted
surfaces (previously bg-transparent looked invisible on muted/40 rows).
- Tighter motion: explicit transition list + `active:translate-y-px` so
clicks feel mechanical.
- New size `icon-xs` for inline action buttons that need to fit in a
log-row toolbar without ballooning the row height.
- Default radius bumped to `rounded-lg`; sm stays `rounded-md`.
CSS grid's default `min-width: auto` per track was letting long
selected-option text and file paths inside dialogs push the container
past its `max-w-lg` cap, which on Windows / smaller viewports clipped
the right edge of inputs and the Select chevron.
- DialogContent / AlertDialogContent: `grid-cols-[minmax(0,1fr)]` clamps
the single track to its container width; `w-[calc(100%-2rem)]` keeps
a 1 rem gutter to the viewport edge on small screens.
- SelectTrigger: `min-w-0` on the trigger itself plus a child-targeted
truncate (`[&>span:not([data-radix-select-icon])]:truncate`) so the
selected text shrinks before the chevron does; chevron gets `shrink-0`
for the same reason.
Both controls used `bg-muted` / `bg-background` for unchecked / thumb
which collapse to the same hue as the surrounding card in dark mode,
making them effectively invisible.
- Switch: unchecked track now bg-input (light) / bg-muted-foreground/25
(dark) with a shadow-inner; thumb uses bg-card (light) /
bg-foreground/95 (dark) so it pops in both states.
- Checkbox: explicit bg-card + hover:border-border/80; slightly larger
radius (5px) for visual rhythm with the rest of the surface.
Static JSON served from raw.githubusercontent.com/.../main/compat/qq.json
that SnowLumaDesktop polls (3-day cached fallback) to classify the local
QQ install as known-good / known-bad / unknown / too-old.
- compat/qq.json — initial allow-all manifest (policy.allowUnknown=true)
- compat/qq.schema.json — JSON Schema for the manifest shape
Editing this file is how we ship "QQ X.Y.Z breaks Hook" advisories
without cutting a Desktop release.
Two additions for trusted local launchers (notably SnowLumaDesktop) to
configure core without writing to disk-shared config:
- SNOWLUMA_WEBUI_PORT overrides runtime.json's webuiPort at startup
without persisting; CLI/Docker users continue to drive it from the
file. Mirrors the existing SNOWLUMA_HOOK_RUNTIME_DIR / *_TRUST_PROXY
conventions.
- SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD seeds the initial WebUI password on
first launch (when webui.json doesn't yet exist), with
mustChangePassword=false. After the file is persisted the env var is
ignored — password rotation continues through the UI.
PR #39 hardened most of the OneBot action surface but left download_file
on the original `await response.arrayBuffer()` path — an authenticated
client could still hand us a multi-GB URL (or a chunked response with no
Content-Length) and OOM the bot. The base64 branch had the same problem
in the other direction: `Buffer.from(huge, 'base64')` allocates the
decoded payload before any size check.
Match the loadBinarySource pattern that `0804351` introduced for
highway uploads:
* HTTP path runs through `fetchDownloadFile`: AbortSignal.timeout
(60s), Content-Length precheck, then a streaming reader that aborts
the moment the running total crosses the 1 GiB cap.
* Base64 path rejects before `Buffer.from` based on the
upper-bound `floor(len * 3 / 4)`, with a post-decode check for
safety.
* Writes go through `fs.promises.writeFile` so a multi-hundred-MB
download doesn't stall every other bot action on the event loop.
Also drop the `actionFailed` helper added in the same PR — it was
intended as a sanitized-error wrapper but never wired up. Wiring it
into the dozen-or-so `String(e)` sites is its own cleanup; for now
remove the dead code (and the no-longer-used createLogger import).
The previous commit tightened login rate-limiting to key off the real
TCP socket peer, which fixed the X-Forwarded-For bypass but had the
known caveat of collapsing every client into a single global bucket
when the WebUI runs behind nginx / Caddy / a SaaS CDN.
Give operators an explicit, audited way to opt back into per-client
keying without re-introducing the spoof:
* `SNOWLUMA_WEBUI_TRUST_PROXY` env var. Modes:
- unset / empty → keep socket peer (safe default, unchanged)
- "loopback" → trust X-Real-IP / X-Forwarded-For when the
immediate socket peer is 127.0.0.1 / ::1
(nginx + WebUI on the same host)
- "1" / "true" / → trust headers from any peer (only safe behind
"all" a SaaS proxy that strips client-set headers)
- comma-separated → trust headers only when the socket peer
IP list matches one of these (proxy on another box)
* When trusting headers we prefer X-Real-IP (single value the proxy
overwrites unconditionally) and fall back to the first hop of XFF.
We deliberately do NOT walk the full XFF chain — without a fully
trusted proxy chain the leftmost value is still spoofable; a
single-tier proxy is the only setup this app realistically sees.
* Boot log prints "login rate-limit keyed by: …" so operators can
verify the mode took effect, plus an extra WARN for "all" reminding
them it's only safe with header-stripping in front.
Logic lives in webui/client-ip.ts as a pure pickClientIp() that takes
a socket-IP resolver, so the trust-proxy matrix can be exercised
without standing up a server — see webui-client-ip.test.ts for the
11 new unit tests covering parse + dispatch + loopback / list / all /
none modes.
Smoke-tested with SNOWLUMA_WEBUI_TRUST_PROXY=loopback:
- 5× failed login w/ X-Forwarded-For: 1.1.1.1 → 401
- 6th attempt same XFF → 429 (locked, per-XFF)
- 6th attempt X-Forwarded-For: 2.2.2.2 → 401 (fresh bucket)
- X-Real-IP overrides XFF when both present
QQ's short-video element protocol hard-limits a single video at 100 MB
(NapCat enforces the same cap in highwayContext.uploadVideo with the
same threshold and tells operators to switch to file upload). Mirror
that hint so OneBot bot authors who hit the cap immediately see the
correct alternative — `upload_group_file` / `upload_private_file`,
which ride the FtnUpload path and go up to 4 GiB — instead of having
to read the docs to figure out why a send_msg with a 200 MB video
silently 'won't work'.
Follow-up on the previous highway commit, addressing two real holes the
Copilot review caught:
* loadBinarySource HTTP path was buffering the entire response via
`await resp.arrayBuffer()` BEFORE length-checking. A server that omits
or understates `Content-Length` (chunked transfer, malicious upstream,
proxy stripping headers) bypassed the cap entirely. Switch to a
streaming reader: accumulate chunks, abort + reject as soon as the
running total exceeds `maxBytes`. The Content-Length precheck still
short-circuits the obvious case before we read a byte.
* video-upload `stageVideoSource` has its own local-path fast-path that
never went through `loadBinarySource`, so the 100 MB MAX_VIDEO_SIZE
guard ran AFTER `fs.readFileSync` had already allocated the entire
file. A 10 GiB local-file pointer would OOM the bot before the check
fired. Add an `fs.statSync` precheck on the local branch, and pass
`MAX_VIDEO_SIZE` explicitly when the source falls through to
`loadBinarySource` so the HTTP / base64 cap matches the on-disk one.
Update the DEFAULT_MAX_BINARY_SIZE comment to stop claiming video paths
are bounded by it — they're bounded by the smaller MAX_VIDEO_SIZE,
enforced inside video-upload.
Adds five regression tests:
- chunked streamed download (no Content-Length) over cap → throws
- Content-Length over cap → throws before reading body
- streamed download inside cap → returns full bytes
- local file over cap (statSync precheck) → throws
- base64 over cap → throws
* highway/utils detectImageFormat: JPEG SOF marker check now excludes
0xC4 (DHT), 0xC8 (JPG), and 0xCC (DAC). The old `(marker & 0xFC) ===
0xC0` matched DHT et al. and then read Huffman table bytes as image
dimensions, producing junk width/height for many real JPEGs.
* loadBinarySource takes an optional maxBytes; defaults to 1 GiB to
defend against an authenticated client triggering a multi-GB load
into memory. Group/private file uploads pass FILE_UPLOAD_MAX_BYTES
(4 GiB) because QQ's file protocol legitimately supports that size.
HTTP fetches also pick up a 60s timeout and a Content-Length precheck.
* highway-client.tcpConnect detaches its error/timeout listeners after
a successful connect so subsequent upload IO errors don't reject an
already-resolved promise. readHttpResponseBody uses local listener
refs + a central detach(), eliminating MaxListenersExceededWarning
during multi-chunk uploads.
* hook/qq-hook-client.nextRequestId now wraps inside uint32 explicitly
and skips id 0 / in-flight ids. The previous `nextRequestId++ >>> 0`
loses precision past Number.MAX_SAFE_INTEGER (postfix increment
evaluates before the shift) and could collide live request ids on
very long-running processes.
* identity-service.rememberUidUin removes stale partner entries before
inserting a new (uid, uin) pair. The old code left orphan uidByUin /
uinByUid entries after a uid/uin re-bind, so the two maps could
disagree.
Action-layer fixes, all cross-checked against NapCat's reference
implementation in packages/napcat-onebot:
* download_file (extended.ts:539) now sanitizes `name` via
path.basename + resolve/relative containment check. Previously an
authenticated client could write `../../config/onebot_<uin>.json`
and replace access tokens / webhook URLs.
* mark_group_msg_as_read / mark_private_msg_as_read / mark_msg_as_read
fall back to meta.targetId when the optional group_id/user_id arg
is missing. The old code passed 0 to the Bridge. NapCat resolves the
peer from message_id alone in MarkMsgAsRead.ts; we now match that.
* set_friend_remark / set_group_remark refuse a missing `remark` field.
The previous `asString(...) ?? ''` silently CLEARED the remark for
any client that forgot the parameter. NapCat's typebox schema makes
`remark` required; we now do the same.
* upload_forward_msg threads `group_id` down to uploadForwardNodes so
the resulting resId lives in the correct namespace (type:3 + groupUin
vs type:1 + selfUid — see bridge/actions/forward.ts). NapCat passes
`peer.chatType === GROUP ? +peerUid : 0` for the same reason.
ApiActionContext.sendForwardMsg + uploadForwardMessage signatures
pick up an optional groupId.
* Private-message reply meta now resolves senderUin from the cached
event (real sender), with a self-id fallback when only meta exists
(bot's own outbound message — `cacheMessageMeta` does not populate
the event row). The old code used meta.targetId, which is the
conversation peer — wrong when the bot replies to its own message.
* message-parser:
- intOr(value, fallback) helper replaces parseInt(String(...)) at
face/at/reply/image/xml/poke/node sites so non-numeric input no
longer produces NaN downstream. Invalid face ids skip the
element rather than emit NaN.
- cqUnescape decodes `,` (escaped comma) — the OneBot 11 spec
requires it and clients in the wild emit it.
* Drop the dead Array.isArray(rawAuth) branch in onebot/network/utils
(Node's headers.authorization is `string | undefined`, never an
array) and the unused WebHonorType import in api-handler.
Stack of WebUI fixes prompted by an internal security/correctness pass:
* getClientIp now resolves the real socket peer via @hono/node-server's
getConnInfo helper instead of trusting `X-Forwarded-For`. The previous
behaviour let any client rotate that header to bypass the 5-attempts/
15-minute login lockout.
* `?token=` is restricted to /api/logs/stream (the only endpoint that
can't use the Authorization header, because EventSource lacks custom
headers). Other routes used to leak tokens via access logs / Referer
/ browser history.
* change-password now invalidates every session (including the current
one) and signals requireRelogin. Keeping the current token alive made
the rotation pointless if the old credentials were already in an
attacker's hands.
* GET /api/config/:uin no longer writes defaults to disk and no longer
doubles up the payload (`{config}` only, dropping the {…config, config}
legacy shape). Frontend's `data?.config ?? data` fallback still works.
* webui.json is moved to .bak.<ts> instead of being silently overwritten
when it fails to parse — losing the prior hash silently was rotating
operator credentials with no warning.
* Process load/unload/refresh routes are deduped into a single helper;
internal error messages are logged but no longer surfaced verbatim to
the client.
* SSE log stream tolerates a closed controller (try/catch around enqueue
+ central teardown) and runs an unref'd janitor to GC expired session
tokens + login attempt counters every minute.
GET on a load helper used to mint a fresh access_token and write it to
disk whenever the per-UIN file was missing or in legacy format. Reading
should not have side effects, and the WebUI's read-only GET handler in
particular was racing on concurrent requests and surprising operators
with materialized config files.
Introduce a `{ persistDefaults?: boolean }` option (default false). The
two boot-time call sites in `OneBotManager` (onSessionStarted, reloadConfig)
opt in explicitly; WebUI's GET path will rely on the new default once
that side of the patch lands.
Also stop reviving default 0.0.0.0 listeners when the operator has
explicitly emptied every adapter — only seed defaults on a true fresh
install (no per-uin and no global config on disk).
Drop the unused deepClone / deepMerge helpers; tryLoadJson now logs a
warning instead of silently swallowing JSON parse errors.
Commit 29f28d6 changed c2c video `compatQmsgSceneType` from 2 to 1
as a "symmetric asymmetry" cleanup, matching the image/ptt convention
where the field tracks the upload's sceneType (c2c=1, group=2). For
video this is wrong.
Image and ptt have *different* legacy compat elements per scene
(notOnlineImage vs customFace; ptt c2c vs group), so the server needs
to know which scene shape to emit. The legacy `videoFile` element
(packet element type 19) has no scene split — fromChatType /
toChatType live inside the element itself — so the QQ NT server
emits a single group-shaped compat payload regardless. NapCat
hardcodes `compatQMsgSceneType: 2` for *both* UploadGroupVideo and
UploadPrivateVideo for exactly this reason.
Setting it to 1 on c2c made the server emit a c2c-scene shaped
compat blob that older QQ clients failed to resolve, showing the
message as "视频已过期" on those receivers. Newer clients only read
the commonElem(48, 11) and displayed fine — which is why only "some
devices" saw the breakage.
Keep `commonElem.businessType = isGroup ? 21 : 11` untouched — that
piece of 29f28d6 is still correct and is what fixed PbSendMsg
result=79.
OneBot clients commonly send [CQ:at,qq=12345] without a name field; we
were piping `@12345` into the text element so QQ rendered the bare uin
instead of the member's card/nickname (napcat resolves via getGroupMember
before encoding). Move the fallback into the element builder so it
consults the IdentityService roster and only falls back to the uin when
the roster has nothing.
The four-page switch lived as a string union (Page) plus an if/else
chain in AppInner, with TopBar reverse-importing Sidebar's NAV_ITEMS
to find the icon for the active tab. Adding a page touched four
places and there was no URL, no history, no deep-linking.
Move routing behind @tanstack/react-router with a layout route
(AppLayout) that owns the polling lists, processOps, selectedUin
and the unload-failed alert; child routes render through <Outlet/>
and read shared state from a new AppStateContext. AuthBoundary still
gates login / forced-password-change above the router. Sidebar uses
<Link> + useRouterState for active state; TopBar and MainLayout look
up the current path the same way.
Behaviour-preserving:
- LoginPage / ChangePasswordPage still mount above the router.
- AppLayout never unmounts during navigation, so selectedUin,
processOps state, the polling state and the unload-failed dialog
all survive page switches just like before.
- Logout calls history.replaceState('/') so the next login lands on
the overview page, matching pre-router behaviour.
- The sidebar-active-pill layoutId animation and the page-transition
AnimatePresence are preserved, keyed off pathname instead of the
removed `active` prop.
New URLs (/, /config, /logs, /settings) work on refresh because the
backend already had SPA fallback in core/src/webui/server.ts. Bundle
grows ~84KB (gzip +27KB) for the router runtime.
Two regressions slipped into the ApiClient/ConfigPage refactor:
1. api.config.save() ran the POST response through normalizeOneBotConfig
and used it to overwrite local state. But POST /api/config/:uin
returns { success, reloaded, message } — no config body — so the
normaliser produced an empty config and wiped the user's edits as
soon as the save succeeded. Honour the "save returns canonical view"
contract by following the POST with a GET inside the client; the
round-trip stays hidden behind the seam.
2. selectedUin lived inside useOneBotInstanceConfig, so navigating away
from ConfigPage unmounted the hook and lost the user's selection.
Lift selectedUin to AppInner and make the hook externally controlled
via { selectedUin, onSelectedUinChange }. Clear it on logout.
App.tsx held three copy-pasted handlers (load / unload / refresh) and
three parallel processXxxPid state slots that were mutually exclusive
but unenforced by the type system. The unload-failed alert was a
separate path, and OverviewPage needed 11 props to drive the table.
Extract useHookProcessOps: one inflight Set for dedup, one Map<pid,
OpKind> for view state, one run() that branches on kind via a
message table, and ownership of the unload-failed alert. OverviewPage
takes a single HookProcessOps prop and queries statusOf(pid).
App.tsx 270 → 216 LOC; OverviewPage props 11 → 7.
App.tsx was the single source of truth for token, fetch policy, 401
handling, and per-UIN config edit state — fetchApi was drilled into
every page and LogsPage read localStorage directly to build its SSE
URL, giving two parallel truths for the bearer token.
Promote the closure to a deep ApiClient module (domain methods +
request() escape hatch) injected via ApiProvider/useApi, and lift
selectedUin/config/saveStatus into useOneBotInstanceConfig so
ConfigPage is self-contained. normalizeOneBotConfig becomes a pure
function. ConfigPage now guards UIN switches when the editor is
dirty and refetches the server-normalised config after save.
ConfigPage prop count drops from 7 to 1; App.tsx from 421 to 270 LOC.
`actions-sync.test.ts` walks every `registerAction(...)` in
`@snowluma/core/src/onebot/actions/` and asserts the SDK's exported
list matches. The napcat-parity work (Tier 1 + Tier 2 + Tier 3 + AI
voice) added 14 actions to core without ever touching the SDK, so the
test caught the drift:
bot_exit cancel_group_todo
complete_group_todo delete_group_folder
get_ai_characters get_ai_record
get_group_ignore_add_request
nc_get_packet_status nc_get_rkey
nc_get_user_status
send_group_ai_record send_packet
set_diy_online_status set_group_todo
Added them to `SNOWLUMA_ACTIONS` and gave each one a typed
`SnowLumaActionMap` entry. Where the request body shape is non-trivial
(AI voice, group todo, DIY status, send_packet, nc_get_user_status),
introduced dedicated param types in `types/params.ts`; where the
response is structured (AI character list, user-status word),
introduced result types in `types/results.ts`. Everything else routes
through `JsonObject` / `EmptyData` so the SDK surface stays small.
Verified:
pnpm --filter @snowluma/sdk typecheck → clean
pnpm --filter @snowluma/sdk test → 17/17 pass