@lowdefy/api 6.1.0 → 7.0.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/dist/context/applySystemTrust.js +45 -0
- package/dist/context/createApiContext.js +18 -3
- package/dist/context/createAuthorizeOutcome.js +91 -0
- package/dist/context/createBoundSystemContext.js +33 -0
- package/dist/context/createEvaluateOperators.js +8 -3
- package/dist/context/createRequestSignal.js +47 -0
- package/dist/context/createSystemContext.js +80 -0
- package/dist/context/getCanonicalUrl.js +27 -0
- package/dist/context/isSameOriginRequest.js +85 -0
- package/dist/context/isWebSocketOriginAllowed.js +63 -0
- package/dist/context/normalizeInjectedCaller.js +58 -0
- package/dist/context/parseRequestBody.js +32 -0
- package/dist/context/readMemberships.js +71 -0
- package/dist/context/resolveAuthentication.js +758 -0
- package/dist/context/resolveStrategyCaller.js +7 -3
- package/dist/csp/addNonceToElements.js +23 -0
- package/dist/csp/createContentSecurityPolicy.js +45 -0
- package/dist/csp/getWebSocketSources.js +36 -0
- package/dist/email/renderAuthEmail.js +99 -0
- package/dist/index.js +21 -5
- package/dist/response/formatErrorForAgent.js +35 -0
- package/dist/response/redactResponse.js +8 -1
- package/dist/routes/agent/authorizeAgent.js +17 -5
- package/dist/routes/agent/callAgent.js +12 -2
- package/dist/routes/agent/collectChatFiles.js +39 -0
- package/dist/routes/agent/prepareAgent.js +23 -4
- package/dist/routes/auth/buildAdminPlugin.js +33 -0
- package/dist/routes/auth/buildCaptchaPlugin.js +61 -0
- package/dist/routes/auth/buildMcpTokenPlugin.js +77 -0
- package/dist/routes/auth/buildOauthPostLogin.js +73 -0
- package/dist/routes/auth/buildPhoneNumberPlugin.js +57 -0
- package/dist/routes/auth/buildProviders.js +61 -0
- package/dist/routes/auth/createAsMetadataHandler.js +27 -0
- package/dist/routes/auth/createAuthLogger.js +31 -0
- package/dist/routes/auth/createMcpAccessTokenClaims.js +52 -0
- package/dist/routes/auth/createOnAPIError.js +41 -0
- package/dist/routes/auth/createSendEmail.js +54 -0
- package/dist/routes/auth/ensureMcpTokenIndexes.js +48 -0
- package/dist/routes/auth/getAuthEnforcement.js +41 -0
- package/dist/routes/auth/getBetterAuth.js +107 -0
- package/dist/routes/auth/getBetterAuthConfig.js +767 -0
- package/dist/routes/auth/handleAuthRequest.js +43 -0
- package/dist/routes/auth/hooks/authHookPoints.js +204 -0
- package/dist/routes/auth/hooks/buildEngineHooks.js +68 -0
- package/dist/routes/auth/hooks/buildHooks.js +112 -0
- package/dist/routes/auth/{callbacks/addUserFieldsToSession.js → hooks/composeAfterSlot.js} +11 -13
- package/dist/routes/auth/hooks/composeBeforeSlot.js +41 -0
- package/dist/routes/auth/hooks/createHookDispatch.js +59 -0
- package/dist/routes/auth/hooks/createUserAfterHook.js +36 -0
- package/dist/routes/auth/hooks/createUserBeforeHook.js +50 -0
- package/dist/routes/auth/hooks/findHookUser.js +27 -0
- package/dist/routes/auth/modelNames.js +30 -0
- package/dist/routes/auth/organizations/OrganizationKeyError.js +28 -0
- package/dist/routes/auth/organizations/authorizeRole.js +27 -0
- package/dist/routes/auth/organizations/buildOrganizationPlugin.js +178 -0
- package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +57 -0
- package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +120 -0
- package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +403 -0
- package/dist/routes/auth/organizations/createAdmissionGateHook.js +50 -0
- package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +90 -0
- package/dist/routes/auth/organizations/createAutoJoinHook.js +68 -0
- package/dist/routes/auth/organizations/createEmailSendGate.js +59 -0
- package/dist/routes/auth/organizations/createExpiredInvitationGate.js +76 -0
- package/dist/routes/auth/organizations/ensureAuthIndexes.js +122 -0
- package/dist/routes/auth/organizations/ensureOrganization.js +132 -0
- package/dist/routes/auth/organizations/findPendingInvitation.js +43 -0
- package/dist/routes/auth/organizations/getHookRequestHeaders.js +24 -0
- package/dist/routes/auth/organizations/getOrganizationBinding.js +65 -0
- package/dist/routes/auth/organizations/isEmailAdmitted.js +89 -0
- package/dist/routes/auth/organizations/organizationAccessControl.js +94 -0
- package/dist/routes/auth/organizations/resolvePinnedOrganization.js +62 -0
- package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +145 -0
- package/dist/routes/auth/requestHooks/buildRequestHooks.js +288 -0
- package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +43 -0
- package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +59 -0
- package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +47 -0
- package/dist/routes/auth/requestHooks/redirectToChallenge.js +79 -0
- package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +31 -0
- package/dist/routes/auth/resolveCookiePrefix.js +30 -0
- package/dist/routes/auth/sanitizeSessionResponse.js +27 -0
- package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
- package/dist/routes/connections/checkUnwalledReach.js +37 -0
- package/dist/routes/connections/getConnectionConfig.js +6 -1
- package/dist/routes/connections/resolveTenantPreflight.js +226 -0
- package/dist/routes/connections/resolveUnwalledReach.js +144 -0
- package/dist/routes/endpoints/acceptDetachedEndpoint.js +50 -0
- package/dist/routes/endpoints/authorizeApiEndpoint.js +13 -4
- package/dist/routes/endpoints/callEndpoint.js +22 -7
- package/dist/routes/endpoints/control/controlParallelFor.js +61 -22
- package/dist/routes/endpoints/control/controlReject.js +23 -1
- package/dist/routes/endpoints/control/controlReturn.js +29 -1
- package/dist/routes/endpoints/control/controlThrow.js +3 -2
- package/dist/routes/endpoints/control/controlTry.js +10 -1
- package/dist/routes/endpoints/control/controlWhile.js +55 -0
- package/dist/routes/endpoints/control/handleControl.js +3 -1
- package/dist/routes/endpoints/createWebhookAnswer.js +78 -0
- package/dist/routes/endpoints/evaluateRoutineOperators.js +2 -1
- package/dist/routes/endpoints/forwardScheduledEndpoint.js +3 -2
- package/dist/routes/endpoints/getEndpointConfig.js +18 -8
- package/dist/routes/endpoints/getSchemaValidator.js +39 -0
- package/dist/routes/endpoints/handleAgentCall.js +21 -2
- package/dist/routes/endpoints/handleAuthStep.js +214 -0
- package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
- package/dist/routes/endpoints/handleEndpointCall.js +43 -6
- package/dist/routes/endpoints/handleRenderNotification.js +14 -4
- package/dist/routes/endpoints/handleRequest.js +12 -1
- package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
- package/dist/routes/endpoints/handleValidateSchema.js +13 -15
- package/dist/routes/endpoints/invokeEndpoint.js +26 -3
- package/dist/routes/endpoints/operatorScope.js +2 -1
- package/dist/routes/{auth/callbacks/createCallbackPlugins.js → endpoints/parseWebhookBody.js} +10 -6
- package/dist/routes/endpoints/resolveCallBinding.js +91 -0
- package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
- package/dist/routes/endpoints/runDetachedEndpoint.js +63 -18
- package/dist/routes/endpoints/runRoutine.js +64 -5
- package/dist/routes/endpoints/runScheduledEndpoint.js +18 -11
- package/dist/routes/endpoints/runWebhookEndpoint.js +69 -23
- package/dist/routes/endpoints/runWebhookVerify.js +129 -0
- package/dist/routes/endpoints/scheduleBackground.js +10 -0
- package/dist/routes/endpoints/test/runTest.js +31 -9
- package/dist/routes/endpoints/validatePayload.js +144 -0
- package/dist/routes/log/logClientError.js +7 -4
- package/dist/routes/mcp/createMcpServer.js +143 -82
- package/dist/routes/mcp/getMcpJwks.js +93 -0
- package/dist/routes/mcp/getMcpResourceBinding.js +41 -0
- package/dist/routes/mcp/getMcpUri.js +69 -0
- package/dist/routes/mcp/oauthResourceLifecycle.js +122 -0
- package/dist/routes/mcp/runAfterToolCall.js +50 -0
- package/dist/routes/notifications/resolveNotificationLinks.js +39 -11
- package/dist/routes/page/dynamic/checkDynamicContent.js +81 -0
- package/dist/routes/page/dynamic/checkLiteralContent.js +242 -0
- package/dist/routes/page/dynamic/createContentError.js +34 -0
- package/dist/routes/page/dynamic/flagIconsOutsidePage.js +39 -0
- package/dist/routes/page/dynamic/flagTypesOutsidePage.js +44 -0
- package/dist/routes/page/dynamic/getPropertiesSchemaErrors.js +35 -0
- package/dist/routes/page/dynamic/loadDynamicArtifacts.js +52 -0
- package/dist/routes/page/dynamic/policy/checkAction.js +204 -0
- package/dist/routes/page/dynamic/policy/checkEvents.js +163 -0
- package/dist/routes/page/dynamic/policy/checkPolicy.js +313 -0
- package/dist/routes/page/dynamic/policy/checkValue.js +214 -0
- package/dist/routes/page/dynamic/policy/collectUrlKinds.js +117 -0
- package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +54 -0
- package/dist/routes/page/dynamic/policy/findSerializerKeys.js +50 -0
- package/dist/routes/page/dynamic/policy/isAllowedUrl.js +53 -0
- package/dist/routes/{auth/createAdapter.js → page/dynamic/policy/isUnderState.js} +5 -9
- package/dist/routes/page/dynamic/policy/normalizeUrlText.js +25 -0
- package/dist/routes/page/dynamic/resolveDynamicContent.js +89 -37
- package/dist/routes/page/dynamic/unescapeOperators.js +21 -4
- package/dist/routes/page/dynamic/validateFragment.js +17 -58
- package/dist/routes/page/getPageConfig.js +76 -6
- package/dist/routes/request/authorizeRequest.js +21 -6
- package/dist/routes/request/callRequest.js +22 -10
- package/dist/routes/request/callRequestResolver.js +49 -6
- package/dist/routes/request/checkConnectionRead.js +1 -1
- package/dist/routes/request/checkConnectionWrite.js +1 -1
- package/dist/routes/request/createWalledResolver.js +75 -0
- package/dist/routes/request/getRequestConfig.js +19 -3
- package/dist/routes/request/maskCredentialProperties.js +34 -0
- package/dist/routes/request/resolveTenancy.js +223 -0
- package/dist/routes/request/validateSchemas.js +7 -6
- package/dist/routes/{auth/events/createEventPlugins.js → rootConfig/getAppEvents.js} +7 -6
- package/dist/routes/rootConfig/getHomeAndMenus.js +23 -16
- package/dist/routes/{auth/events/createSessionEvent.js → rootConfig/getPagePaths.js} +16 -18
- package/dist/routes/rootConfig/getRootConfig.js +9 -3
- package/dist/routes/rootConfig/menus/filterMenuList.js +5 -2
- package/dist/routes/websocket/authorizeWebsocket.js +19 -4
- package/dist/routes/websocket/createChannelRegistry.js +20 -9
- package/dist/routes/websocket/createWebSocketConnection.js +150 -28
- package/dist/routes/websocket/getCallerFingerprint.js +31 -0
- package/dist/routes/websocket/prepareChannel.js +29 -1
- package/dist/routes/websocket/resolveWebsocketCaller.js +40 -0
- package/dist/test/testContext.js +13 -10
- package/package.json +28 -12
- package/dist/context/createAuthorize.js +0 -45
- package/dist/routes/auth/callbacks/addUserFieldsToToken.js +0 -30
- package/dist/routes/auth/callbacks/createCallbacks.js +0 -46
- package/dist/routes/auth/callbacks/createJWTCallback.js +0 -77
- package/dist/routes/auth/callbacks/createRedirectCallback.js +0 -41
- package/dist/routes/auth/callbacks/createSessionCallback.js +0 -81
- package/dist/routes/auth/callbacks/createSignInCallback.js +0 -40
- package/dist/routes/auth/callbacks/validateSessionRoles.js +0 -33
- package/dist/routes/auth/createLogger.js +0 -35
- package/dist/routes/auth/createPrefixedCookies.js +0 -52
- package/dist/routes/auth/createProviders.js +0 -25
- package/dist/routes/auth/defaultAuthUrl.js +0 -31
- package/dist/routes/auth/events/createCreateUserEvent.js +0 -41
- package/dist/routes/auth/events/createEvents.js +0 -56
- package/dist/routes/auth/events/createLinkAccountEvent.js +0 -43
- package/dist/routes/auth/events/createSignInEvent.js +0 -46
- package/dist/routes/auth/events/createSignOutEvent.js +0 -43
- package/dist/routes/auth/events/createUpdateUserEvent.js +0 -41
- package/dist/routes/auth/getAuthConfig.js +0 -90
- package/dist/routes/auth/resolveCookies.js +0 -37
- package/dist/routes/log/formatValidationError.js +0 -31
- /package/dist/{routes/notifications → email}/resolveThemeLogo.js +0 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2020-2026 Lowdefy, Inc
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
15
|
+
*/ import { type } from '@lowdefy/helpers';
|
|
16
|
+
import ensureOrganization from './ensureOrganization.js';
|
|
17
|
+
import { getRegisteredOrganization } from './getOrganizationBinding.js';
|
|
18
|
+
import OrganizationKeyError from './OrganizationKeyError.js';
|
|
19
|
+
// Awaited by the request middleware before handlers run. The engine is
|
|
20
|
+
// constructed lazily on the first request, so that same request would
|
|
21
|
+
// otherwise race the startup ensure and read an unresolved pinned org.
|
|
22
|
+
// After the first resolution this awaits an already-settled memoized
|
|
23
|
+
// promise; the retained binding makes it a no-op read. A failed ensure is
|
|
24
|
+
// logged but not rethrown - the binding stays unresolved and the
|
|
25
|
+
// _organization operator / step organizationId defaulting fail with their
|
|
26
|
+
// own clear errors, instead of every request failing in the middleware. A
|
|
27
|
+
// mis-keyed organization row is the one exception; see the catch.
|
|
28
|
+
async function resolvePinnedOrganization({ auth, logger }) {
|
|
29
|
+
if (type.isNone(auth)) {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
const registered = getRegisteredOrganization({
|
|
33
|
+
auth
|
|
34
|
+
});
|
|
35
|
+
if (type.isNone(registered) || registered.policy !== 'pinned' || registered.database !== true || !type.isNone(registered.pinned)) {
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
await ensureOrganization({
|
|
40
|
+
auth,
|
|
41
|
+
logger,
|
|
42
|
+
slug: registered.slug
|
|
43
|
+
});
|
|
44
|
+
} catch (error) {
|
|
45
|
+
// Transient versus configured. A briefly unreachable database must not log
|
|
46
|
+
// the whole deployment out from the middleware, so those failures are
|
|
47
|
+
// warned and retried on the next fire. An organization row keyed by the
|
|
48
|
+
// wrong id is a permanent property of that database that never fixes
|
|
49
|
+
// itself, and swallowing it produces one warn line and then the pinned
|
|
50
|
+
// active-organization invariant refusing every session - the
|
|
51
|
+
// deployment-wide sign-in page the check exists to replace. Failing every
|
|
52
|
+
// request with a named configuration error is the kinder outcome.
|
|
53
|
+
if (error instanceof OrganizationKeyError) {
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
// Retried on the next fire - ensureOrganization does not memoize failures.
|
|
57
|
+
logger.warn({
|
|
58
|
+
err: error
|
|
59
|
+
}, `Failed to ensure the pinned organization "${registered.slug}" for the request.`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
export default resolvePinnedOrganization;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2020-2026 Lowdefy, Inc
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
15
|
+
*/ // A reimplementation of BetterAuth's two-factor plugin's own challenge-begin
|
|
16
|
+
// sequence, because the plugin only runs it from an after-hook whose matcher
|
|
17
|
+
// covers /sign-in/email, /sign-in/username and /sign-in/phone-number
|
|
18
|
+
// (https://github.com/better-auth/better-auth/issues/10322). Every other way
|
|
19
|
+
// into a session - magic link, OAuth, phone OTP - hands an enrolled user a
|
|
20
|
+
// session without ever asking for their second factor. There is no public
|
|
21
|
+
// beginTwoFactorChallenge helper to call, so the sequence is mirrored here.
|
|
22
|
+
//
|
|
23
|
+
// Delete this file, its callers and twoFactorPluginContract.test.js together
|
|
24
|
+
// when upstream either extends the matcher or exports a server-side helper.
|
|
25
|
+
//
|
|
26
|
+
// Everything below mirrors private plugin internals - verification identifier
|
|
27
|
+
// prefixes, cookie names, the attempts record - none of which is on a public
|
|
28
|
+
// export path, so a rename upstream is invisible to the type checker and would
|
|
29
|
+
// silently turn the challenge into a lie about having MFA.
|
|
30
|
+
// twoFactorPluginContract.test.js is the drift detector for that.
|
|
31
|
+
import crypto from 'node:crypto';
|
|
32
|
+
import { deleteSessionCookie, expireCookie } from 'better-auth/cookies';
|
|
33
|
+
import { generateRandomString } from 'better-auth/crypto';
|
|
34
|
+
// Mirrors two-factor/constant.mjs, which no public export path reaches.
|
|
35
|
+
const TWO_FACTOR_COOKIE_NAME = 'two_factor';
|
|
36
|
+
const TRUST_DEVICE_COOKIE_NAME = 'trust_device';
|
|
37
|
+
// The plugin's own defaults, which apply because the engine constructs
|
|
38
|
+
// twoFactor({ issuer, schema }) with no cookie options. Both cookies must be
|
|
39
|
+
// minted on the same terms the plugin's endpoints later read them on.
|
|
40
|
+
const TWO_FACTOR_COOKIE_MAX_AGE = 600;
|
|
41
|
+
const TRUST_DEVICE_MAX_AGE = 2592000;
|
|
42
|
+
// The trust-device cookie holds `${token}!${identifier}`, where the token binds
|
|
43
|
+
// the identifier to the user. @better-auth/utils' createHMAC('SHA-256',
|
|
44
|
+
// 'base64urlnopad') is plain HMAC-SHA256 over the UTF-8 bytes of the secret as
|
|
45
|
+
// a raw key, base64url without padding - so node:crypto reproduces it byte for
|
|
46
|
+
// byte, and the engine avoids taking a dependency on a package that is only
|
|
47
|
+
// reachable from inside better-auth's own node_modules under pnpm.
|
|
48
|
+
function signTrustDeviceToken({ secret, trustIdentifier, userId }) {
|
|
49
|
+
return crypto.createHmac('sha256', secret).update(`${userId}!${trustIdentifier}`, 'utf8').digest('base64url');
|
|
50
|
+
}
|
|
51
|
+
// Upstream compares the cookie's token with ===. A constant-time compare costs
|
|
52
|
+
// nothing here and the engine should not copy a weaker comparison of a
|
|
53
|
+
// secret-derived value than it can write. timingSafeEqual throws on unequal
|
|
54
|
+
// lengths, so length is screened first - a base64url HMAC-SHA256 digest is
|
|
55
|
+
// fixed-length anyway, so an attacker learns nothing from that branch.
|
|
56
|
+
function tokensMatch(candidate, expected) {
|
|
57
|
+
const candidateBytes = Buffer.from(candidate, 'utf8');
|
|
58
|
+
const expectedBytes = Buffer.from(expected, 'utf8');
|
|
59
|
+
if (candidateBytes.length !== expectedBytes.length) {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
return crypto.timingSafeEqual(candidateBytes, expectedBytes);
|
|
63
|
+
}
|
|
64
|
+
// Returns 'trusted' when the trust-device cookie stood in for the second factor
|
|
65
|
+
// - the sign-in stands and the caller must leave the endpoint's own response
|
|
66
|
+
// alone - or 'challenged' when the session was torn down and the challenge
|
|
67
|
+
// records and cookie were minted, in which case the caller performs its exit.
|
|
68
|
+
// trustDeviceMaxAge mirrors the value passed to the twoFactor plugin, so this
|
|
69
|
+
// mirror rotates a honoured trust record on the same terms the plugin's own
|
|
70
|
+
// password-path hook does. At 0 (trustDevice disabled) the rotation is already
|
|
71
|
+
// expired and the re-set cookie is a browser delete, so a pre-existing trust is
|
|
72
|
+
// not re-extended on these non-password paths.
|
|
73
|
+
async function beginTwoFactorChallenge({ ctx, newSession, trustDeviceMaxAge = TRUST_DEVICE_MAX_AGE }) {
|
|
74
|
+
const secret = ctx.context.secret;
|
|
75
|
+
const userId = newSession.user.id;
|
|
76
|
+
// Honour the trust-device cookie before tearing anything down, exactly as the
|
|
77
|
+
// plugin does on the password path: a device the user already stepped up on
|
|
78
|
+
// must not be challenged again just because they arrived by a different route.
|
|
79
|
+
const trustCookieAttrs = ctx.context.createAuthCookie(TRUST_DEVICE_COOKIE_NAME, {
|
|
80
|
+
maxAge: trustDeviceMaxAge
|
|
81
|
+
});
|
|
82
|
+
const trustCookie = await ctx.getSignedCookie(trustCookieAttrs.name, secret);
|
|
83
|
+
if (trustCookie) {
|
|
84
|
+
const [token, trustIdentifier] = trustCookie.split('!');
|
|
85
|
+
if (token && trustIdentifier && tokensMatch(token, signTrustDeviceToken({
|
|
86
|
+
secret,
|
|
87
|
+
trustIdentifier,
|
|
88
|
+
userId
|
|
89
|
+
}))) {
|
|
90
|
+
const record = await ctx.context.internalAdapter.findVerificationValue(trustIdentifier);
|
|
91
|
+
if (record && record.value === userId && record.expiresAt > new Date()) {
|
|
92
|
+
// Single-use: the record is replaced on every use, so a copied cookie
|
|
93
|
+
// stops working as soon as the real device signs in again.
|
|
94
|
+
await ctx.context.internalAdapter.deleteVerificationByIdentifier(trustIdentifier);
|
|
95
|
+
const newTrustIdentifier = `trust-device-${generateRandomString(32)}`;
|
|
96
|
+
const newToken = signTrustDeviceToken({
|
|
97
|
+
secret,
|
|
98
|
+
trustIdentifier: newTrustIdentifier,
|
|
99
|
+
userId
|
|
100
|
+
});
|
|
101
|
+
await ctx.context.internalAdapter.createVerificationValue({
|
|
102
|
+
value: userId,
|
|
103
|
+
identifier: newTrustIdentifier,
|
|
104
|
+
expiresAt: new Date(Date.now() + trustDeviceMaxAge * 1000)
|
|
105
|
+
});
|
|
106
|
+
await ctx.setSignedCookie(trustCookieAttrs.name, `${newToken}!${newTrustIdentifier}`, secret, trustCookieAttrs.attributes);
|
|
107
|
+
return 'trusted';
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
// A cookie that was presented but did not validate is stale or forged
|
|
111
|
+
// either way - clear it so the browser stops replaying it, then challenge.
|
|
112
|
+
expireCookie(ctx, trustCookieAttrs);
|
|
113
|
+
}
|
|
114
|
+
// The sign-in endpoint already minted a session and set ctx.context.newSession.
|
|
115
|
+
// The second factor is still outstanding, so that session must not survive
|
|
116
|
+
// this request. setNewSession(null) is what keeps downstream hooks from
|
|
117
|
+
// acting on a session row that no longer exists.
|
|
118
|
+
deleteSessionCookie(ctx, true);
|
|
119
|
+
await ctx.context.internalAdapter.deleteSession(newSession.session.token);
|
|
120
|
+
ctx.context.setNewSession(null);
|
|
121
|
+
const identifier = `2fa-${generateRandomString(20)}`;
|
|
122
|
+
const expiresAt = new Date(Date.now() + TWO_FACTOR_COOKIE_MAX_AGE * 1000);
|
|
123
|
+
await ctx.context.internalAdapter.createVerificationValue({
|
|
124
|
+
value: userId,
|
|
125
|
+
identifier,
|
|
126
|
+
expiresAt
|
|
127
|
+
});
|
|
128
|
+
// Load-bearing, and the one that gets forgotten: beginAttempt
|
|
129
|
+
// (two-factor/verify-two-factor.mjs) calls consumeVerificationValue on
|
|
130
|
+
// `2fa-attempts-{identifier}` and throws INVALID_TWO_FACTOR_COOKIE when it is
|
|
131
|
+
// absent. Create only the challenge record above and the challenge page
|
|
132
|
+
// rejects every correct code, blaming the cookie - total failure, misleading
|
|
133
|
+
// error.
|
|
134
|
+
await ctx.context.internalAdapter.createVerificationValue({
|
|
135
|
+
value: '0',
|
|
136
|
+
identifier: `2fa-attempts-${identifier}`,
|
|
137
|
+
expiresAt
|
|
138
|
+
});
|
|
139
|
+
const twoFactorCookie = ctx.context.createAuthCookie(TWO_FACTOR_COOKIE_NAME, {
|
|
140
|
+
maxAge: TWO_FACTOR_COOKIE_MAX_AGE
|
|
141
|
+
});
|
|
142
|
+
await ctx.setSignedCookie(twoFactorCookie.name, identifier, secret, twoFactorCookie.attributes);
|
|
143
|
+
return 'challenged';
|
|
144
|
+
}
|
|
145
|
+
export default beginTwoFactorChallenge;
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2020-2026 Lowdefy, Inc
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
15
|
+
*/ import { createAuthMiddleware } from 'better-auth/api';
|
|
16
|
+
import { type } from '@lowdefy/helpers';
|
|
17
|
+
import createAcceptExistingMemberHook from '../organizations/createAcceptExistingMemberHook.js';
|
|
18
|
+
import createEmailSendGate from '../organizations/createEmailSendGate.js';
|
|
19
|
+
import createExpiredInvitationGate from '../organizations/createExpiredInvitationGate.js';
|
|
20
|
+
import createOauthPostLoginHook from './createOauthPostLoginHook.js';
|
|
21
|
+
import createTwoFactorChallengeHook from './createTwoFactorChallengeHook.js';
|
|
22
|
+
import dispatchRequestHooks from './dispatchRequestHooks.js';
|
|
23
|
+
import redirectToChallenge from './redirectToChallenge.js';
|
|
24
|
+
import resolveTwoFactorPageUrl from './resolveTwoFactorPageUrl.js';
|
|
25
|
+
// The only place options.hooks may be constructed. BetterAuth wraps
|
|
26
|
+
// options.hooks.before and options.hooks.after as a single match-all function
|
|
27
|
+
// each - not a list - so a second assignment anywhere would silently clobber
|
|
28
|
+
// every hook assembled here.
|
|
29
|
+
//
|
|
30
|
+
// Both slots are returned unconditionally, so the caller assigns options.hooks
|
|
31
|
+
// once and the "exactly once" rule holds mechanically rather than by
|
|
32
|
+
// convention. An empty registration list is a no-op slot: it returns undefined
|
|
33
|
+
// for every path. Whether a registration is added stays conditional on config,
|
|
34
|
+
// and those conditions live here so there is one place to read what the engine
|
|
35
|
+
// hooks into.
|
|
36
|
+
function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }) {
|
|
37
|
+
const before = [];
|
|
38
|
+
const after = [];
|
|
39
|
+
// The effective trust-device lifetime, mirroring the value passed to the
|
|
40
|
+
// twoFactor plugin in getBetterAuthConfig. trustDevice: false sets it to 0 so
|
|
41
|
+
// beginTwoFactorChallenge - the mirror covering the non-password sign-in paths
|
|
42
|
+
// - rotates any honoured trust record already expired, exactly as the plugin
|
|
43
|
+
// does on the password path. Leaving it at the 30-day default here would let
|
|
44
|
+
// those paths keep re-extending a pre-existing trust the deployment disabled.
|
|
45
|
+
const trustDeviceMaxAge = authConfig.twoFactor?.trustDevice === false ? 0 : 2592000;
|
|
46
|
+
// Accepting an invitation into an organization the caller already belongs
|
|
47
|
+
// to: the route would write a second member row, which the unique index
|
|
48
|
+
// refuses. Registered under both policies - an existing member can hold a
|
|
49
|
+
// pending invitation under either.
|
|
50
|
+
before.push({
|
|
51
|
+
id: 'acceptExistingMember',
|
|
52
|
+
matches: (path)=>path === '/organization/accept-invitation',
|
|
53
|
+
handler: createAcceptExistingMemberHook()
|
|
54
|
+
});
|
|
55
|
+
if (authConfig.magicLink?.enabled === true) {
|
|
56
|
+
before.push({
|
|
57
|
+
id: 'magicLinkSendGate',
|
|
58
|
+
matches: (path)=>path === '/sign-in/magic-link',
|
|
59
|
+
handler: createEmailSendGate({
|
|
60
|
+
getAuth,
|
|
61
|
+
organizations: authConfig.organizations,
|
|
62
|
+
// The magic-link route's own success body.
|
|
63
|
+
successBody: {
|
|
64
|
+
status: true
|
|
65
|
+
}
|
|
66
|
+
})
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
// The one-time-code send is the same class of unauthenticated send as the
|
|
70
|
+
// magic-link one, so it carries the same admission gate. The combined path -
|
|
71
|
+
// a magic-link email that also carries the code - needs no gate of its own:
|
|
72
|
+
// the code is minted inside sendMagicLink, which only runs after the
|
|
73
|
+
// magic-link gate has already admitted the address.
|
|
74
|
+
if (authConfig.emailOTP?.enabled === true) {
|
|
75
|
+
before.push({
|
|
76
|
+
id: 'emailOtpSendGate',
|
|
77
|
+
matches: (path)=>path === '/email-otp/send-verification-otp',
|
|
78
|
+
handler: createEmailSendGate({
|
|
79
|
+
getAuth,
|
|
80
|
+
organizations: authConfig.organizations,
|
|
81
|
+
// The OTP send route's own success body - a different shape from the
|
|
82
|
+
// magic-link route's, and the suppressed response has to match it.
|
|
83
|
+
successBody: {
|
|
84
|
+
success: true
|
|
85
|
+
}
|
|
86
|
+
})
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
// Organizations are always on, so every app can accept invitations: an
|
|
90
|
+
// expired or cancelled one answers INVITATION_EXPIRED instead of BetterAuth's
|
|
91
|
+
// "Invitation not found".
|
|
92
|
+
before.push({
|
|
93
|
+
id: 'expiredInvitationGate',
|
|
94
|
+
matches: (path)=>path === '/organization/accept-invitation',
|
|
95
|
+
handler: createExpiredInvitationGate({
|
|
96
|
+
getAuth
|
|
97
|
+
})
|
|
98
|
+
});
|
|
99
|
+
// The post-login organization choice (buildOauthPostLogin): stamps the
|
|
100
|
+
// request's cached session when /oauth2/continue confirms the choice, so the
|
|
101
|
+
// authorize call it re-enters with does not send the member back to the
|
|
102
|
+
// picker. Registered with the authorization server itself.
|
|
103
|
+
if (!type.isNone(authConfig.oauthProvider)) {
|
|
104
|
+
before.push({
|
|
105
|
+
id: 'oauthPostLogin',
|
|
106
|
+
matches: (path)=>path === '/oauth2/continue',
|
|
107
|
+
handler: createOauthPostLoginHook()
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
const twoFactorPageUrl = resolveTwoFactorPageUrl({
|
|
111
|
+
authConfig,
|
|
112
|
+
basePath,
|
|
113
|
+
baseUrlOrigin
|
|
114
|
+
});
|
|
115
|
+
// https://github.com/better-auth/better-auth/issues/10322 - the two-factor
|
|
116
|
+
// plugin's sign-in matcher covers /sign-in/email, /sign-in/username and
|
|
117
|
+
// /sign-in/phone-number, and nothing else. Of those three only email and
|
|
118
|
+
// phone-number are reachable here, because /sign-in/username needs the
|
|
119
|
+
// username plugin the engine does not register - but the matcher does claim
|
|
120
|
+
// it, so registering a hook for it would double-fire the challenge rather
|
|
121
|
+
// than close a gap. Every other route to a session is uncovered, so an
|
|
122
|
+
// enrolled user walks past their second factor by clicking "email me a
|
|
123
|
+
// link", and so does anyone holding their inbox. No toggle: a magic link is
|
|
124
|
+
// possession-of-inbox, the factor most likely to be compromised in the
|
|
125
|
+
// incident two-factor exists to survive.
|
|
126
|
+
//
|
|
127
|
+
// twoFactorPageUrl is also gated on, so a challenge can never redirect to
|
|
128
|
+
// undefined. Build validation requires the page whenever twoFactor is enabled,
|
|
129
|
+
// which leaves this guard covering direct construction only.
|
|
130
|
+
if (authConfig.twoFactor?.enabled === true && authConfig.magicLink?.enabled === true && type.isString(twoFactorPageUrl)) {
|
|
131
|
+
after.push(createTwoFactorChallengeHook({
|
|
132
|
+
id: 'magicLinkTwoFactorChallenge',
|
|
133
|
+
matches: (path)=>path === '/magic-link/verify',
|
|
134
|
+
trustDeviceMaxAge,
|
|
135
|
+
// The browser is mid-redirect here with nothing to read a JSON flag
|
|
136
|
+
// with, so this exit redirects rather than returning the password
|
|
137
|
+
// path's { twoFactorRedirect: true }.
|
|
138
|
+
exit: (ctx)=>redirectToChallenge({
|
|
139
|
+
baseUrlOrigin,
|
|
140
|
+
ctx,
|
|
141
|
+
twoFactorPageUrl
|
|
142
|
+
})
|
|
143
|
+
}));
|
|
144
|
+
}
|
|
145
|
+
// https://github.com/better-auth/better-auth/issues/10322 - the two-factor
|
|
146
|
+
// plugin's sign-in matcher does not cover the OAuth callback, so an enrolled
|
|
147
|
+
// user signing in through any IdP walks past their second factor. Built-in and
|
|
148
|
+
// GenericOAuth providers alike return on /callback/:id, so this one hook covers
|
|
149
|
+
// the enterprise-IdP case the trust declaration exists for.
|
|
150
|
+
//
|
|
151
|
+
// Challenged unless the provider is declared trusted for 2FA. Double-challenging
|
|
152
|
+
// a user who has already cleared Google's own MFA is a functionality loss, and
|
|
153
|
+
// "don't enable two-factor alongside an enterprise IdP" is not advice worth
|
|
154
|
+
// giving: Entra has federated-IdP-MFA trust settings and Okta has the IdP
|
|
155
|
+
// factor, so trust is declared per provider. The trust is declared, not
|
|
156
|
+
// verified - no OAuth claim survives BetterAuth's handling reliably enough to
|
|
157
|
+
// depend on.
|
|
158
|
+
//
|
|
159
|
+
// The trust check belongs in matches, not in the handler: a trusted callback
|
|
160
|
+
// stays on exactly the code path it has today rather than entering the
|
|
161
|
+
// interception and short-circuiting inside it.
|
|
162
|
+
//
|
|
163
|
+
// Registered on twoFactor.enabled alone, not on any provider being configured,
|
|
164
|
+
// so adding a provider later cannot find the hook silently unregistered. The
|
|
165
|
+
// predicate costs nothing on paths that do not match.
|
|
166
|
+
const trustedProviderKeys = authConfig.twoFactor?.mfaTrustedProviderKeys ?? [];
|
|
167
|
+
if (authConfig.twoFactor?.enabled === true && type.isString(twoFactorPageUrl)) {
|
|
168
|
+
after.push(createTwoFactorChallengeHook({
|
|
169
|
+
id: 'oauthTwoFactorChallenge',
|
|
170
|
+
// The provider key is the lowercase type for a built-in provider and
|
|
171
|
+
// the Lowdefy provider id for a GenericOAuth one, as
|
|
172
|
+
// buildTwoFactorTrustedProviders writes mfaTrustedProviderKeys.
|
|
173
|
+
matches: (path, ctx)=>path === '/callback/:id' && !trustedProviderKeys.includes(ctx.params.id),
|
|
174
|
+
trustDeviceMaxAge,
|
|
175
|
+
// Mid-redirect with no JS caller, exactly like /magic-link/verify, so the
|
|
176
|
+
// same shared exit carries the destination the user asked for. Here that
|
|
177
|
+
// destination came from the OAuth state rather than a query parameter,
|
|
178
|
+
// which is why the exit reads the pending redirect's location instead of
|
|
179
|
+
// ctx.query.callbackURL.
|
|
180
|
+
exit: (ctx)=>redirectToChallenge({
|
|
181
|
+
baseUrlOrigin,
|
|
182
|
+
ctx,
|
|
183
|
+
twoFactorPageUrl
|
|
184
|
+
})
|
|
185
|
+
}));
|
|
186
|
+
}
|
|
187
|
+
// https://github.com/better-auth/better-auth/issues/10322 - POST /sign-in/social
|
|
188
|
+
// with an idToken body verifies the token and mints a session in the request
|
|
189
|
+
// itself (sign-in.mjs signInSocial), with no /callback/:id round trip, and the
|
|
190
|
+
// two-factor plugin's matcher does not cover it. Every provider BetterAuth can
|
|
191
|
+
// verify id tokens for takes this path - built-ins such as Google and Apple,
|
|
192
|
+
// and a GenericOAuth provider configured by discovery - so anyone holding an
|
|
193
|
+
// enrolled user's IdP credentials could mint an id token and skip the second
|
|
194
|
+
// factor. A direct caller can post one; Login passes one through only when an
|
|
195
|
+
// app sets the idToken param.
|
|
196
|
+
//
|
|
197
|
+
// The same trust rule as the callback, on the same provider key, carried in
|
|
198
|
+
// the body here. The redirect branch of /sign-in/social mints no session, so
|
|
199
|
+
// the challenge hook's newSession guard passes it through untouched.
|
|
200
|
+
if (authConfig.twoFactor?.enabled === true) {
|
|
201
|
+
after.push(createTwoFactorChallengeHook({
|
|
202
|
+
id: 'idTokenTwoFactorChallenge',
|
|
203
|
+
matches: (path, ctx)=>path === '/sign-in/social' && !trustedProviderKeys.includes(ctx.body?.provider),
|
|
204
|
+
trustDeviceMaxAge,
|
|
205
|
+
// A JS caller posted the id token, so the password path's JSON shape,
|
|
206
|
+
// as on the phone-number and email-otp paths.
|
|
207
|
+
exit: (ctx)=>ctx.json({
|
|
208
|
+
twoFactorRedirect: true,
|
|
209
|
+
twoFactorMethods: [
|
|
210
|
+
'totp'
|
|
211
|
+
]
|
|
212
|
+
})
|
|
213
|
+
}));
|
|
214
|
+
}
|
|
215
|
+
// https://github.com/better-auth/better-auth/issues/10322 - the two-factor
|
|
216
|
+
// plugin's sign-in matcher does not cover /phone-number/verify, which mints a
|
|
217
|
+
// session (phone-number/routes.mjs createSession then setSessionCookie), so an
|
|
218
|
+
// enrolled user signing in by SMS code walks past their second factor. No
|
|
219
|
+
// toggle: an SMS code is possession-of-SIM, and SIM-swap is the
|
|
220
|
+
// best-documented account-takeover attack of any factor here.
|
|
221
|
+
//
|
|
222
|
+
// No twoFactorPageUrl in the guard, unlike the redirect paths above: this exit
|
|
223
|
+
// hands the destination decision to the client, so the page URL is not read
|
|
224
|
+
// and a hook gated on it would be unregistered for no reason.
|
|
225
|
+
if (authConfig.twoFactor?.enabled === true && authConfig.phoneNumber?.enabled === true) {
|
|
226
|
+
after.push(createTwoFactorChallengeHook({
|
|
227
|
+
id: 'phoneNumberTwoFactorChallenge',
|
|
228
|
+
matches: (path)=>path === '/phone-number/verify',
|
|
229
|
+
trustDeviceMaxAge,
|
|
230
|
+
// The one difference from the magic-link and OAuth exits: this endpoint
|
|
231
|
+
// answers a live JS caller with JSON rather than a redirect, so it
|
|
232
|
+
// reuses the password path's response shape. PhoneNumberVerify navigates
|
|
233
|
+
// to authPages.twoFactor on the flag, so the challenge page still sees a
|
|
234
|
+
// single arrival shape.
|
|
235
|
+
//
|
|
236
|
+
// twoFactorMethods is the literal ['totp'] rather than the plugin's
|
|
237
|
+
// computation of it. The scope here is TOTP plus backup codes and the
|
|
238
|
+
// challenge page offers both unconditionally, so the plugin's
|
|
239
|
+
// twoFactor-table read and its otpOptions.sendOTP branch - which the
|
|
240
|
+
// engine never configures - would cost a query to produce a value
|
|
241
|
+
// nothing branches on.
|
|
242
|
+
exit: (ctx)=>ctx.json({
|
|
243
|
+
twoFactorRedirect: true,
|
|
244
|
+
twoFactorMethods: [
|
|
245
|
+
'totp'
|
|
246
|
+
]
|
|
247
|
+
})
|
|
248
|
+
}));
|
|
249
|
+
}
|
|
250
|
+
// https://github.com/better-auth/better-auth/issues/10322 - the two-factor
|
|
251
|
+
// plugin's sign-in matcher does not cover /sign-in/email-otp, which mints a
|
|
252
|
+
// session (email-otp/routes.mjs createSession then setSessionCookie), so an
|
|
253
|
+
// enrolled user signing in with an emailed code walks past their second
|
|
254
|
+
// factor. No toggle, for the same reason the magic-link path has none: a
|
|
255
|
+
// code emailed to an inbox is possession-of-inbox, the factor most likely to
|
|
256
|
+
// be compromised in the incident two-factor exists to survive.
|
|
257
|
+
//
|
|
258
|
+
// No twoFactorPageUrl in the guard, matching the phone-number path: this exit
|
|
259
|
+
// hands the destination decision to the client, so the page URL is not read.
|
|
260
|
+
if (authConfig.twoFactor?.enabled === true && authConfig.emailOTP?.enabled === true) {
|
|
261
|
+
after.push(createTwoFactorChallengeHook({
|
|
262
|
+
id: 'emailOtpTwoFactorChallenge',
|
|
263
|
+
matches: (path)=>path === '/sign-in/email-otp',
|
|
264
|
+
trustDeviceMaxAge,
|
|
265
|
+
// A live JS caller, so the password path's JSON response shape rather
|
|
266
|
+
// than a redirect - EmailOtpVerify navigates to authPages.twoFactor on
|
|
267
|
+
// the flag, exactly as PhoneNumberVerify does. twoFactorMethods is the
|
|
268
|
+
// literal ['totp'] for the reason given on the phone path.
|
|
269
|
+
exit: (ctx)=>ctx.json({
|
|
270
|
+
twoFactorRedirect: true,
|
|
271
|
+
twoFactorMethods: [
|
|
272
|
+
'totp'
|
|
273
|
+
]
|
|
274
|
+
})
|
|
275
|
+
}));
|
|
276
|
+
}
|
|
277
|
+
return {
|
|
278
|
+
before: createAuthMiddleware(async (ctx)=>dispatchRequestHooks({
|
|
279
|
+
ctx,
|
|
280
|
+
registrations: before
|
|
281
|
+
})),
|
|
282
|
+
after: createAuthMiddleware(async (ctx)=>dispatchRequestHooks({
|
|
283
|
+
ctx,
|
|
284
|
+
registrations: after
|
|
285
|
+
}))
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
export default buildRequestHooks;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2020-2026 Lowdefy, Inc
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
15
|
+
*/ import { getSessionFromCtx } from 'better-auth/api';
|
|
16
|
+
import { OAUTH_POST_LOGIN_CONFIRMED } from '../buildOauthPostLogin.js';
|
|
17
|
+
// The engine-tier request hooks.before on /oauth2/continue. The oauth-provider
|
|
18
|
+
// resumes the authorization inside this very request and asks
|
|
19
|
+
// postLogin.shouldRedirect again, but it stamps "post-login done" (ba_pl) into
|
|
20
|
+
// the signed query only on its consent redirect - never on the post-login one
|
|
21
|
+
// - so without help the picker page would be shown again and the flow would
|
|
22
|
+
// loop. The choice was just posted (body.postLogin === true), so this marks
|
|
23
|
+
// the session object the request caches (getSessionFromCtx memoizes it on
|
|
24
|
+
// ctx.context.session; the endpoint's sessionMiddleware and authorize read
|
|
25
|
+
// that same object). Nothing is written to the database: the marker exists for
|
|
26
|
+
// this request only, which is exactly as long as it is true.
|
|
27
|
+
//
|
|
28
|
+
// A bare handler: the request-hook assembler matches /oauth2/continue and owns
|
|
29
|
+
// the createAuthMiddleware wrapper. Always falls through - the endpoint itself
|
|
30
|
+
// validates the signed query and the session.
|
|
31
|
+
function createOauthPostLoginHook() {
|
|
32
|
+
return async function oauthPostLoginHook(ctx) {
|
|
33
|
+
if (ctx.body?.postLogin !== true) {
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
const session = await getSessionFromCtx(ctx);
|
|
37
|
+
if (session?.session) {
|
|
38
|
+
session.session[OAUTH_POST_LOGIN_CONFIRMED] = true;
|
|
39
|
+
}
|
|
40
|
+
return undefined;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
export default createOauthPostLoginHook;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2020-2026 Lowdefy, Inc
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
15
|
+
*/ import beginTwoFactorChallenge from './beginTwoFactorChallenge.js';
|
|
16
|
+
// Builds an after-hook registration that intercepts a completed sign-in on a
|
|
17
|
+
// path BetterAuth's two-factor plugin does not cover
|
|
18
|
+
// (https://github.com/better-auth/better-auth/issues/10322). Everything except
|
|
19
|
+
// how the interception answers the caller is identical across those paths, so
|
|
20
|
+
// the entry guards and the challenge live here and `exit` supplies the per-path
|
|
21
|
+
// response: it either returns the hook's response body, or throws a redirect,
|
|
22
|
+
// which runAfterHooks turns into the response.
|
|
23
|
+
function createTwoFactorChallengeHook({ id, matches, exit, trustDeviceMaxAge }) {
|
|
24
|
+
return {
|
|
25
|
+
id,
|
|
26
|
+
matches,
|
|
27
|
+
handler: async (ctx)=>{
|
|
28
|
+
const newSession = ctx.context.newSession;
|
|
29
|
+
// No session means no sign-in happened on this request, so there is
|
|
30
|
+
// nothing to challenge. /callback/:id also serves account linking, which
|
|
31
|
+
// attaches an account to an already signed-in user and redirects without
|
|
32
|
+
// minting a session - a null newSession there is the ordinary linking
|
|
33
|
+
// case, and acting on it would tear down a session that was never created.
|
|
34
|
+
if (!newSession) {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
// Only enrolled users can answer a challenge. Without this guard every
|
|
38
|
+
// sign-in on the hooked path lands on the challenge page, including users
|
|
39
|
+
// holding no two-factor row: verify-totp throws TOTP_NOT_ENABLED and no
|
|
40
|
+
// code they can type will ever work, so enabling two-factor would strand
|
|
41
|
+
// the entire unenrolled population - worse than the gap being closed.
|
|
42
|
+
if (!newSession.user?.twoFactorEnabled) {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
const outcome = await beginTwoFactorChallenge({
|
|
46
|
+
ctx,
|
|
47
|
+
newSession,
|
|
48
|
+
trustDeviceMaxAge
|
|
49
|
+
});
|
|
50
|
+
// The trust-device cookie stood in for the second factor; the session is
|
|
51
|
+
// intact, so the endpoint's own response must stand.
|
|
52
|
+
if (outcome === 'trusted') {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
return exit(ctx);
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
export default createTwoFactorChallengeHook;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2020-2026 Lowdefy, Inc
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
15
|
+
*/ import { type } from '@lowdefy/helpers';
|
|
16
|
+
// Runs the registrations claiming ctx.path, in array order. The first result
|
|
17
|
+
// that is not undefined short-circuits and becomes the slot's return value:
|
|
18
|
+
// for a before slot a return with no "context" key becomes the response, for an
|
|
19
|
+
// after slot a returned ctx.json(...) becomes the response body. undefined
|
|
20
|
+
// means fall through - to the next matching registration, and when none
|
|
21
|
+
// answers, to the endpoint itself. Never return null; BetterAuth reads that as
|
|
22
|
+
// a value and would answer with it.
|
|
23
|
+
// Thrown errors are left alone - `throw ctx.redirect(...)` and
|
|
24
|
+
// `throw new APIError(...)` are how a handler diverts the request.
|
|
25
|
+
async function dispatchRequestHooks({ ctx, registrations }) {
|
|
26
|
+
// A createAuthEndpoint.serverOnly endpoint has no path, and
|
|
27
|
+
// dispatchAuthEndpoint sets path: endpoint.path, so an auth.api call to one
|
|
28
|
+
// arrives here with ctx.path undefined - better-auth supports that, and a
|
|
29
|
+
// matcher using path.startsWith would throw out of the hook slot. No
|
|
30
|
+
// registration matches.
|
|
31
|
+
if (!type.isString(ctx.path)) {
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
for (const registration of registrations){
|
|
35
|
+
// ctx.path is the endpoint's route template (/callback/:id), not the
|
|
36
|
+
// request URL, so a matcher that needs a path parameter reads ctx.params.
|
|
37
|
+
if (!registration.matches(ctx.path, ctx)) {
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
const result = await registration.handler(ctx);
|
|
41
|
+
if (result !== undefined) {
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
export default dispatchRequestHooks;
|