Validating NPM package integrity via CLI commands


(Josh Habdas) #1

In response to an idea from @wilk last month @zkat showed us an example of how to calculate integrity value NPM will use when publishing a release, i.e.

npm pack 'zkat/pacote#v8.1.6' --dry-run --json | grep integrity
# "integrity": "sha512-wTOOfpaAQNEQNtPEx92x9Y9kRWVu45v583XT8x2oEV2xRB74+xdqMZIeGW4uFvAyZdmSBtye+wKdyyLaT8pcmw==",

This method can be adapted to determine the exact SRI value NPM will use for a release:

npm pack --dry-run --json . | grep integrity | cut -d ',' -f1 | cut -d ':' -f2 | tr -d '\" '
# sha512-wTOOfpaAQNEQNtPEx92x9Y9kRWVu45v583XT8x2oEV2xRB74+xdqMZIeGW4uFvAyZdmSBtye+wKdyyLaT8pcmw==

And used inside $(...) to creating signed tags with git prior to publishing to NPM:

git tag --sign -m "-----BEGIN DIST INTEGRITY-----" -m "$(...)" -m "-----END DIST INTEGRITY-----"

Resulting in an annotated tag message like:

-----BEGIN DIST INTEGRITY-----

sha512-66uC60O+jZmtCNmmYGuOlGy764sKYlzx6jXl+RRoJvWUP/jKU6hFP2bCBQ95whYIh/GRrvZE2DjLeNDe/vYvyg==

-----END DIST INTEGRITY-----
-----BEGIN PGP SIGNATURE-----

iQIzBAABCgAdFiEEH4rjgh+1thDOdXy9sUizEVTHWnQFAluDn8MACgkQsUizEVTH
WnSIfQ/9FdU9WuXDBtwNwl+BWHXKAeTs+xOoZvLo0QKTCgt8KrJdzdfh2ZhZFHbh
WaNfDABQadqmUhq9Da+xPC2etwHPQ0bkLVo8olDTzXcF8TS6kF3jSxLA0nWGcopl
dNiXdZVggHbXcdKHqHhSb/Wf4G2wvY9kHA1+dJF38lxDhM0yww40Z/i2V7cYGqAC
YASbT0SIuBuT8XA+fdfYMDDy1A/0QJRVYauQ6joBeOcbUDKbkmE9O1iHNbVabBjT
/lS81cZ/P4g9ZW+rFIlRSdfiISu7xfm9RYJJVYtmOmyOWDUkXqH7Na0uVTMQ/ghT
2iUVfSYo+kzu4Abjo7vGuQJBjkpakxE/TrVpNw8avlTbkBrwlvaKq9W2q9RfhFEa
SEs30LYGEebAStYmuVT60dggF3hDkij3UZufuolPcvnvuniydF60YU2KF313MXZM
2B58m7MvOqCOMmaPaZBxJSovyKbhUeVIrQzgJILmUZOh7DE2bie0n9GqH4mVN5wO
BxjKqhTCxaP+HZ2HDylGVwEQer21YKeuS8/xO09E2b8XZ9/kcgwqleMIfGdVKRPU
DEMNZM75VotRTXKietvpPzEyoyNnhwpnhAynT23tnT4rjh89g6uJwapwaPGGG8WV
pkY0zHMJOKDM6GkwFa9FDKs4oRa5Cvips5AUEm8UUl8X4SsBDBM=
=JOcn
-----END PGP SIGNATURE-----

Allowing one to…

  • Without git, verify the code they have is exactly what they could expect from NPM.
  • With git, fast-forward or rewind HEAD to tag and validate against tag message using npm.
  • Use npm and registry metadata to determine if they’re using the latest release of a package.
  • Reasonably determine the code they received from anywhere has not been tampered with.

Given the benefits of this technique I’d like to propose an npm command alias which eases the process of getting values from npm pack --dry-run --json, e.g.

npm pack get integrity
# sha512-66uC60O+jZmtCNmmYGuOlGy764sKYlzx6jXl+RRoJvWUP/jKU6hFP2bCBQ95whYIh/GRrvZE2DjLeNDe/vYvyg==
npm pack get shasum
# be7956bb908ca80b02155697d9a607bee5e7f924
npm pack get filename
# ssri-6.0.0.tgz
npm pack get files
# [...]

Exposing this data under CLI could be valuable an a number of security and release applications. And even if it’s not added hopefully the information provided here will be helpful to others.