tricache 1.0.2 → 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 (101) hide show
  1. package/README.md +78 -90
  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-CWI4jkS7.d.cts → cache-service-BV5T8-20.d.cts} +122 -21
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-B108FzER.d.ts → cache-service-tpyrXvlH.d.ts} +122 -21
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-H4GFLQ26.js → chunk-KV7KISK2.js} +47 -1
  10. package/dist/{chunk-WYF7NOAT.js → chunk-MB3DMVWN.js} +2111 -543
  11. package/dist/{chunk-OYDU3SMI.js → chunk-RBJRTGFK.js} +5 -0
  12. package/dist/chunk-S5N65I45.js +17 -0
  13. package/dist/cli.cjs +2454 -572
  14. package/dist/cli.js +186 -11
  15. package/dist/dashboard/index.d.cts +2 -2
  16. package/dist/dashboard/index.d.ts +2 -2
  17. package/dist/drizzle/index.cjs +2335 -571
  18. package/dist/drizzle/index.d.cts +2 -2
  19. package/dist/drizzle/index.d.ts +2 -2
  20. package/dist/drizzle/index.js +6 -2
  21. package/dist/edge/index.cjs +145 -43
  22. package/dist/edge/index.d.cts +11 -4
  23. package/dist/edge/index.d.ts +11 -4
  24. package/dist/edge/index.js +118 -43
  25. package/dist/hono/index.cjs +2322 -569
  26. package/dist/hono/index.d.cts +2 -2
  27. package/dist/hono/index.d.ts +2 -2
  28. package/dist/hono/index.js +2 -2
  29. package/dist/{hono-C886ok3X.d.cts → hono-CMv2VdQ6.d.cts} +18 -5
  30. package/dist/{hono-3rDMYVtY.d.ts → hono-Dvq04kX9.d.ts} +18 -5
  31. package/dist/http/index.cjs +2323 -570
  32. package/dist/http/index.d.cts +3 -3
  33. package/dist/http/index.d.ts +3 -3
  34. package/dist/http/index.js +4 -4
  35. package/dist/index.cjs +2554 -620
  36. package/dist/index.d.cts +88 -23
  37. package/dist/index.d.ts +88 -23
  38. package/dist/index.js +873 -16
  39. package/dist/{murmur3-CMGw9PbV.d.cts → murmur3-DF8BFRnu.d.cts} +1 -0
  40. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.ts} +1 -0
  41. package/dist/nestjs/index.cjs +2292 -574
  42. package/dist/nestjs/index.d.cts +19 -5
  43. package/dist/nestjs/index.d.ts +19 -5
  44. package/dist/nestjs/index.js +25 -19
  45. package/dist/next/index.cjs +2306 -571
  46. package/dist/next/index.d.cts +8 -2
  47. package/dist/next/index.d.ts +8 -2
  48. package/dist/next/index.js +36 -9
  49. package/dist/prisma/index.cjs +26 -25
  50. package/dist/prisma/index.d.cts +2 -2
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +14 -25
  53. package/dist/serialize-worker.cjs +162 -39
  54. package/dist/serialize-worker.js +9 -7
  55. package/dist/{types-BA4pz1A0.d.cts → types-F8vRWMrE.d.cts} +162 -45
  56. package/dist/{types-BA4pz1A0.d.ts → types-F8vRWMrE.d.ts} +162 -45
  57. package/package.json +21 -2
  58. package/src/adapters/auto-pipeliner.ts +52 -11
  59. package/src/cache-service.ts +1537 -415
  60. package/src/cli.ts +2 -9
  61. package/src/codec.ts +3 -3
  62. package/src/compression.ts +39 -16
  63. package/src/cross-region.ts +1 -1
  64. package/src/disk-tier.ts +283 -43
  65. package/src/drizzle/index.ts +2 -1
  66. package/src/edge/adapters/cloudflare-do.ts +25 -10
  67. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  68. package/src/edge/adapters/upstash.ts +27 -11
  69. package/src/edge/cache.ts +59 -17
  70. package/src/edge/types.ts +15 -5
  71. package/src/encryption.ts +50 -18
  72. package/src/env.d.ts +1 -1
  73. package/src/errors.ts +12 -0
  74. package/src/http/utils.ts +6 -0
  75. package/src/index.ts +6 -0
  76. package/src/latency-watchdog.ts +5 -1
  77. package/src/nestjs/decorators.ts +11 -6
  78. package/src/nestjs/tricache.module.ts +2 -1
  79. package/src/nestjs/tricache.store.ts +21 -9
  80. package/src/nestjs/types.ts +1 -1
  81. package/src/next/cache-handler.ts +24 -4
  82. package/src/next/types.ts +4 -0
  83. package/src/origin-capacity.ts +134 -0
  84. package/src/prisma/index.ts +14 -32
  85. package/src/remote-snapshot.ts +37 -27
  86. package/src/serialize-worker.ts +8 -5
  87. package/src/sigv4-snapshot-adapter.ts +37 -27
  88. package/src/smart-memory-cache.ts +62 -22
  89. package/src/types.ts +92 -35
  90. package/src/utils/config-comparison.ts +29 -0
  91. package/src/utils/lz4-size.ts +74 -0
  92. package/src/utils/namespace-key.ts +48 -0
  93. package/src/utils/query-key.ts +13 -0
  94. package/src/utils/snapshot-transfer.ts +83 -0
  95. package/src/utils/work-limits.ts +73 -0
  96. package/src/utils/write-revision.ts +4 -0
  97. package/src/wasm/bloom-filter-wasm.ts +16 -1
  98. package/src/worker-pool.ts +28 -8
  99. package/src/wtiny-lfu.ts +62 -14
  100. package/dist/cache-service-GYPZFB7O.js +0 -12
  101. package/dist/chunk-VNRDL5RA.js +0 -666
@@ -42,9 +42,13 @@ var IV_BYTES = 12;
42
42
  var TAG_BYTES = 16;
43
43
  var PREFIX_256 = "enc:v1:";
44
44
  var PREFIX_128 = "a128:v1:";
45
+ var PREFIX_BOUND_256 = "enc:v2:";
46
+ var PREFIX_BOUND_128 = "a128:v2:";
45
47
  var PREFIX_XOR = "xor:v1:";
46
48
  var MAGIC_256 = Buffer.from([84, 82, 73, 67, 49, 69, 78, 67]);
47
49
  var MAGIC_128 = Buffer.from([84, 82, 73, 67, 49, 49, 50, 56]);
50
+ var MAGIC_BOUND_256 = Buffer.from("TRIC2ENC");
51
+ var MAGIC_BOUND_128 = Buffer.from("TRIC2128");
48
52
  var MAGIC_XOR = Buffer.from([84, 82, 73, 67, 49, 88, 79, 82]);
49
53
  var MAGIC_CTR = Buffer.from([84, 82, 73, 67, 49, 67, 84, 82]);
50
54
  var MAGIC_LEN = 8;
@@ -59,6 +63,7 @@ var CacheEncryption = class {
59
63
  _mode;
60
64
  /** Fail-closed on invalid key material when opted in via constructor opts. */
61
65
  _strictKeyValidation;
66
+ _allowLegacyPlaintextRead;
62
67
  _prevKey = null;
63
68
  _prevKeyObj = null;
64
69
  _prevMode = "aes-256-gcm";
@@ -128,6 +133,7 @@ var CacheEncryption = class {
128
133
  const logger = typeof loggerOrMode === "object" && loggerOrMode !== null ? loggerOrMode : consoleLogger;
129
134
  const resolvedMode = typeof loggerOrMode === "string" ? loggerOrMode : mode2;
130
135
  this._strictKeyValidation = opts?.strictKeyValidation ?? false;
136
+ this._allowLegacyPlaintextRead = opts?.allowLegacyPlaintextRead ?? true;
131
137
  this._mode = resolvedMode;
132
138
  if (keyBase642 === void 0 || keyBase642 === null) {
133
139
  if (process.env.NODE_ENV === "production") {
@@ -214,7 +220,8 @@ var CacheEncryption = class {
214
220
  keyBase64: this._key ? this._key.toString("base64") : "",
215
221
  mode: this._mode,
216
222
  prevKeyBase64: this._prevKey ? this._prevKey.toString("base64") : void 0,
217
- prevMode: this._prevMode
223
+ prevMode: this._prevMode,
224
+ allowLegacyPlaintextRead: this._allowLegacyPlaintextRead
218
225
  };
219
226
  }
220
227
  /**
@@ -260,7 +267,7 @@ var CacheEncryption = class {
260
267
  * Returns a mode-prefixed base64 string when a key is configured;
261
268
  * otherwise returns the original string unchanged (backward-compatible).
262
269
  */
263
- encrypt(plaintext) {
270
+ encrypt(plaintext, context) {
264
271
  if (!this._key) return plaintext;
265
272
  if (this._mode === "xor") {
266
273
  const masked = this._xorBuffer(Buffer.from(plaintext, "utf8"));
@@ -278,9 +285,10 @@ var CacheEncryption = class {
278
285
  return PREFIX_CTR + out2.toString("base64");
279
286
  }
280
287
  const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
281
- const prefix = this._mode === "aes-128-gcm" ? PREFIX_128 : PREFIX_256;
288
+ 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;
282
289
  const iv = this._nextIV();
283
290
  const c = (0, import_crypto.createCipheriv)(algo, this._keyObj, iv);
291
+ if (context !== void 0) c.setAAD(Buffer.from(context, "utf8"));
284
292
  const enc2 = c.update(plaintext, "utf8");
285
293
  c.final();
286
294
  const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc2.length);
@@ -294,20 +302,30 @@ var CacheEncryption = class {
294
302
  * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
295
303
  * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
296
304
  */
297
- decrypt(value) {
305
+ assertReadPolicy(value, context) {
306
+ if (!this.isEnabled || this._allowLegacyPlaintextRead || !this._mode.endsWith("-gcm")) return;
307
+ if (context === void 0) throw new Error("Authenticated cache read requires context");
308
+ if (typeof value === "string") {
309
+ if (value.startsWith("ecp:v1:")) return this.assertReadPolicy(Buffer.from(value.slice(7), "base64"), context);
310
+ if (value.startsWith(PREFIX_BOUND_256) || value.startsWith(PREFIX_BOUND_128)) return;
311
+ } else if (value.subarray(0, 8).equals(MAGIC_BOUND_256) || value.subarray(0, 8).equals(MAGIC_BOUND_128)) return;
312
+ throw new Error("Legacy or plaintext cache value rejected; opt in to allowLegacyPlaintextRead for migration");
313
+ }
314
+ decrypt(value, context) {
315
+ this.assertReadPolicy(value, context);
298
316
  try {
299
- return this._decryptWithKey(value, this._key, this._keyObj);
317
+ return this._decryptWithKey(value, this._key, this._keyObj, context);
300
318
  } catch (primaryErr) {
301
319
  if (this._prevKey) {
302
320
  try {
303
- return this._decryptWithKey(value, this._prevKey, this._prevKeyObj);
321
+ return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, context);
304
322
  } catch {
305
323
  }
306
324
  }
307
325
  throw primaryErr;
308
326
  }
309
327
  }
310
- _decryptWithKey(value, key, keyObj) {
328
+ _decryptWithKey(value, key, keyObj, context) {
311
329
  if (value.startsWith(PREFIX_XOR)) {
312
330
  if (!key) throw new Error("Cannot decrypt: encryption key is not set");
313
331
  const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
@@ -327,17 +345,20 @@ var CacheEncryption = class {
327
345
  const fin = d2.final();
328
346
  return (fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2).toString("utf8");
329
347
  }
330
- const is256 = value.startsWith(PREFIX_256);
331
- const is128 = value.startsWith(PREFIX_128);
348
+ const bound = value.startsWith(PREFIX_BOUND_256) || value.startsWith(PREFIX_BOUND_128);
349
+ const is256 = value.startsWith(PREFIX_256) || value.startsWith(PREFIX_BOUND_256);
350
+ const is128 = value.startsWith(PREFIX_128) || value.startsWith(PREFIX_BOUND_128);
332
351
  if (!is256 && !is128) return value;
333
352
  if (!keyObj) throw new Error("Cannot decrypt: encryption key is not set");
334
- const prefix = is128 ? PREFIX_128 : PREFIX_256;
353
+ if (bound && context === void 0) throw new Error("Encrypted value requires authenticated context");
354
+ const prefix = bound ? is128 ? PREFIX_BOUND_128 : PREFIX_BOUND_256 : is128 ? PREFIX_128 : PREFIX_256;
335
355
  const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
336
356
  const combined = Buffer.from(value.slice(prefix.length), "base64");
337
357
  const iv = combined.subarray(0, IV_BYTES);
338
358
  const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
339
359
  const ct = combined.subarray(IV_BYTES + TAG_BYTES);
340
360
  const d = (0, import_crypto.createDecipheriv)(algo, keyObj, iv);
361
+ if (bound) d.setAAD(Buffer.from(context, "utf8"));
341
362
  d.setAuthTag(tag);
342
363
  const plain = d.update(ct);
343
364
  d.final();
@@ -345,7 +366,7 @@ var CacheEncryption = class {
345
366
  }
346
367
  // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
347
368
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
348
- encryptBuffer(data) {
369
+ encryptBuffer(data, context) {
349
370
  if (!this._key) return data;
350
371
  if (this._mode === "xor") {
351
372
  const masked = this._xorBuffer(data);
@@ -366,10 +387,11 @@ var CacheEncryption = class {
366
387
  if (fin.length > 0) fin.copy(out2, MAGIC_LEN + CTR_IV_BYTES + enc3.length);
367
388
  return out2;
368
389
  }
369
- const magic = this._mode === "aes-128-gcm" ? MAGIC_128 : MAGIC_256;
390
+ 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;
370
391
  const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
371
392
  const iv = this._nextIV();
372
393
  const c = (0, import_crypto.createCipheriv)(algo, this._keyObj, iv);
394
+ if (context !== void 0) c.setAAD(Buffer.from(context, "utf8"));
373
395
  const enc2 = c.update(data);
374
396
  c.final();
375
397
  const out = Buffer.allocUnsafe(MAGIC_LEN + IV_BYTES + TAG_BYTES + enc2.length);
@@ -384,20 +406,21 @@ var CacheEncryption = class {
384
406
  * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
385
407
  * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
386
408
  */
387
- decryptBuffer(data) {
409
+ decryptBuffer(data, context) {
410
+ this.assertReadPolicy(data, context);
388
411
  try {
389
- return this._decryptBufferWithKey(data, this._key, this._keyObj);
412
+ return this._decryptBufferWithKey(data, this._key, this._keyObj, context);
390
413
  } catch (primaryErr) {
391
414
  if (this._prevKey) {
392
415
  try {
393
- return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj);
416
+ return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj, context);
394
417
  } catch {
395
418
  }
396
419
  }
397
420
  throw primaryErr;
398
421
  }
399
422
  }
400
- _decryptBufferWithKey(data, key, keyObj) {
423
+ _decryptBufferWithKey(data, key, keyObj, context) {
401
424
  if (data.length < MAGIC_LEN) return data;
402
425
  const magic = data.subarray(0, MAGIC_LEN);
403
426
  if (magic.equals(MAGIC_XOR)) {
@@ -417,15 +440,18 @@ var CacheEncryption = class {
417
440
  const fin = d2.final();
418
441
  return fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2;
419
442
  }
420
- const is256 = magic.equals(MAGIC_256);
421
- const is128 = magic.equals(MAGIC_128);
443
+ const bound = magic.equals(MAGIC_BOUND_256) || magic.equals(MAGIC_BOUND_128);
444
+ const is256 = magic.equals(MAGIC_256) || magic.equals(MAGIC_BOUND_256);
445
+ const is128 = magic.equals(MAGIC_128) || magic.equals(MAGIC_BOUND_128);
422
446
  if (!is256 && !is128) return data;
423
447
  if (!keyObj) throw new Error("Cannot decrypt buffer: encryption key is not set");
448
+ if (bound && context === void 0) throw new Error("Encrypted buffer requires authenticated context");
424
449
  const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
425
450
  const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
426
451
  const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
427
452
  const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
428
453
  const d = (0, import_crypto.createDecipheriv)(algo, keyObj, iv);
454
+ if (bound) d.setAAD(Buffer.from(context, "utf8"));
429
455
  d.setAuthTag(tag);
430
456
  const plain = d.update(ct);
431
457
  d.final();
@@ -436,31 +462,110 @@ var MAGIC_ENVELOPE = Buffer.from([84, 82, 73, 67, 69, 78, 86, 49]);
436
462
 
437
463
  // src/compression.ts
438
464
  var import_zlib = __toESM(require("zlib"), 1);
439
- var import_lz4js = __toESM(require("lz4js"), 1);
440
- var import_zstd_codec = require("zstd-codec");
465
+ var import_node_module = require("module");
466
+
467
+ // src/utils/lz4-size.ts
468
+ function lz4DecodedSize(source, maximum) {
469
+ const malformed = () => new Error("tricache: malformed or unsupported LZ4 frame");
470
+ const oversized = () => new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${maximum} bytes`);
471
+ if (source.length < 11 || source.readUInt32LE(0) !== 407708164) throw malformed();
472
+ const flags = source[4];
473
+ const descriptor = source[5];
474
+ const blockMaximum = [0, 0, 0, 0, 65536, 262144, 1048576, 4194304][descriptor >> 4];
475
+ if ((flags & 192) !== 64 || (flags & 19) !== 0 || (descriptor & 143) !== 0 || !blockMaximum) throw malformed();
476
+ let cursor = 6;
477
+ let declared;
478
+ if (flags & 8) {
479
+ if (cursor + 9 > source.length) throw malformed();
480
+ const size = source.readBigUInt64LE(cursor);
481
+ if (size > BigInt(maximum)) throw oversized();
482
+ declared = Number(size);
483
+ cursor += 8;
484
+ }
485
+ cursor++;
486
+ let total = 0;
487
+ const grow = (amount) => {
488
+ if (amount > maximum - total) throw oversized();
489
+ total += amount;
490
+ };
491
+ while (true) {
492
+ if (cursor + 4 > source.length) throw malformed();
493
+ const rawLength = source.readUInt32LE(cursor);
494
+ cursor += 4;
495
+ if (rawLength === 0) break;
496
+ const length = rawLength & 2147483647;
497
+ if (length > blockMaximum || length > source.length - cursor) throw malformed();
498
+ const end = cursor + length;
499
+ const blockStart = total;
500
+ if (rawLength & 2147483648) {
501
+ grow(length);
502
+ cursor = end;
503
+ } else {
504
+ const readLength = (initial) => {
505
+ let count = initial;
506
+ if (initial === 15) {
507
+ let extra;
508
+ do {
509
+ if (cursor >= end) throw malformed();
510
+ extra = source[cursor++];
511
+ count += extra;
512
+ if (count > maximum) throw oversized();
513
+ } while (extra === 255);
514
+ }
515
+ return count;
516
+ };
517
+ while (cursor < end) {
518
+ const token = source[cursor++];
519
+ const literals = readLength(token >>> 4);
520
+ if (literals > end - cursor) throw malformed();
521
+ grow(literals);
522
+ cursor += literals;
523
+ if (cursor === end) break;
524
+ if (cursor + 2 > end) throw malformed();
525
+ const offset = source.readUInt16LE(cursor);
526
+ cursor += 2;
527
+ const history = flags & 32 ? total - blockStart : total;
528
+ if (offset === 0 || offset > history) throw malformed();
529
+ grow(readLength(token & 15) + 4);
530
+ }
531
+ }
532
+ if (total - blockStart > blockMaximum) throw malformed();
533
+ }
534
+ if (flags & 4) cursor += 4;
535
+ if (cursor !== source.length || declared !== void 0 && declared !== total) throw malformed();
536
+ return total;
537
+ }
538
+
539
+ // src/compression.ts
540
+ var import_meta = {};
541
+ var requireCompression = (0, import_node_module.createRequire)(typeof __filename === "string" ? __filename : import_meta.url);
542
+ var lz4js;
543
+ function getLz4() {
544
+ return lz4js ??= requireCompression("lz4js");
545
+ }
441
546
  var PREFIX_COMPRESSED = "cmp:v1:";
442
547
  var PREFIX_ENC_COMPRESSED = "ecp:v1:";
443
548
  var COMPRESSION_MAGIC = Buffer.from([84, 82, 67, 1]);
444
549
  var zstdSimple = null;
550
+ var zstdGeneric = null;
445
551
  var zstdInitPromise = null;
446
552
  function initZstd() {
447
553
  if (zstdSimple) return Promise.resolve(zstdSimple);
448
554
  if (!zstdInitPromise) {
449
- zstdInitPromise = new Promise((resolve) => {
555
+ zstdInitPromise = import("zstd-codec").then(({ ZstdCodec }) => new Promise((resolve) => {
450
556
  try {
451
- import_zstd_codec.ZstdCodec.run((zstd) => {
557
+ ZstdCodec.run((zstd) => {
452
558
  zstdSimple = new zstd.Simple();
559
+ zstdGeneric = new zstd.Generic();
453
560
  resolve(zstdSimple);
454
561
  });
455
562
  } catch {
456
563
  resolve(null);
457
564
  }
458
- });
565
+ })).catch(() => null);
459
566
  }
460
567
  return zstdInitPromise;
461
568
  }
462
- initZstd().catch(() => {
463
- });
464
569
  function compressBuffer(buf, algorithm, custom) {
465
570
  if (custom) {
466
571
  return custom.compress(buf);
@@ -477,10 +582,11 @@ function compressBuffer(buf, algorithm, custom) {
477
582
  return import_zlib.default.gzipSync(buf, { level: 6 });
478
583
  }
479
584
  if (algorithm === "lz4") {
480
- return Buffer.from(import_lz4js.default.compress(buf));
585
+ return Buffer.from(getLz4().compress(buf));
481
586
  }
482
587
  if (algorithm === "zstd") {
483
588
  if (!zstdSimple) {
589
+ void initZstd();
484
590
  return import_zlib.default.brotliCompressSync(buf, {
485
591
  params: { [import_zlib.default.constants.BROTLI_PARAM_QUALITY]: 4 }
486
592
  });
@@ -490,9 +596,24 @@ function compressBuffer(buf, algorithm, custom) {
490
596
  return buf;
491
597
  }
492
598
  var MAX_DECOMPRESS_BYTES = 25 * 1024 * 1024;
599
+ function decompressLz4(buf) {
600
+ const size = lz4DecodedSize(buf, MAX_DECOMPRESS_BYTES);
601
+ const decoded = Buffer.from(getLz4().decompress(buf, size));
602
+ if (decoded.length !== size) throw new Error("tricache: corrupt LZ4 decoded size");
603
+ return decoded;
604
+ }
605
+ function decompressZstd(buf) {
606
+ const size = zstdGeneric?.contentSize(buf);
607
+ if (!Number.isSafeInteger(size) || size < 0) throw new Error("tricache: Zstandard frame requires a bounded content size");
608
+ if (size > MAX_DECOMPRESS_BYTES) throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
609
+ const decoded = zstdSimple.decompress(buf);
610
+ if (!decoded || decoded.length !== size) throw new Error("tricache: corrupt Zstandard decoded size");
611
+ return Buffer.from(decoded);
612
+ }
493
613
  function decompressBuffer(buf, algorithm = "zstd", custom) {
614
+ if (buf.length > 32 * 1024 * 1024) throw new Error("tricache: compressed input exceeds maximum safety threshold");
494
615
  if (custom) {
495
- const res = custom.decompress(buf);
616
+ const res = custom.decompress(buf, MAX_DECOMPRESS_BYTES);
496
617
  if (res.length > MAX_DECOMPRESS_BYTES) {
497
618
  throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
498
619
  }
@@ -507,7 +628,7 @@ function decompressBuffer(buf, algorithm = "zstd", custom) {
507
628
  if (buf.length >= 4 && buf[0] === 40 && buf[1] === 181 && buf[2] === 47 && buf[3] === 253) {
508
629
  if (zstdSimple) {
509
630
  try {
510
- return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
631
+ return checkSafety(decompressZstd(buf));
511
632
  } catch (err) {
512
633
  if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
513
634
  }
@@ -515,7 +636,7 @@ function decompressBuffer(buf, algorithm = "zstd", custom) {
515
636
  }
516
637
  if (buf.length >= 4 && buf[0] === 4 && buf[1] === 34 && buf[2] === 77 && buf[3] === 24) {
517
638
  try {
518
- return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
639
+ return checkSafety(decompressLz4(buf));
519
640
  } catch (err) {
520
641
  if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
521
642
  }
@@ -534,14 +655,14 @@ function decompressBuffer(buf, algorithm = "zstd", custom) {
534
655
  }
535
656
  if (algorithm === "lz4") {
536
657
  try {
537
- return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
658
+ return checkSafety(decompressLz4(buf));
538
659
  } catch (err) {
539
660
  if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
540
661
  }
541
662
  }
542
663
  if (algorithm === "zstd" && zstdSimple) {
543
664
  try {
544
- return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
665
+ return checkSafety(decompressZstd(buf));
545
666
  } catch (err) {
546
667
  if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
547
668
  }
@@ -568,7 +689,7 @@ function decompressBuffer(buf, algorithm = "zstd", custom) {
568
689
  };
569
690
  const tryLz4 = () => {
570
691
  try {
571
- return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
692
+ return checkSafety(decompressLz4(buf));
572
693
  } catch (err) {
573
694
  if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
574
695
  return null;
@@ -577,7 +698,7 @@ function decompressBuffer(buf, algorithm = "zstd", custom) {
577
698
  const tryZstd = () => {
578
699
  if (!zstdSimple) return null;
579
700
  try {
580
- return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
701
+ return checkSafety(decompressZstd(buf));
581
702
  } catch (err) {
582
703
  if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
583
704
  return null;
@@ -607,13 +728,14 @@ var enc = new CacheEncryption(
607
728
  silentLogger,
608
729
  mode,
609
730
  prevKeyBase64 || void 0,
610
- prevMode
731
+ prevMode,
732
+ { allowLegacyPlaintextRead: import_worker_threads.workerData.allowLegacyPlaintextRead }
611
733
  );
612
734
  var cmpAlgo = compression ?? "zstd";
613
735
  var cmpThreshold = compressionThresholdBytes ?? 1024;
614
736
  import_worker_threads.parentPort.on(
615
737
  "message",
616
- async ({ id, type, payload }) => {
738
+ async ({ id, type, payload, context }) => {
617
739
  try {
618
740
  if (cmpAlgo === "zstd") {
619
741
  await initZstd();
@@ -624,13 +746,13 @@ import_worker_threads.parentPort.on(
624
746
  if (cmpAlgo !== "none" && textPayload.length > cmpThreshold) {
625
747
  const compressed = compressBuffer(Buffer.from(textPayload, "utf8"), cmpAlgo);
626
748
  if (enc.isEnabled) {
627
- const encrypted = enc.encryptBuffer(compressed);
749
+ const encrypted = enc.encryptBuffer(compressed, context);
628
750
  result = PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
629
751
  } else {
630
752
  result = PREFIX_COMPRESSED + compressed.toString("base64");
631
753
  }
632
754
  } else {
633
- result = enc.encrypt(textPayload);
755
+ result = enc.encrypt(textPayload, context);
634
756
  }
635
757
  if (result.length >= 131072) {
636
758
  const outBuf = Buffer.from(result, "utf8");
@@ -642,10 +764,11 @@ import_worker_threads.parentPort.on(
642
764
  import_worker_threads.parentPort.postMessage({ id, result });
643
765
  }
644
766
  } else {
767
+ enc.assertReadPolicy(textPayload, context);
645
768
  let result;
646
769
  if (textPayload.startsWith(PREFIX_ENC_COMPRESSED)) {
647
770
  const rawBuf = Buffer.from(textPayload.slice(PREFIX_ENC_COMPRESSED.length), "base64");
648
- const decryptedBuf = enc.decryptBuffer(rawBuf);
771
+ const decryptedBuf = enc.decryptBuffer(rawBuf, context);
649
772
  const decompressed = decompressBuffer(decryptedBuf, cmpAlgo !== "none" ? cmpAlgo : "brotli");
650
773
  result = decompressed.toString("utf8");
651
774
  } else if (textPayload.startsWith(PREFIX_COMPRESSED)) {
@@ -653,7 +776,7 @@ import_worker_threads.parentPort.on(
653
776
  const decompressed = decompressBuffer(rawBuf, cmpAlgo !== "none" ? cmpAlgo : "brotli");
654
777
  result = decompressed.toString("utf8");
655
778
  } else {
656
- result = enc.decrypt(textPayload);
779
+ result = enc.decrypt(textPayload, context);
657
780
  }
658
781
  if (result.length >= 131072) {
659
782
  const outBuf = Buffer.from(result, "utf8");
@@ -5,7 +5,7 @@ import {
5
5
  compressBuffer,
6
6
  decompressBuffer,
7
7
  initZstd
8
- } from "./chunk-UBWLPKTI.js";
8
+ } from "./chunk-EJXG7WO6.js";
9
9
 
10
10
  // src/serialize-worker.ts
11
11
  import { parentPort, workerData } from "worker_threads";
@@ -25,13 +25,14 @@ var enc = new CacheEncryption(
25
25
  silentLogger,
26
26
  mode,
27
27
  prevKeyBase64 || void 0,
28
- prevMode
28
+ prevMode,
29
+ { allowLegacyPlaintextRead: workerData.allowLegacyPlaintextRead }
29
30
  );
30
31
  var cmpAlgo = compression ?? "zstd";
31
32
  var cmpThreshold = compressionThresholdBytes ?? 1024;
32
33
  parentPort.on(
33
34
  "message",
34
- async ({ id, type, payload }) => {
35
+ async ({ id, type, payload, context }) => {
35
36
  try {
36
37
  if (cmpAlgo === "zstd") {
37
38
  await initZstd();
@@ -42,13 +43,13 @@ parentPort.on(
42
43
  if (cmpAlgo !== "none" && textPayload.length > cmpThreshold) {
43
44
  const compressed = compressBuffer(Buffer.from(textPayload, "utf8"), cmpAlgo);
44
45
  if (enc.isEnabled) {
45
- const encrypted = enc.encryptBuffer(compressed);
46
+ const encrypted = enc.encryptBuffer(compressed, context);
46
47
  result = PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
47
48
  } else {
48
49
  result = PREFIX_COMPRESSED + compressed.toString("base64");
49
50
  }
50
51
  } else {
51
- result = enc.encrypt(textPayload);
52
+ result = enc.encrypt(textPayload, context);
52
53
  }
53
54
  if (result.length >= 131072) {
54
55
  const outBuf = Buffer.from(result, "utf8");
@@ -60,10 +61,11 @@ parentPort.on(
60
61
  parentPort.postMessage({ id, result });
61
62
  }
62
63
  } else {
64
+ enc.assertReadPolicy(textPayload, context);
63
65
  let result;
64
66
  if (textPayload.startsWith(PREFIX_ENC_COMPRESSED)) {
65
67
  const rawBuf = Buffer.from(textPayload.slice(PREFIX_ENC_COMPRESSED.length), "base64");
66
- const decryptedBuf = enc.decryptBuffer(rawBuf);
68
+ const decryptedBuf = enc.decryptBuffer(rawBuf, context);
67
69
  const decompressed = decompressBuffer(decryptedBuf, cmpAlgo !== "none" ? cmpAlgo : "brotli");
68
70
  result = decompressed.toString("utf8");
69
71
  } else if (textPayload.startsWith(PREFIX_COMPRESSED)) {
@@ -71,7 +73,7 @@ parentPort.on(
71
73
  const decompressed = decompressBuffer(rawBuf, cmpAlgo !== "none" ? cmpAlgo : "brotli");
72
74
  result = decompressed.toString("utf8");
73
75
  } else {
74
- result = enc.decrypt(textPayload);
76
+ result = enc.decrypt(textPayload, context);
75
77
  }
76
78
  if (result.length >= 131072) {
77
79
  const outBuf = Buffer.from(result, "utf8");