diff --git a/packages/cli/src/browser/manager.test.ts b/packages/cli/src/browser/manager.test.ts index 1fc280abcd..a756a96932 100644 --- a/packages/cli/src/browser/manager.test.ts +++ b/packages/cli/src/browser/manager.test.ts @@ -31,7 +31,7 @@ import { writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { basename, delimiter, dirname, join, relative, sep } from "node:path"; +import { basename, dirname, join, relative, sep, win32 } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { managedChromeVersion } from "./manager.js"; @@ -364,7 +364,7 @@ describe("findBrowser — cache resolution", () => { const project = join("/", "projects", "shared"); const tools = join("/", "tools", "chrome"); vi.spyOn(process, "cwd").mockReturnValue(project); - vi.stubEnv("PATH", [project, tools].join(delimiter)); + vi.stubEnv("PATH", [project, tools].join(win32.delimiter)); const existing = installFsMocks({ existing: new Set([join(project, "google-chrome.exe")]) }); installPuppeteerBrowsersMock(); const { findSystemBrowser } = await import("./manager.js"); diff --git a/packages/cli/src/commands/cloudrun.ts b/packages/cli/src/commands/cloudrun.ts index 5bb54bef18..404f45c436 100644 --- a/packages/cli/src/commands/cloudrun.ts +++ b/packages/cli/src/commands/cloudrun.ts @@ -14,7 +14,7 @@ import { CliUsageError, failCommand, failUsage } from "../utils/commandResult.js * `progress` don't need them re-passed every call. */ -import { spawnSync } from "node:child_process"; +import { type SpawnSyncReturns, spawnSync } from "node:child_process"; import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { defineCommand } from "../utils/defineCommand.js"; @@ -32,6 +32,7 @@ import { defaultCloudFps } from "../utils/compositionFps.js"; import { DISTRIBUTED_FPS, type DistributedFps, isDistributedFps } from "@hyperframes/core"; import { isMissingPackageError, missingPackageMessage } from "../utils/missingPackage.js"; import { hyperframesConfigDir, seededConfigFile } from "../utils/configDir.js"; +import { projectCopyHint } from "../utils/projectCopyHint.js"; export const examples: Example[] = [ ["Deploy the Cloud Run render stack", "hyperframes cloudrun deploy --project my-gcp-project"], @@ -306,14 +307,20 @@ function stripUndefined>(o: T): Partial { return Object.fromEntries(Object.entries(o).filter(([, v]) => v != null)) as Partial; } +function assertStarted(cmd: string, res: SpawnSyncReturns): void { + if ((res.error as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") return; + throw new Error(`[cloudrun] \`${cmd}\` not found on PATH.${projectCopyHint(cmd)}`); +} function run(cmd: string, cmdArgs: string[], opts: { cwd?: string } = {}): void { const res = spawnSync(cmd, cmdArgs, { stdio: "inherit", cwd: opts.cwd }); + assertStarted(cmd, res); if (res.status !== 0) { throw new Error(`[cloudrun] \`${cmd} ${cmdArgs.join(" ")}\` exited with ${res.status}`); } } function capture(cmd: string, cmdArgs: string[], opts: { cwd?: string } = {}): string { const res = spawnSync(cmd, cmdArgs, { encoding: "utf8", cwd: opts.cwd }); + assertStarted(cmd, res); if (res.status !== 0) { throw new Error(`[cloudrun] \`${cmd} ${cmdArgs.join(" ")}\` failed: ${res.stderr}`); } diff --git a/packages/cli/src/commands/lambda/sam.test.ts b/packages/cli/src/commands/lambda/sam.test.ts index 2c702550cd..d2b732a9e3 100644 --- a/packages/cli/src/commands/lambda/sam.test.ts +++ b/packages/cli/src/commands/lambda/sam.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { execFileSync, spawnSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { @@ -16,6 +16,9 @@ vi.mock("node:child_process", () => ({ spawnSync: vi.fn(() => ({ status: 0 })), })); +const startPath = vi.hoisted(() => ({ value: "" })); +vi.mock("../../utils/windowsExeSearch.js", () => ({ originalPath: () => startPath.value })); + let dir: string | undefined; afterEach(() => { @@ -121,3 +124,27 @@ describe("parseReservedConcurrency", () => { expect(vi.mocked(spawnSync).mock.lastCall?.[1]).toContain("ReservedConcurrency=-1"); }); }); + +describe("missing sam", () => { + it("says why a sam installed in the project's virtualenv was not used", () => { + dir = realpathSync(mkdtempSync(join(tmpdir(), "hf-lambda-sam-venv-"))); + const venv = join(dir, ".venv", "bin"); + mkdirSync(venv, { recursive: true }); + writeFileSync(join(venv, process.platform === "win32" ? "sam.exe" : "sam"), "", { + mode: 0o755, + }); + startPath.value = venv; + const cwd = vi.spyOn(process, "cwd").mockReturnValue(dir); + vi.mocked(execFileSync).mockImplementationOnce(() => { + throw Object.assign(new Error("spawnSync sam ENOENT"), { code: "ENOENT" }); + }); + try { + expect(() => samDeploy({ samDir: "/repo", stackName: "s", region: "us-east-2" })).toThrow( + /not found on PATH\..*A copy at \.[\\/]\.venv[\\/]bin[\\/]sam.* was not used/, + ); + } finally { + cwd.mockRestore(); + startPath.value = ""; + } + }); +}); diff --git a/packages/cli/src/commands/lambda/sam.ts b/packages/cli/src/commands/lambda/sam.ts index c1944099fa..43e325bc90 100644 --- a/packages/cli/src/commands/lambda/sam.ts +++ b/packages/cli/src/commands/lambda/sam.ts @@ -22,6 +22,7 @@ import { execFileSync, spawnSync } from "node:child_process"; import { existsSync } from "node:fs"; import { join } from "node:path"; import { CliUsageError } from "../../utils/commandResult.js"; +import { projectCopyHint } from "../../utils/projectCopyHint.js"; /** Throws with a clear hint when the SAM CLI is not on PATH. */ function assertSamAvailable(): void { @@ -29,7 +30,8 @@ function assertSamAvailable(): void { execFileSync("sam", ["--version"], { stdio: "ignore" }); } catch { throw new Error( - "`sam` CLI not found on PATH. Install AWS SAM CLI from https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html and retry.", + "`sam` CLI not found on PATH. Install AWS SAM CLI from https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html and retry." + + projectCopyHint("sam"), ); } } @@ -40,7 +42,8 @@ function assertAwsCliAvailable(): void { execFileSync("aws", ["--version"], { stdio: "ignore" }); } catch { throw new Error( - "`aws` CLI not found on PATH. Install from https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html and configure credentials before retrying.", + "`aws` CLI not found on PATH. Install from https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html and configure credentials before retrying." + + projectCopyHint("aws"), ); } } diff --git a/packages/cli/src/commands/skills.ts b/packages/cli/src/commands/skills.ts index ba39d3da0f..c9f365bbe1 100644 --- a/packages/cli/src/commands/skills.ts +++ b/packages/cli/src/commands/skills.ts @@ -28,6 +28,7 @@ import { invalidateSkillsCache } from "../utils/skillsUpdateCheck.js"; import { trackSkillsInstallSkipped } from "../telemetry/events.js"; import type { Example } from "./_examples.js"; import { failureMessage, jsonFailure } from "../utils/jsonError.js"; +import { projectCopyHint } from "../utils/projectCopyHint.js"; export const examples: Example[] = [ ["Install all HyperFrames skills", "hyperframes skills"], @@ -205,24 +206,29 @@ function mirrorToInstalledAgents(): void { // best-effort report (one calm line; init carries on and still scaffolds). const SKILLS_TOOLING: ReadonlyArray<{ has: () => boolean; - error: string; + error: () => string; // Low-cardinality tag for the skip telemetry event (e.g. "git_missing"). reason: string; report: () => void; }> = [ { has: hasNpx, - error: "npx not found. Install Node.js and retry.", + error: () => `npx not found. Install Node.js and retry.${projectCopyHint("npx")}`, reason: "npx_missing", - report: () => clack.log.error(c.error("npx not found. Install Node.js and retry.")), + report: () => + clack.log.error( + c.error(`npx not found. Install Node.js and retry.${projectCopyHint("npx")}`), + ), }, { has: hasGit, - error: "git not found. Install git and retry to add AI coding skills.", + error: () => + `git not found. Install git and retry to add AI coding skills.${projectCopyHint("git")}`, reason: "git_missing", // Skip cleanly rather than letting the upstream clone dump a noisy // multi-line `spawn git ENOENT` / "Installation failed" abort. - report: () => console.log(c.dim("Skipping AI coding skills: git not available.")), + report: () => + console.log(c.dim(`Skipping AI coding skills: git not available.${projectCopyHint("git")}`)), }, ]; @@ -230,7 +236,7 @@ const SKILLS_TOOLING: ReadonlyArray<{ function skillsToolingReady(strict: boolean): boolean { for (const tool of SKILLS_TOOLING) { if (tool.has()) continue; - if (strict) throw new Error(tool.error); + if (strict) throw new Error(tool.error()); tool.report(); // Surface the rare best-effort skip (init on a box missing git/npx); the // event respects the telemetry opt-out inside trackEvent. diff --git a/packages/cli/src/utils/dockerBuildFailure.ts b/packages/cli/src/utils/dockerBuildFailure.ts index b8dc5022ca..6bdf9f1799 100644 --- a/packages/cli/src/utils/dockerBuildFailure.ts +++ b/packages/cli/src/utils/dockerBuildFailure.ts @@ -1,4 +1,5 @@ import { normalizeErrorMessage } from "./errorMessage.js"; +import { projectCopyHint } from "./projectCopyHint.js"; export const DOCKER_BUILD_TIMEOUT_MINUTES = 10; @@ -25,7 +26,7 @@ export function describeDockerBuildFailure(error: unknown): DockerBuildFailure { return { title: "Docker not available", message, - hint: "Install Docker: https://docs.docker.com/get-docker/", + hint: `Install Docker: https://docs.docker.com/get-docker/${projectCopyHint("docker")}`, }; } return { diff --git a/packages/cli/src/utils/projectCopyHint.test.ts b/packages/cli/src/utils/projectCopyHint.test.ts new file mode 100644 index 0000000000..bb16c9dfbc --- /dev/null +++ b/packages/cli/src/utils/projectCopyHint.test.ts @@ -0,0 +1,92 @@ +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { delimiter, join, relative, sep } from "node:path"; +import { describe, expect, it, onTestFinished, vi } from "vitest"; +import { projectCopyHint, skippedProjectCopy } from "./projectCopyHint.js"; + +function tempDir(prefix: string): string { + const dir = realpathSync(mkdtempSync(join(tmpdir(), prefix))); + onTestFinished(() => rmSync(dir, { recursive: true, force: true })); + return dir; +} + +function program(dir: string, name: string): void { + mkdirSync(dir, { recursive: true }); + const file = process.platform === "win32" ? `${name}.exe` : name; + writeFileSync(join(dir, file), "#!/bin/sh\n", { mode: 0o755 }); +} + +function inProject(): { project: string; outside: string } { + const project = tempDir("hf-copy-hint-project-"); + const outside = tempDir("hf-copy-hint-outside-"); + vi.spyOn(process, "cwd").mockReturnValue(project); + onTestFinished(() => { + vi.restoreAllMocks(); + }); + return { project, outside }; +} + +describe("projectCopyHint", () => { + it("names a project copy the PATH rule skipped, relative to the project", () => { + const { project, outside } = inProject(); + const venv = join(project, ".venv", "bin"); + program(venv, "sam"); + const pathValue = [venv, outside].join(delimiter); + + const hint = projectCopyHint("sam", pathValue); + + expect(skippedProjectCopy("sam", pathValue)).toMatch( + new RegExp(`^\\.\\${sep}\\.venv\\${sep}bin\\${sep}sam(\\.exe)?$`), + ); + expect(hint).toContain("was not used"); + expect(hint).toContain("outside the current project"); + expect(hint).not.toContain(project); + }); + + it("finds a copy reached through a relative PATH entry", () => { + const { project } = inProject(); + program(join(project, "node_modules", ".bin"), "git"); + + expect(skippedProjectCopy("git", join("node_modules", ".bin"))).toMatch( + new RegExp(`^\\.\\${sep}node_modules\\${sep}\\.bin\\${sep}git`), + ); + }); + + it("says nothing when no skipped folder holds the program", () => { + const { project, outside } = inProject(); + program(outside, "sam"); + mkdirSync(join(project, ".venv", "bin"), { recursive: true }); + + expect(projectCopyHint("sam", [join(project, ".venv", "bin"), outside].join(delimiter))).toBe( + "", + ); + }); + + it("names a skipped copy above the working directory as a ../ path", () => { + const { project } = inProject(); + // An npm or pnpm script run from a subfolder puts the project root's node_modules/.bin on PATH. + writeFileSync(join(project, "package.json"), "{}"); + const sub = join(project, "video"); + mkdirSync(sub); + vi.stubEnv("HOME", tempDir("hf-copy-hint-home-")); + onTestFinished(() => { + vi.unstubAllEnvs(); + }); + vi.spyOn(process, "cwd").mockReturnValue(sub); + const bin = join(project, "node_modules", ".bin"); + program(bin, "npx"); + + expect(skippedProjectCopy("npx", bin)).toMatch( + new RegExp(`^\\.\\.\\${sep}node_modules\\${sep}\\.bin\\${sep}npx(\\.exe)?$`), + ); + expect(projectCopyHint("npx", bin)).toContain(`..${sep}node_modules`); + }); + + it("names a relative PATH entry outside the working directory too, since the rule never trusts one", () => { + const { project } = inProject(); + const sibling = tempDir("hf-copy-hint-sibling-"); + program(sibling, "sam"); + + expect(skippedProjectCopy("sam", relative(project, sibling))).toMatch(/^\.\./); + }); +}); diff --git a/packages/cli/src/utils/projectCopyHint.ts b/packages/cli/src/utils/projectCopyHint.ts new file mode 100644 index 0000000000..0b4fb91357 --- /dev/null +++ b/packages/cli/src/utils/projectCopyHint.ts @@ -0,0 +1,29 @@ +import { isAbsolute, relative, resolve, sep } from "node:path"; +import { executableIn, pathEntries, trustedPathDirs } from "@hyperframes/parsers/ff-binaries"; +import { originalPath } from "./windowsExeSearch.js"; + +function shownPath(cwd: string, found: string): string | undefined { + const rel = relative(cwd, found); + if (isAbsolute(rel)) return undefined; + return rel === ".." || rel.startsWith(`..${sep}`) ? rel : `.${sep}${rel}`; +} + +/** A copy of `name` in a PATH folder the trusted rule skipped, as `./…` or `../…` from the working directory. */ +export function skippedProjectCopy(name: string, pathValue = originalPath()): string | undefined { + const trusted = new Set(trustedPathDirs(pathValue)); + const cwd = process.cwd(); + for (const entry of pathEntries(pathValue)) { + if (!entry || trusted.has(entry)) continue; + const found = executableIn(resolve(cwd, entry), name); + const shown = found && shownPath(cwd, found); + if (shown) return shown; + } + return undefined; +} + +/** A sentence for a not-found message when the project holds a copy of `name`, else "". */ +export function projectCopyHint(name: string, pathValue = originalPath()): string { + const copy = skippedProjectCopy(name, pathValue); + if (!copy) return ""; + return ` A copy at ${copy} was not used: HyperFrames only runs programs from absolute PATH folders outside the current project. Install ${name} outside the project and retry.`; +} diff --git a/packages/cli/src/utils/windowsExeSearch.test.ts b/packages/cli/src/utils/windowsExeSearch.test.ts index 7af0e5932b..30afd68110 100644 --- a/packages/cli/src/utils/windowsExeSearch.test.ts +++ b/packages/cli/src/utils/windowsExeSearch.test.ts @@ -130,46 +130,6 @@ describe("searchOnlyTrustedFolders", () => { ); }); - 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 78be0d8fba..705a51e945 100644 --- a/packages/cli/src/utils/windowsExeSearch.ts +++ b/packages/cli/src/utils/windowsExeSearch.ts @@ -9,37 +9,6 @@ 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, @@ -47,7 +16,7 @@ export function withOnlyTrustedPathFolders( const pathKey = keyOf(env, "PATH"); if (!pathKey) return { ...env }; const value = env[pathKey] ?? ""; - const dirs = platform === "win32" ? windowsTrustedDirs(value, env) : trustedPathDirs(value); + const dirs = trustedPathDirs(value, platform, env); const separator = platform === "win32" ? win32.delimiter : delimiter; return { ...env, [pathKey]: dirs.length > 0 ? dirs.join(separator) : neverCreatedPathFolder() }; } diff --git a/packages/cli/src/whisper/trustedLookup.test.ts b/packages/cli/src/whisper/trustedLookup.test.ts index a75f81f7d6..411bb23802 100644 --- a/packages/cli/src/whisper/trustedLookup.test.ts +++ b/packages/cli/src/whisper/trustedLookup.test.ts @@ -1,6 +1,6 @@ import { mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { delimiter, join } from "node:path"; +import { join, win32 } from "node:path"; import { afterEach, expect, it, onTestFinished, vi } from "vitest"; const originalPlatform = process.platform; @@ -33,11 +33,11 @@ it("on Windows, never takes whisper-cli or parakeet-mlx from the working directo const { findParakeet } = await import("./parakeet.js"); Object.defineProperty(process, "platform", { value: "win32", configurable: true }); - vi.stubEnv("PATH", [project, ".", ""].join(delimiter)); + vi.stubEnv("PATH", [project, ".", ""].join(win32.delimiter)); expect(findWhisper()).toBeUndefined(); expect(findParakeet()).toBeUndefined(); - vi.stubEnv("PATH", [project, tools].join(delimiter)); + vi.stubEnv("PATH", [project, tools].join(win32.delimiter)); expect(findWhisper()).toEqual({ executablePath: join(tools, "whisper-cli.exe"), source: "system", diff --git a/packages/parsers/src/ffBinaries.test.ts b/packages/parsers/src/ffBinaries.test.ts index 749dba4680..0cb9acc213 100644 --- a/packages/parsers/src/ffBinaries.test.ts +++ b/packages/parsers/src/ffBinaries.test.ts @@ -10,7 +10,7 @@ import { writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { delimiter, join, resolve } from "node:path"; +import { delimiter, join, resolve, win32 } from "node:path"; import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest"; type FfBinariesModule = typeof import("./ffBinaries.js"); @@ -239,7 +239,7 @@ describe("findFfBinary", () => { skipped = {}; vi.stubEnv("HYPERFRAMES_FFMPEG_PATH", ""); vi.stubEnv("HYPERFRAMES_FFPROBE_PATH", ""); - process.env.PATH = pathDirs.join(delimiter); + process.env.PATH = pathDirs.join(process.platform === "win32" ? win32.delimiter : delimiter); vi.spyOn(process, "cwd").mockReturnValue(project); vi.resetModules(); vi.doMock("node:fs", async (importOriginal) => { diff --git a/packages/parsers/src/ffBinaries.ts b/packages/parsers/src/ffBinaries.ts index 68cc47a987..f1e3dc68f1 100644 --- a/packages/parsers/src/ffBinaries.ts +++ b/packages/parsers/src/ffBinaries.ts @@ -18,9 +18,11 @@ import { isTrustedExecutablePath, trustedPathDirs } from "./trustedExecutable.js */ export { + executableIn, findTrustedExecutable, isTrustedDirectory, isTrustedExecutablePath, + pathEntries, trustedPathDirs, } from "./trustedExecutable.js"; diff --git a/packages/parsers/src/trustedExecutable.test.ts b/packages/parsers/src/trustedExecutable.test.ts index ee7870c9c5..0bbcb6ca98 100644 --- a/packages/parsers/src/trustedExecutable.test.ts +++ b/packages/parsers/src/trustedExecutable.test.ts @@ -8,7 +8,7 @@ import { writeFileSync, } from "node:fs"; import { homedir, tmpdir } from "node:os"; -import { delimiter, dirname, join, resolve } from "node:path"; +import { delimiter, dirname, join, resolve, win32 } from "node:path"; import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest"; import { findTrustedExecutable, @@ -233,7 +233,7 @@ describe("findTrustedExecutable", () => { Object.defineProperty(process, "platform", { value: realPlatform, configurable: true }); }); vi.spyOn(process, "cwd").mockReturnValue(project); - vi.stubEnv("PATH", [".", project, tools].join(delimiter)); + vi.stubEnv("PATH", [".", project, `"${tools}"`].join(win32.delimiter)); expect(findTrustedExecutable("ffprobe")).toBe(join(tools, "ffprobe.exe")); }); @@ -257,3 +257,68 @@ describe("trustedPathDirs", () => { }, ); }); + +describe("trustedPathDirs on Windows", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("reads an entry wrapped in double quotes", () => { + const project = tempDir("hf-trusted-project-"); + const tools = tempDir("hf-trusted-tools-"); + vi.spyOn(process, "cwd").mockReturnValue(project); + + expect( + trustedPathDirs([`"${tools}"`, `"${project}"`].join(win32.delimiter), "win32", {}), + ).toEqual([tools]); + }); + + it("still skips the project root's and every ancestor's node_modules/.bin, quoted or not", () => { + const project = tempDir("hf-trusted-project-"); + const tools = tempDir("hf-trusted-tools-"); + writeFileSync(join(project, "package.json"), "{}"); + const sub = join(project, "video"); + mkdirSync(sub); + vi.stubEnv("HOME", tempDir("hf-trusted-home-")); + onTestFinished(() => { + vi.unstubAllEnvs(); + }); + vi.spyOn(process, "cwd").mockReturnValue(sub); + const pathValue = [ + `"${join(project, "node_modules", ".bin")}"`, + join(dirname(project), "node_modules", ".bin"), + `"${join(sub, "scripts")}"`, + `"${tools}"`, + ].join(win32.delimiter); + + expect(trustedPathDirs(pathValue, "win32", {})).toEqual([tools]); + }); + + it("keeps the system folders when started from inside System32", () => { + vi.spyOn(process, "cwd").mockReturnValue("C:\\Windows\\System32"); + const pathValue = [ + "C:\\Windows\\system32", + ".", + "C:\\Windows", + "C:/Windows/System32/Wbem/", + "C:\\Windows\\System32\\evil", + "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\", + ].join(win32.delimiter); + + expect(trustedPathDirs(pathValue, "win32", { SystemRoot: "C:\\Windows" })).toEqual([ + "C:\\Windows\\system32", + "C:\\Windows", + "C:/Windows/System32/Wbem/", + "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\", + ]); + }); + + it("takes the system folders from SystemRoot", () => { + vi.spyOn(process, "cwd").mockReturnValue("C:\\Windows\\System32"); + const pathValue = ["C:\\Windows\\System32", "D:\\WinNT\\System32"].join(win32.delimiter); + + expect(trustedPathDirs(pathValue, "win32", { SYSTEMROOT: "D:\\WinNT" })).toEqual([ + "D:\\WinNT\\System32", + ]); + }); +}); diff --git a/packages/parsers/src/trustedExecutable.ts b/packages/parsers/src/trustedExecutable.ts index 847cddb104..243246ce0a 100644 --- a/packages/parsers/src/trustedExecutable.ts +++ b/packages/parsers/src/trustedExecutable.ts @@ -1,6 +1,16 @@ import { accessSync, constants, existsSync, realpathSync, statSync } from "node:fs"; import { homedir } from "node:os"; -import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; +import { + basename, + delimiter, + dirname, + isAbsolute, + join, + relative, + resolve, + sep, + win32, +} from "node:path"; /** * The one rule for finding a helper program by name. A project folder can come from anyone, so a @@ -72,15 +82,51 @@ export function isTrustedExecutablePath(file: string): boolean { } function expandHome(dir: string): string { - if (process.platform === "win32" || !(dir === "~" || dir.startsWith("~/"))) return dir; + if (!(dir === "~" || dir.startsWith("~/"))) return dir; return join(homedir(), dir.slice(1)); } -/** The PATH folders a helper program may come from, in PATH order. */ -export function trustedPathDirs(pathValue = process.env.PATH ?? ""): string[] { - const entries = pathValue.split(delimiter).map(expandHome); +function unquoted(dir: string): string { + return dir.length > 1 && dir.startsWith('"') && dir.endsWith('"') ? dir.slice(1, -1) : dir; +} + +/** PATH entries as the program search reads them: Windows allows quotes, shells expand a leading `~`. */ +export function pathEntries( + pathValue: string, + platform: NodeJS.Platform = process.platform, +): string[] { + if (platform === "win32") return pathValue.split(win32.delimiter).map(unquoted); + return pathValue.split(delimiter).map(expandHome); +} + +function windowsFolderKey(dir: string): string { + return dir.replaceAll("/", "\\").replace(/\\+$/, "").toLowerCase(); +} + +function windowsSystemFolders(env: NodeJS.ProcessEnv): Set { + const rootKey = Object.keys(env).find((key) => key.toUpperCase() === "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), + ); +} + +/** The PATH folders a helper program may come from, in PATH order. Windows always keeps its system folders. */ +export function trustedPathDirs( + pathValue = process.env.PATH ?? "", + platform: NodeJS.Platform = process.platform, + env: NodeJS.ProcessEnv = process.env, +): string[] { + const system = platform === "win32" ? windowsSystemFolders(env) : new Set(); + const entries = pathEntries(pathValue, platform); const trusted = trustRule(); - return [...new Set(entries.filter((dir) => trusted(dir)))]; + return [...new Set(entries.filter((dir) => system.has(windowsFolderKey(dir)) || trusted(dir)))]; } function windowsExtensions(): string[] { @@ -101,13 +147,20 @@ function isExecutableFile(file: string): boolean { } } -export function findTrustedExecutable(name: string): string | undefined { +/** The program `name` in `dir`, trying the Windows program extensions there. */ +export function executableIn(dir: string, name: string): string | undefined { const extensions = process.platform === "win32" ? windowsExtensions() : [""]; + for (const ext of extensions) { + const candidate = join(dir, `${name}${ext}`); + if (isExecutableFile(candidate)) return candidate; + } + return undefined; +} + +export function findTrustedExecutable(name: string): string | undefined { for (const dir of trustedPathDirs()) { - for (const ext of extensions) { - const candidate = join(dir, `${name}${ext}`); - if (isExecutableFile(candidate)) return candidate; - } + const found = executableIn(dir, name); + if (found) return found; } return undefined; }