Ways to prevent npm's supply chain attacks
Here, I collected some ways to mitigate the chance of getting a supply-chain attack when working with npm dependencies.
Use Fewer Dependencies
This is the most obvious solution: the fewer dependencies you have, the lower your chance of being targeted by security vulnerabilities. For instance, if you only need a single utility function from a library like lodash or es-toolkit, you can simply copy and paste its source code into your project. Most of these dependencies have an MIT license, which makes this perfectly acceptable.
Disable postinstall
Postinstall is enabled by default if you use npm or yarn (v1). Essentially, it allows your dependencies to run scripts on the machine after installation, which is not good. To disable it globally, you can run npm config set ignore-scripts true
or better use other package managers like pnpm.
Use npm audit for scripts
You can add npm audit
to your dev/build scripts so that each time you run them, it checks for vulnerabilities in your packages. If any vulnerability is found, it will stop the execution of the command.
minimumReleaseAge
If you're using pnpm, you can set the option minimumReleaseAge. When you install/update your dependencies, it ignores recently published ones (including transient). I think setting it to 1440 (1 day) is more than enough; usually, vulnerabilities are found and reported quite quickly.
Use Multiocular
Multiocular allows you to see changes diff in all your dependencies when you are doing the upgrade. It's still in an early version, but it's helpful if you want to have total control over dependency updates.
Development containers
With development containers, you can run your project in an isolated environment, so that if a supply-chain attack happens, harmful scripts won't have access to your host machine. It's a bit of overkill, but some might find it useful.