@tereo-io/react 0.0.0-stage → 0.1.1

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 (79) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +167 -2
  4. package/dist/api.d.ts +11 -0
  5. package/dist/api.d.ts.map +1 -0
  6. package/dist/api.js +62 -0
  7. package/dist/api.js.map +1 -0
  8. package/dist/config.d.ts +69 -0
  9. package/dist/config.d.ts.map +1 -0
  10. package/dist/config.js +41 -0
  11. package/dist/config.js.map +1 -0
  12. package/dist/events.d.ts +48 -0
  13. package/dist/events.d.ts.map +1 -0
  14. package/dist/events.js +129 -0
  15. package/dist/events.js.map +1 -0
  16. package/dist/hooks.d.ts +21 -0
  17. package/dist/hooks.d.ts.map +1 -0
  18. package/dist/hooks.js +46 -0
  19. package/dist/hooks.js.map +1 -0
  20. package/dist/index.d.ts +16 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +12 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/logger.d.ts +3 -0
  25. package/dist/logger.d.ts.map +1 -0
  26. package/dist/logger.js +9 -0
  27. package/dist/logger.js.map +1 -0
  28. package/dist/markers.d.ts +7 -0
  29. package/dist/markers.d.ts.map +1 -0
  30. package/dist/markers.js +15 -0
  31. package/dist/markers.js.map +1 -0
  32. package/dist/permissions.d.ts +4 -0
  33. package/dist/permissions.d.ts.map +1 -0
  34. package/dist/permissions.js +64 -0
  35. package/dist/permissions.js.map +1 -0
  36. package/dist/provider.d.ts +30 -0
  37. package/dist/provider.d.ts.map +1 -0
  38. package/dist/provider.js +213 -0
  39. package/dist/provider.js.map +1 -0
  40. package/dist/refresh.d.ts +15 -0
  41. package/dist/refresh.d.ts.map +1 -0
  42. package/dist/refresh.js +98 -0
  43. package/dist/refresh.js.map +1 -0
  44. package/dist/signIn.d.ts +13 -0
  45. package/dist/signIn.d.ts.map +1 -0
  46. package/dist/signIn.js +134 -0
  47. package/dist/signIn.js.map +1 -0
  48. package/dist/signOut.d.ts +8 -0
  49. package/dist/signOut.d.ts.map +1 -0
  50. package/dist/signOut.js +69 -0
  51. package/dist/signOut.js.map +1 -0
  52. package/dist/storage.d.ts +6 -0
  53. package/dist/storage.d.ts.map +1 -0
  54. package/dist/storage.js +73 -0
  55. package/dist/storage.js.map +1 -0
  56. package/dist/storageLock.d.ts +14 -0
  57. package/dist/storageLock.d.ts.map +1 -0
  58. package/dist/storageLock.js +100 -0
  59. package/dist/storageLock.js.map +1 -0
  60. package/dist/tokens.d.ts +13 -0
  61. package/dist/tokens.d.ts.map +1 -0
  62. package/dist/tokens.js +27 -0
  63. package/dist/tokens.js.map +1 -0
  64. package/package.json +66 -4
  65. package/src/api.ts +82 -0
  66. package/src/config.ts +108 -0
  67. package/src/events.ts +184 -0
  68. package/src/hooks.ts +62 -0
  69. package/src/index.ts +34 -0
  70. package/src/logger.ts +9 -0
  71. package/src/markers.ts +26 -0
  72. package/src/permissions.ts +77 -0
  73. package/src/provider.tsx +291 -0
  74. package/src/refresh.ts +120 -0
  75. package/src/signIn.ts +168 -0
  76. package/src/signOut.ts +85 -0
  77. package/src/storage.ts +80 -0
  78. package/src/storageLock.ts +111 -0
  79. package/src/tokens.ts +38 -0
@@ -0,0 +1,291 @@
1
+ import { type PermissionRequirement, hasPermission } from "./permissions.js";
2
+ import { type StoredTokens, decodeJwt, readTokens } from "./tokens.js";
3
+ import { useQuery, useQueryClient } from "@tanstack/react-query";
4
+ import { type EventSocket, startTereoEvents } from "./events.js";
5
+ import { type AxiosInstance, isAxiosError } from "axios";
6
+ import { endLocalSession, signOut } from "./signOut.js";
7
+ import { useStoredValue } from "./storage.js";
8
+ import { refreshTokens } from "./refresh.js";
9
+ import { createApiClients } from "./api.js";
10
+ import { hasSession } from "./markers.js";
11
+ import { debugLog } from "./logger.js";
12
+ import { io } from "socket.io-client";
13
+ import { signIn } from "./signIn.js";
14
+ import {
15
+ type ResolvedConfig,
16
+ type TereoAuthConfig,
17
+ type TereoEvent,
18
+ type TereoUser,
19
+ pathWithoutBase,
20
+ resolveConfig,
21
+ setActiveConfig,
22
+ } from "./config.js";
23
+ import {
24
+ type ReactNode,
25
+ createContext,
26
+ useCallback,
27
+ useEffect,
28
+ useMemo,
29
+ useRef,
30
+ useState,
31
+ } from "react";
32
+
33
+ export interface AuthState<U extends TereoUser = TereoUser> {
34
+ user: U | null;
35
+ isLoading: boolean;
36
+ isSignedIn: boolean;
37
+ /** Whether core's live-update socket is connected. */
38
+ isLive: boolean;
39
+ hasPermission: (required: PermissionRequirement) => boolean;
40
+ signIn: typeof signIn;
41
+ signOut: typeof signOut;
42
+ switchOrganization: (orgId: string) => Promise<void>;
43
+ reloadUser: () => Promise<void>;
44
+ }
45
+
46
+ export interface ApiClients {
47
+ authed: Record<string, AxiosInstance>;
48
+ open: Record<string, AxiosInstance>;
49
+ }
50
+
51
+ export const AuthContext = createContext<AuthState | null>(null);
52
+ export const ApiContext = createContext<ApiClients | null>(null);
53
+
54
+ // Every user cached for this client; one identity's entry is that prefix
55
+ // plus its subject and organization.
56
+ const usersKey = (clientId: string) => ["tereo", "user", clientId] as const;
57
+
58
+ const claimOf = (token: string | undefined, claim: string): string | null => {
59
+ const value = token ? decodeJwt(token)?.[claim] : null;
60
+ return typeof value === "string" ? value : null;
61
+ };
62
+
63
+ // A user lookup core refused for the token is not retried; other failures
64
+ // (network, 5xx) are, twice, with backoff.
65
+ const retryUserLookup = (failureCount: number, error: unknown): boolean => {
66
+ const status = isAxiosError(error) ? error.response?.status : undefined;
67
+ if (status === 401 || status === 403) return false;
68
+ return failureCount < 2;
69
+ };
70
+ const userLookupDelay = (attempt: number): number =>
71
+ Math.min(1000 * 2 ** attempt, 30_000);
72
+
73
+ // Events that arrive together reload the user once.
74
+ const RELOAD_DEBOUNCE_MS = 250;
75
+
76
+ const currentRoutePath = (config: ResolvedConfig): string =>
77
+ pathWithoutBase(window.location.pathname, config.basePath).replace(
78
+ /(.)\/+$/,
79
+ "$1"
80
+ ) || "/";
81
+
82
+ /** Needs a `QueryClientProvider` above it. */
83
+ export const TereoAuthProvider = ({
84
+ config,
85
+ children,
86
+ }: {
87
+ config: TereoAuthConfig;
88
+ children: ReactNode;
89
+ }) => {
90
+ // Set during the first render, so hooks and plain functions such as
91
+ // `signIn` work from the start. The config is read once.
92
+ const [resolved] = useState(() => {
93
+ const r = resolveConfig(config);
94
+ setActiveConfig(r);
95
+ return r;
96
+ });
97
+ const { clientId, keys, apis, loadUser } = resolved;
98
+
99
+ const queryClient = useQueryClient();
100
+ const clients = useMemo(() => createApiClients(apis), [apis]);
101
+ const tokens = useStoredValue<StoredTokens>(keys.tokens);
102
+ const accessToken = tokens?.access_token;
103
+ // Keyed on whose token it is, so a sign-in as someone else or into
104
+ // another organization (here or in another tab) never reads the previous
105
+ // identity's user.
106
+ const userId = useMemo(() => claimOf(accessToken, "sub"), [accessToken]);
107
+ const orgId = useMemo(() => claimOf(accessToken, "org_id"), [accessToken]);
108
+ const queryKey = useMemo(
109
+ () => [...usersKey(clientId), userId, orgId] as const,
110
+ [clientId, userId, orgId]
111
+ );
112
+
113
+ // A page load with a session but no token (the access token lives in
114
+ // storage the tab may not have): renew it before deciding anything.
115
+ const [restoring, setRestoring] = useState(() => !tokens && hasSession());
116
+ useEffect(() => {
117
+ if (tokens || !hasSession()) {
118
+ setRestoring(false);
119
+ return;
120
+ }
121
+ // refreshTokens clears what core rejected; other failures leave the
122
+ // next request to retry.
123
+ void refreshTokens()
124
+ .catch(() => {})
125
+ .finally(() => setRestoring(false));
126
+ }, [tokens]);
127
+
128
+ const query = useQuery({
129
+ queryKey,
130
+ queryFn: () => loadUser(clients.authed),
131
+ enabled: tokens !== null,
132
+ retry: retryUserLookup,
133
+ retryDelay: userLookupDelay,
134
+ });
135
+
136
+ useEffect(() => {
137
+ // Signed out here or in another tab: drop the cached user rather than
138
+ // render it until the redirect lands.
139
+ if (!tokens) queryClient.removeQueries({ queryKey: usersKey(clientId) });
140
+ }, [tokens, queryClient, clientId]);
141
+
142
+ useEffect(() => {
143
+ if (tokens || restoring || hasSession()) return;
144
+ if (resolved.isPublicPath(currentRoutePath(resolved))) return;
145
+ window.location.href = `${resolved.basePath}${resolved.signedOutPath}`;
146
+ }, [tokens, restoring, resolved]);
147
+
148
+ const user = tokens ? (query.data ?? null) : null;
149
+
150
+ const check = useCallback(
151
+ (required: PermissionRequirement) =>
152
+ hasPermission(user?.permissions ?? [], required),
153
+ [user]
154
+ );
155
+ const switchOrganization = useCallback(
156
+ (orgId: string) => signIn({ params: { org_id: orgId } }),
157
+ []
158
+ );
159
+ const reloadUser = useCallback(
160
+ () => queryClient.invalidateQueries({ queryKey }),
161
+ [queryClient, queryKey]
162
+ );
163
+
164
+ const reloadTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
165
+
166
+ // A new token (exchange, refresh, another tab) may carry other
167
+ // permissions. A new identity changes the key, which loads on its own;
168
+ // the same one is reloaded now, which also covers any pending event
169
+ // reload.
170
+ const lastToken = useRef(accessToken);
171
+ const lastKey = useRef(queryKey);
172
+ useEffect(() => {
173
+ const previousToken = lastToken.current;
174
+ const previousKey = lastKey.current;
175
+ lastToken.current = accessToken;
176
+ lastKey.current = queryKey;
177
+ if (!previousToken || !accessToken || previousToken === accessToken) return;
178
+ if (reloadTimer.current) clearTimeout(reloadTimer.current);
179
+ reloadTimer.current = null;
180
+ if (previousKey === queryKey)
181
+ void queryClient.invalidateQueries({ queryKey });
182
+ }, [accessToken, queryKey, queryClient]);
183
+
184
+ const [isLive, setIsLive] = useState(false);
185
+
186
+ // `config` is resolved once, but a callback written inline should see
187
+ // the state of the latest render.
188
+ const onEventRef = useRef(config.onEvent);
189
+ useEffect(() => {
190
+ onEventRef.current = config.onEvent;
191
+ }, [config.onEvent]);
192
+
193
+ // The events loop is keyed on the user, not the token: the token (and
194
+ // its sid) rotates on every refresh, and the loop reads the current one
195
+ // at each handshake.
196
+ useEffect(() => {
197
+ if (!resolved.live || !userId) return;
198
+
199
+ const handleEvent = (event: TereoEvent) => {
200
+ onEventRef.current?.(event);
201
+ if (event.type === "session-revoked") return;
202
+ if (reloadTimer.current) clearTimeout(reloadTimer.current);
203
+ reloadTimer.current = setTimeout(() => {
204
+ reloadTimer.current = null;
205
+ void reloadUser();
206
+ }, RELOAD_DEBOUNCE_MS);
207
+ };
208
+
209
+ // Deferred to a microtask so StrictMode's mount, unmount, mount cancels
210
+ // before a handshake starts.
211
+ let stop: (() => void) | null = null;
212
+ let cancelled = false;
213
+ void Promise.resolve().then(() => {
214
+ if (cancelled) return;
215
+ stop = startTereoEvents({
216
+ // socket.io treats a URL's path as a namespace; core serves the
217
+ // socket at `wsPath`, so only the origin goes in the URL.
218
+ createSocket: (auth) => {
219
+ const socket = io(new URL(resolved.coreUrl).origin, {
220
+ path: resolved.wsPath,
221
+ transports: ["websocket", "polling"],
222
+ autoConnect: false,
223
+ auth,
224
+ });
225
+ socket.on("connect", () => setIsLive(true));
226
+ socket.on("disconnect", () => setIsLive(false));
227
+ socket.on("connect_error", () => setIsLive(false));
228
+ return socket as unknown as EventSocket;
229
+ },
230
+ accessToken: () => readTokens()?.access_token ?? null,
231
+ tokenIsFresh: () => {
232
+ const stored = readTokens();
233
+ return (
234
+ !!stored &&
235
+ Date.now() < stored.expiresAt - resolved.tokenExpirationBuffer
236
+ );
237
+ },
238
+ sessionId: () => {
239
+ const token = readTokens()?.access_token;
240
+ const sid = token ? decodeJwt(token)?.sid : null;
241
+ return typeof sid === "string" ? sid : null;
242
+ },
243
+ refresh: refreshTokens,
244
+ // Core already ended the session: a revoke would fail, and an
245
+ // end-session without a usable hint asks the user to confirm.
246
+ sessionEnded: endLocalSession,
247
+ onEvent: handleEvent,
248
+ refused: (reason) => debugLog("Events socket stopped:", reason),
249
+ log: (message, detail) => debugLog(message, detail),
250
+ });
251
+ });
252
+
253
+ return () => {
254
+ cancelled = true;
255
+ if (reloadTimer.current) clearTimeout(reloadTimer.current);
256
+ reloadTimer.current = null;
257
+ stop?.();
258
+ setIsLive(false);
259
+ };
260
+ }, [userId, resolved, reloadUser]);
261
+
262
+ const value = useMemo<AuthState>(
263
+ () => ({
264
+ user,
265
+ isLoading: restoring || query.isLoading || query.isFetching,
266
+ isSignedIn: user !== null,
267
+ isLive,
268
+ hasPermission: check,
269
+ signIn,
270
+ signOut,
271
+ switchOrganization,
272
+ reloadUser,
273
+ }),
274
+ [
275
+ user,
276
+ restoring,
277
+ query.isLoading,
278
+ query.isFetching,
279
+ isLive,
280
+ check,
281
+ switchOrganization,
282
+ reloadUser,
283
+ ]
284
+ );
285
+
286
+ return (
287
+ <ApiContext.Provider value={clients}>
288
+ <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
289
+ </ApiContext.Provider>
290
+ );
291
+ };
package/src/refresh.ts ADDED
@@ -0,0 +1,120 @@
1
+ import { clearSignedIn, isLoggedOut, markLoggedOut } from "./markers.js";
2
+ import { withStorageLock } from "./storageLock.js";
3
+ import axios, { isAxiosError } from "axios";
4
+ import { activeConfig } from "./config.js";
5
+ import { errorLog } from "./logger.js";
6
+ import {
7
+ type StoredTokens,
8
+ decodeJwt,
9
+ readTokens,
10
+ writeTokens,
11
+ } from "./tokens.js";
12
+
13
+ type TokenResponse = Omit<StoredTokens, "expiresAt">;
14
+
15
+ /**
16
+ * Core refused the refresh token (400 invalid_grant, 401 invalid_client):
17
+ * the session is over. Anything else (offline, 429, 5xx) may pass, so the
18
+ * stored tokens are kept for the next attempt.
19
+ */
20
+ export const isRefreshRejected = (error: unknown): boolean => {
21
+ const status = isAxiosError(error) ? error.response?.status : undefined;
22
+ return status === 400 || status === 401;
23
+ };
24
+
25
+ const subjectOf = (accessToken: string | undefined): string | null => {
26
+ const sub = accessToken ? decodeJwt(accessToken)?.sub : null;
27
+ return typeof sub === "string" ? sub : null;
28
+ };
29
+
30
+ const requestRefresh = async (): Promise<StoredTokens> => {
31
+ const { coreUrl, clientId, requestTimeoutMs } = activeConfig();
32
+ // Who the tab is signed in as; nobody on a load with no stored token.
33
+ const signedInAs = subjectOf(readTokens()?.access_token);
34
+
35
+ const res = await axios.post<TokenResponse>(
36
+ `${coreUrl}/oauth/token`,
37
+ new URLSearchParams({
38
+ grant_type: "refresh_token",
39
+ client_id: clientId,
40
+ refresh_token_response_mode: "cookie",
41
+ }),
42
+ {
43
+ withCredentials: true,
44
+ timeout: requestTimeoutMs,
45
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
46
+ }
47
+ );
48
+
49
+ // Signed out in another tab while this refresh was in flight.
50
+ if (isLoggedOut()) throw new Error("Signed out during token refresh");
51
+
52
+ // The refresh cookie is not this user's: something outside the app put it
53
+ // there. Marked signed out so that it is not refreshed from again.
54
+ if (signedInAs && subjectOf(res.data.access_token) !== signedInAs) {
55
+ markLoggedOut();
56
+ writeTokens(null);
57
+ throw new Error("Token refresh answered for another user");
58
+ }
59
+
60
+ // A refresh returns a fresh id_token for the same login, which sign-out
61
+ // sends as the end-session id_token_hint; keep the stored one if not.
62
+ const idToken = res.data.id_token ?? readTokens()?.id_token;
63
+ const tokens: StoredTokens = {
64
+ ...res.data,
65
+ ...(idToken && { id_token: idToken }),
66
+ expiresAt: Date.now() + res.data.expires_in * 1000,
67
+ };
68
+ writeTokens(tokens);
69
+ return tokens;
70
+ };
71
+
72
+ const refreshAcrossTabs = (): Promise<StoredTokens> => {
73
+ const { storagePrefix, tokenExpirationBuffer } = activeConfig();
74
+ const lockName = `${storagePrefix}_refresh`;
75
+ const staleToken = readTokens()?.access_token;
76
+
77
+ const run = async (): Promise<StoredTokens> => {
78
+ // Signed out in another tab while this one waited for the lock.
79
+ if (isLoggedOut()) throw new Error("Signed out");
80
+ // Another tab may have refreshed while this one waited for the lock.
81
+ const stored = readTokens();
82
+ if (
83
+ stored &&
84
+ stored.access_token !== staleToken &&
85
+ Date.now() < stored.expiresAt - tokenExpirationBuffer
86
+ ) {
87
+ return stored;
88
+ }
89
+ return requestRefresh();
90
+ };
91
+
92
+ // navigator.locks is missing outside secure contexts (plain-http hosts).
93
+ return typeof navigator.locks?.request === "function"
94
+ ? navigator.locks.request(lockName, run)
95
+ : withStorageLock(lockName, run);
96
+ };
97
+
98
+ let inFlight: Promise<StoredTokens> | null = null;
99
+
100
+ /**
101
+ * One refresh at a time, across every tab. Tabs share the rotating refresh
102
+ * cookie: two concurrent refreshes get invalid_grant for the loser, and a
103
+ * request still carrying the pre-rotation cookie is treated by core as token
104
+ * reuse, which revokes the whole family.
105
+ */
106
+ export const refreshTokens = (): Promise<StoredTokens> => {
107
+ inFlight ??= refreshAcrossTabs()
108
+ .catch((error: unknown) => {
109
+ errorLog("Token refresh failed:", error);
110
+ if (isRefreshRejected(error)) {
111
+ writeTokens(null);
112
+ clearSignedIn();
113
+ }
114
+ throw error;
115
+ })
116
+ .finally(() => {
117
+ inFlight = null;
118
+ });
119
+ return inFlight;
120
+ };
package/src/signIn.ts ADDED
@@ -0,0 +1,168 @@
1
+ import { type StoredTokens, decodeJwt, writeTokens } from "./tokens.js";
2
+ import { clearLoggedOut, markSignedIn } from "./markers.js";
3
+ import { activeConfig } from "./config.js";
4
+ import axios from "axios";
5
+
6
+ interface PKCEChallenge {
7
+ codeVerifier: string;
8
+ codeChallenge: string;
9
+ state: string;
10
+ nonce: string;
11
+ }
12
+
13
+ type TokenResponse = Omit<StoredTokens, "expiresAt">;
14
+
15
+ const generateRandomString = (length: number): string => {
16
+ const array = new Uint8Array(length);
17
+ crypto.getRandomValues(array);
18
+ return Array.from(array, (byte) => byte.toString(16).padStart(2, "0")).join(
19
+ ""
20
+ );
21
+ };
22
+
23
+ const generateCodeChallenge = async (codeVerifier: string): Promise<string> => {
24
+ const data = new TextEncoder().encode(codeVerifier);
25
+ const digest = await crypto.subtle.digest("SHA-256", data);
26
+ return btoa(String.fromCharCode(...new Uint8Array(digest)))
27
+ .replace(/\+/g, "-")
28
+ .replace(/\//g, "_")
29
+ .replace(/=+$/, "");
30
+ };
31
+
32
+ // sessionStorage, not localStorage: the flow stays in one tab, and a login
33
+ // started in a second tab must not overwrite this tab's verifier and state.
34
+ const readPKCE = (): PKCEChallenge | null => {
35
+ try {
36
+ const raw = sessionStorage.getItem(activeConfig().keys.pkce);
37
+ return raw ? (JSON.parse(raw) as PKCEChallenge) : null;
38
+ } catch {
39
+ return null;
40
+ }
41
+ };
42
+
43
+ const clearPKCE = (): void => {
44
+ try {
45
+ sessionStorage.removeItem(activeConfig().keys.pkce);
46
+ } catch {
47
+ // Nothing stored to clear.
48
+ }
49
+ };
50
+
51
+ /** An in-app path only: never a full URL, which would be an open redirect. */
52
+ const isAppPath = (path: string): boolean =>
53
+ path.startsWith("/") && !path.startsWith("//") && !path.includes("\\");
54
+
55
+ const takePostLoginPath = (): string | null => {
56
+ const { postLoginPath } = activeConfig().keys;
57
+ try {
58
+ const path = sessionStorage.getItem(postLoginPath);
59
+ sessionStorage.removeItem(postLoginPath);
60
+ return path && isAppPath(path) ? path : null;
61
+ } catch {
62
+ return null;
63
+ }
64
+ };
65
+
66
+ /**
67
+ * Redirects to core's authorize endpoint with a fresh PKCE challenge.
68
+ * `returnTo` is an in-app path to land on after the callback, instead of "/".
69
+ */
70
+ export const signIn = async (
71
+ opts: { returnTo?: string; params?: Record<string, string> } = {}
72
+ ): Promise<void> => {
73
+ const { coreUrl, clientId, redirectUri, scopes, keys } = activeConfig();
74
+
75
+ try {
76
+ sessionStorage.removeItem(keys.postLoginPath);
77
+ if (opts.returnTo && isAppPath(opts.returnTo)) {
78
+ sessionStorage.setItem(keys.postLoginPath, opts.returnTo);
79
+ }
80
+ } catch {
81
+ // The sign-in still works; it lands on the default path.
82
+ }
83
+
84
+ const codeVerifier = generateRandomString(64);
85
+ const challenge: PKCEChallenge = {
86
+ codeVerifier,
87
+ codeChallenge: await generateCodeChallenge(codeVerifier),
88
+ state: generateRandomString(32),
89
+ nonce: generateRandomString(32),
90
+ };
91
+ sessionStorage.setItem(keys.pkce, JSON.stringify(challenge));
92
+
93
+ const params = new URLSearchParams({
94
+ scope: scopes,
95
+ ...opts.params,
96
+ response_type: "code",
97
+ client_id: clientId,
98
+ redirect_uri: redirectUri,
99
+ state: challenge.state,
100
+ nonce: challenge.nonce,
101
+ code_challenge: challenge.codeChallenge,
102
+ code_challenge_method: "S256",
103
+ });
104
+
105
+ window.location.href = `${coreUrl}/oauth/authorize?${params}`;
106
+ };
107
+
108
+ /** Finishes the sign-in from the callback's query string. */
109
+ export const completeSignIn = async (
110
+ search: URLSearchParams
111
+ ): Promise<{ returnTo: string | null }> => {
112
+ const { coreUrl, clientId, redirectUri, requestTimeoutMs } = activeConfig();
113
+
114
+ const code = search.get("code");
115
+ const state = search.get("state");
116
+
117
+ const error = search.get("error");
118
+ if (error) {
119
+ // The flow is over; a matching state means the saved entry is this one's.
120
+ if (state && readPKCE()?.state === state) clearPKCE();
121
+ throw new Error(error);
122
+ }
123
+ if (!code || !state) {
124
+ throw new Error("The sign-in response is missing its code or state.");
125
+ }
126
+
127
+ const pkce = readPKCE();
128
+ if (!pkce || pkce.state !== state) {
129
+ throw new Error(
130
+ "This sign-in link does not match the one this tab started. Please sign in again."
131
+ );
132
+ }
133
+ // The verifier is single-use: a failed exchange cannot be retried.
134
+ clearPKCE();
135
+
136
+ const res = await axios.post<TokenResponse>(
137
+ `${coreUrl}/oauth/token`,
138
+ new URLSearchParams({
139
+ grant_type: "authorization_code",
140
+ code,
141
+ redirect_uri: redirectUri,
142
+ client_id: clientId,
143
+ code_verifier: pkce.codeVerifier,
144
+ refresh_token_response_mode: "cookie",
145
+ }),
146
+ {
147
+ withCredentials: true,
148
+ timeout: requestTimeoutMs,
149
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
150
+ }
151
+ );
152
+
153
+ const tokens = res.data;
154
+ // Received straight from the token endpoint over TLS, so the signature
155
+ // need not be checked (OIDC Core 3.1.3.7); the nonce and audience must.
156
+ const idToken = tokens.id_token ? decodeJwt(tokens.id_token) : null;
157
+ if (!idToken || idToken.nonce !== pkce.nonce) {
158
+ throw new Error("ID token nonce validation failed");
159
+ }
160
+ if (idToken.aud !== clientId) {
161
+ throw new Error("ID token was issued to a different client");
162
+ }
163
+
164
+ writeTokens({ ...tokens, expiresAt: Date.now() + tokens.expires_in * 1000 });
165
+ markSignedIn();
166
+ clearLoggedOut();
167
+ return { returnTo: takePostLoginPath() };
168
+ };
package/src/signOut.ts ADDED
@@ -0,0 +1,85 @@
1
+ import { decodeJwt, readTokens, writeTokens } from "./tokens.js";
2
+ import { clearSignedIn, markLoggedOut } from "./markers.js";
3
+ import { activeConfig } from "./config.js";
4
+ import { errorLog } from "./logger.js";
5
+ import axios from "axios";
6
+
7
+ const FORM_HEADERS = { "Content-Type": "application/x-www-form-urlencoded" };
8
+
9
+ // Core's ID_TOKEN_HINT_GRACE_SECONDS: it rejects a hint expired longer ago.
10
+ const ID_TOKEN_HINT_GRACE_SECONDS = 60 * 60;
11
+
12
+ /** The id token, unless core would reject it for having expired too long ago. */
13
+ const usableIdTokenHint = (idToken?: string): string | undefined => {
14
+ if (!idToken) return undefined;
15
+ const exp = decodeJwt(idToken)?.exp;
16
+ if (typeof exp !== "number") return idToken;
17
+ const now = Math.floor(Date.now() / 1000);
18
+ return now - exp > ID_TOKEN_HINT_GRACE_SECONDS ? undefined : idToken;
19
+ };
20
+
21
+ /** Ends the session at core, clears local state and leaves the app. */
22
+ export const signOut = async (): Promise<void> => {
23
+ const { coreUrl, clientId, requestTimeoutMs, signedOutPath, basePath } =
24
+ activeConfig();
25
+ const options = {
26
+ withCredentials: true,
27
+ timeout: requestTimeoutMs,
28
+ headers: FORM_HEADERS,
29
+ };
30
+
31
+ // Set before any network call, so a failed or interrupted sign-out still
32
+ // never refreshes silently on the next load.
33
+ markLoggedOut();
34
+ const hint = usableIdTokenHint(readTokens()?.id_token);
35
+
36
+ // Revoke clears this client's refresh-token cookies; end-session ends the
37
+ // SSO session, whose cookie would otherwise let authorize sign the user
38
+ // straight back in. Each runs even if the other fails.
39
+ const [revoked, ended] = await Promise.allSettled([
40
+ axios.post(
41
+ `${coreUrl}/oauth/revoke`,
42
+ new URLSearchParams({
43
+ client_id: clientId,
44
+ token_type_hint: "refresh_token",
45
+ }),
46
+ options
47
+ ),
48
+ hint
49
+ ? axios.post(
50
+ `${coreUrl}/oauth/end-session`,
51
+ new URLSearchParams({ client_id: clientId, id_token_hint: hint }),
52
+ options
53
+ )
54
+ : Promise.reject(new Error("No usable id_token_hint")),
55
+ ]);
56
+
57
+ if (revoked.status === "rejected") {
58
+ errorLog("Token revocation request failed", revoked.reason);
59
+ }
60
+ if (ended.status === "rejected" && hint) {
61
+ errorLog("End-session request failed", ended.reason);
62
+ }
63
+
64
+ writeTokens(null);
65
+ clearSignedIn();
66
+
67
+ // Without a hint core cannot tell this sign-out from one a cross-site page
68
+ // triggered, so it asks the user to confirm on its own page.
69
+ window.location.href =
70
+ ended.status === "fulfilled"
71
+ ? `${basePath}${signedOutPath}`
72
+ : `${coreUrl}/oauth/end-session?${new URLSearchParams({ client_id: clientId })}`;
73
+ };
74
+
75
+ /**
76
+ * Ends the session in this browser only, for one core has already ended.
77
+ * The logged-out marker keeps the dead refresh cookie from being tried.
78
+ */
79
+ export const endLocalSession = (): void => {
80
+ const { signedOutPath, basePath } = activeConfig();
81
+ markLoggedOut();
82
+ writeTokens(null);
83
+ clearSignedIn();
84
+ window.location.href = `${basePath}${signedOutPath}`;
85
+ };