@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.
Files changed (195) 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 +8 -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/isSameOriginRequest.js +85 -0
  10. package/dist/context/isWebSocketOriginAllowed.js +63 -0
  11. package/dist/context/normalizeInjectedCaller.js +58 -0
  12. package/dist/context/parseRequestBody.js +32 -0
  13. package/dist/context/readMemberships.js +71 -0
  14. package/dist/context/resolveAuthentication.js +758 -0
  15. package/dist/context/resolveStrategyCaller.js +7 -3
  16. package/dist/csp/addNonceToElements.js +23 -0
  17. package/dist/csp/createContentSecurityPolicy.js +45 -0
  18. package/dist/csp/getWebSocketSources.js +36 -0
  19. package/dist/email/renderAuthEmail.js +99 -0
  20. package/dist/index.js +21 -5
  21. package/dist/response/formatErrorForAgent.js +35 -0
  22. package/dist/response/redactResponse.js +8 -1
  23. package/dist/routes/agent/authorizeAgent.js +17 -5
  24. package/dist/routes/agent/callAgent.js +12 -2
  25. package/dist/routes/agent/collectChatFiles.js +39 -0
  26. package/dist/routes/agent/prepareAgent.js +23 -4
  27. package/dist/routes/auth/buildAdminPlugin.js +33 -0
  28. package/dist/routes/auth/buildCaptchaPlugin.js +61 -0
  29. package/dist/routes/auth/buildMcpTokenPlugin.js +77 -0
  30. package/dist/routes/auth/buildOauthPostLogin.js +73 -0
  31. package/dist/routes/auth/buildPhoneNumberPlugin.js +57 -0
  32. package/dist/routes/auth/buildProviders.js +61 -0
  33. package/dist/routes/auth/createAsMetadataHandler.js +27 -0
  34. package/dist/routes/auth/createAuthLogger.js +31 -0
  35. package/dist/routes/auth/createMcpAccessTokenClaims.js +52 -0
  36. package/dist/routes/auth/createOnAPIError.js +41 -0
  37. package/dist/routes/auth/createSendEmail.js +54 -0
  38. package/dist/routes/auth/ensureMcpTokenIndexes.js +48 -0
  39. package/dist/routes/auth/getAuthEnforcement.js +41 -0
  40. package/dist/routes/auth/getBetterAuth.js +107 -0
  41. package/dist/routes/auth/getBetterAuthConfig.js +767 -0
  42. package/dist/routes/auth/handleAuthRequest.js +43 -0
  43. package/dist/routes/auth/hooks/authHookPoints.js +204 -0
  44. package/dist/routes/auth/hooks/buildEngineHooks.js +68 -0
  45. package/dist/routes/auth/hooks/buildHooks.js +112 -0
  46. package/dist/routes/auth/{callbacks/addUserFieldsToSession.js → hooks/composeAfterSlot.js} +11 -13
  47. package/dist/routes/auth/hooks/composeBeforeSlot.js +41 -0
  48. package/dist/routes/auth/hooks/createHookDispatch.js +59 -0
  49. package/dist/routes/auth/hooks/createUserAfterHook.js +36 -0
  50. package/dist/routes/auth/hooks/createUserBeforeHook.js +50 -0
  51. package/dist/routes/auth/hooks/findHookUser.js +27 -0
  52. package/dist/routes/auth/modelNames.js +30 -0
  53. package/dist/routes/auth/organizations/OrganizationKeyError.js +28 -0
  54. package/dist/routes/auth/organizations/authorizeRole.js +27 -0
  55. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +178 -0
  56. package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +57 -0
  57. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +120 -0
  58. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +403 -0
  59. package/dist/routes/auth/organizations/createAdmissionGateHook.js +50 -0
  60. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +90 -0
  61. package/dist/routes/auth/organizations/createAutoJoinHook.js +68 -0
  62. package/dist/routes/auth/organizations/createEmailSendGate.js +59 -0
  63. package/dist/routes/auth/organizations/createExpiredInvitationGate.js +76 -0
  64. package/dist/routes/auth/organizations/ensureAuthIndexes.js +122 -0
  65. package/dist/routes/auth/organizations/ensureOrganization.js +132 -0
  66. package/dist/routes/auth/organizations/findPendingInvitation.js +43 -0
  67. package/dist/routes/auth/organizations/getHookRequestHeaders.js +24 -0
  68. package/dist/routes/auth/organizations/getOrganizationBinding.js +65 -0
  69. package/dist/routes/auth/organizations/isEmailAdmitted.js +89 -0
  70. package/dist/routes/auth/organizations/organizationAccessControl.js +94 -0
  71. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +62 -0
  72. package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +145 -0
  73. package/dist/routes/auth/requestHooks/buildRequestHooks.js +288 -0
  74. package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +43 -0
  75. package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +59 -0
  76. package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +47 -0
  77. package/dist/routes/auth/requestHooks/redirectToChallenge.js +79 -0
  78. package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +31 -0
  79. package/dist/routes/auth/resolveCookiePrefix.js +30 -0
  80. package/dist/routes/auth/sanitizeSessionResponse.js +27 -0
  81. package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
  82. package/dist/routes/connections/checkUnwalledReach.js +37 -0
  83. package/dist/routes/connections/getConnectionConfig.js +6 -1
  84. package/dist/routes/connections/resolveTenantPreflight.js +226 -0
  85. package/dist/routes/connections/resolveUnwalledReach.js +144 -0
  86. package/dist/routes/endpoints/acceptDetachedEndpoint.js +50 -0
  87. package/dist/routes/endpoints/authorizeApiEndpoint.js +13 -4
  88. package/dist/routes/endpoints/callEndpoint.js +22 -7
  89. package/dist/routes/endpoints/control/controlParallelFor.js +61 -22
  90. package/dist/routes/endpoints/control/controlReject.js +23 -1
  91. package/dist/routes/endpoints/control/controlReturn.js +29 -1
  92. package/dist/routes/endpoints/control/controlThrow.js +3 -2
  93. package/dist/routes/endpoints/control/controlTry.js +10 -1
  94. package/dist/routes/endpoints/control/controlWhile.js +55 -0
  95. package/dist/routes/endpoints/control/handleControl.js +3 -1
  96. package/dist/routes/endpoints/createWebhookAnswer.js +78 -0
  97. package/dist/routes/endpoints/evaluateRoutineOperators.js +2 -1
  98. package/dist/routes/endpoints/forwardScheduledEndpoint.js +3 -2
  99. package/dist/routes/endpoints/getEndpointConfig.js +18 -8
  100. package/dist/routes/endpoints/getSchemaValidator.js +39 -0
  101. package/dist/routes/endpoints/handleAgentCall.js +21 -2
  102. package/dist/routes/endpoints/handleAuthStep.js +214 -0
  103. package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
  104. package/dist/routes/endpoints/handleEndpointCall.js +43 -6
  105. package/dist/routes/endpoints/handleRenderNotification.js +14 -4
  106. package/dist/routes/endpoints/handleRequest.js +12 -1
  107. package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
  108. package/dist/routes/endpoints/handleValidateSchema.js +13 -15
  109. package/dist/routes/endpoints/invokeEndpoint.js +26 -3
  110. package/dist/routes/endpoints/operatorScope.js +2 -1
  111. package/dist/routes/{auth/callbacks/createCallbackPlugins.js → endpoints/parseWebhookBody.js} +10 -6
  112. package/dist/routes/endpoints/resolveCallBinding.js +91 -0
  113. package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
  114. package/dist/routes/endpoints/runDetachedEndpoint.js +63 -18
  115. package/dist/routes/endpoints/runRoutine.js +64 -5
  116. package/dist/routes/endpoints/runScheduledEndpoint.js +18 -11
  117. package/dist/routes/endpoints/runWebhookEndpoint.js +69 -23
  118. package/dist/routes/endpoints/runWebhookVerify.js +129 -0
  119. package/dist/routes/endpoints/scheduleBackground.js +10 -0
  120. package/dist/routes/endpoints/test/runTest.js +31 -9
  121. package/dist/routes/endpoints/validatePayload.js +144 -0
  122. package/dist/routes/log/logClientError.js +7 -4
  123. package/dist/routes/mcp/createMcpServer.js +143 -82
  124. package/dist/routes/mcp/getMcpJwks.js +93 -0
  125. package/dist/routes/mcp/getMcpResourceBinding.js +41 -0
  126. package/dist/routes/mcp/getMcpUri.js +69 -0
  127. package/dist/routes/mcp/oauthResourceLifecycle.js +122 -0
  128. package/dist/routes/mcp/runAfterToolCall.js +50 -0
  129. package/dist/routes/notifications/resolveNotificationLinks.js +39 -11
  130. package/dist/routes/page/dynamic/checkDynamicContent.js +81 -0
  131. package/dist/routes/page/dynamic/checkLiteralContent.js +242 -0
  132. package/dist/routes/page/dynamic/createContentError.js +34 -0
  133. package/dist/routes/page/dynamic/flagIconsOutsidePage.js +39 -0
  134. package/dist/routes/page/dynamic/flagTypesOutsidePage.js +44 -0
  135. package/dist/routes/page/dynamic/getPropertiesSchemaErrors.js +35 -0
  136. package/dist/routes/page/dynamic/loadDynamicArtifacts.js +52 -0
  137. package/dist/routes/page/dynamic/policy/checkAction.js +204 -0
  138. package/dist/routes/page/dynamic/policy/checkEvents.js +163 -0
  139. package/dist/routes/page/dynamic/policy/checkPolicy.js +313 -0
  140. package/dist/routes/page/dynamic/policy/checkValue.js +214 -0
  141. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +117 -0
  142. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +54 -0
  143. package/dist/routes/page/dynamic/policy/findSerializerKeys.js +50 -0
  144. package/dist/routes/page/dynamic/policy/isAllowedUrl.js +53 -0
  145. package/dist/routes/{auth/createAdapter.js → page/dynamic/policy/isUnderState.js} +5 -9
  146. package/dist/routes/page/dynamic/policy/normalizeUrlText.js +25 -0
  147. package/dist/routes/page/dynamic/resolveDynamicContent.js +89 -37
  148. package/dist/routes/page/dynamic/unescapeOperators.js +21 -4
  149. package/dist/routes/page/dynamic/validateFragment.js +17 -58
  150. package/dist/routes/page/getPageConfig.js +76 -6
  151. package/dist/routes/request/authorizeRequest.js +21 -6
  152. package/dist/routes/request/callRequest.js +22 -10
  153. package/dist/routes/request/callRequestResolver.js +49 -6
  154. package/dist/routes/request/checkConnectionRead.js +1 -1
  155. package/dist/routes/request/checkConnectionWrite.js +1 -1
  156. package/dist/routes/request/createWalledResolver.js +75 -0
  157. package/dist/routes/request/getRequestConfig.js +19 -3
  158. package/dist/routes/request/maskCredentialProperties.js +34 -0
  159. package/dist/routes/request/resolveTenancy.js +223 -0
  160. package/dist/routes/request/validateSchemas.js +7 -6
  161. package/dist/routes/{auth/events/createEventPlugins.js → rootConfig/getAppEvents.js} +7 -6
  162. package/dist/routes/rootConfig/getHomeAndMenus.js +23 -16
  163. package/dist/routes/{auth/events/createSessionEvent.js → rootConfig/getPagePaths.js} +16 -18
  164. package/dist/routes/rootConfig/getRootConfig.js +9 -3
  165. package/dist/routes/rootConfig/menus/filterMenuList.js +5 -2
  166. package/dist/routes/websocket/authorizeWebsocket.js +19 -4
  167. package/dist/routes/websocket/createChannelRegistry.js +20 -9
  168. package/dist/routes/websocket/createWebSocketConnection.js +150 -28
  169. package/dist/routes/websocket/getCallerFingerprint.js +31 -0
  170. package/dist/routes/websocket/prepareChannel.js +29 -1
  171. package/dist/routes/websocket/resolveWebsocketCaller.js +40 -0
  172. package/dist/test/testContext.js +13 -10
  173. package/package.json +28 -12
  174. package/dist/context/createAuthorize.js +0 -45
  175. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +0 -30
  176. package/dist/routes/auth/callbacks/createCallbacks.js +0 -46
  177. package/dist/routes/auth/callbacks/createJWTCallback.js +0 -77
  178. package/dist/routes/auth/callbacks/createRedirectCallback.js +0 -41
  179. package/dist/routes/auth/callbacks/createSessionCallback.js +0 -81
  180. package/dist/routes/auth/callbacks/createSignInCallback.js +0 -40
  181. package/dist/routes/auth/callbacks/validateSessionRoles.js +0 -33
  182. package/dist/routes/auth/createLogger.js +0 -35
  183. package/dist/routes/auth/createPrefixedCookies.js +0 -52
  184. package/dist/routes/auth/createProviders.js +0 -25
  185. package/dist/routes/auth/defaultAuthUrl.js +0 -31
  186. package/dist/routes/auth/events/createCreateUserEvent.js +0 -41
  187. package/dist/routes/auth/events/createEvents.js +0 -56
  188. package/dist/routes/auth/events/createLinkAccountEvent.js +0 -43
  189. package/dist/routes/auth/events/createSignInEvent.js +0 -46
  190. package/dist/routes/auth/events/createSignOutEvent.js +0 -43
  191. package/dist/routes/auth/events/createUpdateUserEvent.js +0 -41
  192. package/dist/routes/auth/getAuthConfig.js +0 -90
  193. package/dist/routes/auth/resolveCookies.js +0 -37
  194. package/dist/routes/log/formatValidationError.js +0 -31
  195. /package/dist/{routes/notifications → email}/resolveThemeLogo.js +0 -0
@@ -12,21 +12,30 @@
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 { AuthenticationError, ConfigError } from '@lowdefy/errors';
15
+ */ import { AuthenticationError, AuthorizationError, TwoFactorEnrolmentRequiredError } from '@lowdefy/errors';
16
16
  import { type } from '@lowdefy/helpers';
17
- function authorizeApiEndpoint({ authorize, logger, user }, { endpointConfig }) {
18
- if (!authorize(endpointConfig)) {
17
+ function authorizeApiEndpoint({ authorizeOutcome: authorize, logger, user }, { endpointConfig }) {
18
+ const outcome = authorize(endpointConfig);
19
+ if (outcome !== 'allow') {
19
20
  logger.debug({
20
21
  event: 'debug_api_authorize',
21
22
  authorized: false,
23
+ outcome,
22
24
  auth_config: endpointConfig.auth
23
25
  });
26
+ if (outcome === 'enrol_required') {
27
+ // Reached only after the role check passed, so the caller is authorised and
28
+ // this reveals nothing about what exists (Decision 6). A distinct code, not
29
+ // a 401 - a 401 reads to the client as a dead session and bounces the user
30
+ // to sign-in, which is the loop by another route.
31
+ throw new TwoFactorEnrolmentRequiredError(`Two-factor enrolment required for API Endpoint "${endpointConfig.endpointId}".`);
32
+ }
24
33
  // Unauthenticated on a protected endpoint - 401 tells the caller to fix
25
34
  // its credentials. Wrong roles stay opaque below.
26
35
  if (type.isNone(user)) {
27
36
  throw new AuthenticationError(`Authentication required for API endpoint "${endpointConfig.endpointId}".`);
28
37
  }
29
- throw new ConfigError(`API Endpoint "${endpointConfig.endpointId}" does not exist.`);
38
+ throw new AuthorizationError(`API Endpoint "${endpointConfig.endpointId}" does not exist.`);
30
39
  }
31
40
  logger.debug({
32
41
  event: 'debug_api_authorize',
@@ -12,16 +12,16 @@
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 { serializer } from '@lowdefy/helpers';
15
+ */ import { serializer, type } from '@lowdefy/helpers';
16
16
  import { AuthenticationError, ConfigError } from '@lowdefy/errors';
17
17
  import authorizeApiEndpoint from './authorizeApiEndpoint.js';
18
18
  import buildEndpointResult from '../../response/buildEndpointResult.js';
19
19
  import createEvaluateOperators from '../../context/createEvaluateOperators.js';
20
20
  import getEndpointConfig from './getEndpointConfig.js';
21
- import isUnauthenticatedHuman from './isUnauthenticatedHuman.js';
22
21
  import runRoutine from './runRoutine.js';
23
22
  import scheduleBackground from './scheduleBackground.js';
24
- async function callEndpoint(context, { blockId, endpointId, pageId, payload }) {
23
+ import validatePayload from './validatePayload.js';
24
+ async function callEndpoint(context, { blockId, endpointId, outsideCaller = false, pageId, payload }) {
25
25
  const { logger } = context;
26
26
  context.blockId = blockId;
27
27
  context.endpointId = endpointId;
@@ -38,10 +38,11 @@ async function callEndpoint(context, { blockId, endpointId, pageId, payload }) {
38
38
  endpointId
39
39
  });
40
40
  // Block HTTP access to InternalApi endpoints - same error as a missing
41
- // endpoint, including the unauthenticated fork, so an internal endpoint is
42
- // indistinguishable from one that does not exist on both paths.
41
+ // endpoint, including the guarded unauthenticated fork, so an internal
42
+ // endpoint is indistinguishable from one that does not exist on both paths.
43
43
  if (endpointConfig.type === 'InternalApi') {
44
- const err = await isUnauthenticatedHuman(context) ? new AuthenticationError(`Authentication required for API endpoint "${endpointId}".`) : new ConfigError(`API Endpoint "${endpointId}" does not exist.`);
44
+ const unauthenticatedHuman = type.isNone(context.user) && !type.isNone(context.authEnforcement) && context.system !== true;
45
+ const err = unauthenticatedHuman ? new AuthenticationError(`Authentication required for API endpoint "${endpointId}".`) : new ConfigError(`API Endpoint "${endpointId}" does not exist.`);
45
46
  logger.debug({
46
47
  params: {
47
48
  endpointId
@@ -53,9 +54,21 @@ async function callEndpoint(context, { blockId, endpointId, pageId, payload }) {
53
54
  authorizeApiEndpoint(context, {
54
55
  endpointConfig
55
56
  });
57
+ // Validated before the async fork, so a refused payload is answered to the
58
+ // caller rather than failing in the background. A page CallAPI without a
59
+ // payload sends none; it is an empty object here as on every other caller.
60
+ // A page's CallAPI names its page, whose config built the payload. A call that
61
+ // names no page is an API client's own, as is an MCP tool call
62
+ // (outsideCaller), so a refusal is that caller's mistake (validatePayload).
63
+ const deserializedPayload = serializer.deserialize(payload ?? {});
64
+ validatePayload({
65
+ endpointConfig,
66
+ payload: deserializedPayload,
67
+ outsideCaller: outsideCaller || type.isNone(pageId)
68
+ });
56
69
  const routineContext = {
57
70
  steps: {},
58
- payload: serializer.deserialize(payload),
71
+ payload: deserializedPayload,
59
72
  arrayIndices: [],
60
73
  error: null,
61
74
  items: {},
@@ -66,6 +79,8 @@ async function callEndpoint(context, { blockId, endpointId, pageId, payload }) {
66
79
  // Auth was already checked above; the outcome lands in logs (scheduleBackground)
67
80
  // and in whatever the routine itself records.
68
81
  if (endpointConfig.async === true) {
82
+ // The run outlives this request, so the request closing must not cancel it.
83
+ context.signal = undefined;
69
84
  scheduleBackground(context, {
70
85
  event: 'background_endpoint',
71
86
  endpointId
@@ -12,9 +12,32 @@
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 } from '@lowdefy/errors';
15
+ */ import { type } from '@lowdefy/helpers';
16
+ import { ConfigError } from '@lowdefy/errors';
16
17
  import runRoutine from '../runRoutine.js';
17
18
  import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
19
+ // Runs `run(index)` for every index, at most `limit` at a time (every index at once without a
20
+ // limit), and resolves with the results in index order.
21
+ async function runLimited({ count, limit, run }) {
22
+ if (type.isUndefined(limit) || limit >= count) {
23
+ return Promise.all(Array.from({
24
+ length: count
25
+ }, (_, index)=>run(index)));
26
+ }
27
+ const results = new Array(count);
28
+ let next = 0;
29
+ async function lane() {
30
+ while(next < count){
31
+ const index = next;
32
+ next += 1;
33
+ results[index] = await run(index);
34
+ }
35
+ }
36
+ await Promise.all(Array.from({
37
+ length: limit
38
+ }, ()=>lane()));
39
+ return results;
40
+ }
18
41
  async function controlParallelFor(context, routineContext, { control }) {
19
42
  const { endpointId, logger } = context;
20
43
  const { items } = routineContext;
@@ -40,29 +63,45 @@ async function controlParallelFor(context, routineContext, { control }) {
40
63
  if (!control[':do']) {
41
64
  throw new Error(`Invalid :parallel_for in endpoint "${endpointId}" - missing :do.`);
42
65
  }
43
- const promises = array.map((item, index)=>{
44
- const updatedItems = {
45
- ...items,
46
- [itemName]: item
47
- };
48
- logger.debug({
49
- event: 'debug_control_parallel_iteration',
50
- itemName: itemName,
51
- value: item,
52
- items: updatedItems
53
- });
54
- return runRoutine(context, {
55
- ...routineContext,
56
- arrayIndices: [
57
- ...routineContext.arrayIndices,
58
- index
59
- ],
60
- items: updatedItems
61
- }, {
62
- routine: control[':do']
66
+ const concurrency = evaluateRoutineOperators(context, routineContext, {
67
+ input: control[':concurrency'],
68
+ location: control['~k'] ?? ':parallel_for'
69
+ });
70
+ if (!type.isUndefined(concurrency) && (!type.isInt(concurrency) || concurrency < 1)) {
71
+ throw new ConfigError(`Invalid :parallel_for in endpoint "${endpointId}" - :concurrency must be a positive integer.`, {
72
+ received: concurrency,
73
+ configKey: control['~k']
63
74
  });
75
+ }
76
+ // Every item runs, whatever an earlier one returned: :concurrency only limits how many run at
77
+ // once, so the result is the same with or without it.
78
+ const results = await runLimited({
79
+ count: array.length,
80
+ limit: concurrency,
81
+ run: (index)=>{
82
+ const item = array[index];
83
+ const updatedItems = {
84
+ ...items,
85
+ [itemName]: item
86
+ };
87
+ logger.debug({
88
+ event: 'debug_control_parallel_iteration',
89
+ itemName: itemName,
90
+ value: item,
91
+ items: updatedItems
92
+ });
93
+ return runRoutine(context, {
94
+ ...routineContext,
95
+ arrayIndices: [
96
+ ...routineContext.arrayIndices,
97
+ index
98
+ ],
99
+ items: updatedItems
100
+ }, {
101
+ routine: control[':do']
102
+ });
103
+ }
64
104
  });
65
- const results = await Promise.all(promises);
66
105
  const resultsMap = {
67
106
  error: [],
68
107
  reject: [],
@@ -12,7 +12,7 @@
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 { UserError } from '@lowdefy/errors';
15
+ */ import { ConfigError, UserError } from '@lowdefy/errors';
16
16
  import { type } from '@lowdefy/helpers';
17
17
  import createWireProjection from '../../../response/createWireProjection.js';
18
18
  import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
@@ -35,12 +35,34 @@ async function controlReject(context, routineContext, { control }) {
35
35
  cause,
36
36
  isReject: true
37
37
  });
38
+ // :status and :body set the HTTP answer of the webhook whose routine this reject ends
39
+ // (createWebhookAnswer). The build allows them only where a webhook can answer with them.
40
+ if (':status' in control) {
41
+ const status = evaluateRoutineOperators(context, routineContext, {
42
+ input: control[':status'],
43
+ location
44
+ });
45
+ if (!type.isInt(status) || status < 400 || status > 499) {
46
+ throw new ConfigError(':status in :reject must be an integer from 400 to 499.', {
47
+ received: status,
48
+ configKey: control['~k']
49
+ });
50
+ }
51
+ error.webhookStatus = status;
52
+ }
53
+ if (':body' in control) {
54
+ error.webhookBody = evaluateRoutineOperators(context, routineContext, {
55
+ input: control[':body'],
56
+ location
57
+ });
58
+ }
38
59
  // Log under `err` — see controlThrow: only the `err` key runs the pino error
39
60
  // serializer, so `error` would drop the message from the log line.
40
61
  context.logger.warn({
41
62
  event: 'warn_control_reject',
42
63
  err: error
43
64
  });
65
+ error.handled = true;
44
66
  return {
45
67
  status: 'reject',
46
68
  error
@@ -12,16 +12,44 @@
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 evaluateRoutineOperators from '../evaluateRoutineOperators.js';
15
+ */ import { ConfigError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ import checkLiteralContent from '../../page/dynamic/checkLiteralContent.js';
18
+ import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
16
19
  async function controlReturn(context, routineContext, { control }) {
20
+ const literalData = routineContext.literalData ?? null;
17
21
  const response = evaluateRoutineOperators(context, routineContext, {
18
22
  input: control[':return'],
23
+ literalData,
19
24
  location: control['~k'] ?? ':return'
20
25
  });
26
+ // The :return of the endpoint a Dynamic block calls becomes page config.
27
+ if (literalData !== null) {
28
+ checkLiteralContent({
29
+ blocks: response?.blocks,
30
+ configKey: control['~k'],
31
+ literalData
32
+ });
33
+ }
21
34
  context.logger.debug({
22
35
  event: 'debug_control_return',
23
36
  response
24
37
  });
38
+ // :content_type sends a webhook's answer as text (createWebhookAnswer). The build allows it only
39
+ // in a webhook endpoint, and only as text/plain.
40
+ if (':content_type' in control) {
41
+ if (!type.isString(response)) {
42
+ throw new ConfigError(':return with :content_type text/plain must evaluate to a string.', {
43
+ received: response,
44
+ configKey: control['~k']
45
+ });
46
+ }
47
+ return {
48
+ status: 'return',
49
+ response,
50
+ contentType: control[':content_type']
51
+ };
52
+ }
25
53
  return {
26
54
  status: 'return',
27
55
  response
@@ -37,10 +37,11 @@ async function controlThrow(context, routineContext, { control }) {
37
37
  // Log under `err` — the pino error serializer (createNodeLogger) is registered
38
38
  // for the `err` key only; an Error passed as `error` is JSON-dumped without its
39
39
  // non-enumerable `message`/`stack`, producing a log line with no message.
40
- context.logger.error({
41
- event: 'error_control_throw',
40
+ context.logger.warn({
41
+ event: 'warn_control_throw',
42
42
  err: error
43
43
  });
44
+ error.handled = true;
44
45
  return {
45
46
  status: 'error',
46
47
  error
@@ -18,7 +18,16 @@ async function controlTry(context, routineContext, { control }) {
18
18
  context.logger.debug({
19
19
  event: 'debug_control_try'
20
20
  });
21
- let res = await runRoutine(context, routineContext, {
21
+ // With a :catch, an error in :try is handled here: `caught` makes runRoutine log an expected
22
+ // error (RequestError, ServiceError, UserError) at debug instead of as an error (nested
23
+ // controls and endpoint calls inherit it). Config, operator and internal errors are still
24
+ // reported through handleError. :catch and :finally run outside it, so their own errors are
25
+ // logged as usual.
26
+ const tryContext = control[':catch'] ? {
27
+ ...routineContext,
28
+ caught: true
29
+ } : routineContext;
30
+ let res = await runRoutine(context, tryContext, {
22
31
  routine: control[':try']
23
32
  });
24
33
  if (res.status === 'error' && control[':catch']) {
@@ -0,0 +1,55 @@
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 evaluateRoutineOperators from '../evaluateRoutineOperators.js';
16
+ import runRoutine from '../runRoutine.js';
17
+ async function controlWhile(context, routineContext, { control }) {
18
+ const { endpointId, logger } = context;
19
+ if (!control[':do']) {
20
+ throw new Error(`Invalid :while in endpoint "${endpointId}" - missing :do.`);
21
+ }
22
+ // No array index is pushed onto routineContext.arrayIndices. A :while has no item to
23
+ // index, so each iteration overwrites the previous iteration's step results, and
24
+ // `_step: my_step` reads the latest iteration's value. There is no iteration cap.
25
+ let iteration = 0;
26
+ while(true){
27
+ // The condition is evaluated fresh every iteration, so it sees the state and step
28
+ // results the body wrote. Hoisting it out of the loop makes the loop infinite.
29
+ const evaluated = evaluateRoutineOperators(context, routineContext, {
30
+ input: control[':while'],
31
+ location: control['~k'] ?? ':while'
32
+ });
33
+ logger.debug({
34
+ event: 'debug_control_while',
35
+ condition: {
36
+ input: control[':while'],
37
+ evaluated
38
+ },
39
+ iteration
40
+ });
41
+ if (!evaluated) {
42
+ return {
43
+ status: 'continue'
44
+ };
45
+ }
46
+ const res = await runRoutine(context, routineContext, {
47
+ routine: control[':do']
48
+ });
49
+ if (res?.status != 'continue') {
50
+ return res;
51
+ }
52
+ iteration += 1;
53
+ }
54
+ }
55
+ export default controlWhile;
@@ -23,6 +23,7 @@ import controlSetState from './controlSetState.js';
23
23
  import controlSwitch from './controlSwitch.js';
24
24
  import controlThrow from './controlThrow.js';
25
25
  import controlTry from './controlTry.js';
26
+ import controlWhile from './controlWhile.js';
26
27
  const controlHandlers = {
27
28
  ':for': controlFor,
28
29
  ':if': controlIf,
@@ -34,7 +35,8 @@ const controlHandlers = {
34
35
  ':set_state': controlSetState,
35
36
  ':switch': controlSwitch,
36
37
  ':throw': controlThrow,
37
- ':try': controlTry
38
+ ':try': controlTry,
39
+ ':while': controlWhile
38
40
  };
39
41
  async function handleControl(context, routineContext, { control }) {
40
42
  for (const [key, handler] of Object.entries(controlHandlers)){
@@ -0,0 +1,78 @@
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 { serializer } from '@lowdefy/helpers';
16
+ import redactResponse from '../../response/redactResponse.js';
17
+ // The route sends a webhook's answer to a third party, not the Lowdefy client, as plain JSON: a
18
+ // date arrives as an ISO string, not the serializer's { "~d": ... } form, and no build marker
19
+ // crosses.
20
+ function toPlainJson(context, value) {
21
+ return serializer.deserialize(redactResponse(context, value));
22
+ }
23
+ function errorBody({ code, message }) {
24
+ return {
25
+ error: {
26
+ code,
27
+ message
28
+ }
29
+ };
30
+ }
31
+ // The HTTP status and body a webhook route answers with, from the routine's outcome. A :reject
32
+ // answers the :status and :body it set (400 and an error body by default), also when it was
33
+ // raised in an endpoint the routine called. A failed ValidateSchema step answers 400. Any other
34
+ // failure answers 500 with a fixed message, so nothing from the error reaches the caller. A :return
35
+ // with :content_type answers its string as is, for a handshake that wants a text reply.
36
+ function createWebhookAnswer(context, { contentType, error, response, status }) {
37
+ if (status === 'reject') {
38
+ return {
39
+ status: error.webhookStatus ?? 400,
40
+ body: Object.hasOwn(error, 'webhookBody') ? toPlainJson(context, error.webhookBody) : errorBody({
41
+ code: 'rejected',
42
+ message: error.message
43
+ })
44
+ };
45
+ }
46
+ if (status === 'error' && error?.isInvalidRequest === true) {
47
+ return {
48
+ status: 400,
49
+ body: errorBody({
50
+ code: 'invalid_request',
51
+ message: error.message
52
+ })
53
+ };
54
+ }
55
+ if (status === 'error') {
56
+ return {
57
+ status: 500,
58
+ body: errorBody({
59
+ code: 'internal_error',
60
+ message: 'Webhook failed.'
61
+ })
62
+ };
63
+ }
64
+ if (contentType === 'text/plain') {
65
+ return {
66
+ status: 200,
67
+ body: response,
68
+ contentType
69
+ };
70
+ }
71
+ return {
72
+ status: 200,
73
+ body: toPlainJson(context, response) ?? {
74
+ ok: true
75
+ }
76
+ };
77
+ }
78
+ export default createWebhookAnswer;
@@ -15,10 +15,11 @@
15
15
  */ import operatorScope from './operatorScope.js';
16
16
  // Every routine step evaluates against the same frame. Taking the frame from routineContext in one
17
17
  // place means a step handler cannot drop part of it (state, items, loop indices).
18
- function evaluateRoutineOperators(context, routineContext, { input, location }) {
18
+ function evaluateRoutineOperators(context, routineContext, { input, literalData, location }) {
19
19
  return context.evaluateOperators({
20
20
  arrayIndices: routineContext.arrayIndices,
21
21
  input,
22
+ literalData,
22
23
  location,
23
24
  ...operatorScope(routineContext)
24
25
  });
@@ -20,7 +20,7 @@ import getEnvironmentSchedules from './getEnvironmentSchedules.js';
20
20
  import scheduleBackground from './scheduleBackground.js';
21
21
  // Vercel fires cron jobs only on the production deployment, so the schedules of every environment
22
22
  // with a cron.secret are registered there as /api/cron-forward/<environment>/<endpointId> jobs. When
23
- // one fires, this pings the environment's own /api/cron/<endpointId> at its url with that
23
+ // one fires, this pings the environment's own <basePath>/api/cron/<endpointId> at its url with that
24
24
  // environment's CRON_SECRET (the Lowdefy secret named by config.environments.<env>.cron.secret) so
25
25
  // the environment runs its own code, and answers Vercel immediately: the ping is fire-and-forget,
26
26
  // kept alive by scheduleBackground and bounded by the function duration, and its outcome exists only
@@ -65,7 +65,8 @@ async function forwardScheduledEndpoint(context, { environment, endpointId, cron
65
65
  while(origin.endsWith('/')){
66
66
  origin = origin.slice(0, -1);
67
67
  }
68
- const url = `${origin}/api/cron/${endpointId}`;
68
+ // The environment's url is its origin; the app mounts its routes under config.basePath.
69
+ const url = `${origin}${config.basePath ?? ''}/api/cron/${endpointId}`;
69
70
  const timeoutMs = (config?.vercel?.maxDuration ?? 60) * 1000;
70
71
  const headers = {
71
72
  authorization: `Bearer ${secret}`
@@ -13,16 +13,26 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { AuthenticationError, ConfigError } from '@lowdefy/errors';
16
- import isUnauthenticatedHuman from './isUnauthenticatedHuman.js';
17
- // A missing endpoint answers the same as a protected one for an anonymous
18
- // caller on an auth'd app - the message is byte-identical to the one
19
- // authorizeApiEndpoint throws, so present and absent are indistinguishable
20
- // before authenticating. Every other caller keeps the opaque does-not-exist.
21
- async function getEndpointConfig(context, { endpointId }) {
22
- const { logger, readConfigFile } = context;
16
+ import { type } from '@lowdefy/helpers';
17
+ // A missing endpoint id answers the same as a protected one for an anonymous
18
+ // human on an auth'd app: before you authenticate, the only answer is
19
+ // authenticate. Otherwise a logged-out caller enumerates endpoint ids by
20
+ // response difference - 500 for a miss (the handler special-cases only
21
+ // AuthenticationError) versus 401 for a protected one. An authenticated caller
22
+ // gets today's opaque "does not exist" for both a miss and a role refusal,
23
+ // unchanged.
24
+ //
25
+ // Guarded on authEnforcement != null (auth configured) and system !== true (not
26
+ // the engine talking to itself), exactly as the page fork is: "no user" is not
27
+ // "anonymous human who should sign in" - it is also "no auth here" and "this is
28
+ // a system run", and neither should be told to authenticate against nothing.
29
+ // This is NOT a per-entity apiProtectedByDefault default; no such glob surface
30
+ // exists.
31
+ async function getEndpointConfig({ authEnforcement, logger, readConfigFile, system, user }, { endpointId }) {
23
32
  const endpoint = await readConfigFile(`api/${endpointId}.json`);
24
33
  if (!endpoint) {
25
- const err = await isUnauthenticatedHuman(context) ? new AuthenticationError(`Authentication required for API endpoint "${endpointId}".`) : new ConfigError(`API Endpoint "${endpointId}" does not exist.`);
34
+ const unauthenticatedHuman = type.isNone(user) && !type.isNone(authEnforcement) && system !== true;
35
+ const err = unauthenticatedHuman ? new AuthenticationError(`Authentication required for API endpoint "${endpointId}".`) : new ConfigError(`API Endpoint "${endpointId}" does not exist.`);
26
36
  logger.debug({
27
37
  params: {
28
38
  endpointId
@@ -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 { compile } from '@lowdefy/ajv';
16
+ import { LRUCache, serializer } from '@lowdefy/helpers';
17
+ // A ValidateSchema step evaluates its schema property on every call, so each
18
+ // call hands over a new object, and operators in it can change the schema from
19
+ // one call to the next. Validators are cached by the schema's content: the same
20
+ // schema compiles once, a different one gets its own validator, and the cache
21
+ // stays bounded.
22
+ const validators = new LRUCache({
23
+ maxSize: 100
24
+ });
25
+ function getSchemaValidator({ schema }) {
26
+ const key = serializer.serializeToString(schema, {
27
+ stable: true,
28
+ skipMarkers: true
29
+ });
30
+ let validator = validators.get(key);
31
+ if (!validator) {
32
+ validator = compile({
33
+ schema
34
+ });
35
+ validators.set(key, validator);
36
+ }
37
+ return validator;
38
+ }
39
+ export default getSchemaValidator;
@@ -23,12 +23,13 @@ async function handleAgentCall(context, routineContext, { step }) {
23
23
  event: 'debug_start_agent_call',
24
24
  step
25
25
  });
26
- // Evaluate operators in step.properties (resolves agentId, prompt)
26
+ // Evaluate operators in step.properties (resolves agentId, prompt, files)
27
27
  const evaluatedProperties = evaluateRoutineOperators(context, routineContext, {
28
28
  input: step.properties,
29
29
  location: step.stepId
30
30
  });
31
31
  const { agentId, prompt } = evaluatedProperties;
32
+ const files = evaluatedProperties.files ?? [];
32
33
  if (!type.isString(agentId)) {
33
34
  throw new ConfigError(`CallAgent step "${step.stepId}" properties.agentId must evaluate to a string. Received ${JSON.stringify(agentId)}.`, {
34
35
  configKey: step['~k']
@@ -39,12 +40,28 @@ async function handleAgentCall(context, routineContext, { step }) {
39
40
  configKey: step['~k']
40
41
  });
41
42
  }
43
+ // A file url is usually a signed link, and these errors reach the server log, so they name
44
+ // the type received rather than the value.
45
+ if (!type.isArray(files)) {
46
+ throw new ConfigError(`CallAgent step "${step.stepId}" properties.files must evaluate to an array. Received a value of type "${typeof files}".`, {
47
+ configKey: step['~k']
48
+ });
49
+ }
50
+ files.forEach((file, index)=>{
51
+ if (!type.isObject(file) || !type.isString(file.url) || !URL.canParse(file.url) || !type.isString(file.mediaType)) {
52
+ const received = type.isObject(file) ? `a url of type "${typeof file.url}" and a mediaType of type "${typeof file.mediaType}"` : `a value of type "${typeof file}"`;
53
+ throw new ConfigError(`CallAgent step "${step.stepId}" properties.files[${index}] must have a url and a mediaType string. Received ${received}.`, {
54
+ configKey: step['~k']
55
+ });
56
+ }
57
+ });
42
58
  // Headless agent context — no page, no conversation, no sharedState (which
43
59
  // also excludes the client-only update-page-state tool). userId is null
44
60
  // under scheduled (system) context.
45
61
  const agentContext = {
46
62
  conversationId: null,
47
63
  pageId: null,
64
+ pathParams: {},
48
65
  sharedState: undefined,
49
66
  urlQuery: {},
50
67
  userId: context.user?.sub ?? context.user?.id ?? null
@@ -53,13 +70,15 @@ async function handleAgentCall(context, routineContext, { step }) {
53
70
  agentId,
54
71
  agentContext,
55
72
  endpointDepth: routineContext.endpointDepth,
73
+ files: [],
56
74
  mode: 'generate'
57
75
  });
58
76
  const { result } = await agentType.resolver({
59
77
  connection: connectionInstance,
60
78
  properties: {
61
79
  agent: agentConfig,
62
- prompt
80
+ prompt,
81
+ files
63
82
  },
64
83
  context: resolverContext
65
84
  });