tricache 0.7.0 → 0.8.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 (100) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +144 -1428
  3. package/bin/tricache.js +8 -8
  4. package/dashboards/tricache-alerts.yaml +54 -0
  5. package/dashboards/tricache-grafana.json +548 -0
  6. package/dist/cache-service-5MZXFIGK.js +12 -0
  7. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  8. package/dist/{chunk-3XQUQBOZ.js → chunk-6PQ5MOWR.js} +2950 -523
  9. package/dist/chunk-7RV5ZVBB.js +1023 -0
  10. package/dist/{chunk-PFB5FMEY.js → chunk-LJ5QJB5O.js} +116 -20
  11. package/dist/chunk-QNU7B43J.js +687 -0
  12. package/dist/chunk-UGD4VEPD.js +138 -0
  13. package/dist/chunk-XZL45ABR.js +108 -0
  14. package/dist/chunk-ZTSWCFYO.js +135 -0
  15. package/dist/cli.cjs +2894 -518
  16. package/dist/cli.d.ts +1 -0
  17. package/dist/cli.js +103 -5
  18. package/dist/dashboard/index.cjs +1065 -0
  19. package/dist/dashboard/index.d.ts +183 -0
  20. package/dist/dashboard/index.js +22 -0
  21. package/dist/drizzle/index.cjs +2648 -508
  22. package/dist/drizzle/index.d.ts +3 -1
  23. package/dist/drizzle/index.js +1 -1
  24. package/dist/edge/index.cjs +1498 -0
  25. package/dist/edge/index.d.ts +127 -0
  26. package/dist/edge/index.js +1109 -0
  27. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  28. package/dist/http/index.cjs +3038 -589
  29. package/dist/http/index.d.ts +109 -23
  30. package/dist/http/index.js +238 -62
  31. package/dist/index.cjs +6962 -2487
  32. package/dist/index.d.ts +547 -30
  33. package/dist/index.js +104 -5
  34. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  35. package/dist/nestjs/index.cjs +2586 -498
  36. package/dist/nestjs/index.d.ts +3 -1
  37. package/dist/nestjs/index.js +6 -3
  38. package/dist/next/index.cjs +2633 -519
  39. package/dist/next/index.d.ts +13 -7
  40. package/dist/next/index.js +45 -18
  41. package/dist/prisma/index.cjs +2 -1
  42. package/dist/prisma/index.d.ts +3 -1
  43. package/dist/prisma/index.js +2 -1
  44. package/dist/serialize-worker.cjs +31 -19
  45. package/dist/serialize-worker.js +1 -1
  46. package/dist/{cache-service-BblHuF3i.d.ts → types-B6krw64X.d.ts} +605 -646
  47. package/package.json +37 -7
  48. package/src/adapters/auto-pipeliner.ts +206 -0
  49. package/src/adapters/node-redis.ts +370 -0
  50. package/src/cache-service.ts +4231 -3226
  51. package/src/cli.ts +261 -143
  52. package/src/codec.ts +72 -0
  53. package/src/compression.ts +56 -63
  54. package/src/cross-region.ts +245 -0
  55. package/src/dashboard/handler.ts +392 -0
  56. package/src/dashboard/html.ts +594 -0
  57. package/src/dashboard/index.ts +195 -0
  58. package/src/dashboard/types.ts +96 -0
  59. package/src/disk-tier.ts +1223 -821
  60. package/src/drizzle/index.ts +86 -86
  61. package/src/edge/adapters/cloudflare-do.ts +130 -0
  62. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  63. package/src/edge/adapters/upstash.ts +143 -0
  64. package/src/edge/cache.ts +797 -0
  65. package/src/edge/crypto.ts +182 -0
  66. package/src/edge/hono.ts +203 -0
  67. package/src/edge/index.ts +37 -0
  68. package/src/edge/types.ts +230 -0
  69. package/src/edge/utils/base64.ts +63 -0
  70. package/src/edge/utils/murmur3.ts +179 -0
  71. package/src/encryption.ts +635 -493
  72. package/src/http/express.ts +195 -0
  73. package/src/http/fastify.ts +260 -0
  74. package/src/http/index.ts +46 -223
  75. package/src/http/utils.ts +92 -0
  76. package/src/index.ts +149 -47
  77. package/src/ipc-telemetry.ts +481 -0
  78. package/src/latency-watchdog.ts +282 -0
  79. package/src/nestjs/decorators.ts +161 -161
  80. package/src/nestjs/index.ts +23 -23
  81. package/src/nestjs/tricache.module.ts +104 -104
  82. package/src/nestjs/tricache.store.ts +97 -97
  83. package/src/nestjs/types.ts +79 -79
  84. package/src/next/cache-handler.ts +271 -244
  85. package/src/next/index.ts +37 -37
  86. package/src/next/isr-handler.ts +105 -105
  87. package/src/next/types.ts +130 -130
  88. package/src/prisma/index.ts +154 -151
  89. package/src/remote-snapshot.ts +153 -0
  90. package/src/serialize-worker.ts +120 -120
  91. package/src/sigv4-snapshot-adapter.ts +260 -0
  92. package/src/smart-memory-cache.ts +1109 -1024
  93. package/src/types.ts +1199 -902
  94. package/src/utils/cgroup.ts +100 -0
  95. package/src/utils/tracing.ts +54 -0
  96. package/src/wasm/bloom-filter-wasm.ts +109 -102
  97. package/src/worker-pool.ts +299 -299
  98. package/src/wtiny-lfu.ts +624 -0
  99. package/dist/cache-service-AJASH5FX.js +0 -7
  100. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -0,0 +1,245 @@
1
+ /**
2
+ * tricache — Multi-Cluster / Geo-Distributed Cross-Region Invalidation Relay
3
+ *
4
+ * Enables multi-region architectures (e.g. us-east-1 + eu-central-1) with independent
5
+ * Redis clusters to synchronize invalidations across regions without expensive
6
+ * active-active Redis Enterprise licenses.
7
+ */
8
+
9
+ export interface CrossRegionInvalidationEvent {
10
+ /** Unique ID of this invalidation event (UUIDv4) */
11
+ id: string;
12
+ /** Region where the invalidation originated, e.g. 'us-east-1' */
13
+ originRegion: string;
14
+ /** Instance ID that initiated the invalidation */
15
+ originInstanceId: string;
16
+ /** Invalidation operation */
17
+ op: 'del' | 'del-glob' | 'tag_incr';
18
+ /** Cache key or tag name */
19
+ key: string;
20
+ /** New tag version for generational tag invalidation */
21
+ tagVersion?: number;
22
+ /** Timestamp when the event was created */
23
+ timestamp: number;
24
+ /** Optional namespace of the origin cache */
25
+ namespace?: string;
26
+ /** Optional W3C traceparent header for distributed context propagation */
27
+ traceparent?: string;
28
+ }
29
+
30
+ export interface ICrossRegionRelay {
31
+ /**
32
+ * Broadcasts an invalidation event across regions (via HTTP mesh, SNS, SQS, EventBridge, or custom bus).
33
+ */
34
+ broadcast(event: CrossRegionInvalidationEvent): Promise<void>;
35
+ }
36
+
37
+ export interface CrossRegionRelayOptions {
38
+ /**
39
+ * Region identifier for this instance, e.g. 'us-east-1' or 'eu-central-1'.
40
+ */
41
+ currentRegion: string;
42
+
43
+ /**
44
+ * Cross-region relay implementation.
45
+ */
46
+ relay: ICrossRegionRelay;
47
+
48
+ /**
49
+ * Optional shared secret or bearer token for authenticating HTTP webhook mesh calls.
50
+ */
51
+ authSecret?: string;
52
+
53
+ /**
54
+ * Max entries stored in the deduplication cache for preventing invalidation loop echoes.
55
+ * Default: 10,000.
56
+ */
57
+ dedupCacheSize?: number;
58
+
59
+ /**
60
+ * Whether writes via `set()` should also broadcast cross-region.
61
+ * Default: `false` (only explicit invalidations `delete()`, `deletePattern()`,
62
+ * and `invalidateTag()` broadcast cross-region, avoiding inter-region thrashing
63
+ * when independent caches populate from local databases).
64
+ */
65
+ broadcastOnSet?: boolean;
66
+ }
67
+
68
+ export interface HttpMeshRelayOptions {
69
+ /**
70
+ * Array of peer regional webhook endpoints (e.g. ['https://eu.internal.api/cache/invalidation']).
71
+ */
72
+ peerUrls: string[];
73
+
74
+ /**
75
+ * Optional authentication secret sent in the `Authorization: Bearer <secret>` header.
76
+ */
77
+ authSecret?: string;
78
+
79
+ /**
80
+ * Request timeout in milliseconds for each peer. Default: 3000 ms.
81
+ */
82
+ timeoutMs?: number;
83
+
84
+ /**
85
+ * Optional fetch implementation (defaults to globalThis.fetch).
86
+ */
87
+ fetchFn?: typeof fetch;
88
+ }
89
+
90
+ /**
91
+ * Creates an HTTP-based peer mesh relay using native Node 22 `fetch()`.
92
+ * Broadcasts events concurrently to all configured peer URLs.
93
+ */
94
+ export function createHttpMeshRelay(options: HttpMeshRelayOptions): ICrossRegionRelay {
95
+ const peerUrls = options.peerUrls;
96
+ const timeoutMs = options.timeoutMs ?? 3000;
97
+ const fetcher = options.fetchFn ?? globalThis.fetch;
98
+ const headers: Record<string, string> = {
99
+ 'Content-Type': 'application/json',
100
+ };
101
+
102
+ if (options.authSecret) {
103
+ headers['Authorization'] = `Bearer ${options.authSecret}`;
104
+ headers['X-TriCache-Auth'] = options.authSecret;
105
+ }
106
+
107
+ return {
108
+ async broadcast(event: CrossRegionInvalidationEvent): Promise<void> {
109
+ if (!peerUrls.length) return;
110
+
111
+ const body = JSON.stringify(event);
112
+ await Promise.allSettled(
113
+ peerUrls.map(async (url) => {
114
+ const res = await fetcher(url, {
115
+ method: 'POST',
116
+ headers,
117
+ body,
118
+ signal: AbortSignal.timeout(timeoutMs),
119
+ });
120
+ if (!res.ok) {
121
+ throw new Error(`HttpMeshRelay: peer ${url} returned HTTP ${res.status} ${res.statusText}`);
122
+ }
123
+ }),
124
+ );
125
+ },
126
+ };
127
+ }
128
+
129
+ /**
130
+ * Type-checking helper for custom cross-region relays (AWS SNS/SQS, EventBridge, Kafka, NATS).
131
+ */
132
+ export function createCustomCrossRegionRelay(relay: ICrossRegionRelay): ICrossRegionRelay {
133
+ return relay;
134
+ }
135
+
136
+ /**
137
+ * In-memory cross-region mesh bus designed for unit testing and multi-region simulations.
138
+ */
139
+ export function createMemoryCrossRegionRelay(): ICrossRegionRelay & {
140
+ register(region: string, handler: (event: CrossRegionInvalidationEvent) => Promise<unknown> | unknown): () => void;
141
+ getBroadcastCount(): number;
142
+ clear(): void;
143
+ } {
144
+ const handlers = new Map<string, Set<(event: CrossRegionInvalidationEvent) => Promise<unknown> | unknown>>();
145
+ let broadcastCount = 0;
146
+
147
+ return {
148
+ async broadcast(event: CrossRegionInvalidationEvent): Promise<void> {
149
+ broadcastCount++;
150
+ const promises: Promise<unknown>[] = [];
151
+ for (const [region, set] of handlers.entries()) {
152
+ // Only deliver to handlers in DIFFERENT regions
153
+ if (region !== event.originRegion) {
154
+ for (const fn of set) {
155
+ promises.push(Promise.resolve(fn(event)));
156
+ }
157
+ }
158
+ }
159
+ await Promise.allSettled(promises);
160
+ },
161
+
162
+ register(region: string, handler: (event: CrossRegionInvalidationEvent) => Promise<unknown> | unknown): () => void {
163
+ if (!handlers.has(region)) {
164
+ handlers.set(region, new Set());
165
+ }
166
+ handlers.get(region)!.add(handler);
167
+ return () => {
168
+ handlers.get(region)?.delete(handler);
169
+ };
170
+ },
171
+
172
+ getBroadcastCount(): number {
173
+ return broadcastCount;
174
+ },
175
+
176
+ clear(): void {
177
+ handlers.clear();
178
+ broadcastCount = 0;
179
+ },
180
+ };
181
+ }
182
+
183
+ export interface WebhookRequestLike {
184
+ headers: Record<string, string | string[] | undefined>;
185
+ body: unknown;
186
+ }
187
+
188
+ export interface WebhookResponseLike {
189
+ status: number;
190
+ body: { ok: boolean; message?: string };
191
+ }
192
+
193
+ /**
194
+ * Creates a generic webhook handler to receive incoming cross-region invalidation requests.
195
+ * Compatible with Express, Fastify, Next.js route handlers, or Node's `http.createServer`.
196
+ */
197
+ export function createCrossRegionWebhookHandler(
198
+ cache: { receiveCrossRegionInvalidation(event: CrossRegionInvalidationEvent): Promise<boolean> | boolean },
199
+ options: { authSecret?: string } = {},
200
+ ) {
201
+ return async function handleCrossRegionWebhook(req: WebhookRequestLike): Promise<WebhookResponseLike> {
202
+ if (options.authSecret) {
203
+ const authHeader = req.headers['authorization'] ?? req.headers['Authorization'];
204
+ const customHeader = req.headers['x-tricache-auth'] ?? req.headers['X-TriCache-Auth'];
205
+
206
+ const bearer = typeof authHeader === 'string' && authHeader.startsWith('Bearer ')
207
+ ? authHeader.slice(7).trim()
208
+ : authHeader;
209
+
210
+ const provided = (typeof customHeader === 'string' ? customHeader : bearer);
211
+
212
+ if (!provided || provided !== options.authSecret) {
213
+ return {
214
+ status: 401,
215
+ body: { ok: false, message: 'Unauthorized: invalid or missing auth secret' },
216
+ };
217
+ }
218
+ }
219
+
220
+ try {
221
+ let event: CrossRegionInvalidationEvent;
222
+ if (typeof req.body === 'string') {
223
+ event = JSON.parse(req.body) as CrossRegionInvalidationEvent;
224
+ } else if (req.body && typeof req.body === 'object') {
225
+ event = req.body as CrossRegionInvalidationEvent;
226
+ } else {
227
+ return {
228
+ status: 400,
229
+ body: { ok: false, message: 'Invalid payload: body must be JSON object' },
230
+ };
231
+ }
232
+
233
+ const accepted = await cache.receiveCrossRegionInvalidation(event);
234
+ return {
235
+ status: 200,
236
+ body: { ok: true, message: accepted ? 'Invalidation applied' : 'Invalidation ignored (deduplicated or self)' },
237
+ };
238
+ } catch (err) {
239
+ return {
240
+ status: 400,
241
+ body: { ok: false, message: (err as Error).message },
242
+ };
243
+ }
244
+ };
245
+ }
@@ -0,0 +1,392 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ import os from 'node:os';
3
+ import { DASHBOARD_HTML, DASHBOARD_GZIP_BUFFER } from './html.js';
4
+ import type { DashboardOptions } from './types.js';
5
+
6
+ /**
7
+ * Timing-safe string comparison routine using SHA-256 digests to neutralize
8
+ * both length-leakage side-channels and buffer-length mismatch exceptions.
9
+ */
10
+ export function safeCompare(a: string, b: string): boolean {
11
+ if (typeof a !== 'string' || typeof b !== 'string') return false;
12
+ const hashA = createHash('sha256').update(a).digest();
13
+ const hashB = createHash('sha256').update(b).digest();
14
+ return timingSafeEqual(hashA, hashB);
15
+ }
16
+
17
+ /**
18
+ * Standard Security Headers applied to HTML responses.
19
+ */
20
+ const SECURITY_HEADERS: Record<string, string> = {
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
+ 'X-Frame-Options': 'DENY',
23
+ 'X-Content-Type-Options': 'nosniff',
24
+ 'Referrer-Policy': 'same-origin',
25
+ 'Cache-Control': 'no-store, no-cache, must-revalidate',
26
+ };
27
+
28
+ /**
29
+ * Resolve local instance/pod identifier from options or environment.
30
+ */
31
+ export function resolveInstanceId(custom?: string): string {
32
+ if (custom && custom.trim()) return custom.trim();
33
+ if (process.env.POD_NAME) return process.env.POD_NAME;
34
+ if (process.env.HOSTNAME) return process.env.HOSTNAME;
35
+ try {
36
+ return os.hostname();
37
+ } catch {
38
+ return 'tricache-node';
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Build the JSON snapshot payload for /api/metrics and SSE stream events.
44
+ */
45
+ export function buildMetricsPayload(options: DashboardOptions): Record<string, unknown> {
46
+ const metrics = options.cache.metrics();
47
+ return {
48
+ title: options.title || 'TriCache Observability',
49
+ instanceId: resolveInstanceId(options.instanceId),
50
+ nodeVersion: process.version,
51
+ readOnly: !!options.readOnly,
52
+ peerInstances: options.peerInstances || [],
53
+ metrics: {
54
+ ...metrics,
55
+ health: {
56
+ status: metrics.l2CircuitBreaker?.state === 'open' ? 'degraded' : 'healthy',
57
+ circuitBreaker: metrics.l2CircuitBreaker?.state || 'closed',
58
+ uptimeMs: metrics.uptimeMs,
59
+ },
60
+ },
61
+ timestamp: Date.now(),
62
+ };
63
+ }
64
+
65
+ /**
66
+ * Validate incoming authentication against configured Basic Auth or Bearer secret.
67
+ */
68
+ function verifyAuth(req: Request, options: DashboardOptions): { authorized: boolean; user?: string } {
69
+ const url = new URL(req.url, 'http://localhost');
70
+
71
+ // 1. Basic Auth check
72
+ if (options.auth) {
73
+ const authHeader = req.headers.get('authorization') || '';
74
+ if (!authHeader.toLowerCase().startsWith('basic ')) {
75
+ return { authorized: false };
76
+ }
77
+ const b64 = authHeader.slice(6).trim();
78
+ let decoded = '';
79
+ try {
80
+ decoded = Buffer.from(b64, 'base64').toString('utf-8');
81
+ } catch {
82
+ return { authorized: false };
83
+ }
84
+ const colonIdx = decoded.indexOf(':');
85
+ if (colonIdx === -1) return { authorized: false };
86
+
87
+ const username = decoded.slice(0, colonIdx);
88
+ const password = decoded.slice(colonIdx + 1);
89
+
90
+ const userMatch = safeCompare(username, options.auth.username);
91
+ const passMatch = safeCompare(password, options.auth.password);
92
+
93
+ if (userMatch && passMatch) {
94
+ return { authorized: true, user: username };
95
+ }
96
+ return { authorized: false };
97
+ }
98
+
99
+ // 2. Bearer Secret check
100
+ if (options.authSecret) {
101
+ const authHeader = req.headers.get('authorization') || '';
102
+ if (authHeader.toLowerCase().startsWith('bearer ')) {
103
+ const token = authHeader.slice(7).trim();
104
+ if (safeCompare(token, options.authSecret)) {
105
+ return { authorized: true, user: 'token-client' };
106
+ }
107
+ }
108
+ // Check URL query parameter fallback
109
+ const queryToken = url.searchParams.get('token');
110
+ if (queryToken && safeCompare(queryToken, options.authSecret)) {
111
+ return { authorized: true, user: 'token-client' };
112
+ }
113
+ return { authorized: false };
114
+ }
115
+
116
+ // No auth required
117
+ return { authorized: true, user: 'anonymous' };
118
+ }
119
+
120
+ /**
121
+ * Validate CSRF protection on mutating endpoints.
122
+ * Requires mandatory 'X-TriCache-Action: 1' and origin/host verification.
123
+ */
124
+ function verifyCsrf(req: Request): boolean {
125
+ // Enforce custom header which cannot be sent by standard cross-origin forms
126
+ const customHeader = req.headers.get('x-tricache-action');
127
+ if (customHeader !== '1') {
128
+ return false;
129
+ }
130
+
131
+ // Origin / Referer validation if present
132
+ const origin = req.headers.get('origin');
133
+ const host = req.headers.get('host');
134
+ if (origin && host) {
135
+ try {
136
+ const originHost = new URL(origin).host;
137
+ if (originHost !== host) return false;
138
+ } catch {
139
+ return false;
140
+ }
141
+ }
142
+
143
+ return true;
144
+ }
145
+
146
+ /**
147
+ * Framework-agnostic Web Standards request handler for the TriCache dashboard.
148
+ * Accepts a Web Standard Request and returns a Web Standard Response.
149
+ */
150
+ export async function handleDashboardRequest(req: Request, options: DashboardOptions): Promise<Response> {
151
+ // 1. Authenticate request
152
+ const authResult = verifyAuth(req, options);
153
+ if (!authResult.authorized) {
154
+ return new Response(JSON.stringify({ error: 'Unauthorized' }), {
155
+ status: 401,
156
+ headers: {
157
+ 'Content-Type': 'application/json',
158
+ ...(options.auth ? { 'WWW-Authenticate': 'Basic realm="TriCache Dashboard"' } : {}),
159
+ },
160
+ });
161
+ }
162
+
163
+ const url = new URL(req.url, 'http://localhost');
164
+ let pathname = url.pathname;
165
+
166
+ // Strip basePath if present
167
+ const basePath = (options.basePath || '').replace(/\/+$/, '');
168
+ if (basePath && pathname.startsWith(basePath)) {
169
+ pathname = pathname.slice(basePath.length) || '/';
170
+ }
171
+
172
+ // Normalize path
173
+ if (!pathname.startsWith('/')) {
174
+ pathname = '/' + pathname;
175
+ }
176
+
177
+ // Route 1: SSE Live Metric Stream
178
+ if (pathname === '/api/stream' && req.method === 'GET') {
179
+ const encoder = new TextEncoder();
180
+ const intervalMs = Math.max(500, options.streamIntervalMs || 2000);
181
+
182
+ let ticker: NodeJS.Timeout | null = null;
183
+
184
+ const stream = new ReadableStream({
185
+ start(controller) {
186
+ // Send immediate initial frame
187
+ try {
188
+ const initial = buildMetricsPayload(options);
189
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(initial)}\n\n`));
190
+ } catch { /* ignore */ }
191
+
192
+ // Start periodic broadcast ticker
193
+ ticker = setInterval(() => {
194
+ try {
195
+ const data = buildMetricsPayload(options);
196
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`));
197
+ } catch {
198
+ if (ticker) clearInterval(ticker);
199
+ try { controller.close(); } catch { /* ignore */ }
200
+ }
201
+ }, intervalMs);
202
+
203
+ // Tie ticker directly to request abort signal to prevent event loop leaks
204
+ if (req.signal) {
205
+ req.signal.addEventListener('abort', () => {
206
+ if (ticker) {
207
+ clearInterval(ticker);
208
+ ticker = null;
209
+ }
210
+ try { controller.close(); } catch { /* ignore */ }
211
+ });
212
+ }
213
+ },
214
+ cancel() {
215
+ if (ticker) {
216
+ clearInterval(ticker);
217
+ ticker = null;
218
+ }
219
+ },
220
+ });
221
+
222
+ return new Response(stream, {
223
+ status: 200,
224
+ headers: {
225
+ 'Content-Type': 'text/event-stream',
226
+ 'Cache-Control': 'no-cache, no-transform',
227
+ 'Connection': 'keep-alive',
228
+ 'X-Accel-Buffering': 'no',
229
+ },
230
+ });
231
+ }
232
+
233
+ // Route 2: Snapshot Metrics JSON
234
+ if (pathname === '/api/metrics' && req.method === 'GET') {
235
+ const payload = buildMetricsPayload(options);
236
+ return new Response(JSON.stringify(payload), {
237
+ status: 200,
238
+ headers: {
239
+ 'Content-Type': 'application/json',
240
+ 'Cache-Control': 'no-store, no-cache, must-revalidate',
241
+ },
242
+ });
243
+ }
244
+
245
+ // Route 3: Mutating Action - Invalidate Tag
246
+ if (pathname === '/api/actions/invalidate-tag' && req.method === 'POST') {
247
+ const clientIp = req.headers.get('x-forwarded-for') || undefined;
248
+
249
+ // Check Read-Only Mode
250
+ if (options.readOnly) {
251
+ return new Response(JSON.stringify({ ok: false, error: 'Dashboard is in read-only mode' }), {
252
+ status: 403,
253
+ headers: { 'Content-Type': 'application/json' },
254
+ });
255
+ }
256
+
257
+ // CSRF Check
258
+ if (!verifyCsrf(req)) {
259
+ return new Response(JSON.stringify({ ok: false, error: 'Invalid or missing CSRF headers' }), {
260
+ status: 403,
261
+ headers: { 'Content-Type': 'application/json' },
262
+ });
263
+ }
264
+
265
+ try {
266
+ const body = await req.json() as { tag?: string };
267
+ const tag = body?.tag?.trim();
268
+ if (!tag) {
269
+ return new Response(JSON.stringify({ ok: false, error: 'Tag parameter is required' }), {
270
+ status: 400,
271
+ headers: { 'Content-Type': 'application/json' },
272
+ });
273
+ }
274
+
275
+ await options.cache.invalidateTag(tag);
276
+
277
+ // Audit log hook
278
+ options.onAction?.({
279
+ action: 'invalidate-tag',
280
+ target: tag,
281
+ user: authResult.user,
282
+ ip: clientIp,
283
+ timestamp: Date.now(),
284
+ success: true,
285
+ });
286
+
287
+ return new Response(JSON.stringify({ ok: true, tag }), {
288
+ status: 200,
289
+ headers: { 'Content-Type': 'application/json' },
290
+ });
291
+ } catch (err: unknown) {
292
+ const errMsg = err instanceof Error ? err.message : String(err);
293
+ options.onAction?.({
294
+ action: 'invalidate-tag',
295
+ user: authResult.user,
296
+ ip: clientIp,
297
+ timestamp: Date.now(),
298
+ success: false,
299
+ error: errMsg,
300
+ });
301
+ return new Response(JSON.stringify({ ok: false, error: errMsg }), {
302
+ status: 500,
303
+ headers: { 'Content-Type': 'application/json' },
304
+ });
305
+ }
306
+ }
307
+
308
+ // Route 4: Mutating Action - Clear Cache
309
+ if (pathname === '/api/actions/clear' && req.method === 'POST') {
310
+ const clientIp = req.headers.get('x-forwarded-for') || undefined;
311
+
312
+ // Check Read-Only Mode
313
+ if (options.readOnly) {
314
+ return new Response(JSON.stringify({ ok: false, error: 'Dashboard is in read-only mode' }), {
315
+ status: 403,
316
+ headers: { 'Content-Type': 'application/json' },
317
+ });
318
+ }
319
+
320
+ // CSRF Check
321
+ if (!verifyCsrf(req)) {
322
+ return new Response(JSON.stringify({ ok: false, error: 'Invalid or missing CSRF headers' }), {
323
+ status: 403,
324
+ headers: { 'Content-Type': 'application/json' },
325
+ });
326
+ }
327
+
328
+ try {
329
+ await options.cache.clear();
330
+
331
+ options.onAction?.({
332
+ action: 'clear',
333
+ user: authResult.user,
334
+ ip: clientIp,
335
+ timestamp: Date.now(),
336
+ success: true,
337
+ });
338
+
339
+ return new Response(JSON.stringify({ ok: true }), {
340
+ status: 200,
341
+ headers: { 'Content-Type': 'application/json' },
342
+ });
343
+ } catch (err: unknown) {
344
+ const errMsg = err instanceof Error ? err.message : String(err);
345
+ options.onAction?.({
346
+ action: 'clear',
347
+ user: authResult.user,
348
+ ip: clientIp,
349
+ timestamp: Date.now(),
350
+ success: false,
351
+ error: errMsg,
352
+ });
353
+ return new Response(JSON.stringify({ ok: false, error: errMsg }), {
354
+ status: 500,
355
+ headers: { 'Content-Type': 'application/json' },
356
+ });
357
+ }
358
+ }
359
+
360
+ // Route 5: Embedded SPA UI (Default)
361
+ if (pathname === '/' || pathname === '/index.html' || pathname === '') {
362
+ const acceptEncoding = req.headers.get('accept-encoding') || '';
363
+
364
+ // Serve pre-gzipped binary payload if client accepts gzip
365
+ if (acceptEncoding.includes('gzip')) {
366
+ return new Response(new Uint8Array(DASHBOARD_GZIP_BUFFER), {
367
+ status: 200,
368
+ headers: {
369
+ 'Content-Type': 'text/html; charset=utf-8',
370
+ 'Content-Encoding': 'gzip',
371
+ 'Content-Length': String(DASHBOARD_GZIP_BUFFER.length),
372
+ ...SECURITY_HEADERS,
373
+ },
374
+ });
375
+ }
376
+
377
+ // Fallback uncompressed
378
+ return new Response(DASHBOARD_HTML, {
379
+ status: 200,
380
+ headers: {
381
+ 'Content-Type': 'text/html; charset=utf-8',
382
+ ...SECURITY_HEADERS,
383
+ },
384
+ });
385
+ }
386
+
387
+ // 404 Not Found
388
+ return new Response(JSON.stringify({ error: 'Not Found' }), {
389
+ status: 404,
390
+ headers: { 'Content-Type': 'application/json' },
391
+ });
392
+ }