@useauthio/react 0.2.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.
package/src/locate.ts ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Browser helpers for Authio Locate client attestation.
3
+ *
4
+ * Capture device geolocation and pass it to sign-in or standalone verify
5
+ * calls as `client_location`. Requires user consent (browser prompt).
6
+ */
7
+
8
+ export interface ClientLocationCapture {
9
+ latitude: number;
10
+ longitude: number;
11
+ accuracy_m: number;
12
+ captured_at: string;
13
+ source: "browser_geolocation";
14
+ }
15
+
16
+ export interface CaptureClientLocationOptions {
17
+ timeoutMs?: number;
18
+ maximumAgeMs?: number;
19
+ enableHighAccuracy?: boolean;
20
+ }
21
+
22
+ /**
23
+ * Request the browser's current position. Rejects when geolocation is
24
+ * unavailable, denied, or times out.
25
+ */
26
+ export function captureClientLocation(
27
+ opts: CaptureClientLocationOptions = {},
28
+ ): Promise<ClientLocationCapture> {
29
+ if (typeof navigator === "undefined" || !navigator.geolocation) {
30
+ return Promise.reject(new Error("geolocation_unavailable"));
31
+ }
32
+ const timeoutMs = opts.timeoutMs ?? 10_000;
33
+ return new Promise((resolve, reject) => {
34
+ const timer = setTimeout(() => reject(new Error("geolocation_timeout")), timeoutMs);
35
+ navigator.geolocation.getCurrentPosition(
36
+ (pos) => {
37
+ clearTimeout(timer);
38
+ resolve({
39
+ latitude: pos.coords.latitude,
40
+ longitude: pos.coords.longitude,
41
+ accuracy_m: Math.round(pos.coords.accuracy),
42
+ captured_at: new Date(pos.timestamp).toISOString(),
43
+ source: "browser_geolocation",
44
+ });
45
+ },
46
+ (err) => {
47
+ clearTimeout(timer);
48
+ reject(err);
49
+ },
50
+ {
51
+ enableHighAccuracy: opts.enableHighAccuracy ?? false,
52
+ maximumAge: opts.maximumAgeMs ?? 60_000,
53
+ timeout: timeoutMs,
54
+ },
55
+ );
56
+ });
57
+ }
@@ -0,0 +1,419 @@
1
+ import React, {
2
+ createContext,
3
+ useCallback,
4
+ useEffect,
5
+ useMemo,
6
+ useRef,
7
+ useState,
8
+ } from "react";
9
+ import { AuthioError } from "@useauthio/node";
10
+ import { authioFetch } from "./fetch";
11
+ import { createDefaultVerifier, readJwtExp } from "./jwt";
12
+ import { RefreshScheduler } from "./refresh";
13
+ import { isBrowser } from "./ssr";
14
+ import { createTokenStorage, type TokenStorage } from "./storage";
15
+ import { noopEmitter, type TelemetryEmitter } from "./telemetry";
16
+ import type {
17
+ AuthioContextValue,
18
+ AuthioProviderProps,
19
+ AuthioStatus,
20
+ AuthioTokenVerifier,
21
+ AuthioUser,
22
+ } from "./types";
23
+
24
+ export const AuthioContext = createContext<AuthioContextValue | null>(null);
25
+ AuthioContext.displayName = "AuthioContext";
26
+
27
+ interface RefreshEnvelope {
28
+ access_token?: string;
29
+ refresh_token?: string;
30
+ expires_at?: string;
31
+ user?: RawUser | null;
32
+ }
33
+
34
+ interface RawUser {
35
+ id?: string;
36
+ user_id?: string;
37
+ email?: string;
38
+ emailVerified?: boolean;
39
+ email_verified?: boolean;
40
+ name?: string;
41
+ avatarUrl?: string;
42
+ avatar_url?: string;
43
+ }
44
+
45
+ const DEFAULT_REFRESH_LEAD = 60;
46
+ const DEFAULT_AUDIENCE = "authio";
47
+ /** Canonical Lobby (hosted UI) — not the auth-core identity API. */
48
+ export const DEFAULT_SIGN_IN_URL = "https://lobby.authio.com/";
49
+
50
+ /**
51
+ * Top-level context provider. Wrap your app once at the root:
52
+ *
53
+ * ```tsx
54
+ * <AuthioProvider apiUrl="https://auth-api.authio.com" projectId="proj_…">
55
+ * <App />
56
+ * </AuthioProvider>
57
+ * ```
58
+ *
59
+ * Lifecycle:
60
+ *
61
+ * 1. Mount → status `loading`. Issue a `POST /v1/auth/refresh`
62
+ * with `credentials: include`. Auth-core uses the BFF cookie to
63
+ * mint a fresh access token (or 401 if no session).
64
+ * 2. On success: verify the token, stash it per `storage` mode,
65
+ * schedule the next silent refresh `refreshLeadSeconds` before
66
+ * `exp`. Status → `authenticated`.
67
+ * 3. On failure: status → `unauthenticated`. The app shows its
68
+ * sign-in surface; `signIn()` redirects to the hosted UI.
69
+ *
70
+ * The refresh token is NEVER touched from JavaScript — it rides the
71
+ * BFF cookie exclusively. The access token is in-memory by default.
72
+ */
73
+ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
74
+ const {
75
+ apiUrl,
76
+ projectId,
77
+ storage: storageMode = "memory",
78
+ refreshLeadSeconds = DEFAULT_REFRESH_LEAD,
79
+ onTelemetryEvent,
80
+ fetch: fetchImpl,
81
+ signInUrl,
82
+ jwtIssuer,
83
+ jwtAudience = DEFAULT_AUDIENCE,
84
+ verifyToken,
85
+ skipInitialRefresh,
86
+ children,
87
+ } = props;
88
+
89
+ const emit: TelemetryEmitter = onTelemetryEvent ?? noopEmitter;
90
+
91
+ // We deliberately hold storage + verifier + scheduler in refs so a
92
+ // re-render of the provider (parent re-render) doesn't tear them
93
+ // down. They're created once per "shape" of provider props.
94
+ const storageRef = useRef<TokenStorage | null>(null);
95
+ if (storageRef.current === null) {
96
+ storageRef.current = createTokenStorage(storageMode);
97
+ }
98
+
99
+ const verifierRef = useRef<AuthioTokenVerifier | null>(null);
100
+ if (verifierRef.current === null) {
101
+ verifierRef.current =
102
+ verifyToken ??
103
+ createDefaultVerifier(
104
+ apiUrl,
105
+ jwtIssuer ?? apiUrl.replace(/\/$/, ""),
106
+ jwtAudience,
107
+ );
108
+ }
109
+
110
+ // Keep mutable refs to the latest props so closures captured by
111
+ // the scheduler / async refresh loops always see fresh values.
112
+ const propsRef = useRef({
113
+ apiUrl,
114
+ projectId,
115
+ fetchImpl,
116
+ signInUrl,
117
+ emit,
118
+ });
119
+ propsRef.current = { apiUrl, projectId, fetchImpl, signInUrl, emit };
120
+
121
+ useEffect(() => {
122
+ if (!projectId) {
123
+ console.warn(
124
+ "[@useauthio/react] AuthioProvider projectId is missing — auth-core calls and Lobby sign-in will fail. Set projectId=\"proj_…\" on <AuthioProvider>.",
125
+ );
126
+ }
127
+ }, [projectId]);
128
+
129
+ const schedulerRef = useRef<RefreshScheduler | null>(null);
130
+
131
+ const [user, setUser] = useState<AuthioUser | null>(null);
132
+ const [status, setStatus] = useState<AuthioStatus>(
133
+ skipInitialRefresh ? "unauthenticated" : "loading",
134
+ );
135
+ const [accessToken, setAccessToken] = useState<string | null>(null);
136
+
137
+ /**
138
+ * Single refresh attempt. Returns `true` on success (state has
139
+ * been updated to authenticated), `false` on any failure (caller
140
+ * decides what to do with the failure — initial mount transitions
141
+ * to unauthenticated, scheduler backs off).
142
+ */
143
+ const performRefresh = useCallback(async (): Promise<boolean> => {
144
+ const p = propsRef.current;
145
+ try {
146
+ const env = await authioFetch<RefreshEnvelope>({
147
+ apiUrl: p.apiUrl,
148
+ projectId: p.projectId,
149
+ path: "/v1/auth/refresh",
150
+ method: "POST",
151
+ body: {},
152
+ credentials: "include",
153
+ fetchImpl: p.fetchImpl,
154
+ });
155
+ const token = env.access_token;
156
+ if (!token) {
157
+ p.emit({
158
+ kind: "refresh_failed",
159
+ timestamp: Date.now(),
160
+ reason: "missing_access_token",
161
+ attempt: 0,
162
+ });
163
+ return false;
164
+ }
165
+ const verification = await verifierRef.current!(token).catch(() => null);
166
+ if (!verification) {
167
+ p.emit({
168
+ kind: "token_rejected",
169
+ timestamp: Date.now(),
170
+ reason: "verification_failed",
171
+ });
172
+ p.emit({
173
+ kind: "refresh_failed",
174
+ timestamp: Date.now(),
175
+ reason: "verification_failed",
176
+ attempt: 0,
177
+ });
178
+ return false;
179
+ }
180
+ p.emit({
181
+ kind: "token_verified",
182
+ timestamp: Date.now(),
183
+ subject: verification.subject,
184
+ });
185
+ storageRef.current!.set(token);
186
+ setAccessToken(token);
187
+ if (env.user) setUser(coerceUser(env.user));
188
+ setStatus("authenticated");
189
+ p.emit({
190
+ kind: "refresh_succeeded",
191
+ timestamp: Date.now(),
192
+ expiresAt: verification.expiresAt,
193
+ });
194
+ const exp = verification.expiresAt ?? readJwtExp(token);
195
+ if (exp !== null && exp !== undefined) {
196
+ schedulerRef.current?.scheduleAt(exp);
197
+ }
198
+ return true;
199
+ } catch (err) {
200
+ const httpStatus = err instanceof AuthioError ? err.status : undefined;
201
+ const reason =
202
+ err instanceof Error ? err.message : "refresh_failed_unknown";
203
+ p.emit({
204
+ kind: "refresh_failed",
205
+ timestamp: Date.now(),
206
+ reason,
207
+ status: httpStatus,
208
+ attempt: 0,
209
+ });
210
+ return false;
211
+ }
212
+ }, []);
213
+
214
+ // Re-spin the scheduler whenever the lead window changes.
215
+ useEffect(() => {
216
+ schedulerRef.current = new RefreshScheduler({
217
+ leadSeconds: refreshLeadSeconds,
218
+ run: performRefresh,
219
+ onGiveUp: () => {
220
+ storageRef.current!.clear();
221
+ setAccessToken(null);
222
+ setUser(null);
223
+ setStatus("unauthenticated");
224
+ },
225
+ onScheduled: (runAt) =>
226
+ propsRef.current.emit({
227
+ kind: "refresh_scheduled",
228
+ timestamp: Date.now(),
229
+ runAt,
230
+ }),
231
+ });
232
+ return () => {
233
+ schedulerRef.current?.destroy();
234
+ schedulerRef.current = null;
235
+ };
236
+ }, [refreshLeadSeconds, performRefresh]);
237
+
238
+ // Initial bootstrap.
239
+ useEffect(() => {
240
+ if (skipInitialRefresh) {
241
+ // We still try to use a stored token if one is present — that
242
+ // way `skipInitialRefresh` plus a `localStorage` token lets a
243
+ // test or SSR-hydrated app come back authenticated without
244
+ // hitting the network.
245
+ const stored = storageRef.current!.get();
246
+ if (!stored) return;
247
+ let mounted = true;
248
+ (async () => {
249
+ const verification = await verifierRef.current!(stored).catch(
250
+ () => null,
251
+ );
252
+ if (!mounted) return;
253
+ if (!verification) {
254
+ storageRef.current!.clear();
255
+ setStatus("unauthenticated");
256
+ return;
257
+ }
258
+ propsRef.current.emit({
259
+ kind: "token_verified",
260
+ timestamp: Date.now(),
261
+ subject: verification.subject,
262
+ });
263
+ setAccessToken(stored);
264
+ setStatus("authenticated");
265
+ const exp = verification.expiresAt ?? readJwtExp(stored);
266
+ if (exp !== null && exp !== undefined) {
267
+ schedulerRef.current?.scheduleAt(exp);
268
+ }
269
+ })();
270
+ return () => {
271
+ mounted = false;
272
+ };
273
+ }
274
+ if (!isBrowser()) {
275
+ setStatus("unauthenticated");
276
+ return;
277
+ }
278
+ let mounted = true;
279
+ const stored = storageRef.current!.get();
280
+ if (stored) {
281
+ (async () => {
282
+ const verification = await verifierRef.current!(stored).catch(
283
+ () => null,
284
+ );
285
+ if (!mounted) return;
286
+ if (verification) {
287
+ propsRef.current.emit({
288
+ kind: "token_verified",
289
+ timestamp: Date.now(),
290
+ subject: verification.subject,
291
+ });
292
+ setAccessToken(stored);
293
+ setStatus("authenticated");
294
+ const exp = verification.expiresAt ?? readJwtExp(stored);
295
+ if (exp !== null && exp !== undefined) {
296
+ schedulerRef.current?.scheduleAt(exp);
297
+ }
298
+ return;
299
+ }
300
+ propsRef.current.emit({
301
+ kind: "token_rejected",
302
+ timestamp: Date.now(),
303
+ reason: "stored_token_invalid",
304
+ });
305
+ storageRef.current!.clear();
306
+ const ok = await performRefresh();
307
+ if (!ok && mounted) setStatus("unauthenticated");
308
+ })();
309
+ return () => {
310
+ mounted = false;
311
+ };
312
+ }
313
+ (async () => {
314
+ const ok = await performRefresh();
315
+ if (!ok && mounted) setStatus("unauthenticated");
316
+ })();
317
+ return () => {
318
+ mounted = false;
319
+ };
320
+ }, [skipInitialRefresh, performRefresh]);
321
+
322
+ const getAccessToken = useCallback(async (): Promise<string | null> => {
323
+ if (accessToken) {
324
+ const exp = readJwtExp(accessToken);
325
+ const now = Math.floor(Date.now() / 1000);
326
+ if (exp !== null && exp - now > 10) return accessToken;
327
+ }
328
+ const ok = await performRefresh();
329
+ return ok ? storageRef.current!.get() : null;
330
+ }, [accessToken, performRefresh]);
331
+
332
+ const signIn = useCallback(
333
+ (opts: { returnTo?: string } = {}) => {
334
+ const p = propsRef.current;
335
+ p.emit({
336
+ kind: "sign_in_started",
337
+ timestamp: Date.now(),
338
+ method: "redirect",
339
+ });
340
+ if (!isBrowser()) return;
341
+ if (!p.projectId) {
342
+ console.warn(
343
+ "[@useauthio/react] AuthioProvider projectId is missing — Lobby cannot resolve your project. Set projectId=\"proj_…\" on <AuthioProvider>.",
344
+ );
345
+ }
346
+ const base = p.signInUrl ?? DEFAULT_SIGN_IN_URL;
347
+ const url = new URL(base);
348
+ if (p.projectId) {
349
+ url.searchParams.set("project_id", p.projectId);
350
+ }
351
+ url.searchParams.set(
352
+ "redirect_uri",
353
+ opts.returnTo ?? window.location.href,
354
+ );
355
+ window.location.assign(url.toString());
356
+ },
357
+ [],
358
+ );
359
+
360
+ const signOut = useCallback(async (): Promise<void> => {
361
+ const p = propsRef.current;
362
+ const token = storageRef.current!.get();
363
+ try {
364
+ await authioFetch({
365
+ apiUrl: p.apiUrl,
366
+ projectId: p.projectId,
367
+ path: "/v1/auth/sign-out",
368
+ method: "POST",
369
+ body: {},
370
+ credentials: "include",
371
+ extraHeaders: token ? { Authorization: `Bearer ${token}` } : {},
372
+ fetchImpl: p.fetchImpl,
373
+ });
374
+ } catch {
375
+ // Best-effort. Local state still clears below — the worst case
376
+ // is the row outlives the local token, which is the pre-revocation
377
+ // baseline anyway.
378
+ } finally {
379
+ storageRef.current!.clear();
380
+ schedulerRef.current?.clear();
381
+ setAccessToken(null);
382
+ setUser(null);
383
+ setStatus("unauthenticated");
384
+ p.emit({ kind: "sign_out", timestamp: Date.now() });
385
+ }
386
+ }, []);
387
+
388
+ const refresh = useCallback(
389
+ (): Promise<boolean> => performRefresh(),
390
+ [performRefresh],
391
+ );
392
+
393
+ const value = useMemo<AuthioContextValue>(
394
+ () => ({
395
+ user,
396
+ status,
397
+ accessToken,
398
+ getAccessToken,
399
+ signIn,
400
+ signOut,
401
+ refresh,
402
+ }),
403
+ [user, status, accessToken, getAccessToken, signIn, signOut, refresh],
404
+ );
405
+
406
+ return (
407
+ <AuthioContext.Provider value={value}>{children}</AuthioContext.Provider>
408
+ );
409
+ }
410
+
411
+ function coerceUser(raw: RawUser): AuthioUser {
412
+ return {
413
+ id: String(raw.id ?? raw.user_id ?? ""),
414
+ email: String(raw.email ?? ""),
415
+ emailVerified: Boolean(raw.emailVerified ?? raw.email_verified ?? false),
416
+ name: raw.name ?? undefined,
417
+ avatarUrl: raw.avatarUrl ?? raw.avatar_url ?? undefined,
418
+ };
419
+ }
package/src/refresh.ts ADDED
@@ -0,0 +1,124 @@
1
+ import { isBrowser, isTabHidden } from "./ssr";
2
+
3
+ /**
4
+ * Backoff steps when a scheduled refresh fails. The 30s cap matches
5
+ * Authio's published recommendation for client-side rate limits —
6
+ * an SPA spinning at 30s on a single endpoint is well under the
7
+ * default project quota.
8
+ */
9
+ const BACKOFF_DELAYS_MS = [1000, 2000, 4000, 8000, 16000, 30000];
10
+ /** After five consecutive failures we surrender and transition to unauthenticated. */
11
+ const MAX_ATTEMPTS = 5;
12
+
13
+ export interface RefreshSchedulerOptions {
14
+ /** Schedule the silent refresh this many seconds before `exp`. */
15
+ leadSeconds: number;
16
+ /** Returns `true` on success, `false` on failure. Failures trigger backoff. */
17
+ run: () => Promise<boolean>;
18
+ /** Called after `MAX_ATTEMPTS` consecutive failures. */
19
+ onGiveUp: () => void;
20
+ /** Optional sink for "next refresh scheduled at" telemetry. */
21
+ onScheduled?: (runAt: number) => void;
22
+ }
23
+
24
+ /**
25
+ * Silent-refresh scheduler. Wraps a single `setTimeout` and a
26
+ * `visibilitychange` listener:
27
+ *
28
+ * - `scheduleAt(exp)` queues a refresh `leadSeconds` before `exp`.
29
+ * The clock resets `attempts` to zero.
30
+ * - When the timer fires, if the tab is hidden, we DEFER — the
31
+ * visibilitychange listener picks up where we left off when the
32
+ * tab returns. Saves battery on a sleeping background tab.
33
+ * - On failure we walk the `BACKOFF_DELAYS_MS` step list. After
34
+ * `MAX_ATTEMPTS` failures the scheduler calls `onGiveUp` and
35
+ * stops — the provider then transitions to `unauthenticated`.
36
+ * - `clear()` and `destroy()` cancel pending work; the latter
37
+ * also unhooks the visibility listener.
38
+ */
39
+ export class RefreshScheduler {
40
+ private timer: ReturnType<typeof setTimeout> | null = null;
41
+ private attempts = 0;
42
+ private lastExp: number | null = null;
43
+ private destroyed = false;
44
+ private visibilityHandler: (() => void) | null = null;
45
+
46
+ constructor(private readonly opts: RefreshSchedulerOptions) {
47
+ if (isBrowser()) {
48
+ this.visibilityHandler = () => {
49
+ if (this.destroyed) return;
50
+ if (!isTabHidden() && this.timer === null && this.lastExp !== null) {
51
+ this.scheduleAt(this.lastExp);
52
+ }
53
+ };
54
+ document.addEventListener("visibilitychange", this.visibilityHandler);
55
+ }
56
+ }
57
+
58
+ scheduleAt(exp: number): void {
59
+ if (this.destroyed) return;
60
+ this.lastExp = exp;
61
+ this.attempts = 0;
62
+ this.clear();
63
+ const now = Math.floor(Date.now() / 1000);
64
+ const delayMs = Math.max(0, (exp - now - this.opts.leadSeconds) * 1000);
65
+ this.opts.onScheduled?.(Date.now() + delayMs);
66
+ this.timer = setTimeout(() => void this.tick(), delayMs);
67
+ }
68
+
69
+ private async tick(): Promise<void> {
70
+ this.timer = null;
71
+ if (this.destroyed) return;
72
+ if (isTabHidden()) {
73
+ // Defer until the tab is visible again; the visibility handler
74
+ // will call scheduleAt when the user returns.
75
+ return;
76
+ }
77
+ let ok = false;
78
+ try {
79
+ ok = await this.opts.run();
80
+ } catch {
81
+ ok = false;
82
+ }
83
+ if (this.destroyed) return;
84
+ if (ok) {
85
+ // The provider's `run` callback is responsible for calling
86
+ // `scheduleAt(newExp)` on success. We do nothing further here.
87
+ return;
88
+ }
89
+ this.scheduleBackoff();
90
+ }
91
+
92
+ private scheduleBackoff(): void {
93
+ if (this.destroyed) return;
94
+ if (this.attempts >= MAX_ATTEMPTS) {
95
+ this.opts.onGiveUp();
96
+ this.lastExp = null;
97
+ return;
98
+ }
99
+ const delay =
100
+ BACKOFF_DELAYS_MS[Math.min(this.attempts, BACKOFF_DELAYS_MS.length - 1)] ??
101
+ 30_000;
102
+ this.attempts++;
103
+ this.opts.onScheduled?.(Date.now() + delay);
104
+ this.timer = setTimeout(() => void this.tick(), delay);
105
+ }
106
+
107
+ /** Cancel any pending timer but keep the scheduler alive for re-scheduling. */
108
+ clear(): void {
109
+ if (this.timer !== null) {
110
+ clearTimeout(this.timer);
111
+ this.timer = null;
112
+ }
113
+ }
114
+
115
+ /** Permanently stop and unhook listeners. */
116
+ destroy(): void {
117
+ this.destroyed = true;
118
+ this.clear();
119
+ if (this.visibilityHandler && isBrowser()) {
120
+ document.removeEventListener("visibilitychange", this.visibilityHandler);
121
+ }
122
+ this.visibilityHandler = null;
123
+ }
124
+ }