@useauthio/react 0.2.4 → 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
@@ -31,7 +31,7 @@ function wrapFetchError(err, fallbackCode = "network_error") {
31
31
  }
32
32
 
33
33
  // src/version.ts
34
- var SDK_VERSION = "0.2.2";
34
+ var SDK_VERSION = "0.3.0";
35
35
  var SDK_USER_AGENT = `react/${SDK_VERSION}`;
36
36
 
37
37
  // src/fetch.ts
@@ -141,6 +141,74 @@ function isTabHidden() {
141
141
  return document.visibilityState === "hidden";
142
142
  }
143
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
+
144
212
  // src/refresh.ts
145
213
  var BACKOFF_DELAYS_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
146
214
  var MAX_ATTEMPTS = 5;
@@ -162,23 +230,46 @@ var RefreshScheduler = class {
162
230
  attempts = 0;
163
231
  lastExp = null;
164
232
  destroyed = false;
233
+ deferred = null;
165
234
  visibilityHandler = null;
235
+ /** Whether the last tick was held back (and why). `null` when not deferred. */
236
+ deferredReason() {
237
+ return this.deferred;
238
+ }
166
239
  scheduleAt(exp) {
167
240
  if (this.destroyed) return;
168
241
  this.lastExp = exp;
169
242
  this.attempts = 0;
243
+ this.deferred = null;
170
244
  this.clear();
171
245
  const now = Math.floor(Date.now() / 1e3);
172
246
  const delayMs = Math.max(0, (exp - now - this.opts.leadSeconds) * 1e3);
173
247
  this.opts.onScheduled?.(Date.now() + delayMs);
174
248
  this.timer = setTimeout(() => void this.tick(), delayMs);
175
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
+ }
176
259
  async tick() {
177
260
  this.timer = null;
178
261
  if (this.destroyed) return;
179
262
  if (isTabHidden()) {
263
+ this.deferred = "hidden";
264
+ this.opts.onDeferred?.("hidden");
180
265
  return;
181
266
  }
267
+ if (this.opts.shouldDefer?.()) {
268
+ this.deferred = "idle";
269
+ this.opts.onDeferred?.("idle");
270
+ return;
271
+ }
272
+ this.deferred = null;
182
273
  let ok = false;
183
274
  try {
184
275
  ok = await this.opts.run();
@@ -307,7 +398,8 @@ async function mintLobbySignInUrl(opts) {
307
398
  body: JSON.stringify({
308
399
  project_id: opts.projectId,
309
400
  redirect_uri: opts.redirectUri,
310
- ...opts.next ? { next: opts.next } : {}
401
+ ...opts.next ? { next: opts.next } : {},
402
+ ...opts.organizationId ? { organization_id: opts.organizationId } : {}
311
403
  })
312
404
  }
313
405
  );
@@ -328,14 +420,29 @@ async function mintLobbySignInUrl(opts) {
328
420
  if (opts.next) {
329
421
  target.searchParams.set("next", opts.next);
330
422
  }
423
+ if (opts.organizationId) {
424
+ target.searchParams.set("organization_id", opts.organizationId);
425
+ }
331
426
  return target.toString();
332
427
  }
333
428
 
334
429
  // src/telemetry.ts
335
430
  var noopEmitter = () => {
336
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
+ }
337
443
  var AuthioContext = react.createContext(null);
338
444
  AuthioContext.displayName = "AuthioContext";
445
+ var ACTIVITY_GRACE_MS = 1e3;
339
446
  var DEFAULT_REFRESH_LEAD = 60;
340
447
  var DEFAULT_AUDIENCE = "authio";
341
448
  var DEFAULT_SIGN_IN_URL = "https://lobby.authio.com/";
@@ -345,6 +452,7 @@ function AuthioProvider(props) {
345
452
  projectId,
346
453
  storage: storageMode = "memory",
347
454
  refreshLeadSeconds = DEFAULT_REFRESH_LEAD,
455
+ idleRefresh = "defer",
348
456
  onTelemetryEvent,
349
457
  fetch: fetchImpl,
350
458
  signInUrl,
@@ -372,9 +480,19 @@ function AuthioProvider(props) {
372
480
  projectId,
373
481
  fetchImpl,
374
482
  signInUrl,
375
- emit
483
+ emit,
484
+ idleRefresh
376
485
  });
377
- 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);
378
496
  react.useEffect(() => {
379
497
  if (!projectId) {
380
498
  console.warn(
@@ -389,6 +507,17 @@ function AuthioProvider(props) {
389
507
  skipInitialRefresh ? "unauthenticated" : "loading"
390
508
  );
391
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
+ }, []);
392
521
  const performRefresh = react.useCallback(async () => {
393
522
  const p = propsRef.current;
394
523
  try {
@@ -436,6 +565,9 @@ function AuthioProvider(props) {
436
565
  setAccessToken(token);
437
566
  if (env.user) setUser(coerceUser(env.user));
438
567
  setStatus("authenticated");
568
+ adoptPolicy(
569
+ env.session_policy !== void 0 ? coerceSessionPolicy(env.session_policy) : policyRef.current
570
+ );
439
571
  p.emit({
440
572
  kind: "refresh_succeeded",
441
573
  timestamp: Date.now(),
@@ -458,14 +590,15 @@ function AuthioProvider(props) {
458
590
  });
459
591
  return false;
460
592
  }
461
- }, []);
593
+ }, [adoptPolicy]);
462
594
  react.useEffect(() => {
463
- schedulerRef.current = new RefreshScheduler({
595
+ const scheduler = new RefreshScheduler({
464
596
  leadSeconds: refreshLeadSeconds,
465
597
  run: performRefresh,
466
598
  onGiveUp: () => {
467
599
  storageRef.current.clear();
468
600
  refreshTokenRef.current = null;
601
+ clearPolicy();
469
602
  setAccessToken(null);
470
603
  setUser(null);
471
604
  setStatus("unauthenticated");
@@ -474,13 +607,44 @@ function AuthioProvider(props) {
474
607
  kind: "refresh_scheduled",
475
608
  timestamp: Date.now(),
476
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
477
626
  })
478
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
+ });
635
+ return () => {
636
+ unsubscribe();
637
+ scheduler.destroy();
638
+ if (schedulerRef.current === scheduler) schedulerRef.current = null;
639
+ };
640
+ }, [refreshLeadSeconds, performRefresh, clearPolicy, getTracker]);
641
+ react.useEffect(() => {
642
+ const tracker = getTracker();
479
643
  return () => {
480
- schedulerRef.current?.destroy();
481
- schedulerRef.current = null;
644
+ tracker.destroy();
645
+ if (activityRef.current === tracker) activityRef.current = null;
482
646
  };
483
- }, [refreshLeadSeconds, performRefresh]);
647
+ }, [getTracker]);
484
648
  react.useEffect(() => {
485
649
  if (skipInitialRefresh) {
486
650
  const stored2 = storageRef.current.get();
@@ -611,12 +775,13 @@ function AuthioProvider(props) {
611
775
  storageRef.current.clear();
612
776
  refreshTokenRef.current = null;
613
777
  schedulerRef.current?.clear();
778
+ clearPolicy();
614
779
  setAccessToken(null);
615
780
  setUser(null);
616
781
  setStatus("unauthenticated");
617
782
  p.emit({ kind: "sign_out", timestamp: Date.now() });
618
783
  }
619
- }, []);
784
+ }, [clearPolicy]);
620
785
  const refresh = react.useCallback(
621
786
  () => performRefresh(),
622
787
  [performRefresh]
@@ -652,6 +817,9 @@ function AuthioProvider(props) {
652
817
  setAccessToken(input.accessToken);
653
818
  if (input.user) setUser(input.user);
654
819
  setStatus("authenticated");
820
+ adoptPolicy(
821
+ input.sessionPolicy !== void 0 ? input.sessionPolicy : policyRef.current
822
+ );
655
823
  p.emit({
656
824
  kind: "sign_in_completed",
657
825
  timestamp: Date.now(),
@@ -662,7 +830,7 @@ function AuthioProvider(props) {
662
830
  schedulerRef.current?.scheduleAt(exp);
663
831
  }
664
832
  },
665
- []
833
+ [adoptPolicy]
666
834
  );
667
835
  const resolvedSignInUrl = signInUrl ?? DEFAULT_SIGN_IN_URL;
668
836
  const value = react.useMemo(
@@ -670,6 +838,7 @@ function AuthioProvider(props) {
670
838
  user,
671
839
  status,
672
840
  accessToken,
841
+ sessionPolicy,
673
842
  apiUrl,
674
843
  projectId,
675
844
  signInUrl: resolvedSignInUrl,
@@ -684,6 +853,7 @@ function AuthioProvider(props) {
684
853
  user,
685
854
  status,
686
855
  accessToken,
856
+ sessionPolicy,
687
857
  apiUrl,
688
858
  projectId,
689
859
  resolvedSignInUrl,
@@ -757,6 +927,51 @@ function RedirectToSignIn({
757
927
  }, [signIn, returnTo]);
758
928
  return null;
759
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
760
975
  async function signInWithMagicLink(opts) {
761
976
  await authioFetch({
762
977
  apiUrl: opts.apiUrl,
@@ -847,7 +1062,12 @@ async function signInWithPasskey(opts) {
847
1062
  projectId: opts.projectId,
848
1063
  path: "/v1/auth/passkey/login/verify",
849
1064
  method: "POST",
850
- 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(),
851
1071
  credentials: "include",
852
1072
  signal: opts.signal,
853
1073
  fetchImpl: opts.fetch
@@ -855,6 +1075,64 @@ async function signInWithPasskey(opts) {
855
1075
  return {
856
1076
  accessToken: verifyRes.access_token,
857
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),
858
1136
  user: {
859
1137
  id: verifyRes.user.id,
860
1138
  email: verifyRes.user.email,
@@ -1271,13 +1549,19 @@ function captureClientLocation(opts = {}) {
1271
1549
  );
1272
1550
  });
1273
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
+ }
1274
1556
 
1275
1557
  Object.defineProperty(exports, "AuthioError", {
1276
1558
  enumerable: true,
1277
1559
  get: function () { return node.AuthioError; }
1278
1560
  });
1561
+ exports.ActivityTracker = ActivityTracker;
1279
1562
  exports.AuthioContext = AuthioContext;
1280
1563
  exports.AuthioProvider = AuthioProvider;
1564
+ exports.DEVICE_SIGNALS_HEADER = DEVICE_SIGNALS_HEADER;
1281
1565
  exports.PasskeyManager = PasskeyManager;
1282
1566
  exports.RedirectToSignIn = RedirectToSignIn;
1283
1567
  exports.SignedIn = SignedIn;
@@ -1286,17 +1570,24 @@ exports.addPasskey = addPasskey;
1286
1570
  exports.buildEnrollPasskeyUrl = buildEnrollPasskeyUrl;
1287
1571
  exports.canEnrollPasskeyEmbedded = canEnrollPasskeyEmbedded;
1288
1572
  exports.captureClientLocation = captureClientLocation;
1573
+ exports.coerceSessionPolicy = coerceSessionPolicy;
1574
+ exports.collectDeviceSignals = collectDeviceSignals;
1575
+ exports.deviceSignalsExtraHeaders = deviceSignalsExtraHeaders;
1576
+ exports.encodeDeviceSignalsHeader = encodeDeviceSignalsHeader;
1289
1577
  exports.enrollPasskey = enrollPasskey;
1290
1578
  exports.listPasskeys = listPasskeys;
1291
1579
  exports.mintPasskeyRegisterIntent = mintPasskeyRegisterIntent;
1292
1580
  exports.renamePasskey = renamePasskey;
1293
1581
  exports.revokePasskey = revokePasskey;
1582
+ exports.sendEmailOtp = sendEmailOtp;
1294
1583
  exports.signInOrigin = signInOrigin;
1295
1584
  exports.signInWithMagicLink = signInWithMagicLink;
1296
1585
  exports.signInWithPasskey = signInWithPasskey;
1297
1586
  exports.useAuthio = useAuthio;
1298
1587
  exports.useAuthioRequired = useAuthioRequired;
1299
1588
  exports.usePasskeys = usePasskeys;
1589
+ exports.verifyEmailOtp = verifyEmailOtp;
1590
+ exports.verifyLocate = verifyLocate;
1300
1591
  exports.wrapFetchError = wrapFetchError;
1301
1592
  //# sourceMappingURL=index.cjs.map
1302
1593
  //# sourceMappingURL=index.cjs.map