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