How I detect typosquatting attacks before npm install runs
Last week I published Sapo, a pre-install security scanner. Today I want to show you exactly HOW it detects one of the most common attacks: typosquatting.
What is typosquatting?
You want to install lodash. You type fast. You accidentally type lodahs.
Congratulations, you just installed malware.
Attackers register packages with names similar to popular ones:
-
lodahsinstead oflodash -
axoisinstead ofaxios -
reacctinstead ofreact -
expresssinstead ofexpress
These fake packages often contain the REAL package as a dependency (so everything seems to work), plus a little extra code that steals your credentials.
The detection algorithm
Here's the actual logic Sapo uses:
1. Levenshtein Distance
First, we calculate how "close" the package name is to known popular packages:
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, that's suspicious.
2. Common typo patterns
We check 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
Here's the key insight:
If you're trying to install a package with:
- 47 downloads
- Name similar to a package with 40 million downloads
- Created last week
That's almost certainly malicious.
Example detection
$ 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. The fake lodahs has 47.
That ratio is a massive red flag.
Why pre-install matters
Most security tools scan AFTER installation. But by then, the postinstall script has already run.
Sapo intercepts the command BEFORE npm even 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.
Try it yourself
# Install
curl -fsSL https://sapo.salta.world/install.sh | bash
# Restart terminal, then try:
npm install lodahs
You'll see the warning before anything gets installed.
What's next?
I'm working on:
- ML-based anomaly detection
- Sandbox analysis
- VS Code extension
If you have ideas for what to detect next, let me know in the comments!
GitHub: github.com/Salta1414/sapo-cli
Website: sapo.salta.world
Top comments (0)