@terreno/api 57.18.0 → 57.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2071 -2
- package/dist/accountSecurity/accessActions.d.ts +38 -0
- package/dist/accountSecurity/accessActions.js +157 -0
- package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
- package/dist/accountSecurity/accountSecurityApp.js +438 -0
- package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
- package/dist/accountSecurity/accountSecurityService.js +481 -0
- package/dist/accountSecurity/credentialActions.d.ts +16 -0
- package/dist/accountSecurity/credentialActions.js +189 -0
- package/dist/accountSecurity/membershipActions.d.ts +15 -0
- package/dist/accountSecurity/membershipActions.js +81 -0
- package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
- package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
- package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
- package/dist/accountSecurity/securityEventHooks.js +223 -0
- package/dist/accountSecurity/securityEvents.d.ts +162 -0
- package/dist/accountSecurity/securityEvents.js +114 -0
- package/dist/accountSecurity/securityNotifications.d.ts +125 -0
- package/dist/accountSecurity/securityNotifications.js +333 -0
- package/dist/api.js +38 -6
- package/dist/audit/auditEventModel.d.ts +5 -3
- package/dist/audit/auditEventModel.js +8 -6
- package/dist/audit/processQueue.js +4 -2
- package/dist/audit/record.d.ts +2 -2
- package/dist/audit/record.js +3 -0
- package/dist/authRecovery.js +29 -1
- package/dist/betterAuth.d.ts +179 -10
- package/dist/betterAuthApp.d.ts +15 -0
- package/dist/betterAuthApp.js +23 -0
- package/dist/betterAuthChallengeHeaders.d.ts +37 -0
- package/dist/betterAuthChallengeHeaders.js +180 -0
- package/dist/betterAuthFeatures.d.ts +54 -0
- package/dist/betterAuthFeatures.js +239 -0
- package/dist/betterAuthMethods.d.ts +73 -0
- package/dist/betterAuthMethods.js +55 -0
- package/dist/betterAuthOAuthHandoff.d.ts +10 -2
- package/dist/betterAuthOAuthHandoff.js +222 -24
- package/dist/betterAuthSetPassword.d.ts +33 -0
- package/dist/betterAuthSetPassword.js +166 -0
- package/dist/betterAuthSetup.d.ts +57 -8
- package/dist/betterAuthSetup.js +327 -36
- package/dist/consentApp.d.ts +9 -4
- package/dist/consentApp.js +344 -28
- package/dist/consentStatus.d.ts +60 -0
- package/dist/consentStatus.js +111 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +41 -2
- package/dist/expressServer.js +3 -2
- package/dist/index.d.ts +14 -2
- package/dist/index.js +23 -3
- package/dist/mcp/oauth.js +151 -11
- package/dist/mcp/oauthMetadata.d.ts +2 -1
- package/dist/mcp/oauthMetadata.js +7 -4
- package/dist/models/consentResponse.js +51 -0
- package/dist/models/mcpOAuthClient.js +78 -2
- package/dist/models/mcpOAuthToken.js +28 -4
- package/dist/orgs/membershipGuards.d.ts +7 -0
- package/dist/orgs/membershipGuards.js +32 -0
- package/dist/orgs/orgsApp.d.ts +19 -1
- package/dist/orgs/orgsApp.js +55 -24
- package/dist/rateLimit/policies.js +8 -0
- package/dist/rbac/access.js +2 -1
- package/dist/rbac/resolve.d.ts +9 -1
- package/dist/rbac/resolve.js +21 -16
- package/dist/rbac/roleManager.d.ts +6 -0
- package/dist/rbac/roleManager.js +8 -7
- package/dist/rbac/roleModel.d.ts +1 -0
- package/dist/rbac/roleModel.js +45 -3
- package/dist/rbac/statements.d.ts +2 -2
- package/dist/rbac/statements.js +10 -1
- package/dist/rbac/types.d.ts +6 -0
- package/dist/rbac/userWriteGuards.js +2 -1
- package/dist/schemaMetadata.js +8 -1
- package/dist/seedRunner.js +7 -2
- package/dist/terrenoApp.d.ts +4 -0
- package/dist/terrenoApp.js +15 -0
- package/dist/tests/models.d.ts +5 -0
- package/dist/tests/models.js +8 -0
- package/dist/types/consentResponse.d.ts +8 -0
- package/dist/types/mcpOAuth.d.ts +35 -2
- package/package.json +6 -3
- package/src/__snapshots__/openApi.test.ts.snap +288 -0
- package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
- package/src/accountSecurity/accessActions.test.ts +723 -0
- package/src/accountSecurity/accessActions.ts +173 -0
- package/src/accountSecurity/accountSecurity.test.ts +947 -0
- package/src/accountSecurity/accountSecurityApp.ts +720 -0
- package/src/accountSecurity/accountSecurityService.ts +826 -0
- package/src/accountSecurity/credentialActions.test.ts +867 -0
- package/src/accountSecurity/credentialActions.ts +260 -0
- package/src/accountSecurity/membershipActions.ts +89 -0
- package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
- package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
- package/src/accountSecurity/securityEventHooks.ts +294 -0
- package/src/accountSecurity/securityEvents.ts +165 -0
- package/src/accountSecurity/securityNotifications.test.ts +1323 -0
- package/src/accountSecurity/securityNotifications.ts +516 -0
- package/src/api.arrayOperations.test.ts +71 -0
- package/src/api.ts +38 -7
- package/src/audit/auditEventModel.ts +10 -7
- package/src/audit/processQueue.ts +4 -2
- package/src/audit/record.test.ts +15 -0
- package/src/audit/record.ts +10 -2
- package/src/authRecovery.test.ts +23 -0
- package/src/authRecovery.ts +34 -1
- package/src/authRecoveryBetterAuth.test.ts +169 -0
- package/src/betterAuth.ts +194 -8
- package/src/betterAuthApp.ts +32 -0
- package/src/betterAuthChallengeHeaders.test.ts +476 -0
- package/src/betterAuthChallengeHeaders.ts +227 -0
- package/src/betterAuthFeatures.test.ts +489 -0
- package/src/betterAuthFeatures.ts +283 -0
- package/src/betterAuthLinking.test.ts +844 -0
- package/src/betterAuthMethods.test.ts +138 -0
- package/src/betterAuthMethods.ts +98 -0
- package/src/betterAuthOAuthHandoff.test.ts +482 -69
- package/src/betterAuthOAuthHandoff.ts +293 -33
- package/src/betterAuthOAuthProxy.test.ts +421 -0
- package/src/betterAuthPasswordReset.test.ts +190 -0
- package/src/betterAuthSetPassword.test.ts +378 -0
- package/src/betterAuthSetPassword.ts +213 -0
- package/src/betterAuthSetup.test.ts +39 -7
- package/src/betterAuthSetup.ts +457 -38
- package/src/consentApp.test.ts +869 -2
- package/src/consentApp.ts +438 -36
- package/src/consentStatus.test.ts +226 -0
- package/src/consentStatus.ts +171 -0
- package/src/errors.test.ts +81 -0
- package/src/errors.ts +50 -1
- package/src/expressServer.test.ts +29 -0
- package/src/expressServer.ts +3 -2
- package/src/index.ts +30 -0
- package/src/mcp/oauth.test.ts +463 -2
- package/src/mcp/oauth.ts +184 -13
- package/src/mcp/oauthMetadata.ts +5 -2
- package/src/models/consentResponse.ts +53 -0
- package/src/models/mcpOAuthClient.ts +100 -3
- package/src/models/mcpOAuthToken.ts +30 -5
- package/src/orgs/membershipGuards.ts +39 -0
- package/src/orgs/orgRbac.test.ts +1 -1
- package/src/orgs/orgsApp.test.ts +101 -2
- package/src/orgs/orgsApp.ts +69 -28
- package/src/rateLimit/policies.test.ts +53 -0
- package/src/rateLimit/policies.ts +8 -0
- package/src/rbac/access.ts +4 -1
- package/src/rbac/resolve.test.ts +65 -0
- package/src/rbac/resolve.ts +37 -17
- package/src/rbac/roleManager.test.ts +64 -0
- package/src/rbac/roleManager.ts +15 -6
- package/src/rbac/roleModel.test.ts +174 -1
- package/src/rbac/roleModel.ts +66 -3
- package/src/rbac/routes.test.ts +58 -0
- package/src/rbac/statements.test.ts +4 -1
- package/src/rbac/statements.ts +11 -1
- package/src/rbac/types.ts +6 -1
- package/src/rbac/userWriteGuards.test.ts +48 -0
- package/src/rbac/userWriteGuards.ts +5 -2
- package/src/schemaMetadata.test.ts +39 -0
- package/src/schemaMetadata.ts +11 -1
- package/src/seedRunner.test.ts +56 -0
- package/src/seedRunner.ts +7 -2
- package/src/terrenoApp.ts +20 -0
- package/src/tests/accountSecurityTestApp.ts +290 -0
- package/src/tests/betterAuthStubs.ts +188 -0
- package/src/tests/mockOidcProvider.ts +105 -0
- package/src/tests/models.ts +13 -0
- package/src/tests/softwareAuthenticator.ts +183 -0
- package/src/types/consentResponse.ts +8 -0
- package/src/types/mcpOAuth.ts +39 -3
package/src/betterAuthSetup.ts
CHANGED
|
@@ -7,16 +7,30 @@
|
|
|
7
7
|
|
|
8
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
|
+
import {APIError as BetterAuthAPIError, createAuthMiddleware} from "better-auth/api";
|
|
11
11
|
import {toNodeHandler} from "better-auth/node";
|
|
12
12
|
import {bearer} from "better-auth/plugins";
|
|
13
13
|
import type {Application, NextFunction, Request, Response} from "express";
|
|
14
14
|
import mergeWith from "lodash/mergeWith";
|
|
15
15
|
import type {Db} from "mongodb";
|
|
16
16
|
import mongoose from "mongoose";
|
|
17
|
+
import {
|
|
18
|
+
createSecurityEventsPlugin,
|
|
19
|
+
recordSelfSecurityAction,
|
|
20
|
+
} from "./accountSecurity/securityEventHooks";
|
|
17
21
|
import {type HasSetPassword, setPasswordForUser, type UserModel} from "./auth";
|
|
18
22
|
import type {BetterAuthConfig, BetterAuthSessionData, BetterAuthUser} from "./betterAuth";
|
|
23
|
+
import {
|
|
24
|
+
buildFeatureOptions,
|
|
25
|
+
buildFeaturePlugins,
|
|
26
|
+
createLinkingDisabledPlugin,
|
|
27
|
+
createSignUpClosedPlugin,
|
|
28
|
+
isSignUpClosed,
|
|
29
|
+
resolveAppleProvider,
|
|
30
|
+
} from "./betterAuthFeatures";
|
|
31
|
+
import {createMethodsPlugin} from "./betterAuthMethods";
|
|
19
32
|
import {createOAuthHandoffPlugins} from "./betterAuthOAuthHandoff";
|
|
33
|
+
import {createSetPasswordPlugin} from "./betterAuthSetPassword";
|
|
20
34
|
import {APIError, isAPIError} from "./errors";
|
|
21
35
|
import type {AuthRecoveryMail, BetterAuthPasswordCheck} from "./expressServer";
|
|
22
36
|
import {logger} from "./logger";
|
|
@@ -36,6 +50,15 @@ export interface MongoClientLike {
|
|
|
36
50
|
db: () => Db;
|
|
37
51
|
}
|
|
38
52
|
|
|
53
|
+
// One entry of Better Auth's `socialProviders` as Terreno builds it.
|
|
54
|
+
interface SocialProviderConfig {
|
|
55
|
+
appBundleIdentifier?: string;
|
|
56
|
+
clientId: string;
|
|
57
|
+
clientSecret: string;
|
|
58
|
+
disableImplicitSignUp?: boolean;
|
|
59
|
+
disableSignUp?: boolean;
|
|
60
|
+
}
|
|
61
|
+
|
|
39
62
|
export interface CreateBetterAuthOptions {
|
|
40
63
|
config: BetterAuthConfig;
|
|
41
64
|
mongoClient: MongoClientLike;
|
|
@@ -60,6 +83,13 @@ const interpolateMail = (value: string, data: Record<string, string>): string =>
|
|
|
60
83
|
return data[key] ?? "";
|
|
61
84
|
});
|
|
62
85
|
|
|
86
|
+
/**
|
|
87
|
+
* The app page that finishes a Better Auth password reset: `{publicAppUrl}/resetPassword?token=`.
|
|
88
|
+
* The built-in reset mail and the admin sign-in link both point here.
|
|
89
|
+
*/
|
|
90
|
+
export const betterAuthResetPasswordUrl = (publicAppUrl: string, token: string): string =>
|
|
91
|
+
`${publicAppUrl.replace(/\/$/, "")}/resetPassword?token=${encodeURIComponent(token)}`;
|
|
92
|
+
|
|
63
93
|
const fallbackRenderAuthMail = ({
|
|
64
94
|
publicAppUrl,
|
|
65
95
|
templateId,
|
|
@@ -73,7 +103,7 @@ const fallbackRenderAuthMail = ({
|
|
|
73
103
|
}): {html?: string; subject: string; text?: string} => {
|
|
74
104
|
const template = templates?.[templateId] ?? FALLBACK_AUTH_MAIL[templateId];
|
|
75
105
|
const base = publicAppUrl.replace(/\/$/, "");
|
|
76
|
-
const resetUrl =
|
|
106
|
+
const resetUrl = betterAuthResetPasswordUrl(base, token);
|
|
77
107
|
const verifyUrl = `${base}/verifyEmail?token=${encodeURIComponent(token)}`;
|
|
78
108
|
const data = {publicAppUrl: base, resetUrl, token, verifyUrl};
|
|
79
109
|
return {
|
|
@@ -182,27 +212,30 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
|
|
|
182
212
|
|
|
183
213
|
const basePath = config.basePath ?? "/api/auth";
|
|
184
214
|
|
|
185
|
-
const
|
|
215
|
+
const isClosed = isSignUpClosed(config);
|
|
216
|
+
const socialProviders: Record<string, SocialProviderConfig> = {};
|
|
217
|
+
const addSocialProvider = (id: string, provider: SocialProviderConfig): void => {
|
|
218
|
+
socialProviders[id] = isClosed
|
|
219
|
+
? {...provider, disableImplicitSignUp: true, disableSignUp: true}
|
|
220
|
+
: provider;
|
|
221
|
+
};
|
|
186
222
|
|
|
187
223
|
if (config.googleOAuth) {
|
|
188
|
-
|
|
224
|
+
addSocialProvider("google", {
|
|
189
225
|
clientId: config.googleOAuth.clientId,
|
|
190
226
|
clientSecret: config.googleOAuth.clientSecret,
|
|
191
|
-
};
|
|
227
|
+
});
|
|
192
228
|
}
|
|
193
229
|
|
|
194
230
|
if (config.appleOAuth) {
|
|
195
|
-
|
|
196
|
-
clientId: config.appleOAuth.clientId,
|
|
197
|
-
clientSecret: config.appleOAuth.clientSecret,
|
|
198
|
-
};
|
|
231
|
+
addSocialProvider("apple", resolveAppleProvider(config.appleOAuth));
|
|
199
232
|
}
|
|
200
233
|
|
|
201
234
|
if (config.githubOAuth) {
|
|
202
|
-
|
|
235
|
+
addSocialProvider("github", {
|
|
203
236
|
clientId: config.githubOAuth.clientId,
|
|
204
237
|
clientSecret: config.githubOAuth.clientSecret,
|
|
205
|
-
};
|
|
238
|
+
});
|
|
206
239
|
}
|
|
207
240
|
|
|
208
241
|
const emailHooks = createBetterAuthEmailHooks(config);
|
|
@@ -231,7 +264,17 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
|
|
|
231
264
|
{user}: {user: {email?: string; id?: string}},
|
|
232
265
|
request?: PasswordResetRequestLike
|
|
233
266
|
): Promise<void> => {
|
|
234
|
-
await applyBetterAuthPasswordResetToJwt(
|
|
267
|
+
await applyBetterAuthPasswordResetToJwt(
|
|
268
|
+
userModel,
|
|
269
|
+
user,
|
|
270
|
+
request,
|
|
271
|
+
passwordFromUnknown(currentBetterAuthEndpointBody())
|
|
272
|
+
);
|
|
273
|
+
await recordSelfSecurityAction({
|
|
274
|
+
action: "password-reset",
|
|
275
|
+
betterAuthUserId: user.id,
|
|
276
|
+
userModel,
|
|
277
|
+
});
|
|
235
278
|
},
|
|
236
279
|
}
|
|
237
280
|
: {}),
|
|
@@ -259,7 +302,18 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
|
|
|
259
302
|
// Arrays from `options` replace Terreno's; lodash would otherwise merge them by index.
|
|
260
303
|
const replaceArrays = (_target: unknown, source: unknown): unknown =>
|
|
261
304
|
Array.isArray(source) ? source : undefined;
|
|
262
|
-
|
|
305
|
+
// Feature options (account linking, closed sign-up) sit between Terreno's defaults and
|
|
306
|
+
// `config.options`, so an explicit option still wins.
|
|
307
|
+
const merged: BetterAuthOptions = mergeWith(
|
|
308
|
+
{},
|
|
309
|
+
defaults,
|
|
310
|
+
buildFeatureOptions(config),
|
|
311
|
+
config.options,
|
|
312
|
+
replaceArrays
|
|
313
|
+
);
|
|
314
|
+
|
|
315
|
+
// `never` linking (or `options` turning linking off) refuses `/link-social` up front.
|
|
316
|
+
const isLinkingDisabled = merged.account?.accountLinking?.enabled === false;
|
|
263
317
|
|
|
264
318
|
// The handoff hook mints tokens through `auth.api`, which exists only once betterAuth() returns.
|
|
265
319
|
let auth: BetterAuthInstance | undefined;
|
|
@@ -268,6 +322,7 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
|
|
|
268
322
|
apiOrigin: apiOriginOf(typeof merged.baseURL === "string" ? merged.baseURL : baseURL),
|
|
269
323
|
config: config.oauthHandoff,
|
|
270
324
|
getAuth: () => auth,
|
|
325
|
+
isLinkingDisabled,
|
|
271
326
|
})
|
|
272
327
|
: [];
|
|
273
328
|
|
|
@@ -280,9 +335,30 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
|
|
|
280
335
|
// websocket handshakes (RealtimeApp's Better Auth socket validator forwards the handshake
|
|
281
336
|
// token as a bearer header) — without it, a raw session token cannot be validated and
|
|
282
337
|
// socket auth silently fails (the sync client shows perpetually "offline").
|
|
338
|
+
// The methods plugin serves `GET {basePath}/terreno/methods` for login screens, and the
|
|
339
|
+
// set-password plugin serves `POST {basePath}/terreno/set-password` for security screens.
|
|
340
|
+
// With a user model, the app user sync plugin links or creates the app User as each session
|
|
341
|
+
// is created (see createAppUserSyncPlugin), and the security events plugin records the
|
|
342
|
+
// user's own security changes (see createSecurityEventsPlugin).
|
|
343
|
+
// Feature plugins (two-factor, passkey, ...) come before `config.plugins`, so a consumer
|
|
344
|
+
// plugin can still hook around them. The closed sign-up plugin follows `config.plugins` so
|
|
345
|
+
// its init reaches the providers `genericOAuth` registers.
|
|
283
346
|
// The handoff plugins come last so their callback hook sees the final redirect.
|
|
284
347
|
// The credential sync plugin keeps the legacy passport credential in step with Better Auth.
|
|
285
|
-
plugins: [
|
|
348
|
+
plugins: [
|
|
349
|
+
bearer(),
|
|
350
|
+
createMethodsPlugin(),
|
|
351
|
+
createSetPasswordPlugin({userModel}),
|
|
352
|
+
...credentialSyncPlugins,
|
|
353
|
+
...buildFeaturePlugins(config, typeof merged.baseURL === "string" ? merged.baseURL : baseURL),
|
|
354
|
+
...(isLinkingDisabled ? [createLinkingDisabledPlugin()] : []),
|
|
355
|
+
...(userModel
|
|
356
|
+
? [createAppUserSyncPlugin(userModel), createSecurityEventsPlugin(userModel)]
|
|
357
|
+
: []),
|
|
358
|
+
...(config.plugins ?? []),
|
|
359
|
+
...(isClosed ? [createSignUpClosedPlugin()] : []),
|
|
360
|
+
...handoffPlugins,
|
|
361
|
+
],
|
|
286
362
|
});
|
|
287
363
|
|
|
288
364
|
// Cast through unknown: enabling the bearer plugin narrows betterAuth()'s inferred
|
|
@@ -491,6 +567,32 @@ const passwordFromUnknown = (value: unknown): string => {
|
|
|
491
567
|
return candidate;
|
|
492
568
|
};
|
|
493
569
|
|
|
570
|
+
// Better Auth keeps the AsyncLocalStorage of the endpoint being served on this global; the
|
|
571
|
+
// store holds the endpoint's context, including its parsed body. `tryGetCurrentAuthEndpointContext`
|
|
572
|
+
// in `@better-auth/core/context` reads the same store, but that package is not a direct
|
|
573
|
+
// dependency of @terreno/api and `better-auth` does not re-export it.
|
|
574
|
+
const BETTER_AUTH_GLOBAL = Symbol.for("better-auth:global");
|
|
575
|
+
|
|
576
|
+
interface BetterAuthGlobalLike {
|
|
577
|
+
context?: {endpointContextAsyncStorage?: {getStore: () => unknown}};
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* The parsed body of the Better Auth endpoint now being served (HTTP or a direct `auth.api`
|
|
582
|
+
* call), or `undefined` outside one. Better Auth reads an HTTP body before its handler runs, so a
|
|
583
|
+
* hook such as `onPasswordReset` can no longer read it from the request.
|
|
584
|
+
*/
|
|
585
|
+
export const currentBetterAuthEndpointBody = (): unknown => {
|
|
586
|
+
const betterAuthGlobal = (globalThis as Record<symbol, BetterAuthGlobalLike | undefined>)[
|
|
587
|
+
BETTER_AUTH_GLOBAL
|
|
588
|
+
];
|
|
589
|
+
const store = betterAuthGlobal?.context?.endpointContextAsyncStorage?.getStore();
|
|
590
|
+
if (!store || typeof store !== "object") {
|
|
591
|
+
return undefined;
|
|
592
|
+
}
|
|
593
|
+
return (store as {body?: unknown}).body;
|
|
594
|
+
};
|
|
595
|
+
|
|
494
596
|
export const readPasswordFromBetterAuthResetRequest = async (
|
|
495
597
|
request: PasswordResetRequestLike | undefined
|
|
496
598
|
): Promise<string> => {
|
|
@@ -518,12 +620,19 @@ export const readPasswordFromBetterAuthResetRequest = async (
|
|
|
518
620
|
/**
|
|
519
621
|
* After Better Auth password reset, update the JWT/passport hash and bump
|
|
520
622
|
* `tokenEpoch` so a dual-enrolled account cannot keep the old password or
|
|
521
|
-
* outstanding refresh tokens.
|
|
623
|
+
* outstanding refresh tokens. Only an app User that already has a JWT password gets the new one:
|
|
624
|
+
* `POST /auth/login` has no second factor, so a Better Auth only (social) account must not gain a
|
|
625
|
+
* way to sign in there. Its `tokenEpoch` is still bumped.
|
|
626
|
+
*
|
|
627
|
+
* `capturedPassword` is the new password from the parsed body of the reset endpoint being served
|
|
628
|
+
* (`newPassword`, or `password` for the email-OTP and phone-number resets). Without it the
|
|
629
|
+
* password is read from `request`, which works only while the request body is unread.
|
|
522
630
|
*/
|
|
523
631
|
export const applyBetterAuthPasswordResetToJwt = async (
|
|
524
632
|
userModel: UserModel,
|
|
525
633
|
betterAuthUser: {email?: string; id?: string},
|
|
526
|
-
request: PasswordResetRequestLike | undefined
|
|
634
|
+
request: PasswordResetRequestLike | undefined,
|
|
635
|
+
capturedPassword?: string
|
|
527
636
|
): Promise<void> => {
|
|
528
637
|
const betterAuthId = typeof betterAuthUser.id === "string" ? betterAuthUser.id : "";
|
|
529
638
|
const email = typeof betterAuthUser.email === "string" ? betterAuthUser.email : "";
|
|
@@ -534,7 +643,15 @@ export const applyBetterAuthPasswordResetToJwt = async (
|
|
|
534
643
|
if (!appUser) {
|
|
535
644
|
return;
|
|
536
645
|
}
|
|
537
|
-
const
|
|
646
|
+
const hasLegacyPassword =
|
|
647
|
+
userModel.schema.path("hash") !== undefined &&
|
|
648
|
+
Boolean(await userModel.exists({_id: appUser._id, hash: {$exists: true, $ne: null}} as never));
|
|
649
|
+
if (!hasLegacyPassword) {
|
|
650
|
+
appUser.tokenEpoch = (appUser.tokenEpoch ?? 0) + 1;
|
|
651
|
+
await appUser.save();
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
const password = capturedPassword || (await readPasswordFromBetterAuthResetRequest(request));
|
|
538
655
|
if (!password) {
|
|
539
656
|
logger.error("[auth] Better Auth password reset did not include a password to sync to JWT");
|
|
540
657
|
throw new APIError({
|
|
@@ -688,6 +805,15 @@ export const createBetterAuthSessionMiddleware = (
|
|
|
688
805
|
};
|
|
689
806
|
};
|
|
690
807
|
|
|
808
|
+
/**
|
|
809
|
+
* The stable title (and Better Auth error message) for a sign-in whose unverified email matches
|
|
810
|
+
* an app User it cannot prove it owns.
|
|
811
|
+
*/
|
|
812
|
+
export const VERIFY_EMAIL_TO_USE_ACCOUNT = "Verify your email to use this account";
|
|
813
|
+
|
|
814
|
+
/** The Better Auth error code (JSON `code`, OAuth redirect `error`) for the same refusal. */
|
|
815
|
+
const VERIFY_EMAIL_ERROR_CODE = "VERIFY_EMAIL_TO_USE_ACCOUNT";
|
|
816
|
+
|
|
691
817
|
/**
|
|
692
818
|
* Syncs a Better Auth user to the application User model.
|
|
693
819
|
* Creates or updates the user as needed.
|
|
@@ -707,6 +833,13 @@ interface MutableUserDoc {
|
|
|
707
833
|
}
|
|
708
834
|
|
|
709
835
|
export interface SyncBetterAuthUserOptions {
|
|
836
|
+
/**
|
|
837
|
+
* The plaintext password from the sign-up or sign-in request being served. When an app User
|
|
838
|
+
* with the same email is not linked yet and the Better Auth email is unverified, the user is
|
|
839
|
+
* linked only if this password verifies against that User's passport-local-mongoose hash.
|
|
840
|
+
* Never stored or logged.
|
|
841
|
+
*/
|
|
842
|
+
password?: string;
|
|
710
843
|
/**
|
|
711
844
|
* Link an existing app user by email even when Better Auth has not verified the address or
|
|
712
845
|
* the row is bound to another Better Auth id. Only for operator-run seeds that create the
|
|
@@ -715,22 +848,126 @@ export interface SyncBetterAuthUserOptions {
|
|
|
715
848
|
trustEmail?: boolean;
|
|
716
849
|
}
|
|
717
850
|
|
|
851
|
+
// passport-local-mongoose's instance method (v8+ returns a promise).
|
|
852
|
+
type PassportAuthenticate = (
|
|
853
|
+
password: string
|
|
854
|
+
) => Promise<{error?: unknown; user?: unknown}> | undefined;
|
|
855
|
+
|
|
856
|
+
// The parts of a Mongoose model the legacy password check needs beyond `UserModel`.
|
|
857
|
+
interface HydratingUserModel {
|
|
858
|
+
collection?: {
|
|
859
|
+
find: (filter: Record<string, unknown>) => {
|
|
860
|
+
limit: (count: number) => {next: () => Promise<Record<string, unknown> | null>};
|
|
861
|
+
};
|
|
862
|
+
};
|
|
863
|
+
hydrate?: (doc: Record<string, unknown>) => unknown;
|
|
864
|
+
}
|
|
865
|
+
|
|
718
866
|
/**
|
|
719
|
-
*
|
|
720
|
-
*
|
|
867
|
+
* Whether `password` verifies against the passport-local-mongoose hash of a legacy app User.
|
|
868
|
+
* Users without a hash (GitHub-JWT users) and models without the plugin never match.
|
|
869
|
+
*
|
|
870
|
+
* The check runs on a detached copy of the stored document whose `save` does nothing, so
|
|
871
|
+
* passport's `limitAttempts` bookkeeping never counts a Better Auth sign-up against the user's
|
|
872
|
+
* JWT login: a stranger signing up with the victim's email cannot lock the victim out.
|
|
721
873
|
*/
|
|
722
|
-
const
|
|
874
|
+
const legacyPasswordMatches = async (
|
|
875
|
+
userModel: UserModel,
|
|
876
|
+
user: MutableUserDoc,
|
|
877
|
+
password?: string
|
|
878
|
+
): Promise<boolean> => {
|
|
879
|
+
const model = userModel as unknown as HydratingUserModel;
|
|
880
|
+
const id = (user as unknown as {_id?: unknown})._id;
|
|
881
|
+
if (!password || id === undefined || !model.collection || !model.hydrate) {
|
|
882
|
+
return false;
|
|
883
|
+
}
|
|
884
|
+
try {
|
|
885
|
+
// The raw driver read includes the `select: false` hash and salt fields.
|
|
886
|
+
const stored = await model.collection.find({_id: id}).limit(1).next();
|
|
887
|
+
if (!stored) {
|
|
888
|
+
return false;
|
|
889
|
+
}
|
|
890
|
+
const probe = model.hydrate(stored) as {authenticate?: PassportAuthenticate; save?: unknown};
|
|
891
|
+
if (typeof probe.authenticate !== "function") {
|
|
892
|
+
return false;
|
|
893
|
+
}
|
|
894
|
+
probe.save = async (): Promise<unknown> => probe;
|
|
895
|
+
const result = await probe.authenticate(password);
|
|
896
|
+
return Boolean(result?.user);
|
|
897
|
+
} catch (error) {
|
|
898
|
+
logger.debug(`[better-auth] Legacy password check failed: ${error}`);
|
|
899
|
+
return false;
|
|
900
|
+
}
|
|
901
|
+
};
|
|
902
|
+
|
|
903
|
+
interface AppUserClaim {
|
|
904
|
+
betterAuthId?: string;
|
|
905
|
+
emailVerified: boolean;
|
|
906
|
+
password?: string;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/**
|
|
910
|
+
* Whether a Better Auth user may claim the app User that has its email: the User already
|
|
911
|
+
* carries its id (a concurrent request linked it), the email is verified, or the password
|
|
912
|
+
* verifies against the User's legacy passport hash. Anyone can sign up unverified with someone
|
|
913
|
+
* else's email, so nothing weaker counts.
|
|
914
|
+
*/
|
|
915
|
+
const mayClaimAppUser = async (
|
|
916
|
+
userModel: UserModel,
|
|
917
|
+
user: MutableUserDoc,
|
|
918
|
+
claim: AppUserClaim
|
|
919
|
+
): Promise<boolean> =>
|
|
920
|
+
(claim.betterAuthId !== undefined && user.betterAuthId === claim.betterAuthId) ||
|
|
921
|
+
claim.emailVerified ||
|
|
922
|
+
(await legacyPasswordMatches(userModel, user, claim.password));
|
|
923
|
+
|
|
924
|
+
const verifyEmailRefusal = (): APIError =>
|
|
925
|
+
new APIError({
|
|
926
|
+
code: "verify-email-to-use-account",
|
|
927
|
+
disableExternalErrorTracking: true,
|
|
928
|
+
status: 409,
|
|
929
|
+
title: VERIFY_EMAIL_TO_USE_ACCOUNT,
|
|
930
|
+
});
|
|
931
|
+
|
|
932
|
+
const escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
933
|
+
|
|
934
|
+
/**
|
|
935
|
+
* The app User with this email, ignoring case. Better Auth lowercases emails, while legacy
|
|
936
|
+
* Users may have been stored as typed ("Jane@Example.com"); an exact match would miss them,
|
|
937
|
+
* skip the claim guard, and insert a second User.
|
|
938
|
+
*/
|
|
939
|
+
const findAppUserByEmail = async (
|
|
940
|
+
userModel: UserModel,
|
|
941
|
+
email: string
|
|
942
|
+
): Promise<MutableUserDoc | null> =>
|
|
943
|
+
(await findOneOrNoneFor(userModel, {
|
|
944
|
+
email: {$options: "i", $regex: `^${escapeRegExp(email)}$`},
|
|
945
|
+
} as never)) as unknown as MutableUserDoc | null;
|
|
946
|
+
|
|
947
|
+
/** The stable title for a sign-in whose email matches an app User bound to another account. */
|
|
948
|
+
const EMAIL_BOUND_TO_ANOTHER_ACCOUNT = "An account with this email already exists";
|
|
949
|
+
|
|
950
|
+
/** The Better Auth error code (JSON `code`, OAuth redirect `error`) for the same refusal. */
|
|
951
|
+
const EMAIL_BOUND_ERROR_CODE = "ACCOUNT_ALREADY_EXISTS";
|
|
952
|
+
|
|
953
|
+
/**
|
|
954
|
+
* An email alone does not prove the caller owns an existing app user, and an app user already
|
|
955
|
+
* bound to another Better Auth account is never relinked by email. (Whether the caller may claim
|
|
956
|
+
* an unbound row is `mayClaimAppUser`.)
|
|
957
|
+
*/
|
|
958
|
+
const assertNotBoundToAnotherAccount = (
|
|
723
959
|
userByEmail: MutableUserDoc,
|
|
724
|
-
|
|
960
|
+
betterAuthUserId?: string
|
|
725
961
|
): void => {
|
|
726
|
-
if (
|
|
962
|
+
if (!userByEmail.betterAuthId || userByEmail.betterAuthId === betterAuthUserId) {
|
|
727
963
|
return;
|
|
728
964
|
}
|
|
729
965
|
throw new APIError({
|
|
966
|
+
code: "email-bound-to-another-account",
|
|
730
967
|
detail: "Verify the email address before signing in to the existing account.",
|
|
731
968
|
disableExternalErrorTracking: true,
|
|
732
969
|
status: 409,
|
|
733
|
-
title:
|
|
970
|
+
title: EMAIL_BOUND_TO_ANOTHER_ACCOUNT,
|
|
734
971
|
});
|
|
735
972
|
};
|
|
736
973
|
|
|
@@ -788,17 +1025,26 @@ export const syncBetterAuthUser = async (
|
|
|
788
1025
|
}
|
|
789
1026
|
|
|
790
1027
|
// Check if user exists by email (migration case)
|
|
791
|
-
const userByEmail =
|
|
792
|
-
email: betterAuthUser.email,
|
|
793
|
-
})) as unknown as MutableUserDoc | null;
|
|
1028
|
+
const userByEmail = await findAppUserByEmail(userModel, betterAuthUser.email);
|
|
794
1029
|
if (userByEmail?.betterAuthId === betterAuthUser.id) {
|
|
795
1030
|
// A concurrent first contact created this row between the two lookups.
|
|
796
1031
|
return userByEmail;
|
|
797
1032
|
}
|
|
798
1033
|
if (userByEmail) {
|
|
799
1034
|
if (!options.trustEmail) {
|
|
800
|
-
|
|
801
|
-
|
|
1035
|
+
assertNotBoundToAnotherAccount(userByEmail, betterAuthUser.id);
|
|
1036
|
+
const isEmailVerified = betterAuthUser.emailVerified === true;
|
|
1037
|
+
const mayLink = await mayClaimAppUser(userModel, userByEmail, {
|
|
1038
|
+
betterAuthId: betterAuthUser.id,
|
|
1039
|
+
emailVerified: isEmailVerified,
|
|
1040
|
+
password: options.password,
|
|
1041
|
+
});
|
|
1042
|
+
if (!mayLink) {
|
|
1043
|
+
throw verifyEmailRefusal();
|
|
1044
|
+
}
|
|
1045
|
+
if (isEmailVerified) {
|
|
1046
|
+
await revokeUnprovenLegacyPassword(userModel, userByEmail);
|
|
1047
|
+
}
|
|
802
1048
|
}
|
|
803
1049
|
// Link existing user to Better Auth
|
|
804
1050
|
userByEmail.betterAuthId = betterAuthUser.id;
|
|
@@ -827,9 +1073,12 @@ export const syncBetterAuthUser = async (
|
|
|
827
1073
|
return newUser;
|
|
828
1074
|
} catch (error) {
|
|
829
1075
|
// 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.
|
|
1076
|
+
// resolveBetterAuthAppUser recover from it, so it is not an error worth alerting on. An
|
|
1077
|
+
// unverified email that matches an existing User is an expected refusal.
|
|
831
1078
|
if ((error as {code?: number}).code === 11000) {
|
|
832
1079
|
logger.debug(`Better Auth user was created concurrently: ${error}`);
|
|
1080
|
+
} else if (isVerifyEmailRefusal(error)) {
|
|
1081
|
+
logger.info(`[better-auth] Refused to link unverified Better Auth user ${betterAuthUser.id}`);
|
|
833
1082
|
} else if (isAPIError(error) && error.status === 409) {
|
|
834
1083
|
logger.warn(`Refused to link Better Auth user ${betterAuthUser.id} by email: ${error.title}`);
|
|
835
1084
|
} else {
|
|
@@ -839,6 +1088,180 @@ export const syncBetterAuthUser = async (
|
|
|
839
1088
|
}
|
|
840
1089
|
};
|
|
841
1090
|
|
|
1091
|
+
const isVerifyEmailRefusal = (error: unknown): boolean =>
|
|
1092
|
+
isAPIError(error) && error.status === 409 && error.message === VERIFY_EMAIL_TO_USE_ACCOUNT;
|
|
1093
|
+
|
|
1094
|
+
const isBoundToAnotherAccountRefusal = (error: unknown): boolean =>
|
|
1095
|
+
isAPIError(error) && error.status === 409 && error.message === EMAIL_BOUND_TO_ANOTHER_ACCOUNT;
|
|
1096
|
+
|
|
1097
|
+
// The parts of Better Auth's endpoint context the session hook reads.
|
|
1098
|
+
interface SessionHookContext {
|
|
1099
|
+
body?: unknown;
|
|
1100
|
+
params?: Record<string, string | undefined>;
|
|
1101
|
+
path?: string;
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
const bodyString = (body: unknown, key: string): string | undefined => {
|
|
1105
|
+
if (!body || typeof body !== "object") {
|
|
1106
|
+
return undefined;
|
|
1107
|
+
}
|
|
1108
|
+
const value = (body as Record<string, unknown>)[key];
|
|
1109
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
1110
|
+
};
|
|
1111
|
+
|
|
1112
|
+
// The social or generic OAuth provider a session is being created for, if any.
|
|
1113
|
+
const oauthProviderFromContext = (context: SessionHookContext | null): string | undefined => {
|
|
1114
|
+
const path = context?.path ?? "";
|
|
1115
|
+
if (path.startsWith("/callback/")) {
|
|
1116
|
+
return context?.params?.id;
|
|
1117
|
+
}
|
|
1118
|
+
if (path === "/sign-in/social") {
|
|
1119
|
+
return bodyString(context?.body, "provider");
|
|
1120
|
+
}
|
|
1121
|
+
return undefined;
|
|
1122
|
+
};
|
|
1123
|
+
|
|
1124
|
+
// The plaintext password, only on the email requests that carry one.
|
|
1125
|
+
const passwordFromContext = (context: SessionHookContext | null): string | undefined => {
|
|
1126
|
+
if (context?.path !== "/sign-up/email" && context?.path !== "/sign-in/email") {
|
|
1127
|
+
return undefined;
|
|
1128
|
+
}
|
|
1129
|
+
return bodyString(context.body, "password");
|
|
1130
|
+
};
|
|
1131
|
+
|
|
1132
|
+
interface SessionHookAdapter {
|
|
1133
|
+
internalAdapter: {findUserById: (userId: string) => Promise<BetterAuthUser | null>};
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
const verifyEmailConflict = (): BetterAuthAPIError =>
|
|
1137
|
+
new BetterAuthAPIError("CONFLICT", {
|
|
1138
|
+
code: VERIFY_EMAIL_ERROR_CODE,
|
|
1139
|
+
message: VERIFY_EMAIL_TO_USE_ACCOUNT,
|
|
1140
|
+
});
|
|
1141
|
+
|
|
1142
|
+
const boundToAnotherAccountConflict = (): BetterAuthAPIError =>
|
|
1143
|
+
new BetterAuthAPIError("CONFLICT", {
|
|
1144
|
+
code: EMAIL_BOUND_ERROR_CODE,
|
|
1145
|
+
message: EMAIL_BOUND_TO_ANOTHER_ACCOUNT,
|
|
1146
|
+
});
|
|
1147
|
+
|
|
1148
|
+
// The app User with this email that no Better Auth user has claimed yet (or another one has).
|
|
1149
|
+
const findUnclaimedAppUser = async (
|
|
1150
|
+
userModel: UserModel,
|
|
1151
|
+
email: string,
|
|
1152
|
+
betterAuthId?: string
|
|
1153
|
+
): Promise<MutableUserDoc | null> => {
|
|
1154
|
+
const appUser = await findAppUserByEmail(userModel, email);
|
|
1155
|
+
if (!appUser || (betterAuthId !== undefined && appUser.betterAuthId === betterAuthId)) {
|
|
1156
|
+
return null;
|
|
1157
|
+
}
|
|
1158
|
+
return appUser;
|
|
1159
|
+
};
|
|
1160
|
+
|
|
1161
|
+
/**
|
|
1162
|
+
* The plugin that guards and syncs the app User while the request that proves who the user is
|
|
1163
|
+
* (its password, its provider) is still in hand. Session middleware only sees later requests,
|
|
1164
|
+
* which carry neither.
|
|
1165
|
+
*
|
|
1166
|
+
* - Before a Better Auth user is created: when an app User already has the email, creation is
|
|
1167
|
+
* refused with 409 `VERIFY_EMAIL_TO_USE_ACCOUNT` (an OAuth callback redirects with that
|
|
1168
|
+
* `error`) unless the provider verified the email or the sign-up password verifies against
|
|
1169
|
+
* that User's passport hash. An app User bound to another Better Auth account is always
|
|
1170
|
+
* refused, with 409 `ACCOUNT_ALREADY_EXISTS`. Nothing is left behind (no user, account, or verification mail),
|
|
1171
|
+
* so a later verification cannot hand an attacker's password the victim's User.
|
|
1172
|
+
* - Before a session is created, the app User is synced: the OAuth provider id fills
|
|
1173
|
+
* `oauthProvider`, and on `/sign-up/email` and `/sign-in/email` the plaintext password lets an
|
|
1174
|
+
* unverified user claim a legacy User. A refusal fails the sign-in with the same 409s. A
|
|
1175
|
+
* verified email that links a User whose own email was never verified revokes that User's
|
|
1176
|
+
* legacy password and refresh tokens (see `revokeUnprovenLegacyPassword`).
|
|
1177
|
+
* - A failed link that a password was proving fails the sign-in (500 `APP_USER_LINK_FAILED`), so
|
|
1178
|
+
* no session exists that would be refused on every request. Any other sync failure is logged
|
|
1179
|
+
* and the session proceeds; the session middleware retries the sync on the next request.
|
|
1180
|
+
*/
|
|
1181
|
+
export const createAppUserSyncPlugin = (userModel: UserModel): BetterAuthPlugin => {
|
|
1182
|
+
return {
|
|
1183
|
+
id: "terreno-app-user-sync",
|
|
1184
|
+
init: (authContext) => {
|
|
1185
|
+
const {internalAdapter} = authContext as unknown as SessionHookAdapter;
|
|
1186
|
+
return {
|
|
1187
|
+
options: {
|
|
1188
|
+
databaseHooks: {
|
|
1189
|
+
session: {
|
|
1190
|
+
create: {
|
|
1191
|
+
before: async (session, rawContext): Promise<void> => {
|
|
1192
|
+
const context = rawContext as SessionHookContext | null;
|
|
1193
|
+
const betterAuthUser = await internalAdapter.findUserById(session.userId);
|
|
1194
|
+
if (!betterAuthUser) {
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
1197
|
+
const password = passwordFromContext(context);
|
|
1198
|
+
try {
|
|
1199
|
+
await syncBetterAuthUser(
|
|
1200
|
+
userModel,
|
|
1201
|
+
betterAuthUser,
|
|
1202
|
+
oauthProviderFromContext(context),
|
|
1203
|
+
{password}
|
|
1204
|
+
);
|
|
1205
|
+
} catch (error) {
|
|
1206
|
+
if (isVerifyEmailRefusal(error)) {
|
|
1207
|
+
throw verifyEmailConflict();
|
|
1208
|
+
}
|
|
1209
|
+
if (isBoundToAnotherAccountRefusal(error)) {
|
|
1210
|
+
throw boundToAnotherAccountConflict();
|
|
1211
|
+
}
|
|
1212
|
+
if ((error as {code?: number}).code === 11000) {
|
|
1213
|
+
return;
|
|
1214
|
+
}
|
|
1215
|
+
logger.error(`[better-auth] App user sync on sign-in failed: ${error}`);
|
|
1216
|
+
const isPasswordLink =
|
|
1217
|
+
password !== undefined &&
|
|
1218
|
+
(await findUnclaimedAppUser(
|
|
1219
|
+
userModel,
|
|
1220
|
+
betterAuthUser.email,
|
|
1221
|
+
betterAuthUser.id
|
|
1222
|
+
)) !== null;
|
|
1223
|
+
if (isPasswordLink) {
|
|
1224
|
+
throw new BetterAuthAPIError("INTERNAL_SERVER_ERROR", {
|
|
1225
|
+
code: "APP_USER_LINK_FAILED",
|
|
1226
|
+
message: "Could not link your account. Try again.",
|
|
1227
|
+
});
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
},
|
|
1231
|
+
},
|
|
1232
|
+
},
|
|
1233
|
+
user: {
|
|
1234
|
+
create: {
|
|
1235
|
+
before: async (user, rawContext): Promise<void> => {
|
|
1236
|
+
const email = typeof user.email === "string" ? user.email : "";
|
|
1237
|
+
const appUser = email ? await findUnclaimedAppUser(userModel, email) : null;
|
|
1238
|
+
if (!appUser) {
|
|
1239
|
+
return;
|
|
1240
|
+
}
|
|
1241
|
+
if (appUser.betterAuthId) {
|
|
1242
|
+
logger.info(
|
|
1243
|
+
"[better-auth] Refused a sign-up for an app user bound to another account"
|
|
1244
|
+
);
|
|
1245
|
+
throw boundToAnotherAccountConflict();
|
|
1246
|
+
}
|
|
1247
|
+
const mayClaim = await mayClaimAppUser(userModel, appUser, {
|
|
1248
|
+
emailVerified: user.emailVerified === true,
|
|
1249
|
+
password: passwordFromContext(rawContext as SessionHookContext | null),
|
|
1250
|
+
});
|
|
1251
|
+
if (!mayClaim) {
|
|
1252
|
+
logger.info("[better-auth] Refused a sign-up for an existing app user's email");
|
|
1253
|
+
throw verifyEmailConflict();
|
|
1254
|
+
}
|
|
1255
|
+
},
|
|
1256
|
+
},
|
|
1257
|
+
},
|
|
1258
|
+
},
|
|
1259
|
+
},
|
|
1260
|
+
};
|
|
1261
|
+
},
|
|
1262
|
+
} satisfies BetterAuthPlugin;
|
|
1263
|
+
};
|
|
1264
|
+
|
|
842
1265
|
export interface ResolveBetterAuthAppUserOptions {
|
|
843
1266
|
userModel: UserModel;
|
|
844
1267
|
betterAuthUser: BetterAuthUser;
|
|
@@ -920,17 +1343,13 @@ export const getMongoClientFromMongoose = (): MongoClientLike => {
|
|
|
920
1343
|
};
|
|
921
1344
|
|
|
922
1345
|
/**
|
|
923
|
-
*
|
|
924
|
-
*
|
|
925
|
-
*
|
|
926
|
-
*
|
|
927
|
-
* to create users on first session access.
|
|
1346
|
+
* Kept for compatibility; it does nothing. `createBetterAuth` wires the app User sync itself
|
|
1347
|
+
* when given a `userModel`: the `terreno-app-user-sync` plugin guards Better Auth user creation
|
|
1348
|
+
* and syncs the app User as each session is created (see `createAppUserSyncPlugin`), and
|
|
1349
|
+
* `createBetterAuthSessionMiddleware` retries the sync on later requests.
|
|
928
1350
|
*/
|
|
929
1351
|
export const setupBetterAuthUserSync = (_auth: BetterAuthInstance, _userModel: UserModel): void => {
|
|
930
|
-
|
|
931
|
-
// User sync is handled in createBetterAuthSessionMiddleware when a session is accessed.
|
|
932
|
-
// This function is a placeholder for future versions that may support hooks.
|
|
933
|
-
logger.debug("Better Auth user sync configured (via session middleware)");
|
|
1352
|
+
logger.debug("Better Auth user sync configured (via the terreno-app-user-sync plugin)");
|
|
934
1353
|
};
|
|
935
1354
|
|
|
936
1355
|
/**
|