Typosquatting is a package published under a name that looks almost identical to a popular package, so a single mistyped install or a careless copy-paste pulls attacker code instead of the real thing. The tricks are small, which is what makes them work. A swapped letter, a missing hyphen, a homoglyph, a different word order, or a popular name with a plausible suffix is enough, and the malicious package often copies the real README so a quick glance shows nothing wrong. Defense combines similarity detection before install, publisher verification at install time, and monitoring after the fact, because no single check catches every variant.
Quick Workflow
- List every dependency, direct and transitive, from the lockfile, not from memory or from the manifest alone.
- For each dependency, check name similarity against the registry for near-miss names that could be confused with it.
- Verify the publisher and provenance of every new or changed package before it enters the build.
- Allowlist the exact packages and versions the project uses, and require review for anything outside the list.
- Review every lockfile diff in code review, treating a new package name as a security-relevant change, not a routine update.
- Monitor the registries continuously for new packages similar to your most depended-on names.
- On finding a typosquat, remove it, check what it ran with access to, rotate exposed secrets, and report it to the registry.
1. Name similarity detection
Similarity is measurable, so automate it instead of eyeballing names. Edit distance catches transpositions and single-character changes, while a curated list of common tricks catches the cases edit distance misses, such as hyphen removal, suffix additions, and word reordering.
# List all dependencies from the lockfile, the ground truth
jq -r '.packages | keys[]' package-lock.json | grep "^node_modules/" | sed 's|^node_modules/||'
jq -r '.packages | keys[]' package-lock.json | grep -v "^node_modules/" || true
pip freeze | cut -d= -f1
# Check whether near-miss names exist on the public registry
npm view lodahs versions 2>/dev/null && echo "NEAR-MISS EXISTS - lodahs"
npm view loadash versions 2>/dev/null && echo "NEAR-MISS EXISTS - loadash"
npm view react-dom2 versions 2>/dev/null && echo "NEAR-MISS EXISTS - react-dom2"
pip index versions requestes 2>/dev/null
pip index versions reqeusts 2>/dev/null
# similarity_scan.py - flag registry candidates close to real dependencies
import difflib
import json
import subprocess
# Real dependencies, taken from the project lockfile
with open("package-lock.json", encoding="utf-8") as fh:
lock = json.load(fh)
real = sorted({k.replace("node_modules/", "") for k in lock["packages"] if k.startswith("node_modules/")})
# Candidates to check, supplied by a registry search or a monitoring feed
candidates = ["lodahs", "loadash", "react-dom2", "expresss", "axioss"]
for candidate in candidates:
close = difflib.get_close_matches(candidate, real, n=3, cutoff=0.8)
if close:
print(f"SUSPECT - {candidate} is close to {close}")
# Direct check for one dependency and its common typo variants
target = "requests"
variants = ["requestes", "reqeusts", "request", "requestss"]
for variant in variants:
ratio = difflib.SequenceMatcher(None, target, variant).ratio()
if ratio >= 0.8:
print(f"TYPO VARIANT - {variant} similarity {ratio:.2f} to {target}")
A similarity flag is a prompt for human review, not an automatic verdict. Common words legitimately resemble each other, and blocking on similarity alone creates false positives that teach developers to ignore the check.
2. Publisher verification and provenance
A correct name with the wrong publisher is still the wrong package. Check who published the version you are about to install, when the account was created, whether the package is signed or attested, and whether the version history looks like a real project or a single upload designed to be installed once.
# Inspect the publisher and history of a package before installing it
npm view lodash maintainers
npm view lodash time
npm view lodash dist.tarball
# Compare the suspicious package against the real one side by side
npm view lodahs maintainers 2>/dev/null || echo "no such package or no access"
npm view lodash versions --json | tail -20
# Check provenance attestations where the registry provides them
npm view lodash dist.attestations 2>/dev/null || echo "no attestations published"
# Python - check project metadata, homepage, and release history
pip index versions requests
curl -s https://pypi.org/pypi/requests/json | jq '.info | {author, home_page, project_urls}'
curl -s https://pypi.org/pypi/requestes/json | jq '.info | {author, home_page, summary}'
# Reject packages with no verifiable publisher in CI policy, and
# require provenance for packages that handle credentials or crypto
Red flags that warrant a block pending review include a publisher account created days ago, a single version with no history, a README copied verbatim from a popular package, install scripts that reach the network or read environment variables, and a version number far higher than the real package, designed to win a resolver race.
3. Allowlisting and lockfile review
Allowlisting turns "any package that resolves" into "only packages we approved", which makes a typosquat fail closed instead of failing open. The lockfile is the enforcement point, because it records exactly what was installed, including transitive packages that nobody typed by hand.
# Review every lockfile diff before merging, and flag new names
git diff package-lock.json | grep '^+' | grep '"node_modules/' | head -40
git diff Pipfile.lock | grep -i '"name"' | head -40
# Verify installed packages match the lockfile, with no extras
npm ci --dry-run
pip install --dry-run -r requirements.txt 2>/dev/null || pip check
# Audit installed packages for known malicious or suspicious entries
npm audit
pip-audit -r requirements.txt
# Check install scripts, the most common typosquat payload carrier
jq -r '.packages[] | select(.hasInstallScript == true) | input' package-lock.json 2>/dev/null || true
grep -rn "preinstall\|postinstall" package.json packages/*/package.json
# Example allowlist check - every installed name must appear here
comm -23 <(jq -r '.packages | keys[]' package-lock.json | sed 's|^node_modules/||' | grep -v '^$' | sort -u) <(sort approved-packages.txt)
An allowlist that nobody maintains becomes a rubber stamp, so review it on the same cadence as dependency updates, remove packages that are no longer used, and record who approved each addition and why.
4. Continuous monitoring for lookalike packages
Typosquats appear after you have already audited, so monitoring must run on a schedule. Monitor your most depended-on names, the names your developers type most often, and any name that has already been targeted once, since attackers revisit successful targets with new variants.
# Scheduled check - look for new near-miss packages for top dependencies
for name in lodash react express axios requests django flask; do
echo "--- checking variants of $name ---"
npm view "${name}s" versions 2>/dev/null | head -3
npm view "${name}-js" versions 2>/dev/null | head -3
done
# Watch registry feeds and advisories for malicious package reports
# npm advisories, PyPI safety notices, and the osv.dev database all
# publish typosquat takedowns, and your monitoring should ingest them
curl -s "https://api.osv.dev/v1/query" -H "Content-Type: application/json" -d '{"package": {"name": "lodahs", "ecosystem": "npm"}}' | jq .
# When a typosquat is confirmed, remove it and check the blast radius
npm uninstall lodahs
pip uninstall -y requestes
grep -rn "lodahs\|requestes" package.json package-lock.json requirements.txt
# Then rotate any secret the build or install could reach, and
# report the package to the registry for takedown
Monitoring without a response runbook just produces alerts that get ignored. Define in advance who removes the package, who checks build logs for its execution, and who files the registry report, so the first real hit is handled in hours, not weeks.
Edge cases
- Scoped packages are not immune. A scoped name can still be typosquatted at the scope level, and an unscoped lookalike of a scoped package can fool a developer who drops the scope while typing. Monitor scope variants as well as package names.
- Homoglyphs and Unicode tricks. A Cyrillic letter can look identical to a Latin one while being a different package name. Flag any dependency name containing non-ASCII characters for manual review, since legitimate package names are almost always plain ASCII.
- Legitimate forks and similarly named projects. A fork, a community continuation, or a coincidental name collision is not automatically malicious. Publisher history and code comparison decide, not similarity alone.
- Transitive typosquats. The malicious package may enter through a dependency of a dependency, where nobody typed its name at all. Lockfile review and install auditing must cover the full tree, not just direct dependencies.
- Private registry mirrors. A typosquat that reaches a private mirror through upstream syncing is then served as trusted. Mirror only approved packages, or scan mirrored packages on sync, rather than mirroring a public registry wholesale.
- Version confusion layered on typosquatting. A typosquat with a very high version number can also win resolver races against the real package. Version anomalies are a detection signal in their own right, even for correctly spelled names.
Key references
- npm documentation on package security and provenance (docs.npmjs.com)
- PyPI documentation on package verification (pypi.org)
- OSV database for malicious package reports (osv.dev)
- GuardDog and package malware scanning research (DataDog Security Labs)
- Socket.dev malicious package reports (socket.dev)
- OWASP Software Supply Chain Security guidance
- CISA software supply chain attack guidance (cisa.gov)
- Phylum research on typosquatting campaigns (phylum.io)
