@bleedingdev/modern-js-server-runtime-extensions 3.9.0-ultramodern.6 → 3.9.0-ultramodern.8

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.
@@ -5,991 +5,298 @@ import path from 'path';
5
5
  import { injectTelemetryPlugin } from '../src/telemetry';
6
6
  import { getDefaultAppContext, getDefaultConfig } from './helpers';
7
7
 
8
- const makeTempDir = () =>
9
- fs.mkdtempSync(
8
+ type ServerBase = ReturnType<typeof createServerBase>;
9
+
10
+ const SIGNAL_ENDPOINT = '/_modern/contract-gates/runtime-fallback';
11
+ const TOKEN_HEADER = 'x-modernjs-runtime-signal-token';
12
+
13
+ /**
14
+ * Boots a real server with the telemetry plugin and the given snapshot-
15
+ * observation
16
+ * config, then tears the temp workspace down. `server.init()` is left to the
17
+ * caller so fail-closed init can be asserted.
18
+ */
19
+ const withHealthObservation = async (
20
+ snapshotObservation: Record<string, unknown>,
21
+ run: (server: ServerBase, snapshotPath: string) => Promise<void>,
22
+ ) => {
23
+ const tempDir = fs.mkdtempSync(
10
24
  path.join(os.tmpdir(), 'modern-telemetry-health-observation-'),
11
25
  );
12
-
13
- describe('telemetry health observation runtime signal', () => {
14
- test('accepts runtime fallback signal and persists gate snapshot', async () => {
15
- const tempDir = makeTempDir();
16
- const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
17
-
18
- try {
19
- const config = getDefaultConfig();
20
- config.server = {
21
- telemetry: {
26
+ const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
27
+ try {
28
+ const config = getDefaultConfig();
29
+ config.server = {
30
+ telemetry: {
31
+ enabled: true,
32
+ health: {
22
33
  enabled: true,
23
- health: {
34
+ minConsecutiveFailedEvaluations: 1,
35
+ snapshotObservation: {
24
36
  enabled: true,
25
- minConsecutiveFailedEvaluations: 1,
26
- snapshotObservation: {
27
- enabled: true,
28
- gateSnapshotPath: snapshotPath,
29
- pollIntervalMs: 20,
30
- gateStaleAfterMs: 60_000,
31
- runtimeFallbackSignal: {
32
- enabled: true,
33
- endpoint: '/_modern/contract-gates/runtime-fallback',
34
- gateName: 'runtime-mf-fallback-health',
35
- failureHoldMs: 5_000,
36
- maxBodyBytes: 4_096,
37
- auth: {
38
- expectedValue: 'accept-signal-token',
39
- },
40
- },
41
- },
37
+ gateSnapshotPath: snapshotPath,
38
+ ...snapshotObservation,
42
39
  },
43
40
  },
44
- } as any;
45
-
46
- const server = createServerBase({
47
- config,
48
- pwd: tempDir,
49
- appContext: getDefaultAppContext(),
50
- });
51
-
52
- server.addPlugins([
53
- ...createDefaultPlugins({
54
- logger: false,
55
- }),
56
- injectTelemetryPlugin(),
57
- ]);
58
-
59
- await server.init();
60
-
61
- const response = await server.request(
62
- '/_modern/contract-gates/runtime-fallback',
63
- {
64
- method: 'POST',
65
- headers: new Headers({
66
- 'content-type': 'application/json',
67
- 'x-modernjs-runtime-signal-token': 'accept-signal-token',
68
- }),
69
- body: JSON.stringify({
70
- reason: 'remote_load_failed',
71
- phase: 'load',
72
- appName: 'dashboard',
73
- entry: 'https://remote.example.com/remoteEntry.js',
74
- }),
75
- },
76
- {},
77
- );
78
-
79
- expect(response.status).toBe(202);
80
- expect(fs.existsSync(snapshotPath)).toBe(true);
41
+ },
42
+ } as any;
43
+
44
+ const server = createServerBase({
45
+ config,
46
+ pwd: tempDir,
47
+ appContext: getDefaultAppContext(),
48
+ });
49
+ server.addPlugins([
50
+ ...createDefaultPlugins({ logger: false }),
51
+ injectTelemetryPlugin(),
52
+ ]);
53
+
54
+ await run(server, snapshotPath);
55
+ } finally {
56
+ fs.rmSync(tempDir, { recursive: true, force: true });
57
+ }
58
+ };
81
59
 
82
- const snapshot = JSON.parse(fs.readFileSync(snapshotPath, 'utf8')) as {
83
- gates?: Record<string, any>;
84
- };
85
- const gate = snapshot.gates?.['runtime-mf-fallback-health'];
86
- expect(gate).toBeTruthy();
87
- expect(gate.passed).toBe(false);
88
- expect(String(gate.reason)).toContain(
89
- 'runtime_fallback:remote_load_failed',
90
- );
91
- expect(typeof gate.expiresAt).toBe('number');
92
- expect(gate.expiresAt).toBeGreaterThan(Date.now());
93
- } finally {
94
- fs.rmSync(tempDir, { recursive: true, force: true });
95
- }
96
- });
60
+ const postSignal = (server: ServerBase, token: string | null, body: unknown) =>
61
+ server.request(
62
+ SIGNAL_ENDPOINT,
63
+ {
64
+ method: 'POST',
65
+ headers: new Headers({
66
+ 'content-type': 'application/json',
67
+ ...(token ? { [TOKEN_HEADER]: token } : {}),
68
+ }),
69
+ body: JSON.stringify(body),
70
+ },
71
+ {},
72
+ );
97
73
 
74
+ describe('telemetry health observation runtime signal', () => {
98
75
  test('rejects oversized runtime fallback signal payload', async () => {
99
- const tempDir = makeTempDir();
100
- const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
101
-
102
- try {
103
- const config = getDefaultConfig();
104
- config.server = {
105
- telemetry: {
76
+ await withHealthObservation(
77
+ {
78
+ runtimeFallbackSignal: {
106
79
  enabled: true,
107
- health: {
108
- enabled: true,
109
- minConsecutiveFailedEvaluations: 1,
110
- snapshotObservation: {
111
- enabled: true,
112
- gateSnapshotPath: snapshotPath,
113
- runtimeFallbackSignal: {
114
- enabled: true,
115
- endpoint: '/_modern/contract-gates/runtime-fallback',
116
- maxBodyBytes: 16,
117
- auth: {
118
- expectedValue: 'oversize-signal-token',
119
- },
120
- },
121
- },
122
- },
123
- },
124
- } as any;
125
-
126
- const server = createServerBase({
127
- config,
128
- pwd: tempDir,
129
- appContext: getDefaultAppContext(),
130
- });
131
- server.addPlugins([
132
- ...createDefaultPlugins({
133
- logger: false,
134
- }),
135
- injectTelemetryPlugin(),
136
- ]);
137
-
138
- await server.init();
139
-
140
- const response = await server.request(
141
- '/_modern/contract-gates/runtime-fallback',
142
- {
143
- method: 'POST',
144
- headers: new Headers({
145
- 'content-type': 'application/json',
146
- 'x-modernjs-runtime-signal-token': 'oversize-signal-token',
147
- }),
148
- body: JSON.stringify({
149
- reason: 'x'.repeat(2_048),
150
- }),
80
+ endpoint: SIGNAL_ENDPOINT,
81
+ maxBodyBytes: 16,
82
+ auth: { expectedValue: 'oversize-signal-token' },
151
83
  },
152
- {},
153
- );
154
-
155
- expect(response.status).toBe(413);
156
- const payload = (await response.json()) as {
157
- ok?: boolean;
158
- error?: string;
159
- };
160
- expect(payload.ok).toBe(false);
161
- expect(String(payload.error)).toContain('payload too large');
162
- } finally {
163
- fs.rmSync(tempDir, { recursive: true, force: true });
164
- }
84
+ },
85
+ async server => {
86
+ await server.init();
87
+ const response = await postSignal(server, 'oversize-signal-token', {
88
+ reason: 'x'.repeat(2_048),
89
+ });
90
+ expect(response.status).toBe(413);
91
+ const payload = (await response.json()) as { error?: string };
92
+ expect(String(payload.error)).toContain('payload too large');
93
+ },
94
+ );
165
95
  });
166
96
 
167
97
  test('requires runtime fallback auth token when configured', async () => {
168
- const tempDir = makeTempDir();
169
- const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
170
-
171
- try {
172
- const config = getDefaultConfig();
173
- config.server = {
174
- telemetry: {
175
- enabled: true,
176
- health: {
177
- enabled: true,
178
- minConsecutiveFailedEvaluations: 1,
179
- snapshotObservation: {
180
- enabled: true,
181
- gateSnapshotPath: snapshotPath,
182
- runtimeFallbackSignal: {
183
- enabled: true,
184
- endpoint: '/_modern/contract-gates/runtime-fallback',
185
- auth: {
186
- enabled: true,
187
- headerName: 'x-modernjs-runtime-signal-token',
188
- expectedValue: 'top-secret-token',
189
- },
190
- },
191
- },
192
- },
193
- },
194
- } as any;
195
-
196
- const server = createServerBase({
197
- config,
198
- pwd: tempDir,
199
- appContext: getDefaultAppContext(),
200
- });
201
- server.addPlugins([
202
- ...createDefaultPlugins({
203
- logger: false,
204
- }),
205
- injectTelemetryPlugin(),
206
- ]);
207
-
208
- await server.init();
209
-
210
- const rejected = await server.request(
211
- '/_modern/contract-gates/runtime-fallback',
212
- {
213
- method: 'POST',
214
- headers: new Headers({
215
- 'content-type': 'application/json',
216
- }),
217
- body: JSON.stringify({
218
- reason: 'remote_load_failed',
219
- phase: 'load',
220
- appName: 'crm',
221
- }),
222
- },
223
- {},
224
- );
225
- expect(rejected.status).toBe(401);
226
- expect(fs.existsSync(snapshotPath)).toBe(false);
227
-
228
- const accepted = await server.request(
229
- '/_modern/contract-gates/runtime-fallback',
230
- {
231
- method: 'POST',
232
- headers: new Headers({
233
- 'content-type': 'application/json',
234
- 'x-modernjs-runtime-signal-token': 'top-secret-token',
235
- }),
236
- body: JSON.stringify({
237
- reason: 'remote_load_failed',
238
- phase: 'load',
239
- appName: 'crm',
240
- }),
241
- },
242
- {},
243
- );
244
- expect(accepted.status).toBe(202);
245
- expect(fs.existsSync(snapshotPath)).toBe(true);
246
- } finally {
247
- fs.rmSync(tempDir, { recursive: true, force: true });
248
- }
249
- });
250
-
251
- test('exposes runtime status endpoint and applies auth when runtime signal auth is enabled', async () => {
252
- const tempDir = makeTempDir();
253
- const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
254
-
255
- try {
256
- const config = getDefaultConfig();
257
- config.server = {
258
- telemetry: {
98
+ await withHealthObservation(
99
+ {
100
+ runtimeFallbackSignal: {
259
101
  enabled: true,
260
- health: {
102
+ endpoint: SIGNAL_ENDPOINT,
103
+ auth: {
261
104
  enabled: true,
262
- minConsecutiveFailedEvaluations: 1,
263
- snapshotObservation: {
264
- enabled: true,
265
- gateSnapshotPath: snapshotPath,
266
- runtimeFallbackSignal: {
267
- enabled: true,
268
- endpoint: '/_modern/contract-gates/runtime-fallback',
269
- auth: {
270
- enabled: true,
271
- headerName: 'x-modernjs-runtime-signal-token',
272
- expectedValue: 'status-token',
273
- },
274
- },
275
- },
105
+ headerName: TOKEN_HEADER,
106
+ expectedValue: 'top-secret-token',
276
107
  },
277
108
  },
278
- } as any;
279
-
280
- const server = createServerBase({
281
- config,
282
- pwd: tempDir,
283
- appContext: getDefaultAppContext(),
284
- });
285
- server.addPlugins([
286
- ...createDefaultPlugins({
287
- logger: false,
288
- }),
289
- injectTelemetryPlugin(),
290
- ]);
291
-
292
- await server.init();
293
-
294
- const unauthorized = await server.request(
295
- '/_modern/runtime/status',
296
- {
297
- method: 'GET',
298
- headers: new Headers(),
299
- },
300
- {},
301
- );
302
- expect(unauthorized.status).toBe(401);
303
-
304
- const authorized = await server.request(
305
- '/_modern/runtime/status',
306
- {
307
- method: 'GET',
308
- headers: new Headers({
309
- 'x-modernjs-runtime-signal-token': 'status-token',
310
- }),
311
- },
312
- {},
313
- );
314
- expect(authorized.status).toBe(200);
315
- const payload = (await authorized.json()) as {
316
- ok?: boolean;
317
- telemetry?: { queueStats?: { capacity?: number } };
318
- health?: { enabled?: boolean };
319
- runtimeFallbackSignal?: {
320
- enabled?: boolean;
321
- endpoint?: string;
322
- auth?: { enabled?: boolean };
109
+ },
110
+ async (server, snapshotPath) => {
111
+ await server.init();
112
+ const signal = {
113
+ reason: 'remote_load_failed',
114
+ phase: 'load',
115
+ appName: 'crm',
323
116
  };
324
- };
325
- expect(payload.ok).toBe(true);
326
- expect(payload.telemetry?.queueStats?.capacity).toBeGreaterThan(0);
327
- expect(payload.health?.enabled).toBe(true);
328
- expect(payload.runtimeFallbackSignal?.enabled).toBe(true);
329
- expect(payload.runtimeFallbackSignal?.endpoint).toBe(
330
- '/_modern/contract-gates/runtime-fallback',
331
- );
332
- expect(payload.runtimeFallbackSignal?.auth?.enabled).toBe(true);
333
- } finally {
334
- fs.rmSync(tempDir, { recursive: true, force: true });
335
- }
336
- });
337
117
 
338
- test('supports pluggable contract gate snapshot stateStore modules', async () => {
339
- const tempDir = makeTempDir();
340
- const defaultSnapshotPath = path.join(
341
- tempDir,
342
- '.modern/contract-gates.json',
343
- );
344
- const customSnapshotPath = path.join(tempDir, '.state-store/gates.json');
345
- const stateStoreModulePath = path.join(tempDir, 'gate-state-store.js');
118
+ const rejected = await postSignal(server, null, signal);
119
+ expect(rejected.status).toBe(401);
120
+ expect(fs.existsSync(snapshotPath)).toBe(false);
346
121
 
347
- fs.writeFileSync(
348
- stateStoreModulePath,
349
- `'use strict';
350
- const fs = require('fs');
351
- const path = require('path');
352
- exports.createContractGateSnapshotStore = ({ gateSnapshotPath, options }) => {
353
- const targetPath = options && typeof options.snapshotPath === 'string'
354
- ? options.snapshotPath
355
- : gateSnapshotPath;
356
- return {
357
- name: 'test-state-store',
358
- async readSnapshot() {
359
- if (!fs.existsSync(targetPath)) {
360
- return undefined;
361
- }
362
- return JSON.parse(fs.readFileSync(targetPath, 'utf8'));
363
- },
364
- async writeSnapshot(snapshot) {
365
- fs.mkdirSync(path.dirname(targetPath), { recursive: true });
366
- fs.writeFileSync(targetPath, JSON.stringify(snapshot, null, 2));
367
- },
368
- };
369
- };
370
- `,
371
- 'utf8',
122
+ const accepted = await postSignal(server, 'top-secret-token', signal);
123
+ expect(accepted.status).toBe(202);
124
+ expect(fs.existsSync(snapshotPath)).toBe(true);
125
+ },
372
126
  );
373
-
374
- try {
375
- const config = getDefaultConfig();
376
- config.server = {
377
- telemetry: {
378
- enabled: true,
379
- health: {
380
- enabled: true,
381
- minConsecutiveFailedEvaluations: 1,
382
- snapshotObservation: {
383
- enabled: true,
384
- gateSnapshotPath: defaultSnapshotPath,
385
- stateStore: {
386
- module: stateStoreModulePath,
387
- options: {
388
- snapshotPath: customSnapshotPath,
389
- },
390
- },
391
- runtimeFallbackSignal: {
392
- enabled: true,
393
- endpoint: '/_modern/contract-gates/runtime-fallback',
394
- auth: {
395
- expectedValue: 'state-store-token',
396
- },
397
- },
398
- },
399
- },
400
- },
401
- } as any;
402
-
403
- const server = createServerBase({
404
- config,
405
- pwd: tempDir,
406
- appContext: getDefaultAppContext(),
407
- });
408
- server.addPlugins([
409
- ...createDefaultPlugins({
410
- logger: false,
411
- }),
412
- injectTelemetryPlugin(),
413
- ]);
414
-
415
- await server.init();
416
-
417
- const response = await server.request(
418
- '/_modern/contract-gates/runtime-fallback',
419
- {
420
- method: 'POST',
421
- headers: new Headers({
422
- 'content-type': 'application/json',
423
- 'x-modernjs-runtime-signal-token': 'state-store-token',
424
- }),
425
- body: JSON.stringify({
426
- reason: 'remote_mount_failed',
427
- phase: 'mount',
428
- appName: 'crm',
429
- }),
430
- },
431
- {},
432
- );
433
-
434
- expect(response.status).toBe(202);
435
- expect(fs.existsSync(defaultSnapshotPath)).toBe(false);
436
- expect(fs.existsSync(customSnapshotPath)).toBe(true);
437
-
438
- const snapshot = JSON.parse(fs.readFileSync(customSnapshotPath, 'utf8'));
439
- expect(snapshot.gates?.['runtime-mf-fallback-health']?.passed).toBe(
440
- false,
441
- );
442
- } finally {
443
- fs.rmSync(tempDir, { recursive: true, force: true });
444
- }
445
127
  });
446
128
 
447
129
  test('enforces runtime fallback trust policy before mutating gate snapshots', async () => {
448
- const tempDir = makeTempDir();
449
- const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
450
-
451
- try {
452
- const config = getDefaultConfig();
453
- config.server = {
454
- telemetry: {
130
+ await withHealthObservation(
131
+ {
132
+ runtimeFallbackSignal: {
455
133
  enabled: true,
456
- health: {
457
- enabled: true,
458
- minConsecutiveFailedEvaluations: 1,
459
- snapshotObservation: {
460
- enabled: true,
461
- gateSnapshotPath: snapshotPath,
462
- runtimeFallbackSignal: {
463
- enabled: true,
464
- endpoint: '/_modern/contract-gates/runtime-fallback',
465
- auth: {
466
- expectedValue: 'trust-policy-token',
467
- },
468
- trustPolicy: {
469
- allowedApps: ['crm-shell'],
470
- allowedEntryOrigins: ['https://erp.example.com'],
471
- expectedRuntimeDigests: {
472
- 'crm-shell': 'digest-crm-v1',
473
- },
474
- enforceRuntimeDigest: true,
475
- },
476
- },
477
- },
134
+ endpoint: SIGNAL_ENDPOINT,
135
+ auth: { expectedValue: 'trust-policy-token' },
136
+ trustPolicy: {
137
+ allowedApps: ['crm-shell'],
138
+ allowedEntryOrigins: ['https://erp.example.com'],
139
+ expectedRuntimeDigests: { 'crm-shell': 'digest-crm-v1' },
140
+ enforceRuntimeDigest: true,
478
141
  },
479
142
  },
480
- } as any;
481
-
482
- const server = createServerBase({
483
- config,
484
- pwd: tempDir,
485
- appContext: getDefaultAppContext(),
486
- });
487
- server.addPlugins([
488
- ...createDefaultPlugins({
489
- logger: false,
490
- }),
491
- injectTelemetryPlugin(),
492
- ]);
493
-
494
- await server.init();
495
-
496
- const untrustedApp = await server.request(
497
- '/_modern/contract-gates/runtime-fallback',
498
- {
499
- method: 'POST',
500
- headers: new Headers({
501
- 'content-type': 'application/json',
502
- 'x-modernjs-runtime-signal-token': 'trust-policy-token',
503
- }),
504
- body: JSON.stringify({
505
- reason: 'remote_load_failed',
506
- phase: 'load',
507
- appName: 'unknown-app',
508
- entry: 'https://erp.example.com/remoteEntry.js',
509
- runtimeDigest: 'digest-crm-v1',
510
- }),
511
- },
512
- {},
513
- );
514
- expect(untrustedApp.status).toBe(403);
515
-
516
- const digestMismatch = await server.request(
517
- '/_modern/contract-gates/runtime-fallback',
518
- {
519
- method: 'POST',
520
- headers: new Headers({
521
- 'content-type': 'application/json',
522
- 'x-modernjs-runtime-signal-token': 'trust-policy-token',
523
- }),
524
- body: JSON.stringify({
525
- reason: 'remote_load_failed',
526
- phase: 'load',
527
- appName: 'crm-shell',
528
- entry: 'https://erp.example.com/remoteEntry.js',
529
- runtimeDigest: 'digest-wrong',
530
- }),
531
- },
532
- {},
533
- );
534
- expect(digestMismatch.status).toBe(403);
143
+ },
144
+ async (server, snapshotPath) => {
145
+ await server.init();
146
+ const base = {
147
+ reason: 'remote_load_failed',
148
+ phase: 'load',
149
+ appName: 'crm-shell',
150
+ entry: 'https://erp.example.com/remoteEntry.js',
151
+ runtimeDigest: 'digest-crm-v1',
152
+ };
535
153
 
536
- const trusted = await server.request(
537
- '/_modern/contract-gates/runtime-fallback',
538
- {
539
- method: 'POST',
540
- headers: new Headers({
541
- 'content-type': 'application/json',
542
- 'x-modernjs-runtime-signal-token': 'trust-policy-token',
543
- }),
544
- body: JSON.stringify({
545
- reason: 'remote_load_failed',
546
- phase: 'load',
547
- appName: 'crm-shell',
548
- entry: 'https://erp.example.com/remoteEntry.js',
549
- runtimeDigest: 'digest-crm-v1',
550
- metadata: {
551
- compatibility: {
552
- '@tanstack/react-router': '1.170.15',
553
- },
554
- remote: 'remote/Widget',
555
- },
556
- }),
557
- },
558
- {},
559
- );
560
- expect(trusted.status).toBe(202);
154
+ const untrustedApp = await postSignal(server, 'trust-policy-token', {
155
+ ...base,
156
+ appName: 'unknown-app',
157
+ });
158
+ expect(untrustedApp.status).toBe(403);
159
+
160
+ const digestMismatch = await postSignal(server, 'trust-policy-token', {
161
+ ...base,
162
+ runtimeDigest: 'digest-wrong',
163
+ });
164
+ expect(digestMismatch.status).toBe(403);
165
+
166
+ const trusted = await postSignal(server, 'trust-policy-token', {
167
+ ...base,
168
+ metadata: {
169
+ compatibility: { '@tanstack/react-router': '1.170.15' },
170
+ },
171
+ });
172
+ expect(trusted.status).toBe(202);
561
173
 
562
- const snapshot = JSON.parse(fs.readFileSync(snapshotPath, 'utf8')) as {
563
- gates?: Record<string, any>;
564
- };
565
- expect(snapshot.gates?.['runtime-mf-fallback-health']?.passed).toBe(
566
- false,
567
- );
568
- expect(
569
- snapshot.gates?.['runtime-mf-fallback-health']?.metadata?.metadata
570
- ?.compatibility?.['@tanstack/react-router'],
571
- ).toBe('1.170.15');
572
- expect(
573
- snapshot.gates?.['runtime-mf-fallback-health']?.metadata?.metadata
574
- ?.remote,
575
- ).toBe('remote/Widget');
576
- } finally {
577
- fs.rmSync(tempDir, { recursive: true, force: true });
578
- }
174
+ const snapshot = JSON.parse(fs.readFileSync(snapshotPath, 'utf8')) as {
175
+ gates?: Record<string, any>;
176
+ };
177
+ const gate = snapshot.gates?.['runtime-mf-fallback-health'];
178
+ expect(gate?.passed).toBe(false);
179
+ expect(
180
+ gate?.metadata?.metadata?.compatibility?.['@tanstack/react-router'],
181
+ ).toBe('1.170.15');
182
+ },
183
+ );
579
184
  });
580
185
 
581
- test('deduplicates repeated fallback events and enforces rate limits per source window', async () => {
582
- const tempDir = makeTempDir();
583
- const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
584
-
585
- try {
586
- const config = getDefaultConfig();
587
- config.server = {
588
- telemetry: {
186
+ test('dedupes repeated fallback events and rate limits rotated identities', async () => {
187
+ await withHealthObservation(
188
+ {
189
+ runtimeFallbackSignal: {
589
190
  enabled: true,
590
- health: {
591
- enabled: true,
592
- minConsecutiveFailedEvaluations: 1,
593
- snapshotObservation: {
594
- enabled: true,
595
- gateSnapshotPath: snapshotPath,
596
- runtimeFallbackSignal: {
597
- enabled: true,
598
- endpoint: '/_modern/contract-gates/runtime-fallback',
599
- auth: {
600
- expectedValue: 'rate-limit-token',
601
- },
602
- trustPolicy: {
603
- allowedApps: ['crm-shell'],
604
- dedupeWindowMs: 60_000,
605
- maxSignalsPerWindow: 1,
606
- windowMs: 60_000,
607
- },
608
- },
609
- },
191
+ endpoint: SIGNAL_ENDPOINT,
192
+ auth: { expectedValue: 'rate-limit-token' },
193
+ trustPolicy: {
194
+ dedupeWindowMs: 60_000,
195
+ maxSignalsPerWindow: 1,
196
+ windowMs: 60_000,
610
197
  },
611
198
  },
612
- } as any;
613
-
614
- const server = createServerBase({
615
- config,
616
- pwd: tempDir,
617
- appContext: getDefaultAppContext(),
618
- });
619
- server.addPlugins([
620
- ...createDefaultPlugins({
621
- logger: false,
622
- }),
623
- injectTelemetryPlugin(),
624
- ]);
625
-
626
- await server.init();
627
-
628
- const payload = {
629
- reason: 'remote_mount_failed',
630
- phase: 'mount',
631
- appName: 'crm-shell',
632
- entry: 'https://erp.example.com/remoteEntry.js',
633
- };
199
+ },
200
+ async server => {
201
+ await server.init();
202
+ const sendSignal = (appName: string) =>
203
+ postSignal(server, 'rate-limit-token', {
204
+ reason: 'remote_mount_failed',
205
+ phase: 'mount',
206
+ appName,
207
+ entry: `https://${appName}.example.com/remoteEntry.js`,
208
+ });
634
209
 
635
- const first = await server.request(
636
- '/_modern/contract-gates/runtime-fallback',
637
- {
638
- method: 'POST',
639
- headers: new Headers({
640
- 'content-type': 'application/json',
641
- 'x-modernjs-runtime-signal-token': 'rate-limit-token',
642
- }),
643
- body: JSON.stringify(payload),
644
- },
645
- {},
646
- );
647
- expect(first.status).toBe(202);
210
+ expect((await sendSignal('app-a')).status).toBe(202);
648
211
 
649
- const duplicate = await server.request(
650
- '/_modern/contract-gates/runtime-fallback',
651
- {
652
- method: 'POST',
653
- headers: new Headers({
654
- 'content-type': 'application/json',
655
- 'x-modernjs-runtime-signal-token': 'rate-limit-token',
656
- }),
657
- body: JSON.stringify(payload),
658
- },
659
- {},
660
- );
661
- expect(duplicate.status).toBe(202);
662
- const duplicateBody = (await duplicate.json()) as {
663
- deduped?: boolean;
664
- };
665
- expect(duplicateBody.deduped).toBe(true);
212
+ const duplicate = await sendSignal('app-a');
213
+ expect(duplicate.status).toBe(202);
214
+ expect(((await duplicate.json()) as any).deduped).toBe(true);
666
215
 
667
- const secondUnique = await server.request(
668
- '/_modern/contract-gates/runtime-fallback',
669
- {
670
- method: 'POST',
671
- headers: new Headers({
672
- 'content-type': 'application/json',
673
- 'x-modernjs-runtime-signal-token': 'rate-limit-token',
674
- }),
675
- body: JSON.stringify({
676
- ...payload,
677
- reason: 'remote_load_failed',
678
- }),
679
- },
680
- {},
681
- );
682
- expect(secondUnique.status).toBe(429);
683
- } finally {
684
- fs.rmSync(tempDir, { recursive: true, force: true });
685
- }
216
+ // A rotated appName/entry pair used to mint a fresh rate-limit bucket;
217
+ // the limiter is now keyed on connection identity instead.
218
+ expect((await sendSignal('app-b')).status).toBe(429);
219
+ },
220
+ );
686
221
  });
687
222
 
688
223
  test('keeps the runtime fallback signal endpoint disabled unless explicitly enabled', async () => {
689
- const tempDir = makeTempDir();
690
- const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
691
-
692
- try {
693
- const config = getDefaultConfig();
694
- config.server = {
695
- telemetry: {
696
- enabled: true,
697
- health: {
698
- enabled: true,
699
- minConsecutiveFailedEvaluations: 1,
700
- snapshotObservation: {
701
- enabled: true,
702
- gateSnapshotPath: snapshotPath,
703
- // no runtimeFallbackSignal config: the health observation switch must
704
- // stay OFF by default.
705
- },
706
- },
707
- },
708
- } as any;
709
-
710
- const server = createServerBase({
711
- config,
712
- pwd: tempDir,
713
- appContext: getDefaultAppContext(),
714
- });
715
- server.addPlugins([
716
- ...createDefaultPlugins({
717
- logger: false,
718
- }),
719
- injectTelemetryPlugin(),
720
- ]);
721
-
224
+ // no runtimeFallbackSignal config: the health kill switch must stay OFF.
225
+ await withHealthObservation({}, async (server, snapshotPath) => {
722
226
  await server.init();
723
-
724
- const response = await server.request(
725
- '/_modern/contract-gates/runtime-fallback',
726
- {
727
- method: 'POST',
728
- headers: new Headers({
729
- 'content-type': 'application/json',
730
- }),
731
- body: JSON.stringify({
732
- reason: 'remote_load_failed',
733
- phase: 'load',
734
- appName: 'dashboard',
735
- }),
736
- },
737
- {},
738
- );
739
-
227
+ const response = await postSignal(server, null, {
228
+ reason: 'remote_load_failed',
229
+ phase: 'load',
230
+ appName: 'dashboard',
231
+ });
740
232
  expect(response.status).toBe(404);
741
233
  expect(fs.existsSync(snapshotPath)).toBe(false);
742
- } finally {
743
- fs.rmSync(tempDir, { recursive: true, force: true });
744
- }
234
+ });
745
235
  });
746
236
 
747
237
  test('refuses to enable the runtime fallback signal endpoint without an auth token', async () => {
748
- const tempDir = makeTempDir();
749
- const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
750
-
751
- try {
752
- const config = getDefaultConfig();
753
- config.server = {
754
- telemetry: {
755
- enabled: true,
756
- health: {
757
- enabled: true,
758
- snapshotObservation: {
759
- enabled: true,
760
- gateSnapshotPath: snapshotPath,
761
- runtimeFallbackSignal: {
762
- enabled: true,
763
- // no auth token configured: enabling must fail closed.
764
- },
765
- },
766
- },
767
- },
768
- } as any;
769
-
770
- const server = createServerBase({
771
- config,
772
- pwd: tempDir,
773
- appContext: getDefaultAppContext(),
774
- });
775
- server.addPlugins([
776
- ...createDefaultPlugins({
777
- logger: false,
778
- }),
779
- injectTelemetryPlugin(),
780
- ]);
781
-
782
- await expect(server.init()).rejects.toThrow(
783
- /requires an auth token|auth\.expectedValue/,
784
- );
785
- } finally {
786
- fs.rmSync(tempDir, { recursive: true, force: true });
787
- }
788
- });
789
-
790
- test('rate limits cannot be reset by rotating payload identities', async () => {
791
- const tempDir = makeTempDir();
792
- const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
793
-
794
- try {
795
- const config = getDefaultConfig();
796
- config.server = {
797
- telemetry: {
798
- enabled: true,
799
- health: {
800
- enabled: true,
801
- minConsecutiveFailedEvaluations: 1,
802
- snapshotObservation: {
803
- enabled: true,
804
- gateSnapshotPath: snapshotPath,
805
- runtimeFallbackSignal: {
806
- enabled: true,
807
- endpoint: '/_modern/contract-gates/runtime-fallback',
808
- auth: {
809
- expectedValue: 'rotation-token',
810
- },
811
- trustPolicy: {
812
- dedupeWindowMs: 0,
813
- maxSignalsPerWindow: 1,
814
- windowMs: 60_000,
815
- },
816
- },
817
- },
818
- },
819
- },
820
- } as any;
821
-
822
- const server = createServerBase({
823
- config,
824
- pwd: tempDir,
825
- appContext: getDefaultAppContext(),
826
- });
827
- server.addPlugins([
828
- ...createDefaultPlugins({
829
- logger: false,
830
- }),
831
- injectTelemetryPlugin(),
832
- ]);
833
-
834
- await server.init();
835
-
836
- const sendSignal = (appName: string) =>
837
- server.request(
838
- '/_modern/contract-gates/runtime-fallback',
839
- {
840
- method: 'POST',
841
- headers: new Headers({
842
- 'content-type': 'application/json',
843
- 'x-modernjs-runtime-signal-token': 'rotation-token',
844
- }),
845
- body: JSON.stringify({
846
- reason: 'remote_load_failed',
847
- phase: 'load',
848
- appName,
849
- entry: `https://${appName}.example.com/remoteEntry.js`,
850
- }),
851
- },
852
- {},
238
+ await withHealthObservation(
239
+ // enabled with no auth token configured: init must fail closed.
240
+ { runtimeFallbackSignal: { enabled: true } },
241
+ async server => {
242
+ await expect(server.init()).rejects.toThrow(
243
+ /requires an auth token|auth\.expectedValue/,
853
244
  );
854
-
855
- const first = await sendSignal('app-a');
856
- expect(first.status).toBe(202);
857
-
858
- // A rotated appName/entry pair used to mint a fresh rate-limit bucket;
859
- // the limiter is now keyed on connection identity instead.
860
- const rotated = await sendSignal('app-b');
861
- expect(rotated.status).toBe(429);
862
- } finally {
863
- fs.rmSync(tempDir, { recursive: true, force: true });
864
- }
245
+ },
246
+ );
865
247
  });
866
248
 
867
249
  test('runtime status endpoint stays a bare health probe without configured auth', async () => {
868
- const tempDir = makeTempDir();
869
- const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
870
-
871
- try {
872
- const config = getDefaultConfig();
873
- config.server = {
874
- telemetry: {
875
- enabled: true,
876
- health: {
877
- enabled: true,
878
- snapshotObservation: {
879
- enabled: true,
880
- gateSnapshotPath: snapshotPath,
881
- },
882
- },
883
- },
884
- } as any;
885
-
886
- const server = createServerBase({
887
- config,
888
- pwd: tempDir,
889
- appContext: getDefaultAppContext(),
890
- });
891
- server.addPlugins([
892
- ...createDefaultPlugins({
893
- logger: false,
894
- }),
895
- injectTelemetryPlugin(),
896
- ]);
897
-
250
+ await withHealthObservation({}, async server => {
898
251
  await server.init();
899
-
900
252
  const response = await server.request('/_modern/runtime/status', {}, {});
901
253
  expect(response.status).toBe(200);
902
254
  const payload = (await response.json()) as Record<string, unknown>;
903
255
  expect(payload.ok).toBe(true);
904
- expect(typeof payload.timestamp).toBe('number');
905
256
  // No telemetry/health/trust internals are disclosed without auth.
906
257
  expect(payload.telemetry).toBeUndefined();
907
258
  expect(payload.health).toBeUndefined();
908
259
  expect(payload.runtimeFallbackSignal).toBeUndefined();
909
- } finally {
910
- fs.rmSync(tempDir, { recursive: true, force: true });
911
- }
260
+ });
912
261
  });
913
262
 
914
263
  test('runtime status auth works even when the signal endpoint stays disabled', async () => {
915
- const tempDir = makeTempDir();
916
- const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
917
-
918
- try {
919
- const config = getDefaultConfig();
920
- config.server = {
921
- telemetry: {
922
- enabled: true,
923
- health: {
924
- enabled: true,
925
- snapshotObservation: {
926
- enabled: true,
927
- gateSnapshotPath: snapshotPath,
928
- runtimeFallbackSignal: {
929
- // endpoint stays disabled, but its auth config still guards
930
- // the status endpoint detail view.
931
- auth: {
932
- enabled: true,
933
- expectedValue: 'status-only-token',
934
- },
935
- },
936
- },
937
- },
264
+ await withHealthObservation(
265
+ {
266
+ runtimeFallbackSignal: {
267
+ // endpoint stays disabled, but its auth config still guards the
268
+ // status endpoint detail view.
269
+ auth: { enabled: true, expectedValue: 'status-only-token' },
938
270
  },
939
- } as any;
271
+ },
272
+ async server => {
273
+ await server.init();
940
274
 
941
- const server = createServerBase({
942
- config,
943
- pwd: tempDir,
944
- appContext: getDefaultAppContext(),
945
- });
946
- server.addPlugins([
947
- ...createDefaultPlugins({
948
- logger: false,
949
- }),
950
- injectTelemetryPlugin(),
951
- ]);
952
-
953
- await server.init();
954
-
955
- const signalResponse = await server.request(
956
- '/_modern/contract-gates/runtime-fallback',
957
- {
958
- method: 'POST',
959
- headers: new Headers({
960
- 'content-type': 'application/json',
961
- 'x-modernjs-runtime-signal-token': 'status-only-token',
962
- }),
963
- body: JSON.stringify({ appName: 'dashboard' }),
964
- },
965
- {},
966
- );
967
- expect(signalResponse.status).toBe(404);
275
+ const signalResponse = await postSignal(server, 'status-only-token', {
276
+ appName: 'dashboard',
277
+ });
278
+ expect(signalResponse.status).toBe(404);
968
279
 
969
- const unauthorized = await server.request(
970
- '/_modern/runtime/status',
971
- {},
972
- {},
973
- );
974
- expect(unauthorized.status).toBe(401);
280
+ const unauthorized = await server.request(
281
+ '/_modern/runtime/status',
282
+ {},
283
+ {},
284
+ );
285
+ expect(unauthorized.status).toBe(401);
975
286
 
976
- const authorized = await server.request(
977
- '/_modern/runtime/status',
978
- {
979
- method: 'GET',
980
- headers: new Headers({
981
- 'x-modernjs-runtime-signal-token': 'status-only-token',
982
- }),
983
- },
984
- {},
985
- );
986
- expect(authorized.status).toBe(200);
987
- const payload = (await authorized.json()) as Record<string, any>;
988
- expect(payload.ok).toBe(true);
989
- expect(payload.health?.enabled).toBe(true);
990
- expect(payload.runtimeFallbackSignal?.enabled).toBe(false);
991
- } finally {
992
- fs.rmSync(tempDir, { recursive: true, force: true });
993
- }
287
+ const authorized = await server.request(
288
+ '/_modern/runtime/status',
289
+ {
290
+ method: 'GET',
291
+ headers: new Headers({ [TOKEN_HEADER]: 'status-only-token' }),
292
+ },
293
+ {},
294
+ );
295
+ expect(authorized.status).toBe(200);
296
+ const payload = (await authorized.json()) as Record<string, any>;
297
+ expect(payload.health?.enabled).toBe(true);
298
+ expect(payload.runtimeFallbackSignal?.enabled).toBe(false);
299
+ },
300
+ );
994
301
  });
995
302
  });