Square CloudSquare Cloud

Malicious npm packages: how to spot them and what to do

A malicious npm package is code published on purpose to steal data or take over the machine, often at install time. If you installed one, remove it, rotate every credential that machine could reach and reinstall from a clean lockfile.

Updated 8 min read

Learning objectives

After reading this article you will be able to:

  • Recognize the alerts and signs of a malicious npm package
  • Understand typosquatting, dependency confusion, install scripts and compromised maintainer accounts
  • Respond to the incident and make dependency installs harder to exploit
On this page

A malicious package is not a package with a bug. It is code published on purpose to steal tokens, cloud keys and environment variables, install a crypto miner or open a door for whoever published it. And it can act before you write a single line, because npm install can run package scripts on your machine and in CI.

How does a malicious package show up in your project?#

Through an alert, through a package that vanished from the registry or through odd behavior:

1. A malware advisory. The GitHub Advisory Database publishes malware advisories it receives from the npm security team and from the OpenSSF Malicious Packages repository. For npm, the title follows the format Malware in <package>, with no fixed version, and the standard text reads:

text
Any computer that has this package installed or running should be considered fully compromised. All secrets and keys stored on that computer should be rotated immediately from a different computer. The package should be removed, but as full control of the computer may have been given to an outside entity, there is no guarantee that removing the package will remove all malicious software resulting from installing it.

That data reaches you through Dependabot malware alerts, which you turn on separately from regular alerts and which cover npm among other ecosystems, and through scanners that read OSV.dev, which includes the OpenSSF data (its IDs start with MAL-). The tools are compared in how to find vulnerable dependencies.

2. A package replaced by a placeholder. When npm removes a malicious package, it publishes a 0.0.1-security version in its place with this README:

text
# Security holding package

This package contained malicious code and was removed from the registry by the npm security team. A placeholder was published to ensure users are not affected in the future.

If npm view package-name shows 0.0.1-security as the latest version, the package you were using was removed for containing malicious code.

3. Odd behavior. Outbound connections to unknown hosts during install, high CPU with no load, new files outside the project or one of your tokens used from an IP you don't recognize. None of these proves anything alone, but each one is worth investigating.

How does a malicious package get in?#

Vector How it works Main defense
Typosquatting A name almost identical to a popular package, with one letter swapped or an extra hyphen Check the name and copy the install command from the official docs
AI-suggested name An assistant suggests a package that doesn't exist, and someone publishes that name npm view <package> before installing
Dependency confusion Your internal package has no scope, and someone publishes the same name to the public registry with a higher version A scope (@company/package) pointed at your private registry
Install script preinstall, install and postinstall run at install time with your user's permissions, unless something blocks them Per-package approval (allowScripts) or ignore-scripts
Compromised maintainer account A new version of a legitimate package, published with a stolen password or token A lockfile with npm ci and a wait before adopting new versions

npm says it detects typosquats and blocks them from being published, but that it cannot detect dependency confusion, and it recommends scopes for private packages.

The install script is what turns a wrong name into an incident. npm's documentation lists preinstall, install and postinstall among the scripts that run on install, and a package with a binding.gyp and no install or preinstall script of its own gets an automatic node-gyp rebuild. The legitimate use is compiling native code. The malicious use is the same hook reading environment variables and credential files in your home folder the moment the package lands.

How do you know if your project was affected?#

Start from the package name and version in the advisory and answer three questions: is the package in the project, how did it get there and when.

bash
# is the package in the lockfile? which dependency brought it in?
npm ls package-name --package-lock-only
npm explain package-name   # with node_modules installed

# which commit added it to the lockfile
git log -S "node_modules/package-name" --oneline -- package-lock.json

# which lockfile dependencies have install scripts
node -e 'const l=require("./package-lock.json");for(const[p,v]of Object.entries(l.packages))if(v.hasInstallScript)console.log(p)'

# package metadata: version dates, maintainers, repository and scripts
npm view package-name time maintainers repository.url scripts

Compare the version in your lockfile with the affected versions in the advisory. In a package built to be malicious, every version is affected. In a compromised maintainer account, only the versions the attacker published.

Then find out where the install ran: on your machine, on a server, in which CI job. Every place that ran npm install or npm ci with that version counts as compromised, and what matters is the list of secrets each one could reach.

What should you do if you installed a malicious package?#

  1. Isolate. Take the machine off the network or stop the CI runner. Don't keep working on it.

  2. Rotate every credential, from a different computer. npm and GitHub tokens, SSH keys, cloud keys, database passwords, bot tokens, everything in .env and in the CI variables. Revoke the old credential, don't just create a new one. The steps per key type are in API key exposed on GitHub.

  3. Remove the package and reinstall clean. If it is a direct dependency, take it out of package.json; if it is transitive, update the package that pulls it in or force a safe version with overrides.

    bash
    npm uninstall package-name         # if it is a direct dependency
    rm -rf node_modules
    npm install --ignore-scripts       # updates the lockfile without running scripts
    git diff package-lock.json         # review every package that changed
    npm ci                             # clean install from the reviewed lockfile
  4. Look for what was left behind. Look for new workflows in .github/workflows, unknown keys in ~/.ssh/authorized_keys, scheduled tasks, and commits or packages published with your tokens. When in doubt, reinstall the system. The full response playbook is in my app was hacked.

  5. Review account activity. The security logs of GitHub, npm and your cloud provider show logins and token use from unknown origins.

  6. Report it. On the package page at npmjs.com, use Report malware and list the affected versions.

How do you avoid the next malicious package?#

Always install from the lockfile. Commit package-lock.json and use npm ci in CI and in production: it fails if the lockfile and package.json disagree and never rewrites the lockfile. The lockfile pins every package to a cryptographic hash, the integrity field, and OpenSSF recommends that CI only run commands that treat the lockfile as read-only. If CI is new to you, see what CI/CD is.

Approve install scripts one package at a time. In recent npm versions, dependency install scripts follow the allowScripts field in package.json: you approve each package that needs them with npm approve-scripts <package>, and npm install-scripts ls lists the ones not reviewed yet. Depending on your npm version, an unapproved script is skipped or runs with a warning; with strict-allow-scripts=true, the install fails until you approve or deny the package:

ini
# .npmrc at the project root
strict-allow-scripts=true
min-release-age=3
@company:registry=https://registry.company.example/

ignore-scripts=true is the blunt option: npm runs no scripts from package.json files, approved ones included, so packages that compile native code stop working (npm start and npm run still run the script you asked for, but not its pre and post scripts). pnpm only runs dependency scripts you have allowed, and you allow them with pnpm approve-builds. If the install breaks because of this, npm install errors on deploy helps you read the message.

Wait before adopting new versions. min-release-age=3 makes npm install only versions published more than 3 days ago (the value is an example). OWASP recommends giving new versions time to circulate before you adopt them: the wait lets a malicious version be reported and removed before it reaches your project. The cost is that security fixes arrive later too; a package listed in min-release-age-exclude skips the wait.

Scope your internal packages. The @company:registry line tells npm to fetch everything in that scope from your private registry. Create the organization on npmjs.com too: then nobody else can publish under the @company scope on the public registry.

Check the origin before installing. A package that npm view shows as created yesterday, with no repository and a postinstall, deserves suspicion.

Verify signatures and provenance. npm audit signatures checks registry signatures and provenance attestations for the installed packages, and fails if the registry publishes signing keys and a package arrives unsigned:

text
audited 1267 packages in 6s

1267 packages have verified registry signatures
74 packages have verified attestations

Provenance links a package to the repository and build that produced it, but npm's documentation warns that it doesn't guarantee the code isn't malicious.

Keep fewer secrets within reach. CI tokens with the narrowest scope and secrets kept out of loose files on the machine limit the damage of a package that slips past the other defenses. See where to store secrets.

How to do this on Square Cloud#

On Square Cloud, Cubic, the dashboard's AI agent, runs a read-only check-up of your application on every plan: type /checkup in the chat (up to 3 every 10 minutes). Dependencies with known vulnerabilities come from OSV.dev, which brings together the GitHub Advisory Database and other databases, for npm, PyPI, Composer, Go modules, crates.io, RubyGems and Hex. Packages are read from the root lockfiles and from what the application installed, so transitive dependencies are included, and a known malicious package shows up as critical.

When that happens, the rule is the incident one above: remove the package and rotate every credential. The application's environment variables already exist while dependencies install, so treat all of them as exposed: generate new keys at the source and update the values in the dashboard, and the change applies on the next restart. The application's disk persists across deploys, and the install at start happens when there is no node_modules: delete that folder before restarting, so dependencies come from the clean lockfile. Each application runs in an isolated container and can't read another one's variables or files, even in the same account, but a key reused across several applications has to be rotated in all of them.

The check-up also flags credentials written in the code (file and line, never the value). Only the ecosystem, name and version of each package go to OSV.dev, and anything that couldn't be read shows as "not verified", never as "all clear". It is a dependency and configuration check, not a pentest or an audit, so the install-time defenses are still yours to set up. See the details on vulnerability scanning.

Infrastructure

L3/L4/L7 DDoS mitigation and a WAF on every plan

Vulnerability scanning

FAQs

What is the difference between a vulnerable package and a malicious one?

A vulnerable package has a bug someone can exploit, and a new version fixes it. A malicious package was built to cause harm: GitHub's malware advisories list no fixed version, because no safe version exists.

Does removing the malicious package fix it?

Not on its own. The code may have run at install time and copied tokens and keys. GitHub's malware advisories say to treat the machine as compromised and rotate every secret from a different computer.

Does --ignore-scripts make installs safe?

It lowers the risk, because it stops preinstall, install and postinstall from running during installation. Malicious code can still run when your application imports the package, so the other defenses still matter.

How do I report a malicious package on npm?

On the package page at npmjs.com, click Report malware and describe what you found, including the affected versions. The npm security team confirms it, removes the package, publishes a placeholder and issues an advisory.

Next articleWhat is XSS (cross-site scripting) and how to prevent itXSS is when a site delivers an attacker's script to other users' browsers. Learn the types (reflected, stored, DOM), context-aware escaping and what CSP adds.

More in Security

See all 24 articles