@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,767 @@
|
|
|
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 { randomUUID } from 'node:crypto';
|
|
16
|
+
import { customSession, emailOTP, genericOAuth, jwt, magicLink, twoFactor } from 'better-auth/plugins';
|
|
17
|
+
import { cimd } from '@better-auth/cimd';
|
|
18
|
+
import { fetchClientMetadataResource } from '@better-auth/cimd/node';
|
|
19
|
+
import { oauthProvider } from '@better-auth/oauth-provider';
|
|
20
|
+
import { passkey } from '@better-auth/passkey';
|
|
21
|
+
import { ServerParser } from '@lowdefy/operators';
|
|
22
|
+
import { _app, _secret } from '@lowdefy/operators-js/operators/server';
|
|
23
|
+
import { type } from '@lowdefy/helpers';
|
|
24
|
+
import { ConfigError, LowdefyInternalError } from '@lowdefy/errors';
|
|
25
|
+
import getCanonicalUrl from '../../context/getCanonicalUrl.js';
|
|
26
|
+
import buildAdminPlugin from './buildAdminPlugin.js';
|
|
27
|
+
import buildCaptchaPlugin from './buildCaptchaPlugin.js';
|
|
28
|
+
import buildMcpTokenPlugin from './buildMcpTokenPlugin.js';
|
|
29
|
+
import buildHooks from './hooks/buildHooks.js';
|
|
30
|
+
import buildOrganizationPlugin from './organizations/buildOrganizationPlugin.js';
|
|
31
|
+
import buildOauthPostLogin from './buildOauthPostLogin.js';
|
|
32
|
+
import buildPhoneNumberPlugin from './buildPhoneNumberPlugin.js';
|
|
33
|
+
import buildProviders from './buildProviders.js';
|
|
34
|
+
import buildRequestHooks from './requestHooks/buildRequestHooks.js';
|
|
35
|
+
import createAuthLogger from './createAuthLogger.js';
|
|
36
|
+
import createMcpAccessTokenClaims from './createMcpAccessTokenClaims.js';
|
|
37
|
+
import createOnAPIError from './createOnAPIError.js';
|
|
38
|
+
import createSendEmail from './createSendEmail.js';
|
|
39
|
+
import { CLIENT_ADDRESS_HEADER } from './handleAuthRequest.js';
|
|
40
|
+
import modelNames from './modelNames.js';
|
|
41
|
+
import renderAuthEmail from '../../email/renderAuthEmail.js';
|
|
42
|
+
import resolveCookiePrefix from './resolveCookiePrefix.js';
|
|
43
|
+
import sanitizeSessionResponse from './sanitizeSessionResponse.js';
|
|
44
|
+
// Decision 4: under the "pinned" org policy, disable every mounted
|
|
45
|
+
// /organization/* HTTP path EXCEPT /organization/accept-invitation (the
|
|
46
|
+
// invitation flow depends on it and BetterAuth gates it itself). /organization/create
|
|
47
|
+
// is already off via allowUserToCreateOrganization:false. The audited admin steps
|
|
48
|
+
// bypass the router (callPluginEndpoint), so disabling these closes client HTTP
|
|
49
|
+
// access without breaking them. Set on the top-level `options.disabledPaths` (a
|
|
50
|
+
// BetterAuth CORE option, not an org-plugin option): the router's onRequest matches
|
|
51
|
+
// exactly via disabledPaths.includes(normalizedPath), with basePath/`/api/auth`
|
|
52
|
+
// stripped first, so entries must be the exact basePath-stripped `/organization/<segment>`.
|
|
53
|
+
// Verified against the mounted surface of better-auth@1.7.7. Team (`*-team*`) and
|
|
54
|
+
// dynamic-access-control role (`*-role`) endpoints are conditional on
|
|
55
|
+
// teams.enabled / dynamicAccessControl.enabled - neither is set by
|
|
56
|
+
// buildOrganizationPlugin, so they are not mounted and are not listed here.
|
|
57
|
+
const ORG_CLIENT_PATHS_DISABLED_WHEN_PINNED = [
|
|
58
|
+
// Mutations
|
|
59
|
+
'/organization/set-active',
|
|
60
|
+
'/organization/update',
|
|
61
|
+
'/organization/delete',
|
|
62
|
+
'/organization/leave',
|
|
63
|
+
'/organization/update-member-role',
|
|
64
|
+
'/organization/remove-member',
|
|
65
|
+
'/organization/invite-member',
|
|
66
|
+
'/organization/cancel-invitation',
|
|
67
|
+
// Reads
|
|
68
|
+
'/organization/list-members',
|
|
69
|
+
'/organization/get-active-member',
|
|
70
|
+
'/organization/get-active-member-role',
|
|
71
|
+
'/organization/get-full-organization',
|
|
72
|
+
'/organization/get-organization',
|
|
73
|
+
'/organization/list',
|
|
74
|
+
'/organization/get-invitation',
|
|
75
|
+
'/organization/list-invitations',
|
|
76
|
+
'/organization/list-user-invitations',
|
|
77
|
+
'/organization/check-slug',
|
|
78
|
+
'/organization/reject-invitation',
|
|
79
|
+
'/organization/has-permission'
|
|
80
|
+
];
|
|
81
|
+
// The admin plugin's entire mounted HTTP surface is disabled under both org
|
|
82
|
+
// policies. Its checks read the deployment-wide user.role, which nothing in
|
|
83
|
+
// Lowdefy writes, so no browser caller could pass one anyway - this is defence
|
|
84
|
+
// in depth against a future writer, not the load-bearing guard.
|
|
85
|
+
// Disabling costs the admin steps nothing: getPluginEndpoint reaches
|
|
86
|
+
// plugin.endpoints[key] directly, so their calls never travel through the
|
|
87
|
+
// router that consults disabledPaths.
|
|
88
|
+
// Enumerated from the endpoints better-auth@1.7.7's admin plugin mounts. Every
|
|
89
|
+
// path is listed literally - the router matches exactly (see the note on
|
|
90
|
+
// ORG_CLIENT_PATHS_DISABLED_WHEN_PINNED above), so a prefix or wildcard entry
|
|
91
|
+
// would disable nothing.
|
|
92
|
+
const ADMIN_PATHS_DISABLED = [
|
|
93
|
+
'/admin/set-role',
|
|
94
|
+
'/admin/get-user',
|
|
95
|
+
'/admin/create-user',
|
|
96
|
+
'/admin/update-user',
|
|
97
|
+
'/admin/list-users',
|
|
98
|
+
'/admin/list-user-sessions',
|
|
99
|
+
'/admin/unban-user',
|
|
100
|
+
'/admin/ban-user',
|
|
101
|
+
'/admin/impersonate-user',
|
|
102
|
+
'/admin/stop-impersonating',
|
|
103
|
+
'/admin/revoke-user-session',
|
|
104
|
+
'/admin/revoke-user-sessions',
|
|
105
|
+
'/admin/remove-user',
|
|
106
|
+
'/admin/set-user-password',
|
|
107
|
+
'/admin/has-permission'
|
|
108
|
+
];
|
|
109
|
+
// Assembles the BetterAuthOptions object from the auth.json build artifact.
|
|
110
|
+
// Build has validated the config and written all defaults, so this function
|
|
111
|
+
// resolves the _secret operators and maps the Lowdefy surface onto
|
|
112
|
+
// BetterAuth's options - no fallback defaults here.
|
|
113
|
+
// createSystemContext builds a fresh off-request context per hook fire - the
|
|
114
|
+
// bridge a firing hook uses to invoke its InternalApi endpoint.
|
|
115
|
+
// getAuth returns the constructed BetterAuth instance - the engine-tier
|
|
116
|
+
// hooks resolve it lazily at fire time, after construction completes.
|
|
117
|
+
// The scopes the authorization server offers MCP clients, and the vocabulary
|
|
118
|
+
// the per-org protected-resource metadata advertises (RFC 9728
|
|
119
|
+
// scopes_supported) - both read this list so they can never drift apart.
|
|
120
|
+
const MCP_OAUTH_SCOPES = [
|
|
121
|
+
'mcp:read',
|
|
122
|
+
'mcp:write',
|
|
123
|
+
'offline_access'
|
|
124
|
+
];
|
|
125
|
+
// The verify link BetterAuth mints is single-use and is consumed atomically by
|
|
126
|
+
// the first GET (magicLinkVerify -> consumeVerificationValue; allowedAttempts is
|
|
127
|
+
// ignored upstream). Corporate mail security - Defender Safe Links, Proofpoint
|
|
128
|
+
// URL Defense, Mimecast - pre-fetches every link in a delivered message, so that
|
|
129
|
+
// first GET is a scanner and the person clicking lands on INVALID_TOKEN. When the
|
|
130
|
+
// app declares a landing page, the email points there instead: the page is inert
|
|
131
|
+
// to a fetch and only the MagicLinkVerify action on a real click walks to verify.
|
|
132
|
+
//
|
|
133
|
+
// Every query BetterAuth put on the verify URL - token, callbackURL, and the
|
|
134
|
+
// newUserCallbackURL / errorCallbackURL it adds when the caller supplied them -
|
|
135
|
+
// is copied onto the landing URL, because the action reads its defaults back out
|
|
136
|
+
// of the page query. The origin comes from the verify URL rather than
|
|
137
|
+
// baseUrlOrigin: on the zero-config path (no BETTER_AUTH_URL) baseUrlOrigin is
|
|
138
|
+
// undefined while BetterAuth has already derived the request's origin here.
|
|
139
|
+
function buildMagicLinkUrl({ authConfig, config, url }) {
|
|
140
|
+
const landingPage = authConfig.authPages?.magicLink;
|
|
141
|
+
if (!type.isString(landingPage)) {
|
|
142
|
+
return url;
|
|
143
|
+
}
|
|
144
|
+
const verifyUrl = new URL(url);
|
|
145
|
+
const landingUrl = new URL(`${config.basePath ?? ''}${landingPage}`, verifyUrl.origin);
|
|
146
|
+
verifyUrl.searchParams.forEach((value, key)=>{
|
|
147
|
+
landingUrl.searchParams.set(key, value);
|
|
148
|
+
});
|
|
149
|
+
return landingUrl.href;
|
|
150
|
+
}
|
|
151
|
+
// The emailed flows whose links BetterAuth builds from the base URL. Every one
|
|
152
|
+
// needs auth.email; verification mail is always wired with it, since
|
|
153
|
+
// /send-verification-email is public. An invitation carries a link only when
|
|
154
|
+
// the app has an accept page.
|
|
155
|
+
function getEmailLinkFlows({ authConfig }) {
|
|
156
|
+
if (type.isNone(authConfig.email)) {
|
|
157
|
+
return [];
|
|
158
|
+
}
|
|
159
|
+
const flows = [
|
|
160
|
+
'email verification'
|
|
161
|
+
];
|
|
162
|
+
if (authConfig.emailAndPassword?.enabled === true) {
|
|
163
|
+
flows.push('password reset');
|
|
164
|
+
}
|
|
165
|
+
if (authConfig.magicLink?.enabled === true) {
|
|
166
|
+
flows.push('magic link');
|
|
167
|
+
}
|
|
168
|
+
if (type.isString(authConfig.authPages?.acceptInvitation)) {
|
|
169
|
+
flows.push('invitation');
|
|
170
|
+
}
|
|
171
|
+
return flows;
|
|
172
|
+
}
|
|
173
|
+
function getBetterAuthConfig({ appMeta, authJson, config = {}, createSystemContext, dev = false, getAuth, logger, plugins, secrets }) {
|
|
174
|
+
if (type.isNone(getAuth)) {
|
|
175
|
+
throw new LowdefyInternalError('No getAuth accessor was provided to getBetterAuthConfig - the engine-tier membership hooks resolve the BetterAuth instance through it.');
|
|
176
|
+
}
|
|
177
|
+
const operatorsParser = new ServerParser({
|
|
178
|
+
lowdefyApp: appMeta,
|
|
179
|
+
operators: {
|
|
180
|
+
_app,
|
|
181
|
+
_secret
|
|
182
|
+
},
|
|
183
|
+
secrets,
|
|
184
|
+
user: {}
|
|
185
|
+
});
|
|
186
|
+
const { output: authConfig, errors: operatorErrors } = operatorsParser.parse({
|
|
187
|
+
input: authJson,
|
|
188
|
+
location: 'auth',
|
|
189
|
+
payload: {}
|
|
190
|
+
});
|
|
191
|
+
if (operatorErrors.length > 0) {
|
|
192
|
+
// Startup fails on the first error; log the rest so they can all be
|
|
193
|
+
// fixed in one pass instead of one boot per error.
|
|
194
|
+
operatorErrors.slice(1).forEach((error)=>logger.error(error));
|
|
195
|
+
throw operatorErrors[0];
|
|
196
|
+
}
|
|
197
|
+
if (!type.isString(authConfig.secret)) {
|
|
198
|
+
throw new ConfigError('Auth "secret" did not resolve to a string. Check the _secret operator reference and that the secret is set.', {
|
|
199
|
+
received: type.typeOf(authConfig.secret)
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
// Secrets are opaque at build time; strength checks are startup warnings.
|
|
203
|
+
if (authConfig.secret.length < 32) {
|
|
204
|
+
logger.warn('Auth "secret" is shorter than 32 characters. Use a long random value, e.g. `openssl rand -base64 32`.');
|
|
205
|
+
}
|
|
206
|
+
// A strategies-only app configures no database - BetterAuth is constructed
|
|
207
|
+
// without an adapter (its stateless mode, backed by a memory adapter), so
|
|
208
|
+
// getSession runs guard-free and returns null on every request.
|
|
209
|
+
let database;
|
|
210
|
+
if (!type.isNone(authConfig.database)) {
|
|
211
|
+
const adapterPlugin = plugins.adapters[authConfig.database.type];
|
|
212
|
+
if (type.isNone(adapterPlugin)) {
|
|
213
|
+
throw new ConfigError(`Auth database adapter type "${authConfig.database.type}" not found at database "${authConfig.database.id}".`, {
|
|
214
|
+
configKey: authConfig.database['~k']
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
try {
|
|
218
|
+
database = adapterPlugin({
|
|
219
|
+
properties: authConfig.database.properties ?? {}
|
|
220
|
+
});
|
|
221
|
+
} catch (error) {
|
|
222
|
+
// Adapter plugins throw plain errors (missing uri, malformed
|
|
223
|
+
// connection string) - attach the database block's config location.
|
|
224
|
+
throw new ConfigError(`Auth database "${authConfig.database.id}" failed to construct: ${error.message}`, {
|
|
225
|
+
cause: error,
|
|
226
|
+
configKey: authConfig.database['~k']
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const { socialProviders, genericOAuthConfigs } = buildProviders({
|
|
231
|
+
authConfig,
|
|
232
|
+
plugins
|
|
233
|
+
});
|
|
234
|
+
const sendEmail = type.isNone(authConfig.email) ? undefined : createSendEmail({
|
|
235
|
+
connectionId: authConfig.email.connectionId
|
|
236
|
+
});
|
|
237
|
+
// BetterAuth builds password-reset, magic-link and email-verification links,
|
|
238
|
+
// and its trusted origins (the CSRF Origin check and the allowed
|
|
239
|
+
// callbackURL / redirectTo targets), from the base URL. When the deployment's
|
|
240
|
+
// canonical origin is pinned - BETTER_AUTH_URL, else the url of the current
|
|
241
|
+
// environment in config.environments - both are fixed and cannot be steered
|
|
242
|
+
// by a spoofed Host / X-Forwarded-Host header (CWE-640 password-reset
|
|
243
|
+
// poisoning). Without it, baseURL is left unset: BetterAuth then derives the
|
|
244
|
+
// origin from each request, and trusts that one origin only. The dynamic
|
|
245
|
+
// `{ allowedHosts: ['*'] }` form would also derive links per request, but it
|
|
246
|
+
// turns the wildcard into trusted origins, so any site's callbackURL or
|
|
247
|
+
// redirectTo passes the check. The unpinned path takes the link host from the
|
|
248
|
+
// request, so production refuses to start when auth emails links, and warns
|
|
249
|
+
// otherwise. The dev server keeps the request origin: it runs on localhost.
|
|
250
|
+
const canonicalUrl = getCanonicalUrl({
|
|
251
|
+
config
|
|
252
|
+
});
|
|
253
|
+
let baseUrlOrigin;
|
|
254
|
+
if (canonicalUrl) {
|
|
255
|
+
baseUrlOrigin = canonicalUrl;
|
|
256
|
+
} else if (!dev) {
|
|
257
|
+
const emailLinkFlows = getEmailLinkFlows({
|
|
258
|
+
authConfig
|
|
259
|
+
});
|
|
260
|
+
if (emailLinkFlows.length > 0) {
|
|
261
|
+
throw new ConfigError(`Auth base URL is not pinned, and auth emails links (${emailLinkFlows.join(', ')}) that would take their host from the request. Set the BETTER_AUTH_URL environment variable, or the url of the current environment in config.environments, to the app's canonical origin (e.g. https://app.example.com).`, {
|
|
262
|
+
configKey: authConfig.email['~k']
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
logger.warn("Auth base URL is not pinned. Set the url of the current environment in config.environments (or BETTER_AUTH_URL) to the app's canonical origin (e.g. https://app.example.com) so the origins auth trusts do not come from the request's Host header.");
|
|
266
|
+
}
|
|
267
|
+
const options = {
|
|
268
|
+
appName: appMeta?.name ?? 'Lowdefy',
|
|
269
|
+
// Undefined when unpinned - see above. Also used for logo resolution and
|
|
270
|
+
// the invitation accept-URL fallback, which skip the origin when it is
|
|
271
|
+
// unknown.
|
|
272
|
+
baseURL: baseUrlOrigin,
|
|
273
|
+
basePath: `${config.basePath ?? ''}/api/auth`,
|
|
274
|
+
secret: authConfig.secret,
|
|
275
|
+
telemetry: {
|
|
276
|
+
enabled: false
|
|
277
|
+
},
|
|
278
|
+
logger: createAuthLogger({
|
|
279
|
+
logger
|
|
280
|
+
}),
|
|
281
|
+
user: {
|
|
282
|
+
modelName: modelNames.user,
|
|
283
|
+
// Internal additionalFields, deliberately not an app-facing surface:
|
|
284
|
+
// attributes holds admin-set, cross-app authorization inputs;
|
|
285
|
+
// profile is the opaque display-and-app-data bag written by module or
|
|
286
|
+
// app logic (UpdateUserProfile) - the platform never validates,
|
|
287
|
+
// indexes, or reads inside it.
|
|
288
|
+
//
|
|
289
|
+
// contactId is the link to the app's canonical record for the human
|
|
290
|
+
// behind this login. It carries profile's opaque contract, not
|
|
291
|
+
// attributes' - stored, projected onto the caller, and otherwise
|
|
292
|
+
// ignored: never validated, indexed, or read by the platform, and never
|
|
293
|
+
// resolved to whatever it points at. That is module work, and which
|
|
294
|
+
// record the name means is the module's business. A first-class field
|
|
295
|
+
// rather than a key inside profile, because a link to another entity is
|
|
296
|
+
// a different kind of thing from an opaque attribute bag - it belongs
|
|
297
|
+
// with the user's other structural facts.
|
|
298
|
+
additionalFields: {
|
|
299
|
+
attributes: {
|
|
300
|
+
type: 'json',
|
|
301
|
+
required: false,
|
|
302
|
+
input: false
|
|
303
|
+
},
|
|
304
|
+
profile: {
|
|
305
|
+
type: 'json',
|
|
306
|
+
required: false,
|
|
307
|
+
input: false
|
|
308
|
+
},
|
|
309
|
+
contactId: {
|
|
310
|
+
type: 'string',
|
|
311
|
+
required: false,
|
|
312
|
+
input: false
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
},
|
|
316
|
+
verification: {
|
|
317
|
+
modelName: modelNames.verification
|
|
318
|
+
},
|
|
319
|
+
session: {
|
|
320
|
+
modelName: modelNames.session,
|
|
321
|
+
expiresIn: authConfig.session.expiresIn,
|
|
322
|
+
updateAge: authConfig.session.updateAge,
|
|
323
|
+
cookieCache: {
|
|
324
|
+
enabled: authConfig.session.cookieCache.enabled,
|
|
325
|
+
maxAge: authConfig.session.cookieCache.maxAge
|
|
326
|
+
}
|
|
327
|
+
},
|
|
328
|
+
account: {
|
|
329
|
+
modelName: modelNames.account,
|
|
330
|
+
accountLinking: {
|
|
331
|
+
enabled: authConfig.account.accountLinking.enabled,
|
|
332
|
+
trustedProviders: authConfig.account.accountLinking.trustedProviders
|
|
333
|
+
}
|
|
334
|
+
},
|
|
335
|
+
rateLimit: {
|
|
336
|
+
enabled: authConfig.rateLimit.enabled,
|
|
337
|
+
window: authConfig.rateLimit.window,
|
|
338
|
+
max: authConfig.rateLimit.max
|
|
339
|
+
},
|
|
340
|
+
advanced: {
|
|
341
|
+
cookiePrefix: resolveCookiePrefix({
|
|
342
|
+
appMeta,
|
|
343
|
+
dev
|
|
344
|
+
}),
|
|
345
|
+
// The server resolves the client address from the connection and the
|
|
346
|
+
// app's trusted proxies, and handleAuthRequest passes it in this header.
|
|
347
|
+
// BetterAuth reads no other, so X-Forwarded-For sent by a client never
|
|
348
|
+
// picks its rate-limit bucket.
|
|
349
|
+
ipAddress: {
|
|
350
|
+
ipAddressHeaders: [
|
|
351
|
+
CLIENT_ADDRESS_HEADER
|
|
352
|
+
]
|
|
353
|
+
},
|
|
354
|
+
// Decision 7: function-form generateId. The vendored adapter stores a
|
|
355
|
+
// function result verbatim as a plain string (no ObjectId/UUID-binary
|
|
356
|
+
// coercion), so all ids are plain UUID strings that native reads match.
|
|
357
|
+
database: {
|
|
358
|
+
generateId: ()=>randomUUID()
|
|
359
|
+
}
|
|
360
|
+
},
|
|
361
|
+
plugins: []
|
|
362
|
+
};
|
|
363
|
+
if (!type.isNone(database)) {
|
|
364
|
+
options.database = database;
|
|
365
|
+
}
|
|
366
|
+
if (authConfig.session.crossSubDomainCookies.enabled === true) {
|
|
367
|
+
options.advanced.crossSubDomainCookies = {
|
|
368
|
+
enabled: true,
|
|
369
|
+
domain: authConfig.session.crossSubDomainCookies.domain
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
if (authConfig.emailAndPassword?.enabled === true) {
|
|
373
|
+
options.emailAndPassword = {
|
|
374
|
+
enabled: true,
|
|
375
|
+
requireEmailVerification: authConfig.emailAndPassword.requireEmailVerification,
|
|
376
|
+
minPasswordLength: authConfig.emailAndPassword.minPasswordLength,
|
|
377
|
+
disableSignUp: authConfig.emailAndPassword.disableSignUp
|
|
378
|
+
};
|
|
379
|
+
if (sendEmail) {
|
|
380
|
+
options.emailAndPassword.sendResetPassword = async ({ user, url })=>{
|
|
381
|
+
const context = createSystemContext({
|
|
382
|
+
auth: getAuth()
|
|
383
|
+
});
|
|
384
|
+
const { subject, html, text } = await renderAuthEmail({
|
|
385
|
+
flow: 'resetPassword',
|
|
386
|
+
vars: {
|
|
387
|
+
url
|
|
388
|
+
},
|
|
389
|
+
authEmailConfig: authConfig.email,
|
|
390
|
+
baseURL: baseUrlOrigin,
|
|
391
|
+
context
|
|
392
|
+
});
|
|
393
|
+
await sendEmail({
|
|
394
|
+
to: user.email,
|
|
395
|
+
subject,
|
|
396
|
+
html,
|
|
397
|
+
text,
|
|
398
|
+
context
|
|
399
|
+
});
|
|
400
|
+
};
|
|
401
|
+
} else {
|
|
402
|
+
// Password reset is implicit in emailAndPassword, so a missing email
|
|
403
|
+
// config is a startup warning, not a build failure.
|
|
404
|
+
logger.warn('Auth "email" is not configured - password reset emails cannot be sent, so the reset flow is unavailable.');
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
if (sendEmail) {
|
|
408
|
+
options.emailVerification = {
|
|
409
|
+
sendVerificationEmail: async ({ user, url })=>{
|
|
410
|
+
const context = createSystemContext({
|
|
411
|
+
auth: getAuth()
|
|
412
|
+
});
|
|
413
|
+
const { subject, html, text } = await renderAuthEmail({
|
|
414
|
+
flow: 'verifyEmail',
|
|
415
|
+
vars: {
|
|
416
|
+
url
|
|
417
|
+
},
|
|
418
|
+
authEmailConfig: authConfig.email,
|
|
419
|
+
baseURL: baseUrlOrigin,
|
|
420
|
+
context
|
|
421
|
+
});
|
|
422
|
+
await sendEmail({
|
|
423
|
+
to: user.email,
|
|
424
|
+
subject,
|
|
425
|
+
html,
|
|
426
|
+
text,
|
|
427
|
+
context
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
if (Object.keys(socialProviders).length > 0) {
|
|
433
|
+
options.socialProviders = socialProviders;
|
|
434
|
+
}
|
|
435
|
+
const emailOTPEnabled = authConfig.emailOTP?.enabled === true;
|
|
436
|
+
if (authConfig.magicLink?.enabled === true) {
|
|
437
|
+
options.plugins.push(magicLink({
|
|
438
|
+
expiresIn: authConfig.magicLink.expiresIn,
|
|
439
|
+
disableSignUp: authConfig.magicLink.disableSignUp,
|
|
440
|
+
sendMagicLink: async ({ email, url })=>{
|
|
441
|
+
const context = createSystemContext({
|
|
442
|
+
auth: getAuth()
|
|
443
|
+
});
|
|
444
|
+
// One email serves both paths when the code is also configured: mail
|
|
445
|
+
// security that pre-fetches links burns the single-use magic-link
|
|
446
|
+
// token before the person clicks, and the code they type into the tab
|
|
447
|
+
// they started from survives that. createVerificationOTP is the
|
|
448
|
+
// plugin's server-only mint - it stores the sign-in code and returns
|
|
449
|
+
// it, sending nothing - so the code rides on the link email instead of
|
|
450
|
+
// arriving as a second one.
|
|
451
|
+
const otpVars = emailOTPEnabled ? {
|
|
452
|
+
otp: await getAuth().api.createVerificationOTP({
|
|
453
|
+
body: {
|
|
454
|
+
email,
|
|
455
|
+
type: 'sign-in'
|
|
456
|
+
}
|
|
457
|
+
}),
|
|
458
|
+
expiresIn: authConfig.emailOTP.expiresIn
|
|
459
|
+
} : {};
|
|
460
|
+
const { subject, html, text } = await renderAuthEmail({
|
|
461
|
+
flow: 'magicLink',
|
|
462
|
+
vars: {
|
|
463
|
+
url: buildMagicLinkUrl({
|
|
464
|
+
authConfig,
|
|
465
|
+
config,
|
|
466
|
+
url
|
|
467
|
+
}),
|
|
468
|
+
...otpVars
|
|
469
|
+
},
|
|
470
|
+
authEmailConfig: authConfig.email,
|
|
471
|
+
baseURL: baseUrlOrigin,
|
|
472
|
+
context
|
|
473
|
+
});
|
|
474
|
+
await sendEmail({
|
|
475
|
+
to: email,
|
|
476
|
+
subject,
|
|
477
|
+
html,
|
|
478
|
+
text,
|
|
479
|
+
context
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
}));
|
|
483
|
+
}
|
|
484
|
+
// The one-time code sign-in. Only the "sign-in" OTP type is wired: the other
|
|
485
|
+
// types BetterAuth can ask for (email-verification, forget-password,
|
|
486
|
+
// change-email) are reached through endpoints the engine does not mount or
|
|
487
|
+
// document, so a send for one of them is a wiring fault, not a user action.
|
|
488
|
+
if (emailOTPEnabled) {
|
|
489
|
+
options.plugins.push(emailOTP({
|
|
490
|
+
otpLength: authConfig.emailOTP.otpLength,
|
|
491
|
+
expiresIn: authConfig.emailOTP.expiresIn,
|
|
492
|
+
allowedAttempts: authConfig.emailOTP.allowedAttempts,
|
|
493
|
+
disableSignUp: authConfig.emailOTP.disableSignUp,
|
|
494
|
+
sendVerificationOTP: async ({ email, otp, type: otpType })=>{
|
|
495
|
+
if (otpType !== 'sign-in') {
|
|
496
|
+
throw new ConfigError(`Auth "emailOTP" only wires the sign-in code. A "${otpType}" one-time code was requested, and the Lowdefy engine has no email flow for it.`);
|
|
497
|
+
}
|
|
498
|
+
const context = createSystemContext({
|
|
499
|
+
auth: getAuth()
|
|
500
|
+
});
|
|
501
|
+
const { subject, html, text } = await renderAuthEmail({
|
|
502
|
+
flow: 'emailOTP',
|
|
503
|
+
vars: {
|
|
504
|
+
otp,
|
|
505
|
+
expiresIn: authConfig.emailOTP.expiresIn
|
|
506
|
+
},
|
|
507
|
+
authEmailConfig: authConfig.email,
|
|
508
|
+
baseURL: baseUrlOrigin,
|
|
509
|
+
context
|
|
510
|
+
});
|
|
511
|
+
await sendEmail({
|
|
512
|
+
to: email,
|
|
513
|
+
subject,
|
|
514
|
+
html,
|
|
515
|
+
text,
|
|
516
|
+
context
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
}));
|
|
520
|
+
}
|
|
521
|
+
if (genericOAuthConfigs.length > 0) {
|
|
522
|
+
options.plugins.push(genericOAuth({
|
|
523
|
+
config: genericOAuthConfigs
|
|
524
|
+
}));
|
|
525
|
+
}
|
|
526
|
+
if (authConfig.twoFactor?.enabled === true) {
|
|
527
|
+
options.plugins.push(twoFactor({
|
|
528
|
+
allowPasswordless: true,
|
|
529
|
+
issuer: appMeta?.name,
|
|
530
|
+
schema: {
|
|
531
|
+
twoFactor: {
|
|
532
|
+
modelName: modelNames.twoFactor
|
|
533
|
+
}
|
|
534
|
+
},
|
|
535
|
+
// trustDevice: false disables the 30-day "trust this device" skip. There
|
|
536
|
+
// is no dedicated off switch upstream, but trustDeviceMaxAge: 0 mints
|
|
537
|
+
// every trust record already expired and its cookie as a browser delete,
|
|
538
|
+
// so no device is durably trusted and a forged trustDevice: true cannot
|
|
539
|
+
// bypass. Omitted when on, so the plugin's 30-day default applies.
|
|
540
|
+
...authConfig.twoFactor.trustDevice === false ? {
|
|
541
|
+
trustDeviceMaxAge: 0
|
|
542
|
+
} : {}
|
|
543
|
+
}));
|
|
544
|
+
}
|
|
545
|
+
if (authConfig.passkey?.enabled === true) {
|
|
546
|
+
options.plugins.push(passkey({
|
|
547
|
+
rpID: authConfig.passkey.rpId,
|
|
548
|
+
rpName: authConfig.passkey.rpName,
|
|
549
|
+
schema: {
|
|
550
|
+
passkey: {
|
|
551
|
+
modelName: modelNames.passkey
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}));
|
|
555
|
+
}
|
|
556
|
+
// Captcha is server middleware only - the client half is the Captcha block
|
|
557
|
+
// and the captchaToken action param carrying the x-captcha-response header.
|
|
558
|
+
if (authConfig.captcha?.enabled === true) {
|
|
559
|
+
options.plugins.push(buildCaptchaPlugin({
|
|
560
|
+
authConfig
|
|
561
|
+
}));
|
|
562
|
+
}
|
|
563
|
+
// The app is its own OAuth 2.1 authorization server for the MCP endpoint.
|
|
564
|
+
// The AS issuer and the MCP resource URI derive from the
|
|
565
|
+
// canonical origin - a Host-derived issuer would let a spoofed Host header
|
|
566
|
+
// steer where tokens are honoured, so an unpinned origin is a startup error.
|
|
567
|
+
if (!type.isNone(authConfig.oauthProvider)) {
|
|
568
|
+
if (!type.isString(baseUrlOrigin)) {
|
|
569
|
+
throw new ConfigError('Auth "oauthProvider" requires the BETTER_AUTH_URL environment variable to be set to the app\'s canonical origin. The authorization server issuer and the MCP resource URI derive from it.');
|
|
570
|
+
}
|
|
571
|
+
const oauthPagesBasePath = config.basePath ?? '';
|
|
572
|
+
options.plugins.push(// The oauth-provider delegates access-token signing to the core jwt
|
|
573
|
+
// plugin and fails init without it. Only the signing keys are wanted
|
|
574
|
+
// from it: /token (session-JWT minting) is disabled via disabledPaths
|
|
575
|
+
// and disableSettingJwtHeader keeps the set-auth-jwt header off
|
|
576
|
+
// /get-session responses; /jwks stays so access tokens are verifiable.
|
|
577
|
+
// jwt.issuer is deliberately unset - the issuer then defaults to
|
|
578
|
+
// BetterAuth's baseURL + basePath, `${BETTER_AUTH_URL}${basePath}/api/auth`.
|
|
579
|
+
jwt({
|
|
580
|
+
disableSettingJwtHeader: true
|
|
581
|
+
}), oauthProvider({
|
|
582
|
+
loginPage: `${baseUrlOrigin}${oauthPagesBasePath}${authConfig.authPages.signIn}`,
|
|
583
|
+
consentPage: `${baseUrlOrigin}${oauthPagesBasePath}${authConfig.oauthProvider.consentPage}`,
|
|
584
|
+
// Which organization a grant acts in is chosen after login and before
|
|
585
|
+
// consent, and travels as the consent referenceId - see
|
|
586
|
+
// buildOauthPostLogin. Every access token carries it as the
|
|
587
|
+
// organization_id claim the /api/mcp route resolves the member from;
|
|
588
|
+
// the refresh grant re-stamps the same reference, so a refreshed
|
|
589
|
+
// token keeps its organization - while the user is still a member of
|
|
590
|
+
// it (createMcpAccessTokenClaims).
|
|
591
|
+
postLogin: buildOauthPostLogin({
|
|
592
|
+
authConfig,
|
|
593
|
+
baseUrlOrigin,
|
|
594
|
+
basePath: oauthPagesBasePath
|
|
595
|
+
}),
|
|
596
|
+
customAccessTokenClaims: createMcpAccessTokenClaims({
|
|
597
|
+
getAuth
|
|
598
|
+
}),
|
|
599
|
+
// The closed MCP scope vocabulary. Without "openid" the OIDC surface
|
|
600
|
+
// (id tokens, /oauth2/userinfo, /.well-known/openid-configuration)
|
|
601
|
+
// stays dormant. "offline_access" is the OAuth-standard opt-in for a
|
|
602
|
+
// refresh token: the oauth-provider issues one only when the grant
|
|
603
|
+
// carries it, so without it every MCP client is signed out the moment
|
|
604
|
+
// its access token lapses (hourly) and has to re-consent.
|
|
605
|
+
scopes: MCP_OAUTH_SCOPES,
|
|
606
|
+
// An MCP client running several sessions under one sign-in refreshes
|
|
607
|
+
// the same token from each of them within moments. Within this window
|
|
608
|
+
// a rotated refresh token presented again gets the stored response of
|
|
609
|
+
// its rotation instead of being treated as stolen; at 0, the reuse
|
|
610
|
+
// revokes every token the client holds for the user.
|
|
611
|
+
refreshTokenReuseInterval: 120,
|
|
612
|
+
// No client_credentials - every access token is user-consented.
|
|
613
|
+
grantTypes: [
|
|
614
|
+
'authorization_code',
|
|
615
|
+
'refresh_token'
|
|
616
|
+
],
|
|
617
|
+
// Any registered client may request any enabled resource - access is
|
|
618
|
+
// decided by user consent and org membership, not client-resource links.
|
|
619
|
+
enforcePerClientResources: false,
|
|
620
|
+
// The one resource row is owned by the app, never administered over
|
|
621
|
+
// HTTP.
|
|
622
|
+
resourcePrivileges: ()=>false,
|
|
623
|
+
...authConfig.oauthProvider.dynamicClientRegistration === true ? {
|
|
624
|
+
// RFC 7591 open registration - the opt-in fallback for MCP
|
|
625
|
+
// clients that cannot serve a CIMD document. Such clients carry
|
|
626
|
+
// no session, so registration must be unauthenticated.
|
|
627
|
+
allowDynamicClientRegistration: true,
|
|
628
|
+
allowUnauthenticatedClientRegistration: true
|
|
629
|
+
} : {}
|
|
630
|
+
}), // CIMD is the default registration path: an MCP client identifies by an
|
|
631
|
+
// HTTPS client_id URL serving its metadata document. Registers its
|
|
632
|
+
// client discovery on the oauth-provider and advertises
|
|
633
|
+
// client_id_metadata_document_supported in the AS metadata.
|
|
634
|
+
cimd({
|
|
635
|
+
fetchClientMetadataResource
|
|
636
|
+
}), // Member tokens - the long-lived bearer a script sends to /api/mcp in
|
|
637
|
+
// place of an OAuth access token. Only meaningful beside the AS: without
|
|
638
|
+
// it the route authenticates nobody.
|
|
639
|
+
buildMcpTokenPlugin());
|
|
640
|
+
}
|
|
641
|
+
// The admin plugin is framework-controlled - it owns the user row's ban fields
|
|
642
|
+
// and the endpoints the ban, delete and revoke-sessions steps call. Its whole
|
|
643
|
+
// HTTP surface is disabled (see ADMIN_PATHS_DISABLED).
|
|
644
|
+
options.plugins.push(buildAdminPlugin());
|
|
645
|
+
const { afterEmailVerification, databaseHooks, phoneVerified, sendPhoneOtp, sendPhonePasswordResetOtp } = buildHooks({
|
|
646
|
+
authConfig,
|
|
647
|
+
createSystemContext,
|
|
648
|
+
getAuth,
|
|
649
|
+
logger
|
|
650
|
+
});
|
|
651
|
+
if (Object.keys(databaseHooks).length > 0) {
|
|
652
|
+
options.databaseHooks = databaseHooks;
|
|
653
|
+
}
|
|
654
|
+
if (afterEmailVerification) {
|
|
655
|
+
options.emailVerification = {
|
|
656
|
+
...options.emailVerification,
|
|
657
|
+
afterEmailVerification
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
// Every engine-tier request hook lives in requestHooks/ and is dispatched by
|
|
661
|
+
// path from one assembler. BetterAuth wraps options.hooks.before/.after as a
|
|
662
|
+
// single match-all function each, so this is the only assignment of the slot -
|
|
663
|
+
// a second one would clobber it.
|
|
664
|
+
options.hooks = buildRequestHooks({
|
|
665
|
+
authConfig,
|
|
666
|
+
basePath: config.basePath ?? '',
|
|
667
|
+
baseUrlOrigin,
|
|
668
|
+
getAuth
|
|
669
|
+
});
|
|
670
|
+
// Phone login sends SMS through the "phone.otp.send" hook binding - there
|
|
671
|
+
// is no built-in SMS transport, so build validation requires the binding
|
|
672
|
+
// when the plugin is enabled.
|
|
673
|
+
if (authConfig.phoneNumber?.enabled === true) {
|
|
674
|
+
options.plugins.push(buildPhoneNumberPlugin({
|
|
675
|
+
authConfig,
|
|
676
|
+
phoneVerified,
|
|
677
|
+
sendPhoneOtp,
|
|
678
|
+
sendPhonePasswordResetOtp
|
|
679
|
+
}));
|
|
680
|
+
}
|
|
681
|
+
// Organizations are always on, so the plugin always gets an invitation
|
|
682
|
+
// sender. Without auth.email the sender throws at invite-send time (not at
|
|
683
|
+
// build), the same stance as password reset. The accept URL is only
|
|
684
|
+
// buildable when the origin is pinned AND authPages.acceptInvitation is set;
|
|
685
|
+
// otherwise the stock InvitationEmail renders branded with no CTA button.
|
|
686
|
+
async function sendInvitationEmail({ email, organization, invitation }) {
|
|
687
|
+
if (type.isNone(authConfig.email)) {
|
|
688
|
+
throw new ConfigError('Cannot send the invitation email. Configure "auth.email".');
|
|
689
|
+
}
|
|
690
|
+
const acceptPath = authConfig.authPages?.acceptInvitation;
|
|
691
|
+
const canBuildAcceptUrl = type.isString(baseUrlOrigin) && type.isString(acceptPath);
|
|
692
|
+
const basePath = config.basePath ?? '';
|
|
693
|
+
const acceptUrl = canBuildAcceptUrl ? `${baseUrlOrigin}${basePath}${acceptPath}?invitationId=${invitation.id}` : undefined;
|
|
694
|
+
const context = createSystemContext({
|
|
695
|
+
auth: getAuth()
|
|
696
|
+
});
|
|
697
|
+
const { subject, html, text } = await renderAuthEmail({
|
|
698
|
+
flow: 'invitation',
|
|
699
|
+
vars: {
|
|
700
|
+
url: acceptUrl,
|
|
701
|
+
organizationName: organization.name,
|
|
702
|
+
invitationId: invitation.id
|
|
703
|
+
},
|
|
704
|
+
authEmailConfig: authConfig.email,
|
|
705
|
+
baseURL: baseUrlOrigin,
|
|
706
|
+
context
|
|
707
|
+
});
|
|
708
|
+
await sendEmail({
|
|
709
|
+
to: email,
|
|
710
|
+
subject,
|
|
711
|
+
html,
|
|
712
|
+
text,
|
|
713
|
+
context
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
options.plugins.push(buildOrganizationPlugin({
|
|
717
|
+
authConfig,
|
|
718
|
+
getAuth,
|
|
719
|
+
logger,
|
|
720
|
+
sendInvitationEmail
|
|
721
|
+
}));
|
|
722
|
+
// BetterAuth's default /get-session body includes the raw session token - the
|
|
723
|
+
// credential half of the httpOnly session cookie. Lowdefy is cookie-based and
|
|
724
|
+
// never reads it client-side, so strip it: a JS-readable token needlessly
|
|
725
|
+
// undoes the point of the httpOnly cookie. customSession replaces the
|
|
726
|
+
// /get-session endpoint and transforms whatever the core resolver returns, so
|
|
727
|
+
// the token is dropped whether the session came from the DB or the cookie
|
|
728
|
+
// cache. Registered last so the resolver has already applied the organization
|
|
729
|
+
// (activeOrganizationId) and twoFactor session fields before the strip.
|
|
730
|
+
options.plugins.push(customSession(async (sessionResponse)=>sanitizeSessionResponse(sessionResponse)));
|
|
731
|
+
// The admin surface is off under both policies. The org plugin's client HTTP
|
|
732
|
+
// endpoints are policy-aware: pinned disables the full set (everything except
|
|
733
|
+
// accept-invitation/create); tenant is self-serve, so they stay enabled.
|
|
734
|
+
const policy = authConfig.organizations?.policy ?? 'pinned';
|
|
735
|
+
options.disabledPaths = [
|
|
736
|
+
...ADMIN_PATHS_DISABLED,
|
|
737
|
+
...policy === 'pinned' ? ORG_CLIENT_PATHS_DISABLED_WHEN_PINNED : [],
|
|
738
|
+
// The jwt plugin is registered only to sign the oauth-provider's access
|
|
739
|
+
// tokens - /token would mint a session-backed JWT for any logged-in
|
|
740
|
+
// browser, a bearer credential Lowdefy's cookie-based clients never need.
|
|
741
|
+
...type.isNone(authConfig.oauthProvider) ? [] : [
|
|
742
|
+
'/token'
|
|
743
|
+
]
|
|
744
|
+
];
|
|
745
|
+
// Own the logging of auth API errors so a rejected attempt (4xx) is a warn
|
|
746
|
+
// line, not an error - see createOnAPIError.
|
|
747
|
+
options.onAPIError = {
|
|
748
|
+
onError: createOnAPIError({
|
|
749
|
+
logger
|
|
750
|
+
})
|
|
751
|
+
};
|
|
752
|
+
// Decision 5: default every redirect-style auth error - chiefly an OAuth
|
|
753
|
+
// failure - to the resolved authPages.error page, instead of BetterAuth's
|
|
754
|
+
// bare built-in ${baseURL}/error. BetterAuth uses errorURL verbatim in the
|
|
755
|
+
// redirect (it is not joined with baseURL), so make it an absolute app URL
|
|
756
|
+
// when the origin is pinned; without a pinned origin fall back to the
|
|
757
|
+
// app-relative path, which the browser resolves against the callback origin.
|
|
758
|
+
// A per-action errorCallbackUrl on the login action still wins (BetterAuth
|
|
759
|
+
// resolves errorURL ?? onAPIError.errorURL).
|
|
760
|
+
if (type.isString(authConfig.authPages?.error)) {
|
|
761
|
+
const errorPath = `${config.basePath ?? ''}${authConfig.authPages.error}`;
|
|
762
|
+
options.onAPIError.errorURL = type.isString(baseUrlOrigin) ? `${baseUrlOrigin}${errorPath}` : errorPath;
|
|
763
|
+
}
|
|
764
|
+
return options;
|
|
765
|
+
}
|
|
766
|
+
export default getBetterAuthConfig;
|
|
767
|
+
export { MCP_OAUTH_SCOPES };
|