@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
@@ -16,8 +16,12 @@
16
16
  import { ConfigError } from '@lowdefy/errors';
17
17
  import createEvaluateOperators from '../../../context/createEvaluateOperators.js';
18
18
  import invokeEndpoint from '../../endpoints/invokeEndpoint.js';
19
+ import checkDynamicContent from './checkDynamicContent.js';
20
+ import createContentError from './createContentError.js';
21
+ import flagIconsOutsidePage from './flagIconsOutsidePage.js';
22
+ import flagTypesOutsidePage from './flagTypesOutsidePage.js';
23
+ import loadDynamicArtifacts from './loadDynamicArtifacts.js';
19
24
  import unescapeOperators from './unescapeOperators.js';
20
- import validateFragment from './validateFragment.js';
21
25
  const MAX_DYNAMIC_DEPTH = 5;
22
26
  function collectDynamicBlocks(block, found) {
23
27
  if (block.type === 'Dynamic') {
@@ -41,6 +45,7 @@ function setResolvedContent(block, blocks) {
41
45
  delete block.slots.fallback;
42
46
  delete block.properties.endpointId;
43
47
  delete block.properties.params;
48
+ delete block.properties.policy;
44
49
  delete block.properties.required;
45
50
  delete block.properties.types;
46
51
  }
@@ -56,6 +61,14 @@ async function resolveBlocks(context, { blocks, depth, shared }) {
56
61
  async function resolveDynamicBlock(context, { block, depth, shared }) {
57
62
  const { logger } = context;
58
63
  const { endpointId, params, required } = block.properties;
64
+ // Build validated the policy id. The endpoint's data stays literal; only the
65
+ // blocks of a ValidateDynamic step that passed with this policy may come
66
+ // back as config, and the policy is checked again on the final content.
67
+ const policy = type.isNone(block.properties.policy) ? null : shared.artifacts.dynamicPolicies[block.properties.policy];
68
+ // A UserError the routine returns was logged as a warning and marked handled
69
+ // where it was raised (a failed ValidateDynamic step, a :reject, a :throw) or
70
+ // by runRoutine.
71
+ let loggedByRoutine = false;
59
72
  try {
60
73
  if (depth >= MAX_DYNAMIC_DEPTH) {
61
74
  throw new ConfigError(`Dynamic block "${block.blockId}" on page "${shared.pageId}" exceeded the maximum dynamic nesting depth of ${MAX_DYNAMIC_DEPTH}.`, {
@@ -68,14 +81,20 @@ async function resolveDynamicBlock(context, { block, depth, shared }) {
68
81
  blockId: block.blockId,
69
82
  pageId: shared.pageId,
70
83
  params: params ?? {},
84
+ pathParams: shared.pathParams ?? {},
71
85
  urlQuery: shared.urlQuery ?? {}
72
86
  },
73
- endpointDepth: 0
87
+ endpointDepth: 0,
88
+ literalData: {
89
+ clientOperators: shared.artifacts.clientOperators,
90
+ policyId: policy?.id ?? null
91
+ }
74
92
  });
75
93
  if ([
76
94
  'error',
77
95
  'reject'
78
96
  ].includes(status)) {
97
+ loggedByRoutine = error?.name === 'UserError' && error.handled === true;
79
98
  throw error ?? new ConfigError(`Dynamic block "${block.blockId}" on page "${shared.pageId}" endpoint "${endpointId}" failed with status "${status}".`, {
80
99
  configKey: block['~k']
81
100
  });
@@ -86,16 +105,30 @@ async function resolveDynamicBlock(context, { block, depth, shared }) {
86
105
  configKey: block['~k']
87
106
  });
88
107
  }
89
- // Unescape before building so operator counting validates the real
108
+ // Unescape before checking so operator counting validates the real
90
109
  // (client-evaluated) operators against the bundle.
91
- const { blocks, callApiActionRefs, requestActionRefs, warnings } = shared.buildDynamicBlocks({
92
- blocks: unescapeOperators(response.blocks),
93
- pageId: shared.pageId,
110
+ const result = await checkDynamicContent(context, {
111
+ artifacts: shared.artifacts,
112
+ blocks: unescapeOperators({
113
+ value: response.blocks,
114
+ operators: shared.artifacts.clientOperators
115
+ }),
94
116
  dynamicBlockId: block.blockId,
95
117
  idPrefix: block.id,
96
- types: shared.types,
97
- blockMetas: shared.blockMetas
118
+ pageId: shared.pageId,
119
+ pageRequests: shared.pageRequests,
120
+ policy,
121
+ usedTypes: shared.usedTypes
98
122
  });
123
+ if (result.errors.length > 0) {
124
+ throw createContentError({
125
+ block,
126
+ errors: result.errors,
127
+ pageId: shared.pageId,
128
+ policy
129
+ });
130
+ }
131
+ const { blocks, warnings } = result;
99
132
  warnings.forEach((warning)=>{
100
133
  logger.warn({
101
134
  event: 'dynamic_block_warning',
@@ -103,15 +136,6 @@ async function resolveDynamicBlock(context, { block, depth, shared }) {
103
136
  pageId: shared.pageId
104
137
  }, warning.message);
105
138
  });
106
- await validateFragment(context, {
107
- blocks,
108
- blockSchemas: shared.blockSchemas,
109
- callApiActionRefs,
110
- dynamicBlockId: block.blockId,
111
- pageId: shared.pageId,
112
- pageRequests: shared.pageRequests,
113
- requestActionRefs
114
- });
115
139
  await resolveBlocks(context, {
116
140
  blocks,
117
141
  depth: depth + 1,
@@ -120,18 +144,33 @@ async function resolveDynamicBlock(context, { block, depth, shared }) {
120
144
  setResolvedContent(block, blocks);
121
145
  } catch (error) {
122
146
  if (required === true) {
123
- throw new ConfigError(`Dynamic block "${block.blockId}" on page "${shared.pageId}" failed to resolve: ${error.message}`, {
147
+ // A typed Lowdefy error already carries its own class, message and
148
+ // location - rewrapping it as a ConfigError would misreport a service
149
+ // outage or an authorization refusal as the app developer's config.
150
+ if (error.isLowdefyError) {
151
+ throw error;
152
+ }
153
+ throw new ConfigError(`Dynamic block "${block.blockId}" on page "${shared.pageId}" failed to resolve.`, {
124
154
  configKey: block['~k'],
125
155
  cause: error
126
156
  });
127
157
  }
128
- logger.error({
129
- event: 'dynamic_block_error',
130
- blockId: block.blockId,
131
- endpointId,
132
- pageId: shared.pageId,
133
- err: error
134
- }, `Dynamic block "${block.blockId}" on page "${shared.pageId}" failed to resolve: ${error.message}`);
158
+ if (!loggedByRoutine) {
159
+ const entry = {
160
+ event: 'dynamic_block_error',
161
+ blockId: block.blockId,
162
+ endpointId,
163
+ pageId: shared.pageId,
164
+ err: error
165
+ };
166
+ const message = `Dynamic block "${block.blockId}" on page "${shared.pageId}" failed to resolve: ${error.message}`;
167
+ // A UserError is an expected outcome, not a fault.
168
+ if (error.name === 'UserError') {
169
+ logger.warn(entry, message);
170
+ } else {
171
+ logger.error(entry, message);
172
+ }
173
+ }
135
174
  const fallbackBlocks = block.slots?.fallback?.blocks ?? [];
136
175
  setResolvedContent(block, fallbackBlocks);
137
176
  await resolveBlocks(context, {
@@ -141,23 +180,25 @@ async function resolveDynamicBlock(context, { block, depth, shared }) {
141
180
  });
142
181
  }
143
182
  }
144
- async function resolveDynamicContent(context, { pageConfig, urlQuery }) {
145
- // Loaded lazily so apps without dynamic pages never load the build package.
146
- const { default: buildDynamicBlocks } = await import('@lowdefy/build/dynamic');
147
- const [types, blockMetas, blockSchemas] = await Promise.all([
148
- context.readConfigFile('types.json'),
149
- context.readConfigFile('plugins/blockMetas.json'),
150
- context.readConfigFile('plugins/blockSchemas.json')
183
+ async function resolveDynamicContent(context, { pageConfig, pathParams, urlQuery }) {
184
+ const [artifacts, pageTypeSets, iconImports, { default: collectIconNames }] = await Promise.all([
185
+ loadDynamicArtifacts(context),
186
+ context.readConfigFile('pageTypeSets.json'),
187
+ context.readConfigFile('iconImports.json'),
188
+ import('@lowdefy/build/collectIconNames')
151
189
  ]);
152
190
  context.evaluateOperators = createEvaluateOperators(context);
153
191
  const shared = {
154
- blockMetas: blockMetas ?? {},
155
- blockSchemas: blockSchemas ?? {},
156
- buildDynamicBlocks,
192
+ artifacts,
157
193
  pageId: pageConfig.pageId,
158
194
  pageRequests: pageConfig.requests ?? [],
159
- types: types ?? {},
160
- urlQuery
195
+ pathParams,
196
+ urlQuery,
197
+ usedTypes: {
198
+ actions: new Set(),
199
+ blocks: new Set(),
200
+ operators: new Set()
201
+ }
161
202
  };
162
203
  // The page root block itself can be a Dynamic block.
163
204
  await resolveBlocks(context, {
@@ -167,6 +208,17 @@ async function resolveDynamicContent(context, { pageConfig, urlQuery }) {
167
208
  depth: 0,
168
209
  shared
169
210
  });
211
+ flagTypesOutsidePage(context, {
212
+ pageConfig,
213
+ pageTypeSets,
214
+ usedTypes: shared.usedTypes
215
+ });
216
+ flagIconsOutsidePage({
217
+ collectIconNames,
218
+ iconImports,
219
+ pageConfig,
220
+ pageTypeSets
221
+ });
170
222
  return pageConfig;
171
223
  }
172
224
  export default resolveDynamicContent;
@@ -13,23 +13,40 @@
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
+ import { getKeyOperator } from '@lowdefy/operators';
16
17
  // One extra leading underscore defers operator evaluation by one level — the
17
18
  // same convention _function bodies use for __args. Shared operators like
18
19
  // _state are registered on the server, so a plain `_state` in a routine's
19
20
  // :return evaluates there (against empty routine state). Authors write
20
21
  // `__state` instead: it survives the server evaluation untouched, and this
21
22
  // unescape strips one underscore so the client evaluates the real operator.
22
- function unescapeOperators(value) {
23
+ //
24
+ // Only the key of an operator-shaped object that names a client operator is
25
+ // unescaped. Data read into the :return cannot carry operators (the parser
26
+ // rejects them under literalData), so every such object here was written by
27
+ // the developer, and data keys like `__typename` pass through unchanged.
28
+ function unescapeOperators({ value, operators }) {
23
29
  if (type.isArray(value)) {
24
- return value.map(unescapeOperators);
30
+ return value.map((item)=>unescapeOperators({
31
+ value: item,
32
+ operators
33
+ }));
25
34
  }
26
35
  if (!type.isObject(value)) {
27
36
  return value;
28
37
  }
38
+ const keys = Object.keys(value).filter((key)=>!key.startsWith('~'));
39
+ const isOperator = keys.length === 1 && getKeyOperator({
40
+ key: keys[0],
41
+ operators
42
+ }) !== null;
29
43
  const result = {};
30
44
  Object.keys(value).forEach((key)=>{
31
- const unescapedKey = key.startsWith('__') ? key.slice(1) : key;
32
- result[unescapedKey] = unescapeOperators(value[key]);
45
+ const unescapedKey = isOperator && key.startsWith('__') ? key.slice(1) : key;
46
+ result[unescapedKey] = unescapeOperators({
47
+ value: value[key],
48
+ operators
49
+ });
33
50
  });
34
51
  return result;
35
52
  }
@@ -12,59 +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
- */ import { validate } from '@lowdefy/ajv';
16
- import { getOperatorType, type } from '@lowdefy/helpers';
17
- import { ConfigError } from '@lowdefy/errors';
18
- function isOperatorObject(value) {
19
- return getOperatorType(value) !== null;
20
- }
21
- function escapePointerSegment(segment) {
22
- return segment.replace(/~/g, '~0').replace(/\//g, '~1');
23
- }
24
- function collectOperatorPaths(value, path, paths) {
25
- if (type.isArray(value)) {
26
- value.forEach((item, index)=>collectOperatorPaths(item, `${path}/${index}`, paths));
27
- return;
28
- }
29
- if (!type.isObject(value)) {
30
- return;
31
- }
32
- if (isOperatorObject(value)) {
33
- paths.push(path);
34
- return;
35
- }
36
- Object.keys(value).forEach((key)=>{
37
- if (key.startsWith('~')) return;
38
- collectOperatorPaths(value[key], `${path}/${escapePointerSegment(key)}`, paths);
39
- });
40
- }
41
- // A schema violation at or under an operator node cannot be judged before the
42
- // operator evaluates on the client — { _state: columns } may legitimately sit
43
- // where the schema wants an array. Violations on operator-free paths stand.
15
+ */ import { ConfigError } from '@lowdefy/errors';
16
+ import getPropertiesSchemaErrors from './getPropertiesSchemaErrors.js';
44
17
  function validateBlockProperties(block, { blockSchemas, dynamicBlockId, pageId }) {
45
- const properties = block.properties;
46
- if (!type.isObject(properties) || isOperatorObject(properties)) {
47
- return;
48
- }
49
- // Block schemas validate the whole pre-build block shape; the plugin's
50
- // properties schema sits at schema.properties.properties.
51
- const propertiesSchema = blockSchemas[block.type]?.properties?.properties;
52
- if (type.isNone(propertiesSchema)) {
53
- return;
54
- }
55
- const result = validate({
56
- schema: propertiesSchema,
57
- data: properties,
58
- returnErrors: true
18
+ const messages = getPropertiesSchemaErrors({
19
+ block,
20
+ blockSchemas
59
21
  });
60
- if (result.valid) {
61
- return;
62
- }
63
- const operatorPaths = [];
64
- collectOperatorPaths(properties, '', operatorPaths);
65
- const errors = result.errors.filter((error)=>!operatorPaths.some((path)=>error.instancePath === path || error.instancePath.startsWith(`${path}/`)));
66
- if (errors.length > 0) {
67
- const messages = errors.map((error)=>`properties${error.instancePath || ''} ${error.message}`);
22
+ if (messages.length > 0) {
68
23
  throw new ConfigError(`Dynamic block "${dynamicBlockId}" on page "${pageId}" resolved block "${block.blockId}" (${block.type}) has invalid properties:\n${messages.map((message)=>` - ${message}`).join('\n')}`);
69
24
  }
70
25
  }
@@ -85,13 +40,17 @@ async function validateFragment(context, { blocks, blockSchemas, callApiActionRe
85
40
  });
86
41
  });
87
42
  // Request actions can only reference requests defined statically on the page —
88
- // request artifacts are written at build time.
89
- const pageRequestIds = new Set(pageRequests.map((request)=>request.requestId));
90
- requestActionRefs.forEach(({ requestId, blockId, eventId })=>{
91
- if (!pageRequestIds.has(requestId)) {
92
- throw new ConfigError(`Dynamic block "${dynamicBlockId}" on page "${pageId}" resolved content references request "${requestId}" on event "${eventId}" on block "${blockId}" which is not defined on the page.`);
93
- }
94
- });
43
+ // request artifacts are written at build time. A ValidateDynamic step checks
44
+ // content with no page (pageRequests null); the policy's requests list is
45
+ // its check, and page get repeats this one.
46
+ if (pageRequests !== null) {
47
+ const pageRequestIds = new Set(pageRequests.map((request)=>request.requestId));
48
+ requestActionRefs.forEach(({ requestId, blockId, eventId })=>{
49
+ if (!pageRequestIds.has(requestId)) {
50
+ throw new ConfigError(`Dynamic block "${dynamicBlockId}" on page "${pageId}" resolved content references request "${requestId}" on event "${eventId}" on block "${blockId}" which is not defined on the page.`);
51
+ }
52
+ });
53
+ }
95
54
  // CallAPI refs fail resolution instead of the user's click — same checks the
96
55
  // HTTP endpoint route applies.
97
56
  await Promise.all(callApiActionRefs.map(async ({ endpointId, blockId, eventId })=>{
@@ -12,26 +12,96 @@
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 { matchPagePath } from '@lowdefy/node-utils';
16
17
  import resolveDynamicContent from './dynamic/resolveDynamicContent.js';
17
- async function getPageConfig(context, { pageId, urlQuery }) {
18
+ // Matches the request path (basePath and the leading "/" removed) to a page,
19
+ // then returns a status object so the page route can fork on the auth outcome.
20
+ // A matched path also returns the page's pageId and pathParams.
21
+ // - ok: render the page.
22
+ // - not_found and unauthorized both collapse to the opaque /404 redirect -
23
+ // wrong roles never reveal that the page exists.
24
+ // - unauthenticated: a logged-out human gets the authPages.signIn redirect
25
+ // with a callbackUrl back to the requested page.
26
+ // - enrol_required: an authorised caller who has not enrolled a second factor
27
+ // under auth.twoFactor.required gets the authPages.twoFactorEnrol redirect.
28
+ //
29
+ // An unauthenticated caller never learns whether a page exists (Decision 7):
30
+ // in an app whose unlisted ids default to protected, an unmatched path answers
31
+ // unauthenticated, exactly as a protected one does. So in a protected app, a 404
32
+ // means you are signed in - and every app's 404 page stops needing to serve a
33
+ // signed-out visitor who was refused a protected page.
34
+ //
35
+ // The default is a build-resolved boolean, coarser than the glob lists that
36
+ // produced it on purpose: an id absent from the build could still match a
37
+ // declared pattern, and matching globs on the request path to change the answer
38
+ // for URLs that are wrong anyway is a cost the artifact exists to avoid.
39
+ async function getPageConfig(context, { path, urlQuery }) {
40
+ const routes = await context.readConfigFile('routes.json');
41
+ const match = matchPagePath({
42
+ routes,
43
+ path
44
+ });
45
+ if (match === null) {
46
+ if (type.isNone(context.user) && context.authEnforcement?.pagesProtectedByDefault === true) {
47
+ return {
48
+ status: 'unauthenticated'
49
+ };
50
+ }
51
+ return {
52
+ status: 'not_found'
53
+ };
54
+ }
55
+ const { pageId, pathParams } = match;
18
56
  const pageConfig = await context.readConfigFile(`pages/${pageId}.json`);
19
- if (pageConfig && context.authorize(pageConfig)) {
57
+ const outcome = context.authorizeOutcome(pageConfig, {
58
+ pageId
59
+ });
60
+ if (outcome === 'allow') {
20
61
  // eslint-disable-next-line no-unused-vars
21
62
  const { auth, ...rest } = pageConfig;
22
63
  if (rest.dynamic !== true) {
23
64
  // Use serializer.serialize to ensure ~k keys (non-enumerable after deserialize)
24
65
  // are made enumerable again for JSON transfer to client
25
- return serializer.serialize(rest);
66
+ return {
67
+ status: 'ok',
68
+ pageId,
69
+ pathParams,
70
+ pageConfig: serializer.serialize(rest)
71
+ };
26
72
  }
27
73
  // readConfigFile caches parsed artifacts — deep copy before resolution so
28
74
  // one request's resolved content never reaches another via the cache.
29
75
  const resolved = await resolveDynamicContent(context, {
30
76
  pageConfig: serializer.copy(rest),
77
+ pathParams,
31
78
  urlQuery
32
79
  });
33
- return serializer.serialize(resolved);
80
+ return {
81
+ status: 'ok',
82
+ pageId,
83
+ pathParams,
84
+ pageConfig: serializer.serialize(resolved)
85
+ };
86
+ }
87
+ if (outcome === 'enrol_required') {
88
+ return {
89
+ status: 'enrol_required',
90
+ pageId,
91
+ pathParams
92
+ };
93
+ }
94
+ if (type.isNone(context.user)) {
95
+ return {
96
+ status: 'unauthenticated',
97
+ pageId,
98
+ pathParams
99
+ };
34
100
  }
35
- return null;
101
+ return {
102
+ status: 'unauthorized',
103
+ pageId,
104
+ pathParams
105
+ };
36
106
  }
37
107
  export default getPageConfig;
@@ -12,18 +12,33 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import { ConfigError } from '@lowdefy/errors';
16
- function authorizeRequest({ authorize, logger }, { requestConfig }) {
17
- if (!authorize(requestConfig)) {
15
+ */ import { AuthenticationError, AuthorizationError, TwoFactorEnrolmentRequiredError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ function authorizeRequest({ authorizeOutcome: authorize, logger, pageId, user }, { requestConfig }) {
18
+ const outcome = authorize(requestConfig, {
19
+ pageId
20
+ });
21
+ if (outcome !== 'allow') {
18
22
  logger.debug({
19
23
  event: 'debug_request_authorize',
20
24
  authorized: false,
25
+ outcome,
21
26
  auth_config: requestConfig.auth
22
27
  });
28
+ if (outcome === 'enrol_required') {
29
+ // Reached only after the role check passed, so the caller is authorised and
30
+ // this reveals nothing about what exists (Decision 6). A distinct code, not
31
+ // a 401 - a 401 reads to the client as a dead session and bounces the user
32
+ // to sign-in, which is the loop by another route.
33
+ throw new TwoFactorEnrolmentRequiredError(`Two-factor enrolment required for request "${requestConfig.requestId}".`);
34
+ }
35
+ // Unauthenticated on a protected request - 401 tells the caller to fix
36
+ // its credentials. Wrong roles stay opaque below.
37
+ if (type.isNone(user)) {
38
+ throw new AuthenticationError(`Authentication required for request "${requestConfig.requestId}".`);
39
+ }
23
40
  // Throw does not exist error to avoid leaking information that request exists to unauthorized users
24
- throw new ConfigError(`Request "${requestConfig.requestId}" does not exist.`, {
25
- configKey: requestConfig['~k']
26
- });
41
+ throw new AuthorizationError(`Request "${requestConfig.requestId}" does not exist.`);
27
42
  }
28
43
  logger.debug({
29
44
  event: 'debug_request_authorize',
@@ -22,6 +22,7 @@ import getConnection from '../connections/getConnection.js';
22
22
  import getConnectionConfig from '../connections/getConnectionConfig.js';
23
23
  import getRequestConfig from './getRequestConfig.js';
24
24
  import getRequestResolver from './getRequestResolver.js';
25
+ import resolveTenancy from './resolveTenancy.js';
25
26
  import validateSchemas from './validateSchemas.js';
26
27
  import createEvaluateOperators from '../../context/createEvaluateOperators.js';
27
28
  import redactResponse from '../../response/redactResponse.js';
@@ -29,6 +30,7 @@ async function callRequest(context, { blockId, pageId, payload, requestId }) {
29
30
  const { logger } = context;
30
31
  context.blockId = blockId;
31
32
  context.pageId = pageId;
33
+ context.requestId = requestId;
32
34
  const requestPayload = serializer.deserialize(payload);
33
35
  context.payload = requestPayload;
34
36
  context.evaluateOperators = createEvaluateOperators(context);
@@ -57,18 +59,25 @@ async function callRequest(context, { blockId, pageId, payload, requestId }) {
57
59
  connection,
58
60
  requestConfig
59
61
  });
62
+ const { tenant, tenantGuard } = resolveTenancy(context, {
63
+ connection,
64
+ connectionConfig,
65
+ requestConfig,
66
+ writes: requestResolver.meta.checkWrite === true
67
+ });
68
+ // A page request runs outside any routine, so it evaluates against an empty frame.
69
+ const routineContext = {
70
+ arrayIndices: [],
71
+ error: null,
72
+ items: {},
73
+ payload: requestPayload,
74
+ state: {},
75
+ steps: {}
76
+ };
60
77
  const { connectionProperties, requestProperties } = evaluateOperators(context, {
61
78
  connectionConfig,
62
79
  requestConfig,
63
- // A page request runs outside any routine, so it evaluates against an empty frame.
64
- routineContext: {
65
- arrayIndices: [],
66
- error: null,
67
- items: {},
68
- payload: requestPayload,
69
- state: {},
70
- steps: {}
71
- }
80
+ routineContext
72
81
  });
73
82
  checkConnectionRead(context, {
74
83
  connectionConfig,
@@ -94,7 +103,10 @@ async function callRequest(context, { blockId, pageId, payload, requestId }) {
94
103
  endpointDepth: 0,
95
104
  requestConfig,
96
105
  requestProperties,
97
- requestResolver
106
+ requestResolver,
107
+ routineContext,
108
+ tenant,
109
+ tenantGuard
98
110
  });
99
111
  return {
100
112
  id: requestConfig.id,
@@ -12,11 +12,13 @@
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 { RequestError, ServiceError } from '@lowdefy/errors';
15
+ */ import { RequestError, ServiceError, UserError } from '@lowdefy/errors';
16
16
  import getCurrentEnvironment from '../../context/getCurrentEnvironment.js';
17
+ import createWalledResolver from './createWalledResolver.js';
17
18
  import invokeEndpoint from '../endpoints/invokeEndpoint.js';
18
- async function callRequestResolver(context, { connectionProperties, endpointDepth, requestConfig, requestProperties, requestResolver }) {
19
- const { blockId, endpointId, logger, pageId, payload } = context;
19
+ import maskCredentialProperties from './maskCredentialProperties.js';
20
+ async function callRequestResolver(context, { agent = null, connectionProperties, endpointDepth, requestConfig, requestProperties, requestResolver, routineContext, tenant, tenantGuard }) {
21
+ const { blockId, endpointId, logger, pageId, payload, signal } = context;
20
22
  // stepId for endpoint steps (after build), requestId for page requests
21
23
  const stepOrRequestId = requestConfig.stepId ?? requestConfig.requestId;
22
24
  const callApi = async ({ endpointId: targetEndpointId, payload: targetPayload } = {})=>{
@@ -27,6 +29,7 @@ async function callRequestResolver(context, { connectionProperties, endpointDept
27
29
  endpointId: targetEndpointId
28
30
  });
29
31
  const result = await invokeEndpoint(context, {
32
+ agent,
30
33
  endpointId: targetEndpointId,
31
34
  payload: targetPayload,
32
35
  endpointDepth
@@ -58,7 +61,29 @@ async function callRequestResolver(context, { connectionProperties, endpointDept
58
61
  pageId,
59
62
  payload,
60
63
  request: requestProperties,
61
- requestId: stepOrRequestId
64
+ requestId: stepOrRequestId,
65
+ // Aborts when the request that started this work closes: the client
66
+ // disconnected or the server's request timeout answered. Undefined for work
67
+ // nobody waits on (background runs, agent chat). Connection types hand it to
68
+ // their upstream calls so a closed request stops them.
69
+ signal,
70
+ // Names a walled MongoDB connection and returns the bound arguments of
71
+ // getWalledCollection (@lowdefy/connection-mongodb/walled): the only way a
72
+ // plugin reaches a walled database.
73
+ walled: createWalledResolver(context, {
74
+ requestConfig,
75
+ routineContext
76
+ }),
77
+ // The tenant verdict ({ field, value } or null/undefined) computed by
78
+ // resolveTenancy - connection types implementing the scoping contract
79
+ // enforce it (stamp writes, merge filters, inject pipeline matches).
80
+ tenant: tenant ?? null,
81
+ // The unscoped guard ({ field, readOnly } or null) computed by
82
+ // resolveTenancy: readOnly for tenant: none requests, which scoping
83
+ // connection types refuse to write under, and the write guard for shared
84
+ // connections over a walled collection, under which they assert every
85
+ // row the request writes still carries a real organization id.
86
+ tenantGuard: tenantGuard ?? null
62
87
  });
63
88
  return response;
64
89
  } catch (error) {
@@ -78,7 +103,22 @@ async function callRequestResolver(context, { connectionProperties, endpointDept
78
103
  }, error.message);
79
104
  throw error;
80
105
  }
81
- // Check if this is a service error (network, timeout, 5xx)
106
+ // The client left before the resolver finished and the resolver stopped on the
107
+ // signal: the cancellation is the caller's doing, not a fault in the request.
108
+ if (signal?.reason?.name === 'AbortError' && error.name === 'AbortError') {
109
+ const cancelled = new UserError(signal.reason.message, {
110
+ cause: error
111
+ });
112
+ logger.debug({
113
+ params: {
114
+ id: stepOrRequestId,
115
+ type: requestConfig.type
116
+ },
117
+ err: cancelled
118
+ }, cancelled.message);
119
+ throw cancelled;
120
+ }
121
+ // Check if this is a service error (network, timeout, 5xx, 429)
82
122
  if (ServiceError.isServiceError(error)) {
83
123
  const serviceError = new ServiceError(undefined, {
84
124
  cause: error,
@@ -98,7 +138,10 @@ async function callRequestResolver(context, { connectionProperties, endpointDept
98
138
  const requestError = new RequestError(error.message, {
99
139
  cause: error,
100
140
  typeName: requestConfig.type,
101
- received: requestProperties,
141
+ received: maskCredentialProperties({
142
+ requestProperties,
143
+ requestResolver
144
+ }),
102
145
  location: `${requestConfig.connectionId}/${stepOrRequestId}`,
103
146
  configKey: requestConfig['~k']
104
147
  });
@@ -22,7 +22,7 @@ function checkConnectionRead({ logger }, { connectionConfig, connectionPropertie
22
22
  logger.debug({
23
23
  params: {
24
24
  connectionId: connectionConfig.connectionId,
25
- requestId: requestConfig.requestId,
25
+ requestId: requestConfig.stepId ?? requestConfig.requestId,
26
26
  configKey
27
27
  },
28
28
  err
@@ -22,7 +22,7 @@ function checkConnectionWrite({ logger }, { connectionConfig, connectionProperti
22
22
  logger.debug({
23
23
  params: {
24
24
  connectionId: connectionConfig.connectionId,
25
- requestId: requestConfig.requestId,
25
+ requestId: requestConfig.stepId ?? requestConfig.requestId,
26
26
  configKey
27
27
  },
28
28
  err