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/cli.ts CHANGED
@@ -8,9 +8,10 @@
8
8
  * npx tricache clear [--redis redis://localhost:6379] [--namespace <ns>] [--prefix <prefix>]
9
9
  */
10
10
 
11
- import { readFileSync } from 'node:fs';
12
11
  import { parseArgs } from 'node:util';
12
+ import pkg from '../package.json' with { type: 'json' };
13
13
  import { CacheService } from './cache-service.js';
14
+ import { Redis } from 'ioredis';
14
15
  import {
15
16
  IpcTelemetryClient,
16
17
  resolveIpcSocketPath,
@@ -60,14 +61,7 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
60
61
  // (bin/tricache.js). Output must go directly to process stdout without logger prefixes
61
62
  // to support UNIX pipes, terminal formatting, and automated tooling.
62
63
  if (values.version || command === 'version') {
63
- let version = '1.0.1';
64
- try {
65
- const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
66
- if (pkg?.version) version = pkg.version;
67
- } catch {
68
- // fallback to default version
69
- }
70
- console.log(`tricache v${version}`);
64
+ console.log(`tricache v${pkg.version}`);
71
65
  return;
72
66
  }
73
67
 
@@ -178,19 +172,35 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
178
172
  }
179
173
 
180
174
  const redisStr = typeof values.redis === 'string' ? values.redis : undefined;
181
- const redisHost = redisStr ? redisStr.replace(/^redis:\/\//, '').split(':')[0] : undefined;
182
- const redisPort = typeof values.port === 'string'
183
- ? parseInt(values.port, 10)
184
- : (redisStr && redisStr.includes(':') ? parseInt(redisStr.split(':')[1], 10) : 6379);
175
+ let redisHost: string | undefined;
176
+ let redisPort = 6379;
177
+ let redisClient: Redis | undefined;
178
+ if (redisStr) {
179
+ try {
180
+ const url = new URL(redisStr.includes('://') ? redisStr : `redis://${redisStr}`);
181
+ if (url.protocol !== 'redis:' && url.protocol !== 'rediss:') throw new Error('Unsupported Redis URL scheme');
182
+ redisPort = Number(typeof values.port === 'string' ? values.port : url.port || 6379);
183
+ if (!Number.isInteger(redisPort) || redisPort < 1 || redisPort > 65535) throw new Error('Invalid Redis port');
184
+ url.port = String(redisPort);
185
+ redisHost = url.hostname;
186
+ redisClient = new Redis(url.toString(), { lazyConnect: true, commandTimeout: 2500, maxRetriesPerRequest: 1 });
187
+ redisClient.on('error', () => {}); // CacheService reports operation failures without exposing credentials.
188
+ } catch {
189
+ console.error('Invalid Redis host, URL, or port');
190
+ process.exitCode = 1;
191
+ return;
192
+ }
193
+ }
185
194
  const namespace = typeof values.namespace === 'string' ? values.namespace : undefined;
186
195
  const diskCacheDir = typeof values.disk === 'string' ? values.disk : undefined;
187
196
 
188
197
  const cache = new CacheService({
189
198
  redisHost,
190
199
  redisPort,
200
+ redisClient,
191
201
  namespace,
192
202
  diskCacheDir,
193
- disableRedis: !redisHost,
203
+ disableRedis: !redisClient,
194
204
  });
195
205
 
196
206
  try {
@@ -245,6 +255,7 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
245
255
  }
246
256
  } finally {
247
257
  await cache.destroy();
258
+ redisClient?.disconnect();
248
259
  }
249
260
  }
250
261
 
package/src/codec.ts CHANGED
@@ -22,14 +22,14 @@ export interface CacheCodecOptions {
22
22
  moreTypes?: boolean;
23
23
  /**
24
24
  * Decode MessagePack maps as plain JavaScript objects.
25
- * Default: true (ensures plain JS objects and standard maps decode to plain objects).
25
+ * Default: false (preserves Map; record-encoded plain objects remain objects).
26
26
  */
27
27
  mapsAsObjects?: boolean;
28
28
  }
29
29
 
30
30
  /**
31
31
  * CacheCodec wraps msgpackr's Packr/Unpackr to provide unified, high-performance binary
32
- * serialization across L1 in-memory buffers, L1.5 disk spill, and cold-start snapshots.
32
+ * serialization across L1 in-memory buffers, L1.5 disk spill, Redis, and cold-start snapshots.
33
33
  */
34
34
  export class CacheCodec {
35
35
  private readonly packr: Packr;
@@ -39,7 +39,7 @@ export class CacheCodec {
39
39
  useToJSON: options?.useToJSON ?? true,
40
40
  useRecords: options?.useRecords ?? true,
41
41
  moreTypes: options?.moreTypes ?? true,
42
- mapsAsObjects: options?.mapsAsObjects ?? true,
42
+ mapsAsObjects: options?.mapsAsObjects ?? false,
43
43
  };
44
44
  this.packr = new Packr(packrOptions);
45
45
  }
@@ -1,13 +1,19 @@
1
1
  import zlib from 'zlib';
2
- import lz4js from 'lz4js';
3
- import { ZstdCodec } from 'zstd-codec';
2
+ import { createRequire } from 'node:module';
3
+ import { lz4DecodedSize } from './utils/lz4-size.js';
4
+
5
+ const requireCompression = createRequire(typeof __filename === 'string' ? __filename : import.meta.url);
6
+ type Lz4Codec = typeof import('lz4js')['default'];
7
+ let lz4js: Lz4Codec | undefined;
8
+ function getLz4(): Lz4Codec { return lz4js ??= requireCompression('lz4js'); }
4
9
 
5
10
  export type CompressionAlgorithm = 'brotli' | 'gzip' | 'zstd' | 'lz4' | 'none';
6
11
 
7
12
  export interface CustomCompressor {
8
13
  name: string;
9
14
  compress: (buf: Buffer) => Buffer;
10
- decompress: (buf: Buffer) => Buffer;
15
+ /** Honor maxOutputBytes during allocation; the returned size is also checked. */
16
+ decompress: (buf: Buffer, maxOutputBytes?: number) => Buffer;
11
17
  }
12
18
 
13
19
  export const PREFIX_COMPRESSED = 'cmp:v1:';
@@ -17,6 +23,7 @@ export const PREFIX_ENC_COMPRESSED = 'ecp:v1:';
17
23
  const COMPRESSION_MAGIC = Buffer.from([0x54, 0x52, 0x43, 0x01]);
18
24
 
19
25
  let zstdSimple: any = null;
26
+ let zstdGeneric: any = null;
20
27
  let zstdInitPromise: Promise<any> | null = null;
21
28
 
22
29
  /**
@@ -26,23 +33,21 @@ let zstdInitPromise: Promise<any> | null = null;
26
33
  export function initZstd(): Promise<any> {
27
34
  if (zstdSimple) return Promise.resolve(zstdSimple);
28
35
  if (!zstdInitPromise) {
29
- zstdInitPromise = new Promise((resolve) => {
36
+ zstdInitPromise = import('zstd-codec').then(({ ZstdCodec }) => new Promise((resolve) => {
30
37
  try {
31
38
  ZstdCodec.run((zstd: any) => {
32
39
  zstdSimple = new zstd.Simple();
40
+ zstdGeneric = new zstd.Generic();
33
41
  resolve(zstdSimple);
34
42
  });
35
43
  } catch {
36
44
  resolve(null);
37
45
  }
38
- });
46
+ })).catch(() => null);
39
47
  }
40
48
  return zstdInitPromise;
41
49
  }
42
50
 
43
- // Auto-start initialization immediately in the background
44
- initZstd().catch(() => {});
45
-
46
51
  export function isCompressed(buf: Buffer): boolean {
47
52
  return buf.length >= 4 && buf[0] === 0x54 && buf[1] === 0x52 && buf[2] === 0x43 && buf[3] === 0x01;
48
53
  }
@@ -66,10 +71,11 @@ export function compressBuffer(
66
71
  return zlib.gzipSync(buf, { level: 6 });
67
72
  }
68
73
  if (algorithm === 'lz4') {
69
- return Buffer.from(lz4js.compress(buf));
74
+ return Buffer.from(getLz4().compress(buf));
70
75
  }
71
76
  if (algorithm === 'zstd') {
72
77
  if (!zstdSimple) {
78
+ void initZstd();
73
79
  // If zstd WASM compile has not yet finished, fallback to fast Brotli level 4
74
80
  return zlib.brotliCompressSync(buf, {
75
81
  params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 4 },
@@ -82,13 +88,30 @@ export function compressBuffer(
82
88
 
83
89
  export const MAX_DECOMPRESS_BYTES = 25 * 1024 * 1024; // 25 MB decompression bomb safety ceiling
84
90
 
91
+ function decompressLz4(buf: Buffer): Buffer {
92
+ const size = lz4DecodedSize(buf, MAX_DECOMPRESS_BYTES);
93
+ const decoded = Buffer.from(getLz4().decompress(buf, size));
94
+ if (decoded.length !== size) throw new Error('tricache: corrupt LZ4 decoded size');
95
+ return decoded;
96
+ }
97
+
98
+ function decompressZstd(buf: Buffer): Buffer {
99
+ const size = zstdGeneric?.contentSize(buf);
100
+ if (!Number.isSafeInteger(size) || size < 0) throw new Error('tricache: Zstandard frame requires a bounded content size');
101
+ if (size > MAX_DECOMPRESS_BYTES) throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
102
+ const decoded = zstdSimple.decompress(buf);
103
+ if (!decoded || decoded.length !== size) throw new Error('tricache: corrupt Zstandard decoded size');
104
+ return Buffer.from(decoded);
105
+ }
106
+
85
107
  export function decompressBuffer(
86
108
  buf: Buffer,
87
109
  algorithm: CompressionAlgorithm = 'zstd',
88
110
  custom?: CustomCompressor,
89
111
  ): Buffer {
112
+ if (buf.length > 32 * 1024 * 1024) throw new Error('tricache: compressed input exceeds maximum safety threshold');
90
113
  if (custom) {
91
- const res = custom.decompress(buf);
114
+ const res = custom.decompress(buf, MAX_DECOMPRESS_BYTES);
92
115
  if (res.length > MAX_DECOMPRESS_BYTES) {
93
116
  throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
94
117
  }
@@ -106,7 +129,7 @@ export function decompressBuffer(
106
129
  if (buf.length >= 4 && buf[0] === 0x28 && buf[1] === 0xb5 && buf[2] === 0x2f && buf[3] === 0xfd) {
107
130
  if (zstdSimple) {
108
131
  try {
109
- return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
132
+ return checkSafety(decompressZstd(buf));
110
133
  } catch (err: any) {
111
134
  if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
112
135
  /* try recovery */
@@ -117,7 +140,7 @@ export function decompressBuffer(
117
140
  // 2. LZ4 frame magic header: 0x04 0x22 0x4D 0x18
118
141
  if (buf.length >= 4 && buf[0] === 0x04 && buf[1] === 0x22 && buf[2] === 0x4d && buf[3] === 0x18) {
119
142
  try {
120
- return checkSafety(Buffer.from(lz4js.decompress(buf)));
143
+ return checkSafety(decompressLz4(buf));
121
144
  } catch (err: any) {
122
145
  if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
123
146
  /* try recovery */
@@ -143,7 +166,7 @@ export function decompressBuffer(
143
166
  // 4. Algorithm-specific attempts
144
167
  if (algorithm === 'lz4') {
145
168
  try {
146
- return checkSafety(Buffer.from(lz4js.decompress(buf)));
169
+ return checkSafety(decompressLz4(buf));
147
170
  } catch (err: any) {
148
171
  if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
149
172
  /* fallback */
@@ -152,7 +175,7 @@ export function decompressBuffer(
152
175
 
153
176
  if (algorithm === 'zstd' && zstdSimple) {
154
177
  try {
155
- return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
178
+ return checkSafety(decompressZstd(buf));
156
179
  } catch (err: any) {
157
180
  if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
158
181
  /* fallback */
@@ -182,7 +205,7 @@ export function decompressBuffer(
182
205
  };
183
206
  const tryLz4 = (): Buffer | null => {
184
207
  try {
185
- return checkSafety(Buffer.from(lz4js.decompress(buf)));
208
+ return checkSafety(decompressLz4(buf));
186
209
  } catch (err: any) {
187
210
  if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
188
211
  return null;
@@ -191,7 +214,7 @@ export function decompressBuffer(
191
214
  const tryZstd = (): Buffer | null => {
192
215
  if (!zstdSimple) return null;
193
216
  try {
194
- return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
217
+ return checkSafety(decompressZstd(buf));
195
218
  } catch (err: any) {
196
219
  if (err?.message?.includes('exceeds maximum safety threshold')) throw err;
197
220
  return null;
@@ -6,6 +6,19 @@
6
6
  * active-active Redis Enterprise licenses.
7
7
  */
8
8
 
9
+ import { createHash, timingSafeEqual } from 'node:crypto';
10
+
11
+ export function isCrossRegionInvalidationEvent(value: unknown): value is CrossRegionInvalidationEvent {
12
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
13
+ const event = value as Record<string, unknown>;
14
+ const text = (key: string, max: number) => typeof event[key] === 'string' && (event[key] as string).length > 0 && (event[key] as string).length <= max;
15
+ return text('id', 256) && text('originRegion', 128) && text('originInstanceId', 256) && text('key', 8192) &&
16
+ typeof event.op === 'string' && ['del', 'del-glob', 'tag_incr', 'tag_pattern_incr', 'tag_pattern_del'].includes(event.op) &&
17
+ typeof event.timestamp === 'number' && Number.isFinite(event.timestamp) && event.timestamp >= 0 &&
18
+ (event.namespace === undefined || typeof event.namespace === 'string') &&
19
+ (event.tagVersion === undefined || Number.isSafeInteger(event.tagVersion) && Number(event.tagVersion) >= 0);
20
+ }
21
+
9
22
  export interface CrossRegionInvalidationEvent {
10
23
  /** Unique ID of this invalidation event (UUIDv4) */
11
24
  id: string;
@@ -21,7 +34,7 @@ export interface CrossRegionInvalidationEvent {
21
34
  tagVersion?: number;
22
35
  /** Timestamp when the event was created */
23
36
  timestamp: number;
24
- /** Optional namespace of the origin cache */
37
+ /** Exact trimmed namespace of the origin cache. Omitted means the default namespace. */
25
38
  namespace?: string;
26
39
  /** Optional W3C traceparent header for distributed context propagation */
27
40
  traceparent?: string;
@@ -109,7 +122,7 @@ export function createHttpMeshRelay(options: HttpMeshRelayOptions): ICrossRegion
109
122
  if (!peerUrls.length) return;
110
123
 
111
124
  const body = JSON.stringify(event);
112
- await Promise.allSettled(
125
+ const results = await Promise.allSettled(
113
126
  peerUrls.map(async (url) => {
114
127
  const res = await fetcher(url, {
115
128
  method: 'POST',
@@ -122,6 +135,8 @@ export function createHttpMeshRelay(options: HttpMeshRelayOptions): ICrossRegion
122
135
  }
123
136
  }),
124
137
  );
138
+ const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
139
+ if (failures.length) throw new AggregateError(failures.map(result => result.reason), `Cross-region delivery failed for ${failures.length} peer(s)`);
125
140
  },
126
141
  };
127
142
  }
@@ -156,7 +171,9 @@ export function createMemoryCrossRegionRelay(): ICrossRegionRelay & {
156
171
  }
157
172
  }
158
173
  }
159
- await Promise.allSettled(promises);
174
+ const results = await Promise.allSettled(promises);
175
+ const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
176
+ if (failures.length) throw new AggregateError(failures.map(result => result.reason), 'Cross-region handler failed');
160
177
  },
161
178
 
162
179
  register(region: string, handler: (event: CrossRegionInvalidationEvent) => Promise<unknown> | unknown): () => void {
@@ -209,7 +226,7 @@ export function createCrossRegionWebhookHandler(
209
226
 
210
227
  const provided = (typeof customHeader === 'string' ? customHeader : bearer);
211
228
 
212
- if (!provided || provided !== options.authSecret) {
229
+ if (typeof provided !== 'string' || !timingSafeEqual(createHash('sha256').update(provided).digest(), createHash('sha256').update(options.authSecret).digest())) {
213
230
  return {
214
231
  status: 401,
215
232
  body: { ok: false, message: 'Unauthorized: invalid or missing auth secret' },
@@ -230,6 +247,7 @@ export function createCrossRegionWebhookHandler(
230
247
  };
231
248
  }
232
249
 
250
+ if (!isCrossRegionInvalidationEvent(event)) return { status: 400, body: { ok: false, message: 'Invalid invalidation event' } };
233
251
  const accepted = await cache.receiveCrossRegionInvalidation(event);
234
252
  return {
235
253
  status: 200,
@@ -21,7 +21,7 @@ const SECURITY_HEADERS: Record<string, string> = {
21
21
  'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'",
22
22
  'X-Frame-Options': 'DENY',
23
23
  'X-Content-Type-Options': 'nosniff',
24
- 'Referrer-Policy': 'same-origin',
24
+ 'Referrer-Policy': 'no-referrer',
25
25
  'Cache-Control': 'no-store, no-cache, must-revalidate',
26
26
  };
27
27
 
@@ -48,7 +48,7 @@ export function buildMetricsPayload(options: DashboardOptions): Record<string, u
48
48
  title: options.title || 'TriCache Observability',
49
49
  instanceId: resolveInstanceId(options.instanceId),
50
50
  nodeVersion: process.version,
51
- readOnly: !!options.readOnly,
51
+ readOnly: options.readOnly ?? true,
52
52
  peerInstances: options.peerInstances || [],
53
53
  metrics: {
54
54
  ...metrics,
@@ -192,6 +192,7 @@ export async function handleDashboardRequest(req: Request, options: DashboardOpt
192
192
  // Start periodic broadcast ticker
193
193
  ticker = setInterval(() => {
194
194
  try {
195
+ if ((controller.desiredSize ?? 0) <= 0) return; // Drop snapshots instead of buffering for slow readers.
195
196
  const data = buildMetricsPayload(options);
196
197
  controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`));
197
198
  } catch {
@@ -208,7 +209,7 @@ export async function handleDashboardRequest(req: Request, options: DashboardOpt
208
209
  ticker = null;
209
210
  }
210
211
  try { controller.close(); } catch { /* ignore */ }
211
- });
212
+ }, { once: true });
212
213
  }
213
214
  },
214
215
  cancel() {
@@ -247,7 +248,7 @@ export async function handleDashboardRequest(req: Request, options: DashboardOpt
247
248
  const clientIp = req.headers.get('x-forwarded-for') || undefined;
248
249
 
249
250
  // Check Read-Only Mode
250
- if (options.readOnly) {
251
+ if (options.readOnly ?? true) {
251
252
  return new Response(JSON.stringify({ ok: false, error: 'Dashboard is in read-only mode' }), {
252
253
  status: 403,
253
254
  headers: { 'Content-Type': 'application/json' },
@@ -263,7 +264,26 @@ export async function handleDashboardRequest(req: Request, options: DashboardOpt
263
264
  }
264
265
 
265
266
  try {
266
- const body = await req.json() as { tag?: string };
267
+ const maxBytes = options.maxRequestBytes ?? 65536;
268
+ if (Number(req.headers.get('content-length')) > maxBytes) return new Response(JSON.stringify({ error: 'Request body too large' }), { status: 413 });
269
+ const reader = req.body?.getReader();
270
+ const chunks: Uint8Array[] = [];
271
+ let bytes = 0;
272
+ if (reader) {
273
+ try {
274
+ while (true) {
275
+ const chunk = await reader.read();
276
+ if (chunk.done) break;
277
+ bytes += chunk.value.length;
278
+ if (bytes > maxBytes) {
279
+ await reader.cancel();
280
+ return new Response(JSON.stringify({ error: 'Request body too large' }), { status: 413 });
281
+ }
282
+ chunks.push(chunk.value);
283
+ }
284
+ } finally { reader.releaseLock(); }
285
+ }
286
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8')) as { tag?: string };
267
287
  const tag = body?.tag?.trim();
268
288
  if (!tag) {
269
289
  return new Response(JSON.stringify({ ok: false, error: 'Tag parameter is required' }), {
@@ -310,7 +330,7 @@ export async function handleDashboardRequest(req: Request, options: DashboardOpt
310
330
  const clientIp = req.headers.get('x-forwarded-for') || undefined;
311
331
 
312
332
  // Check Read-Only Mode
313
- if (options.readOnly) {
333
+ if (options.readOnly ?? true) {
314
334
  return new Response(JSON.stringify({ ok: false, error: 'Dashboard is in read-only mode' }), {
315
335
  status: 403,
316
336
  headers: { 'Content-Type': 'application/json' },
@@ -290,7 +290,7 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
290
290
  <span class="pulse-dot"></span>
291
291
  <span id="stream-text">SSE Live</span>
292
292
  </div>
293
- <select id="peer-select" class="peer-select" style="display:none;" onchange="if(this.value) window.location.href=this.value;">
293
+ <select id="peer-select" aria-label="Switch cache instance" class="peer-select" style="display:none;" onchange="if(this.value) window.location.href=this.value;">
294
294
  <option value="">Switch Pod...</option>
295
295
  </select>
296
296
  </div>
@@ -350,9 +350,10 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
350
350
 
351
351
  <!-- Invalidate Modal -->
352
352
  <div class="dialog-overlay" id="invalidate-modal">
353
- <div class="dialog">
354
- <h3>Invalidate Tag</h3>
353
+ <div class="dialog" role="dialog" aria-modal="true" aria-labelledby="invalidate-title">
354
+ <h3 id="invalidate-title">Invalidate Tag</h3>
355
355
  <p>Increments generational tag version across local tiers and broadcast backplane.</p>
356
+ <label for="tag-input">Tag name or pattern</label>
356
357
  <input type="text" id="tag-input" placeholder="e.g. products, tenant-123" />
357
358
  <div class="dialog-actions">
358
359
  <button class="btn" onclick="closeModals()">Cancel</button>
@@ -363,8 +364,8 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
363
364
 
364
365
  <!-- Clear Modal -->
365
366
  <div class="dialog-overlay" id="clear-modal">
366
- <div class="dialog">
367
- <h3>Clear Cache</h3>
367
+ <div class="dialog" role="dialog" aria-modal="true" aria-labelledby="clear-title">
368
+ <h3 id="clear-title">Clear Cache</h3>
368
369
  <p>Evict all cached keys from the local L1 memory and NVMe disk tiers.</p>
369
370
  <div class="dialog-actions">
370
371
  <button class="btn" onclick="closeModals()">Cancel</button>
@@ -373,12 +374,20 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
373
374
  </div>
374
375
  </div>
375
376
 
376
- <div id="toast"></div>
377
+ <div id="toast" role="status" aria-live="polite"></div>
377
378
 
378
379
  <script>
379
380
  (function() {
380
381
  let isReadOnly = false;
381
382
  let sseFailed = false;
383
+ let previousFocus = null;
384
+ const token = new URLSearchParams(window.location.search).get('token');
385
+ const basePath = window.location.pathname.replace(/\\/index\\.html$/, '').replace(/\\/+$/, '');
386
+ function apiURL(path) {
387
+ const url = new URL(basePath + '/' + path, window.location.origin);
388
+ if (token) url.searchParams.set('token', token);
389
+ return url.toString();
390
+ }
382
391
 
383
392
  function showToast(msg, duration = 3000) {
384
393
  const t = document.getElementById('toast');
@@ -485,7 +494,8 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
485
494
  }
486
495
 
487
496
  window.fetchMetricsSnapshot = function() {
488
- fetch('api/metrics')
497
+ fetch(apiURL('api/metrics'))
498
+ .then(r => { if (!r.ok) throw new Error('HTTP ' + r.status); return r; })
489
499
  .then(r => r.json())
490
500
  .then(data => updateUI(data))
491
501
  .catch(err => showToast('Failed to fetch snapshot: ' + err.message));
@@ -496,7 +506,7 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
496
506
  fallbackPolling();
497
507
  return;
498
508
  }
499
- const sse = new EventSource('api/stream');
509
+ const sse = new EventSource(apiURL('api/stream'));
500
510
  sse.onmessage = function(e) {
501
511
  try {
502
512
  const data = JSON.parse(e.data);
@@ -521,22 +531,37 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
521
531
 
522
532
  window.openInvalidateModal = function() {
523
533
  if (isReadOnly) return;
534
+ previousFocus = document.activeElement;
524
535
  document.getElementById('invalidate-modal').classList.add('active');
525
536
  document.getElementById('tag-input').focus();
526
537
  };
527
538
  window.openClearModal = function() {
528
539
  if (isReadOnly) return;
540
+ previousFocus = document.activeElement;
529
541
  document.getElementById('clear-modal').classList.add('active');
542
+ document.querySelector('#clear-modal button').focus();
530
543
  };
531
544
  window.closeModals = function() {
532
545
  document.getElementById('invalidate-modal').classList.remove('active');
533
546
  document.getElementById('clear-modal').classList.remove('active');
547
+ if (previousFocus) previousFocus.focus();
534
548
  };
549
+ document.addEventListener('keydown', function(event) {
550
+ const modal = document.querySelector('.dialog-overlay.active');
551
+ if (!modal) return;
552
+ if (event.key === 'Escape') { event.preventDefault(); closeModals(); }
553
+ if (event.key === 'Tab') {
554
+ const controls = modal.querySelectorAll('button, input, select, [tabindex="0"]');
555
+ const first = controls[0], last = controls[controls.length - 1];
556
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
557
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
558
+ }
559
+ });
535
560
 
536
561
  window.submitTagInvalidation = function() {
537
562
  const tag = document.getElementById('tag-input').value.trim();
538
563
  if (!tag) return;
539
- fetch('api/actions/invalidate-tag', {
564
+ fetch(apiURL('api/actions/invalidate-tag'), {
540
565
  method: 'POST',
541
566
  headers: {
542
567
  'Content-Type': 'application/json',
@@ -559,7 +584,7 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
559
584
  };
560
585
 
561
586
  window.submitClear = function() {
562
- fetch('api/actions/clear', {
587
+ fetch(apiURL('api/actions/clear'), {
563
588
  method: 'POST',
564
589
  headers: {
565
590
  'Content-Type': 'application/json',
@@ -10,7 +10,7 @@ export { DASHBOARD_HTML, DASHBOARD_GZIP_BUFFER } from './html.js';
10
10
  /**
11
11
  * Convert a Node.js IncomingMessage into a Web Standards Request.
12
12
  */
13
- async function nodeToWebRequest(req: IncomingMessage): Promise<Request> {
13
+ async function nodeToWebRequest(req: IncomingMessage, res: ServerResponse, maxBytes: number): Promise<Request> {
14
14
  const protocol = (req.socket as { encrypted?: boolean }).encrypted ? 'https' : 'http';
15
15
  const host = req.headers.host || 'localhost';
16
16
  const url = new URL(req.url || '/', `${protocol}://${host}`);
@@ -28,20 +28,24 @@ async function nodeToWebRequest(req: IncomingMessage): Promise<Request> {
28
28
  let body: Uint8Array | null = null;
29
29
  if (req.method !== 'GET' && req.method !== 'HEAD') {
30
30
  const chunks: Buffer[] = [];
31
- for await (const chunk of req) {
32
- chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
31
+ let size = 0;
32
+ const parsed = (req as IncomingMessage & { body?: unknown }).body;
33
+ if (req.readableEnded && parsed !== undefined) chunks.push(Buffer.from(JSON.stringify(parsed)));
34
+ else for await (const chunk of req) {
35
+ const bytes = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
36
+ size += bytes.length;
37
+ if (size > maxBytes) throw Object.assign(new Error('Request body exceeds dashboard limit'), { status: 413 });
38
+ chunks.push(bytes);
33
39
  }
34
40
  if (chunks.length > 0) {
35
41
  body = Buffer.concat(chunks);
42
+ if (body.length > maxBytes) throw Object.assign(new Error('Request body exceeds dashboard limit'), { status: 413 });
36
43
  }
37
44
  }
38
45
 
39
46
  const controller = new AbortController();
40
- req.on('close', () => {
41
- if (req.destroyed || !req.complete) {
42
- controller.abort();
43
- }
44
- });
47
+ req.once('aborted', () => controller.abort());
48
+ res.once('close', () => controller.abort());
45
49
 
46
50
  const init: RequestInit & { duplex?: string } = {
47
51
  method: req.method,
@@ -71,14 +75,26 @@ async function pipeWebResponseToNode(webRes: Response, nodeRes: ServerResponse):
71
75
  }
72
76
 
73
77
  const reader = webRes.body.getReader();
78
+ const cancel = () => { void reader.cancel().catch(() => {}); };
79
+ nodeRes.once('close', cancel);
74
80
  try {
75
81
  while (true) {
76
82
  const { done, value } = await reader.read();
77
83
  if (done) break;
78
- nodeRes.write(value);
84
+ if (nodeRes.destroyed) break;
85
+ if (!nodeRes.write(value)) await new Promise<void>((resolve, reject) => {
86
+ const cleanup = () => { nodeRes.off('drain', onDrain); nodeRes.off('close', onClose); };
87
+ const onDrain = () => { cleanup(); resolve(); };
88
+ const onClose = () => { cleanup(); reject(new Error('Dashboard response closed')); };
89
+ nodeRes.once('drain', onDrain);
90
+ nodeRes.once('close', onClose);
91
+ });
79
92
  }
80
93
  } finally {
81
- nodeRes.end();
94
+ nodeRes.off('close', cancel);
95
+ await reader.cancel().catch(() => {});
96
+ reader.releaseLock();
97
+ if (!nodeRes.destroyed) nodeRes.end();
82
98
  }
83
99
  }
84
100
 
@@ -99,11 +115,16 @@ async function pipeWebResponseToNode(webRes: Response, nodeRes: ServerResponse):
99
115
  export function tricacheDashboard(options: DashboardOptions) {
100
116
  return async (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void): Promise<void> => {
101
117
  try {
102
- const webReq = await nodeToWebRequest(req);
118
+ const webReq = await nodeToWebRequest(req, res, options.maxRequestBytes ?? 65536);
103
119
  const webRes = await handleDashboardRequest(webReq, options);
104
120
  await pipeWebResponseToNode(webRes, res);
105
121
  } catch (err) {
106
- if (typeof next === 'function') {
122
+ if (res.destroyed) return;
123
+ if ((err as { status?: number }).status === 413) {
124
+ res.statusCode = 413;
125
+ res.setHeader('Connection', 'close');
126
+ res.end(JSON.stringify({ error: 'Request body too large' }));
127
+ } else if (typeof next === 'function') {
107
128
  next(err);
108
129
  } else {
109
130
  res.statusCode = 500;
@@ -162,7 +183,7 @@ export async function startDashboardServer(options: StandaloneDashboardOptions):
162
183
  host: string;
163
184
  close: () => Promise<void>;
164
185
  }> {
165
- const port = options.port || 9090;
186
+ const port = options.port ?? 9090;
166
187
  const host = options.host || '127.0.0.1';
167
188
 
168
189
  const middleware = tricacheDashboard(options);
@@ -190,6 +211,7 @@ export async function startDashboardServer(options: StandaloneDashboardOptions):
190
211
  host,
191
212
  close: () => new Promise<void>((resolve, reject) => {
192
213
  server.close(err => (err ? reject(err) : resolve()));
214
+ server.closeAllConnections();
193
215
  }),
194
216
  };
195
217
  }
@@ -63,7 +63,7 @@ export interface DashboardOptions {
63
63
  /**
64
64
  * Enforces read-only mode: disables and blocks all mutating operations
65
65
  * (e.g. invalidate tag, clear cache tier). Mutating endpoints return 403 Forbidden.
66
- * @default false
66
+ * @default true
67
67
  */
68
68
  readOnly?: boolean;
69
69
 
@@ -72,6 +72,8 @@ export interface DashboardOptions {
72
72
  * @default 2000
73
73
  */
74
74
  streamIntervalMs?: number;
75
+ /** Maximum administrative request body size. Default: 64 KiB. */
76
+ maxRequestBytes?: number;
75
77
 
76
78
  /**
77
79
  * Enterprise audit logging hook invoked when an administrative action is attempted.