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