@terreno/api 57.19.2 → 57.20.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 (169) hide show
  1. package/CHANGELOG.md +393 -0
  2. package/dist/accountSecurity/accessActions.d.ts +38 -0
  3. package/dist/accountSecurity/accessActions.js +157 -0
  4. package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
  5. package/dist/accountSecurity/accountSecurityApp.js +438 -0
  6. package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
  7. package/dist/accountSecurity/accountSecurityService.js +481 -0
  8. package/dist/accountSecurity/credentialActions.d.ts +16 -0
  9. package/dist/accountSecurity/credentialActions.js +189 -0
  10. package/dist/accountSecurity/membershipActions.d.ts +15 -0
  11. package/dist/accountSecurity/membershipActions.js +81 -0
  12. package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
  13. package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
  14. package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
  15. package/dist/accountSecurity/securityEventHooks.js +223 -0
  16. package/dist/accountSecurity/securityEvents.d.ts +162 -0
  17. package/dist/accountSecurity/securityEvents.js +114 -0
  18. package/dist/accountSecurity/securityNotifications.d.ts +125 -0
  19. package/dist/accountSecurity/securityNotifications.js +333 -0
  20. package/dist/api.js +38 -6
  21. package/dist/audit/auditEventModel.d.ts +5 -3
  22. package/dist/audit/auditEventModel.js +8 -6
  23. package/dist/audit/processQueue.js +4 -2
  24. package/dist/audit/record.d.ts +2 -2
  25. package/dist/audit/record.js +3 -0
  26. package/dist/authRecovery.js +29 -1
  27. package/dist/betterAuth.d.ts +179 -10
  28. package/dist/betterAuthApp.d.ts +15 -0
  29. package/dist/betterAuthApp.js +23 -0
  30. package/dist/betterAuthChallengeHeaders.d.ts +37 -0
  31. package/dist/betterAuthChallengeHeaders.js +180 -0
  32. package/dist/betterAuthFeatures.d.ts +54 -0
  33. package/dist/betterAuthFeatures.js +239 -0
  34. package/dist/betterAuthMethods.d.ts +73 -0
  35. package/dist/betterAuthMethods.js +55 -0
  36. package/dist/betterAuthOAuthHandoff.d.ts +10 -2
  37. package/dist/betterAuthOAuthHandoff.js +222 -24
  38. package/dist/betterAuthSetPassword.d.ts +33 -0
  39. package/dist/betterAuthSetPassword.js +166 -0
  40. package/dist/betterAuthSetup.d.ts +57 -8
  41. package/dist/betterAuthSetup.js +327 -36
  42. package/dist/consentApp.d.ts +9 -4
  43. package/dist/consentApp.js +344 -28
  44. package/dist/consentStatus.d.ts +60 -0
  45. package/dist/consentStatus.js +111 -0
  46. package/dist/errors.d.ts +6 -0
  47. package/dist/errors.js +41 -2
  48. package/dist/expressServer.js +3 -2
  49. package/dist/index.d.ts +14 -2
  50. package/dist/index.js +23 -3
  51. package/dist/mcp/oauth.js +151 -11
  52. package/dist/mcp/oauthMetadata.d.ts +2 -1
  53. package/dist/mcp/oauthMetadata.js +7 -4
  54. package/dist/models/consentResponse.js +51 -0
  55. package/dist/models/mcpOAuthClient.js +78 -2
  56. package/dist/models/mcpOAuthToken.js +28 -4
  57. package/dist/orgs/membershipGuards.d.ts +7 -0
  58. package/dist/orgs/membershipGuards.js +32 -0
  59. package/dist/orgs/orgsApp.d.ts +19 -1
  60. package/dist/orgs/orgsApp.js +55 -24
  61. package/dist/rateLimit/policies.js +8 -0
  62. package/dist/rbac/access.js +2 -1
  63. package/dist/rbac/resolve.d.ts +9 -1
  64. package/dist/rbac/resolve.js +21 -16
  65. package/dist/rbac/roleManager.d.ts +6 -0
  66. package/dist/rbac/roleManager.js +8 -7
  67. package/dist/rbac/roleModel.d.ts +1 -0
  68. package/dist/rbac/roleModel.js +45 -3
  69. package/dist/rbac/statements.d.ts +2 -2
  70. package/dist/rbac/statements.js +10 -1
  71. package/dist/rbac/types.d.ts +6 -0
  72. package/dist/rbac/userWriteGuards.js +2 -1
  73. package/dist/schemaMetadata.js +8 -1
  74. package/dist/seedRunner.js +7 -2
  75. package/dist/terrenoApp.d.ts +4 -0
  76. package/dist/terrenoApp.js +15 -0
  77. package/dist/tests/models.d.ts +5 -0
  78. package/dist/tests/models.js +8 -0
  79. package/dist/types/consentResponse.d.ts +8 -0
  80. package/dist/types/mcpOAuth.d.ts +35 -2
  81. package/package.json +6 -3
  82. package/src/__snapshots__/openApi.test.ts.snap +288 -0
  83. package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
  84. package/src/accountSecurity/accessActions.test.ts +723 -0
  85. package/src/accountSecurity/accessActions.ts +173 -0
  86. package/src/accountSecurity/accountSecurity.test.ts +947 -0
  87. package/src/accountSecurity/accountSecurityApp.ts +720 -0
  88. package/src/accountSecurity/accountSecurityService.ts +826 -0
  89. package/src/accountSecurity/credentialActions.test.ts +867 -0
  90. package/src/accountSecurity/credentialActions.ts +260 -0
  91. package/src/accountSecurity/membershipActions.ts +89 -0
  92. package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
  93. package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
  94. package/src/accountSecurity/securityEventHooks.ts +294 -0
  95. package/src/accountSecurity/securityEvents.ts +165 -0
  96. package/src/accountSecurity/securityNotifications.test.ts +1323 -0
  97. package/src/accountSecurity/securityNotifications.ts +516 -0
  98. package/src/api.arrayOperations.test.ts +71 -0
  99. package/src/api.ts +38 -7
  100. package/src/audit/auditEventModel.ts +10 -7
  101. package/src/audit/processQueue.ts +4 -2
  102. package/src/audit/record.test.ts +15 -0
  103. package/src/audit/record.ts +10 -2
  104. package/src/authRecovery.test.ts +23 -0
  105. package/src/authRecovery.ts +34 -1
  106. package/src/authRecoveryBetterAuth.test.ts +169 -0
  107. package/src/betterAuth.ts +194 -8
  108. package/src/betterAuthApp.ts +32 -0
  109. package/src/betterAuthChallengeHeaders.test.ts +476 -0
  110. package/src/betterAuthChallengeHeaders.ts +227 -0
  111. package/src/betterAuthFeatures.test.ts +489 -0
  112. package/src/betterAuthFeatures.ts +283 -0
  113. package/src/betterAuthLinking.test.ts +844 -0
  114. package/src/betterAuthMethods.test.ts +138 -0
  115. package/src/betterAuthMethods.ts +98 -0
  116. package/src/betterAuthOAuthHandoff.test.ts +482 -69
  117. package/src/betterAuthOAuthHandoff.ts +293 -33
  118. package/src/betterAuthOAuthProxy.test.ts +421 -0
  119. package/src/betterAuthPasswordReset.test.ts +190 -0
  120. package/src/betterAuthSetPassword.test.ts +378 -0
  121. package/src/betterAuthSetPassword.ts +213 -0
  122. package/src/betterAuthSetup.test.ts +39 -7
  123. package/src/betterAuthSetup.ts +457 -38
  124. package/src/consentApp.test.ts +869 -2
  125. package/src/consentApp.ts +438 -36
  126. package/src/consentStatus.test.ts +226 -0
  127. package/src/consentStatus.ts +171 -0
  128. package/src/errors.test.ts +81 -0
  129. package/src/errors.ts +50 -1
  130. package/src/expressServer.test.ts +29 -0
  131. package/src/expressServer.ts +3 -2
  132. package/src/index.ts +30 -0
  133. package/src/mcp/oauth.test.ts +463 -2
  134. package/src/mcp/oauth.ts +184 -13
  135. package/src/mcp/oauthMetadata.ts +5 -2
  136. package/src/models/consentResponse.ts +53 -0
  137. package/src/models/mcpOAuthClient.ts +100 -3
  138. package/src/models/mcpOAuthToken.ts +30 -5
  139. package/src/orgs/membershipGuards.ts +39 -0
  140. package/src/orgs/orgRbac.test.ts +1 -1
  141. package/src/orgs/orgsApp.test.ts +101 -2
  142. package/src/orgs/orgsApp.ts +69 -28
  143. package/src/rateLimit/policies.test.ts +53 -0
  144. package/src/rateLimit/policies.ts +8 -0
  145. package/src/rbac/access.ts +4 -1
  146. package/src/rbac/resolve.test.ts +65 -0
  147. package/src/rbac/resolve.ts +37 -17
  148. package/src/rbac/roleManager.test.ts +64 -0
  149. package/src/rbac/roleManager.ts +15 -6
  150. package/src/rbac/roleModel.test.ts +174 -1
  151. package/src/rbac/roleModel.ts +66 -3
  152. package/src/rbac/routes.test.ts +58 -0
  153. package/src/rbac/statements.test.ts +4 -1
  154. package/src/rbac/statements.ts +11 -1
  155. package/src/rbac/types.ts +6 -1
  156. package/src/rbac/userWriteGuards.test.ts +48 -0
  157. package/src/rbac/userWriteGuards.ts +5 -2
  158. package/src/schemaMetadata.test.ts +39 -0
  159. package/src/schemaMetadata.ts +11 -1
  160. package/src/seedRunner.test.ts +56 -0
  161. package/src/seedRunner.ts +7 -2
  162. package/src/terrenoApp.ts +20 -0
  163. package/src/tests/accountSecurityTestApp.ts +290 -0
  164. package/src/tests/betterAuthStubs.ts +188 -0
  165. package/src/tests/mockOidcProvider.ts +105 -0
  166. package/src/tests/models.ts +13 -0
  167. package/src/tests/softwareAuthenticator.ts +183 -0
  168. package/src/types/consentResponse.ts +8 -0
  169. package/src/types/mcpOAuth.ts +39 -3
@@ -9,7 +9,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
9
9
  return (mod && mod.__esModule) ? mod : { "default": mod };
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.hasBetterAuthSession = exports.getBetterAuthSession = exports.setupBetterAuthUserSync = exports.getMongoClientFromMongoose = exports.mountBetterAuthRoutes = exports.resolveBetterAuthAppUser = exports.syncBetterAuthUser = exports.createBetterAuthSessionMiddleware = exports.applyBetterAuthPasswordResetToJwt = exports.readPasswordFromBetterAuthResetRequest = exports.verifyBetterAuthCredentialPassword = exports.applyJwtPasswordResetToBetterAuth = exports.createBetterAuth = exports.createBetterAuthEmailHooks = void 0;
12
+ exports.hasBetterAuthSession = exports.getBetterAuthSession = exports.setupBetterAuthUserSync = exports.getMongoClientFromMongoose = exports.mountBetterAuthRoutes = exports.resolveBetterAuthAppUser = exports.createAppUserSyncPlugin = exports.syncBetterAuthUser = exports.VERIFY_EMAIL_TO_USE_ACCOUNT = exports.createBetterAuthSessionMiddleware = exports.applyBetterAuthPasswordResetToJwt = exports.readPasswordFromBetterAuthResetRequest = exports.currentBetterAuthEndpointBody = exports.verifyBetterAuthCredentialPassword = exports.applyJwtPasswordResetToBetterAuth = exports.createBetterAuth = exports.createBetterAuthEmailHooks = exports.betterAuthResetPasswordUrl = void 0;
13
13
  const better_auth_1 = require("better-auth");
14
14
  const mongodb_1 = require("better-auth/adapters/mongodb");
15
15
  const api_1 = require("better-auth/api");
@@ -17,8 +17,12 @@ const node_1 = require("better-auth/node");
17
17
  const plugins_1 = require("better-auth/plugins");
18
18
  const mergeWith_1 = __importDefault(require("lodash/mergeWith"));
19
19
  const mongoose_1 = __importDefault(require("mongoose"));
20
+ const securityEventHooks_1 = require("./accountSecurity/securityEventHooks");
20
21
  const auth_1 = require("./auth");
22
+ const betterAuthFeatures_1 = require("./betterAuthFeatures");
23
+ const betterAuthMethods_1 = require("./betterAuthMethods");
21
24
  const betterAuthOAuthHandoff_1 = require("./betterAuthOAuthHandoff");
25
+ const betterAuthSetPassword_1 = require("./betterAuthSetPassword");
22
26
  const errors_1 = require("./errors");
23
27
  const logger_1 = require("./logger");
24
28
  const plugins_2 = require("./plugins");
@@ -38,10 +42,16 @@ const FALLBACK_AUTH_MAIL = {
38
42
  const interpolateMail = (value, data) => value.replace(/{{\s*([A-Za-z0-9_]+)\s*}}/g, (_match, key) => {
39
43
  return data[key] ?? "";
40
44
  });
45
+ /**
46
+ * The app page that finishes a Better Auth password reset: `{publicAppUrl}/resetPassword?token=`.
47
+ * The built-in reset mail and the admin sign-in link both point here.
48
+ */
49
+ const betterAuthResetPasswordUrl = (publicAppUrl, token) => `${publicAppUrl.replace(/\/$/, "")}/resetPassword?token=${encodeURIComponent(token)}`;
50
+ exports.betterAuthResetPasswordUrl = betterAuthResetPasswordUrl;
41
51
  const fallbackRenderAuthMail = ({ publicAppUrl, templateId, token, templates, }) => {
42
52
  const template = templates?.[templateId] ?? FALLBACK_AUTH_MAIL[templateId];
43
53
  const base = publicAppUrl.replace(/\/$/, "");
44
- const resetUrl = `${base}/resetPassword?token=${encodeURIComponent(token)}`;
54
+ const resetUrl = (0, exports.betterAuthResetPasswordUrl)(base, token);
45
55
  const verifyUrl = `${base}/verifyEmail?token=${encodeURIComponent(token)}`;
46
56
  const data = { publicAppUrl: base, resetUrl, token, verifyUrl };
47
57
  return {
@@ -127,24 +137,27 @@ const createBetterAuth = (options) => {
127
137
  });
128
138
  }
129
139
  const basePath = config.basePath ?? "/api/auth";
140
+ const isClosed = (0, betterAuthFeatures_1.isSignUpClosed)(config);
130
141
  const socialProviders = {};
142
+ const addSocialProvider = (id, provider) => {
143
+ socialProviders[id] = isClosed
144
+ ? { ...provider, disableImplicitSignUp: true, disableSignUp: true }
145
+ : provider;
146
+ };
131
147
  if (config.googleOAuth) {
132
- socialProviders.google = {
148
+ addSocialProvider("google", {
133
149
  clientId: config.googleOAuth.clientId,
134
150
  clientSecret: config.googleOAuth.clientSecret,
135
- };
151
+ });
136
152
  }
137
153
  if (config.appleOAuth) {
138
- socialProviders.apple = {
139
- clientId: config.appleOAuth.clientId,
140
- clientSecret: config.appleOAuth.clientSecret,
141
- };
154
+ addSocialProvider("apple", (0, betterAuthFeatures_1.resolveAppleProvider)(config.appleOAuth));
142
155
  }
143
156
  if (config.githubOAuth) {
144
- socialProviders.github = {
157
+ addSocialProvider("github", {
145
158
  clientId: config.githubOAuth.clientId,
146
159
  clientSecret: config.githubOAuth.clientSecret,
147
- };
160
+ });
148
161
  }
149
162
  const emailHooks = (0, exports.createBetterAuthEmailHooks)(config);
150
163
  const userModel = options.userModel;
@@ -168,7 +181,12 @@ const createBetterAuth = (options) => {
168
181
  ...(userModel
169
182
  ? {
170
183
  onPasswordReset: async ({ user }, request) => {
171
- await (0, exports.applyBetterAuthPasswordResetToJwt)(userModel, user, request);
184
+ await (0, exports.applyBetterAuthPasswordResetToJwt)(userModel, user, request, passwordFromUnknown((0, exports.currentBetterAuthEndpointBody)()));
185
+ await (0, securityEventHooks_1.recordSelfSecurityAction)({
186
+ action: "password-reset",
187
+ betterAuthUserId: user.id,
188
+ userModel,
189
+ });
172
190
  },
173
191
  }
174
192
  : {}),
@@ -194,7 +212,11 @@ const createBetterAuth = (options) => {
194
212
  };
195
213
  // Arrays from `options` replace Terreno's; lodash would otherwise merge them by index.
196
214
  const replaceArrays = (_target, source) => Array.isArray(source) ? source : undefined;
197
- const merged = (0, mergeWith_1.default)({}, defaults, config.options, replaceArrays);
215
+ // Feature options (account linking, closed sign-up) sit between Terreno's defaults and
216
+ // `config.options`, so an explicit option still wins.
217
+ const merged = (0, mergeWith_1.default)({}, defaults, (0, betterAuthFeatures_1.buildFeatureOptions)(config), config.options, replaceArrays);
218
+ // `never` linking (or `options` turning linking off) refuses `/link-social` up front.
219
+ const isLinkingDisabled = merged.account?.accountLinking?.enabled === false;
198
220
  // The handoff hook mints tokens through `auth.api`, which exists only once betterAuth() returns.
199
221
  let auth;
200
222
  const handoffPlugins = config.oauthHandoff
@@ -202,6 +224,7 @@ const createBetterAuth = (options) => {
202
224
  apiOrigin: apiOriginOf(typeof merged.baseURL === "string" ? merged.baseURL : baseURL),
203
225
  config: config.oauthHandoff,
204
226
  getAuth: () => auth,
227
+ isLinkingDisabled,
205
228
  })
206
229
  : [];
207
230
  const credentialSyncPlugins = userModel ? [createCredentialSyncPlugin(userModel)] : [];
@@ -212,9 +235,30 @@ const createBetterAuth = (options) => {
212
235
  // websocket handshakes (RealtimeApp's Better Auth socket validator forwards the handshake
213
236
  // token as a bearer header) — without it, a raw session token cannot be validated and
214
237
  // socket auth silently fails (the sync client shows perpetually "offline").
238
+ // The methods plugin serves `GET {basePath}/terreno/methods` for login screens, and the
239
+ // set-password plugin serves `POST {basePath}/terreno/set-password` for security screens.
240
+ // With a user model, the app user sync plugin links or creates the app User as each session
241
+ // is created (see createAppUserSyncPlugin), and the security events plugin records the
242
+ // user's own security changes (see createSecurityEventsPlugin).
243
+ // Feature plugins (two-factor, passkey, ...) come before `config.plugins`, so a consumer
244
+ // plugin can still hook around them. The closed sign-up plugin follows `config.plugins` so
245
+ // its init reaches the providers `genericOAuth` registers.
215
246
  // The handoff plugins come last so their callback hook sees the final redirect.
216
247
  // The credential sync plugin keeps the legacy passport credential in step with Better Auth.
217
- plugins: [(0, plugins_1.bearer)(), ...credentialSyncPlugins, ...(config.plugins ?? []), ...handoffPlugins],
248
+ plugins: [
249
+ (0, plugins_1.bearer)(),
250
+ (0, betterAuthMethods_1.createMethodsPlugin)(),
251
+ (0, betterAuthSetPassword_1.createSetPasswordPlugin)({ userModel }),
252
+ ...credentialSyncPlugins,
253
+ ...(0, betterAuthFeatures_1.buildFeaturePlugins)(config, typeof merged.baseURL === "string" ? merged.baseURL : baseURL),
254
+ ...(isLinkingDisabled ? [(0, betterAuthFeatures_1.createLinkingDisabledPlugin)()] : []),
255
+ ...(userModel
256
+ ? [(0, exports.createAppUserSyncPlugin)(userModel), (0, securityEventHooks_1.createSecurityEventsPlugin)(userModel)]
257
+ : []),
258
+ ...(config.plugins ?? []),
259
+ ...(isClosed ? [(0, betterAuthFeatures_1.createSignUpClosedPlugin)()] : []),
260
+ ...handoffPlugins,
261
+ ],
218
262
  });
219
263
  // Cast through unknown: enabling the bearer plugin narrows betterAuth()'s inferred
220
264
  // return type to a plugin-specific tuple that no longer matches the plugin-agnostic
@@ -358,6 +402,25 @@ const passwordFromUnknown = (value) => {
358
402
  }
359
403
  return candidate;
360
404
  };
405
+ // Better Auth keeps the AsyncLocalStorage of the endpoint being served on this global; the
406
+ // store holds the endpoint's context, including its parsed body. `tryGetCurrentAuthEndpointContext`
407
+ // in `@better-auth/core/context` reads the same store, but that package is not a direct
408
+ // dependency of @terreno/api and `better-auth` does not re-export it.
409
+ const BETTER_AUTH_GLOBAL = Symbol.for("better-auth:global");
410
+ /**
411
+ * The parsed body of the Better Auth endpoint now being served (HTTP or a direct `auth.api`
412
+ * call), or `undefined` outside one. Better Auth reads an HTTP body before its handler runs, so a
413
+ * hook such as `onPasswordReset` can no longer read it from the request.
414
+ */
415
+ const currentBetterAuthEndpointBody = () => {
416
+ const betterAuthGlobal = globalThis[BETTER_AUTH_GLOBAL];
417
+ const store = betterAuthGlobal?.context?.endpointContextAsyncStorage?.getStore();
418
+ if (!store || typeof store !== "object") {
419
+ return undefined;
420
+ }
421
+ return store.body;
422
+ };
423
+ exports.currentBetterAuthEndpointBody = currentBetterAuthEndpointBody;
361
424
  const readPasswordFromBetterAuthResetRequest = async (request) => {
362
425
  if (!request) {
363
426
  return "";
@@ -384,9 +447,15 @@ exports.readPasswordFromBetterAuthResetRequest = readPasswordFromBetterAuthReset
384
447
  /**
385
448
  * After Better Auth password reset, update the JWT/passport hash and bump
386
449
  * `tokenEpoch` so a dual-enrolled account cannot keep the old password or
387
- * outstanding refresh tokens.
450
+ * outstanding refresh tokens. Only an app User that already has a JWT password gets the new one:
451
+ * `POST /auth/login` has no second factor, so a Better Auth only (social) account must not gain a
452
+ * way to sign in there. Its `tokenEpoch` is still bumped.
453
+ *
454
+ * `capturedPassword` is the new password from the parsed body of the reset endpoint being served
455
+ * (`newPassword`, or `password` for the email-OTP and phone-number resets). Without it the
456
+ * password is read from `request`, which works only while the request body is unread.
388
457
  */
389
- const applyBetterAuthPasswordResetToJwt = async (userModel, betterAuthUser, request) => {
458
+ const applyBetterAuthPasswordResetToJwt = async (userModel, betterAuthUser, request, capturedPassword) => {
390
459
  const betterAuthId = typeof betterAuthUser.id === "string" ? betterAuthUser.id : "";
391
460
  const email = typeof betterAuthUser.email === "string" ? betterAuthUser.email : "";
392
461
  let appUser = betterAuthId ? await (0, plugins_2.findOneOrNoneFor)(userModel, { betterAuthId }) : null;
@@ -396,7 +465,14 @@ const applyBetterAuthPasswordResetToJwt = async (userModel, betterAuthUser, requ
396
465
  if (!appUser) {
397
466
  return;
398
467
  }
399
- const password = await (0, exports.readPasswordFromBetterAuthResetRequest)(request);
468
+ const hasLegacyPassword = userModel.schema.path("hash") !== undefined &&
469
+ Boolean(await userModel.exists({ _id: appUser._id, hash: { $exists: true, $ne: null } }));
470
+ if (!hasLegacyPassword) {
471
+ appUser.tokenEpoch = (appUser.tokenEpoch ?? 0) + 1;
472
+ await appUser.save();
473
+ return;
474
+ }
475
+ const password = capturedPassword || (await (0, exports.readPasswordFromBetterAuthResetRequest)(request));
400
476
  if (!password) {
401
477
  logger_1.logger.error("[auth] Better Auth password reset did not include a password to sync to JWT");
402
478
  throw new errors_1.APIError({
@@ -527,18 +603,88 @@ const createBetterAuthSessionMiddleware = (auth, userModel) => {
527
603
  };
528
604
  exports.createBetterAuthSessionMiddleware = createBetterAuthSessionMiddleware;
529
605
  /**
530
- * An email alone does not prove the caller owns an existing app user. Link by email only when
531
- * Better Auth verified the address and the row is not bound to another Better Auth account.
606
+ * The stable title (and Better Auth error message) for a sign-in whose unverified email matches
607
+ * an app User it cannot prove it owns.
608
+ */
609
+ exports.VERIFY_EMAIL_TO_USE_ACCOUNT = "Verify your email to use this account";
610
+ /** The Better Auth error code (JSON `code`, OAuth redirect `error`) for the same refusal. */
611
+ const VERIFY_EMAIL_ERROR_CODE = "VERIFY_EMAIL_TO_USE_ACCOUNT";
612
+ /**
613
+ * Whether `password` verifies against the passport-local-mongoose hash of a legacy app User.
614
+ * Users without a hash (GitHub-JWT users) and models without the plugin never match.
615
+ *
616
+ * The check runs on a detached copy of the stored document whose `save` does nothing, so
617
+ * passport's `limitAttempts` bookkeeping never counts a Better Auth sign-up against the user's
618
+ * JWT login: a stranger signing up with the victim's email cannot lock the victim out.
619
+ */
620
+ const legacyPasswordMatches = async (userModel, user, password) => {
621
+ const model = userModel;
622
+ const id = user._id;
623
+ if (!password || id === undefined || !model.collection || !model.hydrate) {
624
+ return false;
625
+ }
626
+ try {
627
+ // The raw driver read includes the `select: false` hash and salt fields.
628
+ const stored = await model.collection.find({ _id: id }).limit(1).next();
629
+ if (!stored) {
630
+ return false;
631
+ }
632
+ const probe = model.hydrate(stored);
633
+ if (typeof probe.authenticate !== "function") {
634
+ return false;
635
+ }
636
+ probe.save = async () => probe;
637
+ const result = await probe.authenticate(password);
638
+ return Boolean(result?.user);
639
+ }
640
+ catch (error) {
641
+ logger_1.logger.debug(`[better-auth] Legacy password check failed: ${error}`);
642
+ return false;
643
+ }
644
+ };
645
+ /**
646
+ * Whether a Better Auth user may claim the app User that has its email: the User already
647
+ * carries its id (a concurrent request linked it), the email is verified, or the password
648
+ * verifies against the User's legacy passport hash. Anyone can sign up unverified with someone
649
+ * else's email, so nothing weaker counts.
532
650
  */
533
- const assertEmailLinkAllowed = (userByEmail, betterAuthUser) => {
534
- if (betterAuthUser.emailVerified === true && !userByEmail.betterAuthId) {
651
+ const mayClaimAppUser = async (userModel, user, claim) => (claim.betterAuthId !== undefined && user.betterAuthId === claim.betterAuthId) ||
652
+ claim.emailVerified ||
653
+ (await legacyPasswordMatches(userModel, user, claim.password));
654
+ const verifyEmailRefusal = () => new errors_1.APIError({
655
+ code: "verify-email-to-use-account",
656
+ disableExternalErrorTracking: true,
657
+ status: 409,
658
+ title: exports.VERIFY_EMAIL_TO_USE_ACCOUNT,
659
+ });
660
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
661
+ /**
662
+ * The app User with this email, ignoring case. Better Auth lowercases emails, while legacy
663
+ * Users may have been stored as typed ("Jane@Example.com"); an exact match would miss them,
664
+ * skip the claim guard, and insert a second User.
665
+ */
666
+ const findAppUserByEmail = async (userModel, email) => (await (0, plugins_2.findOneOrNoneFor)(userModel, {
667
+ email: { $options: "i", $regex: `^${escapeRegExp(email)}$` },
668
+ }));
669
+ /** The stable title for a sign-in whose email matches an app User bound to another account. */
670
+ const EMAIL_BOUND_TO_ANOTHER_ACCOUNT = "An account with this email already exists";
671
+ /** The Better Auth error code (JSON `code`, OAuth redirect `error`) for the same refusal. */
672
+ const EMAIL_BOUND_ERROR_CODE = "ACCOUNT_ALREADY_EXISTS";
673
+ /**
674
+ * An email alone does not prove the caller owns an existing app user, and an app user already
675
+ * bound to another Better Auth account is never relinked by email. (Whether the caller may claim
676
+ * an unbound row is `mayClaimAppUser`.)
677
+ */
678
+ const assertNotBoundToAnotherAccount = (userByEmail, betterAuthUserId) => {
679
+ if (!userByEmail.betterAuthId || userByEmail.betterAuthId === betterAuthUserId) {
535
680
  return;
536
681
  }
537
682
  throw new errors_1.APIError({
683
+ code: "email-bound-to-another-account",
538
684
  detail: "Verify the email address before signing in to the existing account.",
539
685
  disableExternalErrorTracking: true,
540
686
  status: 409,
541
- title: "An account with this email already exists",
687
+ title: EMAIL_BOUND_TO_ANOTHER_ACCOUNT,
542
688
  });
543
689
  };
544
690
  /**
@@ -579,17 +725,26 @@ const syncBetterAuthUser = async (userModel, betterAuthUser, oauthProvider, opti
579
725
  return existingUser;
580
726
  }
581
727
  // Check if user exists by email (migration case)
582
- const userByEmail = (await (0, plugins_2.findOneOrNoneFor)(userModel, {
583
- email: betterAuthUser.email,
584
- }));
728
+ const userByEmail = await findAppUserByEmail(userModel, betterAuthUser.email);
585
729
  if (userByEmail?.betterAuthId === betterAuthUser.id) {
586
730
  // A concurrent first contact created this row between the two lookups.
587
731
  return userByEmail;
588
732
  }
589
733
  if (userByEmail) {
590
734
  if (!options.trustEmail) {
591
- assertEmailLinkAllowed(userByEmail, betterAuthUser);
592
- await revokeUnprovenLegacyPassword(userModel, userByEmail);
735
+ assertNotBoundToAnotherAccount(userByEmail, betterAuthUser.id);
736
+ const isEmailVerified = betterAuthUser.emailVerified === true;
737
+ const mayLink = await mayClaimAppUser(userModel, userByEmail, {
738
+ betterAuthId: betterAuthUser.id,
739
+ emailVerified: isEmailVerified,
740
+ password: options.password,
741
+ });
742
+ if (!mayLink) {
743
+ throw verifyEmailRefusal();
744
+ }
745
+ if (isEmailVerified) {
746
+ await revokeUnprovenLegacyPassword(userModel, userByEmail);
747
+ }
593
748
  }
594
749
  // Link existing user to Better Auth
595
750
  userByEmail.betterAuthId = betterAuthUser.id;
@@ -616,10 +771,14 @@ const syncBetterAuthUser = async (userModel, betterAuthUser, oauthProvider, opti
616
771
  }
617
772
  catch (error) {
618
773
  // A duplicate key means a concurrent request created the user first; callers such as
619
- // resolveBetterAuthAppUser recover from it, so it is not an error worth alerting on.
774
+ // resolveBetterAuthAppUser recover from it, so it is not an error worth alerting on. An
775
+ // unverified email that matches an existing User is an expected refusal.
620
776
  if (error.code === 11000) {
621
777
  logger_1.logger.debug(`Better Auth user was created concurrently: ${error}`);
622
778
  }
779
+ else if (isVerifyEmailRefusal(error)) {
780
+ logger_1.logger.info(`[better-auth] Refused to link unverified Better Auth user ${betterAuthUser.id}`);
781
+ }
623
782
  else if ((0, errors_1.isAPIError)(error) && error.status === 409) {
624
783
  logger_1.logger.warn(`Refused to link Better Auth user ${betterAuthUser.id} by email: ${error.title}`);
625
784
  }
@@ -630,6 +789,142 @@ const syncBetterAuthUser = async (userModel, betterAuthUser, oauthProvider, opti
630
789
  }
631
790
  };
632
791
  exports.syncBetterAuthUser = syncBetterAuthUser;
792
+ const isVerifyEmailRefusal = (error) => (0, errors_1.isAPIError)(error) && error.status === 409 && error.message === exports.VERIFY_EMAIL_TO_USE_ACCOUNT;
793
+ const isBoundToAnotherAccountRefusal = (error) => (0, errors_1.isAPIError)(error) && error.status === 409 && error.message === EMAIL_BOUND_TO_ANOTHER_ACCOUNT;
794
+ const bodyString = (body, key) => {
795
+ if (!body || typeof body !== "object") {
796
+ return undefined;
797
+ }
798
+ const value = body[key];
799
+ return typeof value === "string" && value.length > 0 ? value : undefined;
800
+ };
801
+ // The social or generic OAuth provider a session is being created for, if any.
802
+ const oauthProviderFromContext = (context) => {
803
+ const path = context?.path ?? "";
804
+ if (path.startsWith("/callback/")) {
805
+ return context?.params?.id;
806
+ }
807
+ if (path === "/sign-in/social") {
808
+ return bodyString(context?.body, "provider");
809
+ }
810
+ return undefined;
811
+ };
812
+ // The plaintext password, only on the email requests that carry one.
813
+ const passwordFromContext = (context) => {
814
+ if (context?.path !== "/sign-up/email" && context?.path !== "/sign-in/email") {
815
+ return undefined;
816
+ }
817
+ return bodyString(context.body, "password");
818
+ };
819
+ const verifyEmailConflict = () => new api_1.APIError("CONFLICT", {
820
+ code: VERIFY_EMAIL_ERROR_CODE,
821
+ message: exports.VERIFY_EMAIL_TO_USE_ACCOUNT,
822
+ });
823
+ const boundToAnotherAccountConflict = () => new api_1.APIError("CONFLICT", {
824
+ code: EMAIL_BOUND_ERROR_CODE,
825
+ message: EMAIL_BOUND_TO_ANOTHER_ACCOUNT,
826
+ });
827
+ // The app User with this email that no Better Auth user has claimed yet (or another one has).
828
+ const findUnclaimedAppUser = async (userModel, email, betterAuthId) => {
829
+ const appUser = await findAppUserByEmail(userModel, email);
830
+ if (!appUser || (betterAuthId !== undefined && appUser.betterAuthId === betterAuthId)) {
831
+ return null;
832
+ }
833
+ return appUser;
834
+ };
835
+ /**
836
+ * The plugin that guards and syncs the app User while the request that proves who the user is
837
+ * (its password, its provider) is still in hand. Session middleware only sees later requests,
838
+ * which carry neither.
839
+ *
840
+ * - Before a Better Auth user is created: when an app User already has the email, creation is
841
+ * refused with 409 `VERIFY_EMAIL_TO_USE_ACCOUNT` (an OAuth callback redirects with that
842
+ * `error`) unless the provider verified the email or the sign-up password verifies against
843
+ * that User's passport hash. An app User bound to another Better Auth account is always
844
+ * refused, with 409 `ACCOUNT_ALREADY_EXISTS`. Nothing is left behind (no user, account, or verification mail),
845
+ * so a later verification cannot hand an attacker's password the victim's User.
846
+ * - Before a session is created, the app User is synced: the OAuth provider id fills
847
+ * `oauthProvider`, and on `/sign-up/email` and `/sign-in/email` the plaintext password lets an
848
+ * unverified user claim a legacy User. A refusal fails the sign-in with the same 409s. A
849
+ * verified email that links a User whose own email was never verified revokes that User's
850
+ * legacy password and refresh tokens (see `revokeUnprovenLegacyPassword`).
851
+ * - A failed link that a password was proving fails the sign-in (500 `APP_USER_LINK_FAILED`), so
852
+ * no session exists that would be refused on every request. Any other sync failure is logged
853
+ * and the session proceeds; the session middleware retries the sync on the next request.
854
+ */
855
+ const createAppUserSyncPlugin = (userModel) => {
856
+ return {
857
+ id: "terreno-app-user-sync",
858
+ init: (authContext) => {
859
+ const { internalAdapter } = authContext;
860
+ return {
861
+ options: {
862
+ databaseHooks: {
863
+ session: {
864
+ create: {
865
+ before: async (session, rawContext) => {
866
+ const context = rawContext;
867
+ const betterAuthUser = await internalAdapter.findUserById(session.userId);
868
+ if (!betterAuthUser) {
869
+ return;
870
+ }
871
+ const password = passwordFromContext(context);
872
+ try {
873
+ await (0, exports.syncBetterAuthUser)(userModel, betterAuthUser, oauthProviderFromContext(context), { password });
874
+ }
875
+ catch (error) {
876
+ if (isVerifyEmailRefusal(error)) {
877
+ throw verifyEmailConflict();
878
+ }
879
+ if (isBoundToAnotherAccountRefusal(error)) {
880
+ throw boundToAnotherAccountConflict();
881
+ }
882
+ if (error.code === 11000) {
883
+ return;
884
+ }
885
+ logger_1.logger.error(`[better-auth] App user sync on sign-in failed: ${error}`);
886
+ const isPasswordLink = password !== undefined &&
887
+ (await findUnclaimedAppUser(userModel, betterAuthUser.email, betterAuthUser.id)) !== null;
888
+ if (isPasswordLink) {
889
+ throw new api_1.APIError("INTERNAL_SERVER_ERROR", {
890
+ code: "APP_USER_LINK_FAILED",
891
+ message: "Could not link your account. Try again.",
892
+ });
893
+ }
894
+ }
895
+ },
896
+ },
897
+ },
898
+ user: {
899
+ create: {
900
+ before: async (user, rawContext) => {
901
+ const email = typeof user.email === "string" ? user.email : "";
902
+ const appUser = email ? await findUnclaimedAppUser(userModel, email) : null;
903
+ if (!appUser) {
904
+ return;
905
+ }
906
+ if (appUser.betterAuthId) {
907
+ logger_1.logger.info("[better-auth] Refused a sign-up for an app user bound to another account");
908
+ throw boundToAnotherAccountConflict();
909
+ }
910
+ const mayClaim = await mayClaimAppUser(userModel, appUser, {
911
+ emailVerified: user.emailVerified === true,
912
+ password: passwordFromContext(rawContext),
913
+ });
914
+ if (!mayClaim) {
915
+ logger_1.logger.info("[better-auth] Refused a sign-up for an existing app user's email");
916
+ throw verifyEmailConflict();
917
+ }
918
+ },
919
+ },
920
+ },
921
+ },
922
+ },
923
+ };
924
+ },
925
+ };
926
+ };
927
+ exports.createAppUserSyncPlugin = createAppUserSyncPlugin;
633
928
  /**
634
929
  * Finds the application user for a Better Auth session user, creating it on first contact,
635
930
  * and reports whether the account is disabled. Every Better Auth entry point (REST session
@@ -688,17 +983,13 @@ const getMongoClientFromMongoose = () => {
688
983
  };
689
984
  exports.getMongoClientFromMongoose = getMongoClientFromMongoose;
690
985
  /**
691
- * Sets up Better Auth user sync hooks.
692
- * This ensures users created/updated in Better Auth are synced to the application User model.
693
- *
694
- * Note: Better Auth doesn't have built-in event hooks, so we rely on the session middleware
695
- * to create users on first session access.
986
+ * Kept for compatibility; it does nothing. `createBetterAuth` wires the app User sync itself
987
+ * when given a `userModel`: the `terreno-app-user-sync` plugin guards Better Auth user creation
988
+ * and syncs the app User as each session is created (see `createAppUserSyncPlugin`), and
989
+ * `createBetterAuthSessionMiddleware` retries the sync on later requests.
696
990
  */
697
991
  const setupBetterAuthUserSync = (_auth, _userModel) => {
698
- // Better Auth v1.x doesn't expose event hooks for user creation.
699
- // User sync is handled in createBetterAuthSessionMiddleware when a session is accessed.
700
- // This function is a placeholder for future versions that may support hooks.
701
- logger_1.logger.debug("Better Auth user sync configured (via session middleware)");
992
+ logger_1.logger.debug("Better Auth user sync configured (via the terreno-app-user-sync plugin)");
702
993
  };
703
994
  exports.setupBetterAuthUserSync = setupBetterAuthUserSync;
704
995
  /**
@@ -7,13 +7,18 @@
7
7
  */
8
8
  import { type Application } from "express";
9
9
  import type { AdminContribution } from "./adminTypes";
10
- import type { User } from "./auth";
10
+ import { type ResolveConsentForms } from "./consentStatus";
11
11
  import type { PopulatePath } from "./populate";
12
+ import type { AnyTerrenoAccess } from "./rbac/types";
12
13
  import type { TerrenoPlugin } from "./terrenoPlugin";
13
- import type { ConsentFormDocument } from "./types/consentForm";
14
14
  /** Shared populate config for consent response list/read endpoints. */
15
15
  export declare const consentResponsePopulatePaths: PopulatePath[];
16
16
  export interface ConsentAppOptions {
17
+ /**
18
+ * RBAC access control. When set, users whose roles grant `consentResponse:signOnBehalf` may
19
+ * record provisional signatures for other users. When unset, only `user.admin` may.
20
+ */
21
+ accessControl?: AnyTerrenoAccess;
17
22
  auditTrail?: boolean;
18
23
  aiConfig?: {
19
24
  generateContent: (params: {
@@ -27,12 +32,12 @@ export interface ConsentAppOptions {
27
32
  toLocale: string;
28
33
  }) => Promise<string>;
29
34
  };
30
- resolveConsentForms?: (user: User, forms: ConsentFormDocument[]) => ConsentFormDocument[] | Promise<ConsentFormDocument[]>;
35
+ resolveConsentForms?: ResolveConsentForms;
31
36
  supportedLocales?: string[];
32
37
  }
33
38
  export declare class ConsentApp implements TerrenoPlugin {
34
39
  private options;
35
40
  constructor(options?: ConsentAppOptions);
36
41
  adminContribution(): AdminContribution;
37
- register(app: Application): void;
42
+ register(app: Application, openApi?: unknown): void;
38
43
  }