@convex-dev/better-auth 0.11.2 → 0.11.4

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 (87) hide show
  1. package/dist/auth-config.d.ts +1 -1
  2. package/dist/auth-config.d.ts.map +1 -1
  3. package/dist/auth-options.d.ts.map +1 -1
  4. package/dist/auth-options.js +11 -2
  5. package/dist/auth-options.js.map +1 -1
  6. package/dist/client/create-client.d.ts +12 -0
  7. package/dist/client/create-client.d.ts.map +1 -1
  8. package/dist/client/create-client.js +92 -0
  9. package/dist/client/create-client.js.map +1 -1
  10. package/dist/component/_generated/component.d.ts +0 -1
  11. package/dist/component/_generated/component.d.ts.map +1 -1
  12. package/dist/component/adapterTest.d.ts +0 -1
  13. package/dist/component/adapterTest.d.ts.map +1 -1
  14. package/dist/component/adapterTest.js +11 -21
  15. package/dist/component/adapterTest.js.map +1 -1
  16. package/dist/component/testProfiles/auth-options.profile-rename-joins.js +1 -1
  17. package/dist/component/testProfiles/auth-options.profile-rename-joins.js.map +1 -1
  18. package/dist/plugins/convex/index.d.ts +1 -1
  19. package/dist/plugins/convex/index.d.ts.map +1 -1
  20. package/dist/plugins/convex/index.js +3 -1
  21. package/dist/plugins/convex/index.js.map +1 -1
  22. package/dist/plugins/cross-domain/index.d.ts.map +1 -1
  23. package/dist/plugins/cross-domain/index.js +1 -1
  24. package/dist/plugins/cross-domain/index.js.map +1 -1
  25. package/dist/test/adapter-factory/auth-flow.d.ts +1 -21
  26. package/dist/test/adapter-factory/auth-flow.d.ts.map +1 -1
  27. package/dist/test/adapter-factory/auth-flow.js +32 -37
  28. package/dist/test/adapter-factory/auth-flow.js.map +1 -1
  29. package/dist/test/adapter-factory/basic.d.ts +11 -34
  30. package/dist/test/adapter-factory/basic.d.ts.map +1 -1
  31. package/dist/test/adapter-factory/basic.js +54 -2626
  32. package/dist/test/adapter-factory/basic.js.map +1 -1
  33. package/dist/test/adapter-factory/index.d.ts +0 -6
  34. package/dist/test/adapter-factory/index.d.ts.map +1 -1
  35. package/dist/test/adapter-factory/index.js +0 -6
  36. package/dist/test/adapter-factory/index.js.map +1 -1
  37. package/dist/test/adapter-factory/profile-additional-fields.d.ts.map +1 -1
  38. package/dist/test/adapter-factory/profile-additional-fields.js +14 -1
  39. package/dist/test/adapter-factory/profile-additional-fields.js.map +1 -1
  40. package/dist/test/adapter-factory/profile-plugin-table.d.ts.map +1 -1
  41. package/dist/test/adapter-factory/profile-plugin-table.js +8 -1
  42. package/dist/test/adapter-factory/profile-plugin-table.js.map +1 -1
  43. package/dist/test/adapter-factory/profile-rename-joins.d.ts +3 -3
  44. package/dist/test/adapter-factory/profile-rename-joins.d.ts.map +1 -1
  45. package/dist/test/adapter-factory/profile-rename-joins.js +11 -10
  46. package/dist/test/adapter-factory/profile-rename-joins.js.map +1 -1
  47. package/dist/utils/index.d.ts +3 -2
  48. package/dist/utils/index.d.ts.map +1 -1
  49. package/dist/utils/index.js.map +1 -1
  50. package/package.json +5 -7
  51. package/src/auth-config.ts +1 -1
  52. package/src/auth-options.ts +11 -15
  53. package/src/client/adapter.test.ts +20 -5
  54. package/src/client/create-client.test.ts +149 -0
  55. package/src/client/create-client.ts +127 -0
  56. package/src/component/_generated/component.ts +0 -1
  57. package/src/component/adapterTest.ts +12 -26
  58. package/src/component/testProfiles/auth-options.profile-rename-joins.ts +1 -1
  59. package/src/plugins/convex/index.ts +4 -6
  60. package/src/plugins/cross-domain/index.ts +1 -1
  61. package/src/test/adapter-factory/auth-flow.ts +146 -160
  62. package/src/test/adapter-factory/basic.ts +185 -3187
  63. package/src/test/adapter-factory/index.ts +0 -6
  64. package/src/test/adapter-factory/profile-additional-fields.ts +75 -57
  65. package/src/test/adapter-factory/profile-plugin-table.ts +10 -2
  66. package/src/test/adapter-factory/profile-rename-joins.ts +13 -11
  67. package/src/utils/index.ts +3 -2
  68. package/dist/test/adapter-factory/joins.d.ts +0 -18
  69. package/dist/test/adapter-factory/joins.d.ts.map +0 -1
  70. package/dist/test/adapter-factory/joins.js +0 -22
  71. package/dist/test/adapter-factory/joins.js.map +0 -1
  72. package/dist/test/adapter-factory/number-id.d.ts +0 -18
  73. package/dist/test/adapter-factory/number-id.d.ts.map +0 -1
  74. package/dist/test/adapter-factory/number-id.js +0 -36
  75. package/dist/test/adapter-factory/number-id.js.map +0 -1
  76. package/dist/test/adapter-factory/transactions.d.ts +0 -21
  77. package/dist/test/adapter-factory/transactions.d.ts.map +0 -1
  78. package/dist/test/adapter-factory/transactions.js +0 -28
  79. package/dist/test/adapter-factory/transactions.js.map +0 -1
  80. package/dist/test/adapter-factory/uuid.d.ts +0 -18
  81. package/dist/test/adapter-factory/uuid.d.ts.map +0 -1
  82. package/dist/test/adapter-factory/uuid.js +0 -58
  83. package/dist/test/adapter-factory/uuid.js.map +0 -1
  84. package/src/test/adapter-factory/joins.ts +0 -28
  85. package/src/test/adapter-factory/number-id.ts +0 -45
  86. package/src/test/adapter-factory/transactions.ts +0 -38
  87. package/src/test/adapter-factory/uuid.ts +0 -67
@@ -1,11 +1,26 @@
1
1
  /// <reference types="vite/client" />
2
2
 
3
- import { describe } from "vitest";
3
+ import { describe, it } from "vitest";
4
4
  import { convexTest } from "convex-test";
5
5
  import { api } from "../component/_generated/api.js";
6
6
  import schema from "../component/testProfiles/schema.profile-plugin-table.js";
7
7
 
8
- describe("Better Auth Adapter Tests", async () => {
9
- const t = convexTest(schema, import.meta.glob("../component/**/*.*s"));
10
- await t.action(api.adapterTest.runTests, {});
11
- });
8
+ const MIN_NODE_MAJOR = 24;
9
+ const currentNodeMajor = Number.parseInt(
10
+ process.versions.node.split(".")[0] ?? "0",
11
+ 10
12
+ );
13
+
14
+ if (currentNodeMajor < MIN_NODE_MAJOR) {
15
+ describe("Better Auth Adapter Tests", () => {
16
+ it.skip(
17
+ `requires Node ${MIN_NODE_MAJOR}+ (adapter test-utils uses explicit resource management syntax)`,
18
+ () => {}
19
+ );
20
+ });
21
+ } else {
22
+ describe("Better Auth Adapter Tests", async () => {
23
+ const t = convexTest(schema, import.meta.glob("../component/**/*.*s"));
24
+ await t.action(api.adapterTest.runTests, {});
25
+ });
26
+ }
@@ -0,0 +1,149 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { httpRouter } from "convex/server";
3
+ import { createClient } from "./create-client.js";
4
+
5
+ const component = {
6
+ adapter: {
7
+ create: "create",
8
+ findOne: "findOne",
9
+ findMany: "findMany",
10
+ updateOne: "updateOne",
11
+ updateMany: "updateMany",
12
+ deleteOne: "deleteOne",
13
+ deleteMany: "deleteMany",
14
+ },
15
+ } as any;
16
+
17
+ const getRouteHandler = (
18
+ http: ReturnType<typeof httpRouter>,
19
+ path: string,
20
+ method: "GET" | "POST" | "OPTIONS"
21
+ ) => {
22
+ const route = http.lookup(path, method);
23
+ if (!route) {
24
+ return null;
25
+ }
26
+ return route[0] as unknown as {
27
+ _handler: (ctx: unknown, request: Request) => Promise<Response>;
28
+ };
29
+ };
30
+
31
+ describe("createClient route registration", () => {
32
+ it("registerRoutes eagerly initializes auth and infers basePath", () => {
33
+ const client = createClient(component);
34
+ const http = httpRouter();
35
+ const createAuth = vi.fn(() => ({
36
+ handler: async () => new Response("ok"),
37
+ options: {
38
+ basePath: "/custom/auth",
39
+ trustedOrigins: ["https://app.example.com"],
40
+ },
41
+ $context: Promise.resolve({
42
+ options: {
43
+ trustedOrigins: ["https://app.example.com"],
44
+ },
45
+ }),
46
+ }));
47
+
48
+ client.registerRoutes(http, createAuth);
49
+
50
+ expect(createAuth).toHaveBeenCalledTimes(1);
51
+ expect(getRouteHandler(http, "/custom/auth/test", "GET")).toBeTruthy();
52
+ expect(
53
+ getRouteHandler(http, "/.well-known/openid-configuration", "GET")
54
+ ).toBeTruthy();
55
+ });
56
+
57
+ it("registerRoutes uses auth options for CORS and basePath", async () => {
58
+ const client = createClient(component);
59
+ const http = httpRouter();
60
+ const createAuth = vi.fn(() => ({
61
+ handler: async () => new Response("ok"),
62
+ options: {
63
+ basePath: "/custom/auth",
64
+ trustedOrigins: ["https://app.example.com"],
65
+ },
66
+ $context: Promise.resolve({
67
+ options: {
68
+ trustedOrigins: ["https://app.example.com"],
69
+ },
70
+ }),
71
+ }));
72
+
73
+ client.registerRoutes(http, createAuth, { cors: true });
74
+
75
+ expect(createAuth).toHaveBeenCalledTimes(1);
76
+ expect(getRouteHandler(http, "/custom/auth/test", "GET")).toBeTruthy();
77
+ expect(getRouteHandler(http, "/custom/auth/test", "OPTIONS")).toBeTruthy();
78
+
79
+ const optionsHandler = getRouteHandler(
80
+ http,
81
+ "/custom/auth/test",
82
+ "OPTIONS"
83
+ );
84
+ expect(optionsHandler).toBeTruthy();
85
+ const response = await optionsHandler!._handler(
86
+ {},
87
+ new Request("https://deployment.convex.site/custom/auth/test", {
88
+ method: "OPTIONS",
89
+ headers: {
90
+ origin: "https://app.example.com",
91
+ "access-control-request-method": "GET",
92
+ },
93
+ })
94
+ );
95
+
96
+ expect(response.headers.get("access-control-allow-origin")).toBe(
97
+ "https://app.example.com"
98
+ );
99
+ expect(createAuth).toHaveBeenCalledTimes(1);
100
+
101
+ const getHandler = getRouteHandler(http, "/custom/auth/test", "GET");
102
+ expect(getHandler).toBeTruthy();
103
+ await getHandler!._handler(
104
+ {},
105
+ new Request("https://deployment.convex.site/custom/auth/test", {
106
+ method: "GET",
107
+ })
108
+ );
109
+ expect(createAuth).toHaveBeenCalledTimes(2);
110
+ });
111
+
112
+ it("registerRoutesLazy resolves trustedOrigins lazily when needed", async () => {
113
+ const client = createClient(component);
114
+ const http = httpRouter();
115
+ const createAuth = vi.fn(() => ({
116
+ handler: async () => new Response("ok"),
117
+ options: {
118
+ trustedOrigins: ["https://fallback.example.com"],
119
+ },
120
+ $context: Promise.resolve({
121
+ options: {
122
+ trustedOrigins: ["https://fallback.example.com"],
123
+ },
124
+ }),
125
+ }));
126
+
127
+ client.registerRoutesLazy(http, createAuth, { cors: true });
128
+ expect(createAuth).not.toHaveBeenCalled();
129
+ expect(getRouteHandler(http, "/api/auth/test", "GET")).toBeTruthy();
130
+
131
+ const optionsHandler = getRouteHandler(http, "/api/auth/test", "OPTIONS");
132
+ expect(optionsHandler).toBeTruthy();
133
+ const response = await optionsHandler!._handler(
134
+ {},
135
+ new Request("https://deployment.convex.site/api/auth/test", {
136
+ method: "OPTIONS",
137
+ headers: {
138
+ origin: "https://fallback.example.com",
139
+ "access-control-request-method": "GET",
140
+ },
141
+ })
142
+ );
143
+
144
+ expect(response.headers.get("access-control-allow-origin")).toBe(
145
+ "https://fallback.example.com"
146
+ );
147
+ expect(createAuth).toHaveBeenCalledTimes(1);
148
+ });
149
+ });
@@ -19,6 +19,7 @@ import { corsRouter } from "convex-helpers/server/cors";
19
19
  import type defaultSchema from "../component/schema.js";
20
20
  import type { ComponentApi } from "../component/_generated/component.js";
21
21
  import type { CreateAuth, GenericCtx } from "./index.js";
22
+ import type { TrustedOriginsOption } from "../utils/index.js";
22
23
 
23
24
  export type AuthFunctions = {
24
25
  onCreate?: FunctionReference<"mutation", "internal", { [key: string]: any }>;
@@ -72,6 +73,20 @@ type SlimComponentApi = {
72
73
  adapterTest?: ComponentApi["adapterTest"];
73
74
  };
74
75
 
76
+ type RouteCorsOptions =
77
+ | boolean
78
+ | {
79
+ allowedOrigins?: string[];
80
+ allowedHeaders?: string[];
81
+ exposedHeaders?: string[];
82
+ };
83
+
84
+ type RegisterRoutesLazyOptions = {
85
+ basePath?: string;
86
+ trustedOrigins?: TrustedOriginsOption;
87
+ cors?: RouteCorsOptions;
88
+ };
89
+
75
90
  /**
76
91
  * Backend API for the Better Auth component.
77
92
  * Responsible for exposing the `client` and `triggers` APIs to the client, http
@@ -456,5 +471,117 @@ export const createClient = <
456
471
  handler: authRequestHandler,
457
472
  });
458
473
  },
474
+
475
+ registerRoutesLazy: <T extends CreateAuth<DataModel>>(
476
+ http: HttpRouter,
477
+ createAuth: T,
478
+ opts: RegisterRoutesLazyOptions = {}
479
+ ) => {
480
+ let registrationAuth: ReturnType<T> | undefined;
481
+ const getRegistrationAuth = (): ReturnType<T> => {
482
+ registrationAuth =
483
+ registrationAuth ?? (createAuth({} as any) as ReturnType<T>);
484
+ return registrationAuth;
485
+ };
486
+
487
+ const path = opts.basePath ?? "/api/auth";
488
+ let trustedOriginsOption = opts.trustedOrigins;
489
+ const authRequestHandler = httpActionGeneric(async (ctx, request) => {
490
+ if (config?.verbose) {
491
+ // eslint-disable-next-line no-console
492
+ console.log("options.baseURL", getRegistrationAuth().options.baseURL);
493
+ // eslint-disable-next-line no-console
494
+ console.log("request headers", request.headers);
495
+ }
496
+ const auth = createAuth(ctx as any);
497
+ const response = await auth.handler(request);
498
+ if (config?.verbose) {
499
+ // eslint-disable-next-line no-console
500
+ console.log("response headers", response.headers);
501
+ }
502
+ return response;
503
+ });
504
+ const wellKnown = http.lookup("/.well-known/openid-configuration", "GET");
505
+
506
+ // If registerRoutes is used multiple times, this may already be defined
507
+ if (!wellKnown) {
508
+ // Redirect root well-known to api well-known
509
+ http.route({
510
+ path: "/.well-known/openid-configuration",
511
+ method: "GET",
512
+ handler: httpActionGeneric(async () => {
513
+ const url = `${process.env.CONVEX_SITE_URL}${path}/convex/.well-known/openid-configuration`;
514
+ return Response.redirect(url);
515
+ }),
516
+ });
517
+ }
518
+
519
+ if (!opts.cors) {
520
+ http.route({
521
+ pathPrefix: `${path}/`,
522
+ method: "GET",
523
+ handler: authRequestHandler,
524
+ });
525
+
526
+ http.route({
527
+ pathPrefix: `${path}/`,
528
+ method: "POST",
529
+ handler: authRequestHandler,
530
+ });
531
+
532
+ return;
533
+ }
534
+
535
+ const corsOpts =
536
+ typeof opts.cors === "boolean"
537
+ ? { allowedOrigins: [], allowedHeaders: [], exposedHeaders: [] }
538
+ : opts.cors;
539
+ const cors = corsRouter(http, {
540
+ allowedOrigins: async (request) => {
541
+ const resolvedTrustedOrigins =
542
+ trustedOriginsOption ??
543
+ (await getRegistrationAuth().$context).options.trustedOrigins ??
544
+ [];
545
+ trustedOriginsOption = resolvedTrustedOrigins;
546
+ const rawOrigins = Array.isArray(resolvedTrustedOrigins)
547
+ ? resolvedTrustedOrigins
548
+ : await resolvedTrustedOrigins(request);
549
+ const trustedOrigins = rawOrigins.filter(
550
+ (origin): origin is string => typeof origin === "string"
551
+ );
552
+ return trustedOrigins
553
+ .map((origin) =>
554
+ // Strip trailing wildcards, unsupported for allowedOrigins
555
+ origin.endsWith("*") && origin.length > 1
556
+ ? origin.slice(0, -1)
557
+ : origin
558
+ )
559
+ .concat(corsOpts.allowedOrigins ?? []);
560
+ },
561
+ allowCredentials: true,
562
+ allowedHeaders: [
563
+ "Content-Type",
564
+ "Better-Auth-Cookie",
565
+ "Authorization",
566
+ ].concat(corsOpts.allowedHeaders ?? []),
567
+ exposedHeaders: ["Set-Better-Auth-Cookie"].concat(
568
+ corsOpts.exposedHeaders ?? []
569
+ ),
570
+ debug: config?.verbose,
571
+ enforceAllowOrigins: false,
572
+ });
573
+
574
+ cors.route({
575
+ pathPrefix: `${path}/`,
576
+ method: "GET",
577
+ handler: authRequestHandler,
578
+ });
579
+
580
+ cors.route({
581
+ pathPrefix: `${path}/`,
582
+ method: "POST",
583
+ handler: authRequestHandler,
584
+ });
585
+ },
459
586
  };
460
587
  };
@@ -1825,7 +1825,6 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
1825
1825
  >;
1826
1826
  };
1827
1827
  adapterTest: {
1828
- runCustomTests: FunctionReference<"action", "internal", any, any, Name>;
1829
1828
  runTests: FunctionReference<"action", "internal", any, any, Name>;
1830
1829
  };
1831
1830
  testProfiles: {
@@ -13,11 +13,18 @@ import type { ComponentApi } from "./_generated/component.js";
13
13
  // globals are available through dynamic imports.
14
14
 
15
15
  const NORMAL_DISABLED_TESTS = [
16
+ // dynamic-schema-plugin-table/dynamic-schema-additional-fields:
17
+ // Convex validators are static in this harness, so runtime schema mutation
18
+ // tests are validated in dedicated profiles instead.
16
19
  "create - should apply default values to fields",
17
20
  "create - should return null for nullable foreign keys",
18
21
  "create - should support arrays",
19
22
  "create - should support json",
23
+ // convex-id-generation:
24
+ // Convex controls generated IDs at write time.
20
25
  "create - should use generateId if provided",
26
+ // offset-unsupported:
27
+ // Convex adapter rejects offset pagination.
21
28
  "findMany - should be able to perform a complex limited join",
22
29
  "findMany - should find many models with limit and offset",
23
30
  "findMany - should find many models with offset",
@@ -32,6 +39,8 @@ const NORMAL_DISABLED_TESTS = [
32
39
  "findMany - should return empty array when base records don't exist with joins",
33
40
  "findMany - should return null for one-to-one join when joined records don't exist",
34
41
  "findMany - should select fields with one-to-one join",
42
+ // profile-specific coverage:
43
+ // These are intentionally exercised in dedicated profile suites.
35
44
  "findOne - backwards join with modified field name (session base, users-table join)",
36
45
  "findOne - multiple joins should return result even when some joined tables have no matching rows",
37
46
  "findOne - should find a model with modified field name",
@@ -102,7 +111,9 @@ const organizationJoinsProfileApi = profileApi("adapterOrganizationJoins");
102
111
  export const runTests = action(
103
112
  async (ctx: GenericActionCtx<DataModel>, _args: EmptyObject) => {
104
113
  const testUtilsImport = "@better-auth/test-utils/adapter";
105
- const { testAdapter } = await import(testUtilsImport);
114
+ const { testAdapter, transactionsTestSuite, uuidTestSuite } = await import(
115
+ testUtilsImport
116
+ );
106
117
  const adapterFactoryImport = "../test/adapter-factory/index.js";
107
118
  const {
108
119
  coreNormalTestSuite,
@@ -114,8 +125,6 @@ export const runTests = action(
114
125
  renameModelUserCustomTestSuite,
115
126
  renameModelUserTableTestSuite,
116
127
  multiJoinsMissingRowsTestSuite,
117
- transactionsTestSuite,
118
- uuidTestSuite,
119
128
  convexCustomTestSuite,
120
129
  } = await import(adapterFactoryImport);
121
130
 
@@ -264,26 +273,3 @@ export const runTests = action(
264
273
  await executeOrganizationJoinsProfile();
265
274
  }
266
275
  );
267
-
268
- // Keep this export during migration to avoid breaking generated component types.
269
- export const runCustomTests = action(
270
- async (ctx: GenericActionCtx<DataModel>, _args: EmptyObject) => {
271
- const testUtilsImport = "@better-auth/test-utils/adapter";
272
- const { testAdapter } = await import(testUtilsImport);
273
- const adapterFactoryImport = "../test/adapter-factory/index.js";
274
- const { convexCustomTestSuite } = await import(adapterFactoryImport);
275
- const authComponent = createClient<DataModel>(baseProfileApi, {
276
- verbose: false,
277
- });
278
-
279
- const { execute } = await testAdapter({
280
- adapter: () => {
281
- return authComponent.adapter(ctx);
282
- },
283
- runMigrations: () => {},
284
- overrideBetterAuthOptions: getOverrideBetterAuthOptions,
285
- tests: [convexCustomTestSuite()],
286
- });
287
- await execute();
288
- }
289
- );
@@ -1,5 +1,5 @@
1
1
  import type { BetterAuthOptions } from "better-auth/minimal";
2
- import { organization } from "better-auth/plugins";
2
+ import { organization } from "better-auth/plugins/organization";
3
3
  import { options } from "../../auth-options.js";
4
4
 
5
5
  const renamedOneToOnePlugin = {
@@ -5,12 +5,10 @@ import {
5
5
  createAuthMiddleware,
6
6
  sessionMiddleware,
7
7
  } from "better-auth/api";
8
- import {
9
- jwt as jwtPlugin,
10
- bearer as bearerPlugin,
11
- oidcProvider as oidcProviderPlugin,
12
- } from "better-auth/plugins";
13
- import type { JwtOptions, Jwk } from "better-auth/plugins";
8
+ import { bearer as bearerPlugin } from "better-auth/plugins/bearer";
9
+ import { jwt as jwtPlugin } from "better-auth/plugins/jwt";
10
+ import type { JwtOptions, Jwk } from "better-auth/plugins/jwt";
11
+ import { oidcProvider as oidcProviderPlugin } from "better-auth/plugins/oidc-provider";
14
12
  import { omit } from "convex-helpers";
15
13
  import type { AuthConfig, AuthProvider } from "convex/server";
16
14
 
@@ -2,7 +2,7 @@ import type { BetterAuthPlugin } from "better-auth";
2
2
  import { setSessionCookie } from "better-auth/cookies";
3
3
  import { generateRandomString } from "better-auth/crypto";
4
4
  import { createAuthEndpoint, createAuthMiddleware } from "better-auth/api";
5
- import { oneTimeToken as oneTimeTokenPlugin } from "better-auth/plugins";
5
+ import { oneTimeToken as oneTimeTokenPlugin } from "better-auth/plugins/one-time-token";
6
6
  import { z } from "zod";
7
7
 
8
8
  export const crossDomain = ({ siteUrl }: { siteUrl: string }) => {