@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.mjs CHANGED
@@ -259,6 +259,9 @@ class ADataProvider {
259
259
  this.notify();
260
260
  }
261
261
  }
262
+ getSelectedRows() {
263
+ return this._selectAll ? this.pageData : this._selectedRows;
264
+ }
262
265
  _currentPage = 1;
263
266
  _pageSize = 10;
264
267
  _filter = null;
@@ -339,6 +342,10 @@ class ADataProvider {
339
342
  const sortDebounceTime = typeof options?.sortDebounce === "number" ? options.sortDebounce : 200;
340
343
  this._debouncedFilterLoad = useDebounce(() => {
341
344
  this._currentPage = 1;
345
+ this._selectAll = false;
346
+ this._selectedRows = [];
347
+ this._pendingChangedKeys.add("selectAll");
348
+ this._pendingChangedKeys.add("selectedRows");
342
349
  this.loadPageData();
343
350
  }, filterDebounceTime);
344
351
  this._debouncedSortLoad = useDebounce(() => {
@@ -533,8 +540,12 @@ class ADataProvider {
533
540
  this._filter = filter;
534
541
  this.onFilterUpdated();
535
542
  this._currentPage = 1;
543
+ this._selectAll = false;
544
+ this._selectedRows = [];
536
545
  this._pendingChangedKeys.add("filter");
537
546
  this._pendingChangedKeys.add("currentPage");
547
+ this._pendingChangedKeys.add("selectAll");
548
+ this._pendingChangedKeys.add("selectedRows");
538
549
  if (immediate) {
539
550
  this._debouncedFilterLoad?.cancel?.();
540
551
  this.loadPageData();
@@ -688,6 +699,14 @@ function getKeyIdentifier(keyProvider, defaultKey) {
688
699
  const target = keyProvider ?? defaultKey;
689
700
  return getSafeKeyIdentifier(target);
690
701
  }
702
+ function isAuthOrDecryptionError(err) {
703
+ if (!err) return false;
704
+ if (err.name === "OperationError") return true;
705
+ if (err.code === "ERR_CRYPTO_OPERATION_FAILED" || err.code === "ERR_OSSL_EVP_BAD_DECRYPT") return true;
706
+ if (err.cause && isAuthOrDecryptionError(err.cause)) return true;
707
+ const msg = String(err.message || "").toLowerCase();
708
+ 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");
709
+ }
691
710
 
692
711
  class AEncryptionProvider {
693
712
  defaultKey;
@@ -766,6 +785,57 @@ class AEncryptionProvider {
766
785
  async [Symbol.asyncDispose]() {
767
786
  this.dispose();
768
787
  }
788
+ /**
789
+ * Resolves effective Authenticated Additional Data (AAD) for the operation:
790
+ * 1. If options.bindRequestContextAad is explicitly false, returns options.aad directly without context binding.
791
+ * 2. When encrypting (isDecrypt=false): binds request context `req:${method}:${url}` only if options.bindRequestContextAad === true.
792
+ * 3. When decrypting (isDecrypt=true): derives request context `req:${method}:${url}` if url or method is provided.
793
+ * 4. If explicit options.aad is provided: combines with request context if bound, or returns options.aad directly.
794
+ * 5. Otherwise returns undefined.
795
+ */
796
+ _resolveEffectiveAad(options, isDecrypt = false) {
797
+ if (!options) return void 0;
798
+ if (options.bindRequestContextAad === false) return options.aad;
799
+ const hasReqContext = Boolean(options.url || options.method);
800
+ if (options.aad) {
801
+ if (options.bindRequestContextAad === true && hasReqContext) {
802
+ const m = (options.method || "POST").toUpperCase();
803
+ const u = options.url || "";
804
+ const baseAad = typeof options.aad === "string" ? options.aad : options.aad instanceof Uint8Array || options.aad instanceof ArrayBuffer ? textDecoder.decode(options.aad) : String(options.aad);
805
+ return `${baseAad}|req:${m}:${u}`;
806
+ }
807
+ return options.aad;
808
+ }
809
+ const shouldBindReq = isDecrypt ? hasReqContext : options.bindRequestContextAad === true && hasReqContext;
810
+ if (shouldBindReq) {
811
+ const m = (options.method || "POST").toUpperCase();
812
+ const u = options.url || "";
813
+ return `req:${m}:${u}`;
814
+ }
815
+ return void 0;
816
+ }
817
+ /**
818
+ * Helper to deterministically bind record ID and field name into the AAD
819
+ * to prevent ciphertext swapping between fields or records.
820
+ */
821
+ _bindFieldAad(data, field, options) {
822
+ let baseAad = "";
823
+ if (options?.aad) {
824
+ if (typeof options.aad === "string") baseAad = options.aad;
825
+ else if (options.aad instanceof Uint8Array || options.aad instanceof ArrayBuffer) {
826
+ baseAad = textDecoder.decode(options.aad);
827
+ } else {
828
+ baseAad = String(options.aad);
829
+ }
830
+ }
831
+ const recordId = data && typeof data === "object" && (data.id !== void 0 || data._id !== void 0) ? String(data.id ?? data._id) : "";
832
+ const recordPart = recordId ? `|record:${recordId}` : "";
833
+ const reqPart = options?.bindRequestContextAad === true && (options?.url || options?.method) ? `|req:${(options.method || "POST").toUpperCase()}:${options.url || ""}` : "";
834
+ return {
835
+ ...options,
836
+ aad: `aad:${baseAad}${recordPart}${reqPart}|field:${field}`
837
+ };
838
+ }
769
839
  /**
770
840
  * Top-level polymorphic encryption method.
771
841
  * Automatically performs value-level encryption:
@@ -801,7 +871,10 @@ class AEncryptionProvider {
801
871
  }
802
872
  const result = { ...data };
803
873
  const entries = await Promise.all(
804
- fieldsToEncrypt.map(async (field) => [field, await this.encryptValue(result[field], options)])
874
+ fieldsToEncrypt.map(async (field) => {
875
+ const fieldOptions = this._bindFieldAad(data, field, options);
876
+ return [field, await this.encryptValue(result[field], fieldOptions)];
877
+ })
805
878
  );
806
879
  for (const [field, encryptedVal] of entries) {
807
880
  safeSetProperty(result, field, encryptedVal);
@@ -820,7 +893,10 @@ class AEncryptionProvider {
820
893
  await this.warmupKey(options);
821
894
  }
822
895
  const entries = await Promise.all(
823
- keysToEncrypt.map(async (key) => [key, await this.encryptValue(result[key], options)])
896
+ keysToEncrypt.map(async (key) => {
897
+ const fieldOptions = this._bindFieldAad(data, key, options);
898
+ return [key, await this.encryptValue(result[key], fieldOptions)];
899
+ })
824
900
  );
825
901
  for (const [key, encryptedVal] of entries) {
826
902
  safeSetProperty(result, key, encryptedVal);
@@ -853,7 +929,22 @@ class AEncryptionProvider {
853
929
  return payload;
854
930
  }
855
931
  const entries = await Promise.all(
856
- keysToDecrypt.map(async (key) => [key, await this.decryptValue(result[key], options)])
932
+ keysToDecrypt.map(async (key) => {
933
+ const boundOptions = this._bindFieldAad(payload, key, options);
934
+ const hasBoundAad = boundOptions.aad !== options?.aad;
935
+ try {
936
+ return [key, await this.decryptValue(result[key], boundOptions)];
937
+ } catch (err) {
938
+ if (hasBoundAad && isAuthOrDecryptionError(err)) {
939
+ try {
940
+ return [key, await this.decryptValue(result[key], options)];
941
+ } catch (fallbackErr) {
942
+ throw fallbackErr;
943
+ }
944
+ }
945
+ throw err;
946
+ }
947
+ })
857
948
  );
858
949
  for (const [key, decryptedVal] of entries) {
859
950
  safeSetProperty(result, key, decryptedVal);
@@ -1225,11 +1316,11 @@ ${lines.join("\n")}
1225
1316
  * Generates a high-entropy symmetric AES-GCM Account Data Encryption Key (ADEK).
1226
1317
  * Designed for multi-user table and field-level encryption.
1227
1318
  */
1228
- static async generateAccountDataKey(length = 256) {
1319
+ static async generateAccountDataKey(length = 256, extractable = false) {
1229
1320
  const subtle = getSubtleCrypto();
1230
1321
  return await subtle.generateKey(
1231
1322
  { name: "AES-GCM", length },
1232
- true,
1323
+ extractable,
1233
1324
  ["encrypt", "decrypt"]
1234
1325
  );
1235
1326
  }
@@ -1260,7 +1351,7 @@ ${lines.join("\n")}
1260
1351
  * Unwraps a Base64-encoded Account Data Encryption Key (ADEK) using the user's private key (RSA-OAEP).
1261
1352
  * Returns the restored AES-GCM CryptoKey ready for use in CWebCryptoEncryptionProvider.
1262
1353
  */
1263
- static async unwrapAccountKeyForUser(wrappedKeyBase64, userPrivateKey, unwrappedKeyAlgorithm = { name: "AES-GCM", length: 256 }) {
1354
+ static async unwrapAccountKeyForUser(wrappedKeyBase64, userPrivateKey, unwrappedKeyAlgorithm = { name: "AES-GCM", length: 256 }, extractable = false) {
1264
1355
  const subtle = getSubtleCrypto();
1265
1356
  if (userPrivateKey.algorithm.name === "RSA-OAEP") {
1266
1357
  const wrappedBytes = CKeyManager.fromBase64(wrappedKeyBase64);
@@ -1279,7 +1370,7 @@ ${lines.join("\n")}
1279
1370
  "raw",
1280
1371
  unwrappedRawKey,
1281
1372
  unwrappedKeyAlgorithm,
1282
- true,
1373
+ extractable,
1283
1374
  ["encrypt", "decrypt"]
1284
1375
  );
1285
1376
  } finally {
@@ -1452,12 +1543,13 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1452
1543
  return options._warmedKey;
1453
1544
  }
1454
1545
  if (saltOverride) {
1546
+ const rawKey = await this.resolveRawKey(keyProvider);
1455
1547
  const saltKey = typeof saltOverride === "string" ? saltOverride : CKeyManager.toBase64(saltOverride);
1456
- const keyId = getKeyIdentifier(keyProvider, this.defaultKey);
1548
+ const keyId = getSafeKeyIdentifier(rawKey);
1457
1549
  const compoundKey = `${keyId}:${kdfOverride || ""}:${iterationsOverride || ""}:${options?.kdfHash || ""}:${saltKey}`;
1458
1550
  let cached = this._decryptSaltCache.get(compoundKey);
1459
1551
  if (!cached) {
1460
- cached = this._resolveCryptoKeyInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1552
+ cached = this._resolveCryptoKeyInternal(rawKey, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1461
1553
  this._decryptSaltCache.delete(compoundKey);
1462
1554
  throw err;
1463
1555
  });
@@ -1514,9 +1606,9 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1514
1606
  const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
1515
1607
  const matchesKdf = this._cachedKdf !== void 0 && kdf === this._cachedKdf.toLowerCase();
1516
1608
  const matchesSalt = !saltOverride || this._cachedSalt !== void 0 && saltOverride === this._cachedSalt;
1517
- const currentKeyId = getKeyIdentifier(keyProvider, this.defaultKey);
1609
+ const currentKeyId = getSafeKeyIdentifier(rawKey);
1518
1610
  if (this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
1519
- if (!this._cachedKeyId || this._cachedKeyId === currentKeyId) {
1611
+ if (this._cachedKeyId === currentKeyId) {
1520
1612
  return { cryptoKey: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
1521
1613
  }
1522
1614
  }
@@ -1637,7 +1729,7 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1637
1729
  name: "AES-GCM",
1638
1730
  iv
1639
1731
  };
1640
- const aad = options?.aad;
1732
+ const aad = this._resolveEffectiveAad(options, false);
1641
1733
  let hasAad = false;
1642
1734
  if (aad) {
1643
1735
  const aadBytes = typeof aad === "string" ? textEncoder$1.encode(aad) : aad instanceof Uint8Array ? aad : new Uint8Array(aad);
@@ -1699,22 +1791,45 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1699
1791
  name: "AES-GCM",
1700
1792
  iv
1701
1793
  };
1702
- const aad = options?.aad;
1794
+ const aad = this._resolveEffectiveAad(options, true);
1795
+ let hasAad = false;
1703
1796
  if (payload.aad || aad) {
1704
1797
  if (aad) {
1705
1798
  const aadBytes = typeof aad === "string" ? textEncoder$1.encode(aad) : aad instanceof Uint8Array ? aad : new Uint8Array(aad);
1706
1799
  if (aadBytes.byteLength > 0) {
1707
1800
  decryptParams.additionalData = aadBytes;
1801
+ hasAad = true;
1708
1802
  }
1709
1803
  } else if (payload.aad) {
1710
1804
  throw new Error("[CWebCryptoEncryptionProvider] Payload requires Authenticated Additional Data (AAD) for decryption, but none was provided.");
1711
1805
  }
1712
1806
  }
1713
- const decryptedBuffer = await subtle.decrypt(
1714
- decryptParams,
1715
- cryptoKey,
1716
- ciphertextBytes
1717
- );
1807
+ let decryptedBuffer;
1808
+ try {
1809
+ decryptedBuffer = await subtle.decrypt(
1810
+ decryptParams,
1811
+ cryptoKey,
1812
+ ciphertextBytes
1813
+ );
1814
+ } catch (firstErr) {
1815
+ if (!payload.aad && hasAad) {
1816
+ try {
1817
+ const fallbackParams = {
1818
+ name: "AES-GCM",
1819
+ iv
1820
+ };
1821
+ decryptedBuffer = await subtle.decrypt(
1822
+ fallbackParams,
1823
+ cryptoKey,
1824
+ ciphertextBytes
1825
+ );
1826
+ } catch {
1827
+ throw firstErr;
1828
+ }
1829
+ } else {
1830
+ throw firstErr;
1831
+ }
1832
+ }
1718
1833
  try {
1719
1834
  const jsonString = textDecoder.decode(decryptedBuffer);
1720
1835
  return JSON.parse(jsonString);
@@ -1723,7 +1838,12 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1723
1838
  }
1724
1839
  } catch (err) {
1725
1840
  if (err instanceof SyntaxError) throw err;
1726
- throw new Error(`[CWebCryptoEncryptionProvider] Decryption failed: ${err?.message || "Authentication tag mismatch or corrupted ciphertext"}`);
1841
+ const decryptError = new Error(`[CWebCryptoEncryptionProvider] Decryption failed: ${err?.message || "Authentication tag mismatch or corrupted ciphertext"}`);
1842
+ if (err?.name) {
1843
+ decryptError.name = err.name;
1844
+ }
1845
+ decryptError.cause = err;
1846
+ throw decryptError;
1727
1847
  }
1728
1848
  }
1729
1849
  }
@@ -1736,6 +1856,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1736
1856
  _cachedKdf;
1737
1857
  _cachedIter;
1738
1858
  _cachedHash;
1859
+ _cachedKeyId;
1739
1860
  _configuredKid;
1740
1861
  _kdfOptions;
1741
1862
  _decryptSaltCache = /* @__PURE__ */ new Map();
@@ -1746,9 +1867,9 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1746
1867
  this._configuredKid = options.kid || options.keyId;
1747
1868
  }
1748
1869
  this._defaultKdf = options.kdf || "pbkdf2";
1749
- if (options.kdf && options.kdf !== "none") {
1870
+ if (this._defaultKdf !== "none") {
1750
1871
  this._kdfOptions = {
1751
- kdf: options.kdf,
1872
+ kdf: this._defaultKdf,
1752
1873
  iterations: options.kdfIterations,
1753
1874
  hash: options.kdfHash,
1754
1875
  salt: options.kdfSalt,
@@ -1765,6 +1886,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1765
1886
  this._cachedKdf = void 0;
1766
1887
  this._cachedIter = void 0;
1767
1888
  this._cachedHash = void 0;
1889
+ this._cachedKeyId = void 0;
1768
1890
  this._decryptSaltCache.clear();
1769
1891
  }
1770
1892
  clearKeys() {
@@ -1775,6 +1897,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1775
1897
  this._cachedKdf = void 0;
1776
1898
  this._cachedIter = void 0;
1777
1899
  this._cachedHash = void 0;
1900
+ this._cachedKeyId = void 0;
1778
1901
  this._decryptSaltCache.clear();
1779
1902
  }
1780
1903
  async warmupKey(options) {
@@ -1795,12 +1918,14 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1795
1918
  */
1796
1919
  async resolveCBCKeys(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
1797
1920
  if (saltOverride) {
1921
+ const rawKey = await this.resolveRawKey(keyProvider);
1798
1922
  const saltKey = typeof saltOverride === "string" ? saltOverride : CKeyManager.toBase64(saltOverride);
1799
- const keyId = getKeyIdentifier(keyProvider, this.defaultKey);
1800
- const compoundKey = `${keyId}:${kdfOverride || ""}:${iterationsOverride || ""}:${options?.kdfHash || ""}:${saltKey}`;
1923
+ const keyId = getSafeKeyIdentifier(rawKey);
1924
+ const effectiveHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
1925
+ const compoundKey = `${keyId}:${kdfOverride || ""}:${iterationsOverride || ""}:${effectiveHash}:${saltKey}`;
1801
1926
  let cached = this._decryptSaltCache.get(compoundKey);
1802
1927
  if (!cached) {
1803
- cached = this._deriveCBCKeysInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1928
+ cached = this._deriveCBCKeysInternal(rawKey, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1804
1929
  this._decryptSaltCache.delete(compoundKey);
1805
1930
  throw err;
1806
1931
  });
@@ -1820,17 +1945,20 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1820
1945
  return await this._deriveCBCKeysInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride);
1821
1946
  }
1822
1947
  async _deriveCBCKeysInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
1948
+ const rawKey = await this.resolveRawKey(keyProvider);
1949
+ const currentKeyId = getSafeKeyIdentifier(rawKey);
1823
1950
  const subtle = getSubtleCrypto();
1824
- const targetIter = iterationsOverride || options?.kdfIterations;
1825
- const targetHash = options?.kdfHash;
1951
+ const targetIter = iterationsOverride || options?.kdfIterations || this._kdfOptions?.iterations;
1952
+ const targetHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
1826
1953
  const matchesIter = !targetIter || this._cachedIter !== void 0 && targetIter === this._cachedIter;
1827
- const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
1954
+ const matchesHash = this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
1828
1955
  const effectiveKdf = (kdfOverride || options?.kdf || this._defaultKdf || "none").toLowerCase();
1829
1956
  const matchesKdf = this._cachedKdf === "raw" || this._cachedKdf === "hkdf-direct" || this._cachedKdf !== void 0 && effectiveKdf === this._cachedKdf.toLowerCase();
1830
- if (!keyProvider && this._cachedEncKey && this._cachedMacKey && !saltOverride && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
1831
- return { encKey: this._cachedEncKey, macKey: this._cachedMacKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
1957
+ if (this._cachedEncKey && this._cachedMacKey && !saltOverride && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
1958
+ if (this._cachedKeyId === currentKeyId) {
1959
+ return { encKey: this._cachedEncKey, macKey: this._cachedMacKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
1960
+ }
1832
1961
  }
1833
- const rawKey = await this.resolveRawKey(keyProvider);
1834
1962
  if (typeof rawKey !== "string" && rawKey.algorithm) {
1835
1963
  const cryptoKey = rawKey;
1836
1964
  let rawBits;
@@ -1863,6 +1991,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1863
1991
  this._cachedEncKey = encKey2;
1864
1992
  this._cachedMacKey = macKey2;
1865
1993
  this._cachedKdf = "hkdf-direct";
1994
+ this._cachedKeyId = currentKeyId;
1866
1995
  }
1867
1996
  return { encKey: encKey2, macKey: macKey2, kdf: "hkdf-direct" };
1868
1997
  }
@@ -1896,6 +2025,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1896
2025
  this._cachedEncKey = encKey2;
1897
2026
  this._cachedMacKey = macKey2;
1898
2027
  this._cachedKdf = "raw";
2028
+ this._cachedKeyId = currentKeyId;
1899
2029
  }
1900
2030
  return { encKey: encKey2, macKey: macKey2, kdf: "raw" };
1901
2031
  }
@@ -1926,6 +2056,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1926
2056
  this._cachedEncKey = encKey2;
1927
2057
  this._cachedMacKey = macKey2;
1928
2058
  this._cachedKdf = "raw";
2059
+ this._cachedKeyId = currentKeyId;
1929
2060
  }
1930
2061
  return { encKey: encKey2, macKey: macKey2, kdf: "raw" };
1931
2062
  }
@@ -2033,6 +2164,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
2033
2164
  this._cachedKdf = kdfType || "none";
2034
2165
  this._cachedIter = iterNum;
2035
2166
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
2167
+ this._cachedKeyId = currentKeyId;
2036
2168
  }
2037
2169
  return {
2038
2170
  encKey,
@@ -2933,6 +3065,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2933
3065
  _cachedKdf;
2934
3066
  _cachedIter;
2935
3067
  _cachedHash;
3068
+ _cachedKeyId;
2936
3069
  _configuredKid;
2937
3070
  setDefaultKey(key) {
2938
3071
  super.setDefaultKey(key);
@@ -2944,6 +3077,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2944
3077
  this._cachedKdf = void 0;
2945
3078
  this._cachedIter = void 0;
2946
3079
  this._cachedHash = void 0;
3080
+ this._cachedKeyId = void 0;
2947
3081
  }
2948
3082
  clearKeys() {
2949
3083
  super.clearKeys();
@@ -2955,6 +3089,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2955
3089
  this._cachedKdf = void 0;
2956
3090
  this._cachedIter = void 0;
2957
3091
  this._cachedHash = void 0;
3092
+ this._cachedKeyId = void 0;
2958
3093
  }
2959
3094
  async warmupKey(options) {
2960
3095
  const res = await this.deriveKeyAsync(options?.key, void 0, void 0, options);
@@ -2964,6 +3099,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2964
3099
  this._cachedKdf = res.kdf;
2965
3100
  this._cachedIter = res.iter;
2966
3101
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3102
+ this._cachedKeyId = getSafeKeyIdentifier(await this.resolveRawKeyAsync(options?.key));
2967
3103
  }
2968
3104
  }
2969
3105
  /**
@@ -2977,6 +3113,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2977
3113
  this._cachedKdf = res.kdf;
2978
3114
  this._cachedIter = res.iter;
2979
3115
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3116
+ this._cachedKeyId = getSafeKeyIdentifier(this.resolveRawKeySync(options?.key));
2980
3117
  }
2981
3118
  }
2982
3119
  resolveInfoBuffer(infoRaw) {
@@ -3063,12 +3200,14 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3063
3200
  }
3064
3201
  deriveKeySync(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
3065
3202
  const raw = this.resolveRawKeySync(keyProvider);
3203
+ const currentKeyId = getSafeKeyIdentifier(raw);
3066
3204
  if (Buffer.isBuffer(raw)) {
3067
3205
  if (raw.length === 32) {
3068
3206
  if (!keyProvider) {
3069
- if (!this._cachedKey) {
3207
+ if (!this._cachedKey || this._cachedKeyId !== currentKeyId) {
3070
3208
  this._cachedKey = Buffer.from(raw);
3071
3209
  this._cachedKdf = "raw";
3210
+ this._cachedKeyId = currentKeyId;
3072
3211
  }
3073
3212
  return { key: this._cachedKey, kdf: "raw" };
3074
3213
  }
@@ -3086,8 +3225,10 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3086
3225
  const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
3087
3226
  const matchesKdf = this._cachedKdf !== void 0 && kdf === this._cachedKdf.toLowerCase();
3088
3227
  const matchesSalt = !saltOverride || this._cachedSalt !== void 0 && saltOverride === this._cachedSalt;
3089
- if (!keyProvider && this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3090
- return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3228
+ if (this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3229
+ if (this._cachedKeyId === currentKeyId) {
3230
+ return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3231
+ }
3091
3232
  }
3092
3233
  if (kdf === "pbkdf2") {
3093
3234
  const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
@@ -3103,6 +3244,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3103
3244
  this._cachedKdf = "PBKDF2";
3104
3245
  this._cachedIter = iterations;
3105
3246
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3247
+ this._cachedKeyId = currentKeyId;
3106
3248
  }
3107
3249
  return {
3108
3250
  key: key2,
@@ -3128,6 +3270,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3128
3270
  this._cachedSalt = saltBuf.toString("base64");
3129
3271
  this._cachedKdf = "HKDF";
3130
3272
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3273
+ this._cachedKeyId = currentKeyId;
3131
3274
  }
3132
3275
  return {
3133
3276
  key: key2,
@@ -3140,24 +3283,27 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3140
3283
  "[CNodeCryptoEncryptionProvider] WARNING: Decrypting a legacy envelope with no KDF (raw SHA-256 key derivation). This is cryptographically weak. Migrate to pbkdf2 or hkdf."
3141
3284
  );
3142
3285
  }
3143
- if (!keyProvider && this._cachedKey && this._cachedKdf === "none") {
3286
+ if (!keyProvider && this._cachedKey && this._cachedKdf === "none" && this._cachedKeyId === currentKeyId) {
3144
3287
  return { key: this._cachedKey, kdf: "none" };
3145
3288
  }
3146
3289
  const key = crypto$1.createHash("sha256").update(passphrase, "utf8").digest();
3147
3290
  if (!keyProvider) {
3148
3291
  this._cachedKey = key;
3149
3292
  this._cachedKdf = "none";
3293
+ this._cachedKeyId = currentKeyId;
3150
3294
  }
3151
3295
  return { key, kdf: "none" };
3152
3296
  }
3153
3297
  async deriveKeyAsync(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
3154
3298
  const raw = await this.resolveRawKeyAsync(keyProvider);
3299
+ const currentKeyId = getSafeKeyIdentifier(raw);
3155
3300
  if (Buffer.isBuffer(raw)) {
3156
3301
  if (raw.length === 32) {
3157
3302
  if (!keyProvider) {
3158
- if (!this._cachedKey) {
3303
+ if (!this._cachedKey || this._cachedKeyId !== currentKeyId) {
3159
3304
  this._cachedKey = Buffer.from(raw);
3160
3305
  this._cachedKdf = "raw";
3306
+ this._cachedKeyId = currentKeyId;
3161
3307
  }
3162
3308
  return { key: this._cachedKey, kdf: "raw" };
3163
3309
  }
@@ -3175,8 +3321,10 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3175
3321
  const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
3176
3322
  const matchesKdf = this._cachedKdf !== void 0 && kdf === this._cachedKdf.toLowerCase();
3177
3323
  const matchesSalt = !saltOverride || this._cachedSalt !== void 0 && saltOverride === this._cachedSalt;
3178
- if (!keyProvider && this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3179
- return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3324
+ if (this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3325
+ if (this._cachedKeyId === currentKeyId) {
3326
+ return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3327
+ }
3180
3328
  }
3181
3329
  if (kdf === "pbkdf2") {
3182
3330
  const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
@@ -3197,6 +3345,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3197
3345
  this._cachedKdf = "PBKDF2";
3198
3346
  this._cachedIter = iterations;
3199
3347
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3348
+ this._cachedKeyId = currentKeyId;
3200
3349
  }
3201
3350
  return {
3202
3351
  key: key2,
@@ -3227,6 +3376,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3227
3376
  this._cachedSalt = saltBuf.toString("base64");
3228
3377
  this._cachedKdf = "HKDF";
3229
3378
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3379
+ this._cachedKeyId = currentKeyId;
3230
3380
  }
3231
3381
  return {
3232
3382
  key: key2,
@@ -3239,13 +3389,14 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3239
3389
  "[CNodeCryptoEncryptionProvider] WARNING: Decrypting a legacy envelope with no KDF (raw SHA-256 key derivation). This is cryptographically weak. Migrate to pbkdf2 or hkdf."
3240
3390
  );
3241
3391
  }
3242
- if (!keyProvider && this._cachedKey && this._cachedKdf === "none") {
3392
+ if (!keyProvider && this._cachedKey && this._cachedKdf === "none" && this._cachedKeyId === currentKeyId) {
3243
3393
  return { key: this._cachedKey, kdf: "none" };
3244
3394
  }
3245
3395
  const key = crypto$1.createHash("sha256").update(passphrase, "utf8").digest();
3246
3396
  if (!keyProvider) {
3247
3397
  this._cachedKey = key;
3248
3398
  this._cachedKdf = "none";
3399
+ this._cachedKeyId = currentKeyId;
3249
3400
  }
3250
3401
  return { key, kdf: "none" };
3251
3402
  }
@@ -3272,7 +3423,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3272
3423
  const jsonString = JSON.stringify(data);
3273
3424
  const iv = crypto$1.randomBytes(12);
3274
3425
  const cipher = crypto$1.createCipheriv("aes-256-gcm", key, iv);
3275
- const aad = options?.aad;
3426
+ const aad = this._resolveEffectiveAad(options, false);
3276
3427
  let hasAad = false;
3277
3428
  if (aad) {
3278
3429
  const aadBuffer = Buffer.isBuffer(aad) ? aad : Buffer.from(typeof aad === "string" ? aad : new Uint8Array(aad));
@@ -3325,21 +3476,41 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3325
3476
  }
3326
3477
  const decipher = crypto$1.createDecipheriv("aes-256-gcm", key, iv, { authTagLength: 16 });
3327
3478
  decipher.setAuthTag(authTag);
3328
- const aad = options?.aad;
3479
+ const aad = this._resolveEffectiveAad(options, true);
3480
+ let hasAad = false;
3329
3481
  if (payload.aad || aad) {
3330
3482
  if (aad) {
3331
3483
  const aadBuffer = Buffer.isBuffer(aad) ? aad : Buffer.from(typeof aad === "string" ? aad : new Uint8Array(aad));
3332
3484
  if (aadBuffer.length > 0) {
3333
3485
  decipher.setAAD(aadBuffer);
3486
+ hasAad = true;
3334
3487
  }
3335
3488
  } else if (payload.aad) {
3336
3489
  throw new Error("[CNodeCryptoEncryptionProvider] Payload requires Authenticated Additional Data (AAD) for decryption, but none was provided.");
3337
3490
  }
3338
3491
  }
3339
- const decrypted = Buffer.concat([
3340
- decipher.update(ciphertext),
3341
- decipher.final()
3342
- ]);
3492
+ let decrypted;
3493
+ try {
3494
+ decrypted = Buffer.concat([
3495
+ decipher.update(ciphertext),
3496
+ decipher.final()
3497
+ ]);
3498
+ } catch (firstErr) {
3499
+ if (!payload.aad && hasAad) {
3500
+ try {
3501
+ const fallbackDecipher = crypto$1.createDecipheriv("aes-256-gcm", key, iv, { authTagLength: 16 });
3502
+ fallbackDecipher.setAuthTag(authTag);
3503
+ decrypted = Buffer.concat([
3504
+ fallbackDecipher.update(ciphertext),
3505
+ fallbackDecipher.final()
3506
+ ]);
3507
+ } catch {
3508
+ throw firstErr;
3509
+ }
3510
+ } else {
3511
+ throw firstErr;
3512
+ }
3513
+ }
3343
3514
  try {
3344
3515
  const jsonString = decrypted.toString("utf8");
3345
3516
  return JSON.parse(jsonString);
@@ -3392,7 +3563,8 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3392
3563
  if (fieldsToEncrypt.length === 0) return { ...data };
3393
3564
  const result = { ...data };
3394
3565
  for (const field of fieldsToEncrypt) {
3395
- safeSetProperty(result, field, this.encryptValueSync(result[field], options));
3566
+ const fieldOptions = this._bindFieldAad(data, field, options);
3567
+ safeSetProperty(result, field, this.encryptValueSync(result[field], fieldOptions));
3396
3568
  }
3397
3569
  return result;
3398
3570
  }
@@ -3400,7 +3572,8 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3400
3572
  const result = { ...data };
3401
3573
  for (const key of Object.keys(result)) {
3402
3574
  if (result[key] !== void 0 && result[key] !== null && !this.isEncrypted(result[key])) {
3403
- safeSetProperty(result, key, this.encryptValueSync(result[key], options));
3575
+ const fieldOptions = this._bindFieldAad(data, key, options);
3576
+ safeSetProperty(result, key, this.encryptValueSync(result[key], fieldOptions));
3404
3577
  }
3405
3578
  }
3406
3579
  return result;
@@ -3439,7 +3612,21 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3439
3612
  derivedKey = derived.key;
3440
3613
  keyCache.set(salt, derivedKey);
3441
3614
  }
3442
- safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3615
+ const boundOptions = this._bindFieldAad(payload, key, options);
3616
+ const hasBoundAad = boundOptions.aad !== options?.aad;
3617
+ try {
3618
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, boundOptions));
3619
+ } catch (err) {
3620
+ if (hasBoundAad && isAuthOrDecryptionError(err)) {
3621
+ try {
3622
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3623
+ } catch (fallbackErr) {
3624
+ throw fallbackErr;
3625
+ }
3626
+ } else {
3627
+ throw err;
3628
+ }
3629
+ }
3443
3630
  mutated = true;
3444
3631
  }
3445
3632
  }
@@ -3479,7 +3666,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3479
3666
  const jsonString = JSON.stringify(data);
3480
3667
  const iv = crypto$1.randomBytes(12);
3481
3668
  const cipher = crypto$1.createCipheriv("aes-256-gcm", key, iv);
3482
- const aad = options?.aad;
3669
+ const aad = this._resolveEffectiveAad(options, false);
3483
3670
  let hasAad = false;
3484
3671
  if (aad) {
3485
3672
  const aadBuffer = Buffer.isBuffer(aad) ? aad : Buffer.from(typeof aad === "string" ? aad : new Uint8Array(aad));
@@ -3567,7 +3754,21 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3567
3754
  derivedKey = derived.key;
3568
3755
  keyCache.set(salt, derivedKey);
3569
3756
  }
3570
- safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3757
+ const boundOptions = this._bindFieldAad(payload, key, options);
3758
+ const hasBoundAad = boundOptions.aad !== options?.aad;
3759
+ try {
3760
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, boundOptions));
3761
+ } catch (err) {
3762
+ if (hasBoundAad && isAuthOrDecryptionError(err)) {
3763
+ try {
3764
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3765
+ } catch (fallbackErr) {
3766
+ throw fallbackErr;
3767
+ }
3768
+ } else {
3769
+ throw err;
3770
+ }
3771
+ }
3571
3772
  mutated = true;
3572
3773
  }
3573
3774
  }
@@ -4575,6 +4776,12 @@ class CFlatClientDataProvider extends AEncryptedClientProvider {
4575
4776
  }
4576
4777
  });
4577
4778
  }
4779
+ getSelectedRows() {
4780
+ if (this.selectAll) {
4781
+ return this.filteredData && this.filteredData.length > 0 ? this.filteredData : this.allData;
4782
+ }
4783
+ return this.selectedRows;
4784
+ }
4578
4785
  }
4579
4786
 
4580
4787
  class CacheProviderFactory {
@@ -5304,6 +5511,48 @@ function generateId() {
5304
5511
  }
5305
5512
  return Date.now().toString(36) + Math.random().toString(36).slice(2);
5306
5513
  }
5514
+ function uint8ArrayToBase64(bytes) {
5515
+ if (typeof Buffer !== "undefined") {
5516
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
5517
+ }
5518
+ let binary = "";
5519
+ const chunkSize = 8192;
5520
+ for (let i = 0; i < bytes.byteLength; i += chunkSize) {
5521
+ const chunk = bytes.subarray(i, i + chunkSize);
5522
+ binary += String.fromCharCode.apply(null, chunk);
5523
+ }
5524
+ return btoa(binary);
5525
+ }
5526
+ function base64ToUint8Array(base64) {
5527
+ if (typeof Buffer !== "undefined") {
5528
+ const buf = Buffer.from(base64, "base64");
5529
+ return new Uint8Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));
5530
+ }
5531
+ const binary = atob(base64);
5532
+ const bytes = new Uint8Array(binary.length);
5533
+ for (let i = 0; i < binary.length; i++) {
5534
+ bytes[i] = binary.charCodeAt(i);
5535
+ }
5536
+ return bytes;
5537
+ }
5538
+ async function readBlobAsUint8Array(blob) {
5539
+ if (typeof blob.arrayBuffer === "function") {
5540
+ const buffer = await blob.arrayBuffer();
5541
+ return new Uint8Array(buffer);
5542
+ }
5543
+ if (typeof FileReader !== "undefined") {
5544
+ return new Promise((resolve, reject) => {
5545
+ const reader = new FileReader();
5546
+ reader.onload = () => {
5547
+ const buffer = reader.result;
5548
+ resolve(new Uint8Array(buffer));
5549
+ };
5550
+ reader.onerror = () => reject(reader.error);
5551
+ reader.readAsArrayBuffer(blob);
5552
+ });
5553
+ }
5554
+ throw new Error("[RequestQueue] Blob binary extraction is not supported in this environment");
5555
+ }
5307
5556
  const SENSITIVE_HEADER_KEYS = ["authorization", "cookie", "set-cookie", "x-csrf-token"];
5308
5557
  class RequestQueue {
5309
5558
  // ── State ──────────────────────────────────────────────────────────────────
@@ -5330,11 +5579,187 @@ class RequestQueue {
5330
5579
  * Sensitive credentials must never be stored in plaintext in browser storage, and are
5331
5580
  * instead regenerated dynamically at execution time.
5332
5581
  */
5333
- static sanitizeOptions(options) {
5582
+ /**
5583
+ * Adapts binary, multipart, and specialized payload types (FormData, Blob, File,
5584
+ * ArrayBuffer, TypedArrays, URLSearchParams) into JSON-serializable structures
5585
+ * to prevent silent payload loss (BUG-014) when persisting to offline storage.
5586
+ */
5587
+ static async serializeBody(body) {
5588
+ if (body === void 0 || body === null) {
5589
+ return body;
5590
+ }
5591
+ const isFormData = typeof FormData !== "undefined" && (body instanceof FormData || Object.prototype.toString.call(body) === "[object FormData]");
5592
+ if (isFormData) {
5593
+ const entries = [];
5594
+ if (typeof body.entries === "function") {
5595
+ for (const [key, val] of body.entries()) {
5596
+ entries.push([key, await RequestQueue.serializeFieldValue(val)]);
5597
+ }
5598
+ } else if (typeof body.forEach === "function") {
5599
+ const raw = [];
5600
+ body.forEach((val, key) => {
5601
+ raw.push([key, val]);
5602
+ });
5603
+ for (const [key, val] of raw) {
5604
+ entries.push([key, await RequestQueue.serializeFieldValue(val)]);
5605
+ }
5606
+ }
5607
+ return {
5608
+ __katlux_type: "FormData",
5609
+ entries
5610
+ };
5611
+ }
5612
+ const isFile = typeof File !== "undefined" && (body instanceof File || Object.prototype.toString.call(body) === "[object File]");
5613
+ if (isFile) {
5614
+ const bytes = await readBlobAsUint8Array(body);
5615
+ return {
5616
+ __katlux_type: "File",
5617
+ name: body.name,
5618
+ type: body.type || "application/octet-stream",
5619
+ lastModified: body.lastModified,
5620
+ data: uint8ArrayToBase64(bytes)
5621
+ };
5622
+ }
5623
+ const isBlob = typeof Blob !== "undefined" && (body instanceof Blob || Object.prototype.toString.call(body) === "[object Blob]");
5624
+ if (isBlob) {
5625
+ const bytes = await readBlobAsUint8Array(body);
5626
+ return {
5627
+ __katlux_type: "Blob",
5628
+ type: body.type || "application/octet-stream",
5629
+ data: uint8ArrayToBase64(bytes)
5630
+ };
5631
+ }
5632
+ const isArrayBuffer = typeof ArrayBuffer !== "undefined" && (body instanceof ArrayBuffer || Object.prototype.toString.call(body) === "[object ArrayBuffer]");
5633
+ if (isArrayBuffer) {
5634
+ const bytes = new Uint8Array(body);
5635
+ return {
5636
+ __katlux_type: "ArrayBuffer",
5637
+ data: uint8ArrayToBase64(bytes)
5638
+ };
5639
+ }
5640
+ if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(body)) {
5641
+ const view = body;
5642
+ const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
5643
+ return {
5644
+ __katlux_type: "Uint8Array",
5645
+ data: uint8ArrayToBase64(bytes)
5646
+ };
5647
+ }
5648
+ const isURLSearchParams = typeof URLSearchParams !== "undefined" && (body instanceof URLSearchParams || Object.prototype.toString.call(body) === "[object URLSearchParams]");
5649
+ if (isURLSearchParams) {
5650
+ return {
5651
+ __katlux_type: "URLSearchParams",
5652
+ data: body.toString()
5653
+ };
5654
+ }
5655
+ return body;
5656
+ }
5657
+ static async serializeFieldValue(val) {
5658
+ if (typeof File !== "undefined" && (val instanceof File || Object.prototype.toString.call(val) === "[object File]")) {
5659
+ const bytes = await readBlobAsUint8Array(val);
5660
+ return {
5661
+ __katlux_type: "File",
5662
+ name: val.name,
5663
+ type: val.type || "application/octet-stream",
5664
+ lastModified: val.lastModified,
5665
+ data: uint8ArrayToBase64(bytes)
5666
+ };
5667
+ }
5668
+ if (typeof Blob !== "undefined" && (val instanceof Blob || Object.prototype.toString.call(val) === "[object Blob]")) {
5669
+ const bytes = await readBlobAsUint8Array(val);
5670
+ return {
5671
+ __katlux_type: "Blob",
5672
+ type: val.type || "application/octet-stream",
5673
+ data: uint8ArrayToBase64(bytes)
5674
+ };
5675
+ }
5676
+ return typeof val === "string" ? val : String(val);
5677
+ }
5678
+ /**
5679
+ * Reconstitutes serialized offline request bodies back into their live runtime instances
5680
+ * (FormData, Blob, File, ArrayBuffer, Uint8Array, URLSearchParams) before network transmission.
5681
+ */
5682
+ static reconstituteBody(body) {
5683
+ if (!body || typeof body !== "object") {
5684
+ return body;
5685
+ }
5686
+ if (body.__katlux_type === "FormData" && Array.isArray(body.entries)) {
5687
+ if (typeof FormData === "undefined") return body;
5688
+ const fd = new FormData();
5689
+ for (const [key, val] of body.entries) {
5690
+ if (val && typeof val === "object" && val.__katlux_type === "File") {
5691
+ const u8 = base64ToUint8Array(val.data);
5692
+ if (typeof File !== "undefined") {
5693
+ const file = new File([u8], val.name, {
5694
+ type: val.type || "application/octet-stream",
5695
+ lastModified: val.lastModified
5696
+ });
5697
+ fd.append(key, file, val.name);
5698
+ } else if (typeof Blob !== "undefined") {
5699
+ const blob = new Blob([u8], { type: val.type || "application/octet-stream" });
5700
+ fd.append(key, blob, val.name);
5701
+ }
5702
+ } else if (val && typeof val === "object" && val.__katlux_type === "Blob") {
5703
+ if (typeof Blob !== "undefined") {
5704
+ const u8 = base64ToUint8Array(val.data);
5705
+ const blob = new Blob([u8], { type: val.type || "application/octet-stream" });
5706
+ fd.append(key, blob);
5707
+ }
5708
+ } else {
5709
+ fd.append(key, val);
5710
+ }
5711
+ }
5712
+ return fd;
5713
+ }
5714
+ if (body.__katlux_type === "File") {
5715
+ const u8 = base64ToUint8Array(body.data);
5716
+ if (typeof File !== "undefined") {
5717
+ return new File([u8], body.name, {
5718
+ type: body.type || "application/octet-stream",
5719
+ lastModified: body.lastModified
5720
+ });
5721
+ }
5722
+ if (typeof Blob !== "undefined") {
5723
+ return new Blob([u8], { type: body.type || "application/octet-stream" });
5724
+ }
5725
+ return u8;
5726
+ }
5727
+ if (body.__katlux_type === "Blob") {
5728
+ const u8 = base64ToUint8Array(body.data);
5729
+ if (typeof Blob !== "undefined") {
5730
+ return new Blob([u8], { type: body.type || "application/octet-stream" });
5731
+ }
5732
+ return u8;
5733
+ }
5734
+ if (body.__katlux_type === "ArrayBuffer") {
5735
+ const u8 = base64ToUint8Array(body.data);
5736
+ return u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength);
5737
+ }
5738
+ if (body.__katlux_type === "Uint8Array") {
5739
+ return base64ToUint8Array(body.data);
5740
+ }
5741
+ if (body.__katlux_type === "URLSearchParams") {
5742
+ if (typeof URLSearchParams !== "undefined") {
5743
+ return new URLSearchParams(body.data);
5744
+ }
5745
+ return body.data;
5746
+ }
5747
+ return body;
5748
+ }
5749
+ /**
5750
+ * Strips sensitive headers (e.g., authorization, cookie, x-csrf-token) before persisting
5751
+ * request options to persistent storage (IndexedDB / LocalStorage).
5752
+ * Sensitive credentials must never be stored in plaintext in browser storage, and are
5753
+ * instead regenerated dynamically at execution time.
5754
+ */
5755
+ static async sanitizeOptions(options) {
5334
5756
  if (!options) return {};
5335
5757
  const sanitized = {
5336
5758
  method: options.method
5337
5759
  };
5760
+ if (options.credentials) {
5761
+ sanitized.credentials = options.credentials;
5762
+ }
5338
5763
  if (options.headers) {
5339
5764
  const headersObj = {};
5340
5765
  const sensitiveSet = new Set(SENSITIVE_HEADER_KEYS.map((k) => k.toLowerCase()));
@@ -5368,7 +5793,8 @@ class RequestQueue {
5368
5793
  }
5369
5794
  if (options.body !== void 0) {
5370
5795
  try {
5371
- const serialized = JSON.stringify(options.body);
5796
+ const serializedBody = await this.serializeBody(options.body);
5797
+ const serialized = JSON.stringify(serializedBody);
5372
5798
  if (serialized && serialized.length > this.MAX_PAYLOAD_SIZE_BYTES) {
5373
5799
  throw new Error(
5374
5800
  `[RequestQueue] Payload size (${(serialized.length / (1024 * 1024)).toFixed(2)} MB) exceeds maximum allowed size (${(this.MAX_PAYLOAD_SIZE_BYTES / (1024 * 1024)).toFixed(2)} MB)`
@@ -5408,6 +5834,7 @@ class RequestQueue {
5408
5834
  static _onDeadLetter = null;
5409
5835
  static _onFlushComplete = null;
5410
5836
  static _onNetworkError = null;
5837
+ static _onError = null;
5411
5838
  static _headerProvider = null;
5412
5839
  static setHeaderProvider(provider) {
5413
5840
  this._headerProvider = provider;
@@ -5457,6 +5884,12 @@ class RequestQueue {
5457
5884
  static onNetworkError(cb) {
5458
5885
  this._onNetworkError = cb;
5459
5886
  }
5887
+ static onError(cb) {
5888
+ this._onError = cb;
5889
+ }
5890
+ static onQueueFatalError(cb) {
5891
+ this._onError = cb;
5892
+ }
5460
5893
  // ── Enqueue ───────────────────────────────────────────────────────────────
5461
5894
  /**
5462
5895
  * Add an operation to the pending queue and persist it.
@@ -5465,7 +5898,7 @@ class RequestQueue {
5465
5898
  */
5466
5899
  static async enqueue(operation) {
5467
5900
  await this.init();
5468
- const sanitizedOptions = this.sanitizeOptions(operation.options);
5901
+ const sanitizedOptions = await this.sanitizeOptions(operation.options);
5469
5902
  if (this.queue.length >= this.MAX_QUEUE_SIZE) {
5470
5903
  const evicted = this.queue[0];
5471
5904
  await this.moveToDeadLetter(evicted, new Error("Queue capacity exceeded"));
@@ -5528,11 +5961,24 @@ class RequestQueue {
5528
5961
  this.notify();
5529
5962
  this._onNetworkError?.(item);
5530
5963
  } else {
5531
- await this.moveToDeadLetter(item, error, httpStatus);
5964
+ try {
5965
+ await this.moveToDeadLetter(item, error, httpStatus);
5966
+ } catch (dlErr) {
5967
+ await this.persistQueue().catch(() => {
5968
+ });
5969
+ this.notify();
5970
+ const fatalError = dlErr instanceof Error ? dlErr : new Error(String(dlErr));
5971
+ console.error("[RequestQueue] Fatal capacity error moving to dead-letter:", fatalError);
5972
+ this._onError?.(fatalError);
5973
+ }
5532
5974
  }
5533
5975
  break;
5534
5976
  }
5535
5977
  }
5978
+ } catch (topErr) {
5979
+ const fatalError = topErr instanceof Error ? topErr : new Error(String(topErr));
5980
+ console.error("[RequestQueue] flushAll fatal error:", fatalError);
5981
+ this._onError?.(fatalError);
5536
5982
  } finally {
5537
5983
  this.isFlushing = false;
5538
5984
  this.notify();
@@ -5576,7 +6022,16 @@ class RequestQueue {
5576
6022
  this.notify();
5577
6023
  this._onNetworkError?.(item);
5578
6024
  } else {
5579
- await this.moveToDeadLetter(item, error, httpStatus);
6025
+ try {
6026
+ await this.moveToDeadLetter(item, error, httpStatus);
6027
+ } catch (dlErr) {
6028
+ await this.persistQueue().catch(() => {
6029
+ });
6030
+ this.notify();
6031
+ const fatalError = dlErr instanceof Error ? dlErr : new Error(String(dlErr));
6032
+ console.error("[RequestQueue] Fatal capacity error moving to dead-letter:", fatalError);
6033
+ this._onError?.(fatalError);
6034
+ }
5580
6035
  }
5581
6036
  }
5582
6037
  }
@@ -5650,24 +6105,30 @@ class RequestQueue {
5650
6105
  console.error("[RequestQueue] Header provider failed:", err);
5651
6106
  }
5652
6107
  }
5653
- if (typeof document !== "undefined" && document.cookie && !headers["cookie"] && !headers["Cookie"]) {
5654
- headers["cookie"] = document.cookie;
5655
- }
5656
6108
  return headers;
5657
6109
  }
5658
6110
  static async executeRequest(item) {
5659
6111
  const { url, options } = item;
5660
6112
  const headers = await this.regenerateHeaders(options.headers);
6113
+ const body = this.reconstituteBody(options.body);
6114
+ if (typeof FormData !== "undefined" && (body instanceof FormData || Object.prototype.toString.call(body) === "[object FormData]")) {
6115
+ delete headers["content-type"];
6116
+ delete headers["Content-Type"];
6117
+ }
5661
6118
  const fetchOptions = {
5662
6119
  method: item.method,
5663
- body: options.body,
6120
+ body,
5664
6121
  headers,
5665
- query: options.query
6122
+ query: options.query,
6123
+ credentials: options.credentials || "include"
5666
6124
  };
5667
6125
  const fetchFn = globalThis.$fetch || $fetch;
5668
6126
  await fetchFn(url, fetchOptions);
5669
6127
  }
5670
6128
  static async moveToDeadLetter(item, error, httpStatus) {
6129
+ if (this.deadLetterQueue.length >= this.MAX_DEAD_LETTER_SIZE) {
6130
+ 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.`);
6131
+ }
5671
6132
  const deadItem = {
5672
6133
  ...item,
5673
6134
  failedAt: Date.now(),
@@ -5675,11 +6136,6 @@ class RequestQueue {
5675
6136
  httpStatus
5676
6137
  };
5677
6138
  this.queue = this.queue.filter((i) => i.id !== item.id);
5678
- if (this.deadLetterQueue.length >= this.MAX_DEAD_LETTER_SIZE) {
5679
- const evicted = this.deadLetterQueue[0];
5680
- console.warn(`[RequestQueue] Dead-letter queue reached capacity (${this.MAX_DEAD_LETTER_SIZE}). Evicting oldest item: ${evicted?.id}`);
5681
- this.deadLetterQueue = this.deadLetterQueue.slice(1);
5682
- }
5683
6139
  this.deadLetterQueue = [...this.deadLetterQueue, deadItem];
5684
6140
  await this.persistQueue();
5685
6141
  await this.persistDeadLetter();
@@ -5701,6 +6157,7 @@ class RequestQueue {
5701
6157
  this._onDeadLetter = null;
5702
6158
  this._onFlushComplete = null;
5703
6159
  this._onNetworkError = null;
6160
+ this._onError = null;
5704
6161
  this._headerProvider = null;
5705
6162
  this.MAX_PAYLOAD_SIZE_BYTES = 5 * 1024 * 1024;
5706
6163
  this.MAX_QUEUE_SIZE = 500;
@@ -6130,6 +6587,8 @@ class RequestProvider {
6130
6587
  url,
6131
6588
  method,
6132
6589
  isServer,
6590
+ aad: encOptions.aad,
6591
+ bindRequestContextAad: encOptions.bindRequestContextAad,
6133
6592
  key: encOptions.key,
6134
6593
  valueEncryption: encOptions.valueEncryption,
6135
6594
  fields: encOptions.fields,
@@ -8055,13 +8514,41 @@ class CCookieCache extends ACacheProvider {
8055
8514
  return this.instance;
8056
8515
  }
8057
8516
  type = "Cookie";
8517
+ sameSite = "lax";
8518
+ secure = void 0;
8519
+ httpOnly = true;
8520
+ path = "/";
8058
8521
  // Exposed constructor for testing & instantiation
8059
- constructor() {
8522
+ constructor(options) {
8060
8523
  super();
8524
+ if (options) {
8525
+ this.configure(options);
8526
+ }
8527
+ }
8528
+ configure(options) {
8529
+ if (options.sameSite !== void 0) this.sameSite = options.sameSite;
8530
+ if (options.secure !== void 0) this.secure = options.secure;
8531
+ if (options.httpOnly !== void 0) this.httpOnly = options.httpOnly;
8532
+ if (options.path !== void 0) this.path = options.path;
8061
8533
  }
8062
8534
  getCookieKey(key) {
8063
8535
  return "cache:" + encodeURIComponent(key);
8064
8536
  }
8537
+ /**
8538
+ * Resolves the `Secure` flag: an explicit option wins, otherwise follow the
8539
+ * actual protocol so cookies are not silently dropped by browsers over plain HTTP.
8540
+ */
8541
+ resolveSecure(getRequestProtocol, event) {
8542
+ if (this.secure !== void 0) return this.secure;
8543
+ if (event && getRequestProtocol) {
8544
+ try {
8545
+ return getRequestProtocol(event) === "https";
8546
+ } catch {
8547
+ return false;
8548
+ }
8549
+ }
8550
+ return typeof location !== "undefined" && location.protocol === "https:";
8551
+ }
8065
8552
  parseKeyFromCookieName(cookieName) {
8066
8553
  const prefix = "cache:";
8067
8554
  const decoded = decodeURIComponent(cookieName);
@@ -8167,20 +8654,23 @@ class CCookieCache extends ACacheProvider {
8167
8654
  return;
8168
8655
  }
8169
8656
  const maxAge = Math.floor(lifetime / 1e3);
8657
+ const sameSiteFormatted = this.sameSite.charAt(0).toUpperCase() + this.sameSite.slice(1).toLowerCase();
8170
8658
  if (this.isClient(context)) {
8171
8659
  if (typeof document !== "undefined") {
8172
- document.cookie = `${cookieKey}=${cookieValue}; Max-Age=${maxAge}; Path=/; SameSite=Lax`;
8660
+ const secureFlag = this.resolveSecure() ? "; Secure" : "";
8661
+ document.cookie = `${cookieKey}=${cookieValue}; Max-Age=${maxAge}; Path=${this.path}; SameSite=${sameSiteFormatted}${secureFlag}`;
8173
8662
  }
8174
8663
  } else if (context) {
8175
8664
  const event = context?.event ?? context?.ssrContext?.event ?? (context?.node ? context : null);
8176
8665
  if (event) {
8177
8666
  try {
8178
- const { setCookie } = await getH3();
8667
+ const { setCookie, getRequestProtocol } = await getH3();
8179
8668
  setCookie(event, cookieKey, serialized, {
8180
8669
  maxAge,
8181
- path: "/",
8182
- sameSite: "lax",
8183
- httpOnly: true
8670
+ path: this.path,
8671
+ sameSite: this.sameSite,
8672
+ httpOnly: this.httpOnly,
8673
+ secure: this.resolveSecure(getRequestProtocol, event)
8184
8674
  });
8185
8675
  } catch {
8186
8676
  }
@@ -8189,16 +8679,18 @@ class CCookieCache extends ACacheProvider {
8189
8679
  }
8190
8680
  async remove(key, context) {
8191
8681
  const cookieKey = this.getCookieKey(key);
8682
+ const sameSiteFormatted = this.sameSite.charAt(0).toUpperCase() + this.sameSite.slice(1).toLowerCase();
8192
8683
  if (this.isClient(context)) {
8193
8684
  if (typeof document !== "undefined") {
8194
- document.cookie = `${cookieKey}=; Max-Age=0; Path=/; SameSite=Lax`;
8685
+ const secureFlag = this.resolveSecure() ? "; Secure" : "";
8686
+ document.cookie = `${cookieKey}=; Max-Age=0; Path=${this.path}; SameSite=${sameSiteFormatted}${secureFlag}`;
8195
8687
  }
8196
8688
  } else if (context) {
8197
8689
  const event = context?.event ?? context?.ssrContext?.event ?? (context?.node ? context : null);
8198
8690
  if (event) {
8199
8691
  try {
8200
- const { deleteCookie } = await getH3();
8201
- deleteCookie(event, cookieKey, { path: "/", sameSite: "lax", httpOnly: true });
8692
+ const { deleteCookie, getRequestProtocol } = await getH3();
8693
+ deleteCookie(event, cookieKey, { path: this.path, sameSite: this.sameSite, httpOnly: this.httpOnly, secure: this.resolveSecure(getRequestProtocol, event) });
8202
8694
  } catch {
8203
8695
  }
8204
8696
  }
@@ -8452,7 +8944,11 @@ class CServerSessionCache extends ACacheProvider {
8452
8944
  CServerSessionCache._opCounter = 0;
8453
8945
  CServerSessionCache.purgeExpiredServerSessions(50);
8454
8946
  } else if (CServerSessionCache.storage.size >= CServerSessionCache.MAX_SERVER_SESSIONS) {
8455
- CServerSessionCache.purgeExpiredServerSessions();
8947
+ CServerSessionCache.purgeExpiredServerSessions(50);
8948
+ if (CServerSessionCache.storage.size >= CServerSessionCache.MAX_SERVER_SESSIONS) {
8949
+ const oldestKey = CServerSessionCache.storage.keys().next().value;
8950
+ if (oldestKey !== void 0) CServerSessionCache.storage.delete(oldestKey);
8951
+ }
8456
8952
  }
8457
8953
  let sessionData = CServerSessionCache.storage.get(sessionId);
8458
8954
  if (sessionData) {
@@ -9436,4 +9932,4 @@ function isEncrypted(payload) {
9436
9932
  return AEncryptionProvider.isEncrypted(payload);
9437
9933
  }
9438
9934
 
9439
- export { AAPIDataProvider, ADataProvider, AEncryptedClientProvider, AEncryptionProvider, CAPIFlatClientDataProvider, CAPIFlatServerDataProvider, CAPITreeClientDataProvider, CAPITreeServerDataProvider, CApplicationCache, CBrowserSessionCache, CCookieCache, CECDHEncryptionProvider, CFlatClientDataProvider, CFlatServerDataProvider, CIndexedDBCache, CKeyManager, CLocalStorageCache, CMemoryCache, CNodeCryptoEncryptionProvider, CRSAEncryptionProvider, CSearchIndex, CServerSessionCache, CTreeClientDataProvider, CTreeServerDataProvider, CWebCryptoAESCBCProvider, CWebCryptoEncryptionProvider, CacheProviderFactory, DefaultHydrationAdapter, ECacheStrategy, EDataFilterOperator, EQueueStorage, KatluxIndexedDB, QueueStorageFactory, RequestProvider, RequestProviderRegistry, RequestQueue, SENSITIVE_HEADER_KEYS, applyOperator, buildEncryptionContext, clearCachedCipherProvider, clearSSRData, compareAnd, compareEqual, compareIn, compareOr, compareValues, createEncryptionProvider, debounce, decryptPageRows, encryptRows, encryptRowsChunked, evaluateFilter, extractTrigrams, fastKeyHash, fetchWithSSR, filterData, filterTreeData, getAppRoute, getAppRouter, getCipherProvider, getHydrationAdapter, getKeyIdentifier, getPlatformApp, getRandomValues, getSSRData, getSSRPayload, getSafeKeyIdentifier, getSubtleCrypto, isDataEncrypted, isEncrypted, normalizeIndexTerm, onPlatformReady, resolveInfoBytes, safeSetProperty, setHydrationAdapter, sortData, textDecoder, textEncoder$1 as textEncoder, toBase64, useDebounce, useFilterLogic, useSortLogic };
9935
+ export { AAPIDataProvider, ADataProvider, AEncryptedClientProvider, AEncryptionProvider, CAPIFlatClientDataProvider, CAPIFlatServerDataProvider, CAPITreeClientDataProvider, CAPITreeServerDataProvider, CApplicationCache, CBrowserSessionCache, CCookieCache, CECDHEncryptionProvider, CFlatClientDataProvider, CFlatServerDataProvider, CIndexedDBCache, CKeyManager, CLocalStorageCache, CMemoryCache, CNodeCryptoEncryptionProvider, CRSAEncryptionProvider, CSearchIndex, CServerSessionCache, CTreeClientDataProvider, CTreeServerDataProvider, CWebCryptoAESCBCProvider, CWebCryptoEncryptionProvider, CacheProviderFactory, DefaultHydrationAdapter, ECacheStrategy, EDataFilterOperator, EQueueStorage, KatluxIndexedDB, QueueStorageFactory, RequestProvider, RequestProviderRegistry, RequestQueue, SENSITIVE_HEADER_KEYS, applyOperator, buildEncryptionContext, clearCachedCipherProvider, clearSSRData, compareAnd, compareEqual, compareIn, compareOr, compareValues, createEncryptionProvider, debounce, decryptPageRows, encryptRows, encryptRowsChunked, evaluateFilter, extractTrigrams, fastKeyHash, fetchWithSSR, filterData, filterTreeData, getAppRoute, getAppRouter, getCipherProvider, getHydrationAdapter, getKeyIdentifier, getPlatformApp, getRandomValues, getSSRData, getSSRPayload, getSafeKeyIdentifier, getSubtleCrypto, isAuthOrDecryptionError, isDataEncrypted, isEncrypted, normalizeIndexTerm, onPlatformReady, resolveInfoBytes, safeSetProperty, setHydrationAdapter, sortData, textDecoder, textEncoder$1 as textEncoder, toBase64, useDebounce, useFilterLogic, useSortLogic };