@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.
Files changed (208) hide show
  1. package/dist/context/applySystemTrust.js +45 -0
  2. package/dist/context/createApiContext.js +18 -3
  3. package/dist/context/createAuthorizeOutcome.js +91 -0
  4. package/dist/context/createBoundSystemContext.js +33 -0
  5. package/dist/context/createEvaluateOperators.js +10 -3
  6. package/dist/context/createRequestSignal.js +47 -0
  7. package/dist/context/createSystemContext.js +80 -0
  8. package/dist/context/getCanonicalUrl.js +27 -0
  9. package/dist/context/getCurrentEnvironment.js +27 -0
  10. package/dist/context/isSameOriginRequest.js +85 -0
  11. package/dist/context/isWebSocketOriginAllowed.js +63 -0
  12. package/dist/context/normalizeInjectedCaller.js +58 -0
  13. package/dist/context/parseRequestBody.js +32 -0
  14. package/dist/context/readMemberships.js +71 -0
  15. package/dist/context/resolveAuthentication.js +758 -0
  16. package/dist/context/resolveStrategyCaller.js +7 -3
  17. package/dist/csp/addNonceToElements.js +23 -0
  18. package/dist/csp/createContentSecurityPolicy.js +45 -0
  19. package/dist/csp/getWebSocketSources.js +36 -0
  20. package/dist/email/renderAuthEmail.js +99 -0
  21. package/dist/index.js +22 -5
  22. package/dist/response/buildEndpointResult.js +3 -1
  23. package/dist/response/createWireProjection.js +88 -0
  24. package/dist/response/formatErrorForAgent.js +35 -0
  25. package/dist/response/normalizeErrorSources.js +10 -13
  26. package/dist/response/redactErrorResponse.js +42 -8
  27. package/dist/response/redactResponse.js +17 -10
  28. package/dist/routes/agent/authorizeAgent.js +17 -5
  29. package/dist/routes/agent/callAgent.js +12 -2
  30. package/dist/routes/agent/collectChatFiles.js +39 -0
  31. package/dist/routes/agent/prepareAgent.js +29 -4
  32. package/dist/routes/auth/buildAdminPlugin.js +33 -0
  33. package/dist/routes/auth/buildCaptchaPlugin.js +61 -0
  34. package/dist/routes/auth/buildMcpTokenPlugin.js +77 -0
  35. package/dist/routes/auth/buildOauthPostLogin.js +73 -0
  36. package/dist/routes/auth/buildPhoneNumberPlugin.js +57 -0
  37. package/dist/routes/auth/buildProviders.js +61 -0
  38. package/dist/routes/auth/createAsMetadataHandler.js +27 -0
  39. package/dist/routes/auth/createAuthLogger.js +31 -0
  40. package/dist/routes/auth/createMcpAccessTokenClaims.js +52 -0
  41. package/dist/routes/auth/createOnAPIError.js +41 -0
  42. package/dist/routes/auth/createSendEmail.js +54 -0
  43. package/dist/routes/auth/ensureMcpTokenIndexes.js +48 -0
  44. package/dist/routes/auth/getAuthEnforcement.js +41 -0
  45. package/dist/routes/auth/getBetterAuth.js +107 -0
  46. package/dist/routes/auth/getBetterAuthConfig.js +767 -0
  47. package/dist/routes/auth/handleAuthRequest.js +43 -0
  48. package/dist/routes/auth/hooks/authHookPoints.js +204 -0
  49. package/dist/routes/auth/hooks/buildEngineHooks.js +68 -0
  50. package/dist/routes/auth/hooks/buildHooks.js +112 -0
  51. package/dist/routes/auth/{callbacks/addUserFieldsToSession.js → hooks/composeAfterSlot.js} +11 -13
  52. package/dist/routes/auth/hooks/composeBeforeSlot.js +41 -0
  53. package/dist/routes/auth/hooks/createHookDispatch.js +59 -0
  54. package/dist/routes/auth/hooks/createUserAfterHook.js +36 -0
  55. package/dist/routes/auth/hooks/createUserBeforeHook.js +50 -0
  56. package/dist/routes/auth/hooks/findHookUser.js +27 -0
  57. package/dist/routes/auth/modelNames.js +30 -0
  58. package/dist/routes/auth/organizations/OrganizationKeyError.js +28 -0
  59. package/dist/routes/auth/organizations/authorizeRole.js +27 -0
  60. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +178 -0
  61. package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +57 -0
  62. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +120 -0
  63. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +403 -0
  64. package/dist/routes/auth/organizations/createAdmissionGateHook.js +50 -0
  65. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +90 -0
  66. package/dist/routes/auth/organizations/createAutoJoinHook.js +68 -0
  67. package/dist/routes/auth/organizations/createEmailSendGate.js +59 -0
  68. package/dist/routes/auth/organizations/createExpiredInvitationGate.js +76 -0
  69. package/dist/routes/auth/organizations/ensureAuthIndexes.js +122 -0
  70. package/dist/routes/auth/organizations/ensureOrganization.js +132 -0
  71. package/dist/routes/auth/organizations/findPendingInvitation.js +43 -0
  72. package/dist/routes/auth/organizations/getHookRequestHeaders.js +24 -0
  73. package/dist/routes/auth/organizations/getOrganizationBinding.js +65 -0
  74. package/dist/routes/auth/organizations/isEmailAdmitted.js +89 -0
  75. package/dist/routes/auth/organizations/organizationAccessControl.js +94 -0
  76. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +62 -0
  77. package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +145 -0
  78. package/dist/routes/auth/requestHooks/buildRequestHooks.js +288 -0
  79. package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +43 -0
  80. package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +59 -0
  81. package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +47 -0
  82. package/dist/routes/auth/requestHooks/redirectToChallenge.js +79 -0
  83. package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +31 -0
  84. package/dist/routes/auth/resolveCookiePrefix.js +30 -0
  85. package/dist/routes/auth/sanitizeSessionResponse.js +27 -0
  86. package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
  87. package/dist/routes/connections/checkUnwalledReach.js +37 -0
  88. package/dist/routes/connections/getConnectionConfig.js +6 -1
  89. package/dist/routes/connections/resolveTenantPreflight.js +226 -0
  90. package/dist/routes/connections/resolveUnwalledReach.js +144 -0
  91. package/dist/routes/endpoints/acceptDetachedEndpoint.js +50 -0
  92. package/dist/routes/endpoints/authorizeApiEndpoint.js +13 -4
  93. package/dist/routes/endpoints/callEndpoint.js +23 -7
  94. package/dist/routes/endpoints/control/controlFor.js +4 -7
  95. package/dist/routes/endpoints/control/controlIf.js +4 -8
  96. package/dist/routes/endpoints/control/controlLog.js +6 -14
  97. package/dist/routes/endpoints/control/controlParallelFor.js +65 -29
  98. package/dist/routes/endpoints/control/controlReject.js +36 -16
  99. package/dist/routes/endpoints/control/controlReturn.js +32 -9
  100. package/dist/routes/endpoints/control/controlSetState.js +4 -8
  101. package/dist/routes/endpoints/control/controlSwitch.js +4 -8
  102. package/dist/routes/endpoints/control/controlThrow.js +20 -21
  103. package/dist/routes/endpoints/control/controlTry.js +30 -11
  104. package/dist/routes/endpoints/control/controlWhile.js +55 -0
  105. package/dist/routes/endpoints/control/handleControl.js +3 -1
  106. package/dist/routes/endpoints/createWebhookAnswer.js +78 -0
  107. package/dist/routes/endpoints/evaluateRoutineOperators.js +27 -0
  108. package/dist/routes/endpoints/forwardScheduledEndpoint.js +21 -15
  109. package/dist/routes/endpoints/getEndpointConfig.js +18 -8
  110. package/dist/routes/endpoints/getEnvironmentSchedules.js +5 -7
  111. package/dist/routes/endpoints/getSchemaValidator.js +39 -0
  112. package/dist/routes/endpoints/handleAgentCall.js +25 -9
  113. package/dist/routes/endpoints/handleAuthStep.js +214 -0
  114. package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
  115. package/dist/routes/endpoints/handleEndpointCall.js +46 -12
  116. package/dist/routes/endpoints/handleRenderNotification.js +29 -12
  117. package/dist/routes/endpoints/handleRequest.js +13 -6
  118. package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
  119. package/dist/routes/endpoints/handleValidateSchema.js +22 -22
  120. package/dist/routes/endpoints/invokeEndpoint.js +27 -3
  121. package/dist/routes/endpoints/operatorScope.js +28 -0
  122. package/dist/routes/{auth/events/createEventPlugins.js → endpoints/parseWebhookBody.js} +10 -6
  123. package/dist/routes/endpoints/resolveCallBinding.js +91 -0
  124. package/dist/routes/endpoints/resolveCronEnvironment.js +7 -6
  125. package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
  126. package/dist/routes/endpoints/runDetachedEndpoint.js +64 -18
  127. package/dist/routes/endpoints/runRoutine.js +64 -5
  128. package/dist/routes/endpoints/runScheduledEndpoint.js +19 -11
  129. package/dist/routes/endpoints/runWebhookEndpoint.js +70 -23
  130. package/dist/routes/endpoints/runWebhookVerify.js +129 -0
  131. package/dist/routes/endpoints/scheduleBackground.js +10 -0
  132. package/dist/routes/endpoints/test/runTest.js +48 -11
  133. package/dist/routes/endpoints/validatePayload.js +144 -0
  134. package/dist/routes/log/logClientError.js +7 -4
  135. package/dist/routes/mcp/createMcpServer.js +143 -64
  136. package/dist/routes/mcp/getMcpJwks.js +93 -0
  137. package/dist/routes/mcp/getMcpResourceBinding.js +41 -0
  138. package/dist/routes/mcp/getMcpUri.js +69 -0
  139. package/dist/routes/mcp/oauthResourceLifecycle.js +122 -0
  140. package/dist/routes/mcp/runAfterToolCall.js +50 -0
  141. package/dist/routes/notifications/resolveNotificationLinks.js +39 -11
  142. package/dist/routes/page/dynamic/checkDynamicContent.js +81 -0
  143. package/dist/routes/page/dynamic/checkLiteralContent.js +242 -0
  144. package/dist/routes/page/dynamic/createContentError.js +34 -0
  145. package/dist/routes/page/dynamic/flagIconsOutsidePage.js +39 -0
  146. package/dist/routes/page/dynamic/flagTypesOutsidePage.js +44 -0
  147. package/dist/routes/page/dynamic/getPropertiesSchemaErrors.js +35 -0
  148. package/dist/routes/page/dynamic/loadDynamicArtifacts.js +52 -0
  149. package/dist/routes/page/dynamic/policy/checkAction.js +204 -0
  150. package/dist/routes/page/dynamic/policy/checkEvents.js +163 -0
  151. package/dist/routes/page/dynamic/policy/checkPolicy.js +313 -0
  152. package/dist/routes/page/dynamic/policy/checkValue.js +214 -0
  153. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +117 -0
  154. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +54 -0
  155. package/dist/routes/page/dynamic/policy/findSerializerKeys.js +50 -0
  156. package/dist/routes/page/dynamic/policy/isAllowedUrl.js +53 -0
  157. package/dist/routes/{auth/createAdapter.js → page/dynamic/policy/isUnderState.js} +5 -9
  158. package/dist/routes/page/dynamic/policy/normalizeUrlText.js +25 -0
  159. package/dist/routes/page/dynamic/resolveDynamicContent.js +89 -37
  160. package/dist/routes/page/dynamic/unescapeOperators.js +21 -4
  161. package/dist/routes/page/dynamic/validateFragment.js +17 -58
  162. package/dist/routes/page/getPageConfig.js +76 -6
  163. package/dist/routes/request/authorizeRequest.js +21 -6
  164. package/dist/routes/request/callRequest.js +21 -3
  165. package/dist/routes/request/callRequestResolver.js +55 -6
  166. package/dist/routes/request/checkConnectionRead.js +1 -1
  167. package/dist/routes/request/checkConnectionWrite.js +1 -1
  168. package/dist/routes/request/createWalledResolver.js +75 -0
  169. package/dist/routes/request/evaluateOperators.js +8 -12
  170. package/dist/routes/request/getRequestConfig.js +19 -3
  171. package/dist/routes/request/maskCredentialProperties.js +34 -0
  172. package/dist/routes/request/resolveTenancy.js +223 -0
  173. package/dist/routes/request/validateSchemas.js +7 -6
  174. package/dist/routes/{auth/callbacks/createCallbackPlugins.js → rootConfig/getAppEvents.js} +7 -6
  175. package/dist/routes/rootConfig/getHomeAndMenus.js +23 -16
  176. package/dist/routes/{auth/events/createSessionEvent.js → rootConfig/getPagePaths.js} +16 -18
  177. package/dist/routes/rootConfig/getRootConfig.js +9 -3
  178. package/dist/routes/rootConfig/menus/filterMenuList.js +5 -2
  179. package/dist/routes/websocket/authorizeWebsocket.js +19 -4
  180. package/dist/routes/websocket/createChannelRegistry.js +39 -14
  181. package/dist/routes/websocket/createWebSocketConnection.js +162 -28
  182. package/dist/routes/websocket/getCallerFingerprint.js +31 -0
  183. package/dist/routes/websocket/prepareChannel.js +29 -1
  184. package/dist/routes/websocket/resolveWebsocketCaller.js +40 -0
  185. package/dist/test/testContext.js +16 -11
  186. package/package.json +28 -12
  187. package/dist/context/createAuthorize.js +0 -45
  188. package/dist/response/omitErrorProps.js +0 -51
  189. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +0 -30
  190. package/dist/routes/auth/callbacks/createCallbacks.js +0 -46
  191. package/dist/routes/auth/callbacks/createJWTCallback.js +0 -77
  192. package/dist/routes/auth/callbacks/createRedirectCallback.js +0 -41
  193. package/dist/routes/auth/callbacks/createSessionCallback.js +0 -81
  194. package/dist/routes/auth/callbacks/createSignInCallback.js +0 -40
  195. package/dist/routes/auth/callbacks/validateSessionRoles.js +0 -33
  196. package/dist/routes/auth/createLogger.js +0 -35
  197. package/dist/routes/auth/createPrefixedCookies.js +0 -52
  198. package/dist/routes/auth/createProviders.js +0 -25
  199. package/dist/routes/auth/events/createCreateUserEvent.js +0 -41
  200. package/dist/routes/auth/events/createEvents.js +0 -56
  201. package/dist/routes/auth/events/createLinkAccountEvent.js +0 -43
  202. package/dist/routes/auth/events/createSignInEvent.js +0 -46
  203. package/dist/routes/auth/events/createSignOutEvent.js +0 -43
  204. package/dist/routes/auth/events/createUpdateUserEvent.js +0 -41
  205. package/dist/routes/auth/getAuthConfig.js +0 -86
  206. package/dist/routes/auth/resolveCookies.js +0 -37
  207. package/dist/routes/log/formatValidationError.js +0 -31
  208. /package/dist/{routes/notifications → email}/resolveThemeLogo.js +0 -0
@@ -1,4 +1,18 @@
1
- import { jest } from '@jest/globals';
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 { jest } from '@jest/globals';
2
16
  import { wait } from '@lowdefy/helpers';
3
17
  import { operatorsServer } from '@lowdefy/operators-js';
4
18
  import createEvaluateOperators from '../../../context/createEvaluateOperators.js';
@@ -7,7 +21,7 @@ import testContext from '../../../test/testContext.js';
7
21
  // const { _date, _eq, _payload, _secret, _user } = operatorsServer;
8
22
  const operators = {
9
23
  ...operatorsServer,
10
- _error: ()=>{
24
+ _throw_test: ()=>{
11
25
  throw new Error('Test error.');
12
26
  }
13
27
  };
@@ -33,9 +47,22 @@ const mockTestRequestError = jest.fn((request)=>{
33
47
  throw new Error(request.request.message);
34
48
  });
35
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
+ });
36
62
  mockTestRequest.schema = {};
37
63
  mockTestRequestError.schema = {};
38
64
  mockTestRequestWait.schema = {};
65
+ mockTestRequestInFlight.schema = {};
39
66
  mockTestRequest.meta = {
40
67
  checkRead: false,
41
68
  checkWrite: false
@@ -48,13 +75,18 @@ mockTestRequestWait.meta = {
48
75
  checkRead: false,
49
76
  checkWrite: false
50
77
  };
78
+ mockTestRequestInFlight.meta = {
79
+ checkRead: false,
80
+ checkWrite: false
81
+ };
51
82
  const connections = {
52
83
  TestConnection: {
53
84
  schema: {},
54
85
  requests: {
55
86
  TestRequest: mockTestRequest,
56
87
  TestRequestError: mockTestRequestError,
57
- TestRequestWait: mockTestRequestWait
88
+ TestRequestWait: mockTestRequestWait,
89
+ TestRequestInFlight: mockTestRequestInFlight
58
90
  }
59
91
  }
60
92
  };
@@ -65,18 +97,17 @@ const logger = {
65
97
  // error: console.error,
66
98
  error: jest.fn()
67
99
  };
68
- function createTextContext() {
100
+ function createTextContext({ user = {
101
+ id: 'id',
102
+ roles: []
103
+ } } = {}) {
69
104
  const context = testContext({
70
105
  connections,
71
106
  operators,
72
107
  logger,
73
108
  readConfigFile: mockReadConfigFile,
74
109
  secrets,
75
- session: {
76
- user: {
77
- id: 'id'
78
- }
79
- }
110
+ user
80
111
  });
81
112
  context.blockId = 'blockId';
82
113
  context.pageId = 'pageId';
@@ -84,11 +115,16 @@ function createTextContext() {
84
115
  context.evaluateOperators = createEvaluateOperators(context);
85
116
  return context;
86
117
  }
87
- async function runTest({ routine, payload = {} }) {
88
- const context = createTextContext();
118
+ async function runTest({ routine, payload = {}, user }) {
119
+ inFlight.current = 0;
120
+ inFlight.max = 0;
121
+ const context = createTextContext({
122
+ user
123
+ });
89
124
  const routineContext = {
90
125
  steps: {},
91
126
  payload,
127
+ error: null,
92
128
  items: {},
93
129
  arrayIndices: [],
94
130
  state: {},
@@ -103,4 +139,5 @@ async function runTest({ routine, payload = {} }) {
103
139
  routineContext
104
140
  };
105
141
  }
142
+ export { inFlight };
106
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 { ConfigError, loadAndResolveErrorLocation } from '@lowdefy/errors';
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)=>formatValidationError({
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;
@@ -14,35 +14,62 @@
14
14
  limitations under the License.
15
15
  */ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
16
16
  import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
17
- import { AuthenticationError } from '@lowdefy/errors';
18
- import { serializer, type } from '@lowdefy/helpers';
17
+ import { cleanBuildArtifact, serializer, type } from '@lowdefy/helpers';
18
+ import formatErrorForAgent from '../../response/formatErrorForAgent.js';
19
19
  import callEndpoint from '../endpoints/callEndpoint.js';
20
- import isUnauthenticatedHuman from '../endpoints/isUnauthenticatedHuman.js';
20
+ import runAfterToolCall from './runAfterToolCall.js';
21
21
  // LLM-safe tool names use the same rule as buildAgents tool naming.
22
22
  function toToolName(id) {
23
23
  return id.replaceAll('/', '__');
24
24
  }
25
- // Twin of cleanBuildArtifact in packages/utils/ai-utils/src/buildAgentTools.js -
26
- // duplicated here rather than shared, since pulling in @lowdefy/ai-utils would
27
- // add the ai SDK and MCP client deps to api just for this. Strips build-artifact
28
- // serializer markers (~k, ~r, ~l) and unwraps { '~arr': [...] } back to a plain
29
- // array, so payloadSchema reaches MCP clients as plain JSON Schema.
30
- function cleanBuildArtifact(obj) {
31
- return JSON.parse(JSON.stringify(serializer.deserialize(obj)));
25
+ // Whether the caller's token grant covers an endpoint's scope tag, over the
26
+ // closed vocabulary (mcp:read, mcp:write) with mcp:write implying mcp:read.
27
+ // An undefined grant is a caller with no token: consent never happened, so
28
+ // there is nothing to filter on - the authorization outcome alone limits them
29
+ // to public tools. An empty grant is the opposite: consent happened and
30
+ // granted this client nothing on this surface, so it covers no scope.
31
+ function scopeCovers({ grantedScopes, endpointScope }) {
32
+ if (type.isUndefined(grantedScopes)) {
33
+ return true;
34
+ }
35
+ if (endpointScope === 'mcp:write') {
36
+ return grantedScopes.includes('mcp:write');
37
+ }
38
+ return grantedScopes.includes('mcp:read') || grantedScopes.includes('mcp:write');
32
39
  }
33
40
  // A stateless per-request MCP server exposing the configured api endpoints
34
41
  // as tools. Built with the SDK's low-level Server: tool input schemas are
35
42
  // config-provided JSON Schema (payloadSchema), which the low-level handlers
36
43
  // accept directly - no zod conversion. The server is constructed with the
37
- // request's context, so the caller is known at construction time: tools/list
38
- // filters by context.authorize, and tools/call re-authorizes inside
39
- // callEndpoint (defense in depth). Returns null when no mcp block is
40
- // configured.
44
+ // request's context, so the caller is known at construction time: a tool is
45
+ // visible only when the authorization outcome is 'allow' AND the caller's
46
+ // token grant covers the endpoint's scope tag. tools/call re-applies both
47
+ // checks before dispatch - callEndpoint re-authorizes roles inside, but the
48
+ // scope filter exists only on this surface. Returns null when no mcp block
49
+ // is configured.
41
50
  async function createMcpServer({ context }) {
42
51
  const mcpConfig = await context.readConfigFile('mcp.json');
43
52
  if (type.isNone(mcpConfig) || mcpConfig.configured !== true) {
44
53
  return null;
45
54
  }
55
+ async function readVisibleEndpointConfig({ id, scope }) {
56
+ const endpointConfig = await context.readConfigFile(`api/${id}.json`);
57
+ if (type.isNone(endpointConfig)) {
58
+ return null;
59
+ }
60
+ // 'deny' and 'enrol_required' both hide the tool - an unenrolled member
61
+ // must not see an enrolment redirect leak which tools exist for them.
62
+ if (context.authorizeOutcome(endpointConfig) !== 'allow') {
63
+ return null;
64
+ }
65
+ if (!scopeCovers({
66
+ grantedScopes: context.mcpAuth?.grantedScopes,
67
+ endpointScope: scope
68
+ })) {
69
+ return null;
70
+ }
71
+ return endpointConfig;
72
+ }
46
73
  // serverInfo doubles as the connector card in clients such as claude.ai:
47
74
  // title, websiteUrl and icons are optional branding the app may configure,
48
75
  // and are omitted (not sent as undefined) when it does not. icons is config
@@ -63,23 +90,34 @@ async function createMcpServer({ context }) {
63
90
  if (!type.isNone(mcpConfig.icons)) {
64
91
  serverInfo.icons = cleanBuildArtifact(mcpConfig.icons);
65
92
  }
66
- const server = new Server(serverInfo, {
93
+ const serverOptions = {
67
94
  capabilities: {
68
95
  tools: {}
69
96
  }
70
- });
97
+ };
98
+ if (!type.isNone(mcpConfig.instructions)) {
99
+ serverOptions.instructions = mcpConfig.instructions;
100
+ }
101
+ const server = new Server(serverInfo, serverOptions);
71
102
  server.setRequestHandler(ListToolsRequestSchema, async ()=>{
72
103
  const tools = [];
73
- for (const endpointId of mcpConfig.endpoints){
74
- const endpointConfig = await context.readConfigFile(`api/${endpointId}.json`);
75
- if (type.isNone(endpointConfig) || !context.authorize(endpointConfig)) {
104
+ for (const { id, scope, annotations } of mcpConfig.endpoints){
105
+ const endpointConfig = await readVisibleEndpointConfig({
106
+ id,
107
+ scope
108
+ });
109
+ if (type.isNone(endpointConfig)) {
76
110
  continue;
77
111
  }
78
- tools.push({
79
- name: toToolName(endpointId),
112
+ const tool = {
113
+ name: toToolName(id),
80
114
  description: endpointConfig.description,
81
115
  inputSchema: cleanBuildArtifact(endpointConfig.payloadSchema)
82
- });
116
+ };
117
+ if (!type.isNone(annotations)) {
118
+ tool.annotations = cleanBuildArtifact(annotations);
119
+ }
120
+ tools.push(tool);
83
121
  }
84
122
  return {
85
123
  tools
@@ -91,64 +129,104 @@ async function createMcpServer({ context }) {
91
129
  event: 'mcp_tool_call',
92
130
  tool: name
93
131
  });
94
- const endpointId = mcpConfig.endpoints.find((id)=>toToolName(id) === name);
95
- try {
96
- if (!type.isNone(endpointId)) {
97
- const { error, response, success } = await callEndpoint(context, {
98
- blockId: '_mcp',
99
- endpointId,
100
- pageId: '_mcp',
101
- payload: args ?? {}
102
- });
103
- if (!success) {
104
- const deserialized = serializer.deserialize(error);
105
- return {
106
- content: [
107
- {
108
- type: 'text',
109
- text: deserialized?.message ?? 'Endpoint failed.'
110
- }
111
- ],
112
- isError: true
113
- };
132
+ // A role or scope shortfall answers exactly like a name that does not
133
+ // exist: any distinguishable error would let a caller enumerate which
134
+ // gated tools this app has. Same reason it is isError content over 200,
135
+ // not an HTTP status.
136
+ const unknownTool = {
137
+ content: [
138
+ {
139
+ type: 'text',
140
+ text: `Unknown tool "${name}".`
114
141
  }
115
- return {
142
+ ],
143
+ isError: true
144
+ };
145
+ const endpoint = (mcpConfig.endpoints ?? []).find(({ id })=>toToolName(id) === name);
146
+ if (type.isNone(endpoint)) {
147
+ return unknownTool;
148
+ }
149
+ try {
150
+ const endpointConfig = await readVisibleEndpointConfig({
151
+ id: endpoint.id,
152
+ scope: endpoint.scope
153
+ });
154
+ if (type.isNone(endpointConfig)) {
155
+ return unknownTool;
156
+ }
157
+ const payload = args ?? {};
158
+ const { error, response, success } = await callEndpoint(context, {
159
+ blockId: '_mcp',
160
+ endpointId: endpoint.id,
161
+ outsideCaller: true,
162
+ pageId: '_mcp',
163
+ payload
164
+ });
165
+ const deserializedResponse = success ? serializer.deserialize(response) : null;
166
+ let reply;
167
+ if (success) {
168
+ reply = {
116
169
  content: [
117
170
  {
118
171
  type: 'text',
119
- text: JSON.stringify(serializer.deserialize(response))
172
+ text: JSON.stringify(deserializedResponse)
120
173
  }
121
174
  ]
122
175
  };
176
+ } else {
177
+ const deserialized = serializer.deserialize(error);
178
+ // The wire error is generic for every reader. The dev server also attaches the full
179
+ // error for dev tools, and the dev MCP client is a coding agent that needs it to find
180
+ // the failing config.
181
+ const devError = serializer.deserialize(error?.devError);
182
+ reply = {
183
+ content: [
184
+ {
185
+ type: 'text',
186
+ text: type.isNone(deserialized) ? 'Endpoint failed.' : formatErrorForAgent(context, devError ?? deserialized)
187
+ }
188
+ ],
189
+ isError: true
190
+ };
123
191
  }
124
- // An unknown tool answers like a gated one for an anonymous caller on an
125
- // auth'd app, so tools/call cannot be used to enumerate tool names that
126
- // tools/list already hides from that caller.
127
- if (await isUnauthenticatedHuman(context)) {
128
- throw new AuthenticationError(`Authentication required for API endpoint "${name}".`);
129
- }
130
- return {
131
- content: [
132
- {
133
- type: 'text',
134
- text: `Unknown tool "${name}".`
192
+ // Only a call that reached its endpoint's routine runs the hook: the
193
+ // early returns above and the refusals caught below never do.
194
+ if (!type.isNone(mcpConfig.afterToolCall)) {
195
+ await runAfterToolCall(context, {
196
+ hookId: mcpConfig.afterToolCall,
197
+ payload: {
198
+ tool: name,
199
+ endpoint_id: endpoint.id,
200
+ scope: endpoint.scope,
201
+ payload,
202
+ success,
203
+ response: deserializedResponse
135
204
  }
136
- ],
137
- isError: true
138
- };
205
+ });
206
+ }
207
+ return reply;
139
208
  } catch (error) {
140
- // Unauthenticated calls to gated tools are expected probing traffic -
141
- // a warn line and the 401-shaped message, not a structured error log.
142
- if (error.name === 'AuthenticationError') {
143
- context.logger.warn(`Unauthenticated MCP tool call: ${name}`);
209
+ // Refused calls to gated tools and payloads that miss the payloadSchema
210
+ // (UserError) are expected traffic - a warn line and the message the
211
+ // model needs to retry, not a structured error log. Everything else
212
+ // goes through the server's error sink, which resolves the config
213
+ // source, logs it and collects it for the dev feedback channel.
214
+ if ([
215
+ 'AuthenticationError',
216
+ 'AuthorizationError',
217
+ 'TwoFactorEnrolmentRequiredError'
218
+ ].includes(error.name)) {
219
+ context.logger.warn(`Refused MCP tool call: ${name} - ${error.message}`);
220
+ } else if (error.name === 'UserError') {
221
+ context.logger.warn(`Refused MCP tool call: ${name} - ${error.message}`);
144
222
  } else {
145
- context.logger.error(error);
223
+ await context.handleError(error);
146
224
  }
147
225
  return {
148
226
  content: [
149
227
  {
150
228
  type: 'text',
151
- text: error.message
229
+ text: formatErrorForAgent(context, error)
152
230
  }
153
231
  ],
154
232
  isError: true
@@ -158,3 +236,4 @@ async function createMcpServer({ context }) {
158
236
  return server;
159
237
  }
160
238
  export default createMcpServer;
239
+ export { scopeCovers };
@@ -0,0 +1,93 @@
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 { createLocalJWKSet } from 'jose';
16
+ import { type } from '@lowdefy/helpers';
17
+ // Verification keys for MCP access tokens, read in-process from the jwks
18
+ // rows the core jwt plugin persists - the same rows /api/auth/jwks serves.
19
+ // Reading through the adapter keeps token verification free of a self-HTTP
20
+ // dependency: the server never needs to reach its own public origin to
21
+ // authenticate a request. Only the publicKey column is read - it is the
22
+ // plaintext JSON-serialized public JWK, while privateKey is encrypted with
23
+ // the BetterAuth secret and never needed for verification. The row id is
24
+ // the kid the plugin stamps on every token it signs.
25
+ // Mirrors the served JWKS: rows persisted before the alg column existed
26
+ // default to the plugin's EdDSA, and a rotated key stays servable for the
27
+ // plugin's 30-day grace window so tokens signed just before rotation still
28
+ // verify until they expire.
29
+ const DEFAULT_ALG = 'EdDSA';
30
+ const ROTATION_GRACE_MS = 30 * 24 * 3600 * 1000;
31
+ const resolverByAuth = new WeakMap();
32
+ async function loadKeySet({ auth }) {
33
+ const { adapter } = await auth.$context;
34
+ const rows = await adapter.findMany({
35
+ model: 'jwks'
36
+ });
37
+ const now = Date.now();
38
+ const keys = (rows ?? []).filter((row)=>type.isNone(row.expiresAt) || new Date(row.expiresAt).getTime() + ROTATION_GRACE_MS > now).map((row)=>({
39
+ alg: row.alg ?? DEFAULT_ALG,
40
+ ...type.isNone(row.crv) ? {} : {
41
+ crv: row.crv
42
+ },
43
+ ...JSON.parse(row.publicKey),
44
+ kid: row.id
45
+ }));
46
+ return createLocalJWKSet({
47
+ keys
48
+ });
49
+ }
50
+ function createKeyResolver({ auth }) {
51
+ let keySetPromise = null;
52
+ function load() {
53
+ if (keySetPromise === null) {
54
+ // A failed load is never cached - a transient adapter error must not
55
+ // poison the resolver until restart.
56
+ keySetPromise = loadKeySet({
57
+ auth
58
+ }).catch((error)=>{
59
+ keySetPromise = null;
60
+ throw error;
61
+ });
62
+ }
63
+ return keySetPromise;
64
+ }
65
+ return async function resolveMcpKey(protectedHeader, token) {
66
+ const keySet = await load();
67
+ try {
68
+ return await keySet(protectedHeader, token);
69
+ } catch (error) {
70
+ if (error?.code !== 'ERR_JWKS_NO_MATCHING_KEY') {
71
+ throw error;
72
+ }
73
+ // An unknown kid can be a freshly rotated key this process has not
74
+ // seen - refetch once so rotation never strands verification.
75
+ keySetPromise = null;
76
+ const refreshed = await load();
77
+ return refreshed(protectedHeader, token);
78
+ }
79
+ };
80
+ }
81
+ // Returns a jose key resolver, cached per auth instance for the life of the
82
+ // process alongside the instance itself.
83
+ function getMcpJwks({ auth }) {
84
+ let resolver = resolverByAuth.get(auth);
85
+ if (resolver === undefined) {
86
+ resolver = createKeyResolver({
87
+ auth
88
+ });
89
+ resolverByAuth.set(auth, resolver);
90
+ }
91
+ return resolver;
92
+ }
93
+ export default getMcpJwks;