@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,204 @@
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 { type } from '@lowdefy/helpers';
16
+ import { getPossibleOperators } from '@lowdefy/operators';
17
+ import checkValue from './checkValue.js';
18
+ import isUnderState from './isUnderState.js';
19
+ function isLiteralObject({ value, walk }) {
20
+ return type.isObject(value) && getPossibleOperators({
21
+ value,
22
+ operators: walk.clientOperators
23
+ }).length === 0;
24
+ }
25
+ function literalParamsError({ path, action, policy }) {
26
+ return {
27
+ path,
28
+ rule: 'policy.literal',
29
+ message: `${action} params must be literal under dynamic blocks policy "${policy.id}", so the policy can see their target.`
30
+ };
31
+ }
32
+ function checkLink({ params, path, walk }) {
33
+ const { errors, policy } = walk;
34
+ if (type.isString(params)) {
35
+ // The string form is the pageId shorthand (actions-core Link).
36
+ if (!policy.links.pages.includes(params)) {
37
+ errors.push({
38
+ path,
39
+ rule: 'policy.links',
40
+ message: `Page "${params}" is not in dynamic blocks policy "${policy.id}" links.pages.`
41
+ });
42
+ }
43
+ return;
44
+ }
45
+ if (!isLiteralObject({
46
+ value: params,
47
+ walk
48
+ })) {
49
+ errors.push(literalParamsError({
50
+ path,
51
+ action: 'Link',
52
+ policy
53
+ }));
54
+ return;
55
+ }
56
+ if (getPossibleOperators({
57
+ value: params.home,
58
+ operators: walk.clientOperators
59
+ }).length > 0) {
60
+ errors.push(literalParamsError({
61
+ path: `${path}.home`,
62
+ action: 'Link',
63
+ policy
64
+ }));
65
+ }
66
+ }
67
+ function checkCallApi({ params, path, walk }) {
68
+ const { errors, policy } = walk;
69
+ if (!isLiteralObject({
70
+ value: params,
71
+ walk
72
+ }) || !type.isString(params.endpointId)) {
73
+ errors.push(literalParamsError({
74
+ path,
75
+ action: 'CallAPI',
76
+ policy
77
+ }));
78
+ return;
79
+ }
80
+ if (!policy.endpoints.includes(params.endpointId)) {
81
+ errors.push({
82
+ path: `${path}.endpointId`,
83
+ rule: 'policy.endpoints',
84
+ message: `Endpoint "${params.endpointId}" is not in dynamic blocks policy "${policy.id}" endpoints.`
85
+ });
86
+ }
87
+ }
88
+ // Request params take the forms engine/src/Requests.js reads, except { all },
89
+ // which would call every request on the page.
90
+ function getRequestIds({ params, walk }) {
91
+ if (type.isString(params)) return [
92
+ params
93
+ ];
94
+ if (type.isArray(params)) return params;
95
+ const literal = isLiteralObject({
96
+ value: params,
97
+ walk
98
+ });
99
+ if (literal && type.isString(params.requestId)) return [
100
+ params.requestId
101
+ ];
102
+ if (literal && type.isArray(params.requestIds)) return params.requestIds;
103
+ return null;
104
+ }
105
+ function checkRequest({ params, path, walk }) {
106
+ const { errors, policy } = walk;
107
+ const requestIds = getRequestIds({
108
+ params,
109
+ walk
110
+ });
111
+ if (requestIds === null || !requestIds.every((requestId)=>type.isString(requestId))) {
112
+ errors.push({
113
+ path,
114
+ rule: 'policy.requests',
115
+ message: `Request params must be literal request ids under dynamic blocks policy "${policy.id}". "all" is not allowed.`
116
+ });
117
+ return;
118
+ }
119
+ requestIds.forEach((requestId)=>{
120
+ if (!policy.requests.includes(requestId)) {
121
+ errors.push({
122
+ path,
123
+ rule: 'policy.requests',
124
+ message: `Request "${requestId}" is not in dynamic blocks policy "${policy.id}" requests.`
125
+ });
126
+ }
127
+ });
128
+ }
129
+ function checkSetState({ params, path, walk }) {
130
+ const { errors, policy } = walk;
131
+ if (!isLiteralObject({
132
+ value: params,
133
+ walk
134
+ })) {
135
+ errors.push(literalParamsError({
136
+ path,
137
+ action: 'SetState',
138
+ policy
139
+ }));
140
+ return;
141
+ }
142
+ if (type.isNone(policy.state)) {
143
+ return;
144
+ }
145
+ Object.keys(params).forEach((key)=>{
146
+ if (key.startsWith('~')) return;
147
+ if (!isUnderState({
148
+ key,
149
+ state: policy.state
150
+ })) {
151
+ errors.push({
152
+ path: `${path}.${key}`,
153
+ rule: 'policy.state',
154
+ message: `SetState key "${key}" is outside "${policy.state}", the state dynamic blocks policy "${policy.id}" allows.`
155
+ });
156
+ }
157
+ });
158
+ }
159
+ const ACTION_RULES = {
160
+ CallAPI: checkCallApi,
161
+ Link: checkLink,
162
+ Request: checkRequest,
163
+ SetState: checkSetState
164
+ };
165
+ function checkAction({ action, path, walk }) {
166
+ const { errors, policy } = walk;
167
+ if (!isLiteralObject({
168
+ value: action,
169
+ walk
170
+ }) || !type.isString(action.id) || !type.isString(action.type)) {
171
+ errors.push({
172
+ path,
173
+ rule: 'policy.structure',
174
+ message: 'Actions must be objects with a literal string "id" and "type".'
175
+ });
176
+ return;
177
+ }
178
+ if (walk.actionIds.has(action.id)) {
179
+ errors.push({
180
+ path: `${path}.id`,
181
+ rule: 'policy.structure',
182
+ message: `Action id "${action.id}" is used more than once in this event.`
183
+ });
184
+ }
185
+ walk.actionIds.add(action.id);
186
+ if (!policy.actions.includes(action.type)) {
187
+ errors.push({
188
+ path: `${path}.type`,
189
+ rule: 'policy.actions',
190
+ message: `Action type "${action.type}" is not in dynamic blocks policy "${policy.id}" actions.`
191
+ });
192
+ }
193
+ ACTION_RULES[action.type]?.({
194
+ params: action.params,
195
+ path: `${path}.params`,
196
+ walk
197
+ });
198
+ checkValue({
199
+ value: action,
200
+ path,
201
+ walk
202
+ });
203
+ }
204
+ export default checkAction;
@@ -0,0 +1,163 @@
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 { type } from '@lowdefy/helpers';
16
+ import { getPossibleOperators } from '@lowdefy/operators';
17
+ import checkAction from './checkAction.js';
18
+ import checkValue from './checkValue.js';
19
+ function literalError({ path, what, policy }) {
20
+ return {
21
+ path,
22
+ rule: 'policy.literal',
23
+ message: `${what} must be literal under dynamic blocks policy "${policy.id}", not an operator.`
24
+ };
25
+ }
26
+ // Walks an action list and the branches of its controls (:if/:then/:else,
27
+ // :switch/:case/:then/:default, :return), checking each action and returning
28
+ // the number of actions visited.
29
+ function checkActionList({ actions, path, walk }) {
30
+ const { errors, policy } = walk;
31
+ if (!type.isArray(actions)) {
32
+ errors.push(literalError({
33
+ path,
34
+ what: 'An action list',
35
+ policy
36
+ }));
37
+ return 0;
38
+ }
39
+ let count = 0;
40
+ actions.forEach((item, index)=>{
41
+ const itemPath = `${path}.${index}`;
42
+ if (type.isObject(item) && ':if' in item) {
43
+ checkValue({
44
+ value: item[':if'],
45
+ path: `${itemPath}.:if`,
46
+ walk
47
+ });
48
+ count += checkActionList({
49
+ actions: item[':then'] ?? [],
50
+ path: `${itemPath}.:then`,
51
+ walk
52
+ });
53
+ count += checkActionList({
54
+ actions: item[':else'] ?? [],
55
+ path: `${itemPath}.:else`,
56
+ walk
57
+ });
58
+ return;
59
+ }
60
+ if (type.isObject(item) && ':switch' in item) {
61
+ if (!type.isArray(item[':switch'])) {
62
+ errors.push(literalError({
63
+ path: `${itemPath}.:switch`,
64
+ what: 'A :switch',
65
+ policy
66
+ }));
67
+ return;
68
+ }
69
+ item[':switch'].forEach((caseObject, caseIndex)=>{
70
+ const casePath = `${itemPath}.:switch.${caseIndex}`;
71
+ checkValue({
72
+ value: caseObject?.[':case'],
73
+ path: `${casePath}.:case`,
74
+ walk
75
+ });
76
+ count += checkActionList({
77
+ actions: caseObject?.[':then'] ?? [],
78
+ path: `${casePath}.:then`,
79
+ walk
80
+ });
81
+ });
82
+ count += checkActionList({
83
+ actions: item[':default'] ?? [],
84
+ path: `${itemPath}.:default`,
85
+ walk
86
+ });
87
+ return;
88
+ }
89
+ if (type.isObject(item) && ':return' in item) {
90
+ checkValue({
91
+ value: item[':return'],
92
+ path: `${itemPath}.:return`,
93
+ walk
94
+ });
95
+ return;
96
+ }
97
+ count += 1;
98
+ checkAction({
99
+ action: item,
100
+ path: itemPath,
101
+ walk
102
+ });
103
+ });
104
+ return count;
105
+ }
106
+ // An event is an action list or { try, catch, debounce }.
107
+ function checkEvents({ events, path, walk }) {
108
+ const { errors, policy } = walk;
109
+ if (!type.isObject(events) || getPossibleOperators({
110
+ value: events,
111
+ operators: walk.clientOperators
112
+ }).length > 0) {
113
+ errors.push(literalError({
114
+ path,
115
+ what: 'Block "events"',
116
+ policy
117
+ }));
118
+ return;
119
+ }
120
+ Object.keys(events).forEach((eventName)=>{
121
+ if (eventName.startsWith('~')) return;
122
+ const event = events[eventName];
123
+ const eventPath = `${path}.${eventName}`;
124
+ // Action ids are unique per event, across try, catch and control branches.
125
+ walk.actionIds = new Set();
126
+ let count = 0;
127
+ if (type.isArray(event)) {
128
+ count = checkActionList({
129
+ actions: event,
130
+ path: eventPath,
131
+ walk
132
+ });
133
+ } else if (type.isObject(event) && getPossibleOperators({
134
+ value: event,
135
+ operators: walk.clientOperators
136
+ }).length === 0) {
137
+ count += checkActionList({
138
+ actions: event.try ?? [],
139
+ path: `${eventPath}.try`,
140
+ walk
141
+ });
142
+ count += checkActionList({
143
+ actions: event.catch ?? [],
144
+ path: `${eventPath}.catch`,
145
+ walk
146
+ });
147
+ } else {
148
+ errors.push(literalError({
149
+ path: eventPath,
150
+ what: `Event "${eventName}"`,
151
+ policy
152
+ }));
153
+ }
154
+ if (count > policy.limits.actionsPerEvent) {
155
+ errors.push({
156
+ path: eventPath,
157
+ rule: 'limits.actionsPerEvent',
158
+ message: `Event "${eventName}" has ${count} actions. Dynamic blocks policy "${policy.id}" allows ${policy.limits.actionsPerEvent}.`
159
+ });
160
+ }
161
+ });
162
+ }
163
+ export default checkEvents;
@@ -0,0 +1,313 @@
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 { getPossibleOperators, isNestedDeeperThan, MAX_DATA_DEPTH } from '@lowdefy/operators';
17
+ import getPropertiesSchemaErrors from '../getPropertiesSchemaErrors.js';
18
+ import checkEvents from './checkEvents.js';
19
+ import checkValue from './checkValue.js';
20
+ import collectUrlKinds from './collectUrlKinds.js';
21
+ import findSerializerKeys from './findSerializerKeys.js';
22
+ import isUnderState from './isUnderState.js';
23
+ // Block keys walked by a dedicated rule rather than checkValue.
24
+ const STRUCTURAL_KEYS = new Set([
25
+ 'areas',
26
+ 'blocks',
27
+ 'events',
28
+ 'skeleton',
29
+ 'slots'
30
+ ]);
31
+ // Keys that must be literal so the policy and schema can see inside them.
32
+ const LITERAL_KEYS = [
33
+ 'properties',
34
+ 'style',
35
+ 'layout'
36
+ ];
37
+ function structureError({ path, message }) {
38
+ return {
39
+ path,
40
+ rule: 'policy.structure',
41
+ message
42
+ };
43
+ }
44
+ // Child block lists under blocks, slots.<name>.blocks and areas.<name>.blocks.
45
+ function childBlockLists(block) {
46
+ const lists = [];
47
+ if (!type.isUndefined(block.blocks)) {
48
+ lists.push({
49
+ blocks: block.blocks,
50
+ path: 'blocks'
51
+ });
52
+ }
53
+ [
54
+ 'areas',
55
+ 'slots'
56
+ ].forEach((containerKey)=>{
57
+ Object.keys(block[containerKey] ?? {}).forEach((name)=>{
58
+ if (name.startsWith('~')) return;
59
+ lists.push({
60
+ blocks: block[containerKey][name]?.blocks ?? [],
61
+ path: `${containerKey}.${name}.blocks`
62
+ });
63
+ });
64
+ });
65
+ return lists;
66
+ }
67
+ // Blocks that bind state: inputs write their value at their id, lists hold arrays there.
68
+ function bindsState({ block, blockMetas }) {
69
+ const meta = blockMetas[block.type] ?? {};
70
+ return !type.isNone(meta.valueType) || meta.category === 'list';
71
+ }
72
+ function hasPossibleOperators({ value, walk }) {
73
+ return getPossibleOperators({
74
+ value,
75
+ operators: walk.clientOperators
76
+ }).length > 0;
77
+ }
78
+ function checkBlockShape({ block, path, walk }) {
79
+ const { errors } = walk;
80
+ if (!type.isObject(block) || hasPossibleOperators({
81
+ value: block,
82
+ walk
83
+ })) {
84
+ errors.push(structureError({
85
+ path,
86
+ message: 'Blocks must be literal objects.'
87
+ }));
88
+ return false;
89
+ }
90
+ let valid = true;
91
+ if (!type.isString(block.id)) {
92
+ errors.push(structureError({
93
+ path: `${path}.id`,
94
+ message: 'Block "id" must be a string.'
95
+ }));
96
+ valid = false;
97
+ }
98
+ if (!type.isString(block.type)) {
99
+ errors.push(structureError({
100
+ path: `${path}.type`,
101
+ message: 'Block "type" must be a string.'
102
+ }));
103
+ valid = false;
104
+ }
105
+ if (!type.isNone(block.areas) && !type.isNone(block.slots)) {
106
+ errors.push(structureError({
107
+ path,
108
+ message: 'A block cannot have both "areas" and "slots".'
109
+ }));
110
+ }
111
+ return valid;
112
+ }
113
+ function checkBlock({ block, path, depth, walk }) {
114
+ const { blockMetas, blockSchemas, errors, ids, policy } = walk;
115
+ if (!checkBlockShape({
116
+ block,
117
+ path,
118
+ walk
119
+ })) {
120
+ return;
121
+ }
122
+ walk.count += 1;
123
+ if (depth > policy.limits.depth) {
124
+ errors.push({
125
+ path,
126
+ rule: 'limits.depth',
127
+ message: `Block nesting is deeper than ${policy.limits.depth}, the depth dynamic blocks policy "${policy.id}" allows.`
128
+ });
129
+ return;
130
+ }
131
+ if (!policy.blocks.includes(block.type)) {
132
+ errors.push({
133
+ path: `${path}.type`,
134
+ rule: 'policy.blocks',
135
+ message: `Block type "${block.type}" is not in dynamic blocks policy "${policy.id}" blocks.`
136
+ });
137
+ }
138
+ if (bindsState({
139
+ block,
140
+ blockMetas
141
+ })) {
142
+ if (ids.has(block.id)) {
143
+ errors.push({
144
+ path: `${path}.id`,
145
+ rule: 'policy.ids',
146
+ message: `Block id "${block.id}" binds state and is used more than once.`
147
+ });
148
+ }
149
+ ids.add(block.id);
150
+ if (!type.isNone(policy.state) && !isUnderState({
151
+ key: block.id,
152
+ state: policy.state
153
+ })) {
154
+ errors.push({
155
+ path: `${path}.id`,
156
+ rule: 'policy.state',
157
+ message: `Block id "${block.id}" binds state outside "${policy.state}", the state dynamic blocks policy "${policy.id}" allows.`
158
+ });
159
+ }
160
+ }
161
+ LITERAL_KEYS.forEach((key)=>{
162
+ if (hasPossibleOperators({
163
+ value: block[key],
164
+ walk
165
+ })) {
166
+ errors.push({
167
+ path: `${path}.${key}`,
168
+ rule: 'policy.literal',
169
+ message: `Block "${key}" must be literal under dynamic blocks policy "${policy.id}", not an operator.`
170
+ });
171
+ }
172
+ });
173
+ // The block schema marks which properties hold URLs.
174
+ const urlKinds = collectUrlKinds({
175
+ value: block.properties,
176
+ schema: blockSchemas[block.type]?.properties?.properties,
177
+ path: `${path}.properties`
178
+ });
179
+ Object.keys(block).forEach((key)=>{
180
+ if (key.startsWith('~') || STRUCTURAL_KEYS.has(key)) return;
181
+ checkValue({
182
+ value: block[key],
183
+ key,
184
+ path: `${path}.${key}`,
185
+ walk: {
186
+ ...walk,
187
+ urlKinds
188
+ }
189
+ });
190
+ });
191
+ if (!type.isUndefined(block.events)) {
192
+ checkEvents({
193
+ events: block.events,
194
+ path: `${path}.events`,
195
+ walk
196
+ });
197
+ }
198
+ getPropertiesSchemaErrors({
199
+ block,
200
+ blockSchemas
201
+ }).forEach((message)=>{
202
+ errors.push({
203
+ path: `${path}.properties`,
204
+ rule: 'schema',
205
+ message
206
+ });
207
+ });
208
+ // Skeletons render through LoadingBlock without buildBlock, so they obey the
209
+ // same rules as content.
210
+ if (!type.isUndefined(block.skeleton)) {
211
+ checkBlock({
212
+ block: block.skeleton,
213
+ path: `${path}.skeleton`,
214
+ depth: depth + 1,
215
+ walk
216
+ });
217
+ }
218
+ childBlockLists(block).forEach((list)=>{
219
+ // eslint-disable-next-line no-use-before-define
220
+ checkBlockList({
221
+ blocks: list.blocks,
222
+ path: `${path}.${list.path}`,
223
+ depth: depth + 1,
224
+ walk
225
+ });
226
+ });
227
+ }
228
+ function checkBlockList({ blocks, path, depth, walk }) {
229
+ if (!type.isArray(blocks)) {
230
+ walk.errors.push(structureError({
231
+ path,
232
+ message: 'A block list must be an array.'
233
+ }));
234
+ return;
235
+ }
236
+ blocks.forEach((block, index)=>checkBlock({
237
+ block,
238
+ path: `${path}.${index}`,
239
+ depth,
240
+ walk
241
+ }));
242
+ }
243
+ // Applies a dynamic blocks policy to content as submitted (before buildBlock renames
244
+ // ids or moves areas to slots), so every error's path indexes that content.
245
+ // clientOperators is the app's set of client operator names: a key that names
246
+ // none of them is data to the client. routes is the app's route table, which a
247
+ // same-origin navigation URL is matched against to find its page.
248
+ function checkPolicy({ blocks, policy, blockMetas, blockSchemas, clientOperators = null, routes }) {
249
+ // The rules walk content by recursion, so content nested deeper than any
250
+ // Dynamic data may be is refused first, before it can exhaust the stack.
251
+ if (isNestedDeeperThan({
252
+ value: blocks,
253
+ limit: MAX_DATA_DEPTH
254
+ })) {
255
+ return [
256
+ {
257
+ path: 'blocks',
258
+ rule: 'limits.depth',
259
+ message: `Content is nested more than ${MAX_DATA_DEPTH} levels deep. Dynamic blocks policy "${policy.id}" content may nest at most ${MAX_DATA_DEPTH} levels.`
260
+ }
261
+ ];
262
+ }
263
+ // Checked as the page sends it to the client: an Error or Date in the content
264
+ // is a "~e" or "~d" object there.
265
+ const content = serializer.serialize(blocks, {
266
+ skipMarkers: true
267
+ });
268
+ const bytes = JSON.stringify(content).length;
269
+ if (bytes > policy.limits.bytes) {
270
+ return [
271
+ {
272
+ path: 'blocks',
273
+ rule: 'limits.bytes',
274
+ message: `Content is ${bytes} bytes. Dynamic blocks policy "${policy.id}" allows ${policy.limits.bytes}.`
275
+ }
276
+ ];
277
+ }
278
+ const walk = {
279
+ actionIds: new Set(),
280
+ blockMetas,
281
+ blockSchemas,
282
+ clientOperators,
283
+ count: 0,
284
+ errors: [],
285
+ ids: new Set(),
286
+ policy,
287
+ routes
288
+ };
289
+ checkBlockList({
290
+ blocks: content,
291
+ path: 'blocks',
292
+ depth: 1,
293
+ walk
294
+ });
295
+ findSerializerKeys({
296
+ value: content,
297
+ path: 'blocks'
298
+ }).forEach((path)=>{
299
+ walk.errors.push(structureError({
300
+ path,
301
+ message: 'Keys starting with "~" are reserved for serialized values such as dates.'
302
+ }));
303
+ });
304
+ if (walk.count > policy.limits.blocks) {
305
+ walk.errors.unshift({
306
+ path: 'blocks',
307
+ rule: 'limits.blocks',
308
+ message: `Content has ${walk.count} blocks. Dynamic blocks policy "${policy.id}" allows ${policy.limits.blocks}.`
309
+ });
310
+ }
311
+ return walk.errors;
312
+ }
313
+ export default checkPolicy;