Common JavaScript Supply Chain Attack Vectors
Supply chain attacks targeting the npm ecosystem exploit the heavy reliance on transitive dependencies. A single compromised package can affect thousands of downstream applications because npm installs the entire dependency tree by default. Attackers have multiple reliable entry points that require distinct defenses.
Compromised maintainer attacks occur when an attacker gains control of a popular package through social engineering, stolen credentials, or expired maintainer accounts. The 2018 event-stream incident demonstrated the impact: after a maintainer transfer, the package received an update containing obfuscated code that scanned for a specific cryptocurrency wallet library (copay) and exfiltrated private keys when present in the same dependency tree. The malicious code used domain generation algorithms and encrypted C2 communication to avoid detection.
Dependency confusion attacks exploit differences between public and private package resolution. An attacker publishes a package with an identical name to an internal module used by a company. If the company's CI uses npm install without the --registry flag properly locked or without npm scopes, the malicious public package is installed instead. This technique was systematically demonstrated in 2021 against multiple large technology organizations, resulting in proof-of-concept packages being installed in private CI environments at companies including Apple and Microsoft.
Typosquatting targets developers who mistype package names during npm install. Packages such as lodash versus lodas, request versus requeest, or web3 versus web3-js have been used to distribute information stealers or cryptominers. These packages often copy the legitimate README, description, and even some source code to appear authentic while adding a malicious postinstall script that executes only on certain platforms.
Persistent malicious code is frequently hidden using obfuscation techniques such as hexadecimal encoding, multiple layers of eval(), or dynamic require() statements that only activate under specific conditions such as detecting a production environment or particular environment variables. Because npm packages can execute arbitrary code during installation via lifecycle scripts (preinstall, install, postinstall), the attack surface begins before any application code runs. The colors.js incident in 2022, while primarily protestware, illustrated how a single popular utility can disrupt thousands of builds when its maintainer intentionally introduced breaking changes.
These vectors remain effective because many development teams focus exclusively on application-level vulnerabilities while treating dependencies as trusted black boxes. Effective defense requires controls at publication time, installation time, build time, and runtime.
npm Lockfiles, packageManager Field and Install Best Practices
The package-lock.json file is the first line of defense. Generated with npm install, it records exact versions, integrity hashes, and resolved URLs for every package and its transitive dependencies. Using npm ci in CI environments instead of npm install enforces the lockfile and fails fast if the lockfile is missing, outdated, or inconsistent. This command also deletes node_modules before installation, ensuring a clean slate.
Since npm v7, the package.json can declare a packageManager field to lock both the package manager and its exact version. The following configuration pins npm 10.2.4:
{
"name": "my-saas-app",
"packageManager": "npm@10.2.4",
"dependencies": {
"next": "15.0.1"
}
}
This field is respected by corepack (enabled with corepack enable) and by GitHub Actions when using actions/setup-node with cache: 'npm'. Combined with .npmrc settings such as engine-strict=true, teams can reject installations when the wrong npm version is used, preventing subtle differences in dependency resolution between developer machines and CI runners.
Integrity verification happens automatically. Each entry in the lockfile contains a SHA512 hash under the integrity key. npm refuses to install any package whose tarball contents do not match this hash. However, lockfiles only protect against tampering after the package has been published to the registry; they do not prevent malicious code from being published by a compromised maintainer or through dependency confusion.
Additional hardening includes committing the lockfile to version control for every environment (production, staging, development) and using npm ci --ignore-scripts in high-security CI jobs. For monorepos using npm workspaces, the root package-lock.json must be updated with npm install from the workspace root after any dependency change.
npm Provenance Attestations
npm provenance, stabilized after its introduction in npm v8.6.0 and fully supported in npm v9 and v10, attaches cryptographically signed statements to published packages declaring where and how they were built. When enabled, npm automatically generates an attestation using the GitHub OIDC provider stating that the package was built from a specific repository, commit SHA, workflow file, and runner environment.
To publish with provenance use the exact command inside a GitHub Actions workflow:
npm publish --provenance --access public
This requires three conditions: the repository must be public, the workflow must have the id-token: write and contents: read permissions, and the NPM_TOKEN must have publish rights. The resulting package on the npm registry includes a provenance field containing a Sigstore bundle with an intoto attestation.
Verification is performed locally with:
npm audit signatures
npm audit signatures --json
The npm registry web interface displays a "Provenance" badge with a direct link to the signed attestation on the package page. The attestation can be independently verified using the sigstore tooling without trusting npm or GitHub. Teams should add a post-publish step that parses the JSON output of npm audit signatures and fails the build if any package lacks a valid provenance statement.
Provenance prevents an attacker who has stolen npm credentials from publishing a malicious version from their local machine, because the attestation would not match the repository's CI workflow identity. It also creates an auditable chain from source control commit to the exact tarball downloaded by consumers. Common pitfalls include using self-hosted runners without proper OIDC configuration or attempting to publish from local machines, both of which result in missing provenance.
Achieving SLSA Level 3 with GitHub Actions
The Supply-chain Levels for Software Artifacts (SLSA) framework defines progressive integrity controls. SLSA Level 3 requires that builds are performed on ephemeral, isolated runners, that all build steps are declared in a verifiable build definition, that provenance is generated and signed, and that the builder is hermetic. The official slsa-framework/slsa-github-generator at version v1.9.0 makes SLSA L3 attainable for JavaScript projects without writing custom builders.
A complete production workflow combining SLSA L3 and npm provenance follows:
name: SLSA3 Build and Publish
on:
release:
types: [created]
permissions:
contents: read
id-token: write
attestations: write
jobs:
build:
runs-on: ubuntu-latest
outputs:
base64-subjects: ${{ steps.package.outputs.base64-subjects }}
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 # v4.0.2
with:
node-version: 20.11.0
cache: 'npm'
- run: npm ci --ignore-scripts
- name: Build artifacts
run: npm run build
- name: Generate subject for provenance
id: package
run: |
echo "base64-subjects=$(echo -n 'pkg:npm/my-package@1.2.3' | base64 -w0)" >> $GITHUB_OUTPUT
- name: Generate SLSA provenance
uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v1.9.0
with:
base64-subjects: "${{ steps.package.outputs.base64-subjects }}"
upload-assets: true
publish:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 # v4.0.2
with:
node-version: 20.11.0
registry-url: 'https://registry.npmjs.org'
- run: npm ci --ignore-scripts
- run: npm publish --provenance --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
This workflow pins all actions to commit SHAs, uses npm ci --ignore-scripts, produces a signed intoto provenance attestation, and publishes with the npm provenance flag. The resulting artifacts can be verified with slsa-verifier using the command slsa-verifier verify-artifact --builder-id https://github.com/OWNER/REPO/.github/workflows/slsa.yml@refs/tags/v1.2.3.
Teams targeting SLSA L3 should also enable GitHub branch protection rules that require signed commits and status checks for the SLSA workflow. The additional 45-120 seconds of build time is the primary trade-off for smaller teams, but the verifiable build definition prevents tampering even if a GitHub Actions runner is compromised.
Keyless Signing with Sigstore and Cosign
Sigstore provides keyless signing backed by short-lived certificates issued through OpenID Connect from trusted providers including GitHub. The cosign CLI version 2.2.0 or later is the primary tool. Install it via go install sigs.k8s.io/cosign/v2/cmd/cosign@latest or use the official GitHub Action sigstore/cosign-installer.
While npm provenance uses Sigstore under the hood, teams often sign additional build artifacts such as Docker images, release tarballs, or compiled binaries. The command to sign a container image is:
cosign sign --yes us-east1-docker.pkg.dev/my-project/my-app@sha256:...
Verification uses an identity-based policy:
cosign verify us-east1-docker.pkg.dev/my-project/my-app@sha256:... \
--certificate-identity-regexp 'https://github.com/OWNER/REPO/.*' \
--certificate-oidc-issuer 'https://token.actions.githubusercontent.com'
For npm-specific workflows, sign the built .tgz package before publishing and store the signature alongside the SLSA attestation in the GitHub release. The transparency log entry in Rekor provides public auditability. Common operational practice is to run cosign verify as a gate in deployment pipelines before allowing any artifact to reach production clusters.
The removal of long-lived key management is a major operational win, but teams must ensure their OIDC identity is narrowly scoped. Overly broad regex patterns in verification policies reduce the security value of the signature.
Generating CycloneDX SBOMs for npm Projects
A Software Bill of Materials (SBOM) provides a machine-readable inventory of every component and is required for many compliance frameworks. For JavaScript, the CycloneDX standard is well supported by the official @cyclonedx/cyclonedx-npm package at version 1.11.0 or later.
Install globally or as a dev dependency and generate with:
npx @cyclonedx/cyclonedx-npm --output-format JSON --output-file bom.json --include-dev
For production-only SBOMs omit the --include-dev flag. The resulting bom.json contains every direct and transitive dependency, their versions, licenses, integrity hashes, and supplier information. Teams should generate the SBOM after npm ci but before publishing, then attach it as a release asset in the same GitHub workflow that generates the SLSA attestation.
Advanced usage includes merging SBOMs from multiple workspaces in a monorepo using the --workspace flag and validating the SBOM against the CycloneDX schema with cyclonedx validate. The SBOM can be consumed by tools such as Dependency-Track or GitHub Advanced Security for continuous vulnerability monitoring without re-installing the project. Storing SBOMs in a centralized artifact repository alongside each release version enables historical analysis when new vulnerabilities are disclosed months later.
CI/CD Integration and Automated Scanning
Effective supply chain security requires scanning at multiple points in the CI/CD pipeline. A production-grade GitHub workflow includes dependency review on pull requests, signature verification on releases, and SBOM generation on every tagged release.
Core scanning commands include npm audit --audit-level=high --omit=dev to focus only on production dependencies. The --audit-level flag can be set to moderate, high, or critical depending on risk tolerance. GitHub's dependency-review-action at v4 blocks PRs that introduce vulnerable components or forbidden licenses using this configuration:
- uses: actions/dependency-review-action@3b4a6b5c0a5e6e5e4e5f5e5d5c5b5a5d5e5f5e
with:
fail-on-severity: high
deny-licenses: GPL-3.0, AGPL-3.0, LGPL-3.0
retry-on-snapshot-warnings: true
Google's osv-scanner provides additional coverage by querying the OSV vulnerability database:
npx osv-scanner --lockfile ./package-lock.json --fail-on-vuln
Integrate these as sequential steps with clear failure messages. For repositories with legacy transitive vulnerabilities, maintain a .osv-suppressions.json file with expiry dates so suppressions older than 90 days automatically become failures again, preventing indefinite technical debt.
The final stage of the pipeline verifies all signatures and provenance before deployment. This multi-layered scanning approach catches both known CVEs and new malicious packages that have not yet been analyzed by the npm security team.
Hardening package.json, .npmrc and Monorepo Configurations
Beyond lockfiles, several fields and configuration options improve security posture. Use the overrides field available since npm v8.3.0 to force specific versions of vulnerable transitive dependencies across the entire tree:
"overrides": {
"braces": "^3.0.3",
"semver": "^7.5.4",
"xml2js": "^0.5.0"
}
The scripts section should avoid preinstall and install scripts when possible. If a dependency requires them, review the script contents manually before first installation by running npm pack on the dependency and inspecting the extracted tarball.
In .npmrc, enable strict settings for all environments:
audit=true
fund=false
ignore-scripts=true
package-lock=true
engine-strict=true
strict-peer-deps=true
For monorepos, the root .npmrc should include workspaces-update=false to prevent accidental updates. Teams using npm workspaces should run dependency commands exclusively from the workspace root to ensure a single unified lockfile.
Runtime Monitoring, Verification and Ongoing Maintenance
Build-time controls must be complemented by runtime defenses. Subresource Integrity (SRI) should be used when loading any JavaScript bundles from CDNs. The exact attribute is generated with:
openssl dgst -sha384 -binary bundle.js | openssl base64 -A
resulting in integrity="sha384-...". Content Security Policy headers with script-src 'self' 'sha384-...' further limit execution to only verified scripts.
Runtime dependency monitoring can watch for unexpected network calls or filesystem access patterns. Node.js applications can use the --require flag with a security module that instruments the require cache. Linux seccomp profiles or Docker seccomp filters limit the syscalls available to application code, blocking unexpected behaviors from compromised dependencies.
Ongoing maintenance includes monthly review of npm outdated output, automated Dependabot PRs with required reviewer approval for major version bumps, and quarterly full SLSA workflow tests. Rotate npm automation tokens every 90 days and monitor the npm audit feed for new advisories that affect your SBOM.
Implementation Decision Framework and Layered Controls
SLSA Level 3 and full provenance add measurable latency to build pipelines. A typical GitHub Actions workflow using the SLSA generator takes 45-150 seconds longer than a standard build due to isolated runner provisioning, artifact hashing, and attestation generation. For teams releasing multiple times per day this overhead must be weighed against the application's risk profile and data sensitivity.
Keyless Sigstore signing removes key management complexity but introduces dependency on the Sigstore public infrastructure and OIDC providers. If GitHub or the Sigstore Rekor log experiences an outage, signing and provenance generation are blocked. Organizations with extreme availability requirements sometimes maintain a fallback process using cosign with stored keys in a hardware security module, though this increases operational complexity.
SBOM generation and storage adds another artifact that must be versioned and distributed. The additional process complexity can slow velocity for small teams with limited DevOps resources. A pragmatic adoption path is to begin with the packageManager field and npm ci, add provenance on all releases, integrate the SLSA generator next, then add CycloneDX SBOM generation and dependency review gates. Each layer delivers measurable risk reduction and can be adopted independently while maintaining compatibility with existing workflows.
The highest security posture combines exact lockfiles, SLSA Level 3 provenance, Sigstore signatures on all artifacts, CycloneDX SBOMs attached to every release, automated vulnerability scanning with both npm audit and osv-scanner, strict .npmrc settings, and runtime integrity monitoring. This stack raises the cost to attackers dramatically while remaining achievable with open source tooling and GitHub's free tier for most small-to-medium development teams. The concrete commands, workflow examples, and verification steps provided enable immediate implementation without requiring new infrastructure or proprietary tools.
