@lowdefy/api 6.1.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/dist/context/applySystemTrust.js +45 -0
  2. package/dist/context/createApiContext.js +18 -3
  3. package/dist/context/createAuthorizeOutcome.js +91 -0
  4. package/dist/context/createBoundSystemContext.js +33 -0
  5. package/dist/context/createEvaluateOperators.js +8 -3
  6. package/dist/context/createRequestSignal.js +47 -0
  7. package/dist/context/createSystemContext.js +80 -0
  8. package/dist/context/getCanonicalUrl.js +27 -0
  9. package/dist/context/isSameOriginRequest.js +85 -0
  10. package/dist/context/isWebSocketOriginAllowed.js +63 -0
  11. package/dist/context/normalizeInjectedCaller.js +58 -0
  12. package/dist/context/parseRequestBody.js +32 -0
  13. package/dist/context/readMemberships.js +71 -0
  14. package/dist/context/resolveAuthentication.js +758 -0
  15. package/dist/context/resolveStrategyCaller.js +7 -3
  16. package/dist/csp/addNonceToElements.js +23 -0
  17. package/dist/csp/createContentSecurityPolicy.js +45 -0
  18. package/dist/csp/getWebSocketSources.js +36 -0
  19. package/dist/email/renderAuthEmail.js +99 -0
  20. package/dist/index.js +21 -5
  21. package/dist/response/formatErrorForAgent.js +35 -0
  22. package/dist/response/redactResponse.js +8 -1
  23. package/dist/routes/agent/authorizeAgent.js +17 -5
  24. package/dist/routes/agent/callAgent.js +12 -2
  25. package/dist/routes/agent/collectChatFiles.js +39 -0
  26. package/dist/routes/agent/prepareAgent.js +23 -4
  27. package/dist/routes/auth/buildAdminPlugin.js +33 -0
  28. package/dist/routes/auth/buildCaptchaPlugin.js +61 -0
  29. package/dist/routes/auth/buildMcpTokenPlugin.js +77 -0
  30. package/dist/routes/auth/buildOauthPostLogin.js +73 -0
  31. package/dist/routes/auth/buildPhoneNumberPlugin.js +57 -0
  32. package/dist/routes/auth/buildProviders.js +61 -0
  33. package/dist/routes/auth/createAsMetadataHandler.js +27 -0
  34. package/dist/routes/auth/createAuthLogger.js +31 -0
  35. package/dist/routes/auth/createMcpAccessTokenClaims.js +52 -0
  36. package/dist/routes/auth/createOnAPIError.js +41 -0
  37. package/dist/routes/auth/createSendEmail.js +54 -0
  38. package/dist/routes/auth/ensureMcpTokenIndexes.js +48 -0
  39. package/dist/routes/auth/getAuthEnforcement.js +41 -0
  40. package/dist/routes/auth/getBetterAuth.js +107 -0
  41. package/dist/routes/auth/getBetterAuthConfig.js +767 -0
  42. package/dist/routes/auth/handleAuthRequest.js +43 -0
  43. package/dist/routes/auth/hooks/authHookPoints.js +204 -0
  44. package/dist/routes/auth/hooks/buildEngineHooks.js +68 -0
  45. package/dist/routes/auth/hooks/buildHooks.js +112 -0
  46. package/dist/routes/auth/{callbacks/addUserFieldsToSession.js → hooks/composeAfterSlot.js} +11 -13
  47. package/dist/routes/auth/hooks/composeBeforeSlot.js +41 -0
  48. package/dist/routes/auth/hooks/createHookDispatch.js +59 -0
  49. package/dist/routes/auth/hooks/createUserAfterHook.js +36 -0
  50. package/dist/routes/auth/hooks/createUserBeforeHook.js +50 -0
  51. package/dist/routes/auth/hooks/findHookUser.js +27 -0
  52. package/dist/routes/auth/modelNames.js +30 -0
  53. package/dist/routes/auth/organizations/OrganizationKeyError.js +28 -0
  54. package/dist/routes/auth/organizations/authorizeRole.js +27 -0
  55. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +178 -0
  56. package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +57 -0
  57. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +120 -0
  58. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +403 -0
  59. package/dist/routes/auth/organizations/createAdmissionGateHook.js +50 -0
  60. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +90 -0
  61. package/dist/routes/auth/organizations/createAutoJoinHook.js +68 -0
  62. package/dist/routes/auth/organizations/createEmailSendGate.js +59 -0
  63. package/dist/routes/auth/organizations/createExpiredInvitationGate.js +76 -0
  64. package/dist/routes/auth/organizations/ensureAuthIndexes.js +122 -0
  65. package/dist/routes/auth/organizations/ensureOrganization.js +132 -0
  66. package/dist/routes/auth/organizations/findPendingInvitation.js +43 -0
  67. package/dist/routes/auth/organizations/getHookRequestHeaders.js +24 -0
  68. package/dist/routes/auth/organizations/getOrganizationBinding.js +65 -0
  69. package/dist/routes/auth/organizations/isEmailAdmitted.js +89 -0
  70. package/dist/routes/auth/organizations/organizationAccessControl.js +94 -0
  71. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +62 -0
  72. package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +145 -0
  73. package/dist/routes/auth/requestHooks/buildRequestHooks.js +288 -0
  74. package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +43 -0
  75. package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +59 -0
  76. package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +47 -0
  77. package/dist/routes/auth/requestHooks/redirectToChallenge.js +79 -0
  78. package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +31 -0
  79. package/dist/routes/auth/resolveCookiePrefix.js +30 -0
  80. package/dist/routes/auth/sanitizeSessionResponse.js +27 -0
  81. package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
  82. package/dist/routes/connections/checkUnwalledReach.js +37 -0
  83. package/dist/routes/connections/getConnectionConfig.js +6 -1
  84. package/dist/routes/connections/resolveTenantPreflight.js +226 -0
  85. package/dist/routes/connections/resolveUnwalledReach.js +144 -0
  86. package/dist/routes/endpoints/acceptDetachedEndpoint.js +50 -0
  87. package/dist/routes/endpoints/authorizeApiEndpoint.js +13 -4
  88. package/dist/routes/endpoints/callEndpoint.js +22 -7
  89. package/dist/routes/endpoints/control/controlParallelFor.js +61 -22
  90. package/dist/routes/endpoints/control/controlReject.js +23 -1
  91. package/dist/routes/endpoints/control/controlReturn.js +29 -1
  92. package/dist/routes/endpoints/control/controlThrow.js +3 -2
  93. package/dist/routes/endpoints/control/controlTry.js +10 -1
  94. package/dist/routes/endpoints/control/controlWhile.js +55 -0
  95. package/dist/routes/endpoints/control/handleControl.js +3 -1
  96. package/dist/routes/endpoints/createWebhookAnswer.js +78 -0
  97. package/dist/routes/endpoints/evaluateRoutineOperators.js +2 -1
  98. package/dist/routes/endpoints/forwardScheduledEndpoint.js +3 -2
  99. package/dist/routes/endpoints/getEndpointConfig.js +18 -8
  100. package/dist/routes/endpoints/getSchemaValidator.js +39 -0
  101. package/dist/routes/endpoints/handleAgentCall.js +21 -2
  102. package/dist/routes/endpoints/handleAuthStep.js +214 -0
  103. package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
  104. package/dist/routes/endpoints/handleEndpointCall.js +43 -6
  105. package/dist/routes/endpoints/handleRenderNotification.js +14 -4
  106. package/dist/routes/endpoints/handleRequest.js +12 -1
  107. package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
  108. package/dist/routes/endpoints/handleValidateSchema.js +13 -15
  109. package/dist/routes/endpoints/invokeEndpoint.js +26 -3
  110. package/dist/routes/endpoints/operatorScope.js +2 -1
  111. package/dist/routes/{auth/callbacks/createCallbackPlugins.js → endpoints/parseWebhookBody.js} +10 -6
  112. package/dist/routes/endpoints/resolveCallBinding.js +91 -0
  113. package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
  114. package/dist/routes/endpoints/runDetachedEndpoint.js +63 -18
  115. package/dist/routes/endpoints/runRoutine.js +64 -5
  116. package/dist/routes/endpoints/runScheduledEndpoint.js +18 -11
  117. package/dist/routes/endpoints/runWebhookEndpoint.js +69 -23
  118. package/dist/routes/endpoints/runWebhookVerify.js +129 -0
  119. package/dist/routes/endpoints/scheduleBackground.js +10 -0
  120. package/dist/routes/endpoints/test/runTest.js +31 -9
  121. package/dist/routes/endpoints/validatePayload.js +144 -0
  122. package/dist/routes/log/logClientError.js +7 -4
  123. package/dist/routes/mcp/createMcpServer.js +143 -82
  124. package/dist/routes/mcp/getMcpJwks.js +93 -0
  125. package/dist/routes/mcp/getMcpResourceBinding.js +41 -0
  126. package/dist/routes/mcp/getMcpUri.js +69 -0
  127. package/dist/routes/mcp/oauthResourceLifecycle.js +122 -0
  128. package/dist/routes/mcp/runAfterToolCall.js +50 -0
  129. package/dist/routes/notifications/resolveNotificationLinks.js +39 -11
  130. package/dist/routes/page/dynamic/checkDynamicContent.js +81 -0
  131. package/dist/routes/page/dynamic/checkLiteralContent.js +242 -0
  132. package/dist/routes/page/dynamic/createContentError.js +34 -0
  133. package/dist/routes/page/dynamic/flagIconsOutsidePage.js +39 -0
  134. package/dist/routes/page/dynamic/flagTypesOutsidePage.js +44 -0
  135. package/dist/routes/page/dynamic/getPropertiesSchemaErrors.js +35 -0
  136. package/dist/routes/page/dynamic/loadDynamicArtifacts.js +52 -0
  137. package/dist/routes/page/dynamic/policy/checkAction.js +204 -0
  138. package/dist/routes/page/dynamic/policy/checkEvents.js +163 -0
  139. package/dist/routes/page/dynamic/policy/checkPolicy.js +313 -0
  140. package/dist/routes/page/dynamic/policy/checkValue.js +214 -0
  141. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +117 -0
  142. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +54 -0
  143. package/dist/routes/page/dynamic/policy/findSerializerKeys.js +50 -0
  144. package/dist/routes/page/dynamic/policy/isAllowedUrl.js +53 -0
  145. package/dist/routes/{auth/createAdapter.js → page/dynamic/policy/isUnderState.js} +5 -9
  146. package/dist/routes/page/dynamic/policy/normalizeUrlText.js +25 -0
  147. package/dist/routes/page/dynamic/resolveDynamicContent.js +89 -37
  148. package/dist/routes/page/dynamic/unescapeOperators.js +21 -4
  149. package/dist/routes/page/dynamic/validateFragment.js +17 -58
  150. package/dist/routes/page/getPageConfig.js +76 -6
  151. package/dist/routes/request/authorizeRequest.js +21 -6
  152. package/dist/routes/request/callRequest.js +22 -10
  153. package/dist/routes/request/callRequestResolver.js +49 -6
  154. package/dist/routes/request/checkConnectionRead.js +1 -1
  155. package/dist/routes/request/checkConnectionWrite.js +1 -1
  156. package/dist/routes/request/createWalledResolver.js +75 -0
  157. package/dist/routes/request/getRequestConfig.js +19 -3
  158. package/dist/routes/request/maskCredentialProperties.js +34 -0
  159. package/dist/routes/request/resolveTenancy.js +223 -0
  160. package/dist/routes/request/validateSchemas.js +7 -6
  161. package/dist/routes/{auth/events/createEventPlugins.js → rootConfig/getAppEvents.js} +7 -6
  162. package/dist/routes/rootConfig/getHomeAndMenus.js +23 -16
  163. package/dist/routes/{auth/events/createSessionEvent.js → rootConfig/getPagePaths.js} +16 -18
  164. package/dist/routes/rootConfig/getRootConfig.js +9 -3
  165. package/dist/routes/rootConfig/menus/filterMenuList.js +5 -2
  166. package/dist/routes/websocket/authorizeWebsocket.js +19 -4
  167. package/dist/routes/websocket/createChannelRegistry.js +20 -9
  168. package/dist/routes/websocket/createWebSocketConnection.js +150 -28
  169. package/dist/routes/websocket/getCallerFingerprint.js +31 -0
  170. package/dist/routes/websocket/prepareChannel.js +29 -1
  171. package/dist/routes/websocket/resolveWebsocketCaller.js +40 -0
  172. package/dist/test/testContext.js +13 -10
  173. package/package.json +28 -12
  174. package/dist/context/createAuthorize.js +0 -45
  175. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +0 -30
  176. package/dist/routes/auth/callbacks/createCallbacks.js +0 -46
  177. package/dist/routes/auth/callbacks/createJWTCallback.js +0 -77
  178. package/dist/routes/auth/callbacks/createRedirectCallback.js +0 -41
  179. package/dist/routes/auth/callbacks/createSessionCallback.js +0 -81
  180. package/dist/routes/auth/callbacks/createSignInCallback.js +0 -40
  181. package/dist/routes/auth/callbacks/validateSessionRoles.js +0 -33
  182. package/dist/routes/auth/createLogger.js +0 -35
  183. package/dist/routes/auth/createPrefixedCookies.js +0 -52
  184. package/dist/routes/auth/createProviders.js +0 -25
  185. package/dist/routes/auth/defaultAuthUrl.js +0 -31
  186. package/dist/routes/auth/events/createCreateUserEvent.js +0 -41
  187. package/dist/routes/auth/events/createEvents.js +0 -56
  188. package/dist/routes/auth/events/createLinkAccountEvent.js +0 -43
  189. package/dist/routes/auth/events/createSignInEvent.js +0 -46
  190. package/dist/routes/auth/events/createSignOutEvent.js +0 -43
  191. package/dist/routes/auth/events/createUpdateUserEvent.js +0 -41
  192. package/dist/routes/auth/getAuthConfig.js +0 -90
  193. package/dist/routes/auth/resolveCookies.js +0 -37
  194. package/dist/routes/log/formatValidationError.js +0 -31
  195. /package/dist/{routes/notifications → email}/resolveThemeLogo.js +0 -0
@@ -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;
@@ -13,11 +13,14 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { serializer } from '@lowdefy/helpers';
16
- import { ConfigError } from '@lowdefy/errors';
16
+ import { ConfigError, LowdefyInternalError } from '@lowdefy/errors';
17
+ import { getMarkedCredentials } from '@lowdefy/node-utils';
17
18
  import addStepResult from './addStepResult.js';
19
+ import createBoundSystemContext from '../../context/createBoundSystemContext.js';
20
+ import evaluateRoutineOperators from './evaluateRoutineOperators.js';
18
21
  import invokeEndpoint from './invokeEndpoint.js';
22
+ import resolveCallBinding from './resolveCallBinding.js';
19
23
  import scheduleBackground from './scheduleBackground.js';
20
- import evaluateRoutineOperators from './evaluateRoutineOperators.js';
21
24
  async function handleEndpointCall(context, routineContext, { step }) {
22
25
  const { logger } = context;
23
26
  logger.debug({
@@ -29,6 +32,16 @@ async function handleEndpointCall(context, routineContext, { step }) {
29
32
  input: step.properties,
30
33
  location: step.stepId
31
34
  });
35
+ // organization (and caller) bind the target to one organization as a system
36
+ // run: the tenant wall filters and stamps with it, and `_user` is the named
37
+ // stand-in caller, or null.
38
+ const binding = resolveCallBinding(context, {
39
+ caller: evaluatedProperties.caller,
40
+ configKey: step['~k'],
41
+ organization: evaluatedProperties.organization,
42
+ stepId: step.stepId
43
+ });
44
+ const callContext = binding === null ? context : createBoundSystemContext(context, binding);
32
45
  // detached: true — fire-and-forget the call back through the deployment's
33
46
  // /api/detached route, so the target runs in its OWN function invocation
34
47
  // with a fresh duration budget (chainable bounded work without a queue).
@@ -41,7 +54,7 @@ async function handleEndpointCall(context, routineContext, { step }) {
41
54
  throw new ConfigError('CallApi with "detached: true" requires the CRON_SECRET environment variable — the /api/detached route fails closed without it.');
42
55
  }
43
56
  if (!context.origin) {
44
- throw new ConfigError('Detached endpoint calls require the request origin on context.');
57
+ throw new LowdefyInternalError('Detached endpoint calls require the request origin on context.');
45
58
  }
46
59
  const targetEndpointId = evaluatedProperties.endpointId;
47
60
  scheduleBackground(context, {
@@ -50,11 +63,33 @@ async function handleEndpointCall(context, routineContext, { step }) {
50
63
  }, ()=>fetch(`${context.origin}/api/detached/${targetEndpointId}`, {
51
64
  method: 'POST',
52
65
  headers: {
66
+ // The dev server's journey cookies (data set, mutant) ride the hop
67
+ // so the target runs in the same journey run; the production server
68
+ // sets none. Spread first so content-type and authorization win.
69
+ ...context.loopbackHeaders ?? {},
53
70
  'content-type': 'application/json',
54
71
  authorization: `Bearer ${process.env.CRON_SECRET}`
55
72
  },
73
+ // Carry the already-resolved dispatcher identity across the hop
74
+ // (Decision 4): a detached call is a fresh invocation, not a fresh
75
+ // principal. The receiver rehydrates context.user / context.system from
76
+ // this snapshot and authorizes nested calls against it through the
77
+ // normal path - so a user-dispatched detached run reaches nothing the
78
+ // user could not reach synchronously, and a cron/hook/verified-webhook
79
+ // run blanket-passes like its dispatcher. Built server-side from the
80
+ // resolved context, never from user input; the CRON_SECRET proves
81
+ // origin, which is what lets the receiver trust the assertion.
56
82
  body: JSON.stringify({
57
- payload: serializer.serialize(evaluatedProperties.payload ?? {})
83
+ payload: serializer.serialize(evaluatedProperties.payload ?? {}),
84
+ principal: {
85
+ user: serializer.serialize(callContext.user ?? null),
86
+ system: callContext.system === true,
87
+ organizationId: callContext.boundOrganizationId ?? null,
88
+ agent: routineContext.agent ?? null
89
+ },
90
+ // The values this request marked with _credential, so the target's logs scrub them
91
+ // too: the target runs as a new request with a scope of its own.
92
+ credentials: getMarkedCredentials()
58
93
  })
59
94
  }));
60
95
  addStepResult(context, routineContext, {
@@ -74,10 +109,12 @@ async function handleEndpointCall(context, routineContext, { step }) {
74
109
  status: 'continue'
75
110
  };
76
111
  }
77
- const result = await invokeEndpoint(context, {
112
+ const result = await invokeEndpoint(callContext, {
113
+ agent: routineContext.agent,
78
114
  endpointId: evaluatedProperties.endpointId,
79
115
  payload: evaluatedProperties.payload,
80
- endpointDepth: routineContext.endpointDepth
116
+ endpointDepth: routineContext.endpointDepth,
117
+ caught: routineContext.caught === true
81
118
  });
82
119
  // Store the return value in the caller's steps
83
120
  const response = result.status === 'return' ? result.response : null;
@@ -20,7 +20,7 @@ import getCurrentEnvironment from '../../context/getCurrentEnvironment.js';
20
20
  import derivePreview from '../notifications/derivePreview.js';
21
21
  import getNotificationConfig from '../notifications/getNotificationConfig.js';
22
22
  import resolveNotificationLinks from '../notifications/resolveNotificationLinks.js';
23
- import resolveThemeLogo from '../notifications/resolveThemeLogo.js';
23
+ import resolveThemeLogo from '../../email/resolveThemeLogo.js';
24
24
  import evaluateRoutineOperators from './evaluateRoutineOperators.js';
25
25
  function itemHasPageLinks(item, dataKeys) {
26
26
  const links = Object.values(item.links ?? {});
@@ -74,8 +74,8 @@ async function handleRenderNotification(context, routineContext, { step }) {
74
74
  if (!type.isNone(serverUrl)) {
75
75
  serverUrl = serverUrl.replace(/\/$/, '');
76
76
  }
77
- if (!type.isNone(landingPage) && !type.isString(landingPage)) {
78
- throw new ConfigError(`RenderNotification step "${step.stepId}" properties.landingPage must evaluate to a string. Received ${JSON.stringify(landingPage)}.`, {
77
+ if (!type.isNone(landingPage) && !type.isString(landingPage) && !(type.isObject(landingPage) && type.isString(landingPage.pageId))) {
78
+ throw new ConfigError(`RenderNotification step "${step.stepId}" properties.landingPage must evaluate to a page id or an object with a pageId. Received ${JSON.stringify(landingPage)}.`, {
79
79
  configKey: step['~k']
80
80
  });
81
81
  }
@@ -130,13 +130,23 @@ async function handleRenderNotification(context, routineContext, { step }) {
130
130
  });
131
131
  }
132
132
  }
133
+ const routes = await context.readConfigFile('routes.json');
134
+ if (!type.isNone(landingPage)) {
135
+ const landingPageId = type.isString(landingPage) ? landingPage : landingPage.pageId;
136
+ if (!routes.some((route)=>route.pageId === landingPageId)) {
137
+ throw new ConfigError(`RenderNotification step "${step.stepId}" properties.landingPage "${landingPageId}" is not a page id. Pass the landing page's id, not its URL path.`, {
138
+ configKey: step['~k']
139
+ });
140
+ }
141
+ }
133
142
  const resolvedItem = resolveNotificationLinks({
134
143
  item: data,
135
144
  dataKeys: Template.dataKeys ?? [],
136
145
  serverUrl: serverUrl ?? '',
137
146
  basePath,
138
147
  landingPage,
139
- recordId
148
+ recordId,
149
+ routes
140
150
  });
141
151
  let interpolated;
142
152
  try {
@@ -20,6 +20,7 @@ import evaluateOperators from '../request/evaluateOperators.js';
20
20
  import getConnection from '../connections/getConnection.js';
21
21
  import getConnectionConfig from '../connections/getConnectionConfig.js';
22
22
  import getRequestResolver from '../request/getRequestResolver.js';
23
+ import resolveTenancy from '../request/resolveTenancy.js';
23
24
  import validateSchemas from '../request/validateSchemas.js';
24
25
  async function handleRequest(context, routineContext, { request }) {
25
26
  const { logger } = context;
@@ -39,6 +40,12 @@ async function handleRequest(context, routineContext, { request }) {
39
40
  connection,
40
41
  requestConfig
41
42
  });
43
+ const { tenant, tenantGuard } = resolveTenancy(context, {
44
+ connection,
45
+ connectionConfig,
46
+ requestConfig,
47
+ writes: requestResolver.meta.checkWrite === true
48
+ });
42
49
  const { connectionProperties, requestProperties } = evaluateOperators(context, {
43
50
  connectionConfig,
44
51
  requestConfig,
@@ -64,11 +71,15 @@ async function handleRequest(context, routineContext, { request }) {
64
71
  requestProperties
65
72
  });
66
73
  const result = await callRequestResolver(context, {
74
+ agent: routineContext.agent,
67
75
  connectionProperties,
68
76
  endpointDepth: routineContext.endpointDepth,
69
77
  requestConfig,
70
78
  requestProperties,
71
- requestResolver
79
+ requestResolver,
80
+ routineContext,
81
+ tenant,
82
+ tenantGuard
72
83
  });
73
84
  addStepResult(context, routineContext, {
74
85
  result,
@@ -0,0 +1,106 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { serializer, type } from '@lowdefy/helpers';
16
+ import { UserError } from '@lowdefy/errors';
17
+ import checkDynamicContent from '../page/dynamic/checkDynamicContent.js';
18
+ import loadDynamicArtifacts from '../page/dynamic/loadDynamicArtifacts.js';
19
+ import addStepResult from './addStepResult.js';
20
+ import evaluateRoutineOperators from './evaluateRoutineOperators.js';
21
+ // Checks content against a dynamic blocks policy with the same function page get
22
+ // uses, so content that passes here renders. The result lists every violation
23
+ // with its path into the content, for a generator to correct and retry.
24
+ async function handleValidateDynamic(context, routineContext, { step }) {
25
+ const { logger } = context;
26
+ logger.debug({
27
+ event: 'debug_start_validate_dynamic',
28
+ step
29
+ });
30
+ const { blocks, policy: policyId, throwOnInvalid = true } = evaluateRoutineOperators(context, routineContext, {
31
+ input: step.properties,
32
+ location: step.stepId
33
+ });
34
+ const artifacts = await loadDynamicArtifacts(context);
35
+ const policy = artifacts.dynamicPolicies[policyId];
36
+ let errors;
37
+ if (!type.isArray(blocks)) {
38
+ errors = [
39
+ {
40
+ path: 'blocks',
41
+ rule: 'shape',
42
+ message: `Content should be an array of blocks. Received ${JSON.stringify(blocks)}.`
43
+ }
44
+ ];
45
+ } else {
46
+ const result = await checkDynamicContent(context, {
47
+ artifacts,
48
+ // buildBlock mutates the content; the caller's value stays as given.
49
+ blocks: serializer.copy(blocks),
50
+ dynamicBlockId: step.stepId,
51
+ idPrefix: `validate:${step.stepId}`,
52
+ pageId: `endpoint:${step.endpointId}`,
53
+ pageRequests: null,
54
+ policy,
55
+ usedTypes: {
56
+ actions: new Set(),
57
+ blocks: new Set(),
58
+ operators: new Set()
59
+ }
60
+ });
61
+ errors = result.errors.map(({ path, rule, message })=>({
62
+ path,
63
+ rule,
64
+ message
65
+ }));
66
+ }
67
+ const result = {
68
+ valid: errors.length === 0,
69
+ errors,
70
+ blocks
71
+ };
72
+ // A Dynamic block's endpoint may return these blocks as config, if this
73
+ // step checked them against the block's own policy.
74
+ if (result.valid && routineContext.literalData?.policyId === policyId) {
75
+ routineContext.literalData.validatedStepIds.add(step.stepId);
76
+ }
77
+ addStepResult(context, routineContext, {
78
+ result,
79
+ stepId: step.stepId
80
+ });
81
+ if (!result.valid && throwOnInvalid) {
82
+ // Invalid generated content is an expected outcome, not a config fault.
83
+ const error = new UserError(`ValidateDynamic step "${step.stepId}" failed: ${errors[0].path}: ${errors[0].message}`, {
84
+ cause: errors
85
+ });
86
+ logger.warn({
87
+ event: 'warn_validate_dynamic',
88
+ stepId: step.stepId,
89
+ err: error
90
+ });
91
+ error.handled = true;
92
+ return {
93
+ status: 'error',
94
+ error
95
+ };
96
+ }
97
+ logger.debug({
98
+ event: 'debug_end_validate_dynamic',
99
+ stepId: step.stepId,
100
+ valid: result.valid
101
+ });
102
+ return {
103
+ status: 'continue'
104
+ };
105
+ }
106
+ export default handleValidateDynamic;
@@ -12,10 +12,10 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import { validate } from '@lowdefy/ajv';
16
- import { UserError } from '@lowdefy/errors';
15
+ */ import { UserError } from '@lowdefy/errors';
17
16
  import addStepResult from './addStepResult.js';
18
17
  import evaluateRoutineOperators from './evaluateRoutineOperators.js';
18
+ import getSchemaValidator from './getSchemaValidator.js';
19
19
  function buildErrorMessage(errors, stepId) {
20
20
  const first = errors?.[0];
21
21
  if (!first) return `ValidateSchema step "${stepId}" failed.`;
@@ -33,33 +33,31 @@ async function handleValidateSchema(context, routineContext, { step }) {
33
33
  location: step.stepId
34
34
  });
35
35
  const { schema, data, throwOnInvalid = true } = evaluatedProperties;
36
- const { valid, errors } = validate({
37
- schema,
38
- data,
39
- returnErrors: true
40
- });
41
- const result = {
42
- valid,
43
- errors: errors ?? []
44
- };
36
+ const result = getSchemaValidator({
37
+ schema
38
+ })(data);
39
+ const { valid } = result;
45
40
  addStepResult(context, routineContext, {
46
41
  result,
47
42
  stepId: step.stepId
48
43
  });
49
44
  if (!valid && throwOnInvalid) {
50
- // A UserError, so the caller sees which field failed: the message is built from the schema
51
- // path and rule, never the data, and every other server error reaches the client generic.
45
+ // Failed validation of caller-supplied data is an expected user outcome,
46
+ // not a config or system fault.
52
47
  // No cause: a UserError's cause crosses the wire as author data, and the ajv errors carry
53
48
  // server schema detail. They stay in the step result and the log.
54
49
  const error = new UserError(buildErrorMessage(result.errors, step.stepId));
50
+ // A webhook answers an invalid request with 400 rather than 500 (createWebhookAnswer).
51
+ error.isInvalidRequest = true;
55
52
  // Log under `err` — see controlThrow: only the `err` key runs the pino error
56
53
  // serializer, so `error` would drop the message from the log line.
57
- logger.error({
58
- event: 'error_validate_schema',
54
+ logger.warn({
55
+ event: 'warn_validate_schema',
59
56
  stepId: step.stepId,
60
57
  err: error,
61
58
  errors: result.errors
62
59
  });
60
+ error.handled = true;
63
61
  return {
64
62
  status: 'error',
65
63
  error