@useauthio/react 0.2.3 → 0.3.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/dist/index.js CHANGED
@@ -1,7 +1,8 @@
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
- import { jsx, Fragment } from 'react/jsx-runtime';
4
+ import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
5
+ import { startRegistration } from '@simplewebauthn/browser';
5
6
 
6
7
  // src/provider.tsx
7
8
  function wrapFetchError(err, fallbackCode = "network_error") {
@@ -29,7 +30,7 @@ function wrapFetchError(err, fallbackCode = "network_error") {
29
30
  }
30
31
 
31
32
  // src/version.ts
32
- var SDK_VERSION = "0.2.2";
33
+ var SDK_VERSION = "0.3.0";
33
34
  var SDK_USER_AGENT = `react/${SDK_VERSION}`;
34
35
 
35
36
  // src/fetch.ts
@@ -139,6 +140,74 @@ function isTabHidden() {
139
140
  return document.visibilityState === "hidden";
140
141
  }
141
142
 
143
+ // src/activity.ts
144
+ var ACTIVITY_EVENTS = [
145
+ "pointerdown",
146
+ "keydown",
147
+ "touchstart",
148
+ "scroll",
149
+ "focus"
150
+ ];
151
+ var THROTTLE_MS = 1e3;
152
+ var ActivityTracker = class {
153
+ last = 0;
154
+ listeners = /* @__PURE__ */ new Set();
155
+ handler = null;
156
+ visibilityHandler = null;
157
+ destroyed = false;
158
+ constructor(now = Date.now) {
159
+ this.now = now;
160
+ if (!isBrowser()) return;
161
+ this.handler = () => this.mark();
162
+ for (const ev of ACTIVITY_EVENTS) {
163
+ window.addEventListener(ev, this.handler, { passive: true, capture: true });
164
+ }
165
+ this.visibilityHandler = () => {
166
+ if (!isTabHidden()) this.mark();
167
+ };
168
+ document.addEventListener("visibilitychange", this.visibilityHandler);
169
+ }
170
+ now;
171
+ /** Unix ms of the most recent recorded interaction, `0` if none yet. */
172
+ lastActivityAt() {
173
+ return this.last;
174
+ }
175
+ /**
176
+ * Record activity now. Throttled to one write per second; listeners
177
+ * fire only when a write actually happens. Exposed so tests (and
178
+ * embedders with their own activity signal) can poke it directly.
179
+ */
180
+ mark() {
181
+ if (this.destroyed) return;
182
+ const t = this.now();
183
+ if (t - this.last < THROTTLE_MS) return;
184
+ this.last = t;
185
+ for (const l of this.listeners) l(t);
186
+ }
187
+ /** Subscribe to recorded activity. Returns an unsubscribe function. */
188
+ onActivity(listener) {
189
+ this.listeners.add(listener);
190
+ return () => {
191
+ this.listeners.delete(listener);
192
+ };
193
+ }
194
+ destroy() {
195
+ this.destroyed = true;
196
+ this.listeners.clear();
197
+ if (!isBrowser()) return;
198
+ if (this.handler) {
199
+ for (const ev of ACTIVITY_EVENTS) {
200
+ window.removeEventListener(ev, this.handler, { capture: true });
201
+ }
202
+ }
203
+ if (this.visibilityHandler) {
204
+ document.removeEventListener("visibilitychange", this.visibilityHandler);
205
+ }
206
+ this.handler = null;
207
+ this.visibilityHandler = null;
208
+ }
209
+ };
210
+
142
211
  // src/refresh.ts
143
212
  var BACKOFF_DELAYS_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
144
213
  var MAX_ATTEMPTS = 5;
@@ -160,23 +229,46 @@ var RefreshScheduler = class {
160
229
  attempts = 0;
161
230
  lastExp = null;
162
231
  destroyed = false;
232
+ deferred = null;
163
233
  visibilityHandler = null;
234
+ /** Whether the last tick was held back (and why). `null` when not deferred. */
235
+ deferredReason() {
236
+ return this.deferred;
237
+ }
164
238
  scheduleAt(exp) {
165
239
  if (this.destroyed) return;
166
240
  this.lastExp = exp;
167
241
  this.attempts = 0;
242
+ this.deferred = null;
168
243
  this.clear();
169
244
  const now = Math.floor(Date.now() / 1e3);
170
245
  const delayMs = Math.max(0, (exp - now - this.opts.leadSeconds) * 1e3);
171
246
  this.opts.onScheduled?.(Date.now() + delayMs);
172
247
  this.timer = setTimeout(() => void this.tick(), delayMs);
173
248
  }
249
+ /**
250
+ * Re-arm after a deferral. No-op unless a tick is currently held
251
+ * back. Re-schedules against the remembered `exp`, so a token that
252
+ * is already inside its lead window refreshes immediately.
253
+ */
254
+ resume() {
255
+ if (this.destroyed || this.deferred === null || this.lastExp === null) return;
256
+ this.scheduleAt(this.lastExp);
257
+ }
174
258
  async tick() {
175
259
  this.timer = null;
176
260
  if (this.destroyed) return;
177
261
  if (isTabHidden()) {
262
+ this.deferred = "hidden";
263
+ this.opts.onDeferred?.("hidden");
178
264
  return;
179
265
  }
266
+ if (this.opts.shouldDefer?.()) {
267
+ this.deferred = "idle";
268
+ this.opts.onDeferred?.("idle");
269
+ return;
270
+ }
271
+ this.deferred = null;
180
272
  let ok = false;
181
273
  try {
182
274
  ok = await this.opts.run();
@@ -305,7 +397,8 @@ async function mintLobbySignInUrl(opts) {
305
397
  body: JSON.stringify({
306
398
  project_id: opts.projectId,
307
399
  redirect_uri: opts.redirectUri,
308
- ...opts.next ? { next: opts.next } : {}
400
+ ...opts.next ? { next: opts.next } : {},
401
+ ...opts.organizationId ? { organization_id: opts.organizationId } : {}
309
402
  })
310
403
  }
311
404
  );
@@ -326,14 +419,29 @@ async function mintLobbySignInUrl(opts) {
326
419
  if (opts.next) {
327
420
  target.searchParams.set("next", opts.next);
328
421
  }
422
+ if (opts.organizationId) {
423
+ target.searchParams.set("organization_id", opts.organizationId);
424
+ }
329
425
  return target.toString();
330
426
  }
331
427
 
332
428
  // src/telemetry.ts
333
429
  var noopEmitter = () => {
334
430
  };
431
+
432
+ // src/types.ts
433
+ function coerceSessionPolicy(raw) {
434
+ if (!raw || typeof raw !== "object") return null;
435
+ const n = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0;
436
+ return {
437
+ idleTimeoutMin: n(raw.idle_timeout_min),
438
+ absoluteMaxMin: n(raw.absolute_max_min),
439
+ accessTokenTtlMin: n(raw.access_token_ttl_min)
440
+ };
441
+ }
335
442
  var AuthioContext = createContext(null);
336
443
  AuthioContext.displayName = "AuthioContext";
444
+ var ACTIVITY_GRACE_MS = 1e3;
337
445
  var DEFAULT_REFRESH_LEAD = 60;
338
446
  var DEFAULT_AUDIENCE = "authio";
339
447
  var DEFAULT_SIGN_IN_URL = "https://lobby.authio.com/";
@@ -343,6 +451,7 @@ function AuthioProvider(props) {
343
451
  projectId,
344
452
  storage: storageMode = "memory",
345
453
  refreshLeadSeconds = DEFAULT_REFRESH_LEAD,
454
+ idleRefresh = "defer",
346
455
  onTelemetryEvent,
347
456
  fetch: fetchImpl,
348
457
  signInUrl,
@@ -370,9 +479,19 @@ function AuthioProvider(props) {
370
479
  projectId,
371
480
  fetchImpl,
372
481
  signInUrl,
373
- emit
482
+ emit,
483
+ idleRefresh
374
484
  });
375
- propsRef.current = { apiUrl, projectId, fetchImpl, signInUrl, emit };
485
+ propsRef.current = { apiUrl, projectId, fetchImpl, signInUrl, emit, idleRefresh };
486
+ const activityRef = useRef(null);
487
+ const getTracker = useCallback(() => {
488
+ if (activityRef.current === null) {
489
+ activityRef.current = new ActivityTracker();
490
+ }
491
+ return activityRef.current;
492
+ }, []);
493
+ const lastRefreshAtRef = useRef(0);
494
+ const policyRef = useRef(null);
376
495
  useEffect(() => {
377
496
  if (!projectId) {
378
497
  console.warn(
@@ -387,6 +506,17 @@ function AuthioProvider(props) {
387
506
  skipInitialRefresh ? "unauthenticated" : "loading"
388
507
  );
389
508
  const [accessToken, setAccessToken] = useState(null);
509
+ const [sessionPolicy, setSessionPolicy] = useState(null);
510
+ const adoptPolicy = useCallback((policy) => {
511
+ policyRef.current = policy;
512
+ setSessionPolicy(policy);
513
+ lastRefreshAtRef.current = Date.now();
514
+ }, []);
515
+ const clearPolicy = useCallback(() => {
516
+ policyRef.current = null;
517
+ setSessionPolicy(null);
518
+ lastRefreshAtRef.current = 0;
519
+ }, []);
390
520
  const performRefresh = useCallback(async () => {
391
521
  const p = propsRef.current;
392
522
  try {
@@ -434,6 +564,9 @@ function AuthioProvider(props) {
434
564
  setAccessToken(token);
435
565
  if (env.user) setUser(coerceUser(env.user));
436
566
  setStatus("authenticated");
567
+ adoptPolicy(
568
+ env.session_policy !== void 0 ? coerceSessionPolicy(env.session_policy) : policyRef.current
569
+ );
437
570
  p.emit({
438
571
  kind: "refresh_succeeded",
439
572
  timestamp: Date.now(),
@@ -456,14 +589,15 @@ function AuthioProvider(props) {
456
589
  });
457
590
  return false;
458
591
  }
459
- }, []);
592
+ }, [adoptPolicy]);
460
593
  useEffect(() => {
461
- schedulerRef.current = new RefreshScheduler({
594
+ const scheduler = new RefreshScheduler({
462
595
  leadSeconds: refreshLeadSeconds,
463
596
  run: performRefresh,
464
597
  onGiveUp: () => {
465
598
  storageRef.current.clear();
466
599
  refreshTokenRef.current = null;
600
+ clearPolicy();
467
601
  setAccessToken(null);
468
602
  setUser(null);
469
603
  setStatus("unauthenticated");
@@ -472,13 +606,44 @@ function AuthioProvider(props) {
472
606
  kind: "refresh_scheduled",
473
607
  timestamp: Date.now(),
474
608
  runAt
609
+ }),
610
+ // Idle rule: hold the timer refresh when the effective policy has
611
+ // an inactivity timeout and the user hasn't touched the page since
612
+ // the last refresh. Without a policy (legacy projects, old
613
+ // auth-core) this is never true and behaviour is unchanged.
614
+ shouldDefer: () => {
615
+ if (propsRef.current.idleRefresh === "always") return false;
616
+ const policy = policyRef.current;
617
+ if (!policy || policy.idleTimeoutMin <= 0) return false;
618
+ const lastActivity = getTracker().lastActivityAt();
619
+ return lastActivity + ACTIVITY_GRACE_MS < lastRefreshAtRef.current;
620
+ },
621
+ onDeferred: (reason) => propsRef.current.emit({
622
+ kind: "refresh_deferred",
623
+ timestamp: Date.now(),
624
+ reason
475
625
  })
476
626
  });
627
+ schedulerRef.current = scheduler;
628
+ const tracker = getTracker();
629
+ const unsubscribe = tracker.onActivity(() => {
630
+ if (scheduler.deferredReason() !== "idle") return;
631
+ propsRef.current.emit({ kind: "refresh_resumed", timestamp: Date.now() });
632
+ scheduler.resume();
633
+ });
477
634
  return () => {
478
- schedulerRef.current?.destroy();
479
- schedulerRef.current = null;
635
+ unsubscribe();
636
+ scheduler.destroy();
637
+ if (schedulerRef.current === scheduler) schedulerRef.current = null;
480
638
  };
481
- }, [refreshLeadSeconds, performRefresh]);
639
+ }, [refreshLeadSeconds, performRefresh, clearPolicy, getTracker]);
640
+ useEffect(() => {
641
+ const tracker = getTracker();
642
+ return () => {
643
+ tracker.destroy();
644
+ if (activityRef.current === tracker) activityRef.current = null;
645
+ };
646
+ }, [getTracker]);
482
647
  useEffect(() => {
483
648
  if (skipInitialRefresh) {
484
649
  const stored2 = storageRef.current.get();
@@ -609,12 +774,13 @@ function AuthioProvider(props) {
609
774
  storageRef.current.clear();
610
775
  refreshTokenRef.current = null;
611
776
  schedulerRef.current?.clear();
777
+ clearPolicy();
612
778
  setAccessToken(null);
613
779
  setUser(null);
614
780
  setStatus("unauthenticated");
615
781
  p.emit({ kind: "sign_out", timestamp: Date.now() });
616
782
  }
617
- }, []);
783
+ }, [clearPolicy]);
618
784
  const refresh = useCallback(
619
785
  () => performRefresh(),
620
786
  [performRefresh]
@@ -650,6 +816,9 @@ function AuthioProvider(props) {
650
816
  setAccessToken(input.accessToken);
651
817
  if (input.user) setUser(input.user);
652
818
  setStatus("authenticated");
819
+ adoptPolicy(
820
+ input.sessionPolicy !== void 0 ? input.sessionPolicy : policyRef.current
821
+ );
653
822
  p.emit({
654
823
  kind: "sign_in_completed",
655
824
  timestamp: Date.now(),
@@ -660,13 +829,19 @@ function AuthioProvider(props) {
660
829
  schedulerRef.current?.scheduleAt(exp);
661
830
  }
662
831
  },
663
- []
832
+ [adoptPolicy]
664
833
  );
834
+ const resolvedSignInUrl = signInUrl ?? DEFAULT_SIGN_IN_URL;
665
835
  const value = useMemo(
666
836
  () => ({
667
837
  user,
668
838
  status,
669
839
  accessToken,
840
+ sessionPolicy,
841
+ apiUrl,
842
+ projectId,
843
+ signInUrl: resolvedSignInUrl,
844
+ fetchImpl,
670
845
  getAccessToken,
671
846
  signIn,
672
847
  signOut,
@@ -677,6 +852,11 @@ function AuthioProvider(props) {
677
852
  user,
678
853
  status,
679
854
  accessToken,
855
+ sessionPolicy,
856
+ apiUrl,
857
+ projectId,
858
+ resolvedSignInUrl,
859
+ fetchImpl,
680
860
  getAccessToken,
681
861
  signIn,
682
862
  signOut,
@@ -746,6 +926,51 @@ function RedirectToSignIn({
746
926
  }, [signIn, returnTo]);
747
927
  return null;
748
928
  }
929
+
930
+ // src/device-signals.ts
931
+ function collectDeviceSignals() {
932
+ if (typeof window === "undefined") {
933
+ return {};
934
+ }
935
+ const out = {};
936
+ try {
937
+ out.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
938
+ } catch {
939
+ }
940
+ if (typeof screen !== "undefined") {
941
+ out.screen_resolution = `${screen.width}x${screen.height}`;
942
+ }
943
+ if (typeof navigator !== "undefined") {
944
+ if (navigator.language) {
945
+ out.language = navigator.language;
946
+ }
947
+ if (navigator.platform) {
948
+ out.platform = navigator.platform;
949
+ }
950
+ }
951
+ return out;
952
+ }
953
+ function encodeDeviceSignalsHeader(signals) {
954
+ const json = JSON.stringify(signals);
955
+ if (typeof btoa === "function") {
956
+ return btoa(json).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
957
+ }
958
+ const nodeBuffer = globalThis.Buffer;
959
+ if (!nodeBuffer) {
960
+ throw new Error("No base64 encoder available in this environment.");
961
+ }
962
+ return nodeBuffer.from(json, "utf8").toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
963
+ }
964
+ var DEVICE_SIGNALS_HEADER = "X-Authio-Device-Signals";
965
+ function deviceSignalsExtraHeaders(signals) {
966
+ const s = signals ?? collectDeviceSignals();
967
+ if (!s.timezone && !s.screen_resolution && !s.language && !s.platform) {
968
+ return {};
969
+ }
970
+ return { [DEVICE_SIGNALS_HEADER]: encodeDeviceSignalsHeader(s) };
971
+ }
972
+
973
+ // src/sign-in.ts
749
974
  async function signInWithMagicLink(opts) {
750
975
  await authioFetch({
751
976
  apiUrl: opts.apiUrl,
@@ -836,7 +1061,12 @@ async function signInWithPasskey(opts) {
836
1061
  projectId: opts.projectId,
837
1062
  path: "/v1/auth/passkey/login/verify",
838
1063
  method: "POST",
839
- body: { credential: webauthnCredential },
1064
+ body: {
1065
+ credential: webauthnCredential,
1066
+ ...opts.next ? { next: opts.next } : {},
1067
+ ...opts.organizationId ? { organization_id: opts.organizationId } : {}
1068
+ },
1069
+ extraHeaders: deviceSignalsExtraHeaders(),
840
1070
  credentials: "include",
841
1071
  signal: opts.signal,
842
1072
  fetchImpl: opts.fetch
@@ -844,6 +1074,64 @@ async function signInWithPasskey(opts) {
844
1074
  return {
845
1075
  accessToken: verifyRes.access_token,
846
1076
  refreshToken: verifyRes.refresh_token,
1077
+ sessionPolicy: coerceSessionPolicy(verifyRes.session_policy),
1078
+ user: {
1079
+ id: verifyRes.user.id,
1080
+ email: verifyRes.user.email,
1081
+ emailVerified: Boolean(
1082
+ verifyRes.user.emailVerified ?? verifyRes.user.email_verified
1083
+ ),
1084
+ name: verifyRes.user.name,
1085
+ avatarUrl: verifyRes.user.avatarUrl ?? verifyRes.user.avatar_url
1086
+ }
1087
+ };
1088
+ }
1089
+ async function sendEmailOtp(opts) {
1090
+ await authioFetch({
1091
+ apiUrl: opts.apiUrl,
1092
+ projectId: opts.projectId,
1093
+ path: "/v1/auth/email-otp/send",
1094
+ method: "POST",
1095
+ body: {
1096
+ email: opts.email,
1097
+ ...opts.redirectUri ? { redirect_uri: opts.redirectUri } : {},
1098
+ ...opts.next ? { next: opts.next } : {},
1099
+ ...opts.organizationId ? { organization_id: opts.organizationId } : {}
1100
+ },
1101
+ signal: opts.signal,
1102
+ fetchImpl: opts.fetch
1103
+ });
1104
+ }
1105
+ async function verifyEmailOtp(opts) {
1106
+ const verifyRes = await authioFetch({
1107
+ apiUrl: opts.apiUrl,
1108
+ projectId: opts.projectId,
1109
+ path: "/v1/auth/email-otp/verify",
1110
+ method: "POST",
1111
+ body: {
1112
+ email: opts.email,
1113
+ code: opts.code,
1114
+ ...opts.redirectUri ? { redirect_uri: opts.redirectUri } : {},
1115
+ ...opts.next ? { next: opts.next } : {},
1116
+ ...opts.organizationId ? { organization_id: opts.organizationId } : {},
1117
+ ...opts.clientLocation ? { client_location: opts.clientLocation } : {},
1118
+ ...opts.deviceSignals ? { device_signals: opts.deviceSignals } : {}
1119
+ },
1120
+ credentials: "include",
1121
+ signal: opts.signal,
1122
+ fetchImpl: opts.fetch
1123
+ });
1124
+ if (verifyRes.decision === "step_up") {
1125
+ throw new AuthioError({
1126
+ code: "step_up_required",
1127
+ message: "Additional verification is required. Complete the step-up challenge on the hosted sign-in page.",
1128
+ status: 200
1129
+ });
1130
+ }
1131
+ return {
1132
+ accessToken: verifyRes.access_token,
1133
+ refreshToken: verifyRes.refresh_token,
1134
+ sessionPolicy: coerceSessionPolicy(verifyRes.session_policy),
847
1135
  user: {
848
1136
  id: verifyRes.user.id,
849
1137
  email: verifyRes.user.email,
@@ -870,6 +1158,364 @@ function bufferToBase64Url(buf) {
870
1158
  }
871
1159
  return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
872
1160
  }
1161
+ function signInOrigin(signInUrl) {
1162
+ return signInUrl.replace(/\/$/, "");
1163
+ }
1164
+ function canEnrollPasskeyEmbedded(signInUrl) {
1165
+ if (!isBrowser()) return false;
1166
+ return window.location.origin === signInOrigin(signInUrl);
1167
+ }
1168
+ function buildEnrollPasskeyUrl(opts) {
1169
+ const url = new URL(signInOrigin(opts.signInUrl));
1170
+ url.searchParams.set("mode", "add_credential");
1171
+ url.searchParams.set("project_id", opts.projectId);
1172
+ url.searchParams.set("email", opts.email);
1173
+ url.searchParams.set("token", opts.registerToken);
1174
+ if (opts.redirectUri) {
1175
+ url.searchParams.set("redirect_uri", opts.redirectUri);
1176
+ }
1177
+ if (opts.next) {
1178
+ url.searchParams.set("next", opts.next);
1179
+ }
1180
+ return url.toString();
1181
+ }
1182
+ function bearerHeaders(accessToken, origin) {
1183
+ const h = {
1184
+ Authorization: `Bearer ${accessToken}`
1185
+ };
1186
+ if (origin) h["X-Authio-Origin"] = origin;
1187
+ return h;
1188
+ }
1189
+ async function mintPasskeyRegisterIntent(opts) {
1190
+ const body = await authioFetch({
1191
+ apiUrl: opts.apiUrl,
1192
+ projectId: opts.projectId,
1193
+ path: "/v1/me/passkeys/register-intent",
1194
+ method: "POST",
1195
+ body: {},
1196
+ signal: opts.signal,
1197
+ fetchImpl: opts.fetchImpl,
1198
+ extraHeaders: bearerHeaders(opts.accessToken)
1199
+ });
1200
+ return { token: body.token, expiresIn: body.expires_in };
1201
+ }
1202
+ async function enrollPasskey(opts) {
1203
+ if (!isBrowser()) {
1204
+ throw new AuthioError({
1205
+ code: "not_in_browser",
1206
+ message: "enrollPasskey can only be invoked in a browser environment.",
1207
+ status: 0
1208
+ });
1209
+ }
1210
+ const intent = await mintPasskeyRegisterIntent(opts);
1211
+ const redirectUri = opts.returnUrl ?? (typeof window !== "undefined" ? window.location.href : "");
1212
+ const target = buildEnrollPasskeyUrl({
1213
+ signInUrl: opts.signInUrl,
1214
+ projectId: opts.projectId,
1215
+ email: opts.email,
1216
+ registerToken: intent.token,
1217
+ redirectUri,
1218
+ next: opts.next
1219
+ });
1220
+ window.location.assign(target);
1221
+ }
1222
+ async function addPasskey(opts) {
1223
+ if (!isBrowser()) {
1224
+ throw new AuthioError({
1225
+ code: "not_in_browser",
1226
+ message: "addPasskey can only be invoked in a browser environment.",
1227
+ status: 0
1228
+ });
1229
+ }
1230
+ const origin = opts.origin ?? window.location.origin;
1231
+ const intent = await mintPasskeyRegisterIntent(opts);
1232
+ const options = await authioFetch({
1233
+ apiUrl: opts.apiUrl,
1234
+ projectId: opts.projectId,
1235
+ path: "/v1/auth/passkey/register/options",
1236
+ method: "POST",
1237
+ body: { email: opts.email },
1238
+ signal: opts.signal,
1239
+ fetchImpl: opts.fetchImpl,
1240
+ extraHeaders: bearerHeaders(intent.token, origin)
1241
+ });
1242
+ let attestation;
1243
+ try {
1244
+ attestation = await startRegistration({ optionsJSON: options });
1245
+ } catch (err) {
1246
+ throw new AuthioError({
1247
+ code: "webauthn_cancelled",
1248
+ message: err instanceof Error ? err.message : "Passkey registration cancelled by user.",
1249
+ status: 0
1250
+ });
1251
+ }
1252
+ await authioFetch({
1253
+ apiUrl: opts.apiUrl,
1254
+ projectId: opts.projectId,
1255
+ path: "/v1/auth/passkey/register/verify",
1256
+ method: "POST",
1257
+ body: { email: opts.email, credential: attestation },
1258
+ signal: opts.signal,
1259
+ fetchImpl: opts.fetchImpl,
1260
+ extraHeaders: bearerHeaders(intent.token, origin)
1261
+ });
1262
+ }
1263
+ async function listPasskeys(opts) {
1264
+ const res = await authioFetch({
1265
+ apiUrl: opts.apiUrl,
1266
+ projectId: opts.projectId,
1267
+ path: "/v1/me/passkeys",
1268
+ signal: opts.signal,
1269
+ fetchImpl: opts.fetchImpl,
1270
+ extraHeaders: bearerHeaders(opts.accessToken)
1271
+ });
1272
+ return res.data ?? [];
1273
+ }
1274
+ async function renamePasskey(opts, credentialId, name) {
1275
+ await authioFetch({
1276
+ apiUrl: opts.apiUrl,
1277
+ projectId: opts.projectId,
1278
+ path: `/v1/me/passkeys/${encodeURIComponent(credentialId)}`,
1279
+ method: "PATCH",
1280
+ body: { nickname: name },
1281
+ signal: opts.signal,
1282
+ fetchImpl: opts.fetchImpl,
1283
+ extraHeaders: bearerHeaders(opts.accessToken)
1284
+ });
1285
+ }
1286
+ async function revokePasskey(opts, credentialId) {
1287
+ await authioFetch({
1288
+ apiUrl: opts.apiUrl,
1289
+ projectId: opts.projectId,
1290
+ path: `/v1/me/passkeys/${encodeURIComponent(credentialId)}`,
1291
+ method: "DELETE",
1292
+ signal: opts.signal,
1293
+ fetchImpl: opts.fetchImpl,
1294
+ extraHeaders: bearerHeaders(opts.accessToken)
1295
+ });
1296
+ }
1297
+ function usePasskeys() {
1298
+ const ctx = useAuthio();
1299
+ const [passkeys, setPasskeys] = useState([]);
1300
+ const [loading, setLoading] = useState(true);
1301
+ const [error, setError] = useState(null);
1302
+ const refresh = useCallback(async () => {
1303
+ if (ctx.status !== "authenticated") {
1304
+ setPasskeys([]);
1305
+ setLoading(false);
1306
+ return;
1307
+ }
1308
+ setLoading(true);
1309
+ setError(null);
1310
+ try {
1311
+ const token = await ctx.getAccessToken();
1312
+ if (!token) {
1313
+ setPasskeys([]);
1314
+ return;
1315
+ }
1316
+ const rows = await listPasskeys({
1317
+ apiUrl: ctx.apiUrl,
1318
+ projectId: ctx.projectId,
1319
+ accessToken: token,
1320
+ fetchImpl: ctx.fetchImpl
1321
+ });
1322
+ setPasskeys(rows);
1323
+ } catch (err) {
1324
+ setError(err instanceof Error ? err.message : "Failed to load passkeys");
1325
+ setPasskeys([]);
1326
+ } finally {
1327
+ setLoading(false);
1328
+ }
1329
+ }, [
1330
+ ctx.status,
1331
+ ctx.getAccessToken,
1332
+ ctx.apiUrl,
1333
+ ctx.projectId,
1334
+ ctx.fetchImpl
1335
+ ]);
1336
+ useEffect(() => {
1337
+ void refresh();
1338
+ }, [refresh, ctx.status]);
1339
+ const rename = useCallback(
1340
+ async (credentialId, nickname) => {
1341
+ const token = await ctx.getAccessToken();
1342
+ if (!token) throw new Error("Not signed in");
1343
+ await renamePasskey(
1344
+ {
1345
+ apiUrl: ctx.apiUrl,
1346
+ projectId: ctx.projectId,
1347
+ accessToken: token,
1348
+ fetchImpl: ctx.fetchImpl
1349
+ },
1350
+ credentialId,
1351
+ nickname
1352
+ );
1353
+ await refresh();
1354
+ },
1355
+ [ctx.getAccessToken, ctx.apiUrl, ctx.projectId, ctx.fetchImpl, refresh]
1356
+ );
1357
+ const revoke = useCallback(
1358
+ async (credentialId) => {
1359
+ const token = await ctx.getAccessToken();
1360
+ if (!token) throw new Error("Not signed in");
1361
+ await revokePasskey(
1362
+ {
1363
+ apiUrl: ctx.apiUrl,
1364
+ projectId: ctx.projectId,
1365
+ accessToken: token,
1366
+ fetchImpl: ctx.fetchImpl
1367
+ },
1368
+ credentialId
1369
+ );
1370
+ await refresh();
1371
+ },
1372
+ [ctx.getAccessToken, ctx.apiUrl, ctx.projectId, ctx.fetchImpl, refresh]
1373
+ );
1374
+ const enroll = useCallback(
1375
+ async (opts) => {
1376
+ const token = await ctx.getAccessToken();
1377
+ const email = ctx.user?.email;
1378
+ if (!token || !email) throw new Error("Not signed in");
1379
+ await enrollPasskey({
1380
+ apiUrl: ctx.apiUrl,
1381
+ projectId: ctx.projectId,
1382
+ accessToken: token,
1383
+ fetchImpl: ctx.fetchImpl,
1384
+ email,
1385
+ signInUrl: ctx.signInUrl,
1386
+ returnUrl: opts?.returnUrl,
1387
+ next: opts?.next
1388
+ });
1389
+ },
1390
+ [
1391
+ ctx.getAccessToken,
1392
+ ctx.user?.email,
1393
+ ctx.apiUrl,
1394
+ ctx.projectId,
1395
+ ctx.fetchImpl,
1396
+ ctx.signInUrl
1397
+ ]
1398
+ );
1399
+ return { passkeys, loading, error, refresh, rename, revoke, enroll };
1400
+ }
1401
+ function PasskeyManager({
1402
+ className,
1403
+ enrollReturnUrl,
1404
+ enrollNext
1405
+ }) {
1406
+ const { passkeys, loading, error, rename, revoke, enroll } = usePasskeys();
1407
+ const [busyId, setBusyId] = useState(null);
1408
+ const [actionError, setActionError] = useState(null);
1409
+ const [enrolling, setEnrolling] = useState(false);
1410
+ async function onRename(id, nickname) {
1411
+ setBusyId(id);
1412
+ setActionError(null);
1413
+ try {
1414
+ await rename(id, nickname);
1415
+ } catch (err) {
1416
+ setActionError(err instanceof Error ? err.message : "Rename failed");
1417
+ } finally {
1418
+ setBusyId(null);
1419
+ }
1420
+ }
1421
+ async function onRevoke(id) {
1422
+ setBusyId(id);
1423
+ setActionError(null);
1424
+ try {
1425
+ await revoke(id);
1426
+ } catch (err) {
1427
+ setActionError(err instanceof Error ? err.message : "Revoke failed");
1428
+ } finally {
1429
+ setBusyId(null);
1430
+ }
1431
+ }
1432
+ async function onEnroll() {
1433
+ setEnrolling(true);
1434
+ setActionError(null);
1435
+ try {
1436
+ await enroll({ returnUrl: enrollReturnUrl, next: enrollNext });
1437
+ } catch (err) {
1438
+ setEnrolling(false);
1439
+ setActionError(err instanceof Error ? err.message : "Could not start enrollment");
1440
+ }
1441
+ }
1442
+ return /* @__PURE__ */ jsxs("section", { className, "aria-labelledby": "authio-passkey-manager-title", children: [
1443
+ /* @__PURE__ */ jsxs("div", { className: "authio-passkey-manager__header", children: [
1444
+ /* @__PURE__ */ jsx("h2", { id: "authio-passkey-manager-title", children: "Passkeys" }),
1445
+ /* @__PURE__ */ jsx(
1446
+ "button",
1447
+ {
1448
+ type: "button",
1449
+ onClick: () => void onEnroll(),
1450
+ disabled: enrolling || loading,
1451
+ children: enrolling ? "Redirecting\u2026" : "Add passkey"
1452
+ }
1453
+ )
1454
+ ] }),
1455
+ (error || actionError) && /* @__PURE__ */ jsx("p", { role: "alert", className: "authio-passkey-manager__error", children: error ?? actionError }),
1456
+ loading ? /* @__PURE__ */ jsx("p", { className: "authio-passkey-manager__loading", children: "Loading passkeys\u2026" }) : passkeys.length === 0 ? /* @__PURE__ */ jsx("p", { className: "authio-passkey-manager__empty", children: "No passkeys yet. Add one to sign in faster on this account." }) : /* @__PURE__ */ jsx("ul", { className: "authio-passkey-manager__list", children: passkeys.map((p) => /* @__PURE__ */ jsx("li", { className: "authio-passkey-manager__item", children: /* @__PURE__ */ jsx(
1457
+ PasskeyRow,
1458
+ {
1459
+ passkey: p,
1460
+ busy: busyId === p.id,
1461
+ onRename,
1462
+ onRevoke
1463
+ }
1464
+ ) }, p.id)) })
1465
+ ] });
1466
+ }
1467
+ function PasskeyRow({
1468
+ passkey,
1469
+ busy,
1470
+ onRename,
1471
+ onRevoke
1472
+ }) {
1473
+ const [nickname, setNickname] = useState(passkey.nickname ?? "");
1474
+ return /* @__PURE__ */ jsxs("div", { className: "authio-passkey-manager__row", children: [
1475
+ /* @__PURE__ */ jsxs("div", { children: [
1476
+ /* @__PURE__ */ jsx("strong", { children: passkey.authenticator_name }),
1477
+ /* @__PURE__ */ jsxs("div", { className: "authio-passkey-manager__meta", children: [
1478
+ "Added ",
1479
+ new Date(passkey.created_at).toLocaleDateString(),
1480
+ passkey.last_used_at ? ` \xB7 Last used ${new Date(passkey.last_used_at).toLocaleDateString()}` : ""
1481
+ ] })
1482
+ ] }),
1483
+ /* @__PURE__ */ jsxs(
1484
+ "form",
1485
+ {
1486
+ className: "authio-passkey-manager__rename",
1487
+ onSubmit: (e) => {
1488
+ e.preventDefault();
1489
+ void onRename(passkey.id, nickname.trim());
1490
+ },
1491
+ children: [
1492
+ /* @__PURE__ */ jsx(
1493
+ "input",
1494
+ {
1495
+ type: "text",
1496
+ value: nickname,
1497
+ onChange: (e) => setNickname(e.target.value),
1498
+ placeholder: "Nickname",
1499
+ maxLength: 64,
1500
+ disabled: busy
1501
+ }
1502
+ ),
1503
+ /* @__PURE__ */ jsx("button", { type: "submit", disabled: busy, children: "Save" })
1504
+ ]
1505
+ }
1506
+ ),
1507
+ /* @__PURE__ */ jsx(
1508
+ "button",
1509
+ {
1510
+ type: "button",
1511
+ disabled: busy,
1512
+ onClick: () => void onRevoke(passkey.id),
1513
+ className: "authio-passkey-manager__revoke",
1514
+ children: "Revoke"
1515
+ }
1516
+ )
1517
+ ] });
1518
+ }
873
1519
 
874
1520
  // src/locate.ts
875
1521
  function captureClientLocation(opts = {}) {
@@ -902,7 +1548,11 @@ function captureClientLocation(opts = {}) {
902
1548
  );
903
1549
  });
904
1550
  }
1551
+ 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.";
1552
+ async function verifyLocate(_opts) {
1553
+ throw new Error(VERIFY_LOCATE_BACKEND_ONLY);
1554
+ }
905
1555
 
906
- export { AuthioContext, AuthioProvider, RedirectToSignIn, SignedIn, SignedOut, captureClientLocation, signInWithMagicLink, signInWithPasskey, useAuthio, useAuthioRequired, wrapFetchError };
1556
+ export { ActivityTracker, AuthioContext, AuthioProvider, DEVICE_SIGNALS_HEADER, PasskeyManager, RedirectToSignIn, SignedIn, SignedOut, addPasskey, buildEnrollPasskeyUrl, canEnrollPasskeyEmbedded, captureClientLocation, coerceSessionPolicy, collectDeviceSignals, deviceSignalsExtraHeaders, encodeDeviceSignalsHeader, enrollPasskey, listPasskeys, mintPasskeyRegisterIntent, renamePasskey, revokePasskey, sendEmailOtp, signInOrigin, signInWithMagicLink, signInWithPasskey, useAuthio, useAuthioRequired, usePasskeys, verifyEmailOtp, verifyLocate, wrapFetchError };
907
1557
  //# sourceMappingURL=index.js.map
908
1558
  //# sourceMappingURL=index.js.map