@softistx/alxia-react-router 0.88.0 → 0.89.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 (58) hide show
  1. package/README.md +5 -1
  2. package/dist/oidc/callback.d.ts +4 -0
  3. package/dist/oidc/callback.d.ts.map +1 -0
  4. package/dist/oidc/client.d.ts +57 -0
  5. package/dist/oidc/client.d.ts.map +1 -0
  6. package/dist/oidc/context.d.ts +42 -0
  7. package/dist/oidc/context.d.ts.map +1 -0
  8. package/dist/oidc/dpop-fetch.d.ts +2 -1
  9. package/dist/oidc/dpop-fetch.d.ts.map +1 -1
  10. package/dist/oidc/env.d.ts +1 -1
  11. package/dist/oidc/env.d.ts.map +1 -1
  12. package/dist/oidc/index.d.ts +2 -1
  13. package/dist/oidc/index.d.ts.map +1 -1
  14. package/dist/oidc/index.js +550 -486
  15. package/dist/oidc/index.js.map +18 -9
  16. package/dist/oidc/logout.d.ts +4 -0
  17. package/dist/oidc/logout.d.ts.map +1 -0
  18. package/dist/oidc/refresh.d.ts +10 -0
  19. package/dist/oidc/refresh.d.ts.map +1 -0
  20. package/dist/oidc/routes.d.ts +1 -1
  21. package/dist/oidc/routes.d.ts.map +1 -1
  22. package/dist/oidc/session.d.ts +7 -0
  23. package/dist/oidc/session.d.ts.map +1 -0
  24. package/dist/oidc/signin.d.ts +4 -0
  25. package/dist/oidc/signin.d.ts.map +1 -0
  26. package/dist/oidc/stored.d.ts +21 -0
  27. package/dist/oidc/stored.d.ts.map +1 -0
  28. package/dist/oidc/tokens.d.ts +13 -0
  29. package/dist/oidc/tokens.d.ts.map +1 -0
  30. package/dist/oidc/{oidc.d.ts → types.d.ts} +4 -59
  31. package/dist/oidc/{oidc.d.ts.map → types.d.ts.map} +1 -1
  32. package/dist/oidc/user.d.ts +6 -0
  33. package/dist/oidc/user.d.ts.map +1 -0
  34. package/dist/pwa/react/index.d.ts +2 -0
  35. package/dist/pwa/react/index.d.ts.map +1 -1
  36. package/dist/pwa/react/index.js +264 -3
  37. package/dist/pwa/react/index.js.map +6 -3
  38. package/dist/pwa/react/push-status.d.ts +31 -0
  39. package/dist/pwa/react/push-status.d.ts.map +1 -0
  40. package/dist/pwa/react/push-store.d.ts +55 -0
  41. package/dist/pwa/react/push-store.d.ts.map +1 -0
  42. package/dist/pwa/react/use-push-subscription.d.ts +15 -0
  43. package/dist/pwa/react/use-push-subscription.d.ts.map +1 -0
  44. package/dist/pwa/worker/index.d.ts +2 -0
  45. package/dist/pwa/worker/index.d.ts.map +1 -1
  46. package/dist/pwa/worker/index.js +94 -4
  47. package/dist/pwa/worker/index.js.map +7 -6
  48. package/dist/pwa/worker/plan.d.ts +7 -0
  49. package/dist/pwa/worker/plan.d.ts.map +1 -1
  50. package/dist/pwa/worker/push.d.ts +48 -0
  51. package/dist/pwa/worker/push.d.ts.map +1 -0
  52. package/dist/pwa/worker/scope.d.ts +23 -0
  53. package/dist/pwa/worker/scope.d.ts.map +1 -1
  54. package/dist/pwa/worker/start-worker.d.ts +2 -0
  55. package/dist/pwa/worker/start-worker.d.ts.map +1 -1
  56. package/docs/guide/pwa.md +101 -1
  57. package/docs/troubleshooting.md +18 -0
  58. package/package.json +1 -1
@@ -9,6 +9,26 @@ import {
9
9
  sitePath
10
10
  } from "../chunks/index-t68hwhz1.js";
11
11
 
12
+ // src/oidc/errors.ts
13
+ class OidcError 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
+
12
32
  // src/oidc/dpop.ts
13
33
  import {
14
34
  calculateJwkThumbprint,
@@ -165,156 +185,8 @@ function dpopBinding(config) {
165
185
  }
166
186
  };
167
187
  }
168
- // src/oidc/dpop-fetch.ts
169
- function dpopFetch(oidc, user, options = {}) {
170
- let last = user;
171
- return async (input, init) => {
172
- const next = await oidc.refresh(last);
173
- if (next.accessToken !== last.accessToken || next.expiresAt !== last.expiresAt) {
174
- last = next;
175
- options.onUser?.(next);
176
- }
177
- if (last.dpop)
178
- return last.dpop.fetch(input, init);
179
- const headers = new Headers(init?.headers);
180
- headers.set("authorization", `Bearer ${last.accessToken}`);
181
- return last.fetch(String(input), { ...init, headers });
182
- };
183
- }
184
- // src/oidc/env.ts
185
- class OidcEnvError extends Error {
186
- problems;
187
- name = "OidcEnvError";
188
- constructor(problems) {
189
- super(`The OIDC environment is not usable:
190
- ${problems.map((p) => `- ${p}`).join(`
191
- `)}`);
192
- this.problems = problems;
193
- }
194
- }
195
- var LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
196
- var named = (context, suffix) => `${context.prefix}_${suffix}`;
197
- function plain(context, suffix) {
198
- const value = context.env[named(context, suffix)]?.trim();
199
- return value ? value : undefined;
200
- }
201
- function required(context, suffix) {
202
- const value = plain(context, suffix);
203
- if (value === undefined) {
204
- context.problems.push(`${named(context, suffix)} is not set.`);
205
- }
206
- return value;
207
- }
208
- function url(context, suffix, mandatory) {
209
- const value = mandatory ? required(context, suffix) : plain(context, suffix);
210
- if (value === undefined)
211
- return;
212
- const variable = named(context, suffix);
213
- let parsed;
214
- try {
215
- parsed = new URL(value);
216
- } catch {
217
- context.problems.push(`${variable} is not an absolute URL.`);
218
- return;
219
- }
220
- if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && LOOPBACK.has(parsed.hostname))) {
221
- context.problems.push(`${variable} must be an https: URL.`);
222
- return;
223
- }
224
- return value;
225
- }
226
- async function secret(context, suffix, mandatory) {
227
- const direct = plain(context, suffix);
228
- const fileSuffix = `${suffix}_FILE`;
229
- const path = plain(context, fileSuffix);
230
- if (direct !== undefined && path !== undefined) {
231
- context.problems.push(`Set ${named(context, suffix)} or ${named(context, fileSuffix)}, not both.`);
232
- return;
233
- }
234
- if (path === undefined) {
235
- if (direct !== undefined) {
236
- return { value: direct, variable: named(context, suffix) };
237
- }
238
- if (mandatory) {
239
- context.problems.push(`${named(context, fileSuffix)} (or ${named(context, suffix)}) is not set.`);
240
- }
241
- return;
242
- }
243
- const variable = named(context, fileSuffix);
244
- let text;
245
- try {
246
- const { mode } = await context.statFile(path);
247
- if ((mode & 63) !== 0) {
248
- 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.`);
249
- return;
250
- }
251
- text = await context.readFile(path);
252
- } catch {
253
- context.problems.push(`${variable} names a file that cannot be read: check the path and its permissions.`);
254
- return;
255
- }
256
- const value = text.trim();
257
- if (value === "") {
258
- context.problems.push(`${variable} names an empty file.`);
259
- return;
260
- }
261
- if (/\s/.test(value)) {
262
- context.problems.push(`${variable} names a file with whitespace inside: it must hold one value.`);
263
- return;
264
- }
265
- return { value, variable };
266
- }
267
- async function oidcFromEnv(source = {}) {
268
- const context = {
269
- env: source.env ?? process.env,
270
- prefix: source.prefix ?? "OIDC",
271
- problems: [],
272
- readFile: source.readFile ?? ((path) => Bun.file(path).text()),
273
- statFile: source.statFile ?? ((path) => Bun.file(path).stat())
274
- };
275
- const issuer = url(context, "ISSUER", true);
276
- const clientId = required(context, "CLIENT_ID");
277
- const clientSecret = await secret(context, "CLIENT_SECRET", false);
278
- const redirectUri = url(context, "REDIRECT_URI", true);
279
- const postLogoutRedirectUri = url(context, "POST_LOGOUT_REDIRECT_URI", false);
280
- const session = await secret(context, "SESSION_SECRET", true);
281
- if (session !== undefined && session.value.length < 32) {
282
- context.problems.push(`The session secret must be 32 characters or more (${session.variable}).`);
283
- }
284
- if (context.problems.length > 0 || issuer === undefined || clientId === undefined || redirectUri === undefined || session === undefined) {
285
- throw new OidcEnvError(context.problems);
286
- }
287
- return {
288
- issuer,
289
- clientId,
290
- clientSecret: clientSecret?.value,
291
- redirectUri,
292
- secret: session.value,
293
- name: plain(context, "COOKIE_NAME") ?? "oidc",
294
- postLogoutRedirectUri
295
- };
296
- }
297
- // src/oidc/errors.ts
298
- class OidcError extends Error {
299
- code;
300
- headers;
301
- name = "OidcError";
302
- constructor(code, message, headers = new Headers, options) {
303
- super(message, options);
304
- this.code = code;
305
- this.headers = headers;
306
- }
307
- }
308
- // src/oidc/oidc.ts
309
- import { redirect } from "react-router";
310
188
 
311
189
  // src/oidc/flow.ts
312
- import {
313
- createLocalJWKSet,
314
- decodeJwt,
315
- errors as joseErrors,
316
- jwtVerify
317
- } from "jose";
318
190
  var DISCOVERY_TTL = 60 * 60 * 1000;
319
191
  var JWKS_TTL = 10 * 60 * 1000;
320
192
  var isRecord = (value) => typeof value === "object" && value !== null;
@@ -497,44 +369,154 @@ async function pushRequest(fetcher, endpoint, client, params, dpop) {
497
369
  return answer["request_uri"];
498
370
  }
499
371
 
500
- // src/oidc/revoke.ts
501
- async function revokeTokens(input) {
502
- const { stored } = input;
503
- const signal = AbortSignal.timeout(input.timeoutMs);
504
- const timedOut = new Promise((_, reject) => {
505
- signal.addEventListener("abort", () => reject(new OidcError("revoke-failed", `The revocation endpoint did not answer within ${input.timeoutMs} ms.`)), { once: true });
506
- });
507
- timedOut.catch(() => {
508
- return;
509
- });
510
- const tokens = [
511
- ...stored.refreshToken ? [[stored.refreshToken, "refresh_token"]] : [],
512
- [stored.accessToken, "access_token"]
513
- ];
514
- for (const [token, hint] of tokens) {
515
- try {
516
- await Promise.race([
517
- revokeRequest(input.fetcher, input.endpoint, input.client, { token, token_type_hint: hint }, input.signing(stored.dpop), signal),
518
- timedOut
519
- ]);
520
- } catch (error) {
521
- input.report(error instanceof OidcError ? error : new OidcError("revoke-failed", "Revocation failed.", undefined, {
522
- cause: error
523
- }));
524
- if (signal.aborted)
525
- return;
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 OidcError("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 OidcError("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 OidcError("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 OidcError(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 OidcError) {
478
+ for (const value of cleared().getSetCookie()) {
479
+ error.headers.append("Set-Cookie", value);
480
+ }
526
481
  }
482
+ throw error;
527
483
  }
528
484
  }
529
485
 
530
- // src/oidc/oidc.ts
486
+ // src/oidc/context.ts
531
487
  var DEFAULT_ALGORITHMS = ["RS256", "PS256", "ES256", "EdDSA"];
532
488
  var CHALLENGE_SECONDS = 600;
533
489
  var MAX_TIMER_MS = 2147483647;
534
- 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"]));
535
- var isKey = (value) => typeof value === "object" && value !== null && ["ES256", "EdDSA"].includes(value["alg"]) && typeof value["jwk"] === "object";
536
- 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"]));
537
- function oidcClient(options) {
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);
538
520
  const {
539
521
  issuer,
540
522
  clientId,
@@ -547,17 +529,6 @@ function oidcClient(options) {
547
529
  refreshFlightMs = 1e4,
548
530
  clockToleranceSeconds = 30
549
531
  } = options;
550
- for (const [label, value] of [
551
- ["issuer", issuer],
552
- ["clientId", clientId],
553
- ["redirectUri", redirectUri]
554
- ]) {
555
- if (!value)
556
- throw new TypeError(`oidcClient(): ${label} is required.`);
557
- }
558
- if (typeof secret !== "string" || secret.length < 32) {
559
- throw new TypeError("oidcClient(): secret must be a string of at least 32 characters.");
560
- }
561
532
  const {
562
533
  client_id: _id,
563
534
  client_secret: _secret,
@@ -578,328 +549,421 @@ function oidcClient(options) {
578
549
  });
579
550
  const flowSeal = sealer(secret, "flow");
580
551
  const tokenSeal = sealer(secret, "tokens");
552
+ const fetcher = options.fetch ?? ((input, init) => fetch(input, init));
581
553
  const issuerApi = issuerClient({
582
554
  issuer,
583
- fetch: options.fetch ?? ((input, init) => fetch(input, init)),
555
+ fetch: fetcher,
584
556
  now,
585
557
  algorithms: [...options.algorithms ?? DEFAULT_ALGORITHMS],
586
558
  clockToleranceSeconds
587
559
  });
588
- const fetcher = options.fetch ?? ((input, init) => fetch(input, init));
589
- const client = { id: clientId, secret: clientSecret };
590
560
  const par = options.par ?? "auto";
591
- if (!["auto", "always", "never"].includes(par)) {
592
- throw new TypeError("oidcClient(): par must be 'auto', 'always' or 'never'.");
593
- }
594
561
  const dpopAlg = options.dpop ? options.dpop.alg ?? "ES256" : undefined;
595
- if (dpopAlg !== undefined && !["ES256", "EdDSA"].includes(dpopAlg)) {
596
- throw new TypeError("oidcClient(): dpop.alg must be 'ES256' or 'EdDSA'.");
597
- }
598
- if (options.revokeTimeoutMs !== undefined && !(Number.isFinite(options.revokeTimeoutMs) && options.revokeTimeoutMs > 0)) {
599
- throw new TypeError("oidcClient(): revokeTimeoutMs must be a positive finite number of milliseconds.");
600
- }
601
- if (!(Number.isFinite(refreshFlightMs) && refreshFlightMs >= 0 && refreshFlightMs <= MAX_TIMER_MS)) {
602
- throw new TypeError("oidcClient(): refreshFlightMs must be a finite number of milliseconds, from 0 to 2147483647.");
603
- }
562
+ checkTuning(options, par, dpopAlg, refreshFlightMs);
604
563
  const nonces = nonceMemory();
605
- const signing = (key) => key ? { key, nonces, now } : undefined;
606
- const flights = new Map;
607
- const setCookie = (headers, value) => headers.append("Set-Cookie", value);
608
- async function toStored(response, nonce, previous, key) {
609
- const dpop = key && (String(response.token_type).toLowerCase() === "dpop" || previous?.dpop !== undefined && response.token_type === undefined) ? key : undefined;
610
- if (!response.id_token && previous) {
611
- const kept = decodeJwt(previous.idToken);
612
- return {
613
- claims: kept,
614
- stored: {
615
- idToken: previous.idToken,
616
- dpop,
617
- accessToken: response.access_token,
618
- refreshToken: response.refresh_token ?? previous.refreshToken,
619
- expiresAt: typeof response.expires_in === "number" ? now() + response.expires_in * 1000 : now() + 300000
620
- }
621
- };
622
- }
623
- const idToken = response.id_token;
624
- if (!idToken) {
625
- throw new OidcError("invalid-id-token", "The token endpoint sent no id token.");
626
- }
627
- const claims = await issuerApi.verifyIdToken(idToken, clientId, nonce);
628
- if (previous && decodeJwt(previous.idToken).sub !== claims.sub) {
629
- throw new OidcError("invalid-id-token", "A refresh changed the user.");
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 OidcError("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 OidcError ? error : new OidcError("revoke-failed", "Revocation failed.", undefined, {
613
+ cause: error
614
+ }));
615
+ if (signal.aborted)
616
+ return;
630
617
  }
631
- const expiresAt = typeof response.expires_in === "number" ? now() + response.expires_in * 1000 : (claims["exp"] ?? 0) * 1000;
632
- return {
633
- claims,
634
- stored: {
635
- idToken,
636
- dpop,
637
- accessToken: response.access_token,
638
- refreshToken: response.refresh_token ?? previous?.refreshToken,
639
- expiresAt
640
- }
641
- };
642
618
  }
643
- async function commit(headers, stored) {
644
- const lifetime = stored.refreshToken ? sessionSeconds : Math.max(0, (stored.expiresAt - now()) / 1000);
645
- const cookie = cookies.commit(await tokenSeal.seal(stored), new Date(now() + lifetime * 1000), now());
646
- if (cookie.length > 4096) {
647
- throw new OidcError("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.`);
648
- }
649
- setCookie(headers, cookie);
650
- }
651
- const toSignIn = (request, headers) => {
652
- const url = new URL(request.url);
653
- const next = safeNext2(`${url.pathname}${url.search}`);
654
- const target = new URL(signInPath, url);
655
- target.searchParams.set("next", next);
656
- throw redirect(`${target.pathname}${target.search}`, { headers });
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 {}
657
628
  };
658
- function refreshing(stored, key) {
659
- const flying = flights.get(key);
660
- if (flying)
661
- return flying;
662
- const flight = (async () => {
663
- const document = await issuerApi.discover();
664
- const answer = await tokenRequest(fetcher, document.token_endpoint, client, {
665
- ...extraTokenParams,
666
- grant_type: "refresh_token",
667
- refresh_token: key,
668
- scope: scopes.join(" ")
669
- }, "refresh-failed", signing(stored.dpop));
670
- return (await toStored(answer, undefined, stored, stored.dpop)).stored;
671
- })();
672
- flights.set(key, flight);
673
- const forget = () => {
674
- const timer = setTimeout(() => flights.delete(key), refreshFlightMs);
675
- if (typeof timer === "object")
676
- timer.unref();
677
- };
678
- flight.then(forget, () => flights.delete(key));
679
- return flight;
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 OidcError("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);
680
661
  }
681
- const stores = new WeakMap;
682
- async function toUser(stored, headers) {
683
- const user = {
684
- claims: decodeJwt(stored.idToken),
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),
685
677
  accessToken: stored.accessToken,
686
- idToken: stored.idToken,
687
- expiresAt: stored.expiresAt,
688
- headers,
689
- dpop: stored.dpop ? dpopBinding({
690
- key: stored.dpop,
691
- thumbprint: await dpopThumbprint(stored.dpop),
692
- accessToken: stored.accessToken,
693
- nonces,
694
- fetch: fetcher,
695
- now
696
- }) : null,
697
- fetch: fetcher
698
- };
699
- stores.set(user, stored);
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()) {
700
719
  return user;
701
720
  }
702
- async function refresh(user, refreshOptions = {}) {
703
- const stored = stores.get(user);
704
- if (!stored) {
705
- throw new TypeError("oidc.refresh(): the user was not returned by this client.");
706
- }
707
- if (!refreshOptions.force && stored.expiresAt - refreshSkewSeconds * 1000 > now()) {
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())
708
730
  return user;
709
- }
710
- const headers = new Headers;
731
+ throw cause instanceof OidcError ? cause : new OidcError("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()) {
711
751
  try {
712
752
  if (!stored.refreshToken)
713
753
  throw new Error("no refresh token");
714
- const next = await refreshing(stored, stored.refreshToken);
715
- await commit(headers, next);
716
- return toUser(next, headers);
717
- } catch (cause) {
718
- if (stored.expiresAt > now())
719
- return user;
720
- throw cause instanceof OidcError ? cause : new OidcError("refresh-failed", "The refresh failed.", undefined, {
721
- cause
722
- });
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;
723
759
  }
724
760
  }
725
- async function oidcUser(request) {
726
- const headers = new Headers;
727
- const sealed = cookies.token(request);
728
- if (!sealed)
729
- return null;
730
- const opened = await tokenSeal.open(sealed);
731
- if (!isStored(opened)) {
732
- setCookie(headers, cookies.destroy());
733
- return null;
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 generateDpopKey(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 OidcError("par-failed", "Pushed authorization requests are required but the issuer publishes no pushed_authorization_request_endpoint.");
734
812
  }
735
- let stored = opened;
736
- if (stored.expiresAt - refreshSkewSeconds * 1000 <= now()) {
737
- try {
738
- if (!stored.refreshToken)
739
- throw new Error("no refresh token");
740
- stored = await refreshing(stored, stored.refreshToken);
741
- await commit(headers, stored);
742
- } catch {
743
- if (stored.expiresAt <= now())
744
- return null;
745
- }
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);
746
819
  }
747
- return toUser(stored, headers);
748
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 oidcClient(options) {
829
+ const ctx = createContext(options);
749
830
  return {
750
- names: cookies.names,
751
- oidcUser,
752
- refresh,
753
- async requireOidcUser(request) {
754
- const user = await oidcUser(request);
755
- if (user)
756
- return user;
757
- const headers = new Headers;
758
- if (cookies.token(request))
759
- setCookie(headers, cookies.destroy());
760
- return toSignIn(request, headers);
761
- },
762
- async signIn(request) {
763
- const document = await issuerApi.discover();
764
- const url = new URL(request.url);
765
- const flow = {
766
- state: randomToken(),
767
- nonce: randomToken(),
768
- verifier: randomToken(48),
769
- next: safeNext2(url.searchParams.get("next")),
770
- exp: now() + CHALLENGE_SECONDS * 1000,
771
- dpop: dpopAlg ? await generateDpopKey(dpopAlg) : undefined
772
- };
773
- const authRequest = {
774
- ...options.authorizationParams,
775
- response_type: "code",
776
- client_id: clientId,
777
- redirect_uri: redirectUri,
778
- scope: scopes.join(" "),
779
- state: flow.state,
780
- nonce: flow.nonce,
781
- code_challenge: await s256(flow.verifier),
782
- code_challenge_method: "S256",
783
- ...flow.dpop && { dpop_jkt: await dpopThumbprint(flow.dpop) }
784
- };
785
- const endpoint = document.pushed_authorization_request_endpoint;
786
- const push = par === "always" || par === "auto" && document.require_pushed_authorization_requests === true;
787
- const target = new URL(document.authorization_endpoint);
788
- if (push) {
789
- if (!endpoint) {
790
- throw new OidcError("par-failed", "Pushed authorization requests are required but the issuer publishes no pushed_authorization_request_endpoint.");
791
- }
792
- const requestUri = await pushRequest(fetcher, endpoint, client, authRequest, signing(flow.dpop));
793
- target.searchParams.set("client_id", clientId);
794
- target.searchParams.set("request_uri", requestUri);
795
- } else {
796
- for (const [key, value] of Object.entries(authRequest)) {
797
- target.searchParams.set(key, value);
798
- }
799
- }
800
- const headers = new Headers({ "Cache-Control": "no-store" });
801
- setCookie(headers, cookies.commitChallenge(await flowSeal.seal(flow), null, now()));
802
- headers.set("Location", target.toString());
803
- return new Response(null, { status: 302, headers });
804
- },
805
- async callback(request) {
806
- const cleared = () => {
807
- const headers = new Headers;
808
- setCookie(headers, cookies.destroyChallenge());
809
- return headers;
810
- };
811
- const fail = (code, message) => new OidcError(code, message, cleared());
812
- const url = new URL(request.url);
813
- const sealed = cookies.challengeOf(request);
814
- const flow = sealed ? await flowSeal.open(sealed) : null;
815
- if (!isFlow(flow)) {
816
- throw fail("missing-challenge", "The sign-in challenge cookie is missing or unreadable (a second tab, an expired page or a blocked cookie).");
817
- }
818
- if (flow.exp <= now()) {
819
- throw fail("challenge-expired", "The sign-in took too long; start again.");
820
- }
821
- const returned = url.searchParams.get("state");
822
- if (returned === null || !sameText(returned, flow.state)) {
823
- throw fail("state-mismatch", "The returned state is not the one this sign-in sent.");
824
- }
825
- const failure = url.searchParams.get("error");
826
- if (failure) {
827
- const description = url.searchParams.get("error_description");
828
- throw fail("provider-error", `The issuer refused: ${failure}${description ? ` (${description})` : ""}.`);
829
- }
830
- const claimedIssuer = url.searchParams.get("iss");
831
- if (claimedIssuer !== null && claimedIssuer !== issuer) {
832
- throw fail("issuer-mismatch", "The callback names another issuer.");
833
- }
834
- const code = url.searchParams.get("code");
835
- if (!code)
836
- throw fail("missing-code", "The callback carries no code.");
837
- try {
838
- const document = await issuerApi.discover();
839
- const answer = await tokenRequest(fetcher, document.token_endpoint, client, {
840
- ...extraTokenParams,
841
- grant_type: "authorization_code",
842
- code,
843
- redirect_uri: redirectUri,
844
- code_verifier: flow.verifier
845
- }, "token-exchange-failed", signing(flow.dpop));
846
- const { stored } = await toStored(answer, flow.nonce, undefined, flow.dpop);
847
- const headers = cleared();
848
- await commit(headers, stored);
849
- headers.set("Location", safeNext2(flow.next));
850
- headers.set("Cache-Control", "no-store");
851
- return new Response(null, { status: 302, headers });
852
- } catch (error) {
853
- if (error instanceof OidcError) {
854
- for (const value of cleared().getSetCookie()) {
855
- error.headers.append("Set-Cookie", value);
856
- }
857
- }
858
- throw error;
859
- }
860
- },
861
- async logout(request) {
862
- const report = (error) => {
863
- try {
864
- options.onRevokeError?.(error);
865
- } catch {}
866
- };
867
- const headers = new Headers({ "Cache-Control": "no-store" });
868
- setCookie(headers, cookies.destroy());
869
- const sealed = cookies.token(request);
870
- const opened = sealed ? await tokenSeal.open(sealed) : null;
871
- const document = await issuerApi.discover().catch((cause) => {
872
- if (options.revokeOnLogout) {
873
- report(new OidcError("discovery-failed", "Discovery failed at logout, so the tokens were not revoked.", undefined, { cause }));
874
- }
875
- return null;
876
- });
877
- if (options.revokeOnLogout && document?.revocation_endpoint && isStored(opened)) {
878
- await revokeTokens({
879
- fetcher,
880
- client,
881
- endpoint: document.revocation_endpoint,
882
- stored: opened,
883
- signing,
884
- timeoutMs: options.revokeTimeoutMs ?? 3000,
885
- report
886
- });
887
- }
888
- const endpoint = document?.end_session_endpoint;
889
- if (!endpoint) {
890
- headers.set("Location", options.postLogoutRedirectUri ?? "/");
891
- return new Response(null, { status: 302, headers });
892
- }
893
- const target = new URL(endpoint);
894
- if (isStored(opened))
895
- target.searchParams.set("id_token_hint", opened.idToken);
896
- target.searchParams.set("client_id", clientId);
897
- if (options.postLogoutRedirectUri) {
898
- target.searchParams.set("post_logout_redirect_uri", options.postLogoutRedirectUri);
899
- }
900
- headers.set("Location", target.toString());
901
- return new Response(null, { status: 302, headers });
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 dpopFetch(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);
902
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 OidcEnvError 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 oidcFromEnv(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 OidcEnvError(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
903
967
  };
904
968
  }
905
969
  // src/oidc/routes.ts
@@ -962,5 +1026,5 @@ export {
962
1026
  signOutRoute
963
1027
  };
964
1028
 
965
- //# debugId=B7DF2BEADD6B2F6B64756E2164756E21
1029
+ //# debugId=C1E1692B5010A35F64756E2164756E21
966
1030
  //# sourceMappingURL=index.js.map