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:
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 installFor 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:
git show main:package-lock.json | jq '.packages | length' # 412
jq '.packages | length' package-lock.json # 447For 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.

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.

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.

^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.
// 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);Output
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 auditandosv-scannercheck 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 installhonors compatible locked versions but can update the lockfile, so usenpm ciin 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.

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-streamwas 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 signatureschecks 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.