@fluixi/oauth2 1.0.0-alpha.11 → 1.0.0-alpha.110

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 (92) hide show
  1. package/dist/api-guard.cjs +8 -3
  2. package/dist/api-guard.mjs +9 -135
  3. package/dist/backchannel.cjs +467 -0
  4. package/dist/backchannel.d.ts +39 -0
  5. package/dist/backchannel.d.ts.map +1 -0
  6. package/dist/backchannel.js +97 -0
  7. package/dist/backchannel.mjs +19 -0
  8. package/dist/browser.cjs +6 -1
  9. package/dist/browser.mjs +10 -702
  10. package/dist/callback.cjs +2 -2
  11. package/dist/callback.d.ts +2 -2
  12. package/dist/callback.js +3 -3
  13. package/dist/callback.mjs +17 -24
  14. package/dist/{dpop-YPGCGL7S.mjs → chunk-27BGFJIY.mjs} +6 -6
  15. package/dist/chunk-2GLWT7XH.mjs +143 -0
  16. package/dist/chunk-3EICMAF7.mjs +22 -0
  17. package/dist/chunk-4OHJTTX7.mjs +398 -0
  18. package/dist/chunk-4QRYJ4TN.mjs +86 -0
  19. package/dist/chunk-5WX3EV2W.mjs +78 -0
  20. package/dist/chunk-7AMC336S.mjs +52 -0
  21. package/dist/chunk-AAN3YN4S.mjs +63 -0
  22. package/dist/chunk-AWVECOG7.mjs +404 -0
  23. package/dist/chunk-GN5SERAQ.mjs +189 -0
  24. package/dist/chunk-KIXTZEEW.mjs +80 -0
  25. package/dist/chunk-KVW2S6VY.mjs +36 -0
  26. package/dist/chunk-MHWZTXZZ.mjs +9 -0
  27. package/dist/chunk-QC2FFASM.mjs +67 -0
  28. package/dist/chunk-SJOBQPG6.mjs +77 -0
  29. package/dist/chunk-VCNXQCIH.mjs +26 -0
  30. package/dist/chunk-XQJTQV3C.mjs +91 -0
  31. package/dist/client-auth.mjs +6 -78
  32. package/dist/discovery.cjs +6 -1
  33. package/dist/discovery.d.ts.map +1 -1
  34. package/dist/discovery.js +6 -1
  35. package/dist/discovery.mjs +6 -59
  36. package/dist/dpop-store.mjs +6 -118
  37. package/dist/dpop.mjs +11 -95
  38. package/dist/env-config.cjs +1 -1
  39. package/dist/env-config.mjs +5 -214
  40. package/dist/env-credentials.mjs +5 -47
  41. package/dist/index.cjs +108 -8
  42. package/dist/index.d.ts +2 -0
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +1 -0
  45. package/dist/index.mjs +50 -912
  46. package/dist/module.cjs +1 -1
  47. package/dist/module.mjs +5 -20
  48. package/dist/pkce.mjs +11 -56
  49. package/dist/presets.cjs +1 -1
  50. package/dist/presets.mjs +5 -214
  51. package/dist/return-to.mjs +4 -22
  52. package/dist/roles.cjs +1 -1
  53. package/dist/roles.d.ts +1 -1
  54. package/dist/roles.js +1 -1
  55. package/dist/roles.mjs +4 -32
  56. package/dist/server-client.mjs +7 -107
  57. package/dist/server.cjs +795 -153
  58. package/dist/server.d.ts +85 -4
  59. package/dist/server.d.ts.map +1 -1
  60. package/dist/server.js +577 -75
  61. package/dist/server.mjs +442 -310
  62. package/dist/service-client.cjs +7 -2
  63. package/dist/service-client.mjs +16 -133
  64. package/dist/service.cjs +104 -5
  65. package/dist/service.d.ts +1 -1
  66. package/dist/service.d.ts.map +1 -1
  67. package/dist/service.js +38 -6
  68. package/dist/service.mjs +14 -879
  69. package/dist/session-monitor.cjs +98 -0
  70. package/dist/session-monitor.d.ts +32 -0
  71. package/dist/session-monitor.d.ts.map +1 -0
  72. package/dist/session-monitor.js +104 -0
  73. package/dist/session-monitor.mjs +7 -0
  74. package/dist/tokens.cjs +1 -1
  75. package/dist/tokens.d.ts +2 -2
  76. package/dist/tokens.d.ts.map +1 -1
  77. package/dist/tokens.js +1 -1
  78. package/dist/tokens.mjs +5 -4
  79. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  80. package/dist/types.d.ts +8 -0
  81. package/dist/types.d.ts.map +1 -1
  82. package/dist/types.mjs +4 -9
  83. package/dist/verify.cjs +15 -5
  84. package/dist/verify.d.ts +2 -2
  85. package/dist/verify.js +2 -2
  86. package/dist/verify.mjs +17 -580
  87. package/package.json +23 -17
  88. package/dist/browser-N432SMC3.mjs +0 -3545
  89. package/dist/chunk-4TPZVJSR.mjs +0 -10
  90. package/dist/chunk-ZVDC3JW7.mjs +0 -15
  91. package/dist/dpop-DYUR2CH2.mjs +0 -100
  92. /package/dist/{chunk-OGSFNTKA.mjs → chunk-AXPSPTNP.mjs} +0 -0
@@ -1,4 +1,4 @@
1
- /*! @fluixi/oauth2 v1.0.0-alpha.11 | (c) 2026 Ibrahima Touré and Fluixi contributors | MIT */
1
+ /*! @fluixi/oauth2 v1.0.0-alpha.110 | (c) 2026 Ibrahima Touré and Fluixi contributors | MIT */
2
2
  "use strict";
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
@@ -126,8 +126,12 @@ async function discover(issuer, fetcher = fetch) {
126
126
  try {
127
127
  response = await fetcher(documentUrl(issuer));
128
128
  } catch (cause) {
129
+ const why = cause instanceof Error ? cause.message : String(cause);
129
130
  throw new OAuthError(
130
- `Could not read the discovery document at ${documentUrl(issuer)}. In a browser this is usually the provider refusing a cross-origin read: give \`endpoints\` directly, or resolve them on a server. (${cause instanceof Error ? cause.message : String(cause)})`,
131
+ typeof window === "undefined" ? (
132
+ // On a server nothing blocks the read: the provider is down, or the address is wrong.
133
+ `Could not reach the provider at ${documentUrl(issuer)}: is it running, and is the issuer right? (${why})`
134
+ ) : `Could not read the discovery document at ${documentUrl(issuer)}. In a browser this is usually the provider refusing a cross-origin read: give \`endpoints\` directly, or resolve them on a server. (${why})`,
131
135
  "discovery_unreachable"
132
136
  );
133
137
  }
@@ -152,6 +156,7 @@ async function discover(issuer, fetcher = fetch) {
152
156
  jwks: doc.jwks_uri,
153
157
  introspection: doc.introspection_endpoint,
154
158
  revocation: doc.revocation_endpoint,
159
+ checkSession: doc.check_session_iframe,
155
160
  issuer: doc.issuer ?? issuer
156
161
  };
157
162
  })();
@@ -1,136 +1,19 @@
1
- /*! @fluixi/oauth2 v1.0.0-alpha.11 | (c) 2026 Ibrahima Touré and Fluixi contributors | MIT */
2
- import "./chunk-4TPZVJSR.mjs";
3
-
4
- // src/types.ts
5
- var OAuthError = class extends Error {
6
- constructor(message, code, description) {
7
- super(message);
8
- this.code = code;
9
- this.description = description;
10
- this.name = "OAuthError";
11
- }
12
- };
13
-
14
- // src/client-auth.ts
15
- var CANONICAL = {
16
- basic: "client_secret_basic",
17
- body: "client_secret_post",
18
- client_secret_basic: "client_secret_basic",
19
- client_secret_post: "client_secret_post",
20
- private_key_jwt: "private_key_jwt",
21
- none: "none"
22
- };
23
- function resolveMethod(auth) {
24
- if (auth.method) return CANONICAL[auth.method] ?? "client_secret_basic";
25
- if (auth.privateKey) return "private_key_jwt";
26
- return auth.clientSecret ? "client_secret_basic" : "none";
27
- }
28
- function assertUsable(auth, who) {
29
- if (!auth.clientId) throw new Error(`[fluixi/oauth2] ${who} needs a clientId.`);
30
- const method = resolveMethod(auth);
31
- if (method === "private_key_jwt" && !auth.privateKey) {
32
- throw new Error(
33
- `[fluixi/oauth2] ${who}: private_key_jwt needs \`privateKey\`, the JWK whose public half the provider holds.`
34
- );
35
- }
36
- if ((method === "client_secret_basic" || method === "client_secret_post") && !auth.clientSecret) {
37
- throw new Error(
38
- `[fluixi/oauth2] ${who}: ${method} needs a \`clientSecret\`. A public client should use \`method: 'none'\`, which PKCE is what protects.`
39
- );
40
- }
41
- return method;
42
- }
43
- async function loadJose() {
44
- try {
45
- return await import("./browser-N432SMC3.mjs");
46
- } catch {
47
- throw new OAuthError(
48
- "private_key_jwt needs `jose`. Install it: npm i jose. It is an optional peer, so a client using a secret does not carry it.",
49
- "jose_missing"
50
- );
51
- }
52
- }
53
- async function signAssertion(auth, endpoint) {
54
- const jose = await loadJose();
55
- const alg = auth.assertionAlgorithm ?? "RS256";
56
- const key = await jose.importJWK(auth.privateKey, alg);
57
- const kid = auth.keyId ?? auth.privateKey.kid;
58
- return new jose.SignJWT({}).setProtectedHeader(kid ? { alg, kid } : { alg }).setIssuer(auth.clientId).setSubject(auth.clientId).setAudience(endpoint).setJti(crypto.randomUUID()).setIssuedAt().setExpirationTime("1m").sign(key);
59
- }
60
- async function applyClientAuth(auth, endpoint, headers, form) {
61
- switch (resolveMethod(auth)) {
62
- case "client_secret_basic": {
63
- const pair = `${encodeURIComponent(auth.clientId)}:${encodeURIComponent(auth.clientSecret)}`;
64
- headers.authorization = `Basic ${btoa(pair)}`;
65
- break;
66
- }
67
- case "client_secret_post":
68
- form.set("client_id", auth.clientId);
69
- form.set("client_secret", auth.clientSecret);
70
- break;
71
- case "private_key_jwt":
72
- form.set("client_id", auth.clientId);
73
- form.set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
74
- form.set("client_assertion", await signAssertion(auth, endpoint));
75
- break;
76
- case "none":
77
- form.set("client_id", auth.clientId);
78
- break;
79
- }
80
- }
81
-
82
- // src/discovery.ts
83
- var cache = /* @__PURE__ */ new Map();
84
- function documentUrl(issuer) {
85
- return `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`;
86
- }
87
- async function discover(issuer, fetcher = fetch) {
88
- const cached = cache.get(issuer);
89
- if (cached) return cached;
90
- const pending = (async () => {
91
- let response;
92
- try {
93
- response = await fetcher(documentUrl(issuer));
94
- } catch (cause) {
95
- throw new OAuthError(
96
- `Could not read the discovery document at ${documentUrl(issuer)}. In a browser this is usually the provider refusing a cross-origin read: give \`endpoints\` directly, or resolve them on a server. (${cause instanceof Error ? cause.message : String(cause)})`,
97
- "discovery_unreachable"
98
- );
99
- }
100
- if (!response.ok) {
101
- throw new OAuthError(
102
- `Discovery failed for ${issuer}: ${response.status}`,
103
- "discovery_failed"
104
- );
105
- }
106
- const doc = await response.json();
107
- if (!doc.authorization_endpoint || !doc.token_endpoint) {
108
- throw new OAuthError(
109
- `${issuer} published a discovery document with no authorization or token endpoint.`,
110
- "discovery_incomplete"
111
- );
112
- }
113
- return {
114
- authorization: doc.authorization_endpoint,
115
- token: doc.token_endpoint,
116
- userinfo: doc.userinfo_endpoint,
117
- endSession: doc.end_session_endpoint,
118
- jwks: doc.jwks_uri,
119
- introspection: doc.introspection_endpoint,
120
- revocation: doc.revocation_endpoint,
121
- issuer: doc.issuer ?? issuer
122
- };
123
- })();
124
- cache.set(issuer, pending);
125
- pending.catch(() => cache.delete(issuer));
126
- return pending;
127
- }
128
-
129
- // src/pkce.ts
130
- function expiryFrom(expiresIn, now = Date.now()) {
131
- const seconds = typeof expiresIn === "number" ? expiresIn : Number(expiresIn);
132
- return Number.isFinite(seconds) && seconds > 0 ? now + seconds * 1e3 : void 0;
133
- }
1
+ /*! @fluixi/oauth2 v1.0.0-alpha.110 | (c) 2026 Ibrahima Touré and Fluixi contributors | MIT */
2
+ import {
3
+ expiryFrom
4
+ } from "./chunk-QC2FFASM.mjs";
5
+ import {
6
+ applyClientAuth,
7
+ assertUsable,
8
+ resolveMethod
9
+ } from "./chunk-SJOBQPG6.mjs";
10
+ import {
11
+ discover
12
+ } from "./chunk-AAN3YN4S.mjs";
13
+ import {
14
+ OAuthError
15
+ } from "./chunk-AXPSPTNP.mjs";
16
+ import "./chunk-7P6ASYW6.mjs";
134
17
 
135
18
  // src/service-client.ts
136
19
  function createServiceClient(options) {
package/dist/service.cjs CHANGED
@@ -334,8 +334,12 @@ async function discover(issuer, fetcher = fetch) {
334
334
  try {
335
335
  response = await fetcher(documentUrl(issuer));
336
336
  } catch (cause) {
337
+ const why = cause instanceof Error ? cause.message : String(cause);
337
338
  throw new OAuthError(
338
- `Could not read the discovery document at ${documentUrl(issuer)}. In a browser this is usually the provider refusing a cross-origin read: give \`endpoints\` directly, or resolve them on a server. (${cause instanceof Error ? cause.message : String(cause)})`,
339
+ typeof window === "undefined" ? (
340
+ // On a server nothing blocks the read: the provider is down, or the address is wrong.
341
+ `Could not reach the provider at ${documentUrl(issuer)}: is it running, and is the issuer right? (${why})`
342
+ ) : `Could not read the discovery document at ${documentUrl(issuer)}. In a browser this is usually the provider refusing a cross-origin read: give \`endpoints\` directly, or resolve them on a server. (${why})`,
339
343
  "discovery_unreachable"
340
344
  );
341
345
  }
@@ -360,6 +364,7 @@ async function discover(issuer, fetcher = fetch) {
360
364
  jwks: doc.jwks_uri,
361
365
  introspection: doc.introspection_endpoint,
362
366
  revocation: doc.revocation_endpoint,
367
+ checkSession: doc.check_session_iframe,
363
368
  issuer: doc.issuer ?? issuer
364
369
  };
365
370
  })();
@@ -815,6 +820,81 @@ function createServerClient(config, fetcher = fetch) {
815
820
  };
816
821
  }
817
822
 
823
+ // src/session-monitor.ts
824
+ var SETTLE_MS = 15e3;
825
+ var GUARD_KEY = "fx-session-check";
826
+ function recentlyActed() {
827
+ try {
828
+ return Date.now() - Number(sessionStorage.getItem(GUARD_KEY) ?? 0) < SETTLE_MS;
829
+ } catch {
830
+ return false;
831
+ }
832
+ }
833
+ function markActed() {
834
+ try {
835
+ sessionStorage.setItem(GUARD_KEY, String(Date.now()));
836
+ } catch {
837
+ }
838
+ }
839
+ function watchProviderSession(options = {}) {
840
+ if (typeof window === "undefined" || typeof document === "undefined") return () => {
841
+ };
842
+ const base = (options.basePath ?? "/auth").replace(/\/$/, "");
843
+ const fetcher = options.fetcher ?? fetch;
844
+ const onChange = options.onChange ?? (() => {
845
+ const login = new URLSearchParams({ prompt: "none", returnTo: location.pathname + location.search });
846
+ location.assign(`${base}/login?${login}`);
847
+ });
848
+ let stopped = false;
849
+ const cleanups = [];
850
+ const stop = () => {
851
+ stopped = true;
852
+ for (const cleanup of cleanups.splice(0)) cleanup();
853
+ };
854
+ void (async () => {
855
+ const check = await fetcher(`${base}/session-check`, { credentials: "same-origin" }).then((response) => response.ok ? response.json() : null).catch(() => null);
856
+ if (stopped || !check?.frame || !check.state) return;
857
+ const origin = new URL(check.frame).origin;
858
+ const frame = document.createElement("iframe");
859
+ frame.src = check.frame;
860
+ frame.title = "session check";
861
+ frame.setAttribute("aria-hidden", "true");
862
+ frame.tabIndex = -1;
863
+ frame.style.cssText = "position:absolute;width:0;height:0;border:0;visibility:hidden";
864
+ const message = `${check.clientId} ${check.state}`;
865
+ const ask = () => {
866
+ if (!stopped && document.visibilityState === "visible") frame.contentWindow?.postMessage(message, origin);
867
+ };
868
+ let confirmed = false;
869
+ const answer = (event) => {
870
+ if (event.origin !== origin || event.source !== frame.contentWindow) return;
871
+ if (event.data === "unchanged") confirmed = true;
872
+ else if (event.data === "changed") {
873
+ stop();
874
+ if (!confirmed && recentlyActed()) return;
875
+ markActed();
876
+ onChange();
877
+ } else if (event.data === "error") {
878
+ stop();
879
+ }
880
+ };
881
+ window.addEventListener("message", answer);
882
+ frame.addEventListener("load", ask);
883
+ document.addEventListener("visibilitychange", ask);
884
+ window.addEventListener("focus", ask);
885
+ const timer = setInterval(ask, options.intervalMs ?? 3e3);
886
+ document.body.appendChild(frame);
887
+ cleanups.push(() => {
888
+ window.removeEventListener("message", answer);
889
+ document.removeEventListener("visibilitychange", ask);
890
+ window.removeEventListener("focus", ask);
891
+ clearInterval(timer);
892
+ frame.remove();
893
+ });
894
+ })();
895
+ return stop;
896
+ }
897
+
818
898
  // src/service.ts
819
899
  function paramsFromUrl(url) {
820
900
  const href = url ?? (typeof location === "undefined" ? null : location.href);
@@ -841,16 +921,19 @@ function createAuthService(options) {
841
921
  function buildAuthService(options) {
842
922
  const client = clientFor(options);
843
923
  let latest = null;
924
+ const fetchUserFor = async (token) => {
925
+ if (options.fetchUser) return options.fetchUser(token);
926
+ return client.fetchUser(token === COOKIE_SESSION ? void 0 : token);
927
+ };
928
+ const resumesFromCookie = options.config.tokens === "server" && typeof window !== "undefined";
929
+ const [ready, setReady] = (0, import_signal.createSignal)(!resumesFromCookie);
844
930
  const session = (0, import_session.createSession)({
845
931
  /** The credential is the callback, so this is the code exchange. */
846
932
  async login(params) {
847
933
  latest = await client.handleCallback(params);
848
934
  return { token: latest.accessToken, expiresAt: latest.expiresAt };
849
935
  },
850
- async fetchUser(token) {
851
- if (options.fetchUser) return options.fetchUser(token);
852
- return client.fetchUser(token === COOKIE_SESSION ? void 0 : token);
853
- },
936
+ fetchUser: fetchUserFor,
854
937
  async refresh() {
855
938
  latest = await client.refresh();
856
939
  return { token: latest.accessToken, expiresAt: latest.expiresAt };
@@ -873,11 +956,27 @@ function buildAuthService(options) {
873
956
  });
874
957
  const hooks = (0, import_client.createAuthHooks)({
875
958
  session,
959
+ ready,
876
960
  navigate: options.navigate,
877
961
  loginPath: options.loginPath ?? "/login",
878
962
  homePath: options.homePath ?? "/",
879
963
  forbiddenPath: options.forbiddenPath ?? "/403"
880
964
  });
965
+ if (resumesFromCookie && options.config.tokens === "server" && options.config.watchSession !== false) {
966
+ watchProviderSession({ basePath: options.config.basePath });
967
+ }
968
+ const renderedSignedOut = hooks.store.seeded && hooks.store.value().user == null;
969
+ if (resumesFromCookie && renderedSignedOut) setReady(true);
970
+ else if (resumesFromCookie) {
971
+ void (async () => {
972
+ try {
973
+ await session.adopt(COOKIE_SESSION, await fetchUserFor(COOKIE_SESSION));
974
+ } catch {
975
+ } finally {
976
+ setReady(true);
977
+ }
978
+ })();
979
+ }
881
980
  return Object.assign(session, {
882
981
  client,
883
982
  protectedRoute: hooks.protectedRoute,
package/dist/service.d.ts CHANGED
@@ -52,7 +52,7 @@ export interface AuthServiceOptions<U, P = unknown, Q = (p: P) => boolean> {
52
52
  /**
53
53
  * What an application injects.
54
54
  *
55
- * The session's own surface (`user`, `token`, `status`, `isAuthenticated`, `can`, …) plus
55
+ * The session's own surface (`user`, `token`, `status`, `isAuthenticated`, `can`, ...) plus
56
56
  * the three things a redirect flow adds.
57
57
  */
58
58
  export interface AuthService<U, P = unknown, Q = (p: P) => boolean> extends Session<U, AuthCredentials, unknown, P, Q>, Pick<ReturnType<typeof createAuthHooks<U, P, Q>>, 'protectedRoute' | 'Can' | 'Protect' | 'useAuth' | 'useUser' | 'useCan'> {
@@ -1 +1 @@
1
- {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAeA,OAAO,EAAiB,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AC7E,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,4DAA4D;IAC5D,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;;;GAKG;AACH,MAAM,WAAW,WAAW,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,OAAO,CAChE,SAAQ,OAAO,CAAC,CAAC,EAAE,eAAe,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC,EAChD,IAAI,CACF,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,EAC3C,gBAAgB,GAAG,KAAK,GAAG,SAAS,GAAG,SAAS,GAAG,SAAS,GAAG,QAAQ,CACxE;IACH,oFAAoF;IACpF,MAAM,CAAC,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C;;;;OAIG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACnD,kEAAkE;IAClE,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;CAC7B;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,GAAG,cAAc,CAWhE;AAUD,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,OAAO,EACrE,OAAO,EAAE,kBAAkB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GACnC,WAAW,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAStB"}
package/dist/service.js CHANGED
@@ -12,13 +12,14 @@
12
12
  * exchange and the redirect itself is a separate call that never returns. Everything
13
13
  * else lines up directly: `fetchUser`, `refresh`, `logout` and `getExpiry`.
14
14
  */
15
- import { markReactiveScope, openReactiveScope, withReactiveScope } from '@fluixi/reactive/signal';
15
+ import { createSignal, markReactiveScope, openReactiveScope, withReactiveScope } from '@fluixi/reactive/signal';
16
16
  import { createSession } from '@fluixi/session';
17
17
  import { createAuthHooks } from '@fluixi/auth/client';
18
18
  import { expiryFromJwt } from './pkce.js';
19
19
  import { safeReturnTo } from './return-to.js';
20
20
  import { createBrowserClient } from './browser.js';
21
21
  import { createServerClient, COOKIE_SESSION } from './server-client.js';
22
+ import { watchProviderSession } from './session-monitor.js';
22
23
  import { OAuthError } from './types.js';
23
24
  /**
24
25
  * The parameters on the current URL, which is what a callback route has.
@@ -63,17 +64,22 @@ function buildAuthService(options) {
63
64
  // Held so `getExpiry` can answer for a token the session hands back, and so a
64
65
  // server-mode session has something to report when the token is a cookie.
65
66
  let latest = null;
67
+ const fetchUserFor = async (token) => {
68
+ if (options.fetchUser)
69
+ return options.fetchUser(token);
70
+ return client.fetchUser(token === COOKIE_SESSION ? undefined : token);
71
+ };
72
+ // With the tokens on the server, the browser learns it is signed in by asking. Until it
73
+ // has, the hooks keep the user the server rendered with rather than showing nobody.
74
+ const resumesFromCookie = options.config.tokens === 'server' && typeof window !== 'undefined';
75
+ const [ready, setReady] = createSignal(!resumesFromCookie);
66
76
  const session = createSession({
67
77
  /** The credential is the callback, so this is the code exchange. */
68
78
  async login(params) {
69
79
  latest = await client.handleCallback(params);
70
80
  return { token: latest.accessToken, expiresAt: latest.expiresAt };
71
81
  },
72
- async fetchUser(token) {
73
- if (options.fetchUser)
74
- return options.fetchUser(token);
75
- return client.fetchUser(token === COOKIE_SESSION ? undefined : token);
76
- },
82
+ fetchUser: fetchUserFor,
77
83
  async refresh() {
78
84
  latest = await client.refresh();
79
85
  return { token: latest.accessToken, expiresAt: latest.expiresAt };
@@ -101,11 +107,37 @@ function buildAuthService(options) {
101
107
  // rather than a second file an app has to wire up and keep in step.
102
108
  const hooks = createAuthHooks({
103
109
  session: session,
110
+ ready,
104
111
  navigate: options.navigate,
105
112
  loginPath: options.loginPath ?? '/login',
106
113
  homePath: options.homePath ?? '/',
107
114
  forbiddenPath: options.forbiddenPath ?? '/403',
108
115
  });
116
+ // The page the server rendered already says whether anyone is signed in. When it said
117
+ // nobody, there is no session to resume: asking would only get a 401 on every anonymous
118
+ // page. A client-only load has no such answer and still asks.
119
+ // Signed in or not, a session that changes at the provider while the page is open is
120
+ // noticed here rather than at the next page load.
121
+ if (resumesFromCookie && options.config.tokens === 'server' && options.config.watchSession !== false) {
122
+ watchProviderSession({ basePath: options.config.basePath });
123
+ }
124
+ const renderedSignedOut = hooks.store.seeded && hooks.store.value().user == null;
125
+ if (resumesFromCookie && renderedSignedOut)
126
+ setReady(true);
127
+ else if (resumesFromCookie) {
128
+ void (async () => {
129
+ try {
130
+ // The user first: a cookie the server no longer accepts adopts nothing.
131
+ await session.adopt(COOKIE_SESSION, await fetchUserFor(COOKIE_SESSION));
132
+ }
133
+ catch {
134
+ // Signed out after all; the hooks drop the server's user once ready.
135
+ }
136
+ finally {
137
+ setReady(true);
138
+ }
139
+ })();
140
+ }
109
141
  return Object.assign(session, {
110
142
  client,
111
143
  protectedRoute: hooks.protectedRoute,