12 min read

npm Security: The Complete Guide to Package Vulnerabilities

npm Security: The Complete Guide to Package Vulnerabilities
Photo by Irvan Smith / Unsplash

npm processes 4.5 trillion package requests annually, representing 70% year-over-year growth (Sonatype, 2024). This scale makes the JavaScript ecosystem both indispensable and dangerous.

Over 704,000 malicious packages have been identified since 2019, with 512,847 discovered in the past year alone, a 156% increase year-over-year (Sonatype, 2024). The OWASP Top 10 2025 elevated Software Supply Chain Failures to the third most critical web application security risk, reflecting how attacks on package ecosystems have moved from theoretical concern to operational reality.

The average npm project pulls in 79 transitive dependencies (DEV Community, 2025). A single compromised package can cascade through millions of downstream applications within hours. If your applications depend on npm packages, and they almost certainly do, understanding how vulnerabilities work and how to detect them is no longer optional.

Stay ahead of npm security threats. Subscribe to CyberDesserts for practical security content when it matters.


Types of npm Vulnerabilities

Research analysing over 31,000 vulnerabilities across ecosystems from 2017 to 2025 reveals distinct patterns in npm (arXiv, 2025). Understanding these categories helps prioritise detection and response efforts. The following are ordered by prevalence in the npm ecosystem.

Embedded Malicious Code (CWE-506)

Embedded malicious code represents 48.58% of all npm vulnerabilities, the single largest category (arXiv, 2025). Unlike traditional vulnerabilities that result from coding errors, these are packages published with harmful intent from the start.

Malicious packages in npm surged from 38 reports in 2018 to over 2,168 in 2024 (arXiv, 2025). Snyk identified over 3,000 malicious npm packages in 2024 alone, with JavaScript remaining the most targeted ecosystem into 2025 (Snyk, 2025). In Q1 2025, 56% of discovered malware was designed for data exfiltration, up from 26% in Q4 2024 (Sonatype, 2025).

Common tactics include typosquatting (publishing packages with names like lodahs hoping developers mistype lodash), dependency confusion (publishing internal package names to public registries), and star-jacking (cloning popular repositories to build false credibility). Research shows 71.2% of malicious packages use long names with more than 10 characters, and 67.3% include dashes, mimicking legitimate naming conventions (arXiv, 2025).

For detailed analysis of how these attacks work, see our guide to auditing the npm supply chain.

Supply Chain Attacks

Supply chain attacks compromise legitimate packages rather than publishing new malicious ones. By targeting trusted maintainers or build infrastructure, attackers gain access to packages with established user bases.

The September 2025 npm supply chain attack compromised 18 popular packages including chalk and debug, collectively downloaded over 2.6 billion times weekly (Varonis, 2025). The Shai-Hulud worm demonstrated self-propagating behaviour, using stolen npm tokens to automatically inject malicious code into other packages the compromised developer maintained (Unit 42, 2025). CISA issued an official alert recommending organisations pin dependencies to pre-September 16, 2025 versions and rotate all developer credentials (CISA, 2025).

Supply chain attacks averaged just under 13 per month during early 2024 but rose to over 16 per month from October 2024 to May 2025, with some months reaching nearly 25 (Reflectiz, 2025).

For analysis of specific incidents, see our coverage of the Shai-Hulud npm attack.

Prototype Pollution (CWE-1321)

Prototype pollution appears in 560 reports specific to npm, a JavaScript-unique vulnerability class caused by the language's prototype inheritance model (arXiv, 2025).

JavaScript objects inherit properties from prototypes. When attackers manipulate __proto__, constructor, or prototype attributes, they can inject malicious properties that affect every object in the application. Consequences range from denial of service to remote code execution. Server-side prototype pollution is particularly dangerous, enabling full remote code execution without authentication in affected Node.js applications.

Multiple high-profile libraries were affected in 2024, including web3-utils (CVE-2024-21505), dset (CVE-2024-21529), and uplot (CVE-2024-21489). The 2025 Sveltekit vulnerability (CVE-2025-55182) demonstrated how prototype pollution in frameworks can enable remote code execution (Aikido, 2025).

Prevention: Use Object.create(null) for objects handling user input. Validate JSON input with schemas. Avoid unsafe recursive merge functions. Consider using Map instead of plain objects for user-controlled data.

Regular Expression Denial of Service (ReDoS)

ReDoS vulnerabilities exploit inefficient regular expressions that consume excessive CPU when processing malicious input. An attacker can crash applications or cause significant performance degradation with crafted strings.

The cross-spawn package vulnerability (CVE-2024-21538) affected millions of projects through transitive dependencies, demonstrating how ReDoS in widely-used utilities creates broad exposure (Snyk, 2024). Similar vulnerabilities appeared in @eslint/plugin-kit (CVE-2024-21539), es5-ext (CVE-2024-27088), and micromatch (CVE-2024-4067).

ReDoS is particularly insidious because the vulnerable code often appears harmless during development but becomes a security issue under adversarial conditions. The Node.js runtime has addressed several ReDoS vulnerabilities in core packages through 2024 and 2025 security releases (Node.js, 2024).

Path Traversal

Path traversal allows attackers to access files outside intended directories by manipulating file paths. Despite being well-documented since the 1990s, these vulnerabilities increased 85% in closed-source projects from 2023 to 2024 (Aikido, 2024).

The webpack-dev-middleware vulnerability (CVE-2024-29180) allowed arbitrary file access on developer machines through insufficient URL validation. Node.js itself addressed multiple path traversal issues in 2024 and 2025, including CVE-2024-21896 (monkey-patching Buffer internals) and CVE-2025-27210 (Windows device name handling) (Node.js Security Releases, 2024-2025).

Prevention: Never concatenate user-supplied paths directly. Apply URL decoding before path resolution. Use allowlists rather than blocklists. Set strict base directories and validate all paths are relative to them.

Command Injection

Command injection occurs when user input is passed unsanitised to system commands. The BatBadBut vulnerability (CVE-2024-27980) in Node.js demonstrated how improper handling of batch files on Windows could enable arbitrary command execution even without the shell option enabled (Node.js, 2024).

This vulnerability class affects applications using child_process.spawn, child_process.exec, or similar APIs without proper input sanitisation. Attackers can chain commands using characters like ;, |, or && to execute arbitrary code on the server.

Transitive Dependency Vulnerabilities

Transitive dependencies are packages your dependencies depend on. You never explicitly installed them, but they run in your application nonetheless.

A typical npm project has dozens of direct dependencies and hundreds of transitive dependencies. Snyk's 2024 research found only 24% of organisations are confident in the security of their direct dependencies, and just 37% report that dependencies are easy to track (Snyk/Linux Foundation, 2024). Only 25% of teams track only direct dependencies, with almost 5% tracking none at all (Snyk, 2024).

This is why scanning only direct dependencies provides incomplete visibility. The vulnerability might be three or four levels deep in your dependency tree, invisible unless you specifically analyse the complete SBOM.

Abandoned Package Risks

Packages that have not been updated in over 1,000 days are effectively unmaintained. When vulnerabilities are discovered, no patches will be forthcoming.

Research shows the time a vulnerability remains in the ecosystem before being fixed has increased by 95% from 2017 to 2024 (arXiv, 2025). Several critical vulnerabilities in 2024 took over 500 days to fix (Sonatype, 2024). 80% of application dependencies remain un-upgraded for over a year, even when 95% of vulnerable components have fixed versions available (Sonatype, 2024).

Monitoring package freshness is as important as scanning for known CVEs.


How Vulnerabilities Enter Your Codebase

Understanding attack vectors helps focus defensive efforts on the most likely entry points.

Maintainer Account Compromise

The September 2025 npm attack began with a phishing email from npmjs.help, a domain registered specifically for the campaign (Varonis, 2025). The fake login page captured credentials and 2FA tokens through adversary-in-the-middle techniques. One compromised maintainer account cascaded into billions of affected downloads.

Two-factor authentication helps but is not foolproof. Hardware security keys and FIDO-based authentication provide stronger protection against phishing.

Automated Installation

CI/CD pipelines and automated builds that run npm install without version pinning can pull malicious updates automatically. The Shai-Hulud attack specifically targeted CI/CD environments, using GitHub Actions workflows to propagate across repositories (Unit 42, 2025).

Using npm ci instead of npm install in production pipelines ensures you only install exactly what is in your lockfile. It fails if the lockfile is out of sync with package.json rather than silently updating.

AI-Assisted Attack Generation

Security researchers observed AI-generated payloads in recent npm attacks. Unit 42 noted they are "moderately confident that the attackers used AI to generate the malicious script, given the use of comments and emojis" in the Shai-Hulud payload (Unit 42, 2025). The s1ngularity attack also showed signs of AI generation (InfoQ, 2025).

This represents an evolution in attack sophistication, allowing threat actors to rapidly iterate on evasion techniques and generate convincing phishing content.


Detecting npm Vulnerabilities

Multiple tools exist for vulnerability detection. Each has strengths and blind spots.

npm audit

The built-in npm audit command checks your dependencies against npm's vulnerability database. It is free, requires no setup, and integrates with npm workflows.

However, npm audit only catches known vulnerabilities after they are reported. It misses newly published malicious packages, recently compromised legitimate packages, and issues not yet in npm's database. It also cannot assess package age or maintenance status.

If npm audit fix is not resolving your vulnerabilities, see our troubleshooting guide for npm audit fix not working.

Building Custom Scanners

Google's deps.dev API aggregates vulnerability data from multiple sources including npm, GitHub, and the Open Source Vulnerabilities database. It provides broader coverage than npm's database alone and is free to use.

For hands-on detection beyond npm audit, I built a custom scanner using the deps.dev API. See the complete tutorial: Build an npm Vulnerability Scanner.

SBOM Analysis

Software Bill of Materials scanning provides visibility into your complete dependency tree. When a new vulnerability is announced, you can immediately identify which applications are affected.

Regulatory requirements are increasing. The EU's Network and Information Systems Directive (NIS2) came into force in October 2024, with similar regulations emerging in India and Australia (Sonatype, 2024).


npm Security Scanning Tools

No single tool catches everything. The most effective approach combines reactive scanning (known CVEs) with proactive detection (behavioural analysis, malware detection).

Tool Best For Key Capabilities Considerations
npm audit Quick checks, CI baseline Built-in, free, automatic fix suggestions npm database only, reactive to known CVEs, no malware detection
Aikido Security Real-time install protection Safe Chain blocks malware at install, 24-hour cooldown option, live malware feed (6,000+ packages flagged June 2025), 95% noise reduction via reachability analysis Free tier available, paid for full features, detected xrpl compromise in 45 minutes
Socket Behavioural analysis AI-powered threat detection, detects obfuscation/typosquatting/shell scripts, PR integration, browser extension, MCP for AI coding environments Built by npm maintainers (1B+ monthly downloads), discovered Shai-Hulud campaign spread
Snyk Enterprise teams Comprehensive vulnerability database, fix guidance, container scanning, IDE plugins, 6,800+ malicious packages documented since 2023 Industry standard, can be noisy without reachability filtering
Semgrep Supply Chain Code + dependency analysis Combines SAST with SCA, reachability analysis, custom rules, released Shai-Hulud detection rules Developer-focused, open source core
Sonatype Lifecycle Enterprise governance Repository Firewall blocks malware proactively (20,920 attacks blocked Q1 2025), policy enforcement, SBOM management Enterprise pricing, stewards of Maven Central
GitHub Dependabot GitHub-native workflows Automatic PRs for updates, security alerts, free for public repos, GitHub published 2,000+ CVEs in 2024 Reactive to known CVEs, no behavioural malware detection
JFrog Xray Artifactory users Deep Artifactory integration, impact analysis, Curation for package approval workflows Enterprise pricing, best within JFrog ecosystem
Trivy Container and SBOM scanning Open source, comprehensive, filesystem and image scanning, license detection Requires infrastructure setup, no real-time install protection
deps.dev Cross-database coverage Free API, aggregates multiple vulnerability sources, package metadata and dependency graphs Requires custom integration, no out-of-box blocking

Choosing the Right Combination

For individual developers: Start with npm audit for baseline coverage. Add Socket's CLI wrapper (alias npm="socket npm") for real-time malware blocking during local development.

For small teams: GitHub Dependabot provides automatic PRs for known vulnerabilities. Pair with Aikido Safe Chain or Socket for supply chain threat detection at install time.

For enterprise: Layer Snyk or Semgrep for comprehensive coverage with Sonatype Repository Firewall or Aikido Safe Chain for proactive blocking. Consider JFrog Xray if using Artifactory for package management.


Fixing and Preventing npm Vulnerabilities

Detection is only valuable if you act on findings.

Version Pinning and Lockfiles

Lock dependencies to exact versions rather than semver ranges. Always commit package-lock.json or yarn.lock. In production pipelines, use npm ci which fails if the lockfile does not match package.json rather than silently updating.

CISA's guidance following the September 2025 attack specifically recommended pinning dependencies to known safe releases produced prior to the attack date (CISA, 2025).

Cooldown Periods

Several tools now support enforcing minimum package age before allowing installation. Aikido Safe Chain offers a 24-hour cooldown option. Packages compromised and then identified typically get removed within hours or days. A cooldown period prevents your builds from pulling malicious versions during that critical window.

Disabling Install Scripts

Many supply chain attacks execute during preinstall or postinstall scripts. The Shai-Hulud 2.0 campaign shifted from post-install to pre-install execution, dramatically widening its impact across developer machines and CI/CD pipelines (Unit 42, 2025).

Running with --ignore-scripts prevents script execution but may break legitimate packages. A more targeted approach is auditing which packages require scripts and allowlisting only those.

Private Registry Solutions

Enterprise teams benefit from private registries that proxy npm with additional controls. JFrog Artifactory provides package approval workflows and curation policies. Nexus Repository offers security scanning integration. Private registries also provide audit trails showing exactly which packages entered your environment and when.


Enterprise Security Considerations

Larger organisations face additional challenges managing npm security at scale.

Developer Workflow Integration

Security tools that slow developers down get bypassed. Snyk's research found 52% of teams often fail to meet vulnerability SLA deadlines, with 74% setting unrealistic SLAs of a week or less (Snyk, 2024). Integrate scanning into existing workflows rather than adding separate steps.

Assessing your broader security posture? Take the AI Security Maturity Assessment to identify gaps across your security programme.

Incident Response Planning

The September 2025 attack demonstrated how quickly compromises can cascade. CISA's recommended response includes:

  • Conduct dependency review across all software using npm
  • Pin versions to known safe releases
  • Immediately rotate all developer credentials
  • Mandate phishing-resistant MFA on all developer accounts
  • Monitor for anomalous network behaviour
  • Harden GitHub security by removing unnecessary apps and auditing webhooks

Having these procedures documented before an incident saves critical time during response.


What's Coming: The Future of npm Attacks

The npm threat landscape is evolving in predictable directions based on current trends.

AI-assisted attack generation will accelerate. Multiple 2025 attacks showed signs of AI-generated payloads. Attackers are using LLMs to rapidly iterate on evasion techniques, craft convincing phishing content, and generate obfuscated code (Unit 42, 2025; InfoQ, 2025). Security predictions for 2026 expect AI-powered attacks to "outpace human response" (Espria, 2025).

Self-propagating worms will become more common. The Shai-Hulud campaigns demonstrated that supply chain attacks can automate their own spread. When a compromised package encounters additional npm tokens, it can automatically publish malicious versions of any packages it can access, spreading across the ecosystem without direct attacker intervention (Wiz, 2025).

Pre-install attacks will increase. Shai-Hulud 2.0 shifted from post-install to pre-install execution, dramatically widening impact. Expect more attacks to target earlier stages of the installation process (Unit 42, 2025).

Punitive fallback mechanisms will emerge. Shai-Hulud 2.0 introduced destructive behaviour, attempting to delete the victim's home directory if credential theft failed (Unit 42, 2025). Future malware may increasingly combine data theft with sabotage.

CI/CD pipelines remain prime targets. Predictions for 2026 specifically identify DevOps ecosystems as the prime target for supply chain adversaries (ExtraHop, 2025). Organisations urgently innovating with AI applications create additional attack surface.

Traditional security tools will continue to fail. Sonatype notes that "traditional security tools often fail to detect these novel attacks" (Sonatype, 2024). The gap between attack sophistication and detection capability is widening.

The path forward requires proactive security with vigilance against open source malware, decreased consumer complacency, and comprehensive dependency management. Organisations that treat supply chain security as a strategic priority rather than a compliance checkbox will be best positioned for the threat landscape ahead.


Key Takeaways

Managing npm vulnerabilities requires accepting certain realities and adapting accordingly.

  • Malicious code is the biggest threat. Nearly half of npm vulnerabilities are embedded malicious code, not coding errors. Detection must focus on intentional attacks, not just known CVEs.
  • Layer your defences. No single tool catches everything. Combine npm audit with behavioural analysis tools like Aikido or Socket, plus SBOM scanning for visibility.
  • Act on findings quickly. 95% of the time when vulnerable components are consumed, a fixed version already exists. Yet 80% of dependencies remain un-upgraded for over a year.
  • Prepare for incidents. The next major npm compromise is a matter of when, not if. Document response procedures now.
  • Monitor continuously. Point-in-time scans miss rapidly evolving threats. Automated daily or hourly scanning catches issues faster.

This guide covers npm security comprehensively. For deeper dives into specific topics:


The npm threat landscape evolves weekly. Subscribers receive notifications when new attacks emerge and when this guide is updated with new defence strategies.


Last updated: December 2025


References and Sources

  1. Sonatype. (2024). 10th Annual State of the Software Supply Chain Report. 704,102+ malicious packages since 2019; 156% YoY increase; 4.5 trillion npm requests in 2024.
  2. arXiv. (2025). Open Source, Open Threats? Investigating Security Challenges in Open-Source Software. Analysis of 31,267 vulnerabilities across ecosystems 2017-2025; CWE-506 represents 48.58% of npm vulnerabilities; 560 prototype pollution reports in npm.
  3. OWASP. (2025). OWASP Top 10 2025 Release Candidate. Software Supply Chain Failures elevated to #3.
  4. Unit 42, Palo Alto Networks. (2025). Shai-Hulud Worm Compromises npm Ecosystem. Self-propagating attack analysis; AI-generated payload assessment; pre-install vs post-install attack evolution.
  5. CISA. (2025). Alert: Widespread Supply Chain Compromise Impacting npm Ecosystem. Official remediation guidance for September 2025 attack.
  6. Snyk. (2024-2025). State of Open Source Security Report; Malicious Packages in Open Source Ecosystems. 3,600+ malicious packages in 2024; 52% fail vulnerability SLA deadlines.
  7. Socket Security. (2025). Supply Chain Attack Research. Shai-Hulud and CrowdStrike package compromise analysis; AI-powered threat detection.
  8. Aikido Security. (2025). Safe Chain and Security Research. 6,000+ malicious packages flagged June 2025; xrpl compromise detected in 45 minutes; path traversal trends.
  9. Varonis. (2025). AI-Generated Phishing: How One Email Triggered a Global NPM Supply Chain Crisis. 2.6 billion downloads affected; phishing campaign analysis.
  10. GitHub. (2025). GitHub Advisory Database by the Numbers. 2,000+ CVEs published in 2024; fifth-largest CNA in CVE Program.
  11. Wiz Research. (2025). Shai-Hulud npm Supply Chain Attack. First successful self-propagating attack in npm ecosystem; cross-victim exfiltration observed.
  12. InfoQ. (2025). NPM Ecosystem Suffers Two AI-Enabled Credential Stealing Supply Chain Attacks. s1ngularity and Shai-Hulud attack analysis.
  13. ExtraHop. (2025). 2025 Security Predictions: Attacks on the AI Supply Chain. DevOps ecosystem targeting; CI/CD pipeline risks.
  14. Node.js. (2024-2025). Security Releases. BatBadBut (CVE-2024-27980); path traversal fixes; ReDoS mitigations.
  15. Reflectiz. (2025). OWASP Top Ten 2025 Guide. Supply chain attack frequency trends 2024-2025.
  16. DEV Community. (2025). Essential npm Security Tools. Average 79 transitive dependencies per npm project.
  17. Sonatype. (2025). Open Source Malware Index Q1 2025. 56% data exfiltration malware; 18,000 new malicious packages in Q1 2025.