@bleedingdev/modern-js-server-runtime-extensions 3.9.0-ultramodern.3 → 3.9.0-ultramodern.5

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 (171) hide show
  1. package/dist/cjs/bff-policy/crossProjectPolicy.js +309 -0
  2. package/dist/cjs/bff-policy/index.js +62 -0
  3. package/dist/cjs/bff-policy/node.js +69 -0
  4. package/dist/cjs/bff-policy/operationContracts.js +182 -0
  5. package/dist/cjs/bff-policy/resolveCrossProjectPolicy.js +65 -0
  6. package/dist/cjs/errorResponsePlugin.js +57 -0
  7. package/dist/cjs/localisedLoaderPlugin.js +62 -0
  8. package/dist/cjs/mfCache.js +6 -0
  9. package/dist/cjs/module-federation-css/plugin.js +6 -0
  10. package/dist/cjs/serverConfig.js +18 -0
  11. package/dist/cjs/serverPlugin.js +74 -0
  12. package/dist/cjs/static-serving/plugin.js +57 -0
  13. package/dist/cjs/static-serving/responders.js +158 -0
  14. package/dist/cjs/static-serving/staticModuleFederation.js +173 -0
  15. package/dist/cjs/static-serving/staticPrecompressed.js +152 -0
  16. package/dist/cjs/telemetry/canaryCompatibility.js +73 -0
  17. package/dist/cjs/telemetry/healthSetup.js +4 -0
  18. package/dist/cjs/telemetry/lifecycle.js +15 -16
  19. package/dist/cjs/telemetry/plugin.js +10 -3
  20. package/dist/cjs/telemetry/runtimeEndpoints.js +10 -3
  21. package/dist/esm/bff-policy/crossProjectPolicy.mjs +259 -0
  22. package/dist/esm/bff-policy/index.mjs +1 -0
  23. package/dist/esm/errorResponsePlugin.mjs +19 -0
  24. package/dist/esm/localisedLoaderPlugin.mjs +24 -0
  25. package/dist/esm/mfCache.mjs +6 -0
  26. package/dist/esm/module-federation-css/plugin.mjs +6 -0
  27. package/dist/esm/serverConfig.mjs +0 -0
  28. package/dist/esm/serverPlugin.mjs +34 -0
  29. package/dist/esm/telemetry/canaryCompatibility.mjs +35 -0
  30. package/dist/esm/telemetry/healthSetup.mjs +4 -0
  31. package/dist/esm/telemetry/lifecycle.mjs +15 -16
  32. package/dist/esm/telemetry/plugin.mjs +9 -2
  33. package/dist/esm/telemetry/runtimeEndpoints.mjs +10 -3
  34. package/dist/esm-node/bff-policy/crossProjectPolicy.mjs +260 -0
  35. package/dist/esm-node/bff-policy/index.mjs +2 -0
  36. package/dist/esm-node/bff-policy/node.mjs +3 -0
  37. package/dist/esm-node/bff-policy/operationContracts.mjs +129 -0
  38. package/dist/esm-node/bff-policy/resolveCrossProjectPolicy.mjs +28 -0
  39. package/dist/esm-node/errorResponsePlugin.mjs +20 -0
  40. package/dist/esm-node/localisedLoaderPlugin.mjs +25 -0
  41. package/dist/esm-node/mfCache.mjs +6 -0
  42. package/dist/esm-node/module-federation-css/plugin.mjs +6 -0
  43. package/dist/esm-node/serverConfig.mjs +1 -0
  44. package/dist/esm-node/serverPlugin.mjs +35 -0
  45. package/dist/esm-node/static-serving/plugin.mjs +18 -0
  46. package/dist/esm-node/static-serving/responders.mjs +111 -0
  47. package/dist/esm-node/static-serving/staticModuleFederation.mjs +105 -0
  48. package/dist/esm-node/static-serving/staticPrecompressed.mjs +112 -0
  49. package/dist/esm-node/telemetry/canaryCompatibility.mjs +36 -0
  50. package/dist/esm-node/telemetry/healthSetup.mjs +4 -0
  51. package/dist/esm-node/telemetry/lifecycle.mjs +15 -16
  52. package/dist/esm-node/telemetry/plugin.mjs +9 -2
  53. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +10 -3
  54. package/dist/types/bff-policy/crossProjectPolicy.d.ts +110 -0
  55. package/dist/types/bff-policy/index.d.ts +1 -0
  56. package/dist/types/bff-policy/node.d.ts +2 -0
  57. package/dist/types/bff-policy/operationContracts.d.ts +85 -0
  58. package/dist/types/bff-policy/resolveCrossProjectPolicy.d.ts +39 -0
  59. package/dist/types/errorResponsePlugin.d.ts +3 -0
  60. package/dist/types/index.d.ts +1 -0
  61. package/dist/types/localisedLoaderPlugin.d.ts +2 -0
  62. package/dist/types/mfCache.d.ts +2 -3
  63. package/dist/types/module-federation-css/plugin.d.ts +2 -3
  64. package/dist/types/serverConfig.d.ts +17 -0
  65. package/dist/types/serverPlugin.d.ts +5 -0
  66. package/dist/types/static-serving/plugin.d.ts +3 -0
  67. package/dist/types/static-serving/responders.d.ts +2 -0
  68. package/dist/types/static-serving/staticModuleFederation.d.ts +13 -0
  69. package/dist/types/static-serving/staticPrecompressed.d.ts +13 -0
  70. package/dist/types/telemetry/canaryCompatibility.d.ts +19 -0
  71. package/dist/types/telemetry/healthSetup.d.ts +3 -1
  72. package/dist/types/telemetry/lifecycle.d.ts +2 -2
  73. package/dist/types/telemetry/plugin.d.ts +2 -1
  74. package/dist/types/telemetry/runtimeEndpoints.d.ts +3 -1
  75. package/dist/types-esm/backend-federation-security/index.d.mts +68 -0
  76. package/dist/types-esm/backend-federation-security/node.d.mts +3 -0
  77. package/dist/types-esm/bff-policy/crossProjectPolicy.d.mts +110 -0
  78. package/dist/types-esm/bff-policy/index.d.mts +1 -0
  79. package/dist/types-esm/bff-policy/node.d.mts +2 -0
  80. package/dist/types-esm/bff-policy/operationContracts.d.mts +85 -0
  81. package/dist/types-esm/bff-policy/resolveCrossProjectPolicy.d.mts +39 -0
  82. package/dist/types-esm/contract-gate-snapshot-normalization.d.mts +15 -0
  83. package/dist/types-esm/contract-gate-snapshot-store/file-store.d.mts +3 -0
  84. package/dist/types-esm/contract-gate-snapshot-store/http-store.d.mts +5 -0
  85. package/dist/types-esm/contract-gate-snapshot-store/index.d.mts +5 -0
  86. package/dist/types-esm/contract-gate-snapshot-store/resolve.d.mts +9 -0
  87. package/dist/types-esm/contract-gate-snapshot-store/types.d.mts +47 -0
  88. package/dist/types-esm/contractGateSnapshotObserver.d.mts +33 -0
  89. package/dist/types-esm/env.d.mts +40 -0
  90. package/dist/types-esm/errorResponsePlugin.d.mts +3 -0
  91. package/dist/types-esm/index.d.mts +8 -0
  92. package/dist/types-esm/localisedLoaderPlugin.d.mts +2 -0
  93. package/dist/types-esm/mfCache.d.mts +26 -0
  94. package/dist/types-esm/module-federation-css/collector.d.mts +25 -0
  95. package/dist/types-esm/module-federation-css/index.d.mts +8 -0
  96. package/dist/types-esm/module-federation-css/manifest.d.mts +28 -0
  97. package/dist/types-esm/module-federation-css/plugin.d.mts +22 -0
  98. package/dist/types-esm/module-federation-css/remote.d.mts +20 -0
  99. package/dist/types-esm/runtime-fallback-signal/index.d.mts +4 -0
  100. package/dist/types-esm/runtime-fallback-signal/model.d.mts +70 -0
  101. package/dist/types-esm/runtime-fallback-signal/resolver.d.mts +29 -0
  102. package/dist/types-esm/runtime-fallback-signal/store.d.mts +4 -0
  103. package/dist/types-esm/runtimeFallbackSignal.d.mts +1 -0
  104. package/dist/types-esm/runtimeLifecycle.d.mts +10 -0
  105. package/dist/types-esm/serverConfig.d.mts +17 -0
  106. package/dist/types-esm/serverPlugin.d.mts +5 -0
  107. package/dist/types-esm/static-serving/plugin.d.mts +3 -0
  108. package/dist/types-esm/static-serving/responders.d.mts +2 -0
  109. package/dist/types-esm/static-serving/staticModuleFederation.d.mts +13 -0
  110. package/dist/types-esm/static-serving/staticPrecompressed.d.mts +13 -0
  111. package/dist/types-esm/telemetry/canaryCompatibility.d.mts +19 -0
  112. package/dist/types-esm/telemetry/envelope.d.mts +55 -0
  113. package/dist/types-esm/telemetry/exporters.d.mts +12 -0
  114. package/dist/types-esm/telemetry/healthEvaluation.d.mts +20 -0
  115. package/dist/types-esm/telemetry/healthMonitor.d.mts +88 -0
  116. package/dist/types-esm/telemetry/healthSetup.d.mts +19 -0
  117. package/dist/types-esm/telemetry/lifecycle.d.mts +18 -0
  118. package/dist/types-esm/telemetry/metrics.d.mts +3 -0
  119. package/dist/types-esm/telemetry/plugin.d.mts +13 -0
  120. package/dist/types-esm/telemetry/registry.d.mts +69 -0
  121. package/dist/types-esm/telemetry/registryTypes.d.mts +50 -0
  122. package/dist/types-esm/telemetry/runtimeEndpoints.d.mts +37 -0
  123. package/dist/types-esm/telemetry.d.mts +1 -0
  124. package/dist/types-esm/telemetryCore.d.mts +6 -0
  125. package/package.json +158 -26
  126. package/rslib.config.mts +36 -2
  127. package/rstest.config.mts +11 -0
  128. package/src/bff-policy/crossProjectPolicy.ts +781 -0
  129. package/src/bff-policy/index.ts +1 -0
  130. package/src/bff-policy/node.ts +2 -0
  131. package/src/bff-policy/operationContracts.ts +298 -0
  132. package/src/bff-policy/resolveCrossProjectPolicy.ts +88 -0
  133. package/src/errorResponsePlugin.ts +21 -0
  134. package/src/index.ts +4 -0
  135. package/src/localisedLoaderPlugin.ts +34 -0
  136. package/src/mfCache.ts +4 -3
  137. package/src/module-federation-css/plugin.ts +4 -3
  138. package/src/serverConfig.ts +32 -0
  139. package/src/serverPlugin.ts +38 -0
  140. package/src/static-serving/plugin.ts +16 -0
  141. package/src/static-serving/responders.ts +208 -0
  142. package/src/static-serving/staticModuleFederation.ts +255 -0
  143. package/src/static-serving/staticPrecompressed.ts +193 -0
  144. package/src/telemetry/canaryCompatibility.ts +55 -0
  145. package/src/telemetry/healthSetup.ts +9 -1
  146. package/src/telemetry/lifecycle.ts +20 -32
  147. package/src/telemetry/plugin.ts +6 -2
  148. package/src/telemetry/runtimeEndpoints.ts +13 -2
  149. package/tests/bff-policy/crossProjectPolicy.matrix.test.ts +487 -0
  150. package/tests/bff-policy/crossProjectPolicy.test.ts +1004 -0
  151. package/tests/bff-policy/operationContracts.test.ts +221 -0
  152. package/tests/bff-policy/optionalZodPeer.test.ts +30 -0
  153. package/tests/bff-policy/resolveCrossProjectPolicy.test.ts +134 -0
  154. package/tests/contractGateSnapshotObserver.test.ts +0 -58
  155. package/tests/env.test.ts +45 -64
  156. package/tests/localisedLoader.test.ts +120 -0
  157. package/tests/mfCache.test.ts +1 -88
  158. package/tests/moduleFederationCss.test.ts +4 -48
  159. package/tests/nativeErrorResponse.test.ts +199 -0
  160. package/tests/nativeServerAssembly.test.ts +402 -0
  161. package/tests/registration.test.ts +1 -86
  162. package/tests/runtimeLifecycle.test.ts +69 -17
  163. package/tests/static-serving/ordering.test.ts +214 -0
  164. package/tests/static-serving/provider.test.ts +83 -0
  165. package/tests/static-serving/static.test.ts +400 -0
  166. package/tests/telemetry.test.ts +35 -101
  167. package/tests/telemetryAutopilot.test.ts +5 -146
  168. package/tests/telemetryCanaryCompatibility.test.ts +152 -0
  169. package/tests/telemetryHealthMonitor.test.ts +0 -2
  170. package/tests/telemetryLifecycle.test.ts +11 -253
  171. package/tests/telemetryRegistryQueueMatrix.test.ts +0 -1
@@ -1,4 +1,4 @@
1
- import type { ServerTelemetryUserConfig } from '@modern-js/server-core';
1
+ import type { ServerTelemetryUserConfig } from '@modern-js/runtime-extensions/server-config';
2
2
  import {
3
3
  type ContractGateSnapshotStore,
4
4
  DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH,
@@ -22,6 +22,10 @@ import {
22
22
  TelemetryHealthMonitor,
23
23
  TelemetryRegistry,
24
24
  } from '../telemetryCore';
25
+ import {
26
+ createTelemetryCanaryCompatibility,
27
+ type TelemetryCanaryCompatibility,
28
+ } from './canaryCompatibility';
25
29
 
26
30
  type SetupTelemetryHealthMonitoringOptions = {
27
31
  registry: TelemetryRegistry;
@@ -31,6 +35,7 @@ type SetupTelemetryHealthMonitoringOptions = {
31
35
 
32
36
  type SetupTelemetryHealthMonitoringResult = {
33
37
  healthMonitor?: TelemetryHealthMonitor;
38
+ canaryCompatibility?: TelemetryCanaryCompatibility;
34
39
  gateSnapshotStorePromise?: Promise<ContractGateSnapshotStore>;
35
40
  runtimeFallbackSignalConfig?: RuntimeFallbackSignalConfig;
36
41
  runtimeStatusAuthConfig?: RuntimeFallbackSignalAuthConfig;
@@ -69,6 +74,7 @@ export const setupTelemetryHealthMonitoring = ({
69
74
  | Record<string, boolean | { passed: boolean; reason?: string }>
70
75
  | undefined;
71
76
 
77
+ const canaryCompatibility = createTelemetryCanaryCompatibility(registry);
72
78
  const healthMonitor = new TelemetryHealthMonitor({
73
79
  registry,
74
80
  evaluationIntervalMs: legacyHealthConfig.evaluationIntervalMs,
@@ -84,6 +90,7 @@ export const setupTelemetryHealthMonitoring = ({
84
90
  requiredContractGates: Object.keys(contractGates || {}),
85
91
  onTransition: evaluation => {
86
92
  emitHealthTransitionMetric(registry, evaluation);
93
+ canaryCompatibility.observe(evaluation);
87
94
  },
88
95
  });
89
96
 
@@ -150,6 +157,7 @@ export const setupTelemetryHealthMonitoring = ({
150
157
 
151
158
  return {
152
159
  healthMonitor,
160
+ canaryCompatibility,
153
161
  gateSnapshotStorePromise,
154
162
  runtimeFallbackSignalConfig,
155
163
  runtimeStatusAuthConfig,
@@ -1,4 +1,5 @@
1
- import type { ServerTelemetryUserConfig } from '@modern-js/server-core';
1
+ import type { ServerTelemetryUserConfig } from '@modern-js/runtime-extensions/server-config';
2
+ import { logger } from '@modern-js/utils';
2
3
  import {
3
4
  type ContractGateSnapshotStore,
4
5
  resolveContractGateSnapshotPath,
@@ -13,7 +14,7 @@ import {
13
14
  } from '../telemetryCore';
14
15
 
15
16
  type TelemetryLifecycleApi = {
16
- getServerContext: () => unknown;
17
+ onDispose: (disposer: () => Promise<void>) => () => void;
17
18
  onPrepare: (prepare: () => Promise<void>) => void;
18
19
  };
19
20
 
@@ -41,7 +42,7 @@ const ensureTelemetryBeforeExitHook = () => {
41
42
  telemetryBeforeExitHookInstalled = true;
42
43
  process.on('beforeExit', () => {
43
44
  for (const close of [...activeTelemetryLaneClosers]) {
44
- void close();
45
+ void close().catch((error: unknown) => logger.error(error));
45
46
  }
46
47
  });
47
48
  };
@@ -56,43 +57,30 @@ export const registerTelemetryLifecycle = ({
56
57
  appDirectory,
57
58
  }: RegisterTelemetryLifecycleOptions) => {
58
59
  let contractGateSnapshotObserver: ContractGateSnapshotObserver | undefined;
59
- let telemetryLaneClosed = false;
60
- const closeTelemetryLane = async () => {
61
- if (telemetryLaneClosed) {
62
- return;
63
- }
64
- telemetryLaneClosed = true;
65
- activeTelemetryLaneClosers.delete(closeTelemetryLane);
66
- contractGateSnapshotObserver?.stop();
67
- healthMonitor?.stop();
68
- await registry.shutdown();
60
+ let closePromise: Promise<void> | undefined;
61
+ const closeTelemetryLane = () => {
62
+ closePromise ??= Promise.resolve().then(async () => {
63
+ activeTelemetryLaneClosers.delete(closeTelemetryLane);
64
+ contractGateSnapshotObserver?.stop();
65
+ healthMonitor?.stop();
66
+ await registry.shutdown();
67
+ });
68
+ return closePromise;
69
69
  };
70
70
 
71
+ // Registration precedes exporter startup and any later plugin failure.
72
+ // Native prod/dev shutdown and runtime retirement share this disposal path.
73
+ api.onDispose(closeTelemetryLane);
74
+ activeTelemetryLaneClosers.add(closeTelemetryLane);
75
+ ensureTelemetryBeforeExitHook();
76
+
71
77
  let prepared = false;
72
78
  api.onPrepare(async () => {
73
- if (prepared) {
79
+ if (prepared || closePromise) {
74
80
  return;
75
81
  }
76
82
  prepared = true;
77
83
 
78
- // Shutdown path for the telemetry lane: flush pending envelopes and
79
- // stop health/snapshot pollers when the node server closes (this also
80
- // covers dev-server restarts, which close the previous node server
81
- // before assembling a new one), with process beforeExit as the
82
- // final-flush floor when no node server handle exists.
83
- const { nodeServer } = api.getServerContext() as {
84
- nodeServer?: {
85
- once?: (event: string, listener: () => void) => unknown;
86
- };
87
- };
88
- if (nodeServer && typeof nodeServer.once === 'function') {
89
- nodeServer.once('close', () => {
90
- void closeTelemetryLane();
91
- });
92
- }
93
- activeTelemetryLaneClosers.add(closeTelemetryLane);
94
- ensureTelemetryBeforeExitHook();
95
-
96
84
  if (telemetryConfig.exporters?.otlp?.enabled) {
97
85
  maybeWarnLegacyOtlpEndpoint(telemetryConfig.exporters.otlp.endpoint);
98
86
  await registry.register(
@@ -1,10 +1,10 @@
1
- import { parseTraceparent } from '@modern-js/create-request/server';
1
+ import { parseTraceparent } from '@modern-js/runtime-extensions/request-context';
2
+ import type { ServerTelemetryUserConfig } from '@modern-js/runtime-extensions/server-config';
2
3
  import type {
3
4
  Context,
4
5
  Next,
5
6
  ServerEnv,
6
7
  ServerPlugin,
7
- ServerTelemetryUserConfig,
8
8
  } from '@modern-js/server-core';
9
9
  import type { CoreMonitor } from '@modern-js/types';
10
10
  import { logger } from '@modern-js/utils';
@@ -98,6 +98,8 @@ export const resolveTelemetrySloOptions = (
98
98
 
99
99
  export const injectTelemetryPlugin = (): ServerPlugin => ({
100
100
  name: '@modern-js/inject-telemetry',
101
+ pre: ['@modern-js/plugin-inject-route'],
102
+ post: ['@modern-js/plugin-inject-config-middleware'],
101
103
  setup(api) {
102
104
  const serverConfig = api.getServerConfig();
103
105
  const telemetryConfig = serverConfig?.server?.telemetry;
@@ -133,6 +135,7 @@ export const injectTelemetryPlugin = (): ServerPlugin => ({
133
135
 
134
136
  const {
135
137
  healthMonitor,
138
+ canaryCompatibility,
136
139
  gateSnapshotStorePromise,
137
140
  runtimeFallbackSignalConfig,
138
141
  runtimeStatusAuthConfig,
@@ -151,6 +154,7 @@ export const injectTelemetryPlugin = (): ServerPlugin => ({
151
154
  createRuntimeStatusMiddleware({
152
155
  registry,
153
156
  healthMonitor,
157
+ canaryCompatibility,
154
158
  runtimeFallbackSignalConfig,
155
159
  runtimeStatusAuthConfig,
156
160
  }),
@@ -15,10 +15,12 @@ import type {
15
15
  TelemetryHealthMonitor,
16
16
  TelemetryRegistry,
17
17
  } from '../telemetryCore';
18
+ import type { TelemetryCanaryCompatibility } from './canaryCompatibility';
18
19
 
19
20
  type RuntimeStatusMiddlewareOptions = {
20
21
  registry: TelemetryRegistry;
21
22
  healthMonitor?: TelemetryHealthMonitor;
23
+ canaryCompatibility?: TelemetryCanaryCompatibility;
22
24
  runtimeFallbackSignalConfig?: RuntimeFallbackSignalConfig;
23
25
  runtimeStatusAuthConfig?: RuntimeFallbackSignalAuthConfig;
24
26
  };
@@ -87,6 +89,7 @@ export const createRuntimeFallbackSignalMiddleware = (
87
89
  export const createRuntimeStatusMiddleware = ({
88
90
  registry,
89
91
  healthMonitor,
92
+ canaryCompatibility,
90
93
  runtimeFallbackSignalConfig,
91
94
  runtimeStatusAuthConfig,
92
95
  }: RuntimeStatusMiddlewareOptions) => ({
@@ -111,6 +114,7 @@ export const createRuntimeStatusMiddleware = ({
111
114
  runtimeStatusAuthConfig,
112
115
  );
113
116
 
117
+ const healthSnapshot = healthMonitor?.getStatusSnapshot();
114
118
  return c.json({
115
119
  ok: true,
116
120
  timestamp: Date.now(),
@@ -118,12 +122,19 @@ export const createRuntimeStatusMiddleware = ({
118
122
  queueStats: registry.getQueueStats(),
119
123
  exporterHealth: registry.getExporterHealth(),
120
124
  },
121
- health: healthMonitor
125
+ health: healthSnapshot
122
126
  ? {
123
127
  enabled: true,
124
- ...healthMonitor.getStatusSnapshot(),
128
+ ...healthSnapshot,
125
129
  }
126
130
  : { enabled: false },
131
+ canary:
132
+ healthSnapshot && canaryCompatibility
133
+ ? {
134
+ enabled: true,
135
+ ...canaryCompatibility.getStatusSnapshot(healthSnapshot),
136
+ }
137
+ : { enabled: false },
127
138
  runtimeFallbackSignal: runtimeFallbackSignalConfig
128
139
  ? {
129
140
  enabled: true,
@@ -0,0 +1,487 @@
1
+ import {
2
+ type CrossProjectPolicyConfig,
3
+ type CrossProjectPolicyViolationReason,
4
+ evaluateCrossProjectPolicy,
5
+ } from '../../src/bff-policy/crossProjectPolicy';
6
+
7
+ const ENVELOPE_HEADER = 'x-modernjs-bff-envelope';
8
+ const OPERATION_CONTEXT_HEADER = 'x-operation-id';
9
+ const OPERATION_CONTEXT_DETAIL_HEADER = 'x-modernjs-bff-operation-context';
10
+ const VERIFIED_PRODUCER_HEADER = 'x-verified-producer';
11
+
12
+ const OMIT = Symbol('omit header');
13
+
14
+ type RawHeader = {
15
+ kind: 'raw';
16
+ value: string;
17
+ };
18
+
19
+ type HeaderInput = RawHeader | unknown | typeof OMIT;
20
+
21
+ type PolicyMatrixScenario = {
22
+ name: string;
23
+ headers?: Record<string, unknown>;
24
+ envelope?: HeaderInput;
25
+ operationContext?: string | typeof OMIT;
26
+ detail?: HeaderInput;
27
+ config: CrossProjectPolicyConfig;
28
+ nodeEnv?: string;
29
+ expected:
30
+ | {
31
+ kind: 'allow';
32
+ }
33
+ | {
34
+ kind: 'deny';
35
+ reason: CrossProjectPolicyViolationReason;
36
+ };
37
+ };
38
+
39
+ const raw = (value: string): RawHeader => ({
40
+ kind: 'raw',
41
+ value,
42
+ });
43
+
44
+ const isRawHeader = (value: HeaderInput): value is RawHeader =>
45
+ Boolean(
46
+ value &&
47
+ typeof value === 'object' &&
48
+ 'kind' in value &&
49
+ value.kind === 'raw',
50
+ );
51
+
52
+ const encodeHeader = (value: HeaderInput): string =>
53
+ isRawHeader(value) ? value.value : JSON.stringify(value);
54
+
55
+ const validEnvelope = {
56
+ requestId: 'crm.producer-a',
57
+ };
58
+
59
+ const validOperationContext = 'crm.producer-a:GET:/api/customer';
60
+
61
+ const validDetail = {
62
+ requestId: 'crm.producer-a',
63
+ operationId: validOperationContext,
64
+ method: 'GET',
65
+ routePath: '/api/customer',
66
+ schemaHash: 'schema-1',
67
+ operationVersion: 1,
68
+ };
69
+
70
+ const strictContractConfig = {
71
+ enabled: true,
72
+ expectedOperationContracts: {
73
+ 'GET:/api/customer': {
74
+ schemaHash: 'schema-1',
75
+ operationVersion: 1,
76
+ },
77
+ },
78
+ } satisfies CrossProjectPolicyConfig;
79
+
80
+ const verifyProducerHeader = (headers: Record<string, unknown>) =>
81
+ typeof headers[VERIFIED_PRODUCER_HEADER] === 'string'
82
+ ? headers[VERIFIED_PRODUCER_HEADER]
83
+ : undefined;
84
+
85
+ const buildHeaders = ({
86
+ headers,
87
+ envelope,
88
+ operationContext,
89
+ detail,
90
+ }: Pick<
91
+ PolicyMatrixScenario,
92
+ 'headers' | 'envelope' | 'operationContext' | 'detail'
93
+ >): Record<string, unknown> => {
94
+ const result: Record<string, unknown> = {
95
+ ...headers,
96
+ };
97
+
98
+ const envelopeInput = envelope ?? validEnvelope;
99
+ if (envelopeInput !== OMIT) {
100
+ result[ENVELOPE_HEADER] = encodeHeader(envelopeInput);
101
+ }
102
+
103
+ const operationContextInput = operationContext ?? validOperationContext;
104
+ if (operationContextInput !== OMIT) {
105
+ result[OPERATION_CONTEXT_HEADER] = operationContextInput;
106
+ }
107
+
108
+ const detailInput = detail ?? validDetail;
109
+ if (detailInput !== OMIT) {
110
+ result[OPERATION_CONTEXT_DETAIL_HEADER] = encodeHeader(detailInput);
111
+ }
112
+
113
+ return result;
114
+ };
115
+
116
+ const withNodeEnv = <T>(nodeEnv: string | undefined, callback: () => T): T => {
117
+ if (!nodeEnv) {
118
+ return callback();
119
+ }
120
+
121
+ const previousNodeEnv = process.env.NODE_ENV;
122
+ process.env.NODE_ENV = nodeEnv;
123
+ try {
124
+ return callback();
125
+ } finally {
126
+ if (typeof previousNodeEnv === 'undefined') {
127
+ delete process.env.NODE_ENV;
128
+ } else {
129
+ process.env.NODE_ENV = previousNodeEnv;
130
+ }
131
+ }
132
+ };
133
+
134
+ const denialReasonCoverage: Record<CrossProjectPolicyViolationReason, true> = {
135
+ invalid_envelope: true,
136
+ invalid_operation_context_details: true,
137
+ missing_envelope: true,
138
+ missing_operation_context: true,
139
+ missing_operation_context_details: true,
140
+ missing_operation_schema_hash: true,
141
+ missing_operation_version: true,
142
+ missing_request_id: true,
143
+ namespace_not_allowed: true,
144
+ operation_context_details_request_id_mismatch: true,
145
+ operation_context_mismatch: true,
146
+ operation_schema_hash_mismatch: true,
147
+ operation_version_mismatch: true,
148
+ producer_identity_mismatch: true,
149
+ unknown_operation_contract: true,
150
+ };
151
+
152
+ const policyMatrix = [
153
+ {
154
+ name: 'allow: full valid context with verified namespace and contract',
155
+ headers: {
156
+ [VERIFIED_PRODUCER_HEADER]: 'crm',
157
+ },
158
+ config: {
159
+ ...strictContractConfig,
160
+ allowedNamespaces: ['crm'],
161
+ verifyProducerIdentity: verifyProducerHeader,
162
+ },
163
+ expected: {
164
+ kind: 'allow',
165
+ },
166
+ },
167
+ {
168
+ name: 'allow: valid context with optional detail operationId omitted',
169
+ detail: {
170
+ requestId: 'crm.producer-a',
171
+ method: 'GET',
172
+ routePath: '/api/customer',
173
+ schemaHash: 'schema-1',
174
+ operationVersion: 1,
175
+ },
176
+ config: strictContractConfig,
177
+ expected: {
178
+ kind: 'allow',
179
+ },
180
+ },
181
+ {
182
+ name: 'deny: envelope header missing',
183
+ envelope: OMIT,
184
+ config: strictContractConfig,
185
+ expected: {
186
+ kind: 'deny',
187
+ reason: 'missing_envelope',
188
+ },
189
+ },
190
+ {
191
+ name: 'deny: envelope header is not JSON',
192
+ envelope: raw('not-json'),
193
+ config: strictContractConfig,
194
+ expected: {
195
+ kind: 'deny',
196
+ reason: 'invalid_envelope',
197
+ },
198
+ },
199
+ {
200
+ name: 'deny: envelope header JSON is not an object',
201
+ envelope: 123,
202
+ config: strictContractConfig,
203
+ expected: {
204
+ kind: 'deny',
205
+ reason: 'invalid_envelope',
206
+ },
207
+ },
208
+ {
209
+ name: 'deny: envelope requestId missing',
210
+ envelope: {},
211
+ config: strictContractConfig,
212
+ expected: {
213
+ kind: 'deny',
214
+ reason: 'missing_request_id',
215
+ },
216
+ },
217
+ {
218
+ name: 'deny: namespace outside verified allowlist',
219
+ headers: {
220
+ [VERIFIED_PRODUCER_HEADER]: 'billing',
221
+ },
222
+ envelope: {
223
+ requestId: 'billing.producer-a',
224
+ },
225
+ operationContext: 'billing.producer-a:GET:/api/customer',
226
+ detail: {
227
+ requestId: 'billing.producer-a',
228
+ operationId: 'billing.producer-a:GET:/api/customer',
229
+ method: 'GET',
230
+ routePath: '/api/customer',
231
+ schemaHash: 'schema-1',
232
+ operationVersion: 1,
233
+ },
234
+ config: {
235
+ ...strictContractConfig,
236
+ allowedNamespaces: ['crm'],
237
+ verifyProducerIdentity: verifyProducerHeader,
238
+ },
239
+ expected: {
240
+ kind: 'deny',
241
+ reason: 'namespace_not_allowed',
242
+ },
243
+ },
244
+ {
245
+ name: 'deny: producer identity cannot be verified',
246
+ config: {
247
+ ...strictContractConfig,
248
+ verifyProducerIdentity: () => undefined,
249
+ },
250
+ expected: {
251
+ kind: 'deny',
252
+ reason: 'producer_identity_mismatch',
253
+ },
254
+ },
255
+ {
256
+ name: 'deny: producer identity does not match envelope namespace',
257
+ headers: {
258
+ [VERIFIED_PRODUCER_HEADER]: 'billing',
259
+ },
260
+ config: {
261
+ ...strictContractConfig,
262
+ verifyProducerIdentity: verifyProducerHeader,
263
+ },
264
+ expected: {
265
+ kind: 'deny',
266
+ reason: 'producer_identity_mismatch',
267
+ },
268
+ },
269
+ {
270
+ name: 'deny: allowlist without producer verifier fails closed',
271
+ config: {
272
+ enabled: true,
273
+ allowedNamespaces: ['crm'],
274
+ requireOperationContext: false,
275
+ },
276
+ expected: {
277
+ kind: 'deny',
278
+ reason: 'producer_identity_mismatch',
279
+ },
280
+ },
281
+ {
282
+ name: 'deny: operation context header missing',
283
+ operationContext: OMIT,
284
+ config: strictContractConfig,
285
+ expected: {
286
+ kind: 'deny',
287
+ reason: 'missing_operation_context',
288
+ },
289
+ },
290
+ {
291
+ name: 'deny: operation context requestId does not match envelope',
292
+ operationContext: 'billing.producer-a:GET:/api/customer',
293
+ config: strictContractConfig,
294
+ expected: {
295
+ kind: 'deny',
296
+ reason: 'operation_context_mismatch',
297
+ },
298
+ },
299
+ {
300
+ name: 'deny: operation context details header missing',
301
+ detail: OMIT,
302
+ config: strictContractConfig,
303
+ expected: {
304
+ kind: 'deny',
305
+ reason: 'missing_operation_context_details',
306
+ },
307
+ },
308
+ {
309
+ name: 'deny: operation context details header is not JSON',
310
+ detail: raw('not-json'),
311
+ config: strictContractConfig,
312
+ expected: {
313
+ kind: 'deny',
314
+ reason: 'invalid_operation_context_details',
315
+ },
316
+ },
317
+ {
318
+ name: 'deny: operation context details JSON is not an object',
319
+ detail: ['not-an-object'],
320
+ config: strictContractConfig,
321
+ expected: {
322
+ kind: 'deny',
323
+ reason: 'invalid_operation_context_details',
324
+ },
325
+ },
326
+ {
327
+ name: 'deny: operation context details requestId mismatch',
328
+ detail: {
329
+ ...validDetail,
330
+ requestId: 'billing.producer-a',
331
+ },
332
+ config: strictContractConfig,
333
+ expected: {
334
+ kind: 'deny',
335
+ reason: 'operation_context_details_request_id_mismatch',
336
+ },
337
+ },
338
+ {
339
+ name: 'deny: operation context detail operationId conflicts with header',
340
+ detail: {
341
+ requestId: 'crm.producer-a',
342
+ operationId: 'crm.producer-a:GET:/api/invoice',
343
+ method: 'GET',
344
+ routePath: '/api/invoice',
345
+ schemaHash: 'schema-invoice',
346
+ operationVersion: 1,
347
+ },
348
+ config: {
349
+ enabled: true,
350
+ expectedOperationContracts: {
351
+ 'GET:/api/invoice': {
352
+ schemaHash: 'schema-invoice',
353
+ operationVersion: 1,
354
+ },
355
+ },
356
+ },
357
+ expected: {
358
+ kind: 'deny',
359
+ reason: 'operation_context_mismatch',
360
+ },
361
+ },
362
+ {
363
+ name: 'deny: operation schema hash missing',
364
+ detail: {
365
+ requestId: 'crm.producer-a',
366
+ operationId: validOperationContext,
367
+ method: 'GET',
368
+ routePath: '/api/customer',
369
+ operationVersion: 1,
370
+ },
371
+ config: strictContractConfig,
372
+ expected: {
373
+ kind: 'deny',
374
+ reason: 'missing_operation_schema_hash',
375
+ },
376
+ },
377
+ {
378
+ name: 'deny: operation schema hash mismatches contract',
379
+ detail: {
380
+ ...validDetail,
381
+ schemaHash: 'schema-actual',
382
+ },
383
+ config: {
384
+ enabled: true,
385
+ expectedOperationContracts: {
386
+ 'GET:/api/customer': {
387
+ schemaHash: 'schema-expected',
388
+ operationVersion: 1,
389
+ },
390
+ },
391
+ },
392
+ expected: {
393
+ kind: 'deny',
394
+ reason: 'operation_schema_hash_mismatch',
395
+ },
396
+ },
397
+ {
398
+ name: 'deny: operation version missing',
399
+ detail: {
400
+ requestId: 'crm.producer-a',
401
+ operationId: validOperationContext,
402
+ method: 'GET',
403
+ routePath: '/api/customer',
404
+ schemaHash: 'schema-1',
405
+ },
406
+ config: strictContractConfig,
407
+ expected: {
408
+ kind: 'deny',
409
+ reason: 'missing_operation_version',
410
+ },
411
+ },
412
+ {
413
+ name: 'deny: operation version mismatches contract',
414
+ detail: {
415
+ ...validDetail,
416
+ operationVersion: 2,
417
+ },
418
+ config: strictContractConfig,
419
+ expected: {
420
+ kind: 'deny',
421
+ reason: 'operation_version_mismatch',
422
+ },
423
+ },
424
+ {
425
+ name: 'deny: unknown operation contract',
426
+ operationContext: 'crm.producer-a:GET:/api/unknown',
427
+ detail: {
428
+ requestId: 'crm.producer-a',
429
+ operationId: 'crm.producer-a:GET:/api/unknown',
430
+ method: 'GET',
431
+ routePath: '/api/unknown',
432
+ schemaHash: 'schema-1',
433
+ operationVersion: 1,
434
+ },
435
+ config: strictContractConfig,
436
+ expected: {
437
+ kind: 'deny',
438
+ reason: 'unknown_operation_contract',
439
+ },
440
+ },
441
+ {
442
+ name: 'deny: empty operation contract map fails closed',
443
+ config: {
444
+ enabled: true,
445
+ expectedOperationContracts: {},
446
+ },
447
+ expected: {
448
+ kind: 'deny',
449
+ reason: 'unknown_operation_contract',
450
+ },
451
+ },
452
+ ] satisfies PolicyMatrixScenario[];
453
+
454
+ describe('cross-project policy matrix', () => {
455
+ test('covers every current denial reason', () => {
456
+ const expectedReasons = Object.keys(denialReasonCoverage).sort();
457
+ const coveredReasons = [
458
+ ...new Set(
459
+ policyMatrix.flatMap(scenario =>
460
+ scenario.expected.kind === 'deny' ? [scenario.expected.reason] : [],
461
+ ),
462
+ ),
463
+ ].sort();
464
+
465
+ expect(coveredReasons).toEqual(expectedReasons);
466
+ });
467
+
468
+ test('has unique scenario names', () => {
469
+ const names = policyMatrix.map(scenario => scenario.name);
470
+
471
+ expect(new Set(names).size).toBe(names.length);
472
+ });
473
+
474
+ for (const scenario of policyMatrix) {
475
+ test(scenario.name, () => {
476
+ const violation = withNodeEnv(scenario.nodeEnv, () =>
477
+ evaluateCrossProjectPolicy(buildHeaders(scenario), scenario.config),
478
+ );
479
+
480
+ if (scenario.expected.kind === 'allow') {
481
+ expect(violation).toBeNull();
482
+ } else {
483
+ expect(violation?.reason).toBe(scenario.expected.reason);
484
+ }
485
+ });
486
+ }
487
+ });