@bleedingdev/modern-js-server-runtime-extensions 3.5.0-ultramodern.4 → 3.5.0-ultramodern.40

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