@lowdefy/api 6.1.0 → 7.1.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
@@ -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,14 +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: [],
33
43
  error: null,
34
44
  items: {},
35
45
  state: {},
36
- 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)
37
60
  };
38
61
  return runRoutine(context, childRoutineContext, {
39
62
  routine: endpointConfig.routine
@@ -15,8 +15,9 @@
15
15
  */ // The routine fields operators can read. A field added to the routine frame goes here, so every
16
16
  // routine step and control sees it rather than only the ones that remembered to pass it.
17
17
  function operatorScope(routineContext) {
18
- const { error, items, payload, state, steps } = routineContext;
18
+ const { agent, error, items, payload, state, steps } = routineContext;
19
19
  return {
20
+ agent: agent ?? null,
20
21
  error: error ?? null,
21
22
  items,
22
23
  payload,
@@ -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 createCallbackPlugins({ authConfig, plugins, type }) {
16
- return authConfig.callbacks.map((callbackConfig)=>({
17
- fn: plugins.callbacks[callbackConfig.type],
18
- properties: callbackConfig.properties
19
- })).filter((callback)=>callback.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 createCallbackPlugins;
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;
@@ -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,24 +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: [],
53
96
  error: null,
54
97
  items: {},
55
98
  state: {},
56
- endpointDepth: 0
99
+ endpointDepth: 0,
100
+ // The dispatcher's agent, carried in the principal like its identity.
101
+ agent: principal?.agent ?? null
57
102
  };
58
103
  const { error, response, status } = await runRoutine(context, routineContext, {
59
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,19 +57,23 @@ 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: [],
73
78
  error: null,
74
79
  items: {},
@@ -78,6 +83,8 @@ async function runScheduledEndpoint(context, { endpointId, cron, environment })
78
83
  // async: true — acknowledge the cron trigger immediately and run in the
79
84
  // background; transport auth (CRON_SECRET) already passed at the route.
80
85
  if (endpointConfig.async === true) {
86
+ // The run outlives this request, so the request closing must not cancel it.
87
+ context.signal = undefined;
81
88
  scheduleBackground(context, {
82
89
  event: 'background_scheduled_endpoint',
83
90
  endpointId