How to Fix Your Security Vulnerabilities with NPM Overrides
What’s the problem?
You sit down to work on your side project or contribute to a project at work, you npm install with enthusiasm and hope. Then those dreadful messages appear, gazillion vulnerabilities, a zillion of them high. You run npm “audit fix”,and it fixes some of the dependencies. What do you do next? Run “npm audit –force”. Well, that’s brave of you, fortune favors the bold they say. Unfortunately, bold die young and software doesn’t necessarily work when you update dependencies with breaking changes.
Running npm update did not change the number of vulnerable packages and strangely npm audit fix added another vulnerability.
What does the internet say about it?
The Internet might be telling you to use npm shrinkwrap or edit package-lock.json file manually. If you change the package-lock.json, your changes will be overwritten when you npm install next time or even worse, when your CICD pipeline deploys your updates.
Another popular option, Npm shrinkwrap is designed to lock the dev dependencies when you are publishing, and it is not recommended to be used to override package-lock.json file.
Finally, using yarn dependency resolutions or adding npm-force-resolutions package are both viable solutions but npm overrides can easily solve your problem starting version 8.3 and higher.
What is npm overrides?
Overrides provide a way to replace a package in your dependency tree with another version, or another package entirely by adding an overrides attribute to your package.json.
You can further specify if you want a specific package’s dependency to be overridden at any depth.
How to resolve to a different package?
One recent issue has been with ansi-html package, which had more than 9 million weekly downloads until recently. Not getting any fixes from the library maintainers, community fork is now available with the security fixes. A lot of my dependencies has ansi-html as their dependency, by adding an override, I can automatically resolve all of their dependencies to a tar file.
If you are working on your own package and want to your nested dependencies to point to your work in progress, you can override with your brand new package file as well.
What could go wrong?
You can check if adding overrides to your package.json did change your nested dependencies by going into node_modules/ansi-html/package.json and check the name and version field on top.
My nested dependency still has the version with the security issues because I’ve already had npm module installed. Deleting your package-lock.json and node modules will force the next npm install to have the version you intend to have.
Although your node_module/ansi-html folder name has not changed, if you look at folder’s package.json, it is replaced by the ansi-html-community.
One vulnerability down and 103 to go for me, I hope you are doing better.