diff --git a/packages/cli/scripts/build-copy.mjs b/packages/cli/scripts/build-copy.mjs index 6091a07901..f7168db2d0 100644 --- a/packages/cli/scripts/build-copy.mjs +++ b/packages/cli/scripts/build-copy.mjs @@ -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")); diff --git a/packages/cli/src/browser/launch.boundedClose.test.ts b/packages/cli/src/browser/launch.boundedClose.test.ts index 7607926b27..e5817ca958 100644 --- a/packages/cli/src/browser/launch.boundedClose.test.ts +++ b/packages/cli/src/browser/launch.boundedClose.test.ts @@ -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"); + } +}); diff --git a/packages/cli/src/browser/launch.foreignPid.test.ts b/packages/cli/src/browser/launch.foreignPid.test.ts new file mode 100644 index 0000000000..0bf88c4282 --- /dev/null +++ b/packages/cli/src/browser/launch.foreignPid.test.ts @@ -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()), + 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(); +}); diff --git a/packages/cli/src/browser/launch.ts b/packages/cli/src/browser/launch.ts index 1263d9ff57..4badaacea0 100644 --- a/packages/cli/src/browser/launch.ts +++ b/packages/cli/src/browser/launch.ts @@ -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 { return (gracefulClose.get(browser) ?? (() => browser.close()))(); } +async function killWithChildren(child: ChildProcess): Promise { + 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 { 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 { 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((_, reject) => { timer = setTimeout( diff --git a/packages/cli/src/browser/preflight.ts b/packages/cli/src/browser/preflight.ts index 48779d2ea0..4275101900 100644 --- a/packages/cli/src/browser/preflight.ts +++ b/packages/cli/src/browser/preflight.ts @@ -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 { diff --git a/packages/cli/src/browser/windowsChromeWatchdog.ts b/packages/cli/src/browser/windowsChromeWatchdog.ts index 7838e9b7ba..6a9a6f0498 100644 --- a/packages/cli/src/browser/windowsChromeWatchdog.ts +++ b/packages/cli/src/browser/windowsChromeWatchdog.ts @@ -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, }); diff --git a/packages/cli/src/utils/orphanCleanup.ts b/packages/cli/src/utils/orphanCleanup.ts index 8cd2cd6b03..45c2bc0c9f 100644 --- a/packages/cli/src/utils/orphanCleanup.ts +++ b/packages/cli/src/utils/orphanCleanup.ts @@ -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, diff --git a/packages/cli/src/utils/orphanCleanup.windowsHide.test.ts b/packages/cli/src/utils/orphanCleanup.windowsHide.test.ts index fc526600d8..0b01567a37 100644 --- a/packages/cli/src/utils/orphanCleanup.windowsHide.test.ts +++ b/packages/cli/src/utils/orphanCleanup.windowsHide.test.ts @@ -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 ""; diff --git a/packages/cli/src/utils/powershellFootprint.test.ts b/packages/cli/src/utils/powershellFootprint.test.ts new file mode 100644 index 0000000000..a447962137 --- /dev/null +++ b/packages/cli/src/utils/powershellFootprint.test.ts @@ -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/); + } + }); +}); diff --git a/packages/cli/src/utils/processTestUtils.ts b/packages/cli/src/utils/processTestUtils.ts index d3156acc47..80fa58fe33 100644 --- a/packages/cli/src/utils/processTestUtils.ts +++ b/packages/cli/src/utils/processTestUtils.ts @@ -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 { } 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"); } diff --git a/packages/cli/src/utils/processes.ps1 b/packages/cli/src/utils/processes.ps1 new file mode 100644 index 0000000000..5b485d53a9 --- /dev/null +++ b/packages/cli/src/utils/processes.ps1 @@ -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 : its start as a FILETIME. parent : its parent's id. +# table: `id parent start name` lines. version : 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 } } +} diff --git a/packages/cli/src/utils/windowsProcesses.ts b/packages/cli/src/utils/windowsProcesses.ts new file mode 100644 index 0000000000..5423aefdcd --- /dev/null +++ b/packages/cli/src/utils/windowsProcesses.ts @@ -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)]), + ]; +}