How I detect typosquatting attacks before npm install runs
Source: Dev.to
Introduction
Last week I published Sapo, a pre‑install security scanner. Today I’ll show how it detects one of the most common attacks: typosquatting.
What is typosquatting?
Attackers register packages with names similar to popular ones, e.g.:
lodahsinstead oflodashaxoisinstead ofaxiosreacctinstead ofreactexpresssinstead ofexpress
These fake packages often depend on the real package (so everything seems to work) and add malicious code that steals credentials.
Detection logic
1. Similarity check
Sapo calculates how “close” the requested package name is to known popular packages using the Levenshtein distance:
fn levenshtein_distance(a: &str, b: &str) -> usize {
// Returns the number of single‑character edits needed
// to transform string a into string b
}
If the distance is 1–2 characters, the name is considered suspicious.
2. Common typo patterns
Sapo looks for patterns humans actually make:
- Transposed letters:
axois→axios - Missing letters:
expres→express - Double letters:
expresss→express - Adjacent keyboard keys:
reacy→react
3. Popularity comparison
A key insight is the download‑ratio mismatch:
- Target package: 47 downloads
- Similar popular package: 40 million+ downloads
- Recent creation date
Such a disparity strongly indicates a malicious package.
Example run
$ npm install lodahs
[>] Scanning: lodahs@1.0.0
[!] BLOCKED: Typosquatting detected
Similar to: lodash
- lodash: 337,000,000 downloads
- lodahs: 47 downloads
- Levenshtein distance: 1
Installation cancelled.
The real lodash has 337 million downloads, while the fake lodahs has only 47—a massive red flag.
How Sapo works
Sapo intercepts the command before npm starts downloading:
You type: npm install lodahs
↓
Sapo intercepts
↓
API check: is "lodahs" safe?
↓
Response: TYPOSQUATTING DETECTED
↓
Installation blocked
↓
npm never runs
Your machine stays clean.
Installation
curl -fsSL https://sapo.salta.world/install.sh | bash
After restarting the terminal, try:
npm install lodahs
You’ll see the warning before anything gets installed.
Future work
- ML‑based anomaly detection
- Sandbox analysis
- VS Code extension
If you have ideas for what to detect next, let me know in the comments!
Links
- GitHub: https://github.com/Salta1414/sapo-cli
- Website: https://sapo.salta.world