@terreno/api 57.19.2 → 57.21.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 (259) hide show
  1. package/CHANGELOG.md +443 -0
  2. package/biome.jsonc +1 -0
  3. package/dist/accountSecurity/accessActions.d.ts +38 -0
  4. package/dist/accountSecurity/accessActions.js +157 -0
  5. package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
  6. package/dist/accountSecurity/accountSecurityApp.js +438 -0
  7. package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
  8. package/dist/accountSecurity/accountSecurityService.js +481 -0
  9. package/dist/accountSecurity/credentialActions.d.ts +16 -0
  10. package/dist/accountSecurity/credentialActions.js +189 -0
  11. package/dist/accountSecurity/membershipActions.d.ts +15 -0
  12. package/dist/accountSecurity/membershipActions.js +81 -0
  13. package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
  14. package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
  15. package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
  16. package/dist/accountSecurity/securityEventHooks.js +223 -0
  17. package/dist/accountSecurity/securityEvents.d.ts +162 -0
  18. package/dist/accountSecurity/securityEvents.js +114 -0
  19. package/dist/accountSecurity/securityNotifications.d.ts +125 -0
  20. package/dist/accountSecurity/securityNotifications.js +333 -0
  21. package/dist/api.d.ts +3 -3
  22. package/dist/api.js +38 -6
  23. package/dist/audit/auditEventModel.d.ts +5 -3
  24. package/dist/audit/auditEventModel.js +8 -6
  25. package/dist/audit/processQueue.js +4 -2
  26. package/dist/audit/record.d.ts +2 -2
  27. package/dist/audit/record.js +3 -0
  28. package/dist/authRecovery.js +29 -1
  29. package/dist/betterAuth.d.ts +179 -10
  30. package/dist/betterAuthApp.d.ts +15 -0
  31. package/dist/betterAuthApp.js +23 -0
  32. package/dist/betterAuthChallengeHeaders.d.ts +37 -0
  33. package/dist/betterAuthChallengeHeaders.js +180 -0
  34. package/dist/betterAuthFeatures.d.ts +54 -0
  35. package/dist/betterAuthFeatures.js +239 -0
  36. package/dist/betterAuthMethods.d.ts +73 -0
  37. package/dist/betterAuthMethods.js +55 -0
  38. package/dist/betterAuthOAuthHandoff.d.ts +10 -2
  39. package/dist/betterAuthOAuthHandoff.js +222 -24
  40. package/dist/betterAuthSetPassword.d.ts +33 -0
  41. package/dist/betterAuthSetPassword.js +166 -0
  42. package/dist/betterAuthSetup.d.ts +57 -8
  43. package/dist/betterAuthSetup.js +327 -36
  44. package/dist/consentApp.d.ts +9 -4
  45. package/dist/consentApp.js +344 -28
  46. package/dist/consentStatus.d.ts +60 -0
  47. package/dist/consentStatus.js +111 -0
  48. package/dist/errors.d.ts +6 -0
  49. package/dist/errors.js +41 -2
  50. package/dist/expressServer.js +3 -2
  51. package/dist/frameworkModelNames.d.ts +4 -0
  52. package/dist/frameworkModelNames.js +4 -0
  53. package/dist/index.d.ts +18 -2
  54. package/dist/index.js +29 -3
  55. package/dist/mcp/adminTracking.d.ts +28 -0
  56. package/dist/mcp/adminTracking.js +80 -0
  57. package/dist/mcp/auth.d.ts +6 -0
  58. package/dist/mcp/auth.js +12 -2
  59. package/dist/mcp/oauth.js +151 -11
  60. package/dist/mcp/oauthMetadata.d.ts +2 -1
  61. package/dist/mcp/oauthMetadata.js +7 -4
  62. package/dist/mcp/server.d.ts +8 -0
  63. package/dist/mcp/server.js +48 -4
  64. package/dist/models/consentResponse.js +51 -0
  65. package/dist/models/mcpOAuthClient.js +78 -2
  66. package/dist/models/mcpOAuthToken.js +55 -4
  67. package/dist/models/mcpRequestLog.d.ts +2 -0
  68. package/dist/models/mcpRequestLog.js +73 -0
  69. package/dist/models/mcpServiceToken.js +4 -0
  70. package/dist/models/mcpToolSetting.d.ts +2 -0
  71. package/dist/models/mcpToolSetting.js +119 -0
  72. package/dist/models/versionConfig.d.ts +2 -0
  73. package/dist/orgs/membershipGuards.d.ts +7 -0
  74. package/dist/orgs/membershipGuards.js +32 -0
  75. package/dist/orgs/orgsApp.d.ts +19 -1
  76. package/dist/orgs/orgsApp.js +55 -24
  77. package/dist/rateLimit/policies.js +8 -0
  78. package/dist/rbac/access.js +2 -1
  79. package/dist/rbac/auditModel.d.ts +2 -1
  80. package/dist/rbac/resolve.d.ts +9 -1
  81. package/dist/rbac/resolve.js +21 -16
  82. package/dist/rbac/roleManager.d.ts +6 -0
  83. package/dist/rbac/roleManager.js +8 -7
  84. package/dist/rbac/roleModel.d.ts +1 -0
  85. package/dist/rbac/roleModel.js +45 -3
  86. package/dist/rbac/statements.d.ts +2 -2
  87. package/dist/rbac/statements.js +10 -1
  88. package/dist/rbac/types.d.ts +6 -0
  89. package/dist/rbac/userWriteGuards.js +2 -1
  90. package/dist/schemaMetadata.js +8 -1
  91. package/dist/seedRunner.js +7 -2
  92. package/dist/terrenoApp.d.ts +16 -0
  93. package/dist/terrenoApp.js +18 -0
  94. package/dist/tests/models.d.ts +22 -22
  95. package/dist/tests/models.js +15 -1
  96. package/dist/tests/testHelper.d.ts +6 -12
  97. package/dist/tests.d.ts +1 -0
  98. package/dist/tests.js +3 -1
  99. package/dist/types/consentResponse.d.ts +8 -0
  100. package/dist/types/mcpAdmin.d.ts +58 -0
  101. package/dist/types/mcpAdmin.js +2 -0
  102. package/dist/types/mcpOAuth.d.ts +37 -2
  103. package/dist/types/mcpServiceToken.d.ts +2 -0
  104. package/e2e/smoke.ts +193 -0
  105. package/package.json +10 -5
  106. package/src/__snapshots__/openApi.test.ts.snap +288 -0
  107. package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
  108. package/src/accountSecurity/accessActions.test.ts +723 -0
  109. package/src/accountSecurity/accessActions.ts +173 -0
  110. package/src/accountSecurity/accountSecurity.test.ts +947 -0
  111. package/src/accountSecurity/accountSecurityApp.ts +720 -0
  112. package/src/accountSecurity/accountSecurityService.ts +826 -0
  113. package/src/accountSecurity/credentialActions.test.ts +867 -0
  114. package/src/accountSecurity/credentialActions.ts +260 -0
  115. package/src/accountSecurity/membershipActions.ts +89 -0
  116. package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
  117. package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
  118. package/src/accountSecurity/securityEventHooks.ts +294 -0
  119. package/src/accountSecurity/securityEvents.ts +165 -0
  120. package/src/accountSecurity/securityNotifications.test.ts +1323 -0
  121. package/src/accountSecurity/securityNotifications.ts +516 -0
  122. package/src/adminModelRouter.test.ts +8 -6
  123. package/src/api.arrayOperations.test.ts +102 -22
  124. package/src/api.hooks.test.ts +12 -11
  125. package/src/api.query.test.ts +2 -2
  126. package/src/api.test.ts +8 -7
  127. package/src/api.ts +41 -10
  128. package/src/audit/auditApp.test.ts +1 -1
  129. package/src/audit/auditEventModel.ts +10 -7
  130. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  131. package/src/audit/processQueue.ts +4 -2
  132. package/src/audit/record.test.ts +15 -0
  133. package/src/audit/record.ts +10 -2
  134. package/src/auth.test.ts +21 -7
  135. package/src/authRecovery.test.ts +33 -10
  136. package/src/authRecovery.ts +34 -1
  137. package/src/authRecoveryBetterAuth.test.ts +169 -0
  138. package/src/authVerification.test.ts +7 -7
  139. package/src/betterAuth.ts +194 -8
  140. package/src/betterAuthApp.ts +32 -0
  141. package/src/betterAuthChallengeHeaders.test.ts +476 -0
  142. package/src/betterAuthChallengeHeaders.ts +227 -0
  143. package/src/betterAuthFeatures.test.ts +490 -0
  144. package/src/betterAuthFeatures.ts +283 -0
  145. package/src/betterAuthLinking.test.ts +846 -0
  146. package/src/betterAuthMethods.test.ts +138 -0
  147. package/src/betterAuthMethods.ts +98 -0
  148. package/src/betterAuthOAuthHandoff.test.ts +482 -69
  149. package/src/betterAuthOAuthHandoff.ts +293 -33
  150. package/src/betterAuthOAuthProxy.test.ts +421 -0
  151. package/src/betterAuthPasswordReset.test.ts +190 -0
  152. package/src/betterAuthSetPassword.test.ts +378 -0
  153. package/src/betterAuthSetPassword.ts +213 -0
  154. package/src/betterAuthSetup.test.ts +115 -57
  155. package/src/betterAuthSetup.ts +457 -38
  156. package/src/collectionRegistry.test.ts +4 -4
  157. package/src/consentApp.test.ts +869 -2
  158. package/src/consentApp.ts +438 -36
  159. package/src/consentStatus.test.ts +226 -0
  160. package/src/consentStatus.ts +171 -0
  161. package/src/errors.test.ts +81 -0
  162. package/src/errors.ts +50 -1
  163. package/src/expressServer.test.ts +29 -0
  164. package/src/expressServer.ts +3 -2
  165. package/src/frameworkModelNames.test.ts +8 -0
  166. package/src/frameworkModelNames.ts +4 -0
  167. package/src/githubAuth.test.ts +11 -11
  168. package/src/index.ts +38 -0
  169. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  170. package/src/mcp/actionTools.test.ts +11 -5
  171. package/src/mcp/adminTracking.test.ts +272 -0
  172. package/src/mcp/adminTracking.ts +104 -0
  173. package/src/mcp/auth.ts +18 -2
  174. package/src/mcp/oauth.test.ts +463 -2
  175. package/src/mcp/oauth.ts +184 -13
  176. package/src/mcp/oauthMetadata.ts +5 -2
  177. package/src/mcp/server.ts +67 -4
  178. package/src/mcp/serviceTokens.test.ts +2 -1
  179. package/src/mcp/toolGenerator.test.ts +9 -5
  180. package/src/migrations/cli.test.ts +15 -14
  181. package/src/migrations/cli.ts +1 -1
  182. package/src/migrations/generate.test.ts +2 -2
  183. package/src/migrations/load.test.ts +1 -1
  184. package/src/migrations/lock.test.ts +8 -3
  185. package/src/migrations/runner.test.ts +16 -5
  186. package/src/migrations/schemaCatalog.test.ts +4 -1
  187. package/src/models/consentResponse.ts +53 -0
  188. package/src/models/mcpOAuthClient.ts +100 -3
  189. package/src/models/mcpOAuthToken.test.ts +42 -0
  190. package/src/models/mcpOAuthToken.ts +62 -5
  191. package/src/models/mcpRequestLog.ts +81 -0
  192. package/src/models/mcpServiceToken.test.ts +23 -0
  193. package/src/models/mcpServiceToken.ts +10 -0
  194. package/src/models/mcpToolSetting.test.ts +69 -0
  195. package/src/models/mcpToolSetting.ts +138 -0
  196. package/src/models/versionConfig.ts +2 -0
  197. package/src/notifications/notificationsApp.test.ts +5 -8
  198. package/src/notifiers/slackWebApi.test.ts +30 -8
  199. package/src/openApi.test.ts +4 -4
  200. package/src/openApiValidator.test.ts +3 -3
  201. package/src/orgs/membershipGuards.ts +39 -0
  202. package/src/orgs/orgPermissions.test.ts +2 -2
  203. package/src/orgs/orgPlugin.test.ts +4 -3
  204. package/src/orgs/orgRbac.test.ts +1 -1
  205. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  206. package/src/orgs/organizationSettings.test.ts +1 -1
  207. package/src/orgs/orgsApp.test.ts +104 -3
  208. package/src/orgs/orgsApp.ts +69 -28
  209. package/src/permissions.test.ts +2 -2
  210. package/src/rateLimit/policies.test.ts +53 -0
  211. package/src/rateLimit/policies.ts +8 -0
  212. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  213. package/src/rbac/access.ts +4 -1
  214. package/src/rbac/assertAllowed.test.ts +1 -1
  215. package/src/rbac/auditModel.ts +10 -2
  216. package/src/rbac/realtimeAccess.test.ts +3 -2
  217. package/src/rbac/resolve.test.ts +65 -0
  218. package/src/rbac/resolve.ts +37 -17
  219. package/src/rbac/roleManager.test.ts +64 -0
  220. package/src/rbac/roleManager.ts +15 -6
  221. package/src/rbac/roleModel.test.ts +174 -1
  222. package/src/rbac/roleModel.ts +66 -3
  223. package/src/rbac/routes.test.ts +58 -0
  224. package/src/rbac/statements.test.ts +4 -1
  225. package/src/rbac/statements.ts +11 -1
  226. package/src/rbac/types.ts +6 -1
  227. package/src/rbac/userWriteGuards.test.ts +56 -5
  228. package/src/rbac/userWriteGuards.ts +5 -2
  229. package/src/realtime/realtime.test.ts +35 -31
  230. package/src/schemaMetadata.test.ts +39 -0
  231. package/src/schemaMetadata.ts +11 -1
  232. package/src/scrubAdminFields.test.ts +1 -1
  233. package/src/seedRunner.test.ts +56 -0
  234. package/src/seedRunner.ts +7 -2
  235. package/src/sync/adminWindowMutation.test.ts +4 -3
  236. package/src/sync/executors.test.ts +1 -1
  237. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  238. package/src/sync/sync.test.ts +1 -1
  239. package/src/sync/syncPhaseC.test.ts +14 -11
  240. package/src/sync/syncRoutes.test.ts +8 -8
  241. package/src/sync/syncSeqPlugin.test.ts +1 -2
  242. package/src/sync/syncSocket.test.ts +5 -4
  243. package/src/terrenoApp.mcpServiceTokens.test.ts +2 -2
  244. package/src/terrenoApp.migrations.test.ts +8 -7
  245. package/src/terrenoApp.ts +34 -0
  246. package/src/tests/accountSecurityTestApp.ts +290 -0
  247. package/src/tests/betterAuthStubs.ts +189 -0
  248. package/src/tests/bunSetup.ts +1 -1
  249. package/src/tests/mockOidcProvider.ts +105 -0
  250. package/src/tests/models.ts +23 -0
  251. package/src/tests/softwareAuthenticator.ts +183 -0
  252. package/src/tests/testEnv.ts +7 -0
  253. package/src/tests.ts +1 -0
  254. package/src/types/consentResponse.ts +8 -0
  255. package/src/types/mcpAdmin.ts +80 -0
  256. package/src/types/mcpOAuth.ts +44 -3
  257. package/src/types/mcpServiceToken.ts +5 -0
  258. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  259. package/tsconfig.typecheck.json +14 -0
@@ -7,16 +7,30 @@
7
7
 
8
8
  import {type BetterAuthOptions, type BetterAuthPlugin, betterAuth} from "better-auth";
9
9
  import {mongodbAdapter} from "better-auth/adapters/mongodb";
10
- import {createAuthMiddleware} from "better-auth/api";
10
+ import {APIError as BetterAuthAPIError, createAuthMiddleware} from "better-auth/api";
11
11
  import {toNodeHandler} from "better-auth/node";
12
12
  import {bearer} from "better-auth/plugins";
13
13
  import type {Application, NextFunction, Request, Response} from "express";
14
14
  import mergeWith from "lodash/mergeWith";
15
15
  import type {Db} from "mongodb";
16
16
  import mongoose from "mongoose";
17
+ import {
18
+ createSecurityEventsPlugin,
19
+ recordSelfSecurityAction,
20
+ } from "./accountSecurity/securityEventHooks";
17
21
  import {type HasSetPassword, setPasswordForUser, type UserModel} from "./auth";
18
22
  import type {BetterAuthConfig, BetterAuthSessionData, BetterAuthUser} from "./betterAuth";
23
+ import {
24
+ buildFeatureOptions,
25
+ buildFeaturePlugins,
26
+ createLinkingDisabledPlugin,
27
+ createSignUpClosedPlugin,
28
+ isSignUpClosed,
29
+ resolveAppleProvider,
30
+ } from "./betterAuthFeatures";
31
+ import {createMethodsPlugin} from "./betterAuthMethods";
19
32
  import {createOAuthHandoffPlugins} from "./betterAuthOAuthHandoff";
33
+ import {createSetPasswordPlugin} from "./betterAuthSetPassword";
20
34
  import {APIError, isAPIError} from "./errors";
21
35
  import type {AuthRecoveryMail, BetterAuthPasswordCheck} from "./expressServer";
22
36
  import {logger} from "./logger";
@@ -36,6 +50,15 @@ export interface MongoClientLike {
36
50
  db: () => Db;
37
51
  }
38
52
 
53
+ // One entry of Better Auth's `socialProviders` as Terreno builds it.
54
+ interface SocialProviderConfig {
55
+ appBundleIdentifier?: string;
56
+ clientId: string;
57
+ clientSecret: string;
58
+ disableImplicitSignUp?: boolean;
59
+ disableSignUp?: boolean;
60
+ }
61
+
39
62
  export interface CreateBetterAuthOptions {
40
63
  config: BetterAuthConfig;
41
64
  mongoClient: MongoClientLike;
@@ -60,6 +83,13 @@ const interpolateMail = (value: string, data: Record<string, string>): string =>
60
83
  return data[key] ?? "";
61
84
  });
62
85
 
86
+ /**
87
+ * The app page that finishes a Better Auth password reset: `{publicAppUrl}/resetPassword?token=`.
88
+ * The built-in reset mail and the admin sign-in link both point here.
89
+ */
90
+ export const betterAuthResetPasswordUrl = (publicAppUrl: string, token: string): string =>
91
+ `${publicAppUrl.replace(/\/$/, "")}/resetPassword?token=${encodeURIComponent(token)}`;
92
+
63
93
  const fallbackRenderAuthMail = ({
64
94
  publicAppUrl,
65
95
  templateId,
@@ -73,7 +103,7 @@ const fallbackRenderAuthMail = ({
73
103
  }): {html?: string; subject: string; text?: string} => {
74
104
  const template = templates?.[templateId] ?? FALLBACK_AUTH_MAIL[templateId];
75
105
  const base = publicAppUrl.replace(/\/$/, "");
76
- const resetUrl = `${base}/resetPassword?token=${encodeURIComponent(token)}`;
106
+ const resetUrl = betterAuthResetPasswordUrl(base, token);
77
107
  const verifyUrl = `${base}/verifyEmail?token=${encodeURIComponent(token)}`;
78
108
  const data = {publicAppUrl: base, resetUrl, token, verifyUrl};
79
109
  return {
@@ -182,27 +212,30 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
182
212
 
183
213
  const basePath = config.basePath ?? "/api/auth";
184
214
 
185
- const socialProviders: Record<string, {clientId: string; clientSecret: string}> = {};
215
+ const isClosed = isSignUpClosed(config);
216
+ const socialProviders: Record<string, SocialProviderConfig> = {};
217
+ const addSocialProvider = (id: string, provider: SocialProviderConfig): void => {
218
+ socialProviders[id] = isClosed
219
+ ? {...provider, disableImplicitSignUp: true, disableSignUp: true}
220
+ : provider;
221
+ };
186
222
 
187
223
  if (config.googleOAuth) {
188
- socialProviders.google = {
224
+ addSocialProvider("google", {
189
225
  clientId: config.googleOAuth.clientId,
190
226
  clientSecret: config.googleOAuth.clientSecret,
191
- };
227
+ });
192
228
  }
193
229
 
194
230
  if (config.appleOAuth) {
195
- socialProviders.apple = {
196
- clientId: config.appleOAuth.clientId,
197
- clientSecret: config.appleOAuth.clientSecret,
198
- };
231
+ addSocialProvider("apple", resolveAppleProvider(config.appleOAuth));
199
232
  }
200
233
 
201
234
  if (config.githubOAuth) {
202
- socialProviders.github = {
235
+ addSocialProvider("github", {
203
236
  clientId: config.githubOAuth.clientId,
204
237
  clientSecret: config.githubOAuth.clientSecret,
205
- };
238
+ });
206
239
  }
207
240
 
208
241
  const emailHooks = createBetterAuthEmailHooks(config);
@@ -231,7 +264,17 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
231
264
  {user}: {user: {email?: string; id?: string}},
232
265
  request?: PasswordResetRequestLike
233
266
  ): Promise<void> => {
234
- await applyBetterAuthPasswordResetToJwt(userModel, user, request);
267
+ await applyBetterAuthPasswordResetToJwt(
268
+ userModel,
269
+ user,
270
+ request,
271
+ passwordFromUnknown(currentBetterAuthEndpointBody())
272
+ );
273
+ await recordSelfSecurityAction({
274
+ action: "password-reset",
275
+ betterAuthUserId: user.id,
276
+ userModel,
277
+ });
235
278
  },
236
279
  }
237
280
  : {}),
@@ -259,7 +302,18 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
259
302
  // Arrays from `options` replace Terreno's; lodash would otherwise merge them by index.
260
303
  const replaceArrays = (_target: unknown, source: unknown): unknown =>
261
304
  Array.isArray(source) ? source : undefined;
262
- const merged: BetterAuthOptions = mergeWith({}, defaults, config.options, replaceArrays);
305
+ // Feature options (account linking, closed sign-up) sit between Terreno's defaults and
306
+ // `config.options`, so an explicit option still wins.
307
+ const merged: BetterAuthOptions = mergeWith(
308
+ {},
309
+ defaults,
310
+ buildFeatureOptions(config),
311
+ config.options,
312
+ replaceArrays
313
+ );
314
+
315
+ // `never` linking (or `options` turning linking off) refuses `/link-social` up front.
316
+ const isLinkingDisabled = merged.account?.accountLinking?.enabled === false;
263
317
 
264
318
  // The handoff hook mints tokens through `auth.api`, which exists only once betterAuth() returns.
265
319
  let auth: BetterAuthInstance | undefined;
@@ -268,6 +322,7 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
268
322
  apiOrigin: apiOriginOf(typeof merged.baseURL === "string" ? merged.baseURL : baseURL),
269
323
  config: config.oauthHandoff,
270
324
  getAuth: () => auth,
325
+ isLinkingDisabled,
271
326
  })
272
327
  : [];
273
328
 
@@ -280,9 +335,30 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
280
335
  // websocket handshakes (RealtimeApp's Better Auth socket validator forwards the handshake
281
336
  // token as a bearer header) — without it, a raw session token cannot be validated and
282
337
  // socket auth silently fails (the sync client shows perpetually "offline").
338
+ // The methods plugin serves `GET {basePath}/terreno/methods` for login screens, and the
339
+ // set-password plugin serves `POST {basePath}/terreno/set-password` for security screens.
340
+ // With a user model, the app user sync plugin links or creates the app User as each session
341
+ // is created (see createAppUserSyncPlugin), and the security events plugin records the
342
+ // user's own security changes (see createSecurityEventsPlugin).
343
+ // Feature plugins (two-factor, passkey, ...) come before `config.plugins`, so a consumer
344
+ // plugin can still hook around them. The closed sign-up plugin follows `config.plugins` so
345
+ // its init reaches the providers `genericOAuth` registers.
283
346
  // The handoff plugins come last so their callback hook sees the final redirect.
284
347
  // The credential sync plugin keeps the legacy passport credential in step with Better Auth.
285
- plugins: [bearer(), ...credentialSyncPlugins, ...(config.plugins ?? []), ...handoffPlugins],
348
+ plugins: [
349
+ bearer(),
350
+ createMethodsPlugin(),
351
+ createSetPasswordPlugin({userModel}),
352
+ ...credentialSyncPlugins,
353
+ ...buildFeaturePlugins(config, typeof merged.baseURL === "string" ? merged.baseURL : baseURL),
354
+ ...(isLinkingDisabled ? [createLinkingDisabledPlugin()] : []),
355
+ ...(userModel
356
+ ? [createAppUserSyncPlugin(userModel), createSecurityEventsPlugin(userModel)]
357
+ : []),
358
+ ...(config.plugins ?? []),
359
+ ...(isClosed ? [createSignUpClosedPlugin()] : []),
360
+ ...handoffPlugins,
361
+ ],
286
362
  });
287
363
 
288
364
  // Cast through unknown: enabling the bearer plugin narrows betterAuth()'s inferred
@@ -491,6 +567,32 @@ const passwordFromUnknown = (value: unknown): string => {
491
567
  return candidate;
492
568
  };
493
569
 
570
+ // Better Auth keeps the AsyncLocalStorage of the endpoint being served on this global; the
571
+ // store holds the endpoint's context, including its parsed body. `tryGetCurrentAuthEndpointContext`
572
+ // in `@better-auth/core/context` reads the same store, but that package is not a direct
573
+ // dependency of @terreno/api and `better-auth` does not re-export it.
574
+ const BETTER_AUTH_GLOBAL = Symbol.for("better-auth:global");
575
+
576
+ interface BetterAuthGlobalLike {
577
+ context?: {endpointContextAsyncStorage?: {getStore: () => unknown}};
578
+ }
579
+
580
+ /**
581
+ * The parsed body of the Better Auth endpoint now being served (HTTP or a direct `auth.api`
582
+ * call), or `undefined` outside one. Better Auth reads an HTTP body before its handler runs, so a
583
+ * hook such as `onPasswordReset` can no longer read it from the request.
584
+ */
585
+ export const currentBetterAuthEndpointBody = (): unknown => {
586
+ const betterAuthGlobal = (globalThis as Record<symbol, BetterAuthGlobalLike | undefined>)[
587
+ BETTER_AUTH_GLOBAL
588
+ ];
589
+ const store = betterAuthGlobal?.context?.endpointContextAsyncStorage?.getStore();
590
+ if (!store || typeof store !== "object") {
591
+ return undefined;
592
+ }
593
+ return (store as {body?: unknown}).body;
594
+ };
595
+
494
596
  export const readPasswordFromBetterAuthResetRequest = async (
495
597
  request: PasswordResetRequestLike | undefined
496
598
  ): Promise<string> => {
@@ -518,12 +620,19 @@ export const readPasswordFromBetterAuthResetRequest = async (
518
620
  /**
519
621
  * After Better Auth password reset, update the JWT/passport hash and bump
520
622
  * `tokenEpoch` so a dual-enrolled account cannot keep the old password or
521
- * outstanding refresh tokens.
623
+ * outstanding refresh tokens. Only an app User that already has a JWT password gets the new one:
624
+ * `POST /auth/login` has no second factor, so a Better Auth only (social) account must not gain a
625
+ * way to sign in there. Its `tokenEpoch` is still bumped.
626
+ *
627
+ * `capturedPassword` is the new password from the parsed body of the reset endpoint being served
628
+ * (`newPassword`, or `password` for the email-OTP and phone-number resets). Without it the
629
+ * password is read from `request`, which works only while the request body is unread.
522
630
  */
523
631
  export const applyBetterAuthPasswordResetToJwt = async (
524
632
  userModel: UserModel,
525
633
  betterAuthUser: {email?: string; id?: string},
526
- request: PasswordResetRequestLike | undefined
634
+ request: PasswordResetRequestLike | undefined,
635
+ capturedPassword?: string
527
636
  ): Promise<void> => {
528
637
  const betterAuthId = typeof betterAuthUser.id === "string" ? betterAuthUser.id : "";
529
638
  const email = typeof betterAuthUser.email === "string" ? betterAuthUser.email : "";
@@ -534,7 +643,15 @@ export const applyBetterAuthPasswordResetToJwt = async (
534
643
  if (!appUser) {
535
644
  return;
536
645
  }
537
- const password = await readPasswordFromBetterAuthResetRequest(request);
646
+ const hasLegacyPassword =
647
+ userModel.schema.path("hash") !== undefined &&
648
+ Boolean(await userModel.exists({_id: appUser._id, hash: {$exists: true, $ne: null}} as never));
649
+ if (!hasLegacyPassword) {
650
+ appUser.tokenEpoch = (appUser.tokenEpoch ?? 0) + 1;
651
+ await appUser.save();
652
+ return;
653
+ }
654
+ const password = capturedPassword || (await readPasswordFromBetterAuthResetRequest(request));
538
655
  if (!password) {
539
656
  logger.error("[auth] Better Auth password reset did not include a password to sync to JWT");
540
657
  throw new APIError({
@@ -688,6 +805,15 @@ export const createBetterAuthSessionMiddleware = (
688
805
  };
689
806
  };
690
807
 
808
+ /**
809
+ * The stable title (and Better Auth error message) for a sign-in whose unverified email matches
810
+ * an app User it cannot prove it owns.
811
+ */
812
+ export const VERIFY_EMAIL_TO_USE_ACCOUNT = "Verify your email to use this account";
813
+
814
+ /** The Better Auth error code (JSON `code`, OAuth redirect `error`) for the same refusal. */
815
+ const VERIFY_EMAIL_ERROR_CODE = "VERIFY_EMAIL_TO_USE_ACCOUNT";
816
+
691
817
  /**
692
818
  * Syncs a Better Auth user to the application User model.
693
819
  * Creates or updates the user as needed.
@@ -707,6 +833,13 @@ interface MutableUserDoc {
707
833
  }
708
834
 
709
835
  export interface SyncBetterAuthUserOptions {
836
+ /**
837
+ * The plaintext password from the sign-up or sign-in request being served. When an app User
838
+ * with the same email is not linked yet and the Better Auth email is unverified, the user is
839
+ * linked only if this password verifies against that User's passport-local-mongoose hash.
840
+ * Never stored or logged.
841
+ */
842
+ password?: string;
710
843
  /**
711
844
  * Link an existing app user by email even when Better Auth has not verified the address or
712
845
  * the row is bound to another Better Auth id. Only for operator-run seeds that create the
@@ -715,22 +848,126 @@ export interface SyncBetterAuthUserOptions {
715
848
  trustEmail?: boolean;
716
849
  }
717
850
 
851
+ // passport-local-mongoose's instance method (v8+ returns a promise).
852
+ type PassportAuthenticate = (
853
+ password: string
854
+ ) => Promise<{error?: unknown; user?: unknown}> | undefined;
855
+
856
+ // The parts of a Mongoose model the legacy password check needs beyond `UserModel`.
857
+ interface HydratingUserModel {
858
+ collection?: {
859
+ find: (filter: Record<string, unknown>) => {
860
+ limit: (count: number) => {next: () => Promise<Record<string, unknown> | null>};
861
+ };
862
+ };
863
+ hydrate?: (doc: Record<string, unknown>) => unknown;
864
+ }
865
+
718
866
  /**
719
- * An email alone does not prove the caller owns an existing app user. Link by email only when
720
- * Better Auth verified the address and the row is not bound to another Better Auth account.
867
+ * Whether `password` verifies against the passport-local-mongoose hash of a legacy app User.
868
+ * Users without a hash (GitHub-JWT users) and models without the plugin never match.
869
+ *
870
+ * The check runs on a detached copy of the stored document whose `save` does nothing, so
871
+ * passport's `limitAttempts` bookkeeping never counts a Better Auth sign-up against the user's
872
+ * JWT login: a stranger signing up with the victim's email cannot lock the victim out.
721
873
  */
722
- const assertEmailLinkAllowed = (
874
+ const legacyPasswordMatches = async (
875
+ userModel: UserModel,
876
+ user: MutableUserDoc,
877
+ password?: string
878
+ ): Promise<boolean> => {
879
+ const model = userModel as unknown as HydratingUserModel;
880
+ const id = (user as unknown as {_id?: unknown})._id;
881
+ if (!password || id === undefined || !model.collection || !model.hydrate) {
882
+ return false;
883
+ }
884
+ try {
885
+ // The raw driver read includes the `select: false` hash and salt fields.
886
+ const stored = await model.collection.find({_id: id}).limit(1).next();
887
+ if (!stored) {
888
+ return false;
889
+ }
890
+ const probe = model.hydrate(stored) as {authenticate?: PassportAuthenticate; save?: unknown};
891
+ if (typeof probe.authenticate !== "function") {
892
+ return false;
893
+ }
894
+ probe.save = async (): Promise<unknown> => probe;
895
+ const result = await probe.authenticate(password);
896
+ return Boolean(result?.user);
897
+ } catch (error) {
898
+ logger.debug(`[better-auth] Legacy password check failed: ${error}`);
899
+ return false;
900
+ }
901
+ };
902
+
903
+ interface AppUserClaim {
904
+ betterAuthId?: string;
905
+ emailVerified: boolean;
906
+ password?: string;
907
+ }
908
+
909
+ /**
910
+ * Whether a Better Auth user may claim the app User that has its email: the User already
911
+ * carries its id (a concurrent request linked it), the email is verified, or the password
912
+ * verifies against the User's legacy passport hash. Anyone can sign up unverified with someone
913
+ * else's email, so nothing weaker counts.
914
+ */
915
+ const mayClaimAppUser = async (
916
+ userModel: UserModel,
917
+ user: MutableUserDoc,
918
+ claim: AppUserClaim
919
+ ): Promise<boolean> =>
920
+ (claim.betterAuthId !== undefined && user.betterAuthId === claim.betterAuthId) ||
921
+ claim.emailVerified ||
922
+ (await legacyPasswordMatches(userModel, user, claim.password));
923
+
924
+ const verifyEmailRefusal = (): APIError =>
925
+ new APIError({
926
+ code: "verify-email-to-use-account",
927
+ disableExternalErrorTracking: true,
928
+ status: 409,
929
+ title: VERIFY_EMAIL_TO_USE_ACCOUNT,
930
+ });
931
+
932
+ const escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
933
+
934
+ /**
935
+ * The app User with this email, ignoring case. Better Auth lowercases emails, while legacy
936
+ * Users may have been stored as typed ("Jane@Example.com"); an exact match would miss them,
937
+ * skip the claim guard, and insert a second User.
938
+ */
939
+ const findAppUserByEmail = async (
940
+ userModel: UserModel,
941
+ email: string
942
+ ): Promise<MutableUserDoc | null> =>
943
+ (await findOneOrNoneFor(userModel, {
944
+ email: {$options: "i", $regex: `^${escapeRegExp(email)}$`},
945
+ } as never)) as unknown as MutableUserDoc | null;
946
+
947
+ /** The stable title for a sign-in whose email matches an app User bound to another account. */
948
+ const EMAIL_BOUND_TO_ANOTHER_ACCOUNT = "An account with this email already exists";
949
+
950
+ /** The Better Auth error code (JSON `code`, OAuth redirect `error`) for the same refusal. */
951
+ const EMAIL_BOUND_ERROR_CODE = "ACCOUNT_ALREADY_EXISTS";
952
+
953
+ /**
954
+ * An email alone does not prove the caller owns an existing app user, and an app user already
955
+ * bound to another Better Auth account is never relinked by email. (Whether the caller may claim
956
+ * an unbound row is `mayClaimAppUser`.)
957
+ */
958
+ const assertNotBoundToAnotherAccount = (
723
959
  userByEmail: MutableUserDoc,
724
- betterAuthUser: BetterAuthUser
960
+ betterAuthUserId?: string
725
961
  ): void => {
726
- if (betterAuthUser.emailVerified === true && !userByEmail.betterAuthId) {
962
+ if (!userByEmail.betterAuthId || userByEmail.betterAuthId === betterAuthUserId) {
727
963
  return;
728
964
  }
729
965
  throw new APIError({
966
+ code: "email-bound-to-another-account",
730
967
  detail: "Verify the email address before signing in to the existing account.",
731
968
  disableExternalErrorTracking: true,
732
969
  status: 409,
733
- title: "An account with this email already exists",
970
+ title: EMAIL_BOUND_TO_ANOTHER_ACCOUNT,
734
971
  });
735
972
  };
736
973
 
@@ -788,17 +1025,26 @@ export const syncBetterAuthUser = async (
788
1025
  }
789
1026
 
790
1027
  // Check if user exists by email (migration case)
791
- const userByEmail = (await findOneOrNoneFor(userModel, {
792
- email: betterAuthUser.email,
793
- })) as unknown as MutableUserDoc | null;
1028
+ const userByEmail = await findAppUserByEmail(userModel, betterAuthUser.email);
794
1029
  if (userByEmail?.betterAuthId === betterAuthUser.id) {
795
1030
  // A concurrent first contact created this row between the two lookups.
796
1031
  return userByEmail;
797
1032
  }
798
1033
  if (userByEmail) {
799
1034
  if (!options.trustEmail) {
800
- assertEmailLinkAllowed(userByEmail, betterAuthUser);
801
- await revokeUnprovenLegacyPassword(userModel, userByEmail);
1035
+ assertNotBoundToAnotherAccount(userByEmail, betterAuthUser.id);
1036
+ const isEmailVerified = betterAuthUser.emailVerified === true;
1037
+ const mayLink = await mayClaimAppUser(userModel, userByEmail, {
1038
+ betterAuthId: betterAuthUser.id,
1039
+ emailVerified: isEmailVerified,
1040
+ password: options.password,
1041
+ });
1042
+ if (!mayLink) {
1043
+ throw verifyEmailRefusal();
1044
+ }
1045
+ if (isEmailVerified) {
1046
+ await revokeUnprovenLegacyPassword(userModel, userByEmail);
1047
+ }
802
1048
  }
803
1049
  // Link existing user to Better Auth
804
1050
  userByEmail.betterAuthId = betterAuthUser.id;
@@ -827,9 +1073,12 @@ export const syncBetterAuthUser = async (
827
1073
  return newUser;
828
1074
  } catch (error) {
829
1075
  // A duplicate key means a concurrent request created the user first; callers such as
830
- // resolveBetterAuthAppUser recover from it, so it is not an error worth alerting on.
1076
+ // resolveBetterAuthAppUser recover from it, so it is not an error worth alerting on. An
1077
+ // unverified email that matches an existing User is an expected refusal.
831
1078
  if ((error as {code?: number}).code === 11000) {
832
1079
  logger.debug(`Better Auth user was created concurrently: ${error}`);
1080
+ } else if (isVerifyEmailRefusal(error)) {
1081
+ logger.info(`[better-auth] Refused to link unverified Better Auth user ${betterAuthUser.id}`);
833
1082
  } else if (isAPIError(error) && error.status === 409) {
834
1083
  logger.warn(`Refused to link Better Auth user ${betterAuthUser.id} by email: ${error.title}`);
835
1084
  } else {
@@ -839,6 +1088,180 @@ export const syncBetterAuthUser = async (
839
1088
  }
840
1089
  };
841
1090
 
1091
+ const isVerifyEmailRefusal = (error: unknown): boolean =>
1092
+ isAPIError(error) && error.status === 409 && error.message === VERIFY_EMAIL_TO_USE_ACCOUNT;
1093
+
1094
+ const isBoundToAnotherAccountRefusal = (error: unknown): boolean =>
1095
+ isAPIError(error) && error.status === 409 && error.message === EMAIL_BOUND_TO_ANOTHER_ACCOUNT;
1096
+
1097
+ // The parts of Better Auth's endpoint context the session hook reads.
1098
+ interface SessionHookContext {
1099
+ body?: unknown;
1100
+ params?: Record<string, string | undefined>;
1101
+ path?: string;
1102
+ }
1103
+
1104
+ const bodyString = (body: unknown, key: string): string | undefined => {
1105
+ if (!body || typeof body !== "object") {
1106
+ return undefined;
1107
+ }
1108
+ const value = (body as Record<string, unknown>)[key];
1109
+ return typeof value === "string" && value.length > 0 ? value : undefined;
1110
+ };
1111
+
1112
+ // The social or generic OAuth provider a session is being created for, if any.
1113
+ const oauthProviderFromContext = (context: SessionHookContext | null): string | undefined => {
1114
+ const path = context?.path ?? "";
1115
+ if (path.startsWith("/callback/")) {
1116
+ return context?.params?.id;
1117
+ }
1118
+ if (path === "/sign-in/social") {
1119
+ return bodyString(context?.body, "provider");
1120
+ }
1121
+ return undefined;
1122
+ };
1123
+
1124
+ // The plaintext password, only on the email requests that carry one.
1125
+ const passwordFromContext = (context: SessionHookContext | null): string | undefined => {
1126
+ if (context?.path !== "/sign-up/email" && context?.path !== "/sign-in/email") {
1127
+ return undefined;
1128
+ }
1129
+ return bodyString(context.body, "password");
1130
+ };
1131
+
1132
+ interface SessionHookAdapter {
1133
+ internalAdapter: {findUserById: (userId: string) => Promise<BetterAuthUser | null>};
1134
+ }
1135
+
1136
+ const verifyEmailConflict = (): BetterAuthAPIError =>
1137
+ new BetterAuthAPIError("CONFLICT", {
1138
+ code: VERIFY_EMAIL_ERROR_CODE,
1139
+ message: VERIFY_EMAIL_TO_USE_ACCOUNT,
1140
+ });
1141
+
1142
+ const boundToAnotherAccountConflict = (): BetterAuthAPIError =>
1143
+ new BetterAuthAPIError("CONFLICT", {
1144
+ code: EMAIL_BOUND_ERROR_CODE,
1145
+ message: EMAIL_BOUND_TO_ANOTHER_ACCOUNT,
1146
+ });
1147
+
1148
+ // The app User with this email that no Better Auth user has claimed yet (or another one has).
1149
+ const findUnclaimedAppUser = async (
1150
+ userModel: UserModel,
1151
+ email: string,
1152
+ betterAuthId?: string
1153
+ ): Promise<MutableUserDoc | null> => {
1154
+ const appUser = await findAppUserByEmail(userModel, email);
1155
+ if (!appUser || (betterAuthId !== undefined && appUser.betterAuthId === betterAuthId)) {
1156
+ return null;
1157
+ }
1158
+ return appUser;
1159
+ };
1160
+
1161
+ /**
1162
+ * The plugin that guards and syncs the app User while the request that proves who the user is
1163
+ * (its password, its provider) is still in hand. Session middleware only sees later requests,
1164
+ * which carry neither.
1165
+ *
1166
+ * - Before a Better Auth user is created: when an app User already has the email, creation is
1167
+ * refused with 409 `VERIFY_EMAIL_TO_USE_ACCOUNT` (an OAuth callback redirects with that
1168
+ * `error`) unless the provider verified the email or the sign-up password verifies against
1169
+ * that User's passport hash. An app User bound to another Better Auth account is always
1170
+ * refused, with 409 `ACCOUNT_ALREADY_EXISTS`. Nothing is left behind (no user, account, or verification mail),
1171
+ * so a later verification cannot hand an attacker's password the victim's User.
1172
+ * - Before a session is created, the app User is synced: the OAuth provider id fills
1173
+ * `oauthProvider`, and on `/sign-up/email` and `/sign-in/email` the plaintext password lets an
1174
+ * unverified user claim a legacy User. A refusal fails the sign-in with the same 409s. A
1175
+ * verified email that links a User whose own email was never verified revokes that User's
1176
+ * legacy password and refresh tokens (see `revokeUnprovenLegacyPassword`).
1177
+ * - A failed link that a password was proving fails the sign-in (500 `APP_USER_LINK_FAILED`), so
1178
+ * no session exists that would be refused on every request. Any other sync failure is logged
1179
+ * and the session proceeds; the session middleware retries the sync on the next request.
1180
+ */
1181
+ export const createAppUserSyncPlugin = (userModel: UserModel): BetterAuthPlugin => {
1182
+ return {
1183
+ id: "terreno-app-user-sync",
1184
+ init: (authContext) => {
1185
+ const {internalAdapter} = authContext as unknown as SessionHookAdapter;
1186
+ return {
1187
+ options: {
1188
+ databaseHooks: {
1189
+ session: {
1190
+ create: {
1191
+ before: async (session, rawContext): Promise<void> => {
1192
+ const context = rawContext as SessionHookContext | null;
1193
+ const betterAuthUser = await internalAdapter.findUserById(session.userId);
1194
+ if (!betterAuthUser) {
1195
+ return;
1196
+ }
1197
+ const password = passwordFromContext(context);
1198
+ try {
1199
+ await syncBetterAuthUser(
1200
+ userModel,
1201
+ betterAuthUser,
1202
+ oauthProviderFromContext(context),
1203
+ {password}
1204
+ );
1205
+ } catch (error) {
1206
+ if (isVerifyEmailRefusal(error)) {
1207
+ throw verifyEmailConflict();
1208
+ }
1209
+ if (isBoundToAnotherAccountRefusal(error)) {
1210
+ throw boundToAnotherAccountConflict();
1211
+ }
1212
+ if ((error as {code?: number}).code === 11000) {
1213
+ return;
1214
+ }
1215
+ logger.error(`[better-auth] App user sync on sign-in failed: ${error}`);
1216
+ const isPasswordLink =
1217
+ password !== undefined &&
1218
+ (await findUnclaimedAppUser(
1219
+ userModel,
1220
+ betterAuthUser.email,
1221
+ betterAuthUser.id
1222
+ )) !== null;
1223
+ if (isPasswordLink) {
1224
+ throw new BetterAuthAPIError("INTERNAL_SERVER_ERROR", {
1225
+ code: "APP_USER_LINK_FAILED",
1226
+ message: "Could not link your account. Try again.",
1227
+ });
1228
+ }
1229
+ }
1230
+ },
1231
+ },
1232
+ },
1233
+ user: {
1234
+ create: {
1235
+ before: async (user, rawContext): Promise<void> => {
1236
+ const email = typeof user.email === "string" ? user.email : "";
1237
+ const appUser = email ? await findUnclaimedAppUser(userModel, email) : null;
1238
+ if (!appUser) {
1239
+ return;
1240
+ }
1241
+ if (appUser.betterAuthId) {
1242
+ logger.info(
1243
+ "[better-auth] Refused a sign-up for an app user bound to another account"
1244
+ );
1245
+ throw boundToAnotherAccountConflict();
1246
+ }
1247
+ const mayClaim = await mayClaimAppUser(userModel, appUser, {
1248
+ emailVerified: user.emailVerified === true,
1249
+ password: passwordFromContext(rawContext as SessionHookContext | null),
1250
+ });
1251
+ if (!mayClaim) {
1252
+ logger.info("[better-auth] Refused a sign-up for an existing app user's email");
1253
+ throw verifyEmailConflict();
1254
+ }
1255
+ },
1256
+ },
1257
+ },
1258
+ },
1259
+ },
1260
+ };
1261
+ },
1262
+ } satisfies BetterAuthPlugin;
1263
+ };
1264
+
842
1265
  export interface ResolveBetterAuthAppUserOptions {
843
1266
  userModel: UserModel;
844
1267
  betterAuthUser: BetterAuthUser;
@@ -920,17 +1343,13 @@ export const getMongoClientFromMongoose = (): MongoClientLike => {
920
1343
  };
921
1344
 
922
1345
  /**
923
- * Sets up Better Auth user sync hooks.
924
- * This ensures users created/updated in Better Auth are synced to the application User model.
925
- *
926
- * Note: Better Auth doesn't have built-in event hooks, so we rely on the session middleware
927
- * to create users on first session access.
1346
+ * Kept for compatibility; it does nothing. `createBetterAuth` wires the app User sync itself
1347
+ * when given a `userModel`: the `terreno-app-user-sync` plugin guards Better Auth user creation
1348
+ * and syncs the app User as each session is created (see `createAppUserSyncPlugin`), and
1349
+ * `createBetterAuthSessionMiddleware` retries the sync on later requests.
928
1350
  */
929
1351
  export const setupBetterAuthUserSync = (_auth: BetterAuthInstance, _userModel: UserModel): void => {
930
- // Better Auth v1.x doesn't expose event hooks for user creation.
931
- // User sync is handled in createBetterAuthSessionMiddleware when a session is accessed.
932
- // This function is a placeholder for future versions that may support hooks.
933
- logger.debug("Better Auth user sync configured (via session middleware)");
1352
+ logger.debug("Better Auth user sync configured (via the terreno-app-user-sync plugin)");
934
1353
  };
935
1354
 
936
1355
  /**