@katlux/providers 0.1.1-alpha.111 → 0.1.1-alpha.113

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.cjs CHANGED
@@ -256,29 +256,6 @@ class ADataProvider {
256
256
  deduplicate = true;
257
257
  context = null;
258
258
  urlPageParam = "";
259
- _selectedRows = [];
260
- get selectedRows() {
261
- return this._selectedRows;
262
- }
263
- set selectedRows(val) {
264
- this._selectedRows = Array.isArray(val) ? val : [];
265
- this._pendingChangedKeys.add("selectedRows");
266
- this.notify();
267
- }
268
- _selectAll = false;
269
- get selectAll() {
270
- return this._selectAll;
271
- }
272
- set selectAll(val) {
273
- if (this._selectAll !== val) {
274
- this._selectAll = val;
275
- this._pendingChangedKeys.add("selectAll");
276
- this.notify();
277
- }
278
- }
279
- getSelectedRows() {
280
- return this._selectAll ? this.pageData : this._selectedRows;
281
- }
282
259
  _currentPage = 1;
283
260
  _pageSize = 10;
284
261
  _filter = null;
@@ -359,10 +336,6 @@ class ADataProvider {
359
336
  const sortDebounceTime = typeof options?.sortDebounce === "number" ? options.sortDebounce : 200;
360
337
  this._debouncedFilterLoad = useDebounce(() => {
361
338
  this._currentPage = 1;
362
- this._selectAll = false;
363
- this._selectedRows = [];
364
- this._pendingChangedKeys.add("selectAll");
365
- this._pendingChangedKeys.add("selectedRows");
366
339
  this.loadPageData();
367
340
  }, filterDebounceTime);
368
341
  this._debouncedSortLoad = useDebounce(() => {
@@ -373,8 +346,6 @@ class ADataProvider {
373
346
  this.setSortList = this.setSortList.bind(this);
374
347
  this.setCurrentPage = this.setCurrentPage.bind(this);
375
348
  this.setPageSize = this.setPageSize.bind(this);
376
- this.setSelectedRows = this.setSelectedRows.bind(this);
377
- this.setSelectAll = this.setSelectAll.bind(this);
378
349
  this.loadPageData = this.loadPageData.bind(this);
379
350
  this.refresh = this.refresh.bind(this);
380
351
  this.subscribe = this.subscribe.bind(this);
@@ -476,9 +447,7 @@ class ADataProvider {
476
447
  initialLoad: this.initialLoad,
477
448
  error: this.error,
478
449
  filter: this._filter,
479
- sortList: this._sortList,
480
- selectedRows: this.selectedRows,
481
- selectAll: this.selectAll
450
+ sortList: this._sortList
482
451
  };
483
452
  }
484
453
  onFilterUpdated() {
@@ -510,14 +479,6 @@ class ADataProvider {
510
479
  this._pendingChangedKeys.add("currentPage");
511
480
  needsLoad = true;
512
481
  }
513
- if (partial.selectedRows !== void 0) {
514
- this._selectedRows = Array.isArray(partial.selectedRows) ? partial.selectedRows : [];
515
- this._pendingChangedKeys.add("selectedRows");
516
- }
517
- if (partial.selectAll !== void 0 && partial.selectAll !== this._selectAll) {
518
- this._selectAll = partial.selectAll;
519
- this._pendingChangedKeys.add("selectAll");
520
- }
521
482
  if (needsLoad) {
522
483
  if (options?.immediate) {
523
484
  this.cancelPending();
@@ -533,8 +494,7 @@ class ADataProvider {
533
494
  currentPage: this._currentPage,
534
495
  pageSize: this._pageSize,
535
496
  filter: this._filter,
536
- sortList: this._sortList,
537
- selectAll: this._selectAll
497
+ sortList: this._sortList
538
498
  };
539
499
  return JSON.stringify(state);
540
500
  }
@@ -557,12 +517,8 @@ class ADataProvider {
557
517
  this._filter = filter;
558
518
  this.onFilterUpdated();
559
519
  this._currentPage = 1;
560
- this._selectAll = false;
561
- this._selectedRows = [];
562
520
  this._pendingChangedKeys.add("filter");
563
521
  this._pendingChangedKeys.add("currentPage");
564
- this._pendingChangedKeys.add("selectAll");
565
- this._pendingChangedKeys.add("selectedRows");
566
522
  if (immediate) {
567
523
  this._debouncedFilterLoad?.cancel?.();
568
524
  this.loadPageData();
@@ -585,9 +541,7 @@ class ADataProvider {
585
541
  }
586
542
  setCurrentPage(currentPage) {
587
543
  this._currentPage = currentPage;
588
- this._selectAll = false;
589
544
  this._pendingChangedKeys.add("currentPage");
590
- this._pendingChangedKeys.add("selectAll");
591
545
  this.loadPageData();
592
546
  if (typeof window !== "undefined" && this.urlPageParam) {
593
547
  try {
@@ -617,12 +571,6 @@ class ADataProvider {
617
571
  this.loadPageData();
618
572
  this.notify();
619
573
  }
620
- setSelectedRows(rows) {
621
- this.selectedRows = rows;
622
- }
623
- setSelectAll(val) {
624
- this.selectAll = val;
625
- }
626
574
  async refresh(hardRefresh = false) {
627
575
  await this.loadPageData({ disableCache: hardRefresh });
628
576
  }
@@ -716,6 +664,14 @@ function getKeyIdentifier(keyProvider, defaultKey) {
716
664
  const target = keyProvider ?? defaultKey;
717
665
  return getSafeKeyIdentifier(target);
718
666
  }
667
+ function isAuthOrDecryptionError(err) {
668
+ if (!err) return false;
669
+ if (err.name === "OperationError") return true;
670
+ if (err.code === "ERR_CRYPTO_OPERATION_FAILED" || err.code === "ERR_OSSL_EVP_BAD_DECRYPT") return true;
671
+ if (err.cause && isAuthOrDecryptionError(err.cause)) return true;
672
+ const msg = String(err.message || "").toLowerCase();
673
+ return msg.includes("operationerror") || msg.includes("decrypt") || msg.includes("tag") || msg.includes("aad") || msg.includes("authenticated additional data") || msg.includes("authenticate data") || msg.includes("mac");
674
+ }
719
675
 
720
676
  class AEncryptionProvider {
721
677
  defaultKey;
@@ -794,6 +750,57 @@ class AEncryptionProvider {
794
750
  async [Symbol.asyncDispose]() {
795
751
  this.dispose();
796
752
  }
753
+ /**
754
+ * Resolves effective Authenticated Additional Data (AAD) for the operation:
755
+ * 1. If options.bindRequestContextAad is explicitly false, returns options.aad directly without context binding.
756
+ * 2. When encrypting (isDecrypt=false): binds request context `req:${method}:${url}` only if options.bindRequestContextAad === true.
757
+ * 3. When decrypting (isDecrypt=true): derives request context `req:${method}:${url}` if url or method is provided.
758
+ * 4. If explicit options.aad is provided: combines with request context if bound, or returns options.aad directly.
759
+ * 5. Otherwise returns undefined.
760
+ */
761
+ _resolveEffectiveAad(options, isDecrypt = false) {
762
+ if (!options) return void 0;
763
+ if (options.bindRequestContextAad === false) return options.aad;
764
+ const hasReqContext = Boolean(options.url || options.method);
765
+ if (options.aad) {
766
+ if (options.bindRequestContextAad === true && hasReqContext) {
767
+ const m = (options.method || "POST").toUpperCase();
768
+ const u = options.url || "";
769
+ const baseAad = typeof options.aad === "string" ? options.aad : options.aad instanceof Uint8Array || options.aad instanceof ArrayBuffer ? textDecoder.decode(options.aad) : String(options.aad);
770
+ return `${baseAad}|req:${m}:${u}`;
771
+ }
772
+ return options.aad;
773
+ }
774
+ const shouldBindReq = isDecrypt ? hasReqContext : options.bindRequestContextAad === true && hasReqContext;
775
+ if (shouldBindReq) {
776
+ const m = (options.method || "POST").toUpperCase();
777
+ const u = options.url || "";
778
+ return `req:${m}:${u}`;
779
+ }
780
+ return void 0;
781
+ }
782
+ /**
783
+ * Helper to deterministically bind record ID and field name into the AAD
784
+ * to prevent ciphertext swapping between fields or records.
785
+ */
786
+ _bindFieldAad(data, field, options) {
787
+ let baseAad = "";
788
+ if (options?.aad) {
789
+ if (typeof options.aad === "string") baseAad = options.aad;
790
+ else if (options.aad instanceof Uint8Array || options.aad instanceof ArrayBuffer) {
791
+ baseAad = textDecoder.decode(options.aad);
792
+ } else {
793
+ baseAad = String(options.aad);
794
+ }
795
+ }
796
+ const recordId = data && typeof data === "object" && (data.id !== void 0 || data._id !== void 0) ? String(data.id ?? data._id) : "";
797
+ const recordPart = recordId ? `|record:${recordId}` : "";
798
+ const reqPart = options?.bindRequestContextAad === true && (options?.url || options?.method) ? `|req:${(options.method || "POST").toUpperCase()}:${options.url || ""}` : "";
799
+ return {
800
+ ...options,
801
+ aad: `aad:${baseAad}${recordPart}${reqPart}|field:${field}`
802
+ };
803
+ }
797
804
  /**
798
805
  * Top-level polymorphic encryption method.
799
806
  * Automatically performs value-level encryption:
@@ -829,7 +836,10 @@ class AEncryptionProvider {
829
836
  }
830
837
  const result = { ...data };
831
838
  const entries = await Promise.all(
832
- fieldsToEncrypt.map(async (field) => [field, await this.encryptValue(result[field], options)])
839
+ fieldsToEncrypt.map(async (field) => {
840
+ const fieldOptions = this._bindFieldAad(data, field, options);
841
+ return [field, await this.encryptValue(result[field], fieldOptions)];
842
+ })
833
843
  );
834
844
  for (const [field, encryptedVal] of entries) {
835
845
  safeSetProperty(result, field, encryptedVal);
@@ -848,7 +858,10 @@ class AEncryptionProvider {
848
858
  await this.warmupKey(options);
849
859
  }
850
860
  const entries = await Promise.all(
851
- keysToEncrypt.map(async (key) => [key, await this.encryptValue(result[key], options)])
861
+ keysToEncrypt.map(async (key) => {
862
+ const fieldOptions = this._bindFieldAad(data, key, options);
863
+ return [key, await this.encryptValue(result[key], fieldOptions)];
864
+ })
852
865
  );
853
866
  for (const [key, encryptedVal] of entries) {
854
867
  safeSetProperty(result, key, encryptedVal);
@@ -881,7 +894,22 @@ class AEncryptionProvider {
881
894
  return payload;
882
895
  }
883
896
  const entries = await Promise.all(
884
- keysToDecrypt.map(async (key) => [key, await this.decryptValue(result[key], options)])
897
+ keysToDecrypt.map(async (key) => {
898
+ const boundOptions = this._bindFieldAad(payload, key, options);
899
+ const hasBoundAad = boundOptions.aad !== options?.aad;
900
+ try {
901
+ return [key, await this.decryptValue(result[key], boundOptions)];
902
+ } catch (err) {
903
+ if (hasBoundAad && isAuthOrDecryptionError(err)) {
904
+ try {
905
+ return [key, await this.decryptValue(result[key], options)];
906
+ } catch (fallbackErr) {
907
+ throw fallbackErr;
908
+ }
909
+ }
910
+ throw err;
911
+ }
912
+ })
885
913
  );
886
914
  for (const [key, decryptedVal] of entries) {
887
915
  safeSetProperty(result, key, decryptedVal);
@@ -1253,11 +1281,11 @@ ${lines.join("\n")}
1253
1281
  * Generates a high-entropy symmetric AES-GCM Account Data Encryption Key (ADEK).
1254
1282
  * Designed for multi-user table and field-level encryption.
1255
1283
  */
1256
- static async generateAccountDataKey(length = 256) {
1284
+ static async generateAccountDataKey(length = 256, extractable = false) {
1257
1285
  const subtle = getSubtleCrypto();
1258
1286
  return await subtle.generateKey(
1259
1287
  { name: "AES-GCM", length },
1260
- true,
1288
+ extractable,
1261
1289
  ["encrypt", "decrypt"]
1262
1290
  );
1263
1291
  }
@@ -1288,7 +1316,7 @@ ${lines.join("\n")}
1288
1316
  * Unwraps a Base64-encoded Account Data Encryption Key (ADEK) using the user's private key (RSA-OAEP).
1289
1317
  * Returns the restored AES-GCM CryptoKey ready for use in CWebCryptoEncryptionProvider.
1290
1318
  */
1291
- static async unwrapAccountKeyForUser(wrappedKeyBase64, userPrivateKey, unwrappedKeyAlgorithm = { name: "AES-GCM", length: 256 }) {
1319
+ static async unwrapAccountKeyForUser(wrappedKeyBase64, userPrivateKey, unwrappedKeyAlgorithm = { name: "AES-GCM", length: 256 }, extractable = false) {
1292
1320
  const subtle = getSubtleCrypto();
1293
1321
  if (userPrivateKey.algorithm.name === "RSA-OAEP") {
1294
1322
  const wrappedBytes = CKeyManager.fromBase64(wrappedKeyBase64);
@@ -1307,7 +1335,7 @@ ${lines.join("\n")}
1307
1335
  "raw",
1308
1336
  unwrappedRawKey,
1309
1337
  unwrappedKeyAlgorithm,
1310
- true,
1338
+ extractable,
1311
1339
  ["encrypt", "decrypt"]
1312
1340
  );
1313
1341
  } finally {
@@ -1480,12 +1508,13 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1480
1508
  return options._warmedKey;
1481
1509
  }
1482
1510
  if (saltOverride) {
1511
+ const rawKey = await this.resolveRawKey(keyProvider);
1483
1512
  const saltKey = typeof saltOverride === "string" ? saltOverride : CKeyManager.toBase64(saltOverride);
1484
- const keyId = getKeyIdentifier(keyProvider, this.defaultKey);
1513
+ const keyId = getSafeKeyIdentifier(rawKey);
1485
1514
  const compoundKey = `${keyId}:${kdfOverride || ""}:${iterationsOverride || ""}:${options?.kdfHash || ""}:${saltKey}`;
1486
1515
  let cached = this._decryptSaltCache.get(compoundKey);
1487
1516
  if (!cached) {
1488
- cached = this._resolveCryptoKeyInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1517
+ cached = this._resolveCryptoKeyInternal(rawKey, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1489
1518
  this._decryptSaltCache.delete(compoundKey);
1490
1519
  throw err;
1491
1520
  });
@@ -1542,9 +1571,9 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1542
1571
  const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
1543
1572
  const matchesKdf = this._cachedKdf !== void 0 && kdf === this._cachedKdf.toLowerCase();
1544
1573
  const matchesSalt = !saltOverride || this._cachedSalt !== void 0 && saltOverride === this._cachedSalt;
1545
- const currentKeyId = getKeyIdentifier(keyProvider, this.defaultKey);
1574
+ const currentKeyId = getSafeKeyIdentifier(rawKey);
1546
1575
  if (this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
1547
- if (!this._cachedKeyId || this._cachedKeyId === currentKeyId) {
1576
+ if (this._cachedKeyId === currentKeyId) {
1548
1577
  return { cryptoKey: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
1549
1578
  }
1550
1579
  }
@@ -1665,7 +1694,7 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1665
1694
  name: "AES-GCM",
1666
1695
  iv
1667
1696
  };
1668
- const aad = options?.aad;
1697
+ const aad = this._resolveEffectiveAad(options, false);
1669
1698
  let hasAad = false;
1670
1699
  if (aad) {
1671
1700
  const aadBytes = typeof aad === "string" ? textEncoder$1.encode(aad) : aad instanceof Uint8Array ? aad : new Uint8Array(aad);
@@ -1727,22 +1756,45 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1727
1756
  name: "AES-GCM",
1728
1757
  iv
1729
1758
  };
1730
- const aad = options?.aad;
1759
+ const aad = this._resolveEffectiveAad(options, true);
1760
+ let hasAad = false;
1731
1761
  if (payload.aad || aad) {
1732
1762
  if (aad) {
1733
1763
  const aadBytes = typeof aad === "string" ? textEncoder$1.encode(aad) : aad instanceof Uint8Array ? aad : new Uint8Array(aad);
1734
1764
  if (aadBytes.byteLength > 0) {
1735
1765
  decryptParams.additionalData = aadBytes;
1766
+ hasAad = true;
1736
1767
  }
1737
1768
  } else if (payload.aad) {
1738
1769
  throw new Error("[CWebCryptoEncryptionProvider] Payload requires Authenticated Additional Data (AAD) for decryption, but none was provided.");
1739
1770
  }
1740
1771
  }
1741
- const decryptedBuffer = await subtle.decrypt(
1742
- decryptParams,
1743
- cryptoKey,
1744
- ciphertextBytes
1745
- );
1772
+ let decryptedBuffer;
1773
+ try {
1774
+ decryptedBuffer = await subtle.decrypt(
1775
+ decryptParams,
1776
+ cryptoKey,
1777
+ ciphertextBytes
1778
+ );
1779
+ } catch (firstErr) {
1780
+ if (!payload.aad && hasAad) {
1781
+ try {
1782
+ const fallbackParams = {
1783
+ name: "AES-GCM",
1784
+ iv
1785
+ };
1786
+ decryptedBuffer = await subtle.decrypt(
1787
+ fallbackParams,
1788
+ cryptoKey,
1789
+ ciphertextBytes
1790
+ );
1791
+ } catch {
1792
+ throw firstErr;
1793
+ }
1794
+ } else {
1795
+ throw firstErr;
1796
+ }
1797
+ }
1746
1798
  try {
1747
1799
  const jsonString = textDecoder.decode(decryptedBuffer);
1748
1800
  return JSON.parse(jsonString);
@@ -1751,7 +1803,12 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1751
1803
  }
1752
1804
  } catch (err) {
1753
1805
  if (err instanceof SyntaxError) throw err;
1754
- throw new Error(`[CWebCryptoEncryptionProvider] Decryption failed: ${err?.message || "Authentication tag mismatch or corrupted ciphertext"}`);
1806
+ const decryptError = new Error(`[CWebCryptoEncryptionProvider] Decryption failed: ${err?.message || "Authentication tag mismatch or corrupted ciphertext"}`);
1807
+ if (err?.name) {
1808
+ decryptError.name = err.name;
1809
+ }
1810
+ decryptError.cause = err;
1811
+ throw decryptError;
1755
1812
  }
1756
1813
  }
1757
1814
  }
@@ -1764,6 +1821,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1764
1821
  _cachedKdf;
1765
1822
  _cachedIter;
1766
1823
  _cachedHash;
1824
+ _cachedKeyId;
1767
1825
  _configuredKid;
1768
1826
  _kdfOptions;
1769
1827
  _decryptSaltCache = /* @__PURE__ */ new Map();
@@ -1774,9 +1832,9 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1774
1832
  this._configuredKid = options.kid || options.keyId;
1775
1833
  }
1776
1834
  this._defaultKdf = options.kdf || "pbkdf2";
1777
- if (options.kdf && options.kdf !== "none") {
1835
+ if (this._defaultKdf !== "none") {
1778
1836
  this._kdfOptions = {
1779
- kdf: options.kdf,
1837
+ kdf: this._defaultKdf,
1780
1838
  iterations: options.kdfIterations,
1781
1839
  hash: options.kdfHash,
1782
1840
  salt: options.kdfSalt,
@@ -1793,6 +1851,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1793
1851
  this._cachedKdf = void 0;
1794
1852
  this._cachedIter = void 0;
1795
1853
  this._cachedHash = void 0;
1854
+ this._cachedKeyId = void 0;
1796
1855
  this._decryptSaltCache.clear();
1797
1856
  }
1798
1857
  clearKeys() {
@@ -1803,6 +1862,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1803
1862
  this._cachedKdf = void 0;
1804
1863
  this._cachedIter = void 0;
1805
1864
  this._cachedHash = void 0;
1865
+ this._cachedKeyId = void 0;
1806
1866
  this._decryptSaltCache.clear();
1807
1867
  }
1808
1868
  async warmupKey(options) {
@@ -1823,12 +1883,14 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1823
1883
  */
1824
1884
  async resolveCBCKeys(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
1825
1885
  if (saltOverride) {
1886
+ const rawKey = await this.resolveRawKey(keyProvider);
1826
1887
  const saltKey = typeof saltOverride === "string" ? saltOverride : CKeyManager.toBase64(saltOverride);
1827
- const keyId = getKeyIdentifier(keyProvider, this.defaultKey);
1828
- const compoundKey = `${keyId}:${kdfOverride || ""}:${iterationsOverride || ""}:${options?.kdfHash || ""}:${saltKey}`;
1888
+ const keyId = getSafeKeyIdentifier(rawKey);
1889
+ const effectiveHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
1890
+ const compoundKey = `${keyId}:${kdfOverride || ""}:${iterationsOverride || ""}:${effectiveHash}:${saltKey}`;
1829
1891
  let cached = this._decryptSaltCache.get(compoundKey);
1830
1892
  if (!cached) {
1831
- cached = this._deriveCBCKeysInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1893
+ cached = this._deriveCBCKeysInternal(rawKey, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1832
1894
  this._decryptSaltCache.delete(compoundKey);
1833
1895
  throw err;
1834
1896
  });
@@ -1848,17 +1910,20 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1848
1910
  return await this._deriveCBCKeysInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride);
1849
1911
  }
1850
1912
  async _deriveCBCKeysInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
1913
+ const rawKey = await this.resolveRawKey(keyProvider);
1914
+ const currentKeyId = getSafeKeyIdentifier(rawKey);
1851
1915
  const subtle = getSubtleCrypto();
1852
- const targetIter = iterationsOverride || options?.kdfIterations;
1853
- const targetHash = options?.kdfHash;
1916
+ const targetIter = iterationsOverride || options?.kdfIterations || this._kdfOptions?.iterations;
1917
+ const targetHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
1854
1918
  const matchesIter = !targetIter || this._cachedIter !== void 0 && targetIter === this._cachedIter;
1855
- const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
1919
+ const matchesHash = this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
1856
1920
  const effectiveKdf = (kdfOverride || options?.kdf || this._defaultKdf || "none").toLowerCase();
1857
1921
  const matchesKdf = this._cachedKdf === "raw" || this._cachedKdf === "hkdf-direct" || this._cachedKdf !== void 0 && effectiveKdf === this._cachedKdf.toLowerCase();
1858
- if (!keyProvider && this._cachedEncKey && this._cachedMacKey && !saltOverride && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
1859
- return { encKey: this._cachedEncKey, macKey: this._cachedMacKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
1922
+ if (this._cachedEncKey && this._cachedMacKey && !saltOverride && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
1923
+ if (this._cachedKeyId === currentKeyId) {
1924
+ return { encKey: this._cachedEncKey, macKey: this._cachedMacKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
1925
+ }
1860
1926
  }
1861
- const rawKey = await this.resolveRawKey(keyProvider);
1862
1927
  if (typeof rawKey !== "string" && rawKey.algorithm) {
1863
1928
  const cryptoKey = rawKey;
1864
1929
  let rawBits;
@@ -1891,6 +1956,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1891
1956
  this._cachedEncKey = encKey2;
1892
1957
  this._cachedMacKey = macKey2;
1893
1958
  this._cachedKdf = "hkdf-direct";
1959
+ this._cachedKeyId = currentKeyId;
1894
1960
  }
1895
1961
  return { encKey: encKey2, macKey: macKey2, kdf: "hkdf-direct" };
1896
1962
  }
@@ -1924,6 +1990,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1924
1990
  this._cachedEncKey = encKey2;
1925
1991
  this._cachedMacKey = macKey2;
1926
1992
  this._cachedKdf = "raw";
1993
+ this._cachedKeyId = currentKeyId;
1927
1994
  }
1928
1995
  return { encKey: encKey2, macKey: macKey2, kdf: "raw" };
1929
1996
  }
@@ -1954,6 +2021,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1954
2021
  this._cachedEncKey = encKey2;
1955
2022
  this._cachedMacKey = macKey2;
1956
2023
  this._cachedKdf = "raw";
2024
+ this._cachedKeyId = currentKeyId;
1957
2025
  }
1958
2026
  return { encKey: encKey2, macKey: macKey2, kdf: "raw" };
1959
2027
  }
@@ -2061,6 +2129,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
2061
2129
  this._cachedKdf = kdfType || "none";
2062
2130
  this._cachedIter = iterNum;
2063
2131
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
2132
+ this._cachedKeyId = currentKeyId;
2064
2133
  }
2065
2134
  return {
2066
2135
  encKey,
@@ -2961,6 +3030,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2961
3030
  _cachedKdf;
2962
3031
  _cachedIter;
2963
3032
  _cachedHash;
3033
+ _cachedKeyId;
2964
3034
  _configuredKid;
2965
3035
  setDefaultKey(key) {
2966
3036
  super.setDefaultKey(key);
@@ -2972,6 +3042,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2972
3042
  this._cachedKdf = void 0;
2973
3043
  this._cachedIter = void 0;
2974
3044
  this._cachedHash = void 0;
3045
+ this._cachedKeyId = void 0;
2975
3046
  }
2976
3047
  clearKeys() {
2977
3048
  super.clearKeys();
@@ -2983,6 +3054,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2983
3054
  this._cachedKdf = void 0;
2984
3055
  this._cachedIter = void 0;
2985
3056
  this._cachedHash = void 0;
3057
+ this._cachedKeyId = void 0;
2986
3058
  }
2987
3059
  async warmupKey(options) {
2988
3060
  const res = await this.deriveKeyAsync(options?.key, void 0, void 0, options);
@@ -2992,6 +3064,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2992
3064
  this._cachedKdf = res.kdf;
2993
3065
  this._cachedIter = res.iter;
2994
3066
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3067
+ this._cachedKeyId = getSafeKeyIdentifier(await this.resolveRawKeyAsync(options?.key));
2995
3068
  }
2996
3069
  }
2997
3070
  /**
@@ -3005,6 +3078,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3005
3078
  this._cachedKdf = res.kdf;
3006
3079
  this._cachedIter = res.iter;
3007
3080
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3081
+ this._cachedKeyId = getSafeKeyIdentifier(this.resolveRawKeySync(options?.key));
3008
3082
  }
3009
3083
  }
3010
3084
  resolveInfoBuffer(infoRaw) {
@@ -3091,12 +3165,14 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3091
3165
  }
3092
3166
  deriveKeySync(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
3093
3167
  const raw = this.resolveRawKeySync(keyProvider);
3168
+ const currentKeyId = getSafeKeyIdentifier(raw);
3094
3169
  if (Buffer.isBuffer(raw)) {
3095
3170
  if (raw.length === 32) {
3096
3171
  if (!keyProvider) {
3097
- if (!this._cachedKey) {
3172
+ if (!this._cachedKey || this._cachedKeyId !== currentKeyId) {
3098
3173
  this._cachedKey = Buffer.from(raw);
3099
3174
  this._cachedKdf = "raw";
3175
+ this._cachedKeyId = currentKeyId;
3100
3176
  }
3101
3177
  return { key: this._cachedKey, kdf: "raw" };
3102
3178
  }
@@ -3114,8 +3190,10 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3114
3190
  const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
3115
3191
  const matchesKdf = this._cachedKdf !== void 0 && kdf === this._cachedKdf.toLowerCase();
3116
3192
  const matchesSalt = !saltOverride || this._cachedSalt !== void 0 && saltOverride === this._cachedSalt;
3117
- if (!keyProvider && this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3118
- return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3193
+ if (this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3194
+ if (this._cachedKeyId === currentKeyId) {
3195
+ return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3196
+ }
3119
3197
  }
3120
3198
  if (kdf === "pbkdf2") {
3121
3199
  const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
@@ -3131,6 +3209,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3131
3209
  this._cachedKdf = "PBKDF2";
3132
3210
  this._cachedIter = iterations;
3133
3211
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3212
+ this._cachedKeyId = currentKeyId;
3134
3213
  }
3135
3214
  return {
3136
3215
  key: key2,
@@ -3156,6 +3235,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3156
3235
  this._cachedSalt = saltBuf.toString("base64");
3157
3236
  this._cachedKdf = "HKDF";
3158
3237
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3238
+ this._cachedKeyId = currentKeyId;
3159
3239
  }
3160
3240
  return {
3161
3241
  key: key2,
@@ -3168,24 +3248,27 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3168
3248
  "[CNodeCryptoEncryptionProvider] WARNING: Decrypting a legacy envelope with no KDF (raw SHA-256 key derivation). This is cryptographically weak. Migrate to pbkdf2 or hkdf."
3169
3249
  );
3170
3250
  }
3171
- if (!keyProvider && this._cachedKey && this._cachedKdf === "none") {
3251
+ if (!keyProvider && this._cachedKey && this._cachedKdf === "none" && this._cachedKeyId === currentKeyId) {
3172
3252
  return { key: this._cachedKey, kdf: "none" };
3173
3253
  }
3174
3254
  const key = crypto__namespace.createHash("sha256").update(passphrase, "utf8").digest();
3175
3255
  if (!keyProvider) {
3176
3256
  this._cachedKey = key;
3177
3257
  this._cachedKdf = "none";
3258
+ this._cachedKeyId = currentKeyId;
3178
3259
  }
3179
3260
  return { key, kdf: "none" };
3180
3261
  }
3181
3262
  async deriveKeyAsync(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
3182
3263
  const raw = await this.resolveRawKeyAsync(keyProvider);
3264
+ const currentKeyId = getSafeKeyIdentifier(raw);
3183
3265
  if (Buffer.isBuffer(raw)) {
3184
3266
  if (raw.length === 32) {
3185
3267
  if (!keyProvider) {
3186
- if (!this._cachedKey) {
3268
+ if (!this._cachedKey || this._cachedKeyId !== currentKeyId) {
3187
3269
  this._cachedKey = Buffer.from(raw);
3188
3270
  this._cachedKdf = "raw";
3271
+ this._cachedKeyId = currentKeyId;
3189
3272
  }
3190
3273
  return { key: this._cachedKey, kdf: "raw" };
3191
3274
  }
@@ -3203,8 +3286,10 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3203
3286
  const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
3204
3287
  const matchesKdf = this._cachedKdf !== void 0 && kdf === this._cachedKdf.toLowerCase();
3205
3288
  const matchesSalt = !saltOverride || this._cachedSalt !== void 0 && saltOverride === this._cachedSalt;
3206
- if (!keyProvider && this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3207
- return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3289
+ if (this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3290
+ if (this._cachedKeyId === currentKeyId) {
3291
+ return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3292
+ }
3208
3293
  }
3209
3294
  if (kdf === "pbkdf2") {
3210
3295
  const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
@@ -3225,6 +3310,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3225
3310
  this._cachedKdf = "PBKDF2";
3226
3311
  this._cachedIter = iterations;
3227
3312
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3313
+ this._cachedKeyId = currentKeyId;
3228
3314
  }
3229
3315
  return {
3230
3316
  key: key2,
@@ -3255,6 +3341,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3255
3341
  this._cachedSalt = saltBuf.toString("base64");
3256
3342
  this._cachedKdf = "HKDF";
3257
3343
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3344
+ this._cachedKeyId = currentKeyId;
3258
3345
  }
3259
3346
  return {
3260
3347
  key: key2,
@@ -3267,13 +3354,14 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3267
3354
  "[CNodeCryptoEncryptionProvider] WARNING: Decrypting a legacy envelope with no KDF (raw SHA-256 key derivation). This is cryptographically weak. Migrate to pbkdf2 or hkdf."
3268
3355
  );
3269
3356
  }
3270
- if (!keyProvider && this._cachedKey && this._cachedKdf === "none") {
3357
+ if (!keyProvider && this._cachedKey && this._cachedKdf === "none" && this._cachedKeyId === currentKeyId) {
3271
3358
  return { key: this._cachedKey, kdf: "none" };
3272
3359
  }
3273
3360
  const key = crypto__namespace.createHash("sha256").update(passphrase, "utf8").digest();
3274
3361
  if (!keyProvider) {
3275
3362
  this._cachedKey = key;
3276
3363
  this._cachedKdf = "none";
3364
+ this._cachedKeyId = currentKeyId;
3277
3365
  }
3278
3366
  return { key, kdf: "none" };
3279
3367
  }
@@ -3300,7 +3388,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3300
3388
  const jsonString = JSON.stringify(data);
3301
3389
  const iv = crypto__namespace.randomBytes(12);
3302
3390
  const cipher = crypto__namespace.createCipheriv("aes-256-gcm", key, iv);
3303
- const aad = options?.aad;
3391
+ const aad = this._resolveEffectiveAad(options, false);
3304
3392
  let hasAad = false;
3305
3393
  if (aad) {
3306
3394
  const aadBuffer = Buffer.isBuffer(aad) ? aad : Buffer.from(typeof aad === "string" ? aad : new Uint8Array(aad));
@@ -3353,21 +3441,41 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3353
3441
  }
3354
3442
  const decipher = crypto__namespace.createDecipheriv("aes-256-gcm", key, iv, { authTagLength: 16 });
3355
3443
  decipher.setAuthTag(authTag);
3356
- const aad = options?.aad;
3444
+ const aad = this._resolveEffectiveAad(options, true);
3445
+ let hasAad = false;
3357
3446
  if (payload.aad || aad) {
3358
3447
  if (aad) {
3359
3448
  const aadBuffer = Buffer.isBuffer(aad) ? aad : Buffer.from(typeof aad === "string" ? aad : new Uint8Array(aad));
3360
3449
  if (aadBuffer.length > 0) {
3361
3450
  decipher.setAAD(aadBuffer);
3451
+ hasAad = true;
3362
3452
  }
3363
3453
  } else if (payload.aad) {
3364
3454
  throw new Error("[CNodeCryptoEncryptionProvider] Payload requires Authenticated Additional Data (AAD) for decryption, but none was provided.");
3365
3455
  }
3366
3456
  }
3367
- const decrypted = Buffer.concat([
3368
- decipher.update(ciphertext),
3369
- decipher.final()
3370
- ]);
3457
+ let decrypted;
3458
+ try {
3459
+ decrypted = Buffer.concat([
3460
+ decipher.update(ciphertext),
3461
+ decipher.final()
3462
+ ]);
3463
+ } catch (firstErr) {
3464
+ if (!payload.aad && hasAad) {
3465
+ try {
3466
+ const fallbackDecipher = crypto__namespace.createDecipheriv("aes-256-gcm", key, iv, { authTagLength: 16 });
3467
+ fallbackDecipher.setAuthTag(authTag);
3468
+ decrypted = Buffer.concat([
3469
+ fallbackDecipher.update(ciphertext),
3470
+ fallbackDecipher.final()
3471
+ ]);
3472
+ } catch {
3473
+ throw firstErr;
3474
+ }
3475
+ } else {
3476
+ throw firstErr;
3477
+ }
3478
+ }
3371
3479
  try {
3372
3480
  const jsonString = decrypted.toString("utf8");
3373
3481
  return JSON.parse(jsonString);
@@ -3420,7 +3528,8 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3420
3528
  if (fieldsToEncrypt.length === 0) return { ...data };
3421
3529
  const result = { ...data };
3422
3530
  for (const field of fieldsToEncrypt) {
3423
- safeSetProperty(result, field, this.encryptValueSync(result[field], options));
3531
+ const fieldOptions = this._bindFieldAad(data, field, options);
3532
+ safeSetProperty(result, field, this.encryptValueSync(result[field], fieldOptions));
3424
3533
  }
3425
3534
  return result;
3426
3535
  }
@@ -3428,7 +3537,8 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3428
3537
  const result = { ...data };
3429
3538
  for (const key of Object.keys(result)) {
3430
3539
  if (result[key] !== void 0 && result[key] !== null && !this.isEncrypted(result[key])) {
3431
- safeSetProperty(result, key, this.encryptValueSync(result[key], options));
3540
+ const fieldOptions = this._bindFieldAad(data, key, options);
3541
+ safeSetProperty(result, key, this.encryptValueSync(result[key], fieldOptions));
3432
3542
  }
3433
3543
  }
3434
3544
  return result;
@@ -3467,7 +3577,21 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3467
3577
  derivedKey = derived.key;
3468
3578
  keyCache.set(salt, derivedKey);
3469
3579
  }
3470
- safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3580
+ const boundOptions = this._bindFieldAad(payload, key, options);
3581
+ const hasBoundAad = boundOptions.aad !== options?.aad;
3582
+ try {
3583
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, boundOptions));
3584
+ } catch (err) {
3585
+ if (hasBoundAad && isAuthOrDecryptionError(err)) {
3586
+ try {
3587
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3588
+ } catch (fallbackErr) {
3589
+ throw fallbackErr;
3590
+ }
3591
+ } else {
3592
+ throw err;
3593
+ }
3594
+ }
3471
3595
  mutated = true;
3472
3596
  }
3473
3597
  }
@@ -3507,7 +3631,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3507
3631
  const jsonString = JSON.stringify(data);
3508
3632
  const iv = crypto__namespace.randomBytes(12);
3509
3633
  const cipher = crypto__namespace.createCipheriv("aes-256-gcm", key, iv);
3510
- const aad = options?.aad;
3634
+ const aad = this._resolveEffectiveAad(options, false);
3511
3635
  let hasAad = false;
3512
3636
  if (aad) {
3513
3637
  const aadBuffer = Buffer.isBuffer(aad) ? aad : Buffer.from(typeof aad === "string" ? aad : new Uint8Array(aad));
@@ -3595,7 +3719,21 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3595
3719
  derivedKey = derived.key;
3596
3720
  keyCache.set(salt, derivedKey);
3597
3721
  }
3598
- safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3722
+ const boundOptions = this._bindFieldAad(payload, key, options);
3723
+ const hasBoundAad = boundOptions.aad !== options?.aad;
3724
+ try {
3725
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, boundOptions));
3726
+ } catch (err) {
3727
+ if (hasBoundAad && isAuthOrDecryptionError(err)) {
3728
+ try {
3729
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3730
+ } catch (fallbackErr) {
3731
+ throw fallbackErr;
3732
+ }
3733
+ } else {
3734
+ throw err;
3735
+ }
3736
+ }
3599
3737
  mutated = true;
3600
3738
  }
3601
3739
  }
@@ -4603,12 +4741,6 @@ class CFlatClientDataProvider extends AEncryptedClientProvider {
4603
4741
  }
4604
4742
  });
4605
4743
  }
4606
- getSelectedRows() {
4607
- if (this.selectAll) {
4608
- return this.filteredData && this.filteredData.length > 0 ? this.filteredData : this.allData;
4609
- }
4610
- return this.selectedRows;
4611
- }
4612
4744
  }
4613
4745
 
4614
4746
  class CacheProviderFactory {
@@ -5338,6 +5470,48 @@ function generateId() {
5338
5470
  }
5339
5471
  return Date.now().toString(36) + Math.random().toString(36).slice(2);
5340
5472
  }
5473
+ function uint8ArrayToBase64(bytes) {
5474
+ if (typeof Buffer !== "undefined") {
5475
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
5476
+ }
5477
+ let binary = "";
5478
+ const chunkSize = 8192;
5479
+ for (let i = 0; i < bytes.byteLength; i += chunkSize) {
5480
+ const chunk = bytes.subarray(i, i + chunkSize);
5481
+ binary += String.fromCharCode.apply(null, chunk);
5482
+ }
5483
+ return btoa(binary);
5484
+ }
5485
+ function base64ToUint8Array(base64) {
5486
+ if (typeof Buffer !== "undefined") {
5487
+ const buf = Buffer.from(base64, "base64");
5488
+ return new Uint8Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));
5489
+ }
5490
+ const binary = atob(base64);
5491
+ const bytes = new Uint8Array(binary.length);
5492
+ for (let i = 0; i < binary.length; i++) {
5493
+ bytes[i] = binary.charCodeAt(i);
5494
+ }
5495
+ return bytes;
5496
+ }
5497
+ async function readBlobAsUint8Array(blob) {
5498
+ if (typeof blob.arrayBuffer === "function") {
5499
+ const buffer = await blob.arrayBuffer();
5500
+ return new Uint8Array(buffer);
5501
+ }
5502
+ if (typeof FileReader !== "undefined") {
5503
+ return new Promise((resolve, reject) => {
5504
+ const reader = new FileReader();
5505
+ reader.onload = () => {
5506
+ const buffer = reader.result;
5507
+ resolve(new Uint8Array(buffer));
5508
+ };
5509
+ reader.onerror = () => reject(reader.error);
5510
+ reader.readAsArrayBuffer(blob);
5511
+ });
5512
+ }
5513
+ throw new Error("[RequestQueue] Blob binary extraction is not supported in this environment");
5514
+ }
5341
5515
  const SENSITIVE_HEADER_KEYS = ["authorization", "cookie", "set-cookie", "x-csrf-token"];
5342
5516
  class RequestQueue {
5343
5517
  // ── State ──────────────────────────────────────────────────────────────────
@@ -5364,11 +5538,187 @@ class RequestQueue {
5364
5538
  * Sensitive credentials must never be stored in plaintext in browser storage, and are
5365
5539
  * instead regenerated dynamically at execution time.
5366
5540
  */
5367
- static sanitizeOptions(options) {
5541
+ /**
5542
+ * Adapts binary, multipart, and specialized payload types (FormData, Blob, File,
5543
+ * ArrayBuffer, TypedArrays, URLSearchParams) into JSON-serializable structures
5544
+ * to prevent silent payload loss (BUG-014) when persisting to offline storage.
5545
+ */
5546
+ static async serializeBody(body) {
5547
+ if (body === void 0 || body === null) {
5548
+ return body;
5549
+ }
5550
+ const isFormData = typeof FormData !== "undefined" && (body instanceof FormData || Object.prototype.toString.call(body) === "[object FormData]");
5551
+ if (isFormData) {
5552
+ const entries = [];
5553
+ if (typeof body.entries === "function") {
5554
+ for (const [key, val] of body.entries()) {
5555
+ entries.push([key, await RequestQueue.serializeFieldValue(val)]);
5556
+ }
5557
+ } else if (typeof body.forEach === "function") {
5558
+ const raw = [];
5559
+ body.forEach((val, key) => {
5560
+ raw.push([key, val]);
5561
+ });
5562
+ for (const [key, val] of raw) {
5563
+ entries.push([key, await RequestQueue.serializeFieldValue(val)]);
5564
+ }
5565
+ }
5566
+ return {
5567
+ __katlux_type: "FormData",
5568
+ entries
5569
+ };
5570
+ }
5571
+ const isFile = typeof File !== "undefined" && (body instanceof File || Object.prototype.toString.call(body) === "[object File]");
5572
+ if (isFile) {
5573
+ const bytes = await readBlobAsUint8Array(body);
5574
+ return {
5575
+ __katlux_type: "File",
5576
+ name: body.name,
5577
+ type: body.type || "application/octet-stream",
5578
+ lastModified: body.lastModified,
5579
+ data: uint8ArrayToBase64(bytes)
5580
+ };
5581
+ }
5582
+ const isBlob = typeof Blob !== "undefined" && (body instanceof Blob || Object.prototype.toString.call(body) === "[object Blob]");
5583
+ if (isBlob) {
5584
+ const bytes = await readBlobAsUint8Array(body);
5585
+ return {
5586
+ __katlux_type: "Blob",
5587
+ type: body.type || "application/octet-stream",
5588
+ data: uint8ArrayToBase64(bytes)
5589
+ };
5590
+ }
5591
+ const isArrayBuffer = typeof ArrayBuffer !== "undefined" && (body instanceof ArrayBuffer || Object.prototype.toString.call(body) === "[object ArrayBuffer]");
5592
+ if (isArrayBuffer) {
5593
+ const bytes = new Uint8Array(body);
5594
+ return {
5595
+ __katlux_type: "ArrayBuffer",
5596
+ data: uint8ArrayToBase64(bytes)
5597
+ };
5598
+ }
5599
+ if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(body)) {
5600
+ const view = body;
5601
+ const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
5602
+ return {
5603
+ __katlux_type: "Uint8Array",
5604
+ data: uint8ArrayToBase64(bytes)
5605
+ };
5606
+ }
5607
+ const isURLSearchParams = typeof URLSearchParams !== "undefined" && (body instanceof URLSearchParams || Object.prototype.toString.call(body) === "[object URLSearchParams]");
5608
+ if (isURLSearchParams) {
5609
+ return {
5610
+ __katlux_type: "URLSearchParams",
5611
+ data: body.toString()
5612
+ };
5613
+ }
5614
+ return body;
5615
+ }
5616
+ static async serializeFieldValue(val) {
5617
+ if (typeof File !== "undefined" && (val instanceof File || Object.prototype.toString.call(val) === "[object File]")) {
5618
+ const bytes = await readBlobAsUint8Array(val);
5619
+ return {
5620
+ __katlux_type: "File",
5621
+ name: val.name,
5622
+ type: val.type || "application/octet-stream",
5623
+ lastModified: val.lastModified,
5624
+ data: uint8ArrayToBase64(bytes)
5625
+ };
5626
+ }
5627
+ if (typeof Blob !== "undefined" && (val instanceof Blob || Object.prototype.toString.call(val) === "[object Blob]")) {
5628
+ const bytes = await readBlobAsUint8Array(val);
5629
+ return {
5630
+ __katlux_type: "Blob",
5631
+ type: val.type || "application/octet-stream",
5632
+ data: uint8ArrayToBase64(bytes)
5633
+ };
5634
+ }
5635
+ return typeof val === "string" ? val : String(val);
5636
+ }
5637
+ /**
5638
+ * Reconstitutes serialized offline request bodies back into their live runtime instances
5639
+ * (FormData, Blob, File, ArrayBuffer, Uint8Array, URLSearchParams) before network transmission.
5640
+ */
5641
+ static reconstituteBody(body) {
5642
+ if (!body || typeof body !== "object") {
5643
+ return body;
5644
+ }
5645
+ if (body.__katlux_type === "FormData" && Array.isArray(body.entries)) {
5646
+ if (typeof FormData === "undefined") return body;
5647
+ const fd = new FormData();
5648
+ for (const [key, val] of body.entries) {
5649
+ if (val && typeof val === "object" && val.__katlux_type === "File") {
5650
+ const u8 = base64ToUint8Array(val.data);
5651
+ if (typeof File !== "undefined") {
5652
+ const file = new File([u8], val.name, {
5653
+ type: val.type || "application/octet-stream",
5654
+ lastModified: val.lastModified
5655
+ });
5656
+ fd.append(key, file, val.name);
5657
+ } else if (typeof Blob !== "undefined") {
5658
+ const blob = new Blob([u8], { type: val.type || "application/octet-stream" });
5659
+ fd.append(key, blob, val.name);
5660
+ }
5661
+ } else if (val && typeof val === "object" && val.__katlux_type === "Blob") {
5662
+ if (typeof Blob !== "undefined") {
5663
+ const u8 = base64ToUint8Array(val.data);
5664
+ const blob = new Blob([u8], { type: val.type || "application/octet-stream" });
5665
+ fd.append(key, blob);
5666
+ }
5667
+ } else {
5668
+ fd.append(key, val);
5669
+ }
5670
+ }
5671
+ return fd;
5672
+ }
5673
+ if (body.__katlux_type === "File") {
5674
+ const u8 = base64ToUint8Array(body.data);
5675
+ if (typeof File !== "undefined") {
5676
+ return new File([u8], body.name, {
5677
+ type: body.type || "application/octet-stream",
5678
+ lastModified: body.lastModified
5679
+ });
5680
+ }
5681
+ if (typeof Blob !== "undefined") {
5682
+ return new Blob([u8], { type: body.type || "application/octet-stream" });
5683
+ }
5684
+ return u8;
5685
+ }
5686
+ if (body.__katlux_type === "Blob") {
5687
+ const u8 = base64ToUint8Array(body.data);
5688
+ if (typeof Blob !== "undefined") {
5689
+ return new Blob([u8], { type: body.type || "application/octet-stream" });
5690
+ }
5691
+ return u8;
5692
+ }
5693
+ if (body.__katlux_type === "ArrayBuffer") {
5694
+ const u8 = base64ToUint8Array(body.data);
5695
+ return u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength);
5696
+ }
5697
+ if (body.__katlux_type === "Uint8Array") {
5698
+ return base64ToUint8Array(body.data);
5699
+ }
5700
+ if (body.__katlux_type === "URLSearchParams") {
5701
+ if (typeof URLSearchParams !== "undefined") {
5702
+ return new URLSearchParams(body.data);
5703
+ }
5704
+ return body.data;
5705
+ }
5706
+ return body;
5707
+ }
5708
+ /**
5709
+ * Strips sensitive headers (e.g., authorization, cookie, x-csrf-token) before persisting
5710
+ * request options to persistent storage (IndexedDB / LocalStorage).
5711
+ * Sensitive credentials must never be stored in plaintext in browser storage, and are
5712
+ * instead regenerated dynamically at execution time.
5713
+ */
5714
+ static async sanitizeOptions(options) {
5368
5715
  if (!options) return {};
5369
5716
  const sanitized = {
5370
5717
  method: options.method
5371
5718
  };
5719
+ if (options.credentials) {
5720
+ sanitized.credentials = options.credentials;
5721
+ }
5372
5722
  if (options.headers) {
5373
5723
  const headersObj = {};
5374
5724
  const sensitiveSet = new Set(SENSITIVE_HEADER_KEYS.map((k) => k.toLowerCase()));
@@ -5402,7 +5752,8 @@ class RequestQueue {
5402
5752
  }
5403
5753
  if (options.body !== void 0) {
5404
5754
  try {
5405
- const serialized = JSON.stringify(options.body);
5755
+ const serializedBody = await this.serializeBody(options.body);
5756
+ const serialized = JSON.stringify(serializedBody);
5406
5757
  if (serialized && serialized.length > this.MAX_PAYLOAD_SIZE_BYTES) {
5407
5758
  throw new Error(
5408
5759
  `[RequestQueue] Payload size (${(serialized.length / (1024 * 1024)).toFixed(2)} MB) exceeds maximum allowed size (${(this.MAX_PAYLOAD_SIZE_BYTES / (1024 * 1024)).toFixed(2)} MB)`
@@ -5442,6 +5793,7 @@ class RequestQueue {
5442
5793
  static _onDeadLetter = null;
5443
5794
  static _onFlushComplete = null;
5444
5795
  static _onNetworkError = null;
5796
+ static _onError = null;
5445
5797
  static _headerProvider = null;
5446
5798
  static setHeaderProvider(provider) {
5447
5799
  this._headerProvider = provider;
@@ -5491,6 +5843,12 @@ class RequestQueue {
5491
5843
  static onNetworkError(cb) {
5492
5844
  this._onNetworkError = cb;
5493
5845
  }
5846
+ static onError(cb) {
5847
+ this._onError = cb;
5848
+ }
5849
+ static onQueueFatalError(cb) {
5850
+ this._onError = cb;
5851
+ }
5494
5852
  // ── Enqueue ───────────────────────────────────────────────────────────────
5495
5853
  /**
5496
5854
  * Add an operation to the pending queue and persist it.
@@ -5499,7 +5857,7 @@ class RequestQueue {
5499
5857
  */
5500
5858
  static async enqueue(operation) {
5501
5859
  await this.init();
5502
- const sanitizedOptions = this.sanitizeOptions(operation.options);
5860
+ const sanitizedOptions = await this.sanitizeOptions(operation.options);
5503
5861
  if (this.queue.length >= this.MAX_QUEUE_SIZE) {
5504
5862
  const evicted = this.queue[0];
5505
5863
  await this.moveToDeadLetter(evicted, new Error("Queue capacity exceeded"));
@@ -5562,11 +5920,24 @@ class RequestQueue {
5562
5920
  this.notify();
5563
5921
  this._onNetworkError?.(item);
5564
5922
  } else {
5565
- await this.moveToDeadLetter(item, error, httpStatus);
5923
+ try {
5924
+ await this.moveToDeadLetter(item, error, httpStatus);
5925
+ } catch (dlErr) {
5926
+ await this.persistQueue().catch(() => {
5927
+ });
5928
+ this.notify();
5929
+ const fatalError = dlErr instanceof Error ? dlErr : new Error(String(dlErr));
5930
+ console.error("[RequestQueue] Fatal capacity error moving to dead-letter:", fatalError);
5931
+ this._onError?.(fatalError);
5932
+ }
5566
5933
  }
5567
5934
  break;
5568
5935
  }
5569
5936
  }
5937
+ } catch (topErr) {
5938
+ const fatalError = topErr instanceof Error ? topErr : new Error(String(topErr));
5939
+ console.error("[RequestQueue] flushAll fatal error:", fatalError);
5940
+ this._onError?.(fatalError);
5570
5941
  } finally {
5571
5942
  this.isFlushing = false;
5572
5943
  this.notify();
@@ -5610,7 +5981,16 @@ class RequestQueue {
5610
5981
  this.notify();
5611
5982
  this._onNetworkError?.(item);
5612
5983
  } else {
5613
- await this.moveToDeadLetter(item, error, httpStatus);
5984
+ try {
5985
+ await this.moveToDeadLetter(item, error, httpStatus);
5986
+ } catch (dlErr) {
5987
+ await this.persistQueue().catch(() => {
5988
+ });
5989
+ this.notify();
5990
+ const fatalError = dlErr instanceof Error ? dlErr : new Error(String(dlErr));
5991
+ console.error("[RequestQueue] Fatal capacity error moving to dead-letter:", fatalError);
5992
+ this._onError?.(fatalError);
5993
+ }
5614
5994
  }
5615
5995
  }
5616
5996
  }
@@ -5684,24 +6064,30 @@ class RequestQueue {
5684
6064
  console.error("[RequestQueue] Header provider failed:", err);
5685
6065
  }
5686
6066
  }
5687
- if (typeof document !== "undefined" && document.cookie && !headers["cookie"] && !headers["Cookie"]) {
5688
- headers["cookie"] = document.cookie;
5689
- }
5690
6067
  return headers;
5691
6068
  }
5692
6069
  static async executeRequest(item) {
5693
6070
  const { url, options } = item;
5694
6071
  const headers = await this.regenerateHeaders(options.headers);
6072
+ const body = this.reconstituteBody(options.body);
6073
+ if (typeof FormData !== "undefined" && (body instanceof FormData || Object.prototype.toString.call(body) === "[object FormData]")) {
6074
+ delete headers["content-type"];
6075
+ delete headers["Content-Type"];
6076
+ }
5695
6077
  const fetchOptions = {
5696
6078
  method: item.method,
5697
- body: options.body,
6079
+ body,
5698
6080
  headers,
5699
- query: options.query
6081
+ query: options.query,
6082
+ credentials: options.credentials || "include"
5700
6083
  };
5701
6084
  const fetchFn = globalThis.$fetch || ofetch.$fetch;
5702
6085
  await fetchFn(url, fetchOptions);
5703
6086
  }
5704
6087
  static async moveToDeadLetter(item, error, httpStatus) {
6088
+ if (this.deadLetterQueue.length >= this.MAX_DEAD_LETTER_SIZE) {
6089
+ throw new Error(`[RequestQueue] Dead-letter queue reached capacity (${this.MAX_DEAD_LETTER_SIZE}). Please clear the queue manually before proceeding to prevent data loss.`);
6090
+ }
5705
6091
  const deadItem = {
5706
6092
  ...item,
5707
6093
  failedAt: Date.now(),
@@ -5709,11 +6095,6 @@ class RequestQueue {
5709
6095
  httpStatus
5710
6096
  };
5711
6097
  this.queue = this.queue.filter((i) => i.id !== item.id);
5712
- if (this.deadLetterQueue.length >= this.MAX_DEAD_LETTER_SIZE) {
5713
- const evicted = this.deadLetterQueue[0];
5714
- console.warn(`[RequestQueue] Dead-letter queue reached capacity (${this.MAX_DEAD_LETTER_SIZE}). Evicting oldest item: ${evicted?.id}`);
5715
- this.deadLetterQueue = this.deadLetterQueue.slice(1);
5716
- }
5717
6098
  this.deadLetterQueue = [...this.deadLetterQueue, deadItem];
5718
6099
  await this.persistQueue();
5719
6100
  await this.persistDeadLetter();
@@ -5735,6 +6116,7 @@ class RequestQueue {
5735
6116
  this._onDeadLetter = null;
5736
6117
  this._onFlushComplete = null;
5737
6118
  this._onNetworkError = null;
6119
+ this._onError = null;
5738
6120
  this._headerProvider = null;
5739
6121
  this.MAX_PAYLOAD_SIZE_BYTES = 5 * 1024 * 1024;
5740
6122
  this.MAX_QUEUE_SIZE = 500;
@@ -6164,6 +6546,8 @@ class RequestProvider {
6164
6546
  url,
6165
6547
  method,
6166
6548
  isServer,
6549
+ aad: encOptions.aad,
6550
+ bindRequestContextAad: encOptions.bindRequestContextAad,
6167
6551
  key: encOptions.key,
6168
6552
  valueEncryption: encOptions.valueEncryption,
6169
6553
  fields: encOptions.fields,
@@ -8089,13 +8473,41 @@ class CCookieCache extends ACacheProvider {
8089
8473
  return this.instance;
8090
8474
  }
8091
8475
  type = "Cookie";
8476
+ sameSite = "lax";
8477
+ secure = void 0;
8478
+ httpOnly = true;
8479
+ path = "/";
8092
8480
  // Exposed constructor for testing & instantiation
8093
- constructor() {
8481
+ constructor(options) {
8094
8482
  super();
8483
+ if (options) {
8484
+ this.configure(options);
8485
+ }
8486
+ }
8487
+ configure(options) {
8488
+ if (options.sameSite !== void 0) this.sameSite = options.sameSite;
8489
+ if (options.secure !== void 0) this.secure = options.secure;
8490
+ if (options.httpOnly !== void 0) this.httpOnly = options.httpOnly;
8491
+ if (options.path !== void 0) this.path = options.path;
8095
8492
  }
8096
8493
  getCookieKey(key) {
8097
8494
  return "cache:" + encodeURIComponent(key);
8098
8495
  }
8496
+ /**
8497
+ * Resolves the `Secure` flag: an explicit option wins, otherwise follow the
8498
+ * actual protocol so cookies are not silently dropped by browsers over plain HTTP.
8499
+ */
8500
+ resolveSecure(getRequestProtocol, event) {
8501
+ if (this.secure !== void 0) return this.secure;
8502
+ if (event && getRequestProtocol) {
8503
+ try {
8504
+ return getRequestProtocol(event) === "https";
8505
+ } catch {
8506
+ return false;
8507
+ }
8508
+ }
8509
+ return typeof location !== "undefined" && location.protocol === "https:";
8510
+ }
8099
8511
  parseKeyFromCookieName(cookieName) {
8100
8512
  const prefix = "cache:";
8101
8513
  const decoded = decodeURIComponent(cookieName);
@@ -8201,20 +8613,23 @@ class CCookieCache extends ACacheProvider {
8201
8613
  return;
8202
8614
  }
8203
8615
  const maxAge = Math.floor(lifetime / 1e3);
8616
+ const sameSiteFormatted = this.sameSite.charAt(0).toUpperCase() + this.sameSite.slice(1).toLowerCase();
8204
8617
  if (this.isClient(context)) {
8205
8618
  if (typeof document !== "undefined") {
8206
- document.cookie = `${cookieKey}=${cookieValue}; Max-Age=${maxAge}; Path=/; SameSite=Lax`;
8619
+ const secureFlag = this.resolveSecure() ? "; Secure" : "";
8620
+ document.cookie = `${cookieKey}=${cookieValue}; Max-Age=${maxAge}; Path=${this.path}; SameSite=${sameSiteFormatted}${secureFlag}`;
8207
8621
  }
8208
8622
  } else if (context) {
8209
8623
  const event = context?.event ?? context?.ssrContext?.event ?? (context?.node ? context : null);
8210
8624
  if (event) {
8211
8625
  try {
8212
- const { setCookie } = await getH3();
8626
+ const { setCookie, getRequestProtocol } = await getH3();
8213
8627
  setCookie(event, cookieKey, serialized, {
8214
8628
  maxAge,
8215
- path: "/",
8216
- sameSite: "lax",
8217
- httpOnly: true
8629
+ path: this.path,
8630
+ sameSite: this.sameSite,
8631
+ httpOnly: this.httpOnly,
8632
+ secure: this.resolveSecure(getRequestProtocol, event)
8218
8633
  });
8219
8634
  } catch {
8220
8635
  }
@@ -8223,16 +8638,18 @@ class CCookieCache extends ACacheProvider {
8223
8638
  }
8224
8639
  async remove(key, context) {
8225
8640
  const cookieKey = this.getCookieKey(key);
8641
+ const sameSiteFormatted = this.sameSite.charAt(0).toUpperCase() + this.sameSite.slice(1).toLowerCase();
8226
8642
  if (this.isClient(context)) {
8227
8643
  if (typeof document !== "undefined") {
8228
- document.cookie = `${cookieKey}=; Max-Age=0; Path=/; SameSite=Lax`;
8644
+ const secureFlag = this.resolveSecure() ? "; Secure" : "";
8645
+ document.cookie = `${cookieKey}=; Max-Age=0; Path=${this.path}; SameSite=${sameSiteFormatted}${secureFlag}`;
8229
8646
  }
8230
8647
  } else if (context) {
8231
8648
  const event = context?.event ?? context?.ssrContext?.event ?? (context?.node ? context : null);
8232
8649
  if (event) {
8233
8650
  try {
8234
- const { deleteCookie } = await getH3();
8235
- deleteCookie(event, cookieKey, { path: "/", sameSite: "lax", httpOnly: true });
8651
+ const { deleteCookie, getRequestProtocol } = await getH3();
8652
+ deleteCookie(event, cookieKey, { path: this.path, sameSite: this.sameSite, httpOnly: this.httpOnly, secure: this.resolveSecure(getRequestProtocol, event) });
8236
8653
  } catch {
8237
8654
  }
8238
8655
  }
@@ -8486,7 +8903,11 @@ class CServerSessionCache extends ACacheProvider {
8486
8903
  CServerSessionCache._opCounter = 0;
8487
8904
  CServerSessionCache.purgeExpiredServerSessions(50);
8488
8905
  } else if (CServerSessionCache.storage.size >= CServerSessionCache.MAX_SERVER_SESSIONS) {
8489
- CServerSessionCache.purgeExpiredServerSessions();
8906
+ CServerSessionCache.purgeExpiredServerSessions(50);
8907
+ if (CServerSessionCache.storage.size >= CServerSessionCache.MAX_SERVER_SESSIONS) {
8908
+ const oldestKey = CServerSessionCache.storage.keys().next().value;
8909
+ if (oldestKey !== void 0) CServerSessionCache.storage.delete(oldestKey);
8910
+ }
8490
8911
  }
8491
8912
  let sessionData = CServerSessionCache.storage.get(sessionId);
8492
8913
  if (sessionData) {
@@ -9538,6 +9959,7 @@ exports.getSSRData = getSSRData;
9538
9959
  exports.getSSRPayload = getSSRPayload;
9539
9960
  exports.getSafeKeyIdentifier = getSafeKeyIdentifier;
9540
9961
  exports.getSubtleCrypto = getSubtleCrypto;
9962
+ exports.isAuthOrDecryptionError = isAuthOrDecryptionError;
9541
9963
  exports.isDataEncrypted = isDataEncrypted;
9542
9964
  exports.isEncrypted = isEncrypted;
9543
9965
  exports.normalizeIndexTerm = normalizeIndexTerm;