@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
@@ -9,13 +9,16 @@ 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.syncBetterAuthUser = exports.createBetterAuthSessionMiddleware = exports.applyBetterAuthPasswordResetToJwt = exports.readPasswordFromBetterAuthResetRequest = exports.applyJwtPasswordResetToBetterAuth = exports.createBetterAuth = exports.createBetterAuthEmailHooks = void 0;
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;
13
13
  const better_auth_1 = require("better-auth");
14
14
  const mongodb_1 = require("better-auth/adapters/mongodb");
15
+ const api_1 = require("better-auth/api");
15
16
  const node_1 = require("better-auth/node");
16
17
  const plugins_1 = require("better-auth/plugins");
18
+ const mergeWith_1 = __importDefault(require("lodash/mergeWith"));
17
19
  const mongoose_1 = __importDefault(require("mongoose"));
18
20
  const auth_1 = require("./auth");
21
+ const betterAuthOAuthHandoff_1 = require("./betterAuthOAuthHandoff");
19
22
  const errors_1 = require("./errors");
20
23
  const logger_1 = require("./logger");
21
24
  const plugins_2 = require("./plugins");
@@ -69,6 +72,7 @@ const createBetterAuthEmailHooks = (config) => {
69
72
  });
70
73
  const message = {
71
74
  html: rendered.html,
75
+ sensitive: true,
72
76
  subject: rendered.subject,
73
77
  text: rendered.text ?? "",
74
78
  to: user.email,
@@ -85,6 +89,24 @@ const createBetterAuthEmailHooks = (config) => {
85
89
  };
86
90
  };
87
91
  exports.createBetterAuthEmailHooks = createBetterAuthEmailHooks;
92
+ // The API's own origin, which the OAuth handoff never sends a token to.
93
+ const apiOriginOf = (url) => {
94
+ let origin;
95
+ try {
96
+ origin = new URL(url).origin;
97
+ }
98
+ catch {
99
+ origin = "null";
100
+ }
101
+ if (origin === "null") {
102
+ throw new errors_1.APIError({
103
+ detail: `"${url}" is not an absolute http(s) URL`,
104
+ status: 500,
105
+ title: "BETTER_AUTH_URL must be an absolute URL",
106
+ });
107
+ }
108
+ return origin;
109
+ };
88
110
  /**
89
111
  * Creates a Better Auth instance with MongoDB adapter.
90
112
  */
@@ -126,7 +148,7 @@ const createBetterAuth = (options) => {
126
148
  }
127
149
  const emailHooks = (0, exports.createBetterAuthEmailHooks)(config);
128
150
  const userModel = options.userModel;
129
- const auth = (0, better_auth_1.betterAuth)({
151
+ const defaults = {
130
152
  advanced: config.crossDomainCookies
131
153
  ? {
132
154
  defaultCookieAttributes: {
@@ -159,12 +181,6 @@ const createBetterAuth = (options) => {
159
181
  },
160
182
  }
161
183
  : {}),
162
- // The bearer plugin lets clients authenticate with `Authorization: Bearer <sessionToken>`
163
- // instead of the signed session cookie. Required for cross-origin/native clients and for
164
- // websocket handshakes (RealtimeApp's Better Auth socket validator forwards the handshake
165
- // token as a bearer header) — without it, a raw session token cannot be validated and
166
- // socket auth silently fails (the sync client shows perpetually "offline").
167
- plugins: [(0, plugins_1.bearer)()],
168
184
  rateLimit: config.disableRateLimit ? { enabled: false } : undefined,
169
185
  secret,
170
186
  session: {
@@ -175,10 +191,35 @@ const createBetterAuth = (options) => {
175
191
  },
176
192
  socialProviders: Object.keys(socialProviders).length > 0 ? socialProviders : undefined,
177
193
  trustedOrigins: config.trustedOrigins ?? [],
194
+ };
195
+ // Arrays from `options` replace Terreno's; lodash would otherwise merge them by index.
196
+ const replaceArrays = (_target, source) => Array.isArray(source) ? source : undefined;
197
+ const merged = (0, mergeWith_1.default)({}, defaults, config.options, replaceArrays);
198
+ // The handoff hook mints tokens through `auth.api`, which exists only once betterAuth() returns.
199
+ let auth;
200
+ const handoffPlugins = config.oauthHandoff
201
+ ? (0, betterAuthOAuthHandoff_1.createOAuthHandoffPlugins)({
202
+ apiOrigin: apiOriginOf(typeof merged.baseURL === "string" ? merged.baseURL : baseURL),
203
+ config: config.oauthHandoff,
204
+ getAuth: () => auth,
205
+ })
206
+ : [];
207
+ const credentialSyncPlugins = userModel ? [createCredentialSyncPlugin(userModel)] : [];
208
+ const created = (0, better_auth_1.betterAuth)({
209
+ ...merged,
210
+ // The bearer plugin lets clients authenticate with `Authorization: Bearer <sessionToken>`
211
+ // instead of the signed session cookie. Required for cross-origin/native clients and for
212
+ // websocket handshakes (RealtimeApp's Better Auth socket validator forwards the handshake
213
+ // token as a bearer header) — without it, a raw session token cannot be validated and
214
+ // socket auth silently fails (the sync client shows perpetually "offline").
215
+ // The handoff plugins come last so their callback hook sees the final redirect.
216
+ // The credential sync plugin keeps the legacy passport credential in step with Better Auth.
217
+ plugins: [(0, plugins_1.bearer)(), ...credentialSyncPlugins, ...(config.plugins ?? []), ...handoffPlugins],
178
218
  });
179
219
  // Cast through unknown: enabling the bearer plugin narrows betterAuth()'s inferred
180
220
  // return type to a plugin-specific tuple that no longer matches the plugin-agnostic
181
221
  // BetterAuthInstance alias, though the runtime instance is a valid better-auth instance.
222
+ auth = created;
182
223
  return auth;
183
224
  };
184
225
  exports.createBetterAuth = createBetterAuth;
@@ -220,6 +261,92 @@ const applyJwtPasswordResetToBetterAuth = async (auth, user, password) => {
220
261
  await ctx.internalAdapter.deleteUserSessions(betterAuthUserId);
221
262
  };
222
263
  exports.applyJwtPasswordResetToBetterAuth = applyJwtPasswordResetToBetterAuth;
264
+ /**
265
+ * Check `password` against the Better Auth credential account linked to an app user through
266
+ * `betterAuthId`. Returns "no-password" when the user has no linked Better Auth user or that user
267
+ * has no credential password (for example a social-only account).
268
+ */
269
+ const verifyBetterAuthCredentialPassword = async (auth, user, password) => {
270
+ const betterAuthUserId = typeof user.betterAuthId === "string" ? user.betterAuthId : "";
271
+ if (!betterAuthUserId) {
272
+ return "no-password";
273
+ }
274
+ const ctx = (await auth.$context);
275
+ const accounts = await ctx.internalAdapter.findAccounts(betterAuthUserId);
276
+ const credential = accounts.find((account) => account.providerId === "credential" && typeof account.password === "string");
277
+ if (!credential?.password) {
278
+ return "no-password";
279
+ }
280
+ const isMatch = await ctx.password.verify({ hash: credential.password, password });
281
+ return isMatch ? "verified" : "wrong";
282
+ };
283
+ exports.verifyBetterAuthCredentialPassword = verifyBetterAuthCredentialPassword;
284
+ // Better Auth endpoints that change or revoke a user's credentials; the legacy JWT credential
285
+ // must follow them.
286
+ const CREDENTIAL_CHANGE_PATHS = new Set([
287
+ "/change-password",
288
+ "/revoke-sessions",
289
+ "/revoke-other-sessions",
290
+ ]);
291
+ // The new password of an in-flight Better Auth `/reset-password`, keyed by its request. The
292
+ // endpoint reads its JSON body before `onPasswordReset` runs, so the hook cannot read it again.
293
+ const resetPasswordsByRequest = new WeakMap();
294
+ /**
295
+ * After a Better Auth password change, set the legacy passport password of a dual-enrolled app
296
+ * user to the new one; after a password change or session revocation, bump `tokenEpoch` so
297
+ * legacy refresh tokens issued before it stop working.
298
+ */
299
+ const applyBetterAuthCredentialChangeToJwt = async (userModel, ctx) => {
300
+ if (ctx.context.returned instanceof Error) {
301
+ return;
302
+ }
303
+ const betterAuthId = ctx.context.session?.user?.id;
304
+ if (!betterAuthId) {
305
+ return;
306
+ }
307
+ const appUser = await (0, plugins_2.findOneOrNoneFor)(userModel, { betterAuthId });
308
+ if (!appUser) {
309
+ return;
310
+ }
311
+ const newPassword = ctx.body?.newPassword;
312
+ if (ctx.path === "/change-password" && typeof newPassword === "string") {
313
+ // Only an account that already has a legacy password gets the new one, so a Better Auth only
314
+ // account does not gain a second way to sign in.
315
+ const hasLegacyPassword = userModel.schema.path("hash") !== undefined &&
316
+ Boolean(await userModel.exists({ _id: appUser._id, hash: { $exists: true, $ne: null } }));
317
+ if (hasLegacyPassword) {
318
+ await (0, auth_1.setPasswordForUser)(appUser, newPassword);
319
+ }
320
+ }
321
+ if (userModel.schema.path("tokenEpoch") !== undefined) {
322
+ appUser.tokenEpoch = (appUser.tokenEpoch ?? 0) + 1;
323
+ }
324
+ await appUser.save();
325
+ };
326
+ const createCredentialSyncPlugin = (userModel) => ({
327
+ hooks: {
328
+ after: [
329
+ {
330
+ handler: (0, api_1.createAuthMiddleware)(async (ctx) => {
331
+ await applyBetterAuthCredentialChangeToJwt(userModel, ctx);
332
+ }),
333
+ matcher: (ctx) => CREDENTIAL_CHANGE_PATHS.has(ctx.path ?? ""),
334
+ },
335
+ ],
336
+ before: [
337
+ {
338
+ handler: (0, api_1.createAuthMiddleware)(async (ctx) => {
339
+ const newPassword = ctx.body?.newPassword;
340
+ if (ctx.request && typeof newPassword === "string") {
341
+ resetPasswordsByRequest.set(ctx.request, newPassword);
342
+ }
343
+ }),
344
+ matcher: (ctx) => ctx.path === "/reset-password",
345
+ },
346
+ ],
347
+ },
348
+ id: "terreno-credential-sync",
349
+ });
223
350
  const passwordFromUnknown = (value) => {
224
351
  if (!value || typeof value !== "object") {
225
352
  return "";
@@ -235,6 +362,10 @@ const readPasswordFromBetterAuthResetRequest = async (request) => {
235
362
  if (!request) {
236
363
  return "";
237
364
  }
365
+ const stashed = resetPasswordsByRequest.get(request);
366
+ if (stashed) {
367
+ return stashed;
368
+ }
238
369
  const attached = passwordFromUnknown(request.body);
239
370
  if (attached.length > 0) {
240
371
  return attached;
@@ -278,6 +409,66 @@ const applyBetterAuthPasswordResetToJwt = async (userModel, betterAuthUser, requ
278
409
  await appUser.save();
279
410
  };
280
411
  exports.applyBetterAuthPasswordResetToJwt = applyBetterAuthPasswordResetToJwt;
412
+ const UNSAFE_METHODS = new Set(["DELETE", "PATCH", "POST", "PUT"]);
413
+ const headerValue = (value) => Array.isArray(value) ? value[0] : value;
414
+ const originOfReferer = (referer) => {
415
+ if (!referer) {
416
+ return undefined;
417
+ }
418
+ try {
419
+ return new URL(referer).origin;
420
+ }
421
+ catch {
422
+ return "null";
423
+ }
424
+ };
425
+ // True when the request's own `Authorization: Bearer` token is the session Better Auth resolved,
426
+ // rather than a cookie sent beside some other header. The bearer plugin accepts the raw token or
427
+ // the signed `token.signature` form.
428
+ const isBearerSession = (req, sessionToken) => {
429
+ const match = /^Bearer\s+(.+)$/i.exec(headerValue(req.headers.authorization) ?? "");
430
+ if (!match || !sessionToken) {
431
+ return false;
432
+ }
433
+ let bearer = match[1].trim();
434
+ try {
435
+ bearer = decodeURIComponent(bearer);
436
+ }
437
+ catch {
438
+ return false;
439
+ }
440
+ return bearer === sessionToken || bearer.startsWith(`${sessionToken}.`);
441
+ };
442
+ /**
443
+ * A session cookie rides along on requests other sites start, so a cookie-authenticated write is
444
+ * accepted only from an origin in Better Auth's `trustedOrigins` (which includes the API's own
445
+ * origin), the same rule Better Auth applies to its own routes. Bearer requests cannot be forged
446
+ * by another site. A request with no Origin, Referer, or cross-site Fetch Metadata did not come
447
+ * from a browser page, so it is not a cross-site forgery.
448
+ */
449
+ const isUntrustedCookieWrite = async (auth, req, sessionToken) => {
450
+ if (!UNSAFE_METHODS.has(req.method) || !req.headers.cookie) {
451
+ return false;
452
+ }
453
+ if (isBearerSession(req, sessionToken)) {
454
+ return false;
455
+ }
456
+ const context = (await auth.$context);
457
+ const advanced = context.options.advanced;
458
+ const isCsrfCheckDisabled = advanced?.disableCSRFCheck === true ||
459
+ (advanced?.disableOriginCheck === true && advanced.disableCSRFCheck === undefined);
460
+ if (isCsrfCheckDisabled) {
461
+ return false;
462
+ }
463
+ const origin = headerValue(req.headers.origin) ?? originOfReferer(headerValue(req.headers.referer));
464
+ if (!origin) {
465
+ return headerValue(req.headers["sec-fetch-site"]) === "cross-site";
466
+ }
467
+ if (origin === "null") {
468
+ return true;
469
+ }
470
+ return !context.isTrustedOrigin(origin, { allowRelativePaths: false });
471
+ };
281
472
  /**
282
473
  * Creates Express middleware that extracts the Better Auth session
283
474
  * and populates req.user with the application User model.
@@ -288,23 +479,26 @@ const createBetterAuthSessionMiddleware = (auth, userModel) => {
288
479
  const session = await auth.api.getSession({
289
480
  headers: req.headers,
290
481
  });
291
- if (session?.user && session?.session) {
482
+ if (session?.user &&
483
+ session?.session &&
484
+ (await isUntrustedCookieWrite(auth, req, String(session.session.token ?? "")))) {
485
+ // Fall through as anonymous, like a disabled user, so protected routes answer 401.
486
+ logger_1.logger.warn(`[better-auth] Ignored a session cookie on ${req.method} ${req.path} from an untrusted origin`);
487
+ }
488
+ else if (session?.user && session?.session) {
292
489
  const betterAuthUser = session.user;
293
490
  const reqWithSession = req;
294
491
  if (userModel) {
295
- // Look up the application user by betterAuthId
296
- const appUser = await (0, plugins_2.findOneOrNoneFor)(userModel, {
297
- betterAuthId: betterAuthUser.id,
298
- });
299
- if (appUser) {
300
- reqWithSession.user = appUser;
301
- reqWithSession.betterAuthSession = session;
302
- (0, requestContext_1.updateRequestContextFromRequest)(req);
492
+ const { isDisabled, user } = await (0, exports.resolveBetterAuthAppUser)({ betterAuthUser, userModel });
493
+ if (isDisabled) {
494
+ // A disabled account's live sessions stop authenticating. Falling through as
495
+ // anonymous, rather than answering 401 here, keeps Better Auth's own routes
496
+ // (sign-out, signing in as someone else) reachable, since TerrenoApp mounts this
497
+ // middleware before them.
498
+ logger_1.logger.debug(`[better-auth] User ${user.id} is disabled, ignoring their session`);
303
499
  }
304
500
  else {
305
- // User exists in Better Auth but not synced yet - create them
306
- const newUser = await (0, exports.syncBetterAuthUser)(userModel, betterAuthUser);
307
- reqWithSession.user = newUser;
501
+ reqWithSession.user = user;
308
502
  reqWithSession.betterAuthSession = session;
309
503
  (0, requestContext_1.updateRequestContextFromRequest)(req);
310
504
  }
@@ -332,7 +526,45 @@ const createBetterAuthSessionMiddleware = (auth, userModel) => {
332
526
  };
333
527
  };
334
528
  exports.createBetterAuthSessionMiddleware = createBetterAuthSessionMiddleware;
335
- const syncBetterAuthUser = async (userModel, betterAuthUser, oauthProvider) => {
529
+ /**
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.
532
+ */
533
+ const assertEmailLinkAllowed = (userByEmail, betterAuthUser) => {
534
+ if (betterAuthUser.emailVerified === true && !userByEmail.betterAuthId) {
535
+ return;
536
+ }
537
+ throw new errors_1.APIError({
538
+ detail: "Verify the email address before signing in to the existing account.",
539
+ disableExternalErrorTracking: true,
540
+ status: 409,
541
+ title: "An account with this email already exists",
542
+ });
543
+ };
544
+ /**
545
+ * A legacy password on a row whose email was never verified may have been set by someone who
546
+ * does not own the mailbox. Once the verified owner links the row, that password and the
547
+ * refresh tokens issued from it stop working.
548
+ */
549
+ const revokeUnprovenLegacyPassword = async (userModel, userByEmail) => {
550
+ if (userByEmail.emailVerified === true || userModel.schema.path("hash") === undefined) {
551
+ return;
552
+ }
553
+ const hasLegacyPassword = await userModel.exists({
554
+ _id: userByEmail._id,
555
+ hash: { $exists: true, $ne: null },
556
+ });
557
+ if (!hasLegacyPassword) {
558
+ return;
559
+ }
560
+ const bumpEpoch = userModel.schema.path("tokenEpoch") !== undefined;
561
+ await userModel.updateOne({ _id: userByEmail._id }, {
562
+ $unset: { hash: 1, salt: 1 },
563
+ ...(bumpEpoch ? { $inc: { tokenEpoch: 1 } } : {}),
564
+ });
565
+ logger_1.logger.info(`Revoked an unverified legacy password while linking Better Auth user ${userByEmail.id}`);
566
+ };
567
+ const syncBetterAuthUser = async (userModel, betterAuthUser, oauthProvider, options = {}) => {
336
568
  try {
337
569
  const existingUser = (await (0, plugins_2.findOneOrNoneFor)(userModel, {
338
570
  betterAuthId: betterAuthUser.id,
@@ -350,7 +582,15 @@ const syncBetterAuthUser = async (userModel, betterAuthUser, oauthProvider) => {
350
582
  const userByEmail = (await (0, plugins_2.findOneOrNoneFor)(userModel, {
351
583
  email: betterAuthUser.email,
352
584
  }));
585
+ if (userByEmail?.betterAuthId === betterAuthUser.id) {
586
+ // A concurrent first contact created this row between the two lookups.
587
+ return userByEmail;
588
+ }
353
589
  if (userByEmail) {
590
+ if (!options.trustEmail) {
591
+ assertEmailLinkAllowed(userByEmail, betterAuthUser);
592
+ await revokeUnprovenLegacyPassword(userModel, userByEmail);
593
+ }
354
594
  // Link existing user to Better Auth
355
595
  userByEmail.betterAuthId = betterAuthUser.id;
356
596
  if (oauthProvider) {
@@ -375,11 +615,49 @@ const syncBetterAuthUser = async (userModel, betterAuthUser, oauthProvider) => {
375
615
  return newUser;
376
616
  }
377
617
  catch (error) {
378
- logger_1.logger.error(`Error syncing Better Auth user: ${error}`);
618
+ // 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.
620
+ if (error.code === 11000) {
621
+ logger_1.logger.debug(`Better Auth user was created concurrently: ${error}`);
622
+ }
623
+ else if ((0, errors_1.isAPIError)(error) && error.status === 409) {
624
+ logger_1.logger.warn(`Refused to link Better Auth user ${betterAuthUser.id} by email: ${error.title}`);
625
+ }
626
+ else {
627
+ logger_1.logger.error(`Error syncing Better Auth user: ${error}`);
628
+ }
379
629
  throw error;
380
630
  }
381
631
  };
382
632
  exports.syncBetterAuthUser = syncBetterAuthUser;
633
+ /**
634
+ * Finds the application user for a Better Auth session user, creating it on first contact,
635
+ * and reports whether the account is disabled. Every Better Auth entry point (REST session
636
+ * middleware, socket handshake) goes through this so they accept and refuse the same users.
637
+ */
638
+ const resolveBetterAuthAppUser = async ({ userModel, betterAuthUser, }) => {
639
+ const findByBetterAuthId = async () => (await (0, plugins_2.findOneOrNoneFor)(userModel, {
640
+ betterAuthId: betterAuthUser.id,
641
+ }));
642
+ let user = await findByBetterAuthId();
643
+ if (!user) {
644
+ try {
645
+ user = (await (0, exports.syncBetterAuthUser)(userModel, betterAuthUser));
646
+ }
647
+ catch (error) {
648
+ // Right after sign-up the socket handshake and the first REST calls race to create the
649
+ // same user; the loser's insert hits the unique `_id` (or `betterAuthId`) index.
650
+ const isDuplicateKey = error.code === 11000;
651
+ const createdConcurrently = isDuplicateKey ? await findByBetterAuthId() : null;
652
+ if (!createdConcurrently) {
653
+ throw error;
654
+ }
655
+ user = createdConcurrently;
656
+ }
657
+ }
658
+ return { isDisabled: Boolean(user.disabled), user };
659
+ };
660
+ exports.resolveBetterAuthAppUser = resolveBetterAuthAppUser;
383
661
  /**
384
662
  * Mounts Better Auth routes on the Express app.
385
663
  */
@@ -393,7 +671,7 @@ const mountBetterAuthRoutes = (app, auth, basePath = "/api/auth") => {
393
671
  };
394
672
  exports.mountBetterAuthRoutes = mountBetterAuthRoutes;
395
673
  /**
396
- * Gets the MongoDB client from the mongoose connection.
674
+ * Gets a MongoDB client view whose db() is the mongoose connection's database (its dbName).
397
675
  */
398
676
  const getMongoClientFromMongoose = () => {
399
677
  const connection = mongoose_1.default.connection;
@@ -404,7 +682,9 @@ const getMongoClientFromMongoose = () => {
404
682
  title: "Mongoose is not connected. Ensure MongoDB connection is established first.",
405
683
  });
406
684
  }
407
- return client;
685
+ // Use the connection's database (mongoose's dbName option), not the URI default, so Better
686
+ // Auth's collections live beside the app's models.
687
+ return { db: () => client.db(connection.name || undefined) };
408
688
  };
409
689
  exports.getMongoClientFromMongoose = getMongoClientFromMongoose;
410
690
  /**
@@ -33,6 +33,11 @@ export declare const createRouter: (rootPath: string, addRoutes: AddRoutes, midd
33
33
  export declare const createRouterWithAuth: (rootPath: string, addRoutes: (router: Router) => void, middleware?: express.RequestHandler[]) => Array<string | express.RequestHandler | Router>;
34
34
  export interface AuthRecoveryMail {
35
35
  html?: string;
36
+ /**
37
+ * True on Terreno's recovery mail: it carries a one-time secret link. Mail transports should
38
+ * not store its content; `@terreno/comms` keeps no payload for it in the message log.
39
+ */
40
+ sensitive?: boolean;
36
41
  subject: string;
37
42
  text: string;
38
43
  to: string;
@@ -66,7 +71,18 @@ export interface AuthOptions {
66
71
  * BetterAuthApp is registered.
67
72
  */
68
73
  syncPasswordResetToBetterAuth?: (user: User, password: string) => Promise<void>;
74
+ /**
75
+ * Check a password against the user's Better Auth credential account. `PATCH /auth/me` uses it
76
+ * to confirm an email change for a user with no passport password. TerrenoApp wires this when
77
+ * BetterAuthApp is registered.
78
+ */
79
+ verifyBetterAuthPassword?: (user: User, password: string) => Promise<BetterAuthPasswordCheck>;
69
80
  }
81
+ /**
82
+ * Result of {@link AuthOptions.verifyBetterAuthPassword}: the password matched, did not match, or
83
+ * the user has no Better Auth credential password to check.
84
+ */
85
+ export type BetterAuthPasswordCheck = "verified" | "wrong" | "no-password";
70
86
  export declare const cronjob: (name: string, schedule: "hourly" | "minutely" | string, callback: () => void) => void;
71
87
  export interface WrapScriptOptions {
72
88
  onFinish?: (result?: unknown) => void | Promise<void>;
@@ -40,7 +40,6 @@ exports.wrapScript = exports.cronjob = exports.createRouterWithAuth = exports.cr
40
40
  const Sentry = __importStar(require("@sentry/bun"));
41
41
  const cron_1 = __importDefault(require("cron"));
42
42
  const express_1 = __importDefault(require("express"));
43
- const cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
44
43
  const on_finished_1 = __importDefault(require("on-finished"));
45
44
  const passport_1 = __importDefault(require("passport"));
46
45
  const errors_1 = require("./errors");
@@ -49,23 +48,71 @@ const slackNotifier_1 = require("./notifiers/slackNotifier");
49
48
  const SLOW_READ_MAX = 200;
50
49
  const SLOW_WRITE_MAX = 500;
51
50
  const IS_JEST = process.env.JEST_WORKER_ID !== undefined;
52
- const SENSITIVE_REQUEST_BODY_KEYS = [
53
- "newPassword",
54
- "oldPassword",
51
+ const REDACTED = "<REDACTED>";
52
+ // Stop at a depth no real request body reaches, so a self-referencing body cannot loop.
53
+ const MAX_REDACTION_DEPTH = 32;
54
+ // Matched anywhere in a key after lowercasing and removing separators, e.g. currentPassword,
55
+ // refresh_token, client_secret, code_verifier, x-api-key.
56
+ const SENSITIVE_KEY_FRAGMENTS = [
57
+ "apikey",
58
+ "authorization",
59
+ "credential",
60
+ "passcode",
61
+ "passphrase",
62
+ "passwd",
55
63
  "password",
56
- "refreshToken",
64
+ "privatekey",
65
+ "secret",
66
+ "signature",
57
67
  "token",
68
+ "verifier",
58
69
  ];
59
- const redactSensitiveRequestBody = (body) => {
60
- const bodyCopy = (0, cloneDeep_1.default)(body);
61
- for (const key of SENSITIVE_REQUEST_BODY_KEYS) {
62
- if (key in bodyCopy && bodyCopy[key] !== undefined) {
63
- bodyCopy[key] = "<REDACTED>";
70
+ // Matched as whole words of a key, so `code` covers OAuth and verification codes without
71
+ // matching unrelated words that merely contain the letters.
72
+ const SENSITIVE_KEY_WORDS = new Set(["code", "otp", "pin"]);
73
+ const keyWords = (key) => {
74
+ return key
75
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
76
+ .toLowerCase()
77
+ .split(/[^a-z0-9]+/)
78
+ .filter(Boolean);
79
+ };
80
+ /** Whether a request body or query key names credential material that must not be logged. */
81
+ const isSensitiveRequestKey = (key) => {
82
+ const normalized = key.toLowerCase().replace(/[^a-z0-9]/g, "");
83
+ if (SENSITIVE_KEY_FRAGMENTS.some((fragment) => normalized.includes(fragment))) {
84
+ return true;
85
+ }
86
+ return keyWords(key).some((word) => SENSITIVE_KEY_WORDS.has(word));
87
+ };
88
+ const redactSensitiveValue = (value, depth) => {
89
+ if (value === null || typeof value !== "object") {
90
+ return value;
91
+ }
92
+ if (depth >= MAX_REDACTION_DEPTH) {
93
+ return REDACTED;
94
+ }
95
+ if (Array.isArray(value)) {
96
+ return value.map((item) => redactSensitiveValue(item, depth + 1));
97
+ }
98
+ const prototype = Object.getPrototypeOf(value);
99
+ if (prototype !== Object.prototype && prototype !== null) {
100
+ return value;
101
+ }
102
+ const redacted = {};
103
+ for (const [key, child] of Object.entries(value)) {
104
+ if (child !== undefined && isSensitiveRequestKey(key)) {
105
+ redacted[key] = REDACTED;
106
+ }
107
+ else {
108
+ redacted[key] = redactSensitiveValue(child, depth + 1);
64
109
  }
65
110
  }
66
- return bodyCopy;
111
+ return redacted;
112
+ };
113
+ const redactSensitiveRequestBody = (body) => {
114
+ return redactSensitiveValue(body, 0);
67
115
  };
68
- const sensitiveQueryKeySet = new Set(SENSITIVE_REQUEST_BODY_KEYS);
69
116
  const redactSensitiveRequestUrl = (url) => {
70
117
  if (!url) {
71
118
  return "";
@@ -74,8 +121,8 @@ const redactSensitiveRequestUrl = (url) => {
74
121
  const parsed = new URL(url, "http://terreno.invalid");
75
122
  let didRedact = false;
76
123
  for (const key of parsed.searchParams.keys()) {
77
- if (sensitiveQueryKeySet.has(key)) {
78
- parsed.searchParams.set(key, "<REDACTED>");
124
+ if (isSensitiveRequestKey(key)) {
125
+ parsed.searchParams.set(key, REDACTED);
79
126
  didRedact = true;
80
127
  }
81
128
  }
@@ -19,9 +19,18 @@ export interface GitHubAuthOptions {
19
19
  * Defaults to true.
20
20
  */
21
21
  allowAccountLinking?: boolean;
22
+ /**
23
+ * Redirect targets allowed for the `returnTo` query parameter of `GET /auth/github`. Each entry
24
+ * is an exact http(s) origin (`https://app.example.com`) or an exact custom-scheme authority
25
+ * (`myapp://auth`). A `returnTo` that matches no entry is rejected with 400. When this is
26
+ * unset or empty, `returnTo` is ignored and the callback always returns JSON.
27
+ */
28
+ allowedReturnTo?: string[];
22
29
  /**
23
30
  * Custom function to handle user creation or lookup from GitHub profile.
24
31
  * If not provided, a default implementation will be used.
32
+ * `existingUser` is the user who started `GET /auth/github/link`, read from the verified
33
+ * OAuth state; it is never taken from a session or token on the callback request.
25
34
  */
26
35
  findOrCreateUser?: (profile: Profile, accessToken: string, refreshToken: string, existingUser?: Record<string, unknown>) => Promise<unknown>;
27
36
  }