@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
@@ -13,25 +13,35 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { serializer } from '@lowdefy/helpers';
16
- import { ConfigError } from '@lowdefy/errors';
16
+ import { ConfigError, LowdefyInternalError } from '@lowdefy/errors';
17
+ import { getMarkedCredentials } from '@lowdefy/node-utils';
17
18
  import addStepResult from './addStepResult.js';
19
+ import createBoundSystemContext from '../../context/createBoundSystemContext.js';
20
+ import evaluateRoutineOperators from './evaluateRoutineOperators.js';
18
21
  import invokeEndpoint from './invokeEndpoint.js';
22
+ import resolveCallBinding from './resolveCallBinding.js';
19
23
  import scheduleBackground from './scheduleBackground.js';
20
24
  async function handleEndpointCall(context, routineContext, { step }) {
21
- const { logger, evaluateOperators } = context;
25
+ const { logger } = context;
22
26
  logger.debug({
23
27
  event: 'debug_start_endpoint_call',
24
28
  step
25
29
  });
26
30
  // Evaluate operators in step.properties (resolves endpointId, payload)
27
- const evaluatedProperties = evaluateOperators({
31
+ const evaluatedProperties = evaluateRoutineOperators(context, routineContext, {
28
32
  input: step.properties,
29
- items: routineContext.items,
30
- location: step.stepId,
31
- payload: routineContext.payload,
32
- state: routineContext.state,
33
- steps: routineContext.steps
33
+ location: step.stepId
34
34
  });
35
+ // organization (and caller) bind the target to one organization as a system
36
+ // run: the tenant wall filters and stamps with it, and `_user` is the named
37
+ // stand-in caller, or null.
38
+ const binding = resolveCallBinding(context, {
39
+ caller: evaluatedProperties.caller,
40
+ configKey: step['~k'],
41
+ organization: evaluatedProperties.organization,
42
+ stepId: step.stepId
43
+ });
44
+ const callContext = binding === null ? context : createBoundSystemContext(context, binding);
35
45
  // detached: true — fire-and-forget the call back through the deployment's
36
46
  // /api/detached route, so the target runs in its OWN function invocation
37
47
  // with a fresh duration budget (chainable bounded work without a queue).
@@ -44,7 +54,7 @@ async function handleEndpointCall(context, routineContext, { step }) {
44
54
  throw new ConfigError('CallApi with "detached: true" requires the CRON_SECRET environment variable — the /api/detached route fails closed without it.');
45
55
  }
46
56
  if (!context.origin) {
47
- throw new ConfigError('Detached endpoint calls require the request origin on context.');
57
+ throw new LowdefyInternalError('Detached endpoint calls require the request origin on context.');
48
58
  }
49
59
  const targetEndpointId = evaluatedProperties.endpointId;
50
60
  scheduleBackground(context, {
@@ -53,11 +63,33 @@ async function handleEndpointCall(context, routineContext, { step }) {
53
63
  }, ()=>fetch(`${context.origin}/api/detached/${targetEndpointId}`, {
54
64
  method: 'POST',
55
65
  headers: {
66
+ // The dev server's journey cookies (data set, mutant) ride the hop
67
+ // so the target runs in the same journey run; the production server
68
+ // sets none. Spread first so content-type and authorization win.
69
+ ...context.loopbackHeaders ?? {},
56
70
  'content-type': 'application/json',
57
71
  authorization: `Bearer ${process.env.CRON_SECRET}`
58
72
  },
73
+ // Carry the already-resolved dispatcher identity across the hop
74
+ // (Decision 4): a detached call is a fresh invocation, not a fresh
75
+ // principal. The receiver rehydrates context.user / context.system from
76
+ // this snapshot and authorizes nested calls against it through the
77
+ // normal path - so a user-dispatched detached run reaches nothing the
78
+ // user could not reach synchronously, and a cron/hook/verified-webhook
79
+ // run blanket-passes like its dispatcher. Built server-side from the
80
+ // resolved context, never from user input; the CRON_SECRET proves
81
+ // origin, which is what lets the receiver trust the assertion.
59
82
  body: JSON.stringify({
60
- payload: serializer.serialize(evaluatedProperties.payload ?? {})
83
+ payload: serializer.serialize(evaluatedProperties.payload ?? {}),
84
+ principal: {
85
+ user: serializer.serialize(callContext.user ?? null),
86
+ system: callContext.system === true,
87
+ organizationId: callContext.boundOrganizationId ?? null,
88
+ agent: routineContext.agent ?? null
89
+ },
90
+ // The values this request marked with _credential, so the target's logs scrub them
91
+ // too: the target runs as a new request with a scope of its own.
92
+ credentials: getMarkedCredentials()
61
93
  })
62
94
  }));
63
95
  addStepResult(context, routineContext, {
@@ -77,10 +109,12 @@ async function handleEndpointCall(context, routineContext, { step }) {
77
109
  status: 'continue'
78
110
  };
79
111
  }
80
- const result = await invokeEndpoint(context, {
112
+ const result = await invokeEndpoint(callContext, {
113
+ agent: routineContext.agent,
81
114
  endpointId: evaluatedProperties.endpointId,
82
115
  payload: evaluatedProperties.payload,
83
- endpointDepth: routineContext.endpointDepth
116
+ endpointDepth: routineContext.endpointDepth,
117
+ caught: routineContext.caught === true
84
118
  });
85
119
  // Store the return value in the caller's steps
86
120
  const response = result.status === 'return' ? result.response : null;
@@ -16,10 +16,12 @@
16
16
  import { ConfigError } from '@lowdefy/errors';
17
17
  import { type } from '@lowdefy/helpers';
18
18
  import addStepResult from './addStepResult.js';
19
+ import getCurrentEnvironment from '../../context/getCurrentEnvironment.js';
19
20
  import derivePreview from '../notifications/derivePreview.js';
20
21
  import getNotificationConfig from '../notifications/getNotificationConfig.js';
21
22
  import resolveNotificationLinks from '../notifications/resolveNotificationLinks.js';
22
- import resolveThemeLogo from '../notifications/resolveThemeLogo.js';
23
+ import resolveThemeLogo from '../../email/resolveThemeLogo.js';
24
+ import evaluateRoutineOperators from './evaluateRoutineOperators.js';
23
25
  function itemHasPageLinks(item, dataKeys) {
24
26
  const links = Object.values(item.links ?? {});
25
27
  const arrayLinks = dataKeys.flatMap((key)=>(type.isArray(item[key]) ? item[key] : []).map((entry)=>entry?.link));
@@ -29,18 +31,14 @@ function itemHasPageLinks(item, dataKeys) {
29
31
  ].some((link)=>type.isObject(link) && !type.isNone(link.pageId));
30
32
  }
31
33
  async function handleRenderNotification(context, routineContext, { step }) {
32
- const { logger, evaluateOperators } = context;
34
+ const { logger } = context;
33
35
  logger.debug({
34
36
  event: 'debug_start_render_notification',
35
37
  step
36
38
  });
37
- const evaluatedProperties = evaluateOperators({
39
+ const evaluatedProperties = evaluateRoutineOperators(context, routineContext, {
38
40
  input: step.properties,
39
- items: routineContext.items,
40
- location: step.stepId,
41
- payload: routineContext.payload,
42
- state: routineContext.state,
43
- steps: routineContext.steps
41
+ location: step.stepId
44
42
  });
45
43
  const { notificationId, data, landingPage, recordId } = evaluatedProperties;
46
44
  let { serverUrl } = evaluatedProperties;
@@ -65,10 +63,19 @@ async function handleRenderNotification(context, routineContext, { step }) {
65
63
  configKey: step['~k']
66
64
  });
67
65
  }
66
+ } else {
67
+ // The current environment's url is the deployment origin, so links need no per-step wiring.
68
+ // On the dev server the request origin is the local app; in production it is never used, since
69
+ // a spoofed Host header would then steer the links in outgoing mail.
70
+ serverUrl = getCurrentEnvironment({
71
+ config: context.config
72
+ })?.url ?? (context.dev === true ? context.origin : undefined);
73
+ }
74
+ if (!type.isNone(serverUrl)) {
68
75
  serverUrl = serverUrl.replace(/\/$/, '');
69
76
  }
70
- if (!type.isNone(landingPage) && !type.isString(landingPage)) {
71
- throw new ConfigError(`RenderNotification step "${step.stepId}" properties.landingPage must evaluate to a string. Received ${JSON.stringify(landingPage)}.`, {
77
+ if (!type.isNone(landingPage) && !type.isString(landingPage) && !(type.isObject(landingPage) && type.isString(landingPage.pageId))) {
78
+ throw new ConfigError(`RenderNotification step "${step.stepId}" properties.landingPage must evaluate to a page id or an object with a pageId. Received ${JSON.stringify(landingPage)}.`, {
72
79
  configKey: step['~k']
73
80
  });
74
81
  }
@@ -111,7 +118,7 @@ async function handleRenderNotification(context, routineContext, { step }) {
111
118
  });
112
119
  if (itemHasPageLinks(data, Template.dataKeys ?? [])) {
113
120
  if (type.isNone(serverUrl)) {
114
- throw new ConfigError(`Notification "${notificationId}" has links but no server URL is available. Set the serverUrl step property.`, {
121
+ throw new ConfigError(`Notification "${notificationId}" has links but no server URL is available. Set the serverUrl step property, or the url of the current environment in config.environments.`, {
115
122
  configKey: step['~k']
116
123
  });
117
124
  }
@@ -123,13 +130,23 @@ async function handleRenderNotification(context, routineContext, { step }) {
123
130
  });
124
131
  }
125
132
  }
133
+ const routes = await context.readConfigFile('routes.json');
134
+ if (!type.isNone(landingPage)) {
135
+ const landingPageId = type.isString(landingPage) ? landingPage : landingPage.pageId;
136
+ if (!routes.some((route)=>route.pageId === landingPageId)) {
137
+ throw new ConfigError(`RenderNotification step "${step.stepId}" properties.landingPage "${landingPageId}" is not a page id. Pass the landing page's id, not its URL path.`, {
138
+ configKey: step['~k']
139
+ });
140
+ }
141
+ }
126
142
  const resolvedItem = resolveNotificationLinks({
127
143
  item: data,
128
144
  dataKeys: Template.dataKeys ?? [],
129
145
  serverUrl: serverUrl ?? '',
130
146
  basePath,
131
147
  landingPage,
132
- recordId
148
+ recordId,
149
+ routes
133
150
  });
134
151
  let interpolated;
135
152
  try {
@@ -20,10 +20,10 @@ import evaluateOperators from '../request/evaluateOperators.js';
20
20
  import getConnection from '../connections/getConnection.js';
21
21
  import getConnectionConfig from '../connections/getConnectionConfig.js';
22
22
  import getRequestResolver from '../request/getRequestResolver.js';
23
+ import resolveTenancy from '../request/resolveTenancy.js';
23
24
  import validateSchemas from '../request/validateSchemas.js';
24
25
  async function handleRequest(context, routineContext, { request }) {
25
26
  const { logger } = context;
26
- const { items } = routineContext;
27
27
  logger.debug({
28
28
  event: 'debug_start_request',
29
29
  request
@@ -40,13 +40,16 @@ async function handleRequest(context, routineContext, { request }) {
40
40
  connection,
41
41
  requestConfig
42
42
  });
43
+ const { tenant, tenantGuard } = resolveTenancy(context, {
44
+ connection,
45
+ connectionConfig,
46
+ requestConfig,
47
+ writes: requestResolver.meta.checkWrite === true
48
+ });
43
49
  const { connectionProperties, requestProperties } = evaluateOperators(context, {
44
50
  connectionConfig,
45
- items,
46
- payload: routineContext.payload,
47
51
  requestConfig,
48
- state: routineContext.state,
49
- steps: routineContext.steps
52
+ routineContext
50
53
  });
51
54
  checkConnectionRead(context, {
52
55
  connectionConfig,
@@ -68,11 +71,15 @@ async function handleRequest(context, routineContext, { request }) {
68
71
  requestProperties
69
72
  });
70
73
  const result = await callRequestResolver(context, {
74
+ agent: routineContext.agent,
71
75
  connectionProperties,
72
76
  endpointDepth: routineContext.endpointDepth,
73
77
  requestConfig,
74
78
  requestProperties,
75
- requestResolver
79
+ requestResolver,
80
+ routineContext,
81
+ tenant,
82
+ tenantGuard
76
83
  });
77
84
  addStepResult(context, routineContext, {
78
85
  result,
@@ -0,0 +1,106 @@
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, type } from '@lowdefy/helpers';
16
+ import { UserError } from '@lowdefy/errors';
17
+ import checkDynamicContent from '../page/dynamic/checkDynamicContent.js';
18
+ import loadDynamicArtifacts from '../page/dynamic/loadDynamicArtifacts.js';
19
+ import addStepResult from './addStepResult.js';
20
+ import evaluateRoutineOperators from './evaluateRoutineOperators.js';
21
+ // Checks content against a dynamic blocks policy with the same function page get
22
+ // uses, so content that passes here renders. The result lists every violation
23
+ // with its path into the content, for a generator to correct and retry.
24
+ async function handleValidateDynamic(context, routineContext, { step }) {
25
+ const { logger } = context;
26
+ logger.debug({
27
+ event: 'debug_start_validate_dynamic',
28
+ step
29
+ });
30
+ const { blocks, policy: policyId, throwOnInvalid = true } = evaluateRoutineOperators(context, routineContext, {
31
+ input: step.properties,
32
+ location: step.stepId
33
+ });
34
+ const artifacts = await loadDynamicArtifacts(context);
35
+ const policy = artifacts.dynamicPolicies[policyId];
36
+ let errors;
37
+ if (!type.isArray(blocks)) {
38
+ errors = [
39
+ {
40
+ path: 'blocks',
41
+ rule: 'shape',
42
+ message: `Content should be an array of blocks. Received ${JSON.stringify(blocks)}.`
43
+ }
44
+ ];
45
+ } else {
46
+ const result = await checkDynamicContent(context, {
47
+ artifacts,
48
+ // buildBlock mutates the content; the caller's value stays as given.
49
+ blocks: serializer.copy(blocks),
50
+ dynamicBlockId: step.stepId,
51
+ idPrefix: `validate:${step.stepId}`,
52
+ pageId: `endpoint:${step.endpointId}`,
53
+ pageRequests: null,
54
+ policy,
55
+ usedTypes: {
56
+ actions: new Set(),
57
+ blocks: new Set(),
58
+ operators: new Set()
59
+ }
60
+ });
61
+ errors = result.errors.map(({ path, rule, message })=>({
62
+ path,
63
+ rule,
64
+ message
65
+ }));
66
+ }
67
+ const result = {
68
+ valid: errors.length === 0,
69
+ errors,
70
+ blocks
71
+ };
72
+ // A Dynamic block's endpoint may return these blocks as config, if this
73
+ // step checked them against the block's own policy.
74
+ if (result.valid && routineContext.literalData?.policyId === policyId) {
75
+ routineContext.literalData.validatedStepIds.add(step.stepId);
76
+ }
77
+ addStepResult(context, routineContext, {
78
+ result,
79
+ stepId: step.stepId
80
+ });
81
+ if (!result.valid && throwOnInvalid) {
82
+ // Invalid generated content is an expected outcome, not a config fault.
83
+ const error = new UserError(`ValidateDynamic step "${step.stepId}" failed: ${errors[0].path}: ${errors[0].message}`, {
84
+ cause: errors
85
+ });
86
+ logger.warn({
87
+ event: 'warn_validate_dynamic',
88
+ stepId: step.stepId,
89
+ err: error
90
+ });
91
+ error.handled = true;
92
+ return {
93
+ status: 'error',
94
+ error
95
+ };
96
+ }
97
+ logger.debug({
98
+ event: 'debug_end_validate_dynamic',
99
+ stepId: step.stepId,
100
+ valid: result.valid
101
+ });
102
+ return {
103
+ status: 'continue'
104
+ };
105
+ }
106
+ export default handleValidateDynamic;
@@ -12,8 +12,10 @@
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 { validate } from '@lowdefy/ajv';
15
+ */ import { UserError } from '@lowdefy/errors';
16
16
  import addStepResult from './addStepResult.js';
17
+ import evaluateRoutineOperators from './evaluateRoutineOperators.js';
18
+ import getSchemaValidator from './getSchemaValidator.js';
17
19
  function buildErrorMessage(errors, stepId) {
18
20
  const first = errors?.[0];
19
21
  if (!first) return `ValidateSchema step "${stepId}" failed.`;
@@ -21,43 +23,41 @@ function buildErrorMessage(errors, stepId) {
21
23
  return `ValidateSchema step "${stepId}" failed at ${path}: ${first.message}.`;
22
24
  }
23
25
  async function handleValidateSchema(context, routineContext, { step }) {
24
- const { logger, evaluateOperators } = context;
26
+ const { logger } = context;
25
27
  logger.debug({
26
28
  event: 'debug_start_validate_schema',
27
29
  step
28
30
  });
29
- const evaluatedProperties = evaluateOperators({
31
+ const evaluatedProperties = evaluateRoutineOperators(context, routineContext, {
30
32
  input: step.properties,
31
- items: routineContext.items,
32
- location: step.stepId,
33
- payload: routineContext.payload,
34
- steps: routineContext.steps
33
+ location: step.stepId
35
34
  });
36
35
  const { schema, data, throwOnInvalid = true } = evaluatedProperties;
37
- const { valid, errors } = validate({
38
- schema,
39
- data,
40
- returnErrors: true
41
- });
42
- const result = {
43
- valid,
44
- errors: errors ?? []
45
- };
36
+ const result = getSchemaValidator({
37
+ schema
38
+ })(data);
39
+ const { valid } = result;
46
40
  addStepResult(context, routineContext, {
47
41
  result,
48
42
  stepId: step.stepId
49
43
  });
50
44
  if (!valid && throwOnInvalid) {
51
- const error = new Error(buildErrorMessage(result.errors, step.stepId), {
52
- cause: result.errors
53
- });
45
+ // Failed validation of caller-supplied data is an expected user outcome,
46
+ // not a config or system fault.
47
+ // No cause: a UserError's cause crosses the wire as author data, and the ajv errors carry
48
+ // server schema detail. They stay in the step result and the log.
49
+ const error = new UserError(buildErrorMessage(result.errors, step.stepId));
50
+ // A webhook answers an invalid request with 400 rather than 500 (createWebhookAnswer).
51
+ error.isInvalidRequest = true;
54
52
  // Log under `err` — see controlThrow: only the `err` key runs the pino error
55
53
  // serializer, so `error` would drop the message from the log line.
56
- logger.error({
57
- event: 'error_validate_schema',
54
+ logger.warn({
55
+ event: 'warn_validate_schema',
58
56
  stepId: step.stepId,
59
- err: error
57
+ err: error,
58
+ errors: result.errors
60
59
  });
60
+ error.handled = true;
61
61
  return {
62
62
  status: 'error',
63
63
  error
@@ -13,10 +13,12 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { ConfigError } from '@lowdefy/errors';
16
+ import { createLiteralData } from '@lowdefy/operators';
16
17
  import authorizeApiEndpoint from './authorizeApiEndpoint.js';
17
18
  import getEndpointConfig from './getEndpointConfig.js';
18
19
  import runRoutine from './runRoutine.js';
19
- async function invokeEndpoint(context, { endpointId, payload, endpointDepth }) {
20
+ import validatePayload from './validatePayload.js';
21
+ async function invokeEndpoint(context, { agent = null, endpointId, payload, endpointDepth, literalData = null, caught = false, outsideCaller = false }) {
20
22
  if (endpointDepth >= 10) {
21
23
  throw new ConfigError('Endpoint call depth exceeded maximum of 10. Check for recursive endpoint calls.');
22
24
  }
@@ -26,13 +28,35 @@ async function invokeEndpoint(context, { endpointId, payload, endpointDepth }) {
26
28
  authorizeApiEndpoint(context, {
27
29
  endpointConfig
28
30
  });
31
+ const childPayload = payload ?? {};
32
+ // The calling config built the payload, except an agent's tool call, whose
33
+ // model did (outsideCaller): see validatePayload.
34
+ validatePayload({
35
+ endpointConfig,
36
+ payload: childPayload,
37
+ outsideCaller
38
+ });
29
39
  const childRoutineContext = {
30
40
  steps: {},
31
- payload: payload ?? {},
41
+ payload: childPayload,
32
42
  arrayIndices: [],
43
+ error: null,
33
44
  items: {},
34
45
  state: {},
35
- endpointDepth: endpointDepth + 1
46
+ endpointDepth: endpointDepth + 1,
47
+ // Called from inside a :try with a :catch: an expected error the called endpoint does not
48
+ // catch itself is handled by the caller's :catch, so it is logged at debug (runRoutine).
49
+ caught,
50
+ // The agent ({ id, conversationId, files }) whose tool call started this chain of endpoint
51
+ // calls, or null. Set by the engine from the running agent, never from the payload, so
52
+ // `_agent` can mark agent work.
53
+ agent,
54
+ // Set only for the endpoint a Dynamic block calls: its :return becomes page
55
+ // config, so data read into it must not carry operators. Nested CallApi
56
+ // endpoints get a fresh context without it; their result arrives through
57
+ // _step, which the outer :return checks. The control spreads share the one
58
+ // object, so a :return nested in a control sees the same state.
59
+ literalData: literalData === null ? null : createLiteralData(literalData)
36
60
  };
37
61
  return runRoutine(context, childRoutineContext, {
38
62
  routine: endpointConfig.routine
@@ -0,0 +1,28 @@
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
+ */ // The routine fields operators can read. A field added to the routine frame goes here, so every
16
+ // routine step and control sees it rather than only the ones that remembered to pass it.
17
+ function operatorScope(routineContext) {
18
+ const { agent, error, items, payload, state, steps } = routineContext;
19
+ return {
20
+ agent: agent ?? null,
21
+ error: error ?? null,
22
+ items,
23
+ payload,
24
+ state,
25
+ steps
26
+ };
27
+ }
28
+ export default operatorScope;
@@ -12,10 +12,14 @@
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
- */ function createEventPlugins({ authConfig, plugins, type }) {
16
- return authConfig.events.map((eventConfig)=>({
17
- fn: plugins.events[eventConfig.type],
18
- properties: eventConfig.properties
19
- })).filter((event)=>event.fn.meta.type === type);
15
+ */ // Parses a webhook request body as JSON regardless of content-type (SNS posts
16
+ // JSON as text/plain). A body that is not JSON (a form-encoded Slack or Twilio
17
+ // post, an empty body) is passed through as the raw string.
18
+ function parseWebhookBody({ rawBody }) {
19
+ try {
20
+ return JSON.parse(rawBody);
21
+ } catch {
22
+ return rawBody;
23
+ }
20
24
  }
21
- export default createEventPlugins;
25
+ export default parseWebhookBody;
@@ -0,0 +1,91 @@
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 { ConfigError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ function isNonEmptyString(value) {
18
+ return type.isString(value) && value !== '';
19
+ }
20
+ // Decides the organization binding a CallApi step's `organization` and
21
+ // `caller` properties (already evaluated) ask for. Returns null when the step
22
+ // names neither, so the target runs as the calling run does.
23
+ //
24
+ // A binding is accepted only in a trusted system run (a schedule, an auth
25
+ // hook, a webhook whose verifier passed, or a detached run dispatched from
26
+ // one): the bound run is a system run, so naming it from a signed-in caller's
27
+ // routine, a strategy caller's or an unverified webhook's would raise that run
28
+ // to system trust. A run already bound may restate its own binding but not
29
+ // name another organization or another caller.
30
+ function resolveCallBinding(context, { caller, configKey, organization, stepId }) {
31
+ if (type.isNone(organization) && type.isNone(caller)) {
32
+ return null;
33
+ }
34
+ if (type.isNone(organization)) {
35
+ throw new ConfigError(`CallApi step "${stepId}" names a "caller" without an "organization". A stand-in caller only runs inside an organization binding.`, {
36
+ configKey
37
+ });
38
+ }
39
+ if (!isNonEmptyString(organization)) {
40
+ throw new ConfigError(`CallApi step "${stepId}" property "organization" should be a non-empty organization id string.`, {
41
+ received: organization,
42
+ configKey
43
+ });
44
+ }
45
+ if (!type.isNone(caller) && (!type.isObject(caller) || !isNonEmptyString(caller.id) || !isNonEmptyString(caller.name))) {
46
+ throw new ConfigError(`CallApi step "${stepId}" property "caller" should be an object with non-empty string "id" and "name".`, {
47
+ received: caller,
48
+ configKey
49
+ });
50
+ }
51
+ if (context.system !== true) {
52
+ throw new ConfigError(`CallApi step "${stepId}" names an "organization", which is accepted only in a trusted system run (a schedule, an auth hook, a webhook whose verifier passed, or a detached run from one). This run has a signed-in caller, or is a webhook with no passing verifier.`, {
53
+ configKey
54
+ });
55
+ }
56
+ const named = type.isNone(caller) ? null : {
57
+ id: caller.id,
58
+ name: caller.name
59
+ };
60
+ if (type.isNone(context.boundOrganizationId)) {
61
+ return {
62
+ organizationId: organization,
63
+ caller: named
64
+ };
65
+ }
66
+ if (organization !== context.boundOrganizationId) {
67
+ throw new ConfigError(`CallApi step "${stepId}" names organization "${organization}", but this run is already bound to organization "${context.boundOrganizationId}" and can not name another.`, {
68
+ configKey
69
+ });
70
+ }
71
+ const current = type.isNone(context.user) ? null : {
72
+ id: context.user.id,
73
+ name: context.user.name
74
+ };
75
+ if (named === null) {
76
+ return {
77
+ organizationId: organization,
78
+ caller: current
79
+ };
80
+ }
81
+ if (current === null || named.id !== current.id) {
82
+ throw new ConfigError(`CallApi step "${stepId}" names caller "${named.id}", but this run is already bound with ${current === null ? 'no caller' : `caller "${current.id}"`} and can not name another.`, {
83
+ configKey
84
+ });
85
+ }
86
+ return {
87
+ organizationId: organization,
88
+ caller: named
89
+ };
90
+ }
91
+ export default resolveCallBinding;
@@ -16,22 +16,23 @@
16
16
  import { ConfigError } from '@lowdefy/errors';
17
17
  // The environment a cron run resolves its schedules for. A forwarded request names it in the
18
18
  // x-lowdefy-cron-environment header; a request without one is the deployment running its own crons,
19
- // which is the environment declared without a url (the one Vercel fires crons on). Without
20
- // config.cron there are no environments and the endpoint's plain schedules apply.
19
+ // which is the current environment (config.environment). Without config.environments there are no
20
+ // environments and the endpoint's plain schedules apply; without a current environment the
21
+ // `default` schedules apply.
21
22
  function resolveCronEnvironment({ config, environment }) {
22
- const environments = config?.cron?.environments;
23
+ const environments = config?.environments;
23
24
  if (type.isNone(environments)) {
24
25
  if (!type.isNone(environment)) {
25
- throw new ConfigError(`Cron environment "${environment}" is not configured: lowdefy.config.cron.environments is not defined.`);
26
+ throw new ConfigError(`Cron environment "${environment}" is not configured: config.environments is not defined.`);
26
27
  }
27
28
  return undefined;
28
29
  }
29
30
  if (!type.isNone(environment)) {
30
31
  if (!type.isObject(environments[environment])) {
31
- throw new ConfigError(`Cron environment "${environment}" is not declared in lowdefy.config.cron.environments.`);
32
+ throw new ConfigError(`Cron environment "${environment}" is not declared in config.environments.`);
32
33
  }
33
34
  return environment;
34
35
  }
35
- return Object.keys(environments).find((name)=>type.isObject(environments[name]) && type.isUndefined(environments[name].url));
36
+ return config.environment;
36
37
  }
37
38
  export default resolveCronEnvironment;