@bleedingdev/modern-js-bff-core 3.9.0-ultramodern.4 → 3.9.0-ultramodern.6

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 (49) hide show
  1. package/dist/cjs/client/generateClient.js +67 -138
  2. package/dist/cjs/index.js +25 -101
  3. package/dist/esm/client/generateClient.mjs +65 -139
  4. package/dist/esm/index.mjs +0 -4
  5. package/dist/esm-node/client/generateClient.mjs +65 -139
  6. package/dist/esm-node/index.mjs +0 -4
  7. package/dist/types/client/generateClient.d.ts +24 -1
  8. package/dist/types/index.d.ts +0 -4
  9. package/package.json +5 -12
  10. package/dist/cjs/adapter-kit/index.js +0 -144
  11. package/dist/cjs/adapter-kit/parity-scenarios/cross-project-denial.js +0 -55
  12. package/dist/cjs/adapter-kit/parity-scenarios/envelope.js +0 -128
  13. package/dist/cjs/adapter-kit/parity-scenarios/operation-context.js +0 -152
  14. package/dist/cjs/adapter-kit/parity-scenarios/schema.js +0 -109
  15. package/dist/cjs/adapter-kit/parity-scenarios/shared.js +0 -71
  16. package/dist/cjs/adapter-kit/parity.js +0 -204
  17. package/dist/cjs/security/crossProjectPolicy.js +0 -309
  18. package/dist/cjs/security/operationContracts.js +0 -183
  19. package/dist/cjs/security/resolveCrossProjectPolicy.js +0 -65
  20. package/dist/esm/adapter-kit/index.mjs +0 -79
  21. package/dist/esm/adapter-kit/parity-scenarios/cross-project-denial.mjs +0 -17
  22. package/dist/esm/adapter-kit/parity-scenarios/envelope.mjs +0 -90
  23. package/dist/esm/adapter-kit/parity-scenarios/operation-context.mjs +0 -111
  24. package/dist/esm/adapter-kit/parity-scenarios/schema.mjs +0 -71
  25. package/dist/esm/adapter-kit/parity-scenarios/shared.mjs +0 -21
  26. package/dist/esm/adapter-kit/parity.mjs +0 -148
  27. package/dist/esm/security/crossProjectPolicy.mjs +0 -259
  28. package/dist/esm/security/operationContracts.mjs +0 -127
  29. package/dist/esm/security/resolveCrossProjectPolicy.mjs +0 -27
  30. package/dist/esm-node/adapter-kit/index.mjs +0 -80
  31. package/dist/esm-node/adapter-kit/parity-scenarios/cross-project-denial.mjs +0 -18
  32. package/dist/esm-node/adapter-kit/parity-scenarios/envelope.mjs +0 -91
  33. package/dist/esm-node/adapter-kit/parity-scenarios/operation-context.mjs +0 -112
  34. package/dist/esm-node/adapter-kit/parity-scenarios/schema.mjs +0 -72
  35. package/dist/esm-node/adapter-kit/parity-scenarios/shared.mjs +0 -22
  36. package/dist/esm-node/adapter-kit/parity.mjs +0 -149
  37. package/dist/esm-node/security/crossProjectPolicy.mjs +0 -260
  38. package/dist/esm-node/security/operationContracts.mjs +0 -130
  39. package/dist/esm-node/security/resolveCrossProjectPolicy.mjs +0 -28
  40. package/dist/types/adapter-kit/index.d.ts +0 -90
  41. package/dist/types/adapter-kit/parity-scenarios/cross-project-denial.d.ts +0 -2
  42. package/dist/types/adapter-kit/parity-scenarios/envelope.d.ts +0 -2
  43. package/dist/types/adapter-kit/parity-scenarios/operation-context.d.ts +0 -3
  44. package/dist/types/adapter-kit/parity-scenarios/schema.d.ts +0 -2
  45. package/dist/types/adapter-kit/parity-scenarios/shared.d.ts +0 -32
  46. package/dist/types/adapter-kit/parity.d.ts +0 -43
  47. package/dist/types/security/crossProjectPolicy.d.ts +0 -110
  48. package/dist/types/security/operationContracts.d.ts +0 -84
  49. package/dist/types/security/resolveCrossProjectPolicy.d.ts +0 -39
@@ -1,309 +0,0 @@
1
- "use strict";
2
- var __webpack_require__ = {};
3
- (()=>{
4
- __webpack_require__.d = (exports1, getters, values)=>{
5
- var define = (defs, kind)=>{
6
- for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
- enumerable: true,
8
- [kind]: defs[key]
9
- });
10
- };
11
- define(getters, "get");
12
- define(values, "value");
13
- };
14
- })();
15
- (()=>{
16
- __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
- })();
18
- (()=>{
19
- __webpack_require__.r = (exports1)=>{
20
- if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
- value: 'Module'
22
- });
23
- Object.defineProperty(exports1, '__esModule', {
24
- value: true
25
- });
26
- };
27
- })();
28
- var __webpack_exports__ = {};
29
- __webpack_require__.r(__webpack_exports__);
30
- const BFF_ENVELOPE_HEADER = 'x-modernjs-bff-envelope';
31
- const BFF_OPERATION_CONTEXT_HEADER = 'x-operation-id';
32
- const BFF_OPERATION_CONTEXT_DETAIL_HEADER = 'x-modernjs-bff-operation-context';
33
- const DEFAULT_DENY_STATUS = 403;
34
- const NAMESPACE_ALLOWLIST_REQUIRES_VERIFIER_MESSAGE = 'cross-project namespace allowlist requires verifyProducerIdentity';
35
- let hasWarnedAdvisoryNamespaceAllowlist = false;
36
- const splitRoutePath = (routePath)=>routePath.split('/').filter(Boolean);
37
- const isDynamicRouteSegment = (segment)=>segment.startsWith(':') || '*' === segment || segment.startsWith('*') || segment.startsWith('{*');
38
- const hasTrailingSlash = (routePath)=>routePath.length > 1 && routePath.endsWith('/');
39
- const hasUnsafePathEncoding = (requestPath)=>{
40
- let decoded = requestPath;
41
- for(let depth = 0; depth < 8; depth += 1){
42
- if (/%(?:2f|5c)/i.test(decoded)) return true;
43
- try {
44
- const next = decodeURIComponent(decoded);
45
- if (next === decoded) return false;
46
- decoded = next;
47
- } catch {
48
- return true;
49
- }
50
- }
51
- return decoded.includes('%');
52
- };
53
- const routeSegmentsMatch = (templateSegments, requestSegments)=>{
54
- let templateIndex = 0;
55
- let requestIndex = 0;
56
- while(templateIndex < templateSegments.length){
57
- const segment = templateSegments[templateIndex];
58
- const wildcard = '*' === segment || segment.startsWith('*') || segment.startsWith('{*');
59
- const optional = segment.startsWith(':') && segment.endsWith('?');
60
- if (templateIndex < templateSegments.length - 1 && (wildcard || optional)) return false;
61
- if (wildcard) return true;
62
- const requestSegment = requestSegments[requestIndex];
63
- if (void 0 === requestSegment) return optional && templateIndex === templateSegments.length - 1;
64
- if (!segment.startsWith(':') && segment !== requestSegment) return false;
65
- templateIndex += 1;
66
- requestIndex += 1;
67
- }
68
- return requestIndex === requestSegments.length;
69
- };
70
- const routeTemplateMatchScore = (routePath, requestPath)=>{
71
- if (hasTrailingSlash(routePath) !== hasTrailingSlash(requestPath)) return;
72
- const templateSegments = splitRoutePath(routePath);
73
- const requestSegments = splitRoutePath(requestPath);
74
- for(let prefixLength = 0; prefixLength <= templateSegments.length; prefixLength += 1){
75
- const removedPrefix = templateSegments.slice(0, prefixLength);
76
- if (removedPrefix.some(isDynamicRouteSegment)) break;
77
- const mountedTemplate = templateSegments.slice(prefixLength);
78
- if (!routeSegmentsMatch(mountedTemplate, requestSegments)) continue;
79
- const literalSegments = mountedTemplate.filter((segment)=>!isDynamicRouteSegment(segment)).length;
80
- const dynamicSegments = mountedTemplate.length - literalSegments;
81
- return (0 === prefixLength ? 1000000 : 0) + 10000 * literalSegments - 100 * dynamicSegments - prefixLength;
82
- }
83
- };
84
- const resolveCrossProjectRequestObservation = (request, policy)=>{
85
- const requestMethod = String(request.method || '').trim().toUpperCase();
86
- const routePaths = [
87
- ...new Set(Object.keys(policy.expectedOperationContracts ?? {}).flatMap((key)=>{
88
- if (key.startsWith('operation:')) return [];
89
- const separator = key.indexOf(':');
90
- if (-1 === separator || key.slice(0, separator).trim().toUpperCase() !== requestMethod) return [];
91
- return [
92
- key.slice(separator + 1)
93
- ];
94
- }))
95
- ];
96
- if (0 === routePaths.length) return;
97
- if (hasUnsafePathEncoding(request.pathname)) return {
98
- method: request.method,
99
- routePath: request.pathname
100
- };
101
- const matches = routePaths.flatMap((routePath)=>{
102
- const score = routeTemplateMatchScore(routePath, request.pathname);
103
- return void 0 === score ? [] : [
104
- {
105
- routePath,
106
- score
107
- }
108
- ];
109
- });
110
- if (0 === matches.length) return {
111
- method: request.method,
112
- routePath: request.pathname
113
- };
114
- matches.sort((left, right)=>right.score - left.score);
115
- return {
116
- method: request.method,
117
- routePath: matches[1]?.score === matches[0]?.score ? request.pathname : matches[0].routePath
118
- };
119
- };
120
- const normalizeHeaderName = (headerName, fallback)=>(headerName || fallback).trim().toLowerCase();
121
- const normalizeStatusCode = (statusCode)=>{
122
- if ('number' == typeof statusCode && Number.isFinite(statusCode) && statusCode >= 400 && statusCode <= 599) return Math.floor(statusCode);
123
- return DEFAULT_DENY_STATUS;
124
- };
125
- const readHeader = (headers, headerName)=>{
126
- const lowerHeaderName = headerName.toLowerCase();
127
- for (const [name, value] of Object.entries(headers || {}))if (name.toLowerCase() === lowerHeaderName) {
128
- if (Array.isArray(value)) return value.length > 0 ? String(value[0]) : void 0;
129
- if (null == value) return;
130
- return String(value);
131
- }
132
- };
133
- const extractNamespace = (requestId)=>requestId.split(/[/:.]/)[0]?.trim().toLowerCase();
134
- const createViolation = (reason, message, status)=>({
135
- code: 'BFF_CROSS_PROJECT_POLICY_DENIED',
136
- reason,
137
- message,
138
- status
139
- });
140
- const warnAdvisoryNamespaceAllowlist = ()=>{
141
- if (hasWarnedAdvisoryNamespaceAllowlist) return;
142
- hasWarnedAdvisoryNamespaceAllowlist = true;
143
- console.warn(`[Modern.js BFF] ${NAMESPACE_ALLOWLIST_REQUIRES_VERIFIER_MESSAGE}. allowClientAssertedNamespace=true will continue to evaluate allowlist against client-asserted requestId namespaces only.`);
144
- };
145
- const createCrossProjectPolicyEvaluationState = (headers, policy, observedRequest)=>({
146
- headers,
147
- policy,
148
- status: normalizeStatusCode(policy.denyStatus),
149
- requireEnvelope: policy.requireEnvelope ?? true,
150
- requireOperationContext: policy.requireOperationContext ?? true,
151
- requireOperationContextDetails: policy.requireOperationContextDetails ?? true,
152
- requireOperationSchemaHash: policy.requireOperationSchemaHash ?? true,
153
- requireOperationVersion: policy.requireOperationVersion ?? true,
154
- allowUnknownOperations: policy.allowUnknownOperations ?? false,
155
- allowClientAssertedNamespace: policy.allowClientAssertedNamespace ?? false,
156
- verifyProducerIdentity: 'function' == typeof policy.verifyProducerIdentity ? policy.verifyProducerIdentity : void 0,
157
- allowedNamespaces: (policy.allowedNamespaces || []).map((item)=>item.trim().toLowerCase()).filter(Boolean),
158
- envelopeHeader: normalizeHeaderName(policy.envelopeHeader, BFF_ENVELOPE_HEADER),
159
- operationContextHeader: normalizeHeaderName(policy.operationContextHeader, BFF_OPERATION_CONTEXT_HEADER),
160
- operationContextDetailHeader: normalizeHeaderName(policy.operationContextDetailHeader, BFF_OPERATION_CONTEXT_DETAIL_HEADER),
161
- requestId: '',
162
- detailSchemaHash: '',
163
- detailOperationVersion: void 0,
164
- observedRequest: observedRequest ? {
165
- method: String(observedRequest.method || '').trim().toUpperCase(),
166
- routePath: String(observedRequest.routePath || '').trim()
167
- } : void 0,
168
- complete: false
169
- });
170
- const checkNamespaceAllowlistVerifier = (state)=>{
171
- if (state.allowedNamespaces.length > 0 && void 0 === state.verifyProducerIdentity) {
172
- if (!state.allowClientAssertedNamespace) return createViolation('producer_identity_mismatch', NAMESPACE_ALLOWLIST_REQUIRES_VERIFIER_MESSAGE, state.status);
173
- warnAdvisoryNamespaceAllowlist();
174
- }
175
- };
176
- const checkEnvelopeHeader = (state)=>{
177
- const envelopeRaw = readHeader(state.headers, state.envelopeHeader);
178
- if (!envelopeRaw) {
179
- if (!state.requireEnvelope) {
180
- state.complete = true;
181
- return;
182
- }
183
- return createViolation('missing_envelope', `Missing cross-project envelope header "${state.envelopeHeader}"`, state.status);
184
- }
185
- let envelope;
186
- try {
187
- const parsed = JSON.parse(envelopeRaw);
188
- if (!parsed || 'object' != typeof parsed) throw new Error('invalid envelope object');
189
- envelope = parsed;
190
- } catch (_error) {
191
- return createViolation('invalid_envelope', `Invalid cross-project envelope header "${state.envelopeHeader}"`, state.status);
192
- }
193
- const requestId = String(envelope.requestId || '').trim();
194
- if (!requestId) return createViolation('missing_request_id', 'Cross-project envelope does not include a valid requestId', state.status);
195
- state.requestId = requestId;
196
- state.claimedNamespace = extractNamespace(requestId);
197
- state.effectiveNamespace = state.claimedNamespace;
198
- };
199
- const checkProducerIdentity = (state)=>{
200
- if (!state.verifyProducerIdentity) return;
201
- const verifiedNamespaceRaw = state.verifyProducerIdentity(state.headers);
202
- const verifiedNamespace = 'string' == typeof verifiedNamespaceRaw ? verifiedNamespaceRaw.trim().toLowerCase() : void 0;
203
- if (!verifiedNamespace) return createViolation('producer_identity_mismatch', 'Producer identity could not be verified for request', state.status);
204
- if (verifiedNamespace !== state.claimedNamespace) return createViolation('producer_identity_mismatch', `Envelope namespace "${state.claimedNamespace || 'unknown'}" does not match verified producer identity "${verifiedNamespace}"`, state.status);
205
- state.effectiveNamespace = verifiedNamespace;
206
- };
207
- const checkNamespaceAllowlist = (state)=>{
208
- if (state.allowedNamespaces.length > 0) {
209
- if (!state.effectiveNamespace || !state.allowedNamespaces.includes(state.effectiveNamespace)) return createViolation('namespace_not_allowed', `Producer namespace "${state.effectiveNamespace || 'unknown'}" not allowed`, state.status);
210
- }
211
- };
212
- const checkOperationContext = (state)=>{
213
- if (!state.requireOperationContext) {
214
- state.complete = true;
215
- return;
216
- }
217
- const operationContext = readHeader(state.headers, state.operationContextHeader);
218
- if (!operationContext) return createViolation('missing_operation_context', `Missing operation context header "${state.operationContextHeader}"`, state.status);
219
- if (!operationContext.startsWith(`${state.requestId}:`)) return createViolation('operation_context_mismatch', `Operation context header "${state.operationContextHeader}" does not match requestId "${state.requestId}"`, state.status);
220
- state.operationContext = operationContext;
221
- };
222
- const checkOperationContextDetails = (state)=>{
223
- const operationContextDetailsRaw = readHeader(state.headers, state.operationContextDetailHeader);
224
- if (!operationContextDetailsRaw) {
225
- if (state.requireOperationContextDetails) return createViolation('missing_operation_context_details', `Missing operation context details header "${state.operationContextDetailHeader}"`, state.status);
226
- state.complete = true;
227
- return;
228
- }
229
- let operationContextDetails;
230
- try {
231
- const parsed = JSON.parse(operationContextDetailsRaw);
232
- if (!parsed || 'object' != typeof parsed || Array.isArray(parsed)) throw new Error('invalid operation context details object');
233
- operationContextDetails = parsed;
234
- } catch (_error) {
235
- return createViolation('invalid_operation_context_details', `Invalid operation context details header "${state.operationContextDetailHeader}"`, state.status);
236
- }
237
- const detailRequestId = String(operationContextDetails.requestId || '').trim();
238
- 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);
239
- const detailOperationId = String(operationContextDetails.operationId || '').trim();
240
- 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);
241
- state.operationContextDetails = operationContextDetails;
242
- state.detailSchemaHash = String(operationContextDetails.schemaHash || '').trim();
243
- if (state.requireOperationSchemaHash && !state.detailSchemaHash) return createViolation('missing_operation_schema_hash', `Operation context details header "${state.operationContextDetailHeader}" must include schemaHash`, state.status);
244
- state.detailOperationVersion = operationContextDetails.operationVersion;
245
- if (state.requireOperationVersion && 'number' != typeof state.detailOperationVersion) return createViolation('missing_operation_version', `Operation context details header "${state.operationContextDetailHeader}" must include operationVersion`, state.status);
246
- };
247
- const checkOperationContract = (state)=>{
248
- if (!state.operationContextDetails) return;
249
- const expectedContracts = state.policy.expectedOperationContracts;
250
- if (expectedContracts && 'object' == typeof expectedContracts) {
251
- const method = String(state.operationContextDetails.method || '').toUpperCase();
252
- const routePath = String(state.operationContextDetails.routePath || '').trim();
253
- const operationId = String(state.operationContextDetails.operationId || '').trim();
254
- const observedMethod = state.observedRequest?.method;
255
- const observedRoutePath = state.observedRequest?.routePath;
256
- 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);
257
- const contractMethod = observedMethod || method;
258
- const contractRoutePath = observedRoutePath || routePath;
259
- const expectedContract = expectedContracts[`${contractMethod}:${contractRoutePath}`] || (state.observedRequest ? void 0 : expectedContracts[`operation:${operationId}`]);
260
- if (expectedContract) {
261
- const assertedOperationId = operationId || state.operationContext || '';
262
- const canonicalRouteOperationId = `${state.requestId}:${contractMethod}:${contractRoutePath}`;
263
- 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);
264
- 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);
265
- 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);
266
- } else if (!state.allowUnknownOperations) return createViolation('unknown_operation_contract', `No expected operation contract found for operation "${operationId || `${method}:${routePath}`}"`, state.status);
267
- }
268
- };
269
- const CROSS_PROJECT_POLICY_CHECKS = [
270
- checkNamespaceAllowlistVerifier,
271
- checkEnvelopeHeader,
272
- checkProducerIdentity,
273
- checkNamespaceAllowlist,
274
- checkOperationContext,
275
- checkOperationContextDetails,
276
- checkOperationContract
277
- ];
278
- const evaluateCrossProjectPolicy = (headers, policy, observedRequest)=>{
279
- if (!policy?.enabled) return null;
280
- const state = createCrossProjectPolicyEvaluationState(headers, policy, observedRequest);
281
- for (const check of CROSS_PROJECT_POLICY_CHECKS){
282
- const violation = check(state);
283
- if (violation) return violation;
284
- if (state.complete) break;
285
- }
286
- return null;
287
- };
288
- __webpack_require__.d(__webpack_exports__, {}, {
289
- BFF_ENVELOPE_HEADER: BFF_ENVELOPE_HEADER,
290
- BFF_OPERATION_CONTEXT_DETAIL_HEADER: BFF_OPERATION_CONTEXT_DETAIL_HEADER,
291
- BFF_OPERATION_CONTEXT_HEADER: BFF_OPERATION_CONTEXT_HEADER,
292
- evaluateCrossProjectPolicy: evaluateCrossProjectPolicy,
293
- resolveCrossProjectRequestObservation: resolveCrossProjectRequestObservation
294
- });
295
- exports.BFF_ENVELOPE_HEADER = __webpack_exports__.BFF_ENVELOPE_HEADER;
296
- exports.BFF_OPERATION_CONTEXT_DETAIL_HEADER = __webpack_exports__.BFF_OPERATION_CONTEXT_DETAIL_HEADER;
297
- exports.BFF_OPERATION_CONTEXT_HEADER = __webpack_exports__.BFF_OPERATION_CONTEXT_HEADER;
298
- exports.evaluateCrossProjectPolicy = __webpack_exports__.evaluateCrossProjectPolicy;
299
- exports.resolveCrossProjectRequestObservation = __webpack_exports__.resolveCrossProjectRequestObservation;
300
- for(var __rspack_i in __webpack_exports__)if (-1 === [
301
- "BFF_ENVELOPE_HEADER",
302
- "BFF_OPERATION_CONTEXT_DETAIL_HEADER",
303
- "BFF_OPERATION_CONTEXT_HEADER",
304
- "evaluateCrossProjectPolicy",
305
- "resolveCrossProjectRequestObservation"
306
- ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
307
- Object.defineProperty(exports, '__esModule', {
308
- value: true
309
- });
@@ -1,183 +0,0 @@
1
- "use strict";
2
- var __webpack_require__ = {};
3
- (()=>{
4
- __webpack_require__.d = (exports1, getters, values)=>{
5
- var define = (defs, kind)=>{
6
- for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
- enumerable: true,
8
- [kind]: defs[key]
9
- });
10
- };
11
- define(getters, "get");
12
- define(values, "value");
13
- };
14
- })();
15
- (()=>{
16
- __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
- })();
18
- (()=>{
19
- __webpack_require__.r = (exports1)=>{
20
- if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
- value: 'Module'
22
- });
23
- Object.defineProperty(exports1, '__esModule', {
24
- value: true
25
- });
26
- };
27
- })();
28
- var __webpack_exports__ = {};
29
- __webpack_require__.r(__webpack_exports__);
30
- __webpack_require__.d(__webpack_exports__, {
31
- DEFAULT_OPERATION_VERSION: ()=>DEFAULT_OPERATION_VERSION,
32
- buildOperationContractMap: ()=>buildOperationContractMap,
33
- createOperationContractHash: ()=>createOperationContractHash,
34
- createOperationEntries: ()=>createOperationEntries,
35
- createOperationSchemaHash: ()=>createOperationSchemaHash,
36
- deriveOperationVersion: ()=>deriveOperationVersion,
37
- serializeOperationSchemas: ()=>serializeOperationSchemas
38
- });
39
- const external_node_module_namespaceObject = require("node:module");
40
- const external_crypto_namespaceObject = require("crypto");
41
- require("reflect-metadata");
42
- const external_types_js_namespaceObject = require("../types.js");
43
- const DEFAULT_OPERATION_VERSION = 1;
44
- const deriveOperationVersion = (packageVersion)=>{
45
- if ('string' != typeof packageVersion) return DEFAULT_OPERATION_VERSION;
46
- const match = packageVersion.trim().match(/^v?(\d+)\./);
47
- if (!match) return DEFAULT_OPERATION_VERSION;
48
- const major = Number.parseInt(match[1], 10);
49
- return Number.isInteger(major) && major >= 0 ? major : DEFAULT_OPERATION_VERSION;
50
- };
51
- const stableStringify = (value)=>{
52
- if (Array.isArray(value)) return `[${value.map((item)=>stableStringify(item)).join(',')}]`;
53
- if (value && 'object' == typeof value) {
54
- const entries = Object.entries(value).filter(([, entryValue])=>void 0 !== entryValue).sort(([a], [b])=>a.localeCompare(b)).map(([key, entryValue])=>`${JSON.stringify(key)}:${stableStringify(entryValue)}`);
55
- return `{${entries.join(',')}}`;
56
- }
57
- return JSON.stringify(value) ?? 'null';
58
- };
59
- const sha256 = (text)=>(0, external_crypto_namespaceObject.createHash)('sha256').update(text).digest('hex');
60
- let cachedZodToJSONSchema;
61
- const ZOD_SPECIFIER = "zod";
62
- const resolveZodToJSONSchema = ()=>{
63
- if (void 0 !== cachedZodToJSONSchema) return cachedZodToJSONSchema;
64
- try {
65
- const load = (0, external_node_module_namespaceObject.createRequire)(__filename);
66
- const zod = load(ZOD_SPECIFIER);
67
- const candidate = zod?.toJSONSchema ?? zod?.z?.toJSONSchema;
68
- cachedZodToJSONSchema = 'function' == typeof candidate ? candidate : null;
69
- } catch {
70
- cachedZodToJSONSchema = null;
71
- }
72
- return cachedZodToJSONSchema;
73
- };
74
- const INPUT_SCHEMA_METADATA_KEYS = [
75
- external_types_js_namespaceObject.HttpMetadata.Data,
76
- external_types_js_namespaceObject.HttpMetadata.Query,
77
- external_types_js_namespaceObject.HttpMetadata.Params,
78
- external_types_js_namespaceObject.HttpMetadata.Headers,
79
- external_types_js_namespaceObject.HttpMetadata.Files
80
- ];
81
- const serializeSchema = (schema)=>{
82
- const toJSONSchema = resolveZodToJSONSchema();
83
- if (toJSONSchema) try {
84
- return toJSONSchema(schema, {
85
- io: 'input',
86
- unrepresentable: 'any'
87
- });
88
- } catch {}
89
- return {
90
- __unserializableSchema: true
91
- };
92
- };
93
- const serializeOperationSchemas = (handler)=>{
94
- if ('function' != typeof handler) return;
95
- const serialized = {};
96
- for (const metadataKey of INPUT_SCHEMA_METADATA_KEYS){
97
- let schema;
98
- try {
99
- schema = Reflect.getMetadata(metadataKey, handler);
100
- } catch {
101
- schema = void 0;
102
- }
103
- if (null != schema) serialized[metadataKey] = serializeSchema(schema);
104
- }
105
- return Object.keys(serialized).length > 0 ? serialized : void 0;
106
- };
107
- const createOperationContractHash = (operation, requestId)=>sha256(stableStringify({
108
- httpMethod: String(operation.httpMethod || '').toUpperCase(),
109
- name: operation.name,
110
- requestId,
111
- routePath: operation.routePath,
112
- ...operation.schemas ? {
113
- schemas: operation.schemas
114
- } : {}
115
- }));
116
- const createOperationEntries = (handlers)=>handlers.map((item)=>({
117
- name: item.name,
118
- httpMethod: String(item.httpMethod || '').toUpperCase(),
119
- routePath: item.routePath
120
- })).sort((a, b)=>{
121
- const keyA = `${a.routePath}:${a.httpMethod}:${a.name}`;
122
- const keyB = `${b.routePath}:${b.httpMethod}:${b.name}`;
123
- return keyA.localeCompare(keyB);
124
- });
125
- const createOperationSchemaHash = (operationEntries, requestId)=>sha256(stableStringify({
126
- operations: [
127
- ...operationEntries
128
- ].map((item)=>({
129
- hash: item.schemaHash ?? createOperationContractHash({
130
- name: item.name,
131
- httpMethod: item.httpMethod,
132
- routePath: item.routePath
133
- }, requestId)
134
- })).sort((a, b)=>a.hash.localeCompare(b.hash)),
135
- requestId
136
- }));
137
- const buildOperationContractMap = ({ handlers, requestId, operationVersion })=>{
138
- const normalizedRequestId = 'string' == typeof requestId && requestId.trim().length > 0 ? requestId.trim() : 'default';
139
- const normalizedOperationVersion = 'number' == typeof operationVersion && Number.isInteger(operationVersion) ? operationVersion : DEFAULT_OPERATION_VERSION;
140
- const contracts = {};
141
- handlers.forEach((item)=>{
142
- const httpMethod = String(item.httpMethod || '').toUpperCase();
143
- const schemaHash = createOperationContractHash({
144
- name: item.name,
145
- httpMethod,
146
- routePath: item.routePath,
147
- schemas: serializeOperationSchemas(item.handler)
148
- }, normalizedRequestId);
149
- const operationId = `${normalizedRequestId}:${item.name}`;
150
- const contract = {
151
- requestId: normalizedRequestId,
152
- operationVersion: normalizedOperationVersion,
153
- schemaHash,
154
- method: httpMethod,
155
- routePath: item.routePath,
156
- operationId,
157
- handlerName: item.name,
158
- filename: item.filename
159
- };
160
- contracts[`${httpMethod}:${item.routePath}`] = contract;
161
- contracts[`operation:${operationId}`] = contract;
162
- });
163
- return contracts;
164
- };
165
- exports.DEFAULT_OPERATION_VERSION = __webpack_exports__.DEFAULT_OPERATION_VERSION;
166
- exports.buildOperationContractMap = __webpack_exports__.buildOperationContractMap;
167
- exports.createOperationContractHash = __webpack_exports__.createOperationContractHash;
168
- exports.createOperationEntries = __webpack_exports__.createOperationEntries;
169
- exports.createOperationSchemaHash = __webpack_exports__.createOperationSchemaHash;
170
- exports.deriveOperationVersion = __webpack_exports__.deriveOperationVersion;
171
- exports.serializeOperationSchemas = __webpack_exports__.serializeOperationSchemas;
172
- for(var __rspack_i in __webpack_exports__)if (-1 === [
173
- "DEFAULT_OPERATION_VERSION",
174
- "buildOperationContractMap",
175
- "createOperationContractHash",
176
- "createOperationEntries",
177
- "createOperationSchemaHash",
178
- "deriveOperationVersion",
179
- "serializeOperationSchemas"
180
- ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
181
- Object.defineProperty(exports, '__esModule', {
182
- value: true
183
- });
@@ -1,65 +0,0 @@
1
- "use strict";
2
- var __webpack_require__ = {};
3
- (()=>{
4
- __webpack_require__.d = (exports1, getters, values)=>{
5
- var define = (defs, kind)=>{
6
- for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
- enumerable: true,
8
- [kind]: defs[key]
9
- });
10
- };
11
- define(getters, "get");
12
- define(values, "value");
13
- };
14
- })();
15
- (()=>{
16
- __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
- })();
18
- (()=>{
19
- __webpack_require__.r = (exports1)=>{
20
- if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
- value: 'Module'
22
- });
23
- Object.defineProperty(exports1, '__esModule', {
24
- value: true
25
- });
26
- };
27
- })();
28
- var __webpack_exports__ = {};
29
- __webpack_require__.r(__webpack_exports__);
30
- __webpack_require__.d(__webpack_exports__, {
31
- resolveCrossProjectPolicy: ()=>resolveCrossProjectPolicy
32
- });
33
- const external_operationContracts_js_namespaceObject = require("./operationContracts.js");
34
- const resolveCrossProjectPolicy = (input)=>{
35
- const { crossProjectPolicy, handlers, requestId, isCrossProjectServer, operationVersion } = input;
36
- if (!crossProjectPolicy && !isCrossProjectServer) return;
37
- const policy = crossProjectPolicy ?? {};
38
- const effectiveRequestId = 'string' == typeof requestId && requestId.trim().length > 0 ? requestId : 'default';
39
- const generatedContracts = (0, external_operationContracts_js_namespaceObject.buildOperationContractMap)({
40
- handlers,
41
- requestId: effectiveRequestId,
42
- operationVersion
43
- });
44
- return {
45
- ...policy,
46
- enabled: policy.enabled ?? Boolean(isCrossProjectServer),
47
- requireEnvelope: policy.requireEnvelope ?? true,
48
- requireOperationContext: policy.requireOperationContext ?? true,
49
- requireOperationContextDetails: policy.requireOperationContextDetails ?? true,
50
- requireOperationSchemaHash: policy.requireOperationSchemaHash ?? true,
51
- requireOperationVersion: policy.requireOperationVersion ?? true,
52
- allowUnknownOperations: policy.allowUnknownOperations ?? false,
53
- expectedOperationContracts: {
54
- ...policy.expectedOperationContracts ?? {},
55
- ...generatedContracts
56
- }
57
- };
58
- };
59
- exports.resolveCrossProjectPolicy = __webpack_exports__.resolveCrossProjectPolicy;
60
- for(var __rspack_i in __webpack_exports__)if (-1 === [
61
- "resolveCrossProjectPolicy"
62
- ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
63
- Object.defineProperty(exports, '__esModule', {
64
- value: true
65
- });
@@ -1,79 +0,0 @@
1
- import "reflect-metadata";
2
- import { evaluateCrossProjectPolicy } from "../security/crossProjectPolicy.mjs";
3
- import { HttpMetadata, HttpMethod } from "../types.mjs";
4
- import { isInputParamsDeciderHandler, isWithMetaHandler } from "../utils/index.mjs";
5
- const API_ROUTE_METHODS = {
6
- [HttpMethod.Get]: 'get',
7
- [HttpMethod.Post]: 'post',
8
- [HttpMethod.Put]: 'put',
9
- [HttpMethod.Delete]: 'delete',
10
- [HttpMethod.Connect]: 'connect',
11
- [HttpMethod.Trace]: 'trace',
12
- [HttpMethod.Patch]: 'patch',
13
- [HttpMethod.Options]: 'options',
14
- [HttpMethod.Head]: 'head'
15
- };
16
- const toApiRouteMethod = (httpMethod)=>{
17
- const method = API_ROUTE_METHODS[httpMethod];
18
- if (!method) throw new Error(`[bff-core] Unsupported HTTP method "${String(httpMethod)}" in API handler info`);
19
- return method;
20
- };
21
- const getRouteMiddlewares = (handler)=>{
22
- const middlewares = Reflect.getMetadata('middleware', handler);
23
- return Array.isArray(middlewares) ? middlewares : [];
24
- };
25
- const planApiRoutes = (handlerInfos)=>handlerInfos.map(({ routePath, handler, httpMethod })=>({
26
- method: toApiRouteMethod(httpMethod),
27
- routePath,
28
- handler,
29
- middlewares: getRouteMiddlewares(handler)
30
- }));
31
- const HANDLER_WITH_SCHEMA = 'HANDLER_WITH_SCHEMA';
32
- const isSchemaApiHandler = (handler)=>{
33
- if ('function' != typeof handler) return false;
34
- const marked = handler;
35
- return true === marked[HANDLER_WITH_SCHEMA];
36
- };
37
- const getApiHandlerMode = (handler)=>{
38
- if (isWithMetaHandler(handler)) return 'meta';
39
- if (isSchemaApiHandler(handler)) return 'schema';
40
- if (isInputParamsDeciderHandler(handler)) return 'inputParamsDecider';
41
- return 'plain';
42
- };
43
- const mapSchemaHandlerResult = (result)=>{
44
- if ('HandleSuccess' === result.type) return {
45
- success: true,
46
- status: 200,
47
- body: result.value
48
- };
49
- return {
50
- success: false,
51
- status: 'InputValidationError' === result.type ? 400 : 500,
52
- body: result.message
53
- };
54
- };
55
- const getResponseMetaList = (handler)=>{
56
- const responseMeta = Reflect.getMetadata(HttpMetadata.Response, handler);
57
- return Array.isArray(responseMeta) ? responseMeta : [];
58
- };
59
- const buildPositionalHandlerArgs = (input, routePath)=>{
60
- const paramNames = routePath?.match(/:(\w+)/g)?.map((param)=>param.slice(1)) ?? [];
61
- const positionalParams = paramNames.length > 0 ? paramNames.map((param)=>input.params[param]) : Object.values(input.params);
62
- return [
63
- ...positionalParams,
64
- input
65
- ];
66
- };
67
- const checkCrossProjectPolicy = (headers, policy)=>{
68
- const violation = evaluateCrossProjectPolicy(headers, policy);
69
- if (!violation) return null;
70
- return {
71
- status: violation.status,
72
- body: {
73
- code: violation.code,
74
- reason: violation.reason,
75
- message: violation.message
76
- }
77
- };
78
- };
79
- export { HANDLER_WITH_SCHEMA, buildPositionalHandlerArgs, checkCrossProjectPolicy, getApiHandlerMode, getResponseMetaList, getRouteMiddlewares, isSchemaApiHandler, mapSchemaHandlerResult, planApiRoutes, toApiRouteMethod };
@@ -1,17 +0,0 @@
1
- import { deniedScenario, envelopeHeader } from "./shared.mjs";
2
- const createCrossProjectDenialScenarios = ()=>[
3
- deniedScenario('policy denies missing envelope', 'missing_envelope', {}),
4
- deniedScenario('policy denies invalid envelope', 'invalid_envelope', {
5
- 'x-modernjs-bff-envelope': 'not-json'
6
- }),
7
- deniedScenario('policy denies envelope that is valid JSON but not an object', 'invalid_envelope', {
8
- 'x-modernjs-bff-envelope': '123'
9
- }),
10
- deniedScenario('policy denies missing requestId', 'missing_request_id', {
11
- 'x-modernjs-bff-envelope': envelopeHeader(void 0)
12
- }),
13
- deniedScenario('policy denies namespace outside allowlist', 'namespace_not_allowed', {
14
- 'x-modernjs-bff-envelope': envelopeHeader('billing.producer-z')
15
- })
16
- ];
17
- export { createCrossProjectDenialScenarios };