lint
This commit is contained in:
977 files changed
+198426
-158324
No files matched your search
+525
-447
File diff suppressed because it is too large.
Load diff
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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)}`,
|
||||
);
|
||||
}
|
||||
+1030
-809
File diff suppressed because it is too large.
Load diff
@@ -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';
|
||||
}
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
+1186
-931
File diff suppressed because it is too large.
Load diff
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user