@edynamix/mf-isolation 0.0.9 → 0.0.11

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/README.md CHANGED
@@ -95,6 +95,28 @@ export default defineConfig({
95
95
 
96
96
  Routes are module-relative and contain no leading slash. The plugin validates the complete tree, emits deterministic JSON with a SHA-256 revision during builds, and serves the same manifest with `Cache-Control: no-cache` in development.
97
97
 
98
+ For standalone development, combine the manifest with the host-owned navigation browser entry and development BFF:
99
+
100
+ ```ts
101
+ import {
102
+ MF_DEVELOPMENT_HOST_NAVIGATION_PATH,
103
+ mfDevelopmentBffPlugin,
104
+ } from '@edynamix/mf-isolation/vite-development';
105
+
106
+ mfDevelopmentBffPlugin({
107
+ hostNavigationUrl: 'https://host.example.test/host-navigation/index.js',
108
+ moduleApiOrigin: 'https://module.example.test',
109
+ moduleApiPath: '/stockmasterapi/',
110
+ });
111
+
112
+ const localHostNavigationUrl = new URL(
113
+ MF_DEVELOPMENT_HOST_NAVIGATION_PATH,
114
+ 'https://localhost:4200',
115
+ ).href;
116
+ ```
117
+
118
+ `hostNavigationUrl` selects the host environment. Load the browser entry from `localHostNavigationUrl`; the BFF serves the selected bundle and its host-owned logo assets through the secure local origin, avoiding mixed-content failures when the selected host is an HTTP localhost instance. Host API calls go to the selected host origin, while module API calls go to the explicit `moduleApiOrigin`. The BFF performs OIDC authorization code with PKCE, retains tokens and module API cookies in the development process, and forwards authenticated API requests without exposing either to module JavaScript. It also forwards the host-validated navigation selection through `X-Edyn-Navigation-Group-Id` and `X-Edyn-Navigation-Dealer-Id`; module backends must still authorize those values before constructing module-specific session state.
119
+
98
120
  ## Angular CDK overlays
99
121
 
100
122
  The Angular integration targets Angular/CDK 19.x. In a hosted application, install the complete provider array so global and connected overlays share the module boundary's viewport and coordinate system:
@@ -0,0 +1,24 @@
1
+ export declare const MF_HOST_NAVIGATION_CONTRACT_VERSION: 1;
2
+ export interface IMfHostNavigationMountOptions {
3
+ currentModuleId: string;
4
+ localManifestUrl?: string;
5
+ onLocalNavigate?: (path: string) => void;
6
+ target: HTMLElement;
7
+ }
8
+ export interface IMfHostNavigationHandle {
9
+ unmount: () => void;
10
+ updatePath: (path: string) => void;
11
+ }
12
+ export interface IMfHostNavigationApi {
13
+ readonly contractVersion: typeof MF_HOST_NAVIGATION_CONTRACT_VERSION;
14
+ mount: (options: IMfHostNavigationMountOptions) => IMfHostNavigationHandle;
15
+ }
16
+ export interface ILoadMfHostNavigationOptions {
17
+ hostNavigationUrl: string;
18
+ ownerDocument?: Document;
19
+ }
20
+ export interface IMountMfHostNavigationOptions extends IMfHostNavigationMountOptions, ILoadMfHostNavigationOptions {
21
+ }
22
+ export declare const loadMfHostNavigation: ({ hostNavigationUrl, ownerDocument, }: ILoadMfHostNavigationOptions) => Promise<IMfHostNavigationApi>;
23
+ export declare const mountMfHostNavigation: ({ hostNavigationUrl, ownerDocument, ...mountOptions }: IMountMfHostNavigationOptions) => Promise<IMfHostNavigationHandle>;
24
+ //# sourceMappingURL=host-navigation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-navigation.d.ts","sourceRoot":"","sources":["../src/host-navigation.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,mCAAmC,EAAG,CAAU,CAAC;AAE9D,MAAM,WAAW,6BAA6B;IAC5C,eAAe,EAAE,MAAM,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,eAAe,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACzC,MAAM,EAAE,WAAW,CAAC;CACrB;AAED,MAAM,WAAW,uBAAuB;IACtC,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,UAAU,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CACpC;AAED,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,eAAe,EAAE,OAAO,mCAAmC,CAAC;IACrE,KAAK,EAAE,CAAC,OAAO,EAAE,6BAA6B,KAAK,uBAAuB,CAAC;CAC5E;AAED,MAAM,WAAW,4BAA4B;IAC3C,iBAAiB,EAAE,MAAM,CAAC;IAC1B,aAAa,CAAC,EAAE,QAAQ,CAAC;CAC1B;AAED,MAAM,WAAW,6BAA8B,SAAQ,6BAA6B,EAAE,4BAA4B;CAAG;AAsFrH,eAAO,MAAM,oBAAoB,GAAI,uCAGlC,4BAA4B,KAAG,OAAO,CAAC,oBAAoB,CA8B7D,CAAC;AAEF,eAAO,MAAM,qBAAqB,GAAU,uDAIzC,6BAA6B,KAAG,OAAO,CAAC,uBAAuB,CAGjE,CAAC","sourcesContent":["export const MF_HOST_NAVIGATION_CONTRACT_VERSION = 1 as const;\n\nexport interface IMfHostNavigationMountOptions {\n currentModuleId: string;\n localManifestUrl?: string;\n onLocalNavigate?: (path: string) => void;\n target: HTMLElement;\n}\n\nexport interface IMfHostNavigationHandle {\n unmount: () => void;\n updatePath: (path: string) => void;\n}\n\nexport interface IMfHostNavigationApi {\n readonly contractVersion: typeof MF_HOST_NAVIGATION_CONTRACT_VERSION;\n mount: (options: IMfHostNavigationMountOptions) => IMfHostNavigationHandle;\n}\n\nexport interface ILoadMfHostNavigationOptions {\n hostNavigationUrl: string;\n ownerDocument?: Document;\n}\n\nexport interface IMountMfHostNavigationOptions extends IMfHostNavigationMountOptions, ILoadMfHostNavigationOptions {}\n\ninterface IMfHostNavigationWindow extends Window {\n EdynamixHostNavigation?: unknown;\n}\n\nconst pendingLoads = new WeakMap<Document, Map<string, Promise<IMfHostNavigationApi>>>();\nconst loadedUrls = new WeakMap<Window, string>();\n\nconst canonicalHostNavigationUrl = (candidate: string, ownerDocument: Document): string => {\n if (candidate.trim() === '') {\n throw new Error('hostNavigationUrl is required.');\n }\n\n let url: URL;\n try {\n url = new URL(candidate);\n } catch {\n throw new Error('hostNavigationUrl must be an absolute HTTP or HTTPS URL.');\n }\n\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new Error('hostNavigationUrl must use HTTP or HTTPS.');\n }\n if (url.username !== '' || url.password !== '') {\n throw new Error('hostNavigationUrl must not contain credentials.');\n }\n if (url.hash !== '') {\n throw new Error('hostNavigationUrl must not contain a fragment.');\n }\n if (url.protocol === 'http:' && url.hostname !== 'localhost' && url.hostname !== '127.0.0.1' && url.hostname !== ownerDocument.location.hostname) {\n throw new Error('Remote hostNavigationUrl values must use HTTPS.');\n }\n\n return url.href;\n};\n\nconst apiFrom = (ownerWindow: Window): IMfHostNavigationApi => {\n const candidate = (ownerWindow as IMfHostNavigationWindow).EdynamixHostNavigation;\n if (!candidate || typeof candidate !== 'object') {\n throw new Error('The host navigation script did not register its browser API.');\n }\n\n const api = candidate as Partial<IMfHostNavigationApi>;\n if (api.contractVersion !== MF_HOST_NAVIGATION_CONTRACT_VERSION || typeof api.mount !== 'function') {\n throw new Error(`Unsupported host navigation contract. Expected version ${MF_HOST_NAVIGATION_CONTRACT_VERSION}.`);\n }\n\n return api as IMfHostNavigationApi;\n};\n\nconst appendHostNavigationScript = (ownerDocument: Document, ownerWindow: Window, url: string): Promise<IMfHostNavigationApi> => {\n return new Promise((resolve, reject) => {\n const script = ownerDocument.createElement('script');\n script.async = true;\n script.crossOrigin = 'anonymous';\n script.dataset.edynHostNavigationLoader = url;\n script.src = url;\n\n script.addEventListener(\n 'load',\n () => {\n try {\n const api = apiFrom(ownerWindow);\n loadedUrls.set(ownerWindow, url);\n resolve(api);\n } catch (error) {\n script.remove();\n reject(error);\n }\n },\n { once: true },\n );\n script.addEventListener(\n 'error',\n () => {\n script.remove();\n reject(new Error(`The host navigation script could not be loaded from ${url}.`));\n },\n { once: true },\n );\n\n ownerDocument.head.append(script);\n });\n};\n\nexport const loadMfHostNavigation = ({\n hostNavigationUrl,\n ownerDocument = document,\n}: ILoadMfHostNavigationOptions): Promise<IMfHostNavigationApi> => {\n const ownerWindow = ownerDocument.defaultView;\n if (!ownerWindow) {\n return Promise.reject(new Error('The host navigation owner document must have a window.'));\n }\n\n const url = canonicalHostNavigationUrl(hostNavigationUrl, ownerDocument);\n const loadedUrl = loadedUrls.get(ownerWindow);\n if (loadedUrl) {\n if (loadedUrl !== url) {\n return Promise.reject(new Error(`Host navigation is already loaded from ${loadedUrl}.`));\n }\n return Promise.resolve(apiFrom(ownerWindow));\n }\n\n const documentLoads = pendingLoads.get(ownerDocument) ?? new Map<string, Promise<IMfHostNavigationApi>>();\n pendingLoads.set(ownerDocument, documentLoads);\n const pending = documentLoads.get(url);\n if (pending) {\n return pending;\n }\n\n const load = appendHostNavigationScript(ownerDocument, ownerWindow, url).finally(() => {\n documentLoads.delete(url);\n if (documentLoads.size === 0) {\n pendingLoads.delete(ownerDocument);\n }\n });\n documentLoads.set(url, load);\n return load;\n};\n\nexport const mountMfHostNavigation = async ({\n hostNavigationUrl,\n ownerDocument = document,\n ...mountOptions\n}: IMountMfHostNavigationOptions): Promise<IMfHostNavigationHandle> => {\n const api = await loadMfHostNavigation({ hostNavigationUrl, ownerDocument });\n return api.mount(mountOptions);\n};\n"]}
@@ -0,0 +1,97 @@
1
+ export const MF_HOST_NAVIGATION_CONTRACT_VERSION = 1;
2
+ const pendingLoads = new WeakMap();
3
+ const loadedUrls = new WeakMap();
4
+ const canonicalHostNavigationUrl = (candidate, ownerDocument) => {
5
+ if (candidate.trim() === '') {
6
+ throw new Error('hostNavigationUrl is required.');
7
+ }
8
+ let url;
9
+ try {
10
+ url = new URL(candidate);
11
+ }
12
+ catch {
13
+ throw new Error('hostNavigationUrl must be an absolute HTTP or HTTPS URL.');
14
+ }
15
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
16
+ throw new Error('hostNavigationUrl must use HTTP or HTTPS.');
17
+ }
18
+ if (url.username !== '' || url.password !== '') {
19
+ throw new Error('hostNavigationUrl must not contain credentials.');
20
+ }
21
+ if (url.hash !== '') {
22
+ throw new Error('hostNavigationUrl must not contain a fragment.');
23
+ }
24
+ if (url.protocol === 'http:' && url.hostname !== 'localhost' && url.hostname !== '127.0.0.1' && url.hostname !== ownerDocument.location.hostname) {
25
+ throw new Error('Remote hostNavigationUrl values must use HTTPS.');
26
+ }
27
+ return url.href;
28
+ };
29
+ const apiFrom = (ownerWindow) => {
30
+ const candidate = ownerWindow.EdynamixHostNavigation;
31
+ if (!candidate || typeof candidate !== 'object') {
32
+ throw new Error('The host navigation script did not register its browser API.');
33
+ }
34
+ const api = candidate;
35
+ if (api.contractVersion !== MF_HOST_NAVIGATION_CONTRACT_VERSION || typeof api.mount !== 'function') {
36
+ throw new Error(`Unsupported host navigation contract. Expected version ${MF_HOST_NAVIGATION_CONTRACT_VERSION}.`);
37
+ }
38
+ return api;
39
+ };
40
+ const appendHostNavigationScript = (ownerDocument, ownerWindow, url) => {
41
+ return new Promise((resolve, reject) => {
42
+ const script = ownerDocument.createElement('script');
43
+ script.async = true;
44
+ script.crossOrigin = 'anonymous';
45
+ script.dataset.edynHostNavigationLoader = url;
46
+ script.src = url;
47
+ script.addEventListener('load', () => {
48
+ try {
49
+ const api = apiFrom(ownerWindow);
50
+ loadedUrls.set(ownerWindow, url);
51
+ resolve(api);
52
+ }
53
+ catch (error) {
54
+ script.remove();
55
+ reject(error);
56
+ }
57
+ }, { once: true });
58
+ script.addEventListener('error', () => {
59
+ script.remove();
60
+ reject(new Error(`The host navigation script could not be loaded from ${url}.`));
61
+ }, { once: true });
62
+ ownerDocument.head.append(script);
63
+ });
64
+ };
65
+ export const loadMfHostNavigation = ({ hostNavigationUrl, ownerDocument = document, }) => {
66
+ const ownerWindow = ownerDocument.defaultView;
67
+ if (!ownerWindow) {
68
+ return Promise.reject(new Error('The host navigation owner document must have a window.'));
69
+ }
70
+ const url = canonicalHostNavigationUrl(hostNavigationUrl, ownerDocument);
71
+ const loadedUrl = loadedUrls.get(ownerWindow);
72
+ if (loadedUrl) {
73
+ if (loadedUrl !== url) {
74
+ return Promise.reject(new Error(`Host navigation is already loaded from ${loadedUrl}.`));
75
+ }
76
+ return Promise.resolve(apiFrom(ownerWindow));
77
+ }
78
+ const documentLoads = pendingLoads.get(ownerDocument) ?? new Map();
79
+ pendingLoads.set(ownerDocument, documentLoads);
80
+ const pending = documentLoads.get(url);
81
+ if (pending) {
82
+ return pending;
83
+ }
84
+ const load = appendHostNavigationScript(ownerDocument, ownerWindow, url).finally(() => {
85
+ documentLoads.delete(url);
86
+ if (documentLoads.size === 0) {
87
+ pendingLoads.delete(ownerDocument);
88
+ }
89
+ });
90
+ documentLoads.set(url, load);
91
+ return load;
92
+ };
93
+ export const mountMfHostNavigation = async ({ hostNavigationUrl, ownerDocument = document, ...mountOptions }) => {
94
+ const api = await loadMfHostNavigation({ hostNavigationUrl, ownerDocument });
95
+ return api.mount(mountOptions);
96
+ };
97
+ //# sourceMappingURL=host-navigation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-navigation.js","sourceRoot":"","sources":["../src/host-navigation.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,mCAAmC,GAAG,CAAU,CAAC;AA8B9D,MAAM,YAAY,GAAG,IAAI,OAAO,EAAwD,CAAC;AACzF,MAAM,UAAU,GAAG,IAAI,OAAO,EAAkB,CAAC;AAEjD,MAAM,0BAA0B,GAAG,CAAC,SAAiB,EAAE,aAAuB,EAAU,EAAE;IACxF,IAAI,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;IACpD,CAAC;IAED,IAAI,GAAQ,CAAC;IACb,IAAI,CAAC;QACH,GAAG,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,CAAC;IAC3B,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC9E,CAAC;IAED,IAAI,GAAG,CAAC,QAAQ,KAAK,OAAO,IAAI,GAAG,CAAC,QAAQ,KAAK,QAAQ,EAAE,CAAC;QAC1D,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;IAC/D,CAA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AAG,GAAG,MAAM,oBAAoB,CAAC,EAAE,iBAAiB,EAAE,aAAa,EAAE,CAAC,CAAC;IAC7E,OAAO,GAAG,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;AACjC,CAAC,CAAC","sourcesContent":["export const MF_HOST_NAVIGATION_CONTRACT_VERSION = 1 as const;\n\nexport interface IMfHostNavigationMountOptions {\n currentModuleId: string;\n localManifestUrl?: string;\n onLocalNavigate?: (path: string) => void;\n target: HTMLElement;\n}\n\nexport interface IMfHostNavigationHandle {\n unmount: () => void;\n updatePath: (path: string) => void;\n}\n\nexport interface IMfHostNavigationApi {\n readonly contractVersion: typeof MF_HOST_NAVIGATION_CONTRACT_VERSION;\n mount: (options: IMfHostNavigationMountOptions) => IMfHostNavigationHandle;\n}\n\nexport interface ILoadMfHostNavigationOptions {\n hostNavigationUrl: string;\n ownerDocument?: Document;\n}\n\nexport interface IMountMfHostNavigationOptions extends IMfHostNavigationMountOptions, ILoadMfHostNavigationOptions {}\n\ninterface IMfHostNavigationWindow extends Window {\n EdynamixHostNavigation?: unknown;\n}\n\nconst pendingLoads = new WeakMap<Document, Map<string, Promise<IMfHostNavigationApi>>>();\nconst loadedUrls = new WeakMap<Window, string>();\n\nconst canonicalHostNavigationUrl = (candidate: string, ownerDocument: Document): string => {\n if (candidate.trim() === '') {\n throw new Error('hostNavigationUrl is required.');\n }\n\n let url: URL;\n try {\n url = new URL(candidate);\n } catch {\n throw new Error('hostNavigationUrl must be an absolute HTTP or HTTPS URL.');\n }\n\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new Error('hostNavigationUrl must use HTTP or HTTPS.');\n }\n if (url.username !== '' || url.password !== '') {\n throw new Error('hostNavigationUrl must not contain credentials.');\n }\n if (url.hash !== '') {\n throw new Error('hostNavigationUrl must not contain a fragment.');\n }\n if (url.protocol === 'http:' && url.hostname !== 'localhost' && url.hostname !== '127.0.0.1' && url.hostname !== ownerDocument.location.hostname) {\n throw new Error('Remote hostNavigationUrl values must use HTTPS.');\n }\n\n return url.href;\n};\n\nconst apiFrom = (ownerWindow: Window): IMfHostNavigationApi => {\n const candidate = (ownerWindow as IMfHostNavigationWindow).EdynamixHostNavigation;\n if (!candidate || typeof candidate !== 'object') {\n throw new Error('The host navigation script did not register its browser API.');\n }\n\n const api = candidate as Partial<IMfHostNavigationApi>;\n if (api.contractVersion !== MF_HOST_NAVIGATION_CONTRACT_VERSION || typeof api.mount !== 'function') {\n throw new Error(`Unsupported host navigation contract. Expected version ${MF_HOST_NAVIGATION_CONTRACT_VERSION}.`);\n }\n\n return api as IMfHostNavigationApi;\n};\n\nconst appendHostNavigationScript = (ownerDocument: Document, ownerWindow: Window, url: string): Promise<IMfHostNavigationApi> => {\n return new Promise((resolve, reject) => {\n const script = ownerDocument.createElement('script');\n script.async = true;\n script.crossOrigin = 'anonymous';\n script.dataset.edynHostNavigationLoader = url;\n script.src = url;\n\n script.addEventListener(\n 'load',\n () => {\n try {\n const api = apiFrom(ownerWindow);\n loadedUrls.set(ownerWindow, url);\n resolve(api);\n } catch (error) {\n script.remove();\n reject(error);\n }\n },\n { once: true },\n );\n script.addEventListener(\n 'error',\n () => {\n script.remove();\n reject(new Error(`The host navigation script could not be loaded from ${url}.`));\n },\n { once: true },\n );\n\n ownerDocument.head.append(script);\n });\n};\n\nexport const loadMfHostNavigation = ({\n hostNavigationUrl,\n ownerDocument = document,\n}: ILoadMfHostNavigationOptions): Promise<IMfHostNavigationApi> => {\n const ownerWindow = ownerDocument.defaultView;\n if (!ownerWindow) {\n return Promise.reject(new Error('The host navigation owner document must have a window.'));\n }\n\n const url = canonicalHostNavigationUrl(hostNavigationUrl, ownerDocument);\n const loadedUrl = loadedUrls.get(ownerWindow);\n if (loadedUrl) {\n if (loadedUrl !== url) {\n return Promise.reject(new Error(`Host navigation is already loaded from ${loadedUrl}.`));\n }\n return Promise.resolve(apiFrom(ownerWindow));\n }\n\n const documentLoads = pendingLoads.get(ownerDocument) ?? new Map<string, Promise<IMfHostNavigationApi>>();\n pendingLoads.set(ownerDocument, documentLoads);\n const pending = documentLoads.get(url);\n if (pending) {\n return pending;\n }\n\n const load = appendHostNavigationScript(ownerDocument, ownerWindow, url).finally(() => {\n documentLoads.delete(url);\n if (documentLoads.size === 0) {\n pendingLoads.delete(ownerDocument);\n }\n });\n documentLoads.set(url, load);\n return load;\n};\n\nexport const mountMfHostNavigation = async ({\n hostNavigationUrl,\n ownerDocument = document,\n ...mountOptions\n}: IMountMfHostNavigationOptions): Promise<IMfHostNavigationHandle> => {\n const api = await loadMfHostNavigation({ hostNavigationUrl, ownerDocument });\n return api.mount(mountOptions);\n};\n"]}
@@ -0,0 +1,13 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { Plugin } from 'vite';
3
+ export declare const MF_DEVELOPMENT_HOST_NAVIGATION_PATH = "/api/dev-host-navigation/index.js";
4
+ export interface IMfDevelopmentBffPluginOptions {
5
+ developmentOrigin?: string;
6
+ hostNavigationUrl: string;
7
+ moduleApiOrigin: string;
8
+ moduleApiPath: string;
9
+ }
10
+ export declare const mfDevelopmentBffPlugin: (options: IMfDevelopmentBffPluginOptions) => Plugin;
11
+ export type TMfDevelopmentBffMiddleware = (request: IncomingMessage, response: ServerResponse, next: (error?: unknown) => void) => void;
12
+ export declare const createMfDevelopmentBffMiddleware: (options: IMfDevelopmentBffPluginOptions) => TMfDevelopmentBffMiddleware;
13
+ //# sourceMappingURL=vite-development.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite-development.d.ts","sourceRoot":"","sources":["../src/vite-development.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAGjE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAQnC,eAAO,MAAM,mCAAmC,sCAAsC,CAAC;AAuEvF,MAAM,WAAW,8BAA8B;IAC7C,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,MAAM,CAAC;CACvB;AAusBD,eAAO,MAAM,sBAAsB,GAAI,SAAS,8BAA8B,KAAG,MAWhF,CAAC;AAEF,MAAM,MAAM,2BAA2B,GAAG,CAAC,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,IAAI,KAAK,IAAI,CAAC;AAExI,eAAO,MAAM,gCAAgC,GAAI,SAAS,8BAA8B,KAAG,2BAK1F,CAAC","sourcesContent":["import { createHash, randomBytes } from 'node:crypto';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { Readable } from 'node:stream';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport type { Plugin } from 'vite';\n\nconst SESSION_COOKIE = '__Host-edyn_dev_session';\nconst FLOW_COOKIE = '__Host-edyn_oidc_flow';\nconst LOGOUT_COOKIE = '__Host-edyn_oidc_logout';\nconst CALLBACK_PATH = '/callback';\nconst LOGGED_OUT_PATH = '/logged-out';\nconst LOGIN_PATH = '/api/dev-auth/login';\nexport const MF_DEVELOPMENT_HOST_NAVIGATION_PATH = '/api/dev-host-navigation/index.js';\nconst HOST_NAVIGATION_ASSET_PATHS = new Set(['/exsto-icon.svg', '/exsto-text.svg']);\nconst MAX_HOST_NAVIGATION_BYTES = 5 * 1024 * 1024;\nconst MAX_HOST_NAVIGATION_ASSET_BYTES = 512 * 1024;\nconst SESSION_MAX_AGE_SECONDS = 8 * 60 * 60;\nconst FLOW_MAX_AGE_SECONDS = 10 * 60;\nconst TOKEN_REFRESH_SKEW_MS = 30_000;\nconst NAVIGATION_GROUP_HEADER = 'X-Edyn-Navigation-Group-Id';\nconst NAVIGATION_DEALER_HEADER = 'X-Edyn-Navigation-Dealer-Id';\nconst COOKIE_NAME_PATTERN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst COOKIE_VALUE_PATTERN = /^[\\x20-\\x7e]*$/;\nconst ALLOWED_HOST_API_PATHS = [\n '/api/auth/me',\n '/api/navigation',\n '/api/navigation/access-check',\n '/api/navigation/access-request',\n '/api/navigation/counter-stream',\n] as const;\n\ninterface IOidcClientConfiguration {\n clientId: string;\n issuer: string;\n scope: string;\n}\n\ninterface IOidcDiscovery {\n authorizationEndpoint: string;\n endSessionEndpoint: string;\n issuer: string;\n jwksUri: string;\n revocationEndpoint: string | null;\n tokenEndpoint: string;\n}\n\ninterface IOidcFlow {\n codeVerifier: string;\n createdAt: number;\n nonce: string;\n returnTo: string;\n state: string;\n}\n\ninterface IModuleNavigationContext {\n dealerId: number;\n groupId: number;\n}\n\ninterface ITokenSession {\n accessToken: string;\n expiresAt: number;\n idToken: string;\n moduleBootstrapTail: Promise<void>;\n moduleCookies: Map<string, string>;\n moduleNavigationContext: IModuleNavigationContext | null;\n refreshPromise?: Promise<void>;\n refreshToken: string | null;\n}\n\ninterface ILogoutFlow {\n createdAt: number;\n idToken: string | null;\n}\n\ninterface ITokenResponse {\n accessToken: string;\n expiresIn: number;\n idToken: string | null;\n refreshToken: string | null;\n tokenType: string;\n}\n\nexport interface IMfDevelopmentBffPluginOptions {\n developmentOrigin?: string;\n hostNavigationUrl: string;\n moduleApiOrigin: string;\n moduleApiPath: string;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst requiredString = (value: Record<string, unknown>, key: string): string => {\n const candidate = value[key];\n if (typeof candidate !== 'string' || candidate.trim() === '') {\n throw new Error(`OIDC response is missing ${key}.`);\n }\n return candidate;\n};\n\nconst optionalString = (value: Record<string, unknown>, key: string): string | null => {\n const candidate = value[key];\n if (candidate === undefined || candidate === null) {\n return null;\n }\n if (typeof candidate !== 'string' || candidate.trim() === '') {\n throw new Error(`OIDC response contains an invalid ${key}.`);\n }\n return candidate;\n};\n\nconst absoluteHttpsUrl = (candidate: string, label: string, allowLocalHttp = false): URL => {\n let url: URL;\n try {\n url = new URL(candidate);\n } catch {\n throw new Error(`${label} must be an absolute URL.`);\n }\n const isLocalHttp = allowLocalHttp && url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1');\n if (url.protocol !== 'https:' && !isLocalHttp) {\n throw new Error(`${label} must use HTTPS.`);\n }\n if (url.username || url.password || url.hash) {\n throw new Error(`${label} must not contain credentials or a fragment.`);\n }\n return url;\n};\n\nconst moduleApiPrefix = (candidate: string): string => {\n if (!/^\\/[a-z][a-z0-9-]*api\\/$/.test(candidate)) {\n throw new Error('moduleApiPath must look like /moduleapi/.');\n }\n return candidate;\n};\n\nconst base64Url = (size = 32): string => randomBytes(size).toString('base64url');\nconst codeChallengeOf = (verifier: string): string => createHash('sha256').update(verifier).digest('base64url');\n\nconst cookiesOf = (request: IncomingMessage): ReadonlyMap<string, string> => {\n const cookies = new Map<string, string>();\n for (const part of (request.headers.cookie ?? '').split(';')) {\n const separator = part.indexOf('=');\n if (separator <= 0) {\n continue;\n }\n const name = part.slice(0, separator).trim();\n const value = part.slice(separator + 1).trim();\n if (name && value) {\n cookies.set(name, value);\n }\n }\n return cookies;\n};\n\nconst cookie = (name: string, value: string, maxAge: number): string => `${name}=${value}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAge}`;\n\nconst clearCookie = (name: string): string => cookie(name, '', 0);\n\nconst writeJson = (response: ServerResponse, status: number, body: unknown): void => {\n response.statusCode = status;\n response.setHeader('Cache-Control', 'no-store');\n response.setHeader('Content-Type', 'application/json; charset=utf-8');\n response.end(JSON.stringify(body));\n};\n\nconst redirect = (response: ServerResponse, location: string, cookies: string[] = []): void => {\n response.statusCode = 302;\n response.setHeader('Cache-Control', 'no-store');\n response.setHeader('Location', location);\n if (cookies.length > 0) {\n response.setHeader('Set-Cookie', cookies);\n }\n response.end();\n};\n\nconst safeReturnTo = (candidate: string | null): string => {\n if (!candidate?.startsWith('/') || candidate.startsWith('//')) {\n return '/';\n }\n try {\n const parsed = new URL(candidate, 'https://localhost');\n return `${parsed.pathname}${parsed.search}${parsed.hash}`;\n } catch {\n return '/';\n }\n};\n\nconst parseTokenResponse = (value: unknown, requireIdToken: boolean): ITokenResponse => {\n if (!isRecord(value)) {\n throw new Error('OIDC token endpoint returned an invalid response.');\n }\n const expiresIn = value.expires_in;\n if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0) {\n throw new Error('OIDC token endpoint returned an invalid expires_in value.');\n }\n const idToken = optionalString(value, 'id_token');\n if (requireIdToken && !idToken) {\n throw new Error('OIDC token endpoint did not return an ID token.');\n }\n const tokenType = requiredString(value, 'token_type');\n if (tokenType.toLowerCase() !== 'bearer') {\n throw new Error('OIDC token endpoint returned an unsupported token type.');\n }\n return {\n accessToken: requiredString(value, 'access_token'),\n expiresIn,\n idToken,\n refreshToken: optionalString(value, 'refresh_token'),\n tokenType,\n };\n};\n\nconst pathIsHostApi = (path: string): boolean => {\n return ALLOWED_HOST_API_PATHS.some((candidate) => path === candidate || path.startsWith(`${candidate}/`));\n};\n\nconst proxyHeaders = (\n request: IncomingMessage,\n accessToken: string,\n moduleCookies?: Map<string, string>,\n navigationContext?: IModuleNavigationContext | null,\n): Headers => {\n const headers = new Headers();\n for (const [name, value] of Object.entries(request.headers)) {\n if (\n !value ||\n [\n 'authorization',\n 'connection',\n 'content-length',\n 'cookie',\n 'host',\n 'origin',\n 'transfer-encoding',\n NAVIGATION_GROUP_HEADER.toLowerCase(),\n NAVIGATION_DEALER_HEADER.toLowerCase(),\n ].includes(name.toLowerCase())\n ) {\n continue;\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(name, item);\n }\n } else {\n headers.set(name, value);\n }\n }\n headers.set('Authorization', `Bearer ${accessToken}`);\n if (moduleCookies?.size) {\n headers.set('Cookie', [...moduleCookies.values()].join('; '));\n }\n if (navigationContext) {\n headers.set(NAVIGATION_GROUP_HEADER, String(navigationContext.groupId));\n headers.set(NAVIGATION_DEALER_HEADER, String(navigationContext.dealerId));\n }\n return headers;\n};\n\nconst navigationContextIn = (value: unknown): IModuleNavigationContext | null => {\n if (!isRecord(value) || !isRecord(value.context)) {\n return null;\n }\n const groupId = value.context.selectedGroupId;\n const dealerId = value.context.selectedDealerId;\n if (!Number.isSafeInteger(groupId) || (groupId as number) <= 0 || !Number.isSafeInteger(dealerId) || (dealerId as number) < 0) {\n return null;\n }\n return { dealerId: dealerId as number, groupId: groupId as number };\n};\n\nconst updateModuleCookies = (cookies: Map<string, string>, headers: Headers): void => {\n const values = headers.getSetCookie();\n for (const value of values) {\n if (value.length > 4096) {\n continue;\n }\n const [pair, ...attributes] = value.split(';');\n const separator = pair?.indexOf('=') ?? -1;\n if (!pair || separator <= 0) {\n continue;\n }\n const name = pair.slice(0, separator).trim();\n const cookieValue = pair.slice(separator + 1).trim();\n if (!COOKIE_NAME_PATTERN.test(name) || !COOKIE_VALUE_PATTERN.test(cookieValue) || cookieValue.includes(';')) {\n continue;\n }\n const deleted = cookieValue === '' || attributes.some((attribute) => /^\\s*max-age\\s*=\\s*0\\s*$/i.test(attribute));\n if (deleted) {\n cookies.delete(name);\n continue;\n }\n if (!cookies.has(name) && cookies.size >= 32) {\n continue;\n }\n cookies.set(name, `${name}=${cookieValue}`);\n }\n};\n\nconst copyProxyResponse = async (upstream: Response, response: ServerResponse): Promise<void> => {\n response.statusCode = upstream.status;\n for (const [name, value] of upstream.headers) {\n if (!['connection', 'content-encoding', 'content-length', 'set-cookie', 'transfer-encoding'].includes(name.toLowerCase())) {\n response.setHeader(name, value);\n }\n }\n response.setHeader('Cache-Control', upstream.headers.get('cache-control') ?? 'no-store');\n if (!upstream.body) {\n response.end();\n return;\n }\n await new Promise<void>((resolve, reject) => {\n const readable = Readable.fromWeb(upstream.body as never);\n readable.once('error', reject);\n response.once('error', reject);\n response.once('finish', resolve);\n readable.pipe(response);\n });\n};\n\nconst readResponseBody = async (response: Response, maximumBytes: number, label: string): Promise<Buffer> => {\n const declaredLength = Number(response.headers.get('content-length'));\n if (Number.isFinite(declaredLength) && declaredLength > maximumBytes) {\n await response.body?.cancel();\n throw new Error(`${label} exceeded the configured size limit.`);\n }\n if (!response.body) {\n return Buffer.alloc(0);\n }\n\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let totalBytes = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n totalBytes += value.byteLength;\n if (totalBytes > maximumBytes) {\n await reader.cancel();\n throw new Error(`${label} exceeded the configured size limit.`);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks, totalBytes);\n};\n\nclass MfDevelopmentBff {\n readonly #configurationUrl: URL;\n readonly #developmentOrigin: URL;\n readonly #flows = new Map<string, IOidcFlow>();\n readonly #hostOrigin: URL;\n readonly #hostNavigationUrl: URL;\n readonly #jwks = new Map<string, ReturnType<typeof createRemoteJWKSet>>();\n readonly #logoutFlows = new Map<string, ILogoutFlow>();\n readonly #moduleApiOrigin: URL;\n readonly #moduleApiPath: string;\n readonly #sessions = new Map<string, ITokenSession>();\n #configurationPromise: Promise<IOidcClientConfiguration> | null = null;\n #discoveryPromise: Promise<IOidcDiscovery> | null = null;\n\n constructor(options: IMfDevelopmentBffPluginOptions) {\n const hostNavigation = absoluteHttpsUrl(options.hostNavigationUrl, 'hostNavigationUrl', true);\n this.#hostNavigationUrl = hostNavigation;\n this.#hostOrigin = new URL(hostNavigation.origin);\n this.#configurationUrl = new URL('/api/auth/oidc-configuration', this.#hostOrigin);\n this.#developmentOrigin = absoluteHttpsUrl(options.developmentOrigin ?? 'https://localhost:4200', 'developmentOrigin');\n if (this.#developmentOrigin.pathname !== '/' || this.#developmentOrigin.search || this.#developmentOrigin.hash) {\n throw new Error('developmentOrigin must be an origin without a path, query, or fragment.');\n }\n this.#moduleApiOrigin = absoluteHttpsUrl(options.moduleApiOrigin, 'moduleApiOrigin', true);\n if (this.#moduleApiOrigin.pathname !== '/' || this.#moduleApiOrigin.search || this.#moduleApiOrigin.hash) {\n throw new Error('moduleApiOrigin must be an origin without a path, query, or fragment.');\n }\n this.#moduleApiPath = moduleApiPrefix(options.moduleApiPath);\n }\n\n async handle(request: IncomingMessage, response: ServerResponse, next: (error?: unknown) => void): Promise<void> {\n if (!request.url || !request.method) {\n next();\n return;\n }\n const url = new URL(request.url, this.#developmentOrigin);\n this.#prune();\n\n try {\n if (request.method === 'GET' && url.pathname === MF_DEVELOPMENT_HOST_NAVIGATION_PATH) {\n await this.#hostNavigationResource(response, this.#hostNavigationUrl, 'script');\n return;\n }\n if (request.method === 'GET' && HOST_NAVIGATION_ASSET_PATHS.has(url.pathname)) {\n await this.#hostNavigationResource(response, new URL(url.pathname, this.#hostOrigin), 'asset');\n return;\n }\n if (request.method === 'GET' && url.pathname === LOGIN_PATH) {\n await this.#login(request, response, safeReturnTo(url.searchParams.get('returnTo')));\n return;\n }\n if (request.method === 'GET' && url.pathname === CALLBACK_PATH) {\n await this.#callback(request, response, url);\n return;\n }\n if (request.method === 'GET' && url.pathname === LOGGED_OUT_PATH) {\n const returnTo = safeReturnTo(url.searchParams.get('state'));\n redirect(response, `${LOGIN_PATH}?returnTo=${encodeURIComponent(returnTo)}`, [clearCookie(LOGOUT_COOKIE)]);\n return;\n }\n if (request.method === 'GET' && url.pathname === '/frontchannel-logout') {\n const sessionId = cookiesOf(request).get(SESSION_COOKIE);\n if (sessionId) {\n this.#sessions.delete(sessionId);\n }\n response.statusCode = 204;\n response.setHeader('Set-Cookie', clearCookie(SESSION_COOKIE));\n response.end();\n return;\n }\n if (request.method === 'POST' && url.pathname === '/api/auth/logout') {\n await this.#logout(request, response);\n return;\n }\n if (pathIsHostApi(url.pathname) || url.pathname.startsWith(this.#moduleApiPath)) {\n await this.#proxy(request, response, url);\n return;\n }\n next();\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Development authentication failed.';\n writeJson(response, 502, { code: 'development_authentication_failed', error: message });\n }\n }\n\n async #hostNavigationResource(response: ServerResponse, upstreamUrl: URL, kind: 'asset' | 'script'): Promise<void> {\n const upstream = await fetch(upstreamUrl, {\n headers: { Accept: kind === 'script' ? 'text/javascript, application/javascript' : 'image/svg+xml' },\n redirect: 'error',\n });\n if (!upstream.ok) {\n throw new Error(`Host navigation ${kind} failed (${upstream.status}).`);\n }\n const contentType = upstream.headers.get('content-type') ?? '';\n const validContentType =\n kind === 'script' ? /^(?:text|application)\\/javascript(?:;|$)/i.test(contentType) : /^image\\/svg\\+xml(?:;|$)/i.test(contentType);\n if (!validContentType) {\n throw new Error(`Host navigation ${kind} returned an invalid content type.`);\n }\n const maximumBytes = kind === 'script' ? MAX_HOST_NAVIGATION_BYTES : MAX_HOST_NAVIGATION_ASSET_BYTES;\n const body = await readResponseBody(upstream, maximumBytes, `Host navigation ${kind}`);\n response.statusCode = 200;\n response.setHeader('Cache-Control', 'no-store');\n response.setHeader('Content-Type', contentType);\n response.setHeader('X-Content-Type-Options', 'nosniff');\n response.end(body);\n }\n\n async #configuration(): Promise<IOidcClientConfiguration> {\n this.#configurationPromise ??= fetch(this.#configurationUrl, { headers: { Accept: 'application/json' }, redirect: 'error' })\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Host OIDC configuration failed (${response.status}).`);\n }\n const value: unknown = await response.json();\n if (!isRecord(value)) {\n throw new Error('Host OIDC configuration returned an invalid response.');\n }\n const issuer = absoluteHttpsUrl(requiredString(value, 'issuer'), 'OIDC issuer', true).href.replace(/\\/$/, '');\n return { clientId: requiredString(value, 'clientId'), issuer, scope: requiredString(value, 'scope') };\n })\n .catch((error) => {\n this.#configurationPromise = null;\n throw error;\n });\n return this.#configurationPromise;\n }\n\n async #discovery(): Promise<IOidcDiscovery> {\n this.#discoveryPromise ??= this.#configuration()\n .then(async (configuration) => {\n const response = await fetch(`${configuration.issuer}/.well-known/openid-configuration`, {\n headers: { Accept: 'application/json' },\n redirect: 'error',\n });\n if (!response.ok) {\n throw new Error(`OIDC discovery failed (${response.status}).`);\n }\n const value: unknown = await response.json();\n if (!isRecord(value)) {\n throw new Error('OIDC discovery returned an invalid response.');\n }\n const issuer = absoluteHttpsUrl(requiredString(value, 'issuer'), 'OIDC discovery issuer', true).href.replace(/\\/$/, '');\n if (issuer !== configuration.issuer) {\n throw new Error('OIDC discovery issuer does not match the host configuration.');\n }\n const endpoint = (key: string): string => {\n const url = absoluteHttpsUrl(requiredString(value, key), `OIDC ${key}`, true);\n if (url.origin !== new URL(issuer).origin) {\n throw new Error(`OIDC ${key} must use the configured issuer origin.`);\n }\n return url.href;\n };\n const revocation = optionalString(value, 'revocation_endpoint');\n return {\n authorizationEndpoint: endpoint('authorization_endpoint'),\n endSessionEndpoint: endpoint('end_session_endpoint'),\n issuer,\n jwksUri: endpoint('jwks_uri'),\n revocationEndpoint: revocation ? endpoint('revocation_endpoint') : null,\n tokenEndpoint: endpoint('token_endpoint'),\n };\n })\n .catch((error) => {\n this.#discoveryPromise = null;\n throw error;\n });\n return this.#discoveryPromise;\n }\n\n async #login(request: IncomingMessage, response: ServerResponse, returnTo: string): Promise<void> {\n const logoutId = cookiesOf(request).get(LOGOUT_COOKIE);\n if (logoutId) {\n const logout = this.#logoutFlows.get(logoutId);\n this.#logoutFlows.delete(logoutId);\n if (logout) {\n const [configuration, discovery] = await Promise.all([this.#configuration(), this.#discovery()]);\n const endpoint = new URL(discovery.endSessionEndpoint);\n endpoint.searchParams.set('client_id', configuration.clientId);\n endpoint.searchParams.set('post_logout_redirect_uri', new URL(LOGGED_OUT_PATH, this.#developmentOrigin).href);\n endpoint.searchParams.set('state', returnTo);\n if (logout.idToken) {\n endpoint.searchParams.set('id_token_hint', logout.idToken);\n }\n redirect(response, endpoint.href, [clearCookie(LOGOUT_COOKIE)]);\n return;\n }\n }\n\n const [configuration, discovery] = await Promise.all([this.#configuration(), this.#discovery()]);\n const flowId = base64Url();\n const codeVerifier = base64Url(48);\n const flow: IOidcFlow = { codeVerifier, createdAt: Date.now(), nonce: base64Url(), returnTo, state: base64Url() };\n this.#flows.set(flowId, flow);\n\n const endpoint = new URL(discovery.authorizationEndpoint);\n endpoint.searchParams.set('response_type', 'code');\n endpoint.searchParams.set('client_id', configuration.clientId);\n endpoint.searchParams.set('redirect_uri', new URL(CALLBACK_PATH, this.#developmentOrigin).href);\n endpoint.searchParams.set('scope', configuration.scope);\n endpoint.searchParams.set('state', flow.state);\n endpoint.searchParams.set('nonce', flow.nonce);\n endpoint.searchParams.set('code_challenge', codeChallengeOf(codeVerifier));\n endpoint.searchParams.set('code_challenge_method', 'S256');\n redirect(response, endpoint.href, [cookie(FLOW_COOKIE, flowId, FLOW_MAX_AGE_SECONDS)]);\n }\n\n async #callback(request: IncomingMessage, response: ServerResponse, url: URL): Promise<void> {\n const flowId = cookiesOf(request).get(FLOW_COOKIE);\n const flow = flowId ? this.#flows.get(flowId) : undefined;\n if (flowId) {\n this.#flows.delete(flowId);\n }\n if (!flow || url.searchParams.get('state') !== flow.state) {\n writeJson(response, 400, { code: 'invalid_oidc_state', error: 'The OIDC callback state is invalid or expired.' });\n return;\n }\n const providerError = url.searchParams.get('error');\n if (providerError) {\n writeJson(response, 401, { code: providerError, error: url.searchParams.get('error_description') ?? 'Sign-in was rejected.' });\n return;\n }\n const code = url.searchParams.get('code');\n if (!code) {\n writeJson(response, 400, { code: 'missing_authorization_code', error: 'The OIDC callback did not include an authorization code.' });\n return;\n }\n\n const [configuration, discovery] = await Promise.all([this.#configuration(), this.#discovery()]);\n const fields = new URLSearchParams({\n client_id: configuration.clientId,\n code,\n code_verifier: flow.codeVerifier,\n grant_type: 'authorization_code',\n redirect_uri: new URL(CALLBACK_PATH, this.#developmentOrigin).href,\n });\n const tokenResponse = await fetch(discovery.tokenEndpoint, {\n body: fields,\n headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' },\n method: 'POST',\n redirect: 'error',\n });\n if (!tokenResponse.ok) {\n throw new Error(`OIDC token exchange failed (${tokenResponse.status}).`);\n }\n const tokens = parseTokenResponse(await tokenResponse.json(), true);\n const idToken = tokens.idToken;\n if (!idToken) {\n throw new Error('OIDC token endpoint did not return an ID token.');\n }\n const jwks = this.#jwks.get(discovery.jwksUri) ?? createRemoteJWKSet(new URL(discovery.jwksUri));\n this.#jwks.set(discovery.jwksUri, jwks);\n const verified = await jwtVerify(idToken, jwks, {\n audience: configuration.clientId,\n issuer: discovery.issuer,\n requiredClaims: ['sub', 'nonce'],\n });\n if (verified.payload.nonce !== flow.nonce) {\n throw new Error('OIDC ID token nonce does not match the authorization request.');\n }\n\n const sessionId = base64Url();\n this.#sessions.set(sessionId, {\n accessToken: tokens.accessToken,\n expiresAt: Date.now() + tokens.expiresIn * 1000,\n idToken,\n moduleBootstrapTail: Promise.resolve(),\n moduleCookies: new Map(),\n moduleNavigationContext: null,\n refreshToken: tokens.refreshToken,\n });\n redirect(response, flow.returnTo, [cookie(SESSION_COOKIE, sessionId, SESSION_MAX_AGE_SECONDS), clearCookie(FLOW_COOKIE)]);\n }\n\n async #logout(request: IncomingMessage, response: ServerResponse): Promise<void> {\n const sessionId = cookiesOf(request).get(SESSION_COOKIE);\n const session = sessionId ? this.#sessions.get(sessionId) : undefined;\n if (sessionId) {\n this.#sessions.delete(sessionId);\n }\n if (session) {\n void this.#revoke(session).catch(() => undefined);\n }\n const logoutId = base64Url();\n this.#logoutFlows.set(logoutId, { createdAt: Date.now(), idToken: session?.idToken ?? null });\n response.setHeader('Set-Cookie', [clearCookie(SESSION_COOKIE), cookie(LOGOUT_COOKIE, logoutId, FLOW_MAX_AGE_SECONDS)]);\n writeJson(response, 200, { loggedOut: true });\n }\n\n async #revoke(session: ITokenSession): Promise<void> {\n const [configuration, discovery] = await Promise.all([this.#configuration(), this.#discovery()]);\n const revocationEndpoint = discovery.revocationEndpoint;\n if (!revocationEndpoint) {\n return;\n }\n const revoke = async (token: string, hint: string): Promise<void> => {\n await fetch(revocationEndpoint, {\n body: new URLSearchParams({ client_id: configuration.clientId, token, token_type_hint: hint }),\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n method: 'POST',\n redirect: 'error',\n });\n };\n await Promise.all([\n revoke(session.accessToken, 'access_token'),\n session.refreshToken ? revoke(session.refreshToken, 'refresh_token') : Promise.resolve(),\n ]);\n }\n\n async #authenticatedSession(request: IncomingMessage): Promise<ITokenSession | null> {\n const sessionId = cookiesOf(request).get(SESSION_COOKIE);\n const session = sessionId ? this.#sessions.get(sessionId) : undefined;\n if (!session) {\n return null;\n }\n if (session.expiresAt > Date.now() + TOKEN_REFRESH_SKEW_MS) {\n return session;\n }\n if (!session.refreshToken) {\n if (sessionId) {\n this.#sessions.delete(sessionId);\n }\n return null;\n }\n session.refreshPromise ??= this.#refresh(session).finally(() => {\n session.refreshPromise = undefined;\n });\n try {\n await session.refreshPromise;\n return session;\n } catch {\n if (sessionId) {\n this.#sessions.delete(sessionId);\n }\n return null;\n }\n }\n\n async #refresh(session: ITokenSession): Promise<void> {\n const refreshToken = session.refreshToken;\n if (!refreshToken) {\n throw new Error('OIDC refresh token is unavailable.');\n }\n const [configuration, discovery] = await Promise.all([this.#configuration(), this.#discovery()]);\n const response = await fetch(discovery.tokenEndpoint, {\n body: new URLSearchParams({\n client_id: configuration.clientId,\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n }),\n headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' },\n method: 'POST',\n redirect: 'error',\n });\n if (!response.ok) {\n throw new Error(`OIDC refresh failed (${response.status}).`);\n }\n const tokens = parseTokenResponse(await response.json(), false);\n session.accessToken = tokens.accessToken;\n session.expiresAt = Date.now() + tokens.expiresIn * 1000;\n session.refreshToken = tokens.refreshToken ?? session.refreshToken;\n session.idToken = tokens.idToken ?? session.idToken;\n }\n\n async #proxy(request: IncomingMessage, response: ServerResponse, localUrl: URL): Promise<void> {\n const session = await this.#authenticatedSession(request);\n if (!session) {\n writeJson(response, 401, { code: 'missing_access_token', error: 'Sign in is required.' });\n return;\n }\n const isModuleApi = localUrl.pathname.startsWith(this.#moduleApiPath);\n if (isModuleApi && session.moduleCookies.size === 0) {\n const previous = session.moduleBootstrapTail;\n let release = (): void => {};\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n session.moduleBootstrapTail = previous.catch(() => undefined).then(() => current);\n await previous.catch(() => undefined);\n try {\n await this.#proxyAuthenticated(request, response, localUrl, session, true);\n } finally {\n release();\n }\n return;\n }\n await this.#proxyAuthenticated(request, response, localUrl, session, isModuleApi);\n }\n\n async #proxyAuthenticated(\n request: IncomingMessage,\n response: ServerResponse,\n localUrl: URL,\n session: ITokenSession,\n isModuleApi: boolean,\n ): Promise<void> {\n const upstreamOrigin = isModuleApi ? this.#moduleApiOrigin : this.#hostOrigin;\n const upstreamUrl = new URL(`${localUrl.pathname}${localUrl.search}`, upstreamOrigin);\n const method = request.method ?? 'GET';\n const init: RequestInit & { duplex?: 'half' } = {\n headers: proxyHeaders(\n request,\n session.accessToken,\n isModuleApi ? session.moduleCookies : undefined,\n isModuleApi ? session.moduleNavigationContext : undefined,\n ),\n method,\n redirect: 'manual',\n };\n if (method !== 'GET' && method !== 'HEAD') {\n init.body = Readable.toWeb(request) as unknown as BodyInit;\n init.duplex = 'half';\n }\n const upstream = await fetch(upstreamUrl, init);\n if (isModuleApi) {\n updateModuleCookies(session.moduleCookies, upstream.headers);\n } else if (localUrl.pathname === '/api/navigation' && upstream.ok) {\n session.moduleNavigationContext = navigationContextIn(\n await upstream\n .clone()\n .json()\n .catch(() => null),\n );\n }\n await copyProxyResponse(upstream, response);\n }\n\n #prune(): void {\n const now = Date.now();\n for (const [id, flow] of this.#flows) {\n if (flow.createdAt + FLOW_MAX_AGE_SECONDS * 1000 < now) {\n this.#flows.delete(id);\n }\n }\n for (const [id, flow] of this.#logoutFlows) {\n if (flow.createdAt + FLOW_MAX_AGE_SECONDS * 1000 < now) {\n this.#logoutFlows.delete(id);\n }\n }\n for (const [id, session] of this.#sessions) {\n if (!session.refreshToken && session.expiresAt + TOKEN_REFRESH_SKEW_MS < now) {\n this.#sessions.delete(id);\n }\n }\n }\n}\n\nexport const mfDevelopmentBffPlugin = (options: IMfDevelopmentBffPluginOptions): Plugin => {\n const middleware = createMfDevelopmentBffMiddleware(options);\n return {\n apply: 'serve',\n name: 'edynamix-mf-development-bff',\n configureServer(server) {\n server.middlewares.use((request, response, next) => {\n middleware(request, response, next);\n });\n },\n };\n};\n\nexport type TMfDevelopmentBffMiddleware = (request: IncomingMessage, response: ServerResponse, next: (error?: unknown) => void) => void;\n\nexport const createMfDevelopmentBffMiddleware = (options: IMfDevelopmentBffPluginOptions): TMfDevelopmentBffMiddleware => {\n const bff = new MfDevelopmentBff(options);\n return (request, response, next) => {\n void bff.handle(request, response, next);\n };\n};\n"]}
@@ -0,0 +1,702 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { Readable } from 'node:stream';
3
+ import { createRemoteJWKSet, jwtVerify } from 'jose';
4
+ const SESSION_COOKIE = '__Host-edyn_dev_session';
5
+ const FLOW_COOKIE = '__Host-edyn_oidc_flow';
6
+ const LOGOUT_COOKIE = '__Host-edyn_oidc_logout';
7
+ const CALLBACK_PATH = '/callback';
8
+ const LOGGED_OUT_PATH = '/logged-out';
9
+ const LOGIN_PATH = '/api/dev-auth/login';
10
+ export const MF_DEVELOPMENT_HOST_NAVIGATION_PATH = '/api/dev-host-navigation/index.js';
11
+ const HOST_NAVIGATION_ASSET_PATHS = new Set(['/exsto-icon.svg', '/exsto-text.svg']);
12
+ const MAX_HOST_NAVIGATION_BYTES = 5 * 1024 * 1024;
13
+ const MAX_HOST_NAVIGATION_ASSET_BYTES = 512 * 1024;
14
+ const SESSION_MAX_AGE_SECONDS = 8 * 60 * 60;
15
+ const FLOW_MAX_AGE_SECONDS = 10 * 60;
16
+ const TOKEN_REFRESH_SKEW_MS = 30_000;
17
+ const NAVIGATION_GROUP_HEADER = 'X-Edyn-Navigation-Group-Id';
18
+ const NAVIGATION_DEALER_HEADER = 'X-Edyn-Navigation-Dealer-Id';
19
+ const COOKIE_NAME_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
20
+ const COOKIE_VALUE_PATTERN = /^[\x20-\x7e]*$/;
21
+ const ALLOWED_HOST_API_PATHS = [
22
+ '/api/auth/me',
23
+ '/api/navigation',
24
+ '/api/navigation/access-check',
25
+ '/api/navigation/access-request',
26
+ '/api/navigation/counter-stream',
27
+ ];
28
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
29
+ const requiredString = (value, key) => {
30
+ const candidate = value[key];
31
+ if (typeof candidate !== 'string' || candidate.trim() === '') {
32
+ throw new Error(`OIDC response is missing ${key}.`);
33
+ }
34
+ return candidate;
35
+ };
36
+ const optionalString = (value, key) => {
37
+ const candidate = value[key];
38
+ if (candidate === undefined || candidate === null) {
39
+ return null;
40
+ }
41
+ if (typeof candidate !== 'string' || candidate.trim() === '') {
42
+ throw new Error(`OIDC response contains an invalid ${key}.`);
43
+ }
44
+ return candidate;
45
+ };
46
+ const absoluteHttpsUrl = (candidate, label, allowLocalHttp = false) => {
47
+ let url;
48
+ try {
49
+ url = new URL(candidate);
50
+ }
51
+ catch {
52
+ throw new Error(`${label} must be an absolute URL.`);
53
+ }
54
+ const isLocalHttp = allowLocalHttp && url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1');
55
+ if (url.protocol !== 'https:' && !isLocalHttp) {
56
+ throw new Error(`${label} must use HTTPS.`);
57
+ }
58
+ if (url.username || url.password || url.hash) {
59
+ throw new Error(`${label} must not contain credentials or a fragment.`);
60
+ }
61
+ return url;
62
+ };
63
+ const moduleApiPrefix = (candidate) => {
64
+ if (!/^\/[a-z][a-z0-9-]*api\/$/.test(candidate)) {
65
+ throw new Error('moduleApiPath must look like /moduleapi/.');
66
+ }
67
+ return candidate;
68
+ };
69
+ const base64Url = (size = 32) => randomBytes(size).toString('base64url');
70
+ const codeChallengeOf = (verifier) => createHash('sha256').update(verifier).digest('base64url');
71
+ const cookiesOf = (request) => {
72
+ const cookies = new Map();
73
+ for (const part of (request.headers.cookie ?? '').split(';')) {
74
+ const separator = part.indexOf('=');
75
+ if (separator <= 0) {
76
+ continue;
77
+ }
78
+ const name = part.slice(0, separator).trim();
79
+ const value = part.slice(separator + 1).trim();
80
+ if (name && value) {
81
+ cookies.set(name, value);
82
+ }
83
+ }
84
+ return cookies;
85
+ };
86
+ const cookie = (name, value, maxAge) => `${name}=${value}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAge}`;
87
+ const clearCookie = (name) => cookie(name, '', 0);
88
+ const writeJson = (response, status, body) => {
89
+ response.statusCode = status;
90
+ response.setHeader('Cache-Control', 'no-store');
91
+ response.setHeader('Content-Type', 'application/json; charset=utf-8');
92
+ response.end(JSON.stringify(body));
93
+ };
94
+ const redirect = (response, location, cookies = []) => {
95
+ response.statusCode = 302;
96
+ response.setHeader('Cache-Control', 'no-store');
97
+ response.setHeader('Location', location);
98
+ if (cookies.length > 0) {
99
+ response.setHeader('Set-Cookie', cookies);
100
+ }
101
+ response.end();
102
+ };
103
+ const safeReturnTo = (candidate) => {
104
+ if (!candidate?.startsWith('/') || candidate.startsWith('//')) {
105
+ return '/';
106
+ }
107
+ try {
108
+ const parsed = new URL(candidate, 'https://localhost');
109
+ return `${parsed.pathname}${parsed.search}${parsed.hash}`;
110
+ }
111
+ catch {
112
+ return '/';
113
+ }
114
+ };
115
+ const parseTokenResponse = (value, requireIdToken) => {
116
+ if (!isRecord(value)) {
117
+ throw new Error('OIDC token endpoint returned an invalid response.');
118
+ }
119
+ const expiresIn = value.expires_in;
120
+ if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0) {
121
+ throw new Error('OIDC token endpoint returned an invalid expires_in value.');
122
+ }
123
+ const idToken = optionalString(value, 'id_token');
124
+ if (requireIdToken && !idToken) {
125
+ throw new Error('OIDC token endpoint did not return an ID token.');
126
+ }
127
+ const tokenType = requiredString(value, 'token_type');
128
+ if (tokenType.toLowerCase() !== 'bearer') {
129
+ throw new Error('OIDC token endpoint returned an unsupported token type.');
130
+ }
131
+ return {
132
+ accessToken: requiredString(value, 'access_token'),
133
+ expiresIn,
134
+ idToken,
135
+ refreshToken: optionalString(value, 'refresh_token'),
136
+ tokenType,
137
+ };
138
+ };
139
+ const pathIsHostApi = (path) => {
140
+ return ALLOWED_HOST_API_PATHS.some((candidate) => path === candidate || path.startsWith(`${candidate}/`));
141
+ };
142
+ const proxyHeaders = (request, accessToken, moduleCookies, navigationContext) => {
143
+ const headers = new Headers();
144
+ for (const [name, value] of Object.entries(request.headers)) {
145
+ if (!value ||
146
+ [
147
+ 'authorization',
148
+ 'connection',
149
+ 'content-length',
150
+ 'cookie',
151
+ 'host',
152
+ 'origin',
153
+ 'transfer-encoding',
154
+ NAVIGATION_GROUP_HEADER.toLowerCase(),
155
+ NAVIGATION_DEALER_HEADER.toLowerCase(),
156
+ ].includes(name.toLowerCase())) {
157
+ continue;
158
+ }
159
+ if (Array.isArray(value)) {
160
+ for (const item of value) {
161
+ headers.append(name, item);
162
+ }
163
+ }
164
+ else {
165
+ headers.set(name, value);
166
+ }
167
+ }
168
+ headers.set('Authorization', `Bearer ${accessToken}`);
169
+ if (moduleCookies?.size) {
170
+ headers.set('Cookie', [...moduleCookies.values()].join('; '));
171
+ }
172
+ if (navigationContext) {
173
+ headers.set(NAVIGATION_GROUP_HEADER, String(navigationContext.groupId));
174
+ headers.set(NAVIGATION_DEALER_HEADER, String(navigationContext.dealerId));
175
+ }
176
+ return headers;
177
+ };
178
+ const navigationContextIn = (value) => {
179
+ if (!isRecord(value) || !isRecord(value.context)) {
180
+ return null;
181
+ }
182
+ const groupId = value.context.selectedGroupId;
183
+ const dealerId = value.context.selectedDealerId;
184
+ if (!Number.isSafeInteger(groupId) || groupId <= 0 || !Number.isSafeInteger(dealerId) || dealerId < 0) {
185
+ return null;
186
+ }
187
+ return { dealerId: dealerId, groupId: groupId };
188
+ };
189
+ const updateModuleCookies = (cookies, headers) => {
190
+ const values = headers.getSetCookie();
191
+ for (const value of values) {
192
+ if (value.length > 4096) {
193
+ continue;
194
+ }
195
+ const [pair, ...attributes] = value.split(';');
196
+ const separator = pair?.indexOf('=') ?? -1;
197
+ if (!pair || separator <= 0) {
198
+ continue;
199
+ }
200
+ const name = pair.slice(0, separator).trim();
201
+ const cookieValue = pair.slice(separator + 1).trim();
202
+ if (!COOKIE_NAME_PATTERN.test(name) || !COOKIE_VALUE_PATTERN.test(cookieValue) || cookieValue.includes(';')) {
203
+ continue;
204
+ }
205
+ const deleted = cookieValue === '' || attributes.some((attribute) => /^\s*max-age\s*=\s*0\s*$/i.test(attribute));
206
+ if (deleted) {
207
+ cookies.delete(name);
208
+ continue;
209
+ }
210
+ if (!cookies.has(name) && cookies.size >= 32) {
211
+ continue;
212
+ }
213
+ cookies.set(name, `${name}=${cookieValue}`);
214
+ }
215
+ };
216
+ const copyProxyResponse = async (upstream, response) => {
217
+ response.statusCode = upstream.status;
218
+ for (const [name, value] of upstream.headers) {
219
+ if (!['connection', 'content-encoding', 'content-length', 'set-cookie', 'transfer-encoding'].includes(name.toLowerCase())) {
220
+ response.setHeader(name, value);
221
+ }
222
+ }
223
+ response.setHeader('Cache-Control', upstream.headers.get('cache-control') ?? 'no-store');
224
+ if (!upstream.body) {
225
+ response.end();
226
+ return;
227
+ }
228
+ await new Promise((resolve, reject) => {
229
+ const readable = Readable.fromWeb(upstream.body);
230
+ readable.once('error', reject);
231
+ response.once('error', reject);
232
+ response.once('finish', resolve);
233
+ readable.pipe(response);
234
+ });
235
+ };
236
+ const readResponseBody = async (response, maximumBytes, label) => {
237
+ const declaredLength = Number(response.headers.get('content-length'));
238
+ if (Number.isFinite(declaredLength) && declaredLength > maximumBytes) {
239
+ await response.body?.cancel();
240
+ throw new Error(`${label} exceeded the configured size limit.`);
241
+ }
242
+ if (!response.body) {
243
+ return Buffer.alloc(0);
244
+ }
245
+ const reader = response.body.getReader();
246
+ const chunks = [];
247
+ let totalBytes = 0;
248
+ try {
249
+ while (true) {
250
+ const { done, value } = await reader.read();
251
+ if (done) {
252
+ break;
253
+ }
254
+ totalBytes += value.byteLength;
255
+ if (totalBytes > maximumBytes) {
256
+ await reader.cancel();
257
+ throw new Error(`${label} exceeded the configured size limit.`);
258
+ }
259
+ chunks.push(value);
260
+ }
261
+ }
262
+ finally {
263
+ reader.releaseLock();
264
+ }
265
+ return Buffer.concat(chunks, totalBytes);
266
+ };
267
+ class MfDevelopmentBff {
268
+ #configurationUrl;
269
+ #developmentOrigin;
270
+ #flows = new Map();
271
+ #hostOrigin;
272
+ #hostNavigationUrl;
273
+ #jwks = new Map();
274
+ #logoutFlows = new Map();
275
+ #moduleApiOrigin;
276
+ #moduleApiPath;
277
+ #sessions = new Map();
278
+ #configurationPromise = null;
279
+ #discoveryPromise = null;
280
+ constructor(options) {
281
+ const hostNavigation = absoluteHttpsUrl(options.hostNavigationUrl, 'hostNavigationUrl', true);
282
+ this.#hostNavigationUrl = hostNavigation;
283
+ this.#hostOrigin = new URL(hostNavigation.origin);
284
+ this.#configurationUrl = new URL('/api/auth/oidc-configuration', this.#hostOrigin);
285
+ this.#developmentOrigin = absoluteHttpsUrl(options.developmentOrigin ?? 'https://localhost:4200', 'developmentOrigin');
286
+ if (this.#developmentOrigin.pathname !== '/' || this.#developmentOrigin.search || this.#developmentOrigin.hash) {
287
+ throw new Error('developmentOrigin must be an origin without a path, query, or fragment.');
288
+ }
289
+ this.#moduleApiOrigin = absoluteHttpsUrl(options.moduleApiOrigin, 'moduleApiOrigin', true);
290
+ if (this.#moduleApiOrigin.pathname !== '/' || this.#moduleApiOrigin.search || this.#moduleApiOrigin.hash) {
291
+ throw new Error('moduleApiOrigin must be an origin without a path, query, or fragment.');
292
+ }
293
+ this.#moduleApiPath = moduleApiPrefix(options.moduleApiPath);
294
+ }
295
+ async handle(request, response, next) {
296
+ if (!request.url || !request.method) {
297
+ next();
298
+ return;
299
+ }
300
+ const url = new URL(request.url, this.#developmentOrigin);
301
+ this.#prune();
302
+ try {
303
+ if (request.method === 'GET' && url.pathname === MF_DEVELOPMENT_HOST_NAVIGATION_PATH) {
304
+ await this.#hostNavigationResource(response, this.#hostNavigationUrl, 'script');
305
+ return;
306
+ }
307
+ if (request.method === 'GET' && HOST_NAVIGATION_ASSET_PATHS.has(url.pathname)) {
308
+ await this.#hostNavigationResource(response, new URL(url.pathname, this.#hostOrigin), 'asset');
309
+ return;
310
+ }
311
+ if (request.method === 'GET' && url.pathname === LOGIN_PATH) {
312
+ await this.#login(request, response, safeReturnTo(url.searchParams.get('returnTo')));
313
+ return;
314
+ }
315
+ if (request.method === 'GET' && url.pathname === CALLBACK_PATH) {
316
+ await this.#callback(request, response, url);
317
+ return;
318
+ }
319
+ if (request.method === 'GET' && url.pathname === LOGGED_OUT_PATH) {
320
+ const returnTo = safeReturnTo(url.searchParams.get('state'));
321
+ redirect(response, `${LOGIN_PATH}?returnTo=${encodeURIComponent(returnTo)}`, [clearCookie(LOGOUT_COOKIE)]);
322
+ return;
323
+ }
324
+ if (request.method === 'GET' && url.pathname === '/frontchannel-logout') {
325
+ const sessionId = cookiesOf(request).get(SESSION_COOKIE);
326
+ if (sessionId) {
327
+ this.#sessions.delete(sessionId);
328
+ }
329
+ response.statusCode = 204;
330
+ response.setHeader('Set-Cookie', clearCookie(SESSION_COOKIE));
331
+ response.end();
332
+ return;
333
+ }
334
+ if (request.method === 'POST' && url.pathname === '/api/auth/logout') {
335
+ await this.#logout(request, response);
336
+ return;
337
+ }
338
+ if (pathIsHostApi(url.pathname) || url.pathname.startsWith(this.#moduleApiPath)) {
339
+ await this.#proxy(request, response, url);
340
+ return;
341
+ }
342
+ next();
343
+ }
344
+ catch (error) {
345
+ const message = error instanceof Error ? error.message : 'Development authentication failed.';
346
+ writeJson(response, 502, { code: 'development_authentication_failed', error: message });
347
+ }
348
+ }
349
+ async #hostNavigationResource(response, upstreamUrl, kind) {
350
+ const upstream = await fetch(upstreamUrl, {
351
+ headers: { Accept: kind === 'script' ? 'text/javascript, application/javascript' : 'image/svg+xml' },
352
+ redirect: 'error',
353
+ });
354
+ if (!upstream.ok) {
355
+ throw new Error(`Host navigation ${kind} failed (${upstream.status}).`);
356
+ }
357
+ const contentType = upstream.headers.get('content-type') ?? '';
358
+ const validContentType = kind === 'script' ? /^(?:text|application)\/javascript(?:;|$)/i.test(contentType) : /^image\/svg\+xml(?:;|$)/i.test(contentType);
359
+ if (!validContentType) {
360
+ throw new Error(`Host navigation ${kind} returned an invalid content type.`);
361
+ }
362
+ const maximumBytes = kind === 'script' ? MAX_HOST_NAVIGATION_BYTES : MAX_HOST_NAVIGATION_ASSET_BYTES;
363
+ const body = await readResponseBody(upstream, maximumBytes, `Host navigation ${kind}`);
364
+ response.statusCode = 200;
365
+ response.setHeader('Cache-Control', 'no-store');
366
+ response.setHeader('Content-Type', contentType);
367
+ response.setHeader('X-Content-Type-Options', 'nosniff');
368
+ response.end(body);
369
+ }
370
+ async #configuration() {
371
+ this.#configurationPromise ??= fetch(this.#configurationUrl, { headers: { Accept: 'application/json' }, redirect: 'error' })
372
+ .then(async (response) => {
373
+ if (!response.ok) {
374
+ throw new Error(`Host OIDC configuration failed (${response.status}).`);
375
+ }
376
+ const value = await response.json();
377
+ if (!isRecord(value)) {
378
+ throw new Error('Host OIDC configuration returned an invalid response.');
379
+ }
380
+ const issuer = absoluteHttpsUrl(requiredString(value, 'issuer'), 'OIDC issuer', true).href.replace(/\/$/, '');
381
+ return { clientId: requiredString(value, 'clientId'), issuer, scope: requiredString(value, 'scope') };
382
+ })
383
+ .catch((error) => {
384
+ this.#configurationPromise = null;
385
+ throw error;
386
+ });
387
+ return this.#configurationPromise;
388
+ }
389
+ async #discovery() {
390
+ this.#discoveryPromise ??= this.#configuration()
391
+ .then(async (configuration) => {
392
+ const response = await fetch(`${configuration.issuer}/.well-known/openid-configuration`, {
393
+ headers: { Accept: 'application/json' },
394
+ redirect: 'error',
395
+ });
396
+ if (!response.ok) {
397
+ throw new Error(`OIDC discovery failed (${response.status}).`);
398
+ }
399
+ const value = await response.json();
400
+ if (!isRecord(value)) {
401
+ throw new Error('OIDC discovery returned an invalid response.');
402
+ }
403
+ const issuer = absoluteHttpsUrl(requiredString(value, 'issuer'), 'OIDC discovery issuer', true).href.replace(/\/$/, '');
404
+ if (issuer !== configuration.issuer) {
405
+ throw new Error('OIDC discovery issuer does not match the host configuration.');
406
+ }
407
+ const endpoint = (key) => {
408
+ const url = absoluteHttpsUrl(requiredString(value, key), `OIDC ${key}`, true);
409
+ if (url.origin !== new URL(issuer).origin) {
410
+ throw new Error(`OIDC ${key} must use the configured issuer origin.`);
411
+ }
412
+ return url.href;
413
+ };
414
+ const revocation = optionalString(value, 'revocation_endpoint');
415
+ return {
416
+ authorizationEndpoint: endpoint('authorization_endpoint'),
417
+ endSessionEndpoint: endpoint('end_session_endpoint'),
418
+ issuer,
419
+ jwksUri: endpoint('jwks_uri'),
420
+ revocationEndpoint: revocation ? endpoint('revocation_endpoint') : null,
421
+ tokenEndpoint: endpoint('token_endpoint'),
422
+ };
423
+ })
424
+ .catch((error) => {
425
+ this.#discoveryPromise = null;
426
+ throw error;
427
+ });
428
+ return this.#discoveryPromise;
429
+ }
430
+ async #login(request, response, returnTo) {
431
+ const logoutId = cookiesOf(request).get(LOGOUT_COOKIE);
432
+ if (logoutId) {
433
+ const logout = this.#logoutFlows.get(logoutId);
434
+ this.#logoutFlows.delete(logoutId);
435
+ if (logout) {
436
+ const [configuration, discovery] = await Promise.all([this.#configuration(), this.#discovery()]);
437
+ const endpoint = new URL(discovery.endSessionEndpoint);
438
+ endpoint.searchParams.set('client_id', configuration.clientId);
439
+ endpoint.searchParams.set('post_logout_redirect_uri', new URL(LOGGED_OUT_PATH, this.#developmentOrigin).href);
440
+ endpoint.searchParams.set('state', returnTo);
441
+ if (logout.idToken) {
442
+ endpoint.searchParams.set('id_token_hint', logout.idToken);
443
+ }
444
+ redirect(response, endpoint.href, [clearCookie(LOGOUT_COOKIE)]);
445
+ return;
446
+ }
447
+ }
448
+ const [configuration, discovery] = await Promise.all([this.#configuration(), this.#discovery()]);
449
+ const flowId = base64Url();
450
+ const codeVerifier = base64Url(48);
451
+ const flow = { codeVerifier, createdAt: Date.now(), nonce: base64Url(), returnTo, state: base64Url() };
452
+ this.#flows.set(flowId, flow);
453
+ const endpoint = new URL(discovery.authorizationEndpoint);
454
+ endpoint.searchParams.set('response_type', 'code');
455
+ endpoint.searchParams.set('client_id', configuration.clientId);
456
+ endpoint.searchParams.set('redirect_uri', new URL(CALLBACK_PATH, this.#developmentOrigin).href);
457
+ endpoint.searchParams.set('scope', configuration.scope);
458
+ endpoint.searchParams.set('state', flow.state);
459
+ endpoint.searchParams.set('nonce', flow.nonce);
460
+ endpoint.searchParams.set('code_challenge', codeChallengeOf(codeVerifier));
461
+ endpoint.searchParams.set('code_challenge_method', 'S256');
462
+ redirect(response, endpoint.href, [cookie(FLOW_COOKIE, flowId, FLOW_MAX_AGE_SECONDS)]);
463
+ }
464
+ async #callback(request, response, url) {
465
+ const flowId = cookiesOf(request).get(FLOW_COOKIE);
466
+ const flow = flowId ? this.#flows.get(flowId) : undefined;
467
+ if (flowId) {
468
+ this.#flows.delete(flowId);
469
+ }
470
+ if (!flow || url.searchParams.get('state') !== flow.state) {
471
+ writeJson(response, 400, { code: 'invalid_oidc_state', error: 'The OIDC callback state is invalid or expired.' });
472
+ return;
473
+ }
474
+ const providerError = url.searchParams.get('error');
475
+ if (providerError) {
476
+ writeJson(response, 401, { code: providerError, error: url.searchParams.get('error_description') ?? 'Sign-in was rejected.' });
477
+ return;
478
+ }
479
+ const code = url.searchParams.get('code');
480
+ if (!code) {
481
+ writeJson(response, 400, { code: 'missing_authorization_code', error: 'The OIDC callback did not include an authorization code.' });
482
+ return;
483
+ }
484
+ const [configuration, discovery] = await Promise.all([this.#configuration(), this.#discovery()]);
485
+ const fields = new URLSearchParams({
486
+ client_id: configuration.clientId,
487
+ code,
488
+ code_verifier: flow.codeVerifier,
489
+ grant_type: 'authorization_code',
490
+ redirect_uri: new URL(CALLBACK_PATH, this.#developmentOrigin).href,
491
+ });
492
+ const tokenResponse = await fetch(discovery.tokenEndpoint, {
493
+ body: fields,
494
+ headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' },
495
+ method: 'POST',
496
+ redirect: 'error',
497
+ });
498
+ if (!tokenResponse.ok) {
499
+ throw new Error(`OIDC token exchange failed (${tokenResponse.status}).`);
500
+ }
501
+ const tokens = parseTokenResponse(await tokenResponse.json(), true);
502
+ const idToken = tokens.idToken;
503
+ if (!idToken) {
504
+ throw new Error('OIDC token endpoint did not return an ID token.');
505
+ }
506
+ const jwks = this.#jwks.get(discovery.jwksUri) ?? createRemoteJWKSet(new URL(discovery.jwksUri));
507
+ this.#jwks.set(discovery.jwksUri, jwks);
508
+ const verified = await jwtVerify(idToken, jwks, {
509
+ audience: configuration.clientId,
510
+ issuer: discovery.issuer,
511
+ requiredClaims: ['sub', 'nonce'],
512
+ });
513
+ if (verified.payload.nonce !== flow.nonce) {
514
+ throw new Error('OIDC ID token nonce does not match the authorization request.');
515
+ }
516
+ const sessionId = base64Url();
517
+ this.#sessions.set(sessionId, {
518
+ accessToken: tokens.accessToken,
519
+ expiresAt: Date.now() + tokens.expiresIn * 1000,
520
+ idToken,
521
+ moduleBootstrapTail: Promise.resolve(),
522
+ moduleCookies: new Map(),
523
+ moduleNavigationContext: null,
524
+ refreshToken: tokens.refreshToken,
525
+ });
526
+ redirect(response, flow.returnTo, [cookie(SESSION_COOKIE, sessionId, SESSION_MAX_AGE_SECONDS), clearCookie(FLOW_COOKIE)]);
527
+ }
528
+ async #logout(request, response) {
529
+ const sessionId = cookiesOf(request).get(SESSION_COOKIE);
530
+ const session = sessionId ? this.#sessions.get(sessionId) : undefined;
531
+ if (sessionId) {
532
+ this.#sessions.delete(sessionId);
533
+ }
534
+ if (session) {
535
+ void this.#revoke(session).catch(() => undefined);
536
+ }
537
+ const logoutId = base64Url();
538
+ this.#logoutFlows.set(logoutId, { createdAt: Date.now(), idToken: session?.idToken ?? null });
539
+ response.setHeader('Set-Cookie', [clearCookie(SESSION_COOKIE), cookie(LOGOUT_COOKIE, logoutId, FLOW_MAX_AGE_SECONDS)]);
540
+ writeJson(response, 200, { loggedOut: true });
541
+ }
542
+ async #revoke(session) {
543
+ const [configuration, discovery] = await Promise.all([this.#configuration(), this.#discovery()]);
544
+ const revocationEndpoint = discovery.revocationEndpoint;
545
+ if (!revocationEndpoint) {
546
+ return;
547
+ }
548
+ const revoke = async (token, hint) => {
549
+ await fetch(revocationEndpoint, {
550
+ body: new URLSearchParams({ client_id: configuration.clientId, token, token_type_hint: hint }),
551
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
552
+ method: 'POST',
553
+ redirect: 'error',
554
+ });
555
+ };
556
+ await Promise.all([
557
+ revoke(session.accessToken, 'access_token'),
558
+ session.refreshToken ? revoke(session.refreshToken, 'refresh_token') : Promise.resolve(),
559
+ ]);
560
+ }
561
+ async #authenticatedSession(request) {
562
+ const sessionId = cookiesOf(request).get(SESSION_COOKIE);
563
+ const session = sessionId ? this.#sessions.get(sessionId) : undefined;
564
+ if (!session) {
565
+ return null;
566
+ }
567
+ if (session.expiresAt > Date.now() + TOKEN_REFRESH_SKEW_MS) {
568
+ return session;
569
+ }
570
+ if (!session.refreshToken) {
571
+ if (sessionId) {
572
+ this.#sessions.delete(sessionId);
573
+ }
574
+ return null;
575
+ }
576
+ session.refreshPromise ??= this.#refresh(session).finally(() => {
577
+ session.refreshPromise = undefined;
578
+ });
579
+ try {
580
+ await session.refreshPromise;
581
+ return session;
582
+ }
583
+ catch {
584
+ if (sessionId) {
585
+ this.#sessions.delete(sessionId);
586
+ }
587
+ return null;
588
+ }
589
+ }
590
+ async #refresh(session) {
591
+ const refreshToken = session.refreshToken;
592
+ if (!refreshToken) {
593
+ throw new Error('OIDC refresh token is unavailable.');
594
+ }
595
+ const [configuration, discovery] = await Promise.all([this.#configuration(), this.#discovery()]);
596
+ const response = await fetch(discovery.tokenEndpoint, {
597
+ body: new URLSearchParams({
598
+ client_id: configuration.clientId,
599
+ grant_type: 'refresh_token',
600
+ refresh_token: refreshToken,
601
+ }),
602
+ headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' },
603
+ method: 'POST',
604
+ redirect: 'error',
605
+ });
606
+ if (!response.ok) {
607
+ throw new Error(`OIDC refresh failed (${response.status}).`);
608
+ }
609
+ const tokens = parseTokenResponse(await response.json(), false);
610
+ session.accessToken = tokens.accessToken;
611
+ session.expiresAt = Date.now() + tokens.expiresIn * 1000;
612
+ session.refreshToken = tokens.refreshToken ?? session.refreshToken;
613
+ session.idToken = tokens.idToken ?? session.idToken;
614
+ }
615
+ async #proxy(request, response, localUrl) {
616
+ const session = await this.#authenticatedSession(request);
617
+ if (!session) {
618
+ writeJson(response, 401, { code: 'missing_access_token', error: 'Sign in is required.' });
619
+ return;
620
+ }
621
+ const isModuleApi = localUrl.pathname.startsWith(this.#moduleApiPath);
622
+ if (isModuleApi && session.moduleCookies.size === 0) {
623
+ const previous = session.moduleBootstrapTail;
624
+ let release = () => { };
625
+ const current = new Promise((resolve) => {
626
+ release = resolve;
627
+ });
628
+ session.moduleBootstrapTail = previous.catch(() => undefined).then(() => current);
629
+ await previous.catch(() => undefined);
630
+ try {
631
+ await this.#proxyAuthenticated(request, response, localUrl, session, true);
632
+ }
633
+ finally {
634
+ release();
635
+ }
636
+ return;
637
+ }
638
+ await this.#proxyAuthenticated(request, response, localUrl, session, isModuleApi);
639
+ }
640
+ async #proxyAuthenticated(request, response, localUrl, session, isModuleApi) {
641
+ const upstreamOrigin = isModuleApi ? this.#moduleApiOrigin : this.#hostOrigin;
642
+ const upstreamUrl = new URL(`${localUrl.pathname}${localUrl.search}`, upstreamOrigin);
643
+ const method = request.method ?? 'GET';
644
+ const init = {
645
+ headers: proxyHeaders(request, session.accessToken, isModuleApi ? session.moduleCookies : undefined, isModuleApi ? session.moduleNavigationContext : undefined),
646
+ method,
647
+ redirect: 'manual',
648
+ };
649
+ if (method !== 'GET' && method !== 'HEAD') {
650
+ init.body = Readable.toWeb(request);
651
+ init.duplex = 'half';
652
+ }
653
+ const upstream = await fetch(upstreamUrl, init);
654
+ if (isModuleApi) {
655
+ updateModuleCookies(session.moduleCookies, upstream.headers);
656
+ }
657
+ else if (localUrl.pathname === '/api/navigation' && upstream.ok) {
658
+ session.moduleNavigationContext = navigationContextIn(await upstream
659
+ .clone()
660
+ .json()
661
+ .catch(() => null));
662
+ }
663
+ await copyProxyResponse(upstream, response);
664
+ }
665
+ #prune() {
666
+ const now = Date.now();
667
+ for (const [id, flow] of this.#flows) {
668
+ if (flow.createdAt + FLOW_MAX_AGE_SECONDS * 1000 < now) {
669
+ this.#flows.delete(id);
670
+ }
671
+ }
672
+ for (const [id, flow] of this.#logoutFlows) {
673
+ if (flow.createdAt + FLOW_MAX_AGE_SECONDS * 1000 < now) {
674
+ this.#logoutFlows.delete(id);
675
+ }
676
+ }
677
+ for (const [id, session] of this.#sessions) {
678
+ if (!session.refreshToken && session.expiresAt + TOKEN_REFRESH_SKEW_MS < now) {
679
+ this.#sessions.delete(id);
680
+ }
681
+ }
682
+ }
683
+ }
684
+ export const mfDevelopmentBffPlugin = (options) => {
685
+ const middleware = createMfDevelopmentBffMiddleware(options);
686
+ return {
687
+ apply: 'serve',
688
+ name: 'edynamix-mf-development-bff',
689
+ configureServer(server) {
690
+ server.middlewares.use((request, response, next) => {
691
+ middleware(request, response, next);
692
+ });
693
+ },
694
+ };
695
+ };
696
+ export const createMfDevelopmentBffMiddleware = (options) => {
697
+ const bff = new MfDevelopmentBff(options);
698
+ return (request, response, next) => {
699
+ void bff.handle(request, response, next);
700
+ };
701
+ };
702
+ //# sourceMappingURL=vite-development.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite-development.js","sourceRoot":"","sources":["../src/vite-development.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAEtD,OAAO,EAAE,QAAQ,EAA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C,MAAM,sBAAsB,GAAG,CAAC,OAAuC,EAAU,EAAE;IACxF,MAAM,UAAU,GAAG,gCAAgC,CAAC,OAAO,CAAC,CAAC;IAC7D,OAAO;QACL,KAAK,EAAE,OAAO;QACd,IAAI,EAAE,6BAA6B;QACnC,eAAe,CAAC,MAAM;YACpB,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE;gBACjD,UAAU,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC;YACtC,CAAC,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC,CAAC;AAIF,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,OAAuC,EAA+B,EAAE;IACvH,MAAM,GAAG,GAAG,IAAI,gBAAgB,CAAC,OAAO,CAAC,CAAC;IAC1C,OAAO,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE;QACjC,KAAK,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC;IAC3C,CAAC,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import { createHash, randomBytes } from 'node:crypto';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { Readable } from 'node:stream';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport type { Plugin } from 'vite';\n\nconst SESSION_COOKIE = '__Host-edyn_dev_session';\nconst FLOW_COOKIE = '__Host-edyn_oidc_flow';\nconst LOGOUT_COOKIE = '__Host-edyn_oidc_logout';\nconst CALLBACK_PATH = '/callback';\nconst LOGGED_OUT_PATH = '/logged-out';\nconst LOGIN_PATH = '/api/dev-auth/login';\nexport const MF_DEVELOPMENT_HOST_NAVIGATION_PATH = '/api/dev-host-navigation/index.js';\nconst HOST_NAVIGATION_ASSET_PATHS = new Set(['/exsto-icon.svg', '/exsto-text.svg']);\nconst MAX_HOST_NAVIGATION_BYTES = 5 * 1024 * 1024;\nconst MAX_HOST_NAVIGATION_ASSET_BYTES = 512 * 1024;\nconst SESSION_MAX_AGE_SECONDS = 8 * 60 * 60;\nconst FLOW_MAX_AGE_SECONDS = 10 * 60;\nconst TOKEN_REFRESH_SKEW_MS = 30_000;\nconst NAVIGATION_GROUP_HEADER = 'X-Edyn-Navigation-Group-Id';\nconst NAVIGATION_DEALER_HEADER = 'X-Edyn-Navigation-Dealer-Id';\nconst COOKIE_NAME_PATTERN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst COOKIE_VALUE_PATTERN = /^[\\x20-\\x7e]*$/;\nconst ALLOWED_HOST_API_PATHS = [\n '/api/auth/me',\n '/api/navigation',\n '/api/navigation/access-check',\n '/api/navigation/access-request',\n '/api/navigation/counter-stream',\n] as const;\n\ninterface IOidcClientConfiguration {\n clientId: string;\n issuer: string;\n scope: string;\n}\n\ninterface IOidcDiscovery {\n authorizationEndpoint: string;\n endSessionEndpoint: string;\n issuer: string;\n jwksUri: string;\n revocationEndpoint: string | null;\n tokenEndpoint: string;\n}\n\ninterface IOidcFlow {\n codeVerifier: string;\n createdAt: number;\n nonce: string;\n returnTo: string;\n state: string;\n}\n\ninterface IModuleNavigationContext {\n dealerId: number;\n groupId: number;\n}\n\ninterface ITokenSession {\n accessToken: string;\n expiresAt: number;\n idToken: string;\n moduleBootstrapTail: Promise<void>;\n moduleCookies: Map<string, string>;\n moduleNavigationContext: IModuleNavigationContext | null;\n refreshPromise?: Promise<void>;\n refreshToken: string | null;\n}\n\ninterface ILogoutFlow {\n createdAt: number;\n idToken: string | null;\n}\n\ninterface ITokenResponse {\n accessToken: string;\n expiresIn: number;\n idToken: string | null;\n refreshToken: string | null;\n tokenType: string;\n}\n\nexport interface IMfDevelopmentBffPluginOptions {\n developmentOrigin?: string;\n hostNavigationUrl: string;\n moduleApiOrigin: string;\n moduleApiPath: string;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst requiredString = (value: Record<string, unknown>, key: string): string => {\n const candidate = value[key];\n if (typeof candidate !== 'string' || candidate.trim() === '') {\n throw new Error(`OIDC response is missing ${key}.`);\n }\n return candidate;\n};\n\nconst optionalString = (value: Record<string, unknown>, key: string): string | null => {\n const candidate = value[key];\n if (candidate === undefined || candidate === null) {\n return null;\n }\n if (typeof candidate !== 'string' || candidate.trim() === '') {\n throw new Error(`OIDC response contains an invalid ${key}.`);\n }\n return candidate;\n};\n\nconst absoluteHttpsUrl = (candidate: string, label: string, allowLocalHttp = false): URL => {\n let url: URL;\n try {\n url = new URL(candidate);\n } catch {\n throw new Error(`${label} must be an absolute URL.`);\n }\n const isLocalHttp = allowLocalHttp && url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1');\n if (url.protocol !== 'https:' && !isLocalHttp) {\n throw new Error(`${label} must use HTTPS.`);\n }\n if (url.username || url.password || url.hash) {\n throw new Error(`${label} must not contain credentials or a fragment.`);\n }\n return url;\n};\n\nconst moduleApiPrefix = (candidate: string): string => {\n if (!/^\\/[a-z][a-z0-9-]*api\\/$/.test(candidate)) {\n throw new Error('moduleApiPath must look like /moduleapi/.');\n }\n return candidate;\n};\n\nconst base64Url = (size = 32): string => randomBytes(size).toString('base64url');\nconst codeChallengeOf = (verifier: string): string => createHash('sha256').update(verifier).digest('base64url');\n\nconst cookiesOf = (request: IncomingMessage): ReadonlyMap<string, string> => {\n const cookies = new Map<string, string>();\n for (const part of (request.headers.cookie ?? '').split(';')) {\n const separator = part.indexOf('=');\n if (separator <= 0) {\n continue;\n }\n const name = part.slice(0, separator).trim();\n const value = part.slice(separator + 1).trim();\n if (name && value) {\n cookies.set(name, value);\n }\n }\n return cookies;\n};\n\nconst cookie = (name: string, value: string, maxAge: number): string => `${name}=${value}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAge}`;\n\nconst clearCookie = (name: string): string => cookie(name, '', 0);\n\nconst writeJson = (response: ServerResponse, status: number, body: unknown): void => {\n response.statusCode = status;\n response.setHeader('Cache-Control', 'no-store');\n response.setHeader('Content-Type', 'application/json; charset=utf-8');\n response.end(JSON.stringify(body));\n};\n\nconst redirect = (response: ServerResponse, location: string, cookies: string[] = []): void => {\n response.statusCode = 302;\n response.setHeader('Cache-Control', 'no-store');\n response.setHeader('Location', location);\n if (cookies.length > 0) {\n response.setHeader('Set-Cookie', cookies);\n }\n response.end();\n};\n\nconst safeReturnTo = (candidate: string | null): string => {\n if (!candidate?.startsWith('/') || candidate.startsWith('//')) {\n return '/';\n }\n try {\n const parsed = new URL(candidate, 'https://localhost');\n return `${parsed.pathname}${parsed.search}${parsed.hash}`;\n } catch {\n return '/';\n }\n};\n\nconst parseTokenResponse = (value: unknown, requireIdToken: boolean): ITokenResponse => {\n if (!isRecord(value)) {\n throw new Error('OIDC token endpoint returned an invalid response.');\n }\n const expiresIn = value.expires_in;\n if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0) {\n throw new Error('OIDC token endpoint returned an invalid expires_in value.');\n }\n const idToken = optionalString(value, 'id_token');\n if (requireIdToken && !idToken) {\n throw new Error('OIDC token endpoint did not return an ID token.');\n }\n const tokenType = requiredString(value, 'token_type');\n if (tokenType.toLowerCase() !== 'bearer') {\n throw new Error('OIDC token endpoint returned an unsupported token type.');\n }\n return {\n accessToken: requiredString(value, 'access_token'),\n expiresIn,\n idToken,\n refreshToken: optionalString(value, 'refresh_token'),\n tokenType,\n };\n};\n\nconst pathIsHostApi = (path: string): boolean => {\n return ALLOWED_HOST_API_PATHS.some((candidate) => path === candidate || path.startsWith(`${candidate}/`));\n};\n\nconst proxyHeaders = (\n request: IncomingMessage,\n accessToken: string,\n moduleCookies?: Map<string, string>,\n navigationContext?: IModuleNavigationContext | null,\n): Headers => {\n const headers = new Headers();\n for (const [name, value] of Object.entries(request.headers)) {\n if (\n !value ||\n [\n 'authorization',\n 'connection',\n 'content-length',\n 'cookie',\n 'host',\n 'origin',\n 'transfer-encoding',\n NAVIGATION_GROUP_HEADER.toLowerCase(),\n NAVIGATION_DEALER_HEADER.toLowerCase(),\n ].includes(name.toLowerCase())\n ) {\n continue;\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(name, item);\n }\n } else {\n headers.set(name, value);\n }\n }\n headers.set('Authorization', `Bearer ${accessToken}`);\n if (moduleCookies?.size) {\n headers.set('Cookie', [...moduleCookies.values()].join('; '));\n }\n if (navigationContext) {\n headers.set(NAVIGATION_GROUP_HEADER, String(navigationContext.groupId));\n headers.set(NAVIGATION_DEALER_HEADER, String(navigationContext.dealerId));\n }\n return headers;\n};\n\nconst navigationContextIn = (value: unknown): IModuleNavigationContext | null => {\n if (!isRecord(value) || !isRecord(value.context)) {\n return null;\n }\n const groupId = value.context.selectedGroupId;\n const dealerId = value.context.selectedDealerId;\n if (!Number.isSafeInteger(groupId) || (groupId as number) <= 0 || !Number.isSafeInteger(dealerId) || (dealerId as number) < 0) {\n return null;\n }\n return { dealerId: dealerId as number, groupId: groupId as number };\n};\n\nconst updateModuleCookies = (cookies: Map<string, string>, headers: Headers): void => {\n const values = headers.getSetCookie();\n for (const value of values) {\n if (value.length > 4096) {\n continue;\n }\n const [pair, ...attributes] = value.split(';');\n const separator = pair?.indexOf('=') ?? -1;\n if (!pair || separator <= 0) {\n continue;\n }\n const name = pair.slice(0, separator).trim();\n const cookieValue = pair.slice(separator + 1).trim();\n if (!COOKIE_NAME_PATTERN.test(name) || !COOKIE_VALUE_PATTERN.test(cookieValue) || cookieValue.includes(';')) {\n continue;\n }\n const deleted = cookieValue === '' || attributes.some((attribute) => /^\\s*max-age\\s*=\\s*0\\s*$/i.test(attribute));\n if (deleted) {\n cookies.delete(name);\n continue;\n }\n if (!cookies.has(name) && cookies.size >= 32) {\n continue;\n }\n cookies.set(name, `${name}=${cookieValue}`);\n }\n};\n\nconst copyProxyResponse = async (upstream: Response, response: ServerResponse): Promise<void> => {\n response.statusCode = upstream.status;\n for (const [name, value] of upstream.headers) {\n if (!['connection', 'content-encoding', 'content-length', 'set-cookie', 'transfer-encoding'].includes(name.toLowerCase())) {\n response.setHeader(name, value);\n }\n }\n response.setHeader('Cache-Control', upstream.headers.get('cache-control') ?? 'no-store');\n if (!upstream.body) {\n response.end();\n return;\n }\n await new Promise<void>((resolve, reject) => {\n const readable = Readable.fromWeb(upstream.body as never);\n readable.once('error', reject);\n response.once('error', reject);\n response.once('finish', resolve);\n readable.pipe(response);\n });\n};\n\nconst readResponseBody = async (response: Response, maximumBytes: number, label: string): Promise<Buffer> => {\n const declaredLength = Number(response.headers.get('content-length'));\n if (Number.isFinite(declaredLength) && declaredLength > maximumBytes) {\n await response.body?.cancel();\n throw new Error(`${label} exceeded the configured size limit.`);\n }\n if (!response.body) {\n return Buffer.alloc(0);\n }\n\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let totalBytes = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n totalBytes += value.byteLength;\n if (totalBytes > maximumBytes) {\n await reader.cancel();\n throw new Error(`${label} exceeded the configured size limit.`);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks, totalBytes);\n};\n\nclass MfDevelopmentBff {\n readonly #configurationUrl: URL;\n readonly #developmentOrigin: URL;\n readonly #flows = new Map<string, IOidcFlow>();\n readonly #hostOrigin: URL;\n readonly #hostNavigationUrl: URL;\n readonly #jwks = new Map<string, ReturnType<typeof createRemoteJWKSet>>();\n readonly #logoutFlows = new Map<string, ILogoutFlow>();\n readonly #moduleApiOrigin: URL;\n readonly #moduleApiPath: string;\n readonly #sessions = new Map<string, ITokenSession>();\n #configurationPromise: Promise<IOidcClientConfiguration> | null = null;\n #discoveryPromise: Promise<IOidcDiscovery> | null = null;\n\n constructor(options: IMfDevelopmentBffPluginOptions) {\n const hostNavigation = absoluteHttpsUrl(options.hostNavigationUrl, 'hostNavigationUrl', true);\n this.#hostNavigationUrl = hostNavigation;\n this.#hostOrigin = new URL(hostNavigation.origin);\n this.#configurationUrl = new URL('/api/auth/oidc-configuration', this.#hostOrigin);\n this.#developmentOrigin = absoluteHttpsUrl(options.developmentOrigin ?? 'https://localhost:4200', 'developmentOrigin');\n if (this.#developmentOrigin.pathname !== '/' || this.#developmentOrigin.search || this.#developmentOrigin.hash) {\n throw new Error('developmentOrigin must be an origin without a path, query, or fragment.');\n }\n this.#moduleApiOrigin = absoluteHttpsUrl(options.moduleApiOrigin, 'moduleApiOrigin', true);\n if (this.#moduleApiOrigin.pathname !== '/' || this.#moduleApiOrigin.search || this.#moduleApiOrigin.hash) {\n throw new Error('moduleApiOrigin must be an origin without a path, query, or fragment.');\n }\n this.#moduleApiPath = moduleApiPrefix(options.moduleApiPath);\n }\n\n async handle(request: IncomingMessage, response: ServerResponse, next: (error?: unknown) => void): Promise<void> {\n if (!request.url || !request.method) {\n next();\n return;\n }\n const url = new URL(request.url, this.#developmentOrigin);\n this.#prune();\n\n try {\n if (request.method === 'GET' && url.pathname === MF_DEVELOPMENT_HOST_NAVIGATION_PATH) {\n await this.#hostNavigationResource(response, this.#hostNavigationUrl, 'script');\n return;\n }\n if (request.method === 'GET' && HOST_NAVIGATION_ASSET_PATHS.has(url.pathname)) {\n await this.#hostNavigationResource(response, new URL(url.pathname, this.#hostOrigin), 'asset');\n return;\n }\n if (request.method === 'GET' && url.pathname === LOGIN_PATH) {\n await this.#login(request, response, safeReturnTo(url.searchParams.get('returnTo')));\n return;\n }\n if (request.method === 'GET' && url.pathname === CALLBACK_PATH) {\n await this.#callback(request, response, url);\n return;\n }\n if (request.method === 'GET' && url.pathname === LOGGED_OUT_PATH) {\n const returnTo = safeReturnTo(url.searchParams.get('state'));\n redirect(response, `${LOGIN_PATH}?returnTo=${encodeURIComponent(returnTo)}`, [clearCookie(LOGOUT_COOKIE)]);\n return;\n }\n if (request.method === 'GET' && url.pathname === '/frontchannel-logout') {\n const sessionId = cookiesOf(request).get(SESSION_COOKIE);\n if (sessionId) {\n this.#sessions.delete(sessionId);\n }\n response.statusCode = 204;\n response.setHeader('Set-Cookie', clearCookie(SESSION_COOKIE));\n response.end();\n return;\n }\n if (request.method === 'POST' && url.pathname === '/api/auth/logout') {\n await this.#logout(request, response);\n return;\n }\n if (pathIsHostApi(url.pathname) || url.pathname.startsWith(this.#moduleApiPath)) {\n await this.#proxy(request, response, url);\n return;\n }\n next();\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Development authentication failed.';\n writeJson(response, 502, { code: 'development_authentication_failed', error: message });\n }\n }\n\n async #hostNavigationResource(response: ServerResponse, upstreamUrl: URL, kind: 'asset' | 'script'): Promise<void> {\n const upstream = await fetch(upstreamUrl, {\n headers: { Accept: kind === 'script' ? 'text/javascript, application/javascript' : 'image/svg+xml' },\n redirect: 'error',\n });\n if (!upstream.ok) {\n throw new Error(`Host navigation ${kind} failed (${upstream.status}).`);\n }\n const contentType = upstream.headers.get('content-type') ?? '';\n const validContentType =\n kind === 'script' ? /^(?:text|application)\\/javascript(?:;|$)/i.test(contentType) : /^image\\/svg\\+xml(?:;|$)/i.test(contentType);\n if (!validContentType) {\n throw new Error(`Host navigation ${kind} returned an invalid content type.`);\n }\n const maximumBytes = kind === 'script' ? MAX_HOST_NAVIGATION_BYTES : MAX_HOST_NAVIGATION_ASSET_BYTES;\n const body = await readResponseBody(upstream, maximumBytes, `Host navigation ${kind}`);\n response.statusCode = 200;\n response.setHeader('Cache-Control', 'no-store');\n response.setHeader('Content-Type', contentType);\n response.setHeader('X-Content-Type-Options', 'nosniff');\n response.end(body);\n }\n\n async #configuration(): Promise<IOidcClientConfiguration> {\n this.#configurationPromise ??= fetch(this.#configurationUrl, { headers: { Accept: 'application/json' }, redirect: 'error' })\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Host OIDC configuration failed (${response.status}).`);\n }\n const value: unknown = await response.json();\n if (!isRecord(value)) {\n throw new Error('Host OIDC configuration returned an invalid response.');\n }\n const issuer = absoluteHttpsUrl(requiredString(value, 'issuer'), 'OIDC issuer', true).href.replace(/\\/$/, '');\n return { clientId: requiredString(value, 'clientId'), issuer, scope: requiredString(value, 'scope') };\n })\n .catch((error) => {\n this.#configurationPromise = null;\n throw error;\n });\n return this.#configurationPromise;\n }\n\n async #discovery(): Promise<IOidcDiscovery> {\n this.#discoveryPromise ??= this.#configuration()\n .then(async (configuration) => {\n const response = await fetch(`${configuration.issuer}/.well-known/openid-configuration`, {\n headers: { Accept: 'application/json' },\n redirect: 'error',\n });\n if (!response.ok) {\n throw new Error(`OIDC discovery failed (${response.status}).`);\n }\n const value: unknown = await response.json();\n if (!isRecord(value)) {\n throw new Error('OIDC discovery returned an invalid response.');\n }\n const issuer = absoluteHttpsUrl(requiredString(value, 'issuer'), 'OIDC discovery issuer', true).href.replace(/\\/$/, '');\n if (issuer !== configuration.issuer) {\n throw new Error('OIDC discovery issuer does not match the host configuration.');\n }\n const endpoint = (key: string): string => {\n const url = absoluteHttpsUrl(requiredString(value, key), `OIDC ${key}`, true);\n if (url.origin !== new URL(issuer).origin) {\n throw new Error(`OIDC ${key} must use the configured issuer origin.`);\n }\n return url.href;\n };\n const revocation = optionalString(value, 'revocation_endpoint');\n return {\n authorizationEndpoint: endpoint('authorization_endpoint'),\n endSessionEndpoint: endpoint('end_session_endpoint'),\n issuer,\n jwksUri: endpoint('jwks_uri'),\n revocationEndpoint: revocation ? endpoint('revocation_endpoint') : null,\n tokenEndpoint: endpoint('token_endpoint'),\n };\n })\n .catch((error) => {\n this.#discoveryPromise = null;\n throw error;\n });\n return this.#discoveryPromise;\n }\n\n async #login(request: IncomingMessage, response: ServerResponse, returnTo: string): Promise<void> {\n const logoutId = cookiesOf(request).get(LOGOUT_COOKIE);\n if (logoutId) {\n const logout = this.#logoutFlows.get(logoutId);\n this.#logoutFlows.delete(logoutId);\n if (logout) {\n const [configuration, discovery] = await Promise.all([this.#configuration(), this.#discovery()]);\n const endpoint = new URL(discovery.endSessionEndpoint);\n endpoint.searchParams.set('client_id', configuration.clientId);\n endpoint.searchParams.set('post_logout_redirect_uri', new URL(LOGGED_OUT_PATH, this.#developmentOrigin).href);\n endpoint.searchParams.set('state', returnTo);\n if (logout.idToken) {\n endpoint.searchParams.set('id_token_hint', logout.idToken);\n }\n redirect(response, endpoint.href, [clearCookie(LOGOUT_COOKIE)]);\n return;\n }\n }\n\n const [configuration, discovery] = await Promise.all([this.#configuration(), this.#discovery()]);\n const flowId = base64Url();\n const codeVerifier = base64Url(48);\n const flow: IOidcFlow = { codeVerifier, createdAt: Date.now(), nonce: base64Url(), returnTo, state: base64Url() };\n this.#flows.set(flowId, flow);\n\n const endpoint = new URL(discovery.authorizationEndpoint);\n endpoint.searchParams.set('response_type', 'code');\n endpoint.searchParams.set('client_id', configuration.clientId);\n endpoint.searchParams.set('redirect_uri', new URL(CALLBACK_PATH, this.#developmentOrigin).href);\n endpoint.searchParams.set('scope', configuration.scope);\n endpoint.searchParams.set('state', flow.state);\n endpoint.searchParams.set('nonce', flow.nonce);\n endpoint.searchParams.set('code_challenge', codeChallengeOf(codeVerifier));\n endpoint.searchParams.set('code_challenge_method', 'S256');\n redirect(response, endpoint.href, [cookie(FLOW_COOKIE, flowId, FLOW_MAX_AGE_SECONDS)]);\n }\n\n async #callback(request: IncomingMessage, response: ServerResponse, url: URL): Promise<void> {\n const flowId = cookiesOf(request).get(FLOW_COOKIE);\n const flow = flowId ? this.#flows.get(flowId) : undefined;\n if (flowId) {\n this.#flows.delete(flowId);\n }\n if (!flow || url.searchParams.get('state') !== flow.state) {\n writeJson(response, 400, { code: 'invalid_oidc_state', error: 'The OIDC callback state is invalid or expired.' });\n return;\n }\n const providerError = url.searchParams.get('error');\n if (providerError) {\n writeJson(response, 401, { code: providerError, error: url.searchParams.get('error_description') ?? 'Sign-in was rejected.' });\n return;\n }\n const code = url.searchParams.get('code');\n if (!code) {\n writeJson(response, 400, { code: 'missing_authorization_code', error: 'The OIDC callback did not include an authorization code.' });\n return;\n }\n\n const [configuration, discovery] = await Promise.all([this.#configuration(), this.#discovery()]);\n const fields = new URLSearchParams({\n client_id: configuration.clientId,\n code,\n code_verifier: flow.codeVerifier,\n grant_type: 'authorization_code',\n redirect_uri: new URL(CALLBACK_PATH, this.#developmentOrigin).href,\n });\n const tokenResponse = await fetch(discovery.tokenEndpoint, {\n body: fields,\n headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' },\n method: 'POST',\n redirect: 'error',\n });\n if (!tokenResponse.ok) {\n throw new Error(`OIDC token exchange failed (${tokenResponse.status}).`);\n }\n const tokens = parseTokenResponse(await tokenResponse.json(), true);\n const idToken = tokens.idToken;\n if (!idToken) {\n throw new Error('OIDC token endpoint did not return an ID token.');\n }\n const jwks = this.#jwks.get(discovery.jwksUri) ?? createRemoteJWKSet(new URL(discovery.jwksUri));\n this.#jwks.set(discovery.jwksUri, jwks);\n const verified = await jwtVerify(idToken, jwks, {\n audience: configuration.clientId,\n issuer: discovery.issuer,\n requiredClaims: ['sub', 'nonce'],\n });\n if (verified.payload.nonce !== flow.nonce) {\n throw new Error('OIDC ID token nonce does not match the authorization request.');\n }\n\n const sessionId = base64Url();\n this.#sessions.set(sessionId, {\n accessToken: tokens.accessToken,\n expiresAt: Date.now() + tokens.expiresIn * 1000,\n idToken,\n moduleBootstrapTail: Promise.resolve(),\n moduleCookies: new Map(),\n moduleNavigationContext: null,\n refreshToken: tokens.refreshToken,\n });\n redirect(response, flow.returnTo, [cookie(SESSION_COOKIE, sessionId, SESSION_MAX_AGE_SECONDS), clearCookie(FLOW_COOKIE)]);\n }\n\n async #logout(request: IncomingMessage, response: ServerResponse): Promise<void> {\n const sessionId = cookiesOf(request).get(SESSION_COOKIE);\n const session = sessionId ? this.#sessions.get(sessionId) : undefined;\n if (sessionId) {\n this.#sessions.delete(sessionId);\n }\n if (session) {\n void this.#revoke(session).catch(() => undefined);\n }\n const logoutId = base64Url();\n this.#logoutFlows.set(logoutId, { createdAt: Date.now(), idToken: session?.idToken ?? null });\n response.setHeader('Set-Cookie', [clearCookie(SESSION_COOKIE), cookie(LOGOUT_COOKIE, logoutId, FLOW_MAX_AGE_SECONDS)]);\n writeJson(response, 200, { loggedOut: true });\n }\n\n async #revoke(session: ITokenSession): Promise<void> {\n const [configuration, discovery] = await Promise.all([this.#configuration(), this.#discovery()]);\n const revocationEndpoint = discovery.revocationEndpoint;\n if (!revocationEndpoint) {\n return;\n }\n const revoke = async (token: string, hint: string): Promise<void> => {\n await fetch(revocationEndpoint, {\n body: new URLSearchParams({ client_id: configuration.clientId, token, token_type_hint: hint }),\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n method: 'POST',\n redirect: 'error',\n });\n };\n await Promise.all([\n revoke(session.accessToken, 'access_token'),\n session.refreshToken ? revoke(session.refreshToken, 'refresh_token') : Promise.resolve(),\n ]);\n }\n\n async #authenticatedSession(request: IncomingMessage): Promise<ITokenSession | null> {\n const sessionId = cookiesOf(request).get(SESSION_COOKIE);\n const session = sessionId ? this.#sessions.get(sessionId) : undefined;\n if (!session) {\n return null;\n }\n if (session.expiresAt > Date.now() + TOKEN_REFRESH_SKEW_MS) {\n return session;\n }\n if (!session.refreshToken) {\n if (sessionId) {\n this.#sessions.delete(sessionId);\n }\n return null;\n }\n session.refreshPromise ??= this.#refresh(session).finally(() => {\n session.refreshPromise = undefined;\n });\n try {\n await session.refreshPromise;\n return session;\n } catch {\n if (sessionId) {\n this.#sessions.delete(sessionId);\n }\n return null;\n }\n }\n\n async #refresh(session: ITokenSession): Promise<void> {\n const refreshToken = session.refreshToken;\n if (!refreshToken) {\n throw new Error('OIDC refresh token is unavailable.');\n }\n const [configuration, discovery] = await Promise.all([this.#configuration(), this.#discovery()]);\n const response = await fetch(discovery.tokenEndpoint, {\n body: new URLSearchParams({\n client_id: configuration.clientId,\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n }),\n headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' },\n method: 'POST',\n redirect: 'error',\n });\n if (!response.ok) {\n throw new Error(`OIDC refresh failed (${response.status}).`);\n }\n const tokens = parseTokenResponse(await response.json(), false);\n session.accessToken = tokens.accessToken;\n session.expiresAt = Date.now() + tokens.expiresIn * 1000;\n session.refreshToken = tokens.refreshToken ?? session.refreshToken;\n session.idToken = tokens.idToken ?? session.idToken;\n }\n\n async #proxy(request: IncomingMessage, response: ServerResponse, localUrl: URL): Promise<void> {\n const session = await this.#authenticatedSession(request);\n if (!session) {\n writeJson(response, 401, { code: 'missing_access_token', error: 'Sign in is required.' });\n return;\n }\n const isModuleApi = localUrl.pathname.startsWith(this.#moduleApiPath);\n if (isModuleApi && session.moduleCookies.size === 0) {\n const previous = session.moduleBootstrapTail;\n let release = (): void => {};\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n session.moduleBootstrapTail = previous.catch(() => undefined).then(() => current);\n await previous.catch(() => undefined);\n try {\n await this.#proxyAuthenticated(request, response, localUrl, session, true);\n } finally {\n release();\n }\n return;\n }\n await this.#proxyAuthenticated(request, response, localUrl, session, isModuleApi);\n }\n\n async #proxyAuthenticated(\n request: IncomingMessage,\n response: ServerResponse,\n localUrl: URL,\n session: ITokenSession,\n isModuleApi: boolean,\n ): Promise<void> {\n const upstreamOrigin = isModuleApi ? this.#moduleApiOrigin : this.#hostOrigin;\n const upstreamUrl = new URL(`${localUrl.pathname}${localUrl.search}`, upstreamOrigin);\n const method = request.method ?? 'GET';\n const init: RequestInit & { duplex?: 'half' } = {\n headers: proxyHeaders(\n request,\n session.accessToken,\n isModuleApi ? session.moduleCookies : undefined,\n isModuleApi ? session.moduleNavigationContext : undefined,\n ),\n method,\n redirect: 'manual',\n };\n if (method !== 'GET' && method !== 'HEAD') {\n init.body = Readable.toWeb(request) as unknown as BodyInit;\n init.duplex = 'half';\n }\n const upstream = await fetch(upstreamUrl, init);\n if (isModuleApi) {\n updateModuleCookies(session.moduleCookies, upstream.headers);\n } else if (localUrl.pathname === '/api/navigation' && upstream.ok) {\n session.moduleNavigationContext = navigationContextIn(\n await upstream\n .clone()\n .json()\n .catch(() => null),\n );\n }\n await copyProxyResponse(upstream, response);\n }\n\n #prune(): void {\n const now = Date.now();\n for (const [id, flow] of this.#flows) {\n if (flow.createdAt + FLOW_MAX_AGE_SECONDS * 1000 < now) {\n this.#flows.delete(id);\n }\n }\n for (const [id, flow] of this.#logoutFlows) {\n if (flow.createdAt + FLOW_MAX_AGE_SECONDS * 1000 < now) {\n this.#logoutFlows.delete(id);\n }\n }\n for (const [id, session] of this.#sessions) {\n if (!session.refreshToken && session.expiresAt + TOKEN_REFRESH_SKEW_MS < now) {\n this.#sessions.delete(id);\n }\n }\n }\n}\n\nexport const mfDevelopmentBffPlugin = (options: IMfDevelopmentBffPluginOptions): Plugin => {\n const middleware = createMfDevelopmentBffMiddleware(options);\n return {\n apply: 'serve',\n name: 'edynamix-mf-development-bff',\n configureServer(server) {\n server.middlewares.use((request, response, next) => {\n middleware(request, response, next);\n });\n },\n };\n};\n\nexport type TMfDevelopmentBffMiddleware = (request: IncomingMessage, response: ServerResponse, next: (error?: unknown) => void) => void;\n\nexport const createMfDevelopmentBffMiddleware = (options: IMfDevelopmentBffPluginOptions): TMfDevelopmentBffMiddleware => {\n const bff = new MfDevelopmentBff(options);\n return (request, response, next) => {\n void bff.handle(request, response, next);\n };\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@edynamix/mf-isolation",
3
- "version": "0.0.9",
3
+ "version": "0.0.11",
4
4
  "description": "CSS and overlay isolation helpers for eDynamix microfrontends.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -37,10 +37,18 @@
37
37
  "types": "./dist/navigation.d.ts",
38
38
  "import": "./dist/navigation.js"
39
39
  },
40
+ "./host-navigation": {
41
+ "types": "./dist/host-navigation.d.ts",
42
+ "import": "./dist/host-navigation.js"
43
+ },
40
44
  "./vite": {
41
45
  "types": "./dist/vite.d.ts",
42
46
  "import": "./dist/vite.js"
43
47
  },
48
+ "./vite-development": {
49
+ "types": "./dist/vite-development.d.ts",
50
+ "import": "./dist/vite-development.js"
51
+ },
44
52
  "./package.json": "./package.json"
45
53
  },
46
54
  "scripts": {
@@ -62,6 +70,7 @@
62
70
  "access": "public"
63
71
  },
64
72
  "dependencies": {
73
+ "jose": "^6.2.9",
65
74
  "postcss": "^8.5.16",
66
75
  "postcss-selector-parser": "^7.1.4",
67
76
  "postcss-value-parser": "^4.2.0"