@softistx/alxia-react-router 0.87.0 → 0.88.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.
@@ -1,9 +1,13 @@
1
+ import {
2
+ siteCheck
3
+ } from "../chunks/index-6zx9dfvs.js";
1
4
  import {
2
5
  sessionCookies2
3
6
  } from "../chunks/index-1nw5yeek.js";
4
7
  import {
5
- safeNext2
6
- } from "../chunks/index-0786n4qe.js";
8
+ safeNext2,
9
+ sitePath
10
+ } from "../chunks/index-t68hwhz1.js";
7
11
 
8
12
  // src/oidc/dpop.ts
9
13
  import {
@@ -161,6 +165,135 @@ function dpopBinding(config) {
161
165
  }
162
166
  };
163
167
  }
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
+ }
164
297
  // src/oidc/errors.ts
165
298
  class OidcError extends Error {
166
299
  code;
@@ -397,7 +530,7 @@ async function revokeTokens(input) {
397
530
  // src/oidc/oidc.ts
398
531
  var DEFAULT_ALGORITHMS = ["RS256", "PS256", "ES256", "EdDSA"];
399
532
  var CHALLENGE_SECONDS = 600;
400
- var SAME_FLIGHT_MS = 1e4;
533
+ var MAX_TIMER_MS = 2147483647;
401
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"]));
402
535
  var isKey = (value) => typeof value === "object" && value !== null && ["ES256", "EdDSA"].includes(value["alg"]) && typeof value["jwk"] === "object";
403
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"]));
@@ -411,6 +544,7 @@ function oidcClient(options) {
411
544
  signInPath = "/sign-in",
412
545
  sessionSeconds = 30 * 24 * 3600,
413
546
  refreshSkewSeconds = 60,
547
+ refreshFlightMs = 1e4,
414
548
  clockToleranceSeconds = 30
415
549
  } = options;
416
550
  for (const [label, value] of [
@@ -464,6 +598,9 @@ function oidcClient(options) {
464
598
  if (options.revokeTimeoutMs !== undefined && !(Number.isFinite(options.revokeTimeoutMs) && options.revokeTimeoutMs > 0)) {
465
599
  throw new TypeError("oidcClient(): revokeTimeoutMs must be a positive finite number of milliseconds.");
466
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
+ }
467
604
  const nonces = nonceMemory();
468
605
  const signing = (key) => key ? { key, nonces, now } : undefined;
469
606
  const flights = new Map;
@@ -518,8 +655,7 @@ function oidcClient(options) {
518
655
  target.searchParams.set("next", next);
519
656
  throw redirect(`${target.pathname}${target.search}`, { headers });
520
657
  };
521
- function refreshing(stored) {
522
- const key = stored.refreshToken;
658
+ function refreshing(stored, key) {
523
659
  const flying = flights.get(key);
524
660
  if (flying)
525
661
  return flying;
@@ -534,10 +670,58 @@ function oidcClient(options) {
534
670
  return (await toStored(answer, undefined, stored, stored.dpop)).stored;
535
671
  })();
536
672
  flights.set(key, flight);
537
- const forget = () => setTimeout(() => flights.delete(key), SAME_FLIGHT_MS);
673
+ const forget = () => {
674
+ const timer = setTimeout(() => flights.delete(key), refreshFlightMs);
675
+ if (typeof timer === "object")
676
+ timer.unref();
677
+ };
538
678
  flight.then(forget, () => flights.delete(key));
539
679
  return flight;
540
680
  }
681
+ const stores = new WeakMap;
682
+ async function toUser(stored, headers) {
683
+ const user = {
684
+ claims: decodeJwt(stored.idToken),
685
+ 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);
700
+ return user;
701
+ }
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()) {
708
+ return user;
709
+ }
710
+ const headers = new Headers;
711
+ try {
712
+ if (!stored.refreshToken)
713
+ 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
+ });
723
+ }
724
+ }
541
725
  async function oidcUser(request) {
542
726
  const headers = new Headers;
543
727
  const sealed = cookies.token(request);
@@ -553,32 +737,19 @@ function oidcClient(options) {
553
737
  try {
554
738
  if (!stored.refreshToken)
555
739
  throw new Error("no refresh token");
556
- stored = await refreshing(stored);
740
+ stored = await refreshing(stored, stored.refreshToken);
557
741
  await commit(headers, stored);
558
742
  } catch {
559
743
  if (stored.expiresAt <= now())
560
744
  return null;
561
745
  }
562
746
  }
563
- return {
564
- claims: decodeJwt(stored.idToken),
565
- accessToken: stored.accessToken,
566
- idToken: stored.idToken,
567
- expiresAt: stored.expiresAt,
568
- headers,
569
- dpop: stored.dpop ? dpopBinding({
570
- key: stored.dpop,
571
- thumbprint: await dpopThumbprint(stored.dpop),
572
- accessToken: stored.accessToken,
573
- nonces,
574
- fetch: fetcher,
575
- now
576
- }) : null
577
- };
747
+ return toUser(stored, headers);
578
748
  }
579
749
  return {
580
750
  names: cookies.names,
581
751
  oidcUser,
752
+ refresh,
582
753
  async requireOidcUser(request) {
583
754
  const user = await oidcUser(request);
584
755
  if (user)
@@ -731,12 +902,65 @@ function oidcClient(options) {
731
902
  }
732
903
  };
733
904
  }
905
+ // src/oidc/routes.ts
906
+ import { redirect as redirect2 } from "react-router";
907
+ function signInRoute(oidc, options = {}) {
908
+ return {
909
+ async loader({ request }) {
910
+ await options.guard?.(request);
911
+ return oidc.signIn(request);
912
+ }
913
+ };
914
+ }
915
+ function callbackRoute(oidc, options = {}) {
916
+ const errorPath = sitePath(options.errorPath ?? "/", {
917
+ label: "callbackRoute(): errorPath"
918
+ });
919
+ return {
920
+ async loader({ request }) {
921
+ await options.guard?.(request);
922
+ try {
923
+ return await oidc.callback(request);
924
+ } catch (error) {
925
+ if (!(error instanceof OidcError))
926
+ throw error;
927
+ if (options.onError)
928
+ return options.onError(error);
929
+ return redirect2(`${errorPath}?${new URLSearchParams({ "sign-in-error": error.code })}`, { headers: error.headers });
930
+ }
931
+ }
932
+ };
933
+ }
934
+ function signOutRoute(oidc, options = {}) {
935
+ const sameSite = siteCheck(options.origin);
936
+ const redirectTo = sitePath(options.redirectTo ?? "/", {
937
+ label: "signOutRoute(): redirectTo",
938
+ query: true
939
+ });
940
+ return {
941
+ async action({ request }) {
942
+ await options.guard?.(request);
943
+ sameSite(request);
944
+ return oidc.logout(request);
945
+ },
946
+ async loader({ request }) {
947
+ await options.guard?.(request);
948
+ return redirect2(redirectTo);
949
+ }
950
+ };
951
+ }
734
952
  export {
953
+ OidcEnvError,
735
954
  OidcError,
955
+ callbackRoute,
956
+ dpopFetch,
736
957
  generateDpopKey,
737
958
  oidcClient,
738
- signDpopProof
959
+ oidcFromEnv,
960
+ signDpopProof,
961
+ signInRoute,
962
+ signOutRoute
739
963
  };
740
964
 
741
- //# debugId=4C0ACB0CB06F933D64756E2164756E21
965
+ //# debugId=B7DF2BEADD6B2F6B64756E2164756E21
742
966
  //# sourceMappingURL=index.js.map