UNPKG

@iota-big3/sdk-security

Version:

Advanced security features including zero trust, quantum-safe crypto, and ML threat detection

925 lines (924 loc) 28.4 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ComplianceAutomation = void 0; const crypto = __importStar(require("crypto")); const events_1 = require("events"); const fs = __importStar(require("fs/promises")); const path = __importStar(require("path")); const pdfkit_1 = __importDefault(require("pdfkit")); class ComplianceAutomation extends events_1.EventEmitter { constructor(config, logger) { super(); this.controls = new Map(); this.evidenceCache = new Map(); this.config = config; this.logger = logger; this.loadControlDefinitions(); if (config.autoAssessment) { this.startAutomatedAssessment(); } } // Load control definitions for each framework async loadControlDefinitions() { for (const framework of this?.config?.frameworks) { const controls = await this.loadFrameworkControls(framework); controls.forEach(control => { this?.controls?.set(`${framework}:${control.id}`, control); }); } this?.logger?.info('Compliance controls loaded', { frameworks: this?.config?.frameworks, totalControls: this?.controls?.size }); } // Load framework-specific controls async loadFrameworkControls(framework) { switch (framework) { case 'SOC2': return this.loadSOC2Controls(); case 'HIPAA': return this.loadHIPAAControls(); case 'GDPR': return this.loadGDPRControls(); case 'PCI_DSS': return this.loadPCIDSSControls(); case 'ISO27001': return this.loadISO27001Controls(); case 'NIST': return this.loadNISTControls(); default: return []; } } // SOC2 Trust Service Criteria loadSOC2Controls() { return [ {}, id, 'CC1.1', framework, 'SOC2', title, 'Control Environment', description, 'The entity demonstrates a commitment to integrity and ethical values', category, 'Common Criteria', automationSupported, true, assessmentMethod, async (context) => this.assessControlEnvironment(context), requiredEvidence, ['code_of_conduct', 'ethics_policy', 'training_records'] ]; } } exports.ComplianceAutomation = ComplianceAutomation; { id: 'CC2.1', framework; 'SOC2', title; 'Information and Communication', description; 'The entity obtains or generates relevant quality information', category; 'Common Criteria', automationSupported; true, assessmentMethod; async (context) => this.assessInformationQuality(context), requiredEvidence; ['data_classification', 'information_flow', 'communication_policy']; } { id: 'CC6.1', framework; 'SOC2', title; 'Logical and Physical Access Controls', description; 'The entity implements logical access security measures', category; 'Common Criteria', automationSupported; true, assessmentMethod; async (context) => this.assessAccessControls(context), requiredEvidence; ['access_logs', 'user_permissions', 'authentication_config']; } { id: 'CC7.1', framework; 'SOC2', title; 'System Operations', description; 'The entity monitors system components for anomalies', category; 'Common Criteria', automationSupported; true, assessmentMethod; async (context) => this.assessSystemMonitoring(context), requiredEvidence; ['monitoring_logs', 'alert_config', 'incident_reports']; } { id: 'A1.1', framework; 'SOC2', title; 'Availability', description; 'The entity maintains system availability commitments', category; 'Availability', automationSupported; true, assessmentMethod; async (context) => this.assessAvailability(context), requiredEvidence; ['uptime_reports', 'sla_metrics', 'dr_tests']; } loadHIPAAControls(); ControlDefinition[]; { return [ {}, id, '164.308(a)(1)', framework, 'HIPAA', title, 'Security Management Process', description, 'Implement policies to prevent, detect, contain, and correct violations', category, 'Administrative Safeguards', automationSupported, true, assessmentMethod, async (context) => this.assessSecurityManagement(context), requiredEvidence, ['risk_assessment', 'security_policies', 'violation_logs'] ]; } { id: '164.308(a)(3)', framework; 'HIPAA', title; 'Workforce Security', description; 'Ensure workforce members have appropriate access to ePHI', category; 'Administrative Safeguards', automationSupported; true, assessmentMethod; async (context) => this.assessWorkforceSecurity(context), requiredEvidence; ['access_matrix', 'termination_procedures', 'training_completion']; } { id: '164.312(a)(1)', framework; 'HIPAA', title; 'Access Control', description; 'Implement technical policies for electronic access control', category; 'Technical Safeguards', automationSupported; true, assessmentMethod; async (context) => this.assessTechnicalAccessControl(context), requiredEvidence; ['access_logs', 'unique_identifiers', 'encryption_status']; } { id: '164.312(b)', framework; 'HIPAA', title; 'Audit Controls', description; 'Implement audit controls to record and examine activity', category; 'Technical Safeguards', automationSupported; true, assessmentMethod; async (context) => this.assessAuditControls(context), requiredEvidence; ['audit_logs', 'log_reviews', 'retention_policy']; } loadGDPRControls(); ControlDefinition[]; { return [ {}, id, 'Art6', framework, 'GDPR', title, 'Lawfulness of Processing', description, 'Processing shall be lawful only if consent or legal basis exists', category, 'Legal Basis', automationSupported, true, assessmentMethod, async (context) => this.assessLawfulBasis(context), requiredEvidence, ['consent_records', 'legal_basis_documentation', 'processing_registry'] ]; } { id: 'Art25', framework; 'GDPR', title; 'Data Protection by Design', description; 'Implement appropriate technical and organizational measures', category; 'Privacy by Design', automationSupported; true, assessmentMethod; async (context) => this.assessPrivacyByDesign(context), requiredEvidence; ['dpia_results', 'privacy_controls', 'technical_measures']; } { id: 'Art32', framework; 'GDPR', title; 'Security of Processing', description; 'Implement appropriate security measures', category; 'Security', automationSupported; true, assessmentMethod; async (context) => this.assessProcessingSecurity(context), requiredEvidence; ['encryption_inventory', 'security_measures', 'breach_procedures']; } { id: 'Art33', framework; 'GDPR', title; 'Breach Notification', description; 'Notify supervisory authority within 72 hours', category; 'Incident Response', automationSupported; true, assessmentMethod; async (context) => this.assessBreachNotification(context), requiredEvidence; ['breach_log', 'notification_procedures', 'response_times']; } loadPCIDSSControls(); ControlDefinition[]; { return [ {}, id, '1.1', framework, 'PCI_DSS', title, 'Firewall Configuration Standards', description, 'Establish and implement firewall and router configuration standards', category, 'Network Security', automationSupported, true, assessmentMethod, async (context) => this.assessFirewallConfig(context), requiredEvidence, ['firewall_rules', 'network_diagram', 'change_logs'] ]; } { id: '2.1', framework; 'PCI_DSS', title; 'Default Passwords', description; 'Always change vendor-supplied defaults', category; 'System Configuration', automationSupported; true, assessmentMethod; async (context) => this.assessDefaultPasswords(context), requiredEvidence; ['password_policy', 'system_inventory', 'config_standards']; } { id: '3.4', framework; 'PCI_DSS', title; 'PAN Encryption', description; 'Render PAN unreadable anywhere it is stored', category; 'Data Protection', automationSupported; true, assessmentMethod; async (context) => this.assessPANEncryption(context), requiredEvidence; ['encryption_keys', 'data_inventory', 'encryption_methods']; } loadISO27001Controls(); ControlDefinition[]; { return [ {}, id, 'A?.5?.1.1', framework, 'ISO27001', title, 'Information Security Policies', description, 'A set of policies for information security shall be defined', category, 'Information Security Policies', automationSupported, false, requiredEvidence, ['security_policies', 'approval_records', 'review_schedule'] ]; } { id: 'A?.9?.1.1', framework; 'ISO27001', title; 'Access Control Policy', description; 'An access control policy shall be established', category; 'Access Control', automationSupported; true, assessmentMethod; async (context) => this.assessAccessControlPolicy(context), requiredEvidence; ['access_policy', 'user_roles', 'access_reviews']; } loadNISTControls(); ControlDefinition[]; { return [ {}, id, 'ID.AM-1', framework, 'NIST', title, 'Asset Inventory', description, 'Physical devices and systems are inventoried', category, 'Identify - Asset Management', automationSupported, true, assessmentMethod, async (context) => this.assessAssetInventory(context), requiredEvidence, ['asset_inventory', 'system_diagram', 'update_logs'] ]; } { id: 'PR.AC-1', framework; 'NIST', title; 'Identity Management', description; 'Identities and credentials are managed for authorized entities', category; 'Protect - Access Control', automationSupported; true, assessmentMethod; async (context) => this.assessIdentityManagement(context), requiredEvidence; ['identity_registry', 'credential_policy', 'access_logs']; } async; assessControlEnvironment(context, any); Promise < security_types_1.ComplianceStatus > { // Check for existence of required policies const: hasCodeOfConduct = await this.checkEvidence('code_of_conduct'), const: hasEthicsPolicy = await this.checkEvidence('ethics_policy'), const: hasTraining = await this.checkEvidence('training_records'), if(hasCodeOfConduct) { } } && hasEthicsPolicy && hasTraining; { return 'compliant'; } if (hasCodeOfConduct || hasEthicsPolicy) { return 'partial'; } return 'non_compliant'; async; assessAccessControls(context, any); Promise < security_types_1.ComplianceStatus > { // Check authentication configuration const: hasMFA = context.security?.mfaEnabled || false, const: hasRBAC = context.security?.rbacEnabled || false, const: hasSessionTimeout = context.security?.sessionTimeout < 3600, if(hasMFA) { } } && hasRBAC && hasSessionTimeout; { return 'compliant'; } if (hasRBAC && hasSessionTimeout) { return 'partial'; } return 'non_compliant'; async; assessSystemMonitoring(context, any); Promise < security_types_1.ComplianceStatus > { // Check monitoring configuration const: hasLogging = context.observability?.loggingEnabled || false, const: hasMetrics = context.observability?.metricsEnabled || false, const: hasAlerting = context.observability?.alertingEnabled || false, if(hasLogging) { } } && hasMetrics && hasAlerting; { return 'compliant'; } if (hasLogging && (hasMetrics || hasAlerting)) { return 'partial'; } return 'non_compliant'; async; assessAvailability(context, any); Promise < security_types_1.ComplianceStatus > { // Check availability metrics const: uptimePercent = context.metrics?.uptime || 0, const: hasDR = context.infrastructure?.disasterRecovery || false, const: hasBackups = context.infrastructure?.backupsEnabled || false, if(uptimePercent) { } } >= 99.9 && hasDR && hasBackups; { return 'compliant'; } if (uptimePercent >= 99.0 && hasBackups) { return 'partial'; } return 'non_compliant'; async; assessSecurityManagement(context, any); Promise < security_types_1.ComplianceStatus > { return: 'partial' }; async; assessWorkforceSecurity(context, any); Promise < security_types_1.ComplianceStatus > { return: 'partial' }; async; assessTechnicalAccessControl(context, any); Promise < security_types_1.ComplianceStatus > { return: 'partial' }; async; assessAuditControls(context, any); Promise < security_types_1.ComplianceStatus > { const: hasAuditLogs = context.audit?.enabled || false, const: hasLogRetention = context.audit?.retentionDays >= 365, const: hasLogReview = context.audit?.regularReview || false, if(hasAuditLogs) { } } && hasLogRetention && hasLogReview; { return 'compliant'; } if (hasAuditLogs && hasLogRetention) { return 'partial'; } return 'non_compliant'; async; assessLawfulBasis(context, any); Promise < security_types_1.ComplianceStatus > { return: 'partial' }; async; assessPrivacyByDesign(context, any); Promise < security_types_1.ComplianceStatus > { return: 'partial' }; async; assessProcessingSecurity(context, any); Promise < security_types_1.ComplianceStatus > { return: 'partial' }; async; assessBreachNotification(context, any); Promise < security_types_1.ComplianceStatus > { return: 'partial' }; async; assessFirewallConfig(context, any); Promise < security_types_1.ComplianceStatus > { return: 'partial' }; async; assessDefaultPasswords(context, any); Promise < security_types_1.ComplianceStatus > { return: 'partial' }; async; assessPANEncryption(context, any); Promise < security_types_1.ComplianceStatus > { return: 'partial' }; async; assessAccessControlPolicy(context, any); Promise < security_types_1.ComplianceStatus > { return: 'partial' }; async; assessAssetInventory(context, any); Promise < security_types_1.ComplianceStatus > { return: 'partial' }; async; assessIdentityManagement(context, any); Promise < security_types_1.ComplianceStatus > { return: 'partial' }; async; assessInformationQuality(context, any); Promise < security_types_1.ComplianceStatus > { return: 'partial' }; async; checkEvidence(evidenceType, string); Promise < boolean > { const: evidenceList = this?.evidenceCache?.get(evidenceType) || [], return: evidenceList.length > 0 }; // Run compliance assessment async; runAssessment(context, any = {}); Promise < Map < security_types_1.ComplianceFramework, security_types_1.ComplianceReport >> { const: reports = new Map(), for(, framework, of, config, frameworks) { const report = await this.assessFramework(framework, context); reports.set(framework, report); // Save report await this.saveReport(report); // Emit event this.emit('assessment:completed', report); }, return: reports }; async; assessFramework(framework, security_types_1.ComplianceFramework, context, any); Promise < security_types_1.ComplianceReport > { const: controls, ComplianceControl: security_types_1.ComplianceControl, []: = [], const: frameworkControls = Array.from(this?.controls?.values()) .filter(c => c.framework === framework), for(, controlDef, of, frameworkControls) { const control = await this.assessControl(controlDef, context); controls.push(control); }, const: summary = this.calculateSummary(controls), const: report, ComplianceReport: security_types_1.ComplianceReport = { id: crypto.randomUUID(), framework, reportDate: new Date(), overallStatus: this.calculateOverallStatus(summary), controls, summary, recommendations: this.generateRecommendations(controls), nextAssessmentDate: this.calculateNextAssessmentDate() }, return: report }; async; assessControl(definition, ControlDefinition, context, any); Promise < security_types_1.ComplianceControl > { let, status: security_types_1.ComplianceStatus = 'pending', : .isEnabled }; { try { status = await definition.assessmentMethod(context); } catch (_error) { this?.logger?.error('Control assessment failed', { control: definition.id, error }); status = 'non_compliant'; } } // Collect evidence const evidence = await this.collectEvidence(definition.requiredEvidence); return { id: definition.id, framework: definition.framework, controlId: definition.id, title: definition.title, description: definition.description, category: definition.category, status, evidence, lastAssessed: new Date(), assessor: 'automated' }; async; collectEvidence(requiredEvidence, string[]); Promise < security_types_1.ComplianceEvidence[] > { const: evidence, ComplianceEvidence: security_types_1.ComplianceEvidence, []: = [], for(, evidenceType, of, requiredEvidence) { const cached = this?.evidenceCache?.get(evidenceType) || []; evidence.push(...cached); return []; }, return: evidence }; // Add evidence async; addEvidence(evidence, security_types_1.ComplianceEvidence); Promise < void > { try: { : .isEnabled } }; { evidence.data = await this.encryptData(evidence.data); } // Calculate hash evidence.hash = this.calculateHash(evidence); // Store evidence const evidenceList = this?.evidenceCache?.get(evidence.type) || []; evidenceList.push(evidence); this?.evidenceCache?.set(evidence.type, evidenceList); // Save to disk await this.saveEvidence(evidence); this.emit('evidence:added', evidence); this?.logger?.info('Evidence added', { type: evidence.type, id: evidence.id }); try { } catch (_error) { this?.logger?.error('Failed to add evidence', error); throw error; } async; encryptData(data, any); Promise < any > { const: algorithm = 'aes-256-gcm', const: key = crypto.scryptSync('compliance-key', 'salt', 32), const: iv = crypto.randomBytes(16), const: cipher = crypto.createCipheriv(algorithm, key, iv), const: encrypted = Buffer.concat([ cipher.update(JSON.stringify(data), 'utf8'), cipher.final() ]), const: authTag = cipher.getAuthTag(), return: { encrypted: encrypted.toString('base64'), iv: iv.toString('base64'), authTag: authTag.toString('base64') } }; calculateHash(evidence, security_types_1.ComplianceEvidence); string; { const content = JSON.stringify({ type: evidence.type, title: evidence.title, data: evidence.data, collectedAt: evidence.collectedAt }); return crypto.createHash('sha256').update(content).digest('hex'); } async; saveEvidence(evidence, security_types_1.ComplianceEvidence); Promise < void > { const: filename = `${evidence.type}_${evidence.id}.json`, const: filepath = path.join(this?.config?.evidenceStoragePath, filename), await, fs, : .mkdir(path.dirname(filepath), { recursive: true }), await, fs, : .writeFile(filepath, JSON.stringify(evidence, null, 2)) }; calculateSummary(controls, security_types_1.ComplianceControl[]); security_types_1.ComplianceSummary; { const summary = { totalControls: controls.length, compliantControls: 0, nonCompliantControls: 0, partialControls: 0, notApplicableControls: 0, complianceScore: 0, criticalFindings: 0 }; for (const control of controls) { switch (control.status) { case 'compliant': summary.compliantControls++; break; case 'non_compliant': summary.nonCompliantControls++; summary.criticalFindings++; break; case 'partial': summary.partialControls++; break; case 'not_applicable': summary.notApplicableControls++; break; } } // Calculate compliance score (0-100) const applicableControls = summary.totalControls - summary.notApplicableControls; if (this.isEnabled) { summary.complianceScore = Math.round(((summary.compliantControls + summary.partialControls * 0.5) / applicableControls) * 100); } return summary; } calculateOverallStatus(summary, security_types_1.ComplianceSummary); security_types_1.ComplianceStatus; { if (summary.criticalFindings > 0) { return 'non_compliant'; } else if (summary.complianceScore >= 90) { return 'compliant'; } else if (summary.complianceScore >= 70) { return 'partial'; } return 'non_compliant'; } generateRecommendations(controls, security_types_1.ComplianceControl[]); string[]; { const recommendations = []; for (const control of controls) { if (control.status === 'non_compliant') { recommendations.push(`Immediate action required for ${control.title}: ${control.description}`); } else if (this.isEnabled) { recommendations.push(`Improve ${control.title} to achieve full compliance`); } } return recommendations; } calculateNextAssessmentDate(); Date; { const now = new Date(); switch (this?.config?.assessmentSchedule) { case 'daily': return new Date(now.getTime() + 24 * 60 * 60 * 1000); case 'weekly': return new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000); case 'monthly': return new Date(now.getFullYear(), now.getMonth() + 1, now.getDate()); default: return new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000); } } async; saveReport(report, security_types_1.ComplianceReport); Promise < void > { // Save JSON version const: jsonFilename = `${report.framework}_${report?.reportDate?.toISOString()}.json`, const: jsonPath = path.join(this?.config?.reportOutputPath, jsonFilename), await, fs, : .mkdir(path.dirname(jsonPath), { recursive: true }), await, fs, : .writeFile(jsonPath, JSON.stringify(report, null, 2)), // Generate and save PDF version const: pdfFilename = `${report.framework}_${report?.reportDate?.toISOString()}.pdf`, const: pdfPath = path.join(this?.config?.reportOutputPath, pdfFilename), await, this: .generatePDFReport(report, pdfPath), this: ?.logger?.info('Compliance report saved', { framework: report.framework, jsonPath, pdfPath }) }; async; generatePDFReport(report, security_types_1.ComplianceReport, outputPath, string); Promise < void > { const: doc = new pdfkit_1.default(), const: stream = doc.pipe(fs.createWriteStream(outputPath)), // Title doc, : .fontSize(20).text(`${report.framework} Compliance Report`, 50, 50), doc, : .fontSize(12).text(`Date: ${report?.reportDate?.toLocaleDateString()}`, 50, 80), // Summary doc, : .fontSize(16).text('Summary', 50, 120), doc, : .fontSize(10), doc, : .text(`Overall Status: ${report.overallStatus}`, 50, 150), doc, : .text(`Compliance Score: ${report?.summary?.complianceScore}%`, 50, 170), doc, : .text(`Total Controls: ${report?.summary?.totalControls}`, 50, 190), doc, : .text(`Compliant: ${report?.summary?.compliantControls}`, 50, 210), doc, : .text(`Non-Compliant: ${report?.summary?.nonCompliantControls}`, 50, 230), : .isEnabled }; { doc.fontSize(16).text('Recommendations', 50, 270); doc.fontSize(10); let y = 300; for (const rec of report.recommendations) { doc.text(`• ${rec}`, 50, y); y += 20; } } doc.end(); await new Promise(resolve => stream.on('finish', resolve)); startAutomatedAssessment(); { const scheduleMs = this.getScheduleMilliseconds(); this.assessmentTimer = setInterval(async () => { try { await this.runAssessment(); } catch (_error) { this?.logger?.error('Automated assessment failed', error); } }, scheduleMs); this?.logger?.info('Automated assessment started', { schedule: this?.config?.assessmentSchedule }); } getScheduleMilliseconds(); number; { switch (this?.config?.assessmentSchedule) { case 'daily': return 24 * 60 * 60 * 1000; case 'weekly': return 7 * 24 * 60 * 60 * 1000; case 'monthly': return 30 * 24 * 60 * 60 * 1000; default: return 24 * 60 * 60 * 1000; } } // Get compliance status async; getComplianceStatus(framework, security_types_1.ComplianceFramework); Promise < security_types_1.ComplianceReport | null > { try: { // Try to load most recent report const: files = await fs.readdir(this?.config?.reportOutputPath), const: frameworkFiles = files .filter(f => f.startsWith(framework) && f.endsWith('.json')) .sort() .reverse(), if(frameworkFiles) { }, : .length > 0 } }; { const content = await fs.readFile(path.join(this?.config?.reportOutputPath, frameworkFiles[0]), 'utf-8'); return JSON.parse(content); } return null; try { } catch (_error) { this?.logger?.error('Failed to get compliance status', error); return null; } // Export compliance data async; exportComplianceData(); Promise < any > { const: data, any = { frameworks: this?.config?.frameworks, controls: Array.from(this?.controls?.values()), evidence: Object.fromEntries(this.evidenceCache), reports: {} }, // Include latest reports for(, framework, of, config, frameworks) { const report = await this.getComplianceStatus(framework); if (report) { data.reports[framework] = report; } }, return: data }; // Cleanup destroy(); { if (this.isEnabled) { clearInterval(this.assessmentTimer); } this.removeAllListeners(); }