tiagoFlach/dep-trust-score

GitHub: tiagoFlach/dep-trust-score

通过综合分析维护频率、安全漏洞等指标,为 npm 依赖包计算透明可审计的信任评分,帮助团队规避软件供应链风险。

Stars: 0 | Forks: 0

# dep-trust-score [![npm version](https://badge.fury.io/js/dep-trust-score.svg)](https://badge.fury.io/js/dep-trust-score) [![Build Status](https://github.com/tiagoFlach/dep-trust-score/actions/workflows/ci.yml/badge.svg)](https://github.com/tiagoFlach/dep-trust-score) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) 使用有关维护活动、安全记录和生态系统稳定性的客观数据,自动计算 npm 依赖项的信任度。在 CI/CD 流水线中使用它来执行质量标准、防止供应链攻击,并对您的依赖项做出明智的决策。 ## 功能 ✨ **透明评分**:每个分数都有详细的、可解释的因素支持,并支持配置权重 🔒 **安全第一**:检测漏洞、追踪废弃信号并识别高风险依赖项 ⚡ **快速与缓存**:本地缓存减少了 API 调用;离线模式适用于物理隔离环境 🎯 **灵活配置**:根据不同的上下文(生产环境、关键系统、原型设计)调整权重 📊 **多种输出**:用于自动化的 JSON 格式、用于终端的人类可读文本以及详细的报告 🔄 **批量分析**:在单个操作中高效分析多个包 🎮 **编程 API**:在 Node.js 应用程序中使用,提供完整的 TypeScript 支持 ⚙️ **CLI 工具**:用于快速检查和 CI/CD 集成的命令行界面 ## 安装 ``` npm install -g dep-trust-score ``` 或者作为 dev dependency 安装: ``` npm install --save-dev dep-trust-score ``` ## 快速开始 ### CLI 使用 ``` # 检查单个 package trust-score check express # 分析多个 package trust-score batch express lodash react # 获取详细说明 trust-score explain express # 查看 cache 统计信息 trust-score cache stats # 清除 cache trust-score cache clear ``` ### 编程 API ``` import { TrustScoreAPI } from 'dep-trust-score'; const api = new TrustScoreAPI(); // Analyze a single package const score = await api.analyzePackage('express'); console.log(`Express trust score: ${score.score}/100`); // Analyze multiple packages const result = await api.analyzePackages(['express', 'lodash', 'react']); console.log(`Average score: ${result.summary.averageScore}/100`); ``` ## 评分因素 信任分数 (0-100) 由 8 个独立因素计算得出: ### 1. **发布频率** (默认权重 15%) - 衡量包的维护活跃程度 - 定期发布的包得分更高 - **信号**:> 12 次发布/年 = 100,无发布 = 0 ### 2. **包年龄** (权重 10%) - 较老的、成熟的包往往更可靠 - 较新的包风险较高,但如果其他因素表现良好,也能获得高分 - **信号**:1-5 年 = 100,< 1 个月 = 50,> 5 年 = 70+ ### 3. **维护者** (权重 15%) - 多个维护者可降低废弃或单点故障的风险 - **信号**:3 个以上维护者 = 100,1 个 = 60,0 个 = 20 ### 4. **版本历史** (权重 10%) - 丰富的版本历史表明了成熟度和完善度 - **信号**:> 100 个版本 = 100,5 个以上 = 60,1-2 个 = 40 ### 5. **漏洞** (权重 25% - 默认最高) - 已知的 CVE 和安全问题直接影响信任度 - 严重漏洞会大幅扣分 - **信号**:无漏洞 = 100,1 个严重漏洞 = 60,2 个及以上 = 20 ### 6. **依赖复杂度** (权重 10%) - 依赖较少的包具有更小的攻击面 - 过深的依赖树会增加维护负担 - **信号**:0 个依赖 = 100,5-10 个 = 80,50 个及以上 = 30 ### 7. **废弃信号** (权重 10%) - 检测最近未更新的包 - **信号**:上次发布 < 6 个月 = 100,1 年以上 = 50,3 年以上 = 10 ### 8. **包质量** (权重 5%) - 是否包含描述、文档、许可证等 - **信号**:元数据完整 = 100,极简 = 20 ## 理解分数 | 分数 | 状态 | 建议 | |-------|--------|-----------------| | 80-100 | ✅ 优秀 | 可安全用于生产环境 | | 60-79 | ⚠️ 良好 | 通常安全,定期审查 | | 40-59 | ⚠️ 注意 | 仔细审查,在非关键上下文中使用 | | 0-39 | ❌ 危险 | 避免使用或计划替换 | ## 配置 ### 自定义权重 根据您的具体用例调整权重: ``` import { TrustScoreAPI } from 'dep-trust-score'; // Production environment: maximum security focus const productionWeights = { vulnerabilities: 40, publicationFrequency: 15, maintainers: 15, versionHistory: 10, packageAge: 5, dependencies: 10, abandonmentSignals: 5, packageQuality: 0, }; const api = new TrustScoreAPI({ weights: productionWeights }); const score = await api.analyzePackage('express'); ``` 有关更多示例,请参见 [context-specific-weights.ts](examples/context-specific-weights.ts)。 ### 特定环境权重 - **生产环境**:最高安全性,久经考验的稳定性 - **原型设计**:在可靠性与速度之间取得平衡 - **关键系统**:极端的安全性与可靠性关注 - **最小依赖**:最小化外部依赖 ## 离线模式 适用于物理隔离环境或减少网络调用的情况: ``` const api = new TrustScoreAPI(); // Populate cache await api.analyzePackage('express'); // Switch to offline mode api.setOfflineMode(true); // Serves from cache or fails gracefully const score = await api.analyzePackage('express'); ``` ### 缓存管理 ``` // Get cache statistics const stats = api.getCacheStats(); console.log(`Cache size: ${stats.totalSize / 1024} KB, ${stats.fileCount} packages`); // Clear cache api.clearCache(); // Export cache data const cached = api.exportCacheData(); ``` ## CI/CD 集成 ### GitHub Actions 使用包含的 GitHub Actions 工作流在每个 pull request 上检查依赖项: ``` - name: Install trust-score run: npm install -g dep-trust-score - name: Check dependencies run: trust-score batch express lodash react --output json ``` 有关完整示例,请参见 [github-actions.yml](examples/github-actions.yml)。 ### Shell 脚本 ``` #!/bin/bash THRESHOLD=70 for package in express lodash react; do SCORE=$(trust-score check $package --output json | jq .score) if (( $(echo "$SCORE < $THRESHOLD" | bc -l) )); then echo "❌ $package score ($SCORE) below threshold ($THRESHOLD)" exit 1 fi done ``` ### NPM 脚本 ``` { "scripts": { "check:deps": "trust-score batch react redux axios --threshold 60", "check:deps:critical": "trust-score batch react --weights '{\"vulnerabilities\": 50}'" } } ``` ## CLI 命令 ### `trust-score check ` 检查单个包的信任分数。 ``` trust-score check express --output table --explain ``` **选项:** - `--output, -o`:输出格式:`json`、`text`、`table` (默认:`text`) - `--explain, -e`:显示所有因素的详细明细 - `--offline`:使用离线模式 (仅缓存) - `--refresh, -r`:强制从 npm registry 刷新 - `--weights, -w`:作为 JSON 字符串的自定义权重 - `--cache`:自定义缓存目录 ### `trust-score batch ` 高效分析多个包。 ``` trust-score batch express lodash react --threshold 60 --output json ``` **选项:** - `--output, -o`:输出格式:`json`、`text`、`table` (默认:`text`) - `--threshold, -t`:最低分数 (默认:50) - `--offline`:使用离线模式 (仅缓存) - `--weights, -w`:作为 JSON 字符串的自定义权重 ### `trust-score explain ` 获取对分数有贡献的所有因素的详细解释。 ``` trust-score explain express ``` ### `trust-score cache ` 管理本地缓存。 ``` trust-score cache stats # Show cache statistics trust-score cache export # Export all cached scores trust-score cache clear # Clear the cache ``` ### `trust-score config` 显示当前配置和权重。 ``` trust-score config ``` ## API 参考 ### `TrustScoreAPI` 用于编程访问的主类。 ``` import { TrustScoreAPI } from 'dep-trust-score'; const api = new TrustScoreAPI(options); ``` **选项:** ``` interface TrustScoreOptions { weights?: ScoreWeights; // Custom weight configuration offline?: boolean; // Start in offline mode forceRefresh?: boolean; // Always fetch fresh data cacheDir?: string; // Custom cache directory } ``` ### 方法 #### `analyzePackage(packageName: string, forceRefresh?: boolean): Promise` 分析单个包。如果可用则返回缓存结果。 ``` const score = await api.analyzePackage('express'); console.log(score.score); // 85.5 console.log(score.confidence); // 95.2 ``` #### `analyzePackages(packageNames: string[]): Promise` 批量分析多个包。 ``` const result = await api.analyzePackages(['express', 'lodash']); console.log(result.summary.averageScore); // 82.3 console.log(result.packages.length); // 2 ``` #### `setWeights(weights: ScoreWeights): void` 更新评分权重。 ``` api.setWeights({ vulnerabilities: 50, publicationFrequency: 20, }); ``` #### `setOfflineMode(enabled: boolean): void` 启用或禁用离线模式。 ``` api.setOfflineMode(true); ``` #### `getCacheStats(): { cacheDir: string; fileCount: number; totalSize: number }` 获取缓存统计信息。 ``` const stats = api.getCacheStats(); console.log(`${stats.fileCount} packages cached`); ``` #### `clearCache(): void` 清除所有缓存数据。 ``` api.clearCache(); ``` ## TypeScript 支持 包含完整的 TypeScript 类型: ``` import { TrustScoreAPI, TrustScore, ScoreFactors, PackageAnalysisData, ScoreWeights, BatchAnalysisResult, } from 'dep-trust-score'; const score: TrustScore = await api.analyzePackage('express'); ``` ## 示例 ### 示例 1:生产依赖检查 ``` import { TrustScoreAPI } from 'dep-trust-score'; const api = new TrustScoreAPI({ weights: { vulnerabilities: 40, // Security is critical publicationFrequency: 15, maintainers: 15, versionHistory: 10, packageAge: 5, dependencies: 10, abandonmentSignals: 5, } }); const score = await api.analyzePackage('express'); if (score.score < 70) { throw new Error(`Production: ${score.package} trust score too low (${score.score})`); } ``` ### 示例 2:带报告的批量分析 ``` import { TrustScoreAPI } from 'dep-trust-score'; const api = new TrustScoreAPI(); const packages = ['express', 'lodash', 'react', 'vue', 'angular']; const result = await api.analyzePackages(packages); console.log(`Average trust score: ${result.summary.averageScore}/100`); console.log(`Critical packages: ${result.summary.criticalCount}`); const lowestScored = result.packages.sort((a, b) => a.score - b.score)[0]; console.log(`Lowest scored: ${lowestScored.package} (${lowestScored.score})`); ``` ### 示例 3:详细分析报告 ``` const score = await api.analyzePackage('react'); console.log(`Package: ${score.package}`); console.log(`Score: ${score.score}/100`); console.log(`Confidence: ${score.confidence}%`); console.log('\nFactors:'); const b = score.breakdown; console.log(` Vulnerabilities: ${b.vulnerabilities.value}/100 (${b.vulnerabilities.explanation})`); console.log(` Maintainers: ${b.maintainers.value}/100 (${b.maintainers.explanation})`); console.log(` Publication Frequency: ${b.publicationFrequency.value}/100`); console.log(` Abandonment Signals: ${b.abandonmentSignals.value}/100`); ``` 有关更多示例,请参见 [examples/](examples/) 目录。 ## 测试 ``` # 运行所有测试 npm test # 运行并生成覆盖率报告 npm run test:coverage # Watch 模式 npm run test:watch ``` ## 架构 该包遵循清晰、模块化的架构: ``` src/ ├── core/ │ └── types.ts # Core type definitions ├── collectors/ │ └── DataCollector.ts # Fetches npm registry data ├── calculators/ │ └── ScoreCalculator.ts # Calculates trust scores ├── cache/ │ └── LocalCache.ts # Local cache management ├── cli/ │ ├── index.ts # CLI interface │ └── formatters.ts # Output formatting └── index.ts # Main API export ``` ## 贡献 欢迎贡献!请: 1. Fork 本仓库 2. 创建一个 feature 分支 3. 为新功能添加测试 4. 提交一个 pull request ## 性能 - **首次运行**:每个包约 500ms (网络 + 处理) - **缓存运行**:每个包 <10ms - **50 个包的批量分析**:约 15 秒 (启用缓存) ## 限制 - 首次运行需要网络访问 (除非使用离线模式) - 漏洞数据依赖于公共数据库 - 某些包可能在 npm 上没有完整的元数据 - 由社区维护;非官方 npm 项目 ## 未来增强 - [ ] GitHub 安全公告集成 - [ ] npm audit API 集成 - [ ] SBOM (软件物料清单) 支持 - [ ] 历史趋势追踪 - [ ] 分数变化的 Webhook 通知 - [ ] Web 仪表板 UI - [ ] 企业功能 (自定义 registry、身份验证) ## 许可证 MIT ## 支持 - 📖 [文档](docs/) - 🐛 [问题追踪](https://github.com/tiagoFlach/dep-trust-score/issues) - 💬 [讨论](https://github.com/tiagoFlach/dep-trust-score/discussions) **用 ❤️ 制作,以保持 npm 依赖项的安全和可信**
标签:GNU通用公共许可证, LNA, MITM代理, Node.js, npm, TypeScript, 依赖安全, 依赖管理, 信任评分, 包管理器, 安全插件, 文档结构分析, 暗色界面, 统一API, 自动化攻击, 软件质量, 防御废弃依赖, 风险评估工具