@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
@@ -5,17 +5,20 @@
5
5
  * create session middleware, and sync users with the application User model.
6
6
  */
7
7
 
8
- import {betterAuth} from "better-auth";
8
+ import {type BetterAuthOptions, type BetterAuthPlugin, betterAuth} from "better-auth";
9
9
  import {mongodbAdapter} from "better-auth/adapters/mongodb";
10
+ import {createAuthMiddleware} from "better-auth/api";
10
11
  import {toNodeHandler} from "better-auth/node";
11
12
  import {bearer} from "better-auth/plugins";
12
13
  import type {Application, NextFunction, Request, Response} from "express";
14
+ import mergeWith from "lodash/mergeWith";
13
15
  import type {Db} from "mongodb";
14
16
  import mongoose from "mongoose";
15
17
  import {type HasSetPassword, setPasswordForUser, type UserModel} from "./auth";
16
18
  import type {BetterAuthConfig, BetterAuthSessionData, BetterAuthUser} from "./betterAuth";
17
- import {APIError} from "./errors";
18
- import type {AuthRecoveryMail} from "./expressServer";
19
+ import {createOAuthHandoffPlugins} from "./betterAuthOAuthHandoff";
20
+ import {APIError, isAPIError} from "./errors";
21
+ import type {AuthRecoveryMail, BetterAuthPasswordCheck} from "./expressServer";
19
22
  import {logger} from "./logger";
20
23
  import {findOneOrNoneFor} from "./plugins";
21
24
  import {updateRequestContextFromRequest} from "./requestContext";
@@ -106,6 +109,7 @@ export const createBetterAuthEmailHooks = (config: BetterAuthConfig) => {
106
109
  });
107
110
  const message: AuthRecoveryMail = {
108
111
  html: rendered.html,
112
+ sensitive: true,
109
113
  subject: rendered.subject,
110
114
  text: rendered.text ?? "",
111
115
  to: user.email,
@@ -136,6 +140,24 @@ export const createBetterAuthEmailHooks = (config: BetterAuthConfig) => {
136
140
  };
137
141
  };
138
142
 
143
+ // The API's own origin, which the OAuth handoff never sends a token to.
144
+ const apiOriginOf = (url: string): string => {
145
+ let origin: string;
146
+ try {
147
+ origin = new URL(url).origin;
148
+ } catch {
149
+ origin = "null";
150
+ }
151
+ if (origin === "null") {
152
+ throw new APIError({
153
+ detail: `"${url}" is not an absolute http(s) URL`,
154
+ status: 500,
155
+ title: "BETTER_AUTH_URL must be an absolute URL",
156
+ });
157
+ }
158
+ return origin;
159
+ };
160
+
139
161
  /**
140
162
  * Creates a Better Auth instance with MongoDB adapter.
141
163
  */
@@ -186,7 +208,7 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
186
208
  const emailHooks = createBetterAuthEmailHooks(config);
187
209
  const userModel = options.userModel;
188
210
 
189
- const auth = betterAuth({
211
+ const defaults: BetterAuthOptions = {
190
212
  advanced: config.crossDomainCookies
191
213
  ? {
192
214
  defaultCookieAttributes: {
@@ -222,12 +244,6 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
222
244
  },
223
245
  }
224
246
  : {}),
225
- // The bearer plugin lets clients authenticate with `Authorization: Bearer <sessionToken>`
226
- // instead of the signed session cookie. Required for cross-origin/native clients and for
227
- // websocket handshakes (RealtimeApp's Better Auth socket validator forwards the handshake
228
- // token as a bearer header) — without it, a raw session token cannot be validated and
229
- // socket auth silently fails (the sync client shows perpetually "offline").
230
- plugins: [bearer()],
231
247
  rateLimit: config.disableRateLimit ? {enabled: false} : undefined,
232
248
  secret,
233
249
  session: {
@@ -238,15 +254,46 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
238
254
  },
239
255
  socialProviders: Object.keys(socialProviders).length > 0 ? socialProviders : undefined,
240
256
  trustedOrigins: config.trustedOrigins ?? [],
257
+ };
258
+
259
+ // Arrays from `options` replace Terreno's; lodash would otherwise merge them by index.
260
+ const replaceArrays = (_target: unknown, source: unknown): unknown =>
261
+ Array.isArray(source) ? source : undefined;
262
+ const merged: BetterAuthOptions = mergeWith({}, defaults, config.options, replaceArrays);
263
+
264
+ // The handoff hook mints tokens through `auth.api`, which exists only once betterAuth() returns.
265
+ let auth: BetterAuthInstance | undefined;
266
+ const handoffPlugins = config.oauthHandoff
267
+ ? createOAuthHandoffPlugins({
268
+ apiOrigin: apiOriginOf(typeof merged.baseURL === "string" ? merged.baseURL : baseURL),
269
+ config: config.oauthHandoff,
270
+ getAuth: () => auth,
271
+ })
272
+ : [];
273
+
274
+ const credentialSyncPlugins = userModel ? [createCredentialSyncPlugin(userModel)] : [];
275
+
276
+ const created = betterAuth({
277
+ ...merged,
278
+ // The bearer plugin lets clients authenticate with `Authorization: Bearer <sessionToken>`
279
+ // instead of the signed session cookie. Required for cross-origin/native clients and for
280
+ // websocket handshakes (RealtimeApp's Better Auth socket validator forwards the handshake
281
+ // token as a bearer header) — without it, a raw session token cannot be validated and
282
+ // socket auth silently fails (the sync client shows perpetually "offline").
283
+ // The handoff plugins come last so their callback hook sees the final redirect.
284
+ // The credential sync plugin keeps the legacy passport credential in step with Better Auth.
285
+ plugins: [bearer(), ...credentialSyncPlugins, ...(config.plugins ?? []), ...handoffPlugins],
241
286
  });
242
287
 
243
288
  // Cast through unknown: enabling the bearer plugin narrows betterAuth()'s inferred
244
289
  // return type to a plugin-specific tuple that no longer matches the plugin-agnostic
245
290
  // BetterAuthInstance alias, though the runtime instance is a valid better-auth instance.
246
- return auth as unknown as BetterAuthInstance;
291
+ auth = created as unknown as BetterAuthInstance;
292
+ return auth;
247
293
  };
248
294
 
249
295
  interface BetterAuthCredentialAccount {
296
+ password?: string | null;
250
297
  providerId?: string;
251
298
  }
252
299
 
@@ -268,7 +315,10 @@ interface BetterAuthPasswordResetContext {
268
315
  findUserById: (userId: string) => Promise<{id?: string} | null>;
269
316
  updatePassword: (userId: string, password: string) => Promise<unknown>;
270
317
  };
271
- password: {hash: (password: string) => Promise<string>};
318
+ password: {
319
+ hash: (password: string) => Promise<string>;
320
+ verify: (data: {hash: string; password: string}) => Promise<boolean>;
321
+ };
272
322
  }
273
323
 
274
324
  /**
@@ -312,6 +362,118 @@ export const applyJwtPasswordResetToBetterAuth = async (
312
362
  await ctx.internalAdapter.deleteUserSessions(betterAuthUserId);
313
363
  };
314
364
 
365
+ /**
366
+ * Check `password` against the Better Auth credential account linked to an app user through
367
+ * `betterAuthId`. Returns "no-password" when the user has no linked Better Auth user or that user
368
+ * has no credential password (for example a social-only account).
369
+ */
370
+ export const verifyBetterAuthCredentialPassword = async (
371
+ auth: BetterAuthInstance,
372
+ user: {betterAuthId?: string},
373
+ password: string
374
+ ): Promise<BetterAuthPasswordCheck> => {
375
+ const betterAuthUserId = typeof user.betterAuthId === "string" ? user.betterAuthId : "";
376
+ if (!betterAuthUserId) {
377
+ return "no-password";
378
+ }
379
+ const ctx = (await auth.$context) as BetterAuthPasswordResetContext;
380
+ const accounts = await ctx.internalAdapter.findAccounts(betterAuthUserId);
381
+ const credential = accounts.find(
382
+ (account) => account.providerId === "credential" && typeof account.password === "string"
383
+ );
384
+ if (!credential?.password) {
385
+ return "no-password";
386
+ }
387
+ const isMatch = await ctx.password.verify({hash: credential.password, password});
388
+ return isMatch ? "verified" : "wrong";
389
+ };
390
+
391
+ // Better Auth endpoints that change or revoke a user's credentials; the legacy JWT credential
392
+ // must follow them.
393
+ const CREDENTIAL_CHANGE_PATHS = new Set([
394
+ "/change-password",
395
+ "/revoke-sessions",
396
+ "/revoke-other-sessions",
397
+ ]);
398
+
399
+ // The new password of an in-flight Better Auth `/reset-password`, keyed by its request. The
400
+ // endpoint reads its JSON body before `onPasswordReset` runs, so the hook cannot read it again.
401
+ const resetPasswordsByRequest = new WeakMap<object, string>();
402
+
403
+ interface CredentialHookContext {
404
+ body?: Record<string, unknown>;
405
+ context: {returned?: unknown; session?: {user?: {id?: string}} | null};
406
+ path?: string;
407
+ request?: object;
408
+ }
409
+
410
+ /**
411
+ * After a Better Auth password change, set the legacy passport password of a dual-enrolled app
412
+ * user to the new one; after a password change or session revocation, bump `tokenEpoch` so
413
+ * legacy refresh tokens issued before it stop working.
414
+ */
415
+ const applyBetterAuthCredentialChangeToJwt = async (
416
+ userModel: UserModel,
417
+ ctx: CredentialHookContext
418
+ ): Promise<void> => {
419
+ if (ctx.context.returned instanceof Error) {
420
+ return;
421
+ }
422
+ const betterAuthId = ctx.context.session?.user?.id;
423
+ if (!betterAuthId) {
424
+ return;
425
+ }
426
+ const appUser = await findOneOrNoneFor(userModel, {betterAuthId} as never);
427
+ if (!appUser) {
428
+ return;
429
+ }
430
+ const newPassword = ctx.body?.newPassword;
431
+ if (ctx.path === "/change-password" && typeof newPassword === "string") {
432
+ // Only an account that already has a legacy password gets the new one, so a Better Auth only
433
+ // account does not gain a second way to sign in.
434
+ const hasLegacyPassword =
435
+ userModel.schema.path("hash") !== undefined &&
436
+ Boolean(
437
+ await userModel.exists({_id: appUser._id, hash: {$exists: true, $ne: null}} as never)
438
+ );
439
+ if (hasLegacyPassword) {
440
+ await setPasswordForUser(appUser as unknown as HasSetPassword, newPassword);
441
+ }
442
+ }
443
+ if (userModel.schema.path("tokenEpoch") !== undefined) {
444
+ appUser.tokenEpoch = (appUser.tokenEpoch ?? 0) + 1;
445
+ }
446
+ await appUser.save();
447
+ };
448
+
449
+ const createCredentialSyncPlugin = (userModel: UserModel): BetterAuthPlugin => ({
450
+ hooks: {
451
+ after: [
452
+ {
453
+ handler: createAuthMiddleware(async (ctx): Promise<void> => {
454
+ await applyBetterAuthCredentialChangeToJwt(
455
+ userModel,
456
+ ctx as unknown as CredentialHookContext
457
+ );
458
+ }),
459
+ matcher: (ctx): boolean => CREDENTIAL_CHANGE_PATHS.has(ctx.path ?? ""),
460
+ },
461
+ ],
462
+ before: [
463
+ {
464
+ handler: createAuthMiddleware(async (ctx): Promise<void> => {
465
+ const newPassword = (ctx.body as Record<string, unknown> | undefined)?.newPassword;
466
+ if (ctx.request && typeof newPassword === "string") {
467
+ resetPasswordsByRequest.set(ctx.request, newPassword);
468
+ }
469
+ }),
470
+ matcher: (ctx): boolean => ctx.path === "/reset-password",
471
+ },
472
+ ],
473
+ },
474
+ id: "terreno-credential-sync",
475
+ });
476
+
315
477
  interface PasswordResetRequestLike {
316
478
  body?: unknown;
317
479
  clone?: () => {json: () => Promise<unknown>};
@@ -335,6 +497,10 @@ export const readPasswordFromBetterAuthResetRequest = async (
335
497
  if (!request) {
336
498
  return "";
337
499
  }
500
+ const stashed = resetPasswordsByRequest.get(request);
501
+ if (stashed) {
502
+ return stashed;
503
+ }
338
504
  const attached = passwordFromUnknown(request.body);
339
505
  if (attached.length > 0) {
340
506
  return attached;
@@ -381,6 +547,81 @@ export const applyBetterAuthPasswordResetToJwt = async (
381
547
  await appUser.save();
382
548
  };
383
549
 
550
+ const UNSAFE_METHODS = new Set(["DELETE", "PATCH", "POST", "PUT"]);
551
+
552
+ interface OriginCheckContext {
553
+ isTrustedOrigin: (url: string, settings?: {allowRelativePaths: boolean}) => boolean;
554
+ options: {advanced?: {disableCSRFCheck?: boolean; disableOriginCheck?: boolean | string[]}};
555
+ }
556
+
557
+ const headerValue = (value: string | string[] | undefined): string | undefined =>
558
+ Array.isArray(value) ? value[0] : value;
559
+
560
+ const originOfReferer = (referer: string | undefined): string | undefined => {
561
+ if (!referer) {
562
+ return undefined;
563
+ }
564
+ try {
565
+ return new URL(referer).origin;
566
+ } catch {
567
+ return "null";
568
+ }
569
+ };
570
+
571
+ // True when the request's own `Authorization: Bearer` token is the session Better Auth resolved,
572
+ // rather than a cookie sent beside some other header. The bearer plugin accepts the raw token or
573
+ // the signed `token.signature` form.
574
+ const isBearerSession = (req: Request, sessionToken: string): boolean => {
575
+ const match = /^Bearer\s+(.+)$/i.exec(headerValue(req.headers.authorization) ?? "");
576
+ if (!match || !sessionToken) {
577
+ return false;
578
+ }
579
+ let bearer = match[1].trim();
580
+ try {
581
+ bearer = decodeURIComponent(bearer);
582
+ } catch {
583
+ return false;
584
+ }
585
+ return bearer === sessionToken || bearer.startsWith(`${sessionToken}.`);
586
+ };
587
+
588
+ /**
589
+ * A session cookie rides along on requests other sites start, so a cookie-authenticated write is
590
+ * accepted only from an origin in Better Auth's `trustedOrigins` (which includes the API's own
591
+ * origin), the same rule Better Auth applies to its own routes. Bearer requests cannot be forged
592
+ * by another site. A request with no Origin, Referer, or cross-site Fetch Metadata did not come
593
+ * from a browser page, so it is not a cross-site forgery.
594
+ */
595
+ const isUntrustedCookieWrite = async (
596
+ auth: BetterAuthInstance,
597
+ req: Request,
598
+ sessionToken: string
599
+ ): Promise<boolean> => {
600
+ if (!UNSAFE_METHODS.has(req.method) || !req.headers.cookie) {
601
+ return false;
602
+ }
603
+ if (isBearerSession(req, sessionToken)) {
604
+ return false;
605
+ }
606
+ const context = (await auth.$context) as unknown as OriginCheckContext;
607
+ const advanced = context.options.advanced;
608
+ const isCsrfCheckDisabled =
609
+ advanced?.disableCSRFCheck === true ||
610
+ (advanced?.disableOriginCheck === true && advanced.disableCSRFCheck === undefined);
611
+ if (isCsrfCheckDisabled) {
612
+ return false;
613
+ }
614
+ const origin =
615
+ headerValue(req.headers.origin) ?? originOfReferer(headerValue(req.headers.referer));
616
+ if (!origin) {
617
+ return headerValue(req.headers["sec-fetch-site"]) === "cross-site";
618
+ }
619
+ if (origin === "null") {
620
+ return true;
621
+ }
622
+ return !context.isTrustedOrigin(origin, {allowRelativePaths: false});
623
+ };
624
+
384
625
  /**
385
626
  * Creates Express middleware that extracts the Better Auth session
386
627
  * and populates req.user with the application User model.
@@ -395,7 +636,16 @@ export const createBetterAuthSessionMiddleware = (
395
636
  headers: req.headers as Record<string, string>,
396
637
  });
397
638
 
398
- if (session?.user && session?.session) {
639
+ if (
640
+ session?.user &&
641
+ session?.session &&
642
+ (await isUntrustedCookieWrite(auth, req, String(session.session.token ?? "")))
643
+ ) {
644
+ // Fall through as anonymous, like a disabled user, so protected routes answer 401.
645
+ logger.warn(
646
+ `[better-auth] Ignored a session cookie on ${req.method} ${req.path} from an untrusted origin`
647
+ );
648
+ } else if (session?.user && session?.session) {
399
649
  const betterAuthUser = session.user as BetterAuthUser;
400
650
 
401
651
  const reqWithSession = req as Request & {
@@ -403,18 +653,15 @@ export const createBetterAuthSessionMiddleware = (
403
653
  betterAuthSession?: BetterAuthSessionData;
404
654
  };
405
655
  if (userModel) {
406
- // Look up the application user by betterAuthId
407
- const appUser = await findOneOrNoneFor(userModel, {
408
- betterAuthId: betterAuthUser.id,
409
- });
410
- if (appUser) {
411
- reqWithSession.user = appUser as unknown as Request["user"];
412
- reqWithSession.betterAuthSession = session as unknown as BetterAuthSessionData;
413
- updateRequestContextFromRequest(req);
656
+ const {isDisabled, user} = await resolveBetterAuthAppUser({betterAuthUser, userModel});
657
+ if (isDisabled) {
658
+ // A disabled account's live sessions stop authenticating. Falling through as
659
+ // anonymous, rather than answering 401 here, keeps Better Auth's own routes
660
+ // (sign-out, signing in as someone else) reachable, since TerrenoApp mounts this
661
+ // middleware before them.
662
+ logger.debug(`[better-auth] User ${user.id} is disabled, ignoring their session`);
414
663
  } else {
415
- // User exists in Better Auth but not synced yet - create them
416
- const newUser = await syncBetterAuthUser(userModel, betterAuthUser);
417
- reqWithSession.user = newUser as unknown as Request["user"];
664
+ reqWithSession.user = user as unknown as Request["user"];
418
665
  reqWithSession.betterAuthSession = session as unknown as BetterAuthSessionData;
419
666
  updateRequestContextFromRequest(req);
420
667
  }
@@ -448,8 +695,10 @@ export const createBetterAuthSessionMiddleware = (
448
695
  // Loose shape used when mutating Mongoose user documents during Better Auth sync.
449
696
  // The fields are added by the consumer's user schema (via baseUserPlugin or similar).
450
697
  interface MutableUserDoc {
698
+ _id?: unknown;
451
699
  admin?: boolean;
452
700
  email?: string;
701
+ emailVerified?: boolean;
453
702
  name?: string;
454
703
  betterAuthId?: string;
455
704
  oauthProvider?: string | null;
@@ -457,10 +706,71 @@ interface MutableUserDoc {
457
706
  save: () => Promise<unknown>;
458
707
  }
459
708
 
709
+ export interface SyncBetterAuthUserOptions {
710
+ /**
711
+ * Link an existing app user by email even when Better Auth has not verified the address or
712
+ * the row is bound to another Better Auth id. Only for operator-run seeds that create the
713
+ * Better Auth account themselves; never set it for a request-driven sync.
714
+ */
715
+ trustEmail?: boolean;
716
+ }
717
+
718
+ /**
719
+ * An email alone does not prove the caller owns an existing app user. Link by email only when
720
+ * Better Auth verified the address and the row is not bound to another Better Auth account.
721
+ */
722
+ const assertEmailLinkAllowed = (
723
+ userByEmail: MutableUserDoc,
724
+ betterAuthUser: BetterAuthUser
725
+ ): void => {
726
+ if (betterAuthUser.emailVerified === true && !userByEmail.betterAuthId) {
727
+ return;
728
+ }
729
+ throw new APIError({
730
+ detail: "Verify the email address before signing in to the existing account.",
731
+ disableExternalErrorTracking: true,
732
+ status: 409,
733
+ title: "An account with this email already exists",
734
+ });
735
+ };
736
+
737
+ /**
738
+ * A legacy password on a row whose email was never verified may have been set by someone who
739
+ * does not own the mailbox. Once the verified owner links the row, that password and the
740
+ * refresh tokens issued from it stop working.
741
+ */
742
+ const revokeUnprovenLegacyPassword = async (
743
+ userModel: UserModel,
744
+ userByEmail: MutableUserDoc
745
+ ): Promise<void> => {
746
+ if (userByEmail.emailVerified === true || userModel.schema.path("hash") === undefined) {
747
+ return;
748
+ }
749
+ const hasLegacyPassword = await userModel.exists({
750
+ _id: userByEmail._id,
751
+ hash: {$exists: true, $ne: null},
752
+ } as never);
753
+ if (!hasLegacyPassword) {
754
+ return;
755
+ }
756
+ const bumpEpoch = userModel.schema.path("tokenEpoch") !== undefined;
757
+ await userModel.updateOne(
758
+ {_id: userByEmail._id} as never,
759
+ {
760
+ $unset: {hash: 1, salt: 1},
761
+ ...(bumpEpoch ? {$inc: {tokenEpoch: 1}} : {}),
762
+ } as never
763
+ );
764
+ logger.info(
765
+ `Revoked an unverified legacy password while linking Better Auth user ${userByEmail.id}`
766
+ );
767
+ };
768
+
460
769
  export const syncBetterAuthUser = async (
461
770
  userModel: UserModel,
462
771
  betterAuthUser: BetterAuthUser,
463
- oauthProvider?: string
772
+ oauthProvider?: string,
773
+ options: SyncBetterAuthUserOptions = {}
464
774
  ): Promise<MutableUserDoc> => {
465
775
  try {
466
776
  const existingUser = (await findOneOrNoneFor(userModel, {
@@ -481,7 +791,15 @@ export const syncBetterAuthUser = async (
481
791
  const userByEmail = (await findOneOrNoneFor(userModel, {
482
792
  email: betterAuthUser.email,
483
793
  })) as unknown as MutableUserDoc | null;
794
+ if (userByEmail?.betterAuthId === betterAuthUser.id) {
795
+ // A concurrent first contact created this row between the two lookups.
796
+ return userByEmail;
797
+ }
484
798
  if (userByEmail) {
799
+ if (!options.trustEmail) {
800
+ assertEmailLinkAllowed(userByEmail, betterAuthUser);
801
+ await revokeUnprovenLegacyPassword(userModel, userByEmail);
802
+ }
485
803
  // Link existing user to Better Auth
486
804
  userByEmail.betterAuthId = betterAuthUser.id;
487
805
  if (oauthProvider) {
@@ -508,11 +826,64 @@ export const syncBetterAuthUser = async (
508
826
  logger.info(`Created new user from Better Auth: ${newUser.id}`);
509
827
  return newUser;
510
828
  } catch (error) {
511
- logger.error(`Error syncing Better Auth user: ${error}`);
829
+ // A duplicate key means a concurrent request created the user first; callers such as
830
+ // resolveBetterAuthAppUser recover from it, so it is not an error worth alerting on.
831
+ if ((error as {code?: number}).code === 11000) {
832
+ logger.debug(`Better Auth user was created concurrently: ${error}`);
833
+ } else if (isAPIError(error) && error.status === 409) {
834
+ logger.warn(`Refused to link Better Auth user ${betterAuthUser.id} by email: ${error.title}`);
835
+ } else {
836
+ logger.error(`Error syncing Better Auth user: ${error}`);
837
+ }
512
838
  throw error;
513
839
  }
514
840
  };
515
841
 
842
+ export interface ResolveBetterAuthAppUserOptions {
843
+ userModel: UserModel;
844
+ betterAuthUser: BetterAuthUser;
845
+ }
846
+
847
+ export interface ResolvedBetterAuthAppUser {
848
+ user: MutableUserDoc & {disabled?: boolean};
849
+ isDisabled: boolean;
850
+ }
851
+
852
+ /**
853
+ * Finds the application user for a Better Auth session user, creating it on first contact,
854
+ * and reports whether the account is disabled. Every Better Auth entry point (REST session
855
+ * middleware, socket handshake) goes through this so they accept and refuse the same users.
856
+ */
857
+ export const resolveBetterAuthAppUser = async ({
858
+ userModel,
859
+ betterAuthUser,
860
+ }: ResolveBetterAuthAppUserOptions): Promise<ResolvedBetterAuthAppUser> => {
861
+ const findByBetterAuthId = async (): Promise<ResolvedBetterAuthAppUser["user"] | null> =>
862
+ (await findOneOrNoneFor(userModel, {
863
+ betterAuthId: betterAuthUser.id,
864
+ })) as unknown as ResolvedBetterAuthAppUser["user"] | null;
865
+
866
+ let user = await findByBetterAuthId();
867
+ if (!user) {
868
+ try {
869
+ user = (await syncBetterAuthUser(
870
+ userModel,
871
+ betterAuthUser
872
+ )) as ResolvedBetterAuthAppUser["user"];
873
+ } catch (error) {
874
+ // Right after sign-up the socket handshake and the first REST calls race to create the
875
+ // same user; the loser's insert hits the unique `_id` (or `betterAuthId`) index.
876
+ const isDuplicateKey = (error as {code?: number}).code === 11000;
877
+ const createdConcurrently = isDuplicateKey ? await findByBetterAuthId() : null;
878
+ if (!createdConcurrently) {
879
+ throw error;
880
+ }
881
+ user = createdConcurrently;
882
+ }
883
+ }
884
+ return {isDisabled: Boolean(user.disabled), user};
885
+ };
886
+
516
887
  /**
517
888
  * Mounts Better Auth routes on the Express app.
518
889
  */
@@ -532,18 +903,20 @@ export const mountBetterAuthRoutes = (
532
903
  };
533
904
 
534
905
  /**
535
- * Gets the MongoDB client from the mongoose connection.
906
+ * Gets a MongoDB client view whose db() is the mongoose connection's database (its dbName).
536
907
  */
537
908
  export const getMongoClientFromMongoose = (): MongoClientLike => {
538
909
  const connection = mongoose.connection;
539
- const client = (connection as unknown as {client?: MongoClientLike}).client;
910
+ const client = (connection as unknown as {client?: {db: (dbName?: string) => Db}}).client;
540
911
  if (!client) {
541
912
  throw new APIError({
542
913
  status: 500,
543
914
  title: "Mongoose is not connected. Ensure MongoDB connection is established first.",
544
915
  });
545
916
  }
546
- return client;
917
+ // Use the connection's database (mongoose's dbName option), not the URI default, so Better
918
+ // Auth's collections live beside the app's models.
919
+ return {db: (): Db => client.db(connection.name || undefined)};
547
920
  };
548
921
 
549
922
  /**
@@ -225,6 +225,69 @@ describe("expressServer", () => {
225
225
  }
226
226
  });
227
227
 
228
+ it("redacts credentials under any key name and at any depth in logged bodies", () => {
229
+ const logged: string[] = [];
230
+ const originalDebug = logger.debug;
231
+ logger.debug = ((message: string) => {
232
+ logged.push(message);
233
+ }) as typeof logger.debug;
234
+ try {
235
+ const req = {
236
+ body: {
237
+ client_secret: "dummy-client-secret",
238
+ code_verifier: "dummy-code-verifier",
239
+ currentPassword: "dummy-current-pass",
240
+ idToken: {token: "dummy-id-token"},
241
+ integrations: [{apiKey: "dummy-api-key", name: "listed-integration"}],
242
+ otp: "123456",
243
+ provider: "google",
244
+ refresh_token: "dummy-refresh-token",
245
+ },
246
+ method: "POST",
247
+ url: "/api/auth/sign-in/social",
248
+ };
249
+ logRequests(req as never, {locals: {}, on: () => {}} as never, () => {});
250
+ const combined = logged.join("\n");
251
+ for (const secret of [
252
+ "dummy-client-secret",
253
+ "dummy-code-verifier",
254
+ "dummy-current-pass",
255
+ "dummy-id-token",
256
+ "dummy-api-key",
257
+ "123456",
258
+ "dummy-refresh-token",
259
+ ]) {
260
+ expect(combined).not.toContain(secret);
261
+ }
262
+ expect(combined).toContain("google");
263
+ expect(combined).toContain("listed-integration");
264
+ expect(req.body.idToken.token).toBe("dummy-id-token");
265
+ } finally {
266
+ logger.debug = originalDebug;
267
+ }
268
+ });
269
+
270
+ it("redacts OAuth codes and other credential query params in request URLs", () => {
271
+ const logged: string[] = [];
272
+ const originalDebug = logger.debug;
273
+ logger.debug = ((message: string) => {
274
+ logged.push(message);
275
+ }) as typeof logger.debug;
276
+ try {
277
+ const req = {
278
+ method: "GET",
279
+ url: "/api/auth/callback/google?code=dummy-oauth-code&state=abc&client_secret=dummy-cs",
280
+ };
281
+ logRequests(req as never, {locals: {}, on: () => {}} as never, () => {});
282
+ const combined = logged.join("\n");
283
+ expect(combined).not.toContain("dummy-oauth-code");
284
+ expect(combined).not.toContain("dummy-cs");
285
+ expect(combined).toContain("state=abc");
286
+ } finally {
287
+ logger.debug = originalDebug;
288
+ }
289
+ });
290
+
228
291
  it("redacts token query params in request URLs", () => {
229
292
  const logged: string[] = [];
230
293
  const originalDebug = logger.debug;
@@ -531,6 +594,36 @@ describe("expressServer", () => {
531
594
  expect(app).toBeDefined();
532
595
  });
533
596
 
597
+ it("does not log requests when loggingOptions.logRequests is false", async () => {
598
+ const logged: string[] = [];
599
+ const originalDebug = logger.debug;
600
+ logger.debug = ((message: string) => {
601
+ logged.push(message);
602
+ }) as typeof logger.debug;
603
+ try {
604
+ const app = new TerrenoApp({
605
+ configureApp: (httpApp: Router) => {
606
+ httpApp.post("/echo", (_req, res) => {
607
+ res.json({ok: true});
608
+ });
609
+ },
610
+ loggingOptions: {
611
+ disableConsoleLogging: true,
612
+ disableFileLogging: true,
613
+ logRequests: false,
614
+ },
615
+ skipListen: true,
616
+ userModel: typedUserModel,
617
+ }).build();
618
+
619
+ await supertest(app).post("/echo").send({note: "dummy-logged-body"}).expect(200);
620
+
621
+ expect(logged.join("\n")).not.toContain("dummy-logged-body");
622
+ } finally {
623
+ logger.debug = originalDebug;
624
+ }
625
+ });
626
+
534
627
  it("creates server with authOptions", () => {
535
628
  const configureApp = (): void => {};
536
629