@katlux/providers 0.1.1-alpha.111 → 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
@@ -699,6 +699,14 @@ function getKeyIdentifier(keyProvider, defaultKey) {
699
699
  const target = keyProvider ?? defaultKey;
700
700
  return getSafeKeyIdentifier(target);
701
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
+ }
702
710
 
703
711
  class AEncryptionProvider {
704
712
  defaultKey;
@@ -777,6 +785,57 @@ class AEncryptionProvider {
777
785
  async [Symbol.asyncDispose]() {
778
786
  this.dispose();
779
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
+ }
780
839
  /**
781
840
  * Top-level polymorphic encryption method.
782
841
  * Automatically performs value-level encryption:
@@ -812,7 +871,10 @@ class AEncryptionProvider {
812
871
  }
813
872
  const result = { ...data };
814
873
  const entries = await Promise.all(
815
- 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
+ })
816
878
  );
817
879
  for (const [field, encryptedVal] of entries) {
818
880
  safeSetProperty(result, field, encryptedVal);
@@ -831,7 +893,10 @@ class AEncryptionProvider {
831
893
  await this.warmupKey(options);
832
894
  }
833
895
  const entries = await Promise.all(
834
- 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
+ })
835
900
  );
836
901
  for (const [key, encryptedVal] of entries) {
837
902
  safeSetProperty(result, key, encryptedVal);
@@ -864,7 +929,22 @@ class AEncryptionProvider {
864
929
  return payload;
865
930
  }
866
931
  const entries = await Promise.all(
867
- 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
+ })
868
948
  );
869
949
  for (const [key, decryptedVal] of entries) {
870
950
  safeSetProperty(result, key, decryptedVal);
@@ -1236,11 +1316,11 @@ ${lines.join("\n")}
1236
1316
  * Generates a high-entropy symmetric AES-GCM Account Data Encryption Key (ADEK).
1237
1317
  * Designed for multi-user table and field-level encryption.
1238
1318
  */
1239
- static async generateAccountDataKey(length = 256) {
1319
+ static async generateAccountDataKey(length = 256, extractable = false) {
1240
1320
  const subtle = getSubtleCrypto();
1241
1321
  return await subtle.generateKey(
1242
1322
  { name: "AES-GCM", length },
1243
- true,
1323
+ extractable,
1244
1324
  ["encrypt", "decrypt"]
1245
1325
  );
1246
1326
  }
@@ -1271,7 +1351,7 @@ ${lines.join("\n")}
1271
1351
  * Unwraps a Base64-encoded Account Data Encryption Key (ADEK) using the user's private key (RSA-OAEP).
1272
1352
  * Returns the restored AES-GCM CryptoKey ready for use in CWebCryptoEncryptionProvider.
1273
1353
  */
1274
- 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) {
1275
1355
  const subtle = getSubtleCrypto();
1276
1356
  if (userPrivateKey.algorithm.name === "RSA-OAEP") {
1277
1357
  const wrappedBytes = CKeyManager.fromBase64(wrappedKeyBase64);
@@ -1290,7 +1370,7 @@ ${lines.join("\n")}
1290
1370
  "raw",
1291
1371
  unwrappedRawKey,
1292
1372
  unwrappedKeyAlgorithm,
1293
- true,
1373
+ extractable,
1294
1374
  ["encrypt", "decrypt"]
1295
1375
  );
1296
1376
  } finally {
@@ -1463,12 +1543,13 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1463
1543
  return options._warmedKey;
1464
1544
  }
1465
1545
  if (saltOverride) {
1546
+ const rawKey = await this.resolveRawKey(keyProvider);
1466
1547
  const saltKey = typeof saltOverride === "string" ? saltOverride : CKeyManager.toBase64(saltOverride);
1467
- const keyId = getKeyIdentifier(keyProvider, this.defaultKey);
1548
+ const keyId = getSafeKeyIdentifier(rawKey);
1468
1549
  const compoundKey = `${keyId}:${kdfOverride || ""}:${iterationsOverride || ""}:${options?.kdfHash || ""}:${saltKey}`;
1469
1550
  let cached = this._decryptSaltCache.get(compoundKey);
1470
1551
  if (!cached) {
1471
- cached = this._resolveCryptoKeyInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1552
+ cached = this._resolveCryptoKeyInternal(rawKey, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1472
1553
  this._decryptSaltCache.delete(compoundKey);
1473
1554
  throw err;
1474
1555
  });
@@ -1525,9 +1606,9 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1525
1606
  const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
1526
1607
  const matchesKdf = this._cachedKdf !== void 0 && kdf === this._cachedKdf.toLowerCase();
1527
1608
  const matchesSalt = !saltOverride || this._cachedSalt !== void 0 && saltOverride === this._cachedSalt;
1528
- const currentKeyId = getKeyIdentifier(keyProvider, this.defaultKey);
1609
+ const currentKeyId = getSafeKeyIdentifier(rawKey);
1529
1610
  if (this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
1530
- if (!this._cachedKeyId || this._cachedKeyId === currentKeyId) {
1611
+ if (this._cachedKeyId === currentKeyId) {
1531
1612
  return { cryptoKey: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
1532
1613
  }
1533
1614
  }
@@ -1648,7 +1729,7 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1648
1729
  name: "AES-GCM",
1649
1730
  iv
1650
1731
  };
1651
- const aad = options?.aad;
1732
+ const aad = this._resolveEffectiveAad(options, false);
1652
1733
  let hasAad = false;
1653
1734
  if (aad) {
1654
1735
  const aadBytes = typeof aad === "string" ? textEncoder$1.encode(aad) : aad instanceof Uint8Array ? aad : new Uint8Array(aad);
@@ -1710,22 +1791,45 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1710
1791
  name: "AES-GCM",
1711
1792
  iv
1712
1793
  };
1713
- const aad = options?.aad;
1794
+ const aad = this._resolveEffectiveAad(options, true);
1795
+ let hasAad = false;
1714
1796
  if (payload.aad || aad) {
1715
1797
  if (aad) {
1716
1798
  const aadBytes = typeof aad === "string" ? textEncoder$1.encode(aad) : aad instanceof Uint8Array ? aad : new Uint8Array(aad);
1717
1799
  if (aadBytes.byteLength > 0) {
1718
1800
  decryptParams.additionalData = aadBytes;
1801
+ hasAad = true;
1719
1802
  }
1720
1803
  } else if (payload.aad) {
1721
1804
  throw new Error("[CWebCryptoEncryptionProvider] Payload requires Authenticated Additional Data (AAD) for decryption, but none was provided.");
1722
1805
  }
1723
1806
  }
1724
- const decryptedBuffer = await subtle.decrypt(
1725
- decryptParams,
1726
- cryptoKey,
1727
- ciphertextBytes
1728
- );
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
+ }
1729
1833
  try {
1730
1834
  const jsonString = textDecoder.decode(decryptedBuffer);
1731
1835
  return JSON.parse(jsonString);
@@ -1734,7 +1838,12 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1734
1838
  }
1735
1839
  } catch (err) {
1736
1840
  if (err instanceof SyntaxError) throw err;
1737
- 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;
1738
1847
  }
1739
1848
  }
1740
1849
  }
@@ -1747,6 +1856,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1747
1856
  _cachedKdf;
1748
1857
  _cachedIter;
1749
1858
  _cachedHash;
1859
+ _cachedKeyId;
1750
1860
  _configuredKid;
1751
1861
  _kdfOptions;
1752
1862
  _decryptSaltCache = /* @__PURE__ */ new Map();
@@ -1757,9 +1867,9 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1757
1867
  this._configuredKid = options.kid || options.keyId;
1758
1868
  }
1759
1869
  this._defaultKdf = options.kdf || "pbkdf2";
1760
- if (options.kdf && options.kdf !== "none") {
1870
+ if (this._defaultKdf !== "none") {
1761
1871
  this._kdfOptions = {
1762
- kdf: options.kdf,
1872
+ kdf: this._defaultKdf,
1763
1873
  iterations: options.kdfIterations,
1764
1874
  hash: options.kdfHash,
1765
1875
  salt: options.kdfSalt,
@@ -1776,6 +1886,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1776
1886
  this._cachedKdf = void 0;
1777
1887
  this._cachedIter = void 0;
1778
1888
  this._cachedHash = void 0;
1889
+ this._cachedKeyId = void 0;
1779
1890
  this._decryptSaltCache.clear();
1780
1891
  }
1781
1892
  clearKeys() {
@@ -1786,6 +1897,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1786
1897
  this._cachedKdf = void 0;
1787
1898
  this._cachedIter = void 0;
1788
1899
  this._cachedHash = void 0;
1900
+ this._cachedKeyId = void 0;
1789
1901
  this._decryptSaltCache.clear();
1790
1902
  }
1791
1903
  async warmupKey(options) {
@@ -1806,12 +1918,14 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1806
1918
  */
1807
1919
  async resolveCBCKeys(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
1808
1920
  if (saltOverride) {
1921
+ const rawKey = await this.resolveRawKey(keyProvider);
1809
1922
  const saltKey = typeof saltOverride === "string" ? saltOverride : CKeyManager.toBase64(saltOverride);
1810
- const keyId = getKeyIdentifier(keyProvider, this.defaultKey);
1811
- 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}`;
1812
1926
  let cached = this._decryptSaltCache.get(compoundKey);
1813
1927
  if (!cached) {
1814
- cached = this._deriveCBCKeysInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1928
+ cached = this._deriveCBCKeysInternal(rawKey, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1815
1929
  this._decryptSaltCache.delete(compoundKey);
1816
1930
  throw err;
1817
1931
  });
@@ -1831,17 +1945,20 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1831
1945
  return await this._deriveCBCKeysInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride);
1832
1946
  }
1833
1947
  async _deriveCBCKeysInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
1948
+ const rawKey = await this.resolveRawKey(keyProvider);
1949
+ const currentKeyId = getSafeKeyIdentifier(rawKey);
1834
1950
  const subtle = getSubtleCrypto();
1835
- const targetIter = iterationsOverride || options?.kdfIterations;
1836
- const targetHash = options?.kdfHash;
1951
+ const targetIter = iterationsOverride || options?.kdfIterations || this._kdfOptions?.iterations;
1952
+ const targetHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
1837
1953
  const matchesIter = !targetIter || this._cachedIter !== void 0 && targetIter === this._cachedIter;
1838
- const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
1954
+ const matchesHash = this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
1839
1955
  const effectiveKdf = (kdfOverride || options?.kdf || this._defaultKdf || "none").toLowerCase();
1840
1956
  const matchesKdf = this._cachedKdf === "raw" || this._cachedKdf === "hkdf-direct" || this._cachedKdf !== void 0 && effectiveKdf === this._cachedKdf.toLowerCase();
1841
- if (!keyProvider && this._cachedEncKey && this._cachedMacKey && !saltOverride && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
1842
- 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
+ }
1843
1961
  }
1844
- const rawKey = await this.resolveRawKey(keyProvider);
1845
1962
  if (typeof rawKey !== "string" && rawKey.algorithm) {
1846
1963
  const cryptoKey = rawKey;
1847
1964
  let rawBits;
@@ -1874,6 +1991,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1874
1991
  this._cachedEncKey = encKey2;
1875
1992
  this._cachedMacKey = macKey2;
1876
1993
  this._cachedKdf = "hkdf-direct";
1994
+ this._cachedKeyId = currentKeyId;
1877
1995
  }
1878
1996
  return { encKey: encKey2, macKey: macKey2, kdf: "hkdf-direct" };
1879
1997
  }
@@ -1907,6 +2025,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1907
2025
  this._cachedEncKey = encKey2;
1908
2026
  this._cachedMacKey = macKey2;
1909
2027
  this._cachedKdf = "raw";
2028
+ this._cachedKeyId = currentKeyId;
1910
2029
  }
1911
2030
  return { encKey: encKey2, macKey: macKey2, kdf: "raw" };
1912
2031
  }
@@ -1937,6 +2056,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1937
2056
  this._cachedEncKey = encKey2;
1938
2057
  this._cachedMacKey = macKey2;
1939
2058
  this._cachedKdf = "raw";
2059
+ this._cachedKeyId = currentKeyId;
1940
2060
  }
1941
2061
  return { encKey: encKey2, macKey: macKey2, kdf: "raw" };
1942
2062
  }
@@ -2044,6 +2164,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
2044
2164
  this._cachedKdf = kdfType || "none";
2045
2165
  this._cachedIter = iterNum;
2046
2166
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
2167
+ this._cachedKeyId = currentKeyId;
2047
2168
  }
2048
2169
  return {
2049
2170
  encKey,
@@ -2944,6 +3065,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2944
3065
  _cachedKdf;
2945
3066
  _cachedIter;
2946
3067
  _cachedHash;
3068
+ _cachedKeyId;
2947
3069
  _configuredKid;
2948
3070
  setDefaultKey(key) {
2949
3071
  super.setDefaultKey(key);
@@ -2955,6 +3077,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2955
3077
  this._cachedKdf = void 0;
2956
3078
  this._cachedIter = void 0;
2957
3079
  this._cachedHash = void 0;
3080
+ this._cachedKeyId = void 0;
2958
3081
  }
2959
3082
  clearKeys() {
2960
3083
  super.clearKeys();
@@ -2966,6 +3089,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2966
3089
  this._cachedKdf = void 0;
2967
3090
  this._cachedIter = void 0;
2968
3091
  this._cachedHash = void 0;
3092
+ this._cachedKeyId = void 0;
2969
3093
  }
2970
3094
  async warmupKey(options) {
2971
3095
  const res = await this.deriveKeyAsync(options?.key, void 0, void 0, options);
@@ -2975,6 +3099,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2975
3099
  this._cachedKdf = res.kdf;
2976
3100
  this._cachedIter = res.iter;
2977
3101
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3102
+ this._cachedKeyId = getSafeKeyIdentifier(await this.resolveRawKeyAsync(options?.key));
2978
3103
  }
2979
3104
  }
2980
3105
  /**
@@ -2988,6 +3113,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2988
3113
  this._cachedKdf = res.kdf;
2989
3114
  this._cachedIter = res.iter;
2990
3115
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3116
+ this._cachedKeyId = getSafeKeyIdentifier(this.resolveRawKeySync(options?.key));
2991
3117
  }
2992
3118
  }
2993
3119
  resolveInfoBuffer(infoRaw) {
@@ -3074,12 +3200,14 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3074
3200
  }
3075
3201
  deriveKeySync(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
3076
3202
  const raw = this.resolveRawKeySync(keyProvider);
3203
+ const currentKeyId = getSafeKeyIdentifier(raw);
3077
3204
  if (Buffer.isBuffer(raw)) {
3078
3205
  if (raw.length === 32) {
3079
3206
  if (!keyProvider) {
3080
- if (!this._cachedKey) {
3207
+ if (!this._cachedKey || this._cachedKeyId !== currentKeyId) {
3081
3208
  this._cachedKey = Buffer.from(raw);
3082
3209
  this._cachedKdf = "raw";
3210
+ this._cachedKeyId = currentKeyId;
3083
3211
  }
3084
3212
  return { key: this._cachedKey, kdf: "raw" };
3085
3213
  }
@@ -3097,8 +3225,10 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3097
3225
  const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
3098
3226
  const matchesKdf = this._cachedKdf !== void 0 && kdf === this._cachedKdf.toLowerCase();
3099
3227
  const matchesSalt = !saltOverride || this._cachedSalt !== void 0 && saltOverride === this._cachedSalt;
3100
- if (!keyProvider && this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3101
- 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
+ }
3102
3232
  }
3103
3233
  if (kdf === "pbkdf2") {
3104
3234
  const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
@@ -3114,6 +3244,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3114
3244
  this._cachedKdf = "PBKDF2";
3115
3245
  this._cachedIter = iterations;
3116
3246
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3247
+ this._cachedKeyId = currentKeyId;
3117
3248
  }
3118
3249
  return {
3119
3250
  key: key2,
@@ -3139,6 +3270,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3139
3270
  this._cachedSalt = saltBuf.toString("base64");
3140
3271
  this._cachedKdf = "HKDF";
3141
3272
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3273
+ this._cachedKeyId = currentKeyId;
3142
3274
  }
3143
3275
  return {
3144
3276
  key: key2,
@@ -3151,24 +3283,27 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3151
3283
  "[CNodeCryptoEncryptionProvider] WARNING: Decrypting a legacy envelope with no KDF (raw SHA-256 key derivation). This is cryptographically weak. Migrate to pbkdf2 or hkdf."
3152
3284
  );
3153
3285
  }
3154
- if (!keyProvider && this._cachedKey && this._cachedKdf === "none") {
3286
+ if (!keyProvider && this._cachedKey && this._cachedKdf === "none" && this._cachedKeyId === currentKeyId) {
3155
3287
  return { key: this._cachedKey, kdf: "none" };
3156
3288
  }
3157
3289
  const key = crypto$1.createHash("sha256").update(passphrase, "utf8").digest();
3158
3290
  if (!keyProvider) {
3159
3291
  this._cachedKey = key;
3160
3292
  this._cachedKdf = "none";
3293
+ this._cachedKeyId = currentKeyId;
3161
3294
  }
3162
3295
  return { key, kdf: "none" };
3163
3296
  }
3164
3297
  async deriveKeyAsync(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
3165
3298
  const raw = await this.resolveRawKeyAsync(keyProvider);
3299
+ const currentKeyId = getSafeKeyIdentifier(raw);
3166
3300
  if (Buffer.isBuffer(raw)) {
3167
3301
  if (raw.length === 32) {
3168
3302
  if (!keyProvider) {
3169
- if (!this._cachedKey) {
3303
+ if (!this._cachedKey || this._cachedKeyId !== currentKeyId) {
3170
3304
  this._cachedKey = Buffer.from(raw);
3171
3305
  this._cachedKdf = "raw";
3306
+ this._cachedKeyId = currentKeyId;
3172
3307
  }
3173
3308
  return { key: this._cachedKey, kdf: "raw" };
3174
3309
  }
@@ -3186,8 +3321,10 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3186
3321
  const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
3187
3322
  const matchesKdf = this._cachedKdf !== void 0 && kdf === this._cachedKdf.toLowerCase();
3188
3323
  const matchesSalt = !saltOverride || this._cachedSalt !== void 0 && saltOverride === this._cachedSalt;
3189
- if (!keyProvider && this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3190
- 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
+ }
3191
3328
  }
3192
3329
  if (kdf === "pbkdf2") {
3193
3330
  const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
@@ -3208,6 +3345,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3208
3345
  this._cachedKdf = "PBKDF2";
3209
3346
  this._cachedIter = iterations;
3210
3347
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3348
+ this._cachedKeyId = currentKeyId;
3211
3349
  }
3212
3350
  return {
3213
3351
  key: key2,
@@ -3238,6 +3376,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3238
3376
  this._cachedSalt = saltBuf.toString("base64");
3239
3377
  this._cachedKdf = "HKDF";
3240
3378
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3379
+ this._cachedKeyId = currentKeyId;
3241
3380
  }
3242
3381
  return {
3243
3382
  key: key2,
@@ -3250,13 +3389,14 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3250
3389
  "[CNodeCryptoEncryptionProvider] WARNING: Decrypting a legacy envelope with no KDF (raw SHA-256 key derivation). This is cryptographically weak. Migrate to pbkdf2 or hkdf."
3251
3390
  );
3252
3391
  }
3253
- if (!keyProvider && this._cachedKey && this._cachedKdf === "none") {
3392
+ if (!keyProvider && this._cachedKey && this._cachedKdf === "none" && this._cachedKeyId === currentKeyId) {
3254
3393
  return { key: this._cachedKey, kdf: "none" };
3255
3394
  }
3256
3395
  const key = crypto$1.createHash("sha256").update(passphrase, "utf8").digest();
3257
3396
  if (!keyProvider) {
3258
3397
  this._cachedKey = key;
3259
3398
  this._cachedKdf = "none";
3399
+ this._cachedKeyId = currentKeyId;
3260
3400
  }
3261
3401
  return { key, kdf: "none" };
3262
3402
  }
@@ -3283,7 +3423,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3283
3423
  const jsonString = JSON.stringify(data);
3284
3424
  const iv = crypto$1.randomBytes(12);
3285
3425
  const cipher = crypto$1.createCipheriv("aes-256-gcm", key, iv);
3286
- const aad = options?.aad;
3426
+ const aad = this._resolveEffectiveAad(options, false);
3287
3427
  let hasAad = false;
3288
3428
  if (aad) {
3289
3429
  const aadBuffer = Buffer.isBuffer(aad) ? aad : Buffer.from(typeof aad === "string" ? aad : new Uint8Array(aad));
@@ -3336,21 +3476,41 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3336
3476
  }
3337
3477
  const decipher = crypto$1.createDecipheriv("aes-256-gcm", key, iv, { authTagLength: 16 });
3338
3478
  decipher.setAuthTag(authTag);
3339
- const aad = options?.aad;
3479
+ const aad = this._resolveEffectiveAad(options, true);
3480
+ let hasAad = false;
3340
3481
  if (payload.aad || aad) {
3341
3482
  if (aad) {
3342
3483
  const aadBuffer = Buffer.isBuffer(aad) ? aad : Buffer.from(typeof aad === "string" ? aad : new Uint8Array(aad));
3343
3484
  if (aadBuffer.length > 0) {
3344
3485
  decipher.setAAD(aadBuffer);
3486
+ hasAad = true;
3345
3487
  }
3346
3488
  } else if (payload.aad) {
3347
3489
  throw new Error("[CNodeCryptoEncryptionProvider] Payload requires Authenticated Additional Data (AAD) for decryption, but none was provided.");
3348
3490
  }
3349
3491
  }
3350
- const decrypted = Buffer.concat([
3351
- decipher.update(ciphertext),
3352
- decipher.final()
3353
- ]);
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
+ }
3354
3514
  try {
3355
3515
  const jsonString = decrypted.toString("utf8");
3356
3516
  return JSON.parse(jsonString);
@@ -3403,7 +3563,8 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3403
3563
  if (fieldsToEncrypt.length === 0) return { ...data };
3404
3564
  const result = { ...data };
3405
3565
  for (const field of fieldsToEncrypt) {
3406
- 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));
3407
3568
  }
3408
3569
  return result;
3409
3570
  }
@@ -3411,7 +3572,8 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3411
3572
  const result = { ...data };
3412
3573
  for (const key of Object.keys(result)) {
3413
3574
  if (result[key] !== void 0 && result[key] !== null && !this.isEncrypted(result[key])) {
3414
- 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));
3415
3577
  }
3416
3578
  }
3417
3579
  return result;
@@ -3450,7 +3612,21 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3450
3612
  derivedKey = derived.key;
3451
3613
  keyCache.set(salt, derivedKey);
3452
3614
  }
3453
- 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
+ }
3454
3630
  mutated = true;
3455
3631
  }
3456
3632
  }
@@ -3490,7 +3666,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3490
3666
  const jsonString = JSON.stringify(data);
3491
3667
  const iv = crypto$1.randomBytes(12);
3492
3668
  const cipher = crypto$1.createCipheriv("aes-256-gcm", key, iv);
3493
- const aad = options?.aad;
3669
+ const aad = this._resolveEffectiveAad(options, false);
3494
3670
  let hasAad = false;
3495
3671
  if (aad) {
3496
3672
  const aadBuffer = Buffer.isBuffer(aad) ? aad : Buffer.from(typeof aad === "string" ? aad : new Uint8Array(aad));
@@ -3578,7 +3754,21 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3578
3754
  derivedKey = derived.key;
3579
3755
  keyCache.set(salt, derivedKey);
3580
3756
  }
3581
- 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
+ }
3582
3772
  mutated = true;
3583
3773
  }
3584
3774
  }
@@ -5321,6 +5511,48 @@ function generateId() {
5321
5511
  }
5322
5512
  return Date.now().toString(36) + Math.random().toString(36).slice(2);
5323
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
+ }
5324
5556
  const SENSITIVE_HEADER_KEYS = ["authorization", "cookie", "set-cookie", "x-csrf-token"];
5325
5557
  class RequestQueue {
5326
5558
  // ── State ──────────────────────────────────────────────────────────────────
@@ -5347,11 +5579,187 @@ class RequestQueue {
5347
5579
  * Sensitive credentials must never be stored in plaintext in browser storage, and are
5348
5580
  * instead regenerated dynamically at execution time.
5349
5581
  */
5350
- 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) {
5351
5756
  if (!options) return {};
5352
5757
  const sanitized = {
5353
5758
  method: options.method
5354
5759
  };
5760
+ if (options.credentials) {
5761
+ sanitized.credentials = options.credentials;
5762
+ }
5355
5763
  if (options.headers) {
5356
5764
  const headersObj = {};
5357
5765
  const sensitiveSet = new Set(SENSITIVE_HEADER_KEYS.map((k) => k.toLowerCase()));
@@ -5385,7 +5793,8 @@ class RequestQueue {
5385
5793
  }
5386
5794
  if (options.body !== void 0) {
5387
5795
  try {
5388
- const serialized = JSON.stringify(options.body);
5796
+ const serializedBody = await this.serializeBody(options.body);
5797
+ const serialized = JSON.stringify(serializedBody);
5389
5798
  if (serialized && serialized.length > this.MAX_PAYLOAD_SIZE_BYTES) {
5390
5799
  throw new Error(
5391
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)`
@@ -5425,6 +5834,7 @@ class RequestQueue {
5425
5834
  static _onDeadLetter = null;
5426
5835
  static _onFlushComplete = null;
5427
5836
  static _onNetworkError = null;
5837
+ static _onError = null;
5428
5838
  static _headerProvider = null;
5429
5839
  static setHeaderProvider(provider) {
5430
5840
  this._headerProvider = provider;
@@ -5474,6 +5884,12 @@ class RequestQueue {
5474
5884
  static onNetworkError(cb) {
5475
5885
  this._onNetworkError = cb;
5476
5886
  }
5887
+ static onError(cb) {
5888
+ this._onError = cb;
5889
+ }
5890
+ static onQueueFatalError(cb) {
5891
+ this._onError = cb;
5892
+ }
5477
5893
  // ── Enqueue ───────────────────────────────────────────────────────────────
5478
5894
  /**
5479
5895
  * Add an operation to the pending queue and persist it.
@@ -5482,7 +5898,7 @@ class RequestQueue {
5482
5898
  */
5483
5899
  static async enqueue(operation) {
5484
5900
  await this.init();
5485
- const sanitizedOptions = this.sanitizeOptions(operation.options);
5901
+ const sanitizedOptions = await this.sanitizeOptions(operation.options);
5486
5902
  if (this.queue.length >= this.MAX_QUEUE_SIZE) {
5487
5903
  const evicted = this.queue[0];
5488
5904
  await this.moveToDeadLetter(evicted, new Error("Queue capacity exceeded"));
@@ -5545,11 +5961,24 @@ class RequestQueue {
5545
5961
  this.notify();
5546
5962
  this._onNetworkError?.(item);
5547
5963
  } else {
5548
- 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
+ }
5549
5974
  }
5550
5975
  break;
5551
5976
  }
5552
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);
5553
5982
  } finally {
5554
5983
  this.isFlushing = false;
5555
5984
  this.notify();
@@ -5593,7 +6022,16 @@ class RequestQueue {
5593
6022
  this.notify();
5594
6023
  this._onNetworkError?.(item);
5595
6024
  } else {
5596
- 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
+ }
5597
6035
  }
5598
6036
  }
5599
6037
  }
@@ -5667,24 +6105,30 @@ class RequestQueue {
5667
6105
  console.error("[RequestQueue] Header provider failed:", err);
5668
6106
  }
5669
6107
  }
5670
- if (typeof document !== "undefined" && document.cookie && !headers["cookie"] && !headers["Cookie"]) {
5671
- headers["cookie"] = document.cookie;
5672
- }
5673
6108
  return headers;
5674
6109
  }
5675
6110
  static async executeRequest(item) {
5676
6111
  const { url, options } = item;
5677
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
+ }
5678
6118
  const fetchOptions = {
5679
6119
  method: item.method,
5680
- body: options.body,
6120
+ body,
5681
6121
  headers,
5682
- query: options.query
6122
+ query: options.query,
6123
+ credentials: options.credentials || "include"
5683
6124
  };
5684
6125
  const fetchFn = globalThis.$fetch || $fetch;
5685
6126
  await fetchFn(url, fetchOptions);
5686
6127
  }
5687
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
+ }
5688
6132
  const deadItem = {
5689
6133
  ...item,
5690
6134
  failedAt: Date.now(),
@@ -5692,11 +6136,6 @@ class RequestQueue {
5692
6136
  httpStatus
5693
6137
  };
5694
6138
  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
6139
  this.deadLetterQueue = [...this.deadLetterQueue, deadItem];
5701
6140
  await this.persistQueue();
5702
6141
  await this.persistDeadLetter();
@@ -5718,6 +6157,7 @@ class RequestQueue {
5718
6157
  this._onDeadLetter = null;
5719
6158
  this._onFlushComplete = null;
5720
6159
  this._onNetworkError = null;
6160
+ this._onError = null;
5721
6161
  this._headerProvider = null;
5722
6162
  this.MAX_PAYLOAD_SIZE_BYTES = 5 * 1024 * 1024;
5723
6163
  this.MAX_QUEUE_SIZE = 500;
@@ -6147,6 +6587,8 @@ class RequestProvider {
6147
6587
  url,
6148
6588
  method,
6149
6589
  isServer,
6590
+ aad: encOptions.aad,
6591
+ bindRequestContextAad: encOptions.bindRequestContextAad,
6150
6592
  key: encOptions.key,
6151
6593
  valueEncryption: encOptions.valueEncryption,
6152
6594
  fields: encOptions.fields,
@@ -8072,13 +8514,41 @@ class CCookieCache extends ACacheProvider {
8072
8514
  return this.instance;
8073
8515
  }
8074
8516
  type = "Cookie";
8517
+ sameSite = "lax";
8518
+ secure = void 0;
8519
+ httpOnly = true;
8520
+ path = "/";
8075
8521
  // Exposed constructor for testing & instantiation
8076
- constructor() {
8522
+ constructor(options) {
8077
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;
8078
8533
  }
8079
8534
  getCookieKey(key) {
8080
8535
  return "cache:" + encodeURIComponent(key);
8081
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
+ }
8082
8552
  parseKeyFromCookieName(cookieName) {
8083
8553
  const prefix = "cache:";
8084
8554
  const decoded = decodeURIComponent(cookieName);
@@ -8184,20 +8654,23 @@ class CCookieCache extends ACacheProvider {
8184
8654
  return;
8185
8655
  }
8186
8656
  const maxAge = Math.floor(lifetime / 1e3);
8657
+ const sameSiteFormatted = this.sameSite.charAt(0).toUpperCase() + this.sameSite.slice(1).toLowerCase();
8187
8658
  if (this.isClient(context)) {
8188
8659
  if (typeof document !== "undefined") {
8189
- 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}`;
8190
8662
  }
8191
8663
  } else if (context) {
8192
8664
  const event = context?.event ?? context?.ssrContext?.event ?? (context?.node ? context : null);
8193
8665
  if (event) {
8194
8666
  try {
8195
- const { setCookie } = await getH3();
8667
+ const { setCookie, getRequestProtocol } = await getH3();
8196
8668
  setCookie(event, cookieKey, serialized, {
8197
8669
  maxAge,
8198
- path: "/",
8199
- sameSite: "lax",
8200
- httpOnly: true
8670
+ path: this.path,
8671
+ sameSite: this.sameSite,
8672
+ httpOnly: this.httpOnly,
8673
+ secure: this.resolveSecure(getRequestProtocol, event)
8201
8674
  });
8202
8675
  } catch {
8203
8676
  }
@@ -8206,16 +8679,18 @@ class CCookieCache extends ACacheProvider {
8206
8679
  }
8207
8680
  async remove(key, context) {
8208
8681
  const cookieKey = this.getCookieKey(key);
8682
+ const sameSiteFormatted = this.sameSite.charAt(0).toUpperCase() + this.sameSite.slice(1).toLowerCase();
8209
8683
  if (this.isClient(context)) {
8210
8684
  if (typeof document !== "undefined") {
8211
- 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}`;
8212
8687
  }
8213
8688
  } else if (context) {
8214
8689
  const event = context?.event ?? context?.ssrContext?.event ?? (context?.node ? context : null);
8215
8690
  if (event) {
8216
8691
  try {
8217
- const { deleteCookie } = await getH3();
8218
- 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) });
8219
8694
  } catch {
8220
8695
  }
8221
8696
  }
@@ -8469,7 +8944,11 @@ class CServerSessionCache extends ACacheProvider {
8469
8944
  CServerSessionCache._opCounter = 0;
8470
8945
  CServerSessionCache.purgeExpiredServerSessions(50);
8471
8946
  } else if (CServerSessionCache.storage.size >= CServerSessionCache.MAX_SERVER_SESSIONS) {
8472
- 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
+ }
8473
8952
  }
8474
8953
  let sessionData = CServerSessionCache.storage.get(sessionId);
8475
8954
  if (sessionData) {
@@ -9453,4 +9932,4 @@ function isEncrypted(payload) {
9453
9932
  return AEncryptionProvider.isEncrypted(payload);
9454
9933
  }
9455
9934
 
9456
- 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 };