UNPKG

xypriss-security

Version:

XyPriss Security is an advanced JavaScript security library designed for enterprise applications. It provides military-grade encryption, secure data structures, quantum-resistant cryptography, and comprehensive security utilities for modern web applicatio

519 lines (516 loc) 21.1 kB
import { EventEmitter } from 'events'; import { fortifiedLogger } from './fortified-logger.js'; import { fortifiedConfig } from './fortified-config.js'; import { NehoID } from 'nehoid'; import { SecurityManager } from './mods/security-manager.js'; import { CacheManager } from './mods/cache-manager.js'; import { StatsManager } from './mods/stats-manager.js'; import { MemoryManager } from './mods/memory-manager.js'; import { ExecutionEngine } from './mods/execution-engine.js'; import { ExecutionContextManager } from './mods/execution-context.js'; import { ExecutionRouter } from './mods/execution-router.js'; import { TimingManager } from './mods/timing-manager.js'; import { ApiManager } from './mods/api-manager.js'; import { SecurityHandler } from '../security/security-handler.js'; import { PerformanceMonitor } from '../performance/performance-monitor.js'; import { FuncExecutionEngine } from '../engines/execution-engine.js'; import { UltraFastEngine } from '../UFA/ultra-fast-engine.js'; import { UltraFastCache } from '../UFA/ultra-fast-cache.js'; import { UltraFastAllocator } from '../UFA/ultra-fast-allocator.js'; import '../serializer/safe-serializer.js'; import { FortifiedUtils } from '../utils/utils.js'; /** * XyPrissSecurity - Optimized Fortified Function Core (Minimal Architecture) * High-performance implementation with singleton pattern * Migrated from complex implementation to maintain architecture */ /** * Optimized Fortified Function - High-performance implementation * Uses singleton pattern for optimal resource utilization */ class FortifiedFunctionCore extends EventEmitter { constructor(fn, options = {}, functionId) { super(); this.isDestroyed = false; // Performance tracking this.executionCount = 0; this.lastOptimizationCheck = 0; this.optimizationCheckInterval = 100; // Check every 100 executions this.functionId = functionId || this.generateFunctionId(); this.originalFunction = fn; // Get optimized configuration from config manager this.options = fortifiedConfig.createFunctionConfig(this.functionId, options); fortifiedLogger.debug("CORE", `Creating optimized fortified function: ${this.functionId}`, { functionId: this.functionId, ultraFast: this.options.ultraFast, enableJIT: this.options.enableJIT, smartCaching: this.options.smartCaching, }); // Initialize performance components this.functionSignature = this.generateFunctionSignature(fn); this.ultraFastEngine = new UltraFastEngine(this.options); this.ultraFastCache = new UltraFastCache(this.options.maxCacheSize, this.options.maxMemoryUsage); this.ultraFastAllocator = new UltraFastAllocator(); // Initialize timing manager this.timingManager = new TimingManager(this.functionId); // Initialize existing components this.securityManager = new SecurityManager(this.options); this.statsManager = new StatsManager(this.options); this.memoryManager = new MemoryManager(this.options); this.executionContextManager = new ExecutionContextManager(this.options, this.securityManager); this.cacheManager = new CacheManager(this.options, this.securityManager); this.executionEngine = new ExecutionEngine(this.options, this.securityManager); // Initialize advanced components this.securityHandler = new SecurityHandler(); const cacheConfig = this.options.smartCaching ? { strategy: this.options.cacheStrategy, maxSize: this.options.maxCacheSize, ttl: this.options.cacheTTL, autoCleanup: this.options.autoCleanup, compressionEnabled: false, persistToDisk: false, } : undefined; this.performanceMonitor = new PerformanceMonitor(cacheConfig); this.funcExecutionEngine = new FuncExecutionEngine(this.securityHandler, this.performanceMonitor); // Initialize execution router after all dependencies are ready this.executionRouter = new ExecutionRouter(this.options, this.ultraFastEngine, this.ultraFastCache, this.performanceMonitor, this.functionSignature); // Initialize API manager this.apiManager = new ApiManager(this.functionId, this.statsManager, this.cacheManager, this.performanceMonitor, this.ultraFastCache, this.timingManager, this.options); // Configure ultra-fast mode if (this.options.ultraFast) { this.funcExecutionEngine.enableFastMode(this.options.ultraFast === "minimal" ? "minimal" : this.options.ultraFast === "maximum" ? "maximum" : "standard"); } // Setup event forwarding this.setupEventForwarding(); // Setup automatic cleanup if (this.options.autoCleanup) { this.setupAutoCleanup(); } // Update global metrics FortifiedFunctionCore.globalMetrics.totalInstances++; } generateFunctionId() { return NehoID.generate({ prefix: "nehonix.function", size: 16 }); } /** * Generate function signature for optimization */ generateFunctionSignature(fn) { const fnString = fn.toString(); let hash = 0; for (let i = 0; i < fnString.length; i++) { const char = fnString.charCodeAt(i); hash = (hash << 5) - hash + char; hash = hash & hash; } return `fn_${Math.abs(hash).toString(36)}`; } /** * Setup automatic cleanup */ setupAutoCleanup() { this.cleanupInterval = setInterval(() => { this.performanceMonitor.cleanupOldCacheEntries(300000); // 5 minutes // Smart cache warming if predictive analytics is enabled if (this.options.predictiveAnalytics) { this.warmCache(); } // Auto-apply optimization suggestions if auto-tuning is enabled if (this.options.autoTuning) { this.autoApplyOptimizations(); } }, 60000); // Check every minute } /** * Factory method with singleton pattern for optimal resource usage */ static create(fn, options = {}, functionId) { const id = functionId || FortifiedFunctionCore.generateFunctionId(fn); // Check if instance already exists if (FortifiedFunctionCore.instances.has(id)) { const existing = FortifiedFunctionCore.instances.get(id); fortifiedLogger.debug("CORE", `Reusing existing instance: ${id}`); return existing; } // Create new instance const instance = new FortifiedFunctionCore(fn, options, id); FortifiedFunctionCore.instances.set(id, instance); fortifiedLogger.debug("CORE", `Created new optimized instance: ${id}`, { totalInstances: FortifiedFunctionCore.globalMetrics.totalInstances, }); return instance; } /** * Get existing instance by ID */ static getInstance(functionId) { return (FortifiedFunctionCore.instances.get(functionId) || null); } /** * Get all active instances */ static getAllInstances() { return Array.from(FortifiedFunctionCore.instances.values()); } /** * Get global performance metrics */ static getGlobalMetrics() { return { ...FortifiedFunctionCore.globalMetrics }; } /** * Generate unique function ID */ static generateFunctionId(fn) { const fnString = fn.toString(); let hash = 0; for (let i = 0; i < fnString.length; i++) { const char = fnString.charCodeAt(i); hash = (hash << 5) - hash + char; hash = hash & hash; } /**`ff_${Math.abs(hash).toString(36)}_${Date.now().toString(36)}` */ return `ff_${Math.abs(hash).toString(36)}_${Date.now().toString(36)}`; } /** * Get function ID */ getFunctionId() { return this.functionId; } /** * Get current configuration */ getConfiguration() { return { ...this.options }; } /** * Execute with extreme performance optimizations */ async execute(...args) { if (this.isDestroyed) { throw new Error(`Cannot execute destroyed fortified function: ${this.functionId}.`); } this.executionCount++; this.apiManager.incrementExecutionCount(); const startTime = performance.now(); fortifiedLogger.debug("CORE", `Executing function: ${this.functionId}`, { functionId: this.functionId, executionCount: this.executionCount, args: this.options.debugMode ? args : "[hidden]", }); try { let result; // Route to appropriate execution path based on optimization level if (this.options.ultraFast === "maximum" || this.options.enableJIT) { result = await this.executeWithUltraFastEngine(...args); } else if (this.options.ultraFast === "minimal") { result = await this.executeUltraFast(...args); } else { result = await this.executeStandard(...args); } const executionTime = performance.now() - startTime; // Update global metrics FortifiedFunctionCore.globalMetrics.averageExecutionTime = (FortifiedFunctionCore.globalMetrics.averageExecutionTime * (FortifiedFunctionCore.globalMetrics.totalExecutions - 1) + executionTime) / FortifiedFunctionCore.globalMetrics.totalExecutions; // Periodic optimization check if (this.executionCount - this.lastOptimizationCheck >= this.optimizationCheckInterval) { this.performOptimizationCheck(); this.lastOptimizationCheck = this.executionCount; } fortifiedLogger.debug("CORE", `Execution completed: ${this.functionId}`, { functionId: this.functionId, executionTime, executionCount: this.executionCount, }); return result; } catch (error) { const executionTime = performance.now() - startTime; fortifiedLogger.error("CORE", `Execution failed: ${this.functionId}`, { functionId: this.functionId, executionTime, error: error instanceof Error ? error.message : String(error), }); throw error; } } /** * Execute with ultra-fast engine (delegated to ExecutionRouter) */ async executeWithUltraFastEngine(...args) { return await this.executionRouter.executeWithUltraFastEngine(this.originalFunction, args, this.options, this.functionId, FortifiedFunctionCore.globalMetrics); } /** * Ultra-fast execution (delegated to ExecutionRouter) */ async executeUltraFast(...args) { return await this.executionRouter.executeUltraFast(this.originalFunction, args, this.options, FortifiedFunctionCore.globalMetrics); } /** * Standard execution with full security and monitoring (using existing components) */ async executeStandard(...args) { // Use the existing execution path const executionId = FortifiedUtils.generateExecutionId(); const context = await this.executionContextManager.createSecureExecutionContext(executionId, args); try { // Check memoization cache using existing cache manager const cachedResult = await this.cacheManager.getCachedResult(args, executionId); if (cachedResult !== null) { this.statsManager.recordCacheHit(); FortifiedFunctionCore.globalMetrics.totalCacheHits++; return cachedResult; } this.statsManager.recordCacheMiss(); FortifiedFunctionCore.globalMetrics.totalCacheMisses++; // Execute with security and monitoring using existing execution engine const result = await this.executionEngine.executeWithSecurity(this.originalFunction, context, args); // Cache result if memoization is enabled await this.cacheManager.cacheResult(args, result, executionId); // Update statistics this.statsManager.updateStats(context, true); // Schedule cleanup this.executionContextManager.scheduleCleanup(context); return result; } catch (error) { this.statsManager.handleExecutionError(context, error); this.executionContextManager.scheduleCleanup(context); throw error; } } /** * Perform optimization check (delegated to ApiManager) */ performOptimizationCheck() { const stats = this.apiManager.getStats(); if (stats.executionCount >= 10 && this.options.autoTuning) { const optimized = this.apiManager.autoApplyOptimizations(); if (optimized) { this.emit("auto_optimization_applied", { type: "cache_size_increased", functionId: this.functionId, }); } } } // ===== PUBLIC API METHODS (Delegated to ApiManager) ===== getStats() { return this.apiManager.getStats(); } getAuditLog() { return this.apiManager.getAuditLog(); } getCacheStats() { return this.apiManager.getCacheStats(); } getAnalyticsData() { return this.apiManager.getAnalyticsData(); } getOptimizationSuggestions() { return this.apiManager.getOptimizationSuggestions(); } getPerformanceTrends() { return this.apiManager.getPerformanceTrends(); } detectAnomalies() { return this.apiManager.detectAnomalies(); } clearCache() { this.apiManager.clearCache(); this.emit("cache_cleared", { functionId: this.functionId }); } warmCache() { this.apiManager.warmCache(); this.emit("cache_warmed", { functionId: this.functionId }); } handleMemoryPressure(level) { this.apiManager.handleMemoryPressure(level); this.emit("memory_pressure_handled", { level, functionId: this.functionId, }); } /** * Set up event forwarding from components */ setupEventForwarding() { // Forward events from security manager this.securityManager.on("parameter_encrypted", (data) => this.emit("parameter_encrypted", data)); this.securityManager.on("encryption_error", (data) => this.emit("encryption_error", data)); // Forward events from cache manager this.cacheManager.on("cache_hit", (data) => this.emit("cache_hit", data)); this.cacheManager.on("cache_miss", (data) => this.emit("cache_miss", data)); this.cacheManager.on("cache_cleared", () => this.emit("cache_cleared")); // Forward events from stats manager this.statsManager.on("stats_updated", (data) => this.emit("stats_updated", data)); this.statsManager.on("execution_failed", (data) => this.emit("execution_failed", data)); // Forward events from execution context manager this.executionContextManager.on("context_created", (data) => this.emit("context_created", data)); this.executionContextManager.on("context_cleaned", (data) => this.emit("context_cleaned", data)); // Forward events from execution engine this.executionEngine.on("execution_success", (data) => this.emit("execution_success", data)); this.executionEngine.on("execution_error", (data) => this.emit("execution_error", data)); } /** * Auto-apply optimizations (delegated to ApiManager) */ autoApplyOptimizations() { const optimized = this.apiManager.autoApplyOptimizations(); if (optimized) { this.emit("auto_optimization_applied", { type: "cache_size_increased", functionId: this.functionId, }); } } /** * Get detailed metrics (delegated to components) */ getDetailedMetrics() { if (!this.options.detailedMetrics) return null; return { stats: this.getStats(), cacheStats: this.getCacheStats(), analytics: this.getAnalyticsData(), suggestions: this.getOptimizationSuggestions(), trends: this.getPerformanceTrends(), anomalies: this.detectAnomalies(), functionId: this.functionId, globalMetrics: FortifiedFunctionCore.getGlobalMetrics(), }; } /** * Update function options dynamically */ updateOptions(newOptions) { if (this.isDestroyed) { throw new Error(`Cannot update options on destroyed function: ${this.functionId}`); } Object.assign(this.options, newOptions); this.emit("options_updated", { functionId: this.functionId, newOptions, }); } /** * Performance timing methods (delegated to TimingManager) */ startTimer(label, metadata) { this.timingManager.startTimer(label, metadata); } endTimer(label, additionalMetadata) { return this.timingManager.endTimer(label, additionalMetadata); } measureDelay(startPoint, endPoint) { return this.timingManager.measureDelay(startPoint, endPoint); } async timeFunction(label, fn, metadata) { return await this.timingManager.timeFunction(label, fn, metadata); } getTimingStats() { return this.timingManager.getTimingStats(); } clearTimings() { this.timingManager.clearTimings(); } getMeasurementsByPattern(pattern) { return this.timingManager.getMeasurementsByPattern(pattern); } isTimerActive(label) { return this.timingManager.isTimerActive(label); } getActiveTimers() { return this.timingManager.getActiveTimers(); } // ===== ADDITIONAL API METHODS (Delegated to ApiManager) ===== clearAuditLog() { this.apiManager.clearAuditLog(); } getActiveExecutionsCount() { return this.apiManager.getActiveExecutionsCount(); } getUltraFastMetrics() { return this.apiManager.getUltraFastMetrics(); } optimizePerformance() { this.apiManager.optimizePerformance(); } /** * Enhanced destroy method with comprehensive cleanup */ destroy() { if (this.isDestroyed) return; fortifiedLogger.info("CORE", `Destroying optimized fortified function: ${this.functionId}`); // Clean up new modular components this.executionRouter.destroy(); this.timingManager.destroy(); this.apiManager.destroy(); // Clean up existing components this.executionContextManager.destroy(); this.cacheManager.destroy(); this.statsManager.destroy(); this.memoryManager.destroy(); this.executionEngine.destroy(); this.securityManager.destroy(); // Clean up advanced components this.performanceMonitor.destroy(); this.ultraFastEngine.destroy(); this.ultraFastCache.destroy(); this.ultraFastAllocator.destroy(); // Clear cleanup interval if (this.cleanupInterval) { clearInterval(this.cleanupInterval); } // Remove from global instances FortifiedFunctionCore.instances.delete(this.functionId); FortifiedFunctionCore.globalMetrics.totalInstances--; // Mark as destroyed this.isDestroyed = true; this.emit("destroyed", { functionId: this.functionId }); this.removeAllListeners(); fortifiedLogger.info("CORE", `Destroyed optimized fortified function: ${this.functionId}`); } /** * Destroy all instances (cleanup utility) */ static destroyAll() { const instances = Array.from(FortifiedFunctionCore.instances.values()); for (const instance of instances) { instance.destroy(); } fortifiedLogger.info("CORE", `Destroyed all ${instances.length} optimized fortified function instances`); } /** * Get instance count */ static get instancesSize() { return FortifiedFunctionCore.instances.size; } } FortifiedFunctionCore.instances = new Map(); FortifiedFunctionCore.globalMetrics = { totalInstances: 0, totalExecutions: 0, totalCacheHits: 0, totalCacheMisses: 0, averageExecutionTime: 0, }; export { FortifiedFunctionCore }; //# sourceMappingURL=fortified-function-core.js.map