Re-apply a71615a. Fixes #3265 again, with a test!

a71615a accidentally got reverted by 355bb7e, which split the changed
file into multiple files.

Original commit message:

    Check SHA before using files from cache

    Fixes #3265.

    Because 'npm install' *always* writes every package to the cache (even
    if it isn't installed from the registry) before installing it, it's easy
    to end up in a situation where "npm install foo" installs something
    other than the appropriate version from the registry.  eg:

      npm cache clean
      # Install a fork of version 0.0.1:
      npm install https://github.com/glasser/npm-cache-corruption/tarball/93c447e
      rm -rf node_modules
      # Before this commit, this would install the same fork as above
      npm install npm-cache-corruption