ark-oauth-client-node 0.0.0-stage → 2.2.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/src/express.js ADDED
@@ -0,0 +1,820 @@
1
+ import { ArkOAuthClient } from './client.js';
2
+ import { TokenSet } from './tokens.js';
3
+ import { ArkCallbackError, ArkConfigError, ArkOAuthError } from './errors.js';
4
+ import {
5
+ ArkAccessDeniedReasons,
6
+ ArkChallengeProperties,
7
+ DENIED_COOKIE,
8
+ DENIED_MAX_AGE_SECONDS,
9
+ checkSameOrigin,
10
+ deniedUrl,
11
+ describeDenial,
12
+ evaluateAccess,
13
+ localOrDefault,
14
+ normalizeAccountSwitch,
15
+ protectState,
16
+ unprotectState
17
+ } from './access.js';
18
+ import { DENIED_PAGE_CSP, renderAccessDeniedPage } from './denied-page.js';
19
+ import {
20
+ MemorySessionStore,
21
+ appendCookie,
22
+ createSessionId,
23
+ parseCookies,
24
+ serializeCookie,
25
+ signSessionId,
26
+ unsignSessionId
27
+ } from './session.js';
28
+
29
+ /**
30
+ * Interactive sign-in for Express, Connect, and anything else that hands a middleware a Node
31
+ * request and response — Fastify through `@fastify/middie`, Koa through `koa-connect`, or a plain
32
+ * `http.createServer`.
33
+ *
34
+ * It is one middleware rather than a router because a router would mean depending on Express, and
35
+ * this package has no runtime dependencies. The middleware claims its paths (`/login`, the
36
+ * callback, `/logout`, and the three account-switch endpoints under `/ark/`), attaches `req.ark` to
37
+ * everything else, and calls `next()`. Claiming them ahead of the application's own routes is
38
+ * deliberate: the access-denied page has to render for a user who is not allowed in, so it must not
39
+ * sit behind the application's guard.
40
+ *
41
+ * What it takes care of, all of which is easy to get subtly wrong by hand:
42
+ *
43
+ * * the login transaction — `state`, `nonce` and the PKCE verifier, stored server-side, one per
44
+ * concurrent sign-in, so two tabs do not overwrite each other;
45
+ * * the callback checks, in the order that makes them meaningful;
46
+ * * silent refresh shortly before the access token expires, serialised per session, because this
47
+ * server rotates refresh tokens and treats a reused one as theft of the whole family;
48
+ * * sign-out that actually ends the session — the refresh token revoked at the provider, the
49
+ * server-side session destroyed, the cookie cleared, and only then the redirect to the IdP;
50
+ * * the shared-browser case: the entitlement check at the callback, the access-denied page, and the
51
+ * `prompt=login` switch that is the only way out of it.
52
+ */
53
+
54
+ const DEFAULT_SESSION_TTL_SECONDS = 8 * 60 * 60; // matches the server's default SessionLifetimeMinutes
55
+ const TRANSACTION_TTL_SECONDS = 10 * 60;
56
+ const MAX_CONCURRENT_TRANSACTIONS = 5;
57
+ /** Refresh a little before expiry so a request in flight never carries a dead token — the .NET and Python window. */
58
+ const REFRESH_WINDOW_SECONDS = 120;
59
+ /** A sign-in response or an account-switch form is a few hundred bytes; anything near this is not one. */
60
+ const MAX_FORM_BYTES = 64 * 1024;
61
+
62
+ /** Paths compare as the Python and .NET clients compare them: case-insensitive, trailing slash ignored. */
63
+ const samePath = (path, configured) =>
64
+ Boolean(configured) && path.replace(/\/+$/, '').toLowerCase() === String(configured).replace(/\/+$/, '').toLowerCase();
65
+
66
+ const wantsHtml = (req) => (req.headers?.accept ?? '').includes('text/html');
67
+
68
+ /** Plain responses this middleware writes itself: never cached, never content-sniffed. */
69
+ function send(res, status, body, { type = 'text/plain; charset=utf-8', headers = {} } = {}) {
70
+ res.statusCode = status;
71
+ res.setHeader('Content-Type', type);
72
+ res.setHeader('Cache-Control', 'no-store');
73
+ res.setHeader('X-Content-Type-Options', 'nosniff');
74
+ for (const [name, value] of Object.entries(headers)) res.setHeader(name, value);
75
+ res.end(body);
76
+ }
77
+
78
+ function redirect(res, location) {
79
+ res.statusCode = 302;
80
+ res.setHeader('Location', location);
81
+ res.setHeader('Cache-Control', 'no-store');
82
+ res.end();
83
+ }
84
+
85
+ /**
86
+ * Reads a urlencoded POST body when no body parser has already done it, and keeps only string
87
+ * values: `express.urlencoded({ extended: true })` turns `state[]=x` into an array, and nothing in
88
+ * this protocol is anything but a string.
89
+ */
90
+ async function readForm(req) {
91
+ let body = req.body;
92
+ if (!body || typeof body !== 'object') {
93
+ body = {};
94
+ if ((req.headers?.['content-type'] ?? '').includes('application/x-www-form-urlencoded')) {
95
+ const chunks = [];
96
+ let size = 0;
97
+ for await (const chunk of req) {
98
+ size += chunk.length;
99
+ if (size > MAX_FORM_BYTES) throw new ArkCallbackError('the form body is larger than any sign-in response.');
100
+ chunks.push(chunk);
101
+ }
102
+ body = Object.fromEntries(new URLSearchParams(Buffer.concat(chunks).toString('utf8')));
103
+ }
104
+ }
105
+ return Object.fromEntries(Object.entries(body).filter(([, value]) => typeof value === 'string'));
106
+ }
107
+
108
+ export function arkExpress(options = {}) {
109
+ const {
110
+ client: providedClient,
111
+ secret,
112
+ loginPath = '/login',
113
+ callbackPath,
114
+ logoutPath = '/logout',
115
+ store = new MemorySessionStore(),
116
+ cookieName = 'ark_session',
117
+ cookie: cookieOptions = {},
118
+ sessionTtlSeconds = DEFAULT_SESSION_TTL_SECONDS,
119
+ refreshLeewaySeconds = REFRESH_WINDOW_SECONDS,
120
+ fetchUserInfo = false,
121
+ returnToParam = 'returnTo',
122
+ defaultReturnTo = '/',
123
+ errorPath = null,
124
+ onError = null,
125
+ trustProxy = true,
126
+ accountSwitch: accountSwitchOptions = {},
127
+ events = {},
128
+ ...clientOptions
129
+ } = options;
130
+
131
+ const client = providedClient ?? new ArkOAuthClient(clientOptions);
132
+ const switchOptions = normalizeAccountSwitch(accountSwitchOptions);
133
+
134
+ if (!secret || String(secret).length < 16) {
135
+ throw new ArkConfigError(
136
+ "arkExpress: 'secret' is required and must be at least 16 characters. It signs the session cookie; keep it in an " +
137
+ 'environment variable, and use the same value across every instance behind a load balancer.'
138
+ );
139
+ }
140
+
141
+ const configuredCallbackPath =
142
+ callbackPath ?? (client.config.redirectUri ? new URL(client.config.redirectUri).pathname : '/signin-oidc');
143
+
144
+ const cookieDefaults = { httpOnly: true, secure: true, sameSite: 'Lax', path: '/', ...cookieOptions };
145
+
146
+ // A form_post callback is a cross-site POST, and a browser does not send a SameSite=Lax (or
147
+ // Strict) cookie with one. The callback would never find its login transaction, and every sign-in
148
+ // would fail with "could not be matched to a request from this browser".
149
+ if (client.config.responseMode === 'form_post' && String(cookieDefaults.sameSite).toLowerCase() !== 'none') {
150
+ throw new ArkConfigError(
151
+ "arkExpress: responseMode 'form_post' needs cookie: { sameSite: 'None', secure: true }. The provider posts the callback " +
152
+ 'cross-site, and a browser withholds a SameSite=Lax cookie from that request. Or leave responseMode at query.'
153
+ );
154
+ }
155
+
156
+ // Refreshes in flight, keyed by session id. With rotation on, two requests refreshing the same
157
+ // session at once would present the same refresh token twice — which the server reads as theft
158
+ // and answers by revoking the entire family, signing the user out of everything. Within one
159
+ // process this collapses them into a single exchange; across processes, a shared store needs a
160
+ // lock of its own.
161
+ const refreshes = new Map();
162
+
163
+ // ---------------------------------------------------------------
164
+ // request helpers
165
+ // ---------------------------------------------------------------
166
+
167
+ /**
168
+ * This application's origin as the browser sees it. Behind a proxy that is the forwarded pair —
169
+ * both headers or neither, as the Python client reads them, so a lone X-Forwarded-Host cannot
170
+ * graft another host onto this request's scheme. Turn `trustProxy` off when nothing in front of
171
+ * the app sets them; then nothing a client sends can move the redirect URI.
172
+ */
173
+ function originOf(req) {
174
+ const headers = req.headers ?? {};
175
+ if (trustProxy) {
176
+ const proto = headers['x-forwarded-proto']?.split(',')[0].trim();
177
+ const host = headers['x-forwarded-host']?.split(',')[0].trim();
178
+ if (proto && host) return `${proto}://${host}`;
179
+ }
180
+ return `${req.socket?.encrypted ? 'https' : 'http'}://${headers.host}`;
181
+ }
182
+
183
+ const urlOf = (req) => new URL(req.originalUrl ?? req.url ?? '/', originOf(req));
184
+ const absolute = (req, path) => new URL(path, originOf(req)).toString();
185
+ const redirectUriFor = (req) => client.config.redirectUri ?? absolute(req, configuredCallbackPath);
186
+
187
+ function fail(req, res, next, error) {
188
+ if (onError) return onError(error, req, res, next);
189
+ if (errorPath) return redirect(res, `${errorPath}?auth_error=${encodeURIComponent(error.message)}`);
190
+ send(res, error instanceof ArkOAuthError && error.status === 403 ? 403 : 400, `Sign-in failed: ${error.message}`);
191
+ }
192
+
193
+ // ---------------------------------------------------------------
194
+ // session
195
+ // ---------------------------------------------------------------
196
+
197
+ async function loadSession(req) {
198
+ const cookies = parseCookies(req.headers?.cookie);
199
+ const id = unsignSessionId(cookies[cookieName], secret);
200
+ if (!id) return { id: null, data: null };
201
+ const data = await store.get(id);
202
+ return { id: data ? id : null, data };
203
+ }
204
+
205
+ async function saveSession(res, id, data) {
206
+ const sessionId = id ?? createSessionId();
207
+ data.updatedAt = Math.floor(Date.now() / 1000);
208
+ await store.set(sessionId, data, sessionTtlSeconds);
209
+ if (!id) {
210
+ appendCookie(res, serializeCookie(cookieName, signSessionId(sessionId, secret), { ...cookieDefaults, maxAge: sessionTtlSeconds }));
211
+ }
212
+ return sessionId;
213
+ }
214
+
215
+ const expireCookie = (res, name) => appendCookie(res, serializeCookie(name, '', { ...cookieDefaults, maxAge: 0 }));
216
+
217
+ async function dropSession(res, id) {
218
+ if (id) await store.destroy(id);
219
+ expireCookie(res, cookieName);
220
+ }
221
+
222
+ /**
223
+ * Revokes a session's refresh token at the provider. Without it, a session ended here leaves a
224
+ * live refresh token behind until it expires; revoking takes its whole rotation family down.
225
+ */
226
+ async function revokeQuietly(tokens) {
227
+ if (!tokens?.refreshToken) return;
228
+ try {
229
+ await client.revoke(tokens.refreshToken, { tokenTypeHint: 'refresh_token' });
230
+ } catch {
231
+ // Best effort: a provider that is down must not prevent a local sign-out.
232
+ }
233
+ }
234
+
235
+ /** Prunes expired and surplus login transactions, so a bot hitting /login cannot grow a session forever. */
236
+ function pruneTransactions(txs) {
237
+ const now = Math.floor(Date.now() / 1000);
238
+ const live = Object.entries(txs ?? {}).filter(([, tx]) => now - tx.createdAt < TRANSACTION_TTL_SECONDS);
239
+ live.sort((a, b) => b[1].createdAt - a[1].createdAt);
240
+ return Object.fromEntries(live.slice(0, MAX_CONCURRENT_TRANSACTIONS));
241
+ }
242
+
243
+ // ---------------------------------------------------------------
244
+ // sign-in, callback, sign-out
245
+ // ---------------------------------------------------------------
246
+
247
+ async function startLogin(req, res, { returnTo, prompt, loginHint, scopes, maxAge, freshSession = false } = {}) {
248
+ const url = urlOf(req);
249
+ const transaction = await client.createAuthorizationUrl({
250
+ redirectUri: redirectUriFor(req),
251
+ returnTo: returnTo ?? localOrDefault(url.searchParams.get(returnToParam), null) ?? defaultReturnTo,
252
+ prompt,
253
+ loginHint: loginHint ?? url.searchParams.get('login_hint') ?? undefined,
254
+ scopes,
255
+ maxAge
256
+ });
257
+
258
+ // A switch starts from nothing: the previous account's session has just been destroyed, and
259
+ // loading it back would resurrect a dead id.
260
+ const { id, data } = freshSession ? { id: null, data: null } : await loadSession(req);
261
+ const session = data ?? { createdAt: Math.floor(Date.now() / 1000), txs: {} };
262
+ session.txs = pruneTransactions({
263
+ ...session.txs,
264
+ [transaction.state]: {
265
+ codeVerifier: transaction.codeVerifier,
266
+ nonce: transaction.nonce,
267
+ redirectUri: transaction.redirectUri,
268
+ returnTo: transaction.returnTo,
269
+ maxAge: transaction.maxAge,
270
+ createdAt: transaction.createdAt
271
+ }
272
+ });
273
+
274
+ await saveSession(res, id, session);
275
+ redirect(res, transaction.url);
276
+ }
277
+
278
+ async function completeLogin(req, res, next) {
279
+ let params;
280
+ try {
281
+ params = req.method === 'POST' ? await readForm(req) : Object.fromEntries(urlOf(req).searchParams);
282
+ } catch (error) {
283
+ return fail(req, res, next, error);
284
+ }
285
+
286
+ const { id, data } = await loadSession(req);
287
+ const state = params.state;
288
+ const stored = state && data?.txs && Object.hasOwn(data.txs, state) ? data.txs[state] : null;
289
+
290
+ if (!stored) {
291
+ // An error the provider sent without our state (Ark omits it when it refuses the request
292
+ // outright) still names the real problem. Shown, never acted on: nothing is redeemed.
293
+ if (params.error) {
294
+ return fail(
295
+ req,
296
+ res,
297
+ next,
298
+ new ArkOAuthError(params.error, params.error_description ?? null, { body: params, endpoint: 'authorization response' })
299
+ );
300
+ }
301
+ // No transaction means the response cannot be tied to a sign-in this browser started: an
302
+ // expired login, a session lost to a restart with an in-memory store, or a forged callback.
303
+ return fail(
304
+ req,
305
+ res,
306
+ next,
307
+ new ArkCallbackError(
308
+ 'this sign-in could not be matched to a request from this browser. It may have expired — start again from the login page.'
309
+ )
310
+ );
311
+ }
312
+
313
+ // The transaction is single-use whatever happens next.
314
+ delete data.txs[state];
315
+
316
+ let tokens;
317
+ try {
318
+ tokens = await client.handleCallback(params, { state, ...stored });
319
+ } catch (error) {
320
+ await saveSession(res, id, data);
321
+ return fail(req, res, next, error);
322
+ }
323
+
324
+ // Read off the access token without re-verifying it: it arrived over TLS from the token
325
+ // endpoint in this exchange, bound to the verified ID token by at_hash.
326
+ const arkClaims = tokens.arkClaims();
327
+
328
+ // The last point before a session is written. Refusing here rather than at the first guarded
329
+ // page is the whole difference: the browser never holds a session for an account that cannot
330
+ // use this application.
331
+ if (switchOptions.requireArkClaims || events.onEvaluateAccess) {
332
+ const allowed = await evaluateAccess(switchOptions, events, { claims: tokens.claims ?? {}, arkClaims, tokens });
333
+ if (!allowed) {
334
+ await saveSession(res, id, data);
335
+ await revokeQuietly(tokens);
336
+ const returnUrl = localOrDefault(stored.returnTo, switchOptions.homePath);
337
+ return deny(req, res, ArkAccessDeniedReasons.NO_APP_ACCESS, tokens.claims, arkClaims, returnUrl);
338
+ }
339
+ }
340
+
341
+ // A fresh session id at the moment privileges change, so a session id an attacker planted
342
+ // before sign-in is not the one that ends up authenticated (session fixation).
343
+ //
344
+ // Sign-ins still outstanding in other tabs move across to the new session. They are bound to
345
+ // this browser and nothing else — dropping them along with the old session id is what turns a
346
+ // second open tab into "this sign-in could not be matched to a request from this browser".
347
+ const carried = pruneTransactions(data.txs);
348
+ await dropSession(res, id);
349
+
350
+ const session = {
351
+ createdAt: Math.floor(Date.now() / 1000),
352
+ txs: carried,
353
+ tokens: tokens.toJSON(),
354
+ user: tokens.claims,
355
+ arkClaims,
356
+ sub: tokens.subject
357
+ };
358
+
359
+ if (fetchUserInfo && tokens.accessToken && tokens.hasScope('openid')) {
360
+ try {
361
+ session.user = { ...session.user, ...(await client.userInfo(tokens.accessToken)) };
362
+ } catch {
363
+ // UserInfo is supplementary; the ID token already carries what the scopes unlocked.
364
+ }
365
+ }
366
+
367
+ clearDenied(req, res);
368
+ await saveSession(res, null, session);
369
+ redirect(res, localOrDefault(stored.returnTo, defaultReturnTo));
370
+ }
371
+
372
+ async function endSession(req, res, { returnTo } = {}) {
373
+ const { id, data } = await loadSession(req);
374
+ const tokens = TokenSet.fromJSON(data?.tokens);
375
+ await revokeQuietly(tokens);
376
+ await dropSession(res, id);
377
+
378
+ const landing = localOrDefault(returnTo, defaultReturnTo);
379
+ let target = landing;
380
+ try {
381
+ target = await client.endSessionUrl({
382
+ idTokenHint: tokens?.idToken ?? undefined,
383
+ postLogoutRedirectUri: client.config.postLogoutRedirectUri ?? absolute(req, landing)
384
+ });
385
+ } catch {
386
+ // A tenant with no end_session_endpoint still gets a clean local sign-out.
387
+ }
388
+ redirect(res, target);
389
+ }
390
+
391
+ // ---------------------------------------------------------------
392
+ // account switching
393
+ // ---------------------------------------------------------------
394
+
395
+ function clearDenied(req, res) {
396
+ if (parseCookies(req.headers?.cookie)[DENIED_COOKIE]) expireCookie(res, DENIED_COOKIE);
397
+ }
398
+
399
+ /**
400
+ * Abandons the account this application is signed in as and asks the provider for its sign-in
401
+ * form, so the person at the keyboard can enter their own credentials. The local session goes
402
+ * first: a user who abandons the provider's form must not come back to the previous person's.
403
+ */
404
+ async function switchUser(req, res, { returnUrl, loginHint } = {}) {
405
+ const target = localOrDefault(returnUrl, switchOptions.homePath);
406
+ clearDenied(req, res);
407
+
408
+ // Ending the provider session too signs the previous user out of every application they had
409
+ // open; they land back here anonymous, and the next guarded page draws the sign-in form.
410
+ if (switchOptions.endProviderSessionOnSwitch) return endSession(req, res, { returnTo: target });
411
+
412
+ const { id, data } = await loadSession(req);
413
+ await revokeQuietly(TokenSet.fromJSON(data?.tokens));
414
+ if (id) await store.destroy(id);
415
+
416
+ return startLogin(req, res, { ...ArkChallengeProperties.switchUser(target, loginHint, switchOptions.prompt), freshSession: true });
417
+ }
418
+
419
+ /** RP-initiated logout: this application's session and the provider's. */
420
+ async function signOutEverywhere(req, res, { returnUrl } = {}) {
421
+ clearDenied(req, res);
422
+ return endSession(req, res, { returnTo: localOrDefault(returnUrl, switchOptions.homePath) });
423
+ }
424
+
425
+ /** Ends this application's session only, leaving the provider session intact. */
426
+ async function signOutLocally(req, res, { returnUrl } = {}) {
427
+ const { id, data } = await loadSession(req);
428
+ await revokeQuietly(TokenSet.fromJSON(data?.tokens));
429
+ await dropSession(res, id);
430
+ clearDenied(req, res);
431
+ redirect(res, localOrDefault(returnUrl, switchOptions.homePath));
432
+ }
433
+
434
+ /** The account the last denial was about, for an application drawing its own page; else null. */
435
+ function deniedAccount(req) {
436
+ const value = parseCookies(req.headers?.cookie)[DENIED_COOKIE];
437
+ const payload = value ? unprotectState(secret, value) : null;
438
+ if (!payload) return null;
439
+ const { return_url: returnUrl = null, ...rest } = payload;
440
+ return { subject: null, email: null, name: null, reason: null, ...rest, returnUrl };
441
+ }
442
+
443
+ async function deny(req, res, reason, claims, arkClaims, returnUrl) {
444
+ const denied = describeDenial(reason, claims, arkClaims, returnUrl);
445
+ if (events.onAccessDenied) {
446
+ await events.onAccessDenied(denied, req, res);
447
+ // The handler drew a page of its own, or said it had.
448
+ if (denied.handled || res.headersSent) return;
449
+ }
450
+
451
+ const { subject, email, name } = denied;
452
+ appendCookie(
453
+ res,
454
+ serializeCookie(DENIED_COOKIE, protectState(secret, { subject, email, name, reason, return_url: returnUrl ?? null }), {
455
+ ...cookieDefaults,
456
+ sameSite: 'Lax',
457
+ maxAge: DENIED_MAX_AGE_SECONDS
458
+ })
459
+ );
460
+ redirect(res, deniedUrl(switchOptions, returnUrl));
461
+ }
462
+
463
+ function renderDeniedPage(req, res) {
464
+ const denied = deniedAccount(req);
465
+ let email = denied?.email;
466
+ let name = denied?.name;
467
+ if (!email && !name) {
468
+ // Arrived from a 403 rather than from a refused callback, so there is a session to read.
469
+ const user = req.ark?.user ?? {};
470
+ email = user.email ?? user.preferred_username;
471
+ name = user.name;
472
+ }
473
+
474
+ const html = renderAccessDeniedPage(switchOptions, {
475
+ app: switchOptions.appDisplayName ?? client.config.clientId,
476
+ account: switchOptions.showSignedInAccount ? email || name || null : null,
477
+ returnUrl: localOrDefault(urlOf(req).searchParams.get('returnUrl') || denied?.returnUrl, switchOptions.homePath)
478
+ });
479
+
480
+ // Spent on read: a stale cookie must not name the wrong account on a later visit.
481
+ clearDenied(req, res);
482
+ send(res, 403, html, {
483
+ type: 'text/html; charset=utf-8',
484
+ headers: { 'Content-Security-Policy': DENIED_PAGE_CSP, 'Referrer-Policy': 'no-referrer', 'X-Frame-Options': 'DENY' }
485
+ });
486
+ }
487
+
488
+ /** Serves the three account endpoints. Returns true when the request was one of them. */
489
+ async function serveAccountEndpoints(req, res, path) {
490
+ if (!switchOptions.enabled) return false;
491
+
492
+ const isSwitch = samePath(path, switchOptions.switchUserPath);
493
+ const isSignOut = samePath(path, switchOptions.signOutPath);
494
+ if (isSwitch || isSignOut) {
495
+ if (isSignOut && !switchOptions.allowFullSignOut) {
496
+ send(res, 404, 'Not Found');
497
+ return true;
498
+ }
499
+ const guard = checkSameOrigin(req.method, req.headers, originOf(req));
500
+ if (!guard.ok) {
501
+ send(res, guard.status, guard.message, { headers: guard.status === 405 ? { Allow: 'POST' } : {} });
502
+ return true;
503
+ }
504
+ // Form first, then the query string — a returnUrl left out of the form is not lost.
505
+ const form = await readForm(req);
506
+ const query = urlOf(req).searchParams;
507
+ const field = (name) => form[name] || query.get(name) || null;
508
+ if (isSwitch) await switchUser(req, res, { returnUrl: field('returnUrl'), loginHint: field('login_hint') });
509
+ else await signOutEverywhere(req, res, { returnUrl: field('returnUrl') });
510
+ return true;
511
+ }
512
+
513
+ if (switchOptions.serveDefaultPage && samePath(path, switchOptions.accessDeniedPath)) {
514
+ await attachContext(req, res);
515
+ renderDeniedPage(req, res);
516
+ return true;
517
+ }
518
+ return false;
519
+ }
520
+
521
+ // ---------------------------------------------------------------
522
+ // token freshness
523
+ // ---------------------------------------------------------------
524
+
525
+ /**
526
+ * The session's tokens, refreshed first when the access token is about to expire.
527
+ *
528
+ * Every caller ends up holding the rotated tokens, including one that waited on another request's
529
+ * refresh: a request left holding the retired refresh token would present it on its next refresh,
530
+ * and the server answers a reused refresh token by revoking the whole family.
531
+ */
532
+ async function freshTokens(sessionId, session, res) {
533
+ const tokens = TokenSet.fromJSON(session.tokens);
534
+ if (!tokens?.refreshToken || !tokens.expired(refreshLeewaySeconds)) return tokens;
535
+
536
+ let pending = refreshes.get(sessionId);
537
+ if (!pending) {
538
+ pending = refreshSession(sessionId, tokens).finally(() => refreshes.delete(sessionId));
539
+ refreshes.set(sessionId, pending);
540
+ }
541
+
542
+ const result = await pending;
543
+ if (result.signedOut) {
544
+ if (res && !res.headersSent) expireCookie(res, cookieName);
545
+ return null;
546
+ }
547
+ if (result.session) Object.assign(session, result.session);
548
+ return result.tokens;
549
+ }
550
+
551
+ /** Runs one refresh. Never throws: the answer is new tokens, the old ones, or "signed out". */
552
+ async function refreshSession(sessionId, tokens) {
553
+ // The store is the source of truth: another request, or another instance sharing the store,
554
+ // may have refreshed since this one loaded the session.
555
+ const latest = await store.get(sessionId);
556
+ if (!latest) return { signedOut: true };
557
+ const current = TokenSet.fromJSON(latest.tokens) ?? tokens;
558
+ if (!current.expired(refreshLeewaySeconds) || !current.refreshToken) return { tokens: current, session: latest };
559
+
560
+ try {
561
+ const refreshed = await client.refresh(current.refreshToken);
562
+ const session = {
563
+ ...latest,
564
+ tokens: refreshed.toJSON(),
565
+ // The ID token is reissued on refresh; keep the identity in step with it.
566
+ user: refreshed.claims ? { ...latest.user, ...refreshed.claims } : latest.user,
567
+ arkClaims: refreshed.arkClaims()
568
+ };
569
+ await store.set(sessionId, session, sessionTtlSeconds);
570
+ return { tokens: refreshed, session };
571
+ } catch (error) {
572
+ // invalid_grant means the refresh token is spent, revoked, or its session ended at the
573
+ // provider. There is nothing to retry: the user has to sign in again.
574
+ if (error instanceof ArkOAuthError && error.error === 'invalid_grant') {
575
+ await store.destroy(sessionId);
576
+ return { signedOut: true };
577
+ }
578
+ // A transient failure must not sign the user out; the next request tries again.
579
+ return { tokens: current, session: latest };
580
+ }
581
+ }
582
+
583
+ // ---------------------------------------------------------------
584
+ // the middleware
585
+ // ---------------------------------------------------------------
586
+
587
+ async function attachContext(req, res) {
588
+ const { id, data } = await loadSession(req);
589
+ let session = data;
590
+ let tokens = null;
591
+ if (id && session) {
592
+ tokens = await freshTokens(id, session, res);
593
+ if (!tokens) session = null;
594
+ }
595
+
596
+ const authenticated = Boolean(session?.tokens && tokens);
597
+ const claims = () => (authenticated ? session.arkClaims ?? [] : []);
598
+ const scopes = tokens?.scopes() ?? [];
599
+
600
+ req.ark = {
601
+ client,
602
+ store,
603
+ sessionId: authenticated ? id : null,
604
+ isAuthenticated: authenticated,
605
+ user: authenticated ? (session.user ?? null) : null,
606
+ sub: authenticated ? (session.sub ?? null) : null,
607
+ claims: claims(),
608
+ scopes,
609
+ tokens: authenticated ? tokens : null,
610
+ idToken: authenticated ? tokens.idToken : null,
611
+
612
+ /** The current access token, refreshed first if it is about to expire. Read it per call; never cache it. */
613
+ async accessToken() {
614
+ if (!authenticated) return null;
615
+ const current = await freshTokens(id, session, res);
616
+ return current?.accessToken ?? null;
617
+ },
618
+
619
+ /** Attaches the access token to a downstream request's headers. */
620
+ async authorize(headers = {}) {
621
+ const token = await this.accessToken();
622
+ if (token) headers.Authorization = `Bearer ${token}`;
623
+ return headers;
624
+ },
625
+
626
+ hasClaim: (...wanted) => wanted.flat().every((c) => claims().includes(c)),
627
+ hasScope: (...wanted) => wanted.flat().every((s) => scopes.includes(s)),
628
+
629
+ login: (opts) => startLogin(req, res, opts),
630
+ logout: (opts) => endSession(req, res, opts),
631
+ switchUser: (opts) => switchUser(req, res, opts),
632
+ signOutEverywhere: (opts) => signOutEverywhere(req, res, opts),
633
+ signOutLocally: (opts) => signOutLocally(req, res, opts),
634
+ deniedAccount: () => deniedAccount(req)
635
+ };
636
+ }
637
+
638
+ const middleware = async function arkMiddleware(req, res, next) {
639
+ try {
640
+ const path = urlOf(req).pathname;
641
+
642
+ // The account endpoints first: they must answer even when everything else refuses to.
643
+ if (await serveAccountEndpoints(req, res, path)) return;
644
+ if (samePath(path, loginPath)) return await startLogin(req, res);
645
+ if (samePath(path, configuredCallbackPath)) return await completeLogin(req, res, next);
646
+ if (samePath(path, logoutPath)) return await endSession(req, res);
647
+
648
+ await attachContext(req, res);
649
+ next();
650
+ } catch (error) {
651
+ next(error);
652
+ }
653
+ };
654
+
655
+ /**
656
+ * Guards a route. An unauthenticated browser request is sent to the login page with a
657
+ * `returnTo`; an API or fetch request gets 401 and an RFC 6750 challenge, because redirecting
658
+ * XHR to a sign-in page produces a CORS error rather than anything the caller can act on. A
659
+ * signed-in browser missing a claim reaches the access-denied page — with the way out — rather
660
+ * than a bare 403.
661
+ */
662
+ middleware.requireAuth = ({ claims = [], scopes = [] } = {}) =>
663
+ function arkRequireAuth(req, res, next) {
664
+ const ark = req.ark;
665
+ if (!ark) {
666
+ return next(new ArkConfigError('req.ark is missing — mount the arkExpress() middleware before requireAuth().'));
667
+ }
668
+
669
+ if (!ark.isAuthenticated) {
670
+ if (!(wantsHtml(req) && req.method === 'GET')) {
671
+ return send(res, 401, JSON.stringify({ error: 'invalid_token', error_description: 'authentication is required.' }), {
672
+ type: 'application/json',
673
+ headers: { 'WWW-Authenticate': 'Bearer realm="ark", error="invalid_token"' }
674
+ });
675
+ }
676
+ return redirect(res, `${loginPath}?${returnToParam}=${encodeURIComponent(req.originalUrl ?? req.url ?? '/')}`);
677
+ }
678
+
679
+ const missingClaims = [claims].flat().filter((c) => !ark.claims.includes(c));
680
+ const missingScopes = [scopes].flat().filter((s) => !ark.scopes.includes(s));
681
+ if (missingClaims.length || missingScopes.length) {
682
+ if (switchOptions.enabled && wantsHtml(req)) {
683
+ const here = localOrDefault(req.originalUrl ?? req.url, switchOptions.homePath);
684
+ return deny(req, res, ArkAccessDeniedReasons.FORBIDDEN, ark.user, ark.claims, here).catch(next);
685
+ }
686
+ const description = [
687
+ missingClaims.length ? `missing claim(s): ${missingClaims.join(', ')}` : null,
688
+ missingScopes.length ? `missing scope(s): ${missingScopes.join(', ')}` : null
689
+ ]
690
+ .filter(Boolean)
691
+ .join('; ');
692
+ return send(res, 403, JSON.stringify({ error: 'insufficient_scope', error_description: description }), { type: 'application/json' });
693
+ }
694
+
695
+ next();
696
+ };
697
+
698
+ /** Shorthand for requireAuth({ claims }) — Ark authorization claims, the thing to authorise on. */
699
+ middleware.requireClaims = (...claims) => middleware.requireAuth({ claims: claims.flat() });
700
+ middleware.requireScopes = (...scopes) => middleware.requireAuth({ scopes: scopes.flat() });
701
+
702
+ /**
703
+ * This application's configuration beside the provider's live metadata, for a setup or health
704
+ * page — with the redirect URI this request would really send, which is the one to register.
705
+ */
706
+ middleware.checkSetup = async (req) => {
707
+ const report = await client.checkSetup({ origin: originOf(req), callbackPath: configuredCallbackPath });
708
+ return {
709
+ ...report,
710
+ isAuthenticated: Boolean(req.ark?.isAuthenticated),
711
+ signedInAs: req.ark?.user?.name ?? req.ark?.user?.email ?? null,
712
+ authError: urlOf(req).searchParams.get('auth_error')
713
+ };
714
+ };
715
+
716
+ middleware.switchUser = switchUser;
717
+ middleware.signOutEverywhere = signOutEverywhere;
718
+ middleware.signOutLocally = signOutLocally;
719
+ middleware.deniedAccount = deniedAccount;
720
+
721
+ middleware.client = client;
722
+ middleware.store = store;
723
+ middleware.accountSwitch = switchOptions;
724
+ middleware.loginPath = loginPath;
725
+ middleware.callbackPath = configuredCallbackPath;
726
+ middleware.logoutPath = logoutPath;
727
+
728
+ return middleware;
729
+ }
730
+
731
+ /**
732
+ * Makes text safe for a quoted-string in a header. A token's `kid` reaches error messages, and a
733
+ * CR or LF in one would make `setHeader` throw — from inside an async handler, an unhandled
734
+ * rejection, which can take the process down.
735
+ */
736
+ const headerText = (value) =>
737
+ String(value)
738
+ .replace(/[^\x20-\x7e]/g, '?')
739
+ .replace(/["\\]/g, "'")
740
+ .slice(0, 200);
741
+
742
+ /**
743
+ * Bearer-token authentication for an API — the resource-server half.
744
+ *
745
+ * Verification is local, against the cached JWKS, so this costs no network call per request once
746
+ * the keys are loaded. Failures follow RFC 6750: a `WWW-Authenticate` challenge naming the reason,
747
+ * 401 when the token is missing or bad, 403 when it is valid but not allowed to do this.
748
+ */
749
+ export function arkBearer(options = {}) {
750
+ const { client: providedClient, scopes = [], claims = [], audience, optional = false, requireTypeHeader = true, ...clientOptions } = options;
751
+ const client = providedClient ?? new ArkOAuthClient(clientOptions);
752
+
753
+ const challenge = (res, status, error, description) => {
754
+ const text = headerText(description);
755
+ send(res, status, JSON.stringify({ error, error_description: text }), {
756
+ type: 'application/json',
757
+ headers: { 'WWW-Authenticate': `Bearer realm="ark", error="${error}", error_description="${text}"` }
758
+ });
759
+ };
760
+
761
+ const middleware = async function arkBearerMiddleware(req, res, next) {
762
+ try {
763
+ const header = req.headers?.authorization ?? '';
764
+ const token = header.toLowerCase().startsWith('bearer ') ? header.slice(7).trim() : null;
765
+
766
+ if (!token) {
767
+ if (optional) {
768
+ req.ark = { isAuthenticated: false, token: null, claims: [], scopes: [], hasClaim: () => false, hasScope: () => false, client };
769
+ return next();
770
+ }
771
+ return challenge(res, 401, 'invalid_token', 'an access token is required.');
772
+ }
773
+
774
+ let payload;
775
+ try {
776
+ payload = await client.verifyAccessToken(token, { audience, scopes, arkClaims: claims, requireTypeHeader });
777
+ } catch (error) {
778
+ if (error instanceof ArkOAuthError && error.error === 'insufficient_scope') {
779
+ return challenge(res, 403, 'insufficient_scope', error.errorDescription ?? error.message);
780
+ }
781
+ return challenge(res, 401, 'invalid_token', error.message);
782
+ }
783
+
784
+ const arkClaims = Array.isArray(payload.ark_claims) ? payload.ark_claims : payload.ark_claims ? [payload.ark_claims] : [];
785
+ const granted = String(payload.scope ?? '').split(' ').filter(Boolean);
786
+ req.ark = {
787
+ isAuthenticated: true,
788
+ token,
789
+ payload,
790
+ sub: payload.sub,
791
+ clientId: payload.client_id ?? null,
792
+ sessionId: payload.sid ?? null,
793
+ scopes: granted,
794
+ claims: arkClaims,
795
+ hasClaim: (...wanted) => wanted.flat().every((c) => arkClaims.includes(c)),
796
+ hasScope: (...wanted) => wanted.flat().every((s) => granted.includes(s)),
797
+ client
798
+ };
799
+ next();
800
+ } catch (error) {
801
+ next(error);
802
+ }
803
+ };
804
+
805
+ /** A per-route guard, for when different endpoints need different scopes or claims. */
806
+ middleware.require = ({ scopes: needScopes = [], claims: needClaims = [] } = {}) =>
807
+ function arkBearerRequire(req, res, next) {
808
+ const ark = req.ark;
809
+ if (!ark?.isAuthenticated) return challenge(res, 401, 'invalid_token', 'an access token is required.');
810
+ const missing = [
811
+ ...[needScopes].flat().filter((s) => !ark.scopes.includes(s)).map((s) => `scope '${s}'`),
812
+ ...[needClaims].flat().filter((c) => !ark.claims.includes(c)).map((c) => `claim '${c}'`)
813
+ ];
814
+ if (missing.length) return challenge(res, 403, 'insufficient_scope', `the token is missing ${missing.join(', ')}.`);
815
+ next();
816
+ };
817
+
818
+ middleware.client = client;
819
+ return middleware;
820
+ }