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