@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
|
@@ -12,23 +12,38 @@
|
|
|
12
12
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
13
|
See the License for the specific language governing permissions and
|
|
14
14
|
limitations under the License.
|
|
15
|
-
*/ import {
|
|
16
|
-
import
|
|
17
|
-
import
|
|
15
|
+
*/ import { type } from '@lowdefy/helpers';
|
|
16
|
+
import { ConfigError } from '@lowdefy/errors';
|
|
17
|
+
import applySystemTrust from '../../context/applySystemTrust.js';
|
|
18
|
+
import createAuthorizeOutcome from '../../context/createAuthorizeOutcome.js';
|
|
18
19
|
import createEvaluateOperators from '../../context/createEvaluateOperators.js';
|
|
20
|
+
import createWebhookAnswer from './createWebhookAnswer.js';
|
|
19
21
|
import getEndpointConfig from './getEndpointConfig.js';
|
|
22
|
+
import parseWebhookBody from './parseWebhookBody.js';
|
|
20
23
|
import runRoutine from './runRoutine.js';
|
|
21
|
-
|
|
24
|
+
import runWebhookVerify from './runWebhookVerify.js';
|
|
25
|
+
// Runs an endpoint declared `webhook` — a third-party webhook receiver
|
|
22
26
|
// (SNS, Event Grid, Stripe, ...) served on the standard /api/endpoints route,
|
|
23
27
|
// but taking the request RAW: bodies are the caller's own format, not
|
|
24
28
|
// Lowdefy's { payload } envelope, so the routine receives
|
|
25
29
|
// { body, query, headers } as its payload and its return value is sent back
|
|
26
|
-
// verbatim (handshakes require exact response shapes).
|
|
27
|
-
//
|
|
28
|
-
//
|
|
29
|
-
//
|
|
30
|
-
//
|
|
31
|
-
|
|
30
|
+
// verbatim (handshakes require exact response shapes). It returns the HTTP
|
|
31
|
+
// answer, { status, body, contentType? }, that the route sends (see
|
|
32
|
+
// createWebhookAnswer): JSON, or text when contentType is text/plain.
|
|
33
|
+
// Only endpoints that opt in are runnable here (a missing flag reads as a
|
|
34
|
+
// missing endpoint — no probing).
|
|
35
|
+
//
|
|
36
|
+
// The transport is public by design, so the run starts caller-less AND
|
|
37
|
+
// UNTRUSTED (Decision 3): context.user = null, context.system unset. It earns
|
|
38
|
+
// trust only when its declared `webhook.verify` gate passes, run mechanically
|
|
39
|
+
// BEFORE the routine body - so verification can never be forgotten, mis-ordered,
|
|
40
|
+
// or placed after a privileged CallApi. A webhook with no declared verifier
|
|
41
|
+
// runs untrusted throughout, so any nested protected CallApi fails closed.
|
|
42
|
+
//
|
|
43
|
+
// rawBody is the request body exactly as received. Only the verifier sees it
|
|
44
|
+
// (a sender's signature is computed over those bytes, which re-serialising the
|
|
45
|
+
// parsed body does not reproduce); the routine gets the parsed body.
|
|
46
|
+
async function runWebhookEndpoint(context, { endpointId, rawBody, query, headers }) {
|
|
32
47
|
const { logger } = context;
|
|
33
48
|
context.endpointId = endpointId;
|
|
34
49
|
context.evaluateOperators = createEvaluateOperators(context);
|
|
@@ -39,7 +54,8 @@ async function runWebhookEndpoint(context, { endpointId, body, query, headers })
|
|
|
39
54
|
const endpointConfig = await getEndpointConfig(context, {
|
|
40
55
|
endpointId
|
|
41
56
|
});
|
|
42
|
-
|
|
57
|
+
// webhook may be `true` or a `{ verify }` object — gate on truthiness.
|
|
58
|
+
if (!endpointConfig.webhook) {
|
|
43
59
|
const err = new ConfigError(`API Endpoint "${endpointId}" does not exist.`);
|
|
44
60
|
logger.debug({
|
|
45
61
|
params: {
|
|
@@ -49,20 +65,49 @@ async function runWebhookEndpoint(context, { endpointId, body, query, headers })
|
|
|
49
65
|
}, err.message);
|
|
50
66
|
throw err;
|
|
51
67
|
}
|
|
52
|
-
//
|
|
53
|
-
//
|
|
54
|
-
//
|
|
55
|
-
|
|
56
|
-
context.user =
|
|
57
|
-
context.
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
68
|
+
// Caller-less and UNTRUSTED: with context.system unset, createAuthorizeOutcome
|
|
69
|
+
// fails closed on any protected target exactly as an unauthenticated call would
|
|
70
|
+
// (Api and InternalApi alike — InternalApi is an HTTP-exposure choice, not a
|
|
71
|
+
// trust tier, so it earns no special pass).
|
|
72
|
+
context.user = null;
|
|
73
|
+
context.authorizeOutcome = createAuthorizeOutcome(context);
|
|
74
|
+
// A declared verifier is the only thing that can make the run trusted, and it
|
|
75
|
+
// runs before any routine step. On success the runner (not routine or
|
|
76
|
+
// resolver code) sets context.system, matching the state createSystemContext
|
|
77
|
+
// produces for cron. On failure the routine never runs.
|
|
78
|
+
const body = parseWebhookBody({
|
|
79
|
+
rawBody
|
|
61
80
|
});
|
|
81
|
+
const verify = type.isObject(endpointConfig.webhook) ? endpointConfig.webhook.verify : undefined;
|
|
82
|
+
if (!type.isNone(verify)) {
|
|
83
|
+
const verified = await runWebhookVerify(context, {
|
|
84
|
+
verify,
|
|
85
|
+
body,
|
|
86
|
+
rawBody,
|
|
87
|
+
query,
|
|
88
|
+
headers
|
|
89
|
+
});
|
|
90
|
+
if (!verified) {
|
|
91
|
+
logger.warn({
|
|
92
|
+
event: 'webhook_verify_failed',
|
|
93
|
+
endpointId
|
|
94
|
+
});
|
|
95
|
+
return {
|
|
96
|
+
status: 401,
|
|
97
|
+
body: {
|
|
98
|
+
error: {
|
|
99
|
+
code: 'unauthorized',
|
|
100
|
+
message: 'Webhook verification failed.'
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
applySystemTrust(context);
|
|
106
|
+
}
|
|
62
107
|
const routineContext = {
|
|
63
108
|
steps: {},
|
|
64
109
|
payload: {
|
|
65
|
-
body
|
|
110
|
+
body,
|
|
66
111
|
query: query ?? {},
|
|
67
112
|
headers: headers ?? {}
|
|
68
113
|
},
|
|
@@ -72,10 +117,11 @@ async function runWebhookEndpoint(context, { endpointId, body, query, headers })
|
|
|
72
117
|
state: {},
|
|
73
118
|
endpointDepth: 0
|
|
74
119
|
};
|
|
75
|
-
const { error, response, status } = await runRoutine(context, routineContext, {
|
|
120
|
+
const { contentType, error, response, status } = await runRoutine(context, routineContext, {
|
|
76
121
|
routine: endpointConfig.routine
|
|
77
122
|
});
|
|
78
|
-
return
|
|
123
|
+
return createWebhookAnswer(context, {
|
|
124
|
+
contentType,
|
|
79
125
|
error,
|
|
80
126
|
response,
|
|
81
127
|
status
|
|
@@ -0,0 +1,129 @@
|
|
|
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 { ServiceError } from '@lowdefy/errors';
|
|
16
|
+
import { type } from '@lowdefy/helpers';
|
|
17
|
+
import callRequestResolver from '../request/callRequestResolver.js';
|
|
18
|
+
import evaluateRequestOperators from '../request/evaluateOperators.js';
|
|
19
|
+
import getConnection from '../connections/getConnection.js';
|
|
20
|
+
import getConnectionConfig from '../connections/getConnectionConfig.js';
|
|
21
|
+
import getRequestResolver from '../request/getRequestResolver.js';
|
|
22
|
+
import operatorScope from './operatorScope.js';
|
|
23
|
+
import resolveTenancy from '../request/resolveTenancy.js';
|
|
24
|
+
// Runs the endpoint's declared `webhook.verify` request plugin as a gate,
|
|
25
|
+
// against the RAW request (body, rawBody, query, headers), before the routine body
|
|
26
|
+
// (Decision 3). The verifier is a request plugin - the same class of code as a
|
|
27
|
+
// connection request - resolved and invoked through the request-plugin
|
|
28
|
+
// machinery, never as a routine step. It reads the request and reports a
|
|
29
|
+
// verdict; the RUNNER (not routine or resolver code) performs the trust
|
|
30
|
+
// transition, so there is no trust-writing capability on the resolver surface.
|
|
31
|
+
//
|
|
32
|
+
// Returns true only when the verifier passes: it must not throw and must return
|
|
33
|
+
// `true` or `{ verified: true }`. A verifier that throws (e.g. a bad signature)
|
|
34
|
+
// is a failed gate, not a server fault - it fails closed to a false verdict.
|
|
35
|
+
// Config-resolution errors (missing connection / unknown request type) throw:
|
|
36
|
+
// a misconfigured verifier breaks loudly in development rather than silently
|
|
37
|
+
// trusting or silently failing.
|
|
38
|
+
async function runWebhookVerify(context, { verify, body, rawBody, query, headers }) {
|
|
39
|
+
const payload = {
|
|
40
|
+
body,
|
|
41
|
+
rawBody,
|
|
42
|
+
query: query ?? {},
|
|
43
|
+
headers: headers ?? {}
|
|
44
|
+
};
|
|
45
|
+
const connectionConfig = await getConnectionConfig(context, {
|
|
46
|
+
connectionId: verify.connectionId,
|
|
47
|
+
configKey: verify['~k']
|
|
48
|
+
});
|
|
49
|
+
const connection = getConnection(context, {
|
|
50
|
+
connectionConfig
|
|
51
|
+
});
|
|
52
|
+
const requestConfig = {
|
|
53
|
+
type: verify.type,
|
|
54
|
+
connectionId: verify.connectionId,
|
|
55
|
+
requestId: 'webhook.verify',
|
|
56
|
+
properties: verify.properties ?? {},
|
|
57
|
+
// The verifier runs before the run earns trust, with no caller
|
|
58
|
+
// organization, so a verifier on a tenant connection fails closed (caught
|
|
59
|
+
// at resolveTenancy below, verdict false) unless the verify config opts
|
|
60
|
+
// out with tenant: none - which may only read, like any tenant: none
|
|
61
|
+
// request.
|
|
62
|
+
tenant: verify.tenant,
|
|
63
|
+
'~k': verify['~k']
|
|
64
|
+
};
|
|
65
|
+
const requestResolver = getRequestResolver(context, {
|
|
66
|
+
connection,
|
|
67
|
+
requestConfig
|
|
68
|
+
});
|
|
69
|
+
let tenancy;
|
|
70
|
+
try {
|
|
71
|
+
tenancy = resolveTenancy(context, {
|
|
72
|
+
connection,
|
|
73
|
+
connectionConfig,
|
|
74
|
+
requestConfig,
|
|
75
|
+
writes: requestResolver.meta.checkWrite === true
|
|
76
|
+
});
|
|
77
|
+
} catch (error) {
|
|
78
|
+
// Only the org-less-caller refusal is a gate outcome - it must not reach
|
|
79
|
+
// the unauthenticated webhook sender as an error body. Config errors
|
|
80
|
+
// (tenant declared on a type without the contract, a writing verifier
|
|
81
|
+
// under tenant: none) still throw: a misconfigured verifier breaks
|
|
82
|
+
// loudly, per the contract above, rather than failing every webhook as
|
|
83
|
+
// an unverified one inside the resolver call below.
|
|
84
|
+
if (error.name !== 'AuthenticationError') {
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
context.logger.debug({
|
|
88
|
+
event: 'debug_webhook_verify_error',
|
|
89
|
+
err: error
|
|
90
|
+
}, error.message);
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
// The verifier runs before the routine, so it evaluates against a frame of its
|
|
94
|
+
// own: the webhook payload, with no routine state or step results yet.
|
|
95
|
+
const { connectionProperties, requestProperties } = evaluateRequestOperators(context, {
|
|
96
|
+
connectionConfig,
|
|
97
|
+
requestConfig,
|
|
98
|
+
routineContext: operatorScope({
|
|
99
|
+
items: {},
|
|
100
|
+
payload,
|
|
101
|
+
state: {},
|
|
102
|
+
steps: {}
|
|
103
|
+
})
|
|
104
|
+
});
|
|
105
|
+
try {
|
|
106
|
+
const response = await callRequestResolver(context, {
|
|
107
|
+
connectionProperties,
|
|
108
|
+
endpointDepth: 0,
|
|
109
|
+
requestConfig,
|
|
110
|
+
requestProperties,
|
|
111
|
+
requestResolver,
|
|
112
|
+
tenant: tenancy.tenant,
|
|
113
|
+
tenantGuard: tenancy.tenantGuard
|
|
114
|
+
});
|
|
115
|
+
return response === true || type.isObject(response) && response.verified === true;
|
|
116
|
+
} catch (error) {
|
|
117
|
+
// An unreachable verification service is an outage, not a failed signature -
|
|
118
|
+
// swallowing it into a false verdict would report a forged webhook.
|
|
119
|
+
if (ServiceError.isServiceError(error) || error.name === 'ServiceError') {
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
context.logger.debug({
|
|
123
|
+
event: 'debug_webhook_verify_error',
|
|
124
|
+
err: error
|
|
125
|
+
}, error.message);
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
export default runWebhookVerify;
|
|
@@ -33,6 +33,16 @@ function scheduleBackground(context, { event, endpointId }, fn) {
|
|
|
33
33
|
status: result?.status
|
|
34
34
|
});
|
|
35
35
|
} catch (err) {
|
|
36
|
+
// A UserError is the caller's mistake, not a fault: warn level, as on
|
|
37
|
+
// every other call path.
|
|
38
|
+
if (err.name === 'UserError') {
|
|
39
|
+
logger.warn({
|
|
40
|
+
event: `${event}_failed`,
|
|
41
|
+
endpointId,
|
|
42
|
+
err
|
|
43
|
+
}, err.message);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
36
46
|
logger.error({
|
|
37
47
|
event: `${event}_failed`,
|
|
38
48
|
endpointId,
|
|
@@ -47,9 +47,22 @@ const mockTestRequestError = jest.fn((request)=>{
|
|
|
47
47
|
throw new Error(request.request.message);
|
|
48
48
|
});
|
|
49
49
|
const mockTestRequestWait = jest.fn((request)=>wait(request.request.ms));
|
|
50
|
+
// Waits `ms` and records how many of these requests were in flight at once (inFlight.max).
|
|
51
|
+
const inFlight = {
|
|
52
|
+
current: 0,
|
|
53
|
+
max: 0
|
|
54
|
+
};
|
|
55
|
+
const mockTestRequestInFlight = jest.fn(async (request)=>{
|
|
56
|
+
inFlight.current += 1;
|
|
57
|
+
inFlight.max = Math.max(inFlight.max, inFlight.current);
|
|
58
|
+
await wait(request.request.ms);
|
|
59
|
+
inFlight.current -= 1;
|
|
60
|
+
return request.request.response;
|
|
61
|
+
});
|
|
50
62
|
mockTestRequest.schema = {};
|
|
51
63
|
mockTestRequestError.schema = {};
|
|
52
64
|
mockTestRequestWait.schema = {};
|
|
65
|
+
mockTestRequestInFlight.schema = {};
|
|
53
66
|
mockTestRequest.meta = {
|
|
54
67
|
checkRead: false,
|
|
55
68
|
checkWrite: false
|
|
@@ -62,13 +75,18 @@ mockTestRequestWait.meta = {
|
|
|
62
75
|
checkRead: false,
|
|
63
76
|
checkWrite: false
|
|
64
77
|
};
|
|
78
|
+
mockTestRequestInFlight.meta = {
|
|
79
|
+
checkRead: false,
|
|
80
|
+
checkWrite: false
|
|
81
|
+
};
|
|
65
82
|
const connections = {
|
|
66
83
|
TestConnection: {
|
|
67
84
|
schema: {},
|
|
68
85
|
requests: {
|
|
69
86
|
TestRequest: mockTestRequest,
|
|
70
87
|
TestRequestError: mockTestRequestError,
|
|
71
|
-
TestRequestWait: mockTestRequestWait
|
|
88
|
+
TestRequestWait: mockTestRequestWait,
|
|
89
|
+
TestRequestInFlight: mockTestRequestInFlight
|
|
72
90
|
}
|
|
73
91
|
}
|
|
74
92
|
};
|
|
@@ -79,18 +97,17 @@ const logger = {
|
|
|
79
97
|
// error: console.error,
|
|
80
98
|
error: jest.fn()
|
|
81
99
|
};
|
|
82
|
-
function createTextContext(
|
|
100
|
+
function createTextContext({ user = {
|
|
101
|
+
id: 'id',
|
|
102
|
+
roles: []
|
|
103
|
+
} } = {}) {
|
|
83
104
|
const context = testContext({
|
|
84
105
|
connections,
|
|
85
106
|
operators,
|
|
86
107
|
logger,
|
|
87
108
|
readConfigFile: mockReadConfigFile,
|
|
88
109
|
secrets,
|
|
89
|
-
|
|
90
|
-
user: {
|
|
91
|
-
id: 'id'
|
|
92
|
-
}
|
|
93
|
-
}
|
|
110
|
+
user
|
|
94
111
|
});
|
|
95
112
|
context.blockId = 'blockId';
|
|
96
113
|
context.pageId = 'pageId';
|
|
@@ -98,8 +115,12 @@ function createTextContext() {
|
|
|
98
115
|
context.evaluateOperators = createEvaluateOperators(context);
|
|
99
116
|
return context;
|
|
100
117
|
}
|
|
101
|
-
async function runTest({ routine, payload = {} }) {
|
|
102
|
-
|
|
118
|
+
async function runTest({ routine, payload = {}, user }) {
|
|
119
|
+
inFlight.current = 0;
|
|
120
|
+
inFlight.max = 0;
|
|
121
|
+
const context = createTextContext({
|
|
122
|
+
user
|
|
123
|
+
});
|
|
103
124
|
const routineContext = {
|
|
104
125
|
steps: {},
|
|
105
126
|
payload,
|
|
@@ -118,4 +139,5 @@ async function runTest({ routine, payload = {} }) {
|
|
|
118
139
|
routineContext
|
|
119
140
|
};
|
|
120
141
|
}
|
|
142
|
+
export { inFlight };
|
|
121
143
|
export default runTest;
|
|
@@ -0,0 +1,144 @@
|
|
|
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 { compile } from '@lowdefy/ajv';
|
|
16
|
+
import { ConfigError, UserError } from '@lowdefy/errors';
|
|
17
|
+
import { cleanBuildArtifact, type } from '@lowdefy/helpers';
|
|
18
|
+
// Compiled validators keyed by the payloadSchema object: a dev rebuild re-reads
|
|
19
|
+
// the config file and yields a new object, so an edited schema is recompiled on
|
|
20
|
+
// its next call, while a stable production artifact compiles once. Keying by the
|
|
21
|
+
// object rather than the endpoint id also keeps two apps served by one process
|
|
22
|
+
// from sharing an entry.
|
|
23
|
+
const validators = new WeakMap();
|
|
24
|
+
function getValidator({ payloadSchema }) {
|
|
25
|
+
let validate = validators.get(payloadSchema);
|
|
26
|
+
if (!validate) {
|
|
27
|
+
// A schema ajv cannot compile throws here, on the first call - not swallowed.
|
|
28
|
+
validate = compile({
|
|
29
|
+
schema: cleanBuildArtifact(payloadSchema)
|
|
30
|
+
});
|
|
31
|
+
validators.set(payloadSchema, validate);
|
|
32
|
+
}
|
|
33
|
+
return validate;
|
|
34
|
+
}
|
|
35
|
+
// ajv (allErrors) reports every failing keyword, so a `type: [string, 'null']`
|
|
36
|
+
// with an `enum` reports the type miss first. These keywords say what would be
|
|
37
|
+
// accepted, so one of them wins over a `type` error on the same path; any other
|
|
38
|
+
// keyword keeps ajv's order.
|
|
39
|
+
const SPECIFIC_KEYWORDS = [
|
|
40
|
+
'enum',
|
|
41
|
+
'pattern',
|
|
42
|
+
'required',
|
|
43
|
+
'additionalProperties'
|
|
44
|
+
];
|
|
45
|
+
function pickError({ errors }) {
|
|
46
|
+
const first = errors[0];
|
|
47
|
+
if (first.keyword !== 'type') {
|
|
48
|
+
return first;
|
|
49
|
+
}
|
|
50
|
+
return errors.find((error)=>error.instancePath === first.instancePath && SPECIFIC_KEYWORDS.includes(error.keyword)) ?? first;
|
|
51
|
+
}
|
|
52
|
+
function formatValue(value) {
|
|
53
|
+
if (type.isString(value)) {
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
return JSON.stringify(value);
|
|
57
|
+
}
|
|
58
|
+
function additionalPropertyNames({ errors, instancePath }) {
|
|
59
|
+
return errors.filter((error)=>error.keyword === 'additionalProperties' && error.instancePath === instancePath).map((error)=>error.params.additionalProperty);
|
|
60
|
+
}
|
|
61
|
+
// ajv's pattern and required messages already name the pattern and the
|
|
62
|
+
// property; enum and additionalProperties messages name neither.
|
|
63
|
+
function describeError({ error, errors }) {
|
|
64
|
+
if (error.keyword === 'enum') {
|
|
65
|
+
return `${error.message} (${error.params.allowedValues.map(formatValue).join(', ')})`;
|
|
66
|
+
}
|
|
67
|
+
if (error.keyword === 'additionalProperties') {
|
|
68
|
+
const names = additionalPropertyNames({
|
|
69
|
+
errors,
|
|
70
|
+
instancePath: error.instancePath
|
|
71
|
+
});
|
|
72
|
+
return `${error.message} (${names.join(', ')})`;
|
|
73
|
+
}
|
|
74
|
+
return error.message;
|
|
75
|
+
}
|
|
76
|
+
// A `type` error on a path that also has a specific error is the same problem
|
|
77
|
+
// reported twice, and the listed additional properties are one problem.
|
|
78
|
+
function countFurtherProblems({ errors, chosen }) {
|
|
79
|
+
const specificPaths = new Set(errors.filter((error)=>SPECIFIC_KEYWORDS.includes(error.keyword)).map((error)=>error.instancePath));
|
|
80
|
+
return errors.filter((error)=>{
|
|
81
|
+
if (error === chosen) {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
if (error.keyword === 'type' && specificPaths.has(error.instancePath)) {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
return !(chosen.keyword === 'additionalProperties' && error.keyword === 'additionalProperties' && error.instancePath === chosen.instancePath);
|
|
88
|
+
}).length;
|
|
89
|
+
}
|
|
90
|
+
function buildErrorMessage({ endpointConfig, errors }) {
|
|
91
|
+
const chosen = pickError({
|
|
92
|
+
errors
|
|
93
|
+
});
|
|
94
|
+
const path = chosen.instancePath || '(root)';
|
|
95
|
+
let message = `Payload for endpoint "${endpointConfig.endpointId}" does not match its payloadSchema at ${path}: ${describeError({
|
|
96
|
+
error: chosen,
|
|
97
|
+
errors
|
|
98
|
+
})}.`;
|
|
99
|
+
const more = countFurtherProblems({
|
|
100
|
+
errors,
|
|
101
|
+
chosen
|
|
102
|
+
});
|
|
103
|
+
if (more > 0) {
|
|
104
|
+
message += ` (and ${more} more)`;
|
|
105
|
+
}
|
|
106
|
+
return message;
|
|
107
|
+
}
|
|
108
|
+
// A declared payloadSchema is enforced on every caller; the only way to not
|
|
109
|
+
// enforce it is to not declare one.
|
|
110
|
+
//
|
|
111
|
+
// Who built the payload decides whose mistake a refusal is. The app's own
|
|
112
|
+
// config (a page's CallAPI, a CallApi step, a schedule, a hook) building a
|
|
113
|
+
// payload its own endpoint refuses is a config fault: a ConfigError, logged as
|
|
114
|
+
// one, which fails a journey that hits it. An outside caller (an API client, an
|
|
115
|
+
// MCP client's model, an agent's model) sending the wrong shape is an expected
|
|
116
|
+
// outcome of its own request: a UserError, answered with the message it needs
|
|
117
|
+
// to correct the call and never logged at error level. The ajv error array
|
|
118
|
+
// survives as cause either way.
|
|
119
|
+
function validatePayload({ endpointConfig, payload, outsideCaller = false }) {
|
|
120
|
+
if (type.isNone(endpointConfig.payloadSchema)) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
const validate = getValidator({
|
|
124
|
+
payloadSchema: endpointConfig.payloadSchema
|
|
125
|
+
});
|
|
126
|
+
const { valid, errors } = validate(payload);
|
|
127
|
+
if (valid) {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
const message = buildErrorMessage({
|
|
131
|
+
endpointConfig,
|
|
132
|
+
errors
|
|
133
|
+
});
|
|
134
|
+
if (outsideCaller) {
|
|
135
|
+
throw new UserError(message, {
|
|
136
|
+
cause: errors
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
throw new ConfigError(message, {
|
|
140
|
+
cause: errors,
|
|
141
|
+
configKey: endpointConfig['~k']
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
export default validatePayload;
|
|
@@ -12,9 +12,9 @@
|
|
|
12
12
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
13
|
See the License for the specific language governing permissions and
|
|
14
14
|
limitations under the License.
|
|
15
|
-
*/ import {
|
|
15
|
+
*/ import { formatSchemaError } from '@lowdefy/ajv';
|
|
16
|
+
import { ConfigError, loadAndResolveErrorLocation } from '@lowdefy/errors';
|
|
16
17
|
import { serializer, type } from '@lowdefy/helpers';
|
|
17
|
-
import formatValidationError from './formatValidationError.js';
|
|
18
18
|
import validatePluginSchema from './validatePluginSchema.js';
|
|
19
19
|
const validationConfigs = {
|
|
20
20
|
BlockError: {
|
|
@@ -56,7 +56,7 @@ async function logClientError(context, serializedError) {
|
|
|
56
56
|
});
|
|
57
57
|
if (ajvErrors) {
|
|
58
58
|
const displayName = error.name === 'OperatorError' && error.methodName ? `${error.typeName}.${error.methodName}` : error.typeName;
|
|
59
|
-
const messages = ajvErrors.map((ajvError)=>
|
|
59
|
+
const messages = ajvErrors.map((ajvError)=>formatSchemaError({
|
|
60
60
|
ajvError,
|
|
61
61
|
pluginLabel: validationConfig.pluginLabel,
|
|
62
62
|
typeName: displayName,
|
|
@@ -74,10 +74,13 @@ async function logClientError(context, serializedError) {
|
|
|
74
74
|
logger.warn(e);
|
|
75
75
|
}
|
|
76
76
|
}
|
|
77
|
+
// The dev server's context reads its JIT page builds' maps as well; other
|
|
78
|
+
// servers have none and read keyMap.json and refMap.json.
|
|
77
79
|
const location = await loadAndResolveErrorLocation({
|
|
78
80
|
error,
|
|
79
81
|
readConfigFile: context.readConfigFile,
|
|
80
|
-
configDirectory: context.configDirectory
|
|
82
|
+
configDirectory: context.configDirectory,
|
|
83
|
+
readMaps: context.readMaps
|
|
81
84
|
});
|
|
82
85
|
if (location) {
|
|
83
86
|
error.source = location.source;
|