This commit is contained in:
DrSmoothl committed 2026-10-12 15:43:34 +08:00
1 parent effeb66554
commit 7c0519f75f
977 files changed
+198426 -158324

No files matched your search

File diff suppressed because it is too large. Load diff
+60 -44
View File
@@ -1,58 +1,74 @@
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import { packetTimeoutMs } from './packet-timeout';
import {
HookPipeRequestError,
PIPE_STATUS_CONNECTION_UNAVAILABLE,
QqHookClient,
type QqHookSendReply,
HookPipeRequestError,
PIPE_STATUS_CONNECTION_UNAVAILABLE,
QqHookClient,
type QqHookSendReply,
} from './qq-hook-client';
export type OutboundHealthListener = (healthy: boolean) => void;
export class HookPacketClient implements PacketSender {
private outboundHealthy = true;
private outboundHealthy = true;
constructor(
private readonly client: QqHookClient,
private readonly onOutboundHealthChanged?: OutboundHealthListener,
) { }
constructor(
private readonly client: QqHookClient,
private readonly onOutboundHealthChanged?: OutboundHealthListener,
) {}
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
if (!this.client.isLoggedIn) {
return { success: false, gotResponse: false, errorCode: -1, errorMessage: 'qq_hook client is not logged in', responseData: null };
async sendPacket(
serviceCmd: string,
body: Buffer,
timeoutMs = packetTimeoutMs(),
): Promise<SendPacketResult> {
if (!this.client.isLoggedIn) {
return {
success: false,
gotResponse: false,
errorCode: -1,
errorMessage: 'qq_hook client is not logged in',
responseData: null,
};
}
try {
const reply = (await this.client.send(serviceCmd, body, {
wantReply: true,
replyTimeoutMs: timeoutMs,
})) as QqHookSendReply;
this.setOutboundHealthy(true);
return {
success: reply.error === 0,
gotResponse: true,
errorCode: reply.error,
errorMessage: reply.message || '',
responseData: reply.body,
};
} catch (error) {
if (
error instanceof HookPipeRequestError &&
error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE
) {
this.setOutboundHealthy(false);
}
return {
success: false,
gotResponse: false,
errorCode: -1,
errorMessage: error instanceof Error ? error.message : String(error),
responseData: null,
};
}
}
try {
const reply = await this.client.send(serviceCmd, body, {
wantReply: true,
replyTimeoutMs: timeoutMs,
}) as QqHookSendReply;
this.setOutboundHealthy(true);
return {
success: reply.error === 0,
gotResponse: true,
errorCode: reply.error,
errorMessage: reply.message || '',
responseData: reply.body,
};
} catch (error) {
if (error instanceof HookPipeRequestError
&& error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE) {
this.setOutboundHealthy(false);
}
return {
success: false,
gotResponse: false,
errorCode: -1,
errorMessage: error instanceof Error ? error.message : String(error),
responseData: null,
};
}
}
private setOutboundHealthy(healthy: boolean): void {
if (this.outboundHealthy === healthy) {
return;
}
private setOutboundHealthy(healthy: boolean): void {
if (this.outboundHealthy === healthy) return;
this.outboundHealthy = healthy;
this.onOutboundHealthChanged?.(healthy);
}
this.outboundHealthy = healthy;
this.onOutboundHealthChanged?.(healthy);
}
}
+132 -94
View File
@@ -3,128 +3,166 @@ import os from 'os';
import path from 'path';
export interface HookRuntimeDirDeps {
platform?: NodeJS.Platform;
env?: NodeJS.ProcessEnv;
ownUid?: number;
readText?: (file: string) => string;
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;
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;
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;
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';
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);
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;
function ownRuntimeDir(platform: NodeJS.Platform, env: NodeJS.ProcessEnv, ownUid: number): string {
const explicit = configuredDirectory(
env.SNOWLUMA_HOOK_RUNTIME_DIR,
'SNOWLUMA_HOOK_RUNTIME_DIR',
);
const xdg = configuredDirectory(env.XDG_RUNTIME_DIR, 'XDG_RUNTIME_DIR');
if (xdg) return xdg;
if (explicit) {
return explicit;
}
if (platform === 'darwin') {
const tmpdir = configuredDirectory(env.TMPDIR, 'TMPDIR');
if (tmpdir) return path.join(tmpdir, 'snowluma-hook');
}
return `/tmp/snowluma-${ownUid}`;
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'));
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;
if (platform !== 'linux' || !Number.isSafeInteger(targetPid) || targetPid! <= 0) {
return ownRuntimeDir(platform, env, ownUid);
}
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;
}
let environError: unknown;
if (isProcessGoneError(statusError)
&& (isProcessGoneError(environError)
|| (environError instanceof Error
&& environError.message === 'runtime directory is not present'))) {
return ownRuntimeDir(platform, env, ownUid);
}
try {
const targetEnv = parseProcessEnvironment(readText(`/proc/${targetPid}/environ`));
const explicit = configuredDirectory(
targetEnv.SNOWLUMA_HOOK_RUNTIME_DIR,
`QQ process ${targetPid} SNOWLUMA_HOOK_RUNTIME_DIR`,
);
throw new Error(
`cannot resolve hook runtime directory for PID ${targetPid}: `
+ `environment=${errorMessage(environError)}; status=${errorMessage(statusError)}`,
);
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)}`,
);
}
File diff suppressed because it is too large. Load diff
+13 -7
View File
@@ -9,10 +9,10 @@ import type { HookProcessStatus } from './types';
* `loggedIn` *before* tearing the client down, since teardown clears it.
*/
export interface HookFlags {
injected: boolean;
connected: boolean;
loggedIn: boolean;
wasLoggedIn: boolean;
injected: boolean;
connected: boolean;
loggedIn: boolean;
wasLoggedIn: boolean;
}
/**
@@ -25,7 +25,13 @@ export interface HookFlags {
* here.
*/
export function statusFor(flags: HookFlags): HookProcessStatus {
if (!flags.injected) return 'available';
if (flags.connected) return flags.loggedIn ? 'online' : 'loaded';
return flags.wasLoggedIn ? 'disconnected' : 'connecting';
if (!flags.injected) {
return 'available';
}
if (flags.connected) {
return flags.loggedIn ? 'online' : 'loaded';
}
return flags.wasLoggedIn ? 'disconnected' : 'connecting';
}
+7 -3
View File
@@ -1,5 +1,9 @@
export {
HookManager, type BridgeManagerSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
type HookProcessStatus, type QqPortLoginInfo
HookManager,
type BridgeManagerSink,
type HookManagerDeps,
type HookProcessBaseInfo,
type HookProcessInfo,
type HookProcessStatus,
type QqPortLoginInfo,
} from './hook-manager';
+108 -84
View File
@@ -7,135 +7,159 @@ import { listSnowlumaPipePidsSync } from './qq-hook-client';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export interface ManualMapHandle {
base: bigint;
entry: bigint;
exceptionTable: bigint;
size: number;
base: bigint;
entry: bigint;
exceptionTable: bigint;
size: number;
}
interface NativeHookAddon {
getAllMainProcess(): number[];
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>;
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
getAllMainProcess(): number[];
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>;
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
}
export interface HookProcessBaseInfo {
pid: number;
name: string;
path: string;
pid: number;
name: string;
path: string;
}
export interface HookInjectResult {
method: 'loadModuleManual';
handle?: ManualMapHandle;
method: 'loadModuleManual';
handle?: ManualMapHandle;
}
let nativeAddon: NativeHookAddon | null = null;
let nativeLoadError: string | null = null;
function loadNativeAddon(addonPath: string): NativeHookAddon {
const mod = { exports: {} as Record<string, unknown> };
process.dlopen(mod, addonPath);
return mod.exports as unknown as NativeHookAddon;
const mod = { exports: {} as Record<string, unknown> };
process.dlopen(mod, addonPath);
return mod.exports as unknown as NativeHookAddon;
}
type HookBinaryExt = 'node' | 'dll' | 'so';
function platformBinaryName(ext: HookBinaryExt): string {
if (process.platform === 'win32' && process.arch === 'x64') return `snowluma-win32-x64.${ext}`;
return `snowluma-${process.platform}-${process.arch}.${ext}`;
if (process.platform === 'win32' && process.arch === 'x64') {
return `snowluma-win32-x64.${ext}`;
}
return `snowluma-${process.platform}-${process.arch}.${ext}`;
}
function platformInjectableExt(): 'dll' | 'so' {
return process.platform === 'win32' ? 'dll' : 'so';
return process.platform === 'win32' ? 'dll' : 'so';
}
function defaultProcessName(): string {
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
}
function nativeSearchDirs(): string[] {
// Several layouts must be supported:
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
// 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=<root>/packages/bridge/src
// → walk up to <root>/packages and append runtime/native
// Same offset works for `packages/bridge/dist/index.mjs` after build.
// 3. cwd-based fallback when neither __dirname-relative path resolves.
return [
path.resolve(__dirname, 'native'),
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
path.resolve(process.cwd(), 'dist', 'native'),
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
];
// Several layouts must be supported:
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
// 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=<root>/packages/bridge/src
// → walk up to <root>/packages and append runtime/native
// Same offset works for `packages/bridge/dist/index.mjs` after build.
// 3. cwd-based fallback when neither __dirname-relative path resolves.
return [
path.resolve(__dirname, 'native'),
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
path.resolve(process.cwd(), 'dist', 'native'),
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
];
}
export function resolveHookNativePath(ext: HookBinaryExt): string | null {
const fileName = platformBinaryName(ext);
for (const dir of nativeSearchDirs()) {
const fullPath = path.join(dir, fileName);
if (existsSync(fullPath)) return fullPath;
}
return null;
const fileName = platformBinaryName(ext);
for (const dir of nativeSearchDirs()) {
const fullPath = path.join(dir, fileName);
if (existsSync(fullPath)) {
return fullPath;
}
}
return null;
}
export function getNativeHookAddon(): NativeHookAddon | null {
if (nativeAddon) return nativeAddon;
const addonPath = resolveHookNativePath('node');
if (!addonPath) {
nativeLoadError = `No hook native addon found for ${process.platform}-${process.arch}`;
return null;
}
try {
nativeAddon = loadNativeAddon(addonPath);
nativeLoadError = null;
return nativeAddon;
} catch (error) {
nativeLoadError = error instanceof Error ? error.message : String(error);
return null;
}
if (nativeAddon) {
return nativeAddon;
}
const addonPath = resolveHookNativePath('node');
if (!addonPath) {
nativeLoadError = `No hook native addon found for ${process.platform}-${process.arch}`;
return null;
}
try {
nativeAddon = loadNativeAddon(addonPath);
nativeLoadError = null;
return nativeAddon;
} catch (error) {
nativeLoadError = error instanceof Error ? error.message : String(error);
return null;
}
}
export function getNativeHookLoadError(): string | null {
return nativeLoadError;
return nativeLoadError;
}
export function listHookProcesses(): HookProcessBaseInfo[] {
// macOS: no native enumerate-QQ addon. The DYLD_INSERT injection model
// means QQ ran with our dylib already mapped, so the dylib's listener
// socket IS the discovery signal. Treat every `mojo.<pid>.control.sock`
// in the runtime dir as a known process (the watcher's subsequent
// connectable-probe gates the pipe-up emit, so a stale dangling socket
// here doesn't drive a false connect).
if (process.platform === 'darwin') {
return [...listSnowlumaPipePidsSync()]
.sort((a, b) => a - b)
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
}
const addon = getNativeHookAddon();
if (!addon) return [];
return [...new Set(addon.getAllMainProcess())]
.filter(pid => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b)
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
// macOS: no native enumerate-QQ addon. The DYLD_INSERT injection model
// means QQ ran with our dylib already mapped, so the dylib's listener
// socket IS the discovery signal. Treat every `mojo.<pid>.control.sock`
// in the runtime dir as a known process (the watcher's subsequent
// connectable-probe gates the pipe-up emit, so a stale dangling socket
// here doesn't drive a false connect).
if (process.platform === 'darwin') {
return [...listSnowlumaPipePidsSync()]
.sort((a, b) => a - b)
.map((pid) => ({ pid, name: defaultProcessName(), path: '' }));
}
const addon = getNativeHookAddon();
if (!addon) {
return [];
}
return [...new Set(addon.getAllMainProcess())]
.filter((pid) => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b)
.map((pid) => ({ pid, name: defaultProcessName(), path: '' }));
}
export async function injectHookProcess(pid: number): Promise<HookInjectResult> {
const addon = getNativeHookAddon();
if (!addon) {
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
}
const injectableExt = platformInjectableExt();
const dllPath = resolveHookNativePath(injectableExt);
if (!dllPath) {
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
}
return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) };
const addon = getNativeHookAddon();
if (!addon) {
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
}
const injectableExt = platformInjectableExt();
const dllPath = resolveHookNativePath(injectableExt);
if (!dllPath) {
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
}
return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) };
}
export function unloadHookProcess(pid: number, handle: ManualMapHandle): void {
const addon = getNativeHookAddon();
if (!addon) {
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
}
addon.unloadModuleManual(pid, handle);
const addon = getNativeHookAddon();
if (!addon) {
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
}
addon.unloadModuleManual(pid, handle);
}
+1 -1
View File
@@ -4,5 +4,5 @@ import { positiveIntEnv } from '@snowluma/common/env';
export const DEFAULT_PACKET_TIMEOUT_MS = 15_000;
export function packetTimeoutMs(env?: NodeJS.ProcessEnv): number {
return positiveIntEnv('SNOWLUMA_PACKET_TIMEOUT_MS', DEFAULT_PACKET_TIMEOUT_MS, { env });
return positiveIntEnv('SNOWLUMA_PACKET_TIMEOUT_MS', DEFAULT_PACKET_TIMEOUT_MS, { env });
}
+215 -182
View File
@@ -6,17 +6,17 @@ const DEFAULT_INTERVAL_MS = 1500;
const MIN_INTERVAL_MS = 250;
export type PipeWatcherDeps = {
/** Native: list QQ.exe processes currently running. May be async and may
* return `null` (UNKNOWN) when enumeration timed out / failed — in which
* case this tick keeps the prior process+pipe state instead of treating the
* missing data as "everything disappeared" (issue #158). */
listProcesses: () => HookProcessBaseInfo[] | null | Promise<HookProcessBaseInfo[] | null>;
/** 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<Set<number>>;
/** Polling interval in ms. Defaults to 1500, floored to 250. */
intervalMs?: number;
log?: Logger;
/** Native: list QQ.exe processes currently running. May be async and may
* return `null` (UNKNOWN) when enumeration timed out / failed — in which
* case this tick keeps the prior process+pipe state instead of treating the
* missing data as "everything disappeared" (issue #158). */
listProcesses: () => HookProcessBaseInfo[] | null | Promise<HookProcessBaseInfo[] | null>;
/** 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<Set<number>>;
/** Polling interval in ms. Defaults to 1500, floored to 250. */
intervalMs?: number;
log?: Logger;
};
/**
@@ -40,191 +40,224 @@ export type PipeWatcherDeps = {
* dispose logic when QQ.exe is killed with a live pipe.
*/
export class PipeWatcher extends EventEmitter {
private readonly listProcesses: PipeWatcherDeps['listProcesses'];
private readonly listLivePipes: PipeWatcherDeps['listLivePipes'];
private readonly intervalMs: number;
private readonly log: Logger;
private readonly listProcesses: PipeWatcherDeps['listProcesses'];
private readonly listLivePipes: PipeWatcherDeps['listLivePipes'];
private readonly intervalMs: number;
private readonly log: Logger;
private livePipes = new Set<number>();
private knownPids = new Set<number>();
private timer: NodeJS.Timeout | null = null;
private ticking = false;
private pendingWake = false;
private startPromise: Promise<void> | null = null;
private stopped = false;
private livePipes = new Set<number>();
private knownPids = new Set<number>();
private timer: NodeJS.Timeout | null = null;
private ticking = false;
private pendingWake = false;
private startPromise: Promise<void> | null = null;
private stopped = false;
constructor(deps: PipeWatcherDeps) {
super();
this.listProcesses = deps.listProcesses;
this.listLivePipes = deps.listLivePipes;
this.intervalMs = Math.max(MIN_INTERVAL_MS, deps.intervalMs ?? DEFAULT_INTERVAL_MS);
this.log = deps.log ?? createLogger('PipeWatcher');
}
/** Was this PID's pipe live as of the last completed tick? */
isPipeLive(pid: number): boolean {
return this.livePipes.has(pid);
}
/** Was this PID alive as of the last completed tick? */
isProcessAlive(pid: number): boolean {
return this.knownPids.has(pid);
}
/**
* Run an initial tick (so isPipeLive/isProcessAlive return real data)
* and begin the polling loop. Idempotent.
*/
start(): Promise<void> {
if (this.startPromise) return this.startPromise;
this.startPromise = (async () => {
try {
await this.tickOnce();
} finally {
this.scheduleNext(this.intervalMs);
}
})();
return this.startPromise;
}
/** Pull the next scheduled tick forward to the next event-loop turn. */
wake(): void {
if (this.stopped) return;
this.scheduleNext(0);
}
/** Force a single tick now. Resolves after diff events have been emitted. */
tickNow(): Promise<void> {
return this.tickOnce();
}
stop(): void {
this.stopped = true;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
constructor(deps: PipeWatcherDeps) {
super();
this.listProcesses = deps.listProcesses;
this.listLivePipes = deps.listLivePipes;
this.intervalMs = Math.max(MIN_INTERVAL_MS, deps.intervalMs ?? DEFAULT_INTERVAL_MS);
this.log = deps.log ?? createLogger('PipeWatcher');
}
}
dispose(): void {
this.stop();
this.removeAllListeners();
}
private scheduleNext(delayMs: number): void {
if (this.stopped) return;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
/** Was this PID's pipe live as of the last completed tick? */
isPipeLive(pid: number): boolean {
return this.livePipes.has(pid);
}
this.timer = setTimeout(() => {
this.timer = null;
void this.tickAndReschedule();
}, Math.max(0, delayMs));
}
private async tickAndReschedule(): Promise<void> {
try {
await this.tickOnce();
} finally {
this.scheduleNext(this.intervalMs);
/** Was this PID alive as of the last completed tick? */
isProcessAlive(pid: number): boolean {
return this.knownPids.has(pid);
}
}
/**
* Read processes + live pipes, emit diff events. If another tick is
* already running, mark a follow-up tick so we don't lose a wake().
*/
private async tickOnce(): Promise<void> {
if (this.ticking) {
this.pendingWake = true;
return;
/**
* Run an initial tick (so isPipeLive/isProcessAlive return real data)
* and begin the polling loop. Idempotent.
*/
start(): Promise<void> {
if (this.startPromise) {
return this.startPromise;
}
this.startPromise = (async () => {
try {
await this.tickOnce();
} finally {
this.scheduleNext(this.intervalMs);
}
})();
return this.startPromise;
}
this.ticking = true;
try {
let processes: HookProcessBaseInfo[] | null;
try {
processes = await this.listProcesses();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
processes = null;
}
// UNKNOWN (timeout / failure): keep the prior process + pipe snapshot.
// Treating missing data as "everything disappeared" would fire
// process-gone for every live PID and dispose healthy sessions — the
// freeze-then-teardown footgun behind issue #158. Still emit 'tick' so
// the manager's per-tick reconnect retries keep running off last-known
// live pipes.
if (processes === null) {
this.emit('tick');
return;
}
let livePipes: Set<number> | null;
try {
livePipes = await this.listLivePipes(processes);
} catch (error) {
this.log.warn('listLivePipes failed: %s', errMsg(error));
livePipes = null;
}
const newKnownPids = new Set<number>();
for (const proc of processes) newKnownPids.add(proc.pid);
// 1. Newly discovered processes.
for (const proc of processes) {
if (!this.knownPids.has(proc.pid)) {
this.emit('process-discovered', proc);
/** Pull the next scheduled tick forward to the next event-loop turn. */
wake(): void {
if (this.stopped) {
return;
}
}
// 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<number>();
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);
}
}
}
// 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so
// subscribers can run disconnect logic before dispose logic.
for (const pid of this.livePipes) {
if (!newLivePipes.has(pid)) {
this.emit('pipe-down', pid);
}
}
// 4. Processes that disappeared.
for (const pid of this.knownPids) {
if (!newKnownPids.has(pid)) {
this.emit('process-gone', pid);
}
}
this.knownPids = newKnownPids;
this.livePipes = newLivePipes;
this.emit('tick');
} finally {
this.ticking = false;
if (this.pendingWake) {
this.pendingWake = false;
// Defer to break sync recursion if a listener calls wake().
setImmediate(() => { void this.tickOnce(); });
}
this.scheduleNext(0);
}
/** Force a single tick now. Resolves after diff events have been emitted. */
tickNow(): Promise<void> {
return this.tickOnce();
}
stop(): void {
this.stopped = true;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
dispose(): void {
this.stop();
this.removeAllListeners();
}
private scheduleNext(delayMs: number): void {
if (this.stopped) {
return;
}
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(
() => {
this.timer = null;
void this.tickAndReschedule();
},
Math.max(0, delayMs),
);
}
private async tickAndReschedule(): Promise<void> {
try {
await this.tickOnce();
} finally {
this.scheduleNext(this.intervalMs);
}
}
/**
* Read processes + live pipes, emit diff events. If another tick is
* already running, mark a follow-up tick so we don't lose a wake().
*/
private async tickOnce(): Promise<void> {
if (this.ticking) {
this.pendingWake = true;
return;
}
this.ticking = true;
try {
let processes: HookProcessBaseInfo[] | null;
try {
processes = await this.listProcesses();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
processes = null;
}
// UNKNOWN (timeout / failure): keep the prior process + pipe snapshot.
// Treating missing data as "everything disappeared" would fire
// process-gone for every live PID and dispose healthy sessions — the
// freeze-then-teardown footgun behind issue #158. Still emit 'tick' so
// the manager's per-tick reconnect retries keep running off last-known
// live pipes.
if (processes === null) {
this.emit('tick');
return;
}
let livePipes: Set<number> | null;
try {
livePipes = await this.listLivePipes(processes);
} catch (error) {
this.log.warn('listLivePipes failed: %s', errMsg(error));
livePipes = null;
}
const newKnownPids = new Set<number>();
for (const proc of processes) {
newKnownPids.add(proc.pid);
}
// 1. Newly discovered processes.
for (const proc of processes) {
if (!this.knownPids.has(proc.pid)) {
this.emit('process-discovered', proc);
}
}
// 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<number>();
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);
}
}
}
// 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so
// subscribers can run disconnect logic before dispose logic.
for (const pid of this.livePipes) {
if (!newLivePipes.has(pid)) {
this.emit('pipe-down', pid);
}
}
// 4. Processes that disappeared.
for (const pid of this.knownPids) {
if (!newKnownPids.has(pid)) {
this.emit('process-gone', pid);
}
}
this.knownPids = newKnownPids;
this.livePipes = newLivePipes;
this.emit('tick');
} finally {
this.ticking = false;
if (this.pendingWake) {
this.pendingWake = false;
// Defer to break sync recursion if a listener calls wake().
setImmediate(() => {
void this.tickOnce();
});
}
}
}
}
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
return value instanceof Error ? value.message : String(value);
}
+207 -154
View File
@@ -29,30 +29,30 @@ import type { HookProcessBaseInfo } from './injector';
* exactly today's behaviour, no worse.
*/
export interface ProcessEnumerator {
/** Resolve to the process list, or `null` (UNKNOWN) when enumeration timed
* out / failed and the caller should keep its prior state. */
enumerate(): Promise<HookProcessBaseInfo[] | null>;
dispose(): void;
/** Resolve to the process list, or `null` (UNKNOWN) when enumeration timed
* out / failed and the caller should keep its prior state. */
enumerate(): Promise<HookProcessBaseInfo[] | null>;
dispose(): void;
}
export interface NativeEnumeratorDeps {
/** Resolved path to the hook `.node` addon, or null when there is none
* (macOS / missing) — in which case we never spawn a worker. */
addonPath: string | null;
/** Synchronous lister used when worker isolation is unavailable. Returns
* today's value (and may itself block — that's the no-worse-than-before
* fallback). */
fallbackSync: () => HookProcessBaseInfo[];
/** Display name stamped on each returned process (e.g. 'qq' / 'QQ.exe'). */
processName: string;
/** Per-enumeration deadline. Default 4000ms — comfortably above a healthy
* enumeration (single-digit ms) but well under a human "is it dead?". */
timeoutMs?: number;
/** Cap on abandoned (blocked) workers before we stop spawning more and just
* return UNKNOWN until they drain. Bounds thread growth across a long
* hot-update window. Default 4. */
maxOrphans?: number;
log?: Logger;
/** Resolved path to the hook `.node` addon, or null when there is none
* (macOS / missing) — in which case we never spawn a worker. */
addonPath: string | null;
/** Synchronous lister used when worker isolation is unavailable. Returns
* today's value (and may itself block — that's the no-worse-than-before
* fallback). */
fallbackSync: () => HookProcessBaseInfo[];
/** Display name stamped on each returned process (e.g. 'qq' / 'QQ.exe'). */
processName: string;
/** Per-enumeration deadline. Default 4000ms — comfortably above a healthy
* enumeration (single-digit ms) but well under a human "is it dead?". */
timeoutMs?: number;
/** Cap on abandoned (blocked) workers before we stop spawning more and just
* return UNKNOWN until they drain. Bounds thread growth across a long
* hot-update window. Default 4. */
maxOrphans?: number;
log?: Logger;
}
const DEFAULT_TIMEOUT_MS = 4000;
@@ -87,152 +87,205 @@ if (addon) {
`;
function mapPids(pids: number[], processName: string): HookProcessBaseInfo[] {
return [...new Set(pids)]
.filter((pid) => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b)
.map((pid) => ({ pid, name: processName, path: '' }));
return [...new Set(pids)]
.filter((pid) => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b)
.map((pid) => ({ pid, name: processName, path: '' }));
}
export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): ProcessEnumerator {
const log = deps.log ?? createLogger('ProcessEnumerator');
const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS;
const log = deps.log ?? createLogger('ProcessEnumerator');
const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS;
// No addon to isolate (macOS / missing) → never spawn a worker; the sync
// fallback there is a cheap socket read, not a /proc walk.
if (!deps.addonPath) {
return {
async enumerate() {
try {
return deps.fallbackSync();
} catch (err) {
log.warn('enumerate fallback failed: %s', errMsg(err));
return null;
}
},
dispose() { /* nothing to tear down */ },
};
}
const addonPath = deps.addonPath;
let worker: Worker | null = null;
/** Set once we learn the addon can't load in a worker — permanent fallback. */
let isolationBroken = false;
let orphans = 0;
let seq = 0;
const pending = new Map<number, { resolve: (pids: number[] | null) => void }>();
let disposed = false;
const spawnWorker = (): void => {
const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } });
worker = w;
w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => {
if (msg.type === 'ready') return;
if (msg.type === 'fatal') {
// The addon won't load off-thread — give up on isolation for good and
// fall back to the synchronous path from here on. Resolve any in-flight
// request now (UNKNOWN) so it doesn't sit waiting for the timeout.
log.warn('process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration', msg.error ?? '');
isolationBroken = true;
for (const { resolve } of pending.values()) resolve(null);
pending.clear();
teardownWorker();
return;
}
if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') {
const entry = pending.get(msg.id);
if (!entry) return;
pending.delete(msg.id);
entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null);
}
});
w.on('error', (err) => {
log.warn('enumeration worker error: %s', errMsg(err));
if (worker === w) teardownWorker();
});
};
const teardownWorker = (): void => {
const w = worker;
worker = null;
if (!w) return;
// terminate() can't preempt a thread blocked in the native call; it takes
// effect once the call returns. Track it as an orphan until it actually
// exits so we can bound how many we let pile up.
orphans += 1;
w.once('exit', () => { orphans = Math.max(0, orphans - 1); });
void w.terminate().catch(() => { /* already gone */ });
};
const syncFallback = (): HookProcessBaseInfo[] | null => {
try {
return deps.fallbackSync();
} catch (err) {
log.warn('enumerate sync fallback failed: %s', errMsg(err));
return null;
// No addon to isolate (macOS / missing) → never spawn a worker; the sync
// fallback there is a cheap socket read, not a /proc walk.
if (!deps.addonPath) {
return {
async enumerate() {
try {
return deps.fallbackSync();
} catch (err) {
log.warn('enumerate fallback failed: %s', errMsg(err));
return null;
}
},
dispose() {
/* nothing to tear down */
},
};
}
};
return {
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
if (disposed || isolationBroken) return syncFallback();
const addonPath = deps.addonPath;
let worker: Worker | null = null;
/** Set once we learn the addon can't load in a worker — permanent fallback. */
let isolationBroken = false;
let orphans = 0;
let seq = 0;
const pending = new Map<number, { resolve: (pids: number[] | null) => void }>();
let disposed = false;
if (!worker) {
if (orphans >= maxOrphans) {
// Too many blocked workers already piling up (a sustained hang) —
// don't spawn more; report UNKNOWN and let them drain.
return null;
const spawnWorker = (): void => {
const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } });
worker = w;
w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => {
if (msg.type === 'ready') {
return;
}
if (msg.type === 'fatal') {
// The addon won't load off-thread — give up on isolation for good and
// fall back to the synchronous path from here on. Resolve any in-flight
// request now (UNKNOWN) so it doesn't sit waiting for the timeout.
log.warn(
'process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration',
msg.error ?? '',
);
isolationBroken = true;
for (const { resolve } of pending.values()) {
resolve(null);
}
pending.clear();
teardownWorker();
return;
}
if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') {
const entry = pending.get(msg.id);
if (!entry) {
return;
}
pending.delete(msg.id);
entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null);
}
});
w.on('error', (err) => {
log.warn('enumeration worker error: %s', errMsg(err));
if (worker === w) {
teardownWorker();
}
});
};
const teardownWorker = (): void => {
const w = worker;
worker = null;
if (!w) {
return;
}
spawnWorker();
}
const w = worker;
if (!w) return syncFallback();
const id = ++seq;
const resultPromise = new Promise<number[] | null>((resolve) => {
pending.set(id, { resolve });
});
try {
w.postMessage({ type: 'enumerate', id });
} catch (err) {
pending.delete(id);
log.warn('failed to post enumerate request: %s', errMsg(err));
teardownWorker();
return syncFallback();
}
// terminate() can't preempt a thread blocked in the native call; it takes
// effect once the call returns. Track it as an orphan until it actually
// exits so we can bound how many we let pile up.
orphans += 1;
w.once('exit', () => {
orphans = Math.max(0, orphans - 1);
});
void w.terminate().catch(() => {
/* already gone */
});
};
let timer: NodeJS.Timeout | undefined;
const timeout = new Promise<'timeout'>((resolve) => {
timer = setTimeout(() => resolve('timeout'), timeoutMs);
});
const outcome = await Promise.race([resultPromise, timeout]);
if (timer) clearTimeout(timer);
const syncFallback = (): HookProcessBaseInfo[] | null => {
try {
return deps.fallbackSync();
} catch (err) {
log.warn('enumerate sync fallback failed: %s', errMsg(err));
return null;
}
};
if (outcome === 'timeout') {
pending.delete(id);
log.warn('process enumeration timed out after %dms (worker abandoned) — keeping prior process set', timeoutMs);
teardownWorker();
return null;
}
if (outcome === null) {
// Native call threw inside the worker — treat as a transient failure,
// keep prior state rather than nuking every session.
return null;
}
return mapPids(outcome, deps.processName);
},
return {
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
if (disposed || isolationBroken) {
return syncFallback();
}
dispose() {
disposed = true;
for (const { resolve } of pending.values()) resolve(null);
pending.clear();
const w = worker;
worker = null;
if (w) void w.terminate().catch(() => { /* ignore */ });
},
};
if (!worker) {
if (orphans >= maxOrphans) {
// Too many blocked workers already piling up (a sustained hang) —
// don't spawn more; report UNKNOWN and let them drain.
return null;
}
spawnWorker();
}
const w = worker;
if (!w) {
return syncFallback();
}
const id = ++seq;
const resultPromise = new Promise<number[] | null>((resolve) => {
pending.set(id, { resolve });
});
try {
w.postMessage({ type: 'enumerate', id });
} catch (err) {
pending.delete(id);
log.warn('failed to post enumerate request: %s', errMsg(err));
teardownWorker();
return syncFallback();
}
let timer: NodeJS.Timeout | undefined;
const timeout = new Promise<'timeout'>((resolve) => {
timer = setTimeout(() => resolve('timeout'), timeoutMs);
});
const outcome = await Promise.race([resultPromise, timeout]);
if (timer) {
clearTimeout(timer);
}
if (outcome === 'timeout') {
pending.delete(id);
log.warn(
'process enumeration timed out after %dms (worker abandoned) — keeping prior process set',
timeoutMs,
);
teardownWorker();
return null;
}
if (outcome === null) {
// Native call threw inside the worker — treat as a transient failure,
// keep prior state rather than nuking every session.
return null;
}
return mapPids(outcome, deps.processName);
},
dispose() {
disposed = true;
for (const { resolve } of pending.values()) {
resolve(null);
}
pending.clear();
const w = worker;
worker = null;
if (w) {
void w.terminate().catch(() => {
/* ignore */
});
}
},
};
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
return value instanceof Error ? value.message : String(value);
}
File diff suppressed because it is too large. Load diff
+215 -167
View File
@@ -9,11 +9,15 @@ const log = createLogger('LoginProbe');
const probeNotes = new Map<number, string>();
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 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;
@@ -29,21 +33,21 @@ const EXEC_OPTIONS = { timeout: COMMAND_TIMEOUT_MS, killSignal: 'SIGKILL' as con
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;
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;
uin?: string | number;
account?: string | number;
nickname?: string;
}
/**
@@ -55,192 +59,236 @@ interface PtloginUin {
* problem, no answer" and should fall through to the deep-link fallback.
*/
async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin[] | null> {
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`;
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 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 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);
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);
req.on('error', () => resolve(null));
req.on('timeout', () => {
req.destroy();
resolve(null);
});
});
});
}
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallback'> {
const useHttps = port % 2 !== 0;
const useHttps = port % 2 !== 0;
const res1 = await fetchPtlogin(port, useHttps);
const res2 = await fetchPtlogin(port, useHttps);
const res1 = await fetchPtlogin(port, useHttps);
const res2 = await fetchPtlogin(port, useHttps);
if (res1 === null && res2 === null) return 'fallback';
if (res1 === null && res2 === null) {
return 'fallback';
}
const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null);
const target = usable.reduce((a, b) => (a.length <= b.length ? a : b));
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,
};
}
if (target.length === 1) {
const account = target[0];
return {
port,
uin: String(account.uin || account.account || ''),
nickName: account.nickname || '',
identityKnown: true,
};
}
return 'fallback';
return 'fallback';
}
async function getQqProcessCount(): Promise<number> {
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;
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;
}
} 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<number[] | null> {
try {
if (process.platform === 'win32') {
const { stdout } = await execAsync('netstat -ano', EXEC_OPTIONS);
const ports = new Set<number>();
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;
try {
if (process.platform === 'win32') {
const { stdout } = await execAsync('netstat -ano', EXEC_OPTIONS);
const ports = new Set<number>();
const lines = stdout.split('\n');
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<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]));
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<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]));
}
}
return Array.from(ports);
}
}
return Array.from(ports);
} catch {
return null;
}
} catch {
return null;
}
}
async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo | null> {
const ports = await getProcessPorts(pid);
if (ports === null) {
noteProbe(pid, 'unavailable', 0, null);
return null;
}
const ports = await getProcessPorts(pid);
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 };
if (ports === null) {
noteProbe(pid, 'unavailable', 0, null);
return null;
}
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));
if (ports.length === 0) {
const totalPids = await getQqProcessCount();
let ptPortsToTry: number[] = [];
if (matchedOddPorts.length > 0) {
ptPortsToTry = matchedOddPorts;
} else if (matchedEvenPorts.length > 0) {
ptPortsToTry = matchedEvenPorts;
}
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
noteProbe(pid, 'no-ports', 0, totalPids);
return { port: 0, uin: '', identityKnown: false };
}
if (ptPortsToTry.length > 0) {
for (const port of ptPortsToTry) {
const ptResult = await tryPtloginMethod(port);
if (ptResult !== 'fallback') {
return ptResult;
}
noteProbe(pid, 'inconclusive', 0, totalPids);
return null;
}
} else {
const totalPids = await getQqProcessCount();
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
noteProbe(pid, 'no-ports', ports.length, totalPids);
return {
port: ports[0] || 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;
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 !== 'fallback') {
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] || 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<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);
}
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);
}
}
}
+8 -14
View File
@@ -1,21 +1,15 @@
import type { HookProcessBaseInfo } from './injector';
export type HookProcessStatus =
| 'available'
| 'loading'
| 'connecting'
| 'loaded'
| 'online'
| 'error'
| 'disconnected';
'available' | 'loading' | 'connecting' | 'loaded' | 'online' | 'error' | 'disconnected';
/** Public-facing snapshot of a per-PID HookSession. */
export interface HookProcessInfo extends HookProcessBaseInfo {
injected: boolean;
connected: boolean;
loggedIn: boolean;
uin: string;
status: HookProcessStatus;
error: string;
method: string;
injected: boolean;
connected: boolean;
loggedIn: boolean;
uin: string;
status: HookProcessStatus;
error: string;
method: string;
}
@@ -13,203 +13,228 @@ import type { QqHookClient } from '../src/qq-hook-client';
// browser without REST polling.
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
const flush = () => new Promise<void>(r => setImmediate(r));
const flush = () => new Promise<void>((r) => setImmediate(r));
interface Harness {
manager: HookManager;
pipeWatcher: PipeWatcher;
bridgeManager: BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
setProcesses: (next: number[]) => void;
setLivePipes: (next: number[]) => void;
onSessionsChanged: ReturnType<typeof vi.fn>;
clientFactory: ReturnType<typeof vi.fn>;
manager: HookManager;
pipeWatcher: PipeWatcher;
bridgeManager: BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
setProcesses: (next: number[]) => void;
setLivePipes: (next: number[]) => void;
onSessionsChanged: ReturnType<typeof vi.fn>;
clientFactory: ReturnType<typeof vi.fn>;
}
function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}): Harness {
let pids = opts.processes ?? [];
let live = new Set<number>(opts.livePipes ?? []);
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
});
const clientFactory = vi.fn(() => {
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
(c as any).isClosed = false;
(c as any).isLoggedIn = false;
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
(c as any).connectAll = async () => { /* succeed without doing anything */ };
(c as any).close = () => { (c as any).isClosed = true; };
return c as unknown as QqHookClient;
});
const bridgeManager = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
onPidReceiveHealthChanged: vi.fn(),
} as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
const onSessionsChanged = vi.fn();
const manager = new HookManager({
bridgeManager,
pipeWatcher,
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: clientFactory,
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
onSessionsChanged,
});
return {
manager,
pipeWatcher,
bridgeManager,
onSessionsChanged,
clientFactory,
setProcesses: (next) => { pids = next; },
setLivePipes: (next) => { live = new Set(next); },
};
}
describe('HookManager.onSessionsChanged', () => {
it('fires when the watcher discovers a new QQ process', async () => {
const ctx = makeManager({ processes: [] });
await ctx.pipeWatcher.start();
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
ctx.setProcesses([4242]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('fires when the watcher reports a process is gone', async () => {
const ctx = makeManager({ processes: [4242] });
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
ctx.setProcesses([]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('fires when the watcher reports the pipe came up (status: connecting → loaded)', async () => {
const ctx = makeManager({ processes: [4242] });
await ctx.pipeWatcher.start();
await flush();
// Inject so the session is in 'connecting' state; the next pipe-up
// makes attemptConnect succeed and status flips to 'loaded'.
await ctx.manager.loadProcess(4242);
await flush();
ctx.onSessionsChanged.mockClear();
ctx.setLivePipes([4242]);
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => {
const ctx = makeManager({ processes: [] });
ctx.onSessionsChanged.mockImplementation(() => { throw new Error('listener boom'); });
await ctx.pipeWatcher.start();
ctx.setProcesses([4242]);
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
await flush();
// A second tick still fires the callback — it wasn't unregistered by
// the prior throw.
ctx.onSessionsChanged.mockClear();
ctx.setProcesses([4242, 5555]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('is OPTIONAL — omitting it leaves the manager fully functional', async () => {
const pids = [4242];
let pids = opts.processes ?? [];
let live = new Set<number>(opts.livePipes ?? []);
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(),
intervalMs: 60_000,
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
});
const manager = new HookManager({
bridgeManager: {
const clientFactory = vi.fn(() => {
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
(c as any).isClosed = false;
(c as any).isLoggedIn = false;
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
(c as any).connectAll = async () => {
/* succeed without doing anything */
};
(c as any).close = () => {
(c as any).isClosed = true;
};
return c as unknown as QqHookClient;
});
const bridgeManager = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManagerSink,
pipeWatcher,
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: vi.fn(() => {
const c = new EventEmitter() as any;
c.isClosed = false; c.isLoggedIn = false;
c.getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
c.connectAll = async () => undefined;
c.close = () => { c.isClosed = true; };
return c;
}),
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
// onSessionsChanged deliberately omitted
onPidReceiveHealthChanged: vi.fn(),
} as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
const onSessionsChanged = vi.fn();
const manager = new HookManager({
bridgeManager,
pipeWatcher,
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: clientFactory,
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
onSessionsChanged,
});
return {
manager,
pipeWatcher,
bridgeManager,
onSessionsChanged,
clientFactory,
setProcesses: (next) => {
pids = next;
},
setLivePipes: (next) => {
live = new Set(next);
},
};
}
describe('HookManager.onSessionsChanged', () => {
it('fires when the watcher discovers a new QQ process', async () => {
const ctx = makeManager({ processes: [] });
await ctx.pipeWatcher.start();
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
ctx.setProcesses([4242]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('fires when the watcher reports a process is gone', async () => {
const ctx = makeManager({ processes: [4242] });
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
ctx.setProcesses([]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('fires when the watcher reports the pipe came up (status: connecting → loaded)', async () => {
const ctx = makeManager({ processes: [4242] });
await ctx.pipeWatcher.start();
await flush();
// Inject so the session is in 'connecting' state; the next pipe-up
// makes attemptConnect succeed and status flips to 'loaded'.
await ctx.manager.loadProcess(4242);
await flush();
ctx.onSessionsChanged.mockClear();
ctx.setLivePipes([4242]);
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => {
const ctx = makeManager({ processes: [] });
ctx.onSessionsChanged.mockImplementation(() => {
throw new Error('listener boom');
});
await ctx.pipeWatcher.start();
ctx.setProcesses([4242]);
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
await flush();
// A second tick still fires the callback — it wasn't unregistered by
// the prior throw.
ctx.onSessionsChanged.mockClear();
ctx.setProcesses([4242, 5555]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
ctx.manager.dispose();
});
it('is OPTIONAL — omitting it leaves the manager fully functional', async () => {
const pids = [4242];
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(),
intervalMs: 60_000,
});
const manager = new HookManager({
bridgeManager: {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManagerSink,
pipeWatcher,
injector: {
inject: vi.fn(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(),
},
makeClient: vi.fn(() => {
const c = new EventEmitter() as any;
c.isClosed = false;
c.isLoggedIn = false;
c.getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
c.connectAll = async () => undefined;
c.close = () => {
c.isClosed = true;
};
return c;
}),
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
// onSessionsChanged deliberately omitted
});
await pipeWatcher.start();
await pipeWatcher.tickNow();
await flush();
const list = await manager.listProcesses();
expect(list).toHaveLength(1);
expect(list[0].pid).toBe(4242);
manager.dispose();
});
await pipeWatcher.start();
await pipeWatcher.tickNow();
await flush();
const list = await manager.listProcesses();
expect(list).toHaveLength(1);
expect(list[0].pid).toBe(4242);
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] });
await ctx.pipeWatcher.start();
await ctx.manager.loadProcess(4242);
await ctx.manager.refreshProcess(4242);
await flush();
it('forwards stale and recovered receive health for the owning PID', async () => {
const ctx = makeManager({ processes: [4242], livePipes: [4242] });
await ctx.pipeWatcher.start();
await ctx.manager.loadProcess(4242);
await ctx.manager.refreshProcess(4242);
await flush();
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
try {
client.emit('packet', {
seq: 1,
error: 0,
cmd: 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat',
uin: '10001',
body: Buffer.alloc(0),
});
vi.advanceTimersByTime(105_000);
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenCalledWith(4242, false);
try {
client.emit('packet', {
seq: 1,
error: 0,
cmd: 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat',
uin: '10001',
body: Buffer.alloc(0),
});
vi.advanceTimersByTime(105_000);
client.emit('packet', {
seq: 2,
error: 0,
cmd: 'trpc.msg.olpush.OlPushService.MsgPush',
uin: '10001',
body: Buffer.alloc(0),
});
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenLastCalledWith(4242, true);
} finally {
vi.useRealTimers();
ctx.manager.dispose();
}
});
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenCalledWith(4242, false);
client.emit('packet', {
seq: 2,
error: 0,
cmd: 'trpc.msg.olpush.OlPushService.MsgPush',
uin: '10001',
body: Buffer.alloc(0),
});
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenLastCalledWith(
4242,
true,
);
} finally {
vi.useRealTimers();
ctx.manager.dispose();
}
});
});
+408 -365
View File
@@ -9,420 +9,463 @@ import type { HookInjectResult, ManualMapHandle } from '../src/injector';
import type { BridgeManagerSink } from '../src/hook-manager';
import type { QqHookClient } from '../src/qq-hook-client';
import {
createLogger,
getLogLevel,
setLogLevel,
subscribeLogs,
type LogEntry,
createLogger,
getLogLevel,
setLogLevel,
subscribeLogs,
type LogEntry,
} from '@snowluma/common/logger';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
const flush = () => new Promise<void>(r => setImmediate(r));
const flush = () => new Promise<void>((r) => setImmediate(r));
const previousLogLevel = getLogLevel();
function managerTrace(entries: LogEntry[]): LogEntry[] {
return entries.filter(
(entry) => entry.level === 'trace' && entry.scope === 'Hook',
);
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Hook');
}
function makeManager(opts: {
autoLoadOnDiscovery?: boolean;
processes?: number[];
onSessionsChanged?: () => void;
inject?: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
autoLoadOnDiscovery?: boolean;
processes?: number[];
onSessionsChanged?: () => void;
inject?: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
}) {
let pids = opts.processes ?? [];
const live = new Set<number>();
const inject = vi.fn(opts.inject ?? (() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})));
const unload = vi.fn();
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live),
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
});
// FakeClient — never connected; just needs to satisfy EventEmitter +
// a minimal subset of QqHookClient for HookSession.tearDownClient().
const makeClient = vi.fn(() => {
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
(c as any).isClosed = false;
(c as any).isLoggedIn = false;
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
(c as any).connectAll = async () => { throw new Error('test: never really connect'); };
(c as any).close = () => { (c as any).isClosed = true; };
return c as unknown as QqHookClient;
});
const bridgeManager = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManagerSink;
const manager = new HookManager({
bridgeManager,
pipeWatcher,
injector: { inject, unload },
makeClient,
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
onSessionsChanged: opts.onSessionsChanged,
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
});
return {
manager,
inject,
pipeWatcher,
setProcesses: (next: number[]) => { pids = next; },
};
let pids = opts.processes ?? [];
const live = new Set<number>();
const inject = vi.fn(
opts.inject ??
(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
);
const unload = vi.fn();
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live),
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
});
// FakeClient — never connected; just needs to satisfy EventEmitter +
// a minimal subset of QqHookClient for HookSession.tearDownClient().
const makeClient = vi.fn(() => {
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
(c as any).isClosed = false;
(c as any).isLoggedIn = false;
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
(c as any).connectAll = async () => {
throw new Error('test: never really connect');
};
(c as any).close = () => {
(c as any).isClosed = true;
};
return c as unknown as QqHookClient;
});
const bridgeManager = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManagerSink;
const manager = new HookManager({
bridgeManager,
pipeWatcher,
injector: { inject, unload },
makeClient,
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
onSessionsChanged: opts.onSessionsChanged,
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
});
return {
manager,
inject,
pipeWatcher,
setProcesses: (next: number[]) => {
pids = next;
},
};
}
afterEach(() => {
setLogLevel(previousLogLevel);
setLogLevel(previousLogLevel);
});
describe('HookManager runtime TRACE', () => {
it('records discovery and process-gone facts while unchanged ticks stay silent', async () => {
const entries: LogEntry[] = [];
const sessionsChanged = vi.fn();
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({
autoLoadOnDiscovery: false,
processes: [],
onSessionsChanged: sessionsChanged,
it('records discovery and process-gone facts while unchanged ticks stay silent', async () => {
const entries: LogEntry[] = [];
const sessionsChanged = vi.fn();
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({
autoLoadOnDiscovery: false,
processes: [],
onSessionsChanged: sessionsChanged,
});
try {
await ctx.pipeWatcher.start();
const baseline = managerTrace(entries).length;
await ctx.pipeWatcher.tickNow();
await ctx.pipeWatcher.tickNow();
expect(managerTrace(entries)).toHaveLength(baseline);
ctx.setProcesses([4242]);
await ctx.pipeWatcher.tickNow();
ctx.setProcesses([]);
await ctx.pipeWatcher.tickNow();
await flush();
const facts = managerTrace(entries).filter((entry) =>
entry.message.startsWith('hook_manager_fact '),
);
expect(facts.map((entry) => entry.message)).toEqual([
expect.stringContaining('hook_manager_fact event=process_discovered pid=4242'),
'hook_manager_fact event=process_gone pid=4242 tracked=true',
]);
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
try {
await ctx.pipeWatcher.start();
const baseline = managerTrace(entries).length;
await ctx.pipeWatcher.tickNow();
await ctx.pipeWatcher.tickNow();
expect(managerTrace(entries)).toHaveLength(baseline);
ctx.setProcesses([4242]);
await ctx.pipeWatcher.tickNow();
ctx.setProcesses([]);
await ctx.pipeWatcher.tickNow();
await flush();
it('records bounded transient retries and recovery as separate attempts', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject
.mockImplementationOnce(() => {
throw new Error(
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
);
})
.mockImplementationOnce(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
}));
const facts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_manager_fact '),
);
expect(facts.map((entry) => entry.message)).toEqual([
expect.stringContaining('hook_manager_fact event=process_discovered pid=4242'),
'hook_manager_fact event=process_gone pid=4242 tracked=true',
]);
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
try {
await ctx.pipeWatcher.start();
await flush();
await flush();
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
it('records bounded transient retries and recovery as separate attempts', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject
.mockImplementationOnce(() => {
throw new Error(
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
);
})
.mockImplementationOnce(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
}));
try {
await ctx.pipeWatcher.start();
await flush();
await flush();
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
const attempts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_'),
);
expect(attempts.map((entry) => entry.message)).toEqual([
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=1 outcome=failed reason=retry_pending error=.*elapsedMs=\d+$/),
'hook_autoload_start pid=4242 attempt=2 maxAttempts=3',
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=2 outcome=completed reason=recovered state=.*elapsedMs=\d+$/),
]);
expect(attempts[0]!.req).toBe(attempts[1]!.req);
expect(attempts[2]!.req).toBe(attempts[3]!.req);
expect(attempts[0]!.req).not.toBe(attempts[2]!.req);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
it('ends an in-flight auto-load as dropped when a manual load supersedes it', async () => {
const entries: LogEntry[] = [];
let resolveInjection!: (result: HookInjectResult) => void;
const injection = new Promise<HookInjectResult>((resolve) => {
resolveInjection = resolve;
const attempts = managerTrace(entries).filter((entry) =>
entry.message.startsWith('hook_autoload_'),
);
expect(attempts.map((entry) => entry.message)).toEqual([
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
expect.stringMatching(
/^hook_autoload_terminal pid=4242 attempt=1 outcome=failed reason=retry_pending error=.*elapsedMs=\d+$/,
),
'hook_autoload_start pid=4242 attempt=2 maxAttempts=3',
expect.stringMatching(
/^hook_autoload_terminal pid=4242 attempt=2 outcome=completed reason=recovered state=.*elapsedMs=\d+$/,
),
]);
expect(attempts[0]!.req).toBe(attempts[1]!.req);
expect(attempts[2]!.req).toBe(attempts[3]!.req);
expect(attempts[0]!.req).not.toBe(attempts[2]!.req);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({
autoLoadOnDiscovery: true,
processes: [4242],
inject: () => injection,
it('ends an in-flight auto-load as dropped when a manual load supersedes it', async () => {
const entries: LogEntry[] = [];
let resolveInjection!: (result: HookInjectResult) => void;
const injection = new Promise<HookInjectResult>((resolve) => {
resolveInjection = resolve;
});
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({
autoLoadOnDiscovery: true,
processes: [4242],
inject: () => injection,
});
try {
await ctx.pipeWatcher.start();
await flush();
const manualLoad = ctx.manager.loadProcess(4242);
resolveInjection({ method: 'loadModuleManual', handle: DUMMY_HANDLE });
await manualLoad;
await flush();
const attempts = managerTrace(entries).filter((entry) =>
entry.message.startsWith('hook_autoload_'),
);
expect(attempts.map((entry) => entry.message)).toEqual([
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
expect.stringMatching(
/^hook_autoload_terminal pid=4242 attempt=1 outcome=dropped reason=superseded elapsedMs=\d+$/,
),
]);
expect(attempts[0]!.req).toBe(attempts[1]!.req);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
try {
await ctx.pipeWatcher.start();
await flush();
const manualLoad = ctx.manager.loadProcess(4242);
resolveInjection({ method: 'loadModuleManual', handle: DUMMY_HANDLE });
await manualLoad;
await flush();
const attempts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_'),
);
expect(attempts.map((entry) => entry.message)).toEqual([
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
expect.stringMatching(
/^hook_autoload_terminal pid=4242 attempt=1 outcome=dropped reason=superseded elapsedMs=\d+$/,
),
]);
expect(attempts[0]!.req).toBe(attempts[1]!.req);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
it.each([
{
name: 'permanent failure',
error: 'ptrace denied',
ticks: 1,
attempts: 1,
reason: 'permanent_failure',
},
{
name: 'retry exhaustion',
error: 'target process does not map /lib/libc.so.6 while resolving mmap',
ticks: 4,
attempts: 3,
reason: 'retry_exhausted',
},
])('records $name terminal', async ({ error, ticks, attempts, reason }) => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementation(() => {
throw new Error(error);
});
it.each([
{
name: 'permanent failure',
error: 'ptrace denied',
ticks: 1,
attempts: 1,
reason: 'permanent_failure',
},
{
name: 'retry exhaustion',
error: 'target process does not map /lib/libc.so.6 while resolving mmap',
ticks: 4,
attempts: 3,
reason: 'retry_exhausted',
},
])('records $name terminal', async ({ error, ticks, attempts, reason }) => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementation(() => { throw new Error(error); });
try {
await ctx.pipeWatcher.start();
await flush();
await flush();
for (let tick = 0; tick < ticks; tick += 1) {
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
}
try {
await ctx.pipeWatcher.start();
await flush();
await flush();
const starts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_start '),
);
const terminals = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_terminal '),
);
expect(starts).toHaveLength(attempts);
expect(terminals).toHaveLength(attempts);
expect(terminals.at(-1)!.message).toContain(`reason=${reason}`);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
for (let tick = 0; tick < ticks; tick += 1) {
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
}
const starts = managerTrace(entries).filter((entry) =>
entry.message.startsWith('hook_autoload_start '),
);
const terminals = managerTrace(entries).filter((entry) =>
entry.message.startsWith('hook_autoload_terminal '),
);
expect(starts).toHaveLength(attempts);
expect(terminals).toHaveLength(attempts);
expect(terminals.at(-1)!.message).toContain(`reason=${reason}`);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
});
describe('HookManager.autoLoadOnDiscovery', () => {
it('does NOT inject on process-discovered when flag is off', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
await ctx.pipeWatcher.start();
await flush();
expect(ctx.inject).not.toHaveBeenCalled();
ctx.manager.dispose();
});
it('injects every newly-discovered PID when flag is on', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
await ctx.pipeWatcher.start();
// session.load() is queued via a per-session promise chain; flush twice
// so the auto-load runs to completion before we assert.
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(1);
expect(ctx.inject).toHaveBeenCalledWith(4242);
// A second PID appearing mid-flight should also trigger an inject.
ctx.setProcesses([4242, 9999]);
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(2);
expect(ctx.inject).toHaveBeenLastCalledWith(9999);
ctx.manager.dispose();
});
it('swallows inject errors so the watcher keeps running', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementationOnce(() => { throw new Error('ptrace denied'); });
await ctx.pipeWatcher.start();
await flush();
await flush();
// Second PID should still be auto-loaded — the failure on 4242 must
// not leak out of the listener and break the watcher's emit loop.
ctx.setProcesses([4242, 9999]);
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(2);
ctx.manager.dispose();
});
it('retries a transient libc mapping failure on the next watcher tick', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementationOnce(() => {
throw new Error(
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
);
it('does NOT inject on process-discovered when flag is off', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
await ctx.pipeWatcher.start();
await flush();
expect(ctx.inject).not.toHaveBeenCalled();
ctx.manager.dispose();
});
await ctx.pipeWatcher.start();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(1);
it('injects every newly-discovered PID when flag is on', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
await ctx.pipeWatcher.start();
// session.load() is queued via a per-session promise chain; flush twice
// so the auto-load runs to completion before we assert.
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(1);
expect(ctx.inject).toHaveBeenCalledWith(4242);
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(2);
expect(ctx.inject).toHaveBeenLastCalledWith(4242);
// A second PID appearing mid-flight should also trigger an inject.
ctx.setProcesses([4242, 9999]);
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(2);
expect(ctx.inject).toHaveBeenLastCalledWith(9999);
ctx.manager.dispose();
});
it('does not retry permanent auto-load errors', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementation(() => { throw new Error('ptrace denied'); });
await ctx.pipeWatcher.start();
await flush();
await flush();
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(1);
ctx.manager.dispose();
});
it('stops retrying a transient libc mapping failure after three attempts', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementation(() => {
throw new Error(
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
);
ctx.manager.dispose();
});
await ctx.pipeWatcher.start();
await flush();
await flush();
it('swallows inject errors so the watcher keeps running', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementationOnce(() => {
throw new Error('ptrace denied');
});
await ctx.pipeWatcher.start();
await flush();
await flush();
for (let tick = 0; tick < 4; tick += 1) {
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
}
expect(ctx.inject).toHaveBeenCalledTimes(3);
// Second PID should still be auto-loaded — the failure on 4242 must
// not leak out of the listener and break the watcher's emit loop.
ctx.setProcesses([4242, 9999]);
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(2);
ctx.manager.dispose();
});
ctx.manager.dispose();
});
it('retries a transient libc mapping failure on the next watcher tick', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementationOnce(() => {
throw new Error(
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
);
});
await ctx.pipeWatcher.start();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(1);
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(2);
expect(ctx.inject).toHaveBeenLastCalledWith(4242);
ctx.manager.dispose();
});
it('does not retry permanent auto-load errors', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementation(() => {
throw new Error('ptrace denied');
});
await ctx.pipeWatcher.start();
await flush();
await flush();
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.inject).toHaveBeenCalledTimes(1);
ctx.manager.dispose();
});
it('stops retrying a transient libc mapping failure after three attempts', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementation(() => {
throw new Error(
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
);
});
await ctx.pipeWatcher.start();
await flush();
await flush();
for (let tick = 0; tick < 4; tick += 1) {
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
}
expect(ctx.inject).toHaveBeenCalledTimes(3);
ctx.manager.dispose();
});
});
// `shouldAutoLoadPid` reads /proc/<pid>/cmdline directly, so we point
// it at a temporary directory that mimics the procfs layout. This lets
// the tests run on macOS / CI without a live Linux QQ process.
describe('shouldAutoLoadPid', () => {
let tmpProc: string;
const originalReadFileSync = fs.readFileSync;
const log = createLogger('test');
const originalPlatform = process.platform;
const originalAutoLoadAll = process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
let tmpProc: string;
const originalReadFileSync = fs.readFileSync;
const log = createLogger('test');
const originalPlatform = process.platform;
const originalAutoLoadAll = process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
beforeEach(() => {
tmpProc = fs.mkdtempSync(path.join(os.tmpdir(), 'hookmgr-proc-'));
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
// Redirect readFileSync('/proc/<pid>/cmdline') to the tmp dir.
(fs.readFileSync as unknown as typeof fs.readFileSync) = ((p: string, ...rest: unknown[]) => {
const match = /^\/proc\/(\d+)\/cmdline$/.exec(p);
if (match) {
return originalReadFileSync(path.join(tmpProc, match[1], 'cmdline'), ...(rest as [BufferEncoding]));
}
return originalReadFileSync(p, ...(rest as [BufferEncoding]));
}) as typeof fs.readFileSync;
});
beforeEach(() => {
tmpProc = fs.mkdtempSync(path.join(os.tmpdir(), 'hookmgr-proc-'));
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
// Redirect readFileSync('/proc/<pid>/cmdline') to the tmp dir.
(fs.readFileSync as unknown as typeof fs.readFileSync) = ((
p: string,
...rest: unknown[]
) => {
const match = /^\/proc\/(\d+)\/cmdline$/.exec(p);
afterEach(() => {
(fs.readFileSync as unknown as typeof fs.readFileSync) = originalReadFileSync;
Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
if (originalAutoLoadAll === undefined) delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
else process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll;
fs.rmSync(tmpProc, { recursive: true, force: true });
});
if (match) {
return originalReadFileSync(
path.join(tmpProc, match[1], 'cmdline'),
...(rest as [BufferEncoding]),
);
}
function writeCmdline(pid: number, args: string[]): void {
const dir = path.join(tmpProc, String(pid));
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'cmdline'), args.join('\0') + '\0');
}
return originalReadFileSync(p, ...(rest as [BufferEncoding]));
}) as typeof fs.readFileSync;
});
it('allows the QQ main process (no --type=)', () => {
writeCmdline(50, ['qq', '--no-sandbox']);
expect(shouldAutoLoadPid(50, log)).toBe(true);
});
afterEach(() => {
(fs.readFileSync as unknown as typeof fs.readFileSync) = originalReadFileSync;
Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
it('rejects Electron zygotes', () => {
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote', '--no-zygote-sandbox', '--no-sandbox']);
expect(shouldAutoLoadPid(59, log)).toBe(false);
});
if (originalAutoLoadAll === undefined) {
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
} else {
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll;
}
it('rejects renderer/gpu/utility children', () => {
writeCmdline(70, ['/opt/QQ/qq', '--type=renderer']);
writeCmdline(71, ['/opt/QQ/qq', '--type=gpu-process']);
writeCmdline(72, ['/opt/QQ/qq', '--type=utility', '--utility-sub-type=network.mojom.NetworkService']);
expect(shouldAutoLoadPid(70, log)).toBe(false);
expect(shouldAutoLoadPid(71, log)).toBe(false);
expect(shouldAutoLoadPid(72, log)).toBe(false);
});
fs.rmSync(tmpProc, { recursive: true, force: true });
});
it('allows everything if SNOWLUMA_HOOK_AUTOLOAD_ALL=1 (escape hatch)', () => {
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote']);
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = '1';
expect(shouldAutoLoadPid(59, log)).toBe(true);
});
function writeCmdline(pid: number, args: string[]): void {
const dir = path.join(tmpProc, String(pid));
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'cmdline'), args.join('\0') + '\0');
}
it('allows on non-linux platforms (filter is a Linux-only workaround)', () => {
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
// No cmdline file needed — we return true before touching procfs.
expect(shouldAutoLoadPid(59, log)).toBe(true);
});
it('allows the QQ main process (no --type=)', () => {
writeCmdline(50, ['qq', '--no-sandbox']);
expect(shouldAutoLoadPid(50, log)).toBe(true);
});
it('allows when /proc is unreadable (dead PID, permission issue)', () => {
expect(shouldAutoLoadPid(99999, log)).toBe(true);
});
it('rejects Electron zygotes', () => {
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote', '--no-zygote-sandbox', '--no-sandbox']);
expect(shouldAutoLoadPid(59, log)).toBe(false);
});
it('rejects renderer/gpu/utility children', () => {
writeCmdline(70, ['/opt/QQ/qq', '--type=renderer']);
writeCmdline(71, ['/opt/QQ/qq', '--type=gpu-process']);
writeCmdline(72, [
'/opt/QQ/qq',
'--type=utility',
'--utility-sub-type=network.mojom.NetworkService',
]);
expect(shouldAutoLoadPid(70, log)).toBe(false);
expect(shouldAutoLoadPid(71, log)).toBe(false);
expect(shouldAutoLoadPid(72, log)).toBe(false);
});
it('allows everything if SNOWLUMA_HOOK_AUTOLOAD_ALL=1 (escape hatch)', () => {
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote']);
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = '1';
expect(shouldAutoLoadPid(59, log)).toBe(true);
});
it('allows on non-linux platforms (filter is a Linux-only workaround)', () => {
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
// No cmdline file needed — we return true before touching procfs.
expect(shouldAutoLoadPid(59, log)).toBe(true);
});
it('allows when /proc is unreadable (dead PID, permission issue)', () => {
expect(shouldAutoLoadPid(99999, log)).toBe(true);
});
});
@@ -1,60 +1,70 @@
import { describe, expect, it, vi } from 'vitest';
import { HookPacketClient } from '../src/hook-packet-client';
import {
HookPipeRequestError,
PIPE_STATUS_CONNECTION_UNAVAILABLE,
type QqHookClient,
HookPipeRequestError,
PIPE_STATUS_CONNECTION_UNAVAILABLE,
type QqHookClient,
} from '../src/qq-hook-client';
function fakeClient(send: QqHookClient['send']): QqHookClient {
return {
isLoggedIn: true,
send,
} as unknown as QqHookClient;
return {
isLoggedIn: true,
send,
} as unknown as QqHookClient;
}
describe('HookPacketClient outbound health', () => {
it('reports native connection loss once and recovers after a successful request', async () => {
const healthChanged = vi.fn();
const send = vi
.fn<QqHookClient['send']>()
.mockRejectedValueOnce(new HookPipeRequestError(
'The QQ connection changed. Please restart QQ and try again.',
PIPE_STATUS_CONNECTION_UNAVAILABLE,
1,
))
.mockRejectedValueOnce(new HookPipeRequestError(
'The QQ connection changed. Please restart QQ and try again.',
PIPE_STATUS_CONNECTION_UNAVAILABLE,
2,
))
.mockResolvedValueOnce({
requestId: 3,
error: 0,
message: '',
body: Buffer.from('ok'),
});
const sender = new HookPacketClient(fakeClient(send), healthChanged);
it('reports native connection loss once and recovers after a successful request', async () => {
const healthChanged = vi.fn();
const send = vi
.fn<QqHookClient['send']>()
.mockRejectedValueOnce(
new HookPipeRequestError(
'The QQ connection changed. Please restart QQ and try again.',
PIPE_STATUS_CONNECTION_UNAVAILABLE,
1,
),
)
.mockRejectedValueOnce(
new HookPipeRequestError(
'The QQ connection changed. Please restart QQ and try again.',
PIPE_STATUS_CONNECTION_UNAVAILABLE,
2,
),
)
.mockResolvedValueOnce({
requestId: 3,
error: 0,
message: '',
body: Buffer.from('ok'),
});
const sender = new HookPacketClient(fakeClient(send), healthChanged);
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
.resolves.toMatchObject({ success: false, gotResponse: false });
await sender.sendPacket('Test.Command', Buffer.alloc(0));
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
.resolves.toMatchObject({ success: true, gotResponse: true });
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({
success: false,
gotResponse: false,
});
await sender.sendPacket('Test.Command', Buffer.alloc(0));
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({
success: true,
gotResponse: true,
});
expect(healthChanged.mock.calls).toEqual([[false], [true]]);
});
expect(healthChanged.mock.calls).toEqual([[false], [true]]);
});
it('does not classify ordinary request rejection as connection loss', async () => {
const healthChanged = vi.fn();
const send = vi.fn<QqHookClient['send']>().mockRejectedValue(
new HookPipeRequestError('This request is not valid.', -38, 1),
);
const sender = new HookPacketClient(fakeClient(send), healthChanged);
it('does not classify ordinary request rejection as connection loss', async () => {
const healthChanged = vi.fn();
const send = vi
.fn<QqHookClient['send']>()
.mockRejectedValue(new HookPipeRequestError('This request is not valid.', -38, 1));
const sender = new HookPacketClient(fakeClient(send), healthChanged);
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
.resolves.toMatchObject({ success: false, gotResponse: false });
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({
success: false,
gotResponse: false,
});
expect(healthChanged).not.toHaveBeenCalled();
});
expect(healthChanged).not.toHaveBeenCalled();
});
});
@@ -13,87 +13,101 @@ import type { BridgeManagerSink } from '../src/hook-manager';
import type { QqHookClient } from '../src/qq-hook-client';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
const flush = () => new Promise<void>(r => setImmediate(r));
const flush = () => new Promise<void>((r) => setImmediate(r));
class FakeClient extends EventEmitter {
isClosed = false;
isLoggedIn = false;
async connectAll(_opts: { recv: boolean }) {
if (this.isClosed) throw new Error('client is closed');
}
getLoginState() { return { loggedIn: false, uin: '0', uinNumber: 0n }; }
close() {
if (this.isClosed) return;
this.isClosed = true;
this.emit('close');
}
isClosed = false;
isLoggedIn = false;
async connectAll(_opts: { recv: boolean }) {
if (this.isClosed) {
throw new Error('client is closed');
}
}
getLoginState() {
return { loggedIn: false, uin: '0', uinNumber: 0n };
}
close() {
if (this.isClosed) {
return;
}
this.isClosed = true;
this.emit('close');
}
}
describe('HookManager — Docker reconnect-without-login leak guard', () => {
it('after N pipe up/down cycles: no Bridge calls, no client accumulation', async () => {
const PID = 61;
const liveSet = new Set<number>([PID]);
const clients: FakeClient[] = [];
it('after N pipe up/down cycles: no Bridge calls, no client accumulation', async () => {
const PID = 61;
const liveSet = new Set<number>([PID]);
const clients: FakeClient[] = [];
const pipeWatcher = new PipeWatcher({
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
listLivePipes: async () => new Set(liveSet),
intervalMs: 60_000, // manual ticks only
const pipeWatcher = new PipeWatcher({
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
listLivePipes: async () => new Set(liveSet),
intervalMs: 60_000, // manual ticks only
});
const bridgeManager = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManagerSink;
const manager = new HookManager({
bridgeManager,
pipeWatcher,
injector: {
inject: vi.fn(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(),
},
makeClient: () => {
const c = new FakeClient();
clients.push(c);
return c as unknown as QqHookClient;
},
autoLoadOnDiscovery: true,
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
});
// Initial discovery + first connect.
await pipeWatcher.start();
await flush();
await flush();
// Drive 50 pipe up/down cycles with the QQ process staying alive but
// the pipe (= QQ control socket) bouncing every "tick".
const CYCLES = 50;
for (let i = 0; i < CYCLES; i++) {
liveSet.delete(PID);
await pipeWatcher.tickNow();
await flush();
liveSet.add(PID);
await pipeWatcher.tickNow();
await flush();
}
// The "QQ never logs in" hypothesis: BridgeManager should never have
// been told about a login or a disconnect.
expect(bridgeManager.onHookLogin).not.toHaveBeenCalled();
expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled();
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
// Hook layer should hold at most one live client.
const alive = clients.filter((c) => !c.isClosed);
expect(
alive.length,
`live clients after ${CYCLES} cycles: ${alive.length}`,
).toBeLessThanOrEqual(1);
// Total clients minted = roughly one per up cycle. Sanity bound:
// we must have actually exercised the reconnect path.
expect(clients.length).toBeGreaterThan(1);
manager.dispose();
});
const bridgeManager = {
onPacket: vi.fn(),
onHookLogin: vi.fn(),
onPidDisconnected: vi.fn(),
} as unknown as BridgeManagerSink;
const manager = new HookManager({
bridgeManager,
pipeWatcher,
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: () => {
const c = new FakeClient();
clients.push(c);
return c as unknown as QqHookClient;
},
autoLoadOnDiscovery: true,
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
});
// Initial discovery + first connect.
await pipeWatcher.start();
await flush();
await flush();
// Drive 50 pipe up/down cycles with the QQ process staying alive but
// the pipe (= QQ control socket) bouncing every "tick".
const CYCLES = 50;
for (let i = 0; i < CYCLES; i++) {
liveSet.delete(PID);
await pipeWatcher.tickNow();
await flush();
liveSet.add(PID);
await pipeWatcher.tickNow();
await flush();
}
// The "QQ never logs in" hypothesis: BridgeManager should never have
// been told about a login or a disconnect.
expect(bridgeManager.onHookLogin).not.toHaveBeenCalled();
expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled();
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
// Hook layer should hold at most one live client.
const alive = clients.filter(c => !c.isClosed);
expect(alive.length, `live clients after ${CYCLES} cycles: ${alive.length}`).toBeLessThanOrEqual(1);
// Total clients minted = roughly one per up cycle. Sanity bound:
// we must have actually exercised the reconnect path.
expect(clients.length).toBeGreaterThan(1);
manager.dispose();
});
});
@@ -24,100 +24,119 @@ import type { QqHookClient } from '../src/qq-hook-client';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
class FakeClient extends EventEmitter {
isClosed = false;
isLoggedIn = false;
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
isClosed = false;
isLoggedIn = false;
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
async connectAll(_opts: { recv: boolean }): Promise<void> {
if (this.isClosed) throw new Error('client is closed');
}
getLoginState() { return { ...this.loginState }; }
close(): void {
if (this.isClosed) return;
this.isClosed = true;
this.emit('close');
}
async connectAll(_opts: { recv: boolean }): Promise<void> {
if (this.isClosed) {
throw new Error('client is closed');
}
}
getLoginState() {
return { ...this.loginState };
}
close(): void {
if (this.isClosed) {
return;
}
this.isClosed = true;
this.emit('close');
}
}
function totalListenerCount(emitter: EventEmitter): number {
return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0);
return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0);
}
const flush = () => new Promise<void>(r => setImmediate(r));
const flush = () => new Promise<void>((r) => setImmediate(r));
describe('HookSession — pipe reconnect with QQ never logging in', () => {
it('does not accumulate live FakeClient instances across N pipe up/down cycles', async () => {
let pipeLive = true;
const clients: FakeClient[] = [];
const session = new HookSession(61, {
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: () => {
const c = new FakeClient();
clients.push(c);
return c as unknown as QqHookClient;
},
pipeWatcher: { isPipeLive: () => pipeLive },
it('does not accumulate live FakeClient instances across N pipe up/down cycles', async () => {
let pipeLive = true;
const clients: FakeClient[] = [];
const session = new HookSession(61, {
injector: {
inject: vi.fn(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(),
},
makeClient: () => {
const c = new FakeClient();
clients.push(c);
return c as unknown as QqHookClient;
},
pipeWatcher: { isPipeLive: () => pipeLive },
});
await session.load();
session.onPipeUp();
await flush();
const CYCLES = 50;
for (let i = 0; i < CYCLES; i++) {
pipeLive = false;
session.onPipeDown();
await flush();
pipeLive = true;
session.onPipeUp();
await flush();
}
const alive = clients.filter((c) => !c.isClosed);
expect.soft(clients.length).toBeGreaterThan(1);
expect(
alive.length,
`expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`,
).toBeLessThanOrEqual(1);
});
await session.load();
session.onPipeUp();
await flush();
it('drops all listeners from each torn-down client', async () => {
let pipeLive = true;
const clients: FakeClient[] = [];
const session = new HookSession(61, {
injector: {
inject: vi.fn(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(),
},
makeClient: () => {
const c = new FakeClient();
clients.push(c);
return c as unknown as QqHookClient;
},
pipeWatcher: { isPipeLive: () => pipeLive },
});
const CYCLES = 50;
for (let i = 0; i < CYCLES; i++) {
pipeLive = false;
session.onPipeDown();
await flush();
pipeLive = true;
session.onPipeUp();
await flush();
}
await session.load();
session.onPipeUp();
await flush();
const alive = clients.filter(c => !c.isClosed);
expect.soft(clients.length).toBeGreaterThan(1);
expect(alive.length, `expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`)
.toBeLessThanOrEqual(1);
});
const CYCLES = 20;
it('drops all listeners from each torn-down client', async () => {
let pipeLive = true;
const clients: FakeClient[] = [];
const session = new HookSession(61, {
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: () => {
const c = new FakeClient();
clients.push(c);
return c as unknown as QqHookClient;
},
pipeWatcher: { isPipeLive: () => pipeLive },
for (let i = 0; i < CYCLES; i++) {
pipeLive = false;
session.onPipeDown();
await flush();
pipeLive = true;
session.onPipeUp();
await flush();
}
// Every client except the current one should have 0 listeners attached.
// (HookSession.tearDownClient does client.removeAllListeners().)
for (let i = 0; i < clients.length - 1; i++) {
const lc = totalListenerCount(clients[i]);
expect(
lc,
`client #${i} of ${clients.length} still has ${lc} listeners after teardown`,
).toBe(0);
}
});
await session.load();
session.onPipeUp();
await flush();
const CYCLES = 20;
for (let i = 0; i < CYCLES; i++) {
pipeLive = false;
session.onPipeDown();
await flush();
pipeLive = true;
session.onPipeUp();
await flush();
}
// Every client except the current one should have 0 listeners attached.
// (HookSession.tearDownClient does client.removeAllListeners().)
for (let i = 0; i < clients.length - 1; i++) {
const lc = totalListenerCount(clients[i]);
expect(lc, `client #${i} of ${clients.length} still has ${lc} listeners after teardown`)
.toBe(0);
}
});
});
+73 -55
View File
@@ -2,66 +2,84 @@ import { describe, expect, it } from 'vitest';
import { resolveHookRuntimeDir } from '../src/hook-runtime-dir';
function procReader(files: Record<string, string>) {
return (file: string): string => {
const value = files[file];
if (value === undefined) throw new Error(`missing fixture: ${file}`);
return value;
};
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('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('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('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('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');
});
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');
});
});
File diff suppressed because it is too large. Load diff
+52 -40
View File
@@ -3,54 +3,66 @@ import { statusFor, type HookFlags } from '../src/hook-status';
import type { HookProcessStatus } from '../src/types';
const F = (o: Partial<HookFlags>): HookFlags => ({
injected: false, connected: false, loggedIn: false, wasLoggedIn: false, ...o,
injected: false,
connected: false,
loggedIn: false,
wasLoggedIn: false,
...o,
});
describe('statusFor — settled HookProcessStatus derivation', () => {
it('not injected → available (regardless of other flags)', () => {
expect(statusFor(F({ injected: false }))).toBe('available');
// !injected dominates: stale connected/loggedIn bits must not leak through.
expect(statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true }))).toBe('available');
});
it('not injected → available (regardless of other flags)', () => {
expect(statusFor(F({ injected: false }))).toBe('available');
// !injected dominates: stale connected/loggedIn bits must not leak through.
expect(
statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true })),
).toBe('available');
});
it('injected, connected, loggedIn → online', () => {
expect(statusFor(F({ injected: true, connected: true, loggedIn: true }))).toBe('online');
});
it('injected, connected, loggedIn → online', () => {
expect(statusFor(F({ injected: true, connected: true, loggedIn: true }))).toBe('online');
});
it('injected, connected, not loggedIn → loaded', () => {
expect(statusFor(F({ injected: true, connected: true, loggedIn: false }))).toBe('loaded');
});
it('injected, connected, not loggedIn → loaded', () => {
expect(statusFor(F({ injected: true, connected: true, loggedIn: false }))).toBe('loaded');
});
it('injected, not connected, had logged in → disconnected', () => {
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe('disconnected');
});
it('injected, not connected, had logged in → disconnected', () => {
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe(
'disconnected',
);
});
it('injected, not connected, never logged in → connecting', () => {
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe('connecting');
});
it('injected, not connected, never logged in → connecting', () => {
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe(
'connecting',
);
});
it('disconnected vs connecting differ ONLY by wasLoggedIn (same injected+!connected)', () => {
const base = { injected: true, connected: false, loggedIn: false };
expect(statusFor(F({ ...base, wasLoggedIn: true }))).toBe('disconnected');
expect(statusFor(F({ ...base, wasLoggedIn: false }))).toBe('connecting');
});
it('disconnected vs connecting differ ONLY by wasLoggedIn (same injected+!connected)', () => {
const base = { injected: true, connected: false, loggedIn: false };
expect(statusFor(F({ ...base, wasLoggedIn: true }))).toBe('disconnected');
expect(statusFor(F({ ...base, wasLoggedIn: false }))).toBe('connecting');
});
it('covers exactly the five settled states across the flag space', () => {
const seen = new Set<HookProcessStatus>();
for (const injected of [false, true]) {
for (const connected of [false, true]) {
for (const loggedIn of [false, true]) {
for (const wasLoggedIn of [false, true]) {
seen.add(statusFor({ injected, connected, loggedIn, wasLoggedIn }));
}
it('covers exactly the five settled states across the flag space', () => {
const seen = new Set<HookProcessStatus>();
for (const injected of [false, true]) {
for (const connected of [false, true]) {
for (const loggedIn of [false, true]) {
for (const wasLoggedIn of [false, true]) {
seen.add(statusFor({ injected, connected, loggedIn, wasLoggedIn }));
}
}
}
}
}
}
expect([...seen].sort()).toEqual(
['available', 'connecting', 'disconnected', 'loaded', 'online'].sort(),
);
// The two out-of-band states are never produced by the pure derivation.
expect(seen.has('loading')).toBe(false);
expect(seen.has('error')).toBe(false);
});
expect([...seen].sort()).toEqual(
['available', 'connecting', 'disconnected', 'loaded', 'online'].sort(),
);
// The two out-of-band states are never produced by the pure derivation.
expect(seen.has('loading')).toBe(false);
expect(seen.has('error')).toBe(false);
});
});
+310 -297
View File
@@ -3,21 +3,21 @@ import { fileURLToPath } from 'url';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const { existsSyncMock, listPidsMock } = vi.hoisted(() => ({
existsSyncMock: vi.fn<(target: string) => boolean>(() => false),
listPidsMock: vi.fn(() => new Set<number>()),
existsSyncMock: vi.fn<(target: string) => boolean>(() => false),
listPidsMock: vi.fn(() => new Set<number>()),
}));
vi.mock('fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('fs')>();
return {
...actual,
existsSync: (target: Parameters<typeof actual.existsSync>[0]) =>
existsSyncMock(String(target)),
};
const actual = await importOriginal<typeof import('fs')>();
return {
...actual,
existsSync: (target: Parameters<typeof actual.existsSync>[0]) =>
existsSyncMock(String(target)),
};
});
vi.mock('../src/qq-hook-client', () => ({
listSnowlumaPipePidsSync: listPidsMock,
listSnowlumaPipePidsSync: listPidsMock,
}));
const INJECTOR_DIR = path.dirname(fileURLToPath(new URL('../src/injector.ts', import.meta.url)));
@@ -25,378 +25,391 @@ const ORIGINAL_PLATFORM = process.platform;
const ORIGINAL_ARCH = process.arch;
const HANDLE = {
base: 0x7fff0000n,
entry: 0x7fff1234n,
exceptionTable: 0x7fff5678n,
size: 8192,
base: 0x7fff0000n,
entry: 0x7fff1234n,
exceptionTable: 0x7fff5678n,
size: 8192,
};
function setPlatform(platform: NodeJS.Platform, arch: string): void {
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
Object.defineProperty(process, 'arch', { value: arch, configurable: true });
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
Object.defineProperty(process, 'arch', { value: arch, configurable: true });
}
function restorePlatform(): void {
Object.defineProperty(process, 'platform', { value: ORIGINAL_PLATFORM, configurable: true });
Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true });
Object.defineProperty(process, 'platform', { value: ORIGINAL_PLATFORM, configurable: true });
Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true });
}
function nativeSearchDirs(cwd = process.cwd()): string[] {
return [
path.resolve(INJECTOR_DIR, 'native'),
path.resolve(INJECTOR_DIR, '..', '..', 'runtime', 'native'),
path.resolve(cwd, 'dist', 'native'),
path.resolve(cwd, 'packages', 'runtime', 'native'),
];
return [
path.resolve(INJECTOR_DIR, 'native'),
path.resolve(INJECTOR_DIR, '..', '..', 'runtime', 'native'),
path.resolve(cwd, 'dist', 'native'),
path.resolve(cwd, 'packages', 'runtime', 'native'),
];
}
function nativeCandidate(fileName: string, dirIndex: number, cwd = process.cwd()): string {
return path.join(nativeSearchDirs(cwd)[dirIndex]!, fileName);
return path.join(nativeSearchDirs(cwd)[dirIndex]!, fileName);
}
function allowExisting(paths: readonly string[]): void {
const allowed = new Set(paths);
existsSyncMock.mockImplementation((target) => allowed.has(target));
const allowed = new Set(paths);
existsSyncMock.mockImplementation((target) => allowed.has(target));
}
function fakeAddon(overrides: {
getAllMainProcess?: number[];
loadModuleManual?: (pid: number, dylibPath: string) => unknown;
unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void;
} = {}) {
return {
getAllMainProcess: vi.fn(() => overrides.getAllMainProcess ?? []),
loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)),
unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)),
};
function fakeAddon(
overrides: {
getAllMainProcess?: number[];
loadModuleManual?: (pid: number, dylibPath: string) => unknown;
unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void;
} = {},
) {
return {
getAllMainProcess: vi.fn(() => overrides.getAllMainProcess ?? []),
loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)),
unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)),
};
}
function installDlopen(addon: object) {
return vi.spyOn(process, 'dlopen').mockImplementation((mod) => {
(mod as { exports: object }).exports = addon;
});
return vi.spyOn(process, 'dlopen').mockImplementation((mod) => {
(mod as { exports: object }).exports = addon;
});
}
async function loadInjector() {
return import('../src/injector');
return import('../src/injector');
}
beforeEach(() => {
existsSyncMock.mockReset();
existsSyncMock.mockReturnValue(false);
listPidsMock.mockReset();
listPidsMock.mockReturnValue(new Set());
vi.resetModules();
existsSyncMock.mockReset();
existsSyncMock.mockReturnValue(false);
listPidsMock.mockReset();
listPidsMock.mockReturnValue(new Set());
vi.resetModules();
});
afterEach(() => {
restorePlatform();
vi.restoreAllMocks();
restorePlatform();
vi.restoreAllMocks();
});
describe('resolveHookNativePath', () => {
it('returns null after probing every search directory', async () => {
setPlatform('linux', 'x64');
const probed: string[] = [];
existsSyncMock.mockImplementation((target) => {
probed.push(target);
return false;
it('returns null after probing every search directory', async () => {
setPlatform('linux', 'x64');
const probed: string[] = [];
existsSyncMock.mockImplementation((target) => {
probed.push(target);
return false;
});
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('node')).toBeNull();
expect(probed).toEqual([
nativeCandidate('snowluma-linux-x64.node', 0),
nativeCandidate('snowluma-linux-x64.node', 1),
nativeCandidate('snowluma-linux-x64.node', 2),
nativeCandidate('snowluma-linux-x64.node', 3),
]);
});
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('node')).toBeNull();
expect(probed).toEqual([
nativeCandidate('snowluma-linux-x64.node', 0),
nativeCandidate('snowluma-linux-x64.node', 1),
nativeCandidate('snowluma-linux-x64.node', 2),
nativeCandidate('snowluma-linux-x64.node', 3),
]);
});
it('returns the first existing candidate and stops scanning', async () => {
setPlatform('linux', 'x64');
const winner = nativeCandidate('snowluma-linux-x64.node', 0);
const later = nativeCandidate('snowluma-linux-x64.node', 1);
const probed: string[] = [];
existsSyncMock.mockImplementation((target) => {
probed.push(target);
return target === winner || target === later;
});
it('returns the first existing candidate and stops scanning', async () => {
setPlatform('linux', 'x64');
const winner = nativeCandidate('snowluma-linux-x64.node', 0);
const later = nativeCandidate('snowluma-linux-x64.node', 1);
const probed: string[] = [];
existsSyncMock.mockImplementation((target) => {
probed.push(target);
return target === winner || target === later;
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('node')).toBe(winner);
expect(probed).toEqual([winner]);
});
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('node')).toBe(winner);
expect(probed).toEqual([winner]);
});
it('skips missing earlier directories for the injectable .so', async () => {
setPlatform('linux', 'arm64');
const winner = nativeCandidate('snowluma-linux-arm64.so', 2);
allowExisting([winner]);
it('skips missing earlier directories for the injectable .so', async () => {
setPlatform('linux', 'arm64');
const winner = nativeCandidate('snowluma-linux-arm64.so', 2);
allowExisting([winner]);
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('so')).toBe(winner);
});
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('so')).toBe(winner);
});
it('resolves snowluma-win32-x64.dll on win32 x64', async () => {
setPlatform('win32', 'x64');
const winner = nativeCandidate('snowluma-win32-x64.dll', 3);
allowExisting([winner]);
it('resolves snowluma-win32-x64.dll on win32 x64', async () => {
setPlatform('win32', 'x64');
const winner = nativeCandidate('snowluma-win32-x64.dll', 3);
allowExisting([winner]);
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('dll')).toBe(winner);
});
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('dll')).toBe(winner);
});
it('uses the generic platform-arch name on win32 arm64', async () => {
setPlatform('win32', 'arm64');
const winner = nativeCandidate('snowluma-win32-arm64.node', 1);
allowExisting([winner]);
it('uses the generic platform-arch name on win32 arm64', async () => {
setPlatform('win32', 'arm64');
const winner = nativeCandidate('snowluma-win32-arm64.node', 1);
allowExisting([winner]);
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('node')).toBe(winner);
});
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('node')).toBe(winner);
});
it('re-reads process.cwd() for the dist/native fallback', async () => {
setPlatform('darwin', 'arm64');
vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd');
const winner = path.join(
'/tmp/sl-injector-cwd',
'dist',
'native',
'snowluma-darwin-arm64.node',
);
allowExisting([winner]);
it('re-reads process.cwd() for the dist/native fallback', async () => {
setPlatform('darwin', 'arm64');
vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd');
const winner = path.join('/tmp/sl-injector-cwd', 'dist', 'native', 'snowluma-darwin-arm64.node');
allowExisting([winner]);
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('node')).toBe(winner);
});
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('node')).toBe(winner);
});
});
describe('getNativeHookAddon / getNativeHookLoadError', () => {
it('starts with a null load error before any probe', async () => {
const { getNativeHookLoadError } = await loadInjector();
expect(getNativeHookLoadError()).toBeNull();
});
it('returns null and records a missing-binary error', async () => {
setPlatform('linux', 'x64');
const dlopen = vi.spyOn(process, 'dlopen');
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
expect(getNativeHookAddon()).toBeNull();
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
expect(dlopen).not.toHaveBeenCalled();
});
it('dlopens the resolved .node once and caches the addon', async () => {
setPlatform('linux', 'x64');
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
allowExisting([nodePath]);
const addon = fakeAddon();
const dlopen = installDlopen(addon);
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
const first = getNativeHookAddon();
const second = getNativeHookAddon();
expect(first).toBe(addon);
expect(second).toBe(addon);
expect(getNativeHookLoadError()).toBeNull();
expect(dlopen).toHaveBeenCalledTimes(1);
expect(dlopen.mock.calls[0]![1]).toBe(nodePath);
});
it('stores Error.message when process.dlopen throws', async () => {
setPlatform('darwin', 'arm64');
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
vi.spyOn(process, 'dlopen').mockImplementation(() => {
throw new Error('not a valid Node addon');
it('starts with a null load error before any probe', async () => {
const { getNativeHookLoadError } = await loadInjector();
expect(getNativeHookLoadError()).toBeNull();
});
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
expect(getNativeHookAddon()).toBeNull();
expect(getNativeHookLoadError()).toBe('not a valid Node addon');
});
it('returns null and records a missing-binary error', async () => {
setPlatform('linux', 'x64');
const dlopen = vi.spyOn(process, 'dlopen');
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
it('stringifies a non-Error dlopen failure', async () => {
setPlatform('linux', 'x64');
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
vi.spyOn(process, 'dlopen').mockImplementation(() => {
throw 42;
expect(getNativeHookAddon()).toBeNull();
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
expect(dlopen).not.toHaveBeenCalled();
});
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
expect(getNativeHookAddon()).toBeNull();
expect(getNativeHookLoadError()).toBe('42');
});
it('dlopens the resolved .node once and caches the addon', async () => {
setPlatform('linux', 'x64');
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
allowExisting([nodePath]);
const addon = fakeAddon();
const dlopen = installDlopen(addon);
it('retries after a failed load when a binary later appears', async () => {
setPlatform('linux', 'x64');
const nodePath = nativeCandidate('snowluma-linux-x64.node', 1);
const addon = fakeAddon();
installDlopen(addon);
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
const first = getNativeHookAddon();
const second = getNativeHookAddon();
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
expect(getNativeHookAddon()).toBeNull();
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
expect(first).toBe(addon);
expect(second).toBe(addon);
expect(getNativeHookLoadError()).toBeNull();
expect(dlopen).toHaveBeenCalledTimes(1);
expect(dlopen.mock.calls[0]![1]).toBe(nodePath);
});
allowExisting([nodePath]);
expect(getNativeHookAddon()).toBe(addon);
expect(getNativeHookLoadError()).toBeNull();
});
it('stores Error.message when process.dlopen throws', async () => {
setPlatform('darwin', 'arm64');
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
vi.spyOn(process, 'dlopen').mockImplementation(() => {
throw new Error('not a valid Node addon');
});
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
expect(getNativeHookAddon()).toBeNull();
expect(getNativeHookLoadError()).toBe('not a valid Node addon');
});
it('stringifies a non-Error dlopen failure', async () => {
setPlatform('linux', 'x64');
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
vi.spyOn(process, 'dlopen').mockImplementation(() => {
throw 42;
});
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
expect(getNativeHookAddon()).toBeNull();
expect(getNativeHookLoadError()).toBe('42');
});
it('retries after a failed load when a binary later appears', async () => {
setPlatform('linux', 'x64');
const nodePath = nativeCandidate('snowluma-linux-x64.node', 1);
const addon = fakeAddon();
installDlopen(addon);
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
expect(getNativeHookAddon()).toBeNull();
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
allowExisting([nodePath]);
expect(getNativeHookAddon()).toBe(addon);
expect(getNativeHookLoadError()).toBeNull();
});
});
describe('listHookProcesses', () => {
it('on darwin maps sorted pipe pids without opening the native addon', async () => {
setPlatform('darwin', 'arm64');
listPidsMock.mockReturnValue(new Set([42, 7, 15]));
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
const dlopen = installDlopen(fakeAddon({ getAllMainProcess: [99] }));
it('on darwin maps sorted pipe pids without opening the native addon', async () => {
setPlatform('darwin', 'arm64');
listPidsMock.mockReturnValue(new Set([42, 7, 15]));
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
const dlopen = installDlopen(fakeAddon({ getAllMainProcess: [99] }));
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([
{ pid: 7, name: 'qq', path: '' },
{ pid: 15, name: 'qq', path: '' },
{ pid: 42, name: 'qq', path: '' },
]);
expect(listPidsMock).toHaveBeenCalledTimes(1);
expect(dlopen).not.toHaveBeenCalled();
});
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([
{ pid: 7, name: 'qq', path: '' },
{ pid: 15, name: 'qq', path: '' },
{ pid: 42, name: 'qq', path: '' },
]);
expect(listPidsMock).toHaveBeenCalledTimes(1);
expect(dlopen).not.toHaveBeenCalled();
});
it('on darwin returns an empty list when no control sockets exist', async () => {
setPlatform('darwin', 'arm64');
listPidsMock.mockReturnValue(new Set());
it('on darwin returns an empty list when no control sockets exist', async () => {
setPlatform('darwin', 'arm64');
listPidsMock.mockReturnValue(new Set());
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([]);
});
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([]);
});
it('on non-darwin returns [] when the addon cannot be loaded', async () => {
setPlatform('linux', 'x64');
it('on non-darwin returns [] when the addon cannot be loaded', async () => {
setPlatform('linux', 'x64');
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([]);
});
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([]);
});
it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => {
setPlatform('linux', 'x64');
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
allowExisting([nodePath]);
installDlopen(fakeAddon({
getAllMainProcess: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2],
}));
it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => {
setPlatform('linux', 'x64');
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
allowExisting([nodePath]);
installDlopen(
fakeAddon({
getAllMainProcess: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2],
}),
);
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([
{ pid: 2, name: 'qq', path: '' },
{ pid: 8, name: 'qq', path: '' },
]);
});
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([
{ pid: 2, name: 'qq', path: '' },
{ pid: 8, name: 'qq', path: '' },
]);
});
it('on win32 names processes QQ.exe', async () => {
setPlatform('win32', 'x64');
allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]);
installDlopen(fakeAddon({ getAllMainProcess: [9] }));
it('on win32 names processes QQ.exe', async () => {
setPlatform('win32', 'x64');
allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]);
installDlopen(fakeAddon({ getAllMainProcess: [9] }));
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([
{ pid: 9, name: 'QQ.exe', path: '' },
]);
});
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([{ pid: 9, name: 'QQ.exe', path: '' }]);
});
});
describe('injectHookProcess', () => {
it('throws the missing-addon load error', async () => {
setPlatform('linux', 'x64');
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(4242)).rejects.toThrow('No hook native addon found for linux-x64');
});
it('throws when the addon exists but the injectable is missing', async () => {
setPlatform('linux', 'x64');
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
installDlopen(fakeAddon());
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64');
});
it('awaits a thenable loadModuleManual handle', async () => {
setPlatform('linux', 'x64');
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
const soPath = nativeCandidate('snowluma-linux-x64.so', 0);
allowExisting([nodePath, soPath]);
const addon = fakeAddon({
loadModuleManual: () => Promise.resolve(HANDLE),
it('throws the missing-addon load error', async () => {
setPlatform('linux', 'x64');
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(4242)).rejects.toThrow(
'No hook native addon found for linux-x64',
);
});
installDlopen(addon);
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(4242)).resolves.toEqual({
method: 'loadModuleManual',
handle: HANDLE,
it('throws when the addon exists but the injectable is missing', async () => {
setPlatform('linux', 'x64');
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
installDlopen(fakeAddon());
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64');
});
expect(addon.loadModuleManual).toHaveBeenCalledTimes(1);
expect(addon.loadModuleManual).toHaveBeenCalledWith(4242, soPath);
});
it('accepts a synchronous loadModuleManual return value', async () => {
setPlatform('darwin', 'arm64');
const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 2);
const soPath = nativeCandidate('snowluma-darwin-arm64.so', 3);
allowExisting([nodePath, soPath]);
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
installDlopen(addon);
it('awaits a thenable loadModuleManual handle', async () => {
setPlatform('linux', 'x64');
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
const soPath = nativeCandidate('snowluma-linux-x64.so', 0);
allowExisting([nodePath, soPath]);
const addon = fakeAddon({
loadModuleManual: () => Promise.resolve(HANDLE),
});
installDlopen(addon);
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(77)).resolves.toEqual({
method: 'loadModuleManual',
handle: HANDLE,
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(4242)).resolves.toEqual({
method: 'loadModuleManual',
handle: HANDLE,
});
expect(addon.loadModuleManual).toHaveBeenCalledTimes(1);
expect(addon.loadModuleManual).toHaveBeenCalledWith(4242, soPath);
});
expect(addon.loadModuleManual).toHaveBeenCalledWith(77, soPath);
});
it('injects snowluma-win32-x64.dll on win32 x64', async () => {
setPlatform('win32', 'x64');
const nodePath = nativeCandidate('snowluma-win32-x64.node', 0);
const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0);
allowExisting([nodePath, dllPath]);
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
installDlopen(addon);
it('accepts a synchronous loadModuleManual return value', async () => {
setPlatform('darwin', 'arm64');
const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 2);
const soPath = nativeCandidate('snowluma-darwin-arm64.so', 3);
allowExisting([nodePath, soPath]);
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
installDlopen(addon);
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(5150)).resolves.toEqual({
method: 'loadModuleManual',
handle: HANDLE,
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(77)).resolves.toEqual({
method: 'loadModuleManual',
handle: HANDLE,
});
expect(addon.loadModuleManual).toHaveBeenCalledWith(77, soPath);
});
expect(addon.loadModuleManual).toHaveBeenCalledWith(5150, dllPath);
});
it('propagates a rejected loadModuleManual', async () => {
setPlatform('linux', 'x64');
allowExisting([
nativeCandidate('snowluma-linux-x64.node', 0),
nativeCandidate('snowluma-linux-x64.so', 0),
]);
installDlopen(fakeAddon({
loadModuleManual: () => Promise.reject(new Error('map failed')),
}));
it('injects snowluma-win32-x64.dll on win32 x64', async () => {
setPlatform('win32', 'x64');
const nodePath = nativeCandidate('snowluma-win32-x64.node', 0);
const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0);
allowExisting([nodePath, dllPath]);
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
installDlopen(addon);
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(7)).rejects.toThrow('map failed');
});
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(5150)).resolves.toEqual({
method: 'loadModuleManual',
handle: HANDLE,
});
expect(addon.loadModuleManual).toHaveBeenCalledWith(5150, dllPath);
});
it('propagates a rejected loadModuleManual', async () => {
setPlatform('linux', 'x64');
allowExisting([
nativeCandidate('snowluma-linux-x64.node', 0),
nativeCandidate('snowluma-linux-x64.so', 0),
]);
installDlopen(
fakeAddon({
loadModuleManual: () => Promise.reject(new Error('map failed')),
}),
);
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(7)).rejects.toThrow('map failed');
});
});
describe('unloadHookProcess', () => {
it('throws the missing-addon load error', async () => {
setPlatform('linux', 'x64');
const { unloadHookProcess } = await loadInjector();
expect(() => unloadHookProcess(4242, HANDLE)).toThrow('No hook native addon found for linux-x64');
});
it('throws the missing-addon load error', async () => {
setPlatform('linux', 'x64');
const { unloadHookProcess } = await loadInjector();
expect(() => unloadHookProcess(4242, HANDLE)).toThrow(
'No hook native addon found for linux-x64',
);
});
it('forwards pid and handle to unloadModuleManual', async () => {
setPlatform('linux', 'x64');
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
const addon = fakeAddon();
installDlopen(addon);
it('forwards pid and handle to unloadModuleManual', async () => {
setPlatform('linux', 'x64');
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
const addon = fakeAddon();
installDlopen(addon);
const { unloadHookProcess } = await loadInjector();
expect(unloadHookProcess(4242, HANDLE)).toBeUndefined();
expect(addon.unloadModuleManual).toHaveBeenCalledTimes(1);
expect(addon.unloadModuleManual).toHaveBeenCalledWith(4242, HANDLE);
});
const { unloadHookProcess } = await loadInjector();
expect(unloadHookProcess(4242, HANDLE)).toBeUndefined();
expect(addon.unloadModuleManual).toHaveBeenCalledTimes(1);
expect(addon.unloadModuleManual).toHaveBeenCalledWith(4242, HANDLE);
});
});
+17 -17
View File
@@ -6,25 +6,25 @@ const PACKET = 'SNOWLUMA_PACKET_TIMEOUT_MS';
const ACK = 'SNOWLUMA_HOOK_ACK_TIMEOUT_MS';
afterEach(() => {
delete process.env[PACKET];
delete process.env[ACK];
delete process.env[PACKET];
delete process.env[ACK];
});
describe('packet and hook ack timeouts', () => {
it('keeps the 15 second packet default', () => {
expect(packetTimeoutMs({})).toBe(15_000);
});
it('keeps the 15 second packet default', () => {
expect(packetTimeoutMs({})).toBe(15_000);
});
it('reads SNOWLUMA_PACKET_TIMEOUT_MS', () => {
expect(packetTimeoutMs({ [PACKET]: '8000' })).toBe(8000);
expect(packetTimeoutMs({ [PACKET]: '0' })).toBe(15_000);
});
it('reads SNOWLUMA_PACKET_TIMEOUT_MS', () => {
expect(packetTimeoutMs({ [PACKET]: '8000' })).toBe(8000);
expect(packetTimeoutMs({ [PACKET]: '0' })).toBe(15_000);
});
it('uses SNOWLUMA_HOOK_ACK_TIMEOUT_MS when the client is not given one', () => {
process.env[ACK] = '1200';
const client = new QqHookClient(1, { runtimeDir: '/tmp' });
expect(client.defaultAckTimeoutMs).toBe(1200);
const explicit = new QqHookClient(1, { runtimeDir: '/tmp', ackTimeoutMs: 50 });
expect(explicit.defaultAckTimeoutMs).toBe(50);
});
});
it('uses SNOWLUMA_HOOK_ACK_TIMEOUT_MS when the client is not given one', () => {
process.env[ACK] = '1200';
const client = new QqHookClient(1, { runtimeDir: '/tmp' });
expect(client.defaultAckTimeoutMs).toBe(1200);
const explicit = new QqHookClient(1, { runtimeDir: '/tmp', ackTimeoutMs: 50 });
expect(explicit.defaultAckTimeoutMs).toBe(50);
});
});
+282 -252
View File
@@ -3,282 +3,312 @@ import { PipeWatcher } from '../src/pipe-watcher';
import type { HookProcessBaseInfo } from '../src/injector';
function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set<number> }) {
let processes = initial.processes;
let live = initial.live;
const watcher = new PipeWatcher({
listProcesses: () => processes,
// Defensively copy so the watcher can't mutate the test's reference.
listLivePipes: async () => new Set(live),
intervalMs: 60_000, // disable the internal timer; tests drive ticks manually
});
return {
watcher,
setProcesses: (p: HookProcessBaseInfo[]) => { processes = p; },
setLive: (s: Set<number>) => { live = s; },
};
let processes = initial.processes;
let live = initial.live;
const watcher = new PipeWatcher({
listProcesses: () => processes,
// Defensively copy so the watcher can't mutate the test's reference.
listLivePipes: async () => new Set(live),
intervalMs: 60_000, // disable the internal timer; tests drive ticks manually
});
return {
watcher,
setProcesses: (p: HookProcessBaseInfo[]) => {
processes = p;
},
setLive: (s: Set<number>) => {
live = s;
},
};
}
type EventRow = [string, unknown];
function captureEvents(watcher: PipeWatcher): EventRow[] {
const events: EventRow[] = [];
watcher.on('process-discovered', info => events.push(['discovered', (info as HookProcessBaseInfo).pid]));
watcher.on('process-gone', pid => events.push(['gone', pid]));
watcher.on('pipe-up', pid => events.push(['up', pid]));
watcher.on('pipe-down', pid => events.push(['down', pid]));
return events;
const events: EventRow[] = [];
watcher.on('process-discovered', (info) =>
events.push(['discovered', (info as HookProcessBaseInfo).pid]),
);
watcher.on('process-gone', (pid) => events.push(['gone', pid]));
watcher.on('pipe-up', (pid) => events.push(['up', pid]));
watcher.on('pipe-down', (pid) => events.push(['down', pid]));
return events;
}
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,
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();
});
await watcher.start();
it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
const events = captureEvents(ctx.watcher);
await ctx.watcher.start();
expect(observed).toEqual(processes);
watcher.stop();
});
expect(events).toEqual([
['discovered', 1234],
['up', 1234],
]);
expect(ctx.watcher.isPipeLive(1234)).toBe(true);
expect(ctx.watcher.isProcessAlive(1234)).toBe(true);
it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
const events = captureEvents(ctx.watcher);
await ctx.watcher.start();
expect(events).toEqual([
['discovered', 1234],
['up', 1234],
]);
expect(ctx.watcher.isPipeLive(1234)).toBe(true);
expect(ctx.watcher.isProcessAlive(1234)).toBe(true);
ctx.watcher.stop();
});
it('pipe-down emitted when a previously-live pipe disappears', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
ctx.setLive(new Set());
await ctx.watcher.tickNow();
expect(events).toEqual([['down', 1234]]);
expect(ctx.watcher.isPipeLive(1234)).toBe(false);
ctx.watcher.stop();
});
it('process-gone + pipe-down both emitted (pipe-down first) when QQ.exe is killed with a live pipe', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
ctx.setProcesses([]);
ctx.setLive(new Set());
await ctx.watcher.tickNow();
expect(events).toEqual([
['down', 1234],
['gone', 1234],
]);
ctx.watcher.stop();
});
it('ignores live pipes whose process is not running', async () => {
const ctx = setupWatcher({
processes: [],
live: new Set([9999]),
});
const events = captureEvents(ctx.watcher);
await ctx.watcher.start();
expect(events).toEqual([]);
expect(ctx.watcher.isPipeLive(9999)).toBe(false);
ctx.watcher.stop();
});
it('emits pipe-up again after a pipe-down → pipe-up cycle', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set(),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
ctx.setLive(new Set([1234]));
await ctx.watcher.tickNow();
expect(events).toEqual([['up', 1234]]);
ctx.setLive(new Set());
await ctx.watcher.tickNow();
expect(events).toEqual([['up', 1234], ['down', 1234]]);
ctx.setLive(new Set([1234]));
await ctx.watcher.tickNow();
expect(events).toEqual([['up', 1234], ['down', 1234], ['up', 1234]]);
ctx.watcher.stop();
});
it('does not double-emit on idempotent ticks (no state change)', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
await ctx.watcher.tickNow();
await ctx.watcher.tickNow();
expect(events).toEqual([]);
ctx.watcher.stop();
});
it('emits "tick" after every poll', async () => {
const ctx = setupWatcher({ processes: [], live: new Set() });
let ticks = 0;
ctx.watcher.on('tick', () => { ticks++; });
await ctx.watcher.start();
expect(ticks).toBe(1);
await ctx.watcher.tickNow();
expect(ticks).toBe(2);
ctx.watcher.stop();
});
it('wake() pulls the next tick forward', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set(),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
// Wait on 'tick' rather than guessing how many event-loop turns
// setTimeout(0) needs (it's clamped to ~1ms and races setImmediate).
const nextTick = new Promise<void>(resolve => ctx.watcher.once('tick', () => resolve()));
ctx.setLive(new Set([1234]));
ctx.watcher.wake();
await nextTick;
expect(events).toEqual([['up', 1234]]);
ctx.watcher.stop();
});
it('survives a throwing listProcesses without crashing the watcher', async () => {
let processes: HookProcessBaseInfo[] = [];
let live = new Set<number>();
let shouldThrow = true;
const watcher = new PipeWatcher({
listProcesses: () => {
if (shouldThrow) throw new Error('boom');
return processes;
},
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
ctx.watcher.stop();
});
await watcher.start();
expect(watcher.isProcessAlive(1234)).toBe(false);
it('pipe-down emitted when a previously-live pipe disappears', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
shouldThrow = false;
processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
live = new Set([1234]);
const events = captureEvents(watcher);
await watcher.tickNow();
ctx.setLive(new Set());
await ctx.watcher.tickNow();
expect(events).toEqual([['discovered', 1234], ['up', 1234]]);
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,
expect(events).toEqual([['down', 1234]]);
expect(ctx.watcher.isPipeLive(1234)).toBe(false);
ctx.watcher.stop();
});
await watcher.start();
expect(watcher.isPipeLive(1234)).toBe(true);
const events = captureEvents(watcher);
it('process-gone + pipe-down both emitted (pipe-down first) when QQ.exe is killed with a live pipe', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
failPipeDiscovery = true;
await watcher.tickNow();
ctx.setProcesses([]);
ctx.setLive(new Set());
await ctx.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<number>([1234]);
const watcher = new PipeWatcher({
listProcesses: () => result,
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
expect(events).toEqual([
['down', 1234],
['gone', 1234],
]);
ctx.watcher.stop();
});
await watcher.start();
expect(watcher.isProcessAlive(1234)).toBe(true);
expect(watcher.isPipeLive(1234)).toBe(true);
it('ignores live pipes whose process is not running', async () => {
const ctx = setupWatcher({
processes: [],
live: new Set([9999]),
});
const events = captureEvents(ctx.watcher);
await ctx.watcher.start();
const events = captureEvents(watcher);
expect(events).toEqual([]);
expect(ctx.watcher.isPipeLive(9999)).toBe(false);
ctx.watcher.stop();
});
// Enumeration goes UNKNOWN (e.g. native /proc walk timed out during a QQ
// hot-update). Prior process + pipe state MUST be preserved — no teardown.
result = null;
await watcher.tickNow();
expect(events).toEqual([]);
expect(watcher.isProcessAlive(1234)).toBe(true);
expect(watcher.isPipeLive(1234)).toBe(true);
it('emits pipe-up again after a pipe-down → pipe-up cycle', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set(),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
// Enumeration recovers with the same set → still no churn.
result = [{ pid: 1234, name: 'qq', path: '' }];
await watcher.tickNow();
expect(events).toEqual([]);
ctx.setLive(new Set([1234]));
await ctx.watcher.tickNow();
expect(events).toEqual([['up', 1234]]);
// A REAL disappearance (empty list, not null) still fires the teardown.
result = [];
live = new Set();
await watcher.tickNow();
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
watcher.stop();
});
ctx.setLive(new Set());
await ctx.watcher.tickNow();
expect(events).toEqual([
['up', 1234],
['down', 1234],
]);
ctx.setLive(new Set([1234]));
await ctx.watcher.tickNow();
expect(events).toEqual([
['up', 1234],
['down', 1234],
['up', 1234],
]);
ctx.watcher.stop();
});
it('does not double-emit on idempotent ticks (no state change)', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
await ctx.watcher.tickNow();
await ctx.watcher.tickNow();
expect(events).toEqual([]);
ctx.watcher.stop();
});
it('emits "tick" after every poll', async () => {
const ctx = setupWatcher({ processes: [], live: new Set() });
let ticks = 0;
ctx.watcher.on('tick', () => {
ticks++;
});
await ctx.watcher.start();
expect(ticks).toBe(1);
await ctx.watcher.tickNow();
expect(ticks).toBe(2);
ctx.watcher.stop();
});
it('wake() pulls the next tick forward', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set(),
});
await ctx.watcher.start();
const events = captureEvents(ctx.watcher);
// Wait on 'tick' rather than guessing how many event-loop turns
// setTimeout(0) needs (it's clamped to ~1ms and races setImmediate).
const nextTick = new Promise<void>((resolve) => ctx.watcher.once('tick', () => resolve()));
ctx.setLive(new Set([1234]));
ctx.watcher.wake();
await nextTick;
expect(events).toEqual([['up', 1234]]);
ctx.watcher.stop();
});
it('survives a throwing listProcesses without crashing the watcher', async () => {
let processes: HookProcessBaseInfo[] = [];
let live = new Set<number>();
let shouldThrow = true;
const watcher = new PipeWatcher({
listProcesses: () => {
if (shouldThrow) {
throw new Error('boom');
}
return processes;
},
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
});
await watcher.start();
expect(watcher.isProcessAlive(1234)).toBe(false);
shouldThrow = false;
processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
live = new Set([1234]);
const events = captureEvents(watcher);
await watcher.tickNow();
expect(events).toEqual([
['discovered', 1234],
['up', 1234],
]);
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<number>([1234]);
const watcher = new PipeWatcher({
listProcesses: () => result,
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
});
await watcher.start();
expect(watcher.isProcessAlive(1234)).toBe(true);
expect(watcher.isPipeLive(1234)).toBe(true);
const events = captureEvents(watcher);
// Enumeration goes UNKNOWN (e.g. native /proc walk timed out during a QQ
// hot-update). Prior process + pipe state MUST be preserved — no teardown.
result = null;
await watcher.tickNow();
expect(events).toEqual([]);
expect(watcher.isProcessAlive(1234)).toBe(true);
expect(watcher.isPipeLive(1234)).toBe(true);
// Enumeration recovers with the same set → still no churn.
result = [{ pid: 1234, name: 'qq', path: '' }];
await watcher.tickNow();
expect(events).toEqual([]);
// A REAL disappearance (empty list, not null) still fires the teardown.
result = [];
live = new Set();
await watcher.tickNow();
expect(events).toEqual([
['down', 1234],
['gone', 1234],
]);
watcher.stop();
});
});
@@ -5,51 +5,53 @@ import type { HookProcessBaseInfo } from '../src/injector';
const QQ = (pid: number): HookProcessBaseInfo => ({ pid, name: 'qq', path: '' });
describe('createNativeProcessEnumerator', () => {
describe('no addon (macOS / missing) → synchronous fallback, never a worker', () => {
it('returns the sync lister result', async () => {
const en = createNativeProcessEnumerator({
addonPath: null,
fallbackSync: () => [QQ(10), QQ(20)],
processName: 'qq',
});
expect(await en.enumerate()).toEqual([QQ(10), QQ(20)]);
en.dispose();
describe('no addon (macOS / missing) → synchronous fallback, never a worker', () => {
it('returns the sync lister result', async () => {
const en = createNativeProcessEnumerator({
addonPath: null,
fallbackSync: () => [QQ(10), QQ(20)],
processName: 'qq',
});
expect(await en.enumerate()).toEqual([QQ(10), QQ(20)]);
en.dispose();
});
it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => {
const en = createNativeProcessEnumerator({
addonPath: null,
fallbackSync: () => {
throw new Error('boom');
},
processName: 'qq',
});
expect(await en.enumerate()).toBeNull();
en.dispose();
});
});
it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => {
const en = createNativeProcessEnumerator({
addonPath: null,
fallbackSync: () => { throw new Error('boom'); },
processName: 'qq',
});
expect(await en.enumerate()).toBeNull();
en.dispose();
describe('worker isolation that cannot load the addon → permanent fallback', () => {
it('falls back to the sync lister after the worker reports a fatal load error', async () => {
const fallback = vi.fn(() => [QQ(7)]);
const en = createNativeProcessEnumerator({
// A path that exists nowhere → process.dlopen throws in the worker →
// the worker posts 'fatal' → isolation is abandoned for good.
addonPath: '/nonexistent/snowluma-test.node',
fallbackSync: fallback,
processName: 'qq',
timeoutMs: 200,
});
// First call spawns the worker; the fatal message drains it to UNKNOWN.
const first = await en.enumerate();
expect(first).toBeNull();
// Give the 'fatal' message a moment to flip isolationBroken if it hadn't
// already, then subsequent calls take the synchronous fallback.
await new Promise((r) => setTimeout(r, 50));
const second = await en.enumerate();
expect(second).toEqual([QQ(7)]);
expect(fallback).toHaveBeenCalled();
en.dispose();
});
});
});
describe('worker isolation that cannot load the addon → permanent fallback', () => {
it('falls back to the sync lister after the worker reports a fatal load error', async () => {
const fallback = vi.fn(() => [QQ(7)]);
const en = createNativeProcessEnumerator({
// A path that exists nowhere → process.dlopen throws in the worker →
// the worker posts 'fatal' → isolation is abandoned for good.
addonPath: '/nonexistent/snowluma-test.node',
fallbackSync: fallback,
processName: 'qq',
timeoutMs: 200,
});
// First call spawns the worker; the fatal message drains it to UNKNOWN.
const first = await en.enumerate();
expect(first).toBeNull();
// Give the 'fatal' message a moment to flip isolationBroken if it hadn't
// already, then subsequent calls take the synchronous fallback.
await new Promise((r) => setTimeout(r, 50));
const second = await en.enumerate();
expect(second).toEqual([QQ(7)]);
expect(fallback).toHaveBeenCalled();
en.dispose();
});
});
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+49 -47
View File
@@ -1,63 +1,65 @@
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');
}));
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,
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: '1\n', stderr: '' });
});
await expect(probeQqLoginInfo(4242)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
beforeEach(() => {
vi.useFakeTimers();
execMock.mockReset();
socketCtorMock.mockClear();
});
});
it('keeps background identity discovery passive', async () => {
execMock
.mockImplementationOnce((_command, _options, callback) => {
callback(null, {
stdout: 'LISTEN 0 128 127.0.0.1:9218 0.0.0.0:* users:(("qq",pid=4242,fd=12))\n',
stderr: '',
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: '',
identityKnown: false,
});
})
.mockImplementationOnce((_command, _options, callback) => {
callback(null, { stdout: '8\n', stderr: '' });
});
});
await expect(probeQqLoginInfo(4242)).resolves.toBeNull();
expect(socketCtorMock).not.toHaveBeenCalled();
});
it('keeps background identity discovery passive', async () => {
execMock
.mockImplementationOnce((_command, _options, callback) => {
callback(null, {
stdout: '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: '8\n', stderr: '' });
});
await expect(probeQqLoginInfo(4242)).resolves.toBeNull();
expect(socketCtorMock).not.toHaveBeenCalled();
});
});
+4 -4
View File
@@ -1,8 +1,8 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['tests/**/*.test.ts'],
environment: 'node',
},
test: {
include: ['tests/**/*.test.ts'],
environment: 'node',
},
});