@terreno/api 57.1.0 → 57.3.0

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 (283) hide show
  1. package/README.md +17 -7
  2. package/dist/actions.js +19 -7
  3. package/dist/adminTypes.d.ts +26 -0
  4. package/dist/api.d.ts +4 -0
  5. package/dist/api.js +12 -24
  6. package/dist/auth.d.ts +23 -10
  7. package/dist/auth.js +97 -32
  8. package/dist/authRecovery.d.ts +5 -0
  9. package/dist/authRecovery.js +350 -0
  10. package/dist/authTokens.d.ts +8 -0
  11. package/dist/authTokens.js +162 -0
  12. package/dist/betterAuth.d.ts +33 -0
  13. package/dist/betterAuthApp.d.ts +4 -0
  14. package/dist/betterAuthApp.js +26 -8
  15. package/dist/betterAuthSetup.d.ts +44 -2
  16. package/dist/betterAuthSetup.js +288 -18
  17. package/dist/collectionRegistry.d.ts +38 -0
  18. package/dist/collectionRegistry.js +72 -0
  19. package/dist/configurationApp.d.ts +11 -2
  20. package/dist/configurationApp.js +2 -4
  21. package/dist/docLoader.js +35 -6
  22. package/dist/expressServer.d.ts +26 -3
  23. package/dist/expressServer.js +79 -11
  24. package/dist/index.d.ts +16 -0
  25. package/dist/index.js +38 -2
  26. package/dist/mcp/auth.d.ts +1 -0
  27. package/dist/mcp/auth.js +47 -25
  28. package/dist/mcp/handlers.d.ts +1 -1
  29. package/dist/mcp/handlers.js +67 -233
  30. package/dist/mcp/query.d.ts +2 -2
  31. package/dist/mcp/registry.d.ts +1 -5
  32. package/dist/mcp/registry.js +31 -20
  33. package/dist/mcp/schemaGenerator.d.ts +2 -7
  34. package/dist/mcp/schemaGenerator.js +41 -116
  35. package/dist/mcp/server.d.ts +1 -0
  36. package/dist/mcp/server.js +1 -0
  37. package/dist/mcp/serviceTokens.d.ts +16 -0
  38. package/dist/mcp/serviceTokens.js +345 -0
  39. package/dist/mcp/types.d.ts +2 -2
  40. package/dist/models/mcpServiceToken.d.ts +3 -0
  41. package/dist/models/mcpServiceToken.js +208 -0
  42. package/dist/openApiBuilder.d.ts +5 -4
  43. package/dist/openApiBuilder.js +61 -8
  44. package/dist/openApiCompat.js +1 -1
  45. package/dist/openApiValidator.js +0 -2
  46. package/dist/plugins.d.ts +14 -1
  47. package/dist/plugins.js +17 -6
  48. package/dist/populate.d.ts +2 -2
  49. package/dist/populate.js +47 -42
  50. package/dist/rateLimit/applyTrustProxy.d.ts +3 -0
  51. package/dist/rateLimit/applyTrustProxy.js +17 -0
  52. package/dist/rateLimit/createStore.d.ts +2 -0
  53. package/dist/rateLimit/createStore.js +28 -0
  54. package/dist/rateLimit/memoryStore.d.ts +2 -0
  55. package/dist/rateLimit/memoryStore.js +108 -0
  56. package/dist/rateLimit/middleware.d.ts +11 -0
  57. package/dist/rateLimit/middleware.js +110 -0
  58. package/dist/rateLimit/mongoStore.d.ts +3 -0
  59. package/dist/rateLimit/mongoStore.js +122 -0
  60. package/dist/rateLimit/policies.d.ts +14 -0
  61. package/dist/rateLimit/policies.js +151 -0
  62. package/dist/rateLimit/redisStore.d.ts +3 -0
  63. package/dist/rateLimit/redisStore.js +155 -0
  64. package/dist/rateLimit/types.d.ts +54 -0
  65. package/dist/rateLimit/types.js +9 -0
  66. package/dist/rbac/access.js +5 -1
  67. package/dist/rbac/assertAllowed.d.ts +9 -0
  68. package/dist/rbac/assertAllowed.js +182 -0
  69. package/dist/rbac/modelRouterAccess.d.ts +1 -0
  70. package/dist/rbac/modelRouterAccess.js +8 -4
  71. package/dist/rbac/permissionUtils.js +3 -2
  72. package/dist/rbac/resolve.js +5 -4
  73. package/dist/rbac/routes.js +15 -6
  74. package/dist/rbac/statements.d.ts +10 -0
  75. package/dist/rbac/statements.js +13 -2
  76. package/dist/realtime/deprecation.d.ts +12 -0
  77. package/dist/realtime/deprecation.js +32 -0
  78. package/dist/realtime/realtimeApp.d.ts +1 -1
  79. package/dist/realtime/realtimeApp.js +10 -11
  80. package/dist/realtime/registry.d.ts +0 -31
  81. package/dist/realtime/registry.js +44 -31
  82. package/dist/realtime/socketAuth.d.ts +5 -5
  83. package/dist/realtime/socketAuth.js +11 -1
  84. package/dist/realtime/socketUser.d.ts +5 -1
  85. package/dist/realtime/types.d.ts +14 -4
  86. package/dist/schemaMetadata.d.ts +56 -0
  87. package/dist/schemaMetadata.js +513 -0
  88. package/dist/seedRunner.d.ts +88 -0
  89. package/dist/seedRunner.js +627 -0
  90. package/dist/sync/executors.d.ts +12 -2
  91. package/dist/sync/executors.js +8 -10
  92. package/dist/sync/loadHarness.js +28 -19
  93. package/dist/sync/models.js +26 -24
  94. package/dist/sync/mutationHandler.d.ts +9 -0
  95. package/dist/sync/mutationHandler.js +11 -6
  96. package/dist/sync/registrationSideEffects.d.ts +35 -0
  97. package/dist/sync/registrationSideEffects.js +151 -0
  98. package/dist/sync/registry.d.ts +2 -52
  99. package/dist/sync/registry.js +38 -187
  100. package/dist/sync/routes.js +3 -2
  101. package/dist/sync/scripts/compactTombstones.js +0 -2
  102. package/dist/sync/syncApp.d.ts +3 -3
  103. package/dist/sync/syncApp.js +4 -4
  104. package/dist/sync/syncBatch.js +3 -2
  105. package/dist/sync/syncSeqPlugin.d.ts +1 -1
  106. package/dist/sync/syncSeqPlugin.js +20 -16
  107. package/dist/terrenoApp.d.ts +19 -5
  108. package/dist/terrenoApp.js +66 -18
  109. package/dist/tests/models.d.ts +2 -0
  110. package/dist/tests/models.js +6 -0
  111. package/dist/types/authToken.d.ts +33 -0
  112. package/dist/types/authToken.js +2 -0
  113. package/dist/types/mcpServiceToken.d.ts +41 -0
  114. package/dist/types/mcpServiceToken.js +2 -0
  115. package/dist/webhooks/headerValue.d.ts +2 -0
  116. package/dist/webhooks/headerValue.js +14 -0
  117. package/dist/webhooks/idempotency/memoryStore.d.ts +10 -0
  118. package/dist/webhooks/idempotency/memoryStore.js +65 -0
  119. package/dist/webhooks/idempotency/mongoStore.d.ts +4 -0
  120. package/dist/webhooks/idempotency/mongoStore.js +150 -0
  121. package/dist/webhooks/idempotency/webhookReceipt.d.ts +62 -0
  122. package/dist/webhooks/idempotency/webhookReceipt.js +39 -0
  123. package/dist/webhooks/rawBody.d.ts +14 -0
  124. package/dist/webhooks/rawBody.js +22 -0
  125. package/dist/webhooks/timingSafeEqual.d.ts +4 -0
  126. package/dist/webhooks/timingSafeEqual.js +17 -0
  127. package/dist/webhooks/verifiers/hmac.d.ts +15 -0
  128. package/dist/webhooks/verifiers/hmac.js +49 -0
  129. package/dist/webhooks/verifiers/sendgrid.d.ts +10 -0
  130. package/dist/webhooks/verifiers/sendgrid.js +56 -0
  131. package/dist/webhooks/verifiers/stripe.d.ts +9 -0
  132. package/dist/webhooks/verifiers/stripe.js +99 -0
  133. package/dist/webhooks/verifiers/twilio.d.ts +9 -0
  134. package/dist/webhooks/verifiers/twilio.js +112 -0
  135. package/dist/webhooks/webhooksApp.d.ts +33 -0
  136. package/dist/webhooks/webhooksApp.js +195 -0
  137. package/package.json +5 -6
  138. package/src/__snapshots__/openApi.test.ts.snap +270 -0
  139. package/src/__snapshots__/openApiBuilder.test.ts.snap +30 -12
  140. package/src/__snapshots__/schemaMetadata.test.ts.snap +197 -0
  141. package/src/actions.ts +20 -13
  142. package/src/adminModelRouter.test.ts +133 -0
  143. package/src/adminTypes.ts +23 -0
  144. package/src/api.arrayOperations.test.ts +43 -31
  145. package/src/api.hooks.test.ts +38 -29
  146. package/src/api.query.test.ts +31 -31
  147. package/src/api.test.ts +95 -96
  148. package/src/api.ts +16 -27
  149. package/src/auth.test.ts +107 -51
  150. package/src/auth.ts +98 -29
  151. package/src/authRecovery.test.ts +281 -0
  152. package/src/authRecovery.ts +279 -0
  153. package/src/authTokens.test.ts +94 -0
  154. package/src/authTokens.ts +118 -0
  155. package/src/authVerification.test.ts +293 -0
  156. package/src/betterAuth.ts +24 -0
  157. package/src/betterAuthApp.test.ts +1 -0
  158. package/src/betterAuthApp.ts +27 -9
  159. package/src/betterAuthSetup.test.ts +568 -38
  160. package/src/betterAuthSetup.ts +260 -5
  161. package/src/collectionRegistry.test.ts +165 -0
  162. package/src/collectionRegistry.ts +115 -0
  163. package/src/configurationApp.ts +13 -7
  164. package/src/docLoader.test.ts +45 -1
  165. package/src/docLoader.ts +37 -6
  166. package/src/express.d.ts +1 -0
  167. package/src/expressServer.test.ts +130 -66
  168. package/src/expressServer.ts +75 -19
  169. package/src/githubAuth.test.ts +60 -55
  170. package/src/index.ts +58 -0
  171. package/src/mcp/auth.test.ts +47 -0
  172. package/src/mcp/auth.ts +32 -11
  173. package/src/mcp/handlers.ts +45 -172
  174. package/src/mcp/integration.test.ts +59 -9
  175. package/src/mcp/query.ts +2 -4
  176. package/src/mcp/registry.ts +29 -20
  177. package/src/mcp/schemaGenerator.test.ts +8 -0
  178. package/src/mcp/schemaGenerator.ts +49 -131
  179. package/src/mcp/server.ts +2 -0
  180. package/src/mcp/serviceTokens.test.ts +330 -0
  181. package/src/mcp/serviceTokens.ts +307 -0
  182. package/src/mcp/toolGenerator.test.ts +1 -1
  183. package/src/mcp/types.ts +2 -6
  184. package/src/models/mcpServiceToken.test.ts +129 -0
  185. package/src/models/mcpServiceToken.ts +158 -0
  186. package/src/openApi.test.ts +80 -64
  187. package/src/openApiBuilder.test.ts +95 -7
  188. package/src/openApiBuilder.ts +46 -9
  189. package/src/openApiCompat.ts +1 -1
  190. package/src/openApiValidator.test.ts +49 -54
  191. package/src/openApiValidator.ts +1 -3
  192. package/src/plugins.test.ts +14 -0
  193. package/src/plugins.ts +34 -9
  194. package/src/populate.test.ts +34 -0
  195. package/src/populate.ts +40 -29
  196. package/src/rateLimit/applyTrustProxy.ts +17 -0
  197. package/src/rateLimit/createStore.ts +25 -0
  198. package/src/rateLimit/memoryStore.ts +40 -0
  199. package/src/rateLimit/middleware.ts +79 -0
  200. package/src/rateLimit/mongoStore.test.ts +80 -0
  201. package/src/rateLimit/mongoStore.ts +76 -0
  202. package/src/rateLimit/policies.ts +130 -0
  203. package/src/rateLimit/rateLimit.test.ts +328 -0
  204. package/src/rateLimit/redisStore.ioredis.test.ts +29 -0
  205. package/src/rateLimit/redisStore.test.ts +114 -0
  206. package/src/rateLimit/redisStore.ts +85 -0
  207. package/src/rateLimit/types.ts +64 -0
  208. package/src/rbac/access.ts +5 -1
  209. package/src/rbac/assertAllowed.test.ts +325 -0
  210. package/src/rbac/assertAllowed.ts +157 -0
  211. package/src/rbac/backfillAdmins.test.ts +124 -0
  212. package/src/rbac/fieldViews.test.ts +89 -0
  213. package/src/rbac/modelRouterAccess.test.ts +126 -0
  214. package/src/rbac/modelRouterAccess.ts +5 -2
  215. package/src/rbac/permissionUtils.ts +3 -2
  216. package/src/rbac/realtimeAccess.test.ts +109 -1
  217. package/src/rbac/resolve.ts +5 -4
  218. package/src/rbac/roleManager.test.ts +169 -0
  219. package/src/rbac/routes.test.ts +233 -0
  220. package/src/rbac/routes.ts +16 -6
  221. package/src/rbac/statements.test.ts +2 -0
  222. package/src/rbac/statements.ts +12 -1
  223. package/src/realtime/deprecation.test.ts +60 -0
  224. package/src/realtime/deprecation.ts +32 -0
  225. package/src/realtime/realtime.test.ts +8 -4
  226. package/src/realtime/realtimeApp.ts +10 -11
  227. package/src/realtime/realtimeAppSetup.test.ts +32 -5
  228. package/src/realtime/registry.ts +48 -42
  229. package/src/realtime/sessionRevalidation.test.ts +57 -44
  230. package/src/realtime/socketAuth.test.ts +75 -23
  231. package/src/realtime/socketAuth.ts +17 -6
  232. package/src/realtime/socketUser.ts +5 -3
  233. package/src/realtime/types.ts +14 -4
  234. package/src/schemaMetadata.test.ts +405 -0
  235. package/src/schemaMetadata.ts +593 -0
  236. package/src/scrubAdminFields.test.ts +105 -0
  237. package/src/seedRunner.test.ts +591 -0
  238. package/src/seedRunner.ts +464 -0
  239. package/src/sync/docMatchesMutationData.test.ts +16 -0
  240. package/src/sync/ensureSyncIndexes.test.ts +54 -15
  241. package/src/sync/executors.test.ts +40 -0
  242. package/src/sync/executors.ts +24 -12
  243. package/src/sync/integration.test.ts +15 -7
  244. package/src/sync/loadHarness.ts +28 -19
  245. package/src/sync/models.ts +32 -18
  246. package/src/sync/mutationHandler.test.ts +16 -16
  247. package/src/sync/mutationHandler.ts +9 -7
  248. package/src/sync/registrationSideEffects.test.ts +126 -0
  249. package/src/sync/registrationSideEffects.ts +131 -0
  250. package/src/sync/registry.ts +45 -171
  251. package/src/sync/routes.ts +3 -2
  252. package/src/sync/scripts/compactTombstones.ts +0 -2
  253. package/src/sync/sessionRevalidationIntegration.test.ts +12 -11
  254. package/src/sync/sync.test.ts +25 -23
  255. package/src/sync/syncApp.ts +4 -4
  256. package/src/sync/syncBatch.ts +3 -2
  257. package/src/sync/syncFrontier.test.ts +17 -15
  258. package/src/sync/syncPhaseC.test.ts +54 -43
  259. package/src/sync/syncRoutes.test.ts +51 -36
  260. package/src/sync/syncSeqPlugin.ts +66 -44
  261. package/src/sync/syncSocket.test.ts +112 -81
  262. package/src/terrenoApp.mcpServiceTokens.test.ts +173 -0
  263. package/src/terrenoApp.ts +87 -15
  264. package/src/tests/models.ts +14 -1
  265. package/src/types/authToken.ts +43 -0
  266. package/src/types/mcpServiceToken.ts +54 -0
  267. package/src/webhooks/headerValue.test.ts +22 -0
  268. package/src/webhooks/headerValue.ts +12 -0
  269. package/src/webhooks/idempotency/memoryStore.ts +34 -0
  270. package/src/webhooks/idempotency/mongoStore.test.ts +274 -0
  271. package/src/webhooks/idempotency/mongoStore.ts +83 -0
  272. package/src/webhooks/idempotency/webhookReceipt.ts +70 -0
  273. package/src/webhooks/rawBody.test.ts +74 -0
  274. package/src/webhooks/rawBody.ts +23 -0
  275. package/src/webhooks/timingSafeEqual.ts +16 -0
  276. package/src/webhooks/verifiers/hmac.test.ts +110 -0
  277. package/src/webhooks/verifiers/hmac.ts +54 -0
  278. package/src/webhooks/verifiers/providerVerifiers.test.ts +388 -0
  279. package/src/webhooks/verifiers/sendgrid.ts +59 -0
  280. package/src/webhooks/verifiers/stripe.ts +67 -0
  281. package/src/webhooks/verifiers/twilio.ts +69 -0
  282. package/src/webhooks/webhooksApp.test.ts +221 -0
  283. package/src/webhooks/webhooksApp.ts +144 -0
@@ -1,27 +1,42 @@
1
- // noExplicitAny: test mock typing
2
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
1
  import {afterAll, afterEach, describe, expect, it, mock} from "bun:test";
4
2
  import {assert} from "chai";
5
- import express from "express";
3
+ import express, {type Request, type Response} from "express";
6
4
  import {MongoMemoryServer} from "mongodb-memory-server";
7
5
  import mongoose, {Schema} from "mongoose";
6
+ import passportLocalMongoose from "passport-local-mongoose";
8
7
  import type {UserModel} from "./auth";
9
- import type {BetterAuthConfig, BetterAuthUser} from "./betterAuth";
8
+ import type {BetterAuthConfig, BetterAuthSessionData, BetterAuthUser} from "./betterAuth";
10
9
  import {
10
+ applyBetterAuthPasswordResetToJwt,
11
+ applyJwtPasswordResetToBetterAuth,
12
+ type BetterAuthInstance,
11
13
  createBetterAuth,
14
+ createBetterAuthEmailHooks,
12
15
  createBetterAuthSessionMiddleware,
13
16
  getBetterAuthSession,
14
17
  getMongoClientFromMongoose,
15
18
  hasBetterAuthSession,
19
+ type MongoClientLike,
16
20
  mountBetterAuthRoutes,
21
+ readPasswordFromBetterAuthResetRequest,
17
22
  setupBetterAuthUserSync,
18
23
  syncBetterAuthUser,
19
24
  } from "./betterAuthSetup";
20
25
 
26
+ type SessionRequest = Request & {betterAuthSession?: BetterAuthSessionData};
27
+ const makeReq = (overrides: Partial<SessionRequest> = {}): SessionRequest =>
28
+ ({headers: {}, ...overrides}) as SessionRequest;
29
+ const makeRes = (): Response => ({}) as Response;
30
+ const setGetSession = (auth: BetterAuthInstance, getSession: () => unknown): void => {
31
+ (auth.api as unknown as {getSession: () => unknown}).getSession = getSession;
32
+ };
33
+
21
34
  // Use a separate connection to avoid conflict with bunSetup.ts preload
22
35
  let conn: mongoose.Connection;
23
36
  let mongod: MongoMemoryServer;
24
- let TestUser: any;
37
+ let TestUser: UserModel;
38
+ let StrictUser: UserModel;
39
+ let DualAuthUser: UserModel;
25
40
 
26
41
  // Simple user schema for testing
27
42
  const testUserSchema = new Schema({
@@ -32,16 +47,43 @@ const testUserSchema = new Schema({
32
47
  oauthProvider: {type: String},
33
48
  });
34
49
 
50
+ const dualAuthUserSchema = new Schema({
51
+ admin: {default: false, type: Boolean},
52
+ betterAuthId: {type: String},
53
+ email: {required: true, type: String},
54
+ name: {type: String},
55
+ tokenEpoch: {default: 0, type: Number},
56
+ });
57
+ dualAuthUserSchema.plugin(
58
+ passportLocalMongoose as unknown as (schema: Schema, options?: Record<string, unknown>) => void,
59
+ {
60
+ usernameCaseInsensitive: true,
61
+ usernameField: "email",
62
+ }
63
+ );
64
+
65
+ const strictUserSchema = new Schema(
66
+ {
67
+ admin: {default: false, type: Boolean},
68
+ betterAuthId: {type: String},
69
+ email: {required: true, type: String},
70
+ name: {type: String},
71
+ },
72
+ {strict: "throw"}
73
+ );
74
+
35
75
  // Start memory server and create connection before tests run
36
76
  const setup = (async () => {
37
77
  mongod = await MongoMemoryServer.create();
38
78
  conn = mongoose.createConnection(mongod.getUri());
39
79
  await conn.asPromise();
40
- TestUser = conn.model("BetterAuthTestUser", testUserSchema);
80
+ TestUser = conn.model("BetterAuthTestUser", testUserSchema) as UserModel;
81
+ StrictUser = conn.model("BetterAuthStrictUser", strictUserSchema) as UserModel;
82
+ DualAuthUser = conn.model("BetterAuthDualUser", dualAuthUserSchema) as UserModel;
41
83
  })();
42
84
 
43
85
  // Helper to get the mongo client from our separate connection
44
- const getClient = () => (conn as any).client;
86
+ const getClient = (): MongoClientLike => conn.getClient();
45
87
 
46
88
  afterAll(async () => {
47
89
  await conn?.close();
@@ -51,6 +93,8 @@ afterAll(async () => {
51
93
  afterEach(async () => {
52
94
  await setup;
53
95
  await TestUser.deleteMany({});
96
+ await StrictUser.deleteMany({});
97
+ await DualAuthUser.deleteMany({});
54
98
  });
55
99
 
56
100
  describe("createBetterAuth", () => {
@@ -115,7 +159,7 @@ describe("createBetterAuth", () => {
115
159
  const auth = createBetterAuth({config, mongoClient: getClient()});
116
160
 
117
161
  const response = await auth.handler(
118
- new Request("https://api.example.com/api/auth/sign-up/email", {
162
+ new globalThis.Request("https://api.example.com/api/auth/sign-up/email", {
119
163
  body: JSON.stringify({
120
164
  email: "cross-domain-cookie@example.com",
121
165
  name: "Cross Domain",
@@ -177,6 +221,468 @@ describe("createBetterAuth", () => {
177
221
  const auth = createBetterAuth({config, mongoClient: getClient()});
178
222
  expect(auth).toBeDefined();
179
223
  });
224
+
225
+ it("revokes Better Auth sessions on password reset", async () => {
226
+ await setup;
227
+ const config: BetterAuthConfig = {
228
+ baseURL: "http://localhost:3000",
229
+ enabled: true,
230
+ secret: "test-secret-at-least-32-characters-long",
231
+ };
232
+ const auth = createBetterAuth({config, mongoClient: getClient()});
233
+ const options = (
234
+ auth as {
235
+ options?: {emailAndPassword?: {revokeSessionsOnPasswordReset?: boolean}};
236
+ }
237
+ ).options;
238
+ assert.isTrue(options?.emailAndPassword?.revokeSessionsOnPasswordReset);
239
+ });
240
+
241
+ it("wires JWT password sync when a user model is provided", async () => {
242
+ await setup;
243
+ const config: BetterAuthConfig = {
244
+ baseURL: "http://localhost:3000",
245
+ enabled: true,
246
+ secret: "test-secret-at-least-32-characters-long",
247
+ };
248
+ const auth = createBetterAuth({
249
+ config,
250
+ mongoClient: getClient(),
251
+ userModel: DualAuthUser,
252
+ });
253
+ const options = (
254
+ auth as {
255
+ options?: {emailAndPassword?: {onPasswordReset?: unknown}};
256
+ }
257
+ ).options;
258
+ assert.isFunction(options?.emailAndPassword?.onPasswordReset);
259
+ });
260
+
261
+ it("sends reset and verification mail through the injected renderer", async () => {
262
+ await setup;
263
+ const renderedCalls: Array<{templateId: string; token: string}> = [];
264
+ const sent: Array<{subject: string; text?: string; to: string}> = [];
265
+ const hooks = createBetterAuthEmailHooks({
266
+ enabled: true,
267
+ publicAppUrl: "https://app.example.com",
268
+ renderAuthMail: ({templateId, token}) => {
269
+ renderedCalls.push({templateId, token});
270
+ return {subject: templateId, text: `link-${token}`};
271
+ },
272
+ sendMail: async (message) => {
273
+ sent.push({subject: message.subject, text: message.text, to: message.to});
274
+ },
275
+ });
276
+ assert.isDefined(hooks);
277
+ await hooks?.sendResetPassword({
278
+ token: "reset-token",
279
+ url: "https://better-auth.example/ignored",
280
+ user: {email: "reset@example.com"},
281
+ });
282
+ await hooks?.sendVerificationEmail({
283
+ token: "verify-token",
284
+ url: "https://better-auth.example/ignored",
285
+ user: {email: "verify@example.com"},
286
+ });
287
+ assert.deepEqual(renderedCalls, [
288
+ {templateId: "resetPassword", token: "reset-token"},
289
+ {templateId: "verifyEmail", token: "verify-token"},
290
+ ]);
291
+ assert.deepEqual(sent, [
292
+ {subject: "resetPassword", text: "link-reset-token", to: "reset@example.com"},
293
+ {subject: "verifyEmail", text: "link-verify-token", to: "verify@example.com"},
294
+ ]);
295
+ });
296
+
297
+ it("does not send Better Auth recovery mail when publicAppUrl is missing", async () => {
298
+ await setup;
299
+ const sent: Array<{subject: string; to: string}> = [];
300
+ const hooks = createBetterAuthEmailHooks({
301
+ enabled: true,
302
+ sendMail: async (message) => {
303
+ sent.push({subject: message.subject, to: message.to});
304
+ },
305
+ });
306
+ assert.isDefined(hooks);
307
+ await expect(
308
+ hooks?.sendResetPassword({
309
+ token: "reset-token",
310
+ url: "https://better-auth.example/ignored",
311
+ user: {email: "reset@example.com"},
312
+ })
313
+ ).rejects.toThrow("publicAppUrl is required to send recovery mail");
314
+ await expect(
315
+ hooks?.sendVerificationEmail({
316
+ token: "verify-token",
317
+ url: "https://better-auth.example/ignored",
318
+ user: {email: "verify@example.com"},
319
+ })
320
+ ).rejects.toThrow("publicAppUrl is required to send recovery mail");
321
+ assert.deepEqual(sent, []);
322
+ });
323
+ });
324
+
325
+ describe("applyJwtPasswordResetToBetterAuth", () => {
326
+ it("updates the Better Auth credential hash and drops sessions", async () => {
327
+ await setup;
328
+ const auth = createBetterAuth({
329
+ config: {
330
+ baseURL: "http://localhost:3000",
331
+ enabled: true,
332
+ secret: "test-secret-at-least-32-characters-long",
333
+ },
334
+ mongoClient: getClient(),
335
+ });
336
+ const created = await auth.api.signUpEmail({
337
+ body: {
338
+ email: "dual@example.com",
339
+ name: "Dual User",
340
+ password: "old-password-123",
341
+ },
342
+ });
343
+ const betterAuthId = created.user.id;
344
+ await applyJwtPasswordResetToBetterAuth(
345
+ auth,
346
+ {betterAuthId, email: "dual@example.com"},
347
+ "new-password-123"
348
+ );
349
+ await expect(
350
+ auth.api.signInEmail({
351
+ body: {email: "dual@example.com", password: "old-password-123"},
352
+ })
353
+ ).rejects.toThrow();
354
+ const signedIn = await auth.api.signInEmail({
355
+ body: {email: "dual@example.com", password: "new-password-123"},
356
+ });
357
+ assert.isDefined(signedIn.user);
358
+ });
359
+ });
360
+
361
+ describe("readPasswordFromBetterAuthResetRequest", () => {
362
+ it("reads newPassword from a JSON request body", async () => {
363
+ const request = new globalThis.Request("http://localhost/api/auth/reset-password", {
364
+ body: JSON.stringify({newPassword: "synced-password-123", token: "reset-token"}),
365
+ headers: {"Content-Type": "application/json"},
366
+ method: "POST",
367
+ });
368
+ const password = await readPasswordFromBetterAuthResetRequest(request);
369
+ assert.equal(password, "synced-password-123");
370
+ });
371
+ });
372
+
373
+ describe("applyBetterAuthPasswordResetToJwt", () => {
374
+ it("updates the JWT password and tokenEpoch", async () => {
375
+ await setup;
376
+ const registerable = DualAuthUser as unknown as {
377
+ authenticate: () => (
378
+ email: string,
379
+ password: string
380
+ ) => Promise<{user: unknown; error?: Error}>;
381
+ register: (
382
+ user: {betterAuthId: string; email: string},
383
+ password: string
384
+ ) => Promise<{tokenEpoch?: number}>;
385
+ };
386
+ await registerable.register(
387
+ {betterAuthId: "ba-dual-1", email: "dual-jwt@example.com"},
388
+ "old-password-123"
389
+ );
390
+ const request = new globalThis.Request("http://localhost/api/auth/reset-password", {
391
+ body: JSON.stringify({newPassword: "new-password-123"}),
392
+ headers: {"Content-Type": "application/json"},
393
+ method: "POST",
394
+ });
395
+ await applyBetterAuthPasswordResetToJwt(
396
+ DualAuthUser,
397
+ {email: "dual-jwt@example.com", id: "ba-dual-1"},
398
+ request
399
+ );
400
+ const authenticate = registerable.authenticate();
401
+ const oldPassword = await authenticate("dual-jwt@example.com", "old-password-123");
402
+ assert.isNotOk(oldPassword.user);
403
+ const newPassword = await authenticate("dual-jwt@example.com", "new-password-123");
404
+ assert.isDefined(newPassword.user);
405
+ const reloaded = await DualAuthUser.findOne({email: "dual-jwt@example.com"});
406
+ assert.equal(reloaded?.tokenEpoch, 1);
407
+ });
408
+
409
+ it("skips JWT sync when no app user exists", async () => {
410
+ await setup;
411
+ const request = new globalThis.Request("http://localhost/api/auth/reset-password", {
412
+ body: JSON.stringify({newPassword: "new-password-123"}),
413
+ headers: {"Content-Type": "application/json"},
414
+ method: "POST",
415
+ });
416
+ await applyBetterAuthPasswordResetToJwt(
417
+ DualAuthUser,
418
+ {email: "missing-jwt@example.com", id: "ba-missing"},
419
+ request
420
+ );
421
+ const missing = await DualAuthUser.findOne({email: "missing-jwt@example.com"});
422
+ assert.isNull(missing);
423
+ });
424
+
425
+ it("throws when the reset request does not carry a password", async () => {
426
+ await setup;
427
+ await DualAuthUser.create({
428
+ betterAuthId: "ba-dual-nopw",
429
+ email: "nopw-jwt@example.com",
430
+ });
431
+ const request = new globalThis.Request("http://localhost/api/auth/reset-password", {
432
+ body: JSON.stringify({token: "reset-token"}),
433
+ headers: {"Content-Type": "application/json"},
434
+ method: "POST",
435
+ });
436
+ await expect(
437
+ applyBetterAuthPasswordResetToJwt(
438
+ DualAuthUser,
439
+ {email: "nopw-jwt@example.com", id: "ba-dual-nopw"},
440
+ request
441
+ )
442
+ ).rejects.toThrow("Password reset could not sync to JWT credentials");
443
+ });
444
+ });
445
+
446
+ describe("readPasswordFromBetterAuthResetRequest edge cases", () => {
447
+ it("returns an empty string when there is no request", async () => {
448
+ assert.equal(await readPasswordFromBetterAuthResetRequest(undefined), "");
449
+ });
450
+
451
+ it("reads password from an already-parsed body", async () => {
452
+ assert.equal(
453
+ await readPasswordFromBetterAuthResetRequest({body: {password: "attached-pw"}}),
454
+ "attached-pw"
455
+ );
456
+ });
457
+
458
+ it("returns an empty string when the body is not an object and clone is unavailable", async () => {
459
+ assert.equal(await readPasswordFromBetterAuthResetRequest({body: "raw"}), "");
460
+ });
461
+
462
+ it("returns an empty string when the body has no string password", async () => {
463
+ assert.equal(await readPasswordFromBetterAuthResetRequest({body: {newPassword: 42}}), "");
464
+ });
465
+
466
+ it("returns an empty string when cloning the request fails to parse JSON", async () => {
467
+ const request = {
468
+ clone: () => ({
469
+ json: async (): Promise<unknown> => {
470
+ throw new Error("bad json");
471
+ },
472
+ }),
473
+ };
474
+ assert.equal(await readPasswordFromBetterAuthResetRequest(request), "");
475
+ });
476
+ });
477
+
478
+ describe("createBetterAuthEmailHooks fallback rendering", () => {
479
+ it("renders the built-in templates with interpolated links", async () => {
480
+ const sent: Array<{html?: string; subject: string; text: string; to: string}> = [];
481
+ const hooks = createBetterAuthEmailHooks({
482
+ enabled: true,
483
+ publicAppUrl: "https://app.example.com/",
484
+ sendMail: async (message) => {
485
+ sent.push(message);
486
+ },
487
+ });
488
+ assert.isDefined(hooks);
489
+ await hooks?.sendResetPassword({
490
+ token: "a b",
491
+ url: "ignored",
492
+ user: {email: "reset@example.com"},
493
+ });
494
+ await hooks?.sendVerificationEmail({
495
+ token: "v",
496
+ url: "ignored",
497
+ user: {email: "verify@example.com"},
498
+ });
499
+ assert.lengthOf(sent, 2);
500
+ assert.equal(sent[0].subject, "Reset your password");
501
+ assert.equal(sent[0].to, "reset@example.com");
502
+ assert.include(sent[0].text, "https://app.example.com/resetPassword?token=a%20b");
503
+ assert.include(sent[0].html ?? "", 'href="https://app.example.com/resetPassword?token=a%20b"');
504
+ assert.equal(sent[1].subject, "Verify your email");
505
+ assert.include(sent[1].text, "https://app.example.com/verifyEmail?token=v");
506
+ });
507
+
508
+ it("uses custom templates and tolerates missing html/text and unknown keys", async () => {
509
+ const sent: Array<{html?: string; subject: string; text: string; to: string}> = [];
510
+ const hooks = createBetterAuthEmailHooks({
511
+ authMailTemplates: {
512
+ resetPassword: {subject: "Reset for {{ publicAppUrl }} {{unknownKey}}"},
513
+ },
514
+ enabled: true,
515
+ publicAppUrl: "https://app.example.com",
516
+ sendMail: async (message) => {
517
+ sent.push(message);
518
+ },
519
+ });
520
+ await hooks?.sendResetPassword({
521
+ token: "t",
522
+ url: "ignored",
523
+ user: {email: "reset@example.com"},
524
+ });
525
+ assert.lengthOf(sent, 1);
526
+ assert.equal(sent[0].subject, "Reset for https://app.example.com ");
527
+ assert.isUndefined(sent[0].html);
528
+ assert.equal(sent[0].text, "");
529
+ });
530
+
531
+ it("returns undefined when sendMail is not configured", () => {
532
+ assert.isUndefined(createBetterAuthEmailHooks({enabled: true}));
533
+ });
534
+ });
535
+
536
+ describe("createBetterAuth email and password-reset wiring", () => {
537
+ const baseConfig: BetterAuthConfig = {
538
+ baseURL: "http://localhost:3000",
539
+ enabled: true,
540
+ secret: "test-secret-at-least-32-characters-long",
541
+ };
542
+
543
+ it("enables email verification when mail hooks are configured", async () => {
544
+ await setup;
545
+ const auth = createBetterAuth({
546
+ config: {
547
+ ...baseConfig,
548
+ publicAppUrl: "https://app.example.com",
549
+ sendMail: async () => {},
550
+ },
551
+ mongoClient: getClient(),
552
+ });
553
+ const options = (
554
+ auth as {
555
+ options?: {
556
+ emailAndPassword?: {sendResetPassword?: unknown};
557
+ emailVerification?: {sendOnSignUp?: boolean; sendVerificationEmail?: unknown};
558
+ };
559
+ }
560
+ ).options;
561
+ assert.isTrue(options?.emailVerification?.sendOnSignUp);
562
+ assert.isFunction(options?.emailVerification?.sendVerificationEmail);
563
+ assert.isFunction(options?.emailAndPassword?.sendResetPassword);
564
+ });
565
+
566
+ it("syncs the JWT password through the onPasswordReset hook", async () => {
567
+ await setup;
568
+ const auth = createBetterAuth({
569
+ config: baseConfig,
570
+ mongoClient: getClient(),
571
+ userModel: DualAuthUser,
572
+ });
573
+ const registerable = DualAuthUser as unknown as {
574
+ register: (user: {betterAuthId: string; email: string}, password: string) => Promise<unknown>;
575
+ };
576
+ await registerable.register(
577
+ {betterAuthId: "ba-hook-1", email: "hook@example.com"},
578
+ "old-password-123"
579
+ );
580
+ const options = (
581
+ auth as {
582
+ options?: {
583
+ emailAndPassword?: {
584
+ onPasswordReset?: (
585
+ data: {user: {email?: string; id?: string}},
586
+ request?: Request
587
+ ) => Promise<void>;
588
+ };
589
+ };
590
+ }
591
+ ).options;
592
+ const request = new globalThis.Request("http://localhost/api/auth/reset-password", {
593
+ body: JSON.stringify({newPassword: "hooked-password-123"}),
594
+ headers: {"Content-Type": "application/json"},
595
+ method: "POST",
596
+ });
597
+ await options?.emailAndPassword?.onPasswordReset?.(
598
+ {user: {email: "hook@example.com", id: "ba-hook-1"}},
599
+ request as unknown as Request
600
+ );
601
+ const reloaded = await DualAuthUser.findOne({email: "hook@example.com"});
602
+ assert.equal(reloaded?.tokenEpoch, 1);
603
+ });
604
+ });
605
+
606
+ describe("applyJwtPasswordResetToBetterAuth lookups", () => {
607
+ const makeAuth = (): BetterAuthInstance =>
608
+ createBetterAuth({
609
+ config: {
610
+ baseURL: "http://localhost:3000",
611
+ enabled: true,
612
+ secret: "test-secret-at-least-32-characters-long",
613
+ },
614
+ mongoClient: getClient(),
615
+ });
616
+
617
+ it("finds the Better Auth user by email when betterAuthId is missing", async () => {
618
+ await setup;
619
+ const auth = makeAuth();
620
+ await auth.api.signUpEmail({
621
+ body: {email: "by-email@example.com", name: "By Email", password: "old-password-123"},
622
+ });
623
+ await applyJwtPasswordResetToBetterAuth(
624
+ auth,
625
+ {email: "by-email@example.com"},
626
+ "new-password-123"
627
+ );
628
+ const signedIn = await auth.api.signInEmail({
629
+ body: {email: "by-email@example.com", password: "new-password-123"},
630
+ });
631
+ assert.isDefined(signedIn.user);
632
+ });
633
+
634
+ it("falls back to findUserById and no-ops when the user does not exist", async () => {
635
+ await setup;
636
+ const auth = makeAuth();
637
+ const ctx = (await auth.$context) as {
638
+ internalAdapter: {
639
+ findUserByEmail: (email: string) => Promise<unknown>;
640
+ findUserById: (id: string) => Promise<unknown>;
641
+ };
642
+ };
643
+ const emailCalls: string[] = [];
644
+ const idCalls: string[] = [];
645
+ ctx.internalAdapter.findUserByEmail = async (email: string): Promise<null> => {
646
+ emailCalls.push(email);
647
+ return null;
648
+ };
649
+ ctx.internalAdapter.findUserById = async (id: string): Promise<null> => {
650
+ idCalls.push(id);
651
+ return null;
652
+ };
653
+ await applyJwtPasswordResetToBetterAuth(
654
+ auth,
655
+ {betterAuthId: "", email: "ghost@example.com"},
656
+ "new-password-123"
657
+ );
658
+ assert.deepEqual(emailCalls, ["ghost@example.com"]);
659
+ assert.deepEqual(idCalls, []);
660
+ });
661
+
662
+ it("creates a credential account when the user only has a social account", async () => {
663
+ await setup;
664
+ const auth = makeAuth();
665
+ const ctx = (await auth.$context) as {
666
+ internalAdapter: {
667
+ createUser: (user: {email: string; emailVerified: boolean; name: string}) => Promise<{
668
+ id: string;
669
+ }>;
670
+ findAccounts: (userId: string) => Promise<Array<{providerId?: string}>>;
671
+ };
672
+ };
673
+ const created = await ctx.internalAdapter.createUser({
674
+ email: "social@example.com",
675
+ emailVerified: true,
676
+ name: "Social",
677
+ });
678
+ await applyJwtPasswordResetToBetterAuth(auth, {betterAuthId: created.id}, "new-password-123");
679
+ const accounts = await ctx.internalAdapter.findAccounts(created.id);
680
+ assert.isTrue(accounts.some((account) => account.providerId === "credential"));
681
+ const signedIn = await auth.api.signInEmail({
682
+ body: {email: "social@example.com", password: "new-password-123"},
683
+ });
684
+ assert.isDefined(signedIn.user);
685
+ });
180
686
  });
181
687
 
182
688
  describe("syncBetterAuthUser", () => {
@@ -194,7 +700,7 @@ describe("syncBetterAuthUser", () => {
194
700
  it("creates a new user when none exists", async () => {
195
701
  await setup;
196
702
  const baUser = makeBetterAuthUser();
197
- const result = await syncBetterAuthUser(TestUser as UserModel, baUser);
703
+ const result = await syncBetterAuthUser(TestUser, baUser);
198
704
 
199
705
  expect(result).toBeDefined();
200
706
  expect(result.email).toBe("test@example.com");
@@ -203,6 +709,28 @@ describe("syncBetterAuthUser", () => {
203
709
  expect(result.admin).toBe(false);
204
710
  });
205
711
 
712
+ it("creates a user on a strict-throw schema that omits oauthProvider", async () => {
713
+ await setup;
714
+ const baUser = makeBetterAuthUser({email: "strict@example.com"});
715
+ const result = await syncBetterAuthUser(StrictUser, baUser);
716
+
717
+ assert.equal(result.email, "strict@example.com");
718
+ assert.equal(result.betterAuthId, "ba-user-123");
719
+ const saved = await StrictUser.findOne({email: "strict@example.com"}).lean();
720
+ assert.isOk(saved);
721
+ assert.notProperty(saved, "oauthProvider");
722
+ });
723
+
724
+ it("sets oauthProvider on create when a provider is passed", async () => {
725
+ await setup;
726
+ const baUser = makeBetterAuthUser({email: "oauth-create@example.com"});
727
+ const result = await syncBetterAuthUser(TestUser, baUser, "google");
728
+
729
+ assert.equal(result.oauthProvider, "google");
730
+ const saved = await TestUser.findOne({email: "oauth-create@example.com"}).lean();
731
+ assert.equal(saved.oauthProvider, "google");
732
+ });
733
+
206
734
  it("updates an existing user matched by betterAuthId", async () => {
207
735
  await setup;
208
736
  await TestUser.create({
@@ -212,7 +740,7 @@ describe("syncBetterAuthUser", () => {
212
740
  });
213
741
 
214
742
  const baUser = makeBetterAuthUser({email: "new@example.com", name: "New Name"});
215
- const result = await syncBetterAuthUser(TestUser as UserModel, baUser);
743
+ const result = await syncBetterAuthUser(TestUser, baUser);
216
744
 
217
745
  expect(result.email).toBe("new@example.com");
218
746
  expect(result.name).toBe("New Name");
@@ -230,7 +758,7 @@ describe("syncBetterAuthUser", () => {
230
758
  });
231
759
 
232
760
  const baUser = makeBetterAuthUser();
233
- const result = await syncBetterAuthUser(TestUser as UserModel, baUser);
761
+ const result = await syncBetterAuthUser(TestUser, baUser);
234
762
 
235
763
  expect(result.betterAuthId).toBe("ba-user-123");
236
764
  expect(result.email).toBe("test@example.com");
@@ -247,7 +775,7 @@ describe("syncBetterAuthUser", () => {
247
775
  });
248
776
 
249
777
  const baUser = makeBetterAuthUser();
250
- const result = await syncBetterAuthUser(TestUser as UserModel, baUser, "google");
778
+ const result = await syncBetterAuthUser(TestUser, baUser, "google");
251
779
 
252
780
  expect(result.oauthProvider).toBe("google");
253
781
  });
@@ -255,7 +783,7 @@ describe("syncBetterAuthUser", () => {
255
783
  it("uses email prefix as name when name is null", async () => {
256
784
  await setup;
257
785
  const baUser = makeBetterAuthUser({name: null});
258
- const result = await syncBetterAuthUser(TestUser as UserModel, baUser);
786
+ const result = await syncBetterAuthUser(TestUser, baUser);
259
787
 
260
788
  expect(result.name).toBe("test");
261
789
  });
@@ -269,7 +797,7 @@ describe("syncBetterAuthUser", () => {
269
797
  });
270
798
 
271
799
  const baUser = makeBetterAuthUser({name: null});
272
- const result = await syncBetterAuthUser(TestUser as UserModel, baUser);
800
+ const result = await syncBetterAuthUser(TestUser, baUser);
273
801
 
274
802
  expect(result.name).toBe("Keep This Name");
275
803
  });
@@ -299,8 +827,8 @@ describe("createBetterAuthSessionMiddleware", () => {
299
827
 
300
828
  const auth = createBetterAuth({config, mongoClient: getClient()});
301
829
  const middleware = createBetterAuthSessionMiddleware(auth);
302
- const req = {headers: {}} as any;
303
- const res = {} as any;
830
+ const req = makeReq();
831
+ const res = makeRes();
304
832
  const next = mock(() => {});
305
833
 
306
834
  await middleware(req, res, next);
@@ -321,13 +849,13 @@ describe("createBetterAuthSessionMiddleware", () => {
321
849
 
322
850
  // Override getSession to throw
323
851
  const origGetSession = auth.api.getSession;
324
- (auth.api as any).getSession = () => {
852
+ setGetSession(auth, () => {
325
853
  throw new Error("Session error");
326
- };
854
+ });
327
855
 
328
856
  const middleware = createBetterAuthSessionMiddleware(auth);
329
- const req = {headers: {}} as any;
330
- const res = {} as any;
857
+ const req = makeReq();
858
+ const res = makeRes();
331
859
  const next = mock(() => {});
332
860
 
333
861
  await middleware(req, res, next);
@@ -335,7 +863,7 @@ describe("createBetterAuthSessionMiddleware", () => {
335
863
  expect(next).toHaveBeenCalledTimes(1);
336
864
  expect(req.user).toBeUndefined();
337
865
 
338
- (auth.api as any).getSession = origGetSession;
866
+ setGetSession(auth, origGetSession);
339
867
  });
340
868
 
341
869
  it("attaches basic user data when no userModel is provided", async () => {
@@ -358,11 +886,11 @@ describe("createBetterAuthSessionMiddleware", () => {
358
886
  };
359
887
 
360
888
  // Override getSession to return mock session
361
- (auth.api as any).getSession = async () => mockSession;
889
+ setGetSession(auth, async () => mockSession);
362
890
 
363
891
  const middleware = createBetterAuthSessionMiddleware(auth);
364
- const req = {headers: {}} as any;
365
- const res = {} as any;
892
+ const req = makeReq();
893
+ const res = makeRes();
366
894
  const next = mock(() => {});
367
895
 
368
896
  await middleware(req, res, next);
@@ -401,11 +929,11 @@ describe("createBetterAuthSessionMiddleware", () => {
401
929
  },
402
930
  };
403
931
 
404
- (auth.api as any).getSession = async () => mockSession;
932
+ setGetSession(auth, async () => mockSession);
405
933
 
406
- const middleware = createBetterAuthSessionMiddleware(auth, TestUser as UserModel);
407
- const req = {headers: {}} as any;
408
- const res = {} as any;
934
+ const middleware = createBetterAuthSessionMiddleware(auth, TestUser);
935
+ const req = makeReq();
936
+ const res = makeRes();
409
937
  const next = mock(() => {});
410
938
 
411
939
  await middleware(req, res, next);
@@ -435,11 +963,11 @@ describe("createBetterAuthSessionMiddleware", () => {
435
963
  },
436
964
  };
437
965
 
438
- (auth.api as any).getSession = async () => mockSession;
966
+ setGetSession(auth, async () => mockSession);
439
967
 
440
- const middleware = createBetterAuthSessionMiddleware(auth, TestUser as UserModel);
441
- const req = {headers: {}} as any;
442
- const res = {} as any;
968
+ const middleware = createBetterAuthSessionMiddleware(auth, TestUser);
969
+ const req = makeReq();
970
+ const res = makeRes();
443
971
  const next = mock(() => {});
444
972
 
445
973
  await middleware(req, res, next);
@@ -547,25 +1075,27 @@ describe("getMongoClientFromMongoose", () => {
547
1075
 
548
1076
  describe("getBetterAuthSession", () => {
549
1077
  it("returns null when no session is set", () => {
550
- const req = {} as any;
1078
+ const req = makeReq();
551
1079
  expect(getBetterAuthSession(req)).toBeNull();
552
1080
  });
553
1081
 
554
1082
  it("returns session data when set", () => {
555
- const sessionData = {session: {id: "s1"}, user: {id: "u1"}} as any;
556
- const req = {betterAuthSession: sessionData} as any;
1083
+ const sessionData = {session: {id: "s1"}, user: {id: "u1"}} as unknown as BetterAuthSessionData;
1084
+ const req = makeReq({betterAuthSession: sessionData});
557
1085
  expect(getBetterAuthSession(req)).toBe(sessionData);
558
1086
  });
559
1087
  });
560
1088
 
561
1089
  describe("hasBetterAuthSession", () => {
562
1090
  it("returns false when no session is set", () => {
563
- const req = {} as any;
1091
+ const req = makeReq();
564
1092
  expect(hasBetterAuthSession(req)).toBe(false);
565
1093
  });
566
1094
 
567
1095
  it("returns true when session is set", () => {
568
- const req = {betterAuthSession: {session: {}, user: {}}} as any;
1096
+ const req = makeReq({
1097
+ betterAuthSession: {session: {}, user: {}} as unknown as BetterAuthSessionData,
1098
+ });
569
1099
  expect(hasBetterAuthSession(req)).toBe(true);
570
1100
  });
571
1101
  });
@@ -581,6 +1111,6 @@ describe("setupBetterAuthUserSync", () => {
581
1111
 
582
1112
  const auth = createBetterAuth({config, mongoClient: getClient()});
583
1113
 
584
- expect(() => setupBetterAuthUserSync(auth, TestUser as UserModel)).not.toThrow();
1114
+ expect(() => setupBetterAuthUserSync(auth, TestUser)).not.toThrow();
585
1115
  });
586
1116
  });