@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.cjs CHANGED
@@ -716,6 +716,14 @@ function getKeyIdentifier(keyProvider, defaultKey) {
716
716
  const target = keyProvider ?? defaultKey;
717
717
  return getSafeKeyIdentifier(target);
718
718
  }
719
+ function isAuthOrDecryptionError(err) {
720
+ if (!err) return false;
721
+ if (err.name === "OperationError") return true;
722
+ if (err.code === "ERR_CRYPTO_OPERATION_FAILED" || err.code === "ERR_OSSL_EVP_BAD_DECRYPT") return true;
723
+ if (err.cause && isAuthOrDecryptionError(err.cause)) return true;
724
+ const msg = String(err.message || "").toLowerCase();
725
+ return msg.includes("operationerror") || msg.includes("decrypt") || msg.includes("tag") || msg.includes("aad") || msg.includes("authenticated additional data") || msg.includes("authenticate data") || msg.includes("mac");
726
+ }
719
727
 
720
728
  class AEncryptionProvider {
721
729
  defaultKey;
@@ -794,6 +802,57 @@ class AEncryptionProvider {
794
802
  async [Symbol.asyncDispose]() {
795
803
  this.dispose();
796
804
  }
805
+ /**
806
+ * Resolves effective Authenticated Additional Data (AAD) for the operation:
807
+ * 1. If options.bindRequestContextAad is explicitly false, returns options.aad directly without context binding.
808
+ * 2. When encrypting (isDecrypt=false): binds request context `req:${method}:${url}` only if options.bindRequestContextAad === true.
809
+ * 3. When decrypting (isDecrypt=true): derives request context `req:${method}:${url}` if url or method is provided.
810
+ * 4. If explicit options.aad is provided: combines with request context if bound, or returns options.aad directly.
811
+ * 5. Otherwise returns undefined.
812
+ */
813
+ _resolveEffectiveAad(options, isDecrypt = false) {
814
+ if (!options) return void 0;
815
+ if (options.bindRequestContextAad === false) return options.aad;
816
+ const hasReqContext = Boolean(options.url || options.method);
817
+ if (options.aad) {
818
+ if (options.bindRequestContextAad === true && hasReqContext) {
819
+ const m = (options.method || "POST").toUpperCase();
820
+ const u = options.url || "";
821
+ const baseAad = typeof options.aad === "string" ? options.aad : options.aad instanceof Uint8Array || options.aad instanceof ArrayBuffer ? textDecoder.decode(options.aad) : String(options.aad);
822
+ return `${baseAad}|req:${m}:${u}`;
823
+ }
824
+ return options.aad;
825
+ }
826
+ const shouldBindReq = isDecrypt ? hasReqContext : options.bindRequestContextAad === true && hasReqContext;
827
+ if (shouldBindReq) {
828
+ const m = (options.method || "POST").toUpperCase();
829
+ const u = options.url || "";
830
+ return `req:${m}:${u}`;
831
+ }
832
+ return void 0;
833
+ }
834
+ /**
835
+ * Helper to deterministically bind record ID and field name into the AAD
836
+ * to prevent ciphertext swapping between fields or records.
837
+ */
838
+ _bindFieldAad(data, field, options) {
839
+ let baseAad = "";
840
+ if (options?.aad) {
841
+ if (typeof options.aad === "string") baseAad = options.aad;
842
+ else if (options.aad instanceof Uint8Array || options.aad instanceof ArrayBuffer) {
843
+ baseAad = textDecoder.decode(options.aad);
844
+ } else {
845
+ baseAad = String(options.aad);
846
+ }
847
+ }
848
+ const recordId = data && typeof data === "object" && (data.id !== void 0 || data._id !== void 0) ? String(data.id ?? data._id) : "";
849
+ const recordPart = recordId ? `|record:${recordId}` : "";
850
+ const reqPart = options?.bindRequestContextAad === true && (options?.url || options?.method) ? `|req:${(options.method || "POST").toUpperCase()}:${options.url || ""}` : "";
851
+ return {
852
+ ...options,
853
+ aad: `aad:${baseAad}${recordPart}${reqPart}|field:${field}`
854
+ };
855
+ }
797
856
  /**
798
857
  * Top-level polymorphic encryption method.
799
858
  * Automatically performs value-level encryption:
@@ -829,7 +888,10 @@ class AEncryptionProvider {
829
888
  }
830
889
  const result = { ...data };
831
890
  const entries = await Promise.all(
832
- fieldsToEncrypt.map(async (field) => [field, await this.encryptValue(result[field], options)])
891
+ fieldsToEncrypt.map(async (field) => {
892
+ const fieldOptions = this._bindFieldAad(data, field, options);
893
+ return [field, await this.encryptValue(result[field], fieldOptions)];
894
+ })
833
895
  );
834
896
  for (const [field, encryptedVal] of entries) {
835
897
  safeSetProperty(result, field, encryptedVal);
@@ -848,7 +910,10 @@ class AEncryptionProvider {
848
910
  await this.warmupKey(options);
849
911
  }
850
912
  const entries = await Promise.all(
851
- keysToEncrypt.map(async (key) => [key, await this.encryptValue(result[key], options)])
913
+ keysToEncrypt.map(async (key) => {
914
+ const fieldOptions = this._bindFieldAad(data, key, options);
915
+ return [key, await this.encryptValue(result[key], fieldOptions)];
916
+ })
852
917
  );
853
918
  for (const [key, encryptedVal] of entries) {
854
919
  safeSetProperty(result, key, encryptedVal);
@@ -881,7 +946,22 @@ class AEncryptionProvider {
881
946
  return payload;
882
947
  }
883
948
  const entries = await Promise.all(
884
- keysToDecrypt.map(async (key) => [key, await this.decryptValue(result[key], options)])
949
+ keysToDecrypt.map(async (key) => {
950
+ const boundOptions = this._bindFieldAad(payload, key, options);
951
+ const hasBoundAad = boundOptions.aad !== options?.aad;
952
+ try {
953
+ return [key, await this.decryptValue(result[key], boundOptions)];
954
+ } catch (err) {
955
+ if (hasBoundAad && isAuthOrDecryptionError(err)) {
956
+ try {
957
+ return [key, await this.decryptValue(result[key], options)];
958
+ } catch (fallbackErr) {
959
+ throw fallbackErr;
960
+ }
961
+ }
962
+ throw err;
963
+ }
964
+ })
885
965
  );
886
966
  for (const [key, decryptedVal] of entries) {
887
967
  safeSetProperty(result, key, decryptedVal);
@@ -1253,11 +1333,11 @@ ${lines.join("\n")}
1253
1333
  * Generates a high-entropy symmetric AES-GCM Account Data Encryption Key (ADEK).
1254
1334
  * Designed for multi-user table and field-level encryption.
1255
1335
  */
1256
- static async generateAccountDataKey(length = 256) {
1336
+ static async generateAccountDataKey(length = 256, extractable = false) {
1257
1337
  const subtle = getSubtleCrypto();
1258
1338
  return await subtle.generateKey(
1259
1339
  { name: "AES-GCM", length },
1260
- true,
1340
+ extractable,
1261
1341
  ["encrypt", "decrypt"]
1262
1342
  );
1263
1343
  }
@@ -1288,7 +1368,7 @@ ${lines.join("\n")}
1288
1368
  * Unwraps a Base64-encoded Account Data Encryption Key (ADEK) using the user's private key (RSA-OAEP).
1289
1369
  * Returns the restored AES-GCM CryptoKey ready for use in CWebCryptoEncryptionProvider.
1290
1370
  */
1291
- static async unwrapAccountKeyForUser(wrappedKeyBase64, userPrivateKey, unwrappedKeyAlgorithm = { name: "AES-GCM", length: 256 }) {
1371
+ static async unwrapAccountKeyForUser(wrappedKeyBase64, userPrivateKey, unwrappedKeyAlgorithm = { name: "AES-GCM", length: 256 }, extractable = false) {
1292
1372
  const subtle = getSubtleCrypto();
1293
1373
  if (userPrivateKey.algorithm.name === "RSA-OAEP") {
1294
1374
  const wrappedBytes = CKeyManager.fromBase64(wrappedKeyBase64);
@@ -1307,7 +1387,7 @@ ${lines.join("\n")}
1307
1387
  "raw",
1308
1388
  unwrappedRawKey,
1309
1389
  unwrappedKeyAlgorithm,
1310
- true,
1390
+ extractable,
1311
1391
  ["encrypt", "decrypt"]
1312
1392
  );
1313
1393
  } finally {
@@ -1480,12 +1560,13 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1480
1560
  return options._warmedKey;
1481
1561
  }
1482
1562
  if (saltOverride) {
1563
+ const rawKey = await this.resolveRawKey(keyProvider);
1483
1564
  const saltKey = typeof saltOverride === "string" ? saltOverride : CKeyManager.toBase64(saltOverride);
1484
- const keyId = getKeyIdentifier(keyProvider, this.defaultKey);
1565
+ const keyId = getSafeKeyIdentifier(rawKey);
1485
1566
  const compoundKey = `${keyId}:${kdfOverride || ""}:${iterationsOverride || ""}:${options?.kdfHash || ""}:${saltKey}`;
1486
1567
  let cached = this._decryptSaltCache.get(compoundKey);
1487
1568
  if (!cached) {
1488
- cached = this._resolveCryptoKeyInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1569
+ cached = this._resolveCryptoKeyInternal(rawKey, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1489
1570
  this._decryptSaltCache.delete(compoundKey);
1490
1571
  throw err;
1491
1572
  });
@@ -1542,9 +1623,9 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1542
1623
  const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
1543
1624
  const matchesKdf = this._cachedKdf !== void 0 && kdf === this._cachedKdf.toLowerCase();
1544
1625
  const matchesSalt = !saltOverride || this._cachedSalt !== void 0 && saltOverride === this._cachedSalt;
1545
- const currentKeyId = getKeyIdentifier(keyProvider, this.defaultKey);
1626
+ const currentKeyId = getSafeKeyIdentifier(rawKey);
1546
1627
  if (this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
1547
- if (!this._cachedKeyId || this._cachedKeyId === currentKeyId) {
1628
+ if (this._cachedKeyId === currentKeyId) {
1548
1629
  return { cryptoKey: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
1549
1630
  }
1550
1631
  }
@@ -1665,7 +1746,7 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1665
1746
  name: "AES-GCM",
1666
1747
  iv
1667
1748
  };
1668
- const aad = options?.aad;
1749
+ const aad = this._resolveEffectiveAad(options, false);
1669
1750
  let hasAad = false;
1670
1751
  if (aad) {
1671
1752
  const aadBytes = typeof aad === "string" ? textEncoder$1.encode(aad) : aad instanceof Uint8Array ? aad : new Uint8Array(aad);
@@ -1727,22 +1808,45 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1727
1808
  name: "AES-GCM",
1728
1809
  iv
1729
1810
  };
1730
- const aad = options?.aad;
1811
+ const aad = this._resolveEffectiveAad(options, true);
1812
+ let hasAad = false;
1731
1813
  if (payload.aad || aad) {
1732
1814
  if (aad) {
1733
1815
  const aadBytes = typeof aad === "string" ? textEncoder$1.encode(aad) : aad instanceof Uint8Array ? aad : new Uint8Array(aad);
1734
1816
  if (aadBytes.byteLength > 0) {
1735
1817
  decryptParams.additionalData = aadBytes;
1818
+ hasAad = true;
1736
1819
  }
1737
1820
  } else if (payload.aad) {
1738
1821
  throw new Error("[CWebCryptoEncryptionProvider] Payload requires Authenticated Additional Data (AAD) for decryption, but none was provided.");
1739
1822
  }
1740
1823
  }
1741
- const decryptedBuffer = await subtle.decrypt(
1742
- decryptParams,
1743
- cryptoKey,
1744
- ciphertextBytes
1745
- );
1824
+ let decryptedBuffer;
1825
+ try {
1826
+ decryptedBuffer = await subtle.decrypt(
1827
+ decryptParams,
1828
+ cryptoKey,
1829
+ ciphertextBytes
1830
+ );
1831
+ } catch (firstErr) {
1832
+ if (!payload.aad && hasAad) {
1833
+ try {
1834
+ const fallbackParams = {
1835
+ name: "AES-GCM",
1836
+ iv
1837
+ };
1838
+ decryptedBuffer = await subtle.decrypt(
1839
+ fallbackParams,
1840
+ cryptoKey,
1841
+ ciphertextBytes
1842
+ );
1843
+ } catch {
1844
+ throw firstErr;
1845
+ }
1846
+ } else {
1847
+ throw firstErr;
1848
+ }
1849
+ }
1746
1850
  try {
1747
1851
  const jsonString = textDecoder.decode(decryptedBuffer);
1748
1852
  return JSON.parse(jsonString);
@@ -1751,7 +1855,12 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
1751
1855
  }
1752
1856
  } catch (err) {
1753
1857
  if (err instanceof SyntaxError) throw err;
1754
- throw new Error(`[CWebCryptoEncryptionProvider] Decryption failed: ${err?.message || "Authentication tag mismatch or corrupted ciphertext"}`);
1858
+ const decryptError = new Error(`[CWebCryptoEncryptionProvider] Decryption failed: ${err?.message || "Authentication tag mismatch or corrupted ciphertext"}`);
1859
+ if (err?.name) {
1860
+ decryptError.name = err.name;
1861
+ }
1862
+ decryptError.cause = err;
1863
+ throw decryptError;
1755
1864
  }
1756
1865
  }
1757
1866
  }
@@ -1764,6 +1873,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1764
1873
  _cachedKdf;
1765
1874
  _cachedIter;
1766
1875
  _cachedHash;
1876
+ _cachedKeyId;
1767
1877
  _configuredKid;
1768
1878
  _kdfOptions;
1769
1879
  _decryptSaltCache = /* @__PURE__ */ new Map();
@@ -1774,9 +1884,9 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1774
1884
  this._configuredKid = options.kid || options.keyId;
1775
1885
  }
1776
1886
  this._defaultKdf = options.kdf || "pbkdf2";
1777
- if (options.kdf && options.kdf !== "none") {
1887
+ if (this._defaultKdf !== "none") {
1778
1888
  this._kdfOptions = {
1779
- kdf: options.kdf,
1889
+ kdf: this._defaultKdf,
1780
1890
  iterations: options.kdfIterations,
1781
1891
  hash: options.kdfHash,
1782
1892
  salt: options.kdfSalt,
@@ -1793,6 +1903,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1793
1903
  this._cachedKdf = void 0;
1794
1904
  this._cachedIter = void 0;
1795
1905
  this._cachedHash = void 0;
1906
+ this._cachedKeyId = void 0;
1796
1907
  this._decryptSaltCache.clear();
1797
1908
  }
1798
1909
  clearKeys() {
@@ -1803,6 +1914,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1803
1914
  this._cachedKdf = void 0;
1804
1915
  this._cachedIter = void 0;
1805
1916
  this._cachedHash = void 0;
1917
+ this._cachedKeyId = void 0;
1806
1918
  this._decryptSaltCache.clear();
1807
1919
  }
1808
1920
  async warmupKey(options) {
@@ -1823,12 +1935,14 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1823
1935
  */
1824
1936
  async resolveCBCKeys(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
1825
1937
  if (saltOverride) {
1938
+ const rawKey = await this.resolveRawKey(keyProvider);
1826
1939
  const saltKey = typeof saltOverride === "string" ? saltOverride : CKeyManager.toBase64(saltOverride);
1827
- const keyId = getKeyIdentifier(keyProvider, this.defaultKey);
1828
- const compoundKey = `${keyId}:${kdfOverride || ""}:${iterationsOverride || ""}:${options?.kdfHash || ""}:${saltKey}`;
1940
+ const keyId = getSafeKeyIdentifier(rawKey);
1941
+ const effectiveHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
1942
+ const compoundKey = `${keyId}:${kdfOverride || ""}:${iterationsOverride || ""}:${effectiveHash}:${saltKey}`;
1829
1943
  let cached = this._decryptSaltCache.get(compoundKey);
1830
1944
  if (!cached) {
1831
- cached = this._deriveCBCKeysInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1945
+ cached = this._deriveCBCKeysInternal(rawKey, kdfOverride, saltOverride, options, iterationsOverride).catch((err) => {
1832
1946
  this._decryptSaltCache.delete(compoundKey);
1833
1947
  throw err;
1834
1948
  });
@@ -1848,17 +1962,20 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1848
1962
  return await this._deriveCBCKeysInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride);
1849
1963
  }
1850
1964
  async _deriveCBCKeysInternal(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
1965
+ const rawKey = await this.resolveRawKey(keyProvider);
1966
+ const currentKeyId = getSafeKeyIdentifier(rawKey);
1851
1967
  const subtle = getSubtleCrypto();
1852
- const targetIter = iterationsOverride || options?.kdfIterations;
1853
- const targetHash = options?.kdfHash;
1968
+ const targetIter = iterationsOverride || options?.kdfIterations || this._kdfOptions?.iterations;
1969
+ const targetHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
1854
1970
  const matchesIter = !targetIter || this._cachedIter !== void 0 && targetIter === this._cachedIter;
1855
- const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
1971
+ const matchesHash = this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
1856
1972
  const effectiveKdf = (kdfOverride || options?.kdf || this._defaultKdf || "none").toLowerCase();
1857
1973
  const matchesKdf = this._cachedKdf === "raw" || this._cachedKdf === "hkdf-direct" || this._cachedKdf !== void 0 && effectiveKdf === this._cachedKdf.toLowerCase();
1858
- if (!keyProvider && this._cachedEncKey && this._cachedMacKey && !saltOverride && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
1859
- return { encKey: this._cachedEncKey, macKey: this._cachedMacKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
1974
+ if (this._cachedEncKey && this._cachedMacKey && !saltOverride && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
1975
+ if (this._cachedKeyId === currentKeyId) {
1976
+ return { encKey: this._cachedEncKey, macKey: this._cachedMacKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
1977
+ }
1860
1978
  }
1861
- const rawKey = await this.resolveRawKey(keyProvider);
1862
1979
  if (typeof rawKey !== "string" && rawKey.algorithm) {
1863
1980
  const cryptoKey = rawKey;
1864
1981
  let rawBits;
@@ -1891,6 +2008,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1891
2008
  this._cachedEncKey = encKey2;
1892
2009
  this._cachedMacKey = macKey2;
1893
2010
  this._cachedKdf = "hkdf-direct";
2011
+ this._cachedKeyId = currentKeyId;
1894
2012
  }
1895
2013
  return { encKey: encKey2, macKey: macKey2, kdf: "hkdf-direct" };
1896
2014
  }
@@ -1924,6 +2042,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1924
2042
  this._cachedEncKey = encKey2;
1925
2043
  this._cachedMacKey = macKey2;
1926
2044
  this._cachedKdf = "raw";
2045
+ this._cachedKeyId = currentKeyId;
1927
2046
  }
1928
2047
  return { encKey: encKey2, macKey: macKey2, kdf: "raw" };
1929
2048
  }
@@ -1954,6 +2073,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
1954
2073
  this._cachedEncKey = encKey2;
1955
2074
  this._cachedMacKey = macKey2;
1956
2075
  this._cachedKdf = "raw";
2076
+ this._cachedKeyId = currentKeyId;
1957
2077
  }
1958
2078
  return { encKey: encKey2, macKey: macKey2, kdf: "raw" };
1959
2079
  }
@@ -2061,6 +2181,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
2061
2181
  this._cachedKdf = kdfType || "none";
2062
2182
  this._cachedIter = iterNum;
2063
2183
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
2184
+ this._cachedKeyId = currentKeyId;
2064
2185
  }
2065
2186
  return {
2066
2187
  encKey,
@@ -2961,6 +3082,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2961
3082
  _cachedKdf;
2962
3083
  _cachedIter;
2963
3084
  _cachedHash;
3085
+ _cachedKeyId;
2964
3086
  _configuredKid;
2965
3087
  setDefaultKey(key) {
2966
3088
  super.setDefaultKey(key);
@@ -2972,6 +3094,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2972
3094
  this._cachedKdf = void 0;
2973
3095
  this._cachedIter = void 0;
2974
3096
  this._cachedHash = void 0;
3097
+ this._cachedKeyId = void 0;
2975
3098
  }
2976
3099
  clearKeys() {
2977
3100
  super.clearKeys();
@@ -2983,6 +3106,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2983
3106
  this._cachedKdf = void 0;
2984
3107
  this._cachedIter = void 0;
2985
3108
  this._cachedHash = void 0;
3109
+ this._cachedKeyId = void 0;
2986
3110
  }
2987
3111
  async warmupKey(options) {
2988
3112
  const res = await this.deriveKeyAsync(options?.key, void 0, void 0, options);
@@ -2992,6 +3116,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
2992
3116
  this._cachedKdf = res.kdf;
2993
3117
  this._cachedIter = res.iter;
2994
3118
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3119
+ this._cachedKeyId = getSafeKeyIdentifier(await this.resolveRawKeyAsync(options?.key));
2995
3120
  }
2996
3121
  }
2997
3122
  /**
@@ -3005,6 +3130,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3005
3130
  this._cachedKdf = res.kdf;
3006
3131
  this._cachedIter = res.iter;
3007
3132
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3133
+ this._cachedKeyId = getSafeKeyIdentifier(this.resolveRawKeySync(options?.key));
3008
3134
  }
3009
3135
  }
3010
3136
  resolveInfoBuffer(infoRaw) {
@@ -3091,12 +3217,14 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3091
3217
  }
3092
3218
  deriveKeySync(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
3093
3219
  const raw = this.resolveRawKeySync(keyProvider);
3220
+ const currentKeyId = getSafeKeyIdentifier(raw);
3094
3221
  if (Buffer.isBuffer(raw)) {
3095
3222
  if (raw.length === 32) {
3096
3223
  if (!keyProvider) {
3097
- if (!this._cachedKey) {
3224
+ if (!this._cachedKey || this._cachedKeyId !== currentKeyId) {
3098
3225
  this._cachedKey = Buffer.from(raw);
3099
3226
  this._cachedKdf = "raw";
3227
+ this._cachedKeyId = currentKeyId;
3100
3228
  }
3101
3229
  return { key: this._cachedKey, kdf: "raw" };
3102
3230
  }
@@ -3114,8 +3242,10 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3114
3242
  const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
3115
3243
  const matchesKdf = this._cachedKdf !== void 0 && kdf === this._cachedKdf.toLowerCase();
3116
3244
  const matchesSalt = !saltOverride || this._cachedSalt !== void 0 && saltOverride === this._cachedSalt;
3117
- if (!keyProvider && this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3118
- return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3245
+ if (this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3246
+ if (this._cachedKeyId === currentKeyId) {
3247
+ return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3248
+ }
3119
3249
  }
3120
3250
  if (kdf === "pbkdf2") {
3121
3251
  const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
@@ -3131,6 +3261,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3131
3261
  this._cachedKdf = "PBKDF2";
3132
3262
  this._cachedIter = iterations;
3133
3263
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3264
+ this._cachedKeyId = currentKeyId;
3134
3265
  }
3135
3266
  return {
3136
3267
  key: key2,
@@ -3156,6 +3287,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3156
3287
  this._cachedSalt = saltBuf.toString("base64");
3157
3288
  this._cachedKdf = "HKDF";
3158
3289
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3290
+ this._cachedKeyId = currentKeyId;
3159
3291
  }
3160
3292
  return {
3161
3293
  key: key2,
@@ -3168,24 +3300,27 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3168
3300
  "[CNodeCryptoEncryptionProvider] WARNING: Decrypting a legacy envelope with no KDF (raw SHA-256 key derivation). This is cryptographically weak. Migrate to pbkdf2 or hkdf."
3169
3301
  );
3170
3302
  }
3171
- if (!keyProvider && this._cachedKey && this._cachedKdf === "none") {
3303
+ if (!keyProvider && this._cachedKey && this._cachedKdf === "none" && this._cachedKeyId === currentKeyId) {
3172
3304
  return { key: this._cachedKey, kdf: "none" };
3173
3305
  }
3174
3306
  const key = crypto__namespace.createHash("sha256").update(passphrase, "utf8").digest();
3175
3307
  if (!keyProvider) {
3176
3308
  this._cachedKey = key;
3177
3309
  this._cachedKdf = "none";
3310
+ this._cachedKeyId = currentKeyId;
3178
3311
  }
3179
3312
  return { key, kdf: "none" };
3180
3313
  }
3181
3314
  async deriveKeyAsync(keyProvider, kdfOverride, saltOverride, options, iterationsOverride) {
3182
3315
  const raw = await this.resolveRawKeyAsync(keyProvider);
3316
+ const currentKeyId = getSafeKeyIdentifier(raw);
3183
3317
  if (Buffer.isBuffer(raw)) {
3184
3318
  if (raw.length === 32) {
3185
3319
  if (!keyProvider) {
3186
- if (!this._cachedKey) {
3320
+ if (!this._cachedKey || this._cachedKeyId !== currentKeyId) {
3187
3321
  this._cachedKey = Buffer.from(raw);
3188
3322
  this._cachedKdf = "raw";
3323
+ this._cachedKeyId = currentKeyId;
3189
3324
  }
3190
3325
  return { key: this._cachedKey, kdf: "raw" };
3191
3326
  }
@@ -3203,8 +3338,10 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3203
3338
  const matchesHash = !targetHash || this._cachedHash !== void 0 && targetHash.toLowerCase() === this._cachedHash.toLowerCase();
3204
3339
  const matchesKdf = this._cachedKdf !== void 0 && kdf === this._cachedKdf.toLowerCase();
3205
3340
  const matchesSalt = !saltOverride || this._cachedSalt !== void 0 && saltOverride === this._cachedSalt;
3206
- if (!keyProvider && this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3207
- return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3341
+ if (this._cachedKey && matchesSalt && !options?.kdfSalt && matchesKdf && matchesIter && matchesHash) {
3342
+ if (this._cachedKeyId === currentKeyId) {
3343
+ return { key: this._cachedKey, salt: this._cachedSalt, kdf: this._cachedKdf, iter: this._cachedIter };
3344
+ }
3208
3345
  }
3209
3346
  if (kdf === "pbkdf2") {
3210
3347
  const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
@@ -3225,6 +3362,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3225
3362
  this._cachedKdf = "PBKDF2";
3226
3363
  this._cachedIter = iterations;
3227
3364
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3365
+ this._cachedKeyId = currentKeyId;
3228
3366
  }
3229
3367
  return {
3230
3368
  key: key2,
@@ -3255,6 +3393,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3255
3393
  this._cachedSalt = saltBuf.toString("base64");
3256
3394
  this._cachedKdf = "HKDF";
3257
3395
  this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-256";
3396
+ this._cachedKeyId = currentKeyId;
3258
3397
  }
3259
3398
  return {
3260
3399
  key: key2,
@@ -3267,13 +3406,14 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3267
3406
  "[CNodeCryptoEncryptionProvider] WARNING: Decrypting a legacy envelope with no KDF (raw SHA-256 key derivation). This is cryptographically weak. Migrate to pbkdf2 or hkdf."
3268
3407
  );
3269
3408
  }
3270
- if (!keyProvider && this._cachedKey && this._cachedKdf === "none") {
3409
+ if (!keyProvider && this._cachedKey && this._cachedKdf === "none" && this._cachedKeyId === currentKeyId) {
3271
3410
  return { key: this._cachedKey, kdf: "none" };
3272
3411
  }
3273
3412
  const key = crypto__namespace.createHash("sha256").update(passphrase, "utf8").digest();
3274
3413
  if (!keyProvider) {
3275
3414
  this._cachedKey = key;
3276
3415
  this._cachedKdf = "none";
3416
+ this._cachedKeyId = currentKeyId;
3277
3417
  }
3278
3418
  return { key, kdf: "none" };
3279
3419
  }
@@ -3300,7 +3440,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3300
3440
  const jsonString = JSON.stringify(data);
3301
3441
  const iv = crypto__namespace.randomBytes(12);
3302
3442
  const cipher = crypto__namespace.createCipheriv("aes-256-gcm", key, iv);
3303
- const aad = options?.aad;
3443
+ const aad = this._resolveEffectiveAad(options, false);
3304
3444
  let hasAad = false;
3305
3445
  if (aad) {
3306
3446
  const aadBuffer = Buffer.isBuffer(aad) ? aad : Buffer.from(typeof aad === "string" ? aad : new Uint8Array(aad));
@@ -3353,21 +3493,41 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3353
3493
  }
3354
3494
  const decipher = crypto__namespace.createDecipheriv("aes-256-gcm", key, iv, { authTagLength: 16 });
3355
3495
  decipher.setAuthTag(authTag);
3356
- const aad = options?.aad;
3496
+ const aad = this._resolveEffectiveAad(options, true);
3497
+ let hasAad = false;
3357
3498
  if (payload.aad || aad) {
3358
3499
  if (aad) {
3359
3500
  const aadBuffer = Buffer.isBuffer(aad) ? aad : Buffer.from(typeof aad === "string" ? aad : new Uint8Array(aad));
3360
3501
  if (aadBuffer.length > 0) {
3361
3502
  decipher.setAAD(aadBuffer);
3503
+ hasAad = true;
3362
3504
  }
3363
3505
  } else if (payload.aad) {
3364
3506
  throw new Error("[CNodeCryptoEncryptionProvider] Payload requires Authenticated Additional Data (AAD) for decryption, but none was provided.");
3365
3507
  }
3366
3508
  }
3367
- const decrypted = Buffer.concat([
3368
- decipher.update(ciphertext),
3369
- decipher.final()
3370
- ]);
3509
+ let decrypted;
3510
+ try {
3511
+ decrypted = Buffer.concat([
3512
+ decipher.update(ciphertext),
3513
+ decipher.final()
3514
+ ]);
3515
+ } catch (firstErr) {
3516
+ if (!payload.aad && hasAad) {
3517
+ try {
3518
+ const fallbackDecipher = crypto__namespace.createDecipheriv("aes-256-gcm", key, iv, { authTagLength: 16 });
3519
+ fallbackDecipher.setAuthTag(authTag);
3520
+ decrypted = Buffer.concat([
3521
+ fallbackDecipher.update(ciphertext),
3522
+ fallbackDecipher.final()
3523
+ ]);
3524
+ } catch {
3525
+ throw firstErr;
3526
+ }
3527
+ } else {
3528
+ throw firstErr;
3529
+ }
3530
+ }
3371
3531
  try {
3372
3532
  const jsonString = decrypted.toString("utf8");
3373
3533
  return JSON.parse(jsonString);
@@ -3420,7 +3580,8 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3420
3580
  if (fieldsToEncrypt.length === 0) return { ...data };
3421
3581
  const result = { ...data };
3422
3582
  for (const field of fieldsToEncrypt) {
3423
- safeSetProperty(result, field, this.encryptValueSync(result[field], options));
3583
+ const fieldOptions = this._bindFieldAad(data, field, options);
3584
+ safeSetProperty(result, field, this.encryptValueSync(result[field], fieldOptions));
3424
3585
  }
3425
3586
  return result;
3426
3587
  }
@@ -3428,7 +3589,8 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3428
3589
  const result = { ...data };
3429
3590
  for (const key of Object.keys(result)) {
3430
3591
  if (result[key] !== void 0 && result[key] !== null && !this.isEncrypted(result[key])) {
3431
- safeSetProperty(result, key, this.encryptValueSync(result[key], options));
3592
+ const fieldOptions = this._bindFieldAad(data, key, options);
3593
+ safeSetProperty(result, key, this.encryptValueSync(result[key], fieldOptions));
3432
3594
  }
3433
3595
  }
3434
3596
  return result;
@@ -3467,7 +3629,21 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3467
3629
  derivedKey = derived.key;
3468
3630
  keyCache.set(salt, derivedKey);
3469
3631
  }
3470
- safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3632
+ const boundOptions = this._bindFieldAad(payload, key, options);
3633
+ const hasBoundAad = boundOptions.aad !== options?.aad;
3634
+ try {
3635
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, boundOptions));
3636
+ } catch (err) {
3637
+ if (hasBoundAad && isAuthOrDecryptionError(err)) {
3638
+ try {
3639
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3640
+ } catch (fallbackErr) {
3641
+ throw fallbackErr;
3642
+ }
3643
+ } else {
3644
+ throw err;
3645
+ }
3646
+ }
3471
3647
  mutated = true;
3472
3648
  }
3473
3649
  }
@@ -3507,7 +3683,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3507
3683
  const jsonString = JSON.stringify(data);
3508
3684
  const iv = crypto__namespace.randomBytes(12);
3509
3685
  const cipher = crypto__namespace.createCipheriv("aes-256-gcm", key, iv);
3510
- const aad = options?.aad;
3686
+ const aad = this._resolveEffectiveAad(options, false);
3511
3687
  let hasAad = false;
3512
3688
  if (aad) {
3513
3689
  const aadBuffer = Buffer.isBuffer(aad) ? aad : Buffer.from(typeof aad === "string" ? aad : new Uint8Array(aad));
@@ -3595,7 +3771,21 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
3595
3771
  derivedKey = derived.key;
3596
3772
  keyCache.set(salt, derivedKey);
3597
3773
  }
3598
- safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3774
+ const boundOptions = this._bindFieldAad(payload, key, options);
3775
+ const hasBoundAad = boundOptions.aad !== options?.aad;
3776
+ try {
3777
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, boundOptions));
3778
+ } catch (err) {
3779
+ if (hasBoundAad && isAuthOrDecryptionError(err)) {
3780
+ try {
3781
+ safeSetProperty(result, key, this.decryptCiphertextWithKey(fieldPayload, derivedKey, options));
3782
+ } catch (fallbackErr) {
3783
+ throw fallbackErr;
3784
+ }
3785
+ } else {
3786
+ throw err;
3787
+ }
3788
+ }
3599
3789
  mutated = true;
3600
3790
  }
3601
3791
  }
@@ -5338,6 +5528,48 @@ function generateId() {
5338
5528
  }
5339
5529
  return Date.now().toString(36) + Math.random().toString(36).slice(2);
5340
5530
  }
5531
+ function uint8ArrayToBase64(bytes) {
5532
+ if (typeof Buffer !== "undefined") {
5533
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
5534
+ }
5535
+ let binary = "";
5536
+ const chunkSize = 8192;
5537
+ for (let i = 0; i < bytes.byteLength; i += chunkSize) {
5538
+ const chunk = bytes.subarray(i, i + chunkSize);
5539
+ binary += String.fromCharCode.apply(null, chunk);
5540
+ }
5541
+ return btoa(binary);
5542
+ }
5543
+ function base64ToUint8Array(base64) {
5544
+ if (typeof Buffer !== "undefined") {
5545
+ const buf = Buffer.from(base64, "base64");
5546
+ return new Uint8Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));
5547
+ }
5548
+ const binary = atob(base64);
5549
+ const bytes = new Uint8Array(binary.length);
5550
+ for (let i = 0; i < binary.length; i++) {
5551
+ bytes[i] = binary.charCodeAt(i);
5552
+ }
5553
+ return bytes;
5554
+ }
5555
+ async function readBlobAsUint8Array(blob) {
5556
+ if (typeof blob.arrayBuffer === "function") {
5557
+ const buffer = await blob.arrayBuffer();
5558
+ return new Uint8Array(buffer);
5559
+ }
5560
+ if (typeof FileReader !== "undefined") {
5561
+ return new Promise((resolve, reject) => {
5562
+ const reader = new FileReader();
5563
+ reader.onload = () => {
5564
+ const buffer = reader.result;
5565
+ resolve(new Uint8Array(buffer));
5566
+ };
5567
+ reader.onerror = () => reject(reader.error);
5568
+ reader.readAsArrayBuffer(blob);
5569
+ });
5570
+ }
5571
+ throw new Error("[RequestQueue] Blob binary extraction is not supported in this environment");
5572
+ }
5341
5573
  const SENSITIVE_HEADER_KEYS = ["authorization", "cookie", "set-cookie", "x-csrf-token"];
5342
5574
  class RequestQueue {
5343
5575
  // ── State ──────────────────────────────────────────────────────────────────
@@ -5364,11 +5596,187 @@ class RequestQueue {
5364
5596
  * Sensitive credentials must never be stored in plaintext in browser storage, and are
5365
5597
  * instead regenerated dynamically at execution time.
5366
5598
  */
5367
- static sanitizeOptions(options) {
5599
+ /**
5600
+ * Adapts binary, multipart, and specialized payload types (FormData, Blob, File,
5601
+ * ArrayBuffer, TypedArrays, URLSearchParams) into JSON-serializable structures
5602
+ * to prevent silent payload loss (BUG-014) when persisting to offline storage.
5603
+ */
5604
+ static async serializeBody(body) {
5605
+ if (body === void 0 || body === null) {
5606
+ return body;
5607
+ }
5608
+ const isFormData = typeof FormData !== "undefined" && (body instanceof FormData || Object.prototype.toString.call(body) === "[object FormData]");
5609
+ if (isFormData) {
5610
+ const entries = [];
5611
+ if (typeof body.entries === "function") {
5612
+ for (const [key, val] of body.entries()) {
5613
+ entries.push([key, await RequestQueue.serializeFieldValue(val)]);
5614
+ }
5615
+ } else if (typeof body.forEach === "function") {
5616
+ const raw = [];
5617
+ body.forEach((val, key) => {
5618
+ raw.push([key, val]);
5619
+ });
5620
+ for (const [key, val] of raw) {
5621
+ entries.push([key, await RequestQueue.serializeFieldValue(val)]);
5622
+ }
5623
+ }
5624
+ return {
5625
+ __katlux_type: "FormData",
5626
+ entries
5627
+ };
5628
+ }
5629
+ const isFile = typeof File !== "undefined" && (body instanceof File || Object.prototype.toString.call(body) === "[object File]");
5630
+ if (isFile) {
5631
+ const bytes = await readBlobAsUint8Array(body);
5632
+ return {
5633
+ __katlux_type: "File",
5634
+ name: body.name,
5635
+ type: body.type || "application/octet-stream",
5636
+ lastModified: body.lastModified,
5637
+ data: uint8ArrayToBase64(bytes)
5638
+ };
5639
+ }
5640
+ const isBlob = typeof Blob !== "undefined" && (body instanceof Blob || Object.prototype.toString.call(body) === "[object Blob]");
5641
+ if (isBlob) {
5642
+ const bytes = await readBlobAsUint8Array(body);
5643
+ return {
5644
+ __katlux_type: "Blob",
5645
+ type: body.type || "application/octet-stream",
5646
+ data: uint8ArrayToBase64(bytes)
5647
+ };
5648
+ }
5649
+ const isArrayBuffer = typeof ArrayBuffer !== "undefined" && (body instanceof ArrayBuffer || Object.prototype.toString.call(body) === "[object ArrayBuffer]");
5650
+ if (isArrayBuffer) {
5651
+ const bytes = new Uint8Array(body);
5652
+ return {
5653
+ __katlux_type: "ArrayBuffer",
5654
+ data: uint8ArrayToBase64(bytes)
5655
+ };
5656
+ }
5657
+ if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(body)) {
5658
+ const view = body;
5659
+ const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
5660
+ return {
5661
+ __katlux_type: "Uint8Array",
5662
+ data: uint8ArrayToBase64(bytes)
5663
+ };
5664
+ }
5665
+ const isURLSearchParams = typeof URLSearchParams !== "undefined" && (body instanceof URLSearchParams || Object.prototype.toString.call(body) === "[object URLSearchParams]");
5666
+ if (isURLSearchParams) {
5667
+ return {
5668
+ __katlux_type: "URLSearchParams",
5669
+ data: body.toString()
5670
+ };
5671
+ }
5672
+ return body;
5673
+ }
5674
+ static async serializeFieldValue(val) {
5675
+ if (typeof File !== "undefined" && (val instanceof File || Object.prototype.toString.call(val) === "[object File]")) {
5676
+ const bytes = await readBlobAsUint8Array(val);
5677
+ return {
5678
+ __katlux_type: "File",
5679
+ name: val.name,
5680
+ type: val.type || "application/octet-stream",
5681
+ lastModified: val.lastModified,
5682
+ data: uint8ArrayToBase64(bytes)
5683
+ };
5684
+ }
5685
+ if (typeof Blob !== "undefined" && (val instanceof Blob || Object.prototype.toString.call(val) === "[object Blob]")) {
5686
+ const bytes = await readBlobAsUint8Array(val);
5687
+ return {
5688
+ __katlux_type: "Blob",
5689
+ type: val.type || "application/octet-stream",
5690
+ data: uint8ArrayToBase64(bytes)
5691
+ };
5692
+ }
5693
+ return typeof val === "string" ? val : String(val);
5694
+ }
5695
+ /**
5696
+ * Reconstitutes serialized offline request bodies back into their live runtime instances
5697
+ * (FormData, Blob, File, ArrayBuffer, Uint8Array, URLSearchParams) before network transmission.
5698
+ */
5699
+ static reconstituteBody(body) {
5700
+ if (!body || typeof body !== "object") {
5701
+ return body;
5702
+ }
5703
+ if (body.__katlux_type === "FormData" && Array.isArray(body.entries)) {
5704
+ if (typeof FormData === "undefined") return body;
5705
+ const fd = new FormData();
5706
+ for (const [key, val] of body.entries) {
5707
+ if (val && typeof val === "object" && val.__katlux_type === "File") {
5708
+ const u8 = base64ToUint8Array(val.data);
5709
+ if (typeof File !== "undefined") {
5710
+ const file = new File([u8], val.name, {
5711
+ type: val.type || "application/octet-stream",
5712
+ lastModified: val.lastModified
5713
+ });
5714
+ fd.append(key, file, val.name);
5715
+ } else if (typeof Blob !== "undefined") {
5716
+ const blob = new Blob([u8], { type: val.type || "application/octet-stream" });
5717
+ fd.append(key, blob, val.name);
5718
+ }
5719
+ } else if (val && typeof val === "object" && val.__katlux_type === "Blob") {
5720
+ if (typeof Blob !== "undefined") {
5721
+ const u8 = base64ToUint8Array(val.data);
5722
+ const blob = new Blob([u8], { type: val.type || "application/octet-stream" });
5723
+ fd.append(key, blob);
5724
+ }
5725
+ } else {
5726
+ fd.append(key, val);
5727
+ }
5728
+ }
5729
+ return fd;
5730
+ }
5731
+ if (body.__katlux_type === "File") {
5732
+ const u8 = base64ToUint8Array(body.data);
5733
+ if (typeof File !== "undefined") {
5734
+ return new File([u8], body.name, {
5735
+ type: body.type || "application/octet-stream",
5736
+ lastModified: body.lastModified
5737
+ });
5738
+ }
5739
+ if (typeof Blob !== "undefined") {
5740
+ return new Blob([u8], { type: body.type || "application/octet-stream" });
5741
+ }
5742
+ return u8;
5743
+ }
5744
+ if (body.__katlux_type === "Blob") {
5745
+ const u8 = base64ToUint8Array(body.data);
5746
+ if (typeof Blob !== "undefined") {
5747
+ return new Blob([u8], { type: body.type || "application/octet-stream" });
5748
+ }
5749
+ return u8;
5750
+ }
5751
+ if (body.__katlux_type === "ArrayBuffer") {
5752
+ const u8 = base64ToUint8Array(body.data);
5753
+ return u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength);
5754
+ }
5755
+ if (body.__katlux_type === "Uint8Array") {
5756
+ return base64ToUint8Array(body.data);
5757
+ }
5758
+ if (body.__katlux_type === "URLSearchParams") {
5759
+ if (typeof URLSearchParams !== "undefined") {
5760
+ return new URLSearchParams(body.data);
5761
+ }
5762
+ return body.data;
5763
+ }
5764
+ return body;
5765
+ }
5766
+ /**
5767
+ * Strips sensitive headers (e.g., authorization, cookie, x-csrf-token) before persisting
5768
+ * request options to persistent storage (IndexedDB / LocalStorage).
5769
+ * Sensitive credentials must never be stored in plaintext in browser storage, and are
5770
+ * instead regenerated dynamically at execution time.
5771
+ */
5772
+ static async sanitizeOptions(options) {
5368
5773
  if (!options) return {};
5369
5774
  const sanitized = {
5370
5775
  method: options.method
5371
5776
  };
5777
+ if (options.credentials) {
5778
+ sanitized.credentials = options.credentials;
5779
+ }
5372
5780
  if (options.headers) {
5373
5781
  const headersObj = {};
5374
5782
  const sensitiveSet = new Set(SENSITIVE_HEADER_KEYS.map((k) => k.toLowerCase()));
@@ -5402,7 +5810,8 @@ class RequestQueue {
5402
5810
  }
5403
5811
  if (options.body !== void 0) {
5404
5812
  try {
5405
- const serialized = JSON.stringify(options.body);
5813
+ const serializedBody = await this.serializeBody(options.body);
5814
+ const serialized = JSON.stringify(serializedBody);
5406
5815
  if (serialized && serialized.length > this.MAX_PAYLOAD_SIZE_BYTES) {
5407
5816
  throw new Error(
5408
5817
  `[RequestQueue] Payload size (${(serialized.length / (1024 * 1024)).toFixed(2)} MB) exceeds maximum allowed size (${(this.MAX_PAYLOAD_SIZE_BYTES / (1024 * 1024)).toFixed(2)} MB)`
@@ -5442,6 +5851,7 @@ class RequestQueue {
5442
5851
  static _onDeadLetter = null;
5443
5852
  static _onFlushComplete = null;
5444
5853
  static _onNetworkError = null;
5854
+ static _onError = null;
5445
5855
  static _headerProvider = null;
5446
5856
  static setHeaderProvider(provider) {
5447
5857
  this._headerProvider = provider;
@@ -5491,6 +5901,12 @@ class RequestQueue {
5491
5901
  static onNetworkError(cb) {
5492
5902
  this._onNetworkError = cb;
5493
5903
  }
5904
+ static onError(cb) {
5905
+ this._onError = cb;
5906
+ }
5907
+ static onQueueFatalError(cb) {
5908
+ this._onError = cb;
5909
+ }
5494
5910
  // ── Enqueue ───────────────────────────────────────────────────────────────
5495
5911
  /**
5496
5912
  * Add an operation to the pending queue and persist it.
@@ -5499,7 +5915,7 @@ class RequestQueue {
5499
5915
  */
5500
5916
  static async enqueue(operation) {
5501
5917
  await this.init();
5502
- const sanitizedOptions = this.sanitizeOptions(operation.options);
5918
+ const sanitizedOptions = await this.sanitizeOptions(operation.options);
5503
5919
  if (this.queue.length >= this.MAX_QUEUE_SIZE) {
5504
5920
  const evicted = this.queue[0];
5505
5921
  await this.moveToDeadLetter(evicted, new Error("Queue capacity exceeded"));
@@ -5562,11 +5978,24 @@ class RequestQueue {
5562
5978
  this.notify();
5563
5979
  this._onNetworkError?.(item);
5564
5980
  } else {
5565
- await this.moveToDeadLetter(item, error, httpStatus);
5981
+ try {
5982
+ await this.moveToDeadLetter(item, error, httpStatus);
5983
+ } catch (dlErr) {
5984
+ await this.persistQueue().catch(() => {
5985
+ });
5986
+ this.notify();
5987
+ const fatalError = dlErr instanceof Error ? dlErr : new Error(String(dlErr));
5988
+ console.error("[RequestQueue] Fatal capacity error moving to dead-letter:", fatalError);
5989
+ this._onError?.(fatalError);
5990
+ }
5566
5991
  }
5567
5992
  break;
5568
5993
  }
5569
5994
  }
5995
+ } catch (topErr) {
5996
+ const fatalError = topErr instanceof Error ? topErr : new Error(String(topErr));
5997
+ console.error("[RequestQueue] flushAll fatal error:", fatalError);
5998
+ this._onError?.(fatalError);
5570
5999
  } finally {
5571
6000
  this.isFlushing = false;
5572
6001
  this.notify();
@@ -5610,7 +6039,16 @@ class RequestQueue {
5610
6039
  this.notify();
5611
6040
  this._onNetworkError?.(item);
5612
6041
  } else {
5613
- await this.moveToDeadLetter(item, error, httpStatus);
6042
+ try {
6043
+ await this.moveToDeadLetter(item, error, httpStatus);
6044
+ } catch (dlErr) {
6045
+ await this.persistQueue().catch(() => {
6046
+ });
6047
+ this.notify();
6048
+ const fatalError = dlErr instanceof Error ? dlErr : new Error(String(dlErr));
6049
+ console.error("[RequestQueue] Fatal capacity error moving to dead-letter:", fatalError);
6050
+ this._onError?.(fatalError);
6051
+ }
5614
6052
  }
5615
6053
  }
5616
6054
  }
@@ -5684,24 +6122,30 @@ class RequestQueue {
5684
6122
  console.error("[RequestQueue] Header provider failed:", err);
5685
6123
  }
5686
6124
  }
5687
- if (typeof document !== "undefined" && document.cookie && !headers["cookie"] && !headers["Cookie"]) {
5688
- headers["cookie"] = document.cookie;
5689
- }
5690
6125
  return headers;
5691
6126
  }
5692
6127
  static async executeRequest(item) {
5693
6128
  const { url, options } = item;
5694
6129
  const headers = await this.regenerateHeaders(options.headers);
6130
+ const body = this.reconstituteBody(options.body);
6131
+ if (typeof FormData !== "undefined" && (body instanceof FormData || Object.prototype.toString.call(body) === "[object FormData]")) {
6132
+ delete headers["content-type"];
6133
+ delete headers["Content-Type"];
6134
+ }
5695
6135
  const fetchOptions = {
5696
6136
  method: item.method,
5697
- body: options.body,
6137
+ body,
5698
6138
  headers,
5699
- query: options.query
6139
+ query: options.query,
6140
+ credentials: options.credentials || "include"
5700
6141
  };
5701
6142
  const fetchFn = globalThis.$fetch || ofetch.$fetch;
5702
6143
  await fetchFn(url, fetchOptions);
5703
6144
  }
5704
6145
  static async moveToDeadLetter(item, error, httpStatus) {
6146
+ if (this.deadLetterQueue.length >= this.MAX_DEAD_LETTER_SIZE) {
6147
+ throw new Error(`[RequestQueue] Dead-letter queue reached capacity (${this.MAX_DEAD_LETTER_SIZE}). Please clear the queue manually before proceeding to prevent data loss.`);
6148
+ }
5705
6149
  const deadItem = {
5706
6150
  ...item,
5707
6151
  failedAt: Date.now(),
@@ -5709,11 +6153,6 @@ class RequestQueue {
5709
6153
  httpStatus
5710
6154
  };
5711
6155
  this.queue = this.queue.filter((i) => i.id !== item.id);
5712
- if (this.deadLetterQueue.length >= this.MAX_DEAD_LETTER_SIZE) {
5713
- const evicted = this.deadLetterQueue[0];
5714
- console.warn(`[RequestQueue] Dead-letter queue reached capacity (${this.MAX_DEAD_LETTER_SIZE}). Evicting oldest item: ${evicted?.id}`);
5715
- this.deadLetterQueue = this.deadLetterQueue.slice(1);
5716
- }
5717
6156
  this.deadLetterQueue = [...this.deadLetterQueue, deadItem];
5718
6157
  await this.persistQueue();
5719
6158
  await this.persistDeadLetter();
@@ -5735,6 +6174,7 @@ class RequestQueue {
5735
6174
  this._onDeadLetter = null;
5736
6175
  this._onFlushComplete = null;
5737
6176
  this._onNetworkError = null;
6177
+ this._onError = null;
5738
6178
  this._headerProvider = null;
5739
6179
  this.MAX_PAYLOAD_SIZE_BYTES = 5 * 1024 * 1024;
5740
6180
  this.MAX_QUEUE_SIZE = 500;
@@ -6164,6 +6604,8 @@ class RequestProvider {
6164
6604
  url,
6165
6605
  method,
6166
6606
  isServer,
6607
+ aad: encOptions.aad,
6608
+ bindRequestContextAad: encOptions.bindRequestContextAad,
6167
6609
  key: encOptions.key,
6168
6610
  valueEncryption: encOptions.valueEncryption,
6169
6611
  fields: encOptions.fields,
@@ -8089,13 +8531,41 @@ class CCookieCache extends ACacheProvider {
8089
8531
  return this.instance;
8090
8532
  }
8091
8533
  type = "Cookie";
8534
+ sameSite = "lax";
8535
+ secure = void 0;
8536
+ httpOnly = true;
8537
+ path = "/";
8092
8538
  // Exposed constructor for testing & instantiation
8093
- constructor() {
8539
+ constructor(options) {
8094
8540
  super();
8541
+ if (options) {
8542
+ this.configure(options);
8543
+ }
8544
+ }
8545
+ configure(options) {
8546
+ if (options.sameSite !== void 0) this.sameSite = options.sameSite;
8547
+ if (options.secure !== void 0) this.secure = options.secure;
8548
+ if (options.httpOnly !== void 0) this.httpOnly = options.httpOnly;
8549
+ if (options.path !== void 0) this.path = options.path;
8095
8550
  }
8096
8551
  getCookieKey(key) {
8097
8552
  return "cache:" + encodeURIComponent(key);
8098
8553
  }
8554
+ /**
8555
+ * Resolves the `Secure` flag: an explicit option wins, otherwise follow the
8556
+ * actual protocol so cookies are not silently dropped by browsers over plain HTTP.
8557
+ */
8558
+ resolveSecure(getRequestProtocol, event) {
8559
+ if (this.secure !== void 0) return this.secure;
8560
+ if (event && getRequestProtocol) {
8561
+ try {
8562
+ return getRequestProtocol(event) === "https";
8563
+ } catch {
8564
+ return false;
8565
+ }
8566
+ }
8567
+ return typeof location !== "undefined" && location.protocol === "https:";
8568
+ }
8099
8569
  parseKeyFromCookieName(cookieName) {
8100
8570
  const prefix = "cache:";
8101
8571
  const decoded = decodeURIComponent(cookieName);
@@ -8201,20 +8671,23 @@ class CCookieCache extends ACacheProvider {
8201
8671
  return;
8202
8672
  }
8203
8673
  const maxAge = Math.floor(lifetime / 1e3);
8674
+ const sameSiteFormatted = this.sameSite.charAt(0).toUpperCase() + this.sameSite.slice(1).toLowerCase();
8204
8675
  if (this.isClient(context)) {
8205
8676
  if (typeof document !== "undefined") {
8206
- document.cookie = `${cookieKey}=${cookieValue}; Max-Age=${maxAge}; Path=/; SameSite=Lax`;
8677
+ const secureFlag = this.resolveSecure() ? "; Secure" : "";
8678
+ document.cookie = `${cookieKey}=${cookieValue}; Max-Age=${maxAge}; Path=${this.path}; SameSite=${sameSiteFormatted}${secureFlag}`;
8207
8679
  }
8208
8680
  } else if (context) {
8209
8681
  const event = context?.event ?? context?.ssrContext?.event ?? (context?.node ? context : null);
8210
8682
  if (event) {
8211
8683
  try {
8212
- const { setCookie } = await getH3();
8684
+ const { setCookie, getRequestProtocol } = await getH3();
8213
8685
  setCookie(event, cookieKey, serialized, {
8214
8686
  maxAge,
8215
- path: "/",
8216
- sameSite: "lax",
8217
- httpOnly: true
8687
+ path: this.path,
8688
+ sameSite: this.sameSite,
8689
+ httpOnly: this.httpOnly,
8690
+ secure: this.resolveSecure(getRequestProtocol, event)
8218
8691
  });
8219
8692
  } catch {
8220
8693
  }
@@ -8223,16 +8696,18 @@ class CCookieCache extends ACacheProvider {
8223
8696
  }
8224
8697
  async remove(key, context) {
8225
8698
  const cookieKey = this.getCookieKey(key);
8699
+ const sameSiteFormatted = this.sameSite.charAt(0).toUpperCase() + this.sameSite.slice(1).toLowerCase();
8226
8700
  if (this.isClient(context)) {
8227
8701
  if (typeof document !== "undefined") {
8228
- document.cookie = `${cookieKey}=; Max-Age=0; Path=/; SameSite=Lax`;
8702
+ const secureFlag = this.resolveSecure() ? "; Secure" : "";
8703
+ document.cookie = `${cookieKey}=; Max-Age=0; Path=${this.path}; SameSite=${sameSiteFormatted}${secureFlag}`;
8229
8704
  }
8230
8705
  } else if (context) {
8231
8706
  const event = context?.event ?? context?.ssrContext?.event ?? (context?.node ? context : null);
8232
8707
  if (event) {
8233
8708
  try {
8234
- const { deleteCookie } = await getH3();
8235
- deleteCookie(event, cookieKey, { path: "/", sameSite: "lax", httpOnly: true });
8709
+ const { deleteCookie, getRequestProtocol } = await getH3();
8710
+ deleteCookie(event, cookieKey, { path: this.path, sameSite: this.sameSite, httpOnly: this.httpOnly, secure: this.resolveSecure(getRequestProtocol, event) });
8236
8711
  } catch {
8237
8712
  }
8238
8713
  }
@@ -8486,7 +8961,11 @@ class CServerSessionCache extends ACacheProvider {
8486
8961
  CServerSessionCache._opCounter = 0;
8487
8962
  CServerSessionCache.purgeExpiredServerSessions(50);
8488
8963
  } else if (CServerSessionCache.storage.size >= CServerSessionCache.MAX_SERVER_SESSIONS) {
8489
- CServerSessionCache.purgeExpiredServerSessions();
8964
+ CServerSessionCache.purgeExpiredServerSessions(50);
8965
+ if (CServerSessionCache.storage.size >= CServerSessionCache.MAX_SERVER_SESSIONS) {
8966
+ const oldestKey = CServerSessionCache.storage.keys().next().value;
8967
+ if (oldestKey !== void 0) CServerSessionCache.storage.delete(oldestKey);
8968
+ }
8490
8969
  }
8491
8970
  let sessionData = CServerSessionCache.storage.get(sessionId);
8492
8971
  if (sessionData) {
@@ -9538,6 +10017,7 @@ exports.getSSRData = getSSRData;
9538
10017
  exports.getSSRPayload = getSSRPayload;
9539
10018
  exports.getSafeKeyIdentifier = getSafeKeyIdentifier;
9540
10019
  exports.getSubtleCrypto = getSubtleCrypto;
10020
+ exports.isAuthOrDecryptionError = isAuthOrDecryptionError;
9541
10021
  exports.isDataEncrypted = isDataEncrypted;
9542
10022
  exports.isEncrypted = isEncrypted;
9543
10023
  exports.normalizeIndexTerm = normalizeIndexTerm;