Hardening npm, pnpm, and bun Against Supply Chain Attacks
Better Stackgo watch the original →
the gist
Prevent malicious package execution by gating release ages, disabling install scripts, blocking exotic git dependencies, and using automated security firewalls like Socket or npq.
Configuration Hardening
Supply chain attacks often rely on executing malicious code immediately upon installation or exploiting untrusted package sources. You can mitigate these risks by modifying package manager configurations:
- Release Age Gating: Prevent the installation of brand-new, potentially malicious packages by setting a minimum age threshold. For npm, configure this in
.npmrc. For pnpm, setpackage-import-methodor use workspace settings inpnpm-workspace.yaml. For bun, usebunfig.tomlto set the age in seconds. - Disable Install Scripts: Most attacks use
postinstallscripts to execute code. pnpm and bun disable these by default, but you should explicitly manage them. In bun, usetrustedDependenciesinpackage.jsonto whitelist only necessary packages. For npm, consider usinglava-moatto enforce an allow-list. - Restrict Exotic Dependencies: Attackers often use git-based URLs to bypass registry security. In npm, set
allow-git=noneorallow-git=rootin your config. In pnpm, enableblock-exotic-sub-dependencies=trueto ensure only direct dependencies can use non-registry sources.
Automated Security Tooling
Static configuration is insufficient against sophisticated threats. Integrate automated scanning tools into your workflow to audit dependencies before they reach your local machine:
- Socket Firewall: This tool intercepts install commands to block human-confirmed malicious packages and flag AI-detected threats. It supports npm, pnpm, bun, pip, and cargo.
- npq: This utility aliases your install commands to scan packages against the Snyk database, check for typo-squatting, verify registry signatures, and report on maintainer metadata before installation.
- Lockfile Integrity: To prevent attackers from tampering with resolved URLs in your lockfile, use
lockfile-lint. This ensures all packages resolve from trusted hosts and that integrity hashes match the expected values.
Operational Habits
- Use Clean Installs: Always use
npm ci(orpnpm install --frozen-lockfile/bun install --frozen-lockfile) in CI/CD environments to ensure the installation matches the lockfile exactly and fails if discrepancies exist. - Minimize Dependencies: Every dependency increases your attack surface. Replace heavy libraries like
lodashoraxioswith native JavaScript snippets orfetchwhere possible. - Deliberate Upgrades: Avoid bulk updates. Pin dependencies to exact versions to ensure that every upgrade is a conscious, vetted decision rather than an automated drift.