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.

329 lines (325 loc) 11.7 kB
'use strict'; var constants = require('../../utils/constants.js'); var stats = require('../../utils/stats.js'); var randomTypes = require('./random-types.js'); var randomSources = require('./random-sources.js'); var randomEntropy = require('./random-entropy.js'); var randomGenerators = require('./random-generators.js'); var Uint8Array = require('../../helpers/Uint8Array.js'); var types = require('../../types.js'); /** * Random core - Main SecureRandom class with modular architecture */ /** * ## Core Cryptographic Exports * * Primary cryptographic classes and utilities for secure random generation, * key management, validation, and buffer operations. */ /** * ### Secure Random Generation * * High-entropy random number and data generation with multiple entropy sources. * Provides cryptographically secure random values for all security operations. * * @example * ```typescript * import { Random } from "fortify2-js"; * * // Generate secure random bytes * const randomBytes = Random.getRandomBytes(32); * * // Generate secure UUID * const uuid = Random.generateSecureUUID(); * * // Generate random integers * const randomInt = Random.getSecureRandomInt(1, 100); * ``` */ class SecureRandom { constructor() { this.stats = stats.StatsTracker.getInstance(); this.state = { entropyPool: Buffer.alloc(constants.SECURITY_CONSTANTS.ENTROPY_POOL_SIZE), lastReseed: Date.now(), state: randomTypes.RNGState.UNINITIALIZED, bytesGenerated: 0, entropyQuality: randomTypes.EntropyQuality.POOR, securityLevel: types.SecurityLevel.HIGH, quantumSafeMode: false, reseedCounter: 0, hardwareEntropyAvailable: this.detectHardwareEntropy(), sidechannelProtection: true, entropyAugmentation: true, realTimeMonitoring: true, lastEntropyTest: Date.now(), entropyTestResults: new Map(), securityAlerts: [], additionalEntropySources: new Map(), }; this.setupAdditionalEntropySources(); this.initializeEntropyPool(); } /** * Get singleton instance */ static getInstance() { if (!SecureRandom.instance) { SecureRandom.instance = new SecureRandom(); } return SecureRandom.instance; } /** * Initialize entropy pool */ async initializeEntropyPool() { this.state.state = randomTypes.RNGState.INITIALIZING; try { this.state.entropyPool = await randomEntropy.RandomEntropy.initializeEntropyPool(constants.SECURITY_CONSTANTS.ENTROPY_POOL_SIZE); this.state.entropyQuality = randomEntropy.RandomEntropy.assessEntropyQuality(this.state.entropyPool); this.state.state = randomTypes.RNGState.READY; this.state.lastReseed = Date.now(); } catch (error) { this.state.state = randomTypes.RNGState.ERROR; throw new Error(`Failed to initialize entropy pool: ${error}`); } } /** * Setup additional entropy sources */ setupAdditionalEntropySources() { // High-resolution timing entropy this.state.additionalEntropySources.set("timing", () => randomEntropy.RandomEntropy.getTimingEntropy()); // Memory usage entropy this.state.additionalEntropySources.set("memory", () => randomEntropy.RandomEntropy.getMemoryEntropy()); // Process entropy this.state.additionalEntropySources.set("process", () => randomEntropy.RandomEntropy.getProcessEntropy()); } /** * Detect hardware entropy availability */ detectHardwareEntropy() { try { // Check for hardware random number generator if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") { return true; } if (typeof window !== "undefined" && window.crypto && typeof window.crypto.getRandomValues === "function") { return true; } return false; } catch (error) { return false; } } // ============================================================================ // PUBLIC API - CORE RANDOM GENERATION // ============================================================================ /** * Generate ultra-secure random bytes with enhanced entropy * @param length - Number of bytes to generate * @param options - Generation options * @returns Enhanced random bytes */ static getRandomBytes(length, options = {}) { const instance = SecureRandom.getInstance(); // Check if we need to reseed const reseedThreshold = options.reseedThreshold || constants.SECURITY_CONSTANTS.RESEED_THRESHOLD; if (instance.state.bytesGenerated > reseedThreshold) { instance.reseedEntropyPool(); } // Generate bytes using the generators module const bytes = randomGenerators.RandomGenerators.getRandomBytes(length, options); // Update statistics instance.state.bytesGenerated += length; // instance.stats.recordRandomGeneration(length); // TODO: Implement this method // Return enhanced array return new Uint8Array.EnhancedUint8Array(bytes); } /** * Get system random bytes (fallback method) */ static getSystemRandomBytes(length) { return randomGenerators.RandomGenerators.getSystemRandomBytes(length); } /** * Generate secure random integer */ static getSecureRandomInt(min, max, options = {}) { return randomGenerators.RandomGenerators.getSecureRandomInt(min, max, options); } /** * Generate secure UUID v4 */ static generateSecureUUID(options = {}) { return randomGenerators.RandomGenerators.generateSecureUUID(options); } /** * Generate secure random float */ static getSecureRandomFloat(options = {}) { return randomGenerators.RandomGenerators.getSecureRandomFloat(options); } /** * Generate secure random boolean */ static getSecureRandomBoolean(options = {}) { return randomGenerators.RandomGenerators.getSecureRandomBoolean(options); } /** * Generate salt */ static generateSalt(length = 32, options = {}) { return randomGenerators.RandomGenerators.generateSalt(length, options); } // ============================================================================ // ENTROPY MANAGEMENT // ============================================================================ /** * Reseed entropy pool */ reseedEntropyPool() { this.state.state = randomTypes.RNGState.RESEEDING; try { randomEntropy.RandomEntropy.reseedEntropyPool(this.state.entropyPool).then((newPool) => { this.state.entropyPool = newPool; this.state.lastReseed = Date.now(); this.state.reseedCounter++; this.state.state = randomTypes.RNGState.READY; this.state.entropyQuality = randomEntropy.RandomEntropy.assessEntropyQuality(newPool); }); } catch (error) { this.state.state = randomTypes.RNGState.ERROR; console.error("Failed to reseed entropy pool:", error); } } /** * Get entropy analysis */ static getEntropyAnalysis(data) { const instance = SecureRandom.getInstance(); const analysisData = data || instance.state.entropyPool; return randomEntropy.RandomEntropy.analyzeEntropy(analysisData); } /** * Assess entropy quality */ static assessEntropyQuality(data) { return randomEntropy.RandomEntropy.assessEntropyQuality(data); } // ============================================================================ // MONITORING AND STATUS // ============================================================================ /** * Get security monitoring result */ static getSecurityStatus() { const instance = SecureRandom.getInstance(); const libraryStatus = randomSources.RandomSources.getLibraryStatus(); // Assess threats const threats = []; if (instance.state.entropyQuality === randomTypes.EntropyQuality.POOR) { threats.push("Low entropy quality detected"); } if (instance.state.bytesGenerated > constants.SECURITY_CONSTANTS.RESEED_THRESHOLD * 2) { threats.push("Entropy pool needs reseeding"); } if (!libraryStatus.sodium && !libraryStatus.secureRandom) { threats.push("No enhanced entropy sources available"); } // Generate recommendations const recommendations = []; if (threats.length > 0) { recommendations.push("Consider reseeding entropy pool"); } if (instance.state.entropyQuality !== randomTypes.EntropyQuality.MILITARY) { recommendations.push("Enable quantum-safe mode for maximum security"); } return { entropyQuality: instance.state.entropyQuality, securityLevel: instance.state.securityLevel, threats, recommendations, timestamp: Date.now(), bytesGenerated: instance.state.bytesGenerated, reseedCount: instance.state.reseedCounter, libraryStatus, }; } /** * Get library status */ static getLibraryStatus() { return randomSources.RandomSources.getLibraryStatus(); } /** * Check if secure random is available */ static isSecureRandomAvailable() { return ((typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") || (typeof window !== "undefined" && typeof window.crypto !== "undefined" && typeof window.crypto.getRandomValues === "function") || typeof require === "function"); } /** * Get current state */ getState() { return { ...this.state }; } /** * Get statistics */ static getStatistics() { const instance = SecureRandom.getInstance(); return { bytesGenerated: instance.state.bytesGenerated, reseedCount: instance.state.reseedCounter, lastReseed: instance.state.lastReseed, entropyQuality: instance.state.entropyQuality, state: instance.state.state, }; } // ============================================================================ // UTILITY METHODS // ============================================================================ /** * Reset instance (for testing) */ static resetInstance() { SecureRandom.instance = new SecureRandom(); } /** * Enable quantum-safe mode */ static enableQuantumSafeMode() { const instance = SecureRandom.getInstance(); instance.state.quantumSafeMode = true; } /** * Disable quantum-safe mode */ static disableQuantumSafeMode() { const instance = SecureRandom.getInstance(); instance.state.quantumSafeMode = false; } /** * Set security level */ static setSecurityLevel(level) { const instance = SecureRandom.getInstance(); instance.state.securityLevel = level; } } exports.SecureRandom = SecureRandom; //# sourceMappingURL=random-core.js.map