fix(parsers): helper lookups skip the project above the working folder, not only the folder (#7854)

* fix(parsers): helper lookups skip the project above the working folder, not only the folder

* fix(parsers): compare a missing PATH folder by its nearest real parent, so Windows short names match
This commit is contained in:
Michael Wang
2026-11-15 19:12:04 +00:00
committed by GitHub
parent f0fb7aa5a8
commit 7184b6694e
3 changed files with 167 additions and 17 deletions
@@ -79,6 +79,37 @@ describe("searchOnlyTrustedFolders", () => {
},
);
// fails without the fix: the project root's node_modules/.bin that npx adds stayed on PATH when
// the CLI ran from a subfolder, because only folders inside the working directory were dropped.
it.each(["linux", "darwin", "win32"] as const)(
"drops the project root's node_modules/.bin when run from a subfolder, on %s",
(platform) => {
const { project, outside } = inProject();
const sub = join(project, "video");
mkdirSync(join(sub, "node_modules", ".bin"), { recursive: true });
// The temp folder is home, so a marker in a folder above it cannot move the project root.
vi.stubEnv("HOME", dirname(project));
vi.stubEnv("USERPROFILE", dirname(project));
onTestFinished(() => {
vi.unstubAllEnvs();
});
vi.spyOn(process, "cwd").mockReturnValue(sub);
const separator = platform === "win32" ? win32.delimiter : delimiter;
const env: NodeJS.ProcessEnv = {
PATH: [
join(sub, "node_modules", ".bin"),
join(project, "node_modules", ".bin"),
join(dirname(project), "node_modules", ".bin"),
outside[0],
].join(separator),
};
searchOnlyTrustedFolders(env, platform);
expect(env.PATH).toBe(outside[0]);
},
);
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) };
+99 -1
View File
@@ -1,4 +1,12 @@
import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import {
existsSync,
mkdirSync,
mkdtempSync,
realpathSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { homedir, tmpdir } from "node:os";
import { delimiter, dirname, join, resolve } from "node:path";
import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
@@ -46,6 +54,96 @@ describe("isTrustedDirectory", () => {
});
});
/** Makes `dir` the home folder, so a marker in a folder above the temp folder cannot move the project root. */
function homeAt(dir: string): void {
vi.stubEnv("HOME", dir);
vi.stubEnv("USERPROFILE", dir);
}
describe("isTrustedDirectory from a subfolder of a project", () => {
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllEnvs();
});
// fails without the fix: only folders inside the working directory were dropped, so the
// node_modules/.bin a package runner adds for the project root stayed ahead of system folders.
it("drops every ancestor's node_modules and the folders of the project above", () => {
const root = tempDir("hf-trusted-tree-");
homeAt(root);
const project = join(root, "project");
const sub = join(project, "video");
const venv = join(project, ".venv", "bin");
mkdirSync(join(sub, "node_modules", ".bin"), { recursive: true });
mkdirSync(join(project, "node_modules", ".bin"), { recursive: true });
mkdirSync(venv, { recursive: true });
writeFileSync(join(project, "package.json"), "{}");
vi.spyOn(process, "cwd").mockReturnValue(sub);
expect(isTrustedDirectory(join(sub, "node_modules", ".bin"))).toBe(false);
expect(isTrustedDirectory(join(project, "node_modules", ".bin"))).toBe(false);
expect(isTrustedDirectory(join(root, "node_modules", ".bin"))).toBe(false);
expect(isTrustedDirectory(venv)).toBe(false);
expect(isTrustedDirectory(project)).toBe(false);
expect(isTrustedDirectory(join(root, "tools"))).toBe(true);
});
// fails without the fix: a folder that does not exist kept the spelling it was given, so a project
// folder named through a link (or a Windows short name such as RUNNER~1) never matched.
it.skipIf(process.platform === "win32")(
"drops a project folder that does not exist yet, named through a link",
() => {
const root = tempDir("hf-trusted-link-");
homeAt(root);
const project = join(root, "project");
const sub = join(project, "video");
mkdirSync(sub, { recursive: true });
symlinkSync(root, join(root, "link"));
vi.spyOn(process, "cwd").mockReturnValue(sub);
expect(isTrustedDirectory(join(root, "link", "project", "node_modules", ".bin"))).toBe(false);
expect(isTrustedDirectory(join(root, "link", "node_modules", ".bin"))).toBe(false);
},
);
it("keeps the per-user install dirs when the home folder itself holds a package.json or .git", () => {
const home = tempDir("hf-trusted-home-");
const sub = join(home, "films", "launch", "video");
mkdirSync(sub, { recursive: true });
mkdirSync(join(home, ".git"));
writeFileSync(join(home, "package.json"), "{}");
vi.stubEnv("HOME", home);
vi.stubEnv("USERPROFILE", home);
vi.spyOn(process, "cwd").mockReturnValue(sub);
expect(isTrustedDirectory(join(home, ".local", "bin"))).toBe(true);
expect(isTrustedDirectory(join(home, ".bun", "bin"))).toBe(true);
expect(isTrustedDirectory(join(home, "node_modules", ".bin"))).toBe(false);
});
it.skipIf(process.platform === "win32")(
"never finds a helper in the project when run from its subfolder through a package runner",
() => {
const root = tempDir("hf-trusted-runner-");
homeAt(root);
const project = join(root, "project");
const sub = join(project, "video");
const tools = join(root, "tools");
const subBin = join(sub, "node_modules", ".bin");
const projectBin = join(project, "node_modules", ".bin");
for (const dir of [subBin, projectBin, tools]) {
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, "ffmpeg"), "", { mode: 0o755 });
}
vi.spyOn(process, "cwd").mockReturnValue(sub);
vi.stubEnv("PATH", [subBin, projectBin, tools, "/usr/bin", "/bin"].join(delimiter));
expect(trustedPathDirs()).toEqual([tools, "/usr/bin", "/bin"]);
expect(findTrustedExecutable("ffmpeg")).toBe(join(tools, "ffmpeg"));
},
);
});
function tempDir(prefix: string): string {
const dir = realpathSync(mkdtempSync(join(tmpdir(), prefix)));
onTestFinished(() => rmSync(dir, { recursive: true, force: true }));
+37 -16
View File
@@ -1,6 +1,6 @@
import { accessSync, constants, existsSync, realpathSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
/**
* The one rule for finding a helper program by name. A project folder can come from anyone, so a
@@ -9,13 +9,17 @@ import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "no
*/
function comparable(path: string): string {
let full = resolve(path);
try {
full = realpathSync.native(full);
} catch {
full = resolve(path);
const full = resolve(path);
const missing: string[] = [];
for (let dir = full; ; dir = dirname(dir)) {
try {
const real = join(realpathSync.native(dir), ...missing.reverse());
return process.platform === "win32" ? real.toLowerCase() : real;
} catch {
if (dirname(dir) === dir) return process.platform === "win32" ? full.toLowerCase() : full;
missing.push(basename(dir));
}
}
return process.platform === "win32" ? full.toLowerCase() : full;
}
function contains(parent: string, child: string): boolean {
@@ -33,17 +37,33 @@ function projectRoot(cwd: string, home: string): string {
return root;
}
/** Whether a program in `dir` may be run without the person naming it. */
export function isTrustedDirectory(dir: string): boolean {
if (!dir || !isAbsolute(dir)) return false;
const target = comparable(dir);
function ancestorNodeModules(cwd: string): string[] {
const folders: string[] = [];
for (let dir = dirname(cwd); ; dir = dirname(dir)) {
folders.push(comparable(join(dir, "node_modules")));
if (dirname(dir) === dir) return folders;
}
}
function trustRule(): (dir: string) => boolean {
const cwd = comparable(process.cwd());
if (target === cwd) return false;
const home = comparable(homedir());
// From the home folder (or above it) every per-user install dir is inside; skip only the folder.
if (contains(cwd, home)) return true;
// `npm run` puts every ancestor's node_modules/.bin on PATH, so from a subfolder the whole project is untrusted.
return !contains(projectRoot(cwd, home), target);
const fromHome = contains(cwd, home);
const project = fromHome ? cwd : projectRoot(cwd, home);
// `npm run` puts every ancestor's node_modules/.bin on PATH, at and above home too.
const nodeModules = ancestorNodeModules(cwd);
return (dir) => {
if (!dir || !isAbsolute(dir)) return false;
const target = comparable(dir);
if (target === cwd || nodeModules.some((folder) => contains(folder, target))) return false;
return fromHome || !contains(project, target);
};
}
/** Whether a program in `dir` may be run without the person naming it. */
export function isTrustedDirectory(dir: string): boolean {
return trustRule()(dir);
}
/** Whether `file` is an absolute path in a folder {@link isTrustedDirectory} accepts. */
@@ -59,7 +79,8 @@ function expandHome(dir: string): string {
/** 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);
return [...new Set(entries.filter((dir) => isTrustedDirectory(dir)))];
const trusted = trustRule();
return [...new Set(entries.filter((dir) => trusted(dir)))];
}
function windowsExtensions(): string[] {