npm: Found vulnerabilities
npm auditで脆弱性が検出された場合の対処法
概要
npm auditで依存パッケージに既知の脆弱性が検出された場合の対処法です。
エラーメッセージ
```
found 10 vulnerabilities (2 low, 5 moderate, 3 high)
run npm audit fix to fix them, or npm audit for details
```
原因
- 直接依存の脆弱性: 使用しているパッケージに脆弱性
- 推移的依存の脆弱性: 依存の依存に脆弱性
- 古いパッケージ: 修正版がリリースされているのに未更新
- 修正版未リリース: まだ修正が提供されていない
解決策
1. 詳細を確認
```bash
脆弱性の詳細
npm audit
JSON形式で出力
npm audit –json ```
2. 自動修正を試す
```bash
自動修正
npm audit fix
semver majorも更新する場合
npm audit fix –force # 注意: 破壊的変更の可能性 ```
3. 特定パッケージを更新
```bash
特定パッケージを最新に
npm update lodash
メジャーバージョンアップ
npm install lodash@latest ```
4. overridesで強制指定 (npm 8.3+)
```json { “overrides”: { “vulnerable-package”: “2.0.0”, “parent-package”: { “vulnerable-dep”: “^1.5.0” } } } ```
5. 脆弱性を無視(リスク評価後)
```bash
開発依存で実行時に影響なしの場合
.nsprc や audit-level で制御
npm audit –audit-level=high ```
6. 代替パッケージに移行
```bash
脆弱性のあるパッケージを削除
npm uninstall vulnerable-package
代替をインストール
npm install safe-alternative ```
7. CI/CDでの設定
```yaml
GitHub Actions
- name: Security audit run: npm audit –audit-level=high continue-on-error: false ```
よくある間違い
- npm audit fix –force を無条件に実行
- 開発依存の脆弱性で本番を止める
- 脆弱性の実際の影響を評価しない
関連エラー
関連エラー
Node.js の他のエラー
この記事は役に立ちましたか?