fix(bridge): bound process operations

This commit is contained in:
DrSmoothl committed 2026-07-29 02:15:13 +08:00
1 parent 5d1dbecf2e
commit f97444c391
5 files changed
+137 -13

No files matched your search

+2 -2
View File
@@ -24,7 +24,7 @@ const RECEIVE_STALE_CONFIRM_MS = 15_000;
export type HookSessionDeps = {
injector: {
inject: (pid: number) => HookInjectResult;
inject: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
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;
}
+3 -3
View File
@@ -15,7 +15,7 @@ export interface ManualMapHandle {
interface NativeHookAddon {
getAllMainProcess(): number[];
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle;
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>;
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<HookInjectResult> {
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 {
+35 -8
View File
@@ -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<QqPortLoginInfo | 'fallba
async function getQqProcessCount(): Promise<number> {
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<number> {
}
}
async function getProcessPorts(pid: number): Promise<number[]> {
async function getProcessPorts(pid: number): Promise<number[] | null> {
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<number>();
const lines = stdout.split('\n');
for (const line of lines) {
@@ -232,10 +240,11 @@ async function getProcessPorts(pid: number): Promise<number[]> {
}
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<number>();
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<number[]> {
return Array.from(ports);
}
} catch {
return [];
return null;
}
}
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo | null> {
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<QqPortLoginInfo | n
return null;
}
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
let timer: ReturnType<typeof setTimeout> | undefined;
let timedOut = false;
const timeout = new Promise<null>(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);
}
}
@@ -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', () => {
@@ -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,
});
});
});