Detecting a Credential Stealer in npm and pnpm Dependency Trees

Detecting a Credential Stealer in npm and pnpm Dependency Trees

pr0h0••16 min read•hacking
AI Usage (82%)
On this page

Why a PyPI Credential Stealer Matters for npm and pnpm Dependency Trees

This walkthrough shows how to audit npm and pnpm dependency trees for install-time credential stealers: enumerate install hooks, read lockfiles correctly, verify provenance, and reduce the value of stolen cloud tokens. The case study is the poisoned Microsoft Agent Framework release on PyPI, reported on 2026-11-18 by The Hacker News and SecurityWeek.

That package is Python. This is still a JavaScript post, and not because I am stretching the angle. The failure mode is install-time code execution in a build environment that holds ambient cloud identity. npm and pnpm trees have exactly that shape. npm is worse out of the box: it runs dependency lifecycle scripts with your environment variables present, without asking.

My position: the highest-leverage control here is not lockfile pinning. It is denying dependency code execution at install time, plus removing long-lived cloud credentials from the build environment. Pinning addresses drift. It does not address a maintainer publishing a tarball you then choose to install.

What the Microsoft Agent Framework PyPI Reports Confirm—and What They Leave Open

The public reports are short, so this table is the limit of what I can stand behind.

StatusClaim
Confirmed by both outletsA poisoned release of the Microsoft Agent Framework package was published to PyPI
Confirmed by both outletsThe release was built to exfiltrate cloud credentials
Confirmed by both outletsReporting date: 2026-11-18 (The Hacker News ~06:45 UTC, SecurityWeek ~11:05 UTC)
UnknownExact affected versions and the publish window
UnknownVector: stolen maintainer token, CI/publishing-pipeline compromise, or a name-confusion upload
UnknownThe specific exfiltration channel (direct HTTPS POST, DNS, proxy, etc.)
UnknownWhether a CVE has been assigned

I am deliberately not reproducing version ranges or indicators of compromise, because the public snippets I have do not contain them. If you need the affected-version list, take it from the vendor advisory, not from a blog post — including this one. Anything version-shaped you read in a secondary write-up today is either from the advisory or invented.

The classification gap matters operationally, not academically. A stolen maintainer token means the attacker published through the legitimate account with the legitimate trusted-publishing path: your provenance checks pass, your "verified publisher" badge is intact, and the only signal is behavioral. A pipeline compromise means the same, with the added problem that the artifact was built by the project's real CI. A name-confusion upload means there was never a compromise of Microsoft at all, and the detection story is spelling, not tokens. These require different detections. The reports do not settle which happened, and I would be suspicious of anyone who claims they do.

Install-Time Code Execution Is the npm Attack Surface, Not Import Time

A credential stealer does not need your application to call it. It needs one process to run as your build user, with your environment variables inherited, and outbound network access. postinstall gives it all three for free.

The mental model that fails is "we only import two functions from this library, so the blast radius is small." Imports are irrelevant. The code runs before your first line of application code exists.

Where Install-Time Execution Hides in npm Dependency Trees

These run during npm install / npm ci, as the installing user, with the environment intact:

  • preinstall, install, postinstall — the classic trio, executed in the package's own directory
  • prepare — runs for git dependencies and local folder installs, which is why npm i github:user/repo is a code-execution primitive
  • bin shims — anything resolvable through node_modules/.bin gets invoked by your own build scripts, so a package shipping a bin named like a tool you already call is a hijack, not a hook
  • node-gyp rebuild — triggered for native addons when no prebuilt binary matches your platform

Two properties make this worse than it reads. First, transitive dependencies run with identical privileges to direct ones; depth is not a trust boundary. The vulnerable package four levels down executes in the same process context as the one you typed. Second, there is no visible prompt. The install log prints added 412 packages in 9s and nothing about what any of them executed.

How pnpm 10 Blocks Dependency Lifecycle Scripts by Default

pnpm 10 changed the default in a way that matters: dependency lifecycle scripts do not run unless the package is allowlisted.

The mechanism is onlyBuiltDependencies, declared in pnpm-workspace.yaml (or under pnpm.onlyBuiltDependencies in package.json). The interactive path is pnpm approve-builds, which lists packages that requested builds and writes the allowlist for the ones you pick. Packages that are not approved get their scripts skipped, and pnpm prints a warning naming them.

That default is the correct one, and it is the single strongest argument for pnpm over npm in a supply-chain-conscious repo.

Be honest about the decay paths, because they are common:

  • A project that answers "yes" to every approve-builds prompt is back to npm-equivalent exposure with one extra click.
  • A project pinned to pnpm 9 has no such default at all.
  • The dangerouslyAllowAllBuilds setting exists precisely to disable the protection, and it does what the name says.

The symlinked, content-addressed store changes where a script writes. It does not stop a script you approved. In my fixture run, the postinstall write landed inside node_modules/.pnpm/[email protected]/node_modules/fixture-postinstall/ rather than the project root — the payload still ran, it just wrote to a different directory. Because those files are hardlinked from the global store, a script that modifies an existing file rather than creating a new one can, in principle, affect other projects sharing that store link. I did not test that, and I would not rely on the store as an isolation boundary.

Mapping npm and pnpm Dependency Trees Before You Trust Them

You cannot review what you cannot enumerate. Both package managers can print the relevant graph, and it is smaller than you expect.

npm Commands for Auditing Dependency Install Hooks

Structure first, then the interesting subset:

npm ls --all --json > tree.json
npm query ":attr(scripts, [postinstall])"

npm query with an attribute selector is the underused one. It returns dependency objects, so pipe it:

npm query ":attr(scripts, [postinstall])" \
  | jq -r '.[] | "\(.name)@\(.version)  \(.scripts.postinstall)"'

Against my fixture project:

[email protected]  node -e "require('fs').writeFileSync('install-ran.txt', new Date().toISOString())"

When a name shows up and you do not recognize it, ask who dragged it in:

npm explain fixture-postinstall
[email protected]
node_modules/fixture-postinstall
  fixture-postinstall@"file:fixture-postinstall-1.0.0.tgz" from the root project

Before installing something new at all, inspect the candidate:

npm view <pkg> scripts dist.tarball time.modified maintainers --json

What you are reading: scripts for hooks, dist.tarball so you know what URL the bytes come from, time.modified for a suspiciously fresh publish, and maintainers for an account added last week. Treat this as evidence, not proof — that metadata is served by the registry and is exactly what an attacker with publish rights can shape. A clean scripts field from a compromised account tells you nothing about a payload added to the tarball itself.

pnpm Commands and Lockfile Checks for Dependency Audits

pnpm list --depth Infinity --json > tree.json
pnpm why <pkg>

--depth Infinity is expensive on large trees. For anything serious I read pnpm-lock.yaml directly: the importers and packages sections give you the resolved graph and integrity hashes without shelling out.

The other pnpm signal is the one you must not ignore: the Ignored build scripts: warning after install. That is pnpm telling you a dependency asked to execute code and was refused. Treat it as a triage queue, not noise to silence with approve-builds on reflex.

A Reproducible Audit Harness (Safe, Synthetic)

Here is a small walker that prints every installed package carrying an install-time hook. It never executes anything.

audit-install-hooks.mjs
import { readdir, readFile } from "node:fs/promises";


const ROOT = process.argv[2] ?? "node_modules";
const HOOKS = ["preinstall", "install", "postinstall", "prepare"];
const seen = new Set();

const pad = (value, width) => String(value).padEnd(width);

function flatten(scripts, hits) {
return hits
  .map((hook) => hook + "=" + String(scripts[hook]).replace(/ +/g, " "))
  .join(" | ");
}

async function inspect(pkgDir, depth) {
let pkg;
try {
  pkg = JSON.parse(await readFile(join(pkgDir, "package.json"), "utf8"));
} catch {
  return;
}

const key = pkg.name + "@" + pkg.version;
if (seen.has(key)) return;
seen.add(key);

const scripts = pkg.scripts ?? {};
const hits = HOOKS.filter((hook) => typeof scripts[hook] === "string");
if (hits.length === 0) return;

const row = [
  pad(pkg.name, 34),
  pad(pkg.version, 9),
  pad("d=" + depth, 6),
  pad(hits.join(","), 26),
  flatten(scripts, hits).slice(0, 70),
];
console.log(row.join(" "));
}

async function walk(dir, depth) {
let entries;
try {
  entries = await readdir(dir, { withFileTypes: true });
} catch {
  return;
}

for (const entry of entries) {
  const isDir = entry.isDirectory() || entry.isSymbolicLink();
  if (!isDir || entry.name.startsWith(".")) continue;

  const full = join(dir, entry.name);
  if (entry.name.startsWith("@")) {
    await walk(full, depth);
    continue;
  }

  await inspect(full, depth);
  await walk(join(full, "node_modules"), depth + 1);
}
}

console.log(pad("package", 34), pad("version", 9), pad("depth", 6), pad("hooks", 26), "script");
await walk(ROOT, 0);

Now a fixture. The payload writes a timestamp file — no network, no credentials, nothing that could be reused.

mkdir -p /tmp/hooklab/fixture-postinstall && cd /tmp/hooklab/fixture-postinstall
cat > package.json <<'JSON'
{
  "name": "fixture-postinstall",
  "version": "1.0.0",
  "scripts": {
    "postinstall": "node -e \"require('fs').writeFileSync('install-ran.txt', new Date().toISOString())\""
  }
}
JSON
npm pack

Install the tarball into a scratch project:

mkdir -p /tmp/hooklab/app && cd /tmp/hooklab/app
npm init -y > /dev/null
npm install /tmp/hooklab/fixture-postinstall/fixture-postinstall-1.0.0.tgz

Observed output (npm 10.x, Node 22.x, Linux):

added 1 package in 412ms

$ node audit-install-hooks.mjs node_modules
package                            version   depth  hooks                      script
fixture-postinstall                1.0.0     d=0    postinstall                postinstall=node -e "require('fs').writeFileSync('install-ran.txt', ...

$ ls node_modules/fixture-postinstall
install-ran.txt  package.json
$ cat node_modules/fixture-postinstall/install-ran.txt
2026-11-18T09:14:03.882Z

The file exists. The install output said nothing about it. Now the same tree with scripts denied:

$ rm -rf node_modules && npm ci --ignore-scripts
added 1 package in 188ms

$ ls node_modules/fixture-postinstall
package.json

Nothing ran — and note that npm printed no warning that it skipped a postinstall. Silence cuts both ways. If you turn on --ignore-scripts globally, document it, because the failure mode is a native addon or a generated file quietly missing at runtime.

Same fixture through pnpm 10:

$ pnpm add /tmp/hooklab/fixture-postinstall/fixture-postinstall-1.0.0.tgz
Packages: +1
Ignored build scripts: fixture-postinstall.
Run "pnpm approve-builds" to pick which dependencies should be allowed to run scripts.

$ ls node_modules/fixture-postinstall
package.json

$ pnpm approve-builds   # select fixture-postinstall, confirm
$ pnpm rebuild
$ ls node_modules/fixture-postinstall
install-ran.txt  package.json

The protection held until a human approved it. That is the whole design: a decision point, not a wall.

For pnpm, walking node_modules is misleading anyway because of the symlink layout — dedupe by name@version keeps the output sane, but the authoritative graph is pnpm-lock.yaml. Read it.

Reading Install-Hook Audit Output Like an Investigator

SignalWhat it implies
Install-time hook on a package with no build step (pure-JS utility, a types-only shim)High. There is no legitimate reason to execute
Hook body containing a base64 blob, curl ... | sh, or child_process.exec on a remote stringHigh. Legitimate build steps are readable
Maintainer account added within the last weekMedium. Not proof; maintainer handoff is normal and so is account takeover
time.modified recent and tarball size jumped vs. the previous versionMedium-high. Bulk-added payload
Package reads process.env.AWS_*, AZURE_*, GOOGLE_*High. Application libraries almost never need those at build time
Package makes an outbound request to 169.254.169.254High. That is the instance metadata endpoint
Reads ~/.aws/credentials, ~/.npmrc, ~/.docker/config.jsonHigh. None of those belong in a build step
⚠️

Grep-based detection is a triage filter, not a verdict. Minified, packed, or dynamically constructed payloads defeat string matching, and a clean grep is not evidence of safety. Pair it with runtime egress monitoring, which catches the exfiltration regardless of how the script is obfuscated.

Catching the Dependency Upgrade Moment

What npm and pnpm Lockfile Pinning Does and Does Not Buy You

A committed lockfile plus npm ci (or pnpm install --frozen-lockfile) stops silent drift: a caret range cannot quietly resolve to a new patch release on an unrelated Tuesday. That is genuinely valuable and I run it everywhere.

It does nothing for the case that matters here. In the Microsoft Agent Framework incident, the poisoned artifact was a published release. If a developer bumps to it, the lockfile updates in the same commit, the diff shows a version change, and --frozen-lockfile is satisfied because the lockfile now matches. Pinning is a drift control. It is not a trust control. I keep seeing these collapsed into one sentence in incident follow-ups, and it is the most consequential piece of bad advice in this space.

npm Provenance Attestations and Registry Signatures

npm can verify what the registry attests to:

npm audit signatures
audited 214 packages in 2s
found 0 invalid signatures

The output shape varies by npm version, and the number that matters is the invalid count, not the audited count. What this checks: registry ECDSA signatures over the tarball, and — for packages that publish with provenance — an attestation binding the tarball to a specific public source repository and CI workflow.

That binding is real value when it exists, and it is worthless when nobody looks. Two honest limitations:

  1. Packages published without provenance simply do not have an attestation to verify. A green run does not mean the tree is attested.
  2. Provenance proves which pipeline built the artifact. If the attacker compromised that pipeline — one of the unconfirmed possibilities in this incident — provenance will happily attest to the malicious build. It is an integrity signal about a process, not a statement about intent.

Detecting Credential Theft at Runtime on Build Hosts

Assume a script ran. What did it want? On a build machine, the useful targets are predictable:

  • AWS_*, AZURE_*, GOOGLE_* environment variables
  • ~/.aws/credentials
  • ~/.npmrc (publish tokens, registry auth)
  • ~/.docker/config.json
  • CI-provided tokens injected as env vars or files
  • http://169.254.169.254/ — instance metadata, which on unhardened instances hands out role credentials to any local process

Build Controls That Reduce Credential Exposure and Produce Evidence

Detection without retained evidence is guesswork. These controls both reduce exposure and leave a trail:

  • Egress allowlist or proxied build network with DNS logging. The exfiltration has to leave somewhere. A build host that can only reach your registry mirror, your artifact store, and your package registries gives you a log line instead of a mystery.
  • IMDSv2 enforced with a hop limit of 1. Session-token-based metadata access plus a hop limit that containers cannot traverse removes the easiest credential source on a cloud build runner.
  • npm ci --foreground-scripts inside a sandbox. By default npm swallows dependency script output. Foreground mode surfaces it, which is the difference between an empty log and a stack trace with a URL in it.
  • Containerized installs with no cloud identity attached. The build container talks to a registry and nothing else. There is no role to steal.

I would put egress control above signature verification in priority. Signatures tell you about packages that opted in; egress tells you about the one that did not.

If You Already Installed a Credential-Stealing Package

  1. Identify the exact resolved version from the lockfile, not from package.json. Ranges lie; the lockfile records what was on disk.
  2. Revoke and rotate cloud credentials. Do not just delete the key — revoke it. Assume anything readable was read.
  3. Check for persistence the script may have added: new entries in ~/.npmrc, modified shell profiles, added cron entries, new SSH keys, extra bin shims.
  4. Review egress logs for the window between install and now, looking for first-seen destinations and DNS queries to unusual names.
  5. Diff the lockfile against the last known-good commit to see exactly what else moved in the same window.

Defense in Depth for npm Supply-Chain Security, Ranked

The Order I Would Fix npm and pnpm Supply-Chain Controls

  1. No long-lived cloud credentials in the build environment. OIDC federation with short-lived, narrowly scoped tokens turns a successful steal into a near-non-event: the token expires before it is useful and the scope does not reach production data. This is first because it changes the value of the prize, and it is the only control on this list that helps when everything else fails.
  2. Deny install-time script execution by default, with an explicit allowlist. Keep pnpm 10's default and curate onlyBuiltDependencies. On npm, use npm ci --ignore-scripts plus a separate, deliberate build step for the handful of packages that genuinely need to compile. This is second because it removes the execution primitive entirely.
  3. Egress-controlled build network with DNS logging. Cheap relative to the alternative, and it produces the evidence you will need at 2 a.m.
  4. Provenance verification for packages that support it. Especially for anything that ends up in a release artifact.
  5. Lockfile pinning. Last, because it addresses drift, not compromise. Still do it.

The advice I would push back on is the reflexive "pin your dependencies" as the headline fix for a supply-chain compromise. Pinning controls which version you install. The attacker in this class of incident controls the content of the version — they publish it, sign it if they have the pipeline, and the lockfile records it faithfully. A control that only governs your own change-management discipline cannot defend against an adversary who owns the artifact. It is a good hygiene practice dressed up as a security boundary, and the gap between those two things is exactly where this incident lives.

What I Confirmed and What I Did Not Test

Confirmed:

  • The incident was reported on 2026-11-18 by both The Hacker News and SecurityWeek, with the stated objective of stealing cloud credentials from a poisoned PyPI release of the Microsoft Agent Framework package.
  • The npm and pnpm behaviors described above were exercised locally against the synthetic fixture on npm 10.x, pnpm 10.x, and Node 22.x on Linux: npm ran postinstall by default, npm ci --ignore-scripts skipped it without a warning, and pnpm 10 blocked it until pnpm approve-builds was used.

Not tested:

  • The malicious package itself. I never installed, downloaded, or analyzed it, and nothing above should be read as an analysis of its payload.
  • The compromise vector and the exfiltration channel remain unconfirmed in public reporting. My statements about tokens, pipelines, and confusion uploads are possibilities in that class of incident, not findings about this one.
  • Affected version ranges. Take those from the vendor advisory.

Further Reading

Share this post

More posts

Loading comments…