tricache 1.0.1 → 2.0.0

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.
Files changed (127) hide show
  1. package/README.md +89 -93
  2. package/dashboards/tricache-alerts.yaml +80 -4
  3. package/dashboards/tricache-grafana.json +54 -1
  4. package/dashboards/tricache-inventory.rules.yml +21 -0
  5. package/dist/cache-service-BV5T8-20.d.cts +1064 -0
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-tpyrXvlH.d.ts} +157 -24
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  10. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  11. package/dist/{chunk-2AJKEQMZ.js → chunk-KV7KISK2.js} +54 -5
  12. package/dist/{chunk-JYQFQJNJ.js → chunk-MB3DMVWN.js} +3424 -1022
  13. package/dist/chunk-RBJRTGFK.js +94 -0
  14. package/dist/chunk-S5N65I45.js +17 -0
  15. package/dist/cli.cjs +3694 -1070
  16. package/dist/cli.d.cts +12 -0
  17. package/dist/cli.js +210 -14
  18. package/dist/dashboard/index.cjs +111 -29
  19. package/dist/dashboard/index.d.cts +185 -0
  20. package/dist/dashboard/index.d.ts +5 -3
  21. package/dist/dashboard/index.js +1 -1
  22. package/dist/drizzle/index.cjs +3578 -1068
  23. package/dist/drizzle/index.d.cts +46 -0
  24. package/dist/drizzle/index.d.ts +2 -2
  25. package/dist/drizzle/index.js +6 -2
  26. package/dist/edge/index.cjs +368 -162
  27. package/dist/edge/index.d.cts +134 -0
  28. package/dist/edge/index.d.ts +11 -4
  29. package/dist/edge/index.js +314 -155
  30. package/dist/hono/index.cjs +3614 -1087
  31. package/dist/hono/index.d.cts +93 -0
  32. package/dist/hono/index.d.ts +7 -5
  33. package/dist/hono/index.js +16 -9
  34. package/dist/hono-CMv2VdQ6.d.cts +404 -0
  35. package/dist/{hono-DSV2ve66.d.ts → hono-Dvq04kX9.d.ts} +33 -7
  36. package/dist/http/index.cjs +3712 -1124
  37. package/dist/http/index.d.cts +103 -0
  38. package/dist/http/index.d.ts +13 -5
  39. package/dist/http/index.js +92 -43
  40. package/dist/index.cjs +4067 -1252
  41. package/dist/index.d.cts +1071 -0
  42. package/dist/index.d.ts +123 -27
  43. package/dist/index.js +878 -21
  44. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.cts} +1 -0
  45. package/dist/murmur3-DF8BFRnu.d.ts +99 -0
  46. package/dist/nestjs/index.cjs +3635 -1112
  47. package/dist/nestjs/index.d.cts +299 -0
  48. package/dist/nestjs/index.d.ts +120 -33
  49. package/dist/nestjs/index.js +132 -43
  50. package/dist/next/index.cjs +3704 -1175
  51. package/dist/next/index.d.cts +238 -0
  52. package/dist/next/index.d.ts +39 -11
  53. package/dist/next/index.js +202 -102
  54. package/dist/prisma/index.cjs +29 -18
  55. package/dist/prisma/index.d.cts +62 -0
  56. package/dist/prisma/index.d.ts +2 -2
  57. package/dist/prisma/index.js +17 -18
  58. package/dist/serialize-worker.cjs +162 -39
  59. package/dist/serialize-worker.d.cts +2 -0
  60. package/dist/serialize-worker.js +9 -7
  61. package/dist/{types-Dyip5wAl.d.ts → types-F8vRWMrE.d.cts} +186 -54
  62. package/dist/types-F8vRWMrE.d.ts +1636 -0
  63. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  64. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  65. package/package.json +116 -37
  66. package/src/adapters/auto-pipeliner.ts +150 -26
  67. package/src/adapters/node-redis.ts +106 -27
  68. package/src/cache-service.ts +2215 -793
  69. package/src/cli.ts +25 -14
  70. package/src/codec.ts +3 -3
  71. package/src/compression.ts +39 -16
  72. package/src/cross-region.ts +22 -4
  73. package/src/dashboard/handler.ts +26 -6
  74. package/src/dashboard/html.ts +35 -10
  75. package/src/dashboard/index.ts +35 -13
  76. package/src/dashboard/types.ts +3 -1
  77. package/src/disk-tier.ts +448 -102
  78. package/src/drizzle/index.ts +2 -1
  79. package/src/edge/adapters/cloudflare-do.ts +25 -10
  80. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  81. package/src/edge/adapters/upstash.ts +27 -11
  82. package/src/edge/cache.ts +200 -110
  83. package/src/edge/hono.ts +23 -6
  84. package/src/edge/types.ts +17 -5
  85. package/src/encryption.ts +50 -18
  86. package/src/env.d.ts +1 -1
  87. package/src/errors.ts +12 -0
  88. package/src/hono/index.ts +19 -9
  89. package/src/http/express.ts +62 -17
  90. package/src/http/fastify.ts +35 -21
  91. package/src/http/utils.ts +60 -20
  92. package/src/index.ts +6 -0
  93. package/src/ipc-telemetry.ts +35 -9
  94. package/src/latency-watchdog.ts +5 -1
  95. package/src/nestjs/decorators.ts +11 -6
  96. package/src/nestjs/index.ts +2 -0
  97. package/src/nestjs/keyv-adapter.ts +68 -0
  98. package/src/nestjs/tricache.module.ts +15 -12
  99. package/src/nestjs/tricache.store.ts +69 -26
  100. package/src/nestjs/types.ts +30 -16
  101. package/src/next/cache-handler.ts +151 -53
  102. package/src/next/index.ts +1 -0
  103. package/src/next/types.ts +25 -0
  104. package/src/origin-capacity.ts +134 -0
  105. package/src/prisma/index.ts +17 -24
  106. package/src/remote-snapshot.ts +37 -27
  107. package/src/serialize-worker.ts +8 -5
  108. package/src/sigv4-snapshot-adapter.ts +37 -27
  109. package/src/smart-memory-cache.ts +121 -44
  110. package/src/types.ts +117 -37
  111. package/src/utils/cgroup.ts +12 -0
  112. package/src/utils/config-comparison.ts +29 -0
  113. package/src/utils/deadline.ts +14 -0
  114. package/src/utils/diagnostics.ts +27 -0
  115. package/src/utils/lz4-size.ts +74 -0
  116. package/src/utils/namespace-key.ts +48 -0
  117. package/src/utils/query-key.ts +13 -0
  118. package/src/utils/redis-slot.ts +13 -0
  119. package/src/utils/snapshot-transfer.ts +83 -0
  120. package/src/utils/work-limits.ts +73 -0
  121. package/src/utils/write-revision.ts +4 -0
  122. package/src/wasm/bloom-filter-wasm.ts +25 -5
  123. package/src/worker-pool.ts +44 -15
  124. package/src/wtiny-lfu.ts +82 -20
  125. package/dist/cache-service-MG7PN6MX.js +0 -12
  126. package/dist/chunk-3I5L7K6I.js +0 -704
  127. package/dist/chunk-BQRURGGD.js +0 -60
@@ -29,9 +29,13 @@ var IV_BYTES = 12;
29
29
  var TAG_BYTES = 16;
30
30
  var PREFIX_256 = "enc:v1:";
31
31
  var PREFIX_128 = "a128:v1:";
32
+ var PREFIX_BOUND_256 = "enc:v2:";
33
+ var PREFIX_BOUND_128 = "a128:v2:";
32
34
  var PREFIX_XOR = "xor:v1:";
33
35
  var MAGIC_256 = Buffer.from([84, 82, 73, 67, 49, 69, 78, 67]);
34
36
  var MAGIC_128 = Buffer.from([84, 82, 73, 67, 49, 49, 50, 56]);
37
+ var MAGIC_BOUND_256 = Buffer.from("TRIC2ENC");
38
+ var MAGIC_BOUND_128 = Buffer.from("TRIC2128");
35
39
  var MAGIC_XOR = Buffer.from([84, 82, 73, 67, 49, 88, 79, 82]);
36
40
  var MAGIC_CTR = Buffer.from([84, 82, 73, 67, 49, 67, 84, 82]);
37
41
  var MAGIC_LEN = 8;
@@ -46,6 +50,7 @@ var CacheEncryption = class {
46
50
  _mode;
47
51
  /** Fail-closed on invalid key material when opted in via constructor opts. */
48
52
  _strictKeyValidation;
53
+ _allowLegacyPlaintextRead;
49
54
  _prevKey = null;
50
55
  _prevKeyObj = null;
51
56
  _prevMode = "aes-256-gcm";
@@ -115,6 +120,7 @@ var CacheEncryption = class {
115
120
  const logger = typeof loggerOrMode === "object" && loggerOrMode !== null ? loggerOrMode : consoleLogger;
116
121
  const resolvedMode = typeof loggerOrMode === "string" ? loggerOrMode : mode;
117
122
  this._strictKeyValidation = opts?.strictKeyValidation ?? false;
123
+ this._allowLegacyPlaintextRead = opts?.allowLegacyPlaintextRead ?? true;
118
124
  this._mode = resolvedMode;
119
125
  if (keyBase64 === void 0 || keyBase64 === null) {
120
126
  if (process.env.NODE_ENV === "production") {
@@ -201,7 +207,8 @@ var CacheEncryption = class {
201
207
  keyBase64: this._key ? this._key.toString("base64") : "",
202
208
  mode: this._mode,
203
209
  prevKeyBase64: this._prevKey ? this._prevKey.toString("base64") : void 0,
204
- prevMode: this._prevMode
210
+ prevMode: this._prevMode,
211
+ allowLegacyPlaintextRead: this._allowLegacyPlaintextRead
205
212
  };
206
213
  }
207
214
  /**
@@ -247,7 +254,7 @@ var CacheEncryption = class {
247
254
  * Returns a mode-prefixed base64 string when a key is configured;
248
255
  * otherwise returns the original string unchanged (backward-compatible).
249
256
  */
250
- encrypt(plaintext) {
257
+ encrypt(plaintext, context) {
251
258
  if (!this._key) return plaintext;
252
259
  if (this._mode === "xor") {
253
260
  const masked = this._xorBuffer(Buffer.from(plaintext, "utf8"));
@@ -265,9 +272,10 @@ var CacheEncryption = class {
265
272
  return PREFIX_CTR + out2.toString("base64");
266
273
  }
267
274
  const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
268
- const prefix = this._mode === "aes-128-gcm" ? PREFIX_128 : PREFIX_256;
275
+ const prefix = context === void 0 ? this._mode === "aes-128-gcm" ? PREFIX_128 : PREFIX_256 : this._mode === "aes-128-gcm" ? PREFIX_BOUND_128 : PREFIX_BOUND_256;
269
276
  const iv = this._nextIV();
270
277
  const c = createCipheriv(algo, this._keyObj, iv);
278
+ if (context !== void 0) c.setAAD(Buffer.from(context, "utf8"));
271
279
  const enc = c.update(plaintext, "utf8");
272
280
  c.final();
273
281
  const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
@@ -281,20 +289,30 @@ var CacheEncryption = class {
281
289
  * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
282
290
  * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
283
291
  */
284
- decrypt(value) {
292
+ assertReadPolicy(value, context) {
293
+ if (!this.isEnabled || this._allowLegacyPlaintextRead || !this._mode.endsWith("-gcm")) return;
294
+ if (context === void 0) throw new Error("Authenticated cache read requires context");
295
+ if (typeof value === "string") {
296
+ if (value.startsWith("ecp:v1:")) return this.assertReadPolicy(Buffer.from(value.slice(7), "base64"), context);
297
+ if (value.startsWith(PREFIX_BOUND_256) || value.startsWith(PREFIX_BOUND_128)) return;
298
+ } else if (value.subarray(0, 8).equals(MAGIC_BOUND_256) || value.subarray(0, 8).equals(MAGIC_BOUND_128)) return;
299
+ throw new Error("Legacy or plaintext cache value rejected; opt in to allowLegacyPlaintextRead for migration");
300
+ }
301
+ decrypt(value, context) {
302
+ this.assertReadPolicy(value, context);
285
303
  try {
286
- return this._decryptWithKey(value, this._key, this._keyObj);
304
+ return this._decryptWithKey(value, this._key, this._keyObj, context);
287
305
  } catch (primaryErr) {
288
306
  if (this._prevKey) {
289
307
  try {
290
- return this._decryptWithKey(value, this._prevKey, this._prevKeyObj);
308
+ return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, context);
291
309
  } catch {
292
310
  }
293
311
  }
294
312
  throw primaryErr;
295
313
  }
296
314
  }
297
- _decryptWithKey(value, key, keyObj) {
315
+ _decryptWithKey(value, key, keyObj, context) {
298
316
  if (value.startsWith(PREFIX_XOR)) {
299
317
  if (!key) throw new Error("Cannot decrypt: encryption key is not set");
300
318
  const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
@@ -314,17 +332,20 @@ var CacheEncryption = class {
314
332
  const fin = d2.final();
315
333
  return (fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2).toString("utf8");
316
334
  }
317
- const is256 = value.startsWith(PREFIX_256);
318
- const is128 = value.startsWith(PREFIX_128);
335
+ const bound = value.startsWith(PREFIX_BOUND_256) || value.startsWith(PREFIX_BOUND_128);
336
+ const is256 = value.startsWith(PREFIX_256) || value.startsWith(PREFIX_BOUND_256);
337
+ const is128 = value.startsWith(PREFIX_128) || value.startsWith(PREFIX_BOUND_128);
319
338
  if (!is256 && !is128) return value;
320
339
  if (!keyObj) throw new Error("Cannot decrypt: encryption key is not set");
321
- const prefix = is128 ? PREFIX_128 : PREFIX_256;
340
+ if (bound && context === void 0) throw new Error("Encrypted value requires authenticated context");
341
+ const prefix = bound ? is128 ? PREFIX_BOUND_128 : PREFIX_BOUND_256 : is128 ? PREFIX_128 : PREFIX_256;
322
342
  const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
323
343
  const combined = Buffer.from(value.slice(prefix.length), "base64");
324
344
  const iv = combined.subarray(0, IV_BYTES);
325
345
  const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
326
346
  const ct = combined.subarray(IV_BYTES + TAG_BYTES);
327
347
  const d = createDecipheriv(algo, keyObj, iv);
348
+ if (bound) d.setAAD(Buffer.from(context, "utf8"));
328
349
  d.setAuthTag(tag);
329
350
  const plain = d.update(ct);
330
351
  d.final();
@@ -332,7 +353,7 @@ var CacheEncryption = class {
332
353
  }
333
354
  // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
334
355
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
335
- encryptBuffer(data) {
356
+ encryptBuffer(data, context) {
336
357
  if (!this._key) return data;
337
358
  if (this._mode === "xor") {
338
359
  const masked = this._xorBuffer(data);
@@ -353,10 +374,11 @@ var CacheEncryption = class {
353
374
  if (fin.length > 0) fin.copy(out2, MAGIC_LEN + CTR_IV_BYTES + enc2.length);
354
375
  return out2;
355
376
  }
356
- const magic = this._mode === "aes-128-gcm" ? MAGIC_128 : MAGIC_256;
377
+ const magic = context === void 0 ? this._mode === "aes-128-gcm" ? MAGIC_128 : MAGIC_256 : this._mode === "aes-128-gcm" ? MAGIC_BOUND_128 : MAGIC_BOUND_256;
357
378
  const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
358
379
  const iv = this._nextIV();
359
380
  const c = createCipheriv(algo, this._keyObj, iv);
381
+ if (context !== void 0) c.setAAD(Buffer.from(context, "utf8"));
360
382
  const enc = c.update(data);
361
383
  c.final();
362
384
  const out = Buffer.allocUnsafe(MAGIC_LEN + IV_BYTES + TAG_BYTES + enc.length);
@@ -371,20 +393,21 @@ var CacheEncryption = class {
371
393
  * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
372
394
  * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
373
395
  */
374
- decryptBuffer(data) {
396
+ decryptBuffer(data, context) {
397
+ this.assertReadPolicy(data, context);
375
398
  try {
376
- return this._decryptBufferWithKey(data, this._key, this._keyObj);
399
+ return this._decryptBufferWithKey(data, this._key, this._keyObj, context);
377
400
  } catch (primaryErr) {
378
401
  if (this._prevKey) {
379
402
  try {
380
- return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj);
403
+ return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj, context);
381
404
  } catch {
382
405
  }
383
406
  }
384
407
  throw primaryErr;
385
408
  }
386
409
  }
387
- _decryptBufferWithKey(data, key, keyObj) {
410
+ _decryptBufferWithKey(data, key, keyObj, context) {
388
411
  if (data.length < MAGIC_LEN) return data;
389
412
  const magic = data.subarray(0, MAGIC_LEN);
390
413
  if (magic.equals(MAGIC_XOR)) {
@@ -404,15 +427,18 @@ var CacheEncryption = class {
404
427
  const fin = d2.final();
405
428
  return fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2;
406
429
  }
407
- const is256 = magic.equals(MAGIC_256);
408
- const is128 = magic.equals(MAGIC_128);
430
+ const bound = magic.equals(MAGIC_BOUND_256) || magic.equals(MAGIC_BOUND_128);
431
+ const is256 = magic.equals(MAGIC_256) || magic.equals(MAGIC_BOUND_256);
432
+ const is128 = magic.equals(MAGIC_128) || magic.equals(MAGIC_BOUND_128);
409
433
  if (!is256 && !is128) return data;
410
434
  if (!keyObj) throw new Error("Cannot decrypt buffer: encryption key is not set");
435
+ if (bound && context === void 0) throw new Error("Encrypted buffer requires authenticated context");
411
436
  const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
412
437
  const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
413
438
  const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
414
439
  const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
415
440
  const d = createDecipheriv(algo, keyObj, iv);
441
+ if (bound) d.setAAD(Buffer.from(context, "utf8"));
416
442
  d.setAuthTag(tag);
417
443
  const plain = d.update(ct);
418
444
  d.final();
@@ -497,31 +523,109 @@ var EnvelopeEncryption = class {
497
523
 
498
524
  // src/compression.ts
499
525
  import zlib from "zlib";
500
- import lz4js from "lz4js";
501
- import { ZstdCodec } from "zstd-codec";
526
+ import { createRequire } from "module";
527
+
528
+ // src/utils/lz4-size.ts
529
+ function lz4DecodedSize(source, maximum) {
530
+ const malformed = () => new Error("tricache: malformed or unsupported LZ4 frame");
531
+ const oversized = () => new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${maximum} bytes`);
532
+ if (source.length < 11 || source.readUInt32LE(0) !== 407708164) throw malformed();
533
+ const flags = source[4];
534
+ const descriptor = source[5];
535
+ const blockMaximum = [0, 0, 0, 0, 65536, 262144, 1048576, 4194304][descriptor >> 4];
536
+ if ((flags & 192) !== 64 || (flags & 19) !== 0 || (descriptor & 143) !== 0 || !blockMaximum) throw malformed();
537
+ let cursor = 6;
538
+ let declared;
539
+ if (flags & 8) {
540
+ if (cursor + 9 > source.length) throw malformed();
541
+ const size = source.readBigUInt64LE(cursor);
542
+ if (size > BigInt(maximum)) throw oversized();
543
+ declared = Number(size);
544
+ cursor += 8;
545
+ }
546
+ cursor++;
547
+ let total = 0;
548
+ const grow = (amount) => {
549
+ if (amount > maximum - total) throw oversized();
550
+ total += amount;
551
+ };
552
+ while (true) {
553
+ if (cursor + 4 > source.length) throw malformed();
554
+ const rawLength = source.readUInt32LE(cursor);
555
+ cursor += 4;
556
+ if (rawLength === 0) break;
557
+ const length = rawLength & 2147483647;
558
+ if (length > blockMaximum || length > source.length - cursor) throw malformed();
559
+ const end = cursor + length;
560
+ const blockStart = total;
561
+ if (rawLength & 2147483648) {
562
+ grow(length);
563
+ cursor = end;
564
+ } else {
565
+ const readLength = (initial) => {
566
+ let count = initial;
567
+ if (initial === 15) {
568
+ let extra;
569
+ do {
570
+ if (cursor >= end) throw malformed();
571
+ extra = source[cursor++];
572
+ count += extra;
573
+ if (count > maximum) throw oversized();
574
+ } while (extra === 255);
575
+ }
576
+ return count;
577
+ };
578
+ while (cursor < end) {
579
+ const token = source[cursor++];
580
+ const literals = readLength(token >>> 4);
581
+ if (literals > end - cursor) throw malformed();
582
+ grow(literals);
583
+ cursor += literals;
584
+ if (cursor === end) break;
585
+ if (cursor + 2 > end) throw malformed();
586
+ const offset = source.readUInt16LE(cursor);
587
+ cursor += 2;
588
+ const history = flags & 32 ? total - blockStart : total;
589
+ if (offset === 0 || offset > history) throw malformed();
590
+ grow(readLength(token & 15) + 4);
591
+ }
592
+ }
593
+ if (total - blockStart > blockMaximum) throw malformed();
594
+ }
595
+ if (flags & 4) cursor += 4;
596
+ if (cursor !== source.length || declared !== void 0 && declared !== total) throw malformed();
597
+ return total;
598
+ }
599
+
600
+ // src/compression.ts
601
+ var requireCompression = createRequire(typeof __filename === "string" ? __filename : import.meta.url);
602
+ var lz4js;
603
+ function getLz4() {
604
+ return lz4js ??= requireCompression("lz4js");
605
+ }
502
606
  var PREFIX_COMPRESSED = "cmp:v1:";
503
607
  var PREFIX_ENC_COMPRESSED = "ecp:v1:";
504
608
  var COMPRESSION_MAGIC = Buffer.from([84, 82, 67, 1]);
505
609
  var zstdSimple = null;
610
+ var zstdGeneric = null;
506
611
  var zstdInitPromise = null;
507
612
  function initZstd() {
508
613
  if (zstdSimple) return Promise.resolve(zstdSimple);
509
614
  if (!zstdInitPromise) {
510
- zstdInitPromise = new Promise((resolve) => {
615
+ zstdInitPromise = import("zstd-codec").then(({ ZstdCodec }) => new Promise((resolve) => {
511
616
  try {
512
617
  ZstdCodec.run((zstd) => {
513
618
  zstdSimple = new zstd.Simple();
619
+ zstdGeneric = new zstd.Generic();
514
620
  resolve(zstdSimple);
515
621
  });
516
622
  } catch {
517
623
  resolve(null);
518
624
  }
519
- });
625
+ })).catch(() => null);
520
626
  }
521
627
  return zstdInitPromise;
522
628
  }
523
- initZstd().catch(() => {
524
- });
525
629
  function isCompressed(buf) {
526
630
  return buf.length >= 4 && buf[0] === 84 && buf[1] === 82 && buf[2] === 67 && buf[3] === 1;
527
631
  }
@@ -541,10 +645,11 @@ function compressBuffer(buf, algorithm, custom) {
541
645
  return zlib.gzipSync(buf, { level: 6 });
542
646
  }
543
647
  if (algorithm === "lz4") {
544
- return Buffer.from(lz4js.compress(buf));
648
+ return Buffer.from(getLz4().compress(buf));
545
649
  }
546
650
  if (algorithm === "zstd") {
547
651
  if (!zstdSimple) {
652
+ void initZstd();
548
653
  return zlib.brotliCompressSync(buf, {
549
654
  params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 4 }
550
655
  });
@@ -554,9 +659,24 @@ function compressBuffer(buf, algorithm, custom) {
554
659
  return buf;
555
660
  }
556
661
  var MAX_DECOMPRESS_BYTES = 25 * 1024 * 1024;
662
+ function decompressLz4(buf) {
663
+ const size = lz4DecodedSize(buf, MAX_DECOMPRESS_BYTES);
664
+ const decoded = Buffer.from(getLz4().decompress(buf, size));
665
+ if (decoded.length !== size) throw new Error("tricache: corrupt LZ4 decoded size");
666
+ return decoded;
667
+ }
668
+ function decompressZstd(buf) {
669
+ const size = zstdGeneric?.contentSize(buf);
670
+ if (!Number.isSafeInteger(size) || size < 0) throw new Error("tricache: Zstandard frame requires a bounded content size");
671
+ if (size > MAX_DECOMPRESS_BYTES) throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
672
+ const decoded = zstdSimple.decompress(buf);
673
+ if (!decoded || decoded.length !== size) throw new Error("tricache: corrupt Zstandard decoded size");
674
+ return Buffer.from(decoded);
675
+ }
557
676
  function decompressBuffer(buf, algorithm = "zstd", custom) {
677
+ if (buf.length > 32 * 1024 * 1024) throw new Error("tricache: compressed input exceeds maximum safety threshold");
558
678
  if (custom) {
559
- const res = custom.decompress(buf);
679
+ const res = custom.decompress(buf, MAX_DECOMPRESS_BYTES);
560
680
  if (res.length > MAX_DECOMPRESS_BYTES) {
561
681
  throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
562
682
  }
@@ -571,7 +691,7 @@ function decompressBuffer(buf, algorithm = "zstd", custom) {
571
691
  if (buf.length >= 4 && buf[0] === 40 && buf[1] === 181 && buf[2] === 47 && buf[3] === 253) {
572
692
  if (zstdSimple) {
573
693
  try {
574
- return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
694
+ return checkSafety(decompressZstd(buf));
575
695
  } catch (err) {
576
696
  if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
577
697
  }
@@ -579,7 +699,7 @@ function decompressBuffer(buf, algorithm = "zstd", custom) {
579
699
  }
580
700
  if (buf.length >= 4 && buf[0] === 4 && buf[1] === 34 && buf[2] === 77 && buf[3] === 24) {
581
701
  try {
582
- return checkSafety(Buffer.from(lz4js.decompress(buf)));
702
+ return checkSafety(decompressLz4(buf));
583
703
  } catch (err) {
584
704
  if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
585
705
  }
@@ -598,14 +718,14 @@ function decompressBuffer(buf, algorithm = "zstd", custom) {
598
718
  }
599
719
  if (algorithm === "lz4") {
600
720
  try {
601
- return checkSafety(Buffer.from(lz4js.decompress(buf)));
721
+ return checkSafety(decompressLz4(buf));
602
722
  } catch (err) {
603
723
  if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
604
724
  }
605
725
  }
606
726
  if (algorithm === "zstd" && zstdSimple) {
607
727
  try {
608
- return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
728
+ return checkSafety(decompressZstd(buf));
609
729
  } catch (err) {
610
730
  if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
611
731
  }
@@ -632,7 +752,7 @@ function decompressBuffer(buf, algorithm = "zstd", custom) {
632
752
  };
633
753
  const tryLz4 = () => {
634
754
  try {
635
- return checkSafety(Buffer.from(lz4js.decompress(buf)));
755
+ return checkSafety(decompressLz4(buf));
636
756
  } catch (err) {
637
757
  if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
638
758
  return null;
@@ -641,7 +761,7 @@ function decompressBuffer(buf, algorithm = "zstd", custom) {
641
761
  const tryZstd = () => {
642
762
  if (!zstdSimple) return null;
643
763
  try {
644
- return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
764
+ return checkSafety(decompressZstd(buf));
645
765
  } catch (err) {
646
766
  if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
647
767
  return null;
@@ -66,7 +66,6 @@ function honoEdgeCache(options = {}) {
66
66
  cache,
67
67
  etag = true,
68
68
  ttl = 300,
69
- swr,
70
69
  tags,
71
70
  skipCache,
72
71
  keyGenerator,
@@ -80,6 +79,8 @@ function honoEdgeCache(options = {}) {
80
79
  if (skipCache && skipCache(c)) {
81
80
  return await next();
82
81
  }
82
+ const credentials = ["authorization", "cookie", "x-api-key", "x-auth-token"].filter((name) => c.req.header?.(name));
83
+ if (c.req.header?.("range") || credentials.length > 0 && (!options.cacheAuthenticated || !keyGenerator && !credentials.every((name) => headerWhitelist?.some((header) => header.toLowerCase() === name)))) return await next();
83
84
  const cc = c.req.header?.("cache-control") || c.req.header?.("Cache-Control");
84
85
  if (typeof cc === "string") {
85
86
  const lower = cc.toLowerCase();
@@ -90,7 +91,12 @@ function honoEdgeCache(options = {}) {
90
91
  if (!cache) {
91
92
  return await next();
92
93
  }
93
- const key = buildEdgeDeterministicKey(c, { keyGenerator, headerWhitelist });
94
+ let key = buildEdgeDeterministicKey(c, { keyGenerator, headerWhitelist });
95
+ if (credentials.length) {
96
+ if (!globalThis.crypto?.subtle) return await next();
97
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(key));
98
+ key = `edge:http:identity:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
99
+ }
94
100
  const ifNoneMatch = c.req.header?.("if-none-match") || c.req.header?.("If-None-Match");
95
101
  const resolvedTags = typeof tags === "function" ? tags(c) : tags;
96
102
  let ranNext = false;
@@ -113,6 +119,10 @@ function honoEdgeCache(options = {}) {
113
119
  });
114
120
  }
115
121
  const cc2 = res.headers?.get?.("cache-control");
122
+ const vary = String(res.headers?.get?.("vary") ?? "").split(",").map((name) => name.trim().toLowerCase()).filter(Boolean);
123
+ if (res.headers?.get?.("set-cookie") || vary.includes("*") || !keyGenerator && vary.some((name) => !headerWhitelist?.some((header) => header.toLowerCase() === name))) {
124
+ throw new NonCacheableEdgeResponseError({ body: "", contentType, status: 0 });
125
+ }
116
126
  if (cc2) {
117
127
  const lowerCc = cc2.toLowerCase();
118
128
  if (lowerCc.includes("no-store") || lowerCc.includes("no-cache") || lowerCc.includes("private")) {
@@ -154,9 +164,9 @@ function honoEdgeCache(options = {}) {
154
164
  },
155
165
  ttl,
156
166
  {
157
- swr,
167
+ swr: 0,
158
168
  tags: resolvedTags,
159
- ctx: c.executionCtx
169
+ ctx: readExecutionContext(c)
160
170
  }
161
171
  );
162
172
  if (!cached) {
@@ -183,6 +193,13 @@ function honoEdgeCache(options = {}) {
183
193
  }
184
194
  };
185
195
  }
196
+ function readExecutionContext(c) {
197
+ try {
198
+ return c.executionCtx;
199
+ } catch {
200
+ return void 0;
201
+ }
202
+ }
186
203
  function applyEdgeResponse(c, body, status, headers) {
187
204
  const response = c.body(body, status, headers);
188
205
  c.res = response;