npm Supply Chain Attacks: How to Protect Your Codebase in 2026
How npm supply chain attacks work, the real incidents behind them, and the npm security best practices I use for lockfiles, install scripts, and CI.
By Pavle AleksicSecurity & Best PracticesUpdated 19 min read
On this page
- The short answer
- What an npm supply chain attack looks like
- The incidents worth learning from
- What npm and GitHub changed since
- Lockfile hygiene and npm ci
- Block install scripts by default
- Make new versions wait
- Pin and override transitive dependencies
- Provenance and trusted publishing
- Dependabot and Renovate config that doesn't auto-merge malware
- Where npm audit stops being enough
- SBOMs: know what you shipped
- Harden CI so a bad install can't reach your secrets
- Incident response: the checklist for the day it hits you
- Frequently asked questions
- What is an npm supply chain attack?
- Does npm audit protect me from supply chain attacks?
- Should I use --ignore-scripts?
- How long should I wait before installing a new package version?
- Is pnpm more secure than npm?
- What should I do if I installed a compromised package?
- Do I need an SBOM?
- Working with me
If you run npm install in CI and you haven't thought hard about what actually executes on your build server, the last year should have your attention. An npm supply chain attack doesn't need a bug in your code. It needs one maintainer in your dependency tree to get phished, and a version range in your package.json loose enough to pull in whatever they publish next.
I've shipped JavaScript for the better part of two decades, and the threat model has flipped. The dangerous code is no longer the code you wrote. It's the hundreds or thousands of transitive dependencies you never read, any of which can run code on your laptop or your CI runner the moment it's installed. The build server is the soft target, because that's where the cloud credentials, npm tokens, and deploy keys live.
This post is for engineering leads, solo developers, and founders who own a JavaScript codebase and want a concrete, current playbook. It covers how these attacks actually work, the incidents worth learning from (with sources), what npm and pnpm changed in response, and the npm security best practices I apply on projects I take over: lockfile discipline, blocking install scripts, delaying new versions, provenance, Dependabot and Renovate config, SBOMs, CI hardening, and an incident-response checklist for the day it happens to you.
The short answer
If you only do five things this week:
- Install from the lockfile in CI with
npm ci, nevernpm install, and review lockfile diffs in PRs. - Stop dependency install scripts from running by default. npm 12 and pnpm 11 now do this out of the box; on older versions, turn it on yourself and allowlist the few packages that need a build step.
- Make new versions wait a few days before you install them, with
min-release-agein npm,minimumReleaseAgein pnpm or Renovate, orcooldownin Dependabot. - Get long-lived npm tokens out of CI. Publish with trusted publishing (OIDC), and keep install steps away from secrets.
- Have an incident-response checklist written down before you need it, including which credentials to rotate and in what order.
Everything below is the detail behind those five.
What an npm supply chain attack looks like
These are the patterns that matter in practice:
- Compromised maintainer accounts. A popular, trusted package gets a malicious patch release pushed by an attacker who phished or session-hijacked the maintainer. You didn't add a dependency. A
^range silently pulled in the poisoned version. - Malicious install scripts. The payload doesn't need to be imported. A
preinstallorpostinstallscript runs duringnpm installand reads~/.npmrc,~/.aws, environment variables, and CI secrets before your build starts. - Self-replicating worms. The payload steals the victim's npm token and uses it to publish trojanized versions of other packages that person maintains, turning one compromise into hundreds without human effort.
- Typosquatting and slopsquatting. A package one keystroke away from a real one, or a name an LLM hallucinated that someone then registered. The OWASP NPM Security Cheat Sheet now covers both.
- Maintainer handoff. An attacker volunteers to maintain an abandoned package, gets publish rights, and ships malware months later.
- Git and URL dependencies. Dependencies resolved from git or remote tarballs bypass registry checks entirely, and GitHub has noted that git dependencies can carry
.npmrcfiles that execute code during install even with--ignore-scripts.
The common thread: installing a package is executing code written by a stranger. Treat it that way. It's also why the 2025 OWASP Top 10 broadened "Vulnerable and Outdated Components" into a new A03 category, Software Supply Chain Failures (I cover the list in my OWASP Top 10 guide).
The incidents worth learning from
I only list incidents here that I could tie to a primary or official source. Each one teaches something specific.
| When | Incident | What happened | The lesson |
|---|---|---|---|
| Sep to Nov 2018 | event-stream | A new maintainer, who got access by offering to help, added flatmap-stream as a dependency in 3.3.6. It carried an encrypted payload targeting the Copay bitcoin wallet. | Maintainer handoff is an attack vector. Pin and review what a "patch" actually changed. |
| Oct 22, 2021 | ua-parser-js | The maintainer's account was hijacked and versions 0.7.29, 0.8.0, and 1.0.0 were published with malware. | Treat any machine that installed a bad version as compromised, not just the app. |
| Sep 8, 2025 | chalk, debug, and others | A maintainer was phished via a look-alike npm support domain. Malicious versions injected browser code that redirected crypto transactions. | 2FA that can be phished isn't enough. Waiting a few days would have avoided it. |
| Sep 2025 | Shai-Hulud | A self-replicating worm stole secrets and npm tokens, then republished other packages owned by each victim. More than 500 packages were affected. | Install-time scripts plus long-lived tokens let malware spread on its own. |
| Nov 2025 | Shai-Hulud 2.0 | A second wave ran in preinstall, harvested credentials with TruffleHog, and published stolen data to new GitHub repos. | preinstall runs before anything else. Scripts off by default is the real fix. |
The sources: npm's own event-stream incident write-up and the original GitHub issue; the GitHub advisory for ua-parser-js, which says to rotate every secret on an affected machine from a different computer; the GitHub advisory for debug 4.4.2; and the CISA alert on the npm ecosystem compromise from September 23, 2025.
On Shai-Hulud, CISA's description is worth reading in full. The worm scanned for GitHub personal access tokens and AWS, GCP, and Azure keys, exfiltrated them, and pushed them to a public GitHub repo named Shai-Hulud. It then used the victim's npm credentials to inject code into their other packages and publish new versions. GitHub's response post says it was notified on September 14, 2025 and removed more than 500 compromised packages.
The November wave, which security firm mnemonic documented as Shai-Hulud 2.0, started uploading malicious versions between November 21 and 23, 2025. It added a preinstall hook that installed the Bun runtime to run a large obfuscated payload, and if it couldn't steal credentials, it tried to delete writable files in the user's home directory. The counts kept rising while it was reported, so I won't quote a final number.
What npm and GitHub changed since
The registry has tightened a lot since September 2025, and some of the advice you'll find online is now out of date.
- Classic tokens are gone. GitHub permanently revoked all npm classic tokens on December 9, 2025.
npm loginnow gives you a two-hour session, with 2FA enforced for publishing, and granular write tokens are capped at 90 days. - Trusted publishing is GA. npm trusted publishing with OIDC became generally available on July 31, 2025. CI publishes without any stored npm token.
- npm 12 turned install scripts off. The July 8, 2026 changelog announced npm 12 as generally available, with dependency lifecycle scripts and implicit
node-gypbuilds no longer running unless approved, and git and remote URL dependencies no longer resolved unless explicitly allowed. - 2FA-bypass tokens are being phased out for sensitive account actions, with direct publishing from those tokens expected to end around January 2027, per the same changelog.
None of this protects you if you're on an old npm in CI, if your lockfile pulls a bad version before it's caught, or if your own team's tokens leak. The registry raised the floor. You still own the house.
Lockfile hygiene and npm ci
Step one is making installs reproducible. npm install resolves ranges and can rewrite your lockfile. npm ci, per the npm docs, requires an existing package-lock.json, exits with an error if it disagrees with package.json, deletes any existing node_modules, and never writes to either file.
# In CI, never this:
npm install
# Always this: exact, lockfile-driven, no surprise resolutions
npm ci
# pnpm and Yarn equivalents
pnpm install --frozen-lockfile
yarn install --immutableThe lockfile is only as good as your review of it. The rules I put in place on every project:
- Commit it, always, and one lockfile per repo. A
package-lock.jsonsitting next to apnpm-lock.yamlmeans someone is installing from the wrong one. - Review lockfile diffs. A 4,000-line lockfile diff in a PR titled "fix typo" is exactly where a malicious version bump hides. Make dependency changes separate PRs.
- Check the
resolvedURLs. Every entry should point at your registry. Agit+httpsor random tarball URL deserves a question. - Keep the lockfile current deliberately, through Dependabot or Renovate PRs, not as a side effect of someone running
npm installlocally. - Add new dependencies on purpose. Before adding a package, check its age, maintainers, repo link, and download history with
npm view. That's how you catch slopsquats.
Block install scripts by default
Install scripts are the single most abused vector, and most packages don't need them. What you do depends on your package manager version.
npm 12 and later. Dependency install scripts are blocked by default. Review and approve the ones you need, then commit the resulting allowlist, which npm writes to package.json:
# See which dependencies have install scripts that are currently blocked
npm approve-scripts --allow-scripts-pending
# Approve the few you trust (entries are pinned to the installed version by default)
npm approve-scripts esbuild sharp
# Explicitly deny the rest so the decision is recorded
npm deny-scripts some-telemetry-packageBy default an unapproved script is skipped with a warning. Set strict-allow-scripts=true in .npmrc if you'd rather the install fail, which I prefer in CI so nobody misses the warning. The npm config reference documents all of these, plus dangerously-allow-all-scripts, which you should treat as a red flag in code review.
npm 11. Upgrade to npm 11.16 or later to get the same policy as warnings, or use the blunt instrument:
# .npmrc, checked into the repo
ignore-scripts=true
allow-git=noneThen rebuild only the packages you've vetted with npm rebuild esbuild sharp. One catch: ignore-scripts also stops your own project's lifecycle scripts like prepare, so you may need to call them explicitly.
pnpm. pnpm 10.0.0 stopped running dependency lifecycle scripts by default, and pnpm 11 replaced onlyBuiltDependencies with allowBuilds. With strictDepBuilds on by default, an install fails if a dependency has a build script nobody has reviewed:
# pnpm-workspace.yaml
allowBuilds:
esbuild: true
sharp: true
core-js: false # its postinstall only prints a message; deny it
strictDepBuilds: trueIf a brand-new dependency suddenly needs an install script to function, that is a signal to investigate before it goes on the allowlist.
Make new versions wait
This is counterintuitive, so stay with me. Malicious versions are usually caught and pulled within hours to days. The September 2025 chalk and debug versions were spotted within hours of publication. If your tooling installs releases the minute they appear, you're on the front line of every attack. If it waits a few days, someone else's alarm goes off first.
All the major tools now support a minimum release age. Note the units differ, which trips people up:
# .npmrc: npm, in DAYS
min-release-age=3# pnpm-workspace.yaml: pnpm, in MINUTES (pnpm 11 defaults to 1440, one day)
minimumReleaseAge: 4320
minimumReleaseAgeExclude:
- "@my-company/*" # your own packages don't need to waitIn npm, min-release-age works by setting an internal before date, so it applies to every install, not just updates. The pnpm docs also describe trustPolicy: no-downgrade, which fails an install if a package's trust level drops compared to earlier releases, for example a package that always shipped with provenance suddenly publishing without it. That's exactly the signal a stolen token produces.
The tradeoff is real: when a genuine security fix ships, you want it now. All of these tools let you exclude specific packages, and Dependabot's cooldown doesn't apply to security updates at all.
Pin and override transitive dependencies
Direct dependencies are easy to reason about. Transitive ones are where you get burned. The overrides field forces a specific version deep in the tree, to patch a known-bad release or to pin something that keeps drifting:
{
"overrides": {
"debug": "4.4.3",
"minimist": "1.2.8",
"@babel/traverse": {
"ms": "2.1.3"
}
}
}During an active incident, overrides is how you force every path in your tree onto a clean version without waiting for each intermediate maintainer to release. pnpm has the same feature under overrides in pnpm-workspace.yaml. Document why each override exists, and remove it when it's no longer needed, or it becomes its own form of drift.
Provenance and trusted publishing
Provenance is a signed statement of which repository and which CI workflow built a package. It won't stop a maintainer from going rogue, but it turns "this artifact came from the repo I think it did" into a checkable fact. On the consumer side:
# Verify registry signatures and provenance attestations of installed packages
npm audit signaturesIf you publish packages, trusted publishing is the biggest single improvement you can make. Per the npm trusted publishing docs, it works from GitHub Actions, GitLab CI/CD, and CircleCI cloud runners (not self-hosted), needs npm CLI 11.5.1 or later and Node 22.14.0 or later, and generates provenance automatically for public packages from public repos on GitHub and GitLab. There is no token to steal:
name: Publish
on:
push:
tags: ["v*"]
permissions:
contents: read
id-token: write # OIDC for trusted publishing
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version: "24"
registry-url: "https://registry.npmjs.org"
- run: npm ci
- run: npm test
- run: npm publish # no NODE_AUTH_TOKEN neededOnce it works, npm recommends going to the package's settings and choosing "Require two-factor authentication and disallow tokens," then revoking any automation tokens you no longer use. For extra safety, npm also supports staged publishing (npm stage publish), where a human approves with 2FA before the version goes live. Shai-Hulud spread because tokens could publish without a human. Take that ability away.
Dependabot and Renovate config that doesn't auto-merge malware
Dependency bots are good. Auto-merging every PR the minute it opens is not. Here's a Dependabot config with grouping and a cooldown, using the cooldown option:
# .github/dependabot.yml
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
cooldown:
default-days: 5
semver-major-days: 30
semver-minor-days: 7
semver-patch-days: 3
groups:
minor-and-patch:
update-types: ["minor", "patch"]
open-pull-requests-limit: 5
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
cooldown:
default-days: 7And the Renovate equivalent, using minimumReleaseAge. Renovate's own docs suggest at least 3 days for npm, since packages younger than 72 hours can still be unpublished:
{
"extends": ["config:recommended"],
"minimumReleaseAge": "5 days",
"internalChecksFilter": "strict",
"prCreation": "not-pending",
"packageRules": [
{
"matchUpdateTypes": ["patch"],
"matchCurrentVersion": "!/^0/",
"automerge": true
},
{
"matchUpdateTypes": ["major"],
"minimumReleaseAge": "14 days"
}
]
}With internalChecksFilter: "strict", Renovate won't raise a PR for a version that's still inside the age window. If you do auto-merge patches, only do it with a real test suite and the age gate in place.
Where npm audit stops being enough
npm audit checks known advisories. It tells you nothing about a malicious version published an hour ago, because there's no advisory yet. Behavioral scanners (Socket is the one I see most, and there are others) flag packages that suddenly add install scripts, network calls, or obfuscated code in a patch release, which is how new attacks get spotted before a CVE exists. Run both: npm audit --audit-level=high for the known, a behavioral check on dependency PRs for the unknown.
SBOMs: know what you shipped
When the next incident drops, the first question is "are we affected?" If answering it means grepping lockfiles across 30 repos by hand, you've lost an afternoon you didn't have. Generate a Software Bill of Materials on every build and keep it with the artifact:
# CycloneDX or SPDX, omitting dev dependencies for a production SBOM
npm sbom --sbom-format cyclonedx --omit dev > sbom.cdx.jsonThe npm sbom command supports both cyclonedx and spdx formats. Store the file as a build artifact or attach it to the release. Then "which of our deployed services shipped debug@4.4.2?" is a query, not a scramble. Enterprise customers increasingly ask for SBOMs in security questionnaires, too, so it pays twice.
Harden CI so a bad install can't reach your secrets
Assume one day a malicious script does run on your runner. The goal is that it finds nothing worth stealing and can't phone home. This is the part of a GitHub Actions setup I look at first.
- Least-privilege
GITHUB_TOKEN. GitHub's security hardening guide recommends a read-only default with per-job increases. Putpermissions: contents: readat the top of every workflow. - Pin third-party actions to a full commit SHA, not a tag that can be moved. GitHub's guide now also describes a workflow lockfile as the stronger option where you can adopt it.
- Separate install from secrets. The install-and-test job should have no deploy credentials. Secrets belong only in the job that deploys, which consumes a built artifact and doesn't run
npm installagain. - Use OIDC for cloud access instead of long-lived AWS or GCP keys stored as repo secrets. Short-lived, workflow-scoped credentials can't be reused next week. My secrets management post covers the wider setup.
- Restrict egress where you can. Ephemeral, network-restricted runners (or tools like StepSecurity's Harden-Runner on GitHub-hosted runners) turn "exfiltrate to webhook.site" into a blocked request and an alert.
- Lock down
pull_request_targetand never check out and build untrusted fork code in a context with secrets. - Build in clean containers. A minimal production Dockerfile with
npm ci --omit=devin a separate stage keeps build tools and their dependencies out of what you ship.
Developer laptops deserve the same thinking. The September 2025 worm ran wherever npm install ran, and a laptop with a ~/.npmrc token, an AWS profile, and a GitHub CLI login is a richer target than most CI runners.
Incident response: the checklist for the day it hits you
When an advisory names a package you use, speed matters and panic doesn't help. This is the order I work in:
- Confirm exposure. Search lockfiles and SBOMs across every repo for the affected package and exact versions. Check caches and artifact registries (Artifactory, Verdaccio, CI caches) too, as CISA advised during Shai-Hulud.
- Freeze dependency changes. Pause Dependabot and Renovate auto-merges and block new installs that could re-resolve the bad version.
- Identify where it ran. List every CI run, developer machine, and container build that installed the bad version during the exposure window. "Installed" is what matters if the payload was an install script.
- Rotate credentials from a clean machine. npm tokens, GitHub tokens and SSH keys, cloud keys, and any secret that was in the environment of an affected run. The ua-parser-js advisory is explicit: assume the machine is fully compromised.
- Look for persistence and propagation. New GitHub repos you didn't create, unfamiliar self-hosted runners, new workflow files, unexpected package versions published under your org, new OAuth apps or webhooks.
- Pin to a clean version. Use
overridesto force a known-good release everywhere, regenerate the lockfile, and verify withnpm ls. - Rebuild and redeploy from clean runners, not cached layers that might contain the bad package.
- Check what shipped to users. The chalk and debug payload targeted browsers, so a frontend bundle built during the window needs rebuilding and redeploying even if your servers were fine.
- Write it down. A short post-incident note: exposure window, what ran where, what was rotated, and which control would have prevented it.
Keep this list in your repo's SECURITY.md or runbook, with the actual commands and the names of whoever can rotate which credentials. At 2 a.m. nobody remembers who owns the npm org.
Frequently asked questions
What is an npm supply chain attack?
It's an attack where malicious code reaches your application through a dependency rather than through your own code. Usually an attacker publishes a malicious version of a legitimate package (after stealing the maintainer's credentials) or registers a look-alike package, and the code runs when you install or import it. Install scripts make it worse, because the code runs before you've used the package at all.
Does npm audit protect me from supply chain attacks?
Only partly. npm audit checks your dependencies against known advisories, so it helps once an incident is public, but it can't catch a malicious version published an hour ago. Pair it with a release-age delay, blocked install scripts, and a behavioral scanner on dependency PRs.
Should I use --ignore-scripts?
On npm 11 or earlier, yes, as a default with an explicit rebuild list for the packages that need it. On npm 12, dependency scripts are already blocked unless approved, so use npm approve-scripts instead. On pnpm, review builds through allowBuilds.
How long should I wait before installing a new package version?
Three to seven days is a sensible default for most teams. Most malicious versions in the big 2025 incidents were caught within hours to days, and Renovate's docs suggest at least three days for npm because younger packages can still be unpublished. Exclude your own internal packages and fast-track genuine security fixes.
Is pnpm more secure than npm?
pnpm moved first on secure defaults: it blocks dependency build scripts and, from pnpm 11, applies a one-day minimum release age by default. npm 12 has since closed much of the gap on install scripts and git dependencies. Either is fine if you configure it deliberately; the package manager you configure carefully beats the one you don't.
What should I do if I installed a compromised package?
Assume every secret on that machine or CI runner is stolen. Rotate npm, GitHub, and cloud credentials from a different machine, check for persistence such as new repos, runners, or workflows, pin a clean version with overrides, and rebuild from clean environments. Then check whether the compromised code was bundled into anything you shipped to users.
Do I need an SBOM?
If you have more than a couple of services, or you sell to companies with security reviews, yes. An SBOM turns "are we affected?" into a quick search when an incident breaks, and npm sbom generates one in CycloneDX or SPDX format with no extra tooling.
Working with me
None of this is exotic, but it's the kind of work that slips while everyone is shipping features. I harden install pipelines, CI workflows, and dependency policies as part of my cloud and DevOps work and backend engagements, and it's one of the first things I check when taking over an existing codebase. If you want a second pair of eyes on your setup, or help on the day an advisory names one of your dependencies, get in touch.