Building Software
Sections

Contents Section 8, Security

Dependencies and the Supply Chain

Every package you install, and every package it pulls in, is code you run with your own permissions.

Section 8 of 9, subsection 6 of 6. Depth: explain. A 10-minute read.

Mistakes to catch in review

  1. An import of a package that does not exist, or of a lookalike name an attacker registered to catch exactly that mistake.

  2. A large dependency added to replace ten lines of code.

  3. Unpinned versions that pull in a compromised release on the next install.

  4. Install scripts that run arbitrary code on every developer machine and build server.

  5. A dependency scanned once when it was added and never again, so a later advisory for a version you ship goes unnoticed.

  6. A small vendor handed a token for every repository when it needed one, so a breach there reaches all of them.

Other People's Code, Running as You

An agent is adding a feature and needs to turn titles into URL slugs. The diff adds a dependency to package.json and calls it through a new import. After install, the slug feature passes its tests.

In those few seconds your machine downloaded code written by people you have never heard of. Some downloaded code runs during install, and other code runs when your build or app loads it. The agent did not check who those people are. Checking is your job, and most of it takes a few commands.

What installing a package actually does

A package is a folder of code plus a manifest that names the other packages it needs. When you install one, the package manager downloads it, reads its manifest, downloads each package listed there, reads their manifests, and keeps going until nothing new appears. The result is a tree, and the packages you named are only its top row.

Dependency code in the same process generally shares that process's file, environment and network access. It can read environment variables, open files in your home directory, and make network requests, because the language gives it the same powers as your own code. On a developer's laptop that means SSH keys and cloud credentials. On a build server it means deployment secrets.

So adding a package means trusting the people who can publish new versions of it, and of everything under it, today and in every future release you install. Russ Cox's essay "Our Software Dependency Problem" makes this case.

The name might not be real

Language models suggest package names from patterns in their training data, and sometimes the pattern produces a name that was never published. A 2024 study of code-generating models ("We Have a Package for You!", linked from this page) found that about 5 percent of the packages suggested by commercial models and about 22 percent of those suggested by open-source models did not exist. Many of the invented names came back when the same prompt was run again.

Repetition is what makes this exploitable. If a model reliably suggests a missing name, an attacker can register that name with a malicious package and wait for agents to install it. This is sometimes called slopsquatting. It is the machine-generated version of typosquatting, where an attacker registers a name one keystroke away from a popular package. In 2017 a package called crossenv sat on npm next to the real cross-env and sent the environment variables of whoever installed it to its author.

A missing package fails loudly at install time, so the dangerous case is the one where the install succeeds. The question to ask of any new name is whether this is the package you meant, and you answer it from the registry:

Shell
npm view some-package time.created maintainers             # facts about the package
npm view some-package@1.4.2 repository.url scripts         # the exact release you will install

For a Python package, the PyPI project page shows release history, maintainers and repository links. You are looking for agreement between several independent signals. The repository link points to a project you recognize, and that repository's README names the same package. The package's age and download count fit its reputation. A package created two weeks ago, with a name one letter off a library that has millions of weekly downloads, is the pattern to reject on sight.

The tree is larger than the diff

The agent's pull request adds one dependency. The lockfile, package-lock.json, lists every package in the tree, so you can count before and after:

Shell
git show main:package-lock.json | jq '.packages | length'    # 412
jq '.packages | length' package-lock.json                     # 447

For lockfile versions 2 and 3, these commands count package-location entries, and the example shows a net growth of 35. (The count includes one entry for the project itself, which cancels out in the difference.) Review the lockfile diff for every package that was added or changed. Each new package has its own maintainers with publish rights, so the review question has changed from "is this library good?" to "do I trust everyone who can publish these packages, with our credentials?"

That question should be weighed against what the dependency saves. Some packages wrap a single expression. For inputs already validated as safe integers, n % 2 === 0 is enough, while is-even pulls in is-odd and is-number, which also validate their input. Keep any validation your callers rely on. Some replace code the platform now provides: structuredClone has been built into Node.js since version 17 and into all major browsers since 2022, and it handles most deep-copy needs. When an agent pulls in a large library for one function, ask how long the function would be if you wrote it. If the answer is ten lines you can read in a minute, write the ten lines.

On the left, a package.json box marked one new line points to a highlighted box, new dependency, the one you named. It fans out to three packages, each marked own maintainers, and those fan out to five more packages. A note under package.json reads one line in the diff; a note under the tree reads net +35 lockfile entries. The tree is a simplified sketch; it does not draw all 35 entries.
The diff adds one line to package.json, but each package under the new dependency has its own maintainers who can publish. The tree is simplified; in the lesson's example the lockfile grows by a net 35 entries.

To see the whole tree for a project, not just the change, use the package manager's own listing: npm ls --all for Node, uv tree or pipdeptree for Python, go list -m all for Go, cargo tree for Rust. For a release inventory, generate a software bill of materials (SBOM) for the actual artifact, in a standard format such as CycloneDX or SPDX, and record its scope: runtime packages, system libraries and downloaded binaries. Its value shows up on the day an advisory names a vulnerable version, because you can search one file per release instead of rebuilding the tree from memory.

Why transitive packages need the same scrutiny

Two well-documented attacks reached their victims through packages the victims never chose directly.

In 2018 the maintainer of event-stream, a popular npm package, handed publishing rights to a volunteer who offered to help. The new maintainer added a dependency called flatmap-stream, and a later release of that dependency carried an encrypted payload that activated only inside the build of one Bitcoin wallet app and tried to steal wallet keys. Projects using event-stream did not change a line of their own code. They picked up the payload through a package two levels down.

In 2024, a contributor who had spent about two years building trust as a co-maintainer of xz, a compression library, shipped a backdoor in releases 5.6.0 and 5.6.1. The payload was hidden in binary test files, and the script that unpacked it into the build existed only in the release tarballs, absent from the source repository. On some Linux distributions, the OpenSSH server loads liblzma indirectly through another library, and that indirect path was the target. Andres Freund, a developer at Microsoft, found it because SSH logins on his test machine had become about half a second slower. Russ Cox's "Timeline of the xz open source attack" reconstructs the whole sequence.

Two lanes. The 2018 lane: a project, with no code changed, depends on event-stream, which depends on flatmap-stream, highlighted and marked encrypted payload. The 2024 lane: the OpenSSH server loads another library, which loads liblzma, highlighted and marked xz 5.6.0 and 5.6.1. Below liblzma, a release tarball box, marked unpack script, not in repo, points up into it with the words into the build. A note under flatmap-stream reads two levels down; a note at the bottom left reads never named, same access.
In both attacks the payload sat in a package the victim never named: flatmap-stream under event-stream in 2018, and liblzma reached through another library in 2024, built by a script found only in the release tarball.

A dependency you never named has the same access as one you did. The checks you apply to a direct dependency apply to everything it brings in, and the tree listing is where you find them.

Pinning, and what a lockfile guarantees

A manifest usually names a range of versions. In npm, "^1.4.2" means any version from 1.4.2 up to, but excluding, 2.0.0. That range is resolved at install time, so a release published tonight can land on your build server tomorrow with no change on your side.

A box labelled ^1.4.2 range holds 1.4.2, included, and an arrow labelled newer to a highlighted new release published tonight. A dashed arrow leads on, out of the box, to 2.0.0, excluded. An arrow runs from the new release down to a build server box marked tomorrow's install. A note reads no change on your side.
^1.4.2 admits every version from 1.4.2 up to, but excluding, 2.0.0, so a release published tonight falls inside the range and the next install picks it up.

This happened with ua-parser-js in October 2021. An attacker took over the maintainer's npm account and published versions 0.7.29, 0.8.0 and 1.0.0 containing a cryptocurrency miner and a password stealer. Projects that resolved their version range during that window, with no lockfile holding them to an older version, installed one of them.

Lockfiles record resolved versions and, for registry artifacts, usually integrity hashes. Installing from one with npm ci, uv sync --locked, or pip install --require-hashes -r requirements.txt fails if a downloaded file does not match its recorded hash. The installed set can still vary with platform and options, and local dependencies and files fetched by install scripts need separate controls. Go selects versions from go.mod requirements, while go.sum records checksums and the checksum database helps detect changed contents, so commit both. Updates then become a deliberate change you review in a pull request.

This sketch runs both kinds of install against a registry that gains a malicious release overnight. The digest stands in for the integrity field npm writes into package-lock.json.

TypeScriptRuns in your browser
// The registry: each published version of one package and the contents of its tarball.
const registry = new Map<string, string>([
  ["1.4.2", "export default slugify;"],
  ["1.5.0", "export default fasterSlugify;"],
  ["2.0.0", "export { slugify };"],
]);

// "^1.4.2" accepts 1.4.2 and anything newer below 2.0.0 (prereleases left out).
function resolveCaret(base: string): string {
  const [major, minor, patch] = base.split(".").map(Number);
  const matches = [...registry.keys()].filter((v) => {
    const [a, b, c] = v.split(".").map(Number);
    return a === major && (b > minor || (b === minor && c >= patch));
  });
  return matches.sort((x, y) => x.localeCompare(y, "en", { numeric: true })).at(-1)!;
}

// npm records a SHA-512 digest; SHA-256 shows the same idea. Shortened for display.
async function digest(text: string): Promise<string> {
  const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
  return [...new Uint8Array(bytes)].slice(0, 6).map((b) => b.toString(16).padStart(2, "0")).join("");
}

// Monday: the lockfile records the version the range resolved to, and its digest.
const mondayVersion = resolveCaret("1.4.2");
const lock = { version: mondayVersion, integrity: await digest(registry.get(mondayVersion)!) };
console.log("Monday, range install:", mondayVersion);

// Overnight, someone with a stolen maintainer token publishes a new release.
registry.set("1.5.1", "export default fasterSlugify; uploadCredentials();");
console.log("Tuesday, range install:", resolveCaret("1.4.2"));

async function installLocked(tarball: string): Promise<string> {
  const actual = await digest(tarball);
  return actual === lock.integrity ? `installed ${lock.version}` : `refused, digest ${actual} is not ${lock.integrity}`;
}
console.log("Tuesday, locked install:", await installLocked(registry.get(lock.version)!));
// The same version, altered on a mirror or in transit.
console.log("Altered download:", await installLocked(registry.get(lock.version)! + " uploadCredentials();"));

// A lockfile first written on Tuesday records whatever the range resolves to that day.
const tuesdayVersion = resolveCaret("1.4.2");
console.log("Lockfile written Tuesday pins:", tuesdayVersion);

The range install picked up the overnight release. The locked install kept Monday's version and refused a download whose contents had changed.

  • A lockfile freezes whatever it recorded, as the last line of the sketch shows. If a compromised version was already resolved when the lockfile was written, the lockfile keeps installing it faithfully.
  • It says nothing about whether a version is safe. Scanners such as npm audit and osv-scanner check against published advisories in databases like OSV and the GitHub Advisory Database. A clean result leaves unknown vulnerabilities and unreported malicious code undetected.
  • It only works where installs use it. Without a compatible lockfile, npm resolves the range at install time and may pick a newly published release. npm install honors compatible locked versions but can update the lockfile, so use npm ci in CI, where a mismatch fails the build. A step that deletes the lockfile to fix a conflict leaves you with no lockfile at all.
  • It does not stop code from running during installation.

Scanning again

A scan compares your tree with the advisories that exist on the day it runs. New advisories keep arriving for versions you already ship, and attackers can use AI to rewrite a malicious package until the malware scanners in use stop flagging it. A package that scanned clean when it was added is clean as of that date. Run the scan on a schedule against the lockfile on your main branch and each release's SBOM, and give every new finding for a shipped version an owner and a date.

Install scripts

Before npm 12, npm ran a dependency's preinstall, install and postinstall scripts automatically, as the user running the install. That is still the behavior wherever an older npm is installed, which includes many CI images. npm 12, published in July 2026, blocks dependency install scripts by default: install commands skip lifecycle scripts for any dependency without a matching entry in the allowScripts field of package.json, and npm approve-scripts some-package maintains that field. Either way, a script that is enabled or approved runs with the installer's permissions before the application imports the package, on every developer machine and build server that installs the project.

Two lanes. Top lane, before npm 12: an install pill points straight to a highlighted box, script runs, as the installer, along an arrow labelled runs directly. Bottom lane, npm 12: an install pill points to a decision diamond asking whether the script is listed in allowScripts. Yes leads to a second highlighted box, script runs, as the installer; no leads down to a box, skipped, no matching entry. A note between the two script boxes reads before any import.
Before npm 12 an install runs dependency scripts directly; npm 12 runs only those listed in allowScripts and skips the rest. Either way, a script that runs does so as the installer, before the app imports the package.

Most packages with install scripts use them for ordinary reasons, like compiling a native module or downloading a prebuilt binary for your platform. The trouble is that the mechanism cannot distinguish those from a script that uploads ~/.aws/credentials. When npm view some-package@1.4.2 scripts shows an install hook for the exact version you will install, read it, along with the files the hook runs. If it downloads something, find out from where, and whether the download is checked against a hash published somewhere other than the download server.

pnpm (10 and later) and Bun require approval for dependency scripts, and Bun's default list includes some trusted packages, so check the effective approvals in your project. On older npm, set ignore-scripts=true in .npmrc, and after review run npm rebuild some-package --ignore-scripts=false for the packages that need their scripts. With npm 12, use allowScripts instead, since ignore-scripts=true still suppresses the hooks of approved packages. Python has the same issue in a different form: installing from a source distribution runs its build code, while installing a prebuilt wheel only unpacks files, so pip install --only-binary :all: refuses the source path. Go does not run code from dependencies at install time at all.

Vendors that hold many customers' keys

Services raise the same trust question. A CI add-on, a secrets-sync tool or a code-quality bot that holds tokens for your repositories holds them for its other customers too, so one breach there reaches all of them at once. A small vendor in that position is a valuable target and often a thinly defended one. For each vendor that holds a credential of yours, ask what an attacker gets the day that vendor is breached. Scope each credential to what the vendor does, move what you can to platforms you already depend on, and remove integrations nobody uses.

Evaluating a dependency before you add it

Record the registry or repository evidence behind each review decision:

  • Is the name the one you meant? Check the repository link, the reverse link from the repository, the package age and the download count.
  • Who can publish it, and did that change recently? A new maintainer on an old, popular package is how event-stream was compromised.
  • Is it maintained? Look at the dates of recent releases and whether security issues get answered.
  • What is its security history? Search OSV for past advisories and see how quickly they were fixed.
  • What does it bring in and what does it run at install? Count the tree change and read any install scripts.
  • Where it is available, does the published package carry provenance? npm audit signatures checks registry signatures and provenance attestations, which link a published package to the source commit and build that produced it. The SLSA specification defines what those attestations can prove.

Return an unresolved risk to the agent with the evidence, and ask for an alternative. Judge release frequency against the package's maturity, and past vulnerabilities against how they were handled.

Add a dependency only when writing and maintaining the code yourself would cost more than trusting every account that can publish the package or anything under it.

Check your understanding

8 questions on this lesson. Pick an answer to see whether it holds and why.

  1. 1An agent's pull request adds this dependency, and the repository has no lockfile. The registry has 2.3.1, 2.4.0 and 3.0.0. Tonight someone with a stolen maintainer token publishes 2.4.1 and points the latest tag at it. Tomorrow CI runs a fresh npm install on a clean runner. Which version does it install?
    JSON
    {
      "dependencies": {
        "date-tidy": "^2.3.1"
      }
    }
    Show the answer

    Answer C. A caret range accepts any version from 2.3.1 up to but excluding 3.0.0. With no lockfile the range is resolved again on every install. npm takes the version the latest tag points to when it falls inside the range, and otherwise the highest version that does, and here both rules give 2.4.1. The number written in the manifest is only the floor of the range, which is why reading ^2.3.1 as a pin is the common mistake.

  2. 2An agent added these steps to the CI script to get past a lockfile merge conflict. Each CI run starts from a fresh checkout with no node_modules, no npm-shrinkwrap.json and no other lockfile. What did the build lose?
    Shell
    rm package-lock.json
    npm install
    npm test
    Show the answer

    Answer B. package.json holds ranges, so it cannot rebuild yesterday's tree. On a clean runner with no lockfile of any kind, npm resolves each range against the registry as it is today, so any matching release published since can come in, and it writes a new lockfile from what it finds. The fix is to resolve the conflict inside the lockfile and keep installing with npm ci, which fails the build on a mismatch.

  3. 3Your project commits a lockfile with integrity hashes, and CI installs with npm ci. Which of these can still be installed in CI?
    Show the answer

    Answer D. The lockfile keeps installing whatever it recorded, and the hash was taken from the compromised contents, so every check passes. New releases are not installed, direct or transitive, because npm ci uses the recorded versions. The altered tarball is the one people expect to slip through, but its hash no longer matches and the install fails.

  4. 4npm audit reports 0 vulnerabilities for a project with 600 packages in its lockfile. What has that result established?
    Show the answer

    Answer A. A scanner compares installed versions against advisories that have already been reported and published. Malicious code nobody has reported, and flaws nobody has found, also produce a clean result. It does check transitive packages as well. What it cannot see is anything nobody has reported yet.

  5. 5An agent added a dependency for this one call. order holds strings, numbers, an items array and a placedAt field that is a Date. Which replacement keeps the behavior without the dependency?
    TypeScript
    import cloneDeep from "deep-clone-plus"; // 31 packages in its tree
    
    const draft = cloneDeep(order);
    draft.items.push(extraItem);
    Show the answer

    Answer C. structuredClone is built into Node.js 17 and later and into current browsers. It copies nested arrays and keeps a Date as a Date. The JSON round trip is the tempting choice, but it turns placedAt into a string. The other two copy only the top level, so pushing onto draft.items would also change order.items.

  6. 6Your package.json has an allowScripts entry, which npm 12 reads, approving install scripts for one package. The CI image still ships npm 10. What happens when CI installs?
    Show the answer

    Answer A. npm 10 does not read allowScripts, and it runs every dependency's preinstall, install and postinstall scripts by default. npm 11.16 honors explicit denials in the field but still runs unreviewed scripts, and npm 12 blocks any script not approved. The protection exists only where an npm that enforces the field is the one running. Pin the CI image to npm 12, or set ignore-scripts=true there and rebuild the reviewed packages explicitly.

  7. 7An agent imports a package, and the install fails with a 404 because no package by that name exists. A teammate says the mistake was harmless since nothing was installed. What risk remains?
    Show the answer

    Answer B. Research on package hallucination found that invented names come back again and again across prompts, which is what makes registering them worth an attacker's time. A 404 today means only that nothing is published under that name yet. Often nothing stops someone from publishing it tomorrow, and then the same import installs their code.

  8. 8A code-quality bot from a five-person startup asks for an organization-wide token with write access to every repository, so it can post review comments. You use it on three repositories. What do you do?
    Show the answer

    Answer B. A vendor that holds write tokens for many customers is one breach away from all of them, which makes a small one a valuable and thinly defended target. Scoping the grant to what the bot does limits what that breach reaches. Rotation shortens how long a stolen token works but leaves its reach across every repository, and a questionnaire from last year says little about today.

You understand it when you can

Drill

An agent's pull request adds three packages: one whose name is a single letter off a popular library, one that brings in 140 transitive dependencies to pad a string, and one with an install script that downloads a binary. Decide which to reject, and show how you would confirm that each package is the one you think it is.

Topics

Choosing Dependencies
Checking maintenance, ownership, license and size before adding a package, and preferring fewer packages overall.
Pinning and Lockfiles
Making installs reproducible and updates deliberate.
Vulnerability Scanning and Patching
Finding known vulnerabilities in dependencies, scanning again on a schedule because advisories keep arriving and attackers keep rewriting, and patching steadily.
Hallucinated and Typosquatted Packages
Package names that models invent and attackers register, and how to verify a package is the real one.
Provenance and SBOMs
Build attestations, signatures and software bills of materials that show what went into a release.
Vendors Holding Many Customers' Keys
Small vendors that hold credentials for many customers, what a breach there reaches, and scoping or moving what they hold.

Further reading

Start here

Short reads

Watch

Books

  • Software Supply Chain Security: Securing the End-to-End Supply Chain for Software, Firmware, and Hardware. Cassie Crossley, 2024.

    Identifies the risks and controls at each link of the chain, from secure development to third-party risk and software transparency.

  • Software Transparency: Supply Chain Security in an Era of a Software-Driven Society. Chris Hughes and Tony Turner, 2023.

    Explains SBOMs, attestations and provenance: what they record, how producers and consumers use them, and how they show what went into a release.

  • Software Engineering at Google: Lessons Learned from Programming Over Time. Titus Winters, Tom Manshreck and Hyrum Wright, 2020. Free to read online.

    Its dependency-management chapter explains why every added dependency is a long-term cost and why version resolution is hard, which is the case for adding fewer packages.

Primary sources