@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/dist/index.esm.js CHANGED
@@ -1,8 +1,3 @@
1
- import { useState, useEffect, useCallback } from 'react';
2
- import { Injectable } from '@angular/core';
3
- import { BehaviorSubject, Subject, from } from 'rxjs';
4
- import { map, catchError } from 'rxjs/operators';
5
-
6
1
  /**
7
2
  * Configuration types for @bantis/local-cipher
8
3
  */
@@ -1158,7 +1153,7 @@ class SecureStorage {
1158
1153
  }
1159
1154
  SecureStorage.instance = null;
1160
1155
 
1161
- const secureStorage$2 = SecureStorage.getInstance();
1156
+ const secureStorage$1 = SecureStorage.getInstance();
1162
1157
  /**
1163
1158
  * Función de debug para verificar el estado del sistema de encriptación
1164
1159
  * Muestra información detallada en la consola
@@ -1167,7 +1162,7 @@ async function debugEncryptionState() {
1167
1162
  console.group('🔐 Estado del Sistema de Encriptación');
1168
1163
  console.log('Soporte Crypto API:', EncryptionHelper.isSupported());
1169
1164
  // Obtener información de debug
1170
- const debugInfo = secureStorage$2.getDebugInfo();
1165
+ const debugInfo = secureStorage$1.getDebugInfo();
1171
1166
  console.log('Claves encriptadas:', debugInfo.encryptedKeys.length);
1172
1167
  console.log('Claves sin encriptar:', debugInfo.unencryptedKeys);
1173
1168
  console.log('Total de claves:', debugInfo.totalKeys);
@@ -1204,449 +1199,23 @@ async function forceMigration(customKeys) {
1204
1199
  ];
1205
1200
  const keysToMigrate = customKeys || defaultKeys;
1206
1201
  console.log(`🔄 Iniciando migración forzada de ${keysToMigrate.length} claves...`);
1207
- await secureStorage$2.migrateExistingData(keysToMigrate);
1202
+ await secureStorage$1.migrateExistingData(keysToMigrate);
1208
1203
  console.log('✅ Migración forzada completada');
1209
1204
  // Mostrar estado después de la migración
1210
1205
  await debugEncryptionState();
1211
1206
  }
1212
1207
 
1213
- // Allow custom storage instance or use default
1214
- let defaultStorage = null;
1215
- function getDefaultStorage() {
1216
- if (!defaultStorage) {
1217
- defaultStorage = SecureStorage.getInstance();
1218
- }
1219
- return defaultStorage;
1220
- }
1221
- /**
1222
- * Hook de React para usar SecureStorage de forma reactiva
1223
- * Similar a useState pero con persistencia encriptada
1224
- *
1225
- * @param key - Clave para almacenar en localStorage
1226
- * @param initialValue - Valor inicial si no existe en storage
1227
- * @param storage - Instancia personalizada de SecureStorage (opcional)
1228
- * @returns [value, setValue, loading, error]
1229
- *
1230
- * @example
1231
- * const [token, setToken, loading] = useSecureStorage('accessToken', '');
1232
- */
1233
- function useSecureStorage(key, initialValue, storage) {
1234
- const secureStorage = storage || getDefaultStorage();
1235
- const [storedValue, setStoredValue] = useState(initialValue);
1236
- const [loading, setLoading] = useState(true);
1237
- const [error, setError] = useState(null);
1238
- // Cargar valor inicial
1239
- useEffect(() => {
1240
- const loadValue = async () => {
1241
- try {
1242
- setLoading(true);
1243
- setError(null);
1244
- const item = await secureStorage.getItem(key);
1245
- if (item !== null) {
1246
- // Si T es un objeto, parsear JSON
1247
- if (typeof initialValue === 'object') {
1248
- setStoredValue(JSON.parse(item));
1249
- }
1250
- else {
1251
- setStoredValue(item);
1252
- }
1253
- }
1254
- else {
1255
- setStoredValue(initialValue);
1256
- }
1257
- }
1258
- catch (err) {
1259
- setError(err instanceof Error ? err : new Error('Error al cargar valor'));
1260
- setStoredValue(initialValue);
1261
- }
1262
- finally {
1263
- setLoading(false);
1264
- }
1265
- };
1266
- loadValue();
1267
- }, [key]); // Solo recargar si cambia la clave
1268
- // Función para actualizar el valor
1269
- const setValue = useCallback(async (value) => {
1270
- try {
1271
- setError(null);
1272
- setStoredValue(value);
1273
- // Si T es un objeto, convertir a JSON
1274
- const valueToStore = typeof value === 'object'
1275
- ? JSON.stringify(value)
1276
- : String(value);
1277
- await secureStorage.setItem(key, valueToStore);
1278
- }
1279
- catch (err) {
1280
- setError(err instanceof Error ? err : new Error('Error al guardar valor'));
1281
- throw err;
1282
- }
1283
- }, [key, secureStorage]);
1284
- return [storedValue, setValue, loading, error];
1285
- }
1286
- /**
1287
- * Hook para verificar si una clave existe en SecureStorage
1288
- *
1289
- * @param key - Clave a verificar
1290
- * @param storage - Instancia personalizada de SecureStorage (opcional)
1291
- * @returns [exists, loading, error]
1292
- *
1293
- * @example
1294
- * const [hasToken, loading] = useSecureStorageItem('accessToken');
1295
- */
1296
- function useSecureStorageItem(key, storage) {
1297
- const secureStorage = storage || getDefaultStorage();
1298
- const [exists, setExists] = useState(false);
1299
- const [loading, setLoading] = useState(true);
1300
- const [error, setError] = useState(null);
1301
- useEffect(() => {
1302
- const checkExists = async () => {
1303
- try {
1304
- setLoading(true);
1305
- setError(null);
1306
- const hasItem = await secureStorage.hasItem(key);
1307
- setExists(hasItem);
1308
- }
1309
- catch (err) {
1310
- setError(err instanceof Error ? err : new Error('Error al verificar clave'));
1311
- setExists(false);
1312
- }
1313
- finally {
1314
- setLoading(false);
1315
- }
1316
- };
1317
- checkExists();
1318
- }, [key, secureStorage]);
1319
- return [exists, loading, error];
1320
- }
1321
- /**
1322
- * Hook para obtener información de debug del almacenamiento
1323
- *
1324
- * @param storage - Instancia personalizada de SecureStorage (opcional)
1325
- * @returns Información de debug
1326
- *
1327
- * @example
1328
- * const debugInfo = useSecureStorageDebug();
1329
- * console.log(`Claves encriptadas: ${debugInfo.encryptedKeys.length}`);
1330
- */
1331
- function useSecureStorageDebug(storage) {
1332
- const secureStorage = storage || getDefaultStorage();
1333
- const [debugInfo, setDebugInfo] = useState(secureStorage.getDebugInfo());
1334
- useEffect(() => {
1335
- // Actualizar cada segundo
1336
- const interval = setInterval(() => {
1337
- setDebugInfo(secureStorage.getDebugInfo());
1338
- }, 1000);
1339
- return () => clearInterval(interval);
1340
- }, [secureStorage]);
1341
- return debugInfo;
1342
- }
1343
- /**
1344
- * Exportar la instancia de SecureStorage para uso directo
1345
- */
1346
- const secureStorage$1 = getDefaultStorage();
1347
-
1348
- /******************************************************************************
1349
- Copyright (c) Microsoft Corporation.
1350
-
1351
- Permission to use, copy, modify, and/or distribute this software for any
1352
- purpose with or without fee is hereby granted.
1353
-
1354
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1355
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1356
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1357
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1358
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1359
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1360
- PERFORMANCE OF THIS SOFTWARE.
1361
- ***************************************************************************** */
1362
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
1363
-
1364
-
1365
- function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
1366
- function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
1367
- var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
1368
- var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
1369
- var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
1370
- var _, done = false;
1371
- for (var i = decorators.length - 1; i >= 0; i--) {
1372
- var context = {};
1373
- for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
1374
- for (var p in contextIn.access) context.access[p] = contextIn.access[p];
1375
- context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
1376
- var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
1377
- if (kind === "accessor") {
1378
- if (result === void 0) continue;
1379
- if (result === null || typeof result !== "object") throw new TypeError("Object expected");
1380
- if (_ = accept(result.get)) descriptor.get = _;
1381
- if (_ = accept(result.set)) descriptor.set = _;
1382
- if (_ = accept(result.init)) initializers.unshift(_);
1383
- }
1384
- else if (_ = accept(result)) {
1385
- if (kind === "field") initializers.unshift(_);
1386
- else descriptor[key] = _;
1387
- }
1388
- }
1389
- if (target) Object.defineProperty(target, contextIn.name, descriptor);
1390
- done = true;
1391
- }
1392
- function __runInitializers(thisArg, initializers, value) {
1393
- var useValue = arguments.length > 2;
1394
- for (var i = 0; i < initializers.length; i++) {
1395
- value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
1396
- }
1397
- return useValue ? value : void 0;
1398
- }
1399
- function __setFunctionName(f, name, prefix) {
1400
- if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
1401
- return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
1402
- }
1403
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
1404
- var e = new Error(message);
1405
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
1406
- };
1407
-
1408
- /**
1409
- * Servicio de Angular para SecureStorage v2
1410
- * Proporciona una API reactiva usando RxJS Observables
1411
- *
1412
- * @example
1413
- * constructor(private secureStorage: SecureStorageService) {}
1414
- *
1415
- * // Guardar
1416
- * this.secureStorage.setItem('token', 'abc123').subscribe();
1417
- *
1418
- * // Leer
1419
- * this.secureStorage.getItem('token').subscribe(token => console.log(token));
1420
- *
1421
- * // Escuchar eventos
1422
- * this.secureStorage.events$.subscribe(event => console.log(event));
1423
- */
1424
- let SecureStorageService = (() => {
1425
- let _classDecorators = [Injectable({
1426
- providedIn: 'root'
1427
- })];
1428
- let _classDescriptor;
1429
- let _classExtraInitializers = [];
1430
- let _classThis;
1431
- _classThis = class {
1432
- constructor(config) {
1433
- this.debugInfo$ = new BehaviorSubject(this.getDebugInfo());
1434
- this.eventsSubject$ = new Subject();
1435
- /**
1436
- * Observable de eventos de storage
1437
- */
1438
- this.events$ = this.eventsSubject$.asObservable();
1439
- this.storage = SecureStorage.getInstance(config);
1440
- // Setup event forwarding to Observable
1441
- this.storage.on('encrypted', (data) => this.eventsSubject$.next(data));
1442
- this.storage.on('decrypted', (data) => this.eventsSubject$.next(data));
1443
- this.storage.on('deleted', (data) => this.eventsSubject$.next(data));
1444
- this.storage.on('cleared', (data) => this.eventsSubject$.next(data));
1445
- this.storage.on('expired', (data) => this.eventsSubject$.next(data));
1446
- this.storage.on('error', (data) => this.eventsSubject$.next(data));
1447
- this.storage.on('keyRotated', (data) => this.eventsSubject$.next(data));
1448
- this.storage.on('compressed', (data) => this.eventsSubject$.next(data));
1449
- this.storage.on('decompressed', (data) => this.eventsSubject$.next(data));
1450
- // Actualizar debug info cada segundo
1451
- setInterval(() => {
1452
- this.debugInfo$.next(this.getDebugInfo());
1453
- }, 1000);
1454
- }
1455
- /**
1456
- * Guarda un valor encriptado
1457
- * @param key - Clave
1458
- * @param value - Valor a guardar
1459
- * @returns Observable que completa cuando se guarda
1460
- */
1461
- setItem(key, value) {
1462
- return from(this.storage.setItem(key, value));
1463
- }
1464
- /**
1465
- * Guarda un valor con expiración
1466
- * @param key - Clave
1467
- * @param value - Valor a guardar
1468
- * @param options - Opciones de expiración
1469
- * @returns Observable que completa cuando se guarda
1470
- */
1471
- setItemWithExpiry(key, value, options) {
1472
- return from(this.storage.setItemWithExpiry(key, value, options));
1473
- }
1474
- /**
1475
- * Recupera un valor desencriptado
1476
- * @param key - Clave
1477
- * @returns Observable con el valor o null
1478
- */
1479
- getItem(key) {
1480
- return from(this.storage.getItem(key));
1481
- }
1482
- /**
1483
- * Elimina un valor
1484
- * @param key - Clave a eliminar
1485
- * @returns Observable que completa cuando se elimina
1486
- */
1487
- removeItem(key) {
1488
- return from(this.storage.removeItem(key));
1489
- }
1490
- /**
1491
- * Verifica si existe una clave
1492
- * @param key - Clave a verificar
1493
- * @returns Observable con true/false
1494
- */
1495
- hasItem(key) {
1496
- return from(this.storage.hasItem(key));
1497
- }
1498
- /**
1499
- * Limpia todos los datos encriptados
1500
- */
1501
- clear() {
1502
- this.storage.clear();
1503
- }
1504
- /**
1505
- * Limpia todos los items expirados
1506
- * @returns Observable con el número de items eliminados
1507
- */
1508
- cleanExpired() {
1509
- return from(this.storage.cleanExpired());
1510
- }
1511
- /**
1512
- * Verifica la integridad de un valor
1513
- * @param key - Clave a verificar
1514
- * @returns Observable con true si es válido
1515
- */
1516
- verifyIntegrity(key) {
1517
- return from(this.storage.verifyIntegrity(key));
1518
- }
1519
- /**
1520
- * Obtiene información de integridad de un valor
1521
- * @param key - Clave
1522
- * @returns Observable con información de integridad
1523
- */
1524
- getIntegrityInfo(key) {
1525
- return from(this.storage.getIntegrityInfo(key));
1526
- }
1527
- /**
1528
- * Crea un namespace para organizar datos
1529
- * @param name - Nombre del namespace
1530
- * @returns Instancia de NamespacedStorage
1531
- */
1532
- namespace(name) {
1533
- return this.storage.namespace(name);
1534
- }
1535
- /**
1536
- * Rota todas las claves de encriptación
1537
- * @returns Observable que completa cuando termina la rotación
1538
- */
1539
- rotateKeys() {
1540
- return from(this.storage.rotateKeys());
1541
- }
1542
- /**
1543
- * Exporta todos los datos como backup
1544
- * @returns Observable con el backup
1545
- */
1546
- exportEncryptedData() {
1547
- return from(this.storage.exportEncryptedData());
1548
- }
1549
- /**
1550
- * Importa datos desde un backup
1551
- * @param backup - Backup a importar
1552
- * @returns Observable que completa cuando termina la importación
1553
- */
1554
- importEncryptedData(backup) {
1555
- return from(this.storage.importEncryptedData(backup));
1556
- }
1557
- /**
1558
- * Migra datos existentes a formato encriptado
1559
- * @param keys - Array de claves a migrar
1560
- * @returns Observable que completa cuando termina la migración
1561
- */
1562
- migrateExistingData(keys) {
1563
- return from(this.storage.migrateExistingData(keys));
1564
- }
1565
- /**
1566
- * Obtiene información de debug como Observable
1567
- * @returns Observable con información de debug que se actualiza automáticamente
1568
- */
1569
- getDebugInfo$() {
1570
- return this.debugInfo$.asObservable();
1571
- }
1572
- /**
1573
- * Obtiene información de debug de forma síncrona
1574
- */
1575
- getDebugInfo() {
1576
- return this.storage.getDebugInfo();
1577
- }
1578
- /**
1579
- * Helper para guardar objetos JSON
1580
- * @param key - Clave
1581
- * @param value - Objeto a guardar
1582
- */
1583
- setObject(key, value) {
1584
- return this.setItem(key, JSON.stringify(value));
1585
- }
1586
- /**
1587
- * Helper para guardar objetos JSON con expiración
1588
- * @param key - Clave
1589
- * @param value - Objeto a guardar
1590
- * @param options - Opciones de expiración
1591
- */
1592
- setObjectWithExpiry(key, value, options) {
1593
- return this.setItemWithExpiry(key, JSON.stringify(value), options);
1594
- }
1595
- /**
1596
- * Helper para recuperar objetos JSON
1597
- * @param key - Clave
1598
- * @returns Observable con el objeto parseado o null
1599
- */
1600
- getObject(key) {
1601
- return this.getItem(key).pipe(map(value => value ? JSON.parse(value) : null), catchError(() => from([null])));
1602
- }
1603
- /**
1604
- * Registra un listener para un tipo de evento específico
1605
- * @param event - Tipo de evento
1606
- * @param handler - Función manejadora
1607
- */
1608
- on(event, handler) {
1609
- this.storage.on(event, handler);
1610
- }
1611
- /**
1612
- * Elimina un listener de evento
1613
- * @param event - Tipo de evento
1614
- * @param handler - Función manejadora
1615
- */
1616
- off(event, handler) {
1617
- this.storage.off(event, handler);
1618
- }
1619
- /**
1620
- * Observable filtrado por tipo de evento
1621
- * @param eventType - Tipo de evento a filtrar
1622
- * @returns Observable con eventos del tipo especificado
1623
- */
1624
- onEvent$(eventType) {
1625
- return this.events$.pipe(map(event => event.type === eventType ? event : null), map(event => event));
1626
- }
1627
- };
1628
- __setFunctionName(_classThis, "SecureStorageService");
1629
- (() => {
1630
- const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
1631
- __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
1632
- _classThis = _classDescriptor.value;
1633
- if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
1634
- __runInitializers(_classThis, _classExtraInitializers);
1635
- })();
1636
- return _classThis;
1637
- })();
1638
-
1639
1208
  /**
1640
- * @bantis/local-cipher v2.0.0
1641
- * Librería de cifrado local AES-256-GCM para Angular, React y JavaScript
1209
+ * @bantis/local-cipher - Core Module
1210
+ * Framework-agnostic client-side encryption for browser storage
1642
1211
  *
1643
- * @author MTT
1212
+ * @version 2.1.0
1644
1213
  * @license MIT
1645
1214
  */
1646
- // Core exports
1215
+ // Core classes
1647
1216
  const secureStorage = SecureStorage.getInstance();
1648
1217
  // Version
1649
- const VERSION = '2.0.0';
1218
+ const VERSION = '2.1.0';
1650
1219
 
1651
- export { DEFAULT_CONFIG, EncryptionHelper, EventEmitter, KeyRotation, LIBRARY_VERSION, Logger, NamespacedStorage, STORAGE_VERSION, SecureStorage, SecureStorageService, VERSION, compress, debugEncryptionState, decompress, forceMigration, isCompressionSupported, secureStorage$1 as reactSecureStorage, secureStorage, shouldCompress, useSecureStorage, useSecureStorageDebug, useSecureStorageItem };
1220
+ export { DEFAULT_CONFIG, EncryptionHelper, EventEmitter, KeyRotation, LIBRARY_VERSION, Logger, NamespacedStorage, STORAGE_VERSION, SecureStorage, VERSION, compress, debugEncryptionState, decompress, forceMigration, isCompressionSupported, secureStorage, shouldCompress };
1652
1221
  //# sourceMappingURL=index.esm.js.map