@bantis/local-cipher 2.0.1 → 2.2.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,1423 @@
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: 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) {
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
+ async getIndex() {
547
+ const indexValue = await this.storage.getItem(`${this.prefix}__index__`);
548
+ return indexValue ? JSON.parse(indexValue) : [];
549
+ }
550
+ async saveToIndex(key) {
551
+ const index = await this.getIndex();
552
+ if (!index.includes(key)) {
553
+ index.push(key);
554
+ await this.storage.setItem(`${this.prefix}__index__`, JSON.stringify(index));
555
+ }
556
+ }
557
+ async removeFromIndex(key) {
558
+ const index = await this.getIndex();
559
+ const newIndex = index.filter(k => k !== key);
560
+ if (newIndex.length !== index.length) {
561
+ await this.storage.setItem(`${this.prefix}__index__`, JSON.stringify(newIndex));
562
+ }
563
+ }
564
+ /**
565
+ * Set item in this namespace
566
+ */
567
+ async setItem(key, value) {
568
+ await this.storage.setItem(`${this.prefix}${key}`, value);
569
+ await this.saveToIndex(key);
570
+ }
571
+ /**
572
+ * Set item with expiry in this namespace
573
+ */
574
+ async setItemWithExpiry(key, value, options) {
575
+ await this.storage.setItemWithExpiry(`${this.prefix}${key}`, value, options);
576
+ await this.saveToIndex(key);
577
+ }
578
+ /**
579
+ * Get item from this namespace
580
+ */
581
+ async getItem(key) {
582
+ return this.storage.getItem(`${this.prefix}${key}`);
583
+ }
584
+ /**
585
+ * Remove item from this namespace
586
+ */
587
+ async removeItem(key) {
588
+ await this.storage.removeItem(`${this.prefix}${key}`);
589
+ await this.removeFromIndex(key);
590
+ }
591
+ /**
592
+ * Check if item exists in this namespace
593
+ */
594
+ async hasItem(key) {
595
+ return this.storage.hasItem(`${this.prefix}${key}`);
596
+ }
597
+ /**
598
+ * Clear all items in this namespace
599
+ */
600
+ async clearNamespace() {
601
+ const keysToRemove = await this.getIndex();
602
+ for (const key of keysToRemove) {
603
+ await this.storage.removeItem(`${this.prefix}${key}`);
604
+ }
605
+ await this.storage.removeItem(`${this.prefix}__index__`);
606
+ }
607
+ /**
608
+ * Get all keys in this namespace
609
+ */
610
+ async keys() {
611
+ return this.getIndex();
612
+ }
613
+ }
614
+
615
+ /**
616
+ * Compression utilities using CompressionStream API
617
+ */
618
+ /**
619
+ * Check if compression is supported
620
+ */
621
+ function isCompressionSupported() {
622
+ return typeof CompressionStream !== 'undefined' && typeof DecompressionStream !== 'undefined';
623
+ }
624
+ /**
625
+ * Compress a string using gzip
626
+ */
627
+ async function compress(data) {
628
+ if (!isCompressionSupported()) {
629
+ // Fallback: return uncompressed data with marker
630
+ const encoder = new TextEncoder();
631
+ return encoder.encode(data);
632
+ }
633
+ try {
634
+ const stream = new Blob([data]).stream();
635
+ const compressedStream = stream.pipeThrough(new CompressionStream('gzip'));
636
+ const compressedBlob = await new Response(compressedStream).blob();
637
+ const buffer = await compressedBlob.arrayBuffer();
638
+ return new Uint8Array(buffer);
639
+ }
640
+ catch (error) {
641
+ console.warn('Compression failed, returning uncompressed data:', error);
642
+ const encoder = new TextEncoder();
643
+ return encoder.encode(data);
644
+ }
645
+ }
646
+ /**
647
+ * Decompress gzip data to string
648
+ */
649
+ async function decompress(data) {
650
+ if (!isCompressionSupported()) {
651
+ // Fallback: assume uncompressed
652
+ const decoder = new TextDecoder();
653
+ return decoder.decode(data);
654
+ }
655
+ try {
656
+ const stream = new Blob([data]).stream();
657
+ const decompressedStream = stream.pipeThrough(new DecompressionStream('gzip'));
658
+ const decompressedBlob = await new Response(decompressedStream).blob();
659
+ return await decompressedBlob.text();
660
+ }
661
+ catch (error) {
662
+ // If decompression fails, try to decode as plain text
663
+ console.warn('Decompression failed, trying plain text:', error);
664
+ const decoder = new TextDecoder();
665
+ return decoder.decode(data);
666
+ }
667
+ }
668
+ /**
669
+ * Check if data should be compressed based on size
670
+ */
671
+ function shouldCompress(data, threshold = 1024) {
672
+ return data.length >= threshold;
673
+ }
674
+
675
+ /**
676
+ * SecureStorage v2 - API de alto nivel que imita localStorage con cifrado automático
677
+ * Incluye: configuración personalizable, eventos, compresión, expiración, namespaces, rotación de claves
678
+ */
679
+ class SecureStorage {
680
+ constructor(config) {
681
+ this.cleanupInterval = null;
682
+ // Merge config with defaults
683
+ this.config = {
684
+ encryption: { ...DEFAULT_CONFIG.encryption, ...config?.encryption },
685
+ storage: { ...DEFAULT_CONFIG.storage, ...config?.storage },
686
+ debug: { ...DEFAULT_CONFIG.debug, ...config?.debug },
687
+ };
688
+ // Initialize components
689
+ this.logger = new Logger(this.config.debug);
690
+ this.encryptionHelper = new EncryptionHelper(this.config.encryption);
691
+ this.eventEmitter = new EventEmitter();
692
+ this.keyRotation = new KeyRotation(this.encryptionHelper, this.logger);
693
+ this.logger.info('SecureStorage v2 initialized', this.config);
694
+ // Setup auto-cleanup if enabled
695
+ if (this.config.storage.autoCleanup) {
696
+ this.setupAutoCleanup();
697
+ }
698
+ }
699
+ /**
700
+ * Obtiene la instancia singleton de SecureStorage
701
+ */
702
+ static getInstance(config) {
703
+ if (!SecureStorage.instance) {
704
+ SecureStorage.instance = new SecureStorage(config);
705
+ }
706
+ return SecureStorage.instance;
707
+ }
708
+ /**
709
+ * Setup automatic cleanup of expired items
710
+ */
711
+ setupAutoCleanup() {
712
+ if (this.cleanupInterval) {
713
+ clearInterval(this.cleanupInterval);
714
+ }
715
+ this.cleanupInterval = setInterval(() => {
716
+ this.cleanExpired().catch(err => {
717
+ this.logger.error('Auto-cleanup failed:', err);
718
+ });
719
+ }, this.config.storage.cleanupInterval);
720
+ this.logger.debug(`Auto-cleanup enabled with interval: ${this.config.storage.cleanupInterval}ms`);
721
+ }
722
+ /**
723
+ * Guarda un valor encriptado en localStorage
724
+ */
725
+ async setItem(key, value) {
726
+ this.logger.time(`setItem:${key}`);
727
+ if (!EncryptionHelper.isSupported()) {
728
+ this.logger.warn('Web Crypto API no soportada, usando localStorage sin encriptar');
729
+ localStorage.setItem(key, value);
730
+ return;
731
+ }
732
+ try {
733
+ // Check if compression should be applied
734
+ const shouldCompressData = this.config.storage.compression &&
735
+ shouldCompress(value, this.config.storage.compressionThreshold);
736
+ let processedValue = value;
737
+ let compressed = false;
738
+ if (shouldCompressData) {
739
+ this.logger.debug(`Compressing value for key: ${key}`);
740
+ const compressedData = await compress(value);
741
+ processedValue = this.encryptionHelper['arrayBufferToBase64'](compressedData.buffer);
742
+ compressed = true;
743
+ this.eventEmitter.emit('compressed', { key });
744
+ }
745
+ // Create StoredValue wrapper
746
+ const now = Date.now();
747
+ const storedValue = {
748
+ value: processedValue,
749
+ createdAt: now,
750
+ modifiedAt: now,
751
+ version: STORAGE_VERSION,
752
+ compressed,
753
+ };
754
+ // Calculate checksum for integrity
755
+ const checksum = await this.calculateChecksum(processedValue);
756
+ storedValue.checksum = checksum;
757
+ // Serialize StoredValue
758
+ const serialized = JSON.stringify(storedValue);
759
+ // Encrypt the key
760
+ const encryptedKey = await this.encryptionHelper.encryptKey(key);
761
+ // Encrypt the value
762
+ const encryptedValue = await this.encryptionHelper.encrypt(serialized);
763
+ // Store in localStorage
764
+ localStorage.setItem(encryptedKey, encryptedValue);
765
+ this.logger.verbose(`Stored key: ${key}, compressed: ${compressed}, size: ${encryptedValue.length}`);
766
+ this.eventEmitter.emit('encrypted', { key, metadata: { compressed, size: encryptedValue.length } });
767
+ this.logger.timeEnd(`setItem:${key}`);
768
+ }
769
+ catch (error) {
770
+ this.logger.error(`Error al guardar dato encriptado para ${key}:`, error);
771
+ this.eventEmitter.emit('error', { key, error: error });
772
+ localStorage.setItem(key, value);
773
+ }
774
+ }
775
+ /**
776
+ * Guarda un valor con tiempo de expiración
777
+ */
778
+ async setItemWithExpiry(key, value, options) {
779
+ this.logger.time(`setItemWithExpiry:${key}`);
780
+ if (!EncryptionHelper.isSupported()) {
781
+ this.logger.warn('Web Crypto API no soportada, usando localStorage sin encriptar');
782
+ localStorage.setItem(key, value);
783
+ return;
784
+ }
785
+ try {
786
+ // Check if compression should be applied
787
+ const shouldCompressData = this.config.storage.compression &&
788
+ shouldCompress(value, this.config.storage.compressionThreshold);
789
+ let processedValue = value;
790
+ let compressed = false;
791
+ if (shouldCompressData) {
792
+ this.logger.debug(`Compressing value for key: ${key}`);
793
+ const compressedData = await compress(value);
794
+ processedValue = this.encryptionHelper['arrayBufferToBase64'](compressedData.buffer);
795
+ compressed = true;
796
+ this.eventEmitter.emit('compressed', { key });
797
+ }
798
+ // Calculate expiration timestamp
799
+ let expiresAt;
800
+ if (options.expiresIn) {
801
+ expiresAt = Date.now() + options.expiresIn;
802
+ }
803
+ else if (options.expiresAt) {
804
+ expiresAt = options.expiresAt.getTime();
805
+ }
806
+ // Create StoredValue wrapper
807
+ const now = Date.now();
808
+ const storedValue = {
809
+ value: processedValue,
810
+ createdAt: now,
811
+ modifiedAt: now,
812
+ version: STORAGE_VERSION,
813
+ compressed,
814
+ expiresAt,
815
+ };
816
+ // Calculate checksum for integrity
817
+ const checksum = await this.calculateChecksum(processedValue);
818
+ storedValue.checksum = checksum;
819
+ // Serialize StoredValue
820
+ const serialized = JSON.stringify(storedValue);
821
+ // Encrypt the key
822
+ const encryptedKey = await this.encryptionHelper.encryptKey(key);
823
+ // Encrypt the value
824
+ const encryptedValue = await this.encryptionHelper.encrypt(serialized);
825
+ // Store in localStorage
826
+ localStorage.setItem(encryptedKey, encryptedValue);
827
+ this.logger.verbose(`Stored key with expiry: ${key}, expiresAt: ${expiresAt}`);
828
+ this.eventEmitter.emit('encrypted', { key, metadata: { compressed, expiresAt } });
829
+ this.logger.timeEnd(`setItemWithExpiry:${key}`);
830
+ }
831
+ catch (error) {
832
+ this.logger.error(`Error al guardar dato con expiración para ${key}:`, error);
833
+ this.eventEmitter.emit('error', { key, error: error });
834
+ throw error;
835
+ }
836
+ }
837
+ /**
838
+ * Recupera y desencripta un valor de localStorage
839
+ */
840
+ async getItem(key) {
841
+ this.logger.time(`getItem:${key}`);
842
+ if (!EncryptionHelper.isSupported()) {
843
+ return localStorage.getItem(key);
844
+ }
845
+ try {
846
+ // Encrypt the key
847
+ const encryptedKey = await this.encryptionHelper.encryptKey(key);
848
+ // Get encrypted value
849
+ let encryptedValue = localStorage.getItem(encryptedKey);
850
+ // Backward compatibility: try with plain key
851
+ if (!encryptedValue) {
852
+ encryptedValue = localStorage.getItem(key);
853
+ if (!encryptedValue) {
854
+ this.logger.timeEnd(`getItem:${key}`);
855
+ return null;
856
+ }
857
+ }
858
+ // Decrypt the value
859
+ const decrypted = await this.encryptionHelper.decrypt(encryptedValue);
860
+ // Try to parse as StoredValue (v2 format)
861
+ let storedValue;
862
+ try {
863
+ storedValue = JSON.parse(decrypted);
864
+ // Validate it's a StoredValue object
865
+ if (!storedValue.value || !storedValue.version) {
866
+ // 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
+ }
873
+ catch {
874
+ // Not JSON, it's v1 format (plain string), auto-migrate
875
+ this.logger.info(`Auto-migrating v1 data for key: ${key}`);
876
+ await this.setItem(key, decrypted);
877
+ this.logger.timeEnd(`getItem:${key}`);
878
+ return decrypted;
879
+ }
880
+ // Check expiration
881
+ if (storedValue.expiresAt && storedValue.expiresAt < Date.now()) {
882
+ this.logger.info(`Key expired: ${key}`);
883
+ await this.removeItem(key);
884
+ this.eventEmitter.emit('expired', { key });
885
+ this.logger.timeEnd(`getItem:${key}`);
886
+ return null;
887
+ }
888
+ // Verify integrity if checksum exists
889
+ if (storedValue.checksum) {
890
+ const calculatedChecksum = await this.calculateChecksum(storedValue.value);
891
+ if (calculatedChecksum !== storedValue.checksum) {
892
+ this.logger.warn(`Integrity check failed for key: ${key}`);
893
+ this.eventEmitter.emit('error', {
894
+ key,
895
+ error: new Error('Integrity verification failed')
896
+ });
897
+ }
898
+ }
899
+ // Decompress if needed
900
+ let finalValue = storedValue.value;
901
+ if (storedValue.compressed) {
902
+ this.logger.debug(`Decompressing value for key: ${key}`);
903
+ const compressedData = this.encryptionHelper['base64ToArrayBuffer'](storedValue.value);
904
+ finalValue = await decompress(new Uint8Array(compressedData));
905
+ this.eventEmitter.emit('decompressed', { key });
906
+ }
907
+ this.eventEmitter.emit('decrypted', { key });
908
+ this.logger.timeEnd(`getItem:${key}`);
909
+ return finalValue;
910
+ }
911
+ catch (error) {
912
+ this.logger.error(`Error al recuperar dato encriptado para ${key}:`, error);
913
+ this.eventEmitter.emit('error', { key, error: error });
914
+ // Fallback: try plain key
915
+ const fallback = localStorage.getItem(key);
916
+ this.logger.timeEnd(`getItem:${key}`);
917
+ return fallback;
918
+ }
919
+ }
920
+ /**
921
+ * Elimina un valor de localStorage
922
+ */
923
+ async removeItem(key) {
924
+ if (!EncryptionHelper.isSupported()) {
925
+ localStorage.removeItem(key);
926
+ return;
927
+ }
928
+ try {
929
+ const encryptedKey = await this.encryptionHelper.encryptKey(key);
930
+ localStorage.removeItem(encryptedKey);
931
+ localStorage.removeItem(key); // Remove both versions
932
+ this.eventEmitter.emit('deleted', { key });
933
+ this.logger.info(`Removed key: ${key}`);
934
+ }
935
+ catch (error) {
936
+ this.logger.error(`Error al eliminar dato para ${key}:`, error);
937
+ localStorage.removeItem(key);
938
+ }
939
+ }
940
+ /**
941
+ * Verifica si existe un valor para la clave dada
942
+ */
943
+ async hasItem(key) {
944
+ const value = await this.getItem(key);
945
+ return value !== null;
946
+ }
947
+ /**
948
+ * Limpia todos los datos encriptados
949
+ */
950
+ clear() {
951
+ this.encryptionHelper.clearEncryptedData();
952
+ this.eventEmitter.emit('cleared', {});
953
+ this.logger.info('All encrypted data cleared');
954
+ }
955
+ /**
956
+ * Limpia todos los items expirados
957
+ */
958
+ async cleanExpired() {
959
+ this.logger.info('Starting cleanup of expired items...');
960
+ let cleanedCount = 0;
961
+ const keysToCheck = [];
962
+ for (let i = 0; i < localStorage.length; i++) {
963
+ const key = localStorage.key(i);
964
+ if (key && key.startsWith('__enc_')) {
965
+ keysToCheck.push(key);
966
+ }
967
+ }
968
+ for (const encryptedKey of keysToCheck) {
969
+ try {
970
+ const encryptedValue = localStorage.getItem(encryptedKey);
971
+ if (!encryptedValue)
972
+ continue;
973
+ const decrypted = await this.encryptionHelper.decrypt(encryptedValue);
974
+ const storedValue = JSON.parse(decrypted);
975
+ if (storedValue.expiresAt && storedValue.expiresAt < Date.now()) {
976
+ localStorage.removeItem(encryptedKey);
977
+ cleanedCount++;
978
+ this.eventEmitter.emit('expired', { key: encryptedKey });
979
+ }
980
+ }
981
+ catch (error) {
982
+ this.logger.warn(`Failed to check expiration for ${encryptedKey}:`, error);
983
+ }
984
+ }
985
+ this.logger.info(`Cleanup completed. Removed ${cleanedCount} expired items`);
986
+ return cleanedCount;
987
+ }
988
+ /**
989
+ * Verifica la integridad de un valor almacenado
990
+ */
991
+ async verifyIntegrity(key) {
992
+ try {
993
+ const encryptedKey = await this.encryptionHelper.encryptKey(key);
994
+ const encryptedValue = localStorage.getItem(encryptedKey);
995
+ if (!encryptedValue)
996
+ return false;
997
+ const decrypted = await this.encryptionHelper.decrypt(encryptedValue);
998
+ const storedValue = JSON.parse(decrypted);
999
+ if (!storedValue.checksum) {
1000
+ this.logger.warn(`No checksum found for key: ${key}`);
1001
+ return true; // No checksum to verify
1002
+ }
1003
+ const calculatedChecksum = await this.calculateChecksum(storedValue.value);
1004
+ return calculatedChecksum === storedValue.checksum;
1005
+ }
1006
+ catch (error) {
1007
+ this.logger.error(`Error verifying integrity for ${key}:`, error);
1008
+ return false;
1009
+ }
1010
+ }
1011
+ /**
1012
+ * Obtiene información de integridad de un valor
1013
+ */
1014
+ async getIntegrityInfo(key) {
1015
+ try {
1016
+ const encryptedKey = await this.encryptionHelper.encryptKey(key);
1017
+ const encryptedValue = localStorage.getItem(encryptedKey);
1018
+ if (!encryptedValue)
1019
+ return null;
1020
+ const decrypted = await this.encryptionHelper.decrypt(encryptedValue);
1021
+ const storedValue = JSON.parse(decrypted);
1022
+ const valid = storedValue.checksum
1023
+ ? await this.calculateChecksum(storedValue.value) === storedValue.checksum
1024
+ : true;
1025
+ return {
1026
+ valid,
1027
+ lastModified: storedValue.modifiedAt,
1028
+ checksum: storedValue.checksum || '',
1029
+ version: storedValue.version,
1030
+ };
1031
+ }
1032
+ catch (error) {
1033
+ this.logger.error(`Error getting integrity info for ${key}:`, error);
1034
+ return null;
1035
+ }
1036
+ }
1037
+ /**
1038
+ * Crea un namespace para organizar datos
1039
+ */
1040
+ namespace(name) {
1041
+ this.logger.debug(`Creating namespace: ${name}`);
1042
+ return new NamespacedStorage(this, name);
1043
+ }
1044
+ /**
1045
+ * Rota todas las claves de encriptación
1046
+ */
1047
+ async rotateKeys() {
1048
+ this.logger.info('Starting key rotation...');
1049
+ await this.keyRotation.rotateKeys();
1050
+ this.eventEmitter.emit('keyRotated', {});
1051
+ this.logger.info('Key rotation completed');
1052
+ }
1053
+ /**
1054
+ * Exporta todos los datos encriptados como backup
1055
+ */
1056
+ async exportEncryptedData() {
1057
+ return this.keyRotation.exportEncryptedData();
1058
+ }
1059
+ /**
1060
+ * Importa datos desde un backup
1061
+ */
1062
+ async importEncryptedData(backup) {
1063
+ return this.keyRotation.importEncryptedData(backup);
1064
+ }
1065
+ /**
1066
+ * Registra un listener de eventos
1067
+ */
1068
+ on(event, listener) {
1069
+ this.eventEmitter.on(event, listener);
1070
+ }
1071
+ /**
1072
+ * Registra un listener de un solo uso
1073
+ */
1074
+ once(event, listener) {
1075
+ this.eventEmitter.once(event, listener);
1076
+ }
1077
+ /**
1078
+ * Elimina un listener de eventos
1079
+ */
1080
+ off(event, listener) {
1081
+ this.eventEmitter.off(event, listener);
1082
+ }
1083
+ /**
1084
+ * Elimina todos los listeners de un evento
1085
+ */
1086
+ removeAllListeners(event) {
1087
+ this.eventEmitter.removeAllListeners(event);
1088
+ }
1089
+ /**
1090
+ * Migra datos existentes no encriptados a formato encriptado
1091
+ */
1092
+ async migrateExistingData(keys) {
1093
+ if (!EncryptionHelper.isSupported()) {
1094
+ this.logger.warn('Web Crypto API no soportada, no se puede migrar');
1095
+ return;
1096
+ }
1097
+ this.logger.info(`Iniciando migración de ${keys.length} claves...`);
1098
+ for (const key of keys) {
1099
+ try {
1100
+ const value = localStorage.getItem(key);
1101
+ if (value === null)
1102
+ continue;
1103
+ // Try to decrypt to check if already encrypted
1104
+ try {
1105
+ await this.encryptionHelper.decrypt(value);
1106
+ this.logger.info(`✓ ${key} ya está encriptado, saltando`);
1107
+ continue;
1108
+ }
1109
+ catch {
1110
+ // Not encrypted, proceed with migration
1111
+ }
1112
+ await this.setItem(key, value);
1113
+ localStorage.removeItem(key);
1114
+ this.logger.info(`✓ ${key} migrado exitosamente`);
1115
+ }
1116
+ catch (error) {
1117
+ this.logger.error(`✗ Error al migrar ${key}:`, error);
1118
+ }
1119
+ }
1120
+ this.logger.info('✅ Migración completada');
1121
+ }
1122
+ /**
1123
+ * Obtiene información de debug sobre el estado del almacenamiento
1124
+ */
1125
+ getDebugInfo() {
1126
+ const allKeys = [];
1127
+ for (let i = 0; i < localStorage.length; i++) {
1128
+ const key = localStorage.key(i);
1129
+ if (key)
1130
+ allKeys.push(key);
1131
+ }
1132
+ const encryptedKeys = allKeys.filter(key => key.startsWith('__enc_'));
1133
+ const unencryptedKeys = allKeys.filter(key => !key.startsWith('__enc_') && key !== '__app_salt' && key !== '__key_version');
1134
+ return {
1135
+ cryptoSupported: EncryptionHelper.isSupported(),
1136
+ encryptedKeys,
1137
+ unencryptedKeys,
1138
+ totalKeys: allKeys.length,
1139
+ config: this.config,
1140
+ };
1141
+ }
1142
+ /**
1143
+ * Calcula el checksum SHA-256 de un valor
1144
+ */
1145
+ async calculateChecksum(value) {
1146
+ const encoder = new TextEncoder();
1147
+ const data = encoder.encode(value);
1148
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
1149
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
1150
+ return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
1151
+ }
1152
+ /**
1153
+ * Cleanup on destroy
1154
+ */
1155
+ destroy() {
1156
+ if (this.cleanupInterval) {
1157
+ clearInterval(this.cleanupInterval);
1158
+ this.cleanupInterval = null;
1159
+ }
1160
+ this.removeAllListeners();
1161
+ this.logger.info('SecureStorage destroyed');
1162
+ SecureStorage.instance = null;
1163
+ }
1164
+ }
1165
+ SecureStorage.instance = null;
1166
+
1167
+ const secureStorage$2 = SecureStorage.getInstance();
1168
+ /**
1169
+ * Función de debug para verificar el estado del sistema de encriptación
1170
+ * Muestra información detallada en la consola
1171
+ */
1172
+ async function debugEncryptionState() {
1173
+ console.group('🔐 Estado del Sistema de Encriptación');
1174
+ console.log('Soporte Crypto API:', EncryptionHelper.isSupported());
1175
+ // Obtener información de debug
1176
+ const debugInfo = secureStorage$2.getDebugInfo();
1177
+ console.log('Claves encriptadas:', debugInfo.encryptedKeys.length);
1178
+ console.log('Claves sin encriptar:', debugInfo.unencryptedKeys);
1179
+ console.log('Total de claves:', debugInfo.totalKeys);
1180
+ if (debugInfo.encryptedKeys.length > 0) {
1181
+ console.log('✅ Datos encriptados encontrados:');
1182
+ debugInfo.encryptedKeys.forEach(key => {
1183
+ const value = localStorage.getItem(key);
1184
+ console.log(` ${key}: ${value?.substring(0, 30)}...`);
1185
+ });
1186
+ }
1187
+ else {
1188
+ console.log('⚠️ No se encontraron datos encriptados');
1189
+ }
1190
+ if (debugInfo.unencryptedKeys.length > 0) {
1191
+ console.log('⚠️ Claves sin encriptar encontradas:');
1192
+ debugInfo.unencryptedKeys.forEach(key => {
1193
+ console.log(` ${key}`);
1194
+ });
1195
+ }
1196
+ console.groupEnd();
1197
+ }
1198
+ /**
1199
+ * Fuerza la migración de claves comunes a formato encriptado
1200
+ * Útil para desarrollo y testing
1201
+ */
1202
+ async function forceMigration(customKeys) {
1203
+ const defaultKeys = [
1204
+ 'accessToken',
1205
+ 'refreshToken',
1206
+ 'user',
1207
+ 'sessionId',
1208
+ 'authToken',
1209
+ 'userData',
1210
+ ];
1211
+ const keysToMigrate = customKeys || defaultKeys;
1212
+ console.log(`🔄 Iniciando migración forzada de ${keysToMigrate.length} claves...`);
1213
+ await secureStorage$2.migrateExistingData(keysToMigrate);
1214
+ console.log('✅ Migración forzada completada');
1215
+ // Mostrar estado después de la migración
1216
+ await debugEncryptionState();
1217
+ }
1218
+
1219
+ /**
1220
+ * @bantis/local-cipher - Core Module
1221
+ * Framework-agnostic client-side encryption for browser storage
1222
+ *
1223
+ * @version 2.1.0
1224
+ * @license MIT
1225
+ */
1226
+ // Core classes
1227
+ const secureStorage$1 = SecureStorage.getInstance();
1228
+ // Version
1229
+ const VERSION = '2.1.0';
1230
+
1231
+ /**
1232
+ * React Hooks for @bantis/local-cipher
1233
+ * Provides reactive hooks for encrypted browser storage
1234
+ */
1235
+ // Allow custom storage instance or use default
1236
+ let defaultStorage = null;
1237
+ function getDefaultStorage() {
1238
+ if (!defaultStorage) {
1239
+ defaultStorage = SecureStorage.getInstance();
1240
+ }
1241
+ return defaultStorage;
1242
+ }
1243
+ /**
1244
+ * Initialize SecureStorage with custom configuration
1245
+ */
1246
+ function initializeSecureStorage(config) {
1247
+ defaultStorage = SecureStorage.getInstance(config);
1248
+ return defaultStorage;
1249
+ }
1250
+ /**
1251
+ * Hook de React para usar SecureStorage de forma reactiva
1252
+ * Similar a useState pero con persistencia encriptada
1253
+ */
1254
+ function useSecureStorage(key, initialValue, storage) {
1255
+ const secureStorage = storage || getDefaultStorage();
1256
+ const [storedValue, setStoredValue] = useState(initialValue);
1257
+ const [loading, setLoading] = useState(true);
1258
+ const [error, setError] = useState(null);
1259
+ useEffect(() => {
1260
+ const loadValue = async () => {
1261
+ try {
1262
+ setLoading(true);
1263
+ setError(null);
1264
+ const item = await secureStorage.getItem(key);
1265
+ if (item !== null) {
1266
+ if (typeof initialValue === 'object') {
1267
+ setStoredValue(JSON.parse(item));
1268
+ }
1269
+ else {
1270
+ setStoredValue(item);
1271
+ }
1272
+ }
1273
+ else {
1274
+ setStoredValue(initialValue);
1275
+ }
1276
+ }
1277
+ catch (err) {
1278
+ setError(err instanceof Error ? err : new Error('Error al cargar valor'));
1279
+ setStoredValue(initialValue);
1280
+ }
1281
+ finally {
1282
+ setLoading(false);
1283
+ }
1284
+ };
1285
+ loadValue();
1286
+ }, [key]);
1287
+ const setValue = useCallback(async (value) => {
1288
+ try {
1289
+ setError(null);
1290
+ setStoredValue(value);
1291
+ const valueToStore = typeof value === 'object'
1292
+ ? JSON.stringify(value)
1293
+ : String(value);
1294
+ await secureStorage.setItem(key, valueToStore);
1295
+ }
1296
+ catch (err) {
1297
+ setError(err instanceof Error ? err : new Error('Error al guardar valor'));
1298
+ throw err;
1299
+ }
1300
+ }, [key, secureStorage]);
1301
+ return [storedValue, setValue, loading, error];
1302
+ }
1303
+ /**
1304
+ * Hook para usar SecureStorage con expiración
1305
+ */
1306
+ function useSecureStorageWithExpiry(key, initialValue, expiryOptions, storage) {
1307
+ const secureStorage = storage || getDefaultStorage();
1308
+ const [storedValue, setStoredValue] = useState(initialValue);
1309
+ const [loading, setLoading] = useState(true);
1310
+ const [error, setError] = useState(null);
1311
+ useEffect(() => {
1312
+ const loadValue = async () => {
1313
+ try {
1314
+ setLoading(true);
1315
+ setError(null);
1316
+ const item = await secureStorage.getItem(key);
1317
+ if (item !== null) {
1318
+ if (typeof initialValue === 'object') {
1319
+ setStoredValue(JSON.parse(item));
1320
+ }
1321
+ else {
1322
+ setStoredValue(item);
1323
+ }
1324
+ }
1325
+ else {
1326
+ setStoredValue(initialValue);
1327
+ }
1328
+ }
1329
+ catch (err) {
1330
+ setError(err instanceof Error ? err : new Error('Error al cargar valor'));
1331
+ setStoredValue(initialValue);
1332
+ }
1333
+ finally {
1334
+ setLoading(false);
1335
+ }
1336
+ };
1337
+ loadValue();
1338
+ }, [key]);
1339
+ const setValue = useCallback(async (value) => {
1340
+ try {
1341
+ setError(null);
1342
+ setStoredValue(value);
1343
+ const valueToStore = typeof value === 'object'
1344
+ ? JSON.stringify(value)
1345
+ : String(value);
1346
+ await secureStorage.setItemWithExpiry(key, valueToStore, expiryOptions);
1347
+ }
1348
+ catch (err) {
1349
+ setError(err instanceof Error ? err : new Error('Error al guardar valor'));
1350
+ throw err;
1351
+ }
1352
+ }, [key, secureStorage, expiryOptions]);
1353
+ return [storedValue, setValue, loading, error];
1354
+ }
1355
+ /**
1356
+ * Hook para verificar si una clave existe en SecureStorage
1357
+ */
1358
+ function useSecureStorageItem(key, storage) {
1359
+ const secureStorage = storage || getDefaultStorage();
1360
+ const [exists, setExists] = useState(false);
1361
+ const [loading, setLoading] = useState(true);
1362
+ const [error, setError] = useState(null);
1363
+ useEffect(() => {
1364
+ const checkExists = async () => {
1365
+ try {
1366
+ setLoading(true);
1367
+ setError(null);
1368
+ const hasItem = await secureStorage.hasItem(key);
1369
+ setExists(hasItem);
1370
+ }
1371
+ catch (err) {
1372
+ setError(err instanceof Error ? err : new Error('Error al verificar clave'));
1373
+ setExists(false);
1374
+ }
1375
+ finally {
1376
+ setLoading(false);
1377
+ }
1378
+ };
1379
+ checkExists();
1380
+ }, [key, secureStorage]);
1381
+ return [exists, loading, error];
1382
+ }
1383
+ /**
1384
+ * Hook para escuchar eventos de SecureStorage
1385
+ */
1386
+ function useSecureStorageEvents(event, handler, storage) {
1387
+ const secureStorage = storage || getDefaultStorage();
1388
+ useEffect(() => {
1389
+ secureStorage.on(event, handler);
1390
+ return () => {
1391
+ secureStorage.off(event, handler);
1392
+ };
1393
+ }, [event, handler, secureStorage]);
1394
+ }
1395
+ /**
1396
+ * Hook para obtener información de debug del almacenamiento
1397
+ */
1398
+ function useSecureStorageDebug(storage) {
1399
+ const secureStorage = storage || getDefaultStorage();
1400
+ const [debugInfo, setDebugInfo] = useState(secureStorage.getDebugInfo());
1401
+ useEffect(() => {
1402
+ const interval = setInterval(() => {
1403
+ setDebugInfo(secureStorage.getDebugInfo());
1404
+ }, 1000);
1405
+ return () => clearInterval(interval);
1406
+ }, [secureStorage]);
1407
+ return debugInfo;
1408
+ }
1409
+ /**
1410
+ * Hook para usar un namespace de SecureStorage
1411
+ */
1412
+ function useNamespace(namespace, storage) {
1413
+ const secureStorage = storage || getDefaultStorage();
1414
+ const [namespacedStorage] = useState(() => secureStorage.namespace(namespace));
1415
+ return namespacedStorage;
1416
+ }
1417
+ /**
1418
+ * Exportar la instancia de SecureStorage para uso directo
1419
+ */
1420
+ const secureStorage = getDefaultStorage();
1421
+
1422
+ 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 };
1423
+ //# sourceMappingURL=react.esm.js.map