@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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,46 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@useauthio/react` are documented here. This
4
+ project adheres to [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
5
+ and [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [0.2.0] — 2026-06-12
8
+
9
+ ### Changed
10
+ - **Renamed npm package `@authio/react` → `@useauthio/react`.** The
11
+ original `@authio` scope could not be claimed on npm, so every Authio
12
+ SDK now publishes under the organization scope `@useauthio`. Install
13
+ with `npm install @useauthio/react` and update imports accordingly.
14
+ The old `@authio/react` name is retired; releases below this entry were
15
+ published (or prepared) under the old name and are kept for history.
16
+
17
+ ## [0.1.1] — 2026-06-06
18
+
19
+ ### Fixed
20
+ - `signIn()` now redirects to Lobby (`https://lobby.authio.com/`) with
21
+ `redirect_uri` instead of auth-core `/v1/auth/sign-in` with `return_to`.
22
+ - Warn when `projectId` is missing; never append `project_id=undefined`.
23
+
24
+ ## [0.1.0] — 2026-05-22
25
+
26
+ ### Added
27
+ - Initial release of the `@authio/react` SDK for pure-SPA Authio integrations.
28
+ - `<AuthioProvider apiUrl projectId />` context provider with silent-refresh scheduling.
29
+ - `useAuthio()` hook returning `{ user, status, accessToken, getAccessToken, signIn, signOut, refresh }`.
30
+ - `useAuthioRequired({ fallback, redirectTo })` convenience hook.
31
+ - `<SignedIn>` / `<SignedOut>` declarative gates and `<RedirectToSignIn returnTo />` helper.
32
+ - `signInWithMagicLink` and `signInWithPasskey` top-level helpers (not hook-bound) for form handlers.
33
+ - Token storage modes: `memory` (default), `localStorage`, `sessionStorage`, `none`. Refresh tokens are never JS-accessible.
34
+ - JWT signature verification via `@authio/node`'s `JwtVerifier` (EdDSA-pinned, refuses `alg: none`).
35
+ - Optional `onTelemetryEvent` hook for Sentry/Datadog wiring. No phone-home by default.
36
+ - SSR-safe — every hook handles `typeof window === "undefined"`.
37
+ - Dual ESM + CJS build via tsup, full TypeScript declarations, zero runtime deps beyond `@authio/node`.
38
+
39
+ ### Notes
40
+ - `@authio/node` is pulled in via `file:./vendor/authio-node` so local CI
41
+ resolves without requiring the `@authio` npm scope to be claimed.
42
+ When the scope is registered, the dependency will flip to
43
+ `"@authio/node": "^0.1.0"` and the `vendor/` tree will be removed in
44
+ the same release. (Operator follow-up.)
45
+
46
+ [0.1.0]: https://github.com/authio-com/authio_react/releases/tag/v0.1.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Authio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,323 @@
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset=".github/logo-dark.png">
4
+ <img alt="Authio" src=".github/logo-light.png" width="220">
5
+ </picture>
6
+ </p>
7
+
8
+ # @useauthio/react
9
+
10
+ > Part of **[Authio Lobby](https://authio.com/products/lobby)** —
11
+ > Authio's drop-in passwordless authentication. Learn more at
12
+ > https://authio.com/products/lobby.
13
+
14
+ React SDK for Authio — hooks, gates, and sign-in helpers for **pure
15
+ SPAs** that talk directly to auth-core via CORS. If you have a
16
+ Next.js or other BFF, reach for [`@useauthio/nextjs`](https://github.com/authio-com/authio_nextjs)
17
+ instead.
18
+
19
+ ## Recent additions
20
+
21
+ - **`@useauthio/widgets` ships.** Drop-in
22
+ `<AuthioSSOConnectionWidget>` and `<AuthioDirectorySyncWidget>`
23
+ components let your customers' IT admins configure SAML / OIDC and
24
+ SCIM directories from inside your own product. Mint the JWT from
25
+ your BFF; embed the widget anywhere in your `SignedIn` tree. See
26
+ [`authio_widgets`](https://github.com/authio-com/authio_widgets) and
27
+ the docs:
28
+ [`/widgets/overview`](https://docs.authio.com/widgets/overview),
29
+ [`/widgets/tokens`](https://docs.authio.com/widgets/tokens),
30
+ [`/sdks/react`](https://docs.authio.com/sdks/react#embedding-the-authiowidgets-surface).
31
+ - **JWT carries `roles` + `permissions` now.** Every customer-session
32
+ access token in a customer-tenant project ships the new claims
33
+ ([`/concepts/roles-and-permissions`](https://docs.authio.com/concepts/roles-and-permissions)).
34
+ The hooks (`useAuthio`, `useUser`, etc.) keep their existing shape;
35
+ the new claims are exposed on `session.claims` for any code that
36
+ wants to gate UI on roles or permissions.
37
+ - **`kind: "widget"` JWTs are explicitly refused on every customer
38
+ surface.** Embedding the widget bundle alongside `@useauthio/react`
39
+ composes safely; the widget bearer is never confusable with the
40
+ standard customer session JWT.
41
+
42
+ - `<AuthioProvider>` + `useAuthio()` for session state.
43
+ - `<SignedIn>` / `<SignedOut>` / `<RedirectToSignIn>` declarative gates.
44
+ - `signInWithMagicLink()` and `signInWithPasskey()` as top-level
45
+ helpers — call them straight from your form submit handler.
46
+ - Silent refresh with visibility-aware scheduling and exponential
47
+ backoff on failure.
48
+ - JWT signature verification (EdDSA-pinned) via `@useauthio/node`'s
49
+ `JwtVerifier`. Tokens that fail verification are dropped.
50
+ - SSR-safe — every hook handles `typeof window === "undefined"`.
51
+ - Dual ESM + CJS build via tsup; zero runtime deps beyond `@useauthio/node`.
52
+
53
+ ---
54
+
55
+ ## 5-minute integration
56
+
57
+ Install:
58
+
59
+ ```bash
60
+ npm install @useauthio/react
61
+ # or: pnpm add @useauthio/react
62
+ ```
63
+
64
+ Wrap your app once at the root:
65
+
66
+ ```tsx
67
+ // src/main.tsx
68
+ import React from "react";
69
+ import ReactDOM from "react-dom/client";
70
+ import { AuthioProvider } from "@useauthio/react";
71
+ import App from "./App";
72
+
73
+ ReactDOM.createRoot(document.getElementById("root")!).render(
74
+ <AuthioProvider
75
+ apiUrl={import.meta.env.VITE_AUTHIO_API_URL}
76
+ projectId={import.meta.env.VITE_AUTHIO_PROJECT_ID}
77
+ >
78
+ <App />
79
+ </AuthioProvider>,
80
+ );
81
+ ```
82
+
83
+ Drop gates and a magic-link form:
84
+
85
+ ```tsx
86
+ import {
87
+ SignedIn,
88
+ SignedOut,
89
+ signInWithMagicLink,
90
+ useAuthio,
91
+ } from "@useauthio/react";
92
+
93
+ export default function App() {
94
+ const { user, signOut } = useAuthio();
95
+ return (
96
+ <>
97
+ <SignedOut>
98
+ <MagicLinkForm />
99
+ </SignedOut>
100
+ <SignedIn>
101
+ <p>Hello, {user?.email}!</p>
102
+ <button onClick={() => void signOut()}>Sign out</button>
103
+ </SignedIn>
104
+ </>
105
+ );
106
+ }
107
+
108
+ function MagicLinkForm() {
109
+ const [email, setEmail] = React.useState("");
110
+ return (
111
+ <form
112
+ onSubmit={async (e) => {
113
+ e.preventDefault();
114
+ await signInWithMagicLink({
115
+ apiUrl: import.meta.env.VITE_AUTHIO_API_URL,
116
+ projectId: import.meta.env.VITE_AUTHIO_PROJECT_ID,
117
+ email,
118
+ redirectUri: `${window.location.origin}/auth/callback`,
119
+ });
120
+ }}
121
+ >
122
+ <input value={email} onChange={(e) => setEmail(e.target.value)} />
123
+ <button>Send magic link</button>
124
+ </form>
125
+ );
126
+ }
127
+ ```
128
+
129
+ That's it. The provider runs a silent `POST /v1/auth/refresh` against
130
+ your BFF cookie at mount, schedules a renewal one minute before the
131
+ access JWT expires, and verifies every received token against the
132
+ auth-core JWKS before trusting it.
133
+
134
+ A complete runnable example lives in [`examples/vite-react/`](./examples/vite-react/).
135
+
136
+ ---
137
+
138
+ ## API reference
139
+
140
+ ### `<AuthioProvider>`
141
+
142
+ | Prop | Type | Default | Description |
143
+ |------|------|---------|-------------|
144
+ | `apiUrl` | `string` (required) | — | Auth-core base URL, e.g. `"https://auth-api.authio.com"`. |
145
+ | `projectId` | `string` (required) | — | Project ID (`proj_…`). Sent as `X-Authio-Project` on every call. |
146
+ | `storage` | `"memory" \| "localStorage" \| "sessionStorage" \| "none"` | `"memory"` | Access-token storage backend. **Refresh tokens are never JS-accessible** regardless of this setting. |
147
+ | `refreshLeadSeconds` | `number` | `60` | How many seconds before `exp` to schedule the silent refresh. |
148
+ | `onTelemetryEvent` | `(event: AuthioTelemetryEvent) => void` | — | Sink for SDK telemetry (refresh outcomes, sign-in starts/completes, token verification). No phone-home by default. |
149
+ | `fetch` | `typeof fetch` | `globalThis.fetch` | DI for tests / custom transports. |
150
+ | `signInUrl` | `string` | `https://lobby.authio.com/` | Lobby (hosted UI) sign-in URL. |
151
+ | `jwtIssuer` | `string` | `apiUrl` | JWT `iss` claim to require during verification. |
152
+ | `jwtAudience` | `string` | `"authio"` | JWT `aud` claim to require during verification. |
153
+ | `verifyToken` | `AuthioTokenVerifier` | `JwtVerifier`-based | Override the verification step (testing / custom JWKS). |
154
+ | `skipInitialRefresh` | `boolean` | `false` | Skip the bootstrap refresh and start in `unauthenticated`. |
155
+
156
+ ### `useAuthio()`
157
+
158
+ ```ts
159
+ {
160
+ user: AuthioUser | null;
161
+ status: "loading" | "authenticated" | "unauthenticated";
162
+ accessToken: string | null;
163
+ getAccessToken: () => Promise<string | null>;
164
+ signIn: (opts?: { returnTo?: string }) => void;
165
+ signOut: () => Promise<void>;
166
+ refresh: () => Promise<boolean>;
167
+ }
168
+ ```
169
+
170
+ - `getAccessToken()` returns the current token if it's more than 10s
171
+ from `exp`, otherwise transparently triggers a refresh and returns
172
+ the new value (or `null` on failure). Use it as your `Authorization`
173
+ source for outbound API calls.
174
+ - `signIn()` navigates the tab to Lobby (`signInUrl`) with
175
+ `?project_id=…&redirect_uri=…`.
176
+ - `signOut()` best-effort POSTs to `/v1/auth/sign-out`, then clears
177
+ local state regardless of the upstream result.
178
+ - `refresh()` runs one refresh attempt and resolves `true` on success.
179
+
180
+ ### `useAuthioRequired({ fallback, redirectTo })`
181
+
182
+ Convenience hook for "this view requires a session". While the
183
+ provider is loading or the session is unauthenticated, returns
184
+ `fallback` via the `gate` field. When unauthenticated, kicks off a
185
+ redirect to `redirectTo` (or `signIn()` if omitted).
186
+
187
+ ```tsx
188
+ function Dashboard() {
189
+ const { user, gate } = useAuthioRequired({ fallback: <Spinner /> });
190
+ if (gate) return gate;
191
+ return <h1>Hello {user!.email}</h1>;
192
+ }
193
+ ```
194
+
195
+ ### Gates
196
+
197
+ - `<SignedIn>` — renders children only when status is `"authenticated"`.
198
+ - `<SignedOut>` — renders children only when status is `"unauthenticated"`.
199
+ - `<RedirectToSignIn returnTo="/dashboard" />` — declarative; calls
200
+ `signIn({ returnTo })` on mount.
201
+
202
+ All three render `null` while status is `"loading"` so authenticated-only
203
+ UI never flashes during the initial refresh.
204
+
205
+ ### `signInWithMagicLink({ apiUrl, projectId, email, redirectUri, signal?, fetch? })`
206
+
207
+ Top-level helper, **not hook-bound** — drop it directly into your
208
+ form submit handler. POSTs `/v1/auth/magic-link/send`. Throws
209
+ `AuthioError` on any failure so you can render `err.code` /
210
+ `err.message` directly. Returns `void` on success — the magic link is
211
+ now in the user's inbox.
212
+
213
+ ### `signInWithPasskey({ apiUrl, projectId, email?, signal?, fetch? })`
214
+
215
+ Runs the full WebAuthn assertion ceremony against
216
+ `/v1/auth/passkey/login/options` + `/v1/auth/passkey/login/verify`.
217
+ Returns `{ accessToken, refreshToken?, user }`. Throws `AuthioError`
218
+ with codes `not_in_browser`, `webauthn_unsupported`,
219
+ `webauthn_cancelled`, or any auth-core error code on a step failure.
220
+
221
+ The returned `refreshToken` is included for completeness but the SDK
222
+ itself never persists it — auth-core also sets the refresh cookie via
223
+ `Set-Cookie` and that's the canonical home for it.
224
+
225
+ ### `AuthioError`
226
+
227
+ Re-exported from `@useauthio/node`. Thrown by every helper and the
228
+ provider on failure. Shape: `{ code, message, status, requestId? }`.
229
+
230
+ ---
231
+
232
+ ## When to use this vs. `@useauthio/nextjs`
233
+
234
+ | You have… | Use |
235
+ |-----------|-----|
236
+ | A pure SPA (Vite, CRA, Webpack) talking directly to auth-core via CORS | **`@useauthio/react`** (this package) |
237
+ | A Next.js app with a BFF (`/api/auth/*` route handlers) | [`@useauthio/nextjs`](https://github.com/authio-com/authio_nextjs) |
238
+ | A Remix / TanStack Start / Astro app | `@useauthio/react` for the client; your framework's loader/action helpers for the server |
239
+
240
+ The reason for the split: `@useauthio/nextjs` lives in the BFF cookie
241
+ world — it owns `authio_session` + `authio_refresh` HttpOnly cookies
242
+ on **your origin** and the SPA sees only `useUser()`-style hooks
243
+ pointed at `/api/auth/me`. `@useauthio/react` lives in the CORS world —
244
+ your SPA fetches `auth-api.authio.com` directly with
245
+ `credentials: include`, and the refresh cookie is set on the
246
+ auth-core origin. Both end up with the same DX in components, but
247
+ the network shape and the threat surface differ.
248
+
249
+ ---
250
+
251
+ ## CSP guidance
252
+
253
+ The provider issues `fetch` to `apiUrl`. Configure your Content
254
+ Security Policy so the browser allows it:
255
+
256
+ ```http
257
+ Content-Security-Policy:
258
+ default-src 'self';
259
+ connect-src 'self' https://auth-api.authio.com;
260
+ script-src 'self';
261
+ style-src 'self' 'unsafe-inline';
262
+ ```
263
+
264
+ If you've moved auth-core to a custom domain (e.g.
265
+ `auth.acme.com`), allowlist that host instead. The hosted sign-in UI
266
+ itself is reached via a top-level navigation (`window.location.assign`),
267
+ which is not subject to `connect-src`.
268
+
269
+ ---
270
+
271
+ ## Security considerations on token storage
272
+
273
+ | Mode | Where the access token lives | XSS exposure | Persistence |
274
+ |------|------------------------------|--------------|-------------|
275
+ | `"memory"` (default) | A closure inside `<AuthioProvider>` | Same as your app code | Cleared on hard reload |
276
+ | `"sessionStorage"` | `window.sessionStorage` | **Readable by any script on the same origin** | Cleared when tab closes |
277
+ | `"localStorage"` | `window.localStorage` | **Readable by any script on the same origin** | Survives reload |
278
+ | `"none"` | Nowhere — refetched on every page load | None | None |
279
+
280
+ **Default is `"memory"` for a reason**: a single XSS escape gets the
281
+ attacker your access token if it's in `localStorage` / `sessionStorage`.
282
+ The 15-minute access-token TTL caps the blast radius, but a
283
+ sufficiently-clever attacker can chain that into a refresh-rotation.
284
+
285
+ If you need persistence-across-reloads on a SPA (no BFF cookie),
286
+ pick `"sessionStorage"` over `"localStorage"` — the blast radius
287
+ is one tab. If you have a BFF, you don't need either; the `memory`
288
+ mode plus the refresh cookie is enough.
289
+
290
+ **The refresh token is NEVER stored in JS-accessible storage**,
291
+ regardless of which `storage` mode you choose. It rides only the
292
+ HttpOnly cookie that auth-core sets at `/v1/auth/refresh` and
293
+ `/v1/auth/passkey/login/verify`. `getAccessToken()` and the silent
294
+ refresh path both call those endpoints with `credentials: include`
295
+ to pick up the rotated token without ever surfacing the refresh
296
+ token to your code.
297
+
298
+ ---
299
+
300
+ ## CSRF guidance
301
+
302
+ If your SPA is hosted on a different origin than auth-core (e.g.
303
+ `app.acme.com` calling `auth-api.authio.com`):
304
+
305
+ 1. Auth-core's CORS allowlist must include your SPA origin.
306
+ The auth-core operator adds it via the project settings.
307
+ 2. The provider always uses `credentials: include` on
308
+ `/v1/auth/refresh` and `/v1/auth/sign-out`, so the browser sends
309
+ the refresh cookie on those calls.
310
+ 3. Auth-core enforces a SameSite=None refresh cookie when the SPA
311
+ origin differs from the cookie origin, plus the per-project CORS
312
+ origin check — that's the line of defence against CSRF on the
313
+ refresh endpoint itself.
314
+
315
+ If your SPA is hosted on the SAME parent domain as auth-core (e.g.
316
+ both under `*.acme.com`), the refresh cookie is a SameSite=Lax
317
+ first-party cookie and the cross-origin check is implicit.
318
+
319
+ ---
320
+
321
+ ## License
322
+
323
+ MIT — see [LICENSE](./LICENSE).