@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.
@@ -0,0 +1,63 @@
1
+ import { SDK_USER_AGENT } from "./version";
2
+
3
+ export interface MintLobbySignInUrlOptions {
4
+ apiUrl: string;
5
+ projectId: string;
6
+ hostedUiUrl: string;
7
+ redirectUri: string;
8
+ /** Post-login path threaded separately from redirect_uri (BFF ?next=). */
9
+ next?: string;
10
+ fetchImpl?: typeof fetch;
11
+ }
12
+
13
+ /**
14
+ * Build a Lobby sign-in URL. Prefers a short-lived signed `?ctx=` token
15
+ * minted by auth-core; falls back to legacy `project_id` / `redirect_uri`
16
+ * query params when minting is unavailable.
17
+ */
18
+ export async function mintLobbySignInUrl(
19
+ opts: MintLobbySignInUrlOptions,
20
+ ): Promise<string> {
21
+ const target = new URL(opts.hostedUiUrl.replace(/\/$/, "") + "/");
22
+
23
+ if (opts.projectId) {
24
+ try {
25
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch.bind(globalThis);
26
+ const res = await fetchImpl(
27
+ `${opts.apiUrl.replace(/\/$/, "")}/v1/auth/lobby-context`,
28
+ {
29
+ method: "POST",
30
+ headers: {
31
+ Accept: "application/json",
32
+ "Content-Type": "application/json",
33
+ "X-Authio-Project": opts.projectId,
34
+ "X-Authio-SDK": SDK_USER_AGENT,
35
+ },
36
+ body: JSON.stringify({
37
+ project_id: opts.projectId,
38
+ redirect_uri: opts.redirectUri,
39
+ ...(opts.next ? { next: opts.next } : {}),
40
+ }),
41
+ },
42
+ );
43
+ if (res.ok) {
44
+ const body = (await res.json()) as { ctx?: unknown };
45
+ if (typeof body.ctx === "string" && body.ctx.trim()) {
46
+ target.searchParams.set("ctx", body.ctx.trim());
47
+ return target.toString();
48
+ }
49
+ }
50
+ } catch {
51
+ // Fall through to legacy query params.
52
+ }
53
+ }
54
+
55
+ if (opts.projectId) {
56
+ target.searchParams.set("project_id", opts.projectId);
57
+ }
58
+ target.searchParams.set("redirect_uri", opts.redirectUri);
59
+ if (opts.next) {
60
+ target.searchParams.set("next", opts.next);
61
+ }
62
+ return target.toString();
63
+ }
package/src/provider.tsx CHANGED
@@ -12,6 +12,7 @@ import { createDefaultVerifier, readJwtExp } from "./jwt";
12
12
  import { RefreshScheduler } from "./refresh";
13
13
  import { isBrowser } from "./ssr";
14
14
  import { createTokenStorage, type TokenStorage } from "./storage";
15
+ import { mintLobbySignInUrl } from "./lobby-context";
15
16
  import { noopEmitter, type TelemetryEmitter } from "./telemetry";
16
17
  import type {
17
18
  AuthioContextValue,
@@ -128,6 +129,15 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
128
129
 
129
130
  const schedulerRef = useRef<RefreshScheduler | null>(null);
130
131
 
132
+ // Optional in-memory refresh token. React's canonical refresh path is the
133
+ // same-origin BFF HttpOnly cookie (performRefresh posts with
134
+ // credentials: "include"). But a pure SPA completing a magic-link/passkey
135
+ // sign-in via handleSignInResult may receive a refresh token directly
136
+ // (e.g. from the callback redirect URL) with no cookie available; we hold
137
+ // it here, memory-only (never web-storage), and send it in the refresh
138
+ // body as a fallback. Mirrors @useauthio/vue's state.ts.
139
+ const refreshTokenRef = useRef<string | null>(null);
140
+
131
141
  const [user, setUser] = useState<AuthioUser | null>(null);
132
142
  const [status, setStatus] = useState<AuthioStatus>(
133
143
  skipInitialRefresh ? "unauthenticated" : "loading",
@@ -148,10 +158,13 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
148
158
  projectId: p.projectId,
149
159
  path: "/v1/auth/refresh",
150
160
  method: "POST",
151
- body: {},
161
+ body: refreshTokenRef.current
162
+ ? { refresh_token: refreshTokenRef.current }
163
+ : {},
152
164
  credentials: "include",
153
165
  fetchImpl: p.fetchImpl,
154
166
  });
167
+ if (env.refresh_token) refreshTokenRef.current = env.refresh_token;
155
168
  const token = env.access_token;
156
169
  if (!token) {
157
170
  p.emit({
@@ -218,6 +231,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
218
231
  run: performRefresh,
219
232
  onGiveUp: () => {
220
233
  storageRef.current!.clear();
234
+ refreshTokenRef.current = null;
221
235
  setAccessToken(null);
222
236
  setUser(null);
223
237
  setStatus("unauthenticated");
@@ -329,8 +343,8 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
329
343
  return ok ? storageRef.current!.get() : null;
330
344
  }, [accessToken, performRefresh]);
331
345
 
332
- const signIn = useCallback(
333
- (opts: { returnTo?: string } = {}) => {
346
+ const signIn = useCallback((opts: { returnTo?: string } = {}) => {
347
+ void (async () => {
334
348
  const p = propsRef.current;
335
349
  p.emit({
336
350
  kind: "sign_in_started",
@@ -343,19 +357,16 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
343
357
  "[@useauthio/react] AuthioProvider projectId is missing — Lobby cannot resolve your project. Set projectId=\"proj_…\" on <AuthioProvider>.",
344
358
  );
345
359
  }
346
- const base = p.signInUrl ?? DEFAULT_SIGN_IN_URL;
347
- const url = new URL(base);
348
- if (p.projectId) {
349
- url.searchParams.set("project_id", p.projectId);
350
- }
351
- url.searchParams.set(
352
- "redirect_uri",
353
- opts.returnTo ?? window.location.href,
354
- );
355
- window.location.assign(url.toString());
356
- },
357
- [],
358
- );
360
+ const url = await mintLobbySignInUrl({
361
+ apiUrl: p.apiUrl,
362
+ projectId: p.projectId,
363
+ hostedUiUrl: p.signInUrl ?? DEFAULT_SIGN_IN_URL,
364
+ redirectUri: opts.returnTo ?? window.location.href,
365
+ fetchImpl: p.fetchImpl,
366
+ });
367
+ window.location.assign(url);
368
+ })();
369
+ }, []);
359
370
 
360
371
  const signOut = useCallback(async (): Promise<void> => {
361
372
  const p = propsRef.current;
@@ -377,6 +388,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
377
388
  // baseline anyway.
378
389
  } finally {
379
390
  storageRef.current!.clear();
391
+ refreshTokenRef.current = null;
380
392
  schedulerRef.current?.clear();
381
393
  setAccessToken(null);
382
394
  setUser(null);
@@ -390,6 +402,58 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
390
402
  [performRefresh],
391
403
  );
392
404
 
405
+ const handleSignInResult = useCallback(
406
+ async (input: {
407
+ accessToken: string;
408
+ refreshToken?: string | null;
409
+ user?: AuthioUser | null;
410
+ }): Promise<void> => {
411
+ const p = propsRef.current;
412
+ const verification = await verifierRef
413
+ .current!(input.accessToken)
414
+ .catch(() => null);
415
+ if (!verification) {
416
+ p.emit({
417
+ kind: "token_rejected",
418
+ timestamp: Date.now(),
419
+ reason: "handoff_verification_failed",
420
+ });
421
+ // Leave the session unauthenticated and surface the rejection so
422
+ // the caller can show an error rather than silently swallowing it.
423
+ storageRef.current!.clear();
424
+ refreshTokenRef.current = null;
425
+ setAccessToken(null);
426
+ setUser(null);
427
+ setStatus("unauthenticated");
428
+ throw new AuthioError({
429
+ code: "token_rejected",
430
+ message: "Authio rejected the handed-off access token signature.",
431
+ status: 0,
432
+ });
433
+ }
434
+ if (input.refreshToken) refreshTokenRef.current = input.refreshToken;
435
+ p.emit({
436
+ kind: "token_verified",
437
+ timestamp: Date.now(),
438
+ subject: verification.subject,
439
+ });
440
+ storageRef.current!.set(input.accessToken);
441
+ setAccessToken(input.accessToken);
442
+ if (input.user) setUser(input.user);
443
+ setStatus("authenticated");
444
+ p.emit({
445
+ kind: "sign_in_completed",
446
+ timestamp: Date.now(),
447
+ method: "magic_link",
448
+ });
449
+ const exp = verification.expiresAt ?? readJwtExp(input.accessToken);
450
+ if (exp !== null && exp !== undefined) {
451
+ schedulerRef.current?.scheduleAt(exp);
452
+ }
453
+ },
454
+ [],
455
+ );
456
+
393
457
  const value = useMemo<AuthioContextValue>(
394
458
  () => ({
395
459
  user,
@@ -399,8 +463,18 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
399
463
  signIn,
400
464
  signOut,
401
465
  refresh,
466
+ handleSignInResult,
402
467
  }),
403
- [user, status, accessToken, getAccessToken, signIn, signOut, refresh],
468
+ [
469
+ user,
470
+ status,
471
+ accessToken,
472
+ getAccessToken,
473
+ signIn,
474
+ signOut,
475
+ refresh,
476
+ handleSignInResult,
477
+ ],
404
478
  );
405
479
 
406
480
  return (
package/src/sign-in.ts CHANGED
@@ -55,7 +55,9 @@ export async function signInWithMagicLink(
55
55
  path: "/v1/auth/magic-link/send",
56
56
  method: "POST",
57
57
  body: {
58
- email: opts.email,
58
+ // auth-core's magic-link send reads the recipient as `destination`
59
+ // (email or E.164), NOT `email`. See magiclink.go magicLinkSendReq.
60
+ destination: opts.email,
59
61
  redirect_uri: opts.redirectUri,
60
62
  },
61
63
  signal: opts.signal,
@@ -200,17 +202,22 @@ export async function signInWithPasskey(
200
202
  const assertion = credential as PublicKeyCredential & {
201
203
  response: AuthenticatorAssertionResponse;
202
204
  };
203
- const verifyBody = {
205
+ // auth-core's passkey login/verify expects the standard WebAuthn JSON
206
+ // (camelCase) wrapped under a top-level `credential` key — it parses
207
+ // req.Credential with go-webauthn's ParseCredentialRequestResponseBody
208
+ // and rejects unknown top-level fields (DisallowUnknownFields). See
209
+ // passkey.go passkeyLoginVerify + the P1 passkey conformance flow.
210
+ const webauthnCredential = {
204
211
  id: assertion.id,
205
- raw_id: bufferToBase64Url(assertion.rawId),
212
+ rawId: bufferToBase64Url(assertion.rawId),
206
213
  type: assertion.type,
207
214
  response: {
208
- client_data_json: bufferToBase64Url(assertion.response.clientDataJSON),
209
- authenticator_data: bufferToBase64Url(
215
+ clientDataJSON: bufferToBase64Url(assertion.response.clientDataJSON),
216
+ authenticatorData: bufferToBase64Url(
210
217
  assertion.response.authenticatorData,
211
218
  ),
212
219
  signature: bufferToBase64Url(assertion.response.signature),
213
- user_handle: assertion.response.userHandle
220
+ userHandle: assertion.response.userHandle
214
221
  ? bufferToBase64Url(assertion.response.userHandle)
215
222
  : null,
216
223
  },
@@ -221,7 +228,7 @@ export async function signInWithPasskey(
221
228
  projectId: opts.projectId,
222
229
  path: "/v1/auth/passkey/login/verify",
223
230
  method: "POST",
224
- body: verifyBody,
231
+ body: { credential: webauthnCredential },
225
232
  credentials: "include",
226
233
  signal: opts.signal,
227
234
  fetchImpl: opts.fetch,
package/src/types.ts CHANGED
@@ -58,6 +58,35 @@ export interface AuthioContextValue {
58
58
  * authenticated), `false` on failure (state is unauthenticated).
59
59
  */
60
60
  refresh: () => Promise<boolean>;
61
+ /**
62
+ * Hand a freshly-obtained `(accessToken, refreshToken?, user?)` triple to
63
+ * the SDK — e.g. after a magic-link callback redirect lands on your SPA
64
+ * with `?access_token=…&refresh_token=…` in the URL, or after
65
+ * `signInWithPasskey()` resolves. Verifies the access token against the
66
+ * live JWKS, adopts it into provider state (status → `authenticated`),
67
+ * persists it per the `storage` mode, and (re-)arms the silent-refresh
68
+ * scheduler.
69
+ *
70
+ * This is the client-side token-handoff a pure SPA needs when it does
71
+ * NOT have a same-origin BFF refresh cookie to bootstrap from. Throws
72
+ * `AuthioError` (code `token_rejected`) when the token fails
73
+ * verification; state is left `unauthenticated`.
74
+ *
75
+ * ```tsx
76
+ * const { handleSignInResult } = useAuthio();
77
+ * // on your /auth/callback page:
78
+ * const p = new URLSearchParams(window.location.search);
79
+ * const accessToken = p.get("access_token");
80
+ * if (accessToken) {
81
+ * await handleSignInResult({ accessToken, refreshToken: p.get("refresh_token") });
82
+ * }
83
+ * ```
84
+ */
85
+ handleSignInResult: (input: {
86
+ accessToken: string;
87
+ refreshToken?: string | null;
88
+ user?: AuthioUser | null;
89
+ }) => Promise<void>;
61
90
  }
62
91
 
63
92
  /** Result of a single JWT verification attempt. */
@@ -75,7 +104,7 @@ export type AuthioTokenVerifier = (
75
104
  export interface AuthioProviderProps {
76
105
  /** Authio auth-core base URL, e.g. `"https://auth-api.authio.com"`. */
77
106
  apiUrl: string;
78
- /** Project ID (`proj_…`). Sent as `X-Authio-Project` on every call. */
107
+ /** Project ID (`proj_…`). Dashboard environment ID; API field `project_id`. Sent as `X-Authio-Project` on every call. */
79
108
  projectId: string;
80
109
  /**
81
110
  * Where the access token lives. Defaults to `"memory"`. NEVER stores
package/src/version.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  /** Published @useauthio/react version — keep in sync with package.json. */
2
- export const SDK_VERSION = "0.2.0";
2
+ export const SDK_VERSION = "0.2.2";
3
3
 
4
4
  export const SDK_USER_AGENT = `react/${SDK_VERSION}` as const;