@terreno/api 57.16.2 → 57.17.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/dist/auth.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.addMeRoutes = exports.addAuthRoutes = exports.setupAuth = exports.generateTokens = exports.setPasswordForUser = exports.MAX_PASSWORD_LENGTH = exports.signupUser = exports.omitUserRolesFromWriteBody = exports.stripPrivilegedUserFields = exports.PRIVILEGED_USER_FIELDS = exports.authenticateMiddleware = void 0;
6
+ exports.addMeRoutes = exports.addAuthRoutes = exports.setupAuth = exports.isUserDisabled = exports.generateTokens = exports.setPasswordForUser = exports.MAX_PASSWORD_LENGTH = exports.signupUser = exports.omitUserRolesFromWriteBody = exports.stripPrivilegedUserFields = exports.SELF_SERVICE_BLOCKED_USER_FIELDS = exports.USER_CREDENTIAL_FIELDS = exports.PRIVILEGED_USER_FIELDS = exports.authenticateMiddleware = void 0;
7
7
  const node_crypto_1 = require("node:crypto");
8
8
  const express_1 = __importDefault(require("express"));
9
9
  const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
@@ -18,6 +18,7 @@ const authTokens_1 = require("./authTokens");
18
18
  const errors_1 = require("./errors");
19
19
  const logger_1 = require("./logger");
20
20
  const policies_1 = require("./rateLimit/policies");
21
+ const userWriteGuards_1 = require("./rbac/userWriteGuards");
21
22
  const requestContext_1 = require("./requestContext");
22
23
  const authenticateMiddleware = (anonymous = false) => {
23
24
  const strategies = ["jwt"];
@@ -47,6 +48,10 @@ const authenticateMiddleware = (anonymous = false) => {
47
48
  // req.logIn used to populate authInfo; keep that passport-public API
48
49
  // intact for downstream consumers.
49
50
  req.authInfo = (info ?? {});
51
+ // Only the jwt strategy reaches this callback with a user (anonymous calls pass()).
52
+ if (!(0, requestContext_1.getCurrentRequestContext)()?.credential) {
53
+ (0, requestContext_1.setRequestContext)({ credential: "jwt" });
54
+ }
50
55
  return next();
51
56
  })(req, res, next);
52
57
  };
@@ -66,14 +71,48 @@ exports.PRIVILEGED_USER_FIELDS = [
66
71
  "tokenEpoch",
67
72
  ];
68
73
  /**
69
- * Removes {@link PRIVILEGED_USER_FIELDS} from a self-service body. Fields are dropped rather
70
- * than rejected so clients that echo a whole user object back still succeed.
74
+ * passport-local-mongoose password and lockout fields. Only the password flows (reset,
75
+ * `setPassword`-gated actions) write them, so RBAC user-model writes through modelRouter, sync,
76
+ * MCP, and the admin panel drop them along with {@link PRIVILEGED_USER_FIELDS}.
77
+ */
78
+ exports.USER_CREDENTIAL_FIELDS = ["hash", "salt", "attempts", "last"];
79
+ const RBAC_USER_WRITE_BLOCKED_FIELDS = [...exports.PRIVILEGED_USER_FIELDS, ...exports.USER_CREDENTIAL_FIELDS];
80
+ /**
81
+ * Fields self-service requests (anonymous signup, `PATCH /me`) must never set: the
82
+ * {@link PRIVILEGED_USER_FIELDS} plus the fields that bind an external credential to the row
83
+ * (Better Auth id, GitHub link, OAuth provider), the passport-local-mongoose password and
84
+ * lockout state, and the disabled flag. Only the Better Auth sync, GitHub link, and password
85
+ * flows that own them write these. Kept apart from PRIVILEGED_USER_FIELDS so authorized admin
86
+ * User writes through modelRouter, sync, MCP, and the admin panel can still manage the identity
87
+ * and disabled fields (those writes still drop {@link USER_CREDENTIAL_FIELDS}).
88
+ */
89
+ exports.SELF_SERVICE_BLOCKED_USER_FIELDS = [
90
+ ...exports.PRIVILEGED_USER_FIELDS,
91
+ "betterAuthId",
92
+ "githubId",
93
+ "githubUsername",
94
+ "githubProfileUrl",
95
+ "githubAvatarUrl",
96
+ "oauthProvider",
97
+ "hash",
98
+ "salt",
99
+ "attempts",
100
+ "last",
101
+ "disabled",
102
+ ];
103
+ const isWriteKeyForAnyField = (key, fields) => {
104
+ return fields.some((field) => (0, userWriteGuards_1.isWriteKeyForField)(key, field));
105
+ };
106
+ /**
107
+ * Removes {@link SELF_SERVICE_BLOCKED_USER_FIELDS} from a self-service body, including dotted
108
+ * paths into them (`roles.0`). Fields are dropped rather than rejected so clients that echo a
109
+ * whole user object back still succeed.
71
110
  */
72
111
  const stripPrivilegedUserFields = (body, context) => {
73
112
  const sanitized = {};
74
113
  const dropped = [];
75
114
  for (const [key, value] of Object.entries(body)) {
76
- if (exports.PRIVILEGED_USER_FIELDS.includes(key)) {
115
+ if (isWriteKeyForAnyField(key, exports.SELF_SERVICE_BLOCKED_USER_FIELDS)) {
77
116
  dropped.push(key);
78
117
  continue;
79
118
  }
@@ -85,18 +124,53 @@ const stripPrivilegedUserFields = (body, context) => {
85
124
  return sanitized;
86
125
  };
87
126
  exports.stripPrivilegedUserFields = stripPrivilegedUserFields;
127
+ // Password keys clients send to a profile update; PATCH /me rejects them rather than ignore them.
128
+ const PROFILE_PASSWORD_FIELDS = ["password", "newPassword"];
88
129
  const isEmailUpdateChangingMailbox = (currentEmail, nextEmail) => {
89
130
  if (typeof currentEmail !== "string" || typeof nextEmail !== "string") {
90
131
  return false;
91
132
  }
92
133
  return currentEmail.trim().toLowerCase() !== nextEmail.trim().toLowerCase();
93
134
  };
135
+ // The body field PATCH /me reads to confirm an email change. It is never written to the user.
136
+ const CURRENT_PASSWORD_FIELD = "currentPassword";
137
+ // passport-local-mongoose errors that mean the user has no passport password to check.
138
+ const NO_PASSPORT_PASSWORD_ERRORS = new Set(["IncorrectUsernameError", "NoSaltValueStoredError"]);
139
+ // passport-local-mongoose lockout errors (`limitAttempts`), reported to the user as they are.
140
+ const LOCKOUT_ERRORS = new Set(["AttemptTooSoonError", "TooManyAttemptsError"]);
141
+ /**
142
+ * Confirm `password` is the user's current password: first against the passport-local-mongoose
143
+ * hash (which counts a wrong attempt toward its lockout when `limitAttempts` is on), then, for a
144
+ * user with no passport password, against the Better Auth credential when Better Auth is wired.
145
+ */
146
+ const checkCurrentPassword = async (doc, password, authOptions) => {
147
+ const authenticate = doc
148
+ .authenticate;
149
+ if (typeof authenticate === "function") {
150
+ const result = (await authenticate.call(doc, password));
151
+ if (result?.user) {
152
+ return { status: "verified" };
153
+ }
154
+ const errorName = result?.error?.name ?? "";
155
+ if (!NO_PASSPORT_PASSWORD_ERRORS.has(errorName)) {
156
+ // Pass the lockout message through so the user knows why a right password fails.
157
+ const message = LOCKOUT_ERRORS.has(errorName) ? result?.error?.message : undefined;
158
+ return { message, status: "wrong" };
159
+ }
160
+ }
161
+ if (authOptions?.verifyBetterAuthPassword) {
162
+ return { status: await authOptions.verifyBetterAuthPassword(doc, password) };
163
+ }
164
+ return { status: "no-password" };
165
+ };
94
166
  const omitPrivilegedFieldsFromObject = (item, allowAdminWrite) => {
95
167
  if (!item || typeof item !== "object" || Array.isArray(item)) {
96
168
  return item;
97
169
  }
98
170
  const record = item;
99
- const fieldsToDrop = exports.PRIVILEGED_USER_FIELDS.filter((field) => field in record && !(field === "admin" && allowAdminWrite));
171
+ // Only the exact `admin` key is an authorized legacy-admin write; `admin.x` is never one.
172
+ const fieldsToDrop = Object.keys(record).filter((key) => isWriteKeyForAnyField(key, RBAC_USER_WRITE_BLOCKED_FIELDS) &&
173
+ !(key === "admin" && allowAdminWrite));
100
174
  if (fieldsToDrop.length === 0) {
101
175
  return item;
102
176
  }
@@ -110,10 +184,11 @@ const omitPrivilegedFieldsFromObject = (item, allowAdminWrite) => {
110
184
  /**
111
185
  * When RBAC is enabled, authority-bearing User fields must not flow through ordinary mongoose
112
186
  * writes on `/users`, sync, or MCP. AdminApp captures role assignments before this runs and
113
- * explicitly marks authorized legacy-admin writes after its additional checks.
187
+ * explicitly marks authorized legacy-admin writes after its additional checks. The user model is
188
+ * recognized by {@link isRbacUserModelName}.
114
189
  */
115
190
  const omitUserRolesFromWriteBody = (modelName, accessControl, body, allowAdminWrite = false) => {
116
- if (modelName !== "User" || !accessControl || body == null) {
191
+ if (!(0, userWriteGuards_1.isRbacUserModelName)(modelName, accessControl) || body == null) {
117
192
  return body;
118
193
  }
119
194
  if (Array.isArray(body)) {
@@ -304,6 +379,13 @@ const generateTokens = async (user, authOptions, options = {}) => {
304
379
  return { refreshToken, sessionId, token };
305
380
  };
306
381
  exports.generateTokens = generateTokens;
382
+ /**
383
+ * Whether an account has been disabled (`isDisabledPlugin`). Disabled users must not
384
+ * authenticate or receive new tokens on any path.
385
+ * @internal
386
+ */
387
+ const isUserDisabled = (user) => user?.disabled === true;
388
+ exports.isUserDisabled = isUserDisabled;
307
389
  const setupAuth = (app, userModel) => {
308
390
  if (!userModel.createStrategy) {
309
391
  throw new errors_1.APIError({ status: 500, title: "setupAuth userModel must have .createStrategy()" });
@@ -322,15 +404,17 @@ const setupAuth = (app, userModel) => {
322
404
  return done(error);
323
405
  }
324
406
  }));
407
+ // Only the jwt cookie or the Bearer scheme carries an access JWT. Other schemes (such as
408
+ // "Secret") skip decodeJWTMiddleware, so passport must not read a JWT out of them either.
325
409
  const customTokenExtractor = (req) => {
326
- let token = null;
327
410
  if (req?.cookies?.jwt) {
328
- token = req.cookies.jwt;
411
+ return req.cookies.jwt;
329
412
  }
330
- else if (req?.headers?.authorization) {
331
- token = req?.headers?.authorization.split(" ")[1];
413
+ const [scheme, value] = (req?.headers?.authorization ?? "").split(" ");
414
+ if (scheme?.toLowerCase() === "bearer" && value) {
415
+ return value;
332
416
  }
333
- return token;
417
+ return null;
334
418
  };
335
419
  if (process.env.TOKEN_SECRET) {
336
420
  if (process.env.NODE_ENV !== "test") {
@@ -355,6 +439,10 @@ const setupAuth = (app, userModel) => {
355
439
  return done(error, false);
356
440
  }
357
441
  if (user) {
442
+ if ((0, exports.isUserDisabled)(user)) {
443
+ logger_1.logger.warn(`[jwt] User ${user.id} is disabled`);
444
+ return done(null, false);
445
+ }
358
446
  return done(null, user);
359
447
  }
360
448
  if (userModel.createAnonymousUser) {
@@ -456,6 +544,10 @@ const addAuthRoutes = (app, userModel, authOptions) => {
456
544
  logger_1.logger.warn(`Invalid login: ${info}`);
457
545
  return res.status(401).json({ message: info?.message });
458
546
  }
547
+ if ((0, exports.isUserDisabled)(user)) {
548
+ logger_1.logger.warn(`[auth] Refusing login for disabled user ${user._id}`);
549
+ return next(new errors_1.APIError({ status: 401, title: "User is disabled" }));
550
+ }
459
551
  if (authOptions?.requireEmailVerification && user.emailVerified !== true) {
460
552
  return next(new errors_1.APIError({
461
553
  code: "email-not-verified",
@@ -501,7 +593,7 @@ const addAuthRoutes = (app, userModel, authOptions) => {
501
593
  const user = await userModel.findById(decoded.id);
502
594
  const tokenEpoch = typeof decoded.te === "number" ? decoded.te : 0;
503
595
  const userEpoch = user?.tokenEpoch ?? 0;
504
- if (!user || tokenEpoch !== userEpoch) {
596
+ if (!user || tokenEpoch !== userEpoch || (0, exports.isUserDisabled)(user)) {
505
597
  logger_1.logger.error(`Invalid refresh token, user id: ${req.user?.id}`);
506
598
  return res.status(401).json({ message: "Invalid refresh token" });
507
599
  }
@@ -565,7 +657,7 @@ const addAuthRoutes = (app, userModel, authOptions) => {
565
657
  (0, authRecovery_1.addAuthRecoveryRoutes)(app, userModel, authOptions);
566
658
  };
567
659
  exports.addAuthRoutes = addAuthRoutes;
568
- const addMeRoutes = (app, userModel, _authOptions, accessControl) => {
660
+ const addMeRoutes = (app, userModel, authOptions, accessControl) => {
569
661
  const router = express_1.default.Router();
570
662
  router.get("/me", (0, exports.authenticateMiddleware)(), async (req, res) => {
571
663
  if (!req.user?.id) {
@@ -602,9 +694,39 @@ const addMeRoutes = (app, userModel, _authOptions, accessControl) => {
602
694
  // } catch (e) {
603
695
  // return res.status(403).send({message: (e as Error).message});
604
696
  // }
697
+ const body = (req.body ?? {});
698
+ // `password` is not a schema path, so assigning it would save nothing and still answer 200.
699
+ if (PROFILE_PASSWORD_FIELDS.some((field) => field in body)) {
700
+ return res.status(400).send({
701
+ message: "PATCH /auth/me does not change passwords. Use the password reset flow or Better Auth change-password.",
702
+ });
703
+ }
704
+ const { [CURRENT_PASSWORD_FIELD]: currentPassword, ...profileBody } = body;
705
+ const previousEmail = doc.email;
605
706
  try {
606
- const update = (0, exports.stripPrivilegedUserFields)(req.body ?? {}, "PATCH /auth/me");
707
+ const update = (0, exports.stripPrivilegedUserFields)(profileBody, "PATCH /auth/me");
607
708
  const isMailboxChange = isEmailUpdateChangingMailbox(doc.email, update.email);
709
+ if (isMailboxChange) {
710
+ // A stolen session must not be able to move the recovery address, so changing the
711
+ // mailbox needs the current password.
712
+ if (typeof currentPassword !== "string" || currentPassword.length === 0) {
713
+ return res.status(403).send({
714
+ message: "Enter your current password to change your email.",
715
+ });
716
+ }
717
+ const check = await checkCurrentPassword(doc, currentPassword, authOptions);
718
+ if (check.status === "no-password") {
719
+ return res.status(400).send({
720
+ message: "Set a password on your account before changing your email. Use the password reset flow to set one.",
721
+ });
722
+ }
723
+ if (check.status === "wrong") {
724
+ logger_1.logger.warn(`[auth] Rejected email change for user ${String(doc._id)}: wrong password`);
725
+ return res.status(403).send({
726
+ message: check.message ?? "The current password is incorrect.",
727
+ });
728
+ }
729
+ }
608
730
  Object.assign(doc, update);
609
731
  if (isMailboxChange) {
610
732
  await authTokens_1.AuthToken.invalidateUnusedFor({ _id: String(doc._id) }, "passwordReset");
@@ -614,6 +736,9 @@ const addMeRoutes = (app, userModel, _authOptions, accessControl) => {
614
736
  }
615
737
  }
616
738
  await doc.save();
739
+ if (isMailboxChange && typeof previousEmail === "string" && typeof doc.email === "string") {
740
+ await (0, authRecovery_1.sendEmailChangedNotice)({ authOptions, newEmail: doc.email, previousEmail });
741
+ }
617
742
  const dataObject = doc.toObject();
618
743
  dataObject.id = doc._id;
619
744
  return res.json({ data: dataObject });
@@ -2,4 +2,35 @@ import express from "express";
2
2
  import { type User, type UserModel } from "./auth";
3
3
  import type { AuthOptions } from "./expressServer";
4
4
  export declare const sendVerificationEmail: (user: User, authOptions?: AuthOptions) => Promise<void>;
5
+ /**
6
+ * Partially mask an email for a notice: `renamed@example.com` becomes `r***@e***.com`. Keeps the
7
+ * first character of the local part and of the domain, plus the top-level domain.
8
+ */
9
+ export declare const maskEmailAddress: (email: string) => string;
10
+ /**
11
+ * Tell the previous address that the account email changed. The notice carries no link or token
12
+ * that acts on the account. Without a configured `sendMail` it logs a warning and sends nothing;
13
+ * a delivery failure is logged and never undoes the change.
14
+ */
15
+ export declare const sendEmailChangedNotice: ({ authOptions, newEmail, previousEmail, }: {
16
+ authOptions?: AuthOptions;
17
+ newEmail: string;
18
+ previousEmail: string;
19
+ }) => Promise<void>;
20
+ export interface ChangeUserPasswordOptions {
21
+ /** The admin making the change; recorded in the audit log line, never with the password. */
22
+ adminId?: unknown;
23
+ /** The Express app (`req.app`) the auth routes were added to. */
24
+ app?: express.Application;
25
+ /** Auth options to use instead of the ones registered on `app`. */
26
+ authOptions?: AuthOptions;
27
+ }
28
+ /**
29
+ * Change a user's password on the server and end the credentials issued before it: sets the
30
+ * passport password, increments `tokenEpoch` (legacy refresh tokens and MCP credentials stop
31
+ * working), saves, and, when Better Auth is registered, sets the Better Auth password and deletes
32
+ * that user's Better Auth sessions. Use it for every server-side password change; calling
33
+ * `setPasswordForUser` alone revokes nothing.
34
+ */
35
+ export declare const changeUserPassword: (user: User, password: string, options?: ChangeUserPasswordOptions) => Promise<void>;
5
36
  export declare const addAuthRecoveryRoutes: (app: express.Application, userModel: UserModel, authOptions?: AuthOptions) => void;
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.addAuthRecoveryRoutes = exports.sendVerificationEmail = void 0;
6
+ exports.addAuthRecoveryRoutes = exports.changeUserPassword = exports.sendEmailChangedNotice = exports.maskEmailAddress = exports.sendVerificationEmail = void 0;
7
7
  const express_1 = __importDefault(require("express"));
8
8
  const api_1 = require("./api");
9
9
  const auth_1 = require("./auth");
@@ -84,6 +84,7 @@ const sendVerificationEmail = async (user, authOptions) => {
84
84
  const verifyUrl = buildVerifyUrl(authOptions.publicAppUrl, issued.token);
85
85
  await deliverRecoveryMail(authOptions, {
86
86
  html: verifyEmailHtml(verifyUrl),
87
+ sensitive: true,
87
88
  subject: VERIFY_EMAIL_SUBJECT,
88
89
  text: verifyEmailText(verifyUrl),
89
90
  to: userEmail(user),
@@ -100,10 +101,90 @@ const deliverRecoveryMail = async (authOptions, message) => {
100
101
  }
101
102
  logger_1.logger.info(`[auth] Console recovery mail subject=${message.subject} textLength=${message.text.length}`);
102
103
  };
104
+ const EMAIL_CHANGED_SUBJECT = "Your account email was changed";
105
+ const maskSegment = (value) => {
106
+ if (value.length === 0) {
107
+ return "***";
108
+ }
109
+ return `${value[0]}***`;
110
+ };
111
+ /**
112
+ * Partially mask an email for a notice: `renamed@example.com` becomes `r***@e***.com`. Keeps the
113
+ * first character of the local part and of the domain, plus the top-level domain.
114
+ */
115
+ const maskEmailAddress = (email) => {
116
+ const trimmed = email.trim();
117
+ const atIndex = trimmed.lastIndexOf("@");
118
+ if (atIndex <= 0) {
119
+ return maskSegment(trimmed);
120
+ }
121
+ const local = trimmed.slice(0, atIndex);
122
+ const domain = trimmed.slice(atIndex + 1);
123
+ const dotIndex = domain.lastIndexOf(".");
124
+ if (dotIndex <= 0) {
125
+ return `${maskSegment(local)}@${maskSegment(domain)}`;
126
+ }
127
+ return `${maskSegment(local)}@${maskSegment(domain.slice(0, dotIndex))}${domain.slice(dotIndex)}`;
128
+ };
129
+ exports.maskEmailAddress = maskEmailAddress;
130
+ const emailChangedText = (maskedNewEmail) => `The email address on your account was changed to ${maskedNewEmail}. ` +
131
+ "If you did not make this change, contact support right away.";
132
+ const emailChangedHtml = (maskedNewEmail) => `<p>The email address on your account was changed to ${maskedNewEmail}.</p>` +
133
+ "<p>If you did not make this change, contact support right away.</p>";
134
+ /**
135
+ * Tell the previous address that the account email changed. The notice carries no link or token
136
+ * that acts on the account. Without a configured `sendMail` it logs a warning and sends nothing;
137
+ * a delivery failure is logged and never undoes the change.
138
+ */
139
+ const sendEmailChangedNotice = async ({ authOptions, newEmail, previousEmail, }) => {
140
+ if (!authOptions?.sendMail) {
141
+ logger_1.logger.warn("[auth] No sendMail configured; skipped the email change notice to the old address");
142
+ return;
143
+ }
144
+ const maskedNewEmail = (0, exports.maskEmailAddress)(newEmail);
145
+ try {
146
+ await authOptions.sendMail({
147
+ html: emailChangedHtml(maskedNewEmail),
148
+ sensitive: true,
149
+ subject: EMAIL_CHANGED_SUBJECT,
150
+ text: emailChangedText(maskedNewEmail),
151
+ to: previousEmail,
152
+ });
153
+ }
154
+ catch (error) {
155
+ logger_1.logger.error("[auth] Failed to send the email change notice to the old address", { error });
156
+ }
157
+ };
158
+ exports.sendEmailChangedNotice = sendEmailChangedNotice;
103
159
  const incrementTokenEpoch = (user) => {
104
160
  user.tokenEpoch = (user.tokenEpoch ?? 0) + 1;
105
161
  };
162
+ // The auth options passed to addAuthRoutes, kept on the app so changeUserPassword can reach the
163
+ // Better Auth credential sync that TerrenoApp wires after the routes are added.
164
+ const AUTH_OPTIONS_LOCAL_KEY = "terrenoAuthOptions";
165
+ const authOptionsFromApp = (app) => app?.locals?.[AUTH_OPTIONS_LOCAL_KEY];
166
+ /**
167
+ * Change a user's password on the server and end the credentials issued before it: sets the
168
+ * passport password, increments `tokenEpoch` (legacy refresh tokens and MCP credentials stop
169
+ * working), saves, and, when Better Auth is registered, sets the Better Auth password and deletes
170
+ * that user's Better Auth sessions. Use it for every server-side password change; calling
171
+ * `setPasswordForUser` alone revokes nothing.
172
+ */
173
+ const changeUserPassword = async (user, password, options = {}) => {
174
+ const audit = options.adminId === undefined ? undefined : { adminId: options.adminId };
175
+ await (0, auth_1.setPasswordForUser)(user, password, undefined, audit);
176
+ incrementTokenEpoch(user);
177
+ await user.save();
178
+ const authOptions = options.authOptions ?? authOptionsFromApp(options.app);
179
+ if (authOptions?.syncPasswordResetToBetterAuth) {
180
+ await authOptions.syncPasswordResetToBetterAuth(user, password);
181
+ }
182
+ };
183
+ exports.changeUserPassword = changeUserPassword;
106
184
  const addAuthRecoveryRoutes = (app, userModel, authOptions) => {
185
+ if (authOptions) {
186
+ app.locals[AUTH_OPTIONS_LOCAL_KEY] = authOptions;
187
+ }
107
188
  const forgotPassword = (0, api_1.asyncHandler)(async (req, res) => {
108
189
  const email = normalizeEmail(req.body?.email);
109
190
  if (email) {
@@ -118,6 +199,7 @@ const addAuthRecoveryRoutes = (app, userModel, authOptions) => {
118
199
  const resetUrl = buildResetUrl(authOptions.publicAppUrl, issued.token);
119
200
  await deliverRecoveryMail(authOptions, {
120
201
  html: resetPasswordHtml(resetUrl),
202
+ sensitive: true,
121
203
  subject: RESET_PASSWORD_SUBJECT,
122
204
  text: resetPasswordText(resetUrl),
123
205
  to: userEmail(user, email),
@@ -152,12 +234,10 @@ const addAuthRecoveryRoutes = (app, userModel, authOptions) => {
152
234
  if (!user) {
153
235
  throw new errors_1.APIError({ status: 400, title: "Invalid or expired reset token" });
154
236
  }
155
- await (0, auth_1.setPasswordForUser)(user, password);
156
- incrementTokenEpoch(user);
157
- await user.save();
158
- if (authOptions?.syncPasswordResetToBetterAuth) {
159
- await authOptions.syncPasswordResetToBetterAuth(user, password);
237
+ if ((0, auth_1.isUserDisabled)(user)) {
238
+ throw new errors_1.APIError({ status: 401, title: "User is disabled" });
160
239
  }
240
+ await (0, exports.changeUserPassword)(user, password, { authOptions });
161
241
  const tokens = await (0, auth_1.generateTokens)(user, authOptions);
162
242
  return res.json({
163
243
  data: { refreshToken: tokens.refreshToken, token: tokens.token, userId: user._id },
@@ -4,6 +4,15 @@
4
4
  * These types support optional Better Auth integration alongside the existing
5
5
  * JWT/Passport authentication system.
6
6
  */
7
+ import type { BetterAuthOptions, BetterAuthPlugin } from "better-auth";
8
+ /**
9
+ * Makes nested option objects optional too, so `options` can set one nested field (such as
10
+ * `emailAndPassword.requireEmailVerification`) without restating the fields Terreno sets.
11
+ * Functions, arrays, and strings are kept as they are.
12
+ */
13
+ export type BetterAuthOptionsOverride<T = Omit<BetterAuthOptions, "basePath" | "plugins">> = T extends (...args: never[]) => unknown ? T : T extends readonly unknown[] | string ? T : T extends object ? {
14
+ [K in keyof T]?: BetterAuthOptionsOverride<T[K]>;
15
+ } : T;
7
16
  /**
8
17
  * OAuth provider configuration for Better Auth.
9
18
  */
@@ -61,6 +70,7 @@ export interface BetterAuthConfig {
61
70
  /** Deliver auth mail. Typically `getCommsService().sendMail`. */
62
71
  sendMail?: (message: {
63
72
  html?: string;
73
+ sensitive?: boolean;
64
74
  subject: string;
65
75
  text: string;
66
76
  to: string;
@@ -95,6 +105,82 @@ export interface BetterAuthConfig {
95
105
  * `NODE_ENV=production`).
96
106
  */
97
107
  disableRateLimit?: boolean;
108
+ /**
109
+ * Any other Better Auth option, deep-merged over the options Terreno builds from this
110
+ * config (for example `emailAndPassword.requireEmailVerification`,
111
+ * `emailAndPassword.password.{hash, verify}`, or `databaseHooks`). Arrays replace Terreno's
112
+ * rather than merging by index. An explicit value wins (an `undefined` value is ignored),
113
+ * including over Terreno's security defaults: the `database` adapter, `emailAndPassword.revokeSessionsOnPasswordReset`, and
114
+ * `session.cookieCache`. Set the base path with `basePath` and plugins with `plugins`.
115
+ */
116
+ options?: BetterAuthOptionsOverride;
117
+ /**
118
+ * Better Auth plugins, appended after Terreno's `bearer()` plugin. Their endpoints mount
119
+ * under `basePath`. They are not added to the `auth.api` type.
120
+ */
121
+ plugins?: BetterAuthPlugin[];
122
+ /**
123
+ * Hands a one-time token to web apps that sign in with a social or generic OAuth provider
124
+ * from another site, so they can use the bearer scheme without cookies. Unset by default.
125
+ *
126
+ * Start the sign-in with a top-level navigation to
127
+ * `GET {basePath}/oauth-handoff/start?provider=<id>&callbackURL=<url>` (optional
128
+ * `errorCallbackURL`), not with `POST /sign-in/social` from fetch. The start endpoint sets the
129
+ * OAuth state cookie first-party on the API's origin and redirects to the provider, so the
130
+ * cookie comes back on the callback even when the browser blocks third-party cookies. It works
131
+ * for social and generic OAuth providers. It answers 400, with no redirect, unless
132
+ * `callbackURL` (and `errorCallbackURL`, when given) is an absolute URL on one of `webOrigins`
133
+ * that `trustedOrigins` also allows, and unless the request is a page navigation. The URL's
134
+ * query is kept as it is. When the provider is unknown or cannot start, it redirects to
135
+ * `errorCallbackURL` (or `callbackURL`) with `error=provider_not_found` or
136
+ * `error=sign_in_failed`. It does not take `scopes`, `loginHint`, `requestSignUp`, or
137
+ * `newUserCallbackURL`, so a provider with `disableImplicitSignUp` cannot sign up new users
138
+ * through it. Better Auth's limiter allows three starts per ten seconds per IP.
139
+ *
140
+ * When set, Terreno adds Better Auth's `oneTimeToken` plugin (three-minute, single-use tokens,
141
+ * stored hashed, which clients cannot mint) and an after-hook on `/callback/:id`. When that
142
+ * callback creates a session and redirects to a listed path on one of `webOrigins`, the
143
+ * redirect `Location` gets `ott=<token>` in its URL fragment. The web app exchanges it once
144
+ * with `POST {basePath}/one-time-token/verify`, which answers with the session and the
145
+ * `set-auth-token` header.
146
+ *
147
+ * No other redirect gets a token: paths outside `callbackPaths`, app schemes (`exp://`,
148
+ * `terreno://`), relative paths, the API's own origin, and origins that only `trustedOrigins`
149
+ * allows (including wildcard patterns) are left as they are. The start endpoint refuses a
150
+ * `callbackURL` outside `callbackPaths` too; `errorCallbackURL` may be any path on a web
151
+ * origin, since an error redirect never carries a token. Each web origin must also be in
152
+ * `trustedOrigins`, or both the start endpoint and `POST /sign-in/social` refuse it as a
153
+ * `callbackURL`.
154
+ *
155
+ * The handoff is for bearer clients only. A handed-off callback redirect carries no session
156
+ * cookie for the API's origin, and verify drops every Set-Cookie it would send (the session
157
+ * cookies and any a plugin adds there), so a cookie-mode app gets no session from it.
158
+ */
159
+ oauthHandoff?: BetterAuthOAuthHandoffConfig;
160
+ }
161
+ /**
162
+ * Where the OAuth one-time-token handoff may send a token.
163
+ */
164
+ export interface BetterAuthOAuthHandoffConfig {
165
+ /**
166
+ * Exact `http:` or `https:` origins of the web apps, such as `"https://app.example.com"`.
167
+ * Scheme, host and port must match the redirect exactly. Patterns, paths, and other schemes
168
+ * are rejected when Better Auth is created, and so is an empty list.
169
+ */
170
+ webOrigins: string[];
171
+ /**
172
+ * Exact paths on those origins that may receive the token, such as `"/auth/return"`.
173
+ * Defaults to `["/"]`. The redirect must already be written the way the URL parser prints
174
+ * it (lower-case host, no default port, credentials, backslashes, or dot segments), and its
175
+ * path must equal one of these exactly (case, trailing slashes and encoded characters all
176
+ * count). Its query is free, so `?handoff=<nonce>` still works. Each entry must start with one `/` and be in normal form:
177
+ * no `.` or `..` segments, encoded slashes or backslashes, spaces, query, or fragment.
178
+ *
179
+ * Keep the list to the page that reads the token. That page must strip the fragment before
180
+ * anything else runs and must never redirect, on the server or in the browser, because a
181
+ * browser carries the fragment through a redirect that has none of its own.
182
+ */
183
+ callbackPaths?: string[];
98
184
  }
99
185
  /**
100
186
  * Auth provider selection for TerrenoApp.
@@ -9,6 +9,23 @@ import type { UserModel } from "./auth";
9
9
  import type { BetterAuthConfig } from "./betterAuth";
10
10
  import { type BetterAuthInstance } from "./betterAuthSetup";
11
11
  import type { TerrenoPlugin } from "./terrenoPlugin";
12
+ /**
13
+ * The capability a registered plugin offers when it owns the app's Better Auth instance, as
14
+ * BetterAuthApp does. TerrenoApp mounts its session middleware and RealtimeApp validates socket
15
+ * sessions with it, so both find the provider the same way: {@link findBetterAuthProvider}.
16
+ */
17
+ export interface BetterAuthProvider {
18
+ getAuth: () => BetterAuthInstance | undefined;
19
+ ensureAuth?: () => BetterAuthInstance;
20
+ markSessionMiddlewareMounted?: () => void;
21
+ getBetterAuthBasePath?: () => string;
22
+ }
23
+ /** Whether a registered plugin provides the app's Better Auth instance. */
24
+ export declare const isBetterAuthProvider: (plugin: unknown) => plugin is BetterAuthProvider;
25
+ /** The first registered plugin that provides the app's Better Auth instance, if any. */
26
+ export declare const findBetterAuthProvider: (registrations: readonly unknown[]) => BetterAuthProvider | undefined;
27
+ /** The provider's Better Auth instance, creating it when the provider supports that. */
28
+ export declare const getProvidedBetterAuth: (provider: BetterAuthProvider | undefined) => BetterAuthInstance | undefined;
12
29
  export interface BetterAuthAppOptions {
13
30
  config: BetterAuthConfig;
14
31
  userModel?: UserModel;
@@ -6,9 +6,20 @@
6
6
  * and user sync on an existing Express application.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.BetterAuthApp = void 0;
9
+ exports.BetterAuthApp = exports.getProvidedBetterAuth = exports.findBetterAuthProvider = exports.isBetterAuthProvider = void 0;
10
10
  const betterAuthSetup_1 = require("./betterAuthSetup");
11
11
  const logger_1 = require("./logger");
12
+ /** Whether a registered plugin provides the app's Better Auth instance. */
13
+ const isBetterAuthProvider = (plugin) => typeof plugin === "object" &&
14
+ plugin !== null &&
15
+ typeof plugin.getAuth === "function";
16
+ exports.isBetterAuthProvider = isBetterAuthProvider;
17
+ /** The first registered plugin that provides the app's Better Auth instance, if any. */
18
+ const findBetterAuthProvider = (registrations) => registrations.find(exports.isBetterAuthProvider);
19
+ exports.findBetterAuthProvider = findBetterAuthProvider;
20
+ /** The provider's Better Auth instance, creating it when the provider supports that. */
21
+ const getProvidedBetterAuth = (provider) => provider?.ensureAuth?.() ?? provider?.getAuth();
22
+ exports.getProvidedBetterAuth = getProvidedBetterAuth;
12
23
  class BetterAuthApp {
13
24
  auth;
14
25
  options;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * OAuth one-time-token handoff for cross-site web apps that use Better Auth's bearer scheme.
3
+ *
4
+ * A social sign-in ends with a top-level redirect from the API to the web app, so the web app
5
+ * never sees the `set-auth-token` header. When the OAuth callback creates a session and
6
+ * redirects to a configured web origin, this adds a single-use, short-lived token to the
7
+ * redirect's URL fragment, which the web app exchanges for the bearer at
8
+ * `POST {basePath}/one-time-token/verify`. Fragments are not sent to servers or in `Referer`.
9
+ */
10
+ import type { BetterAuthPlugin } from "better-auth";
11
+ import type { BetterAuthOAuthHandoffConfig } from "./betterAuth";
12
+ export interface CreateOAuthHandoffPluginsOptions {
13
+ /** The API's own origin (from `baseURL`); it never receives a token. */
14
+ apiOrigin: string;
15
+ config: BetterAuthOAuthHandoffConfig;
16
+ /** Returns the Better Auth instance, which exists only after these plugins are built. */
17
+ getAuth: () => unknown;
18
+ }
19
+ /**
20
+ * Builds the plugins `createBetterAuth` adds for `oauthHandoff`: Better Auth's `oneTimeToken`
21
+ * (server-minted only, hashed at rest, no `set-ott` header) and the callback after-hook that
22
+ * puts a token in the redirect fragment for configured web origins.
23
+ */
24
+ export declare const createOAuthHandoffPlugins: ({ apiOrigin, config, getAuth, }: CreateOAuthHandoffPluginsOptions) => BetterAuthPlugin[];