Running npm install executes code from every package in the dependency tree that declares an install script, with the full permissions of the developer or CI job that ran it, before anyone has imported a line. That is how the Shai-Hulud worm and its successors stole npm, GitHub and cloud credentials from laptops and runners and then used them to republish more packages. The defences have improved sharply in 2026: npm 12 blocks dependency install scripts unless the project approves them, pnpm, Yarn and Bun ship similar allowlists, and all four can refuse versions that are too new. This guide covers what runs at install time, how to configure script allowlists and release-age cooldowns in each package manager, lockfile discipline, registry and dependency source settings, and how to keep credentials out of reach of install-time code. It is for developers, build engineers and platform teams who install JavaScript dependencies, and reflects package manager documentation read on 27 October 2026.
Key takeaways
- Install scripts are remote code execution by design.
preinstall,installandpostinstallrun arbitrary commands, and abinding.gypfile triggers a native build even without a declared script. - Default-deny is now available everywhere. npm 12's
allowScripts, pnpm'sallowBuildswithstrictDepBuilds, Yarn'senableScriptsand Bun'strustedDependenciesall let only reviewed packages run scripts. Use them, and pin approvals to versions. - A cooldown stops most worms. Malicious versions are usually found and removed within hours to days, so
min-release-age,minimumReleaseAgeornpmMinimalAgeGatekeep you from installing them while they are live. - Frozen lockfiles stop drift, not poisoning.
npm ciinstalls exactly what the lockfile says, so review lockfile changes as code, and prefer tools that re-verify lockfile entries. - Keep secrets away from installs. Run dependency installs in a step with no publish tokens, cloud credentials or write-capable CI tokens in its environment or files.
What runs when you install a package
npm's scripts documentation lists the lifecycle events that run during npm install and npm ci. Each one can execute any command the package author chooses.
| Trigger | When it runs | Security note |
|---|---|---|
preinstall | Before dependencies are fetched or unpacked | Runs earliest, with the job's environment; the usual first stage for credential stealers |
install, postinstall | After the package is placed in node_modules | Most common hook in malicious packages; also legitimately used to download or build native binaries |
binding.gyp with no install script | npm defaults install to node-gyp rebuild | Compiles native code, so it counts as install-time execution |
prepare for git dependencies | npm installs the git package's dependencies and devDependencies, runs prepare, then packs it | Pulls a second dependency tree and runs its code; npm 12 blocks git dependencies by default |
Explicit npm run, npm test, npx | When invoked | Not covered by install-script controls; npx and global installs need their own allowlist |
Install scripts receive the full process environment, so anything in environment variables, ~/.npmrc, cloud CLI configuration, SSH agents or the CI workspace is readable. The Shai-Hulud npm Worm, First Wave ran a bundled script at install time that collected environment variables, cloud secret manager contents and tokens found on disk, then used each npm token to publish infected versions of the owner's other packages. In ATT&CK terms this is T1195.001 Compromise Software Dependencies and Development Tools followed by T1552.001 Credentials In Files. See the Shai-Hulud npm Worm Guide for the campaign.
Script allowlists by package manager
The old advice was to set ignore-scripts=true and live with broken native modules. Every major client now offers an allowlist instead, and most deny by default.
| Client | Default for dependency scripts | Allowlist mechanism | Notes |
|---|---|---|---|
| npm 12 (12.0.0 released 8 July 2026) | Blocked unless approved | allowScripts in the root package.json, maintained with npm approve-scripts and npm deny-scripts | Approvals are pinned to pkg@version by default; denials (false) always win; run npm rebuild after approving |
| npm 11 and earlier | Run | ignore-scripts=true in .npmrc, or a plugin such as @lavamoat/allow-scripts as OWASP describes | Upgrade path: install npm 12 explicitly if your Node.js release bundles an older npm |
| pnpm (current docs, v12) | Disallowed and treated as unreviewed; strictDepBuilds defaults to true, so the install fails | allowBuilds map in pnpm-workspace.yaml with true or false per package or version range; pnpm approve-builds | onlyBuiltDependencies and neverBuiltDependencies were removed in v11 and replaced by allowBuilds; git dependencies need URL or commit keys |
| Yarn (Berry) | Current documentation lists enableScripts default false for third-party packages; workspace scripts still run | dependenciesMeta to control scripts per package | Check the default on your Yarn version before relying on it |
| Bun | Not run, except a curated default list of popular npm packages | trustedDependencies array in package.json | The default list applies only to registry packages; file: and git: sources must be listed explicitly to prevent name spoofing |
Operating an allowlist well
- Review before approving:
npm approve-scripts --allow-scripts-pendinglists packages whose scripts were skipped without changing anything. Read what each script does; many packages only need their script for optional features. - Keep approvals pinned: npm writes
[email protected]entries by default, so a new version of an approved package must be reviewed again. Name-only approvals (--no-allow-scripts-pin) let a hijacked future version run. - Record denials: a
falseentry stops the package being offered for approval again and documents the decision. pnpm'sallowBuildsand newerpermissionsmap work the same way. - Do not make the escape hatch permanent: npm's
--dangerously-allow-all-scriptsand pnpm'sdangerouslyAllowAllBuildsexist for migration; npm describes its use as "strongly discouraged". - Cover one-off contexts:
npx,npm execandnpm install -ghave no projectpackage.json, so npm uses theallow-scriptsconfig (for examplenpm config set allow-scripts=sharp --location=user). Passing--allow-scriptson a project install is an error by design. - Remember what allowlists do not cover: malicious code in a package's runtime files still runs when your application or tests import it. Allowlists move execution from install time to a point where other controls (sandboxing, tests, review) can act.
Release-age cooldowns
Worms depend on speed: a compromised version is published and installed by thousands of pipelines before anyone notices. The OpenSSF Concise Guide recommends a cooldown of typically around three days for updates without known vulnerabilities, and pnpm's documentation notes that most malicious releases are discovered and removed within an hour.
| Client | Setting | Default | Exceptions |
|---|---|---|---|
| npm | min-release-age=<days> or before=<date> | Not set | min-release-age-exclude (names or globs) |
| pnpm | minimumReleaseAge (minutes) | 1440 (one day), applied to transitive dependencies; strict only when you set it explicitly | minimumReleaseAgeExclude by name, pattern or exact version |
| Yarn | npmMinimalAgeGate | Documented as 1w | Per-package configuration |
- Pick a window you can live with: three to seven days catches most campaigns we have recorded while keeping dependencies reasonably fresh.
- Plan for urgent security fixes: npm notes that a cooldown can stop
npm audit fixinstalling a patched version, in which case it warns and exits non-zero. Add the package to the exclude list for that fix rather than disabling the cooldown. - Exempt your own scope carefully: excluding
@yourorg/*is common, but it means a compromise of your own publishing path is installed immediately. - Align automated update tools: configure Dependabot or Renovate with a matching minimum age so bots do not open, and auto-merge, pull requests for versions your installer would reject. See the Dependency Update Automation Guide.
Lockfiles and frozen installs
A lockfile records the exact version, resolved location and integrity hash (an SRI sha512 string) of every package. It only protects you if installs are forced to follow it.
- Use frozen installs in CI:
npm cirequires apackage-lock.json, fails if it does not matchpackage.json, deletes any existingnode_modulesand never writes either file. The equivalents arepnpm install --frozen-lockfileand Yarn's immutable installs, which Yarn documents as the default on CI. - Review lockfile diffs: a pull request that changes
resolvedURLs to an unfamiliar host, adds git or tarball sources, or bumps many transitive packages at once deserves scrutiny. Lockfiles are large and rarely read, which makes them a good hiding place. - Prefer clients that re-verify: pnpm re-applies
minimumReleaseAgeandtrustPolicyto every lockfile entry unlesstrustLockfileis true, and its documentation says to leave that false whenever outside collaborators can edit the lockfile. Yarn'senableHardenedModevalidates lockfile content against the registry and turns on automatically for pull requests from public repositories. - Keep
resolvedfields: npm cannot pin script approvals for entries without aresolvedURL, so avoid lockfile options that strip it. - Do not commit
node_modulesor rely on caches across trust boundaries: a cache written by an untrusted job can feed a trusted one.
Registry configuration and dependency sources
Where packages come from matters as much as what runs. npm 12 tightened defaults for non-registry sources.
| npm setting | Default (npm 12) | What it controls | Recommendation |
|---|---|---|---|
allow-git | none | Dependencies from git references, which run git against remote repositories | Keep none; use root only if your own package.json needs a git dependency |
allow-remote | none | Tarball URL dependencies on hosts other than the configured registry | Keep none; use replace-registry-host if your registry serves tarballs from another host |
allow-file, allow-directory | all | Local tarballs and directories | Set root in CI so transitive packages cannot point at local paths |
@yourorg:registry= | Not set | Which registry serves a scope | Map every internal scope to your private registry to prevent dependency confusion |
strict-ssl | true | TLS validation to registries | Never disable; add corporate CAs with cafile instead |
- pnpm equivalent:
blockExoticSubdeps(default true) allows git and tarball URL sources only for direct dependencies; transitive packages must come from the registry or other trusted sources. - Dependency confusion: OWASP's npm cheat sheet advises scoped names for internal packages, scope-to-registry mapping in
.npmrc, and reserving internal names on the public registry. See the Malicious Package and Dependency Confusion Guide. - Use a proxy registry with policy: a repository manager in front of the public registry can enforce age gates, block known-malicious versions and keep an audit trail of what was fetched.
- Typosquats and hallucinated names: allowlists do not help if you approve the wrong package. See the Slopsquatting and Package Hallucination Guide.
Where identity fits: keeping credentials out of reach
Install-time malware is a credential thief first. The question is what it can find.
- Separate install from privileged steps: run
npm ciin a job or container with no publish tokens, cloud credentials or write-capableGITHUB_TOKEN. Pass built artefacts to later jobs that hold credentials. - Use read-only tokens for private registries: scope them to the packages needed, inject them only for the install step, and never write them to a persistent
~/.npmrc. See the npm Tokens Security Guide. - Remove publish tokens entirely: trusted publishing removes the most valuable thing a worm can steal. See the npm Trusted Publishing and Provenance Guide.
- Use ephemeral runners and restrict egress so stolen data has nowhere to go and nothing persists between jobs.
- Protect developer machines: install in dev containers or VMs for untrusted projects, keep cloud credentials short-lived, and avoid long-lived tokens in shell profiles. See the Developer Workstation and IDE Security Guide.
Rolling out install-time controls
- Inventory: list projects, package managers and versions, and which dependencies declare install scripts (
npm approve-scripts --allow-scripts-pendingor pnpm's ignored builds report). - Pilot in audit mode: on npm 11, run CI once with
--ignore-scriptsto see what breaks; on npm 12 or pnpm, the install output lists skipped scripts. Fix or approve each. - Commit the policy:
allowScripts,allowBuilds,trustedDependenciesand cooldown settings go into the repository so every developer and runner shares them. - Enforce in CI: frozen installs, the cooldown, strict build checks and source restrictions, with the install step isolated from secrets.
- Extend to developers: user-level
.npmrcsettings fornpxand global installs. - Rollback: if a legitimate package breaks, approve it with a pinned entry rather than turning the policy off; keep the previous lockfile and configuration in version control so a revert is one commit.
Decision guidance: on npm, upgrading to npm 12 gives default-deny with the least effort; teams that cannot upgrade yet should use ignore-scripts=true plus explicit npm rebuild for the few packages that need it. pnpm suits monorepos that want strict failure on unreviewed builds and lockfile re-verification. Small teams can rely on client defaults plus a cooldown; large organisations should add a proxy registry with central policy and a shared configuration package.
Detection and measurement
| Signal | Source | Meaning |
|---|---|---|
| New entries in skipped-script or ignored-build reports | Install output in CI logs | A dependency newly added or updated an install script |
| Outbound connections during dependency install | Runner egress logs, network policy denials | Exfiltration or second-stage download |
Processes reading ~/.npmrc, cloud credential files or running secret scanners during install | EDR on developer machines and self-hosted runners | Credential harvesting |
| New public repositories or workflows created by a developer's token | GitHub audit log | Worm behaviour seen in Shai-Hulud |
| Lockfile changes adding git, tarball or new registry hosts | Pull request diff checks | Source manipulation or dependency confusion |
- Allowlist coverage: share of repositories with a committed default-deny script policy. Target 100%.
- Approved scripts per project: trend downwards as packages that do not need scripts are denied.
- Cooldown coverage: share of CI pipelines enforcing a minimum release age of at least three days.
- Secret-free install steps: share of pipelines where the install step has no publish or cloud credentials.
- Frozen install rate: share of CI installs using
npm cior an equivalent.
Common failure patterns
- Approving everything to unblock a build:
npm approve-scripts --allor a permanentdangerouslyAllowAllBuildsturns default-deny back into default-allow. - Name-only approvals: an approval that covers any future version runs the hijacked version too.
- Installing in the same job that publishes or deploys: install-time code inherits every secret the job holds, which is how worms obtain publish tokens.
- Cooldowns with broad exclusions: excluding popular frameworks or your whole organisation scope removes protection where compromise is most likely.
- Trusting the lockfile from an untrusted pull request: frozen installs faithfully install whatever a poisoned lockfile specifies.
- Forgetting
npxand global tools: one-off executions bypass project policy unless user-level configuration covers them.
Lessons from incidents
The 2025 and 2026 npm worms share a pattern: a stolen maintainer token publishes a version with an install-time payload, the payload steals more tokens from whoever installs it, and the cycle repeats within hours. Campaigns recorded in our breach database, including the first Shai-Hulud wave and the Shai-Hulud npm Worm 2025 follow-up, whose preinstall script launched a payload on developer machines and CI runners and created more than 25,000 exfiltration repositories, relied on three things this guide addresses: install scripts that ran without review, fresh versions installed immediately, and credentials available to the installing process. Removing any one of the three breaks the chain for your organisation.
Framework mapping
| Framework | Reference | Install-time control |
|---|---|---|
| NIST SP 800-53 Rev. 5 | CM-7 Least Functionality, CM-11 User-installed Software | Default-deny install scripts, restricted dependency sources |
| NIST SP 800-53 Rev. 5 | SR-3 Supply Chain Controls and Processes, SR-11 Component Authenticity, SI-7 | Cooldowns, proxy registry policy, lockfile integrity hashes |
| NIST CSF 2.0 | ID.RA-09, PR.PS-02 | Assess components before use; maintain dependencies with risk-based timing |
| MITRE ATT&CK v20 | T1195.001, T1195.002, T1059.007, T1552.001 | Malicious dependencies, JavaScript execution at install, credential theft from files |
| OWASP | NPM Security Cheat Sheet | Lockfile enforcement, script control, dependency confusion defences |
Practitioner checklist
- Upgrade to npm 12 or configure an equivalent default-deny script policy in pnpm, Yarn or Bun.
- Commit the script allowlist with version-pinned approvals and explicit denials, and review pending scripts before approving.
- Set a release-age cooldown of three to seven days in the client and in dependency update bots, with narrow, documented exclusions.
- Use frozen installs (
npm ci,--frozen-lockfile, immutable installs) in every CI pipeline. - Review lockfile changes and enable lockfile re-verification where your client supports it.
- Keep
allow-gitandallow-remoteatnone, setallow-fileandallow-directorytorootin CI, and map internal scopes to your private registry. - Run installs in steps with no publish tokens, cloud credentials or write-capable CI tokens, on ephemeral runners with restricted egress.
- Configure user-level allowlists for
npxand global installs on developer machines. - Alert on network activity and credential file access during installs, and on lockfile source changes.
Standards and references
- npm Docs: scripts
- npm Docs: config (allow-scripts, allow-git, min-release-age)
- npm Docs: npm-approve-scripts
- npm Docs: npm-ci
- pnpm: Settings (allowBuilds, strictDepBuilds, minimumReleaseAge)
- Yarn: Configuration options (.yarnrc.yml)
- Bun: Lifecycle scripts
- OWASP: NPM Security Cheat Sheet
Related NHI Mgmt Group resources: Node.js Security Guide · Shai-Hulud npm Worm Guide · Malicious Open Source Package Response Playbook · Software Supply Chain Security Guide