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