@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.d.cts CHANGED
@@ -24,6 +24,10 @@ export { AuthioError } from '@useauthio/node';
24
24
  * - `refresh_scheduled`: a future silent refresh has been timer-
25
25
  * scheduled. `runAt` is the unix millisecond at which the refresh
26
26
  * will fire (subject to the visibilitychange deferral).
27
+ * - `refresh_deferred`: a scheduled refresh was held back — `hidden`
28
+ * when the tab is in the background, `idle` when the user has not
29
+ * interacted since the last refresh and the session policy has an
30
+ * inactivity timeout. `refresh_resumed` follows when it re-arms.
27
31
  * - `sign_in_started` / `sign_in_completed` / `sign_in_failed`: the
28
32
  * three terminal states of a sign-in attempt. `method` says which
29
33
  * surface initiated it.
@@ -50,6 +54,14 @@ type AuthioTelemetryEvent = {
50
54
  kind: "refresh_scheduled";
51
55
  timestamp: number;
52
56
  runAt: number;
57
+ } | {
58
+ kind: "refresh_deferred";
59
+ timestamp: number;
60
+ /** `hidden`: background tab. `idle`: no user activity under an inactivity policy. */
61
+ reason: "hidden" | "idle";
62
+ } | {
63
+ kind: "refresh_resumed";
64
+ timestamp: number;
53
65
  } | {
54
66
  kind: "sign_in_started";
55
67
  timestamp: number;
@@ -98,11 +110,57 @@ interface AuthioUser {
98
110
  * - `unauthenticated` — no session; show your sign-in surface.
99
111
  */
100
112
  type AuthioStatus = "loading" | "authenticated" | "unauthenticated";
113
+ /**
114
+ * Effective session-lifecycle policy for the current session, as reported
115
+ * by auth-core in the `session_policy` field of every session envelope
116
+ * (sign-in, refresh, switch-org). Values are minutes; `0` means "no limit
117
+ * at this layer". `null` on the context when auth-core predates the field.
118
+ *
119
+ * The SDK uses `idleTimeoutMin` to decide whether a timer-driven silent
120
+ * refresh should be held back while the user is inactive — see the
121
+ * `idleRefresh` provider prop.
122
+ */
123
+ interface SessionPolicy {
124
+ idleTimeoutMin: number;
125
+ absoluteMaxMin: number;
126
+ accessTokenTtlMin: number;
127
+ }
128
+ /** Wire shape of `session_policy` on auth-core envelopes. */
129
+ interface RawSessionPolicy {
130
+ idle_timeout_min?: number;
131
+ absolute_max_min?: number;
132
+ access_token_ttl_min?: number;
133
+ }
134
+ /**
135
+ * Normalise a raw `session_policy` object. Returns `null` when the field
136
+ * is absent or malformed (older auth-core), so callers can keep the
137
+ * legacy always-refresh behaviour.
138
+ */
139
+ declare function coerceSessionPolicy(raw: RawSessionPolicy | null | undefined): SessionPolicy | null;
140
+ /**
141
+ * How the silent-refresh timer behaves while the user is inactive.
142
+ *
143
+ * - `"defer"` (default): when the effective policy has an inactivity
144
+ * timeout (`sessionPolicy.idleTimeoutMin > 0`) and there has been no
145
+ * user interaction since the last refresh, the scheduled refresh is
146
+ * held until the next interaction. Without an inactivity policy the
147
+ * refresh always runs — identical to previous SDK versions.
148
+ * - `"always"`: never hold a refresh for inactivity (tab-hidden
149
+ * deferral still applies). Escape hatch for apps whose background
150
+ * work needs a warm token even when nobody is at the keyboard.
151
+ */
152
+ type AuthioIdleRefreshMode = "defer" | "always";
101
153
  type AuthioStorageMode = "memory" | "localStorage" | "sessionStorage" | "none";
102
154
  interface AuthioContextValue {
103
155
  user: AuthioUser | null;
104
156
  status: AuthioStatus;
105
157
  accessToken: string | null;
158
+ /**
159
+ * Effective session-lifecycle policy reported by auth-core on the last
160
+ * envelope, or `null` when unknown (no session yet, or an auth-core
161
+ * that predates `session_policy`).
162
+ */
163
+ sessionPolicy: SessionPolicy | null;
106
164
  /** Same `apiUrl` passed to `<AuthioProvider>`. */
107
165
  apiUrl: string;
108
166
  /** Same `projectId` passed to `<AuthioProvider>`. */
@@ -164,6 +222,8 @@ interface AuthioContextValue {
164
222
  accessToken: string;
165
223
  refreshToken?: string | null;
166
224
  user?: AuthioUser | null;
225
+ /** Policy from the sign-in envelope, when the helper surfaced one. */
226
+ sessionPolicy?: SessionPolicy | null;
167
227
  }) => Promise<void>;
168
228
  }
169
229
  /** Result of a single JWT verification attempt. */
@@ -194,6 +254,14 @@ interface AuthioProviderProps {
194
254
  * a background tab.
195
255
  */
196
256
  refreshLeadSeconds?: number;
257
+ /**
258
+ * Silent-refresh behaviour while the user is inactive. Defaults to
259
+ * `"defer"`: under a project/org inactivity policy the timer-driven
260
+ * refresh waits for the next user interaction instead of keeping the
261
+ * session warm on an idle tab. Projects without an inactivity policy
262
+ * are unaffected. See {@link AuthioIdleRefreshMode}.
263
+ */
264
+ idleRefresh?: AuthioIdleRefreshMode;
197
265
  /**
198
266
  * Optional sink for SDK telemetry (refresh outcomes, sign-in
199
267
  * starts/completes, token verification results). Useful for
@@ -359,6 +427,87 @@ interface RedirectToSignInProps {
359
427
  */
360
428
  declare function RedirectToSignIn({ returnTo, }: RedirectToSignInProps): React.ReactElement | null;
361
429
 
430
+ /**
431
+ * Optional browser device signals for Authio risk / device fingerprinting.
432
+ *
433
+ * Web browsers do not expose a hardware ID (IMEI, serial, MAC). These
434
+ * coarse, non-PII signals improve device recognition alongside the
435
+ * server-parsed user agent. auth-core hashes them server-side — never
436
+ * send a precomputed fingerprint from the client.
437
+ */
438
+ interface DeviceSignalsCapture {
439
+ timezone?: string;
440
+ screen_resolution?: string;
441
+ language?: string;
442
+ platform?: string;
443
+ }
444
+ /** Collect coarse device signals available in a browser context. */
445
+ declare function collectDeviceSignals(): DeviceSignalsCapture;
446
+ /** Encode signals for the `X-Authio-Device-Signals` request header. */
447
+ declare function encodeDeviceSignalsHeader(signals: DeviceSignalsCapture): string;
448
+ /** Header name auth-core reads for optional client device signals. */
449
+ declare const DEVICE_SIGNALS_HEADER = "X-Authio-Device-Signals";
450
+ declare function deviceSignalsExtraHeaders(signals?: DeviceSignalsCapture): Record<string, string>;
451
+
452
+ /**
453
+ * Browser helpers for Authio Locate client attestation.
454
+ *
455
+ * Capture device geolocation and pass it to sign-in or standalone verify
456
+ * calls as `client_location`. Requires user consent (browser prompt).
457
+ */
458
+ interface ClientLocationCapture {
459
+ latitude: number;
460
+ longitude: number;
461
+ accuracy_m: number;
462
+ captured_at: string;
463
+ source: "browser_geolocation";
464
+ }
465
+ interface CaptureClientLocationOptions {
466
+ timeoutMs?: number;
467
+ maximumAgeMs?: number;
468
+ enableHighAccuracy?: boolean;
469
+ }
470
+ /**
471
+ * Request the browser's current position. Rejects when geolocation is
472
+ * unavailable, denied, or times out.
473
+ */
474
+ declare function captureClientLocation(opts?: CaptureClientLocationOptions): Promise<ClientLocationCapture>;
475
+ type LocateAction = "sign_in" | "wager_placed" | "contest_entry" | string;
476
+ interface VerifyLocateOptions {
477
+ apiUrl: string;
478
+ projectId: string;
479
+ accessToken: string;
480
+ action: LocateAction;
481
+ clientLocation?: ClientLocationCapture;
482
+ idempotencyKey?: string;
483
+ fetchImpl?: typeof fetch;
484
+ signal?: AbortSignal;
485
+ }
486
+ interface LocateVerifyResult {
487
+ verification_id: string;
488
+ decision: "allow" | "block";
489
+ confidence: number;
490
+ method: string;
491
+ location: {
492
+ country: string;
493
+ region: string;
494
+ source: string;
495
+ };
496
+ network_signals: {
497
+ vpn: boolean;
498
+ datacenter: boolean;
499
+ tor: boolean;
500
+ anonymous_proxy: boolean;
501
+ satellite: boolean;
502
+ };
503
+ evasion_signals: string[];
504
+ }
505
+ /**
506
+ * @deprecated Use backend proxy with `@useauthio/node` `authio.locate.verify()` — see JB migration guide.
507
+ * This helper always throws; it must not send a user JWT to the sk_-only verify route.
508
+ */
509
+ declare function verifyLocate(_opts: VerifyLocateOptions): Promise<LocateVerifyResult>;
510
+
362
511
  interface SignInWithMagicLinkOptions {
363
512
  /** Authio auth-core base URL. */
364
513
  apiUrl: string;
@@ -410,12 +559,22 @@ interface SignInWithPasskeyOptions {
410
559
  * the user picks their key from the browser's native chooser.
411
560
  */
412
561
  email?: string;
562
+ /**
563
+ * Post-sign-in path on the app (`next`) forwarded to auth-core on
564
+ * the verify call. Older auth-core deployments ignore it; token
565
+ * handling on the client is unchanged either way.
566
+ */
567
+ next?: string;
568
+ /** Organization scope (`org_…`) for org-policy enforcement. */
569
+ organizationId?: string;
413
570
  signal?: AbortSignal;
414
571
  fetch?: typeof fetch;
415
572
  }
416
573
  interface SignInWithPasskeyResult {
417
574
  accessToken: string;
418
575
  refreshToken?: string;
576
+ /** Effective session policy from the envelope, `null` on older auth-core. */
577
+ sessionPolicy: SessionPolicy | null;
419
578
  user: AuthioUser;
420
579
  }
421
580
  /**
@@ -444,6 +603,77 @@ interface SignInWithPasskeyResult {
444
603
  * canonical storage. Callers should typically discard `refreshToken`.
445
604
  */
446
605
  declare function signInWithPasskey(opts: SignInWithPasskeyOptions): Promise<SignInWithPasskeyResult>;
606
+ interface SendEmailOtpOptions {
607
+ /** Authio auth-core base URL. */
608
+ apiUrl: string;
609
+ /** Project ID (`proj_…`). */
610
+ projectId: string;
611
+ /** Email address to send the 6-digit code to. */
612
+ email: string;
613
+ /**
614
+ * Where auth-core should consider the sign-in to be headed. Optional —
615
+ * when omitted, auth-core derives it from the request Origin.
616
+ */
617
+ redirectUri?: string;
618
+ /** Post-sign-in path on the app, carried through to the session redirect. */
619
+ next?: string;
620
+ /** Organization scope (`org_…`) for org-policy enforcement. */
621
+ organizationId?: string;
622
+ signal?: AbortSignal;
623
+ fetch?: typeof fetch;
624
+ }
625
+ /**
626
+ * POSTs `/v1/auth/email-otp/send` — the same endpoint/body shape the
627
+ * hosted Lobby's "Email me a code" button uses. Returns `void` on
628
+ * success; the code is now in the user's inbox. Throws `AuthioError`
629
+ * on any failure (rate-limit, invalid email, org policy, network).
630
+ *
631
+ * Note: unlike `verifyEmailOtp`, the send endpoint does not accept
632
+ * `client_location` — capture location once and pass it to verify.
633
+ */
634
+ declare function sendEmailOtp(opts: SendEmailOtpOptions): Promise<void>;
635
+ interface VerifyEmailOtpOptions {
636
+ apiUrl: string;
637
+ projectId: string;
638
+ /** Email address the code was sent to. */
639
+ email: string;
640
+ /** The 6-digit code from the user's inbox. */
641
+ code: string;
642
+ /** Fallback redirect target when the send call didn't record one. */
643
+ redirectUri?: string;
644
+ /** Post-sign-in path on the app. */
645
+ next?: string;
646
+ /** Organization scope (`org_…`) for org-policy enforcement. */
647
+ organizationId?: string;
648
+ /** Optional browser geolocation for Authio Locate attestation. */
649
+ clientLocation?: ClientLocationCapture;
650
+ /** Optional coarse device signals for risk / device recognition. */
651
+ deviceSignals?: DeviceSignalsCapture;
652
+ signal?: AbortSignal;
653
+ fetch?: typeof fetch;
654
+ }
655
+ interface VerifyEmailOtpResult {
656
+ accessToken: string;
657
+ refreshToken?: string;
658
+ /** Effective session policy from the envelope, `null` on older auth-core. */
659
+ sessionPolicy: SessionPolicy | null;
660
+ user: AuthioUser;
661
+ }
662
+ /**
663
+ * POSTs `/v1/auth/email-otp/verify` with the code the user typed —
664
+ * mirrors the hosted Lobby's verify body shape. On success returns
665
+ * `{ accessToken, refreshToken, user }`; auth-core also sets the
666
+ * session cookie via `Set-Cookie` (the request runs with
667
+ * `credentials: "include"`), which is the canonical storage.
668
+ *
669
+ * Throws `AuthioError`:
670
+ *
671
+ * - `invalid_code` for a wrong/expired code (auth-core's code).
672
+ * - `step_up_required` when the risk engine withholds the session
673
+ * pending a second factor — finish the sign-in on the hosted UI.
674
+ * - Whatever else auth-core returns (rate-limit, policy, etc.).
675
+ */
676
+ declare function verifyEmailOtp(opts: VerifyEmailOtpOptions): Promise<VerifyEmailOtpResult>;
447
677
 
448
678
  interface AuthioPasskey {
449
679
  id: string;
@@ -555,30 +785,6 @@ interface PasskeyManagerProps {
555
785
  */
556
786
  declare function PasskeyManager({ className, enrollReturnUrl, enrollNext, }: PasskeyManagerProps): React.ReactElement;
557
787
 
558
- /**
559
- * Browser helpers for Authio Locate client attestation.
560
- *
561
- * Capture device geolocation and pass it to sign-in or standalone verify
562
- * calls as `client_location`. Requires user consent (browser prompt).
563
- */
564
- interface ClientLocationCapture {
565
- latitude: number;
566
- longitude: number;
567
- accuracy_m: number;
568
- captured_at: string;
569
- source: "browser_geolocation";
570
- }
571
- interface CaptureClientLocationOptions {
572
- timeoutMs?: number;
573
- maximumAgeMs?: number;
574
- enableHighAccuracy?: boolean;
575
- }
576
- /**
577
- * Request the browser's current position. Rejects when geolocation is
578
- * unavailable, denied, or times out.
579
- */
580
- declare function captureClientLocation(opts?: CaptureClientLocationOptions): Promise<ClientLocationCapture>;
581
-
582
788
  /**
583
789
  * Wrap a native fetch rejection (network error, abort, timeout) in
584
790
  * an `AuthioError` so consumers always get a typed `code` to switch
@@ -586,4 +792,38 @@ declare function captureClientLocation(opts?: CaptureClientLocationOptions): Pro
586
792
  */
587
793
  declare function wrapFetchError(err: unknown, fallbackCode?: string): AuthioError;
588
794
 
589
- export { type AddPasskeyOptions, AuthioContext, type AuthioContextValue, type AuthioPasskey, AuthioProvider, type AuthioProviderProps, type AuthioStatus, type AuthioStorageMode, type AuthioTelemetryEvent, type AuthioTokenVerification, type AuthioTokenVerifier, type AuthioUser, type CaptureClientLocationOptions, type ClientLocationCapture, type EnrollPasskeyOptions, type PasskeyApiOptions, PasskeyManager, type PasskeyManagerProps, RedirectToSignIn, type RedirectToSignInProps, type SignInWithMagicLinkOptions, type SignInWithPasskeyOptions, type SignInWithPasskeyResult, SignedIn, type SignedInProps, SignedOut, type SignedOutProps, type UseAuthioRequiredOptions, type UseAuthioRequiredResult, type UsePasskeysResult, addPasskey, buildEnrollPasskeyUrl, canEnrollPasskeyEmbedded, captureClientLocation, enrollPasskey, listPasskeys, mintPasskeyRegisterIntent, renamePasskey, revokePasskey, signInOrigin, signInWithMagicLink, signInWithPasskey, useAuthio, useAuthioRequired, usePasskeys, wrapFetchError };
795
+ type ActivityListener = (at: number) => void;
796
+ /**
797
+ * Tracks the last moment the user interacted with the page. Used by the
798
+ * provider to decide whether a scheduled silent refresh should run or
799
+ * be deferred: when the project/org has an inactivity (idle) timeout,
800
+ * refreshing on a timer while nobody is at the keyboard would bump the
801
+ * server's `last_active_at` and defeat that policy. See `RefreshScheduler`.
802
+ *
803
+ * SSR-safe — under SSR `lastActivityAt()` is `0` and listeners are never
804
+ * attached.
805
+ */
806
+ declare class ActivityTracker {
807
+ private last;
808
+ private listeners;
809
+ private handler;
810
+ private visibilityHandler;
811
+ private destroyed;
812
+ constructor(now?: () => number);
813
+ private readonly now;
814
+ /** Unix ms of the most recent recorded interaction, `0` if none yet. */
815
+ lastActivityAt(): number;
816
+ /**
817
+ * Record activity now. Throttled to one write per second; listeners
818
+ * fire only when a write actually happens. Exposed so tests (and
819
+ * embedders with their own activity signal) can poke it directly.
820
+ */
821
+ mark(): void;
822
+ /** Subscribe to recorded activity. Returns an unsubscribe function. */
823
+ onActivity(listener: ActivityListener): () => void;
824
+ destroy(): void;
825
+ }
826
+
827
+ type RefreshDeferReason = "hidden" | "idle";
828
+
829
+ export { type ActivityListener, ActivityTracker, type AddPasskeyOptions, AuthioContext, type AuthioContextValue, type AuthioIdleRefreshMode, type AuthioPasskey, AuthioProvider, type AuthioProviderProps, type AuthioStatus, type AuthioStorageMode, type AuthioTelemetryEvent, type AuthioTokenVerification, type AuthioTokenVerifier, type AuthioUser, type CaptureClientLocationOptions, type ClientLocationCapture, DEVICE_SIGNALS_HEADER, type DeviceSignalsCapture, type EnrollPasskeyOptions, type LocateAction, type LocateVerifyResult, type PasskeyApiOptions, PasskeyManager, type PasskeyManagerProps, type RawSessionPolicy, RedirectToSignIn, type RedirectToSignInProps, type RefreshDeferReason, type SendEmailOtpOptions, type SessionPolicy, type SignInWithMagicLinkOptions, type SignInWithPasskeyOptions, type SignInWithPasskeyResult, SignedIn, type SignedInProps, SignedOut, type SignedOutProps, type UseAuthioRequiredOptions, type UseAuthioRequiredResult, type UsePasskeysResult, type VerifyEmailOtpOptions, type VerifyEmailOtpResult, type VerifyLocateOptions, addPasskey, buildEnrollPasskeyUrl, canEnrollPasskeyEmbedded, captureClientLocation, coerceSessionPolicy, collectDeviceSignals, deviceSignalsExtraHeaders, encodeDeviceSignalsHeader, enrollPasskey, listPasskeys, mintPasskeyRegisterIntent, renamePasskey, revokePasskey, sendEmailOtp, signInOrigin, signInWithMagicLink, signInWithPasskey, useAuthio, useAuthioRequired, usePasskeys, verifyEmailOtp, verifyLocate, wrapFetchError };