From 83eae240fb5f5747c94b6aabdc5448e59f119a5e Mon Sep 17 00:00:00 2001 From: James Russo Date: Sun, 15 Nov 2026 01:24:20 +0000 Subject: [PATCH] fix(cli): start helper programs only from trusted PATH folders on every platform (#7787) * 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 * 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 * 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 --------- 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 | 19 +-- .../cli/src/utils/installerDetection.test.ts | 34 ++++- packages/cli/src/utils/installerDetection.ts | 5 +- .../cli/src/utils/windowsExeSearch.test.ts | 136 +++++++++++++++++- packages/cli/src/utils/windowsExeSearch.ts | 72 +++++++++- 7 files changed, 358 insertions(+), 39 deletions(-) diff --git a/packages/cli/src/commands/doctor.test.ts b/packages/cli/src/commands/doctor.test.ts index b5cd369c70..48d567a79a 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 f008e2cf89..feb687f953 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 d2f8ea0f3b..8def789a50 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,21 +79,12 @@ 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], 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 3714315e6e..e09ac053a7 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 79884d2cd8..c38e13aa3d 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 f43117135a..5e38edf5e9 100644 --- a/packages/cli/src/utils/windowsExeSearch.test.ts +++ b/packages/cli/src/utils/windowsExeSearch.test.ts @@ -1,8 +1,30 @@ -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, win32 } 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, + withOnlyTrustedPathFolders, +} 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 +46,112 @@ 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 separator = platform === "win32" ? win32.delimiter : delimiter; + const env: NodeJS.ProcessEnv = { + PATH: [ + "", + ".", + join("node_modules", ".bin"), + outside[0], + join(project, "node_modules", ".bin"), + project, + outside[1], + ].join(separator), + }; + + searchOnlyTrustedFolders(env, platform); + + 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(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) }; + + 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 93c0120c22..78be0d8fba 100644 --- a/packages/cli/src/utils/windowsExeSearch.ts +++ b/packages/cli/src/utils/windowsExeSearch.ts @@ -1,3 +1,57 @@ +import { delimiter, win32 } from "node:path"; +import { fileURLToPath } from "node:url"; +import { trustedPathDirs } from "@hyperframes/parsers/ff-binaries"; + +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); +} + +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 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) : neverCreatedPathFolder() }; +} + export function skipWorkingDirectoryInExeSearch( env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform, @@ -5,4 +59,20 @@ 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 = 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();