Handling Package Vulnerabilities in Web Projects with pnpm

Handling Package Vulnerabilities in Web Projects with pnpm

pnpm audit

In today's fast-paced web projects, with ever-changing technologies, tools, and dependencies, it can be challenging to keep everything up to date. Some may argue that this isn't a significant concern, as long as the project works as expected at a given moment. However, as mentioned in a previous article, keeping dependencies up to date not only ensures stability or optimization but also provides the latest security patches for your application. As you might have guessed, pnpm provides a variety of features to assist you in this regard.

Checking for vulnerabilities

First, we have to identify if the project has any known vulnerabilities within its dependencies using the `audit` command.

pnpm audit

This command checks every package against the GitHub Advisory Database and indicates through a report which packages are currently carrying security issues and what is their level of threat.

The output of pnpm audit command

Vulnerabilities resolution

If the audit command identifies some issues, you can try to automatically fix them by running the pnpm update command. This will try to update each vulnerable package to a safe version, without introducing breaking changes.

If there are still some vulnerabilities after running the update, you can try to use the overrides field.

pnpm section added after running audit --fix

Simply run the audit command with the fix option, and it will add a new section in the package.json file indicating the version of the packages to use whenever those packages and their dependency graph are resolved during the installation.

pnpm audit --fix

You can also specify a threat level while fixing the vulnerabilities, for instance, to only fix the critical ones first :

pnpm audit --audit-level critical

Good to know

If you are running the pnpm audit command in a CI pipeline, you can output the audit report as a JSON file thanks to the -json option. You can then make available this report as an artifact of your pipeline for future reference.

To maintain a secure development environment in the long run, it's crucial to regularly audit your project for vulnerabilities. You should consider running the audit command as part of your continuous integration process or at regular intervals during development.