UNPKG

fortify2-js

Version:

MOST POWERFUL JavaScript Security Library! Military-grade cryptography + 19 enhanced object methods + quantum-resistant algorithms + perfect TypeScript support. More powerful than Lodash with built-in security.

421 lines (417 loc) 15.4 kB
'use strict'; var events = require('events'); var CacheFactory = require('../../integrations/express/cache/CacheFactory.js'); var nehoid = require('nehoid'); var index = require('../../security/secure-array/index.js'); var exec_const = require('./const/exec.const.js'); /** * FortifyJS - Ultra-Fast Optimized Execution Engine * Achieves execution with preserved security features */ class FuncExecutionEngine extends events.EventEmitter { constructor(securityHandler, performanceMonitor) { super(); this.activeExecutions = new Map(); this.cacheInitialized = false; // **ULTRA-FAST OPTIMIZATION: Hot path optimizations** this.executionCounter = 0; this.lastCleanup = 0; this.cleanupInterval = 10000; // 10s // **PERFORMANCE MODES** this.fastMode = true; this.securityLevel = "standard"; // **ULTRA-FAST OPTIMIZATION: Pre-allocated performance tracking** this.performanceStats = { totalExecutions: 0, cacheHits: 0, averageTime: 0, lastExecutionTime: 0, }; // **ULTRA-FAST OPTIMIZATION: Batch operations** this.pendingCleanups = []; this.securityHandler = securityHandler; this.performanceMonitor = performanceMonitor; // **ULTRA-FAST: Initialize everything synchronously** this.initializeFastCache(); this.preAllocateResources(); this.startOptimizationLoop(); } /** * **ULTRA-FAST OPTIMIZATION: Pre-allocate all resources** */ preAllocateResources() { // Pre-generate 500 execution IDs for zero-allocation const ID_POOL = index.createSecureArray([]); const b = nehoid.NehoID.batch({ count: 500, parallel: true, ensureUnique: true, format: "nano", }); ID_POOL.pushAll(b); // Pre-allocate 200 contexts for (let i = 0; i < 200; i++) { exec_const.CONTEXT_POOL.push(this.createFastContext()); } // Pre-allocate 100 buffer maps for (let i = 0; i < 100; i++) { exec_const.BUFFER_POOL.push(new Map()); } } /** * **ULTRA-FAST OPTIMIZATION: Start background optimization loop** */ startOptimizationLoop() { setInterval(() => { this.optimizeMemory(); this.processPendingCleanups(); }, 5000); } /** * **ULTRA-FAST OPTIMIZATION: Memory optimization** */ optimizeMemory() { const now = performance.now(); // Only run expensive cleanup every 10 seconds if (now - this.lastCleanup > this.cleanupInterval) { // Batch cleanup old executions const toDelete = []; for (const [id, context] of this.activeExecutions) { if (now - context.startTime > 30000) { // 30s old toDelete.push(id); } } toDelete.forEach((id) => { const context = this.activeExecutions.get(id); if (context) { this.returnContextToPool(context); this.activeExecutions.delete(id); } }); this.lastCleanup = now; } // Maintain pool sizes while (exec_const.CONTEXT_POOL.length < 50) { exec_const.CONTEXT_POOL.push(this.createFastContext()); } while (exec_const.ID_POOL.length < 100) { exec_const.ID_POOL.push(`exec_${Date.now()}_${Math.random()}`); } } /** * **ULTRA-FAST OPTIMIZATION: Process pending cleanups in batches** */ processPendingCleanups() { if (this.pendingCleanups.length === 0) return; const batch = this.pendingCleanups.splice(0, 10); // Process 10 at a time batch.forEach((id) => { const context = this.activeExecutions.get(id); if (context) { this.returnContextToPool(context); this.activeExecutions.delete(id); } }); } /** * **ULTRA-FAST OPTIMIZATION: Fast cache initialization (sync)** */ initializeFastCache() { // Initialize cache without async operations for maximum speed try { this.ultraFastCache = CacheFactory.createOptimalCache({ type: "memory", memory: { maxSize: 100, // 100MB algorithm: "lru", evictionPolicy: "lru", }, performance: { batchSize: 100, asyncWrite: false, // Sync for speed prefetchEnabled: false, // Disable for simplicity }, security: { encryption: false, // Disable for speed, re-enable if needed accessMonitoring: false, }, monitoring: { enabled: false, // Disable for maximum speed detailed: false, }, }); this.cacheInitialized = true; } catch (error) { console.warn("Fast cache init failed:", error); this.cacheInitialized = false; } } /** * **ULTRA-FAST OPTIMIZATION: Create minimal context** */ createFastContext() { return { executionId: "", encryptedParameters: new Map(), secureBuffers: new Map(), startTime: 0, memorySnapshot: 0, auditEntry: { timestamp: new Date(), executionId: "", parametersHash: "", executionTime: 0, memoryUsage: 0, success: false, securityFlags: [], }, }; } /** * **ULTRA-FAST OPTIMIZATION: Get context from pool (zero allocation)** */ getPooledContext() { let context = exec_const.CONTEXT_POOL.pop(); if (!context) { context = this.createFastContext(); } // Reset context with minimal operations context.executionId = exec_const.ID_POOL.pop() || `exec_${++this.executionCounter}`; context.startTime = performance.now(); context.memorySnapshot = 0; // Skip memory calculation for speed context.encryptedParameters.clear(); context.secureBuffers.clear(); context.auditEntry.executionId = context.executionId; context.auditEntry.success = false; context.auditEntry.securityFlags.length = 0; context.auditEntry.timestamp = new Date(); return context; } /** * **ULTRA-FAST OPTIMIZATION: Return context to pool** */ returnContextToPool(context) { if (exec_const.CONTEXT_POOL.length < 200) { // Clean sensitive data context.encryptedParameters.clear(); context.secureBuffers.clear(); // Return ID to pool if (exec_const.ID_POOL.length < 500) { exec_const.ID_POOL.push(context.executionId); } exec_const.CONTEXT_POOL.push(context); } } /** * **ULTRA-FAST: Lightning-fast execution (<4ms target)** */ async executeLightning(fn, args, options) { const startTime = performance.now(); // **ULTRA-FAST: Check execution cache first (most likely path)** if (options.memoize) { const cacheKey = this.generateFastCacheKey(args, fn.name); const cached = exec_const.EXECUTION_CACHE.get(cacheKey); if (cached !== undefined) { this.performanceStats.cacheHits++; this.performanceStats.lastExecutionTime = performance.now() - startTime; return cached; } } // **ULTRA-FAST: Skip context creation for minimal security** let result; if (this.securityLevel === "minimal") { // Direct execution - fastest path result = await fn(...args); } else { // Standard execution with minimal overhead const context = this.getPooledContext(); this.activeExecutions.set(context.executionId, context); try { // Execute with minimal security checks result = await this.executeWithMinimalSecurity(fn, args, context, options); context.auditEntry.success = true; } catch (error) { context.auditEntry.success = false; context.auditEntry.errorMessage = error.message; throw error; } finally { // Schedule cleanup (non-blocking) this.scheduleAsyncCleanup(context.executionId); } } // **ULTRA-FAST: Cache result if successful** if (options.memoize && result !== undefined) { const cacheKey = this.generateFastCacheKey(args, fn.name); exec_const.EXECUTION_CACHE.set(cacheKey, result); // Prevent cache from growing too large if (exec_const.EXECUTION_CACHE.size > 1000) { const firstKey = exec_const.EXECUTION_CACHE.keys().next().value; if (firstKey !== undefined) { exec_const.EXECUTION_CACHE.delete(firstKey); } } } // **ULTRA-FAST: Update performance stats** this.performanceStats.totalExecutions++; this.performanceStats.lastExecutionTime = performance.now() - startTime; this.performanceStats.averageTime = (this.performanceStats.averageTime * (this.performanceStats.totalExecutions - 1) + this.performanceStats.lastExecutionTime) / this.performanceStats.totalExecutions; return result; } /** * **ULTRA-FAST OPTIMIZATION: Minimal security execution** */ async executeWithMinimalSecurity(fn, args, context, options) { // **SECURITY PRESERVED: Parameter hashing (cached)** if (options.parameterValidation) { const argsStr = JSON.stringify(args); let hash = exec_const.HASH_CACHE.get(argsStr); if (!hash) { hash = await this.securityHandler.hashParameters(args); exec_const.HASH_CACHE.set(argsStr, hash); // Prevent hash cache from growing too large if (exec_const.HASH_CACHE.size > 500) { const firstKey = exec_const.HASH_CACHE.keys().next().value; if (firstKey !== undefined) { exec_const.HASH_CACHE.delete(firstKey); } } } context.auditEntry.parametersHash = hash; } // **SECURITY PRESERVED: Timeout protection** if (options.timeout > 0) { return await Promise.race([ fn(...args), new Promise((_, reject) => setTimeout(() => reject(new Error(`Timeout after ${options.timeout}ms`)), options.timeout)), ]); } // **ULTRA-FAST: Direct execution** return await fn(...args); } /** * **ULTRA-FAST OPTIMIZATION: Fast cache key generation** */ generateFastCacheKey(args, fnName) { // Use function name + simple arg stringification for maximum speed return `${fnName}_${JSON.stringify(args) .replace(exec_const.PARAM_HASH_REGEX, "") .substring(0, 50)}`; } /** * **ULTRA-FAST OPTIMIZATION: Non-blocking cleanup scheduling** */ scheduleAsyncCleanup(executionId) { this.pendingCleanups.push(executionId); // Process cleanups in next tick to avoid blocking if (!this.cleanupTimer) { this.cleanupTimer = setTimeout(() => { this.processPendingCleanups(); this.cleanupTimer = undefined; }, 0); } } /** * **COMPATIBILITY: Maintain existing interface** */ async createSecureExecutionContext(args, options) { const context = this.getPooledContext(); if (options.parameterValidation) { context.auditEntry.parametersHash = await this.securityHandler.hashParameters(args); } this.activeExecutions.set(context.executionId, context); this.emit("context_created", { executionId: context.executionId }); return context; } /** * **COMPATIBILITY: execution with performance optimizations** */ async executeWithSecurity(fn, _context, args, options) { // Route to lightning-fast execution for best performance return await this.executeLightning(fn, args, options); } /** * **PERFORMANCE MONITORING: Get comprehensive stats** */ getPerformanceStats() { return { ...this.performanceStats, cacheHitRate: this.performanceStats.cacheHits / this.performanceStats.totalExecutions, poolSizes: { contexts: exec_const.CONTEXT_POOL.length, ids: exec_const.ID_POOL.length, buffers: exec_const.BUFFER_POOL.length, hashCache: exec_const.HASH_CACHE.size, executionCache: exec_const.EXECUTION_CACHE.size, }, activeExecutions: this.activeExecutions.size, pendingCleanups: this.pendingCleanups.length, securityLevel: this.securityLevel, fastMode: this.fastMode, }; } /** * **SECURITY CONFIGURATION: Enable different security levels** */ setSecurityLevel(level) { this.securityLevel = level; console.log(`Security level set to: ${level}`); } /** * **CACHE MANAGEMENT: Clear all caches** */ clearAllCaches() { exec_const.EXECUTION_CACHE.clear(); exec_const.HASH_CACHE.clear(); exec_const.FUNCTION_CACHE.clear(); console.log("All caches cleared"); } /** * **COMPATIBILITY: Legacy methods** */ enableFastMode(level = "minimal") { this.fastMode = true; this.securityLevel = level; } handleExecutionComplete(context, success, error, _options) { // Update performance stats this.performanceMonitor.updateStats(context, success); if (!success && error) { context.auditEntry.errorMessage = error.message; } // Schedule non-blocking cleanup this.scheduleAsyncCleanup(context.executionId); } getActiveExecutionsCount() { return this.activeExecutions.size; } cleanupAllExecutions() { this.activeExecutions.forEach((_, id) => { this.scheduleAsyncCleanup(id); }); } async destroy() { // Clear all caches and pools this.clearAllCaches(); exec_const.CONTEXT_POOL.length = 0; exec_const.ID_POOL.length = 0; exec_const.BUFFER_POOL.length = 0; if (this.ultraFastCache) { await this.ultraFastCache.disconnect(); } } } exports.FuncExecutionEngine = FuncExecutionEngine; //# sourceMappingURL=execution-engine.js.map