Sub topic 8
Checking a Package Before You Install It
What this chapter assumes
You have used pip or npm to install packages. You know what PyPI and the npm registry are. You have asked an AI assistant for code that imports a library. The earlier chapters explained why models invent package names and how an attacker can register those names. This chapter covers the defender's side: the checks to run between "the assistant suggested a package" and "the package is installed."
What a check can and cannot tell you
No single check proves a package is safe. A check can only raise or lower your suspicion. Two questions matter most:
- Does this name exist on the registry at all?
- If it exists, does its history look like a real project, or like something registered last week?
The second question matters because slopsquatting works by registering the missing names. After an attacker registers a hallucinated name, a simple "does it exist?" check passes. Existence alone is therefore weak evidence. Age, history, and links to a real source repository are stronger.
Step 1: Confirm the name exists
On PyPI, a missing project returns HTTP 404 from the JSON API at https://pypi.org/pypi/<name>/json. On npm, npm view <name> fails with an E404 error.
A 404 is useful but incomplete:
- The name may be hallucinated. Do not install it, and do not try to "fix" it by guessing a similar name.
- The name may be real but absent from the registry you are querying. For example, an internal package lives on a private index.
- The name may be unregistered today and registered tomorrow by someone who saw the same model suggestion. Treat a 404 as a snapshot.
A 404 from the public registry for a name that your assistant presented as a well-known library is a clear warning. Ask the assistant for the library's official documentation URL, then read that page.
Step 2: Read the package's history
For a package that exists, look for these signals.
| Signal | Reassuring | Suspicious |
|---|---|---|
| First upload date | Months or years ago | Days or weeks ago |
| Release count | Many releases over time | One release, or several in one day |
| Source repository link | Points to a repository whose contents match the package | Missing, or points to an unrelated or empty repository |
| Maintainers | Known organization or long-standing individual | New account with no other projects |
| Install scripts | None, or well-explained build steps | Network calls, obfuscated code, `postinstall` that downloads files |
| Name fit | Matches the project's documentation exactly | Close to a popular name but not identical |
Download counts help only a little. Counts can be inflated, and a legitimate new package has low counts. Use them as one signal among several.
Metadata is written by the publisher. A malicious author can fill in a convincing description and link a real repository that is not theirs. The strongest check is to confirm the link in the other direction. Open the repository and see whether its README or documentation tells you to install this exact package name.
Checking PyPI with a script
The script below queries the PyPI JSON API for every name given on the command line. It prints the release count, the earliest upload time, and the home page. A 404 is reported as a possible hallucination.
import json
import re
import sys
import urllib.error
import urllib.request
NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")
def pypi_summary(name):
if not NAME_RE.fullmatch(name):
raise ValueError(f"invalid package name: {name!r}")
url = f"https://pypi.org/pypi/{name}/json"
try:
with urllib.request.urlopen(url, timeout=10) as resp:
data = json.load(resp)
except urllib.error.HTTPError as err:
if err.code == 404:
return None
raise
uploads = [
f["upload_time_iso_8601"]
for files in data["releases"].values()
for f in files
]
return {
"releases": len(data["releases"]),
"first_upload": min(uploads) if uploads else None,
"home_page": data["info"].get("home_page"),
}
if __name__ == "__main__":
for pkg in sys.argv[1:]:
info = pypi_summary(pkg)
if info is None:
print(f"{pkg}: NOT FOUND on PyPI (possible hallucination, do not install)")
else:
print(f"{pkg}: {info}")Save it as check_pypi.py and run it with the names you want to check:
python check_pypi.py requests some-name-the-assistant-suggestedSome points about how the script behaves:
- The name check comes first. The regular expression rejects anything that is not a plausible package name. This keeps odd characters, such as slashes or query strings, out of the URL you build from text that an assistant or a file supplied.
- It only reads data. The script never downloads or runs the package. It is safe to run on a name you do not trust.
first_uploadis the earliest file upload across all releases. The timestamps are ISO 8601 strings in the same format, sominpicks the oldest one. A date from this month on a package that claims to be a mature library is a red flag.home_pageis oftenNone. Many modern projects put their links inproject_urlsinstead. ANonehere is not suspicious by itself. Checkdata["info"]["project_urls"for more.- It does not judge. The script reports facts. You decide whether a package with 2 releases and a first upload nine days ago fits what you were told.
Extend the script as needed. A common addition is to compute the age in days and print a warning below a threshold your team picks.
Checking npm from the command line
npm has this built in. npm view reads registry metadata without installing anything.
# When was it created, and when was each version published?
npm view example-package time
# Where does the package say its source lives, and who maintains it?
npm view example-package repository.url maintainers
# Does it declare install-time scripts?
npm view example-package scriptsIn the time output, compare the created entry with the date of the first version. The scripts output matters most for risk. If it lists preinstall, install, or postinstall, read what they run before you proceed. Those scripts execute during installation, as covered earlier in this tutorial.
If you want to look at the actual contents, download the tarball without installing it:
npm pack example-package
tar -tzf example-package-*.tgznpm pack fetches the tarball and does not run its scripts. You can then list and read the files. For PyPI, pip download can run build code when it fetches a source distribution, so ask for wheels only:
pip download --only-binary=:all: --no-deps example-package -d /tmp/inspectA wheel is a pre-built archive, which pip unpacks without running the package's build code. Unzip it and read the files. If no wheel exists, the command fails. In that case, inspect the source distribution by downloading it directly from the PyPI page and not through pip.
Putting the checks in order
The diagram shows one reasonable order. Cheap checks come first and the expensive manual review comes last.
The "stop" branch matters as much as the others. When a name does not exist, the safe response is to find the correct library from an authoritative source. Do not search for the nearest-sounding name. Near matches are where typosquatting packages live.
Edge cases and common mistakes
- Name normalization. PyPI treats
My_Package,my-package, andmy.packageas the same project. The JSON API redirects these forms to the normalized name. A script that compares the name you typed with the name in the response can report a false mismatch. Compare normalized forms. - Similar names are not the same package.
python-dateutilanddateutilare different names. Always confirm that the name you check is the exact name you will put inrequirements.txt. - Scoped npm names. A name such as
@scope/pkgbelongs to an organization scope. An unscoped lookalike with the same suffix is not related to it. Verify the scope and the organization. - Transitive dependencies. A package you vet can depend on others you did not vet. Inspect the dependency list with
npm view example-package dependencies, or therequires_distfield in the PyPI JSON. A lockfile review (covered in the next chapter) covers the full tree. - Established packages can be compromised. A long history lowers risk from slopsquatting but does not remove supply-chain risk from account takeover. Pinning and review still apply.
- Old does not mean good. An attacker can register a name early and publish nothing malicious until a later release. Look at what changed in the most recent version, not only at the first upload date.
Making the check routine
Manual checks fail when they depend on memory. Build them into the workflow:
- Run your existence and age check as a pre-commit hook or CI job on any change to
requirements.txt,pyproject.toml, orpackage.json. - Require a human reviewer to approve any newly added dependency, not only version bumps.
- Keep a short team-approved list of packages for common tasks. When the assistant suggests something outside the list, the check is mandatory.
- When you run an assistant that can install packages itself, make it ask for approval first or restrict it to the approved list. The risk amplifiers earlier in this tutorial explain why.
Lockfiles and hash pinning, covered next, turn a one-time check into a lasting guarantee. They ensure that the package you vetted is the package you install later.
Exercise
Your assistant adds fastjson-utils to requirements.txt. check_pypi.py reports 1 release, a first upload 6 days ago, and a home_page of None. Should you install it? Name two further steps you would take.
Show answer
No, not yet. A single, very recent release with no home page matches the profile of a newly registered, possibly malicious name. Further steps: (1) look for an authoritative source that tells you to install this exact name, such as the documentation of the library you meant to use, and check that the repository exists and matches; (2) inspect the package without installing it, for example with pip download --only-binary=:all: --no-deps fastjson-utils -d /tmp/inspect and reading the unzipped files, and check project_urls in the JSON for repository links. If neither confirms legitimacy, reject it and use a well-known library instead.
Exercise
Why is a successful lookup (no 404) not enough to trust a package suggested by an AI assistant?
Show answer
Slopsquatting works by registering names that models hallucinate, so a hallucinated name can exist on the registry by the time you check. You also need age, release history, maintainer, and a source repository that confirms the package name, because those are harder for an attacker to fake.