@robelest/convex-auth 0.0.2 → 0.0.3-preview.1

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.
Files changed (173) hide show
  1. package/dist/bin.cjs +1 -1
  2. package/dist/client/index.d.ts +33 -9
  3. package/dist/client/index.d.ts.map +1 -1
  4. package/dist/client/index.js +79 -13
  5. package/dist/client/index.js.map +1 -1
  6. package/dist/component/_generated/component.d.ts +48 -0
  7. package/dist/component/_generated/component.d.ts.map +1 -1
  8. package/dist/component/index.d.ts +10 -4
  9. package/dist/component/index.d.ts.map +1 -1
  10. package/dist/component/index.js +8 -3
  11. package/dist/component/index.js.map +1 -1
  12. package/dist/component/public.d.ts +163 -3
  13. package/dist/component/public.d.ts.map +1 -1
  14. package/dist/component/public.js +124 -0
  15. package/dist/component/public.js.map +1 -1
  16. package/dist/component/schema.d.ts +81 -2
  17. package/dist/component/schema.d.ts.map +1 -1
  18. package/dist/component/schema.js +45 -0
  19. package/dist/component/schema.js.map +1 -1
  20. package/dist/providers/anonymous.d.ts +3 -0
  21. package/dist/providers/anonymous.d.ts.map +1 -1
  22. package/dist/providers/anonymous.js +3 -0
  23. package/dist/providers/anonymous.js.map +1 -1
  24. package/dist/providers/credentials.d.ts +3 -0
  25. package/dist/providers/credentials.d.ts.map +1 -1
  26. package/dist/providers/credentials.js +3 -0
  27. package/dist/providers/credentials.js.map +1 -1
  28. package/dist/providers/email.d.ts +3 -0
  29. package/dist/providers/email.d.ts.map +1 -1
  30. package/dist/providers/email.js +3 -0
  31. package/dist/providers/email.js.map +1 -1
  32. package/dist/providers/passkey.d.ts +7 -1
  33. package/dist/providers/passkey.d.ts.map +1 -1
  34. package/dist/providers/passkey.js +7 -1
  35. package/dist/providers/passkey.js.map +1 -1
  36. package/dist/providers/password.d.ts +3 -0
  37. package/dist/providers/password.d.ts.map +1 -1
  38. package/dist/providers/password.js +3 -0
  39. package/dist/providers/password.js.map +1 -1
  40. package/dist/providers/phone.d.ts +3 -0
  41. package/dist/providers/phone.d.ts.map +1 -1
  42. package/dist/providers/phone.js +3 -0
  43. package/dist/providers/phone.js.map +1 -1
  44. package/dist/providers/totp.d.ts +8 -0
  45. package/dist/providers/totp.d.ts.map +1 -1
  46. package/dist/providers/totp.js +8 -0
  47. package/dist/providers/totp.js.map +1 -1
  48. package/dist/server/convex-auth.d.ts +185 -25
  49. package/dist/server/convex-auth.d.ts.map +1 -1
  50. package/dist/server/convex-auth.js +317 -58
  51. package/dist/server/convex-auth.js.map +1 -1
  52. package/dist/server/email-templates.d.ts +18 -0
  53. package/dist/server/email-templates.d.ts.map +1 -0
  54. package/dist/server/email-templates.js +74 -0
  55. package/dist/server/email-templates.js.map +1 -0
  56. package/dist/server/errors.d.ts +146 -0
  57. package/dist/server/errors.d.ts.map +1 -0
  58. package/dist/server/errors.js +176 -0
  59. package/dist/server/errors.js.map +1 -0
  60. package/dist/server/implementation/apiKey.d.ts +74 -0
  61. package/dist/server/implementation/apiKey.d.ts.map +1 -0
  62. package/dist/server/implementation/apiKey.js +139 -0
  63. package/dist/server/implementation/apiKey.js.map +1 -0
  64. package/dist/server/implementation/index.d.ts +151 -14
  65. package/dist/server/implementation/index.d.ts.map +1 -1
  66. package/dist/server/implementation/index.js +216 -24
  67. package/dist/server/implementation/index.js.map +1 -1
  68. package/dist/server/implementation/mutations/createAccountFromCredentials.d.ts.map +1 -1
  69. package/dist/server/implementation/mutations/createAccountFromCredentials.js +2 -1
  70. package/dist/server/implementation/mutations/createAccountFromCredentials.js.map +1 -1
  71. package/dist/server/implementation/mutations/createVerificationCode.d.ts +2 -2
  72. package/dist/server/implementation/mutations/index.d.ts +6 -6
  73. package/dist/server/implementation/mutations/modifyAccount.d.ts.map +1 -1
  74. package/dist/server/implementation/mutations/modifyAccount.js +2 -1
  75. package/dist/server/implementation/mutations/modifyAccount.js.map +1 -1
  76. package/dist/server/implementation/mutations/userOAuth.d.ts.map +1 -1
  77. package/dist/server/implementation/mutations/userOAuth.js +2 -1
  78. package/dist/server/implementation/mutations/userOAuth.js.map +1 -1
  79. package/dist/server/implementation/mutations/verifierSignature.d.ts.map +1 -1
  80. package/dist/server/implementation/mutations/verifierSignature.js +2 -1
  81. package/dist/server/implementation/mutations/verifierSignature.js.map +1 -1
  82. package/dist/server/implementation/passkey.d.ts.map +1 -1
  83. package/dist/server/implementation/passkey.js +28 -29
  84. package/dist/server/implementation/passkey.js.map +1 -1
  85. package/dist/server/implementation/provider.d.ts.map +1 -1
  86. package/dist/server/implementation/provider.js +5 -4
  87. package/dist/server/implementation/provider.js.map +1 -1
  88. package/dist/server/implementation/redirects.d.ts.map +1 -1
  89. package/dist/server/implementation/redirects.js +2 -1
  90. package/dist/server/implementation/redirects.js.map +1 -1
  91. package/dist/server/implementation/refreshTokens.d.ts.map +1 -1
  92. package/dist/server/implementation/refreshTokens.js +2 -1
  93. package/dist/server/implementation/refreshTokens.js.map +1 -1
  94. package/dist/server/implementation/signIn.d.ts.map +1 -1
  95. package/dist/server/implementation/signIn.js +8 -18
  96. package/dist/server/implementation/signIn.js.map +1 -1
  97. package/dist/server/implementation/totp.d.ts.map +1 -1
  98. package/dist/server/implementation/totp.js +16 -17
  99. package/dist/server/implementation/totp.js.map +1 -1
  100. package/dist/server/implementation/users.d.ts.map +1 -1
  101. package/dist/server/implementation/users.js +3 -2
  102. package/dist/server/implementation/users.js.map +1 -1
  103. package/dist/server/index.d.ts +157 -3
  104. package/dist/server/index.d.ts.map +1 -1
  105. package/dist/server/index.js +180 -17
  106. package/dist/server/index.js.map +1 -1
  107. package/dist/server/oauth/authorizationUrl.d.ts.map +1 -1
  108. package/dist/server/oauth/authorizationUrl.js +2 -1
  109. package/dist/server/oauth/authorizationUrl.js.map +1 -1
  110. package/dist/server/oauth/callback.d.ts.map +1 -1
  111. package/dist/server/oauth/callback.js +5 -4
  112. package/dist/server/oauth/callback.js.map +1 -1
  113. package/dist/server/oauth/checks.d.ts.map +1 -1
  114. package/dist/server/oauth/checks.js +2 -1
  115. package/dist/server/oauth/checks.js.map +1 -1
  116. package/dist/server/oauth/convexAuth.d.ts.map +1 -1
  117. package/dist/server/oauth/convexAuth.js +3 -2
  118. package/dist/server/oauth/convexAuth.js.map +1 -1
  119. package/dist/server/provider_utils.d.ts +2 -0
  120. package/dist/server/provider_utils.d.ts.map +1 -1
  121. package/dist/server/types.d.ts +240 -5
  122. package/dist/server/types.d.ts.map +1 -1
  123. package/dist/server/utils.d.ts.map +1 -1
  124. package/dist/server/utils.js +2 -1
  125. package/dist/server/utils.js.map +1 -1
  126. package/dist/server/version.d.ts +2 -0
  127. package/dist/server/version.d.ts.map +1 -0
  128. package/dist/server/version.js +3 -0
  129. package/dist/server/version.js.map +1 -0
  130. package/package.json +7 -2
  131. package/src/cli/index.ts +1 -1
  132. package/src/cli/utils.ts +248 -0
  133. package/src/client/index.ts +105 -15
  134. package/src/component/_generated/component.ts +61 -0
  135. package/src/component/index.ts +11 -2
  136. package/src/component/public.ts +142 -0
  137. package/src/component/schema.ts +52 -0
  138. package/src/providers/anonymous.ts +3 -0
  139. package/src/providers/credentials.ts +3 -0
  140. package/src/providers/email.ts +3 -0
  141. package/src/providers/passkey.ts +8 -1
  142. package/src/providers/password.ts +3 -0
  143. package/src/providers/phone.ts +3 -0
  144. package/src/providers/totp.ts +9 -0
  145. package/src/server/convex-auth.ts +385 -73
  146. package/src/server/email-templates.ts +77 -0
  147. package/src/server/errors.ts +269 -0
  148. package/src/server/implementation/apiKey.ts +186 -0
  149. package/src/server/implementation/index.ts +288 -28
  150. package/src/server/implementation/mutations/createAccountFromCredentials.ts +2 -1
  151. package/src/server/implementation/mutations/modifyAccount.ts +2 -3
  152. package/src/server/implementation/mutations/userOAuth.ts +2 -1
  153. package/src/server/implementation/mutations/verifierSignature.ts +2 -1
  154. package/src/server/implementation/passkey.ts +33 -35
  155. package/src/server/implementation/provider.ts +5 -8
  156. package/src/server/implementation/redirects.ts +2 -3
  157. package/src/server/implementation/refreshTokens.ts +2 -1
  158. package/src/server/implementation/signIn.ts +9 -18
  159. package/src/server/implementation/totp.ts +18 -21
  160. package/src/server/implementation/users.ts +4 -7
  161. package/src/server/index.ts +240 -37
  162. package/src/server/oauth/authorizationUrl.ts +2 -1
  163. package/src/server/oauth/callback.ts +5 -4
  164. package/src/server/oauth/checks.ts +3 -1
  165. package/src/server/oauth/convexAuth.ts +6 -3
  166. package/src/server/types.ts +254 -5
  167. package/src/server/utils.ts +3 -1
  168. package/src/server/version.ts +2 -0
  169. package/dist/server/portal.d.ts +0 -116
  170. package/dist/server/portal.d.ts.map +0 -1
  171. package/dist/server/portal.js +0 -294
  172. package/dist/server/portal.js.map +0 -1
  173. package/src/server/portal.ts +0 -375
@@ -1,4 +1,5 @@
1
1
  import { ConvexHttpClient } from "convex/browser";
2
+ import { ConvexError } from "convex/values";
2
3
  import { jwtDecode } from "jwt-decode";
3
4
  import { parse, serialize } from "cookie";
4
5
  import type {
@@ -7,30 +8,79 @@ import type {
7
8
  } from "./implementation/index.js";
8
9
  import { isLocalHost } from "./utils.js";
9
10
 
11
+ /** Cookie lifetime configuration for auth tokens. */
10
12
  export type AuthCookieConfig = {
13
+ /** Maximum age in seconds, or `null` for session cookies. */
11
14
  maxAge: number | null;
12
15
  };
13
16
 
17
+ /** Raw cookie values extracted from a request. */
14
18
  export type AuthCookies = {
19
+ /** The JWT access token, or `null` when absent. */
15
20
  token: string | null;
21
+ /** The refresh token, or `null` when absent. */
16
22
  refreshToken: string | null;
23
+ /** The OAuth PKCE verifier, or `null` when absent. */
17
24
  verifier: string | null;
18
25
  };
19
26
 
27
+ /** A structured cookie ready to be set via any framework's cookie API. */
28
+ export type AuthCookie = {
29
+ name: string;
30
+ value: string;
31
+ options: {
32
+ path: string;
33
+ httpOnly: boolean;
34
+ secure: boolean;
35
+ sameSite: "lax" | "strict" | "none";
36
+ maxAge?: number;
37
+ expires?: Date;
38
+ };
39
+ };
40
+
41
+ /**
42
+ * Options for the SSR auth helper returned by {@link server}.
43
+ */
20
44
  export type ServerOptions = {
21
- /** Convex deployment URL. */
45
+ /** Convex deployment URL (e.g. `https://your-app.convex.cloud`). */
22
46
  url: string;
47
+ /**
48
+ * Path the client POSTs auth actions to. Defaults to `"/api/auth"`.
49
+ * Must match the `proxy` option on the client.
50
+ */
23
51
  apiRoute?: string;
52
+ /** Cookie `maxAge` in seconds, or `null` for session cookies. */
24
53
  cookieMaxAge?: number | null;
54
+ /** Enable verbose debug logging for token refresh and cookie operations. */
25
55
  verbose?: boolean;
56
+ /**
57
+ * Control whether `refresh()` handles OAuth `?code=` query parameters.
58
+ *
59
+ * - `true` (default): always exchange the code on GET requests with `text/html` accept.
60
+ * - `false`: never exchange — useful when only the client handles codes.
61
+ * - A function: called with the `Request` for per-request decisions.
62
+ */
26
63
  shouldHandleCode?: ((request: Request) => boolean | Promise<boolean>) | boolean;
27
64
  };
28
65
 
29
66
  export type RefreshResult = {
30
- response?: Response;
31
- cookies?: string[];
67
+ /** Structured cookies to set on the response. */
68
+ cookies: AuthCookie[];
69
+ /** URL to redirect to (set after OAuth code exchange). */
70
+ redirect?: string;
71
+ /** JWT for SSR hydration, or `null` if not authenticated. */
72
+ token: string | null;
32
73
  };
33
74
 
75
+ /**
76
+ * Derive the cookie names used for auth tokens.
77
+ *
78
+ * On localhost the names are unprefixed; on production hosts they
79
+ * use the `__Host-` prefix for tighter security.
80
+ *
81
+ * @param host - The `Host` header value. Omit to use unprefixed names.
82
+ * @returns An object with `token`, `refreshToken`, and `verifier` cookie names.
83
+ */
34
84
  export function authCookieNames(host?: string) {
35
85
  const prefix = isLocalHost(host) ? "" : "__Host-";
36
86
  return {
@@ -40,6 +90,13 @@ export function authCookieNames(host?: string) {
40
90
  };
41
91
  }
42
92
 
93
+ /**
94
+ * Parse auth cookie values from a raw `Cookie` header string.
95
+ *
96
+ * @param cookieHeader - The raw `Cookie` header, or `null`/`undefined`.
97
+ * @param host - The `Host` header, used to determine cookie name prefixes.
98
+ * @returns Parsed {@link AuthCookies} with `token`, `refreshToken`, and `verifier`.
99
+ */
43
100
  export function parseAuthCookies(
44
101
  cookieHeader: string | null | undefined,
45
102
  host?: string,
@@ -53,6 +110,16 @@ export function parseAuthCookies(
53
110
  };
54
111
  }
55
112
 
113
+ /**
114
+ * Serialize auth cookies into `Set-Cookie` header strings.
115
+ *
116
+ * Nulled-out values produce deletion cookies (maxAge 0, expired date).
117
+ *
118
+ * @param cookies - The auth cookie values to serialize.
119
+ * @param host - The `Host` header, used for cookie name prefixes and `Secure` flag.
120
+ * @param config - Cookie lifetime config. Defaults to session cookies.
121
+ * @returns An array of three `Set-Cookie` header strings.
122
+ */
56
123
  export function serializeAuthCookies(
57
124
  cookies: AuthCookies,
58
125
  host?: string,
@@ -86,6 +153,67 @@ export function serializeAuthCookies(
86
153
  ];
87
154
  }
88
155
 
156
+ /**
157
+ * Build structured cookie objects for any SSR framework.
158
+ *
159
+ * Use with SvelteKit's `event.cookies.set()`, TanStack Start's `setCookie()`,
160
+ * Next.js's `cookies().set()`, or any other framework cookie API.
161
+ */
162
+ export function structuredAuthCookies(
163
+ cookies: AuthCookies,
164
+ host?: string,
165
+ config: AuthCookieConfig = { maxAge: null },
166
+ ): AuthCookie[] {
167
+ const names = authCookieNames(host);
168
+ const secure = !isLocalHost(host);
169
+ const base = {
170
+ path: "/" as const,
171
+ httpOnly: true as const,
172
+ secure,
173
+ sameSite: "lax" as const,
174
+ };
175
+ const maxAge = config.maxAge ?? undefined;
176
+ return [
177
+ {
178
+ name: names.token,
179
+ value: cookies.token ?? "",
180
+ options: {
181
+ ...base,
182
+ maxAge: cookies.token === null ? 0 : maxAge,
183
+ expires: cookies.token === null ? new Date(0) : undefined,
184
+ },
185
+ },
186
+ {
187
+ name: names.refreshToken,
188
+ value: cookies.refreshToken ?? "",
189
+ options: {
190
+ ...base,
191
+ maxAge: cookies.refreshToken === null ? 0 : maxAge,
192
+ expires: cookies.refreshToken === null ? new Date(0) : undefined,
193
+ },
194
+ },
195
+ {
196
+ name: names.verifier,
197
+ value: cookies.verifier ?? "",
198
+ options: {
199
+ ...base,
200
+ maxAge: cookies.verifier === null ? 0 : maxAge,
201
+ expires: cookies.verifier === null ? new Date(0) : undefined,
202
+ },
203
+ },
204
+ ];
205
+ }
206
+
207
+ /**
208
+ * Check whether a request pathname matches the auth proxy route.
209
+ *
210
+ * Handles trailing-slash ambiguity: both `/api/auth` and `/api/auth/`
211
+ * match regardless of how `apiRoute` is configured.
212
+ *
213
+ * @param pathname - The request URL pathname.
214
+ * @param apiRoute - The configured proxy route (e.g. `"/api/auth"`).
215
+ * @returns `true` when the pathname matches the proxy route.
216
+ */
89
217
  export function shouldProxyAuthAction(pathname: string, apiRoute: string) {
90
218
  if (apiRoute.endsWith("/")) {
91
219
  return pathname === apiRoute || pathname === apiRoute.slice(0, -1);
@@ -98,6 +226,39 @@ const MINIMUM_REQUIRED_TOKEN_LIFETIME_MS = 10_000;
98
226
 
99
227
  type DecodedToken = { exp?: number; iat?: number };
100
228
 
229
+ /**
230
+ * Create an SSR auth helper for server-side frameworks.
231
+ *
232
+ * Handles cookie-based token management, OAuth code exchange,
233
+ * and automatic JWT refresh on page loads. Works with any
234
+ * framework that gives you a `Request` object — SvelteKit,
235
+ * TanStack Start, Remix, Next.js, etc.
236
+ *
237
+ * @param options - SSR configuration (Convex URL, proxy route, cookie lifetime).
238
+ * @returns An object with `token`, `verify`, `proxy`, and `refresh` methods.
239
+ *
240
+ * @example SvelteKit hooks
241
+ * ```ts
242
+ * // src/hooks.server.ts
243
+ * import { server } from '@robelest/convex-auth/server';
244
+ *
245
+ * const auth = server({ url: CONVEX_URL });
246
+ *
247
+ * export const handle = async ({ event, resolve }) => {
248
+ * const { cookies, token } = await auth.refresh(event.request);
249
+ * for (const c of cookies) event.cookies.set(c.name, c.value, c.options);
250
+ * event.locals.token = token;
251
+ * return resolve(event);
252
+ * };
253
+ * ```
254
+ *
255
+ * @example Generic proxy endpoint
256
+ * ```ts
257
+ * if (shouldProxyAuthAction(url.pathname, '/api/auth')) {
258
+ * return auth.proxy(request);
259
+ * }
260
+ * ```
261
+ */
101
262
  export function server(options: ServerOptions) {
102
263
  const convexUrl = options.url;
103
264
  const apiRoute = options.apiRoute ?? "/api/auth";
@@ -216,10 +377,25 @@ export function server(options: ServerOptions) {
216
377
  };
217
378
 
218
379
  return {
380
+ /**
381
+ * Read the JWT from the request cookies without any validation.
382
+ *
383
+ * @param request - The incoming HTTP request.
384
+ * @returns The raw JWT string, or `null` when no token cookie exists.
385
+ */
219
386
  token(request: Request): string | null {
220
387
  return parseRequestCookies(request).token;
221
388
  },
222
389
 
390
+ /**
391
+ * Check whether the request carries a non-expired JWT.
392
+ *
393
+ * Performs local expiration checking only (no network call).
394
+ * Use for lightweight auth guards in middleware.
395
+ *
396
+ * @param request - The incoming HTTP request.
397
+ * @returns `true` when a valid, non-expired JWT exists in the cookies.
398
+ */
223
399
  async verify(request: Request): Promise<boolean> {
224
400
  const token = parseRequestCookies(request).token;
225
401
  if (token === null) {
@@ -232,6 +408,17 @@ export function server(options: ServerOptions) {
232
408
  return decodedToken.exp * 1000 > Date.now();
233
409
  },
234
410
 
411
+ /**
412
+ * Handle a proxied `signIn` or `signOut` POST from the client.
413
+ *
414
+ * Validates the route, method, and origin, then forwards the
415
+ * action to Convex and returns a `Response` with updated
416
+ * `Set-Cookie` headers. The client never sees the real
417
+ * refresh token — it stays in httpOnly cookies.
418
+ *
419
+ * @param request - The incoming POST request from the client.
420
+ * @returns A JSON `Response` with auth result and cookie headers.
421
+ */
235
422
  async proxy(request: Request): Promise<Response> {
236
423
  const requestUrl = new URL(request.url);
237
424
  if (!shouldProxyAuthAction(requestUrl.pathname, apiRoute)) {
@@ -308,8 +495,16 @@ export function server(options: ServerOptions) {
308
495
  );
309
496
  }
310
497
  return jsonResponse(result);
311
- } catch (error) {
312
- const response = jsonResponse({ error: (error as Error).message }, 400);
498
+ } catch (error: unknown) {
499
+ // Forward structured error data when available (ConvexError with { code, message }).
500
+ const errorBody =
501
+ error instanceof ConvexError &&
502
+ typeof error.data === "object" &&
503
+ error.data !== null &&
504
+ "code" in error.data
505
+ ? { error: (error.data as { message?: string }).message ?? String(error), authError: error.data }
506
+ : { error: error instanceof Error ? error.message : String(error) };
507
+ const response = jsonResponse(errorBody, 400);
313
508
  return attachCookies(
314
509
  response,
315
510
  serializeAuthCookies(
@@ -346,23 +541,36 @@ export function server(options: ServerOptions) {
346
541
  );
347
542
  },
348
543
 
544
+ /**
545
+ * Refresh auth tokens on page load.
546
+ *
547
+ * Call this in your server hooks/middleware on every request.
548
+ * It handles three scenarios:
549
+ *
550
+ * 1. **OAuth code exchange** — exchanges a `?code=` query param for tokens and returns a redirect URL.
551
+ * 2. **Token refresh** — refreshes the JWT if it's close to expiry.
552
+ * 3. **No-op** — returns the existing token when no refresh is needed.
553
+ *
554
+ * @param request - The incoming HTTP request.
555
+ * @returns Structured cookies to set on the response, an optional redirect URL, and the current JWT.
556
+ */
349
557
  async refresh(request: Request): Promise<RefreshResult> {
350
558
  const host = cookieHost(request);
559
+ const currentToken = parseRequestCookies(request).token;
351
560
 
561
+ // CORS request — clear all auth cookies.
352
562
  if (isCorsRequest(request)) {
353
563
  return {
354
- cookies: serializeAuthCookies(
355
- {
356
- token: null,
357
- refreshToken: null,
358
- verifier: null,
359
- },
564
+ cookies: structuredAuthCookies(
565
+ { token: null, refreshToken: null, verifier: null },
360
566
  host,
361
567
  cookieConfig,
362
568
  ),
569
+ token: null,
363
570
  };
364
571
  }
365
572
 
573
+ // OAuth code exchange — exchange code for tokens and redirect.
366
574
  const requestUrl = new URL(request.url);
367
575
  const code = requestUrl.searchParams.get("code");
368
576
  const shouldHandleCode =
@@ -392,47 +600,41 @@ export function server(options: ServerOptions) {
392
600
  if (result.tokens === undefined) {
393
601
  throw new Error("Invalid `auth:signIn` result for code exchange");
394
602
  }
395
- const response = Response.redirect(redirectUrl.toString(), 302);
396
603
  return {
397
- response: attachCookies(
398
- response,
399
- serializeAuthCookies(
400
- {
401
- token: result.tokens?.token ?? null,
402
- refreshToken: result.tokens?.refreshToken ?? null,
403
- verifier: null,
404
- },
405
- host,
406
- cookieConfig,
407
- ),
604
+ cookies: structuredAuthCookies(
605
+ {
606
+ token: result.tokens?.token ?? null,
607
+ refreshToken: result.tokens?.refreshToken ?? null,
608
+ verifier: null,
609
+ },
610
+ host,
611
+ cookieConfig,
408
612
  ),
613
+ redirect: redirectUrl.toString(),
614
+ token: result.tokens?.token ?? null,
409
615
  };
410
616
  } catch (error) {
411
617
  console.error(error);
412
- const response = Response.redirect(redirectUrl.toString(), 302);
413
618
  return {
414
- response: attachCookies(
415
- response,
416
- serializeAuthCookies(
417
- {
418
- token: null,
419
- refreshToken: null,
420
- verifier: null,
421
- },
422
- host,
423
- cookieConfig,
424
- ),
619
+ cookies: structuredAuthCookies(
620
+ { token: null, refreshToken: null, verifier: null },
621
+ host,
622
+ cookieConfig,
425
623
  ),
624
+ redirect: redirectUrl.toString(),
625
+ token: null,
426
626
  };
427
627
  }
428
628
  }
429
629
 
630
+ // Normal page load — refresh tokens if needed.
430
631
  const tokens = await refreshTokens(request);
431
632
  if (tokens === undefined) {
432
- return {};
633
+ // No refresh needed — return current token for hydration.
634
+ return { cookies: [], token: currentToken };
433
635
  }
434
636
  return {
435
- cookies: serializeAuthCookies(
637
+ cookies: structuredAuthCookies(
436
638
  {
437
639
  token: tokens?.token ?? null,
438
640
  refreshToken: tokens?.refreshToken ?? null,
@@ -441,6 +643,7 @@ export function server(options: ServerOptions) {
441
643
  host,
442
644
  cookieConfig,
443
645
  ),
646
+ token: tokens?.token ?? null,
444
647
  };
445
648
  },
446
649
  };
@@ -7,6 +7,7 @@ import {
7
7
  } from "./convexAuth.js";
8
8
  import { Cookie } from "@auth/core/lib/utils/cookie.js";
9
9
  import { logWithLevel } from "../implementation/utils.js";
10
+ import { throwAuthError } from "../errors.js";
10
11
 
11
12
  /**
12
13
  * Generates an authorization/request token URL.
@@ -25,7 +26,7 @@ export async function getAuthorizationUrl(
25
26
  const { as, authorization: authorizationEndpoint, configSource } = provider;
26
27
 
27
28
  if (!authorizationEndpoint) {
28
- throw new TypeError("Could not determine the authorization endpoint.");
29
+ throwAuthError("PROVIDER_NOT_CONFIGURED", "Could not determine the authorization endpoint.");
29
30
  }
30
31
  if (!url) {
31
32
  url = new URL(authorizationEndpoint.url);
@@ -12,6 +12,7 @@ import {
12
12
  callbackUrl,
13
13
  getAuthorizationSignature,
14
14
  } from "./convexAuth.js";
15
+ import { throwAuthError } from "../errors.js";
15
16
 
16
17
  function formUrlEncode(token: string) {
17
18
  return encodeURIComponent(token).replace(/%20/g, "+");
@@ -88,7 +89,7 @@ export async function handleOAuth(
88
89
  });
89
90
  break;
90
91
  default:
91
- throw new Error("unsupported client authentication method");
92
+ throwAuthError("OAUTH_UNSUPPORTED_AUTH_METHOD");
92
93
  }
93
94
 
94
95
  const resCookies: Cookie[] = [];
@@ -110,7 +111,7 @@ export async function handleOAuth(
110
111
  ...Object.fromEntries(err.cause.entries()),
111
112
  };
112
113
  logWithLevel("DEBUG", "OAuthCallbackError", cause);
113
- throw new Error("OAuth Provider returned an error", { cause });
114
+ throwAuthError("OAUTH_PROVIDER_ERROR", "OAuth provider returned an error", { cause: JSON.stringify(cause) });
114
115
  }
115
116
  throw err;
116
117
  }
@@ -174,7 +175,7 @@ export async function handleOAuth(
174
175
  processedCodeResponse,
175
176
  );
176
177
  if (idTokenClaimsOrUndefined === undefined) {
177
- throw new Error("ID Token claims are missing");
178
+ throwAuthError("OAUTH_MISSING_ID_TOKEN");
178
179
  }
179
180
  const idTokenClaims = idTokenClaimsOrUndefined;
180
181
  profile = idTokenClaims;
@@ -221,7 +222,7 @@ export async function handleOAuth(
221
222
  );
222
223
  profile = await userinfoResponse.json();
223
224
  } else {
224
- throw new TypeError("No userinfo endpoint configured");
225
+ throwAuthError("OAUTH_NO_USERINFO");
225
226
  }
226
227
  }
227
228
 
@@ -6,6 +6,7 @@ import type { InternalOptions } from "./types.js";
6
6
  import { Cookie } from "@auth/core/lib/utils/cookie.js";
7
7
  import { CookiesOptions } from "@auth/core/types.js";
8
8
  import { logWithLevel } from "../implementation/utils.js";
9
+ import { throwAuthError } from "../errors.js";
9
10
 
10
11
  const COOKIE_TTL = 60 * 15; // 15 minutes
11
12
 
@@ -97,7 +98,8 @@ export const state = {
97
98
  const { provider } = options;
98
99
  if (!provider.checks.includes("state")) {
99
100
  if (origin) {
100
- throw new Error(
101
+ throwAuthError(
102
+ "OAUTH_INVALID_STATE",
101
103
  "State data was provided but the provider is not configured to use state",
102
104
  );
103
105
  }
@@ -7,6 +7,7 @@ import * as o from "oauth4webapi";
7
7
  import { normalizeEndpoint } from "../provider_utils.js";
8
8
  import { isLocalHost } from "../utils.js";
9
9
  import { OAuthConfig } from "@auth/core/providers/oauth.js";
10
+ import { throwAuthError } from "../errors.js";
10
11
 
11
12
  // ConvexAuth: The logic for the callback URL is different from Auth.js
12
13
  export function callbackUrl(providerId: string) {
@@ -92,7 +93,8 @@ export async function oAuthConfigToInternalProvider(config: OAuthConfig<any>): P
92
93
  if (!config.authorization || !config.token || !config.userinfo) {
93
94
  // Taken from https://github.com/nextauthjs/next-auth/blob/a7491dcb9355ff2d01fb8e9236636605e2090145/packages/core/src/lib/actions/callback/oauth/callback.ts#L63
94
95
  if (!config.issuer) {
95
- throw new Error(
96
+ throwAuthError(
97
+ "PROVIDER_NOT_CONFIGURED",
96
98
  `Provider \`${config.id}\` is missing an \`issuer\` URL configuration. Consult the provider docs.`,
97
99
  );
98
100
  }
@@ -109,8 +111,9 @@ export async function oAuthConfigToInternalProvider(config: OAuthConfig<any>): P
109
111
  );
110
112
 
111
113
  if (!discoveredAs.token_endpoint)
112
- throw new TypeError(
113
- "TODO: Authorization server did not provide a token endpoint.",
114
+ throwAuthError(
115
+ "PROVIDER_NOT_CONFIGURED",
116
+ "Authorization server did not provide a token endpoint.",
114
117
  );
115
118
 
116
119
  const as: o.AuthorizationServer = discoveredAs;