@terreno/api 57.16.2 → 57.18.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 (184) hide show
  1. package/dist/actions.d.ts +26 -3
  2. package/dist/actions.js +102 -16
  3. package/dist/api.d.ts +7 -0
  4. package/dist/api.js +59 -3
  5. package/dist/auth.d.ts +28 -4
  6. package/dist/auth.js +140 -15
  7. package/dist/authRecovery.d.ts +31 -0
  8. package/dist/authRecovery.js +86 -6
  9. package/dist/betterAuth.d.ts +86 -0
  10. package/dist/betterAuthApp.d.ts +17 -0
  11. package/dist/betterAuthApp.js +12 -1
  12. package/dist/betterAuthOAuthHandoff.d.ts +24 -0
  13. package/dist/betterAuthOAuthHandoff.js +305 -0
  14. package/dist/betterAuthSetup.d.ts +37 -2
  15. package/dist/betterAuthSetup.js +304 -24
  16. package/dist/expressServer.d.ts +16 -0
  17. package/dist/expressServer.js +61 -14
  18. package/dist/githubAuth.d.ts +9 -0
  19. package/dist/githubAuth.js +230 -31
  20. package/dist/index.d.ts +9 -1
  21. package/dist/index.js +27 -3
  22. package/dist/mcp/actionTools.d.ts +4 -0
  23. package/dist/mcp/actionTools.js +158 -0
  24. package/dist/mcp/auth.d.ts +30 -0
  25. package/dist/mcp/auth.js +83 -28
  26. package/dist/mcp/createMCPRequest.d.ts +5 -1
  27. package/dist/mcp/createMCPRequest.js +3 -3
  28. package/dist/mcp/handlers.d.ts +3 -0
  29. package/dist/mcp/handlers.js +43 -27
  30. package/dist/mcp/oauth.d.ts +14 -0
  31. package/dist/mcp/oauth.js +618 -0
  32. package/dist/mcp/oauthMetadata.d.ts +89 -0
  33. package/dist/mcp/oauthMetadata.js +137 -0
  34. package/dist/mcp/registry.d.ts +5 -0
  35. package/dist/mcp/registry.js +9 -1
  36. package/dist/mcp/server.d.ts +6 -0
  37. package/dist/mcp/server.js +44 -7
  38. package/dist/mcp/serviceTokens.js +12 -2
  39. package/dist/mcp/toolExecution.d.ts +12 -0
  40. package/dist/mcp/toolExecution.js +60 -0
  41. package/dist/mcp/toolGenerator.d.ts +4 -1
  42. package/dist/mcp/toolGenerator.js +26 -60
  43. package/dist/mcp/types.d.ts +4 -4
  44. package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
  45. package/dist/models/mcpOAuthAuthorization.js +86 -0
  46. package/dist/models/mcpOAuthClient.d.ts +2 -0
  47. package/dist/models/mcpOAuthClient.js +42 -0
  48. package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
  49. package/dist/models/mcpOAuthRevokedFamily.js +36 -0
  50. package/dist/models/mcpOAuthToken.d.ts +12 -0
  51. package/dist/models/mcpOAuthToken.js +159 -0
  52. package/dist/models/mcpServiceToken.d.ts +1 -0
  53. package/dist/models/mcpServiceToken.js +21 -4
  54. package/dist/permissions.d.ts +7 -0
  55. package/dist/permissions.js +18 -1
  56. package/dist/rateLimit/policies.d.ts +4 -0
  57. package/dist/rateLimit/policies.js +46 -7
  58. package/dist/rbac/access.js +1 -0
  59. package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
  60. package/dist/rbac/membershipOrgAdminSource.js +5 -0
  61. package/dist/rbac/modelRouterAccess.d.ts +7 -1
  62. package/dist/rbac/modelRouterAccess.js +37 -24
  63. package/dist/rbac/realtimeAccess.js +17 -3
  64. package/dist/rbac/resolve.js +66 -9
  65. package/dist/rbac/roleManager.js +60 -5
  66. package/dist/rbac/roleModel.js +1 -1
  67. package/dist/rbac/statements.d.ts +1 -1
  68. package/dist/rbac/statements.js +13 -1
  69. package/dist/rbac/types.d.ts +12 -0
  70. package/dist/rbac/userWriteGuards.d.ts +50 -0
  71. package/dist/rbac/userWriteGuards.js +156 -0
  72. package/dist/realtime/changeStreamWatcher.d.ts +4 -1
  73. package/dist/realtime/changeStreamWatcher.js +157 -73
  74. package/dist/realtime/queryMatcher.d.ts +3 -0
  75. package/dist/realtime/queryMatcher.js +25 -10
  76. package/dist/realtime/realtimeApp.d.ts +16 -1
  77. package/dist/realtime/realtimeApp.js +76 -8
  78. package/dist/realtime/socketAuth.d.ts +17 -6
  79. package/dist/realtime/socketAuth.js +77 -16
  80. package/dist/realtime/types.d.ts +8 -5
  81. package/dist/requestContext.d.ts +22 -0
  82. package/dist/requestContext.js +22 -1
  83. package/dist/seedRunner.js +3 -1
  84. package/dist/sortFields.d.ts +33 -0
  85. package/dist/sortFields.js +55 -0
  86. package/dist/sync/executors.js +140 -2
  87. package/dist/sync/models.d.ts +2 -0
  88. package/dist/sync/models.js +5 -0
  89. package/dist/sync/mutationHandler.js +70 -7
  90. package/dist/sync/routes.js +4 -2
  91. package/dist/sync/syncSeqPlugin.js +6 -5
  92. package/dist/terrenoApp.d.ts +14 -0
  93. package/dist/terrenoApp.js +21 -6
  94. package/dist/types/mcpOAuth.d.ts +101 -0
  95. package/dist/types/mcpOAuth.js +2 -0
  96. package/dist/types/mcpServiceToken.d.ts +8 -0
  97. package/package.json +3 -3
  98. package/src/actions.test.ts +118 -0
  99. package/src/actions.ts +139 -17
  100. package/src/api.arrayOperations.test.ts +78 -0
  101. package/src/api.test.ts +36 -0
  102. package/src/api.ts +76 -4
  103. package/src/auth.test.ts +521 -3
  104. package/src/auth.ts +171 -17
  105. package/src/authRecovery.test.ts +99 -0
  106. package/src/authRecovery.ts +117 -5
  107. package/src/authVerification.test.ts +3 -3
  108. package/src/betterAuth.ts +104 -1
  109. package/src/betterAuthApp.test.ts +634 -1
  110. package/src/betterAuthApp.ts +28 -0
  111. package/src/betterAuthOAuthHandoff.test.ts +946 -0
  112. package/src/betterAuthOAuthHandoff.ts +375 -0
  113. package/src/betterAuthSetup.test.ts +393 -4
  114. package/src/betterAuthSetup.ts +402 -29
  115. package/src/expressServer.test.ts +93 -0
  116. package/src/expressServer.ts +81 -14
  117. package/src/githubAuth.test.ts +448 -6
  118. package/src/githubAuth.ts +276 -34
  119. package/src/index.ts +35 -1
  120. package/src/mcp/actionTools.test.ts +498 -0
  121. package/src/mcp/actionTools.ts +220 -0
  122. package/src/mcp/auth.test.ts +114 -1
  123. package/src/mcp/auth.ts +122 -35
  124. package/src/mcp/createMCPRequest.ts +8 -2
  125. package/src/mcp/handlers.test.ts +27 -0
  126. package/src/mcp/handlers.ts +21 -6
  127. package/src/mcp/oauth.test.ts +1026 -0
  128. package/src/mcp/oauth.ts +798 -0
  129. package/src/mcp/oauthMetadata.ts +234 -0
  130. package/src/mcp/registry.ts +11 -0
  131. package/src/mcp/server.ts +54 -14
  132. package/src/mcp/serviceTokens.ts +16 -3
  133. package/src/mcp/toolExecution.ts +67 -0
  134. package/src/mcp/toolGenerator.ts +27 -83
  135. package/src/mcp/types.ts +4 -4
  136. package/src/models/mcpOAuthAuthorization.ts +97 -0
  137. package/src/models/mcpOAuthClient.ts +49 -0
  138. package/src/models/mcpOAuthRevokedFamily.ts +47 -0
  139. package/src/models/mcpOAuthToken.test.ts +82 -0
  140. package/src/models/mcpOAuthToken.ts +195 -0
  141. package/src/models/mcpServiceToken.ts +26 -2
  142. package/src/permissions.ts +17 -0
  143. package/src/rateLimit/policies.ts +54 -10
  144. package/src/rateLimit/rateLimit.test.ts +41 -0
  145. package/src/rbac/access.ts +1 -0
  146. package/src/rbac/membershipOrgAdminSource.ts +5 -0
  147. package/src/rbac/modelRouterAccess.ts +40 -23
  148. package/src/rbac/realtimeAccess.test.ts +43 -0
  149. package/src/rbac/realtimeAccess.ts +23 -3
  150. package/src/rbac/resolve.test.ts +179 -1
  151. package/src/rbac/resolve.ts +78 -9
  152. package/src/rbac/roleManager.test.ts +132 -0
  153. package/src/rbac/roleManager.ts +69 -5
  154. package/src/rbac/roleModel.ts +1 -1
  155. package/src/rbac/statements.ts +14 -1
  156. package/src/rbac/types.ts +12 -0
  157. package/src/rbac/userWriteGuards.test.ts +407 -0
  158. package/src/rbac/userWriteGuards.ts +185 -0
  159. package/src/realtime/changeStreamWatcher.ts +203 -75
  160. package/src/realtime/queryMatcher.ts +30 -13
  161. package/src/realtime/realtime.test.ts +132 -0
  162. package/src/realtime/realtimeApp.ts +94 -10
  163. package/src/realtime/realtimeAppSetup.test.ts +282 -1
  164. package/src/realtime/socketAuth.test.ts +140 -8
  165. package/src/realtime/socketAuth.ts +90 -19
  166. package/src/realtime/types.ts +8 -5
  167. package/src/requestContext.ts +52 -1
  168. package/src/requestCredential.test.ts +89 -0
  169. package/src/seedRunner.test.ts +21 -0
  170. package/src/seedRunner.ts +3 -1
  171. package/src/sortFields.ts +69 -0
  172. package/src/sync/executors.test.ts +382 -3
  173. package/src/sync/executors.ts +179 -4
  174. package/src/sync/models.ts +8 -0
  175. package/src/sync/mutationHandler.test.ts +166 -2
  176. package/src/sync/mutationHandler.ts +97 -5
  177. package/src/sync/routes.ts +4 -2
  178. package/src/sync/syncFrontier.test.ts +11 -0
  179. package/src/sync/syncPhaseC.test.ts +18 -0
  180. package/src/sync/syncSeqPlugin.ts +6 -5
  181. package/src/sync/syncSocket.test.ts +92 -0
  182. package/src/terrenoApp.ts +36 -21
  183. package/src/types/mcpOAuth.ts +129 -0
  184. package/src/types/mcpServiceToken.ts +6 -1
package/src/auth.ts CHANGED
@@ -12,13 +12,15 @@ import {
12
12
  type StrategyOptions,
13
13
  } from "passport-jwt";
14
14
  import {Strategy as LocalStrategy} from "passport-local";
15
- import {addAuthRecoveryRoutes, sendVerificationEmail} from "./authRecovery";
15
+ import {addAuthRecoveryRoutes, sendEmailChangedNotice, sendVerificationEmail} from "./authRecovery";
16
16
  import {AuthToken} from "./authTokens";
17
17
  import {APIError, apiErrorMiddleware, errorMessage} from "./errors";
18
- import type {AuthOptions} from "./expressServer";
18
+ import type {AuthOptions, BetterAuthPasswordCheck} from "./expressServer";
19
19
  import {logger} from "./logger";
20
20
  import {isJwtCredentialExchangePath} from "./rateLimit/policies";
21
+ import {isRbacUserModelName, isWriteKeyForField} from "./rbac/userWriteGuards";
21
22
  import {
23
+ getCurrentRequestContext,
22
24
  getSessionIdFromJwtPayload,
23
25
  type JwtSessionPayload,
24
26
  setRequestContext,
@@ -98,6 +100,10 @@ export const authenticateMiddleware = (anonymous = false) => {
98
100
  // req.logIn used to populate authInfo; keep that passport-public API
99
101
  // intact for downstream consumers.
100
102
  req.authInfo = (info ?? {}) as Express.AuthInfo;
103
+ // Only the jwt strategy reaches this callback with a user (anonymous calls pass()).
104
+ if (!getCurrentRequestContext()?.credential) {
105
+ setRequestContext({credential: "jwt"});
106
+ }
101
107
  return next();
102
108
  }
103
109
  )(req, res, next);
@@ -119,8 +125,46 @@ export const PRIVILEGED_USER_FIELDS = [
119
125
  ] as const;
120
126
 
121
127
  /**
122
- * Removes {@link PRIVILEGED_USER_FIELDS} from a self-service body. Fields are dropped rather
123
- * than rejected so clients that echo a whole user object back still succeed.
128
+ * passport-local-mongoose password and lockout fields. Only the password flows (reset,
129
+ * `setPassword`-gated actions) write them, so RBAC user-model writes through modelRouter, sync,
130
+ * MCP, and the admin panel drop them along with {@link PRIVILEGED_USER_FIELDS}.
131
+ */
132
+ export const USER_CREDENTIAL_FIELDS = ["hash", "salt", "attempts", "last"] as const;
133
+
134
+ const RBAC_USER_WRITE_BLOCKED_FIELDS = [...PRIVILEGED_USER_FIELDS, ...USER_CREDENTIAL_FIELDS];
135
+
136
+ /**
137
+ * Fields self-service requests (anonymous signup, `PATCH /me`) must never set: the
138
+ * {@link PRIVILEGED_USER_FIELDS} plus the fields that bind an external credential to the row
139
+ * (Better Auth id, GitHub link, OAuth provider), the passport-local-mongoose password and
140
+ * lockout state, and the disabled flag. Only the Better Auth sync, GitHub link, and password
141
+ * flows that own them write these. Kept apart from PRIVILEGED_USER_FIELDS so authorized admin
142
+ * User writes through modelRouter, sync, MCP, and the admin panel can still manage the identity
143
+ * and disabled fields (those writes still drop {@link USER_CREDENTIAL_FIELDS}).
144
+ */
145
+ export const SELF_SERVICE_BLOCKED_USER_FIELDS = [
146
+ ...PRIVILEGED_USER_FIELDS,
147
+ "betterAuthId",
148
+ "githubId",
149
+ "githubUsername",
150
+ "githubProfileUrl",
151
+ "githubAvatarUrl",
152
+ "oauthProvider",
153
+ "hash",
154
+ "salt",
155
+ "attempts",
156
+ "last",
157
+ "disabled",
158
+ ] as const;
159
+
160
+ const isWriteKeyForAnyField = (key: string, fields: readonly string[]): boolean => {
161
+ return fields.some((field) => isWriteKeyForField(key, field));
162
+ };
163
+
164
+ /**
165
+ * Removes {@link SELF_SERVICE_BLOCKED_USER_FIELDS} from a self-service body, including dotted
166
+ * paths into them (`roles.0`). Fields are dropped rather than rejected so clients that echo a
167
+ * whole user object back still succeed.
124
168
  */
125
169
  export const stripPrivilegedUserFields = (
126
170
  body: Record<string, unknown>,
@@ -129,7 +173,7 @@ export const stripPrivilegedUserFields = (
129
173
  const sanitized: Record<string, unknown> = {};
130
174
  const dropped: string[] = [];
131
175
  for (const [key, value] of Object.entries(body)) {
132
- if ((PRIVILEGED_USER_FIELDS as readonly string[]).includes(key)) {
176
+ if (isWriteKeyForAnyField(key, SELF_SERVICE_BLOCKED_USER_FIELDS)) {
133
177
  dropped.push(key);
134
178
  continue;
135
179
  }
@@ -141,6 +185,9 @@ export const stripPrivilegedUserFields = (
141
185
  return sanitized;
142
186
  };
143
187
 
188
+ // Password keys clients send to a profile update; PATCH /me rejects them rather than ignore them.
189
+ const PROFILE_PASSWORD_FIELDS = ["password", "newPassword"] as const;
190
+
144
191
  const isEmailUpdateChangingMailbox = (currentEmail: unknown, nextEmail: unknown): boolean => {
145
192
  if (typeof currentEmail !== "string" || typeof nextEmail !== "string") {
146
193
  return false;
@@ -148,13 +195,65 @@ const isEmailUpdateChangingMailbox = (currentEmail: unknown, nextEmail: unknown)
148
195
  return currentEmail.trim().toLowerCase() !== nextEmail.trim().toLowerCase();
149
196
  };
150
197
 
198
+ // The body field PATCH /me reads to confirm an email change. It is never written to the user.
199
+ const CURRENT_PASSWORD_FIELD = "currentPassword";
200
+
201
+ // passport-local-mongoose errors that mean the user has no passport password to check.
202
+ const NO_PASSPORT_PASSWORD_ERRORS = new Set(["IncorrectUsernameError", "NoSaltValueStoredError"]);
203
+
204
+ // passport-local-mongoose lockout errors (`limitAttempts`), reported to the user as they are.
205
+ const LOCKOUT_ERRORS = new Set(["AttemptTooSoonError", "TooManyAttemptsError"]);
206
+
207
+ interface PassportAuthenticateResult {
208
+ error?: {message?: string; name?: string};
209
+ user?: unknown;
210
+ }
211
+
212
+ interface CurrentPasswordCheck {
213
+ message?: string;
214
+ status: BetterAuthPasswordCheck;
215
+ }
216
+
217
+ /**
218
+ * Confirm `password` is the user's current password: first against the passport-local-mongoose
219
+ * hash (which counts a wrong attempt toward its lockout when `limitAttempts` is on), then, for a
220
+ * user with no passport password, against the Better Auth credential when Better Auth is wired.
221
+ */
222
+ const checkCurrentPassword = async (
223
+ doc: User,
224
+ password: string,
225
+ authOptions: AuthOptions | undefined
226
+ ): Promise<CurrentPasswordCheck> => {
227
+ const authenticate = (doc as unknown as {authenticate?: (password: string) => unknown})
228
+ .authenticate;
229
+ if (typeof authenticate === "function") {
230
+ const result = (await authenticate.call(doc, password)) as PassportAuthenticateResult;
231
+ if (result?.user) {
232
+ return {status: "verified"};
233
+ }
234
+ const errorName = result?.error?.name ?? "";
235
+ if (!NO_PASSPORT_PASSWORD_ERRORS.has(errorName)) {
236
+ // Pass the lockout message through so the user knows why a right password fails.
237
+ const message = LOCKOUT_ERRORS.has(errorName) ? result?.error?.message : undefined;
238
+ return {message, status: "wrong"};
239
+ }
240
+ }
241
+ if (authOptions?.verifyBetterAuthPassword) {
242
+ return {status: await authOptions.verifyBetterAuthPassword(doc, password)};
243
+ }
244
+ return {status: "no-password"};
245
+ };
246
+
151
247
  const omitPrivilegedFieldsFromObject = (item: unknown, allowAdminWrite: boolean): unknown => {
152
248
  if (!item || typeof item !== "object" || Array.isArray(item)) {
153
249
  return item;
154
250
  }
155
251
  const record = item as Record<string, unknown>;
156
- const fieldsToDrop = PRIVILEGED_USER_FIELDS.filter(
157
- (field) => field in record && !(field === "admin" && allowAdminWrite)
252
+ // Only the exact `admin` key is an authorized legacy-admin write; `admin.x` is never one.
253
+ const fieldsToDrop = Object.keys(record).filter(
254
+ (key) =>
255
+ isWriteKeyForAnyField(key, RBAC_USER_WRITE_BLOCKED_FIELDS) &&
256
+ !(key === "admin" && allowAdminWrite)
158
257
  );
159
258
  if (fieldsToDrop.length === 0) {
160
259
  return item;
@@ -170,7 +269,8 @@ const omitPrivilegedFieldsFromObject = (item: unknown, allowAdminWrite: boolean)
170
269
  /**
171
270
  * When RBAC is enabled, authority-bearing User fields must not flow through ordinary mongoose
172
271
  * writes on `/users`, sync, or MCP. AdminApp captures role assignments before this runs and
173
- * explicitly marks authorized legacy-admin writes after its additional checks.
272
+ * explicitly marks authorized legacy-admin writes after its additional checks. The user model is
273
+ * recognized by {@link isRbacUserModelName}.
174
274
  */
175
275
  export const omitUserRolesFromWriteBody = (
176
276
  modelName: string,
@@ -178,7 +278,7 @@ export const omitUserRolesFromWriteBody = (
178
278
  body: unknown,
179
279
  allowAdminWrite = false
180
280
  ): unknown => {
181
- if (modelName !== "User" || !accessControl || body == null) {
281
+ if (!isRbacUserModelName(modelName, accessControl) || body == null) {
182
282
  return body;
183
283
  }
184
284
  if (Array.isArray(body)) {
@@ -417,6 +517,14 @@ export const generateTokens = async (
417
517
  return {refreshToken, sessionId, token};
418
518
  };
419
519
 
520
+ /**
521
+ * Whether an account has been disabled (`isDisabledPlugin`). Disabled users must not
522
+ * authenticate or receive new tokens on any path.
523
+ * @internal
524
+ */
525
+ export const isUserDisabled = (user: unknown): boolean =>
526
+ (user as {disabled?: boolean} | null | undefined)?.disabled === true;
527
+
420
528
  export const setupAuth = (app: express.Application, userModel: UserModel): void => {
421
529
  if (!userModel.createStrategy) {
422
530
  throw new APIError({status: 500, title: "setupAuth userModel must have .createStrategy()"});
@@ -442,14 +550,17 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
442
550
  ) as passport.Strategy
443
551
  );
444
552
 
553
+ // Only the jwt cookie or the Bearer scheme carries an access JWT. Other schemes (such as
554
+ // "Secret") skip decodeJWTMiddleware, so passport must not read a JWT out of them either.
445
555
  const customTokenExtractor: JwtFromRequestFunction = (req) => {
446
- let token: string | null = null;
447
556
  if (req?.cookies?.jwt) {
448
- token = req.cookies.jwt;
449
- } else if (req?.headers?.authorization) {
450
- token = req?.headers?.authorization.split(" ")[1];
557
+ return req.cookies.jwt;
558
+ }
559
+ const [scheme, value] = (req?.headers?.authorization ?? "").split(" ");
560
+ if (scheme?.toLowerCase() === "bearer" && value) {
561
+ return value;
451
562
  }
452
- return token;
563
+ return null;
453
564
  };
454
565
 
455
566
  if (process.env.TOKEN_SECRET) {
@@ -477,6 +588,10 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
477
588
  return done(error, false);
478
589
  }
479
590
  if (user) {
591
+ if (isUserDisabled(user)) {
592
+ logger.warn(`[jwt] User ${user.id} is disabled`);
593
+ return done(null, false);
594
+ }
480
595
  return done(null, user);
481
596
  }
482
597
  if (userModel.createAnonymousUser) {
@@ -600,6 +715,10 @@ export const addAuthRoutes = (
600
715
  logger.warn(`Invalid login: ${info}`);
601
716
  return res.status(401).json({message: info?.message});
602
717
  }
718
+ if (isUserDisabled(user)) {
719
+ logger.warn(`[auth] Refusing login for disabled user ${user._id}`);
720
+ return next(new APIError({status: 401, title: "User is disabled"}));
721
+ }
603
722
  if (authOptions?.requireEmailVerification && user.emailVerified !== true) {
604
723
  return next(
605
724
  new APIError({
@@ -650,7 +769,7 @@ export const addAuthRoutes = (
650
769
  const user = await userModel.findById(decoded.id);
651
770
  const tokenEpoch = typeof decoded.te === "number" ? decoded.te : 0;
652
771
  const userEpoch = (user as User | null)?.tokenEpoch ?? 0;
653
- if (!user || tokenEpoch !== userEpoch) {
772
+ if (!user || tokenEpoch !== userEpoch || isUserDisabled(user)) {
654
773
  logger.error(`Invalid refresh token, user id: ${req.user?.id}`);
655
774
  return res.status(401).json({message: "Invalid refresh token"});
656
775
  }
@@ -724,7 +843,7 @@ export const addAuthRoutes = (
724
843
  export const addMeRoutes = (
725
844
  app: express.Application,
726
845
  userModel: UserModel,
727
- _authOptions?: AuthOptions,
846
+ authOptions?: AuthOptions,
728
847
  accessControl?: import("./rbac/types").AnyTerrenoAccess
729
848
  ): void => {
730
849
  const router = express.Router();
@@ -764,9 +883,41 @@ export const addMeRoutes = (
764
883
  // } catch (e) {
765
884
  // return res.status(403).send({message: (e as Error).message});
766
885
  // }
886
+ const body = (req.body ?? {}) as Record<string, unknown>;
887
+ // `password` is not a schema path, so assigning it would save nothing and still answer 200.
888
+ if (PROFILE_PASSWORD_FIELDS.some((field) => field in body)) {
889
+ return res.status(400).send({
890
+ message:
891
+ "PATCH /auth/me does not change passwords. Use the password reset flow or Better Auth change-password.",
892
+ });
893
+ }
894
+ const {[CURRENT_PASSWORD_FIELD]: currentPassword, ...profileBody} = body;
895
+ const previousEmail = doc.email;
767
896
  try {
768
- const update = stripPrivilegedUserFields(req.body ?? {}, "PATCH /auth/me");
897
+ const update = stripPrivilegedUserFields(profileBody, "PATCH /auth/me");
769
898
  const isMailboxChange = isEmailUpdateChangingMailbox(doc.email, update.email);
899
+ if (isMailboxChange) {
900
+ // A stolen session must not be able to move the recovery address, so changing the
901
+ // mailbox needs the current password.
902
+ if (typeof currentPassword !== "string" || currentPassword.length === 0) {
903
+ return res.status(403).send({
904
+ message: "Enter your current password to change your email.",
905
+ });
906
+ }
907
+ const check = await checkCurrentPassword(doc, currentPassword, authOptions);
908
+ if (check.status === "no-password") {
909
+ return res.status(400).send({
910
+ message:
911
+ "Set a password on your account before changing your email. Use the password reset flow to set one.",
912
+ });
913
+ }
914
+ if (check.status === "wrong") {
915
+ logger.warn(`[auth] Rejected email change for user ${String(doc._id)}: wrong password`);
916
+ return res.status(403).send({
917
+ message: check.message ?? "The current password is incorrect.",
918
+ });
919
+ }
920
+ }
770
921
  Object.assign(doc, update);
771
922
  if (isMailboxChange) {
772
923
  await AuthToken.invalidateUnusedFor({_id: String(doc._id)}, "passwordReset");
@@ -776,6 +927,9 @@ export const addMeRoutes = (
776
927
  }
777
928
  }
778
929
  await doc.save();
930
+ if (isMailboxChange && typeof previousEmail === "string" && typeof doc.email === "string") {
931
+ await sendEmailChangedNotice({authOptions, newEmail: doc.email, previousEmail});
932
+ }
779
933
 
780
934
  const dataObject = doc.toObject() as unknown as Record<string, unknown>;
781
935
  dataObject.id = doc._id;
@@ -5,12 +5,14 @@ import mongoose from "mongoose";
5
5
  import supertest from "supertest";
6
6
 
7
7
  import {MAX_PASSWORD_LENGTH} from "./auth";
8
+ import {changeUserPassword} from "./authRecovery";
8
9
  import {AuthToken} from "./authTokens";
9
10
  import {TerrenoApp} from "./terrenoApp";
10
11
  import {setupDb, UserModel} from "./tests";
11
12
 
12
13
  interface CapturedMail {
13
14
  html?: string;
15
+ sensitive?: boolean;
14
16
  subject: string;
15
17
  text: string;
16
18
  to: string;
@@ -43,6 +45,25 @@ describe("password reset routes", () => {
43
45
  }).build();
44
46
  });
45
47
 
48
+ it("marks reset and verification mail as sensitive so transports do not store the link", async () => {
49
+ await supertest(app)
50
+ .post("/auth/forgotPassword")
51
+ .send({email: "notAdmin@example.com"})
52
+ .expect(202);
53
+ const login = await supertest(app)
54
+ .post("/auth/login")
55
+ .send({email: "notAdmin@example.com", password: "password"})
56
+ .expect(200);
57
+ await supertest(app)
58
+ .post("/auth/sendVerification")
59
+ .set("authorization", `Bearer ${login.body.data.token}`)
60
+ .send({})
61
+ .expect(202);
62
+
63
+ assert.lengthOf(sentMail, 2);
64
+ assert.isTrue(sentMail.every((mail) => mail.sensitive === true));
65
+ });
66
+
46
67
  it("returns 202 for existing and missing emails and only mails existing users", async () => {
47
68
  const existing = await supertest(app)
48
69
  .post("/auth/forgotPassword")
@@ -218,6 +239,27 @@ describe("password reset routes", () => {
218
239
  assert.equal(synced[0]?.password, "bridged-password-123");
219
240
  });
220
241
 
242
+ it("refuses to reset the password or issue tokens for a disabled user", async () => {
243
+ await supertest(app)
244
+ .post("/auth/forgotPassword")
245
+ .send({email: "notAdmin@example.com"})
246
+ .expect(202);
247
+ const token = tokenFromResetUrl(sentMail[0]?.text ?? "");
248
+ await UserModel.updateOne({email: "notAdmin@example.com"}, {disabled: true});
249
+
250
+ const reset = await supertest(app)
251
+ .post("/auth/resetPassword")
252
+ .send({password: "disabled-new-password", token})
253
+ .expect(401);
254
+ assert.isUndefined(reset.body.data?.token);
255
+
256
+ await UserModel.updateOne({email: "notAdmin@example.com"}, {disabled: false});
257
+ await supertest(app)
258
+ .post("/auth/login")
259
+ .send({email: "notAdmin@example.com", password: "disabled-new-password"})
260
+ .expect(401);
261
+ });
262
+
221
263
  it("does not consume a reset token when the new password is too long", async () => {
222
264
  await supertest(app)
223
265
  .post("/auth/forgotPassword")
@@ -322,3 +364,60 @@ describe("password reset routes", () => {
322
364
  }
323
365
  });
324
366
  });
367
+
368
+ describe("changeUserPassword", () => {
369
+ beforeEach(async () => {
370
+ await setupDb();
371
+ });
372
+
373
+ it("sets the password, bumps tokenEpoch, and runs the Better Auth sync registered on the app", async () => {
374
+ const synced: string[] = [];
375
+ const app = new TerrenoApp({
376
+ authOptions: {
377
+ syncPasswordResetToBetterAuth: async (_user, password): Promise<void> => {
378
+ synced.push(password);
379
+ },
380
+ },
381
+ skipListen: true,
382
+ userModel: UserModel,
383
+ }).build();
384
+ const login = await supertest(app)
385
+ .post("/auth/login")
386
+ .send({email: "notAdmin@example.com", password: "password"})
387
+ .expect(200);
388
+ const user = await UserModel.findOne({email: "notAdmin@example.com"});
389
+ assert.isNotNull(user);
390
+
391
+ await changeUserPassword(user as never, "changed-password-123", {adminId: "admin-1", app});
392
+
393
+ assert.deepEqual(synced, ["changed-password-123"]);
394
+ const stored = await UserModel.findOne({email: "notAdmin@example.com"});
395
+ assert.equal(stored?.tokenEpoch, 1);
396
+ await supertest(app)
397
+ .post("/auth/refresh_token")
398
+ .send({refreshToken: login.body.data.refreshToken})
399
+ .expect(401);
400
+ await supertest(app)
401
+ .post("/auth/login")
402
+ .send({email: "notAdmin@example.com", password: "changed-password-123"})
403
+ .expect(200);
404
+ });
405
+
406
+ it("prefers explicit authOptions and works without an app", async () => {
407
+ const synced: string[] = [];
408
+ const user = await UserModel.findOne({email: "notAdmin@example.com"});
409
+
410
+ await changeUserPassword(user as never, "explicit-password-123", {
411
+ authOptions: {
412
+ syncPasswordResetToBetterAuth: async (_user, password): Promise<void> => {
413
+ synced.push(password);
414
+ },
415
+ },
416
+ });
417
+ await changeUserPassword(user as never, "no-sync-password-123");
418
+
419
+ assert.deepEqual(synced, ["explicit-password-123"]);
420
+ const stored = await UserModel.findOne({email: "notAdmin@example.com"});
421
+ assert.equal(stored?.tokenEpoch, 2);
422
+ });
423
+ });
@@ -5,6 +5,7 @@ import {
5
5
  authenticateMiddleware,
6
6
  generateTokens,
7
7
  type HasSetPassword,
8
+ isUserDisabled,
8
9
  MAX_PASSWORD_LENGTH,
9
10
  setPasswordForUser,
10
11
  type User,
@@ -112,6 +113,7 @@ export const sendVerificationEmail = async (
112
113
  const verifyUrl = buildVerifyUrl(authOptions.publicAppUrl, issued.token);
113
114
  await deliverRecoveryMail(authOptions, {
114
115
  html: verifyEmailHtml(verifyUrl),
116
+ sensitive: true,
115
117
  subject: VERIFY_EMAIL_SUBJECT,
116
118
  text: verifyEmailText(verifyUrl),
117
119
  to: userEmail(user),
@@ -134,15 +136,126 @@ const deliverRecoveryMail = async (
134
136
  );
135
137
  };
136
138
 
139
+ const EMAIL_CHANGED_SUBJECT = "Your account email was changed";
140
+
141
+ const maskSegment = (value: string): string => {
142
+ if (value.length === 0) {
143
+ return "***";
144
+ }
145
+ return `${value[0]}***`;
146
+ };
147
+
148
+ /**
149
+ * Partially mask an email for a notice: `renamed@example.com` becomes `r***@e***.com`. Keeps the
150
+ * first character of the local part and of the domain, plus the top-level domain.
151
+ */
152
+ export const maskEmailAddress = (email: string): string => {
153
+ const trimmed = email.trim();
154
+ const atIndex = trimmed.lastIndexOf("@");
155
+ if (atIndex <= 0) {
156
+ return maskSegment(trimmed);
157
+ }
158
+ const local = trimmed.slice(0, atIndex);
159
+ const domain = trimmed.slice(atIndex + 1);
160
+ const dotIndex = domain.lastIndexOf(".");
161
+ if (dotIndex <= 0) {
162
+ return `${maskSegment(local)}@${maskSegment(domain)}`;
163
+ }
164
+ return `${maskSegment(local)}@${maskSegment(domain.slice(0, dotIndex))}${domain.slice(dotIndex)}`;
165
+ };
166
+
167
+ const emailChangedText = (maskedNewEmail: string): string =>
168
+ `The email address on your account was changed to ${maskedNewEmail}. ` +
169
+ "If you did not make this change, contact support right away.";
170
+
171
+ const emailChangedHtml = (maskedNewEmail: string): string =>
172
+ `<p>The email address on your account was changed to ${maskedNewEmail}.</p>` +
173
+ "<p>If you did not make this change, contact support right away.</p>";
174
+
175
+ /**
176
+ * Tell the previous address that the account email changed. The notice carries no link or token
177
+ * that acts on the account. Without a configured `sendMail` it logs a warning and sends nothing;
178
+ * a delivery failure is logged and never undoes the change.
179
+ */
180
+ export const sendEmailChangedNotice = async ({
181
+ authOptions,
182
+ newEmail,
183
+ previousEmail,
184
+ }: {
185
+ authOptions?: AuthOptions;
186
+ newEmail: string;
187
+ previousEmail: string;
188
+ }): Promise<void> => {
189
+ if (!authOptions?.sendMail) {
190
+ logger.warn(
191
+ "[auth] No sendMail configured; skipped the email change notice to the old address"
192
+ );
193
+ return;
194
+ }
195
+ const maskedNewEmail = maskEmailAddress(newEmail);
196
+ try {
197
+ await authOptions.sendMail({
198
+ html: emailChangedHtml(maskedNewEmail),
199
+ sensitive: true,
200
+ subject: EMAIL_CHANGED_SUBJECT,
201
+ text: emailChangedText(maskedNewEmail),
202
+ to: previousEmail,
203
+ });
204
+ } catch (error: unknown) {
205
+ logger.error("[auth] Failed to send the email change notice to the old address", {error});
206
+ }
207
+ };
208
+
137
209
  const incrementTokenEpoch = (user: User): void => {
138
210
  user.tokenEpoch = (user.tokenEpoch ?? 0) + 1;
139
211
  };
140
212
 
213
+ // The auth options passed to addAuthRoutes, kept on the app so changeUserPassword can reach the
214
+ // Better Auth credential sync that TerrenoApp wires after the routes are added.
215
+ const AUTH_OPTIONS_LOCAL_KEY = "terrenoAuthOptions";
216
+
217
+ const authOptionsFromApp = (app: express.Application | undefined): AuthOptions | undefined =>
218
+ app?.locals?.[AUTH_OPTIONS_LOCAL_KEY] as AuthOptions | undefined;
219
+
220
+ export interface ChangeUserPasswordOptions {
221
+ /** The admin making the change; recorded in the audit log line, never with the password. */
222
+ adminId?: unknown;
223
+ /** The Express app (`req.app`) the auth routes were added to. */
224
+ app?: express.Application;
225
+ /** Auth options to use instead of the ones registered on `app`. */
226
+ authOptions?: AuthOptions;
227
+ }
228
+
229
+ /**
230
+ * Change a user's password on the server and end the credentials issued before it: sets the
231
+ * passport password, increments `tokenEpoch` (legacy refresh tokens and MCP credentials stop
232
+ * working), saves, and, when Better Auth is registered, sets the Better Auth password and deletes
233
+ * that user's Better Auth sessions. Use it for every server-side password change; calling
234
+ * `setPasswordForUser` alone revokes nothing.
235
+ */
236
+ export const changeUserPassword = async (
237
+ user: User,
238
+ password: string,
239
+ options: ChangeUserPasswordOptions = {}
240
+ ): Promise<void> => {
241
+ const audit = options.adminId === undefined ? undefined : {adminId: options.adminId};
242
+ await setPasswordForUser(user as unknown as HasSetPassword, password, undefined, audit);
243
+ incrementTokenEpoch(user);
244
+ await (user as unknown as {save: () => Promise<unknown>}).save();
245
+ const authOptions = options.authOptions ?? authOptionsFromApp(options.app);
246
+ if (authOptions?.syncPasswordResetToBetterAuth) {
247
+ await authOptions.syncPasswordResetToBetterAuth(user, password);
248
+ }
249
+ };
250
+
141
251
  export const addAuthRecoveryRoutes = (
142
252
  app: express.Application,
143
253
  userModel: UserModel,
144
254
  authOptions?: AuthOptions
145
255
  ): void => {
256
+ if (authOptions) {
257
+ app.locals[AUTH_OPTIONS_LOCAL_KEY] = authOptions;
258
+ }
146
259
  const forgotPassword = asyncHandler(async (req: express.Request, res: express.Response) => {
147
260
  const email = normalizeEmail(req.body?.email);
148
261
  if (email) {
@@ -156,6 +269,7 @@ export const addAuthRecoveryRoutes = (
156
269
  const resetUrl = buildResetUrl(authOptions.publicAppUrl, issued.token);
157
270
  await deliverRecoveryMail(authOptions, {
158
271
  html: resetPasswordHtml(resetUrl),
272
+ sensitive: true,
159
273
  subject: RESET_PASSWORD_SUBJECT,
160
274
  text: resetPasswordText(resetUrl),
161
275
  to: userEmail(user, email),
@@ -190,12 +304,10 @@ export const addAuthRecoveryRoutes = (
190
304
  if (!user) {
191
305
  throw new APIError({status: 400, title: "Invalid or expired reset token"});
192
306
  }
193
- await setPasswordForUser(user as unknown as HasSetPassword, password);
194
- incrementTokenEpoch(user);
195
- await (user as unknown as {save: () => Promise<unknown>}).save();
196
- if (authOptions?.syncPasswordResetToBetterAuth) {
197
- await authOptions.syncPasswordResetToBetterAuth(user, password);
307
+ if (isUserDisabled(user)) {
308
+ throw new APIError({status: 401, title: "User is disabled"});
198
309
  }
310
+ await changeUserPassword(user, password, {authOptions});
199
311
  const tokens = await generateTokens(user, authOptions);
200
312
  return res.json({
201
313
  data: {refreshToken: tokens.refreshToken, token: tokens.token, userId: user._id},
@@ -229,7 +229,7 @@ describe("email verification gating", () => {
229
229
  await supertest(openApp)
230
230
  .patch("/auth/me")
231
231
  .set("authorization", `Bearer ${accessToken}`)
232
- .send({email: "new-mailbox@example.com"})
232
+ .send({currentPassword: "password", email: "new-mailbox@example.com"})
233
233
  .expect(200);
234
234
 
235
235
  await supertest(openApp).post("/auth/verifyEmail").send({token: issued.token}).expect(400);
@@ -250,7 +250,7 @@ describe("email verification gating", () => {
250
250
  await supertest(openApp)
251
251
  .patch("/auth/me")
252
252
  .set("authorization", `Bearer ${accessToken}`)
253
- .send({email: "new-mailbox@example.com"})
253
+ .send({currentPassword: "password", email: "new-mailbox@example.com"})
254
254
  .expect(200);
255
255
 
256
256
  await supertest(openApp)
@@ -303,7 +303,7 @@ describe("email verification gating", () => {
303
303
  await supertest(app)
304
304
  .patch("/auth/me")
305
305
  .set("authorization", `Bearer ${accessToken}`)
306
- .send({email: "new-reset-only@example.com"})
306
+ .send({currentPassword: "password", email: "new-reset-only@example.com"})
307
307
  .expect(200);
308
308
 
309
309
  await supertest(app)