diff --git a/packages/bridge/src/hook-manager.ts b/packages/bridge/src/hook-manager.ts index 6850867f..49d38d3f 100644 --- a/packages/bridge/src/hook-manager.ts +++ b/packages/bridge/src/hook-manager.ts @@ -160,7 +160,7 @@ export class HookManager { } else { this.pipeWatcher = new PipeWatcher({ listProcesses: this.enumerate, - listLivePipes: () => QqHookClient.listLivePipes(), + listLivePipes: processes => QqHookClient.listLivePipes(processes.map(({ pid }) => pid)), intervalMs: deps.watcherIntervalMs, log: this.log, }); diff --git a/packages/bridge/src/hook-runtime-dir.ts b/packages/bridge/src/hook-runtime-dir.ts new file mode 100644 index 00000000..c3c4562e --- /dev/null +++ b/packages/bridge/src/hook-runtime-dir.ts @@ -0,0 +1,130 @@ +import { readFileSync } from 'fs'; +import os from 'os'; +import path from 'path'; + +export interface HookRuntimeDirDeps { + platform?: NodeJS.Platform; + env?: NodeJS.ProcessEnv; + ownUid?: number; + readText?: (file: string) => string; +} + +function configuredDirectory(value: string | undefined, variable: string): string | null { + if (!value) return null; + if (!path.isAbsolute(value)) { + throw new Error(`${variable} must be an absolute path`); + } + return value; +} + +function parseProcessEnvironment(raw: string): NodeJS.ProcessEnv { + const result: NodeJS.ProcessEnv = {}; + for (const entry of raw.split('\0')) { + if (!entry) continue; + const separator = entry.indexOf('='); + if (separator <= 0) continue; + result[entry.slice(0, separator)] = entry.slice(separator + 1); + } + return result; +} + +function parseRealUid(status: string): number | null { + const match = /^Uid:\s+(\d+)/m.exec(status); + if (!match) return null; + const uid = Number(match[1]); + return Number.isSafeInteger(uid) && uid >= 0 ? uid : null; +} + +function isProcessGoneError(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException | undefined)?.code; + return code === 'ENOENT' || code === 'ESRCH'; +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +function ownRuntimeDir( + platform: NodeJS.Platform, + env: NodeJS.ProcessEnv, + ownUid: number, +): string { + const explicit = configuredDirectory( + env.SNOWLUMA_HOOK_RUNTIME_DIR, + 'SNOWLUMA_HOOK_RUNTIME_DIR', + ); + if (explicit) return explicit; + + const xdg = configuredDirectory(env.XDG_RUNTIME_DIR, 'XDG_RUNTIME_DIR'); + if (xdg) return xdg; + + if (platform === 'darwin') { + const tmpdir = configuredDirectory(env.TMPDIR, 'TMPDIR'); + if (tmpdir) return path.join(tmpdir, 'snowluma-hook'); + } + return `/tmp/snowluma-${ownUid}`; +} + +/** + * Resolve the socket directory for the target QQ process. The supervisor may + * run under a different user, so its own runtime directory is not authoritative. + */ +export function resolveHookRuntimeDir( + targetPid?: number, + deps: HookRuntimeDirDeps = {}, +): string { + const platform = deps.platform ?? process.platform; + const env = deps.env ?? process.env; + const ownUid = deps.ownUid + ?? (typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid); + const readText = deps.readText ?? ((file: string) => readFileSync(file, 'utf8')); + + if (platform !== 'linux' || !Number.isSafeInteger(targetPid) || targetPid! <= 0) { + return ownRuntimeDir(platform, env, ownUid); + } + + let environError: unknown; + try { + const targetEnv = parseProcessEnvironment(readText(`/proc/${targetPid}/environ`)); + const explicit = configuredDirectory( + targetEnv.SNOWLUMA_HOOK_RUNTIME_DIR, + `QQ process ${targetPid} SNOWLUMA_HOOK_RUNTIME_DIR`, + ); + if (explicit) return explicit; + const xdg = configuredDirectory( + targetEnv.XDG_RUNTIME_DIR, + `QQ process ${targetPid} XDG_RUNTIME_DIR`, + ); + if (xdg) return xdg; + environError = new Error('runtime directory is not present'); + } catch (error) { + // An invalid explicit path is configuration corruption and must remain + // visible. Permission/race failures are expected when /proc disappears; + // the status-file fallback below can still recover the target uid. + if (error instanceof Error && error.message.includes('must be an absolute path')) { + throw error; + } + environError = error; + } + + let statusError: unknown; + try { + const uid = parseRealUid(readText(`/proc/${targetPid}/status`)); + if (uid !== null) return `/tmp/snowluma-${uid}`; + statusError = new Error('real uid is not available'); + } catch (error) { + statusError = error; + } + + if (isProcessGoneError(statusError) + && (isProcessGoneError(environError) + || (environError instanceof Error + && environError.message === 'runtime directory is not present'))) { + return ownRuntimeDir(platform, env, ownUid); + } + + throw new Error( + `cannot resolve hook runtime directory for PID ${targetPid}: ` + + `environment=${errorMessage(environError)}; status=${errorMessage(statusError)}`, + ); +} diff --git a/packages/bridge/src/hook-session.ts b/packages/bridge/src/hook-session.ts index c07b4445..8052b6c3 100644 --- a/packages/bridge/src/hook-session.ts +++ b/packages/bridge/src/hook-session.ts @@ -15,10 +15,12 @@ import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe'; import { statusFor } from './hook-status'; import type { HookProcessInfo, HookProcessStatus } from './types'; -/** How often to actively re-probe QQ's login state while connected but not yet - * logged in — the safety net for a login the native hook never pushed (Docker - * auto-login races/bypasses the pushed loginState frame). */ +/** How often to re-check account identity while the connection is not ready. + * Identity alone never proves that requests can be served. */ const LOGIN_RECONCILE_INTERVAL_MS = 3000; +const LOGIN_IDENTITY_OBSERVE_INTERVAL_MS = 30_000; +const LOGIN_HINT_MAX_ATTEMPTS = 3; +const LOGIN_HINT_RETRY_DELAYS_MS = [3000, 9000] as const; /** QQ emits this response periodically while its MSF receive path is healthy. * Seeing it once arms the watchdog; before that, silence is UNKNOWN rather @@ -99,6 +101,11 @@ export class HookSession extends EventEmitter { private disposed = false; private loginProbeTimer: ReturnType | null = null; private probing = false; + private acceptedLoginHintUin = ''; + private loginHintAttemptUin = ''; + private loginHintAttempts = 0; + private nextLoginHintAt = 0; + private nextLoginIdentityObservationAt = 0; private _receiveHealthy = true; private receiveWatchUin = ''; private receiveWatchArmed = false; @@ -575,6 +582,7 @@ export class HookSession extends EventEmitter { this.bound = false; this.connected = false; this.loggedIn = false; + this.resetLoginHint(); } private handleLoginState(state: QqHookLoginState): void { @@ -582,8 +590,7 @@ export class HookSession extends EventEmitter { const previousUin = this._uin; this._uin = state.uin || state.uinNumber.toString(); this.loggedIn = state.loggedIn && isRealUin(this._uin); - // However login was observed (pushed frame or the active probe), the - // safety net's job is done. + // Login readiness has now been confirmed, so identity probing is done. if (this.loggedIn) { this.stopLoginReconcile(); // A PID can switch accounts without an intermediate logout edge. Never @@ -639,13 +646,9 @@ export class HookSession extends EventEmitter { } // ─────────────── login reconcile (Docker auto-login safety net) ─────────── - // The hook's loginState frame is edge-triggered (pushed only when the native - // observes the login transition). When that edge is missed — QQ auto-logged - // in before connect, or a silent session-restore path the hook doesn't - // intercept — we'd sit at 'loaded'/'connecting' forever. So while connected - // but not logged in, actively re-probe QQ's own ports and synthesize the - // login once it reports a real uin. Idempotent with the pushed-frame path - // (handleLoginState's wasLoggedIn guard dedups the 'login' emit). + // 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. private startLoginReconcile(): void { if (this.loginProbeTimer || this.disposed) return; @@ -666,34 +669,85 @@ export class HookSession extends EventEmitter { // slow probe never stacks concurrent subprocess-spawning scans. if (this.probing) return; if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; } + if (Date.now() < this.nextLoginIdentityObservationAt) return; this.probing = true; try { let info: QqPortLoginInfo | null; try { info = await this.probeLogin(this.pid); - } catch { + } catch (error) { + this.log.trace( + 'login identity probe failed: PID=%d err=%s', + this.pid, + errMsg(error), + ); return; // best-effort; the interval retries } // The await yielded — re-check we still want this before mutating state. if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; } if (info?.loggedIn && isRealUin(info.uin)) { - this.log.info('login reconciled via active probe: PID=%d UIN=%s', this.pid, info.uin); - // isRealUin guarantees a pure non-empty digit string, so BigInt() here - // cannot throw (keep that contract if isRealUin's regex is ever changed). - // Reconcile through QqHookClient instead of mutating HookSession alone: - // packet sending and login waiters must observe the same state before - // the login event starts Bridge / OneBot initialization. - this.client!.reconcileLoginState({ - loggedIn: true, - uin: info.uin, - uinNumber: BigInt(info.uin), - }); + const client = this.client; + if (!client) return; + if (this.acceptedLoginHintUin === info.uin) { + this.nextLoginIdentityObservationAt = Date.now() + + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS; + return; + } + if (this.loginHintAttemptUin !== info.uin) { + this.loginHintAttemptUin = info.uin; + this.loginHintAttempts = 0; + this.nextLoginHintAt = 0; + this.nextLoginIdentityObservationAt = 0; + } + if (this.loginHintAttempts >= LOGIN_HINT_MAX_ATTEMPTS + || Date.now() < this.nextLoginHintAt) return; + + const attempt = ++this.loginHintAttempts; + this.log.info('login identity discovered: PID=%d UIN=%s; awaiting readiness', this.pid, info.uin); + try { + await client.reconcileLoginIdentity(info.uin); + if (this.client !== client || this.disposed || !this.connected || this.loggedIn) return; + this.acceptedLoginHintUin = info.uin; + this.nextLoginIdentityObservationAt = Date.now() + + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS; + } catch (error) { + if (this.client !== client || this.disposed) return; + if (attempt >= LOGIN_HINT_MAX_ATTEMPTS) { + this.log.warn( + 'login identity reconciliation failed: PID=%d UIN=%s attempts=%d err=%s', + this.pid, + info.uin, + attempt, + errMsg(error), + ); + this.nextLoginIdentityObservationAt = Date.now() + + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS; + } else { + this.nextLoginHintAt = Date.now() + + LOGIN_HINT_RETRY_DELAYS_MS[attempt - 1]!; + this.log.trace( + 'login identity hint failed: PID=%d UIN=%s attempt=%d err=%s', + this.pid, + info.uin, + attempt, + errMsg(error), + ); + } + } } } finally { this.probing = false; } } + private resetLoginHint(): void { + this.acceptedLoginHintUin = ''; + this.loginHintAttemptUin = ''; + this.loginHintAttempts = 0; + this.nextLoginHintAt = 0; + this.nextLoginIdentityObservationAt = 0; + } + private handlePacket(packet: QqHookPacket): void { if (!this.loggedIn) return; const uin = packet.uin || this._uin; diff --git a/packages/bridge/src/pipe-watcher.ts b/packages/bridge/src/pipe-watcher.ts index 7b615423..d763126b 100644 --- a/packages/bridge/src/pipe-watcher.ts +++ b/packages/bridge/src/pipe-watcher.ts @@ -11,8 +11,9 @@ export type PipeWatcherDeps = { * case this tick keeps the prior process+pipe state instead of treating the * missing data as "everything disappeared" (issue #158). */ listProcesses: () => HookProcessBaseInfo[] | null | Promise; - /** Native: PIDs that currently have a live SnowLuma named pipe. */ - listLivePipes: () => Promise>; + /** Native: PIDs that currently have a live SnowLuma named pipe. The current + * process snapshot lets Linux inspect each target user's runtime directory. */ + listLivePipes: (processes: readonly HookProcessBaseInfo[]) => Promise>; /** Polling interval in ms. Defaults to 1500, floored to 250. */ intervalMs?: number; log?: Logger; @@ -158,12 +159,12 @@ export class PipeWatcher extends EventEmitter { this.emit('tick'); return; } - let livePipes: Set; + let livePipes: Set | null; try { - livePipes = await this.listLivePipes(); + livePipes = await this.listLivePipes(processes); } catch (error) { this.log.warn('listLivePipes failed: %s', errMsg(error)); - livePipes = new Set(); + livePipes = null; } const newKnownPids = new Set(); @@ -179,11 +180,19 @@ export class PipeWatcher extends EventEmitter { // 2. Pipes that came up. Ignore pipes for processes we don't know // about (would race against an out-of-order tick). const newLivePipes = new Set(); - for (const pid of livePipes) { - if (!newKnownPids.has(pid)) continue; - newLivePipes.add(pid); - if (!this.livePipes.has(pid)) { - this.emit('pipe-up', pid); + if (livePipes === null) { + // Keep the last known pipe state for processes that still exist, while + // allowing confirmed process exits to complete their normal teardown. + for (const pid of this.livePipes) { + if (newKnownPids.has(pid)) newLivePipes.add(pid); + } + } else { + for (const pid of livePipes) { + if (!newKnownPids.has(pid)) continue; + newLivePipes.add(pid); + if (!this.livePipes.has(pid)) { + this.emit('pipe-up', pid); + } } } diff --git a/packages/bridge/src/qq-hook-client.ts b/packages/bridge/src/qq-hook-client.ts index 29417536..c89b76e4 100644 --- a/packages/bridge/src/qq-hook-client.ts +++ b/packages/bridge/src/qq-hook-client.ts @@ -6,10 +6,11 @@ import { runWithTraceRequest, } from '@snowluma/common/logger'; import { renderParamsVerbose } from '@snowluma/common/log-summary'; +import { isRealUin } from '@snowluma/common/uin'; import { readdirSync, promises as fs } from 'fs'; import net from 'net'; -import os from 'os'; import path from 'path'; +import { resolveHookRuntimeDir } from './hook-runtime-dir'; export const PIPE_MAGIC = 0x31504851; export const PIPE_VERSION = 1; @@ -34,6 +35,7 @@ export enum PipeOp { error = 5, recvPacket = 6, loginState = 7, + loginIdentityHint = 17, } const PipeFlagWantReply = 1 << 0; @@ -69,6 +71,7 @@ export interface QqHookSendReply { export interface QqHookClientOptions { ackTimeoutMs?: number; replyTimeoutMs?: number; + runtimeDir?: string; } export interface QqHookSendOptions { @@ -100,6 +103,20 @@ interface PendingAck { wantReply: boolean; } +function isMissingDirectoryError(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException | undefined)?.code; + return code === 'ENOENT' || code === 'ENOTDIR'; +} + +function isUnavailableSocketError(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException | undefined)?.code; + return code === 'ENOENT' + || code === 'ENOTDIR' + || code === 'ENOTSOCK' + || code === 'ECONNREFUSED' + || code === 'ECONNRESET'; +} + /** * Sync directory scan for `mojo..control.sock` socket files in the * runtime dir, returning the pid set. Used by the darwin path of @@ -114,14 +131,15 @@ interface PendingAck { * variant still gates the subsequent `pipe-up` emit via a real connect. */ export function listSnowlumaPipePidsSync( - runtimeDir = linuxRuntimeDir(), + runtimeDir = resolveHookRuntimeDir(), ): Set { const result = new Set(); let names: string[]; try { names = readdirSync(runtimeDir); - } catch { - return result; + } catch (error) { + if (isMissingDirectoryError(error)) return result; + throw error; } for (const name of names) { const m = /^mojo\.(\d+)\.control\.sock$/i.exec(name); @@ -132,37 +150,11 @@ export function listSnowlumaPipePidsSync( return result; } -function linuxRuntimeDir(): string { - // Name kept for historical reasons (the function predates the macOS port); - // applies to every non-win32 platform. The fallback order mirrors each - // platform hook's runtime_dir(): explicit override first, then the OS- - // native ephemeral-dir convention. - const explicit = process.env.SNOWLUMA_HOOK_RUNTIME_DIR; - if (explicit && explicit.length > 0) return explicit; - const xdg = process.env.XDG_RUNTIME_DIR; - if (xdg && xdg.length > 0) return xdg; - // macOS: dylib defaults to "$TMPDIR/snowluma-hook" (apps/qq/macos/ - // qq_hook_dylib.cpp's runtime_dir()). $TMPDIR is per-user on macOS - // (under /var/folders/.../T) so this is the right place — Linux's - // /tmp/snowluma- doesn't exist on a stock Mac. - if (process.platform === 'darwin') { - const tmpdir = process.env.TMPDIR; - if (tmpdir && tmpdir.length > 0) { - const trimmed = tmpdir.endsWith('/') ? tmpdir.slice(0, -1) : tmpdir; - return path.join(trimmed, 'snowluma-hook'); - } - } - // Linux fallback: mirrors hook_stub.cpp runtime_dir() last-resort. - // process.geteuid is POSIX-only; cast to allow non-Linux type checks. - const uid = typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid; - return `/tmp/snowluma-${uid}`; -} - -function mojoPipeName(pid: number, suffix: string): string { +function mojoPipeName(pid: number, suffix: string, runtimeDir = resolveHookRuntimeDir(pid)): string { if (process.platform === 'win32') { return `\\\\.\\pipe\\mojo.${pid}.${suffix}`; } - return path.join(linuxRuntimeDir(), `mojo.${pid}.${suffix}.sock`); + return path.join(runtimeDir, `mojo.${pid}.${suffix}.sock`); } type LinuxPipeProbe = (socketPath: string) => Promise; @@ -171,16 +163,18 @@ async function isConnectableUnixSocket(socketPath: string): Promise { try { const stat = await fs.stat(socketPath); if (!stat.isSocket()) return false; - } catch { - return false; + } catch (error) { + if (isUnavailableSocketError(error)) return false; + throw error; } - return new Promise((resolve) => { + return new Promise((resolve, reject) => { let socket: net.Socket; try { socket = net.createConnection(socketPath); - } catch { - resolve(false); + } catch (error) { + if (isUnavailableSocketError(error)) resolve(false); + else reject(error); return; } let done = false; @@ -195,20 +189,31 @@ async function isConnectableUnixSocket(socketPath: string): Promise { }; timer = setTimeout(() => finish(false), DEFAULT_PIPE_PROBE_TIMEOUT_MS); socket.once('connect', () => finish(true)); - socket.once('error', () => finish(false)); + socket.once('error', error => { + if (isUnavailableSocketError(error)) finish(false); + else { + if (done) return; + done = true; + clearTimeout(timer); + socket.removeAllListeners(); + socket.destroy(); + reject(error); + } + }); }); } export async function listLiveLinuxPipePids( - runtimeDir = linuxRuntimeDir(), + runtimeDir = resolveHookRuntimeDir(), probe: LinuxPipeProbe = isConnectableUnixSocket, ): Promise> { const result = new Set(); let names: string[]; try { names = await fs.readdir(runtimeDir); - } catch { - return result; + } catch (error) { + if (isMissingDirectoryError(error)) return result; + throw error; } await Promise.all(names.map(async (name) => { @@ -440,6 +445,7 @@ class FrameReader { export class QqHookClient extends EventEmitter { readonly pid: number; + readonly runtimeDir: string; readonly defaultAckTimeoutMs: number; readonly defaultReplyTimeoutMs: number; @@ -462,9 +468,11 @@ export class QqHookClient extends EventEmitter { constructor(pid: number, { ackTimeoutMs = DEFAULT_ACK_TIMEOUT_MS, replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS, + runtimeDir = resolveHookRuntimeDir(pid), }: QqHookClientOptions = {}) { super(); this.pid = pid; + this.runtimeDir = runtimeDir; this.defaultAckTimeoutMs = ackTimeoutMs; this.defaultReplyTimeoutMs = replyTimeoutMs; } @@ -490,16 +498,14 @@ export class QqHookClient extends EventEmitter { } /** - * Reconcile a login edge that the native hook could not replay after the - * pipe connected. The client remains the single source of truth so packet - * sending, login waiters, and HookSession all observe the same transition. + * Forward an observed account identity for reconciliation. This does not + * change login state; readiness still requires peer confirmation. */ - reconcileLoginState(state: QqHookLoginState): void { - this.applyLoginState({ - loggedIn: state.loggedIn, - uin: state.uin || state.uinNumber.toString(), - uinNumber: state.uinNumber, - }); + async reconcileLoginIdentity(uin: string): Promise { + if (!isRealUin(uin)) { + throw new Error(`invalid QQ login identity hint: ${JSON.stringify(uin)}`); + } + await this.sendAckOnly(PipeOp.loginIdentityHint, BigInt(uin), 'login identity hint'); } async waitForLogin({ timeoutMs = 0 } = {}): Promise { @@ -512,12 +518,12 @@ export class QqHookClient extends EventEmitter { return withTimeout(deferred.promise, timeoutMs, 'waitForLogin'); } - static controlPipeName(pid: number): string { - return mojoPipeName(pid, 'control'); + static controlPipeName(pid: number, runtimeDir = resolveHookRuntimeDir(pid)): string { + return mojoPipeName(pid, 'control', runtimeDir); } - static recvPipeName(pid: number): string { - return mojoPipeName(pid, 'recv'); + static recvPipeName(pid: number, runtimeDir = resolveHookRuntimeDir(pid)): string { + return mojoPipeName(pid, 'recv', runtimeDir); } /** @@ -526,7 +532,7 @@ export class QqHookClient extends EventEmitter { * opening the pipe, so probing cannot disturb the first real client connect. */ static async probePipe(pid: number): Promise { - const live = await QqHookClient.listLivePipes(); + const live = await QqHookClient.listLivePipes([pid]); return live.has(pid); } @@ -535,20 +541,24 @@ export class QqHookClient extends EventEmitter { * in a single filesystem listing. The HookManager's pipe-watcher uses this * to drive connect/reconnect decisions without per-PID stat calls. */ - static async listLivePipes(): Promise> { + static async listLivePipes(pids: readonly number[] = []): Promise> { const result = new Set(); - try { - if (process.platform === 'win32') { - const names = await fs.readdir('\\\\.\\pipe\\'); - for (const name of names) { - const m = /^mojo\.(\d+)\.control$/i.exec(name); - if (m) result.add(Number(m[1])); - } - } else { - return await listLiveLinuxPipePids(); + if (process.platform === 'win32') { + const names = await fs.readdir('\\\\.\\pipe\\'); + for (const name of names) { + const m = /^mojo\.(\d+)\.control$/i.exec(name); + if (m) result.add(Number(m[1])); + } + } else { + const runtimeDirs = new Set(); + if (pids.length === 0) { + runtimeDirs.add(resolveHookRuntimeDir()); + } else { + for (const pid of pids) runtimeDirs.add(resolveHookRuntimeDir(pid)); + } + for (const runtimeDir of runtimeDirs) { + for (const pid of await listLiveLinuxPipePids(runtimeDir)) result.add(pid); } - } catch { - /* directory missing or inaccessible — treat as no live pipes */ } return result; } @@ -605,18 +615,7 @@ export class QqHookClient extends EventEmitter { }: QqHookSendOptions = {}): Promise { await this.connect(); - // Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would - // misbehave once the integer exceeds Number.MAX_SAFE_INTEGER (the - // postfix increment loses precision before the shift), letting two - // distinct requests collide on the same id. Skip 0 because zero is - // used as a sentinel by the wire protocol. - let requestId = this.nextRequestId; - while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) { - requestId = (requestId + 1) >>> 0; - if (requestId === 0) requestId = 1; - } - this.nextRequestId = (requestId + 1) >>> 0; - if (this.nextRequestId === 0) this.nextRequestId = 1; + const requestId = this.allocateRequestId(); const startedAt = Date.now(); const bodyBytes = toBuffer(body); const payload = encodeFrame({ @@ -840,12 +839,49 @@ export class QqHookClient extends EventEmitter { return writePromise; } + private allocateRequestId(): number { + // Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would lose + // precision past Number.MAX_SAFE_INTEGER. Zero remains the wire sentinel. + let requestId = this.nextRequestId; + while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) { + requestId = (requestId + 1) >>> 0; + if (requestId === 0) requestId = 1; + } + this.nextRequestId = (requestId + 1) >>> 0; + if (this.nextRequestId === 0) this.nextRequestId = 1; + return requestId; + } + + private async sendAckOnly(op: PipeOp, value0: bigint, label: string): Promise { + await this.connect(); + const requestId = this.allocateRequestId(); + const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>(); + ackDeferred.promise.catch(() => { /* observed by the await below */ }); + this.pendingAcks.set(requestId, { + resolve: ackDeferred.resolve, + reject: ackDeferred.reject, + wantReply: false, + }); + try { + await this.writeControl(encodeFrame({ op, requestId, value0 })); + await withTimeout( + ackDeferred.promise, + this.defaultAckTimeoutMs, + `${label} ack ${requestId}`, + ); + return requestId; + } catch (error) { + this.pendingAcks.delete(requestId); + throw error; + } + } + private async connectPipe(kind: 'control' | 'recv'): Promise { return runWithTraceRequest(async () => { const startedAt = Date.now(); const pipeName = kind === 'control' - ? QqHookClient.controlPipeName(this.pid) - : QqHookClient.recvPipeName(this.pid); + ? QqHookClient.controlPipeName(this.pid, this.runtimeDir) + : QqHookClient.recvPipeName(this.pid, this.runtimeDir); let phase: 'connect' | 'hello' = 'connect'; runtimeLog.trace( 'hook_pipe_start pid=%d kind=%s pipeName=%j', diff --git a/packages/bridge/tests/hook-runtime-dir.test.ts b/packages/bridge/tests/hook-runtime-dir.test.ts new file mode 100644 index 00000000..f8a6e14b --- /dev/null +++ b/packages/bridge/tests/hook-runtime-dir.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from 'vitest'; +import { resolveHookRuntimeDir } from '../src/hook-runtime-dir'; + +function procReader(files: Record) { + return (file: string): string => { + const value = files[file]; + if (value === undefined) throw new Error(`missing fixture: ${file}`); + return value; + }; +} + +describe('resolveHookRuntimeDir — Linux target process ownership', () => { + it('uses the QQ process runtime directory instead of the supervisor user directory', () => { + expect(resolveHookRuntimeDir(46301, { + platform: 'linux', + env: { XDG_RUNTIME_DIR: '/run/user/0' }, + ownUid: 0, + readText: procReader({ + '/proc/46301/environ': 'HOME=/home/rikka\0XDG_RUNTIME_DIR=/run/user/1000\0', + '/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n', + }), + })).toBe('/run/user/1000'); + }); + + it('falls back to the QQ process uid when its environment has no runtime directory', () => { + expect(resolveHookRuntimeDir(46301, { + platform: 'linux', + env: { XDG_RUNTIME_DIR: '/run/user/0' }, + ownUid: 0, + readText: procReader({ + '/proc/46301/environ': 'HOME=/home/rikka\0', + '/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n', + }), + })).toBe('/tmp/snowluma-1000'); + }); + + it('fails visibly when target ownership cannot be determined', () => { + expect(() => resolveHookRuntimeDir(46301, { + platform: 'linux', + env: { XDG_RUNTIME_DIR: '/run/user/0' }, + ownUid: 0, + readText: () => { throw new Error('permission denied'); }, + })).toThrow(/cannot resolve hook runtime directory.*permission denied/); + }); + + it('uses the current convention when the target disappears during discovery', () => { + const gone = Object.assign(new Error('process disappeared'), { code: 'ENOENT' }); + expect(resolveHookRuntimeDir(46301, { + platform: 'linux', + env: { XDG_RUNTIME_DIR: '/run/user/0' }, + ownUid: 0, + readText: () => { throw gone; }, + })).toBe('/run/user/0'); + }); + + it('honours an explicit runtime directory inherited by the QQ process', () => { + expect(resolveHookRuntimeDir(46301, { + platform: 'linux', + env: {}, + ownUid: 0, + readText: procReader({ + '/proc/46301/environ': 'SNOWLUMA_HOOK_RUNTIME_DIR=/srv/snowluma-hook\0', + '/proc/46301/status': 'Uid:\t1000\t1000\t1000\t1000\n', + }), + })).toBe('/srv/snowluma-hook'); + }); +}); diff --git a/packages/bridge/tests/hook-session.test.ts b/packages/bridge/tests/hook-session.test.ts index a2b33e19..1dab2f79 100644 --- a/packages/bridge/tests/hook-session.test.ts +++ b/packages/bridge/tests/hook-session.test.ts @@ -33,7 +33,10 @@ class FakeClient extends EventEmitter { isClosed = false; isLoggedIn = false; shouldFailConnect = false; + nativeReadyOnIdentityHint = false; + identityHintFailures = 0; readonly sentPackets: Array<{ serviceCmd: string; body: Buffer }> = []; + readonly loginIdentityHints: string[] = []; private loginState = { loggedIn: false, uin: '0', uinNumber: 0n }; async connectAll(_opts: { recv: boolean }): Promise { @@ -46,6 +49,14 @@ class FakeClient extends EventEmitter { this.loginState = { ...state }; this.emit('loginState', { ...this.loginState }); } + async reconcileLoginIdentity(uin: string): Promise { + this.loginIdentityHints.push(uin); + if (this.identityHintFailures > 0) { + this.identityHintFailures--; + throw new Error('identity hint unavailable'); + } + if (this.nativeReadyOnIdentityHint) this.fireLogin(uin); + } async send(serviceCmd: string, body: Buffer) { this.sentPackets.push({ serviceCmd, body: Buffer.from(body) }); return { @@ -76,6 +87,8 @@ function makeSession(opts: { clientFailsConnect?: boolean; onPacket?: PacketSink; probeLogin?: (pid: number) => Promise; + nativeReadyOnIdentityHint?: boolean; + identityHintFailures?: number; } = {}) { const pid = opts.pid ?? 1234; let pipeLive = opts.pipeLive ?? false; @@ -93,6 +106,8 @@ function makeSession(opts: { makeClient: () => { const c = new FakeClient(); if (opts.clientFailsConnect) c.shouldFailConnect = true; + c.nativeReadyOnIdentityHint = opts.nativeReadyOnIdentityHint ?? false; + c.identityHintFailures = opts.identityHintFailures ?? 0; clients.push(c); // Cast: FakeClient mirrors only the surface HookSession touches. return c as unknown as QqHookClient; @@ -810,10 +825,11 @@ describe('HookSession — packet forwarding', () => { }); describe('HookSession — login reconcile (Docker auto-login safety net)', () => { - it('keeps the packet sender usable when login is reconciled by the active probe', async () => { + 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', loggedIn: true }), + nativeReadyOnIdentityHint: true, }); let sender: PacketSender | undefined; ctx.session.on('login', (_uin: string, nextSender: PacketSender) => { @@ -839,10 +855,9 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () => ]); }); - it('reconciles login via the active probe when the pushed frame is missed', async () => { - // Probe reports logged-in; the FakeClient never fires a loginState frame - // (the missed-edge Docker case). The immediate reconcile probe must detect - // it and emit "login". + it('treats a port-probed 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', loggedIn: true }), @@ -853,12 +868,83 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () => await ctx.session.load(); ctx.session.onPipeUp(); await flush(); // connect (not logged in via frame) → starts reconcile - await flush(); // immediate probe resolves → handleLoginState + await flush(); // immediate probe resolves → forwards identity hint - expect(loginSpy).toHaveBeenCalledOnce(); - expect(loginSpy.mock.calls[0]![0]).toBe('10001'); - expect(ctx.session.status).toBe('online'); - expect(ctx.session.uin).toBe('10001'); + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']); + expect(loginSpy).not.toHaveBeenCalled(); + expect(ctx.session.status).toBe('loaded'); + expect(ctx.session.uin).toBe('0'); + }); + + it('forwards the same identity at most once per pipe connection', async () => { + vi.useFakeTimers(); + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }), + }); + try { + await ctx.session.load(); + ctx.session.onPipeUp(); + await vi.advanceTimersByTimeAsync(0); + await vi.advanceTimersByTimeAsync(9000); + + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']); + } finally { + ctx.session.dispose(); + vi.useRealTimers(); + } + }); + + it('keeps observing identity after acknowledgement and forwards an account change', async () => { + vi.useFakeTimers(); + let uin = '10001'; + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => ({ port: 4301, uin, loggedIn: true }), + }); + try { + await ctx.session.load(); + ctx.session.onPipeUp(); + await vi.advanceTimersByTimeAsync(0); + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']); + + uin = '20002'; + await vi.advanceTimersByTimeAsync(29_999); + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']); + + await vi.advanceTimersByTimeAsync(1); + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '20002']); + } finally { + ctx.session.dispose(); + vi.useRealTimers(); + } + }); + + it('retries identity forwarding failures with a strict bound', async () => { + vi.useFakeTimers(); + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }), + identityHintFailures: 3, + }); + try { + await ctx.session.load(); + ctx.session.onPipeUp(); + await vi.advanceTimersByTimeAsync(0); + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']); + + await vi.advanceTimersByTimeAsync(3000); + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001']); + + await vi.advanceTimersByTimeAsync(9000); + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001', '10001']); + + await vi.advanceTimersByTimeAsync(30_000); + expect(ctx.currentClient().loginIdentityHints).toHaveLength(3); + } finally { + ctx.session.dispose(); + vi.useRealTimers(); + } }); it('does not log in when the probe reports not-logged-in', async () => { @@ -912,6 +998,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () => const ctx = makeSession({ pipeLive: true, probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn }), + nativeReadyOnIdentityHint: true, }); const loginSpy = vi.fn(); ctx.session.on('login', loginSpy); diff --git a/packages/bridge/tests/pipe-watcher.test.ts b/packages/bridge/tests/pipe-watcher.test.ts index 29abc90e..26214c56 100644 --- a/packages/bridge/tests/pipe-watcher.test.ts +++ b/packages/bridge/tests/pipe-watcher.test.ts @@ -30,6 +30,27 @@ function captureEvents(watcher: PipeWatcher): EventRow[] { } describe('PipeWatcher', () => { + it('passes the current process snapshot to pipe discovery', async () => { + const processes = [ + { pid: 1234, name: 'qq', path: '/opt/QQ/qq' }, + { pid: 5678, name: 'qq', path: '/opt/QQ/qq' }, + ]; + let observed: readonly HookProcessBaseInfo[] | undefined; + const watcher = new PipeWatcher({ + listProcesses: () => processes, + listLivePipes: async current => { + observed = current; + return new Set(); + }, + intervalMs: 60_000, + }); + + await watcher.start(); + + expect(observed).toEqual(processes); + watcher.stop(); + }); + it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => { const ctx = setupWatcher({ processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], @@ -193,6 +214,38 @@ describe('PipeWatcher', () => { watcher.stop(); }); + it('preserves live sessions when pipe discovery temporarily fails', async () => { + let processes = [{ pid: 1234, name: 'QQ.exe', path: '' }]; + let failPipeDiscovery = false; + const watcher = new PipeWatcher({ + listProcesses: () => processes, + listLivePipes: async () => { + if (failPipeDiscovery) throw new Error('permission denied'); + return new Set([1234]); + }, + intervalMs: 60_000, + }); + + await watcher.start(); + expect(watcher.isPipeLive(1234)).toBe(true); + const events = captureEvents(watcher); + + failPipeDiscovery = true; + await watcher.tickNow(); + + expect(events).toEqual([]); + expect(watcher.isProcessAlive(1234)).toBe(true); + expect(watcher.isPipeLive(1234)).toBe(true); + + processes = []; + await watcher.tickNow(); + + expect(events).toEqual([['down', 1234], ['gone', 1234]]); + expect(watcher.isProcessAlive(1234)).toBe(false); + expect(watcher.isPipeLive(1234)).toBe(false); + watcher.stop(); + }); + it('UNKNOWN (null) enumeration keeps prior state — no false process-gone (issue #158)', async () => { let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }]; let live = new Set([1234]); diff --git a/packages/bridge/tests/qq-hook-client.test.ts b/packages/bridge/tests/qq-hook-client.test.ts index d3a76f7f..f38a6a66 100644 --- a/packages/bridge/tests/qq-hook-client.test.ts +++ b/packages/bridge/tests/qq-hook-client.test.ts @@ -151,6 +151,35 @@ describe('listLiveLinuxPipePids', () => { }); describe('QqHookClient — pipe frame limits', () => { + it('forwards a probed account as a native identity hint without changing login state', async () => { + const pid = 778819; + const writes: Buffer[] = []; + const connection = mockControlPipe(pid, (socket, payload) => { + writes.push(Buffer.from(payload)); + const requestId = payload.readUInt32LE(8); + queueMicrotask(() => socket.emit('data', pipeFrame({ + op: PipeOp.sendAck, + requestId, + }))); + }); + const client = new QqHookClient(pid); + try { + await client.reconcileLoginIdentity('10001'); + + expect(writes).toHaveLength(1); + expect(writes[0]!.readUInt16LE(6)).toBe(PipeOp.loginIdentityHint); + expect(writes[0]!.readBigUInt64LE(32)).toBe(10001n); + expect(client.getLoginState()).toEqual({ + loggedIn: false, + uin: '0', + uinNumber: 0n, + }); + } finally { + client.close(); + connection.mockRestore(); + } + }); + it.each([ ['command', 20, MAX_PIPE_CMD_BYTES], ['message', 24, MAX_PIPE_MSG_BYTES],