/** * @fileoverview Security Analytics Engine * @module @nahisaho/musubix-security/intelligence/security-analytics * * Provides trend analysis, metrics collection, statistical reporting, * and security insights for comprehensive security management. * * NOTE: This analytics engine consumes vulnerability data from the security package's * scanners. Its severity-to-score mapping (critical=100, high=75, medium=50, low=25, * info=10) is specific to risk analytics and differs from the security score deduction * weights in core's SecurityScanner (which starts from 100 and deducts per finding). * These are distinct calculation models serving different purposes: this engine tracks * trends over time, while core's scanner produces a point-in-time quality score. */ import type { Vulnerability } from '../types/index.js'; import type { RiskSummary } from './risk-scorer.js'; /** * Time period for analytics */ export type TimePeriod = 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'; /** * Security metric type */ export type MetricType = 'vulnerability-count' | 'average-risk-score' | 'mean-time-to-remediate' | 'security-debt' | 'fix-rate' | 'detection-rate' | 'false-positive-rate' | 'coverage'; /** * Security metric */ export interface SecurityMetric { /** Metric type */ type: MetricType; /** Metric value */ value: number; /** Unit */ unit: string; /** Timestamp */ timestamp: Date; /** Period */ period: TimePeriod; /** Change from previous period */ change?: { value: number; percentage: number; direction: 'up' | 'down' | 'stable'; }; /** Breakdown by category */ breakdown?: Record; } /** * Security trend */ export interface SecurityTrend { /** Trend name */ name: string; /** Metric type */ metricType: MetricType; /** Data points */ dataPoints: { timestamp: Date; value: number; }[]; /** Trend direction */ direction: 'improving' | 'declining' | 'stable'; /** Trend strength (0-1) */ strength: number; /** Forecast for next period */ forecast?: number; /** Insights */ insights: string[]; } /** * Vulnerability statistics */ export interface VulnerabilityStats { /** Total count */ total: number; /** By severity */ bySeverity: { critical: number; high: number; medium: number; low: number; info: number; }; /** By type */ byType: Record; /** By file */ byFile: Record; /** New vulnerabilities in period */ newInPeriod: number; /** Fixed vulnerabilities in period */ fixedInPeriod: number; /** Average age (days) */ averageAge: number; /** Oldest vulnerability age (days) */ oldestAge: number; } /** * Security score card */ export interface SecurityScorecard { /** Overall score (0-100) */ overallScore: number; /** Grade (A-F) */ grade: 'A' | 'B' | 'C' | 'D' | 'F'; /** Category scores */ categoryScores: { category: string; score: number; weight: number; }[]; /** Key findings */ keyFindings: string[]; /** Improvement suggestions */ improvements: string[]; /** Comparison with industry */ industryComparison?: { percentile: number; average: number; }; /** Historical scores */ history: { period: string; score: number; }[]; } /** * Security dashboard data */ export interface SecurityDashboard { /** Summary */ summary: { totalVulnerabilities: number; criticalCount: number; overallRisk: number; securityScore: number; trend: 'improving' | 'declining' | 'stable'; }; /** Recent activity */ recentActivity: { timestamp: Date; type: 'vulnerability-found' | 'vulnerability-fixed' | 'scan-completed'; description: string; }[]; /** Top risks */ topRisks: { vulnerability: Vulnerability; riskScore: number; daysOpen: number; }[]; /** Metrics */ metrics: SecurityMetric[]; /** Trends */ trends: SecurityTrend[]; /** Scorecard */ scorecard: SecurityScorecard; /** Generated at */ generatedAt: Date; } /** * Analytics report */ export interface AnalyticsReport { /** Report ID */ id: string; /** Report title */ title: string; /** Period covered */ period: { start: Date; end: Date; }; /** Executive summary */ executiveSummary: string; /** Key metrics */ keyMetrics: SecurityMetric[]; /** Trends */ trends: SecurityTrend[]; /** Vulnerability stats */ vulnerabilityStats: VulnerabilityStats; /** Risk summary */ riskSummary: RiskSummary; /** Recommendations */ recommendations: { priority: 'high' | 'medium' | 'low'; description: string; impact: string; }[]; /** Generated at */ generatedAt: Date; } /** * Analytics event */ export interface AnalyticsEvent { /** Event ID */ id: string; /** Event type */ type: 'scan' | 'vulnerability' | 'fix' | 'alert' | 'report'; /** Timestamp */ timestamp: Date; /** Data */ data: Record; /** Tags */ tags: string[]; } /** * Security Analytics options */ export interface SecurityAnalyticsOptions { /** Data retention period in days */ retentionDays?: number; /** Enable real-time metrics */ enableRealtime?: boolean; /** Industry benchmark data */ industryBenchmark?: Record; /** Custom metric calculators */ customMetrics?: Map number>; } /** * Security Analytics Engine */ export declare class SecurityAnalytics { private options; private events; private metricsHistory; private vulnerabilityHistory; constructor(options?: SecurityAnalyticsOptions); /** * Record an analytics event */ recordEvent(event: Omit): void; /** * Record vulnerability discovery */ recordVulnerability(vulnerability: Vulnerability): void; /** * Record vulnerability fix */ recordFix(vulnerabilityId: string): void; /** * Record scan completion */ recordScan(scanResults: { filesScanned: number; vulnerabilitiesFound: number; duration: number; }): void; /** * Prune old events */ private pruneOldEvents; /** * Get events by type */ getEventsByType(type: AnalyticsEvent['type'], since?: Date): AnalyticsEvent[]; /** * Calculate metric for a period */ calculateMetric(type: MetricType, period?: TimePeriod): SecurityMetric; /** * Get period start date */ private getPeriodStart; /** * Get previous period start date */ private getPreviousPeriodStart; /** * Calculate average risk from events */ private calculateAverageRisk; /** * Calculate previous period value */ private calculatePreviousPeriodValue; /** * Calculate mean time to remediate */ private calculateMTTR; /** * Calculate security debt */ private calculateSecurityDebt; /** * Calculate trend */ calculateTrend(metricType: MetricType, dataPoints?: number): SecurityTrend; /** * Simple linear regression */ private linearRegression; /** * Generate trend insights */ private generateTrendInsights; /** * Get vulnerability statistics */ getVulnerabilityStats(since?: Date): VulnerabilityStats; /** * Generate security scorecard */ generateScorecard(): SecurityScorecard; /** * Convert score to grade */ private scoreToGrade; /** * Get historical scores */ private getHistoricalScores; /** * Generate dashboard data */ generateDashboard(): SecurityDashboard; /** * Format event description */ private formatEventDescription; /** * Generate analytics report */ generateReport(startDate: Date, endDate: Date): AnalyticsReport; /** * Generate executive summary */ private generateExecutiveSummary; /** * Generate report recommendations */ private generateReportRecommendations; /** * Get all metrics */ getAllMetrics(period?: TimePeriod): SecurityMetric[]; /** * Export analytics data */ exportData(): { events: AnalyticsEvent[]; metricsHistory: Record; vulnerabilityHistory: Record; }; } /** * Create a SecurityAnalytics instance */ export declare function createSecurityAnalytics(options?: SecurityAnalyticsOptions): SecurityAnalytics; /** * Quick dashboard generation */ export declare function generateDashboard(events: AnalyticsEvent[]): SecurityDashboard; //# sourceMappingURL=security-analytics.d.ts.map