From f6ca9d5f6535b65e189b4a7022e8e47e2a82b31f Mon Sep 17 00:00:00 2001 From: H3CoF6 <1707889225@qq.com> Date: Sun, 18 Oct 2026 12:10:37 +0800 Subject: [PATCH] feat(bridge): detect local QQ accounts with shared process snapshots (#525) Read QQ account databases and attribute identities to their owning processes. Share snapshots across REST, watcher updates and login reconciliation, discard stale results, and report detection failures. --- AGENTS.md | 3 +- packages/bridge/package.json | 9 +- packages/bridge/src/hook-manager.ts | 161 +++- packages/bridge/src/hook-session.ts | 108 +-- packages/bridge/src/index.ts | 3 +- packages/bridge/src/injector.ts | 1 + packages/bridge/src/qq-account/db-lock.ts | 98 +++ packages/bridge/src/qq-account/detect.ts | 62 ++ packages/bridge/src/qq-account/index.ts | 22 + packages/bridge/src/qq-account/login-db.ts | 199 +++++ packages/bridge/src/qq-account/paths.ts | 161 ++++ packages/bridge/src/qq-account/sqlcipher.ts | 461 +++++++++++ packages/bridge/src/qq-port-probe.ts | 293 ------- packages/bridge/src/types.ts | 8 + .../tests/hook-manager-state-notify.test.ts | 209 ++++- packages/bridge/tests/hook-manager.test.ts | 42 + .../tests/hook-reconnect-no-login-e2e.test.ts | 1 + packages/bridge/tests/hook-session.test.ts | 89 ++- .../bridge/tests/qq-account-db-lock.test.ts | 123 +++ .../bridge/tests/qq-account-detect.test.ts | 241 ++++++ packages/bridge/tests/qq-account-fixtures.ts | 195 +++++ .../bridge/tests/qq-account-login-db.test.ts | 246 ++++++ .../tests/qq-account-path-isolation.test.ts | 51 ++ .../bridge/tests/qq-account-paths.test.ts | 106 +++ .../bridge/tests/qq-account-real-data.test.ts | 30 + .../bridge/tests/qq-account-sqlcipher.test.ts | 324 ++++++++ .../bridge/tests/qq-port-probe-more.test.ts | 724 ------------------ packages/bridge/tests/qq-port-probe.test.ts | 77 -- packages/core/src/webui/server.ts | 24 - packages/webui/README.md | 12 + .../src/components/pages/processes-page.tsx | 125 ++- .../src/components/process-probe-dialog.tsx | 190 ----- packages/webui/src/lib/api/client.ts | 4 - packages/webui/src/lib/api/types.ts | 1 - packages/webui/src/types.ts | 6 + .../webui/tests/api-client-timeout.test.ts | 25 +- packages/webui/tests/processes-page.test.tsx | 76 ++ pnpm-lock.yaml | 3 + 38 files changed, 2979 insertions(+), 1534 deletions(-) create mode 100644 packages/bridge/src/qq-account/db-lock.ts create mode 100644 packages/bridge/src/qq-account/detect.ts create mode 100644 packages/bridge/src/qq-account/index.ts create mode 100644 packages/bridge/src/qq-account/login-db.ts create mode 100644 packages/bridge/src/qq-account/paths.ts create mode 100644 packages/bridge/src/qq-account/sqlcipher.ts delete mode 100644 packages/bridge/src/qq-port-probe.ts create mode 100644 packages/bridge/tests/qq-account-db-lock.test.ts create mode 100644 packages/bridge/tests/qq-account-detect.test.ts create mode 100644 packages/bridge/tests/qq-account-fixtures.ts create mode 100644 packages/bridge/tests/qq-account-login-db.test.ts create mode 100644 packages/bridge/tests/qq-account-path-isolation.test.ts create mode 100644 packages/bridge/tests/qq-account-paths.test.ts create mode 100644 packages/bridge/tests/qq-account-real-data.test.ts create mode 100644 packages/bridge/tests/qq-account-sqlcipher.test.ts delete mode 100644 packages/bridge/tests/qq-port-probe-more.test.ts delete mode 100644 packages/bridge/tests/qq-port-probe.test.ts delete mode 100644 packages/webui/src/components/process-probe-dialog.tsx create mode 100644 packages/webui/tests/processes-page.test.tsx diff --git a/AGENTS.md b/AGENTS.md index b67638a3..f8ccc63b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,7 +16,7 @@ This is a pnpm workspace. Package ownership matters more than directory names: | Location | Responsibility | | --- | --- | | `packages/core` | Application entry, per-account Bridge orchestration, WebUI backend, notifications, release assembly | -| `packages/bridge` | QQ process discovery, Hook sessions, native transport lifecycle | +| `packages/bridge` | QQ process discovery, local account/login detection, Hook sessions, native transport lifecycle | | `packages/protocol` | Packet decoding, typed QQ events, identity resolution, protocol requests and media transfers | | `packages/onebot` | Action validation and dispatch, event conversion, message storage, HTTP/WebSocket adapters | | `packages/common` | Shared logging, configuration and utilities without business dependencies | @@ -38,6 +38,7 @@ Read the relevant owner before changing a path: | Change | Start here | | --- | --- | | Connection or account lifecycle | [Hook manager](packages/bridge/src/hook-manager.ts), [Bridge manager](packages/core/src/bridge/manager.ts), [OneBot instance](packages/onebot/src/instance.ts) | +| Which account a QQ process is signed in as | [Account detection](packages/bridge/src/qq-account/detect.ts), [login.db reader](packages/bridge/src/qq-account/login-db.ts), [QQ data paths](packages/bridge/src/qq-account/paths.ts) | | Incoming QQ events or identity | [Packet pipeline](packages/protocol/src/packet-pipeline.ts), [message decoders](packages/protocol/src/msg-push/index.ts), [identity service](packages/protocol/src/identity-service.ts) | | OneBot actions or message segments | [Action definitions](packages/onebot/src/actions/index.ts), [validation helpers](packages/onebot/src/action-kit.ts), [event conversion](packages/onebot/src/event-converter/index.ts) | | WebUI | [Interaction conventions](packages/webui/README.md), `packages/webui/src`, `packages/core/src/webui` | diff --git a/packages/bridge/package.json b/packages/bridge/package.json index 7285f97c..1a38e886 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -40,9 +40,9 @@ "types": "./src/qq-hook-client.ts", "default": "./src/qq-hook-client.ts" }, - "./qq-port-probe": { - "types": "./src/qq-port-probe.ts", - "default": "./src/qq-port-probe.ts" + "./qq-account": { + "types": "./src/qq-account/index.ts", + "default": "./src/qq-account/index.ts" }, "./types": { "types": "./src/types.ts", @@ -54,7 +54,8 @@ "typecheck": "tsc --noEmit" }, "dependencies": { - "@snowluma/common": "workspace:*" + "@snowluma/common": "workspace:*", + "@snowluma/sqlite": "workspace:*" }, "devDependencies": { "@types/node": "catalog:", diff --git a/packages/bridge/src/hook-manager.ts b/packages/bridge/src/hook-manager.ts index 82b713d3..2d6ee817 100644 --- a/packages/bridge/src/hook-manager.ts +++ b/packages/bridge/src/hook-manager.ts @@ -14,11 +14,13 @@ import { import { PipeWatcher } from './pipe-watcher'; import { createNativeProcessEnumerator, type ProcessEnumerator } from './process-enumerator'; import { QqHookClient } from './qq-hook-client'; -import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe'; -import type { HookProcessInfo } from './types'; +import { detectAccountLoginsForPids, type AccountLoginState } from './qq-account'; +import type { HookProcessAccount, HookProcessInfo } from './types'; const AUTO_LOAD_MAX_ATTEMPTS = 3; +const DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS = 5000; + type AutoLoadAttempt = { attempts: number; inFlight: boolean; @@ -54,6 +56,14 @@ export type HookManagerDeps = { watcherIntervalMs?: number; /** Native process lister used by `listProcesses()`. Defaults to the native addon. */ listProcesses?: () => HookProcessBaseInfo[]; + /** Local account detection used to label each process with the account QQ is + * signed in as. Receives the pids to label so each one is resolved against + * the HOME it actually runs under (a container can give every QQ instance + * its own). Defaults to reading QQ's own account data. */ + detectAccounts?: (pids: readonly number[]) => Promise; + /** How often the watcher re-probes the account label of each process, in + * milliseconds. Defaults to `DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS`. */ + accountReprobeIntervalMs?: number; /** When true, every newly-discovered QQ process is auto-injected (fires * `loadProcess(pid)` from the watcher's 'process-discovered' handler). * Failed loads are logged and leave the session in the 'error' state. @@ -101,6 +111,8 @@ export class HookManager { /** The owned enumerator (worker lifecycle), or null when a custom lister was * injected (tests) — nothing to tear down in that case. */ private readonly enumerator: ProcessEnumerator | null; + private readonly detectAccounts: (pids: readonly number[]) => Promise; + private readonly accountReprobeIntervalMs: number; private readonly autoLoadOnDiscovery: boolean; private readonly onSessionsChangedRaw?: () => void; private readonly log: Logger; @@ -108,6 +120,11 @@ export class HookManager { private readonly autoLoadAttempts = new Map(); private readonly startPromise: Promise; + private accounts = new Map(); + private accountProbe: Promise | null = null; + private nextAccountProbeAt = 0; + private lastAccountProbeFailure = ''; + private disposed = false; constructor(deps: HookManagerDeps) { @@ -127,6 +144,9 @@ export class HookManager { }, }; this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid)); + this.detectAccounts = deps.detectAccounts ?? detectAccountLoginsForPids; + this.accountReprobeIntervalMs = + deps.accountReprobeIntervalMs ?? DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS; this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false; // A custom lister (tests) is used directly — no worker, no isolation, just @@ -177,22 +197,20 @@ export class HookManager { async listProcesses(): Promise { await this.startPromise; const processes = await this.enumerate(); - - if (processes === null) { - // Enumeration timed out / failed — report the last-known sessions rather - // than an empty list (which the WebUI would render as "no QQ"). - return [...this.sessions.values()].map((s) => s.toInfo()).sort((a, b) => a.pid - b.pid); - } - - const result: HookProcessInfo[] = []; - - for (const proc of processes) { - const session = this.ensureSession(proc.pid); - session.attachProcessInfo(proc); - result.push(session.toInfo()); - } - - return result.sort((a, b) => a.pid - b.pid); + // A failed enumeration preserves the last known process set. + const sessions = + processes === null + ? [...this.sessions.values()] + : processes.map((proc) => { + const session = this.ensureSession(proc.pid); + session.attachProcessInfo(proc); + return session; + }); + await this.refreshAccounts(); + return sessions + .filter((session) => this.sessions.get(session.pid) === session) + .map((session) => this.processInfo(session)) + .sort((a, b) => a.pid - b.pid); } async loadProcess(pid: number): Promise { @@ -200,11 +218,10 @@ export class HookManager { await this.startPromise; this.autoLoadAttempts.delete(pid); const session = this.ensureSession(pid); - const info = await session.load(); - // Pull the next tick forward so a freshly-injected pipe gets noticed - // within the next event-loop turn instead of after the full interval. + await session.load(); this.pipeWatcher.wake(); - return info; + await this.refreshAccounts(); + return this.processInfo(session); } async unloadProcess(pid: number): Promise { @@ -212,19 +229,18 @@ export class HookManager { await this.startPromise; this.autoLoadAttempts.delete(pid); const session = this.ensureSession(pid); - return session.unload(); + await session.unload(); + await this.refreshAccounts(); + return this.processInfo(session); } async refreshProcess(pid: number): Promise { this.assertValidPid(pid); await this.startPromise; const session = this.ensureSession(pid); - return session.refresh(); - } - - async probeProcessLoginInfo(pid: number): Promise { - this.assertValidPid(pid); - return probeQqLoginInfo(pid); + await session.refresh(); + await this.refreshAccounts(); + return this.processInfo(session); } dispose(): void { @@ -239,6 +255,7 @@ export class HookManager { } this.sessions.clear(); + this.accounts.clear(); this.autoLoadAttempts.clear(); this.enumerator?.dispose(); @@ -249,6 +266,80 @@ export class HookManager { // ─────────────── wiring ─────────────── + private processInfo(session: HookSession): HookProcessInfo { + return { ...session.toInfo(), account: this.accounts.get(session.pid) ?? null }; + } + + /** REST, watcher ticks and login reconciliation share the same account snapshot. */ + private async refreshAccounts(): Promise { + if (this.disposed) { + return; + } + + if (this.accountProbe) { + await this.accountProbe; + + // Process discovery invalidates the snapshot while a read is in flight. + if (this.nextAccountProbeAt === 0) { + await this.refreshAccounts(); + } + + return; + } + + if (Date.now() < this.nextAccountProbeAt || this.sessions.size === 0) { + return; + } + + this.nextAccountProbeAt = Date.now() + this.accountReprobeIntervalMs; + this.accountProbe = runWithTraceRequest(() => this.readAccounts()).finally(() => { + this.accountProbe = null; + }); + await this.accountProbe; + } + + private async readAccounts(): Promise { + const sessions = new Map(this.sessions); + const accounts = new Map(); + + try { + for (const state of await this.detectAccounts([...sessions.keys()])) { + if ( + state.pid !== null && + sessions.has(state.pid) && + this.sessions.get(state.pid) === sessions.get(state.pid) + ) { + accounts.set(state.pid, { uin: state.uin, nickname: state.nickname }); + } + } + + this.lastAccountProbeFailure = ''; + } catch (error) { + const message = errMsg(error); + + if (this.lastAccountProbeFailure !== message) { + this.lastAccountProbeFailure = message; + this.log.warn('account detection failed: %s', message); + } + } + + if (this.disposed) { + return; + } + + const changed = + accounts.size !== this.accounts.size || + [...accounts].some(([pid, account]) => { + const previous = this.accounts.get(pid); + return previous?.uin !== account.uin || previous.nickname !== account.nickname; + }); + this.accounts = accounts; + + if (changed) { + this.notifySessionsChanged(); + } + } + private bindWatcher(): void { this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => { if (this.disposed) { @@ -338,6 +429,8 @@ export class HookManager { return; } + void this.refreshAccounts(); + for (const session of this.sessions.values()) { const autoLoad = this.autoLoadAttempts.get(session.pid); @@ -500,6 +593,10 @@ export class HookManager { makeClient: this.makeClient, pipeWatcher: this.pipeWatcher, onPacket: this.onPacket, + detectLoginUin: async () => { + await this.refreshAccounts(); + return this.accounts.get(pid)?.uin ?? null; + }, log: this.log, }); session.attachProcessInfo({ name: defaultProcessName() }); @@ -523,9 +620,12 @@ export class HookManager { }); session.on('disposed', () => { this.sessions.delete(pid); + this.accounts.delete(pid); + this.nextAccountProbeAt = 0; }); this.sessions.set(pid, session); + this.nextAccountProbeAt = 0; return session; } @@ -612,5 +712,4 @@ export function shouldAutoLoadPid(pid: number, log: Logger): boolean { } export type { HookProcessBaseInfo } from './injector'; -export type { QqPortLoginInfo } from './qq-port-probe'; -export type { HookProcessInfo, HookProcessStatus } from './types'; +export type { HookProcessAccount, HookProcessInfo, HookProcessStatus } from './types'; diff --git a/packages/bridge/src/hook-session.ts b/packages/bridge/src/hook-session.ts index ca4b1e2f..09e6074b 100644 --- a/packages/bridge/src/hook-session.ts +++ b/packages/bridge/src/hook-session.ts @@ -10,8 +10,8 @@ import { isRealUin } from '@snowluma/common/uin'; import { EventEmitter } from 'events'; import { HookPacketClient } from './hook-packet-client'; import type { HookInjectResult } from './injector'; +import { detectUinForPid } from './qq-account'; import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client'; -import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe'; import { statusFor } from './hook-status'; import type { HookProcessInfo, HookProcessStatus } from './types'; @@ -36,10 +36,10 @@ export type HookSessionDeps = { unload: (pid: number, handle: HookInjectResult['handle']) => void; }; makeClient: (pid: number) => QqHookClient; - /** Active, pipe-independent login probe (reads QQ's ptlogin/deeplink ports). - * Drives the login-reconcile safety net; injectable for tests. Defaults to - * `probeQqLoginInfo`. */ - probeLogin?: (pid: number) => Promise; + /** Account QQ's local data reports as signed in on `pid`, or null. Drives the + * login-reconcile safety net; injectable for tests. Defaults to + * `detectUinForPid`. */ + detectLoginUin?: (pid: number) => Promise; /** Sync fast-path check used by load() to skip re-injection when a * prior SnowLuma run left a working pipe behind. `tickNow` forces a * fresh poll — used after unload to dodge the up-to-1500ms cache @@ -80,7 +80,7 @@ export class HookSession extends EventEmitter { private readonly injector: HookSessionDeps['injector']; private readonly makeClient: HookSessionDeps['makeClient']; - private readonly probeLogin: (pid: number) => Promise; + private readonly detectLoginUin: (pid: number) => Promise; private readonly pipeWatcher: HookSessionDeps['pipeWatcher']; private readonly onPacket: PacketSink | null; private readonly log: Logger; @@ -101,9 +101,9 @@ export class HookSession extends EventEmitter { private bound = false; private opChain: Promise = Promise.resolve(); private disposed = false; - private loginProbeTimer: ReturnType | null = null; - private probing = false; - private lastProbeFailure = ''; + private loginReconcileTimer: ReturnType | null = null; + private detecting = false; + private lastDetectFailure = ''; private acceptedLoginHintUin = ''; private loginHintAttemptUin = ''; private loginHintAttempts = 0; @@ -121,7 +121,7 @@ export class HookSession extends EventEmitter { this.pid = pid; this.injector = deps.injector; this.makeClient = deps.makeClient; - this.probeLogin = deps.probeLogin ?? probeQqLoginInfo; + this.detectLoginUin = deps.detectLoginUin ?? detectUinForPid; this.pipeWatcher = deps.pipeWatcher; this.onPacket = deps.onPacket ?? null; this.log = deps.log ?? createLogger('HookSession'); @@ -170,6 +170,8 @@ export class HookSession extends EventEmitter { status: this._status, error: this._error, method: this._method, + // Filled in by HookManager from the client's local account data. + account: null, }; } @@ -636,7 +638,7 @@ export class HookSession extends EventEmitter { this.applyStatus(); // The native hook only PUSHES a loginState frame on the login edge; // if QQ logged in before/around connect (Docker auto-login) that edge - // is missed and we'd wait forever. Actively re-probe until logged in. + // is missed and we'd wait forever. Keep re-detecting until logged in. runWithoutRequestContext(() => this.startLoginReconcile()); } @@ -796,39 +798,41 @@ export class HookSession extends EventEmitter { } // ─────────────── login reconcile (Docker auto-login safety net) ─────────── - // The local endpoint can identify an auto-restored account before the - // runtime is ready. Forward identity for reconciliation, but never synthesize - // online state from the probe. + // QQ can restore an account on its own before the runtime is ready, and its + // local account data names that account. Forward the identity for + // reconciliation, but never synthesize online state from the detection. private startLoginReconcile(): void { - if (this.loginProbeTimer || this.disposed) { + if (this.loginReconcileTimer || this.disposed) { return; } this.log.info('awaiting login: PID=%d', this.pid); - void this.probeLoginOnce(); // immediate — catch already-logged-in fast - this.loginProbeTimer = setInterval( - () => void this.probeLoginOnce(), + void this.detectLoginOnce(); // immediate — catch already-logged-in fast + this.loginReconcileTimer = setInterval( + () => void this.detectLoginOnce(), LOGIN_RECONCILE_INTERVAL_MS, ); - this.loginProbeTimer.unref?.(); + this.loginReconcileTimer.unref?.(); } private stopLoginReconcile(): void { - if (this.loginProbeTimer) { - clearInterval(this.loginProbeTimer); - this.loginProbeTimer = null; + if (this.loginReconcileTimer) { + clearInterval(this.loginReconcileTimer); + this.loginReconcileTimer = null; } } - private async probeLoginOnce(): Promise { - // A port-scan probe can outlast the interval; skip overlapping ticks so a - // slow probe never stacks concurrent subprocess-spawning scans. - if (this.probing) { + private async detectLoginOnce(): Promise { + // Detecting the account reads the filesystem; skip overlapping ticks so a + // slow read never stacks on top of the interval. + if (this.detecting) { return; } - if (this.disposed || !this.connected || this.loggedIn) { + const client = this.client; + + if (this.disposed || !client || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; } @@ -837,46 +841,44 @@ export class HookSession extends EventEmitter { return; } - this.probing = true; + this.detecting = true; try { - let info: QqPortLoginInfo | null; + let uin: string | null; try { - info = await this.probeLogin(this.pid); + uin = await this.detectLoginUin(this.pid); } catch (error) { const message = errMsg(error); - const note = `${this.pid}:${message}`; - if (this.lastProbeFailure !== note) { - this.lastProbeFailure = note; - this.log.warn('login probe failed: PID=%d err=%s', this.pid, message); + if (this.lastDetectFailure !== message) { + this.lastDetectFailure = message; + this.log.warn( + 'login identity detection failed: PID=%d err=%s', + this.pid, + message, + ); } return; // best-effort; the interval retries } - // The await yielded — re-check we still want this before mutating state. - if (this.disposed || !this.connected || this.loggedIn) { - this.stopLoginReconcile(); + // A reconnect owns a new client; an older read cannot supply its identity. + if (this.client !== client || this.disposed || !this.connected || this.loggedIn) { return; } - if (info?.identityKnown && isRealUin(info.uin)) { - const client = this.client; + this.lastDetectFailure = ''; - if (!client) { - return; - } - - if (this.acceptedLoginHintUin === info.uin) { + if (uin !== null && isRealUin(uin)) { + if (this.acceptedLoginHintUin === uin) { this.nextLoginIdentityObservationAt = Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS; return; } - if (this.loginHintAttemptUin !== info.uin) { - this.loginHintAttemptUin = info.uin; + if (this.loginHintAttemptUin !== uin) { + this.loginHintAttemptUin = uin; this.loginHintAttempts = 0; this.nextLoginHintAt = 0; this.nextLoginIdentityObservationAt = 0; @@ -893,11 +895,11 @@ export class HookSession extends EventEmitter { this.log.info( 'login identity discovered: PID=%d UIN=%s; awaiting readiness', this.pid, - info.uin, + uin, ); try { - await client.reconcileLoginIdentity(info.uin); + await client.reconcileLoginIdentity(uin); if ( this.client !== client || @@ -908,7 +910,7 @@ export class HookSession extends EventEmitter { return; } - this.acceptedLoginHintUin = info.uin; + this.acceptedLoginHintUin = uin; this.nextLoginIdentityObservationAt = Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS; } catch (error) { @@ -920,7 +922,7 @@ export class HookSession extends EventEmitter { this.log.warn( 'login identity reconciliation failed: PID=%d UIN=%s attempts=%d err=%s', this.pid, - info.uin, + uin, attempt, errMsg(error), ); @@ -932,7 +934,7 @@ export class HookSession extends EventEmitter { this.log.trace( 'login identity hint failed: PID=%d UIN=%s attempt=%d err=%s', this.pid, - info.uin, + uin, attempt, errMsg(error), ); @@ -940,7 +942,7 @@ export class HookSession extends EventEmitter { } } } finally { - this.probing = false; + this.detecting = false; } } @@ -950,7 +952,7 @@ export class HookSession extends EventEmitter { this.loginHintAttempts = 0; this.nextLoginHintAt = 0; this.nextLoginIdentityObservationAt = 0; - this.lastProbeFailure = ''; + this.lastDetectFailure = ''; } private handlePacket(packet: QqHookPacket): void { diff --git a/packages/bridge/src/index.ts b/packages/bridge/src/index.ts index f204d34a..c2b4e170 100644 --- a/packages/bridge/src/index.ts +++ b/packages/bridge/src/index.ts @@ -2,11 +2,12 @@ export { HookManager, type BridgeManagerSink, type HookManagerDeps, + type HookProcessAccount, type HookProcessBaseInfo, type HookProcessInfo, type HookProcessStatus, - type QqPortLoginInfo, } from './hook-manager'; +export { type AccountLoginState, type LocalAccount } from './qq-account'; export { getRuntimeIntegrity, hasLowProcessIntegrity, diff --git a/packages/bridge/src/injector.ts b/packages/bridge/src/injector.ts index b5fe8864..25ba8d0f 100644 --- a/packages/bridge/src/injector.ts +++ b/packages/bridge/src/injector.ts @@ -16,6 +16,7 @@ export interface ManualMapHandle { interface NativeHookAddon { getRuntimeIntegrity?(): unknown; getAllMainProcess(): number[]; + probeDbLock?(dbPath: string): { pid: number; name: string }[]; loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise; unloadModuleManual(pid: number, handle: ManualMapHandle): void; } diff --git a/packages/bridge/src/qq-account/db-lock.ts b/packages/bridge/src/qq-account/db-lock.ts new file mode 100644 index 00000000..089d10be --- /dev/null +++ b/packages/bridge/src/qq-account/db-lock.ts @@ -0,0 +1,98 @@ +import fs from 'node:fs'; +import { getNativeHookAddon } from '../injector'; + +export interface DbLockHolder { + pid: number; + + name: string; +} + +export function probeDbLock(dbPath: string): DbLockHolder[] { + if (process.platform === 'win32') { + return probeWindowsHolders(dbPath); + } + + return process.platform === 'linux' ? probeLinuxLocks(dbPath) : []; +} + +function probeWindowsHolders(dbPath: string): DbLockHolder[] { + const addon = getNativeHookAddon(); + + if (!addon?.probeDbLock) { + throw new Error('Windows account detection requires a hook addon with probeDbLock'); + } + + const holders = addon.probeDbLock(dbPath); + + if ( + !Array.isArray(holders) || + holders.some( + (holder) => + !holder || + !Number.isInteger(holder.pid) || + holder.pid <= 0 || + typeof holder.name !== 'string', + ) + ) { + throw new Error('Invalid database holders returned by the hook addon'); + } + + return holders; +} + +export function isQqProcessName(name: string): boolean { + return ( + name + .trim() + .toLowerCase() + .replace(/\.exe$/, '') === 'qq' + ); +} + +/** Match POSIX locks by device and inode; the table does not contain file paths. */ +function probeLinuxLocks(dbPath: string): DbLockHolder[] { + const stat = fs.statSync(dbPath, { throwIfNoEntry: false }); + + if (!stat) { + return []; + } + + const key = deviceInodeKey(stat.dev, stat.ino); + const table = fs.readFileSync('/proc/locks', 'utf8'); + const holders: DbLockHolder[] = []; + const seen = new Set(); + + for (const line of table.split('\n')) { + // `: : ` + const fields = line.trim().split(/\s+/); + + if (fields.length < 8 || fields[5] !== key) { + continue; + } + + const pid = Number(fields[4]); + + if (!Number.isInteger(pid) || pid <= 0 || seen.has(pid)) { + continue; + } + + seen.add(pid); + holders.push({ pid, name: readProcessName(pid) }); + } + + return holders; +} + +function deviceInodeKey(device: number, inode: number): string { + const major = (device >> 8) & 0xfff; + const minor = (device & 0xff) | ((device >> 12) & 0xfff00); + return `${major.toString(16).padStart(2, '0')}:${minor.toString(16).padStart(2, '0')}:${inode}`; +} + +function readProcessName(pid: number): string { + try { + return fs.readFileSync(`/proc/${pid}/comm`, 'utf8').trim(); + } catch { + return ''; + } +} diff --git a/packages/bridge/src/qq-account/detect.ts b/packages/bridge/src/qq-account/detect.ts new file mode 100644 index 00000000..cf98ef26 --- /dev/null +++ b/packages/bridge/src/qq-account/detect.ts @@ -0,0 +1,62 @@ +import { createLogger } from '@snowluma/common/logger'; +import { isQqProcessName, probeDbLock } from './db-lock'; +import { readLocalAccounts, type LocalAccount } from './login-db'; +import { loginDbPaths, ntMsgDbPath, qqDataRoots, qqDataRootsForPid } from './paths'; + +const log = createLogger('QqAccount'); +const reportedFailures = new Map(); + +export interface AccountLoginState extends LocalAccount { + pid: number | null; +} + +export async function detectAccountLogins( + roots: readonly string[] = qqDataRoots(), +): Promise { + const states: AccountLoginState[] = []; + + for (const root of roots) { + const report = await readLocalAccounts(root); + + for (const dbPath of loginDbPaths(root)) { + const failure = report.failures.find((item) => item.path === dbPath); + + if (!failure) { + reportedFailures.delete(dbPath); + continue; + } + + const detail = + failure.error instanceof Error + ? failure.error.message + : String(failure.error ?? ''); + const reason = detail ? failure.reason + ': ' + detail : failure.reason; + + if (reportedFailures.get(dbPath) !== reason) { + reportedFailures.set(dbPath, reason); + log.warn('login.db unreadable: path=%s reason=%s', dbPath, reason); + } + } + + for (const account of report.accounts) { + const holder = probeDbLock(ntMsgDbPath(root, account)).find((candidate) => + isQqProcessName(candidate.name), + ); + states.push({ ...account, pid: holder?.pid ?? null }); + } + } + + return states; +} + +export async function detectAccountLoginsForPids( + pids: readonly number[], +): Promise { + const roots = [...new Set(pids.flatMap((pid) => qqDataRootsForPid(pid)))]; + return detectAccountLogins(roots); +} + +export async function detectUinForPid(pid: number): Promise { + const accounts = await detectAccountLoginsForPids([pid]); + return accounts.find((account) => account.pid === pid)?.uin ?? null; +} diff --git a/packages/bridge/src/qq-account/index.ts b/packages/bridge/src/qq-account/index.ts new file mode 100644 index 00000000..496d70c8 --- /dev/null +++ b/packages/bridge/src/qq-account/index.ts @@ -0,0 +1,22 @@ +export { isQqProcessName, probeDbLock, type DbLockHolder } from './db-lock'; +export { + detectAccountLogins, + detectAccountLoginsForPids, + detectUinForPid, + type AccountLoginState, +} from './detect'; +export { + readLocalAccounts, + type LocalAccount, + type LocalAccountReport, + type LoginDbFailure, +} from './login-db'; +export { accountDirName, loginDbPaths, ntMsgDbPath, qqDataRoots, qqDataRootsForPid } from './paths'; +export { + decryptDatabase, + detectAlgorithm, + type DecryptedDatabase, + type KdfHmacAlgorithm, + type PageHmacAlgorithm, + type SqlcipherAlgorithm, +} from './sqlcipher'; diff --git a/packages/bridge/src/qq-account/login-db.ts b/packages/bridge/src/qq-account/login-db.ts new file mode 100644 index 00000000..361b7d1f --- /dev/null +++ b/packages/bridge/src/qq-account/login-db.ts @@ -0,0 +1,199 @@ +import { isRealUin } from '@snowluma/common/uin'; +import { SqliteDatabase } from '@snowluma/sqlite'; +import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { loginDbPaths } from './paths'; +import { decryptDatabase, detectAlgorithm } from './sqlcipher'; + +const LOGIN_DB_PASSPHRASE = 'BD156D6710D54D8782F4'; +const COLUMN_UIN = '1000'; +const COLUMN_UID = '1001'; +const COLUMN_NICKNAME = '1007'; + +export interface LocalAccount { + uin: string; + uid: string; + nickname: string; +} + +export type LoginDbFailure = 'read-failed' | 'undecryptable' | 'query-failed'; + +type LoginDbResult = { accounts: LocalAccount[] } | { failure: LoginDbFailure; error?: unknown }; + +export interface LocalAccountReport { + accounts: LocalAccount[]; + failures: Array<{ path: string; reason: LoginDbFailure; error?: unknown }>; +} + +// Share concurrent reads and invalidate when either the database or its WAL changes. +const accountCache = new Map }>(); + +export async function readLocalAccounts(root: string): Promise { + const merged = new Map(); + const failures: LocalAccountReport['failures'] = []; + + for (const dbPath of loginDbPaths(root)) { + const result = await readLoginDb(dbPath); + + if ('failure' in result) { + failures.push({ path: dbPath, reason: result.failure, error: result.error }); + continue; + } + + for (const account of result.accounts) { + if (!merged.has(account.uin)) { + merged.set(account.uin, account); + } + } + } + + return { accounts: [...merged.values()], failures }; +} + +async function readLoginDb(dbPath: string): Promise { + let stamp: string; + + try { + const files = await Promise.all([statIfPresent(dbPath), statIfPresent(dbPath + '-wal')]); + stamp = files.map((info) => (info ? info.mtimeMs + ':' + info.size : '-')).join('|'); + } catch (error) { + accountCache.delete(dbPath); + return { failure: 'read-failed', error }; + } + + const cached = accountCache.get(dbPath); + + if (cached?.stamp === stamp) { + return cached.result; + } + + const entry = { stamp, result: decryptAndQuery(dbPath) }; + accountCache.set(dbPath, entry); + const result = await entry.result; + + if ('failure' in result && accountCache.get(dbPath) === entry) { + accountCache.delete(dbPath); + } + + return result; +} + +async function decryptAndQuery(dbPath: string): Promise { + let image: Buffer; + let wal: Buffer | null; + + try { + const contents = await readIfPresent(dbPath); + + if (!contents) { + return { accounts: [] }; + } + + image = contents; + wal = await readIfPresent(dbPath + '-wal'); + } catch (error) { + return { failure: 'read-failed', error }; + } + + const algorithm = detectAlgorithm(image, LOGIN_DB_PASSPHRASE); + + if (!algorithm) { + return { failure: 'undecryptable' }; + } + + const decrypted = decryptDatabase(image, wal, LOGIN_DB_PASSPHRASE, algorithm); + + if (!decrypted) { + return { failure: 'undecryptable' }; + } + + try { + return { accounts: await queryLoginTable(decrypted.image) }; + } catch (error) { + return { failure: 'query-failed', error }; + } +} + +// SQLite opens a private temporary image; QQ's database and sidecars stay read-only. +async function queryLoginTable(image: Buffer): Promise { + const directory = await mkdtemp(path.join(os.tmpdir(), 'snowluma-qq-login-')); + const dbPath = path.join(directory, 'login.db'); + + try { + await writeFile(dbPath, image, { mode: 0o600 }); + const db = new SqliteDatabase(dbPath, { readOnly: true }); + + try { + const rows = await db + .prepare( + `SELECT [${COLUMN_UIN}], [${COLUMN_UID}], [${COLUMN_NICKNAME}] FROM login_table`, + ) + .all(); + const accounts: LocalAccount[] = []; + + for (const row of rows) { + const account = { + uin: asText(row[COLUMN_UIN]), + uid: asText(row[COLUMN_UID]), + nickname: asText(row[COLUMN_NICKNAME]), + }; + + if (isRealUin(account.uin) && account.uid.length > 0) { + accounts.push(account); + } + } + + return accounts; + } finally { + await db.close(); + } + } finally { + await rm(directory, { recursive: true, force: true }); + } +} + +async function readIfPresent(file: string): Promise { + try { + return await readFile(file); + } catch (error) { + if (isNotFound(error)) { + return null; + } + + throw error; + } +} + +function isNotFound(error: unknown): boolean { + return error instanceof Error && 'code' in error && error.code === 'ENOENT'; +} + +async function statIfPresent(file: string) { + try { + return await stat(file); + } catch (error) { + if (isNotFound(error)) { + return null; + } + + throw error; + } +} + +/** SQLite values arrive as numbers, strings or blobs depending on the column. */ +function asText(value: unknown): string { + if (typeof value === 'string') { + return value; + } + + if (typeof value === 'number' || typeof value === 'bigint') { + return String(value); + } + + if (value instanceof Uint8Array) { + return Buffer.from(value).toString('utf8'); + } + + return ''; +} diff --git a/packages/bridge/src/qq-account/paths.ts b/packages/bridge/src/qq-account/paths.ts new file mode 100644 index 00000000..f848e4b2 --- /dev/null +++ b/packages/bridge/src/qq-account/paths.ts @@ -0,0 +1,161 @@ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import path from 'node:path'; + +const LOGIN_DB_SEGMENTS = ['nt_db', 'login.db'] as const; + +export function qqDataRoots(): string[] { + if (process.platform === 'win32') { + return windowsDataRoots(); + } + + if (process.platform === 'linux') { + return linuxDataRoots({ ...process.env, HOME: process.env.HOME || homedir() }); + } + + return []; +} + +/** Each Linux client owns its HOME; an unavailable process has no known root. */ +export function qqDataRootsForPid(pid: number): string[] { + if (process.platform === 'win32') { + return windowsDataRoots(); + } + + if (process.platform !== 'linux') { + return []; + } + + const environment = readProcessEnvironment(pid); + return environment ? linuxDataRoots(environment) : []; +} + +function linuxDataRoots(environment: { HOME?: string; XDG_CONFIG_HOME?: string }): string[] { + const base = + environment.XDG_CONFIG_HOME || + (environment.HOME ? path.join(environment.HOME, '.config') : null); + return base ? [path.join(base, 'QQ')] : []; +} + +function readProcessEnvironment(pid: number): { HOME?: string; XDG_CONFIG_HOME?: string } | null { + let raw: string; + + try { + raw = readFileSync(`/proc/${pid}/environ`, 'utf8'); + } catch (error) { + if (error instanceof Error && 'code' in error && error.code === 'ENOENT') { + return null; + } + + throw error; + } + + const environment: { HOME?: string; XDG_CONFIG_HOME?: string } = {}; + + for (const entry of raw.split('\0')) { + const separator = entry.indexOf('='); + + if (separator <= 0) { + continue; + } + + const name = entry.slice(0, separator); + + if (name === 'HOME' || name === 'XDG_CONFIG_HOME') { + environment[name] = entry.slice(separator + 1); + } + } + + return environment; +} + +/** Both Linux layouts occur in QQ installations; the primary takes precedence. */ +export function loginDbPaths(root: string): string[] { + if (process.platform === 'win32') { + return [path.join(root, 'nt_qq', 'global', ...LOGIN_DB_SEGMENTS)]; + } + + return [ + path.join(root, 'global', ...LOGIN_DB_SEGMENTS), + path.join(root, 'nt_qq', 'global', ...LOGIN_DB_SEGMENTS), + ]; +} + +export function ntMsgDbPath(root: string, account: { uin: string; uid: string }): string { + if (process.platform === 'win32') { + return path.join(root, account.uin, 'nt_qq', 'nt_db', 'nt_msg.db'); + } + + return path.join(root, accountDirName(account.uid), 'nt_db', 'nt_msg.db'); +} + +export function accountDirName(uid: string): string { + const digest = createHash('md5').update(uid, 'utf8').digest('hex'); + return `nt_qq_${createHash('md5').update(`${digest}nt_kernel`, 'utf8').digest('hex')}`; +} + +function windowsDataRoots(): string[] { + const configured = tencentFilesRootFromUserDataInfo(); + return [configured ?? path.join(homedir(), 'Documents', 'Tencent Files')]; +} + +export function tencentFilesRootFromUserDataInfo(home = homedir()): string | null { + const ini = path.join( + path.dirname(home), + 'Public', + 'Documents', + 'Tencent', + 'QQ', + 'UserDataInfo.ini', + ); + let text: string; + + try { + text = readFileSync(ini, 'utf8'); + } catch (error) { + if (error instanceof Error && 'code' in error && error.code === 'ENOENT') { + return null; + } + + throw error; + } + + let inDataSet = false; + + for (const raw of text.split(/\r?\n/)) { + const line = raw.trim(); + + if (line.startsWith('[') && line.endsWith(']')) { + inDataSet = line.toLowerCase() === '[userdataset]'; + continue; + } + + if (!inDataSet) { + continue; + } + + const separator = line.indexOf('='); + + if ( + separator === -1 || + line.slice(0, separator).trim().toLowerCase() !== 'userdatasavepath' + ) { + continue; + } + + const value = line.slice(separator + 1).trim(); + + if (value.length === 0) { + return null; + } + + // The ini always holds Windows paths, so resolve them with the win32 + // flavor wherever this runs. + return path.win32.basename(value).toLowerCase() === 'tencent files' + ? value + : path.win32.join(value, 'Tencent Files'); + } + + return null; +} diff --git a/packages/bridge/src/qq-account/sqlcipher.ts b/packages/bridge/src/qq-account/sqlcipher.ts new file mode 100644 index 00000000..0709c3fd --- /dev/null +++ b/packages/bridge/src/qq-account/sqlcipher.ts @@ -0,0 +1,461 @@ +/** + * SQLCipher v4 page decryption for QQ NT's local databases. + * + * QQ NT stores every database under `nt_db/` as a SQLCipher v4 stream behind a + * 1024-byte client header: + * + * [ 1024-byte client header ][ page 1 ][ page 2 ] ... + * ^ KDF salt = first 16 bytes of page 1 + * + * Each page ends with `IV (16 bytes) || page HMAC`, rounded up to the AES block + * size; the page size is 4096 on every database QQ writes. Page 1's ciphertext + * starts after its 16-byte salt, which replaces the plaintext "SQLite format 3" + * magic — so the decrypted body of page 1 starts at page offset 16 and can never + * contain that magic. A candidate key is therefore confirmed by recomputing the + * page HMAC over the *ciphertext*, which is independent of the AES pass. + * + * The page-HMAC and KDF-HMAC algorithms are not fixed across client builds, so + * they are probed per database (12 combinations) instead of assumed. + */ + +import { createDecipheriv, createHmac, pbkdf2Sync } from 'node:crypto'; + +/** QQ NT prepends this many bytes before the SQLCipher stream. */ +export const DATABASE_HEADER_SIZE = 1024; + +const PAGE_SIZE = 4096; +const SALT_SIZE = 16; +const IV_SIZE = 16; +const KEY_SIZE = 32; + +/** SQLCipher v4 derives the AES key with this many PBKDF2 iterations. */ +const KDF_ITERATIONS = 4000; +/** The per-page HMAC key uses a fast derivation over the page salt. */ +const HMAC_KEY_ITERATIONS = 2; +/** SQLCipher's HMAC salt is the page salt XOR this mask. */ +const HMAC_SALT_MASK = 0x3a; + +const WAL_HEADER_SIZE = 32; +const WAL_FRAME_HEADER_SIZE = 24; + +const SQLITE_MAGIC = Buffer.from('SQLite format 3\0', 'latin1'); + +export type PageHmacAlgorithm = 'none' | 'sha1' | 'sha256' | 'sha512'; +export type KdfHmacAlgorithm = 'sha1' | 'sha256' | 'sha512'; + +/** One SQLCipher algorithm pair, as probed against a database's page 1. */ +export interface SqlcipherAlgorithm { + pageHmac: PageHmacAlgorithm; + kdfHmac: KdfHmacAlgorithm; +} + +/** Every pair to probe, in order: `cipher_use_hmac = OFF` first, then each digest. */ +const PAGE_HMAC_ALGORITHMS: readonly PageHmacAlgorithm[] = ['none', 'sha1', 'sha256', 'sha512']; +const KDF_HMAC_ALGORITHMS: readonly KdfHmacAlgorithm[] = ['sha1', 'sha256', 'sha512']; + +const PAGE_HMAC_DIGEST_BYTES: Record = { + none: 0, + sha1: 20, + sha256: 32, + sha512: 64, +}; + +/** A database image decrypted from disk, with its `-wal` frames folded in. */ +export interface DecryptedDatabase { + /** A self-contained plaintext SQLite image (rollback-journal mode). */ + image: Buffer; + /** Frames folded in from the `-wal` sidecar, 0 when there was nothing to merge. */ + walFrames: number; +} + +/** + * Probe the algorithm pair of an encrypted database. + * + * Returns null when the page-1 HMAC matches no combination under `passphrase`, + * which means either the passphrase or the file layout is not what we expect. + */ +export function detectAlgorithm(image: Buffer, passphrase: string): SqlcipherAlgorithm | null { + const pageOne = readPageOne(image); + + if (!pageOne) { + return null; + } + + const salt = pageOne.subarray(0, SALT_SIZE); + + for (const pageHmac of PAGE_HMAC_ALGORITHMS) { + for (const kdfHmac of KDF_HMAC_ALGORITHMS) { + const algorithm: SqlcipherAlgorithm = { pageHmac, kdfHmac }; + const key = deriveKey(passphrase, salt, kdfHmac); + + if (verifyPageOne(pageOne, key, algorithm)) { + return algorithm; + } + } + } + + return null; +} + +/** + * Decrypt a whole database and fold in the `-wal` sidecar when there is one. + * + * QQ keeps a long-lived WAL, so everything committed since the last checkpoint + * — including an account that just signed in — lives only in the sidecar. + * Returns null when the image cannot be decrypted. + */ +export function decryptDatabase( + image: Buffer, + wal: Buffer | null, + passphrase: string, + algorithm: SqlcipherAlgorithm, +): DecryptedDatabase | null { + const pageOne = readPageOne(image); + + if (!pageOne) { + return null; + } + + const key = deriveKey(passphrase, pageOne.subarray(0, SALT_SIZE), algorithm.kdfHmac); + const base = decryptPages(image, key, algorithm); + + if (!base) { + return null; + } + + const merged = applyWal(base, wal, key, algorithm); + normalizeImage(merged.image); + return merged; +} + +/** Page 1 as stored, or null when the file is too short to hold a header + page 1. */ +function readPageOne(image: Buffer): Buffer | null { + if (image.length < DATABASE_HEADER_SIZE + PAGE_SIZE) { + return null; + } + + return image.subarray(DATABASE_HEADER_SIZE, DATABASE_HEADER_SIZE + PAGE_SIZE); +} + +/** Per-page reserve = IV + page HMAC digest, rounded up to the AES block size. */ +function reserveBytes(algorithm: SqlcipherAlgorithm): number { + const digestBytes = PAGE_HMAC_DIGEST_BYTES[algorithm.pageHmac]; + return Math.ceil((IV_SIZE + digestBytes) / 16) * 16; +} + +function deriveKey(passphrase: string, salt: Buffer, kdfHmac: KdfHmacAlgorithm): Buffer { + return pbkdf2Sync(passphrase, salt, KDF_ITERATIONS, KEY_SIZE, kdfHmac); +} + +/** + * Confirm a candidate key against page 1. + * + * With the page HMAC enabled the check runs over the stored ciphertext, exactly + * like SQLCipher's own verification. With HMAC off there is nothing to verify on + * the ciphertext, so page 1 is decrypted and the SQLite header fields that live + * past the salt-occupied first 16 bytes are checked instead. + */ +function verifyPageOne(pageOne: Buffer, key: Buffer, algorithm: SqlcipherAlgorithm): boolean { + const reserve = reserveBytes(algorithm); + const digestBytes = PAGE_HMAC_DIGEST_BYTES[algorithm.pageHmac]; + + if (digestBytes === 0) { + const body = decryptPageBody(pageOne, key, SALT_SIZE, reserve); + return body !== null && hasSqliteHeaderFields(body); + } + + const hmacSalt = Buffer.alloc(SALT_SIZE); + + for (let index = 0; index < SALT_SIZE; index++) { + hmacSalt[index] = pageOne[index] ^ HMAC_SALT_MASK; + } + + const hmacKey = pbkdf2Sync(key, hmacSalt, HMAC_KEY_ITERATIONS, KEY_SIZE, algorithm.kdfHmac); + const bodyEnd = PAGE_SIZE - reserve; + const pageNumber = Buffer.alloc(4); + pageNumber.writeUInt32LE(1); + const input = Buffer.concat([ + pageOne.subarray(SALT_SIZE, bodyEnd), + pageOne.subarray(bodyEnd, bodyEnd + IV_SIZE), + pageNumber, + ]); + const computed = createHmac(algorithm.pageHmac, hmacKey).update(input).digest(); + const stored = pageOne.subarray(bodyEnd + IV_SIZE, bodyEnd + IV_SIZE + digestBytes); + return equalsBytes(computed, stored); +} + +/** The decrypted page-1 body starts at file offset 16 (the salt replaces 0..16). */ +function hasSqliteHeaderFields(body: Buffer): boolean { + if (body.length < 8) { + return false; + } + + const pageSize = body.readUInt16BE(0); + const pageSizeOk = pageSize === 1 || (pageSize >= 512 && (pageSize & (pageSize - 1)) === 0); + return pageSizeOk && body[5] === 64 && body[6] === 32 && body[7] === 32; +} + +function equalsBytes(left: Buffer, right: Buffer): boolean { + if (left.length !== right.length) { + return false; + } + + let diff = 0; + + for (let index = 0; index < left.length; index++) { + diff |= left[index]! ^ right[index]!; + } + + return diff === 0; +} + +/** + * Decrypt every page of the main file, in place on a fresh buffer. + * + * `skip` drops the salt prefix of page 1; the reserve region of each page is + * left zeroed, which is how SQLCipher lays the plaintext out. + */ +function decryptPages(image: Buffer, key: Buffer, algorithm: SqlcipherAlgorithm): Buffer | null { + const stream = image.subarray(DATABASE_HEADER_SIZE); + const pageCount = Math.floor(stream.length / PAGE_SIZE); + + if (pageCount === 0) { + return null; + } + + const reserve = reserveBytes(algorithm); + const plain = Buffer.alloc(pageCount * PAGE_SIZE); + + for (let index = 0; index < pageCount; index++) { + const pageNumber = index + 1; + const page = stream.subarray(index * PAGE_SIZE, (index + 1) * PAGE_SIZE); + const body = decryptPageBody(page, key, pageNumber === 1 ? SALT_SIZE : 0, reserve); + + if (body === null) { + return null; + } + + writePlaintextPage(plain, index * PAGE_SIZE, pageNumber, body); + } + + return plain; +} + +/** Decrypt one page body, or null when the page cannot hold an IV + digest. */ +function decryptPageBody(page: Buffer, key: Buffer, skip: number, reserve: number): Buffer | null { + const cipherLength = PAGE_SIZE - skip - reserve; + + if (cipherLength <= 0) { + return null; + } + + const ciphertext = page.subarray(skip, skip + cipherLength); + const iv = page.subarray(skip + cipherLength, skip + cipherLength + IV_SIZE); + const decipher = createDecipheriv('aes-256-cbc', key, iv); + decipher.setAutoPadding(false); + return Buffer.concat([decipher.update(ciphertext), decipher.final()]); +} + +/** + * Write one decrypted page into the plaintext image. + * + * Page 1 is special in both the main file and the WAL: its first 16 on-disk + * bytes hold the KDF salt in place of SQLite's magic, so the magic and the + * page-size field have to be restored. Every other page's body starts at offset + * 0 of the page. + */ +function writePlaintextPage(image: Buffer, offset: number, pageNumber: number, body: Buffer): void { + if (pageNumber !== 1) { + body.copy(image, offset, 0, Math.min(body.length, PAGE_SIZE)); + return; + } + + SQLITE_MAGIC.copy(image, offset); + body.copy(image, offset + SALT_SIZE, 0, Math.min(body.length, PAGE_SIZE - SALT_SIZE)); + image.writeUInt16BE(PAGE_SIZE, offset + 16); +} + +/** + * Fold the `-wal` sidecar into a decrypted image and return the frame count. + * + * A WAL is not wrapped in SQLCipher's envelope the way the main file is: its + * 32-byte header and every 24-byte frame header stay plaintext, and each frame + * carries one encrypted page (page 1 keeping its salt prefix). SQLite's frame + * checksums are computed over the frames *as stored*, i.e. over the ciphertext, + * which is why the intact prefix is established before any decryption. + * + * Only frames up to the last commit are applied, and the database size recorded + * by that commit decides how many pages the merged image has — a torn tail from + * a running QQ therefore contributes nothing. + */ +function applyWal( + base: Buffer, + wal: Buffer | null, + key: Buffer, + algorithm: SqlcipherAlgorithm, +): DecryptedDatabase { + const log = wal === null ? null : parseWal(wal); + + if (!log || log.frames.length === 0) { + return { image: base, walFrames: 0 }; + } + + let lastCommit = -1; + + for (let index = 0; index < log.frames.length; index++) { + if (log.frames[index]!.commitSize !== 0) { + lastCommit = index; + } + } + + if (lastCommit < 0) { + return { image: base, walFrames: 0 }; + } + + const pageCount = log.frames[lastCommit]!.commitSize; + const basePageCount = base.length / PAGE_SIZE; + + // A commit can only grow the database by the pages its own log carries, so + // anything past that bound is a corrupt frame header rather than a size. + if (pageCount < 1 || pageCount > basePageCount + log.frames.length) { + return { image: base, walFrames: 0 }; + } + + const merged = Buffer.alloc(pageCount * PAGE_SIZE); + base.copy(merged, 0, 0, Math.min(base.length, merged.length)); + const reserve = reserveBytes(algorithm); + + for (let index = 0; index <= lastCommit; index++) { + const frame = log.frames[index]!; + + if (frame.pageNumber === 0 || frame.pageNumber > pageCount) { + continue; + } + + const page = wal!.subarray(frame.offset, frame.offset + PAGE_SIZE); + const body = decryptPageBody(page, key, frame.pageNumber === 1 ? SALT_SIZE : 0, reserve); + + if (body === null) { + return { image: base, walFrames: 0 }; + } + + writePlaintextPage(merged, (frame.pageNumber - 1) * PAGE_SIZE, frame.pageNumber, body); + } + + return { image: merged, walFrames: lastCommit + 1 }; +} + +interface WalFrame { + pageNumber: number; + /** Database size in pages recorded by a commit frame, 0 for a non-commit frame. */ + commitSize: number; + /** Offset of the frame's page inside the `-wal` buffer. */ + offset: number; +} + +interface WalLog { + frames: WalFrame[]; + littleEndian: boolean; +} + +/** + * Validate a `-wal` buffer and collect its intact frames. + * + * Validation stops at the first frame whose checksum does not continue the + * chain, mirroring SQLite's own recovery: everything after that frame is either + * half-written or belongs to an aborted transaction. + */ +function parseWal(wal: Buffer): WalLog | null { + if (wal.length < WAL_HEADER_SIZE + WAL_FRAME_HEADER_SIZE + PAGE_SIZE) { + return null; + } + + const magic = wal.readUInt32BE(0); + const littleEndian = magic === 0x377f0682 ? true : magic === 0x377f0683 ? false : null; + + if (littleEndian === null || wal.readUInt32BE(8) !== PAGE_SIZE) { + return null; + } + + // The header checksum covers its first 24 bytes; magic and page size are + // excluded from the checksummed range by that length. + const header = walChecksum([0, 0], [wal.subarray(0, WAL_HEADER_SIZE - 8)], littleEndian); + + if (header[0] !== wal.readUInt32BE(24) || header[1] !== wal.readUInt32BE(28)) { + return null; + } + + const frameSize = WAL_FRAME_HEADER_SIZE + PAGE_SIZE; + const frames: WalFrame[] = []; + let running = header; + + for (let offset = WAL_HEADER_SIZE; offset + frameSize <= wal.length; offset += frameSize) { + const frameHeader = wal.subarray(offset, offset + WAL_FRAME_HEADER_SIZE); + const page = wal.subarray(offset + WAL_FRAME_HEADER_SIZE, offset + frameSize); + running = walChecksum(running, [frameHeader.subarray(0, 8), page], littleEndian); + + if ( + running[0] !== frameHeader.readUInt32BE(16) || + running[1] !== frameHeader.readUInt32BE(20) + ) { + break; + } + + frames.push({ + pageNumber: frameHeader.readUInt32BE(0), + commitSize: frameHeader.readUInt32BE(4), + offset: offset + WAL_FRAME_HEADER_SIZE, + }); + } + + return { frames, littleEndian }; +} + +/** + * SQLite's rolling WAL checksum: two 32-bit accumulators advanced over 8-byte + * word pairs. The byte order is fixed by the WAL magic (`0x377f0682` = + * little-endian words, `0x377f0683` = big-endian) and is unrelated to the + * host's byte order. + * + * Every chunk fed in here is a multiple of 8 bytes: the header contributes 24 + * bytes, a frame its first 8 header bytes plus a whole page. + */ +function walChecksum( + seed: [number, number], + chunks: readonly Buffer[], + littleEndian: boolean, +): [number, number] { + let first = seed[0]; + let second = seed[1]; + + for (const chunk of chunks) { + for (let offset = 0; offset + 8 <= chunk.length; offset += 8) { + const high = littleEndian ? chunk.readUInt32LE(offset) : chunk.readUInt32BE(offset); + const low = littleEndian + ? chunk.readUInt32LE(offset + 4) + : chunk.readUInt32BE(offset + 4); + first = (first + high + second) >>> 0; + second = (second + low + first) >>> 0; + } + } + + return [first, second]; +} + +/** + * Make the assembled image self-consistent before it is handed to SQLite. + * + * The merge can add or remove pages relative to the base image, and the header + * fields that describe the database are only trusted while page 1's change + * counter and version-valid-for agree. The write/read version bytes are reset + * to the legacy journal so the image can be opened read-only without needing a + * `-wal`/`-shm` pair next to it. + */ +function normalizeImage(image: Buffer): void { + const pageCount = image.length / PAGE_SIZE; + const changeCounter = image.readUInt32BE(24); + image[18] = 1; + image[19] = 1; + image.writeUInt32BE(pageCount, 28); + image.writeUInt32BE(changeCounter, 92); +} diff --git a/packages/bridge/src/qq-port-probe.ts b/packages/bridge/src/qq-port-probe.ts deleted file mode 100644 index 8402d073..00000000 --- a/packages/bridge/src/qq-port-probe.ts +++ /dev/null @@ -1,293 +0,0 @@ -import { createLogger } from '@snowluma/common/logger'; -import { exec } from 'child_process'; -import http from 'http'; -import https from 'https'; -import { promisify } from 'util'; - -const execAsync = promisify(exec); -const log = createLogger('LoginProbe'); -const probeNotes = new Map(); - -function noteProbe(pid: number, result: string, ports: number, processes: number | null): void { - const processText = processes === null ? '' : ` processes=${processes}`; - const message = `login probe: PID=${pid} result=${result} ports=${ports}${processText}`; - - if (probeNotes.get(pid) === message) { - return; - } - - probeNotes.set(pid, message); - log.info(message); -} - -const CONNECTION_TIMEOUT_MS = 500; -const COMMAND_TIMEOUT_MS = 1500; -const OVERALL_PROBE_TIMEOUT_MS = 5000; -const EXEC_OPTIONS = { timeout: COMMAND_TIMEOUT_MS, killSignal: 'SIGKILL' as const }; -// QQ's Ptlogin quick-login ports plus its main process mean a single -// logged-in client surfaces roughly this many processes. When no usable -// probe port is found, a count BELOW this implies the target PID is still at -// the login screen; AT/ABOVE it the environment is ambiguous (multiple or -// unrelated `qq` processes), so the passive probe returns no conclusion. -const LOGGED_OUT_PROCESS_COUNT_MAX = 6; - -export interface QqPortLoginInfo { - port: number; - uin: string; - uid?: string; - nickName?: string; - /** The local QQ endpoint exposed an account identity. This does not prove - * the native protocol session is ready to send or receive packets. */ - identityKnown: boolean; -} - -/** One entry of the Ptlogin `pt_get_uins` JSONP array. Only the fields the - * probe reads are modelled; QQ sends more but they're irrelevant here. */ -interface PtloginUin { - uin?: string | number; - account?: string | number; - nickname?: string; -} - -/** - * One `pt_get_uins` call. Returns the parsed account array (possibly empty — - * an EMPTY array is a real answer: "0 accounts", NOT an error) or `null` when - * the port could not be reached / the body was not a usable pt_get_uins - * response (connect refused, timeout, unparseable). Callers MUST distinguish - * the two: `[]` feeds the logged-in/out decision, `null` means "network - * problem, no answer". Neither outcome triggers interactive probing. - */ -async function fetchPtlogin(port: number, useHttps: boolean): Promise { - return new Promise((resolve) => { - const protocol = useHttps ? 'https' : 'http'; - const url = `${protocol}://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`; - - const headers = { - Host: 'localhost.ptlogin2.qq.com', - Referer: 'https://xui.ptlogin2.qq.com/', - Cookie: 'pt_local_token=0', - }; - - const handleResponse = (res: http.IncomingMessage) => { - let text = ''; - res.on('data', (chunk) => { - text += chunk.toString(); - }); - res.on('end', () => { - try { - const inner = text.split('[')[1].split(']')[0]; - const data = JSON.parse('[' + inner + ']') as PtloginUin[]; - resolve(data); - } catch { - resolve(null); - } - }); - }; - - const req = useHttps - ? https.get( - url, - { headers, timeout: CONNECTION_TIMEOUT_MS, rejectUnauthorized: false }, - handleResponse, - ) - : http.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS }, handleResponse); - - req.on('error', () => resolve(null)); - req.on('timeout', () => { - req.destroy(); - resolve(null); - }); - }); -} - -async function tryPtloginMethod(port: number): Promise { - const useHttps = port % 2 !== 0; - - const res1 = await fetchPtlogin(port, useHttps); - const res2 = await fetchPtlogin(port, useHttps); - - if (res1 === null && res2 === null) { - return null; - } - - const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null); - const target = usable.reduce((a, b) => (a.length <= b.length ? a : b)); - - if (target.length === 1) { - const account = target[0]; - return { - port, - uin: String(account.uin || account.account || ''), - nickName: account.nickname || '', - identityKnown: true, - }; - } - - return null; -} - -async function getQqProcessCount(): Promise { - try { - if (process.platform === 'win32') { - const { stdout } = await execAsync( - 'tasklist /fi "imagename eq QQ.exe" /nh', - EXEC_OPTIONS, - ); - return stdout - .toLowerCase() - .split('\n') - .filter((line) => line.includes('qq.exe')).length; - } else { - const { stdout } = await execAsync('pgrep -c qq', EXEC_OPTIONS); - return parseInt(stdout.trim(), 10) || 0; - } - } catch { - // On failure report the ambiguous threshold so we never falsely - // conclude "logged out". - return LOGGED_OUT_PROCESS_COUNT_MAX; - } -} - -async function getProcessPorts(pid: number): Promise { - try { - if (process.platform === 'win32') { - const { stdout } = await execAsync('netstat -ano', EXEC_OPTIONS); - const ports = new Set(); - const lines = stdout.split('\n'); - - for (const line of lines) { - const parts = line.trim().split(/\s+/); - - if (parts.length < 5) { - continue; - } - - const owningPid = parts[parts.length - 1]; - - if (owningPid !== String(pid)) { - continue; - } - - const localAddr = parts[1]; - const portMatch = localAddr.match(/:(\d+)$/); - - if (!portMatch) { - continue; - } - - ports.add(Number(portMatch[1])); - } - - return Array.from(ports); - } else { - const { stdout } = await execAsync('ss -tlnp', EXEC_OPTIONS); - const ports = new Set(); - const lines = stdout.split('\n'); - - for (const line of lines) { - if (!line.includes(`pid=${pid},`) && !line.includes(`pid=${pid})`)) { - continue; - } - - const match = line.match(/:(\d+)\s/); - - if (match) { - ports.add(Number(match[1])); - } - } - - return Array.from(ports); - } - } catch { - return null; - } -} - -async function probeQqLoginInfoInternal(pid: number): Promise { - const ports = await getProcessPorts(pid); - - if (ports === null) { - noteProbe(pid, 'unavailable', 0, null); - return null; - } - - if (ports.length === 0) { - const totalPids = await getQqProcessCount(); - - if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) { - noteProbe(pid, 'no-ports', 0, totalPids); - return { port: 0, uin: '', identityKnown: false }; - } - - noteProbe(pid, 'inconclusive', 0, totalPids); - return null; - } - - const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309]; - const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310]; - - const matchedOddPorts = ports.filter((p) => ODD_PT_PORTS.includes(p)); - const matchedEvenPorts = ports.filter((p) => EVEN_PT_PORTS.includes(p)); - - let ptPortsToTry: number[] = []; - - if (matchedOddPorts.length > 0) { - ptPortsToTry = matchedOddPorts; - } else if (matchedEvenPorts.length > 0) { - ptPortsToTry = matchedEvenPorts; - } - - if (ptPortsToTry.length > 0) { - for (const port of ptPortsToTry) { - const ptResult = await tryPtloginMethod(port); - - if (ptResult !== null) { - return ptResult; - } - } - } else { - const totalPids = await getQqProcessCount(); - - if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) { - noteProbe(pid, 'no-ports', ports.length, totalPids); - return { - port: ports[0], - uin: '', - identityKnown: false, - }; - } - - noteProbe(pid, 'inconclusive', ports.length, totalPids); - return null; - } - - // Background discovery must remain passive. Interactive application - // endpoints are deliberately excluded from automatic probing. - noteProbe(pid, 'no-match', ptPortsToTry.length, null); - return null; -} - -export async function probeQqLoginInfo(pid: number): Promise { - let timer: ReturnType | undefined; - let timedOut = false; - const timeout = new Promise((resolve) => { - timer = setTimeout(() => { - timedOut = true; - resolve(null); - }, OVERALL_PROBE_TIMEOUT_MS); - }); - - try { - const result = await Promise.race([probeQqLoginInfoInternal(pid), timeout]); - - if (timedOut) { - log.warn('login check timed out: PID=%d', pid); - } - - return result; - } finally { - if (timer) { - clearTimeout(timer); - } - } -} diff --git a/packages/bridge/src/types.ts b/packages/bridge/src/types.ts index 4f8de478..8f87ddde 100644 --- a/packages/bridge/src/types.ts +++ b/packages/bridge/src/types.ts @@ -3,6 +3,12 @@ import type { HookProcessBaseInfo } from './injector'; export type HookProcessStatus = 'available' | 'loading' | 'connecting' | 'loaded' | 'online' | 'error' | 'disconnected'; +/** Account the QQ client is signed in as, as reported by its local data. */ +export interface HookProcessAccount { + uin: string; + nickname: string; +} + /** Public-facing snapshot of a per-PID HookSession. */ export interface HookProcessInfo extends HookProcessBaseInfo { injected: boolean; @@ -12,4 +18,6 @@ export interface HookProcessInfo extends HookProcessBaseInfo { status: HookProcessStatus; error: string; method: string; + /** Locally detected identity; null means unknown, not necessarily signed out. */ + account: HookProcessAccount | null; } diff --git a/packages/bridge/tests/hook-manager-state-notify.test.ts b/packages/bridge/tests/hook-manager-state-notify.test.ts index 0ddc4bff..bd298352 100644 --- a/packages/bridge/tests/hook-manager-state-notify.test.ts +++ b/packages/bridge/tests/hook-manager-state-notify.test.ts @@ -5,6 +5,7 @@ import { PipeWatcher } from '../src/pipe-watcher'; import type { ManualMapHandle } from '../src/injector'; import type { BridgeManagerSink } from '../src/hook-manager'; import type { QqHookClient } from '../src/qq-hook-client'; +import type { AccountLoginState } from '../src/qq-account'; // Regression cover for the WebUI SSE wiring: HookManager must call its // optional `onSessionsChanged` callback every time the observable set of @@ -25,7 +26,14 @@ interface Harness { clientFactory: ReturnType; } -function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}): Harness { +function makeManager( + opts: { + processes?: number[]; + livePipes?: number[]; + detectAccounts?: (pids: readonly number[]) => Promise; + accountReprobeIntervalMs?: number; + } = {}, +): Harness { let pids = opts.processes ?? []; let live = new Set(opts.livePipes ?? []); const pipeWatcher = new PipeWatcher({ @@ -65,6 +73,8 @@ function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}): }, makeClient: clientFactory, listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), + detectAccounts: opts.detectAccounts ?? (async () => []), + accountReprobeIntervalMs: opts.accountReprobeIntervalMs, onSessionsChanged, }); return { @@ -184,6 +194,7 @@ describe('HookManager.onSessionsChanged', () => { return c; }), listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), + detectAccounts: async () => [], // onSessionsChanged deliberately omitted }); await pipeWatcher.start(); @@ -196,6 +207,202 @@ describe('HookManager.onSessionsChanged', () => { }); }); +describe('HookManager periodic account re-probe', () => { + it('shares one account probe between watcher ticks and concurrent snapshots', async () => { + const probe = Promise.withResolvers(); + const detectAccounts = vi.fn(() => probe.promise); + const ctx = makeManager({ processes: [4242], detectAccounts }); + + try { + await ctx.pipeWatcher.start(); + const first = ctx.manager.listProcesses(); + const second = ctx.manager.listProcesses(); + await flush(); + expect(detectAccounts).toHaveBeenCalledTimes(1); + probe.resolve([{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 }]); + const snapshots = await Promise.all([first, second]); + expect(snapshots.map((list) => list[0]!.account)).toEqual([ + { uin: '10001', nickname: 'Alice' }, + { uin: '10001', nickname: 'Alice' }, + ]); + } finally { + probe.resolve([]); + ctx.manager.dispose(); + } + }); + + it('keeps all process labels when an operation reads just one process', async () => { + const accounts: AccountLoginState[] = [ + { uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 }, + { uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 5151 }, + ]; + const detectAccounts = vi.fn(async (pids: readonly number[]) => + accounts.filter((account) => pids.includes(account.pid!)), + ); + const ctx = makeManager({ processes: [4242, 5151], detectAccounts }); + + try { + await ctx.manager.listProcesses(); + const baseline = detectAccounts.mock.calls.length; + expect((await ctx.manager.refreshProcess(4242)).account?.uin).toBe('10001'); + ctx.onSessionsChanged.mockClear(); + await ctx.pipeWatcher.tickNow(); + await flush(); + expect(detectAccounts).toHaveBeenCalledTimes(baseline); + expect(ctx.onSessionsChanged).not.toHaveBeenCalled(); + expect((await ctx.manager.listProcesses())[1]!.account?.uin).toBe('10002'); + } finally { + ctx.manager.dispose(); + } + }); + + it('does not publish a late account result for an exited process', async () => { + const probe = Promise.withResolvers(); + const ctx = makeManager({ processes: [4242], detectAccounts: () => probe.promise }); + + try { + await ctx.pipeWatcher.start(); + const snapshot = ctx.manager.listProcesses(); + await flush(); + ctx.setProcesses([]); + await ctx.pipeWatcher.tickNow(); + await flush(); + ctx.onSessionsChanged.mockClear(); + probe.resolve([{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 }]); + await flush(); + expect(await snapshot).toEqual([]); + expect(ctx.onSessionsChanged).not.toHaveBeenCalled(); + expect(await ctx.manager.listProcesses()).toEqual([]); + } finally { + probe.resolve([]); + ctx.manager.dispose(); + } + }); + + // A login can happen with no hook edge at all (QQ signs in after SnowLuma + // started, or before the hook was injected), so no session status changes + // and nothing pushes a fresh processes snapshot. These cover the watcher + // pass that re-reads the account labels and invalidates when they move. + + it('publishes when a process gains an account label', async () => { + let accounts: AccountLoginState[] = [{ uin: '1', uid: 'u1', nickname: 'A', pid: null }]; + const ctx = makeManager({ + processes: [4242], + detectAccounts: async () => accounts, + accountReprobeIntervalMs: 0, + }); + await ctx.pipeWatcher.start(); + await flush(); + ctx.onSessionsChanged.mockClear(); + + // QQ finished signing in: the account's nt_msg.db is now held by 4242. + accounts = [{ uin: '1', uid: 'u1', nickname: 'A', pid: 4242 }]; + await ctx.pipeWatcher.tickNow(); + await flush(); + await flush(); + + expect(ctx.onSessionsChanged).toHaveBeenCalled(); + const list = await ctx.manager.listProcesses(); + expect(list[0]!.account).toEqual({ uin: '1', nickname: 'A' }); + + ctx.manager.dispose(); + }); + + it('stays silent while the labels are unchanged', async () => { + const accounts: AccountLoginState[] = [{ uin: '1', uid: 'u1', nickname: 'A', pid: 4242 }]; + const detectAccounts = vi.fn(async () => accounts); + const ctx = makeManager({ + processes: [4242], + detectAccounts, + accountReprobeIntervalMs: 0, + }); + await ctx.pipeWatcher.start(); + await flush(); + ctx.onSessionsChanged.mockClear(); + + await ctx.pipeWatcher.tickNow(); + await ctx.pipeWatcher.tickNow(); + await flush(); + await flush(); + + // Detection did run again — it just had nothing new to report. + expect(detectAccounts.mock.calls.length).toBeGreaterThan(1); + expect(ctx.onSessionsChanged).not.toHaveBeenCalled(); + + ctx.manager.dispose(); + }); + + it('ignores accounts that are not signed in on any process', async () => { + let accounts: AccountLoginState[] = [{ uin: '1', uid: 'u1', nickname: 'A', pid: null }]; + const ctx = makeManager({ + processes: [4242], + detectAccounts: async () => accounts, + accountReprobeIntervalMs: 0, + }); + await ctx.pipeWatcher.start(); + await flush(); + ctx.onSessionsChanged.mockClear(); + + // Only the cached-account set changed (another account signed in on + // another machine/user); no process label moved. + accounts = [ + { uin: '1', uid: 'u1', nickname: 'A', pid: null }, + { uin: '2', uid: 'u2', nickname: 'B', pid: null }, + ]; + await ctx.pipeWatcher.tickNow(); + await flush(); + await flush(); + + expect(ctx.onSessionsChanged).not.toHaveBeenCalled(); + + ctx.manager.dispose(); + }); + + it('throttles the probe to the configured interval', async () => { + const detectAccounts = vi.fn(async () => [] as AccountLoginState[]); + const ctx = makeManager({ + processes: [4242], + detectAccounts, + accountReprobeIntervalMs: 60_000, + }); + await ctx.pipeWatcher.start(); + await flush(); + const baseline = detectAccounts.mock.calls.length; + + await ctx.pipeWatcher.tickNow(); + await ctx.pipeWatcher.tickNow(); + await flush(); + + expect(detectAccounts.mock.calls.length).toBe(baseline); + + ctx.manager.dispose(); + }); + + it('keeps working when detection fails, and reports the failure once', async () => { + const ctx = makeManager({ + processes: [4242], + detectAccounts: async () => { + throw new Error('login.db unreadable'); + }, + accountReprobeIntervalMs: 0, + }); + await ctx.pipeWatcher.start(); + await flush(); + ctx.onSessionsChanged.mockClear(); + + await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow(); + await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow(); + await flush(); + await flush(); + + // Detection failing is not a label change, so nothing is published. + expect(ctx.onSessionsChanged).not.toHaveBeenCalled(); + expect((await ctx.manager.listProcesses())[0]!.account).toBeNull(); + + ctx.manager.dispose(); + }); +}); + describe('HookManager receive-health wiring (#233)', () => { it('forwards stale and recovered receive health for the owning PID', async () => { const ctx = makeManager({ processes: [4242], livePipes: [4242] }); diff --git a/packages/bridge/tests/hook-manager.test.ts b/packages/bridge/tests/hook-manager.test.ts index ae62f079..d563993e 100644 --- a/packages/bridge/tests/hook-manager.test.ts +++ b/packages/bridge/tests/hook-manager.test.ts @@ -7,6 +7,7 @@ import { HookManager, shouldAutoLoadPid } from '../src/hook-manager'; import { PipeWatcher } from '../src/pipe-watcher'; import type { HookInjectResult, ManualMapHandle } from '../src/injector'; import type { BridgeManagerSink } from '../src/hook-manager'; +import type { AccountLoginState } from '../src/qq-account'; import type { QqHookClient } from '../src/qq-hook-client'; import { createLogger, @@ -29,6 +30,7 @@ function makeManager(opts: { processes?: number[]; onSessionsChanged?: () => void; inject?: (pid: number) => HookInjectResult | Promise; + detectAccounts?: (pids: readonly number[]) => Promise; }) { let pids = opts.processes ?? []; const live = new Set(); @@ -76,6 +78,8 @@ function makeManager(opts: { autoLoadOnDiscovery: opts.autoLoadOnDiscovery, onSessionsChanged: opts.onSessionsChanged, listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), + // Detection reads QQ's own data directories; tests stay off the host. + detectAccounts: opts.detectAccounts ?? (async () => []), }); return { manager, @@ -469,3 +473,41 @@ describe('shouldAutoLoadPid', () => { expect(shouldAutoLoadPid(99999, log)).toBe(true); }); }); + +describe('HookManager — signed-in account labelling', () => { + it('labels each process with the account detected on it', async () => { + const ctx = makeManager({ + processes: [4242, 5151], + detectAccounts: async () => [ + { uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 }, + { uin: '10002', uid: 'u_b', nickname: 'Bob', pid: null }, + ], + }); + + try { + const list = await ctx.manager.listProcesses(); + expect(list.map((info) => [info.pid, info.account])).toEqual([ + [4242, { uin: '10001', nickname: 'Alice' }], + [5151, null], + ]); + } finally { + ctx.manager.dispose(); + } + }); + + it('leaves processes unlabelled when detection fails', async () => { + const ctx = makeManager({ + processes: [4242], + detectAccounts: async () => { + throw new Error('login.db unreadable'); + }, + }); + + try { + const list = await ctx.manager.listProcesses(); + expect(list[0]!.account).toBeNull(); + } finally { + ctx.manager.dispose(); + } + }); +}); diff --git a/packages/bridge/tests/hook-reconnect-no-login-e2e.test.ts b/packages/bridge/tests/hook-reconnect-no-login-e2e.test.ts index e2e8dcbf..de6725a6 100644 --- a/packages/bridge/tests/hook-reconnect-no-login-e2e.test.ts +++ b/packages/bridge/tests/hook-reconnect-no-login-e2e.test.ts @@ -71,6 +71,7 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => { }, autoLoadOnDiscovery: true, listProcesses: () => [{ pid: PID, name: 'qq', path: '' }], + detectAccounts: async () => [], }); // Initial discovery + first connect. diff --git a/packages/bridge/tests/hook-session.test.ts b/packages/bridge/tests/hook-session.test.ts index 404f56ad..1cbca2eb 100644 --- a/packages/bridge/tests/hook-session.test.ts +++ b/packages/bridge/tests/hook-session.test.ts @@ -8,7 +8,6 @@ import { type QqHookClient, type QqHookPacket, } from '../src/qq-hook-client'; -import type { QqPortLoginInfo } from '../src/qq-port-probe'; import type { PacketSender } from '@snowluma/common/packet-sender'; import type { PacketSink } from '@snowluma/common/protocol-types'; import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger'; @@ -104,7 +103,7 @@ function makeSession( pipeLive?: boolean; clientFailsConnect?: boolean; onPacket?: PacketSink; - probeLogin?: (pid: number) => Promise; + detectLoginUin?: (pid: number) => Promise; nativeReadyOnIdentityHint?: boolean; identityHintFailures?: number; } = {}, @@ -116,10 +115,9 @@ function makeSession( inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), unload: vi.fn(), }; - // Default probe exposes no identity so the reconcile safety net is inert - // unless a test opts into a known account. - const probeLogin = - opts.probeLogin ?? (async () => ({ port: 0, uin: '', identityKnown: false })); + // Default detection exposes no account so the reconcile safety net is inert + // unless a test opts into a known one. + const detectLoginUin = opts.detectLoginUin ?? (async () => null); const session = new HookSession(pid, { injector, @@ -136,7 +134,7 @@ function makeSession( // Cast: FakeClient mirrors only the surface HookSession touches. return c as unknown as QqHookClient; }, - probeLogin, + detectLoginUin, pipeWatcher: { isPipeLive: () => pipeLive }, onPacket: opts.onPacket, }); @@ -1003,10 +1001,35 @@ describe('HookSession — packet forwarding', () => { }); describe('HookSession — login reconcile (Docker auto-login safety net)', () => { + it('discards an identity read started before a pipe reconnect', async () => { + const detection = Promise.withResolvers(); + const ctx = makeSession({ pipeLive: true, detectLoginUin: () => detection.promise }); + + try { + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + const previous = ctx.currentClient(); + previous.close(); + await flush(); + ctx.session.onPipeUp(); + await flush(); + const current = ctx.currentClient(); + expect(current).not.toBe(previous); + detection.resolve('10001'); + await flush(); + expect(current.loginIdentityHints).toEqual([]); + expect(previous.loginIdentityHints).toEqual([]); + } finally { + detection.resolve(null); + ctx.session.dispose(); + } + }); + it('keeps the packet sender usable only after native readiness confirms the identity hint', async () => { const ctx = makeSession({ pipeLive: true, - probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }), + detectLoginUin: async () => '10001', nativeReadyOnIdentityHint: true, }); let sender: PacketSender | undefined; @@ -1033,12 +1056,12 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () => ]); }); - it('treats a port-probed account as an identity hint, not native login proof', async () => { + it('treats a locally detected account as an identity hint, not native login proof', async () => { // Account identity does not prove request readiness. The bridge must wait // for a login-state confirmation instead of synthesizing one. const ctx = makeSession({ pipeLive: true, - probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }), + detectLoginUin: async () => '10001', }); const loginSpy = vi.fn(); ctx.session.on('login', loginSpy); @@ -1058,7 +1081,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () => vi.useFakeTimers(); const ctx = makeSession({ pipeLive: true, - probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }), + detectLoginUin: async () => '10001', }); try { @@ -1079,7 +1102,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () => let uin = '10001'; const ctx = makeSession({ pipeLive: true, - probeLogin: async () => ({ port: 4301, uin, identityKnown: true }), + detectLoginUin: async () => uin, }); try { @@ -1104,7 +1127,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () => vi.useFakeTimers(); const ctx = makeSession({ pipeLive: true, - probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }), + detectLoginUin: async () => '10001', identityHintFailures: 3, }); @@ -1128,10 +1151,10 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () => } }); - it('does not log in when the probe reports not-logged-in', async () => { + it('does not log in when no account is detected', async () => { const ctx = makeSession({ pipeLive: true, - probeLogin: async () => ({ port: 0, uin: '', identityKnown: false }), + detectLoginUin: async () => null, }); const loginSpy = vi.fn(); ctx.session.on('login', loginSpy); @@ -1144,10 +1167,10 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () => expect(ctx.session.status).toBe('loaded'); }); - it('ignores a probe with a non-real uin (0)', async () => { + it('ignores a detected account with a non-real uin (0)', async () => { const ctx = makeSession({ pipeLive: true, - probeLogin: async () => ({ port: 4301, uin: '0', identityKnown: true }), + detectLoginUin: async () => '0', }); const loginSpy = vi.fn(); ctx.session.on('login', loginSpy); @@ -1159,11 +1182,11 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () => expect(loginSpy).not.toHaveBeenCalled(); }); - it('tolerates a throwing probe (best-effort, no crash/login)', async () => { + it('tolerates a throwing detection (best-effort, no crash/login)', async () => { const ctx = makeSession({ pipeLive: true, - probeLogin: async () => { - throw new Error('port scan failed'); + detectLoginUin: async () => { + throw new Error('account detection unavailable'); }, }); const loginSpy = vi.fn(); @@ -1177,14 +1200,14 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () => expect(ctx.session.status).toBe('loaded'); }); - it('detects a login that lands on a LATER interval probe', async () => { + it('detects a login that lands on a LATER interval check', async () => { vi.useFakeTimers(); try { - let identityKnown = false; + let signedIn = false; const ctx = makeSession({ pipeLive: true, - probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown }), + detectLoginUin: async () => (signedIn ? '10001' : null), nativeReadyOnIdentityHint: true, }); const loginSpy = vi.fn(); @@ -1195,8 +1218,8 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () => await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (not logged in yet) expect(loginSpy).not.toHaveBeenCalled(); - identityKnown = true; // QQ exposes the restored identity - await vi.advanceTimersByTimeAsync(3000); // next interval probe picks it up + signedIn = true; // the account's database shows up as signed in + await vi.advanceTimersByTimeAsync(3000); // next interval check picks it up expect(loginSpy).toHaveBeenCalledOnce(); expect(ctx.session.status).toBe('online'); @@ -1208,8 +1231,8 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () => it('does not double-emit when the pushed frame logs in first', async () => { // Pushed-frame login wins; a subsequent probe with the same uin must not // re-emit (handleLoginState dedups), and the reconcile timer is stopped. - const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', identityKnown: true })); - const ctx = makeSession({ pipeLive: true, probeLogin }); + const detectLoginUin = vi.fn(async () => '10001'); + const ctx = makeSession({ pipeLive: true, detectLoginUin }); const loginSpy = vi.fn(); ctx.session.on('login', loginSpy); @@ -1414,27 +1437,27 @@ describe('HookSession — end-to-end receive health (#233)', () => { }); }); -describe('HookSession — login reconcile does not stack concurrent probes', () => { - it('skips overlapping ticks while a slow probe is in flight', async () => { +describe('HookSession — login reconcile does not stack concurrent detections', () => { + it('skips overlapping ticks while a slow detection is in flight', async () => { vi.useFakeTimers(); try { - // A probe that never resolves — simulates a slow port scan spanning + // A detection that never resolves — simulates a slow read spanning // multiple intervals. The in-flight guard must call it only once. - const probeLogin = vi.fn( + const detectLoginUin = vi.fn( () => new Promise(() => { /* pending */ }), ); - const ctx = makeSession({ pipeLive: true, probeLogin }); + const ctx = makeSession({ pipeLive: true, detectLoginUin }); await ctx.session.load(); ctx.session.onPipeUp(); await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (starts, stays pending) await vi.advanceTimersByTimeAsync(9000); // 3 more interval ticks - expect(probeLogin).toHaveBeenCalledTimes(1); // not stacked + expect(detectLoginUin).toHaveBeenCalledTimes(1); // not stacked } finally { vi.useRealTimers(); } diff --git a/packages/bridge/tests/qq-account-db-lock.test.ts b/packages/bridge/tests/qq-account-db-lock.test.ts new file mode 100644 index 00000000..042aa221 --- /dev/null +++ b/packages/bridge/tests/qq-account-db-lock.test.ts @@ -0,0 +1,123 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { mkdtemp, rm } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { SqliteDatabase } from '@snowluma/sqlite'; +import { isQqProcessName, probeDbLock } from '../src/qq-account/db-lock'; + +const native = vi.hoisted(() => ({ addon: vi.fn<() => unknown>(() => null) })); + +vi.mock('../src/injector', () => ({ getNativeHookAddon: native.addon })); + +const IS_LINUX = process.platform === 'linux'; +const ORIGINAL_PLATFORM = process.platform; + +/** Run `probeDbLock` as if the host were Windows, with a stubbed addon. */ +function asWindows(addon: unknown, run: () => T): T { + Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }); + native.addon.mockReturnValue(addon); + + try { + return run(); + } finally { + Object.defineProperty(process, 'platform', { + value: ORIGINAL_PLATFORM, + configurable: true, + }); + } +} + +afterEach(() => { + native.addon.mockReset(); + native.addon.mockReturnValue(null); +}); + +describe('database holder probe', () => { + it.runIf(IS_LINUX)('reports nothing for a file that is not there', () => { + const missing = path.join(os.tmpdir(), `snowluma-absent-${process.pid}.db`); + expect(probeDbLock(missing)).toEqual([]); + }); + + it.runIf(IS_LINUX)('finds the process holding a database', async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), 'snowluma-lock-')); + const file = path.join(directory, 'nt_msg.db'); + const db = new SqliteDatabase(file); + + try { + // A rollback-journal write transaction takes a POSIX lock on the + // database file itself, which is exactly what a signed-in client + // holds on the account's nt_msg.db. + await db.exec('PRAGMA journal_mode = DELETE'); + await db.exec('CREATE TABLE t(value TEXT)'); + await db.exec('BEGIN IMMEDIATE'); + + const holders = probeDbLock(file); + const self = holders.find((holder) => holder.pid === process.pid); + expect(self).toBeDefined(); + // The holder is named from /proc//comm, and that name is what + // keeps a holder that is not QQ from being mistaken for one. + expect(self!.name.length).toBeGreaterThan(0); + expect(isQqProcessName(self!.name)).toBe(false); + + await db.exec('ROLLBACK'); + expect(probeDbLock(file).some((holder) => holder.pid === process.pid)).toBe(false); + } finally { + await db.close(); + await rm(directory, { recursive: true, force: true }); + } + }); +}); + +describe('Windows holder probe', () => { + it('reports the holders the addon lists', () => { + const holders = asWindows( + { + probeDbLock: () => [ + { pid: 4242, name: 'QQ.exe' }, + { pid: 7, name: 'weq' }, + ], + }, + () => probeDbLock('C:\\Tencent Files\\10001\\nt_qq\\nt_db\\nt_msg.db'), + ); + + expect(holders).toEqual([ + { pid: 4242, name: 'QQ.exe' }, + { pid: 7, name: 'weq' }, + ]); + }); + + it.each([[{ pid: 0, name: 'QQ' }], [{ pid: 9 }], [null], 'not-an-array'])( + 'reports malformed native results: %j', + (result) => { + expect(() => + asWindows({ probeDbLock: () => result }, () => probeDbLock('C:\\nt_msg.db')), + ).toThrow('Invalid database holders'); + }, + ); + + it('accepts an empty holder list', () => { + expect(asWindows({ probeDbLock: () => [] }, () => probeDbLock('C:\\nt_msg.db'))).toEqual( + [], + ); + }); + + it.each([null, {}])('reports an unavailable native probe: %j', (addon) => { + expect(() => asWindows(addon, () => probeDbLock('C:\\nt_msg.db'))).toThrow( + 'requires a hook addon with probeDbLock', + ); + }); +}); + +describe('QQ process names', () => { + it('accepts the name each platform reports for the client', () => { + expect(isQqProcessName('QQ')).toBe(true); + expect(isQqProcessName('QQ.exe')).toBe(true); + expect(isQqProcessName(' qq ')).toBe(true); + }); + + it('rejects other holders', () => { + expect(isQqProcessName('node')).toBe(false); + expect(isQqProcessName('qqmusic')).toBe(false); + expect(isQqProcessName('')).toBe(false); + }); +}); diff --git a/packages/bridge/tests/qq-account-detect.test.ts b/packages/bridge/tests/qq-account-detect.test.ts new file mode 100644 index 00000000..cb61b620 --- /dev/null +++ b/packages/bridge/tests/qq-account-detect.test.ts @@ -0,0 +1,241 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { spawn } from 'node:child_process'; +import { mkdtemp, rm } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger'; + +const mocks = vi.hoisted(() => ({ + readLocalAccounts: vi.fn(), + probeDbLock: vi.fn(), +})); + +// The account list and the holder probe are covered on their own; this file is +// about how the two are joined. +vi.mock('../src/qq-account/login-db', () => ({ readLocalAccounts: mocks.readLocalAccounts })); +vi.mock('../src/qq-account/db-lock', async (importOriginal) => ({ + ...(await importOriginal()), + probeDbLock: mocks.probeDbLock, +})); + +import { detectAccountLogins, detectAccountLoginsForPids } from '../src/qq-account/detect'; +import { loginDbPaths, ntMsgDbPath } from '../src/qq-account/paths'; + +const ALICE = { uin: '10001', uid: 'u_alice', nickname: 'Alice' }; +const BOB = { uin: '10002', uid: 'u_bob', nickname: 'Bob' }; + +const roots: string[] = []; +const children: Array> = []; + +afterEach(async () => { + mocks.readLocalAccounts.mockReset(); + mocks.probeDbLock.mockReset(); + + for (const child of children.splice(0)) { + child.kill(); + } + + for (const root of roots.splice(0)) { + await rm(root, { recursive: true, force: true }); + } +}); + +async function makeRoot(): Promise { + const root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-detect-')); + roots.push(root); + return root; +} + +/** + * A live process whose `/proc//environ` carries `HOME` (and any extra + * variables given). + * + * `XDG_CONFIG_HOME` is dropped unless the caller sets it: it outranks `HOME` + * when deriving the data root, and a CI runner exports its own, which would + * otherwise decide the result instead of the HOME under test. + * + * Resolves only once the child has run past `execve`, because `/proc/` + * still shows the parent's environment before that. + */ +function spawnWithHome(home: string, extra: Record = {}): Promise { + return new Promise((resolve, reject) => { + const env: NodeJS.ProcessEnv = { ...process.env }; + delete env.XDG_CONFIG_HOME; + Object.assign(env, { HOME: home }, extra); + const child = spawn( + process.execPath, + ['-e', 'console.log("ready"); setTimeout(() => {}, 30000)'], + { env, stdio: ['ignore', 'pipe', 'ignore'] }, + ); + children.push(child); + child.stdout!.once('data', () => resolve(child.pid!)); + child.once('error', reject); + }); +} + +describe('local account detection', () => { + it('labels each account with the process holding its database', async () => { + const root = await makeRoot(); + mocks.readLocalAccounts.mockResolvedValue({ accounts: [ALICE, BOB], failures: [] }); + mocks.probeDbLock.mockImplementation((dbPath: string) => { + if (dbPath === ntMsgDbPath(root, ALICE)) { + return [{ pid: 4242, name: 'qq' }]; + } + + // A holder that is not the client must not be mistaken for one. + return [{ pid: 999, name: 'node' }]; + }); + + await expect(detectAccountLogins([root])).resolves.toEqual([ + { ...ALICE, pid: 4242 }, + { ...BOB, pid: null }, + ]); + }); + + it('merges the accounts of every root instead of stopping at the first', async () => { + const own = await makeRoot(); + const extra = await makeRoot(); + mocks.readLocalAccounts.mockImplementation(async (root: string) => + root === own ? { accounts: [ALICE], failures: [] } : { accounts: [BOB], failures: [] }, + ); + mocks.probeDbLock.mockImplementation((dbPath: string) => + dbPath === ntMsgDbPath(extra, BOB) ? [{ pid: 5151, name: 'qq' }] : [], + ); + + await expect(detectAccountLogins([own, extra])).resolves.toEqual([ + { ...ALICE, pid: null }, + { ...BOB, pid: 5151 }, + ]); + + // An account held under an instance's own HOME is still labelled, which + // is what a single-root lookup cannot do. + expect(mocks.probeDbLock).toHaveBeenCalledWith(ntMsgDbPath(extra, BOB)); + }); + + it('keeps account records with the same uin scoped to their own root', async () => { + const first = await makeRoot(); + const second = await makeRoot(); + mocks.readLocalAccounts.mockImplementation(async (root: string) => + root === first + ? { accounts: [ALICE], failures: [] } + : { accounts: [{ ...ALICE, nickname: 'Stale' }], failures: [] }, + ); + mocks.probeDbLock.mockImplementation((file: string) => + file === ntMsgDbPath(second, ALICE) ? [{ pid: 5151, name: 'qq' }] : [], + ); + + await expect(detectAccountLogins([first, second])).resolves.toEqual([ + { ...ALICE, pid: null }, + { ...ALICE, nickname: 'Stale', pid: 5151 }, + ]); + }); + + it('reports nothing when there are no roots', async () => { + await expect(detectAccountLogins([])).resolves.toEqual([]); + expect(mocks.readLocalAccounts).not.toHaveBeenCalled(); + }); + + it('logs a named reason when a login.db is present but unreadable', async () => { + const root = await makeRoot(); + const entries: LogEntry[] = []; + const previousLevel = getLogLevel(); + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + + try { + mocks.readLocalAccounts.mockResolvedValue({ + accounts: [], + failures: [ + { + path: loginDbPaths(root)[0]!, + reason: 'undecryptable', + }, + ], + }); + mocks.probeDbLock.mockReturnValue([]); + + // An unreadable login.db must not look like "no accounts": an + // operator reading the log has to see why nothing was reported. + await detectAccountLogins([root]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + const warned = entries.filter( + (entry) => entry.level === 'warn' && entry.scope === 'QqAccount', + ); + expect(warned).toHaveLength(1); + expect(warned[0]!.message).toContain('login.db unreadable'); + expect(warned[0]!.message).toContain('undecryptable'); + }); +}); + +describe.runIf(process.platform === 'linux')('per-process data roots', () => { + it('reads each pid against the HOME that process runs under', async () => { + const home = await makeRoot(); + const pid = await spawnWithHome(home); + mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] }); + mocks.probeDbLock.mockReturnValue([]); + + await detectAccountLoginsForPids([pid]); + + // `/.config/QQ`, from the child's environment rather than ours. + expect(mocks.readLocalAccounts).toHaveBeenCalledWith(path.join(home, '.config', 'QQ')); + }); + + it('asks each root once when several processes share a HOME', async () => { + const home = await makeRoot(); + const pids = [await spawnWithHome(home), await spawnWithHome(home)]; + mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] }); + mocks.probeDbLock.mockReturnValue([]); + + await detectAccountLoginsForPids(pids); + + expect(mocks.readLocalAccounts).toHaveBeenCalledTimes(1); + }); + + it('honours XDG_CONFIG_HOME of the process over its HOME', async () => { + const home = await makeRoot(); + const configHome = await makeRoot(); + const pid = await spawnWithHome(home, { XDG_CONFIG_HOME: configHome }); + mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] }); + mocks.probeDbLock.mockReturnValue([]); + + await detectAccountLoginsForPids([pid]); + + // The XDG variable outranks HOME, as it does for the client itself. + expect(mocks.readLocalAccounts).toHaveBeenCalledWith(path.join(configHome, 'QQ')); + }); + + it('keeps each process on its own root when the HOMEs differ', async () => { + const first = await makeRoot(); + const second = await makeRoot(); + const pids = [await spawnWithHome(first), await spawnWithHome(second)]; + mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] }); + mocks.probeDbLock.mockReturnValue([]); + + await detectAccountLoginsForPids(pids); + + expect(mocks.readLocalAccounts).toHaveBeenCalledWith(path.join(first, '.config', 'QQ')); + expect(mocks.readLocalAccounts).toHaveBeenCalledWith(path.join(second, '.config', 'QQ')); + }); + + it('does not substitute another HOME when the pid is gone', async () => { + const home = await makeRoot(); + const pid = await spawnWithHome(home); + mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] }); + mocks.probeDbLock.mockReturnValue([]); + + // The child exits, so its environment is no longer readable. + await new Promise((resolve) => { + const child = children[children.length - 1]!; + child.once('exit', () => resolve()); + child.kill(); + }); + + await detectAccountLoginsForPids([pid]); + + expect(mocks.readLocalAccounts).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/bridge/tests/qq-account-fixtures.ts b/packages/bridge/tests/qq-account-fixtures.ts new file mode 100644 index 00000000..41e36fb7 --- /dev/null +++ b/packages/bridge/tests/qq-account-fixtures.ts @@ -0,0 +1,195 @@ +/** + * Encryption helpers for the account-detection tests. + * + * The shipped code only decrypts, so producing an encrypted fixture means + * mirroring SQLCipher's page layout here: `[client header][page 1]…` with each + * page ending in `IV || page HMAC`, and a `-wal` whose frame header stays + * plaintext while the page inside it is encrypted. + */ + +import { createCipheriv, createHmac, pbkdf2Sync, randomBytes } from 'node:crypto'; +import type { KdfHmacAlgorithm, PageHmacAlgorithm } from '../src/qq-account/sqlcipher'; + +export interface FixtureAlgorithm { + pageHmac: PageHmacAlgorithm; + kdfHmac: KdfHmacAlgorithm; +} + +export const FIXTURE_PASSPHRASE = 'BD156D6710D54D8782F4'; +export const FIXTURE_PAGE_SIZE = 4096; +export const FIXTURE_HEADER_SIZE = 1024; +export const FIXTURE_WAL_HEADER_SIZE = 32; +export const FIXTURE_WAL_FRAME_HEADER_SIZE = 24; + +const DIGEST_BYTES: Record = { + none: 0, + sha1: 20, + sha256: 32, + sha512: 64, +}; + +const KDF_ITERATIONS = 4000; +const HMAC_KEY_ITERATIONS = 2; +const HMAC_SALT_MASK = 0x3a; + +export function reserveBytes(algorithm: FixtureAlgorithm): number { + return Math.ceil((16 + DIGEST_BYTES[algorithm.pageHmac]) / 16) * 16; +} + +/** Encrypt a plaintext SQLite image the way QQ NT stores it. */ +export function encryptImage( + plain: Buffer, + algorithm: FixtureAlgorithm, + passphrase = FIXTURE_PASSPHRASE, + salt = randomBytes(16), +): Buffer { + const pageCount = plain.length / FIXTURE_PAGE_SIZE; + const key = pbkdf2Sync(passphrase, salt, KDF_ITERATIONS, 32, algorithm.kdfHmac); + const output = Buffer.alloc(FIXTURE_HEADER_SIZE + plain.length); + + for (let index = 0; index < pageCount; index++) { + const pageNumber = index + 1; + const skip = pageNumber === 1 ? 16 : 0; + const body = plain.subarray( + index * FIXTURE_PAGE_SIZE + skip, + (index + 1) * FIXTURE_PAGE_SIZE, + ); + + if (pageNumber === 1) { + // Page 1 stores the KDF salt where SQLite keeps its magic. + salt.copy(output, FIXTURE_HEADER_SIZE); + } + + encryptPageInto( + output, + FIXTURE_HEADER_SIZE + index * FIXTURE_PAGE_SIZE, + body, + pageNumber, + key, + salt, + algorithm, + ); + } + + return output; +} + +/** Encrypt the pages of a real (plaintext) WAL, recomputing the frame checksums. */ +export function encryptWal( + plainWal: Buffer, + encryptedImage: Buffer, + algorithm: FixtureAlgorithm, + passphrase = FIXTURE_PASSPHRASE, +): Buffer { + const salt = encryptedImage.subarray(FIXTURE_HEADER_SIZE, FIXTURE_HEADER_SIZE + 16); + const key = pbkdf2Sync(passphrase, salt, KDF_ITERATIONS, 32, algorithm.kdfHmac); + const frameSize = FIXTURE_WAL_FRAME_HEADER_SIZE + FIXTURE_PAGE_SIZE; + const output = Buffer.alloc(plainWal.length); + plainWal.copy(output, 0, 0, FIXTURE_WAL_HEADER_SIZE); + + let running = walChecksum([0, 0], [output.subarray(0, FIXTURE_WAL_HEADER_SIZE - 8)], true); + + for ( + let offset = FIXTURE_WAL_HEADER_SIZE; + offset + frameSize <= plainWal.length; + offset += frameSize + ) { + const frameHeader = plainWal.subarray(offset, offset + FIXTURE_WAL_FRAME_HEADER_SIZE); + const pageNumber = frameHeader.readUInt32BE(0); + const skip = pageNumber === 1 ? 16 : 0; + const page = plainWal.subarray(offset + FIXTURE_WAL_FRAME_HEADER_SIZE, offset + frameSize); + encryptPageInto( + output, + offset + FIXTURE_WAL_FRAME_HEADER_SIZE, + page.subarray(skip), + pageNumber, + key, + salt, + algorithm, + ); + + const stored = output.subarray(offset, offset + FIXTURE_WAL_FRAME_HEADER_SIZE); + frameHeader.copy(stored, 0, 0, 8); + running = walChecksum( + running, + [ + stored.subarray(0, 8), + output.subarray(offset + FIXTURE_WAL_FRAME_HEADER_SIZE, offset + frameSize), + ], + true, + ); + stored.writeUInt32BE(running[0], 16); + stored.writeUInt32BE(running[1], 20); + } + + return output; +} + +/** + * SQLite's rolling WAL checksum, as the fixture needs it to rebuild frame + * checksums — and to prove the shipped implementation agrees with what SQLite + * itself wrote in a real `-wal`. + */ +export function walChecksum( + seed: [number, number], + chunks: readonly Buffer[], + littleEndian: boolean, +): [number, number] { + let first = seed[0]; + let second = seed[1]; + + for (const chunk of chunks) { + for (let offset = 0; offset + 8 <= chunk.length; offset += 8) { + const high = littleEndian ? chunk.readUInt32LE(offset) : chunk.readUInt32BE(offset); + const low = littleEndian + ? chunk.readUInt32LE(offset + 4) + : chunk.readUInt32BE(offset + 4); + first = (first + high + second) >>> 0; + second = (second + low + first) >>> 0; + } + } + + return [first, second]; +} + +function encryptPageInto( + output: Buffer, + pageOffset: number, + body: Buffer, + pageNumber: number, + key: Buffer, + salt: Buffer, + algorithm: FixtureAlgorithm, +): void { + // Page 1 stores the KDF salt where SQLite keeps its magic, so its ciphertext + // starts one salt past the page boundary. + const offset = pageOffset + (pageNumber === 1 ? 16 : 0); + const reserve = reserveBytes(algorithm); + const cipherLength = body.length - reserve; + const iv = randomBytes(16); + const cipher = createCipheriv('aes-256-cbc', key, iv); + cipher.setAutoPadding(false); + const ciphertext = Buffer.concat([ + cipher.update(body.subarray(0, cipherLength)), + cipher.final(), + ]); + ciphertext.copy(output, offset); + iv.copy(output, offset + cipherLength); + + const digestBytes = DIGEST_BYTES[algorithm.pageHmac]; + + if (digestBytes === 0) { + return; + } + + const hmacSalt = Buffer.from(salt.map((byte) => byte ^ HMAC_SALT_MASK)); + const hmacKey = pbkdf2Sync(key, hmacSalt, HMAC_KEY_ITERATIONS, 32, algorithm.kdfHmac); + const pageNumberBytes = Buffer.alloc(4); + pageNumberBytes.writeUInt32LE(pageNumber); + const digest = createHmac(algorithm.pageHmac, hmacKey) + .update(ciphertext) + .update(iv) + .update(pageNumberBytes) + .digest(); + digest.copy(output, offset + cipherLength + 16); +} diff --git a/packages/bridge/tests/qq-account-login-db.test.ts b/packages/bridge/tests/qq-account-login-db.test.ts new file mode 100644 index 00000000..a9f29939 --- /dev/null +++ b/packages/bridge/tests/qq-account-login-db.test.ts @@ -0,0 +1,246 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdir, mkdtemp, rm, utimes, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { SqliteDatabase } from '@snowluma/sqlite'; + +const mocks = vi.hoisted(() => ({ + detectAlgorithm: vi.fn(), + decryptDatabase: vi.fn(), +})); + +// The page crypto is covered on its own; account reading stands on top of it, so +// the fixtures below hand over plaintext images and the decrypt step is stubbed +// to pass them through. +vi.mock('../src/qq-account/sqlcipher', () => ({ + detectAlgorithm: mocks.detectAlgorithm, + decryptDatabase: mocks.decryptDatabase, +})); + +vi.mock('../src/qq-account/paths', () => ({ + loginDbPaths: (root: string) => [path.join(root, PRIMARY), path.join(root, SECONDARY)], +})); + +import { readLocalAccounts } from '../src/qq-account/login-db'; + +const PRIMARY = path.join('global', 'nt_db', 'login.db'); +const SECONDARY = path.join('nt_qq', 'global', 'nt_db', 'login.db'); + +/** Write a plaintext database with QQ's account table at `file`. */ +async function writeLoginDb( + file: string, + rows: ReadonlyArray, +): Promise { + await mkdir(path.dirname(file), { recursive: true }); + await rm(file, { force: true }); + await rm(`${file}-wal`, { force: true }); + const db = new SqliteDatabase(file); + + try { + await db.exec('CREATE TABLE login_table("1000" TEXT, "1001" TEXT, "1007" TEXT)'); + + for (const [uin, uid, nickname] of rows) { + await db.prepare('INSERT INTO login_table VALUES (?, ?, ?)').run(uin, uid, nickname); + } + } finally { + await db.close(); + } +} + +async function makeRoot( + rows: ReadonlyArray, + secondaryRows: ReadonlyArray = [], +): Promise { + const root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-login-')); + await writeLoginDb(path.join(root, PRIMARY), rows); + + if (secondaryRows.length > 0) { + await writeLoginDb(path.join(root, SECONDARY), secondaryRows); + } + + return root; +} + +const roots: string[] = []; + +beforeEach(() => { + mocks.detectAlgorithm.mockReturnValue({ pageHmac: 'sha1', kdfHmac: 'sha512' }); + mocks.decryptDatabase.mockImplementation((image: Buffer) => ({ image, walFrames: 0 })); +}); + +afterEach(async () => { + mocks.detectAlgorithm.mockReset(); + mocks.decryptDatabase.mockReset(); + + for (const root of roots.splice(0)) { + await rm(root, { recursive: true, force: true }); + } +}); + +async function trackedRoot( + rows: ReadonlyArray, + secondaryRows: ReadonlyArray = [], +): Promise { + const root = await makeRoot(rows, secondaryRows); + roots.push(root); + return root; +} + +describe('local account list', () => { + it('reads the accounts QQ cached locally', async () => { + const root = await trackedRoot([['10001', 'u_a', 'Alice']]); + + await expect(readLocalAccounts(root)).resolves.toEqual({ + accounts: [{ uin: '10001', uid: 'u_a', nickname: 'Alice' }], + failures: [], + }); + }); + + it('merges both login.db locations, letting the primary win on a clash', async () => { + const root = await trackedRoot( + [ + ['10001', 'u_a', 'Alice'], + ['10002', 'u_b', 'Bob'], + ], + [ + ['10001', 'u_a_stale', 'AliceStale'], + ['10003', 'u_c', 'Carol'], + ], + ); + + expect(await readLocalAccounts(root)).toEqual({ + accounts: [ + { uin: '10001', uid: 'u_a', nickname: 'Alice' }, + { uin: '10002', uid: 'u_b', nickname: 'Bob' }, + { uin: '10003', uid: 'u_c', nickname: 'Carol' }, + ], + failures: [], + }); + }); + + it('re-decrypts only when the database or its sidecar changes', async () => { + const root = await trackedRoot([['10001', 'u_a', 'Alice']]); + const file = path.join(root, PRIMARY); + + await readLocalAccounts(root); + await readLocalAccounts(root); + expect(mocks.decryptDatabase).toHaveBeenCalledTimes(1); + + // A login that just happened rewrites the database; the new rows have to + // show up instead of the cached list. + await writeLoginDb(file, [ + ['10001', 'u_a', 'Alice'], + ['10002', 'u_b', 'Bob'], + ]); + await utimes(file, new Date(Date.now() + 60_000), new Date(Date.now() + 60_000)); + expect((await readLocalAccounts(root)).accounts).toHaveLength(2); + expect(mocks.decryptDatabase).toHaveBeenCalledTimes(2); + + // The sidecar counts as a change too: a batch committed to the WAL only + // leaves login.db untouched. + await writeFile(`${file}-wal`, Buffer.alloc(0)); + await readLocalAccounts(root); + expect(mocks.decryptDatabase).toHaveBeenCalledTimes(3); + }); + + it('shares concurrent reads of the same database image', async () => { + const root = await trackedRoot([['10001', 'u_a', 'Alice']]); + const reports = await Promise.all([readLocalAccounts(root), readLocalAccounts(root)]); + expect(reports[0]).toEqual(reports[1]); + expect(mocks.decryptDatabase).toHaveBeenCalledTimes(1); + }); + + it('reports an unreadable WAL instead of reading a stale base image', async () => { + const root = await trackedRoot([['10001', 'u_a', 'Alice']]); + const file = path.join(root, PRIMARY); + await mkdir(`${file}-wal`); + const report = await readLocalAccounts(root); + expect(report.accounts).toEqual([]); + expect(report.failures).toMatchObject([{ path: file, reason: 'read-failed' }]); + expect(report.failures[0]!.error).toBeDefined(); + }); + + it('reports missing schema columns instead of accepting quoted column names as identities', async () => { + const root = await trackedRoot([['10001', 'u_a', 'Alice']]); + const file = path.join(root, PRIMARY); + const db = new SqliteDatabase(file); + + try { + await db.exec('ALTER TABLE login_table DROP COLUMN "1001"'); + } finally { + await db.close(); + } + + const report = await readLocalAccounts(root); + expect(report.accounts).toEqual([]); + expect(report.failures).toMatchObject([{ path: file, reason: 'query-failed' }]); + expect(report.failures[0]!.error).toBeDefined(); + }); + + it('reports no accounts when the file cannot be decrypted, and retries later', async () => { + const root = await trackedRoot([['10001', 'u_a', 'Alice']]); + mocks.detectAlgorithm.mockReturnValue(null); + + await expect(readLocalAccounts(root)).resolves.toEqual({ + accounts: [], + failures: [{ path: path.join(root, PRIMARY), reason: 'undecryptable' }], + }); + + mocks.detectAlgorithm.mockReturnValue({ pageHmac: 'sha1', kdfHmac: 'sha512' }); + const file = path.join(root, PRIMARY); + await utimes(file, new Date(Date.now() + 60_000), new Date(Date.now() + 60_000)); + + await expect(readLocalAccounts(root)).resolves.toEqual({ + accounts: [{ uin: '10001', uid: 'u_a', nickname: 'Alice' }], + failures: [], + }); + }); + + it('names an unreadable login.db instead of reporting "no accounts"', async () => { + const root = await trackedRoot([['10001', 'u_a', 'Alice']]); + mocks.detectAlgorithm.mockReturnValue(null); + + // A login.db that cannot be decrypted is not the same as a machine with + // no accounts, and the caller has to be able to tell them apart. + await expect(readLocalAccounts(root)).resolves.toEqual({ + accounts: [], + failures: [{ path: path.join(root, PRIMARY), reason: 'undecryptable' }], + }); + }); + + it('keeps an unreadable sidecar from hiding the accounts a good database has', async () => { + const root = await trackedRoot([['10001', 'u_a', 'Alice']], [['10002', 'u_b', 'Bob']]); + const secondary = path.join(root, SECONDARY); + const bogus = Buffer.alloc(8192, 7); + mocks.detectAlgorithm.mockImplementation((image: Buffer) => + image[0] === 7 ? null : { pageHmac: 'sha1', kdfHmac: 'sha512' }, + ); + await writeFile(secondary, bogus); + + const report = await readLocalAccounts(root); + expect(report.accounts.map((account) => account.uin)).toEqual(['10001']); + expect(report.failures).toEqual([{ path: secondary, reason: 'undecryptable' }]); + }); + + it('skips rows that carry no usable identity', async () => { + const root = await trackedRoot([ + ['10001', 'u_a', 'Alice'], + ['10002', '', 'Broken'], + ['', 'u_d', 'Nameless'], + ['../10001', 'u_e', 'Invalid UIN'], + ]); + + await expect(readLocalAccounts(root)).resolves.toEqual({ + accounts: [{ uin: '10001', uid: 'u_a', nickname: 'Alice' }], + failures: [], + }); + }); + + it('reports no accounts when login.db is missing', async () => { + const root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-login-')); + roots.push(root); + + // Neither candidate file exists: nothing cached, and nothing to report. + await expect(readLocalAccounts(root)).resolves.toEqual({ accounts: [], failures: [] }); + }); +}); diff --git a/packages/bridge/tests/qq-account-path-isolation.test.ts b/packages/bridge/tests/qq-account-path-isolation.test.ts new file mode 100644 index 00000000..a461de29 --- /dev/null +++ b/packages/bridge/tests/qq-account-path-isolation.test.ts @@ -0,0 +1,51 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import path from 'node:path'; +import { qqDataRoots, qqDataRootsForPid } from '../src/qq-account/paths'; + +const files = vi.hoisted(() => ({ read: vi.fn() })); +vi.mock('node:fs', () => ({ readFileSync: files.read })); +const platform = process.platform; + +beforeEach(() => { + Object.defineProperty(process, 'platform', { value: 'linux', configurable: true }); +}); +afterEach(() => { + Object.defineProperty(process, 'platform', { value: platform, configurable: true }); + files.read.mockReset(); +}); + +describe('account data root isolation', () => { + it('uses the client HOME and honours its XDG configuration', () => { + files.read.mockReturnValue('HOME=/clients/a\0IGNORED=value\0'); + expect(qqDataRootsForPid(42)).toEqual([path.join('/clients/a', '.config', 'QQ')]); + files.read.mockReturnValue('HOME=/clients/a\0XDG_CONFIG_HOME=/clients/config\0'); + expect(qqDataRootsForPid(42)).toEqual([path.join('/clients/config', 'QQ')]); + }); + + it('does not guess a HOME when the client environment has none', () => { + files.read.mockReturnValue('OTHER=value\0'); + expect(qqDataRootsForPid(42)).toEqual([]); + }); + + it('reports no root for an exited process', () => { + files.read.mockImplementation(() => { + throw Object.assign(new Error('gone'), { code: 'ENOENT' }); + }); + expect(qqDataRootsForPid(42)).toEqual([]); + }); + + it('surfaces permission failures instead of reading another user directory', () => { + const error = Object.assign(new Error('denied'), { code: 'EACCES' }); + files.read.mockImplementation(() => { + throw error; + }); + expect(() => qqDataRootsForPid(42)).toThrow(error); + }); + + it('uses only the configured Windows data root', () => { + Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }); + files.read.mockReturnValue('[UserDataSet]\nUserDataSavePath=D:\\QQ\\Tencent Files\n'); + expect(qqDataRoots()).toEqual(['D:\\QQ\\Tencent Files']); + expect(files.read).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/bridge/tests/qq-account-paths.test.ts b/packages/bridge/tests/qq-account-paths.test.ts new file mode 100644 index 00000000..c0da04da --- /dev/null +++ b/packages/bridge/tests/qq-account-paths.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, it } from 'vitest'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { + accountDirName, + loginDbPaths, + ntMsgDbPath, + tencentFilesRootFromUserDataInfo, +} from '../src/qq-account/paths'; + +const IS_WINDOWS = process.platform === 'win32'; + +describe('QQ data paths', () => { + it('derives the Linux account directory from the account uid', () => { + // md5(md5("u_test_account") + "nt_kernel") + expect(accountDirName('u_test_account')).toBe('nt_qq_7b9b3c3f2cf89e087b2e024777ea5f5f'); + }); + + it('lists the login.db locations of the current platform', () => { + const root = 'root'; + const windows = path.join(root, 'nt_qq', 'global', 'nt_db', 'login.db'); + + expect(loginDbPaths(root)).toEqual( + IS_WINDOWS ? [windows] : [path.join(root, 'global', 'nt_db', 'login.db'), windows], + ); + }); + + it('locates an account database per platform', () => { + const root = 'root'; + const account = { uin: '10001', uid: 'u_test_account' }; + + expect(ntMsgDbPath(root, account)).toBe( + IS_WINDOWS + ? path.join(root, '10001', 'nt_qq', 'nt_db', 'nt_msg.db') + : path.join(root, 'nt_qq_7b9b3c3f2cf89e087b2e024777ea5f5f', 'nt_db', 'nt_msg.db'), + ); + }); +}); + +describe('Windows data root detection', () => { + /** Recreate `/Documents/Tencent/QQ/UserDataInfo.ini` for a fake home. */ + async function withUserDataInfo( + contents: string, + run: (home: string) => Promise | void, + ): Promise { + const base = await mkdtemp(path.join(os.tmpdir(), 'snowluma-ini-')); + + try { + const home = path.join(base, 'user'); + const ini = path.join(base, 'Public', 'Documents', 'Tencent', 'QQ', 'UserDataInfo.ini'); + await mkdir(path.dirname(ini), { recursive: true }); + await writeFile(ini, contents, 'utf8'); + await run(home); + } finally { + await rm(base, { recursive: true, force: true }); + } + } + + it('reads UserDataSavePath from the ini QQ itself writes', async () => { + await withUserDataInfo( + '[UserDataSet]\nUserDataSavePath=D:\\Tencent\\Tencent Files\n', + (home) => { + expect(tencentFilesRootFromUserDataInfo(home)).toBe('D:\\Tencent\\Tencent Files'); + }, + ); + }); + + it('appends the Tencent Files segment when the ini stops one level short', async () => { + await withUserDataInfo('[UserDataSet]\nUserDataSavePath=D:\\Tencent\n', (home) => { + expect(tencentFilesRootFromUserDataInfo(home)).toBe('D:\\Tencent\\Tencent Files'); + }); + }); + + it('ignores other sections and the UserDataSavePathType key', async () => { + await withUserDataInfo( + [ + '[UserDataImportSet]', + 'OldVerDataPath=D:\\Legacy\\Tencent Files', + '[UserDataSet]', + 'UserDataSavePathType=2', + 'UserDataSavePath=E:\\Current\\Tencent Files', + '', + ].join('\n'), + (home) => { + expect(tencentFilesRootFromUserDataInfo(home)).toBe('E:\\Current\\Tencent Files'); + }, + ); + }); + + it('reports nothing when the ini is missing', async () => { + const base = await mkdtemp(path.join(os.tmpdir(), 'snowluma-ini-')); + + try { + expect(tencentFilesRootFromUserDataInfo(path.join(base, 'absent'))).toBeNull(); + } finally { + await rm(base, { recursive: true, force: true }); + } + }); + + it('reports nothing when the ini has no usable path', async () => { + await withUserDataInfo('[UserDataSet]\nUserDataSavePath=\n', (home) => { + expect(tencentFilesRootFromUserDataInfo(home)).toBeNull(); + }); + }); +}); diff --git a/packages/bridge/tests/qq-account-real-data.test.ts b/packages/bridge/tests/qq-account-real-data.test.ts new file mode 100644 index 00000000..cacd5e72 --- /dev/null +++ b/packages/bridge/tests/qq-account-real-data.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest'; +import { detectAccountLogins } from '../src/qq-account/detect'; + +/** + * Account detection against a real QQ data directory. + * + * Point `SNOWLUMA_QQ_DATA_ROOT` at one (for example `~/.config/QQ`) to run + * these; without it they are skipped, which is what CI and any machine without + * the client do. They are the only check that exercises login.db as QQ actually + * writes it, together with the holder probe on the databases it currently holds. + */ +const REAL_DATA_ROOT = process.env.SNOWLUMA_QQ_DATA_ROOT; + +describe('account detection against real client data', () => { + it.runIf(Boolean(REAL_DATA_ROOT))('reads the accounts and their processes', async () => { + const accounts = await detectAccountLogins([REAL_DATA_ROOT!]); + + expect(accounts.length).toBeGreaterThan(0); + + for (const account of accounts) { + expect(account.uin).toMatch(/^\d{5,10}$/); + expect(account.uid).toMatch(/^u_/); + + if (account.pid !== null) { + expect(Number.isInteger(account.pid)).toBe(true); + expect(() => process.kill(account.pid!, 0)).not.toThrow(); + } + } + }); +}); diff --git a/packages/bridge/tests/qq-account-sqlcipher.test.ts b/packages/bridge/tests/qq-account-sqlcipher.test.ts new file mode 100644 index 00000000..e43c90be --- /dev/null +++ b/packages/bridge/tests/qq-account-sqlcipher.test.ts @@ -0,0 +1,324 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { SqliteDatabase } from '@snowluma/sqlite'; +import { + DATABASE_HEADER_SIZE, + decryptDatabase, + detectAlgorithm, + type SqlcipherAlgorithm, +} from '../src/qq-account/sqlcipher'; +import { + FIXTURE_HEADER_SIZE, + FIXTURE_PAGE_SIZE, + FIXTURE_PASSPHRASE, + FIXTURE_WAL_FRAME_HEADER_SIZE, + FIXTURE_WAL_HEADER_SIZE, + encryptImage, + encryptWal, + reserveBytes, + walChecksum, + type FixtureAlgorithm, +} from './qq-account-fixtures'; + +const SHA1_SHA512: FixtureAlgorithm = { pageHmac: 'sha1', kdfHmac: 'sha512' }; + +/** + * Reserved space SQLite is told about for an encrypted database: room for the + * IV plus the largest page digest. SQLCipher's own reserve always fits inside + * it, which is why the tail of every page is disposable. + */ +const HEADER_RESERVED_BYTES = 80; + +/** Offset of one frame in a `-wal` buffer. */ +function frameOffset(index: number): number { + return FIXTURE_WAL_HEADER_SIZE + index * (FIXTURE_WAL_FRAME_HEADER_SIZE + FIXTURE_PAGE_SIZE); +} + +/** Last frame index a merge may have applied, or -1 when nothing was committed. */ +function lastCommitFrame(wal: Buffer, maxFrameIndex = frameCount(wal) - 1): number { + let last = -1; + + for (let index = 0; index <= maxFrameIndex; index++) { + if (wal.readUInt32BE(frameOffset(index) + 4) !== 0) { + last = index; + } + } + + return last; +} + +function frameCount(wal: Buffer): number { + const frameSize = FIXTURE_WAL_FRAME_HEADER_SIZE + FIXTURE_PAGE_SIZE; + return Math.floor((wal.length - FIXTURE_WAL_HEADER_SIZE) / frameSize); +} + +/** Frames up to and including the last commit, i.e. what a merge should apply. */ +function committedFrames(wal: Buffer, maxFrameIndex?: number): number { + return lastCommitFrame(wal, maxFrameIndex) + 1; +} + +/** Database size the last applicable commit declares. */ +function lastCommitSize(wal: Buffer, maxFrameIndex?: number): number { + return wal.readUInt32BE(frameOffset(lastCommitFrame(wal, maxFrameIndex)) + 4); +} + +/** Page content as the last applicable commit left it, keyed by page number. */ +function committedPages(wal: Buffer, maxFrameIndex?: number): Map { + const pages = new Map(); + const last = lastCommitFrame(wal, maxFrameIndex); + const size = lastCommitSize(wal, maxFrameIndex); + + for (let index = 0; index <= last; index++) { + const pageNumber = wal.readUInt32BE(frameOffset(index)); + + if (pageNumber >= 1 && pageNumber <= size) { + pages.set( + pageNumber, + wal.subarray( + frameOffset(index) + FIXTURE_WAL_FRAME_HEADER_SIZE, + frameOffset(index + 1), + ), + ); + } + } + + return pages; +} + +/** Compare one merged page against the page a frame carried. */ +function expectPageMatches( + merged: Buffer, + expectedPage: Buffer, + pageNumber: number, + algorithm: FixtureAlgorithm, +): void { + const reserve = reserveBytes(algorithm); + const start = (pageNumber - 1) * FIXTURE_PAGE_SIZE; + // Page 1's SQLite header carries the fields the merge keeps consistent with + // the assembled image (change counter, page count, journal mode), so only the + // page body is compared there. + const bodyStart = pageNumber === 1 ? 100 : 0; + expect(merged.subarray(start + bodyStart, start + FIXTURE_PAGE_SIZE - reserve)).toEqual( + expectedPage.subarray(bodyStart, FIXTURE_PAGE_SIZE - reserve), + ); + expect( + merged + .subarray(start + FIXTURE_PAGE_SIZE - reserve, start + FIXTURE_PAGE_SIZE) + .equals(Buffer.alloc(reserve)), + ).toBe(true); +} + +/** A plaintext image with the header fields the merge keeps consistent. */ +function plaintextImage(pageCount: number, marker = 0): Buffer { + const image = Buffer.alloc(pageCount * FIXTURE_PAGE_SIZE); + + for (let page = 0; page < pageCount; page++) { + for (let offset = 0; offset < FIXTURE_PAGE_SIZE - HEADER_RESERVED_BYTES; offset++) { + image[page * FIXTURE_PAGE_SIZE + offset] = (page * 31 + offset + marker) % 251; + } + } + + image.write('SQLite format 3\0', 0, 'latin1'); + image.writeUInt16BE(FIXTURE_PAGE_SIZE, 16); + image[18] = 1; + image[19] = 1; + image[20] = HEADER_RESERVED_BYTES; + image[21] = 64; + image[22] = 32; + image[23] = 32; + image.writeUInt32BE(7, 24); + image.writeUInt32BE(pageCount, 28); + image.writeUInt32BE(7, 92); + return image; +} + +/** A real SQLite database in WAL mode, plus the sidecar SQLite wrote for it. */ +async function realWalDatabase( + directory: string, + inserts: string[][], +): Promise<{ image: Buffer; wal: Buffer; db: SqliteDatabase }> { + const file = path.join(directory, 'source.db'); + const db = new SqliteDatabase(file); + await db.exec('PRAGMA wal_autocheckpoint = 0'); + await db.exec('CREATE TABLE t(value TEXT)'); + + for (const [value] of inserts) { + await db.prepare('INSERT INTO t VALUES (?)').run(value); + } + + return { image: await readFile(file), wal: await readFile(`${file}-wal`), db }; +} + +describe('SQLCipher page decryption', () => { + it('round-trips a page image and normalizes the header', () => { + const plain = plaintextImage(3); + plain[18] = 2; // stored as a WAL-mode database, like QQ writes them + plain[19] = 2; + const encrypted = encryptImage(plain, SHA1_SHA512); + + expect(detectAlgorithm(encrypted, FIXTURE_PASSPHRASE)).toEqual(SHA1_SHA512); + + const decrypted = decryptDatabase(encrypted, null, FIXTURE_PASSPHRASE, SHA1_SHA512); + expect(decrypted).not.toBeNull(); + + const expected = Buffer.from(plain); + expected[18] = 1; + expected[19] = 1; + expected.writeUInt32BE(3, 28); + expected.writeUInt32BE(7, 92); + expect(decrypted!.image.equals(expected)).toBe(true); + expect(decrypted!.walFrames).toBe(0); + }); + + it('probes the algorithm pair instead of assuming one', () => { + const plain = plaintextImage(2); + + for (const algorithm of [ + { pageHmac: 'sha256', kdfHmac: 'sha256' }, + { pageHmac: 'sha512', kdfHmac: 'sha1' }, + { pageHmac: 'none', kdfHmac: 'sha512' }, + ] satisfies SqlcipherAlgorithm[]) { + const encrypted = encryptImage(plain, algorithm); + expect(detectAlgorithm(encrypted, FIXTURE_PASSPHRASE)).toEqual(algorithm); + expect( + decryptDatabase(encrypted, null, FIXTURE_PASSPHRASE, algorithm)!.image.equals( + plain, + ), + ).toBe(true); + } + }); + + it('rejects a wrong passphrase and a file that is too short', () => { + const encrypted = encryptImage(plaintextImage(2), SHA1_SHA512); + expect(detectAlgorithm(encrypted, 'wrong-passphrase')).toBeNull(); + expect( + detectAlgorithm(Buffer.alloc(DATABASE_HEADER_SIZE + 512), FIXTURE_PASSPHRASE), + ).toBeNull(); + expect(decryptDatabase(Buffer.alloc(64), null, FIXTURE_PASSPHRASE, SHA1_SHA512)).toBeNull(); + }); +}); + +describe('SQLCipher WAL folding', () => { + it('reproduces the frame checksums SQLite itself wrote', async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), 'snowluma-wal-')); + + try { + const { wal, db } = await realWalDatabase(directory, [['a'], ['b']]); + const littleEndian = wal.readUInt32BE(0) === 0x377f0682; + const frameSize = FIXTURE_WAL_FRAME_HEADER_SIZE + FIXTURE_PAGE_SIZE; + expect((wal.length - FIXTURE_WAL_HEADER_SIZE) % frameSize).toBe(0); + + const header = walChecksum( + [0, 0], + [wal.subarray(0, FIXTURE_WAL_HEADER_SIZE - 8)], + littleEndian, + ); + expect(header).toEqual([wal.readUInt32BE(24), wal.readUInt32BE(28)]); + + let running = header; + + for ( + let offset = FIXTURE_WAL_HEADER_SIZE; + offset + frameSize <= wal.length; + offset += frameSize + ) { + const frame = wal.subarray(offset, offset + FIXTURE_WAL_FRAME_HEADER_SIZE); + running = walChecksum( + running, + [ + frame.subarray(0, 8), + wal.subarray(offset + FIXTURE_WAL_FRAME_HEADER_SIZE, offset + frameSize), + ], + littleEndian, + ); + expect(running).toEqual([frame.readUInt32BE(16), frame.readUInt32BE(20)]); + } + + await db.close(); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); + + it('folds every committed frame into the decrypted image', async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), 'snowluma-wal-')); + + try { + const { image, wal, db } = await realWalDatabase(directory, [['a'], ['b']]); + const encryptedImage = encryptImage(image, SHA1_SHA512); + const encryptedWal = encryptWal(wal, encryptedImage, SHA1_SHA512); + + const decrypted = decryptDatabase( + encryptedImage, + encryptedWal, + FIXTURE_PASSPHRASE, + SHA1_SHA512, + ); + expect(decrypted!.walFrames).toBe(committedFrames(wal)); + expect(decrypted!.image.length).toBe(lastCommitSize(wal) * FIXTURE_PAGE_SIZE); + + // Every page a committed frame carried has to arrive as it was written, + // apart from the on-disk IV/HMAC region the encryptor owns. + for (const [pageNumber, page] of committedPages(wal)) { + expectPageMatches(decrypted!.image, page, pageNumber, SHA1_SHA512); + } + + await db.close(); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); + + it('keeps the intact prefix of a WAL torn by a running client', async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), 'snowluma-wal-')); + + try { + const { image, wal, db } = await realWalDatabase(directory, [['a'], ['b']]); + const encryptedImage = encryptImage(image, SHA1_SHA512); + const encryptedWal = encryptWal(wal, encryptedImage, SHA1_SHA512); + const frameSize = FIXTURE_WAL_FRAME_HEADER_SIZE + FIXTURE_PAGE_SIZE; + const frameCount = (wal.length - FIXTURE_WAL_HEADER_SIZE) / frameSize; + // Shred the last frame's page: everything after the previous commit + // must be dropped rather than half-applied. + encryptedWal[encryptedWal.length - 8] ^= 0xff; + + const decrypted = decryptDatabase( + encryptedImage, + encryptedWal, + FIXTURE_PASSPHRASE, + SHA1_SHA512, + ); + expect(decrypted).not.toBeNull(); + expect(decrypted!.walFrames).toBeLessThan(frameCount); + // Frames up to the tear survive; the merge still stops at the last + // commit they contain rather than applying a partial transaction. + expect(decrypted!.walFrames).toBe(committedFrames(wal, frameCount - 2)); + + // Everything the surviving commits wrote has to be in the image. + for (const [pageNumber, page] of committedPages(wal, frameCount - 2)) { + expectPageMatches(decrypted!.image, page, pageNumber, SHA1_SHA512); + } + + await db.close(); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); +}); + +describe('SQLCipher header handling', () => { + it('keeps the client header opaque and stores the salt at the start of page 1', () => { + const plain = plaintextImage(2); + const encrypted = encryptImage(plain, SHA1_SHA512); + const header = encrypted.subarray(0, FIXTURE_HEADER_SIZE); + + expect(header.equals(Buffer.alloc(FIXTURE_HEADER_SIZE))).toBe(true); + expect( + encrypted + .subarray(FIXTURE_HEADER_SIZE + 16, FIXTURE_HEADER_SIZE + 48) + .equals(plain.subarray(16, 48)), + ).toBe(false); + }); +}); diff --git a/packages/bridge/tests/qq-port-probe-more.test.ts b/packages/bridge/tests/qq-port-probe-more.test.ts deleted file mode 100644 index 63562899..00000000 --- a/packages/bridge/tests/qq-port-probe-more.test.ts +++ /dev/null @@ -1,724 +0,0 @@ -import { EventEmitter } from 'events'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { getLogLevel, setLogLevel, subscribeLogs } from '@snowluma/common/logger'; - -const execMock = vi.hoisted(() => vi.fn()); -const httpGetMock = vi.hoisted(() => vi.fn()); -const httpsGetMock = vi.hoisted(() => vi.fn()); - -vi.mock('child_process', () => ({ exec: execMock })); -vi.mock('http', () => ({ - default: { get: httpGetMock }, - get: httpGetMock, -})); -vi.mock('https', () => ({ - default: { get: httpsGetMock }, - get: httpsGetMock, -})); - -import { probeQqLoginInfo } from '../src/qq-port-probe'; - -const originalPlatform = process.platform; -const EXEC_OPTIONS = { timeout: 1500, killSignal: 'SIGKILL' }; -const PTLOGIN_HEADERS = { - Host: 'localhost.ptlogin2.qq.com', - Referer: 'https://xui.ptlogin2.qq.com/', - Cookie: 'pt_local_token=0', -}; - -type ExecCallback = (error: Error | null, result?: { stdout: string; stderr: string }) => void; -type RequestLike = EventEmitter & { destroy: ReturnType }; - -function setPlatform(platform: string): void { - Object.defineProperty(process, 'platform', { value: platform, configurable: true }); -} - -function mockExec(replies: Record): void { - execMock.mockImplementation((command: string, _options: unknown, callback: ExecCallback) => { - const reply = replies[command]; - - if (reply === undefined) { - callback(new Error(`unexpected command ${command}`)); - return; - } - - if (reply instanceof Error) { - callback(reply); - return; - } - - callback(null, { stdout: reply, stderr: '' }); - }); -} - -function execCommands(): string[] { - return execMock.mock.calls.map((call) => String(call[0])); -} - -function ssLine(port: number, pid: number, owner: 'comma' | 'paren' = 'comma'): string { - const tag = owner === 'comma' ? `pid=${pid},fd=9` : `pid=${pid}`; - return `LISTEN 0 128 127.0.0.1:${port} 0.0.0.0:* users:(("qq",${tag}))`; -} - -function netstatLine(localAddr: string, pid: number): string { - return ` TCP ${localAddr} 0.0.0.0:0 LISTENING ${pid}`; -} - -function jsonp(accounts: unknown[]): string { - return `ptui_getuins_CB(${JSON.stringify(accounts)});`; -} - -function requestStub(): RequestLike { - const req = new EventEmitter() as RequestLike; - req.destroy = vi.fn(); - return req; -} - -function replyBody(body: string | ReadonlyArray) { - return ( - _url: string, - _options: unknown, - onResponse: (res: EventEmitter) => void, - ): RequestLike => { - const req = requestStub(); - const res = new EventEmitter(); - onResponse(res); - const chunks = typeof body === 'string' ? [body] : body; - - for (const chunk of chunks) { - res.emit('data', chunk); - } - - res.emit('end'); - return req; - }; -} - -function replyError(error: Error) { - return (): RequestLike => { - const req = requestStub(); - queueMicrotask(() => req.emit('error', error)); - return req; - }; -} - -beforeEach(() => { - execMock.mockReset(); - httpGetMock.mockReset(); - httpsGetMock.mockReset(); - setPlatform('linux'); -}); - -afterEach(() => { - setPlatform(originalPlatform); - vi.useRealTimers(); -}); - -describe('probeQqLoginInfo — unix listing', () => { - it('returns null when ss cannot list sockets', async () => { - mockExec({ 'ss -tlnp': new Error('ss: not found') }); - - await expect(probeQqLoginInfo(3310)).resolves.toBeNull(); - expect(execCommands()).toEqual(['ss -tlnp']); - expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS); - expect(httpGetMock).not.toHaveBeenCalled(); - expect(httpsGetMock).not.toHaveBeenCalled(); - }); - - it('reports a logged-out identity when the PID has no sockets and pgrep is below 6', async () => { - mockExec({ - 'ss -tlnp': 'State Recv-Q Send-Q Local Address:Port Peer Address:Port\n', - 'pgrep -c qq': '5\n', - }); - - await expect(probeQqLoginInfo(3311)).resolves.toEqual({ - port: 0, - uin: '', - identityKnown: false, - }); - expect(execCommands()).toEqual(['ss -tlnp', 'pgrep -c qq']); - expect(execMock.mock.calls[1]?.[1]).toEqual(EXEC_OPTIONS); - }); - - it('treats a pgrep count of 0 as logged out', async () => { - mockExec({ - 'ss -tlnp': '', - 'pgrep -c qq': '0\n', - }); - - await expect(probeQqLoginInfo(3312)).resolves.toEqual({ - port: 0, - uin: '', - identityKnown: false, - }); - }); - - it('treats a non-numeric pgrep count as 0 and therefore logged out', async () => { - mockExec({ - 'ss -tlnp': '', - 'pgrep -c qq': 'qq: no process found\n', - }); - - await expect(probeQqLoginInfo(3313)).resolves.toEqual({ - port: 0, - uin: '', - identityKnown: false, - }); - }); - - it('returns null when there are no sockets and pgrep is 6 or higher', async () => { - mockExec({ - 'ss -tlnp': '', - 'pgrep -c qq': '6\n', - }); - await expect(probeQqLoginInfo(3314)).resolves.toBeNull(); - - mockExec({ - 'ss -tlnp': '', - 'pgrep -c qq': '9\n', - }); - await expect(probeQqLoginInfo(3315)).resolves.toBeNull(); - }); - - it('does not treat a failed pgrep as logged out', async () => { - mockExec({ - 'ss -tlnp': '', - 'pgrep -c qq': new Error('pgrep: exit 1'), - }); - - await expect(probeQqLoginInfo(3316)).resolves.toBeNull(); - }); - - it('uses the first listening port as a logged-out hint when no Ptlogin port is present', async () => { - mockExec({ - 'ss -tlnp': [ssLine(9218, 4410), ssLine(18000, 4410)].join('\n'), - 'pgrep -c qq': ' 4 \n', - }); - - await expect(probeQqLoginInfo(4410)).resolves.toEqual({ - port: 9218, - uin: '', - identityKnown: false, - }); - expect(httpGetMock).not.toHaveBeenCalled(); - expect(httpsGetMock).not.toHaveBeenCalled(); - }); - - it('returns null for non-Ptlogin ports when the QQ process count is ambiguous', async () => { - mockExec({ - 'ss -tlnp': ssLine(9218, 4411), - 'pgrep -c qq': '7\n', - }); - - await expect(probeQqLoginInfo(4411)).resolves.toBeNull(); - expect(httpGetMock).not.toHaveBeenCalled(); - expect(httpsGetMock).not.toHaveBeenCalled(); - }); - - it('collects unique ports from ss lines that name the PID with either pid=N, or pid=N)', async () => { - mockExec({ - 'ss -tlnp': [ - 'LISTEN 0 128 127.0.0.1:4301users:(("qq",pid=4412,fd=1))', - ssLine(4301, 4412, 'comma'), - ssLine(4301, 4412, 'comma'), - ssLine(4305, 4412, 'paren'), - ssLine(4305, 9999, 'comma'), - 'ESTAB 0 0 127.0.0.1:4307 127.0.0.1:443 users:(("qq",pid=4412,fd=4))', - ].join('\n'), - }); - httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '10001', nickname: 'Ada' }]))); - - await expect(probeQqLoginInfo(4412)).resolves.toEqual({ - port: 4301, - uin: '10001', - nickName: 'Ada', - identityKnown: true, - }); - expect(httpsGetMock).toHaveBeenCalledTimes(2); - expect(httpsGetMock.mock.calls[0]?.[0]).toBe( - 'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', - ); - }); -}); - -describe('probeQqLoginInfo — Ptlogin identity', () => { - it('reads a single account from an odd Ptlogin port over https', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5501) }); - httpsGetMock.mockImplementation( - replyBody( - jsonp([ - { - uin: 319427101, - account: 1, - nickname: 'Snow', - extra: 'ignored', - }, - ]), - ), - ); - - await expect(probeQqLoginInfo(5501)).resolves.toEqual({ - port: 4301, - uin: '319427101', - nickName: 'Snow', - identityKnown: true, - }); - expect(httpGetMock).not.toHaveBeenCalled(); - expect(httpsGetMock).toHaveBeenCalledTimes(2); - expect(httpsGetMock.mock.calls[0]?.[1]).toEqual({ - headers: PTLOGIN_HEADERS, - timeout: 500, - rejectUnauthorized: false, - }); - }); - - it('reads a single account from an even Ptlogin port over http', async () => { - mockExec({ 'ss -tlnp': ssLine(4302, 5502) }); - httpGetMock.mockImplementation( - replyBody( - jsonp([ - { - account: '2880036470', - }, - ]), - ), - ); - - await expect(probeQqLoginInfo(5502)).resolves.toEqual({ - port: 4302, - uin: '2880036470', - nickName: '', - identityKnown: true, - }); - expect(httpsGetMock).not.toHaveBeenCalled(); - expect(httpGetMock).toHaveBeenCalledTimes(2); - expect(httpGetMock.mock.calls[0]?.[0]).toBe( - 'http://127.0.0.1:4302/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', - ); - expect(httpGetMock.mock.calls[0]?.[1]).toEqual({ - headers: PTLOGIN_HEADERS, - timeout: 500, - }); - }); - - it('probes every documented odd Ptlogin port over https', async () => { - for (const port of [4301, 4303, 4305, 4307, 4309]) { - execMock.mockReset(); - httpsGetMock.mockReset(); - httpGetMock.mockReset(); - mockExec({ 'ss -tlnp': ssLine(port, 5510) }); - httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '70001', nickname: 'Odd' }]))); - - await expect(probeQqLoginInfo(5510)).resolves.toEqual({ - port, - uin: '70001', - nickName: 'Odd', - identityKnown: true, - }); - expect(httpGetMock).not.toHaveBeenCalled(); - expect(String(httpsGetMock.mock.calls[0]?.[0])).toBe( - `https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`, - ); - } - }); - - it('probes every documented even Ptlogin port over http when no odd port is listening', async () => { - for (const port of [4302, 4304, 4306, 4308, 4310]) { - execMock.mockReset(); - httpsGetMock.mockReset(); - httpGetMock.mockReset(); - mockExec({ 'ss -tlnp': ssLine(port, 5511) }); - httpGetMock.mockImplementation(replyBody(jsonp([{ uin: '70002', nickname: 'Even' }]))); - - await expect(probeQqLoginInfo(5511)).resolves.toEqual({ - port, - uin: '70002', - nickName: 'Even', - identityKnown: true, - }); - expect(httpsGetMock).not.toHaveBeenCalled(); - expect(String(httpGetMock.mock.calls[0]?.[0])).toBe( - `http://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`, - ); - } - }); - - it('prefers odd Ptlogin ports and never falls through to even ones', async () => { - mockExec({ - 'ss -tlnp': [ssLine(4302, 5520), ssLine(4301, 5520)].join('\n'), - }); - httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED'))); - - await expect(probeQqLoginInfo(5520)).resolves.toBeNull(); - expect(httpsGetMock).toHaveBeenCalled(); - expect(httpGetMock).not.toHaveBeenCalled(); - expect(execCommands()).toEqual(['ss -tlnp']); - }); - - it('tries the next odd Ptlogin port after the first one fails', async () => { - mockExec({ - 'ss -tlnp': [ssLine(4301, 5521), ssLine(4305, 5521)].join('\n'), - }); - httpsGetMock - .mockImplementationOnce(replyBody('nope')) - .mockImplementationOnce(replyBody('nope')) - .mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }]))) - .mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }]))); - - await expect(probeQqLoginInfo(5521)).resolves.toEqual({ - port: 4305, - uin: '188888', - nickName: 'Next', - identityKnown: true, - }); - expect(httpsGetMock.mock.calls.map((call) => call[0])).toEqual([ - 'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', - 'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', - 'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', - 'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', - ]); - }); - - it('stops after the first Ptlogin port that yields a single account', async () => { - mockExec({ - 'ss -tlnp': [ssLine(4303, 5522), ssLine(4309, 5522)].join('\n'), - }); - httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '42', nickname: 'First' }]))); - - await expect(probeQqLoginInfo(5522)).resolves.toEqual({ - port: 4303, - uin: '42', - nickName: 'First', - identityKnown: true, - }); - expect(httpsGetMock).toHaveBeenCalledTimes(2); - }); - - it('uses account when uin is missing or empty, including a numeric 0 uin', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5530) }); - httpsGetMock - .mockImplementationOnce( - replyBody(jsonp([{ uin: 0, account: 314159, nickname: 'Zero' }])), - ) - .mockImplementationOnce( - replyBody(jsonp([{ uin: '', account: '314159', nickname: 'Zero' }])), - ); - - await expect(probeQqLoginInfo(5530)).resolves.toEqual({ - port: 4301, - uin: '314159', - nickName: 'Zero', - identityKnown: true, - }); - }); - - it('returns an empty uin when the single account has neither uin nor account', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5531) }); - httpsGetMock.mockImplementation(replyBody('[{"nickname":"Anon"}]')); - - await expect(probeQqLoginInfo(5531)).resolves.toEqual({ - port: 4301, - uin: '', - nickName: 'Anon', - identityKnown: true, - }); - }); - - it('keeps the shorter of the two pt_get_uins snapshots', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5540) }); - httpsGetMock - .mockImplementationOnce( - replyBody( - jsonp([ - { uin: '11', nickname: 'A' }, - { uin: '22', nickname: 'B' }, - ]), - ), - ) - .mockImplementationOnce(replyBody(jsonp([{ uin: '33', nickname: 'Cora' }]))); - - await expect(probeQqLoginInfo(5540)).resolves.toEqual({ - port: 4301, - uin: '33', - nickName: 'Cora', - identityKnown: true, - }); - }); - - it('keeps the first snapshot when both pt_get_uins calls have one account', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5541) }); - httpsGetMock - .mockImplementationOnce(replyBody(jsonp([{ uin: '100', nickname: 'Left' }]))) - .mockImplementationOnce(replyBody(jsonp([{ uin: '200', nickname: 'Right' }]))); - - await expect(probeQqLoginInfo(5541)).resolves.toEqual({ - port: 4301, - uin: '100', - nickName: 'Left', - identityKnown: true, - }); - }); - - it('accepts a single account from the second fetch when the first fetch is unusable', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5542) }); - httpsGetMock - .mockImplementationOnce(replyError(new Error('ECONNRESET'))) - .mockImplementationOnce(replyBody(jsonp([{ uin: '9090', nickname: 'Retry' }]))); - - await expect(probeQqLoginInfo(5542)).resolves.toEqual({ - port: 4301, - uin: '9090', - nickName: 'Retry', - identityKnown: true, - }); - }); - - it('returns null for an empty pt_get_uins array and does not consult pgrep', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5550) }); - httpsGetMock.mockImplementation(replyBody('ptui_getuins_CB([]);')); - - await expect(probeQqLoginInfo(5550)).resolves.toBeNull(); - expect(execCommands()).toEqual(['ss -tlnp']); - }); - - it('returns null when both snapshots have more than one account', async () => { - mockExec({ 'ss -tlnp': ssLine(4304, 5551) }); - httpGetMock.mockImplementation(replyBody(jsonp([{ uin: '1' }, { uin: '2' }]))); - - await expect(probeQqLoginInfo(5551)).resolves.toBeNull(); - }); - - it('returns null when both fetches fail to parse a pt_get_uins body', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5552) }); - httpsGetMock.mockImplementation(replyBody('not-jsonp')); - - await expect(probeQqLoginInfo(5552)).resolves.toBeNull(); - }); - - it('returns null when both fetches error', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5553) }); - httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED'))); - - await expect(probeQqLoginInfo(5553)).resolves.toBeNull(); - }); - - it('destroys the request and returns null when both fetches time out', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5554) }); - const seen: RequestLike[] = []; - httpsGetMock.mockImplementation(() => { - const req = requestStub(); - seen.push(req); - queueMicrotask(() => req.emit('timeout')); - return req; - }); - - await expect(probeQqLoginInfo(5554)).resolves.toBeNull(); - expect(seen).toHaveLength(2); - expect(seen[0]?.destroy).toHaveBeenCalledTimes(1); - expect(seen[1]?.destroy).toHaveBeenCalledTimes(1); - }); - - it('joins chunked pt_get_uins bodies including Buffer pieces', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5560) }); - httpsGetMock.mockImplementation( - replyBody([ - 'ptui_getuins_CB([', - Buffer.from('{"uin":"10001","nickname":"Ada"}'), - ']);', - ]), - ); - - await expect(probeQqLoginInfo(5560)).resolves.toEqual({ - port: 4301, - uin: '10001', - nickName: 'Ada', - identityKnown: true, - }); - }); - - it('treats a nickname that closes the JSONP array early as unusable', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5561) }); - httpsGetMock.mockImplementation( - replyBody('ptui_getuins_CB([{"nickname":"a]b","uin":"1"}]);'), - ); - - await expect(probeQqLoginInfo(5561)).resolves.toBeNull(); - }); -}); - -describe('probeQqLoginInfo — win32 listing', () => { - beforeEach(() => { - setPlatform('win32'); - }); - - it('returns null when netstat cannot list sockets', async () => { - mockExec({ 'netstat -ano': new Error('netstat: access denied') }); - - await expect(probeQqLoginInfo(6610)).resolves.toBeNull(); - expect(execCommands()).toEqual(['netstat -ano']); - expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS); - }); - - it('counts QQ.exe rows from tasklist when netstat lists no sockets for the PID', async () => { - mockExec({ - 'netstat -ano': [ - 'Active Connections', - '', - ' Proto Local Address Foreign Address State PID', - netstatLine('127.0.0.1:4301', 1), - ].join('\n'), - 'tasklist /fi "imagename eq QQ.exe" /nh': [ - 'QQ.exe 100 Console 1 10,000 K', - 'QQ.exe 101 Console 1 11,000 K', - 'explorer.exe 200 Console 1 9,000 K', - ].join('\n'), - }); - - await expect(probeQqLoginInfo(6611)).resolves.toEqual({ - port: 0, - uin: '', - identityKnown: false, - }); - expect(execCommands()).toEqual(['netstat -ano', 'tasklist /fi "imagename eq QQ.exe" /nh']); - }); - - it('returns null when tasklist reports 6 or more QQ.exe rows and the PID has no sockets', async () => { - mockExec({ - 'netstat -ano': '', - 'tasklist /fi "imagename eq QQ.exe" /nh': [ - 'QQ.exe 1', - 'QQ.exe 2', - 'QQ.exe 3', - 'qq.exe 4', - 'QQ.EXE 5', - 'QQ.exe 6', - ].join('\n'), - }); - - await expect(probeQqLoginInfo(6612)).resolves.toBeNull(); - }); - - it('does not treat a failed tasklist as logged out', async () => { - mockExec({ - 'netstat -ano': '', - 'tasklist /fi "imagename eq QQ.exe" /nh': new Error('tasklist: exit 1'), - }); - - await expect(probeQqLoginInfo(6613)).resolves.toBeNull(); - }); - - it('parses netstat rows for the owning PID and skips short or portless lines', async () => { - mockExec({ - 'netstat -ano': [ - 'Active Connections', - ' TCP 127.0.0.1:4301 LISTENING', - ' TCP 127.0.0.1 0.0.0.0:0 LISTENING 6620', - netstatLine('10.0.0.8:18000', 1), - netstatLine('127.0.0.1:4303', 6620), - netstatLine('[::1]:4303', 6620), - netstatLine('127.0.0.1:9218', 6620), - ].join('\n'), - }); - httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '20002', nickname: 'Win' }]))); - - await expect(probeQqLoginInfo(6620)).resolves.toEqual({ - port: 4303, - uin: '20002', - nickName: 'Win', - identityKnown: true, - }); - expect(httpsGetMock).toHaveBeenCalledTimes(2); - expect(httpsGetMock.mock.calls[0]?.[0]).toBe( - 'https://127.0.0.1:4303/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', - ); - }); - - it('uses the first netstat port as a logged-out hint when no Ptlogin port is present', async () => { - mockExec({ - 'netstat -ano': [ - netstatLine('127.0.0.1:18000', 6630), - netstatLine('127.0.0.1:18001', 6630), - ].join('\n'), - 'tasklist /fi "imagename eq QQ.exe" /nh': 'QQ.exe 100\n', - }); - - await expect(probeQqLoginInfo(6630)).resolves.toEqual({ - port: 18000, - uin: '', - identityKnown: false, - }); - expect(httpGetMock).not.toHaveBeenCalled(); - expect(httpsGetMock).not.toHaveBeenCalled(); - }); -}); - -describe('probeQqLoginInfo — overall deadline', () => { - it('returns null and warns after 5000ms if listing never finishes', async () => { - vi.useFakeTimers(); - execMock.mockImplementation(() => undefined); - const previousLevel = getLogLevel(); - setLogLevel('info'); - const warnings: string[] = []; - const unsubscribe = subscribeLogs((entry) => { - if (entry.scope === 'LoginProbe' && entry.level === 'warn') { - warnings.push(entry.message); - } - }); - - try { - const pending = probeQqLoginInfo(9001); - let settled: unknown = 'pending'; - void pending.then((value) => { - settled = value; - }); - - await vi.advanceTimersByTimeAsync(4999); - expect(settled).toBe('pending'); - - await vi.advanceTimersByTimeAsync(1); - await expect(pending).resolves.toBeNull(); - expect(warnings).toEqual(['login check timed out: PID=9001']); - } finally { - unsubscribe(); - setLogLevel(previousLevel); - } - }); - - it('does not warn when the probe finishes before the deadline', async () => { - mockExec({ - 'ss -tlnp': '', - 'pgrep -c qq': '2\n', - }); - const previousLevel = getLogLevel(); - setLogLevel('info'); - const warnings: string[] = []; - const unsubscribe = subscribeLogs((entry) => { - if (entry.scope === 'LoginProbe') { - warnings.push(entry.message); - } - }); - - try { - await expect(probeQqLoginInfo(9002)).resolves.toEqual({ - port: 0, - uin: '', - identityKnown: false, - }); - await probeQqLoginInfo(9002); - expect(warnings).toEqual(['login probe: PID=9002 result=no-ports ports=0 processes=2']); - } finally { - unsubscribe(); - setLogLevel(previousLevel); - } - }); - - it('abandons a hung Ptlogin fetch at the overall deadline', async () => { - vi.useFakeTimers(); - mockExec({ 'ss -tlnp': ssLine(4301, 9003) }); - httpsGetMock.mockImplementation(() => requestStub()); - - const pending = probeQqLoginInfo(9003); - await vi.advanceTimersByTimeAsync(5000); - await expect(pending).resolves.toBeNull(); - }); -}); diff --git a/packages/bridge/tests/qq-port-probe.test.ts b/packages/bridge/tests/qq-port-probe.test.ts deleted file mode 100644 index 4517b222..00000000 --- a/packages/bridge/tests/qq-port-probe.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; - -const execMock = vi.hoisted(() => vi.fn()); -const socketCtorMock = vi.hoisted(() => - vi.fn(function MockSocket() { - throw new Error('interactive QQ probe must not run'); - }), -); - -vi.mock('child_process', () => ({ exec: execMock })); -vi.mock('net', () => ({ - default: { Socket: socketCtorMock }, - Socket: socketCtorMock, -})); - -import { probeQqLoginInfo } from '../src/qq-port-probe'; - -describe('probeQqLoginInfo — bounded execution', () => { - beforeEach(() => { - vi.useFakeTimers(); - execMock.mockReset(); - socketCtorMock.mockClear(); - }); - - afterEach(() => { - vi.useRealTimers(); - }); - - it('allows a later probe after a timed-out attempt', async () => { - execMock.mockImplementation(() => undefined); - const first = probeQqLoginInfo(4242); - await vi.advanceTimersByTimeAsync(10_000); - await expect(first).resolves.toBeNull(); - - execMock - .mockImplementationOnce((_command, _options, callback) => { - callback(null, { stdout: '', stderr: '' }); - }) - .mockImplementationOnce((_command, _options, callback) => { - callback(null, { - stdout: process.platform === 'win32' ? 'QQ.exe 4242 Console 1 1234 K\n' : '1\n', - stderr: '', - }); - }); - - await expect(probeQqLoginInfo(4242)).resolves.toEqual({ - port: 0, - uin: '', - identityKnown: false, - }); - }); - - it('keeps background identity discovery passive', async () => { - execMock - .mockImplementationOnce((_command, _options, callback) => { - callback(null, { - stdout: - process.platform === 'win32' - ? 'TCP 127.0.0.1:9218 0.0.0.0:0 LISTENING 4242\n' - : 'LISTEN 0 128 127.0.0.1:9218 0.0.0.0:* users:(("qq",pid=4242,fd=12))\n', - stderr: '', - }); - }) - .mockImplementationOnce((_command, _options, callback) => { - callback(null, { - stdout: - process.platform === 'win32' - ? 'QQ.exe 4242 Console 1 1234 K\n'.repeat(8) - : '8\n', - stderr: '', - }); - }); - - await expect(probeQqLoginInfo(4242)).resolves.toBeNull(); - expect(socketCtorMock).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 4b0074cf..e6447c55 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -1947,30 +1947,6 @@ export async function initWebUI( processAction('refresh', (pid) => hookManager!.refreshProcess(pid)), ); - app.get('/api/processes/:pid/probe-login', async (c) => { - if (!hookManager) { - return c.json({ info: null, message: 'hook manager is not available' }, 503); - } - - const pid = Number(c.req.param('pid')); - - if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) { - return c.json({ info: null, message: 'invalid pid' }, 400); - } - - try { - const info = await hookManager.probeProcessLoginInfo(pid); - return c.json({ info }); - } catch (err) { - log.warn( - 'probe-login pid=%d failed: %s', - pid, - err instanceof Error ? err.message : String(err), - ); - return c.json({ info: null, message: '探测失败' }, 500); - } - }); - app.get('/api/config/:uin', (c) => { const uin = c.req.param('uin'); diff --git a/packages/webui/README.md b/packages/webui/README.md index 78bbf585..586c1efb 100644 --- a/packages/webui/README.md +++ b/packages/webui/README.md @@ -39,6 +39,18 @@ request headers. The backend still accepts `Authorization: Bearer ` for existing clients when the dedicated header is absent. Both layers still require their own valid credentials. +## Process account detection + +Process cards use QQ's local account data before injection and the hook's confirmed +identity after login. Missing local data means the account is unknown. It does not +prove that QQ is signed out, and local detection alone never marks a bridge online. +The manual login probe and `/api/processes/:pid/probe-login` endpoint are removed. + +Linux resolves data roots from each QQ process's `XDG_CONFIG_HOME` or `HOME`. +Windows requires a hook addon with `probeDbLock`; the currently bundled addon does +not provide it, so pre-injection account detection is unavailable there. A missing +interface is logged. Hook login events continue to report the online account. + ## Account notification templates Webhook bodies and email subjects/bodies support `{uin}`, `{nickname}`, `{event}` diff --git a/packages/webui/src/components/pages/processes-page.tsx b/packages/webui/src/components/pages/processes-page.tsx index f0c411d1..d8fe7b32 100644 --- a/packages/webui/src/components/pages/processes-page.tsx +++ b/packages/webui/src/components/pages/processes-page.tsx @@ -1,11 +1,11 @@ import { useMemo, useState } from 'react'; import { motion } from 'motion/react'; -import { AlertCircle, CheckCircle2, Cpu, Eye, Loader2, RefreshCw, Unplug } from 'lucide-react'; +import { AlertCircle, Cpu, Loader2, RefreshCw, Unplug } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; +import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { ConfirmDialog } from '@/components/confirm-dialog'; -import { ProcessProbeDialog } from '@/components/process-probe-dialog'; import { SkeletonSwap } from '@/components/interior/skeleton-swap'; import { cn } from '@/lib/utils'; import type { HookProcessInfo } from '@/types'; @@ -18,6 +18,11 @@ const SORT_OPTIONS: { id: string; label: string }[] = [ { id: 'name', label: '名称' }, { id: 'status', label: '状态' }, ]; + +function qqAvatarUrl(uin: string) { + return `/avatar/${encodeURIComponent(uin)}`; +} + // Online-first, then by how actionable the state is. const STATUS_ORDER: Record = { online: 0, @@ -44,11 +49,7 @@ function processBadgeVariant(status: HookProcessInfo['status']) { return 'success' as const; } - if (status === 'error') { - return 'destructive' as const; - } - - if (status === 'disconnected') { + if (status === 'error' || status === 'disconnected') { return 'destructive' as const; } @@ -59,13 +60,6 @@ function processBadgeVariant(status: HookProcessInfo['status']) { return 'secondary' as const; } -/** - * Process / injection control surface. Split out of the overview page so the - * homepage stays a read-only monitoring dashboard. State (processList, - * processOps) is owned by AppLayout and read from context, so this page needs - * no plumbing of its own; the layout keeps polling and the unload-failed alert - * regardless of which page is mounted. - */ export function ProcessesPage() { const { processList, processOps, refreshProcesses, resources } = useAppState(); const { statusOf, banner: processActionStatus, load, unload, refresh } = processOps; @@ -76,19 +70,14 @@ export function ProcessesPage() { pid: number; name: string; } | null>(null); - const [probeDialog, setProbeDialog] = useState<{ pid: number; name: string } | null>(null); - const sortKey = pages.processesSort; const sorted = useMemo(() => { const arr = [...processList]; if (sortKey === 'name') { - arr.sort((a, b) => (a.name || '').localeCompare(b.name || '')); + arr.sort((a, b) => a.name.localeCompare(b.name)); } else if (sortKey === 'status') { - arr.sort( - (a, b) => - (STATUS_ORDER[a.status] ?? 9) - (STATUS_ORDER[b.status] ?? 9) || a.pid - b.pid, - ); + arr.sort((a, b) => STATUS_ORDER[a.status] - STATUS_ORDER[b.status] || a.pid - b.pid); } else { arr.sort((a, b) => a.pid - b.pid); } @@ -102,9 +91,7 @@ export function ProcessesPage() {
进程注入 - - 加载 SnowLuma 后会监听登录状态,登录后自动接入 OneBot 流程 - + 加载后,已登录账号将自动接入 OneBot
{processList.length > 1 && ( @@ -192,18 +179,21 @@ export function ProcessesPage() {

未检测到可加载 QQ 主进程

- 请确认 QQ 已启动后点击右上角刷新 + 启动 QQ 后刷新

) : (
{sorted.map((proc, idx) => { + const uin = proc.loggedIn ? proc.uin : proc.account?.uin; + const nickname = + proc.account?.uin === uin ? proc.account?.nickname : ''; + const name = nickname || uin || proc.name; const op = statusOf(proc.pid); const loading = op === 'load' || proc.status === 'loading'; const unloading = op === 'unload'; const refreshing = op === 'refresh'; const busy = op != null || proc.status === 'loading'; - const isOnline = proc.status === 'online'; const canUnload = proc.injected; // Refresh is meaningful whenever a hook may exist (so the user // can re-check the pipe and trigger a reconnect on demand). @@ -230,28 +220,36 @@ export function ProcessesPage() { a second row so name / PID / path get the full width instead of collapsing to "Q..". */}
-
- {isOnline ? ( - - ) : proc.status === 'error' ? ( - - ) : ( - - )} -
+ {uin ? ( + + + + {name.slice(0, 2)} + + + ) : ( +
+ {proc.status === 'error' ? ( + + ) : ( + + )} +
+ )}
- {proc.name || 'QQ.exe'} + {name}
PID {proc.pid} - {proc.uin && proc.uin !== '0' - ? ` · UIN ${proc.uin}` - : ''} + {uin ? ` · QQ ${uin}` : ''}
{proc.path && (
- {showRefresh && (
); } diff --git a/packages/webui/src/components/process-probe-dialog.tsx b/packages/webui/src/components/process-probe-dialog.tsx deleted file mode 100644 index e4943c94..00000000 --- a/packages/webui/src/components/process-probe-dialog.tsx +++ /dev/null @@ -1,190 +0,0 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; -import { Eye, User, UserX } from 'lucide-react'; -import { Modal } from '@/components/interior/modal'; -import { SkeletonSwap } from '@/components/interior/skeleton-swap'; -import { Button } from '@/components/ui/button'; -import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; -import { Badge } from '@/components/ui/badge'; -import { useApi } from '@/lib/api'; - -interface QqPortLoginInfo { - port: number; - uin: string; - uid?: string; - nickName?: string; - identityKnown: boolean; -} - -interface ProcessProbeDialogProps { - pid: number; - processName: string; - open: boolean; - onOpenChange: (open: boolean) => void; - onLoad?: () => void; -} - -function qqAvatarUrl(uin: string) { - return `/avatar/${encodeURIComponent(uin)}`; -} - -export function ProcessProbeDialog({ - pid, - processName, - open, - onOpenChange, - onLoad, -}: ProcessProbeDialogProps) { - const api = useApi(); - const [loading, setLoading] = useState(false); - const [info, setInfo] = useState(null); - const [error, setError] = useState(null); - const activeProbe = useRef(null); - - const probe = useCallback(async () => { - activeProbe.current?.abort(); - const controller = new AbortController(); - activeProbe.current = controller; - setLoading(true); - setError(null); - setInfo(null); - - try { - const result = await api.processes.probeLoginInfo(pid, controller.signal); - - if (activeProbe.current !== controller) { - return; - } - - setInfo(result as QqPortLoginInfo | null); - - if (!result) { - setError('未检测到可用的账号身份信息'); - } - } catch (err) { - if (activeProbe.current !== controller || controller.signal.aborted) { - return; - } - - setError(err instanceof Error ? err.message : '探测失败'); - } finally { - if (activeProbe.current === controller) { - activeProbe.current = null; - setLoading(false); - } - } - }, [api.processes, pid]); - - useEffect(() => { - if (open) { - void probe(); - } else { - activeProbe.current?.abort(); - activeProbe.current = null; - setLoading(false); - setInfo(null); - setError(null); - } - - return () => { - activeProbe.current?.abort(); - activeProbe.current = null; - }; - }, [open, probe]); - - return ( - onOpenChange(false)} - title="查看登录状态" - description={`${processName} (PID ${pid})`} - closeLabel="关闭登录状态弹窗" - > -
-

- 账号检测不保证 100% 成功,检测结果仅供参考。 -

- - {!loading ? ( - error ? ( -
- -

{error}

-
- ) : info ? ( -
- {info.identityKnown ? ( -
- - - - - - -
-
- - {info.nickName || info.uin} - - 已识别账号 -
-
- UIN: {info.uin} -
- {info.uid && ( -
- UID: {info.uid} -
- )} -
- 端口: {info.port} -
-
- 此结果仅表示账号身份已识别,协议会话是否就绪以进程状态为准。 -
-
-
- ) : ( -
- -
-

等待登录

-

- 端口 {info.port} 已响应,但未检测到登录账号 -

-
-
- )} -
- ) : null - ) : null} -
- -
- - {!loading && info?.identityKnown && onLoad && ( - - )} - {!loading && ( - - )} -
-
-
- ); -} diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index 38040186..5c6a86ea 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -122,10 +122,6 @@ class HttpApiClient implements ApiClient { load: (pid) => this.postJson(`/api/processes/${pid}/load`), unload: (pid) => this.postJson(`/api/processes/${pid}/unload`), refresh: (pid) => this.postJson(`/api/processes/${pid}/refresh`), - probeLoginInfo: (pid, signal) => - this.fetchJson<{ info: unknown }>(`/api/processes/${pid}/probe-login`, { - signal, - }).then((d) => d.info ?? null), }; this.config = { diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index 79ddfcfa..dd8c5aae 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -181,7 +181,6 @@ export interface ApiClient { load(pid: number): Promise; unload(pid: number): Promise; refresh(pid: number): Promise; - probeLoginInfo(pid: number, signal?: AbortSignal): Promise; }; // ---- OneBotInstance per-UIN config ---- diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index dd6b1582..9b807a85 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -55,6 +55,11 @@ export interface AccountConnections { databaseMigration?: AccountDatabaseMigration; } +export interface HookProcessAccount { + uin: string; + nickname: string; +} + export interface HookProcessInfo { pid: number; name: string; @@ -66,6 +71,7 @@ export interface HookProcessInfo { status: 'available' | 'loading' | 'connecting' | 'loaded' | 'online' | 'error' | 'disconnected'; error: string; method: string; + account: HookProcessAccount | null; } export type MessageFormat = 'array' | 'string'; diff --git a/packages/webui/tests/api-client-timeout.test.ts b/packages/webui/tests/api-client-timeout.test.ts index dd630073..850986d1 100644 --- a/packages/webui/tests/api-client-timeout.test.ts +++ b/packages/webui/tests/api-client-timeout.test.ts @@ -44,7 +44,7 @@ describe('API client request deadline', () => { await rejection; }); - it('cancels a login probe without preventing a later retry', async () => { + it('cancels a request without preventing a later retry', async () => { const fetchMock = vi .fn() .mockImplementationOnce( @@ -60,29 +60,22 @@ describe('API client request deadline', () => { }), ) .mockResolvedValueOnce( - new Response( - JSON.stringify({ - info: { port: 0, uin: '', identityKnown: false }, - }), - { - status: 200, - headers: { 'content-type': 'application/json' }, - }, - ), + new Response(JSON.stringify({ list: [] }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }), ); vi.stubGlobal('fetch', fetchMock); const client = createApiClient({ tokenStore }); const controller = new AbortController(); - const cancelled = client.processes.probeLoginInfo(4242, controller.signal); + const cancelled = client.request('/api/processes', { signal: controller.signal }); controller.abort(); await expect(cancelled).rejects.toMatchObject({ name: 'AbortError' }); - await expect(client.processes.probeLoginInfo(4242)).resolves.toEqual({ - port: 0, - uin: '', - identityKnown: false, - }); + await expect( + client.request('/api/processes').then((response) => response.json()), + ).resolves.toEqual({ list: [] }); }); it('settles a pending login with a retryable timeout message', async () => { diff --git a/packages/webui/tests/processes-page.test.tsx b/packages/webui/tests/processes-page.test.tsx new file mode 100644 index 00000000..cffda348 --- /dev/null +++ b/packages/webui/tests/processes-page.test.tsx @@ -0,0 +1,76 @@ +import { renderToStaticMarkup } from 'react-dom/server'; +import { describe, expect, it, vi } from 'vitest'; +import { ProcessesPage } from '../src/components/pages/processes-page'; +import type { HookProcessInfo } from '../src/types'; + +const state = vi.hoisted(() => ({ processList: [] as HookProcessInfo[] })); + +vi.mock('@/contexts/AppStateContext', () => ({ + useAppState: () => ({ + processList: state.processList, + processOps: { statusOf: () => null, banner: null }, + refreshProcesses: vi.fn(), + resources: { processList: { ready: true, error: '' } }, + }), +})); +vi.mock('@/contexts/LayoutContext', () => ({ + useLayout: () => ({ pages: { processesSort: 'pid' }, setPages: vi.fn() }), +})); +vi.mock('@/contexts/ThemeContext', () => ({ + useTheme: () => ({ appearance: { disableMotion: true } }), +})); +vi.mock('@/components/confirm-dialog', () => ({ ConfirmDialog: () => null })); + +function renderProcess(overrides: Partial) { + state.processList = [ + { + pid: 4242, + name: 'qq', + path: '', + injected: false, + connected: false, + loggedIn: false, + uin: '0', + status: 'available', + error: '', + method: '', + account: null, + ...overrides, + }, + ]; + return renderToStaticMarkup(); +} + +describe('process account labels', () => { + it('does not label an unidentified process as signed out', () => { + const markup = renderProcess({}); + expect(markup).toContain('PID 4242'); + expect(markup).not.toContain('未登录'); + expect(markup).not.toContain('/avatar/'); + }); + + it('shows the locally detected identity before hook login', () => { + const markup = renderProcess({ account: { uin: '10001', nickname: 'Alice' } }); + expect(markup).toContain('Alice'); + expect(markup).toContain('/avatar/10001'); + expect(markup).toContain('QQ 10001'); + }); + + it('uses native login identity without an account database', () => { + const markup = renderProcess({ loggedIn: true, uin: '10002', status: 'online' }); + expect(markup).toContain('/avatar/10002'); + expect(markup).toContain('已在线'); + }); + + it('does not apply a stale local nickname to a newly logged-in account', () => { + const markup = renderProcess({ + loggedIn: true, + uin: '10002', + status: 'online', + account: { uin: '10001', nickname: 'Alice' }, + }); + expect(markup).toContain('/avatar/10002'); + expect(markup).not.toContain('Alice'); + expect(markup).not.toContain('10001'); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d4a01706..47c53dc6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -81,6 +81,9 @@ importers: '@snowluma/common': specifier: workspace:* version: link:../common + '@snowluma/sqlite': + specifier: workspace:* + version: link:../sqlite devDependencies: '@types/node': specifier: 'catalog:'