Files
hyperframes/packages/cli/src/utils/orphanCleanup.ts
T
Miguel Ángel b930c4d2d7 fix(cli): Windows Chrome cleanup and process reads no longer pass PowerShell command text (#8085)
* fix(cli): Windows process reads and Chrome cleanup no longer pass PowerShell command text

* fix(cli): a forced Chrome close on Windows ends what Chrome started

* test(cli): the forced-close test's child holds no pipe to the browser

* test(cli): the forced-close test's child outlives a dead parent, as Chrome's do

* test(cli): forced-close test waits for the kill; PowerShell starts only via processReadArgs

* fix(cli): Windows cleanup ends only a process the CLI started, never a pid it was handed
2026-11-17 20:27:58 +00:00

231 lines
7.7 KiB
TypeScript

// fallow-ignore-file code-duplication
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { HYPERFRAMES_BROWSER_MARKER_ARG } from "@hyperframes/core/browser-marker";
import { runRenderSetupWorker } from "./cancellableProcess.js";
import { terminateProcessTree, windowsProcessTreeKillArgs } from "./processTree.js";
import { processReadArgs } from "./windowsProcesses.js";
export { windowsProcessTreeKillArgs };
/**
* Kill the current user's orphaned (PPID 1) Chrome trees that carry the HyperFrames launch marker, so detached
* browsers other tools started survive. Returns the count of killed process trees.
*/
export function killOrphanedProcesses(): number {
if (process.env.HYPERFRAMES_NO_ORPHAN_CLEANUP === "1" || process.platform === "win32") return 0;
return killOrphansMatching(HYPERFRAMES_BROWSER_MARKER_ARG);
}
export async function killOrphanedProcessesForRender(signal: AbortSignal): Promise<number> {
return runRenderSetupWorker<number>("orphan-cleanup", {}, { signal, timeoutMs: 15_000 });
}
export function killProcessTree(pid: number, signal: NodeJS.Signals = "SIGTERM"): void {
void terminateProcessTree(pid, { signal }).catch(() => undefined);
}
/**
* Return a process birth token suitable for detecting PID reuse. The token is
* diagnostic state only: callers must still prove the live server is a
* descendant before treating a saved wrapper as the owned process-tree root.
*/
export function processIdentity(pid: number): string | null {
if (!Number.isInteger(pid) || pid <= 0) return null;
try {
if (process.platform === "win32") {
const created = execFileSync("powershell.exe", processReadArgs("identity", pid), {
encoding: "utf8",
timeout: 2000,
stdio: ["pipe", "pipe", "ignore"],
windowsHide: true,
}).trim();
return created ? `windows:${created}` : null;
}
if (process.platform === "linux") {
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
const fields = stat
.slice(stat.lastIndexOf(") ") + 2)
.trim()
.split(/\s+/);
const startTicks = fields[19]; // field 22 overall; fields starts at process state (3)
return startTicks ? `linux:${startTicks}` : null;
}
const started = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
encoding: "utf8",
timeout: 2000,
}).trim();
return started ? `posix:${started}` : null;
} catch {
return null;
}
}
type ParentPidLookup = (pid: number) => number | null;
export interface ProcessAncestor {
pid: number;
identity: string;
}
interface ProcessRecord extends ProcessAncestor {
parentPid: number;
startedAt?: bigint | undefined;
}
const holdsReusedPid = (parent: ProcessRecord, child: ProcessRecord | undefined): boolean =>
parent.startedAt !== undefined &&
child?.startedAt !== undefined &&
parent.startedAt > child.startedAt;
function recordsToAncestors(pid: number, records: readonly ProcessRecord[]): ProcessAncestor[] {
const byPid = new Map(records.map((record) => [record.pid, record]));
const ancestors: ProcessAncestor[] = [];
const visited = new Set<number>([pid]);
let current = pid;
for (let depth = 0; depth < 64; depth++) {
const child = byPid.get(current);
const parent = child?.parentPid;
if (parent === undefined || parent <= 1 || visited.has(parent)) break;
visited.add(parent);
const ancestor = byPid.get(parent);
if (!ancestor || holdsReusedPid(ancestor, child)) break;
ancestors.push({ pid: ancestor.pid, identity: ancestor.identity });
current = parent;
}
return ancestors;
}
/**
* Capture an off-Linux ancestor chain in one process-table lookup. This keeps
* the birth token attached to every tracked PID without a PowerShell/ps spawn
* for each ancestor.
*/
export function processAncestorSnapshot(pid: number): ProcessAncestor[] {
if (!Number.isInteger(pid) || pid <= 0 || process.platform === "linux") return [];
try {
if (process.platform === "win32") {
const output = execFileSync("powershell.exe", processReadArgs("table"), {
encoding: "utf8",
timeout: 2000,
stdio: ["pipe", "pipe", "ignore"],
windowsHide: true,
});
const records = output
.split(/\r?\n/)
.map((line) => line.trim().split(/\s+/))
.map(
([processId, parentProcessId, creationDate]): ProcessRecord => ({
pid: Number(processId),
parentPid: Number(parentProcessId),
identity: creationDate ? `windows:${creationDate}` : "",
startedAt:
creationDate && /^\d+$/.test(creationDate) ? BigInt(creationDate) : undefined,
}),
)
.filter(
(record) =>
Number.isInteger(record.pid) &&
record.pid > 0 &&
Number.isInteger(record.parentPid) &&
record.parentPid > 0 &&
record.identity !== "",
);
return recordsToAncestors(pid, records);
}
const output = execFileSync("ps", ["-axo", "pid=,ppid=,lstart="], {
encoding: "utf8",
timeout: 2000,
});
const records = output
.split(/\r?\n/)
.map((line) => line.match(/^\s*(\d+)\s+(\d+)\s+(.+)$/))
.filter((match): match is RegExpMatchArray => match !== null)
.map(([, processId, parentProcessId, started]) => ({
pid: Number(processId),
parentPid: Number(parentProcessId),
identity: `posix:${started?.trim() ?? ""}`,
}));
return recordsToAncestors(pid, records);
} catch {
return [];
}
}
export function processParentPid(pid: number): number | null {
try {
const output =
process.platform === "win32"
? execFileSync("powershell.exe", processReadArgs("parent", pid), {
encoding: "utf8",
timeout: 2000,
stdio: ["pipe", "pipe", "ignore"],
windowsHide: true,
})
: execFileSync("ps", ["-o", "ppid=", "-p", String(pid)], {
encoding: "utf8",
timeout: 2000,
});
const parentPid = Number(output.trim());
return Number.isInteger(parentPid) && parentPid > 0 ? parentPid : null;
} catch {
return null;
}
}
/**
* Prove that `childPid` currently belongs to the process tree rooted at
* `ancestorPid`. The walk fails closed on missing, invalid, or cyclic process
* metadata so a stale saved PID can never authorize terminating a new process.
*/
export function isProcessDescendant(
childPid: number,
ancestorPid: number,
parentPid: ParentPidLookup = processParentPid,
): boolean {
if (childPid <= 0 || ancestorPid <= 0 || childPid === ancestorPid) return false;
const visited = new Set<number>();
let current = childPid;
for (let depth = 0; depth < 64; depth++) {
if (visited.has(current)) return false;
visited.add(current);
const parent = parentPid(current);
if (parent === ancestorPid) return true;
if (parent === null || parent <= 1) return false;
current = parent;
}
return false;
}
/** One process-table read: a spawn per candidate PID cost half a second before `preview` listened. */
function killOrphansMatching(marker: string): number {
const uid = process.getuid?.();
const owner = uid === undefined ? ["-A"] : ["-U", String(uid)];
let table: string;
try {
table = execFileSync("ps", [...owner, "-ww", "-o", "pid=,ppid=,args="], {
encoding: "utf-8",
timeout: 3000,
});
} catch {
return 0;
}
let killed = 0;
for (const line of table.split("\n")) {
const match = line.match(/^\s*(\d+)\s+(\d+)\s+(.*)$/);
if (!match || match[2] !== "1") continue;
if (!match[3]!.split(/\s+/).includes(marker)) continue;
killProcessTree(Number(match[1]));
killed++;
}
return killed;
}