Skip to main content

Security and hardening · Intermediate · 24 min

Pin and verify dependencies with lockfiles and hashes

By Padding · Updated 18 Nov 2026
node:26 image (Debian) · Node.js 26.13.1 · npm 11.20.0 · Python 3 from Debian · uv 0.13.10

You will lock a small Node.js project and two small Python projects to exact versions and hashes, watch npm ci, pip and uv refuse a tampered package, turn off install scripts by default, route private package names to their own registry and check signatures and provenance before you trust a release.

On this page

When you write "debug": "^4.3.0" in a package.json or python-slugify>=9 in a requirements file, you are not naming a package. You are naming a set of packages, and the installer picks one on the day it runs. Two laptops a week apart can end up with different code, and neither person typed anything different. Worse, nothing in that line says what the files should contain, so a changed file on a mirror, a proxy or a compromised account installs without complaint.

Lockfiles and hashes fix both problems. A lockfile records the exact version of every package, including the ones you never asked for by name. A hash records what the downloaded file must contain, byte for byte. With both in place the installer either produces exactly what you reviewed, or stops.

In this tutorial you build three small throwaway projects in ~/pin-demo:

  • a Node.js app with a lockfile, where you watch npm ci refuse a lockfile that has drifted and a package whose hash does not match
  • a Python app with a compiled, hashed requirements file, where you watch pip refuse a changed wheel
  • a uv project, where the lockfile does the same job and the same tampering fails

Along the way you turn off install scripts by default, send private package names to a private registry only, and check registry signatures and PyPI provenance. Hashes prove you got the file you recorded. They do not prove the file was safe when you recorded it, so you still review what you add.

Step 1 · See how a version range picks what you install

Create the Node.js app with one dependency written as a caret range:

Bash
mkdir -p ~/pin-demo/npm-app
cd ~/pin-demo/npm-app
cat > package.json <<'JSON'
{
  "name": "pin-demo-app",
  "version": "1.0.0",
  "private": true,
  "dependencies": {
    "debug": "^4.3.0"
  }
}
JSON
npm view "debug@^4.3.0" version

^4.3.0 means "4.3.0 or anything later that still starts with 4". npm view lists every published version that fits, and there are several. Whichever is newest on the day you install is the one you get, and the same goes for every package that debug itself depends on.

Install, then look at what npm wrote down:

Bash
npm install
node -p 'const lock = require("./package-lock.json"); ["debug", "ms"].map((name) => { const p = lock.packages["node_modules/" + name]; return `${name} ${p.version}\n  ${p.resolved}\n  ${p.integrity}` }).join("\n")'

package-lock.json has one entry per installed package, including ms, which you never named: debug pulled it in. Each entry has three fields that matter here:

  • version: the exact release chosen from the range
  • resolved: the URL the tarball came from
  • integrity: a SHA-512 hash of that tarball, in the sha512-... form browsers also use for scripts

Commit package-lock.json next to package.json. Without it, the next install repeats the choice from scratch.

Check it worked

npm view printed a list of versions starting at 4.3.0. The node -p command printed something like:

Text
debug 4.4.3
  https://registry.npmjs.org/debug/-/debug-4.4.3.tgz
  sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==
ms 2.1.3
  https://registry.npmjs.org/ms/-/ms-2.1.3.tgz
  sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==

The versions may be newer than these if debug has shipped a release since.

Step 2 · Install from the lockfile with npm ci

npm install treats the lockfile as a strong hint: if package.json asks for something the lockfile cannot satisfy, it resolves again and rewrites the lockfile. npm ci treats the lockfile as the contract. It deletes node_modules, installs exactly what the lockfile lists and never writes to package.json or package-lock.json. Use it in CI, in Dockerfiles and on servers:

Bash
npm ci
npm ls --all

Now make the two files disagree, the way they do when someone edits package.json by hand and forgets to reinstall:

Bash
npm pkg set dependencies.debug=^3.2.0
Bash
npm ci

npm ci stops before installing anything. Put the range back and it installs again:

Bash
npm pkg set dependencies.debug=^4.3.0
npm ci

Check it worked

The out-of-sync run ended with npm error code EUSAGE and a message that npm ci can only install packages when your package.json and package-lock.json are in sync, followed by a line like Invalid: lock file's debug@4.4.3 does not satisfy debug@3.2.7. After the range was restored, npm ci printed added 2 packages.

Step 3 · Watch npm ci refuse a tampered hash

The integrity field is checked every time npm extracts a tarball, whether it came from the registry, a mirror or the local cache. To see that, change the hash recorded for ms to the hash of something else. Keep a copy of the good lockfile first:

Bash
cp package-lock.json package-lock.json.good
node -e '
const fs = require("node:fs")
const { createHash } = require("node:crypto")
const lock = JSON.parse(fs.readFileSync("package-lock.json", "utf8"))
lock.packages["node_modules/ms"].integrity = "sha512-" + createHash("sha512").update("not the ms tarball").digest("base64")
fs.writeFileSync("package-lock.json", JSON.stringify(lock, null, 2) + "\n")
console.log("ms now expects", lock.packages["node_modules/ms"].integrity)'

This is the same situation as a registry, proxy or mirror serving a different file under a known name and version, seen from the other side: the lockfile and the file no longer agree. Install:

Bash
npm ci

npm retries the download a couple of times, then stops. Restore the good lockfile and install again:

Bash
cp package-lock.json.good package-lock.json
rm package-lock.json.good
npm ci

In your own repository, restore with git checkout package-lock.json instead of a copy. If an EINTEGRITY error ever appears without anyone having touched the lockfile, do not delete the hash or the lockfile to make it go away. Find out which side changed: the registry, a proxy, a mirror or a commit.

Check it worked

The tampered run printed npm warn tarball ... seems to be corrupted. Trying again., then npm error code EINTEGRITY and a line with integrity checksum failed when using sha512: wanted sha512-... but got sha512-6Flzub.... After the restore, npm ci printed added 2 packages.

On a slow or prepaid connection this check costs you nothing extra: npm ci reuses tarballs from the local cache and still checks each one against the lockfile, so a repeat install downloads very little.

Step 4 · Stop install scripts from running by default

A package can declare preinstall, install and postinstall scripts, which npm runs on your machine during installation, with your user's access to your files and tokens. Most packages do not need them, and they are the usual way a malicious package does its damage. To see one run, make a tiny local package whose script only writes a harmless marker file into your project:

Bash
mkdir -p ~/pin-demo/hello-hook
cd ~/pin-demo/hello-hook
cat > package.json <<'JSON'
{
  "name": "hello-hook",
  "version": "1.0.0",
  "description": "Demo package whose install script writes a marker file",
  "license": "MIT",
  "scripts": {
    "postinstall": "node install.js"
  }
}
JSON
cat > install.js <<'JS'
// Runs during npm install. A real attacker would read tokens or files here instead.
const fs = require('node:fs')
const path = require('node:path')
fs.writeFileSync(path.join(process.env.INIT_CWD, 'HELLO-HOOK-RAN.txt'), 'hello-hook ran its install script\n')
JS
npm pack
cd ~/pin-demo/npm-app
npm install ../hello-hook/hello-hook-1.0.0.tgz
cat HELLO-HOOK-RAN.txt

You only asked npm to install a package, and code from that package ran. Turn install scripts off for this project with a project .npmrc, then reinstall from the lockfile:

Bash
rm HELLO-HOOK-RAN.txt
npm config set ignore-scripts=true --location=project
cat .npmrc
npm ci
ls

When a package you trust genuinely needs its install step (some packages compile native code there), run that one package's scripts on purpose, after review:

Bash
npm rebuild hello-hook --ignore-scripts=false
cat HELLO-HOOK-RAN.txt

ignore-scripts also skips the pre- and post- hooks of your own project scripts, though npm test and npm run <name> still run the script you name. Commit the .npmrc, and use npm ci --ignore-scripts in CI images where you cannot rely on the file.

Check it worked

The first install printed hello-hook ran its install script. With ignore-scripts=true in .npmrc, npm ci succeeded and ls showed no HELLO-HOOK-RAN.txt. npm rebuild hello-hook --ignore-scripts=false created it again.

Step 5 · Check names, private scopes and registry signatures

A lockfile faithfully pins whatever you installed, including a typo. Typosquatting relies on that: a package called debgu or debug-js waiting for a slip of the keyboard or a confident suggestion from an AI coding assistant. Before you add a dependency, look at what the registry says about it:

Bash
npm view debug name repository.url time.created

A real, long-lived package has a source repository you recognise and a creation date years back. A name that appeared last week, with no repository or one that does not match, needs a closer look before it goes anywhere near a lockfile.

Dependency confusion is the related trick for private code. If your company has an internal package called billing-utils and someone publishes billing-utils with a higher version on the public registry, an installer that looks in both places may pick the public one. On npm, give internal packages a scope and map the scope to your own registry, so @your-org/... names are never looked up anywhere else. Replace your-org and the URL with your own:

Bash
npm config set @your-org:registry=https://npm.your-org.example/ --location=project
npm config get @your-org:registry

Also register the scope name on the public registry, so nobody else can publish under it.

Finally, check that what you installed is what the registry published. The public npm registry signs every package version, and npm audit signatures checks those signatures, and any provenance attestations, for everything in node_modules:

Bash
npm audit signatures

Check it worked

npm view printed repository.url = 'git://github.com/debug-js/debug.git' and a creation date in 2011. npm config get printed your scoped registry URL, and .npmrc now has two lines. npm audit signatures ended with 2 packages have verified registry signatures: debug and ms. hello-hook came from a local tarball, so it has no registry signature to check.

Step 6 · Compile a hashed requirements file for pip

Python's equivalent of the lockfile, for pip, is a compiled requirements file: every package pinned with ==, each with the hashes of its allowed files. On Ubuntu or Debian, install Python's virtual environment support first (on macOS, the Python from python.org or Homebrew already has it):

Bash
sudo apt-get update
sudo apt-get install -y python3 python3-venv

Write the loose requirement you actually care about in requirements.in, and let uv compile it into a pinned, hashed requirements.txt:

Bash
mkdir -p ~/pin-demo/py-app
cd ~/pin-demo/py-app
echo 'python-slugify>=9' > requirements.in
uv pip compile requirements.in --generate-hashes -o requirements.txt
cat requirements.txt

People edit requirements.in; the tool writes requirements.txt. Commit both. When you want newer versions, compile again on purpose and review the difference in the pull request.

Install into a fresh virtual environment with hash checking switched on, and use the package:

Bash
python3 -m venv .venv
.venv/bin/pip install --require-hashes -r requirements.txt
.venv/bin/python -c 'from slugify import slugify; print(slugify("Ọjà Lagos: Weekend Menu"))'

pip turns on hash-checking mode by itself as soon as one line in a requirements file has a --hash, but writing --require-hashes makes the intent explicit and fails loudly if someone later compiles a file without hashes. In this mode every package must be pinned with == and every package must have a hash, including dependencies of dependencies.

Check it worked

requirements.txt lists python-slugify==9.2.0 and text-unidecode==1.3, each followed by two --hash=sha256:... lines (one for the wheel, one for the source archive) and a # via comment saying why it is there. The install succeeds, and the last command prints oja-lagos-weekend-menu: text-unidecode turned the Yoruba letters into plain ASCII.

Step 7 · Make pip refuse a changed file

Many teams install from an internal mirror or a folder of downloaded wheels, which is also useful where bandwidth is scarce: download once, install on many machines. The hashes in requirements.txt protect you there too. Download the files into a local folder, checking hashes as you go:

Bash
.venv/bin/pip download --require-hashes -r requirements.txt -d mirror
ls mirror

Now change one wheel, the way a compromised mirror might. This adds one harmless Python file inside the text-unidecode wheel:

Bash
python3 - <<'PY'
import glob
import zipfile

wheel = glob.glob("mirror/text_unidecode-*.whl")[0]
with zipfile.ZipFile(wheel, "a") as archive:
    archive.writestr("text_unidecode/extra.py", "print('added after the hash was recorded')\n")
print("changed", wheel)
PY

Install from the folder only, in a new environment:

Bash
python3 -m venv .venv-mirror
Bash
.venv-mirror/bin/pip install --no-index --find-links mirror --require-hashes -r requirements.txt

pip refuses and installs nothing. Replace the folder with clean copies and the same install works:

Bash
rm -rf mirror
.venv/bin/pip download --require-hashes -r requirements.txt -d mirror
.venv-mirror/bin/pip install --no-index --find-links mirror --require-hashes -r requirements.txt

Check it worked

The install from the changed folder ended with ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE, named text-unidecode==1.3, and listed the two expected hashes and the one it got. After the clean download, the same command ended with Successfully installed python-slugify-9.2.0 text-unidecode-1.3.

Step 8 · Lock a uv project and keep it honest

If your project is managed with uv, uv.lock does this job, and you do not need a requirements file at all. Create a small project:

Bash
mkdir -p ~/pin-demo/uv-app
cd ~/pin-demo/uv-app
cat > pyproject.toml <<'TOML'
[project]
name = "slug-app"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
    "python-slugify>=9",
]
TOML
uv lock
grep -A 6 'name = "text-unidecode"' uv.lock

Every package in uv.lock has its exact version, the index it came from, and the URL, size and sha256 hash of each file. uv checks those hashes whenever it installs. In CI and on servers, install with --locked, which fails if the lockfile no longer matches pyproject.toml instead of quietly updating it:

Bash
uv sync --locked

See it refuse drift. This adds a dependency to pyproject.toml without updating the lock:

Bash
cat > pyproject.toml <<'TOML'
[project]
name = "slug-app"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
    "python-slugify>=9",
    "text-unidecode>=1.3",
]
TOML
Bash
uv sync --locked

Put the file back, then tamper with a hash in the lockfile and reinstall from scratch:

Bash
cat > pyproject.toml <<'TOML'
[project]
name = "slug-app"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
    "python-slugify>=9",
]
TOML
cp uv.lock uv.lock.good
python3 - <<'PY'
import re
from pathlib import Path

lock = Path("uv.lock")
text = lock.read_text()
start = text.index('name = "text-unidecode"')
wheel = re.compile(r'(text_unidecode-[^"]+\.whl", hash = "sha256:)([0-9a-f]{64})')
lock.write_text(text[:start] + wheel.sub(r"\g<1>" + "0" * 64, text[start:], count=1))
print("changed the text-unidecode wheel hash")
PY
rm -rf .venv
Bash
uv sync --locked
Bash
cp uv.lock.good uv.lock
rm uv.lock.good
uv sync --locked

If something downstream still needs a requirements file, such as a deployment that runs plain pip, generate one from the lock. uv export includes hashes by default:

Bash
uv export --format requirements.txt --no-emit-project -o requirements.txt
grep -c -- '--hash=sha256:' requirements.txt

For private Python packages, avoid pip install --extra-index-url with an internal index: pip treats all indexes as equal and installs the highest version it finds anywhere, which is exactly the dependency confusion opening. With uv, declare the internal index as explicit, so it is only used for packages you assign to it, and name those packages in tool.uv.sources. Replace the names and URL with your own:

TOML
[[tool.uv.index]]
name = "internal"
url = "https://pypi.your-org.example/simple"
explicit = true

[tool.uv.sources]
your-org-billing = { index = "internal" }

uv also stops at the first index that has a package (its default first-index strategy), rather than comparing versions across indexes. Leave that default alone unless you have a reason you can write down.

Check it worked

The drift run ended with an error that the lockfile at uv.lock needs to be updated, but --locked was provided, and named the added requirement. The tampered run ended with Failed to download text-unidecode==1.3 and Hash mismatch, showing an expected hash of zeros and the real computed one. After the restore, uv sync --locked installed two packages, and the grep -c printed 4.

Step 9 · Read where a PyPI release came from

A hash proves you got the same file as last time. It cannot tell you who built that file. PyPI attestations can: when a project publishes from a CI system such as GitHub Actions with trusted publishing, PyPI stores a signed statement that links each file to the repository and workflow that built it. PyPI shows it on each file's page, and its Integrity API returns it as JSON. Look at the provenance for one urllib3 wheel:

Bash
curl -fsS https://pypi.org/integrity/urllib3/2.8.0/urllib3-2.8.0-py3-none-any.whl/provenance \
  | python3 -c '
import json, sys
for bundle in json.load(sys.stdin)["attestation_bundles"]:
    print(bundle["publisher"])
'

Read the publisher against what you expect: the project's real repository, its release workflow. A release that suddenly stops having attestations, or comes from a different repository, is worth a question before you upgrade. Not every project publishes attestations yet; for one that does not, the Integrity API answers 404.

Reading this JSON tells you what PyPI recorded. It is not a cryptographic check on your machine. To verify the signatures yourself, use the pypi-attestations tool from the PyPI project, and check your installer's documentation before you assume it does this for you. On npm, npm audit signatures from the earlier step already verified provenance attestations where packages had them.

Check it worked

The command printed one line like {'environment': 'publish', 'kind': 'GitHub', 'repository': 'urllib3/urllib3', 'workflow': 'publish.yml'}: urllib3 2.8.0 was built by the publish.yml workflow in the urllib3/urllib3 repository on GitHub.

Next steps

You pinned three projects, saw each installer stop on a drifted lockfile or a changed file, and closed the doors that install scripts and mixed registries leave open. Delete the demo when you are done:

Bash
cd ~
rm -rf ~/pin-demo

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.