@passflow/node 0.1.3 → 0.3.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.
@@ -0,0 +1,898 @@
1
+ import { t as isLoopbackHost } from "./loopback-CDiL_KzV.mjs";
2
+ import { EncryptJWT, decodeJwt, jwtDecrypt } from "jose";
3
+ import * as oauth from "oauth4webapi";
4
+ // src/session/config.ts
5
+ const DEFAULT_SCOPES = [
6
+ "openid",
7
+ "profile",
8
+ "email",
9
+ "offline_access"
10
+ ];
11
+ const DEFAULT_ROUTES = {
12
+ login: "/auth/login",
13
+ callback: "/auth/callback",
14
+ logout: "/auth/logout"
15
+ };
16
+ const MIN_SECRET_LENGTH = 32;
17
+ /** A route is a plain absolute path: it becomes a cookie `Path`, so it may hold nothing that ends the attribute. */
18
+ const ROUTE = /^\/[A-Za-z0-9\-._~/%]*$/;
19
+ function processEnv() {
20
+ return globalThis.process?.env ?? {};
21
+ }
22
+ /**
23
+ * The session settings from environment variables: `PASSFLOW_ISSUER`, `PASSFLOW_CLIENT_ID`,
24
+ * `PASSFLOW_CLIENT_SECRET`, `PASSFLOW_SECRET` and `APP_BASE_URL`. A variable that is unset or empty is left
25
+ * out, so an explicit value spread after this one wins. Reads `process.env` when `env` is not given.
26
+ */
27
+ function configFromEnv(env) {
28
+ const source = env ?? processEnv();
29
+ const read = (name) => {
30
+ const value = source[name];
31
+ return typeof value === "string" && value !== "" ? value : void 0;
32
+ };
33
+ const config = {};
34
+ const issuer = read("PASSFLOW_ISSUER");
35
+ const clientId = read("PASSFLOW_CLIENT_ID");
36
+ const clientSecret = read("PASSFLOW_CLIENT_SECRET");
37
+ const secret = read("PASSFLOW_SECRET");
38
+ const baseUrl = read("APP_BASE_URL");
39
+ if (issuer !== void 0) config.issuer = issuer;
40
+ if (clientId !== void 0) config.clientId = clientId;
41
+ if (clientSecret !== void 0) config.clientSecret = clientSecret;
42
+ if (secret !== void 0) config.secret = secret;
43
+ if (baseUrl !== void 0) config.baseUrl = baseUrl;
44
+ return config;
45
+ }
46
+ function requireString(value, envName, option) {
47
+ if (typeof value !== "string" || value === "") throw new TypeError(`[passflow] ${envName} is not set (config.${option})`);
48
+ return value;
49
+ }
50
+ /** https, or http on a loopback host. The error names the variable, never the value. */
51
+ function requireUrl(value, envName, option) {
52
+ const raw = requireString(value, envName, option);
53
+ let url;
54
+ try {
55
+ url = new URL(raw);
56
+ } catch {
57
+ throw new TypeError(`[passflow] ${envName} must be a valid URL (config.${option})`);
58
+ }
59
+ if (url.protocol === "https:") return {
60
+ url,
61
+ loopback: false
62
+ };
63
+ if (url.protocol === "http:" && isLoopbackHost(raw, url)) return {
64
+ url,
65
+ loopback: true
66
+ };
67
+ throw new TypeError(`[passflow] ${envName} must use https unless the host is loopback (config.${option})`);
68
+ }
69
+ function requireRoutes(routes) {
70
+ if (routes === void 0) return { ...DEFAULT_ROUTES };
71
+ if (typeof routes !== "object" || routes === null) throw new TypeError("[passflow] config.routes must be an object");
72
+ const given = routes;
73
+ const resolved = { ...DEFAULT_ROUTES };
74
+ for (const key of [
75
+ "login",
76
+ "callback",
77
+ "logout"
78
+ ]) {
79
+ const value = given[key];
80
+ if (value === void 0) continue;
81
+ if (typeof value !== "string" || !ROUTE.test(value)) throw new TypeError(`[passflow] config.routes.${key} must be an absolute path such as ${DEFAULT_ROUTES[key]}`);
82
+ if (value.endsWith("/")) throw new TypeError(`[passflow] config.routes.${key} must not end in "/" (use ${value.replace(/\/+$/, "") || DEFAULT_ROUTES[key]})`);
83
+ resolved[key] = value;
84
+ }
85
+ if (new Set(Object.values(resolved)).size !== 3) throw new TypeError("[passflow] config.routes must name three different paths");
86
+ return resolved;
87
+ }
88
+ function requireScopes(scopes) {
89
+ if (scopes === void 0) return [...DEFAULT_SCOPES];
90
+ if (!Array.isArray(scopes) || scopes.length === 0 || !scopes.every((scope) => typeof scope === "string" && /^[\x21\x23-\x5b\x5d-\x7e]+$/.test(scope))) throw new TypeError("[passflow] config.scopes must name one or more scopes");
91
+ return [...scopes];
92
+ }
93
+ /**
94
+ * Checks every value. Called on first use, never at import, so a build without the environment passes.
95
+ * Throws `TypeError` naming the environment variable or option that is missing or wrong.
96
+ */
97
+ function resolveConfig(config) {
98
+ if (typeof config !== "object" || config === null) throw new TypeError("[passflow] the session config must be an object");
99
+ const issuer = requireUrl(config.issuer, "PASSFLOW_ISSUER", "issuer");
100
+ const clientId = requireString(config.clientId, "PASSFLOW_CLIENT_ID", "clientId");
101
+ const clientSecret = requireString(config.clientSecret, "PASSFLOW_CLIENT_SECRET", "clientSecret");
102
+ const secret = requireString(config.secret, "PASSFLOW_SECRET", "secret");
103
+ if (secret.length < MIN_SECRET_LENGTH) throw new TypeError(`[passflow] PASSFLOW_SECRET must be at least ${String(MIN_SECRET_LENGTH)} characters (config.secret)`);
104
+ const base = requireUrl(config.baseUrl, "APP_BASE_URL", "baseUrl");
105
+ if (base.url.pathname !== "/" || base.url.search !== "" || base.url.hash !== "") throw new TypeError("[passflow] APP_BASE_URL must be the app's origin, with no path (config.baseUrl)");
106
+ if (config.fetch !== void 0 && typeof config.fetch !== "function") throw new TypeError("[passflow] config.fetch must be a function");
107
+ if (config.now !== void 0 && typeof config.now !== "function") throw new TypeError("[passflow] config.now must be a function");
108
+ return {
109
+ issuer: issuer.url,
110
+ issuerIsLoopback: issuer.loopback,
111
+ clientId,
112
+ clientSecret,
113
+ secret,
114
+ baseUrl: base.url.origin,
115
+ secure: base.url.protocol === "https:",
116
+ scopes: requireScopes(config.scopes),
117
+ routes: requireRoutes(config.routes),
118
+ fetch: config.fetch,
119
+ now: config.now ?? (() => /* @__PURE__ */ new Date())
120
+ };
121
+ }
122
+ // src/session/cookies.ts
123
+ /** The session cookie's name over http loopback, where a browser refuses `Secure` and so the `__Host-` prefix. */
124
+ const SESSION_COOKIE = "passflow_session";
125
+ /** The transaction cookie's name over http loopback. */
126
+ const TRANSACTION_COOKIE = "passflow_txn";
127
+ /**
128
+ * Over https both names carry `__Host-`: the browser then takes the cookie only with `Secure`, `Path=/` and no
129
+ * `Domain`, so a sibling subdomain cannot plant one under a parent domain.
130
+ */
131
+ const HOST_PREFIX = "__Host-";
132
+ /** A sealed value longer than this is split into `<name>.0`, `<name>.1`, … */
133
+ const CHUNK_SIZE = 3500;
134
+ /** Browsers keep a cookie for at most 400 days, whatever `Max-Age` says. */
135
+ const MAX_COOKIE_AGE = 3456e4;
136
+ const DIGITS = /^\d+$/;
137
+ /** The session cookie's name: `__Host-passflow_session` over https, `passflow_session` over http loopback. */
138
+ function sessionCookieName(secure) {
139
+ return secure ? `${HOST_PREFIX}${SESSION_COOKIE}` : SESSION_COOKIE;
140
+ }
141
+ /** The transaction cookie's name: `__Host-passflow_txn` over https, `passflow_txn` over http loopback. */
142
+ function transactionCookieName(secure) {
143
+ return secure ? `${HOST_PREFIX}${TRANSACTION_COOKIE}` : TRANSACTION_COOKIE;
144
+ }
145
+ /** The name–value pairs of a `Cookie` header, in order. A part with no `=` is skipped. */
146
+ function parseCookies(cookieHeader) {
147
+ if (typeof cookieHeader !== "string" || cookieHeader === "") return [];
148
+ const pairs = [];
149
+ for (const part of cookieHeader.split(";")) {
150
+ const eq = part.indexOf("=");
151
+ if (eq < 0) continue;
152
+ const name = part.slice(0, eq).trim();
153
+ if (name !== "") pairs.push([name, part.slice(eq + 1).trim()]);
154
+ }
155
+ return pairs;
156
+ }
157
+ /** The chunk index of `name` under `base` (`<base>.<digits>`), or `undefined`. */
158
+ function chunkIndex(name, base) {
159
+ if (!name.startsWith(`${base}.`)) return;
160
+ const digits = name.slice(base.length + 1);
161
+ return DIGITS.test(digits) ? Number(digits) : void 0;
162
+ }
163
+ /** True for the session cookie of one scheme (see `sessionCookieName`) and for its chunks, `<name>.<digits>`. */
164
+ function isSessionCookieName(name, secure) {
165
+ const base = sessionCookieName(secure);
166
+ return name === base || chunkIndex(name, base) !== void 0;
167
+ }
168
+ /** True for a session cookie name of either scheme. */
169
+ function isAnySessionCookieName(name) {
170
+ return isSessionCookieName(name, true) || isSessionCookieName(name, false);
171
+ }
172
+ /**
173
+ * True when the `Cookie` header carries a session cookie of either scheme: the base name or any chunk. It is
174
+ * broader than the reader, so a request the reader can treat as signed in is always one this reports.
175
+ */
176
+ function hasSessionCookie(cookieHeader) {
177
+ return parseCookies(cookieHeader).some(([name]) => isAnySessionCookieName(name));
178
+ }
179
+ /** The value of the first cookie named `name`, or `undefined`. */
180
+ function readCookie(cookieHeader, name) {
181
+ return parseCookies(cookieHeader).find(([n]) => n === name)?.[1];
182
+ }
183
+ /**
184
+ * The sealed session from the `Cookie` header, read only under the name `secure` selects: the other scheme's
185
+ * name is ignored. The base cookie wins when present. Otherwise the chunks `.0` to `.n-1` are joined in order;
186
+ * a gap, or more than `MAX_CHUNKS`, reads as no session.
187
+ */
188
+ function readSessionValue(cookieHeader, secure) {
189
+ const pairs = parseCookies(cookieHeader);
190
+ const baseName = sessionCookieName(secure);
191
+ const base = pairs.find(([name]) => name === baseName);
192
+ if (base !== void 0) return base[1] === "" ? void 0 : base[1];
193
+ const chunks = /* @__PURE__ */ new Map();
194
+ for (const [name, value] of pairs) {
195
+ const index = chunkIndex(name, baseName);
196
+ if (index !== void 0 && !chunks.has(index)) chunks.set(index, value);
197
+ }
198
+ if (chunks.size === 0 || chunks.size > 3) return;
199
+ let value = "";
200
+ for (let i = 0; i < chunks.size; i++) {
201
+ const chunk = chunks.get(i);
202
+ if (chunk === void 0 || chunk === "") return;
203
+ value += chunk;
204
+ }
205
+ return value;
206
+ }
207
+ /** A `Set-Cookie` value: always HttpOnly and SameSite=Lax; `Secure` when the app is served over https. */
208
+ function serializeCookie(name, value, { path, maxAge, secure }) {
209
+ const attributes = [
210
+ `${name}=${value}`,
211
+ `Path=${path}`,
212
+ `Max-Age=${String(Math.max(0, Math.floor(maxAge)))}`,
213
+ "HttpOnly",
214
+ "SameSite=Lax"
215
+ ];
216
+ if (secure) attributes.push("Secure");
217
+ return attributes.join("; ");
218
+ }
219
+ /** A `Set-Cookie` value that expires the cookie. */
220
+ function expireCookie(name, path, secure) {
221
+ return serializeCookie(name, "", {
222
+ path,
223
+ maxAge: 0,
224
+ secure
225
+ });
226
+ }
227
+ var SessionTooLargeError = class extends Error {
228
+ bytes;
229
+ constructor(bytes) {
230
+ super(`[passflow] the sealed session is ${String(bytes)} bytes, over the ${String(CHUNK_SIZE * 3)}-byte limit`);
231
+ this.name = "SessionTooLargeError";
232
+ this.bytes = bytes;
233
+ }
234
+ };
235
+ /**
236
+ * The `Set-Cookie` values that store `value` as the session, and the pairs a replaced `Cookie` header carries.
237
+ * Every session cookie of this scheme in the incoming request that is not written now is expired, however many
238
+ * there are. Throws `SessionTooLargeError` when the value needs more than `MAX_CHUNKS` chunks.
239
+ */
240
+ function writeSessionCookies(value, cookieHeader, options) {
241
+ const pairs = [];
242
+ const baseName = sessionCookieName(options.secure);
243
+ if (value.length <= 3500) pairs.push([baseName, value]);
244
+ else {
245
+ const count = Math.ceil(value.length / CHUNK_SIZE);
246
+ if (count > 3) throw new SessionTooLargeError(value.length);
247
+ for (let i = 0; i < count; i++) pairs.push([`${baseName}.${String(i)}`, value.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE)]);
248
+ }
249
+ const cookie = {
250
+ path: "/",
251
+ maxAge: options.maxAge,
252
+ secure: options.secure
253
+ };
254
+ const setCookies = pairs.map(([name, chunk]) => serializeCookie(name, chunk, cookie));
255
+ const written = new Set(pairs.map(([name]) => name));
256
+ setCookies.push(...expireSessionCookies(cookieHeader, options.secure, written));
257
+ return {
258
+ setCookies,
259
+ pairs
260
+ };
261
+ }
262
+ /**
263
+ * `Set-Cookie` values that expire every session cookie of this scheme in the request, except the names in
264
+ * `keep`. The other scheme's names are left alone: they are never read under this scheme.
265
+ */
266
+ function expireSessionCookies(cookieHeader, secure, keep = /* @__PURE__ */ new Set()) {
267
+ const names = /* @__PURE__ */ new Set();
268
+ for (const [name] of parseCookies(cookieHeader)) if (isSessionCookieName(name, secure) && !keep.has(name)) names.add(name);
269
+ return [...names].map((name) => expireCookie(name, "/", secure));
270
+ }
271
+ /**
272
+ * The `Cookie` header with every session cookie, of either scheme, replaced by `pairs`. Other cookies keep
273
+ * their order.
274
+ */
275
+ function replaceSessionCookies(cookieHeader, pairs) {
276
+ return [...parseCookies(cookieHeader).filter(([name]) => !isAnySessionCookieName(name)), ...pairs].map(([name, value]) => `${name}=${value}`).join("; ");
277
+ }
278
+ // src/session/oidc.ts
279
+ const SESSION_ENDING_ERRORS = /* @__PURE__ */ new Set(["invalid_grant", "invalid_client"]);
280
+ /**
281
+ * Errors a call to `fetch` rejected with. `fetch` rejects only when no answer came back, whatever the runtime
282
+ * names the error, so each of these counts as an unavailable issuer.
283
+ */
284
+ const fetchRejections = /* @__PURE__ */ new WeakSet();
285
+ /** `fetch` (the configured one, else the global one), with its rejections recorded in `fetchRejections`. */
286
+ function recordingFetch(custom) {
287
+ return async (input, init) => {
288
+ try {
289
+ return await (custom ?? fetch)(input, init);
290
+ } catch (error) {
291
+ if (typeof error === "object" && error !== null) fetchRejections.add(error);
292
+ throw error;
293
+ }
294
+ };
295
+ }
296
+ /** How long one call to the issuer may take before it is abandoned. */
297
+ const ISSUER_TIMEOUT_MS = 1e4;
298
+ /**
299
+ * True when the issuer could not serve a call: no answer came back (the host is unreachable, its name doesn't
300
+ * resolve, the connection is refused or dropped, or the call timed out), or the answer was a 5xx. Any error
301
+ * `fetch` rejected with counts, whatever its name or message. Outside `fetch`, the runtime reports a stalled body
302
+ * as a `TypeError` (undici's "terminated", a browser runtime's "NetworkError") or as a `TimeoutError` or
303
+ * `AbortError`. oauth4webapi wraps some of these: a body that stalls after the headers arrived becomes an
304
+ * `OperationProcessingError` whose `cause` is the timeout, and a 5xx comes as an error with a `status`
305
+ * (`ResponseBodyError`, `WWWAuthenticateChallengeError`) or with the `Response` as its `cause`. So the error and
306
+ * its causes are checked, a few levels deep. Malformed JSON and an OAuth error answer below 500 are neither.
307
+ */
308
+ function isIssuerUnavailable(error, depth = 0) {
309
+ if (typeof error !== "object" || error === null || depth > 3) return false;
310
+ if (fetchRejections.has(error)) return true;
311
+ const { name, message, status, cause } = error;
312
+ if (name === "TimeoutError" || name === "AbortError") return true;
313
+ if (error instanceof TypeError && typeof message === "string") {
314
+ if (/fetch failed|failed to fetch|networkerror|network error|^terminated$/i.test(message)) return true;
315
+ }
316
+ if (typeof status === "number" && status >= 500) return true;
317
+ return isIssuerUnavailable(cause, depth + 1);
318
+ }
319
+ /** The `exp` of a JWT, read without verifying it, or `undefined`. Only used to time the session. */
320
+ function unverifiedExp(token) {
321
+ if (typeof token !== "string") return;
322
+ try {
323
+ const { exp } = decodeJwt(token);
324
+ return typeof exp === "number" && Number.isFinite(exp) ? exp : void 0;
325
+ } catch {
326
+ return;
327
+ }
328
+ }
329
+ /**
330
+ * True when a token endpoint error says the session is over, and not that the call merely failed. An unavailable
331
+ * issuer (a 5xx, a timeout, no answer) never ends it, whatever OAuth error the answer carries.
332
+ */
333
+ function endsSession(error) {
334
+ if (isIssuerUnavailable(error)) return false;
335
+ if (error instanceof oauth.ResponseBodyError) return SESSION_ENDING_ERRORS.has(error.error);
336
+ if (error instanceof oauth.WWWAuthenticateChallengeError) return error.cause.some((challenge) => SESSION_ENDING_ERRORS.has(String(challenge.parameters.error)));
337
+ return false;
338
+ }
339
+ /**
340
+ * The OpenID Connect calls the session makes, through oauth4webapi: discovery, the authorization request, the
341
+ * code grant with the client secret and PKCE, refresh, revocation and UserInfo. `http://` is allowed only when
342
+ * the issuer's host is loopback.
343
+ */
344
+ function createOidcClient(config, nowSeconds) {
345
+ const requestOptions = {
346
+ [oauth.customFetch]: recordingFetch(config.fetch),
347
+ signal: () => AbortSignal.timeout(ISSUER_TIMEOUT_MS)
348
+ };
349
+ if (config.issuerIsLoopback) requestOptions[oauth.allowInsecureRequests] = true;
350
+ const clientAuth = oauth.ClientSecretPost(config.clientSecret);
351
+ const redirectUri = `${config.baseUrl}${config.routes.callback}`;
352
+ let discovery;
353
+ /** Built per call, so that oauth4webapi's clock follows the configured one. */
354
+ const client = () => ({
355
+ client_id: config.clientId,
356
+ [oauth.clockSkew]: nowSeconds() - Math.floor(Date.now() / 1e3)
357
+ });
358
+ /** Discovery runs once; a failed attempt is forgotten, so the next request tries again. */
359
+ const server = () => {
360
+ if (discovery === void 0) {
361
+ const pending = oauth.discoveryRequest(config.issuer, {
362
+ ...requestOptions,
363
+ algorithm: "oidc"
364
+ }).then((response) => oauth.processDiscoveryResponse(config.issuer, response));
365
+ discovery = pending;
366
+ pending.catch(() => {
367
+ if (discovery === pending) discovery = void 0;
368
+ });
369
+ }
370
+ return discovery;
371
+ };
372
+ /** The access token's expiry: `expires_in` when given, else the token's own `exp`. */
373
+ const accessTokenExpiry = (response) => {
374
+ if (typeof response.expires_in === "number" && Number.isFinite(response.expires_in)) return nowSeconds() + Math.floor(response.expires_in);
375
+ return unverifiedExp(response.access_token);
376
+ };
377
+ return {
378
+ redirectUri,
379
+ async authorizationRequest() {
380
+ const as = await server();
381
+ if (as.authorization_endpoint === void 0) throw new Error("[passflow] the issuer has no authorization endpoint");
382
+ const codeVerifier = oauth.generateRandomCodeVerifier();
383
+ const state = oauth.generateRandomState();
384
+ const nonce = oauth.generateRandomNonce();
385
+ const url = new URL(as.authorization_endpoint);
386
+ url.search = new URLSearchParams({
387
+ client_id: config.clientId,
388
+ redirect_uri: redirectUri,
389
+ response_type: "code",
390
+ scope: config.scopes.join(" "),
391
+ state,
392
+ nonce,
393
+ code_challenge: await oauth.calculatePKCECodeChallenge(codeVerifier),
394
+ code_challenge_method: "S256"
395
+ }).toString();
396
+ return {
397
+ url: url.href,
398
+ state,
399
+ nonce,
400
+ codeVerifier
401
+ };
402
+ },
403
+ /**
404
+ * Checks `state`, redeems the code, validates the ID token (iss, aud, exp, nonce) and reads UserInfo, whose
405
+ * `sub` must equal the ID token's. Throws on any failure, a refresh token without a numeric `exp` included.
406
+ * The ID token is returned too, for sign-out's `id_token_hint`.
407
+ */
408
+ async signIn(callbackUrl, transaction) {
409
+ const as = await server();
410
+ const params = oauth.validateAuthResponse(as, client(), callbackUrl, transaction.state);
411
+ const response = await oauth.authorizationCodeGrantRequest(as, client(), clientAuth, params, redirectUri, transaction.codeVerifier, requestOptions);
412
+ const result = await oauth.processAuthorizationCodeResponse(as, client(), response, {
413
+ expectedNonce: transaction.nonce,
414
+ requireIdToken: true
415
+ });
416
+ const claims = oauth.getValidatedIdTokenClaims(result);
417
+ if (claims === void 0 || result.id_token === void 0) throw new Error("[passflow] the token response has no ID token");
418
+ const accessTokenExpiresAt = accessTokenExpiry(result);
419
+ const refreshTokenExpiresAt = unverifiedExp(result.refresh_token);
420
+ if (accessTokenExpiresAt === void 0 || result.refresh_token === void 0 || refreshTokenExpiresAt === void 0) throw new Error("[passflow] the token response needs an access token expiry and a refresh token with exp");
421
+ const userInfo = await oauth.processUserInfoResponse(as, client(), claims.sub, await oauth.userInfoRequest(as, client(), result.access_token, requestOptions));
422
+ return {
423
+ accessToken: result.access_token,
424
+ accessTokenExpiresAt,
425
+ refreshToken: result.refresh_token,
426
+ refreshTokenExpiresAt,
427
+ idToken: result.id_token,
428
+ userInfo
429
+ };
430
+ },
431
+ /**
432
+ * Redeems the refresh token. A response with no new refresh token keeps the old one and its `exp`; a new
433
+ * one without a numeric `exp` counts as `failed`. An ID token in the response is returned to replace the kept one.
434
+ */
435
+ async refresh(refreshToken, refreshTokenExpiresAt) {
436
+ try {
437
+ const as = await server();
438
+ const response = await oauth.refreshTokenGrantRequest(as, client(), clientAuth, refreshToken, requestOptions);
439
+ const result = await oauth.processRefreshTokenResponse(as, client(), response);
440
+ const accessTokenExpiresAt = accessTokenExpiry(result);
441
+ const nextRefreshToken = result.refresh_token ?? refreshToken;
442
+ const nextExpiresAt = result.refresh_token === void 0 ? refreshTokenExpiresAt : unverifiedExp(result.refresh_token);
443
+ if (accessTokenExpiresAt === void 0 || nextExpiresAt === void 0) return { kind: "failed" };
444
+ const tokens = {
445
+ accessToken: result.access_token,
446
+ accessTokenExpiresAt,
447
+ refreshToken: nextRefreshToken,
448
+ refreshTokenExpiresAt: nextExpiresAt
449
+ };
450
+ if (result.id_token !== void 0) tokens.idToken = result.id_token;
451
+ return {
452
+ kind: "refreshed",
453
+ tokens
454
+ };
455
+ } catch (error) {
456
+ return endsSession(error) ? { kind: "ended" } : { kind: "failed" };
457
+ }
458
+ },
459
+ /** Revokes the refresh token. The result is ignored: sign-out goes on either way. */
460
+ async revoke(refreshToken) {
461
+ try {
462
+ const as = await server();
463
+ await oauth.revocationRequest(as, client(), clientAuth, refreshToken, requestOptions);
464
+ } catch {}
465
+ },
466
+ /**
467
+ * Passflow's end-session URL with `client_id`, the app's home page as the return address and, when the
468
+ * session holds one, the ID token as `id_token_hint`: Passflow then ends its session with no confirmation
469
+ * page. Without a hint, Passflow asks the user to confirm. `undefined` when discovery fails or names no
470
+ * end-session endpoint.
471
+ */
472
+ async endSessionUrl(idTokenHint) {
473
+ try {
474
+ const as = await server();
475
+ if (as.end_session_endpoint === void 0) return;
476
+ const url = new URL(as.end_session_endpoint);
477
+ const params = new URLSearchParams();
478
+ if (idTokenHint !== void 0) params.set("id_token_hint", idTokenHint);
479
+ params.set("client_id", config.clientId);
480
+ params.set("post_logout_redirect_uri", `${config.baseUrl}/`);
481
+ url.search = params.toString();
482
+ return url.href;
483
+ } catch {
484
+ return;
485
+ }
486
+ }
487
+ };
488
+ }
489
+ // src/session/seal.ts
490
+ /** HKDF `info` for the session cookie's key. */
491
+ const SESSION_KEY_INFO = "passflow/session/v1";
492
+ /** HKDF `info` for the transaction cookie's key. A sealed transaction never opens as a session, or back. */
493
+ const TRANSACTION_KEY_INFO = "passflow/txn/v1";
494
+ const encoder = new TextEncoder();
495
+ /** A 256-bit key derived from the app's secret with HKDF-SHA256, empty salt, and `info`. WebCrypto only. */
496
+ async function deriveKey(secret, info) {
497
+ const base = await crypto.subtle.importKey("raw", encoder.encode(secret), "HKDF", false, ["deriveBits"]);
498
+ const bits = await crypto.subtle.deriveBits({
499
+ name: "HKDF",
500
+ hash: "SHA-256",
501
+ salt: /* @__PURE__ */ new Uint8Array(),
502
+ info: encoder.encode(info)
503
+ }, base, 256);
504
+ return new Uint8Array(bits);
505
+ }
506
+ /** A compact JWE, `dir` with `A256GCM`: encrypted and authenticated with `key`. */
507
+ function seal(payload, key) {
508
+ return new EncryptJWT(payload).setProtectedHeader({
509
+ alg: "dir",
510
+ enc: "A256GCM"
511
+ }).encrypt(key);
512
+ }
513
+ /**
514
+ * The payload of a value `seal` made with `key`, or `null` for anything else: a tampered value, another key,
515
+ * another algorithm, or an `exp` that has passed at `now` (in seconds).
516
+ */
517
+ async function open(value, key, now) {
518
+ try {
519
+ const { payload } = await jwtDecrypt(value, key, {
520
+ keyManagementAlgorithms: ["dir"],
521
+ contentEncryptionAlgorithms: ["A256GCM"],
522
+ currentDate: /* @__PURE__ */ new Date(now * 1e3),
523
+ requiredClaims: ["exp"],
524
+ clockTolerance: 0
525
+ });
526
+ return typeof payload.exp === "number" && payload.exp > now ? payload : null;
527
+ } catch {
528
+ return null;
529
+ }
530
+ }
531
+ // src/session/manager.ts
532
+ /**
533
+ * A refresh starts once the access token has this many seconds left, or fewer, and at most half its lifetime:
534
+ * a one-minute token is then used for 30 s instead of refreshing on every request.
535
+ */
536
+ const REFRESH_MARGIN = 60;
537
+ /** How long a sign-in may take, from `/auth/login` to the callback. */
538
+ const TRANSACTION_LIFETIME = 600;
539
+ const NO_STORE = "no-store";
540
+ const RETURN_TO_BASE = "https://return-to.invalid";
541
+ const CONTROL = /[\u0000-\u001f\u007f]/;
542
+ /** A path that starts with exactly one `/` and holds no `\` or control character. */
543
+ function isPlainPath(path) {
544
+ return path.startsWith("/") && !path.startsWith("//") && !path.includes("\\") && !CONTROL.test(path);
545
+ }
546
+ /**
547
+ * `returnTo` when it is a relative path on the app's own origin, else `/`. The path is normalised first (dot
548
+ * segments removed, as the browser would), and the result is checked again, so `/..//evil.com`, which normalises
549
+ * to `//evil.com`, is refused. Checked without the config, so a page can build a sign-in link before the
550
+ * environment is read.
551
+ */
552
+ function safeReturnTo(returnTo) {
553
+ if (typeof returnTo !== "string" || !isPlainPath(returnTo)) return "/";
554
+ let url;
555
+ try {
556
+ url = new URL(returnTo, RETURN_TO_BASE);
557
+ } catch {
558
+ return "/";
559
+ }
560
+ if (url.origin !== RETURN_TO_BASE) return "/";
561
+ const normalised = `${url.pathname}${url.search}${url.hash}`;
562
+ if (!isPlainPath(normalised)) return "/";
563
+ try {
564
+ return new URL(normalised, RETURN_TO_BASE).origin === RETURN_TO_BASE ? normalised : "/";
565
+ } catch {
566
+ return "/";
567
+ }
568
+ }
569
+ function isRecord(value) {
570
+ return typeof value === "object" && value !== null && !Array.isArray(value);
571
+ }
572
+ function isTime(value) {
573
+ return typeof value === "number" && Number.isFinite(value);
574
+ }
575
+ /** True when a sealed value was made for this issuer and client: one sealed for another reads as absent. */
576
+ function isBound(payload, binding) {
577
+ return payload.iss === binding.iss && payload.cid === binding.cid;
578
+ }
579
+ function asSessionPayload(payload, binding) {
580
+ if (payload === null || !isBound(payload, binding) || payload.v !== 1 || !isRecord(payload.user) || typeof payload.user.sub !== "string" || typeof payload.at !== "string" || !isTime(payload.atExp) || !isTime(payload.atIat) || typeof payload.rt !== "string" || payload.it !== void 0 && typeof payload.it !== "string" || !isTime(payload.iat) || !isTime(payload.exp)) return null;
581
+ return payload;
582
+ }
583
+ function asTransactionPayload(payload, binding) {
584
+ if (payload === null || !isBound(payload, binding) || typeof payload.state !== "string" || typeof payload.nonce !== "string" || typeof payload.codeVerifier !== "string" || typeof payload.returnTo !== "string" || !isTime(payload.exp)) return null;
585
+ return payload;
586
+ }
587
+ /**
588
+ * The user from UserInfo: `email_verified` becomes `emailVerified`; a claim of the wrong type is dropped, and so
589
+ * is every claim `PassflowUser` doesn't name.
590
+ */
591
+ function toUser(info) {
592
+ const { sub, email, email_verified, name, picture } = info;
593
+ const user = { sub };
594
+ if (typeof email === "string") user.email = email;
595
+ if (typeof email_verified === "boolean") user.emailVerified = email_verified;
596
+ if (typeof name === "string") user.name = name;
597
+ if (typeof picture === "string") user.picture = picture;
598
+ return user;
599
+ }
600
+ const toSession = (payload) => ({
601
+ user: payload.user,
602
+ expiresAt: payload.exp
603
+ });
604
+ const escapeHtml = (text) => text.replace(/[&<>"']/g, (c) => `&#${String(c.charCodeAt(0))};`);
605
+ /**
606
+ * 503 for a sign-in the issuer could not serve: no answer (a network error or a timeout), or a 5xx. No retry:
607
+ * the user tries again later.
608
+ */
609
+ function issuerUnreachable(setCookies) {
610
+ const headers = new Headers({
611
+ "Content-Type": "text/plain; charset=utf-8",
612
+ "Cache-Control": NO_STORE
613
+ });
614
+ for (const cookie of setCookies) headers.append("Set-Cookie", cookie);
615
+ return new Response("Sign-in is unavailable: the Passflow issuer could not be reached. Try again later.", {
616
+ status: 503,
617
+ headers
618
+ });
619
+ }
620
+ /**
621
+ * False for a prefetch the request declares (`Sec-Purpose`, `Purpose`, or `Next-Router-Prefetch` where the
622
+ * framework passes it on; the Next.js proxy may strip it, so sign-out links must be plain anchors) and for a
623
+ * request another site started (`Sec-Fetch-Site` other than `same-origin` or `none`). A browser that sends no
624
+ * `Sec-Fetch-Site` counts as deliberate.
625
+ */
626
+ function isDeliberateNavigation(request) {
627
+ const purpose = `${request.headers.get("sec-purpose") ?? ""} ${request.headers.get("purpose") ?? ""}`;
628
+ if (/prefetch/i.test(purpose) || request.headers.has("next-router-prefetch")) return false;
629
+ const site = request.headers.get("sec-fetch-site");
630
+ return site === null || site === "same-origin" || site === "none";
631
+ }
632
+ function redirect(location, setCookies) {
633
+ const headers = new Headers({
634
+ Location: location,
635
+ "Cache-Control": NO_STORE
636
+ });
637
+ for (const cookie of setCookies) headers.append("Set-Cookie", cookie);
638
+ return new Response(null, {
639
+ status: 302,
640
+ headers
641
+ });
642
+ }
643
+ /**
644
+ * The server-side sign-in session for a web app: the auth routes, an encrypted and chunked session cookie,
645
+ * and refresh when the access token is due. Framework-neutral: it reads web `Request`s and returns web
646
+ * `Response`s. The config is checked on first use and throws `TypeError` naming what is missing.
647
+ */
648
+ function createSessionManager(config) {
649
+ let resolved;
650
+ const ready = () => {
651
+ if (resolved === void 0) {
652
+ const checked = resolveConfig(config);
653
+ const nowSeconds = () => Math.floor(checked.now().getTime() / 1e3);
654
+ resolved = {
655
+ config: checked,
656
+ binding: {
657
+ iss: checked.issuer.href,
658
+ cid: checked.clientId
659
+ },
660
+ oidc: createOidcClient(checked, nowSeconds),
661
+ sessionKey: deriveKey(checked.secret, SESSION_KEY_INFO),
662
+ transactionKey: deriveKey(checked.secret, TRANSACTION_KEY_INFO)
663
+ };
664
+ }
665
+ return resolved;
666
+ };
667
+ const now = () => Math.floor(ready().config.now().getTime() / 1e3);
668
+ /**
669
+ * A same-origin path as an absolute URL on `baseUrl`. Redirects are absolute because some frameworks (the
670
+ * Next.js proxy) refuse a relative `Location`. `path` has passed `safeReturnTo`, so it stays on the app.
671
+ */
672
+ const appUrl = (path) => new URL(path, ready().config.baseUrl).href;
673
+ async function readSession(cookieHeader) {
674
+ const value = readSessionValue(cookieHeader, ready().config.secure);
675
+ if (value === void 0) return null;
676
+ const { sessionKey, binding } = ready();
677
+ return asSessionPayload(await open(value, await sessionKey, now()), binding);
678
+ }
679
+ /** Seals `payload` into session cookies. Throws `SessionTooLargeError` over the chunk limit. */
680
+ async function writeSession(payload, cookieHeader) {
681
+ const { config: c, sessionKey } = ready();
682
+ return writeSessionCookies(await seal(payload, await sessionKey), cookieHeader, {
683
+ maxAge: Math.min(payload.exp - now(), MAX_COOKIE_AGE),
684
+ secure: c.secure
685
+ });
686
+ }
687
+ function signInFailed(setCookies) {
688
+ const href = escapeHtml(ready().config.routes.login);
689
+ const headers = new Headers({
690
+ "Content-Type": "text/html; charset=utf-8",
691
+ "Cache-Control": NO_STORE
692
+ });
693
+ for (const cookie of setCookies) headers.append("Set-Cookie", cookie);
694
+ const body = `<!doctype html><title>Sign-in failed</title><p>Sign-in failed. Try again.</p><p><a href="${href}">Sign in</a></p>`;
695
+ return new Response(body, {
696
+ status: 400,
697
+ headers
698
+ });
699
+ }
700
+ async function login(url) {
701
+ const { config: c, binding, oidc, transactionKey } = ready();
702
+ let request;
703
+ try {
704
+ request = await oidc.authorizationRequest();
705
+ } catch (error) {
706
+ if (isIssuerUnavailable(error)) return issuerUnreachable([]);
707
+ throw error;
708
+ }
709
+ const sealed = await seal({
710
+ ...binding,
711
+ state: request.state,
712
+ nonce: request.nonce,
713
+ codeVerifier: request.codeVerifier,
714
+ returnTo: safeReturnTo(url.searchParams.get("returnTo")),
715
+ exp: now() + TRANSACTION_LIFETIME
716
+ }, await transactionKey);
717
+ const cookie = serializeCookie(transactionCookieName(c.secure), sealed, {
718
+ path: "/",
719
+ maxAge: TRANSACTION_LIFETIME,
720
+ secure: c.secure
721
+ });
722
+ return redirect(request.url, [cookie]);
723
+ }
724
+ async function callback(url, cookieHeader) {
725
+ const { config: c, binding, oidc, transactionKey } = ready();
726
+ const transactionName = transactionCookieName(c.secure);
727
+ const clearTransaction = [expireCookie(transactionName, "/", c.secure)];
728
+ if (!c.secure) clearTransaction.push(expireCookie(transactionName, c.routes.callback, false));
729
+ try {
730
+ const sealed = readCookie(cookieHeader, transactionName);
731
+ const transaction = sealed === void 0 ? null : asTransactionPayload(await open(sealed, await transactionKey, now()), binding);
732
+ if (transaction === null) return signInFailed(clearTransaction);
733
+ const result = await oidc.signIn(url, transaction);
734
+ const payload = {
735
+ ...binding,
736
+ v: 1,
737
+ user: toUser(result.userInfo),
738
+ at: result.accessToken,
739
+ atExp: result.accessTokenExpiresAt,
740
+ atIat: now(),
741
+ rt: result.refreshToken,
742
+ it: result.idToken,
743
+ iat: now(),
744
+ exp: result.refreshTokenExpiresAt
745
+ };
746
+ if (payload.exp <= payload.iat) return signInFailed(clearTransaction);
747
+ const { setCookies } = await writeSession(payload, cookieHeader);
748
+ return redirect(appUrl(safeReturnTo(transaction.returnTo)), [...setCookies, ...clearTransaction]);
749
+ } catch (error) {
750
+ if (isIssuerUnavailable(error)) return issuerUnreachable(clearTransaction);
751
+ if (error instanceof SessionTooLargeError) console.error(`[passflow] sign-in failed: ${error.message}`);
752
+ return signInFailed(clearTransaction);
753
+ }
754
+ }
755
+ async function logout(cookieHeader) {
756
+ const { config: c, oidc } = ready();
757
+ const payload = await readSession(cookieHeader);
758
+ if (payload !== null) await oidc.revoke(payload.rt);
759
+ return redirect(await oidc.endSessionUrl(payload?.it) ?? appUrl("/"), [...expireSessionCookies(cookieHeader, c.secure), expireCookie(transactionCookieName(c.secure), "/", c.secure)]);
760
+ }
761
+ /** Any other path: continues, refreshing first when the access token is due. */
762
+ async function proceed(cookieHeader) {
763
+ const payload = await readSession(cookieHeader);
764
+ if (payload === null) return {
765
+ kind: "continue",
766
+ session: null,
767
+ setCookies: []
768
+ };
769
+ const margin = Math.min(REFRESH_MARGIN, Math.max(0, Math.floor((payload.atExp - payload.atIat) / 2)));
770
+ if (payload.atExp - margin > now()) return {
771
+ kind: "continue",
772
+ session: toSession(payload),
773
+ setCookies: []
774
+ };
775
+ const { config: c, oidc } = ready();
776
+ const signedOut = replaceSessionCookies(cookieHeader, []);
777
+ const result = await oidc.refresh(payload.rt, payload.exp);
778
+ if (result.kind === "ended") return {
779
+ kind: "continue",
780
+ session: null,
781
+ setCookies: expireSessionCookies(cookieHeader, c.secure),
782
+ cookieHeader: signedOut
783
+ };
784
+ if (result.kind === "failed") {
785
+ const at = now();
786
+ if (payload.exp > at && payload.atExp > at) return {
787
+ kind: "continue",
788
+ session: toSession(payload),
789
+ setCookies: []
790
+ };
791
+ return {
792
+ kind: "continue",
793
+ session: null,
794
+ setCookies: [],
795
+ cookieHeader: signedOut
796
+ };
797
+ }
798
+ const next = {
799
+ ...payload,
800
+ at: result.tokens.accessToken,
801
+ atExp: result.tokens.accessTokenExpiresAt,
802
+ atIat: now(),
803
+ rt: result.tokens.refreshToken,
804
+ exp: result.tokens.refreshTokenExpiresAt
805
+ };
806
+ if (result.tokens.idToken !== void 0) next.it = result.tokens.idToken;
807
+ if (next.exp <= now()) return {
808
+ kind: "continue",
809
+ session: null,
810
+ setCookies: [],
811
+ cookieHeader: signedOut
812
+ };
813
+ try {
814
+ const { setCookies, pairs } = await writeSession(next, cookieHeader);
815
+ return {
816
+ kind: "continue",
817
+ session: toSession(next),
818
+ setCookies,
819
+ cookieHeader: replaceSessionCookies(cookieHeader, pairs)
820
+ };
821
+ } catch (error) {
822
+ if (error instanceof SessionTooLargeError) console.error(`[passflow] refresh could not store the session: ${error.message}`);
823
+ return {
824
+ kind: "continue",
825
+ session: null,
826
+ setCookies: [],
827
+ cookieHeader: signedOut
828
+ };
829
+ }
830
+ }
831
+ return {
832
+ async handle(request) {
833
+ const url = new URL(request.url);
834
+ const cookieHeader = request.headers.get("cookie");
835
+ const { routes } = ready().config;
836
+ const route = [
837
+ routes.login,
838
+ routes.callback,
839
+ routes.logout
840
+ ].find((path) => url.pathname === path || url.pathname === `${path}/`);
841
+ if (route === void 0) return proceed(cookieHeader);
842
+ if (request.method !== "GET") return {
843
+ kind: "response",
844
+ response: new Response(null, {
845
+ status: 405,
846
+ headers: {
847
+ Allow: "GET",
848
+ "Cache-Control": NO_STORE
849
+ }
850
+ })
851
+ };
852
+ if (route === routes.login) return {
853
+ kind: "response",
854
+ response: await login(url)
855
+ };
856
+ if (route === routes.callback) return {
857
+ kind: "response",
858
+ response: await callback(url, cookieHeader)
859
+ };
860
+ if (!isDeliberateNavigation(request)) return {
861
+ kind: "response",
862
+ response: new Response(null, {
863
+ status: 204,
864
+ headers: { "Cache-Control": NO_STORE }
865
+ })
866
+ };
867
+ return {
868
+ kind: "response",
869
+ response: await logout(cookieHeader)
870
+ };
871
+ },
872
+ async getSession(cookieHeader) {
873
+ const payload = await readSession(cookieHeader);
874
+ return payload !== null && payload.atExp > now() ? toSession(payload) : null;
875
+ },
876
+ async getAccessToken(cookieHeader) {
877
+ const payload = await readSession(cookieHeader);
878
+ return payload !== null && payload.atExp > now() ? payload.at : null;
879
+ },
880
+ loginPath(returnTo) {
881
+ return `${config.routes?.login ?? DEFAULT_ROUTES.login}?returnTo=${encodeURIComponent(safeReturnTo(returnTo))}`;
882
+ },
883
+ isSameOrigin(request) {
884
+ const origin = request.headers.get("origin");
885
+ if (origin !== null) return origin === ready().config.baseUrl;
886
+ const site = request.headers.get("sec-fetch-site");
887
+ return site === "same-origin" || site === "none";
888
+ },
889
+ hasSessionCookie,
890
+ unauthorized() {
891
+ return new Response(null, {
892
+ status: 401,
893
+ headers: { "Cache-Control": NO_STORE }
894
+ });
895
+ }
896
+ };
897
+ }
898
+ export { configFromEnv, createSessionManager, hasSessionCookie };