@lowdefy/api 6.0.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 +10 -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/getCurrentEnvironment.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 +22 -5
- package/dist/response/buildEndpointResult.js +3 -1
- package/dist/response/createWireProjection.js +88 -0
- package/dist/response/formatErrorForAgent.js +35 -0
- package/dist/response/normalizeErrorSources.js +10 -13
- package/dist/response/redactErrorResponse.js +42 -8
- package/dist/response/redactResponse.js +17 -10
- 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 +29 -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 +23 -7
- package/dist/routes/endpoints/control/controlFor.js +4 -7
- package/dist/routes/endpoints/control/controlIf.js +4 -8
- package/dist/routes/endpoints/control/controlLog.js +6 -14
- package/dist/routes/endpoints/control/controlParallelFor.js +65 -29
- package/dist/routes/endpoints/control/controlReject.js +36 -16
- package/dist/routes/endpoints/control/controlReturn.js +32 -9
- package/dist/routes/endpoints/control/controlSetState.js +4 -8
- package/dist/routes/endpoints/control/controlSwitch.js +4 -8
- package/dist/routes/endpoints/control/controlThrow.js +20 -21
- package/dist/routes/endpoints/control/controlTry.js +30 -11
- 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 +27 -0
- package/dist/routes/endpoints/forwardScheduledEndpoint.js +21 -15
- package/dist/routes/endpoints/getEndpointConfig.js +18 -8
- package/dist/routes/endpoints/getEnvironmentSchedules.js +5 -7
- package/dist/routes/endpoints/getSchemaValidator.js +39 -0
- package/dist/routes/endpoints/handleAgentCall.js +25 -9
- package/dist/routes/endpoints/handleAuthStep.js +214 -0
- package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
- package/dist/routes/endpoints/handleEndpointCall.js +46 -12
- package/dist/routes/endpoints/handleRenderNotification.js +29 -12
- package/dist/routes/endpoints/handleRequest.js +13 -6
- package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
- package/dist/routes/endpoints/handleValidateSchema.js +22 -22
- package/dist/routes/endpoints/invokeEndpoint.js +27 -3
- package/dist/routes/endpoints/operatorScope.js +28 -0
- package/dist/routes/{auth/events/createEventPlugins.js → endpoints/parseWebhookBody.js} +10 -6
- package/dist/routes/endpoints/resolveCallBinding.js +91 -0
- package/dist/routes/endpoints/resolveCronEnvironment.js +7 -6
- package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
- package/dist/routes/endpoints/runDetachedEndpoint.js +64 -18
- package/dist/routes/endpoints/runRoutine.js +64 -5
- package/dist/routes/endpoints/runScheduledEndpoint.js +19 -11
- package/dist/routes/endpoints/runWebhookEndpoint.js +70 -23
- package/dist/routes/endpoints/runWebhookVerify.js +129 -0
- package/dist/routes/endpoints/scheduleBackground.js +10 -0
- package/dist/routes/endpoints/test/runTest.js +48 -11
- package/dist/routes/endpoints/validatePayload.js +144 -0
- package/dist/routes/log/logClientError.js +7 -4
- package/dist/routes/mcp/createMcpServer.js +143 -64
- 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 +21 -3
- package/dist/routes/request/callRequestResolver.js +55 -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/evaluateOperators.js +8 -12
- 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/callbacks/createCallbackPlugins.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 +39 -14
- package/dist/routes/websocket/createWebSocketConnection.js +162 -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 +16 -11
- package/package.json +28 -12
- package/dist/context/createAuthorize.js +0 -45
- package/dist/response/omitErrorProps.js +0 -51
- 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/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 -86
- 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,39 @@
|
|
|
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
|
+
// The files the person attached in the conversation the chat request carried: every file part
|
|
17
|
+
// that holds a storage key (AgentChat sets providerMetadata.lowdefy.key on an upload), in message
|
|
18
|
+
// order. A tool endpoint reads them with `_agent: files`. They come from the request, not from a
|
|
19
|
+
// tool call, so the model can only name a file of this conversation. The messages are the
|
|
20
|
+
// client's, not yet validated, so a malformed message or part is passed over here and refused
|
|
21
|
+
// by the agent's message validation.
|
|
22
|
+
function collectChatFiles({ messages }) {
|
|
23
|
+
const files = [];
|
|
24
|
+
for (const message of messages){
|
|
25
|
+
if (!type.isArray(message?.parts)) continue;
|
|
26
|
+
for (const part of message.parts){
|
|
27
|
+
const key = part?.providerMetadata?.lowdefy?.key;
|
|
28
|
+
if (part?.type === 'file' && type.isString(key)) {
|
|
29
|
+
files.push({
|
|
30
|
+
key,
|
|
31
|
+
filename: part.filename ?? null,
|
|
32
|
+
mediaType: part.mediaType
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return files;
|
|
38
|
+
}
|
|
39
|
+
export default collectChatFiles;
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/ import { type } from '@lowdefy/helpers';
|
|
16
16
|
import buildEndpointResult from '../../response/buildEndpointResult.js';
|
|
17
|
+
import createWireProjection from '../../response/createWireProjection.js';
|
|
17
18
|
import getEndpointConfig from '../endpoints/getEndpointConfig.js';
|
|
18
19
|
import invokeEndpoint from '../endpoints/invokeEndpoint.js';
|
|
19
20
|
import authorizeAgent from './authorizeAgent.js';
|
|
@@ -26,14 +27,25 @@ import getConnection from '../connections/getConnection.js';
|
|
|
26
27
|
// config, evaluates operators, creates the provider connection, and builds the
|
|
27
28
|
// resolver context. mode ('chat' | 'generate') selects the resolver's execution
|
|
28
29
|
// path; endpointDepth threads the endpoint call depth cap through agent tool
|
|
29
|
-
// and hook endpoint calls.
|
|
30
|
-
async function prepareAgent(context, { agentId, agentContext, endpointDepth = 0, mode = 'chat' }) {
|
|
30
|
+
// and hook endpoint calls; files are the chat's attached files `_agent: files` reads.
|
|
31
|
+
async function prepareAgent(context, { agentId, agentContext, endpointDepth = 0, files, mode = 'chat' }) {
|
|
31
32
|
const agentConfig = await getAgentConfig(context, {
|
|
32
33
|
agentId
|
|
33
34
|
});
|
|
34
35
|
authorizeAgent(context, {
|
|
35
36
|
agentConfig
|
|
36
37
|
});
|
|
38
|
+
// What `_agent` reads in the tool and hook endpoints this agent calls. Built here from the
|
|
39
|
+
// agent being run, its conversation and the files of the chat request, so no tool input can
|
|
40
|
+
// set or change it.
|
|
41
|
+
// sharedState is the chat's shared state the browser sent with the request, the same value
|
|
42
|
+
// the agent's own context reads.
|
|
43
|
+
const agent = {
|
|
44
|
+
id: agentId,
|
|
45
|
+
conversationId: agentContext.conversationId ?? null,
|
|
46
|
+
files,
|
|
47
|
+
sharedState: agentContext.sharedState ?? null
|
|
48
|
+
};
|
|
37
49
|
// Evaluate operators in agent properties (e.g. _user, _secret, _payload)
|
|
38
50
|
agentConfig.properties = context.evaluateOperators({
|
|
39
51
|
input: agentConfig.properties ?? {},
|
|
@@ -71,7 +83,16 @@ async function prepareAgent(context, { agentId, agentContext, endpointDepth = 0,
|
|
|
71
83
|
const resolverContext = {
|
|
72
84
|
agentContext,
|
|
73
85
|
i18n: context.i18n,
|
|
86
|
+
logger: context.logger,
|
|
74
87
|
mode,
|
|
88
|
+
// Cancels a headless (CallAgent) run when the request that started it closes;
|
|
89
|
+
// undefined for chat runs and background routines (see callAgent).
|
|
90
|
+
signal: context.signal,
|
|
91
|
+
// The agent stream's error text reaches the end user and AgentChat config, so it takes
|
|
92
|
+
// the wire policy. Built here because the agent plugins cannot import @lowdefy/api.
|
|
93
|
+
// The AI SDK types onError's argument as unknown: a tool can reject with null or a
|
|
94
|
+
// string, which takes the generic message like any other non-author error.
|
|
95
|
+
wireErrorMessage: (error)=>createWireProjection(context)(type.isError(error) ? error : new Error(String(error))).message,
|
|
75
96
|
evaluateOperators: (input)=>context.evaluateOperators({
|
|
76
97
|
input,
|
|
77
98
|
location: agentConfig.agentId,
|
|
@@ -79,11 +100,15 @@ async function prepareAgent(context, { agentId, agentContext, endpointDepth = 0,
|
|
|
79
100
|
state: {},
|
|
80
101
|
steps: {}
|
|
81
102
|
}),
|
|
82
|
-
|
|
103
|
+
// outsideCaller marks a tool call, whose input the model built; a hook's
|
|
104
|
+
// payload is built by Lowdefy for the hook endpoint the config names.
|
|
105
|
+
callEndpoint: async (endpointId, { payload, outsideCaller = false })=>{
|
|
83
106
|
const { error, response, status } = await invokeEndpoint(context, {
|
|
107
|
+
agent,
|
|
84
108
|
endpointId,
|
|
85
109
|
payload,
|
|
86
|
-
endpointDepth
|
|
110
|
+
endpointDepth,
|
|
111
|
+
outsideCaller
|
|
87
112
|
});
|
|
88
113
|
return buildEndpointResult(context, {
|
|
89
114
|
error,
|
|
@@ -0,0 +1,33 @@
|
|
|
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 { admin } from 'better-auth/plugins';
|
|
16
|
+
// The admin plugin is registered for two things: it owns the
|
|
17
|
+
// banned/banReason/banExpires fields on the user row, and it owns the endpoints
|
|
18
|
+
// the BanUser, UnbanUser, DeleteUser and RevokeUserSessions steps call. Those
|
|
19
|
+
// calls carry server authority - callPluginEndpoint injects an acting user with
|
|
20
|
+
// role: 'admin', which the vendor's built-in admin role satisfies - and the
|
|
21
|
+
// step floor is what authorizes them, per organization and bounded by the
|
|
22
|
+
// target's membership there.
|
|
23
|
+
//
|
|
24
|
+
// So the vendor's default roles are all this needs. Nothing in Lowdefy writes
|
|
25
|
+
// user.role, so no real browser session holds a role in adminRoles and no
|
|
26
|
+
// browser caller can satisfy any /admin/* check; the whole surface is disabled
|
|
27
|
+
// at the router besides (see ADMIN_PATHS_DISABLED in getBetterAuthConfig).
|
|
28
|
+
// A custom access control would only exist to grant a real user authority the
|
|
29
|
+
// platform has none to grant.
|
|
30
|
+
function buildAdminPlugin() {
|
|
31
|
+
return admin();
|
|
32
|
+
}
|
|
33
|
+
export default buildAdminPlugin;
|
|
@@ -0,0 +1,61 @@
|
|
|
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 { captcha } from 'better-auth/plugins';
|
|
16
|
+
import { type } from '@lowdefy/helpers';
|
|
17
|
+
import { ConfigError } from '@lowdefy/errors';
|
|
18
|
+
// The protected set is computed from the enabled login methods - the union
|
|
19
|
+
// of each method's public initiate endpoints, including the message-send
|
|
20
|
+
// endpoints that spend money. This deliberately deviates from BetterAuth's
|
|
21
|
+
// static default (three email paths), which would leave
|
|
22
|
+
// /phone-number/send-otp - the most expensive endpoint and the reason this
|
|
23
|
+
// plugin exists - unprotected. Verify/consume endpoints stay uncovered: they
|
|
24
|
+
// are guarded by their own single-use, attempt-limited codes, and captcha
|
|
25
|
+
// tokens are single-use, so covering them would demand a second token per
|
|
26
|
+
// flow.
|
|
27
|
+
function computeCaptchaEndpoints({ authConfig }) {
|
|
28
|
+
const endpoints = [
|
|
29
|
+
'/sign-up/email',
|
|
30
|
+
'/sign-in/email',
|
|
31
|
+
'/request-password-reset',
|
|
32
|
+
'/send-verification-email'
|
|
33
|
+
];
|
|
34
|
+
if (authConfig.magicLink?.enabled === true) {
|
|
35
|
+
endpoints.push('/sign-in/magic-link');
|
|
36
|
+
}
|
|
37
|
+
if (authConfig.phoneNumber?.enabled === true) {
|
|
38
|
+
endpoints.push('/phone-number/send-otp', '/sign-in/phone-number', '/phone-number/request-password-reset');
|
|
39
|
+
}
|
|
40
|
+
return endpoints;
|
|
41
|
+
}
|
|
42
|
+
// Maps auth.captcha onto BetterAuth's captcha plugin - a self-contained
|
|
43
|
+
// onRequest middleware that verifies the x-captcha-response header against
|
|
44
|
+
// the provider's siteverify API and fails closed. An explicit
|
|
45
|
+
// auth.captcha.endpoints replaces the computed set entirely.
|
|
46
|
+
function buildCaptchaPlugin({ authConfig }) {
|
|
47
|
+
const captchaConfig = authConfig.captcha;
|
|
48
|
+
if (!type.isString(captchaConfig.secretKey)) {
|
|
49
|
+
throw new ConfigError('Auth "captcha.secretKey" did not resolve to a string. Check the _secret operator reference and that the secret is set.', {
|
|
50
|
+
received: type.typeOf(captchaConfig.secretKey)
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
return captcha({
|
|
54
|
+
provider: captchaConfig.provider,
|
|
55
|
+
secretKey: captchaConfig.secretKey,
|
|
56
|
+
endpoints: captchaConfig.endpoints ?? computeCaptchaEndpoints({
|
|
57
|
+
authConfig
|
|
58
|
+
})
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
export default buildCaptchaPlugin;
|
|
@@ -0,0 +1,77 @@
|
|
|
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 modelNames from './modelNames.js';
|
|
16
|
+
// Member tokens for MCP scripts live in the auth database as their own model,
|
|
17
|
+
// so the adapter reads and writes them like every other auth row and the MCP
|
|
18
|
+
// route's lookup is one more indexed read beside consents, users and members.
|
|
19
|
+
// The plugin declares the schema only - no endpoints: tokens are created and
|
|
20
|
+
// revoked by the auth steps, never over BetterAuth's HTTP surface. The token
|
|
21
|
+
// itself is never stored, only its SHA-256 (hash) and its first characters
|
|
22
|
+
// (start) so people can tell tokens apart.
|
|
23
|
+
function buildMcpTokenPlugin() {
|
|
24
|
+
return {
|
|
25
|
+
id: 'lowdefy-mcp-token',
|
|
26
|
+
schema: {
|
|
27
|
+
mcpToken: {
|
|
28
|
+
modelName: modelNames.mcpToken,
|
|
29
|
+
fields: {
|
|
30
|
+
organizationId: {
|
|
31
|
+
type: 'string',
|
|
32
|
+
required: true,
|
|
33
|
+
index: true
|
|
34
|
+
},
|
|
35
|
+
userId: {
|
|
36
|
+
type: 'string',
|
|
37
|
+
required: true,
|
|
38
|
+
index: true
|
|
39
|
+
},
|
|
40
|
+
// The member row the token was made for. The route accepts the token
|
|
41
|
+
// only while that row stands, so leaving, removal or deletion ends
|
|
42
|
+
// it by any path, and a rejoined member's new row holds no old tokens.
|
|
43
|
+
memberId: {
|
|
44
|
+
type: 'string',
|
|
45
|
+
required: true
|
|
46
|
+
},
|
|
47
|
+
name: {
|
|
48
|
+
type: 'string',
|
|
49
|
+
required: true
|
|
50
|
+
},
|
|
51
|
+
hash: {
|
|
52
|
+
type: 'string',
|
|
53
|
+
required: true,
|
|
54
|
+
unique: true
|
|
55
|
+
},
|
|
56
|
+
start: {
|
|
57
|
+
type: 'string',
|
|
58
|
+
required: true
|
|
59
|
+
},
|
|
60
|
+
createdAt: {
|
|
61
|
+
type: 'date',
|
|
62
|
+
required: true
|
|
63
|
+
},
|
|
64
|
+
expiresAt: {
|
|
65
|
+
type: 'date',
|
|
66
|
+
required: false
|
|
67
|
+
},
|
|
68
|
+
lastUsedAt: {
|
|
69
|
+
type: 'date',
|
|
70
|
+
required: false
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
export default buildMcpTokenPlugin;
|
|
@@ -0,0 +1,73 @@
|
|
|
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 { APIError } from 'better-auth/api';
|
|
16
|
+
import { type } from '@lowdefy/helpers';
|
|
17
|
+
// The oauth-provider's post-login seat: after login and before consent, the
|
|
18
|
+
// authorization server asks which organization the grant acts in. The answer
|
|
19
|
+
// is the consent referenceId - it keys consent per (client, user,
|
|
20
|
+
// organization), rides the authorization code and the refresh-token row, and
|
|
21
|
+
// is what customAccessTokenClaims stamps onto every access token as
|
|
22
|
+
// organization_id. So the organization an MCP token acts in is never a URL
|
|
23
|
+
// segment or a client-supplied parameter: it is the member's own choice,
|
|
24
|
+
// signed into the code by the AS and re-verified against the live member row
|
|
25
|
+
// on every request.
|
|
26
|
+
//
|
|
27
|
+
// Under the tenant policy the member chooses on the configured page (the page
|
|
28
|
+
// runs SetActiveOrganization for the chosen organization, then OAuthContinue),
|
|
29
|
+
// and the choice is made on every authorization - a one-organization member
|
|
30
|
+
// sees a single preselected row. The plugin asks shouldRedirect on every
|
|
31
|
+
// authorize call, including the one /oauth2/continue re-enters with after the
|
|
32
|
+
// choice, and only its CONSENT redirect carries the "post-login done" marker
|
|
33
|
+
// (ba_pl) - so an unconditional true would loop back to the picker forever.
|
|
34
|
+
// The request hook on /oauth2/continue (createOauthPostLoginHook) stamps the
|
|
35
|
+
// session object cached on that request instead, and shouldRedirect reads the
|
|
36
|
+
// stamp: true until the choice has been posted, false on the authorize call
|
|
37
|
+
// that carries it. Under the pinned policy there is one organization and
|
|
38
|
+
// nothing to choose: the redirect is skipped and the reference is the pinned
|
|
39
|
+
// organization, whose id is its slug. The page is still required by the
|
|
40
|
+
// plugin option shape, so the consent page stands in - it is never redirected
|
|
41
|
+
// to.
|
|
42
|
+
//
|
|
43
|
+
// The marker lives on the in-request session object only - never persisted -
|
|
44
|
+
// so it cannot outlive the request that made the choice.
|
|
45
|
+
const OAUTH_POST_LOGIN_CONFIRMED = 'oauthPostLoginConfirmed';
|
|
46
|
+
function buildOauthPostLogin({ authConfig, baseUrlOrigin, basePath }) {
|
|
47
|
+
if (authConfig.organizations?.policy === 'pinned') {
|
|
48
|
+
return {
|
|
49
|
+
page: `${baseUrlOrigin}${basePath}${authConfig.oauthProvider.consentPage}`,
|
|
50
|
+
shouldRedirect: ()=>false,
|
|
51
|
+
consentReferenceId: ()=>authConfig.organizations.org
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
page: `${baseUrlOrigin}${basePath}${authConfig.oauthProvider.postLoginPage}`,
|
|
56
|
+
shouldRedirect: ({ session })=>session?.[OAUTH_POST_LOGIN_CONFIRMED] !== true,
|
|
57
|
+
consentReferenceId: ({ session })=>{
|
|
58
|
+
const organizationId = session?.activeOrganizationId;
|
|
59
|
+
// The plugin's contract: fail here when the reference is missing rather
|
|
60
|
+
// than let a consent be recorded without one - a token minted without
|
|
61
|
+
// organization_id would be refused by the MCP route on every call.
|
|
62
|
+
if (!type.isString(organizationId) || organizationId.length === 0) {
|
|
63
|
+
throw new APIError('BAD_REQUEST', {
|
|
64
|
+
error: 'invalid_request',
|
|
65
|
+
error_description: 'No organization was selected for this authorization. Choose an organization and try again.'
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return organizationId;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
export { OAUTH_POST_LOGIN_CONFIRMED };
|
|
73
|
+
export default buildOauthPostLogin;
|
|
@@ -0,0 +1,57 @@
|
|
|
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 { phoneNumber } from 'better-auth/plugins';
|
|
16
|
+
import { type } from '@lowdefy/helpers';
|
|
17
|
+
import { ConfigError } from '@lowdefy/errors';
|
|
18
|
+
// The wire format is pinned to E.164. BetterAuth's default validator accepts
|
|
19
|
+
// any string, which mints several identities for one phone ("+27 83 123 4567",
|
|
20
|
+
// "0831234567" and "+27831234567") and spends real money on malformed sends.
|
|
21
|
+
// Normalization belongs in the UI's locale-aware input widgets.
|
|
22
|
+
const E164_REGEX = /^\+[1-9]\d{1,14}$/;
|
|
23
|
+
// Maps auth.phoneNumber onto BetterAuth's phoneNumber plugin. The SMS send
|
|
24
|
+
// callbacks are the composed "phone.otp.send" / "phone.passwordReset.send"
|
|
25
|
+
// hook slots - build validation guarantees the OTP send binding exists when
|
|
26
|
+
// the plugin is enabled, so sendPhoneOtp is always a function here.
|
|
27
|
+
function buildPhoneNumberPlugin({ authConfig, phoneVerified, sendPhoneOtp, sendPhonePasswordResetOtp }) {
|
|
28
|
+
const phoneNumberConfig = authConfig.phoneNumber;
|
|
29
|
+
const options = {
|
|
30
|
+
otpLength: phoneNumberConfig.otpLength,
|
|
31
|
+
expiresIn: phoneNumberConfig.expiresIn,
|
|
32
|
+
allowedAttempts: phoneNumberConfig.allowedAttempts,
|
|
33
|
+
requireVerification: phoneNumberConfig.requireVerification,
|
|
34
|
+
phoneNumberValidator: (value)=>E164_REGEX.test(value),
|
|
35
|
+
sendOTP: sendPhoneOtp,
|
|
36
|
+
// BetterAuth's /phone-number/request-password-reset returns
|
|
37
|
+
// { status: true } without sending anything when sendPasswordResetOTP is
|
|
38
|
+
// not configured - a user asking for a reset would get silence and a 200
|
|
39
|
+
// in the logs. Fail loudly naming the fix instead.
|
|
40
|
+
sendPasswordResetOTP: sendPhonePasswordResetOtp ?? (()=>{
|
|
41
|
+
throw new ConfigError('Password reset over phone is not configured. Bind an InternalApi endpoint to the "phone.passwordReset.send" auth hook point to send reset codes.');
|
|
42
|
+
})
|
|
43
|
+
};
|
|
44
|
+
if (!type.isNone(phoneVerified)) {
|
|
45
|
+
options.callbackOnVerification = phoneVerified;
|
|
46
|
+
}
|
|
47
|
+
if (!type.isNone(phoneNumberConfig.signUpOnVerification)) {
|
|
48
|
+
const { tempEmailDomain } = phoneNumberConfig.signUpOnVerification;
|
|
49
|
+
options.signUpOnVerification = {
|
|
50
|
+
// The E.164 digits with the "+" stripped keep the derived address
|
|
51
|
+
// unique per phone; uniqueness is inherited from the phone number's.
|
|
52
|
+
getTempEmail: (value)=>`${value.replace(/\D/g, '')}@${tempEmailDomain}`
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
return phoneNumber(options);
|
|
56
|
+
}
|
|
57
|
+
export default buildPhoneNumberPlugin;
|
|
@@ -0,0 +1,61 @@
|
|
|
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 { ConfigError } from '@lowdefy/errors';
|
|
17
|
+
// Splits the unified auth.providers array into BetterAuth's two shapes:
|
|
18
|
+
// built-in providers become socialProviders entries keyed by the BetterAuth
|
|
19
|
+
// provider key; GenericOAuth entries become genericOAuth plugin configs
|
|
20
|
+
// keyed by the Lowdefy provider id.
|
|
21
|
+
function buildProviders({ authConfig, plugins }) {
|
|
22
|
+
const socialProviders = {};
|
|
23
|
+
const genericOAuthConfigs = [];
|
|
24
|
+
(authConfig.providers ?? []).forEach((provider)=>{
|
|
25
|
+
const providerPlugin = plugins.providers[provider.type];
|
|
26
|
+
if (type.isNone(providerPlugin)) {
|
|
27
|
+
throw new ConfigError(`Auth provider type "${provider.type}" not found at provider "${provider.id}".`, {
|
|
28
|
+
configKey: provider['~k']
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
let definition;
|
|
32
|
+
try {
|
|
33
|
+
definition = providerPlugin({
|
|
34
|
+
id: provider.id,
|
|
35
|
+
properties: provider.properties ?? {}
|
|
36
|
+
});
|
|
37
|
+
} catch (error) {
|
|
38
|
+
// Provider plugins throw plain errors (an invalid property) - attach the
|
|
39
|
+
// provider's id and config location.
|
|
40
|
+
throw new ConfigError(`Auth provider "${provider.id}" is invalid: ${error.message}`, {
|
|
41
|
+
cause: error,
|
|
42
|
+
configKey: provider['~k']
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
if (definition.kind === 'generic') {
|
|
46
|
+
genericOAuthConfigs.push(definition.config);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (!type.isNone(socialProviders[definition.provider])) {
|
|
50
|
+
throw new ConfigError(`Auth provider "${definition.provider}" is configured more than once. BetterAuth supports one configuration per built-in provider.`, {
|
|
51
|
+
configKey: provider['~k']
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
socialProviders[definition.provider] = definition.options;
|
|
55
|
+
});
|
|
56
|
+
return {
|
|
57
|
+
socialProviders,
|
|
58
|
+
genericOAuthConfigs
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
export default buildProviders;
|
|
@@ -0,0 +1,27 @@
|
|
|
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 { oauthProviderAuthServerMetadata } from '@better-auth/oauth-provider';
|
|
16
|
+
// The oauth-provider plugin serves its AS metadata relative to the auth
|
|
17
|
+
// mount, so the RFC 8414 path-inserted location a client derives from the
|
|
18
|
+
// issuer (/.well-known/oauth-authorization-server/api/auth) must be mounted
|
|
19
|
+
// by the servers themselves. This wraps the vendor handler around the live
|
|
20
|
+
// auth instance - the served document, issuer included, then cannot drift
|
|
21
|
+
// from the plugin's own metadata - and keeps the @better-auth/oauth-provider
|
|
22
|
+
// import beside the plugin registration instead of in each server. Returns
|
|
23
|
+
// (request: Request) => Promise<Response>.
|
|
24
|
+
function createAsMetadataHandler({ auth }) {
|
|
25
|
+
return oauthProviderAuthServerMetadata(auth);
|
|
26
|
+
}
|
|
27
|
+
export default createAsMetadataHandler;
|
|
@@ -0,0 +1,31 @@
|
|
|
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
|
+
*/ // Adapts the Lowdefy logger to BetterAuth's logger contract:
|
|
16
|
+
// { disabled, level, log(level, message, ...args) }.
|
|
17
|
+
function createAuthLogger({ logger }) {
|
|
18
|
+
return {
|
|
19
|
+
disabled: false,
|
|
20
|
+
level: logger?.isLevelEnabled?.('debug') === true ? 'debug' : 'warn',
|
|
21
|
+
log: (level, message, ...args)=>{
|
|
22
|
+
const log = logger?.[level] ?? logger?.info;
|
|
23
|
+
if (!log) return;
|
|
24
|
+
log.call(logger, {
|
|
25
|
+
event: 'auth_engine',
|
|
26
|
+
args
|
|
27
|
+
}, message);
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export default createAuthLogger;
|
|
@@ -0,0 +1,52 @@
|
|
|
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 { APIError } from 'better-auth/api';
|
|
16
|
+
import { type } from '@lowdefy/helpers';
|
|
17
|
+
// Every MCP access token carries the organization its grant acts in as the
|
|
18
|
+
// organization_id claim - the consent referenceId (buildOauthPostLogin). The
|
|
19
|
+
// refresh grant re-stamps that reference without asking whether the user still
|
|
20
|
+
// belongs to the organization, so a member who left or was removed would keep
|
|
21
|
+
// refreshing into tokens the MCP route refuses: the client refreshes, retries,
|
|
22
|
+
// gets the same 401 and gives up, and never re-runs sign-in and the
|
|
23
|
+
// organization choice. Refusing the mint with invalid_grant is what sends an
|
|
24
|
+
// OAuth client back through authorization.
|
|
25
|
+
function createMcpAccessTokenClaims({ getAuth }) {
|
|
26
|
+
return async function mcpAccessTokenClaims({ user, referenceId }) {
|
|
27
|
+
const { adapter } = await getAuth().$context;
|
|
28
|
+
const member = await adapter.findOne({
|
|
29
|
+
model: 'member',
|
|
30
|
+
where: [
|
|
31
|
+
{
|
|
32
|
+
field: 'userId',
|
|
33
|
+
value: user.id
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
field: 'organizationId',
|
|
37
|
+
value: referenceId
|
|
38
|
+
}
|
|
39
|
+
]
|
|
40
|
+
});
|
|
41
|
+
if (type.isNone(member)) {
|
|
42
|
+
throw new APIError('BAD_REQUEST', {
|
|
43
|
+
error: 'invalid_grant',
|
|
44
|
+
error_description: 'The user is no longer a member of the organization this grant acts in. Authorize again to choose an organization.'
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
organization_id: referenceId
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
export default createMcpAccessTokenClaims;
|
|
@@ -0,0 +1,41 @@
|
|
|
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
|
+
// BetterAuth's router logs every APIError at error level when the logger level
|
|
17
|
+
// is warn or debug, so a wrong password, an expired link or a stale OAuth
|
|
18
|
+
// authorization query produced an ERROR line in the server log on every
|
|
19
|
+
// attempt. Supplying onAPIError.onError replaces that logging - the router
|
|
20
|
+
// returns right after calling it and the HTTP response is unaffected.
|
|
21
|
+
//
|
|
22
|
+
// A 4xx is the auth server rejecting the caller's attempt: expected traffic,
|
|
23
|
+
// one warn line, the same treatment the server error handler gives an
|
|
24
|
+
// AuthenticationError. Anything else is a fault in the auth engine or its
|
|
25
|
+
// adapter and stays at error level with the error object, so the cause chain
|
|
26
|
+
// and stack are logged.
|
|
27
|
+
function createOnAPIError({ logger }) {
|
|
28
|
+
return function onAPIError(error) {
|
|
29
|
+
const statusCode = error?.statusCode;
|
|
30
|
+
if (type.isInt(statusCode) && statusCode >= 400 && statusCode < 500) {
|
|
31
|
+
logger.warn({
|
|
32
|
+
event: 'auth_engine',
|
|
33
|
+
code: error.body?.code,
|
|
34
|
+
status: statusCode
|
|
35
|
+
}, `Auth request rejected (${statusCode}): ${error.message}`);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
logger.error(error);
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export default createOnAPIError;
|