tricache 0.7.1 → 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 (95) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +87 -1371
  3. package/dashboards/tricache-alerts.yaml +54 -0
  4. package/dashboards/tricache-grafana.json +548 -0
  5. package/dist/cache-service-5MZXFIGK.js +12 -0
  6. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  7. package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  10. package/dist/chunk-QNU7B43J.js +687 -0
  11. package/dist/chunk-UGD4VEPD.js +138 -0
  12. package/dist/chunk-XZL45ABR.js +108 -0
  13. package/dist/chunk-ZTSWCFYO.js +135 -0
  14. package/dist/cli.cjs +2790 -471
  15. package/dist/cli.d.ts +1 -0
  16. package/dist/cli.js +103 -5
  17. package/dist/dashboard/index.cjs +1065 -0
  18. package/dist/dashboard/index.d.ts +183 -0
  19. package/dist/dashboard/index.js +22 -0
  20. package/dist/drizzle/index.cjs +2553 -470
  21. package/dist/drizzle/index.d.ts +3 -1
  22. package/dist/drizzle/index.js +1 -1
  23. package/dist/edge/index.cjs +1498 -0
  24. package/dist/edge/index.d.ts +127 -0
  25. package/dist/edge/index.js +1109 -0
  26. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  27. package/dist/http/index.cjs +2926 -562
  28. package/dist/http/index.d.ts +109 -23
  29. package/dist/http/index.js +220 -72
  30. package/dist/index.cjs +6936 -2518
  31. package/dist/index.d.ts +547 -30
  32. package/dist/index.js +104 -5
  33. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  34. package/dist/nestjs/index.cjs +2494 -463
  35. package/dist/nestjs/index.d.ts +3 -1
  36. package/dist/nestjs/index.js +6 -3
  37. package/dist/next/index.cjs +2517 -483
  38. package/dist/next/index.d.ts +4 -2
  39. package/dist/next/index.js +14 -10
  40. package/dist/prisma/index.d.ts +3 -1
  41. package/dist/serialize-worker.cjs +5 -4
  42. package/dist/serialize-worker.js +1 -1
  43. package/dist/{cache-service-D8tIXmzb.d.ts → types-B6krw64X.d.ts} +596 -659
  44. package/package.json +34 -6
  45. package/src/adapters/auto-pipeliner.ts +206 -0
  46. package/src/adapters/node-redis.ts +370 -0
  47. package/src/cache-service.ts +1339 -402
  48. package/src/cli.ts +120 -2
  49. package/src/codec.ts +72 -0
  50. package/src/cross-region.ts +245 -0
  51. package/src/dashboard/handler.ts +392 -0
  52. package/src/dashboard/html.ts +594 -0
  53. package/src/dashboard/index.ts +195 -0
  54. package/src/dashboard/types.ts +96 -0
  55. package/src/disk-tier.ts +449 -47
  56. package/src/drizzle/index.ts +86 -86
  57. package/src/edge/adapters/cloudflare-do.ts +130 -0
  58. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  59. package/src/edge/adapters/upstash.ts +143 -0
  60. package/src/edge/cache.ts +797 -0
  61. package/src/edge/crypto.ts +182 -0
  62. package/src/edge/hono.ts +203 -0
  63. package/src/edge/index.ts +37 -0
  64. package/src/edge/types.ts +230 -0
  65. package/src/edge/utils/base64.ts +63 -0
  66. package/src/edge/utils/murmur3.ts +179 -0
  67. package/src/encryption.ts +127 -5
  68. package/src/http/express.ts +195 -0
  69. package/src/http/fastify.ts +260 -0
  70. package/src/http/index.ts +39 -258
  71. package/src/http/utils.ts +92 -0
  72. package/src/index.ts +149 -47
  73. package/src/ipc-telemetry.ts +481 -0
  74. package/src/latency-watchdog.ts +282 -0
  75. package/src/nestjs/decorators.ts +161 -161
  76. package/src/nestjs/index.ts +23 -23
  77. package/src/nestjs/tricache.module.ts +104 -104
  78. package/src/nestjs/tricache.store.ts +97 -97
  79. package/src/nestjs/types.ts +79 -79
  80. package/src/next/cache-handler.ts +12 -9
  81. package/src/next/index.ts +37 -37
  82. package/src/next/isr-handler.ts +105 -105
  83. package/src/next/types.ts +130 -130
  84. package/src/remote-snapshot.ts +153 -0
  85. package/src/serialize-worker.ts +120 -120
  86. package/src/sigv4-snapshot-adapter.ts +260 -0
  87. package/src/smart-memory-cache.ts +91 -8
  88. package/src/types.ts +290 -2
  89. package/src/utils/cgroup.ts +100 -0
  90. package/src/utils/tracing.ts +54 -0
  91. package/src/wasm/bloom-filter-wasm.ts +109 -102
  92. package/src/worker-pool.ts +299 -299
  93. package/src/wtiny-lfu.ts +624 -0
  94. package/dist/cache-service-5GATUYAK.js +0 -7
  95. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -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
+ }