How-To Guide

How to Detect Typosquatted Packages in CI

Catch typosquatted and malicious dependencies in CI with name-similarity checks, allow-lists, lockfile review and install-script blocking.

On this page

  1. Introduction
  2. The Anatomy of a Typosquat
  3. Allow-Listing Dependencies
  4. Name-Similarity Screening
  5. Blocking Install Scripts
  6. Lockfile Review and Integrity
  7. Monitoring and Incident Response
  8. Common Pitfalls and Conclusion

Introduction

Typosquatting is a supply-chain attack that relies on a human misreading a package name. An attacker publishes lodahs, crossenv or a package one character away from a popular one, and a developer who mistypes the install command, or an autocomplete that picks the wrong suggestion, pulls the malicious package. The code then runs with the developer’s or the build’s privileges. Because the typo is invisible at a glance, the defence has to be automated: compare new dependency names against known-good names, allow-list what your project uses, and block the install-time scripts that malicious packages rely on.

The Anatomy of a Typosquat

Attackers use several tricks. A homoglyph swap replaces a character with a look-alike, such as a Cyrillic a or the digit 1 for a letter l. A transposition swaps two adjacent characters. A separator change moves or removes a hyphen. A scope or prefix is added or removed, such as @scope/pkg versus pkg. A pluralisation adds or drops an s. Each exploits a human failing to notice a one-character difference.

The malicious package usually carries an install script that runs on installation, which is when the attacker’s code executes, before any of your code imports the package. Blocking install scripts and reviewing the postinstall behaviour is therefore central to the defence, because many attacks depend on that automatic execution.

# common typosquat patterns
homoglyph     lodash  -> l0dash / 1odash / lодаsh (Cyrillic o)
transposition lodash  -> lodsha
separator     cross-env -> crossenv
scope tricks  @scope/pkg -> scope-pkg / @scope/pkg-extra
pluralisation express -> expresses
# most carry a postinstall script that runs the payload

Allow-Listing Dependencies

The strongest defence is an explicit allow-list: the build may install only packages on the list, and adding a package requires review. A typo cannot sneak in, because the mistyped name is not on the list and the install fails. This is the same principle as an allow-list for executable actions, applied to the dependency graph.

For ecosystems and teams where a full allow-list is impractical, allow-list the direct dependencies and verify the transitive tree by lockfile review and integrity. The point is to make the set of installable packages finite and known, rather than whatever the resolver happens to find.

# allow-list gate in CI
allowed = read("allowed-packages.txt")     # one name per line
for pkg in lockfile.packages():
  if pkg not in allowed:
    fail("package not in allow-list: " + pkg)
# adding a dependency => PR that updates allowed-packages.txt, reviewed

Name-Similarity Screening

Before a new dependency is accepted, screen its name against the names of the most popular packages in the ecosystem. Compute the edit distance and flag anything within one or two edits of a popular name, or matching a known homoglyph substitution. A flagged name gets human review rather than automatic acceptance.

Normalise before comparing so homoglyphs and separators do not hide a match: transliterate look-alikes to ASCII, lowercase, and strip separators. Then compare edit distance on the normalised forms. A candidate that normalises to within one edit of a top-1000 package name is worth a second look.

import unicodedata, re

def normalise(name: str) -> str:
    # transliterate look-alikes to ASCII, drop separators, lowercase
    s = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode()
    return re.sub(r"[-_.]", "", s).lower()

def levenshtein(a: str, b: str) -> int:
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
        prev = cur
    return prev[-1]

def suspicious(name: str, popular: list[str], max_distance: int = 1) -> list[str]:
    n = normalise(name)
    return [p for p in popular if 0 < levenshtein(n, normalise(p)) <= max_distance]

Blocking Install Scripts

Many malicious packages execute their payload in a postinstall script. Block install scripts where the package manager supports it, and allow them only for packages that genuinely need a build step, reviewed explicitly. This removes the automatic execution that most typosquats depend on.

Where scripts must run, sandbox the install: no network except the registry, no production secrets, a writable temp directory only. A build that installs dependencies with no privileges beyond what the build needs converts a successful typosquat from a breach into a failed script. This is the same least-privilege discipline used for builds generally.

# npm: ignore lifecycle scripts by default, allow-list exceptions.
npm ci --ignore-scripts

# where a package truly needs a build step, allow only it:
# .npmrc
ignore-scripts=true
# and run the approved build step explicitly in a sandboxed stage

# pnpm 10+: scripts are blocked unless allow-listed in pnpm-workspace.yaml

Lockfile Review and Integrity

The lockfile is where a new package appears, so review its diff. A PR that adds a dependency should show the new package, its version, its resolved URL and its integrity hash; a surprising transitive addition is a red flag. Require review of lockfile changes rather than letting the resolver update it silently.

Pin integrity hashes so a swapped artifact fails to install, and pin the registry so a package cannot be redirected. Integrity checking catches substitution after resolution, which is the complement to name screening before resolution. Together they cover the name and the artifact.

# Review the lockfile diff on every dependency change.
git diff --stat package-lock.json pnpm-lock.yaml yarn.lock
# a new transitive package with no obvious parent is worth a look
# integrity hashes in the lockfile make a swapped tarball fail to install
npm ci --ignore-scripts   # installs exactly the lockfile, verified

Monitoring and Incident Response

Subscribe to advisories for the ecosystems you use and watch for takeovers: a package gaining a new maintainer, a sudden major version, a new install script. A previously trusted package that changes behaviour is as dangerous as a fake one. Emit a diff of your dependency tree between builds so an unexpected change is visible.

Have a plan for what to do when a dependency is compromised: identify which builds and deployments included it, rotate any secrets that were present in those environments, and pin a known-good version or remove the dependency. Because install scripts run in the build, rotate build-visible credentials first.

# dependency-change signals worth alerting on
[ ] new maintainer on a package you depend on
[ ] a new postinstall/preinstall script appears
[ ] a major version bump with no changelog
[ ] a transitive dependency appears with no parent change
[ ] the resolved registry/URL for a package changes
# incident: rotate build-visible secrets FIRST, then pin/remove

Common Pitfalls and Conclusion

Do not rely on developers noticing a typo; the whole point is that it is easy to miss. Do not allow-list only direct dependencies and ignore the transitive tree. Do not enable install scripts by default. Do not accept a lockfile change without review. And do not assume a popular package is safe forever; takeovers turn good packages malicious.

Typosquatting exploits a single misread character, so the defence must be mechanical: allow-list installable packages, screen new names for similarity to popular ones, block install scripts, review lockfile diffs, verify integrity, and monitor for takeovers. Layered this way, a typo cannot install, a malicious script cannot run, and a compromised dependency is detected rather than trusted.

Sources: OWASP: Vulnerable and outdated components, npm: npm ci and –ignore-scripts, GitHub Advisory Database.

FAQ

Why block install scripts?
Because malicious packages usually run their payload in a postinstall script, before your code imports them. Blocking scripts by default removes the automatic execution the attack depends on; allow them only for packages that genuinely need a build step.
What similarity threshold should I use?
Flag names within one edit of a popular package name after normalising homoglyphs and separators. One edit catches the common typos while keeping the review queue small; tighten or loosen based on how many false positives you see.

Related Examples