@katlux/providers 0.1.1-alpha.109 → 0.1.1-alpha.112

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
@@ -276,6 +276,9 @@ class ADataProvider {
276
276
  this.notify();
277
277
  }
278
278
  }
279
+ getSelectedRows() {
280
+ return this._selectAll ? this.pageData : this._selectedRows;
281
+ }
279
282
  _currentPage = 1;
280
283
  _pageSize = 10;
281
284
  _filter = null;
@@ -356,6 +359,10 @@ class ADataProvider {
356
359
  const sortDebounceTime = typeof options?.sortDebounce === "number" ? options.sortDebounce : 200;
357
360
  this._debouncedFilterLoad = useDebounce(() => {
358
361
  this._currentPage = 1;
362
+ this._selectAll = false;
363
+ this._selectedRows = [];
364
+ this._pendingChangedKeys.add("selectAll");
365
+ this._pendingChangedKeys.add("selectedRows");
359
366
  this.loadPageData();
360
367
  }, filterDebounceTime);
361
368
  this._debouncedSortLoad = useDebounce(() => {
@@ -550,8 +557,12 @@ class ADataProvider {
550
557
  this._filter = filter;
551
558
  this.onFilterUpdated();
552
559
  this._currentPage = 1;
560
+ this._selectAll = false;
561
+ this._selectedRows = [];
553
562
  this._pendingChangedKeys.add("filter");
554
563
  this._pendingChangedKeys.add("currentPage");
564
+ this._pendingChangedKeys.add("selectAll");
565
+ this._pendingChangedKeys.add("selectedRows");
555
566
  if (immediate) {
556
567
  this._debouncedFilterLoad?.cancel?.();
557
568
  this.loadPageData();
@@ -705,6 +716,14 @@ function getKeyIdentifier(keyProvider, defaultKey) {
705
716
  const target = keyProvider ?? defaultKey;
706
717
  return getSafeKeyIdentifier(target);
707
718
  }
719
+ function isAuthOrDecryptionError(err) {
720
+ if (!err) return false;
721
+ if (err.name === "OperationError") return true;
722
+ if (err.code === "ERR_CRYPTO_OPERATION_FAILED" || err.code === "ERR_OSSL_EVP_BAD_DECRYPT") return true;
723
+ if (err.cause && isAuthOrDecryptionError(err.cause)) return true;
724
+ const msg = String(err.message || "").toLowerCase();
725
+ 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");
726
+ }
708
727
 
709
728
  class AEncryptionProvider {
710
729
  defaultKey;
@@ -783,6 +802,57 @@ class AEncryptionProvider {
783
802
  async [Symbol.asyncDispose]() {
784
803
  this.dispose();
785
804
  }
805
+ /**
806
+ * Resolves effective Authenticated Additional Data (AAD) for the operation:
807
+ * 1. If options.bindRequestContextAad is explicitly false, returns options.aad directly without context binding.
808
+ * 2. When encrypting (isDecrypt=false): binds request context `req:${method}:${url}` only if options.bindRequestContextAad === true.
809
+ * 3. When decrypting (isDecrypt=true): derives request context `req:${method}:${url}` if url or method is provided.
810
+ * 4. If explicit options.aad is provided: combines with request context if bound, or returns options.aad directly.
811
+ * 5. Otherwise returns undefined.
812
+ */
813
+ _resolveEffectiveAad(options, isDecrypt = false) {
814
+ if (!options) return void 0;
815
+ if (options.bindRequestContextAad === false) return options.aad;
816
+ const hasReqContext = Boolean(options.url || options.method);
817
+ if (options.aad) {
818
+ if (options.bindRequestContextAad === true && hasReqContext) {
819
+ const m = (options.method || "POST").toUpperCase();
820
+ const u = options.url || "";
821
+ const baseAad = typeof options.aad === "string" ? options.aad : options.aad instanceof Uint8Array || options.aad instanceof ArrayBuffer ? textDecoder.decode(options.aad) : String(options.aad);
822
+ return `${baseAad}|req:${m}:${u}`;
823
+ }
824
+ return options.aad;
825
+ }
826
+ const shouldBindReq = isDecrypt ? hasReqContext : options.bindRequestContextAad === true && hasReqContext;
827
+ if (shouldBindReq) {
828
+ const m = (options.method || "POST").toUpperCase();
829
+ const u = options.url || "";
830
+ return `req:${m}:${u}`;
831
+ }
832
+ return void 0;
833
+ }
834
+ /**
835
+ * Helper to deterministically bind record ID and field name into the AAD
836
+ * to prevent ciphertext swapping between fields or records.
837
+ */
838
+ _bindFieldAad(data, field, options) {
839
+ let baseAad = "";
840
+ if (options?.aad) {
841
+ if (typeof options.aad === "string") baseAad = options.aad;
842
+ else if (options.aad instanceof Uint8Array || options.aad instanceof ArrayBuffer) {
843
+ baseAad = textDecoder.decode(options.aad);
844
+ } else {
845
+ baseAad = String(options.aad);
846
+ }
847
+ }
848
+ const recordId = data && typeof data === "object" && (data.id !== void 0 || data._id !== void 0) ? String(data.id ?? data._id) : "";
849
+ const recordPart = recordId ? `|record:${recordId}` : "";
850
+ const reqPart = options?.bindRequestContextAad === true && (options?.url || options?.method) ? `|req:${(options.method || "POST").toUpperCase()}:${options.url || ""}` : "";
851
+ return {
852
+ ...options,
853
+ aad: `aad:${baseAad}${recordPart}${reqPart}|field:${field}`
854
+ };
855
+ }
786
856
  /**
787
857
  * Top-level polymorphic encryption method.
788
858
  * Automatically performs value-level encryption:
@@ -818,7 +888,10 @@ class AEncryptionProvider {
818
888
  }
819
889
  const result = { ...data };
820
890
  const entries = await Promise.all(
821
- fieldsToEncrypt.map(async (field) => [field, await this.encryptValue(result[field], options)])
891
+ fieldsToEncrypt.map(async (field) => {
892
+ const fieldOptions = this._bindFieldAad(data, field, options);
893
+ return [field, await this.encryptValue(result[field], fieldOptions)];
894
+ })
822
895
  );
823
896
  for (const [field, encryptedVal] of entries) {
824
897
  safeSetProperty(result, field, encryptedVal);
@@ -837,7 +910,10 @@ class AEncryptionProvider {
837
910
  await this.warmupKey(options);
838
911
  }
839
912
  const entries = await Promise.all(
840
- keysToEncrypt.map(async (key) => [key, await this.encryptValue(result[key], options)])
913
+ keysToEncrypt.map(async (key) => {
914
+ const fieldOptions = this._bindFieldAad(data, key, options);
915
+ return [key, await this.encryptValue(result[key], fieldOptions)];
916
+ })
841
917
  );
842
918
  for (const [key, encryptedVal] of entries) {
843
919
  safeSetProperty(result, key, encryptedVal);
@@ -870,7 +946,22 @@ class AEncryptionProvider {
870
946
  return payload;
871
947
  }
872
948
  const entries = await Promise.all(
873
- keysToDecrypt.map(async (key) => [key, await this.decryptValue(result[key], options)])
949
+ keysToDecrypt.map(async (key) => {
950
+ const boundOptions = this._bindFieldAad(payload, key, options);
951
+ const hasBoundAad = boundOptions.aad !== options?.aad;
952
+ try {
953
+ return [key, await this.decryptValue(result[key], boundOptions)];
954
+ } catch (err) {
955
+ if (hasBoundAad && isAuthOrDecryptionError(err)) {
956
+ try {
957
+ return [key, await this.decryptValue(result[key], options)];
958
+ } catch (fallbackErr) {
959
+ throw fallbackErr;
960
+ }
961
+ }
962
+ throw err;
963
+ }
964
+ })
874
965
  );
875
966
  for (const [key, decryptedVal] of entries) {
876
967
  safeSetProperty(result, key, decryptedVal);
@@ -1242,11 +1333,11 @@ ${lines.join("\n")}
1242
1333
  * Generates a high-entropy symmetric AES-GCM Account Data Encryption Key (ADEK).
1243
1334
  * Designed for multi-user table and field-level encryption.
1244
1335
  */
1245
- static async generateAccountDataKey(length = 256) {
1336
+ static async generateAccountDataKey(length = 256, extractable = false) {
1246
1337
  const subtle = getSubtleCrypto();
1247
1338
  return await subtle.generateKey(
1248
1339
  { name: "AES-GCM", length },
1249
- true,
1340
+ extractable,
1250
1341
  ["encrypt", "decrypt"]
1251
1342
  );
1252
1343
  }
@@ -1277,7 +1368,7 @@ ${lines.join("\n")}
1277
1368
  * Unwraps a Base64-encoded Account Data Encryption Key (ADEK) using the user's private key (RSA-OAEP).
1278
1369
  * Returns the restored AES-GCM CryptoKey ready for use in CWebCryptoEncryptionProvider.
1279
1370
  */
1280
- static async unwrapAccountKeyForUser(wrappedKeyBase64, userPrivateKey, unwrappedKeyAlgorithm = { name: "AES-GCM", length: 256 }) {
1371
+ static async unwrapAccountKeyForUser(wrappedKeyBase64, userPrivateKey, unwrappedKeyAlgorithm = { name: "AES-GCM", length: 256 }, extractable = false) {
1281
1372
  const subtle = getSubtleCrypto();
1282
1373
  if (userPrivateKey.algorithm.name === "RSA-OAEP") {
1283
1374
  const wrappedBytes = CKeyManager.fromBase64(wrappedKeyBase64);
@@ -1296,7 +1387,7 @@ ${lines.join("\n")}
1296
1387
  "raw",
1297
1388
  unwrappedRawKey,
1298
1389
  unwrappedKeyAlgorithm,
1299
- true,
1390
+ extractable,
1300
1391
  ["encrypt", "decrypt"]
1301
1392
  );
1302
1393
  } finally {
@@ -1469,12 +1560,13 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1469
1560
  return options._warmedKey;
1470
1561
  }
1471
1562
  if (saltOverride) {
1563
+ const rawKey = await this.resolveRawKey(keyProvider);
1472
1564
  const saltKey = typeof saltOverride === "string" ? saltOverride : CKeyManager.toBase64(saltOverride);
1473
- const keyId = getKeyIdentifier(keyProvider, this.defaultKey);
1565
+ const keyId = getSafeKeyIdentifier(rawKey);
1474
1566
  const compoundKey = `${keyId}:${kdfOverride || ""}:${iterationsOverride || ""}:${options?.kdfHash || ""}:${saltKey}`;
1475
1567
  let cached = this._decryptSaltCache.get(compoundKey);
1476
1568
  if (!cached) {
1477
- cached = this._resolveCryptoKeyInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1569
+ cached = this._resolveCryptoKeyInternal(rawKey, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1478
1570
  this._decryptSaltCache.delete(compoundKey);
1479
1571
  throw err;
1480
1572
  });
@@ -1531,9 +1623,9 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1531
1623
  const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
1532
1624
  const matchesKdf = this._cachedKdf !== void 0 && kdf === this._cachedKdf.toLowerCase();
1533
1625
  const matchesSalt = !saltOverride || this._cachedSalt !== void 0 && saltOverride === this._cachedSalt;
1534
- const currentKeyId = getKeyIdentifier(keyProvider, this.defaultKey);
1626
+ const currentKeyId = getSafeKeyIdentifier(rawKey);
1535
1627
  if (this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
1536
- if (!this._cachedKeyId || this._cachedKeyId === currentKeyId) {
1628
+ if (this._cachedKeyId === currentKeyId) {
1537
1629
  return { cryptoKey: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
1538
1630
  }
1539
1631
  }
@@ -1654,7 +1746,7 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1654
1746
  name: "AES-GCM",
1655
1747
  iv
1656
1748
  };
1657
- const aad = options?.aad;
1749
+ const aad = this._resolveEffectiveAad(options, false);
1658
1750
  let hasAad = false;
1659
1751
  if (aad) {
1660
1752
  const aadBytes = typeof aad === "string" ? textEncoder$1.encode(aad) : aad instanceof Uint8Array ? aad : new Uint8Array(aad);
@@ -1716,22 +1808,45 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1716
1808
  name: "AES-GCM",
1717
1809
  iv
1718
1810
  };
1719
- const aad = options?.aad;
1811
+ const aad = this._resolveEffectiveAad(options, true);
1812
+ let hasAad = false;
1720
1813
  if (payload.aad || aad) {
1721
1814
  if (aad) {
1722
1815
  const aadBytes = typeof aad === "string" ? textEncoder$1.encode(aad) : aad instanceof Uint8Array ? aad : new Uint8Array(aad);
1723
1816
  if (aadBytes.byteLength > 0) {
1724
1817
  decryptParams.additionalData = aadBytes;
1818
+ hasAad = true;
1725
1819
  }
1726
1820
  } else if (payload.aad) {
1727
1821
  throw new Error("[CWebCryptoEncryptionProvider] Payload requires Authenticated Additional Data (AAD) for decryption, but none was provided.");
1728
1822
  }
1729
1823
  }
1730
- const decryptedBuffer = await subtle.decrypt(
1731
- decryptParams,
1732
- cryptoKey,
1733
- ciphertextBytes
1734
- );
1824
+ let decryptedBuffer;
1825
+ try {
1826
+ decryptedBuffer = await subtle.decrypt(
1827
+ decryptParams,
1828
+ cryptoKey,
1829
+ ciphertextBytes
1830
+ );
1831
+ } catch (firstErr) {
1832
+ if (!payload.aad && hasAad) {
1833
+ try {
1834
+ const fallbackParams = {
1835
+ name: "AES-GCM",
1836
+ iv
1837
+ };
1838
+ decryptedBuffer = await subtle.decrypt(
1839
+ fallbackParams,
1840
+ cryptoKey,
1841
+ ciphertextBytes
1842
+ );
1843
+ } catch {
1844
+ throw firstErr;
1845
+ }
1846
+ } else {
1847
+ throw firstErr;
1848
+ }
1849
+ }
1735
1850
  try {
1736
1851
  const jsonString = textDecoder.decode(decryptedBuffer);
1737
1852
  return JSON.parse(jsonString);
@@ -1740,7 +1855,12 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1740
1855
  }
1741
1856
  } catch (err) {
1742
1857
  if (err instanceof SyntaxError) throw err;
1743
- throw new Error(`[CWebCryptoEncryptionProvider] Decryption failed: ${err?.message || "Authentication tag mismatch or corrupted ciphertext"}`);
1858
+ const decryptError = new Error(`[CWebCryptoEncryptionProvider] Decryption failed: ${err?.message || "Authentication tag mismatch or corrupted ciphertext"}`);
1859
+ if (err?.name) {
1860
+ decryptError.name = err.name;
1861
+ }
1862
+ decryptError.cause = err;
1863
+ throw decryptError;
1744
1864
  }
1745
1865
  }
1746
1866
  }
@@ -1753,6 +1873,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1753
1873
  _cachedKdf;
1754
1874
  _cachedIter;
1755
1875
  _cachedHash;
1876
+ _cachedKeyId;
1756
1877
  _configuredKid;
1757
1878
  _kdfOptions;
1758
1879
  _decryptSaltCache = /* @__PURE__ */ new Map();
@@ -1763,9 +1884,9 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1763
1884
  this._configuredKid = options.kid || options.keyId;
1764
1885
  }
1765
1886
  this._defaultKdf = options.kdf || "pbkdf2";
1766
- if (options.kdf && options.kdf !== "none") {
1887
+ if (this._defaultKdf !== "none") {
1767
1888
  this._kdfOptions = {
1768
- kdf: options.kdf,
1889
+ kdf: this._defaultKdf,
1769
1890
  iterations: options.kdfIterations,
1770
1891
  hash: options.kdfHash,
1771
1892
  salt: options.kdfSalt,
@@ -1782,6 +1903,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1782
1903
  this._cachedKdf = void 0;
1783
1904
  this._cachedIter = void 0;
1784
1905
  this._cachedHash = void 0;
1906
+ this._cachedKeyId = void 0;
1785
1907
  this._decryptSaltCache.clear();
1786
1908
  }
1787
1909
  clearKeys() {
@@ -1792,6 +1914,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1792
1914
  this._cachedKdf = void 0;
1793
1915
  this._cachedIter = void 0;
1794
1916
  this._cachedHash = void 0;
1917
+ this._cachedKeyId = void 0;
1795
1918
  this._decryptSaltCache.clear();
1796
1919
  }
1797
1920
  async warmupKey(options) {
@@ -1812,12 +1935,14 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1812
1935
  */
1813
1936
  async resolveCBCKeys(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
1814
1937
  if (saltOverride) {
1938
+ const rawKey = await this.resolveRawKey(keyProvider);
1815
1939
  const saltKey = typeof saltOverride === "string" ? saltOverride : CKeyManager.toBase64(saltOverride);
1816
- const keyId = getKeyIdentifier(keyProvider, this.defaultKey);
1817
- const compoundKey = `${keyId}:${kdfOverride || ""}:${iterationsOverride || ""}:${options?.kdfHash || ""}:${saltKey}`;
1940
+ const keyId = getSafeKeyIdentifier(rawKey);
1941
+ const effectiveHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
1942
+ const compoundKey = `${keyId}:${kdfOverride || ""}:${iterationsOverride || ""}:${effectiveHash}:${saltKey}`;
1818
1943
  let cached = this._decryptSaltCache.get(compoundKey);
1819
1944
  if (!cached) {
1820
- cached = this._deriveCBCKeysInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1945
+ cached = this._deriveCBCKeysInternal(rawKey, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1821
1946
  this._decryptSaltCache.delete(compoundKey);
1822
1947
  throw err;
1823
1948
  });
@@ -1837,17 +1962,20 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1837
1962
  return await this._deriveCBCKeysInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride);
1838
1963
  }
1839
1964
  async _deriveCBCKeysInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
1965
+ const rawKey = await this.resolveRawKey(keyProvider);
1966
+ const currentKeyId = getSafeKeyIdentifier(rawKey);
1840
1967
  const subtle = getSubtleCrypto();
1841
- const targetIter = iterationsOverride || options?.kdfIterations;
1842
- const targetHash = options?.kdfHash;
1968
+ const targetIter = iterationsOverride || options?.kdfIterations || this._kdfOptions?.iterations;
1969
+ const targetHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
1843
1970
  const matchesIter = !targetIter || this._cachedIter !== void 0 && targetIter === this._cachedIter;
1844
- const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
1971
+ const matchesHash = this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
1845
1972
  const effectiveKdf = (kdfOverride || options?.kdf || this._defaultKdf || "none").toLowerCase();
1846
1973
  const matchesKdf = this._cachedKdf === "raw" || this._cachedKdf === "hkdf-direct" || this._cachedKdf !== void 0 && effectiveKdf === this._cachedKdf.toLowerCase();
1847
- if (!keyProvider && this._cachedEncKey && this._cachedMacKey && !saltOverride && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
1848
- return { encKey: this._cachedEncKey, macKey: this._cachedMacKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
1974
+ if (this._cachedEncKey && this._cachedMacKey && !saltOverride && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
1975
+ if (this._cachedKeyId === currentKeyId) {
1976
+ return { encKey: this._cachedEncKey, macKey: this._cachedMacKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
1977
+ }
1849
1978
  }
1850
- const rawKey = await this.resolveRawKey(keyProvider);
1851
1979
  if (typeof rawKey !== "string" && rawKey.algorithm) {
1852
1980
  const cryptoKey = rawKey;
1853
1981
  let rawBits;
@@ -1880,6 +2008,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1880
2008
  this._cachedEncKey = encKey2;
1881
2009
  this._cachedMacKey = macKey2;
1882
2010
  this._cachedKdf = "hkdf-direct";
2011
+ this._cachedKeyId = currentKeyId;
1883
2012
  }
1884
2013
  return { encKey: encKey2, macKey: macKey2, kdf: "hkdf-direct" };
1885
2014
  }
@@ -1913,6 +2042,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1913
2042
  this._cachedEncKey = encKey2;
1914
2043
  this._cachedMacKey = macKey2;
1915
2044
  this._cachedKdf = "raw";
2045
+ this._cachedKeyId = currentKeyId;
1916
2046
  }
1917
2047
  return { encKey: encKey2, macKey: macKey2, kdf: "raw" };
1918
2048
  }
@@ -1943,6 +2073,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1943
2073
  this._cachedEncKey = encKey2;
1944
2074
  this._cachedMacKey = macKey2;
1945
2075
  this._cachedKdf = "raw";
2076
+ this._cachedKeyId = currentKeyId;
1946
2077
  }
1947
2078
  return { encKey: encKey2, macKey: macKey2, kdf: "raw" };
1948
2079
  }
@@ -2050,6 +2181,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
2050
2181
  this._cachedKdf = kdfType || "none";
2051
2182
  this._cachedIter = iterNum;
2052
2183
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
2184
+ this._cachedKeyId = currentKeyId;
2053
2185
  }
2054
2186
  return {
2055
2187
  encKey,
@@ -2950,6 +3082,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2950
3082
  _cachedKdf;
2951
3083
  _cachedIter;
2952
3084
  _cachedHash;
3085
+ _cachedKeyId;
2953
3086
  _configuredKid;
2954
3087
  setDefaultKey(key) {
2955
3088
  super.setDefaultKey(key);
@@ -2961,6 +3094,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2961
3094
  this._cachedKdf = void 0;
2962
3095
  this._cachedIter = void 0;
2963
3096
  this._cachedHash = void 0;
3097
+ this._cachedKeyId = void 0;
2964
3098
  }
2965
3099
  clearKeys() {
2966
3100
  super.clearKeys();
@@ -2972,6 +3106,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2972
3106
  this._cachedKdf = void 0;
2973
3107
  this._cachedIter = void 0;
2974
3108
  this._cachedHash = void 0;
3109
+ this._cachedKeyId = void 0;
2975
3110
  }
2976
3111
  async warmupKey(options) {
2977
3112
  const res = await this.deriveKeyAsync(options?.key, void 0, void 0, options);
@@ -2981,6 +3116,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2981
3116
  this._cachedKdf = res.kdf;
2982
3117
  this._cachedIter = res.iter;
2983
3118
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3119
+ this._cachedKeyId = getSafeKeyIdentifier(await this.resolveRawKeyAsync(options?.key));
2984
3120
  }
2985
3121
  }
2986
3122
  /**
@@ -2994,6 +3130,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2994
3130
  this._cachedKdf = res.kdf;
2995
3131
  this._cachedIter = res.iter;
2996
3132
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3133
+ this._cachedKeyId = getSafeKeyIdentifier(this.resolveRawKeySync(options?.key));
2997
3134
  }
2998
3135
  }
2999
3136
  resolveInfoBuffer(infoRaw) {
@@ -3080,12 +3217,14 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3080
3217
  }
3081
3218
  deriveKeySync(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
3082
3219
  const raw = this.resolveRawKeySync(keyProvider);
3220
+ const currentKeyId = getSafeKeyIdentifier(raw);
3083
3221
  if (Buffer.isBuffer(raw)) {
3084
3222
  if (raw.length === 32) {
3085
3223
  if (!keyProvider) {
3086
- if (!this._cachedKey) {
3224
+ if (!this._cachedKey || this._cachedKeyId !== currentKeyId) {
3087
3225
  this._cachedKey = Buffer.from(raw);
3088
3226
  this._cachedKdf = "raw";
3227
+ this._cachedKeyId = currentKeyId;
3089
3228
  }
3090
3229
  return { key: this._cachedKey, kdf: "raw" };
3091
3230
  }
@@ -3103,8 +3242,10 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3103
3242
  const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
3104
3243
  const matchesKdf = this._cachedKdf !== void 0 && kdf === this._cachedKdf.toLowerCase();
3105
3244
  const matchesSalt = !saltOverride || this._cachedSalt !== void 0 && saltOverride === this._cachedSalt;
3106
- if (!keyProvider && this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3107
- return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3245
+ if (this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3246
+ if (this._cachedKeyId === currentKeyId) {
3247
+ return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3248
+ }
3108
3249
  }
3109
3250
  if (kdf === "pbkdf2") {
3110
3251
  const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
@@ -3120,6 +3261,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3120
3261
  this._cachedKdf = "PBKDF2";
3121
3262
  this._cachedIter = iterations;
3122
3263
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3264
+ this._cachedKeyId = currentKeyId;
3123
3265
  }
3124
3266
  return {
3125
3267
  key: key2,
@@ -3145,6 +3287,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3145
3287
  this._cachedSalt = saltBuf.toString("base64");
3146
3288
  this._cachedKdf = "HKDF";
3147
3289
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3290
+ this._cachedKeyId = currentKeyId;
3148
3291
  }
3149
3292
  return {
3150
3293
  key: key2,
@@ -3157,24 +3300,27 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3157
3300
  "[CNodeCryptoEncryptionProvider] WARNING: Decrypting a legacy envelope with no KDF (raw SHA-256 key derivation). This is cryptographically weak. Migrate to pbkdf2 or hkdf."
3158
3301
  );
3159
3302
  }
3160
- if (!keyProvider && this._cachedKey && this._cachedKdf === "none") {
3303
+ if (!keyProvider && this._cachedKey && this._cachedKdf === "none" && this._cachedKeyId === currentKeyId) {
3161
3304
  return { key: this._cachedKey, kdf: "none" };
3162
3305
  }
3163
3306
  const key = crypto__namespace.createHash("sha256").update(passphrase, "utf8").digest();
3164
3307
  if (!keyProvider) {
3165
3308
  this._cachedKey = key;
3166
3309
  this._cachedKdf = "none";
3310
+ this._cachedKeyId = currentKeyId;
3167
3311
  }
3168
3312
  return { key, kdf: "none" };
3169
3313
  }
3170
3314
  async deriveKeyAsync(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
3171
3315
  const raw = await this.resolveRawKeyAsync(keyProvider);
3316
+ const currentKeyId = getSafeKeyIdentifier(raw);
3172
3317
  if (Buffer.isBuffer(raw)) {
3173
3318
  if (raw.length === 32) {
3174
3319
  if (!keyProvider) {
3175
- if (!this._cachedKey) {
3320
+ if (!this._cachedKey || this._cachedKeyId !== currentKeyId) {
3176
3321
  this._cachedKey = Buffer.from(raw);
3177
3322
  this._cachedKdf = "raw";
3323
+ this._cachedKeyId = currentKeyId;
3178
3324
  }
3179
3325
  return { key: this._cachedKey, kdf: "raw" };
3180
3326
  }
@@ -3192,8 +3338,10 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3192
3338
  const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
3193
3339
  const matchesKdf = this._cachedKdf !== void 0 && kdf === this._cachedKdf.toLowerCase();
3194
3340
  const matchesSalt = !saltOverride || this._cachedSalt !== void 0 && saltOverride === this._cachedSalt;
3195
- if (!keyProvider && this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3196
- return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3341
+ if (this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3342
+ if (this._cachedKeyId === currentKeyId) {
3343
+ return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3344
+ }
3197
3345
  }
3198
3346
  if (kdf === "pbkdf2") {
3199
3347
  const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
@@ -3214,6 +3362,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3214
3362
  this._cachedKdf = "PBKDF2";
3215
3363
  this._cachedIter = iterations;
3216
3364
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3365
+ this._cachedKeyId = currentKeyId;
3217
3366
  }
3218
3367
  return {
3219
3368
  key: key2,
@@ -3244,6 +3393,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3244
3393
  this._cachedSalt = saltBuf.toString("base64");
3245
3394
  this._cachedKdf = "HKDF";
3246
3395
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3396
+ this._cachedKeyId = currentKeyId;
3247
3397
  }
3248
3398
  return {
3249
3399
  key: key2,
@@ -3256,13 +3406,14 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3256
3406
  "[CNodeCryptoEncryptionProvider] WARNING: Decrypting a legacy envelope with no KDF (raw SHA-256 key derivation). This is cryptographically weak. Migrate to pbkdf2 or hkdf."
3257
3407
  );
3258
3408
  }
3259
- if (!keyProvider && this._cachedKey && this._cachedKdf === "none") {
3409
+ if (!keyProvider && this._cachedKey && this._cachedKdf === "none" && this._cachedKeyId === currentKeyId) {
3260
3410
  return { key: this._cachedKey, kdf: "none" };
3261
3411
  }
3262
3412
  const key = crypto__namespace.createHash("sha256").update(passphrase, "utf8").digest();
3263
3413
  if (!keyProvider) {
3264
3414
  this._cachedKey = key;
3265
3415
  this._cachedKdf = "none";
3416
+ this._cachedKeyId = currentKeyId;
3266
3417
  }
3267
3418
  return { key, kdf: "none" };
3268
3419
  }
@@ -3289,7 +3440,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3289
3440
  const jsonString = JSON.stringify(data);
3290
3441
  const iv = crypto__namespace.randomBytes(12);
3291
3442
  const cipher = crypto__namespace.createCipheriv("aes-256-gcm", key, iv);
3292
- const aad = options?.aad;
3443
+ const aad = this._resolveEffectiveAad(options, false);
3293
3444
  let hasAad = false;
3294
3445
  if (aad) {
3295
3446
  const aadBuffer = Buffer.isBuffer(aad) ? aad : Buffer.from(typeof aad === "string" ? aad : new Uint8Array(aad));
@@ -3342,21 +3493,41 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3342
3493
  }
3343
3494
  const decipher = crypto__namespace.createDecipheriv("aes-256-gcm", key, iv, { authTagLength: 16 });
3344
3495
  decipher.setAuthTag(authTag);
3345
- const aad = options?.aad;
3496
+ const aad = this._resolveEffectiveAad(options, true);
3497
+ let hasAad = false;
3346
3498
  if (payload.aad || aad) {
3347
3499
  if (aad) {
3348
3500
  const aadBuffer = Buffer.isBuffer(aad) ? aad : Buffer.from(typeof aad === "string" ? aad : new Uint8Array(aad));
3349
3501
  if (aadBuffer.length > 0) {
3350
3502
  decipher.setAAD(aadBuffer);
3503
+ hasAad = true;
3351
3504
  }
3352
3505
  } else if (payload.aad) {
3353
3506
  throw new Error("[CNodeCryptoEncryptionProvider] Payload requires Authenticated Additional Data (AAD) for decryption, but none was provided.");
3354
3507
  }
3355
3508
  }
3356
- const decrypted = Buffer.concat([
3357
- decipher.update(ciphertext),
3358
- decipher.final()
3359
- ]);
3509
+ let decrypted;
3510
+ try {
3511
+ decrypted = Buffer.concat([
3512
+ decipher.update(ciphertext),
3513
+ decipher.final()
3514
+ ]);
3515
+ } catch (firstErr) {
3516
+ if (!payload.aad && hasAad) {
3517
+ try {
3518
+ const fallbackDecipher = crypto__namespace.createDecipheriv("aes-256-gcm", key, iv, { authTagLength: 16 });
3519
+ fallbackDecipher.setAuthTag(authTag);
3520
+ decrypted = Buffer.concat([
3521
+ fallbackDecipher.update(ciphertext),
3522
+ fallbackDecipher.final()
3523
+ ]);
3524
+ } catch {
3525
+ throw firstErr;
3526
+ }
3527
+ } else {
3528
+ throw firstErr;
3529
+ }
3530
+ }
3360
3531
  try {
3361
3532
  const jsonString = decrypted.toString("utf8");
3362
3533
  return JSON.parse(jsonString);
@@ -3409,7 +3580,8 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3409
3580
  if (fieldsToEncrypt.length === 0) return { ...data };
3410
3581
  const result = { ...data };
3411
3582
  for (const field of fieldsToEncrypt) {
3412
- safeSetProperty(result, field, this.encryptValueSync(result[field], options));
3583
+ const fieldOptions = this._bindFieldAad(data, field, options);
3584
+ safeSetProperty(result, field, this.encryptValueSync(result[field], fieldOptions));
3413
3585
  }
3414
3586
  return result;
3415
3587
  }
@@ -3417,7 +3589,8 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3417
3589
  const result = { ...data };
3418
3590
  for (const key of Object.keys(result)) {
3419
3591
  if (result[key] !== void 0 && result[key] !== null && !this.isEncrypted(result[key])) {
3420
- safeSetProperty(result, key, this.encryptValueSync(result[key], options));
3592
+ const fieldOptions = this._bindFieldAad(data, key, options);
3593
+ safeSetProperty(result, key, this.encryptValueSync(result[key], fieldOptions));
3421
3594
  }
3422
3595
  }
3423
3596
  return result;
@@ -3456,7 +3629,21 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3456
3629
  derivedKey = derived.key;
3457
3630
  keyCache.set(salt, derivedKey);
3458
3631
  }
3459
- safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3632
+ const boundOptions = this._bindFieldAad(payload, key, options);
3633
+ const hasBoundAad = boundOptions.aad !== options?.aad;
3634
+ try {
3635
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, boundOptions));
3636
+ } catch (err) {
3637
+ if (hasBoundAad && isAuthOrDecryptionError(err)) {
3638
+ try {
3639
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3640
+ } catch (fallbackErr) {
3641
+ throw fallbackErr;
3642
+ }
3643
+ } else {
3644
+ throw err;
3645
+ }
3646
+ }
3460
3647
  mutated = true;
3461
3648
  }
3462
3649
  }
@@ -3496,7 +3683,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3496
3683
  const jsonString = JSON.stringify(data);
3497
3684
  const iv = crypto__namespace.randomBytes(12);
3498
3685
  const cipher = crypto__namespace.createCipheriv("aes-256-gcm", key, iv);
3499
- const aad = options?.aad;
3686
+ const aad = this._resolveEffectiveAad(options, false);
3500
3687
  let hasAad = false;
3501
3688
  if (aad) {
3502
3689
  const aadBuffer = Buffer.isBuffer(aad) ? aad : Buffer.from(typeof aad === "string" ? aad : new Uint8Array(aad));
@@ -3584,7 +3771,21 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3584
3771
  derivedKey = derived.key;
3585
3772
  keyCache.set(salt, derivedKey);
3586
3773
  }
3587
- safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3774
+ const boundOptions = this._bindFieldAad(payload, key, options);
3775
+ const hasBoundAad = boundOptions.aad !== options?.aad;
3776
+ try {
3777
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, boundOptions));
3778
+ } catch (err) {
3779
+ if (hasBoundAad && isAuthOrDecryptionError(err)) {
3780
+ try {
3781
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3782
+ } catch (fallbackErr) {
3783
+ throw fallbackErr;
3784
+ }
3785
+ } else {
3786
+ throw err;
3787
+ }
3788
+ }
3588
3789
  mutated = true;
3589
3790
  }
3590
3791
  }
@@ -4592,6 +4793,12 @@ class CFlatClientDataProvider extends AEncryptedClientProvider {
4592
4793
  }
4593
4794
  });
4594
4795
  }
4796
+ getSelectedRows() {
4797
+ if (this.selectAll) {
4798
+ return this.filteredData && this.filteredData.length > 0 ? this.filteredData : this.allData;
4799
+ }
4800
+ return this.selectedRows;
4801
+ }
4595
4802
  }
4596
4803
 
4597
4804
  class CacheProviderFactory {
@@ -5321,6 +5528,48 @@ function generateId() {
5321
5528
  }
5322
5529
  return Date.now().toString(36) + Math.random().toString(36).slice(2);
5323
5530
  }
5531
+ function uint8ArrayToBase64(bytes) {
5532
+ if (typeof Buffer !== "undefined") {
5533
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
5534
+ }
5535
+ let binary = "";
5536
+ const chunkSize = 8192;
5537
+ for (let i = 0; i < bytes.byteLength; i += chunkSize) {
5538
+ const chunk = bytes.subarray(i, i + chunkSize);
5539
+ binary += String.fromCharCode.apply(null, chunk);
5540
+ }
5541
+ return btoa(binary);
5542
+ }
5543
+ function base64ToUint8Array(base64) {
5544
+ if (typeof Buffer !== "undefined") {
5545
+ const buf = Buffer.from(base64, "base64");
5546
+ return new Uint8Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));
5547
+ }
5548
+ const binary = atob(base64);
5549
+ const bytes = new Uint8Array(binary.length);
5550
+ for (let i = 0; i < binary.length; i++) {
5551
+ bytes[i] = binary.charCodeAt(i);
5552
+ }
5553
+ return bytes;
5554
+ }
5555
+ async function readBlobAsUint8Array(blob) {
5556
+ if (typeof blob.arrayBuffer === "function") {
5557
+ const buffer = await blob.arrayBuffer();
5558
+ return new Uint8Array(buffer);
5559
+ }
5560
+ if (typeof FileReader !== "undefined") {
5561
+ return new Promise((resolve, reject) => {
5562
+ const reader = new FileReader();
5563
+ reader.onload = () => {
5564
+ const buffer = reader.result;
5565
+ resolve(new Uint8Array(buffer));
5566
+ };
5567
+ reader.onerror = () => reject(reader.error);
5568
+ reader.readAsArrayBuffer(blob);
5569
+ });
5570
+ }
5571
+ throw new Error("[RequestQueue] Blob binary extraction is not supported in this environment");
5572
+ }
5324
5573
  const SENSITIVE_HEADER_KEYS = ["authorization", "cookie", "set-cookie", "x-csrf-token"];
5325
5574
  class RequestQueue {
5326
5575
  // ── State ──────────────────────────────────────────────────────────────────
@@ -5347,11 +5596,187 @@ class RequestQueue {
5347
5596
  * Sensitive credentials must never be stored in plaintext in browser storage, and are
5348
5597
  * instead regenerated dynamically at execution time.
5349
5598
  */
5350
- static sanitizeOptions(options) {
5599
+ /**
5600
+ * Adapts binary, multipart, and specialized payload types (FormData, Blob, File,
5601
+ * ArrayBuffer, TypedArrays, URLSearchParams) into JSON-serializable structures
5602
+ * to prevent silent payload loss (BUG-014) when persisting to offline storage.
5603
+ */
5604
+ static async serializeBody(body) {
5605
+ if (body === void 0 || body === null) {
5606
+ return body;
5607
+ }
5608
+ const isFormData = typeof FormData !== "undefined" && (body instanceof FormData || Object.prototype.toString.call(body) === "[object FormData]");
5609
+ if (isFormData) {
5610
+ const entries = [];
5611
+ if (typeof body.entries === "function") {
5612
+ for (const [key, val] of body.entries()) {
5613
+ entries.push([key, await RequestQueue.serializeFieldValue(val)]);
5614
+ }
5615
+ } else if (typeof body.forEach === "function") {
5616
+ const raw = [];
5617
+ body.forEach((val, key) => {
5618
+ raw.push([key, val]);
5619
+ });
5620
+ for (const [key, val] of raw) {
5621
+ entries.push([key, await RequestQueue.serializeFieldValue(val)]);
5622
+ }
5623
+ }
5624
+ return {
5625
+ __katlux_type: "FormData",
5626
+ entries
5627
+ };
5628
+ }
5629
+ const isFile = typeof File !== "undefined" && (body instanceof File || Object.prototype.toString.call(body) === "[object File]");
5630
+ if (isFile) {
5631
+ const bytes = await readBlobAsUint8Array(body);
5632
+ return {
5633
+ __katlux_type: "File",
5634
+ name: body.name,
5635
+ type: body.type || "application/octet-stream",
5636
+ lastModified: body.lastModified,
5637
+ data: uint8ArrayToBase64(bytes)
5638
+ };
5639
+ }
5640
+ const isBlob = typeof Blob !== "undefined" && (body instanceof Blob || Object.prototype.toString.call(body) === "[object Blob]");
5641
+ if (isBlob) {
5642
+ const bytes = await readBlobAsUint8Array(body);
5643
+ return {
5644
+ __katlux_type: "Blob",
5645
+ type: body.type || "application/octet-stream",
5646
+ data: uint8ArrayToBase64(bytes)
5647
+ };
5648
+ }
5649
+ const isArrayBuffer = typeof ArrayBuffer !== "undefined" && (body instanceof ArrayBuffer || Object.prototype.toString.call(body) === "[object ArrayBuffer]");
5650
+ if (isArrayBuffer) {
5651
+ const bytes = new Uint8Array(body);
5652
+ return {
5653
+ __katlux_type: "ArrayBuffer",
5654
+ data: uint8ArrayToBase64(bytes)
5655
+ };
5656
+ }
5657
+ if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(body)) {
5658
+ const view = body;
5659
+ const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
5660
+ return {
5661
+ __katlux_type: "Uint8Array",
5662
+ data: uint8ArrayToBase64(bytes)
5663
+ };
5664
+ }
5665
+ const isURLSearchParams = typeof URLSearchParams !== "undefined" && (body instanceof URLSearchParams || Object.prototype.toString.call(body) === "[object URLSearchParams]");
5666
+ if (isURLSearchParams) {
5667
+ return {
5668
+ __katlux_type: "URLSearchParams",
5669
+ data: body.toString()
5670
+ };
5671
+ }
5672
+ return body;
5673
+ }
5674
+ static async serializeFieldValue(val) {
5675
+ if (typeof File !== "undefined" && (val instanceof File || Object.prototype.toString.call(val) === "[object File]")) {
5676
+ const bytes = await readBlobAsUint8Array(val);
5677
+ return {
5678
+ __katlux_type: "File",
5679
+ name: val.name,
5680
+ type: val.type || "application/octet-stream",
5681
+ lastModified: val.lastModified,
5682
+ data: uint8ArrayToBase64(bytes)
5683
+ };
5684
+ }
5685
+ if (typeof Blob !== "undefined" && (val instanceof Blob || Object.prototype.toString.call(val) === "[object Blob]")) {
5686
+ const bytes = await readBlobAsUint8Array(val);
5687
+ return {
5688
+ __katlux_type: "Blob",
5689
+ type: val.type || "application/octet-stream",
5690
+ data: uint8ArrayToBase64(bytes)
5691
+ };
5692
+ }
5693
+ return typeof val === "string" ? val : String(val);
5694
+ }
5695
+ /**
5696
+ * Reconstitutes serialized offline request bodies back into their live runtime instances
5697
+ * (FormData, Blob, File, ArrayBuffer, Uint8Array, URLSearchParams) before network transmission.
5698
+ */
5699
+ static reconstituteBody(body) {
5700
+ if (!body || typeof body !== "object") {
5701
+ return body;
5702
+ }
5703
+ if (body.__katlux_type === "FormData" && Array.isArray(body.entries)) {
5704
+ if (typeof FormData === "undefined") return body;
5705
+ const fd = new FormData();
5706
+ for (const [key, val] of body.entries) {
5707
+ if (val && typeof val === "object" && val.__katlux_type === "File") {
5708
+ const u8 = base64ToUint8Array(val.data);
5709
+ if (typeof File !== "undefined") {
5710
+ const file = new File([u8], val.name, {
5711
+ type: val.type || "application/octet-stream",
5712
+ lastModified: val.lastModified
5713
+ });
5714
+ fd.append(key, file, val.name);
5715
+ } else if (typeof Blob !== "undefined") {
5716
+ const blob = new Blob([u8], { type: val.type || "application/octet-stream" });
5717
+ fd.append(key, blob, val.name);
5718
+ }
5719
+ } else if (val && typeof val === "object" && val.__katlux_type === "Blob") {
5720
+ if (typeof Blob !== "undefined") {
5721
+ const u8 = base64ToUint8Array(val.data);
5722
+ const blob = new Blob([u8], { type: val.type || "application/octet-stream" });
5723
+ fd.append(key, blob);
5724
+ }
5725
+ } else {
5726
+ fd.append(key, val);
5727
+ }
5728
+ }
5729
+ return fd;
5730
+ }
5731
+ if (body.__katlux_type === "File") {
5732
+ const u8 = base64ToUint8Array(body.data);
5733
+ if (typeof File !== "undefined") {
5734
+ return new File([u8], body.name, {
5735
+ type: body.type || "application/octet-stream",
5736
+ lastModified: body.lastModified
5737
+ });
5738
+ }
5739
+ if (typeof Blob !== "undefined") {
5740
+ return new Blob([u8], { type: body.type || "application/octet-stream" });
5741
+ }
5742
+ return u8;
5743
+ }
5744
+ if (body.__katlux_type === "Blob") {
5745
+ const u8 = base64ToUint8Array(body.data);
5746
+ if (typeof Blob !== "undefined") {
5747
+ return new Blob([u8], { type: body.type || "application/octet-stream" });
5748
+ }
5749
+ return u8;
5750
+ }
5751
+ if (body.__katlux_type === "ArrayBuffer") {
5752
+ const u8 = base64ToUint8Array(body.data);
5753
+ return u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength);
5754
+ }
5755
+ if (body.__katlux_type === "Uint8Array") {
5756
+ return base64ToUint8Array(body.data);
5757
+ }
5758
+ if (body.__katlux_type === "URLSearchParams") {
5759
+ if (typeof URLSearchParams !== "undefined") {
5760
+ return new URLSearchParams(body.data);
5761
+ }
5762
+ return body.data;
5763
+ }
5764
+ return body;
5765
+ }
5766
+ /**
5767
+ * Strips sensitive headers (e.g., authorization, cookie, x-csrf-token) before persisting
5768
+ * request options to persistent storage (IndexedDB / LocalStorage).
5769
+ * Sensitive credentials must never be stored in plaintext in browser storage, and are
5770
+ * instead regenerated dynamically at execution time.
5771
+ */
5772
+ static async sanitizeOptions(options) {
5351
5773
  if (!options) return {};
5352
5774
  const sanitized = {
5353
5775
  method: options.method
5354
5776
  };
5777
+ if (options.credentials) {
5778
+ sanitized.credentials = options.credentials;
5779
+ }
5355
5780
  if (options.headers) {
5356
5781
  const headersObj = {};
5357
5782
  const sensitiveSet = new Set(SENSITIVE_HEADER_KEYS.map((k) => k.toLowerCase()));
@@ -5385,7 +5810,8 @@ class RequestQueue {
5385
5810
  }
5386
5811
  if (options.body !== void 0) {
5387
5812
  try {
5388
- const serialized = JSON.stringify(options.body);
5813
+ const serializedBody = await this.serializeBody(options.body);
5814
+ const serialized = JSON.stringify(serializedBody);
5389
5815
  if (serialized && serialized.length > this.MAX_PAYLOAD_SIZE_BYTES) {
5390
5816
  throw new Error(
5391
5817
  `[RequestQueue] Payload size (${(serialized.length / (1024 * 1024)).toFixed(2)} MB) exceeds maximum allowed size (${(this.MAX_PAYLOAD_SIZE_BYTES / (1024 * 1024)).toFixed(2)} MB)`
@@ -5425,6 +5851,7 @@ class RequestQueue {
5425
5851
  static _onDeadLetter = null;
5426
5852
  static _onFlushComplete = null;
5427
5853
  static _onNetworkError = null;
5854
+ static _onError = null;
5428
5855
  static _headerProvider = null;
5429
5856
  static setHeaderProvider(provider) {
5430
5857
  this._headerProvider = provider;
@@ -5474,6 +5901,12 @@ class RequestQueue {
5474
5901
  static onNetworkError(cb) {
5475
5902
  this._onNetworkError = cb;
5476
5903
  }
5904
+ static onError(cb) {
5905
+ this._onError = cb;
5906
+ }
5907
+ static onQueueFatalError(cb) {
5908
+ this._onError = cb;
5909
+ }
5477
5910
  // ── Enqueue ───────────────────────────────────────────────────────────────
5478
5911
  /**
5479
5912
  * Add an operation to the pending queue and persist it.
@@ -5482,7 +5915,7 @@ class RequestQueue {
5482
5915
  */
5483
5916
  static async enqueue(operation) {
5484
5917
  await this.init();
5485
- const sanitizedOptions = this.sanitizeOptions(operation.options);
5918
+ const sanitizedOptions = await this.sanitizeOptions(operation.options);
5486
5919
  if (this.queue.length >= this.MAX_QUEUE_SIZE) {
5487
5920
  const evicted = this.queue[0];
5488
5921
  await this.moveToDeadLetter(evicted, new Error("Queue capacity exceeded"));
@@ -5545,11 +5978,24 @@ class RequestQueue {
5545
5978
  this.notify();
5546
5979
  this._onNetworkError?.(item);
5547
5980
  } else {
5548
- await this.moveToDeadLetter(item, error, httpStatus);
5981
+ try {
5982
+ await this.moveToDeadLetter(item, error, httpStatus);
5983
+ } catch (dlErr) {
5984
+ await this.persistQueue().catch(() => {
5985
+ });
5986
+ this.notify();
5987
+ const fatalError = dlErr instanceof Error ? dlErr : new Error(String(dlErr));
5988
+ console.error("[RequestQueue] Fatal capacity error moving to dead-letter:", fatalError);
5989
+ this._onError?.(fatalError);
5990
+ }
5549
5991
  }
5550
5992
  break;
5551
5993
  }
5552
5994
  }
5995
+ } catch (topErr) {
5996
+ const fatalError = topErr instanceof Error ? topErr : new Error(String(topErr));
5997
+ console.error("[RequestQueue] flushAll fatal error:", fatalError);
5998
+ this._onError?.(fatalError);
5553
5999
  } finally {
5554
6000
  this.isFlushing = false;
5555
6001
  this.notify();
@@ -5593,7 +6039,16 @@ class RequestQueue {
5593
6039
  this.notify();
5594
6040
  this._onNetworkError?.(item);
5595
6041
  } else {
5596
- await this.moveToDeadLetter(item, error, httpStatus);
6042
+ try {
6043
+ await this.moveToDeadLetter(item, error, httpStatus);
6044
+ } catch (dlErr) {
6045
+ await this.persistQueue().catch(() => {
6046
+ });
6047
+ this.notify();
6048
+ const fatalError = dlErr instanceof Error ? dlErr : new Error(String(dlErr));
6049
+ console.error("[RequestQueue] Fatal capacity error moving to dead-letter:", fatalError);
6050
+ this._onError?.(fatalError);
6051
+ }
5597
6052
  }
5598
6053
  }
5599
6054
  }
@@ -5667,24 +6122,30 @@ class RequestQueue {
5667
6122
  console.error("[RequestQueue] Header provider failed:", err);
5668
6123
  }
5669
6124
  }
5670
- if (typeof document !== "undefined" && document.cookie && !headers["cookie"] && !headers["Cookie"]) {
5671
- headers["cookie"] = document.cookie;
5672
- }
5673
6125
  return headers;
5674
6126
  }
5675
6127
  static async executeRequest(item) {
5676
6128
  const { url, options } = item;
5677
6129
  const headers = await this.regenerateHeaders(options.headers);
6130
+ const body = this.reconstituteBody(options.body);
6131
+ if (typeof FormData !== "undefined" && (body instanceof FormData || Object.prototype.toString.call(body) === "[object FormData]")) {
6132
+ delete headers["content-type"];
6133
+ delete headers["Content-Type"];
6134
+ }
5678
6135
  const fetchOptions = {
5679
6136
  method: item.method,
5680
- body: options.body,
6137
+ body,
5681
6138
  headers,
5682
- query: options.query
6139
+ query: options.query,
6140
+ credentials: options.credentials || "include"
5683
6141
  };
5684
6142
  const fetchFn = globalThis.$fetch || ofetch.$fetch;
5685
6143
  await fetchFn(url, fetchOptions);
5686
6144
  }
5687
6145
  static async moveToDeadLetter(item, error, httpStatus) {
6146
+ if (this.deadLetterQueue.length >= this.MAX_DEAD_LETTER_SIZE) {
6147
+ 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.`);
6148
+ }
5688
6149
  const deadItem = {
5689
6150
  ...item,
5690
6151
  failedAt: Date.now(),
@@ -5692,11 +6153,6 @@ class RequestQueue {
5692
6153
  httpStatus
5693
6154
  };
5694
6155
  this.queue = this.queue.filter((i) => i.id !== item.id);
5695
- if (this.deadLetterQueue.length >= this.MAX_DEAD_LETTER_SIZE) {
5696
- const evicted = this.deadLetterQueue[0];
5697
- console.warn(`[RequestQueue] Dead-letter queue reached capacity (${this.MAX_DEAD_LETTER_SIZE}). Evicting oldest item: ${evicted?.id}`);
5698
- this.deadLetterQueue = this.deadLetterQueue.slice(1);
5699
- }
5700
6156
  this.deadLetterQueue = [...this.deadLetterQueue, deadItem];
5701
6157
  await this.persistQueue();
5702
6158
  await this.persistDeadLetter();
@@ -5718,6 +6174,7 @@ class RequestQueue {
5718
6174
  this._onDeadLetter = null;
5719
6175
  this._onFlushComplete = null;
5720
6176
  this._onNetworkError = null;
6177
+ this._onError = null;
5721
6178
  this._headerProvider = null;
5722
6179
  this.MAX_PAYLOAD_SIZE_BYTES = 5 * 1024 * 1024;
5723
6180
  this.MAX_QUEUE_SIZE = 500;
@@ -6147,6 +6604,8 @@ class RequestProvider {
6147
6604
  url,
6148
6605
  method,
6149
6606
  isServer,
6607
+ aad: encOptions.aad,
6608
+ bindRequestContextAad: encOptions.bindRequestContextAad,
6150
6609
  key: encOptions.key,
6151
6610
  valueEncryption: encOptions.valueEncryption,
6152
6611
  fields: encOptions.fields,
@@ -8072,13 +8531,41 @@ class CCookieCache extends ACacheProvider {
8072
8531
  return this.instance;
8073
8532
  }
8074
8533
  type = "Cookie";
8534
+ sameSite = "lax";
8535
+ secure = void 0;
8536
+ httpOnly = true;
8537
+ path = "/";
8075
8538
  // Exposed constructor for testing & instantiation
8076
- constructor() {
8539
+ constructor(options) {
8077
8540
  super();
8541
+ if (options) {
8542
+ this.configure(options);
8543
+ }
8544
+ }
8545
+ configure(options) {
8546
+ if (options.sameSite !== void 0) this.sameSite = options.sameSite;
8547
+ if (options.secure !== void 0) this.secure = options.secure;
8548
+ if (options.httpOnly !== void 0) this.httpOnly = options.httpOnly;
8549
+ if (options.path !== void 0) this.path = options.path;
8078
8550
  }
8079
8551
  getCookieKey(key) {
8080
8552
  return "cache:" + encodeURIComponent(key);
8081
8553
  }
8554
+ /**
8555
+ * Resolves the `Secure` flag: an explicit option wins, otherwise follow the
8556
+ * actual protocol so cookies are not silently dropped by browsers over plain HTTP.
8557
+ */
8558
+ resolveSecure(getRequestProtocol, event) {
8559
+ if (this.secure !== void 0) return this.secure;
8560
+ if (event && getRequestProtocol) {
8561
+ try {
8562
+ return getRequestProtocol(event) === "https";
8563
+ } catch {
8564
+ return false;
8565
+ }
8566
+ }
8567
+ return typeof location !== "undefined" && location.protocol === "https:";
8568
+ }
8082
8569
  parseKeyFromCookieName(cookieName) {
8083
8570
  const prefix = "cache:";
8084
8571
  const decoded = decodeURIComponent(cookieName);
@@ -8184,20 +8671,23 @@ class CCookieCache extends ACacheProvider {
8184
8671
  return;
8185
8672
  }
8186
8673
  const maxAge = Math.floor(lifetime / 1e3);
8674
+ const sameSiteFormatted = this.sameSite.charAt(0).toUpperCase() + this.sameSite.slice(1).toLowerCase();
8187
8675
  if (this.isClient(context)) {
8188
8676
  if (typeof document !== "undefined") {
8189
- document.cookie = `${cookieKey}=${cookieValue}; Max-Age=${maxAge}; Path=/; SameSite=Lax`;
8677
+ const secureFlag = this.resolveSecure() ? "; Secure" : "";
8678
+ document.cookie = `${cookieKey}=${cookieValue}; Max-Age=${maxAge}; Path=${this.path}; SameSite=${sameSiteFormatted}${secureFlag}`;
8190
8679
  }
8191
8680
  } else if (context) {
8192
8681
  const event = context?.event ?? context?.ssrContext?.event ?? (context?.node ? context : null);
8193
8682
  if (event) {
8194
8683
  try {
8195
- const { setCookie } = await getH3();
8684
+ const { setCookie, getRequestProtocol } = await getH3();
8196
8685
  setCookie(event, cookieKey, serialized, {
8197
8686
  maxAge,
8198
- path: "/",
8199
- sameSite: "lax",
8200
- httpOnly: true
8687
+ path: this.path,
8688
+ sameSite: this.sameSite,
8689
+ httpOnly: this.httpOnly,
8690
+ secure: this.resolveSecure(getRequestProtocol, event)
8201
8691
  });
8202
8692
  } catch {
8203
8693
  }
@@ -8206,16 +8696,18 @@ class CCookieCache extends ACacheProvider {
8206
8696
  }
8207
8697
  async remove(key, context) {
8208
8698
  const cookieKey = this.getCookieKey(key);
8699
+ const sameSiteFormatted = this.sameSite.charAt(0).toUpperCase() + this.sameSite.slice(1).toLowerCase();
8209
8700
  if (this.isClient(context)) {
8210
8701
  if (typeof document !== "undefined") {
8211
- document.cookie = `${cookieKey}=; Max-Age=0; Path=/; SameSite=Lax`;
8702
+ const secureFlag = this.resolveSecure() ? "; Secure" : "";
8703
+ document.cookie = `${cookieKey}=; Max-Age=0; Path=${this.path}; SameSite=${sameSiteFormatted}${secureFlag}`;
8212
8704
  }
8213
8705
  } else if (context) {
8214
8706
  const event = context?.event ?? context?.ssrContext?.event ?? (context?.node ? context : null);
8215
8707
  if (event) {
8216
8708
  try {
8217
- const { deleteCookie } = await getH3();
8218
- deleteCookie(event, cookieKey, { path: "/", sameSite: "lax", httpOnly: true });
8709
+ const { deleteCookie, getRequestProtocol } = await getH3();
8710
+ deleteCookie(event, cookieKey, { path: this.path, sameSite: this.sameSite, httpOnly: this.httpOnly, secure: this.resolveSecure(getRequestProtocol, event) });
8219
8711
  } catch {
8220
8712
  }
8221
8713
  }
@@ -8469,7 +8961,11 @@ class CServerSessionCache extends ACacheProvider {
8469
8961
  CServerSessionCache._opCounter = 0;
8470
8962
  CServerSessionCache.purgeExpiredServerSessions(50);
8471
8963
  } else if (CServerSessionCache.storage.size >= CServerSessionCache.MAX_SERVER_SESSIONS) {
8472
- CServerSessionCache.purgeExpiredServerSessions();
8964
+ CServerSessionCache.purgeExpiredServerSessions(50);
8965
+ if (CServerSessionCache.storage.size >= CServerSessionCache.MAX_SERVER_SESSIONS) {
8966
+ const oldestKey = CServerSessionCache.storage.keys().next().value;
8967
+ if (oldestKey !== void 0) CServerSessionCache.storage.delete(oldestKey);
8968
+ }
8473
8969
  }
8474
8970
  let sessionData = CServerSessionCache.storage.get(sessionId);
8475
8971
  if (sessionData) {
@@ -9521,6 +10017,7 @@ exports.getSSRData = getSSRData;
9521
10017
  exports.getSSRPayload = getSSRPayload;
9522
10018
  exports.getSafeKeyIdentifier = getSafeKeyIdentifier;
9523
10019
  exports.getSubtleCrypto = getSubtleCrypto;
10020
+ exports.isAuthOrDecryptionError = isAuthOrDecryptionError;
9524
10021
  exports.isDataEncrypted = isDataEncrypted;
9525
10022
  exports.isEncrypted = isEncrypted;
9526
10023
  exports.normalizeIndexTerm = normalizeIndexTerm;