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
This commit is contained in:
Miguel Ángel
2026-11-17 20:27:58 +00:00
committed by GitHub
parent 7407968882
commit b930c4d2d7
12 changed files with 210 additions and 99 deletions
+3
View File
@@ -215,6 +215,9 @@ async function main() {
const inspectorRuntime = join(REPO_ROOT, "packages", "inspector", "dist", "inspection.js");
cpSync(inspectorRuntime, join(DIST, "inspection.js"));
// Windows process reads run this file with -File (utils/windowsProcesses.ts), found beside the bundled chunks.
cpSync(join(CLI_ROOT, "src", "utils", "processes.ps1"), join(DIST, "processes.ps1"));
copyGsapVendorFiles();
copyMdFiles(join(CLI_ROOT, "src", "docs"), join(DIST, "docs"));
@@ -1,7 +1,8 @@
import { spawn } from "node:child_process";
import { once } from "node:events";
import type { Browser, LaunchOptions, PuppeteerNode } from "puppeteer-core";
import { expect, it } from "vitest";
import { expect, it, vi } from "vitest";
import { processIsAlive } from "../utils/processTree.js";
import { launchManagedBrowser } from "./launch.js";
it("kills a browser that acknowledged close but never exits, so every caller's close() returns", async () => {
@@ -13,8 +14,34 @@ it("kills a browser that acknowledged close but never exits, so every caller's c
try {
const launched = await launchManagedBrowser(puppeteer, { headless: true }, { diagnose: false });
await launched.close();
expect(child.signalCode).toBe("SIGKILL");
expect(child.exitCode !== null || child.signalCode !== null).toBe(true);
} finally {
child.kill("SIGKILL");
}
});
it("a forced close also ends what the browser started, as Windows ends no child with its parent", async () => {
const child = spawn(
process.execPath,
[
"-e",
`const kid = require("node:child_process").spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: "ignore", detached: true });
console.log(kid.pid); setTimeout(() => {}, 60000);`,
],
{ stdio: "pipe" },
);
const [line] = (await once(child.stdout!, "data")) as [Buffer];
const kid = Number(String(line).trim());
const browser = { process: () => child, close: () => once(child, "exit") } as unknown as Browser;
const puppeteer = {
launch: async (_options: LaunchOptions) => browser,
} as unknown as PuppeteerNode;
try {
const launched = await launchManagedBrowser(puppeteer, { headless: true }, { diagnose: false });
await launched.close();
await vi.waitFor(() => expect(processIsAlive(kid)).toBe(false), { timeout: 2_000 });
} finally {
child.kill("SIGKILL");
if (processIsAlive(kid)) process.kill(kid, "SIGKILL");
}
});
@@ -0,0 +1,38 @@
import { EventEmitter } from "node:events";
import type { ChildProcess } from "node:child_process";
import type { Browser } from "puppeteer-core";
import { afterEach, expect, it, vi } from "vitest";
const { treeEnds } = vi.hoisted(() => ({ treeEnds: vi.fn(async (_pid: number) => {}) }));
vi.mock("../utils/processTree.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../utils/processTree.js")>()),
terminateWindowsProcessTree: treeEnds,
}));
import { closeManagedBrowser } from "./launch.js";
import { watchChromeTree } from "./windowsChromeWatchdog.js";
const platform = process.platform;
afterEach(() => Object.defineProperty(process, "platform", { value: platform }));
const handedPid = () =>
Object.assign(new EventEmitter(), {
pid: process.pid,
exitCode: null,
signalCode: null,
kill: () => true,
});
it("on Windows, a forced close or a watchdog ends only a process the CLI started, never a pid it was handed", async () => {
Object.defineProperty(process, "platform", { value: "win32" });
const child = handedPid();
const browser = {
process: () => child,
close: () => new Promise(() => {}),
} as unknown as Browser;
await expect(closeManagedBrowser(browser)).rejects.toThrow(
"Browser process did not exit after forced shutdown.",
);
expect(treeEnds).not.toHaveBeenCalled();
expect(watchChromeTree(handedPid() as unknown as ChildProcess)).toBeUndefined();
});
+11 -5
View File
@@ -1,4 +1,4 @@
import type { ChildProcess } from "node:child_process";
import { ChildProcess } from "node:child_process";
import {
inAgentSandbox,
isOneProcessOverPipe,
@@ -19,7 +19,7 @@ import {
} from "./gpuPolicy.js";
import { normalizeErrorMessage, notePageCrash } from "../utils/errorMessage.js";
import { requestCliExit } from "../utils/commandResult.js";
import { processIsAlive } from "../utils/processTree.js";
import { processIsAlive, terminateWindowsProcessTree } from "../utils/processTree.js";
import { chromeDescendants, reapChromeTree } from "./chromeTree.js";
import { watchChromeTree, type ChromeWatchdog } from "./windowsChromeWatchdog.js";
@@ -174,7 +174,6 @@ async function launchOwnedBrowser(
ownSignals();
const abort = new AbortController();
const signal = options.signal ? AbortSignal.any([options.signal, abort.signal]) : abort.signal;
const launchedAt = Date.now();
const launch = untilLaunchOrAbort(
puppeteer.launch({
...options,
@@ -202,13 +201,14 @@ async function launchOwnedBrowser(
const child = browser.process();
if (!child) throw new Error("A launched browser has no owned process.");
browsers.add(browser);
const watchdog = watchChromeTree(child, launchedAt);
const watchdog = watchChromeTree(child);
if (watchdog) watchdogs.set(browser, watchdog);
gracefulClose.set(browser, browser.close.bind(browser));
browser.close = () => closeManagedBrowser(browser);
const newPage = browser.newPage;
browser.newPage = async (...args) => closeOnRendererCrash(await newPage.apply(browser, args));
child.once("exit", () => {
watchdog?.release(true);
browsers.delete(browser);
destroyBrowserPipes(child);
});
@@ -300,6 +300,12 @@ function closeGracefully(browser: Browser): Promise<void> {
return (gracefulClose.get(browser) ?? (() => browser.close()))();
}
async function killWithChildren(child: ChildProcess): Promise<void> {
const ours = child instanceof ChildProcess && child.pid !== undefined;
if (process.platform !== "win32" || !ours) return void child.kill("SIGKILL");
await terminateWindowsProcessTree(child.pid).catch(() => child.kill("SIGKILL"));
}
async function closedWithoutKill(browser: Browser): Promise<boolean> {
const child = browser.process();
if (!child) throw new Error("A managed browser lost its owned process.");
@@ -319,7 +325,7 @@ async function closedWithoutKill(browser: Browser): Promise<boolean> {
grace,
]);
const clean = child.exitCode !== null || child.signalCode !== null;
if (!clean) child.kill("SIGKILL");
if (!clean) await killWithChildren(child);
clearTimeout(timer);
const exitLimit = new Promise<never>((_, reject) => {
timer = setTimeout(
+3 -12
View File
@@ -19,6 +19,7 @@ import {
import { getFreeDiskMb } from "../telemetry/system.js";
import { runCancellableProcess } from "../utils/cancellableProcess.js";
import { normalizeErrorMessage } from "../utils/errorMessage.js";
import { processReadArgs } from "../utils/windowsProcesses.js";
export type EnvironmentCheckLevel = "ok" | "warn" | "error";
@@ -281,18 +282,8 @@ async function windowsChromeVersionMajor(
try {
const { stdout } = await runCancellableProcess(
"powershell.exe",
[
"-NoProfile",
"-NonInteractive",
"-Command",
"(Get-Item -LiteralPath $env:HF_CHROME).VersionInfo.ProductVersion",
],
{
signal,
timeoutMs: 10_000,
maxBufferBytes: 4 * 1024,
env: { ...process.env, HF_CHROME: executablePath },
},
processReadArgs("version", executablePath),
{ signal, timeoutMs: 10_000, maxBufferBytes: 4 * 1024 },
);
return extractMajorVersion(stdout);
} catch {
@@ -1,11 +1,8 @@
import { spawn, type ChildProcess } from "node:child_process";
import { realpathSync } from "node:fs";
const SWEEP = `$b=[int]$env:HF_CHROME_PID; $x=$env:HF_CHROME_EXE; $t=[DateTimeOffset]::FromUnixTimeMilliseconds([int64]$env:HF_CHROME_SINCE).UtcDateTime; Get-CimInstance Win32_Process | Where-Object { ($_.ProcessId -eq $b -or $_.ParentProcessId -eq $b) -and $_.ExecutablePath -eq $x -and $_.CreationDate.ToUniversalTime() -ge $t } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;
import { ChildProcess, spawn } from "node:child_process";
const WATCHDOG = `let clean = false;
const done = () => {
if (!clean) require("node:child_process").spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", ${JSON.stringify(SWEEP)}], { windowsHide: true, timeout: 20000 });
if (!clean) require("node:child_process").spawnSync("taskkill", ["/PID", process.env.HF_CHROME_PID, "/T", "/F"], { windowsHide: true, stdio: "ignore", timeout: 20000 });
process.exit(0);
};
process.stdin.on("data", (data) => { clean ||= String(data).includes("clean"); });
@@ -16,29 +13,12 @@ export interface ChromeWatchdog {
release(clean: boolean): void;
}
function executableOf(chrome: ChildProcess): string | undefined {
try {
return realpathSync.native(chrome.spawnfile);
} catch {
export function watchChromeTree(chrome: ChildProcess): ChromeWatchdog | undefined {
if (process.platform !== "win32" || !(chrome instanceof ChildProcess) || chrome.pid === undefined)
return undefined;
}
}
/** Windows does not end a process's children with it, so Chrome's children outlive a killed CLI without this. */
export function watchChromeTree(
chrome: ChildProcess,
launchedAt: number,
): ChromeWatchdog | undefined {
const executable = process.platform === "win32" ? executableOf(chrome) : undefined;
if (!executable || chrome.pid === undefined) return undefined;
const watchdog = spawn(process.execPath, ["-e", WATCHDOG], {
detached: true,
env: {
...process.env,
HF_CHROME_PID: String(chrome.pid),
HF_CHROME_EXE: executable,
HF_CHROME_SINCE: String(launchedAt),
},
env: { ...process.env, HF_CHROME_PID: String(chrome.pid) },
stdio: ["pipe", "ignore", "ignore"],
windowsHide: true,
});
+19 -40
View File
@@ -4,6 +4,7 @@ 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 };
@@ -34,21 +35,12 @@ 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",
[
"-NoProfile",
"-NonInteractive",
"-Command",
`$p = Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}' -ErrorAction SilentlyContinue; if ($p) { $p.CreationDate.ToFileTimeUtc() }`,
],
{
encoding: "utf8",
timeout: 2000,
stdio: ["pipe", "pipe", "ignore"],
windowsHide: true,
},
).trim();
const created = execFileSync("powershell.exe", processReadArgs("identity", pid), {
encoding: "utf8",
timeout: 2000,
stdio: ["pipe", "pipe", "ignore"],
windowsHide: true,
}).trim();
return created ? `windows:${created}` : null;
}
@@ -118,16 +110,12 @@ 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",
[
"-NoProfile",
"-NonInteractive",
"-Command",
'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId) $($_.CreationDate.ToFileTimeUtc())" }',
],
{ encoding: "utf8", timeout: 2000, stdio: ["pipe", "pipe", "ignore"], windowsHide: true },
);
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+/))
@@ -174,21 +162,12 @@ export function processParentPid(pid: number): number | null {
try {
const output =
process.platform === "win32"
? execFileSync(
"powershell.exe",
[
"-NoProfile",
"-NonInteractive",
"-Command",
`$p = Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}' -ErrorAction SilentlyContinue; if ($p) { $p.ParentProcessId }`,
],
{
encoding: "utf8",
timeout: 2000,
stdio: ["pipe", "pipe", "ignore"],
windowsHide: true,
},
)
? 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,
@@ -16,10 +16,10 @@ describe("Windows orphan-cleanup child-process options", () => {
Object.defineProperty(process, "platform", { value: "win32", configurable: true });
execFileSyncMock.mockImplementation((command: string, args: string[]) => {
if (command === "taskkill") return Buffer.alloc(0);
const script = args.at(-1) ?? "";
if (script.includes("CreationDate")) return "123456\n";
if (script.includes("ProcessId = 400")) return "300\n";
if (script.includes("ProcessId = 300")) return "200\n";
const [read, pid] = args.slice(-2);
if (read === "identity") return "123456\n";
if (read === "parent" && pid === "400") return "300\n";
if (read === "parent" && pid === "300") return "200\n";
return "1\n";
});
});
@@ -41,8 +41,7 @@ describe("Windows orphan-cleanup child-process options", () => {
it("captures the complete Windows ancestor chain with one hidden PowerShell lookup", () => {
execFileSyncMock.mockImplementation((_command: string, args: string[]) => {
const script = args.at(-1) ?? "";
if (script.includes("Get-CimInstance Win32_Process |")) {
if (args.includes("table")) {
return "400 300 444\n300 200 333\n200 1 222\n";
}
return "";
@@ -0,0 +1,58 @@
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { processReadArgs } from "./windowsProcesses.js";
const src = fileURLToPath(new URL("../", import.meta.url));
const SCRIPT = join(src, "utils", "processes.ps1");
// Norton 360's behaviour shield flagged powershell.exe started with process-killing command text (Get-CimInstance
// Win32_Process + Stop-Process -Force); its file shield reads script files.
const SHIPPED = readdirSync(src, { recursive: true, withFileTypes: true })
.filter((each) => each.isFile() && /\.(ts|mjs|ps1)$/.test(each.name))
.filter((each) => !/\.(test|fixture)\.ts$/.test(each.name))
.map((each) => join(each.parentPath, each.name));
const code = (file: string) =>
readFileSync(file, "utf8")
.split("\n")
.filter((line) => !/^\s*(\/\/|#|\*|\/\*)/.test(line))
.join("\n");
describe("the PowerShell the CLI starts on Windows", () => {
it("is only ever the shipped processes.ps1, run as a file with plain arguments", () => {
for (const args of [processReadArgs("table"), processReadArgs("identity", 42)]) {
expect(args[args.indexOf("-File") + 1]).toBe(SCRIPT);
expect(args.some((arg) => /^-(command|encodedcommand|ec)$/i.test(arg))).toBe(false);
}
expect(processReadArgs("identity", 42).slice(-2)).toEqual(["identity", "42"]);
expect(existsSync(SCRIPT)).toBe(true);
const copy = readFileSync(join(src, "..", "scripts", "build-copy.mjs"), "utf8");
expect(copy).toContain("processes.ps1");
});
it("is started only with processReadArgs, so no flag or plain argument can carry command text", () => {
let starts = 0;
for (const file of SHIPPED) {
const text = code(file);
for (const start of text.matchAll(/["'`]powershell(?:\.exe)?["'`]\s*,\s*/gi)) {
starts++;
const args = text.slice(start.index + start[0].length);
expect(args.startsWith("processReadArgs("), `${file}: ${args.slice(0, 60)}`).toBe(true);
}
}
expect(starts).toBeGreaterThanOrEqual(5);
});
it("is never given command text, and nothing outside processes.ps1 reads or ends processes through it", () => {
expect(SHIPPED.length).toBeGreaterThan(100);
for (const file of SHIPPED) {
const text = code(file);
expect(text, file).not.toMatch(
/["'`]-(Command|EncodedCommand|ec)["'`]|FromBase64String|\[scriptblock\]::Create|Add-Type|Invoke-Expression|Stop-Process/i,
);
if (file !== SCRIPT) expect(text, file).not.toMatch(/Get-CimInstance|Win32_Process/);
}
});
});
+2 -9
View File
@@ -1,5 +1,6 @@
import { execFileSync, type ChildProcess } from "node:child_process";
import { readFileSync, readdirSync } from "node:fs";
import { processReadArgs } from "./windowsProcesses.js";
export function testProcessIsAlive(pid: number): boolean {
if (process.platform === "linux") {
@@ -50,15 +51,7 @@ function processTable(): Map<number, TableEntry> {
}
const listing =
process.platform === "win32"
? execFileSync(
"powershell.exe",
[
"-NoProfile",
"-Command",
'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId) $($_.CreationDate.Ticks) $($_.Name)" }',
],
{ encoding: "utf8" },
)
? execFileSync("powershell.exe", processReadArgs("table"), { encoding: "utf8" })
: execFileSync("ps", ["-A", "-o", "pid=,ppid=,comm="], { encoding: "utf8" });
return parseProcessListing(listing, process.platform === "win32");
}
+20
View File
@@ -0,0 +1,20 @@
# The CLI's reads of Windows' process table and a file's version (utils/windowsProcesses.ts), run with -File; nothing
# a call passes is run as code. identity <id>: its start as a FILETIME. parent <id>: its parent's id.
# table: `id parent start name` lines. version <path>: the file's product version.
param([ValidateSet('identity', 'parent', 'table', 'version')][string]$Read, [string]$Target = '')
$ErrorActionPreference = 'SilentlyContinue'
function Find-Process([string]$Id) {
if ($Id -match '^\d+$') { Get-CimInstance Win32_Process -Filter "ProcessId=$([int]$Id)" }
}
switch ($Read) {
'identity' { $process = Find-Process $Target; if ($process) { $process.CreationDate.ToFileTimeUtc() } }
'parent' { $process = Find-Process $Target; if ($process) { $process.ParentProcessId } }
'table' {
Get-CimInstance Win32_Process | ForEach-Object {
'{0} {1} {2} {3}' -f $_.ProcessId, $_.ParentProcessId, $_.CreationDate.ToFileTimeUtc(), $_.Name
}
}
'version' { if ($Target) { (Get-Item -LiteralPath $Target).VersionInfo.ProductVersion } }
}
@@ -0,0 +1,17 @@
import { fileURLToPath } from "node:url";
type ProcessRead = "identity" | "parent" | "table" | "version";
/** One read of processes.ps1, shipped beside this code; antivirus flags PowerShell given command text. */
export function processReadArgs(read: ProcessRead, target?: string | number): string[] {
return [
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-File",
fileURLToPath(new URL("./processes.ps1", import.meta.url)),
read,
...(target === undefined ? [] : [String(target)]),
];
}