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