@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.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createContext, useRef, useEffect, useState, useCallback, useMemo, useContext } from 'react';
1
+ import { createContext, useRef, useCallback, useEffect, useState, useMemo, useContext } from 'react';
2
2
  import { AuthioError, JwtVerifier } from '@useauthio/node';
3
3
  export { AuthioError } from '@useauthio/node';
4
4
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
@@ -30,7 +30,7 @@ function wrapFetchError(err, fallbackCode = "network_error") {
30
30
  }
31
31
 
32
32
  // src/version.ts
33
- var SDK_VERSION = "0.2.2";
33
+ var SDK_VERSION = "0.3.0";
34
34
  var SDK_USER_AGENT = `react/${SDK_VERSION}`;
35
35
 
36
36
  // src/fetch.ts
@@ -140,6 +140,74 @@ function isTabHidden() {
140
140
  return document.visibilityState === "hidden";
141
141
  }
142
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
+
143
211
  // src/refresh.ts
144
212
  var BACKOFF_DELAYS_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
145
213
  var MAX_ATTEMPTS = 5;
@@ -161,23 +229,46 @@ var RefreshScheduler = class {
161
229
  attempts = 0;
162
230
  lastExp = null;
163
231
  destroyed = false;
232
+ deferred = null;
164
233
  visibilityHandler = null;
234
+ /** Whether the last tick was held back (and why). `null` when not deferred. */
235
+ deferredReason() {
236
+ return this.deferred;
237
+ }
165
238
  scheduleAt(exp) {
166
239
  if (this.destroyed) return;
167
240
  this.lastExp = exp;
168
241
  this.attempts = 0;
242
+ this.deferred = null;
169
243
  this.clear();
170
244
  const now = Math.floor(Date.now() / 1e3);
171
245
  const delayMs = Math.max(0, (exp - now - this.opts.leadSeconds) * 1e3);
172
246
  this.opts.onScheduled?.(Date.now() + delayMs);
173
247
  this.timer = setTimeout(() => void this.tick(), delayMs);
174
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
+ }
175
258
  async tick() {
176
259
  this.timer = null;
177
260
  if (this.destroyed) return;
178
261
  if (isTabHidden()) {
262
+ this.deferred = "hidden";
263
+ this.opts.onDeferred?.("hidden");
179
264
  return;
180
265
  }
266
+ if (this.opts.shouldDefer?.()) {
267
+ this.deferred = "idle";
268
+ this.opts.onDeferred?.("idle");
269
+ return;
270
+ }
271
+ this.deferred = null;
181
272
  let ok = false;
182
273
  try {
183
274
  ok = await this.opts.run();
@@ -306,7 +397,8 @@ async function mintLobbySignInUrl(opts) {
306
397
  body: JSON.stringify({
307
398
  project_id: opts.projectId,
308
399
  redirect_uri: opts.redirectUri,
309
- ...opts.next ? { next: opts.next } : {}
400
+ ...opts.next ? { next: opts.next } : {},
401
+ ...opts.organizationId ? { organization_id: opts.organizationId } : {}
310
402
  })
311
403
  }
312
404
  );
@@ -327,14 +419,29 @@ async function mintLobbySignInUrl(opts) {
327
419
  if (opts.next) {
328
420
  target.searchParams.set("next", opts.next);
329
421
  }
422
+ if (opts.organizationId) {
423
+ target.searchParams.set("organization_id", opts.organizationId);
424
+ }
330
425
  return target.toString();
331
426
  }
332
427
 
333
428
  // src/telemetry.ts
334
429
  var noopEmitter = () => {
335
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
+ }
336
442
  var AuthioContext = createContext(null);
337
443
  AuthioContext.displayName = "AuthioContext";
444
+ var ACTIVITY_GRACE_MS = 1e3;
338
445
  var DEFAULT_REFRESH_LEAD = 60;
339
446
  var DEFAULT_AUDIENCE = "authio";
340
447
  var DEFAULT_SIGN_IN_URL = "https://lobby.authio.com/";
@@ -344,6 +451,7 @@ function AuthioProvider(props) {
344
451
  projectId,
345
452
  storage: storageMode = "memory",
346
453
  refreshLeadSeconds = DEFAULT_REFRESH_LEAD,
454
+ idleRefresh = "defer",
347
455
  onTelemetryEvent,
348
456
  fetch: fetchImpl,
349
457
  signInUrl,
@@ -371,9 +479,19 @@ function AuthioProvider(props) {
371
479
  projectId,
372
480
  fetchImpl,
373
481
  signInUrl,
374
- emit
482
+ emit,
483
+ idleRefresh
375
484
  });
376
- 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);
377
495
  useEffect(() => {
378
496
  if (!projectId) {
379
497
  console.warn(
@@ -388,6 +506,17 @@ function AuthioProvider(props) {
388
506
  skipInitialRefresh ? "unauthenticated" : "loading"
389
507
  );
390
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
+ }, []);
391
520
  const performRefresh = useCallback(async () => {
392
521
  const p = propsRef.current;
393
522
  try {
@@ -435,6 +564,9 @@ function AuthioProvider(props) {
435
564
  setAccessToken(token);
436
565
  if (env.user) setUser(coerceUser(env.user));
437
566
  setStatus("authenticated");
567
+ adoptPolicy(
568
+ env.session_policy !== void 0 ? coerceSessionPolicy(env.session_policy) : policyRef.current
569
+ );
438
570
  p.emit({
439
571
  kind: "refresh_succeeded",
440
572
  timestamp: Date.now(),
@@ -457,14 +589,15 @@ function AuthioProvider(props) {
457
589
  });
458
590
  return false;
459
591
  }
460
- }, []);
592
+ }, [adoptPolicy]);
461
593
  useEffect(() => {
462
- schedulerRef.current = new RefreshScheduler({
594
+ const scheduler = new RefreshScheduler({
463
595
  leadSeconds: refreshLeadSeconds,
464
596
  run: performRefresh,
465
597
  onGiveUp: () => {
466
598
  storageRef.current.clear();
467
599
  refreshTokenRef.current = null;
600
+ clearPolicy();
468
601
  setAccessToken(null);
469
602
  setUser(null);
470
603
  setStatus("unauthenticated");
@@ -473,13 +606,44 @@ function AuthioProvider(props) {
473
606
  kind: "refresh_scheduled",
474
607
  timestamp: Date.now(),
475
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
476
625
  })
477
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
+ });
634
+ return () => {
635
+ unsubscribe();
636
+ scheduler.destroy();
637
+ if (schedulerRef.current === scheduler) schedulerRef.current = null;
638
+ };
639
+ }, [refreshLeadSeconds, performRefresh, clearPolicy, getTracker]);
640
+ useEffect(() => {
641
+ const tracker = getTracker();
478
642
  return () => {
479
- schedulerRef.current?.destroy();
480
- schedulerRef.current = null;
643
+ tracker.destroy();
644
+ if (activityRef.current === tracker) activityRef.current = null;
481
645
  };
482
- }, [refreshLeadSeconds, performRefresh]);
646
+ }, [getTracker]);
483
647
  useEffect(() => {
484
648
  if (skipInitialRefresh) {
485
649
  const stored2 = storageRef.current.get();
@@ -610,12 +774,13 @@ function AuthioProvider(props) {
610
774
  storageRef.current.clear();
611
775
  refreshTokenRef.current = null;
612
776
  schedulerRef.current?.clear();
777
+ clearPolicy();
613
778
  setAccessToken(null);
614
779
  setUser(null);
615
780
  setStatus("unauthenticated");
616
781
  p.emit({ kind: "sign_out", timestamp: Date.now() });
617
782
  }
618
- }, []);
783
+ }, [clearPolicy]);
619
784
  const refresh = useCallback(
620
785
  () => performRefresh(),
621
786
  [performRefresh]
@@ -651,6 +816,9 @@ function AuthioProvider(props) {
651
816
  setAccessToken(input.accessToken);
652
817
  if (input.user) setUser(input.user);
653
818
  setStatus("authenticated");
819
+ adoptPolicy(
820
+ input.sessionPolicy !== void 0 ? input.sessionPolicy : policyRef.current
821
+ );
654
822
  p.emit({
655
823
  kind: "sign_in_completed",
656
824
  timestamp: Date.now(),
@@ -661,7 +829,7 @@ function AuthioProvider(props) {
661
829
  schedulerRef.current?.scheduleAt(exp);
662
830
  }
663
831
  },
664
- []
832
+ [adoptPolicy]
665
833
  );
666
834
  const resolvedSignInUrl = signInUrl ?? DEFAULT_SIGN_IN_URL;
667
835
  const value = useMemo(
@@ -669,6 +837,7 @@ function AuthioProvider(props) {
669
837
  user,
670
838
  status,
671
839
  accessToken,
840
+ sessionPolicy,
672
841
  apiUrl,
673
842
  projectId,
674
843
  signInUrl: resolvedSignInUrl,
@@ -683,6 +852,7 @@ function AuthioProvider(props) {
683
852
  user,
684
853
  status,
685
854
  accessToken,
855
+ sessionPolicy,
686
856
  apiUrl,
687
857
  projectId,
688
858
  resolvedSignInUrl,
@@ -756,6 +926,51 @@ function RedirectToSignIn({
756
926
  }, [signIn, returnTo]);
757
927
  return null;
758
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
759
974
  async function signInWithMagicLink(opts) {
760
975
  await authioFetch({
761
976
  apiUrl: opts.apiUrl,
@@ -846,7 +1061,12 @@ async function signInWithPasskey(opts) {
846
1061
  projectId: opts.projectId,
847
1062
  path: "/v1/auth/passkey/login/verify",
848
1063
  method: "POST",
849
- 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(),
850
1070
  credentials: "include",
851
1071
  signal: opts.signal,
852
1072
  fetchImpl: opts.fetch
@@ -854,6 +1074,64 @@ async function signInWithPasskey(opts) {
854
1074
  return {
855
1075
  accessToken: verifyRes.access_token,
856
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),
857
1135
  user: {
858
1136
  id: verifyRes.user.id,
859
1137
  email: verifyRes.user.email,
@@ -1270,7 +1548,11 @@ function captureClientLocation(opts = {}) {
1270
1548
  );
1271
1549
  });
1272
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
+ }
1273
1555
 
1274
- export { AuthioContext, AuthioProvider, PasskeyManager, RedirectToSignIn, SignedIn, SignedOut, addPasskey, buildEnrollPasskeyUrl, canEnrollPasskeyEmbedded, captureClientLocation, enrollPasskey, listPasskeys, mintPasskeyRegisterIntent, renamePasskey, revokePasskey, signInOrigin, signInWithMagicLink, signInWithPasskey, useAuthio, useAuthioRequired, usePasskeys, 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 };
1275
1557
  //# sourceMappingURL=index.js.map
1276
1558
  //# sourceMappingURL=index.js.map