@bleedingdev/modern-js-bff-core 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.
Files changed (60) hide show
  1. package/dist/cjs/client/generateClient.js +67 -138
  2. package/dist/cjs/index.js +24 -114
  3. package/dist/cjs/router/index.js +7 -5
  4. package/dist/cjs/utils/index.js +11 -21
  5. package/dist/esm/client/generateClient.mjs +65 -139
  6. package/dist/esm/index.mjs +1 -5
  7. package/dist/esm/router/index.mjs +7 -5
  8. package/dist/esm/utils/index.mjs +0 -1
  9. package/dist/esm-node/client/generateClient.mjs +65 -139
  10. package/dist/esm-node/index.mjs +1 -5
  11. package/dist/esm-node/router/index.mjs +7 -5
  12. package/dist/esm-node/utils/index.mjs +0 -1
  13. package/dist/types/client/generateClient.d.ts +24 -1
  14. package/dist/types/index.d.ts +1 -5
  15. package/dist/types/utils/index.d.ts +0 -1
  16. package/package.json +10 -19
  17. package/dist/cjs/adapter-kit/index.js +0 -144
  18. package/dist/cjs/adapter-kit/parity-scenarios/cross-project-denial.js +0 -55
  19. package/dist/cjs/adapter-kit/parity-scenarios/envelope.js +0 -128
  20. package/dist/cjs/adapter-kit/parity-scenarios/operation-context.js +0 -152
  21. package/dist/cjs/adapter-kit/parity-scenarios/schema.js +0 -109
  22. package/dist/cjs/adapter-kit/parity-scenarios/shared.js +0 -71
  23. package/dist/cjs/adapter-kit/parity.js +0 -204
  24. package/dist/cjs/security/crossProjectPolicy.js +0 -309
  25. package/dist/cjs/security/operationContracts.js +0 -183
  26. package/dist/cjs/security/resolveCrossProjectPolicy.js +0 -65
  27. package/dist/cjs/utils/alias.js +0 -112
  28. package/dist/esm/adapter-kit/index.mjs +0 -79
  29. package/dist/esm/adapter-kit/parity-scenarios/cross-project-denial.mjs +0 -17
  30. package/dist/esm/adapter-kit/parity-scenarios/envelope.mjs +0 -90
  31. package/dist/esm/adapter-kit/parity-scenarios/operation-context.mjs +0 -111
  32. package/dist/esm/adapter-kit/parity-scenarios/schema.mjs +0 -71
  33. package/dist/esm/adapter-kit/parity-scenarios/shared.mjs +0 -21
  34. package/dist/esm/adapter-kit/parity.mjs +0 -148
  35. package/dist/esm/security/crossProjectPolicy.mjs +0 -259
  36. package/dist/esm/security/operationContracts.mjs +0 -127
  37. package/dist/esm/security/resolveCrossProjectPolicy.mjs +0 -27
  38. package/dist/esm/utils/alias.mjs +0 -57
  39. package/dist/esm-node/adapter-kit/index.mjs +0 -80
  40. package/dist/esm-node/adapter-kit/parity-scenarios/cross-project-denial.mjs +0 -18
  41. package/dist/esm-node/adapter-kit/parity-scenarios/envelope.mjs +0 -91
  42. package/dist/esm-node/adapter-kit/parity-scenarios/operation-context.mjs +0 -112
  43. package/dist/esm-node/adapter-kit/parity-scenarios/schema.mjs +0 -72
  44. package/dist/esm-node/adapter-kit/parity-scenarios/shared.mjs +0 -22
  45. package/dist/esm-node/adapter-kit/parity.mjs +0 -149
  46. package/dist/esm-node/security/crossProjectPolicy.mjs +0 -260
  47. package/dist/esm-node/security/operationContracts.mjs +0 -130
  48. package/dist/esm-node/security/resolveCrossProjectPolicy.mjs +0 -28
  49. package/dist/esm-node/utils/alias.mjs +0 -58
  50. package/dist/types/adapter-kit/index.d.ts +0 -90
  51. package/dist/types/adapter-kit/parity-scenarios/cross-project-denial.d.ts +0 -2
  52. package/dist/types/adapter-kit/parity-scenarios/envelope.d.ts +0 -2
  53. package/dist/types/adapter-kit/parity-scenarios/operation-context.d.ts +0 -3
  54. package/dist/types/adapter-kit/parity-scenarios/schema.d.ts +0 -2
  55. package/dist/types/adapter-kit/parity-scenarios/shared.d.ts +0 -32
  56. package/dist/types/adapter-kit/parity.d.ts +0 -43
  57. package/dist/types/security/crossProjectPolicy.d.ts +0 -110
  58. package/dist/types/security/operationContracts.d.ts +0 -84
  59. package/dist/types/security/resolveCrossProjectPolicy.d.ts +0 -39
  60. package/dist/types/utils/alias.d.ts +0 -7
@@ -1,71 +0,0 @@
1
- const createSchemaParityScenarios = ()=>[
2
- {
3
- name: 'schema handler success',
4
- policy: false,
5
- request: {
6
- method: 'patch',
7
- path: '/schema',
8
- headers: {
9
- 'content-type': 'application/json'
10
- },
11
- body: {
12
- id: 777
13
- }
14
- },
15
- expected: {
16
- kind: 'payload',
17
- status: 200,
18
- payload: {
19
- type: 'HandleSuccess',
20
- value: {
21
- id: 777
22
- }
23
- }
24
- }
25
- },
26
- {
27
- name: 'schema handler input validation error',
28
- policy: false,
29
- request: {
30
- method: 'patch',
31
- path: '/schema',
32
- headers: {
33
- 'content-type': 'application/json'
34
- },
35
- body: {
36
- id: 'aaa'
37
- }
38
- },
39
- expected: {
40
- kind: 'payload',
41
- status: 200,
42
- payload: {
43
- type: 'InputValidationError',
44
- message: 'invalid input'
45
- }
46
- }
47
- },
48
- {
49
- name: 'schema handler output validation error',
50
- policy: false,
51
- request: {
52
- method: 'patch',
53
- path: '/schema',
54
- headers: {
55
- 'content-type': 'application/json'
56
- },
57
- body: {
58
- id: 'boom'
59
- }
60
- },
61
- expected: {
62
- kind: 'payload',
63
- status: 200,
64
- payload: {
65
- type: 'OutputValidationError',
66
- message: 'invalid output'
67
- }
68
- }
69
- }
70
- ];
71
- export { createSchemaParityScenarios };
@@ -1,21 +0,0 @@
1
- const PARITY_REQUEST_ID = 'crm';
2
- const PARITY_PRODUCER_REQUEST_ID = 'crm.producer-a';
3
- const envelopeHeader = (requestId)=>JSON.stringify(void 0 === requestId ? {} : {
4
- requestId
5
- });
6
- const detailHeader = (details)=>JSON.stringify(details);
7
- const deniedScenario = (name, reason, headers)=>({
8
- name,
9
- policy: true,
10
- request: {
11
- method: 'get',
12
- path: '/hello',
13
- headers
14
- },
15
- expected: {
16
- kind: 'denied',
17
- status: 403,
18
- reason
19
- }
20
- });
21
- export { PARITY_PRODUCER_REQUEST_ID, PARITY_REQUEST_ID, deniedScenario, detailHeader, envelopeHeader };
@@ -1,148 +0,0 @@
1
- import { buildOperationContractMap } from "../security/operationContracts.mjs";
2
- import { HttpMethod } from "../types.mjs";
3
- import { createCrossProjectDenialScenarios } from "./parity-scenarios/cross-project-denial.mjs";
4
- import { createEnvelopeParityScenarios } from "./parity-scenarios/envelope.mjs";
5
- import { createOperationContextDenialScenarios, createOperationContextSuccessScenarios } from "./parity-scenarios/operation-context.mjs";
6
- import { createSchemaParityScenarios } from "./parity-scenarios/schema.mjs";
7
- import { PARITY_PRODUCER_REQUEST_ID, PARITY_REQUEST_ID, envelopeHeader } from "./parity-scenarios/shared.mjs";
8
- const PARITY_FIXTURE_FILENAME = 'bff-core/adapter-kit/parity-fixture.ts';
9
- const HANDLER_WITH_SCHEMA = 'HANDLER_WITH_SCHEMA';
10
- const isRecord = (value)=>Boolean(value) && 'object' == typeof value;
11
- const createSchemaFixtureHandler = ()=>{
12
- const handler = (input)=>{
13
- const data = isRecord(input) && isRecord(input.data) ? input.data : void 0;
14
- const id = data?.id;
15
- if ('number' == typeof id) return {
16
- type: 'HandleSuccess',
17
- value: {
18
- id
19
- }
20
- };
21
- if ('boom' === id) return {
22
- type: 'OutputValidationError',
23
- message: 'invalid output'
24
- };
25
- return {
26
- type: 'InputValidationError',
27
- message: 'invalid input'
28
- };
29
- };
30
- return Object.assign(handler, {
31
- [HANDLER_WITH_SCHEMA]: true
32
- });
33
- };
34
- const createParityApiHandlerInfos = ()=>[
35
- {
36
- name: 'getHello',
37
- httpMethod: HttpMethod.Get,
38
- routeName: '/hello',
39
- routePath: '/hello',
40
- filename: PARITY_FIXTURE_FILENAME,
41
- handler: ()=>({
42
- message: 'hello'
43
- })
44
- },
45
- {
46
- name: 'postHello',
47
- httpMethod: HttpMethod.Post,
48
- routeName: '/hello',
49
- routePath: '/hello',
50
- filename: PARITY_FIXTURE_FILENAME,
51
- handler: ()=>'hello'
52
- },
53
- {
54
- name: 'getNothing',
55
- httpMethod: HttpMethod.Get,
56
- routeName: '/nothing',
57
- routePath: '/nothing',
58
- filename: PARITY_FIXTURE_FILENAME,
59
- handler: ()=>void 0
60
- },
61
- {
62
- name: 'postEcho',
63
- httpMethod: HttpMethod.Post,
64
- routeName: '/echo',
65
- routePath: '/echo',
66
- filename: PARITY_FIXTURE_FILENAME,
67
- handler: (input)=>{
68
- const normalized = isRecord(input) ? input : {};
69
- return {
70
- data: normalized.data ?? null,
71
- query: normalized.query ?? {},
72
- cookie: normalized.cookies ?? null
73
- };
74
- }
75
- },
76
- {
77
- name: 'getItem',
78
- httpMethod: HttpMethod.Get,
79
- routeName: '/items/:id',
80
- routePath: '/items/:id',
81
- filename: PARITY_FIXTURE_FILENAME,
82
- handler: (id, input)=>({
83
- id,
84
- query: isRecord(input) ? input.query ?? {} : {}
85
- })
86
- },
87
- {
88
- name: 'patchSchema',
89
- httpMethod: HttpMethod.Patch,
90
- routeName: '/schema',
91
- routePath: '/schema',
92
- filename: PARITY_FIXTURE_FILENAME,
93
- handler: createSchemaFixtureHandler()
94
- }
95
- ];
96
- const createParityBffConfig = ()=>({
97
- requestId: PARITY_PRODUCER_REQUEST_ID,
98
- crossProjectPolicy: {
99
- enabled: true,
100
- allowedNamespaces: [
101
- PARITY_REQUEST_ID
102
- ],
103
- allowClientAssertedNamespace: true
104
- }
105
- });
106
- const getParityContracts = ()=>buildOperationContractMap({
107
- handlers: createParityApiHandlerInfos(),
108
- requestId: PARITY_PRODUCER_REQUEST_ID
109
- });
110
- const createAdapterParityScenarios = ()=>{
111
- const contracts = getParityContracts();
112
- const helloContract = contracts['GET:/hello'];
113
- const validEnvelope = envelopeHeader(PARITY_PRODUCER_REQUEST_ID);
114
- const validOperationId = helloContract.operationId;
115
- const context = {
116
- helloContract,
117
- validEnvelope,
118
- validOperationId
119
- };
120
- return [
121
- ...createEnvelopeParityScenarios(),
122
- ...createSchemaParityScenarios(),
123
- ...createOperationContextSuccessScenarios(context),
124
- ...createCrossProjectDenialScenarios(),
125
- ...createOperationContextDenialScenarios(context)
126
- ];
127
- };
128
- const toParityResult = (res)=>({
129
- status: res.status,
130
- payload: res.type.includes('json') ? res.body : '' === res.text ? void 0 : res.text
131
- });
132
- const formatValue = (value)=>JSON.stringify(value);
133
- const assertParityResult = (scenario, res)=>{
134
- const result = toParityResult(res);
135
- const failures = [];
136
- const { expected } = scenario;
137
- if (result.status !== expected.status) failures.push(`status: expected ${expected.status}, received ${result.status}`);
138
- if ('payload' === expected.kind) {
139
- if (formatValue(result.payload) !== formatValue(expected.payload)) failures.push(`payload: expected ${formatValue(expected.payload)}, received ${formatValue(result.payload)}`);
140
- } else {
141
- const payload = isRecord(result.payload) ? result.payload : {};
142
- if ('BFF_CROSS_PROJECT_POLICY_DENIED' !== payload.code) failures.push(`denial code: expected "BFF_CROSS_PROJECT_POLICY_DENIED", received ${formatValue(payload.code)}`);
143
- if (payload.reason !== expected.reason) failures.push(`denial reason: expected "${expected.reason}", received ${formatValue(payload.reason)}`);
144
- if ('string' != typeof payload.message || 0 === payload.message.length) failures.push(`denial message: expected non-empty string, received ${formatValue(payload.message)}`);
145
- }
146
- if (failures.length > 0) throw new Error(`Adapter parity scenario "${scenario.name}" failed:\n- ${failures.join('\n- ')}`);
147
- };
148
- export { PARITY_PRODUCER_REQUEST_ID, PARITY_REQUEST_ID, assertParityResult, createAdapterParityScenarios, createParityApiHandlerInfos, createParityBffConfig, toParityResult };
@@ -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 };