@softistx/alxia-react-router 0.89.5 → 0.90.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.
Files changed (46) hide show
  1. package/README.md +30 -1
  2. package/dist/chunks/{index-1nw5yeek.js → index-qkyt0bka.js} +3 -3
  3. package/dist/chunks/{index-1nw5yeek.js.map → index-qkyt0bka.js.map} +1 -1
  4. package/dist/chunks/index-w61bjnkw.js +1019 -0
  5. package/dist/chunks/index-w61bjnkw.js.map +27 -0
  6. package/dist/clavix/api-url.d.ts +43 -0
  7. package/dist/clavix/api-url.d.ts.map +1 -0
  8. package/dist/clavix/client.d.ts +22 -0
  9. package/dist/clavix/client.d.ts.map +1 -0
  10. package/dist/clavix/core.d.ts +39 -0
  11. package/dist/clavix/core.d.ts.map +1 -0
  12. package/dist/clavix/env.d.ts +26 -0
  13. package/dist/clavix/env.d.ts.map +1 -0
  14. package/dist/clavix/index.d.ts +19 -0
  15. package/dist/clavix/index.d.ts.map +1 -0
  16. package/dist/clavix/index.js +673 -0
  17. package/dist/clavix/index.js.map +22 -0
  18. package/dist/clavix/landing.d.ts +67 -0
  19. package/dist/clavix/landing.d.ts.map +1 -0
  20. package/dist/clavix/messages.d.ts +53 -0
  21. package/dist/clavix/messages.d.ts.map +1 -0
  22. package/dist/clavix/notice.d.ts +32 -0
  23. package/dist/clavix/notice.d.ts.map +1 -0
  24. package/dist/clavix/refusal.d.ts +29 -0
  25. package/dist/clavix/refusal.d.ts.map +1 -0
  26. package/dist/clavix/relay.d.ts +41 -0
  27. package/dist/clavix/relay.d.ts.map +1 -0
  28. package/dist/clavix/routes.d.ts +5 -0
  29. package/dist/clavix/routes.d.ts.map +1 -0
  30. package/dist/clavix/send.d.ts +32 -0
  31. package/dist/clavix/send.d.ts.map +1 -0
  32. package/dist/clavix/state.d.ts +20 -0
  33. package/dist/clavix/state.d.ts.map +1 -0
  34. package/dist/clavix/types.d.ts +97 -0
  35. package/dist/clavix/types.d.ts.map +1 -0
  36. package/dist/clavix/viewer.d.ts +12 -0
  37. package/dist/clavix/viewer.d.ts.map +1 -0
  38. package/dist/oidc/index.js +23 -1025
  39. package/dist/oidc/index.js.map +3 -21
  40. package/dist/session/index.js +1 -1
  41. package/docs/README.md +2 -1
  42. package/docs/guide/clavix.md +332 -0
  43. package/docs/guide/oidc.md +3 -0
  44. package/docs/roadmap.md +6 -0
  45. package/docs/troubleshooting.md +41 -0
  46. package/package.json +8 -2
@@ -0,0 +1,1019 @@
1
+ import {
2
+ siteCheck
3
+ } from "./index-6zx9dfvs.js";
4
+ import {
5
+ sessionCookies2
6
+ } from "./index-qkyt0bka.js";
7
+ import {
8
+ safeNext2,
9
+ sitePath
10
+ } from "./index-t68hwhz1.js";
11
+
12
+ // src/oidc/errors.ts
13
+ class OidcError2 extends Error {
14
+ code;
15
+ headers;
16
+ name = "OidcError";
17
+ constructor(code, message, headers = new Headers, options) {
18
+ super(message, options);
19
+ this.code = code;
20
+ this.headers = headers;
21
+ }
22
+ }
23
+
24
+ // src/oidc/flow.ts
25
+ import {
26
+ createLocalJWKSet,
27
+ decodeJwt,
28
+ errors as joseErrors,
29
+ jwtVerify
30
+ } from "jose";
31
+
32
+ // src/oidc/dpop.ts
33
+ import {
34
+ calculateJwkThumbprint,
35
+ exportJWK,
36
+ generateKeyPair,
37
+ importJWK,
38
+ SignJWT
39
+ } from "jose";
40
+
41
+ // src/oidc/seal.ts
42
+ var encoder = new TextEncoder;
43
+ var decoder = new TextDecoder;
44
+ var toBase64Url = (bytes) => {
45
+ let binary = "";
46
+ for (const byte of bytes)
47
+ binary += String.fromCharCode(byte);
48
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
49
+ };
50
+ var fromBase64Url = (text) => {
51
+ const padded = text.replaceAll("-", "+").replaceAll("_", "/");
52
+ const binary = atob(padded + "=".repeat((4 - padded.length % 4) % 4));
53
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
54
+ };
55
+ var randomToken = (bytes = 32) => toBase64Url(crypto.getRandomValues(new Uint8Array(bytes)));
56
+ function sameText(a, b) {
57
+ const left = encoder.encode(a);
58
+ const right = encoder.encode(b);
59
+ let difference = left.length ^ right.length;
60
+ for (let index = 0;index < Math.max(left.length, right.length); index++) {
61
+ difference |= (left[index] ?? 0) ^ (right[index] ?? 0);
62
+ }
63
+ return difference === 0;
64
+ }
65
+ async function s256(verifier) {
66
+ return toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(verifier))));
67
+ }
68
+ function sealer(secret, purpose) {
69
+ const key = crypto.subtle.digest("SHA-256", encoder.encode(`alxia-oidc/${purpose}/${secret}`)).then((raw) => crypto.subtle.importKey("raw", raw, "AES-GCM", false, [
70
+ "encrypt",
71
+ "decrypt"
72
+ ]));
73
+ const additionalData = encoder.encode(purpose);
74
+ return {
75
+ async seal(value) {
76
+ const iv = crypto.getRandomValues(new Uint8Array(12));
77
+ const data = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData }, await key, encoder.encode(JSON.stringify(value))));
78
+ const out = new Uint8Array(iv.length + data.length);
79
+ out.set(iv);
80
+ out.set(data, iv.length);
81
+ return toBase64Url(out);
82
+ },
83
+ async open(text) {
84
+ try {
85
+ const bytes = fromBase64Url(text);
86
+ if (bytes.length < 29)
87
+ return null;
88
+ const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12), additionalData }, await key, bytes.slice(12));
89
+ return JSON.parse(decoder.decode(plain));
90
+ } catch {
91
+ return null;
92
+ }
93
+ }
94
+ };
95
+ }
96
+
97
+ // src/oidc/dpop.ts
98
+ var encoder2 = new TextEncoder;
99
+ async function generateDpopKey2(alg = "ES256") {
100
+ const { privateKey } = await generateKeyPair(alg, { extractable: true });
101
+ return {
102
+ alg,
103
+ jwk: pick(await exportJWK(privateKey), ["kty", "crv", "x", "y", "d"])
104
+ };
105
+ }
106
+ var pick = (jwk, names) => Object.fromEntries(names.flatMap((name) => jwk[name] === undefined ? [] : [[name, jwk[name]]]));
107
+ var publicOf = (jwk) => pick(jwk, ["kty", "crv", "x", "y"]);
108
+ var dpopThumbprint = (key) => calculateJwkThumbprint(publicOf(key.jwk), "sha256");
109
+ function dpopTarget(url) {
110
+ const target = new URL(url);
111
+ target.search = "";
112
+ target.hash = "";
113
+ return target.toString();
114
+ }
115
+ async function signDpopProof2(key, input) {
116
+ const signer = await importJWK(key.jwk, key.alg);
117
+ const iat = Math.floor((input.now ?? Date.now)() / 1000);
118
+ const ath = input.accessToken === undefined ? undefined : toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", encoder2.encode(input.accessToken))));
119
+ return new SignJWT({
120
+ htm: input.method.toUpperCase(),
121
+ htu: dpopTarget(input.url),
122
+ jti: randomToken(16),
123
+ iat,
124
+ ...input.nonce !== undefined && { nonce: input.nonce },
125
+ ...ath !== undefined && { ath }
126
+ }).setProtectedHeader({
127
+ typ: "dpop+jwt",
128
+ alg: key.alg,
129
+ jwk: publicOf(key.jwk)
130
+ }).sign(signer);
131
+ }
132
+ function nonceMemory() {
133
+ const nonces = new Map;
134
+ return {
135
+ get: (url) => nonces.get(new URL(url).origin),
136
+ set: (url, nonce) => void nonces.set(new URL(url).origin, nonce)
137
+ };
138
+ }
139
+ async function wantsNonce(response) {
140
+ if (!response.headers.get("dpop-nonce"))
141
+ return false;
142
+ if (response.status === 401) {
143
+ return /use_dpop_nonce/.test(response.headers.get("www-authenticate") ?? "");
144
+ }
145
+ if (response.status !== 400)
146
+ return false;
147
+ const body = await response.clone().json().catch(() => null);
148
+ return typeof body === "object" && body !== null && body["error"] === "use_dpop_nonce";
149
+ }
150
+ function dpopBinding(config) {
151
+ const { key, accessToken, nonces } = config;
152
+ const proof = ({ method, url, nonce }) => signDpopProof2(key, {
153
+ method,
154
+ url,
155
+ accessToken,
156
+ nonce: nonce ?? nonces.get(url),
157
+ now: config.now
158
+ });
159
+ return {
160
+ thumbprint: config.thumbprint,
161
+ proof,
162
+ async headers(input) {
163
+ return {
164
+ authorization: `DPoP ${accessToken}`,
165
+ dpop: await proof(input)
166
+ };
167
+ },
168
+ async fetch(input, init) {
169
+ const url = String(input);
170
+ const method = init?.method ?? "GET";
171
+ const send = async (nonce) => {
172
+ const headers = new Headers(init?.headers);
173
+ headers.set("authorization", `DPoP ${accessToken}`);
174
+ headers.set("dpop", await proof({ method, url, nonce }));
175
+ const response = await config.fetch(url, { ...init, headers });
176
+ const sent = response.headers.get("dpop-nonce");
177
+ if (sent)
178
+ nonces.set(url, sent);
179
+ return response;
180
+ };
181
+ const first = await send();
182
+ if (!await wantsNonce(first))
183
+ return first;
184
+ return send(first.headers.get("dpop-nonce") ?? undefined);
185
+ }
186
+ };
187
+ }
188
+
189
+ // src/oidc/flow.ts
190
+ var DISCOVERY_TTL = 60 * 60 * 1000;
191
+ var JWKS_TTL = 10 * 60 * 1000;
192
+ var isRecord = (value) => typeof value === "object" && value !== null;
193
+ var text = (value) => typeof value === "string" && value !== "";
194
+ function issuerClient(config) {
195
+ const { issuer, now } = config;
196
+ let discovery;
197
+ let keys;
198
+ async function getJson(url, code) {
199
+ let response;
200
+ try {
201
+ response = await config.fetch(url, {
202
+ headers: { accept: "application/json" }
203
+ });
204
+ } catch (cause) {
205
+ throw new OidcError2(code, `Could not reach ${url}.`, undefined, {
206
+ cause
207
+ });
208
+ }
209
+ if (!response.ok) {
210
+ throw new OidcError2(code, `${url} answered ${response.status}.`);
211
+ }
212
+ return response.json().catch(() => {
213
+ throw new OidcError2(code, `${url} did not answer JSON.`);
214
+ });
215
+ }
216
+ async function loadDiscovery() {
217
+ const url = `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`;
218
+ const body = await getJson(url, "discovery-failed");
219
+ if (!isRecord(body) || !text(body["authorization_endpoint"]) || !text(body["token_endpoint"]) || !text(body["jwks_uri"])) {
220
+ throw new OidcError2("discovery-failed", `${url} lacks authorization_endpoint, token_endpoint or jwks_uri.`);
221
+ }
222
+ for (const key of [
223
+ "authorization_endpoint",
224
+ "token_endpoint",
225
+ "jwks_uri"
226
+ ]) {
227
+ const endpoint = new URL(String(body[key]));
228
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(endpoint.hostname);
229
+ if (endpoint.protocol !== "https:" && !(loopback && endpoint.protocol === "http:")) {
230
+ throw new OidcError2("discovery-failed", `${url} gives a ${key} that is not https.`);
231
+ }
232
+ }
233
+ if (body["issuer"] !== issuer) {
234
+ throw new OidcError2("issuer-mismatch", `${url} names the issuer ${JSON.stringify(body["issuer"])}, not ${JSON.stringify(issuer)}.`);
235
+ }
236
+ return body;
237
+ }
238
+ const discover = () => {
239
+ if (!discovery || now() - discovery.at > DISCOVERY_TTL) {
240
+ const value = loadDiscovery();
241
+ const entry = { at: now(), value };
242
+ discovery = entry;
243
+ value.catch(() => {
244
+ if (discovery === entry)
245
+ discovery = undefined;
246
+ });
247
+ }
248
+ return discovery.value;
249
+ };
250
+ async function jwks(force) {
251
+ if (force || !keys || now() - keys.at > JWKS_TTL) {
252
+ const value = discover().then(async (document) => await getJson(document.jwks_uri, "invalid-id-token"));
253
+ const entry = { at: now(), value };
254
+ keys = entry;
255
+ value.catch(() => {
256
+ if (keys === entry)
257
+ keys = undefined;
258
+ });
259
+ }
260
+ return keys.value;
261
+ }
262
+ async function verifyIdToken(idToken, clientId, nonce) {
263
+ const document = await discover();
264
+ const check = async (force) => jwtVerify(idToken, createLocalJWKSet(await jwks(force)), {
265
+ issuer: document.issuer,
266
+ audience: clientId,
267
+ algorithms: config.algorithms,
268
+ clockTolerance: config.clockToleranceSeconds,
269
+ currentDate: new Date(now()),
270
+ requiredClaims: ["exp", "iat", "sub"]
271
+ });
272
+ let payload;
273
+ try {
274
+ try {
275
+ ({ payload } = await check(false));
276
+ } catch (error) {
277
+ if (!(error instanceof joseErrors.JWKSNoMatchingKey))
278
+ throw error;
279
+ ({ payload } = await check(true));
280
+ }
281
+ } catch (cause) {
282
+ if (cause instanceof OidcError2)
283
+ throw cause;
284
+ throw new OidcError2("invalid-id-token", `The id token was refused: ${cause instanceof Error ? cause.message : String(cause)}`, undefined, { cause });
285
+ }
286
+ if (Array.isArray(payload.aud) && payload.aud.length > 1 && payload["azp"] !== clientId) {
287
+ throw new OidcError2("invalid-id-token", "The id token has several audiences and its azp is not this client.");
288
+ }
289
+ if (nonce !== undefined && payload["nonce"] !== nonce) {
290
+ throw new OidcError2("nonce-mismatch", "The id token nonce is not the one this sign-in sent.");
291
+ }
292
+ return payload;
293
+ }
294
+ return { discover, verifyIdToken };
295
+ }
296
+ async function postForm(fetcher, endpoint, client, params, code, what, dpop, signal) {
297
+ const body = new URLSearchParams(params);
298
+ const headers = {
299
+ "content-type": "application/x-www-form-urlencoded",
300
+ accept: "application/json"
301
+ };
302
+ if (client.secret === undefined) {
303
+ body.set("client_id", client.id);
304
+ } else {
305
+ const pair = `${encodeURIComponent(client.id)}:${encodeURIComponent(client.secret)}`;
306
+ headers["authorization"] = `Basic ${btoa(pair)}`;
307
+ }
308
+ const send = async (nonce) => {
309
+ const sent = dpop ? {
310
+ ...headers,
311
+ dpop: await signDpopProof2(dpop.key, {
312
+ method: "POST",
313
+ url: endpoint,
314
+ nonce,
315
+ now: dpop.now
316
+ })
317
+ } : headers;
318
+ try {
319
+ const response = await fetcher(endpoint, {
320
+ method: "POST",
321
+ headers: sent,
322
+ body,
323
+ ...signal && { signal }
324
+ });
325
+ const given = response.headers.get("dpop-nonce");
326
+ if (dpop && given)
327
+ dpop.nonces.set(endpoint, given);
328
+ return response;
329
+ } catch (cause) {
330
+ throw new OidcError2(code, `The ${what} could not be reached.`, undefined, { cause });
331
+ }
332
+ };
333
+ let response = await send(dpop?.nonces.get(endpoint));
334
+ if (dpop && await wantsNonce(response)) {
335
+ await response.body?.cancel().catch(() => {
336
+ return;
337
+ });
338
+ response = await send(response.headers.get("dpop-nonce") ?? undefined);
339
+ }
340
+ const answer = await response.json().catch(() => null);
341
+ return { response, answer };
342
+ }
343
+ var detailOf = (answer) => isRecord(answer) ? [answer["error"], answer["error_description"]].filter(text).join(": ") : "";
344
+ async function tokenRequest(fetcher, endpoint, client, params, code, dpop) {
345
+ const { response, answer } = await postForm(fetcher, endpoint, client, params, code, "token endpoint", dpop);
346
+ if (!response.ok || !isRecord(answer) || !text(answer["access_token"])) {
347
+ const detail = detailOf(answer);
348
+ throw new OidcError2(code, `The token endpoint answered ${response.status}${detail ? ` (${detail})` : ""}.`);
349
+ }
350
+ const type = String(answer["token_type"] ?? "bearer").toLowerCase();
351
+ if (type !== "bearer" && !(dpop && type === "dpop")) {
352
+ throw new OidcError2(code, "The token endpoint did not issue a bearer token.");
353
+ }
354
+ return answer;
355
+ }
356
+ async function revokeRequest(fetcher, endpoint, client, params, dpop, signal) {
357
+ const { response, answer } = await postForm(fetcher, endpoint, client, params, "revoke-failed", "revocation endpoint", dpop, signal);
358
+ if (!response.ok) {
359
+ const detail = detailOf(answer);
360
+ throw new OidcError2("revoke-failed", `The revocation endpoint answered ${response.status}${detail ? ` (${detail})` : ""}.`);
361
+ }
362
+ }
363
+ async function pushRequest(fetcher, endpoint, client, params, dpop) {
364
+ const { response, answer } = await postForm(fetcher, endpoint, client, params, "par-failed", "pushed authorization request endpoint", dpop);
365
+ if (!response.ok || !isRecord(answer) || !text(answer["request_uri"])) {
366
+ const detail = detailOf(answer);
367
+ throw new OidcError2("par-failed", `The pushed authorization request endpoint answered ${response.status}${detail ? ` (${detail})` : ""}.`);
368
+ }
369
+ return answer["request_uri"];
370
+ }
371
+
372
+ // src/oidc/stored.ts
373
+ var isKey = (value) => typeof value === "object" && value !== null && ["ES256", "EdDSA"].includes(value["alg"]) && typeof value["jwk"] === "object";
374
+ var isFlow = (value) => typeof value === "object" && value !== null && ["state", "nonce", "verifier", "next"].every((key) => typeof value[key] === "string") && typeof value["exp"] === "number" && (value["dpop"] === undefined || isKey(value["dpop"]));
375
+ var isStored = (value) => typeof value === "object" && value !== null && typeof value["idToken"] === "string" && typeof value["accessToken"] === "string" && typeof value["expiresAt"] === "number" && (value["dpop"] === undefined || isKey(value["dpop"]));
376
+
377
+ // src/oidc/tokens.ts
378
+ async function toStored(ctx, response, nonce, previous, key) {
379
+ const { now } = ctx;
380
+ const dpop = key && (String(response.token_type).toLowerCase() === "dpop" || previous?.dpop !== undefined && response.token_type === undefined) ? key : undefined;
381
+ if (!response.id_token && previous) {
382
+ const kept = decodeJwt(previous.idToken);
383
+ return {
384
+ claims: kept,
385
+ stored: {
386
+ idToken: previous.idToken,
387
+ dpop,
388
+ accessToken: response.access_token,
389
+ refreshToken: response.refresh_token ?? previous.refreshToken,
390
+ expiresAt: typeof response.expires_in === "number" ? now() + response.expires_in * 1000 : now() + 300000
391
+ }
392
+ };
393
+ }
394
+ const idToken = response.id_token;
395
+ if (!idToken) {
396
+ throw new OidcError2("invalid-id-token", "The token endpoint sent no id token.");
397
+ }
398
+ const claims = await ctx.issuerApi.verifyIdToken(idToken, ctx.clientId, nonce);
399
+ if (previous && decodeJwt(previous.idToken).sub !== claims.sub) {
400
+ throw new OidcError2("invalid-id-token", "A refresh changed the user.");
401
+ }
402
+ const expiresAt = typeof response.expires_in === "number" ? now() + response.expires_in * 1000 : (claims["exp"] ?? 0) * 1000;
403
+ return {
404
+ claims,
405
+ stored: {
406
+ idToken,
407
+ dpop,
408
+ accessToken: response.access_token,
409
+ refreshToken: response.refresh_token ?? previous?.refreshToken,
410
+ expiresAt
411
+ }
412
+ };
413
+ }
414
+ async function commit(ctx, headers, stored) {
415
+ const { now } = ctx;
416
+ const lifetime = stored.refreshToken ? ctx.sessionSeconds : Math.max(0, (stored.expiresAt - now()) / 1000);
417
+ const cookie = ctx.cookies.commit(await ctx.tokenSeal.seal(stored), new Date(now() + lifetime * 1000), now());
418
+ if (cookie.length > 4096) {
419
+ throw new OidcError2("token-cookie-too-large", `The token cookie is ${cookie.length} bytes, over the 4096 a browser keeps. Ask the issuer for fewer claims or a shorter access token.`);
420
+ }
421
+ headers.append("Set-Cookie", cookie);
422
+ }
423
+
424
+ // src/oidc/callback.ts
425
+ async function checkedFlow(ctx, request, fail) {
426
+ const url = new URL(request.url);
427
+ const sealed = ctx.cookies.challengeOf(request);
428
+ const flow = sealed ? await ctx.flowSeal.open(sealed) : null;
429
+ if (!isFlow(flow)) {
430
+ throw fail("missing-challenge", "The sign-in challenge cookie is missing or unreadable (a second tab, an expired page or a blocked cookie).");
431
+ }
432
+ if (flow.exp <= ctx.now()) {
433
+ throw fail("challenge-expired", "The sign-in took too long; start again.");
434
+ }
435
+ const returned = url.searchParams.get("state");
436
+ if (returned === null || !sameText(returned, flow.state)) {
437
+ throw fail("state-mismatch", "The returned state is not the one this sign-in sent.");
438
+ }
439
+ const failure = url.searchParams.get("error");
440
+ if (failure) {
441
+ const description = url.searchParams.get("error_description");
442
+ throw fail("provider-error", `The issuer refused: ${failure}${description ? ` (${description})` : ""}.`);
443
+ }
444
+ const claimedIssuer = url.searchParams.get("iss");
445
+ if (claimedIssuer !== null && claimedIssuer !== ctx.issuer) {
446
+ throw fail("issuer-mismatch", "The callback names another issuer.");
447
+ }
448
+ const code = url.searchParams.get("code");
449
+ if (!code)
450
+ throw fail("missing-code", "The callback carries no code.");
451
+ return { flow, code };
452
+ }
453
+ async function callback(ctx, request) {
454
+ const cleared = () => {
455
+ const headers = new Headers;
456
+ headers.append("Set-Cookie", ctx.cookies.destroyChallenge());
457
+ return headers;
458
+ };
459
+ const fail = (code, message) => new OidcError2(code, message, cleared());
460
+ const { flow, code } = await checkedFlow(ctx, request, fail);
461
+ try {
462
+ const document = await ctx.issuerApi.discover();
463
+ const answer = await tokenRequest(ctx.fetcher, document.token_endpoint, ctx.client, {
464
+ ...ctx.extraTokenParams,
465
+ grant_type: "authorization_code",
466
+ code,
467
+ redirect_uri: ctx.redirectUri,
468
+ code_verifier: flow.verifier
469
+ }, "token-exchange-failed", ctx.signing(flow.dpop));
470
+ const { stored } = await toStored(ctx, answer, flow.nonce, undefined, flow.dpop);
471
+ const headers = cleared();
472
+ await commit(ctx, headers, stored);
473
+ headers.set("Location", safeNext2(flow.next));
474
+ headers.set("Cache-Control", "no-store");
475
+ return new Response(null, { status: 302, headers });
476
+ } catch (error) {
477
+ if (error instanceof OidcError2) {
478
+ for (const value of cleared().getSetCookie()) {
479
+ error.headers.append("Set-Cookie", value);
480
+ }
481
+ }
482
+ throw error;
483
+ }
484
+ }
485
+
486
+ // src/oidc/context.ts
487
+ var DEFAULT_ALGORITHMS = ["RS256", "PS256", "ES256", "EdDSA"];
488
+ var CHALLENGE_SECONDS = 600;
489
+ var MAX_TIMER_MS = 2147483647;
490
+ function checkRequired(options) {
491
+ for (const [label, value] of [
492
+ ["issuer", options.issuer],
493
+ ["clientId", options.clientId],
494
+ ["redirectUri", options.redirectUri]
495
+ ]) {
496
+ if (!value)
497
+ throw new TypeError(`oidcClient(): ${label} is required.`);
498
+ }
499
+ const { secret } = options;
500
+ if (typeof secret !== "string" || secret.length < 32) {
501
+ throw new TypeError("oidcClient(): secret must be a string of at least 32 characters.");
502
+ }
503
+ }
504
+ function checkTuning(options, par, dpopAlg, refreshFlightMs) {
505
+ if (!["auto", "always", "never"].includes(par)) {
506
+ throw new TypeError("oidcClient(): par must be 'auto', 'always' or 'never'.");
507
+ }
508
+ if (dpopAlg !== undefined && !["ES256", "EdDSA"].includes(dpopAlg)) {
509
+ throw new TypeError("oidcClient(): dpop.alg must be 'ES256' or 'EdDSA'.");
510
+ }
511
+ if (options.revokeTimeoutMs !== undefined && !(Number.isFinite(options.revokeTimeoutMs) && options.revokeTimeoutMs > 0)) {
512
+ throw new TypeError("oidcClient(): revokeTimeoutMs must be a positive finite number of milliseconds.");
513
+ }
514
+ if (!(Number.isFinite(refreshFlightMs) && refreshFlightMs >= 0 && refreshFlightMs <= MAX_TIMER_MS)) {
515
+ throw new TypeError("oidcClient(): refreshFlightMs must be a finite number of milliseconds, from 0 to 2147483647.");
516
+ }
517
+ }
518
+ function createContext(options) {
519
+ checkRequired(options);
520
+ const {
521
+ issuer,
522
+ clientId,
523
+ clientSecret,
524
+ redirectUri,
525
+ secret,
526
+ signInPath = "/sign-in",
527
+ sessionSeconds = 30 * 24 * 3600,
528
+ refreshSkewSeconds = 60,
529
+ refreshFlightMs = 1e4,
530
+ clockToleranceSeconds = 30
531
+ } = options;
532
+ const {
533
+ client_id: _id,
534
+ client_secret: _secret,
535
+ ...extraTokenParams
536
+ } = options.tokenParams ?? {};
537
+ const now = options.now ?? Date.now;
538
+ const scopes = [
539
+ ...new Set(["openid", ...options.scopes ?? ["profile", "email"]])
540
+ ];
541
+ const cookies = sessionCookies2({
542
+ session: options.name,
543
+ challenge: `${options.name}_flow`,
544
+ challengePath: "/",
545
+ challengeHostPrefix: true,
546
+ challengeSeconds: CHALLENGE_SECONDS,
547
+ secure: options.secure,
548
+ sameSite: "lax"
549
+ });
550
+ const flowSeal = sealer(secret, "flow");
551
+ const tokenSeal = sealer(secret, "tokens");
552
+ const fetcher = options.fetch ?? ((input, init) => fetch(input, init));
553
+ const issuerApi = issuerClient({
554
+ issuer,
555
+ fetch: fetcher,
556
+ now,
557
+ algorithms: [...options.algorithms ?? DEFAULT_ALGORITHMS],
558
+ clockToleranceSeconds
559
+ });
560
+ const par = options.par ?? "auto";
561
+ const dpopAlg = options.dpop ? options.dpop.alg ?? "ES256" : undefined;
562
+ checkTuning(options, par, dpopAlg, refreshFlightMs);
563
+ const nonces = nonceMemory();
564
+ return {
565
+ options,
566
+ issuer,
567
+ clientId,
568
+ redirectUri,
569
+ signInPath,
570
+ sessionSeconds,
571
+ refreshSkewSeconds,
572
+ refreshFlightMs,
573
+ scopes,
574
+ extraTokenParams,
575
+ now,
576
+ cookies,
577
+ flowSeal,
578
+ tokenSeal,
579
+ issuerApi,
580
+ fetcher,
581
+ client: { id: clientId, secret: clientSecret },
582
+ par,
583
+ dpopAlg,
584
+ nonces,
585
+ signing: (key) => key ? { key, nonces, now } : undefined,
586
+ flights: new Map,
587
+ stores: new WeakMap
588
+ };
589
+ }
590
+
591
+ // src/oidc/revoke.ts
592
+ async function revokeTokens(input) {
593
+ const { stored } = input;
594
+ const signal = AbortSignal.timeout(input.timeoutMs);
595
+ const timedOut = new Promise((_, reject) => {
596
+ signal.addEventListener("abort", () => reject(new OidcError2("revoke-failed", `The revocation endpoint did not answer within ${input.timeoutMs} ms.`)), { once: true });
597
+ });
598
+ timedOut.catch(() => {
599
+ return;
600
+ });
601
+ const tokens = [
602
+ ...stored.refreshToken ? [[stored.refreshToken, "refresh_token"]] : [],
603
+ [stored.accessToken, "access_token"]
604
+ ];
605
+ for (const [token, hint] of tokens) {
606
+ try {
607
+ await Promise.race([
608
+ revokeRequest(input.fetcher, input.endpoint, input.client, { token, token_type_hint: hint }, input.signing(stored.dpop), signal),
609
+ timedOut
610
+ ]);
611
+ } catch (error) {
612
+ input.report(error instanceof OidcError2 ? error : new OidcError2("revoke-failed", "Revocation failed.", undefined, {
613
+ cause: error
614
+ }));
615
+ if (signal.aborted)
616
+ return;
617
+ }
618
+ }
619
+ }
620
+
621
+ // src/oidc/logout.ts
622
+ async function logout(ctx, request) {
623
+ const { options } = ctx;
624
+ const report = (error) => {
625
+ try {
626
+ options.onRevokeError?.(error);
627
+ } catch {}
628
+ };
629
+ const headers = new Headers({ "Cache-Control": "no-store" });
630
+ headers.append("Set-Cookie", ctx.cookies.destroy());
631
+ const sealed = ctx.cookies.token(request);
632
+ const opened = sealed ? await ctx.tokenSeal.open(sealed) : null;
633
+ const document = await ctx.issuerApi.discover().catch((cause) => {
634
+ if (options.revokeOnLogout) {
635
+ report(new OidcError2("discovery-failed", "Discovery failed at logout, so the tokens were not revoked.", undefined, { cause }));
636
+ }
637
+ return null;
638
+ });
639
+ if (options.revokeOnLogout && document?.revocation_endpoint && isStored(opened)) {
640
+ await revokeTokens({
641
+ fetcher: ctx.fetcher,
642
+ client: ctx.client,
643
+ endpoint: document.revocation_endpoint,
644
+ stored: opened,
645
+ signing: ctx.signing,
646
+ timeoutMs: options.revokeTimeoutMs ?? 3000,
647
+ report
648
+ });
649
+ }
650
+ const endpoint = document?.end_session_endpoint;
651
+ if (!endpoint) {
652
+ headers.set("Location", options.postLogoutRedirectUri ?? "/");
653
+ return new Response(null, { status: 302, headers });
654
+ }
655
+ const target = new URL(endpoint);
656
+ if (isStored(opened))
657
+ target.searchParams.set("id_token_hint", opened.idToken);
658
+ target.searchParams.set("client_id", ctx.clientId);
659
+ if (options.postLogoutRedirectUri) {
660
+ target.searchParams.set("post_logout_redirect_uri", options.postLogoutRedirectUri);
661
+ }
662
+ headers.set("Location", target.toString());
663
+ return new Response(null, { status: 302, headers });
664
+ }
665
+
666
+ // src/oidc/user.ts
667
+ async function toUser(ctx, stored, headers) {
668
+ const user = {
669
+ claims: decodeJwt(stored.idToken),
670
+ accessToken: stored.accessToken,
671
+ idToken: stored.idToken,
672
+ expiresAt: stored.expiresAt,
673
+ headers,
674
+ dpop: stored.dpop ? dpopBinding({
675
+ key: stored.dpop,
676
+ thumbprint: await dpopThumbprint(stored.dpop),
677
+ accessToken: stored.accessToken,
678
+ nonces: ctx.nonces,
679
+ fetch: ctx.fetcher,
680
+ now: ctx.now
681
+ }) : null,
682
+ fetch: ctx.fetcher
683
+ };
684
+ ctx.stores.set(user, stored);
685
+ return user;
686
+ }
687
+
688
+ // src/oidc/refresh.ts
689
+ function refreshing(ctx, stored, key) {
690
+ const { flights } = ctx;
691
+ const flying = flights.get(key);
692
+ if (flying)
693
+ return flying;
694
+ const flight = (async () => {
695
+ const document = await ctx.issuerApi.discover();
696
+ const answer = await tokenRequest(ctx.fetcher, document.token_endpoint, ctx.client, {
697
+ ...ctx.extraTokenParams,
698
+ grant_type: "refresh_token",
699
+ refresh_token: key,
700
+ scope: ctx.scopes.join(" ")
701
+ }, "refresh-failed", ctx.signing(stored.dpop));
702
+ return (await toStored(ctx, answer, undefined, stored, stored.dpop)).stored;
703
+ })();
704
+ flights.set(key, flight);
705
+ const forget = () => {
706
+ const timer = setTimeout(() => flights.delete(key), ctx.refreshFlightMs);
707
+ if (typeof timer === "object")
708
+ timer.unref();
709
+ };
710
+ flight.then(forget, () => flights.delete(key));
711
+ return flight;
712
+ }
713
+ async function refresh(ctx, user, refreshOptions = {}) {
714
+ const stored = ctx.stores.get(user);
715
+ if (!stored) {
716
+ throw new TypeError("oidc.refresh(): the user was not returned by this client.");
717
+ }
718
+ if (!refreshOptions.force && stored.expiresAt - ctx.refreshSkewSeconds * 1000 > ctx.now()) {
719
+ return user;
720
+ }
721
+ const headers = new Headers;
722
+ try {
723
+ if (!stored.refreshToken)
724
+ throw new Error("no refresh token");
725
+ const next = await refreshing(ctx, stored, stored.refreshToken);
726
+ await commit(ctx, headers, next);
727
+ return toUser(ctx, next, headers);
728
+ } catch (cause) {
729
+ if (stored.expiresAt > ctx.now())
730
+ return user;
731
+ throw cause instanceof OidcError2 ? cause : new OidcError2("refresh-failed", "The refresh failed.", undefined, {
732
+ cause
733
+ });
734
+ }
735
+ }
736
+
737
+ // src/oidc/session.ts
738
+ import { redirect } from "react-router";
739
+ async function oidcUser(ctx, request) {
740
+ const headers = new Headers;
741
+ const sealed = ctx.cookies.token(request);
742
+ if (!sealed)
743
+ return null;
744
+ const opened = await ctx.tokenSeal.open(sealed);
745
+ if (!isStored(opened)) {
746
+ headers.append("Set-Cookie", ctx.cookies.destroy());
747
+ return null;
748
+ }
749
+ let stored = opened;
750
+ if (stored.expiresAt - ctx.refreshSkewSeconds * 1000 <= ctx.now()) {
751
+ try {
752
+ if (!stored.refreshToken)
753
+ throw new Error("no refresh token");
754
+ stored = await refreshing(ctx, stored, stored.refreshToken);
755
+ await commit(ctx, headers, stored);
756
+ } catch {
757
+ if (stored.expiresAt <= ctx.now())
758
+ return null;
759
+ }
760
+ }
761
+ return toUser(ctx, stored, headers);
762
+ }
763
+ var toSignIn = (ctx, request, headers) => {
764
+ const url = new URL(request.url);
765
+ const next = safeNext2(`${url.pathname}${url.search}`);
766
+ const target = new URL(ctx.signInPath, url);
767
+ target.searchParams.set("next", next);
768
+ throw redirect(`${target.pathname}${target.search}`, { headers });
769
+ };
770
+ async function requireOidcUser(ctx, request) {
771
+ const user = await oidcUser(ctx, request);
772
+ if (user)
773
+ return user;
774
+ const headers = new Headers;
775
+ if (ctx.cookies.token(request)) {
776
+ headers.append("Set-Cookie", ctx.cookies.destroy());
777
+ }
778
+ return toSignIn(ctx, request, headers);
779
+ }
780
+
781
+ // src/oidc/signin.ts
782
+ async function signIn(ctx, request) {
783
+ const { clientId, now } = ctx;
784
+ const document = await ctx.issuerApi.discover();
785
+ const url = new URL(request.url);
786
+ const flow = {
787
+ state: randomToken(),
788
+ nonce: randomToken(),
789
+ verifier: randomToken(48),
790
+ next: safeNext2(url.searchParams.get("next")),
791
+ exp: now() + CHALLENGE_SECONDS * 1000,
792
+ dpop: ctx.dpopAlg ? await generateDpopKey2(ctx.dpopAlg) : undefined
793
+ };
794
+ const authRequest = {
795
+ ...ctx.options.authorizationParams,
796
+ response_type: "code",
797
+ client_id: clientId,
798
+ redirect_uri: ctx.redirectUri,
799
+ scope: ctx.scopes.join(" "),
800
+ state: flow.state,
801
+ nonce: flow.nonce,
802
+ code_challenge: await s256(flow.verifier),
803
+ code_challenge_method: "S256",
804
+ ...flow.dpop && { dpop_jkt: await dpopThumbprint(flow.dpop) }
805
+ };
806
+ const endpoint = document.pushed_authorization_request_endpoint;
807
+ const push = ctx.par === "always" || ctx.par === "auto" && document.require_pushed_authorization_requests === true;
808
+ const target = new URL(document.authorization_endpoint);
809
+ if (push) {
810
+ if (!endpoint) {
811
+ throw new OidcError2("par-failed", "Pushed authorization requests are required but the issuer publishes no pushed_authorization_request_endpoint.");
812
+ }
813
+ const requestUri = await pushRequest(ctx.fetcher, endpoint, ctx.client, authRequest, ctx.signing(flow.dpop));
814
+ target.searchParams.set("client_id", clientId);
815
+ target.searchParams.set("request_uri", requestUri);
816
+ } else {
817
+ for (const [key, value] of Object.entries(authRequest)) {
818
+ target.searchParams.set(key, value);
819
+ }
820
+ }
821
+ const headers = new Headers({ "Cache-Control": "no-store" });
822
+ headers.append("Set-Cookie", ctx.cookies.commitChallenge(await ctx.flowSeal.seal(flow), null, now()));
823
+ headers.set("Location", target.toString());
824
+ return new Response(null, { status: 302, headers });
825
+ }
826
+
827
+ // src/oidc/client.ts
828
+ function oidcClient2(options) {
829
+ const ctx = createContext(options);
830
+ return {
831
+ names: ctx.cookies.names,
832
+ oidcUser: (request) => oidcUser(ctx, request),
833
+ refresh: (user, refreshOptions) => refresh(ctx, user, refreshOptions),
834
+ requireOidcUser: (request) => requireOidcUser(ctx, request),
835
+ signIn: (request) => signIn(ctx, request),
836
+ callback: (request) => callback(ctx, request),
837
+ logout: (request) => logout(ctx, request)
838
+ };
839
+ }
840
+ // src/oidc/dpop-fetch.ts
841
+ function dpopFetch2(oidc, user, options = {}) {
842
+ let last = user;
843
+ return async (input, init) => {
844
+ const next = await oidc.refresh(last);
845
+ if (next.accessToken !== last.accessToken || next.expiresAt !== last.expiresAt) {
846
+ last = next;
847
+ options.onUser?.(next);
848
+ }
849
+ if (last.dpop)
850
+ return last.dpop.fetch(input, init);
851
+ const headers = new Headers(init?.headers);
852
+ headers.set("authorization", `Bearer ${last.accessToken}`);
853
+ return last.fetch(String(input), { ...init, headers });
854
+ };
855
+ }
856
+ // src/oidc/env.ts
857
+ class OidcEnvError2 extends Error {
858
+ problems;
859
+ name = "OidcEnvError";
860
+ constructor(problems) {
861
+ super(`The OIDC environment is not usable:
862
+ ${problems.map((p) => `- ${p}`).join(`
863
+ `)}`);
864
+ this.problems = problems;
865
+ }
866
+ }
867
+ var LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
868
+ var named = (context, suffix) => `${context.prefix}_${suffix}`;
869
+ function plain(context, suffix) {
870
+ const value = context.env[named(context, suffix)]?.trim();
871
+ return value ? value : undefined;
872
+ }
873
+ function required(context, suffix) {
874
+ const value = plain(context, suffix);
875
+ if (value === undefined) {
876
+ context.problems.push(`${named(context, suffix)} is not set.`);
877
+ }
878
+ return value;
879
+ }
880
+ function url(context, suffix, mandatory) {
881
+ const value = mandatory ? required(context, suffix) : plain(context, suffix);
882
+ if (value === undefined)
883
+ return;
884
+ const variable = named(context, suffix);
885
+ let parsed;
886
+ try {
887
+ parsed = new URL(value);
888
+ } catch {
889
+ context.problems.push(`${variable} is not an absolute URL.`);
890
+ return;
891
+ }
892
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && LOOPBACK.has(parsed.hostname))) {
893
+ context.problems.push(`${variable} must be an https: URL.`);
894
+ return;
895
+ }
896
+ return value;
897
+ }
898
+ async function secret(context, suffix, mandatory) {
899
+ const direct = plain(context, suffix);
900
+ const fileSuffix = `${suffix}_FILE`;
901
+ const path = plain(context, fileSuffix);
902
+ if (direct !== undefined && path !== undefined) {
903
+ context.problems.push(`Set ${named(context, suffix)} or ${named(context, fileSuffix)}, not both.`);
904
+ return;
905
+ }
906
+ if (path === undefined) {
907
+ if (direct !== undefined) {
908
+ return { value: direct, variable: named(context, suffix) };
909
+ }
910
+ if (mandatory) {
911
+ context.problems.push(`${named(context, fileSuffix)} (or ${named(context, suffix)}) is not set.`);
912
+ }
913
+ return;
914
+ }
915
+ const variable = named(context, fileSuffix);
916
+ let text;
917
+ try {
918
+ const { mode } = await context.statFile(path);
919
+ if ((mode & 63) !== 0) {
920
+ context.problems.push(`${variable} names a file readable by group or others (mode ${(mode & 511).toString(8)}); restrict it to its owner, such as chmod 600.`);
921
+ return;
922
+ }
923
+ text = await context.readFile(path);
924
+ } catch {
925
+ context.problems.push(`${variable} names a file that cannot be read: check the path and its permissions.`);
926
+ return;
927
+ }
928
+ const value = text.trim();
929
+ if (value === "") {
930
+ context.problems.push(`${variable} names an empty file.`);
931
+ return;
932
+ }
933
+ if (/\s/.test(value)) {
934
+ context.problems.push(`${variable} names a file with whitespace inside: it must hold one value.`);
935
+ return;
936
+ }
937
+ return { value, variable };
938
+ }
939
+ async function oidcFromEnv2(source = {}) {
940
+ const context = {
941
+ env: source.env ?? process.env,
942
+ prefix: source.prefix ?? "OIDC",
943
+ problems: [],
944
+ readFile: source.readFile ?? ((path) => Bun.file(path).text()),
945
+ statFile: source.statFile ?? ((path) => Bun.file(path).stat())
946
+ };
947
+ const issuer = url(context, "ISSUER", true);
948
+ const clientId = required(context, "CLIENT_ID");
949
+ const clientSecret = await secret(context, "CLIENT_SECRET", false);
950
+ const redirectUri = url(context, "REDIRECT_URI", true);
951
+ const postLogoutRedirectUri = url(context, "POST_LOGOUT_REDIRECT_URI", false);
952
+ const session = await secret(context, "SESSION_SECRET", true);
953
+ if (session !== undefined && session.value.length < 32) {
954
+ context.problems.push(`The session secret must be 32 characters or more (${session.variable}).`);
955
+ }
956
+ if (context.problems.length > 0 || issuer === undefined || clientId === undefined || redirectUri === undefined || session === undefined) {
957
+ throw new OidcEnvError2(context.problems);
958
+ }
959
+ return {
960
+ issuer,
961
+ clientId,
962
+ clientSecret: clientSecret?.value,
963
+ redirectUri,
964
+ secret: session.value,
965
+ name: plain(context, "COOKIE_NAME") ?? "oidc",
966
+ postLogoutRedirectUri
967
+ };
968
+ }
969
+ // src/oidc/routes.ts
970
+ import { redirect as redirect2 } from "react-router";
971
+ function signInRoute2(oidc, options = {}) {
972
+ return {
973
+ async loader({ request }) {
974
+ await options.guard?.(request);
975
+ return oidc.signIn(request);
976
+ }
977
+ };
978
+ }
979
+ function callbackRoute2(oidc, options = {}) {
980
+ const errorPath = sitePath(options.errorPath ?? "/", {
981
+ label: "callbackRoute(): errorPath"
982
+ });
983
+ return {
984
+ async loader({ request }) {
985
+ await options.guard?.(request);
986
+ try {
987
+ return await oidc.callback(request);
988
+ } catch (error) {
989
+ if (!(error instanceof OidcError2))
990
+ throw error;
991
+ if (options.onError)
992
+ return options.onError(error);
993
+ return redirect2(`${errorPath}?${new URLSearchParams({ "sign-in-error": error.code })}`, { headers: error.headers });
994
+ }
995
+ }
996
+ };
997
+ }
998
+ function signOutRoute2(oidc, options = {}) {
999
+ const sameSite = siteCheck(options.origin);
1000
+ const redirectTo = sitePath(options.redirectTo ?? "/", {
1001
+ label: "signOutRoute(): redirectTo",
1002
+ query: true
1003
+ });
1004
+ return {
1005
+ async action({ request }) {
1006
+ await options.guard?.(request);
1007
+ sameSite(request);
1008
+ return oidc.logout(request);
1009
+ },
1010
+ async loader({ request }) {
1011
+ await options.guard?.(request);
1012
+ return redirect2(redirectTo);
1013
+ }
1014
+ };
1015
+ }
1016
+ export { OidcError2, generateDpopKey2, signDpopProof2, oidcClient2, dpopFetch2, OidcEnvError2, oidcFromEnv2, signInRoute2, callbackRoute2, signOutRoute2 };
1017
+
1018
+ //# debugId=5D5F4A6CE23C34A964756E2164756E21
1019
+ //# sourceMappingURL=index-w61bjnkw.js.map