diff --git a/packages/bridge/src/hook-session.ts b/packages/bridge/src/hook-session.ts index 07465bfa..4d5ad5d2 100644 --- a/packages/bridge/src/hook-session.ts +++ b/packages/bridge/src/hook-session.ts @@ -24,7 +24,7 @@ const RECEIVE_STALE_CONFIRM_MS = 15_000; export type HookSessionDeps = { injector: { - inject: (pid: number) => HookInjectResult; + inject: (pid: number) => HookInjectResult | Promise; unload: (pid: number, handle: HookInjectResult['handle']) => void; }; makeClient: (pid: number) => QqHookClient; @@ -232,7 +232,7 @@ export class HookSession extends EventEmitter { this._method = this._method || 'reconnect'; this.log.info('PID=%d already has SnowLuma pipe; will reconnect', this.pid); } else { - this.injectResult = this.injector.inject(this.pid); + this.injectResult = await this.injector.inject(this.pid); this.injected = true; this._method = this.injectResult.method; } diff --git a/packages/bridge/src/injector.ts b/packages/bridge/src/injector.ts index df491faa..1cabeda5 100644 --- a/packages/bridge/src/injector.ts +++ b/packages/bridge/src/injector.ts @@ -15,7 +15,7 @@ export interface ManualMapHandle { interface NativeHookAddon { getAllMainProcess(): number[]; - loadModuleManual(pid: number, dylibPath: string): ManualMapHandle; + loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise; unloadModuleManual(pid: number, handle: ManualMapHandle): void; } @@ -119,7 +119,7 @@ export function listHookProcesses(): HookProcessBaseInfo[] { .map(pid => ({ pid, name: defaultProcessName(), path: '' })); } -export function injectHookProcess(pid: number): HookInjectResult { +export async function injectHookProcess(pid: number): Promise { const addon = getNativeHookAddon(); if (!addon) { throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available'); @@ -129,7 +129,7 @@ export function injectHookProcess(pid: number): HookInjectResult { if (!dllPath) { throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`); } - return { method: 'loadModuleManual', handle: addon.loadModuleManual(pid, dllPath) }; + return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) }; } export function unloadHookProcess(pid: number, handle: ManualMapHandle): void { diff --git a/packages/bridge/src/qq-port-probe.ts b/packages/bridge/src/qq-port-probe.ts index be25eefd..4daa5c78 100644 --- a/packages/bridge/src/qq-port-probe.ts +++ b/packages/bridge/src/qq-port-probe.ts @@ -1,3 +1,4 @@ +import { createLogger } from '@snowluma/common/logger'; import { exec } from 'child_process'; import net from 'net'; import http from 'http'; @@ -5,11 +6,15 @@ import https from 'https'; import { promisify } from 'util'; const execAsync = promisify(exec); +const log = createLogger('LoginProbe'); const PORT_RANGE_START = 9210; const PORT_RANGE_END = 9219; const PROBE_TIMEOUT_MS = 1000; 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 @@ -200,10 +205,13 @@ async function tryPtloginMethod(port: number): Promise { try { if (process.platform === 'win32') { - const { stdout } = await execAsync('tasklist /fi "imagename eq QQ.exe" /nh'); + 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'); + const { stdout } = await execAsync('pgrep -c qq', EXEC_OPTIONS); return parseInt(stdout.trim(), 10) || 0; } } catch { @@ -213,10 +221,10 @@ async function getQqProcessCount(): Promise { } } -async function getProcessPorts(pid: number): Promise { +async function getProcessPorts(pid: number): Promise { try { if (process.platform === 'win32') { - const { stdout } = await execAsync(`netstat -ano | findstr ${pid}`); + const { stdout } = await execAsync('netstat -ano', EXEC_OPTIONS); const ports = new Set(); const lines = stdout.split('\n'); for (const line of lines) { @@ -232,10 +240,11 @@ async function getProcessPorts(pid: number): Promise { } return Array.from(ports); } else { - const { stdout } = await execAsync(`ss -tlnp | grep pid=${pid}`); + 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])); @@ -244,13 +253,13 @@ async function getProcessPorts(pid: number): Promise { return Array.from(ports); } } catch { - return []; + return null; } } - -export async function probeQqLoginInfo(pid: number): Promise { +async function probeQqLoginInfoInternal(pid: number): Promise { const ports = await getProcessPorts(pid); + if (ports === null) return null; if (ports.length === 0) { const totalPids = await getQqProcessCount(); @@ -298,3 +307,21 @@ 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/tests/hook-session.test.ts b/packages/bridge/tests/hook-session.test.ts index 8d54fa64..befbb48d 100644 --- a/packages/bridge/tests/hook-session.test.ts +++ b/packages/bridge/tests/hook-session.test.ts @@ -116,6 +116,33 @@ describe('HookSession — load', () => { expect(info.status).toBe('connecting'); }); + it('keeps loading pending until asynchronous component loading completes', async () => { + let finishLoading!: (result: { method: 'loadModuleManual'; handle: ManualMapHandle }) => void; + const loading = new Promise<{ method: 'loadModuleManual'; handle: ManualMapHandle }>(resolve => { + finishLoading = resolve; + }); + const injector = { + inject: vi.fn(() => loading), + unload: vi.fn(), + }; + const session = new HookSession(1234, { + injector, + makeClient: () => new FakeClient() as unknown as QqHookClient, + pipeWatcher: { isPipeLive: () => false }, + }); + + const load = session.load(); + await flush(); + + expect(session.status).toBe('loading'); + finishLoading({ method: 'loadModuleManual', handle: DUMMY_HANDLE }); + await expect(load).resolves.toMatchObject({ + status: 'connecting', + method: 'loadModuleManual', + injected: true, + }); + }); + it('inject failure → status error, error message captured', async () => { const injector = { inject: vi.fn(() => { throw new Error('inject boom'); }), @@ -130,6 +157,37 @@ describe('HookSession — load', () => { expect(info.status).toBe('error'); expect(info.error).toBe('inject boom'); }); + + it('can retry after asynchronous component loading fails', async () => { + const injector = { + inject: vi + .fn() + .mockRejectedValueOnce(new Error('component loading timed out')) + .mockResolvedValueOnce({ + method: 'loadModuleManual' as const, + handle: DUMMY_HANDLE, + }), + unload: vi.fn(), + }; + const session = new HookSession(1234, { + injector, + makeClient: () => new FakeClient() as unknown as QqHookClient, + pipeWatcher: { isPipeLive: () => false }, + }); + + await expect(session.load()).resolves.toMatchObject({ + status: 'error', + error: 'component loading timed out', + injected: false, + }); + await expect(session.load()).resolves.toMatchObject({ + status: 'connecting', + method: 'loadModuleManual', + injected: true, + error: '', + }); + expect(injector.inject).toHaveBeenCalledTimes(2); + }); }); describe('HookSession — pipe up/down → connect lifecycle', () => { diff --git a/packages/bridge/tests/qq-port-probe.test.ts b/packages/bridge/tests/qq-port-probe.test.ts new file mode 100644 index 00000000..6a3289e9 --- /dev/null +++ b/packages/bridge/tests/qq-port-probe.test.ts @@ -0,0 +1,39 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const execMock = vi.hoisted(() => vi.fn()); + +vi.mock('child_process', () => ({ exec: execMock })); + +import { probeQqLoginInfo } from '../src/qq-port-probe'; + +describe('probeQqLoginInfo — bounded execution', () => { + beforeEach(() => { + vi.useFakeTimers(); + execMock.mockReset(); + }); + + 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: '1\n', stderr: '' }); + }); + + await expect(probeQqLoginInfo(4242)).resolves.toEqual({ + port: 0, + uin: '', + loggedIn: false, + }); + }); +});