You install a package. The terminal prints a few warnings, updates your lockfile, and returns control.

Everything looks normal.

Meanwhile, that dependency could have read your environment variables, GitHub credentials, or cloud infrastructure tokens. You haven’t even imported it into your application yet.

Installing a dependency is not always a passive operation. Package managers can execute code during installation, with the same permissions as the developer running the command.

This makes npm and PyPI particularly attractive targets for software supply chain attacks.

In this article, we’ll look at how these attacks work, what makes a dependency suspicious, and how to protect your machine and your CI.

1. The Scale of the Problem

Between May 2025 and June 2026, Solar Security analyzed packages from npm and PyPI using its own monitoring infrastructure.

The distribution of detected malicious packages was heavily skewed toward npm:

EcosystemShare of detected malicious packages
npm86%
PyPI14%

These numbers describe the researchers’ sample. They don’t prove that npm is inherently less secure than PyPI: npm is simply much larger and more attractive to attackers targeting web developers.

What matters more is the behavior behind those packages. Across both ecosystems, execution at install time was one of the most common techniques.

2. Your Dependency Can Run Before You Import It

Most JavaScript developers type this dozens of times a week:

bash
npm install some-package

What’s less obvious is that npm executes lifecycle scripts defined by every dependency in the tree, not just the one you asked for.

Consider this perfectly legitimate package.json:

json
{
  "name": "example-library",
  "version": "1.0.0",
  "scripts": {
    "preinstall": "node scripts/check.js",
    "postinstall": "node scripts/setup.js"
  }
}

These hooks have valid uses. Libraries use them to download native binaries, verify platform compatibility, or compile code.

The security problem is that these scripts execute code supplied by someone else, on your machine, before you’ve looked at a single line of it.

Here is a harmless demonstration.

scripts/setup.js

js
console.log('Installation script executed');
console.log('Node.js version:', process.version);
console.log('Platform:', process.platform);
console.log('Home directory:', process.env.HOME ?? process.env.USERPROFILE);

No import is required. The package manager itself runs the script. And the last line shows the real point: an install script has the same access to your environment and file system as you do.

text
npm install some-package
        │
        ├─ resolve dependency tree
        ├─ download & extract tarballs
        ├─ preinstall   ← third-party code runs
        ├─ install      ← third-party code runs
        ├─ postinstall  ← third-party code runs
        └─ update package-lock.json
                                   (you haven't imported anything yet)

Python has a similar attack surface. Installing from a source distribution runs the package’s build backend, which can execute arbitrary code, including the classic setup.py.

Installing a prebuilt wheel skips that build step, although it doesn’t make the package itself safe: the malicious code can simply wait until you import it.

The key takeaway: installing software and running software are not separate security events.

3. What Makes a Developer’s Machine Valuable?

A typical development environment holds far more sensitive information than an ordinary workstation.

Think about the credentials you use during a normal working day:

  • GitHub access tokens and SSH keys.
  • npm publishing tokens in ~/.npmrc.
  • Cloud credentials in ~/.aws, ~/.config/gcloud, or ~/.azure.
  • Database connection strings.
  • API keys stored in .env files.
  • Browser sessions and authentication cookies.
  • CI/CD deployment secrets.

A dependency running under your user account can read most of these files.

Even a package installed only as a dev dependency can be dangerous. It doesn’t need to end up in your production bundle to compromise your development environment.

The same applies to CI runners, which are often even more valuable targets. A compromised build job may expose credentials that grant access to private repositories, package publishing, deployment infrastructure, or production services.

The impact depends on the permissions available to the affected process, which is exactly why limiting those permissions is so effective.

4. How Malicious Packages Reach Your Project

Attackers don’t need to convince you to install an obviously suspicious library. There are several ways an unwanted dependency can sneak into a legitimate project:

Entry pointHow it works
TyposquattingA name that resembles a popular library: reacct, lodahs
Transitive dependenciesA library you trust pulls in an unwanted indirect dependency
Compromised updatesA legitimate package receives a malicious release
Disguised functionalityA working utility hides unrelated malicious behavior

Typosquatting is easy to understand and relatively easy to avoid. Compromised updates are much harder to defend against.

You might have used the same package for years. Its repository looks legitimate, its documentation is excellent, and millions of developers depend on it.

None of that guarantees the next release is safe.

5. Recognizing Suspicious Code

Security analysis becomes more useful when you look at combinations of behaviors rather than individual functions.

A call to fetch() is normal. So is reading a configuration file. Base64 encoding is used in thousands of legitimate applications.

But a small string formatting library that reads credentials, spawns external processes, decodes hidden executable content, and talks to an unrelated server deserves a much closer look.

Useful red flags:

  • Install hooks in a package that has no reason to need them.
  • Heavily obfuscated or minified code in a package that ships readable source elsewhere.
  • Network requests to domains unrelated to the package’s purpose.
  • Access to files like ~/.npmrc, ~/.ssh, or ~/.aws from a library that should never touch them.
  • eval, new Function, or child_process combined with decoded strings.

Base64 is not encryption

You’ll often see encoded strings like this in suspicious code:

js
const encoded = 'SGVsbG8sIGRldmVsb3BlciE=';

const decoded = Buffer.from(encoded, 'base64').toString('utf8');

console.log(decoded);

Output:

text
Hello, developer!

Base64 itself is harmless. It’s just a way to hide a string from a quick visual scan.

The concern arises when decoded content is treated as code rather than data, for example passed to eval() or written to disk and executed.

During a review, decode suspicious strings to inspect them, but never execute the result. Unknown code should never run on your regular development machine.

Unexpected external downloads

Some libraries legitimately download platform-specific binaries during installation. esbuild, sharp, and Playwright all do something like this.

However, a package that fetches executable content from an undocumented server adds a serious risk: the downloaded content can change at any time, independently of the published package version.

That quietly bypasses the guarantees of version pinning and integrity hashes. Your lockfile verifies the tarball, not whatever the tarball downloads afterwards.

A locked dependency is not a locked execution environment.

6. When a Trusted Package Becomes the Attack Vector

One of the most significant cases discussed in the Solar Security research is the Shai-Hulud campaign, a self-replicating worm that spread through npm.

On November 24, 2025, its second wave hit PostHog and other well-known maintainers, including Zapier, Postman, and ENS Domains. Attackers used compromised maintainer credentials to publish trojanized versions of legitimate packages such as posthog-js, posthog-node, and @posthog/cli@0.5.15.

The malicious @posthog/cli release is a good illustration of how these attacks are designed:

  1. A new preinstall script ran setup_bun.js, which installed the Bun runtime and then executed an obfuscated bun_environment.js payload.
  2. The payload collected GitHub and npm tokens, environment variables, and AWS, GCP, and Azure secrets. It even ran TruffleHog, a legitimate secret scanner, to find more credentials on disk.
  3. The stolen data was exfiltrated through the GitHub API, and stolen npm tokens were used to publish infected versions of other packages, which is what made it a worm.
  4. If it couldn’t find any tokens, it attempted to destroy writable files in the user’s home directory.
  5. Meanwhile, the original postinstall script still downloaded the real CLI binary, so the package kept working exactly as expected.

That last point is what makes this kind of attack so dangerous. Nothing looked broken. Developers already trusted the software, the package name was correct, and the tool did its job.

text
compromised maintainer token
            │
            ▼
   malicious release on npm ──────────────────────────┐
            │                                         │
   developers & CI run npm install                    │
            │                                         │
   preinstall steals tokens & cloud secrets           │
            │                                         │
   stolen npm tokens ──▶ publish infected versions ───┘
                         of the victims' own packages

A compromised maintainer account can turn an established package into a distribution channel for malicious code overnight.

Popularity, download counts, and a familiar name are useful signals, but they are not security guarantees.

7. How to Inspect a Package Before Installing It

You don’t need to be a malware analyst to make better dependency decisions.

Start with the package metadata:

bash
npm view example-package \
  version \
  repository \
  maintainers \
  scripts \
  dependencies \
  dist.integrity \
  --json

This reads information from the registry without installing anything.

Look for unexpected maintainers, a missing repository link, install hooks, and dependencies that have nothing to do with the library’s purpose. A version published minutes ago by a maintainer you’ve never seen before deserves extra caution.

Download the package without installing it

The published npm tarball may contain files that aren’t in the public GitHub repository. That’s exactly what happened in several real attacks: the GitHub source was clean, but the published package was not.

Download the tarball without running anything:

bash
npm pack example-package@1.2.3 --ignore-scripts

List its contents:

bash
tar -tzf example-package-1.2.3.tgz

Inspect the published manifest:

bash
tar -xOf example-package-1.2.3.tgz package/package.json

Pay particular attention to executable scripts, unusually large bundled files, and install hooks.

For a package you already suspect, do this inspection in an isolated environment such as a disposable container or VM, not on your main workstation.

Find out why a dependency is installed

Sometimes you discover an unfamiliar package in node_modules and have no idea how it got there.

npm can tell you:

bash
npm explain example-package

Or show where it sits in the tree:

bash
npm ls example-package --all

This tells you whether it’s a direct dependency or was pulled in by another library.

List every package that runs code at install time

It’s worth knowing exactly which of your dependencies use install hooks. This small script walks node_modules and prints them:

list-install-scripts.mjs

js
import { readdirSync, readFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';

const HOOKS = ['preinstall', 'install', 'postinstall'];
const found = [];

function scan(dir) {
  if (!existsSync(dir)) return;

  for (const entry of readdirSync(dir, { withFileTypes: true })) {
    if (!entry.isDirectory() || entry.name.startsWith('.')) continue;

    const pkgDir = join(dir, entry.name);

    // Scoped packages: node_modules/@scope/name
    if (entry.name.startsWith('@')) {
      scan(pkgDir);
      continue;
    }

    const manifest = join(pkgDir, 'package.json');

    if (existsSync(manifest)) {
      const pkg = JSON.parse(readFileSync(manifest, 'utf8'));
      const hooks = HOOKS.filter(hook => pkg.scripts?.[hook]);

      if (hooks.length > 0) {
        found.push({
          package: `${pkg.name}@${pkg.version}`,
          hooks: hooks.map(h => `${h}: ${pkg.scripts[h]}`).join(' | '),
        });
      }
    }

    // Nested node_modules (non-hoisted dependencies)
    scan(join(pkgDir, 'node_modules'));
  }
}

scan(join(process.cwd(), 'node_modules'));
console.table(found);
console.log(`${found.length} package(s) with install-time scripts`);

Install dependencies with scripts disabled, then run it:

bash
npm ci --ignore-scripts
node list-install-scripts.mjs

Example output:

text
┌─────────┬─────────────────────────┬──────────────────────────────────────────────┐
│ (index) │ package                 │ hooks                                        │
├─────────┼─────────────────────────┼──────────────────────────────────────────────┤
│ 0       │ '@parcel/watcher@2.6.0' │ 'install: node scripts/build-from-source.js' │
│ 1       │ 'esbuild@0.24.2'        │ 'postinstall: node install.js'               │
└─────────┴─────────────────────────┴──────────────────────────────────────────────┘
2 package(s) with install-time scripts

In most projects the list is short. A new entry appearing after a routine dependency update is exactly the kind of change worth investigating.

One caveat: a package with a binding.gyp file gets an implicit node-gyp rebuild install step even without an explicit script, so native modules may not show up in this list.

8. Disable Installation Scripts Where Possible

One of the simplest ways to reduce install-time exposure is to turn lifecycle scripts off.

bash
npm install --ignore-scripts

In CI:

bash
npm ci --ignore-scripts

Or for the whole project:

.npmrc

ini
ignore-scripts=true

There’s a trade-off. Some packages genuinely need install scripts to download native binaries or generate files, and disabling scripts will break them.

A better long-term approach is to allow scripts only for packages you’ve explicitly approved.

pnpm does this by default: since pnpm 10, dependency lifecycle scripts are blocked unless you allow them. When you install a package that wants to run a build script, pnpm warns you, and you decide:

bash
pnpm approve-builds

Your decisions are saved in pnpm-workspace.yaml and committed with the project:

pnpm-workspace.yaml

yaml
allowBuilds:
  esbuild: true
  sharp: true
  core-js: false

(pnpm 10 stored the same list as onlyBuiltDependencies; pnpm 11 replaced it with allowBuilds.)

Review each package before approving it. An allowlist of three or four well-known packages is a much smaller attack surface than “everything in the tree”.

Remember that disabling install scripts closes only one execution path. Malicious code can still run when a package is imported, built, tested, or executed through a CLI.

9. Build a Safer CI Pipeline

CI environments deserve special attention because they often hold credentials that developers don’t have locally: publishing tokens, deployment keys, production cloud access.

A dependency installation job should never automatically receive production deployment permissions.

Here’s a basic GitHub Actions workflow that installs dependencies with lifecycle scripts disabled and checks for known vulnerabilities:

.github/workflows/security.yml

yaml
name: Dependency Security

on:
  pull_request:
  push:
    branches: [main]

permissions:
  contents: read

jobs:
  dependency-check:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          persist-credentials: false

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 22

      - name: Install dependencies
        run: npm ci --ignore-scripts

      - name: Audit dependencies
        run: npm audit --audit-level=high

A few details are doing real work here:

  • permissions: contents: read limits the automatically issued GITHUB_TOKEN to read-only access.
  • persist-credentials: false stops the checkout action from leaving that token in the local Git config, where any script could read it.
  • The job receives no publishing credentials or deployment secrets at all.

This is a starting point, not a complete security pipeline. For production workflows, pin third-party actions to full commit SHAs instead of version tags, since tags can be moved.

Also note that npm audit checks dependencies against known vulnerability advisories. A malicious package published an hour ago almost certainly has no advisory yet.

Passing an audit doesn’t prove your dependencies are safe.

Separate installation from deployment

text
┌────────────────┐   ┌────────────────┐   ┌────────────────┐   ┌──────────────────┐
│ install        │──▶│ test & audit   │──▶│ build          │──▶│ deploy / publish │
│ no secrets     │   │ no secrets     │   │ no secrets     │   │ short-lived OIDC │
│ read-only token│   │ read-only token│   │ read-only token│   │ protected branch │
└────────────────┘   └────────────────┘   └────────────────┘   └──────────────────┘

Keep deployment and publishing in separate jobs that run only when needed, ideally on protected branches with required reviews.

Where possible, use short-lived credentials through OpenID Connect instead of long-lived cloud access keys. For npm publishing, trusted publishing from GitHub Actions removes the need to store an npm token in CI at all.

If a dependency compromises the installation stage, it should find nothing worth stealing.

10. Lockfiles Help, but They Are Not a Security Boundary

Every application should commit its lockfile.

For npm projects, that means committing package-lock.json and installing with:

bash
npm ci

instead of letting every CI build resolve versions from scratch.

Lockfiles improve reproducibility and record an integrity hash for every package.

But an integrity hash answers only one question: “Did I receive the expected package contents?”

It doesn’t answer the one that matters here: “Are those contents safe?”

If you lock a malicious version, npm ci will faithfully install that malicious version every time.

Review lockfile changes as part of your normal pull request process:

bash
git diff main -- package.json package-lock.json

A small version bump can introduce dozens of new transitive dependencies. Those changes deserve attention, especially when they add new install scripts.

11. Useful Security Tools for Developers

You don’t have to rely on manual review alone. These tools solve different parts of the problem:

  • Socket analyzes what dependencies actually do (network access, install scripts, obfuscated code) and flags suspicious changes between versions. It’s one of the few tools focused on malicious packages rather than known vulnerabilities.
  • OSV-Scanner checks your dependencies against the open-source vulnerability database.
  • TruffleHog finds and verifies leaked credentials in repositories and other sources.
  • Gitleaks detects hardcoded secrets in source code and Git history, and works well as a pre-commit hook.
  • Renovate turns dependency updates into reviewable pull requests, so nothing changes silently. Its minimum release age setting can also delay adopting brand-new versions until the community has had time to spot problems.
  • Verdaccio is a private npm registry you can use as a controlled proxy. Package approval and scanning require additional policies or tooling on top.

Vulnerability scanning, secret detection, dependency management, and malicious package analysis complement each other.

No single scanner covers everything.

12. What If You’ve Already Installed a Malicious Package?

Deleting node_modules is not enough.

If malicious code has already run, it may have stolen credentials, modified files, or set up persistence outside the project directory.

Treat it as a security incident:

  1. Isolate the affected workstation or CI runner.
  2. Preserve logs, lockfiles, and the exact package versions involved.
  3. From a clean device, revoke potentially exposed GitHub, npm, and cloud credentials.
  4. Review active sessions, SSH keys, OAuth apps, and personal access tokens.
  5. Check your repositories for unexpected commits, new workflows, and package releases you didn’t publish.
  6. Look for unauthorized cloud activity and deployment changes.
  7. Rebuild the affected environment from a trusted source.
  8. Restore access with newly issued, minimally scoped credentials.

Changing your password alone doesn’t invalidate API tokens or stolen session cookies. Revoke them separately.

Known campaigns often leave traces you can search for. For example, PostHog’s post-mortem of the Shai-Hulud attack suggested looking for its payload files:

bash
find . -name "setup_bun.js" \
  -o -name "bun_environment.js" \
  -o -name "truffleSecrets.json"

and checking npm logs for unexpected install scripts:

bash
grep -R "preinstall" ~/.npm/_logs

Finding nothing doesn’t prove you’re clean, but finding something tells you immediately what you’re dealing with.

If the machine belongs to your company, involve the security team before you wipe anything. Evidence you destroy can’t help them work out what was taken.

13. A Better Dependency Security Strategy

The goal is not to stop using open-source software. Modern development would be nearly impossible without it.

The goal is to reduce unnecessary trust.

For individual developers, that means:

  • Checking unfamiliar packages before installing them.
  • Allowing install scripts only for packages that need them.
  • Committing lockfiles and reviewing their diffs.
  • Keeping long-lived credentials out of places where third-party code runs.

For teams, it also means:

  • Controlled registries and dependency approval policies.
  • Automated checks for malicious packages, not just vulnerabilities.
  • Isolated build environments with minimal permissions.
  • Restricted, short-lived publishing and deployment credentials.

Security should be part of dependency management, not something that starts after an incident.

Final Thoughts

We spend considerable time reviewing application code, validating user input, configuring authentication, and protecting production APIs.

Then we install hundreds of dependencies maintained by people we’ve never met.

Every new dependency introduces another trust relationship. Every update can change it.

The next time you run npm install, remember that you’re not just downloading a collection of JavaScript files.

You may also be giving someone else’s code permission to run on your machine.

That deserves the same attention as any other security-sensitive operation.