Commit Graph
71 Commits
Author SHA1 Message Date
DrSmoothl ebd02c3f3d chore(release): v1.12.3 2026-07-15 21:31:59 +08:00
DrSmoothl e8cb49ced9 feat(bridge): detect stalled receive paths
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.
2026-07-15 16:46:16 +08:00
DrSmoothl a3467a8d89 chore(release): v1.12.2 2026-07-14 07:57:08 +08:00
DrSmoothl c04864dd21 chore(release): v1.12.1 2026-07-10 14:00:40 +08:00
DrSmoothl b6fb5bd530 chore(release): v1.12.0 2026-07-07 22:38:02 +08:00
DrSmoothl d35e276730 chore(release): v1.11.4 2026-07-06 15:04:55 +08:00
DrSmoothl 0e6e2ec51d chore(release): v1.11.3 2026-07-05 14:26:10 +08:00
H3CoF6andClaude Opus 4.8 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
DrSmoothl 6cb7f2c6d0 chore(release): v1.11.2 2026-07-04 13:39:00 +08:00
DrSmoothl 72aedbc612 chore(release): v1.11.1 2026-07-01 22:15:01 +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 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 48e2777bc3 chore(release): v1.11.0 2026-06-30 20:38:37 +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 7ec74f2928 chore(release): v1.10.4 2026-06-28 22:48:00 +08:00
DrSmoothl 351db573d8 chore(release): v1.10.3 2026-06-26 19:49:41 +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
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 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 1bd126562f chore(release): v1.10.2 2026-06-22 21:31:06 +08:00
DrSmoothl 8b87f80951 chore(release): v1.10.1 2026-06-22 01:45:25 +08:00
DrSmoothl 9efe16237d chore(release): v1.10.0 2026-06-21 20:22:46 +08:00
DrSmoothl f71ed2e4db chore(license): source-available non-commercial license
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)
2026-06-19 02:26:33 +08:00
DrSmoothl dfb6aa54c7 chore(release): v1.9.13 2026-06-18 17:16:15 +08:00
DrSmoothl 16920b4444 chore(release): v1.9.12 2026-06-16 21:59:31 +08:00
DrSmoothl 652a817568 chore(spike): retire KickNT force-offline probes, keep read-only body capture
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.
2026-06-16 18:17:46 +08:00
DrSmoothl 300fa70148 feat(spike): add logging and handling for KickNT command in bridge and session 2026-06-16 00:34:03 +08:00
DrSmoothl 7e59dbf79b chore(release): v1.9.11 2026-06-15 13:57:38 +08:00
DrSmoothl ee8eb928b3 chore(release): v1.9.10 2026-06-14 16:28:39 +08:00
DrSmoothl a3a36718d6 chore(release): v1.9.9 2026-06-11 16:42:23 +08:00
DrSmoothl d508814dfa chore(release): v1.9.8 2026-06-09 14:22:43 +08:00
DrSmoothl 515bac4b3c chore(release): v1.9.7 2026-06-07 22:29:37 +08:00
DrSmoothl 6a2fd9e8f3 fix(bridge): don't crash the daemon when the hook pipe closes mid-send
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.
2026-06-07 22:15:07 +08:00
DrSmoothl 174150c5e1 chore(release): v1.9.6 2026-06-07 21:19:00 +08:00
DrSmoothl 4fcaba2f3e chore(release): v1.9.5 2026-06-03 21:55:37 +08:00
DrSmoothl a1f372bc9d chore(release): v1.9.4 2026-06-01 16:21:54 +08:00
DrSmoothl f9252fb26d fix(bridge): type Ptlogin probe + de-magic process threshold (PR #73 follow-up)
PR #73's login-state probe shipped with issues:
- `fetchPtlogin` returned `Promise<any[]>`, tripping the repo's
  `@typescript-eslint/no-explicit-any` (error) and breaking `pnpm lint`.
  Modelled the read fields as a `PtloginUin` interface and cast the parsed
  JSONP to it.
- `tryPtloginMethod` had a dead `if` whose two branches both returned
  'fallback'; collapsed to a single return with a comment.
- The `< 6` QQ-process-count heuristic was a bare magic number (one copy
  annotated only with "13579 5个端口全部用光"). Extracted to
  `LOGGED_OUT_PROCESS_COUNT_MAX` with an explanation and reused in all three
  sites (incl. the error fallback).

Behaviour-preserving: the probing logic (Ptlogin parse, deep-link fallback,
PID port discovery) is unchanged — only typing and the magic constant.
2026-05-31 22:33:22 +08:00
H3CoF6 b3749560c8 New implement for QQ status detection 2026-05-31 04:51:54 +08:00
DrSmoothl ad081e2149 chore(release): v1.9.3 2026-05-30 20:53:45 +08:00
DrSmoothl 5924346823 chore(release): v1.9.2 2026-05-24 18:01:50 +08:00
手瓜一十雪 afbec8ed44 Cleanup imports and formatting in bridge
Reorder and tidy imports, re-export types, and apply minor formatting fixes across the bridge package. Changes include:

- Reordered imports and grouped related imports in hook-manager, hook-session, pipe-watcher, qq-hook-client, qq-port-probe and others.
- Moved several type re-exports (HookProcessBaseInfo, QqPortLoginInfo, HookProcessInfo/Status) in hook-manager and consolidated exports in package entry index.ts.
- Minor whitespace/style tweaks: constructor spacing, for-loop formatting, empty catch handlers, and small refactors that do not change runtime behavior.

These are non-functional housekeeping changes to improve consistency and readability.
2026-05-24 13:14:36 +08:00
DrSmoothl f53df5e313 refactor(packages): extract @snowluma/bridge (hook + QQ lifecycle)
Split the QQ NT client lifecycle / hook injection layer out of
@snowluma/core into its own self-contained package. The new bridge
package owns:
  - native hook addon loader (injector)
  - HookManager + per-PID HookSession orchestration
  - PipeWatcher for QQ process discovery
  - QqHookClient pipe protocol
  - qq-port-probe for early UIN sniffing

The hook layer used to type its main collaborator as
`BridgeManager` directly. To keep the new package free of any
dependency on @snowluma/core, the cross-package coupling is now
expressed via a 3-method `BridgeManagerSink` interface that lives
in the bridge package. BridgeManager (in core) satisfies the
interface structurally with no source changes; the top-level
app/webui still inject it the same way.

Pure file relocation otherwise: git mv preserves history at 100%
on every file, the only logic edit is the interface introduction
in hook-manager.ts and an updated `nativeSearchDirs()` offset
(one fewer `..` since hook now lives at packages/bridge/src
instead of packages/core/src/hook).
2026-05-23 23:40:57 +08:00
DrSmoothl c16064d7e3 refactor(packages): rename @snowluma/bridge → @snowluma/protocol
The package previously named "bridge" houses the protocol-byte layer
(OIDB cmds, msg-push decoders, highway uploaders, element-builder,
event bus). The name "bridge" suggested transport/lifecycle, which it
isn't — that role lives in core/hook and core/bridge/manager. Rename
to match what's actually inside.

This is a pure rename: zero logic changes, all 73 import sites updated
mechanically and TS-verified. core/onebot dependencies key updated.
ESLint override path adjusted for the moved oidb-services directory.

Rename detection threshold: git log --find-renames=20% recommended
when following history across this commit — content-replacement
(@snowluma/bridge → @snowluma/protocol) dropped per-file similarity
below git's default 50% on import-heavy files.
2026-05-23 23:31:03 +08:00
DrSmoothl 98296fcec5 fix(send-like): update serialization to resolve user UID and adjust payload structure 2026-05-23 22:50:40 +08:00
DrSmoothl d8c72c2ebc fix(events): surface verify-text on group_invite ("你们好" → comment)
User report:
  SnowLuma's group_invite event renders to OneBot with empty
  `comment`, so the bot's approval-prompt template shows nickname
  + uin + flag but loses the requester's verify message.

  NapCat's same flow shows the verify text:
    【进群申请】批准/驳回:
    昵称:KitaIkuyo
    QQ:1957003260
    flag:1779543612823906
    等级:7
    你们好               ← only NapCat shows this line

Root cause:
  The OIDB push (GroupRequestJoinNotice subType=84) only carries
  `(groupUin, targetUid)` and a few opaque numeric fields — no
  string for the verify text. NapCat doesn't use the push directly;
  they poll `nodeIKernelGroupService.getGroupNotifies` (= our OIDB
  0x10C0 pending-request queue at `FetchGroupRequests`) which
  returns each pending row with `postscript` (the verify text) and
  `seq` (server sequence id). Reference:
    dev/NapCatQQ/packages/napcat-onebot/index.ts:483-498
    (`flag = notify.seq`, `comment = notify.postscript`).

  Our pipeline didn't enrich. The decoder set `message: ''` and
  emitted, so OneBot's `comment` was empty.

Fix:
  - Extend `PacketPipelineDeps` with a `resolveGroupJoinRequest(
    groupId, uid, subType)` hook. Bridge.ts wires it to
    `fetchGroupRequests` and matches on `(groupId, uid)` —
    targetUid for `subType='add'`, invitorUid for
    `subType='invite'`.
  - `dispatchAfterStrangerResolve` now fires the profile + request
    lookups in PARALLEL via `Promise.allSettled` so a flake on one
    path doesn't kill the other. The request lookup's `comment`
    lands on `event.message`; OneBot converts that to `comment`.

Decisions:
  - Kept the existing `add:<groupId>:<uid>` flag format (consumer
    bots already parse it). Switching to NapCat's sequence-form
    flag would break callers and is a separate breaking change.
  - Both lookups fail-open: if either rejects, the event still
    emits with whatever info we did get, so the bot at least sees
    the request and can render the bare nickname.

Regression tests:
  - `populates event.message from the pending-request queue` — pins
    the user-reported "你们好" case end-to-end through the pipeline.
  - `runs lookups in parallel` — profile resolves, request fails;
    event still ships with the resolved uin and an empty message.
  - `invite subtype matches the request on invitorUid` — explicit
    contract for the invite-forwarded-to-admin case where the
    pending row's REQUESTER is `invitorUid`, not `targetUid`.

345 bridge tests pass (was 342 + 3 new); typecheck + lint clean.
2026-05-23 22:00:14 +08:00
DrSmoothl 8631453940 fix(events): self-heal group_invite cache pollution from pre-fix builds
User report: after [a4909ec], log STILL shows
  群邀请 950929451 -> [bot group(950929451)]
  get_stranger_info params=user_id=950929451 → 未知昵称

But NapCat and a sibling SnowLuma bot in the same group BOTH decoded
the same push as `QQ:1957003260 nickname:KitaIkuyo`. So the wire is
correct — our bot is just looking it up wrong.

Root cause: **legacy cache pollution**. The pre-fix decoder fallback
stored `<requester_uid> → <groupUin>` in the identity DB whenever
`resolveUidToUin` missed (because the fallback `ctx.fromUin` on a
group-scoped push IS the group's own uin). After upgrading to
[a4909ec], `decodeGroupJoinRequest` calls `resolveUidToUin` which
hits the polluted in-memory map (re-populated from SQLite at boot)
and returns the groupUin instead of 0. The new `needsStrangerResolve`
guard only fired on `fromUin <= 0` — so the polluted value flowed
straight through and re-emitted the bug.

Two-part heal:

  1. `needsStrangerResolve` now ALSO fires when `fromUin === groupId`
     — the pollution signature. A real requester's uin can never
     equal the group's own uin, so this is a safe override that
     forces the async UID-form FetchUserProfile lookup, which then
     `rememberUidUin`s the correct mapping on success (eviction is
     already wired in identity-service.ts:468-471).

  2. `rememberEventIdentity` for group_invite now passes `uin: 0`
     when `event.fromUin === event.groupId`, so future writes don't
     re-pollute the cache (`rememberUidUin` short-circuits on
     normalized uin ≤ 0).

Cache self-heals on first event after upgrade — no manual DB nuke
needed.

Regression test pins the legacy-pollution path: feeds an event
where `fromUin === groupId` (matching the user's log), verifies the
resolver fires and patches fromUin to the correct value.
2026-05-23 18:40:01 +08:00
DrSmoothl a4909ec9e5 fix(events): resolve stranger nickname on group_invite (no more 未知昵称)
User report: when a stranger requests to join a group, the bot
receives `user_id=<groupId>` (instead of the requester's actual
uin) and `get_stranger_info` returns no nickname → bot displays
"未知昵称".

Two layered bugs:

  1. **Decoder fallback was wrong.** `decodeGroupJoinRequest` /
     `decodeGroupInvitation` / `decodeGroupInvite` all passed
     `ctx.fromUin` as the fallback uin when `resolveUidToUin` missed
     the local cache. But for group-scoped pushes `ctx.fromUin` is
     the GROUP's own uin — falling back to it produces the bogus
     `fromUin === groupId` collision the user saw. Fix: pass 0.

  2. **No async resolve for stranger UIDs.** The push only carries
     the requester's UID string. When the UID isn't in our cache
     (true for any stranger who isn't yet a group member), we have
     no UIN — and our UIN-form `FetchUserProfile` can't help. The
     pipeline never tried to look up the stranger by UID, so the
     event went out with `fromUin=0` (or, with the old fallback,
     the group's own uin).

Cross-checked against Lagrange.Core's flow:

  dev/Lagrange.Core/.../MessagingLogic.cs:215-224
    case GroupSysRequestJoinEvent join:
        var fetchUidEvent = FetchUserInfoEvent.Create(join.TargetUid);
        var results = await Collection.Business.SendEvent(fetchUidEvent);
        uint targetUin = results.Count == 0 ? 0
            : ((FetchUserInfoEvent)results[0]).UserInfo.Uin;
        var joinArgs = new GroupJoinRequestEvent(join.GroupUin, targetUin);

  dev/Lagrange.Core/.../OidbSvcTrpcTcp0xFE1_2.cs:9-26
    — UID-form variant of the same OIDB 0xFE1_2: field 1 is `uid:
      string`, envelope `reserved=0` (no uinForm flag).

  dev/Lagrange.Core/.../FetchUserInfoService.cs:66-78
    — picks UID vs UIN form based on which input is set.

Changes:

  - `proto-defs/oidb-actions/base.ts`: add `OidbUserInfoByUidRequest`
    (same shape as the UIN variant but field 1 is `uid: string`).
  - `bridge/oidb-services/contacts/fetch-user-profile-by-uid.ts`:
    new namespace at 0xFE1_2 with UID-form encoding, no `uinForm`.
  - `bridge/msg-push/decoders/group-join-request.ts`: 3 decoders'
    `resolveUidToUin` fallbacks change `ctx.fromUin` → 0.
  - `bridge/packet-pipeline.ts`: new `resolveStrangerProfile(uid)`
    dep + `needsStrangerResolve` check + async dispatch that fires
    the lookup before emitting the event. Fail open if the lookup
    rejects (event still ships with `fromUin=0` so the OneBot bot
    can fall back to the uid in the flag).
  - `core/bridge/apis/contacts.ts`: `fetchUserProfileByUid(uid)`
    facade method.
  - `core/bridge/bridge.ts`: wire `resolveStrangerProfile` into the
    pipeline deps so it routes through the new namespace.

Tests:
  - UID-form namespace: declares the right cmd/subcmd, packages uid
    as field 1, decodes nickname + uin so the pipeline patch works.
  - Pipeline stranger resolve: patches event.fromUin from the
    resolver response; fails open on null / throw; skips the wire
    call when fromUin is already populated or fromUid is empty.

All 655 tests pass (was 645 + 10 new); typecheck + lint clean.
2026-05-23 17:15:59 +08:00
DrSmoothl 4755a91cb3 fix(image): use Chinese summary defaults to match QQ ecosystem
Mobile QQ, Lagrange.Core, and NapCat all use the literal Chinese
bubble-preview strings `[图片]` / `[动画表情]`. SnowLuma was emitting
English `[image]` / `[sticker]` as fallback, so QQ clients showed
"[image]" in chat-list previews instead of the expected Chinese.

Cross-checked against:
  dev/NapCatQQ/.../packet/message/element.ts:367-371
  dev/Lagrange.Core/.../Message/Entity/ImageEntity.cs:186-192

Both branch the same way: subType=1 → `[动画表情]`, else → `[图片]`.

Changes:
  - `bridge/highway/image-upload.ts`: both code paths (fingerprint +
    load-from-source) now emit the Chinese defaults. Subtype branch
    flipped to `subType === 1 ? '[动画表情]' : '[图片]'` to match the
    upstream convention (our old check was `subType === 0` →
    `[image]`, which would label any non-zero subType — not just
    stickers — as `[sticker]`).
  - `bridge/msg-push/rich-body-decoder.ts`: all three decode paths
    (NotOnlineImage / CustomFace / commonElem image) now substitute
    the Chinese default when the server omits `textSummary`. Empty-
    string is also treated as missing (matches NapCat's `=== ''`).
  - Tests updated to assert the Chinese defaults; new test pins
    that a caller-supplied summary still overrides verdef.

The OneBot caller's `summary` field on the MessageElement still
wins when set, so downstream clients passing custom bubble text
(e.g. for accessibility) keep working.
2026-05-23 15:05:28 +08:00