@useauthio/react 0.2.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.
@@ -0,0 +1,442 @@
1
+ import React, { ReactNode } from 'react';
2
+ import { AuthioError } from '@useauthio/node';
3
+ export { AuthioError } from '@useauthio/node';
4
+
5
+ /**
6
+ * Telemetry event union emitted by `@useauthio/react`. Pass
7
+ * `onTelemetryEvent` to `<AuthioProvider>` to capture these — wire
8
+ * them into Sentry / Datadog / your observability stack of choice.
9
+ *
10
+ * The SDK does not phone home by default. If `onTelemetryEvent` is
11
+ * omitted, every event is dropped.
12
+ *
13
+ * All events carry a millisecond `timestamp` taken from `Date.now()`
14
+ * at emit. Additional fields per kind:
15
+ *
16
+ * - `refresh_succeeded`: a silent refresh against `/v1/auth/refresh`
17
+ * produced a fresh, verified access token.
18
+ * - `refresh_failed`: refresh attempt failed — either the network
19
+ * call rejected, the response was malformed, or token
20
+ * verification rejected the new token. `reason` is human-readable;
21
+ * `status` is the HTTP status (or `undefined` on network errors);
22
+ * `attempt` is the 0-indexed retry count for this scheduled
23
+ * refresh.
24
+ * - `refresh_scheduled`: a future silent refresh has been timer-
25
+ * scheduled. `runAt` is the unix millisecond at which the refresh
26
+ * will fire (subject to the visibilitychange deferral).
27
+ * - `sign_in_started` / `sign_in_completed` / `sign_in_failed`: the
28
+ * three terminal states of a sign-in attempt. `method` says which
29
+ * surface initiated it.
30
+ * - `sign_out`: the user clicked sign-out; emitted after the local
31
+ * cookie + token state has been cleared, regardless of whether
32
+ * the upstream `POST /v1/auth/sign-out` returned 2xx.
33
+ * - `token_verified`: a token passed signature verification. The
34
+ * `subject` is the verified `sub` claim.
35
+ * - `token_rejected`: a token failed verification; the SDK has
36
+ * already discarded it. `reason` is the verifier's error
37
+ * message.
38
+ */
39
+ type AuthioTelemetryEvent = {
40
+ kind: "refresh_succeeded";
41
+ timestamp: number;
42
+ expiresAt?: number;
43
+ } | {
44
+ kind: "refresh_failed";
45
+ timestamp: number;
46
+ reason: string;
47
+ status?: number;
48
+ attempt: number;
49
+ } | {
50
+ kind: "refresh_scheduled";
51
+ timestamp: number;
52
+ runAt: number;
53
+ } | {
54
+ kind: "sign_in_started";
55
+ timestamp: number;
56
+ method: "magic_link" | "passkey" | "redirect";
57
+ } | {
58
+ kind: "sign_in_completed";
59
+ timestamp: number;
60
+ method: "magic_link" | "passkey" | "redirect";
61
+ } | {
62
+ kind: "sign_in_failed";
63
+ timestamp: number;
64
+ method: "magic_link" | "passkey" | "redirect";
65
+ reason: string;
66
+ } | {
67
+ kind: "sign_out";
68
+ timestamp: number;
69
+ } | {
70
+ kind: "token_verified";
71
+ timestamp: number;
72
+ subject: string;
73
+ } | {
74
+ kind: "token_rejected";
75
+ timestamp: number;
76
+ reason: string;
77
+ };
78
+
79
+ /**
80
+ * Minimal user shape consumed by `@useauthio/react`. We deliberately
81
+ * keep this lean so the SPA doesn't need to know about org pivots,
82
+ * memberships, etc. Customers that need richer data fetch
83
+ * `/v1/users/me` (or similar) from their own UI layer using
84
+ * `getAccessToken()`.
85
+ */
86
+ interface AuthioUser {
87
+ id: string;
88
+ email: string;
89
+ emailVerified: boolean;
90
+ name?: string;
91
+ avatarUrl?: string;
92
+ }
93
+ /**
94
+ * The provider walks through three states:
95
+ * - `loading` — initial mount; we're trying to refresh
96
+ * against the BFF cookie before showing UI.
97
+ * - `authenticated` — a verified access token is in memory.
98
+ * - `unauthenticated` — no session; show your sign-in surface.
99
+ */
100
+ type AuthioStatus = "loading" | "authenticated" | "unauthenticated";
101
+ type AuthioStorageMode = "memory" | "localStorage" | "sessionStorage" | "none";
102
+ interface AuthioContextValue {
103
+ user: AuthioUser | null;
104
+ status: AuthioStatus;
105
+ accessToken: string | null;
106
+ /**
107
+ * Returns the current access token, silently refreshing if it's
108
+ * within 10 seconds of expiry. Returns `null` when no session
109
+ * is available (the caller should `signIn()` or show the
110
+ * unauthenticated UI).
111
+ */
112
+ getAccessToken: () => Promise<string | null>;
113
+ /**
114
+ * Navigates the tab to the auth-core hosted sign-in UI. Pass
115
+ * `returnTo` to specify the URL the user lands back on after
116
+ * sign-in completes; defaults to the current `window.location.href`.
117
+ */
118
+ signIn: (opts?: {
119
+ returnTo?: string;
120
+ }) => void;
121
+ /**
122
+ * Best-effort revokes the session against auth-core and clears
123
+ * the local in-memory / web-storage access token.
124
+ */
125
+ signOut: () => Promise<void>;
126
+ /**
127
+ * Forces a refresh now. Resolves `true` on success (state is
128
+ * authenticated), `false` on failure (state is unauthenticated).
129
+ */
130
+ refresh: () => Promise<boolean>;
131
+ }
132
+ /** Result of a single JWT verification attempt. */
133
+ interface AuthioTokenVerification {
134
+ /** The verified token's subject (`sub` claim). */
135
+ subject: string;
136
+ /** Optional expiry (unix seconds) — used to schedule the next refresh. */
137
+ expiresAt?: number;
138
+ }
139
+ type AuthioTokenVerifier = (token: string) => Promise<AuthioTokenVerification | null>;
140
+ interface AuthioProviderProps {
141
+ /** Authio auth-core base URL, e.g. `"https://auth-api.authio.com"`. */
142
+ apiUrl: string;
143
+ /** Project ID (`proj_…`). Sent as `X-Authio-Project` on every call. */
144
+ projectId: string;
145
+ /**
146
+ * Where the access token lives. Defaults to `"memory"`. NEVER stores
147
+ * the refresh token in JS-accessible storage regardless of this
148
+ * setting — the refresh token rides only the BFF cookie. See
149
+ * README §Security considerations for the XSS-tradeoff discussion
150
+ * around `localStorage` and `sessionStorage`.
151
+ */
152
+ storage?: AuthioStorageMode;
153
+ /**
154
+ * How many seconds before `exp` to schedule the silent refresh.
155
+ * Defaults to 60. The refresh fires lazily — if the tab is hidden
156
+ * we defer until `visibilitychange` so we don't waste battery on
157
+ * a background tab.
158
+ */
159
+ refreshLeadSeconds?: number;
160
+ /**
161
+ * Optional sink for SDK telemetry (refresh outcomes, sign-in
162
+ * starts/completes, token verification results). Useful for
163
+ * Sentry / Datadog wiring. The SDK never phones home by default —
164
+ * if you don't pass this, no events are emitted.
165
+ */
166
+ onTelemetryEvent?: (event: AuthioTelemetryEvent) => void;
167
+ /** Inject a custom `fetch` implementation. Defaults to `globalThis.fetch`. */
168
+ fetch?: typeof fetch;
169
+ /**
170
+ * Override the Lobby (hosted UI) sign-in URL. Defaults to
171
+ * `https://lobby.authio.com/`. Customers running a custom Authio
172
+ * domain (e.g. `auth.acme.com`) point this at their hosted UI.
173
+ */
174
+ signInUrl?: string;
175
+ /**
176
+ * JWT issuer to require during verification. Defaults to `apiUrl`.
177
+ * Auth-core mints tokens with `iss` set to its own public origin.
178
+ */
179
+ jwtIssuer?: string;
180
+ /** JWT audience to require. Defaults to `"authio"`. */
181
+ jwtAudience?: string;
182
+ /**
183
+ * Override the JWT verification step. Default uses `JwtVerifier`
184
+ * from `@useauthio/node` (EdDSA-pinned, refuses `alg: none`). Pass a
185
+ * custom verifier for tests or to use a pre-distributed JWKS.
186
+ * Failure (resolved `null` or thrown) discards the token and
187
+ * transitions to `unauthenticated`.
188
+ */
189
+ verifyToken?: AuthioTokenVerifier;
190
+ /**
191
+ * When `true`, skips the initial refresh attempt on mount and
192
+ * starts in the `unauthenticated` state. Useful in tests and in
193
+ * SSR-rendered pages that hydrate without a session.
194
+ */
195
+ skipInitialRefresh?: boolean;
196
+ children: ReactNode;
197
+ }
198
+
199
+ declare const AuthioContext: React.Context<AuthioContextValue | null>;
200
+ /**
201
+ * Top-level context provider. Wrap your app once at the root:
202
+ *
203
+ * ```tsx
204
+ * <AuthioProvider apiUrl="https://auth-api.authio.com" projectId="proj_…">
205
+ * <App />
206
+ * </AuthioProvider>
207
+ * ```
208
+ *
209
+ * Lifecycle:
210
+ *
211
+ * 1. Mount → status `loading`. Issue a `POST /v1/auth/refresh`
212
+ * with `credentials: include`. Auth-core uses the BFF cookie to
213
+ * mint a fresh access token (or 401 if no session).
214
+ * 2. On success: verify the token, stash it per `storage` mode,
215
+ * schedule the next silent refresh `refreshLeadSeconds` before
216
+ * `exp`. Status → `authenticated`.
217
+ * 3. On failure: status → `unauthenticated`. The app shows its
218
+ * sign-in surface; `signIn()` redirects to the hosted UI.
219
+ *
220
+ * The refresh token is NEVER touched from JavaScript — it rides the
221
+ * BFF cookie exclusively. The access token is in-memory by default.
222
+ */
223
+ declare function AuthioProvider(props: AuthioProviderProps): React.ReactElement;
224
+
225
+ /**
226
+ * Throws if called outside `<AuthioProvider>` — the most common
227
+ * mistake people make is dropping a hook into a page that hasn't
228
+ * been wrapped yet.
229
+ *
230
+ * The return shape is stable per render — `getAccessToken`,
231
+ * `signIn`, `signOut`, `refresh` are referentially identical
232
+ * across renders so they're safe in dependency arrays.
233
+ */
234
+ declare function useAuthio(): AuthioContextValue;
235
+ interface UseAuthioRequiredOptions {
236
+ /**
237
+ * Element to render while the provider is still loading the
238
+ * initial session (between mount and the first refresh result).
239
+ * Defaults to `null`.
240
+ */
241
+ fallback?: ReactNode;
242
+ /**
243
+ * Path the SDK should redirect the user to when status resolves
244
+ * to `unauthenticated`. Optional — when omitted we call
245
+ * `signIn()` which targets the auth-core hosted UI.
246
+ */
247
+ redirectTo?: string;
248
+ }
249
+ interface UseAuthioRequiredResult {
250
+ user: AuthioUser | null;
251
+ status: "loading" | "authenticated" | "unauthenticated";
252
+ accessToken: string | null;
253
+ /**
254
+ * Renderable React node — return this directly from your
255
+ * component. While loading or unauthenticated this carries the
256
+ * fallback (or null); once authenticated it returns `null` so
257
+ * the caller continues to render its own protected content.
258
+ *
259
+ * Patterns:
260
+ *
261
+ * ```tsx
262
+ * function Dashboard() {
263
+ * const { user, gate } = useAuthioRequired({ fallback: <Spinner /> });
264
+ * if (gate) return gate;
265
+ * return <h1>Hello {user!.email}</h1>;
266
+ * }
267
+ * ```
268
+ */
269
+ gate: ReactNode | null;
270
+ }
271
+ /**
272
+ * Convenience hook for "this view requires a session". While the
273
+ * provider is loading the initial session it returns `fallback`;
274
+ * when it resolves to unauthenticated it triggers a redirect to
275
+ * `redirectTo` (or the auth-core hosted UI via `signIn()`) and
276
+ * keeps rendering the fallback to bridge the navigation. Once
277
+ * authenticated, `gate` is `null` and the caller renders its
278
+ * protected content.
279
+ *
280
+ * SSR-safe — under SSR `gate` resolves to the fallback so the
281
+ * server render doesn't redirect.
282
+ */
283
+ declare function useAuthioRequired(opts?: UseAuthioRequiredOptions): UseAuthioRequiredResult;
284
+
285
+ interface SignedInProps {
286
+ children: ReactNode;
287
+ }
288
+ /**
289
+ * Renders `children` only when the provider's status is
290
+ * `"authenticated"`. Renders nothing while loading — this matches
291
+ * Clerk's `<SignedIn>` semantics so authenticated-only UI doesn't
292
+ * flash during the initial refresh.
293
+ */
294
+ declare function SignedIn({ children }: SignedInProps): React.ReactElement | null;
295
+ interface SignedOutProps {
296
+ children: ReactNode;
297
+ }
298
+ /**
299
+ * Renders `children` only when the provider's status is
300
+ * `"unauthenticated"`. Renders nothing while loading.
301
+ */
302
+ declare function SignedOut({ children }: SignedOutProps): React.ReactElement | null;
303
+ interface RedirectToSignInProps {
304
+ /**
305
+ * Target URL the user should land on after sign-in completes.
306
+ * Forwarded to Lobby as `?redirect_uri=…`. Defaults to the
307
+ * current `window.location.href`.
308
+ */
309
+ returnTo?: string;
310
+ }
311
+ /**
312
+ * Declarative redirect. Drop into your routing layer to bounce
313
+ * unauthenticated visitors to the hosted UI:
314
+ *
315
+ * ```tsx
316
+ * <SignedOut>
317
+ * <RedirectToSignIn returnTo="/dashboard" />
318
+ * </SignedOut>
319
+ * ```
320
+ *
321
+ * SSR-safe — no-op under server render.
322
+ */
323
+ declare function RedirectToSignIn({ returnTo, }: RedirectToSignInProps): React.ReactElement | null;
324
+
325
+ interface SignInWithMagicLinkOptions {
326
+ /** Authio auth-core base URL. */
327
+ apiUrl: string;
328
+ /** Project ID (`proj_…`). */
329
+ projectId: string;
330
+ /** Email address to send the magic-link to. */
331
+ email: string;
332
+ /**
333
+ * URL on the SPA the magic-link click-through should land on.
334
+ * Auth-core will redirect there with the access token in the URL
335
+ * after the user clicks the link in their inbox.
336
+ */
337
+ redirectUri: string;
338
+ signal?: AbortSignal;
339
+ fetch?: typeof fetch;
340
+ }
341
+ /**
342
+ * POSTs `/v1/auth/magic-link/send`. Top-level helper, intentionally
343
+ * not hook-bound — drop it directly into your form submit handler.
344
+ * Throws `AuthioError` on any failure (rate-limit, bad email,
345
+ * network down, etc.) so the caller can render the auth-core error
346
+ * code verbatim.
347
+ *
348
+ * Returns `void` on success — the link is now in the user's inbox.
349
+ * Show a "Check your email" screen and let the user click through.
350
+ *
351
+ * Example:
352
+ *
353
+ * ```ts
354
+ * try {
355
+ * await signInWithMagicLink({
356
+ * apiUrl: "https://auth-api.authio.com",
357
+ * projectId: "proj_123",
358
+ * email,
359
+ * redirectUri: `${window.location.origin}/auth/callback`,
360
+ * });
361
+ * setMessage("Check your email!");
362
+ * } catch (err) {
363
+ * if (err instanceof AuthioError) setError(err.message);
364
+ * }
365
+ * ```
366
+ */
367
+ declare function signInWithMagicLink(opts: SignInWithMagicLinkOptions): Promise<void>;
368
+ interface SignInWithPasskeyOptions {
369
+ apiUrl: string;
370
+ projectId: string;
371
+ /**
372
+ * Identifier hint for the passkey lookup. Optional — when omitted
373
+ * the user picks their key from the browser's native chooser.
374
+ */
375
+ email?: string;
376
+ signal?: AbortSignal;
377
+ fetch?: typeof fetch;
378
+ }
379
+ interface SignInWithPasskeyResult {
380
+ accessToken: string;
381
+ refreshToken?: string;
382
+ user: AuthioUser;
383
+ }
384
+ /**
385
+ * Runs the full WebAuthn assertion ceremony against auth-core:
386
+ *
387
+ * 1. `POST /v1/auth/passkey/login/options` to receive the
388
+ * `PublicKeyCredentialRequestOptions` shaped for this project.
389
+ * 2. `navigator.credentials.get({ publicKey: options })` to
390
+ * prompt the user for their authenticator (Touch ID, hardware
391
+ * key, platform key, etc.).
392
+ * 3. `POST /v1/auth/passkey/login/verify` with the resulting
393
+ * assertion → returns `{ access_token, refresh_token, user }`.
394
+ *
395
+ * Throws `AuthioError` on any step failure:
396
+ *
397
+ * - `not_in_browser` if `window`/`navigator` is missing (Vite SSR /
398
+ * test environment without jsdom).
399
+ * - `webauthn_unsupported` if `navigator.credentials.get` is
400
+ * missing (legacy browser).
401
+ * - `webauthn_cancelled` if the user dismisses the chooser.
402
+ * - Whatever auth-core returns on the options or verify call.
403
+ *
404
+ * The returned `refreshToken` is included for completeness, but the
405
+ * SDK never persists it — auth-core's `/v1/auth/passkey/login/verify`
406
+ * also sets the refresh cookie via `Set-Cookie`, which is the
407
+ * canonical storage. Callers should typically discard `refreshToken`.
408
+ */
409
+ declare function signInWithPasskey(opts: SignInWithPasskeyOptions): Promise<SignInWithPasskeyResult>;
410
+
411
+ /**
412
+ * Browser helpers for Authio Locate client attestation.
413
+ *
414
+ * Capture device geolocation and pass it to sign-in or standalone verify
415
+ * calls as `client_location`. Requires user consent (browser prompt).
416
+ */
417
+ interface ClientLocationCapture {
418
+ latitude: number;
419
+ longitude: number;
420
+ accuracy_m: number;
421
+ captured_at: string;
422
+ source: "browser_geolocation";
423
+ }
424
+ interface CaptureClientLocationOptions {
425
+ timeoutMs?: number;
426
+ maximumAgeMs?: number;
427
+ enableHighAccuracy?: boolean;
428
+ }
429
+ /**
430
+ * Request the browser's current position. Rejects when geolocation is
431
+ * unavailable, denied, or times out.
432
+ */
433
+ declare function captureClientLocation(opts?: CaptureClientLocationOptions): Promise<ClientLocationCapture>;
434
+
435
+ /**
436
+ * Wrap a native fetch rejection (network error, abort, timeout) in
437
+ * an `AuthioError` so consumers always get a typed `code` to switch
438
+ * on. Already-typed `AuthioError` instances pass through unchanged.
439
+ */
440
+ declare function wrapFetchError(err: unknown, fallbackCode?: string): AuthioError;
441
+
442
+ 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 };