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
+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)]),
];
}