@syncular/server-hono 0.0.6-95 → 0.2.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 (104) hide show
  1. package/README.md +5 -23
  2. package/dist/admin-page.d.ts +14 -0
  3. package/dist/admin-page.js +217 -0
  4. package/dist/admin.d.ts +39 -0
  5. package/dist/admin.js +142 -0
  6. package/dist/index.d.ts +16 -14
  7. package/dist/index.js +134 -23
  8. package/package.json +19 -53
  9. package/src/admin-page.ts +217 -0
  10. package/src/admin.ts +193 -0
  11. package/src/index.ts +175 -31
  12. package/dist/api-key-auth.d.ts +0 -49
  13. package/dist/api-key-auth.d.ts.map +0 -1
  14. package/dist/api-key-auth.js +0 -110
  15. package/dist/api-key-auth.js.map +0 -1
  16. package/dist/blobs.d.ts +0 -69
  17. package/dist/blobs.d.ts.map +0 -1
  18. package/dist/blobs.js +0 -383
  19. package/dist/blobs.js.map +0 -1
  20. package/dist/console/gateway.d.ts +0 -33
  21. package/dist/console/gateway.d.ts.map +0 -1
  22. package/dist/console/gateway.js +0 -2534
  23. package/dist/console/gateway.js.map +0 -1
  24. package/dist/console/index.d.ts +0 -11
  25. package/dist/console/index.d.ts.map +0 -1
  26. package/dist/console/index.js +0 -11
  27. package/dist/console/index.js.map +0 -1
  28. package/dist/console/routes.d.ts +0 -33
  29. package/dist/console/routes.d.ts.map +0 -1
  30. package/dist/console/routes.js +0 -2890
  31. package/dist/console/routes.js.map +0 -1
  32. package/dist/console/schemas.d.ts +0 -490
  33. package/dist/console/schemas.d.ts.map +0 -1
  34. package/dist/console/schemas.js +0 -303
  35. package/dist/console/schemas.js.map +0 -1
  36. package/dist/console/types.d.ts +0 -142
  37. package/dist/console/types.d.ts.map +0 -1
  38. package/dist/console/types.js +0 -2
  39. package/dist/console/types.js.map +0 -1
  40. package/dist/console/ui.d.ts +0 -38
  41. package/dist/console/ui.d.ts.map +0 -1
  42. package/dist/console/ui.js +0 -43
  43. package/dist/console/ui.js.map +0 -1
  44. package/dist/create-server.d.ts +0 -68
  45. package/dist/create-server.d.ts.map +0 -1
  46. package/dist/create-server.js +0 -109
  47. package/dist/create-server.js.map +0 -1
  48. package/dist/index.d.ts.map +0 -1
  49. package/dist/index.js.map +0 -1
  50. package/dist/openapi.d.ts +0 -45
  51. package/dist/openapi.d.ts.map +0 -1
  52. package/dist/openapi.js +0 -59
  53. package/dist/openapi.js.map +0 -1
  54. package/dist/proxy/connection-manager.d.ts +0 -78
  55. package/dist/proxy/connection-manager.d.ts.map +0 -1
  56. package/dist/proxy/connection-manager.js +0 -251
  57. package/dist/proxy/connection-manager.js.map +0 -1
  58. package/dist/proxy/index.d.ts +0 -8
  59. package/dist/proxy/index.d.ts.map +0 -1
  60. package/dist/proxy/index.js +0 -8
  61. package/dist/proxy/index.js.map +0 -1
  62. package/dist/proxy/routes.d.ts +0 -74
  63. package/dist/proxy/routes.d.ts.map +0 -1
  64. package/dist/proxy/routes.js +0 -147
  65. package/dist/proxy/routes.js.map +0 -1
  66. package/dist/rate-limit.d.ts +0 -101
  67. package/dist/rate-limit.d.ts.map +0 -1
  68. package/dist/rate-limit.js +0 -186
  69. package/dist/rate-limit.js.map +0 -1
  70. package/dist/routes.d.ts +0 -145
  71. package/dist/routes.d.ts.map +0 -1
  72. package/dist/routes.js +0 -1471
  73. package/dist/routes.js.map +0 -1
  74. package/dist/ws.d.ts +0 -235
  75. package/dist/ws.d.ts.map +0 -1
  76. package/dist/ws.js +0 -614
  77. package/dist/ws.js.map +0 -1
  78. package/src/__tests__/blob-routes.test.ts +0 -424
  79. package/src/__tests__/console-gateway-live-routes.test.ts +0 -297
  80. package/src/__tests__/console-gateway-routes.test.ts +0 -1364
  81. package/src/__tests__/console-routes.test.ts +0 -1543
  82. package/src/__tests__/console-ui.test.ts +0 -114
  83. package/src/__tests__/create-server.test.ts +0 -342
  84. package/src/__tests__/pull-chunk-storage.test.ts +0 -576
  85. package/src/__tests__/rate-limit.test.ts +0 -78
  86. package/src/__tests__/realtime-bridge.test.ts +0 -135
  87. package/src/__tests__/sync-rate-limit-routing.test.ts +0 -185
  88. package/src/__tests__/ws-connection-manager.test.ts +0 -176
  89. package/src/api-key-auth.ts +0 -179
  90. package/src/blobs.ts +0 -534
  91. package/src/console/gateway.ts +0 -3603
  92. package/src/console/index.ts +0 -11
  93. package/src/console/routes.ts +0 -3748
  94. package/src/console/schemas.ts +0 -434
  95. package/src/console/types.ts +0 -151
  96. package/src/console/ui.ts +0 -100
  97. package/src/create-server.ts +0 -206
  98. package/src/openapi.ts +0 -74
  99. package/src/proxy/connection-manager.ts +0 -340
  100. package/src/proxy/index.ts +0 -8
  101. package/src/proxy/routes.ts +0 -223
  102. package/src/rate-limit.ts +0 -321
  103. package/src/routes.ts +0 -2007
  104. package/src/ws.ts +0 -802
@@ -1,1543 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
2
- import { createDatabase } from '@syncular/core';
3
- import { createPgliteDialect } from '@syncular/dialect-pglite';
4
- import { ensureSyncSchema, type SyncCoreDb } from '@syncular/server';
5
- import { createPostgresServerDialect } from '@syncular/server-dialect-postgres';
6
- import { Hono } from 'hono';
7
- import type { Generated, Kysely } from 'kysely';
8
- import {
9
- type CreateConsoleRoutesOptions,
10
- createConsoleRoutes,
11
- } from '../console';
12
-
13
- interface SyncRequestEventsTable {
14
- event_id: Generated<number>;
15
- partition_id: string;
16
- request_id: string | null;
17
- trace_id: string | null;
18
- span_id: string | null;
19
- event_type: 'push' | 'pull';
20
- sync_path: 'http-combined' | 'ws-push';
21
- actor_id: string;
22
- client_id: string;
23
- transport_path: 'direct' | 'relay';
24
- status_code: number;
25
- outcome: string;
26
- response_status: string;
27
- error_code: string | null;
28
- duration_ms: number;
29
- commit_seq: number | null;
30
- operation_count: number | null;
31
- row_count: number | null;
32
- subscription_count: number | null;
33
- scopes_summary: unknown | null;
34
- tables: string[];
35
- error_message: string | null;
36
- payload_ref: string | null;
37
- created_at: Generated<string>;
38
- }
39
-
40
- interface SyncRequestPayloadsTable {
41
- payload_ref: string;
42
- partition_id: string;
43
- request_payload: unknown;
44
- response_payload: unknown | null;
45
- created_at: Generated<string>;
46
- }
47
-
48
- interface SyncOperationEventsTable {
49
- operation_id: Generated<number>;
50
- operation_type: string;
51
- console_user_id: string | null;
52
- partition_id: string | null;
53
- target_client_id: string | null;
54
- request_payload: unknown | null;
55
- result_payload: unknown | null;
56
- created_at: Generated<string>;
57
- }
58
-
59
- interface SyncApiKeysTable {
60
- key_id: string;
61
- key_hash: string;
62
- key_prefix: string;
63
- name: string;
64
- key_type: 'relay' | 'proxy' | 'admin';
65
- scope_keys: unknown | null;
66
- actor_id: string | null;
67
- created_at: Generated<string>;
68
- expires_at: string | null;
69
- last_used_at: string | null;
70
- revoked_at: string | null;
71
- }
72
-
73
- interface TestDb extends SyncCoreDb {
74
- sync_request_events: SyncRequestEventsTable;
75
- sync_request_payloads: SyncRequestPayloadsTable;
76
- sync_operation_events: SyncOperationEventsTable;
77
- sync_api_keys: SyncApiKeysTable;
78
- }
79
-
80
- type TimelineResponse = {
81
- items: Array<{
82
- type: 'commit' | 'event';
83
- timestamp: string;
84
- commit: {
85
- commitSeq: number;
86
- actorId: string;
87
- clientId: string;
88
- affectedTables: string[];
89
- } | null;
90
- event: {
91
- eventId: number;
92
- actorId: string;
93
- clientId: string;
94
- eventType: 'push' | 'pull';
95
- outcome: string;
96
- tables: string[];
97
- } | null;
98
- }>;
99
- total: number;
100
- offset: number;
101
- limit: number;
102
- };
103
-
104
- type OperationsResponse = {
105
- items: Array<{
106
- operationId: number;
107
- operationType: 'prune' | 'compact' | 'notify_data_change' | 'evict_client';
108
- consoleUserId: string | null;
109
- partitionId: string | null;
110
- targetClientId: string | null;
111
- requestPayload: unknown;
112
- resultPayload: unknown;
113
- createdAt: string;
114
- }>;
115
- total: number;
116
- offset: number;
117
- limit: number;
118
- };
119
-
120
- type ApiKeysResponse = {
121
- items: Array<{
122
- keyId: string;
123
- keyPrefix: string;
124
- name: string;
125
- keyType: 'relay' | 'proxy' | 'admin';
126
- scopeKeys: string[];
127
- actorId: string | null;
128
- createdAt: string;
129
- expiresAt: string | null;
130
- lastUsedAt: string | null;
131
- revokedAt: string | null;
132
- }>;
133
- total: number;
134
- offset: number;
135
- limit: number;
136
- };
137
-
138
- function timelineItemKey(item: TimelineResponse['items'][number]): string {
139
- if (item.type === 'commit') {
140
- return `C${item.commit?.commitSeq ?? 'unknown'}`;
141
- }
142
- return `E${item.event?.eventId ?? 'unknown'}`;
143
- }
144
-
145
- const CONSOLE_TOKEN = 'console-test-token';
146
-
147
- describe('console timeline route filters', () => {
148
- let db: Kysely<TestDb>;
149
- let dialect: ReturnType<typeof createPostgresServerDialect>;
150
- let app: Hono;
151
- let baseTimeMs: number;
152
-
153
- function atIso(minutes: number): string {
154
- return new Date(baseTimeMs + minutes * 60_000).toISOString();
155
- }
156
-
157
- async function requestTimeline(args: {
158
- query?: Record<string, string | number | undefined>;
159
- authenticated?: boolean;
160
- }): Promise<Response> {
161
- const params = new URLSearchParams({ limit: '50', offset: '0' });
162
- for (const [key, value] of Object.entries(args.query ?? {})) {
163
- if (value === undefined) continue;
164
- params.set(key, String(value));
165
- }
166
-
167
- return app.request(
168
- `http://localhost/console/timeline?${params.toString()}`,
169
- {
170
- headers:
171
- args.authenticated === false
172
- ? undefined
173
- : { Authorization: `Bearer ${CONSOLE_TOKEN}` },
174
- }
175
- );
176
- }
177
-
178
- async function readTimeline(
179
- query: Record<string, string | number | undefined> = {}
180
- ): Promise<TimelineResponse> {
181
- const response = await requestTimeline({ query });
182
- expect(response.status).toBe(200);
183
- return (await response.json()) as TimelineResponse;
184
- }
185
-
186
- async function requestEventPayload(
187
- eventId: number,
188
- query: Record<string, string | number | undefined> = {}
189
- ): Promise<Response> {
190
- const params = new URLSearchParams();
191
- for (const [key, value] of Object.entries(query)) {
192
- if (value === undefined) continue;
193
- params.set(key, String(value));
194
- }
195
- const queryString = params.toString();
196
-
197
- return app.request(
198
- `http://localhost/console/events/${eventId}/payload${queryString ? `?${queryString}` : ''}`,
199
- {
200
- headers: { Authorization: `Bearer ${CONSOLE_TOKEN}` },
201
- }
202
- );
203
- }
204
-
205
- async function requestNotifyDataChange(body: {
206
- tables: string[];
207
- partitionId?: string;
208
- }): Promise<Response> {
209
- return app.request('http://localhost/console/notify-data-change', {
210
- method: 'POST',
211
- headers: {
212
- Authorization: `Bearer ${CONSOLE_TOKEN}`,
213
- 'Content-Type': 'application/json',
214
- },
215
- body: JSON.stringify(body),
216
- });
217
- }
218
-
219
- async function readOperations(
220
- query: Record<string, string | number | undefined> = {}
221
- ): Promise<OperationsResponse> {
222
- const params = new URLSearchParams({ limit: '50', offset: '0' });
223
- for (const [key, value] of Object.entries(query)) {
224
- if (value === undefined) continue;
225
- params.set(key, String(value));
226
- }
227
-
228
- const response = await app.request(
229
- `http://localhost/console/operations?${params.toString()}`,
230
- {
231
- headers: { Authorization: `Bearer ${CONSOLE_TOKEN}` },
232
- }
233
- );
234
- expect(response.status).toBe(200);
235
- return (await response.json()) as OperationsResponse;
236
- }
237
-
238
- async function requestCommits(
239
- query: Record<string, string | number | undefined> = {}
240
- ): Promise<Response> {
241
- const params = new URLSearchParams({ limit: '50', offset: '0' });
242
- for (const [key, value] of Object.entries(query)) {
243
- if (value === undefined) continue;
244
- params.set(key, String(value));
245
- }
246
-
247
- return app.request(
248
- `http://localhost/console/commits?${params.toString()}`,
249
- {
250
- headers: { Authorization: `Bearer ${CONSOLE_TOKEN}` },
251
- }
252
- );
253
- }
254
-
255
- async function requestClients(
256
- query: Record<string, string | number | undefined> = {}
257
- ): Promise<Response> {
258
- const params = new URLSearchParams({ limit: '50', offset: '0' });
259
- for (const [key, value] of Object.entries(query)) {
260
- if (value === undefined) continue;
261
- params.set(key, String(value));
262
- }
263
-
264
- return app.request(
265
- `http://localhost/console/clients?${params.toString()}`,
266
- {
267
- headers: { Authorization: `Bearer ${CONSOLE_TOKEN}` },
268
- }
269
- );
270
- }
271
-
272
- async function requestEvents(
273
- query: Record<string, string | number | undefined> = {}
274
- ): Promise<Response> {
275
- const params = new URLSearchParams({ limit: '50', offset: '0' });
276
- for (const [key, value] of Object.entries(query)) {
277
- if (value === undefined) continue;
278
- params.set(key, String(value));
279
- }
280
-
281
- return app.request(`http://localhost/console/events?${params.toString()}`, {
282
- headers: { Authorization: `Bearer ${CONSOLE_TOKEN}` },
283
- });
284
- }
285
-
286
- async function requestClearEvents(): Promise<Response> {
287
- return app.request('http://localhost/console/events', {
288
- method: 'DELETE',
289
- headers: { Authorization: `Bearer ${CONSOLE_TOKEN}` },
290
- });
291
- }
292
-
293
- async function requestPruneEvents(): Promise<Response> {
294
- return app.request('http://localhost/console/events/prune', {
295
- method: 'POST',
296
- headers: { Authorization: `Bearer ${CONSOLE_TOKEN}` },
297
- });
298
- }
299
-
300
- async function requestApiKeys(
301
- query: Record<string, string | number | undefined> = {}
302
- ): Promise<Response> {
303
- const params = new URLSearchParams({ limit: '50', offset: '0' });
304
- for (const [key, value] of Object.entries(query)) {
305
- if (value === undefined) continue;
306
- params.set(key, String(value));
307
- }
308
-
309
- return app.request(
310
- `http://localhost/console/api-keys?${params.toString()}`,
311
- {
312
- headers: { Authorization: `Bearer ${CONSOLE_TOKEN}` },
313
- }
314
- );
315
- }
316
-
317
- async function readApiKeys(
318
- query: Record<string, string | number | undefined> = {}
319
- ): Promise<ApiKeysResponse> {
320
- const response = await requestApiKeys(query);
321
- expect(response.status).toBe(200);
322
- return (await response.json()) as ApiKeysResponse;
323
- }
324
-
325
- async function requestBulkRevokeApiKeys(keyIds: string[]): Promise<Response> {
326
- return app.request('http://localhost/console/api-keys/bulk-revoke', {
327
- method: 'POST',
328
- headers: {
329
- Authorization: `Bearer ${CONSOLE_TOKEN}`,
330
- 'Content-Type': 'application/json',
331
- },
332
- body: JSON.stringify({ keyIds }),
333
- });
334
- }
335
-
336
- async function requestStageRotateApiKey(keyId: string): Promise<Response> {
337
- return app.request(
338
- `http://localhost/console/api-keys/${keyId}/rotate/stage`,
339
- {
340
- method: 'POST',
341
- headers: {
342
- Authorization: `Bearer ${CONSOLE_TOKEN}`,
343
- },
344
- }
345
- );
346
- }
347
-
348
- async function requestCommitDetail(
349
- seq: number,
350
- query: Record<string, string | number | undefined> = {}
351
- ): Promise<Response> {
352
- const params = new URLSearchParams();
353
- for (const [key, value] of Object.entries(query)) {
354
- if (value === undefined) continue;
355
- params.set(key, String(value));
356
- }
357
- const queryString = params.toString();
358
-
359
- return app.request(
360
- `http://localhost/console/commits/${seq}${queryString ? `?${queryString}` : ''}`,
361
- {
362
- headers: { Authorization: `Bearer ${CONSOLE_TOKEN}` },
363
- }
364
- );
365
- }
366
-
367
- async function requestEventDetail(
368
- eventId: number,
369
- query: Record<string, string | number | undefined> = {}
370
- ): Promise<Response> {
371
- const params = new URLSearchParams();
372
- for (const [key, value] of Object.entries(query)) {
373
- if (value === undefined) continue;
374
- params.set(key, String(value));
375
- }
376
- const queryString = params.toString();
377
-
378
- return app.request(
379
- `http://localhost/console/events/${eventId}${queryString ? `?${queryString}` : ''}`,
380
- {
381
- headers: { Authorization: `Bearer ${CONSOLE_TOKEN}` },
382
- }
383
- );
384
- }
385
-
386
- async function requestEvictClient(
387
- clientId: string,
388
- query: Record<string, string | number | undefined> = {}
389
- ): Promise<Response> {
390
- const params = new URLSearchParams();
391
- for (const [key, value] of Object.entries(query)) {
392
- if (value === undefined) continue;
393
- params.set(key, String(value));
394
- }
395
- const queryString = params.toString();
396
-
397
- return app.request(
398
- `http://localhost/console/clients/${clientId}${queryString ? `?${queryString}` : ''}`,
399
- {
400
- method: 'DELETE',
401
- headers: { Authorization: `Bearer ${CONSOLE_TOKEN}` },
402
- }
403
- );
404
- }
405
-
406
- async function requestTimeseriesStats(args: {
407
- query?: Record<string, string | number | undefined>;
408
- targetApp?: Hono;
409
- }): Promise<Response> {
410
- const params = new URLSearchParams({ interval: 'hour', range: '24h' });
411
- for (const [key, value] of Object.entries(args.query ?? {})) {
412
- if (value === undefined) continue;
413
- params.set(key, String(value));
414
- }
415
-
416
- return (args.targetApp ?? app).request(
417
- `http://localhost/console/stats/timeseries?${params.toString()}`,
418
- {
419
- headers: { Authorization: `Bearer ${CONSOLE_TOKEN}` },
420
- }
421
- );
422
- }
423
-
424
- async function requestLatencyStats(args: {
425
- query?: Record<string, string | number | undefined>;
426
- targetApp?: Hono;
427
- }): Promise<Response> {
428
- const params = new URLSearchParams({ range: '24h' });
429
- for (const [key, value] of Object.entries(args.query ?? {})) {
430
- if (value === undefined) continue;
431
- params.set(key, String(value));
432
- }
433
-
434
- return (args.targetApp ?? app).request(
435
- `http://localhost/console/stats/latency?${params.toString()}`,
436
- {
437
- headers: { Authorization: `Bearer ${CONSOLE_TOKEN}` },
438
- }
439
- );
440
- }
441
-
442
- function createTestApp(
443
- overrides: Pick<CreateConsoleRoutesOptions<TestDb>, 'metrics'> = {}
444
- ): Hono {
445
- const routes = createConsoleRoutes({
446
- db,
447
- dialect,
448
- handlers: [],
449
- authenticate: async (c) =>
450
- c.req.header('Authorization') === `Bearer ${CONSOLE_TOKEN}`
451
- ? { consoleUserId: 'console-test' }
452
- : null,
453
- corsOrigins: '*',
454
- ...overrides,
455
- });
456
- const nextApp = new Hono();
457
- nextApp.route('/console', routes);
458
- return nextApp;
459
- }
460
-
461
- beforeEach(async () => {
462
- // Keep fixture events within the current metrics windows (for example 24h).
463
- baseTimeMs =
464
- Math.floor(Date.now() / (60 * 60 * 1000)) * (60 * 60 * 1000) -
465
- 60 * 60 * 1000;
466
-
467
- dialect = createPostgresServerDialect();
468
- db = createDatabase<TestDb>({
469
- dialect: createPgliteDialect(),
470
- family: 'postgres',
471
- });
472
- await ensureSyncSchema(db, dialect);
473
- await dialect.ensureConsoleSchema?.(db);
474
-
475
- await db
476
- .insertInto('sync_commits')
477
- .values([
478
- {
479
- partition_id: 'default',
480
- actor_id: 'actor-a',
481
- client_id: 'client-a',
482
- client_commit_id: 'commit-a',
483
- created_at: atIso(10),
484
- meta: null,
485
- result_json: null,
486
- change_count: 2,
487
- affected_tables: ['tasks'],
488
- },
489
- {
490
- partition_id: 'default',
491
- actor_id: 'actor-b',
492
- client_id: 'client-b',
493
- client_commit_id: 'commit-b',
494
- created_at: atIso(20),
495
- meta: null,
496
- result_json: null,
497
- change_count: 1,
498
- affected_tables: ['notes'],
499
- },
500
- ])
501
- .execute();
502
-
503
- const commitRows = await db
504
- .selectFrom('sync_commits')
505
- .select(['commit_seq', 'client_commit_id'])
506
- .execute();
507
-
508
- const commitSeqByClientCommitId = new Map(
509
- commitRows.map((row) => [row.client_commit_id, Number(row.commit_seq)])
510
- );
511
-
512
- await db
513
- .insertInto('sync_request_events')
514
- .values([
515
- {
516
- partition_id: 'default',
517
- request_id: 'req-1',
518
- trace_id: 'trace-1',
519
- span_id: 'span-1',
520
- event_type: 'push',
521
- sync_path: 'http-combined',
522
- actor_id: 'actor-a',
523
- client_id: 'client-a',
524
- transport_path: 'direct',
525
- status_code: 200,
526
- outcome: 'applied',
527
- response_status: 'success',
528
- error_code: null,
529
- duration_ms: 18,
530
- commit_seq: commitSeqByClientCommitId.get('commit-a') ?? null,
531
- operation_count: 2,
532
- row_count: 2,
533
- subscription_count: null,
534
- scopes_summary: null,
535
- tables: ['tasks'],
536
- error_message: null,
537
- payload_ref: 'payload-1',
538
- created_at: atIso(30),
539
- },
540
- {
541
- partition_id: 'default',
542
- request_id: 'req-2',
543
- trace_id: 'trace-2',
544
- span_id: 'span-2',
545
- event_type: 'pull',
546
- sync_path: 'http-combined',
547
- actor_id: 'actor-c',
548
- client_id: 'client-c',
549
- transport_path: 'direct',
550
- status_code: 500,
551
- outcome: 'error',
552
- response_status: 'server_error',
553
- error_code: 'INTERNAL_SERVER_ERROR',
554
- duration_ms: 44,
555
- commit_seq: null,
556
- operation_count: null,
557
- row_count: null,
558
- subscription_count: 2,
559
- scopes_summary: JSON.stringify({ org_id: 'org-1' }),
560
- tables: ['notes'],
561
- error_message: 'pull failed',
562
- payload_ref: null,
563
- created_at: atIso(40),
564
- },
565
- {
566
- partition_id: 'default',
567
- request_id: 'req-3',
568
- trace_id: null,
569
- span_id: null,
570
- event_type: 'pull',
571
- sync_path: 'http-combined',
572
- actor_id: 'actor-a',
573
- client_id: 'client-d',
574
- transport_path: 'relay',
575
- status_code: 409,
576
- outcome: 'rejected',
577
- response_status: 'client_error',
578
- error_code: 'CONFLICT',
579
- duration_ms: 22,
580
- commit_seq: null,
581
- operation_count: 1,
582
- row_count: 1,
583
- subscription_count: 1,
584
- scopes_summary: JSON.stringify({ org_id: ['org-1', 'org-2'] }),
585
- tables: ['tasks', 'notes'],
586
- error_message: null,
587
- payload_ref: null,
588
- created_at: atIso(50),
589
- },
590
- ])
591
- .execute();
592
-
593
- await db
594
- .insertInto('sync_request_payloads')
595
- .values({
596
- payload_ref: 'payload-1',
597
- partition_id: 'default',
598
- request_payload: JSON.stringify({
599
- clientCommitId: 'commit-a',
600
- operations: [{ table: 'tasks', op: 'upsert' }],
601
- }),
602
- response_payload: JSON.stringify({
603
- status: 'applied',
604
- commitSeq: commitSeqByClientCommitId.get('commit-a') ?? null,
605
- }),
606
- created_at: atIso(31),
607
- })
608
- .execute();
609
-
610
- await db
611
- .insertInto('sync_operation_events')
612
- .values([
613
- {
614
- operation_type: 'prune',
615
- console_user_id: 'console-test',
616
- partition_id: null,
617
- target_client_id: null,
618
- request_payload: JSON.stringify({ watermarkCommitSeq: 2 }),
619
- result_payload: JSON.stringify({ deletedCommits: 1 }),
620
- created_at: atIso(32),
621
- },
622
- {
623
- operation_type: 'evict_client',
624
- console_user_id: 'console-test',
625
- partition_id: null,
626
- target_client_id: 'client-d',
627
- request_payload: JSON.stringify({ clientId: 'client-d' }),
628
- result_payload: JSON.stringify({ evicted: true }),
629
- created_at: atIso(52),
630
- },
631
- ])
632
- .execute();
633
-
634
- app = createTestApp();
635
- });
636
-
637
- afterEach(async () => {
638
- await db.destroy();
639
- });
640
-
641
- it('filters by actor, client, and table across merged timeline rows', async () => {
642
- const actorFiltered = await readTimeline({ actorId: 'actor-a' });
643
- expect(actorFiltered.total).toBe(3);
644
- expect(
645
- actorFiltered.items.every(
646
- (item) =>
647
- item.commit?.actorId === 'actor-a' ||
648
- item.event?.actorId === 'actor-a'
649
- )
650
- ).toBe(true);
651
-
652
- const clientFiltered = await readTimeline({ clientId: 'client-d' });
653
- expect(clientFiltered.total).toBe(1);
654
- expect(clientFiltered.items[0]?.event?.clientId).toBe('client-d');
655
-
656
- const tableFiltered = await readTimeline({ table: 'tasks' });
657
- expect(tableFiltered.total).toBe(3);
658
- expect(
659
- tableFiltered.items.every((item) =>
660
- item.type === 'commit'
661
- ? (item.commit?.affectedTables ?? []).includes('tasks')
662
- : (item.event?.tables ?? []).includes('tasks')
663
- )
664
- ).toBe(true);
665
- });
666
-
667
- it('applies outcome and event-type filters to event rows in all-view mode', async () => {
668
- const outcomeFiltered = await readTimeline({ outcome: 'error' });
669
- expect(outcomeFiltered.total).toBe(1);
670
- expect(outcomeFiltered.items[0]?.type).toBe('event');
671
- expect(outcomeFiltered.items[0]?.event?.outcome).toBe('error');
672
-
673
- const eventTypeFiltered = await readTimeline({ eventType: 'push' });
674
- expect(eventTypeFiltered.total).toBe(1);
675
- expect(eventTypeFiltered.items[0]?.type).toBe('event');
676
- expect(eventTypeFiltered.items[0]?.event?.eventType).toBe('push');
677
- });
678
-
679
- it('applies request-id and trace-id filters to event rows', async () => {
680
- const requestIdFiltered = await readTimeline({ requestId: 'req-2' });
681
- expect(requestIdFiltered.total).toBe(1);
682
- expect(requestIdFiltered.items[0]?.type).toBe('event');
683
- expect(requestIdFiltered.items[0]?.event?.eventId).toBeDefined();
684
-
685
- const traceIdFiltered = await readTimeline({ traceId: 'trace-1' });
686
- expect(traceIdFiltered.total).toBe(1);
687
- expect(traceIdFiltered.items[0]?.type).toBe('event');
688
- expect(traceIdFiltered.items[0]?.event?.eventType).toBe('push');
689
- });
690
-
691
- it('applies time-window and search filtering', async () => {
692
- const fromFiltered = await readTimeline({ from: atIso(35) });
693
- expect(fromFiltered.total).toBe(2);
694
- expect(fromFiltered.items[0]?.timestamp >= atIso(35)).toBe(true);
695
- expect(fromFiltered.items[1]?.timestamp >= atIso(35)).toBe(true);
696
-
697
- const searchFiltered = await readTimeline({ search: 'client-d' });
698
- expect(searchFiltered.total).toBe(1);
699
- expect(searchFiltered.items[0]?.event?.clientId).toBe('client-d');
700
- });
701
-
702
- it('returns deterministic pagination slices for merged timeline rows', async () => {
703
- const pageOne = await readTimeline({ limit: 2, offset: 0 });
704
- const pageTwo = await readTimeline({ limit: 2, offset: 2 });
705
-
706
- expect(pageOne.total).toBe(5);
707
- expect(pageTwo.total).toBe(5);
708
- expect(pageOne.items.length).toBe(2);
709
- expect(pageTwo.items.length).toBe(2);
710
-
711
- const pageOneKeys = pageOne.items.map(timelineItemKey);
712
- const pageTwoKeys = pageTwo.items.map(timelineItemKey);
713
-
714
- expect(pageOneKeys[0]).not.toBe(pageTwoKeys[0]);
715
- expect(pageOneKeys.some((key) => pageTwoKeys.includes(key))).toBe(false);
716
- });
717
-
718
- it('lists operation audit events and filters by operation type', async () => {
719
- const allOps = await readOperations();
720
- expect(allOps.total).toBe(2);
721
- expect(allOps.items[0]?.operationType).toBe('evict_client');
722
- expect(allOps.items[1]?.operationType).toBe('prune');
723
-
724
- const pruneOps = await readOperations({ operationType: 'prune' });
725
- expect(pruneOps.total).toBe(1);
726
- expect(pruneOps.items[0]?.operationType).toBe('prune');
727
- expect(pruneOps.items[0]?.consoleUserId).toBe('console-test');
728
- });
729
-
730
- it('supports notify-data-change and records an operation audit event', async () => {
731
- const response = await requestNotifyDataChange({
732
- tables: ['tasks', 'notes'],
733
- partitionId: 'default',
734
- });
735
-
736
- expect(response.status).toBe(200);
737
- const payload = (await response.json()) as {
738
- commitSeq: number;
739
- tables: string[];
740
- deletedChunks: number;
741
- };
742
-
743
- expect(payload.commitSeq).toBeGreaterThan(0);
744
- expect(payload.tables).toEqual(['tasks', 'notes']);
745
- expect(payload.deletedChunks).toBeGreaterThanOrEqual(0);
746
-
747
- const notifyOps = await readOperations({
748
- operationType: 'notify_data_change',
749
- });
750
- expect(notifyOps.total).toBe(1);
751
- expect(notifyOps.items[0]?.consoleUserId).toBe('console-test');
752
- expect(notifyOps.items[0]?.requestPayload).toEqual({
753
- tables: ['tasks', 'notes'],
754
- partitionId: 'default',
755
- });
756
- expect(notifyOps.items[0]?.resultPayload).toEqual(payload);
757
- });
758
-
759
- it('returns stats from aggregated metrics mode with partition filtering', async () => {
760
- const aggregatedApp = createTestApp({
761
- metrics: {
762
- aggregationMode: 'aggregated',
763
- },
764
- });
765
-
766
- const timeseriesResponse = await requestTimeseriesStats({
767
- query: { partitionId: 'default' },
768
- targetApp: aggregatedApp,
769
- });
770
- expect(timeseriesResponse.status).toBe(200);
771
- const timeseriesPayload = (await timeseriesResponse.json()) as {
772
- buckets: Array<{
773
- pushCount: number;
774
- pullCount: number;
775
- errorCount: number;
776
- }>;
777
- };
778
-
779
- const totals = timeseriesPayload.buckets.reduce(
780
- (acc, bucket) => ({
781
- pushCount: acc.pushCount + bucket.pushCount,
782
- pullCount: acc.pullCount + bucket.pullCount,
783
- errorCount: acc.errorCount + bucket.errorCount,
784
- }),
785
- { pushCount: 0, pullCount: 0, errorCount: 0 }
786
- );
787
- expect(totals.pushCount).toBe(1);
788
- expect(totals.pullCount).toBe(2);
789
- expect(totals.errorCount).toBe(1);
790
-
791
- const latencyResponse = await requestLatencyStats({
792
- query: { partitionId: 'default' },
793
- targetApp: aggregatedApp,
794
- });
795
- expect(latencyResponse.status).toBe(200);
796
- const latencyPayload = (await latencyResponse.json()) as {
797
- push: { p50: number; p90: number; p99: number };
798
- pull: { p50: number; p90: number; p99: number };
799
- };
800
-
801
- expect(latencyPayload.push.p50).toBe(18);
802
- expect(latencyPayload.push.p90).toBe(18);
803
- expect(latencyPayload.push.p99).toBe(18);
804
- expect(latencyPayload.pull.p50).toBe(22);
805
- expect(latencyPayload.pull.p90).toBe(44);
806
- expect(latencyPayload.pull.p99).toBe(44);
807
- });
808
-
809
- it('applies partition filters across timeline, list, and operation endpoints', async () => {
810
- await db
811
- .insertInto('sync_commits')
812
- .values({
813
- partition_id: 'tenant-b',
814
- actor_id: 'actor-z',
815
- client_id: 'shared-client',
816
- client_commit_id: 'commit-z',
817
- created_at: atIso(55),
818
- meta: null,
819
- result_json: null,
820
- change_count: 1,
821
- affected_tables: ['tasks'],
822
- })
823
- .execute();
824
-
825
- const tenantCommitRow = await db
826
- .selectFrom('sync_commits')
827
- .select(['commit_seq'])
828
- .where('partition_id', '=', 'tenant-b')
829
- .where('client_commit_id', '=', 'commit-z')
830
- .executeTakeFirst();
831
-
832
- const tenantCommitSeq = Number(tenantCommitRow?.commit_seq);
833
- expect(Number.isFinite(tenantCommitSeq)).toBe(true);
834
-
835
- await db
836
- .insertInto('sync_changes')
837
- .values({
838
- partition_id: 'tenant-b',
839
- commit_seq: tenantCommitSeq,
840
- table: 'tasks',
841
- row_id: 'row-z',
842
- op: 'upsert',
843
- row_json: JSON.stringify({ id: 'row-z', title: 'tenant row' }),
844
- row_version: 1,
845
- scopes: JSON.stringify({ org_id: 'tenant-b' }),
846
- })
847
- .execute();
848
-
849
- await db
850
- .insertInto('sync_request_events')
851
- .values({
852
- partition_id: 'tenant-b',
853
- request_id: 'req-z',
854
- trace_id: 'trace-z',
855
- span_id: 'span-z',
856
- event_type: 'push',
857
- sync_path: 'http-combined',
858
- actor_id: 'actor-z',
859
- client_id: 'shared-client',
860
- transport_path: 'direct',
861
- status_code: 200,
862
- outcome: 'applied',
863
- response_status: 'success',
864
- error_code: null,
865
- duration_ms: 12,
866
- commit_seq: tenantCommitSeq,
867
- operation_count: 1,
868
- row_count: 1,
869
- subscription_count: null,
870
- scopes_summary: null,
871
- tables: ['tasks'],
872
- error_message: null,
873
- payload_ref: 'payload-z',
874
- created_at: atIso(56),
875
- })
876
- .execute();
877
-
878
- await db
879
- .insertInto('sync_request_payloads')
880
- .values({
881
- payload_ref: 'payload-z',
882
- partition_id: 'tenant-b',
883
- request_payload: JSON.stringify({
884
- clientCommitId: 'commit-z',
885
- operations: [{ table: 'tasks', op: 'upsert' }],
886
- }),
887
- response_payload: JSON.stringify({
888
- status: 'applied',
889
- commitSeq: tenantCommitSeq,
890
- }),
891
- created_at: atIso(56),
892
- })
893
- .execute();
894
-
895
- await db
896
- .insertInto('sync_client_cursors')
897
- .values([
898
- {
899
- partition_id: 'default',
900
- client_id: 'shared-client',
901
- actor_id: 'actor-a',
902
- cursor: 1,
903
- effective_scopes: JSON.stringify({ org_id: 'default' }),
904
- updated_at: atIso(57),
905
- },
906
- {
907
- partition_id: 'tenant-b',
908
- client_id: 'shared-client',
909
- actor_id: 'actor-z',
910
- cursor: tenantCommitSeq,
911
- effective_scopes: JSON.stringify({ org_id: 'tenant-b' }),
912
- updated_at: atIso(58),
913
- },
914
- ])
915
- .execute();
916
-
917
- await db
918
- .insertInto('sync_operation_events')
919
- .values({
920
- operation_type: 'notify_data_change',
921
- console_user_id: 'console-test',
922
- partition_id: 'tenant-b',
923
- target_client_id: null,
924
- request_payload: JSON.stringify({
925
- tables: ['tasks'],
926
- partitionId: 'tenant-b',
927
- }),
928
- result_payload: JSON.stringify({ commitSeq: tenantCommitSeq }),
929
- created_at: atIso(59),
930
- })
931
- .execute();
932
-
933
- const tenantTimeline = await readTimeline({ partitionId: 'tenant-b' });
934
- expect(tenantTimeline.total).toBe(2);
935
- expect(
936
- tenantTimeline.items.every((item) =>
937
- item.type === 'commit'
938
- ? item.commit?.clientId === 'shared-client'
939
- : item.event?.partitionId === 'tenant-b'
940
- )
941
- ).toBe(true);
942
-
943
- const commitsResponse = await requestCommits({ partitionId: 'tenant-b' });
944
- expect(commitsResponse.status).toBe(200);
945
- const commitsPayload = (await commitsResponse.json()) as {
946
- items: Array<{ clientId: string }>;
947
- total: number;
948
- };
949
- expect(commitsPayload.total).toBe(1);
950
- expect(commitsPayload.items[0]?.clientId).toBe('shared-client');
951
-
952
- const clientsResponse = await requestClients({ partitionId: 'tenant-b' });
953
- expect(clientsResponse.status).toBe(200);
954
- const clientsPayload = (await clientsResponse.json()) as {
955
- items: Array<{ actorId: string }>;
956
- total: number;
957
- };
958
- expect(clientsPayload.total).toBe(1);
959
- expect(clientsPayload.items[0]?.actorId).toBe('actor-z');
960
-
961
- const eventsResponse = await requestEvents({ partitionId: 'tenant-b' });
962
- expect(eventsResponse.status).toBe(200);
963
- const eventsPayload = (await eventsResponse.json()) as {
964
- items: Array<{ partitionId: string }>;
965
- total: number;
966
- };
967
- expect(eventsPayload.total).toBe(1);
968
- expect(eventsPayload.items[0]?.partitionId).toBe('tenant-b');
969
-
970
- const tenantOps = await readOperations({ partitionId: 'tenant-b' });
971
- expect(tenantOps.total).toBe(1);
972
- expect(tenantOps.items[0]?.partitionId).toBe('tenant-b');
973
- expect(tenantOps.items[0]?.operationType).toBe('notify_data_change');
974
- });
975
-
976
- it('guards detail endpoints and client eviction with partition filters', async () => {
977
- await db
978
- .insertInto('sync_commits')
979
- .values({
980
- partition_id: 'tenant-b',
981
- actor_id: 'actor-z',
982
- client_id: 'shared-client',
983
- client_commit_id: 'commit-z-detail',
984
- created_at: atIso(55),
985
- meta: null,
986
- result_json: null,
987
- change_count: 1,
988
- affected_tables: ['tasks'],
989
- })
990
- .execute();
991
-
992
- const tenantCommitRow = await db
993
- .selectFrom('sync_commits')
994
- .select(['commit_seq'])
995
- .where('partition_id', '=', 'tenant-b')
996
- .where('client_commit_id', '=', 'commit-z-detail')
997
- .executeTakeFirst();
998
- const tenantCommitSeq = Number(tenantCommitRow?.commit_seq);
999
- expect(Number.isFinite(tenantCommitSeq)).toBe(true);
1000
-
1001
- await db
1002
- .insertInto('sync_changes')
1003
- .values({
1004
- partition_id: 'tenant-b',
1005
- commit_seq: tenantCommitSeq,
1006
- table: 'tasks',
1007
- row_id: 'row-z-detail',
1008
- op: 'upsert',
1009
- row_json: JSON.stringify({ id: 'row-z-detail' }),
1010
- row_version: 1,
1011
- scopes: JSON.stringify({ org_id: 'tenant-b' }),
1012
- })
1013
- .execute();
1014
-
1015
- await db
1016
- .insertInto('sync_request_events')
1017
- .values({
1018
- partition_id: 'tenant-b',
1019
- request_id: 'req-z-detail',
1020
- trace_id: 'trace-z-detail',
1021
- span_id: 'span-z-detail',
1022
- event_type: 'push',
1023
- sync_path: 'http-combined',
1024
- actor_id: 'actor-z',
1025
- client_id: 'shared-client',
1026
- transport_path: 'direct',
1027
- status_code: 200,
1028
- outcome: 'applied',
1029
- response_status: 'success',
1030
- error_code: null,
1031
- duration_ms: 15,
1032
- commit_seq: tenantCommitSeq,
1033
- operation_count: 1,
1034
- row_count: 1,
1035
- subscription_count: null,
1036
- scopes_summary: null,
1037
- tables: ['tasks'],
1038
- error_message: null,
1039
- payload_ref: 'payload-z-detail',
1040
- created_at: atIso(56),
1041
- })
1042
- .execute();
1043
-
1044
- await db
1045
- .insertInto('sync_request_payloads')
1046
- .values({
1047
- payload_ref: 'payload-z-detail',
1048
- partition_id: 'tenant-b',
1049
- request_payload: JSON.stringify({ clientCommitId: 'commit-z-detail' }),
1050
- response_payload: JSON.stringify({ status: 'applied' }),
1051
- created_at: atIso(56),
1052
- })
1053
- .execute();
1054
-
1055
- await db
1056
- .insertInto('sync_client_cursors')
1057
- .values([
1058
- {
1059
- partition_id: 'default',
1060
- client_id: 'shared-client',
1061
- actor_id: 'actor-a',
1062
- cursor: 1,
1063
- effective_scopes: JSON.stringify({ org_id: 'default' }),
1064
- updated_at: atIso(57),
1065
- },
1066
- {
1067
- partition_id: 'tenant-b',
1068
- client_id: 'shared-client',
1069
- actor_id: 'actor-z',
1070
- cursor: tenantCommitSeq,
1071
- effective_scopes: JSON.stringify({ org_id: 'tenant-b' }),
1072
- updated_at: atIso(58),
1073
- },
1074
- ])
1075
- .execute();
1076
-
1077
- const tenantEventRow = await db
1078
- .selectFrom('sync_request_events')
1079
- .select(['event_id'])
1080
- .where('request_id', '=', 'req-z-detail')
1081
- .executeTakeFirst();
1082
- const tenantEventId = Number(tenantEventRow?.event_id);
1083
- expect(Number.isFinite(tenantEventId)).toBe(true);
1084
-
1085
- const commitDetailOk = await requestCommitDetail(tenantCommitSeq, {
1086
- partitionId: 'tenant-b',
1087
- });
1088
- expect(commitDetailOk.status).toBe(200);
1089
-
1090
- const commitDetailWrongPartition = await requestCommitDetail(
1091
- tenantCommitSeq,
1092
- {
1093
- partitionId: 'default',
1094
- }
1095
- );
1096
- expect(commitDetailWrongPartition.status).toBe(404);
1097
-
1098
- const eventDetailOk = await requestEventDetail(tenantEventId, {
1099
- partitionId: 'tenant-b',
1100
- });
1101
- expect(eventDetailOk.status).toBe(200);
1102
-
1103
- const eventDetailWrongPartition = await requestEventDetail(tenantEventId, {
1104
- partitionId: 'default',
1105
- });
1106
- expect(eventDetailWrongPartition.status).toBe(404);
1107
-
1108
- const payloadOk = await requestEventPayload(tenantEventId, {
1109
- partitionId: 'tenant-b',
1110
- });
1111
- expect(payloadOk.status).toBe(200);
1112
-
1113
- const payloadWrongPartition = await requestEventPayload(tenantEventId, {
1114
- partitionId: 'default',
1115
- });
1116
- expect(payloadWrongPartition.status).toBe(404);
1117
-
1118
- const evictDefault = await requestEvictClient('shared-client', {
1119
- partitionId: 'default',
1120
- });
1121
- expect(evictDefault.status).toBe(200);
1122
- expect((await evictDefault.json()) as { evicted: boolean }).toEqual({
1123
- evicted: true,
1124
- });
1125
-
1126
- const tenantCursorAfterDefaultEvict = await db
1127
- .selectFrom('sync_client_cursors')
1128
- .select(['client_id'])
1129
- .where('partition_id', '=', 'tenant-b')
1130
- .where('client_id', '=', 'shared-client')
1131
- .executeTakeFirst();
1132
- expect(tenantCursorAfterDefaultEvict).toBeDefined();
1133
-
1134
- const evictTenant = await requestEvictClient('shared-client', {
1135
- partitionId: 'tenant-b',
1136
- });
1137
- expect(evictTenant.status).toBe(200);
1138
- expect((await evictTenant.json()) as { evicted: boolean }).toEqual({
1139
- evicted: true,
1140
- });
1141
-
1142
- const tenantCursorAfterTenantEvict = await db
1143
- .selectFrom('sync_client_cursors')
1144
- .select(['client_id'])
1145
- .where('partition_id', '=', 'tenant-b')
1146
- .where('client_id', '=', 'shared-client')
1147
- .executeTakeFirst();
1148
- expect(tenantCursorAfterTenantEvict).toBeUndefined();
1149
- });
1150
-
1151
- it('filters API keys by type and lifecycle status', async () => {
1152
- const dayMs = 24 * 60 * 60 * 1000;
1153
- const now = Date.now();
1154
- const isoAfter = (days: number): string =>
1155
- new Date(now + days * dayMs).toISOString();
1156
-
1157
- await db
1158
- .insertInto('sync_api_keys')
1159
- .values([
1160
- {
1161
- key_id: 'key-relay-active',
1162
- key_hash: 'hash-1',
1163
- key_prefix: 'srly_active_',
1164
- name: 'relay-active',
1165
- key_type: 'relay',
1166
- scope_keys: ['scope-a'],
1167
- actor_id: 'actor-a',
1168
- created_at: atIso(11),
1169
- expires_at: null,
1170
- last_used_at: null,
1171
- revoked_at: null,
1172
- },
1173
- {
1174
- key_id: 'key-relay-expiring',
1175
- key_hash: 'hash-2',
1176
- key_prefix: 'srly_expire_',
1177
- name: 'relay-expiring',
1178
- key_type: 'relay',
1179
- scope_keys: ['scope-a', 'scope-b'],
1180
- actor_id: null,
1181
- created_at: atIso(12),
1182
- expires_at: isoAfter(3),
1183
- last_used_at: null,
1184
- revoked_at: null,
1185
- },
1186
- {
1187
- key_id: 'key-relay-expired',
1188
- key_hash: 'hash-3',
1189
- key_prefix: 'srly_expired',
1190
- name: 'relay-expired',
1191
- key_type: 'relay',
1192
- scope_keys: [],
1193
- actor_id: null,
1194
- created_at: atIso(13),
1195
- expires_at: isoAfter(-1),
1196
- last_used_at: null,
1197
- revoked_at: null,
1198
- },
1199
- {
1200
- key_id: 'key-relay-revoked',
1201
- key_hash: 'hash-4',
1202
- key_prefix: 'srly_revoked',
1203
- name: 'relay-revoked',
1204
- key_type: 'relay',
1205
- scope_keys: [],
1206
- actor_id: null,
1207
- created_at: atIso(14),
1208
- expires_at: isoAfter(10),
1209
- last_used_at: null,
1210
- revoked_at: isoAfter(0),
1211
- },
1212
- {
1213
- key_id: 'key-admin-future',
1214
- key_hash: 'hash-5',
1215
- key_prefix: 'sadm_future_',
1216
- name: 'admin-future',
1217
- key_type: 'admin',
1218
- scope_keys: ['org:1'],
1219
- actor_id: 'actor-admin',
1220
- created_at: atIso(15),
1221
- expires_at: isoAfter(60),
1222
- last_used_at: null,
1223
- revoked_at: null,
1224
- },
1225
- ])
1226
- .execute();
1227
-
1228
- const relayOnly = await readApiKeys({ type: 'relay' });
1229
- expect(relayOnly.total).toBe(4);
1230
- expect(relayOnly.items.every((item) => item.keyType === 'relay')).toBe(
1231
- true
1232
- );
1233
-
1234
- const revokedOnly = await readApiKeys({ status: 'revoked' });
1235
- expect(revokedOnly.total).toBe(1);
1236
- expect(revokedOnly.items[0]?.name).toBe('relay-revoked');
1237
-
1238
- const activeOnly = await readApiKeys({ status: 'active' });
1239
- expect(activeOnly.total).toBe(3);
1240
- expect(activeOnly.items.some((item) => item.name === 'relay-active')).toBe(
1241
- true
1242
- );
1243
- expect(
1244
- activeOnly.items.some((item) => item.name === 'relay-expiring')
1245
- ).toBe(true);
1246
- expect(activeOnly.items.some((item) => item.name === 'admin-future')).toBe(
1247
- true
1248
- );
1249
- expect(activeOnly.items.some((item) => item.name === 'relay-expired')).toBe(
1250
- false
1251
- );
1252
- expect(activeOnly.items.some((item) => item.name === 'relay-revoked')).toBe(
1253
- false
1254
- );
1255
-
1256
- const expiringDefault = await readApiKeys({ status: 'expiring' });
1257
- expect(expiringDefault.total).toBe(1);
1258
- expect(expiringDefault.items[0]?.name).toBe('relay-expiring');
1259
- });
1260
-
1261
- it('applies custom expiring-window filters for API keys', async () => {
1262
- const dayMs = 24 * 60 * 60 * 1000;
1263
- const now = Date.now();
1264
- const isoAfter = (days: number): string =>
1265
- new Date(now + days * dayMs).toISOString();
1266
-
1267
- await db
1268
- .insertInto('sync_api_keys')
1269
- .values([
1270
- {
1271
- key_id: 'key-expiring-3',
1272
- key_hash: 'hash-e3',
1273
- key_prefix: 'srel_exp_03',
1274
- name: 'expiring-3',
1275
- key_type: 'relay',
1276
- scope_keys: [],
1277
- actor_id: null,
1278
- created_at: atIso(16),
1279
- expires_at: isoAfter(3),
1280
- last_used_at: null,
1281
- revoked_at: null,
1282
- },
1283
- {
1284
- key_id: 'key-expiring-10',
1285
- key_hash: 'hash-e10',
1286
- key_prefix: 'srel_exp_10',
1287
- name: 'expiring-10',
1288
- key_type: 'relay',
1289
- scope_keys: [],
1290
- actor_id: null,
1291
- created_at: atIso(17),
1292
- expires_at: isoAfter(10),
1293
- last_used_at: null,
1294
- revoked_at: null,
1295
- },
1296
- ])
1297
- .execute();
1298
-
1299
- const expiringInSevenDays = await readApiKeys({
1300
- status: 'expiring',
1301
- expiresWithinDays: 7,
1302
- });
1303
- expect(expiringInSevenDays.total).toBe(1);
1304
- expect(expiringInSevenDays.items[0]?.name).toBe('expiring-3');
1305
-
1306
- const expiringInFourteenDays = await readApiKeys({
1307
- status: 'expiring',
1308
- expiresWithinDays: 14,
1309
- });
1310
- expect(expiringInFourteenDays.total).toBe(2);
1311
- const expiringNames = expiringInFourteenDays.items
1312
- .map((item) => item.name)
1313
- .sort();
1314
- expect(expiringNames).toEqual(['expiring-10', 'expiring-3']);
1315
- });
1316
-
1317
- it('bulk revokes active keys and reports already-revoked/not-found ids', async () => {
1318
- const nowIso = atIso(18);
1319
-
1320
- await db
1321
- .insertInto('sync_api_keys')
1322
- .values([
1323
- {
1324
- key_id: 'bulk-active-1',
1325
- key_hash: 'bulk-hash-1',
1326
- key_prefix: 'bulk_active1',
1327
- name: 'bulk-active-1',
1328
- key_type: 'relay',
1329
- scope_keys: [],
1330
- actor_id: null,
1331
- created_at: nowIso,
1332
- expires_at: null,
1333
- last_used_at: null,
1334
- revoked_at: null,
1335
- },
1336
- {
1337
- key_id: 'bulk-active-2',
1338
- key_hash: 'bulk-hash-2',
1339
- key_prefix: 'bulk_active2',
1340
- name: 'bulk-active-2',
1341
- key_type: 'proxy',
1342
- scope_keys: [],
1343
- actor_id: null,
1344
- created_at: nowIso,
1345
- expires_at: null,
1346
- last_used_at: null,
1347
- revoked_at: null,
1348
- },
1349
- {
1350
- key_id: 'bulk-revoked-1',
1351
- key_hash: 'bulk-hash-3',
1352
- key_prefix: 'bulk_revoked',
1353
- name: 'bulk-revoked-1',
1354
- key_type: 'admin',
1355
- scope_keys: [],
1356
- actor_id: null,
1357
- created_at: nowIso,
1358
- expires_at: null,
1359
- last_used_at: null,
1360
- revoked_at: nowIso,
1361
- },
1362
- ])
1363
- .execute();
1364
-
1365
- const response = await requestBulkRevokeApiKeys([
1366
- 'bulk-active-1',
1367
- 'bulk-active-2',
1368
- 'bulk-revoked-1',
1369
- 'bulk-missing-1',
1370
- ]);
1371
- expect(response.status).toBe(200);
1372
-
1373
- const payload = (await response.json()) as {
1374
- requestedCount: number;
1375
- revokedCount: number;
1376
- alreadyRevokedCount: number;
1377
- notFoundCount: number;
1378
- revokedKeyIds: string[];
1379
- alreadyRevokedKeyIds: string[];
1380
- notFoundKeyIds: string[];
1381
- };
1382
-
1383
- expect(payload.requestedCount).toBe(4);
1384
- expect(payload.revokedCount).toBe(2);
1385
- expect(payload.alreadyRevokedCount).toBe(1);
1386
- expect(payload.notFoundCount).toBe(1);
1387
- expect(payload.revokedKeyIds.sort()).toEqual([
1388
- 'bulk-active-1',
1389
- 'bulk-active-2',
1390
- ]);
1391
- expect(payload.alreadyRevokedKeyIds).toEqual(['bulk-revoked-1']);
1392
- expect(payload.notFoundKeyIds).toEqual(['bulk-missing-1']);
1393
-
1394
- const revokedRows = await db
1395
- .selectFrom('sync_api_keys')
1396
- .select(['key_id', 'revoked_at'])
1397
- .where('key_id', 'in', ['bulk-active-1', 'bulk-active-2'])
1398
- .execute();
1399
- expect(revokedRows.every((row) => row.revoked_at !== null)).toBe(true);
1400
- });
1401
-
1402
- it('stages key rotation without revoking the original key', async () => {
1403
- const nowIso = atIso(19);
1404
-
1405
- await db
1406
- .insertInto('sync_api_keys')
1407
- .values({
1408
- key_id: 'stage-old-key',
1409
- key_hash: 'stage-hash-1',
1410
- key_prefix: 'stage_old__',
1411
- name: 'stage-old',
1412
- key_type: 'relay',
1413
- scope_keys: ['scope-x'],
1414
- actor_id: 'actor-stage',
1415
- created_at: nowIso,
1416
- expires_at: null,
1417
- last_used_at: null,
1418
- revoked_at: null,
1419
- })
1420
- .execute();
1421
-
1422
- const response = await requestStageRotateApiKey('stage-old-key');
1423
- expect(response.status).toBe(200);
1424
-
1425
- const payload = (await response.json()) as {
1426
- key: {
1427
- keyId: string;
1428
- keyPrefix: string;
1429
- name: string;
1430
- keyType: 'relay' | 'proxy' | 'admin';
1431
- scopeKeys: string[];
1432
- actorId: string | null;
1433
- };
1434
- secretKey: string;
1435
- };
1436
-
1437
- expect(payload.key.keyId).not.toBe('stage-old-key');
1438
- expect(payload.key.name).toBe('stage-old');
1439
- expect(payload.key.keyType).toBe('relay');
1440
- expect(payload.key.scopeKeys).toEqual(['scope-x']);
1441
- expect(payload.key.actorId).toBe('actor-stage');
1442
- expect(payload.secretKey.startsWith(payload.key.keyPrefix)).toBe(true);
1443
-
1444
- const oldRow = await db
1445
- .selectFrom('sync_api_keys')
1446
- .select(['revoked_at'])
1447
- .where('key_id', '=', 'stage-old-key')
1448
- .executeTakeFirst();
1449
- expect(oldRow?.revoked_at).toBeNull();
1450
-
1451
- const newRow = await db
1452
- .selectFrom('sync_api_keys')
1453
- .select(['key_id', 'revoked_at'])
1454
- .where('key_id', '=', payload.key.keyId)
1455
- .executeTakeFirst();
1456
- expect(newRow?.key_id).toBe(payload.key.keyId);
1457
- expect(newRow?.revoked_at).toBeNull();
1458
- });
1459
-
1460
- it('rejects unauthenticated timeline requests', async () => {
1461
- const response = await requestTimeline({ authenticated: false });
1462
- expect(response.status).toBe(401);
1463
- expect(await response.json()).toEqual({ error: 'UNAUTHENTICATED' });
1464
- });
1465
-
1466
- it('returns payload snapshots for events with payload refs', async () => {
1467
- const row = await db
1468
- .selectFrom('sync_request_events')
1469
- .select(['event_id'])
1470
- .where('request_id', '=', 'req-1')
1471
- .executeTakeFirst();
1472
-
1473
- expect(row).toBeDefined();
1474
- const eventId = Number(row?.event_id);
1475
- const response = await requestEventPayload(eventId);
1476
-
1477
- expect(response.status).toBe(200);
1478
- const payload = (await response.json()) as {
1479
- payloadRef: string;
1480
- partitionId: string;
1481
- requestPayload: { clientCommitId: string };
1482
- responsePayload: { status: string };
1483
- };
1484
-
1485
- expect(payload.payloadRef).toBe('payload-1');
1486
- expect(payload.partitionId).toBe('default');
1487
- expect(payload.requestPayload.clientCommitId).toBe('commit-a');
1488
- expect(payload.responsePayload.status).toBe('applied');
1489
- });
1490
-
1491
- it('deletes payload snapshots when clearing events', async () => {
1492
- const response = await requestClearEvents();
1493
- expect(response.status).toBe(200);
1494
-
1495
- const eventCountRow = await db
1496
- .selectFrom('sync_request_events')
1497
- .select(({ fn }) => fn.countAll().as('total'))
1498
- .executeTakeFirst();
1499
- expect(Number(eventCountRow?.total ?? 0)).toBe(0);
1500
-
1501
- const payloadCountRow = await db
1502
- .selectFrom('sync_request_payloads')
1503
- .select(({ fn }) => fn.countAll().as('total'))
1504
- .executeTakeFirst();
1505
- expect(Number(payloadCountRow?.total ?? 0)).toBe(0);
1506
- });
1507
-
1508
- it('prunes orphaned payload snapshots during event pruning', async () => {
1509
- await db
1510
- .insertInto('sync_request_payloads')
1511
- .values({
1512
- payload_ref: 'payload-orphan',
1513
- partition_id: 'default',
1514
- request_payload: JSON.stringify({ orphan: true }),
1515
- response_payload: JSON.stringify({ ok: true }),
1516
- created_at: atIso(33),
1517
- })
1518
- .execute();
1519
-
1520
- const response = await requestPruneEvents();
1521
- expect(response.status).toBe(200);
1522
-
1523
- const orphan = await db
1524
- .selectFrom('sync_request_payloads')
1525
- .select(['payload_ref'])
1526
- .where('payload_ref', '=', 'payload-orphan')
1527
- .executeTakeFirst();
1528
- expect(orphan).toBeUndefined();
1529
- });
1530
-
1531
- it('disables credentialed CORS headers when wildcard origin is configured', async () => {
1532
- const response = await app.request('http://localhost/console/events', {
1533
- method: 'OPTIONS',
1534
- headers: {
1535
- Origin: 'https://example.com',
1536
- 'Access-Control-Request-Method': 'GET',
1537
- },
1538
- });
1539
-
1540
- expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*');
1541
- expect(response.headers.get('Access-Control-Allow-Credentials')).toBeNull();
1542
- });
1543
- });