@bleedingdev/modern-js-server-runtime-extensions 3.9.0-ultramodern.2 → 3.9.0-ultramodern.21
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.
- package/README.md +8 -6
- package/dist/cjs/backend-federation-security/index.js +73 -152
- package/dist/cjs/bff-policy/crossProjectPolicy.js +299 -0
- package/dist/cjs/bff-policy/index.js +69 -0
- package/dist/cjs/bff-policy/node.js +85 -0
- package/dist/cjs/bff-policy/operationContracts.js +197 -0
- package/dist/cjs/bff-policy/operationIdentity.js +81 -0
- package/dist/cjs/bff-policy/producer.js +79 -0
- package/dist/cjs/bff-policy/resolveCrossProjectPolicy.js +65 -0
- package/dist/cjs/contract-gate-snapshot-store/http-store.js +1 -8
- package/dist/cjs/errorResponsePlugin.js +57 -0
- package/dist/cjs/localisedLoader.js +65 -0
- package/dist/cjs/localisedLoaderPlugin.js +62 -0
- package/dist/cjs/mfCache.js +6 -0
- package/dist/cjs/module-federation-css/plugin.js +6 -0
- package/dist/cjs/module-federation-css/remote.js +2 -1
- package/dist/cjs/serverConfig.js +18 -0
- package/dist/cjs/serverPlugin.js +74 -0
- package/dist/cjs/static-serving/plugin.js +57 -0
- package/dist/cjs/static-serving/responders.js +158 -0
- package/dist/cjs/static-serving/staticModuleFederation.js +173 -0
- package/dist/cjs/static-serving/staticPrecompressed.js +152 -0
- package/dist/cjs/telemetry/exporters.js +4 -4
- package/dist/cjs/telemetry/healthSetup.js +14 -14
- package/dist/cjs/telemetry/lifecycle.js +20 -21
- package/dist/cjs/telemetry/plugin.js +10 -4
- package/dist/cjs/telemetry/runtimeEndpoints.js +3 -2
- package/dist/cjs/telemetryCore.js +5 -5
- package/dist/esm/backend-federation-security/index.mjs +73 -152
- package/dist/esm/bff-policy/crossProjectPolicy.mjs +249 -0
- package/dist/esm/bff-policy/index.mjs +2 -0
- package/dist/esm/bff-policy/operationIdentity.mjs +30 -0
- package/dist/esm/bff-policy/producer.mjs +31 -0
- package/dist/esm/contract-gate-snapshot-store/http-store.mjs +1 -8
- package/dist/esm/errorResponsePlugin.mjs +19 -0
- package/dist/esm/localisedLoader.mjs +24 -0
- package/dist/esm/localisedLoaderPlugin.mjs +24 -0
- package/dist/esm/mfCache.mjs +6 -0
- package/dist/esm/module-federation-css/plugin.mjs +6 -0
- package/dist/esm/module-federation-css/remote.mjs +2 -1
- package/dist/esm/serverConfig.mjs +0 -0
- package/dist/esm/serverPlugin.mjs +34 -0
- package/dist/esm/telemetry/exporters.mjs +2 -2
- package/dist/esm/telemetry/healthSetup.mjs +14 -14
- package/dist/esm/telemetry/lifecycle.mjs +21 -22
- package/dist/esm/telemetry/plugin.mjs +9 -3
- package/dist/esm/telemetry/runtimeEndpoints.mjs +3 -2
- package/dist/esm/telemetryCore.mjs +1 -1
- package/dist/esm-node/backend-federation-security/index.mjs +73 -152
- package/dist/esm-node/bff-policy/crossProjectPolicy.mjs +250 -0
- package/dist/esm-node/bff-policy/index.mjs +3 -0
- package/dist/esm-node/bff-policy/node.mjs +4 -0
- package/dist/esm-node/bff-policy/operationContracts.mjs +107 -0
- package/dist/esm-node/bff-policy/operationIdentity.mjs +31 -0
- package/dist/esm-node/bff-policy/producer.mjs +32 -0
- package/dist/esm-node/bff-policy/resolveCrossProjectPolicy.mjs +28 -0
- package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +1 -8
- package/dist/esm-node/errorResponsePlugin.mjs +20 -0
- package/dist/esm-node/localisedLoader.mjs +25 -0
- package/dist/esm-node/localisedLoaderPlugin.mjs +25 -0
- package/dist/esm-node/mfCache.mjs +6 -0
- package/dist/esm-node/module-federation-css/plugin.mjs +6 -0
- package/dist/esm-node/module-federation-css/remote.mjs +2 -1
- package/dist/esm-node/serverConfig.mjs +1 -0
- package/dist/esm-node/serverPlugin.mjs +35 -0
- package/dist/esm-node/static-serving/plugin.mjs +18 -0
- package/dist/esm-node/static-serving/responders.mjs +111 -0
- package/dist/esm-node/static-serving/staticModuleFederation.mjs +105 -0
- package/dist/esm-node/static-serving/staticPrecompressed.mjs +112 -0
- package/dist/esm-node/telemetry/exporters.mjs +2 -2
- package/dist/esm-node/telemetry/healthSetup.mjs +14 -14
- package/dist/esm-node/telemetry/lifecycle.mjs +21 -22
- package/dist/esm-node/telemetry/plugin.mjs +9 -3
- package/dist/esm-node/telemetry/runtimeEndpoints.mjs +3 -2
- package/dist/esm-node/telemetryCore.mjs +1 -1
- package/dist/types/backend-federation-security/node.d.ts +1 -1
- package/dist/types/bff-policy/crossProjectPolicy.d.ts +101 -0
- package/dist/types/bff-policy/index.d.ts +2 -0
- package/dist/types/bff-policy/node.d.ts +3 -0
- package/dist/types/bff-policy/operationContracts.d.ts +46 -0
- package/dist/types/bff-policy/operationIdentity.d.ts +34 -0
- package/dist/types/bff-policy/producer.d.ts +10 -0
- package/dist/types/bff-policy/resolveCrossProjectPolicy.d.ts +39 -0
- package/dist/types/errorResponsePlugin.d.ts +3 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/localisedLoader.d.ts +15 -0
- package/dist/types/localisedLoaderPlugin.d.ts +2 -0
- package/dist/types/mfCache.d.ts +2 -3
- package/dist/types/module-federation-css/plugin.d.ts +2 -3
- package/dist/types/module-federation-css/remote.d.ts +2 -0
- package/dist/types/serverConfig.d.ts +17 -0
- package/dist/types/serverPlugin.d.ts +5 -0
- package/dist/types/static-serving/plugin.d.ts +3 -0
- package/dist/types/static-serving/responders.d.ts +2 -0
- package/dist/types/static-serving/staticModuleFederation.d.ts +13 -0
- package/dist/types/static-serving/staticPrecompressed.d.ts +13 -0
- package/dist/types/telemetry/exporters.d.ts +1 -1
- package/dist/types/telemetry/healthSetup.d.ts +3 -3
- package/dist/types/telemetry/lifecycle.d.ts +4 -4
- package/dist/types/telemetry/plugin.d.ts +2 -1
- package/dist/types/telemetryCore.d.ts +1 -1
- package/dist/types-esm/backend-federation-security/index.d.mts +68 -0
- package/dist/types-esm/backend-federation-security/node.d.mts +3 -0
- package/dist/types-esm/bff-policy/crossProjectPolicy.d.mts +101 -0
- package/dist/types-esm/bff-policy/index.d.mts +2 -0
- package/dist/types-esm/bff-policy/node.d.mts +3 -0
- package/dist/types-esm/bff-policy/operationContracts.d.mts +46 -0
- package/dist/types-esm/bff-policy/operationIdentity.d.mts +34 -0
- package/dist/types-esm/bff-policy/producer.d.mts +10 -0
- package/dist/types-esm/bff-policy/resolveCrossProjectPolicy.d.mts +39 -0
- package/dist/types-esm/contract-gate-snapshot-normalization.d.mts +15 -0
- package/dist/types-esm/contract-gate-snapshot-store/file-store.d.mts +3 -0
- package/dist/types-esm/contract-gate-snapshot-store/http-store.d.mts +5 -0
- package/dist/types-esm/contract-gate-snapshot-store/index.d.mts +5 -0
- package/dist/types-esm/contract-gate-snapshot-store/resolve.d.mts +9 -0
- package/dist/types-esm/contract-gate-snapshot-store/types.d.mts +47 -0
- package/dist/types-esm/contractGateSnapshotObserver.d.mts +33 -0
- package/dist/types-esm/env.d.mts +40 -0
- package/dist/types-esm/errorResponsePlugin.d.mts +3 -0
- package/dist/types-esm/index.d.mts +8 -0
- package/dist/types-esm/localisedLoader.d.mts +15 -0
- package/dist/types-esm/localisedLoaderPlugin.d.mts +2 -0
- package/dist/types-esm/mfCache.d.mts +26 -0
- package/dist/types-esm/module-federation-css/collector.d.mts +25 -0
- package/dist/types-esm/module-federation-css/index.d.mts +8 -0
- package/dist/types-esm/module-federation-css/manifest.d.mts +28 -0
- package/dist/types-esm/module-federation-css/plugin.d.mts +22 -0
- package/dist/types-esm/module-federation-css/remote.d.mts +22 -0
- package/dist/types-esm/runtime-fallback-signal/index.d.mts +4 -0
- package/dist/types-esm/runtime-fallback-signal/model.d.mts +70 -0
- package/dist/types-esm/runtime-fallback-signal/resolver.d.mts +29 -0
- package/dist/types-esm/runtime-fallback-signal/store.d.mts +4 -0
- package/dist/types-esm/runtimeFallbackSignal.d.mts +1 -0
- package/dist/types-esm/runtimeLifecycle.d.mts +10 -0
- package/dist/types-esm/serverConfig.d.mts +17 -0
- package/dist/types-esm/serverPlugin.d.mts +5 -0
- package/dist/types-esm/static-serving/plugin.d.mts +3 -0
- package/dist/types-esm/static-serving/responders.d.mts +2 -0
- package/dist/types-esm/static-serving/staticModuleFederation.d.mts +13 -0
- package/dist/types-esm/static-serving/staticPrecompressed.d.mts +13 -0
- package/dist/types-esm/telemetry/envelope.d.mts +55 -0
- package/dist/types-esm/telemetry/exporters.d.mts +12 -0
- package/dist/types-esm/telemetry/healthEvaluation.d.mts +20 -0
- package/dist/types-esm/telemetry/healthMonitor.d.mts +88 -0
- package/dist/types-esm/telemetry/healthSetup.d.mts +17 -0
- package/dist/types-esm/telemetry/lifecycle.d.mts +18 -0
- package/dist/types-esm/telemetry/metrics.d.mts +3 -0
- package/dist/types-esm/telemetry/plugin.d.mts +13 -0
- package/dist/types-esm/telemetry/registry.d.mts +69 -0
- package/dist/types-esm/telemetry/registryTypes.d.mts +50 -0
- package/dist/types-esm/telemetry/runtimeEndpoints.d.mts +35 -0
- package/dist/types-esm/telemetry.d.mts +1 -0
- package/dist/types-esm/telemetryCore.d.mts +6 -0
- package/package.json +183 -29
- package/rslib.config.mts +36 -2
- package/rstest.config.mts +11 -0
- package/src/backend-federation-security/index.ts +151 -318
- package/src/backend-federation-security/node.ts +24 -22
- package/src/bff-policy/crossProjectPolicy.ts +754 -0
- package/src/bff-policy/index.ts +2 -0
- package/src/bff-policy/node.ts +3 -0
- package/src/bff-policy/operationContracts.ts +225 -0
- package/src/bff-policy/operationIdentity.ts +90 -0
- package/src/bff-policy/producer.ts +40 -0
- package/src/bff-policy/resolveCrossProjectPolicy.ts +88 -0
- package/src/contract-gate-snapshot-store/http-store.ts +1 -11
- package/src/contract-gate-snapshot-store/resolve.ts +0 -1
- package/src/errorResponsePlugin.ts +21 -0
- package/src/index.ts +4 -0
- package/src/localisedLoader.ts +50 -0
- package/src/localisedLoaderPlugin.ts +33 -0
- package/src/mfCache.ts +4 -3
- package/src/module-federation-css/plugin.ts +4 -3
- package/src/module-federation-css/remote.ts +3 -1
- package/src/serverConfig.ts +32 -0
- package/src/serverPlugin.ts +38 -0
- package/src/static-serving/plugin.ts +16 -0
- package/src/static-serving/responders.ts +208 -0
- package/src/static-serving/staticModuleFederation.ts +255 -0
- package/src/static-serving/staticPrecompressed.ts +193 -0
- package/src/telemetry/exporters.ts +1 -1
- package/src/telemetry/healthSetup.ts +17 -20
- package/src/telemetry/lifecycle.ts +27 -39
- package/src/telemetry/plugin.ts +6 -4
- package/src/telemetry/runtimeEndpoints.ts +3 -2
- package/src/telemetryCore.ts +1 -1
- package/tests/backendFederationSecurity.test.ts +63 -0
- package/tests/bff-policy/crossProjectPolicy.matrix.test.ts +450 -0
- package/tests/bff-policy/crossProjectPolicy.test.ts +197 -0
- package/tests/bff-policy/operationContracts.test.ts +278 -0
- package/tests/bff-policy/optionalZodPeer.test.ts +30 -0
- package/tests/bff-policy/resolveCrossProjectPolicy.test.ts +76 -0
- package/tests/bff-policy/zodEvaluatorProbe.test.ts +49 -0
- package/tests/contractGateSnapshotObserver.test.ts +0 -58
- package/tests/contractGateSnapshotStore.test.ts +0 -51
- package/tests/env.test.ts +45 -64
- package/tests/localisedLoader.test.ts +155 -0
- package/tests/mfCache.test.ts +1 -88
- package/tests/moduleFederationCss.test.ts +98 -41
- package/tests/nativeErrorResponse.test.ts +118 -0
- package/tests/nativeServerAssembly.test.ts +385 -0
- package/tests/runtimeLifecycle.test.ts +69 -17
- package/tests/static-serving/ordering.test.ts +214 -0
- package/tests/static-serving/static.test.ts +411 -0
- package/tests/telemetry.test.ts +35 -198
- package/tests/telemetryHealthMonitor.test.ts +0 -4
- package/tests/telemetryHealthObservation.test.ts +302 -0
- package/tests/telemetryLifecycle.test.ts +7 -303
- package/tests/telemetryRegistryQueueMatrix.test.ts +14 -111
- package/tests/registration.test.ts +0 -112
- package/tests/telemetryAutopilot.test.ts +0 -1134
|
@@ -142,97 +142,85 @@ const sha256Hex = async (bytes, signal)=>{
|
|
|
142
142
|
const digest = new Uint8Array(await readWithAbort(subtle.digest('SHA-256', bytes), signal));
|
|
143
143
|
return Array.from(digest, (byte)=>byte.toString(16).padStart(2, '0')).join('');
|
|
144
144
|
};
|
|
145
|
-
async function
|
|
146
|
-
const
|
|
147
|
-
assertAllowedEntryUrl(requestedUrl, true === options.allowInsecureHttp);
|
|
148
|
-
const maxBytes = options.maxBytes ?? DEFAULT_MAX_RESOURCE_BYTES;
|
|
149
|
-
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new BackendFederationRemoteEntryError('invalid_verification', '[Module Federation] Backend federation resource maxBytes must be a positive safe integer.');
|
|
145
|
+
async function acquireBackendFederationResource(requestedUrl, options, policy) {
|
|
146
|
+
const { label, maxBytes, exactByteLength } = policy;
|
|
150
147
|
const timeoutMs = options.timeoutMs ?? DEFAULT_ENTRY_TIMEOUT_MS;
|
|
151
|
-
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0) throw new BackendFederationRemoteEntryError('invalid_verification', '[Module Federation]
|
|
148
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 0) throw new BackendFederationRemoteEntryError('invalid_verification', '[Module Federation] Resource maxBytes must be a positive safe integer and timeoutMs a non-negative safe integer.');
|
|
149
|
+
if (void 0 !== exactByteLength && exactByteLength > maxBytes) throw new BackendFederationRemoteEntryError('entry_too_large', `[Module Federation] ${label} exceeds the ${maxBytes}-byte policy limit.`);
|
|
152
150
|
const controller = new AbortController();
|
|
153
151
|
let timedOut = false;
|
|
154
|
-
|
|
155
|
-
const onCallerAbort = ()=>{
|
|
156
|
-
callerAborted = true;
|
|
157
|
-
controller.abort(options.signal?.reason);
|
|
158
|
-
};
|
|
152
|
+
const onCallerAbort = ()=>controller.abort(options.signal?.reason);
|
|
159
153
|
if (options.signal?.aborted) onCallerAbort();
|
|
160
154
|
else options.signal?.addEventListener('abort', onCallerAbort, {
|
|
161
155
|
once: true
|
|
162
156
|
});
|
|
163
157
|
const timeout = timeoutMs > 0 ? setTimeout(()=>{
|
|
164
158
|
timedOut = true;
|
|
165
|
-
controller.abort(new Error(
|
|
159
|
+
controller.abort(new Error(`${label} timed out after ${timeoutMs}ms`));
|
|
166
160
|
}, timeoutMs) : void 0;
|
|
167
|
-
const fetchResource = options.fetch ?? globalThis.fetch;
|
|
168
161
|
let reader;
|
|
169
|
-
|
|
170
|
-
const cancellationError = (cause)=>new BackendFederationRemoteEntryError(timedOut ? 'timeout' : 'aborted', timedOut ? `[Module Federation] Backend federation ${resourceKind} timed out after ${timeoutMs}ms.` : `[Module Federation] Backend federation ${resourceKind} loading was aborted.`, {
|
|
171
|
-
cause
|
|
172
|
-
});
|
|
162
|
+
let response;
|
|
173
163
|
try {
|
|
174
|
-
|
|
175
|
-
if (
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
if (!response.ok) throw new BackendFederationRemoteEntryError('fetch_failed', `[Module Federation] Backend federation ${resourceKind} returned HTTP ${response.status}.`);
|
|
190
|
-
if (response.url) {
|
|
191
|
-
const responseUrl = canonicalEntryUrl(response.url);
|
|
192
|
-
if (responseUrl.href !== requestedUrl.href) throw new BackendFederationRemoteEntryError('redirect_mismatch', `[Module Federation] Backend federation ${resourceKind} redirected outside its trusted URL.`, {
|
|
193
|
-
details: {
|
|
194
|
-
expected: redactBackendFederationUrl(requestedUrl.href),
|
|
195
|
-
received: redactBackendFederationUrl(responseUrl.href)
|
|
196
|
-
}
|
|
197
|
-
});
|
|
198
|
-
}
|
|
164
|
+
const fetchResource = options.fetch ?? globalThis.fetch;
|
|
165
|
+
if (controller.signal.aborted) throw controller.signal.reason;
|
|
166
|
+
if ('function' != typeof fetchResource) throw new Error('Loading requires fetch.');
|
|
167
|
+
response = await readWithAbort(fetchResource(requestedUrl.href, {
|
|
168
|
+
cache: 'no-store',
|
|
169
|
+
redirect: 'error',
|
|
170
|
+
signal: controller.signal
|
|
171
|
+
}), controller.signal);
|
|
172
|
+
if (!response.ok) throw new BackendFederationRemoteEntryError('fetch_failed', `[Module Federation] ${label} returned HTTP ${response.status}.`);
|
|
173
|
+
if (response.url && canonicalEntryUrl(response.url).href !== requestedUrl.href) throw new BackendFederationRemoteEntryError('redirect_mismatch', `[Module Federation] ${label} redirected outside its trusted URL.`, {
|
|
174
|
+
details: {
|
|
175
|
+
expected: redactBackendFederationUrl(requestedUrl.href),
|
|
176
|
+
received: redactBackendFederationUrl(response.url)
|
|
177
|
+
}
|
|
178
|
+
});
|
|
199
179
|
const contentLength = parseContentLength(response.headers?.get('content-length') ?? null);
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
throw new BackendFederationRemoteEntryError('entry_too_large', `[Module Federation] Backend federation ${resourceKind} declares ${contentLength} bytes, exceeding its ${maxBytes}-byte policy limit.`);
|
|
204
|
-
}
|
|
180
|
+
const byteLimit = exactByteLength ?? maxBytes;
|
|
181
|
+
if (void 0 !== contentLength && contentLength > maxBytes) throw new BackendFederationRemoteEntryError('entry_too_large', `[Module Federation] ${label} declares ${contentLength} bytes, exceeding its ${maxBytes}-byte policy limit.`);
|
|
182
|
+
const exactBytes = void 0 === exactByteLength ? void 0 : new Uint8Array(exactByteLength);
|
|
205
183
|
const chunks = [];
|
|
206
184
|
let byteLength = 0;
|
|
185
|
+
const append = (chunk)=>{
|
|
186
|
+
if (byteLength + chunk.byteLength > byteLimit) throw new BackendFederationRemoteEntryError('entry_too_large', `[Module Federation] ${label} exceeded its ${byteLimit}-byte limit while streaming.`);
|
|
187
|
+
if (exactBytes) exactBytes.set(chunk, byteLength);
|
|
188
|
+
else chunks.push(chunk);
|
|
189
|
+
byteLength += chunk.byteLength;
|
|
190
|
+
};
|
|
207
191
|
if (response.body) {
|
|
208
192
|
reader = response.body.getReader();
|
|
209
193
|
while(true){
|
|
210
194
|
const result = await readWithAbort(reader.read(), controller.signal);
|
|
211
195
|
if (result.done) break;
|
|
212
|
-
|
|
213
|
-
if (byteLength > maxBytes) throw new BackendFederationRemoteEntryError('entry_too_large', `[Module Federation] Backend federation ${resourceKind} exceeded its ${maxBytes}-byte limit while streaming.`);
|
|
214
|
-
chunks.push(result.value);
|
|
196
|
+
append(result.value);
|
|
215
197
|
}
|
|
216
|
-
} else if (response.text)
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
198
|
+
} else if (void 0 === exactByteLength && response.text) append(new TextEncoder().encode(await readWithAbort(response.text(), controller.signal)));
|
|
199
|
+
if (void 0 !== exactByteLength && byteLength !== exactByteLength) throw new BackendFederationRemoteEntryError('byte_length_mismatch', `[Module Federation] ${label} byte length mismatch.`, {
|
|
200
|
+
details: {
|
|
201
|
+
expected: exactByteLength,
|
|
202
|
+
received: byteLength
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
const bytes = exactBytes ?? new Uint8Array(byteLength);
|
|
223
206
|
let offset = 0;
|
|
224
207
|
for (const chunk of chunks){
|
|
225
208
|
bytes.set(chunk, offset);
|
|
226
209
|
offset += chunk.byteLength;
|
|
227
210
|
}
|
|
228
|
-
if (controller.signal.aborted) throw
|
|
211
|
+
if (controller.signal.aborted) throw controller.signal.reason;
|
|
212
|
+
if (policy.verify) await readWithAbort(policy.verify(bytes, controller.signal), controller.signal);
|
|
229
213
|
return bytes;
|
|
230
214
|
} catch (cause) {
|
|
231
|
-
|
|
232
|
-
|
|
215
|
+
const cancelled = controller.signal.aborted;
|
|
216
|
+
controller.abort(cause);
|
|
217
|
+
if (reader) reader.cancel(cause).catch(()=>void 0);
|
|
218
|
+
else if (response?.body) response.body.cancel(cause).catch(()=>void 0);
|
|
219
|
+
if (cancelled) throw new BackendFederationRemoteEntryError(timedOut ? 'timeout' : 'aborted', timedOut ? `[Module Federation] ${label} timed out after ${timeoutMs}ms.` : `[Module Federation] ${label} loading was aborted.`, {
|
|
220
|
+
cause
|
|
221
|
+
});
|
|
233
222
|
if (cause instanceof BackendFederationRemoteEntryError) throw cause;
|
|
234
|
-
|
|
235
|
-
throw new BackendFederationRemoteEntryError('fetch_failed', `[Module Federation] Backend federation ${resourceKind} loading failed.`, {
|
|
223
|
+
throw new BackendFederationRemoteEntryError('fetch_failed', `[Module Federation] ${label} loading failed.`, {
|
|
236
224
|
cause
|
|
237
225
|
});
|
|
238
226
|
} finally{
|
|
@@ -240,6 +228,14 @@ async function loadBoundedBackendFederationResource(resourceUrl, options = {}) {
|
|
|
240
228
|
options.signal?.removeEventListener('abort', onCallerAbort);
|
|
241
229
|
}
|
|
242
230
|
}
|
|
231
|
+
async function loadBoundedBackendFederationResource(resourceUrl, options = {}) {
|
|
232
|
+
const requestedUrl = canonicalEntryUrl(resourceUrl);
|
|
233
|
+
assertAllowedEntryUrl(requestedUrl, true === options.allowInsecureHttp);
|
|
234
|
+
return acquireBackendFederationResource(requestedUrl, options, {
|
|
235
|
+
label: `Backend federation ${options.kind ?? 'manifest'}`,
|
|
236
|
+
maxBytes: options.maxBytes ?? DEFAULT_MAX_RESOURCE_BYTES
|
|
237
|
+
});
|
|
238
|
+
}
|
|
243
239
|
const evaluateBackendFederationCommonJsEntry = (remote, bytes, evaluator)=>{
|
|
244
240
|
let source;
|
|
245
241
|
try {
|
|
@@ -263,99 +259,24 @@ const evaluateBackendFederationCommonJsEntry = (remote, bytes, evaluator)=>{
|
|
|
263
259
|
async function loadVerifiedBackendFederationEntry(options) {
|
|
264
260
|
const verification = resolveTrustedVerification(options.verification, options.expected ?? {});
|
|
265
261
|
const requestedUrl = assertVerification(options.remote, verification, options.expected ?? {}, true === options.allowInsecureHttp);
|
|
266
|
-
const
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
const onCallerAbort = ()=>{
|
|
275
|
-
callerAborted = true;
|
|
276
|
-
controller.abort(options.signal?.reason);
|
|
277
|
-
};
|
|
278
|
-
if (options.signal?.aborted) onCallerAbort();
|
|
279
|
-
else options.signal?.addEventListener('abort', onCallerAbort, {
|
|
280
|
-
once: true
|
|
281
|
-
});
|
|
282
|
-
const timeout = timeoutMs > 0 ? setTimeout(()=>{
|
|
283
|
-
timedOut = true;
|
|
284
|
-
controller.abort(new Error(`Backend remote entry timed out after ${timeoutMs}ms`));
|
|
285
|
-
}, timeoutMs) : void 0;
|
|
286
|
-
const fetchEntry = options.fetch ?? globalThis.fetch;
|
|
287
|
-
let reader;
|
|
288
|
-
const cancellationError = (cause)=>new BackendFederationRemoteEntryError(timedOut ? 'timeout' : 'aborted', timedOut ? `[Module Federation] Backend remote ${options.remote.name} timed out after ${timeoutMs}ms.` : `[Module Federation] Backend remote ${options.remote.name} loading was aborted.`, {
|
|
289
|
-
cause
|
|
290
|
-
});
|
|
291
|
-
try {
|
|
292
|
-
if (controller.signal.aborted) throw cancellationError(controller.signal.reason);
|
|
293
|
-
if ('function' != typeof fetchEntry) throw new BackendFederationRemoteEntryError('fetch_failed', '[Module Federation] Backend remote entry loading requires fetch.');
|
|
294
|
-
let response;
|
|
295
|
-
try {
|
|
296
|
-
response = await readWithAbort(fetchEntry(requestedUrl.href, {
|
|
297
|
-
cache: 'no-store',
|
|
298
|
-
redirect: 'error',
|
|
299
|
-
signal: controller.signal
|
|
300
|
-
}), controller.signal);
|
|
301
|
-
} catch (cause) {
|
|
302
|
-
if (controller.signal.aborted) throw cancellationError(cause);
|
|
303
|
-
throw new BackendFederationRemoteEntryError('fetch_failed', `[Module Federation] Failed to fetch backend remote ${options.remote.name}.`, {
|
|
304
|
-
cause
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
if (!response.ok) throw new BackendFederationRemoteEntryError('fetch_failed', `[Module Federation] Backend remote ${options.remote.name} returned HTTP ${response.status}.`);
|
|
308
|
-
if (response.url) {
|
|
309
|
-
const responseUrl = canonicalEntryUrl(response.url);
|
|
310
|
-
if (responseUrl.href !== requestedUrl.href) throw new BackendFederationRemoteEntryError('redirect_mismatch', `[Module Federation] Backend remote ${options.remote.name} redirected outside its verified entry URL.`, {
|
|
262
|
+
const bytes = await acquireBackendFederationResource(requestedUrl, options, {
|
|
263
|
+
label: `Backend remote ${options.remote.name}`,
|
|
264
|
+
maxBytes: options.maxBytes ?? DEFAULT_MAX_ENTRY_BYTES,
|
|
265
|
+
exactByteLength: verification.byteLength,
|
|
266
|
+
async verify (bytes, signal) {
|
|
267
|
+
const actualDigest = await sha256Hex(bytes, signal);
|
|
268
|
+
if (signal.aborted) throw signal.reason;
|
|
269
|
+
if (actualDigest !== verification.sha256) throw new BackendFederationRemoteEntryError('integrity_mismatch', `[Module Federation] Backend remote ${options.remote.name} SHA-256 mismatch.`, {
|
|
311
270
|
details: {
|
|
312
|
-
expected:
|
|
313
|
-
received:
|
|
271
|
+
expected: verification.sha256,
|
|
272
|
+
received: actualDigest
|
|
314
273
|
}
|
|
315
274
|
});
|
|
316
275
|
}
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
throw new BackendFederationRemoteEntryError('entry_too_large', `[Module Federation] Backend remote ${options.remote.name} declares ${contentLength} bytes, exceeding its ${maxBytes}-byte policy limit.`);
|
|
323
|
-
}
|
|
324
|
-
reader = response.body?.getReader();
|
|
325
|
-
const bytes = new Uint8Array(verification.byteLength);
|
|
326
|
-
let byteLength = 0;
|
|
327
|
-
if (reader) while(true){
|
|
328
|
-
const result = await readWithAbort(reader.read(), controller.signal);
|
|
329
|
-
if (result.done) break;
|
|
330
|
-
const nextByteLength = byteLength + result.value.byteLength;
|
|
331
|
-
if (nextByteLength > byteLimit) throw new BackendFederationRemoteEntryError('entry_too_large', `[Module Federation] Backend remote ${options.remote.name} exceeded its ${byteLimit}-byte limit while streaming.`);
|
|
332
|
-
bytes.set(result.value, byteLength);
|
|
333
|
-
byteLength = nextByteLength;
|
|
334
|
-
}
|
|
335
|
-
if (byteLength !== verification.byteLength) throw new BackendFederationRemoteEntryError('byte_length_mismatch', `[Module Federation] Backend remote ${options.remote.name} byte length mismatch.`, {
|
|
336
|
-
details: {
|
|
337
|
-
expected: verification.byteLength,
|
|
338
|
-
received: byteLength
|
|
339
|
-
}
|
|
340
|
-
});
|
|
341
|
-
const actualDigest = await sha256Hex(bytes, controller.signal);
|
|
342
|
-
if (controller.signal.aborted) throw cancellationError(controller.signal.reason);
|
|
343
|
-
if (actualDigest !== verification.sha256) throw new BackendFederationRemoteEntryError('integrity_mismatch', `[Module Federation] Backend remote ${options.remote.name} SHA-256 mismatch.`, {
|
|
344
|
-
details: {
|
|
345
|
-
expected: verification.sha256,
|
|
346
|
-
received: actualDigest
|
|
347
|
-
}
|
|
348
|
-
});
|
|
349
|
-
return evaluateBackendFederationCommonJsEntry(options.remote, bytes, options.evaluateCommonJs);
|
|
350
|
-
} catch (cause) {
|
|
351
|
-
if (!controller.signal.aborted) controller.abort(cause);
|
|
352
|
-
await reader?.cancel(cause).catch(()=>void 0);
|
|
353
|
-
if (cause instanceof BackendFederationRemoteEntryError && !('aborted' === cause.code && timedOut)) throw cause;
|
|
354
|
-
if (controller.signal.aborted && (timedOut || callerAborted)) throw cancellationError(cause);
|
|
355
|
-
throw cause;
|
|
356
|
-
} finally{
|
|
357
|
-
if (timeout) clearTimeout(timeout);
|
|
358
|
-
options.signal?.removeEventListener('abort', onCallerAbort);
|
|
359
|
-
}
|
|
276
|
+
});
|
|
277
|
+
if (options.signal?.aborted) throw new BackendFederationRemoteEntryError('aborted', `[Module Federation] Backend remote ${options.remote.name} loading was aborted.`, {
|
|
278
|
+
cause: options.signal.reason
|
|
279
|
+
});
|
|
280
|
+
return evaluateBackendFederationCommonJsEntry(options.remote, bytes, options.evaluateCommonJs);
|
|
360
281
|
}
|
|
361
282
|
export { BackendFederationRemoteEntryError, evaluateBackendFederationCommonJsEntry, loadBoundedBackendFederationResource, loadVerifiedBackendFederationEntry, redactBackendFederationUrl, resolveBackendFederationRemoteEntryVerification };
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
const BFF_ENVELOPE_HEADER = 'x-modernjs-bff-envelope';
|
|
2
|
+
const BFF_OPERATION_CONTEXT_HEADER = 'x-operation-id';
|
|
3
|
+
const BFF_OPERATION_CONTEXT_DETAIL_HEADER = 'x-modernjs-bff-operation-context';
|
|
4
|
+
const DEFAULT_DENY_STATUS = 403;
|
|
5
|
+
const NAMESPACE_ALLOWLIST_REQUIRES_VERIFIER_MESSAGE = 'cross-project namespace allowlist requires verifyProducerIdentity';
|
|
6
|
+
const splitRoutePath = (routePath)=>routePath.split('/').filter(Boolean);
|
|
7
|
+
const isDynamicRouteSegment = (segment)=>segment.startsWith(':') || '*' === segment || segment.startsWith('*') || segment.startsWith('{*');
|
|
8
|
+
const hasTrailingSlash = (routePath)=>routePath.length > 1 && routePath.endsWith('/');
|
|
9
|
+
const hasUnsafePathEncoding = (requestPath)=>{
|
|
10
|
+
let decoded = requestPath;
|
|
11
|
+
for(let depth = 0; depth < 8; depth += 1){
|
|
12
|
+
if (/%(?:2f|5c)/i.test(decoded)) return true;
|
|
13
|
+
try {
|
|
14
|
+
const next = decodeURIComponent(decoded);
|
|
15
|
+
if (next === decoded) return false;
|
|
16
|
+
decoded = next;
|
|
17
|
+
} catch {
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return decoded.includes('%');
|
|
22
|
+
};
|
|
23
|
+
const routeSegmentsMatch = (templateSegments, requestSegments)=>{
|
|
24
|
+
let templateIndex = 0;
|
|
25
|
+
let requestIndex = 0;
|
|
26
|
+
while(templateIndex < templateSegments.length){
|
|
27
|
+
const segment = templateSegments[templateIndex];
|
|
28
|
+
const wildcard = '*' === segment || segment.startsWith('*') || segment.startsWith('{*');
|
|
29
|
+
const optional = segment.startsWith(':') && segment.endsWith('?');
|
|
30
|
+
if (templateIndex < templateSegments.length - 1 && (wildcard || optional)) return false;
|
|
31
|
+
if (wildcard) return true;
|
|
32
|
+
const requestSegment = requestSegments[requestIndex];
|
|
33
|
+
if (void 0 === requestSegment) return optional && templateIndex === templateSegments.length - 1;
|
|
34
|
+
if (!segment.startsWith(':') && segment !== requestSegment) return false;
|
|
35
|
+
templateIndex += 1;
|
|
36
|
+
requestIndex += 1;
|
|
37
|
+
}
|
|
38
|
+
return requestIndex === requestSegments.length;
|
|
39
|
+
};
|
|
40
|
+
const routeTemplateMatchScore = (routePath, requestPath)=>{
|
|
41
|
+
if (hasTrailingSlash(routePath) !== hasTrailingSlash(requestPath)) return;
|
|
42
|
+
const templateSegments = splitRoutePath(routePath);
|
|
43
|
+
const requestSegments = splitRoutePath(requestPath);
|
|
44
|
+
for(let prefixLength = 0; prefixLength <= templateSegments.length; prefixLength += 1){
|
|
45
|
+
const removedPrefix = templateSegments.slice(0, prefixLength);
|
|
46
|
+
if (removedPrefix.some(isDynamicRouteSegment)) break;
|
|
47
|
+
const mountedTemplate = templateSegments.slice(prefixLength);
|
|
48
|
+
if (!routeSegmentsMatch(mountedTemplate, requestSegments)) continue;
|
|
49
|
+
const literalSegments = mountedTemplate.filter((segment)=>!isDynamicRouteSegment(segment)).length;
|
|
50
|
+
const dynamicSegments = mountedTemplate.length - literalSegments;
|
|
51
|
+
return (0 === prefixLength ? 1000000 : 0) + 10000 * literalSegments - 100 * dynamicSegments - prefixLength;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
const resolveCrossProjectRequestObservation = (request, policy)=>{
|
|
55
|
+
const requestMethod = String(request.method || '').trim().toUpperCase();
|
|
56
|
+
const routePaths = [
|
|
57
|
+
...new Set(Object.keys(policy.expectedOperationContracts ?? {}).flatMap((key)=>{
|
|
58
|
+
if (key.startsWith('operation:')) return [];
|
|
59
|
+
const separator = key.indexOf(':');
|
|
60
|
+
if (-1 === separator || key.slice(0, separator).trim().toUpperCase() !== requestMethod) return [];
|
|
61
|
+
return [
|
|
62
|
+
key.slice(separator + 1)
|
|
63
|
+
];
|
|
64
|
+
}))
|
|
65
|
+
];
|
|
66
|
+
if (0 === routePaths.length) return;
|
|
67
|
+
if (hasUnsafePathEncoding(request.pathname)) return {
|
|
68
|
+
method: request.method,
|
|
69
|
+
routePath: request.pathname
|
|
70
|
+
};
|
|
71
|
+
const matches = routePaths.flatMap((routePath)=>{
|
|
72
|
+
const score = routeTemplateMatchScore(routePath, request.pathname);
|
|
73
|
+
return void 0 === score ? [] : [
|
|
74
|
+
{
|
|
75
|
+
routePath,
|
|
76
|
+
score
|
|
77
|
+
}
|
|
78
|
+
];
|
|
79
|
+
});
|
|
80
|
+
if (0 === matches.length) return {
|
|
81
|
+
method: request.method,
|
|
82
|
+
routePath: request.pathname
|
|
83
|
+
};
|
|
84
|
+
matches.sort((left, right)=>right.score - left.score);
|
|
85
|
+
return {
|
|
86
|
+
method: request.method,
|
|
87
|
+
routePath: matches[1]?.score === matches[0]?.score ? request.pathname : matches[0].routePath
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
const normalizeHeaderName = (headerName, fallback)=>(headerName || fallback).trim().toLowerCase();
|
|
91
|
+
const normalizeStatusCode = (statusCode)=>{
|
|
92
|
+
if ('number' == typeof statusCode && Number.isFinite(statusCode) && statusCode >= 400 && statusCode <= 599) return Math.floor(statusCode);
|
|
93
|
+
return DEFAULT_DENY_STATUS;
|
|
94
|
+
};
|
|
95
|
+
const readHeader = (headers, headerName)=>{
|
|
96
|
+
const lowerHeaderName = headerName.toLowerCase();
|
|
97
|
+
for (const [name, value] of Object.entries(headers || {}))if (name.toLowerCase() === lowerHeaderName) {
|
|
98
|
+
if (Array.isArray(value)) return value.length > 0 ? String(value[0]) : void 0;
|
|
99
|
+
if (null == value) return;
|
|
100
|
+
return String(value);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
const extractNamespace = (requestId)=>requestId.split(/[/:.]/)[0]?.trim().toLowerCase();
|
|
104
|
+
const createViolation = (reason, message, status)=>({
|
|
105
|
+
code: 'BFF_CROSS_PROJECT_POLICY_DENIED',
|
|
106
|
+
reason,
|
|
107
|
+
message,
|
|
108
|
+
status
|
|
109
|
+
});
|
|
110
|
+
const createCrossProjectPolicyEvaluationState = (headers, policy, observedRequest)=>({
|
|
111
|
+
headers,
|
|
112
|
+
policy,
|
|
113
|
+
status: normalizeStatusCode(policy.denyStatus),
|
|
114
|
+
requireEnvelope: policy.requireEnvelope ?? true,
|
|
115
|
+
requireOperationContext: policy.requireOperationContext ?? true,
|
|
116
|
+
requireOperationContextDetails: policy.requireOperationContextDetails ?? true,
|
|
117
|
+
requireOperationSchemaHash: policy.requireOperationSchemaHash ?? true,
|
|
118
|
+
requireOperationVersion: policy.requireOperationVersion ?? true,
|
|
119
|
+
allowUnknownOperations: policy.allowUnknownOperations ?? false,
|
|
120
|
+
verifyProducerIdentity: 'function' == typeof policy.verifyProducerIdentity ? policy.verifyProducerIdentity : void 0,
|
|
121
|
+
allowedNamespaces: (policy.allowedNamespaces || []).map((item)=>item.trim().toLowerCase()).filter(Boolean),
|
|
122
|
+
envelopeHeader: normalizeHeaderName(policy.envelopeHeader, BFF_ENVELOPE_HEADER),
|
|
123
|
+
operationContextHeader: normalizeHeaderName(policy.operationContextHeader, BFF_OPERATION_CONTEXT_HEADER),
|
|
124
|
+
operationContextDetailHeader: normalizeHeaderName(policy.operationContextDetailHeader, BFF_OPERATION_CONTEXT_DETAIL_HEADER),
|
|
125
|
+
requestId: '',
|
|
126
|
+
detailSchemaHash: '',
|
|
127
|
+
detailOperationVersion: void 0,
|
|
128
|
+
observedRequest: observedRequest ? {
|
|
129
|
+
method: String(observedRequest.method || '').trim().toUpperCase(),
|
|
130
|
+
routePath: String(observedRequest.routePath || '').trim()
|
|
131
|
+
} : void 0,
|
|
132
|
+
complete: false
|
|
133
|
+
});
|
|
134
|
+
const checkNamespaceAllowlistVerifier = (state)=>{
|
|
135
|
+
if (state.allowedNamespaces.length > 0 && void 0 === state.verifyProducerIdentity) return createViolation('producer_identity_mismatch', NAMESPACE_ALLOWLIST_REQUIRES_VERIFIER_MESSAGE, state.status);
|
|
136
|
+
};
|
|
137
|
+
const checkEnvelopeHeader = (state)=>{
|
|
138
|
+
const envelopeRaw = readHeader(state.headers, state.envelopeHeader);
|
|
139
|
+
if (!envelopeRaw) {
|
|
140
|
+
if (!state.requireEnvelope) {
|
|
141
|
+
state.complete = true;
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
return createViolation('missing_envelope', `Missing cross-project envelope header "${state.envelopeHeader}"`, state.status);
|
|
145
|
+
}
|
|
146
|
+
let envelope;
|
|
147
|
+
try {
|
|
148
|
+
const parsed = JSON.parse(envelopeRaw);
|
|
149
|
+
if (!parsed || 'object' != typeof parsed) throw new Error('invalid envelope object');
|
|
150
|
+
envelope = parsed;
|
|
151
|
+
} catch (_error) {
|
|
152
|
+
return createViolation('invalid_envelope', `Invalid cross-project envelope header "${state.envelopeHeader}"`, state.status);
|
|
153
|
+
}
|
|
154
|
+
const requestId = String(envelope.requestId || '').trim();
|
|
155
|
+
if (!requestId) return createViolation('missing_request_id', 'Cross-project envelope does not include a valid requestId', state.status);
|
|
156
|
+
state.requestId = requestId;
|
|
157
|
+
state.claimedNamespace = extractNamespace(requestId);
|
|
158
|
+
state.effectiveNamespace = state.claimedNamespace;
|
|
159
|
+
};
|
|
160
|
+
const checkProducerIdentity = (state)=>{
|
|
161
|
+
if (!state.verifyProducerIdentity) return;
|
|
162
|
+
const verifiedNamespaceRaw = state.verifyProducerIdentity(state.headers);
|
|
163
|
+
const verifiedNamespace = 'string' == typeof verifiedNamespaceRaw ? verifiedNamespaceRaw.trim().toLowerCase() : void 0;
|
|
164
|
+
if (!verifiedNamespace) return createViolation('producer_identity_mismatch', 'Producer identity could not be verified for request', state.status);
|
|
165
|
+
if (verifiedNamespace !== state.claimedNamespace) return createViolation('producer_identity_mismatch', `Envelope namespace "${state.claimedNamespace || 'unknown'}" does not match verified producer identity "${verifiedNamespace}"`, state.status);
|
|
166
|
+
state.effectiveNamespace = verifiedNamespace;
|
|
167
|
+
};
|
|
168
|
+
const checkNamespaceAllowlist = (state)=>{
|
|
169
|
+
if (state.allowedNamespaces.length > 0) {
|
|
170
|
+
if (!state.effectiveNamespace || !state.allowedNamespaces.includes(state.effectiveNamespace)) return createViolation('namespace_not_allowed', `Producer namespace "${state.effectiveNamespace || 'unknown'}" not allowed`, state.status);
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
const checkOperationContext = (state)=>{
|
|
174
|
+
if (!state.requireOperationContext) {
|
|
175
|
+
state.complete = true;
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const operationContext = readHeader(state.headers, state.operationContextHeader);
|
|
179
|
+
if (!operationContext) return createViolation('missing_operation_context', `Missing operation context header "${state.operationContextHeader}"`, state.status);
|
|
180
|
+
if (!operationContext.startsWith(`${state.requestId}:`)) return createViolation('operation_context_mismatch', `Operation context header "${state.operationContextHeader}" does not match requestId "${state.requestId}"`, state.status);
|
|
181
|
+
state.operationContext = operationContext;
|
|
182
|
+
};
|
|
183
|
+
const checkOperationContextDetails = (state)=>{
|
|
184
|
+
const operationContextDetailsRaw = readHeader(state.headers, state.operationContextDetailHeader);
|
|
185
|
+
if (!operationContextDetailsRaw) {
|
|
186
|
+
if (state.requireOperationContextDetails) return createViolation('missing_operation_context_details', `Missing operation context details header "${state.operationContextDetailHeader}"`, state.status);
|
|
187
|
+
state.complete = true;
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
let operationContextDetails;
|
|
191
|
+
try {
|
|
192
|
+
const parsed = JSON.parse(operationContextDetailsRaw);
|
|
193
|
+
if (!parsed || 'object' != typeof parsed || Array.isArray(parsed)) throw new Error('invalid operation context details object');
|
|
194
|
+
operationContextDetails = parsed;
|
|
195
|
+
} catch (_error) {
|
|
196
|
+
return createViolation('invalid_operation_context_details', `Invalid operation context details header "${state.operationContextDetailHeader}"`, state.status);
|
|
197
|
+
}
|
|
198
|
+
const detailRequestId = String(operationContextDetails.requestId || '').trim();
|
|
199
|
+
if (detailRequestId && detailRequestId !== state.requestId) return createViolation('operation_context_details_request_id_mismatch', `Operation context details requestId "${detailRequestId}" does not match envelope requestId "${state.requestId}"`, state.status);
|
|
200
|
+
const detailOperationId = String(operationContextDetails.operationId || '').trim();
|
|
201
|
+
if (state.operationContext && detailOperationId && detailOperationId !== state.operationContext) return createViolation('operation_context_mismatch', `Operation context details operationId "${detailOperationId}" does not match operation context "${state.operationContext}"`, state.status);
|
|
202
|
+
state.operationContextDetails = operationContextDetails;
|
|
203
|
+
state.detailSchemaHash = String(operationContextDetails.schemaHash || '').trim();
|
|
204
|
+
if (state.requireOperationSchemaHash && !state.detailSchemaHash) return createViolation('missing_operation_schema_hash', `Operation context details header "${state.operationContextDetailHeader}" must include schemaHash`, state.status);
|
|
205
|
+
state.detailOperationVersion = operationContextDetails.operationVersion;
|
|
206
|
+
if (state.requireOperationVersion && 'number' != typeof state.detailOperationVersion) return createViolation('missing_operation_version', `Operation context details header "${state.operationContextDetailHeader}" must include operationVersion`, state.status);
|
|
207
|
+
};
|
|
208
|
+
const checkOperationContract = (state)=>{
|
|
209
|
+
if (!state.operationContextDetails) return;
|
|
210
|
+
const expectedContracts = state.policy.expectedOperationContracts;
|
|
211
|
+
if (expectedContracts && 'object' == typeof expectedContracts) {
|
|
212
|
+
const method = String(state.operationContextDetails.method || '').toUpperCase();
|
|
213
|
+
const routePath = String(state.operationContextDetails.routePath || '').trim();
|
|
214
|
+
const operationId = String(state.operationContextDetails.operationId || '').trim();
|
|
215
|
+
const observedMethod = state.observedRequest?.method;
|
|
216
|
+
const observedRoutePath = state.observedRequest?.routePath;
|
|
217
|
+
if (observedMethod && observedRoutePath && (method !== observedMethod || routePath !== observedRoutePath)) return createViolation('operation_context_mismatch', `Client operation "${operationId || `${method}:${routePath}`}" does not match observed request "${observedMethod}:${observedRoutePath}"`, state.status);
|
|
218
|
+
const contractMethod = observedMethod || method;
|
|
219
|
+
const contractRoutePath = observedRoutePath || routePath;
|
|
220
|
+
const expectedContract = expectedContracts[`${contractMethod}:${contractRoutePath}`] || (state.observedRequest ? void 0 : expectedContracts[`operation:${operationId}`]);
|
|
221
|
+
if (expectedContract) {
|
|
222
|
+
const assertedOperationId = operationId || state.operationContext || '';
|
|
223
|
+
const canonicalRouteOperationId = `${state.requestId}:${contractMethod}:${contractRoutePath}`;
|
|
224
|
+
if (state.observedRequest && assertedOperationId !== expectedContract.operationId && assertedOperationId !== canonicalRouteOperationId) return createViolation('operation_context_mismatch', `Client operation "${assertedOperationId}" does not identify observed contract "${expectedContract.operationId || canonicalRouteOperationId}"`, state.status);
|
|
225
|
+
if (expectedContract.schemaHash && state.detailSchemaHash && expectedContract.schemaHash !== state.detailSchemaHash) return createViolation('operation_schema_hash_mismatch', `Operation schema hash mismatch for "${operationId || `${method}:${routePath}`}"`, state.status);
|
|
226
|
+
if ('number' == typeof expectedContract.operationVersion && 'number' == typeof state.detailOperationVersion && expectedContract.operationVersion !== state.detailOperationVersion) return createViolation('operation_version_mismatch', `Operation version mismatch for "${operationId || `${method}:${routePath}`}"`, state.status);
|
|
227
|
+
} else if (!state.allowUnknownOperations) return createViolation('unknown_operation_contract', `No expected operation contract found for operation "${operationId || `${method}:${routePath}`}"`, state.status);
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
const CROSS_PROJECT_POLICY_CHECKS = [
|
|
231
|
+
checkNamespaceAllowlistVerifier,
|
|
232
|
+
checkEnvelopeHeader,
|
|
233
|
+
checkProducerIdentity,
|
|
234
|
+
checkNamespaceAllowlist,
|
|
235
|
+
checkOperationContext,
|
|
236
|
+
checkOperationContextDetails,
|
|
237
|
+
checkOperationContract
|
|
238
|
+
];
|
|
239
|
+
const evaluateCrossProjectPolicy = (headers, policy, observedRequest)=>{
|
|
240
|
+
if (!policy?.enabled) return null;
|
|
241
|
+
const state = createCrossProjectPolicyEvaluationState(headers, policy, observedRequest);
|
|
242
|
+
for (const check of CROSS_PROJECT_POLICY_CHECKS){
|
|
243
|
+
const violation = check(state);
|
|
244
|
+
if (violation) return violation;
|
|
245
|
+
if (state.complete) break;
|
|
246
|
+
}
|
|
247
|
+
return null;
|
|
248
|
+
};
|
|
249
|
+
export { BFF_ENVELOPE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER, evaluateCrossProjectPolicy, resolveCrossProjectRequestObservation };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const DEFAULT_OPERATION_VERSION = 1;
|
|
2
|
+
const deriveOperationVersion = (packageVersion)=>{
|
|
3
|
+
if ('string' != typeof packageVersion) return DEFAULT_OPERATION_VERSION;
|
|
4
|
+
const match = packageVersion.trim().match(/^v?(\d+)\./);
|
|
5
|
+
if (!match) return DEFAULT_OPERATION_VERSION;
|
|
6
|
+
const major = Number.parseInt(match[1], 10);
|
|
7
|
+
return Number.isInteger(major) && major >= 0 ? major : DEFAULT_OPERATION_VERSION;
|
|
8
|
+
};
|
|
9
|
+
const stableOperationStringify = (value)=>{
|
|
10
|
+
if (Array.isArray(value)) return `[${value.map((item)=>stableOperationStringify(item)).join(',')}]`;
|
|
11
|
+
if (value && 'object' == typeof value) {
|
|
12
|
+
const entries = Object.entries(value).filter(([, entryValue])=>void 0 !== entryValue).sort(([a], [b])=>a.localeCompare(b)).map(([key, entryValue])=>`${JSON.stringify(key)}:${stableOperationStringify(entryValue)}`);
|
|
13
|
+
return `{${entries.join(',')}}`;
|
|
14
|
+
}
|
|
15
|
+
return JSON.stringify(value) ?? 'null';
|
|
16
|
+
};
|
|
17
|
+
const serializeOperationContract = (operation, requestId)=>stableOperationStringify({
|
|
18
|
+
httpMethod: String(operation.httpMethod || '').toUpperCase(),
|
|
19
|
+
name: operation.name,
|
|
20
|
+
requestId,
|
|
21
|
+
routePath: operation.routePath,
|
|
22
|
+
...operation.schemas ? {
|
|
23
|
+
schemas: operation.schemas
|
|
24
|
+
} : {}
|
|
25
|
+
});
|
|
26
|
+
async function digestOperationContract(operation, requestId) {
|
|
27
|
+
const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(serializeOperationContract(operation, requestId)));
|
|
28
|
+
return Array.from(new Uint8Array(digest), (value)=>value.toString(16).padStart(2, '0')).join('');
|
|
29
|
+
}
|
|
30
|
+
export { DEFAULT_OPERATION_VERSION, deriveOperationVersion, digestOperationContract, serializeOperationContract, stableOperationStringify };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import node_path from "node:path";
|
|
3
|
+
import { deriveOperationVersion } from "./operationIdentity.mjs";
|
|
4
|
+
function resolveOperationProducer(options) {
|
|
5
|
+
for (const directory of options.directories){
|
|
6
|
+
if (!directory) continue;
|
|
7
|
+
let current = node_path.resolve(directory);
|
|
8
|
+
while(true){
|
|
9
|
+
const filename = node_path.join(current, 'package.json');
|
|
10
|
+
if (existsSync(filename)) {
|
|
11
|
+
options.onDependency?.(filename);
|
|
12
|
+
let metadata = {};
|
|
13
|
+
try {
|
|
14
|
+
metadata = JSON.parse(readFileSync(filename, 'utf8')) ?? {};
|
|
15
|
+
} catch {}
|
|
16
|
+
return {
|
|
17
|
+
requestId: options.requestId?.trim() || 'string' == typeof metadata.name && metadata.name.trim() || 'default',
|
|
18
|
+
operationVersion: deriveOperationVersion(metadata.version)
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
const parent = node_path.dirname(current);
|
|
22
|
+
if (parent === current) break;
|
|
23
|
+
current = parent;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
requestId: options.requestId?.trim() || 'default',
|
|
28
|
+
operationVersion: deriveOperationVersion()
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export { resolveOperationProducer };
|
|
@@ -1,13 +1,6 @@
|
|
|
1
1
|
import { normalizeSnapshot } from "./resolve.mjs";
|
|
2
2
|
import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from "./types.mjs";
|
|
3
3
|
const DEFAULT_HTTP_STORE_TIMEOUT_MS = 5000;
|
|
4
|
-
const BUILTIN_HTTP_STATE_STORE_MODULES = new Set([
|
|
5
|
-
'http',
|
|
6
|
-
'@modern-js/server-core/http',
|
|
7
|
-
'@modern-js/server-core/contract-gate-http-store',
|
|
8
|
-
'@modern-js/server-runtime-extensions/http',
|
|
9
|
-
'@modern-js/server-runtime-extensions/contract-gate-http-store'
|
|
10
|
-
]);
|
|
11
4
|
const normalizeHttpStoreOptions = (options)=>{
|
|
12
5
|
const endpoint = 'string' == typeof options?.endpoint ? options.endpoint.trim() : '';
|
|
13
6
|
if (!endpoint) throw new Error('[telemetry.health.snapshot] HTTP stateStore requires options.endpoint');
|
|
@@ -86,7 +79,7 @@ const createHttpContractGateSnapshotStore = (options)=>{
|
|
|
86
79
|
};
|
|
87
80
|
const tryResolveBuiltinSnapshotStore = (input)=>{
|
|
88
81
|
const moduleName = input.stateStore.module.trim();
|
|
89
|
-
if (
|
|
82
|
+
if ('http' !== moduleName) return;
|
|
90
83
|
return createHttpContractGateSnapshotStore(input.stateStore.options || {});
|
|
91
84
|
};
|
|
92
85
|
export { createHttpContractGateSnapshotStore, tryResolveBuiltinSnapshotStore };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { createSafeJsonFailureResponse } from "@modern-js/runtime-extensions/safe-failure";
|
|
2
|
+
const injectErrorResponsePlugin = ()=>({
|
|
3
|
+
name: '@modern-js/safe-error-response',
|
|
4
|
+
setup (api) {
|
|
5
|
+
api.handleError(async (input, next)=>{
|
|
6
|
+
const prefix = api.getServerConfig().bff?.prefix || '/api';
|
|
7
|
+
const prefixes = Array.isArray(prefix) ? prefix : [
|
|
8
|
+
prefix
|
|
9
|
+
];
|
|
10
|
+
if (prefixes.some((value)=>input.context.req.path.startsWith(value))) return {
|
|
11
|
+
...input,
|
|
12
|
+
response: createSafeJsonFailureResponse(input.error)
|
|
13
|
+
};
|
|
14
|
+
next?.(input);
|
|
15
|
+
return input;
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
export { injectErrorResponsePlugin };
|