@bantis/local-cipher 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"react.js","sources":["../src/types/index.ts","../src/core/EncryptionHelper.ts","../src/core/EventEmitter.ts","../src/utils/logger.ts","../src/core/KeyRotation.ts","../src/core/NamespacedStorage.ts","../src/utils/compression.ts","../src/core/SecureStorage.ts","../src/utils/debug.ts","../src/index.ts","../src/react/hooks.ts"],"sourcesContent":["/**\n * Configuration types for @bantis/local-cipher\n */\n\n/**\n * Encryption configuration options\n */\nexport interface EncryptionConfig {\n /** Number of PBKDF2 iterations (default: 100000) */\n iterations?: number;\n /** Salt length in bytes (default: 16) */\n saltLength?: number;\n /** IV length in bytes (default: 12) */\n ivLength?: number;\n /** Custom app identifier for fingerprinting (default: 'bantis-local-cipher-v2') */\n appIdentifier?: string;\n /** AES key length in bits (default: 256) */\n keyLength?: 128 | 192 | 256;\n}\n\n/**\n * Storage configuration options\n */\nexport interface StorageConfig {\n /** Enable data compression (default: true for values > 1KB) */\n compression?: boolean;\n /** Compression threshold in bytes (default: 1024) */\n compressionThreshold?: number;\n /** Enable automatic cleanup of expired items (default: true) */\n autoCleanup?: boolean;\n /** Auto cleanup interval in ms (default: 60000 - 1 minute) */\n cleanupInterval?: number;\n}\n\n/**\n * Debug configuration options\n */\nexport interface DebugConfig {\n /** Enable debug mode (default: false) */\n enabled?: boolean;\n /** Log level (default: 'info') */\n logLevel?: LogLevel;\n /** Custom log prefix (default: 'SecureStorage') */\n prefix?: string;\n}\n\n/**\n * Log levels\n */\nexport type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug' | 'verbose';\n\n/**\n * Complete configuration for SecureStorage\n */\nexport interface SecureStorageConfig {\n /** Encryption configuration */\n encryption?: EncryptionConfig;\n /** Storage configuration */\n storage?: StorageConfig;\n /** Debug configuration */\n debug?: DebugConfig;\n}\n\n/**\n * Stored value with metadata\n */\nexport interface StoredValue {\n /** Encrypted value */\n value: string;\n /** Expiration timestamp (ms since epoch) */\n expiresAt?: number;\n /** Creation timestamp (ms since epoch) */\n createdAt: number;\n /** Last modified timestamp (ms since epoch) */\n modifiedAt: number;\n /** Data version for migration */\n version: number;\n /** Whether value is compressed */\n compressed?: boolean;\n /** SHA-256 checksum for integrity */\n checksum?: string;\n}\n\n/**\n * Options for setItemWithExpiry\n */\nexport interface ExpiryOptions {\n /** Expiration time in milliseconds from now */\n expiresIn?: number;\n /** Absolute expiration date */\n expiresAt?: Date;\n}\n\n/**\n * Encrypted backup structure\n */\nexport interface EncryptedBackup {\n /** Backup version */\n version: string;\n /** Backup timestamp */\n timestamp: number;\n /** Encrypted data */\n data: Record<string, string>;\n /** Backup metadata */\n metadata: {\n /** Key version used for encryption */\n keyVersion: number;\n /** Encryption algorithm */\n algorithm: string;\n /** Number of items */\n itemCount: number;\n };\n}\n\n/**\n * Integrity information\n */\nexport interface IntegrityInfo {\n /** Whether data is valid */\n valid: boolean;\n /** Last modified timestamp */\n lastModified: number;\n /** SHA-256 checksum */\n checksum: string;\n /** Data version */\n version: number;\n}\n\n/**\n * Storage event types\n */\nexport type StorageEventType =\n | 'encrypted'\n | 'decrypted'\n | 'deleted'\n | 'cleared'\n | 'expired'\n | 'error'\n | 'keyRotated'\n | 'compressed'\n | 'decompressed';\n\n/**\n * Storage event data\n */\nexport interface StorageEventData {\n /** Event type */\n type: StorageEventType;\n /** Key involved (if applicable) */\n key?: string;\n /** Event timestamp */\n timestamp: number;\n /** Additional metadata */\n metadata?: any;\n /** Error (if type is 'error') */\n error?: Error;\n}\n\n/**\n * Event listener function\n */\nexport type EventListener = (data: StorageEventData) => void;\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONFIG: Required<SecureStorageConfig> = {\n encryption: {\n iterations: 100000,\n saltLength: 16,\n ivLength: 12,\n appIdentifier: 'bantis-local-cipher-v2',\n keyLength: 256,\n },\n storage: {\n compression: true,\n compressionThreshold: 1024,\n autoCleanup: true,\n cleanupInterval: 60000,\n },\n debug: {\n enabled: false,\n logLevel: 'info',\n prefix: 'SecureStorage',\n },\n};\n\n/**\n * Current library version\n */\nexport const LIBRARY_VERSION = '2.0.0';\n\n/**\n * Storage data version\n */\nexport const STORAGE_VERSION = 2;\n","import type { EncryptionConfig } from '../types';\nimport { DEFAULT_CONFIG } from '../types';\n\n/**\n * EncryptionHelper - Clase responsable de todas las operaciones criptográficas\n * Implementa AES-256-GCM con derivación de claves PBKDF2 y fingerprinting del navegador\n */\nexport class EncryptionHelper {\n // Constantes criptográficas (ahora configurables)\n private static readonly ALGORITHM = 'AES-GCM';\n private static readonly HASH_ALGORITHM = 'SHA-256';\n private static readonly SALT_STORAGE_KEY = '__app_salt';\n private static readonly KEY_VERSION_KEY = '__key_version';\n\n // Configuración\n private readonly config: Required<EncryptionConfig>;\n\n // Propiedades privadas\n private key: CryptoKey | null = null;\n private baseKey: string = '';\n private baseKeyPromise: Promise<string> | null = null;\n private keyVersion: number = 1;\n\n constructor(config?: EncryptionConfig) {\n this.config = { ...DEFAULT_CONFIG.encryption, ...config } as Required<EncryptionConfig>;\n\n // Load key version from storage\n const storedVersion = localStorage.getItem(EncryptionHelper.KEY_VERSION_KEY);\n if (storedVersion) {\n this.keyVersion = parseInt(storedVersion, 10);\n }\n }\n\n /**\n * Get current key version\n */\n public getKeyVersion(): number {\n return this.keyVersion;\n }\n\n /**\n * Genera un fingerprint único del navegador\n * Combina múltiples características del navegador para crear una huella digital\n */\n private async generateBaseKey(): Promise<string> {\n if (this.baseKeyPromise) {\n return this.baseKeyPromise;\n }\n\n this.baseKeyPromise = (async () => {\n const components = [\n navigator.userAgent,\n navigator.language,\n screen.width.toString(),\n screen.height.toString(),\n screen.colorDepth.toString(),\n new Intl.DateTimeFormat().resolvedOptions().timeZone,\n this.config.appIdentifier,\n ];\n\n const fingerprint = components.join('|');\n this.baseKey = await this.hashString(fingerprint);\n return this.baseKey;\n })();\n\n return this.baseKeyPromise;\n }\n\n /**\n * Hashea un string usando SHA-256\n * @param str - String a hashear\n * @returns Hash hexadecimal\n */\n private async hashString(str: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(str);\n const hashBuffer = await crypto.subtle.digest(EncryptionHelper.HASH_ALGORITHM, data);\n return this.arrayBufferToHex(hashBuffer);\n }\n\n /**\n * Deriva una clave criptográfica usando PBKDF2\n * @param password - Password base (fingerprint)\n * @param salt - Salt aleatorio\n * @returns CryptoKey para AES-GCM\n */\n private async deriveKey(password: string, salt: Uint8Array): Promise<CryptoKey> {\n const encoder = new TextEncoder();\n const passwordBuffer = encoder.encode(password);\n\n // Importar el password como material de clave\n const keyMaterial = await crypto.subtle.importKey(\n 'raw',\n passwordBuffer,\n 'PBKDF2',\n false,\n ['deriveBits', 'deriveKey']\n );\n\n // Derivar la clave AES-GCM\n return crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt,\n iterations: this.config.iterations,\n hash: EncryptionHelper.HASH_ALGORITHM,\n },\n keyMaterial,\n {\n name: EncryptionHelper.ALGORITHM,\n length: this.config.keyLength,\n },\n false,\n ['encrypt', 'decrypt']\n );\n }\n\n /**\n * Inicializa el sistema de encriptación generando un nuevo salt\n */\n public async initialize(): Promise<void> {\n // Generar salt aleatorio\n const salt = crypto.getRandomValues(new Uint8Array(this.config.saltLength));\n\n // Obtener y hashear el baseKey\n const baseKey = await this.generateBaseKey();\n\n // Derivar la clave\n this.key = await this.deriveKey(baseKey, salt);\n\n // Increment key version\n this.keyVersion++;\n localStorage.setItem(EncryptionHelper.KEY_VERSION_KEY, this.keyVersion.toString());\n\n // Guardar el salt en localStorage\n localStorage.setItem(\n EncryptionHelper.SALT_STORAGE_KEY,\n this.arrayBufferToBase64(salt.buffer)\n );\n }\n\n /**\n * Inicializa desde un salt almacenado previamente\n */\n public async initializeFromStored(): Promise<void> {\n const storedSalt = localStorage.getItem(EncryptionHelper.SALT_STORAGE_KEY);\n\n if (!storedSalt) {\n // Si no hay salt almacenado, inicializar uno nuevo\n await this.initialize();\n return;\n }\n\n // Recuperar el salt\n const salt = new Uint8Array(this.base64ToArrayBuffer(storedSalt));\n\n // Obtener el baseKey\n const baseKey = await this.generateBaseKey();\n\n // Derivar la misma clave\n this.key = await this.deriveKey(baseKey, salt);\n }\n\n /**\n * Encripta un texto plano usando AES-256-GCM\n * @param plaintext - Texto a encriptar\n * @returns Texto encriptado en Base64 (IV + datos encriptados)\n */\n public async encrypt(plaintext: string): Promise<string> {\n if (!this.key) {\n await this.initializeFromStored();\n }\n\n if (!this.key) {\n throw new Error('No se pudo inicializar la clave de encriptación');\n }\n\n // Convertir texto a bytes\n const encoder = new TextEncoder();\n const data = encoder.encode(plaintext);\n\n // Generar IV aleatorio\n const iv = crypto.getRandomValues(new Uint8Array(this.config.ivLength));\n\n // Encriptar\n const encryptedBuffer = await crypto.subtle.encrypt(\n {\n name: EncryptionHelper.ALGORITHM,\n iv,\n },\n this.key,\n data\n );\n\n // Combinar IV + datos encriptados\n const combined = new Uint8Array(iv.length + encryptedBuffer.byteLength);\n combined.set(iv, 0);\n combined.set(new Uint8Array(encryptedBuffer), iv.length);\n\n // Retornar en Base64\n return this.arrayBufferToBase64(combined.buffer);\n }\n\n /**\n * Desencripta un texto encriptado\n * @param ciphertext - Texto encriptado en Base64\n * @returns Texto plano\n */\n public async decrypt(ciphertext: string): Promise<string> {\n if (!this.key) {\n await this.initializeFromStored();\n }\n\n if (!this.key) {\n throw new Error('No se pudo inicializar la clave de encriptación');\n }\n\n try {\n // Decodificar de Base64\n const combined = new Uint8Array(this.base64ToArrayBuffer(ciphertext));\n\n // Extraer IV y datos encriptados\n const iv = combined.slice(0, this.config.ivLength);\n const encryptedData = combined.slice(this.config.ivLength);\n\n // Desencriptar\n const decryptedBuffer = await crypto.subtle.decrypt(\n {\n name: EncryptionHelper.ALGORITHM,\n iv,\n },\n this.key,\n encryptedData\n );\n\n // Convertir bytes a texto\n const decoder = new TextDecoder();\n return decoder.decode(decryptedBuffer);\n } catch (error) {\n throw new Error(`Error al desencriptar: ${error instanceof Error ? error.message : 'Error desconocido'}`);\n }\n }\n\n /**\n * Encripta el nombre de una clave para ofuscar nombres en localStorage\n * @param keyName - Nombre original de la clave\n * @returns Nombre encriptado con prefijo __enc_\n */\n public async encryptKey(keyName: string): Promise<string> {\n const baseKey = await this.generateBaseKey();\n const combined = keyName + baseKey;\n const hash = await this.hashString(combined);\n return `__enc_${hash.substring(0, 16)}`;\n }\n\n /**\n * Limpia todos los datos encriptados del localStorage\n */\n public clearEncryptedData(): void {\n const keysToRemove: string[] = [];\n\n // Identificar todas las claves encriptadas\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key && key.startsWith('__enc_')) {\n keysToRemove.push(key);\n }\n }\n\n // Eliminar claves encriptadas\n keysToRemove.forEach(key => localStorage.removeItem(key));\n\n // Eliminar salt\n localStorage.removeItem(EncryptionHelper.SALT_STORAGE_KEY);\n\n // Resetear clave en memoria\n this.key = null;\n this.baseKey = '';\n this.baseKeyPromise = null;\n }\n\n /**\n * Verifica si el navegador soporta Web Crypto API\n */\n public static isSupported(): boolean {\n return !!(\n typeof crypto !== 'undefined' &&\n crypto.subtle &&\n crypto.getRandomValues\n );\n }\n\n // Métodos auxiliares para conversión de datos\n\n private arrayBufferToBase64(buffer: ArrayBuffer): string {\n const bytes = new Uint8Array(buffer);\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n }\n\n private base64ToArrayBuffer(base64: string): ArrayBuffer {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes.buffer;\n }\n\n private arrayBufferToHex(buffer: ArrayBuffer): string {\n const bytes = new Uint8Array(buffer);\n return Array.from(bytes)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n }\n}\n","import type { StorageEventType, StorageEventData, EventListener } from '../types';\n\n/**\n * Simple event emitter for storage events\n */\nexport class EventEmitter {\n private listeners: Map<StorageEventType, Set<EventListener>> = new Map();\n private onceListeners: Map<StorageEventType, Set<EventListener>> = new Map();\n\n /**\n * Register an event listener\n */\n on(event: StorageEventType, listener: EventListener): void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n this.listeners.get(event)!.add(listener);\n }\n\n /**\n * Register a one-time event listener\n */\n once(event: StorageEventType, listener: EventListener): void {\n if (!this.onceListeners.has(event)) {\n this.onceListeners.set(event, new Set());\n }\n this.onceListeners.get(event)!.add(listener);\n }\n\n /**\n * Remove an event listener\n */\n off(event: StorageEventType, listener: EventListener): void {\n this.listeners.get(event)?.delete(listener);\n this.onceListeners.get(event)?.delete(listener);\n }\n\n /**\n * Remove all listeners for an event\n */\n removeAllListeners(event?: StorageEventType): void {\n if (event) {\n this.listeners.delete(event);\n this.onceListeners.delete(event);\n } else {\n this.listeners.clear();\n this.onceListeners.clear();\n }\n }\n\n /**\n * Emit an event\n */\n emit(event: StorageEventType, data: Omit<StorageEventData, 'type' | 'timestamp'>): void {\n const eventData: StorageEventData = {\n type: event,\n timestamp: Date.now(),\n ...data,\n };\n\n // Call regular listeners\n this.listeners.get(event)?.forEach(listener => {\n try {\n listener(eventData);\n } catch (error) {\n console.error(`Error in event listener for ${event}:`, error);\n }\n });\n\n // Call and remove once listeners\n const onceSet = this.onceListeners.get(event);\n if (onceSet) {\n onceSet.forEach(listener => {\n try {\n listener(eventData);\n } catch (error) {\n console.error(`Error in once listener for ${event}:`, error);\n }\n });\n this.onceListeners.delete(event);\n }\n }\n\n /**\n * Get listener count for an event\n */\n listenerCount(event: StorageEventType): number {\n const regularCount = this.listeners.get(event)?.size ?? 0;\n const onceCount = this.onceListeners.get(event)?.size ?? 0;\n return regularCount + onceCount;\n }\n\n /**\n * Get all event types with listeners\n */\n eventNames(): StorageEventType[] {\n const events = new Set<StorageEventType>();\n this.listeners.forEach((_, event) => events.add(event));\n this.onceListeners.forEach((_, event) => events.add(event));\n return Array.from(events);\n }\n}\n","import type { LogLevel, DebugConfig } from '../types';\n\n/**\n * Logger utility for debug mode\n */\nexport class Logger {\n private enabled: boolean;\n private logLevel: LogLevel;\n private prefix: string;\n\n private static readonly LOG_LEVELS: Record<LogLevel, number> = {\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n debug: 4,\n verbose: 5,\n };\n\n constructor(config: DebugConfig = {}) {\n this.enabled = config.enabled ?? false;\n this.logLevel = config.logLevel ?? 'info';\n this.prefix = config.prefix ?? 'SecureStorage';\n }\n\n private shouldLog(level: LogLevel): boolean {\n if (!this.enabled) return false;\n return Logger.LOG_LEVELS[level] <= Logger.LOG_LEVELS[this.logLevel];\n }\n\n private formatMessage(level: string, message: string, ...args: any[]): string {\n const timestamp = new Date().toISOString();\n return `[${this.prefix}] [${level.toUpperCase()}] ${timestamp} - ${message}`;\n }\n\n error(message: string, ...args: any[]): void {\n if (this.shouldLog('error')) {\n console.error(this.formatMessage('error', message), ...args);\n }\n }\n\n warn(message: string, ...args: any[]): void {\n if (this.shouldLog('warn')) {\n console.warn(this.formatMessage('warn', message), ...args);\n }\n }\n\n info(message: string, ...args: any[]): void {\n if (this.shouldLog('info')) {\n console.info(this.formatMessage('info', message), ...args);\n }\n }\n\n debug(message: string, ...args: any[]): void {\n if (this.shouldLog('debug')) {\n console.debug(this.formatMessage('debug', message), ...args);\n }\n }\n\n verbose(message: string, ...args: any[]): void {\n if (this.shouldLog('verbose')) {\n console.log(this.formatMessage('verbose', message), ...args);\n }\n }\n\n time(label: string): void {\n if (this.enabled && this.shouldLog('debug')) {\n console.time(`[${this.prefix}] ${label}`);\n }\n }\n\n timeEnd(label: string): void {\n if (this.enabled && this.shouldLog('debug')) {\n console.timeEnd(`[${this.prefix}] ${label}`);\n }\n }\n\n group(label: string): void {\n if (this.enabled && this.shouldLog('debug')) {\n console.group(`[${this.prefix}] ${label}`);\n }\n }\n\n groupEnd(): void {\n if (this.enabled && this.shouldLog('debug')) {\n console.groupEnd();\n }\n }\n}\n","import { EncryptionHelper } from './EncryptionHelper';\nimport type { EncryptedBackup } from '../types';\nimport { Logger } from '../utils/logger';\n\n/**\n * Key rotation utilities\n */\nexport class KeyRotation {\n private encryptionHelper: EncryptionHelper;\n private logger: Logger;\n\n constructor(encryptionHelper: EncryptionHelper, logger?: Logger) {\n this.encryptionHelper = encryptionHelper;\n this.logger = logger ?? new Logger();\n }\n\n /**\n * Rotate all encryption keys\n * Re-encrypts all data with a new salt\n */\n async rotateKeys(): Promise<void> {\n this.logger.info('Starting key rotation...');\n\n // 1. Export all current data\n const backup = await this.exportEncryptedData();\n\n // 2. Clear old encryption\n this.encryptionHelper.clearEncryptedData();\n\n // 3. Initialize new encryption\n await this.encryptionHelper.initialize();\n\n // 4. Re-encrypt all data\n for (const [key, value] of Object.entries(backup.data)) {\n const encryptedKey = await this.encryptionHelper.encryptKey(key);\n const encryptedValue = await this.encryptionHelper.encrypt(value);\n localStorage.setItem(encryptedKey, encryptedValue);\n }\n\n this.logger.info(`Key rotation completed. Re-encrypted ${backup.metadata.itemCount} items`);\n }\n\n /**\n * Export all encrypted data as backup\n */\n async exportEncryptedData(): Promise<EncryptedBackup> {\n this.logger.info('Exporting encrypted data...');\n const data: Record<string, string> = {};\n let itemCount = 0;\n\n for (let i = 0; i < localStorage.length; i++) {\n const encryptedKey = localStorage.key(i);\n if (encryptedKey && encryptedKey.startsWith('__enc_')) {\n const encryptedValue = localStorage.getItem(encryptedKey);\n if (encryptedValue) {\n try {\n // Decrypt to get original key and value\n const decryptedValue = await this.encryptionHelper.decrypt(encryptedValue);\n // Store with encrypted key as identifier\n data[encryptedKey] = decryptedValue;\n itemCount++;\n } catch (error) {\n this.logger.warn(`Failed to decrypt key ${encryptedKey}:`, error);\n }\n }\n }\n }\n\n const backup: EncryptedBackup = {\n version: '2.0.0',\n timestamp: Date.now(),\n data,\n metadata: {\n keyVersion: this.encryptionHelper.getKeyVersion(),\n algorithm: 'AES-256-GCM',\n itemCount,\n },\n };\n\n this.logger.info(`Exported ${itemCount} items`);\n return backup;\n }\n\n /**\n * Import encrypted data from backup\n */\n async importEncryptedData(backup: EncryptedBackup): Promise<void> {\n this.logger.info(`Importing backup from ${new Date(backup.timestamp).toISOString()}...`);\n\n let imported = 0;\n for (const [encryptedKey, value] of Object.entries(backup.data)) {\n try {\n const encryptedValue = await this.encryptionHelper.encrypt(value);\n localStorage.setItem(encryptedKey, encryptedValue);\n imported++;\n } catch (error) {\n this.logger.error(`Failed to import key ${encryptedKey}:`, error);\n }\n }\n\n this.logger.info(`Imported ${imported}/${backup.metadata.itemCount} items`);\n }\n}\n","import type { SecureStorageConfig } from '../types';\n\n/**\n * Namespaced storage for organizing data\n */\nexport class NamespacedStorage {\n private prefix: string;\n private storage: any; // Reference to parent SecureStorage\n\n constructor(storage: any, namespace: string) {\n this.storage = storage;\n this.prefix = `__ns_${namespace}__`;\n }\n\n /**\n * Set item in this namespace\n */\n async setItem(key: string, value: string): Promise<void> {\n return this.storage.setItem(`${this.prefix}${key}`, value);\n }\n\n /**\n * Set item with expiry in this namespace\n */\n async setItemWithExpiry(key: string, value: string, options: { expiresIn?: number; expiresAt?: Date }): Promise<void> {\n return this.storage.setItemWithExpiry(`${this.prefix}${key}`, value, options);\n }\n\n /**\n * Get item from this namespace\n */\n async getItem(key: string): Promise<string | null> {\n return this.storage.getItem(`${this.prefix}${key}`);\n }\n\n /**\n * Remove item from this namespace\n */\n async removeItem(key: string): Promise<void> {\n return this.storage.removeItem(`${this.prefix}${key}`);\n }\n\n /**\n * Check if item exists in this namespace\n */\n async hasItem(key: string): Promise<boolean> {\n return this.storage.hasItem(`${this.prefix}${key}`);\n }\n\n /**\n * Clear all items in this namespace\n */\n async clearNamespace(): Promise<void> {\n const keysToRemove: string[] = [];\n\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key && key.includes(this.prefix)) {\n keysToRemove.push(key.replace(this.prefix, ''));\n }\n }\n\n for (const key of keysToRemove) {\n await this.removeItem(key);\n }\n }\n\n /**\n * Get all keys in this namespace\n */\n async keys(): Promise<string[]> {\n const keys: string[] = [];\n\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key && key.includes(this.prefix)) {\n keys.push(key.replace(this.prefix, ''));\n }\n }\n\n return keys;\n }\n}\n","/**\n * Compression utilities using CompressionStream API\n */\n\n/**\n * Check if compression is supported\n */\nexport function isCompressionSupported(): boolean {\n return typeof CompressionStream !== 'undefined' && typeof DecompressionStream !== 'undefined';\n}\n\n/**\n * Compress a string using gzip\n */\nexport async function compress(data: string): Promise<Uint8Array> {\n if (!isCompressionSupported()) {\n // Fallback: return uncompressed data with marker\n const encoder = new TextEncoder();\n return encoder.encode(data);\n }\n\n try {\n const encoder = new TextEncoder();\n const stream = new Blob([data]).stream();\n const compressedStream = stream.pipeThrough(new CompressionStream('gzip'));\n const compressedBlob = await new Response(compressedStream).blob();\n const buffer = await compressedBlob.arrayBuffer();\n return new Uint8Array(buffer);\n } catch (error) {\n console.warn('Compression failed, returning uncompressed data:', error);\n const encoder = new TextEncoder();\n return encoder.encode(data);\n }\n}\n\n/**\n * Decompress gzip data to string\n */\nexport async function decompress(data: Uint8Array): Promise<string> {\n if (!isCompressionSupported()) {\n // Fallback: assume uncompressed\n const decoder = new TextDecoder();\n return decoder.decode(data);\n }\n\n try {\n const stream = new Blob([data]).stream();\n const decompressedStream = stream.pipeThrough(new DecompressionStream('gzip'));\n const decompressedBlob = await new Response(decompressedStream).blob();\n return await decompressedBlob.text();\n } catch (error) {\n // If decompression fails, try to decode as plain text\n console.warn('Decompression failed, trying plain text:', error);\n const decoder = new TextDecoder();\n return decoder.decode(data);\n }\n}\n\n/**\n * Check if data should be compressed based on size\n */\nexport function shouldCompress(data: string, threshold: number = 1024): boolean {\n return data.length >= threshold;\n}\n\n/**\n * Get compression ratio\n */\nexport function getCompressionRatio(original: number, compressed: number): number {\n return compressed / original;\n}\n","import { EncryptionHelper } from './EncryptionHelper';\nimport { EventEmitter } from './EventEmitter';\nimport { KeyRotation } from './KeyRotation';\nimport { NamespacedStorage } from './NamespacedStorage';\nimport { Logger } from '../utils/logger';\nimport { compress, decompress, shouldCompress } from '../utils/compression';\nimport type {\n SecureStorageConfig,\n StoredValue,\n ExpiryOptions,\n IntegrityInfo,\n StorageEventType,\n EventListener,\n} from '../types';\nimport { DEFAULT_CONFIG, STORAGE_VERSION } from '../types';\n\n/**\n * SecureStorage v2 - API de alto nivel que imita localStorage con cifrado automático\n * Incluye: configuración personalizable, eventos, compresión, expiración, namespaces, rotación de claves\n */\nexport class SecureStorage {\n private static instance: SecureStorage | null = null;\n private encryptionHelper: EncryptionHelper;\n private eventEmitter: EventEmitter;\n private keyRotation: KeyRotation;\n private logger: Logger;\n private config: Required<SecureStorageConfig>;\n private cleanupInterval: NodeJS.Timeout | null = null;\n\n private constructor(config?: SecureStorageConfig) {\n // Merge config with defaults\n this.config = {\n encryption: { ...DEFAULT_CONFIG.encryption, ...config?.encryption },\n storage: { ...DEFAULT_CONFIG.storage, ...config?.storage },\n debug: { ...DEFAULT_CONFIG.debug, ...config?.debug },\n } as Required<SecureStorageConfig>;\n\n // Initialize components\n this.logger = new Logger(this.config.debug);\n this.encryptionHelper = new EncryptionHelper(this.config.encryption);\n this.eventEmitter = new EventEmitter();\n this.keyRotation = new KeyRotation(this.encryptionHelper, this.logger);\n\n this.logger.info('SecureStorage v2 initialized', this.config);\n\n // Setup auto-cleanup if enabled\n if (this.config.storage.autoCleanup) {\n this.setupAutoCleanup();\n }\n }\n\n /**\n * Obtiene la instancia singleton de SecureStorage\n */\n public static getInstance(config?: SecureStorageConfig): SecureStorage {\n if (!SecureStorage.instance) {\n SecureStorage.instance = new SecureStorage(config);\n }\n return SecureStorage.instance;\n }\n\n /**\n * Setup automatic cleanup of expired items\n */\n private setupAutoCleanup(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n }\n\n this.cleanupInterval = setInterval(() => {\n this.cleanExpired().catch(err => {\n this.logger.error('Auto-cleanup failed:', err);\n });\n }, this.config.storage.cleanupInterval);\n\n this.logger.debug(`Auto-cleanup enabled with interval: ${this.config.storage.cleanupInterval}ms`);\n }\n\n /**\n * Guarda un valor encriptado en localStorage\n */\n public async setItem(key: string, value: string): Promise<void> {\n this.logger.time(`setItem:${key}`);\n\n if (!EncryptionHelper.isSupported()) {\n this.logger.warn('Web Crypto API no soportada, usando localStorage sin encriptar');\n localStorage.setItem(key, value);\n return;\n }\n\n try {\n // Check if compression should be applied\n const shouldCompressData = this.config.storage.compression &&\n shouldCompress(value, this.config.storage.compressionThreshold);\n\n let processedValue = value;\n let compressed = false;\n\n if (shouldCompressData) {\n this.logger.debug(`Compressing value for key: ${key}`);\n const compressedData = await compress(value);\n processedValue = this.encryptionHelper['arrayBufferToBase64'](compressedData.buffer);\n compressed = true;\n this.eventEmitter.emit('compressed', { key });\n }\n\n // Create StoredValue wrapper\n const now = Date.now();\n const storedValue: StoredValue = {\n value: processedValue,\n createdAt: now,\n modifiedAt: now,\n version: STORAGE_VERSION,\n compressed,\n };\n\n // Calculate checksum for integrity\n const checksum = await this.calculateChecksum(processedValue);\n storedValue.checksum = checksum;\n\n // Serialize StoredValue\n const serialized = JSON.stringify(storedValue);\n\n // Encrypt the key\n const encryptedKey = await this.encryptionHelper.encryptKey(key);\n\n // Encrypt the value\n const encryptedValue = await this.encryptionHelper.encrypt(serialized);\n\n // Store in localStorage\n localStorage.setItem(encryptedKey, encryptedValue);\n\n this.logger.verbose(`Stored key: ${key}, compressed: ${compressed}, size: ${encryptedValue.length}`);\n this.eventEmitter.emit('encrypted', { key, metadata: { compressed, size: encryptedValue.length } });\n this.logger.timeEnd(`setItem:${key}`);\n } catch (error) {\n this.logger.error(`Error al guardar dato encriptado para ${key}:`, error);\n this.eventEmitter.emit('error', { key, error: error as Error });\n localStorage.setItem(key, value);\n }\n }\n\n /**\n * Guarda un valor con tiempo de expiración\n */\n public async setItemWithExpiry(key: string, value: string, options: ExpiryOptions): Promise<void> {\n this.logger.time(`setItemWithExpiry:${key}`);\n\n if (!EncryptionHelper.isSupported()) {\n this.logger.warn('Web Crypto API no soportada, usando localStorage sin encriptar');\n localStorage.setItem(key, value);\n return;\n }\n\n try {\n // Check if compression should be applied\n const shouldCompressData = this.config.storage.compression &&\n shouldCompress(value, this.config.storage.compressionThreshold);\n\n let processedValue = value;\n let compressed = false;\n\n if (shouldCompressData) {\n this.logger.debug(`Compressing value for key: ${key}`);\n const compressedData = await compress(value);\n processedValue = this.encryptionHelper['arrayBufferToBase64'](compressedData.buffer);\n compressed = true;\n this.eventEmitter.emit('compressed', { key });\n }\n\n // Calculate expiration timestamp\n let expiresAt: number | undefined;\n if (options.expiresIn) {\n expiresAt = Date.now() + options.expiresIn;\n } else if (options.expiresAt) {\n expiresAt = options.expiresAt.getTime();\n }\n\n // Create StoredValue wrapper\n const now = Date.now();\n const storedValue: StoredValue = {\n value: processedValue,\n createdAt: now,\n modifiedAt: now,\n version: STORAGE_VERSION,\n compressed,\n expiresAt,\n };\n\n // Calculate checksum for integrity\n const checksum = await this.calculateChecksum(processedValue);\n storedValue.checksum = checksum;\n\n // Serialize StoredValue\n const serialized = JSON.stringify(storedValue);\n\n // Encrypt the key\n const encryptedKey = await this.encryptionHelper.encryptKey(key);\n\n // Encrypt the value\n const encryptedValue = await this.encryptionHelper.encrypt(serialized);\n\n // Store in localStorage\n localStorage.setItem(encryptedKey, encryptedValue);\n\n this.logger.verbose(`Stored key with expiry: ${key}, expiresAt: ${expiresAt}`);\n this.eventEmitter.emit('encrypted', { key, metadata: { compressed, expiresAt } });\n this.logger.timeEnd(`setItemWithExpiry:${key}`);\n } catch (error) {\n this.logger.error(`Error al guardar dato con expiración para ${key}:`, error);\n this.eventEmitter.emit('error', { key, error: error as Error });\n throw error;\n }\n }\n\n /**\n * Recupera y desencripta un valor de localStorage\n */\n public async getItem(key: string): Promise<string | null> {\n this.logger.time(`getItem:${key}`);\n\n if (!EncryptionHelper.isSupported()) {\n return localStorage.getItem(key);\n }\n\n try {\n // Encrypt the key\n const encryptedKey = await this.encryptionHelper.encryptKey(key);\n\n // Get encrypted value\n let encryptedValue = localStorage.getItem(encryptedKey);\n\n // Backward compatibility: try with plain key\n if (!encryptedValue) {\n encryptedValue = localStorage.getItem(key);\n if (!encryptedValue) {\n this.logger.timeEnd(`getItem:${key}`);\n return null;\n }\n }\n\n // Decrypt the value\n const decrypted = await this.encryptionHelper.decrypt(encryptedValue);\n\n // Try to parse as StoredValue (v2 format)\n let storedValue: StoredValue;\n try {\n storedValue = JSON.parse(decrypted);\n\n // Validate it's a StoredValue object\n if (!storedValue.value || !storedValue.version) {\n // It's v1 format (plain string), auto-migrate\n this.logger.info(`Auto-migrating v1 data for key: ${key}`);\n await this.setItem(key, decrypted);\n this.logger.timeEnd(`getItem:${key}`);\n return decrypted;\n }\n } catch {\n // Not JSON, it's v1 format (plain string), auto-migrate\n this.logger.info(`Auto-migrating v1 data for key: ${key}`);\n await this.setItem(key, decrypted);\n this.logger.timeEnd(`getItem:${key}`);\n return decrypted;\n }\n\n // Check expiration\n if (storedValue.expiresAt && storedValue.expiresAt < Date.now()) {\n this.logger.info(`Key expired: ${key}`);\n await this.removeItem(key);\n this.eventEmitter.emit('expired', { key });\n this.logger.timeEnd(`getItem:${key}`);\n return null;\n }\n\n // Verify integrity if checksum exists\n if (storedValue.checksum) {\n const calculatedChecksum = await this.calculateChecksum(storedValue.value);\n if (calculatedChecksum !== storedValue.checksum) {\n this.logger.warn(`Integrity check failed for key: ${key}`);\n this.eventEmitter.emit('error', {\n key,\n error: new Error('Integrity verification failed')\n });\n }\n }\n\n // Decompress if needed\n let finalValue = storedValue.value;\n if (storedValue.compressed) {\n this.logger.debug(`Decompressing value for key: ${key}`);\n const compressedData = this.encryptionHelper['base64ToArrayBuffer'](storedValue.value);\n finalValue = await decompress(new Uint8Array(compressedData));\n this.eventEmitter.emit('decompressed', { key });\n }\n\n this.eventEmitter.emit('decrypted', { key });\n this.logger.timeEnd(`getItem:${key}`);\n return finalValue;\n } catch (error) {\n this.logger.error(`Error al recuperar dato encriptado para ${key}:`, error);\n this.eventEmitter.emit('error', { key, error: error as Error });\n // Fallback: try plain key\n const fallback = localStorage.getItem(key);\n this.logger.timeEnd(`getItem:${key}`);\n return fallback;\n }\n }\n\n /**\n * Elimina un valor de localStorage\n */\n public async removeItem(key: string): Promise<void> {\n if (!EncryptionHelper.isSupported()) {\n localStorage.removeItem(key);\n return;\n }\n\n try {\n const encryptedKey = await this.encryptionHelper.encryptKey(key);\n localStorage.removeItem(encryptedKey);\n localStorage.removeItem(key); // Remove both versions\n this.eventEmitter.emit('deleted', { key });\n this.logger.info(`Removed key: ${key}`);\n } catch (error) {\n this.logger.error(`Error al eliminar dato para ${key}:`, error);\n localStorage.removeItem(key);\n }\n }\n\n /**\n * Verifica si existe un valor para la clave dada\n */\n public async hasItem(key: string): Promise<boolean> {\n const value = await this.getItem(key);\n return value !== null;\n }\n\n /**\n * Limpia todos los datos encriptados\n */\n public clear(): void {\n this.encryptionHelper.clearEncryptedData();\n this.eventEmitter.emit('cleared', {});\n this.logger.info('All encrypted data cleared');\n }\n\n /**\n * Limpia todos los items expirados\n */\n public async cleanExpired(): Promise<number> {\n this.logger.info('Starting cleanup of expired items...');\n let cleanedCount = 0;\n\n const keysToCheck: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key && key.startsWith('__enc_')) {\n keysToCheck.push(key);\n }\n }\n\n for (const encryptedKey of keysToCheck) {\n try {\n const encryptedValue = localStorage.getItem(encryptedKey);\n if (!encryptedValue) continue;\n\n const decrypted = await this.encryptionHelper.decrypt(encryptedValue);\n const storedValue: StoredValue = JSON.parse(decrypted);\n\n if (storedValue.expiresAt && storedValue.expiresAt < Date.now()) {\n localStorage.removeItem(encryptedKey);\n cleanedCount++;\n this.eventEmitter.emit('expired', { key: encryptedKey });\n }\n } catch (error) {\n this.logger.warn(`Failed to check expiration for ${encryptedKey}:`, error);\n }\n }\n\n this.logger.info(`Cleanup completed. Removed ${cleanedCount} expired items`);\n return cleanedCount;\n }\n\n /**\n * Verifica la integridad de un valor almacenado\n */\n public async verifyIntegrity(key: string): Promise<boolean> {\n try {\n const encryptedKey = await this.encryptionHelper.encryptKey(key);\n const encryptedValue = localStorage.getItem(encryptedKey);\n\n if (!encryptedValue) return false;\n\n const decrypted = await this.encryptionHelper.decrypt(encryptedValue);\n const storedValue: StoredValue = JSON.parse(decrypted);\n\n if (!storedValue.checksum) {\n this.logger.warn(`No checksum found for key: ${key}`);\n return true; // No checksum to verify\n }\n\n const calculatedChecksum = await this.calculateChecksum(storedValue.value);\n return calculatedChecksum === storedValue.checksum;\n } catch (error) {\n this.logger.error(`Error verifying integrity for ${key}:`, error);\n return false;\n }\n }\n\n /**\n * Obtiene información de integridad de un valor\n */\n public async getIntegrityInfo(key: string): Promise<IntegrityInfo | null> {\n try {\n const encryptedKey = await this.encryptionHelper.encryptKey(key);\n const encryptedValue = localStorage.getItem(encryptedKey);\n\n if (!encryptedValue) return null;\n\n const decrypted = await this.encryptionHelper.decrypt(encryptedValue);\n const storedValue: StoredValue = JSON.parse(decrypted);\n\n const valid = storedValue.checksum\n ? await this.calculateChecksum(storedValue.value) === storedValue.checksum\n : true;\n\n return {\n valid,\n lastModified: storedValue.modifiedAt,\n checksum: storedValue.checksum || '',\n version: storedValue.version,\n };\n } catch (error) {\n this.logger.error(`Error getting integrity info for ${key}:`, error);\n return null;\n }\n }\n\n /**\n * Crea un namespace para organizar datos\n */\n public namespace(name: string): NamespacedStorage {\n this.logger.debug(`Creating namespace: ${name}`);\n return new NamespacedStorage(this, name);\n }\n\n /**\n * Rota todas las claves de encriptación\n */\n public async rotateKeys(): Promise<void> {\n this.logger.info('Starting key rotation...');\n await this.keyRotation.rotateKeys();\n this.eventEmitter.emit('keyRotated', {});\n this.logger.info('Key rotation completed');\n }\n\n /**\n * Exporta todos los datos encriptados como backup\n */\n public async exportEncryptedData() {\n return this.keyRotation.exportEncryptedData();\n }\n\n /**\n * Importa datos desde un backup\n */\n public async importEncryptedData(backup: any) {\n return this.keyRotation.importEncryptedData(backup);\n }\n\n /**\n * Registra un listener de eventos\n */\n public on(event: StorageEventType, listener: EventListener): void {\n this.eventEmitter.on(event, listener);\n }\n\n /**\n * Registra un listener de un solo uso\n */\n public once(event: StorageEventType, listener: EventListener): void {\n this.eventEmitter.once(event, listener);\n }\n\n /**\n * Elimina un listener de eventos\n */\n public off(event: StorageEventType, listener: EventListener): void {\n this.eventEmitter.off(event, listener);\n }\n\n /**\n * Elimina todos los listeners de un evento\n */\n public removeAllListeners(event?: StorageEventType): void {\n this.eventEmitter.removeAllListeners(event);\n }\n\n /**\n * Migra datos existentes no encriptados a formato encriptado\n */\n public async migrateExistingData(keys: string[]): Promise<void> {\n if (!EncryptionHelper.isSupported()) {\n this.logger.warn('Web Crypto API no soportada, no se puede migrar');\n return;\n }\n\n this.logger.info(`Iniciando migración de ${keys.length} claves...`);\n\n for (const key of keys) {\n try {\n const value = localStorage.getItem(key);\n if (value === null) continue;\n\n // Try to decrypt to check if already encrypted\n try {\n await this.encryptionHelper.decrypt(value);\n this.logger.info(`✓ ${key} ya está encriptado, saltando`);\n continue;\n } catch {\n // Not encrypted, proceed with migration\n }\n\n await this.setItem(key, value);\n localStorage.removeItem(key);\n this.logger.info(`✓ ${key} migrado exitosamente`);\n } catch (error) {\n this.logger.error(`✗ Error al migrar ${key}:`, error);\n }\n }\n\n this.logger.info('✅ Migración completada');\n }\n\n /**\n * Obtiene información de debug sobre el estado del almacenamiento\n */\n public getDebugInfo(): {\n cryptoSupported: boolean;\n encryptedKeys: string[];\n unencryptedKeys: string[];\n totalKeys: number;\n config: Required<SecureStorageConfig>;\n } {\n const allKeys: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key) allKeys.push(key);\n }\n\n const encryptedKeys = allKeys.filter(key => key.startsWith('__enc_'));\n const unencryptedKeys = allKeys.filter(\n key => !key.startsWith('__enc_') && key !== '__app_salt' && key !== '__key_version'\n );\n\n return {\n cryptoSupported: EncryptionHelper.isSupported(),\n encryptedKeys,\n unencryptedKeys,\n totalKeys: allKeys.length,\n config: this.config,\n };\n }\n\n /**\n * Calcula el checksum SHA-256 de un valor\n */\n private async calculateChecksum(value: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(value);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n }\n\n /**\n * Cleanup on destroy\n */\n public destroy(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = null;\n }\n this.removeAllListeners();\n this.logger.info('SecureStorage destroyed');\n }\n}\n","import { EncryptionHelper } from '../core/EncryptionHelper';\nimport { SecureStorage } from '../core/SecureStorage';\n\nconst secureStorage = SecureStorage.getInstance();\n\n/**\n * Función de debug para verificar el estado del sistema de encriptación\n * Muestra información detallada en la consola\n */\nexport async function debugEncryptionState(): Promise<void> {\n console.group('🔐 Estado del Sistema de Encriptación');\n\n console.log('Soporte Crypto API:', EncryptionHelper.isSupported());\n\n // Obtener información de debug\n const debugInfo = secureStorage.getDebugInfo();\n\n console.log('Claves encriptadas:', debugInfo.encryptedKeys.length);\n console.log('Claves sin encriptar:', debugInfo.unencryptedKeys);\n console.log('Total de claves:', debugInfo.totalKeys);\n\n if (debugInfo.encryptedKeys.length > 0) {\n console.log('✅ Datos encriptados encontrados:');\n debugInfo.encryptedKeys.forEach(key => {\n const value = localStorage.getItem(key);\n console.log(` ${key}: ${value?.substring(0, 30)}...`);\n });\n } else {\n console.log('⚠️ No se encontraron datos encriptados');\n }\n\n if (debugInfo.unencryptedKeys.length > 0) {\n console.log('⚠️ Claves sin encriptar encontradas:');\n debugInfo.unencryptedKeys.forEach(key => {\n console.log(` ${key}`);\n });\n }\n\n console.groupEnd();\n}\n\n/**\n * Fuerza la migración de claves comunes a formato encriptado\n * Útil para desarrollo y testing\n */\nexport async function forceMigration(customKeys?: string[]): Promise<void> {\n const defaultKeys = [\n 'accessToken',\n 'refreshToken',\n 'user',\n 'sessionId',\n 'authToken',\n 'userData',\n ];\n\n const keysToMigrate = customKeys || defaultKeys;\n\n console.log(`🔄 Iniciando migración forzada de ${keysToMigrate.length} claves...`);\n\n await secureStorage.migrateExistingData(keysToMigrate);\n\n console.log('✅ Migración forzada completada');\n\n // Mostrar estado después de la migración\n await debugEncryptionState();\n}\n\n/**\n * Limpia todos los datos encriptados (útil para testing)\n */\nexport function clearAllEncryptedData(): void {\n console.log('🗑️ Limpiando todos los datos encriptados...');\n secureStorage.clear();\n console.log('✅ Datos encriptados limpiados');\n}\n\n/**\n * Prueba el sistema de encriptación con datos de ejemplo\n */\nexport async function testEncryption(): Promise<void> {\n console.group('🧪 Prueba del Sistema de Encriptación');\n\n try {\n const testKey = '__test_encryption_key';\n const testValue = 'Este es un valor de prueba con caracteres especiales: áéíóú ñ 你好 🔐';\n\n console.log('1. Guardando valor de prueba...');\n await secureStorage.setItem(testKey, testValue);\n console.log('✅ Valor guardado');\n\n console.log('2. Recuperando valor...');\n const retrieved = await secureStorage.getItem(testKey);\n console.log('✅ Valor recuperado:', retrieved);\n\n console.log('3. Verificando integridad...');\n if (retrieved === testValue) {\n console.log('✅ Integridad verificada - Los valores coinciden');\n } else {\n console.error('❌ Error de integridad - Los valores NO coinciden');\n console.log('Original:', testValue);\n console.log('Recuperado:', retrieved);\n }\n\n console.log('4. Limpiando valor de prueba...');\n await secureStorage.removeItem(testKey);\n console.log('✅ Valor eliminado');\n\n console.log('5. Verificando eliminación...');\n const shouldBeNull = await secureStorage.getItem(testKey);\n if (shouldBeNull === null) {\n console.log('✅ Eliminación verificada');\n } else {\n console.error('❌ El valor no fue eliminado correctamente');\n }\n\n console.log('\\n✅ Todas las pruebas pasaron exitosamente');\n } catch (error) {\n console.error('❌ Error en las pruebas:', error);\n }\n\n console.groupEnd();\n}\n","/**\n * @bantis/local-cipher - Core Module\n * Framework-agnostic client-side encryption for browser storage\n * \n * @version 2.1.0\n * @license MIT\n */\n\n// Core classes\nexport { EncryptionHelper } from './core/EncryptionHelper';\nexport { SecureStorage } from './core/SecureStorage';\nexport { EventEmitter } from './core/EventEmitter';\nexport { KeyRotation } from './core/KeyRotation';\nexport { NamespacedStorage } from './core/NamespacedStorage';\n\n// Type exports\nexport type {\n EncryptionConfig,\n StorageConfig,\n DebugConfig,\n SecureStorageConfig,\n StoredValue,\n ExpiryOptions,\n EncryptedBackup,\n IntegrityInfo,\n StorageEventType,\n StorageEventData,\n EventListener,\n LogLevel,\n} from './types';\nexport { DEFAULT_CONFIG, LIBRARY_VERSION, STORAGE_VERSION } from './types';\n\n// Utility exports\nexport { Logger } from './utils/logger';\nexport { compress, decompress, shouldCompress, isCompressionSupported } from './utils/compression';\nexport { debugEncryptionState, forceMigration } from './utils/debug';\n\n// Default instance for vanilla JS\nimport { SecureStorage } from './core/SecureStorage';\nexport const secureStorage = SecureStorage.getInstance();\n\n// Version\nexport const VERSION = '2.1.0';\n","/**\n * React Hooks for @bantis/local-cipher\n * Provides reactive hooks for encrypted browser storage\n */\n\nimport { useState, useEffect, useCallback } from 'react';\nimport { SecureStorage } from '../core/SecureStorage';\nimport type { SecureStorageConfig, StorageEventType, StorageEventData, ExpiryOptions } from '../types';\n\n// Allow custom storage instance or use default\nlet defaultStorage: SecureStorage | null = null;\n\nfunction getDefaultStorage(): SecureStorage {\n if (!defaultStorage) {\n defaultStorage = SecureStorage.getInstance();\n }\n return defaultStorage;\n}\n\n/**\n * Initialize SecureStorage with custom configuration\n */\nexport function initializeSecureStorage(config?: SecureStorageConfig): SecureStorage {\n defaultStorage = SecureStorage.getInstance(config);\n return defaultStorage;\n}\n\n/**\n * Hook de React para usar SecureStorage de forma reactiva\n * Similar a useState pero con persistencia encriptada\n */\nexport function useSecureStorage<T = string>(\n key: string,\n initialValue: T,\n storage?: SecureStorage\n): [T, (value: T) => Promise<void>, boolean, Error | null] {\n const secureStorage = storage || getDefaultStorage();\n const [storedValue, setStoredValue] = useState<T>(initialValue);\n const [loading, setLoading] = useState<boolean>(true);\n const [error, setError] = useState<Error | null>(null);\n\n useEffect(() => {\n const loadValue = async () => {\n try {\n setLoading(true);\n setError(null);\n const item = await secureStorage.getItem(key);\n\n if (item !== null) {\n if (typeof initialValue === 'object') {\n setStoredValue(JSON.parse(item) as T);\n } else {\n setStoredValue(item as T);\n }\n } else {\n setStoredValue(initialValue);\n }\n } catch (err) {\n setError(err instanceof Error ? err : new Error('Error al cargar valor'));\n setStoredValue(initialValue);\n } finally {\n setLoading(false);\n }\n };\n\n loadValue();\n }, [key]);\n\n const setValue = useCallback(\n async (value: T) => {\n try {\n setError(null);\n setStoredValue(value);\n\n const valueToStore = typeof value === 'object'\n ? JSON.stringify(value)\n : String(value);\n\n await secureStorage.setItem(key, valueToStore);\n } catch (err) {\n setError(err instanceof Error ? err : new Error('Error al guardar valor'));\n throw err;\n }\n },\n [key, secureStorage]\n );\n\n return [storedValue, setValue, loading, error];\n}\n\n/**\n * Hook para usar SecureStorage con expiración\n */\nexport function useSecureStorageWithExpiry<T = string>(\n key: string,\n initialValue: T,\n expiryOptions: ExpiryOptions,\n storage?: SecureStorage\n): [T, (value: T) => Promise<void>, boolean, Error | null] {\n const secureStorage = storage || getDefaultStorage();\n const [storedValue, setStoredValue] = useState<T>(initialValue);\n const [loading, setLoading] = useState<boolean>(true);\n const [error, setError] = useState<Error | null>(null);\n\n useEffect(() => {\n const loadValue = async () => {\n try {\n setLoading(true);\n setError(null);\n const item = await secureStorage.getItem(key);\n\n if (item !== null) {\n if (typeof initialValue === 'object') {\n setStoredValue(JSON.parse(item) as T);\n } else {\n setStoredValue(item as T);\n }\n } else {\n setStoredValue(initialValue);\n }\n } catch (err) {\n setError(err instanceof Error ? err : new Error('Error al cargar valor'));\n setStoredValue(initialValue);\n } finally {\n setLoading(false);\n }\n };\n\n loadValue();\n }, [key]);\n\n const setValue = useCallback(\n async (value: T) => {\n try {\n setError(null);\n setStoredValue(value);\n\n const valueToStore = typeof value === 'object'\n ? JSON.stringify(value)\n : String(value);\n\n await secureStorage.setItemWithExpiry(key, valueToStore, expiryOptions);\n } catch (err) {\n setError(err instanceof Error ? err : new Error('Error al guardar valor'));\n throw err;\n }\n },\n [key, secureStorage, expiryOptions]\n );\n\n return [storedValue, setValue, loading, error];\n}\n\n/**\n * Hook para verificar si una clave existe en SecureStorage\n */\nexport function useSecureStorageItem(\n key: string,\n storage?: SecureStorage\n): [boolean, boolean, Error | null] {\n const secureStorage = storage || getDefaultStorage();\n const [exists, setExists] = useState<boolean>(false);\n const [loading, setLoading] = useState<boolean>(true);\n const [error, setError] = useState<Error | null>(null);\n\n useEffect(() => {\n const checkExists = async () => {\n try {\n setLoading(true);\n setError(null);\n const hasItem = await secureStorage.hasItem(key);\n setExists(hasItem);\n } catch (err) {\n setError(err instanceof Error ? err : new Error('Error al verificar clave'));\n setExists(false);\n } finally {\n setLoading(false);\n }\n };\n\n checkExists();\n }, [key, secureStorage]);\n\n return [exists, loading, error];\n}\n\n/**\n * Hook para escuchar eventos de SecureStorage\n */\nexport function useSecureStorageEvents(\n event: StorageEventType,\n handler: (data: StorageEventData) => void,\n storage?: SecureStorage\n): void {\n const secureStorage = storage || getDefaultStorage();\n\n useEffect(() => {\n secureStorage.on(event, handler);\n\n return () => {\n secureStorage.off(event, handler);\n };\n }, [event, handler, secureStorage]);\n}\n\n/**\n * Hook para obtener información de debug del almacenamiento\n */\nexport function useSecureStorageDebug(storage?: SecureStorage) {\n const secureStorage = storage || getDefaultStorage();\n const [debugInfo, setDebugInfo] = useState(secureStorage.getDebugInfo());\n\n useEffect(() => {\n const interval = setInterval(() => {\n setDebugInfo(secureStorage.getDebugInfo());\n }, 1000);\n\n return () => clearInterval(interval);\n }, [secureStorage]);\n\n return debugInfo;\n}\n\n/**\n * Hook para usar un namespace de SecureStorage\n */\nexport function useNamespace(namespace: string, storage?: SecureStorage) {\n const secureStorage = storage || getDefaultStorage();\n const [namespacedStorage] = useState(() => secureStorage.namespace(namespace));\n\n return namespacedStorage;\n}\n\n/**\n * Exportar la instancia de SecureStorage para uso directo\n */\nexport const secureStorage = getDefaultStorage();\n"],"names":["secureStorage","useState","useEffect","useCallback"],"mappings":";;;;AAAA;;AAEG;AAiKH;;AAEG;AACI,MAAM,cAAc,GAAkC;AACzD,IAAA,UAAU,EAAE;AACR,QAAA,UAAU,EAAE,MAAM;AAClB,QAAA,UAAU,EAAE,EAAE;AACd,QAAA,QAAQ,EAAE,EAAE;AACZ,QAAA,aAAa,EAAE,wBAAwB;AACvC,QAAA,SAAS,EAAE,GAAG;AACjB,KAAA;AACD,IAAA,OAAO,EAAE;AACL,QAAA,WAAW,EAAE,IAAI;AACjB,QAAA,oBAAoB,EAAE,IAAI;AAC1B,QAAA,WAAW,EAAE,IAAI;AACjB,QAAA,eAAe,EAAE,KAAK;AACzB,KAAA;AACD,IAAA,KAAK,EAAE;AACH,QAAA,OAAO,EAAE,KAAK;AACd,QAAA,QAAQ,EAAE,MAAM;AAChB,QAAA,MAAM,EAAE,eAAe;AAC1B,KAAA;;AAGL;;AAEG;AACI,MAAM,eAAe,GAAG;AAE/B;;AAEG;AACI,MAAM,eAAe,GAAG;;AChM/B;;;AAGG;MACU,gBAAgB,CAAA;AAgBzB,IAAA,WAAA,CAAY,MAAyB,EAAA;;QAL7B,IAAA,CAAA,GAAG,GAAqB,IAAI;QAC5B,IAAA,CAAA,OAAO,GAAW,EAAE;QACpB,IAAA,CAAA,cAAc,GAA2B,IAAI;QAC7C,IAAA,CAAA,UAAU,GAAW,CAAC;AAG1B,QAAA,IAAI,CAAC,MAAM,GAAG,EAAE,GAAG,cAAc,CAAC,UAAU,EAAE,GAAG,MAAM,EAAgC;;QAGvF,MAAM,aAAa,GAAG,YAAY,CAAC,OAAO,CAAC,gBAAgB,CAAC,eAAe,CAAC;QAC5E,IAAI,aAAa,EAAE;YAC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AC,aAAa,CAAC,YAAY,EAAE,CAAC;QAC9C,CAAC,EAAE,IAAI,CAAC;AAER,QAAA,OAAO,MAAM,aAAa,CAAC,QAAQ,CAAC;AACxC,IAAA,CAAC,EAAE,CAAC,aAAa,CAAC,CAAC;AAEnB,IAAA,OAAO,SAAS;AACpB;AAEA;;AAEG;AACG,SAAU,YAAY,CAAC,SAAiB,EAAE,OAAuB,EAAA;AACnE,IAAA,MAAM,aAAa,GAAG,OAAO,IAAI,iBAAiB,EAAE;AACpD,IAAA,MAAM,CAAC,iBAAiB,CAAC,GAAGD,cAAQ,CAAC,MAAM,aAAa,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;AAE9E,IAAA,OAAO,iBAAiB;AAC5B;AAEA;;AAEG;AACI,MAAM,aAAa,GAAG,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Configuration types for @bantis/local-cipher
3
+ */
4
+ /**
5
+ * Encryption configuration options
6
+ */
7
+ export interface EncryptionConfig {
8
+ /** Number of PBKDF2 iterations (default: 100000) */
9
+ iterations?: number;
10
+ /** Salt length in bytes (default: 16) */
11
+ saltLength?: number;
12
+ /** IV length in bytes (default: 12) */
13
+ ivLength?: number;
14
+ /** Custom app identifier for fingerprinting (default: 'bantis-local-cipher-v2') */
15
+ appIdentifier?: string;
16
+ /** AES key length in bits (default: 256) */
17
+ keyLength?: 128 | 192 | 256;
18
+ }
19
+ /**
20
+ * Storage configuration options
21
+ */
22
+ export interface StorageConfig {
23
+ /** Enable data compression (default: true for values > 1KB) */
24
+ compression?: boolean;
25
+ /** Compression threshold in bytes (default: 1024) */
26
+ compressionThreshold?: number;
27
+ /** Enable automatic cleanup of expired items (default: true) */
28
+ autoCleanup?: boolean;
29
+ /** Auto cleanup interval in ms (default: 60000 - 1 minute) */
30
+ cleanupInterval?: number;
31
+ }
32
+ /**
33
+ * Debug configuration options
34
+ */
35
+ export interface DebugConfig {
36
+ /** Enable debug mode (default: false) */
37
+ enabled?: boolean;
38
+ /** Log level (default: 'info') */
39
+ logLevel?: LogLevel;
40
+ /** Custom log prefix (default: 'SecureStorage') */
41
+ prefix?: string;
42
+ }
43
+ /**
44
+ * Log levels
45
+ */
46
+ export type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug' | 'verbose';
47
+ /**
48
+ * Complete configuration for SecureStorage
49
+ */
50
+ export interface SecureStorageConfig {
51
+ /** Encryption configuration */
52
+ encryption?: EncryptionConfig;
53
+ /** Storage configuration */
54
+ storage?: StorageConfig;
55
+ /** Debug configuration */
56
+ debug?: DebugConfig;
57
+ }
58
+ /**
59
+ * Stored value with metadata
60
+ */
61
+ export interface StoredValue {
62
+ /** Encrypted value */
63
+ value: string;
64
+ /** Expiration timestamp (ms since epoch) */
65
+ expiresAt?: number;
66
+ /** Creation timestamp (ms since epoch) */
67
+ createdAt: number;
68
+ /** Last modified timestamp (ms since epoch) */
69
+ modifiedAt: number;
70
+ /** Data version for migration */
71
+ version: number;
72
+ /** Whether value is compressed */
73
+ compressed?: boolean;
74
+ /** SHA-256 checksum for integrity */
75
+ checksum?: string;
76
+ }
77
+ /**
78
+ * Options for setItemWithExpiry
79
+ */
80
+ export interface ExpiryOptions {
81
+ /** Expiration time in milliseconds from now */
82
+ expiresIn?: number;
83
+ /** Absolute expiration date */
84
+ expiresAt?: Date;
85
+ }
86
+ /**
87
+ * Encrypted backup structure
88
+ */
89
+ export interface EncryptedBackup {
90
+ /** Backup version */
91
+ version: string;
92
+ /** Backup timestamp */
93
+ timestamp: number;
94
+ /** Encrypted data */
95
+ data: Record<string, string>;
96
+ /** Backup metadata */
97
+ metadata: {
98
+ /** Key version used for encryption */
99
+ keyVersion: number;
100
+ /** Encryption algorithm */
101
+ algorithm: string;
102
+ /** Number of items */
103
+ itemCount: number;
104
+ };
105
+ }
106
+ /**
107
+ * Integrity information
108
+ */
109
+ export interface IntegrityInfo {
110
+ /** Whether data is valid */
111
+ valid: boolean;
112
+ /** Last modified timestamp */
113
+ lastModified: number;
114
+ /** SHA-256 checksum */
115
+ checksum: string;
116
+ /** Data version */
117
+ version: number;
118
+ }
119
+ /**
120
+ * Storage event types
121
+ */
122
+ export type StorageEventType = 'encrypted' | 'decrypted' | 'deleted' | 'cleared' | 'expired' | 'error' | 'keyRotated' | 'compressed' | 'decompressed';
123
+ /**
124
+ * Storage event data
125
+ */
126
+ export interface StorageEventData {
127
+ /** Event type */
128
+ type: StorageEventType;
129
+ /** Key involved (if applicable) */
130
+ key?: string;
131
+ /** Event timestamp */
132
+ timestamp: number;
133
+ /** Additional metadata */
134
+ metadata?: any;
135
+ /** Error (if type is 'error') */
136
+ error?: Error;
137
+ }
138
+ /**
139
+ * Event listener function
140
+ */
141
+ export type EventListener = (data: StorageEventData) => void;
142
+ /**
143
+ * Default configuration values
144
+ */
145
+ export declare const DEFAULT_CONFIG: Required<SecureStorageConfig>;
146
+ /**
147
+ * Current library version
148
+ */
149
+ export declare const LIBRARY_VERSION = "2.0.0";
150
+ /**
151
+ * Storage data version
152
+ */
153
+ export declare const STORAGE_VERSION = 2;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Compression utilities using CompressionStream API
3
+ */
4
+ /**
5
+ * Check if compression is supported
6
+ */
7
+ export declare function isCompressionSupported(): boolean;
8
+ /**
9
+ * Compress a string using gzip
10
+ */
11
+ export declare function compress(data: string): Promise<Uint8Array>;
12
+ /**
13
+ * Decompress gzip data to string
14
+ */
15
+ export declare function decompress(data: Uint8Array): Promise<string>;
16
+ /**
17
+ * Check if data should be compressed based on size
18
+ */
19
+ export declare function shouldCompress(data: string, threshold?: number): boolean;
20
+ /**
21
+ * Get compression ratio
22
+ */
23
+ export declare function getCompressionRatio(original: number, compressed: number): number;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Función de debug para verificar el estado del sistema de encriptación
3
+ * Muestra información detallada en la consola
4
+ */
5
+ export declare function debugEncryptionState(): Promise<void>;
6
+ /**
7
+ * Fuerza la migración de claves comunes a formato encriptado
8
+ * Útil para desarrollo y testing
9
+ */
10
+ export declare function forceMigration(customKeys?: string[]): Promise<void>;
11
+ /**
12
+ * Limpia todos los datos encriptados (útil para testing)
13
+ */
14
+ export declare function clearAllEncryptedData(): void;
15
+ /**
16
+ * Prueba el sistema de encriptación con datos de ejemplo
17
+ */
18
+ export declare function testEncryption(): Promise<void>;
@@ -0,0 +1,22 @@
1
+ import type { DebugConfig } from '../types';
2
+ /**
3
+ * Logger utility for debug mode
4
+ */
5
+ export declare class Logger {
6
+ private enabled;
7
+ private logLevel;
8
+ private prefix;
9
+ private static readonly LOG_LEVELS;
10
+ constructor(config?: DebugConfig);
11
+ private shouldLog;
12
+ private formatMessage;
13
+ error(message: string, ...args: any[]): void;
14
+ warn(message: string, ...args: any[]): void;
15
+ info(message: string, ...args: any[]): void;
16
+ debug(message: string, ...args: any[]): void;
17
+ verbose(message: string, ...args: any[]): void;
18
+ time(label: string): void;
19
+ timeEnd(label: string): void;
20
+ group(label: string): void;
21
+ groupEnd(): void;
22
+ }
package/package.json CHANGED
@@ -1,11 +1,28 @@
1
1
  {
2
2
  "name": "@bantis/local-cipher",
3
- "version": "2.0.0",
4
- "description": "Librería de cifrado local AES-256-GCM v2 con configuración personalizable, eventos, compresión, expiración, namespaces y rotación de claves para Angular, React y JavaScript",
3
+ "version": "2.1.0",
4
+ "description": "Client-side encryption for localStorage - Framework-agnostic with React and Angular support",
5
5
  "type": "module",
6
- "main": "dist/index.js",
7
- "module": "dist/index.esm.js",
8
- "types": "dist/index.d.ts",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.esm.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/index.esm.js",
12
+ "require": "./dist/index.js",
13
+ "types": "./dist/index.d.ts"
14
+ },
15
+ "./react": {
16
+ "import": "./dist/react.esm.js",
17
+ "require": "./dist/react.js",
18
+ "types": "./dist/react.d.ts"
19
+ },
20
+ "./angular": {
21
+ "import": "./dist/angular.esm.js",
22
+ "require": "./dist/angular.js",
23
+ "types": "./dist/angular.d.ts"
24
+ }
25
+ },
9
26
  "files": [
10
27
  "dist",
11
28
  "README.md",
@@ -21,15 +38,29 @@
21
38
  },
22
39
  "keywords": [
23
40
  "encryption",
24
- "aes-256-gcm",
25
- "pbkdf2",
26
41
  "localstorage",
27
42
  "security",
43
+ "aes-256-gcm",
28
44
  "crypto",
29
- "angular",
30
- "react",
31
45
  "typescript",
32
- "fingerprinting"
46
+ "react",
47
+ "angular",
48
+ "web-crypto-api",
49
+ "client-side-encryption",
50
+ "browser-storage",
51
+ "pbkdf2",
52
+ "secure-storage",
53
+ "data-encryption",
54
+ "xss-protection",
55
+ "frontend-security",
56
+ "storage-encryption",
57
+ "encrypted-storage",
58
+ "browser-encryption",
59
+ "javascript-encryption",
60
+ "secure-localstorage",
61
+ "aes-encryption",
62
+ "token-storage",
63
+ "jwt-encryption"
33
64
  ],
34
65
  "author": "MTT",
35
66
  "license": "MIT",
@@ -58,14 +89,18 @@
58
89
  "typescript": "^5.3.3"
59
90
  },
60
91
  "peerDependencies": {
61
- "react": ">=16.8.0",
62
- "@angular/core": ">=12.0.0"
92
+ "@angular/core": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0",
93
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0",
94
+ "rxjs": "^7.0.0"
63
95
  },
64
96
  "peerDependenciesMeta": {
97
+ "@angular/core": {
98
+ "optional": true
99
+ },
65
100
  "react": {
66
101
  "optional": true
67
102
  },
68
- "@angular/core": {
103
+ "rxjs": {
69
104
  "optional": true
70
105
  }
71
106
  }