@useauthio/react 0.2.1 → 0.2.3

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 CHANGED
@@ -4,6 +4,46 @@ All notable changes to `@useauthio/react` are documented here. This
4
4
  project adheres to [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
5
5
  and [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.2.3] — 2026-06-17
8
+
9
+ ### Added
10
+ - **Signed lobby context tokens.** `signIn()` now POSTs to
11
+ `/v1/auth/lobby-context` and redirects with a short-lived `?ctx=…`
12
+ param when auth-core supports it, so `project_id` and `redirect_uri`
13
+ are not exposed in the browser URL. Falls back to legacy query params
14
+ when minting fails or auth-core is unavailable.
15
+ - **Environment terminology in docs.** README documents `projectId` as
16
+ the dashboard **environment ID** (`proj_…`; API field `project_id`).
17
+ Env var names (`AUTHIO_PROJECT_ID`, `VITE_AUTHIO_PROJECT_ID`) are
18
+ unchanged for backward compatibility.
19
+
20
+ ### Changed
21
+ - README adds custom-domain guidance: keep the default Lobby URL at
22
+ runtime, override `signInUrl` / `VITE_AUTHIO_SIGN_IN_URL` for branded
23
+ auth hosts; DNS CNAME target is `cname.authiodns.com` (docs-only).
24
+
25
+ ## [0.2.2] — 2026-06-13
26
+
27
+ ### Fixed
28
+ - **Magic-link sign-in now matches auth-core.** `signInWithMagicLink`
29
+ sent the recipient as `email`; auth-core's `POST /v1/auth/magic-link/send`
30
+ reads it as `destination`. Real sends were rejected; they now succeed.
31
+ - **Passkey login now completes.** `signInWithPasskey` posted a flat,
32
+ snake-cased assertion body to `/v1/auth/passkey/login/verify`; auth-core
33
+ expects the standard WebAuthn JSON (camelCase) wrapped under a top-level
34
+ `credential` key and rejects unknown fields. The verify body is now
35
+ `{ credential: { id, rawId, type, response: { clientDataJSON,
36
+ authenticatorData, signature, userHandle } } }`.
37
+
38
+ ### Added
39
+ - **Client-side token-handoff.** `useAuthio()` now exposes
40
+ `handleSignInResult({ accessToken, refreshToken?, user? })`, which
41
+ verifies the access token against the live JWKS, adopts it into provider
42
+ state (`status: authenticated`), and arms the silent-refresh scheduler.
43
+ A pure SPA can now complete a magic-link sign-in by reading
44
+ `?access_token=…` off the callback redirect and handing it to the SDK —
45
+ no same-origin BFF refresh cookie required (parity with `@useauthio/vue`).
46
+
7
47
  ## [0.2.1] — 2026-06-13
8
48
 
9
49
  ### Fixed
package/README.md CHANGED
@@ -133,6 +133,27 @@ auth-core JWKS before trusting it.
133
133
 
134
134
  A complete runnable example lives in [`examples/vite-react/`](./examples/vite-react/).
135
135
 
136
+ ### Custom auth domains
137
+
138
+ The default `signInUrl` is the platform Lobby (`https://lobby.authio.com/`).
139
+ Enterprise customers with a branded auth host point `signInUrl` at that URL
140
+ instead — in Vite apps, typically via `VITE_AUTHIO_SIGN_IN_URL`:
141
+
142
+ ```tsx
143
+ <AuthioProvider
144
+ apiUrl={import.meta.env.VITE_AUTHIO_API_URL}
145
+ projectId={import.meta.env.VITE_AUTHIO_PROJECT_ID}
146
+ signInUrl={
147
+ import.meta.env.VITE_AUTHIO_SIGN_IN_URL ?? "https://lobby.authio.com/"
148
+ }
149
+ />
150
+ ```
151
+
152
+ DNS setup for a vanity hostname (e.g. `auth.acme.com`) is dashboard-side:
153
+ CNAME your auth host to **`cname.authiodns.com`**. The SDK does not reference
154
+ that CNAME at runtime — it only affects where end users sign in when you override
155
+ `signInUrl`. See [Custom domains](https://docs.authio.com/guides/custom-domains).
156
+
136
157
  ---
137
158
 
138
159
  ## API reference
@@ -142,12 +163,12 @@ A complete runnable example lives in [`examples/vite-react/`](./examples/vite-re
142
163
  | Prop | Type | Default | Description |
143
164
  |------|------|---------|-------------|
144
165
  | `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. |
166
+ | `projectId` | `string` (required) | — | Environment ID (`proj_…`; API field `project_id`). Sent as `X-Authio-Project` on every call. |
146
167
  | `storage` | `"memory" \| "localStorage" \| "sessionStorage" \| "none"` | `"memory"` | Access-token storage backend. **Refresh tokens are never JS-accessible** regardless of this setting. |
147
168
  | `refreshLeadSeconds` | `number` | `60` | How many seconds before `exp` to schedule the silent refresh. |
148
169
  | `onTelemetryEvent` | `(event: AuthioTelemetryEvent) => void` | — | Sink for SDK telemetry (refresh outcomes, sign-in starts/completes, token verification). No phone-home by default. |
149
170
  | `fetch` | `typeof fetch` | `globalThis.fetch` | DI for tests / custom transports. |
150
- | `signInUrl` | `string` | `https://lobby.authio.com/` | Lobby (hosted UI) sign-in URL. |
171
+ | `signInUrl` | `string` | `https://lobby.authio.com/` | Lobby (hosted UI) sign-in URL. Set to your branded auth host (e.g. `https://auth.acme.com/`) when using a custom domain — see [Custom auth domains](#custom-auth-domains) below. |
151
172
  | `jwtIssuer` | `string` | `apiUrl` | JWT `iss` claim to require during verification. |
152
173
  | `jwtAudience` | `string` | `"authio"` | JWT `aud` claim to require during verification. |
153
174
  | `verifyToken` | `AuthioTokenVerifier` | `JwtVerifier`-based | Override the verification step (testing / custom JWKS). |
@@ -171,8 +192,10 @@ A complete runnable example lives in [`examples/vite-react/`](./examples/vite-re
171
192
  from `exp`, otherwise transparently triggers a refresh and returns
172
193
  the new value (or `null` on failure). Use it as your `Authorization`
173
194
  source for outbound API calls.
174
- - `signIn()` navigates the tab to Lobby (`signInUrl`) with
175
- `?project_id=…&redirect_uri=…`.
195
+ - `signIn()` navigates the tab to Lobby (`signInUrl`). When auth-core
196
+ supports it, the SDK mints a short-lived `ctx` token so
197
+ `project_id` and `redirect_uri` are not exposed in the URL; it falls
198
+ back to legacy `?project_id=…&redirect_uri=…` query params otherwise.
176
199
  - `signOut()` best-effort POSTs to `/v1/auth/sign-out`, then clears
177
200
  local state regardless of the upstream result.
178
201
  - `refresh()` runs one refresh attempt and resolves `true` on success.
package/dist/index.cjs CHANGED
@@ -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.0";
33
+ var SDK_VERSION = "0.2.2";
34
34
  var SDK_USER_AGENT = `react/${SDK_VERSION}`;
35
35
 
36
36
  // src/fetch.ts
@@ -287,6 +287,49 @@ function createTokenStorage(mode = "memory") {
287
287
  return new MemoryStorage();
288
288
  }
289
289
 
290
+ // src/lobby-context.ts
291
+ async function mintLobbySignInUrl(opts) {
292
+ const target = new URL(opts.hostedUiUrl.replace(/\/$/, "") + "/");
293
+ if (opts.projectId) {
294
+ try {
295
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch.bind(globalThis);
296
+ const res = await fetchImpl(
297
+ `${opts.apiUrl.replace(/\/$/, "")}/v1/auth/lobby-context`,
298
+ {
299
+ method: "POST",
300
+ headers: {
301
+ Accept: "application/json",
302
+ "Content-Type": "application/json",
303
+ "X-Authio-Project": opts.projectId,
304
+ "X-Authio-SDK": SDK_USER_AGENT
305
+ },
306
+ body: JSON.stringify({
307
+ project_id: opts.projectId,
308
+ redirect_uri: opts.redirectUri,
309
+ ...opts.next ? { next: opts.next } : {}
310
+ })
311
+ }
312
+ );
313
+ if (res.ok) {
314
+ const body = await res.json();
315
+ if (typeof body.ctx === "string" && body.ctx.trim()) {
316
+ target.searchParams.set("ctx", body.ctx.trim());
317
+ return target.toString();
318
+ }
319
+ }
320
+ } catch {
321
+ }
322
+ }
323
+ if (opts.projectId) {
324
+ target.searchParams.set("project_id", opts.projectId);
325
+ }
326
+ target.searchParams.set("redirect_uri", opts.redirectUri);
327
+ if (opts.next) {
328
+ target.searchParams.set("next", opts.next);
329
+ }
330
+ return target.toString();
331
+ }
332
+
290
333
  // src/telemetry.ts
291
334
  var noopEmitter = () => {
292
335
  };
@@ -339,6 +382,7 @@ function AuthioProvider(props) {
339
382
  }
340
383
  }, [projectId]);
341
384
  const schedulerRef = react.useRef(null);
385
+ const refreshTokenRef = react.useRef(null);
342
386
  const [user, setUser] = react.useState(null);
343
387
  const [status, setStatus] = react.useState(
344
388
  skipInitialRefresh ? "unauthenticated" : "loading"
@@ -352,10 +396,11 @@ function AuthioProvider(props) {
352
396
  projectId: p.projectId,
353
397
  path: "/v1/auth/refresh",
354
398
  method: "POST",
355
- body: {},
399
+ body: refreshTokenRef.current ? { refresh_token: refreshTokenRef.current } : {},
356
400
  credentials: "include",
357
401
  fetchImpl: p.fetchImpl
358
402
  });
403
+ if (env.refresh_token) refreshTokenRef.current = env.refresh_token;
359
404
  const token = env.access_token;
360
405
  if (!token) {
361
406
  p.emit({
@@ -419,6 +464,7 @@ function AuthioProvider(props) {
419
464
  run: performRefresh,
420
465
  onGiveUp: () => {
421
466
  storageRef.current.clear();
467
+ refreshTokenRef.current = null;
422
468
  setAccessToken(null);
423
469
  setUser(null);
424
470
  setStatus("unauthenticated");
@@ -521,8 +567,8 @@ function AuthioProvider(props) {
521
567
  const ok = await performRefresh();
522
568
  return ok ? storageRef.current.get() : null;
523
569
  }, [accessToken, performRefresh]);
524
- const signIn = react.useCallback(
525
- (opts = {}) => {
570
+ const signIn = react.useCallback((opts = {}) => {
571
+ void (async () => {
526
572
  const p = propsRef.current;
527
573
  p.emit({
528
574
  kind: "sign_in_started",
@@ -535,19 +581,16 @@ function AuthioProvider(props) {
535
581
  '[@useauthio/react] AuthioProvider projectId is missing \u2014 Lobby cannot resolve your project. Set projectId="proj_\u2026" on <AuthioProvider>.'
536
582
  );
537
583
  }
538
- const base = p.signInUrl ?? DEFAULT_SIGN_IN_URL;
539
- const url = new URL(base);
540
- if (p.projectId) {
541
- url.searchParams.set("project_id", p.projectId);
542
- }
543
- url.searchParams.set(
544
- "redirect_uri",
545
- opts.returnTo ?? window.location.href
546
- );
547
- window.location.assign(url.toString());
548
- },
549
- []
550
- );
584
+ const url = await mintLobbySignInUrl({
585
+ apiUrl: p.apiUrl,
586
+ projectId: p.projectId,
587
+ hostedUiUrl: p.signInUrl ?? DEFAULT_SIGN_IN_URL,
588
+ redirectUri: opts.returnTo ?? window.location.href,
589
+ fetchImpl: p.fetchImpl
590
+ });
591
+ window.location.assign(url);
592
+ })();
593
+ }, []);
551
594
  const signOut = react.useCallback(async () => {
552
595
  const p = propsRef.current;
553
596
  const token = storageRef.current.get();
@@ -565,6 +608,7 @@ function AuthioProvider(props) {
565
608
  } catch {
566
609
  } finally {
567
610
  storageRef.current.clear();
611
+ refreshTokenRef.current = null;
568
612
  schedulerRef.current?.clear();
569
613
  setAccessToken(null);
570
614
  setUser(null);
@@ -576,6 +620,49 @@ function AuthioProvider(props) {
576
620
  () => performRefresh(),
577
621
  [performRefresh]
578
622
  );
623
+ const handleSignInResult = react.useCallback(
624
+ async (input) => {
625
+ const p = propsRef.current;
626
+ const verification = await verifierRef.current(input.accessToken).catch(() => null);
627
+ if (!verification) {
628
+ p.emit({
629
+ kind: "token_rejected",
630
+ timestamp: Date.now(),
631
+ reason: "handoff_verification_failed"
632
+ });
633
+ storageRef.current.clear();
634
+ refreshTokenRef.current = null;
635
+ setAccessToken(null);
636
+ setUser(null);
637
+ setStatus("unauthenticated");
638
+ throw new node.AuthioError({
639
+ code: "token_rejected",
640
+ message: "Authio rejected the handed-off access token signature.",
641
+ status: 0
642
+ });
643
+ }
644
+ if (input.refreshToken) refreshTokenRef.current = input.refreshToken;
645
+ p.emit({
646
+ kind: "token_verified",
647
+ timestamp: Date.now(),
648
+ subject: verification.subject
649
+ });
650
+ storageRef.current.set(input.accessToken);
651
+ setAccessToken(input.accessToken);
652
+ if (input.user) setUser(input.user);
653
+ setStatus("authenticated");
654
+ p.emit({
655
+ kind: "sign_in_completed",
656
+ timestamp: Date.now(),
657
+ method: "magic_link"
658
+ });
659
+ const exp = verification.expiresAt ?? readJwtExp(input.accessToken);
660
+ if (exp !== null && exp !== void 0) {
661
+ schedulerRef.current?.scheduleAt(exp);
662
+ }
663
+ },
664
+ []
665
+ );
579
666
  const value = react.useMemo(
580
667
  () => ({
581
668
  user,
@@ -584,9 +671,19 @@ function AuthioProvider(props) {
584
671
  getAccessToken,
585
672
  signIn,
586
673
  signOut,
587
- refresh
674
+ refresh,
675
+ handleSignInResult
588
676
  }),
589
- [user, status, accessToken, getAccessToken, signIn, signOut, refresh]
677
+ [
678
+ user,
679
+ status,
680
+ accessToken,
681
+ getAccessToken,
682
+ signIn,
683
+ signOut,
684
+ refresh,
685
+ handleSignInResult
686
+ ]
590
687
  );
591
688
  return /* @__PURE__ */ jsxRuntime.jsx(AuthioContext.Provider, { value, children });
592
689
  }
@@ -657,7 +754,9 @@ async function signInWithMagicLink(opts) {
657
754
  path: "/v1/auth/magic-link/send",
658
755
  method: "POST",
659
756
  body: {
660
- email: opts.email,
757
+ // auth-core's magic-link send reads the recipient as `destination`
758
+ // (email or E.164), NOT `email`. See magiclink.go magicLinkSendReq.
759
+ destination: opts.email,
661
760
  redirect_uri: opts.redirectUri
662
761
  },
663
762
  signal: opts.signal,
@@ -720,17 +819,17 @@ async function signInWithPasskey(opts) {
720
819
  });
721
820
  }
722
821
  const assertion = credential;
723
- const verifyBody = {
822
+ const webauthnCredential = {
724
823
  id: assertion.id,
725
- raw_id: bufferToBase64Url(assertion.rawId),
824
+ rawId: bufferToBase64Url(assertion.rawId),
726
825
  type: assertion.type,
727
826
  response: {
728
- client_data_json: bufferToBase64Url(assertion.response.clientDataJSON),
729
- authenticator_data: bufferToBase64Url(
827
+ clientDataJSON: bufferToBase64Url(assertion.response.clientDataJSON),
828
+ authenticatorData: bufferToBase64Url(
730
829
  assertion.response.authenticatorData
731
830
  ),
732
831
  signature: bufferToBase64Url(assertion.response.signature),
733
- user_handle: assertion.response.userHandle ? bufferToBase64Url(assertion.response.userHandle) : null
832
+ userHandle: assertion.response.userHandle ? bufferToBase64Url(assertion.response.userHandle) : null
734
833
  }
735
834
  };
736
835
  const verifyRes = await authioFetch({
@@ -738,7 +837,7 @@ async function signInWithPasskey(opts) {
738
837
  projectId: opts.projectId,
739
838
  path: "/v1/auth/passkey/login/verify",
740
839
  method: "POST",
741
- body: verifyBody,
840
+ body: { credential: webauthnCredential },
742
841
  credentials: "include",
743
842
  signal: opts.signal,
744
843
  fetchImpl: opts.fetch