UNPKG

anon-identity

Version:

Decentralized identity framework with DIDs, Verifiable Credentials, and privacy-preserving selective disclosure

389 lines 13.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ActivityMonitoringService = void 0; const activity_logger_1 = require("./activity-logger"); const websocket_server_1 = require("./websocket-server"); const activity_search_service_1 = require("./activity-search-service"); const activity_exporter_1 = require("./activity-exporter"); const activity_archival_service_1 = require("./activity-archival-service"); /** * Comprehensive activity monitoring service that integrates all components */ class ActivityMonitoringService { constructor(config = {}) { this.config = { enableIndexing: true, enableStreaming: true, enableIPFS: false, websocket: { enabled: false, port: 8080, path: '/activity-stream', maxConnections: 1000, ...config.websocket }, alerts: { enabled: true, errorRateThreshold: 0.1, // 10% volumeThreshold: 1000, // 1000 activities per hour enableEmail: false, enableWebhook: false, ...config.alerts }, ...config }; this.initializeServices(); } /** * Start the monitoring service */ async start(httpServer) { // Start WebSocket server if enabled if (this.config.websocket?.enabled && this.streamManager) { this.webSocketServer = new websocket_server_1.ActivityWebSocketServer(this.streamManager, httpServer, { port: this.config.websocket.port, path: this.config.websocket.path, maxConnections: this.config.websocket.maxConnections }); console.log(`Activity WebSocket server started on ${this.config.websocket.path}`); } console.log('Activity Monitoring Service started'); } /** * Stop the monitoring service */ async stop() { await this.logger.cleanup(); if (this.webSocketServer) { await this.webSocketServer.close(); } console.log('Activity Monitoring Service stopped'); } /** * Log an activity */ async logActivity(activity) { return this.logger.logActivity(activity); } /** * Search activities */ async searchActivities(query) { if (!this.searchService) { throw new Error('Search service not initialized - enable indexing'); } return this.searchService.searchActivities(query); } /** * Get activity summary */ async getActivitySummary(agentDID, period, startDate) { if (!this.searchService) { throw new Error('Search service not initialized - enable indexing'); } return this.searchService.getActivitySummary(agentDID, period, startDate); } /** * Get recent activities for an agent */ async getRecentActivities(agentDID, limit = 50) { if (!this.searchService) { throw new Error('Search service not initialized - enable indexing'); } return this.searchService.getRecentActivities(agentDID, limit); } /** * Subscribe to real-time activity stream */ subscribeToActivities(filters, callback, metadata) { if (!this.streamManager) { throw new Error('Stream manager not initialized - enable streaming'); } return this.streamManager.subscribe(filters, callback, metadata); } /** * Subscribe to agent activities */ subscribeToAgent(agentDID, callback, metadata) { if (!this.streamManager) { throw new Error('Stream manager not initialized - enable streaming'); } return this.streamManager.subscribeToAgent(agentDID, callback, metadata); } /** * Subscribe to critical events */ subscribeToCriticalEvents(callback, metadata) { if (!this.streamManager) { throw new Error('Stream manager not initialized - enable streaming'); } return this.streamManager.subscribeToCriticalEvents(callback, metadata); } /** * Get comprehensive monitoring statistics */ async getMonitoringStats() { const indexStats = this.logger.getActivityIndex()?.getStats(); const streamStats = this.streamManager?.getMetrics(); const wsStats = this.webSocketServer?.getStats(); // Calculate activities in last hour let lastHourActivities = 0; let totalActivities = 0; let errorCount = 0; if (indexStats) { totalActivities = indexStats.totalActivities; // Calculate error rate Object.entries(indexStats.byStatus).forEach(([status, count]) => { if (status === 'failed' || status === 'denied') { errorCount += count; } }); // Get recent activities for last hour calculation if (this.searchService) { const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000); const recentQuery = { dateRange: { start: oneHourAgo, end: new Date() } }; try { const recentResult = await this.searchService.searchActivities(recentQuery); lastHourActivities = recentResult.total; } catch { // Ignore errors in stats calculation } } } return { activities: { total: totalActivities, lastHour: lastHourActivities, errorRate: totalActivities > 0 ? errorCount / totalActivities : 0 }, agents: { active: indexStats?.agentCount || 0, totalSessions: 0 // Would need to track this separately }, streaming: { connections: wsStats?.connectedClients || 0, subscriptions: wsStats?.totalSubscriptions || 0, eventsPublished: streamStats?.totalEvents || 0 }, storage: { ipfsEnabled: !!this.logger.getIPFSStorage(), indexEnabled: !!this.logger.getActivityIndex(), totalIndexed: indexStats?.totalActivities || 0 } }; } /** * Get activity trends */ async getActivityTrends(agentDID, days = 7) { if (!this.searchService) { throw new Error('Search service not initialized - enable indexing'); } return this.searchService.getActivityTrends(agentDID, days); } /** * Compare multiple agents */ async compareAgents(agentDIDs, period = 'week') { if (!this.searchService) { throw new Error('Search service not initialized - enable indexing'); } return this.searchService.compareAgents(agentDIDs, period); } /** * Force flush all pending activities */ async flush() { await this.logger.flush(); } /** * Get the underlying logger instance */ getLogger() { return this.logger; } /** * Get the stream manager instance */ getStreamManager() { return this.streamManager; } /** * Get the WebSocket server instance */ getWebSocketServer() { return this.webSocketServer; } /** * Get the search service instance */ getSearchService() { return this.searchService; } /** * Export activities to various formats */ async exportActivities(query, options) { if (!this.exporter) { throw new Error('Exporter not initialized - enable indexing'); } return this.exporter.exportActivities(query, options); } /** * Generate compliance report */ async generateComplianceReport(agentDID, template, period) { if (!this.exporter) { throw new Error('Exporter not initialized - enable indexing'); } return this.exporter.generateComplianceReport(agentDID, template, period); } /** * Create audit proof for activities */ async createAuditProof(query, privateKey) { if (!this.exporter || !this.searchService) { throw new Error('Export services not initialized - enable indexing'); } const searchResult = await this.searchService.searchActivities(query); return this.exporter.createAuditProof(searchResult.activities, privateKey); } /** * Add archival policy */ addArchivalPolicy(policy) { if (!this.archivalService) { throw new Error('Archival service not initialized - enable indexing'); } this.archivalService.addPolicy(policy); } /** * Add archival rule */ addArchivalRule(rule) { if (!this.archivalService) { throw new Error('Archival service not initialized - enable indexing'); } this.archivalService.addRule(rule); } /** * Archive activities based on criteria */ async archiveActivities(query, policyId, options) { if (!this.archivalService) { throw new Error('Archival service not initialized - enable indexing'); } return this.archivalService.archiveActivities(query, policyId, options); } /** * Handle GDPR data deletion request */ async handleGDPRDataDeletion(parentDID) { if (!this.archivalService) { throw new Error('Archival service not initialized - enable indexing'); } return this.archivalService.handleGDPRDataDeletion(parentDID); } /** * Register GDPR compliance information */ registerGDPRCompliance(parentDID, info) { if (!this.archivalService) { throw new Error('Archival service not initialized - enable indexing'); } this.archivalService.registerGDPRCompliance(parentDID, info); } /** * Generate data retention report */ async generateRetentionReport() { if (!this.archivalService) { throw new Error('Archival service not initialized - enable indexing'); } return this.archivalService.generateRetentionReport(); } /** * Get the exporter instance */ getExporter() { return this.exporter; } /** * Get the archival service instance */ getArchivalService() { return this.archivalService; } // Private methods initializeServices() { // Initialize activity logger this.logger = new activity_logger_1.ActivityLogger(this.config); // Initialize stream manager if streaming is enabled if (this.config.enableStreaming) { this.streamManager = this.logger.getStreamManager(); } // Initialize search service if indexing is enabled if (this.config.enableIndexing) { const index = this.logger.getActivityIndex(); const ipfsStorage = this.logger.getIPFSStorage(); if (index) { this.searchService = new activity_search_service_1.ActivitySearchService(index, ipfsStorage); // Initialize exporter this.exporter = new activity_exporter_1.ActivityExporter(this.searchService); // Initialize archival service this.archivalService = new activity_archival_service_1.ActivityArchivalService(this.searchService, this.exporter, index, ipfsStorage, { defaultRetentionDays: 90, complianceMode: true, autoArchival: true }); } } // Setup alert monitoring if enabled if (this.config.alerts?.enabled && this.streamManager) { this.setupAlertMonitoring(); } } setupAlertMonitoring() { if (!this.streamManager) return; // Subscribe to alerts and handle them this.streamManager.subscribeToAlerts(async (event) => { const alert = event.data; console.log(`[ALERT] ${alert.severity.toUpperCase()}: ${alert.message}`); // Handle different alert types if (this.config.alerts?.enableWebhook && this.config.alerts?.webhookUrl) { await this.sendWebhookAlert(alert); } if (this.config.alerts?.enableEmail) { await this.sendEmailAlert(alert); } }, undefined, { source: 'monitoring-service' }); } async sendWebhookAlert(alert) { if (!this.config.alerts?.webhookUrl) return; try { // This would typically use fetch or axios in a real implementation console.log(`Webhook alert would be sent to: ${this.config.alerts.webhookUrl}`); console.log('Alert data:', JSON.stringify(alert, null, 2)); } catch (error) { console.error('Failed to send webhook alert:', error); } } async sendEmailAlert(alert) { try { // This would typically integrate with an email service console.log('Email alert would be sent'); console.log('Alert data:', JSON.stringify(alert, null, 2)); } catch (error) { console.error('Failed to send email alert:', error); } } } exports.ActivityMonitoringService = ActivityMonitoringService; //# sourceMappingURL=activity-monitoring-service.js.map