「npm audit」って何?って時に少し調べた時のノート
npm auditとは?
npm auditコマンドとは、プロジェクトのディレクトリ内で使用している npm パッケージのセキュリティをチェックするコマンドです。
npm auditコマンドを実行して問題のあるパッケージが見つかった場合、通常はパッケージを更新して対応することになります。
npm auditを実際に使用する。
// 実際に入力するコマンド npm audit
出力結果(抜粋) ※ 指摘項目が多すぎたので、画面に収まりませんでした。
found 4548 vulnerabilities (4547 low, 1 high) in 1340 scanned packages run `npm audit fix` to fix 4547 of them. 1 vulnerability requires semver-major dependency updates.
npm auditでの指摘項目への対応方法
方法1:指摘項目に対し、まとめて対応する
アップデートを実施する
以下のコマンドでまとめて更新することができる場合があります。
// 実際に入力するコマンド npm audit fix
package.jsonで許容された範囲でモジュールをアップデートし脆弱性を解消します。package.jsonで許容されたバージョン範囲以上のアップデートが必要な場合は指摘が残ります。
出力結果
npm WARN acorn-jsx@5.2.0 requires a peer of acorn@^6.0.0 || ^7.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN The package babel-jest is included as both a dev and production dependency.
npm WARN The package babel-plugin-transform-es2015-modules-commonjs is included as both a dev and production dependency.
npm WARN The package jest is included as both a dev and production dependency.
npm WARN The package nodemon is included as both a dev and production dependency.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
updated 2 packages in 10.048s
88 packages are looking for funding
run `npm fund` for details
fixed 4547 of 4548 vulnerabilities in 1340 scanned packages
1 package update for 1 vulnerability involved breaking changes
(use `npm audit fix --force` to install breaking changes; or refer to `npm audit` for steps to fix these manually)
アップデート結果を確認する
// 実際に入力するコマンド npm audit
出力結果
=== npm audit security report ===
# Run npm install --save-dev documentation@13.0.2 to resolve 1 vulnerability
SEMVER WARNING: Recommended action is a potentially breaking change
Low Prototype Pollution
Package yargs-parser
Dependency of documentation [dev]
Path documentation > yargs > yargs-parser
More info https://npmjs.com/advisories/1500
found 1 low severity vulnerability in 1340 scanned packages
1 vulnerability requires semver-major dependency updates.
方法2:指摘項目に対し個別に対応する
2-1:package.json でバージョンを修正
- package.jsonで対象のモジュールを検索する。
npm auditの推奨バージョンに変更する。
2-2:node_modulesディレクトリを削除する
sudo rm -r node_modules
※ Windowsの場合はnode_modulesフォルダを削除すればよいはずです。
2-3:package-lock.jsonを削除する
- ただ消せばOKです。
2-4:node_moduleをインストールする
npm install
2-5:結果を確認する
npm audit
補足
package-lock.jsonでnode_modulesのバージョンを固定化するよりも、package.jsonまかせでバージョンを管理する方が好みなので、package-lock.json、node_modulesを消してから、npm installを実行しなおしています。
バージョン指定方法の詳細
- 詳細を別ページに記載しました。興味がある方はご参照下さい。