@bantis/local-cipher 2.0.1 → 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,1414 @@
1
+ import { useState, useEffect, useCallback } from 'react';
2
+
3
+ /**
4
+ * Configuration types for @bantis/local-cipher
5
+ */
6
+ /**
7
+ * Default configuration values
8
+ */
9
+ const DEFAULT_CONFIG = {
10
+ encryption: {
11
+ iterations: 100000,
12
+ saltLength: 16,
13
+ ivLength: 12,
14
+ appIdentifier: 'bantis-local-cipher-v2',
15
+ keyLength: 256,
16
+ },
17
+ storage: {
18
+ compression: true,
19
+ compressionThreshold: 1024,
20
+ autoCleanup: true,
21
+ cleanupInterval: 60000,
22
+ },
23
+ debug: {
24
+ enabled: false,
25
+ logLevel: 'info',
26
+ prefix: 'SecureStorage',
27
+ },
28
+ };
29
+ /**
30
+ * Current library version
31
+ */
32
+ const LIBRARY_VERSION = '2.0.0';
33
+ /**
34
+ * Storage data version
35
+ */
36
+ const STORAGE_VERSION = 2;
37
+
38
+ /**
39
+ * EncryptionHelper - Clase responsable de todas las operaciones criptográficas
40
+ * Implementa AES-256-GCM con derivación de claves PBKDF2 y fingerprinting del navegador
41
+ */
42
+ class EncryptionHelper {
43
+ constructor(config) {
44
+ // Propiedades privadas
45
+ this.key = null;
46
+ this.baseKey = '';
47
+ this.baseKeyPromise = null;
48
+ this.keyVersion = 1;
49
+ this.config = { ...DEFAULT_CONFIG.encryption, ...config };
50
+ // Load key version from storage
51
+ const storedVersion = localStorage.getItem(EncryptionHelper.KEY_VERSION_KEY);
52
+ if (storedVersion) {
53
+ this.keyVersion = parseInt(storedVersion, 10);
54
+ }
55
+ }
56
+ /**
57
+ * Get current key version
58
+ */
59
+ getKeyVersion() {
60
+ return this.keyVersion;
61
+ }
62
+ /**
63
+ * Genera un fingerprint único del navegador
64
+ * Combina múltiples características del navegador para crear una huella digital
65
+ */
66
+ async generateBaseKey() {
67
+ if (this.baseKeyPromise) {
68
+ return this.baseKeyPromise;
69
+ }
70
+ this.baseKeyPromise = (async () => {
71
+ const components = [
72
+ navigator.userAgent,
73
+ navigator.language,
74
+ screen.width.toString(),
75
+ screen.height.toString(),
76
+ screen.colorDepth.toString(),
77
+ new Intl.DateTimeFormat().resolvedOptions().timeZone,
78
+ this.config.appIdentifier,
79
+ ];
80
+ const fingerprint = components.join('|');
81
+ this.baseKey = await this.hashString(fingerprint);
82
+ return this.baseKey;
83
+ })();
84
+ return this.baseKeyPromise;
85
+ }
86
+ /**
87
+ * Hashea un string usando SHA-256
88
+ * @param str - String a hashear
89
+ * @returns Hash hexadecimal
90
+ */
91
+ async hashString(str) {
92
+ const encoder = new TextEncoder();
93
+ const data = encoder.encode(str);
94
+ const hashBuffer = await crypto.subtle.digest(EncryptionHelper.HASH_ALGORITHM, data);
95
+ return this.arrayBufferToHex(hashBuffer);
96
+ }
97
+ /**
98
+ * Deriva una clave criptográfica usando PBKDF2
99
+ * @param password - Password base (fingerprint)
100
+ * @param salt - Salt aleatorio
101
+ * @returns CryptoKey para AES-GCM
102
+ */
103
+ async deriveKey(password, salt) {
104
+ const encoder = new TextEncoder();
105
+ const passwordBuffer = encoder.encode(password);
106
+ // Importar el password como material de clave
107
+ const keyMaterial = await crypto.subtle.importKey('raw', passwordBuffer, 'PBKDF2', false, ['deriveBits', 'deriveKey']);
108
+ // Derivar la clave AES-GCM
109
+ return crypto.subtle.deriveKey({
110
+ name: 'PBKDF2',
111
+ salt,
112
+ iterations: this.config.iterations,
113
+ hash: EncryptionHelper.HASH_ALGORITHM,
114
+ }, keyMaterial, {
115
+ name: EncryptionHelper.ALGORITHM,
116
+ length: this.config.keyLength,
117
+ }, false, ['encrypt', 'decrypt']);
118
+ }
119
+ /**
120
+ * Inicializa el sistema de encriptación generando un nuevo salt
121
+ */
122
+ async initialize() {
123
+ // Generar salt aleatorio
124
+ const salt = crypto.getRandomValues(new Uint8Array(this.config.saltLength));
125
+ // Obtener y hashear el baseKey
126
+ const baseKey = await this.generateBaseKey();
127
+ // Derivar la clave
128
+ this.key = await this.deriveKey(baseKey, salt);
129
+ // Increment key version
130
+ this.keyVersion++;
131
+ localStorage.setItem(EncryptionHelper.KEY_VERSION_KEY, this.keyVersion.toString());
132
+ // Guardar el salt en localStorage
133
+ localStorage.setItem(EncryptionHelper.SALT_STORAGE_KEY, this.arrayBufferToBase64(salt.buffer));
134
+ }
135
+ /**
136
+ * Inicializa desde un salt almacenado previamente
137
+ */
138
+ async initializeFromStored() {
139
+ const storedSalt = localStorage.getItem(EncryptionHelper.SALT_STORAGE_KEY);
140
+ if (!storedSalt) {
141
+ // Si no hay salt almacenado, inicializar uno nuevo
142
+ await this.initialize();
143
+ return;
144
+ }
145
+ // Recuperar el salt
146
+ const salt = new Uint8Array(this.base64ToArrayBuffer(storedSalt));
147
+ // Obtener el baseKey
148
+ const baseKey = await this.generateBaseKey();
149
+ // Derivar la misma clave
150
+ this.key = await this.deriveKey(baseKey, salt);
151
+ }
152
+ /**
153
+ * Encripta un texto plano usando AES-256-GCM
154
+ * @param plaintext - Texto a encriptar
155
+ * @returns Texto encriptado en Base64 (IV + datos encriptados)
156
+ */
157
+ async encrypt(plaintext) {
158
+ if (!this.key) {
159
+ await this.initializeFromStored();
160
+ }
161
+ if (!this.key) {
162
+ throw new Error('No se pudo inicializar la clave de encriptación');
163
+ }
164
+ // Convertir texto a bytes
165
+ const encoder = new TextEncoder();
166
+ const data = encoder.encode(plaintext);
167
+ // Generar IV aleatorio
168
+ const iv = crypto.getRandomValues(new Uint8Array(this.config.ivLength));
169
+ // Encriptar
170
+ const encryptedBuffer = await crypto.subtle.encrypt({
171
+ name: EncryptionHelper.ALGORITHM,
172
+ iv,
173
+ }, this.key, data);
174
+ // Combinar IV + datos encriptados
175
+ const combined = new Uint8Array(iv.length + encryptedBuffer.byteLength);
176
+ combined.set(iv, 0);
177
+ combined.set(new Uint8Array(encryptedBuffer), iv.length);
178
+ // Retornar en Base64
179
+ return this.arrayBufferToBase64(combined.buffer);
180
+ }
181
+ /**
182
+ * Desencripta un texto encriptado
183
+ * @param ciphertext - Texto encriptado en Base64
184
+ * @returns Texto plano
185
+ */
186
+ async decrypt(ciphertext) {
187
+ if (!this.key) {
188
+ await this.initializeFromStored();
189
+ }
190
+ if (!this.key) {
191
+ throw new Error('No se pudo inicializar la clave de encriptación');
192
+ }
193
+ try {
194
+ // Decodificar de Base64
195
+ const combined = new Uint8Array(this.base64ToArrayBuffer(ciphertext));
196
+ // Extraer IV y datos encriptados
197
+ const iv = combined.slice(0, this.config.ivLength);
198
+ const encryptedData = combined.slice(this.config.ivLength);
199
+ // Desencriptar
200
+ const decryptedBuffer = await crypto.subtle.decrypt({
201
+ name: EncryptionHelper.ALGORITHM,
202
+ iv,
203
+ }, this.key, encryptedData);
204
+ // Convertir bytes a texto
205
+ const decoder = new TextDecoder();
206
+ return decoder.decode(decryptedBuffer);
207
+ }
208
+ catch (error) {
209
+ throw new Error(`Error al desencriptar: ${error instanceof Error ? error.message : 'Error desconocido'}`);
210
+ }
211
+ }
212
+ /**
213
+ * Encripta el nombre de una clave para ofuscar nombres en localStorage
214
+ * @param keyName - Nombre original de la clave
215
+ * @returns Nombre encriptado con prefijo __enc_
216
+ */
217
+ async encryptKey(keyName) {
218
+ const baseKey = await this.generateBaseKey();
219
+ const combined = keyName + baseKey;
220
+ const hash = await this.hashString(combined);
221
+ return `__enc_${hash.substring(0, 16)}`;
222
+ }
223
+ /**
224
+ * Limpia todos los datos encriptados del localStorage
225
+ */
226
+ clearEncryptedData() {
227
+ const keysToRemove = [];
228
+ // Identificar todas las claves encriptadas
229
+ for (let i = 0; i < localStorage.length; i++) {
230
+ const key = localStorage.key(i);
231
+ if (key && key.startsWith('__enc_')) {
232
+ keysToRemove.push(key);
233
+ }
234
+ }
235
+ // Eliminar claves encriptadas
236
+ keysToRemove.forEach(key => localStorage.removeItem(key));
237
+ // Eliminar salt
238
+ localStorage.removeItem(EncryptionHelper.SALT_STORAGE_KEY);
239
+ // Resetear clave en memoria
240
+ this.key = null;
241
+ this.baseKey = '';
242
+ this.baseKeyPromise = null;
243
+ }
244
+ /**
245
+ * Verifica si el navegador soporta Web Crypto API
246
+ */
247
+ static isSupported() {
248
+ return !!(typeof crypto !== 'undefined' &&
249
+ crypto.subtle &&
250
+ crypto.getRandomValues);
251
+ }
252
+ // Métodos auxiliares para conversión de datos
253
+ arrayBufferToBase64(buffer) {
254
+ const bytes = new Uint8Array(buffer);
255
+ let binary = '';
256
+ for (let i = 0; i < bytes.length; i++) {
257
+ binary += String.fromCharCode(bytes[i]);
258
+ }
259
+ return btoa(binary);
260
+ }
261
+ base64ToArrayBuffer(base64) {
262
+ const binary = atob(base64);
263
+ const bytes = new Uint8Array(binary.length);
264
+ for (let i = 0; i < binary.length; i++) {
265
+ bytes[i] = binary.charCodeAt(i);
266
+ }
267
+ return bytes.buffer;
268
+ }
269
+ arrayBufferToHex(buffer) {
270
+ const bytes = new Uint8Array(buffer);
271
+ return Array.from(bytes)
272
+ .map(b => b.toString(16).padStart(2, '0'))
273
+ .join('');
274
+ }
275
+ }
276
+ // Constantes criptográficas (ahora configurables)
277
+ EncryptionHelper.ALGORITHM = 'AES-GCM';
278
+ EncryptionHelper.HASH_ALGORITHM = 'SHA-256';
279
+ EncryptionHelper.SALT_STORAGE_KEY = '__app_salt';
280
+ EncryptionHelper.KEY_VERSION_KEY = '__key_version';
281
+
282
+ /**
283
+ * Simple event emitter for storage events
284
+ */
285
+ class EventEmitter {
286
+ constructor() {
287
+ this.listeners = new Map();
288
+ this.onceListeners = new Map();
289
+ }
290
+ /**
291
+ * Register an event listener
292
+ */
293
+ on(event, listener) {
294
+ if (!this.listeners.has(event)) {
295
+ this.listeners.set(event, new Set());
296
+ }
297
+ this.listeners.get(event).add(listener);
298
+ }
299
+ /**
300
+ * Register a one-time event listener
301
+ */
302
+ once(event, listener) {
303
+ if (!this.onceListeners.has(event)) {
304
+ this.onceListeners.set(event, new Set());
305
+ }
306
+ this.onceListeners.get(event).add(listener);
307
+ }
308
+ /**
309
+ * Remove an event listener
310
+ */
311
+ off(event, listener) {
312
+ this.listeners.get(event)?.delete(listener);
313
+ this.onceListeners.get(event)?.delete(listener);
314
+ }
315
+ /**
316
+ * Remove all listeners for an event
317
+ */
318
+ removeAllListeners(event) {
319
+ if (event) {
320
+ this.listeners.delete(event);
321
+ this.onceListeners.delete(event);
322
+ }
323
+ else {
324
+ this.listeners.clear();
325
+ this.onceListeners.clear();
326
+ }
327
+ }
328
+ /**
329
+ * Emit an event
330
+ */
331
+ emit(event, data) {
332
+ const eventData = {
333
+ type: event,
334
+ timestamp: Date.now(),
335
+ ...data,
336
+ };
337
+ // Call regular listeners
338
+ this.listeners.get(event)?.forEach(listener => {
339
+ try {
340
+ listener(eventData);
341
+ }
342
+ catch (error) {
343
+ console.error(`Error in event listener for ${event}:`, error);
344
+ }
345
+ });
346
+ // Call and remove once listeners
347
+ const onceSet = this.onceListeners.get(event);
348
+ if (onceSet) {
349
+ onceSet.forEach(listener => {
350
+ try {
351
+ listener(eventData);
352
+ }
353
+ catch (error) {
354
+ console.error(`Error in once listener for ${event}:`, error);
355
+ }
356
+ });
357
+ this.onceListeners.delete(event);
358
+ }
359
+ }
360
+ /**
361
+ * Get listener count for an event
362
+ */
363
+ listenerCount(event) {
364
+ const regularCount = this.listeners.get(event)?.size ?? 0;
365
+ const onceCount = this.onceListeners.get(event)?.size ?? 0;
366
+ return regularCount + onceCount;
367
+ }
368
+ /**
369
+ * Get all event types with listeners
370
+ */
371
+ eventNames() {
372
+ const events = new Set();
373
+ this.listeners.forEach((_, event) => events.add(event));
374
+ this.onceListeners.forEach((_, event) => events.add(event));
375
+ return Array.from(events);
376
+ }
377
+ }
378
+
379
+ /**
380
+ * Logger utility for debug mode
381
+ */
382
+ class Logger {
383
+ constructor(config = {}) {
384
+ this.enabled = config.enabled ?? false;
385
+ this.logLevel = config.logLevel ?? 'info';
386
+ this.prefix = config.prefix ?? 'SecureStorage';
387
+ }
388
+ shouldLog(level) {
389
+ if (!this.enabled)
390
+ return false;
391
+ return Logger.LOG_LEVELS[level] <= Logger.LOG_LEVELS[this.logLevel];
392
+ }
393
+ formatMessage(level, message, ...args) {
394
+ const timestamp = new Date().toISOString();
395
+ return `[${this.prefix}] [${level.toUpperCase()}] ${timestamp} - ${message}`;
396
+ }
397
+ error(message, ...args) {
398
+ if (this.shouldLog('error')) {
399
+ console.error(this.formatMessage('error', message), ...args);
400
+ }
401
+ }
402
+ warn(message, ...args) {
403
+ if (this.shouldLog('warn')) {
404
+ console.warn(this.formatMessage('warn', message), ...args);
405
+ }
406
+ }
407
+ info(message, ...args) {
408
+ if (this.shouldLog('info')) {
409
+ console.info(this.formatMessage('info', message), ...args);
410
+ }
411
+ }
412
+ debug(message, ...args) {
413
+ if (this.shouldLog('debug')) {
414
+ console.debug(this.formatMessage('debug', message), ...args);
415
+ }
416
+ }
417
+ verbose(message, ...args) {
418
+ if (this.shouldLog('verbose')) {
419
+ console.log(this.formatMessage('verbose', message), ...args);
420
+ }
421
+ }
422
+ time(label) {
423
+ if (this.enabled && this.shouldLog('debug')) {
424
+ console.time(`[${this.prefix}] ${label}`);
425
+ }
426
+ }
427
+ timeEnd(label) {
428
+ if (this.enabled && this.shouldLog('debug')) {
429
+ console.timeEnd(`[${this.prefix}] ${label}`);
430
+ }
431
+ }
432
+ group(label) {
433
+ if (this.enabled && this.shouldLog('debug')) {
434
+ console.group(`[${this.prefix}] ${label}`);
435
+ }
436
+ }
437
+ groupEnd() {
438
+ if (this.enabled && this.shouldLog('debug')) {
439
+ console.groupEnd();
440
+ }
441
+ }
442
+ }
443
+ Logger.LOG_LEVELS = {
444
+ silent: 0,
445
+ error: 1,
446
+ warn: 2,
447
+ info: 3,
448
+ debug: 4,
449
+ verbose: 5,
450
+ };
451
+
452
+ /**
453
+ * Key rotation utilities
454
+ */
455
+ class KeyRotation {
456
+ constructor(encryptionHelper, logger) {
457
+ this.encryptionHelper = encryptionHelper;
458
+ this.logger = logger ?? new Logger();
459
+ }
460
+ /**
461
+ * Rotate all encryption keys
462
+ * Re-encrypts all data with a new salt
463
+ */
464
+ async rotateKeys() {
465
+ this.logger.info('Starting key rotation...');
466
+ // 1. Export all current data
467
+ const backup = await this.exportEncryptedData();
468
+ // 2. Clear old encryption
469
+ this.encryptionHelper.clearEncryptedData();
470
+ // 3. Initialize new encryption
471
+ await this.encryptionHelper.initialize();
472
+ // 4. Re-encrypt all data
473
+ for (const [key, value] of Object.entries(backup.data)) {
474
+ const encryptedKey = await this.encryptionHelper.encryptKey(key);
475
+ const encryptedValue = await this.encryptionHelper.encrypt(value);
476
+ localStorage.setItem(encryptedKey, encryptedValue);
477
+ }
478
+ this.logger.info(`Key rotation completed. Re-encrypted ${backup.metadata.itemCount} items`);
479
+ }
480
+ /**
481
+ * Export all encrypted data as backup
482
+ */
483
+ async exportEncryptedData() {
484
+ this.logger.info('Exporting encrypted data...');
485
+ const data = {};
486
+ let itemCount = 0;
487
+ for (let i = 0; i < localStorage.length; i++) {
488
+ const encryptedKey = localStorage.key(i);
489
+ if (encryptedKey && encryptedKey.startsWith('__enc_')) {
490
+ const encryptedValue = localStorage.getItem(encryptedKey);
491
+ if (encryptedValue) {
492
+ try {
493
+ // Decrypt to get original key and value
494
+ const decryptedValue = await this.encryptionHelper.decrypt(encryptedValue);
495
+ // Store with encrypted key as identifier
496
+ data[encryptedKey] = decryptedValue;
497
+ itemCount++;
498
+ }
499
+ catch (error) {
500
+ this.logger.warn(`Failed to decrypt key ${encryptedKey}:`, error);
501
+ }
502
+ }
503
+ }
504
+ }
505
+ const backup = {
506
+ version: '2.0.0',
507
+ timestamp: Date.now(),
508
+ data,
509
+ metadata: {
510
+ keyVersion: this.encryptionHelper.getKeyVersion(),
511
+ algorithm: 'AES-256-GCM',
512
+ itemCount,
513
+ },
514
+ };
515
+ this.logger.info(`Exported ${itemCount} items`);
516
+ return backup;
517
+ }
518
+ /**
519
+ * Import encrypted data from backup
520
+ */
521
+ async importEncryptedData(backup) {
522
+ this.logger.info(`Importing backup from ${new Date(backup.timestamp).toISOString()}...`);
523
+ let imported = 0;
524
+ for (const [encryptedKey, value] of Object.entries(backup.data)) {
525
+ try {
526
+ const encryptedValue = await this.encryptionHelper.encrypt(value);
527
+ localStorage.setItem(encryptedKey, encryptedValue);
528
+ imported++;
529
+ }
530
+ catch (error) {
531
+ this.logger.error(`Failed to import key ${encryptedKey}:`, error);
532
+ }
533
+ }
534
+ this.logger.info(`Imported ${imported}/${backup.metadata.itemCount} items`);
535
+ }
536
+ }
537
+
538
+ /**
539
+ * Namespaced storage for organizing data
540
+ */
541
+ class NamespacedStorage {
542
+ constructor(storage, namespace) {
543
+ this.storage = storage;
544
+ this.prefix = `__ns_${namespace}__`;
545
+ }
546
+ /**
547
+ * Set item in this namespace
548
+ */
549
+ async setItem(key, value) {
550
+ return this.storage.setItem(`${this.prefix}${key}`, value);
551
+ }
552
+ /**
553
+ * Set item with expiry in this namespace
554
+ */
555
+ async setItemWithExpiry(key, value, options) {
556
+ return this.storage.setItemWithExpiry(`${this.prefix}${key}`, value, options);
557
+ }
558
+ /**
559
+ * Get item from this namespace
560
+ */
561
+ async getItem(key) {
562
+ return this.storage.getItem(`${this.prefix}${key}`);
563
+ }
564
+ /**
565
+ * Remove item from this namespace
566
+ */
567
+ async removeItem(key) {
568
+ return this.storage.removeItem(`${this.prefix}${key}`);
569
+ }
570
+ /**
571
+ * Check if item exists in this namespace
572
+ */
573
+ async hasItem(key) {
574
+ return this.storage.hasItem(`${this.prefix}${key}`);
575
+ }
576
+ /**
577
+ * Clear all items in this namespace
578
+ */
579
+ async clearNamespace() {
580
+ const keysToRemove = [];
581
+ for (let i = 0; i < localStorage.length; i++) {
582
+ const key = localStorage.key(i);
583
+ if (key && key.includes(this.prefix)) {
584
+ keysToRemove.push(key.replace(this.prefix, ''));
585
+ }
586
+ }
587
+ for (const key of keysToRemove) {
588
+ await this.removeItem(key);
589
+ }
590
+ }
591
+ /**
592
+ * Get all keys in this namespace
593
+ */
594
+ async keys() {
595
+ const keys = [];
596
+ for (let i = 0; i < localStorage.length; i++) {
597
+ const key = localStorage.key(i);
598
+ if (key && key.includes(this.prefix)) {
599
+ keys.push(key.replace(this.prefix, ''));
600
+ }
601
+ }
602
+ return keys;
603
+ }
604
+ }
605
+
606
+ /**
607
+ * Compression utilities using CompressionStream API
608
+ */
609
+ /**
610
+ * Check if compression is supported
611
+ */
612
+ function isCompressionSupported() {
613
+ return typeof CompressionStream !== 'undefined' && typeof DecompressionStream !== 'undefined';
614
+ }
615
+ /**
616
+ * Compress a string using gzip
617
+ */
618
+ async function compress(data) {
619
+ if (!isCompressionSupported()) {
620
+ // Fallback: return uncompressed data with marker
621
+ const encoder = new TextEncoder();
622
+ return encoder.encode(data);
623
+ }
624
+ try {
625
+ const encoder = new TextEncoder();
626
+ const stream = new Blob([data]).stream();
627
+ const compressedStream = stream.pipeThrough(new CompressionStream('gzip'));
628
+ const compressedBlob = await new Response(compressedStream).blob();
629
+ const buffer = await compressedBlob.arrayBuffer();
630
+ return new Uint8Array(buffer);
631
+ }
632
+ catch (error) {
633
+ console.warn('Compression failed, returning uncompressed data:', error);
634
+ const encoder = new TextEncoder();
635
+ return encoder.encode(data);
636
+ }
637
+ }
638
+ /**
639
+ * Decompress gzip data to string
640
+ */
641
+ async function decompress(data) {
642
+ if (!isCompressionSupported()) {
643
+ // Fallback: assume uncompressed
644
+ const decoder = new TextDecoder();
645
+ return decoder.decode(data);
646
+ }
647
+ try {
648
+ const stream = new Blob([data]).stream();
649
+ const decompressedStream = stream.pipeThrough(new DecompressionStream('gzip'));
650
+ const decompressedBlob = await new Response(decompressedStream).blob();
651
+ return await decompressedBlob.text();
652
+ }
653
+ catch (error) {
654
+ // If decompression fails, try to decode as plain text
655
+ console.warn('Decompression failed, trying plain text:', error);
656
+ const decoder = new TextDecoder();
657
+ return decoder.decode(data);
658
+ }
659
+ }
660
+ /**
661
+ * Check if data should be compressed based on size
662
+ */
663
+ function shouldCompress(data, threshold = 1024) {
664
+ return data.length >= threshold;
665
+ }
666
+
667
+ /**
668
+ * SecureStorage v2 - API de alto nivel que imita localStorage con cifrado automático
669
+ * Incluye: configuración personalizable, eventos, compresión, expiración, namespaces, rotación de claves
670
+ */
671
+ class SecureStorage {
672
+ constructor(config) {
673
+ this.cleanupInterval = null;
674
+ // Merge config with defaults
675
+ this.config = {
676
+ encryption: { ...DEFAULT_CONFIG.encryption, ...config?.encryption },
677
+ storage: { ...DEFAULT_CONFIG.storage, ...config?.storage },
678
+ debug: { ...DEFAULT_CONFIG.debug, ...config?.debug },
679
+ };
680
+ // Initialize components
681
+ this.logger = new Logger(this.config.debug);
682
+ this.encryptionHelper = new EncryptionHelper(this.config.encryption);
683
+ this.eventEmitter = new EventEmitter();
684
+ this.keyRotation = new KeyRotation(this.encryptionHelper, this.logger);
685
+ this.logger.info('SecureStorage v2 initialized', this.config);
686
+ // Setup auto-cleanup if enabled
687
+ if (this.config.storage.autoCleanup) {
688
+ this.setupAutoCleanup();
689
+ }
690
+ }
691
+ /**
692
+ * Obtiene la instancia singleton de SecureStorage
693
+ */
694
+ static getInstance(config) {
695
+ if (!SecureStorage.instance) {
696
+ SecureStorage.instance = new SecureStorage(config);
697
+ }
698
+ return SecureStorage.instance;
699
+ }
700
+ /**
701
+ * Setup automatic cleanup of expired items
702
+ */
703
+ setupAutoCleanup() {
704
+ if (this.cleanupInterval) {
705
+ clearInterval(this.cleanupInterval);
706
+ }
707
+ this.cleanupInterval = setInterval(() => {
708
+ this.cleanExpired().catch(err => {
709
+ this.logger.error('Auto-cleanup failed:', err);
710
+ });
711
+ }, this.config.storage.cleanupInterval);
712
+ this.logger.debug(`Auto-cleanup enabled with interval: ${this.config.storage.cleanupInterval}ms`);
713
+ }
714
+ /**
715
+ * Guarda un valor encriptado en localStorage
716
+ */
717
+ async setItem(key, value) {
718
+ this.logger.time(`setItem:${key}`);
719
+ if (!EncryptionHelper.isSupported()) {
720
+ this.logger.warn('Web Crypto API no soportada, usando localStorage sin encriptar');
721
+ localStorage.setItem(key, value);
722
+ return;
723
+ }
724
+ try {
725
+ // Check if compression should be applied
726
+ const shouldCompressData = this.config.storage.compression &&
727
+ shouldCompress(value, this.config.storage.compressionThreshold);
728
+ let processedValue = value;
729
+ let compressed = false;
730
+ if (shouldCompressData) {
731
+ this.logger.debug(`Compressing value for key: ${key}`);
732
+ const compressedData = await compress(value);
733
+ processedValue = this.encryptionHelper['arrayBufferToBase64'](compressedData.buffer);
734
+ compressed = true;
735
+ this.eventEmitter.emit('compressed', { key });
736
+ }
737
+ // Create StoredValue wrapper
738
+ const now = Date.now();
739
+ const storedValue = {
740
+ value: processedValue,
741
+ createdAt: now,
742
+ modifiedAt: now,
743
+ version: STORAGE_VERSION,
744
+ compressed,
745
+ };
746
+ // Calculate checksum for integrity
747
+ const checksum = await this.calculateChecksum(processedValue);
748
+ storedValue.checksum = checksum;
749
+ // Serialize StoredValue
750
+ const serialized = JSON.stringify(storedValue);
751
+ // Encrypt the key
752
+ const encryptedKey = await this.encryptionHelper.encryptKey(key);
753
+ // Encrypt the value
754
+ const encryptedValue = await this.encryptionHelper.encrypt(serialized);
755
+ // Store in localStorage
756
+ localStorage.setItem(encryptedKey, encryptedValue);
757
+ this.logger.verbose(`Stored key: ${key}, compressed: ${compressed}, size: ${encryptedValue.length}`);
758
+ this.eventEmitter.emit('encrypted', { key, metadata: { compressed, size: encryptedValue.length } });
759
+ this.logger.timeEnd(`setItem:${key}`);
760
+ }
761
+ catch (error) {
762
+ this.logger.error(`Error al guardar dato encriptado para ${key}:`, error);
763
+ this.eventEmitter.emit('error', { key, error: error });
764
+ localStorage.setItem(key, value);
765
+ }
766
+ }
767
+ /**
768
+ * Guarda un valor con tiempo de expiración
769
+ */
770
+ async setItemWithExpiry(key, value, options) {
771
+ this.logger.time(`setItemWithExpiry:${key}`);
772
+ if (!EncryptionHelper.isSupported()) {
773
+ this.logger.warn('Web Crypto API no soportada, usando localStorage sin encriptar');
774
+ localStorage.setItem(key, value);
775
+ return;
776
+ }
777
+ try {
778
+ // Check if compression should be applied
779
+ const shouldCompressData = this.config.storage.compression &&
780
+ shouldCompress(value, this.config.storage.compressionThreshold);
781
+ let processedValue = value;
782
+ let compressed = false;
783
+ if (shouldCompressData) {
784
+ this.logger.debug(`Compressing value for key: ${key}`);
785
+ const compressedData = await compress(value);
786
+ processedValue = this.encryptionHelper['arrayBufferToBase64'](compressedData.buffer);
787
+ compressed = true;
788
+ this.eventEmitter.emit('compressed', { key });
789
+ }
790
+ // Calculate expiration timestamp
791
+ let expiresAt;
792
+ if (options.expiresIn) {
793
+ expiresAt = Date.now() + options.expiresIn;
794
+ }
795
+ else if (options.expiresAt) {
796
+ expiresAt = options.expiresAt.getTime();
797
+ }
798
+ // Create StoredValue wrapper
799
+ const now = Date.now();
800
+ const storedValue = {
801
+ value: processedValue,
802
+ createdAt: now,
803
+ modifiedAt: now,
804
+ version: STORAGE_VERSION,
805
+ compressed,
806
+ expiresAt,
807
+ };
808
+ // Calculate checksum for integrity
809
+ const checksum = await this.calculateChecksum(processedValue);
810
+ storedValue.checksum = checksum;
811
+ // Serialize StoredValue
812
+ const serialized = JSON.stringify(storedValue);
813
+ // Encrypt the key
814
+ const encryptedKey = await this.encryptionHelper.encryptKey(key);
815
+ // Encrypt the value
816
+ const encryptedValue = await this.encryptionHelper.encrypt(serialized);
817
+ // Store in localStorage
818
+ localStorage.setItem(encryptedKey, encryptedValue);
819
+ this.logger.verbose(`Stored key with expiry: ${key}, expiresAt: ${expiresAt}`);
820
+ this.eventEmitter.emit('encrypted', { key, metadata: { compressed, expiresAt } });
821
+ this.logger.timeEnd(`setItemWithExpiry:${key}`);
822
+ }
823
+ catch (error) {
824
+ this.logger.error(`Error al guardar dato con expiración para ${key}:`, error);
825
+ this.eventEmitter.emit('error', { key, error: error });
826
+ throw error;
827
+ }
828
+ }
829
+ /**
830
+ * Recupera y desencripta un valor de localStorage
831
+ */
832
+ async getItem(key) {
833
+ this.logger.time(`getItem:${key}`);
834
+ if (!EncryptionHelper.isSupported()) {
835
+ return localStorage.getItem(key);
836
+ }
837
+ try {
838
+ // Encrypt the key
839
+ const encryptedKey = await this.encryptionHelper.encryptKey(key);
840
+ // Get encrypted value
841
+ let encryptedValue = localStorage.getItem(encryptedKey);
842
+ // Backward compatibility: try with plain key
843
+ if (!encryptedValue) {
844
+ encryptedValue = localStorage.getItem(key);
845
+ if (!encryptedValue) {
846
+ this.logger.timeEnd(`getItem:${key}`);
847
+ return null;
848
+ }
849
+ }
850
+ // Decrypt the value
851
+ const decrypted = await this.encryptionHelper.decrypt(encryptedValue);
852
+ // Try to parse as StoredValue (v2 format)
853
+ let storedValue;
854
+ try {
855
+ storedValue = JSON.parse(decrypted);
856
+ // Validate it's a StoredValue object
857
+ if (!storedValue.value || !storedValue.version) {
858
+ // It's v1 format (plain string), auto-migrate
859
+ this.logger.info(`Auto-migrating v1 data for key: ${key}`);
860
+ await this.setItem(key, decrypted);
861
+ this.logger.timeEnd(`getItem:${key}`);
862
+ return decrypted;
863
+ }
864
+ }
865
+ catch {
866
+ // Not JSON, it's v1 format (plain string), auto-migrate
867
+ this.logger.info(`Auto-migrating v1 data for key: ${key}`);
868
+ await this.setItem(key, decrypted);
869
+ this.logger.timeEnd(`getItem:${key}`);
870
+ return decrypted;
871
+ }
872
+ // Check expiration
873
+ if (storedValue.expiresAt && storedValue.expiresAt < Date.now()) {
874
+ this.logger.info(`Key expired: ${key}`);
875
+ await this.removeItem(key);
876
+ this.eventEmitter.emit('expired', { key });
877
+ this.logger.timeEnd(`getItem:${key}`);
878
+ return null;
879
+ }
880
+ // Verify integrity if checksum exists
881
+ if (storedValue.checksum) {
882
+ const calculatedChecksum = await this.calculateChecksum(storedValue.value);
883
+ if (calculatedChecksum !== storedValue.checksum) {
884
+ this.logger.warn(`Integrity check failed for key: ${key}`);
885
+ this.eventEmitter.emit('error', {
886
+ key,
887
+ error: new Error('Integrity verification failed')
888
+ });
889
+ }
890
+ }
891
+ // Decompress if needed
892
+ let finalValue = storedValue.value;
893
+ if (storedValue.compressed) {
894
+ this.logger.debug(`Decompressing value for key: ${key}`);
895
+ const compressedData = this.encryptionHelper['base64ToArrayBuffer'](storedValue.value);
896
+ finalValue = await decompress(new Uint8Array(compressedData));
897
+ this.eventEmitter.emit('decompressed', { key });
898
+ }
899
+ this.eventEmitter.emit('decrypted', { key });
900
+ this.logger.timeEnd(`getItem:${key}`);
901
+ return finalValue;
902
+ }
903
+ catch (error) {
904
+ this.logger.error(`Error al recuperar dato encriptado para ${key}:`, error);
905
+ this.eventEmitter.emit('error', { key, error: error });
906
+ // Fallback: try plain key
907
+ const fallback = localStorage.getItem(key);
908
+ this.logger.timeEnd(`getItem:${key}`);
909
+ return fallback;
910
+ }
911
+ }
912
+ /**
913
+ * Elimina un valor de localStorage
914
+ */
915
+ async removeItem(key) {
916
+ if (!EncryptionHelper.isSupported()) {
917
+ localStorage.removeItem(key);
918
+ return;
919
+ }
920
+ try {
921
+ const encryptedKey = await this.encryptionHelper.encryptKey(key);
922
+ localStorage.removeItem(encryptedKey);
923
+ localStorage.removeItem(key); // Remove both versions
924
+ this.eventEmitter.emit('deleted', { key });
925
+ this.logger.info(`Removed key: ${key}`);
926
+ }
927
+ catch (error) {
928
+ this.logger.error(`Error al eliminar dato para ${key}:`, error);
929
+ localStorage.removeItem(key);
930
+ }
931
+ }
932
+ /**
933
+ * Verifica si existe un valor para la clave dada
934
+ */
935
+ async hasItem(key) {
936
+ const value = await this.getItem(key);
937
+ return value !== null;
938
+ }
939
+ /**
940
+ * Limpia todos los datos encriptados
941
+ */
942
+ clear() {
943
+ this.encryptionHelper.clearEncryptedData();
944
+ this.eventEmitter.emit('cleared', {});
945
+ this.logger.info('All encrypted data cleared');
946
+ }
947
+ /**
948
+ * Limpia todos los items expirados
949
+ */
950
+ async cleanExpired() {
951
+ this.logger.info('Starting cleanup of expired items...');
952
+ let cleanedCount = 0;
953
+ const keysToCheck = [];
954
+ for (let i = 0; i < localStorage.length; i++) {
955
+ const key = localStorage.key(i);
956
+ if (key && key.startsWith('__enc_')) {
957
+ keysToCheck.push(key);
958
+ }
959
+ }
960
+ for (const encryptedKey of keysToCheck) {
961
+ try {
962
+ const encryptedValue = localStorage.getItem(encryptedKey);
963
+ if (!encryptedValue)
964
+ continue;
965
+ const decrypted = await this.encryptionHelper.decrypt(encryptedValue);
966
+ const storedValue = JSON.parse(decrypted);
967
+ if (storedValue.expiresAt && storedValue.expiresAt < Date.now()) {
968
+ localStorage.removeItem(encryptedKey);
969
+ cleanedCount++;
970
+ this.eventEmitter.emit('expired', { key: encryptedKey });
971
+ }
972
+ }
973
+ catch (error) {
974
+ this.logger.warn(`Failed to check expiration for ${encryptedKey}:`, error);
975
+ }
976
+ }
977
+ this.logger.info(`Cleanup completed. Removed ${cleanedCount} expired items`);
978
+ return cleanedCount;
979
+ }
980
+ /**
981
+ * Verifica la integridad de un valor almacenado
982
+ */
983
+ async verifyIntegrity(key) {
984
+ try {
985
+ const encryptedKey = await this.encryptionHelper.encryptKey(key);
986
+ const encryptedValue = localStorage.getItem(encryptedKey);
987
+ if (!encryptedValue)
988
+ return false;
989
+ const decrypted = await this.encryptionHelper.decrypt(encryptedValue);
990
+ const storedValue = JSON.parse(decrypted);
991
+ if (!storedValue.checksum) {
992
+ this.logger.warn(`No checksum found for key: ${key}`);
993
+ return true; // No checksum to verify
994
+ }
995
+ const calculatedChecksum = await this.calculateChecksum(storedValue.value);
996
+ return calculatedChecksum === storedValue.checksum;
997
+ }
998
+ catch (error) {
999
+ this.logger.error(`Error verifying integrity for ${key}:`, error);
1000
+ return false;
1001
+ }
1002
+ }
1003
+ /**
1004
+ * Obtiene información de integridad de un valor
1005
+ */
1006
+ async getIntegrityInfo(key) {
1007
+ try {
1008
+ const encryptedKey = await this.encryptionHelper.encryptKey(key);
1009
+ const encryptedValue = localStorage.getItem(encryptedKey);
1010
+ if (!encryptedValue)
1011
+ return null;
1012
+ const decrypted = await this.encryptionHelper.decrypt(encryptedValue);
1013
+ const storedValue = JSON.parse(decrypted);
1014
+ const valid = storedValue.checksum
1015
+ ? await this.calculateChecksum(storedValue.value) === storedValue.checksum
1016
+ : true;
1017
+ return {
1018
+ valid,
1019
+ lastModified: storedValue.modifiedAt,
1020
+ checksum: storedValue.checksum || '',
1021
+ version: storedValue.version,
1022
+ };
1023
+ }
1024
+ catch (error) {
1025
+ this.logger.error(`Error getting integrity info for ${key}:`, error);
1026
+ return null;
1027
+ }
1028
+ }
1029
+ /**
1030
+ * Crea un namespace para organizar datos
1031
+ */
1032
+ namespace(name) {
1033
+ this.logger.debug(`Creating namespace: ${name}`);
1034
+ return new NamespacedStorage(this, name);
1035
+ }
1036
+ /**
1037
+ * Rota todas las claves de encriptación
1038
+ */
1039
+ async rotateKeys() {
1040
+ this.logger.info('Starting key rotation...');
1041
+ await this.keyRotation.rotateKeys();
1042
+ this.eventEmitter.emit('keyRotated', {});
1043
+ this.logger.info('Key rotation completed');
1044
+ }
1045
+ /**
1046
+ * Exporta todos los datos encriptados como backup
1047
+ */
1048
+ async exportEncryptedData() {
1049
+ return this.keyRotation.exportEncryptedData();
1050
+ }
1051
+ /**
1052
+ * Importa datos desde un backup
1053
+ */
1054
+ async importEncryptedData(backup) {
1055
+ return this.keyRotation.importEncryptedData(backup);
1056
+ }
1057
+ /**
1058
+ * Registra un listener de eventos
1059
+ */
1060
+ on(event, listener) {
1061
+ this.eventEmitter.on(event, listener);
1062
+ }
1063
+ /**
1064
+ * Registra un listener de un solo uso
1065
+ */
1066
+ once(event, listener) {
1067
+ this.eventEmitter.once(event, listener);
1068
+ }
1069
+ /**
1070
+ * Elimina un listener de eventos
1071
+ */
1072
+ off(event, listener) {
1073
+ this.eventEmitter.off(event, listener);
1074
+ }
1075
+ /**
1076
+ * Elimina todos los listeners de un evento
1077
+ */
1078
+ removeAllListeners(event) {
1079
+ this.eventEmitter.removeAllListeners(event);
1080
+ }
1081
+ /**
1082
+ * Migra datos existentes no encriptados a formato encriptado
1083
+ */
1084
+ async migrateExistingData(keys) {
1085
+ if (!EncryptionHelper.isSupported()) {
1086
+ this.logger.warn('Web Crypto API no soportada, no se puede migrar');
1087
+ return;
1088
+ }
1089
+ this.logger.info(`Iniciando migración de ${keys.length} claves...`);
1090
+ for (const key of keys) {
1091
+ try {
1092
+ const value = localStorage.getItem(key);
1093
+ if (value === null)
1094
+ continue;
1095
+ // Try to decrypt to check if already encrypted
1096
+ try {
1097
+ await this.encryptionHelper.decrypt(value);
1098
+ this.logger.info(`✓ ${key} ya está encriptado, saltando`);
1099
+ continue;
1100
+ }
1101
+ catch {
1102
+ // Not encrypted, proceed with migration
1103
+ }
1104
+ await this.setItem(key, value);
1105
+ localStorage.removeItem(key);
1106
+ this.logger.info(`✓ ${key} migrado exitosamente`);
1107
+ }
1108
+ catch (error) {
1109
+ this.logger.error(`✗ Error al migrar ${key}:`, error);
1110
+ }
1111
+ }
1112
+ this.logger.info('✅ Migración completada');
1113
+ }
1114
+ /**
1115
+ * Obtiene información de debug sobre el estado del almacenamiento
1116
+ */
1117
+ getDebugInfo() {
1118
+ const allKeys = [];
1119
+ for (let i = 0; i < localStorage.length; i++) {
1120
+ const key = localStorage.key(i);
1121
+ if (key)
1122
+ allKeys.push(key);
1123
+ }
1124
+ const encryptedKeys = allKeys.filter(key => key.startsWith('__enc_'));
1125
+ const unencryptedKeys = allKeys.filter(key => !key.startsWith('__enc_') && key !== '__app_salt' && key !== '__key_version');
1126
+ return {
1127
+ cryptoSupported: EncryptionHelper.isSupported(),
1128
+ encryptedKeys,
1129
+ unencryptedKeys,
1130
+ totalKeys: allKeys.length,
1131
+ config: this.config,
1132
+ };
1133
+ }
1134
+ /**
1135
+ * Calcula el checksum SHA-256 de un valor
1136
+ */
1137
+ async calculateChecksum(value) {
1138
+ const encoder = new TextEncoder();
1139
+ const data = encoder.encode(value);
1140
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
1141
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
1142
+ return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
1143
+ }
1144
+ /**
1145
+ * Cleanup on destroy
1146
+ */
1147
+ destroy() {
1148
+ if (this.cleanupInterval) {
1149
+ clearInterval(this.cleanupInterval);
1150
+ this.cleanupInterval = null;
1151
+ }
1152
+ this.removeAllListeners();
1153
+ this.logger.info('SecureStorage destroyed');
1154
+ }
1155
+ }
1156
+ SecureStorage.instance = null;
1157
+
1158
+ const secureStorage$2 = SecureStorage.getInstance();
1159
+ /**
1160
+ * Función de debug para verificar el estado del sistema de encriptación
1161
+ * Muestra información detallada en la consola
1162
+ */
1163
+ async function debugEncryptionState() {
1164
+ console.group('🔐 Estado del Sistema de Encriptación');
1165
+ console.log('Soporte Crypto API:', EncryptionHelper.isSupported());
1166
+ // Obtener información de debug
1167
+ const debugInfo = secureStorage$2.getDebugInfo();
1168
+ console.log('Claves encriptadas:', debugInfo.encryptedKeys.length);
1169
+ console.log('Claves sin encriptar:', debugInfo.unencryptedKeys);
1170
+ console.log('Total de claves:', debugInfo.totalKeys);
1171
+ if (debugInfo.encryptedKeys.length > 0) {
1172
+ console.log('✅ Datos encriptados encontrados:');
1173
+ debugInfo.encryptedKeys.forEach(key => {
1174
+ const value = localStorage.getItem(key);
1175
+ console.log(` ${key}: ${value?.substring(0, 30)}...`);
1176
+ });
1177
+ }
1178
+ else {
1179
+ console.log('⚠️ No se encontraron datos encriptados');
1180
+ }
1181
+ if (debugInfo.unencryptedKeys.length > 0) {
1182
+ console.log('⚠️ Claves sin encriptar encontradas:');
1183
+ debugInfo.unencryptedKeys.forEach(key => {
1184
+ console.log(` ${key}`);
1185
+ });
1186
+ }
1187
+ console.groupEnd();
1188
+ }
1189
+ /**
1190
+ * Fuerza la migración de claves comunes a formato encriptado
1191
+ * Útil para desarrollo y testing
1192
+ */
1193
+ async function forceMigration(customKeys) {
1194
+ const defaultKeys = [
1195
+ 'accessToken',
1196
+ 'refreshToken',
1197
+ 'user',
1198
+ 'sessionId',
1199
+ 'authToken',
1200
+ 'userData',
1201
+ ];
1202
+ const keysToMigrate = customKeys || defaultKeys;
1203
+ console.log(`🔄 Iniciando migración forzada de ${keysToMigrate.length} claves...`);
1204
+ await secureStorage$2.migrateExistingData(keysToMigrate);
1205
+ console.log('✅ Migración forzada completada');
1206
+ // Mostrar estado después de la migración
1207
+ await debugEncryptionState();
1208
+ }
1209
+
1210
+ /**
1211
+ * @bantis/local-cipher - Core Module
1212
+ * Framework-agnostic client-side encryption for browser storage
1213
+ *
1214
+ * @version 2.1.0
1215
+ * @license MIT
1216
+ */
1217
+ // Core classes
1218
+ const secureStorage$1 = SecureStorage.getInstance();
1219
+ // Version
1220
+ const VERSION = '2.1.0';
1221
+
1222
+ /**
1223
+ * React Hooks for @bantis/local-cipher
1224
+ * Provides reactive hooks for encrypted browser storage
1225
+ */
1226
+ // Allow custom storage instance or use default
1227
+ let defaultStorage = null;
1228
+ function getDefaultStorage() {
1229
+ if (!defaultStorage) {
1230
+ defaultStorage = SecureStorage.getInstance();
1231
+ }
1232
+ return defaultStorage;
1233
+ }
1234
+ /**
1235
+ * Initialize SecureStorage with custom configuration
1236
+ */
1237
+ function initializeSecureStorage(config) {
1238
+ defaultStorage = SecureStorage.getInstance(config);
1239
+ return defaultStorage;
1240
+ }
1241
+ /**
1242
+ * Hook de React para usar SecureStorage de forma reactiva
1243
+ * Similar a useState pero con persistencia encriptada
1244
+ */
1245
+ function useSecureStorage(key, initialValue, storage) {
1246
+ const secureStorage = storage || getDefaultStorage();
1247
+ const [storedValue, setStoredValue] = useState(initialValue);
1248
+ const [loading, setLoading] = useState(true);
1249
+ const [error, setError] = useState(null);
1250
+ useEffect(() => {
1251
+ const loadValue = async () => {
1252
+ try {
1253
+ setLoading(true);
1254
+ setError(null);
1255
+ const item = await secureStorage.getItem(key);
1256
+ if (item !== null) {
1257
+ if (typeof initialValue === 'object') {
1258
+ setStoredValue(JSON.parse(item));
1259
+ }
1260
+ else {
1261
+ setStoredValue(item);
1262
+ }
1263
+ }
1264
+ else {
1265
+ setStoredValue(initialValue);
1266
+ }
1267
+ }
1268
+ catch (err) {
1269
+ setError(err instanceof Error ? err : new Error('Error al cargar valor'));
1270
+ setStoredValue(initialValue);
1271
+ }
1272
+ finally {
1273
+ setLoading(false);
1274
+ }
1275
+ };
1276
+ loadValue();
1277
+ }, [key]);
1278
+ const setValue = useCallback(async (value) => {
1279
+ try {
1280
+ setError(null);
1281
+ setStoredValue(value);
1282
+ const valueToStore = typeof value === 'object'
1283
+ ? JSON.stringify(value)
1284
+ : String(value);
1285
+ await secureStorage.setItem(key, valueToStore);
1286
+ }
1287
+ catch (err) {
1288
+ setError(err instanceof Error ? err : new Error('Error al guardar valor'));
1289
+ throw err;
1290
+ }
1291
+ }, [key, secureStorage]);
1292
+ return [storedValue, setValue, loading, error];
1293
+ }
1294
+ /**
1295
+ * Hook para usar SecureStorage con expiración
1296
+ */
1297
+ function useSecureStorageWithExpiry(key, initialValue, expiryOptions, storage) {
1298
+ const secureStorage = storage || getDefaultStorage();
1299
+ const [storedValue, setStoredValue] = useState(initialValue);
1300
+ const [loading, setLoading] = useState(true);
1301
+ const [error, setError] = useState(null);
1302
+ useEffect(() => {
1303
+ const loadValue = async () => {
1304
+ try {
1305
+ setLoading(true);
1306
+ setError(null);
1307
+ const item = await secureStorage.getItem(key);
1308
+ if (item !== null) {
1309
+ if (typeof initialValue === 'object') {
1310
+ setStoredValue(JSON.parse(item));
1311
+ }
1312
+ else {
1313
+ setStoredValue(item);
1314
+ }
1315
+ }
1316
+ else {
1317
+ setStoredValue(initialValue);
1318
+ }
1319
+ }
1320
+ catch (err) {
1321
+ setError(err instanceof Error ? err : new Error('Error al cargar valor'));
1322
+ setStoredValue(initialValue);
1323
+ }
1324
+ finally {
1325
+ setLoading(false);
1326
+ }
1327
+ };
1328
+ loadValue();
1329
+ }, [key]);
1330
+ const setValue = useCallback(async (value) => {
1331
+ try {
1332
+ setError(null);
1333
+ setStoredValue(value);
1334
+ const valueToStore = typeof value === 'object'
1335
+ ? JSON.stringify(value)
1336
+ : String(value);
1337
+ await secureStorage.setItemWithExpiry(key, valueToStore, expiryOptions);
1338
+ }
1339
+ catch (err) {
1340
+ setError(err instanceof Error ? err : new Error('Error al guardar valor'));
1341
+ throw err;
1342
+ }
1343
+ }, [key, secureStorage, expiryOptions]);
1344
+ return [storedValue, setValue, loading, error];
1345
+ }
1346
+ /**
1347
+ * Hook para verificar si una clave existe en SecureStorage
1348
+ */
1349
+ function useSecureStorageItem(key, storage) {
1350
+ const secureStorage = storage || getDefaultStorage();
1351
+ const [exists, setExists] = useState(false);
1352
+ const [loading, setLoading] = useState(true);
1353
+ const [error, setError] = useState(null);
1354
+ useEffect(() => {
1355
+ const checkExists = async () => {
1356
+ try {
1357
+ setLoading(true);
1358
+ setError(null);
1359
+ const hasItem = await secureStorage.hasItem(key);
1360
+ setExists(hasItem);
1361
+ }
1362
+ catch (err) {
1363
+ setError(err instanceof Error ? err : new Error('Error al verificar clave'));
1364
+ setExists(false);
1365
+ }
1366
+ finally {
1367
+ setLoading(false);
1368
+ }
1369
+ };
1370
+ checkExists();
1371
+ }, [key, secureStorage]);
1372
+ return [exists, loading, error];
1373
+ }
1374
+ /**
1375
+ * Hook para escuchar eventos de SecureStorage
1376
+ */
1377
+ function useSecureStorageEvents(event, handler, storage) {
1378
+ const secureStorage = storage || getDefaultStorage();
1379
+ useEffect(() => {
1380
+ secureStorage.on(event, handler);
1381
+ return () => {
1382
+ secureStorage.off(event, handler);
1383
+ };
1384
+ }, [event, handler, secureStorage]);
1385
+ }
1386
+ /**
1387
+ * Hook para obtener información de debug del almacenamiento
1388
+ */
1389
+ function useSecureStorageDebug(storage) {
1390
+ const secureStorage = storage || getDefaultStorage();
1391
+ const [debugInfo, setDebugInfo] = useState(secureStorage.getDebugInfo());
1392
+ useEffect(() => {
1393
+ const interval = setInterval(() => {
1394
+ setDebugInfo(secureStorage.getDebugInfo());
1395
+ }, 1000);
1396
+ return () => clearInterval(interval);
1397
+ }, [secureStorage]);
1398
+ return debugInfo;
1399
+ }
1400
+ /**
1401
+ * Hook para usar un namespace de SecureStorage
1402
+ */
1403
+ function useNamespace(namespace, storage) {
1404
+ const secureStorage = storage || getDefaultStorage();
1405
+ const [namespacedStorage] = useState(() => secureStorage.namespace(namespace));
1406
+ return namespacedStorage;
1407
+ }
1408
+ /**
1409
+ * Exportar la instancia de SecureStorage para uso directo
1410
+ */
1411
+ const secureStorage = getDefaultStorage();
1412
+
1413
+ export { DEFAULT_CONFIG, EncryptionHelper, EventEmitter, KeyRotation, LIBRARY_VERSION, Logger, NamespacedStorage, STORAGE_VERSION, SecureStorage, VERSION, compress, debugEncryptionState, decompress, forceMigration, initializeSecureStorage, isCompressionSupported, secureStorage as reactSecureStorage, secureStorage$1 as secureStorage, shouldCompress, useNamespace, useSecureStorage, useSecureStorageDebug, useSecureStorageEvents, useSecureStorageItem, useSecureStorageWithExpiry };
1414
+ //# sourceMappingURL=react.esm.js.map