@fluixi/oauth2 1.0.0-alpha.11 → 1.0.0-alpha.111

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/api-guard.cjs +8 -3
  2. package/dist/api-guard.mjs +9 -135
  3. package/dist/backchannel.cjs +467 -0
  4. package/dist/backchannel.d.ts +39 -0
  5. package/dist/backchannel.d.ts.map +1 -0
  6. package/dist/backchannel.js +97 -0
  7. package/dist/backchannel.mjs +19 -0
  8. package/dist/browser.cjs +6 -1
  9. package/dist/browser.mjs +10 -702
  10. package/dist/callback.cjs +2 -2
  11. package/dist/callback.d.ts +2 -2
  12. package/dist/callback.js +3 -3
  13. package/dist/callback.mjs +17 -24
  14. package/dist/{dpop-YPGCGL7S.mjs → chunk-27BGFJIY.mjs} +6 -6
  15. package/dist/chunk-2GLWT7XH.mjs +143 -0
  16. package/dist/chunk-3EICMAF7.mjs +22 -0
  17. package/dist/chunk-4OHJTTX7.mjs +398 -0
  18. package/dist/chunk-4QRYJ4TN.mjs +86 -0
  19. package/dist/chunk-5WX3EV2W.mjs +78 -0
  20. package/dist/chunk-7AMC336S.mjs +52 -0
  21. package/dist/chunk-AAN3YN4S.mjs +63 -0
  22. package/dist/chunk-AWVECOG7.mjs +404 -0
  23. package/dist/chunk-GN5SERAQ.mjs +189 -0
  24. package/dist/chunk-KIXTZEEW.mjs +80 -0
  25. package/dist/chunk-KVW2S6VY.mjs +36 -0
  26. package/dist/chunk-MHWZTXZZ.mjs +9 -0
  27. package/dist/chunk-QC2FFASM.mjs +67 -0
  28. package/dist/chunk-SJOBQPG6.mjs +77 -0
  29. package/dist/chunk-VCNXQCIH.mjs +26 -0
  30. package/dist/chunk-XQJTQV3C.mjs +91 -0
  31. package/dist/client-auth.mjs +6 -78
  32. package/dist/discovery.cjs +6 -1
  33. package/dist/discovery.d.ts.map +1 -1
  34. package/dist/discovery.js +6 -1
  35. package/dist/discovery.mjs +6 -59
  36. package/dist/dpop-store.mjs +6 -118
  37. package/dist/dpop.mjs +11 -95
  38. package/dist/env-config.cjs +1 -1
  39. package/dist/env-config.mjs +5 -214
  40. package/dist/env-credentials.mjs +5 -47
  41. package/dist/index.cjs +108 -8
  42. package/dist/index.d.ts +2 -0
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +1 -0
  45. package/dist/index.mjs +50 -912
  46. package/dist/module.cjs +1 -1
  47. package/dist/module.mjs +5 -20
  48. package/dist/pkce.mjs +11 -56
  49. package/dist/presets.cjs +1 -1
  50. package/dist/presets.mjs +5 -214
  51. package/dist/return-to.mjs +4 -22
  52. package/dist/roles.cjs +1 -1
  53. package/dist/roles.d.ts +1 -1
  54. package/dist/roles.js +1 -1
  55. package/dist/roles.mjs +4 -32
  56. package/dist/server-client.mjs +7 -107
  57. package/dist/server.cjs +795 -153
  58. package/dist/server.d.ts +85 -4
  59. package/dist/server.d.ts.map +1 -1
  60. package/dist/server.js +577 -75
  61. package/dist/server.mjs +442 -310
  62. package/dist/service-client.cjs +7 -2
  63. package/dist/service-client.mjs +16 -133
  64. package/dist/service.cjs +104 -5
  65. package/dist/service.d.ts +1 -1
  66. package/dist/service.d.ts.map +1 -1
  67. package/dist/service.js +38 -6
  68. package/dist/service.mjs +14 -879
  69. package/dist/session-monitor.cjs +98 -0
  70. package/dist/session-monitor.d.ts +32 -0
  71. package/dist/session-monitor.d.ts.map +1 -0
  72. package/dist/session-monitor.js +104 -0
  73. package/dist/session-monitor.mjs +7 -0
  74. package/dist/tokens.cjs +1 -1
  75. package/dist/tokens.d.ts +2 -2
  76. package/dist/tokens.d.ts.map +1 -1
  77. package/dist/tokens.js +1 -1
  78. package/dist/tokens.mjs +5 -4
  79. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  80. package/dist/types.d.ts +8 -0
  81. package/dist/types.d.ts.map +1 -1
  82. package/dist/types.mjs +4 -9
  83. package/dist/verify.cjs +15 -5
  84. package/dist/verify.d.ts +2 -2
  85. package/dist/verify.js +2 -2
  86. package/dist/verify.mjs +17 -580
  87. package/package.json +23 -17
  88. package/dist/browser-N432SMC3.mjs +0 -3545
  89. package/dist/chunk-4TPZVJSR.mjs +0 -10
  90. package/dist/chunk-ZVDC3JW7.mjs +0 -15
  91. package/dist/dpop-DYUR2CH2.mjs +0 -100
  92. /package/dist/{chunk-OGSFNTKA.mjs → chunk-AXPSPTNP.mjs} +0 -0
package/dist/server.js CHANGED
@@ -21,7 +21,7 @@
21
21
  * cookieSecret: process.env.SESSION_SECRET!,
22
22
  * });
23
23
  *
24
- * export default defineMiddleware([auth, …]);
24
+ * export default defineMiddleware([auth, ...]);
25
25
  * ```
26
26
  *
27
27
  * The cookie itself is `@fluixi/session/server`, which knows nothing about OAuth: it
@@ -32,10 +32,150 @@ import { createSessionCookie } from '@fluixi/session/server';
32
32
  import { safeReturnTo } from './return-to.js';
33
33
  import { applyClientAuth, } from './client-auth.js';
34
34
  import { discover } from './discovery.js';
35
+ import { idTokenClaims, logoutTokenVerifier, memoryLogouts } from './backchannel.js';
35
36
  import { createPkcePair, createStateValue, expiryFrom, timingSafeEqual } from './pkce.js';
36
37
  import { OAuthError } from './types.js';
37
38
  import { createDpopKey, exportDpopKey, importDpopKey, nonceFrom, proofFor } from './dpop.js';
38
39
  import { defineModule } from '@fluixi/start/app';
40
+ /** Ends the state of a sign-in started again after an answer the browser had no flow for. */
41
+ const RETRY_MARK = '.retry';
42
+ // OpenID Connect Core's prompts, and `create` from its user registration specification.
43
+ const PROMPTS = new Set(['none', 'login', 'consent', 'select_account', 'create']);
44
+ const DEFAULT_SCOPES = ['openid', 'profile', 'email'];
45
+ /** Set by the login route itself: forwarding one from the query string would let a link change it. */
46
+ const CLIENT_PARAMS = new Set(['response_type', 'client_id', 'redirect_uri', 'scope', 'state', 'nonce', 'code_challenge', 'code_challenge_method', 'prompt', 'request', 'request_uri']);
47
+ /** What a `prompt=none` request ends with when the provider would have to ask the visitor. */
48
+ const SILENT_REFUSALS = new Set([
49
+ 'login_required',
50
+ 'consent_required',
51
+ 'interaction_required',
52
+ 'account_selection_required',
53
+ ]);
54
+ /**
55
+ * The cookie saying the provider was just asked silently and knew nobody. It holds the
56
+ * `session_state` that answer carried, which the page watches for a later sign-in. It
57
+ * expires soon on purpose: kept for the browser session, it hid a sign-in made at the
58
+ * provider while no page was open to notice.
59
+ */
60
+ function checkedCookie(config, sessionState) {
61
+ const name = `${config.cookieName ?? 'fx_session'}_checked`;
62
+ const secure = config.secureCookie ?? process.env.NODE_ENV === 'production';
63
+ const maxAge = Math.max(0, Math.floor(config.silentRecheck ?? 60));
64
+ const value = sessionState ?? '1';
65
+ return { name, header: `${name}=${value}; Path=/; Max-Age=${maxAge}; HttpOnly; SameSite=Lax${secure ? '; Secure' : ''}` };
66
+ }
67
+ /** A `session_state` as Session Management builds it, `<hash>.<salt>`; anything else is dropped. */
68
+ function sessionStateFrom(url) {
69
+ const value = url.searchParams.get('session_state');
70
+ return value && /^[\w-]{1,128}\.[\w-]{1,64}$/.test(value) ? value : undefined;
71
+ }
72
+ /** A document load, as opposed to a fetch, an asset or a form post. */
73
+ function isPageRequest(request) {
74
+ if (request.method !== 'GET')
75
+ return false;
76
+ const dest = request.headers.get('sec-fetch-dest');
77
+ if (dest)
78
+ return dest === 'document';
79
+ return (request.headers.get('accept') ?? '').includes('text/html');
80
+ }
81
+ function cookieValue(request, name) {
82
+ for (const part of (request.headers.get('cookie') ?? '').split(';')) {
83
+ const [key, ...rest] = part.trim().split('=');
84
+ if (key === name)
85
+ return rest.join('=');
86
+ }
87
+ return undefined;
88
+ }
89
+ function hasCookie(request, name) {
90
+ return cookieValue(request, name) !== undefined;
91
+ }
92
+ /** Whether `pathname` is `path` or below it. */
93
+ function under(pathname, path) {
94
+ return pathname === path || pathname.startsWith(path.endsWith('/') ? path : `${path}/`);
95
+ }
96
+ /** Where `signIn` sends a signed-out visitor's page request, or null to render it as is. */
97
+ function signInRedirect(request, config) {
98
+ if (!isPageRequest(request))
99
+ return null;
100
+ const url = new URL(request.url);
101
+ const base = (config.basePath ?? '/auth').replace(/\/$/, '');
102
+ const guarded = (config.protectedPaths ?? []).some((path) => under(url.pathname, path));
103
+ const mode = guarded ? 'required' : (config.signIn ?? 'manual');
104
+ if (mode === 'manual')
105
+ return null;
106
+ if ([base, ...(config.publicPaths ?? [])].some((path) => under(url.pathname, path)))
107
+ return null;
108
+ // Back from a refused sign-in: show the page and its error, or a required sign-in would
109
+ // send the visitor straight back to the provider, which refuses again, in a loop.
110
+ if (url.searchParams.has('auth_error'))
111
+ return null;
112
+ if (mode === 'silent' && hasCookie(request, checkedCookie(config).name))
113
+ return null;
114
+ const login = new URLSearchParams({ returnTo: url.pathname + url.search });
115
+ if (mode === 'silent')
116
+ login.set('prompt', 'none');
117
+ return new Response(null, { status: 302, headers: { location: `${base}/login?${login}` } });
118
+ }
119
+ /** A JWT's payload, or nothing: the token is the session's own, so it is read, not verified. */
120
+ function jwtClaims(token) {
121
+ const part = token.split('.')[1];
122
+ if (!part)
123
+ return {};
124
+ try {
125
+ const claims = JSON.parse(Buffer.from(part, 'base64url').toString('utf8'));
126
+ return claims && typeof claims === 'object' ? claims : {};
127
+ }
128
+ catch {
129
+ return {};
130
+ }
131
+ }
132
+ /**
133
+ * The scopes the app asks for that this session was not granted. `offline_access` is left out:
134
+ * a provider grants it to the refresh token, not the access token. A session that recorded no
135
+ * scope is taken to have what was asked (RFC 6749 §5.1: the answer omits it when equal).
136
+ */
137
+ function missingScopes(config, session) {
138
+ if (session.scope === undefined)
139
+ return [];
140
+ const granted = new Set(session.scope.split(' ').filter(Boolean));
141
+ return (config.scopes ?? DEFAULT_SCOPES).filter((scope) => scope !== 'offline_access' && !granted.has(scope));
142
+ }
143
+ /**
144
+ * The cookie saying a silent sign-in was tried for these missing scopes. Its value is them, so
145
+ * a provider that still withholds one is not asked again on every page load, while a scope
146
+ * added later is.
147
+ */
148
+ function rescopeCookie(config, missing) {
149
+ const name = `${config.cookieName ?? 'fx_session'}_rescope`;
150
+ const secure = config.secureCookie ?? process.env.NODE_ENV === 'production';
151
+ const value = encodeURIComponent((missing ?? []).join(' '));
152
+ return { name, header: `${name}=${value}; Path=/; Max-Age=${60 * 60 * 24}; HttpOnly; SameSite=Lax${secure ? '; Secure' : ''}` };
153
+ }
154
+ /**
155
+ * Where a signed-in page request goes when its session lacks a scope the app now asks for: a
156
+ * silent sign-in, once per set of missing scopes, which keeps the session if the provider has
157
+ * to ask the person something. Null to render the page as is.
158
+ */
159
+ function rescopeRedirect(request, config, session) {
160
+ if (!isPageRequest(request))
161
+ return null;
162
+ const missing = missingScopes(config, session);
163
+ if (!missing.length)
164
+ return null;
165
+ const url = new URL(request.url);
166
+ const base = (config.basePath ?? '/auth').replace(/\/$/, '');
167
+ if ([base, ...(config.publicPaths ?? [])].some((path) => under(url.pathname, path)))
168
+ return null;
169
+ const marker = rescopeCookie(config, missing);
170
+ if (cookieValue(request, marker.name) === encodeURIComponent(missing.join(' ')))
171
+ return null;
172
+ const login = new URLSearchParams({ returnTo: url.pathname + url.search, prompt: 'none' });
173
+ for (const [name, value] of Object.entries(config.rescopeParams?.(jwtClaims(session.accessToken)) ?? {})) {
174
+ if (value)
175
+ login.set(name, value);
176
+ }
177
+ return new Response(null, { status: 302, headers: { location: `${base}/login?${login}`, 'set-cookie': marker.header } });
178
+ }
39
179
  /**
40
180
  * Nonces providers asked for, per origin, shared by the routes and `sessionLocals`. A nonce
41
181
  * is the server's to set (RFC 9449 §8, §9), so the latest one it sent is the one to use.
@@ -56,38 +196,76 @@ function learnNonce(url, response) {
56
196
  return fresh && !response.ok;
57
197
  }
58
198
  /**
59
- * A request carrying the session's access token: the `DPoP` scheme and a proof bound to the
60
- * token when the provider bound it, `Bearer` otherwise.
199
+ * Sends a request with the session's access token: as a bearer token, or with a DPoP proof
200
+ * for this method and URL when the token is bound to the session's key. A nonce the server
201
+ * asks for is learned and the request sent once more, so the body must be one that can be
202
+ * sent twice (a string, not a stream).
61
203
  */
62
- async function withToken(url, session) {
204
+ async function sendAs(session, input, init = {}) {
205
+ const url = String(input);
206
+ const method = (init.method ?? 'GET').toUpperCase();
63
207
  const key = session.dpop && session.tokenType?.toLowerCase() === 'dpop' ? await importDpopKey(session.dpop) : null;
64
208
  const send = async () => {
65
- const headers = {
209
+ const credentials = {
66
210
  authorization: `${key ? 'DPoP' : 'Bearer'} ${session.accessToken}`,
67
211
  };
68
212
  if (key)
69
- await prove(headers, key, 'GET', url, session.accessToken);
70
- return fetch(url, { headers });
213
+ await prove(credentials, key, method, url, session.accessToken);
214
+ const headers = new Headers(init.headers);
215
+ for (const [name, value] of Object.entries(credentials))
216
+ headers.set(name, value);
217
+ return fetch(url, { ...init, method, headers });
71
218
  };
72
219
  let response = await send();
73
220
  if (key && learnNonce(url, response))
74
221
  response = await send();
75
222
  return response;
76
223
  }
224
+ const withToken = (url, session) => sendAs(session, url);
77
225
  /**
78
- * The middleware.
79
- *
80
- * Handles `<basePath>/login`, `/callback`, `/refresh`, `/me` and `/logout`, and passes
81
- * anything else along untouched.
226
+ * The provider did not process the token request: it answered 429 or 5xx, or the connection
227
+ * never opened. The same request may be sent again after `retryAfterMs`.
82
228
  */
83
- export function oauthRoutes(config) {
84
- const base = (config.basePath ?? '/auth').replace(/\/$/, '');
85
- const scopes = config.scopes ?? ['openid', 'profile', 'email'];
86
- const cookie = createSessionCookie({
87
- secret: config.cookieSecret,
88
- name: config.cookieName,
89
- secure: config.secureCookie,
90
- });
229
+ class ProviderUnavailable extends OAuthError {
230
+ retryAfterMs;
231
+ constructor(retryAfterMs) {
232
+ super('The authorization server is unavailable.', 'temporarily_unavailable');
233
+ this.retryAfterMs = retryAfterMs;
234
+ }
235
+ }
236
+ /**
237
+ * The request may have been processed, but its answer is unusable: it timed out, the
238
+ * connection broke after it was sent, or a success came back without an access token. A
239
+ * refresh token sent this way may already have been rotated.
240
+ */
241
+ class AnswerLost extends OAuthError {
242
+ constructor(what) {
243
+ super(`The token request's answer was lost (${what}).`, 'answer_lost');
244
+ }
245
+ }
246
+ /** Connection failures that happen before the request is sent. */
247
+ const NOT_SENT = new Set(['ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ENETUNREACH', 'EHOSTUNREACH', 'UND_ERR_CONNECT_TIMEOUT']);
248
+ const RETRY_DEFAULT_MS = 5_000;
249
+ const RETRY_MAX_MS = 300_000;
250
+ /** The pause a 429 or 5xx asks for (`Retry-After`, seconds or a date), within sane bounds. */
251
+ function retryAfter(response) {
252
+ const header = response.headers.get('retry-after');
253
+ if (!header)
254
+ return RETRY_DEFAULT_MS;
255
+ const seconds = Number(header);
256
+ const ms = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(header) - Date.now();
257
+ return Number.isFinite(ms) ? Math.min(Math.max(ms, 1_000), RETRY_MAX_MS) : RETRY_DEFAULT_MS;
258
+ }
259
+ /** What a failed `fetch` means for the request: never sent, or possibly processed. */
260
+ function unanswered(error) {
261
+ const code = error?.cause?.code;
262
+ if (code && NOT_SENT.has(code))
263
+ return new ProviderUnavailable(RETRY_DEFAULT_MS);
264
+ return new AnswerLost(code ?? (error instanceof Error ? error.name : 'no answer'));
265
+ }
266
+ /** Endpoints, client authentication and the token request, for the routes and `sessionLocals`. */
267
+ function tokenClient(config) {
268
+ const timeoutMs = config.tokenTimeoutMs ?? 10_000;
91
269
  let endpoints = config.endpoints ?? null;
92
270
  const resolve = async () => {
93
271
  if (endpoints)
@@ -98,10 +276,6 @@ export function oauthRoutes(config) {
98
276
  endpoints = await discover(config.issuer);
99
277
  return endpoints;
100
278
  };
101
- const json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), {
102
- status,
103
- headers: { 'content-type': 'application/json', ...headers },
104
- });
105
279
  const clientAuth = {
106
280
  clientId: config.clientId,
107
281
  // `client_secret_post` by default here, which is what this half has always sent, so
@@ -124,29 +298,191 @@ export function oauthRoutes(config) {
124
298
  await applyClientAuth(clientAuth, token, headers, form);
125
299
  if (key)
126
300
  await prove(headers, key, 'POST', token);
127
- return fetch(token, { method: 'POST', headers, body: form.toString() });
301
+ return fetch(token, { method: 'POST', headers, body: form.toString(), signal: AbortSignal.timeout(timeoutMs) });
128
302
  };
129
- let response = await attempt();
130
- if (key && learnNonce(token, response))
303
+ let response;
304
+ let payload = null;
305
+ try {
131
306
  response = await attempt();
132
- const payload = (await response.json().catch(() => ({})));
307
+ if (key && learnNonce(token, response))
308
+ response = await attempt();
309
+ if (response.status === 429 || response.status >= 500)
310
+ throw new ProviderUnavailable(retryAfter(response));
311
+ payload = (await response.json().catch(() => null));
312
+ }
313
+ catch (error) {
314
+ throw error instanceof OAuthError ? error : unanswered(error);
315
+ }
133
316
  if (!response.ok) {
134
- throw new OAuthError(String(payload.error ?? 'token_request_failed'), String(payload.error ?? 'token_request_failed'));
317
+ throw new OAuthError(String(payload?.error ?? 'token_request_failed'), String(payload?.error ?? 'token_request_failed'));
318
+ }
319
+ // A token endpoint's success always carries one (RFC 6749 5.1). Anything else (a proxy's
320
+ // page, a truncated body) is not a session, and the provider may have rotated the token.
321
+ if (typeof payload?.access_token !== 'string' || !payload.access_token) {
322
+ throw new AnswerLost('a success without an access token');
135
323
  }
136
324
  return payload;
137
325
  }
326
+ return { resolve, tokenRequest, clientAuth };
327
+ }
328
+ /**
329
+ * Renewals in flight or just finished, by the refresh token they spent. The provider rotates
330
+ * refresh tokens and treats a second use of one as theft, revoking the whole family: requests
331
+ * that arrive together with the same expired cookie (a page and its server functions) must
332
+ * share one renewal, and one that arrives a moment later with the old cookie still gets its
333
+ * result. One process only; replicas need the provider to allow a short reuse window.
334
+ */
335
+ const renewals = new Map();
336
+ const RENEWAL_REUSE_MS = 30_000;
337
+ /** How long a refused or possibly rotated refresh token stays recorded, so it is not sent again. */
338
+ const SPENT_MS = 5 * 60_000;
339
+ /** The session with fresh tokens, or null when the provider refuses to renew it. */
340
+ function renew(current, tokenRequest) {
341
+ const refreshToken = current.refreshToken;
342
+ const now = Date.now();
343
+ for (const [key, entry] of renewals)
344
+ if (entry.until <= now)
345
+ renewals.delete(key);
346
+ const known = renewals.get(refreshToken);
347
+ if (known)
348
+ return known.result;
349
+ const result = (async () => {
350
+ // The key that obtained the refresh token, or the provider refuses the refresh.
351
+ const key = current.dpop ? await importDpopKey(current.dpop) : null;
352
+ const payload = await tokenRequest({ grant_type: 'refresh_token', refresh_token: refreshToken }, key);
353
+ return {
354
+ accessToken: String(payload.access_token ?? ''),
355
+ // A provider that rotates refresh tokens sends a new one; one that does not
356
+ // expects the old one to keep working.
357
+ refreshToken: typeof payload.refresh_token === 'string' ? payload.refresh_token : refreshToken,
358
+ idToken: typeof payload.id_token === 'string' ? payload.id_token : current.idToken,
359
+ expiresAt: expiryFrom(payload.expires_in),
360
+ tokenType: typeof payload.token_type === 'string' ? payload.token_type : current.tokenType,
361
+ dpop: current.dpop,
362
+ sessionState: current.sessionState,
363
+ scope: typeof payload.scope === 'string' ? payload.scope : current.scope,
364
+ };
365
+ })().catch((error) => {
366
+ // Not processed (the provider down or busy): nothing was spent. Ask again after the pause.
367
+ if (error instanceof ProviderUnavailable) {
368
+ renewals.set(refreshToken, { until: Date.now() + error.retryAfterMs, result });
369
+ throw error;
370
+ }
371
+ // Refused, or answered in a way that was lost after the provider may have rotated the
372
+ // token: the session is over either way. Sending the token again would be a replay, which
373
+ // the provider answers by ending every session of this sign-in.
374
+ if (error instanceof OAuthError) {
375
+ renewals.set(refreshToken, { until: Date.now() + SPENT_MS, result });
376
+ return null;
377
+ }
378
+ renewals.delete(refreshToken);
379
+ throw error;
380
+ });
381
+ renewals.set(refreshToken, { until: now + RENEWAL_REUSE_MS, result });
382
+ return result;
383
+ }
384
+ /** Renewed a little before it runs out, so a request does not reach an API with a dying token. */
385
+ const EXPIRY_SKEW_MS = 30_000;
386
+ const expired = (session) => session.expiresAt !== undefined && session.expiresAt - EXPIRY_SKEW_MS <= Date.now();
387
+ /**
388
+ * The middleware.
389
+ *
390
+ * Handles `<basePath>/login`, `/callback`, `/refresh`, `/me`, `/session-check` and
391
+ * `/logout`, and passes anything else along untouched.
392
+ */
393
+ // One default store per configuration, so the routes and sessionLocals built from it share it.
394
+ const defaultLogouts = new WeakMap();
395
+ function logoutsOf(config) {
396
+ if (config.logouts)
397
+ return config.logouts;
398
+ let store = defaultLogouts.get(config);
399
+ if (!store)
400
+ defaultLogouts.set(config, (store = memoryLogouts()));
401
+ return store;
402
+ }
403
+ /** Whether the provider has ended this session over the back channel. */
404
+ async function endedAtProvider(config, session) {
405
+ const id = idTokenClaims(session.idToken);
406
+ if (!id.sid && !id.sub)
407
+ return false;
408
+ return logoutsOf(config).ended({ sid: id.sid, sub: id.sub, since: (id.iat ?? 0) * 1000 });
409
+ }
410
+ export function oauthRoutes(config) {
411
+ for (const name of config.authorizeParams ?? []) {
412
+ if (CLIENT_PARAMS.has(name))
413
+ throw new Error(`authorizeParams cannot include "${name}": the login route sets it.`);
414
+ }
415
+ const { resolve, tokenRequest, clientAuth } = tokenClient(config);
416
+ const json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), {
417
+ status,
418
+ headers: { 'content-type': 'application/json', ...headers },
419
+ });
420
+ const base = (config.basePath ?? '/auth').replace(/\/$/, '');
421
+ const scopes = config.scopes ?? DEFAULT_SCOPES;
422
+ const cookie = createSessionCookie({
423
+ secret: config.cookieSecret,
424
+ name: config.cookieName,
425
+ secure: config.secureCookie,
426
+ });
138
427
  return async function middleware(request, next) {
139
428
  const url = new URL(request.url);
140
429
  if (!url.pathname.startsWith(`${base}/`))
141
430
  return next();
142
431
  const route = url.pathname.slice(base.length);
143
432
  const session = async () => {
144
- return cookie.read(request);
433
+ const current = await cookie.read(request);
434
+ return current && (await endedAtProvider(config, current)) ? null : current;
145
435
  };
436
+ if (route === '/backchannel-logout') {
437
+ // The provider, server to server: a session this app took part in has ended there.
438
+ const headers = { 'cache-control': 'no-store' };
439
+ if (request.method !== 'POST')
440
+ return json({ error: 'invalid_request' }, 405, headers);
441
+ try {
442
+ const form = await request.formData();
443
+ const token = form.get('logout_token');
444
+ if (typeof token !== 'string' || !token)
445
+ throw new Error('no logout_token');
446
+ const endpoints = await resolve();
447
+ const issuer = endpoints.issuer ?? config.issuer;
448
+ if (!issuer)
449
+ throw new Error('no issuer');
450
+ if (!endpoints.jwks)
451
+ throw new Error('no jwks_uri');
452
+ // Read fresh for each logout (they are rare), so a rotated key is always known.
453
+ const jwks = (await (await fetch(endpoints.jwks)).json());
454
+ const entry = await logoutTokenVerifier({ issuer, clientId: config.clientId, jwks })(token);
455
+ await logoutsOf(config).add(entry);
456
+ return new Response(null, { status: 200, headers });
457
+ }
458
+ catch {
459
+ return json({ error: 'invalid_request' }, 400, headers);
460
+ }
461
+ }
146
462
  if (route === '/login') {
147
- const { authorization } = await resolve();
463
+ let authorization;
464
+ try {
465
+ ({ authorization } = await resolve());
466
+ }
467
+ catch (error) {
468
+ if (!(error instanceof OAuthError) || error.code !== 'discovery_unreachable')
469
+ throw error;
470
+ // The provider is down: back to the app, which can say so, rather than an error page.
471
+ const back = safeReturnTo(url.searchParams.get('returnTo'), {
472
+ fallback: config.defaultReturnTo ?? '/',
473
+ origin: url.origin,
474
+ allowedOrigins: config.allowedReturnOrigins,
475
+ });
476
+ const target = new URL(back, url.origin);
477
+ target.searchParams.set('auth_error', 'provider_unreachable');
478
+ const location = target.origin === url.origin ? target.pathname + target.search : target.toString();
479
+ return new Response(null, { status: 302, headers: { location } });
480
+ }
148
481
  const { verifier, challenge } = await createPkcePair();
149
- const state = createStateValue();
482
+ // A retry carries its mark in the state itself: the one place that survives the trip
483
+ // when the cookie does not, so a second failed attempt is told apart from the first.
484
+ const retry = url.searchParams.get('retry') === '1';
485
+ const state = createStateValue() + (retry ? RETRY_MARK : '');
150
486
  const target = new URL(authorization);
151
487
  target.searchParams.set('response_type', 'code');
152
488
  target.searchParams.set('client_id', config.clientId);
@@ -155,10 +491,21 @@ export function oauthRoutes(config) {
155
491
  target.searchParams.set('state', state);
156
492
  target.searchParams.set('code_challenge', challenge);
157
493
  target.searchParams.set('code_challenge_method', 'S256');
494
+ // Only the values OpenID Connect defines; anything else from the query string is dropped.
495
+ const prompt = url.searchParams.get('prompt');
496
+ if (prompt && PROMPTS.has(prompt))
497
+ target.searchParams.set('prompt', prompt);
498
+ for (const name of config.authorizeParams ?? []) {
499
+ const value = url.searchParams.get(name);
500
+ if (value)
501
+ target.searchParams.set(name, value);
502
+ }
158
503
  // The verifier goes in the cookie, which is the only thing that survives the trip
159
- // and is not readable by the page.
504
+ // and is not readable by the page. A silent sign-in from a signed-in page (a scope the
505
+ // session lacks) keeps the session beside it, so a provider that has to ask leaves it.
506
+ const kept = prompt === 'none' ? await session() : null;
160
507
  const pendingCookie = await cookie.write({
161
- accessToken: '',
508
+ ...(kept?.accessToken ? { ...kept, pending: undefined } : { accessToken: '' }),
162
509
  pending: {
163
510
  verifier,
164
511
  state,
@@ -169,11 +516,12 @@ export function oauthRoutes(config) {
169
516
  origin: url.origin,
170
517
  allowedOrigins: config.allowedReturnOrigins,
171
518
  }) || undefined,
519
+ silent: prompt === 'none' || undefined,
172
520
  },
173
521
  },
174
522
  // Ten minutes: long enough to sign in, short enough that an abandoned attempt
175
- // does not sit in the browser.
176
- { maxAge: 600 });
523
+ // does not sit in the browser. A kept session keeps its own lifetime.
524
+ kept?.accessToken ? undefined : { maxAge: 600 });
177
525
  return new Response(null, {
178
526
  status: 302,
179
527
  headers: {
@@ -186,25 +534,93 @@ export function oauthRoutes(config) {
186
534
  const current = await session();
187
535
  const pending = current?.pending;
188
536
  const error = url.searchParams.get('error');
189
- if (error)
190
- return json({ error }, 400);
537
+ if (error) {
538
+ // Back to the page the flow started from, never a JSON answer the visitor reads.
539
+ const ours = !!pending && timingSafeEqual(pending.state, url.searchParams.get('state') ?? '');
540
+ let location = safeReturnTo(ours ? pending.returnTo ?? config.defaultReturnTo : config.defaultReturnTo, {
541
+ fallback: '/',
542
+ origin: url.origin,
543
+ allowedOrigins: config.allowedReturnOrigins,
544
+ });
545
+ const headers = new Headers();
546
+ if (ours && pending.silent && SILENT_REFUSALS.has(error) && current?.accessToken) {
547
+ // Signed in already and only after a scope: the session stays as it was.
548
+ headers.set('set-cookie', await cookie.write({ ...current, pending: undefined }));
549
+ headers.set('location', location);
550
+ return new Response(null, { status: 302, headers });
551
+ }
552
+ headers.append('set-cookie', cookie.clear());
553
+ if (ours && pending.silent && SILENT_REFUSALS.has(error)) {
554
+ // Nobody signed in at the provider: remember it was asked, and show the page as is.
555
+ headers.append('set-cookie', checkedCookie(config, sessionStateFrom(url)).header);
556
+ }
557
+ else {
558
+ const target = new URL(location, url.origin);
559
+ target.searchParams.set('auth_error', error);
560
+ location = target.origin === url.origin ? target.pathname + target.search : target.toString();
561
+ }
562
+ headers.set('location', location);
563
+ return new Response(null, { status: 302, headers });
564
+ }
191
565
  const code = url.searchParams.get('code');
192
566
  const state = url.searchParams.get('state');
193
567
  if (!code)
194
568
  return json({ error: 'no_code' }, 400);
195
569
  if (!pending || !state || !timingSafeEqual(pending.state, state)) {
196
- return json({ error: 'state_mismatch' }, 400);
570
+ // An answer this browser has no flow for: its cookie expired (a sign-in that took longer
571
+ // than ten minutes, a provider page refreshed long after), or another tab started a
572
+ // newer one. Already signed in, the answer is a leftover. Otherwise start again once,
573
+ // and only then give up, on a page rather than with JSON.
574
+ const home = safeReturnTo(config.defaultReturnTo, { fallback: '/', origin: url.origin, allowedOrigins: config.allowedReturnOrigins });
575
+ if (current?.accessToken)
576
+ return new Response(null, { status: 302, headers: { location: home } });
577
+ if (!state?.endsWith(RETRY_MARK)) {
578
+ return new Response(null, { status: 302, headers: { location: `${base}/login?retry=1` } });
579
+ }
580
+ const target = new URL(home, url.origin);
581
+ target.searchParams.set('auth_error', 'state_mismatch');
582
+ return new Response(null, {
583
+ status: 302,
584
+ headers: {
585
+ location: target.origin === url.origin ? target.pathname + target.search : target.toString(),
586
+ 'set-cookie': cookie.clear(),
587
+ },
588
+ });
197
589
  }
198
590
  // The token is bound here, at the exchange, so this is where the session's key is made.
199
591
  const key = config.dpop
200
592
  ? await createDpopKey(config.dpopAlgorithm, { extractable: true })
201
593
  : null;
202
- const payload = await tokenRequest({
203
- grant_type: 'authorization_code',
204
- code,
205
- redirect_uri: config.redirectUri,
206
- code_verifier: pending.verifier,
207
- }, key);
594
+ let payload;
595
+ try {
596
+ payload = await tokenRequest({
597
+ grant_type: 'authorization_code',
598
+ code,
599
+ redirect_uri: config.redirectUri,
600
+ code_verifier: pending.verifier,
601
+ }, key);
602
+ }
603
+ catch (error) {
604
+ if (!(error instanceof OAuthError))
605
+ throw error;
606
+ // Back to the app with the reason, as for a refusal at the provider, rather than an
607
+ // error page: a provider that did not answer in time, or the code it refused.
608
+ const unreachable = error.code === 'temporarily_unavailable' || error.code === 'answer_lost';
609
+ const back = safeReturnTo(pending.returnTo ?? config.defaultReturnTo, {
610
+ fallback: '/',
611
+ origin: url.origin,
612
+ allowedOrigins: config.allowedReturnOrigins,
613
+ });
614
+ const target = new URL(back, url.origin);
615
+ target.searchParams.set('auth_error', unreachable ? 'provider_unreachable' : error.code);
616
+ return new Response(null, {
617
+ status: 302,
618
+ headers: {
619
+ location: target.origin === url.origin ? target.pathname + target.search : target.toString(),
620
+ 'set-cookie': cookie.clear(),
621
+ },
622
+ });
623
+ }
208
624
  const signedIn = await cookie.write({
209
625
  accessToken: String(payload.access_token ?? ''),
210
626
  refreshToken: typeof payload.refresh_token === 'string' ? payload.refresh_token : undefined,
@@ -212,6 +628,8 @@ export function oauthRoutes(config) {
212
628
  expiresAt: expiryFrom(payload.expires_in),
213
629
  tokenType: typeof payload.token_type === 'string' ? payload.token_type : undefined,
214
630
  dpop: key ? await exportDpopKey(key) : undefined,
631
+ sessionState: sessionStateFrom(url),
632
+ scope: typeof payload.scope === 'string' ? payload.scope : undefined,
215
633
  });
216
634
  return new Response(null, {
217
635
  status: 302,
@@ -232,22 +650,10 @@ export function oauthRoutes(config) {
232
650
  const current = await session();
233
651
  if (!current?.refreshToken)
234
652
  return json({ error: 'no_session' }, 401);
235
- // The key that obtained the refresh token, or the provider refuses the refresh.
236
- const key = current.dpop ? await importDpopKey(current.dpop) : null;
237
- const payload = await tokenRequest({ grant_type: 'refresh_token', refresh_token: current.refreshToken }, key);
238
- const refreshed = await cookie.write({
239
- accessToken: String(payload.access_token ?? ''),
240
- // A provider that rotates refresh tokens sends a new one; one that does not
241
- // expects the old one to keep working.
242
- refreshToken: typeof payload.refresh_token === 'string'
243
- ? payload.refresh_token
244
- : current.refreshToken,
245
- idToken: current.idToken,
246
- expiresAt: expiryFrom(payload.expires_in),
247
- tokenType: typeof payload.token_type === 'string' ? payload.token_type : current.tokenType,
248
- dpop: current.dpop,
249
- });
250
- return json({ ok: true }, 200, { 'set-cookie': refreshed });
653
+ const renewed = await renew(current, tokenRequest);
654
+ if (!renewed)
655
+ return json({ error: 'refresh_refused' }, 401, { 'set-cookie': cookie.clear() });
656
+ return json({ ok: true }, 200, { 'set-cookie': await cookie.write(renewed) });
251
657
  }
252
658
  if (route === '/me') {
253
659
  const current = await session();
@@ -262,6 +668,16 @@ export function oauthRoutes(config) {
262
668
  const claims = (await response.json());
263
669
  return json(config.mapUser ? config.mapUser(claims, current.accessToken) : claims);
264
670
  }
671
+ if (route === '/session-check') {
672
+ // What the page needs to watch the provider's session: its check page, this client,
673
+ // and the last answer's session_state, signed in or not. Nothing secret: the state is
674
+ // a salted hash bound to this origin.
675
+ const { checkSession } = await resolve().catch(() => ({ checkSession: undefined }));
676
+ const current = await session();
677
+ const checked = cookieValue(request, checkedCookie(config).name);
678
+ const state = current?.accessToken ? current.sessionState : checked !== '1' ? checked : undefined;
679
+ return json({ frame: checkSession ?? null, clientId: config.clientId, state: state ?? null });
680
+ }
265
681
  if (route === '/revoke') {
266
682
  const current = await session();
267
683
  const hint = url.searchParams.get('hint') === 'access_token' ? 'access_token' : 'refresh_token';
@@ -302,18 +718,21 @@ export function oauthRoutes(config) {
302
718
  }
303
719
  // Max-Age=0 is what removes it. Clearing the value alone leaves a cookie behind.
304
720
  const cleared = cookie.clear();
721
+ // Signed out on purpose: `silent` must not sign them straight back in.
722
+ const headers = new Headers();
723
+ headers.append('set-cookie', cleared);
724
+ headers.append('set-cookie', checkedCookie(config).header);
305
725
  if (endSession && current?.idToken) {
306
726
  const target = new URL(endSession);
307
727
  target.searchParams.set('id_token_hint', current.idToken);
308
728
  if (config.defaultReturnTo) {
309
729
  target.searchParams.set('post_logout_redirect_uri', config.defaultReturnTo);
310
730
  }
311
- return new Response(null, {
312
- status: 302,
313
- headers: { location: target.toString(), 'set-cookie': cleared },
314
- });
731
+ headers.set('location', target.toString());
732
+ return new Response(null, { status: 302, headers });
315
733
  }
316
- return json({ ok: true }, 200, { 'set-cookie': cleared });
734
+ headers.set('content-type', 'application/json');
735
+ return new Response(JSON.stringify({ ok: true }), { status: 200, headers });
317
736
  }
318
737
  return next();
319
738
  };
@@ -349,6 +768,7 @@ export function sessionLocals(config) {
349
768
  name: config.cookieName,
350
769
  secure: config.secureCookie,
351
770
  });
771
+ const { tokenRequest } = tokenClient(config);
352
772
  const ttl = config.userCacheMs ?? 30_000;
353
773
  /**
354
774
  * Keyed by the access token, which this process already holds in the cookie it just
@@ -376,23 +796,82 @@ export function sessionLocals(config) {
376
796
  return async function middleware(request, next) {
377
797
  const { getRequestLocals } = await import('@fluixi/server');
378
798
  const locals = getRequestLocals(request);
379
- const session = await cookie.read(request);
799
+ let session = await cookie.read(request);
800
+ // What the browser's cookie must become: renewed tokens, or nothing.
801
+ let setCookie;
802
+ const respond = async (response) => {
803
+ if (!setCookie)
804
+ return response;
805
+ const copy = new Response(response.body, response);
806
+ copy.headers.append('set-cookie', setCookie);
807
+ return copy;
808
+ };
809
+ const renewOrDrop = async (current) => {
810
+ const renewed = current.refreshToken ? await renew(current, tokenRequest) : null;
811
+ setCookie = renewed ? await cookie.write(renewed) : cookie.clear();
812
+ return renewed;
813
+ };
814
+ // An access token lives minutes, the session days: renew it here, on the request that
815
+ // finds it expired, rather than rendering a signed-in visitor as nobody.
816
+ // Set when the provider could not renew now: the session stays, it is retried later.
817
+ let paused = false;
818
+ const keep = (current) => (error) => {
819
+ if (error instanceof ProviderUnavailable)
820
+ paused = true;
821
+ return current;
822
+ };
823
+ if (session?.accessToken && expired(session)) {
824
+ session = await renewOrDrop(session).catch(keep(session));
825
+ }
380
826
  // Written either way. A route that reads locals should find "nobody" rather than
381
827
  // nothing, so the absent case and the signed-out case look the same to it.
382
- if (!session?.accessToken) {
828
+ const signedOut = async () => {
829
+ const redirect = signInRedirect(request, config);
830
+ if (redirect)
831
+ return respond(redirect);
383
832
  locals.auth = { user: null, session: null };
384
- return next();
833
+ return respond(await next());
834
+ };
835
+ if (!session?.accessToken)
836
+ return signedOut();
837
+ // Ended at the provider (back-channel logout): this session is over too.
838
+ if (await endedAtProvider(config, session)) {
839
+ setCookie = cookie.clear();
840
+ session = null;
841
+ return signedOut();
385
842
  }
386
- const cached = cache.get(session.accessToken);
843
+ // Granted fewer scopes than the app asks for now: a silent sign-in brings them, once.
844
+ const rescope = rescopeRedirect(request, config, session);
845
+ if (rescope)
846
+ return respond(rescope);
847
+ // Server code calls the app's APIs as this user with it; the token itself stays here.
848
+ const live = session;
849
+ const fetchAs = (input, init) => sendAs(live, input, init);
850
+ const cached = cache.get(live.accessToken);
387
851
  if (cached && cached.until > Date.now()) {
388
- locals.auth = { user: cached.user, session: { expiresAt: session.expiresAt } };
389
- return next();
852
+ locals.auth = { user: cached.user, session: { expiresAt: live.expiresAt }, fetch: fetchAs };
853
+ return respond(await next());
390
854
  }
391
855
  let user = null;
856
+ let unreachable = false;
392
857
  try {
393
858
  const endpoints = config.endpoints ?? (config.issuer ? await discover(config.issuer) : null);
394
859
  if (endpoints?.userinfo) {
395
- const response = await withToken(endpoints.userinfo, session);
860
+ let response = await withToken(endpoints.userinfo, session);
861
+ // Refused before its time (revoked, a clock apart): renew once, and when that is
862
+ // refused too the session is over, so the visitor goes the signed-out way.
863
+ if (response.status === 401 && !setCookie && !paused) {
864
+ session = await renewOrDrop(session).catch(keep(session));
865
+ if (!session)
866
+ return signedOut();
867
+ response = await withToken(endpoints.userinfo, session);
868
+ }
869
+ if (response.status === 401) {
870
+ // Not renewable just now: signed out for this request, renewed on a later one.
871
+ if (!paused)
872
+ setCookie = cookie.clear();
873
+ return signedOut();
874
+ }
396
875
  if (response.ok) {
397
876
  const claims = (await response.json());
398
877
  user = config.mapUser ? config.mapUser(claims, session.accessToken) : claims;
@@ -404,12 +883,34 @@ export function sessionLocals(config) {
404
883
  }
405
884
  catch {
406
885
  // A provider that is unreachable should not take the page down with it. The render
407
- // proceeds as signed out, and the client retries on its own.
886
+ // proceeds as signed out, and the client retries on its own; `unreachable` tells
887
+ // server code it is not the visitor who is signed out.
888
+ unreachable = true;
408
889
  }
409
- locals.auth = { user, session: user ? { expiresAt: session.expiresAt } : null };
410
- return next();
890
+ if (!session)
891
+ return signedOut();
892
+ const current = session;
893
+ const fetchCurrent = (input, init) => sendAs(current, input, init);
894
+ locals.auth = user
895
+ ? { user, session: { expiresAt: current.expiresAt }, fetch: fetchCurrent }
896
+ : { user: null, session: null, ...(unreachable ? { unreachable: true } : {}) };
897
+ return respond(await next());
411
898
  };
412
899
  }
900
+ /**
901
+ * The request's auth, for server code: a route's data loader, a server function, an API route.
902
+ * Reads the current request's locals, or `request`'s when one is given.
903
+ *
904
+ * ```ts
905
+ * const { fetch } = await requestAuth();
906
+ * const projects = await fetch?.(`${apiUrl}/projects`).then((r) => r.json());
907
+ * ```
908
+ */
909
+ export async function requestAuth(request) {
910
+ const { getLocals, getRequestLocals } = await import('@fluixi/server');
911
+ const locals = (request ? getRequestLocals(request) : getLocals());
912
+ return locals.auth ?? { user: null, session: null };
913
+ }
413
914
  /**
414
915
  * The server half of `authModule`, listed in `src/app.config.server.ts`: the routes and the
415
916
  * session middleware that `tokens: 'server'` needs, in the order they have to run.
@@ -420,3 +921,4 @@ export function sessionLocals(config) {
420
921
  export function authServerModule(config) {
421
922
  return defineModule({ name: 'oauth2-server', middleware: [oauthRoutes(config), sessionLocals(config)] });
422
923
  }
924
+ export { memoryLogouts } from './backchannel.js';