TRENDING
Row of white terraced houses on a green hillside in County Donegal, identical except for their front doors, which are yellow, red and pale blue
November 24, 2026
How to Stop pip From Installing a Typosquatted or Made-Up Package Name: Build a Name Gate in Python and Measure It on the 15,000 Most Downloaded PyPI Projects and 12,067 Names From OSSF’s Malicious-Package Reports
Close-up of the cutting teeth of a paper shredder packed with shredded paper and colored scraps
November 24, 2026
Dragos’s Canaries Turn AI-Router Privacy Flags Into a Measurement, and OpenRouter’s Public ZDR List Shows the Label Sat on the MiniMax and Phala Routes Through October, Its 125 Removals Reproduce as Eight Providers’ Entire Lists, and the Post Later Dropped Its Vercel and OpenRouter Example
Antique surgeon’s bone saw with a black grip and a long serrated steel blade on a pale grey background
November 24, 2026
Google Says a Suspected China-Nexus Group Exploited the vCenter Authentication Bypass in Early September, About Ten Weeks Before the Patch, but Broadcom’s Advisory Never Says It Was Exploited, the July Claim Rests on a Modifiable Build Timestamp, and the CVE Record Omits vCenter 7.0
A chalkboard covered with handwritten equations and a boxed inequality, standing for a mathematical proof
November 24, 2026
How to Prove a Rust Function Correct With Verus: Write a Spec, Read the Prover’s Errors, and Find the Bugs Tests Miss
Wooden folding rule showing a Burgos-inch scale above a centimetre scale, resting on a stone beside a lake
November 24, 2026
OpenAI’s Perplexity Proposal Turns One Internal Chart Into a Candidate Industry Limit, but Its “Cybersecurity Expert” Label Sits at 0.828, Not Below 0.8, the Millennium Prize Label Rides a November Release for a September Result, and on Open Models Per-Token Loss Hides a 2.25x Compression Gap
24 Nov 2026
SXZ.io SXZ.io
  • Home
Search the Site
Popular Searches:
Technology Amazon AI
Recent Posts
A black missile-shaped test model mounted on a support strut inside a large concrete wind tunnel test section, with a perforated wall on the left
How to Test Kubernetes Admission Policies Without a Cluster: Write Kyverno ValidatingPolicies, Prove Them With kyverno test, and Gate Pull Requests in CI
November 23, 2026
Several small yellow spirit-level bubble vials on a camera tripod head and a base plate, each bubble resting near the center
DeepMind’s Quantum Agents Make Lean the Referee and the Headline Ratios Reproduce From the Released Files, but 260x of the Arcsin 290x Came From a Stage Classical Simulation Could Check, the 8x and 2.5x Use Refined Baselines, and the Fusion and Grover Figures Moved Between arXiv Versions
November 23, 2026
Rows of open sluice gates on a weir with water flowing through them, in Rožmitál pod Třemšínem, Czech Republic
Norway’s National Security Authority Tells Every Azure API Management Customer to Assume Secrets Are Out, Microsoft’s Private Notice Limits Exposure to Classic Tiers That Skipped Its Guidance, and No CVE or Public Advisory Says What the Flaw Is
November 23, 2026
SXZ.io SXZ.io
  • Home

Categories

Articles 313 Posts
News 319 Posts
Learning Hub 285 Posts
Home/Learning Hub/How to Stop pip From Installing a Typosquatted or Made-Up Package Name: Build a Name Gate in Python and Measure It on the 15,000 Most Downloaded PyPI Projects and 12,067 Names From OSSF’s Malicious-Package Reports
Learning Hub

How to Stop pip From Installing a Typosquatted or Made-Up Package Name: Build a Name Gate in Python and Measure It on the 15,000 Most Downloaded PyPI Projects and 12,067 Names From OSSF’s Malicious-Package Reports

Build a Python gate that reads a requirements file and allows, reviews or blocks each package name, then measure it on 15,000 popular PyPI names and 12,067 malicious-package reports, compare it with...

November 23, 2026 50 Min Read
18

When you type pip install followed by a name, you hand that name to a program that will fetch whatever the package index says the name is. Two kinds of bad names matter. A typosquatted name is a look-alike that someone registered on purpose, such as a popular project with two letters swapped. A made-up name is one that nobody had registered until an AI assistant suggested it; if someone registers it afterwards, the next person who trusts the assistant installs it. A 2024 research paper that generated 576,000 code samples with 16 popular code-generation models reported that “the average percentage of hallucinated packages is at least 5.2% for commercial models and 21.7% for open-source models”. Step 11 of this tutorial repeats a very small version of that experiment on your own machine.

Table Of Content

  • The ideas you need before you write any code
  • Prerequisites
  • Step 0: Set up the project
  • Step 1: Fold a name the way PyPI does
  • Step 2: Read what PyPI already checks
  • Step 3: Download the two data sets
  • Step 4: Count the edits between two names
  • Step 5: Turn the checks into two rules
  • Step 6: Measure the rules on real names
  • What the main table says
  • How long should the protected list be?
  • Does the edit rule work for short names?
  • The honest summary
  • Step 7: Make the lookup fast
  • Step 8: Ask PyPI whether the name exists and how old it is
  • Step 9: Work out what an alert means
  • Step 10: Assemble the gate
  • The policy and the code
  • Try the policy on seven made-up situations
  • Run it on a requirements file
  • Check everything pip would install
  • Step 11: Ask small local models for package names
  • What came out
  • Step 12: Test the gate, then plant bugs to see if the tests notice
  • Plant bugs to see whether the tests notice
  • Put the gate where the install happens
  • Common mistakes
  • What this gate cannot do
  • Where to go next
  • Sources and method

By the end you will have a small Python tool, gate.py, that reads a requirements file and prints allow, review or block for every package name, with the reason. You will also have measured what such a gate can and cannot do, using two public data sets: the 15,000 most downloaded PyPI projects, and 12,067 package names from the Open Source Security Foundation’s malicious-package reports. The measurements are the honest part of the tutorial. Spoiler: names that look like popular projects are a small share of the malicious names, and that tells you how to use the gate.

No security background is assumed. If you can read a short Python function, you can follow along. Every step gives you the code, the output to expect, and a plain explanation of what the code does and why it is written that way.

The ideas you need before you write any code

A package index is the server that pip downloads from; here that is PyPI, the Python Package Index. Every package on it is a project with a name. A requirement is a line such as requests==2.34.2 in a requirements file: a name, and usually a version rule.

Normalization is the rule that makes different spellings of a name mean the same project. The Python Packaging User Guide defines it as lower-casing the name and replacing every run of dots, hyphens and underscores with a single hyphen, so Flask_Login and flask.login are one project. Step 1 turns that rule into code.

Typosquatting is registering a name that is one slip away from a popular one, hoping that people mistype it. An edit is one change to a string: inserting a character, deleting one, replacing one, or swapping two neighbours. The edit distance between two names is the smallest number of edits that turns one into the other. requests and reqeusts are one edit apart (a swap), and that is exactly the slip a typist makes.

Last, two words from testing. A false alarm (a false positive) is a harmless name the gate flags. A miss (a false negative) is a bad name it lets through. A gate that is wrong in both directions is normal; the useful question is how often, and what you do about it. Step 9 puts numbers on it.

Prerequisites

  • Operating system: I ran everything on Windows 11. The code is portable Python; only the command that activates the virtual environment differs on macOS and Linux.
  • Python: Python 3.13.14. I did not test other versions.
  • Packages: requests 2.34.2, packaging 26.3 and pytest 9.2.0. The optional rapidfuzz 3.14.6 adds one cross-check test that is skipped when it is missing.
  • Network: access to pypi.org, github.com, api.github.com and raw.githubusercontent.com. No account, token or API key is needed. GitHub limits anonymous API calls, and the lab makes about ten.
  • Optional for Step 11: Ollama 0.32.9 with the models qwen2.5:0.5b, qwen2.5:1.5b and qwen3.5:4b already pulled. Everything else works without it.
  • Time and disk: about two hours to read and type. Step 6 takes about 40 seconds and Step 11 about three minutes on my machine; the other scripts finish within about 20 seconds. The downloaded data is about 1.3 megabytes.
  • Knowledge: Python functions, lists, sets and dictionaries. Nothing about package managers or security is assumed.

Step 0: Set up the project

Create a folder and a virtual environment, then install the packages. The last command prints your Python version so you can compare it with mine.

mkdir namegate
cd namegate
python -m venv .venv
.venv\Scripts\activate
python -m pip install requests==2.34.2 packaging==26.3 pytest==9.2.0 rapidfuzz==3.14.6
python --version
Python 3.13.14

On macOS and Linux the activation line is source .venv/bin/activate. All files you create in the next steps go in this one folder, because the scripts import each other by name.

Step 1: Fold a name the way PyPI does

You will build names.py across three steps. Start with the top of the file: the imports, two functions that fold a name, and one constant you will use in Step 4. The first function is the normalization rule quoted above. The second, ultranormalize, reproduces a stronger fold that PyPI uses to refuse names that are “too similar”: it drops dots, underscores and hyphens, then turns the letters l and i into the digit 1 and the letter o into the digit 0. I copied that rule from PyPI’s own database migration in Step 2, so you can check it yourself.

"""names.py: write, fold and compare Python package names."""
import re

# Every character a normalized PyPI name can contain.
ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789-"

_RUN_OF_SEPARATORS = re.compile(r"[-_.]+")


def normalize(name):
    """PEP 503: each run of - _ . becomes one hyphen, then lower case."""
    return _RUN_OF_SEPARATORS.sub("-", name).lower()


def ultranormalize(name):
    """PyPI's ultranormalize_name(): drop - _ ., then l and i become 1 and o becomes 0."""
    folded = re.sub(r"[-_.]", "", name).lower()
    return folded.replace("l", "1").replace("i", "1").replace("o", "0")

Now see what the two folds do to some names. The second group holds toasting, the six look-alikes that PyPI’s own tests refuse when a project called toasting already exists, and one control, toasting2.

"""step01_normalize.py: the same project, written six ways."""
from names import normalize, ultranormalize

print("PEP 503 normalization:")
for raw in ["Flask_Login", "flask.login", "FLASK--LOGIN", "flask-login"]:
    print(f"  {raw:14} -> {normalize(raw)}")

print()
print("PyPI's stronger ultranormalize_name() fold:")
for raw in ["toasting", "toast1ng", "toastlng", "t0asting", "toast-ing", "toast.ing", "toast_ing", "toasting2"]:
    print(f"  {raw:11} -> normalize {normalize(raw):11} ultranormalize {ultranormalize(raw)}")
python step01_normalize.py
PEP 503 normalization:
  Flask_Login    -> flask-login
  flask.login    -> flask-login
  FLASK--LOGIN   -> flask-login
  flask-login    -> flask-login

PyPI's stronger ultranormalize_name() fold:
  toasting    -> normalize toasting    ultranormalize t0ast1ng
  toast1ng    -> normalize toast1ng    ultranormalize t0ast1ng
  toastlng    -> normalize toastlng    ultranormalize t0ast1ng
  t0asting    -> normalize t0asting    ultranormalize t0ast1ng
  toast-ing   -> normalize toast-ing   ultranormalize t0ast1ng
  toast.ing   -> normalize toast-ing   ultranormalize t0ast1ng
  toast_ing   -> normalize toast-ing   ultranormalize t0ast1ng
  toasting2   -> normalize toasting2   ultranormalize t0ast1ng2

Read the first group: four spellings, one normalized name. Read the second group: all seven spellings collapse to t0ast1ng under the stronger fold, while toasting2 stays different because it has a different last character. The point of the second fold is that toast1ng (a digit one) and toastlng (a lowercase L) look like toasting in many fonts. To verify this step, check that your output has the same eight ultranormalize values as above.

Step 2: Read what PyPI already checks

Before you build a gate, find out what the index does for you. The script below downloads five source files from the pypi/warehouse repository, which is the code that runs PyPI, at one pinned commit, and prints only the lines that matter. Pinning the commit means you read exactly what I read, and the script saves the files because Step 6 reuses one of them.

"""step02_pypi_source.py: read what PyPI itself checks when a new project name is created.

Fetches five files from pypi/warehouse at one pinned commit, saves them under
data/, and prints the lines that answer the question.
"""
import importlib.util
import pathlib
import re

import requests

COMMIT = "d8c20b4f6e01d096d803aa4c3cb7ac7fd089e353"
BASE = f"https://raw.githubusercontent.com/pypi/warehouse/{COMMIT}/"
FILES = {
    "project_utils": "warehouse/utils/project.py",
    "services": "warehouse/packaging/services.py",
    "tasks": "warehouse/packaging/tasks.py",
    "typosnyper": "warehouse/packaging/typosnyper.py",
    "ultranormalize": "warehouse/migrations/versions/d18d443f89f0_ultranormalize_name_function.py",
}
DATA = pathlib.Path(__file__).parent / "data"
DATA.mkdir(exist_ok=True)


def load(key):
    path = DATA / f"warehouse_{key}.py"
    if not path.exists():
        reply = requests.get(BASE + FILES[key], headers={"User-Agent": "name-gate-lab/1.0"}, timeout=60)
        reply.raise_for_status()
        path.write_bytes(reply.content)
    return path.read_text(encoding="utf-8").splitlines()


def show(lines, pattern, start=0, stop=None):
    for number, line in enumerate(lines, 1):
        if number > start and (stop is None or number < stop) and re.search(pattern, line):
            print(f"  {number:4}: {line.strip()}")


print("warehouse commit", COMMIT[:10])
print("\n1. Allowed characters (warehouse/utils/project.py)")
show(load("project_utils"), r"PROJECT_NAME_RE = |A-Z0-9._-")

services = load("services")
begin = next(i for i, l in enumerate(services, 1) if "def check_project_name" in l)
end = next(i for i, l in enumerate(services, 1) if "def create_project" in l)
print("\n2. Refused when the name is first created (services.py, check_project_name)")
show(services, r"raise ProjectNameUnavailable", begin, end)

print("\n3. The fold behind 'too similar' (migration d18d443f89f0)")
show(load("ultranormalize"), r"regexp_replace|'\(")

print("\n4. The typo checks (typosnyper.py)")
typo = load("typosnyper")
start = next(i for i, l in enumerate(typo, 1) if "for check in (" in l)
show(typo, r"^\s+_\w+,$", start, start + 8)
spec = importlib.util.spec_from_file_location("warehouse_typosnyper", DATA / "warehouse_typosnyper.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
print(f"  built-in popular list: {len(module._TOP_PROJECT_NAMES)} names")

print("\n5. What happens on a match (tasks.py, typo_check_project_name)")
show(load("tasks"), r"\.limit\(10000\)|top_dependents_corpus|typo_check_name\(|IsTypoSnyperMatch|record only")
python step02_pypi_source.py
warehouse commit d8c20b4f6e

1. Allowed characters (warehouse/utils/project.py)
    65: PROJECT_NAME_RE = re.compile(
    66: r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])\Z", re.IGNORECASE | re.ASCII

2. Refused when the name is first created (services.py, check_project_name)
   586: raise ProjectNameUnavailableInvalidError
   590: raise ProjectNameUnavailableStdlibError
   597: raise ProjectNameUnavailableExistingError(existing_project)
   604: raise ProjectNameUnavailableProhibitedError
   611: raise ProjectNameUnavailableSimilarError(similar_project_name)

3. The fold behind 'too similar' (migration d18d443f89f0)
    20: regexp_replace(
    21: regexp_replace(
    22: regexp_replace($1, '(\.|_|-)', '', 'ig'),
    23: '(l|L|i|I)', '1', 'ig'
    25: '(o|O)', '0', 'ig'

4. The typo checks (typosnyper.py)
   415: _repeated_characters,
   416: _omitted_characters,
   417: _swapped_characters,
   418: _swapped_words,
   419: _common_typos,
  built-in popular list: 200 names

5. What happens on a match (tasks.py, typo_check_project_name)
   358: def compute_top_dependents_corpus(request: Request) -> dict[str, int]:
   419: .limit(10000)
   429: cache_key = "top_dependents_corpus"
   431: logger.info("Stored `top_dependents_corpus` in query results cache.")
   459: corpus = request.find_service(IQueryResultsCache).get("top_dependents_corpus")
   460: typo_check_match = typo_check_name(canonicalize_name(project_name), corpus=corpus)
   473: # Annotate the project for admin review. This is a record only - the kind is
   478: kind=ObservationKind.IsTypoSnyperMatch,

Here is what each section tells you.

  • Section 1 is the pattern every project name must match. It allows only ASCII letters, digits, dots, underscores and hyphens (the re.ASCII flag matters), so the pattern does not accept Unicode look-alike letters. The look-alikes that do matter are the plain ASCII ones, such as l, 1 and i.
  • Section 2 lists the five reasons a new name can be refused: the name is invalid, it collides with a Python standard-library module, it already exists after normalization, it is on a prohibited list, or it is “too similar to an existing project”, as PyPI’s help page puts it.
  • Section 3 is the fold behind “too similar”: the same ultranormalize you wrote in Step 1. PyPI added that block in December 2021 (pull request 10498).
  • Section 4 lists five typo checks: repeated characters, omitted characters, swapped characters, swapped words and common keyboard typos. They compare a new name against a list of popular names.
  • Section 5 shows what happens on a match. The popular list is built by a query that ranks projects by how many other projects depend on them (the query ends with a limit of 10,000 names), and a match is recorded for review. A code comment calls it “a record only”, and the task’s own docstring says it works by “recording an observation and notifying admins for review when it looks like a typo”.

In plain words: PyPI refuses a short list of name collisions outright, but a typo-like name is allowed through and shown to human administrators afterwards. The typo checks arrived in March 2025 (pull request 17649) and were moved into a task that runs after the project is committed in August 2026 (pull request 20387); from the first version, a match was logged and the upload went on. Nothing in the project page that pip downloads reports the result: a live response for requests has only the fields files, meta, name, project-status and versions. That is the gap your gate fills on your side: it runs before you install, and it can look at the one thing the index cannot, which is what you are about to install.

Step 3: Download the two data sets

You need two lists of names. The first is a ranking of popular projects, the names worth protecting. The second is a list of names that were reported as malicious, to test the gate against. Both are pinned to a commit so your numbers match mine.

  • Popular names: the hugovk/top-pypi-packages repository, described as “A monthly dump of the 15,000 most-downloaded packages from PyPI”. I used the November 2026 update (data from 2026-11-01).
  • Reported names: the ossf/malicious-packages repository, “a collection of reports of malicious packages identified in Open Source package repositories”. It keeps one folder per package, so a single GitHub API call lists every PyPI name.
"""fetch_data.py: download the two public data sets the lab needs into data/.

Both are pinned to a commit, so the numbers in this article reproduce.

1. PyPI download ranking (hugovk/top-pypi-packages, the 2026-11 update).
2. The names of the PyPI packages in OSSF's malicious-packages repository
   (one directory per package under osv/malicious/pypi; one GitHub API call).
"""
import json
import pathlib

import requests

TOP_COMMIT = "29c0d4c38c28c0e6b99e73fa09cb91a2323ca51b"
OSSF_COMMIT = "76a57187b091b4cebcd717bceab76876b34dfe66"
DATA = pathlib.Path(__file__).parent / "data"
UA = {"User-Agent": "name-gate-lab/1.0"}


def main():
    DATA.mkdir(exist_ok=True)
    url = f"https://raw.githubusercontent.com/hugovk/top-pypi-packages/{TOP_COMMIT}/top-pypi-packages.min.json"
    top = requests.get(url, headers=UA, timeout=60)
    top.raise_for_status()
    (DATA / "top-pypi-packages.json").write_bytes(top.content)
    print("top list:", len(top.json()["rows"]), "rows, last_update", top.json()["last_update"])

    url = f"https://api.github.com/repos/ossf/malicious-packages/git/trees/{OSSF_COMMIT}:osv/malicious/pypi"
    tree = requests.get(url, headers=UA, timeout=120)
    tree.raise_for_status()
    t = tree.json()
    names = sorted(e["path"] for e in t["tree"] if e["type"] == "tree")
    (DATA / "ossf-pypi-names.json").write_text(
        json.dumps({"commit": OSSF_COMMIT, "names": names}), encoding="utf-8")
    print("OSSF names:", len(names), "truncated:", t.get("truncated"))


if __name__ == "__main__":
    main()
python fetch_data.py
top list: 15000 rows, last_update 2026-11-01 06:41:05
OSSF names: 12067 truncated: False

Now look at the data. The script prints the size of each list and checks which names appear on both.

"""step03_data.py: look at the two data sets, and at the names that are on both."""
import json
import pathlib

import requests

from names import normalize

HERE = pathlib.Path(__file__).parent
UA = {"User-Agent": "name-gate-lab/1.0"}

rows = json.loads((HERE / "data" / "top-pypi-packages.json").read_text(encoding="utf-8"))["rows"]
top = [normalize(r["project"]) for r in rows]
print(f"download ranking: {len(top)} projects, first five: {', '.join(top[:5])}")
print(f"  rank 1,000 is {top[999]}, rank 15,000 is {top[-1]}")

ossf = json.loads((HERE / "data" / "ossf-pypi-names.json").read_text(encoding="utf-8"))
originals = {normalize(n): n for n in ossf["names"]}
print(f"OSSF malicious-packages at {ossf['commit'][:10]}: {len(originals)} PyPI package names")
print("  a few of them:", ", ".join(sorted(originals)[600:604]))

both = sorted(set(originals) & set(top))
print(f"\n{len(both)} names are on both lists:")
cache = HERE / "data" / "ossf-overlap.json"
if cache.exists():
    records = json.loads(cache.read_text(encoding="utf-8"))
else:
    records = {}
    for name in both:
        url = f"https://api.github.com/repos/ossf/malicious-packages/contents/osv/malicious/pypi/{originals[name]}"
        listing = requests.get(url, params={"ref": ossf["commit"]}, headers=UA, timeout=60).json()
        records[name] = [requests.get(item["download_url"], headers=UA, timeout=60).json() for item in listing]
    cache.write_text(json.dumps(records), encoding="utf-8")
for name in both:
    for rec in records[name]:
        versions = [v for a in rec.get("affected", []) for v in a.get("versions", [])]
        shown = ", ".join(versions[:3]) + (" ..." if len(versions) > 3 else "") if versions else "no version list"
        print(f"  {name:16} {rec['id']}  versions: {shown}")
python step03_data.py
download ranking: 15000 projects, first five: boto3, packaging, typing-extensions, certifi, idna
  rank 1,000 is types-paramiko, rank 15,000 is asynckivy
OSSF malicious-packages at 76a57187b0: 12067 PyPI package names
  a few of them: bitcionlib, bitcoiinlib, bitcoilib, bitcoilnib

9 names are on both lists:
  agent-framework  MAL-2026-20101  versions: 1.26.2, 1.26.1
  durabletask      MAL-2026-4174  versions: 1.4.1, 1.4.2, 1.4.3
  elementary-data  MAL-2026-3083  versions: 0.23.3
  guardrails-ai    MAL-2026-3607  versions: 0.10.1
  lightning        MAL-2026-3201  versions: 2.6.2, 2.6.3
  litellm          MAL-2026-2144  versions: 1.82.7, 1.82.8, 1.107.0
  mistralai        MAL-2026-3608  versions: 2.4.6
  num2words        MAL-2025-6794  versions: 0.5.15, 0.5.16
  telnyx           MAL-2026-2254  versions: 4.87.1, 4.87.2

Nine names are on both lists. They are not look-alikes: they are real, popular projects, and each OSSF record lists specific malicious versions of them, such as litellm 1.82.7, 1.82.8 and 1.107.0. Those are compromised releases of genuine projects (we covered two of them: the poisoned LiteLLM 1.107.0 and Microsoft’s agent-framework), so a name check cannot help with them. I remove those nine names from the test set and call the remaining 12,058 the squat candidates. That label is deliberate: the OSSF repository collects reports, it is not a list that someone hand-labelled as typosquats, so many of the 12,058 are not typosquats at all.

Step 4: Count the edits between two names

Add two functions to names.py, below the ones from Step 1. The first, osa_distance, computes the edit distance. It builds a grid one row per character of a, where each cell holds the cheapest number of edits to turn the first few characters of a into the first few characters of b; the answer is the bottom-right cell. The name stands for “optimal string alignment”, the version of edit distance in which swapping two neighbours counts as one edit, which is how typists slip. The limit argument lets it stop early: once every cell in a row is above the limit, no later row can get back under it.

The second function, neighbors1, does the opposite job. Instead of measuring the distance between two names, it writes out every string that is exactly one edit away from a name. You will see in Step 7 why that is useful.

# names.py (continued)
def osa_distance(a, b, limit=None):
    """Optimal string alignment distance between a and b.

    One edit is an insertion, a deletion, a replacement, or a swap of two
    neighbouring characters. If the answer must be larger than limit, the
    function stops early and returns limit + 1.
    """
    if limit is None:
        limit = max(len(a), len(b))
    if abs(len(a) - len(b)) > limit:
        return limit + 1
    older, previous = None, list(range(len(b) + 1))
    for i in range(1, len(a) + 1):
        current = [i] + [0] * len(b)
        for j in range(1, len(b) + 1):
            cost = 0 if a[i - 1] == b[j - 1] else 1
            value = min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost)
            if i > 1 and j > 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]:
                value = min(value, older[j - 2] + 1)
            current[j] = value
        if min(current) > limit:
            return limit + 1  # no later row can get back under the limit
        older, previous = previous, current
    return min(previous[-1], limit + 1)
# names.py (continued)
def neighbors1(name, alphabet=ALPHABET):
    """Every string exactly one edit away from name."""
    found = set()
    for i in range(len(name) + 1):
        head, tail = name[:i], name[i:]
        if tail:
            found.add(head + tail[1:])                      # delete one character
        if len(tail) > 1:
            found.add(head + tail[1] + tail[0] + tail[2:])  # swap two neighbours
        for ch in alphabet:
            if tail:
                found.add(head + ch + tail[1:])             # replace one character
            found.add(head + ch + tail)                     # insert one character
    found.discard(name)
    return found

Try them on requests. The script also contains a plain version of edit distance without swaps, so you can see what the swap rule changes.

"""step04_distance.py: count the edits between a popular name and a guess."""
from names import neighbors1, osa_distance


def levenshtein(a, b):
    """Plain edit distance: insert, delete or replace one character. No swaps."""
    row = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        new = [i]
        for j, cb in enumerate(b, 1):
            new.append(min(row[j] + 1, new[j - 1] + 1, row[j - 1] + (ca != cb)))
        row = new
    return row[-1]


popular = "requests"
print(f"{'guess':16} {'levenshtein':>11} {'osa':>4} {'osa, limit 1':>13}")
for guess in ["requests", "request", "requestss", "reqeusts", "rekwests", "python-requests", "numpy"]:
    print(f"{guess:16} {levenshtein(popular, guess):11} {osa_distance(popular, guess):4} {osa_distance(popular, guess, 1):13}")

print()
print(len(neighbors1(popular)), "different strings are exactly one edit away from", repr(popular))
print("a few of them:", sorted(neighbors1(popular))[:3], "...", sorted(neighbors1(popular))[-2:])
python step04_distance.py
guess            levenshtein  osa  osa, limit 1
requests                   0    0             0
request                    1    1             1
requestss                  1    1             1
reqeusts                   2    1             1
rekwests                   2    2             2
python-requests            7    7             2
numpy                      7    7             2

628 different strings are exactly one edit away from 'requests'
a few of them: ['-equests', '-requests', '0equests'] ... ['zequests', 'zrequests']

Compare the reqeusts row: plain edit distance says 2 (you would have to replace two letters), while the swap-aware distance says 1, which matches how the mistake happens on a keyboard. The python-requests and numpy rows show the limit at work: asking “is it within 1?” returns 2 immediately, which means “more than 1”, without finishing the grid. And 628 different strings are one edit from requests, which is a small enough set to write out in full.

Step 5: Turn the checks into two rules

Now package the checks as rules. First add a third fold to names.py. A skeleton goes one step beyond PyPI’s fold: after ultranormalize, it also turns rn into m and vv into w (they look alike in many typefaces) and collapses repeated letters, so reequests and requests get the same skeleton.

# names.py (continued)
def skeleton(name):
    """Our wider fold: ultranormalize, then rn -> m, vv -> w, and repeated letters collapse."""
    folded = ultranormalize(name).replace("rn", "m").replace("vv", "w")
    return re.sub(r"(.)\1+", r"\1", folded)

Then create rules.py. It holds a Protected class: a set of popular names, built once, with two questions you can ask about any other name. skeleton_hits asks whether the name has the same skeleton as a protected name. edit1_hits asks whether the name is exactly one edit from a protected name, and it ignores names shorter than MIN_EDIT_LENGTH (six letters). I chose six after measuring, as you will see in Step 6; very short names have too many real, unrelated neighbours.

"""rules.py: does this name look like a popular one?"""
import dataclasses
import json
import pathlib

from names import neighbors1, normalize, skeleton

# Shorter names have too many neighbours that are real, unrelated projects.
MIN_EDIT_LENGTH = 6


@dataclasses.dataclass(frozen=True)
class Finding:
    rule: str
    target: str


def load_top(path, count):
    """The `count` most downloaded project names, normalized, most popular first."""
    rows = json.loads(pathlib.Path(path).read_text(encoding="utf-8"))["rows"]
    return [normalize(row["project"]) for row in rows[:count]]


class Protected:
    """A set of popular names plus a skeleton lookup built once."""

    def __init__(self, names):
        self.names = {normalize(n) for n in names}
        self.by_skeleton = {}
        for name in sorted(self.names):
            self.by_skeleton.setdefault(skeleton(name), []).append(name)

    def skeleton_hits(self, name):
        key = normalize(name)
        return [t for t in self.by_skeleton.get(skeleton(key), []) if t != key]

    def edit1_hits(self, name, min_length=MIN_EDIT_LENGTH):
        key = normalize(name)
        if len(key) < min_length:
            return []
        return sorted(v for v in neighbors1(key) if v in self.names)

    def findings(self, name):
        found = [Finding("skeleton", t) for t in self.skeleton_hits(name)]
        seen = {f.target for f in found}
        found += [Finding("edit1", t) for t in self.edit1_hits(name) if t not in seen]
        return found

Notice how edit1_hits works: it generates every one-edit variant of the name and keeps those that are protected names, which is a set lookup, not a comparison against every popular name. Try the rules on some names.

"""step05_rules.py: what do the two rules say about some names?"""
import pathlib

from rules import Protected, load_top

HERE = pathlib.Path(__file__).parent
top = load_top(HERE / "data" / "top-pypi-packages.json", 1000)
protected = Protected(top)
print(f"protecting the {len(protected.names)} most downloaded names\n")

for name in ["requests", "reqeusts", "requestss", "reequests", "reque5ts", "rnatplotlib",
             "nunpy", "numpyy", "pandas-utils", "my-company-tools", "Requests_"]:
    found = protected.findings(name)
    text = ", ".join(f"{f.rule} -> {f.target}" for f in found) or "no finding"
    note = "  (is a protected name)" if name in protected.names else ""
    print(f"{name:18} {text}{note}")
python step05_rules.py
protecting the 1000 most downloaded names

requests           no finding  (is a protected name)
reqeusts           edit1 -> requests
requestss          skeleton -> requests
reequests          skeleton -> requests
reque5ts           edit1 -> requests
rnatplotlib        skeleton -> matplotlib
nunpy              no finding
numpyy             skeleton -> numpy
pandas-utils       no finding
my-company-tools   no finding
Requests_          skeleton -> requests

Read the rows from the top. requests is a protected name, so it is not its own squat. reqeusts and reque5ts are one edit away. requestss and reequests are reported by the skeleton rule, because repeated letters collapse; findings lists the skeleton hit first and drops the duplicate edit hit for the same target. rnatplotlib is two edits from matplotlib, which only the skeleton rule can see. nunpy is one replaced letter away from numpy but has five letters, so the edit rule skips it; that is a real miss, and the next step shows why accepting it is reasonable. pandas-utils and my-company-tools have no finding, and the last row shows that a capital letter and a trailing underscore do not hide a name: the skeleton drops the separator.

Step 6: Measure the rules on real names

This is the step that tells you whether the idea works. The script compares eleven rules on two sets of names, with the 1,000 most downloaded projects protected:

  • Squat candidates: the 12,058 OSSF names that are not on the top-15,000 list.
  • Ordinary names: the 14,000 projects ranked 1,001 to 15,000 by downloads, treated as legitimate. They are lesser-known projects, the kind of names a real gate meets most of the time.

It prints how many names in each set each rule flags. It also loads PyPI’s own typosnyper.py (downloaded in Step 2) and runs it on the same names, so you can compare the gate with the index’s checks. For PyPI’s production list I cannot see, I use my top 1,000 as a stand-in, and I also run its built-in list of 200 names. The script takes about 40 seconds.

"""measure.py: how well do the name rules separate squat-like names from ordinary ones?

squats = names in OSSF's malicious-packages list that are not on the top-15,000 list
legit  = top-15,000 names ranked below the protected set (treated as ordinary projects)
"""
import collections
import importlib.util
import json
import pathlib

from names import neighbors1, normalize, osa_distance, skeleton, ultranormalize
from rules import MIN_EDIT_LENGTH, Protected

HERE = pathlib.Path(__file__).parent
OUT = HERE / "out"
OUT.mkdir(exist_ok=True)

rows = json.loads((HERE / "data" / "top-pypi-packages.json").read_text(encoding="utf-8"))["rows"]
top = [normalize(r["project"]) for r in rows]
rank = {name: i for i, name in enumerate(top)}
ossf = {normalize(n) for n in json.loads((HERE / "data" / "ossf-pypi-names.json").read_text(encoding="utf-8"))["names"]}
squats = sorted(ossf - set(top))
N = 1000
legit = top[N:]
print(f"protected: the {N} most downloaded names")
print(f"squat candidates: {len(squats)} OSSF names not on the top list; legit comparison set: {len(legit)} names ranked {N + 1} to {len(top)}")

by_ultra, by_skeleton = {}, {}
for i, name in enumerate(top):
    by_ultra.setdefault(ultranormalize(name), []).append(i)
    by_skeleton.setdefault(skeleton(name), []).append(i)


def best(ranks, me):
    """The most popular rank among ranks, ignoring the name itself."""
    return min((r for r in ranks if r != me), default=None)


def features(name):
    me = rank.get(name)
    near = [rank[v] for v in neighbors1(name) if v in rank]
    return {"ultra": best(by_ultra.get(ultranormalize(name), []), me),
            "skeleton": best(by_skeleton.get(skeleton(name), []), me),
            "edit1": best(near, me)}


feats = {name: features(name) for name in squats + top}


def hit(name, key, n):
    r = feats[name][key]
    return r is not None and r < n


def gate_rule(name, n=N):
    return hit(name, "skeleton", n) or (len(name) >= MIN_EDIT_LENGTH and hit(name, "edit1", n))


# Rules that need to look at every protected name.
protected_n = top[:N]
long_names = [p for p in protected_n if len(p) >= 6]
by_len = collections.defaultdict(list)
for p in protected_n:
    by_len[len(p)].append(p)
token_runs = {tuple(p.split("-")) for p in protected_n}


def two_edits_long(x):
    if len(x) < 10:
        return False
    return any(osa_distance(x, p, 2) <= 2 for size in range(len(x) - 2, len(x) + 3) for p in by_len.get(size, ()))


def contains_popular(x):
    return any(p in x for p in long_names)


def extra_words(x):
    t = tuple(x.split("-"))
    return any(t[i:j] in token_runs for i in range(len(t)) for j in range(i + 1, len(t) + 1) if j - i < len(t))


spec = importlib.util.spec_from_file_location("typosnyper", HERE / "data" / "warehouse_typosnyper.py")
typosnyper = importlib.util.module_from_spec(spec)
spec.loader.exec_module(typosnyper)
corpus = set(protected_n)

rules = [
    ("ultranormalize match (PyPI refuses these at upload)", lambda x: hit(x, "ultra", N)),
    ("skeleton match", lambda x: hit(x, "skeleton", N)),
    ("one edit, any length", lambda x: hit(x, "edit1", N)),
    ("one edit, 4+ letters", lambda x: len(x) >= 4 and hit(x, "edit1", N)),
    ("one edit, 6+ letters", lambda x: len(x) >= 6 and hit(x, "edit1", N)),
    ("GATE: skeleton, or one edit with 6+ letters", gate_rule),
    ("two edits, 10+ letters", two_edits_long),
    ("contains a popular name (6+ letters)", contains_popular),
    ("popular name plus extra words", extra_words),
    ("PyPI typosnyper, our top 1,000 as the corpus", lambda x: typosnyper.typo_check_name(x, corpus=corpus) is not None),
    ("PyPI typosnyper, its built-in list of 200", lambda x: typosnyper.typo_check_name(x) is not None),
]
print()
print(f"{'rule':52} {'squats':>14} {'legit':>14}")
results = {}
for label, rule in rules:
    sh = sum(map(rule, squats))
    lh = sum(map(rule, legit))
    results[label] = (sh, lh)
    print(f"{label:52} {sh:5d} {sh / len(squats):7.2%} {lh:5d} {lh / len(legit):7.2%}")

kinds = collections.Counter(typosnyper.typo_check_name(x, corpus=corpus)[0] for x in squats
                            if typosnyper.typo_check_name(x, corpus=corpus))
print("\ntyposnyper checks that fired on the squat candidates:", dict(kinds))

print("\nGATE rule by protected-set size")
print(f"{'protected':>10} {'squats flagged':>16} {'legit flagged':>16}")
for n in (200, 500, 1000, 2000, 5000):
    rest = top[n:]
    sh = sum(gate_rule(x, n) for x in squats)
    lh = sum(gate_rule(x, n) for x in rest)
    print(f"{n:10} {sh:6d} {sh / len(squats):8.2%} {lh:6d} {lh / len(rest):8.2%}")

print("\none edit from a protected name, by length of the checked name")
print(f"{'letters':>8} {'squats':>7} {'flagged':>8} {'legit':>7} {'flagged':>8}")
for low, high in ((1, 3), (4, 5), (6, 8), (9, 99)):
    s = [x for x in squats if low <= len(x) <= high]
    l = [x for x in legit if low <= len(x) <= high]
    sf = sum(hit(x, "edit1", N) for x in s)
    lf = sum(hit(x, "edit1", N) for x in l)
    label = f"{low}-{high}" if high < 99 else f"{low}+"
    print(f"{label:>8} {len(s):7d} {sf:6d} {sf / len(s):2.0%} {len(l):7d} {lf:6d} {lf / len(l):2.0%}".replace("  %", " %"))

protected = Protected(protected_n)
agree = sum(bool(protected.findings(x)) == gate_rule(x) for x in squats + legit)
print(f"\nProtected.findings agrees with the rank-based count on {agree} of {len(squats) + len(legit)} names")

flagged = []
for x in legit:
    for f in protected.findings(x)[:1]:
        flagged.append({"name": x, "rule": f.rule, "target": f.target})
squat_hits, legit_hits = results["GATE: skeleton, or one edit with 6+ letters"]
(OUT / "legit_flagged.json").write_text(json.dumps(flagged), encoding="utf-8")
(OUT / "measure.json").write_text(json.dumps({
    "squats": len(squats), "legit": len(legit), "squat_hits": squat_hits, "legit_hits": legit_hits}), encoding="utf-8")
print(f"saved {len(flagged)} flagged legit names to out/legit_flagged.json")
python measure.py
protected: the 1000 most downloaded names
squat candidates: 12058 OSSF names not on the top list; legit comparison set: 14000 names ranked 1001 to 15000

rule                                                         squats          legit
ultranormalize match (PyPI refuses these at upload)      0   0.00%     3   0.02%
skeleton match                                         242   2.01%     5   0.04%
one edit, any length                                   743   6.16%   218   1.56%
one edit, 4+ letters                                   739   6.13%   176   1.26%
one edit, 6+ letters                                   698   5.79%   100   0.71%
GATE: skeleton, or one edit with 6+ letters            711   5.90%   103   0.74%
two edits, 10+ letters                                 413   3.43%    98   0.70%
contains a popular name (6+ letters)                   360   2.99%  2281  16.29%
popular name plus extra words                         1234  10.23%  3049  21.78%
PyPI typosnyper, our top 1,000 as the corpus           615   5.10%    66   0.47%
PyPI typosnyper, its built-in list of 200              476   3.95%    26   0.19%

typosnyper checks that fired on the squat candidates: {'swapped_characters': 160, 'repeated_characters': 226, 'common_typos': 46, 'omitted_characters': 181, 'swapped_words': 2}

GATE rule by protected-set size
 protected   squats flagged    legit flagged
       200    475    3.94%     27    0.18%
       500    633    5.25%     56    0.39%
      1000    711    5.90%    103    0.74%
      2000    817    6.78%    155    1.19%
      5000    875    7.26%    217    2.17%

one edit from a protected name, by length of the checked name
 letters  squats  flagged   legit  flagged
     1-3      32      4 12%     189     42 22%
     4-5     400     41 10%    1038     76 7%
     6-8    2354    225 10%    2866     56 2%
      9+    9272    473 5%    9907     44 0%

Protected.findings agrees with the rank-based count on 26058 of 26058 names
saved 103 flagged legit names to out/legit_flagged.json

What the main table says

The first table is the main result. Read it with the second and third columns side by side: a rule is useful when it flags a much bigger share of the squat candidates than of the ordinary names.

  • Ultranormalize match: 0 of 12,058. PyPI refuses those names at upload, so none were found. Three ordinary names collide with a protected name under that fold; I did not look into why.
  • Skeleton match: 242 squat candidates (2.01 percent) against 5 ordinary names (0.04 percent). This is the sharpest rule: roughly 50 times more likely to hit a squat candidate than an ordinary name.
  • One edit, 6+ letters: 698 (5.79 percent) against 100 (0.71 percent), about 8 times. Allowing any length catches 45 more squat candidates and 118 more ordinary names, which is a poor trade.
  • The gate (skeleton, or one edit with 6+ letters): 711 (5.90 percent) against 103 (0.74 percent).
  • Two edits, 10+ letters: 413 against 98. A wider net with a similar number of false alarms; I left it out.
  • Contains a popular name and popular name plus extra words: these flag more ordinary names than squat candidates (16.29 and 21.78 percent against 2.99 and 10.23 percent). PyPI is full of honest plugins such as pytest-cov, so “contains pytest” says almost nothing. On this data these two rules do worse than chance, because they flag ordinary names more often than squat candidates.
  • PyPI’s typosnyper: with my top 1,000 as the list it flags 615 squat candidates (5.10 percent) and 66 ordinary names (0.47 percent). That is fewer false alarms than my gate for a little less recall, because its checks only consider plausible keyboard slips, while my gate accepts any single edit. The summary line under the table shows which of its five checks fired: repeated characters 226, omitted characters 181, swapped characters 160, common typos 46, swapped words 2.

How long should the protected list be?

Protecting 5,000 names instead of 1,000 raises the gate’s hit rate on squat candidates from 5.90 to 7.26 percent, while the share of ordinary names it flags climbs from 0.74 to 2.17 percent. More names means more neighbours that are real projects. I stayed at 1,000.

Does the edit rule work for short names?

The last table says no: among names of 1 to 3 letters, 22 percent of the ordinary names are one edit from a protected name (42 of 189), and for 4 to 5 letters it is 7 percent (76 of 1,038), against 10 percent of the squat candidates. At 6 to 8 letters the numbers are 2 percent against 10 percent, and at 9 or more letters 0.4 percent (44 of 9,907) against 5 percent. That is why MIN_EDIT_LENGTH is 6. The last line of the output confirms that the Protected class from Step 5 gives the same answer as this script’s separate counting on all 26,058 names, and it saves the 103 flagged ordinary names for Step 8.

The honest summary

So the honest summary is this: a name gate based on look-alikes would have raised an alert on about 6 percent of the malicious-package names in this data set. The other 94 percent are either look-alikes of projects outside the protected list or have names that do not resemble any popular project. The four names printed in Step 3 (bitcionlib, bitcoiinlib, bitcoilib and bitcoilnib) are look-alikes of bitcoinlib, which is number 12,903 by downloads, so a gate that protects only the top 1,000 does not see them and one that protects all 15,000 does. Others are generated families, such as the 15 names that start with libvm. The gate is one layer, not a cure.

Step 7: Make the lookup fast

You may wonder why edit1_hits generates variants instead of calling osa_distance on every protected name. The script below times both on the same 300 names, once with 1,000 protected names and once with all 15,000, and checks that they give identical answers.

"""step07_speed.py: compare a distance scan with the set-lookup trick."""
import json
import pathlib
import random
import time

from names import normalize, osa_distance
from rules import MIN_EDIT_LENGTH, Protected, load_top

HERE = pathlib.Path(__file__).parent
ossf = sorted({normalize(n) for n in json.loads((HERE / "data" / "ossf-pypi-names.json").read_text(encoding="utf-8"))["names"]})
queries = random.Random(7).sample([n for n in ossf if len(n) >= MIN_EDIT_LENGTH], 300)
print(f"{len(queries)} queries")
print(f"{'protected':>10} {'scan ms/query':>14} {'lookup ms/query':>16} {'speed-up':>9} {'same answers':>13}")
for size in (1000, 15000):
    top = load_top(HERE / "data" / "top-pypi-packages.json", size)
    protected = Protected(top)

    def scan(name):
        """Compare the name with every protected name, stopping early inside each comparison."""
        return sorted(p for p in top if abs(len(p) - len(name)) <= 1 and osa_distance(name, p, 1) == 1)

    t0 = time.perf_counter()
    slow = [scan(q) for q in queries]
    t1 = time.perf_counter()
    fast = [protected.edit1_hits(q) for q in queries]
    t2 = time.perf_counter()
    same = sum(a == b for a, b in zip(slow, fast))
    print(f"{size:10} {(t1 - t0) / len(queries) * 1000:14.2f} {(t2 - t1) / len(queries) * 1000:16.2f} "
          f"{(t1 - t0) / (t2 - t1):8.1f}x {same:9} of {len(queries)}")
python step07_speed.py
300 queries
 protected  scan ms/query  lookup ms/query  speed-up  same answers
      1000           0.53             0.12      4.6x       300 of 300
     15000           7.56             0.12     63.4x       300 of 300

The distance scan gets slower as the protected list grows (0.53 ms per name for 1,000, 7.56 ms for 15,000), because it compares against every popular name. The set lookup costs the same 0.12 ms either way, because it generates the same few hundred variants whatever the list size. Both gave identical answers for all 300 names. Timings depend on your machine, so expect different milliseconds but the same pattern.

Step 8: Ask PyPI whether the name exists and how old it is

The name rules only look at spelling. Two facts from the index make them far more useful: whether the project exists at all, and when it was first uploaded. pip reads project pages from the “Simple API”, and PyPI offers a JSON form of it (PEP 691). Since PEP 700, each file entry can carry an upload-time, which that PEP says represents “the time the file was uploaded to the index”. The class below asks for one project page, treats an HTTP 404 as “no such project”, and takes the earliest upload time as the project’s first upload. FakeIndex is a dictionary with the same lookup method, so tests need no network.

"""pypi_index.py: ask PyPI whether a project exists and when it was first uploaded.

Uses the same JSON Simple API that pip reads (PEP 691), whose file entries carry
an upload-time (PEP 700).
"""
import dataclasses
import datetime as dt

import requests

from names import normalize

ACCEPT = "application/vnd.pypi.simple.v1+json"


@dataclasses.dataclass(frozen=True)
class Project:
    name: str
    exists: bool
    first_upload: dt.datetime | None = None
    files: int = 0

    def age_days(self, now=None):
        if self.first_upload is None:
            return None
        now = now or dt.datetime.now(dt.timezone.utc)
        return (now - self.first_upload).days


class PyPIIndex:
    def __init__(self, base="https://pypi.org/simple/", session=None):
        self.base = base
        self.session = session or requests.Session()
        self.session.headers["User-Agent"] = "name-gate-lab/1.0"
        self.cache = {}

    def lookup(self, name):
        key = normalize(name)
        if key not in self.cache:
            reply = self.session.get(self.base + key + "/", headers={"Accept": ACCEPT}, timeout=20)
            if reply.status_code == 404:
                self.cache[key] = Project(key, False)
            else:
                reply.raise_for_status()
                files = reply.json()["files"]
                times = [dt.datetime.fromisoformat(f["upload-time"]) for f in files if f.get("upload-time")]
                self.cache[key] = Project(key, True, min(times) if times else None, len(files))
        return self.cache[key]


class FakeIndex:
    """A dictionary standing in for PyPI, so tests need no network."""

    def __init__(self, projects):
        self.projects = {normalize(p.name): p for p in projects}

    def lookup(self, name):
        key = normalize(name)
        return self.projects.get(key, Project(key, False))

Now ask the real PyPI about four names: a giant project, a name written in the old style, the httpx2 project, and a name that cannot exist.

"""step08_live.py: ask the real PyPI about a few names."""
from pypi_index import PyPIIndex

index = PyPIIndex()
for name in ["requests", "Flask_Login", "httpx2", "zz-no-such-project-4f9a1c7e"]:
    project = index.lookup(name)
    if project.exists:
        first = project.first_upload.date() if project.first_upload else "unknown"
        print(f"{name:30} exists, {project.files:4} files, first upload {first}, age {project.age_days()} days")
    else:
        print(f"{name:30} not found (HTTP 404)")
python step08_live.py
requests                       exists,  244 files, first upload 2011-02-14, age 5761 days
Flask_Login                    exists,   31 files, first upload 2013-06-18, age 4905 days
httpx2                         exists,   48 files, first upload 2026-05-11, age 196 days
zz-no-such-project-4f9a1c7e    not found (HTTP 404)

The numbers in the age column grow by one every day; the other fields should match. httpx2 is a real project that was first uploaded in May 2026 and sits one edit from httpx. It is popular enough to be on the protected list itself, so the gate allows it, but a less popular project like it would be flagged; you will meet one in Step 10. The made-up name returns a 404.

Now use this to ask a sharper question. Of the 103 ordinary names the gate flagged in Step 6, how old are they? If most were brand new, the age check would not help. The script below asks PyPI for each one.

"""measure_age.py: how old are the legit names the gate rules flagged?

Reads out/legit_flagged.json (written by measure.py) and asks PyPI for each name.
"""
import collections
import json
import pathlib
import statistics
import time

from pypi_index import PyPIIndex

HERE = pathlib.Path(__file__).parent
(HERE / "out").mkdir(exist_ok=True)
flagged = json.loads((HERE / "out" / "legit_flagged.json").read_text(encoding="utf-8"))
index = PyPIIndex()
ages = {}
missing = []
for item in flagged:
    project = index.lookup(item["name"])
    if not project.exists:
        missing.append(item["name"])
    else:
        ages[item["name"]] = project.age_days()
    time.sleep(0.05)

known = [a for a in ages.values() if a is not None]
print(f"flagged legit names: {len(flagged)}, still on PyPI: {len(ages)}, gone: {len(missing)}")
print(f"first upload under 90 days ago: {sum(a < 90 for a in known)}; under 365 days: {sum(a < 365 for a in known)}")
print(f"median age {statistics.median(known) / 365.25:.1f} years, oldest {max(known) / 365.25:.1f} years")
by_rule = collections.Counter(item["rule"] for item in flagged)
print("by rule:", dict(by_rule))
print("\nthe five youngest flagged names:")
targets = {item["name"]: item for item in flagged}
for name, age in sorted(ages.items(), key=lambda kv: kv[1])[:5]:
    print(f"  {name:22} {age:4} days  {targets[name]['rule']} -> {targets[name]['target']}")
(HERE / "out" / "age.json").write_text(json.dumps({"known": len(known), "young90": sum(a < 90 for a in known),
                                                    "young365": sum(a < 365 for a in known)}), encoding="utf-8")
python measure_age.py
flagged legit names: 103, still on PyPI: 103, gone: 0
first upload under 90 days ago: 0; under 365 days: 6
median age 8.3 years, oldest 20.6 years
by rule: {'edit1': 98, 'skeleton': 5}

the five youngest flagged names:
  zuvloop                 109 days  edit1 -> uvloop
  vmodal                  135 days  edit1 -> modal
  pytest-httpx2           187 days  edit1 -> pytest-httpx
  sqlglotc                202 days  edit1 -> sqlglot
  py-cpuinfo2             242 days  edit1 -> py-cpuinfo

All 103 flagged ordinary names still exist, none was first uploaded in the last 90 days, only six in the last year, and the median is 8.3 years. A rule that says “look-alike and younger than 90 days” would have raised no false alarm on this set. There is a catch, which I come back to in the limits: the top-15,000 list is a list of survivors. A legitimate project that appeared last month rarely has enough downloads to be on it, so this set cannot tell you how many brand-new but honest look-alike names exist.

Step 9: Work out what an alert means

A rule can look good in a table and still bury you in false alarms. Whether an alert is worth reading depends on how rare bad names are among the names you check, which is called the base rate. The script below uses Bayes’ rule with the measured numbers: the gate’s hit rate on squat candidates (5.90 percent) and its false-alarm rate on ordinary names (0.74 percent). It also shows what happens if you require the project to be younger than 90 days. Nothing was seen in 14,000 tries, so it plans with 3 divided by 14,000, the “rule of three” upper bound for a rate that was never observed.

"""step09_policy.py: what share of the alerts would be real? A base-rate calculation."""
import json
import pathlib

HERE = pathlib.Path(__file__).parent
measured = json.loads((HERE / "out" / "measure.json").read_text(encoding="utf-8"))
ages = json.loads((HERE / "out" / "age.json").read_text(encoding="utf-8"))

recall = measured["squat_hits"] / measured["squats"]
false_alarm = measured["legit_hits"] / measured["legit"]
young = ages["young90"]
# With nothing seen in n tries, the "rule of three" says the true rate is below 3 / n (95 percent).
false_alarm_age = max(young, 3) / measured["legit"]

print(f"name rule alone      : catches {recall:.2%} of squat candidates, flags {false_alarm:.2%} of ordinary names")
print(f"name rule + under 90 days old: {young} of {measured['legit']} ordinary names flagged; planning with {false_alarm_age:.3%} (3 / n)")
print("assumption: a squat is under 90 days old when you check it (a guess, not a measurement)\n")
print(f"{'1 name in every':>16} {'real alerts, name rule alone':>30} {'real alerts, plus age check':>29}")
for one_in in (100, 1_000, 10_000, 100_000):
    p = 1 / one_in
    alone = p * recall / (p * recall + (1 - p) * false_alarm)
    with_age = p * recall / (p * recall + (1 - p) * false_alarm_age)
    print(f"{one_in:16,} {alone:29.2%} {with_age:29.2%}")
python step09_policy.py
name rule alone      : catches 5.90% of squat candidates, flags 0.74% of ordinary names
name rule + under 90 days old: 0 of 14000 ordinary names flagged; planning with 0.021% (3 / n)
assumption: a squat is under 90 days old when you check it (a guess, not a measurement)

 1 name in every   real alerts, name rule alone   real alerts, plus age check
             100                         7.49%                        73.54%
           1,000                         0.80%                        21.60%
          10,000                         0.08%                         2.68%
         100,000                         0.01%                         0.27%

Take the 1-in-1,000 row, which means that one name in every thousand you check is a squat: with the name rule alone, only 0.80 percent of alerts are real, so about 124 alerts out of 125 are noise. With the age check added, 21.60 percent are real. The age check cuts the false alarms per real alert by a factor of about 34, but the last column carries an assumption you should not skip: it assumes that a malicious name is under 90 days old when you check it. I could not measure that, because the malicious projects have been removed from PyPI and the index no longer says when they were uploaded. Treat the table as a what-if.

Step 10: Assemble the gate

The policy and the code

Now combine the pieces. The function decide turns one name into a verdict, using this policy:

  • A name on your allowlist (projects a person has reviewed) or already in the protected set is allowed.
  • A name that does not exist on PyPI is blocked: nothing legitimate can be installed under it, and for an AI assistant it is the sign of a made-up name.
  • A name that looks like a protected name and was first uploaded under 90 days ago is blocked.
  • A look-alike that is older, a young project with no resemblance to anything, or a look-alike checked offline is sent to review for a person to decide.
  • Everything else is allowed.

The command-line part reads a requirements file with the packaging library, so it understands extras and markers the way pip does; it strips comments itself. It refuses to guess about two kinds of lines: option lines such as -r other.txt (it tells you to check them by hand) and name @ url requirements (they bypass the index, so no index check applies). The optional --resolve flag asks pip what it would install, without installing anything, by using pip’s report feature, and checks every name in the answer, so dependencies of dependencies are included.

"""gate.py: check every package name in a requirements file before pip installs it.

Exit status: 0 when nothing reached the --fail-on level, 1 for review, 2 for block.
"""
import argparse
import dataclasses
import datetime as dt
import json
import pathlib
import subprocess
import sys

from packaging.requirements import InvalidRequirement, Requirement

from names import normalize
from pypi_index import PyPIIndex
from rules import Protected, load_top

LEVELS = {"allow": 0, "review": 1, "block": 2}
HERE = pathlib.Path(__file__).parent


@dataclasses.dataclass
class Verdict:
    name: str
    level: str
    reasons: list


def decide(name, protected, index=None, allow=frozenset(), now=None, young_days=90):
    """Turn one package name into allow, review or block, with the reasons."""
    key = normalize(name)
    if key in allow:
        return Verdict(key, "allow", ["on the allowlist"])
    if key in protected.names:
        return Verdict(key, "allow", ["is itself a protected popular name"])
    reasons = [f"{f.rule}: looks like {f.target}" for f in protected.findings(key)]
    looks_like = bool(reasons)
    project = None
    if index is not None:
        project = index.lookup(key)
        if not project.exists:
            return Verdict(key, "block", ["no such project on PyPI"] + reasons)
    age = project.age_days(now) if project else None
    young = age is not None and age < young_days
    if young:
        reasons.append(f"young project: first upload {age} days ago")
    if not looks_like:
        return Verdict(key, "review" if young else "allow", reasons)
    if young:
        return Verdict(key, "block", reasons)
    if project is None:
        reasons.append("age not checked (offline)")
    return Verdict(key, "review", reasons)


def read_requirements(path):
    """Return ([(name, url or None)], [(line, problem)]) for a requirements file."""
    entries, problems = [], []
    for raw in pathlib.Path(path).read_text(encoding="utf-8").splitlines():
        line = raw.split(" #", 1)[0].strip()
        if not line or line.startswith("#"):
            continue
        if line.startswith("-"):
            problems.append((line, "option line skipped, check it by hand"))
            continue
        try:
            req = Requirement(line)
        except InvalidRequirement:
            problems.append((line, "cannot be parsed as a requirement"))
            continue
        entries.append((req.name, req.url))
    return entries, problems


def resolve_names(path):
    """Ask pip what it would install, without installing and without building anything."""
    cmd = [sys.executable, "-m", "pip", "install", "--dry-run", "--ignore-installed",
           "--only-binary", ":all:", "--quiet", "--report", "-", "-r", str(path)]
    done = subprocess.run(cmd, capture_output=True, text=True)
    if done.returncode != 0:
        sys.exit("pip could not resolve the file:\n" + done.stderr.strip()[-800:])
    report = json.loads(done.stdout)
    return sorted({normalize(item["metadata"]["name"]) for item in report["install"]})


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("requirements")
    parser.add_argument("--top", type=int, default=1000, help="how many popular names to protect")
    parser.add_argument("--data", default=str(HERE / "data" / "top-pypi-packages.json"))
    parser.add_argument("--allow", help="file with one reviewed project name per line")
    parser.add_argument("--offline", action="store_true", help="skip the PyPI lookups")
    parser.add_argument("--resolve", action="store_true", help="also check every name pip would install")
    parser.add_argument("--young-days", type=int, default=90)
    parser.add_argument("--fail-on", choices=["review", "block"], default="review")
    args = parser.parse_args(argv)

    protected = Protected(load_top(args.data, args.top))
    allow = set()
    if args.allow:
        allow = {normalize(line.split("#")[0].strip())
                 for line in pathlib.Path(args.allow).read_text(encoding="utf-8").splitlines()
                 if line.split("#")[0].strip()}
    index = None if args.offline else PyPIIndex()
    now = dt.datetime.now(dt.timezone.utc)

    entries, problems = read_requirements(args.requirements)
    verdicts = []
    for line, problem in problems:
        verdicts.append(Verdict(line, "review", [problem]))
    seen = set()
    for name, url in entries:
        seen.add(normalize(name))
        if url:
            verdicts.append(Verdict(normalize(name), "review", ["installs from a URL, not from the index: " + url]))
        else:
            verdicts.append(decide(name, protected, index, allow, now, args.young_days))
    if args.resolve:
        for name in resolve_names(args.requirements):
            if name not in seen:
                verdicts.append(decide(name, protected, index, allow, now, args.young_days))

    worst = max((LEVELS[v.level] for v in verdicts), default=0)
    for v in sorted(verdicts, key=lambda v: (-LEVELS[v.level], v.name)):
        print(f"{v.level.upper():7} {v.name:24} {'; '.join(v.reasons)}")
    counts = {level: sum(v.level == level for v in verdicts) for level in LEVELS}
    print(f"\n{counts['allow']} allow, {counts['review']} review, {counts['block']} block")
    return worst if worst >= LEVELS[args.fail_on] else 0


if __name__ == "__main__":
    sys.exit(main())

Try the policy on seven made-up situations

First see the policy on seven made-up situations. The script uses FakeIndex with ages I chose, so the output never changes.

"""step10_decide.py: the policy on seven made-up situations, with a fake PyPI."""
import datetime as dt
import pathlib

from gate import decide
from pypi_index import FakeIndex, Project
from rules import Protected, load_top

HERE = pathlib.Path(__file__).parent
NOW = dt.datetime(2026, 11, 23, tzinfo=dt.timezone.utc)
protected = Protected(load_top(HERE / "data" / "top-pypi-packages.json", 1000))


def project(name, days_old):
    return Project(name, True, NOW - dt.timedelta(days=days_old), 4)


index = FakeIndex([
    project("flask-cors-helpers", 900),   # old, unrelated to any popular name
    project("reqeusts", 12),              # a swapped-letter name uploaded 12 days ago
    project("requestz", 700),             # one letter off, but old
    project("reequests", 3),              # repeated letter, very young
    project("tiny-new-tool", 5),          # young but unrelated
    project("httpx2", 196),               # one edit from httpx, a real project we reviewed
])
cases = [("flask-cors-helpers", set()), ("reqeusts", set()), ("requestz", set()), ("reequests", set()),
         ("tiny-new-tool", set()), ("zz-invented-name", set()), ("httpx2", {"httpx2"})]
for name, allow in cases:
    verdict = decide(name, protected, index, allow, now=NOW)
    print(f"{verdict.level.upper():7} {verdict.name:20} {'; '.join(verdict.reasons)}")
python step10_decide.py
ALLOW   flask-cors-helpers   
BLOCK   reqeusts             edit1: looks like requests; young project: first upload 12 days ago
REVIEW  requestz             edit1: looks like requests
BLOCK   reequests            skeleton: looks like requests; young project: first upload 3 days ago
REVIEW  tiny-new-tool        young project: first upload 5 days ago
BLOCK   zz-invented-name     no such project on PyPI
ALLOW   httpx2               on the allowlist

Each line is one rule from the policy: an old, unrelated name is allowed; a swapped-letter name uploaded 12 days ago is blocked; one letter off but 700 days old goes to review; a repeated-letter name 3 days old is blocked through the skeleton rule; a young unrelated project goes to review; a name that does not exist is blocked; and an allowlisted name passes.

Run it on a requirements file

Now run it on a requirements file that has some trouble in it. The file is plain text; create it as requirements.sample.txt.

# requirements.sample.txt: a made-up project file with some trouble in it
requests==2.34.2
flask>=3.0
numpy
pyyaml  # config files
reqeusts
pytest-httpx2
zz-no-such-project-4f9a1c7e
internal-tool @ https://example.com/internal_tool-1.0-py3-none-any.whl
-r more-requirements.txt

First run without any network, which checks spelling only. The command after it prints the exit status; in PowerShell use $LASTEXITCODE, and in cmd.exe use echo %ERRORLEVEL%.

python gate.py requirements.sample.txt --offline
echo $?
REVIEW  -r more-requirements.txt option line skipped, check it by hand
REVIEW  internal-tool            installs from a URL, not from the index: https://example.com/internal_tool-1.0-py3-none-any.whl
REVIEW  pytest-httpx2            edit1: looks like pytest-httpx; age not checked (offline)
REVIEW  reqeusts                 edit1: looks like requests; age not checked (offline)
ALLOW   flask                    is itself a protected popular name
ALLOW   numpy                    is itself a protected popular name
ALLOW   pyyaml                   is itself a protected popular name
ALLOW   requests                 is itself a protected popular name
ALLOW   zz-no-such-project-4f9a1c7e 

5 allow, 4 review, 0 block
1

Offline, the spelling rules flag reqeusts and pytest-httpx2 and say that their age was not checked, so both go to review instead of being blocked. The made-up name zz-no-such-project-4f9a1c7e is allowed, because nothing about its spelling resembles a popular project; only the index can tell that it does not exist. The exit status 1 means “review needed”. Now run it for real:

python gate.py requirements.sample.txt
echo $?
BLOCK   reqeusts                 no such project on PyPI; edit1: looks like requests
BLOCK   zz-no-such-project-4f9a1c7e no such project on PyPI
REVIEW  -r more-requirements.txt option line skipped, check it by hand
REVIEW  internal-tool            installs from a URL, not from the index: https://example.com/internal_tool-1.0-py3-none-any.whl
REVIEW  pytest-httpx2            edit1: looks like pytest-httpx
ALLOW   flask                    is itself a protected popular name
ALLOW   numpy                    is itself a protected popular name
ALLOW   pyyaml                   is itself a protected popular name
ALLOW   requests                 is itself a protected popular name

4 allow, 3 review, 2 block
2

With the index available, reqeusts turns out not to exist on PyPI, so it is blocked, and so is the made-up name. pytest-httpx2 is a real pytest plugin that is one edit from pytest-httpx, so it needs a person’s review. The URL requirement and the -r line are sent to review on purpose. The exit status is 2 because something was blocked. To record that someone has looked at pytest-httpx2, put it on an allowlist, with a comment explaining why:

pytest-httpx2  # reviewed 2026-11-23: a pytest plugin for httpx2, first uploaded months ago
python gate.py requirements.sample.txt --allow allow.txt
echo $?
BLOCK   reqeusts                 no such project on PyPI; edit1: looks like requests
BLOCK   zz-no-such-project-4f9a1c7e no such project on PyPI
REVIEW  -r more-requirements.txt option line skipped, check it by hand
REVIEW  internal-tool            installs from a URL, not from the index: https://example.com/internal_tool-1.0-py3-none-any.whl
ALLOW   flask                    is itself a protected popular name
ALLOW   numpy                    is itself a protected popular name
ALLOW   pytest-httpx2            on the allowlist
ALLOW   pyyaml                   is itself a protected popular name
ALLOW   requests                 is itself a protected popular name

5 allow, 2 review, 2 block
2

The line for pytest-httpx2 now says on the allowlist. The two blocks and the two lines that need a human remain, as they should.

Check everything pip would install

Last, the --resolve flag, on a smaller file with two requirements:

requests==2.34.2
flask>=3.0
python gate.py requirements.small.txt --resolve
echo $?
ALLOW   blinker                  is itself a protected popular name
ALLOW   certifi                  is itself a protected popular name
ALLOW   charset-normalizer       is itself a protected popular name
ALLOW   click                    is itself a protected popular name
ALLOW   flask                    is itself a protected popular name
ALLOW   idna                     is itself a protected popular name
ALLOW   itsdangerous             is itself a protected popular name
ALLOW   jinja2                   is itself a protected popular name
ALLOW   markupsafe               is itself a protected popular name
ALLOW   requests                 is itself a protected popular name
ALLOW   urllib3                  is itself a protected popular name
ALLOW   werkzeug                 is itself a protected popular name

12 allow, 0 review, 0 block
0

pip resolved those two requirements into 12 projects, and the gate checked all of them; every one is on the protected list. Under the hood the flag runs pip with --dry-run, --ignore-installed, --quiet and --report -. The pip documentation says that combination “can be used to resolve a set of requirements without actually installing them”. The script also passes --only-binary :all:, which pip documents as “Do not use source packages”; I added it so that resolving never has to build a source package, which would run that package’s build code on your machine, the thing you are trying to avoid. The price is that resolving fails for a project that offers only a source package, and the gate then stops with pip’s error message.

Step 11: Ask small local models for package names

Now the other half of the title. The script below asks three small models running in Ollama which PyPI package to install for 30 tasks, two answers each at temperature 0.7 with seeds 1 and 2. Fifteen tasks are everyday (read YAML files, send HTTP requests); fifteen are niche (decode ship-position messages, read Garmin activity files). It extracts the package name from each reply, then asks PyPI whether that name exists. One decision deserves a note: the script writes the invented names to a local file but never prints them. Publishing a list of names that models tend to invent would hand squatters a shopping list.

"""llm_probe.py: which package names do small local models make up?

Asks each Ollama model the same question for 30 tasks, twice, and checks every
answer against PyPI. The made-up names are saved locally and never printed.
"""
import collections
import json
import pathlib
import re

import requests

from names import normalize
from pypi_index import PyPIIndex
from rules import load_top

HERE = pathlib.Path(__file__).parent
(HERE / "out").mkdir(exist_ok=True)
MODELS = ["qwen2.5:0.5b", "qwen2.5:1.5b", "qwen3.5:4b"]
SEEDS = [1, 2]
EVERYDAY = ["read and write Excel files", "send HTTP requests", "parse HTML pages",
            "validate JSON against a schema", "resize and convert images", "talk to a PostgreSQL database",
            "parse command line arguments with subcommands", "read settings from a .env file",
            "compress data with zstd", "generate PDF files", "schedule recurring jobs",
            "parse dates written in many formats", "write tests with fixtures", "talk to Redis",
            "read YAML files"]
NICHE = ["decode AIS ship position messages", "read Garmin FIT activity files", "validate IBAN bank account numbers",
         "parse FIX financial protocol messages", "convert dates to the Hijri calendar",
         "read DBC files for CAN bus signals", "talk to a Modbus TCP device", "parse GPX tracks with elevation profiles",
         "compute Estonian personal identity code checksums", "read Sentinel-2 satellite band files",
         "parse DICOM medical image headers", "decode Wiegand card reader frames",
         "generate QR codes with a logo in the middle", "talk to an OPC UA server",
         "read Apache Parquet files without pandas"]
TASKS = [("everyday", t) for t in EVERYDAY] + [("niche", t) for t in NICHE]


def ask(model, task, seed):
    body = {"model": model, "stream": False,
            "prompt": f"Which PyPI package should I install to {task}? Reply with only the exact package name, nothing else.",
            "options": {"temperature": 0.7, "seed": seed, "num_predict": 24}}
    if model.startswith("qwen3"):
        body["think"] = False
    reply = requests.post("http://127.0.0.1:11434/api/generate", json=body, timeout=300)
    reply.raise_for_status()
    return reply.json()["response"]


def extract_name(reply):
    """The package name in a one-line reply, or None."""
    lines = reply.strip().splitlines()
    if not lines:
        return None
    line = re.sub(r"^(python -m )?pip3? install\s+", "", lines[0].strip().strip("`'\"* "), flags=re.I)
    words = line.split()
    if not words:
        return None
    token = re.sub(r"[=<>!~\[].*$", "", words[0]).strip("`'\",.;:()")
    return token if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", token) else None


def main():
    popular = set(load_top(HERE / "data" / "top-pypi-packages.json", 1000))
    index = PyPIIndex()
    answers = []
    for model in MODELS:
        for kind, task in TASKS:
            for seed in SEEDS:
                reply = ask(model, task, seed)
                name = extract_name(reply)
                answers.append({"model": model, "kind": kind, "task": task, "seed": seed, "reply": reply, "name": name})
    for a in answers:
        if a["name"] is None:
            a["class"] = "unparseable"
            continue
        key = normalize(a["name"])
        project = index.lookup(key)
        if not project.exists:
            a["class"] = "missing"
        elif key in popular:
            a["class"] = "popular"
        else:
            a["class"] = "other"
            a["age_days"] = project.age_days()
    (HERE / "out" / "llm_answers.json").write_text(json.dumps(answers, indent=1), encoding="utf-8")

    print(f"{len(TASKS)} tasks x {len(SEEDS)} seeds per model; temperature 0.7")
    print(f"{'model':14} {'asked':>6} {'popular':>8} {'other':>6} {'missing':>8} {'unparsed':>9}  {'missing %':>9}")
    for model in MODELS:
        rows = [a for a in answers if a["model"] == model]
        c = collections.Counter(a["class"] for a in rows)
        print(f"{model:14} {len(rows):6} {c['popular']:8} {c['other']:6} {c['missing']:8} {c['unparseable']:9}  {c['missing'] / len(rows):9.1%}")
    print("\nmissing share by kind of task")
    for kind in ("everyday", "niche"):
        parts = []
        for model in MODELS:
            rows = [a for a in answers if a["model"] == model and a["kind"] == kind]
            parts.append(f"{model} {sum(a['class'] == 'missing' for a in rows)}/{len(rows)}")
        print(f"  {kind:9}", ";  ".join(parts))
    others = [a for a in answers if a["class"] == "other"]
    young = [a for a in others if a.get("age_days") is not None and a["age_days"] < 365]
    print(f"\nanswers that exist but are outside the top 1,000: {len(others)}, first uploaded under a year ago: {len(young)}")
    distinct = {normalize(a["name"]) for a in answers if a["class"] == "missing"}
    print(f"distinct names that do not exist: {len(distinct)}")


if __name__ == "__main__":
    main()
python llm_probe.py
30 tasks x 2 seeds per model; temperature 0.7
model           asked  popular  other  missing  unparsed  missing %
qwen2.5:0.5b       60       16      7       33         4      55.0%
qwen2.5:1.5b       60       20     16       23         1      38.3%
qwen3.5:4b         60       24      8       27         1      45.0%

missing share by kind of task
  everyday  qwen2.5:0.5b 11/30;  qwen2.5:1.5b 5/30;  qwen3.5:4b 7/30
  niche     qwen2.5:0.5b 22/30;  qwen2.5:1.5b 18/30;  qwen3.5:4b 20/30

answers that exist but are outside the top 1,000: 31, first uploaded under a year ago: 0
distinct names that do not exist: 80

What came out

Read the table. “Popular” means the name is on the top-1,000 list, “other” means the project exists but is less popular, and “missing” means PyPI answered 404. Between 38 and 55 percent of the answers named a project that does not exist: 33 of 60 for qwen2.5:0.5b, 23 of 60 for qwen2.5:1.5b and 27 of 60 for qwen3.5:4b. The bigger model did not do better than the middle one. The split by task is clear: on everyday tasks 11, 5 and 7 of 30 answers were missing, and on niche tasks 22, 18 and 20 of 30. Of the 83 missing answers, 80 were different names, so across two samples per task the invented names rarely repeated. The 31 answers that exist but are not popular were all old projects (none was first uploaded in the last year).

Be careful what you take from this. These are small local models and a task list that is half niche on purpose, so the percentages are not a measure of any frontier model, and two samples per task say little about how often a model repeats the same invented name. The paper quoted at the start used 16 models and 576,000 samples. What the experiment does show is that on this machine, with these models, a gate that blocks non-existent names would have stopped 83 of the 180 answers (46 percent). The gate in Step 10 does that.

Step 12: Test the gate, then plant bugs to see if the tests notice

A gate that fails silently is worse than none, so give it tests. The file below checks the folds against PyPI’s own refused names, the edit distance against known values and (when rapidfuzz is installed) against a reference implementation on 4,000 random pairs, neighbors1 against a brute-force definition for every name of up to three characters over a three-letter alphabet, the two rules on named cases including the six-letter boundary, every branch of the policy including the 89 and 90 day boundary, and the command line’s exit codes. None of these tests needs the network.

"""test_gate.py: no network needed. Optional: pip install rapidfuzz for the cross-check."""
import datetime as dt
import itertools
import json
import random

import pytest

import gate
from names import ALPHABET, neighbors1, normalize, osa_distance, skeleton, ultranormalize
from pypi_index import FakeIndex, Project
from rules import Protected

NOW = dt.datetime(2026, 11, 23, tzinfo=dt.timezone.utc)
POPULAR = ["requests", "numpy", "pandas", "python-dateutil", "pytest", "matplotlib", "flask"]
PROTECTED = Protected(POPULAR)


def project(name, age_days=500):
    return Project(name, True, NOW - dt.timedelta(days=age_days), 3)


# --- names -------------------------------------------------------------------

@pytest.mark.parametrize("raw, expected", [
    ("Flask_Login", "flask-login"), ("flask.login", "flask-login"), ("FLASK--LOGIN", "flask-login"),
    ("a_.-b", "a-b"), ("Pillow", "pillow")])
def test_normalize(raw, expected):
    assert normalize(raw) == expected


def test_ultranormalize_matches_the_names_pypi_tests_refuse():
    assert {ultranormalize(n) for n in
            ["toasting", "toast1ng", "toastlng", "t0asting", "toast-ing", "toast.ing", "toast_ing"]} == {"t0ast1ng"}
    assert ultranormalize("toasting2") != ultranormalize("toasting")


@pytest.mark.parametrize("a, b", [("reequests", "requests"), ("rnatplotlib", "matplotlib"),
                                  ("pillow", "pilow"), ("vvheel", "wheel")])
def test_skeleton_collisions(a, b):
    assert skeleton(a) == skeleton(b)


@pytest.mark.parametrize("a, b, expected", [
    ("", "", 0), ("a", "", 1), ("ab", "ba", 1), ("requests", "reqeusts", 1), ("kitten", "sitting", 3),
    ("abcdef", "badcfe", 3), ("ca", "abc", 3), ("requests", "request", 1), ("flask", "flasks", 1)])
def test_osa_known_values(a, b, expected):
    assert osa_distance(a, b) == expected


def test_osa_limit_stops_early():
    assert osa_distance("abcdef", "uvwxyz", 2) == 3
    assert osa_distance("a", "abcdef", 2) == 3
    assert osa_distance("ab", "xyzw", 2) == 3
    assert osa_distance("requests", "reqeusts", 1) == 1


def test_osa_matches_rapidfuzz():
    rapidfuzz = pytest.importorskip("rapidfuzz.distance")
    rng = random.Random(3)
    for _ in range(4000):
        a = "".join(rng.choice("abc-") for _ in range(rng.randint(0, 9)))
        b = "".join(rng.choice("abc-") for _ in range(rng.randint(0, 9)))
        true = rapidfuzz.OSA.distance(a, b)
        assert osa_distance(a, b) == true
        for limit in (1, 2, 3):
            assert osa_distance(a, b, limit) == min(true, limit + 1), (a, b, limit)


def test_neighbors1_is_exactly_the_strings_one_edit_away():
    alphabet = "ab-"
    universe = ["".join(p) for n in range(5) for p in itertools.product(alphabet, repeat=n)]
    for name in universe:
        if len(name) > 3:
            continue
        expected = {s for s in universe if osa_distance(name, s) == 1}
        assert neighbors1(name, alphabet) == expected, name


def test_neighbors1_is_a_few_hundred_strings_for_a_real_name():
    found = neighbors1("requests")
    assert "reqeusts" in found and "requestss" in found and "equests" in found and "request" in found
    assert "requests" not in found
    assert all(set(s) <= set(ALPHABET) for s in found)


# --- rules -------------------------------------------------------------------

@pytest.mark.parametrize("name, rule, target", [
    ("reqeusts", "edit1", "requests"), ("reque5ts", "edit1", "requests"),
    ("requestss", "skeleton", "requests"), ("reequests", "skeleton", "requests"),
    ("python-dateutils", "edit1", "python-dateutil"), ("rnatplotlib", "skeleton", "matplotlib"),
    ("pandaz", "edit1", "pandas")])
def test_findings(name, rule, target):
    assert [(f.rule, f.target) for f in PROTECTED.findings(name)] == [(rule, target)]


def test_short_names_and_unrelated_names_have_no_finding():
    assert PROTECTED.findings("nunpy") == []          # five letters, below the edit limit
    assert PROTECTED.findings("my-company-tools") == []
    assert PROTECTED.findings("requests") == []       # a protected name is not its own squat


def test_edit_rule_starts_at_six_letters():
    assert PROTECTED.edit1_hits("pandaz") == ["pandas"]
    assert PROTECTED.edit1_hits("flaks") == []        # five letters
    assert Protected(["flask"]).edit1_hits("flaks", min_length=5) == ["flask"]


# --- decisions ---------------------------------------------------------------

def decide(name, projects=(), **kw):
    index = FakeIndex(projects)
    return gate.decide(name, PROTECTED, index, now=NOW, **kw)


def test_protected_name_is_allowed():
    assert decide("Requests").level == "allow"


def test_allowlist_wins_and_is_normalized():
    assert decide("Reqeusts", [project("reqeusts")], allow={"reqeusts"}).level == "allow"


def test_missing_project_is_blocked():
    verdict = decide("reqeusts")
    assert verdict.level == "block" and "no such project" in verdict.reasons[0]


def test_old_lookalike_needs_review():
    verdict = decide("reqeusts", [project("reqeusts", 500)])
    assert verdict.level == "review"
    assert "edit1: looks like requests" in verdict.reasons


def test_young_lookalike_is_blocked():
    assert decide("reqeusts", [project("reqeusts", 10)]).level == "block"


def test_young_boundary():
    assert decide("reqeusts", [project("reqeusts", 89)]).level == "block"
    assert decide("reqeusts", [project("reqeusts", 90)]).level == "review"
    assert decide("reqeusts", [project("reqeusts", 40)], young_days=30).level == "review"


def test_young_but_unrelated_project_needs_review():
    verdict = decide("brand-new-thing", [project("brand-new-thing", 3)])
    assert verdict.level == "review" and "young project" in verdict.reasons[0]


def test_old_unrelated_project_is_allowed():
    assert decide("brand-new-thing", [project("brand-new-thing", 300)]).level == "allow"


def test_offline_lookalike_is_review_not_block():
    verdict = gate.decide("reqeusts", PROTECTED, None, now=NOW)
    assert verdict.level == "review" and "age not checked (offline)" in verdict.reasons


def test_project_without_upload_times_is_not_young():
    index = FakeIndex([Project("reqeusts", True, None, 0)])
    assert gate.decide("reqeusts", PROTECTED, index, now=NOW).level == "review"


# --- requirements files and the command line ---------------------------------

def test_read_requirements(tmp_path):
    path = tmp_path / "requirements.txt"
    path.write_text("\n".join([
        "# a comment", "", "requests==2.34.2  # pinned", "Flask[async]>=3.0 ; python_version >= '3.10'",
        "-r other.txt", "tool @ https://example.com/tool-1.0.whl", "not a requirement !!"]), encoding="utf-8")
    entries, problems = gate.read_requirements(path)
    assert entries == [("requests", None), ("Flask", None), ("tool", "https://example.com/tool-1.0.whl")]
    assert [p[0] for p in problems] == ["-r other.txt", "not a requirement !!"]


def write_cli_files(tmp_path, lines):
    data = tmp_path / "top.json"
    data.write_text(json.dumps({"rows": [{"project": p} for p in POPULAR]}), encoding="utf-8")
    req = tmp_path / "requirements.txt"
    req.write_text("\n".join(lines), encoding="utf-8")
    return ["--data", str(data), "--top", "7", "--offline", str(req)]


def test_cli_exit_codes(tmp_path, capsys):
    clean = write_cli_files(tmp_path, ["requests", "numpy"])
    assert gate.main(clean) == 0
    lookalike = write_cli_files(tmp_path, ["requests", "reqeusts"])
    assert gate.main(lookalike) == 1
    assert gate.main(lookalike + ["--fail-on", "block"]) == 0
    out = capsys.readouterr().out
    assert "REVIEW  reqeusts" in out and "1 allow, 1 review, 0 block" in out


def test_cli_flags_url_requirements(tmp_path, capsys):
    args = write_cli_files(tmp_path, ["tool @ https://example.com/tool-1.0.whl"])
    assert gate.main(args) == 1
    assert "installs from a URL" in capsys.readouterr().out
python -m pytest -q test_gate.py
............................................. [100%]
45 passed in 0.21s

Plant bugs to see whether the tests notice

Passing tests show only that the tests and the code agree. To learn whether they would notice a mistake, plant one. The script below copies the code, changes one thing at a time (forgetting to lower-case a name, skipping the swap case, allowing a name that is 90 days old, comparing the allowlist before normalizing, and so on), runs the tests, and expects a failure each time.

"""mutants.py: plant one bug at a time in a copy of the code and check that the tests notice."""
import pathlib
import shutil
import subprocess
import sys
import tempfile

HERE = pathlib.Path(__file__).parent
FILES = ["names.py", "rules.py", "pypi_index.py", "gate.py", "test_gate.py"]

MUTANTS = [
    ("normalize forgets lower case", "names.py",
     'return _RUN_OF_SEPARATORS.sub("-", name).lower()', 'return _RUN_OF_SEPARATORS.sub("-", name)'),
    ("ultranormalize forgets o -> 0", "names.py", '.replace("o", "0")', ""),
    ("skeleton forgets repeated letters", "names.py",
     'return re.sub(r"(.)\\1+", r"\\1", folded)', "return folded"),
    ("osa has no swap", "names.py", "if i > 1 and j > 1 and a[i - 1]", "if False and a[i - 1]"),
    ("osa result is not capped at limit + 1", "names.py", "return min(previous[-1], limit + 1)", "return previous[-1]"),
    ("osa length filter is off by one", "names.py", "if abs(len(a) - len(b)) > limit:", "if abs(len(a) - len(b)) >= limit:"),
    ("neighbors1 drops the swap", "names.py", "found.add(head + tail[1] + tail[0] + tail[2:])", "pass"),
    ("neighbors1 never inserts at the end", "names.py", "for i in range(len(name) + 1):", "for i in range(len(name)):"),
    ("a protected name is its own squat", "rules.py", "if t != key]", "]"),
    ("edit rule starts at seven letters", "rules.py", "MIN_EDIT_LENGTH = 6", "MIN_EDIT_LENGTH = 7"),
    ("allowlist is not normalized", "gate.py", "if key in allow:", "if name in allow:"),
    ("a young project is 90 days or less", "gate.py", "age < young_days", "age <= young_days"),
    ("a missing project is only a review", "gate.py", 'return Verdict(key, "block", ["no such project on PyPI"] + reasons)',
     'return Verdict(key, "review", ["no such project on PyPI"] + reasons)'),
    ("a young unrelated project is allowed", "gate.py", 'return Verdict(key, "review" if young else "allow", reasons)',
     'return Verdict(key, "allow", reasons)'),
    ("inline comments are kept", "gate.py", 'raw.split(" #", 1)[0].strip()', "raw.strip()"),
]


def run(folder):
    done = subprocess.run([sys.executable, "-m", "pytest", "-q", "-x", "-p", "no:cacheprovider", "test_gate.py"],
                          cwd=folder, capture_output=True, text=True)
    return done.returncode


def main():
    caught = 0
    with tempfile.TemporaryDirectory() as tmp:
        clean = pathlib.Path(tmp) / "clean"
        clean.mkdir()
        for name in FILES:
            shutil.copy(HERE / name, clean / name)
        print(f"unmodified code: pytest exit {run(clean)}")
        for number, (label, filename, old, new) in enumerate(MUTANTS, 1):
            folder = pathlib.Path(tmp) / f"m{number}"
            folder.mkdir()
            for name in FILES:
                shutil.copy(HERE / name, folder / name)
            text = (folder / filename).read_text(encoding="utf-8")
            assert text.count(old) == 1, (label, text.count(old))
            (folder / filename).write_text(text.replace(old, new), encoding="utf-8")
            failed = run(folder) != 0
            caught += failed
            print(f"{number:2}. {'caught  ' if failed else 'SURVIVED'} {label}")
    print(f"\n{caught} of {len(MUTANTS)} planted bugs caught")


if __name__ == "__main__":
    main()
python mutants.py
unmodified code: pytest exit 0
 1. caught   normalize forgets lower case
 2. caught   ultranormalize forgets o -> 0
 3. caught   skeleton forgets repeated letters
 4. caught   osa has no swap
 5. caught   osa result is not capped at limit + 1
 6. caught   osa length filter is off by one
 7. caught   neighbors1 drops the swap
 8. caught   neighbors1 never inserts at the end
 9. caught   a protected name is its own squat
10. caught   edit rule starts at seven letters
11. caught   allowlist is not normalized
12. caught   a young project is 90 days or less
13. caught   a missing project is only a review
14. caught   a young unrelated project is allowed
15. caught   inline comments are kept

15 of 15 planted bugs caught

All 15 planted bugs were caught. An earlier version of this list had a mutant that survived: a stricter early-exit rule in osa_distance that kept looking at two rows instead of one. In a throwaway script I compared the two versions on every pair of strings of two to six letters over a three-letter alphabet, with limits of 1 and 2, and the answers never differed. The reason is that the smallest value in a row is at most one more than the smallest value in the row before it, so when a row is above the limit, the row before it was at least at the limit, and a swap, which reaches back two rows and adds one edit, cannot bring the answer under the limit. I simplified the code and dropped the mutant. A surviving mutant means either a test is missing or the code you planted a bug in does not matter, and it is worth finding out which.

Put the gate where the install happens

A gate only helps if it runs before the install. Two places matter. In your CI pipeline or install script, run the gate first and install only if it exits with 0, for example:

python gate.py requirements.txt --fail-on block && python -m pip install -r requirements.txt

That line uses the && operator of bash and of PowerShell 7 and later; in Windows PowerShell 5.1, run the gate first and test $LASTEXITCODE. --fail-on block lets review lines through; the default --fail-on review stops on both. The second place is an AI coding agent’s tool: if an agent can run pip install, make the agent call the gate on the name first and refuse on a block. Our agent harness tutorial shows where such a check goes. When the gate asks for review, a person adds a line to the allowlist file, and the line stays in the repository as a record of who vouched for the name.

pip also has stronger controls that look at content instead of spelling. Its “Secure installs” page describes two: “Enable Hash-checking Mode” and “Disallow source distributions”. Hash-checking mode “uses local hashes, embedded in a requirements.txt file, to protect against remote tampering and network issues”. Combine the gate with both, plus a dependency cooldown and a periodic SBOM and pip-audit check. The gate stops a bad name at the door; the others help when a good name goes bad.

Common mistakes

  • Comparing names before normalizing them. Flask_Login and flask-login are one project. Normalize both sides first, as every function here does.
  • Using “contains” or “extra words” rules. Step 6 shows they flag honest plugins far more often than squats.
  • Applying the edit rule to short names. More than one in five of the 1-to-3-letter ordinary names is one edit from a protected name.
  • Treating a popularity list as a trust list. A protected name is one worth imitating, not one that is safe; nine popular projects appear in the malicious-package reports because specific releases were compromised.
  • Letting the gate run pip on source packages while it resolves. Keep --only-binary :all: on the resolve step.
  • Never refreshing the popular list. The ranking is monthly. Re-run fetch_data.py with a newer commit when you want to track it.

What this gate cannot do

  • It sees about 6 percent of the malicious names. That is the share of the OSSF names that resemble a top-1,000 project, measured on one snapshot. Most of the OSSF names here do not look like a top-1,000 project, so the gate does not replace content checks.
  • It cannot see a good name that went bad. Nine names on both lists are real projects with compromised releases.
  • The test sets are imperfect. The OSSF list is a collection of reports, not a labelled typosquat set, and the ordinary names are survivors with a median age of 8.3 years in the flagged group. The age check’s cost on brand-new honest projects is unmeasured here; a new, honest look-alike goes to review or block until a person allowlists it.
  • The model experiment is small. Three small models, 30 tasks, two samples each.
  • It checks PyPI names only. npm, crates.io and others have their own rules and data, and I did not test them.
  • The PyPI comparison is a stand-in. PyPI’s production list (about 10,000 names ranked by dependents) is not public, so my numbers for its checks use the top 1,000 by downloads.

Where to go next

  • Replace the download ranking with names pulled from your own lock files, so the protected list is what your projects actually use.
  • Add a baseline: treat names already in last month’s requirements as trusted, and apply the strict checks only to names that are new to the repository.
  • Look at PyPI’s typosnyper source in Step 2 and port one of its checks that mine does not have, then measure whether it adds anything.
  • Run the Step 11 experiment on the model your own team uses, with tasks from your own codebase.
  • Read the project’s status marker. PEP 792 lets an index mark a project as quarantined when it is “generally unsafe for use”, and then the index offers no files for it. The live response for requests carries {'status': 'active'} under project-status. The PEP’s prose names that key project-status.state, but its JSON example and the live response use status, so read what the server really sends. Make the gate block a quarantined project and test it with FakeIndex.

Sources and method

  • Python Packaging User Guide, name normalization; PEP 503; PEP 691 and PEP 700 for the JSON Simple API and upload-time; PEP 792 for project status markers.
  • PyPI’s code, pypi/warehouse at commit d8c20b4f6e (November 20, 2026): typosnyper.py, tasks.py, services.py, utils/project.py and the ultranormalize migration; pull requests 10498, 17649 and 20387; PyPI help, choosing a name. I read the source; I did not observe PyPI’s production behavior.
  • Data: hugovk/top-pypi-packages (commit 29c0d4c38c) and ossf/malicious-packages (commit 76a57187b0).
  • pip documentation: installation report, pip install and secure installs.
  • Research paper: We Have a Package for You! A Comprehensive Analysis of Package Hallucinations by Code Generating LLMs (arXiv 2406.10279).
  • Ollama’s API documentation for the generate endpoint and its seed option.
  • Method and dates: all measurements were run on November 23, 2026 on Windows 11 with Python 3.13.14, pytest 9.2.0, rapidfuzz 3.14.6 (cross-check only) and Ollama 0.32.9. The squat candidates are the 12,058 OSSF names that are not on the top-15,000 list; the ordinary names are the 14,000 projects ranked 1,001 to 15,000. The PyPI lookups and the model answers are from that day and will change.

Tags:

AI AgentsEdit DistancepipPyPIPython PackagingSoftware Supply Chain SecurityTyposquatting

Share

Close-up of the cutting teeth of a paper shredder packed with shredded paper and colored scraps
Previous Post

Dragos’s Canaries Turn AI-Router Privacy Flags Into a Measurement, and OpenRouter’s Public ZDR List Shows the Label Sat on the MiniMax and Phala Routes Through October, Its 125 Removals Reproduce as Eight Providers’ Entire Lists, and the Post Later Dropped Its Vercel and OpenRouter Example

Rows of open sluice gates on a weir with water flowing through them, in Rožmitál pod Třemšínem, Czech Republic
Next Post

Norway’s National Security Authority Tells Every Azure API Management Customer to Assume Secrets Are Out, Microsoft’s Private Notice Limits Exposure to Classic Tiers That Skipped Its Guidance, and No CVE or Public Advisory Says What the Flaw Is

No Comment! Be the first one.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Latest
23 Nov
How to Test Kubernetes Admission Policies Without a Cluster: Write Kyverno ValidatingPolicies, Prove Them With kyverno test, and Gate Pull Requests in CI
23 Nov
DeepMind’s Quantum Agents Make Lean the Referee and the Headline Ratios Reproduce From the Released Files, but 260x of the Arcsin 290x Came From a Stage Classical Simulation Could Check, the 8x and 2.5x Use Refined Baselines, and the Fusion and Grover Figures Moved Between arXiv Versions
Trending
November 23, 2026
How to Test Kubernetes Admission Policies Without a Cluster: Write Kyverno ValidatingPolicies, Prove Them With kyverno test, and Gate Pull Requests in CI
November 23, 2026
DeepMind’s Quantum Agents Make Lean the Referee and the Headline Ratios Reproduce From the Released Files, but 260x of the Arcsin 290x Came From a Stage Classical Simulation Could Check, the 8x and 2.5x Use Refined Baselines, and the Fusion and Grover Figures Moved Between arXiv Versions
November 23, 2026
Norway’s National Security Authority Tells Every Azure API Management Customer to Assume Secrets Are Out, Microsoft’s Private Notice Limits Exposure to Classic Tiers That Skipped Its Guidance, and No CVE or Public Advisory Says What the Flaw Is
November 23, 2026
How to Stop pip From Installing a Typosquatted or Made-Up Package Name: Build a Name Gate in Python and Measure It on the 15,000 Most Downloaded PyPI Projects and 12,067 Names From OSSF’s Malicious-Package Reports
November 23, 2026
Dragos’s Canaries Turn AI-Router Privacy Flags Into a Measurement, and OpenRouter’s Public ZDR List Shows the Label Sat on the MiniMax and Phala Routes Through October, Its 125 Removals Reproduce as Eight Providers’ Entire Lists, and the Post Later Dropped Its Vercel and OpenRouter Example
November 23, 2026
Google Says a Suspected China-Nexus Group Exploited the vCenter Authentication Bypass in Early September, About Ten Weeks Before the Patch, but Broadcom’s Advisory Never Says It Was Exploited, the July Claim Rests on a Modifiable Build Timestamp, and the CVE Record Omits vCenter 7.0

Related Posts

A laptop wrapped in a chain and padlock, illustrating least-privilege controls for AI agents.
Learning Hub

How to Secure Tool-Using AI Agents Before They Touch Production

June 8, 2026
Colorful sticky notes arranged on an office wall, symbolizing governance checklists and planning.
Learning Hub

AI Governance for Agentic Apps: A Practical Checklist for Builders

June 8, 2026
A technician connects green fiber optic cables at a data center, representing a private production inference endpoint.
Learning Hub

How to Deploy a Fine-Tuned LLM Behind a Private Production Inference Endpoint

June 8, 2026
Narrow aisle behind black supercomputer racks in a data center
Learning Hub

Kubernetes SELinux Volume Labeling: What Cluster Operators Should Audit Before v1.37

June 8, 2026
SXZ.io SXZ.io
  • [email protected]

Categories

Articles
Learning Hub
News

All Rights Reserved by SXZ.io ©2026