@terreno/api 57.19.2 → 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 +393 -0
- 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
|
@@ -5,29 +5,93 @@
|
|
|
5
5
|
* A social sign-in ends with a top-level redirect from the API to the web app, so the web app
|
|
6
6
|
* never sees the `set-auth-token` header. When the OAuth callback creates a session and
|
|
7
7
|
* redirects to a configured web origin, this adds a single-use, short-lived token to the
|
|
8
|
-
* redirect's URL fragment
|
|
8
|
+
* redirect's URL fragment (also when oauth-proxy finishes a preview's sign-in, since the preview
|
|
9
|
+
* creates the session on its own completion endpoint), which the web app exchanges for the bearer at
|
|
9
10
|
* `POST {basePath}/one-time-token/verify`. Fragments are not sent to servers or in `Referer`.
|
|
11
|
+
*
|
|
12
|
+
* Linking a provider to a signed-in bearer user works the same way in reverse: the web app
|
|
13
|
+
* mints a single-use link token with its bearer (`POST {basePath}/oauth-handoff/link-intent`),
|
|
14
|
+
* then posts it from a top-level form to `POST {basePath}/oauth-handoff/link-start`, which
|
|
15
|
+
* starts Better Auth's link flow with the state cookie first-party on the API's origin.
|
|
10
16
|
*/
|
|
11
17
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
18
|
exports.createOAuthHandoffPlugins = void 0;
|
|
13
19
|
const api_1 = require("better-auth/api");
|
|
20
|
+
const crypto_1 = require("better-auth/crypto");
|
|
14
21
|
const plugins_1 = require("better-auth/plugins");
|
|
22
|
+
const luxon_1 = require("luxon");
|
|
15
23
|
const zod_1 = require("zod");
|
|
16
24
|
const errors_1 = require("./errors");
|
|
17
25
|
const logger_1 = require("./logger");
|
|
18
|
-
/** Minutes a handoff token stays valid. */
|
|
26
|
+
/** Minutes a handoff token, or a link token, stays valid. */
|
|
19
27
|
const HANDOFF_TOKEN_MINUTES = 3;
|
|
28
|
+
// Link tokens live in Better Auth's verification table under their own namespace, hashed.
|
|
29
|
+
const LINK_INTENT_IDENTIFIER_PREFIX = "terreno-link-intent:";
|
|
30
|
+
const LINK_TOKEN_LENGTH = 32;
|
|
20
31
|
const HANDOFF_FRAGMENT_KEY = "ott";
|
|
21
32
|
const HTTP_STATUS_FOUND = 302;
|
|
33
|
+
// oauth-proxy's deprecated completion path; its current one is `/callback/:id/oauth-proxy`.
|
|
34
|
+
const LEGACY_OAUTH_PROXY_CALLBACK_PATH = "/oauth-proxy-callback";
|
|
35
|
+
// The endpoints that end a social sign-in with a session and a redirect: the provider callback
|
|
36
|
+
// (`/callback/:id`) and, on a preview behind oauth-proxy, the completion the stable deploy sends
|
|
37
|
+
// the browser to (`/callback/:id/oauth-proxy`, or the deprecated `/oauth-proxy-callback`).
|
|
38
|
+
const isSessionCallbackPath = (context) => Boolean(context.path?.startsWith("/callback/") || context.path === LEGACY_OAUTH_PROXY_CALLBACK_PATH);
|
|
22
39
|
// The redirect must name its own scheme and host; anything else is relative to the API.
|
|
23
40
|
const ABSOLUTE_HTTP_URL = /^https?:\/\//i;
|
|
24
|
-
// Better Auth's own limit for `/sign-in/*`, applied to the start
|
|
41
|
+
// Better Auth's own limit for `/sign-in/*`, applied to the start and link endpoints too.
|
|
25
42
|
const START_RATE_LIMIT = { max: 3, window: 10 };
|
|
43
|
+
const RATE_LIMITED_PATHS = new Set([
|
|
44
|
+
"/oauth-handoff/start",
|
|
45
|
+
"/oauth-handoff/link-intent",
|
|
46
|
+
"/oauth-handoff/link-start",
|
|
47
|
+
]);
|
|
26
48
|
const startQuerySchema = zod_1.z.object({
|
|
27
49
|
callbackURL: zod_1.z.string(),
|
|
28
50
|
errorCallbackURL: zod_1.z.string().optional(),
|
|
29
51
|
provider: zod_1.z.string(),
|
|
30
52
|
});
|
|
53
|
+
const linkIntentBodySchema = zod_1.z.object({
|
|
54
|
+
callbackURL: zod_1.z.string(),
|
|
55
|
+
errorCallbackURL: zod_1.z.string().optional(),
|
|
56
|
+
provider: zod_1.z.string().min(1),
|
|
57
|
+
});
|
|
58
|
+
const linkStartBodySchema = zod_1.z.object({ token: zod_1.z.string().min(1) });
|
|
59
|
+
// Request headers a link start does not pass on to linkSocial: the credentials, since it
|
|
60
|
+
// authenticates only with the session its token names, never with whatever cookie the browser
|
|
61
|
+
// holds for the API, and the form body's own framing.
|
|
62
|
+
const DROPPED_LINK_HEADERS = new Set(["authorization", "content-length", "content-type", "cookie"]);
|
|
63
|
+
// Hashes a link token the way oneTimeToken hashes its own: SHA-256, base64url without padding.
|
|
64
|
+
const hashLinkToken = async (token) => {
|
|
65
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
|
|
66
|
+
return Buffer.from(digest).toString("base64url");
|
|
67
|
+
};
|
|
68
|
+
const parseLinkIntent = (value) => {
|
|
69
|
+
try {
|
|
70
|
+
const parsed = JSON.parse(value);
|
|
71
|
+
if (typeof parsed.callbackURL !== "string" ||
|
|
72
|
+
typeof parsed.provider !== "string" ||
|
|
73
|
+
typeof parsed.sessionToken !== "string" ||
|
|
74
|
+
(parsed.errorCallbackURL !== undefined && typeof parsed.errorCallbackURL !== "string")) {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
return parsed;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
// The `error=` code a failed linkSocial call sends back to the web app.
|
|
84
|
+
const linkStartErrorCode = (error) => {
|
|
85
|
+
const statusCode = error.statusCode;
|
|
86
|
+
if (statusCode === 404) {
|
|
87
|
+
return "provider_not_found";
|
|
88
|
+
}
|
|
89
|
+
// The session the token names was revoked or expired after the intent.
|
|
90
|
+
if (statusCode === 401) {
|
|
91
|
+
return "session_expired";
|
|
92
|
+
}
|
|
93
|
+
return "link_failed";
|
|
94
|
+
};
|
|
31
95
|
const invalidWebOrigin = (detail) => new errors_1.APIError({
|
|
32
96
|
detail,
|
|
33
97
|
status: 500,
|
|
@@ -121,7 +185,7 @@ const withHandoffToken = (location, token) => {
|
|
|
121
185
|
* (server-minted only, hashed at rest, no `set-ott` header) and the callback after-hook that
|
|
122
186
|
* puts a token in the redirect fragment for configured web origins.
|
|
123
187
|
*/
|
|
124
|
-
const createOAuthHandoffPlugins = ({ apiOrigin, config, getAuth, }) => {
|
|
188
|
+
const createOAuthHandoffPlugins = ({ apiOrigin, config, getAuth, isLinkingDisabled = false, }) => {
|
|
125
189
|
if (config.webOrigins.length === 0) {
|
|
126
190
|
throw invalidWebOrigin("webOrigins is empty, so no sign-in could receive a token");
|
|
127
191
|
}
|
|
@@ -181,30 +245,51 @@ const createOAuthHandoffPlugins = ({ apiOrigin, config, getAuth, }) => {
|
|
|
181
245
|
}
|
|
182
246
|
headers.delete("set-auth-token");
|
|
183
247
|
};
|
|
248
|
+
// Only a page navigation may start an OAuth flow; an <img> or fetch would overwrite the
|
|
249
|
+
// browser's state cookie for a flow in progress.
|
|
250
|
+
const isPageNavigation = (headers) => {
|
|
251
|
+
const fetchDest = headers?.get("sec-fetch-dest");
|
|
252
|
+
return !fetchDest || fetchDest === "document";
|
|
253
|
+
};
|
|
254
|
+
// The return URLs of a sign-in start: `callbackURL` must be a listed path on a listed web
|
|
255
|
+
// origin, `errorCallbackURL` any path on one, and `trustedOrigins` must allow both. GET skips
|
|
256
|
+
// Better Auth's own origin check, so both lists are enforced here. Returns the refusal message, or null when both URLs pass.
|
|
257
|
+
const returnURLError = (context, callbackURL, errorCallbackURL) => {
|
|
258
|
+
const isTrusted = (url) => context.isTrustedOrigin(url, { allowRelativePaths: false });
|
|
259
|
+
if (!isHandoffTarget(callbackURL) || !isTrusted(callbackURL)) {
|
|
260
|
+
return "callbackURL must be one of oauthHandoff.callbackPaths on a web origin in both oauthHandoff.webOrigins and trustedOrigins";
|
|
261
|
+
}
|
|
262
|
+
// An error page never receives a token, so any path on a listed origin will do.
|
|
263
|
+
if (errorCallbackURL !== undefined &&
|
|
264
|
+
(!isWebOriginURL(errorCallbackURL) || !isTrusted(errorCallbackURL))) {
|
|
265
|
+
return "errorCallbackURL must be on one of oauthHandoff.webOrigins and trustedOrigins";
|
|
266
|
+
}
|
|
267
|
+
return null;
|
|
268
|
+
};
|
|
269
|
+
// The return URLs of a link: both may be any absolute URL on a listed web origin that
|
|
270
|
+
// `trustedOrigins` allows. A link creates no session, so no token ever travels on its return
|
|
271
|
+
// and `callbackPaths` do not apply. Returns the refusal message, or null when both URLs pass.
|
|
272
|
+
const linkReturnURLError = (context, callbackURL, errorCallbackURL) => {
|
|
273
|
+
const isAllowed = (url) => isWebOriginURL(url) && context.isTrustedOrigin(url, { allowRelativePaths: false });
|
|
274
|
+
if (!isAllowed(callbackURL)) {
|
|
275
|
+
return "callbackURL must be on one of oauthHandoff.webOrigins and trustedOrigins";
|
|
276
|
+
}
|
|
277
|
+
if (errorCallbackURL !== undefined && !isAllowed(errorCallbackURL)) {
|
|
278
|
+
return "errorCallbackURL must be on one of oauthHandoff.webOrigins and trustedOrigins";
|
|
279
|
+
}
|
|
280
|
+
return null;
|
|
281
|
+
};
|
|
184
282
|
// The web app navigates the whole page here instead of calling `POST /sign-in/social`
|
|
185
283
|
// with fetch, so the OAuth state cookie is set first-party on the API's origin and comes
|
|
186
284
|
// back on the provider's top-level redirect to the callback.
|
|
187
285
|
const oauthHandoffStart = (0, api_1.createAuthEndpoint)("/oauth-handoff/start", { method: "GET", query: startQuerySchema }, async (ctx) => {
|
|
188
286
|
const { callbackURL, errorCallbackURL, provider } = ctx.query;
|
|
189
|
-
|
|
190
|
-
// browser's state cookie for a flow in progress.
|
|
191
|
-
const fetchDest = ctx.headers?.get("sec-fetch-dest");
|
|
192
|
-
if (fetchDest && fetchDest !== "document") {
|
|
287
|
+
if (!isPageNavigation(ctx.headers)) {
|
|
193
288
|
throw ctx.error("BAD_REQUEST", { message: "Open this URL as a page navigation" });
|
|
194
289
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
throw ctx.error("BAD_REQUEST", {
|
|
199
|
-
message: "callbackURL must be one of oauthHandoff.callbackPaths on a web origin in both oauthHandoff.webOrigins and trustedOrigins",
|
|
200
|
-
});
|
|
201
|
-
}
|
|
202
|
-
// An error page never receives a token, so any path on a listed origin will do.
|
|
203
|
-
if (errorCallbackURL !== undefined &&
|
|
204
|
-
(!isWebOriginURL(errorCallbackURL) || !isTrusted(errorCallbackURL))) {
|
|
205
|
-
throw ctx.error("BAD_REQUEST", {
|
|
206
|
-
message: "errorCallbackURL must be on one of oauthHandoff.webOrigins and trustedOrigins",
|
|
207
|
-
});
|
|
290
|
+
const refusal = returnURLError(ctx.context, callbackURL, errorCallbackURL);
|
|
291
|
+
if (refusal) {
|
|
292
|
+
throw ctx.error("BAD_REQUEST", { message: refusal });
|
|
208
293
|
}
|
|
209
294
|
ctx.setHeader("cache-control", "no-store");
|
|
210
295
|
const auth = getAuth();
|
|
@@ -242,8 +327,121 @@ const createOAuthHandoffPlugins = ({ apiOrigin, config, getAuth, }) => {
|
|
|
242
327
|
}
|
|
243
328
|
throw ctx.redirect(started.response.url);
|
|
244
329
|
});
|
|
330
|
+
// A signed-in client (bearer or cookie) asks to link a provider. The link itself must start
|
|
331
|
+
// from a top-level navigation so the state cookie is first-party on the API's origin, and a
|
|
332
|
+
// bearer cannot ride along on a navigation, so this mints a single-use token that stands for
|
|
333
|
+
// the caller's session and the checked return URLs.
|
|
334
|
+
const oauthHandoffLinkIntent = (0, api_1.createAuthEndpoint)("/oauth-handoff/link-intent", { body: linkIntentBodySchema, method: "POST", use: [api_1.sensitiveSessionMiddleware] }, async (ctx) => {
|
|
335
|
+
if (isLinkingDisabled) {
|
|
336
|
+
throw ctx.error("FORBIDDEN", {
|
|
337
|
+
code: "LINKING_DISABLED",
|
|
338
|
+
message: "Account linking is turned off",
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
const { callbackURL, errorCallbackURL, provider } = ctx.body;
|
|
342
|
+
const refusal = linkReturnURLError(ctx.context, callbackURL, errorCallbackURL);
|
|
343
|
+
if (refusal) {
|
|
344
|
+
throw ctx.error("BAD_REQUEST", { message: refusal });
|
|
345
|
+
}
|
|
346
|
+
const token = (0, crypto_1.generateRandomString)(LINK_TOKEN_LENGTH);
|
|
347
|
+
const intent = {
|
|
348
|
+
callbackURL,
|
|
349
|
+
provider,
|
|
350
|
+
sessionToken: ctx.context.session.session.token,
|
|
351
|
+
...(errorCallbackURL !== undefined ? { errorCallbackURL } : {}),
|
|
352
|
+
};
|
|
353
|
+
await ctx.context.internalAdapter.createVerificationValue({
|
|
354
|
+
expiresAt: luxon_1.DateTime.now().plus({ minutes: HANDOFF_TOKEN_MINUTES }).toJSDate(),
|
|
355
|
+
identifier: `${LINK_INTENT_IDENTIFIER_PREFIX}${await hashLinkToken(token)}`,
|
|
356
|
+
value: JSON.stringify(intent),
|
|
357
|
+
});
|
|
358
|
+
ctx.setHeader("cache-control", "no-store");
|
|
359
|
+
return ctx.json({ startURL: `${ctx.context.baseURL}/oauth-handoff/link-start`, token });
|
|
360
|
+
});
|
|
361
|
+
// The web app submits a hidden form here (a top-level POST navigation), so the token never
|
|
362
|
+
// lands in a URL, history, or access log. The token is used up before anything else happens.
|
|
363
|
+
const oauthHandoffLinkStart = (0, api_1.createAuthEndpoint)("/oauth-handoff/link-start", {
|
|
364
|
+
body: linkStartBodySchema,
|
|
365
|
+
metadata: { allowedMediaTypes: ["application/x-www-form-urlencoded"] },
|
|
366
|
+
method: "POST",
|
|
367
|
+
}, async (ctx) => {
|
|
368
|
+
// Checked before the token is used, so a refused request leaves it for the real one.
|
|
369
|
+
if (!isPageNavigation(ctx.headers)) {
|
|
370
|
+
throw ctx.error("BAD_REQUEST", { message: "Submit the link token as a page navigation" });
|
|
371
|
+
}
|
|
372
|
+
// Browsers send Origin on every form POST. Only the web apps may start a link, so a page
|
|
373
|
+
// elsewhere cannot push a token it holds through a visitor's browser. A missing or `null`
|
|
374
|
+
// Origin is refused too, as Better Auth refuses it for cookie requests.
|
|
375
|
+
const origin = ctx.headers?.get("origin");
|
|
376
|
+
if (!origin || !isWebOriginURL(origin)) {
|
|
377
|
+
throw ctx.error("FORBIDDEN", {
|
|
378
|
+
message: "A link must start from one of oauthHandoff.webOrigins",
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
const consumed = await ctx.context.internalAdapter.consumeVerificationValue(`${LINK_INTENT_IDENTIFIER_PREFIX}${await hashLinkToken(ctx.body.token)}`);
|
|
382
|
+
const intent = consumed ? parseLinkIntent(consumed.value) : null;
|
|
383
|
+
// Without a live token there is no checked URL to send the page to.
|
|
384
|
+
if (!intent) {
|
|
385
|
+
throw ctx.error("BAD_REQUEST", { message: "Invalid or expired link token" });
|
|
386
|
+
}
|
|
387
|
+
const { callbackURL, errorCallbackURL, provider, sessionToken } = intent;
|
|
388
|
+
const refusal = linkReturnURLError(ctx.context, callbackURL, errorCallbackURL);
|
|
389
|
+
if (refusal) {
|
|
390
|
+
throw ctx.error("BAD_REQUEST", { message: refusal });
|
|
391
|
+
}
|
|
392
|
+
ctx.setHeader("cache-control", "no-store");
|
|
393
|
+
// The request's own headers keep hooks working, but never its credentials: the link runs
|
|
394
|
+
// as the session the token names, through the bearer plugin.
|
|
395
|
+
const headers = new Headers();
|
|
396
|
+
ctx.headers?.forEach((value, name) => {
|
|
397
|
+
if (!DROPPED_LINK_HEADERS.has(name.toLowerCase())) {
|
|
398
|
+
headers.set(name, value);
|
|
399
|
+
}
|
|
400
|
+
});
|
|
401
|
+
headers.set("authorization", `Bearer ${sessionToken}`);
|
|
402
|
+
const auth = getAuth();
|
|
403
|
+
let started;
|
|
404
|
+
try {
|
|
405
|
+
// linkSocial checks the session again (a revoked one answers 401), stores the link in the
|
|
406
|
+
// OAuth state, and sets the state cookie.
|
|
407
|
+
started = await auth.api.linkSocialAccount({
|
|
408
|
+
body: {
|
|
409
|
+
callbackURL,
|
|
410
|
+
disableRedirect: true,
|
|
411
|
+
provider,
|
|
412
|
+
...(errorCallbackURL !== undefined ? { errorCallbackURL } : {}),
|
|
413
|
+
},
|
|
414
|
+
headers,
|
|
415
|
+
returnHeaders: true,
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
catch (error) {
|
|
419
|
+
const code = linkStartErrorCode(error);
|
|
420
|
+
logger_1.logger.error("[better-auth] OAuth handoff could not start the link", {
|
|
421
|
+
code,
|
|
422
|
+
errorName: error instanceof Error ? error.name : typeof error,
|
|
423
|
+
});
|
|
424
|
+
const target = new URL(errorCallbackURL ?? callbackURL);
|
|
425
|
+
target.searchParams.set("error", code);
|
|
426
|
+
throw ctx.redirect(target.toString());
|
|
427
|
+
}
|
|
428
|
+
// Only the OAuth state cookie goes to the browser: `state` with Better Auth's database
|
|
429
|
+
// state strategy, `oauth_state` with its cookie strategy. Anything else reading the session
|
|
430
|
+
// set, such as a session cookie or its cache, would sign a bearer client in with a cookie
|
|
431
|
+
// on the API's origin.
|
|
432
|
+
const stateCookieNames = new Set([
|
|
433
|
+
ctx.context.createAuthCookie("state").name,
|
|
434
|
+
ctx.context.createAuthCookie("oauth_state").name,
|
|
435
|
+
]);
|
|
436
|
+
for (const cookie of started.headers.getSetCookie()) {
|
|
437
|
+
if (stateCookieNames.has(cookie.slice(0, cookie.indexOf("=")).trim())) {
|
|
438
|
+
ctx.responseHeaders.append("set-cookie", cookie);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
throw ctx.redirect(started.response.url);
|
|
442
|
+
});
|
|
245
443
|
const handoffPlugin = {
|
|
246
|
-
endpoints: { oauthHandoffStart },
|
|
444
|
+
endpoints: { oauthHandoffLinkIntent, oauthHandoffLinkStart, oauthHandoffStart },
|
|
247
445
|
hooks: {
|
|
248
446
|
after: [
|
|
249
447
|
{
|
|
@@ -270,7 +468,7 @@ const createOAuthHandoffPlugins = ({ apiOrigin, config, getAuth, }) => {
|
|
|
270
468
|
dropSessionFromResponse(headers, ctx.context.authCookies);
|
|
271
469
|
ctx.setHeader("location", withHandoffToken(location, token));
|
|
272
470
|
}),
|
|
273
|
-
matcher:
|
|
471
|
+
matcher: isSessionCallbackPath,
|
|
274
472
|
},
|
|
275
473
|
{
|
|
276
474
|
// Verify is for bearer clients only. It signs the session in with a cookie, which the
|
|
@@ -288,7 +486,7 @@ const createOAuthHandoffPlugins = ({ apiOrigin, config, getAuth, }) => {
|
|
|
288
486
|
rateLimit: [
|
|
289
487
|
{
|
|
290
488
|
...START_RATE_LIMIT,
|
|
291
|
-
pathMatcher: (path) => path
|
|
489
|
+
pathMatcher: (path) => RATE_LIMITED_PATHS.has(path),
|
|
292
490
|
},
|
|
293
491
|
],
|
|
294
492
|
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Set a first password for a signed-in user who has none (they signed up with a social or
|
|
3
|
+
* generic OAuth provider, or a passkey), and keep the app User's JWT password in step with the
|
|
4
|
+
* Better Auth one.
|
|
5
|
+
*
|
|
6
|
+
* Better Auth's own `setPassword` is server-only, so a security screen cannot call it. This
|
|
7
|
+
* plugin serves `POST {basePath}/terreno/set-password` (`{newPassword}`) for the signed-in user:
|
|
8
|
+
* - the session must be fresh (`freshSessionMiddleware`: signed in within Better Auth's
|
|
9
|
+
* `session.freshAge`, a day by default), so a stolen old session cannot add a lasting password,
|
|
10
|
+
* and it is read from the database, not the cookie cache (`sensitiveSessionMiddleware`), so a
|
|
11
|
+
* revoked session cannot either;
|
|
12
|
+
* - it is refused (409 `PASSWORD_ALREADY_SET`) when the user already has a password: changing one
|
|
13
|
+
* goes through `/change-password`, which checks the current password. Two concurrent requests
|
|
14
|
+
* leave one password: the later credential row is removed and its request refused;
|
|
15
|
+
* - the new password follows Better Auth's `minPasswordLength` / `maxPasswordLength`;
|
|
16
|
+
* - with a `userModel`, the app User linked by `betterAuthId` gets the same passport password
|
|
17
|
+
* when it already has one (a dual-enrolled account), so a JWT sign-in with the same email and
|
|
18
|
+
* password keeps working, and its `tokenEpoch` is bumped. A Better Auth only account never
|
|
19
|
+
* gains a legacy password: the JWT `POST /auth/login` has no second factor.
|
|
20
|
+
*
|
|
21
|
+
* `/change-password` (and session revocation) reach the legacy credential through the credential
|
|
22
|
+
* sync plugin in `betterAuthSetup.ts`, which follows the same rule and bumps `tokenEpoch`.
|
|
23
|
+
*
|
|
24
|
+
* The security events plugin records a successful set as `password-set`.
|
|
25
|
+
*/
|
|
26
|
+
import type { BetterAuthPlugin } from "better-auth";
|
|
27
|
+
import { type UserModel } from "./auth";
|
|
28
|
+
/**
|
|
29
|
+
* The Better Auth plugin `createBetterAuth` always adds for `POST {basePath}/terreno/set-password`.
|
|
30
|
+
*/
|
|
31
|
+
export declare const createSetPasswordPlugin: ({ userModel, }?: {
|
|
32
|
+
userModel?: UserModel;
|
|
33
|
+
}) => BetterAuthPlugin;
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Set a first password for a signed-in user who has none (they signed up with a social or
|
|
4
|
+
* generic OAuth provider, or a passkey), and keep the app User's JWT password in step with the
|
|
5
|
+
* Better Auth one.
|
|
6
|
+
*
|
|
7
|
+
* Better Auth's own `setPassword` is server-only, so a security screen cannot call it. This
|
|
8
|
+
* plugin serves `POST {basePath}/terreno/set-password` (`{newPassword}`) for the signed-in user:
|
|
9
|
+
* - the session must be fresh (`freshSessionMiddleware`: signed in within Better Auth's
|
|
10
|
+
* `session.freshAge`, a day by default), so a stolen old session cannot add a lasting password,
|
|
11
|
+
* and it is read from the database, not the cookie cache (`sensitiveSessionMiddleware`), so a
|
|
12
|
+
* revoked session cannot either;
|
|
13
|
+
* - it is refused (409 `PASSWORD_ALREADY_SET`) when the user already has a password: changing one
|
|
14
|
+
* goes through `/change-password`, which checks the current password. Two concurrent requests
|
|
15
|
+
* leave one password: the later credential row is removed and its request refused;
|
|
16
|
+
* - the new password follows Better Auth's `minPasswordLength` / `maxPasswordLength`;
|
|
17
|
+
* - with a `userModel`, the app User linked by `betterAuthId` gets the same passport password
|
|
18
|
+
* when it already has one (a dual-enrolled account), so a JWT sign-in with the same email and
|
|
19
|
+
* password keeps working, and its `tokenEpoch` is bumped. A Better Auth only account never
|
|
20
|
+
* gains a legacy password: the JWT `POST /auth/login` has no second factor.
|
|
21
|
+
*
|
|
22
|
+
* `/change-password` (and session revocation) reach the legacy credential through the credential
|
|
23
|
+
* sync plugin in `betterAuthSetup.ts`, which follows the same rule and bumps `tokenEpoch`.
|
|
24
|
+
*
|
|
25
|
+
* The security events plugin records a successful set as `password-set`.
|
|
26
|
+
*/
|
|
27
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
28
|
+
exports.createSetPasswordPlugin = void 0;
|
|
29
|
+
const api_1 = require("better-auth/api");
|
|
30
|
+
const luxon_1 = require("luxon");
|
|
31
|
+
const zod_1 = require("zod");
|
|
32
|
+
const auth_1 = require("./auth");
|
|
33
|
+
const logger_1 = require("./logger");
|
|
34
|
+
const plugins_1 = require("./plugins");
|
|
35
|
+
/** The path the plugin serves, under Better Auth's `basePath`. */
|
|
36
|
+
const SET_PASSWORD_PATH = "/terreno/set-password";
|
|
37
|
+
const setPasswordBodySchema = zod_1.z.object({
|
|
38
|
+
newPassword: zod_1.z.string().meta({ description: "The password to add to the account" }),
|
|
39
|
+
});
|
|
40
|
+
/**
|
|
41
|
+
* The app User linked to a Better Auth user by `betterAuthId`. There is no email fallback: the
|
|
42
|
+
* app user sync links the User before any session exists, and an email match alone does not
|
|
43
|
+
* prove the session owns that User.
|
|
44
|
+
*/
|
|
45
|
+
const findLinkedAppUser = async (userModel, betterAuthUserId) => (await (0, plugins_1.findOneOrNoneFor)(userModel, {
|
|
46
|
+
betterAuthId: betterAuthUserId,
|
|
47
|
+
}));
|
|
48
|
+
/**
|
|
49
|
+
* Sets the passport-local-mongoose hash of the linked app User to the new password, only when
|
|
50
|
+
* it already has one, so a Better Auth only account does not gain a second way to sign in. Like
|
|
51
|
+
* every server-side password change, replacing it bumps `tokenEpoch`, so JWT refresh tokens
|
|
52
|
+
* issued under the old password stop working. Does nothing when no app User is linked or the
|
|
53
|
+
* model has no passport plugin. Never throws: Better Auth already holds the password, so a
|
|
54
|
+
* failure is logged.
|
|
55
|
+
*/
|
|
56
|
+
const syncPasswordToAppUser = async ({ betterAuthUserId, password, userModel, }) => {
|
|
57
|
+
try {
|
|
58
|
+
const appUser = await findLinkedAppUser(userModel, betterAuthUserId);
|
|
59
|
+
if (!appUser || typeof appUser.setPassword !== "function") {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const hasLegacyPassword = userModel.schema.path("hash") !== undefined &&
|
|
63
|
+
Boolean(await userModel.exists({ _id: appUser._id, hash: { $exists: true, $ne: null } }));
|
|
64
|
+
if (!hasLegacyPassword) {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
await (0, auth_1.setPasswordForUser)(appUser, password);
|
|
68
|
+
if (userModel.schema.path("tokenEpoch") !== undefined) {
|
|
69
|
+
appUser.tokenEpoch = (appUser.tokenEpoch ?? 0) + 1;
|
|
70
|
+
}
|
|
71
|
+
await appUser.save();
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
logger_1.logger.error(`[better-auth] Syncing a new password to the app User failed: ${error}`);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const createdAtOf = (row) => {
|
|
78
|
+
if (!row.createdAt) {
|
|
79
|
+
return 0;
|
|
80
|
+
}
|
|
81
|
+
return typeof row.createdAt === "string"
|
|
82
|
+
? luxon_1.DateTime.fromISO(row.createdAt).toMillis()
|
|
83
|
+
: luxon_1.DateTime.fromJSDate(row.createdAt).toMillis();
|
|
84
|
+
};
|
|
85
|
+
/** The credential row that wins when concurrent requests each created one: the oldest. */
|
|
86
|
+
const firstCredential = (rows) => [...rows]
|
|
87
|
+
.filter((row) => row.providerId === "credential")
|
|
88
|
+
.sort((a, b) => createdAtOf(a) - createdAtOf(b) || String(a.id).localeCompare(String(b.id)))[0];
|
|
89
|
+
/**
|
|
90
|
+
* The Better Auth plugin `createBetterAuth` always adds for `POST {basePath}/terreno/set-password`.
|
|
91
|
+
*/
|
|
92
|
+
const createSetPasswordPlugin = ({ userModel, } = {}) => {
|
|
93
|
+
const terrenoSetPassword = (0, api_1.createAuthEndpoint)(SET_PASSWORD_PATH, {
|
|
94
|
+
body: setPasswordBodySchema,
|
|
95
|
+
method: "POST",
|
|
96
|
+
use: [api_1.sensitiveSessionMiddleware, api_1.freshSessionMiddleware],
|
|
97
|
+
}, async (ctx) => {
|
|
98
|
+
if (ctx.context.options.emailAndPassword?.enabled !== true) {
|
|
99
|
+
throw ctx.error("BAD_REQUEST", {
|
|
100
|
+
code: "EMAIL_PASSWORD_DISABLED",
|
|
101
|
+
message: "Email and password sign-in is turned off",
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
const { newPassword } = ctx.body;
|
|
105
|
+
const { minPasswordLength, maxPasswordLength } = ctx.context.password.config;
|
|
106
|
+
if (newPassword.length < minPasswordLength) {
|
|
107
|
+
throw ctx.error("BAD_REQUEST", {
|
|
108
|
+
code: "PASSWORD_TOO_SHORT",
|
|
109
|
+
message: "Password too short",
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
if (newPassword.length > maxPasswordLength) {
|
|
113
|
+
throw ctx.error("BAD_REQUEST", { code: "PASSWORD_TOO_LONG", message: "Password too long" });
|
|
114
|
+
}
|
|
115
|
+
const sessionUser = ctx.context.session.user;
|
|
116
|
+
const userId = sessionUser.id;
|
|
117
|
+
const alreadySet = () => ctx.error("CONFLICT", {
|
|
118
|
+
code: "PASSWORD_ALREADY_SET",
|
|
119
|
+
message: "User already has a password set",
|
|
120
|
+
});
|
|
121
|
+
const account = await ctx.context.internalAdapter.findCredentialAccount(userId);
|
|
122
|
+
if (account?.password) {
|
|
123
|
+
throw alreadySet();
|
|
124
|
+
}
|
|
125
|
+
const passwordHash = await ctx.context.password.hash(newPassword);
|
|
126
|
+
if (account) {
|
|
127
|
+
// Only fills a row that still has no password, so a concurrent set cannot be overwritten.
|
|
128
|
+
const filled = await ctx.context.adapter.update({
|
|
129
|
+
model: "account",
|
|
130
|
+
update: { password: passwordHash, updatedAt: luxon_1.DateTime.now().toJSDate() },
|
|
131
|
+
where: [
|
|
132
|
+
{ field: "id", value: account.id },
|
|
133
|
+
{ field: "password", value: null },
|
|
134
|
+
],
|
|
135
|
+
});
|
|
136
|
+
if (!filled) {
|
|
137
|
+
throw alreadySet();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
const created = await ctx.context.internalAdapter.linkAccount({
|
|
142
|
+
accountId: userId,
|
|
143
|
+
password: passwordHash,
|
|
144
|
+
providerId: "credential",
|
|
145
|
+
userId,
|
|
146
|
+
});
|
|
147
|
+
// A concurrent request may have created a credential row too; the oldest one stays.
|
|
148
|
+
const rows = (await ctx.context.internalAdapter.findAccounts(userId));
|
|
149
|
+
const winner = firstCredential(rows);
|
|
150
|
+
if (winner && String(winner.id) !== String(created.id)) {
|
|
151
|
+
await ctx.context.internalAdapter.deleteAccount(created.id);
|
|
152
|
+
throw alreadySet();
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (userModel) {
|
|
156
|
+
await syncPasswordToAppUser({ betterAuthUserId: userId, password: newPassword, userModel });
|
|
157
|
+
}
|
|
158
|
+
ctx.setHeader("cache-control", "no-store");
|
|
159
|
+
return ctx.json({ status: true });
|
|
160
|
+
});
|
|
161
|
+
return {
|
|
162
|
+
endpoints: { terrenoSetPassword },
|
|
163
|
+
id: "terreno-set-password",
|
|
164
|
+
};
|
|
165
|
+
};
|
|
166
|
+
exports.createSetPasswordPlugin = createSetPasswordPlugin;
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* This module provides functions to initialize Better Auth with MongoDB,
|
|
5
5
|
* create session middleware, and sync users with the application User model.
|
|
6
6
|
*/
|
|
7
|
-
import { betterAuth } from "better-auth";
|
|
7
|
+
import { type BetterAuthPlugin, betterAuth } from "better-auth";
|
|
8
8
|
import type { Application, NextFunction, Request, Response } from "express";
|
|
9
9
|
import type { Db } from "mongodb";
|
|
10
10
|
import { type UserModel } from "./auth";
|
|
@@ -25,6 +25,11 @@ export interface CreateBetterAuthOptions {
|
|
|
25
25
|
mongoClient: MongoClientLike;
|
|
26
26
|
userModel?: UserModel;
|
|
27
27
|
}
|
|
28
|
+
/**
|
|
29
|
+
* The app page that finishes a Better Auth password reset: `{publicAppUrl}/resetPassword?token=`.
|
|
30
|
+
* The built-in reset mail and the admin sign-in link both point here.
|
|
31
|
+
*/
|
|
32
|
+
export declare const betterAuthResetPasswordUrl: (publicAppUrl: string, token: string) => string;
|
|
28
33
|
export declare const createBetterAuthEmailHooks: (config: BetterAuthConfig) => {
|
|
29
34
|
sendResetPassword: ({ token, user, }: {
|
|
30
35
|
token: string;
|
|
@@ -68,21 +73,38 @@ interface PasswordResetRequestLike {
|
|
|
68
73
|
json: () => Promise<unknown>;
|
|
69
74
|
};
|
|
70
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* The parsed body of the Better Auth endpoint now being served (HTTP or a direct `auth.api`
|
|
78
|
+
* call), or `undefined` outside one. Better Auth reads an HTTP body before its handler runs, so a
|
|
79
|
+
* hook such as `onPasswordReset` can no longer read it from the request.
|
|
80
|
+
*/
|
|
81
|
+
export declare const currentBetterAuthEndpointBody: () => unknown;
|
|
71
82
|
export declare const readPasswordFromBetterAuthResetRequest: (request: PasswordResetRequestLike | undefined) => Promise<string>;
|
|
72
83
|
/**
|
|
73
84
|
* After Better Auth password reset, update the JWT/passport hash and bump
|
|
74
85
|
* `tokenEpoch` so a dual-enrolled account cannot keep the old password or
|
|
75
|
-
* outstanding refresh tokens.
|
|
86
|
+
* outstanding refresh tokens. Only an app User that already has a JWT password gets the new one:
|
|
87
|
+
* `POST /auth/login` has no second factor, so a Better Auth only (social) account must not gain a
|
|
88
|
+
* way to sign in there. Its `tokenEpoch` is still bumped.
|
|
89
|
+
*
|
|
90
|
+
* `capturedPassword` is the new password from the parsed body of the reset endpoint being served
|
|
91
|
+
* (`newPassword`, or `password` for the email-OTP and phone-number resets). Without it the
|
|
92
|
+
* password is read from `request`, which works only while the request body is unread.
|
|
76
93
|
*/
|
|
77
94
|
export declare const applyBetterAuthPasswordResetToJwt: (userModel: UserModel, betterAuthUser: {
|
|
78
95
|
email?: string;
|
|
79
96
|
id?: string;
|
|
80
|
-
}, request: PasswordResetRequestLike | undefined) => Promise<void>;
|
|
97
|
+
}, request: PasswordResetRequestLike | undefined, capturedPassword?: string) => Promise<void>;
|
|
81
98
|
/**
|
|
82
99
|
* Creates Express middleware that extracts the Better Auth session
|
|
83
100
|
* and populates req.user with the application User model.
|
|
84
101
|
*/
|
|
85
102
|
export declare const createBetterAuthSessionMiddleware: (auth: BetterAuthInstance, userModel?: UserModel) => (req: Request, _res: Response, next: NextFunction) => Promise<void>;
|
|
103
|
+
/**
|
|
104
|
+
* The stable title (and Better Auth error message) for a sign-in whose unverified email matches
|
|
105
|
+
* an app User it cannot prove it owns.
|
|
106
|
+
*/
|
|
107
|
+
export declare const VERIFY_EMAIL_TO_USE_ACCOUNT = "Verify your email to use this account";
|
|
86
108
|
/**
|
|
87
109
|
* Syncs a Better Auth user to the application User model.
|
|
88
110
|
* Creates or updates the user as needed.
|
|
@@ -99,6 +121,13 @@ interface MutableUserDoc {
|
|
|
99
121
|
save: () => Promise<unknown>;
|
|
100
122
|
}
|
|
101
123
|
export interface SyncBetterAuthUserOptions {
|
|
124
|
+
/**
|
|
125
|
+
* The plaintext password from the sign-up or sign-in request being served. When an app User
|
|
126
|
+
* with the same email is not linked yet and the Better Auth email is unverified, the user is
|
|
127
|
+
* linked only if this password verifies against that User's passport-local-mongoose hash.
|
|
128
|
+
* Never stored or logged.
|
|
129
|
+
*/
|
|
130
|
+
password?: string;
|
|
102
131
|
/**
|
|
103
132
|
* Link an existing app user by email even when Better Auth has not verified the address or
|
|
104
133
|
* the row is bound to another Better Auth id. Only for operator-run seeds that create the
|
|
@@ -107,6 +136,27 @@ export interface SyncBetterAuthUserOptions {
|
|
|
107
136
|
trustEmail?: boolean;
|
|
108
137
|
}
|
|
109
138
|
export declare const syncBetterAuthUser: (userModel: UserModel, betterAuthUser: BetterAuthUser, oauthProvider?: string, options?: SyncBetterAuthUserOptions) => Promise<MutableUserDoc>;
|
|
139
|
+
/**
|
|
140
|
+
* The plugin that guards and syncs the app User while the request that proves who the user is
|
|
141
|
+
* (its password, its provider) is still in hand. Session middleware only sees later requests,
|
|
142
|
+
* which carry neither.
|
|
143
|
+
*
|
|
144
|
+
* - Before a Better Auth user is created: when an app User already has the email, creation is
|
|
145
|
+
* refused with 409 `VERIFY_EMAIL_TO_USE_ACCOUNT` (an OAuth callback redirects with that
|
|
146
|
+
* `error`) unless the provider verified the email or the sign-up password verifies against
|
|
147
|
+
* that User's passport hash. An app User bound to another Better Auth account is always
|
|
148
|
+
* refused, with 409 `ACCOUNT_ALREADY_EXISTS`. Nothing is left behind (no user, account, or verification mail),
|
|
149
|
+
* so a later verification cannot hand an attacker's password the victim's User.
|
|
150
|
+
* - Before a session is created, the app User is synced: the OAuth provider id fills
|
|
151
|
+
* `oauthProvider`, and on `/sign-up/email` and `/sign-in/email` the plaintext password lets an
|
|
152
|
+
* unverified user claim a legacy User. A refusal fails the sign-in with the same 409s. A
|
|
153
|
+
* verified email that links a User whose own email was never verified revokes that User's
|
|
154
|
+
* legacy password and refresh tokens (see `revokeUnprovenLegacyPassword`).
|
|
155
|
+
* - A failed link that a password was proving fails the sign-in (500 `APP_USER_LINK_FAILED`), so
|
|
156
|
+
* no session exists that would be refused on every request. Any other sync failure is logged
|
|
157
|
+
* and the session proceeds; the session middleware retries the sync on the next request.
|
|
158
|
+
*/
|
|
159
|
+
export declare const createAppUserSyncPlugin: (userModel: UserModel) => BetterAuthPlugin;
|
|
110
160
|
export interface ResolveBetterAuthAppUserOptions {
|
|
111
161
|
userModel: UserModel;
|
|
112
162
|
betterAuthUser: BetterAuthUser;
|
|
@@ -132,11 +182,10 @@ export declare const mountBetterAuthRoutes: (app: Application, auth: BetterAuthI
|
|
|
132
182
|
*/
|
|
133
183
|
export declare const getMongoClientFromMongoose: () => MongoClientLike;
|
|
134
184
|
/**
|
|
135
|
-
*
|
|
136
|
-
*
|
|
137
|
-
*
|
|
138
|
-
*
|
|
139
|
-
* to create users on first session access.
|
|
185
|
+
* Kept for compatibility; it does nothing. `createBetterAuth` wires the app User sync itself
|
|
186
|
+
* when given a `userModel`: the `terreno-app-user-sync` plugin guards Better Auth user creation
|
|
187
|
+
* and syncs the app User as each session is created (see `createAppUserSyncPlugin`), and
|
|
188
|
+
* `createBetterAuthSessionMiddleware` retries the sync on later requests.
|
|
140
189
|
*/
|
|
141
190
|
export declare const setupBetterAuthUserSync: (_auth: BetterAuthInstance, _userModel: UserModel) => void;
|
|
142
191
|
/**
|