@useauthio/react 0.2.4 → 0.3.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.
package/src/locate.ts CHANGED
@@ -55,3 +55,45 @@ export function captureClientLocation(
55
55
  );
56
56
  });
57
57
  }
58
+
59
+ export type LocateAction = "sign_in" | "wager_placed" | "contest_entry" | string;
60
+
61
+ export interface VerifyLocateOptions {
62
+ apiUrl: string;
63
+ projectId: string;
64
+ accessToken: string;
65
+ action: LocateAction;
66
+ clientLocation?: ClientLocationCapture;
67
+ idempotencyKey?: string;
68
+ fetchImpl?: typeof fetch;
69
+ signal?: AbortSignal;
70
+ }
71
+
72
+ export interface LocateVerifyResult {
73
+ verification_id: string;
74
+ decision: "allow" | "block";
75
+ confidence: number;
76
+ method: string;
77
+ location: { country: string; region: string; source: string };
78
+ network_signals: {
79
+ vpn: boolean;
80
+ datacenter: boolean;
81
+ tor: boolean;
82
+ anonymous_proxy: boolean;
83
+ satellite: boolean;
84
+ };
85
+ evasion_signals: string[];
86
+ }
87
+
88
+ const VERIFY_LOCATE_BACKEND_ONLY =
89
+ "verifyLocate() is not supported in @useauthio/react: POST /v1/locate/verify requires a project secret key (sk_live_/sk_test_), not a user JWT. " +
90
+ "Capture GPS with captureClientLocation(), POST to your backend, and call authio.locate.verify() via @useauthio/node. " +
91
+ "See authio_locate/docs/JB_MIGRATION_GUIDE.md.";
92
+
93
+ /**
94
+ * @deprecated Use backend proxy with `@useauthio/node` `authio.locate.verify()` — see JB migration guide.
95
+ * This helper always throws; it must not send a user JWT to the sk_-only verify route.
96
+ */
97
+ export async function verifyLocate(_opts: VerifyLocateOptions): Promise<LocateVerifyResult> {
98
+ throw new Error(VERIFY_LOCATE_BACKEND_ONLY);
99
+ }
package/src/passkeys.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { AuthioError } from "@useauthio/node";
2
2
  import { startRegistration } from "@simplewebauthn/browser";
3
3
  import { authioFetch } from "./fetch";
4
+ import { AUTHIO_MESSAGES } from "./errors";
4
5
  import { isBrowser } from "./ssr";
5
6
 
6
7
  export interface AuthioPasskey {
@@ -120,7 +121,8 @@ export async function enrollPasskey(opts: EnrollPasskeyOptions): Promise<void> {
120
121
  if (!isBrowser()) {
121
122
  throw new AuthioError({
122
123
  code: "not_in_browser",
123
- message: "enrollPasskey can only be invoked in a browser environment.",
124
+ message:
125
+ "Passkey setup only works in a web browser. Call enrollPasskey from client-side code.",
124
126
  status: 0,
125
127
  });
126
128
  }
@@ -150,7 +152,8 @@ export async function addPasskey(opts: AddPasskeyOptions): Promise<void> {
150
152
  if (!isBrowser()) {
151
153
  throw new AuthioError({
152
154
  code: "not_in_browser",
153
- message: "addPasskey can only be invoked in a browser environment.",
155
+ message:
156
+ "Passkey setup only works in a web browser. Call addPasskey from client-side code.",
154
157
  status: 0,
155
158
  });
156
159
  }
@@ -175,14 +178,21 @@ export async function addPasskey(opts: AddPasskeyOptions): Promise<void> {
175
178
  try {
176
179
  attestation = await startRegistration({ optionsJSON: options });
177
180
  } catch (err) {
178
- throw new AuthioError({
179
- code: "webauthn_cancelled",
180
- message:
181
- err instanceof Error
182
- ? err.message
183
- : "Passkey registration cancelled by user.",
181
+ // Browser/WebAuthn text is not user-friendly; keep it on `cause`.
182
+ const already =
183
+ err instanceof Error &&
184
+ (err.name === "InvalidStateError" ||
185
+ (err as { code?: string }).code ===
186
+ "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED");
187
+ const e = new AuthioError({
188
+ code: already ? "webauthn_already_registered" : "webauthn_cancelled",
189
+ message: already
190
+ ? AUTHIO_MESSAGES.webauthn_already_registered
191
+ : AUTHIO_MESSAGES.webauthn_registration_cancelled,
184
192
  status: 0,
185
193
  });
194
+ Object.defineProperty(e, "cause", { value: err, enumerable: false });
195
+ throw e;
186
196
  }
187
197
 
188
198
  await authioFetch<{ ok?: boolean }>({
package/src/provider.tsx CHANGED
@@ -9,17 +9,21 @@ import React, {
9
9
  import { AuthioError } from "@useauthio/node";
10
10
  import { authioFetch } from "./fetch";
11
11
  import { createDefaultVerifier, readJwtExp } from "./jwt";
12
+ import { ActivityTracker } from "./activity";
12
13
  import { RefreshScheduler } from "./refresh";
13
14
  import { isBrowser } from "./ssr";
14
15
  import { createTokenStorage, type TokenStorage } from "./storage";
15
16
  import { mintLobbySignInUrl } from "./lobby-context";
16
17
  import { noopEmitter, type TelemetryEmitter } from "./telemetry";
17
- import type {
18
- AuthioContextValue,
19
- AuthioProviderProps,
20
- AuthioStatus,
21
- AuthioTokenVerifier,
22
- AuthioUser,
18
+ import {
19
+ coerceSessionPolicy,
20
+ type AuthioContextValue,
21
+ type AuthioProviderProps,
22
+ type AuthioStatus,
23
+ type AuthioTokenVerifier,
24
+ type AuthioUser,
25
+ type RawSessionPolicy,
26
+ type SessionPolicy,
23
27
  } from "./types";
24
28
 
25
29
  export const AuthioContext = createContext<AuthioContextValue | null>(null);
@@ -30,8 +34,17 @@ interface RefreshEnvelope {
30
34
  refresh_token?: string;
31
35
  expires_at?: string;
32
36
  user?: RawUser | null;
37
+ session_policy?: RawSessionPolicy;
33
38
  }
34
39
 
40
+ /**
41
+ * Grace window around a refresh inside which user activity still counts
42
+ * as "after" it. The tracker throttles writes to 1/s, so an interaction
43
+ * landing just after a refresh may carry a timestamp just before it;
44
+ * we err toward refreshing.
45
+ */
46
+ const ACTIVITY_GRACE_MS = 1000;
47
+
35
48
  interface RawUser {
36
49
  id?: string;
37
50
  user_id?: string;
@@ -77,6 +90,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
77
90
  projectId,
78
91
  storage: storageMode = "memory",
79
92
  refreshLeadSeconds = DEFAULT_REFRESH_LEAD,
93
+ idleRefresh = "defer",
80
94
  onTelemetryEvent,
81
95
  fetch: fetchImpl,
82
96
  signInUrl,
@@ -116,8 +130,24 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
116
130
  fetchImpl,
117
131
  signInUrl,
118
132
  emit,
133
+ idleRefresh,
119
134
  });
120
- propsRef.current = { apiUrl, projectId, fetchImpl, signInUrl, emit };
135
+ propsRef.current = { apiUrl, projectId, fetchImpl, signInUrl, emit, idleRefresh };
136
+
137
+ // User-activity tracker + the two timestamps the idle-deferral rule
138
+ // compares. Refs, not state: the scheduler reads them from a timer
139
+ // callback and a re-render must never re-create the tracker.
140
+ const activityRef = useRef<ActivityTracker | null>(null);
141
+ // Lazily (re)created so a StrictMode double-mount, which destroys the
142
+ // tracker in the simulated unmount, gets a fresh one on the re-run.
143
+ const getTracker = useCallback((): ActivityTracker => {
144
+ if (activityRef.current === null) {
145
+ activityRef.current = new ActivityTracker();
146
+ }
147
+ return activityRef.current;
148
+ }, []);
149
+ const lastRefreshAtRef = useRef(0);
150
+ const policyRef = useRef<SessionPolicy | null>(null);
121
151
 
122
152
  useEffect(() => {
123
153
  if (!projectId) {
@@ -143,6 +173,20 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
143
173
  skipInitialRefresh ? "unauthenticated" : "loading",
144
174
  );
145
175
  const [accessToken, setAccessToken] = useState<string | null>(null);
176
+ const [sessionPolicy, setSessionPolicy] = useState<SessionPolicy | null>(null);
177
+
178
+ /** Adopt a policy from an envelope and mark "refreshed now". */
179
+ const adoptPolicy = useCallback((policy: SessionPolicy | null) => {
180
+ policyRef.current = policy;
181
+ setSessionPolicy(policy);
182
+ lastRefreshAtRef.current = Date.now();
183
+ }, []);
184
+
185
+ const clearPolicy = useCallback(() => {
186
+ policyRef.current = null;
187
+ setSessionPolicy(null);
188
+ lastRefreshAtRef.current = 0;
189
+ }, []);
146
190
 
147
191
  /**
148
192
  * Single refresh attempt. Returns `true` on success (state has
@@ -199,6 +243,13 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
199
243
  setAccessToken(token);
200
244
  if (env.user) setUser(coerceUser(env.user));
201
245
  setStatus("authenticated");
246
+ // Older auth-core omits session_policy; keep whatever we last saw
247
+ // rather than flapping to null and re-enabling timer refresh.
248
+ adoptPolicy(
249
+ env.session_policy !== undefined
250
+ ? coerceSessionPolicy(env.session_policy)
251
+ : policyRef.current,
252
+ );
202
253
  p.emit({
203
254
  kind: "refresh_succeeded",
204
255
  timestamp: Date.now(),
@@ -222,16 +273,17 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
222
273
  });
223
274
  return false;
224
275
  }
225
- }, []);
276
+ }, [adoptPolicy]);
226
277
 
227
278
  // Re-spin the scheduler whenever the lead window changes.
228
279
  useEffect(() => {
229
- schedulerRef.current = new RefreshScheduler({
280
+ const scheduler = new RefreshScheduler({
230
281
  leadSeconds: refreshLeadSeconds,
231
282
  run: performRefresh,
232
283
  onGiveUp: () => {
233
284
  storageRef.current!.clear();
234
285
  refreshTokenRef.current = null;
286
+ clearPolicy();
235
287
  setAccessToken(null);
236
288
  setUser(null);
237
289
  setStatus("unauthenticated");
@@ -242,12 +294,48 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
242
294
  timestamp: Date.now(),
243
295
  runAt,
244
296
  }),
297
+ // Idle rule: hold the timer refresh when the effective policy has
298
+ // an inactivity timeout and the user hasn't touched the page since
299
+ // the last refresh. Without a policy (legacy projects, old
300
+ // auth-core) this is never true and behaviour is unchanged.
301
+ shouldDefer: () => {
302
+ if (propsRef.current.idleRefresh === "always") return false;
303
+ const policy = policyRef.current;
304
+ if (!policy || policy.idleTimeoutMin <= 0) return false;
305
+ const lastActivity = getTracker().lastActivityAt();
306
+ return lastActivity + ACTIVITY_GRACE_MS < lastRefreshAtRef.current;
307
+ },
308
+ onDeferred: (reason) =>
309
+ propsRef.current.emit({
310
+ kind: "refresh_deferred",
311
+ timestamp: Date.now(),
312
+ reason,
313
+ }),
314
+ });
315
+ schedulerRef.current = scheduler;
316
+ // The next interaction after an idle deferral re-arms the timer —
317
+ // immediately, if the token is already inside its lead window.
318
+ const tracker = getTracker();
319
+ const unsubscribe = tracker.onActivity(() => {
320
+ if (scheduler.deferredReason() !== "idle") return;
321
+ propsRef.current.emit({ kind: "refresh_resumed", timestamp: Date.now() });
322
+ scheduler.resume();
245
323
  });
246
324
  return () => {
247
- schedulerRef.current?.destroy();
248
- schedulerRef.current = null;
325
+ unsubscribe();
326
+ scheduler.destroy();
327
+ if (schedulerRef.current === scheduler) schedulerRef.current = null;
249
328
  };
250
- }, [refreshLeadSeconds, performRefresh]);
329
+ }, [refreshLeadSeconds, performRefresh, clearPolicy, getTracker]);
330
+
331
+ // Tear the activity tracker down with the provider.
332
+ useEffect(() => {
333
+ const tracker = getTracker();
334
+ return () => {
335
+ tracker.destroy();
336
+ if (activityRef.current === tracker) activityRef.current = null;
337
+ };
338
+ }, [getTracker]);
251
339
 
252
340
  // Initial bootstrap.
253
341
  useEffect(() => {
@@ -390,12 +478,13 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
390
478
  storageRef.current!.clear();
391
479
  refreshTokenRef.current = null;
392
480
  schedulerRef.current?.clear();
481
+ clearPolicy();
393
482
  setAccessToken(null);
394
483
  setUser(null);
395
484
  setStatus("unauthenticated");
396
485
  p.emit({ kind: "sign_out", timestamp: Date.now() });
397
486
  }
398
- }, []);
487
+ }, [clearPolicy]);
399
488
 
400
489
  const refresh = useCallback(
401
490
  (): Promise<boolean> => performRefresh(),
@@ -407,6 +496,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
407
496
  accessToken: string;
408
497
  refreshToken?: string | null;
409
498
  user?: AuthioUser | null;
499
+ sessionPolicy?: SessionPolicy | null;
410
500
  }): Promise<void> => {
411
501
  const p = propsRef.current;
412
502
  const verification = await verifierRef
@@ -427,7 +517,8 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
427
517
  setStatus("unauthenticated");
428
518
  throw new AuthioError({
429
519
  code: "token_rejected",
430
- message: "Authio rejected the handed-off access token signature.",
520
+ message:
521
+ "We couldn't verify your sign-in. Please sign in again.",
431
522
  status: 0,
432
523
  });
433
524
  }
@@ -441,6 +532,9 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
441
532
  setAccessToken(input.accessToken);
442
533
  if (input.user) setUser(input.user);
443
534
  setStatus("authenticated");
535
+ adoptPolicy(
536
+ input.sessionPolicy !== undefined ? input.sessionPolicy : policyRef.current,
537
+ );
444
538
  p.emit({
445
539
  kind: "sign_in_completed",
446
540
  timestamp: Date.now(),
@@ -451,7 +545,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
451
545
  schedulerRef.current?.scheduleAt(exp);
452
546
  }
453
547
  },
454
- [],
548
+ [adoptPolicy],
455
549
  );
456
550
 
457
551
  const resolvedSignInUrl = signInUrl ?? DEFAULT_SIGN_IN_URL;
@@ -461,6 +555,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
461
555
  user,
462
556
  status,
463
557
  accessToken,
558
+ sessionPolicy,
464
559
  apiUrl,
465
560
  projectId,
466
561
  signInUrl: resolvedSignInUrl,
@@ -475,6 +570,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
475
570
  user,
476
571
  status,
477
572
  accessToken,
573
+ sessionPolicy,
478
574
  apiUrl,
479
575
  projectId,
480
576
  resolvedSignInUrl,
package/src/refresh.ts CHANGED
@@ -10,6 +10,8 @@ const BACKOFF_DELAYS_MS = [1000, 2000, 4000, 8000, 16000, 30000];
10
10
  /** After five consecutive failures we surrender and transition to unauthenticated. */
11
11
  const MAX_ATTEMPTS = 5;
12
12
 
13
+ export type RefreshDeferReason = "hidden" | "idle";
14
+
13
15
  export interface RefreshSchedulerOptions {
14
16
  /** Schedule the silent refresh this many seconds before `exp`. */
15
17
  leadSeconds: number;
@@ -19,6 +21,15 @@ export interface RefreshSchedulerOptions {
19
21
  onGiveUp: () => void;
20
22
  /** Optional sink for "next refresh scheduled at" telemetry. */
21
23
  onScheduled?: (runAt: number) => void;
24
+ /**
25
+ * Consulted when the timer fires (after the hidden-tab check). Return
26
+ * `true` to hold the refresh until `resume()` is called — the
27
+ * provider uses this to skip refreshing while the user is idle under
28
+ * an inactivity policy. Omit for the legacy always-refresh behaviour.
29
+ */
30
+ shouldDefer?: () => boolean;
31
+ /** Fired when a tick is held back, with the reason. */
32
+ onDeferred?: (reason: RefreshDeferReason) => void;
22
33
  }
23
34
 
24
35
  /**
@@ -30,6 +41,10 @@ export interface RefreshSchedulerOptions {
30
41
  * - When the timer fires, if the tab is hidden, we DEFER — the
31
42
  * visibilitychange listener picks up where we left off when the
32
43
  * tab returns. Saves battery on a sleeping background tab.
44
+ * - If `shouldDefer()` says so (user idle under an inactivity
45
+ * policy), we also DEFER and wait for `resume()` — the provider
46
+ * calls it on the next user interaction, which re-runs the tick
47
+ * immediately when the token is inside its lead window.
33
48
  * - On failure we walk the `BACKOFF_DELAYS_MS` step list. After
34
49
  * `MAX_ATTEMPTS` failures the scheduler calls `onGiveUp` and
35
50
  * stops — the provider then transitions to `unauthenticated`.
@@ -41,6 +56,7 @@ export class RefreshScheduler {
41
56
  private attempts = 0;
42
57
  private lastExp: number | null = null;
43
58
  private destroyed = false;
59
+ private deferred: RefreshDeferReason | null = null;
44
60
  private visibilityHandler: (() => void) | null = null;
45
61
 
46
62
  constructor(private readonly opts: RefreshSchedulerOptions) {
@@ -55,10 +71,16 @@ export class RefreshScheduler {
55
71
  }
56
72
  }
57
73
 
74
+ /** Whether the last tick was held back (and why). `null` when not deferred. */
75
+ deferredReason(): RefreshDeferReason | null {
76
+ return this.deferred;
77
+ }
78
+
58
79
  scheduleAt(exp: number): void {
59
80
  if (this.destroyed) return;
60
81
  this.lastExp = exp;
61
82
  this.attempts = 0;
83
+ this.deferred = null;
62
84
  this.clear();
63
85
  const now = Math.floor(Date.now() / 1000);
64
86
  const delayMs = Math.max(0, (exp - now - this.opts.leadSeconds) * 1000);
@@ -66,14 +88,33 @@ export class RefreshScheduler {
66
88
  this.timer = setTimeout(() => void this.tick(), delayMs);
67
89
  }
68
90
 
91
+ /**
92
+ * Re-arm after a deferral. No-op unless a tick is currently held
93
+ * back. Re-schedules against the remembered `exp`, so a token that
94
+ * is already inside its lead window refreshes immediately.
95
+ */
96
+ resume(): void {
97
+ if (this.destroyed || this.deferred === null || this.lastExp === null) return;
98
+ this.scheduleAt(this.lastExp);
99
+ }
100
+
69
101
  private async tick(): Promise<void> {
70
102
  this.timer = null;
71
103
  if (this.destroyed) return;
72
104
  if (isTabHidden()) {
73
105
  // Defer until the tab is visible again; the visibility handler
74
106
  // will call scheduleAt when the user returns.
107
+ this.deferred = "hidden";
108
+ this.opts.onDeferred?.("hidden");
109
+ return;
110
+ }
111
+ if (this.opts.shouldDefer?.()) {
112
+ // User is idle under an inactivity policy. Hold until resume().
113
+ this.deferred = "idle";
114
+ this.opts.onDeferred?.("idle");
75
115
  return;
76
116
  }
117
+ this.deferred = null;
77
118
  let ok = false;
78
119
  try {
79
120
  ok = await this.opts.run();