Sub topic 8
Checking a Package Before You Install It
This chapter assumes you can use pip or npm, know what PyPI and the npm registry are, and have taken package suggestions from an AI coding assistant. It covers how to verify a suggested package before it reaches your machine.
Why verification is the key step
A model can suggest a name that does not exist. An attacker can register that name later. Your check is the last point where a person can catch the problem. After pip install or npm install runs, install-time code may already have executed.
Verification answers two separate questions:
- Does the package exist?
- If it exists, is it the package you meant, and does it look trustworthy?
A 404 answers the first question and is a strong warning. A successful lookup does not answer the second. A slopsquatted package exists by design, so "it installed fine" proves nothing.
Signals worth checking
Look at several signals together. No single one is decisive.
| Signal | Healthy sign | Warning sign |
|---|---|---|
| First upload date | Months or years ago | Days or weeks ago |
| Release count | Many releases over time | One or two releases |
| Source repository | Linked, active, and the repository links back to the package | Missing, or a repository that does not mention the package |
| Name match | Exactly the library you meant | Close to a famous library, or a generic name |
| Maintainers | Known individuals or organizations | Unknown account created recently |
| Downloads | Consistent with its claimed popularity | Very low for a "standard" library |
Treat age and sparse history as the cheapest signals to automate. Treat the source repository as the most informative signal to check by hand.
Checking a PyPI package with a script
PyPI offers a JSON API at https://pypi.org/pypi/<name>/json. The script below queries it for each name on the command line. A 404 is reported as a possible hallucination. Otherwise it prints the release count, first upload time, and home page, so a very new or sparse package stands out.
It validates the name with a regular expression first. This matters because the name is interpolated into a URL, and untrusted text should not be placed there unchecked.
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 python check_pypi.py requests some-invented-name. A long-established library shows many releases and an old first upload. A name with one release uploaded last week deserves a manual review.
Checking an npm package
For npm, npm view reads registry metadata without installing anything. The time field lists when the package was created and when each version was published.
# npm: inspect a suggested package, then install from the lockfile without running lifecycle scripts
npm view example-package time
npm ci --ignore-scriptsIf npm view reports an E404 error, the name is not in the registry. Treat that the same way as a PyPI 404. The second command installs only what package-lock.json specifies and skips preinstall and postinstall scripts, which are a common place for malicious code to run.
Common errors
- Trusting a hit as proof. Existence is not trust. Always check age, history, and repository.
- Trusting the home page field. The author sets it. Open the repository and confirm it points back to the same package name.
- Checking only the exact name. A real package may exist under a slightly different name than the one the model gave. Search the registry and compare.
- Skipping transitive dependencies. A vetted package can depend on an unvetted one. Review the lockfile diff, not just your direct additions.
- Verifying after installing. Run the check first. Install-time scripts can run before you look.
Exercise
An assistant suggests fastjson-utils-pro. Your PyPI check shows the package exists, has one release uploaded nine days ago, and has no home page. Should you install it? What would you do next?
Show answer
Do not install it yet. Existence only shows that someone registered the name, and a single recent release with no linked source is the pattern a slopsquatted package would show. Search for the well-known library that does what you need, read the package's files on PyPI, and look for a matching public repository. If you still need it, install it in a disposable environment and pin it with hashes after review.