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