@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
@@ -0,0 +1,64 @@
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
+ // The one place an org-scoped auth step's target organization is decided. The
18
+ // floor authorizes against the result and the step writes into it, so a second
19
+ // resolution anywhere else would not crash - it would silently authorize
20
+ // organization A while the step writes into organization B.
21
+ //
22
+ // An explicit organizationId always wins: that is what a multi-organization
23
+ // admin module passes, and it is what lets a session pinned to the team
24
+ // organization administer the customer organization. A slug (only ListMembers
25
+ // accepts one) is an explicit selection too, and is resolved to an id here so
26
+ // the authorized organization and the listed organization are the same one.
27
+ // Otherwise the deployment's pinned organization is the default - under the
28
+ // "tenant" policy there is no single implied organization, so an omitted
29
+ // organizationId is a runtime error naming the fix.
30
+ async function resolveStepOrganizationId({ auth, configKey, organization, properties, stepId }) {
31
+ if (!type.isNone(properties?.organizationId)) {
32
+ return properties.organizationId;
33
+ }
34
+ if (!type.isNone(properties?.organizationSlug)) {
35
+ const { adapter } = await auth.$context;
36
+ const found = await adapter.findOne({
37
+ model: 'organization',
38
+ where: [
39
+ {
40
+ field: 'slug',
41
+ value: properties.organizationSlug
42
+ }
43
+ ]
44
+ });
45
+ if (type.isNone(found)) {
46
+ throw new ConfigError(`Auth step "${stepId}" found no organization with slug "${properties.organizationSlug}".`, {
47
+ configKey
48
+ });
49
+ }
50
+ return found.id;
51
+ }
52
+ if (organization?.policy === 'tenant') {
53
+ throw new ConfigError(`Auth step "${stepId}" requires an "organizationId" property under the "tenant" organizations policy - there is no pinned organization to default to. Set organizationId on the step properties.`, {
54
+ configKey
55
+ });
56
+ }
57
+ if (type.isNone(organization?.pinned?.id)) {
58
+ throw new ConfigError(`Auth step "${stepId}" could not default "organizationId" - the pinned organization is not resolved. Set organizationId on the step properties, or check that auth organizations are configured and the database is reachable.`, {
59
+ configKey
60
+ });
61
+ }
62
+ return organization.pinned.id;
63
+ }
64
+ export default resolveStepOrganizationId;
@@ -12,22 +12,63 @@
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
+ import { markCredential } from '@lowdefy/node-utils';
17
+ import applySystemTrust from '../../context/applySystemTrust.js';
18
+ import authorizeApiEndpoint from './authorizeApiEndpoint.js';
16
19
  import buildEndpointResult from '../../response/buildEndpointResult.js';
17
- import createAuthorize from '../../context/createAuthorize.js';
20
+ import createAuthorizeOutcome from '../../context/createAuthorizeOutcome.js';
18
21
  import createEvaluateOperators from '../../context/createEvaluateOperators.js';
19
22
  import getEndpointConfig from './getEndpointConfig.js';
20
23
  import runRoutine from './runRoutine.js';
24
+ import validatePayload from './validatePayload.js';
21
25
  // Runs an endpoint invoked through the detached route (a CallApi step with
22
26
  // `detached: true` fire-and-forgets an HTTP call back to the deployment, so the
23
27
  // target runs in its OWN function invocation with a fresh duration budget).
24
- // Like a cron run this is authorized by the transport layer (CRON_SECRET) and
25
- // executes as a system context: no user session, `_user` resolves to undefined,
26
- // and InternalApi endpoints are callable. Payload arrives serialized (dates
27
- // etc. survive the HTTP hop via @lowdefy/helpers serializer).
28
- async function runDetachedEndpoint(context, { endpointId, payload }) {
28
+ // The transport is authorized by CRON_SECRET, which proves the loopback request
29
+ // originated from the deployment (an ORIGIN proof, not an identity). A detached
30
+ // call is a fresh invocation, not a fresh principal (Decision 4): it runs with
31
+ // the SAME identity the dispatching run had, carried across the hop and
32
+ // rehydrated here. There is no detached-specific authorization rule - the target
33
+ // and its nested calls flow through the normal `authorizeOutcome` path against the
34
+ // carried identity, exactly as a synchronous CallApi would.
35
+ // Payload arrives serialized (dates etc. survive the HTTP hop via
36
+ // @lowdefy/helpers serializer).
37
+ async function runDetachedEndpoint(context, { credentials = [], endpointId, outsideCaller = false, payload, principal }) {
29
38
  const { logger } = context;
39
+ // Marked before anything is logged: the payload can hold what the dispatcher marked.
40
+ if (credentials.length > 0) {
41
+ markCredential(credentials);
42
+ }
30
43
  context.endpointId = endpointId;
44
+ // Rehydrate the dispatcher's identity carried across the CRON_SECRET-gated
45
+ // hop BEFORE deriving authorizeOutcome and evaluateOperators, so both the auth check
46
+ // and the `_user` operator see the carried identity. This is a sanctioned
47
+ // substitute writer for resolveAuthentication - the principal was resolved
48
+ // upstream and built server-side, never from user input. A stale principal
49
+ // (roles changed between dispatch and run) is acceptable for at-most-once
50
+ // fire-and-forget - no re-resolution.
51
+ if (principal?.system === true) {
52
+ // The dispatcher was a trusted system context (cron, hook, or a verified
53
+ // webhook) - the detached run inherits it and blanket-passes, bound to the
54
+ // same organization and stand-in caller when it was bound to one.
55
+ const user = serializer.deserialize(principal.user ?? null);
56
+ applySystemTrust(context, {
57
+ organizationId: principal.organizationId,
58
+ caller: type.isNone(user) ? null : {
59
+ id: user.id,
60
+ name: user.name
61
+ }
62
+ });
63
+ } else {
64
+ // The dispatcher was a real user (or a strategy caller) - carry that
65
+ // identity. This is NOT a system context (context.system stays unset), so
66
+ // nested authorization is re-checked against these roles exactly as it
67
+ // would be in-invocation - the run reaches nothing the dispatcher could not
68
+ // reach synchronously.
69
+ context.user = serializer.deserialize(principal?.user ?? null);
70
+ context.authorizeOutcome = createAuthorizeOutcome(context);
71
+ }
31
72
  context.evaluateOperators = createEvaluateOperators(context);
32
73
  logger.debug({
33
74
  event: 'debug_detached_endpoint',
@@ -36,23 +77,28 @@ async function runDetachedEndpoint(context, { endpointId, payload }) {
36
77
  const endpointConfig = await getEndpointConfig(context, {
37
78
  endpointId
38
79
  });
39
- // Force a system context regardless of any session cookie sent with the request.
40
- // system: true — nested CallApi steps are authorized like function calls (the run
41
- // was already authorized at the transport layer), not re-gated on a user session.
42
- context.session = undefined;
43
- context.user = undefined;
44
- context.system = true;
45
- context.authorize = createAuthorize({
46
- session: undefined,
47
- system: true
80
+ authorizeApiEndpoint(context, {
81
+ endpointConfig
82
+ });
83
+ const deserializedPayload = serializer.deserialize(payload ?? {});
84
+ // A detached CallApi step's config built the payload. The dev server's agent
85
+ // tool runs a system endpoint through here with a payload the agent wrote
86
+ // (outsideCaller): see validatePayload.
87
+ validatePayload({
88
+ endpointConfig,
89
+ payload: deserializedPayload,
90
+ outsideCaller
48
91
  });
49
92
  const routineContext = {
50
93
  steps: {},
51
- payload: serializer.deserialize(payload ?? {}),
94
+ payload: deserializedPayload,
52
95
  arrayIndices: [],
96
+ error: null,
53
97
  items: {},
54
98
  state: {},
55
- endpointDepth: 0
99
+ endpointDepth: 0,
100
+ // The dispatcher's agent, carried in the principal like its identity.
101
+ agent: principal?.agent ?? null
56
102
  };
57
103
  const { error, response, status } = await runRoutine(context, routineContext, {
58
104
  routine: endpointConfig.routine
@@ -12,13 +12,25 @@
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 { type } from '@lowdefy/helpers';
15
+ */ import { LowdefyInternalError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
16
17
  import handleAgentCall from './handleAgentCall.js';
18
+ import handleAuthStep from './handleAuthStep.js';
19
+ import handleDescribeDynamicPolicy from './handleDescribeDynamicPolicy.js';
17
20
  import handleControl from './control/handleControl.js';
18
21
  import handleEndpointCall from './handleEndpointCall.js';
19
22
  import handleRenderNotification from './handleRenderNotification.js';
20
23
  import handleRequest from './handleRequest.js';
24
+ import handleValidateDynamic from './handleValidateDynamic.js';
21
25
  import handleValidateSchema from './handleValidateSchema.js';
26
+ // Errors a :catch can handle as an outcome of the call, not a fault in the app: a request or
27
+ // provider that failed or found nothing, an external service that did not answer, and author
28
+ // errors meant for the user. Config, operator and internal errors are faults even when caught.
29
+ const expectedCaughtErrorNames = new Set([
30
+ 'RequestError',
31
+ 'ServiceError',
32
+ 'UserError'
33
+ ]);
22
34
  async function runRoutine(context, routineContext, { routine }) {
23
35
  try {
24
36
  if (type.isObject(routine)) {
@@ -32,6 +44,16 @@ async function runRoutine(context, routineContext, { routine }) {
32
44
  step: routine
33
45
  });
34
46
  }
47
+ if (routine.id?.startsWith?.('validateDynamic:')) {
48
+ return await handleValidateDynamic(context, routineContext, {
49
+ step: routine
50
+ });
51
+ }
52
+ if (routine.id?.startsWith?.('describeDynamic:')) {
53
+ return await handleDescribeDynamicPolicy(context, routineContext, {
54
+ step: routine
55
+ });
56
+ }
35
57
  if (routine.id?.startsWith?.('validate:')) {
36
58
  return await handleValidateSchema(context, routineContext, {
37
59
  step: routine
@@ -42,6 +64,11 @@ async function runRoutine(context, routineContext, { routine }) {
42
64
  step: routine
43
65
  });
44
66
  }
67
+ if (routine.id?.startsWith?.('auth:')) {
68
+ return await handleAuthStep(context, routineContext, {
69
+ step: routine
70
+ });
71
+ }
45
72
  if (routine.id?.startsWith?.('notification:')) {
46
73
  return await handleRenderNotification(context, routineContext, {
47
74
  step: routine
@@ -68,7 +95,7 @@ async function runRoutine(context, routineContext, { routine }) {
68
95
  status: 'continue'
69
96
  };
70
97
  }
71
- throw new Error('Invalid routine.', {
98
+ throw new LowdefyInternalError('Invalid routine.', {
72
99
  cause: {
73
100
  routine
74
101
  }
@@ -80,9 +107,41 @@ async function runRoutine(context, routineContext, { routine }) {
80
107
  error
81
108
  };
82
109
  }
83
- // handleError sets error.handled once it has logged - it is the single sink
84
- // that owns the flag, so a nested runRoutine re-throwing this error does not
85
- // log it again.
110
+ // An expected error inside a :try with a :catch is handled by that :catch, so it is logged
111
+ // once, at debug (a provider's 404 in a waterfall is not a fault). The :catch can still
112
+ // rethrow it. Any other caught error still goes to handleError below, so its config location
113
+ // is resolved and it reaches the dev error feed and error tracking; the :catch runs as well.
114
+ if (routineContext.caught === true && expectedCaughtErrorNames.has(error.name)) {
115
+ if (!error.handled) {
116
+ context.logger.debug({
117
+ event: 'debug_routine_caught_error',
118
+ err: error
119
+ }, error.message);
120
+ error.handled = true;
121
+ }
122
+ return {
123
+ status: 'error',
124
+ error
125
+ };
126
+ }
127
+ // A UserError is an expected outcome, not a fault: it is logged once, as a
128
+ // warning. A step or control that logs one marks it handled; one thrown
129
+ // without being logged is logged here.
130
+ if (error.name === 'UserError') {
131
+ if (!error.handled) {
132
+ context.logger.warn({
133
+ event: 'warn_routine_user_error',
134
+ err: error
135
+ }, error.message);
136
+ error.handled = true;
137
+ }
138
+ return {
139
+ status: 'error',
140
+ error
141
+ };
142
+ }
143
+ // handleError sets error.handled once it has logged, so a nested runRoutine
144
+ // re-throwing this error does not log it again.
86
145
  if (!error.handled) {
87
146
  await context.handleError(error);
88
147
  }
@@ -13,7 +13,7 @@
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 createAuthorize from '../../context/createAuthorize.js';
16
+ import applySystemTrust from '../../context/applySystemTrust.js';
17
17
  import buildEndpointResult from '../../response/buildEndpointResult.js';
18
18
  import createEvaluateOperators from '../../context/createEvaluateOperators.js';
19
19
  import findSchedule from './findSchedule.js';
@@ -22,6 +22,7 @@ import getEnvironmentSchedules from './getEnvironmentSchedules.js';
22
22
  import resolveCronEnvironment from './resolveCronEnvironment.js';
23
23
  import runRoutine from './runRoutine.js';
24
24
  import scheduleBackground from './scheduleBackground.js';
25
+ import validatePayload from './validatePayload.js';
25
26
  // Runs an endpoint routine on a schedule (cron). Unlike callEndpoint this does NOT check the
26
27
  // endpoint's `auth` config and does NOT block InternalApi: a cron run is authorized by the transport
27
28
  // layer (CRON_SECRET) plus the endpoint declaring the firing schedule, and runs as a system context
@@ -56,20 +57,25 @@ async function runScheduledEndpoint(context, { endpointId, cron, environment })
56
57
  endpointId,
57
58
  environment: cronEnvironment
58
59
  });
59
- // Force a system context regardless of any session cookie sent with the request.
60
- // system: true — nested CallApi steps are authorized like function calls (the run
61
- // was already authorized at the transport layer), not re-gated on a user session.
62
- context.session = undefined;
63
- context.user = undefined;
64
- context.system = true;
65
- context.authorize = createAuthorize({
66
- session: undefined,
67
- system: true
60
+ // Cron is trusted at the transport (CRON_SECRET), so it holds a system
61
+ // context from construction, regardless of any session cookie sent with the
62
+ // request (Decisions 1, 2). The request context is a pre-resolved substitute
63
+ // writer for resolveAuthentication - the engine's single-writer carve-out -
64
+ // and applySystemTrust sets the same invariant bundle createSystemContext
65
+ // produces for the hook path.
66
+ applySystemTrust(context);
67
+ // An authored schedule.payload that breaks the endpoint's own contract fails
68
+ // the run.
69
+ const schedulePayload = schedule.payload ?? {};
70
+ validatePayload({
71
+ endpointConfig,
72
+ payload: schedulePayload
68
73
  });
69
74
  const routineContext = {
70
75
  steps: {},
71
- payload: schedule.payload ?? {},
76
+ payload: schedulePayload,
72
77
  arrayIndices: [],
78
+ error: null,
73
79
  items: {},
74
80
  state: {},
75
81
  endpointDepth: 0
@@ -77,6 +83,8 @@ async function runScheduledEndpoint(context, { endpointId, cron, environment })
77
83
  // async: true — acknowledge the cron trigger immediately and run in the
78
84
  // background; transport auth (CRON_SECRET) already passed at the route.
79
85
  if (endpointConfig.async === true) {
86
+ // The run outlives this request, so the request closing must not cancel it.
87
+ context.signal = undefined;
80
88
  scheduleBackground(context, {
81
89
  event: 'background_scheduled_endpoint',
82
90
  endpointId
@@ -12,23 +12,38 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import { ConfigError } from '@lowdefy/errors';
16
- import buildEndpointResult from '../../response/buildEndpointResult.js';
17
- import createAuthorize from '../../context/createAuthorize.js';
15
+ */ import { type } from '@lowdefy/helpers';
16
+ import { ConfigError } from '@lowdefy/errors';
17
+ import applySystemTrust from '../../context/applySystemTrust.js';
18
+ import createAuthorizeOutcome from '../../context/createAuthorizeOutcome.js';
18
19
  import createEvaluateOperators from '../../context/createEvaluateOperators.js';
20
+ import createWebhookAnswer from './createWebhookAnswer.js';
19
21
  import getEndpointConfig from './getEndpointConfig.js';
22
+ import parseWebhookBody from './parseWebhookBody.js';
20
23
  import runRoutine from './runRoutine.js';
21
- // Runs an endpoint declared `webhook: true` — a third-party webhook receiver
24
+ import runWebhookVerify from './runWebhookVerify.js';
25
+ // Runs an endpoint declared `webhook` — a third-party webhook receiver
22
26
  // (SNS, Event Grid, Stripe, ...) served on the standard /api/endpoints route,
23
27
  // but taking the request RAW: bodies are the caller's own format, not
24
28
  // Lowdefy's { payload } envelope, so the routine receives
25
29
  // { body, query, headers } as its payload and its return value is sent back
26
- // verbatim (handshakes require exact response shapes). Only endpoints that
27
- // opt in are runnable here (a missing flag reads as a missing endpoint — no
28
- // probing). The transport is public by design: authenticating the caller
29
- // (shared-secret query param, signature header) is the webhook routine's own
30
- // first step. Executes as a system context.
31
- async function runWebhookEndpoint(context, { endpointId, body, query, headers }) {
30
+ // verbatim (handshakes require exact response shapes). It returns the HTTP
31
+ // answer, { status, body, contentType? }, that the route sends (see
32
+ // createWebhookAnswer): JSON, or text when contentType is text/plain.
33
+ // Only endpoints that opt in are runnable here (a missing flag reads as a
34
+ // missing endpoint — no probing).
35
+ //
36
+ // The transport is public by design, so the run starts caller-less AND
37
+ // UNTRUSTED (Decision 3): context.user = null, context.system unset. It earns
38
+ // trust only when its declared `webhook.verify` gate passes, run mechanically
39
+ // BEFORE the routine body - so verification can never be forgotten, mis-ordered,
40
+ // or placed after a privileged CallApi. A webhook with no declared verifier
41
+ // runs untrusted throughout, so any nested protected CallApi fails closed.
42
+ //
43
+ // rawBody is the request body exactly as received. Only the verifier sees it
44
+ // (a sender's signature is computed over those bytes, which re-serialising the
45
+ // parsed body does not reproduce); the routine gets the parsed body.
46
+ async function runWebhookEndpoint(context, { endpointId, rawBody, query, headers }) {
32
47
  const { logger } = context;
33
48
  context.endpointId = endpointId;
34
49
  context.evaluateOperators = createEvaluateOperators(context);
@@ -39,7 +54,8 @@ async function runWebhookEndpoint(context, { endpointId, body, query, headers })
39
54
  const endpointConfig = await getEndpointConfig(context, {
40
55
  endpointId
41
56
  });
42
- if (endpointConfig.webhook !== true) {
57
+ // webhook may be `true` or a `{ verify }` object — gate on truthiness.
58
+ if (!endpointConfig.webhook) {
43
59
  const err = new ConfigError(`API Endpoint "${endpointId}" does not exist.`);
44
60
  logger.debug({
45
61
  params: {
@@ -49,32 +65,63 @@ async function runWebhookEndpoint(context, { endpointId, body, query, headers })
49
65
  }, err.message);
50
66
  throw err;
51
67
  }
52
- // Force a system context regardless of any session cookie sent with the request.
53
- // system: true — nested CallApi steps are authorized like function calls (the run
54
- // was already authorized at the transport layer), not re-gated on a user session.
55
- context.session = undefined;
56
- context.user = undefined;
57
- context.system = true;
58
- context.authorize = createAuthorize({
59
- session: undefined,
60
- system: true
68
+ // Caller-less and UNTRUSTED: with context.system unset, createAuthorizeOutcome
69
+ // fails closed on any protected target exactly as an unauthenticated call would
70
+ // (Api and InternalApi alike — InternalApi is an HTTP-exposure choice, not a
71
+ // trust tier, so it earns no special pass).
72
+ context.user = null;
73
+ context.authorizeOutcome = createAuthorizeOutcome(context);
74
+ // A declared verifier is the only thing that can make the run trusted, and it
75
+ // runs before any routine step. On success the runner (not routine or
76
+ // resolver code) sets context.system, matching the state createSystemContext
77
+ // produces for cron. On failure the routine never runs.
78
+ const body = parseWebhookBody({
79
+ rawBody
61
80
  });
81
+ const verify = type.isObject(endpointConfig.webhook) ? endpointConfig.webhook.verify : undefined;
82
+ if (!type.isNone(verify)) {
83
+ const verified = await runWebhookVerify(context, {
84
+ verify,
85
+ body,
86
+ rawBody,
87
+ query,
88
+ headers
89
+ });
90
+ if (!verified) {
91
+ logger.warn({
92
+ event: 'webhook_verify_failed',
93
+ endpointId
94
+ });
95
+ return {
96
+ status: 401,
97
+ body: {
98
+ error: {
99
+ code: 'unauthorized',
100
+ message: 'Webhook verification failed.'
101
+ }
102
+ }
103
+ };
104
+ }
105
+ applySystemTrust(context);
106
+ }
62
107
  const routineContext = {
63
108
  steps: {},
64
109
  payload: {
65
- body: body ?? null,
110
+ body,
66
111
  query: query ?? {},
67
112
  headers: headers ?? {}
68
113
  },
69
114
  arrayIndices: [],
115
+ error: null,
70
116
  items: {},
71
117
  state: {},
72
118
  endpointDepth: 0
73
119
  };
74
- const { error, response, status } = await runRoutine(context, routineContext, {
120
+ const { contentType, error, response, status } = await runRoutine(context, routineContext, {
75
121
  routine: endpointConfig.routine
76
122
  });
77
- return buildEndpointResult(context, {
123
+ return createWebhookAnswer(context, {
124
+ contentType,
78
125
  error,
79
126
  response,
80
127
  status
@@ -0,0 +1,129 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { ServiceError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ import callRequestResolver from '../request/callRequestResolver.js';
18
+ import evaluateRequestOperators from '../request/evaluateOperators.js';
19
+ import getConnection from '../connections/getConnection.js';
20
+ import getConnectionConfig from '../connections/getConnectionConfig.js';
21
+ import getRequestResolver from '../request/getRequestResolver.js';
22
+ import operatorScope from './operatorScope.js';
23
+ import resolveTenancy from '../request/resolveTenancy.js';
24
+ // Runs the endpoint's declared `webhook.verify` request plugin as a gate,
25
+ // against the RAW request (body, rawBody, query, headers), before the routine body
26
+ // (Decision 3). The verifier is a request plugin - the same class of code as a
27
+ // connection request - resolved and invoked through the request-plugin
28
+ // machinery, never as a routine step. It reads the request and reports a
29
+ // verdict; the RUNNER (not routine or resolver code) performs the trust
30
+ // transition, so there is no trust-writing capability on the resolver surface.
31
+ //
32
+ // Returns true only when the verifier passes: it must not throw and must return
33
+ // `true` or `{ verified: true }`. A verifier that throws (e.g. a bad signature)
34
+ // is a failed gate, not a server fault - it fails closed to a false verdict.
35
+ // Config-resolution errors (missing connection / unknown request type) throw:
36
+ // a misconfigured verifier breaks loudly in development rather than silently
37
+ // trusting or silently failing.
38
+ async function runWebhookVerify(context, { verify, body, rawBody, query, headers }) {
39
+ const payload = {
40
+ body,
41
+ rawBody,
42
+ query: query ?? {},
43
+ headers: headers ?? {}
44
+ };
45
+ const connectionConfig = await getConnectionConfig(context, {
46
+ connectionId: verify.connectionId,
47
+ configKey: verify['~k']
48
+ });
49
+ const connection = getConnection(context, {
50
+ connectionConfig
51
+ });
52
+ const requestConfig = {
53
+ type: verify.type,
54
+ connectionId: verify.connectionId,
55
+ requestId: 'webhook.verify',
56
+ properties: verify.properties ?? {},
57
+ // The verifier runs before the run earns trust, with no caller
58
+ // organization, so a verifier on a tenant connection fails closed (caught
59
+ // at resolveTenancy below, verdict false) unless the verify config opts
60
+ // out with tenant: none - which may only read, like any tenant: none
61
+ // request.
62
+ tenant: verify.tenant,
63
+ '~k': verify['~k']
64
+ };
65
+ const requestResolver = getRequestResolver(context, {
66
+ connection,
67
+ requestConfig
68
+ });
69
+ let tenancy;
70
+ try {
71
+ tenancy = resolveTenancy(context, {
72
+ connection,
73
+ connectionConfig,
74
+ requestConfig,
75
+ writes: requestResolver.meta.checkWrite === true
76
+ });
77
+ } catch (error) {
78
+ // Only the org-less-caller refusal is a gate outcome - it must not reach
79
+ // the unauthenticated webhook sender as an error body. Config errors
80
+ // (tenant declared on a type without the contract, a writing verifier
81
+ // under tenant: none) still throw: a misconfigured verifier breaks
82
+ // loudly, per the contract above, rather than failing every webhook as
83
+ // an unverified one inside the resolver call below.
84
+ if (error.name !== 'AuthenticationError') {
85
+ throw error;
86
+ }
87
+ context.logger.debug({
88
+ event: 'debug_webhook_verify_error',
89
+ err: error
90
+ }, error.message);
91
+ return false;
92
+ }
93
+ // The verifier runs before the routine, so it evaluates against a frame of its
94
+ // own: the webhook payload, with no routine state or step results yet.
95
+ const { connectionProperties, requestProperties } = evaluateRequestOperators(context, {
96
+ connectionConfig,
97
+ requestConfig,
98
+ routineContext: operatorScope({
99
+ items: {},
100
+ payload,
101
+ state: {},
102
+ steps: {}
103
+ })
104
+ });
105
+ try {
106
+ const response = await callRequestResolver(context, {
107
+ connectionProperties,
108
+ endpointDepth: 0,
109
+ requestConfig,
110
+ requestProperties,
111
+ requestResolver,
112
+ tenant: tenancy.tenant,
113
+ tenantGuard: tenancy.tenantGuard
114
+ });
115
+ return response === true || type.isObject(response) && response.verified === true;
116
+ } catch (error) {
117
+ // An unreachable verification service is an outage, not a failed signature -
118
+ // swallowing it into a false verdict would report a forged webhook.
119
+ if (ServiceError.isServiceError(error) || error.name === 'ServiceError') {
120
+ throw error;
121
+ }
122
+ context.logger.debug({
123
+ event: 'debug_webhook_verify_error',
124
+ err: error
125
+ }, error.message);
126
+ return false;
127
+ }
128
+ }
129
+ export default runWebhookVerify;
@@ -33,6 +33,16 @@ function scheduleBackground(context, { event, endpointId }, fn) {
33
33
  status: result?.status
34
34
  });
35
35
  } catch (err) {
36
+ // A UserError is the caller's mistake, not a fault: warn level, as on
37
+ // every other call path.
38
+ if (err.name === 'UserError') {
39
+ logger.warn({
40
+ event: `${event}_failed`,
41
+ endpointId,
42
+ err
43
+ }, err.message);
44
+ return;
45
+ }
36
46
  logger.error({
37
47
  event: `${event}_failed`,
38
48
  endpointId,