UNPKG

xypriss-security

Version:

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

722 lines 22.7 kB
/*************************************************************************** * 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. ***************************************************************************** */ import type { CachedData, CacheStats, CacheOptions, FileCacheOptions, FileCacheStats, FileCacheMetadata, FileCacheCleanupOptions, FileCacheStrategy } from "./types/cache.type"; import { UltraStats, UltraCacheOptions, UltraMemoryCacheEntry } from "./types/UFSIMC.type"; import { SecureInMemoryCache } from "./useCache"; import { UltraFastSecureInMemoryCache } from "./UFSIMC"; export { CONFIG as DEFAULT_CACHE_CONFIG, DEFAULT_FILE_CACHE_CONFIG, } from "./config/cache.config"; import { FileCache } from "./cacheSys"; import { SecureCacheClient } from "./SCC"; export declare const Cache: SecureInMemoryCache; /** * SecureInMemoryCache class for creating custom cache instances * * Advanced in-memory cache with military-grade encryption and intelligent * memory management. Ideal for high-performance applications requiring * secure temporary storage. * * @example * ```typescript * import { SecureInMemoryCache } from "xypriss-security"; * * const customCache = new SecureInMemoryCache({ * maxSize: 1000, * defaultTTL: 300000, // 5 minutes * encryptionKey: 'your-secret-key', * compressionThreshold: 1024 * }); * * await customCache.set('api:response', largeDataObject); * ``` * * @since 4.2.2 */ export { SecureInMemoryCache }; /** * UltraFastSecureInMemoryCache class for ultra-high performance caching * * Advanced ultra-fast cache with military-grade encryption, intelligent * memory management, and performance optimizations. Ideal for high-throughput * applications requiring maximum performance with security. * * @example * ```typescript * import { UltraFastSecureInMemoryCache } from "xypriss-security"; * * const ultraCache = new UltraFastSecureInMemoryCache(10000); * await ultraCache.set('high-freq-data', data, { priority: 10 }); * const stats = ultraCache.getUltraStats; * ``` * * @since 4.2.3 */ export { UltraFastSecureInMemoryCache }; /** * FileCache class for persistent storage * * Enterprise-grade file-based cache with real disk space monitoring, * atomic operations, and configurable storage strategies. * * @example * ```typescript * import { FileCache } from "xypriss-security"; * * const fileCache = new FileCache({ * directory: './app-cache', * encrypt: true, * compress: true, * namingStrategy: 'hierarchical', * maxCacheSize: 500 * 1024 * 1024 // 500MB * }); * * // Get real-time cache statistics including disk usage * const stats = await fileCache.getStats(); * console.log(`Disk usage: ${stats.diskUsage.percentage}%`); * ``` * * @since 4.2.0 */ export { FileCache }; /** * TypeScript type definitions for cache operations * * Complete type definitions for all cache interfaces, ensuring * type safety and excellent developer experience. * * @since 4.2.2 */ export type { CachedData, CacheStats, CacheOptions, FileCacheOptions, FileCacheStats, FileCacheMetadata, FileCacheCleanupOptions, FileCacheStrategy, UltraStats, UltraCacheOptions, UltraMemoryCacheEntry, }; /** * 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 */ export declare const generateFilePath: (key: string, options?: Partial<FileCacheOptions>) => string; export 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 "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 */ export 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 "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 */ export 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 "xypriss-security"; * * // Remove expired session * const removed = await removeFileCache('session:expired123'); * console.log(removed ? 'Session cleared' : 'Session not found'); * ``` * * @since 4.2.2 */ export 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 "xypriss-security"; * * if (await hasFileCache('config:app-settings')) { * const config = await readFileCache('config:app-settings'); * } else { * // Load from default configuration * } * ``` * * @since 4.2.2 */ export 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 "xypriss-security"; * * // Clear cache during maintenance * await clearFileCache(); * console.log('Cache cleared successfully'); * ``` * * @since 4.2.2 */ export 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 "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 */ export 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 "xypriss-security"; * * const result = await cleanupFileCache(); * console.log(`Cleaned ${result.cleaned} files, freed ${result.totalSize} bytes`); * ``` * * @since 4.2.2 */ export 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 "xypriss-security"; * * const sessionData = await readCache('session:user123'); * console.log('User ID:', sessionData.userId || 'Not found'); * ``` * * @since 4.2.2 */ export 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 "xypriss-security"; * * await writeCache('user:profile', userData, { ttl: 1800000 }); // 30 min * ``` * * @since 4.2.2 */ export 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 "xypriss-security"; * * const stats = getCacheStats(); * console.log(`Hit rate: ${stats.hitRate}%`); * console.log(`Memory usage: ${stats.memoryUsage} bytes`); * ``` * * @since 4.2.2 */ export 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 "xypriss-security"; * * await expireCache('session:expired123'); * console.log('Session removed from cache'); * ``` * * @since 4.2.2 */ export 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 "xypriss-security"; * * await clearAllCache(); * console.log('Memory cache cleared'); * ``` * * @since 4.2.2 */ export declare const clearAllCache: () => Promise<void>; /** * Legacy filepath function * @deprecated use generateFilePath instead */ export 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 "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 */ export declare const createOptimalCache: (options: { type: "memory" | "file" | "hybrid"; config?: Partial<FileCacheOptions>; }) => SecureInMemoryCache | FileCache | { memory: SecureInMemoryCache; 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 */ export declare const deleteFileCache: (key: string) => Promise<boolean>; /** * Cache module version and metadata * @since 4.2.0 */ export declare const CACHE_VERSION = "4.2.3"; export declare const CACHE_BUILD_DATE = "2025-04-06"; /** * Default export for convenience * @since 4.2.2 */ declare const _default: { Cache: SecureInMemoryCache; readonly FileCache: typeof FileCache; SecureInMemoryCache: typeof SecureInMemoryCache; createOptimalCache: (options: { type: "memory" | "file" | "hybrid"; config?: Partial<FileCacheOptions>; }) => SecureInMemoryCache | FileCache | { memory: SecureInMemoryCache; file: FileCache; get(key: string): Promise<CachedData | null>; set(key: string, value: CachedData, options?: any): Promise<boolean>; }; generateFilePath: (key: string, options?: Partial<FileCacheOptions>) => string; writeFileCache: (key: string, data: CachedData, options?: Partial<FileCacheOptions>) => Promise<boolean>; readFileCache: (key: string) => Promise<CachedData | null>; removeFileCache: (key: string) => Promise<boolean>; hasFileCache: (key: string) => Promise<boolean>; clearFileCache: () => Promise<void>; getFileCacheStats: () => Promise<FileCacheStats>; cleanupFileCache: (options?: Partial<FileCacheCleanupOptions>) => Promise<{ cleaned: number; errors: number; totalSize: number; }>; writeCache: (key: string, data: CachedData, options?: Partial<CacheOptions> | undefined) => Promise<boolean>; readCache: (key: string) => Promise<CachedData>; getCacheStats: () => CacheStats; expireCache: (key: string) => Promise<void>; clearAllCache: () => Promise<void>; defaultFileCache: FileCache; CACHE_VERSION: string; CACHE_BUILD_DATE: string; }; export default _default; /** * Redis configuration options */ export interface RedisConfig { /** 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 */ export interface MemoryConfig { /** 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 */ export interface SecurityConfig { /** 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 */ export interface MonitoringConfig { /** Enable performance metrics collection */ enabled: boolean; /** Metrics collection interval in milliseconds */ interval?: number; /** Enable health checks */ healthChecks?: boolean; } /** * Cache configuration options */ export interface CacheConfig { /** 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; /** Memory configuration (required for memory and hybrid strategies) */ memory?: MemoryConfig; /** Security configuration */ security?: SecurityConfig; /** Monitoring configuration */ monitoring?: MonitoringConfig; /** Enable compression */ compression?: boolean; } /** * Cache options for set operations */ export interface CacheSetOptions { /** Time to live in seconds */ ttl?: number; /** Array of tags for bulk invalidation */ tags?: string[]; } /** * Secure cache statistics interface */ export 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 */ export interface CacheHealth { status: "healthy" | "degraded" | "unhealthy"; details: { redis?: { connected: boolean; latency?: number; error?: string; }; memory?: { usage: number; available: number; }; errors?: string[]; lastCheck: Date; }; } /** * Fortified function interface for public API to avoid TypeScript issues with private members */ export interface IFortifiedFunction<T extends any[], R> { (...args: T): R; getStats(): any; getAnalyticsData(): any; getOptimizationSuggestions(): any[]; getPerformanceTrends(): any; detectAnomalies(): any[]; getDetailedMetrics(): any; clearCache(): void; getCacheStats(): { hits: number; misses: number; size: number; }; warmCache(args: T[]): Promise<void>; handleMemoryPressure(level: "low" | "medium" | "high"): void; optimizePerformance(): void; updateOptions(newOptions: any): void; getConfiguration(): any; } /** * Cache interface for public API to avoid TypeScript issues with private members */ export 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; memoize<TArgs extends any[], TResult>(keyGenerator: (...args: TArgs) => string, computeFunction: (...args: TArgs) => TResult | Promise<TResult>, options?: CacheSetOptions): (...args: TArgs) => Promise<TResult>; } /** * Short alias for SecureCacheClient for convenience * * @example * ```typescript * import { SCC } from "xypriss-security"; * * const cache = new SCC({ * strategy: "redis", * redis: { host: "localhost", port: 6379 } * }); * ``` */ export { SecureCacheClient as SCC }; //# sourceMappingURL=index.d.ts.map