npm

Why package-lock.json need integrity?


Why package-lock.json use SHA-512 for integrity? What does it works for?

I've analyzed package.json and package-lock.json for package update work. Sometimes I don't know why it exists. I understand other parameters but integrity.

And I want to know how it works. when it creates or change the value


Solution

  • Per the npm documentation:

    The linked W3C documentation further explains that SSI is:

    ...a mechanism by which user agents may verify that a fetched resource has been delivered without unexpected manipulation.

    When you use npm install/npm ci to install your packages, the npm CLI downloads metadata and tarballs from the specified registry or registries (you can see this activity by adding --loglevel=http). Here's an example of lockfile content showing the resolved tarball for one of the dependencies, along with the SSI string:

        "node_modules/@ampproject/remapping": {
          "version": "2.3.0",
          "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz",
          "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==",
    

    Under certain circumstances (e.g. "man in the middle" attack on a network, or taking control of a registry server), it might be possible for an attacker to replace the content of the resolved tarball with malware. npm would download path/to/wherever.tgz and install and run this malicious code - in the best case that immediately breaks something, in the more likely and much worse case it's crafted to seem to be working but quietly doing terrible things in the background. To avoid this, after the tarball is downloaded but before unpacking and using it, npm checks that it matches the stored integrity hash. If not, it throws an EINTEGRITY error and aborts the install.

    In other words: without the integrity check, there is no way to ensure that the dependency your project is about to install and run is actually the code that you think it is.