@bleedingdev/modern-js-server-runtime-extensions 3.5.0-ultramodern.9 → 3.5.0-ultramodern.91

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 (179) hide show
  1. package/dist/cjs/contract-gate-snapshot-normalization.js +122 -0
  2. package/dist/cjs/contract-gate-snapshot-store/file-store.js +102 -0
  3. package/dist/cjs/contract-gate-snapshot-store/http-store.js +133 -0
  4. package/dist/cjs/contract-gate-snapshot-store/index.js +58 -0
  5. package/dist/cjs/contract-gate-snapshot-store/resolve.js +124 -0
  6. package/dist/cjs/contract-gate-snapshot-store/types.js +44 -0
  7. package/dist/cjs/contractGateAutopilot.js +22 -70
  8. package/dist/cjs/index.js +6 -25
  9. package/dist/cjs/mfCache.js +2 -2
  10. package/dist/cjs/module-federation-css/collector.js +79 -0
  11. package/dist/cjs/module-federation-css/index.js +55 -0
  12. package/dist/cjs/module-federation-css/manifest.js +129 -0
  13. package/dist/cjs/module-federation-css/plugin.js +71 -0
  14. package/dist/cjs/module-federation-css/remote.js +133 -0
  15. package/dist/cjs/runtime-fallback-signal/index.js +93 -0
  16. package/dist/cjs/runtime-fallback-signal/model.js +157 -0
  17. package/dist/cjs/runtime-fallback-signal/resolver.js +163 -0
  18. package/dist/cjs/runtime-fallback-signal/store.js +83 -0
  19. package/dist/cjs/runtimeFallbackSignal.js +32 -281
  20. package/dist/cjs/telemetry/canary.js +180 -0
  21. package/dist/cjs/telemetry/canaryEvaluation.js +79 -0
  22. package/dist/cjs/telemetry/canarySetup.js +107 -0
  23. package/dist/cjs/telemetry/envelope.js +223 -0
  24. package/dist/cjs/telemetry/exporters.js +148 -0
  25. package/dist/cjs/telemetry/lifecycle.js +98 -0
  26. package/dist/cjs/telemetry/metrics.js +115 -0
  27. package/dist/cjs/telemetry/plugin.js +185 -0
  28. package/dist/cjs/telemetry/registry.js +296 -0
  29. package/dist/cjs/telemetry/registryTypes.js +46 -0
  30. package/dist/cjs/telemetry/runtimeEndpoints.js +135 -0
  31. package/dist/cjs/telemetry.js +32 -343
  32. package/dist/cjs/telemetryCore.js +14 -767
  33. package/dist/esm/contract-gate-snapshot-normalization.mjs +81 -0
  34. package/dist/esm/contract-gate-snapshot-store/file-store.mjs +51 -0
  35. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +92 -0
  36. package/dist/esm/contract-gate-snapshot-store/index.mjs +4 -0
  37. package/dist/esm/contract-gate-snapshot-store/resolve.mjs +70 -0
  38. package/dist/esm/contract-gate-snapshot-store/types.mjs +3 -0
  39. package/dist/esm/contractGateAutopilot.mjs +21 -69
  40. package/dist/esm/index.mjs +1 -2
  41. package/dist/esm/mfCache.mjs +2 -2
  42. package/dist/esm/module-federation-css/collector.mjs +38 -0
  43. package/dist/esm/module-federation-css/index.mjs +4 -0
  44. package/dist/esm/module-federation-css/manifest.mjs +69 -0
  45. package/dist/esm/module-federation-css/plugin.mjs +33 -0
  46. package/dist/esm/module-federation-css/remote.mjs +92 -0
  47. package/dist/esm/runtime-fallback-signal/index.mjs +3 -0
  48. package/dist/esm/runtime-fallback-signal/model.mjs +73 -0
  49. package/dist/esm/runtime-fallback-signal/resolver.mjs +107 -0
  50. package/dist/esm/runtime-fallback-signal/store.mjs +39 -0
  51. package/dist/esm/runtimeFallbackSignal.mjs +1 -222
  52. package/dist/esm/telemetry/canary.mjs +142 -0
  53. package/dist/esm/telemetry/canaryEvaluation.mjs +41 -0
  54. package/dist/esm/telemetry/canarySetup.mjs +69 -0
  55. package/dist/esm/telemetry/envelope.mjs +164 -0
  56. package/dist/esm/telemetry/exporters.mjs +104 -0
  57. package/dist/esm/telemetry/lifecycle.mjs +60 -0
  58. package/dist/esm/telemetry/metrics.mjs +77 -0
  59. package/dist/esm/telemetry/plugin.mjs +87 -0
  60. package/dist/esm/telemetry/registry.mjs +258 -0
  61. package/dist/esm/telemetry/registryTypes.mjs +8 -0
  62. package/dist/esm/telemetry/runtimeEndpoints.mjs +94 -0
  63. package/dist/esm/telemetry.mjs +1 -275
  64. package/dist/esm/telemetryCore.mjs +6 -759
  65. package/dist/esm-node/contract-gate-snapshot-normalization.mjs +82 -0
  66. package/dist/esm-node/contract-gate-snapshot-store/file-store.mjs +52 -0
  67. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +93 -0
  68. package/dist/esm-node/contract-gate-snapshot-store/index.mjs +5 -0
  69. package/dist/esm-node/contract-gate-snapshot-store/resolve.mjs +71 -0
  70. package/dist/esm-node/contract-gate-snapshot-store/types.mjs +4 -0
  71. package/dist/esm-node/contractGateAutopilot.mjs +21 -69
  72. package/dist/esm-node/index.mjs +1 -2
  73. package/dist/esm-node/mfCache.mjs +2 -2
  74. package/dist/esm-node/module-federation-css/collector.mjs +39 -0
  75. package/dist/esm-node/module-federation-css/index.mjs +5 -0
  76. package/dist/esm-node/module-federation-css/manifest.mjs +70 -0
  77. package/dist/esm-node/module-federation-css/plugin.mjs +34 -0
  78. package/dist/esm-node/module-federation-css/remote.mjs +93 -0
  79. package/dist/esm-node/runtime-fallback-signal/index.mjs +4 -0
  80. package/dist/esm-node/runtime-fallback-signal/model.mjs +74 -0
  81. package/dist/esm-node/runtime-fallback-signal/resolver.mjs +108 -0
  82. package/dist/esm-node/runtime-fallback-signal/store.mjs +40 -0
  83. package/dist/esm-node/runtimeFallbackSignal.mjs +1 -222
  84. package/dist/esm-node/telemetry/canary.mjs +143 -0
  85. package/dist/esm-node/telemetry/canaryEvaluation.mjs +42 -0
  86. package/dist/esm-node/telemetry/canarySetup.mjs +70 -0
  87. package/dist/esm-node/telemetry/envelope.mjs +165 -0
  88. package/dist/esm-node/telemetry/exporters.mjs +105 -0
  89. package/dist/esm-node/telemetry/lifecycle.mjs +61 -0
  90. package/dist/esm-node/telemetry/metrics.mjs +78 -0
  91. package/dist/esm-node/telemetry/plugin.mjs +88 -0
  92. package/dist/esm-node/telemetry/registry.mjs +259 -0
  93. package/dist/esm-node/telemetry/registryTypes.mjs +9 -0
  94. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +95 -0
  95. package/dist/esm-node/telemetry.mjs +1 -275
  96. package/dist/esm-node/telemetryCore.mjs +6 -759
  97. package/dist/types/contract-gate-snapshot-normalization.d.ts +15 -0
  98. package/dist/types/contract-gate-snapshot-store/file-store.d.ts +3 -0
  99. package/dist/types/contract-gate-snapshot-store/http-store.d.ts +5 -0
  100. package/dist/types/contract-gate-snapshot-store/index.d.ts +5 -0
  101. package/dist/types/contract-gate-snapshot-store/resolve.d.ts +9 -0
  102. package/dist/types/{contractGateSnapshotStore.d.ts → contract-gate-snapshot-store/types.d.ts} +1 -11
  103. package/dist/types/contractGateAutopilot.d.ts +3 -6
  104. package/dist/types/index.d.ts +1 -2
  105. package/dist/types/module-federation-css/collector.d.ts +25 -0
  106. package/dist/types/module-federation-css/index.d.ts +8 -0
  107. package/dist/types/module-federation-css/manifest.d.ts +28 -0
  108. package/dist/types/module-federation-css/plugin.d.ts +23 -0
  109. package/dist/types/module-federation-css/remote.d.ts +20 -0
  110. package/dist/types/runtime-fallback-signal/index.d.ts +4 -0
  111. package/dist/types/runtime-fallback-signal/model.d.ts +70 -0
  112. package/dist/types/runtime-fallback-signal/resolver.d.ts +29 -0
  113. package/dist/types/runtime-fallback-signal/store.d.ts +4 -0
  114. package/dist/types/runtimeFallbackSignal.d.ts +1 -94
  115. package/dist/types/telemetry/canary.d.ts +85 -0
  116. package/dist/types/telemetry/canaryEvaluation.d.ts +20 -0
  117. package/dist/types/telemetry/canarySetup.d.ts +17 -0
  118. package/dist/types/telemetry/envelope.d.ts +55 -0
  119. package/dist/types/telemetry/exporters.d.ts +12 -0
  120. package/dist/types/telemetry/lifecycle.d.ts +18 -0
  121. package/dist/types/telemetry/metrics.d.ts +3 -0
  122. package/dist/types/telemetry/plugin.d.ts +12 -0
  123. package/dist/types/telemetry/registry.d.ts +69 -0
  124. package/dist/types/telemetry/registryTypes.d.ts +50 -0
  125. package/dist/types/telemetry/runtimeEndpoints.d.ts +35 -0
  126. package/dist/types/telemetry.d.ts +1 -12
  127. package/dist/types/telemetryCore.d.ts +6 -257
  128. package/package.json +10 -12
  129. package/src/contract-gate-snapshot-normalization.ts +155 -0
  130. package/src/contract-gate-snapshot-store/file-store.ts +83 -0
  131. package/src/contract-gate-snapshot-store/http-store.ts +159 -0
  132. package/src/contract-gate-snapshot-store/index.ts +20 -0
  133. package/src/contract-gate-snapshot-store/resolve.ts +179 -0
  134. package/src/contract-gate-snapshot-store/types.ts +64 -0
  135. package/src/contractGateAutopilot.ts +39 -131
  136. package/src/index.ts +1 -17
  137. package/src/mfCache.ts +3 -1
  138. package/src/module-federation-css/collector.ts +82 -0
  139. package/src/module-federation-css/index.ts +14 -0
  140. package/src/module-federation-css/manifest.ts +163 -0
  141. package/src/module-federation-css/plugin.ts +86 -0
  142. package/src/module-federation-css/remote.ts +165 -0
  143. package/src/runtime-fallback-signal/index.ts +34 -0
  144. package/src/runtime-fallback-signal/model.ts +230 -0
  145. package/src/runtime-fallback-signal/resolver.ts +304 -0
  146. package/src/runtime-fallback-signal/store.ts +78 -0
  147. package/src/runtimeFallbackSignal.ts +1 -584
  148. package/src/telemetry/canary.ts +291 -0
  149. package/src/telemetry/canaryEvaluation.ts +83 -0
  150. package/src/telemetry/canarySetup.ts +160 -0
  151. package/src/telemetry/envelope.ts +277 -0
  152. package/src/telemetry/exporters.ts +165 -0
  153. package/src/telemetry/lifecycle.ts +138 -0
  154. package/src/telemetry/metrics.ts +141 -0
  155. package/src/telemetry/plugin.ts +197 -0
  156. package/src/telemetry/registry.ts +424 -0
  157. package/src/telemetry/registryTypes.ts +63 -0
  158. package/src/telemetry/runtimeEndpoints.ts +172 -0
  159. package/src/telemetry.ts +1 -554
  160. package/src/telemetryCore.ts +34 -1332
  161. package/tests/contractGateAutopilot.test.ts +205 -0
  162. package/tests/contractGateSnapshotStore.test.ts +54 -1
  163. package/tests/helpers.ts +1 -0
  164. package/tests/moduleFederationCss.test.ts +1 -1
  165. package/tests/registration.test.ts +1 -1
  166. package/tests/telemetry.test.ts +51 -0
  167. package/tests/telemetryAutopilot.test.ts +141 -0
  168. package/tests/telemetryCanaryOrchestrator.test.ts +225 -0
  169. package/tests/telemetryLifecycle.test.ts +253 -2
  170. package/tests/telemetryRegistryQueueMatrix.test.ts +227 -0
  171. package/dist/cjs/contractGateSnapshotStore.js +0 -253
  172. package/dist/cjs/moduleFederationCss.js +0 -285
  173. package/dist/esm/contractGateSnapshotStore.mjs +0 -190
  174. package/dist/esm/moduleFederationCss.mjs +0 -225
  175. package/dist/esm-node/contractGateSnapshotStore.mjs +0 -192
  176. package/dist/esm-node/moduleFederationCss.mjs +0 -226
  177. package/dist/types/moduleFederationCss.d.ts +0 -87
  178. package/src/contractGateSnapshotStore.ts +0 -420
  179. package/src/moduleFederationCss.ts +0 -473
@@ -0,0 +1,93 @@
1
+ import "node:module";
2
+ import { collectModuleFederationManifestCss, getHostManifest, normalizeRemoteEntry, warn } from "./manifest.mjs";
3
+ const DEFAULT_REMOTE_MANIFEST_TIMEOUT = 1500;
4
+ const fetchJsonWithTimeout = async (url, fetcher, timeout)=>{
5
+ const controller = new AbortController();
6
+ let timeoutId;
7
+ try {
8
+ const response = await Promise.race([
9
+ fetcher(url, {
10
+ signal: controller.signal
11
+ }),
12
+ new Promise((_, reject)=>{
13
+ timeoutId = setTimeout(()=>{
14
+ controller.abort();
15
+ reject(new Error(`Request timed out after ${timeout}ms`));
16
+ }, timeout);
17
+ })
18
+ ]);
19
+ if (!response.ok) throw new Error(`Unexpected status ${response.status}`);
20
+ return await response.json();
21
+ } finally{
22
+ if (timeoutId) clearTimeout(timeoutId);
23
+ }
24
+ };
25
+ const collectDirectRemoteModuleFederationCssWithMeta = async (pwd, options = {})=>{
26
+ const hostManifest = await getHostManifest(pwd, options.monitors);
27
+ if (!hostManifest) return {
28
+ assets: [],
29
+ errored: false
30
+ };
31
+ const fetcher = options.fetcher || globalThis.fetch?.bind(globalThis);
32
+ if (!fetcher) {
33
+ warn(options.monitors, 'Skip module federation remote CSS collection because fetch is unavailable.');
34
+ return {
35
+ assets: [],
36
+ errored: false
37
+ };
38
+ }
39
+ const timeout = options.timeout ?? DEFAULT_REMOTE_MANIFEST_TIMEOUT;
40
+ const remoteResults = await Promise.all((hostManifest.remotes || []).map(async (remote)=>{
41
+ if (!remote.entry) return {
42
+ assets: [],
43
+ errored: false
44
+ };
45
+ const remoteEntry = normalizeRemoteEntry(remote.entry);
46
+ if (!remoteEntry) return {
47
+ assets: [],
48
+ errored: false
49
+ };
50
+ let remoteManifestUrl;
51
+ try {
52
+ remoteManifestUrl = new URL(remoteEntry).toString();
53
+ } catch {
54
+ warn(options.monitors, 'Skip module federation remote CSS collection for non-absolute manifest URL %s', remoteEntry);
55
+ return {
56
+ assets: [],
57
+ errored: false
58
+ };
59
+ }
60
+ try {
61
+ const remoteManifest = await fetchJsonWithTimeout(remoteManifestUrl, fetcher, timeout);
62
+ return {
63
+ assets: collectModuleFederationManifestCss(remoteManifest, remoteManifestUrl),
64
+ errored: false
65
+ };
66
+ } catch (error) {
67
+ warn(options.monitors, 'Load module federation remote manifest %s failed, error = %s', remoteManifestUrl, error instanceof Error ? error.message : error);
68
+ return {
69
+ assets: [],
70
+ errored: true
71
+ };
72
+ }
73
+ }));
74
+ const cssAssets = [];
75
+ const seen = new Set();
76
+ let errored = false;
77
+ for (const result of remoteResults){
78
+ errored = errored || result.errored;
79
+ for (const asset of result.assets)if (!seen.has(asset)) {
80
+ seen.add(asset);
81
+ cssAssets.push(asset);
82
+ }
83
+ }
84
+ return {
85
+ assets: cssAssets,
86
+ errored
87
+ };
88
+ };
89
+ const collectDirectRemoteModuleFederationCss = async (pwd, options = {})=>{
90
+ const { assets } = await collectDirectRemoteModuleFederationCssWithMeta(pwd, options);
91
+ return assets;
92
+ };
93
+ export { collectDirectRemoteModuleFederationCss, collectDirectRemoteModuleFederationCssWithMeta };
@@ -0,0 +1,4 @@
1
+ import "node:module";
2
+ export { DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS, DEFAULT_RUNTIME_FALLBACK_GATE_NAME, DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES, DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, DEFAULT_RUNTIME_STATUS_ENDPOINT, createRuntimeSignalError, getRuntimeSignalErrorStatusCode, parseRuntimeFallbackSignalPayload, parseRuntimeFallbackSignalPayloadFromRawBody } from "./model.mjs";
3
+ export { enforceRuntimeFallbackSignalAuth, enforceRuntimeFallbackSignalAuthToken, enforceRuntimeFallbackSignalTrustPolicy, normalizeRequiredRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackTrustPolicy, resolveRuntimeFallbackSignalEndpoint } from "./resolver.mjs";
4
+ export { createRuntimeFallbackSignalRuntimeState, persistRuntimeFallbackContractGate } from "./store.mjs";
@@ -0,0 +1,74 @@
1
+ import "node:module";
2
+ const DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT = '/_modern/contract-gates/runtime-fallback';
3
+ const DEFAULT_RUNTIME_STATUS_ENDPOINT = '/_modern/runtime/status';
4
+ const DEFAULT_RUNTIME_FALLBACK_GATE_NAME = 'runtime-mf-fallback-health';
5
+ const DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS = 300000;
6
+ const DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES = 16384;
7
+ const DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER = 'x-modernjs-runtime-signal-token';
8
+ const DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW = 30;
9
+ const DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS = 60000;
10
+ const DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS = 10000;
11
+ function createRuntimeSignalError(message, code) {
12
+ const error = new Error(message);
13
+ error.code = code;
14
+ return error;
15
+ }
16
+ function getRuntimeSignalErrorStatusCode(signalError) {
17
+ if ('PAYLOAD_TOO_LARGE' === signalError.code) return 413;
18
+ if ('INVALID_PAYLOAD' === signalError.code) return 400;
19
+ if ('UNAUTHORIZED' === signalError.code) return 401;
20
+ if ('RATE_LIMITED' === signalError.code) return 429;
21
+ if ('UNTRUSTED_SOURCE' === signalError.code) return 403;
22
+ return 500;
23
+ }
24
+ function normalizeRuntimeSignalOrigin(value) {
25
+ if ('string' != typeof value || 0 === value.trim().length) return;
26
+ try {
27
+ return new URL(value).origin;
28
+ } catch (_error) {
29
+ return;
30
+ }
31
+ }
32
+ function normalizeRuntimeSignalAppName(payload) {
33
+ if ('string' != typeof payload.appName) return 'unknown';
34
+ const normalized = payload.appName.trim();
35
+ return normalized.length > 0 ? normalized : 'unknown';
36
+ }
37
+ function normalizeRuntimeSignalRuntimeDigest(payload) {
38
+ if ('string' == typeof payload.runtimeDigest && payload.runtimeDigest.trim()) return payload.runtimeDigest.trim();
39
+ const metadata = payload.metadata;
40
+ if (metadata && 'object' == typeof metadata && !Array.isArray(metadata) && 'string' == typeof metadata.runtimeDigest) {
41
+ const digest = String(metadata.runtimeDigest).trim();
42
+ if (digest) return digest;
43
+ }
44
+ }
45
+ function getUtf8ByteLength(input) {
46
+ if ("u" > typeof Buffer) return Buffer.byteLength(input);
47
+ return new TextEncoder().encode(input).length;
48
+ }
49
+ async function parseRuntimeFallbackSignalPayload(c, maxBodyBytes) {
50
+ const contentLengthHeader = c.req.header('content-length');
51
+ if (contentLengthHeader) {
52
+ const contentLength = Number.parseInt(contentLengthHeader, 10);
53
+ if (Number.isFinite(contentLength) && contentLength > maxBodyBytes) throw createRuntimeSignalError('runtime fallback signal payload too large', 'PAYLOAD_TOO_LARGE');
54
+ }
55
+ const rawBody = await c.req.raw.text();
56
+ const payload = parseRuntimeFallbackSignalPayloadFromRawBody(rawBody, maxBodyBytes);
57
+ return {
58
+ rawBody,
59
+ payload
60
+ };
61
+ }
62
+ function parseRuntimeFallbackSignalPayloadFromRawBody(rawBody, maxBodyBytes) {
63
+ if (!rawBody || 0 === rawBody.trim().length) throw createRuntimeSignalError('runtime fallback signal body empty', 'INVALID_PAYLOAD');
64
+ if (getUtf8ByteLength(rawBody) > maxBodyBytes) throw createRuntimeSignalError('runtime fallback signal payload too large', 'PAYLOAD_TOO_LARGE');
65
+ let payload;
66
+ try {
67
+ payload = JSON.parse(rawBody);
68
+ } catch (_error) {
69
+ throw createRuntimeSignalError('runtime fallback signal body must be valid JSON', 'INVALID_PAYLOAD');
70
+ }
71
+ if (!payload || 'object' != typeof payload || Array.isArray(payload)) throw createRuntimeSignalError('runtime fallback signal body must be a JSON object', 'INVALID_PAYLOAD');
72
+ return payload;
73
+ }
74
+ export { DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER, DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS, DEFAULT_RUNTIME_FALLBACK_GATE_NAME, DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES, DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS, DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW, DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS, DEFAULT_RUNTIME_STATUS_ENDPOINT, createRuntimeSignalError, getRuntimeSignalErrorStatusCode, normalizeRuntimeSignalAppName, normalizeRuntimeSignalOrigin, normalizeRuntimeSignalRuntimeDigest, parseRuntimeFallbackSignalPayload, parseRuntimeFallbackSignalPayloadFromRawBody };
@@ -0,0 +1,108 @@
1
+ import "node:module";
2
+ import { createHash, timingSafeEqual } from "node:crypto";
3
+ import { DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER, DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS, DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW, DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS, createRuntimeSignalError, normalizeRuntimeSignalAppName, normalizeRuntimeSignalOrigin, normalizeRuntimeSignalRuntimeDigest } from "./model.mjs";
4
+ import { cleanupRuntimeFallbackSignalRuntimeState } from "./store.mjs";
5
+ function resolveRuntimeFallbackSignalEndpoint(configuredEndpoint) {
6
+ if ('string' == typeof configuredEndpoint && configuredEndpoint.trim()) return configuredEndpoint.trim();
7
+ return DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT;
8
+ }
9
+ function normalizeRuntimeFallbackSignalAuthConfig(configured) {
10
+ const headerName = 'string' == typeof configured?.headerName && configured.headerName.trim() ? configured.headerName.trim().toLowerCase() : DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER;
11
+ const expectedFromEnv = 'string' == typeof configured?.expectedValueEnv && configured.expectedValueEnv.trim().length > 0 ? process.env[configured.expectedValueEnv.trim()] : void 0;
12
+ const expectedFromConfig = 'string' == typeof configured?.expectedValue && configured.expectedValue.trim().length > 0 ? configured.expectedValue.trim() : void 0;
13
+ const expectedValue = expectedFromConfig || expectedFromEnv;
14
+ const enabled = configured?.enabled === true;
15
+ if (enabled && !expectedValue) throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] auth.enabled true but no expected token configured');
16
+ return {
17
+ enabled,
18
+ headerName,
19
+ expectedValue
20
+ };
21
+ }
22
+ function normalizeRequiredRuntimeFallbackSignalAuthConfig(configured) {
23
+ if (configured?.enabled === false) throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] auth.enabled cannot be false when runtimeFallbackSignal.enabled is true');
24
+ const authConfig = normalizeRuntimeFallbackSignalAuthConfig(configured);
25
+ if (!authConfig.expectedValue) throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] auth.expectedValue or auth.expectedValueEnv is required when runtimeFallbackSignal.enabled is true');
26
+ return {
27
+ ...authConfig,
28
+ enabled: true
29
+ };
30
+ }
31
+ function safeTokenEquals(candidate, expected) {
32
+ const candidateDigest = createHash('sha256').update(candidate).digest();
33
+ const expectedDigest = createHash('sha256').update(expected).digest();
34
+ return timingSafeEqual(candidateDigest, expectedDigest);
35
+ }
36
+ function enforceRuntimeFallbackSignalAuthToken(token, authConfig) {
37
+ if (!authConfig.enabled) return;
38
+ if (!token || !authConfig.expectedValue || !safeTokenEquals(token, authConfig.expectedValue)) throw createRuntimeSignalError('runtime fallback signal auth failed', 'UNAUTHORIZED');
39
+ }
40
+ function enforceRuntimeFallbackSignalAuth(c, runtimeSignalConfig) {
41
+ enforceRuntimeFallbackSignalAuthToken(c.req.header(runtimeSignalConfig.auth.headerName), runtimeSignalConfig.auth);
42
+ }
43
+ const normalizeInteger = (value, fallback, minimum)=>{
44
+ const candidate = 'number' == typeof value && Number.isFinite(value) ? value : fallback;
45
+ return Math.max(minimum, Math.floor(candidate));
46
+ };
47
+ function normalizeRuntimeFallbackTrustPolicy(configured) {
48
+ const allowedApps = Array.isArray(configured?.allowedApps) ? configured.allowedApps.map((item)=>'string' == typeof item ? item.trim() : '').filter(Boolean) : [];
49
+ const allowedEntryOrigins = Array.isArray(configured?.allowedEntryOrigins) ? configured.allowedEntryOrigins.map((item)=>normalizeRuntimeSignalOrigin(item)).filter((item)=>Boolean(item)) : [];
50
+ const expectedRuntimeDigests = {};
51
+ Object.entries(configured?.expectedRuntimeDigests || {}).forEach(([appName, digest])=>{
52
+ if ('string' == typeof appName && appName.trim().length > 0 && 'string' == typeof digest && digest.trim().length > 0) expectedRuntimeDigests[appName.trim()] = digest.trim();
53
+ });
54
+ return {
55
+ allowedApps,
56
+ allowedEntryOrigins,
57
+ expectedRuntimeDigests,
58
+ enforceRuntimeDigest: configured?.enforceRuntimeDigest === true,
59
+ maxSignalsPerWindow: normalizeInteger(configured?.maxSignalsPerWindow, DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW, 1),
60
+ windowMs: normalizeInteger(configured?.windowMs, DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS, 1),
61
+ dedupeWindowMs: normalizeInteger(configured?.dedupeWindowMs, DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS, 0)
62
+ };
63
+ }
64
+ function enforceRuntimeFallbackSignalTrustPolicy(payload, runtimeSignalContext, source = {}) {
65
+ const { trustPolicy, runtimeState } = runtimeSignalContext;
66
+ const now = Date.now();
67
+ cleanupRuntimeFallbackSignalRuntimeState(now, runtimeState, trustPolicy);
68
+ const appName = normalizeRuntimeSignalAppName(payload);
69
+ const entryOrigin = normalizeRuntimeSignalOrigin(payload.entry);
70
+ const runtimeDigest = normalizeRuntimeSignalRuntimeDigest(payload);
71
+ if (trustPolicy.allowedApps.length > 0 && !trustPolicy.allowedApps.includes(appName)) throw createRuntimeSignalError(`runtime fallback signal app "${appName}" is not trusted`, 'UNTRUSTED_SOURCE');
72
+ if (trustPolicy.allowedEntryOrigins.length > 0) {
73
+ if (!entryOrigin || !trustPolicy.allowedEntryOrigins.includes(entryOrigin)) throw createRuntimeSignalError(`runtime fallback signal entry origin "${entryOrigin || 'unknown'}" is not trusted`, 'UNTRUSTED_SOURCE');
74
+ }
75
+ const expectedDigest = trustPolicy.expectedRuntimeDigests[appName];
76
+ if (expectedDigest && runtimeDigest !== expectedDigest) throw createRuntimeSignalError(`runtime fallback runtimeDigest mismatch for app "${appName}"`, 'UNTRUSTED_SOURCE');
77
+ if (trustPolicy.enforceRuntimeDigest && !runtimeDigest) throw createRuntimeSignalError(`runtime fallback signal app "${appName}" missing runtimeDigest`, 'UNTRUSTED_SOURCE');
78
+ const dedupeFingerprint = JSON.stringify({
79
+ appName,
80
+ entryOrigin: entryOrigin || 'unknown',
81
+ reason: payload.reason || 'runtime_fallback',
82
+ phase: payload.phase || 'unknown',
83
+ runtimeDigest: runtimeDigest || 'unknown'
84
+ });
85
+ const dedupeWindowMs = trustPolicy.dedupeWindowMs;
86
+ if (dedupeWindowMs > 0) {
87
+ const lastSeenAt = runtimeState.dedupeByFingerprint.get(dedupeFingerprint);
88
+ runtimeState.dedupeByFingerprint.set(dedupeFingerprint, now);
89
+ if ('number' == typeof lastSeenAt && now - lastSeenAt <= dedupeWindowMs) return {
90
+ deduped: true
91
+ };
92
+ } else runtimeState.dedupeByFingerprint.set(dedupeFingerprint, now);
93
+ const remoteAddress = source.remoteAddress?.trim();
94
+ const sourceKey = remoteAddress || 'unknown-remote';
95
+ const rateState = runtimeState.rateLimitBySource.get(sourceKey);
96
+ if (!rateState || now - rateState.windowStartedAt > trustPolicy.windowMs) runtimeState.rateLimitBySource.set(sourceKey, {
97
+ count: 1,
98
+ windowStartedAt: now
99
+ });
100
+ else {
101
+ if (rateState.count >= trustPolicy.maxSignalsPerWindow) throw createRuntimeSignalError(`runtime fallback signal rate-limited source "${sourceKey}"`, 'RATE_LIMITED');
102
+ rateState.count += 1;
103
+ }
104
+ return {
105
+ deduped: false
106
+ };
107
+ }
108
+ export { enforceRuntimeFallbackSignalAuth, enforceRuntimeFallbackSignalAuthToken, enforceRuntimeFallbackSignalTrustPolicy, normalizeRequiredRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackTrustPolicy, resolveRuntimeFallbackSignalEndpoint };
@@ -0,0 +1,40 @@
1
+ import "node:module";
2
+ import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from "../contract-gate-snapshot-store/index.mjs";
3
+ function createRuntimeFallbackSignalRuntimeState() {
4
+ return {
5
+ rateLimitBySource: new Map(),
6
+ dedupeByFingerprint: new Map()
7
+ };
8
+ }
9
+ function cleanupRuntimeFallbackSignalRuntimeState(now, runtimeState, trustPolicy) {
10
+ const rateLimitWindowMs = Math.max(1, trustPolicy.windowMs);
11
+ for (const [sourceKey, rateState] of runtimeState.rateLimitBySource)if (now - rateState.windowStartedAt > rateLimitWindowMs) runtimeState.rateLimitBySource.delete(sourceKey);
12
+ const dedupeWindowMs = Math.max(0, trustPolicy.dedupeWindowMs);
13
+ if (0 === dedupeWindowMs) return void runtimeState.dedupeByFingerprint.clear();
14
+ for (const [fingerprint, lastSeenAt] of runtimeState.dedupeByFingerprint)if (now - lastSeenAt > dedupeWindowMs) runtimeState.dedupeByFingerprint.delete(fingerprint);
15
+ }
16
+ async function persistRuntimeFallbackContractGate(payload, runtimeSignalConfig) {
17
+ const now = Date.now();
18
+ const gateSnapshotStore = await runtimeSignalConfig.gateSnapshotStore;
19
+ const snapshot = await gateSnapshotStore.readSnapshot() || {};
20
+ const existingGates = snapshot.gates && 'object' == typeof snapshot.gates ? snapshot.gates : {};
21
+ const reason = 'string' == typeof payload.reason ? payload.reason : 'runtime_fallback';
22
+ const phase = 'string' == typeof payload.phase ? payload.phase : 'unknown';
23
+ const appName = 'string' == typeof payload.appName ? payload.appName : 'unknown';
24
+ const entry = 'string' == typeof payload.entry ? payload.entry : void 0;
25
+ snapshot.schemaVersion = 'number' == typeof snapshot.schemaVersion ? snapshot.schemaVersion : CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
26
+ snapshot.updatedAt = now;
27
+ snapshot.gates = {
28
+ ...existingGates,
29
+ [runtimeSignalConfig.gateName]: {
30
+ passed: false,
31
+ reason: `runtime_fallback:${reason} phase=${phase} app=${appName}${entry ? ` entry=${entry}` : ''}`,
32
+ updatedAt: now,
33
+ expiresAt: now + runtimeSignalConfig.failureHoldMs,
34
+ source: 'runtime-mf-fallback-signal',
35
+ metadata: payload
36
+ }
37
+ };
38
+ await gateSnapshotStore.writeSnapshot(snapshot);
39
+ }
40
+ export { cleanupRuntimeFallbackSignalRuntimeState, createRuntimeFallbackSignalRuntimeState, persistRuntimeFallbackContractGate };
@@ -1,223 +1,2 @@
1
1
  import "node:module";
2
- import { createHash, timingSafeEqual } from "node:crypto";
3
- import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from "./contractGateSnapshotStore.mjs";
4
- const DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT = '/_modern/contract-gates/runtime-fallback';
5
- const DEFAULT_RUNTIME_STATUS_ENDPOINT = '/_modern/runtime/status';
6
- const DEFAULT_RUNTIME_FALLBACK_GATE_NAME = 'runtime-mf-fallback-health';
7
- const DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS = 300000;
8
- const DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES = 16384;
9
- const DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER = 'x-modernjs-runtime-signal-token';
10
- const DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW = 30;
11
- const DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS = 60000;
12
- const DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS = 10000;
13
- function resolveRuntimeFallbackSignalEndpoint(configuredEndpoint) {
14
- const rawEndpoint = configuredEndpoint?.trim();
15
- if (!rawEndpoint) return DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT;
16
- if (rawEndpoint.startsWith('/')) return rawEndpoint;
17
- try {
18
- return new URL(rawEndpoint).pathname || DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT;
19
- } catch (_error) {
20
- return `/${rawEndpoint.replace(/^\/+/, '')}`;
21
- }
22
- }
23
- function createRuntimeSignalError(message, code) {
24
- const error = new Error(message);
25
- error.code = code;
26
- return error;
27
- }
28
- function getUtf8ByteLength(input) {
29
- if ("u" > typeof Buffer) return Buffer.byteLength(input);
30
- return new TextEncoder().encode(input).length;
31
- }
32
- function normalizeRuntimeSignalOrigin(value) {
33
- if ('string' != typeof value || 0 === value.trim().length) return;
34
- try {
35
- return new URL(value).origin;
36
- } catch (_error) {
37
- return;
38
- }
39
- }
40
- function normalizeRuntimeSignalAppName(payload) {
41
- if ('string' != typeof payload.appName) return 'unknown';
42
- const normalized = payload.appName.trim();
43
- return normalized.length > 0 ? normalized : 'unknown';
44
- }
45
- function normalizeRuntimeSignalRuntimeDigest(payload) {
46
- if ('string' == typeof payload.runtimeDigest && payload.runtimeDigest.trim()) return payload.runtimeDigest.trim();
47
- const metadata = payload.metadata;
48
- if (metadata && 'object' == typeof metadata && !Array.isArray(metadata) && 'string' == typeof metadata.runtimeDigest) {
49
- const digest = String(metadata.runtimeDigest).trim();
50
- if (digest) return digest;
51
- }
52
- }
53
- function normalizeRuntimeFallbackSignalAuthConfig(configured) {
54
- const headerName = 'string' == typeof configured?.headerName && configured.headerName.trim() ? configured.headerName.trim().toLowerCase() : DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER;
55
- const expectedFromEnv = 'string' == typeof configured?.expectedValueEnv && configured.expectedValueEnv.trim().length > 0 ? process.env[configured.expectedValueEnv.trim()] : void 0;
56
- const expectedFromConfig = 'string' == typeof configured?.expectedValue && configured.expectedValue.trim().length > 0 ? configured.expectedValue.trim() : void 0;
57
- const expectedValue = expectedFromConfig || expectedFromEnv;
58
- const enabled = configured?.enabled === true;
59
- if (enabled && !expectedValue) throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] auth.enabled is true but no expected token is configured');
60
- return {
61
- enabled,
62
- headerName,
63
- expectedValue
64
- };
65
- }
66
- function normalizeRequiredRuntimeFallbackSignalAuthConfig(configured) {
67
- if (configured?.enabled === false) throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] the endpoint cannot be enabled with auth disabled; configure auth.expectedValue or auth.expectedValueEnv');
68
- try {
69
- return normalizeRuntimeFallbackSignalAuthConfig({
70
- ...configured,
71
- enabled: true
72
- });
73
- } catch (_error) {
74
- throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] enabling the endpoint requires an auth token; configure auth.expectedValue or auth.expectedValueEnv');
75
- }
76
- }
77
- function safeTokenEquals(candidate, expected) {
78
- const candidateDigest = createHash('sha256').update(candidate).digest();
79
- const expectedDigest = createHash('sha256').update(expected).digest();
80
- return timingSafeEqual(candidateDigest, expectedDigest);
81
- }
82
- function enforceRuntimeFallbackSignalAuthToken(token, authConfig) {
83
- if (!authConfig.enabled) return;
84
- if (!token || !authConfig.expectedValue || !safeTokenEquals(token, authConfig.expectedValue)) throw createRuntimeSignalError('runtime fallback signal auth failed', 'UNAUTHORIZED');
85
- }
86
- function enforceRuntimeFallbackSignalAuth(c, runtimeSignalConfig) {
87
- enforceRuntimeFallbackSignalAuthToken(c.req.header(runtimeSignalConfig.auth.headerName), runtimeSignalConfig.auth);
88
- }
89
- function normalizeRuntimeFallbackTrustPolicy(configured) {
90
- const allowedApps = Array.isArray(configured?.allowedApps) ? configured.allowedApps.map((item)=>'string' == typeof item ? item.trim() : '').filter(Boolean) : [];
91
- const allowedEntryOrigins = Array.isArray(configured?.allowedEntryOrigins) ? configured.allowedEntryOrigins.map((item)=>normalizeRuntimeSignalOrigin(item)).filter((item)=>Boolean(item)) : [];
92
- const expectedRuntimeDigestsRaw = configured?.expectedRuntimeDigests || {};
93
- const expectedRuntimeDigests = {};
94
- Object.entries(expectedRuntimeDigestsRaw).forEach(([appName, digest])=>{
95
- if ('string' == typeof appName && appName.trim().length > 0 && 'string' == typeof digest && digest.trim().length > 0) expectedRuntimeDigests[appName.trim()] = digest.trim();
96
- });
97
- return {
98
- allowedApps,
99
- allowedEntryOrigins,
100
- expectedRuntimeDigests,
101
- enforceRuntimeDigest: configured?.enforceRuntimeDigest === true,
102
- maxSignalsPerWindow: Math.max(1, Math.floor(configured?.maxSignalsPerWindow ?? DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW)),
103
- windowMs: Math.max(1000, Math.floor(configured?.windowMs ?? DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS)),
104
- dedupeWindowMs: Math.max(0, Math.floor(configured?.dedupeWindowMs ?? DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS))
105
- };
106
- }
107
- function createRuntimeFallbackSignalRuntimeState() {
108
- return {
109
- rateLimitBySource: new Map(),
110
- dedupeByFingerprint: new Map()
111
- };
112
- }
113
- function cleanupRuntimeFallbackSignalRuntimeState(now, runtimeState, trustPolicy) {
114
- const dedupeExpiryMs = Math.max(trustPolicy.dedupeWindowMs, trustPolicy.windowMs, 1000);
115
- runtimeState.dedupeByFingerprint.forEach((lastSeenAt, fingerprint)=>{
116
- if (now - lastSeenAt > dedupeExpiryMs) runtimeState.dedupeByFingerprint.delete(fingerprint);
117
- });
118
- runtimeState.rateLimitBySource.forEach((state, source)=>{
119
- if (now - state.windowStartedAt > 2 * trustPolicy.windowMs) runtimeState.rateLimitBySource.delete(source);
120
- });
121
- }
122
- function enforceRuntimeFallbackSignalTrustPolicy(payload, runtimeSignalContext, source = {}) {
123
- const { trustPolicy, runtimeState } = runtimeSignalContext;
124
- const now = Date.now();
125
- cleanupRuntimeFallbackSignalRuntimeState(now, runtimeState, trustPolicy);
126
- const appName = normalizeRuntimeSignalAppName(payload);
127
- const entryOrigin = normalizeRuntimeSignalOrigin(payload.entry);
128
- const runtimeDigest = normalizeRuntimeSignalRuntimeDigest(payload);
129
- if (trustPolicy.allowedApps.length > 0 && !trustPolicy.allowedApps.includes(appName)) throw createRuntimeSignalError(`runtime fallback signal app "${appName}" is not trusted`, 'UNTRUSTED_SOURCE');
130
- if (trustPolicy.allowedEntryOrigins.length > 0) {
131
- if (!entryOrigin || !trustPolicy.allowedEntryOrigins.includes(entryOrigin)) throw createRuntimeSignalError(`runtime fallback signal entry origin "${entryOrigin || 'unknown'}" is not trusted`, 'UNTRUSTED_SOURCE');
132
- }
133
- const expectedDigest = trustPolicy.expectedRuntimeDigests[appName];
134
- if (expectedDigest && runtimeDigest !== expectedDigest) throw createRuntimeSignalError(`runtime fallback runtimeDigest mismatch for app "${appName}"`, 'UNTRUSTED_SOURCE');
135
- if (trustPolicy.enforceRuntimeDigest && !runtimeDigest) throw createRuntimeSignalError(`runtime fallback signal for app "${appName}" is missing runtimeDigest`, 'UNTRUSTED_SOURCE');
136
- const dedupeFingerprint = JSON.stringify({
137
- appName,
138
- entryOrigin: entryOrigin || 'unknown',
139
- reason: payload.reason || 'runtime_fallback',
140
- phase: payload.phase || 'unknown',
141
- runtimeDigest: runtimeDigest || 'unknown'
142
- });
143
- const dedupeWindowMs = trustPolicy.dedupeWindowMs;
144
- if (dedupeWindowMs > 0) {
145
- const lastSeenAt = runtimeState.dedupeByFingerprint.get(dedupeFingerprint);
146
- runtimeState.dedupeByFingerprint.set(dedupeFingerprint, now);
147
- if ('number' == typeof lastSeenAt && now - lastSeenAt <= dedupeWindowMs) return {
148
- deduped: true
149
- };
150
- } else runtimeState.dedupeByFingerprint.set(dedupeFingerprint, now);
151
- const remoteAddress = source.remoteAddress?.trim();
152
- const sourceKey = remoteAddress || 'unknown-remote';
153
- const rateState = runtimeState.rateLimitBySource.get(sourceKey);
154
- if (!rateState || now - rateState.windowStartedAt > trustPolicy.windowMs) runtimeState.rateLimitBySource.set(sourceKey, {
155
- count: 1,
156
- windowStartedAt: now
157
- });
158
- else {
159
- if (rateState.count >= trustPolicy.maxSignalsPerWindow) throw createRuntimeSignalError(`runtime fallback signal rate-limited for source "${sourceKey}"`, 'RATE_LIMITED');
160
- rateState.count += 1;
161
- }
162
- return {
163
- deduped: false
164
- };
165
- }
166
- async function parseRuntimeFallbackSignalPayload(c, maxBodyBytes) {
167
- const contentLengthHeader = c.req.header('content-length');
168
- if (contentLengthHeader) {
169
- const contentLength = Number.parseInt(contentLengthHeader, 10);
170
- if (Number.isFinite(contentLength) && contentLength > maxBodyBytes) throw createRuntimeSignalError('runtime fallback signal payload too large', 'PAYLOAD_TOO_LARGE');
171
- }
172
- const rawBody = await c.req.raw.text();
173
- const payload = parseRuntimeFallbackSignalPayloadFromRawBody(rawBody, maxBodyBytes);
174
- return {
175
- rawBody,
176
- payload
177
- };
178
- }
179
- function parseRuntimeFallbackSignalPayloadFromRawBody(rawBody, maxBodyBytes) {
180
- if (!rawBody || 0 === rawBody.trim().length) throw createRuntimeSignalError('runtime fallback signal body is empty', 'INVALID_PAYLOAD');
181
- if (getUtf8ByteLength(rawBody) > maxBodyBytes) throw createRuntimeSignalError('runtime fallback signal payload too large', 'PAYLOAD_TOO_LARGE');
182
- let payload;
183
- try {
184
- payload = JSON.parse(rawBody);
185
- } catch (_error) {
186
- throw createRuntimeSignalError('runtime fallback signal body must be valid JSON', 'INVALID_PAYLOAD');
187
- }
188
- if (!payload || 'object' != typeof payload || Array.isArray(payload)) throw createRuntimeSignalError('runtime fallback signal body must be a JSON object', 'INVALID_PAYLOAD');
189
- return payload;
190
- }
191
- function getRuntimeSignalErrorStatusCode(signalError) {
192
- if ('PAYLOAD_TOO_LARGE' === signalError.code) return 413;
193
- if ('INVALID_PAYLOAD' === signalError.code) return 400;
194
- if ('UNAUTHORIZED' === signalError.code) return 401;
195
- if ('RATE_LIMITED' === signalError.code) return 429;
196
- if ('UNTRUSTED_SOURCE' === signalError.code) return 403;
197
- return 500;
198
- }
199
- async function persistRuntimeFallbackContractGate(payload, runtimeSignalConfig) {
200
- const now = Date.now();
201
- const gateSnapshotStore = await runtimeSignalConfig.gateSnapshotStore;
202
- const snapshot = await gateSnapshotStore.readSnapshot() || {};
203
- const existingGates = snapshot.gates && 'object' == typeof snapshot.gates ? snapshot.gates : {};
204
- const reason = 'string' == typeof payload.reason ? payload.reason : 'runtime_fallback';
205
- const phase = 'string' == typeof payload.phase ? payload.phase : 'unknown';
206
- const appName = 'string' == typeof payload.appName ? payload.appName : 'unknown';
207
- const entry = 'string' == typeof payload.entry ? payload.entry : void 0;
208
- snapshot.schemaVersion = 'number' == typeof snapshot.schemaVersion ? snapshot.schemaVersion : CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
209
- snapshot.updatedAt = now;
210
- snapshot.gates = {
211
- ...existingGates,
212
- [runtimeSignalConfig.gateName]: {
213
- passed: false,
214
- reason: `runtime_fallback:${reason} phase=${phase} app=${appName}${entry ? ` entry=${entry}` : ''}`,
215
- updatedAt: now,
216
- expiresAt: now + runtimeSignalConfig.failureHoldMs,
217
- source: 'runtime-mf-fallback-signal',
218
- metadata: payload
219
- }
220
- };
221
- await gateSnapshotStore.writeSnapshot(snapshot);
222
- }
223
- export { DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS, DEFAULT_RUNTIME_FALLBACK_GATE_NAME, DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES, DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, DEFAULT_RUNTIME_STATUS_ENDPOINT, createRuntimeFallbackSignalRuntimeState, createRuntimeSignalError, enforceRuntimeFallbackSignalAuth, enforceRuntimeFallbackSignalAuthToken, enforceRuntimeFallbackSignalTrustPolicy, getRuntimeSignalErrorStatusCode, normalizeRequiredRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackTrustPolicy, parseRuntimeFallbackSignalPayload, parseRuntimeFallbackSignalPayloadFromRawBody, persistRuntimeFallbackContractGate, resolveRuntimeFallbackSignalEndpoint };
2
+ export * from "./runtime-fallback-signal/index.mjs";