UNPKG

xypriss-security

Version:

Advanced High-Performance Security Framework. Military-grade encryption, post-quantum resilience, and fortified data structures.

725 lines 24.7 kB
"use strict"; /*************************************************************************** * XyPrissSecurity - Secure Array Types * * This file contains type definitions for the SecureArray 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. ***************************************************************************** */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SCC = exports.CACHE_BUILD_DATE = exports.CACHE_VERSION = exports.deleteFileCache = exports.createOptimalCache = exports.filepath = exports.clearAllCache = exports.expireCache = exports.getCacheStats = exports.writeCache = exports.readCache = exports.cleanupFileCache = exports.getFileCacheStats = exports.clearFileCache = exports.hasFileCache = exports.removeFileCache = exports.readFileCache = exports.writeFileCache = exports.defaultFileCache = exports.generateFilePath = exports.FileCache = exports.UltraFastSecureInMemoryCache = exports.SecureInMemoryCache = exports.Cache = exports.DEFAULT_FILE_CACHE_CONFIG = exports.DEFAULT_CACHE_CONFIG = void 0; const path_1 = __importDefault(require("path")); // XyPrissSecurity Core imports const core_1 = require("../../core"); // Cache implementation const useCache_1 = require("./useCache"); Object.defineProperty(exports, "SecureInMemoryCache", { enumerable: true, get: function () { return useCache_1.SecureInMemoryCache; } }); const UFSIMC_1 = require("./UFSIMC"); Object.defineProperty(exports, "UltraFastSecureInMemoryCache", { enumerable: true, get: function () { return UFSIMC_1.UltraFastSecureInMemoryCache; } }); // Configuration const cache_config_1 = require("./config/cache.config"); var cache_config_2 = require("./config/cache.config"); Object.defineProperty(exports, "DEFAULT_CACHE_CONFIG", { enumerable: true, get: function () { return cache_config_2.CONFIG; } }); Object.defineProperty(exports, "DEFAULT_FILE_CACHE_CONFIG", { enumerable: true, get: function () { return cache_config_2.DEFAULT_FILE_CACHE_CONFIG; } }); const cacheSys_1 = require("./cacheSys"); Object.defineProperty(exports, "FileCache", { enumerable: true, get: function () { return cacheSys_1.FileCache; } }); const SCC_1 = require("./SCC"); Object.defineProperty(exports, "SCC", { enumerable: true, get: function () { return SCC_1.SecureCacheClient; } }); // Note: func (fortified-function) will be re-implemented separately // SecureCacheAdapter type will be imported dynamically when needed /** * @fileoverview XyPrissSecurity 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 "xypriss-security"; * * 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 "xypriss-security"; * * 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 "xypriss-security"; * * const hybridCache = createOptimalCache({ * type: 'hybrid', * config: { encrypt: true, compress: true } * }); * ``` * * @version 4.2.3 * @author NEHONIX * @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 "xypriss-security"; * * // 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 */ let _Cache = null; exports.Cache = new Proxy({}, { get(target, prop) { if (!_Cache) { _Cache = new useCache_1.SecureInMemoryCache(); } const value = _Cache[prop]; return typeof value === "function" ? value.bind(_Cache) : value; }, }); // ======================================== // 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 "xypriss-security"; * * // 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_1.DEFAULT_FILE_CACHE_CONFIG, ...options }; const sanitized = core_1.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_1.default.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_1.default.resolve(config.directory, String(year), month, day, `${sanitized}${config.extension}`); break; case "direct": const safeKey = key.replace(/[^a-zA-Z0-9_-]/g, "_"); filePath = path_1.default.resolve(config.directory, `${safeKey}${config.extension}`); break; case "flat": default: filePath = path_1.default.resolve(config.directory, `${sanitized}${config.extension}`); break; } return filePath; }; exports.generateFilePath = generateFilePath; // ======================================== // 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 "xypriss-security"; * * // 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; exports.defaultFileCache = new Proxy({}, { get(target, prop) { if (!_defaultFileCache) { _defaultFileCache = new cacheSys_1.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 "xypriss-security"; * * // 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 exports.defaultFileCache.set(key, data, options); }; exports.writeFileCache = writeFileCache; /** * 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 "xypriss-security"; * * 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 exports.defaultFileCache.get(key); }; exports.readFileCache = readFileCache; /** * 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 "xypriss-security"; * * // 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 exports.defaultFileCache.delete(key); }; exports.removeFileCache = removeFileCache; /** * 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 "xypriss-security"; * * 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 exports.defaultFileCache.has(key); }; exports.hasFileCache = hasFileCache; /** * Clear all file cache entries * * Removes all cached files and resets statistics. * Use with caution in production environments. * * @example * ```typescript * import { clearFileCache } from "xypriss-security"; * * // Clear cache during maintenance * await clearFileCache(); * console.log('Cache cleared successfully'); * ``` * * @since 4.2.2 */ const clearFileCache = async () => { return exports.defaultFileCache.clear(); }; exports.clearFileCache = clearFileCache; /** * 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 "xypriss-security"; * * 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 exports.defaultFileCache.getStats(); }; exports.getFileCacheStats = getFileCacheStats; /** * 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 "xypriss-security"; * * const result = await cleanupFileCache(); * console.log(`Cleaned ${result.cleaned} files, freed ${result.totalSize} bytes`); * ``` * * @since 4.2.2 */ const cleanupFileCache = async (options) => { return exports.defaultFileCache.cleanup(options); }; exports.cleanupFileCache = cleanupFileCache; // ======================================== // 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 "xypriss-security"; * * 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 exports.Cache.get(...args); return result || {}; }; exports.readCache = readCache; /** * 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 "xypriss-security"; * * await writeCache('user:profile', userData, { ttl: 1800000 }); // 30 min * ``` * * @since 4.2.2 */ const writeCache = async (...args) => { return exports.Cache.set(...args); }; exports.writeCache = writeCache; /** * 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 "xypriss-security"; * * const stats = getCacheStats(); * console.log(`Hit rate: ${stats.hitRate}%`); * console.log(`Memory usage: ${stats.memoryUsage} bytes`); * ``` * * @since 4.2.2 */ const getCacheStats = () => { return exports.Cache.getStats; }; exports.getCacheStats = getCacheStats; /** * 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 "xypriss-security"; * * await expireCache('session:expired123'); * console.log('Session removed from cache'); * ``` * * @since 4.2.2 */ const expireCache = (key) => { exports.Cache.delete(key); return Promise.resolve(); }; exports.expireCache = expireCache; /** * 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 "xypriss-security"; * * await clearAllCache(); * console.log('Memory cache cleared'); * ``` * * @since 4.2.2 */ const clearAllCache = () => { exports.Cache.clear(); return Promise.resolve(); }; exports.clearAllCache = clearAllCache; /** * Legacy filepath function * @deprecated use generateFilePath instead */ const filepath = (origin) => { return (0, exports.generateFilePath)(origin, { namingStrategy: "hierarchical" }); }; exports.filepath = filepath; // ======================================== // 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 "xypriss-security"; * * // 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_1.SecureInMemoryCache(); case "file": return new cacheSys_1.FileCache(options.config); case "hybrid": // Return both memory cache and file cache in a wrapper return { memory: new useCache_1.SecureInMemoryCache(), file: new cacheSys_1.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_1.SecureInMemoryCache(); } }; exports.createOptimalCache = createOptimalCache; // ======================================== // ADDITIONAL EXPORTS // ======================================== /** * Legacy file cache function names for backward compatibility * @deprecated Use the new function names for better clarity */ exports.deleteFileCache = exports.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 XyPrissSecurity CS gracefully..."); try { exports.Cache.shutdown(); } catch (error) { console.error("Error during cache shutdown:", error); } }; // Register shutdown handlers // TEMPORARILY DISABLED - Handled by XyPrissServer // process.on("SIGTERM", handleGracefulShutdown); // process.on("SIGINT", handleGracefulShutdown); // ======================================== // MODULE METADATA // ======================================== /** * Cache module version and metadata * @since 4.2.0 */ exports.CACHE_VERSION = "4.2.3"; exports.CACHE_BUILD_DATE = "2025-04-06"; /** * Default export for convenience * @since 4.2.2 */ exports.default = { Cache: exports.Cache, get FileCache() { return cacheSys_1.FileCache; }, SecureInMemoryCache: useCache_1.SecureInMemoryCache, createOptimalCache: exports.createOptimalCache, generateFilePath: exports.generateFilePath, writeFileCache: exports.writeFileCache, readFileCache: exports.readFileCache, removeFileCache: exports.removeFileCache, hasFileCache: exports.hasFileCache, clearFileCache: exports.clearFileCache, getFileCacheStats: exports.getFileCacheStats, cleanupFileCache: exports.cleanupFileCache, writeCache: exports.writeCache, readCache: exports.readCache, getCacheStats: exports.getCacheStats, expireCache: exports.expireCache, clearAllCache: exports.clearAllCache, defaultFileCache: exports.defaultFileCache, CACHE_VERSION: exports.CACHE_VERSION, CACHE_BUILD_DATE: exports.CACHE_BUILD_DATE, }; //# sourceMappingURL=index.js.map