@bantis/local-cipher 2.0.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +112 -17
- package/dist/angular/SecureStorageService.d.ts +156 -0
- package/dist/angular.d.ts +9 -0
- package/dist/angular.esm.js +1516 -0
- package/dist/angular.esm.js.map +1 -0
- package/dist/angular.js +1535 -0
- package/dist/angular.js.map +1 -0
- package/dist/core/EncryptionHelper.d.ts +76 -0
- package/dist/core/EventEmitter.d.ts +36 -0
- package/dist/core/KeyRotation.d.ts +24 -0
- package/dist/core/NamespacedStorage.d.ts +39 -0
- package/dist/core/SecureStorage.d.ts +114 -0
- package/dist/index.d.ts +16 -700
- package/dist/index.esm.js +9 -440
- package/dist/index.esm.js.map +1 -1
- package/dist/index.js +8 -444
- package/dist/index.js.map +1 -1
- package/dist/react/hooks.d.ts +39 -0
- package/dist/react.d.ts +9 -0
- package/dist/react.esm.js +1414 -0
- package/dist/react.esm.js.map +1 -0
- package/dist/react.js +1440 -0
- package/dist/react.js.map +1 -0
- package/dist/types/index.d.ts +153 -0
- package/dist/utils/compression.d.ts +23 -0
- package/dist/utils/debug.d.ts +18 -0
- package/dist/utils/logger.d.ts +22 -0
- package/package.json +30 -9
package/dist/angular.js
ADDED
|
@@ -0,0 +1,1535 @@
|
|
|
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,
|
|
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, ...args) {
|
|
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
|
+
/**
|
|
551
|
+
* Set item in this namespace
|
|
552
|
+
*/
|
|
553
|
+
async setItem(key, value) {
|
|
554
|
+
return this.storage.setItem(`${this.prefix}${key}`, value);
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Set item with expiry in this namespace
|
|
558
|
+
*/
|
|
559
|
+
async setItemWithExpiry(key, value, options) {
|
|
560
|
+
return this.storage.setItemWithExpiry(`${this.prefix}${key}`, value, options);
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* Get item from this namespace
|
|
564
|
+
*/
|
|
565
|
+
async getItem(key) {
|
|
566
|
+
return this.storage.getItem(`${this.prefix}${key}`);
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Remove item from this namespace
|
|
570
|
+
*/
|
|
571
|
+
async removeItem(key) {
|
|
572
|
+
return this.storage.removeItem(`${this.prefix}${key}`);
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Check if item exists in this namespace
|
|
576
|
+
*/
|
|
577
|
+
async hasItem(key) {
|
|
578
|
+
return this.storage.hasItem(`${this.prefix}${key}`);
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Clear all items in this namespace
|
|
582
|
+
*/
|
|
583
|
+
async clearNamespace() {
|
|
584
|
+
const keysToRemove = [];
|
|
585
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
586
|
+
const key = localStorage.key(i);
|
|
587
|
+
if (key && key.includes(this.prefix)) {
|
|
588
|
+
keysToRemove.push(key.replace(this.prefix, ''));
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
for (const key of keysToRemove) {
|
|
592
|
+
await this.removeItem(key);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Get all keys in this namespace
|
|
597
|
+
*/
|
|
598
|
+
async keys() {
|
|
599
|
+
const keys = [];
|
|
600
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
601
|
+
const key = localStorage.key(i);
|
|
602
|
+
if (key && key.includes(this.prefix)) {
|
|
603
|
+
keys.push(key.replace(this.prefix, ''));
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
return keys;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Compression utilities using CompressionStream API
|
|
612
|
+
*/
|
|
613
|
+
/**
|
|
614
|
+
* Check if compression is supported
|
|
615
|
+
*/
|
|
616
|
+
function isCompressionSupported() {
|
|
617
|
+
return typeof CompressionStream !== 'undefined' && typeof DecompressionStream !== 'undefined';
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Compress a string using gzip
|
|
621
|
+
*/
|
|
622
|
+
async function compress(data) {
|
|
623
|
+
if (!isCompressionSupported()) {
|
|
624
|
+
// Fallback: return uncompressed data with marker
|
|
625
|
+
const encoder = new TextEncoder();
|
|
626
|
+
return encoder.encode(data);
|
|
627
|
+
}
|
|
628
|
+
try {
|
|
629
|
+
const encoder = new TextEncoder();
|
|
630
|
+
const stream = new Blob([data]).stream();
|
|
631
|
+
const compressedStream = stream.pipeThrough(new CompressionStream('gzip'));
|
|
632
|
+
const compressedBlob = await new Response(compressedStream).blob();
|
|
633
|
+
const buffer = await compressedBlob.arrayBuffer();
|
|
634
|
+
return new Uint8Array(buffer);
|
|
635
|
+
}
|
|
636
|
+
catch (error) {
|
|
637
|
+
console.warn('Compression failed, returning uncompressed data:', error);
|
|
638
|
+
const encoder = new TextEncoder();
|
|
639
|
+
return encoder.encode(data);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* Decompress gzip data to string
|
|
644
|
+
*/
|
|
645
|
+
async function decompress(data) {
|
|
646
|
+
if (!isCompressionSupported()) {
|
|
647
|
+
// Fallback: assume uncompressed
|
|
648
|
+
const decoder = new TextDecoder();
|
|
649
|
+
return decoder.decode(data);
|
|
650
|
+
}
|
|
651
|
+
try {
|
|
652
|
+
const stream = new Blob([data]).stream();
|
|
653
|
+
const decompressedStream = stream.pipeThrough(new DecompressionStream('gzip'));
|
|
654
|
+
const decompressedBlob = await new Response(decompressedStream).blob();
|
|
655
|
+
return await decompressedBlob.text();
|
|
656
|
+
}
|
|
657
|
+
catch (error) {
|
|
658
|
+
// If decompression fails, try to decode as plain text
|
|
659
|
+
console.warn('Decompression failed, trying plain text:', error);
|
|
660
|
+
const decoder = new TextDecoder();
|
|
661
|
+
return decoder.decode(data);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Check if data should be compressed based on size
|
|
666
|
+
*/
|
|
667
|
+
function shouldCompress(data, threshold = 1024) {
|
|
668
|
+
return data.length >= threshold;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* SecureStorage v2 - API de alto nivel que imita localStorage con cifrado automático
|
|
673
|
+
* Incluye: configuración personalizable, eventos, compresión, expiración, namespaces, rotación de claves
|
|
674
|
+
*/
|
|
675
|
+
class SecureStorage {
|
|
676
|
+
constructor(config) {
|
|
677
|
+
this.cleanupInterval = null;
|
|
678
|
+
// Merge config with defaults
|
|
679
|
+
this.config = {
|
|
680
|
+
encryption: { ...DEFAULT_CONFIG.encryption, ...config?.encryption },
|
|
681
|
+
storage: { ...DEFAULT_CONFIG.storage, ...config?.storage },
|
|
682
|
+
debug: { ...DEFAULT_CONFIG.debug, ...config?.debug },
|
|
683
|
+
};
|
|
684
|
+
// Initialize components
|
|
685
|
+
this.logger = new Logger(this.config.debug);
|
|
686
|
+
this.encryptionHelper = new EncryptionHelper(this.config.encryption);
|
|
687
|
+
this.eventEmitter = new EventEmitter();
|
|
688
|
+
this.keyRotation = new KeyRotation(this.encryptionHelper, this.logger);
|
|
689
|
+
this.logger.info('SecureStorage v2 initialized', this.config);
|
|
690
|
+
// Setup auto-cleanup if enabled
|
|
691
|
+
if (this.config.storage.autoCleanup) {
|
|
692
|
+
this.setupAutoCleanup();
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Obtiene la instancia singleton de SecureStorage
|
|
697
|
+
*/
|
|
698
|
+
static getInstance(config) {
|
|
699
|
+
if (!SecureStorage.instance) {
|
|
700
|
+
SecureStorage.instance = new SecureStorage(config);
|
|
701
|
+
}
|
|
702
|
+
return SecureStorage.instance;
|
|
703
|
+
}
|
|
704
|
+
/**
|
|
705
|
+
* Setup automatic cleanup of expired items
|
|
706
|
+
*/
|
|
707
|
+
setupAutoCleanup() {
|
|
708
|
+
if (this.cleanupInterval) {
|
|
709
|
+
clearInterval(this.cleanupInterval);
|
|
710
|
+
}
|
|
711
|
+
this.cleanupInterval = setInterval(() => {
|
|
712
|
+
this.cleanExpired().catch(err => {
|
|
713
|
+
this.logger.error('Auto-cleanup failed:', err);
|
|
714
|
+
});
|
|
715
|
+
}, this.config.storage.cleanupInterval);
|
|
716
|
+
this.logger.debug(`Auto-cleanup enabled with interval: ${this.config.storage.cleanupInterval}ms`);
|
|
717
|
+
}
|
|
718
|
+
/**
|
|
719
|
+
* Guarda un valor encriptado en localStorage
|
|
720
|
+
*/
|
|
721
|
+
async setItem(key, value) {
|
|
722
|
+
this.logger.time(`setItem:${key}`);
|
|
723
|
+
if (!EncryptionHelper.isSupported()) {
|
|
724
|
+
this.logger.warn('Web Crypto API no soportada, usando localStorage sin encriptar');
|
|
725
|
+
localStorage.setItem(key, value);
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
try {
|
|
729
|
+
// Check if compression should be applied
|
|
730
|
+
const shouldCompressData = this.config.storage.compression &&
|
|
731
|
+
shouldCompress(value, this.config.storage.compressionThreshold);
|
|
732
|
+
let processedValue = value;
|
|
733
|
+
let compressed = false;
|
|
734
|
+
if (shouldCompressData) {
|
|
735
|
+
this.logger.debug(`Compressing value for key: ${key}`);
|
|
736
|
+
const compressedData = await compress(value);
|
|
737
|
+
processedValue = this.encryptionHelper['arrayBufferToBase64'](compressedData.buffer);
|
|
738
|
+
compressed = true;
|
|
739
|
+
this.eventEmitter.emit('compressed', { key });
|
|
740
|
+
}
|
|
741
|
+
// Create StoredValue wrapper
|
|
742
|
+
const now = Date.now();
|
|
743
|
+
const storedValue = {
|
|
744
|
+
value: processedValue,
|
|
745
|
+
createdAt: now,
|
|
746
|
+
modifiedAt: now,
|
|
747
|
+
version: STORAGE_VERSION,
|
|
748
|
+
compressed,
|
|
749
|
+
};
|
|
750
|
+
// Calculate checksum for integrity
|
|
751
|
+
const checksum = await this.calculateChecksum(processedValue);
|
|
752
|
+
storedValue.checksum = checksum;
|
|
753
|
+
// Serialize StoredValue
|
|
754
|
+
const serialized = JSON.stringify(storedValue);
|
|
755
|
+
// Encrypt the key
|
|
756
|
+
const encryptedKey = await this.encryptionHelper.encryptKey(key);
|
|
757
|
+
// Encrypt the value
|
|
758
|
+
const encryptedValue = await this.encryptionHelper.encrypt(serialized);
|
|
759
|
+
// Store in localStorage
|
|
760
|
+
localStorage.setItem(encryptedKey, encryptedValue);
|
|
761
|
+
this.logger.verbose(`Stored key: ${key}, compressed: ${compressed}, size: ${encryptedValue.length}`);
|
|
762
|
+
this.eventEmitter.emit('encrypted', { key, metadata: { compressed, size: encryptedValue.length } });
|
|
763
|
+
this.logger.timeEnd(`setItem:${key}`);
|
|
764
|
+
}
|
|
765
|
+
catch (error) {
|
|
766
|
+
this.logger.error(`Error al guardar dato encriptado para ${key}:`, error);
|
|
767
|
+
this.eventEmitter.emit('error', { key, error: error });
|
|
768
|
+
localStorage.setItem(key, value);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* Guarda un valor con tiempo de expiración
|
|
773
|
+
*/
|
|
774
|
+
async setItemWithExpiry(key, value, options) {
|
|
775
|
+
this.logger.time(`setItemWithExpiry:${key}`);
|
|
776
|
+
if (!EncryptionHelper.isSupported()) {
|
|
777
|
+
this.logger.warn('Web Crypto API no soportada, usando localStorage sin encriptar');
|
|
778
|
+
localStorage.setItem(key, value);
|
|
779
|
+
return;
|
|
780
|
+
}
|
|
781
|
+
try {
|
|
782
|
+
// Check if compression should be applied
|
|
783
|
+
const shouldCompressData = this.config.storage.compression &&
|
|
784
|
+
shouldCompress(value, this.config.storage.compressionThreshold);
|
|
785
|
+
let processedValue = value;
|
|
786
|
+
let compressed = false;
|
|
787
|
+
if (shouldCompressData) {
|
|
788
|
+
this.logger.debug(`Compressing value for key: ${key}`);
|
|
789
|
+
const compressedData = await compress(value);
|
|
790
|
+
processedValue = this.encryptionHelper['arrayBufferToBase64'](compressedData.buffer);
|
|
791
|
+
compressed = true;
|
|
792
|
+
this.eventEmitter.emit('compressed', { key });
|
|
793
|
+
}
|
|
794
|
+
// Calculate expiration timestamp
|
|
795
|
+
let expiresAt;
|
|
796
|
+
if (options.expiresIn) {
|
|
797
|
+
expiresAt = Date.now() + options.expiresIn;
|
|
798
|
+
}
|
|
799
|
+
else if (options.expiresAt) {
|
|
800
|
+
expiresAt = options.expiresAt.getTime();
|
|
801
|
+
}
|
|
802
|
+
// Create StoredValue wrapper
|
|
803
|
+
const now = Date.now();
|
|
804
|
+
const storedValue = {
|
|
805
|
+
value: processedValue,
|
|
806
|
+
createdAt: now,
|
|
807
|
+
modifiedAt: now,
|
|
808
|
+
version: STORAGE_VERSION,
|
|
809
|
+
compressed,
|
|
810
|
+
expiresAt,
|
|
811
|
+
};
|
|
812
|
+
// Calculate checksum for integrity
|
|
813
|
+
const checksum = await this.calculateChecksum(processedValue);
|
|
814
|
+
storedValue.checksum = checksum;
|
|
815
|
+
// Serialize StoredValue
|
|
816
|
+
const serialized = JSON.stringify(storedValue);
|
|
817
|
+
// Encrypt the key
|
|
818
|
+
const encryptedKey = await this.encryptionHelper.encryptKey(key);
|
|
819
|
+
// Encrypt the value
|
|
820
|
+
const encryptedValue = await this.encryptionHelper.encrypt(serialized);
|
|
821
|
+
// Store in localStorage
|
|
822
|
+
localStorage.setItem(encryptedKey, encryptedValue);
|
|
823
|
+
this.logger.verbose(`Stored key with expiry: ${key}, expiresAt: ${expiresAt}`);
|
|
824
|
+
this.eventEmitter.emit('encrypted', { key, metadata: { compressed, expiresAt } });
|
|
825
|
+
this.logger.timeEnd(`setItemWithExpiry:${key}`);
|
|
826
|
+
}
|
|
827
|
+
catch (error) {
|
|
828
|
+
this.logger.error(`Error al guardar dato con expiración para ${key}:`, error);
|
|
829
|
+
this.eventEmitter.emit('error', { key, error: error });
|
|
830
|
+
throw error;
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Recupera y desencripta un valor de localStorage
|
|
835
|
+
*/
|
|
836
|
+
async getItem(key) {
|
|
837
|
+
this.logger.time(`getItem:${key}`);
|
|
838
|
+
if (!EncryptionHelper.isSupported()) {
|
|
839
|
+
return localStorage.getItem(key);
|
|
840
|
+
}
|
|
841
|
+
try {
|
|
842
|
+
// Encrypt the key
|
|
843
|
+
const encryptedKey = await this.encryptionHelper.encryptKey(key);
|
|
844
|
+
// Get encrypted value
|
|
845
|
+
let encryptedValue = localStorage.getItem(encryptedKey);
|
|
846
|
+
// Backward compatibility: try with plain key
|
|
847
|
+
if (!encryptedValue) {
|
|
848
|
+
encryptedValue = localStorage.getItem(key);
|
|
849
|
+
if (!encryptedValue) {
|
|
850
|
+
this.logger.timeEnd(`getItem:${key}`);
|
|
851
|
+
return null;
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
// Decrypt the value
|
|
855
|
+
const decrypted = await this.encryptionHelper.decrypt(encryptedValue);
|
|
856
|
+
// Try to parse as StoredValue (v2 format)
|
|
857
|
+
let storedValue;
|
|
858
|
+
try {
|
|
859
|
+
storedValue = JSON.parse(decrypted);
|
|
860
|
+
// Validate it's a StoredValue object
|
|
861
|
+
if (!storedValue.value || !storedValue.version) {
|
|
862
|
+
// It's v1 format (plain string), auto-migrate
|
|
863
|
+
this.logger.info(`Auto-migrating v1 data for key: ${key}`);
|
|
864
|
+
await this.setItem(key, decrypted);
|
|
865
|
+
this.logger.timeEnd(`getItem:${key}`);
|
|
866
|
+
return decrypted;
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
catch {
|
|
870
|
+
// Not JSON, 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
|
+
// Check expiration
|
|
877
|
+
if (storedValue.expiresAt && storedValue.expiresAt < Date.now()) {
|
|
878
|
+
this.logger.info(`Key expired: ${key}`);
|
|
879
|
+
await this.removeItem(key);
|
|
880
|
+
this.eventEmitter.emit('expired', { key });
|
|
881
|
+
this.logger.timeEnd(`getItem:${key}`);
|
|
882
|
+
return null;
|
|
883
|
+
}
|
|
884
|
+
// Verify integrity if checksum exists
|
|
885
|
+
if (storedValue.checksum) {
|
|
886
|
+
const calculatedChecksum = await this.calculateChecksum(storedValue.value);
|
|
887
|
+
if (calculatedChecksum !== storedValue.checksum) {
|
|
888
|
+
this.logger.warn(`Integrity check failed for key: ${key}`);
|
|
889
|
+
this.eventEmitter.emit('error', {
|
|
890
|
+
key,
|
|
891
|
+
error: new Error('Integrity verification failed')
|
|
892
|
+
});
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
// Decompress if needed
|
|
896
|
+
let finalValue = storedValue.value;
|
|
897
|
+
if (storedValue.compressed) {
|
|
898
|
+
this.logger.debug(`Decompressing value for key: ${key}`);
|
|
899
|
+
const compressedData = this.encryptionHelper['base64ToArrayBuffer'](storedValue.value);
|
|
900
|
+
finalValue = await decompress(new Uint8Array(compressedData));
|
|
901
|
+
this.eventEmitter.emit('decompressed', { key });
|
|
902
|
+
}
|
|
903
|
+
this.eventEmitter.emit('decrypted', { key });
|
|
904
|
+
this.logger.timeEnd(`getItem:${key}`);
|
|
905
|
+
return finalValue;
|
|
906
|
+
}
|
|
907
|
+
catch (error) {
|
|
908
|
+
this.logger.error(`Error al recuperar dato encriptado para ${key}:`, error);
|
|
909
|
+
this.eventEmitter.emit('error', { key, error: error });
|
|
910
|
+
// Fallback: try plain key
|
|
911
|
+
const fallback = localStorage.getItem(key);
|
|
912
|
+
this.logger.timeEnd(`getItem:${key}`);
|
|
913
|
+
return fallback;
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Elimina un valor de localStorage
|
|
918
|
+
*/
|
|
919
|
+
async removeItem(key) {
|
|
920
|
+
if (!EncryptionHelper.isSupported()) {
|
|
921
|
+
localStorage.removeItem(key);
|
|
922
|
+
return;
|
|
923
|
+
}
|
|
924
|
+
try {
|
|
925
|
+
const encryptedKey = await this.encryptionHelper.encryptKey(key);
|
|
926
|
+
localStorage.removeItem(encryptedKey);
|
|
927
|
+
localStorage.removeItem(key); // Remove both versions
|
|
928
|
+
this.eventEmitter.emit('deleted', { key });
|
|
929
|
+
this.logger.info(`Removed key: ${key}`);
|
|
930
|
+
}
|
|
931
|
+
catch (error) {
|
|
932
|
+
this.logger.error(`Error al eliminar dato para ${key}:`, error);
|
|
933
|
+
localStorage.removeItem(key);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
/**
|
|
937
|
+
* Verifica si existe un valor para la clave dada
|
|
938
|
+
*/
|
|
939
|
+
async hasItem(key) {
|
|
940
|
+
const value = await this.getItem(key);
|
|
941
|
+
return value !== null;
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* Limpia todos los datos encriptados
|
|
945
|
+
*/
|
|
946
|
+
clear() {
|
|
947
|
+
this.encryptionHelper.clearEncryptedData();
|
|
948
|
+
this.eventEmitter.emit('cleared', {});
|
|
949
|
+
this.logger.info('All encrypted data cleared');
|
|
950
|
+
}
|
|
951
|
+
/**
|
|
952
|
+
* Limpia todos los items expirados
|
|
953
|
+
*/
|
|
954
|
+
async cleanExpired() {
|
|
955
|
+
this.logger.info('Starting cleanup of expired items...');
|
|
956
|
+
let cleanedCount = 0;
|
|
957
|
+
const keysToCheck = [];
|
|
958
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
959
|
+
const key = localStorage.key(i);
|
|
960
|
+
if (key && key.startsWith('__enc_')) {
|
|
961
|
+
keysToCheck.push(key);
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
for (const encryptedKey of keysToCheck) {
|
|
965
|
+
try {
|
|
966
|
+
const encryptedValue = localStorage.getItem(encryptedKey);
|
|
967
|
+
if (!encryptedValue)
|
|
968
|
+
continue;
|
|
969
|
+
const decrypted = await this.encryptionHelper.decrypt(encryptedValue);
|
|
970
|
+
const storedValue = JSON.parse(decrypted);
|
|
971
|
+
if (storedValue.expiresAt && storedValue.expiresAt < Date.now()) {
|
|
972
|
+
localStorage.removeItem(encryptedKey);
|
|
973
|
+
cleanedCount++;
|
|
974
|
+
this.eventEmitter.emit('expired', { key: encryptedKey });
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
catch (error) {
|
|
978
|
+
this.logger.warn(`Failed to check expiration for ${encryptedKey}:`, error);
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
this.logger.info(`Cleanup completed. Removed ${cleanedCount} expired items`);
|
|
982
|
+
return cleanedCount;
|
|
983
|
+
}
|
|
984
|
+
/**
|
|
985
|
+
* Verifica la integridad de un valor almacenado
|
|
986
|
+
*/
|
|
987
|
+
async verifyIntegrity(key) {
|
|
988
|
+
try {
|
|
989
|
+
const encryptedKey = await this.encryptionHelper.encryptKey(key);
|
|
990
|
+
const encryptedValue = localStorage.getItem(encryptedKey);
|
|
991
|
+
if (!encryptedValue)
|
|
992
|
+
return false;
|
|
993
|
+
const decrypted = await this.encryptionHelper.decrypt(encryptedValue);
|
|
994
|
+
const storedValue = JSON.parse(decrypted);
|
|
995
|
+
if (!storedValue.checksum) {
|
|
996
|
+
this.logger.warn(`No checksum found for key: ${key}`);
|
|
997
|
+
return true; // No checksum to verify
|
|
998
|
+
}
|
|
999
|
+
const calculatedChecksum = await this.calculateChecksum(storedValue.value);
|
|
1000
|
+
return calculatedChecksum === storedValue.checksum;
|
|
1001
|
+
}
|
|
1002
|
+
catch (error) {
|
|
1003
|
+
this.logger.error(`Error verifying integrity for ${key}:`, error);
|
|
1004
|
+
return false;
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
/**
|
|
1008
|
+
* Obtiene información de integridad de un valor
|
|
1009
|
+
*/
|
|
1010
|
+
async getIntegrityInfo(key) {
|
|
1011
|
+
try {
|
|
1012
|
+
const encryptedKey = await this.encryptionHelper.encryptKey(key);
|
|
1013
|
+
const encryptedValue = localStorage.getItem(encryptedKey);
|
|
1014
|
+
if (!encryptedValue)
|
|
1015
|
+
return null;
|
|
1016
|
+
const decrypted = await this.encryptionHelper.decrypt(encryptedValue);
|
|
1017
|
+
const storedValue = JSON.parse(decrypted);
|
|
1018
|
+
const valid = storedValue.checksum
|
|
1019
|
+
? await this.calculateChecksum(storedValue.value) === storedValue.checksum
|
|
1020
|
+
: true;
|
|
1021
|
+
return {
|
|
1022
|
+
valid,
|
|
1023
|
+
lastModified: storedValue.modifiedAt,
|
|
1024
|
+
checksum: storedValue.checksum || '',
|
|
1025
|
+
version: storedValue.version,
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
catch (error) {
|
|
1029
|
+
this.logger.error(`Error getting integrity info for ${key}:`, error);
|
|
1030
|
+
return null;
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
/**
|
|
1034
|
+
* Crea un namespace para organizar datos
|
|
1035
|
+
*/
|
|
1036
|
+
namespace(name) {
|
|
1037
|
+
this.logger.debug(`Creating namespace: ${name}`);
|
|
1038
|
+
return new NamespacedStorage(this, name);
|
|
1039
|
+
}
|
|
1040
|
+
/**
|
|
1041
|
+
* Rota todas las claves de encriptación
|
|
1042
|
+
*/
|
|
1043
|
+
async rotateKeys() {
|
|
1044
|
+
this.logger.info('Starting key rotation...');
|
|
1045
|
+
await this.keyRotation.rotateKeys();
|
|
1046
|
+
this.eventEmitter.emit('keyRotated', {});
|
|
1047
|
+
this.logger.info('Key rotation completed');
|
|
1048
|
+
}
|
|
1049
|
+
/**
|
|
1050
|
+
* Exporta todos los datos encriptados como backup
|
|
1051
|
+
*/
|
|
1052
|
+
async exportEncryptedData() {
|
|
1053
|
+
return this.keyRotation.exportEncryptedData();
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Importa datos desde un backup
|
|
1057
|
+
*/
|
|
1058
|
+
async importEncryptedData(backup) {
|
|
1059
|
+
return this.keyRotation.importEncryptedData(backup);
|
|
1060
|
+
}
|
|
1061
|
+
/**
|
|
1062
|
+
* Registra un listener de eventos
|
|
1063
|
+
*/
|
|
1064
|
+
on(event, listener) {
|
|
1065
|
+
this.eventEmitter.on(event, listener);
|
|
1066
|
+
}
|
|
1067
|
+
/**
|
|
1068
|
+
* Registra un listener de un solo uso
|
|
1069
|
+
*/
|
|
1070
|
+
once(event, listener) {
|
|
1071
|
+
this.eventEmitter.once(event, listener);
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* Elimina un listener de eventos
|
|
1075
|
+
*/
|
|
1076
|
+
off(event, listener) {
|
|
1077
|
+
this.eventEmitter.off(event, listener);
|
|
1078
|
+
}
|
|
1079
|
+
/**
|
|
1080
|
+
* Elimina todos los listeners de un evento
|
|
1081
|
+
*/
|
|
1082
|
+
removeAllListeners(event) {
|
|
1083
|
+
this.eventEmitter.removeAllListeners(event);
|
|
1084
|
+
}
|
|
1085
|
+
/**
|
|
1086
|
+
* Migra datos existentes no encriptados a formato encriptado
|
|
1087
|
+
*/
|
|
1088
|
+
async migrateExistingData(keys) {
|
|
1089
|
+
if (!EncryptionHelper.isSupported()) {
|
|
1090
|
+
this.logger.warn('Web Crypto API no soportada, no se puede migrar');
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
this.logger.info(`Iniciando migración de ${keys.length} claves...`);
|
|
1094
|
+
for (const key of keys) {
|
|
1095
|
+
try {
|
|
1096
|
+
const value = localStorage.getItem(key);
|
|
1097
|
+
if (value === null)
|
|
1098
|
+
continue;
|
|
1099
|
+
// Try to decrypt to check if already encrypted
|
|
1100
|
+
try {
|
|
1101
|
+
await this.encryptionHelper.decrypt(value);
|
|
1102
|
+
this.logger.info(`✓ ${key} ya está encriptado, saltando`);
|
|
1103
|
+
continue;
|
|
1104
|
+
}
|
|
1105
|
+
catch {
|
|
1106
|
+
// Not encrypted, proceed with migration
|
|
1107
|
+
}
|
|
1108
|
+
await this.setItem(key, value);
|
|
1109
|
+
localStorage.removeItem(key);
|
|
1110
|
+
this.logger.info(`✓ ${key} migrado exitosamente`);
|
|
1111
|
+
}
|
|
1112
|
+
catch (error) {
|
|
1113
|
+
this.logger.error(`✗ Error al migrar ${key}:`, error);
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
this.logger.info('✅ Migración completada');
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* Obtiene información de debug sobre el estado del almacenamiento
|
|
1120
|
+
*/
|
|
1121
|
+
getDebugInfo() {
|
|
1122
|
+
const allKeys = [];
|
|
1123
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
1124
|
+
const key = localStorage.key(i);
|
|
1125
|
+
if (key)
|
|
1126
|
+
allKeys.push(key);
|
|
1127
|
+
}
|
|
1128
|
+
const encryptedKeys = allKeys.filter(key => key.startsWith('__enc_'));
|
|
1129
|
+
const unencryptedKeys = allKeys.filter(key => !key.startsWith('__enc_') && key !== '__app_salt' && key !== '__key_version');
|
|
1130
|
+
return {
|
|
1131
|
+
cryptoSupported: EncryptionHelper.isSupported(),
|
|
1132
|
+
encryptedKeys,
|
|
1133
|
+
unencryptedKeys,
|
|
1134
|
+
totalKeys: allKeys.length,
|
|
1135
|
+
config: this.config,
|
|
1136
|
+
};
|
|
1137
|
+
}
|
|
1138
|
+
/**
|
|
1139
|
+
* Calcula el checksum SHA-256 de un valor
|
|
1140
|
+
*/
|
|
1141
|
+
async calculateChecksum(value) {
|
|
1142
|
+
const encoder = new TextEncoder();
|
|
1143
|
+
const data = encoder.encode(value);
|
|
1144
|
+
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
|
|
1145
|
+
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
1146
|
+
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
|
|
1147
|
+
}
|
|
1148
|
+
/**
|
|
1149
|
+
* Cleanup on destroy
|
|
1150
|
+
*/
|
|
1151
|
+
destroy() {
|
|
1152
|
+
if (this.cleanupInterval) {
|
|
1153
|
+
clearInterval(this.cleanupInterval);
|
|
1154
|
+
this.cleanupInterval = null;
|
|
1155
|
+
}
|
|
1156
|
+
this.removeAllListeners();
|
|
1157
|
+
this.logger.info('SecureStorage destroyed');
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
SecureStorage.instance = null;
|
|
1161
|
+
|
|
1162
|
+
const secureStorage$1 = SecureStorage.getInstance();
|
|
1163
|
+
/**
|
|
1164
|
+
* Función de debug para verificar el estado del sistema de encriptación
|
|
1165
|
+
* Muestra información detallada en la consola
|
|
1166
|
+
*/
|
|
1167
|
+
async function debugEncryptionState() {
|
|
1168
|
+
console.group('🔐 Estado del Sistema de Encriptación');
|
|
1169
|
+
console.log('Soporte Crypto API:', EncryptionHelper.isSupported());
|
|
1170
|
+
// Obtener información de debug
|
|
1171
|
+
const debugInfo = secureStorage$1.getDebugInfo();
|
|
1172
|
+
console.log('Claves encriptadas:', debugInfo.encryptedKeys.length);
|
|
1173
|
+
console.log('Claves sin encriptar:', debugInfo.unencryptedKeys);
|
|
1174
|
+
console.log('Total de claves:', debugInfo.totalKeys);
|
|
1175
|
+
if (debugInfo.encryptedKeys.length > 0) {
|
|
1176
|
+
console.log('✅ Datos encriptados encontrados:');
|
|
1177
|
+
debugInfo.encryptedKeys.forEach(key => {
|
|
1178
|
+
const value = localStorage.getItem(key);
|
|
1179
|
+
console.log(` ${key}: ${value?.substring(0, 30)}...`);
|
|
1180
|
+
});
|
|
1181
|
+
}
|
|
1182
|
+
else {
|
|
1183
|
+
console.log('⚠️ No se encontraron datos encriptados');
|
|
1184
|
+
}
|
|
1185
|
+
if (debugInfo.unencryptedKeys.length > 0) {
|
|
1186
|
+
console.log('⚠️ Claves sin encriptar encontradas:');
|
|
1187
|
+
debugInfo.unencryptedKeys.forEach(key => {
|
|
1188
|
+
console.log(` ${key}`);
|
|
1189
|
+
});
|
|
1190
|
+
}
|
|
1191
|
+
console.groupEnd();
|
|
1192
|
+
}
|
|
1193
|
+
/**
|
|
1194
|
+
* Fuerza la migración de claves comunes a formato encriptado
|
|
1195
|
+
* Útil para desarrollo y testing
|
|
1196
|
+
*/
|
|
1197
|
+
async function forceMigration(customKeys) {
|
|
1198
|
+
const defaultKeys = [
|
|
1199
|
+
'accessToken',
|
|
1200
|
+
'refreshToken',
|
|
1201
|
+
'user',
|
|
1202
|
+
'sessionId',
|
|
1203
|
+
'authToken',
|
|
1204
|
+
'userData',
|
|
1205
|
+
];
|
|
1206
|
+
const keysToMigrate = customKeys || defaultKeys;
|
|
1207
|
+
console.log(`🔄 Iniciando migración forzada de ${keysToMigrate.length} claves...`);
|
|
1208
|
+
await secureStorage$1.migrateExistingData(keysToMigrate);
|
|
1209
|
+
console.log('✅ Migración forzada completada');
|
|
1210
|
+
// Mostrar estado después de la migración
|
|
1211
|
+
await debugEncryptionState();
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
/**
|
|
1215
|
+
* @bantis/local-cipher - Core Module
|
|
1216
|
+
* Framework-agnostic client-side encryption for browser storage
|
|
1217
|
+
*
|
|
1218
|
+
* @version 2.1.0
|
|
1219
|
+
* @license MIT
|
|
1220
|
+
*/
|
|
1221
|
+
// Core classes
|
|
1222
|
+
const secureStorage = SecureStorage.getInstance();
|
|
1223
|
+
// Version
|
|
1224
|
+
const VERSION = '2.1.0';
|
|
1225
|
+
|
|
1226
|
+
/******************************************************************************
|
|
1227
|
+
Copyright (c) Microsoft Corporation.
|
|
1228
|
+
|
|
1229
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
1230
|
+
purpose with or without fee is hereby granted.
|
|
1231
|
+
|
|
1232
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
1233
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
1234
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
1235
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
1236
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
1237
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
1238
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
1239
|
+
***************************************************************************** */
|
|
1240
|
+
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
|
|
1241
|
+
|
|
1242
|
+
|
|
1243
|
+
function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
|
|
1244
|
+
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
|
|
1245
|
+
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
|
|
1246
|
+
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
|
|
1247
|
+
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
|
|
1248
|
+
var _, done = false;
|
|
1249
|
+
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
1250
|
+
var context = {};
|
|
1251
|
+
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
|
|
1252
|
+
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
|
|
1253
|
+
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
|
|
1254
|
+
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
|
|
1255
|
+
if (kind === "accessor") {
|
|
1256
|
+
if (result === void 0) continue;
|
|
1257
|
+
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
|
|
1258
|
+
if (_ = accept(result.get)) descriptor.get = _;
|
|
1259
|
+
if (_ = accept(result.set)) descriptor.set = _;
|
|
1260
|
+
if (_ = accept(result.init)) initializers.unshift(_);
|
|
1261
|
+
}
|
|
1262
|
+
else if (_ = accept(result)) {
|
|
1263
|
+
if (kind === "field") initializers.unshift(_);
|
|
1264
|
+
else descriptor[key] = _;
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
if (target) Object.defineProperty(target, contextIn.name, descriptor);
|
|
1268
|
+
done = true;
|
|
1269
|
+
}
|
|
1270
|
+
function __runInitializers(thisArg, initializers, value) {
|
|
1271
|
+
var useValue = arguments.length > 2;
|
|
1272
|
+
for (var i = 0; i < initializers.length; i++) {
|
|
1273
|
+
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
|
|
1274
|
+
}
|
|
1275
|
+
return useValue ? value : void 0;
|
|
1276
|
+
}
|
|
1277
|
+
function __setFunctionName(f, name, prefix) {
|
|
1278
|
+
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
|
|
1279
|
+
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
|
|
1280
|
+
}
|
|
1281
|
+
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
|
1282
|
+
var e = new Error(message);
|
|
1283
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
1284
|
+
};
|
|
1285
|
+
|
|
1286
|
+
/**
|
|
1287
|
+
* Servicio de Angular para SecureStorage v2
|
|
1288
|
+
* Proporciona una API reactiva usando RxJS Observables
|
|
1289
|
+
*
|
|
1290
|
+
* @example
|
|
1291
|
+
* constructor(private secureStorage: SecureStorageService) {}
|
|
1292
|
+
*
|
|
1293
|
+
* // Guardar
|
|
1294
|
+
* this.secureStorage.setItem('token', 'abc123').subscribe();
|
|
1295
|
+
*
|
|
1296
|
+
* // Leer
|
|
1297
|
+
* this.secureStorage.getItem('token').subscribe(token => console.log(token));
|
|
1298
|
+
*
|
|
1299
|
+
* // Escuchar eventos
|
|
1300
|
+
* this.secureStorage.events$.subscribe(event => console.log(event));
|
|
1301
|
+
*/
|
|
1302
|
+
let SecureStorageService = (() => {
|
|
1303
|
+
let _classDecorators = [core.Injectable({
|
|
1304
|
+
providedIn: 'root'
|
|
1305
|
+
})];
|
|
1306
|
+
let _classDescriptor;
|
|
1307
|
+
let _classExtraInitializers = [];
|
|
1308
|
+
let _classThis;
|
|
1309
|
+
_classThis = class {
|
|
1310
|
+
constructor(config) {
|
|
1311
|
+
this.debugInfo$ = new rxjs.BehaviorSubject(this.getDebugInfo());
|
|
1312
|
+
this.eventsSubject$ = new rxjs.Subject();
|
|
1313
|
+
/**
|
|
1314
|
+
* Observable de eventos de storage
|
|
1315
|
+
*/
|
|
1316
|
+
this.events$ = this.eventsSubject$.asObservable();
|
|
1317
|
+
this.storage = SecureStorage.getInstance(config);
|
|
1318
|
+
// Setup event forwarding to Observable
|
|
1319
|
+
this.storage.on('encrypted', (data) => this.eventsSubject$.next(data));
|
|
1320
|
+
this.storage.on('decrypted', (data) => this.eventsSubject$.next(data));
|
|
1321
|
+
this.storage.on('deleted', (data) => this.eventsSubject$.next(data));
|
|
1322
|
+
this.storage.on('cleared', (data) => this.eventsSubject$.next(data));
|
|
1323
|
+
this.storage.on('expired', (data) => this.eventsSubject$.next(data));
|
|
1324
|
+
this.storage.on('error', (data) => this.eventsSubject$.next(data));
|
|
1325
|
+
this.storage.on('keyRotated', (data) => this.eventsSubject$.next(data));
|
|
1326
|
+
this.storage.on('compressed', (data) => this.eventsSubject$.next(data));
|
|
1327
|
+
this.storage.on('decompressed', (data) => this.eventsSubject$.next(data));
|
|
1328
|
+
// Actualizar debug info cada segundo
|
|
1329
|
+
setInterval(() => {
|
|
1330
|
+
this.debugInfo$.next(this.getDebugInfo());
|
|
1331
|
+
}, 1000);
|
|
1332
|
+
}
|
|
1333
|
+
/**
|
|
1334
|
+
* Guarda un valor encriptado
|
|
1335
|
+
* @param key - Clave
|
|
1336
|
+
* @param value - Valor a guardar
|
|
1337
|
+
* @returns Observable que completa cuando se guarda
|
|
1338
|
+
*/
|
|
1339
|
+
setItem(key, value) {
|
|
1340
|
+
return rxjs.from(this.storage.setItem(key, value));
|
|
1341
|
+
}
|
|
1342
|
+
/**
|
|
1343
|
+
* Guarda un valor con expiración
|
|
1344
|
+
* @param key - Clave
|
|
1345
|
+
* @param value - Valor a guardar
|
|
1346
|
+
* @param options - Opciones de expiración
|
|
1347
|
+
* @returns Observable que completa cuando se guarda
|
|
1348
|
+
*/
|
|
1349
|
+
setItemWithExpiry(key, value, options) {
|
|
1350
|
+
return rxjs.from(this.storage.setItemWithExpiry(key, value, options));
|
|
1351
|
+
}
|
|
1352
|
+
/**
|
|
1353
|
+
* Recupera un valor desencriptado
|
|
1354
|
+
* @param key - Clave
|
|
1355
|
+
* @returns Observable con el valor o null
|
|
1356
|
+
*/
|
|
1357
|
+
getItem(key) {
|
|
1358
|
+
return rxjs.from(this.storage.getItem(key));
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* Elimina un valor
|
|
1362
|
+
* @param key - Clave a eliminar
|
|
1363
|
+
* @returns Observable que completa cuando se elimina
|
|
1364
|
+
*/
|
|
1365
|
+
removeItem(key) {
|
|
1366
|
+
return rxjs.from(this.storage.removeItem(key));
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* Verifica si existe una clave
|
|
1370
|
+
* @param key - Clave a verificar
|
|
1371
|
+
* @returns Observable con true/false
|
|
1372
|
+
*/
|
|
1373
|
+
hasItem(key) {
|
|
1374
|
+
return rxjs.from(this.storage.hasItem(key));
|
|
1375
|
+
}
|
|
1376
|
+
/**
|
|
1377
|
+
* Limpia todos los datos encriptados
|
|
1378
|
+
*/
|
|
1379
|
+
clear() {
|
|
1380
|
+
this.storage.clear();
|
|
1381
|
+
}
|
|
1382
|
+
/**
|
|
1383
|
+
* Limpia todos los items expirados
|
|
1384
|
+
* @returns Observable con el número de items eliminados
|
|
1385
|
+
*/
|
|
1386
|
+
cleanExpired() {
|
|
1387
|
+
return rxjs.from(this.storage.cleanExpired());
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* Verifica la integridad de un valor
|
|
1391
|
+
* @param key - Clave a verificar
|
|
1392
|
+
* @returns Observable con true si es válido
|
|
1393
|
+
*/
|
|
1394
|
+
verifyIntegrity(key) {
|
|
1395
|
+
return rxjs.from(this.storage.verifyIntegrity(key));
|
|
1396
|
+
}
|
|
1397
|
+
/**
|
|
1398
|
+
* Obtiene información de integridad de un valor
|
|
1399
|
+
* @param key - Clave
|
|
1400
|
+
* @returns Observable con información de integridad
|
|
1401
|
+
*/
|
|
1402
|
+
getIntegrityInfo(key) {
|
|
1403
|
+
return rxjs.from(this.storage.getIntegrityInfo(key));
|
|
1404
|
+
}
|
|
1405
|
+
/**
|
|
1406
|
+
* Crea un namespace para organizar datos
|
|
1407
|
+
* @param name - Nombre del namespace
|
|
1408
|
+
* @returns Instancia de NamespacedStorage
|
|
1409
|
+
*/
|
|
1410
|
+
namespace(name) {
|
|
1411
|
+
return this.storage.namespace(name);
|
|
1412
|
+
}
|
|
1413
|
+
/**
|
|
1414
|
+
* Rota todas las claves de encriptación
|
|
1415
|
+
* @returns Observable que completa cuando termina la rotación
|
|
1416
|
+
*/
|
|
1417
|
+
rotateKeys() {
|
|
1418
|
+
return rxjs.from(this.storage.rotateKeys());
|
|
1419
|
+
}
|
|
1420
|
+
/**
|
|
1421
|
+
* Exporta todos los datos como backup
|
|
1422
|
+
* @returns Observable con el backup
|
|
1423
|
+
*/
|
|
1424
|
+
exportEncryptedData() {
|
|
1425
|
+
return rxjs.from(this.storage.exportEncryptedData());
|
|
1426
|
+
}
|
|
1427
|
+
/**
|
|
1428
|
+
* Importa datos desde un backup
|
|
1429
|
+
* @param backup - Backup a importar
|
|
1430
|
+
* @returns Observable que completa cuando termina la importación
|
|
1431
|
+
*/
|
|
1432
|
+
importEncryptedData(backup) {
|
|
1433
|
+
return rxjs.from(this.storage.importEncryptedData(backup));
|
|
1434
|
+
}
|
|
1435
|
+
/**
|
|
1436
|
+
* Migra datos existentes a formato encriptado
|
|
1437
|
+
* @param keys - Array de claves a migrar
|
|
1438
|
+
* @returns Observable que completa cuando termina la migración
|
|
1439
|
+
*/
|
|
1440
|
+
migrateExistingData(keys) {
|
|
1441
|
+
return rxjs.from(this.storage.migrateExistingData(keys));
|
|
1442
|
+
}
|
|
1443
|
+
/**
|
|
1444
|
+
* Obtiene información de debug como Observable
|
|
1445
|
+
* @returns Observable con información de debug que se actualiza automáticamente
|
|
1446
|
+
*/
|
|
1447
|
+
getDebugInfo$() {
|
|
1448
|
+
return this.debugInfo$.asObservable();
|
|
1449
|
+
}
|
|
1450
|
+
/**
|
|
1451
|
+
* Obtiene información de debug de forma síncrona
|
|
1452
|
+
*/
|
|
1453
|
+
getDebugInfo() {
|
|
1454
|
+
return this.storage.getDebugInfo();
|
|
1455
|
+
}
|
|
1456
|
+
/**
|
|
1457
|
+
* Helper para guardar objetos JSON
|
|
1458
|
+
* @param key - Clave
|
|
1459
|
+
* @param value - Objeto a guardar
|
|
1460
|
+
*/
|
|
1461
|
+
setObject(key, value) {
|
|
1462
|
+
return this.setItem(key, JSON.stringify(value));
|
|
1463
|
+
}
|
|
1464
|
+
/**
|
|
1465
|
+
* Helper para guardar objetos JSON con expiración
|
|
1466
|
+
* @param key - Clave
|
|
1467
|
+
* @param value - Objeto a guardar
|
|
1468
|
+
* @param options - Opciones de expiración
|
|
1469
|
+
*/
|
|
1470
|
+
setObjectWithExpiry(key, value, options) {
|
|
1471
|
+
return this.setItemWithExpiry(key, JSON.stringify(value), options);
|
|
1472
|
+
}
|
|
1473
|
+
/**
|
|
1474
|
+
* Helper para recuperar objetos JSON
|
|
1475
|
+
* @param key - Clave
|
|
1476
|
+
* @returns Observable con el objeto parseado o null
|
|
1477
|
+
*/
|
|
1478
|
+
getObject(key) {
|
|
1479
|
+
return this.getItem(key).pipe(operators.map(value => value ? JSON.parse(value) : null), operators.catchError(() => rxjs.from([null])));
|
|
1480
|
+
}
|
|
1481
|
+
/**
|
|
1482
|
+
* Registra un listener para un tipo de evento específico
|
|
1483
|
+
* @param event - Tipo de evento
|
|
1484
|
+
* @param handler - Función manejadora
|
|
1485
|
+
*/
|
|
1486
|
+
on(event, handler) {
|
|
1487
|
+
this.storage.on(event, handler);
|
|
1488
|
+
}
|
|
1489
|
+
/**
|
|
1490
|
+
* Elimina un listener de evento
|
|
1491
|
+
* @param event - Tipo de evento
|
|
1492
|
+
* @param handler - Función manejadora
|
|
1493
|
+
*/
|
|
1494
|
+
off(event, handler) {
|
|
1495
|
+
this.storage.off(event, handler);
|
|
1496
|
+
}
|
|
1497
|
+
/**
|
|
1498
|
+
* Observable filtrado por tipo de evento
|
|
1499
|
+
* @param eventType - Tipo de evento a filtrar
|
|
1500
|
+
* @returns Observable con eventos del tipo especificado
|
|
1501
|
+
*/
|
|
1502
|
+
onEvent$(eventType) {
|
|
1503
|
+
return this.events$.pipe(operators.map(event => event.type === eventType ? event : null), operators.map(event => event));
|
|
1504
|
+
}
|
|
1505
|
+
};
|
|
1506
|
+
__setFunctionName(_classThis, "SecureStorageService");
|
|
1507
|
+
(() => {
|
|
1508
|
+
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
|
|
1509
|
+
__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
|
|
1510
|
+
_classThis = _classDescriptor.value;
|
|
1511
|
+
if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
|
|
1512
|
+
__runInitializers(_classThis, _classExtraInitializers);
|
|
1513
|
+
})();
|
|
1514
|
+
return _classThis;
|
|
1515
|
+
})();
|
|
1516
|
+
|
|
1517
|
+
exports.DEFAULT_CONFIG = DEFAULT_CONFIG;
|
|
1518
|
+
exports.EncryptionHelper = EncryptionHelper;
|
|
1519
|
+
exports.EventEmitter = EventEmitter;
|
|
1520
|
+
exports.KeyRotation = KeyRotation;
|
|
1521
|
+
exports.LIBRARY_VERSION = LIBRARY_VERSION;
|
|
1522
|
+
exports.Logger = Logger;
|
|
1523
|
+
exports.NamespacedStorage = NamespacedStorage;
|
|
1524
|
+
exports.STORAGE_VERSION = STORAGE_VERSION;
|
|
1525
|
+
exports.SecureStorage = SecureStorage;
|
|
1526
|
+
exports.SecureStorageService = SecureStorageService;
|
|
1527
|
+
exports.VERSION = VERSION;
|
|
1528
|
+
exports.compress = compress;
|
|
1529
|
+
exports.debugEncryptionState = debugEncryptionState;
|
|
1530
|
+
exports.decompress = decompress;
|
|
1531
|
+
exports.forceMigration = forceMigration;
|
|
1532
|
+
exports.isCompressionSupported = isCompressionSupported;
|
|
1533
|
+
exports.secureStorage = secureStorage;
|
|
1534
|
+
exports.shouldCompress = shouldCompress;
|
|
1535
|
+
//# sourceMappingURL=angular.js.map
|