@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/dist/index.js CHANGED
@@ -1,36 +1,150 @@
1
- import { createContext, useRef, useEffect, useState, useCallback, useMemo, useContext } from 'react';
1
+ import { createContext, useRef, useCallback, useEffect, useState, useMemo, useContext } from 'react';
2
2
  import { AuthioError, JwtVerifier } from '@useauthio/node';
3
3
  export { AuthioError } from '@useauthio/node';
4
4
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
5
5
  import { startRegistration } from '@simplewebauthn/browser';
6
6
 
7
7
  // src/provider.tsx
8
+ var AUTHIO_MESSAGES = {
9
+ network_error: "We couldn't reach the sign-in service. Check your internet connection and try again.",
10
+ timeout: "The sign-in service took too long to respond. Please try again.",
11
+ aborted: "The request was cancelled before it finished. Please try again.",
12
+ invalid_response: "We couldn't finish signing you in because the sign-in service sent an unexpected response. Please try again.",
13
+ step_up_required: "For your security, we need one more check before signing you in.",
14
+ sign_in_denied: "We couldn't sign you in. If you think this is a mistake, contact support or your administrator.",
15
+ rate_limited: "Too many attempts. Please wait a moment and try again.",
16
+ server_error: "Something went wrong on our side. Please try again in a moment.",
17
+ request_failed: "We couldn't complete that request. Please try again.",
18
+ webauthn_cancelled: "Passkey sign-in was cancelled or timed out. Please try again.",
19
+ webauthn_registration_cancelled: "Passkey setup was cancelled or timed out. Please try again.",
20
+ webauthn_already_registered: "This device already has a passkey for your account.",
21
+ webauthn_unsupported: "This browser doesn't support passkeys. Try a different browser, or sign in another way.",
22
+ not_signed_in: "You need to be signed in to do that. Please sign in and try again.",
23
+ token_rejected: "We couldn't verify your sign-in. Please sign in again."
24
+ };
25
+ function withCause(err, cause) {
26
+ if (cause !== void 0) {
27
+ Object.defineProperty(err, "cause", {
28
+ value: cause,
29
+ enumerable: false,
30
+ configurable: true,
31
+ writable: true
32
+ });
33
+ }
34
+ return err;
35
+ }
8
36
  function wrapFetchError(err, fallbackCode = "network_error") {
9
37
  if (err instanceof AuthioError) return err;
10
- if (err instanceof Error && err.name === "AbortError") {
11
- return new AuthioError({
12
- code: "aborted",
13
- message: err.message || "Request aborted",
14
- status: 0
38
+ const e = err && typeof err === "object" ? err : {};
39
+ const name = typeof e.name === "string" ? e.name : "";
40
+ const rawMessage = typeof e.message === "string" ? e.message : "";
41
+ const isTimeout = name === "TimeoutError" || /timed? ?out/i.test(rawMessage);
42
+ if (isTimeout) {
43
+ return withCause(
44
+ new AuthioError({
45
+ code: "timeout",
46
+ message: AUTHIO_MESSAGES.timeout,
47
+ status: 0
48
+ }),
49
+ err
50
+ );
51
+ }
52
+ if (name === "AbortError") {
53
+ return withCause(
54
+ new AuthioError({
55
+ code: "aborted",
56
+ message: AUTHIO_MESSAGES.aborted,
57
+ status: 0
58
+ }),
59
+ err
60
+ );
61
+ }
62
+ const message = fallbackCode === "network_error" ? AUTHIO_MESSAGES.network_error : AUTHIO_MESSAGES.request_failed;
63
+ return withCause(
64
+ new AuthioError({ code: fallbackCode, message, status: 0 }),
65
+ err
66
+ );
67
+ }
68
+ function messageForStatus(status) {
69
+ if (status === 429) return AUTHIO_MESSAGES.rate_limited;
70
+ if (status >= 500) return AUTHIO_MESSAGES.server_error;
71
+ return AUTHIO_MESSAGES.request_failed;
72
+ }
73
+ var AuthioStepUpRequiredError = class extends AuthioError {
74
+ stepUpUrl;
75
+ challengeId;
76
+ requiredMethod;
77
+ reasons;
78
+ enrollmentRequired;
79
+ /** auth-core's own explanation of the step, when it sent one. */
80
+ serverMessage;
81
+ constructor(opts) {
82
+ super({
83
+ code: "step_up_required",
84
+ message: AUTHIO_MESSAGES.step_up_required,
85
+ status: opts.status,
86
+ requestId: opts.requestId
15
87
  });
88
+ this.name = "AuthioStepUpRequiredError";
89
+ this.stepUpUrl = opts.stepUpUrl;
90
+ this.challengeId = opts.challengeId;
91
+ this.requiredMethod = opts.requiredMethod;
92
+ this.reasons = opts.reasons ?? [];
93
+ this.enrollmentRequired = Boolean(opts.enrollmentRequired);
94
+ this.serverMessage = opts.serverMessage;
16
95
  }
17
- if (err instanceof Error && /timeout/i.test(err.message)) {
18
- return new AuthioError({
19
- code: "timeout",
20
- message: err.message,
21
- status: 0
96
+ };
97
+ var AuthioSignInDeniedError = class extends AuthioError {
98
+ denyCode;
99
+ reasons;
100
+ constructor(opts) {
101
+ super({
102
+ code: "sign_in_denied",
103
+ message: nonEmpty(opts.message) ?? AUTHIO_MESSAGES.sign_in_denied,
104
+ status: opts.status,
105
+ requestId: opts.requestId
22
106
  });
107
+ this.name = "AuthioSignInDeniedError";
108
+ this.denyCode = opts.denyCode;
109
+ this.reasons = opts.reasons ?? [];
23
110
  }
24
- const message = err instanceof Error ? err.message : "Unknown network error";
25
- return new AuthioError({
26
- code: fallbackCode,
27
- message,
28
- status: 0
29
- });
111
+ };
112
+ function isStepUpRequired(err) {
113
+ return err instanceof AuthioStepUpRequiredError;
114
+ }
115
+ function riskDecisionError(body, status) {
116
+ if (!body || typeof body !== "object") return null;
117
+ const decision = typeof body.decision === "string" ? body.decision : "";
118
+ const reasons = Array.isArray(body.reasons) ? body.reasons.filter((r) => typeof r === "string") : [];
119
+ if (decision === "step_up" || body.code === "step_up_required") {
120
+ return new AuthioStepUpRequiredError({
121
+ status,
122
+ stepUpUrl: nonEmpty(body.step_up_url),
123
+ challengeId: nonEmpty(body.challenge_id),
124
+ requiredMethod: nonEmpty(body.required_method),
125
+ reasons,
126
+ enrollmentRequired: body.enrollment_required === true,
127
+ serverMessage: nonEmpty(body.message),
128
+ requestId: body.request_id
129
+ });
130
+ }
131
+ if (decision === "block" || decision === "deny") {
132
+ return new AuthioSignInDeniedError({
133
+ status,
134
+ message: body.message,
135
+ denyCode: nonEmpty(body.code) ?? nonEmpty(body.error),
136
+ reasons,
137
+ requestId: body.request_id
138
+ });
139
+ }
140
+ return null;
141
+ }
142
+ function nonEmpty(v) {
143
+ return typeof v === "string" && v.trim() !== "" ? v : void 0;
30
144
  }
31
145
 
32
146
  // src/version.ts
33
- var SDK_VERSION = "0.2.2";
147
+ var SDK_VERSION = "0.3.1";
34
148
  var SDK_USER_AGENT = `react/${SDK_VERSION}`;
35
149
 
36
150
  // src/fetch.ts
@@ -75,10 +189,14 @@ async function authioFetch(opts) {
75
189
  if (opts.signal) opts.signal.removeEventListener("abort", onCallerAbort);
76
190
  }
77
191
  if (!res.ok) {
78
- const body = await res.json().catch(() => ({}));
192
+ const raw = await res.json().catch(() => ({}));
193
+ const body = raw && typeof raw === "object" ? raw : {};
194
+ const risk = riskDecisionError(body, res.status);
195
+ if (risk) throw risk;
196
+ const message = typeof body.message === "string" && body.message.trim() !== "" ? body.message : messageForStatus(res.status);
79
197
  throw new AuthioError({
80
198
  code: body.code ?? body.error ?? "request_failed",
81
- message: body.message ?? `Request to ${opts.path} failed with status ${res.status}`,
199
+ message,
82
200
  status: res.status,
83
201
  requestId: body.request_id
84
202
  });
@@ -91,7 +209,7 @@ async function authioFetch(opts) {
91
209
  } catch {
92
210
  throw new AuthioError({
93
211
  code: "invalid_response",
94
- message: `Response from ${opts.path} was not valid JSON`,
212
+ message: AUTHIO_MESSAGES.invalid_response,
95
213
  status: res.status
96
214
  });
97
215
  }
@@ -140,6 +258,74 @@ function isTabHidden() {
140
258
  return document.visibilityState === "hidden";
141
259
  }
142
260
 
261
+ // src/activity.ts
262
+ var ACTIVITY_EVENTS = [
263
+ "pointerdown",
264
+ "keydown",
265
+ "touchstart",
266
+ "scroll",
267
+ "focus"
268
+ ];
269
+ var THROTTLE_MS = 1e3;
270
+ var ActivityTracker = class {
271
+ last = 0;
272
+ listeners = /* @__PURE__ */ new Set();
273
+ handler = null;
274
+ visibilityHandler = null;
275
+ destroyed = false;
276
+ constructor(now = Date.now) {
277
+ this.now = now;
278
+ if (!isBrowser()) return;
279
+ this.handler = () => this.mark();
280
+ for (const ev of ACTIVITY_EVENTS) {
281
+ window.addEventListener(ev, this.handler, { passive: true, capture: true });
282
+ }
283
+ this.visibilityHandler = () => {
284
+ if (!isTabHidden()) this.mark();
285
+ };
286
+ document.addEventListener("visibilitychange", this.visibilityHandler);
287
+ }
288
+ now;
289
+ /** Unix ms of the most recent recorded interaction, `0` if none yet. */
290
+ lastActivityAt() {
291
+ return this.last;
292
+ }
293
+ /**
294
+ * Record activity now. Throttled to one write per second; listeners
295
+ * fire only when a write actually happens. Exposed so tests (and
296
+ * embedders with their own activity signal) can poke it directly.
297
+ */
298
+ mark() {
299
+ if (this.destroyed) return;
300
+ const t = this.now();
301
+ if (t - this.last < THROTTLE_MS) return;
302
+ this.last = t;
303
+ for (const l of this.listeners) l(t);
304
+ }
305
+ /** Subscribe to recorded activity. Returns an unsubscribe function. */
306
+ onActivity(listener) {
307
+ this.listeners.add(listener);
308
+ return () => {
309
+ this.listeners.delete(listener);
310
+ };
311
+ }
312
+ destroy() {
313
+ this.destroyed = true;
314
+ this.listeners.clear();
315
+ if (!isBrowser()) return;
316
+ if (this.handler) {
317
+ for (const ev of ACTIVITY_EVENTS) {
318
+ window.removeEventListener(ev, this.handler, { capture: true });
319
+ }
320
+ }
321
+ if (this.visibilityHandler) {
322
+ document.removeEventListener("visibilitychange", this.visibilityHandler);
323
+ }
324
+ this.handler = null;
325
+ this.visibilityHandler = null;
326
+ }
327
+ };
328
+
143
329
  // src/refresh.ts
144
330
  var BACKOFF_DELAYS_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
145
331
  var MAX_ATTEMPTS = 5;
@@ -161,23 +347,46 @@ var RefreshScheduler = class {
161
347
  attempts = 0;
162
348
  lastExp = null;
163
349
  destroyed = false;
350
+ deferred = null;
164
351
  visibilityHandler = null;
352
+ /** Whether the last tick was held back (and why). `null` when not deferred. */
353
+ deferredReason() {
354
+ return this.deferred;
355
+ }
165
356
  scheduleAt(exp) {
166
357
  if (this.destroyed) return;
167
358
  this.lastExp = exp;
168
359
  this.attempts = 0;
360
+ this.deferred = null;
169
361
  this.clear();
170
362
  const now = Math.floor(Date.now() / 1e3);
171
363
  const delayMs = Math.max(0, (exp - now - this.opts.leadSeconds) * 1e3);
172
364
  this.opts.onScheduled?.(Date.now() + delayMs);
173
365
  this.timer = setTimeout(() => void this.tick(), delayMs);
174
366
  }
367
+ /**
368
+ * Re-arm after a deferral. No-op unless a tick is currently held
369
+ * back. Re-schedules against the remembered `exp`, so a token that
370
+ * is already inside its lead window refreshes immediately.
371
+ */
372
+ resume() {
373
+ if (this.destroyed || this.deferred === null || this.lastExp === null) return;
374
+ this.scheduleAt(this.lastExp);
375
+ }
175
376
  async tick() {
176
377
  this.timer = null;
177
378
  if (this.destroyed) return;
178
379
  if (isTabHidden()) {
380
+ this.deferred = "hidden";
381
+ this.opts.onDeferred?.("hidden");
382
+ return;
383
+ }
384
+ if (this.opts.shouldDefer?.()) {
385
+ this.deferred = "idle";
386
+ this.opts.onDeferred?.("idle");
179
387
  return;
180
388
  }
389
+ this.deferred = null;
181
390
  let ok = false;
182
391
  try {
183
392
  ok = await this.opts.run();
@@ -306,7 +515,9 @@ async function mintLobbySignInUrl(opts) {
306
515
  body: JSON.stringify({
307
516
  project_id: opts.projectId,
308
517
  redirect_uri: opts.redirectUri,
309
- ...opts.next ? { next: opts.next } : {}
518
+ ...opts.next ? { next: opts.next } : {},
519
+ ...opts.organizationId ? { organization_id: opts.organizationId } : {},
520
+ ...opts.xrayVisitorProof ? { xray_visitor_proof: opts.xrayVisitorProof } : {}
310
521
  })
311
522
  }
312
523
  );
@@ -327,14 +538,32 @@ async function mintLobbySignInUrl(opts) {
327
538
  if (opts.next) {
328
539
  target.searchParams.set("next", opts.next);
329
540
  }
541
+ if (opts.organizationId) {
542
+ target.searchParams.set("organization_id", opts.organizationId);
543
+ }
544
+ if (opts.xrayVisitorProof) {
545
+ target.searchParams.set("xray_visitor_proof", opts.xrayVisitorProof);
546
+ }
330
547
  return target.toString();
331
548
  }
332
549
 
333
550
  // src/telemetry.ts
334
551
  var noopEmitter = () => {
335
552
  };
553
+
554
+ // src/types.ts
555
+ function coerceSessionPolicy(raw) {
556
+ if (!raw || typeof raw !== "object") return null;
557
+ const n = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0;
558
+ return {
559
+ idleTimeoutMin: n(raw.idle_timeout_min),
560
+ absoluteMaxMin: n(raw.absolute_max_min),
561
+ accessTokenTtlMin: n(raw.access_token_ttl_min)
562
+ };
563
+ }
336
564
  var AuthioContext = createContext(null);
337
565
  AuthioContext.displayName = "AuthioContext";
566
+ var ACTIVITY_GRACE_MS = 1e3;
338
567
  var DEFAULT_REFRESH_LEAD = 60;
339
568
  var DEFAULT_AUDIENCE = "authio";
340
569
  var DEFAULT_SIGN_IN_URL = "https://lobby.authio.com/";
@@ -344,6 +573,7 @@ function AuthioProvider(props) {
344
573
  projectId,
345
574
  storage: storageMode = "memory",
346
575
  refreshLeadSeconds = DEFAULT_REFRESH_LEAD,
576
+ idleRefresh = "defer",
347
577
  onTelemetryEvent,
348
578
  fetch: fetchImpl,
349
579
  signInUrl,
@@ -371,9 +601,19 @@ function AuthioProvider(props) {
371
601
  projectId,
372
602
  fetchImpl,
373
603
  signInUrl,
374
- emit
604
+ emit,
605
+ idleRefresh
375
606
  });
376
- propsRef.current = { apiUrl, projectId, fetchImpl, signInUrl, emit };
607
+ propsRef.current = { apiUrl, projectId, fetchImpl, signInUrl, emit, idleRefresh };
608
+ const activityRef = useRef(null);
609
+ const getTracker = useCallback(() => {
610
+ if (activityRef.current === null) {
611
+ activityRef.current = new ActivityTracker();
612
+ }
613
+ return activityRef.current;
614
+ }, []);
615
+ const lastRefreshAtRef = useRef(0);
616
+ const policyRef = useRef(null);
377
617
  useEffect(() => {
378
618
  if (!projectId) {
379
619
  console.warn(
@@ -388,6 +628,17 @@ function AuthioProvider(props) {
388
628
  skipInitialRefresh ? "unauthenticated" : "loading"
389
629
  );
390
630
  const [accessToken, setAccessToken] = useState(null);
631
+ const [sessionPolicy, setSessionPolicy] = useState(null);
632
+ const adoptPolicy = useCallback((policy) => {
633
+ policyRef.current = policy;
634
+ setSessionPolicy(policy);
635
+ lastRefreshAtRef.current = Date.now();
636
+ }, []);
637
+ const clearPolicy = useCallback(() => {
638
+ policyRef.current = null;
639
+ setSessionPolicy(null);
640
+ lastRefreshAtRef.current = 0;
641
+ }, []);
391
642
  const performRefresh = useCallback(async () => {
392
643
  const p = propsRef.current;
393
644
  try {
@@ -435,6 +686,9 @@ function AuthioProvider(props) {
435
686
  setAccessToken(token);
436
687
  if (env.user) setUser(coerceUser(env.user));
437
688
  setStatus("authenticated");
689
+ adoptPolicy(
690
+ env.session_policy !== void 0 ? coerceSessionPolicy(env.session_policy) : policyRef.current
691
+ );
438
692
  p.emit({
439
693
  kind: "refresh_succeeded",
440
694
  timestamp: Date.now(),
@@ -457,14 +711,15 @@ function AuthioProvider(props) {
457
711
  });
458
712
  return false;
459
713
  }
460
- }, []);
714
+ }, [adoptPolicy]);
461
715
  useEffect(() => {
462
- schedulerRef.current = new RefreshScheduler({
716
+ const scheduler = new RefreshScheduler({
463
717
  leadSeconds: refreshLeadSeconds,
464
718
  run: performRefresh,
465
719
  onGiveUp: () => {
466
720
  storageRef.current.clear();
467
721
  refreshTokenRef.current = null;
722
+ clearPolicy();
468
723
  setAccessToken(null);
469
724
  setUser(null);
470
725
  setStatus("unauthenticated");
@@ -473,13 +728,44 @@ function AuthioProvider(props) {
473
728
  kind: "refresh_scheduled",
474
729
  timestamp: Date.now(),
475
730
  runAt
731
+ }),
732
+ // Idle rule: hold the timer refresh when the effective policy has
733
+ // an inactivity timeout and the user hasn't touched the page since
734
+ // the last refresh. Without a policy (legacy projects, old
735
+ // auth-core) this is never true and behaviour is unchanged.
736
+ shouldDefer: () => {
737
+ if (propsRef.current.idleRefresh === "always") return false;
738
+ const policy = policyRef.current;
739
+ if (!policy || policy.idleTimeoutMin <= 0) return false;
740
+ const lastActivity = getTracker().lastActivityAt();
741
+ return lastActivity + ACTIVITY_GRACE_MS < lastRefreshAtRef.current;
742
+ },
743
+ onDeferred: (reason) => propsRef.current.emit({
744
+ kind: "refresh_deferred",
745
+ timestamp: Date.now(),
746
+ reason
476
747
  })
477
748
  });
749
+ schedulerRef.current = scheduler;
750
+ const tracker = getTracker();
751
+ const unsubscribe = tracker.onActivity(() => {
752
+ if (scheduler.deferredReason() !== "idle") return;
753
+ propsRef.current.emit({ kind: "refresh_resumed", timestamp: Date.now() });
754
+ scheduler.resume();
755
+ });
478
756
  return () => {
479
- schedulerRef.current?.destroy();
480
- schedulerRef.current = null;
757
+ unsubscribe();
758
+ scheduler.destroy();
759
+ if (schedulerRef.current === scheduler) schedulerRef.current = null;
481
760
  };
482
- }, [refreshLeadSeconds, performRefresh]);
761
+ }, [refreshLeadSeconds, performRefresh, clearPolicy, getTracker]);
762
+ useEffect(() => {
763
+ const tracker = getTracker();
764
+ return () => {
765
+ tracker.destroy();
766
+ if (activityRef.current === tracker) activityRef.current = null;
767
+ };
768
+ }, [getTracker]);
483
769
  useEffect(() => {
484
770
  if (skipInitialRefresh) {
485
771
  const stored2 = storageRef.current.get();
@@ -610,12 +896,13 @@ function AuthioProvider(props) {
610
896
  storageRef.current.clear();
611
897
  refreshTokenRef.current = null;
612
898
  schedulerRef.current?.clear();
899
+ clearPolicy();
613
900
  setAccessToken(null);
614
901
  setUser(null);
615
902
  setStatus("unauthenticated");
616
903
  p.emit({ kind: "sign_out", timestamp: Date.now() });
617
904
  }
618
- }, []);
905
+ }, [clearPolicy]);
619
906
  const refresh = useCallback(
620
907
  () => performRefresh(),
621
908
  [performRefresh]
@@ -637,7 +924,7 @@ function AuthioProvider(props) {
637
924
  setStatus("unauthenticated");
638
925
  throw new AuthioError({
639
926
  code: "token_rejected",
640
- message: "Authio rejected the handed-off access token signature.",
927
+ message: "We couldn't verify your sign-in. Please sign in again.",
641
928
  status: 0
642
929
  });
643
930
  }
@@ -651,6 +938,9 @@ function AuthioProvider(props) {
651
938
  setAccessToken(input.accessToken);
652
939
  if (input.user) setUser(input.user);
653
940
  setStatus("authenticated");
941
+ adoptPolicy(
942
+ input.sessionPolicy !== void 0 ? input.sessionPolicy : policyRef.current
943
+ );
654
944
  p.emit({
655
945
  kind: "sign_in_completed",
656
946
  timestamp: Date.now(),
@@ -661,7 +951,7 @@ function AuthioProvider(props) {
661
951
  schedulerRef.current?.scheduleAt(exp);
662
952
  }
663
953
  },
664
- []
954
+ [adoptPolicy]
665
955
  );
666
956
  const resolvedSignInUrl = signInUrl ?? DEFAULT_SIGN_IN_URL;
667
957
  const value = useMemo(
@@ -669,6 +959,7 @@ function AuthioProvider(props) {
669
959
  user,
670
960
  status,
671
961
  accessToken,
962
+ sessionPolicy,
672
963
  apiUrl,
673
964
  projectId,
674
965
  signInUrl: resolvedSignInUrl,
@@ -683,6 +974,7 @@ function AuthioProvider(props) {
683
974
  user,
684
975
  status,
685
976
  accessToken,
977
+ sessionPolicy,
686
978
  apiUrl,
687
979
  projectId,
688
980
  resolvedSignInUrl,
@@ -756,6 +1048,51 @@ function RedirectToSignIn({
756
1048
  }, [signIn, returnTo]);
757
1049
  return null;
758
1050
  }
1051
+
1052
+ // src/device-signals.ts
1053
+ function collectDeviceSignals() {
1054
+ if (typeof window === "undefined") {
1055
+ return {};
1056
+ }
1057
+ const out = {};
1058
+ try {
1059
+ out.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
1060
+ } catch {
1061
+ }
1062
+ if (typeof screen !== "undefined") {
1063
+ out.screen_resolution = `${screen.width}x${screen.height}`;
1064
+ }
1065
+ if (typeof navigator !== "undefined") {
1066
+ if (navigator.language) {
1067
+ out.language = navigator.language;
1068
+ }
1069
+ if (navigator.platform) {
1070
+ out.platform = navigator.platform;
1071
+ }
1072
+ }
1073
+ return out;
1074
+ }
1075
+ function encodeDeviceSignalsHeader(signals) {
1076
+ const json = JSON.stringify(signals);
1077
+ if (typeof btoa === "function") {
1078
+ return btoa(json).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1079
+ }
1080
+ const nodeBuffer = globalThis.Buffer;
1081
+ if (!nodeBuffer) {
1082
+ throw new Error("No base64 encoder available in this environment.");
1083
+ }
1084
+ return nodeBuffer.from(json, "utf8").toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1085
+ }
1086
+ var DEVICE_SIGNALS_HEADER = "X-Authio-Device-Signals";
1087
+ function deviceSignalsExtraHeaders(signals) {
1088
+ const s = signals ?? collectDeviceSignals();
1089
+ if (!s.timezone && !s.screen_resolution && !s.language && !s.platform) {
1090
+ return {};
1091
+ }
1092
+ return { [DEVICE_SIGNALS_HEADER]: encodeDeviceSignalsHeader(s) };
1093
+ }
1094
+
1095
+ // src/sign-in.ts
759
1096
  async function signInWithMagicLink(opts) {
760
1097
  await authioFetch({
761
1098
  apiUrl: opts.apiUrl,
@@ -766,24 +1103,51 @@ async function signInWithMagicLink(opts) {
766
1103
  // auth-core's magic-link send reads the recipient as `destination`
767
1104
  // (email or E.164), NOT `email`. See magiclink.go magicLinkSendReq.
768
1105
  destination: opts.email,
769
- redirect_uri: opts.redirectUri
1106
+ redirect_uri: opts.redirectUri,
1107
+ ...opts.xrayVisitorProof ? { xray_visitor_proof: opts.xrayVisitorProof } : {}
770
1108
  },
771
1109
  signal: opts.signal,
772
1110
  fetchImpl: opts.fetch
773
1111
  });
774
1112
  }
1113
+ function sessionFromResponse(res, status = 200) {
1114
+ const risk = riskDecisionError(res, status);
1115
+ if (risk) throw risk;
1116
+ const accessToken = res && typeof res.access_token === "string" ? res.access_token : "";
1117
+ const user = res && res.user && typeof res.user === "object" ? res.user : null;
1118
+ const userId = user && typeof user.id === "string" ? user.id : "";
1119
+ if (!res || !accessToken || !user || !userId) {
1120
+ throw new AuthioError({
1121
+ code: "invalid_response",
1122
+ message: AUTHIO_MESSAGES.invalid_response,
1123
+ status
1124
+ });
1125
+ }
1126
+ return {
1127
+ accessToken,
1128
+ refreshToken: typeof res.refresh_token === "string" ? res.refresh_token : void 0,
1129
+ sessionPolicy: coerceSessionPolicy(res.session_policy),
1130
+ user: {
1131
+ id: userId,
1132
+ email: typeof user.email === "string" ? user.email : "",
1133
+ emailVerified: Boolean(user.emailVerified ?? user.email_verified),
1134
+ name: user.name,
1135
+ avatarUrl: user.avatarUrl ?? user.avatar_url
1136
+ }
1137
+ };
1138
+ }
775
1139
  async function signInWithPasskey(opts) {
776
1140
  if (!isBrowser() || typeof navigator === "undefined") {
777
1141
  throw new AuthioError({
778
1142
  code: "not_in_browser",
779
- message: "signInWithPasskey can only be invoked in a browser environment.",
1143
+ message: "Passkey sign-in only works in a web browser. Call signInWithPasskey from client-side code.",
780
1144
  status: 0
781
1145
  });
782
1146
  }
783
1147
  if (!navigator.credentials || !navigator.credentials.get) {
784
1148
  throw new AuthioError({
785
1149
  code: "webauthn_unsupported",
786
- message: "This browser does not support WebAuthn (passkeys).",
1150
+ message: AUTHIO_MESSAGES.webauthn_unsupported,
787
1151
  status: 0
788
1152
  });
789
1153
  }
@@ -796,6 +1160,13 @@ async function signInWithPasskey(opts) {
796
1160
  signal: opts.signal,
797
1161
  fetchImpl: opts.fetch
798
1162
  });
1163
+ if (!options || typeof options.challenge !== "string" || !options.challenge) {
1164
+ throw new AuthioError({
1165
+ code: "invalid_response",
1166
+ message: AUTHIO_MESSAGES.invalid_response,
1167
+ status: 200
1168
+ });
1169
+ }
799
1170
  const publicKey = {
800
1171
  challenge: base64UrlToBuffer(options.challenge),
801
1172
  rpId: options.rpId,
@@ -814,16 +1185,18 @@ async function signInWithPasskey(opts) {
814
1185
  signal: opts.signal
815
1186
  });
816
1187
  } catch (err) {
817
- throw new AuthioError({
1188
+ const e = new AuthioError({
818
1189
  code: "webauthn_cancelled",
819
- message: err instanceof Error ? err.message : "Passkey ceremony cancelled by user.",
1190
+ message: AUTHIO_MESSAGES.webauthn_cancelled,
820
1191
  status: 0
821
1192
  });
1193
+ Object.defineProperty(e, "cause", { value: err, enumerable: false });
1194
+ throw e;
822
1195
  }
823
1196
  if (!credential) {
824
1197
  throw new AuthioError({
825
1198
  code: "webauthn_cancelled",
826
- message: "Passkey ceremony returned no credential.",
1199
+ message: AUTHIO_MESSAGES.webauthn_cancelled,
827
1200
  status: 0
828
1201
  });
829
1202
  }
@@ -846,24 +1219,57 @@ async function signInWithPasskey(opts) {
846
1219
  projectId: opts.projectId,
847
1220
  path: "/v1/auth/passkey/login/verify",
848
1221
  method: "POST",
849
- body: { credential: webauthnCredential },
1222
+ body: {
1223
+ credential: webauthnCredential,
1224
+ ...opts.next ? { next: opts.next } : {},
1225
+ ...opts.organizationId ? { organization_id: opts.organizationId } : {},
1226
+ ...opts.xrayVisitorProof ? { xray_visitor_proof: opts.xrayVisitorProof } : {}
1227
+ },
1228
+ extraHeaders: deviceSignalsExtraHeaders(),
850
1229
  credentials: "include",
851
1230
  signal: opts.signal,
852
1231
  fetchImpl: opts.fetch
853
1232
  });
854
- return {
855
- accessToken: verifyRes.access_token,
856
- refreshToken: verifyRes.refresh_token,
857
- user: {
858
- id: verifyRes.user.id,
859
- email: verifyRes.user.email,
860
- emailVerified: Boolean(
861
- verifyRes.user.emailVerified ?? verifyRes.user.email_verified
862
- ),
863
- name: verifyRes.user.name,
864
- avatarUrl: verifyRes.user.avatarUrl ?? verifyRes.user.avatar_url
865
- }
866
- };
1233
+ return sessionFromResponse(verifyRes);
1234
+ }
1235
+ async function sendEmailOtp(opts) {
1236
+ await authioFetch({
1237
+ apiUrl: opts.apiUrl,
1238
+ projectId: opts.projectId,
1239
+ path: "/v1/auth/email-otp/send",
1240
+ method: "POST",
1241
+ body: {
1242
+ email: opts.email,
1243
+ ...opts.redirectUri ? { redirect_uri: opts.redirectUri } : {},
1244
+ ...opts.next ? { next: opts.next } : {},
1245
+ ...opts.organizationId ? { organization_id: opts.organizationId } : {},
1246
+ ...opts.xrayVisitorProof ? { xray_visitor_proof: opts.xrayVisitorProof } : {}
1247
+ },
1248
+ signal: opts.signal,
1249
+ fetchImpl: opts.fetch
1250
+ });
1251
+ }
1252
+ async function verifyEmailOtp(opts) {
1253
+ const verifyRes = await authioFetch({
1254
+ apiUrl: opts.apiUrl,
1255
+ projectId: opts.projectId,
1256
+ path: "/v1/auth/email-otp/verify",
1257
+ method: "POST",
1258
+ body: {
1259
+ email: opts.email,
1260
+ code: opts.code,
1261
+ ...opts.redirectUri ? { redirect_uri: opts.redirectUri } : {},
1262
+ ...opts.next ? { next: opts.next } : {},
1263
+ ...opts.organizationId ? { organization_id: opts.organizationId } : {},
1264
+ ...opts.clientLocation ? { client_location: opts.clientLocation } : {},
1265
+ ...opts.deviceSignals ? { device_signals: opts.deviceSignals } : {},
1266
+ ...opts.xrayVisitorProof ? { xray_visitor_proof: opts.xrayVisitorProof } : {}
1267
+ },
1268
+ credentials: "include",
1269
+ signal: opts.signal,
1270
+ fetchImpl: opts.fetch
1271
+ });
1272
+ return sessionFromResponse(verifyRes);
867
1273
  }
868
1274
  function base64UrlToBuffer(b64u) {
869
1275
  const padded = b64u.replace(/-/g, "+").replace(/_/g, "/").padEnd(b64u.length + (4 - b64u.length % 4) % 4, "=");
@@ -925,7 +1331,7 @@ async function enrollPasskey(opts) {
925
1331
  if (!isBrowser()) {
926
1332
  throw new AuthioError({
927
1333
  code: "not_in_browser",
928
- message: "enrollPasskey can only be invoked in a browser environment.",
1334
+ message: "Passkey setup only works in a web browser. Call enrollPasskey from client-side code.",
929
1335
  status: 0
930
1336
  });
931
1337
  }
@@ -945,7 +1351,7 @@ async function addPasskey(opts) {
945
1351
  if (!isBrowser()) {
946
1352
  throw new AuthioError({
947
1353
  code: "not_in_browser",
948
- message: "addPasskey can only be invoked in a browser environment.",
1354
+ message: "Passkey setup only works in a web browser. Call addPasskey from client-side code.",
949
1355
  status: 0
950
1356
  });
951
1357
  }
@@ -965,11 +1371,14 @@ async function addPasskey(opts) {
965
1371
  try {
966
1372
  attestation = await startRegistration({ optionsJSON: options });
967
1373
  } catch (err) {
968
- throw new AuthioError({
969
- code: "webauthn_cancelled",
970
- message: err instanceof Error ? err.message : "Passkey registration cancelled by user.",
1374
+ const already = err instanceof Error && (err.name === "InvalidStateError" || err.code === "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED");
1375
+ const e = new AuthioError({
1376
+ code: already ? "webauthn_already_registered" : "webauthn_cancelled",
1377
+ message: already ? AUTHIO_MESSAGES.webauthn_already_registered : AUTHIO_MESSAGES.webauthn_registration_cancelled,
971
1378
  status: 0
972
1379
  });
1380
+ Object.defineProperty(e, "cause", { value: err, enumerable: false });
1381
+ throw e;
973
1382
  }
974
1383
  await authioFetch({
975
1384
  apiUrl: opts.apiUrl,
@@ -1016,6 +1425,13 @@ async function revokePasskey(opts, credentialId) {
1016
1425
  extraHeaders: bearerHeaders(opts.accessToken)
1017
1426
  });
1018
1427
  }
1428
+ function notSignedIn() {
1429
+ return new AuthioError({
1430
+ code: "not_signed_in",
1431
+ message: AUTHIO_MESSAGES.not_signed_in,
1432
+ status: 401
1433
+ });
1434
+ }
1019
1435
  function usePasskeys() {
1020
1436
  const ctx = useAuthio();
1021
1437
  const [passkeys, setPasskeys] = useState([]);
@@ -1043,7 +1459,7 @@ function usePasskeys() {
1043
1459
  });
1044
1460
  setPasskeys(rows);
1045
1461
  } catch (err) {
1046
- setError(err instanceof Error ? err.message : "Failed to load passkeys");
1462
+ setError(err instanceof AuthioError ? err.message : "We couldn't load your passkeys. Please refresh the page and try again.");
1047
1463
  setPasskeys([]);
1048
1464
  } finally {
1049
1465
  setLoading(false);
@@ -1061,7 +1477,7 @@ function usePasskeys() {
1061
1477
  const rename = useCallback(
1062
1478
  async (credentialId, nickname) => {
1063
1479
  const token = await ctx.getAccessToken();
1064
- if (!token) throw new Error("Not signed in");
1480
+ if (!token) throw notSignedIn();
1065
1481
  await renamePasskey(
1066
1482
  {
1067
1483
  apiUrl: ctx.apiUrl,
@@ -1079,7 +1495,7 @@ function usePasskeys() {
1079
1495
  const revoke = useCallback(
1080
1496
  async (credentialId) => {
1081
1497
  const token = await ctx.getAccessToken();
1082
- if (!token) throw new Error("Not signed in");
1498
+ if (!token) throw notSignedIn();
1083
1499
  await revokePasskey(
1084
1500
  {
1085
1501
  apiUrl: ctx.apiUrl,
@@ -1097,7 +1513,7 @@ function usePasskeys() {
1097
1513
  async (opts) => {
1098
1514
  const token = await ctx.getAccessToken();
1099
1515
  const email = ctx.user?.email;
1100
- if (!token || !email) throw new Error("Not signed in");
1516
+ if (!token || !email) throw notSignedIn();
1101
1517
  await enrollPasskey({
1102
1518
  apiUrl: ctx.apiUrl,
1103
1519
  projectId: ctx.projectId,
@@ -1135,7 +1551,7 @@ function PasskeyManager({
1135
1551
  try {
1136
1552
  await rename(id, nickname);
1137
1553
  } catch (err) {
1138
- setActionError(err instanceof Error ? err.message : "Rename failed");
1554
+ setActionError(err instanceof AuthioError ? err.message : "We couldn't rename that passkey. Please try again.");
1139
1555
  } finally {
1140
1556
  setBusyId(null);
1141
1557
  }
@@ -1146,7 +1562,7 @@ function PasskeyManager({
1146
1562
  try {
1147
1563
  await revoke(id);
1148
1564
  } catch (err) {
1149
- setActionError(err instanceof Error ? err.message : "Revoke failed");
1565
+ setActionError(err instanceof AuthioError ? err.message : "We couldn't remove that passkey. Please try again.");
1150
1566
  } finally {
1151
1567
  setBusyId(null);
1152
1568
  }
@@ -1158,7 +1574,7 @@ function PasskeyManager({
1158
1574
  await enroll({ returnUrl: enrollReturnUrl, next: enrollNext });
1159
1575
  } catch (err) {
1160
1576
  setEnrolling(false);
1161
- setActionError(err instanceof Error ? err.message : "Could not start enrollment");
1577
+ setActionError(err instanceof AuthioError ? err.message : "We couldn't start passkey setup. Please try again.");
1162
1578
  }
1163
1579
  }
1164
1580
  return /* @__PURE__ */ jsxs("section", { className, "aria-labelledby": "authio-passkey-manager-title", children: [
@@ -1270,7 +1686,11 @@ function captureClientLocation(opts = {}) {
1270
1686
  );
1271
1687
  });
1272
1688
  }
1689
+ var VERIFY_LOCATE_BACKEND_ONLY = "verifyLocate() is not supported in @useauthio/react: POST /v1/locate/verify requires a project secret key (sk_live_/sk_test_), not a user JWT. Capture GPS with captureClientLocation(), POST to your backend, and call authio.locate.verify() via @useauthio/node. See authio_locate/docs/JB_MIGRATION_GUIDE.md.";
1690
+ async function verifyLocate(_opts) {
1691
+ throw new Error(VERIFY_LOCATE_BACKEND_ONLY);
1692
+ }
1273
1693
 
1274
- export { AuthioContext, AuthioProvider, PasskeyManager, RedirectToSignIn, SignedIn, SignedOut, addPasskey, buildEnrollPasskeyUrl, canEnrollPasskeyEmbedded, captureClientLocation, enrollPasskey, listPasskeys, mintPasskeyRegisterIntent, renamePasskey, revokePasskey, signInOrigin, signInWithMagicLink, signInWithPasskey, useAuthio, useAuthioRequired, usePasskeys, wrapFetchError };
1694
+ export { AUTHIO_MESSAGES, ActivityTracker, AuthioContext, AuthioProvider, AuthioSignInDeniedError, AuthioStepUpRequiredError, DEVICE_SIGNALS_HEADER, PasskeyManager, RedirectToSignIn, SignedIn, SignedOut, addPasskey, buildEnrollPasskeyUrl, canEnrollPasskeyEmbedded, captureClientLocation, coerceSessionPolicy, collectDeviceSignals, deviceSignalsExtraHeaders, encodeDeviceSignalsHeader, enrollPasskey, isStepUpRequired, listPasskeys, mintPasskeyRegisterIntent, renamePasskey, revokePasskey, sendEmailOtp, signInOrigin, signInWithMagicLink, signInWithPasskey, useAuthio, useAuthioRequired, usePasskeys, verifyEmailOtp, verifyLocate, wrapFetchError };
1275
1695
  //# sourceMappingURL=index.js.map
1276
1696
  //# sourceMappingURL=index.js.map