@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.d.ts 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,65 @@ 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;
164
+ /** Same `apiUrl` passed to `<AuthioProvider>`. */
165
+ apiUrl: string;
166
+ /** Same `projectId` passed to `<AuthioProvider>`. */
167
+ projectId: string;
168
+ /** Resolved hosted sign-in URL (custom domain or Lobby default). */
169
+ signInUrl: string;
170
+ /** Custom fetch from provider props, if any. */
171
+ fetchImpl?: typeof fetch;
106
172
  /**
107
173
  * Returns the current access token, silently refreshing if it's
108
174
  * within 10 seconds of expiry. Returns `null` when no session
@@ -156,6 +222,8 @@ interface AuthioContextValue {
156
222
  accessToken: string;
157
223
  refreshToken?: string | null;
158
224
  user?: AuthioUser | null;
225
+ /** Policy from the sign-in envelope, when the helper surfaced one. */
226
+ sessionPolicy?: SessionPolicy | null;
159
227
  }) => Promise<void>;
160
228
  }
161
229
  /** Result of a single JWT verification attempt. */
@@ -186,6 +254,14 @@ interface AuthioProviderProps {
186
254
  * a background tab.
187
255
  */
188
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;
189
265
  /**
190
266
  * Optional sink for SDK telemetry (refresh outcomes, sign-in
191
267
  * starts/completes, token verification results). Useful for
@@ -351,6 +427,87 @@ interface RedirectToSignInProps {
351
427
  */
352
428
  declare function RedirectToSignIn({ returnTo, }: RedirectToSignInProps): React.ReactElement | null;
353
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
+
354
511
  interface SignInWithMagicLinkOptions {
355
512
  /** Authio auth-core base URL. */
356
513
  apiUrl: string;
@@ -402,12 +559,22 @@ interface SignInWithPasskeyOptions {
402
559
  * the user picks their key from the browser's native chooser.
403
560
  */
404
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;
405
570
  signal?: AbortSignal;
406
571
  fetch?: typeof fetch;
407
572
  }
408
573
  interface SignInWithPasskeyResult {
409
574
  accessToken: string;
410
575
  refreshToken?: string;
576
+ /** Effective session policy from the envelope, `null` on older auth-core. */
577
+ sessionPolicy: SessionPolicy | null;
411
578
  user: AuthioUser;
412
579
  }
413
580
  /**
@@ -436,30 +603,187 @@ interface SignInWithPasskeyResult {
436
603
  * canonical storage. Callers should typically discard `refreshToken`.
437
604
  */
438
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>;
439
677
 
678
+ interface AuthioPasskey {
679
+ id: string;
680
+ nickname: string | null;
681
+ aaguid: string | null;
682
+ authenticator_name: string;
683
+ transports: string[];
684
+ sign_count: number;
685
+ last_used_at: string | null;
686
+ created_at: string;
687
+ }
688
+ /** Shared options for authenticated `/v1/me/passkeys` calls. */
689
+ interface PasskeyApiOptions {
690
+ apiUrl: string;
691
+ projectId: string;
692
+ accessToken: string;
693
+ signal?: AbortSignal;
694
+ fetchImpl?: typeof fetch;
695
+ }
696
+ interface AddPasskeyOptions extends PasskeyApiOptions {
697
+ email: string;
698
+ /**
699
+ * WebAuthn ceremony origin (sent as `X-Authio-Origin`). Defaults to
700
+ * `window.location.origin` in the browser.
701
+ */
702
+ origin?: string;
703
+ }
704
+ interface EnrollPasskeyOptions extends PasskeyApiOptions {
705
+ email: string;
706
+ /** Hosted sign-in UI base URL (lobby / custom domain). */
707
+ signInUrl: string;
708
+ /** Where to return after enrollment (`redirect_uri` query param). */
709
+ returnUrl?: string;
710
+ /** Post-login path on the return host (`next` query param). */
711
+ next?: string;
712
+ }
713
+ interface BuildEnrollPasskeyUrlOptions {
714
+ signInUrl: string;
715
+ projectId: string;
716
+ email: string;
717
+ registerToken: string;
718
+ redirectUri?: string;
719
+ next?: string;
720
+ }
721
+ /** Normalize a hosted-UI base URL (no trailing slash). */
722
+ declare function signInOrigin(signInUrl: string): string;
440
723
  /**
441
- * Browser helpers for Authio Locate client attestation.
724
+ * True when inline WebAuthn registration can run on the current page
725
+ * (same origin as the hosted sign-in UI / custom auth domain).
726
+ */
727
+ declare function canEnrollPasskeyEmbedded(signInUrl: string): boolean;
728
+ /** Build the hosted-UI URL for `mode=add_credential` passkey enrollment. */
729
+ declare function buildEnrollPasskeyUrl(opts: BuildEnrollPasskeyUrlOptions): string;
730
+ /** Mint a short-lived JWT for add-credential WebAuthn (`register-intent`). */
731
+ declare function mintPasskeyRegisterIntent(opts: PasskeyApiOptions): Promise<{
732
+ token: string;
733
+ expiresIn: number;
734
+ }>;
735
+ /**
736
+ * Enroll a passkey by redirecting to the hosted sign-in UI on the
737
+ * sign-in origin (`mode=add_credential`). Use when the SPA origin
738
+ * differs from the WebAuthn RP ID.
739
+ */
740
+ declare function enrollPasskey(opts: EnrollPasskeyOptions): Promise<void>;
741
+ /**
742
+ * Enroll a passkey inline on the current origin via WebAuthn.
442
743
  *
443
- * Capture device geolocation and pass it to sign-in or standalone verify
444
- * calls as `client_location`. Requires user consent (browser prompt).
744
+ * 1. `POST /v1/me/passkeys/register-intent`
745
+ * 2. `POST /v1/auth/passkey/register/options` + ceremony
746
+ * 3. `POST /v1/auth/passkey/register/verify`
445
747
  */
446
- interface ClientLocationCapture {
447
- latitude: number;
448
- longitude: number;
449
- accuracy_m: number;
450
- captured_at: string;
451
- source: "browser_geolocation";
748
+ declare function addPasskey(opts: AddPasskeyOptions): Promise<void>;
749
+ /** List passkeys for the signed-in user (`GET /v1/me/passkeys`). */
750
+ declare function listPasskeys(opts: PasskeyApiOptions): Promise<AuthioPasskey[]>;
751
+ /** Rename a passkey (`PATCH /v1/me/passkeys/{credentialId}`). */
752
+ declare function renamePasskey(opts: PasskeyApiOptions, credentialId: string, name: string): Promise<void>;
753
+ /** Revoke a passkey (`DELETE /v1/me/passkeys/{credentialId}`). */
754
+ declare function revokePasskey(opts: PasskeyApiOptions, credentialId: string): Promise<void>;
755
+
756
+ interface UsePasskeysResult {
757
+ passkeys: AuthioPasskey[];
758
+ loading: boolean;
759
+ error: string | null;
760
+ refresh: () => Promise<void>;
761
+ rename: (credentialId: string, nickname: string) => Promise<void>;
762
+ revoke: (credentialId: string) => Promise<void>;
763
+ enroll: (opts?: {
764
+ returnUrl?: string;
765
+ next?: string;
766
+ }) => Promise<void>;
452
767
  }
453
- interface CaptureClientLocationOptions {
454
- timeoutMs?: number;
455
- maximumAgeMs?: number;
456
- enableHighAccuracy?: boolean;
768
+ /**
769
+ * Load and mutate the signed-in user's passkeys via `/v1/me/passkeys`.
770
+ * Requires `<AuthioProvider>` with a live session.
771
+ */
772
+ declare function usePasskeys(): UsePasskeysResult;
773
+
774
+ interface PasskeyManagerProps {
775
+ className?: string;
776
+ /** Passed to {@link enrollPasskey} as `returnUrl`. */
777
+ enrollReturnUrl?: string;
778
+ enrollNext?: string;
457
779
  }
458
780
  /**
459
- * Request the browser's current position. Rejects when geolocation is
460
- * unavailable, denied, or times out.
781
+ * Drop-in passkey device list for customer apps. Lists, renames, and
782
+ * revokes via `/v1/me/passkeys`; "Add passkey" redirects to the hosted
783
+ * sign-in UI (`mode=add_credential`) so the WebAuthn ceremony runs on
784
+ * the sign-in origin.
461
785
  */
462
- declare function captureClientLocation(opts?: CaptureClientLocationOptions): Promise<ClientLocationCapture>;
786
+ declare function PasskeyManager({ className, enrollReturnUrl, enrollNext, }: PasskeyManagerProps): React.ReactElement;
463
787
 
464
788
  /**
465
789
  * Wrap a native fetch rejection (network error, abort, timeout) in
@@ -468,4 +792,38 @@ declare function captureClientLocation(opts?: CaptureClientLocationOptions): Pro
468
792
  */
469
793
  declare function wrapFetchError(err: unknown, fallbackCode?: string): AuthioError;
470
794
 
471
- export { AuthioContext, type AuthioContextValue, AuthioProvider, type AuthioProviderProps, type AuthioStatus, type AuthioStorageMode, type AuthioTelemetryEvent, type AuthioTokenVerification, type AuthioTokenVerifier, type AuthioUser, type CaptureClientLocationOptions, type ClientLocationCapture, RedirectToSignIn, type RedirectToSignInProps, type SignInWithMagicLinkOptions, type SignInWithPasskeyOptions, type SignInWithPasskeyResult, SignedIn, type SignedInProps, SignedOut, type SignedOutProps, type UseAuthioRequiredOptions, type UseAuthioRequiredResult, captureClientLocation, signInWithMagicLink, signInWithPasskey, useAuthio, useAuthioRequired, 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 };