What you'll learn: By the end of this lesson you will be able to explain why a front-end application is mostly code its team did not write, separate known vulnerabilities from malicious releases, describe what a lockfile pins and what
npm ciguarantees, name the three places dependency code runs (developer machines, CI and the user's browser), choose controls for each (install-script policy, release delay, audit, provenance, review of lockfile changes, SBOM), and say what each control does not do.
Think of a restaurant kitchen. The chef cooks, but the flour, the oil and the pre-made sauces come from suppliers, and the suppliers have suppliers. Food safety is not only about the chef's hands: it is about knowing which deliveries arrived, checking that this week's flour is the flour you ordered, and being able to name every kitchen that received a recalled batch. A modern front end is that kitchen. Its package.json lists a few dozen names, and the installed tree behind them is far larger.
The running example is the product page of a grocery marketplace, a React single-page app called shop-web that is built in CI and served as static files. Its package.json lists a few dozen direct dependencies; the full tree (direct plus transitive) holds on the order of a thousand packages (illustrative). The question: if one package three levels down publishes a bad version tomorrow, what stops it reaching your customers, and your build machines?
This lesson builds on how modules and packages are wired together (the planned lesson on JavaScript modules and TypeScript at scale; plain text for now). The browser-side defences it hands over to are in Content Security Policy and XSS Defenses.
The core idea
- Your application is mostly other people's code. OWASP's 2025 Top 10 category "Software Supply Chain Failures" describes breakdowns or compromises in the process of building, distributing or updating software, many of which come from vulnerable or malicious third-party code, tools or dependencies. It notes that components typically run with the same privileges as the application itself.
- There are two different problems. A known vulnerability is a flaw in a legitimate release that is later found and published. A malicious release is a version that someone deliberately made harmful, through a hijacked maintainer account, a bad new maintainer or a planted package. Audit tools handle the first well. The second needs controls that do not depend on anyone having noticed yet.
- Dependency code runs in three places. On the developer's machine and in CI during install and build (where secrets such as tokens live), and in every user's browser after the bundle ships. A control placed at one of them does nothing for the other two.
What gets installed, and what pins it
A dependency is declared as a version range. The npm documentation says dependencies map a package name to a range string, and the supported forms include exact versions, ~ and ^ ranges, wildcards and || unions. A range such as ^2.4.0 is a promise that npm may pick any newer matching release, so two installs a day apart can produce different trees.
The lockfile removes that drift. npm's documentation says package-lock.json records the exact tree that was generated, so later installs can rebuild identical trees despite intermediate dependency updates; it is meant to be committed, and it makes tree changes reviewable in diffs. Each entry carries a resolved field (where the package actually came from) and an integrity field, a sha512 or sha1 Subresource Integrity string for the artifact that was unpacked there.
npm ci is the install built for automation. The documentation says it needs an existing lockfile, exits with an error if the lockfile and package.json do not match, removes any existing node_modules first, and never writes to package.json or the lockfiles: "installs are essentially frozen". npm install in CI, by contrast, is allowed to update the lock when it and package.json disagree.
Two things the lockfile does not do. It does not say a pinned version is safe: a malicious version that was locked is locked. And it does not apply to a change you make deliberately: when a pull request updates the lock, someone has to read that diff.
Figure 1. Where dependency code runs
How to read this: the same registry feeds two places that hold credentials (the two boxes in the zone) and, through the bundle, every browser. An install-time attack goes after the left side; a bundled malicious package goes after the right. Different controls guard each.
Install scripts: code that runs before you have run anything
npm's lifecycle scripts include preinstall, install and postinstall, which run when a package is installed, and prepare, which runs on a local npm install without package arguments. A dependency can therefore run code on your machine at install time, before you import a single function from it. A package that has a binding.gyp file and no custom install script is built with node-gyp rebuild by default. Git and tarball dependencies add their own twist: npm's documentation says a git dependency triggers a build step if it uses workspaces or defines scripts such as build, prepare or postinstall.
Why this matters more than it first seems: CISA's alert on the September 2025 npm compromise, a self-replicating worm known as Shai-Hulud, says it compromised over 500 packages, scanned the environment for credentials such as GitHub tokens and cloud keys, and spread by logging in to the registry as the compromised developer and publishing tainted versions of that developer's other packages. OWASP's description adds that developer machines became prime targets. Install-time code is an attack surface of its own.
Two controls exist today. npm's --ignore-scripts setting stops npm running scripts from package.json files (the npm ci documentation lists it as a config that defaults to false). pnpm goes further in its current documentation: it does not run the build scripts of dependencies unless they are allowed in allowBuilds, and its strictDepBuilds setting, on by default, makes an install fail if a dependency has a build script that is not allowed. The right default for CI is "no scripts, then allow the few packages that need to compile something, by name".
Version delay, exotic sources and alerts
A bad release does the most damage in the window before anyone has noticed it. A delay between "published" and "installed" gives the community and the registry time to notice (how long that takes varies, and no delay guarantees it). pnpm's minimumReleaseAge setting is that idea: its documentation lists a default of 1440 minutes (one day), with 10080 (one week) as an example of a longer wait, and 0 to opt out. It also lists blockExoticSubdeps, on by default, which blocks transitive dependencies from using git repositories or direct tarball URLs, and a trustPolicy of no-downgrade that blocks a package whose trust level has dropped since earlier releases. These are pnpm features at the time of writing; check your own package manager's documentation for equivalents instead of assuming them.
Dependabot is GitHub's way of getting update pull requests on a schedule. Its documentation says you commit .github/dependabot.yml, one entry per ecosystem, with a schedule.interval, and that by default it updates only direct dependencies declared in a manifest, with an opt-in for indirect ones. Update pull requests make the version a reviewed decision.
Audit, provenance and what they tell you
npm audit sends a description of your dependencies to the registry and asks for a report of known vulnerabilities. Its documentation says that by default the bulk endpoint receives the name and versions of each package in the tree, that audit fix runs a full npm install and can apply only some fixes, and that fixes needing a SemVer-major change require --force. The word to hold on to is known: a freshly published malicious version that no advisory mentions yet passes.
npm audit signatures verifies the registry signatures and the provenance attestations of what you downloaded. Provenance is a statement linking a published package to its source repository and build instructions: npm's page says a provenance attestation is a link to the package's source code and build instructions from the build environment, signed through Sigstore and recorded in a public transparency ledger, with publishing from supported cloud CI providers (at the time of the page, GitHub Actions and GitLab CI/CD). The same page is plain about the limit: provenance "does not guarantee the package has no malicious code". It tells you where and how the file was built, so you can audit it and decide whether to trust it. A compromised maintainer pipeline can still publish a perfectly attested bad release.
SLSA (Supply-chain Levels for Software Artifacts) makes the same point from the producer's side. Its v1.0 Build track protects against tampering during or after the build; it does not address organisations that intentionally produce malicious software, and an artifact's SLSA level is independent of the level of its dependencies.
Figure 2. A malicious release, step by step
How to read this: each control cuts a different arrow. A lockfile stops a silent range upgrade, an install-script policy stops the second step even if the version is pulled, and a release delay keeps you off the new version while it is still unnoticed.
Reading the tree you actually have
You cannot defend what you cannot list. npm explain <name> (alias npm why) prints the chain of dependencies causing a package to be installed, so "why is this in my build" has an answer. An SBOM (software bill of materials) is the formal version of the same list: OWASP's prevention advice for this category starts with generating and managing an SBOM centrally, covering direct and transitive dependencies, and continuing with removing unused dependencies, monitoring CVE, NVD and OSV sources, obtaining components only from trusted sources and preferring signed packages.
The root overrides field in package.json lets you replace a package anywhere in the tree with another version or another package. It is read only from the root manifest, which makes it the emergency lever when a transitive dependency is found bad and its parent has not updated. Several copies of one library at different versions (see Independent Deployment and Shared Dependencies and Monorepos and Shared Libraries) mean more code to review and more places for a fix to miss.
Three illustrations
Illustration 1: the minimal example, what the lockfile hash is
A lockfile integrity value is a hash of the downloaded file, so a replaced file no longer matches. The check below uses Node's built-in crypto. The "tarball" is a stand-in string: the point is the mechanism, not a real package.
import { createHash } from "node:crypto";
const sri = (bytes) => "sha512-" + createHash("sha512").update(bytes).digest("base64");
const tarball = Buffer.from("pretend these are the bytes of chart-lib-2.4.1.tgz");
const lockedIntegrity = sri(tarball);
const tampered = Buffer.from("pretend these are the bytes of chart-lib-2.4.1.tgz, plus one line");
console.log("locked :", lockedIntegrity.slice(0, 24) + "...");
console.log("same file:", sri(tarball) === lockedIntegrity);
console.log("changed :", sri(tampered) === lockedIntegrity);
Output, from running it in Node 26.13.1:
locked : sha512-ma/c04sfsfcrrCilV...
same file: true
changed : false
The hash proves that the bytes you installed are the bytes that were locked, not that the locked bytes were good. That is the line between integrity and trust.
Illustration 2: the realistic example, linting a lockfile change
On the product page, a pull request that touches package-lock.json is a security-relevant change that reviewers rarely read. A small script can flag the entries worth a human look: packages resolved from somewhere other than the registry you expect, and entries with no integrity value. The lockfile below is constructed for the example, in the lockfileVersion: 3 shape the npm documentation describes.
const REGISTRY = "https://registry.npmjs.org/";
const lock = {
lockfileVersion: 3,
packages: {
"": { name: "shop-web" },
"node_modules/react": { version: "19.1.0", resolved: REGISTRY + "react/-/react-19.1.0.tgz", integrity: "sha512-AAAA" },
"node_modules/chart-lib": { version: "2.4.1", resolved: REGISTRY + "chart-lib/-/chart-lib-2.4.1.tgz", integrity: "sha512-BBBB" },
"node_modules/tiny-format": { version: "1.0.3", resolved: "git+ssh://git@example.com/someone/tiny-format.git#abc123" },
"node_modules/color-utils": { version: "3.0.0", resolved: "https://mirror.example.net/color-utils-3.0.0.tgz", integrity: "sha512-CCCC" },
},
};
function lint(lock) {
const problems = [];
for (const [path, entry] of Object.entries(lock.packages)) {
if (path === "") continue;
const name = path.replace("node_modules/", "");
if (!entry.resolved?.startsWith(REGISTRY)) problems.push(`${name}: resolved outside ${REGISTRY} (${new URL(entry.resolved.replace("git+ssh://git@", "ssh://")).host})`);
if (!entry.integrity) problems.push(`${name}: no integrity hash`);
}
return problems;
}
const found = lint(lock);
console.log(`${Object.keys(lock.packages).length - 1} packages checked, ${found.length} problems`);
for (const p of found) console.log(" -", p);
Output, from running it in Node 26.13.1:
4 packages checked, 3 problems
- tiny-format: resolved outside https://registry.npmjs.org/ (example.com)
- tiny-format: no integrity hash
- color-utils: resolved outside https://registry.npmjs.org/ (mirror.example.net)
Two of the three findings are about one git dependency (no integrity value, fetched from another host, and, per the npm documentation, possibly built with scripts). The third is a package resolved from a host other than the default registry, which can be legitimate when a company mirrors the registry: the script's job is to make a person confirm that on purpose. In CI this would fail the pull request until an exception is written into an allowlist.
Illustration 3: a failure, the "harmless" patch update
An automated job runs npm install before each build and the project has a range of ^2.4.0 for a small formatting package, with the lockfile in .gitignore because "it causes merge conflicts". One morning a new patch release of that package contains an install script that reads environment variables and sends them out. Nothing in the repository changed. The next CI run resolves the new version, runs the script with CI's secrets in the environment and builds a bundle that includes the package. This has the same shape as the worm in CISA's alert (stolen credentials, tainted versions, secrets read from the environment), and every control above addresses a piece of it: commit the lockfile and use npm ci, run installs without scripts, hold new versions for a delay, and keep long-lived secrets out of the install step.
Choosing controls
Figure 3. A defence on each side of the build
How to read this: every box is a chance to stop a bad release, and none is sufficient alone. The row on top is about what enters the build; the lower row is about limiting damage if something gets through, which is where staged rollouts (OWASP's advice so a compromised update does not reach everyone at once) and a Content Security Policy come in.
| Control | Stops | Does not stop | Cost |
|---|---|---|---|
Commit the lockfile, npm ci |
Silent version drift, a changed file under a locked version | A malicious version that was locked on purpose | Lock-change reviews |
| No install scripts by default | Install-time code on developer and CI machines | Malicious code that runs when the app runs | Allowlist upkeep for packages that compile |
| Release delay | Fast-moving bad releases | A bad release that stays unnoticed longer than the delay | Slower access to fixes (an override path is needed) |
npm audit |
Versions with published advisories | Fresh malicious releases | Noise: advisories that do not affect the app |
| Provenance and signatures | Files not built where claimed | A compromised build pipeline | Only packages that publish it |
| Dependabot or similar PRs | Falling far behind on fixes | The content of the update | Review time |
| SBOM and inventory | Not knowing where a component is | Anything on its own | Tooling and upkeep |
Figure 4. Should we take this dependency?
small function do it?"} -->|"yes"| Z["Write it; no new dependency"] A -->|"no"| B{"Maintained, widely used,
few transitive packages?"} B -->|"no"| Y["Look for another option
or vendor a reviewed copy"] B -->|"yes"| C{"Install scripts or
git / tarball sources?"} C -->|"yes"| X["Allow by name, with a
reason in the allowlist"] C -->|"no"| W["Add: exact lock entry,
delay on updates"]
How to read this: the cheapest dependency is the one you do not take. The questions run from "do we need it" to "how will it reach our machines", so the review happens before the package is in the tree, not after.
The other side of this topic
On the server side the same supply chain applies to build tools, base container images and the libraries a service uses, with the same ideas of lockfiles, signed artifacts and software bills of materials. What differs is what a bad dependency can reach: a service holds database credentials, while a front-end bundle runs inside a user's browser session. The front-end habit is to treat the bundle as code with the user's privileges on your origin.
Build it
This lesson has no lab. The two scripts above are plain Node with no install and were run to produce the output shown. No package registry was contacted and no real package was inspected. The lockfile in Illustration 2 is constructed; a real lint would also need rules for workspaces, bundled dependencies and registry mirrors.
In practice: hardening the dependency pipeline of the product page
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The shop-web team has about forty direct dependencies and a tree of roughly a thousand packages (illustrative). The security team asks a simple question after reading about the worm that spread through npm: "if a package we use were compromised tonight, would our build or our customers be affected, and would we know?" Nobody can answer. The lockfile is committed but CI runs npm install, several developers run installs with scripts enabled, and nobody has listed which packages need to run code at install time.
Starting architecture
Figure 5. Today: install, resolve, build, ship
How to read this: the two warning boxes are where a bad release would act: in CI, where install scripts see deploy secrets, and in the browser, where there is no policy to limit what a bundled package may do.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
Run npm audit in CI and fail on findings |
Known vulnerabilities | Noise from advisories that do not apply | A false sense of safety against malicious releases |
| Pin everything to exact versions by hand | Range drift | A lot of manual upgrades | Fixes arrive late; the lockfile already does most of this |
npm ci, no install scripts by default, a release delay, reviewed lock diffs, SBOM, staged rollout |
Silent drift, install-time code, fast-moving bad releases, blind spots | Allowlist upkeep and a few days' delay on new versions | Work for the first month; an override path is needed for urgent fixes |
The decision
| Field | Decision record |
|---|---|
| Context | CI resolves versions with scripts enabled and secrets present; nobody reviews lock changes or knows which packages run install code. |
| Decision | Use npm ci in CI and for deploys. Disable install scripts by default and list, with a reason, the few packages allowed to run them. Add a release delay for new versions with a documented override for urgent security fixes. Require a human review of every lockfile diff, with the lint from Illustration 2 as a gate. Keep long-lived secrets out of the install step. Generate an SBOM per release. Start a Content Security Policy in report-only mode. |
| Consequences, good | A version only changes when a person approves a diff; install-time code is a short, named list; the team can answer "where do we use package X". |
| Consequences, bad | Slower access to new versions; the allowlist needs an owner; urgent fixes need a written exception path. |
| Revisit when | The tree grows sharply, a package manager adds a better control, or an incident shows a gap. |
Rollout and verification
- Inventory first. List every package that has an install script or a non-registry source, and decide for each: allow, replace or remove.
- Switch CI to
npm ciwith scripts off on a branch; make the build fail loudly when a dependency needs a script, and fix by allowing it by name. - Turn on the lockfile lint in report mode, read a week of findings, then make it blocking with a documented exception file.
- Practise the bad day. Pretend one package is compromised: use
npm explainto find every path to it, add anoverridesentry, rebuild, and time it. - Check the secrets available to the install step; production deploy credentials should not be among them.
The 2 a.m. failure
An advisory says a package three levels down contains malicious code, and the version range allows the affected release. The alert fires, but nobody can say whether the last build pulled it in, because CI does not record which versions each build used.
First three checks: (1) look at the lockfile and the build's installed versions; (2) use npm explain to find which direct dependency pulls it in; (3) check the build logs and the secrets that were present during install. Mitigation: pin away from the bad version with overrides, rebuild, rotate any secret that the install step could see, and roll back to the last release built before the bad version appeared. Follow-up: store the lockfile and SBOM with every release, so "what did this build contain" is a lookup, not an investigation.
Architect's notes
- Treat install as execution. A package install is "run other people's code with my credentials" unless you turn that off.
- Separate integrity from trust. Hashes, signatures and provenance prove which bytes you have and where they came from, not that they are good.
- Fewer dependencies is a security control. Each one you drop is a supplier you do not have to watch.
- Delay is cheap insurance, and so is an exception path for taking an urgent fix quickly.
- Layer the defences. Build-side and browser-side controls cover different failures.
Common mistakes
- Treating
npm auditas the whole story. It reports known vulnerabilities; a new malicious release is not in it yet. - Running
npm installin CI instead ofnpm ci, or ignoring the lockfile in version control. - Approving lockfile diffs without reading them.
- Leaving install scripts on everywhere and never listing who needs them.
- Assuming provenance means safe.
- Pinning exact versions and never updating. Known vulnerabilities pile up.
- Allowing git or tarball dependencies casually. They may run build scripts.
- No inventory.
Key takeaways
- A front end is mostly third-party code, which runs on developer machines, in CI and in every user's browser.
- A known vulnerability and a malicious release are different problems; audit tools help with the first.
- The lockfile pins the tree and
npm ciinstalls it frozen; neither says the pinned code is safe. - Install scripts run code before the app does; turn them off by default and allow by name.
- A release delay, reviewed lock diffs and staged rollouts reduce the chance that a fresh bad release reaches production.
- Provenance and signatures show origin, not intent. Pair them with inventory, an SBOM and a browser-side policy.
Practice exercises
Exercise 1: Starter (30 min). Pick a project you have. List its direct dependencies, then run npm explain on three packages you do not recognise and write down which direct dependency brought each one in.
Exercise 2: Intermediate (2 hours). Extend the lockfile lint from Illustration 2 to read a real package-lock.json, flag entries that are not from the registry you expect, and read an exceptions file. Run it on a project and review every finding.
Exercise 3: Advanced (half day). Write the one-page response plan for "a transitive dependency was compromised overnight": finding affected builds, rotating secrets, overriding and rebuilding, who decides, and the record afterwards. Drill it with a teammate.
Related reading
In this course:
- Content Security Policy: the browser-side limit on what a bundled package can load or send.
- XSS Defenses: the other way untrusted code reaches your page.
- Monorepos and Shared Libraries: lockfiles and shared packages across a repository.
- Independent Deployment and Shared Dependencies: duplicate versions in a front-end tree.
- Token Storage and Secure Cookies: what a malicious script can read in the browser.
Official documentation
- npm Docs: npm ci and package-lock.json: frozen installs,
resolvedandintegrity. - npm Docs: scripts and package.json: lifecycle scripts, ranges,
overrides, git and tarball dependencies. - npm Docs: npm audit and generating provenance statements: known vulnerabilities, signatures and attestations.
- pnpm: Supply chain security: build-script policy, release age, exotic sources and trust policy.
- OWASP Top 10:2025 A03, Software Supply Chain Failures: scope, prevention and example attacks.
- CISA: Widespread supply chain compromise impacting npm and SLSA v1.0: an incident alert and the producer-side framework.