@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
@@ -23,6 +23,7 @@ import controlSetState from './controlSetState.js';
23
23
  import controlSwitch from './controlSwitch.js';
24
24
  import controlThrow from './controlThrow.js';
25
25
  import controlTry from './controlTry.js';
26
+ import controlWhile from './controlWhile.js';
26
27
  const controlHandlers = {
27
28
  ':for': controlFor,
28
29
  ':if': controlIf,
@@ -34,7 +35,8 @@ const controlHandlers = {
34
35
  ':set_state': controlSetState,
35
36
  ':switch': controlSwitch,
36
37
  ':throw': controlThrow,
37
- ':try': controlTry
38
+ ':try': controlTry,
39
+ ':while': controlWhile
38
40
  };
39
41
  async function handleControl(context, routineContext, { control }) {
40
42
  for (const [key, handler] of Object.entries(controlHandlers)){
@@ -0,0 +1,78 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { serializer } from '@lowdefy/helpers';
16
+ import redactResponse from '../../response/redactResponse.js';
17
+ // The route sends a webhook's answer to a third party, not the Lowdefy client, as plain JSON: a
18
+ // date arrives as an ISO string, not the serializer's { "~d": ... } form, and no build marker
19
+ // crosses.
20
+ function toPlainJson(context, value) {
21
+ return serializer.deserialize(redactResponse(context, value));
22
+ }
23
+ function errorBody({ code, message }) {
24
+ return {
25
+ error: {
26
+ code,
27
+ message
28
+ }
29
+ };
30
+ }
31
+ // The HTTP status and body a webhook route answers with, from the routine's outcome. A :reject
32
+ // answers the :status and :body it set (400 and an error body by default), also when it was
33
+ // raised in an endpoint the routine called. A failed ValidateSchema step answers 400. Any other
34
+ // failure answers 500 with a fixed message, so nothing from the error reaches the caller. A :return
35
+ // with :content_type answers its string as is, for a handshake that wants a text reply.
36
+ function createWebhookAnswer(context, { contentType, error, response, status }) {
37
+ if (status === 'reject') {
38
+ return {
39
+ status: error.webhookStatus ?? 400,
40
+ body: Object.hasOwn(error, 'webhookBody') ? toPlainJson(context, error.webhookBody) : errorBody({
41
+ code: 'rejected',
42
+ message: error.message
43
+ })
44
+ };
45
+ }
46
+ if (status === 'error' && error?.isInvalidRequest === true) {
47
+ return {
48
+ status: 400,
49
+ body: errorBody({
50
+ code: 'invalid_request',
51
+ message: error.message
52
+ })
53
+ };
54
+ }
55
+ if (status === 'error') {
56
+ return {
57
+ status: 500,
58
+ body: errorBody({
59
+ code: 'internal_error',
60
+ message: 'Webhook failed.'
61
+ })
62
+ };
63
+ }
64
+ if (contentType === 'text/plain') {
65
+ return {
66
+ status: 200,
67
+ body: response,
68
+ contentType
69
+ };
70
+ }
71
+ return {
72
+ status: 200,
73
+ body: toPlainJson(context, response) ?? {
74
+ ok: true
75
+ }
76
+ };
77
+ }
78
+ export default createWebhookAnswer;
@@ -0,0 +1,27 @@
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 operatorScope from './operatorScope.js';
16
+ // Every routine step evaluates against the same frame. Taking the frame from routineContext in one
17
+ // place means a step handler cannot drop part of it (state, items, loop indices).
18
+ function evaluateRoutineOperators(context, routineContext, { input, literalData, location }) {
19
+ return context.evaluateOperators({
20
+ arrayIndices: routineContext.arrayIndices,
21
+ input,
22
+ literalData,
23
+ location,
24
+ ...operatorScope(routineContext)
25
+ });
26
+ }
27
+ export default evaluateRoutineOperators;
@@ -18,29 +18,34 @@ import findSchedule from './findSchedule.js';
18
18
  import getEndpointConfig from './getEndpointConfig.js';
19
19
  import getEnvironmentSchedules from './getEnvironmentSchedules.js';
20
20
  import scheduleBackground from './scheduleBackground.js';
21
- // Vercel fires cron jobs only on the production deployment, so the schedules of every other
22
- // environment are registered there as /api/cron-forward/<environment>/<endpointId> jobs. When one
23
- // fires, this pings the environment's own /api/cron/<endpointId> with that environment's
24
- // CRON_SECRET (a Lowdefy secret named in config.cron.environments) so the environment runs its own
25
- // code, and answers Vercel immediately: the ping is fire-and-forget, kept alive by scheduleBackground
26
- // and bounded by the function duration, and its outcome exists only in the logs.
21
+ // Vercel fires cron jobs only on the production deployment, so the schedules of every environment
22
+ // with a cron.secret are registered there as /api/cron-forward/<environment>/<endpointId> jobs. When
23
+ // one fires, this pings the environment's own <basePath>/api/cron/<endpointId> at its url with that
24
+ // environment's CRON_SECRET (the Lowdefy secret named by config.environments.<env>.cron.secret) so
25
+ // the environment runs its own code, and answers Vercel immediately: the ping is fire-and-forget,
26
+ // kept alive by scheduleBackground and bounded by the function duration, and its outcome exists only
27
+ // in the logs.
27
28
  async function forwardScheduledEndpoint(context, { environment, endpointId, cron }) {
28
29
  const { config, logger, secrets } = context;
29
- const target = config?.cron?.environments?.[environment];
30
+ const target = config?.environments?.[environment];
30
31
  if (!type.isObject(target)) {
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
- if (type.isUndefined(target.url)) {
34
- throw new ConfigError(`Cron environment "${environment}" has no url to forward to: it is the environment that runs the crons.`);
34
+ if (environment === config.environment) {
35
+ throw new ConfigError(`Cron environment "${environment}" is this deployment's own environment: its crons run here, not forwarded.`);
35
36
  }
36
- if (target.enabled === false) {
37
+ if (target.cron?.enabled === false) {
37
38
  throw new ConfigError(`Cron environment "${environment}" is disabled.`);
38
39
  }
39
- const secret = secrets?.[target.secret];
40
+ const secretName = target.cron?.secret;
41
+ if (type.isUndefined(secretName)) {
42
+ throw new ConfigError(`Cron environment "${environment}" has no cron.secret: crons are only forwarded to environments with one.`);
43
+ }
44
+ const secret = secrets?.[secretName];
40
45
  if (!type.isString(secret) || secret === '') {
41
- throw new ConfigError(`Secret "${target.secret}" holding the CRON_SECRET of cron environment "${environment}" is not set. Set the LOWDEFY_SECRET_${target.secret} environment variable on this deployment.`);
46
+ throw new ConfigError(`Secret "${secretName}" holding the CRON_SECRET of cron environment "${environment}" is not set. Set the LOWDEFY_SECRET_${secretName} environment variable on this deployment.`);
42
47
  }
43
- // The same build is deployed to every environment, so the local artifact says whether the target
48
+ // Every environment builds from the same config, so the local artifact says whether the target
44
49
  // declares the firing schedule: fail here with a config error instead of having the target 500.
45
50
  const endpointConfig = await getEndpointConfig(context, {
46
51
  endpointId
@@ -60,7 +65,8 @@ async function forwardScheduledEndpoint(context, { environment, endpointId, cron
60
65
  while(origin.endsWith('/')){
61
66
  origin = origin.slice(0, -1);
62
67
  }
63
- const url = `${origin}/api/cron/${endpointId}`;
68
+ // The environment's url is its origin; the app mounts its routes under config.basePath.
69
+ const url = `${origin}${config.basePath ?? ''}/api/cron/${endpointId}`;
64
70
  const timeoutMs = (config?.vercel?.maxDuration ?? 60) * 1000;
65
71
  const headers = {
66
72
  authorization: `Bearer ${secret}`
@@ -13,16 +13,26 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { AuthenticationError, ConfigError } from '@lowdefy/errors';
16
- import isUnauthenticatedHuman from './isUnauthenticatedHuman.js';
17
- // A missing endpoint answers the same as a protected one for an anonymous
18
- // caller on an auth'd app - the message is byte-identical to the one
19
- // authorizeApiEndpoint throws, so present and absent are indistinguishable
20
- // before authenticating. Every other caller keeps the opaque does-not-exist.
21
- async function getEndpointConfig(context, { endpointId }) {
22
- const { logger, readConfigFile } = context;
16
+ import { type } from '@lowdefy/helpers';
17
+ // A missing endpoint id answers the same as a protected one for an anonymous
18
+ // human on an auth'd app: before you authenticate, the only answer is
19
+ // authenticate. Otherwise a logged-out caller enumerates endpoint ids by
20
+ // response difference - 500 for a miss (the handler special-cases only
21
+ // AuthenticationError) versus 401 for a protected one. An authenticated caller
22
+ // gets today's opaque "does not exist" for both a miss and a role refusal,
23
+ // unchanged.
24
+ //
25
+ // Guarded on authEnforcement != null (auth configured) and system !== true (not
26
+ // the engine talking to itself), exactly as the page fork is: "no user" is not
27
+ // "anonymous human who should sign in" - it is also "no auth here" and "this is
28
+ // a system run", and neither should be told to authenticate against nothing.
29
+ // This is NOT a per-entity apiProtectedByDefault default; no such glob surface
30
+ // exists.
31
+ async function getEndpointConfig({ authEnforcement, logger, readConfigFile, system, user }, { endpointId }) {
23
32
  const endpoint = await readConfigFile(`api/${endpointId}.json`);
24
33
  if (!endpoint) {
25
- const err = await isUnauthenticatedHuman(context) ? new AuthenticationError(`Authentication required for API endpoint "${endpointId}".`) : new ConfigError(`API Endpoint "${endpointId}" does not exist.`);
34
+ const unauthenticatedHuman = type.isNone(user) && !type.isNone(authEnforcement) && system !== true;
35
+ const err = unauthenticatedHuman ? new AuthenticationError(`Authentication required for API endpoint "${endpointId}".`) : new ConfigError(`API Endpoint "${endpointId}" does not exist.`);
26
36
  logger.debug({
27
37
  params: {
28
38
  endpointId
@@ -13,17 +13,15 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { type } from '@lowdefy/helpers';
16
- // With config.cron.environments declared the build resolves `schedules` onto every environment
17
- // (schedules.<name>, defaults inherited), so an environment run reads its own list; without
18
- // environments the endpoint carries a plain array.
16
+ // With config.environments declared the build resolves `schedules` onto every environment
17
+ // (schedules.<name>, defaults inherited, plus schedules.default), so an environment run reads its
18
+ // own list and a deployment with no current environment reads the default; without environments
19
+ // the endpoint carries a plain array.
19
20
  function getEnvironmentSchedules({ endpointConfig, environment }) {
20
21
  const schedules = endpointConfig.schedules;
21
22
  if (type.isArray(schedules)) {
22
23
  return schedules;
23
24
  }
24
- if (environment === undefined) {
25
- return [];
26
- }
27
- return schedules?.[environment] ?? [];
25
+ return schedules?.[environment ?? 'default'] ?? [];
28
26
  }
29
27
  export default getEnvironmentSchedules;
@@ -0,0 +1,39 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { compile } from '@lowdefy/ajv';
16
+ import { LRUCache, serializer } from '@lowdefy/helpers';
17
+ // A ValidateSchema step evaluates its schema property on every call, so each
18
+ // call hands over a new object, and operators in it can change the schema from
19
+ // one call to the next. Validators are cached by the schema's content: the same
20
+ // schema compiles once, a different one gets its own validator, and the cache
21
+ // stays bounded.
22
+ const validators = new LRUCache({
23
+ maxSize: 100
24
+ });
25
+ function getSchemaValidator({ schema }) {
26
+ const key = serializer.serializeToString(schema, {
27
+ stable: true,
28
+ skipMarkers: true
29
+ });
30
+ let validator = validators.get(key);
31
+ if (!validator) {
32
+ validator = compile({
33
+ schema
34
+ });
35
+ validators.set(key, validator);
36
+ }
37
+ return validator;
38
+ }
39
+ export default getSchemaValidator;
@@ -16,22 +16,20 @@
16
16
  import { type } from '@lowdefy/helpers';
17
17
  import addStepResult from './addStepResult.js';
18
18
  import prepareAgent from '../agent/prepareAgent.js';
19
+ import evaluateRoutineOperators from './evaluateRoutineOperators.js';
19
20
  async function handleAgentCall(context, routineContext, { step }) {
20
- const { logger, evaluateOperators } = context;
21
+ const { logger } = context;
21
22
  logger.debug({
22
23
  event: 'debug_start_agent_call',
23
24
  step
24
25
  });
25
- // Evaluate operators in step.properties (resolves agentId, prompt)
26
- const evaluatedProperties = evaluateOperators({
26
+ // Evaluate operators in step.properties (resolves agentId, prompt, files)
27
+ const evaluatedProperties = evaluateRoutineOperators(context, routineContext, {
27
28
  input: step.properties,
28
- items: routineContext.items,
29
- location: step.stepId,
30
- payload: routineContext.payload,
31
- state: routineContext.state,
32
- steps: routineContext.steps
29
+ location: step.stepId
33
30
  });
34
31
  const { agentId, prompt } = evaluatedProperties;
32
+ const files = evaluatedProperties.files ?? [];
35
33
  if (!type.isString(agentId)) {
36
34
  throw new ConfigError(`CallAgent step "${step.stepId}" properties.agentId must evaluate to a string. Received ${JSON.stringify(agentId)}.`, {
37
35
  configKey: step['~k']
@@ -42,12 +40,28 @@ async function handleAgentCall(context, routineContext, { step }) {
42
40
  configKey: step['~k']
43
41
  });
44
42
  }
43
+ // A file url is usually a signed link, and these errors reach the server log, so they name
44
+ // the type received rather than the value.
45
+ if (!type.isArray(files)) {
46
+ throw new ConfigError(`CallAgent step "${step.stepId}" properties.files must evaluate to an array. Received a value of type "${typeof files}".`, {
47
+ configKey: step['~k']
48
+ });
49
+ }
50
+ files.forEach((file, index)=>{
51
+ if (!type.isObject(file) || !type.isString(file.url) || !URL.canParse(file.url) || !type.isString(file.mediaType)) {
52
+ const received = type.isObject(file) ? `a url of type "${typeof file.url}" and a mediaType of type "${typeof file.mediaType}"` : `a value of type "${typeof file}"`;
53
+ throw new ConfigError(`CallAgent step "${step.stepId}" properties.files[${index}] must have a url and a mediaType string. Received ${received}.`, {
54
+ configKey: step['~k']
55
+ });
56
+ }
57
+ });
45
58
  // Headless agent context — no page, no conversation, no sharedState (which
46
59
  // also excludes the client-only update-page-state tool). userId is null
47
60
  // under scheduled (system) context.
48
61
  const agentContext = {
49
62
  conversationId: null,
50
63
  pageId: null,
64
+ pathParams: {},
51
65
  sharedState: undefined,
52
66
  urlQuery: {},
53
67
  userId: context.user?.sub ?? context.user?.id ?? null
@@ -56,13 +70,15 @@ async function handleAgentCall(context, routineContext, { step }) {
56
70
  agentId,
57
71
  agentContext,
58
72
  endpointDepth: routineContext.endpointDepth,
73
+ files: [],
59
74
  mode: 'generate'
60
75
  });
61
76
  const { result } = await agentType.resolver({
62
77
  connection: connectionInstance,
63
78
  properties: {
64
79
  agent: agentConfig,
65
- prompt
80
+ prompt,
81
+ files
66
82
  },
67
83
  context: resolverContext
68
84
  });
@@ -0,0 +1,214 @@
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 { AuthorizationError, ConfigError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ import { markCredential } from '@lowdefy/node-utils';
18
+ import addStepResult from './addStepResult.js';
19
+ import authorizeRole from '../auth/organizations/authorizeRole.js';
20
+ import evaluateRoutineOperators from './evaluateRoutineOperators.js';
21
+ import resolveStepOrganizationId from './resolveStepOrganizationId.js';
22
+ // Refusals name what was asked for, because "refused" with no subject is the
23
+ // failure people report: { member: ['update'] } reads as "member: [update]".
24
+ function describePermissions(permissions) {
25
+ return Object.entries(permissions ?? {}).map(([resource, actions])=>`${resource}: [${(actions ?? []).join(', ')}]`).join(', ');
26
+ }
27
+ async function handleAuthStep(context, routineContext, { step }) {
28
+ const { logger } = context;
29
+ logger.debug({
30
+ event: 'debug_start_auth_step',
31
+ step
32
+ });
33
+ // Evaluate operators in step.properties before resolving the step type, so
34
+ // a malformed properties block surfaces the same way it does for every
35
+ // other step type.
36
+ const evaluatedProperties = evaluateRoutineOperators(context, routineContext, {
37
+ input: step.properties,
38
+ location: step.stepId
39
+ });
40
+ const stepFn = context.steps?.[step.type];
41
+ if (type.isNone(stepFn)) {
42
+ throw new ConfigError(`Auth step type "${step.type}" is not defined.`, {
43
+ configKey: step['~k']
44
+ });
45
+ }
46
+ // Checked before the caller - an auth-less app should hear "no auth
47
+ // engine", not a misleading missing-caller error.
48
+ if (type.isNone(context.auth)) {
49
+ throw new ConfigError(`Auth step "${step.stepId}" requires the auth engine - auth is not configured (or dev.mockUser is active).`, {
50
+ configKey: step['~k']
51
+ });
52
+ }
53
+ // The floor passes on either of two independent doors (Decision 1):
54
+ // 1. a run-level system context (context.system === true) - a trusted,
55
+ // caller-less run (cron, hook, verified webhook), or
56
+ // 2. a single step marked system (step.system === true, admin's
57
+ // skipUserAdminRoleCheck) - a per-step waiver in an otherwise
58
+ // user/public run, which never sets context.system.
59
+ // Either door makes the step act caller-less as the system.
60
+ const actingAsSystem = context.system === true || step.system === true;
61
+ // A resolved caller is context.user carrying an id. A caller-less run needs
62
+ // no principal only when one of the two system doors is open.
63
+ const hasCaller = type.isObject(context.user) && !type.isNone(context.user.id);
64
+ if (!hasCaller && !actingAsSystem) {
65
+ throw new ConfigError(`Auth step "${step.stepId}" requires an authenticated caller. Set system: true on the step for caller-less system routines.`, {
66
+ configKey: step['~k']
67
+ });
68
+ }
69
+ // Acting as the system is an explicit trust decision, not attribution - the
70
+ // step runs caller-less as the system (even when a caller is present, for
71
+ // the per-step marker).
72
+ const acting = actingAsSystem ? {
73
+ system: true,
74
+ user: null
75
+ } : {
76
+ system: false,
77
+ user: context.user
78
+ };
79
+ // The user-administration floor. It is per-step and per-scope: each step
80
+ // declares the authority it requires in meta.authority, and the floor
81
+ // enforces it mechanically here so an app can never expose member mutation
82
+ // by forgetting a check. Only seven of the sixteen steps call an organization
83
+ // plugin endpoint; the other nine go adapter-direct or through the admin
84
+ // plugin, whose check reads a deployment-wide user.role and structurally
85
+ // cannot answer "is the caller an administrator of THIS organization". For
86
+ // those nine, no check that can express per-organization authority runs
87
+ // anywhere else - the floor is their only authorization.
88
+ const authority = stepFn.meta?.authority;
89
+ if (type.isNone(authority)) {
90
+ throw new ConfigError(`Auth step "${step.stepId}" of type "${step.type}" declares no "meta.authority" - every auth step must declare the authority it requires.`, {
91
+ configKey: step['~k']
92
+ });
93
+ }
94
+ // A system-scoped step has no organization to be authorized in, so a caller
95
+ // can never satisfy it - it runs only where the run itself is trusted.
96
+ if (authority.scope === 'system' && acting.system !== true) {
97
+ throw new ConfigError(`Auth step "${step.stepId}" may only run in a caller-less system routine. Set system: true on the step, or run it from a system context.`, {
98
+ configKey: step['~k']
99
+ });
100
+ }
101
+ // A caller-scoped step acts only on rows the caller owns (their own MCP
102
+ // grant, their own membership), so it needs no organization authority - but
103
+ // it has no meaning without a caller, and the system has no rows of its own
104
+ // to act on.
105
+ if (authority.scope === 'caller' && acting.system === true) {
106
+ throw new ConfigError(`Auth step "${step.stepId}" acts on the caller's own records and cannot run as the system. Remove system: true, or run it from a caller's routine.`, {
107
+ configKey: step['~k']
108
+ });
109
+ }
110
+ // Resolved for every org-scoped step, including the ones acting as the
111
+ // system: the step is told which organization it writes in rather than
112
+ // working it out again, so the organization the floor authorized and the
113
+ // organization the step writes into cannot drift apart.
114
+ const organizationId = authority.scope === 'org' ? await resolveStepOrganizationId({
115
+ auth: context.auth,
116
+ configKey: step['~k'],
117
+ organization: context.organization,
118
+ properties: evaluatedProperties,
119
+ stepId: step.stepId
120
+ }) : null;
121
+ // Both system doors bypass the checks below - acting as the system is the
122
+ // trust decision, and an author-declared step.system is an escape hatch
123
+ // visible in a diff. Reaching the block means acting.system !== true, so the
124
+ // system-scope refusal above and this branch are exclusive.
125
+ if (authority.scope === 'org' && acting.system !== true) {
126
+ // Evaluated before the scope check: a person saves their own profile
127
+ // without holding any org authority, and without holding a member row in
128
+ // the organization the request happens to name.
129
+ const selfTargetKey = authority.selfTargetExempt;
130
+ const selfTargeted = !type.isNone(selfTargetKey) && evaluatedProperties?.[selfTargetKey] === context.user.id;
131
+ if (!selfTargeted) {
132
+ const { adapter } = await context.auth.$context;
133
+ // The caller's authority is their member row in the TARGET organization,
134
+ // which is the same question the organization endpoint would ask, asked
135
+ // one layer earlier so the adapter-direct and admin-plugin steps get it
136
+ // too.
137
+ const callerMember = await adapter.findOne({
138
+ model: 'member',
139
+ where: [
140
+ {
141
+ field: 'userId',
142
+ value: context.user.id
143
+ },
144
+ {
145
+ field: 'organizationId',
146
+ value: organizationId
147
+ }
148
+ ]
149
+ });
150
+ if (type.isNone(callerMember) || !authorizeRole({
151
+ permissions: authority.permissions,
152
+ role: callerMember.role
153
+ })) {
154
+ throw new AuthorizationError(`Auth step "${step.stepId}" refused - the caller does not hold ${describePermissions(authority.permissions)} in organization "${organizationId}".`);
155
+ }
156
+ // A step that writes the user row reaches a row shared by the whole
157
+ // deployment, so org authority alone would let an administrator of any
158
+ // organization reach any user. Membership in the same organization is
159
+ // what makes the target the caller's business. Steps that write a member
160
+ // row declare no targetUser - their target is already a row there. An
161
+ // absent property is the step's own required-property error, so leave it
162
+ // to the step.
163
+ const targetId = type.isNone(authority.targetUser) ? undefined : evaluatedProperties?.[authority.targetUser];
164
+ if (!type.isNone(targetId)) {
165
+ const targetMember = await adapter.findOne({
166
+ model: 'member',
167
+ where: [
168
+ {
169
+ field: 'userId',
170
+ value: targetId
171
+ },
172
+ {
173
+ field: 'organizationId',
174
+ value: organizationId
175
+ }
176
+ ]
177
+ });
178
+ if (type.isNone(targetMember)) {
179
+ throw new AuthorizationError(`Auth step "${step.stepId}" refused - user "${targetId}" is not a member of organization "${organizationId}".`);
180
+ }
181
+ }
182
+ }
183
+ }
184
+ // organization is the retained organizations state ({ policy, pinned }) -
185
+ // steps read policy for their own messages. organizationId is the resolved
186
+ // target, which is what a step scopes its write to.
187
+ // mcp is the MCP route's token outcome (client, organization, scopes) for a
188
+ // caller that arrived over /api/mcp, null on every other surface - the
189
+ // caller-scoped grant steps read it to find the grant behind the call.
190
+ // markCredential lets a step that makes a credential (a member token) keep
191
+ // it out of every log line for the rest of the request.
192
+ const result = await stepFn({
193
+ acting,
194
+ auth: context.auth,
195
+ markCredential,
196
+ mcp: context.mcpAuth ?? null,
197
+ organization: context.organization ?? null,
198
+ organizationId,
199
+ properties: evaluatedProperties
200
+ });
201
+ addStepResult(context, routineContext, {
202
+ result,
203
+ stepId: step.stepId
204
+ });
205
+ logger.debug({
206
+ event: 'debug_end_auth_step',
207
+ stepId: step.stepId,
208
+ type: step.type
209
+ });
210
+ return {
211
+ status: 'continue'
212
+ };
213
+ }
214
+ export default handleAuthStep;
@@ -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 loadDynamicArtifacts from '../page/dynamic/loadDynamicArtifacts.js';
16
+ import addStepResult from './addStepResult.js';
17
+ import evaluateRoutineOperators from './evaluateRoutineOperators.js';
18
+ // Returns what a dynamic blocks policy allows, with the properties schema of each
19
+ // allowed block and the params schema of each allowed action and operator, so a generator's prompt is derived from the policy
20
+ // rather than written by hand and left to drift from it.
21
+ async function handleDescribeDynamicPolicy(context, routineContext, { step }) {
22
+ const { policy: policyId } = evaluateRoutineOperators(context, routineContext, {
23
+ input: step.properties,
24
+ location: step.stepId
25
+ });
26
+ const [{ blockSchemas, dynamicPolicies }, actionSchemas, operatorSchemas] = await Promise.all([
27
+ loadDynamicArtifacts(context),
28
+ context.readConfigFile('plugins/actionSchemas.json'),
29
+ context.readConfigFile('plugins/operatorSchemas.json')
30
+ ]);
31
+ const policy = dynamicPolicies[policyId];
32
+ const blocks = {};
33
+ policy.blocks.forEach((blockType)=>{
34
+ blocks[blockType] = blockSchemas[blockType]?.properties?.properties ?? null;
35
+ });
36
+ const actions = {};
37
+ policy.actions.forEach((actionType)=>{
38
+ actions[actionType] = actionSchemas?.[actionType] ?? null;
39
+ });
40
+ const operators = {};
41
+ policy.operators.forEach((operator)=>{
42
+ operators[operator] = operatorSchemas?.[operator] ?? null;
43
+ });
44
+ const result = {
45
+ id: policy.id,
46
+ blocks,
47
+ actions,
48
+ operators,
49
+ endpoints: policy.endpoints,
50
+ requests: policy.requests,
51
+ links: policy.links,
52
+ state: policy.state,
53
+ html: policy.html,
54
+ limits: policy.limits
55
+ };
56
+ addStepResult(context, routineContext, {
57
+ result,
58
+ stepId: step.stepId
59
+ });
60
+ return {
61
+ status: 'continue'
62
+ };
63
+ }
64
+ export default handleDescribeDynamicPolicy;