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.

1,751 lines (1,737 loc) 429 kB
import { Request, Response, NextFunction, RequestHandler, Express } from 'express'; export { NextFunction, Request, RequestHandler, Response, Router } from 'express'; import * as crypto from 'crypto'; import crypto__default from 'crypto'; import { EventEmitter } from 'events'; import { Server } from 'http'; type CachedData = Record<string, any>; interface MemoryCacheEntry { data: string; iv: string; authTag: string; timestamp: number; expiresAt: number; accessCount: number; lastAccessed: number; compressed: boolean; size: number; version: number; } interface CacheStats { hits: number; misses: number; evictions: number; totalSize: number; entryCount: number; hitRate: number; memoryUsage: { used: number; limit: number; percentage: number; }; totalAccesses: number; size: number; capacity: number; } interface CacheOptions { ttl?: number; compress?: boolean; encrypt?: boolean; } /** * Options for file-based cache operations */ interface FileCacheOptions extends CacheOptions { maxCacheSize: number; /** Directory to store cache files (default: .data/cache) */ directory?: string; /** File extension for cache files (default: .cache) */ extension?: string; /** Enable atomic writes (write to temp file then rename) */ atomic?: boolean; /** Enable file compression */ compress?: boolean; /** Custom file naming strategy */ namingStrategy?: "hash" | "direct" | "hierarchical" | "dated" | "flat"; /** Maximum file size in bytes (default: 10MB) */ maxFileSize?: number; /** Enable file metadata tracking */ trackMetadata?: boolean; } /** * File cache entry metadata */ interface FileCacheMetadata { /** Original cache key */ key: string; /** File creation timestamp */ createdAt: number; /** Last access timestamp */ lastAccessed: number; /** Expiration timestamp */ expiresAt: number; /** File size in bytes */ size: number; /** Number of times accessed */ accessCount: number; /** Whether data is compressed */ compressed: boolean; /** Whether data is encrypted */ encrypted: boolean; /** Data type information */ dataType: string; /** File version for migration support */ version: number; } /** * File cache statistics */ interface FileCacheStats { /** Total number of cache files */ fileCount: number; /** Total disk space used in bytes */ totalSize: number; /** Number of cache hits */ hits: number; /** Number of cache misses */ misses: number; /** Number of expired files cleaned up */ cleanups: number; /** Average file size in bytes */ averageFileSize: number; /** Cache hit rate percentage */ hitRate: number; /** Disk usage by directory */ diskUsage: { used: number; available: number; percentage: number; }; /** File age distribution */ ageDistribution: { fresh: number; recent: number; old: number; }; reads: number; writes: number; deletes: number; errors: number; totalFiles: number; avgResponseTime: number; lastCleanup: number; } /** * File cache cleanup options */ interface FileCacheCleanupOptions { /** Remove expired files */ removeExpired?: boolean; /** Remove files older than specified age in milliseconds */ maxAge?: number; /** Maximum number of files to keep (LRU cleanup) */ maxFiles?: number; /** Maximum total size in bytes (size-based cleanup) */ maxTotalSize?: number; /** Dry run mode (don't actually delete files) */ dryRun?: boolean; } /** * File cache directory structure */ type FileCacheStrategy = "flat" | "hierarchical" | "dated" | "custom"; /** * Enhanced cache configuration */ interface SecureCacheConfig { strategy?: "memory" | "redis" | "hybrid" | "distributed"; memory?: { maxSize?: number; maxEntries?: number; ttl?: number; algorithm?: "lru" | "lfu" | "fifo"; evictionPolicy?: "lru" | "lfu" | "fifo" | "ttl"; preallocation?: boolean; }; redis?: { host?: string; port?: number; password?: string; db?: number; cluster?: { enabled?: boolean; nodes?: Array<{ host: string; port: number; }>; options?: any; }; pool?: { min?: number; max?: number; acquireTimeoutMillis?: number; }; sentinel?: { enabled?: boolean; sentinels?: Array<{ host: string; port: number; }>; name?: string; }; }; performance?: { batchSize?: number; compressionThreshold?: number; hotDataThreshold?: number; prefetchEnabled?: boolean; asyncWrite?: boolean; pipeline?: boolean; connectionPooling?: boolean; }; security?: { encryption?: boolean; keyRotation?: boolean; accessMonitoring?: boolean; sanitization?: boolean; auditLogging?: boolean; }; monitoring?: { enabled?: boolean; metricsInterval?: number; alertThresholds?: { memoryUsage?: number; hitRate?: number; errorRate?: number; latency?: number; }; detailed?: boolean; }; resilience?: { retryAttempts?: number; retryDelay?: number; circuitBreaker?: boolean; fallback?: boolean; healthCheck?: boolean; }; } /** * Enhanced cache statistics */ interface EnhancedCacheStats { memory: CacheStats; redis?: { connected: boolean; commandsProcessed: number; operations: number; memoryUsage: { used: number; peak: number; percentage: number; }; keyspaceHits: number; keyspaceMisses: number; hits: number; misses: number; hitRate: number; connectedClients: number; connections: number; keys: number; uptime: number; lastUpdate: number; }; performance: { totalOperations: number; averageResponseTime: number; hotDataHitRate: number; compressionRatio: number; networkLatency: number; }; security: { encryptedEntries: number; keyRotations: number; suspiciousAccess: number; securityEvents: number; }; } /** * FortifyJS Secure Cache Adapter * Ultra-fast hybrid cache system combining security cache with Redis clustering * * Features: * - Memory-first hybrid architecture for maximum speed * - Redis Cluster support with automatic failover * - Connection pooling and health monitoring * - Advanced tagging and invalidation * - Real-time performance metrics * - Military-grade security from FortifyJS security cache */ /** * UF secure cache adapter */ declare class SecureCacheAdapter extends EventEmitter { private config; private memoryCache; private redisClient?; private connectionPool; private metadata; private stats; private healthMonitor?; private metricsCollector?; private masterEncryptionKey; private logger; constructor(config?: SecureCacheConfig); /** * Initialize statistics */ private initializeStats; /** * Initialize master encryption key for consistent encryption */ private initializeMasterKey; /** * Initialize memory cache with security features */ private initializeMemoryCache; /** * Connect to cache backends */ connect(): Promise<void>; /** * Initialize Redis with clustering and failover support */ private initializeRedis; /** * Setup Redis event handlers for monitoring and failover */ private setupRedisEventHandlers; /** * Start monitoring and health checks */ private startMonitoring; /** * Perform health check on all cache backends */ private performHealthCheck; /** * Collect performance metrics */ private collectMetrics; /** * Update performance metrics */ private updatePerformanceMetrics; /** * Generate cache key with namespace and security */ private generateKey; /** * Determine if data should be considered "hot" (frequently accessed) */ private isHotData; /** * Update access metadata for performance optimization */ private updateAccessMetadata; /** * Convert any data to CachedData format for SecurityCache compatibility */ private toCachedData; /** * Extract raw data from CachedData format */ private fromCachedData; /** * Serialize data for Redis storage with proper encryption */ private serializeForRedis; /** * Deserialize data from Redis storage with proper decryption */ private deserializeFromRedis; /** * Get value from cache with ultra-fast hybrid strategy */ get(key: string): Promise<any>; /** * Set value in cache with intelligent placement */ set(key: string, value: any, options?: { ttl?: number; tags?: string[]; }): Promise<boolean>; /** * Delete value from cache */ delete(key: string): Promise<boolean>; /** * Check if key exists in cache */ exists(key: string): Promise<boolean>; /** * Clear all cache entries */ clear(): Promise<void>; /** * Get value from Redis with encryption support */ private getFromRedis; /** * Set value in Redis with encryption and TTL support */ private setInRedis; /** * Set tags for cache invalidation */ private setTags; /** * Record response time for performance monitoring */ private recordResponseTime; /** * Invalidate cache entries by tags */ invalidateByTags(tags: string[]): Promise<number>; /** * Get multiple values at once (batch operation) */ mget(keys: string[]): Promise<Record<string, any>>; /** * Set multiple values at once (batch operation) */ mset(entries: Record<string, any> | Array<[string, any]>, options?: { ttl?: number; tags?: string[]; }): Promise<boolean>; /** * Get TTL for a specific key */ getTTL(key: string): Promise<number>; /** * Set expiration time for a key */ expire(key: string, ttl: number): Promise<boolean>; /** * Get all keys matching a pattern */ keys(pattern?: string): Promise<string[]>; /** * Extract original key from cache key */ private extractOriginalKey; /** * Get comprehensive cache statistics */ getStats(): Promise<EnhancedCacheStats>; /** * Update Redis statistics using Redis INFO command */ private updateRedisStats; /** * Calculate Redis memory usage percentage */ private calculateRedisMemoryPercentage; /** * Get cache health status */ getHealth(): { status: "healthy" | "degraded" | "unhealthy"; details: any; }; /** * Disconnect from all cache backends */ disconnect(): Promise<void>; } interface UltraMemoryCacheEntry extends MemoryCacheEntry { hotness: number; priority: number; tags: Set<string>; metadata: Record<string, any>; checksum: string; } interface UltraCacheOptions extends CacheOptions { priority?: number; tags?: string[]; metadata?: Record<string, any>; skipEncryption?: boolean; skipCompression?: boolean; onEvict?: (key: string, value: CachedData) => void; } interface UltraStats extends CacheStats { averageAccessTime: number; compressionRatio: number; encryptionOverhead: number; hotKeys: string[]; coldKeys: string[]; tagStats: Map<string, number>; } /** * Secure In-Memory Cache (SIMC) v2.0 * * Backward-compatible wrapper around UFSIMC that provides the same API as SIMC v1.0 * while delivering significantly performance and advanced features. */ /** * Secure In-Memory Cache (SIMC) v2.0 * * Now powered by Ultra-Fast Secure In-Memory Cache (UFSIMC) for significantly improved performance * while maintaining 100% backward compatibility with existing SIMC API. * * Performance improvements over SIMC v1.0: * - 10-50x faster cache operations through optimized algorithms * - Advanced hotness tracking and intelligent caching strategies * - Optimized memory management with object pooling * - Smart compression and encryption with minimal overhead * - Real-time performance monitoring and adaptive optimization * - Sub-millisecond cache hits with predictive prefetching * * Backward Compatibility: * All existing SIMC code will work without any changes while automatically benefiting * from UFSIMC's performance and advanced features. No API changes required. * * Migration Benefits: * - Existing applications get instant performance boost * - Same security guarantees with encryption * - Better memory efficiency and automatic cleanup * - Advanced monitoring and health diagnostics * - Zero code changes required for existing users */ declare class SIMC extends EventEmitter { private ultraCache; constructor(); /** * Setup event forwarding from UFSIMC to maintain compatibility */ private setupEventForwarding; /** * Convert SIMC options to UFSIMC-compatible format */ private convertToUFSIMCOptions; /** * Convert UFSIMC stats to SIMC-compatible format */ private convertToSIMCStats; /** * Validate and normalize cache key */ private validateKey; /** * Store data in cache with optional TTL and compression * * with UFSIMC's intelligent caching strategies while maintaining * the exact same API as SIMC v1.0 for seamless backward compatibility. * * @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 */ set(key: string, data: CachedData, options?: Partial<CacheOptions>): Promise<boolean>; /** * Retrieve data from cache * * with UFSIMC's predictive prefetching and hotness tracking * for significantly faster retrieval times. * * @param key - Unique identifier for the cached data * @returns Promise resolving to cached data or null */ get(key: string): Promise<CachedData | null>; /** * Delete entry from cache * * @param key - Cache key to remove * @returns True if entry was deleted, false otherwise */ delete(key: string): boolean; /** * Check if key exists in cache * * @param key - Cache key to check * @returns True if key exists and is not expired */ has(key: string): boolean; /** * Clear all cache entries */ clear(): void; /** * Get cache statistics in SIMC v1.0 compatible format * * with additional performance metrics from UFSIMC * while maintaining the same return structure for compatibility. * * @returns Cache statistics */ get getStats(): CacheStats; /** * Get cache size information * * @returns Object with entries count and total bytes */ get size(): { entries: number; bytes: number; }; /** * Clean up expired entries * * with UFSIMC's intelligent cleanup strategies. * Note: UFSIMC handles cleanup automatically, this method is for compatibility. * * @returns Number of entries cleaned up (estimated based on stats) */ cleanup(): number; /** * Shutdown cache and cleanup resources * * Properly shuts down UFSIMC and cleans up all resources. */ shutdown(): void; } interface SimpleLogger { warn(component: string, message: string, ...args: any[]): void; securityWarning(message: string, ...args: any[]): void; } /** * Ultra-Fast Secure In-Memory Cache (UFSIMC) * Extends SIMC with extreme performance optimizations and advanced features */ declare class UFSIMC extends EventEmitter { private lru; private keyHashMap; private tagIndex; private priorityQueues; private hotnessDecayTimer?; private stats; private encryptionKey; private keyRotationTimer?; private cleanupTimer?; private securityTimer?; private performanceTimer?; private encryptionPool; private accessTimes; private accessPatterns; private rateLimiter; private integrityCheck; private anomalyThreshold; private logger?; constructor(maxEntries?: number, logger?: SimpleLogger); /** * Warm up cipher pools for better performance */ private warmUpPools; /** * Start performance monitoring */ private startPerformanceMonitoring; /** * Enhanced encryption initialization with key derivation */ private initializeEncryption; /** * Ultra-fast key validation and hashing */ private validateAndHashKey; /** * High-performance compression with adaptive algorithms */ private smartCompress; /** * Smart decompression */ private smartDecompress; /** * High-performance encryption with pooling */ private fastEncrypt; /** * High-performance decryption */ private fastDecrypt; /** * Calculate data checksum for integrity */ private calculateChecksum; /** * Rate limiting check */ private checkRateLimit; /** * Ultra-fast SET operation with advanced features */ set(key: string, value: CachedData, options?: UltraCacheOptions): Promise<boolean>; /** * Ultra-fast GET operation with hotness tracking */ get(key: string): Promise<CachedData | null>; /** * Helper method for decryption and decompression */ private decryptAndDecompress; /** * Batch GET operation for multiple keys */ getMultiple(keys: string[]): Promise<Map<string, CachedData | null>>; /** * Set multiple key-value pairs */ setMultiple(entries: Array<{ key: string; value: CachedData; options?: UltraCacheOptions; }>): Promise<boolean[]>; /** * Delete by tag */ deleteByTag(tag: string): Promise<number>; /** * Get keys by tag */ getKeysByTag(tag: string): string[]; /** * Advanced cache statistics */ get getUltraStats(): UltraStats; /** * Export cache data for backup */ exportData(): Promise<any>; /** * Import cache data from backup */ importData(data: any): Promise<boolean>; /** * Performance and maintenance methods */ private updatePerformanceMetrics; private updateHotColdKeys; private optimizeHotness; private decayHotness; private recordAccessTime; private updateStatsAfterSet; private trackAccess; private cleanupIndexes; private findOriginalKey; private startMaintenanceTasks; private cleanup; private rotateEncryptionKey; private performSecurityChecks; private emergencyCleanup; private detectAnomalies; /** * Get cache health report */ getHealthReport(): { status: "healthy" | "warning" | "critical"; issues: string[]; recommendations: string[]; metrics: UltraStats; }; /** * Optimize cache configuration automatically */ autoOptimize(): void; /** * Prefetch data based on access patterns */ prefetch(predictor: (key: string, metadata: any) => Promise<CachedData | null>): Promise<number>; /** * Create a cache snapshot for debugging */ createSnapshot(): any; /** * Validate cache integrity */ validateIntegrity(): Promise<{ valid: number; invalid: number; errors: string[]; }>; /** * Enhanced delete with pattern matching */ delete(key: string): boolean; /** * Delete with pattern (supports wildcards) */ deletePattern(pattern: string): number; /** * Check if key exists */ has(key: string): boolean; /** * Clear all entries */ clear(): void; /** * Get cache size */ get size(): { entries: number; bytes: number; }; /** * Graceful shutdown */ shutdown(): Promise<void>; } declare const CONFIG: { CACHE_EXPIRY_MS: number; KEY_ROTATION_MS: number; ALGORITHM: "aes-256-gcm"; ENCODING: crypto.BinaryToTextEncoding; KEY_ITERATIONS: number; KEY_LENGTH: number; MAX_CACHE_SIZE_MB: number; MAX_ENTRIES: number; COMPRESSION_THRESHOLD_BYTES: number; CLEANUP_INTERVAL_MS: number; SECURITY_CHECK_INTERVAL_MS: number; MAX_KEY_LENGTH: number; MAX_VALUE_SIZE_MB: number; }; /** * Default configuration for file-based cache */ declare const DEFAULT_FILE_CACHE_CONFIG: Required<FileCacheOptions>; /** * Comprehensive File Cache System */ declare class FileCache { private config; private stats; constructor(options?: Partial<FileCacheOptions>); /** * Initialize cache statistics by scanning existing files */ private initializeStats; /** * Ensure base cache directory exists */ private ensureBaseDirectory; /** * Update cache statistics */ private updateStats; /** * Update disk usage statistics */ private updateDiskUsage; /** * Calculate directory size recursively */ private getDirectorySize; /** * Update age distribution statistics */ private updateAgeDistribution; /** * Write data to file cache */ set(key: string, value: CachedData, options?: Partial<FileCacheOptions>): Promise<boolean>; /** * Read data from file cache */ get(key: string, updatedContent?: boolean): Promise<CachedData | null>; /** * Delete cache entry */ delete(key: string): Promise<boolean>; /** * Check if key exists and is not expired */ has(key: string): Promise<boolean>; /** * Clear all cache files */ clear(): Promise<void>; /** * Recursively delete directory */ private deleteDirectory; /** * Cleanup expired entries */ cleanup(_options?: Partial<FileCacheCleanupOptions>): Promise<{ cleaned: number; errors: number; totalSize: number; }>; /** * Get all cache files recursively */ private getAllCacheFiles; /** * Get cache statistics with real-time updates */ getStats(): Promise<FileCacheStats>; /** * Get cache size information */ get size(): { files: number; bytes: number; }; /** * Get detailed cache information */ getCacheInfo(): Promise<{ config: Required<FileCacheOptions>; stats: FileCacheStats; health: { healthy: boolean; issues: string[]; recommendations: string[]; }; }>; } /*************************************************************************** * 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 NEHONIX * @since 2024-12-19 * @license MIT */ /** * 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 */ declare const Cache: SIMC; /** * 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 */ declare const generateFilePath: (key: string, options?: Partial<FileCacheOptions>) => string; declare const defaultFileCache: FileCache; /** * 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 */ declare const writeFileCache: (key: string, data: CachedData, options?: Partial<FileCacheOptions>) => Promise<boolean>; /** * 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 */ declare const readFileCache: (key: string) => Promise<CachedData | null>; /** * 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 */ declare const removeFileCache: (key: string) => Promise<boolean>; /** * 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 */ declare const hasFileCache: (key: string) => Promise<boolean>; /** * 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 */ declare const clearFileCache: () => Promise<void>; /** * 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 */ declare const getFileCacheStats: () => Promise<FileCacheStats>; /** * 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 */ declare const cleanupFileCache: (options?: Partial<FileCacheCleanupOptions>) => Promise<{ cleaned: number; errors: number; totalSize: number; }>; /** * 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 */ declare const readCache: (...args: Parameters<typeof Cache.get>) => Promise<CachedData>; /** * 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 */ declare const writeCache: (...args: Parameters<typeof Cache.set>) => Promise<boolean>; /** * 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 */ declare const getCacheStats: () => CacheStats; /** * 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 */ declare const expireCache: (key: string) => Promise<void>; /** * 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 */ declare const clearAllCache: () => Promise<void>; /** * Legacy filepath function * @deprecated use generateFilePath instead */ declare const filepath: (origin: string) => string; /** * 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 */ declare const createOptimalCache: (options: { type: "memory" | "file" | "hybrid"; config?: Partial<FileCacheOptions>; }) => SIMC | FileCache | { memory: SIMC; file: FileCache; get(key: string): Promise<CachedData | null>; set(key: string, value: CachedData, options?: any): Promise<boolean>; }; /** * Legacy file cache function names for backward compatibility * @deprecated Use the new function names for better clarity */ declare const deleteFileCache: (key: string) => Promise<boolean>; /** * Cache module version and metadata * @since 4.2.0 */ declare const CACHE_VERSION = "4.2.3"; declare const CACHE_BUILD_DATE = "2025-04-06"; /** * Redis configuration options */ interface RedisConfig$1 { /** Redis server hostname */ host: string; /** Redis server port */ port: number; /** Redis authentication password */ password?: string; /** Redis database number */ db?: number; /** Connection timeout in milliseconds */ connectTimeout?: number; /** Command timeout in milliseconds */ commandTimeout?: number; /** Redis Cluster configuration */ cluster?: { enabled: boolean; nodes: Array<{ host: string; port: number; }>; }; /** Redis Sentinel configuration */ sentinel?: { enabled: boolean; masters: string[]; sentinels: Array<{ host: string; port: number; }>; }; } /** * Memory cache configuration options */ interface MemoryConfig$1 { /** Maximum memory cache size in MB */ maxSize: number; /** Maximum number of cache entries */ maxEntries: number; /** LRU eviction policy settings */ evictionPolicy?: "lru" | "lfu" | "fifo"; } /** * Security configuration options */ interface SecurityConfig$1 { /** Enable AES-256-GCM encryption */ encryption: boolean; /** Enable automatic key rotation */ keyRotation?: boolean; /** Custom encryption key (base64 encoded) */ customKey?: string; } /** * Monitoring and health check configuration */ interface MonitoringConfig { /** Enable performance metrics collection */ enabled: boolean; /** Metrics collection interval in milliseconds */ interval?: number; /** Enable health checks */ healthChecks?: boolean; } /** * Cache configuration options */ interface CacheConfig$1 { /** Cache strategy: memory, redis, or hybrid */ strategy: "memory" | "redis" | "hybrid"; /** Default TTL in seconds */ ttl?: number; /** Redis configuration (required for redis and hybrid strategies) */ redis?: RedisConfig$1; /** Memory configuration (required for memory and hybrid strategies) */ memory?: MemoryConfig$1; /** Security configuration */ security?: SecurityConfig$1; /** Monitoring configuration */ monitoring?: MonitoringConfig; /** Enable compression */ compression?: boolean; } /** * Cache options for set operations */ interface CacheSetOptions { /** Time to live in seconds */ ttl?: number; /** Array of tags for bulk invalidation */ tags?: string[]; } /** * Secure cache statistics interface */ interface SecureCacheStats { memory: { hitRate: number; missRate: number; size: number; entries: number; maxSize: number; maxEntries: number; }; redis?: { hitRate: number; missRate: number; connected: boolean; memoryUsage: number; keyCount: number; }; operations: { total: number; gets: number; sets: number; deletes: number; errors: number; }; performance: { avgResponseTime: number; p95ResponseTime: number; p99ResponseTime: number; }; } /** * Cache health status interface */ interface CacheHealth { status: "healthy" | "degraded" | "unhealthy"; details: { redis?: { connected: boolean; latency?: number; error?: string; }; memory?: { usage: number; available: number; }; errors?: string[]; lastCheck: Date; }; } /** * Cache interface for public API to avoid TypeScript issues with private members */ interface ICacheAdapter { get<T = any>(key: string): Promise<T | null>; set<T = any>(key: string, value: T, options?: CacheSetOptions): Promise<boolean>; delete(key: string): Promise<boolean>; exists(key: string): Promise<boolean>; clear(): Promise<void>; connect(): Promise<void>; disconnect(): Promise<void>; getStats(): Promise<SecureCacheStats>; mget<T = any>(keys: string[]): Promise<Record<string, T>>; mset<T = any>(entries: Record<string, T> | Array<[string, T]>, options?: CacheSetOptions): Promise<boolean>; invalidateByTags(tags: string[]): Promise<number>; getTTL(key: string): Promise<number>; expire(key: string, ttl: number): Promise<boolean>; keys(pattern?: string): Promise<string[]>; getHealth(): CacheHealth; } /** * SecureCacheClient - Enterprise-grade secure caching solution * * A high-performance, secure cache client that supports multiple backend strategies * including memory-only, Redis-only, and hybrid (memory + Redis) configurations. * Features military-grade AES-256-GCM encryption, intelligent compression, and * comprehensive monitoring capabilities. * * ## Features * - **Multi-Strategy Support**: Memory, Redis, or Hybrid caching * - **Military-Grade Security**: AES-256-GCM encryption with key rotation * - **High Availability**: Redis Cluster and Sentinel support * - **Performance Optimized**: Intelligent compression and hot data promotion * - **Production Ready**: Comprehensive monitoring and health checks * - **Type Safe**: Full TypeScript support with detailed interfaces * * ## Supported Cache Strategies * - `memory`: Ultra-fast in-memory caching with LRU eviction * - `redis`: Distributed Redis caching with clustering support * - `hybrid`: Memory-first with Redis backup for optimal performance * * ## Security Features * - AES-256-GCM encryption for all cached data * - Automatic key rotation and tamper detection * - Secure serialization with integrity verification * - Access pattern monitoring and anomaly detection * * @example Basic Redis Configuration * ```typescript * import { SecureCacheClient } from "fortify2-js"; * * const cache = new SecureCacheClient({ * strategy: "redis", * redis: { * host: "localhost", * port: 6379, * password: "your-secure-password" * } * }); * * await cache.connect(); * await cache.set("user:123", { name: "John", role: "admin" }, { ttl: 3600 }); * const user = await cache.get("user:123"); * ``` * * @example Hybrid Strategy with Encryption * ```typescript * const cache = new SecureCacheClient({ * strategy: "hybrid", * memory: { * maxSize: 100, // 100MB * maxEntries: 10000 * }, * redis: { * host: "redis-cluster.example.com", * port: 6379, * cluster: { * enabled: true, * nodes: [ * { host: "redis-1", port: 6379 }, * { host: "redis-2", port: 6379 } * ] * } * }, * security: { * encryption: true, * keyRotation: true * } * }); * ``` * * @example Advanced Usage with Tags and Monitoring * ```typescript * // Store data with tags for bulk invalidation * await cache.set("product:123", productData, { * ttl: 1800, * tags: ["products", "category:electronics"] * }); * * // Batch operations for better performance * await cache.mset({ * "user:1": userData1, * "user:2": userData2 * }, { ttl: 3600 }); * * // Invalidate by tags * await cache.invalidateByTags(["products"]); * * // Monitor cache health * const health = cache.getHealth(); * if (health.status !== "healthy") { * console.warn("Cache issues:", health.details); * } * * // Get performance statistics * const stats = await cache.getStats(); * console.log(`Hit rate: ${stats.memory.hitRate * 100}%`); * ``` * * @since 4.2.3 * @version 4.2.3 * @author NEHONIX * @see {@link ICacheAdapter} for the complete interface definition * @see {@link https://lab.nehonix.space/nehonix_viewer/_doc/Nehonix%20FortifyJs} for detailed documentation */ declare class SecureCacheClient { private adapter; private config; /** * Creates a new SecureCacheClient instance * * @param config - Cache configuration object * @param config.strategy - Cache strategy: "memory", "redis", or "hybrid" * @param config.redis - Redis configuration (required for "redis" and "hybrid" strategies) * @param config.redis.host - Redis server hostname * @param config.redis.port - Redis server port * @param config.redis.password - Redis authentication password * @param config.redis.cluster - Redis cluster configuration * @param config.memory - Memory cache configuration (for "memory" and "hybrid" strategies) * @param config.memory.maxSize - Maximum memory cache size in MB * @param config.memory.maxEntries - Maximum number of cache entries * @param config.security - Security configuration * @param config.security.encryption - Enable AES-256-GCM encryption * @param config.security.keyRotation - Enable automatic key rotation * @param config.monitoring - Monitoring and health check configuration * * @example * ```typescript * const cache = new SecureCacheClient({ * strategy: "hybrid", * redis: { host: "localhost", port: 6379 }, * memory: { maxSize: 100, maxEntries: 10000 }, * security: { encryption: true } * }); * ``` */ constructor(config: CacheConfig$1); /** * Ensures the cache adapter is initialized * @private * @returns Promise resolving to the initialized adapter */ private ensureAdapter; /** * Retrieves a value from the cache * * @param key - The cache key to retrieve * @returns Promise resolving to the cached value, or null if not found * * @example * ```typescript * const user = await cache.read<User>("user:123"); * if (user) { * console.log("Found user:", user.name); * } * ``` */ read<T = any>(key: string): Promise<T | null>; /** * Stores a value in the cache with optional TTL and tags * * @param key - The cache key to store the value under * @param value - The value to cache (will be automatically serialized) * @param options - Optional caching options * @param options.ttl - Time to live in seconds (default: configured TTL) * @param options.tags - Array of tags for bulk invalidation * @returns Promise resolving to true if successful, false otherwise * * @example * ```typescript * // Basic usage * await cache.write("user:123", { name: "John", role: "admin" }); * * // With TTL (1 hour) * await cache.write("session:abc", sessionData, { ttl: 3600 }); * * // With tags for bulk invalidation * await cache.write("product:456", productData, { * ttl: 1800, * tags: ["products", "category:electronics"] * }); * ``` */ write<T = any>(key: string, value: T, options?: CacheSetOptions): Promise<boolean>; /** * Deletes a value from the cache * * @param key - The cache key to delete * @returns Promise resolving to true if the key was deleted, false if not found * * @example * ```typescript * const deleted = await cache.delete("user