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