Finds unused, missing and misplaced dependencies in a Python project: imports never declared, declared packages never imported, runtime code using dev-only packages, test-only runtime deps and requirements.txt vs pyproject.toml drift, with import-name mapping. Stdlib Python.
---
name: python-unused-and-missing-dependency-finder
description: Finds unused, missing and misplaced dependencies in a Python project: imports never declared, declared packages never imported, runtime code using dev-only packages, test-only runtime deps and requirements.txt vs pyproject.toml drift, with import-name mapping. Stdlib Python.
---
# Python Unused and Missing Dependency Finder
You help Python developers keep the list of dependencies honest. Over time projects collect packages nobody imports anymore (slower installs, a bigger attack surface, more security alerts), and code starts importing packages that were never declared and only work because they happen to be installed on the developer's laptop or come in through another package. Production then breaks with `ModuleNotFoundError` after an unrelated upgrade. You compare what the project declares with what its code really imports, explain every finding, and propose a small, safe cleanup.
An import scan is static: it cannot see plugins loaded by name, packages used only from the command line, database drivers chosen by a connection string, or code generated at runtime. Never delete a dependency only because the scan says "unused"; check it first and say how you checked.
## Files in this skill
- `scripts/dep_check.py` - parses requirements*.txt (with `-r` includes, extras, markers, URLs), pyproject.toml (`[project]` dependencies and optional-dependencies, `[dependency-groups]`, Poetry dependencies and groups) and every .py file with `ast` (never executes code); separates runtime code from tests, detects optional imports (`try/except ImportError`) and typing-only imports (`if TYPE_CHECKING`), skips the standard library and the project's own modules, maps import names to package names, and prints findings D01-D10 + E01; `--map`, `--ignore`, `--exclude`, `--use-installed`, `--format text|md|json|csv`, `--fail-on`, `--self-test` runs 31 checks (Python 3.8+ standard library only)
- `references/import-names-vs-package-names.md` - why `import yaml` means PyYAML, the common mismatches, and how to find the right name
- `references/false-positives-and-safe-removal.md` - when "unused" is not really unused, and a safe step-by-step removal routine
- `templates/dependency-cleanup-pr.md` - a pull request description for the cleanup with the evidence for each change
- `examples/shopapp/` - a small FastAPI shop project with a pyproject.toml, a pinned requirements.txt, two modules and one test file that contain one of each typical problem
## Workflow
### 1. Find the declarations
Ask where the project declares its dependencies and how it is installed in production (Docker image from `requirements.txt`, `pip install .`, Poetry, uv). Usual places:
```
pyproject.toml [project] dependencies, [project.optional-dependencies], [dependency-groups], [tool.poetry.*]
requirements.txt runtime (often pinned by pip-compile or uv export)
requirements-dev.txt tests, linters, type checkers (any requirements file with dev/test/lint/doc/ci in its name)
```
If the project uses a different layout, pass the files explicitly with `--requirements` and `--dev-requirements`.
### 2. Run the check
```
python3 scripts/dep_check.py . # auto-detects requirements*.txt and pyproject.toml
python3 scripts/dep_check.py . --format md > dependency-check.md
python3 scripts/dep_check.py . --requirements requirements/base.txt --dev-requirements requirements/test.txt
python3 scripts/dep_check.py . --exclude "scripts/*" --exclude "docs/*"
python3 scripts/dep_check.py . --map ruamel=ruamel.yaml --ignore psycopg2-binary
python3 scripts/dep_check.py . --use-installed # inside the project's virtualenv: map names via installed packages
python3 scripts/dep_check.py . --fail-on high # CI gate: fail on missing / dev-only runtime imports
python3 scripts/dep_check.py --self-test
```
Exit code 0 = fine (or `--fail-on none`, the default), 1 = findings at or above `--fail-on`, 2 = unreadable input.
| Code | Severity | Finding | Usual fix |
|---|---|---|---|
| D01 | high | runtime code imports a package that is not declared | declare it (with a sensible lower bound) |
| D02 | medium | tests import a package that is not declared | add it to the dev/test group |
| D03 | high | runtime code imports a package declared only as dev | move it to runtime dependencies |
| D04 | medium | runtime dependency never imported | check (see references), then remove |
| D05 | low | runtime dependency only imported by tests | move it to the dev/test group |
| D06 | info | optional import (try/except ImportError), not declared | declare it as an extra, document it |
| D07 | info | typing-only import, not declared | usually a stub package; add to dev if mypy needs it |
| D08 | info | runtime dependency that is a tool or server (uvicorn, gunicorn) | keep if production starts it from the command line |
| D09 | low | dev dependency never imported and not a known tool | check, then remove |
| D10 | low | requirements file and pyproject.toml lists have drifted | regenerate the pins or align the two lists |
| E01 | info | a file could not be parsed | fix the syntax error or exclude the file |
### 3. Check every finding before changing anything
Use `references/false-positives-and-safe-removal.md`. For each D04/D09 candidate search the repository for the package name outside Python imports (`grep -ri name Dockerfile Procfile *.cfg *.ini *.toml *.yaml .github`), check entry points and plugins (pytest plugins, SQLAlchemy dialects, Django `INSTALLED_APPS`, Celery brokers), and ask whether production runs it as a command. For D01 check if the package arrives only through another dependency today: that is exactly the fragile case to fix.
### 4. Propose the change
Group the changes: add missing (D01/D02/D03), move (D03/D05), remove after checks (D04/D09), document optional extras (D06), align pins (D10). Keep version ranges in pyproject.toml and exact pins only in the lock or requirements file. For every removal say how it was verified (tests pass in a fresh virtualenv, app starts, Docker image builds).
### 5. Verify in a clean environment
```
python3 -m venv /tmp/clean && /tmp/clean/bin/pip install -r requirements.txt && /tmp/clean/bin/python -c "import shopapp.api"
/tmp/clean/bin/pip install -e ".[dev]" && /tmp/clean/bin/python -m pytest -q
```
A fresh environment is the only reliable proof that nothing missing was hiding behind a package installed by hand.
### 6. Report
Fill `templates/dependency-cleanup-pr.md`: the findings table, each change with its evidence, what was deliberately kept and why, and the clean-environment test result.
## Rules
- Never remove a package on the scan result alone; show the check for each removal.
- Never run or import the project's code to find imports; the script only parses files.
- Treat missing runtime dependencies (D01, D03) as bugs: they decide whether a fresh deploy works.
- Do not upgrade versions as part of a cleanup; keep it a separate change.
- Respect the project's tool (pip-tools, Poetry, uv, Hatch); give commands for that tool, not a different one.
- Say clearly that dynamic imports, plugins and command-line tools are invisible to the scan.
FILE:references/import-names-vs-package-names.md
# Import names vs package names
The name you `pip install` (the distribution) and the name you `import` (the top-level module) are often different. A dependency checker has to translate between them, otherwise `PyYAML` looks unused and `yaml` looks undeclared at the same time.
## Common mismatches
| Import | Package on PyPI | Note |
|---|---|---|
| `yaml` | PyYAML | |
| `PIL` | Pillow | the old PIL package is dead |
| `sklearn` | scikit-learn | never install the `sklearn` placeholder package |
| `cv2` | opencv-python | also -headless and -contrib variants |
| `bs4` | beautifulsoup4 | |
| `dateutil` | python-dateutil | |
| `dotenv` | python-dotenv | |
| `jwt` | PyJWT | `jwt` on PyPI is a different library |
| `attr` | attrs | `import attrs` also works on newer versions |
| `Crypto` | pycryptodome | |
| `psycopg2` | psycopg2 or psycopg2-binary | |
| `google.protobuf` | protobuf | many `google.*` namespaces belong to different packages |
| `git` | GitPython | |
| `github` | PyGithub | |
| `fitz` | PyMuPDF | |
| `MySQLdb` | mysqlclient | |
## Name normalization
Package names are compared after PEP 503 normalization: lower case, and runs of `-`, `_` and `.` become one `-`. `Flask_SQLAlchemy`, `flask-sqlalchemy` and `flask.sqlalchemy` are the same package.
## Finding the right name for an unknown import
1. Inside the project's virtualenv: `python3 -c "from importlib.metadata import packages_distributions as p; print(p().get('yaml'))"` prints `['PyYAML']`. The script does this for every import with `--use-installed`.
2. `pip show -f <package>` lists the top-level modules a package installs.
3. On PyPI, check the project's "Homepage" and the import example in its README.
4. Add the answer to the run with `--map import_name=package-name` and, if it is common, to the mapping table in the script.
## Packages that are used without an import
- Servers and commands: uvicorn, gunicorn, celery workers, alembic, honcho.
- Plugins discovered by name: pytest-* plugins, flake8-* plugins, SQLAlchemy and Django database drivers named in a URL or a settings file, Jinja extensions.
- Stub packages for type checkers: types-requests, mypy-boto3-*.
- Packages needed by another import: FastAPI's and Starlette's `TestClient` need httpx; pandas needs openpyxl to read Excel files.
The script knows the common tools and a few implied packages, but every project has its own; treat its "unused" list as candidates, not as decisions.
FILE:references/false-positives-and-safe-removal.md
# False positives and safe removal
## Why a package can look unused but is needed
- **Started from the command line**: `uvicorn shopapp.api:app`, `gunicorn`, `celery -A app worker`, `alembic upgrade head`. Search the Dockerfile, Procfile, Makefile, compose files, systemd units and CI workflows.
- **Loaded by name**: pytest plugins (`pytest-cov`, `pytest-asyncio`), Django apps in `INSTALLED_APPS`, SQLAlchemy dialects in a database URL (`postgresql+psycopg2://`), logging handlers in a config file, Celery brokers (`redis://`), Jinja or Markdown extensions.
- **Imported dynamically**: `importlib.import_module(setting)`, entry points, plugin registries. The script only sees literal `import_module("name")` calls.
- **Needed by another import**: `fastapi.testclient` needs httpx, `pandas.read_excel` needs openpyxl, `requests[socks]` needs PySocks.
- **Pinned on purpose**: a transitive dependency pinned in the requirements file to fix a security issue or a bug (for example `urllib3`, `idna`). Keep it and add a comment with the reason.
- **Used in notebooks, scripts or docs that were excluded** from the scan.
## Why a package can look missing but is fine
- It is the project's own package with an unusual layout (pass `--exclude` or check that it lives in `src/` or the project root).
- It is only imported under `if TYPE_CHECKING:` (D07) or in a `try/except ImportError` block (D06).
- It is vendored inside the repository (then it is a local module; check the folder name).
## Safe removal routine
1. Search the whole repository for the package name and its import name, not only `.py` files: `git grep -n -i -e name -e import_name`.
2. Check the plugin and command-line cases above.
3. Remove it from the declaration (pyproject.toml and the requirements or lock file together).
4. Create a fresh virtualenv, install from the declarations only, then import the app, run the tests and, if there is one, build the Docker image.
5. Remove packages in small batches so a failure points to one change.
6. Write the evidence into the pull request (see the template).
## Missing dependencies are the urgent part
A package that is imported but not declared (D01) or declared only for development (D03) works on a laptop where someone installed it by hand, and fails on the next clean deploy. Fix those first, even if the cleanup of unused packages waits.
FILE:templates/dependency-cleanup-pr.md
# Dependency cleanup: {{project or package name}}
**Checked with:** `dep_check.py` on {{date}}, {{N}} Python files ({{M}} tests)
**Declarations:** {{pyproject.toml / requirements.txt / requirements-dev.txt}}
**Installed in production by:** {{Docker image from requirements.txt / pip install . / Poetry / uv}}
## Findings
| Code | Package | Finding | Decision |
|---|---|---|---|
| D01 | {{package}} | {{imported in file:line, not declared}} | {{add to runtime, >=x.y}} |
| D03 | {{package}} | {{runtime import, dev-only}} | {{move to runtime}} |
| D04 | {{package}} | {{never imported}} | {{remove / keep because ...}} |
## Changes
### Added
- `{{package}}>={{version}}` - imported by {{file}}; worked only because {{it came in through another package / was installed by hand}}.
### Moved
- `{{package}}` from {{dev}} to {{runtime}} (or the other way) - {{reason}}.
### Removed (with evidence)
- `{{package}}` - no import, no CLI use (searched Dockerfile, Procfile, CI), no plugin entry; tests pass without it.
### Kept on purpose
- `{{package}}` - {{started from the command line / plugin / pinned for a security fix}}.
## Verification
- Fresh virtualenv from the declarations only: {{pass/fail}}
- `python -c "import {{app}}"`: {{pass/fail}}
- Test suite: {{N passed}}
- Docker image build: {{pass/fail or not applicable}}
## Not covered by this check
- Dynamic imports and plugins loaded by name are invisible to a static scan; listed above what was checked by hand.
FILE:examples/shopapp/pyproject.toml
[project]
name = "shopapp"
version = "0.4.0"
description = "Order API and reports for a small online shop (example project)"
requires-python = ">=3.10"
dependencies = [
"fastapi>=0.110",
"pydantic>=2.6",
"sqlalchemy>=2.0",
"requests>=2.31",
"python-dateutil>=2.9",
"PyYAML>=6.0",
"pandas>=2.2",
"uvicorn[standard]>=0.29",
"faker>=24.0",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"pytest-cov>=5.0",
"ruff>=0.4",
"httpx>=0.27",
"freezegun>=1.4",
"openpyxl>=3.1",
"rich>=13.7",
]
[tool.ruff]
line-length = 100
FILE:examples/shopapp/requirements.txt
# pinned for the Docker image (generated by pip-compile, trimmed for the example)
fastapi==0.115.0
pydantic==2.9.2
sqlalchemy==2.0.35
requests==2.32.3
python-dateutil==2.9.0.post0
PyYAML==6.0.2
uvicorn[standard]==0.30.6
FILE:examples/shopapp/src/shopapp/__init__.py
"""shopapp - order API and reports for a small online shop (example project)."""
__version__ = "0.4.0"
FILE:examples/shopapp/src/shopapp/api.py
"""HTTP API for orders."""
import os
from datetime import datetime
import requests
import stripe
import yaml
from dateutil import parser as dateparser
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from sqlalchemy import create_engine, text
from shopapp import reports
app = FastAPI(title="shopapp")
engine = create_engine(os.environ.get("DATABASE_URL", "sqlite:///shop.db"))
stripe.api_key = os.environ.get("STRIPE_KEY", "")
with open(os.environ.get("SHOP_CONFIG", "config.yaml"), encoding="utf-8") as fh:
CONFIG = yaml.safe_load(fh) or {}
class Order(BaseModel):
id: int
email: str
total_cents: int
created_at: datetime
@app.get("/orders/{order_id}")
def get_order(order_id: int) -> Order:
with engine.connect() as conn:
row = conn.execute(text("select id, email, total_cents, created_at from orders where id = :id"), {"id": order_id}).first()
if row is None:
raise HTTPException(status_code=404, detail="order not found")
return Order(id=row[0], email=row[1], total_cents=row[2], created_at=dateparser.parse(str(row[3])))
@app.post("/orders/{order_id}/refund")
def refund(order_id: int) -> dict:
order = get_order(order_id)
stripe.Refund.create(payment_intent=str(order.id))
requests.post(CONFIG.get("webhook_url", "https://example.com/hook"), json={"refunded": order.id}, timeout=10)
return {"ok": True}
@app.get("/reports/daily.xlsx")
def daily_report() -> dict:
return {"path": reports.daily_sales_workbook()}
FILE:examples/shopapp/src/shopapp/reports.py
"""Sales reports: an Excel workbook and an optional upload to S3."""
from __future__ import annotations
import csv
import os
from typing import TYPE_CHECKING
from openpyxl import Workbook
try:
import boto3
except ImportError: # uploads are optional
boto3 = None
if TYPE_CHECKING:
from mypy_boto3_s3 import S3Client
def daily_sales_workbook(rows=None, path="daily_sales.xlsx"):
wb = Workbook()
ws = wb.active
ws.append(["order_id", "email", "total"])
for row in rows or []:
ws.append(row)
wb.save(path)
if boto3 is not None and os.environ.get("REPORT_BUCKET"):
client: S3Client = boto3.client("s3")
client.upload_file(path, os.environ["REPORT_BUCKET"], os.path.basename(path))
return path
def to_csv(rows, path="daily_sales.csv"):
with open(path, "w", newline="", encoding="utf-8") as fh:
csv.writer(fh).writerows(rows)
return path
FILE:examples/shopapp/tests/test_api.py
import pytest
import respx
from faker import Faker
from fastapi.testclient import TestClient
from freezegun import freeze_time
from shopapp.api import app
fake = Faker()
client = TestClient(app)
@freeze_time("2026-12-01 10:00:00")
def test_missing_order_returns_404():
assert client.get("/orders/999999").status_code == 404
@respx.mock
def test_refund_calls_webhook():
respx.post("https://example.com/hook").respond(200)
pytest.skip("needs a seeded database")
FILE:scripts/dep_check.py
#!/usr/bin/env python3
"""dep_check.py - find unused, missing and misplaced dependencies in a Python project.
Compares what a project declares (requirements*.txt, pyproject.toml: [project] dependencies,
optional-dependencies, [dependency-groups], Poetry dependencies and groups) with what its code
really imports (parsed with ast, never executed). Knows the usual import-name vs package-name
differences (yaml -> PyYAML, PIL -> Pillow, sklearn -> scikit-learn ...), skips the standard
library and the project's own modules, separates runtime code from tests, and understands
optional imports (try/except ImportError) and typing-only imports (if TYPE_CHECKING).
Usage:
dep_check.py PROJECT_DIR [--requirements FILE ...] [--dev-requirements FILE ...]
[--pyproject FILE] [--exclude GLOB ...] [--map IMPORT=PACKAGE ...]
[--ignore PACKAGE ...] [--use-installed] [--format text|md|json|csv]
[--fail-on none|info|low|medium|high]
dep_check.py --self-test
Exit: 0 ok, 1 findings at or above --fail-on, 2 unreadable input. Python 3.8+, standard library only
(tomllib is used on 3.11+, a small built-in reader for the needed tables otherwise).
"""
import argparse, ast, csv, fnmatch, io, json, os, re, sys
SEV = {"info": 0, "low": 1, "medium": 2, "high": 3}
# import name -> distribution name, for the common cases where they differ
IMPORT_TO_DIST = {
"yaml": "pyyaml", "PIL": "pillow", "sklearn": "scikit-learn", "cv2": "opencv-python",
"bs4": "beautifulsoup4", "dateutil": "python-dateutil", "dotenv": "python-dotenv",
"jwt": "pyjwt", "attr": "attrs", "Crypto": "pycryptodome", "serial": "pyserial",
"usb": "pyusb", "docx": "python-docx", "pptx": "python-pptx", "multipart": "python-multipart",
"jose": "python-jose", "slugify": "python-slugify", "gi": "pygobject", "OpenSSL": "pyopenssl",
"zmq": "pyzmq", "magic": "python-magic", "psycopg2": "psycopg2", "MySQLdb": "mysqlclient",
"google.protobuf": "protobuf", "googleapiclient": "google-api-python-client",
"telegram": "python-telegram-bot", "discord": "discord-py", "win32api": "pywin32",
"win32com": "pywin32", "skimage": "scikit-image", "Levenshtein": "levenshtein",
"fitz": "pymupdf", "lxml": "lxml", "markdown": "markdown", "dns": "dnspython",
"nacl": "pynacl", "socks": "pysocks", "Xlib": "python-xlib", "pkg_resources": "setuptools",
"setuptools": "setuptools", "ldap": "python-ldap", "jinja2": "jinja2", "kafka": "kafka-python",
"sentry_sdk": "sentry-sdk", "dateparser": "dateparser", "tz": "pytz", "pytz": "pytz",
"rest_framework": "djangorestframework", "flask_sqlalchemy": "flask-sqlalchemy",
"flask_cors": "flask-cors", "github": "pygithub", "git": "gitpython", "editor": "python-editor",
}
# distributions that provide one of several import names (alternatives count as the same package)
DIST_ALIASES = {"psycopg2-binary": "psycopg2", "opencv-python-headless": "opencv-python",
"opencv-contrib-python": "opencv-python", "pillow-simd": "pillow",
"pyjwt": "pyjwt", "tensorflow-cpu": "tensorflow"}
# installed and used as tools, plugins, servers or stubs, never imported by application code
TOOL_PREFIXES = ("types-", "pytest-", "flake8-", "mypy-", "sphinx-", "pre-commit", "mkdocs-")
TOOLS = {"pytest", "black", "ruff", "mypy", "flake8", "isort", "pylint", "coverage", "tox", "nox",
"pre-commit", "build", "twine", "wheel", "setuptools", "pip", "pip-tools", "hatch",
"hatchling", "poetry", "poetry-core", "sphinx", "mkdocs", "mkdocs-material", "bandit",
"safety", "pip-audit", "invoke", "ipython", "jupyter", "notebook", "jupyterlab",
"gunicorn", "uvicorn", "hypercorn", "daphne", "waitress", "supervisor", "honcho",
"watchdog", "python-dotenv-cli", "alembic", "celery-flower", "flower", "debugpy",
"commitizen", "towncrier", "bump-my-version", "bumpversion", "pyright", "codespell"}
# imports that need another package which is never imported by name
IMPLIED = {"fastapi.testclient": ["httpx"], "starlette.testclient": ["httpx"],
"pandas.io.excel": ["openpyxl"], "uvicorn.workers": ["gunicorn"]}
STD_FALLBACK = set("""__future__ abc argparse array ast asyncio base64 bisect builtins bz2 calendar
cmath collections concurrent configparser contextlib contextvars copy csv ctypes dataclasses datetime
decimal difflib dis email encodings enum errno faulthandler fnmatch fractions ftplib functools gc
getpass gettext glob gzip hashlib heapq hmac html http imaplib importlib inspect io ipaddress
itertools json keyword linecache locale logging lzma mailbox math mimetypes multiprocessing netrc
numbers operator os pathlib pickle pkgutil platform plistlib pprint profile pstats queue random re
sched secrets select selectors shelve shlex shutil signal site smtplib socket socketserver sqlite3
ssl stat statistics string struct subprocess sys sysconfig tarfile tempfile textwrap threading time
timeit tkinter token tokenize tomllib trace traceback types typing unicodedata unittest urllib uuid
venv warnings wave weakref webbrowser wsgiref xml xmlrpc zipfile zipimport zlib zoneinfo""".split())
STDLIB = set(getattr(sys, "stdlib_module_names", ())) or STD_FALLBACK
SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", ".env", "node_modules", "__pycache__", ".tox",
".nox", "build", "dist", ".mypy_cache", ".pytest_cache", ".ruff_cache", "site-packages"}
def norm(name):
"""PEP 503 normalized distribution name."""
return re.sub(r"[-_.]+", "-", name.strip()).lower()
# ---------------------------------------------------------------- declared dependencies
REQ_NAME = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9._-]*)\s*(\[[^\]]*\])?\s*(.*)$")
def parse_req_line(line):
"""'requests[socks]>=2.31 ; python_version>="3.8"' -> ('requests', '>=2.31') or None."""
line = line.split(" #", 1)[0].strip()
if not line or line.startswith("#"):
return None
if " @ " in line: # name @ url
return norm(line.split(" @ ", 1)[0].split("[", 1)[0]), "@ url"
m = REQ_NAME.match(line.split(";", 1)[0])
if not m:
return None
return norm(m.group(1)), (m.group(3) or "").strip()
def read_requirements(path, seen=None):
"""Returns (deps {name: spec}, notes [str]). Follows -r / -c includes relative to the file."""
seen = seen if seen is not None else set()
path = os.path.abspath(path)
deps, notes = {}, []
if path in seen:
return deps, notes
seen.add(path)
with open(path, encoding="utf-8") as fh:
for raw in fh:
line = raw.strip()
if not line or line.startswith("#"):
continue
if line.startswith(("-r ", "--requirement ")):
inc = os.path.join(os.path.dirname(path), line.split(None, 1)[1].strip())
d, n = read_requirements(inc, seen)
deps.update(d); notes += n
continue
if line.startswith(("-c ", "--constraint ", "--index-url", "--extra-index-url", "-i ", "--find-links", "-f ", "--trusted-host", "--hash")):
continue
if line.startswith(("-e ", "--editable ")) or re.match(r"^(git\+|https?://|file:|\.{0,2}/)", line):
egg = re.search(r"#egg=([A-Za-z0-9._-]+)", line)
if egg:
deps[norm(egg.group(1))] = "editable/url"
else:
notes.append("%s: skipped line without a package name: %s" % (os.path.basename(path), line[:80]))
continue
r = parse_req_line(line)
if r:
deps[r[0]] = r[1]
else:
notes.append("%s: could not parse: %s" % (os.path.basename(path), line[:80]))
return deps, notes
def load_toml(path):
try:
import tomllib # Python 3.11+
with open(path, "rb") as fh:
return tomllib.load(fh)
except ImportError:
return mini_toml(open(path, encoding="utf-8").read())
def mini_toml(text):
"""Tiny TOML reader for 3.8-3.10: tables, dotted table names, strings, string arrays and inline
tables as strings. Enough for dependency tables; not a general TOML parser."""
data, cur = {}, None
cur = data
lines = text.splitlines()
i = 0
while i < len(lines):
line = lines[i].split("#", 1)[0].strip() if not lines[i].strip().startswith("#") else ""
i += 1
if not line:
continue
m = re.match(r"^\[\[?([^\]]+)\]\]?$", line)
if m:
cur = data
for part in [p.strip().strip('"') for p in m.group(1).split(".")]:
cur = cur.setdefault(part, {})
continue
if "=" not in line:
continue
key, val = [x.strip() for x in line.split("=", 1)]
key = key.strip('"')
if val.startswith("[") and not val.rstrip().endswith("]"):
while i < len(lines):
val += " " + lines[i].split("#", 1)[0].strip(); i += 1
if val.rstrip().endswith("]"):
break
if val.startswith("["):
cur[key] = re.findall(r'"([^"]*)"|\'([^\']*)\'', val)
cur[key] = [a or b for a, b in cur[key]]
elif val.startswith(("\"", "'")):
cur[key] = val[1:-1]
else:
cur[key] = val
return data
def read_pyproject(path):
"""Returns (runtime {name: spec}, dev {name: spec}, project_name or None)."""
try:
t = load_toml(path)
except ValueError as e:
raise ValueError("%s: %s" % (os.path.basename(path), e))
run, dev = {}, {}
proj = t.get("project", {}) or {}
for line in proj.get("dependencies", []) or []:
r = parse_req_line(line)
if r: run[r[0]] = r[1]
for group, lines in (proj.get("optional-dependencies", {}) or {}).items():
target = dev if re.search(r"dev|test|lint|doc|type|ci", group, re.I) else run
for line in lines or []:
r = parse_req_line(line)
if r: target.setdefault(r[0], r[1] + " [extra:%s]" % group)
for group, lines in (t.get("dependency-groups", {}) or {}).items():
for line in lines or []:
if isinstance(line, str):
r = parse_req_line(line)
if r: dev[r[0]] = r[1]
poetry = (t.get("tool", {}) or {}).get("poetry", {}) or {}
for name, spec in (poetry.get("dependencies", {}) or {}).items():
if name.lower() != "python":
run[norm(name)] = spec if isinstance(spec, str) else "poetry"
for name, spec in (poetry.get("dev-dependencies", {}) or {}).items():
dev[norm(name)] = spec if isinstance(spec, str) else "poetry"
for group in (poetry.get("group", {}) or {}).values():
for name, spec in ((group or {}).get("dependencies", {}) or {}).items():
dev[norm(name)] = spec if isinstance(spec, str) else "poetry"
return run, dev, proj.get("name") or poetry.get("name")
# ---------------------------------------------------------------- imports
class ImportVisitor(ast.NodeVisitor):
def __init__(self):
self.found = [] # (module, line, kind) kind: normal | optional | typing
self.optional = 0
self.typing = 0
def _add(self, mod, line):
kind = "typing" if self.typing else ("optional" if self.optional else "normal")
self.found.append((mod, line, kind))
def visit_Import(self, node):
for a in node.names:
self._add(a.name, node.lineno)
def visit_ImportFrom(self, node):
if node.level == 0 and node.module:
self._add(node.module, node.lineno)
def visit_Try(self, node):
catches = any(self._is_import_error(h.type) for h in node.handlers)
self.optional += catches
for n in node.body:
self.visit(n)
self.optional -= catches
for part in node.handlers + node.orelse + node.finalbody:
self.visit(part)
visit_TryStar = visit_Try
@staticmethod
def _is_import_error(t):
if t is None:
return True
names = [t] if not isinstance(t, ast.Tuple) else list(t.elts)
return any(isinstance(n, ast.Name) and n.id in ("ImportError", "ModuleNotFoundError", "Exception") for n in names)
def visit_If(self, node):
test = node.test
is_tc = (isinstance(test, ast.Name) and test.id == "TYPE_CHECKING") or \
(isinstance(test, ast.Attribute) and test.attr == "TYPE_CHECKING")
self.typing += is_tc
for n in node.body:
self.visit(n)
self.typing -= is_tc
for n in node.orelse:
self.visit(n)
def visit_Call(self, node):
# importlib.import_module("x") / __import__("x") with a literal name
f = node.func
name = f.attr if isinstance(f, ast.Attribute) else (f.id if isinstance(f, ast.Name) else "")
if name in ("import_module", "__import__") and node.args and isinstance(node.args[0], ast.Constant) \
and isinstance(node.args[0].value, str) and not node.args[0].value.startswith("."):
self._add(node.args[0].value, node.lineno)
self.generic_visit(node)
def is_test_file(rel):
parts = rel.replace("\\", "/").split("/")
base = parts[-1]
return any(p in ("tests", "test", "testing") for p in parts[:-1]) or base.startswith("test_") \
or base.endswith("_test.py") or base == "conftest.py"
def walk_py(root, excludes):
for d, dirs, files in os.walk(root):
dirs[:] = sorted(x for x in dirs if x not in SKIP_DIRS and not x.endswith(".egg-info"))
for f in sorted(files):
if f.endswith(".py"):
full = os.path.join(d, f)
rel = os.path.relpath(full, root).replace("\\", "/")
if any(fnmatch.fnmatch(rel, g) for g in excludes):
continue
yield full, rel
def local_modules(root, files):
"""Top-level names that belong to the project itself (packages, modules, src layout)."""
names = set()
for _, rel in files:
parts = rel.split("/")
if parts[0] in ("src", "lib") and len(parts) > 1:
parts = parts[1:]
names.add(parts[0][:-3] if parts[0].endswith(".py") else parts[0])
if len(parts) > 1 and parts[0] in ("tests", "test"):
names.add(parts[1][:-3] if parts[1].endswith(".py") else parts[1])
return names
def import_to_dist(mod, extra_map, installed):
top = mod.split(".")[0]
for key in (mod, ".".join(mod.split(".")[:2]), top):
if key in extra_map:
return norm(extra_map[key])
if key in IMPORT_TO_DIST:
return norm(IMPORT_TO_DIST[key])
if installed and top in installed:
return norm(installed[top][0])
return norm(top)
def same_pkg(a, b):
a, b = DIST_ALIASES.get(a, a), DIST_ALIASES.get(b, b)
return a == b
def is_tool(name):
return name in TOOLS or name.startswith(TOOL_PREFIXES)
# ---------------------------------------------------------------- analysis
def analyze(root, req_files=None, dev_req_files=None, pyproject=None, excludes=(), extra_map=None,
ignore=(), use_installed=False):
root = os.path.abspath(root)
if not os.path.isdir(root):
raise FileNotFoundError("project directory not found: %s" % root)
extra_map = dict(extra_map or {})
notes, runtime, dev, sources = [], {}, {}, {}
# discover declaration files
if req_files is None and dev_req_files is None:
req_files, dev_req_files = [], []
for f in sorted(os.listdir(root)):
if re.match(r"^requirements.*\.(txt|in)$", f):
(dev_req_files if re.search(r"dev|test|lint|doc|ci", f) else req_files).append(os.path.join(root, f))
for f in req_files or []:
d, n = read_requirements(f); notes += n
for k, v in d.items():
runtime[k] = v; sources.setdefault(k, []).append(os.path.basename(f))
for f in dev_req_files or []:
d, n = read_requirements(f); notes += n
for k, v in d.items():
dev[k] = v; sources.setdefault(k, []).append(os.path.basename(f))
pp = pyproject or os.path.join(root, "pyproject.toml")
project_name, req_run = None, dict(runtime)
pp_run = {}
if os.path.exists(pp):
r, d, project_name = read_pyproject(pp)
pp_run = {k: v for k, v in r.items() if "extra:" not in v}
for k, v in r.items():
runtime.setdefault(k, v); sources.setdefault(k, []).append("pyproject.toml")
for k, v in d.items():
dev.setdefault(k, v); sources.setdefault(k, []).append("pyproject.toml (dev)")
if not runtime and not dev:
notes.append("no dependency declarations found (requirements*.txt or pyproject.toml)")
installed = {}
if use_installed:
try:
from importlib.metadata import packages_distributions
installed = packages_distributions()
except Exception as e: # pragma: no cover
notes.append("--use-installed not available: %s" % e)
files = list(walk_py(root, excludes))
local = local_modules(root, files)
if project_name:
local.add(project_name.replace("-", "_"))
uses = {} # dist -> list of (rel, line, kind, is_test, module)
implied = {} # dist -> uses through another import (e.g. httpx via fastapi.testclient)
parse_errors = []
for full, rel in files:
try:
tree = ast.parse(open(full, encoding="utf-8").read(), filename=rel)
except (SyntaxError, UnicodeDecodeError) as e:
parse_errors.append((rel, str(e).split("\n")[0])); continue
v = ImportVisitor(); v.visit(tree)
for mod, line, kind in v.found:
top = mod.split(".")[0]
if top in STDLIB or top in local or top.startswith("_"):
continue
dist = import_to_dist(mod, extra_map, installed)
uses.setdefault(dist, []).append((rel, line, kind, is_test_file(rel), mod))
for key, extra_pkgs in IMPLIED.items():
if mod == key or mod.startswith(key + "."):
for x in extra_pkgs:
implied.setdefault(norm(x), []).append((rel, line, kind, is_test_file(rel), mod))
ignore = {norm(x) for x in ignore}
def declared_as(dist):
for k in runtime:
if same_pkg(k, dist): return "runtime", k
for k in dev:
if same_pkg(k, dist): return "dev", k
return None, None
findings = []
def add(code, sev, pkg, msg, where=None):
if pkg in ignore: return
findings.append({"code": code, "severity": sev, "package": pkg, "message": msg, "where": where or []})
for dist in sorted(uses):
u = uses[dist]
run_u = [x for x in u if not x[3] and x[2] == "normal"]
opt_u = [x for x in u if not x[3] and x[2] == "optional"]
typ_u = [x for x in u if not x[3] and x[2] == "typing"]
test_u = [x for x in u if x[3]]
kind, decl = declared_as(dist)
loc = lambda xs: ["%s:%d" % (x[0], x[1]) for x in xs[:5]]
mods = sorted({x[4].split(".")[0] for x in u})
hint = "" if mods == [dist] else " (import %s)" % ", ".join(mods)
if kind is None:
if run_u:
add("D01", "high", dist, "imported by runtime code but not declared%s" % hint, loc(run_u))
elif opt_u:
add("D06", "info", dist, "optional import (try/except ImportError) not declared; consider an extra%s" % hint, loc(opt_u))
elif test_u:
add("D02", "medium", dist, "imported by tests but not declared as a dev/test dependency%s" % hint, loc(test_u))
elif typ_u:
add("D07", "info", dist, "imported only under TYPE_CHECKING and not declared; fine if a stub or dev dependency provides it%s" % hint, loc(typ_u))
elif kind == "dev" and run_u:
add("D03", "high", decl, "imported by runtime code but declared only as a dev dependency; it will be missing in production%s" % hint, loc(run_u))
elif kind == "runtime" and not run_u and not opt_u and test_u and not typ_u:
add("D05", "low", decl, "declared as a runtime dependency but only imported by tests; move it to dev/test%s" % hint, loc(test_u))
used_dists = set(uses) | set(implied)
if req_run and pp_run:
for name in sorted(set(pp_run) - set(req_run)):
if any(same_pkg(name, d) for d in used_dists) or not is_tool(name):
add("D10", "low", name, "declared in pyproject.toml but missing from the requirements file(s); installs from the requirements file (e.g. a Docker image) will not get it")
for name in sorted(set(req_run) - set(pp_run)):
add("D10", "low", name, "pinned in the requirements file(s) but not declared in pyproject.toml; the two lists have drifted")
both = sorted(set(req_run) & set(pp_run))
if both:
notes.append("%d packages appear in both the requirements file(s) and pyproject.toml (pins vs ranges is normal; keep them in sync): %s" % (len(both), ", ".join(both)))
for name in sorted(runtime):
if not any(same_pkg(name, d) for d in used_dists):
if is_tool(name):
add("D08", "info", name, "runtime dependency that is a tool, server or plugin and is never imported; check that production really needs it (e.g. an ASGI or WSGI server started from the command line)")
else:
add("D04", "medium", name, "declared as a runtime dependency but never imported (check plugins, entry points, CLI use or dynamic imports before removing)")
for name in sorted(dev):
if not any(same_pkg(name, d) for d in used_dists) and not is_tool(name):
add("D09", "low", name, "declared as a dev dependency but never imported and not a known tool")
for rel, err in parse_errors:
add("E01", "info", rel, "could not parse file, imports not checked: %s" % err)
findings.sort(key=lambda f: (-SEV[f["severity"]], f["code"], f["package"]))
summary = {"project": root, "python_files": len(files), "test_files": sum(1 for _, r in files if is_test_file(r)),
"declared_runtime": len(runtime), "declared_dev": len(dev), "imported_packages": len(uses),
"by_severity": {s: sum(1 for f in findings if f["severity"] == s) for s in ("high", "medium", "low", "info")}}
return {"summary": summary, "findings": findings, "notes": notes,
"declared": {"runtime": runtime, "dev": dev, "sources": sources},
"imports": {d: [{"file": x[0], "line": x[1], "kind": x[2], "test": x[3], "module": x[4]} for x in u] for d, u in sorted(uses.items())}}
# ---------------------------------------------------------------- output
def render(res, fmt):
s, F = res["summary"], res["findings"]
if fmt == "json":
return json.dumps(res, indent=2)
if fmt == "csv":
out = io.StringIO(); w = csv.writer(out)
w.writerow(["code", "severity", "package", "message", "where"])
for f in F:
w.writerow([f["code"], f["severity"], f["package"], f["message"], " ".join(f["where"])])
return out.getvalue().rstrip("\n")
md = fmt == "md"
L = []
L.append("## Dependency check" if md else "Dependency check")
L.append("%s files scanned (%d tests), %d runtime + %d dev dependencies declared, %d third-party packages imported" % (
s["python_files"], s["test_files"], s["declared_runtime"], s["declared_dev"], s["imported_packages"]))
b = s["by_severity"]
L.append("Findings: %d high, %d medium, %d low, %d info" % (b["high"], b["medium"], b["low"], b["info"]))
L.append("")
if md:
L += ["| Code | Severity | Package | Finding | Where |", "|---|---|---|---|---|"]
for f in F:
L.append("| %s | %s | `%s` | %s | %s |" % (f["code"], f["severity"], f["package"], f["message"], ", ".join(f["where"]) or "-"))
else:
L.append("Findings")
for f in F:
L.append(" %s %-6s %-22s %s" % (f["code"], f["severity"], f["package"], f["message"]))
if f["where"]:
L.append(" at " + ", ".join(f["where"]))
if not F:
L.append(" none")
if res["notes"]:
L += ["", "### Notes" if md else "Notes"] + ["- " + n for n in res["notes"]]
return "\n".join(L)
# ---------------------------------------------------------------- self-test
def self_test():
import tempfile, shutil
checks = []
def ok(name, cond):
checks.append((name, bool(cond)))
ok("norm", norm("Py_YAML.x") == "py-yaml-x")
ok("req line extras/markers", parse_req_line('requests[socks]>=2.31 ; python_version>="3.8"') == ("requests", ">=2.31"))
ok("req line url", parse_req_line("mypkg @ https://x/y.whl")[0] == "mypkg")
ok("req comment", parse_req_line("# hi") is None)
ok("map yaml", import_to_dist("yaml", {}, {}) == "pyyaml")
ok("map dotted", import_to_dist("google.protobuf.json_format", {}, {}) == "protobuf")
ok("map override", import_to_dist("foo.bar", {"foo": "Foo-Lib"}, {}) == "foo-lib")
ok("alias psycopg2-binary", same_pkg("psycopg2-binary", "psycopg2"))
ok("tool prefix", is_tool("pytest-cov") and is_tool("types-requests") and not is_tool("requests"))
ok("test file", is_test_file("tests/test_a.py") and is_test_file("pkg/conftest.py") and not is_test_file("pkg/a.py"))
t = mini_toml('[project]\nname = "x"\ndependencies = [\n "a>=1",\n "b",\n]\n[project.optional-dependencies]\ndev = ["pytest"]\n')
ok("mini toml", t["project"]["dependencies"] == ["a>=1", "b"] and t["project"]["optional-dependencies"]["dev"] == ["pytest"])
v = ImportVisitor()
v.visit(ast.parse("import a\ntry:\n import b\nexcept ImportError:\n b = None\nif TYPE_CHECKING:\n import c\nfrom . import d\nimport importlib\nimportlib.import_module('e')\n"))
kinds = {m: k for m, _, k in v.found}
ok("visitor kinds", kinds.get("a") == "normal" and kinds.get("b") == "optional" and kinds.get("c") == "typing" and "d" not in kinds and kinds.get("e") == "normal")
tmp = tempfile.mkdtemp()
try:
os.makedirs(os.path.join(tmp, "src", "app")); os.makedirs(os.path.join(tmp, "tests"))
open(os.path.join(tmp, "requirements.txt"), "w").write("requests==2.31\nPyYAML>=6\nunusedlib\ngunicorn\n-r requirements-extra.txt\n")
open(os.path.join(tmp, "requirements-extra.txt"), "w").write("psycopg2-binary\n")
open(os.path.join(tmp, "requirements-dev.txt"), "w").write("pytest\nruff\nhttpx\nnever-used-dev\n")
open(os.path.join(tmp, "src", "app", "__init__.py"), "w").write("")
open(os.path.join(tmp, "src", "app", "main.py"), "w").write("import os, json\nimport requests\nimport yaml\nimport psycopg2\nimport httpx\nimport attr\nfrom app import util\ntry:\n import ujson\nexcept ImportError:\n ujson = None\n")
open(os.path.join(tmp, "src", "app", "util.py"), "w").write("def f(:\n")
open(os.path.join(tmp, "tests", "test_main.py"), "w").write("import pytest\nimport respx\nfrom app import main\n")
r = analyze(tmp)
codes = {(f["code"], f["package"]) for f in r["findings"]}
ok("D01 missing attrs", ("D01", "attrs") in codes)
ok("D03 dev-only httpx used at runtime", ("D03", "httpx") in codes)
ok("D04 unused", ("D04", "unusedlib") in codes)
ok("D08 server tool", ("D08", "gunicorn") in codes)
ok("D02 test import undeclared", ("D02", "respx") in codes)
ok("D06 optional", ("D06", "ujson") in codes)
ok("D09 unused dev", ("D09", "never-used-dev") in codes and ("D09", "ruff") not in codes)
ok("include + alias used", not any(f["package"] == "psycopg2-binary" for f in r["findings"]))
ok("yaml mapped, no false D01", ("D01", "yaml") not in codes and ("D04", "pyyaml") not in codes)
ok("E01 parse error", ("E01", "src/app/util.py") in codes)
ok("local + stdlib ignored", not any(f["package"] in ("os", "json", "app") for f in r["findings"]))
r2 = analyze(tmp, ignore=["attrs"])
ok("ignore", not any(f["package"] == "attrs" for f in r2["findings"]))
ok("sorted high first", r["findings"][0]["severity"] == "high")
t2 = os.path.join(tmp, "p2"); os.makedirs(os.path.join(t2, "tests"))
open(os.path.join(t2, "pyproject.toml"), "w").write('[project]\nname = "p2"\ndependencies = ["requests>=2", "fastapi"]\n[project.optional-dependencies]\ntest = ["httpx", "pytest"]\n')
open(os.path.join(t2, "requirements.txt"), "w").write("requests==2.32.3\nidna==3.7\n")
open(os.path.join(t2, "p2.py"), "w").write("import requests\nimport fastapi\n")
open(os.path.join(t2, "tests", "test_p2.py"), "w").write("from fastapi.testclient import TestClient\nimport p2\n")
c2 = {(f["code"], f["package"]) for f in analyze(t2)["findings"]}
ok("D10 drift both ways", ("D10", "fastapi") in c2 and ("D10", "idna") in c2 and ("D10", "requests") not in c2)
ok("implied httpx via TestClient", ("D09", "httpx") not in c2)
ok("project module p2 is local", not any(f["package"] == "p2" for f in analyze(t2)["findings"]))
ok("csv render", render(r, "csv").splitlines()[0].startswith("code,severity"))
ok("json render", json.loads(render(r, "json"))["summary"]["python_files"] == 4)
ok("explicit files override auto-detect", not analyze(tmp, [os.path.join(tmp, "requirements-dev.txt")], [])["declared"]["dev"])
finally:
shutil.rmtree(tmp)
bad = [n for n, c in checks if not c]
if bad:
print("self-test FAILED: " + ", ".join(bad)); return 1
print("self-test OK: %d checks" % len(checks)); return 0
def main(argv=None):
ap = argparse.ArgumentParser(description="Find unused, missing and misplaced Python dependencies.")
ap.add_argument("project", nargs="?")
ap.add_argument("--requirements", action="append", help="runtime requirements file (repeatable); default: auto-detect")
ap.add_argument("--dev-requirements", action="append", help="dev/test requirements file (repeatable)")
ap.add_argument("--pyproject", help="path to pyproject.toml (default: PROJECT/pyproject.toml)")
ap.add_argument("--exclude", action="append", default=[], help="glob of files to skip, relative to the project")
ap.add_argument("--map", action="append", default=[], help="IMPORT=PACKAGE mapping, e.g. --map ruamel=ruamel.yaml")
ap.add_argument("--ignore", action="append", default=[], help="package name to leave out of the findings")
ap.add_argument("--use-installed", action="store_true", help="also map import names with the current environment's installed packages")
ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
ap.add_argument("--fail-on", choices=["none", "info", "low", "medium", "high"], default="none")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.project:
ap.error("PROJECT directory is required")
extra = {}
for m in a.map:
if "=" not in m:
ap.error("--map needs IMPORT=PACKAGE, got %r" % m)
k, v = m.split("=", 1); extra[k.strip()] = v.strip()
req = a.requirements; dev = a.dev_requirements
if req is not None or dev is not None:
req, dev = req or [], dev or []
try:
res = analyze(a.project, req, dev, a.pyproject, a.exclude, extra, a.ignore, a.use_installed)
except (OSError, ValueError) as e:
print("error: %s" % e, file=sys.stderr); return 2
print(render(res, a.format))
if a.fail_on != "none" and any(SEV[f["severity"]] >= SEV[a.fail_on] for f in res["findings"]):
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
Reviews the changes between two npm package-lock.json files before a merge: added, removed, upgraded and downgraded packages, plus supply-chain red flags such as install scripts, git or foreign tarball sources, changed integrity hashes, major bumps, duplicates and copyleft licenses. Stdlib Python.
---
name: npm-lockfile-change-auditor
description: Reviews the changes between two npm package-lock.json files before a merge: added, removed, upgraded and downgraded packages, plus supply-chain red flags such as install scripts, git or foreign tarball sources, changed integrity hashes, major bumps, duplicates and copyleft licenses. Stdlib Python.
---
# npm Lockfile Change Auditor
You help developers and reviewers understand what a change to `package-lock.json` really installs. Lockfile diffs are thousands of lines long, so most people approve them without reading, and that is exactly where unexpected install scripts, packages pulled from a git repository or a random tarball host, silently republished versions and surprise major upgrades slip in. You compare the lockfile before and after the change, summarize it in a few lines, and point the reviewer at the handful of entries that deserve a human look.
You do not replace `npm audit`, a vulnerability database or a security review. A flag means "look at this", not "this is malicious": many legitimate packages (image and database drivers, for example) need install scripts. Never run, install or publish anything to check a package; read the lockfile, the package page and the source instead.
## Files in this skill
- `scripts/lockfile_diff.py` - compares two lockfiles (lockfileVersion 1, 2 or 3), lists added, removed, upgraded and downgraded packages with semver bump kind and direct/dev markers, and prints flags L01-L09 + E01 with a severity; `--format text|md|json`, `--fail-on` for CI, `--allow-scope` for your own scopes, `--self-test` runs 16 checks (Python 3.8+ standard library only)
- `references/lockfile-format.md` - how npm lockfiles are structured (v1 vs v2/v3), what `resolved`, `integrity`, `hasInstallScript`, `dev` and `link` mean, and how to get the "before" file from git
- `references/supply-chain-red-flags.md` - what each flag can mean, how to check it in a few minutes, and when it is fine
- `templates/lockfile-review-comment.md` - a short pull request comment for the reviewer or author
- `examples/package-lock.before.json`, `examples/package-lock.after.json` - a fictional shop front end before and after a dependency update (hashes are synthetic; `num-guard`, `fast-mirror-cache`, `pdf-forge-lite` and `tiny-color-utils` are made-up packages)
## Workflow
### 1. Get both lockfiles
In the repository, with the pull request branch checked out:
```
git show origin/main:package-lock.json > /tmp/lock.before.json
cp package-lock.json /tmp/lock.after.json
```
For a merge request from a fork, use the merge base: `git show $(git merge-base origin/main HEAD):package-lock.json`. If the project uses `npm-shrinkwrap.json`, compare that file instead. pnpm and Yarn lockfiles have other formats and are not supported.
### 2. Run the audit
```
python3 scripts/lockfile_diff.py /tmp/lock.before.json /tmp/lock.after.json
python3 scripts/lockfile_diff.py before.json after.json --format md > lockfile-review.md
python3 scripts/lockfile_diff.py before.json after.json --allow-scope @acme --registry https://npm.acme.internal/
python3 scripts/lockfile_diff.py before.json after.json --fail-on medium --max-added 40 # CI gate
python3 scripts/lockfile_diff.py --self-test
```
Exit code 0 = nothing at or above `--fail-on` (default high), 1 = findings at or above it, 2 = unreadable input.
| Code | Severity | Meaning |
|---|---|---|
| L01 | high | added or changed package runs an install script (`hasInstallScript`) |
| L02 | high | resolved from outside the allowed registries: git, GitHub, plain http, another tarball host, local path |
| L03 | high | same name and version, different integrity hash |
| L04 | medium | package has no integrity hash |
| L05 | medium | major upgrade of a direct dependency (0.x minor bumps count as major) |
| L06 | medium | any downgrade |
| L07 | low | a package is now installed in more versions than before |
| L08 | low | more than `--max-added` packages added (default 25) |
| L09 | medium | license changed, or a strong copyleft license (GPL, AGPL, SSPL) was added; LGPL is not flagged |
| E01 | low | lockfile entries that could not be parsed |
### 3. Investigate the flags
Work from high to low with `references/supply-chain-red-flags.md`:
- L01: is the package known to need a build step (native addons, binary downloads)? Read its `package.json` scripts on the registry page or in the source before installing. Unknown small packages with a postinstall script deserve the most attention.
- L02: was the git or tarball source added on purpose (a fork waiting for an upstream fix)? Prefer a published version; pin git sources to a full commit hash, never a branch.
- L03: never accept a changed hash for the same version without an explanation; reinstall from a clean cache and compare with the registry.
- L05/L06: check the changelog for breaking changes; ask why a downgrade happened (often a merge conflict resolved the wrong way).
- L07/L08: run `npm ls <name>` and `npm dedupe`; ask whether the new dependency is worth its tree.
- L09: check the license against your company policy before the code ships.
### 4. Report
Fill `templates/lockfile-review-comment.md` with the one-line summary, the high findings with what you checked, the medium findings with the decision, and a clear verdict: approve, approve after changes, or block until a question is answered. Keep the comment short; link to the full `--format md` output if needed.
## Rules
- Report what the lockfile says; do not guess that a package is malicious. Say what you checked and what is still unknown.
- Do not run `npm install` on an untrusted branch just to inspect it; `npm install --ignore-scripts` in a throwaway container is the safe way if you must.
- Treat your own scoped packages and private registry as trusted only when they are configured with `--allow-scope` and `--registry`.
- If a lockfile cannot be parsed (exit 2), say so and ask for the file instead of reviewing a partial diff.
FILE:references/lockfile-format.md
# npm lockfile format in short
## Versions
- **lockfileVersion 1** (npm 5-6): a nested `dependencies` map. Each entry has `version`, `resolved`, `integrity`, optional `dev`, and its own nested `dependencies` for copies that could not be hoisted. Git dependencies keep the git URL in `version`.
- **lockfileVersion 2** (npm 7-8): contains both the old `dependencies` map and the new flat `packages` map, so older npm versions can still read it.
- **lockfileVersion 3** (npm 9+): only the `packages` map. This is what most projects have today.
The script reads `packages` when present and falls back to `dependencies` for version 1 files.
## The `packages` map
Keys are install paths relative to the project root:
- `""` is the root project; its `dependencies`, `devDependencies` and `optionalDependencies` list the **direct** dependencies.
- `node_modules/express` is a hoisted copy at the top level.
- `node_modules/pdf-forge-lite/node_modules/ms` is a nested copy, installed because another version of `ms` already sits at the top.
- Workspace folders appear as `packages/web` with a matching `node_modules/web` entry that has `"link": true`.
## Fields that matter for review
| Field | Meaning | Review question |
|---|---|---|
| `version` | exact installed version | expected bump kind? |
| `resolved` | where the tarball comes from | registry, or git / other host / local path? |
| `integrity` | SRI hash (`sha512-...`) checked on install | present? changed for the same version? |
| `hasInstallScript` | the package defines preinstall, install or postinstall | known reason for a build step? |
| `dev`, `optional`, `peer` | install context | does a production image get it? |
| `license` | license string from the package manifest | allowed by policy? |
| `link` | symlink to a local folder (workspaces) | expected workspace? |
## Getting the "before" file
```
git show origin/main:package-lock.json > /tmp/lock.before.json # target branch
git show $(git merge-base origin/main HEAD):package-lock.json > /tmp/lock.base.json # branch point
```
Compare against the merge base when the target branch moved since the branch was created; otherwise unrelated updates from main show up as changes.
## Useful npm commands (read-only)
- `npm ls <name>` - why a package is installed and in which versions
- `npm view <name>@<version> scripts dist.integrity license repository` - registry metadata
- `npm explain <name>` - the dependency path to a package
- `npm ci --ignore-scripts` - install exactly from the lockfile without running scripts (use in a throwaway container)
FILE:references/supply-chain-red-flags.md
# Lockfile red flags: what they can mean and how to check
Spend a few minutes per high finding. Most flags have an ordinary explanation; the goal is that someone looked.
## L01 install script (high)
- **Can mean:** a native addon or binary download (image processing, database drivers, browser automation) - common and fine; or a small, unknown package running code on every developer machine and CI runner - the classic supply-chain attack path.
- **Check:** `npm view <pkg>@<ver> scripts`; read the script and what it downloads; check the repository, maintainers, weekly downloads and publish date. A brand-new version of a tiny package that suddenly gained a postinstall script is the strongest signal.
- **Fine when:** the package is well known for needing a build step and the script matches its documentation.
- **Reduce risk:** `npm ci --ignore-scripts` in CI where possible, plus an allow-list for packages that really need scripts.
## L02 source outside the registry (high)
- **Can mean:** a temporary fork, a private package served from another host, a dependency confusion attempt, or a typo in a registry setting.
- **Check:** who added it and why (commit message, PR description); for git sources make sure the URL pins a full commit hash, not a branch or tag that can move; for tarballs check the host.
- **Fine when:** the team owns the source and added it on purpose; then configure it with `--registry` or `--allow-scope` so the next run is quiet.
## L03 integrity changed for the same version (high)
- **Can mean:** the tarball was republished or tampered with, a mirror served a different file, or someone edited the lockfile by hand.
- **Check:** `npm view <pkg>@<ver> dist.integrity` and compare with both lockfiles; reinstall from a clean cache.
- **Never** accept this without an explanation.
## L04 no integrity hash (medium)
- **Can mean:** an old lockfile, a tarball URL dependency, or a hand-edited entry. Without a hash npm cannot verify the download.
- **Check:** regenerate the lockfile with a current npm and see whether the hash appears.
## L05 major upgrade of a direct dependency (medium)
- **Can mean:** breaking API changes (for example a package that became ESM-only), dropped Node versions, changed defaults.
- **Check:** the changelog or release notes between the two versions, the test results, and whether the code was updated for the new API.
## L06 downgrade (medium)
- **Can mean:** a merge conflict in the lockfile resolved the wrong way, a deliberate pin to avoid a broken release, or an accidental `npm install` with an older lockfile.
- **Check:** ask the author; deliberate pins deserve a comment in `package.json` or the PR.
## L07 duplicate versions (low)
- **Can mean:** a dependency needs an older or newer range. Duplicates grow bundle size and can break singletons (React, state libraries, plugins).
- **Check:** `npm ls <name>`; try `npm dedupe`; check whether the dependency that pulls the other version can be updated.
## L08 many packages added (low)
- **Can mean:** a heavy new dependency for a small feature.
- **Check:** is there a lighter alternative or a built-in API? How much does it add to install time and bundle size?
## L09 license (medium)
- **Can mean:** a strong copyleft license (GPL, AGPL, SSPL) that may conflict with how the product is distributed or hosted, or a license change between versions.
- **Check:** the company license policy; ask legal when unsure. LGPL and file-level copyleft (MPL) are usually acceptable for unmodified dependencies but follow your policy.
## Not covered by this skill
Known vulnerabilities (`npm audit`, OSV, GitHub Dependabot alerts), typosquatting detection by name similarity, maintainer account takeovers, and behavior of the code itself. Mention these limits in the review when the change is risky.
FILE:templates/lockfile-review-comment.md
### Lockfile review - {{branch or PR number}}
**Summary:** {{before}} -> {{after}} packages (+{{added}} / -{{removed}}, {{upgraded}} upgraded, {{downgraded}} downgraded). Findings: {{high}} high, {{medium}} medium, {{low}} low.
**High findings (checked):**
- `{{package}}` {{code}}: {{what the flag says}} - checked: {{what you looked at}} - result: {{ok / needs change / unknown}}
**Medium findings (decision):**
- `{{package}}` {{code}}: {{detail}} - {{accepted because ... / please ...}}
**Questions for the author:**
- {{question}}
**Verdict:** {{approve / approve after the changes above / blocked until the questions are answered}}
<sub>Generated with `lockfile_diff.py` ({{options used}}); flags are prompts for a human check, not proof of a problem. Known vulnerabilities are covered separately by {{npm audit / Dependabot / OSV}}.</sub>
FILE:examples/package-lock.before.json
{
"name": "shop-web",
"version": "1.8.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "shop-web",
"version": "1.8.0",
"license": "UNLICENSED",
"dependencies": {
"axios": "^1.6.8",
"chalk": "^4.1.2",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"lodash": "^4.17.21",
"num-guard": "^7.0.0"
},
"devDependencies": {
"eslint-plugin-shop": "^2.3.0"
}
},
"node_modules/axios": {
"version": "1.6.8",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.8.tgz",
"integrity": "sha512-h+pJqpknU/puknkW9gNz2SJzAC3yayISzJVs5NMocV9W8TtJgXtgkjSV1dV43UyCg3doAQHr5aHoGDltkR+9Qg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6"
}
},
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-tuZs5w21yj0mWJSFWzn/P1KbPjKDszFi8jUvyYwvFraLNC9SxaSFLxTd5j3J5sckjw1iQRUAlmZq36Sk8SCPsw==",
"license": "MIT"
},
"node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-IGyVRcglbQuX9vghGUdjPizKtlC9kF6pKI4iF0VbeM2D4OcU4I7EVNu7jF1NtCnvCg2K4VRgeCD4JBcMVJvekg==",
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/dotenv": {
"version": "16.4.5",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz",
"integrity": "sha512-FozMT1uEvHOVZ5j8YRBmYvqyYFwCw8U2EV3sB9duBP0B9RpzkMR99rEyqFUHj75jrN8yFRZRblpffavyTT3DHQ==",
"license": "BSD-2-Clause"
},
"node_modules/eslint-plugin-shop": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-shop/-/eslint-plugin-shop-2.3.0.tgz",
"integrity": "sha512-Nxo9SDdVqWsY3GgmyJeZJPHoGgIGS4qk5NvrHhwlKmvalrqVQdTlgYlv+/j9i5i9e0jFGijQP5wwrWRPpCXI3g==",
"license": "MIT",
"dev": true
},
"node_modules/express": {
"version": "4.19.2",
"resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz",
"integrity": "sha512-pK3Mp/RdynyDYm/vwEbzN3s024WaRmmBKhoHa/1MJYfDX39wcj3GhpP+ePsf50bSqMIu+2B3/bRfxCFnXNCW0g==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9"
}
},
"node_modules/follow-redirects": {
"version": "1.15.6",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.6.tgz",
"integrity": "sha512-tw23l2yC1J9sF5HNEgkG/stImEWD7XAr/WhWGjkP9/EawlvZDTyqzBjse0gwgoPXIsDpU2aaIs41w1icDCqoWg==",
"license": "MIT"
},
"node_modules/lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-fxzPxCwrTent7KYhmQeq0bJWwlz0JeL/i+kQPiTfMp16m0A2Xb0sMtBqoprlMokIPx1b6Wjvam1PKY+foW2HVQ==",
"license": "MIT"
},
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-GzDco1VK+DfxVedli4bMu6XC47vqtBmY8/ezspZotp8r4Hs/5pUXBizBu70MZuxmkTa9Zk713DWfcC47dVLcaA==",
"license": "MIT"
},
"node_modules/num-guard": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/num-guard/-/num-guard-7.0.0.tgz",
"integrity": "sha512-SA+dO/f3ji1Qn2qHJDKNw/pddElkUFmZ6xwnx9nA6u5/tn9eVFg4W6iWjpWLYqwuVZpdUIPAeoS+LOgYgjdlyA==",
"license": "MIT"
}
}
}
FILE:examples/package-lock.after.json
{
"name": "shop-web",
"version": "1.9.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "shop-web",
"version": "1.9.0",
"license": "UNLICENSED",
"dependencies": {
"axios": "^1.7.7",
"chalk": "^5.3.0",
"dotenv": "^15.0.1",
"express": "^4.21.1",
"fast-mirror-cache": "^0.9.2",
"lodash-es": "^4.17.21",
"num-guard": "^7.0.0",
"pdf-forge-lite": "^3.1.0",
"sharp": "^0.33.5",
"tiny-color-utils": "github:tinycolor-dev/tiny-color-utils#v1.2.0"
},
"devDependencies": {
"eslint-plugin-shop": "^2.3.0"
}
},
"node_modules/@img/sharp-libvips-linux-x64": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz",
"integrity": "sha512-KSKmbu86qbPDX2Fg7mzOJBqPzWFwm/vvgNWxV+OStenJTzTXEG23BY9IXodPqCj1I56IknMT0Yzc7FORZ8WizQ==",
"license": "LGPL-3.0-or-later",
"optional": true
},
"node_modules/axios": {
"version": "1.7.7",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.7.tgz",
"integrity": "sha512-gEwIsrhOaKnz/2O83q20UHMgotVsn+9mJP/UXM39JJvtKcv6dBDfWp07KyoFzp/L8B+2r2ARQT8NcfQt595rVw==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6"
}
},
"node_modules/chalk": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz",
"integrity": "sha512-kzbQJkH30MjQcVvUMzvngjj8dZquO6SGW8NZAqAzcdSQjq1lBnslgEv/t3pfD05FRRw+YVLBg1k5r1Xk//0DiA==",
"license": "MIT"
},
"node_modules/color": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz",
"integrity": "sha512-QAM/0AGs6Rbsjyd5RpCAMTvZBcJOlKnqDFo1U28hVQXIArfyMkRd5DgKSF2ACkmj3VDDB2FkuTdQsTohiI7uwg==",
"license": "MIT"
},
"node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-IGyVRcglbQuX9vghGUdjPizKtlC9kF6pKI4iF0VbeM2D4OcU4I7EVNu7jF1NtCnvCg2K4VRgeCD4JBcMVJvekg==",
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/detect-libc": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz",
"integrity": "sha512-b1oO5S/RaQ1B8eqrd/4rLs373tpfvrn9OJZjzfp6qbf1tWwHWe8flGoA1y61x1Q9Ir4ci6Vggf4dwEcmT31ZLg==",
"license": "Apache-2.0"
},
"node_modules/dotenv": {
"version": "15.0.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-15.0.1.tgz",
"integrity": "sha512-C2QtPIs33kljlM6z0PAcQLDm0vjzBA0j7eNcyuLZeMqzPvnEHUca+04HvUE+cBqsGP4Np7Aa0yKNLgiOEZVUfA==",
"license": "BSD-2-Clause"
},
"node_modules/eslint-plugin-shop": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-shop/-/eslint-plugin-shop-2.3.0.tgz",
"integrity": "sha512-Nxo9SDdVqWsY3GgmyJeZJPHoGgIGS4qk5NvrHhwlKmvalrqVQdTlgYlv+/j9i5i9e0jFGijQP5wwrWRPpCXI3g==",
"license": "MIT",
"dev": true
},
"node_modules/express": {
"version": "4.21.1",
"resolved": "https://registry.npmjs.org/express/-/express-4.21.1.tgz",
"integrity": "sha512-rAzf1CydYap1e4hQCgawnrbmFPhK3m5mqdtgbjAlrXv0/gw8R4LjfbRYlI6ep33Z4WjJBJf5F0iNXTYGtFezqA==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9"
}
},
"node_modules/fast-mirror-cache": {
"version": "0.9.2",
"resolved": "https://cdn.fastmirror.example/fast-mirror-cache-0.9.2.tgz",
"license": "MIT"
},
"node_modules/follow-redirects": {
"version": "1.15.9",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
"integrity": "sha512-Gup9VODh23XNgK9/olbrZz3eFBvVRw8uDLHmZXgxsibt93VvdzJnQ+Sic8dGACxqghxt8wjgbjkfyj5exQOM3g==",
"license": "MIT"
},
"node_modules/lodash-es": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz",
"integrity": "sha512-XSr9Mh++0EfIoxa8f08FovgmfZnC9S3Wu5cGGXLKtqurs7eIGuc69n+gTRYYq4fldrustqc/zTJf1Gp9hWSDgw==",
"license": "MIT"
},
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-GzDco1VK+DfxVedli4bMu6XC47vqtBmY8/ezspZotp8r4Hs/5pUXBizBu70MZuxmkTa9Zk713DWfcC47dVLcaA==",
"license": "MIT"
},
"node_modules/num-guard": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/num-guard/-/num-guard-7.0.0.tgz",
"integrity": "sha512-eCC5PP9eeiIfi59qfoUPSyvnSHliveOayW2MlGMo4vibNcHy+coWksCNDg9kMth0LXSSIFqGtYVAzIES3hGiwg==",
"license": "MIT"
},
"node_modules/pdf-forge-lite": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/pdf-forge-lite/-/pdf-forge-lite-3.1.0.tgz",
"integrity": "sha512-JR3M9MvN1ddgL4WBYkzdOhylzW8fXBVlgsoyVKr8/81lyNjESpI33qVl7MsG7Dr6gbcg4wR5Edp+IrsrULGUuw==",
"license": "AGPL-3.0-only",
"dependencies": {
"ms": "^2.1.3"
}
},
"node_modules/pdf-forge-lite/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-SNPMCfwMJciLloOwk1dR7uiNbEGq+2NV3Dxrg760V/KNK+Uq4w5U2vcmL31cswWNU1Fht3QgPY4jDq3ysrp7FQ==",
"license": "MIT"
},
"node_modules/semver": {
"version": "7.6.3",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz",
"integrity": "sha512-78L8GUmHBY1B5u6cHP5VdH/RoVks7Oiw8LRc6hpI1qLFY8RrEx8SZaLGZRRHduWjubYvBj9CMOawQM3Y7J1/HQ==",
"license": "ISC"
},
"node_modules/sharp": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz",
"integrity": "sha512-QuP41KmtRXiWMfiTQsT7tGQV872pcKpHPvNzOxXuizG9/ecgKUnjW5JV9PzgdaOTUsD6EeUh3wLwVLCfELm4Fg==",
"license": "Apache-2.0",
"hasInstallScript": true,
"dependencies": {
"color": "^4.2.3",
"detect-libc": "^2.0.3",
"semver": "^7.6.3"
}
},
"node_modules/tiny-color-utils": {
"version": "1.2.0",
"resolved": "git+ssh://git@github.com/tinycolor-dev/tiny-color-utils.git#3f9c2a1d8e7b6c5a4f3e2d1c0b9a8f7e6d5c4b3a",
"license": "MIT",
"hasInstallScript": true
}
}
}
FILE:scripts/lockfile_diff.py
#!/usr/bin/env python3
"""lockfile_diff.py - npm lockfile change auditor. Python 3.8+ standard library only.
Compares two npm lockfiles (package-lock.json or npm-shrinkwrap.json, lockfileVersion 1, 2 or 3)
and reports which installed packages were added, removed, upgraded or downgraded, plus supply-chain
and maintenance red flags that deserve a human look before the change is merged.
Typical use in a pull request:
git show origin/main:package-lock.json > /tmp/lock.before.json
lockfile_diff.py /tmp/lock.before.json package-lock.json
Usage:
lockfile_diff.py BEFORE AFTER [--registry https://registry.npmjs.org/] [--allow-scope @acme]
[--max-added 25] [--fail-on high|medium|low|none] [--format text|md|json]
lockfile_diff.py --self-test
Exit: 0 nothing at or above --fail-on (default high), 1 findings at or above it, 2 unreadable input.
Flags (severity):
L01 high added or changed package that runs an install script (hasInstallScript)
L02 high package resolved from outside the registry (git, GitHub, http(s) tarball, file/link)
L03 high same name and version but a different integrity hash (possible tampering or republish)
L04 medium package without an integrity hash (cannot be verified on install)
L05 medium major version upgrade of a direct dependency
L06 medium downgrade of any package
L07 low a package now installed in two or more versions (duplicate copies)
L08 low more than --max-added packages added in one change
L09 medium license changed, or a strong copyleft license (GPL, AGPL, SSPL) appears
E01 entries that could not be parsed (skipped)
"""
import argparse, json, re, sys
from urllib.parse import urlparse
SEV = {"L01": "high", "L02": "high", "L03": "high", "L04": "medium", "L05": "medium", "L06": "medium",
"L07": "low", "L08": "low", "L09": "medium", "E01": "low"}
RANK = {"none": 99, "high": 3, "medium": 2, "low": 1}
COPYLEFT = re.compile(r"\b(A?GPL|SSPL)", re.I)
def parse_version(v):
"""'1.2.3-beta.1' -> (1, 2, 3, 'beta.1'); returns None for non-semver strings."""
m = re.match(r"^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$", str(v or "").strip())
if not m:
return None
return int(m.group(1)), int(m.group(2)), int(m.group(3)), m.group(4) or ""
def cmp_version(a, b):
pa, pb = parse_version(a), parse_version(b)
if pa is None or pb is None:
return 0 if a == b else None
if pa[:3] != pb[:3]:
return -1 if pa[:3] < pb[:3] else 1
if pa[3] == pb[3]:
return 0
if not pa[3]:
return 1 # release > prerelease
if not pb[3]:
return -1
return -1 if pa[3] < pb[3] else 1
def bump_kind(old, new):
po, pn = parse_version(old), parse_version(new)
if po is None or pn is None:
return "other"
if pn[0] != po[0]:
return "major"
if pn[0] == 0 and pn[1] != po[1]:
return "major" # 0.x minor bumps are breaking by semver convention
if pn[1] != po[1]:
return "minor"
if pn[2] != po[2]:
return "patch"
return "prerelease"
def name_from_path(path):
"""'node_modules/a/node_modules/@s/b' -> '@s/b'."""
tail = path.split("node_modules/")[-1]
return tail.rstrip("/")
def load(path):
"""Return (entries, errors, meta). entries: {install_path: {name, version, resolved, integrity, license, script, dev, direct}}."""
with open(path, encoding="utf-8") as fh:
data = json.load(fh)
if not isinstance(data, dict):
raise ValueError("top level is not a JSON object")
lv = data.get("lockfileVersion", 1)
entries, errors = {}, []
root = {}
if isinstance(data.get("packages"), dict):
root = data["packages"].get("", {}) or {}
direct = set((root.get("dependencies") or {})) | set((root.get("devDependencies") or {})) | set((root.get("optionalDependencies") or {}))
for p, e in data["packages"].items():
if p == "":
continue
if not isinstance(e, dict) or "node_modules/" not in p:
if isinstance(e, dict) and e.get("link"):
continue # workspace folder entry; its node_modules link is checked instead
errors.append(p)
continue
name = e.get("name") or name_from_path(p)
top = p.count("node_modules/") == 1
entries[p] = dict(name=name, version=str(e.get("version", "")), resolved=e.get("resolved", ""),
integrity=e.get("integrity", ""), license=e.get("license", ""),
script=bool(e.get("hasInstallScript")), dev=bool(e.get("dev")),
link=bool(e.get("link")), direct=top and name in direct)
elif isinstance(data.get("dependencies"), dict):
def walk(deps, prefix, top):
for name, e in deps.items():
p = prefix + "node_modules/" + name
if not isinstance(e, dict) or "version" not in e:
errors.append(p)
continue
ver = str(e["version"])
resolved = e.get("resolved", "")
if not resolved and re.match(r"^(git|github:|file:|https?:)", ver):
resolved = ver
entries[p] = dict(name=name, version=ver, resolved=resolved, integrity=e.get("integrity", ""),
license="", script=False, dev=bool(e.get("dev")), link=False, direct=top)
if isinstance(e.get("dependencies"), dict):
walk(e["dependencies"], p + "/", False)
walk(data["dependencies"], "", True)
else:
raise ValueError("no 'packages' or 'dependencies' map found")
return entries, errors, dict(lockfileVersion=lv, name=data.get("name", ""), root=root)
def source_problem(resolved, registry, link):
if link:
return None
if not resolved:
return None
r = resolved.lower()
if r.startswith(("git+", "git:", "github:", "git@")) or "codeload.github.com" in r:
return "git source"
if r.startswith(("file:", "link:")):
return "local path"
if r.startswith("http:"):
return "plain http tarball"
if r.startswith("https:"):
host = urlparse(r).netloc
if host not in {urlparse(x).netloc for x in registry}:
return "tarball from " + host
return None
def audit(before, after, registry=("https://registry.npmjs.org/",), allow_scopes=(), max_added=25):
b_ent, b_err, b_meta = before
a_ent, a_err, a_meta = after
by_name_b, by_name_a = {}, {}
for p, e in b_ent.items():
by_name_b.setdefault(e["name"], set()).add(e["version"])
for p, e in a_ent.items():
by_name_a.setdefault(e["name"], set()).add(e["version"])
changes = dict(added=[], removed=[], upgraded=[], downgraded=[], changed_source=[])
flags = []
def flag(code, pkg, detail):
flags.append(dict(code=code, severity=SEV[code], package=pkg, detail=detail))
for p in sorted(set(a_ent) - set(b_ent)):
e = a_ent[p]
changes["added"].append(dict(path=p, name=e["name"], version=e["version"], direct=e["direct"], dev=e["dev"]))
for p in sorted(set(b_ent) - set(a_ent)):
e = b_ent[p]
changes["removed"].append(dict(path=p, name=e["name"], version=e["version"], direct=e["direct"]))
for p in sorted(set(a_ent) & set(b_ent)):
o, n = b_ent[p], a_ent[p]
if o["version"] != n["version"]:
c = cmp_version(o["version"], n["version"])
row = dict(path=p, name=n["name"], old=o["version"], new=n["version"], kind=bump_kind(o["version"], n["version"]), direct=n["direct"])
if c == 1:
row["kind"] = "downgrade"
changes["downgraded"].append(row)
flag("L06", n["name"], "%s -> %s (downgrade)" % (o["version"], n["version"]))
else:
changes["upgraded"].append(row)
if row["kind"] == "major" and n["direct"]:
flag("L05", n["name"], "%s -> %s (major, direct dependency)" % (o["version"], n["version"]))
elif o["integrity"] and n["integrity"] and o["integrity"] != n["integrity"]:
flag("L03", n["name"], "%s: integrity hash changed without a version change" % n["version"])
if o["resolved"] != n["resolved"] and o["version"] == n["version"] and source_problem(n["resolved"], registry, n["link"]):
changes["changed_source"].append(dict(path=p, name=n["name"], old=o["resolved"], new=n["resolved"]))
if o["license"] and n["license"] and o["license"] != n["license"]:
flag("L09", n["name"], "license %s -> %s" % (o["license"], n["license"]))
touched = set(x["path"] for x in changes["added"]) | set(x["path"] for x in changes["upgraded"] + changes["downgraded"] + changes["changed_source"])
for p in sorted(touched):
e = a_ent[p]
scoped_ok = any(e["name"].startswith(s.rstrip("/") + "/") for s in allow_scopes)
if e["script"] and not scoped_ok:
flag("L01", e["name"], "%s runs an install script (preinstall/install/postinstall)" % e["version"])
sp = source_problem(e["resolved"], registry, e["link"])
if sp and not scoped_ok:
flag("L02", e["name"], "%s resolved from %s: %s" % (e["version"], sp, e["resolved"]))
if not e["integrity"] and not e["link"] and not (sp and sp.startswith(("git", "local"))):
flag("L04", e["name"], "%s has no integrity hash" % e["version"])
if p in {x["path"] for x in changes["added"]} and e["license"] and COPYLEFT.search(e["license"]):
flag("L09", e["name"], "%s added with license %s" % (e["version"], e["license"]))
for name in sorted(by_name_a):
if len(by_name_a[name]) > 1 and len(by_name_a[name]) > len(by_name_b.get(name, set())):
flag("L07", name, "now installed in %d versions: %s" % (len(by_name_a[name]), ", ".join(sorted(by_name_a[name], key=lambda v: parse_version(v) or (0, 0, 0, v)))))
if len(changes["added"]) > max_added:
flag("L08", "-", "%d packages added (limit %d)" % (len(changes["added"]), max_added))
for p in a_err:
flag("E01", p, "entry could not be parsed and was skipped")
order = {"high": 0, "medium": 1, "low": 2}
flags.sort(key=lambda f: (order[f["severity"]], f["code"], f["package"]))
summary = dict(before=len(b_ent), after=len(a_ent), added=len(changes["added"]), removed=len(changes["removed"]),
upgraded=len(changes["upgraded"]), downgraded=len(changes["downgraded"]),
direct_changes=sum(1 for x in changes["added"] + changes["upgraded"] + changes["downgraded"] if x.get("direct")),
high=sum(f["severity"] == "high" for f in flags), medium=sum(f["severity"] == "medium" for f in flags),
low=sum(f["severity"] == "low" for f in flags),
lockfile_versions=[b_meta["lockfileVersion"], a_meta["lockfileVersion"]])
return dict(summary=summary, changes=changes, flags=flags)
def render_text(r):
s = r["summary"]
out = ["npm lockfile change audit",
"- packages %d -> %d: +%d added, -%d removed, %d upgraded, %d downgraded (%d direct)" % (
s["before"], s["after"], s["added"], s["removed"], s["upgraded"], s["downgraded"], s["direct_changes"]),
"- findings: %d high, %d medium, %d low; lockfileVersion %s -> %s" % (s["high"], s["medium"], s["low"], *s["lockfile_versions"]), ""]
c = r["changes"]
if c["upgraded"] or c["downgraded"]:
out.append("Version changes")
for x in c["upgraded"] + c["downgraded"]:
out.append(" %-28s %-10s -> %-10s %-10s%s" % (x["name"], x["old"], x["new"], x["kind"], " direct" if x["direct"] else ""))
out.append("")
if c["added"]:
out.append("Added")
for x in c["added"]:
out.append(" %-28s %-10s%s%s" % (x["name"], x["version"], " direct" if x["direct"] else "", " dev" if x["dev"] else ""))
out.append("")
if c["removed"]:
out.append("Removed")
for x in c["removed"]:
out.append(" %-28s %s" % (x["name"], x["version"]))
out.append("")
out.append("Findings" if r["flags"] else "Findings: none")
for f in r["flags"]:
out.append(" %s %-6s %-26s %s" % (f["code"], f["severity"], f["package"], f["detail"]))
return "\n".join(out)
def render_md(r):
s = r["summary"]
out = ["## npm lockfile change audit", "",
"**%d -> %d packages**: +%d added, -%d removed, %d upgraded, %d downgraded (%d direct). Findings: **%d high**, %d medium, %d low." % (
s["before"], s["after"], s["added"], s["removed"], s["upgraded"], s["downgraded"], s["direct_changes"], s["high"], s["medium"], s["low"]), ""]
if r["flags"]:
out += ["| Code | Severity | Package | Detail |", "|---|---|---|---|"]
out += ["| %s | %s | `%s` | %s |" % (f["code"], f["severity"], f["package"], f["detail"].replace("|", "\\|")) for f in r["flags"]]
out.append("")
ch = r["changes"]["upgraded"] + r["changes"]["downgraded"]
if ch:
out += ["| Package | From | To | Kind |", "|---|---|---|---|"]
out += ["| `%s`%s | %s | %s | %s |" % (x["name"], " (direct)" if x["direct"] else "", x["old"], x["new"], x["kind"]) for x in ch]
return "\n".join(out)
def run(argv):
ap = argparse.ArgumentParser(description="Audit the changes between two npm lockfiles.")
ap.add_argument("before", nargs="?")
ap.add_argument("after", nargs="?")
ap.add_argument("--registry", action="append", help="allowed registry URL (repeatable; default registry.npmjs.org)")
ap.add_argument("--allow-scope", action="append", default=[], help="trusted scope, e.g. @acme (skips L01/L02 for it)")
ap.add_argument("--max-added", type=int, default=25)
ap.add_argument("--fail-on", choices=["high", "medium", "low", "none"], default="high")
ap.add_argument("--format", choices=["text", "md", "json"], default="text")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.before or not a.after:
ap.print_usage(sys.stderr)
return 2
try:
before, after = load(a.before), load(a.after)
except (OSError, ValueError) as e:
print("error: cannot read lockfile: %s" % e, file=sys.stderr)
return 2
r = audit(before, after, tuple(a.registry or ["https://registry.npmjs.org/"]), tuple(a.allow_scope), a.max_added)
print(json.dumps(r, indent=2) if a.format == "json" else render_md(r) if a.format == "md" else render_text(r))
worst = max([RANK[f["severity"]] for f in r["flags"]] or [0])
return 1 if worst >= RANK[a.fail_on] else 0
def self_test():
checks = 0
def ok(cond, msg):
nonlocal checks
checks += 1
if not cond:
raise AssertionError(msg)
ok(cmp_version("1.2.3", "1.10.0") == -1, "numeric compare")
ok(cmp_version("2.0.0-rc.1", "2.0.0") == -1, "prerelease < release")
ok(bump_kind("4.17.21", "5.0.0") == "major", "major")
ok(bump_kind("0.3.1", "0.4.0") == "major", "0.x minor is major")
ok(bump_kind("1.2.3", "1.2.9") == "patch", "patch")
ok(name_from_path("node_modules/a/node_modules/@s/b") == "@s/b", "nested scoped name")
reg = ("https://registry.npmjs.org/",)
ok(source_problem("git+ssh://git@github.com/x/y.git#abc", reg, False) == "git source", "git")
ok(source_problem("https://registry.npmjs.org/a/-/a-1.0.0.tgz", reg, False) is None, "registry ok")
ok(source_problem("https://example.com/a.tgz", reg, False) == "tarball from example.com", "foreign host")
def lock(pk):
return ({"node_modules/" + k: dict(dict(name=k, resolved="https://registry.npmjs.org/%s/-/x.tgz" % k, integrity="sha512-" + k + v.get("version", ""),
license="MIT", script=False, dev=False, link=False, direct=True), **v) for k, v in pk.items()}, [], dict(lockfileVersion=3))
b = lock({"a": dict(version="1.0.0"), "b": dict(version="2.0.0"), "c": dict(version="1.0.0")})
n = lock({"a": dict(version="2.0.0"), "b": dict(version="1.9.0"), "d": dict(version="1.0.0", script=True, license="AGPL-3.0")})
n[0]["node_modules/c"] = dict(b[0]["node_modules/c"], integrity="sha512-other")
r = audit(b, n, reg)
codes = sorted(f["code"] for f in r["flags"])
ok(r["summary"]["added"] == 1 and r["summary"]["removed"] == 0, "added count")
ok("L05" in codes, "major direct flagged")
ok("L06" in codes, "downgrade flagged")
ok("L01" in codes and "L09" in codes, "install script and copyleft flagged")
ok("L03" in codes, "integrity change flagged")
r2 = audit(b, b, reg)
ok(r2["flags"] == [] and r2["summary"]["upgraded"] == 0, "identical lockfiles are clean")
n2 = lock({"a": dict(version="1.0.0"), "b": dict(version="2.0.0"), "c": dict(version="1.0.0"), "@acme/tool": dict(version="1.0.0", script=True)})
ok(not [f for f in audit(b, n2, reg, ("@acme",))["flags"] if f["code"] == "L01"], "allowed scope skips L01")
print("self-test OK: %d checks" % checks)
return 0
if __name__ == "__main__":
sys.exit(run(sys.argv[1:]))
Opinionated conventions for publishing small, stable Java libraries with Maven: pinned plugins, tiny dependency trees, API compatibility checks and Central releases.
# Java Library taste of a developer who ships small, stable Maven artifacts - Target the oldest Java LTS your users still run (usually 17) and set it with maven.compiler.release, not source/target. Confidence: 0.90 - Use the Maven Wrapper (mvnw) and commit it so every build uses the same Maven version. Confidence: 0.90 - Pin every plugin version in pluginManagement; never rely on Maven's default plugin versions. Confidence: 0.95 - Keep runtime dependencies near zero; a library should not drag Guava or Commons into every consumer. Confidence: 0.85 - Mark compile-only and annotation-processor dependencies as provided or optional so they do not leak transitively. Confidence: 0.80 - Ship a module-info.java, or at least an Automatic-Module-Name in the manifest, so JPMS users get a stable module name. Confidence: 0.85 - Put everything not meant for users in an internal package and do not export it from the module. Confidence: 0.85 - Prefer immutable value types (records or final classes with builders) for the public API. Confidence: 0.85 - Never return null from public methods; return Optional for single values and empty collections for lists. Confidence: 0.85 - Throw unchecked exceptions with clear messages, and define one library-specific base exception type. Confidence: 0.75 - Annotate nullability with JSpecify (@NullMarked at package level) so Kotlin and static analysis tools see the contract. Confidence: 0.75 - Use SLF4J as the only logging dependency and never configure a logging backend inside the library. Confidence: 0.90 - Test with JUnit 5 and AssertJ, and keep unit tests runnable with a plain mvn verify and no network. Confidence: 0.90 - Run integration tests with the Failsafe plugin and Testcontainers instead of shared test databases. Confidence: 0.80 - Enforce formatting with Spotless (google-java-format or palantir-java-format) and fail CI on drift. Confidence: 0.80 - Run Error Prone or SpotBugs in CI and treat new warnings as build failures. Confidence: 0.70 - Use japicmp or revapi to block accidental binary-incompatible changes in minor and patch releases. Confidence: 0.85 - Follow semantic versioning strictly; breaking changes wait for a major version with a migration note. Confidence: 0.90 - Publish a BOM when the project has more than one artifact so users can align versions in one place. Confidence: 0.75 - Generate and publish sources and Javadoc jars, and write Javadoc for every public type and method. Confidence: 0.85 - Publish to Maven Central through the Central Portal with signed artifacts, released from CI, never from a laptop. Confidence: 0.85 - Make builds reproducible by setting project.build.outputTimestamp. Confidence: 0.70 - Test the library in CI on every supported Java version with a matrix build. Confidence: 0.85 - Keep a CHANGELOG.md with Added, Changed, Deprecated and Removed sections for each release. Confidence: 0.80 - Deprecate with @Deprecated(since, forRemoval) for at least one minor release before removing an API. Confidence: 0.80
Opinionated conventions for building and releasing Swift packages: Package.swift setup, strict concurrency, Swift Testing, DocC and semver.
# Swift Package taste of a developer who ships small, well-tested Swift libraries - Use Swift Package Manager as the only distribution method for new libraries, and skip CocoaPods and Carthage specs unless users ask. Confidence: 0.85 - Set the swift-tools-version to the oldest toolchain you really test on, and raise it on purpose in a minor release. Confidence: 0.80 - Declare explicit platform minimums in Package.swift (.iOS, .macOS, .watchOS, .tvOS, .visionOS) instead of relying on defaults. Confidence: 0.85 - Keep one focused library product per package; split optional integrations into separate targets users can opt into. Confidence: 0.80 - Use the standard layout (Sources/<Target>, Tests/<Target>Tests) and avoid custom path settings. Confidence: 0.90 - Enable Swift 6 language mode and strict concurrency checking, and mark public types Sendable where it is true. Confidence: 0.80 - Keep the public API small: default to internal, and make each public symbol a deliberate decision. Confidence: 0.90 - Prefer value types and protocols with small requirements over class hierarchies in public APIs. Confidence: 0.80 - Offer async/await APIs first, and add completion-handler or Combine wrappers only when users need them. Confidence: 0.75 - Avoid third-party dependencies in a library; when one is needed, use a version range from: a major version, never a branch or exact revision. Confidence: 0.85 - Write tests with Swift Testing (@Test, #expect) for new code and keep XCTest only where it is already used. Confidence: 0.75 - Run CI on macOS and Linux with swift build and swift test, plus xcodebuild for each Apple platform you claim to support. Confidence: 0.85 - Write DocC documentation for every public symbol and include at least one article showing the main use case. Confidence: 0.80 - Host the docs on the Swift Package Index and keep a .spi.yml so builds and documentation stay green there. Confidence: 0.70 - Follow semantic versioning with plain tags like 1.4.0, without a v prefix, so SPM resolves them. Confidence: 0.90 - Use @available and deprecation messages with a renamed: hint one minor release before removing an API. Confidence: 0.85 - Keep resources in a Resources folder declared with .process and access them only through Bundle.module. Confidence: 0.75 - Format with swift-format or SwiftFormat and lint with SwiftLint in CI, using a config committed to the repo. Confidence: 0.70 - Avoid build plugins and macros unless they remove real boilerplate, because they slow builds and need extra trust prompts. Confidence: 0.65 - Ship a privacy manifest (PrivacyInfo.xcprivacy) when the library touches required-reason APIs. Confidence: 0.75 - Keep Package.resolved out of library repositories, but commit it in apps and example projects. Confidence: 0.80 - Include a runnable example app or snippet in the README that compiles in CI. Confidence: 0.70 - Keep a CHANGELOG.md with Added, Changed, Deprecated and Fixed sections for every release. Confidence: 0.80
Opinionated conventions for building, testing and releasing small, dependable Ruby gems with clean gemspecs and safe publishing.
# Ruby Gem taste of a maintainer who ships small, dependable gems with boring releases - Scaffold new gems with `bundle gem <name> --test=rspec --ci=github --linter=rubocop` and keep the generated layout instead of inventing a custom one. Confidence: 0.80 - Keep the gemspec as the single source of truth for metadata, required Ruby version and runtime dependencies; the Gemfile only adds development tools. Confidence: 0.90 - Set `required_ruby_version` explicitly and support only Ruby versions that still receive security fixes. Confidence: 0.85 - Build `spec.files` from `git ls-files` filtered to `lib`, `sig`, `exe`, LICENSE, README and CHANGELOG so tests and fixtures never ship in the package. Confidence: 0.85 - Add as few runtime dependencies as possible and give each one a pessimistic constraint like `~> 2.3`, never an unbounded `>=`. Confidence: 0.90 - Do not commit `Gemfile.lock` for a library; let CI resolve fresh dependencies so breakage shows up early. Confidence: 0.65 - Namespace everything under one top-level module that matches the gem name, and never monkey-patch core classes from a library. Confidence: 0.95 - Use Zeitwerk for gems with many files, and plain `require_relative` for small ones. Confidence: 0.70 - Expose configuration through a `configure` block that yields a plain configuration object with documented defaults. Confidence: 0.80 - Define a base `<GemName>::Error < StandardError` and raise specific subclasses so callers can rescue the whole family. Confidence: 0.90 - Add `# frozen_string_literal: true` to every Ruby file. Confidence: 0.80 - Write tests in RSpec with `--require spec_helper`, random order and `disable_monkey_patching!` turned on. Confidence: 0.80 - Run CI on a matrix of all supported Rubies plus `head`, with `head` allowed to fail. Confidence: 0.85 - Enforce style with RuboCop (or Standard) in CI, and keep project-wide disables in `.rubocop.yml` instead of inline comments. Confidence: 0.75 - Ship RBS signatures in `sig/` for the public API, or at least YARD types, so editors and Steep can check callers. Confidence: 0.60 - Document every public method with YARD and keep a runnable quick-start example at the top of the README. Confidence: 0.80 - Follow Semantic Versioning strictly and keep `VERSION` in `lib/<gem>/version.rb` as the only place the version lives. Confidence: 0.95 - Maintain a CHANGELOG in Keep a Changelog format and update it in the same pull request as the change. Confidence: 0.85 - Deprecate before removing: warn through `Kernel#warn` with `category: :deprecated` for at least one minor release. Confidence: 0.85 - Publish from CI with RubyGems trusted publishing on a tagged release instead of running `gem push` from a laptop. Confidence: 0.85 - Require MFA for every owner by setting `rubygems_mfa_required` to "true" in the gemspec metadata. Confidence: 0.95 - Set `source_code_uri`, `changelog_uri` and `bug_tracker_uri` in the metadata so rubygems.org links back to the repository. Confidence: 0.75 - Keep optional integrations (Rails, Sidekiq) behind separate requires such as `require "<gem>/rails"` so they never load by default. Confidence: 0.80 - Test the packaged gem, not only the repo: build it in CI, install it into a clean bundle and run a smoke script. Confidence: 0.70