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.

733 lines (729 loc) 22.9 kB
'use strict'; var path = require('path'); require('../../types.js'); var hashCore = require('../../core/hash/hash-core.js'); require('../../core/hash/hash-types.js'); require('crypto'); require('../../core/random/random-types.js'); require('../../core/random/random-sources.js'); require('nehonix-uri-processor'); require('../../utils/memory/index.js'); require('argon2'); require('../../algorithms/hash-algorithms.js'); require('child_process'); require('../../types/secure-memory.js'); require('https'); require('../runtime-verification.js'); require('../tamper-evident-logging.js'); require('../secure-string/advanced/entropy-analyzer.js'); require('../secure-string/advanced/quantum-safe.js'); require('../secure-string/advanced/performance-monitor.js'); require('nehoid'); require('../../core/password/index.js'); var useCache = require('./useCache.js'); var UFSIMC = require('./UFSIMC.js'); var cache_config = require('./config/cache.config.js'); var cacheSys = require('./cacheSys.js'); /*************************************************************************** * FortifyJS - Secure Array Types * * This file contains type definitions for the SecureArray modular architecture * * @author Nehonix * @license MIT * * Copyright (c) 2025 Nehonix. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ***************************************************************************** */ /** * @fileoverview FortifyJS Unified Cache System - Enterprise-Grade Caching Solution * * A comprehensive, caching solution combining multiple strategies * with military-grade security and ultra-fast performance optimization. * * ## Cache Strategies * - **Memory Cache**: Ultra-fast in-process storage with LRU eviction * - **File Cache**: Persistent cross-process storage with real disk monitoring * - **Hybrid Cache**: Automatic optimization between memory and file storage * - **Redis Cache**: Distributed scalable storage (via integrations) * * ## Security Features * - AES-256-GCM encryption for all cached data * - PBKDF2 key derivation with automatic key rotation * - Tamper-evident storage with integrity verification * - Secure key management and access pattern monitoring * - Memory-safe operations with automatic cleanup * * ## Performance Features * - Zlib compression for large values (configurable threshold) * - LRU eviction with intelligent memory pressure management * - Real-time disk space monitoring and automatic cleanup * - Atomic file operations for data consistency * - Sub-millisecond cache hits with object pooling * - Configurable TTL with background expiration cleanup * * ## Production Features * - Comprehensive error handling with graceful degradation * - Real-time performance metrics and health monitoring * - Configurable naming strategies (flat, hierarchical, dated, direct) * - Cross-platform compatibility (Windows, macOS, Linux) * - Zero-dependency core with optional integrations * - TypeScript support with complete type definitions * * @example * ```typescript * // Quick start with default memory cache * import { Cache } from "fortify2-js"; * * await Cache.set('user:123', { name: 'John', role: 'admin' }, { ttl: 3600000 }); * const user = await Cache.get('user:123'); * * // File-based persistent cache * import { FileCache } from "fortify2-js"; * * const fileCache = new FileCache({ * directory: './cache', * encrypt: true, * compress: true, * maxCacheSize: 1024 * 1024 * 100 // 100MB * }); * * await fileCache.set('session:abc', sessionData, { ttl: 86400000 }); * * // Hybrid cache for optimal performance * import { createOptimalCache } from "fortify2-js"; * * const hybridCache = createOptimalCache({ * type: 'hybrid', * config: { encrypt: true, compress: true } * }); * ``` * * @version 4.2.3 * @author FortifyJS Team * @since 2024-12-19 * @license MIT */ // ======================================== // MAIN CACHE EXPORTS // ======================================== /** * Default secure in-memory cache instance * * Pre-configured singleton instance with optimal security settings for immediate use. * Features AES-256-GCM encryption, LRU eviction, and automatic memory management. * * @example * ```typescript * import { Cache } from "fortify2-js"; * * // Store user session with 1-hour TTL * await Cache.set('session:user123', { * userId: 123, * permissions: ['read', 'write'], * loginTime: Date.now() * }, { ttl: 3600000 }); * * // Retrieve cached data * const session = await Cache.get('session:user123'); * * // Check cache statistics * const stats = Cache.getStats(); * console.log(`Hit rate: ${stats.hitRate}%`); * ``` * * @since 4.2.2 */ const Cache = new useCache.SecureInMemoryCache(); // ======================================== // FILE CACHE UTILITIES // ======================================== /** * Generate a secure file path for cache storage * * Creates secure, collision-resistant file paths using configurable naming strategies. * All keys are hashed using SHA-256 to prevent directory traversal attacks and * ensure consistent path generation across platforms. * * @param key - The cache key to generate a path for * @param options - Optional configuration for path generation * @returns Secure file path for the given key * * @example * ```typescript * import { generateFilePath } from "fortify2-js"; * * // Hierarchical structure (recommended for large caches) * const path1 = generateFilePath('user:123', { * namingStrategy: 'hierarchical', * directory: './cache' * }); * // Result: ./cache/a1/b2/a1b2c3d4...cache * * // Date-based organization (good for time-series data) * const path2 = generateFilePath('daily-report', { * namingStrategy: 'dated', * directory: './reports' * }); * // Result: ./reports/2024/12/19/hash...cache * * // Direct naming (human-readable, limited special chars) * const path3 = generateFilePath('config-settings', { * namingStrategy: 'direct', * directory: './config' * }); * // Result: ./config/config-settings.cache * ``` * * @since 4.2.2 */ const generateFilePath = (key, options = {}) => { const config = { ...cache_config.DEFAULT_FILE_CACHE_CONFIG, ...options }; const sanitized = hashCore.Hash.create(key, { outputFormat: "hex" }); let filePath; switch (config.namingStrategy) { case "hierarchical": const dir = sanitized.substring(0, 2); const subdir = sanitized.substring(2, 4); filePath = path.resolve(config.directory, dir, subdir, `${sanitized}${config.extension}`); break; case "dated": const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, "0"); const day = String(now.getDate()).padStart(2, "0"); filePath = path.resolve(config.directory, String(year), month, day, `${sanitized}${config.extension}`); break; case "direct": const safeKey = key.replace(/[^a-zA-Z0-9_-]/g, "_"); filePath = path.resolve(config.directory, `${safeKey}${config.extension}`); break; case "flat": default: filePath = path.resolve(config.directory, `${sanitized}${config.extension}`); break; } return filePath; }; // ======================================== // FILE CACHE EXPORTS // ======================================== /** * Default FileCache instance with lazy initialization * * Pre-configured file cache instance optimized for general use cases. * Features encryption, compression, and real disk space monitoring. * Uses lazy initialization to avoid circular dependency issues. * * @example * ```typescript * import { defaultFileCache } from "fortify2-js"; * * // Store large dataset with compression * await defaultFileCache.set('analytics:daily', bigDataSet, { * ttl: 86400000, // 24 hours * compress: true * }); * * // Check cache health * const info = await defaultFileCache.getCacheInfo(); * if (!info.health.healthy) { * console.warn('Cache issues:', info.health.issues); * } * ``` * * @since 4.2.0 */ let _defaultFileCache = null; const defaultFileCache = new Proxy({}, { get(target, prop) { if (!_defaultFileCache) { _defaultFileCache = new cacheSys.FileCache(); } const value = _defaultFileCache[prop]; return typeof value === "function" ? value.bind(_defaultFileCache) : value; }, }); /** * Write data to file cache with automatic optimization * * Stores data in the file cache with intelligent compression and encryption. * Automatically handles large objects and provides atomic write operations. * * @param key - Unique identifier for the cached data * @param data - Data to cache (any serializable type) * @param options - Optional cache configuration * @returns Promise resolving to true if successful * * @example * ```typescript * import { writeFileCache } from "fortify2-js"; * * // Cache user profile with encryption * const success = await writeFileCache('profile:user123', { * name: 'John Doe', * preferences: { theme: 'dark', lang: 'en' } * }, { * encrypt: true, * ttl: 3600000 // 1 hour * }); * ``` * * @since 4.2.2 */ const writeFileCache = async (key, data, options) => { return defaultFileCache.set(key, data, options); }; /** * Read data from file cache with automatic decryption * * Retrieves and automatically decrypts/decompresses cached data. * Returns null for expired or non-existent entries. * * @param key - Unique identifier for the cached data * @returns Promise resolving to cached data or null * * @example * ```typescript * import { readFileCache } from "fortify2-js"; * * const userData = await readFileCache('profile:user123'); * if (userData) { * console.log('Welcome back,', userData.name); * } else { * console.log('Cache miss - loading from database'); * } * ``` * * @since 4.2.2 */ const readFileCache = async (key) => { return defaultFileCache.get(key); }; /** * Remove specific entry from file cache * * Permanently deletes a cache entry and updates disk usage statistics. * Safe to call on non-existent keys. * * @param key - Unique identifier for the cached data * @returns Promise resolving to true if entry was deleted * * @example * ```typescript * import { removeFileCache } from "fortify2-js"; * * // Remove expired session * const removed = await removeFileCache('session:expired123'); * console.log(removed ? 'Session cleared' : 'Session not found'); * ``` * * @since 4.2.2 */ const removeFileCache = async (key) => { return defaultFileCache.delete(key); }; /** * Check if file cache entry exists and is valid * * Verifies cache entry existence without loading the data. * Automatically removes expired entries during check. * * @param key - Unique identifier for the cached data * @returns Promise resolving to true if entry exists and is valid * * @example * ```typescript * import { hasFileCache } from "fortify2-js"; * * if (await hasFileCache('config:app-settings')) { * const config = await readFileCache('config:app-settings'); * } else { * // Load from default configuration * } * ``` * * @since 4.2.2 */ const hasFileCache = async (key) => { return defaultFileCache.has(key); }; /** * Clear all file cache entries * * Removes all cached files and resets statistics. * Use with caution in production environments. * * @example * ```typescript * import { clearFileCache } from "fortify2-js"; * * // Clear cache during maintenance * await clearFileCache(); * console.log('Cache cleared successfully'); * ``` * * @since 4.2.2 */ const clearFileCache = async () => { return defaultFileCache.clear(); }; /** * Get comprehensive file cache statistics * * Returns real-time statistics including disk usage, hit rates, * and performance metrics with health assessment. * * @returns Promise resolving to detailed cache statistics * * @example * ```typescript * import { getFileCacheStats } from "fortify2-js"; * * const stats = await getFileCacheStats(); * console.log(`Cache efficiency: ${stats.hitRate}%`); * console.log(`Disk usage: ${stats.diskUsage.percentage}%`); * console.log(`Average response time: ${stats.avgResponseTime}ms`); * ``` * * @since 4.2.2 */ const getFileCacheStats = async () => { return defaultFileCache.getStats(); }; /** * Clean up expired file cache entries * * Removes expired entries and optimizes disk usage. * Automatically runs in background but can be triggered manually. * * @param options - Optional cleanup configuration * @returns Promise resolving to cleanup results * * @example * ```typescript * import { cleanupFileCache } from "fortify2-js"; * * const result = await cleanupFileCache(); * console.log(`Cleaned ${result.cleaned} files, freed ${result.totalSize} bytes`); * ``` * * @since 4.2.2 */ const cleanupFileCache = async (options) => { return defaultFileCache.cleanup(options); }; // ======================================== // MEMORY CACHE API // ======================================== /** * Read data from memory cache with fallback * * Retrieves data from the default memory cache instance. * Returns empty object if key is not found (legacy behavior). * * @param args - Arguments passed to Cache.get() * @returns Promise resolving to cached data or empty object * * @example * ```typescript * import { readCache } from "fortify2-js"; * * const sessionData = await readCache('session:user123'); * console.log('User ID:', sessionData.userId || 'Not found'); * ``` * * @since 4.2.2 */ const readCache = async (...args) => { const result = await Cache.get(...args); return result || {}; }; /** * Write data to memory cache * * Stores data in the default memory cache instance with encryption * and automatic compression for large values. * * @param args - Arguments passed to Cache.set() * @returns Promise resolving to true if successful * * @example * ```typescript * import { writeCache } from "fortify2-js"; * * await writeCache('user:profile', userData, { ttl: 1800000 }); // 30 min * ``` * * @since 4.2.2 */ const writeCache = async (...args) => { return Cache.set(...args); }; /** * Get memory cache performance statistics * * Returns comprehensive statistics including hit rates, memory usage, * and performance metrics for the default cache instance. * * @returns Current cache statistics * * @example * ```typescript * import { getCacheStats } from "fortify2-js"; * * const stats = getCacheStats(); * console.log(`Hit rate: ${stats.hitRate}%`); * console.log(`Memory usage: ${stats.memoryUsage} bytes`); * ``` * * @since 4.2.2 */ const getCacheStats = () => { return Cache.getStats; }; /** * Remove entry from memory cache * * Immediately removes a cache entry and frees associated memory. * Safe to call on non-existent keys. * * @param key - Cache key to remove * @returns Promise that resolves when deletion is complete * * @example * ```typescript * import { expireCache } from "fortify2-js"; * * await expireCache('session:expired123'); * console.log('Session removed from cache'); * ``` * * @since 4.2.2 */ const expireCache = (key) => { Cache.delete(key); return Promise.resolve(); }; /** * Clear all memory cache entries * * Removes all cached data and resets statistics. * Use with caution in production environments. * * @returns Promise that resolves when cache is cleared * * @example * ```typescript * import { clearAllCache } from "fortify2-js"; * * await clearAllCache(); * console.log('Memory cache cleared'); * ``` * * @since 4.2.2 */ const clearAllCache = () => { Cache.clear(); return Promise.resolve(); }; /** * Legacy filepath function * @deprecated use generateFilePath instead */ const filepath = (origin) => { return generateFilePath(origin, { namingStrategy: "hierarchical" }); }; // ======================================== // UTILITY FUNCTIONS // ======================================== /** * Create optimal cache instance based on performance requirements * * Factory function that creates the most suitable cache instance for your use case. * Automatically configures security settings and performance optimizations. * * @param options - Cache configuration options * @param options.type - Cache strategy: 'memory' (fastest), 'file' (persistent), 'hybrid' (balanced) * @param options.config - Optional file cache configuration (ignored for memory-only) * @returns Configured cache instance optimized for the specified requirements * * @example * ```typescript * import { createOptimalCache } from "fortify2-js"; * * // Ultra-fast memory cache for session data * const sessionCache = createOptimalCache({ type: 'memory' }); * * // Persistent file cache for application data * const appCache = createOptimalCache({ * type: 'file', * config: { * directory: './app-cache', * encrypt: true, * maxCacheSize: 100 * 1024 * 1024 // 100MB * } * }); * * // Hybrid cache for optimal performance and persistence * const hybridCache = createOptimalCache({ * type: 'hybrid', * config: { encrypt: true, compress: true } * }); * * // Use hybrid cache (memory-first with file backup) * await hybridCache.set('user:123', userData); * const user = await hybridCache.get('user:123'); // Served from memory * ``` * * @since 4.2.2 */ const createOptimalCache = (options) => { switch (options.type) { case "memory": return new useCache.SecureInMemoryCache(); case "file": return new cacheSys.FileCache(options.config); case "hybrid": // Return both memory cache and file cache in a wrapper return { memory: new useCache.SecureInMemoryCache(), file: new cacheSys.FileCache(options.config), async get(key) { // Try memory first, then file let result = await this.memory.get(key); if (!result) { result = await this.file.get(key); if (result) { // Cache in memory for faster access await this.memory.set(key, result); } } return result; }, async set(key, value, options) { // Set in both caches const memoryResult = await this.memory.set(key, value, options); const fileResult = await this.file.set(key, value, options); return memoryResult && fileResult; }, }; default: return new useCache.SecureInMemoryCache(); } }; // ======================================== // ADDITIONAL EXPORTS // ======================================== /** * Legacy file cache function names for backward compatibility * @deprecated Use the new function names for better clarity */ const deleteFileCache = removeFileCache; // ======================================== // GRACEFUL SHUTDOWN HANDLING // ======================================== /** * Graceful shutdown handler for cache system * * Automatically registered to handle SIGTERM and SIGINT signals. * Ensures all cache operations complete before process termination. * * @internal * @since 4.2.2 */ const handleGracefulShutdown = () => { console.log("Shutting down FortifyJS CS gracefully..."); try { Cache.shutdown(); } catch (error) { console.error("Error during cache shutdown:", error); } }; // Register shutdown handlers process.on("SIGTERM", handleGracefulShutdown); process.on("SIGINT", handleGracefulShutdown); // ======================================== // MODULE METADATA // ======================================== /** * Cache module version and metadata * @since 4.2.0 */ const CACHE_VERSION = "4.2.3"; const CACHE_BUILD_DATE = "2025-04-06"; /** * Default export for convenience * @since 4.2.2 */ var index = { Cache, get FileCache() { return cacheSys.FileCache; }, SecureInMemoryCache: useCache.SecureInMemoryCache, createOptimalCache, generateFilePath, writeFileCache, readFileCache, removeFileCache, hasFileCache, clearFileCache, getFileCacheStats, cleanupFileCache, writeCache, readCache, getCacheStats, expireCache, clearAllCache, defaultFileCache, CACHE_VERSION, CACHE_BUILD_DATE, }; exports.SecureInMemoryCache = useCache.SecureInMemoryCache; exports.UltraFastSecureInMemoryCache = UFSIMC.UltraFastSecureInMemoryCache; exports.DEFAULT_CACHE_CONFIG = cache_config.CONFIG; exports.DEFAULT_FILE_CACHE_CONFIG = cache_config.DEFAULT_FILE_CACHE_CONFIG; exports.FileCache = cacheSys.FileCache; exports.CACHE_BUILD_DATE = CACHE_BUILD_DATE; exports.CACHE_VERSION = CACHE_VERSION; exports.Cache = Cache; exports.cleanupFileCache = cleanupFileCache; exports.clearAllCache = clearAllCache; exports.clearFileCache = clearFileCache; exports.createOptimalCache = createOptimalCache; exports.default = index; exports.defaultFileCache = defaultFileCache; exports.deleteFileCache = deleteFileCache; exports.expireCache = expireCache; exports.filepath = filepath; exports.generateFilePath = generateFilePath; exports.getCacheStats = getCacheStats; exports.getFileCacheStats = getFileCacheStats; exports.hasFileCache = hasFileCache; exports.readCache = readCache; exports.readFileCache = readFileCache; exports.removeFileCache = removeFileCache; exports.writeCache = writeCache; exports.writeFileCache = writeFileCache; //# sourceMappingURL=index.js.map