mcpField
D
dependency-audit

dependency-audit

github.com/bobmatnyc开发78427 次安装15 周前更新
代码仓库

关于 dependency-audit

用于审计、更新和清理项目依赖的工作流技能,面向开发者评估漏洞、过时或未使用的包及开源风险,并验证更新结果。

主要功能

  1. 01检查过时的软件包
  2. 02扫描安全漏洞
  3. 03检测未使用的依赖
  4. 04提供弃用库迁移指导
  5. 05审查许可证与过时风险
  6. 06更新后的测试流程

适用场景

  1. 01定期维护项目依赖
  2. 02响应 CVE 安全公告
  3. 03发布前检查依赖
  4. 04审查代码中的依赖变更

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill dependency-audit

安装后在 Claude Code 中输入/dependency-audit确认已加载。

附带文件metadata.jsonreferences/open-source-safety.md

详细介绍

依赖项审计技能

概述

用于审计、更新和清理项目依赖项的系统化工作流。涵盖安全漏洞扫描、过时软件包检测、未使用依赖项移除,以及从已弃用的库迁移。

适用场景

  • 每周/每月维护依赖项
  • 安全公告发布后(CVE 公告)
  • 重大版本发布前
  • 软件包体积意外增大时
  • 代码审查依赖项变更时
  • 开始维护遗留项目时

快速审计流程

1. 检查过时的软件包
# npm
npm outdated

# pnpm
pnpm outdated

# yarn
yarn outdated

# pip (Python)
pip list --outdated

# poetry (Python)
poetry show --outdated
2. 扫描安全漏洞
# npm
npm audit
npm audit fix          # Auto-fix where possible
npm audit fix --force  # Force major version updates (risky)

# pnpm
pnpm audit
pnpm audit --fix

# yarn
yarn audit
yarn audit --fix

# Python
pip-audit              # Requires: pip install pip-audit
safety check           # Requires: pip install safety
3. 查找未使用的依赖项
# JavaScript/TypeScript
npx depcheck

# Output example:
# Unused dependencies
# * lodash
# * moment
# Unused devDependencies
# * @types/old-package

# Python
pip-autoremove --list  # Requires: pip install pip-autoremove

审计命令

JavaScript/TypeScript/Node.js
npm
# Check what's outdated
npm outdated

# Update within semver range (safe)
npm update

# Update specific package to latest
npm install package@latest

# Check security vulnerabilities
npm audit

# Auto-fix vulnerabilities
npm audit fix

# View dependency tree
npm list
npm list --depth=0  # Top-level only

# Why is this package installed?
npm ls package-name

# Check for duplicate packages
npm dedupe
pnpm
# Check outdated
pnpm outdated

# Update all dependencies
pnpm update

# Update specific package
pnpm update package@latest

# Security audit
pnpm audit

# Deduplicate
pnpm dedupe

# List all packages
pnpm list
yarn
# Check outdated
yarn outdated

# Upgrade interactive (recommended)
yarn upgrade-interactive

# Update all
yarn upgrade

# Security audit
yarn audit

# Why is this here?
yarn why package-name
Python
pip
# List outdated
pip list --outdated

# Update specific package
pip install --upgrade package-name

# Security audit
pip-audit  # Install: pip install pip-audit

# Freeze current dependencies
pip freeze > requirements.txt

# Check dependencies of a package
pip show package-name
poetry
# Show outdated
poetry show --outdated

# Update all
poetry update

# Update specific package
poetry update package-name

# Security check
poetry audit  # poetry-audit-plugin required

# Show dependency tree
poetry show --tree
pipenv
# Check for security vulnerabilities
pipenv check

# Update all
pipenv update

# Update specific
pipenv update package-name

# Show dependency graph
pipenv graph

优先级矩阵

优先级类型操作时间安排示例
P0严重 CVE(正在遭到利用)立即修补当天身份验证绕过、RCE
P1高危 CVE 或主要框架更新规划迁移1-2 周Next.js、React 主版本
P2已弃用但仍在使用查找替代方案2-4 周moment.js → date-fns
P3次要/补丁更新批量更新每月不会造成破坏的更新
P4未使用的依赖项移除下一个清理 PR无用的导入
优先级决策树
Is there a CVE?
├─ Yes → Is it critical/high severity?
│  ├─ Yes → P0 (patch immediately)
│  └─ No → P1 (plan update)
└─ No → Is package deprecated?
   ├─ Yes → Is it actively used?
   │  ├─ Yes → P2 (find replacement)
   │  └─ No → P4 (remove)
   └─ No → Is it outdated?
      ├─ Major version → P1 (plan migration)
      ├─ Minor/patch → P3 (batch update)
      └─ Unused → P4 (remove)

常见替代方案

日期/时间库
JavaScript/TypeScript
// ❌ moment.js (deprecated, 288KB minified)
import moment from 'moment';
const formatted = moment().format('YYYY-MM-DD');
const diff = moment(date1).diff(moment(date2), 'days');

// ✅ date-fns (tree-shakeable, 2-5KB per function)
import { format, differenceInDays } from 'date-fns';
const formatted = format(new Date(), 'yyyy-MM-dd');
const diff = differenceInDays(date1, date2);

// ✅ Native Intl (zero bundle cost)
const formatted = new Intl.DateTimeFormat('en-US').format(new Date());
const relative = new Intl.RelativeTimeFormat('en').format(-1, 'day'); // "1 day ago"
Python
# ❌ arrow (overhead for simple tasks)
import arrow
now = arrow.now().format('YYYY-MM-DD')

# ✅ Native datetime
from datetime import datetime
now = datetime.now().strftime('%Y-%m-%d')

# ✅ pendulum (for complex timezone handling)
import pendulum
now = pendulum.now('America/New_York')
实用工具库
JavaScript/TypeScript
// ❌ Full lodash import (70KB)
import _ from 'lodash';
const value = _.get(obj, 'path.to.value');
const unique = _.uniq(array);

// ✅ Specific imports (5-10KB)
import get from 'lodash/get';
import uniq from 'lodash/uniq';

// ✅ Native alternatives (0KB)
const value = obj?.path?.to?.value;           // Optional chaining
const unique = [...new Set(array)];           // Set
const keys = Object.keys(obj);                // Object.keys
const flat = array.flat();                    // Array.flat()
const grouped = Object.groupBy(arr, fn);      // Object.groupBy
HTTP 客户端
JavaScript/TypeScript
// ❌ axios (11KB) - often unnecessary
import axios from 'axios';
const { data } = await axios.get('/api/users');

// ✅ Native fetch (0KB) - built-in
const response = await fetch('/api/users');
const data = await response.json();

// ✅ ky (2KB) - if you need retries/timeout
import ky from 'ky';
const data = await ky.get('/api/users').json();
Python
# ❌ requests (large for serverless)
import requests
response = requests.get('https://api.example.com')

# ✅ httpx (async support, same API)
import httpx
async with httpx.AsyncClient() as client:
    response = await client.get('https://api.example.com')

# ✅ urllib (native, for simple cases)
from urllib.request import urlopen
response = urlopen('https://api.example.com')
测试库
JavaScript/TypeScript
// Consider consolidating test runners

// If using Jest + Vitest + Playwright separately:
// ✅ Vitest can replace Jest in most projects (faster, native ESM)
// ✅ Keep Playwright for E2E, use Vitest for unit/integration
验证库
JavaScript/TypeScript
// ❌ Multiple validation libraries
import * as yup from 'yup';
import Joi from 'joi';
import { z } from 'zod';

// ✅ Pick one (Zod recommended for TypeScript)
import { z } from 'zod';
const schema = z.object({
  email: z.string().email(),
  age: z.number().min(0)
});

更新策略

批量更新相关依赖项
# Update all ESLint-related packages together
pnpm update eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin

# Update all testing packages together
pnpm update vitest @vitest/ui @vitest/coverage-v8

# Update all Next.js packages together
pnpm update next react react-dom @types/react @types/react-dom
更新后进行测试
全面测试清单
# 1. Type check
pnpm tsc --noEmit

# 2. Lint
pnpm lint

# 3. Unit tests
pnpm test

# 4. Build verification
pnpm build

# 5. Dev server (smoke test)
pnpm dev
# Open browser, test key features

# 6. E2E tests (if available)
pnpm test:e2e
渐进式更新策略
重大版本更新
# 1. Create branch
git checkout -b chore/update-nextjs-15

# 2. Update package.json
# Change "next": "^14.0.0" → "^15.0.0"

# 3. Install
pnpm install

# 4. Read migration guide
# Visit: nextjs.org/docs/upgrading

# 5. Address breaking changes
# Follow migration guide step-by-step

# 6. Test thoroughly
pnpm test && pnpm build

# 7. Commit and PR
git add .
git commit -m "chore: upgrade Next.js to v15"

清理工作流

步骤 1:识别未使用的依赖项
npx depcheck

输出示例:

Unused dependencies
* lodash
* moment
* old-library

Unused devDependencies
* @types/old-package
* unused-test-lib
步骤 2:确认未在使用
# Search codebase for imports
rg "from 'lodash'" --type ts
rg "import.*lodash" --type ts
rg "require\('lodash'\)" --type js

# If no results → safe to remove
步骤 3:移除软件包
pnpm remove lodash
步骤 4:更新锁定文件
# npm
rm package-lock.json
npm install

# pnpm
rm pnpm-lock.yaml
pnpm install

# yarn
rm yarn.lock
yarn install
步骤 5:测试
pnpm test
pnpm build
清理 PR 模板
## Dependency Cleanup

### Security Updates (P0/P1)
- [ ] `next`: 14.0.4 → 14.2.3 (CVE-2024-XXXX)
- [ ] `jose`: 4.15.4 → 4.15.5 (CVE-2024-YYYY)

### Removed (Unused)
- [ ] `lodash` - replaced with native JS methods
- [ ] `moment` - replaced with date-fns
- [ ] `@types/old-package` - package no longer used

### Updated (Maintenance)
- [ ] `eslint`: 8.57.0 → 9.0.0
- [ ] `typescript`: 5.3.3 → 5.4.2

### Migration Notes
**lodash → Native**:
- `_.get()` → optional chaining `obj?.prop?.value`
- `_.uniq()` → `[...new Set(array)]`

**moment → date-fns**:
- `moment().format('YYYY-MM-DD')` → `format(new Date(), 'yyyy-MM-dd')`

### Testing
- [ ] All tests pass (`pnpm test`)
- [ ] Build succeeds (`pnpm build`)
- [ ] No runtime errors in dev (`pnpm dev`)
- [ ] E2E tests pass (if applicable)

### Bundle Size Impact
- Before: 2.4 MB
- After: 1.8 MB
- **Savings: 600 KB (25% reduction)**

安全扫描

自动化安全检查
GitHub Actions
# .github/workflows/security.yml
name: Security Audit

on:
  schedule:
    - cron: '0 0 * * 1'  # Weekly on Monday
  pull_request:
  push:
    branches: [main]

jobs:
  audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install dependencies
        run: npm ci

      - name: Run security audit
        run: npm audit --audit-level=high

      - name: Check for outdated packages
        run: npm outdated || true

      - name: Dependency review
        uses: actions/dependency-review-action@v4
        if: github.event_name == 'pull_request'
Snyk 集成
# .github/workflows/snyk.yml
name: Snyk Security

on: [push, pull_request]

jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Run Snyk to check for vulnerabilities
        uses: snyk/actions/node@master
        env:
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
手动安全命令
# npm security audit
npm audit

# Show only high/critical
npm audit --audit-level=high

# Get JSON report
npm audit --json > audit-report.json

# Snyk (requires: npm install -g snyk)
snyk test                    # Test for vulnerabilities
snyk monitor                 # Continuous monitoring
snyk wizard                  # Interactive fixing

# Socket.dev (supply chain security)
npx socket-npm audit
CVE 响应流程
  1. 通知:收到安全公告(GitHub、npm、Snyk)

  2. 评估影响:

    # Find where vulnerable package is used
    npm ls vulnerable-package
    
    # Check if we use vulnerable functionality
    rg "vulnerableFunction" --type ts
    
  3. 修补:

    # Update to patched version
    npm install [email protected]
    
    # Or update dependency that depends on it
    npm update parent-package
    
  4. 验证修复:

    npm audit
    # Should show 0 vulnerabilities
    
  5. 测试并部署:

    pnpm test && pnpm build
    git commit -m "fix: patch CVE-2024-XXXX in vulnerable-package"
    

开源安全

漏洞扫描回答的是“是否存在漏洞?”——但第三方风险有三个相互独立的维度。应以其中的最高风险为准,而不只是看 CVE:

  • 许可证风险 — 按许可证类型评估知识产权/法律风险:
    • 高: 强 Copyleft(GPL-2.0/3.0、AGPL-3.0、LGPL-2.1/3.0)——可能需要公开整个应用程序的源代码。在分发型/商业产品中应予以阻止。
    • 中: 弱 Copyleft(MPL-2.0、EPL-1.0)——只需公开对组件文件所做的修改。未经修改使用则可以接受。
    • 低: 宽松许可证(MIT、Apache-2.0、BSD)——只需注明出处。
    • 未知(NOASSERTION):在确认许可证前,按高风险处理。
  • CVE 加权 — 按严重程度加权(严重 ≫ 高 ≫ 中 ≫ 低),而不是只看数量;这可进一步细化上文的 P0–P4 优先级矩阵。
  • 过时程度 — 根据与最新版本的差距评分;落后一个或多个主版本,或上游已停止维护的依赖项,风险等级应上调。
# License audit
npx license-checker --failOn "GPL-3.0;AGPL-3.0;LGPL-3.0"   # JS/TS
pip-licenses --fail-on "GPL-3.0;AGPL-3.0"                  # Python

将以下内容加入月度检查清单:不得新增高风险或未知许可证;阻止存在严重/高危 CVE 的依赖项,并为中危/低危问题指定负责人和到期时间;落后超过一个主版本的依赖项,必须制定迁移计划。

完整框架请参阅 references/open-source-safety.md,其中包括等级表、CVE 加权模型、过时程度评分,以及传递依赖(“朋友的朋友”)信任模型。

改编自 CAST Highlight 的开源安全方法论 (https://doc.casthighlight.com/);许可证等级与 https://choosealicense.com/appendix/ 保持一致。


总结

月度维护检查清单
## Dependency Maintenance - [YYYY-MM]

### Security
- [ ] Run `npm audit` and address high/critical issues
- [ ] Review GitHub security advisories
- [ ] Check Snyk dashboard (if integrated)

### Updates
- [ ] Check `npm outdated` for major updates
- [ ] Update patch versions: `npm update`
- [ ] Plan migration for deprecated packages

### Cleanup
- [ ] Run `npx depcheck` to find unused deps
- [ ] Remove packages with zero imports
- [ ] Deduplicate: `npm dedupe`

### Testing
- [ ] Run full test suite
- [ ] Check build succeeds
- [ ] Verify dev server works
- [ ] Test in production-like environment

### Documentation
- [ ] Update CHANGELOG.md
- [ ] Document breaking changes
- [ ] Update .env.example if needed
最佳实践
  • 自动化:设置 GitHub Actions,每周进行审计
  • 批量更新:将相关的依赖项更新分组处理
  • 全面测试:更新后绝不跳过测试
  • 记录文档:及时更新 CHANGELOG.md
  • 衡量影响:跟踪打包体积的变化
  • 及时了解动态:订阅安全公告
  • 使用锁定文件:提交 package-lock.json/pnpm-lock.yaml
  • 渐进式迁移:不要一次性更新所有内容

评论

支持 Markdown