Arm receive monitoring only after an existing QQ heartbeat has been observed, preserving compatibility with sessions that do not expose the signal.
Require 90 seconds of receive silence plus a 15-second confirmation window before reporting degradation. Any later inbound frame refreshes or restores health, including non-routable frames that still prove the receive path is alive.
Bind watchdog state to the active account epoch so direct login switches and packet-driven account migration cannot inherit stale deadlines from a previous account.
Forward health transitions to the bridge layer without reconnecting, reinjecting, or otherwise changing session recovery behavior. Add regression coverage for arming, recovery, sleep-resume confirmation, account migration, and invalid-UIN frames.
Refs #233.
* 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>
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.
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.
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.
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.
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.
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.
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).
Switch from open-source to a NapCat-style source-available, NON-commercial
license so the free software cannot be resold / paid-deployed — which an OSI
license (AGPL included) cannot prevent. Source stays public for study and
non-commercial self-hosting; commercial use and public release of modifications
require written permission; the native addon (snowluma-*.node) is carved out as
proprietary. Explicitly NOT OSI open source.
- LICENSE: SnowLuma Source-Available Non-Commercial License v1.0 (bilingual)
- all 14 package.json: "license": "SEE LICENSE IN LICENSE"
- README license section; CONTRIBUTING contribution-licensing note + a grant
letting the project relicense contributions under commercial terms
(contributors keep copyright)
Conclude the spike on the inbound
`trpc.qq_new_tech.status_svc.StatusService.KickNT` push and remove its
throwaway instrumentation:
- Bridge: drop the outbound send probe.
- HookSession: drop the loggedIn-gate bypass; restore `if (!this.loggedIn) return;`.
- HookManager: drop the disconnect-timing log.
Keep one read-only `[KICK-BODY]` probe in Bridge that logs the KickNT push
body (hex + utf8) so the reason fields (tipsTitle / tipsDesc) can be reversed
for the upcoming notification reason-enrichment. Remove once captured.
When the control pipe drops while a send() is awaiting its ack,
rejectControlPending() rejects both the ack and the reply deferreds. The
reply is only awaited after the ack, so an ack-first rejection leaves the
reply promise rejected with NO awaiter — an unhandled rejection that, under
Node's default policy, kills the process. In Docker supervisor restarts it
(every session drops for ~1s); on a bare Windows run it just dies, surfacing
as "connection pipe closed" with the bot offline after hours of uptime.
Attach a no-op .catch() to each deferred at creation so a rejection can never
go unhandled (the real await still observes the value/rejection). Add a
regression test that drops the pipe mid-send and asserts no unhandled
rejection escapes — it fails without the guard.
Also install last-resort process guards (unhandledRejection / uncaughtException)
in the app entry: log and keep serving instead of exiting, so any other stray
rejection cannot take the daemon down and its stack is captured. The bridge's
watcher reconnects the dropped pipe on the next tick.
PR #73's login-state probe shipped with issues:
- `fetchPtlogin` returned `Promise<any[]>`, tripping the repo's
`@typescript-eslint/no-explicit-any` (error) and breaking `pnpm lint`.
Modelled the read fields as a `PtloginUin` interface and cast the parsed
JSONP to it.
- `tryPtloginMethod` had a dead `if` whose two branches both returned
'fallback'; collapsed to a single return with a comment.
- The `< 6` QQ-process-count heuristic was a bare magic number (one copy
annotated only with "13579 5个端口全部用光"). Extracted to
`LOGGED_OUT_PROCESS_COUNT_MAX` with an explanation and reused in all three
sites (incl. the error fallback).
Behaviour-preserving: the probing logic (Ptlogin parse, deep-link fallback,
PID port discovery) is unchanged — only typing and the magic constant.
Reorder and tidy imports, re-export types, and apply minor formatting fixes across the bridge package. Changes include:
- Reordered imports and grouped related imports in hook-manager, hook-session, pipe-watcher, qq-hook-client, qq-port-probe and others.
- Moved several type re-exports (HookProcessBaseInfo, QqPortLoginInfo, HookProcessInfo/Status) in hook-manager and consolidated exports in package entry index.ts.
- Minor whitespace/style tweaks: constructor spacing, for-loop formatting, empty catch handlers, and small refactors that do not change runtime behavior.
These are non-functional housekeeping changes to improve consistency and readability.
Split the QQ NT client lifecycle / hook injection layer out of
@snowluma/core into its own self-contained package. The new bridge
package owns:
- native hook addon loader (injector)
- HookManager + per-PID HookSession orchestration
- PipeWatcher for QQ process discovery
- QqHookClient pipe protocol
- qq-port-probe for early UIN sniffing
The hook layer used to type its main collaborator as
`BridgeManager` directly. To keep the new package free of any
dependency on @snowluma/core, the cross-package coupling is now
expressed via a 3-method `BridgeManagerSink` interface that lives
in the bridge package. BridgeManager (in core) satisfies the
interface structurally with no source changes; the top-level
app/webui still inject it the same way.
Pure file relocation otherwise: git mv preserves history at 100%
on every file, the only logic edit is the interface introduction
in hook-manager.ts and an updated `nativeSearchDirs()` offset
(one fewer `..` since hook now lives at packages/bridge/src
instead of packages/core/src/hook).
The package previously named "bridge" houses the protocol-byte layer
(OIDB cmds, msg-push decoders, highway uploaders, element-builder,
event bus). The name "bridge" suggested transport/lifecycle, which it
isn't — that role lives in core/hook and core/bridge/manager. Rename
to match what's actually inside.
This is a pure rename: zero logic changes, all 73 import sites updated
mechanically and TS-verified. core/onebot dependencies key updated.
ESLint override path adjusted for the moved oidb-services directory.
Rename detection threshold: git log --find-renames=20% recommended
when following history across this commit — content-replacement
(@snowluma/bridge → @snowluma/protocol) dropped per-file similarity
below git's default 50% on import-heavy files.
User report:
SnowLuma's group_invite event renders to OneBot with empty
`comment`, so the bot's approval-prompt template shows nickname
+ uin + flag but loses the requester's verify message.
NapCat's same flow shows the verify text:
【进群申请】批准/驳回:
昵称:KitaIkuyo
QQ:1957003260
flag:1779543612823906
等级:7
你们好 ← only NapCat shows this line
Root cause:
The OIDB push (GroupRequestJoinNotice subType=84) only carries
`(groupUin, targetUid)` and a few opaque numeric fields — no
string for the verify text. NapCat doesn't use the push directly;
they poll `nodeIKernelGroupService.getGroupNotifies` (= our OIDB
0x10C0 pending-request queue at `FetchGroupRequests`) which
returns each pending row with `postscript` (the verify text) and
`seq` (server sequence id). Reference:
dev/NapCatQQ/packages/napcat-onebot/index.ts:483-498
(`flag = notify.seq`, `comment = notify.postscript`).
Our pipeline didn't enrich. The decoder set `message: ''` and
emitted, so OneBot's `comment` was empty.
Fix:
- Extend `PacketPipelineDeps` with a `resolveGroupJoinRequest(
groupId, uid, subType)` hook. Bridge.ts wires it to
`fetchGroupRequests` and matches on `(groupId, uid)` —
targetUid for `subType='add'`, invitorUid for
`subType='invite'`.
- `dispatchAfterStrangerResolve` now fires the profile + request
lookups in PARALLEL via `Promise.allSettled` so a flake on one
path doesn't kill the other. The request lookup's `comment`
lands on `event.message`; OneBot converts that to `comment`.
Decisions:
- Kept the existing `add:<groupId>:<uid>` flag format (consumer
bots already parse it). Switching to NapCat's sequence-form
flag would break callers and is a separate breaking change.
- Both lookups fail-open: if either rejects, the event still
emits with whatever info we did get, so the bot at least sees
the request and can render the bare nickname.
Regression tests:
- `populates event.message from the pending-request queue` — pins
the user-reported "你们好" case end-to-end through the pipeline.
- `runs lookups in parallel` — profile resolves, request fails;
event still ships with the resolved uin and an empty message.
- `invite subtype matches the request on invitorUid` — explicit
contract for the invite-forwarded-to-admin case where the
pending row's REQUESTER is `invitorUid`, not `targetUid`.
345 bridge tests pass (was 342 + 3 new); typecheck + lint clean.
User report: after [a4909ec], log STILL shows
群邀请 950929451 -> [bot group(950929451)]
get_stranger_info params=user_id=950929451 → 未知昵称
But NapCat and a sibling SnowLuma bot in the same group BOTH decoded
the same push as `QQ:1957003260 nickname:KitaIkuyo`. So the wire is
correct — our bot is just looking it up wrong.
Root cause: **legacy cache pollution**. The pre-fix decoder fallback
stored `<requester_uid> → <groupUin>` in the identity DB whenever
`resolveUidToUin` missed (because the fallback `ctx.fromUin` on a
group-scoped push IS the group's own uin). After upgrading to
[a4909ec], `decodeGroupJoinRequest` calls `resolveUidToUin` which
hits the polluted in-memory map (re-populated from SQLite at boot)
and returns the groupUin instead of 0. The new `needsStrangerResolve`
guard only fired on `fromUin <= 0` — so the polluted value flowed
straight through and re-emitted the bug.
Two-part heal:
1. `needsStrangerResolve` now ALSO fires when `fromUin === groupId`
— the pollution signature. A real requester's uin can never
equal the group's own uin, so this is a safe override that
forces the async UID-form FetchUserProfile lookup, which then
`rememberUidUin`s the correct mapping on success (eviction is
already wired in identity-service.ts:468-471).
2. `rememberEventIdentity` for group_invite now passes `uin: 0`
when `event.fromUin === event.groupId`, so future writes don't
re-pollute the cache (`rememberUidUin` short-circuits on
normalized uin ≤ 0).
Cache self-heals on first event after upgrade — no manual DB nuke
needed.
Regression test pins the legacy-pollution path: feeds an event
where `fromUin === groupId` (matching the user's log), verifies the
resolver fires and patches fromUin to the correct value.
User report: when a stranger requests to join a group, the bot
receives `user_id=<groupId>` (instead of the requester's actual
uin) and `get_stranger_info` returns no nickname → bot displays
"未知昵称".
Two layered bugs:
1. **Decoder fallback was wrong.** `decodeGroupJoinRequest` /
`decodeGroupInvitation` / `decodeGroupInvite` all passed
`ctx.fromUin` as the fallback uin when `resolveUidToUin` missed
the local cache. But for group-scoped pushes `ctx.fromUin` is
the GROUP's own uin — falling back to it produces the bogus
`fromUin === groupId` collision the user saw. Fix: pass 0.
2. **No async resolve for stranger UIDs.** The push only carries
the requester's UID string. When the UID isn't in our cache
(true for any stranger who isn't yet a group member), we have
no UIN — and our UIN-form `FetchUserProfile` can't help. The
pipeline never tried to look up the stranger by UID, so the
event went out with `fromUin=0` (or, with the old fallback,
the group's own uin).
Cross-checked against Lagrange.Core's flow:
dev/Lagrange.Core/.../MessagingLogic.cs:215-224
case GroupSysRequestJoinEvent join:
var fetchUidEvent = FetchUserInfoEvent.Create(join.TargetUid);
var results = await Collection.Business.SendEvent(fetchUidEvent);
uint targetUin = results.Count == 0 ? 0
: ((FetchUserInfoEvent)results[0]).UserInfo.Uin;
var joinArgs = new GroupJoinRequestEvent(join.GroupUin, targetUin);
dev/Lagrange.Core/.../OidbSvcTrpcTcp0xFE1_2.cs:9-26
— UID-form variant of the same OIDB 0xFE1_2: field 1 is `uid:
string`, envelope `reserved=0` (no uinForm flag).
dev/Lagrange.Core/.../FetchUserInfoService.cs:66-78
— picks UID vs UIN form based on which input is set.
Changes:
- `proto-defs/oidb-actions/base.ts`: add `OidbUserInfoByUidRequest`
(same shape as the UIN variant but field 1 is `uid: string`).
- `bridge/oidb-services/contacts/fetch-user-profile-by-uid.ts`:
new namespace at 0xFE1_2 with UID-form encoding, no `uinForm`.
- `bridge/msg-push/decoders/group-join-request.ts`: 3 decoders'
`resolveUidToUin` fallbacks change `ctx.fromUin` → 0.
- `bridge/packet-pipeline.ts`: new `resolveStrangerProfile(uid)`
dep + `needsStrangerResolve` check + async dispatch that fires
the lookup before emitting the event. Fail open if the lookup
rejects (event still ships with `fromUin=0` so the OneBot bot
can fall back to the uid in the flag).
- `core/bridge/apis/contacts.ts`: `fetchUserProfileByUid(uid)`
facade method.
- `core/bridge/bridge.ts`: wire `resolveStrangerProfile` into the
pipeline deps so it routes through the new namespace.
Tests:
- UID-form namespace: declares the right cmd/subcmd, packages uid
as field 1, decodes nickname + uin so the pipeline patch works.
- Pipeline stranger resolve: patches event.fromUin from the
resolver response; fails open on null / throw; skips the wire
call when fromUin is already populated or fromUid is empty.
All 655 tests pass (was 645 + 10 new); typecheck + lint clean.
Mobile QQ, Lagrange.Core, and NapCat all use the literal Chinese
bubble-preview strings `[图片]` / `[动画表情]`. SnowLuma was emitting
English `[image]` / `[sticker]` as fallback, so QQ clients showed
"[image]" in chat-list previews instead of the expected Chinese.
Cross-checked against:
dev/NapCatQQ/.../packet/message/element.ts:367-371
dev/Lagrange.Core/.../Message/Entity/ImageEntity.cs:186-192
Both branch the same way: subType=1 → `[动画表情]`, else → `[图片]`.
Changes:
- `bridge/highway/image-upload.ts`: both code paths (fingerprint +
load-from-source) now emit the Chinese defaults. Subtype branch
flipped to `subType === 1 ? '[动画表情]' : '[图片]'` to match the
upstream convention (our old check was `subType === 0` →
`[image]`, which would label any non-zero subType — not just
stickers — as `[sticker]`).
- `bridge/msg-push/rich-body-decoder.ts`: all three decode paths
(NotOnlineImage / CustomFace / commonElem image) now substitute
the Chinese default when the server omits `textSummary`. Empty-
string is also treated as missing (matches NapCat's `=== ''`).
- Tests updated to assert the Chinese defaults; new test pins
that a caller-supplied summary still overrides verdef.
The OneBot caller's `summary` field on the MessageElement still
wins when set, so downstream clients passing custom bubble text
(e.g. for accessibility) keep working.