@bleedingdev/modern-js-server-runtime-extensions 3.9.0-ultramodern.11 → 3.9.0-ultramodern.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/backend-federation-security/index.js +73 -152
- package/dist/cjs/backend-federation-security/node.js +3 -3
- package/dist/cjs/bff-policy/index.js +7 -0
- package/dist/cjs/bff-policy/node.js +20 -4
- package/dist/cjs/bff-policy/operationContracts.js +150 -135
- package/dist/cjs/bff-policy/operationIdentity.js +81 -0
- package/dist/cjs/bff-policy/producer.js +79 -0
- package/dist/cjs/localisedLoaderPlugin.js +22 -1
- package/dist/esm/backend-federation-security/index.mjs +73 -152
- package/dist/esm/backend-federation-security/node.mjs +3 -3
- package/dist/esm/bff-policy/index.mjs +1 -0
- package/dist/esm/bff-policy/operationIdentity.mjs +30 -0
- package/dist/esm/bff-policy/producer.mjs +31 -0
- package/dist/esm/localisedLoaderPlugin.mjs +22 -1
- package/dist/esm-node/backend-federation-security/index.mjs +73 -152
- package/dist/esm-node/backend-federation-security/node.mjs +3 -3
- package/dist/esm-node/bff-policy/index.mjs +1 -0
- package/dist/esm-node/bff-policy/node.mjs +1 -0
- package/dist/esm-node/bff-policy/operationContracts.mjs +5 -27
- package/dist/esm-node/bff-policy/operationIdentity.mjs +31 -0
- package/dist/esm-node/bff-policy/producer.mjs +32 -0
- package/dist/esm-node/localisedLoaderPlugin.mjs +22 -1
- package/dist/types/backend-federation-security/node.d.ts +1 -1
- package/dist/types/bff-policy/index.d.ts +1 -0
- package/dist/types/bff-policy/node.d.ts +1 -0
- package/dist/types/bff-policy/operationContracts.d.ts +2 -41
- package/dist/types/bff-policy/operationIdentity.d.ts +34 -0
- package/dist/types/bff-policy/producer.d.ts +10 -0
- package/dist/types-esm/backend-federation-security/node.d.mts +1 -1
- package/dist/types-esm/bff-policy/index.d.mts +1 -0
- package/dist/types-esm/bff-policy/node.d.mts +1 -0
- package/dist/types-esm/bff-policy/operationContracts.d.mts +2 -41
- package/dist/types-esm/bff-policy/operationIdentity.d.mts +34 -0
- package/dist/types-esm/bff-policy/producer.d.mts +10 -0
- package/package.json +13 -13
- package/src/backend-federation-security/index.ts +151 -318
- package/src/backend-federation-security/node.ts +32 -22
- package/src/bff-policy/index.ts +1 -0
- package/src/bff-policy/node.ts +1 -0
- package/src/bff-policy/operationContracts.ts +13 -86
- package/src/bff-policy/operationIdentity.ts +90 -0
- package/src/bff-policy/producer.ts +40 -0
- package/src/localisedLoaderPlugin.ts +31 -0
- package/tests/backendFederationSecurity.test.ts +71 -0
- package/tests/bff-policy/operationContracts.test.ts +57 -0
- package/tests/localisedLoader.test.ts +36 -1
|
@@ -5,67 +5,17 @@ import 'reflect-metadata';
|
|
|
5
5
|
// Structural handler protocol; native operators retain ownership of metadata.
|
|
6
6
|
type ApiHandler = (...args: any) => any | Promise<any>;
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
routePath: string;
|
|
20
|
-
operationId: string;
|
|
21
|
-
handlerName: string;
|
|
22
|
-
filename?: string;
|
|
23
|
-
};
|
|
24
|
-
|
|
25
|
-
export type OperationContractMap = Record<string, OperationContractDefinition>;
|
|
26
|
-
|
|
27
|
-
export const DEFAULT_OPERATION_VERSION = 1;
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Derives the operation version from a producer package version: the semver
|
|
31
|
-
* major is the contract version, so consumers regenerated against an older
|
|
32
|
-
* producer major fail the `operation_version_mismatch` gate instead of
|
|
33
|
-
* silently calling an incompatible API.
|
|
34
|
-
*
|
|
35
|
-
* Falls back to {@link DEFAULT_OPERATION_VERSION} when no parseable version
|
|
36
|
-
* is available.
|
|
37
|
-
*/
|
|
38
|
-
export const deriveOperationVersion = (packageVersion?: unknown): number => {
|
|
39
|
-
if (typeof packageVersion !== 'string') {
|
|
40
|
-
return DEFAULT_OPERATION_VERSION;
|
|
41
|
-
}
|
|
42
|
-
const match = packageVersion.trim().match(/^v?(\d+)\./);
|
|
43
|
-
if (!match) {
|
|
44
|
-
return DEFAULT_OPERATION_VERSION;
|
|
45
|
-
}
|
|
46
|
-
const major = Number.parseInt(match[1]!, 10);
|
|
47
|
-
return Number.isInteger(major) && major >= 0
|
|
48
|
-
? major
|
|
49
|
-
: DEFAULT_OPERATION_VERSION;
|
|
50
|
-
};
|
|
51
|
-
|
|
52
|
-
/** JSON.stringify with recursively sorted object keys for stable hashing. */
|
|
53
|
-
const stableStringify = (value: unknown): string => {
|
|
54
|
-
if (Array.isArray(value)) {
|
|
55
|
-
return `[${value.map(item => stableStringify(item)).join(',')}]`;
|
|
56
|
-
}
|
|
57
|
-
if (value && typeof value === 'object') {
|
|
58
|
-
const entries = Object.entries(value as Record<string, unknown>)
|
|
59
|
-
.filter(([, entryValue]) => typeof entryValue !== 'undefined')
|
|
60
|
-
.sort(([a], [b]) => a.localeCompare(b))
|
|
61
|
-
.map(
|
|
62
|
-
([key, entryValue]) =>
|
|
63
|
-
`${JSON.stringify(key)}:${stableStringify(entryValue)}`,
|
|
64
|
-
);
|
|
65
|
-
return `{${entries.join(',')}}`;
|
|
66
|
-
}
|
|
67
|
-
return JSON.stringify(value) ?? 'null';
|
|
68
|
-
};
|
|
8
|
+
import {
|
|
9
|
+
DEFAULT_OPERATION_VERSION,
|
|
10
|
+
type OperationContractDefinition,
|
|
11
|
+
type OperationContractEntry,
|
|
12
|
+
type OperationContractHashInput,
|
|
13
|
+
type OperationContractMap,
|
|
14
|
+
serializeOperationContract,
|
|
15
|
+
stableOperationStringify,
|
|
16
|
+
} from './operationIdentity';
|
|
17
|
+
|
|
18
|
+
export * from './operationIdentity';
|
|
69
19
|
|
|
70
20
|
const sha256 = (text: string) =>
|
|
71
21
|
createHash('sha256').update(text).digest('hex');
|
|
@@ -156,33 +106,10 @@ export const serializeOperationSchemas = (
|
|
|
156
106
|
return Object.keys(serialized).length > 0 ? serialized : undefined;
|
|
157
107
|
};
|
|
158
108
|
|
|
159
|
-
export type OperationContractHashInput = OperationContractEntry & {
|
|
160
|
-
/** Serialized schema documents; omit for schema-less operations. */
|
|
161
|
-
schemas?: Record<string, unknown> | undefined;
|
|
162
|
-
};
|
|
163
|
-
|
|
164
|
-
/**
|
|
165
|
-
* Per-operation contract hash. The hash covers the operation identity
|
|
166
|
-
* (name, method, route, producer requestId) plus the serialized input
|
|
167
|
-
* schemas, so:
|
|
168
|
-
*
|
|
169
|
-
* - changing an input schema changes the hash of exactly that operation;
|
|
170
|
-
* - reordering routes or adding unrelated operations never rotates the hash
|
|
171
|
-
* of other operations (each operation is hashed independently).
|
|
172
|
-
*/
|
|
173
109
|
export const createOperationContractHash = (
|
|
174
110
|
operation: OperationContractHashInput,
|
|
175
111
|
requestId: string,
|
|
176
|
-
): string =>
|
|
177
|
-
sha256(
|
|
178
|
-
stableStringify({
|
|
179
|
-
httpMethod: String(operation.httpMethod || '').toUpperCase(),
|
|
180
|
-
name: operation.name,
|
|
181
|
-
requestId,
|
|
182
|
-
routePath: operation.routePath,
|
|
183
|
-
...(operation.schemas ? { schemas: operation.schemas } : {}),
|
|
184
|
-
}),
|
|
185
|
-
);
|
|
112
|
+
): string => sha256(serializeOperationContract(operation, requestId));
|
|
186
113
|
|
|
187
114
|
export const createOperationEntries = (
|
|
188
115
|
handlers: Array<{
|
|
@@ -213,7 +140,7 @@ export const createOperationSchemaHash = (
|
|
|
213
140
|
requestId: string,
|
|
214
141
|
): string =>
|
|
215
142
|
sha256(
|
|
216
|
-
|
|
143
|
+
stableOperationStringify({
|
|
217
144
|
operations: [...operationEntries]
|
|
218
145
|
.map(item => ({
|
|
219
146
|
hash:
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
export type OperationContractEntry = {
|
|
2
|
+
name: string;
|
|
3
|
+
httpMethod: string;
|
|
4
|
+
routePath: string;
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
export type OperationContractDefinition = {
|
|
8
|
+
requestId: string;
|
|
9
|
+
operationVersion: number;
|
|
10
|
+
schemaHash: string;
|
|
11
|
+
method: string;
|
|
12
|
+
routePath: string;
|
|
13
|
+
operationId: string;
|
|
14
|
+
handlerName: string;
|
|
15
|
+
filename?: string;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export type OperationContractMap = Record<string, OperationContractDefinition>;
|
|
19
|
+
|
|
20
|
+
export const DEFAULT_OPERATION_VERSION = 1;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Derives the operation version from a producer package version: the semver
|
|
24
|
+
* major is the contract version, so consumers regenerated against an older
|
|
25
|
+
* producer major fail the `operation_version_mismatch` gate instead of
|
|
26
|
+
* silently calling an incompatible API.
|
|
27
|
+
*
|
|
28
|
+
* Falls back to {@link DEFAULT_OPERATION_VERSION} when no parseable version
|
|
29
|
+
* is available.
|
|
30
|
+
*/
|
|
31
|
+
export const deriveOperationVersion = (packageVersion?: unknown): number => {
|
|
32
|
+
if (typeof packageVersion !== 'string') {
|
|
33
|
+
return DEFAULT_OPERATION_VERSION;
|
|
34
|
+
}
|
|
35
|
+
const match = packageVersion.trim().match(/^v?(\d+)\./);
|
|
36
|
+
if (!match) {
|
|
37
|
+
return DEFAULT_OPERATION_VERSION;
|
|
38
|
+
}
|
|
39
|
+
const major = Number.parseInt(match[1]!, 10);
|
|
40
|
+
return Number.isInteger(major) && major >= 0
|
|
41
|
+
? major
|
|
42
|
+
: DEFAULT_OPERATION_VERSION;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** JSON.stringify with recursively sorted object keys for stable hashing. */
|
|
46
|
+
export const stableOperationStringify = (value: unknown): string => {
|
|
47
|
+
if (Array.isArray(value)) {
|
|
48
|
+
return `[${value.map(item => stableOperationStringify(item)).join(',')}]`;
|
|
49
|
+
}
|
|
50
|
+
if (value && typeof value === 'object') {
|
|
51
|
+
const entries = Object.entries(value as Record<string, unknown>)
|
|
52
|
+
.filter(([, entryValue]) => typeof entryValue !== 'undefined')
|
|
53
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
54
|
+
.map(
|
|
55
|
+
([key, entryValue]) =>
|
|
56
|
+
`${JSON.stringify(key)}:${stableOperationStringify(entryValue)}`,
|
|
57
|
+
);
|
|
58
|
+
return `{${entries.join(',')}}`;
|
|
59
|
+
}
|
|
60
|
+
return JSON.stringify(value) ?? 'null';
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export type OperationContractHashInput = OperationContractEntry & {
|
|
64
|
+
schemas?: Record<string, unknown>;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export const serializeOperationContract = (
|
|
68
|
+
operation: OperationContractHashInput,
|
|
69
|
+
requestId: string,
|
|
70
|
+
): string =>
|
|
71
|
+
stableOperationStringify({
|
|
72
|
+
httpMethod: String(operation.httpMethod || '').toUpperCase(),
|
|
73
|
+
name: operation.name,
|
|
74
|
+
requestId,
|
|
75
|
+
routePath: operation.routePath,
|
|
76
|
+
...(operation.schemas ? { schemas: operation.schemas } : {}),
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
export async function digestOperationContract(
|
|
80
|
+
operation: OperationContractHashInput,
|
|
81
|
+
requestId: string,
|
|
82
|
+
): Promise<string> {
|
|
83
|
+
const digest = await globalThis.crypto.subtle.digest(
|
|
84
|
+
'SHA-256',
|
|
85
|
+
new TextEncoder().encode(serializeOperationContract(operation, requestId)),
|
|
86
|
+
);
|
|
87
|
+
return Array.from(new Uint8Array(digest), value =>
|
|
88
|
+
value.toString(16).padStart(2, '0'),
|
|
89
|
+
).join('');
|
|
90
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { deriveOperationVersion } from './operationIdentity';
|
|
4
|
+
|
|
5
|
+
/** Resolve the owning package once. Never borrow an ancestor's version when
|
|
6
|
+
* the producer has an absent or invalid version of its own. */
|
|
7
|
+
export function resolveOperationProducer(options: {
|
|
8
|
+
directories: Array<string | undefined>;
|
|
9
|
+
requestId?: string;
|
|
10
|
+
onDependency?: (filename: string) => void;
|
|
11
|
+
}) {
|
|
12
|
+
for (const directory of options.directories) {
|
|
13
|
+
if (!directory) continue;
|
|
14
|
+
let current = path.resolve(directory);
|
|
15
|
+
while (true) {
|
|
16
|
+
const filename = path.join(current, 'package.json');
|
|
17
|
+
if (existsSync(filename)) {
|
|
18
|
+
options.onDependency?.(filename);
|
|
19
|
+
let metadata: { name?: unknown; version?: unknown } = {};
|
|
20
|
+
try {
|
|
21
|
+
metadata = JSON.parse(readFileSync(filename, 'utf8')) ?? {};
|
|
22
|
+
} catch {}
|
|
23
|
+
return {
|
|
24
|
+
requestId:
|
|
25
|
+
options.requestId?.trim() ||
|
|
26
|
+
(typeof metadata.name === 'string' && metadata.name.trim()) ||
|
|
27
|
+
'default',
|
|
28
|
+
operationVersion: deriveOperationVersion(metadata.version),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
const parent = path.dirname(current);
|
|
32
|
+
if (parent === current) break;
|
|
33
|
+
current = parent;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
requestId: options.requestId?.trim() || 'default',
|
|
38
|
+
operationVersion: deriveOperationVersion(),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -1,11 +1,41 @@
|
|
|
1
1
|
import { setLoaderRouteIdResolver } from '@modern-js/plugin-data-loader/runtime';
|
|
2
2
|
import { resolveLocalisedLoaderRouteId } from '@modern-js/runtime-extensions/localised-loader-identity';
|
|
3
|
+
import { applyLocalisedUrlsToRoutes } from '@modern-js/runtime-extensions/localised-urls';
|
|
3
4
|
import {
|
|
4
5
|
getLoaderCtx,
|
|
5
6
|
type MiddlewareHandler,
|
|
7
|
+
type ServerLoaderBundle,
|
|
6
8
|
type ServerPlugin,
|
|
7
9
|
} from '@modern-js/server-core';
|
|
8
10
|
|
|
11
|
+
function expandCanonicalRoutes(routes: ServerLoaderBundle['routes']) {
|
|
12
|
+
const languages = new Set<string>();
|
|
13
|
+
const localisedUrls: Record<string, Record<string, string>> = {};
|
|
14
|
+
let physical = false;
|
|
15
|
+
const visit = (nodes: ServerLoaderBundle['routes']) => {
|
|
16
|
+
for (const route of nodes) {
|
|
17
|
+
physical ||= 'modernCanonicalPath' in route;
|
|
18
|
+
const identity = Reflect.get(route, 'modernLocalisedRoute') as
|
|
19
|
+
| { canonicalPath: string; paths?: Record<string, string> }
|
|
20
|
+
| undefined;
|
|
21
|
+
if (identity?.paths) {
|
|
22
|
+
localisedUrls[identity.canonicalPath] = identity.paths;
|
|
23
|
+
for (const language of Object.keys(identity.paths))
|
|
24
|
+
languages.add(language);
|
|
25
|
+
}
|
|
26
|
+
if ('children' in route && route.children) visit(route.children);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
visit(routes);
|
|
30
|
+
return physical || languages.size === 0
|
|
31
|
+
? routes
|
|
32
|
+
: (applyLocalisedUrlsToRoutes(
|
|
33
|
+
routes,
|
|
34
|
+
[...languages],
|
|
35
|
+
localisedUrls,
|
|
36
|
+
) as typeof routes);
|
|
37
|
+
}
|
|
38
|
+
|
|
9
39
|
export function injectLocalisedLoaderPlugin(): ServerPlugin {
|
|
10
40
|
return {
|
|
11
41
|
name: '@modern-js/localised-loader',
|
|
@@ -19,6 +49,7 @@ export function injectLocalisedLoaderPlugin(): ServerPlugin {
|
|
|
19
49
|
requestedRouteId,
|
|
20
50
|
matchedRouteIds,
|
|
21
51
|
),
|
|
52
|
+
expandCanonicalRoutes,
|
|
22
53
|
);
|
|
23
54
|
await next();
|
|
24
55
|
};
|
|
@@ -402,10 +402,18 @@ describe('verified backend federation entry loading', () => {
|
|
|
402
402
|
) as { get(id: string): () => string };
|
|
403
403
|
|
|
404
404
|
expect(builtinEntry.get('./effect-api')()).toBe('value');
|
|
405
|
+
const privateCapability = { register: () => undefined };
|
|
406
|
+
const capabilityEntry = evaluateNodeBackendFederationCommonJs(
|
|
407
|
+
'module.exports = { get: () => () => __modernjs_backend_private_capability__ };',
|
|
408
|
+
{ remote: { entry: entryUrl, name: remoteName } },
|
|
409
|
+
privateCapability,
|
|
410
|
+
) as { get(id: string): () => unknown };
|
|
411
|
+
expect(capabilityEntry.get('./effect-api')()).toBe(privateCapability);
|
|
405
412
|
expect(() =>
|
|
406
413
|
evaluateNodeBackendFederationCommonJs(
|
|
407
414
|
"require('@attacker/package'); module.exports = { get() {} };",
|
|
408
415
|
{ remote: { entry: entryUrl, name: remoteName } },
|
|
416
|
+
privateCapability,
|
|
409
417
|
),
|
|
410
418
|
).toThrow(
|
|
411
419
|
expect.objectContaining<Partial<BackendFederationRemoteEntryError>>({
|
|
@@ -414,3 +422,66 @@ describe('verified backend federation entry loading', () => {
|
|
|
414
422
|
);
|
|
415
423
|
});
|
|
416
424
|
});
|
|
425
|
+
|
|
426
|
+
describe('shared acquisition deadline', () => {
|
|
427
|
+
test.each([
|
|
428
|
+
'resource',
|
|
429
|
+
'entry',
|
|
430
|
+
] as const)('%s settles despite noncooperative stream cancellation', async kind => {
|
|
431
|
+
let cancelled = false;
|
|
432
|
+
const fetch = async () =>
|
|
433
|
+
new Response(
|
|
434
|
+
new ReadableStream<Uint8Array>({
|
|
435
|
+
cancel() {
|
|
436
|
+
cancelled = true;
|
|
437
|
+
return new Promise(() => {});
|
|
438
|
+
},
|
|
439
|
+
}),
|
|
440
|
+
);
|
|
441
|
+
const policy = { fetch, timeoutMs: 10 };
|
|
442
|
+
const operation =
|
|
443
|
+
kind === 'resource'
|
|
444
|
+
? loadBoundedBackendFederationResource(entryUrl, policy)
|
|
445
|
+
: loadVerifiedNodeEntry({
|
|
446
|
+
...policy,
|
|
447
|
+
remote: { entry: entryUrl, name: remoteName },
|
|
448
|
+
verification: verification(),
|
|
449
|
+
});
|
|
450
|
+
await expect(operation).rejects.toMatchObject({ code: 'timeout' });
|
|
451
|
+
expect(cancelled).toBe(true);
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
test('the entry deadline includes SHA-256 and never evaluates after expiration', async () => {
|
|
455
|
+
const evaluateCommonJs = rs.fn();
|
|
456
|
+
const digest = rs
|
|
457
|
+
.spyOn(globalThis.crypto.subtle, 'digest')
|
|
458
|
+
.mockImplementation(() => new Promise(() => {}));
|
|
459
|
+
try {
|
|
460
|
+
await expect(
|
|
461
|
+
loadVerifiedBackendFederationEntry({
|
|
462
|
+
fetch: async () => new Response(source),
|
|
463
|
+
timeoutMs: 10,
|
|
464
|
+
remote: { entry: entryUrl, name: remoteName },
|
|
465
|
+
verification: verification(),
|
|
466
|
+
evaluateCommonJs,
|
|
467
|
+
}),
|
|
468
|
+
).rejects.toMatchObject({ code: 'timeout' });
|
|
469
|
+
expect(evaluateCommonJs).not.toHaveBeenCalled();
|
|
470
|
+
} finally {
|
|
471
|
+
digest.mockRestore();
|
|
472
|
+
}
|
|
473
|
+
});
|
|
474
|
+
|
|
475
|
+
test('zero disables the timer while retaining exact-byte verification', async () => {
|
|
476
|
+
const entry = await loadVerifiedNodeEntry({
|
|
477
|
+
fetch: async () => {
|
|
478
|
+
await new Promise(resolve => setTimeout(resolve, 20));
|
|
479
|
+
return new Response(source);
|
|
480
|
+
},
|
|
481
|
+
timeoutMs: 0,
|
|
482
|
+
remote: { entry: entryUrl, name: remoteName },
|
|
483
|
+
verification: verification(),
|
|
484
|
+
});
|
|
485
|
+
expect(typeof entry.get).toBe('function');
|
|
486
|
+
});
|
|
487
|
+
});
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import 'reflect-metadata';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
2
5
|
import { z } from 'zod';
|
|
3
6
|
import {
|
|
4
7
|
buildOperationContractMap,
|
|
@@ -8,6 +11,8 @@ import {
|
|
|
8
11
|
deriveOperationVersion,
|
|
9
12
|
type OperationContractSource,
|
|
10
13
|
} from '../../src/bff-policy/operationContracts';
|
|
14
|
+
import { digestOperationContract } from '../../src/bff-policy/operationIdentity';
|
|
15
|
+
import { resolveOperationProducer } from '../../src/bff-policy/producer';
|
|
11
16
|
|
|
12
17
|
const createSchemaHandler = (schema: z.ZodType) => {
|
|
13
18
|
const handler = () => ({ ok: true });
|
|
@@ -16,6 +21,58 @@ const createSchemaHandler = (schema: z.ZodType) => {
|
|
|
16
21
|
};
|
|
17
22
|
|
|
18
23
|
describe('operation contract utilities', () => {
|
|
24
|
+
test('browser and Node hash the same canonical operation including nested schemas', async () => {
|
|
25
|
+
const operation = {
|
|
26
|
+
name: 'café',
|
|
27
|
+
httpMethod: 'post',
|
|
28
|
+
routePath: '/api/:id',
|
|
29
|
+
schemas: {
|
|
30
|
+
QUERY: {
|
|
31
|
+
properties: { z: { type: 'number' }, a: { enum: ['x', 'y'] } },
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
expect(await digestOperationContract(operation, 'producer')).toBe(
|
|
36
|
+
createOperationContractHash(operation, 'producer'),
|
|
37
|
+
);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test('resolves the owning producer beyond former depth limits and never borrows its parent version', () => {
|
|
41
|
+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'bff-producer-'));
|
|
42
|
+
const producer = path.join(root, 'producer');
|
|
43
|
+
const nested = path.join(
|
|
44
|
+
producer,
|
|
45
|
+
...Array.from({ length: 35 }, () => 'nested'),
|
|
46
|
+
);
|
|
47
|
+
fs.mkdirSync(nested, { recursive: true });
|
|
48
|
+
fs.writeFileSync(
|
|
49
|
+
path.join(root, 'package.json'),
|
|
50
|
+
JSON.stringify({ version: '99.0.0' }),
|
|
51
|
+
);
|
|
52
|
+
fs.writeFileSync(
|
|
53
|
+
path.join(producer, 'package.json'),
|
|
54
|
+
JSON.stringify({ name: 'producer', version: '3.1.0' }),
|
|
55
|
+
);
|
|
56
|
+
try {
|
|
57
|
+
const dependencies: string[] = [];
|
|
58
|
+
expect(
|
|
59
|
+
resolveOperationProducer({
|
|
60
|
+
directories: [nested, root],
|
|
61
|
+
onDependency: file => dependencies.push(file),
|
|
62
|
+
}),
|
|
63
|
+
).toEqual({ requestId: 'producer', operationVersion: 3 });
|
|
64
|
+
expect(dependencies).toEqual([path.join(producer, 'package.json')]);
|
|
65
|
+
fs.writeFileSync(path.join(producer, 'package.json'), '{broken');
|
|
66
|
+
expect(
|
|
67
|
+
resolveOperationProducer({
|
|
68
|
+
directories: [nested, root],
|
|
69
|
+
requestId: ' explicit ',
|
|
70
|
+
}),
|
|
71
|
+
).toEqual({ requestId: 'explicit', operationVersion: 1 });
|
|
72
|
+
} finally {
|
|
73
|
+
fs.rmSync(root, { recursive: true, force: true });
|
|
74
|
+
}
|
|
75
|
+
});
|
|
19
76
|
test('creates deterministic operation entries and aggregate hashes', () => {
|
|
20
77
|
const handlers = [
|
|
21
78
|
{
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { handleRequest } from '@modern-js/plugin-data-loader/runtime';
|
|
2
|
+
import { applyLocalisedUrlsToRoutes } from '@modern-js/runtime-extensions/localised-urls';
|
|
2
3
|
import {
|
|
3
4
|
createServerBase,
|
|
4
5
|
getLoaderCtx,
|
|
@@ -40,10 +41,12 @@ const routes = [
|
|
|
40
41
|
})),
|
|
41
42
|
];
|
|
42
43
|
|
|
44
|
+
let activeRoutes = routes;
|
|
45
|
+
|
|
43
46
|
const render: MiddlewareHandler = async context =>
|
|
44
47
|
(await handleRequest({
|
|
45
48
|
request: context.req.raw,
|
|
46
|
-
routes,
|
|
49
|
+
routes: activeRoutes,
|
|
47
50
|
serverRoutes: [
|
|
48
51
|
{
|
|
49
52
|
urlPath: '/base',
|
|
@@ -118,3 +121,35 @@ test('retains canonical routes and rejects loader IDs from another route', async
|
|
|
118
121
|
expect((await load('/base/cs/zdroje/item', 'search'))?.status).toBe(403);
|
|
119
122
|
expect((await load('/base/cs/hledat', 'missing'))?.status).toBe(403);
|
|
120
123
|
});
|
|
124
|
+
|
|
125
|
+
test('projects canonical routes for loader matching without rewriting the request URL', async () => {
|
|
126
|
+
const previous = activeRoutes;
|
|
127
|
+
activeRoutes = applyLocalisedUrlsToRoutes(
|
|
128
|
+
[
|
|
129
|
+
{
|
|
130
|
+
type: 'nested',
|
|
131
|
+
id: 'search',
|
|
132
|
+
path: ':lang/search',
|
|
133
|
+
loader: ({ params, request }) =>
|
|
134
|
+
Response.json({
|
|
135
|
+
language: params.lang,
|
|
136
|
+
url: request.url,
|
|
137
|
+
}),
|
|
138
|
+
},
|
|
139
|
+
] satisfies NestedRoute[],
|
|
140
|
+
['en', 'cs'],
|
|
141
|
+
{ '/search': { en: '/search', cs: '/hledat' } },
|
|
142
|
+
'canonical',
|
|
143
|
+
) as typeof routes;
|
|
144
|
+
try {
|
|
145
|
+
const response = await load('/base/cs/hledat?q=tractor', 'search');
|
|
146
|
+
expect(response?.status).toBe(200);
|
|
147
|
+
expect(await response?.json()).toEqual({
|
|
148
|
+
language: 'cs',
|
|
149
|
+
url: 'https://example.test/base/cs/hledat?q=tractor&__loader=search',
|
|
150
|
+
});
|
|
151
|
+
expect((await load('/base/cs/hledat', 'missing'))?.status).toBe(403);
|
|
152
|
+
} finally {
|
|
153
|
+
activeRoutes = previous;
|
|
154
|
+
}
|
|
155
|
+
});
|