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
package/src/edge/types.ts CHANGED
@@ -22,13 +22,19 @@ export interface IEdgeRemoteStorage {
22
22
  /** Optional clear by prefix or all keys. */
23
23
  clear?(prefix?: string): Promise<void>;
24
24
 
25
- /** Optional atomic or monotonic tag version increment for generational tag invalidation. */
25
+ /** Enumerate complete keys under a literal prefix in bounded pages. Required for remote wildcard tags. */
26
+ scanKeys?(prefix: string): AsyncIterable<string>;
27
+
28
+ /** Counter semantics; Workers KV is eventually consistent, not an atomic authority. */
29
+ readonly tagConsistency?: 'atomic' | 'eventual';
30
+
31
+ /** Optional atomic or monotonic tag increment. The service supplies the complete typed storage key; adapters must use it unchanged. */
26
32
  incrementTagVersion?(tag: string): Promise<number>;
27
33
 
28
- /** Optional tag version retrieval. */
34
+ /** Optional tag version retrieval by complete typed storage key. */
29
35
  getTagVersion?(tag: string): Promise<number>;
30
36
 
31
- /** Optional batch tag version retrieval. */
37
+ /** Optional batch tag retrieval; result keys must match the complete supplied storage keys. */
32
38
  batchGetTagVersions?(tags: string[]): Promise<Record<string, number>>;
33
39
  }
34
40
 
@@ -84,7 +90,7 @@ export interface EdgeCacheOptions {
84
90
  mode?: 'aes-256-gcm' | 'aes-128-gcm';
85
91
  };
86
92
 
87
- /** Multi-tenant key namespace prefix. */
93
+ /** Namespace encoded into a v3 storage keyspace with disjoint data/tag domains. Upgrades start cold; coordinate writers. Use a separate namespace from Node, whose value format differs. */
88
94
  namespace?: string;
89
95
 
90
96
  /** OpenTelemetry-compatible tracer for distributed tracing. */
@@ -96,6 +102,8 @@ export interface EdgeCacheOptions {
96
102
  * - `IEdgeBloomFilter`: a custom or configured `WasmBloomFilter` or `Murmur3BloomFilter` instance.
97
103
  */
98
104
  bloomFilter?: boolean | IEdgeBloomFilter;
105
+ /** Only enable when the filter is an externally maintained, complete remote key set. Default: false. */
106
+ bloomFilterAuthoritative?: boolean;
99
107
  }
100
108
 
101
109
  /**
@@ -123,6 +131,8 @@ export interface UpstashRedisOptions {
123
131
 
124
132
  /** Optional custom fetch implementation (defaults to globalThis.fetch). */
125
133
  fetch?: typeof globalThis.fetch;
134
+ /** Allow an explicit unscoped clear() to execute FLUSHDB. Default: false. */
135
+ dangerouslyFlushDatabase?: boolean;
126
136
  }
127
137
 
128
138
  /**
@@ -149,7 +159,7 @@ export interface CloudflareDOStorage {
149
159
  put<T = unknown>(entries: Record<string, T>): Promise<void>;
150
160
  delete(key: string): Promise<boolean>;
151
161
  delete(keys: string[]): Promise<number>;
152
- list?<T = unknown>(options?: { prefix?: string; limit?: number }): Promise<Map<string, T>>;
162
+ list?<T = unknown>(options?: { prefix?: string; limit?: number; startAfter?: string }): Promise<Map<string, T>>;
153
163
  }
154
164
 
155
165
  /**
@@ -218,6 +228,8 @@ export interface EdgeExportSnapshotOptions {
218
228
  */
219
229
  export interface EdgeSnapshotPayload {
220
230
  version: number;
231
+ /** Encoded storage namespace identity, not the raw namespace option. */
232
+ namespace: string;
221
233
  writtenAt: number;
222
234
  entries: Array<{
223
235
  key: string;
package/src/encryption.ts CHANGED
@@ -57,6 +57,8 @@ const TAG_BYTES = 16; // 128-bit auth tag
57
57
  // ── Redis prefixes ────────────────────────────────────────────────────────────
58
58
  const PREFIX_256 = 'enc:v1:'; // AES-256-GCM (legacy-compatible)
59
59
  const PREFIX_128 = 'a128:v1:'; // AES-128-GCM
60
+ const PREFIX_BOUND_256 = 'enc:v2:'; // GCM with caller-supplied authenticated context
61
+ const PREFIX_BOUND_128 = 'a128:v2:';
60
62
  const PREFIX_XOR = 'xor:v1:'; // XOR obfuscation
61
63
 
62
64
  // ── Binary magic headers (8 bytes each) ──────────────────────────────────────
@@ -64,6 +66,8 @@ const PREFIX_XOR = 'xor:v1:'; // XOR obfuscation
64
66
  const MAGIC_256 = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x45, 0x4e, 0x43]);
65
67
  /** "TRIC1128" — AES-128-GCM disk blob */
66
68
  const MAGIC_128 = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x31, 0x32, 0x38]);
69
+ const MAGIC_BOUND_256 = Buffer.from('TRIC2ENC');
70
+ const MAGIC_BOUND_128 = Buffer.from('TRIC2128');
67
71
  /** "TRIC1XOR" — XOR-obfuscated disk blob */
68
72
  const MAGIC_XOR = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x58, 0x4f, 0x52]);
69
73
  /** "TRIC1CTR" — AES-128-CTR disk blob */
@@ -86,6 +90,7 @@ export class CacheEncryption {
86
90
  private _mode: EncryptionMode;
87
91
  /** Fail-closed on invalid key material when opted in via constructor opts. */
88
92
  private readonly _strictKeyValidation: boolean;
93
+ private readonly _allowLegacyPlaintextRead: boolean;
89
94
  private _prevKey: Buffer | null = null;
90
95
  private _prevKeyObj: KeyObject | null = null;
91
96
  private _prevMode: EncryptionMode = 'aes-256-gcm';
@@ -172,7 +177,7 @@ export class CacheEncryption {
172
177
  mode: EncryptionMode = 'aes-256-gcm',
173
178
  previousKeyBase64?: string,
174
179
  previousMode?: EncryptionMode,
175
- opts?: { strictKeyValidation?: boolean },
180
+ opts?: { strictKeyValidation?: boolean; allowLegacyPlaintextRead?: boolean },
176
181
  ) {
177
182
  const logger: ILogger = (typeof loggerOrMode === 'object' && loggerOrMode !== null)
178
183
  ? loggerOrMode
@@ -181,6 +186,7 @@ export class CacheEncryption {
181
186
  ? loggerOrMode
182
187
  : mode;
183
188
  this._strictKeyValidation = opts?.strictKeyValidation ?? false;
189
+ this._allowLegacyPlaintextRead = opts?.allowLegacyPlaintextRead ?? true;
184
190
 
185
191
  this._mode = resolvedMode;
186
192
  if (keyBase64 === undefined || keyBase64 === null) {
@@ -277,12 +283,14 @@ export class CacheEncryption {
277
283
  mode: EncryptionMode;
278
284
  prevKeyBase64: string | undefined;
279
285
  prevMode: EncryptionMode;
286
+ allowLegacyPlaintextRead: boolean;
280
287
  } {
281
288
  return {
282
289
  keyBase64: this._key ? this._key.toString('base64') : '',
283
290
  mode: this._mode,
284
291
  prevKeyBase64: this._prevKey ? this._prevKey.toString('base64') : undefined,
285
292
  prevMode: this._prevMode,
293
+ allowLegacyPlaintextRead: this._allowLegacyPlaintextRead,
286
294
  };
287
295
  }
288
296
 
@@ -336,7 +344,7 @@ export class CacheEncryption {
336
344
  * Returns a mode-prefixed base64 string when a key is configured;
337
345
  * otherwise returns the original string unchanged (backward-compatible).
338
346
  */
339
- encrypt(plaintext: string): string {
347
+ encrypt(plaintext: string, context?: string): string {
340
348
  if (!this._key) return plaintext;
341
349
  if (this._mode === 'xor') {
342
350
  // WARNING: XOR is NOT cryptographic — obfuscation only.
@@ -355,9 +363,12 @@ export class CacheEncryption {
355
363
  return PREFIX_CTR + out.toString('base64');
356
364
  }
357
365
  const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
358
- const prefix = this._mode === 'aes-128-gcm' ? PREFIX_128 : PREFIX_256;
366
+ const prefix = context === undefined
367
+ ? (this._mode === 'aes-128-gcm' ? PREFIX_128 : PREFIX_256)
368
+ : (this._mode === 'aes-128-gcm' ? PREFIX_BOUND_128 : PREFIX_BOUND_256);
359
369
  const iv = this._nextIV();
360
370
  const c = createCipheriv(algo, this._keyObj!, iv);
371
+ if (context !== undefined) c.setAAD(Buffer.from(context, 'utf8'));
361
372
  const enc = c.update(plaintext, 'utf8'); // GCM: final() emits no bytes
362
373
  c.final(); // finalise — makes auth tag available
363
374
  const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
@@ -372,20 +383,31 @@ export class CacheEncryption {
372
383
  * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
373
384
  * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
374
385
  */
375
- decrypt(value: string): string {
386
+ assertReadPolicy(value: string | Buffer, context?: string): void {
387
+ if (!this.isEnabled || this._allowLegacyPlaintextRead || !this._mode.endsWith('-gcm')) return;
388
+ if (context === undefined) throw new Error('Authenticated cache read requires context');
389
+ if (typeof value === 'string') {
390
+ if (value.startsWith('ecp:v1:')) return this.assertReadPolicy(Buffer.from(value.slice(7), 'base64'), context);
391
+ if (value.startsWith(PREFIX_BOUND_256) || value.startsWith(PREFIX_BOUND_128)) return;
392
+ } else if (value.subarray(0, 8).equals(MAGIC_BOUND_256) || value.subarray(0, 8).equals(MAGIC_BOUND_128)) return;
393
+ throw new Error('Legacy or plaintext cache value rejected; opt in to allowLegacyPlaintextRead for migration');
394
+ }
395
+
396
+ decrypt(value: string, context?: string): string {
397
+ this.assertReadPolicy(value, context);
376
398
  try {
377
- return this._decryptWithKey(value, this._key, this._keyObj);
399
+ return this._decryptWithKey(value, this._key, this._keyObj, context);
378
400
  } catch (primaryErr) {
379
401
  if (this._prevKey) {
380
402
  try {
381
- return this._decryptWithKey(value, this._prevKey, this._prevKeyObj);
403
+ return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, context);
382
404
  } catch { /* ignore — fall through to re-throw primary */ }
383
405
  }
384
406
  throw primaryErr;
385
407
  }
386
408
  }
387
409
 
388
- private _decryptWithKey(value: string, key: Buffer | null, keyObj: KeyObject | null): string {
410
+ private _decryptWithKey(value: string, key: Buffer | null, keyObj: KeyObject | null, context?: string): string {
389
411
  if (value.startsWith(PREFIX_XOR)) {
390
412
  if (!key) throw new Error('Cannot decrypt: encryption key is not set');
391
413
  // WARNING: XOR is NOT cryptographic — obfuscation only.
@@ -407,17 +429,20 @@ export class CacheEncryption {
407
429
  const fin = d.final(); // CTR: almost always empty — concat before UTF-8 decode to avoid split-sequence corruption
408
430
  return (fin.length > 0 ? Buffer.concat([plain, fin]) : plain).toString('utf8');
409
431
  }
410
- const is256 = value.startsWith(PREFIX_256);
411
- const is128 = value.startsWith(PREFIX_128);
432
+ const bound = value.startsWith(PREFIX_BOUND_256) || value.startsWith(PREFIX_BOUND_128);
433
+ const is256 = value.startsWith(PREFIX_256) || value.startsWith(PREFIX_BOUND_256);
434
+ const is128 = value.startsWith(PREFIX_128) || value.startsWith(PREFIX_BOUND_128);
412
435
  if (!is256 && !is128) return value;
413
436
  if (!keyObj) throw new Error('Cannot decrypt: encryption key is not set');
414
- const prefix = is128 ? PREFIX_128 : PREFIX_256;
437
+ if (bound && context === undefined) throw new Error('Encrypted value requires authenticated context');
438
+ const prefix = bound ? (is128 ? PREFIX_BOUND_128 : PREFIX_BOUND_256) : (is128 ? PREFIX_128 : PREFIX_256);
415
439
  const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
416
440
  const combined = Buffer.from(value.slice(prefix.length), 'base64');
417
441
  const iv = combined.subarray(0, IV_BYTES);
418
442
  const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
419
443
  const ct = combined.subarray(IV_BYTES + TAG_BYTES);
420
444
  const d = createDecipheriv(algo, keyObj, iv);
445
+ if (bound) d.setAAD(Buffer.from(context!, 'utf8'));
421
446
  d.setAuthTag(tag);
422
447
  const plain = d.update(ct); // GCM: final() emits no bytes
423
448
  d.final(); // verifies auth tag — throws on tamper
@@ -427,7 +452,7 @@ export class CacheEncryption {
427
452
  // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
428
453
 
429
454
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
430
- encryptBuffer(data: Buffer): Buffer {
455
+ encryptBuffer(data: Buffer, context?: string): Buffer {
431
456
  if (!this._key) return data;
432
457
  if (this._mode === 'xor') {
433
458
  // WARNING: XOR is NOT cryptographic — obfuscation only.
@@ -450,10 +475,13 @@ export class CacheEncryption {
450
475
  if (fin.length > 0) fin.copy(out, MAGIC_LEN + CTR_IV_BYTES + enc.length);
451
476
  return out;
452
477
  }
453
- const magic = this._mode === 'aes-128-gcm' ? MAGIC_128 : MAGIC_256;
478
+ const magic = context === undefined
479
+ ? (this._mode === 'aes-128-gcm' ? MAGIC_128 : MAGIC_256)
480
+ : (this._mode === 'aes-128-gcm' ? MAGIC_BOUND_128 : MAGIC_BOUND_256);
454
481
  const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
455
482
  const iv = this._nextIV();
456
483
  const c = createCipheriv(algo, this._keyObj!, iv);
484
+ if (context !== undefined) c.setAAD(Buffer.from(context, 'utf8'));
457
485
  const enc = c.update(data); // GCM: final() emits no bytes
458
486
  c.final(); // finalise — makes auth tag available
459
487
  // Single pre-allocated output buffer: magic(8) | iv(12) | tag(16) | ciphertext(N)
@@ -470,20 +498,21 @@ export class CacheEncryption {
470
498
  * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
471
499
  * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
472
500
  */
473
- decryptBuffer(data: Buffer): Buffer {
501
+ decryptBuffer(data: Buffer, context?: string): Buffer {
502
+ this.assertReadPolicy(data, context);
474
503
  try {
475
- return this._decryptBufferWithKey(data, this._key, this._keyObj);
504
+ return this._decryptBufferWithKey(data, this._key, this._keyObj, context);
476
505
  } catch (primaryErr) {
477
506
  if (this._prevKey) {
478
507
  try {
479
- return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj);
508
+ return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj, context);
480
509
  } catch { /* ignore — re-throw primary */ }
481
510
  }
482
511
  throw primaryErr;
483
512
  }
484
513
  }
485
514
 
486
- private _decryptBufferWithKey(data: Buffer, key: Buffer | null, keyObj: KeyObject | null): Buffer {
515
+ private _decryptBufferWithKey(data: Buffer, key: Buffer | null, keyObj: KeyObject | null, context?: string): Buffer {
487
516
  if (data.length < MAGIC_LEN) return data;
488
517
  const magic = data.subarray(0, MAGIC_LEN);
489
518
 
@@ -506,15 +535,18 @@ export class CacheEncryption {
506
535
  const fin = d.final(); // CTR: almost always empty — captured defensively
507
536
  return fin.length > 0 ? Buffer.concat([plain, fin]) : plain;
508
537
  }
509
- const is256 = magic.equals(MAGIC_256);
510
- const is128 = magic.equals(MAGIC_128);
538
+ const bound = magic.equals(MAGIC_BOUND_256) || magic.equals(MAGIC_BOUND_128);
539
+ const is256 = magic.equals(MAGIC_256) || magic.equals(MAGIC_BOUND_256);
540
+ const is128 = magic.equals(MAGIC_128) || magic.equals(MAGIC_BOUND_128);
511
541
  if (!is256 && !is128) return data;
512
542
  if (!keyObj) throw new Error('Cannot decrypt buffer: encryption key is not set');
543
+ if (bound && context === undefined) throw new Error('Encrypted buffer requires authenticated context');
513
544
  const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
514
545
  const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
515
546
  const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
516
547
  const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
517
548
  const d = createDecipheriv(algo, keyObj, iv);
549
+ if (bound) d.setAAD(Buffer.from(context!, 'utf8'));
518
550
  d.setAuthTag(tag);
519
551
  const plain = d.update(ct); // GCM: final() emits no bytes
520
552
  d.final(); // verifies auth tag — throws on tamper
package/src/env.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  declare module 'lz4js' {
2
2
  const lz4js: {
3
3
  compress: (buf: Uint8Array | Buffer) => Uint8Array;
4
- decompress: (buf: Uint8Array | Buffer) => Uint8Array;
4
+ decompress: (buf: Uint8Array | Buffer, maxSize?: number) => Uint8Array;
5
5
  };
6
6
  export default lz4js;
7
7
  }
package/src/errors.ts ADDED
@@ -0,0 +1,12 @@
1
+ /** Thrown when the opt-in read gate lacks fresh invalidation consumer proof. */
2
+ export class CacheInvalidationUnavailableError extends Error {
3
+ readonly reason: string;
4
+ readonly detectedAt: number | null;
5
+
6
+ constructor(reason: string, detectedAt: number | null) {
7
+ super(`TriCacheError: cached reads are unavailable because invalidation is not ready (${reason})`);
8
+ this.name = 'CacheInvalidationUnavailableError';
9
+ this.reason = reason;
10
+ this.detectedAt = detectedAt;
11
+ }
12
+ }
package/src/hono/index.ts CHANGED
@@ -20,6 +20,8 @@ import {
20
20
  buildDeterministicKey,
21
21
  generateETag,
22
22
  shouldSkipCache,
23
+ isShareableHttpResponse,
24
+ matchesETag,
23
25
  type KeyDerivationOptions,
24
26
  } from '../http/utils.js';
25
27
 
@@ -40,12 +42,12 @@ export interface HonoCacheContext {
40
42
  clone?: () => { text: () => Promise<string> };
41
43
  body?: unknown;
42
44
  };
43
- body: (data: unknown, status?: number, headers?: Record<string, string>) => unknown;
45
+ body: (...args: any[]) => any;
44
46
  executionCtx?: unknown;
45
47
  }
46
48
 
47
49
  export type HonoNext = () => Promise<void>;
48
- export type HonoMiddleware = (c: HonoCacheContext, next: HonoNext) => Promise<unknown>;
50
+ export type HonoMiddleware = (c: HonoCacheContext, next: HonoNext) => Promise<Response | void>;
49
51
 
50
52
  export interface HonoCacheOptions extends Omit<WrapOptions, 'tags'>, Omit<KeyDerivationOptions, 'keyGenerator'> {
51
53
  /** TriCache instance. If omitted, lazily resolves the default singleton via CacheService.create(). */
@@ -58,6 +60,8 @@ export interface HonoCacheOptions extends Omit<WrapOptions, 'tags'>, Omit<KeyDer
58
60
  skipCache?: (c: HonoCacheContext) => boolean;
59
61
  /** Dynamic tags derivation from the Hono context. */
60
62
  tags?: string[] | ((c: HonoCacheContext) => string[]);
63
+ /** @deprecated Response refreshes run on live requests. Use data-level cache.get()/wrap() for SWR. */
64
+ swr?: number;
61
65
  }
62
66
 
63
67
  export interface CachedHonoResponse {
@@ -71,7 +75,7 @@ export interface CachedHonoResponse {
71
75
  function readRequestHeader(c: HonoCacheContext, name: string): string | undefined {
72
76
  const headerFn = c.req.header;
73
77
  if (typeof headerFn === 'function') {
74
- const viaFn = headerFn(name) ?? headerFn(name.toLowerCase());
78
+ const viaFn = headerFn.call(c.req, name) ?? headerFn.call(c.req, name.toLowerCase());
75
79
  if (viaFn !== undefined && viaFn !== null && viaFn !== '') {
76
80
  return viaFn;
77
81
  }
@@ -95,6 +99,10 @@ function toRequestLike(c: HonoCacheContext, headerWhitelist?: string[]) {
95
99
  const headers: Record<string, string | undefined> = {};
96
100
  const cacheControl = readRequestHeader(c, 'cache-control');
97
101
  const ifNoneMatch = readRequestHeader(c, 'if-none-match');
102
+ for (const name of ['authorization', 'cookie', 'range', 'x-api-key', 'x-auth-token']) {
103
+ const value = readRequestHeader(c, name);
104
+ if (value) headers[name] = value;
105
+ }
98
106
 
99
107
  if (cacheControl) {
100
108
  headers['cache-control'] = cacheControl;
@@ -133,8 +141,8 @@ function applyHonoCachedResponse(
133
141
  c: HonoCacheContext,
134
142
  cached: CachedHonoResponse,
135
143
  ifNoneMatch: string | undefined,
136
- ): unknown {
137
- if (cached.etag && ifNoneMatch === cached.etag) {
144
+ ): Response | void {
145
+ if (cached.etag && matchesETag(ifNoneMatch, cached.etag)) {
138
146
  const notModifiedHeaders: Record<string, string> = { ETag: cached.etag };
139
147
  if (cached.headers?.['cache-control']) notModifiedHeaders['Cache-Control'] = cached.headers['cache-control'];
140
148
  if (cached.headers?.['vary']) notModifiedHeaders['Vary'] = cached.headers['vary'];
@@ -159,6 +167,7 @@ function applyHonoCachedResponse(
159
167
  async function snapshotHonoResponse(
160
168
  c: HonoCacheContext,
161
169
  etag: boolean,
170
+ options: KeyDerivationOptions,
162
171
  ): Promise<CachedHonoResponse> {
163
172
  const res = c.res;
164
173
  if (!res) {
@@ -178,6 +187,7 @@ async function snapshotHonoResponse(
178
187
  }
179
188
 
180
189
  const status = res.status ?? 200;
190
+ if (!isShareableHttpResponse(status, name => res.headers?.get?.(name), options)) return { body: '', contentType, status: 0 };
181
191
  if (!isCacheableStatus(status)) {
182
192
  return { body: '', contentType, status };
183
193
  }
@@ -249,7 +259,6 @@ export function cacheMiddleware(options: HonoCacheOptions = {}): HonoMiddleware
249
259
  cache,
250
260
  etag = true,
251
261
  ttl = 300,
252
- swr,
253
262
  tags,
254
263
  skipCache,
255
264
  keyGenerator,
@@ -265,7 +274,7 @@ export function cacheMiddleware(options: HonoCacheOptions = {}): HonoMiddleware
265
274
  }
266
275
 
267
276
  const reqLike = toRequestLike(c, headerWhitelist);
268
- if (shouldSkipCache(reqLike, skipCache ? () => skipCache(c) : undefined)) {
277
+ if (shouldSkipCache(reqLike, skipCache ? () => skipCache(c) : undefined, { ...options, keyGenerator: keyGenerator ? () => keyGenerator(c) : undefined })) {
269
278
  return await next();
270
279
  }
271
280
 
@@ -289,14 +298,15 @@ export function cacheMiddleware(options: HonoCacheOptions = {}): HonoMiddleware
289
298
  async () => {
290
299
  ranNext = true;
291
300
  await next();
292
- const snapshot = await snapshotHonoResponse(c, etag);
301
+ const snapshot = await snapshotHonoResponse(c, etag, { headerWhitelist, keyGenerator: keyGenerator ? () => keyGenerator(c) : undefined });
293
302
  if (!isCacheableStatus(snapshot.status)) {
294
303
  throw new NonCacheableHonoResponseError(snapshot);
295
304
  }
296
305
  return snapshot;
297
306
  },
298
307
  ttl,
299
- { swr, tags: resolvedTags },
308
+ // Never invoke a completed Hono next() chain from background work.
309
+ { swr: 0, tags: resolvedTags },
300
310
  );
301
311
 
302
312
  return applyHonoCachedResponse(c, cached, ifNoneMatch);
@@ -4,6 +4,9 @@ import {
4
4
  buildDeterministicKey,
5
5
  generateETag,
6
6
  shouldSkipCache,
7
+ isCacheableHttpResponse,
8
+ isShareableHttpResponse,
9
+ matchesETag,
7
10
  type KeyDerivationOptions,
8
11
  } from './utils.js';
9
12
 
@@ -16,6 +19,8 @@ export interface ExpressCacheOptions extends Omit<WrapOptions, 'tags'>, KeyDeriv
16
19
  skipCache?: (req: any) => boolean;
17
20
  /** Dynamic tags derivation from request. */
18
21
  tags?: string[] | ((req: any) => string[]);
22
+ /** @deprecated Response refreshes run on live requests. Use data-level cache.get()/wrap() for SWR. */
23
+ swr?: number;
19
24
  }
20
25
 
21
26
  export interface CachedHttpResponse {
@@ -23,6 +28,14 @@ export interface CachedHttpResponse {
23
28
  contentType?: string;
24
29
  etag?: string;
25
30
  status: number;
31
+ binary?: boolean;
32
+ headers?: Record<string, string | string[]>;
33
+ }
34
+
35
+ class UncacheableHttpResponse extends Error {
36
+ constructor(readonly response: CachedHttpResponse, readonly shareable: boolean) {
37
+ super('Response is not cacheable');
38
+ }
26
39
  }
27
40
 
28
41
  /**
@@ -56,11 +69,11 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
56
69
  cache,
57
70
  etag = true,
58
71
  ttl = 300,
59
- swr,
60
72
  tags,
61
73
  skipCache,
62
74
  keyGenerator,
63
75
  headerWhitelist,
76
+ cacheAuthenticated,
64
77
  } = options;
65
78
 
66
79
  return async (req: any, res: any, next: any) => {
@@ -69,7 +82,7 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
69
82
  return next();
70
83
  }
71
84
 
72
- if (shouldSkipCache(req, skipCache)) {
85
+ if (shouldSkipCache(req, skipCache, options)) {
73
86
  return next();
74
87
  }
75
88
 
@@ -79,7 +92,8 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
79
92
  activeCache = CacheService.create();
80
93
  }
81
94
 
82
- const key = buildDeterministicKey(req, { keyGenerator, headerWhitelist });
95
+ const keyOptions = { keyGenerator, headerWhitelist, cacheAuthenticated };
96
+ const key = buildDeterministicKey(req, keyOptions);
83
97
  const ifNoneMatch = req.headers ? (req.headers['if-none-match'] || req.headers['If-None-Match']) : undefined;
84
98
 
85
99
  const resolvedTags = typeof tags === 'function' ? tags(req) : tags;
@@ -94,15 +108,18 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
94
108
  const rawJson = res.json;
95
109
  const rawSend = res.send;
96
110
  const rawEnd = res.end;
111
+ const rawWrite = res.write;
97
112
  const origJson = rawJson?.bind(res);
98
113
  const origSend = rawSend?.bind(res);
99
114
  const origEnd = rawEnd?.bind(res);
100
115
  let settled = false;
116
+ let streamed = false;
101
117
 
102
118
  const cleanup = () => {
103
119
  if (rawJson !== undefined) res.json = rawJson;
104
120
  if (rawSend !== undefined) res.send = rawSend;
105
121
  if (rawEnd !== undefined) res.end = rawEnd;
122
+ if (rawWrite !== undefined) res.write = rawWrite;
106
123
  res.removeListener?.('close', onClose);
107
124
  };
108
125
 
@@ -110,8 +127,20 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
110
127
  if (settled) return;
111
128
  settled = true;
112
129
  respondedLocally = true;
130
+ response.binary = Buffer.isBuffer(response.body);
131
+ if (typeof res.getHeaders === 'function') {
132
+ const headers: Record<string, string | string[]> = {};
133
+ for (const [name, value] of Object.entries(res.getHeaders())) {
134
+ if (!['content-length', 'transfer-encoding', 'connection', 'set-cookie', 'etag', 'content-type'].includes(name.toLowerCase()) && value != null) {
135
+ headers[name] = Array.isArray(value) ? value as string[] : String(value);
136
+ }
137
+ }
138
+ response.headers = headers;
139
+ }
140
+ const header = (name: string) => res.getHeader?.(name);
113
141
  cleanup();
114
- resolve(response);
142
+ if (!streamed && isCacheableHttpResponse(response.status, header, keyOptions)) resolve(response);
143
+ else reject(new UncacheableHttpResponse(response, !streamed && isShareableHttpResponse(response.status, header, keyOptions)));
115
144
  };
116
145
 
117
146
  const onClose = () => {
@@ -123,6 +152,10 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
123
152
  };
124
153
 
125
154
  res.once?.('close', onClose);
155
+ if (rawWrite) res.write = (...args: unknown[]) => {
156
+ streamed = true;
157
+ return rawWrite.apply(res, args);
158
+ };
126
159
 
127
160
  const getStatusCode = () => (res.statusCode ?? 200);
128
161
 
@@ -134,7 +167,7 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
134
167
 
135
168
  settle({ body, contentType, etag: bodyEtag, status });
136
169
 
137
- if (status >= 200 && status < 300 && ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
170
+ if (isCacheableHttpResponse(status, name => res.getHeader?.(name), keyOptions) && bodyEtag && matchesETag(ifNoneMatch, bodyEtag)) {
138
171
  res.status?.(304);
139
172
  origEnd?.();
140
173
  return;
@@ -155,7 +188,7 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
155
188
 
156
189
  settle({ body, contentType, etag: bodyEtag, status });
157
190
 
158
- if (status >= 200 && status < 300 && ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
191
+ if (isCacheableHttpResponse(status, name => res.getHeader?.(name), keyOptions) && bodyEtag && matchesETag(ifNoneMatch, bodyEtag)) {
159
192
  res.status?.(304);
160
193
  origEnd?.();
161
194
  return;
@@ -169,13 +202,13 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
169
202
  }
170
203
 
171
204
  if (origEnd) {
172
- res.end = (body?: unknown) => {
205
+ res.end = (body?: unknown, ...args: unknown[]) => {
173
206
  const status = getStatusCode();
174
207
  const bodyEtag = etag && body != null ? generateETag(body) : undefined;
175
208
  const contentType = res.getHeader?.('content-type') as string | undefined;
176
209
 
177
210
  settle({ body, contentType, etag: bodyEtag, status });
178
- return origEnd(body as never);
211
+ return origEnd(body, ...args);
179
212
  };
180
213
  }
181
214
 
@@ -191,19 +224,15 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
191
224
  });
192
225
  },
193
226
  ttl,
194
- { swr, tags: resolvedTags }
227
+ // res/next belong to this request and cannot be reused for background SWR.
228
+ { swr: 0, tags: resolvedTags }
195
229
  );
196
230
 
197
- // Status gate: only cache 2xx successful responses
198
- const isNon2xx = typeof cached.status === 'number' && (cached.status < 200 || cached.status >= 300);
199
- if (isNon2xx) {
200
- await activeCache.delete(key).catch(() => {});
201
- }
202
-
203
231
  if (!respondedLocally && !res.headersSent) {
204
- if (!isNon2xx && cached.etag) {
232
+ for (const [name, value] of Object.entries(cached.headers ?? {})) res.setHeader?.(name, value);
233
+ if (cached.etag) {
205
234
  if (res.setHeader) res.setHeader('ETag', cached.etag);
206
- if (ifNoneMatch === cached.etag) {
235
+ if (matchesETag(ifNoneMatch, cached.etag)) {
207
236
  return res.status(304).end();
208
237
  }
209
238
  }
@@ -216,6 +245,11 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
216
245
  res.status(cached.status);
217
246
  }
218
247
 
248
+ if (req.method === 'HEAD') return res.end?.();
249
+ if (cached.binary) {
250
+ const body = Buffer.isBuffer(cached.body) ? cached.body : Buffer.from((cached.body as { data: number[] }).data);
251
+ return res.send ? res.send(body) : res.end?.(body);
252
+ }
219
253
  if (typeof cached.body === 'object' && cached.body !== null && res.json) {
220
254
  return res.json(cached.body);
221
255
  } else if (res.send) {
@@ -225,6 +259,17 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
225
259
  }
226
260
  }
227
261
  } catch (err) {
262
+ if (err instanceof UncacheableHttpResponse) {
263
+ if (respondedLocally || res.headersSent) return;
264
+ // Never share a private, varied, cookie-setting, or partial response with another request.
265
+ if (!err.shareable) return next();
266
+ const response = err.response;
267
+ if (response.contentType) res.setHeader?.('Content-Type', response.contentType);
268
+ res.status?.(response.status);
269
+ return typeof response.body === 'object' && response.body !== null && !response.binary && res.json
270
+ ? res.json(response.body)
271
+ : res.send ? res.send(response.body) : res.end?.(response.body);
272
+ }
228
273
  next(err);
229
274
  }
230
275
  };