From 5f0a748c868ce0527fa6353574059b8daed445f8 Mon Sep 17 00:00:00 2001 From: James Date: Sun, 15 Nov 2026 00:13:23 +0000 Subject: [PATCH 1/3] fix(cli): start helper programs only from trusted PATH folders on every platform At startup the CLI and its worker entry points rewrite their own PATH to absolute folders outside the working directory, on every platform, so a program planted in the project (a relative or empty PATH entry, node_modules/.bin, or any folder inside the cwd) is never run by name. Child processes inherit the trimmed PATH. media-use reuses the same helper instead of its private copy. doctor resolves docker with findTrustedExecutable and runs it by absolute path with execFileSync, no shell. A docker found only in the project's node_modules/.bin is reported as not found, with a hint that it was skipped. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/commands/doctor.test.ts | 81 ++++++++++++++++++- packages/cli/src/commands/doctor.ts | 50 ++++++++---- packages/cli/src/commands/media-use.ts | 17 ++-- .../cli/src/utils/windowsExeSearch.test.ts | 80 +++++++++++++++++- packages/cli/src/utils/windowsExeSearch.ts | 28 ++++++- 5 files changed, 223 insertions(+), 33 deletions(-) diff --git a/packages/cli/src/commands/doctor.test.ts b/packages/cli/src/commands/doctor.test.ts index b5cd369c708..48d567a79a8 100644 --- a/packages/cli/src/commands/doctor.test.ts +++ b/packages/cli/src/commands/doctor.test.ts @@ -3,19 +3,23 @@ import { mkdirSync, mkdtempSync, readFileSync, + realpathSync, rmSync, utimesSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { delimiter, join } from "node:path"; +import type { ExecFileSyncOptions } from "node:child_process"; import { pathToFileURL } from "node:url"; -import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { describe, it, expect, beforeEach, afterEach, onTestFinished, vi } from "vitest"; import { optionalPackageDir } from "../utils/optionalPackages.js"; import { TESTED_FFMPEG_VERSION, buildDoctorReport, ffmpegDoctorDetail, + checkDocker, + checkDockerRunning, checkFramesCache, checkOptionalPackage, redactHome, @@ -84,6 +88,79 @@ describe("redactHome", () => { }); }); +describe("Docker checks", () => { + const dockerName = process.platform === "win32" ? "docker.exe" : "docker"; + + type RunFile = (file: string, args: string[], options: ExecFileSyncOptions) => string; + + function dir(prefix: string): string { + const path = realpathSync(mkdtempSync(join(tmpdir(), prefix))); + onTestFinished(() => rmSync(path, { recursive: true, force: true })); + return path; + } + + function projectWithDocker(): { projectBin: string; projectDocker: string } { + const project = dir("hf-doctor-project-"); + const projectBin = join(project, "node_modules", ".bin"); + mkdirSync(projectBin, { recursive: true }); + const projectDocker = join(projectBin, dockerName); + writeFileSync(projectDocker, "#!/bin/sh\n", { mode: 0o755 }); + vi.spyOn(process, "cwd").mockReturnValue(project); + onTestFinished(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + }); + return { projectBin, projectDocker }; + } + + it("runs docker by its absolute path from a folder outside the project, with no shell", () => { + const { projectBin } = projectWithDocker(); + const outside = dir("hf-doctor-bin-"); + const docker = join(outside, dockerName); + writeFileSync(docker, "#!/bin/sh\n", { mode: 0o755 }); + vi.stubEnv("PATH", [projectBin, outside].join(delimiter)); + const run = vi.fn(() => "Docker version 27.0.0\n"); + + expect(checkDocker(undefined, run)).toEqual({ ok: true, detail: "Docker version 27.0.0" }); + expect(checkDockerRunning(undefined, run)).toEqual({ ok: true, detail: "Running" }); + + expect(run.mock.calls.map(([file, args]) => [file, args])).toEqual([ + [docker, ["--version"]], + [docker, ["info"]], + ]); + for (const [, , options] of run.mock.calls) expect(options).not.toHaveProperty("shell"); + }); + + it("reports a docker found only inside the project as missing and says it was skipped", () => { + const { projectBin, projectDocker } = projectWithDocker(); + vi.stubEnv("PATH", [projectBin, "."].join(delimiter)); + const run = vi.fn(() => ""); + + const result = checkDocker(undefined, run); + + expect(result.ok).toBe(false); + expect(result.detail).toBe("Not found"); + expect(result.hint).toContain(projectDocker); + expect(result.hint).toContain("outside the project"); + expect(result.hint).toContain("https://docs.docker.com/get-docker/"); + expect(checkDockerRunning(undefined, run)).toMatchObject({ ok: false, detail: "Not running" }); + expect(run).not.toHaveBeenCalled(); + }); + + it("keeps the plain install hint when there is no docker anywhere", () => { + vi.spyOn(process, "cwd").mockReturnValue(dir("hf-doctor-empty-")); + onTestFinished(() => { + vi.restoreAllMocks(); + }); + + expect(checkDocker(() => undefined)).toEqual({ + ok: false, + detail: "Not found", + hint: "https://docs.docker.com/get-docker/", + }); + }); +}); + describe("parseToolVersion", () => { it("extracts ffmpeg version from full copyright line", () => { expect( diff --git a/packages/cli/src/commands/doctor.ts b/packages/cli/src/commands/doctor.ts index f008e2cf893..feb687f9536 100644 --- a/packages/cli/src/commands/doctor.ts +++ b/packages/cli/src/commands/doctor.ts @@ -1,10 +1,10 @@ // fallow-ignore-file complexity import { defineCommand } from "../utils/defineCommand.js"; -import { execSync } from "node:child_process"; +import { execFileSync, type ExecFileSyncOptions } from "node:child_process"; import * as fs from "node:fs"; import { existsSync } from "node:fs"; import { platform } from "node:os"; -import { dirname } from "node:path"; +import { dirname, join } from "node:path"; import { resolveExtractCacheDir } from "@hyperframes/engine"; import { findTrustedExecutable } from "@hyperframes/parsers/ff-binaries"; import type { Example } from "./_examples.js"; @@ -62,22 +62,44 @@ export function ffmpegDoctorDetail(detail: string): string { : `${detail}; loudness numbers are only comparable on ${TESTED_FFMPEG_VERSION}`; } -function checkDocker(): CheckResult { +const DOCKER_INSTALL_HINT = "https://docs.docker.com/get-docker/"; + +type RunFile = (file: string, args: string[], options: ExecFileSyncOptions) => string | Buffer; + +const findDocker = (): string | undefined => findTrustedExecutable("docker"); + +function dockerInsideProject(cwd = process.cwd()): string | undefined { + const names = process.platform === "win32" ? ["docker.exe", "docker.cmd"] : ["docker"]; + return names.map((name) => join(cwd, "node_modules", ".bin", name)).find(existsSync); +} + +function dockerNotFound(): CheckResult { + const skipped = dockerInsideProject(); + return { + ok: false, + detail: "Not found", + hint: skipped + ? `Skipped ${skipped}: the CLI only runs helper programs from folders outside the project. ${DOCKER_INSTALL_HINT}` + : DOCKER_INSTALL_HINT, + }; +} + +export function checkDocker(find = findDocker, run: RunFile = execFileSync): CheckResult { + const docker = find(); + if (!docker) return dockerNotFound(); try { - const version = execSync("docker --version", { encoding: "utf-8", timeout: 5000 }).trim(); - return { ok: true, detail: version }; + const version = run(docker, ["--version"], { encoding: "utf-8", timeout: 5000 }); + return { ok: true, detail: version.toString().trim() }; } catch { - return { - ok: false, - detail: "Not found", - hint: "https://docs.docker.com/get-docker/", - }; + return dockerNotFound(); } } -function checkDockerRunning(): CheckResult { +export function checkDockerRunning(find = findDocker, run: RunFile = execFileSync): CheckResult { try { - execSync("docker info", { stdio: "pipe", timeout: 5000 }); + const docker = find(); + if (!docker) throw new Error("docker not found"); + run(docker, ["info"], { stdio: "pipe", timeout: 5000 }); return { ok: true, detail: "Running" }; } catch { return { @@ -432,8 +454,8 @@ export default defineCommand({ }); } for (const check of [ - { name: "Docker", run: checkDocker }, - { name: "Docker running", run: checkDockerRunning }, + { name: "Docker", run: () => checkDocker() }, + { name: "Docker running", run: () => checkDockerRunning() }, ]) { const result = await check.run(); outcomes.push({ diff --git a/packages/cli/src/commands/media-use.ts b/packages/cli/src/commands/media-use.ts index d2f8ea0f3ba..a6fef0cfd5d 100644 --- a/packages/cli/src/commands/media-use.ts +++ b/packages/cli/src/commands/media-use.ts @@ -1,12 +1,14 @@ import { defineCommand } from "../utils/defineCommand.js"; -import { delimiter, dirname, join, resolve } from "node:path"; +import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { spawnSync } from "node:child_process"; import { existsSync } from "node:fs"; import { finishCommand } from "../utils/commandResult.js"; import { withMediaAuthEnvironment } from "../auth/media-environment.js"; -import { trustedPathDirs } from "@hyperframes/parsers/ff-binaries"; -import { skipWorkingDirectoryInExeSearch } from "../utils/windowsExeSearch.js"; +import { + skipWorkingDirectoryInExeSearch, + withOnlyTrustedPathFolders, +} from "../utils/windowsExeSearch.js"; const MEDIA_USE_ARGS = { type: { type: "string", description: "What to find: bgm, sfx, image, icon, logo, voice" }, @@ -77,15 +79,6 @@ export function mediaUseVerbFlags(verb: MediaUseVerb): string[] { return verb === "resolve" ? [] : [`--${verb}`]; } -const NEVER_CREATED_PATH_FOLDER = fileURLToPath(new URL("no-trusted-path-folder", import.meta.url)); - -function withOnlyTrustedPathFolders(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { - const pathKey = Object.keys(env).find((name) => name.toUpperCase() === "PATH"); - if (!pathKey) return { ...env }; - const dirs = trustedPathDirs(env[pathKey]); - return { ...env, [pathKey]: dirs.length > 0 ? dirs.join(delimiter) : NEVER_CREATED_PATH_FOLDER }; -} - export function mediaUseEngineEnv( env: NodeJS.ProcessEnv, entry: string | undefined = process.argv[1], diff --git a/packages/cli/src/utils/windowsExeSearch.test.ts b/packages/cli/src/utils/windowsExeSearch.test.ts index f43117135af..d38ad0eb960 100644 --- a/packages/cli/src/utils/windowsExeSearch.test.ts +++ b/packages/cli/src/utils/windowsExeSearch.test.ts @@ -1,8 +1,26 @@ -import { readFileSync } from "node:fs"; -import { dirname, join } from "node:path"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { delimiter, dirname, isAbsolute, join } from "node:path"; import { fileURLToPath } from "node:url"; -import { describe, expect, it } from "vitest"; -import { skipWorkingDirectoryInExeSearch } from "./windowsExeSearch.js"; +import { describe, expect, it, onTestFinished, vi } from "vitest"; +import { searchOnlyTrustedFolders, skipWorkingDirectoryInExeSearch } from "./windowsExeSearch.js"; + +function tempDir(prefix: string): string { + const dir = realpathSync(mkdtempSync(join(tmpdir(), prefix))); + onTestFinished(() => rmSync(dir, { recursive: true, force: true })); + return dir; +} + +function inProject(): { project: string; outside: string[] } { + const project = tempDir("hf-exe-search-project-"); + const outside = [tempDir("hf-exe-search-a-"), tempDir("hf-exe-search-b-")]; + mkdirSync(join(project, "node_modules", ".bin"), { recursive: true }); + vi.spyOn(process, "cwd").mockReturnValue(project); + onTestFinished(() => { + vi.restoreAllMocks(); + }); + return { project, outside }; +} describe("skipWorkingDirectoryInExeSearch", () => { it("turns off the working-directory lookup on Windows", () => { @@ -24,6 +42,60 @@ describe("skipWorkingDirectoryInExeSearch", () => { }); }); +describe("searchOnlyTrustedFolders", () => { + it.each(["linux", "darwin", "win32"] as const)( + "keeps only absolute PATH folders outside the project, in order, on %s", + (platform) => { + const { project, outside } = inProject(); + const env: NodeJS.ProcessEnv = { + PATH: [ + "", + ".", + join("node_modules", ".bin"), + outside[0], + join(project, "node_modules", ".bin"), + project, + outside[1], + ].join(delimiter), + }; + + searchOnlyTrustedFolders(env, platform); + + expect(env.PATH).toBe([outside[0], outside[1]].join(delimiter)); + }, + ); + + it("finds the PATH key whatever its case, as Windows spells it Path", () => { + const { project, outside } = inProject(); + const env: NodeJS.ProcessEnv = { Path: [project, outside[0], "."].join(delimiter) }; + + searchOnlyTrustedFolders(env, "win32"); + + expect(env).toEqual({ Path: outside[0], NoDefaultCurrentDirectoryInExePath: "1" }); + }); + + it("never leaves an empty PATH, which would mean the working directory", () => { + const { project } = inProject(); + const env: NodeJS.ProcessEnv = { PATH: ["", ".", project].join(delimiter) }; + + searchOnlyTrustedFolders(env, "linux"); + + expect(env.PATH?.split(delimiter)).toHaveLength(1); + expect(isAbsolute(env.PATH ?? "")).toBe(true); + expect(existsSync(env.PATH ?? "")).toBe(false); + expect(env.PATH?.startsWith(project)).toBe(false); + }); + + it("adds no PATH when there was none", () => { + inProject(); + const env: NodeJS.ProcessEnv = {}; + + searchOnlyTrustedFolders(env, "linux"); + + expect(env).toEqual({}); + }); +}); + describe("program entries", () => { it("each one that starts its own process turns the lookup off before it spawns anything", () => { const cliRoot = join(dirname(fileURLToPath(import.meta.url)), "..", ".."); diff --git a/packages/cli/src/utils/windowsExeSearch.ts b/packages/cli/src/utils/windowsExeSearch.ts index 93c0120c229..02022c36b5e 100644 --- a/packages/cli/src/utils/windowsExeSearch.ts +++ b/packages/cli/src/utils/windowsExeSearch.ts @@ -1,3 +1,20 @@ +import { delimiter } from "node:path"; +import { fileURLToPath } from "node:url"; +import { trustedPathDirs } from "@hyperframes/parsers/ff-binaries"; + +const NEVER_CREATED_PATH_FOLDER = fileURLToPath(new URL("no-trusted-path-folder", import.meta.url)); + +function pathKeyOf(env: NodeJS.ProcessEnv): string | undefined { + return Object.keys(env).find((name) => name.toUpperCase() === "PATH"); +} + +export function withOnlyTrustedPathFolders(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + const pathKey = pathKeyOf(env); + if (!pathKey) return { ...env }; + const dirs = trustedPathDirs(env[pathKey]); + return { ...env, [pathKey]: dirs.length > 0 ? dirs.join(delimiter) : NEVER_CREATED_PATH_FOLDER }; +} + export function skipWorkingDirectoryInExeSearch( env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform, @@ -5,4 +22,13 @@ export function skipWorkingDirectoryInExeSearch( if (platform === "win32") env.NoDefaultCurrentDirectoryInExePath ??= "1"; } -skipWorkingDirectoryInExeSearch(); +export function searchOnlyTrustedFolders( + env: NodeJS.ProcessEnv = process.env, + platform: NodeJS.Platform = process.platform, +): void { + const pathKey = pathKeyOf(env); + if (pathKey) env[pathKey] = withOnlyTrustedPathFolders(env)[pathKey]; + skipWorkingDirectoryInExeSearch(env, platform); +} + +searchOnlyTrustedFolders(); From 3c2bd8e7ac821ccef88b2403d14bbffe48f73a10 Mon Sep 17 00:00:00 2001 From: James Date: Sun, 15 Nov 2026 00:30:00 +0000 Subject: [PATCH 2/3] fix(cli): keep stale-install detection and Windows system folders after PATH trim The stale hyperframes check for reverse start reads the PATH the process started with, so an older copy in the project's node_modules/.bin is still reported. It only reads the filesystem and never runs that copy. On Windows the trim now keeps %SystemRoot%, System32, System32\Wbem and the WindowsPowerShell folder even when the CLI starts inside them, so an elevated prompt in C:\Windows\System32 can still run cmd, taskkill, tasklist, powershell and tar. PATH entries wrapped in double quotes are unquoted before the check instead of being dropped. PATH order is kept. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/commands/media-use.ts | 2 +- .../cli/src/utils/installerDetection.test.ts | 34 +++++++++- packages/cli/src/utils/installerDetection.ts | 5 +- .../cli/src/utils/windowsExeSearch.test.ts | 66 +++++++++++++++++-- packages/cli/src/utils/windowsExeSearch.ts | 61 ++++++++++++++--- 5 files changed, 148 insertions(+), 20 deletions(-) diff --git a/packages/cli/src/commands/media-use.ts b/packages/cli/src/commands/media-use.ts index a6fef0cfd5d..8def789a508 100644 --- a/packages/cli/src/commands/media-use.ts +++ b/packages/cli/src/commands/media-use.ts @@ -84,7 +84,7 @@ export function mediaUseEngineEnv( entry: string | undefined = process.argv[1], platform: NodeJS.Platform = process.platform, ): NodeJS.ProcessEnv { - const scoped = withOnlyTrustedPathFolders(env); + const scoped = withOnlyTrustedPathFolders(env, platform); skipWorkingDirectoryInExeSearch(scoped, platform); if (!entry || /\.[cm]?ts$/.test(entry)) return scoped; return { ...scoped, HYPERFRAMES_CLI_ENTRY: resolve(entry) }; diff --git a/packages/cli/src/utils/installerDetection.test.ts b/packages/cli/src/utils/installerDetection.test.ts index 3714315e6e5..e09ac053a7b 100644 --- a/packages/cli/src/utils/installerDetection.test.ts +++ b/packages/cli/src/utils/installerDetection.test.ts @@ -1,7 +1,7 @@ import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { delimiter, dirname, join } from "node:path"; -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; // The module inspects `process.argv[1]` + `realpathSync`. We stub both so // each test describes a hypothetical install layout without touching the @@ -266,9 +266,13 @@ describe("runningInstall: which binary runs, and the command that updates it", ( describe("shadowingInstall: the older global install a plain `npx hyperframes` runs instead", () => { const saved = { argv1: process.argv[1], path: process.env["PATH"] }; + beforeEach(() => { + vi.resetModules(); + }); afterEach(() => { process.argv[1] = saved.argv1 ?? ""; process.env["PATH"] = saved.path; + vi.restoreAllMocks(); }); /** An npx copy running now, and a global npm install of `globalVersion` first on PATH. */ @@ -335,6 +339,26 @@ describe("shadowingInstall: the older global install a plain `npx hyperframes` r }); }); + it("still sees an older copy in the project's node_modules/.bin after startup trims PATH", async () => { + const root = layout(null); + const pkg = onPathInstead(root, "app/node_modules/hyperframes"); + writeFileSync(join(root, "app/bun.lock"), ""); + const projectBin = join(root, "app/node_modules/.bin"); + mkdirSync(projectBin, { recursive: true }); + symlinkSync(join(pkg, "bin/hyperframes.mjs"), join(projectBin, "hyperframes")); + const [npxBin] = (process.env["PATH"] ?? "").split(delimiter); + process.env["PATH"] = [npxBin, projectBin].join(delimiter); + vi.spyOn(process, "cwd").mockReturnValue(join(root, "app")); + + const { shadowingInstall } = await import("./installerDetection.js"); + + expect(process.env["PATH"]).toBe(npxBin); + expect(shadowingInstall("0.9.29")).toEqual({ + version: "0.9.8", + updateCommand: "bun add hyperframes@0.9.29", + }); + }); + it("stays quiet when no manager is known to move the older install", async () => { const root = layout(null); onPathInstead(root, "opt/hyperframes"); @@ -342,11 +366,15 @@ describe("shadowingInstall: the older global install a plain `npx hyperframes` r expect(shadowingInstall("0.9.29")).toBeNull(); }); - it("stays quiet when the global install is not older, or there is none", async () => { - const { shadowingInstall } = await import("./installerDetection.js"); + it("stays quiet when the global install is not older", async () => { layout("0.9.29"); + const { shadowingInstall } = await import("./installerDetection.js"); expect(shadowingInstall("0.9.29")).toBeNull(); + }); + + it("stays quiet when there is no global install", async () => { layout(null); + const { shadowingInstall } = await import("./installerDetection.js"); expect(shadowingInstall("0.9.29")).toBeNull(); }); diff --git a/packages/cli/src/utils/installerDetection.ts b/packages/cli/src/utils/installerDetection.ts index 79884d2cd8c..c38e13aa3d4 100644 --- a/packages/cli/src/utils/installerDetection.ts +++ b/packages/cli/src/utils/installerDetection.ts @@ -10,6 +10,7 @@ import { existsSync, readFileSync, realpathSync } from "node:fs"; import { delimiter, dirname, join, posix } from "node:path"; import { compareVersions } from "compare-versions"; import { isSafeVersion } from "./safeVersion.js"; +import { originalPath } from "./windowsExeSearch.js"; export type InstallerKind = "npm" | "bun" | "pnpm" | "brew" | "skip"; @@ -327,8 +328,8 @@ function resolvedOrNull(path: string): string | null { } /** The first `hyperframes` on PATH that is neither this copy nor another npx/bunx cache copy. */ -function firstGlobalOnPath(self: string | null): string | null { - for (const dir of (process.env["PATH"] ?? "").split(delimiter)) { +function firstGlobalOnPath(self: string | null, pathValue = originalPath()): string | null { + for (const dir of pathValue.split(delimiter)) { const real = dir ? resolvedOrNull(join(dir, "hyperframes")) : null; if (real && real !== self && !isEphemeralExec(real)) return real; } diff --git a/packages/cli/src/utils/windowsExeSearch.test.ts b/packages/cli/src/utils/windowsExeSearch.test.ts index d38ad0eb960..5e38edf5e97 100644 --- a/packages/cli/src/utils/windowsExeSearch.test.ts +++ b/packages/cli/src/utils/windowsExeSearch.test.ts @@ -1,9 +1,13 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; -import { delimiter, dirname, isAbsolute, join } from "node:path"; +import { delimiter, dirname, isAbsolute, join, win32 } from "node:path"; import { fileURLToPath } from "node:url"; import { describe, expect, it, onTestFinished, vi } from "vitest"; -import { searchOnlyTrustedFolders, skipWorkingDirectoryInExeSearch } from "./windowsExeSearch.js"; +import { + searchOnlyTrustedFolders, + skipWorkingDirectoryInExeSearch, + withOnlyTrustedPathFolders, +} from "./windowsExeSearch.js"; function tempDir(prefix: string): string { const dir = realpathSync(mkdtempSync(join(tmpdir(), prefix))); @@ -47,6 +51,7 @@ describe("searchOnlyTrustedFolders", () => { "keeps only absolute PATH folders outside the project, in order, on %s", (platform) => { const { project, outside } = inProject(); + const separator = platform === "win32" ? win32.delimiter : delimiter; const env: NodeJS.ProcessEnv = { PATH: [ "", @@ -56,24 +61,75 @@ describe("searchOnlyTrustedFolders", () => { join(project, "node_modules", ".bin"), project, outside[1], - ].join(delimiter), + ].join(separator), }; searchOnlyTrustedFolders(env, platform); - expect(env.PATH).toBe([outside[0], outside[1]].join(delimiter)); + expect(env.PATH).toBe([outside[0], outside[1]].join(separator)); }, ); it("finds the PATH key whatever its case, as Windows spells it Path", () => { const { project, outside } = inProject(); - const env: NodeJS.ProcessEnv = { Path: [project, outside[0], "."].join(delimiter) }; + const env: NodeJS.ProcessEnv = { Path: [project, outside[0], "."].join(win32.delimiter) }; searchOnlyTrustedFolders(env, "win32"); expect(env).toEqual({ Path: outside[0], NoDefaultCurrentDirectoryInExePath: "1" }); }); + it("accepts a Windows PATH entry wrapped in double quotes", () => { + const { project, outside } = inProject(); + const env: NodeJS.ProcessEnv = { + Path: [`"${outside[0]}"`, `"${project}"`, outside[1]].join(win32.delimiter), + }; + + expect(withOnlyTrustedPathFolders(env, "win32").Path).toBe( + [outside[0], outside[1]].join(win32.delimiter), + ); + }); + + it("keeps the Windows system folders when started from inside System32", () => { + vi.spyOn(process, "cwd").mockReturnValue("C:\\Windows\\System32"); + onTestFinished(() => { + vi.restoreAllMocks(); + }); + const env: NodeJS.ProcessEnv = { + SystemRoot: "C:\\Windows", + Path: [ + "C:\\Windows\\system32", + ".", + "C:\\Windows", + "C:/Windows/System32/Wbem/", + "C:\\Windows\\System32\\evil", + "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\", + ].join(win32.delimiter), + }; + + expect(withOnlyTrustedPathFolders(env, "win32").Path).toBe( + [ + "C:\\Windows\\system32", + "C:\\Windows", + "C:/Windows/System32/Wbem/", + "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\", + ].join(win32.delimiter), + ); + }); + + it("takes the system folders from SystemRoot", () => { + vi.spyOn(process, "cwd").mockReturnValue("C:\\Windows\\System32"); + onTestFinished(() => { + vi.restoreAllMocks(); + }); + const env: NodeJS.ProcessEnv = { + SYSTEMROOT: "D:\\WinNT", + Path: ["C:\\Windows\\System32", "D:\\WinNT\\System32"].join(win32.delimiter), + }; + + expect(withOnlyTrustedPathFolders(env, "win32").Path).toBe("D:\\WinNT\\System32"); + }); + it("never leaves an empty PATH, which would mean the working directory", () => { const { project } = inProject(); const env: NodeJS.ProcessEnv = { PATH: ["", ".", project].join(delimiter) }; diff --git a/packages/cli/src/utils/windowsExeSearch.ts b/packages/cli/src/utils/windowsExeSearch.ts index 02022c36b5e..63c84cf5a74 100644 --- a/packages/cli/src/utils/windowsExeSearch.ts +++ b/packages/cli/src/utils/windowsExeSearch.ts @@ -1,18 +1,54 @@ -import { delimiter } from "node:path"; +import { delimiter, win32 } from "node:path"; import { fileURLToPath } from "node:url"; import { trustedPathDirs } from "@hyperframes/parsers/ff-binaries"; const NEVER_CREATED_PATH_FOLDER = fileURLToPath(new URL("no-trusted-path-folder", import.meta.url)); -function pathKeyOf(env: NodeJS.ProcessEnv): string | undefined { - return Object.keys(env).find((name) => name.toUpperCase() === "PATH"); +function keyOf(env: NodeJS.ProcessEnv, name: string): string | undefined { + return Object.keys(env).find((key) => key.toUpperCase() === name); } -export function withOnlyTrustedPathFolders(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { - const pathKey = pathKeyOf(env); +function windowsFolderKey(dir: string): string { + return dir.replaceAll("/", "\\").replace(/\\+$/, "").toLowerCase(); +} + +function windowsSystemFolders(env: NodeJS.ProcessEnv): Set { + const rootKey = keyOf(env, "SYSTEMROOT"); + const root = (rootKey && env[rootKey]) || "C:\\Windows"; + const system32 = win32.join(root, "System32"); + return new Set( + [ + root, + system32, + win32.join(system32, "Wbem"), + win32.join(system32, "WindowsPowerShell", "v1.0"), + ].map(windowsFolderKey), + ); +} + +function unquoted(dir: string): string { + return dir.length > 1 && dir.startsWith('"') && dir.endsWith('"') ? dir.slice(1, -1) : dir; +} + +function windowsTrustedDirs(pathValue: string, env: NodeJS.ProcessEnv): string[] { + const entries = pathValue.split(win32.delimiter).map(unquoted); + const trusted = new Set(trustedPathDirs(entries.join(delimiter))); + const system = windowsSystemFolders(env); + return [ + ...new Set(entries.filter((dir) => trusted.has(dir) || system.has(windowsFolderKey(dir)))), + ]; +} + +export function withOnlyTrustedPathFolders( + env: NodeJS.ProcessEnv, + platform: NodeJS.Platform = process.platform, +): NodeJS.ProcessEnv { + const pathKey = keyOf(env, "PATH"); if (!pathKey) return { ...env }; - const dirs = trustedPathDirs(env[pathKey]); - return { ...env, [pathKey]: dirs.length > 0 ? dirs.join(delimiter) : NEVER_CREATED_PATH_FOLDER }; + const value = env[pathKey] ?? ""; + const dirs = platform === "win32" ? windowsTrustedDirs(value, env) : trustedPathDirs(value); + const separator = platform === "win32" ? win32.delimiter : delimiter; + return { ...env, [pathKey]: dirs.length > 0 ? dirs.join(separator) : NEVER_CREATED_PATH_FOLDER }; } export function skipWorkingDirectoryInExeSearch( @@ -26,9 +62,16 @@ export function searchOnlyTrustedFolders( env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform, ): void { - const pathKey = pathKeyOf(env); - if (pathKey) env[pathKey] = withOnlyTrustedPathFolders(env)[pathKey]; + const pathKey = keyOf(env, "PATH"); + if (pathKey) env[pathKey] = withOnlyTrustedPathFolders(env, platform)[pathKey]; skipWorkingDirectoryInExeSearch(env, platform); } +const pathKeyAtStart = keyOf(process.env, "PATH"); +const PATH_AT_START = (pathKeyAtStart && process.env[pathKeyAtStart]) || ""; + +export function originalPath(): string { + return PATH_AT_START; +} + searchOnlyTrustedFolders(); From 6e5f0bedc91be21e01b755952c3383adadc9241f Mon Sep 17 00:00:00 2001 From: James Date: Sun, 15 Nov 2026 00:47:41 +0000 Subject: [PATCH 3/3] fix(cli): resolve the empty-PATH placeholder only when it is needed Computing it at import threw in test environments where import.meta.url is not a file URL. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/utils/windowsExeSearch.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/utils/windowsExeSearch.ts b/packages/cli/src/utils/windowsExeSearch.ts index 63c84cf5a74..78be0d8fbaa 100644 --- a/packages/cli/src/utils/windowsExeSearch.ts +++ b/packages/cli/src/utils/windowsExeSearch.ts @@ -2,7 +2,8 @@ import { delimiter, win32 } from "node:path"; import { fileURLToPath } from "node:url"; import { trustedPathDirs } from "@hyperframes/parsers/ff-binaries"; -const NEVER_CREATED_PATH_FOLDER = fileURLToPath(new URL("no-trusted-path-folder", import.meta.url)); +const neverCreatedPathFolder = () => + fileURLToPath(new URL("no-trusted-path-folder", import.meta.url)); function keyOf(env: NodeJS.ProcessEnv, name: string): string | undefined { return Object.keys(env).find((key) => key.toUpperCase() === name); @@ -48,7 +49,7 @@ export function withOnlyTrustedPathFolders( const value = env[pathKey] ?? ""; const dirs = platform === "win32" ? windowsTrustedDirs(value, env) : trustedPathDirs(value); const separator = platform === "win32" ? win32.delimiter : delimiter; - return { ...env, [pathKey]: dirs.length > 0 ? dirs.join(separator) : NEVER_CREATED_PATH_FOLDER }; + return { ...env, [pathKey]: dirs.length > 0 ? dirs.join(separator) : neverCreatedPathFolder() }; } export function skipWorkingDirectoryInExeSearch(