@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,112 +0,0 @@
1
- import "node:module";
2
- import { PARITY_PRODUCER_REQUEST_ID, deniedScenario, detailHeader } from "./shared.mjs";
3
- const createOperationContextSuccessScenarios = ({ helloContract, validEnvelope, validOperationId })=>[
4
- {
5
- name: 'policy pass with full operation context',
6
- policy: true,
7
- request: {
8
- method: 'get',
9
- path: '/hello',
10
- headers: {
11
- 'x-modernjs-bff-envelope': validEnvelope,
12
- 'x-operation-id': validOperationId,
13
- 'x-modernjs-bff-operation-context': detailHeader({
14
- requestId: PARITY_PRODUCER_REQUEST_ID,
15
- method: 'GET',
16
- routePath: '/hello',
17
- schemaHash: helloContract.schemaHash,
18
- operationVersion: helloContract.operationVersion
19
- })
20
- }
21
- },
22
- expected: {
23
- kind: 'payload',
24
- status: 200,
25
- payload: {
26
- message: 'hello'
27
- }
28
- }
29
- }
30
- ];
31
- const getMismatchedOperationVersion = (contract)=>{
32
- const operationVersion = contract.operationVersion;
33
- if ('number' != typeof operationVersion) throw new Error('Adapter parity hello contract requires operationVersion');
34
- return operationVersion + 1;
35
- };
36
- const createOperationContextDenialScenarios = ({ helloContract, validEnvelope, validOperationId })=>[
37
- deniedScenario('policy denies missing operation context', 'missing_operation_context', {
38
- 'x-modernjs-bff-envelope': validEnvelope
39
- }),
40
- deniedScenario('policy denies operation context mismatch', 'operation_context_mismatch', {
41
- 'x-modernjs-bff-envelope': validEnvelope,
42
- 'x-operation-id': 'someone-else:parity'
43
- }),
44
- deniedScenario('policy denies missing operation context details', 'missing_operation_context_details', {
45
- 'x-modernjs-bff-envelope': validEnvelope,
46
- 'x-operation-id': validOperationId
47
- }),
48
- deniedScenario('policy denies JSON-array operation context details', 'invalid_operation_context_details', {
49
- 'x-modernjs-bff-envelope': validEnvelope,
50
- 'x-operation-id': validOperationId,
51
- 'x-modernjs-bff-operation-context': '[]'
52
- }),
53
- deniedScenario('policy denies invalid operation context details', 'invalid_operation_context_details', {
54
- 'x-modernjs-bff-envelope': validEnvelope,
55
- 'x-operation-id': validOperationId,
56
- 'x-modernjs-bff-operation-context': 'not-json'
57
- }),
58
- deniedScenario('policy denies detail requestId mismatch', 'operation_context_details_request_id_mismatch', {
59
- 'x-modernjs-bff-envelope': validEnvelope,
60
- 'x-operation-id': validOperationId,
61
- 'x-modernjs-bff-operation-context': detailHeader({
62
- requestId: 'crm.producer-b',
63
- method: 'GET',
64
- routePath: '/hello',
65
- schemaHash: helloContract.schemaHash,
66
- operationVersion: helloContract.operationVersion
67
- })
68
- }),
69
- deniedScenario('policy denies missing operation schema hash', 'missing_operation_schema_hash', {
70
- 'x-modernjs-bff-envelope': validEnvelope,
71
- 'x-operation-id': validOperationId,
72
- 'x-modernjs-bff-operation-context': detailHeader({
73
- requestId: PARITY_PRODUCER_REQUEST_ID,
74
- method: 'GET',
75
- routePath: '/hello',
76
- operationVersion: helloContract.operationVersion
77
- })
78
- }),
79
- deniedScenario('policy denies missing operation version', 'missing_operation_version', {
80
- 'x-modernjs-bff-envelope': validEnvelope,
81
- 'x-operation-id': validOperationId,
82
- 'x-modernjs-bff-operation-context': detailHeader({
83
- requestId: PARITY_PRODUCER_REQUEST_ID,
84
- method: 'GET',
85
- routePath: '/hello',
86
- schemaHash: helloContract.schemaHash
87
- })
88
- }),
89
- deniedScenario('policy denies operation schema hash mismatch', 'operation_schema_hash_mismatch', {
90
- 'x-modernjs-bff-envelope': validEnvelope,
91
- 'x-operation-id': validOperationId,
92
- 'x-modernjs-bff-operation-context': detailHeader({
93
- requestId: PARITY_PRODUCER_REQUEST_ID,
94
- method: 'GET',
95
- routePath: '/hello',
96
- schemaHash: 'deadbeef',
97
- operationVersion: helloContract.operationVersion
98
- })
99
- }),
100
- deniedScenario('policy denies operation version mismatch', 'operation_version_mismatch', {
101
- 'x-modernjs-bff-envelope': validEnvelope,
102
- 'x-operation-id': validOperationId,
103
- 'x-modernjs-bff-operation-context': detailHeader({
104
- requestId: PARITY_PRODUCER_REQUEST_ID,
105
- method: 'GET',
106
- routePath: '/hello',
107
- schemaHash: helloContract.schemaHash,
108
- operationVersion: getMismatchedOperationVersion(helloContract)
109
- })
110
- })
111
- ];
112
- export { createOperationContextDenialScenarios, createOperationContextSuccessScenarios };
@@ -1,72 +0,0 @@
1
- import "node:module";
2
- const createSchemaParityScenarios = ()=>[
3
- {
4
- name: 'schema handler success',
5
- policy: false,
6
- request: {
7
- method: 'patch',
8
- path: '/schema',
9
- headers: {
10
- 'content-type': 'application/json'
11
- },
12
- body: {
13
- id: 777
14
- }
15
- },
16
- expected: {
17
- kind: 'payload',
18
- status: 200,
19
- payload: {
20
- type: 'HandleSuccess',
21
- value: {
22
- id: 777
23
- }
24
- }
25
- }
26
- },
27
- {
28
- name: 'schema handler input validation error',
29
- policy: false,
30
- request: {
31
- method: 'patch',
32
- path: '/schema',
33
- headers: {
34
- 'content-type': 'application/json'
35
- },
36
- body: {
37
- id: 'aaa'
38
- }
39
- },
40
- expected: {
41
- kind: 'payload',
42
- status: 200,
43
- payload: {
44
- type: 'InputValidationError',
45
- message: 'invalid input'
46
- }
47
- }
48
- },
49
- {
50
- name: 'schema handler output validation error',
51
- policy: false,
52
- request: {
53
- method: 'patch',
54
- path: '/schema',
55
- headers: {
56
- 'content-type': 'application/json'
57
- },
58
- body: {
59
- id: 'boom'
60
- }
61
- },
62
- expected: {
63
- kind: 'payload',
64
- status: 200,
65
- payload: {
66
- type: 'OutputValidationError',
67
- message: 'invalid output'
68
- }
69
- }
70
- }
71
- ];
72
- export { createSchemaParityScenarios };
@@ -1,22 +0,0 @@
1
- import "node:module";
2
- const PARITY_REQUEST_ID = 'crm';
3
- const PARITY_PRODUCER_REQUEST_ID = 'crm.producer-a';
4
- const envelopeHeader = (requestId)=>JSON.stringify(void 0 === requestId ? {} : {
5
- requestId
6
- });
7
- const detailHeader = (details)=>JSON.stringify(details);
8
- const deniedScenario = (name, reason, headers)=>({
9
- name,
10
- policy: true,
11
- request: {
12
- method: 'get',
13
- path: '/hello',
14
- headers
15
- },
16
- expected: {
17
- kind: 'denied',
18
- status: 403,
19
- reason
20
- }
21
- });
22
- export { PARITY_PRODUCER_REQUEST_ID, PARITY_REQUEST_ID, deniedScenario, detailHeader, envelopeHeader };
@@ -1,149 +0,0 @@
1
- import "node:module";
2
- import { buildOperationContractMap } from "../security/operationContracts.mjs";
3
- import { HttpMethod } from "../types.mjs";
4
- import { createCrossProjectDenialScenarios } from "./parity-scenarios/cross-project-denial.mjs";
5
- import { createEnvelopeParityScenarios } from "./parity-scenarios/envelope.mjs";
6
- import { createOperationContextDenialScenarios, createOperationContextSuccessScenarios } from "./parity-scenarios/operation-context.mjs";
7
- import { createSchemaParityScenarios } from "./parity-scenarios/schema.mjs";
8
- import { PARITY_PRODUCER_REQUEST_ID, PARITY_REQUEST_ID, envelopeHeader } from "./parity-scenarios/shared.mjs";
9
- const PARITY_FIXTURE_FILENAME = 'bff-core/adapter-kit/parity-fixture.ts';
10
- const HANDLER_WITH_SCHEMA = 'HANDLER_WITH_SCHEMA';
11
- const isRecord = (value)=>Boolean(value) && 'object' == typeof value;
12
- const createSchemaFixtureHandler = ()=>{
13
- const handler = (input)=>{
14
- const data = isRecord(input) && isRecord(input.data) ? input.data : void 0;
15
- const id = data?.id;
16
- if ('number' == typeof id) return {
17
- type: 'HandleSuccess',
18
- value: {
19
- id
20
- }
21
- };
22
- if ('boom' === id) return {
23
- type: 'OutputValidationError',
24
- message: 'invalid output'
25
- };
26
- return {
27
- type: 'InputValidationError',
28
- message: 'invalid input'
29
- };
30
- };
31
- return Object.assign(handler, {
32
- [HANDLER_WITH_SCHEMA]: true
33
- });
34
- };
35
- const createParityApiHandlerInfos = ()=>[
36
- {
37
- name: 'getHello',
38
- httpMethod: HttpMethod.Get,
39
- routeName: '/hello',
40
- routePath: '/hello',
41
- filename: PARITY_FIXTURE_FILENAME,
42
- handler: ()=>({
43
- message: 'hello'
44
- })
45
- },
46
- {
47
- name: 'postHello',
48
- httpMethod: HttpMethod.Post,
49
- routeName: '/hello',
50
- routePath: '/hello',
51
- filename: PARITY_FIXTURE_FILENAME,
52
- handler: ()=>'hello'
53
- },
54
- {
55
- name: 'getNothing',
56
- httpMethod: HttpMethod.Get,
57
- routeName: '/nothing',
58
- routePath: '/nothing',
59
- filename: PARITY_FIXTURE_FILENAME,
60
- handler: ()=>void 0
61
- },
62
- {
63
- name: 'postEcho',
64
- httpMethod: HttpMethod.Post,
65
- routeName: '/echo',
66
- routePath: '/echo',
67
- filename: PARITY_FIXTURE_FILENAME,
68
- handler: (input)=>{
69
- const normalized = isRecord(input) ? input : {};
70
- return {
71
- data: normalized.data ?? null,
72
- query: normalized.query ?? {},
73
- cookie: normalized.cookies ?? null
74
- };
75
- }
76
- },
77
- {
78
- name: 'getItem',
79
- httpMethod: HttpMethod.Get,
80
- routeName: '/items/:id',
81
- routePath: '/items/:id',
82
- filename: PARITY_FIXTURE_FILENAME,
83
- handler: (id, input)=>({
84
- id,
85
- query: isRecord(input) ? input.query ?? {} : {}
86
- })
87
- },
88
- {
89
- name: 'patchSchema',
90
- httpMethod: HttpMethod.Patch,
91
- routeName: '/schema',
92
- routePath: '/schema',
93
- filename: PARITY_FIXTURE_FILENAME,
94
- handler: createSchemaFixtureHandler()
95
- }
96
- ];
97
- const createParityBffConfig = ()=>({
98
- requestId: PARITY_PRODUCER_REQUEST_ID,
99
- crossProjectPolicy: {
100
- enabled: true,
101
- allowedNamespaces: [
102
- PARITY_REQUEST_ID
103
- ],
104
- allowClientAssertedNamespace: true
105
- }
106
- });
107
- const getParityContracts = ()=>buildOperationContractMap({
108
- handlers: createParityApiHandlerInfos(),
109
- requestId: PARITY_PRODUCER_REQUEST_ID
110
- });
111
- const createAdapterParityScenarios = ()=>{
112
- const contracts = getParityContracts();
113
- const helloContract = contracts['GET:/hello'];
114
- const validEnvelope = envelopeHeader(PARITY_PRODUCER_REQUEST_ID);
115
- const validOperationId = helloContract.operationId;
116
- const context = {
117
- helloContract,
118
- validEnvelope,
119
- validOperationId
120
- };
121
- return [
122
- ...createEnvelopeParityScenarios(),
123
- ...createSchemaParityScenarios(),
124
- ...createOperationContextSuccessScenarios(context),
125
- ...createCrossProjectDenialScenarios(),
126
- ...createOperationContextDenialScenarios(context)
127
- ];
128
- };
129
- const toParityResult = (res)=>({
130
- status: res.status,
131
- payload: res.type.includes('json') ? res.body : '' === res.text ? void 0 : res.text
132
- });
133
- const formatValue = (value)=>JSON.stringify(value);
134
- const assertParityResult = (scenario, res)=>{
135
- const result = toParityResult(res);
136
- const failures = [];
137
- const { expected } = scenario;
138
- if (result.status !== expected.status) failures.push(`status: expected ${expected.status}, received ${result.status}`);
139
- if ('payload' === expected.kind) {
140
- if (formatValue(result.payload) !== formatValue(expected.payload)) failures.push(`payload: expected ${formatValue(expected.payload)}, received ${formatValue(result.payload)}`);
141
- } else {
142
- const payload = isRecord(result.payload) ? result.payload : {};
143
- if ('BFF_CROSS_PROJECT_POLICY_DENIED' !== payload.code) failures.push(`denial code: expected "BFF_CROSS_PROJECT_POLICY_DENIED", received ${formatValue(payload.code)}`);
144
- if (payload.reason !== expected.reason) failures.push(`denial reason: expected "${expected.reason}", received ${formatValue(payload.reason)}`);
145
- if ('string' != typeof payload.message || 0 === payload.message.length) failures.push(`denial message: expected non-empty string, received ${formatValue(payload.message)}`);
146
- }
147
- if (failures.length > 0) throw new Error(`Adapter parity scenario "${scenario.name}" failed:\n- ${failures.join('\n- ')}`);
148
- };
149
- export { PARITY_PRODUCER_REQUEST_ID, PARITY_REQUEST_ID, assertParityResult, createAdapterParityScenarios, createParityApiHandlerInfos, createParityBffConfig, toParityResult };
@@ -1,260 +0,0 @@
1
- import "node:module";
2
- const BFF_ENVELOPE_HEADER = 'x-modernjs-bff-envelope';
3
- const BFF_OPERATION_CONTEXT_HEADER = 'x-operation-id';
4
- const BFF_OPERATION_CONTEXT_DETAIL_HEADER = 'x-modernjs-bff-operation-context';
5
- const DEFAULT_DENY_STATUS = 403;
6
- const NAMESPACE_ALLOWLIST_REQUIRES_VERIFIER_MESSAGE = 'cross-project namespace allowlist requires verifyProducerIdentity';
7
- let hasWarnedAdvisoryNamespaceAllowlist = false;
8
- const splitRoutePath = (routePath)=>routePath.split('/').filter(Boolean);
9
- const isDynamicRouteSegment = (segment)=>segment.startsWith(':') || '*' === segment || segment.startsWith('*') || segment.startsWith('{*');
10
- const hasTrailingSlash = (routePath)=>routePath.length > 1 && routePath.endsWith('/');
11
- const hasUnsafePathEncoding = (requestPath)=>{
12
- let decoded = requestPath;
13
- for(let depth = 0; depth < 8; depth += 1){
14
- if (/%(?:2f|5c)/i.test(decoded)) return true;
15
- try {
16
- const next = decodeURIComponent(decoded);
17
- if (next === decoded) return false;
18
- decoded = next;
19
- } catch {
20
- return true;
21
- }
22
- }
23
- return decoded.includes('%');
24
- };
25
- const routeSegmentsMatch = (templateSegments, requestSegments)=>{
26
- let templateIndex = 0;
27
- let requestIndex = 0;
28
- while(templateIndex < templateSegments.length){
29
- const segment = templateSegments[templateIndex];
30
- const wildcard = '*' === segment || segment.startsWith('*') || segment.startsWith('{*');
31
- const optional = segment.startsWith(':') && segment.endsWith('?');
32
- if (templateIndex < templateSegments.length - 1 && (wildcard || optional)) return false;
33
- if (wildcard) return true;
34
- const requestSegment = requestSegments[requestIndex];
35
- if (void 0 === requestSegment) return optional && templateIndex === templateSegments.length - 1;
36
- if (!segment.startsWith(':') && segment !== requestSegment) return false;
37
- templateIndex += 1;
38
- requestIndex += 1;
39
- }
40
- return requestIndex === requestSegments.length;
41
- };
42
- const routeTemplateMatchScore = (routePath, requestPath)=>{
43
- if (hasTrailingSlash(routePath) !== hasTrailingSlash(requestPath)) return;
44
- const templateSegments = splitRoutePath(routePath);
45
- const requestSegments = splitRoutePath(requestPath);
46
- for(let prefixLength = 0; prefixLength <= templateSegments.length; prefixLength += 1){
47
- const removedPrefix = templateSegments.slice(0, prefixLength);
48
- if (removedPrefix.some(isDynamicRouteSegment)) break;
49
- const mountedTemplate = templateSegments.slice(prefixLength);
50
- if (!routeSegmentsMatch(mountedTemplate, requestSegments)) continue;
51
- const literalSegments = mountedTemplate.filter((segment)=>!isDynamicRouteSegment(segment)).length;
52
- const dynamicSegments = mountedTemplate.length - literalSegments;
53
- return (0 === prefixLength ? 1000000 : 0) + 10000 * literalSegments - 100 * dynamicSegments - prefixLength;
54
- }
55
- };
56
- const resolveCrossProjectRequestObservation = (request, policy)=>{
57
- const requestMethod = String(request.method || '').trim().toUpperCase();
58
- const routePaths = [
59
- ...new Set(Object.keys(policy.expectedOperationContracts ?? {}).flatMap((key)=>{
60
- if (key.startsWith('operation:')) return [];
61
- const separator = key.indexOf(':');
62
- if (-1 === separator || key.slice(0, separator).trim().toUpperCase() !== requestMethod) return [];
63
- return [
64
- key.slice(separator + 1)
65
- ];
66
- }))
67
- ];
68
- if (0 === routePaths.length) return;
69
- if (hasUnsafePathEncoding(request.pathname)) return {
70
- method: request.method,
71
- routePath: request.pathname
72
- };
73
- const matches = routePaths.flatMap((routePath)=>{
74
- const score = routeTemplateMatchScore(routePath, request.pathname);
75
- return void 0 === score ? [] : [
76
- {
77
- routePath,
78
- score
79
- }
80
- ];
81
- });
82
- if (0 === matches.length) return {
83
- method: request.method,
84
- routePath: request.pathname
85
- };
86
- matches.sort((left, right)=>right.score - left.score);
87
- return {
88
- method: request.method,
89
- routePath: matches[1]?.score === matches[0]?.score ? request.pathname : matches[0].routePath
90
- };
91
- };
92
- const normalizeHeaderName = (headerName, fallback)=>(headerName || fallback).trim().toLowerCase();
93
- const normalizeStatusCode = (statusCode)=>{
94
- if ('number' == typeof statusCode && Number.isFinite(statusCode) && statusCode >= 400 && statusCode <= 599) return Math.floor(statusCode);
95
- return DEFAULT_DENY_STATUS;
96
- };
97
- const readHeader = (headers, headerName)=>{
98
- const lowerHeaderName = headerName.toLowerCase();
99
- for (const [name, value] of Object.entries(headers || {}))if (name.toLowerCase() === lowerHeaderName) {
100
- if (Array.isArray(value)) return value.length > 0 ? String(value[0]) : void 0;
101
- if (null == value) return;
102
- return String(value);
103
- }
104
- };
105
- const extractNamespace = (requestId)=>requestId.split(/[/:.]/)[0]?.trim().toLowerCase();
106
- const createViolation = (reason, message, status)=>({
107
- code: 'BFF_CROSS_PROJECT_POLICY_DENIED',
108
- reason,
109
- message,
110
- status
111
- });
112
- const warnAdvisoryNamespaceAllowlist = ()=>{
113
- if (hasWarnedAdvisoryNamespaceAllowlist) return;
114
- hasWarnedAdvisoryNamespaceAllowlist = true;
115
- console.warn(`[Modern.js BFF] ${NAMESPACE_ALLOWLIST_REQUIRES_VERIFIER_MESSAGE}. allowClientAssertedNamespace=true will continue to evaluate allowlist against client-asserted requestId namespaces only.`);
116
- };
117
- const createCrossProjectPolicyEvaluationState = (headers, policy, observedRequest)=>({
118
- headers,
119
- policy,
120
- status: normalizeStatusCode(policy.denyStatus),
121
- requireEnvelope: policy.requireEnvelope ?? true,
122
- requireOperationContext: policy.requireOperationContext ?? true,
123
- requireOperationContextDetails: policy.requireOperationContextDetails ?? true,
124
- requireOperationSchemaHash: policy.requireOperationSchemaHash ?? true,
125
- requireOperationVersion: policy.requireOperationVersion ?? true,
126
- allowUnknownOperations: policy.allowUnknownOperations ?? false,
127
- allowClientAssertedNamespace: policy.allowClientAssertedNamespace ?? false,
128
- verifyProducerIdentity: 'function' == typeof policy.verifyProducerIdentity ? policy.verifyProducerIdentity : void 0,
129
- allowedNamespaces: (policy.allowedNamespaces || []).map((item)=>item.trim().toLowerCase()).filter(Boolean),
130
- envelopeHeader: normalizeHeaderName(policy.envelopeHeader, BFF_ENVELOPE_HEADER),
131
- operationContextHeader: normalizeHeaderName(policy.operationContextHeader, BFF_OPERATION_CONTEXT_HEADER),
132
- operationContextDetailHeader: normalizeHeaderName(policy.operationContextDetailHeader, BFF_OPERATION_CONTEXT_DETAIL_HEADER),
133
- requestId: '',
134
- detailSchemaHash: '',
135
- detailOperationVersion: void 0,
136
- observedRequest: observedRequest ? {
137
- method: String(observedRequest.method || '').trim().toUpperCase(),
138
- routePath: String(observedRequest.routePath || '').trim()
139
- } : void 0,
140
- complete: false
141
- });
142
- const checkNamespaceAllowlistVerifier = (state)=>{
143
- if (state.allowedNamespaces.length > 0 && void 0 === state.verifyProducerIdentity) {
144
- if (!state.allowClientAssertedNamespace) return createViolation('producer_identity_mismatch', NAMESPACE_ALLOWLIST_REQUIRES_VERIFIER_MESSAGE, state.status);
145
- warnAdvisoryNamespaceAllowlist();
146
- }
147
- };
148
- const checkEnvelopeHeader = (state)=>{
149
- const envelopeRaw = readHeader(state.headers, state.envelopeHeader);
150
- if (!envelopeRaw) {
151
- if (!state.requireEnvelope) {
152
- state.complete = true;
153
- return;
154
- }
155
- return createViolation('missing_envelope', `Missing cross-project envelope header "${state.envelopeHeader}"`, state.status);
156
- }
157
- let envelope;
158
- try {
159
- const parsed = JSON.parse(envelopeRaw);
160
- if (!parsed || 'object' != typeof parsed) throw new Error('invalid envelope object');
161
- envelope = parsed;
162
- } catch (_error) {
163
- return createViolation('invalid_envelope', `Invalid cross-project envelope header "${state.envelopeHeader}"`, state.status);
164
- }
165
- const requestId = String(envelope.requestId || '').trim();
166
- if (!requestId) return createViolation('missing_request_id', 'Cross-project envelope does not include a valid requestId', state.status);
167
- state.requestId = requestId;
168
- state.claimedNamespace = extractNamespace(requestId);
169
- state.effectiveNamespace = state.claimedNamespace;
170
- };
171
- const checkProducerIdentity = (state)=>{
172
- if (!state.verifyProducerIdentity) return;
173
- const verifiedNamespaceRaw = state.verifyProducerIdentity(state.headers);
174
- const verifiedNamespace = 'string' == typeof verifiedNamespaceRaw ? verifiedNamespaceRaw.trim().toLowerCase() : void 0;
175
- if (!verifiedNamespace) return createViolation('producer_identity_mismatch', 'Producer identity could not be verified for request', state.status);
176
- if (verifiedNamespace !== state.claimedNamespace) return createViolation('producer_identity_mismatch', `Envelope namespace "${state.claimedNamespace || 'unknown'}" does not match verified producer identity "${verifiedNamespace}"`, state.status);
177
- state.effectiveNamespace = verifiedNamespace;
178
- };
179
- const checkNamespaceAllowlist = (state)=>{
180
- if (state.allowedNamespaces.length > 0) {
181
- if (!state.effectiveNamespace || !state.allowedNamespaces.includes(state.effectiveNamespace)) return createViolation('namespace_not_allowed', `Producer namespace "${state.effectiveNamespace || 'unknown'}" not allowed`, state.status);
182
- }
183
- };
184
- const checkOperationContext = (state)=>{
185
- if (!state.requireOperationContext) {
186
- state.complete = true;
187
- return;
188
- }
189
- const operationContext = readHeader(state.headers, state.operationContextHeader);
190
- if (!operationContext) return createViolation('missing_operation_context', `Missing operation context header "${state.operationContextHeader}"`, state.status);
191
- if (!operationContext.startsWith(`${state.requestId}:`)) return createViolation('operation_context_mismatch', `Operation context header "${state.operationContextHeader}" does not match requestId "${state.requestId}"`, state.status);
192
- state.operationContext = operationContext;
193
- };
194
- const checkOperationContextDetails = (state)=>{
195
- const operationContextDetailsRaw = readHeader(state.headers, state.operationContextDetailHeader);
196
- if (!operationContextDetailsRaw) {
197
- if (state.requireOperationContextDetails) return createViolation('missing_operation_context_details', `Missing operation context details header "${state.operationContextDetailHeader}"`, state.status);
198
- state.complete = true;
199
- return;
200
- }
201
- let operationContextDetails;
202
- try {
203
- const parsed = JSON.parse(operationContextDetailsRaw);
204
- if (!parsed || 'object' != typeof parsed || Array.isArray(parsed)) throw new Error('invalid operation context details object');
205
- operationContextDetails = parsed;
206
- } catch (_error) {
207
- return createViolation('invalid_operation_context_details', `Invalid operation context details header "${state.operationContextDetailHeader}"`, state.status);
208
- }
209
- const detailRequestId = String(operationContextDetails.requestId || '').trim();
210
- 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);
211
- const detailOperationId = String(operationContextDetails.operationId || '').trim();
212
- 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);
213
- state.operationContextDetails = operationContextDetails;
214
- state.detailSchemaHash = String(operationContextDetails.schemaHash || '').trim();
215
- if (state.requireOperationSchemaHash && !state.detailSchemaHash) return createViolation('missing_operation_schema_hash', `Operation context details header "${state.operationContextDetailHeader}" must include schemaHash`, state.status);
216
- state.detailOperationVersion = operationContextDetails.operationVersion;
217
- if (state.requireOperationVersion && 'number' != typeof state.detailOperationVersion) return createViolation('missing_operation_version', `Operation context details header "${state.operationContextDetailHeader}" must include operationVersion`, state.status);
218
- };
219
- const checkOperationContract = (state)=>{
220
- if (!state.operationContextDetails) return;
221
- const expectedContracts = state.policy.expectedOperationContracts;
222
- if (expectedContracts && 'object' == typeof expectedContracts) {
223
- const method = String(state.operationContextDetails.method || '').toUpperCase();
224
- const routePath = String(state.operationContextDetails.routePath || '').trim();
225
- const operationId = String(state.operationContextDetails.operationId || '').trim();
226
- const observedMethod = state.observedRequest?.method;
227
- const observedRoutePath = state.observedRequest?.routePath;
228
- 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);
229
- const contractMethod = observedMethod || method;
230
- const contractRoutePath = observedRoutePath || routePath;
231
- const expectedContract = expectedContracts[`${contractMethod}:${contractRoutePath}`] || (state.observedRequest ? void 0 : expectedContracts[`operation:${operationId}`]);
232
- if (expectedContract) {
233
- const assertedOperationId = operationId || state.operationContext || '';
234
- const canonicalRouteOperationId = `${state.requestId}:${contractMethod}:${contractRoutePath}`;
235
- 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);
236
- 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);
237
- 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);
238
- } else if (!state.allowUnknownOperations) return createViolation('unknown_operation_contract', `No expected operation contract found for operation "${operationId || `${method}:${routePath}`}"`, state.status);
239
- }
240
- };
241
- const CROSS_PROJECT_POLICY_CHECKS = [
242
- checkNamespaceAllowlistVerifier,
243
- checkEnvelopeHeader,
244
- checkProducerIdentity,
245
- checkNamespaceAllowlist,
246
- checkOperationContext,
247
- checkOperationContextDetails,
248
- checkOperationContract
249
- ];
250
- const evaluateCrossProjectPolicy = (headers, policy, observedRequest)=>{
251
- if (!policy?.enabled) return null;
252
- const state = createCrossProjectPolicyEvaluationState(headers, policy, observedRequest);
253
- for (const check of CROSS_PROJECT_POLICY_CHECKS){
254
- const violation = check(state);
255
- if (violation) return violation;
256
- if (state.complete) break;
257
- }
258
- return null;
259
- };
260
- export { BFF_ENVELOPE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER, evaluateCrossProjectPolicy, resolveCrossProjectRequestObservation };