@depsshield/core
v0.2.0
Published
Core scoring engine and data clients for DepsShield
Maintainers
Readme
@depsshield/core
Core scoring engine and data clients for DepsShield. This package provides the foundation for assessing npm package security risks.
Quick Start
import { PackageAssessor } from '@depsshield/core';
const assessor = new PackageAssessor();
const score = await assessor.assess('lodash', '4.17.20');
console.log(`Risk Level: ${score.riskLevel}`);
console.log(`Total Score: ${score.total}/200`);
console.log(`Vulnerabilities: ${score.vulnerabilities.length}`);
console.log(`Recommendation: ${score.recommendation}`);Features
✅ Vulnerability Detection - Fetches CVE data from OSV.dev ✅ Package Metadata - Retrieves npm registry information ✅ 3-Component Risk Scoring - Vulnerability + Maintenance + Popularity (0-200 scale) ✅ Smart Recommendations - Context-aware guidance with version suggestions ✅ Type-Safe - Full TypeScript support with strict mode ✅ Error Handling - Comprehensive error types and retry logic ✅ Well-Tested - 66 passing tests (29 unit + 37 integration)
Architecture
@depsshield/core/
├── assessment/ # Main orchestration layer
│ ├── assessor.ts # PackageAssessor (public API)
│ └── README.md # → Detailed docs
├── data/ # External API clients
│ ├── osv.ts # OSV.dev vulnerability client
│ ├── npm.ts # npm registry client
│ ├── cache.ts # Caching layer
│ └── README.md # → Detailed docs
├── scoring/ # Risk scoring algorithm ✅
│ ├── calculator.ts # Scoring logic (COMPLETE)
│ ├── weights.ts # Scoring constants
│ └── README.md # → Detailed docs
├── types/ # TypeScript type definitions
│ └── index.ts
└── utils/ # Shared utilities
├── errors.ts # Error types
├── validation.ts # Input validation
├── retry.ts # Retry logic
└── README.md # → Detailed docsDetailed Documentation
For implementation details, see the module-specific READMEs:
- src/assessment/ - Package assessment orchestration
- src/data/ - OSV and npm API clients
- src/scoring/ - Risk scoring algorithm
- src/utils/ - Error handling, validation, retry logic
API Reference
Main API: PackageAssessor
class PackageAssessor {
constructor(config?: AssessorConfig);
async assess(packageName: string, version?: string): Promise<DepsShieldScore>;
}Returns: DepsShieldScore
Data Clients
// OSV Client - Vulnerability data
class OSVClient {
async queryVulnerabilities(
ecosystem: string,
packageName: string,
version?: string
): Promise<Vulnerability[]>;
}
// npm Client - Package metadata
class NpmClient {
async getPackageMetadata(packageName: string, version?: string): Promise<PackageMetadata>;
async getDownloadStats(packageName: string): Promise<number>;
}See: Data Clients Documentation
Scoring ✅
// Individual scoring components
function calculateVulnerabilityScore(vulnerabilities: Vulnerability[]): number;
function calculateMaintenanceScore(lastUpdate: Date): number;
function calculatePopularityScore(weeklyDownloads: number): number;
// Complete scoring orchestration
function calculateCompleteScore(
vulnerabilities: Vulnerability[],
metadata: PackageMetadata
): { total: number; riskLevel: RiskLevel; components: ScoreComponents };
// Risk classification
function classifyRisk(total: number): RiskLevel;Scoring System:
- Vulnerability Score (0-100): CRITICAL: 40, HIGH: 25, MEDIUM: 10, LOW: 5 (capped)
- Maintenance Score (0-50): >2y: 50, 1-2y: 30, 6-12m: 15, <6m: 0
- Popularity Score (0-50): <1K: 25, <10K: 15, <100K: 5, ≥100K: 0
Usage Examples
Basic Assessment
import { PackageAssessor } from '@depsshield/core';
const assessor = new PackageAssessor();
// Assess latest version
const latest = await assessor.assess('express');
// Assess specific version
const specific = await assessor.assess('lodash', '4.17.20');
// Assess scoped package
const scoped = await assessor.assess('@types/node');Custom Configuration
import { PackageAssessor, OSVClient, NpmClient } from '@depsshield/core';
const assessor = new PackageAssessor({
osvClient: new OSVClient({ timeout: 15000 }),
npmClient: new NpmClient({ timeout: 15000 }),
});Error Handling
import { PackageAssessor, PackageNotFoundError, ValidationError } from '@depsshield/core';
try {
const score = await assessor.assess('my-package');
} catch (error) {
if (error instanceof PackageNotFoundError) {
console.error('Package not found in npm registry');
} else if (error instanceof ValidationError) {
console.error('Invalid package name:', error.message);
} else {
console.error('Unexpected error:', error);
}
}Development
Setup
cd packages/core
pnpm install
pnpm buildTesting
# Run all tests
pnpm test
# Run specific test suite
pnpm test data/__tests__/osv.test.ts
# Watch mode
pnpm test:watch
# Coverage
pnpm test:coverageBuilding
# Build once
pnpm build
# Clean build
pnpm clean && pnpm buildTest Coverage
Total: 66 passing tests across 4 test suites
| Module | Tests | Status | Details | | --------------- | ----- | ---------- | -------------------------- | | Scoring | 29 | ✅ Passing | Unit tests for all scoring | | OSV Client | 8 | ✅ Passing | Integration with OSV API | | npm Client | 13 | ✅ Passing | Integration with npm API | | PackageAssessor | 16 | ✅ Passing | End-to-end assessments |
See individual module READMEs for detailed test descriptions.
Implementation Status
✅ Completed (Week 1)
Day 1-2: Project Setup
- [x] Monorepo with pnpm workspaces
- [x] TypeScript strict mode configuration
- [x] Testing framework (Vitest)
- [x] Linting & formatting (ESLint, Prettier)
Day 3-5: Data Integration
- [x] OSV API client with vulnerability detection
- [x] npm Registry client with metadata & downloads
- [x] PackageAssessor orchestration
- [x] Error handling & validation
- [x] Retry logic with exponential backoff
- [x] Integration tests with real packages
Day 6-7: Scoring Engine
- [x] Vulnerability scoring (0-100)
- [x] Maintenance scoring (0-50)
- [x] Popularity scoring (0-50)
- [x] Complete score calculation
- [x] Enhanced recommendation generation
- [x] Comprehensive unit tests (29 tests)
📅 Upcoming (Week 2-4)
- [ ] Week 2: MCP server integration
- [ ] Week 3: REST API + Redis caching
- [ ] Week 4: CLI implementation
Performance
Target Metrics:
- p95 Response Time: < 3 seconds
- Cache Hit Rate: > 80% (with Redis)
- Vulnerability Detection: 100% accuracy
Current Performance (without caching):
- OSV query: 500-2000ms
- npm metadata: 100-500ms
- Total (parallel): ~2000ms
Dependencies
Runtime
node-cache- In-memory caching
Development
typescript- Type checkingvitest- Testing framework@types/node- Node.js types
TypeScript
Strict mode enabled with full type coverage:
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"declaration": true
}
}Contributing
See ../../DEVELOPMENT.md for development guidelines.
License
MIT
Related Packages
@depsshield/mcp-server- MCP protocol implementation (Week 2)@depsshield/cli- Command-line interface (Week 1)
Status: ✅ Week 1 Complete - Full implementation with 3-component scoring Test Coverage: 66 tests passing (29 unit + 37 integration) Next: Week 2 - MCP Server implementation
For questions or issues, see ../../TODO.md for current development status.
