@useauthio/react 0.2.1 → 0.2.2

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/src/provider.tsx CHANGED
@@ -128,6 +128,15 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
128
128
 
129
129
  const schedulerRef = useRef<RefreshScheduler | null>(null);
130
130
 
131
+ // Optional in-memory refresh token. React's canonical refresh path is the
132
+ // same-origin BFF HttpOnly cookie (performRefresh posts with
133
+ // credentials: "include"). But a pure SPA completing a magic-link/passkey
134
+ // sign-in via handleSignInResult may receive a refresh token directly
135
+ // (e.g. from the callback redirect URL) with no cookie available; we hold
136
+ // it here, memory-only (never web-storage), and send it in the refresh
137
+ // body as a fallback. Mirrors @useauthio/vue's state.ts.
138
+ const refreshTokenRef = useRef<string | null>(null);
139
+
131
140
  const [user, setUser] = useState<AuthioUser | null>(null);
132
141
  const [status, setStatus] = useState<AuthioStatus>(
133
142
  skipInitialRefresh ? "unauthenticated" : "loading",
@@ -148,10 +157,13 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
148
157
  projectId: p.projectId,
149
158
  path: "/v1/auth/refresh",
150
159
  method: "POST",
151
- body: {},
160
+ body: refreshTokenRef.current
161
+ ? { refresh_token: refreshTokenRef.current }
162
+ : {},
152
163
  credentials: "include",
153
164
  fetchImpl: p.fetchImpl,
154
165
  });
166
+ if (env.refresh_token) refreshTokenRef.current = env.refresh_token;
155
167
  const token = env.access_token;
156
168
  if (!token) {
157
169
  p.emit({
@@ -218,6 +230,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
218
230
  run: performRefresh,
219
231
  onGiveUp: () => {
220
232
  storageRef.current!.clear();
233
+ refreshTokenRef.current = null;
221
234
  setAccessToken(null);
222
235
  setUser(null);
223
236
  setStatus("unauthenticated");
@@ -377,6 +390,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
377
390
  // baseline anyway.
378
391
  } finally {
379
392
  storageRef.current!.clear();
393
+ refreshTokenRef.current = null;
380
394
  schedulerRef.current?.clear();
381
395
  setAccessToken(null);
382
396
  setUser(null);
@@ -390,6 +404,58 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
390
404
  [performRefresh],
391
405
  );
392
406
 
407
+ const handleSignInResult = useCallback(
408
+ async (input: {
409
+ accessToken: string;
410
+ refreshToken?: string | null;
411
+ user?: AuthioUser | null;
412
+ }): Promise<void> => {
413
+ const p = propsRef.current;
414
+ const verification = await verifierRef
415
+ .current!(input.accessToken)
416
+ .catch(() => null);
417
+ if (!verification) {
418
+ p.emit({
419
+ kind: "token_rejected",
420
+ timestamp: Date.now(),
421
+ reason: "handoff_verification_failed",
422
+ });
423
+ // Leave the session unauthenticated and surface the rejection so
424
+ // the caller can show an error rather than silently swallowing it.
425
+ storageRef.current!.clear();
426
+ refreshTokenRef.current = null;
427
+ setAccessToken(null);
428
+ setUser(null);
429
+ setStatus("unauthenticated");
430
+ throw new AuthioError({
431
+ code: "token_rejected",
432
+ message: "Authio rejected the handed-off access token signature.",
433
+ status: 0,
434
+ });
435
+ }
436
+ if (input.refreshToken) refreshTokenRef.current = input.refreshToken;
437
+ p.emit({
438
+ kind: "token_verified",
439
+ timestamp: Date.now(),
440
+ subject: verification.subject,
441
+ });
442
+ storageRef.current!.set(input.accessToken);
443
+ setAccessToken(input.accessToken);
444
+ if (input.user) setUser(input.user);
445
+ setStatus("authenticated");
446
+ p.emit({
447
+ kind: "sign_in_completed",
448
+ timestamp: Date.now(),
449
+ method: "magic_link",
450
+ });
451
+ const exp = verification.expiresAt ?? readJwtExp(input.accessToken);
452
+ if (exp !== null && exp !== undefined) {
453
+ schedulerRef.current?.scheduleAt(exp);
454
+ }
455
+ },
456
+ [],
457
+ );
458
+
393
459
  const value = useMemo<AuthioContextValue>(
394
460
  () => ({
395
461
  user,
@@ -399,8 +465,18 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
399
465
  signIn,
400
466
  signOut,
401
467
  refresh,
468
+ handleSignInResult,
402
469
  }),
403
- [user, status, accessToken, getAccessToken, signIn, signOut, refresh],
470
+ [
471
+ user,
472
+ status,
473
+ accessToken,
474
+ getAccessToken,
475
+ signIn,
476
+ signOut,
477
+ refresh,
478
+ handleSignInResult,
479
+ ],
404
480
  );
405
481
 
406
482
  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. */
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;