How to Stop Slopsquatting: Protect Your Frontend Project from AI-Hallucinated npm Packages

TL;DR — Slopsquatting is attackers registering npm package names that AI assistants hallucinate. Wrap installs with Socket, run npm audit signatures in CI, and add a pre-commit hook that blocks any new dependency that is missing, brand new or a near-miss of a popular name.

Slopsquatting: an npm supply chain attack where someone registers a package name that AI coding assistants keep hallucinating, then waits for developers to install it. No typo required. The model invents react-use-debounce-hook, you hit enter, and a postinstall script is reading your .env before the progress bar finishes.

The defence is three cheap layers: a scanner at install time, signature checks in CI, and a pre-commit hook that refuses any new dependency it cannot vouch for. Total setup is about fifteen minutes.

  1. Wrap every install with the Socket CLI so risky packages are flagged before they reach node_modules.
  2. Run npm audit signatures in CI to verify registry signatures and provenance attestations.
  3. Add a script that checks each new dependency and import against the npm registry for existence, age, downloads and lookalike names.
  4. Wire that script into a pre-commit hook with husky so unverified packages never land in a commit.
  5. Harden your package manager with a release-age delay and disabled install scripts.

What is slopsquatting and why does it work?

Slopsquatting is the registration of package names that LLMs hallucinate, so that AI-generated install commands pull attacker-controlled code. It works because the hallucinations are repeatable, which makes them predictable targets.

The term comes from Seth Larson of the Python Software Foundation. The numbers come from a USENIX Security 2025 study that generated 576,000 code samples across 16 models: roughly 19.7% of recommended packages did not exist, giving over 205,000 unique fake names. Commercial models hallucinated about 5% of the time, open source models about 21%. The part that matters: 43% of hallucinated names reappeared in all ten reruns of the same prompt. An attacker only needs to run popular prompts, collect the recurring names and publish them.

This is not theoretical. A Lasso Security researcher noticed models repeatedly recommending a non-existent huggingface-cli package, registered an empty one, and logged more than 30,000 downloads in three months. It was harmless. The next one will not be.

Agentic tools make it worse, because the install happens without you reading the name. If you lean on an agent (I do, see our Claude Code vs Cursor comparison), the review step you used to do with your eyes has to move into tooling.

terminal npm install
terminal npm install

Step 1: Wrap installs with socket.dev

Use Socket's CLI as a wrapper around npm so every install is scanned for malware, install scripts and typosquats before anything executes. It catches behaviour, not just known CVEs, which is exactly what a three-day-old malicious package needs.

npm install -g socket
socket npm install some-package

When a package looks wrong (new maintainer, obfuscated code, network access in a postinstall, a name one character off a popular one) Socket stops and asks before proceeding. Alias it if you want the protection without the typing:

alias npm="socket npm"
alias npx="socket npx"

Also install the Socket GitHub app on the repository. It is free for open source and comments on any pull request that adds a suspicious dependency, which covers teammates who skipped the alias. There is a VS Code extension that scores imports inline as well, useful when an assistant is autocompleting import lines for you.

Step 2: Does npm audit signatures catch hallucinated packages?

No. npm audit signatures proves that the tarballs you installed are the ones the registry published, and that provenance attestations are valid. It does not tell you whether the package should exist in the first place.

Run it anyway, because it closes a different hole: tampered tarballs and mirror substitution.

npm ci
npm audit signatures

The docs don't spell this out, but a malicious slopsquatted package passes this check happily. It was published to the real registry, so the registry signed it. What you do get is a count of packages with verified provenance attestations, and that is a useful signal: a dependency that claims to be an official SDK but has no provenance linking it to the vendor's repository deserves a second look.

Put both commands in CI before your build step. If you deploy through Vercel or Netlify, remember the build environment holds deploy tokens and API keys, which is precisely what install-time malware goes looking for. Fail the pipeline before the build, not after.

Step 3: Write the dependency verification script

This script blocks a commit if any new dependency or bare import does not exist on npm, was first published under 30 days ago, has under 1,000 weekly downloads, or sits within a couple of edits of a popular package name. It needs Node 18+ and zero dependencies, which feels appropriate.

Save it as scripts/verify-deps.mjs:

#!/usr/bin/env node
import { execFileSync } from 'node:child_process';
import { builtinModules } from 'node:module';

const POPULAR = ['react', 'react-dom', 'lodash', 'axios', 'express', 'vite', 'vitest', 'zod', 'zustand', 'tailwindcss', 'typescript', 'date-fns'];
const ALLOW = new Set(['preact']);
const MIN_AGE_DAYS = 30;
const MIN_WEEKLY_DOWNLOADS = 1000;
const SKIP = /^(\.|\/|~|#|@\/|node:|virtual:)/;
const IMPORT_RE = /(?:from\s*|import\s*\(?\s*|require\s*\(\s*)['"]([^'"\s]+)['"]/g;

const git = (...args) => execFileSync('git', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
const depsOf = (ref) => {
  try {
    const pkg = JSON.parse(git('show', `${ref}:package.json`));
    return new Set(Object.keys({ ...pkg.dependencies, ...pkg.devDependencies }));
  } catch {
    return new Set();
  }
};
const pkgName = (spec) => spec.split('/').slice(0, spec.startsWith('@') ? 2 : 1).join('/');

const known = depsOf('HEAD');
const candidates = depsOf('');

const files = git('diff', '--cached', '--name-only', '--diff-filter=ACM')
  .split('\n')
  .filter((f) => /\.(m?[jt]sx?)$/.test(f));
for (const file of files) {
  for (const [, spec] of git('show', `:${file}`).matchAll(IMPORT_RE)) {
    if (!SKIP.test(spec) && !builtinModules.includes(spec)) candidates.add(pkgName(spec));
  }
}

const lev = (a, b) => {
  const row = Array.from({ length: b.length + 1 }, (_, i) => i);
  for (let i = 1; i <= a.length; i++) {
    let prev = row[0];
    row[0] = i;
    for (let j = 1; j <= b.length; j++) {
      const tmp = row[j];
      row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
      prev = tmp;
    }
  }
  return row[b.length];
};

async function check(name) {
  const res = await fetch(`https://registry.npmjs.org/${name.replace('/', '%2f')}`);
  if (res.status === 404) return 'does not exist on npm (hallucinated?)';
  if (!res.ok) return `registry returned ${res.status}`;
  const meta = await res.json();
  const ageDays = (Date.now() - new Date(meta.time.created)) / 864e5;
  if (ageDays < MIN_AGE_DAYS) return `first published ${Math.floor(ageDays)} days ago`;
  const dl = await fetch(`https://api.npmjs.org/downloads/point/last-week/${name}`).then((r) => r.json());
  if ((dl.downloads ?? 0) < MIN_WEEKLY_DOWNLOADS) return `only ${dl.downloads ?? 0} downloads last week`;
  const twin = POPULAR.find((p) => lev(p, name) <= (p.length > 5 ? 2 : 1));
  if (twin && !POPULAR.includes(name)) return `looks like a typosquat of ${twin}`;
  return null;
}

const problems = [];
for (const name of candidates) {
  if (known.has(name) || ALLOW.has(name)) continue;
  const reason = await check(name);
  if (reason) problems.push(`  ${name}: ${reason}`);
}
if (problems.length) {
  console.error(`Blocked: unverified dependencies\n${problems.join('\n')}`);
  process.exit(1);
}

How it works: git show :package.json reads the staged manifest, git show HEAD:package.json reads the committed one, and anything already committed is trusted. Staged source files are scanned for bare import specifiers too, so an import the assistant wrote without adding to the manifest still gets checked.

Three things to tune before you rely on it:

  • POPULAR: replace my list with the packages your project actually uses. Lookalike detection is only as good as this list.
  • ALLOW: legitimate near-misses (preact is one edit from react), internal workspace package names and anything niche you have vetted by hand go here.
  • SKIP: add your own path aliases. If your tsconfig maps components/* without a prefix, the script will think components is a package. This one will cost you twenty minutes of confusion if you forget.

In a monorepo it reads the root package.json only. Run it per workspace or extend depsOf to merge manifests.

code editor git commit
code editor git commit

Step 4: Wire it into a pre-commit hook

Use husky to run the script on every commit. Three commands:

npm install --save-dev husky
npx husky init
echo "node scripts/verify-deps.mjs" > .husky/pre-commit

Commits that touch no dependencies make zero network calls, so the hook is effectively free day to day. When the registry is down or you are on a train, git commit --no-verify gets you past it. That escape hatch is the reason to run the same script in CI as well: local hooks are a convenience, CI is the enforcement.

Step 5: Harden the package manager

Make the package manager refuse fresh releases and install scripts by default. Most malicious packages are pulled within days, so a delay alone removes a large share of the risk.

For npm, disable lifecycle scripts project-wide:

echo "ignore-scripts=true" >> .npmrc

pnpm 10 already blocks dependency install scripts unless you allow them, and recent versions add a release-age gate in pnpm-workspace.yaml:

minimumReleaseAge: 10080

That is seven days in minutes. It is one of the better reasons to pick pnpm that never shows up in speed charts; our pnpm vs Bun vs npm benchmark covers the rest.

Should you trust package names from AI assistants at all?

Trust them the way you trust a Stack Overflow answer from 2014: probably right, verify before running. Well-known packages are almost always named correctly. The danger zone is the long tail, where the model stitches a plausible name together from fragments.

The red flags are consistent. A name that reads like a description (react-auth-session-manager), a package you have never seen for a job you thought the framework handled, or an install command the agent ran without mentioning it. If the name is new to you, open its npm page before installing. Ten seconds.

My recommendation: do all five steps, but if you only do one, do the pre-commit script plus its CI twin. Socket is the better detector, yet a hard gate you own, with thresholds you chose, is what stops the 2am commit.

FAQs

What is the difference between slopsquatting and typosquatting?

Typosquatting relies on a human mistyping a real package name, such as lodahs for lodash. Slopsquatting relies on an AI model inventing a name that never existed, which an attacker then registers. The payloads are the same; the source of the wrong name is different.

How often do AI coding assistants hallucinate npm packages?

A 2025 USENIX Security study found about 19.7% of package recommendations across 16 models pointed at non-existent packages, with commercial models near 5% and open source models near 21%. Rates vary by model and prompt, but 43% of hallucinated names repeated on every rerun, which is what makes them exploitable.

Does npm audit detect malicious or fake packages?

Not reliably. npm audit reports known advisories, so a freshly published malicious package has none, and npm audit signatures only confirms the tarball matches what the registry published. Use a behavioural scanner like Socket and an existence, age and popularity check alongside them.

Is socket.dev free for open source projects?

Yes. The Socket GitHub app and CLI are free for open source repositories, with paid plans for private repositories and team features. The CLI wrapper works locally without the GitHub app.

Can a lockfile protect me from slopsquatting?

Only after the fact. A lockfile pins whatever you installed, so if the first install was a slopsquatted package, the lockfile faithfully pins the malware. Verification has to happen before the dependency is added, which is what the pre-commit hook is for.

H
Hiten

Senior frontend engineer and architect: 17 years shipping complex web platforms, plus Android and iOS apps for clients. More at hiten.dev