@mpfrontend/security-bff 0.1.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js ADDED
@@ -0,0 +1,880 @@
1
+ import { createHash, createPublicKey, randomBytes, randomUUID, sign as signData, verify, timingSafeEqual } from 'node:crypto';
2
+ import { setTimeout as delay } from 'node:timers/promises';
3
+ import { createPreferenceCookie, negotiateLocale } from '@mpfrontend/i18n';
4
+ import { createMemorySessionVault } from './session-store-core.js';
5
+ /** The response headers a streamed route may pass to the client; no other upstream header ever crosses. */
6
+ export const STREAM_RESPONSE_HEADERS = Object.freeze(['content-type', 'content-length', 'content-disposition', 'content-security-policy']);
7
+ /** English only, MP Frontend's one built-in language; a product lists the locales its backends answer in. */
8
+ export const defaultApiLocales = Object.freeze({ supported: Object.freeze(['en']), defaultLocale: 'en' });
9
+ /** A client assertion lives this long (RFC 7523 recommends a short lifetime). */
10
+ export const CLIENT_ASSERTION_LIFETIME_SECONDS = 60;
11
+ function signingKey(source) {
12
+ const key = typeof source === 'function' ? source() : source;
13
+ if (!key || typeof key.keyId !== 'string' || !/^[\x21-\x7e]{1,128}$/.test(key.keyId) || key.privateKey?.type !== 'private')
14
+ throw new Error('INVALID_CLIENT_SIGNING_KEY');
15
+ const algorithm = key.algorithm ?? (key.privateKey.asymmetricKeyType === 'ec' ? 'ES256' : 'RS256');
16
+ const type = key.privateKey.asymmetricKeyType;
17
+ if (!((algorithm === 'ES256' && type === 'ec') || ((algorithm === 'RS256' || algorithm === 'PS256') && (type === 'rsa' || type === 'rsa-pss'))))
18
+ throw new Error('INVALID_CLIENT_SIGNING_KEY');
19
+ return { ...key, algorithm };
20
+ }
21
+ /** A private_key_jwt client assertion (RFC 7523 section 3): iss and sub are the client, aud the token endpoint. */
22
+ export function clientAssertion(clientId, audience, source, now = Date.now()) {
23
+ const key = signingKey(source), issued = Math.floor(now / 1000);
24
+ const header = Buffer.from(JSON.stringify({ alg: key.algorithm, kid: key.keyId, typ: 'JWT' })).toString('base64url');
25
+ const payload = Buffer.from(JSON.stringify({ iss: clientId, sub: clientId, aud: audience, jti: randomUUID(), iat: issued, exp: issued + CLIENT_ASSERTION_LIFETIME_SECONDS })).toString('base64url');
26
+ const input = Buffer.from(header + '.' + payload);
27
+ const signature = key.algorithm === 'ES256' ? signData('sha256', input, { key: key.privateKey, dsaEncoding: 'ieee-p1363' })
28
+ : key.algorithm === 'PS256' ? signData('sha256', input, { key: key.privateKey, padding: 6, saltLength: 32 }) : signData('sha256', input, key.privateKey);
29
+ return header + '.' + payload + '.' + signature.toString('base64url');
30
+ }
31
+ /** The unmet conditions of a production configuration, in a stable order; empty when it may start. */
32
+ export function productionRefusals(config) {
33
+ const refusals = [], profile = config.production;
34
+ const https = (value) => { try {
35
+ return value !== undefined && new URL(value).protocol === 'https:';
36
+ }
37
+ catch {
38
+ return false;
39
+ } };
40
+ if (!https(config.publicOrigin))
41
+ refusals.push('HTTPS_PUBLIC_ORIGIN_REQUIRED');
42
+ if (!https(config.issuer) || (config.providerOrigin !== undefined && !https(config.providerOrigin)))
43
+ refusals.push('HTTPS_IDENTITY_PROVIDER_REQUIRED');
44
+ const security = profile?.sessionVault?.security;
45
+ if (!security?.durable)
46
+ refusals.push('DURABLE_SESSION_VAULT_REQUIRED');
47
+ if (!security?.tls)
48
+ refusals.push('SESSION_VAULT_TLS_REQUIRED');
49
+ if (!security?.authenticated)
50
+ refusals.push('SESSION_VAULT_AUTHENTICATION_REQUIRED');
51
+ if (!security?.hostKeyRing)
52
+ refusals.push('HOST_KEY_RING_REQUIRED');
53
+ const client = profile?.clientAuthentication;
54
+ // A public client counts only when the configuration declares it explicitly.
55
+ const configured = client?.method === 'none' ? client.publicClient === true
56
+ : client?.method === 'client_secret_basic' ? client.secret !== undefined && client.secret !== ''
57
+ : client?.method === 'private_key_jwt' ? client.key !== undefined : false;
58
+ if (!configured)
59
+ refusals.push('CLIENT_AUTHENTICATION_REQUIRED');
60
+ if (profile?.secureCookies !== true)
61
+ refusals.push('SECURE_COOKIES_REQUIRED');
62
+ return refusals;
63
+ }
64
+ export const SESSION_LIMITS = Object.freeze({ defaultIdleTimeoutSeconds: 1800, maxIdleTimeoutSeconds: 86400, defaultAbsoluteLifetimeSeconds: 28800, maxAbsoluteLifetimeSeconds: 604800 });
65
+ export const defaultAuthorizationClaims = Object.freeze(['realm_access', 'resource_access', 'groups', 'scope', 'tenant_id']);
66
+ const opaque = () => randomBytes(32).toString('base64url');
67
+ const jsonHeaders = { 'content-type': 'application/json', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' };
68
+ function equal(left, right) { const a = Buffer.from(left), b = Buffer.from(right); return a.length === b.length && timingSafeEqual(a, b); }
69
+ function cookieValue(header, name) { return header?.split(';').map(v => v.trim()).find(v => v.startsWith(name + '='))?.slice(name.length + 1); }
70
+ function origin(value) { const u = new URL(value); if (!['http:', 'https:'].includes(u.protocol) || u.username || u.password || u.pathname !== '/' || u.search || u.hash)
71
+ throw new Error('INVALID_ORIGIN'); return u.origin; }
72
+ function fail(status, code) { throw Object.assign(new Error(code), { status }); }
73
+ // Only this private transport/status classification can retain a refresh record. Generic503 errors
74
+ // (vault integrity, malformed responses, failed validation or CAS) must never gain this exception.
75
+ class IdentityUnavailable extends Error {
76
+ status = 503;
77
+ constructor() { super('IDENTITY_UNAVAILABLE'); }
78
+ }
79
+ const MAX_PROJECTION = 4096, compactToken = /^[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*$/;
80
+ /** The allowlisted claims for /context, bounded in size. A token, an object or an oversized value is left out. */
81
+ export function projectClaims(claims, allowed) {
82
+ const projection = {};
83
+ let size = 2;
84
+ const plain = (value) => typeof value === 'number' ? Number.isFinite(value) : typeof value === 'boolean' || (typeof value === 'string' && value.length <= 512 && !compactToken.test(value));
85
+ for (const name of allowed) {
86
+ const value = claims[name];
87
+ const accepted = plain(value) ? value : Array.isArray(value) && value.length <= 16 && value.every(entry => typeof entry === 'string' && entry.length <= 128 && !compactToken.test(entry)) ? Object.freeze([...value]) : undefined;
88
+ if (accepted === undefined)
89
+ continue;
90
+ const cost = JSON.stringify(name).length + JSON.stringify(accepted).length + 2;
91
+ if (size + cost > MAX_PROJECTION)
92
+ continue;
93
+ size += cost;
94
+ projection[name] = accepted;
95
+ }
96
+ return Object.freeze(projection);
97
+ }
98
+ function write(res, status, body) { res.writeHead(status, jsonHeaders); res.end(JSON.stringify(body)); }
99
+ async function body(req) { const chunks = []; let size = 0; for await (const raw of req) {
100
+ const chunk = Buffer.from(raw);
101
+ size += chunk.length;
102
+ if (size > 65536)
103
+ fail(413, 'BODY_TOO_LARGE');
104
+ chunks.push(chunk);
105
+ } return Buffer.concat(chunks); }
106
+ const mediaTypePattern = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
107
+ /** The media type of a Content-Type value, without its parameters and in lower case; undefined when there is none. */
108
+ function mediaType(value) { const type = value?.split(';')[0].trim().toLowerCase(); return type || undefined; }
109
+ /** The longest timeout a streamed route may set: one day. */
110
+ const STREAM_TIMEOUT_MAX_MS = 86400000;
111
+ /**
112
+ * Media types whose document runs script when a browser shows it inline on the app's origin: HTML, XHTML, SVG, any
113
+ * XML and script itself. A streamed answer of one of them must pass a Content-Disposition and a
114
+ * Content-Security-Policy, so that the route can serve it as an attachment or sandbox it.
115
+ */
116
+ const scriptCapable = (type) => ['text/html', 'application/xhtml+xml', 'image/svg+xml', 'text/xml', 'application/xml',
117
+ 'text/javascript', 'application/javascript', 'application/ecmascript', 'text/ecmascript'].includes(type) || type.endsWith('+xml');
118
+ /**
119
+ * Whether the answer of a script-capable type is safe to serve inline: an attachment, which a browser saves, or a
120
+ * Content-Security-Policy with the sandbox directive, which gives the document no origin. The startup check only
121
+ * proves that the route may pass both headers; the upstream decides at run time whether it sent them.
122
+ */
123
+ const attachment = (value) => value !== null && /^\s*attachment\s*(;|$)/i.test(value);
124
+ const sandboxed = (value) => value !== null && /(^|;)\s*sandbox\s*(;|\s|$)/i.test(value);
125
+ /** Refuses a stream policy that is incomplete or out of bounds; nothing is filled in with a default. */
126
+ function checkStream(route) {
127
+ const stream = route.stream, refuse = () => { throw new Error('INVALID_ROUTE_STREAM'); };
128
+ // An in-process route keeps its contract: one body in, one JSON answer out.
129
+ if (route.invoke)
130
+ refuse();
131
+ const types = (list) => Array.isArray(list) && list.length > 0 && list.length <= 32 && new Set(list).size === list.length && list.every(type => typeof type === 'string' && mediaTypePattern.test(type));
132
+ if (route.method === 'GET') {
133
+ if (stream.requestTypes !== undefined || stream.maxRequestBytes !== undefined)
134
+ refuse();
135
+ }
136
+ else if (!types(stream.requestTypes) || !Number.isSafeInteger(stream.maxRequestBytes) || stream.maxRequestBytes < 1)
137
+ refuse();
138
+ if (!types(stream.responseTypes))
139
+ refuse();
140
+ const names = stream.responseHeaders;
141
+ if (!Array.isArray(names) || new Set(names).size !== names.length || !names.every(name => STREAM_RESPONSE_HEADERS.includes(name)) || !names.includes('content-type'))
142
+ refuse();
143
+ if (stream.responseTypes.some(scriptCapable) && !(names.includes('content-disposition') && names.includes('content-security-policy')))
144
+ throw new Error('INVALID_ROUTE_STREAM:SCRIPT_CAPABLE_TYPE');
145
+ const time = (value) => Number.isSafeInteger(value) && value >= 10 && value <= STREAM_TIMEOUT_MAX_MS;
146
+ if (!time(stream.idleTimeoutMs) || !time(stream.totalTimeoutMs) || !time(stream.sessionCheckMs) || stream.idleTimeoutMs > stream.totalTimeoutMs || stream.sessionCheckMs > stream.totalTimeoutMs)
147
+ refuse();
148
+ }
149
+ export function createBff(config) {
150
+ if ('production' in config && config.production !== undefined) {
151
+ // No condition falls back: a missing one refuses startup and names what is missing.
152
+ const refusals = productionRefusals(config);
153
+ if (refusals.length)
154
+ throw new Error('PRODUCTION_PROFILE_REFUSED:' + refusals.join(','));
155
+ }
156
+ else if (config.development !== true || process.env.NODE_ENV === 'production')
157
+ throw new Error('DURABLE_SESSION_STORE_REQUIRED');
158
+ const production = 'production' in config && config.production !== undefined ? config.production : undefined;
159
+ const ordinaryLoginTimeoutSeconds = config.ordinaryLoginTimeoutSeconds ?? 300;
160
+ if (!Number.isSafeInteger(ordinaryLoginTimeoutSeconds) || ordinaryLoginTimeoutSeconds < 300 || ordinaryLoginTimeoutSeconds > 600)
161
+ throw new Error('INVALID_ORDINARY_LOGIN_TIMEOUT');
162
+ const publicOrigin = origin(config.publicOrigin), issuer = config.issuer.replace(/\/$/, '');
163
+ const providerOrigin = config.providerOrigin ? origin(config.providerOrigin) : new URL(issuer).origin;
164
+ if (!/^(?:__Host-)?[a-z][a-z0-9_]{1,60}$/.test(config.cookieName))
165
+ throw new Error('INVALID_COOKIE_NAME');
166
+ const supportedUiLocales = new Set(config.supportedUiLocales ?? []);
167
+ if ([...supportedUiLocales].some(value => !/^[-a-zA-Z0-9]{2,16}$/.test(value)))
168
+ throw new Error('INVALID_UI_LOCALE');
169
+ if (config.uiLocaleCookie && !/^[a-z][a-z0-9_]{1,60}$/.test(config.uiLocaleCookie))
170
+ throw new Error('INVALID_UI_LOCALE_COOKIE');
171
+ const contextClaims = [...(config.contextClaims ?? [])], claimSource = config.contextClaimSource ?? 'id';
172
+ if (contextClaims.length > 32 || new Set(contextClaims).size !== contextClaims.length || contextClaims.some(name => !/^[a-zA-Z][a-zA-Z0-9_:.-]{0,63}$/.test(name) || /token/i.test(name) || ['at_hash', 'c_hash', 'nonce'].includes(name)))
173
+ throw new Error('INVALID_CONTEXT_CLAIMS');
174
+ if (claimSource !== 'id' && claimSource !== 'access')
175
+ throw new Error('INVALID_CONTEXT_CLAIMS');
176
+ const preferences = config.preferenceCookie ? createPreferenceCookie(config.preferenceCookie) : undefined;
177
+ const backChannel = config.backChannelLogout === true;
178
+ const acrToken = /^[\x21-\x7e]{1,128}$/;
179
+ const acrAllowlist = new Set(config.acrValues ?? []);
180
+ if ([...acrAllowlist].some(value => !acrToken.test(value)))
181
+ throw new Error('INVALID_ACR_VALUES');
182
+ const returnPaths = config.returnPaths ?? ['/'];
183
+ for (const route of config.routes) {
184
+ const requirement = route.authentication;
185
+ if (!requirement)
186
+ continue;
187
+ if (requirement.maxAge !== undefined && (!Number.isSafeInteger(requirement.maxAge) || requirement.maxAge < 0 || requirement.maxAge > 86400))
188
+ throw new Error('INVALID_ROUTE_AUTHENTICATION');
189
+ if (requirement.acr !== undefined && (!requirement.acr.length || requirement.acr.some(value => !acrAllowlist.has(value))))
190
+ throw new Error('INVALID_ROUTE_AUTHENTICATION');
191
+ }
192
+ /** A same-origin path from the allowlist, or undefined: never another origin, never a protocol-relative path. */
193
+ const returnPath = (value) => {
194
+ if (value === null)
195
+ return undefined;
196
+ if (value.length > 512 || !/^\/(?![/\\])[^\s\\]*$/.test(value))
197
+ return null;
198
+ let parsed;
199
+ try {
200
+ parsed = new URL(value, publicOrigin);
201
+ }
202
+ catch {
203
+ return null;
204
+ }
205
+ if (parsed.origin !== publicOrigin)
206
+ return null;
207
+ return returnPaths.some(path => typeof path === 'string' ? path === parsed.pathname : path.test(parsed.pathname)) ? parsed.pathname + parsed.search : null;
208
+ };
209
+ /** The step-up the current session needs for a requirement, or undefined when it is enough. */
210
+ const needsStepUp = (value, requirement) => {
211
+ if (!requirement)
212
+ return false;
213
+ const stale = requirement.maxAge !== undefined && (value.authTime === undefined || (value.authTime + requirement.maxAge) * 1000 < Date.now());
214
+ const weak = requirement.acr !== undefined && (value.acr === undefined || !requirement.acr.includes(value.acr));
215
+ return stale || weak;
216
+ };
217
+ const stepUp = (res, requirement, resubmit) => {
218
+ const query = new URLSearchParams();
219
+ if (requirement.maxAge !== undefined)
220
+ query.set('max_age', String(requirement.maxAge));
221
+ if (requirement.acr)
222
+ query.set('acr_values', requirement.acr.join(' '));
223
+ const challenge = { ...(requirement.maxAge !== undefined ? { maxAge: requirement.maxAge } : {}), ...(requirement.acr ? { acrValues: [...requirement.acr] } : {}),
224
+ login: '/api/session/login' + (query.size ? '?' + query : ''), resubmit };
225
+ write(res, 401, { type: 'about:blank', status: 401, title: 'STEP_UP_REQUIRED', stepUp: challenge });
226
+ };
227
+ /** An RFC 9470 challenge of an upstream API, reduced to the values the step-up needs. */
228
+ const upstreamStepUp = (header) => {
229
+ if (!header || !/^Bearer\s/i.test(header))
230
+ return undefined;
231
+ const parameters = Object.fromEntries([...header.matchAll(/([a-z_]+)="([^"]*)"/gi)].map(match => [match[1].toLowerCase(), match[2]]));
232
+ if (parameters.error !== 'insufficient_user_authentication')
233
+ return undefined;
234
+ const maxAge = parameters.max_age !== undefined && /^\d{1,5}$/.test(parameters.max_age) ? Number(parameters.max_age) : undefined;
235
+ const acr = parameters.acr_values?.split(' ').filter(value => acrAllowlist.has(value));
236
+ if (maxAge === undefined && !acr?.length)
237
+ return undefined;
238
+ return { ...(maxAge !== undefined ? { maxAge } : {}), ...(acr?.length ? { acr } : {}) };
239
+ };
240
+ const apiLocales = config.apiLocales ?? defaultApiLocales;
241
+ if (!apiLocales.supported.length || apiLocales.supported.some(value => !/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/.test(value)) || !apiLocales.supported.includes(apiLocales.defaultLocale))
242
+ throw new Error('INVALID_API_LOCALES');
243
+ for (const route of config.routes) {
244
+ origin(route.origin);
245
+ if (route.pattern.global || route.pattern.sticky)
246
+ throw new Error('STATEFUL_ROUTE_PATTERN');
247
+ if (route.stream !== undefined)
248
+ checkStream(route);
249
+ }
250
+ // Production never uses the memory vault; development keeps it as its default.
251
+ const vault = production ? production.sessionVault : config.sessionVault ?? createMemorySessionVault();
252
+ let keys = [], keysUntil = 0;
253
+ // __Host-: Secure, Path=/ and no Domain, so no other host or path can set or read the session cookie.
254
+ const productionPrefix = production !== undefined && production.hostPrefix !== false;
255
+ const sessionCookie = config.cookieName.startsWith('__Host-') || !productionPrefix ? config.cookieName : '__Host-' + config.cookieName;
256
+ if (sessionCookie.startsWith('__Host-') && !publicOrigin.startsWith('https:'))
257
+ throw new Error('HOST_PREFIX_REQUIRES_HTTPS');
258
+ const transactionCookie = sessionCookie + '_login';
259
+ const policy = config.session ?? {};
260
+ const sameSite = policy.sameSite ?? (production ? 'Strict' : 'Lax');
261
+ const idleSeconds = policy.idleTimeoutSeconds ?? SESSION_LIMITS.defaultIdleTimeoutSeconds;
262
+ const absoluteSeconds = policy.absoluteLifetimeSeconds ?? SESSION_LIMITS.defaultAbsoluteLifetimeSeconds;
263
+ if (sameSite !== 'Strict' && sameSite !== 'Lax')
264
+ throw new Error('INVALID_SESSION_POLICY');
265
+ if (!Number.isSafeInteger(idleSeconds) || idleSeconds < 60 || idleSeconds > SESSION_LIMITS.maxIdleTimeoutSeconds)
266
+ throw new Error('INVALID_SESSION_POLICY');
267
+ if (!Number.isSafeInteger(absoluteSeconds) || absoluteSeconds < 300 || absoluteSeconds > SESSION_LIMITS.maxAbsoluteLifetimeSeconds || idleSeconds > absoluteSeconds)
268
+ throw new Error('INVALID_SESSION_POLICY');
269
+ const authorizationClaims = [...(policy.authorizationClaims ?? defaultAuthorizationClaims)];
270
+ const authority = (claims) => JSON.stringify(authorizationClaims.map(name => claims[name] ?? null));
271
+ // Activity is recorded at most this often, so that an idle timeout does not cost a write per request.
272
+ const touchMs = Math.min(60000, idleSeconds * 100);
273
+ const secure = production !== undefined || publicOrigin.startsWith('https:');
274
+ const cookie = (name, value, maxAge, site = 'Lax') => name + '=' + value + '; HttpOnly; SameSite=' + site + '; Path=/; Max-Age=' + maxAge + (secure || name.startsWith('__Host-') ? '; Secure' : '');
275
+ const sessionSetCookie = (id, maxAge) => cookie(sessionCookie, id, maxAge, sameSite);
276
+ const provider = (path) => providerOrigin + new URL(issuer).pathname + '/protocol/openid-connect/' + path;
277
+ async function identityResponse(path, options = {}) {
278
+ let response;
279
+ try {
280
+ response = await fetch(provider(path), { ...options, redirect: 'error', signal: AbortSignal.timeout(8000) });
281
+ }
282
+ catch {
283
+ throw new IdentityUnavailable();
284
+ }
285
+ if (response.status === 429 || response.status >= 500)
286
+ throw new IdentityUnavailable();
287
+ return response;
288
+ }
289
+ async function validate(token, audience, nonce, subjectOptional = false) {
290
+ const parts = token.split('.');
291
+ if (parts.length !== 3)
292
+ fail(401, 'INVALID_TOKEN');
293
+ const header = JSON.parse(Buffer.from(parts[0], 'base64url').toString());
294
+ if (header.alg !== 'RS256' || !header.kid)
295
+ fail(401, 'INVALID_TOKEN');
296
+ if (Date.now() > keysUntil || !keys.some(k => k.kid === header.kid)) {
297
+ const response = await identityResponse('certs');
298
+ if (!response.ok)
299
+ fail(401, 'INVALID_IDENTITY_RESPONSE');
300
+ const jwks = await response.json();
301
+ keys = jwks.keys.filter(k => k.kty === 'RSA' && (!k.alg || k.alg === 'RS256') && (!k.use || k.use === 'sig')).map(jwk => ({ kid: jwk.kid, jwk }));
302
+ keysUntil = Date.now() + 60000;
303
+ }
304
+ const key = keys.find(k => k.kid === header.kid);
305
+ if (!key || !verify('RSA-SHA256', Buffer.from(parts[0] + '.' + parts[1]), createPublicKey({ key: key.jwk, format: 'jwk' }), Buffer.from(parts[2], 'base64url')))
306
+ fail(401, 'INVALID_TOKEN');
307
+ const claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString()), now = Math.floor(Date.now() / 1000);
308
+ if (claims.iss !== issuer || (!claims.sub && !subjectOptional) || (claims.sub !== undefined && typeof claims.sub !== 'string') || !Number.isFinite(claims.exp) || claims.exp <= now || !Number.isFinite(claims.iat) || claims.iat > now + 30 || (claims.nbf !== undefined && claims.nbf > now + 30) || !(Array.isArray(claims.aud) ? claims.aud.includes(audience) : claims.aud === audience))
309
+ fail(401, 'INVALID_TOKEN');
310
+ if (audience === config.clientId && ((Array.isArray(claims.aud) && claims.aud.length > 1 && !claims.azp) || (claims.azp && claims.azp !== config.clientId)))
311
+ fail(401, 'INVALID_TOKEN');
312
+ if (nonce !== undefined && claims.nonce !== nonce)
313
+ fail(401, 'INVALID_NONCE');
314
+ return claims;
315
+ }
316
+ if (backChannel && (!vault.indexSession || !vault.revokeIndexed))
317
+ throw new Error('BACKCHANNEL_LOGOUT_VAULT_UNSUPPORTED');
318
+ /**
319
+ * Indexes a session by the provider's session id and by subject, for back-channel logout. A session is
320
+ * indexed before it is stored: when indexing fails no session exists that a logout could not find, and an
321
+ * index entry without its session is harmless.
322
+ */
323
+ async function index(id, value) {
324
+ if (backChannel)
325
+ await vault.indexSession(id, { ...(value.sid ? { sid: value.sid } : {}), sub: value.claims.sub }, value.absoluteExpires);
326
+ }
327
+ const clientAuthentication = production ? production.clientAuthentication : config.clientAuthentication;
328
+ if (clientAuthentication?.method === 'private_key_jwt')
329
+ signingKey(clientAuthentication.key);
330
+ if (clientAuthentication?.method === 'client_secret_basic' && (typeof clientAuthentication.secret === 'string' ? !clientAuthentication.secret : typeof clientAuthentication.secret !== 'function'))
331
+ throw new Error('INVALID_CLIENT_SECRET');
332
+ // The assertion audience is the token endpoint as the issuer names it, not an internal provider origin.
333
+ const tokenEndpoint = issuer + '/protocol/openid-connect/token';
334
+ /** Client authentication for a request to the provider; the credential goes only into this request. */
335
+ function authenticate(parameters) {
336
+ parameters.set('client_id', config.clientId);
337
+ if (clientAuthentication?.method === 'client_secret_basic') {
338
+ const secret = typeof clientAuthentication.secret === 'function' ? clientAuthentication.secret() : clientAuthentication.secret;
339
+ // RFC 6749 section 2.3.1: both parts are form-urlencoded before Base64.
340
+ const encode = (value) => encodeURIComponent(value).replace(/%20/g, '+');
341
+ return { authorization: 'Basic ' + Buffer.from(encode(config.clientId) + ':' + encode(secret)).toString('base64') };
342
+ }
343
+ if (clientAuthentication?.method === 'private_key_jwt') {
344
+ parameters.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');
345
+ parameters.set('client_assertion', clientAssertion(config.clientId, tokenEndpoint, clientAuthentication.key));
346
+ }
347
+ return {};
348
+ }
349
+ async function tokenRequest(parameters) {
350
+ const headers = authenticate(parameters);
351
+ const response = await identityResponse('token', { method: 'POST', body: parameters, headers });
352
+ if (!response.ok)
353
+ fail(401, 'LOGIN_REQUIRED');
354
+ const result = await response.json();
355
+ if (!result.access_token || !result.refresh_token)
356
+ fail(401, 'INVALID_TOKEN_RESPONSE');
357
+ return result;
358
+ }
359
+ async function session(req, refresh = true) {
360
+ const id = cookieValue(req.headers.cookie, sessionCookie);
361
+ if (!id || !/^[-_a-zA-Z0-9]{43}$/.test(id))
362
+ fail(401, 'LOGIN_REQUIRED');
363
+ const deadline = Date.now() + 10000;
364
+ for (;;) {
365
+ const record = await vault.read('session', id), value = record?.value;
366
+ if (!record || !value || value.absoluteExpires <= Date.now())
367
+ fail(401, 'LOGIN_REQUIRED');
368
+ // An idle session fails closed and is removed; activity is the last authenticated request.
369
+ if ((value.lastSeen ?? Date.now()) + idleSeconds * 1000 <= Date.now()) {
370
+ await vault.remove('session', id);
371
+ fail(401, 'LOGIN_REQUIRED');
372
+ }
373
+ const stale = Date.now() - (value.lastSeen ?? 0) >= touchMs;
374
+ if (!refresh || value.expires >= Date.now() + 30000) {
375
+ if (!stale)
376
+ return { id, value };
377
+ // Record activity under the lease; a busy lease means another request is already writing.
378
+ const owner = opaque();
379
+ if (!await vault.acquire(id, owner, 30000))
380
+ return { id, value };
381
+ try {
382
+ const current = await vault.read('session', id);
383
+ if (!current)
384
+ fail(401, 'LOGIN_REQUIRED');
385
+ const next = { ...current.value, lastSeen: Date.now() };
386
+ return { id, value: await vault.update(id, current, next, owner) ? next : current.value };
387
+ }
388
+ finally {
389
+ await vault.release(id, owner);
390
+ }
391
+ }
392
+ const owner = opaque();
393
+ if (!await vault.acquire(id, owner, 30000)) {
394
+ if (Date.now() >= deadline)
395
+ fail(503, 'SESSION_REFRESH_BUSY');
396
+ await delay(50);
397
+ continue;
398
+ }
399
+ try {
400
+ // Another replica may have refreshed or revoked after our first read.
401
+ const current = await vault.read('session', id);
402
+ if (!current)
403
+ fail(401, 'LOGIN_REQUIRED');
404
+ if (current.value.expires >= Date.now() + 30000)
405
+ return { id, value: current.value };
406
+ const tokens = await tokenRequest(new URLSearchParams({ grant_type: 'refresh_token', refresh_token: current.value.refresh }));
407
+ const claims = await validate(tokens.access_token, config.audience);
408
+ if (claims.sub !== current.value.claims.sub || claims.tenant_id !== current.value.claims.tenant_id)
409
+ fail(401, 'SESSION_CHANGED');
410
+ // The projection follows a refreshed ID token of the same subject, or the refreshed access token.
411
+ let identity = current.value.identity;
412
+ if (claimSource === 'access')
413
+ identity = projectClaims(claims, contextClaims);
414
+ else if (tokens.id_token) {
415
+ const refreshed = await validate(tokens.id_token, config.clientId);
416
+ if (refreshed.sub !== claims.sub)
417
+ fail(401, 'SESSION_CHANGED');
418
+ identity = projectClaims(refreshed, contextClaims);
419
+ }
420
+ const next = { ...current.value, access: tokens.access_token, refresh: tokens.refresh_token, claims, ...(identity ? { identity } : {}), expires: claims.exp * 1000, lastSeen: Date.now() };
421
+ if (authority(claims) !== authority(current.value.claims)) {
422
+ // Changed roles or authorization claims rotate the session id: a new record, the old one removed.
423
+ const rotated = opaque();
424
+ await index(rotated, next);
425
+ await vault.create('session', rotated, next, current.value.absoluteExpires);
426
+ await vault.remove('session', id);
427
+ return { id: rotated, value: next, rotated: true };
428
+ }
429
+ // CAS requires both the original revision and the still-owned lease. Logout cannot be undone.
430
+ if (!await vault.update(id, current, next, owner))
431
+ fail(401, 'LOGIN_REQUIRED');
432
+ return { id, value: next };
433
+ }
434
+ catch (error) {
435
+ // Fail the current request; do not serve cached claims/access during an outage. Keep only the
436
+ // unchanged verified record/absolute TTL. No retry or saving an unverified rotated token.
437
+ if (!(error instanceof IdentityUnavailable))
438
+ await vault.remove('session', id);
439
+ throw error;
440
+ }
441
+ finally {
442
+ await vault.release(id, owner);
443
+ }
444
+ }
445
+ }
446
+ /**
447
+ * OpenID Connect Back-Channel Logout 1.0: a signed logout token from the issuer ends every session of its
448
+ * provider session id (sid), or of its subject when it carries no sid. Nothing is listed or returned.
449
+ */
450
+ async function backChannelLogout(req, res) {
451
+ if (req.headers['content-type']?.split(';')[0] !== 'application/x-www-form-urlencoded')
452
+ fail(400, 'INVALID_LOGOUT_TOKEN');
453
+ const token = new URLSearchParams((await body(req)).toString('utf8')).get('logout_token');
454
+ let claims;
455
+ try {
456
+ if (!token)
457
+ throw new Error();
458
+ // A logout token names a sid, a subject or both (section 2.4).
459
+ claims = await validate(token, config.clientId, undefined, true);
460
+ if (typeof claims.sub !== 'string' && typeof claims.sid !== 'string')
461
+ throw new Error();
462
+ const events = claims.events;
463
+ const event = events?.['http://schemas.openid.net/event/backchannel-logout'];
464
+ if (!event || typeof event !== 'object' || Array.isArray(event))
465
+ throw new Error();
466
+ if ('nonce' in claims)
467
+ throw new Error();
468
+ if (typeof claims.jti !== 'string' || !claims.jti || claims.jti.length > 256)
469
+ throw new Error();
470
+ if (claims.sid !== undefined && (typeof claims.sid !== 'string' || !claims.sid || claims.sid.length > 256))
471
+ throw new Error();
472
+ // A logout token is accepted for a bounded time after it was issued.
473
+ if (claims.iat < Math.floor(Date.now() / 1000) - 300)
474
+ throw new Error();
475
+ }
476
+ catch (error) {
477
+ if (error instanceof IdentityUnavailable)
478
+ throw error;
479
+ fail(400, 'INVALID_LOGOUT_TOKEN');
480
+ }
481
+ const replayKey = 'logout-token:' + issuer + '\u0000' + String(claims.jti);
482
+ // Revocation is idempotent; the token is recorded only after it, so that a store outage can be retried.
483
+ if (await vault.read('transaction', replayKey))
484
+ fail(400, 'INVALID_LOGOUT_TOKEN');
485
+ if (typeof claims.sid === 'string')
486
+ await vault.revokeIndexed('sid', claims.sid);
487
+ else
488
+ await vault.revokeIndexed('sub', claims.sub);
489
+ await vault.create('transaction', replayKey, true, Date.now() + 360000).catch(async (error) => { if (await vault.read('transaction', replayKey))
490
+ return; throw error; });
491
+ res.writeHead(200, { 'cache-control': 'no-store' });
492
+ res.end();
493
+ }
494
+ /**
495
+ * Relays one streamed route after every check of an ordinary route has passed. The request body goes
496
+ * upstream through a pull stream that reads the next chunk from the client only when the upstream
497
+ * connection asks for one, so the BFF holds a bounded window of the body, never all of it; the answer comes
498
+ * back the same way. The BFF never parses, inspects, stores or logs a streamed body.
499
+ */
500
+ async function streamRoute(req, res, call) {
501
+ const { stream, headers } = call, hasBody = call.method !== 'GET';
502
+ let length = 0;
503
+ if (hasBody) {
504
+ // Until these checks pass, a refusal ends the connection (set by the handler for a streamed body).
505
+ const type = mediaType(req.headers['content-type']);
506
+ if (!type || !stream.requestTypes.includes(type))
507
+ fail(415, 'MEDIA_TYPE_NOT_ALLOWED');
508
+ // The size is known before the first byte goes upstream: a streamed body declares its length.
509
+ const declared = req.headers['content-length'];
510
+ if (declared === undefined)
511
+ fail(411, 'LENGTH_REQUIRED');
512
+ if (!/^\d{1,15}$/.test(declared))
513
+ fail(400, 'INVALID_CONTENT_LENGTH');
514
+ length = Number(declared);
515
+ if (length > stream.maxRequestBytes)
516
+ fail(413, 'BODY_TOO_LARGE');
517
+ res.removeHeader('connection');
518
+ headers['content-type'] = req.headers['content-type'];
519
+ headers['content-length'] = declared;
520
+ }
521
+ const upstream = new AbortController();
522
+ let finished = false, idle, received = 0;
523
+ const finish = () => { finished = true; clearTimeout(idle); clearTimeout(total); clearInterval(check); };
524
+ /** Ends the transfer: the upstream call is aborted; the client gets an error, or a cut connection once the answer has started. */
525
+ const end = (status, code) => {
526
+ if (finished)
527
+ return;
528
+ finish();
529
+ upstream.abort();
530
+ if (res.headersSent) {
531
+ res.destroy();
532
+ return;
533
+ }
534
+ if (res.destroyed)
535
+ return;
536
+ res.setHeader('connection', 'close');
537
+ write(res, status, { type: 'about:blank', status, title: code });
538
+ };
539
+ /** A client that goes away ends the upstream call; nobody is left to answer. */
540
+ const abandon = () => { if (finished)
541
+ return; finish(); upstream.abort(); };
542
+ // The transfer's timers never keep a process alive on their own; the server does.
543
+ const activity = () => { clearTimeout(idle); idle = setTimeout(() => end(504, 'UPSTREAM_TIMEOUT'), stream.idleTimeoutMs).unref(); };
544
+ const total = setTimeout(() => end(504, 'UPSTREAM_TIMEOUT'), stream.totalTimeoutMs).unref();
545
+ activity();
546
+ /** True while the session record exists and its absolute lifetime has not ended (logout, revocation, rotation or expiry end it). */
547
+ const sessionAlive = async () => { const record = await vault.read('session', call.sessionId); return !!record?.value && record.value.absoluteExpires > Date.now(); };
548
+ const check = setInterval(() => { if (!finished)
549
+ sessionAlive().then(alive => { if (!alive)
550
+ end(401, 'LOGIN_REQUIRED'); }, () => end(503, 'SESSION_STORE_UNAVAILABLE')); }, stream.sessionCheckMs).unref();
551
+ res.on('close', () => { if (!res.writableFinished)
552
+ abandon(); });
553
+ req.on('error', abandon);
554
+ /**
555
+ * The session is read again when the request body ends: before its last chunk goes upstream, so that an
556
+ * upstream that frames the body by its Content-Length never receives the whole body of an ended session.
557
+ */
558
+ const bodyEnds = async () => {
559
+ let alive = false;
560
+ try {
561
+ alive = await sessionAlive();
562
+ }
563
+ catch {
564
+ end(503, 'SESSION_STORE_UNAVAILABLE');
565
+ }
566
+ if (!alive)
567
+ end(401, 'LOGIN_REQUIRED');
568
+ return !finished;
569
+ };
570
+ const chunks = req[Symbol.asyncIterator]();
571
+ const body = hasBody ? new ReadableStream({
572
+ async pull(controller) {
573
+ let next;
574
+ try {
575
+ next = await chunks.next();
576
+ }
577
+ catch (error) {
578
+ abandon();
579
+ controller.error(error);
580
+ return;
581
+ }
582
+ if (finished) {
583
+ controller.error(new Error('TRANSFER_ENDED'));
584
+ return;
585
+ }
586
+ if (next.done) {
587
+ if (received !== length) {
588
+ abandon();
589
+ controller.error(new Error('INCOMPLETE_BODY'));
590
+ return;
591
+ }
592
+ if (length === 0 && !await bodyEnds()) {
593
+ controller.error(new Error('TRANSFER_ENDED'));
594
+ return;
595
+ }
596
+ controller.close();
597
+ return;
598
+ }
599
+ const chunk = next.value;
600
+ received += chunk.length;
601
+ activity();
602
+ // The declared length and the route's maximum bound the count as well.
603
+ if (received > length || received > stream.maxRequestBytes) {
604
+ end(413, 'BODY_TOO_LARGE');
605
+ controller.error(new Error('BODY_TOO_LARGE'));
606
+ return;
607
+ }
608
+ if (received === length && !await bodyEnds()) {
609
+ controller.error(new Error('TRANSFER_ENDED'));
610
+ return;
611
+ }
612
+ controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength));
613
+ },
614
+ cancel() { void chunks.return?.(); },
615
+ }, { highWaterMark: 0 }) : undefined;
616
+ let answer;
617
+ try {
618
+ answer = await fetch(call.target, { method: call.method, headers, ...(body ? { body, duplex: 'half' } : {}), redirect: 'error', signal: upstream.signal });
619
+ }
620
+ catch {
621
+ end(503, 'SERVICE_UNAVAILABLE');
622
+ return;
623
+ }
624
+ if (finished) {
625
+ await answer.body?.cancel().catch(() => undefined);
626
+ return;
627
+ }
628
+ activity();
629
+ // An upload the upstream answered before reading it whole leaves the rest of the body unread.
630
+ const unread = () => { if (hasBody && received < length)
631
+ res.setHeader('connection', 'close'); };
632
+ const challenge = answer.status === 401 ? upstreamStepUp(answer.headers.get('www-authenticate')) : undefined;
633
+ if (challenge) {
634
+ finish();
635
+ upstream.abort();
636
+ unread();
637
+ stepUp(res, challenge, call.resubmit);
638
+ return;
639
+ }
640
+ const type = mediaType(answer.headers.get('content-type'));
641
+ const empty = type === undefined && ([204, 205, 304].includes(answer.status) || answer.headers.get('content-length') === '0');
642
+ // An answer of a type the route does not list is refused whole: none of its body is read.
643
+ if (!empty && (type === undefined || !stream.responseTypes.includes(type))) {
644
+ end(502, 'UPSTREAM_MEDIA_TYPE_REJECTED');
645
+ return;
646
+ }
647
+ // An answer that a browser would run as a document, without a download disposition or a sandbox, is refused whole.
648
+ if (!empty && type !== undefined && scriptCapable(type) && !attachment(answer.headers.get('content-disposition')) && !sandboxed(answer.headers.get('content-security-policy'))) {
649
+ end(502, 'UPSTREAM_INLINE_SCRIPT_REFUSED');
650
+ return;
651
+ }
652
+ const passed = { 'x-content-type-options': 'nosniff', 'cache-control': 'no-store', 'x-correlation-id': call.requestId,
653
+ ...(answer.headers.get('idempotency-replayed') ? { 'idempotency-replayed': 'true' } : {}) };
654
+ for (const name of stream.responseHeaders) {
655
+ const value = answer.headers.get(name);
656
+ // fetch decodes a content encoding, after which the encoded length no longer applies.
657
+ if (value !== null && !(name === 'content-length' && answer.headers.has('content-encoding')))
658
+ passed[name] = value;
659
+ }
660
+ unread();
661
+ try {
662
+ res.writeHead(answer.status, passed);
663
+ }
664
+ catch {
665
+ end(502, 'UPSTREAM_HEADER_REJECTED');
666
+ return;
667
+ }
668
+ if (empty) {
669
+ finish();
670
+ upstream.abort();
671
+ res.end();
672
+ return;
673
+ }
674
+ const reader = answer.body.getReader();
675
+ try {
676
+ for (;;) {
677
+ const { done, value } = await reader.read();
678
+ if (finished)
679
+ return;
680
+ if (done)
681
+ break;
682
+ activity();
683
+ if (!res.write(value))
684
+ await new Promise(resolve => { const go = () => { res.off('drain', go); res.off('close', go); resolve(); }; res.on('drain', go); res.on('close', go); });
685
+ if (finished)
686
+ return;
687
+ activity();
688
+ }
689
+ }
690
+ catch {
691
+ end(502, 'UPSTREAM_INTERRUPTED');
692
+ return;
693
+ }
694
+ finish();
695
+ res.end();
696
+ }
697
+ return async function handle(req, res) {
698
+ try {
699
+ const url = new URL(req.url ?? '/', publicOrigin), method = req.method ?? 'GET';
700
+ if (url.pathname === '/health' && method === 'GET') {
701
+ if (!await vault.healthy())
702
+ fail(503, 'SESSION_STORE_UNAVAILABLE');
703
+ write(res, 200, { status: 'ready', profile: vault.profile });
704
+ return;
705
+ }
706
+ if (url.pathname === '/login' && method === 'GET') {
707
+ // No unverified forwarded IP/header is trusted. The peer is the trusted presentation host.
708
+ if (config.loginRateLimit && !await config.loginRateLimit(req.socket.remoteAddress ?? 'unknown'))
709
+ fail(429, 'LOGIN_LIMIT');
710
+ // A step-up names a recent sign-in, acceptable acr values and the allowlisted path to return to.
711
+ const maxAgeParameter = url.searchParams.get('max_age'), acrParameter = url.searchParams.get('acr_values');
712
+ const maxAge = maxAgeParameter === null ? undefined : /^\d{1,5}$/.test(maxAgeParameter) && Number(maxAgeParameter) <= 86400 ? Number(maxAgeParameter) : fail(400, 'INVALID_STEP_UP');
713
+ const acr = acrParameter === null ? undefined : acrParameter.split(' ');
714
+ if (acr && (!acr.length || acr.length > 8 || acr.some(value => !acrAllowlist.has(value))))
715
+ fail(400, 'INVALID_STEP_UP');
716
+ const returnTo = returnPath(url.searchParams.get('return_to'));
717
+ if (returnTo === null)
718
+ fail(400, 'INVALID_RETURN_PATH');
719
+ const loginTimeoutSeconds = maxAge !== undefined || acr !== undefined ? 300 : ordinaryLoginTimeoutSeconds;
720
+ const state = opaque(), verifier = opaque(), nonce = opaque(), expires = Date.now() + loginTimeoutSeconds * 1000;
721
+ await vault.create('transaction', state, { verifier, nonce, expires, ...(maxAge !== undefined ? { maxAge } : {}), ...(acr ? { acr } : {}), ...(returnTo ? { returnTo } : {}) }, expires);
722
+ const redirect = new URL(issuer + '/protocol/openid-connect/auth');
723
+ const parameters = new URLSearchParams({ client_id: config.clientId, response_type: 'code', prompt: 'login', scope: 'openid profile', redirect_uri: publicOrigin + '/api/session/callback', state, nonce, code_challenge: createHash('sha256').update(verifier).digest('base64url'), code_challenge_method: 'S256' });
724
+ if (maxAge !== undefined)
725
+ parameters.set('max_age', String(maxAge));
726
+ if (acr)
727
+ parameters.set('acr_values', acr.join(' '));
728
+ // The query wins, then the preference cookie's language, then the older whole-value locale cookie.
729
+ const uiLocale = url.searchParams.get('ui_locales') ?? preferences?.read(req.headers.cookie).lang ?? (config.uiLocaleCookie ? cookieValue(req.headers.cookie, config.uiLocaleCookie) : undefined);
730
+ if (uiLocale && supportedUiLocales.has(uiLocale))
731
+ parameters.set('ui_locales', uiLocale);
732
+ redirect.search = parameters.toString();
733
+ res.writeHead(302, { 'location': redirect.href, 'set-cookie': cookie(transactionCookie, state, loginTimeoutSeconds), 'cache-control': 'no-store' });
734
+ res.end();
735
+ return;
736
+ }
737
+ if (url.pathname === '/callback' && method === 'GET') {
738
+ const state = url.searchParams.get('state') ?? '', saved = cookieValue(req.headers.cookie, transactionCookie) ?? '';
739
+ if (!/^[-_a-zA-Z0-9]{43}$/.test(state) || !equal(state, saved))
740
+ fail(401, 'INVALID_LOGIN_STATE');
741
+ const transaction = (await vault.consume('transaction', state))?.value;
742
+ if (!transaction || transaction.expires <= Date.now())
743
+ fail(401, 'INVALID_LOGIN_STATE');
744
+ const code = url.searchParams.get('code');
745
+ if (!code)
746
+ fail(401, 'LOGIN_FAILED');
747
+ const tokens = await tokenRequest(new URLSearchParams({ grant_type: 'authorization_code', code, code_verifier: transaction.verifier, redirect_uri: publicOrigin + '/api/session/callback' }));
748
+ if (!tokens.id_token)
749
+ fail(401, 'ID_TOKEN_REQUIRED');
750
+ const identity = await validate(tokens.id_token, config.clientId, transaction.nonce), claims = await validate(tokens.access_token, config.audience);
751
+ if (identity.sub !== claims.sub || (config.requireTenant && !claims.tenant_id && !config.tenantExemptRoles?.some(role => claims.realm_access?.roles?.includes(role))))
752
+ fail(401, 'INVALID_IDENTITY');
753
+ // A requested step-up is accepted only when the new ID token proves it; nothing is lowered.
754
+ const authTime = typeof identity.auth_time === 'number' && Number.isFinite(identity.auth_time) ? identity.auth_time : undefined;
755
+ const acrClaim = typeof identity.acr === 'string' ? identity.acr : undefined;
756
+ if (transaction.maxAge !== undefined && (authTime === undefined || (authTime + transaction.maxAge) * 1000 + 30000 < Date.now()))
757
+ fail(401, 'STEP_UP_FAILED');
758
+ if (transaction.acr && (acrClaim === undefined || !transaction.acr.includes(acrClaim)))
759
+ fail(401, 'STEP_UP_FAILED');
760
+ // Sign-in always issues a new session id; a session id from before sign-in is removed.
761
+ const old = cookieValue(req.headers.cookie, sessionCookie);
762
+ if (old)
763
+ await vault.remove('session', old);
764
+ const id = opaque(), absoluteExpires = Date.now() + absoluteSeconds * 1000;
765
+ const projected = projectClaims(claimSource === 'id' ? identity : claims, contextClaims);
766
+ const created = { access: tokens.access_token, refresh: tokens.refresh_token, claims, identity: projected, csrf: opaque(), expires: claims.exp * 1000, absoluteExpires, lastSeen: Date.now(),
767
+ ...(authTime !== undefined ? { authTime } : {}), ...(acrClaim !== undefined ? { acr: acrClaim } : {}),
768
+ ...(typeof identity.sid === 'string' && identity.sid.length <= 256 ? { sid: identity.sid } : {}) };
769
+ await index(id, created);
770
+ await vault.create('session', id, created, absoluteExpires);
771
+ const cookies = [sessionSetCookie(id, absoluteSeconds), cookie(transactionCookie, '', 0)];
772
+ if (sameSite === 'Strict') {
773
+ // A Strict cookie set at the end of a cross-site redirect chain is not sent on the next hop of that
774
+ // chain; a same-origin page that moves on lets the browser send it.
775
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'set-cookie': cookies, 'cache-control': 'no-store', 'referrer-policy': 'no-referrer',
776
+ 'content-security-policy': "default-src 'none'; frame-ancestors 'none'" });
777
+ const target = (transaction.returnTo ?? '/').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
778
+ res.end('<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=' + target + '">');
779
+ return;
780
+ }
781
+ res.writeHead(303, { 'location': publicOrigin + (transaction.returnTo ?? '/'), 'set-cookie': cookies, 'cache-control': 'no-store' });
782
+ res.end();
783
+ return;
784
+ }
785
+ if (url.pathname === '/backchannel-logout' && method === 'POST') {
786
+ if (!backChannel)
787
+ fail(404, 'OPERATION_NOT_FOUND');
788
+ await backChannelLogout(req, res);
789
+ return;
790
+ }
791
+ // A body for a streamed route is not read before its checks pass; a refusal closes the connection, so
792
+ // that the body is never read only to be discarded. The route itself removes this when it streams.
793
+ const own = url.pathname === '/context' || url.pathname === '/logout';
794
+ const streamed = method !== 'GET' && !own && config.routes.find(r => r.method === method && r.pattern.test(url.pathname))?.stream !== undefined;
795
+ if (streamed)
796
+ res.setHeader('connection', 'close');
797
+ const current = await session(req, !(url.pathname === '/logout' && method === 'POST'));
798
+ if (current.rotated)
799
+ res.setHeader('set-cookie', sessionSetCookie(current.id, Math.max(1, Math.floor((current.value.absoluteExpires - Date.now()) / 1000))));
800
+ if (method !== 'GET') {
801
+ if (req.headers.origin !== publicOrigin || typeof req.headers['x-csrf-token'] !== 'string' || !equal(current.value.csrf, req.headers['x-csrf-token']))
802
+ fail(403, 'CSRF_REJECTED');
803
+ // A streamed route checks the media types it declares, after the allowlist; every other request is JSON.
804
+ if (!streamed && req.headers['content-type']?.split(';')[0] !== 'application/json')
805
+ fail(415, 'JSON_REQUIRED');
806
+ }
807
+ if (url.pathname === '/context' && method === 'GET') {
808
+ const c = current.value.claims;
809
+ write(res, 200, { authenticated: true, subject: c.sub, name: c.preferred_username ?? c.sub, roles: c.realm_access?.roles ?? [], tenant: c.tenant_id ?? null, claims: current.value.identity ?? {}, csrf: current.value.csrf, expiresAt: current.value.absoluteExpires });
810
+ return;
811
+ }
812
+ if (url.pathname === '/logout' && method === 'POST') {
813
+ await vault.remove('session', current.id);
814
+ // Revoke the server-held refresh token; local logout succeeds even when the provider is down.
815
+ const revocation = new URLSearchParams({ refresh_token: current.value.refresh });
816
+ await Promise.resolve().then(() => fetch(provider('logout'), { method: 'POST', body: revocation, headers: authenticate(revocation), signal: AbortSignal.timeout(5000) })).catch(() => undefined);
817
+ res.setHeader('set-cookie', sessionSetCookie('', 0));
818
+ write(res, 200, { authenticated: false });
819
+ return;
820
+ }
821
+ // An explicit route per operation; URL normalization and redirects cannot escape the allowlist.
822
+ const route = config.routes.find(r => r.method === method && r.pattern.test(url.pathname));
823
+ if (!route)
824
+ fail(404, 'OPERATION_NOT_FOUND');
825
+ if (route.roles && !route.roles.some(role => current.value.claims.realm_access?.roles?.includes(role)))
826
+ fail(403, 'FORBIDDEN');
827
+ // Only an allowlisted token is ever sent upstream; the browser's header is never forwarded as given.
828
+ const headers = { authorization: 'Bearer ' + current.value.access, 'Accept-Language': negotiateLocale(req.headers['accept-language'], apiLocales.supported, apiLocales.defaultLocale) };
829
+ const requestId = opaque();
830
+ headers['X-Correlation-ID'] = requestId;
831
+ if (method !== 'GET')
832
+ headers['content-type'] = 'application/json';
833
+ const idempotency = req.headers['idempotency-key'];
834
+ if (idempotency) {
835
+ if (typeof idempotency !== 'string' || !/^[-a-zA-Z0-9_]{8,128}$/.test(idempotency))
836
+ fail(400, 'INVALID_IDEMPOTENCY_KEY');
837
+ headers['Idempotency-Key'] = idempotency;
838
+ }
839
+ // The BFF never holds or replays a write: the presentation server resubmits it after step-up, and only
840
+ // a request that is safe or carries an idempotency key may be resubmitted without the person.
841
+ const resubmit = method === 'GET' || idempotency ? 'idempotent' : 'manual';
842
+ if (needsStepUp(current.value, route.authentication)) {
843
+ stepUp(res, route.authentication, resubmit);
844
+ return;
845
+ }
846
+ const target = new URL((route.prefix ?? '') + url.pathname + url.search, route.origin);
847
+ if (target.origin !== route.origin)
848
+ fail(400, 'INVALID_PATH');
849
+ if (route.stream) {
850
+ await streamRoute(req, res, { route, stream: route.stream, target, method, headers, requestId, resubmit, sessionId: current.id });
851
+ return;
852
+ }
853
+ const bytes = method === 'GET' ? undefined : await body(req);
854
+ if (route.invoke) {
855
+ const reply = await route.invoke({ path: url.pathname, headers, body: bytes });
856
+ write(res, reply.status, reply.body);
857
+ return;
858
+ }
859
+ const upstream = await fetch(target, { method, headers, ...(bytes ? { body: new Uint8Array(bytes) } : {}), redirect: 'error', signal: AbortSignal.timeout(15000) });
860
+ const raw = await upstream.text();
861
+ const challenge = upstream.status === 401 ? upstreamStepUp(upstream.headers.get('www-authenticate')) : undefined;
862
+ if (challenge) {
863
+ stepUp(res, challenge, resubmit);
864
+ return;
865
+ }
866
+ res.writeHead(upstream.status, { ...jsonHeaders, 'x-correlation-id': requestId, ...(upstream.headers.get('idempotency-replayed') ? { 'idempotency-replayed': 'true' } : {}) });
867
+ res.end(raw);
868
+ }
869
+ catch (error) {
870
+ // A streamed answer that has started cannot become an error answer; its connection is cut.
871
+ if (res.headersSent) {
872
+ res.destroy();
873
+ return;
874
+ }
875
+ const status = error.status ?? 503;
876
+ write(res, status, { type: 'about:blank', status, title: status === 503 ? 'SERVICE_UNAVAILABLE' : error.message });
877
+ }
878
+ };
879
+ }
880
+ //# sourceMappingURL=core.js.map