@lowdefy/api 6.0.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/dist/context/applySystemTrust.js +45 -0
  2. package/dist/context/createApiContext.js +18 -3
  3. package/dist/context/createAuthorizeOutcome.js +91 -0
  4. package/dist/context/createBoundSystemContext.js +33 -0
  5. package/dist/context/createEvaluateOperators.js +10 -3
  6. package/dist/context/createRequestSignal.js +47 -0
  7. package/dist/context/createSystemContext.js +80 -0
  8. package/dist/context/getCanonicalUrl.js +27 -0
  9. package/dist/context/getCurrentEnvironment.js +27 -0
  10. package/dist/context/isSameOriginRequest.js +85 -0
  11. package/dist/context/isWebSocketOriginAllowed.js +63 -0
  12. package/dist/context/normalizeInjectedCaller.js +58 -0
  13. package/dist/context/parseRequestBody.js +32 -0
  14. package/dist/context/readMemberships.js +71 -0
  15. package/dist/context/resolveAuthentication.js +758 -0
  16. package/dist/context/resolveStrategyCaller.js +7 -3
  17. package/dist/csp/addNonceToElements.js +23 -0
  18. package/dist/csp/createContentSecurityPolicy.js +45 -0
  19. package/dist/csp/getWebSocketSources.js +36 -0
  20. package/dist/email/renderAuthEmail.js +99 -0
  21. package/dist/index.js +22 -5
  22. package/dist/response/buildEndpointResult.js +3 -1
  23. package/dist/response/createWireProjection.js +88 -0
  24. package/dist/response/formatErrorForAgent.js +35 -0
  25. package/dist/response/normalizeErrorSources.js +10 -13
  26. package/dist/response/redactErrorResponse.js +42 -8
  27. package/dist/response/redactResponse.js +17 -10
  28. package/dist/routes/agent/authorizeAgent.js +17 -5
  29. package/dist/routes/agent/callAgent.js +12 -2
  30. package/dist/routes/agent/collectChatFiles.js +39 -0
  31. package/dist/routes/agent/prepareAgent.js +29 -4
  32. package/dist/routes/auth/buildAdminPlugin.js +33 -0
  33. package/dist/routes/auth/buildCaptchaPlugin.js +61 -0
  34. package/dist/routes/auth/buildMcpTokenPlugin.js +77 -0
  35. package/dist/routes/auth/buildOauthPostLogin.js +73 -0
  36. package/dist/routes/auth/buildPhoneNumberPlugin.js +57 -0
  37. package/dist/routes/auth/buildProviders.js +61 -0
  38. package/dist/routes/auth/createAsMetadataHandler.js +27 -0
  39. package/dist/routes/auth/createAuthLogger.js +31 -0
  40. package/dist/routes/auth/createMcpAccessTokenClaims.js +52 -0
  41. package/dist/routes/auth/createOnAPIError.js +41 -0
  42. package/dist/routes/auth/createSendEmail.js +54 -0
  43. package/dist/routes/auth/ensureMcpTokenIndexes.js +48 -0
  44. package/dist/routes/auth/getAuthEnforcement.js +41 -0
  45. package/dist/routes/auth/getBetterAuth.js +107 -0
  46. package/dist/routes/auth/getBetterAuthConfig.js +767 -0
  47. package/dist/routes/auth/handleAuthRequest.js +43 -0
  48. package/dist/routes/auth/hooks/authHookPoints.js +204 -0
  49. package/dist/routes/auth/hooks/buildEngineHooks.js +68 -0
  50. package/dist/routes/auth/hooks/buildHooks.js +112 -0
  51. package/dist/routes/auth/{callbacks/addUserFieldsToSession.js → hooks/composeAfterSlot.js} +11 -13
  52. package/dist/routes/auth/hooks/composeBeforeSlot.js +41 -0
  53. package/dist/routes/auth/hooks/createHookDispatch.js +59 -0
  54. package/dist/routes/auth/hooks/createUserAfterHook.js +36 -0
  55. package/dist/routes/auth/hooks/createUserBeforeHook.js +50 -0
  56. package/dist/routes/auth/hooks/findHookUser.js +27 -0
  57. package/dist/routes/auth/modelNames.js +30 -0
  58. package/dist/routes/auth/organizations/OrganizationKeyError.js +28 -0
  59. package/dist/routes/auth/organizations/authorizeRole.js +27 -0
  60. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +178 -0
  61. package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +57 -0
  62. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +120 -0
  63. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +403 -0
  64. package/dist/routes/auth/organizations/createAdmissionGateHook.js +50 -0
  65. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +90 -0
  66. package/dist/routes/auth/organizations/createAutoJoinHook.js +68 -0
  67. package/dist/routes/auth/organizations/createEmailSendGate.js +59 -0
  68. package/dist/routes/auth/organizations/createExpiredInvitationGate.js +76 -0
  69. package/dist/routes/auth/organizations/ensureAuthIndexes.js +122 -0
  70. package/dist/routes/auth/organizations/ensureOrganization.js +132 -0
  71. package/dist/routes/auth/organizations/findPendingInvitation.js +43 -0
  72. package/dist/routes/auth/organizations/getHookRequestHeaders.js +24 -0
  73. package/dist/routes/auth/organizations/getOrganizationBinding.js +65 -0
  74. package/dist/routes/auth/organizations/isEmailAdmitted.js +89 -0
  75. package/dist/routes/auth/organizations/organizationAccessControl.js +94 -0
  76. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +62 -0
  77. package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +145 -0
  78. package/dist/routes/auth/requestHooks/buildRequestHooks.js +288 -0
  79. package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +43 -0
  80. package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +59 -0
  81. package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +47 -0
  82. package/dist/routes/auth/requestHooks/redirectToChallenge.js +79 -0
  83. package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +31 -0
  84. package/dist/routes/auth/resolveCookiePrefix.js +30 -0
  85. package/dist/routes/auth/sanitizeSessionResponse.js +27 -0
  86. package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
  87. package/dist/routes/connections/checkUnwalledReach.js +37 -0
  88. package/dist/routes/connections/getConnectionConfig.js +6 -1
  89. package/dist/routes/connections/resolveTenantPreflight.js +226 -0
  90. package/dist/routes/connections/resolveUnwalledReach.js +144 -0
  91. package/dist/routes/endpoints/acceptDetachedEndpoint.js +50 -0
  92. package/dist/routes/endpoints/authorizeApiEndpoint.js +13 -4
  93. package/dist/routes/endpoints/callEndpoint.js +23 -7
  94. package/dist/routes/endpoints/control/controlFor.js +4 -7
  95. package/dist/routes/endpoints/control/controlIf.js +4 -8
  96. package/dist/routes/endpoints/control/controlLog.js +6 -14
  97. package/dist/routes/endpoints/control/controlParallelFor.js +65 -29
  98. package/dist/routes/endpoints/control/controlReject.js +36 -16
  99. package/dist/routes/endpoints/control/controlReturn.js +32 -9
  100. package/dist/routes/endpoints/control/controlSetState.js +4 -8
  101. package/dist/routes/endpoints/control/controlSwitch.js +4 -8
  102. package/dist/routes/endpoints/control/controlThrow.js +20 -21
  103. package/dist/routes/endpoints/control/controlTry.js +30 -11
  104. package/dist/routes/endpoints/control/controlWhile.js +55 -0
  105. package/dist/routes/endpoints/control/handleControl.js +3 -1
  106. package/dist/routes/endpoints/createWebhookAnswer.js +78 -0
  107. package/dist/routes/endpoints/evaluateRoutineOperators.js +27 -0
  108. package/dist/routes/endpoints/forwardScheduledEndpoint.js +21 -15
  109. package/dist/routes/endpoints/getEndpointConfig.js +18 -8
  110. package/dist/routes/endpoints/getEnvironmentSchedules.js +5 -7
  111. package/dist/routes/endpoints/getSchemaValidator.js +39 -0
  112. package/dist/routes/endpoints/handleAgentCall.js +25 -9
  113. package/dist/routes/endpoints/handleAuthStep.js +214 -0
  114. package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
  115. package/dist/routes/endpoints/handleEndpointCall.js +46 -12
  116. package/dist/routes/endpoints/handleRenderNotification.js +29 -12
  117. package/dist/routes/endpoints/handleRequest.js +13 -6
  118. package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
  119. package/dist/routes/endpoints/handleValidateSchema.js +22 -22
  120. package/dist/routes/endpoints/invokeEndpoint.js +27 -3
  121. package/dist/routes/endpoints/operatorScope.js +28 -0
  122. package/dist/routes/{auth/events/createEventPlugins.js → endpoints/parseWebhookBody.js} +10 -6
  123. package/dist/routes/endpoints/resolveCallBinding.js +91 -0
  124. package/dist/routes/endpoints/resolveCronEnvironment.js +7 -6
  125. package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
  126. package/dist/routes/endpoints/runDetachedEndpoint.js +64 -18
  127. package/dist/routes/endpoints/runRoutine.js +64 -5
  128. package/dist/routes/endpoints/runScheduledEndpoint.js +19 -11
  129. package/dist/routes/endpoints/runWebhookEndpoint.js +70 -23
  130. package/dist/routes/endpoints/runWebhookVerify.js +129 -0
  131. package/dist/routes/endpoints/scheduleBackground.js +10 -0
  132. package/dist/routes/endpoints/test/runTest.js +48 -11
  133. package/dist/routes/endpoints/validatePayload.js +144 -0
  134. package/dist/routes/log/logClientError.js +7 -4
  135. package/dist/routes/mcp/createMcpServer.js +143 -64
  136. package/dist/routes/mcp/getMcpJwks.js +93 -0
  137. package/dist/routes/mcp/getMcpResourceBinding.js +41 -0
  138. package/dist/routes/mcp/getMcpUri.js +69 -0
  139. package/dist/routes/mcp/oauthResourceLifecycle.js +122 -0
  140. package/dist/routes/mcp/runAfterToolCall.js +50 -0
  141. package/dist/routes/notifications/resolveNotificationLinks.js +39 -11
  142. package/dist/routes/page/dynamic/checkDynamicContent.js +81 -0
  143. package/dist/routes/page/dynamic/checkLiteralContent.js +242 -0
  144. package/dist/routes/page/dynamic/createContentError.js +34 -0
  145. package/dist/routes/page/dynamic/flagIconsOutsidePage.js +39 -0
  146. package/dist/routes/page/dynamic/flagTypesOutsidePage.js +44 -0
  147. package/dist/routes/page/dynamic/getPropertiesSchemaErrors.js +35 -0
  148. package/dist/routes/page/dynamic/loadDynamicArtifacts.js +52 -0
  149. package/dist/routes/page/dynamic/policy/checkAction.js +204 -0
  150. package/dist/routes/page/dynamic/policy/checkEvents.js +163 -0
  151. package/dist/routes/page/dynamic/policy/checkPolicy.js +313 -0
  152. package/dist/routes/page/dynamic/policy/checkValue.js +214 -0
  153. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +117 -0
  154. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +54 -0
  155. package/dist/routes/page/dynamic/policy/findSerializerKeys.js +50 -0
  156. package/dist/routes/page/dynamic/policy/isAllowedUrl.js +53 -0
  157. package/dist/routes/{auth/createAdapter.js → page/dynamic/policy/isUnderState.js} +5 -9
  158. package/dist/routes/page/dynamic/policy/normalizeUrlText.js +25 -0
  159. package/dist/routes/page/dynamic/resolveDynamicContent.js +89 -37
  160. package/dist/routes/page/dynamic/unescapeOperators.js +21 -4
  161. package/dist/routes/page/dynamic/validateFragment.js +17 -58
  162. package/dist/routes/page/getPageConfig.js +76 -6
  163. package/dist/routes/request/authorizeRequest.js +21 -6
  164. package/dist/routes/request/callRequest.js +21 -3
  165. package/dist/routes/request/callRequestResolver.js +55 -6
  166. package/dist/routes/request/checkConnectionRead.js +1 -1
  167. package/dist/routes/request/checkConnectionWrite.js +1 -1
  168. package/dist/routes/request/createWalledResolver.js +75 -0
  169. package/dist/routes/request/evaluateOperators.js +8 -12
  170. package/dist/routes/request/getRequestConfig.js +19 -3
  171. package/dist/routes/request/maskCredentialProperties.js +34 -0
  172. package/dist/routes/request/resolveTenancy.js +223 -0
  173. package/dist/routes/request/validateSchemas.js +7 -6
  174. package/dist/routes/{auth/callbacks/createCallbackPlugins.js → rootConfig/getAppEvents.js} +7 -6
  175. package/dist/routes/rootConfig/getHomeAndMenus.js +23 -16
  176. package/dist/routes/{auth/events/createSessionEvent.js → rootConfig/getPagePaths.js} +16 -18
  177. package/dist/routes/rootConfig/getRootConfig.js +9 -3
  178. package/dist/routes/rootConfig/menus/filterMenuList.js +5 -2
  179. package/dist/routes/websocket/authorizeWebsocket.js +19 -4
  180. package/dist/routes/websocket/createChannelRegistry.js +39 -14
  181. package/dist/routes/websocket/createWebSocketConnection.js +162 -28
  182. package/dist/routes/websocket/getCallerFingerprint.js +31 -0
  183. package/dist/routes/websocket/prepareChannel.js +29 -1
  184. package/dist/routes/websocket/resolveWebsocketCaller.js +40 -0
  185. package/dist/test/testContext.js +16 -11
  186. package/package.json +28 -12
  187. package/dist/context/createAuthorize.js +0 -45
  188. package/dist/response/omitErrorProps.js +0 -51
  189. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +0 -30
  190. package/dist/routes/auth/callbacks/createCallbacks.js +0 -46
  191. package/dist/routes/auth/callbacks/createJWTCallback.js +0 -77
  192. package/dist/routes/auth/callbacks/createRedirectCallback.js +0 -41
  193. package/dist/routes/auth/callbacks/createSessionCallback.js +0 -81
  194. package/dist/routes/auth/callbacks/createSignInCallback.js +0 -40
  195. package/dist/routes/auth/callbacks/validateSessionRoles.js +0 -33
  196. package/dist/routes/auth/createLogger.js +0 -35
  197. package/dist/routes/auth/createPrefixedCookies.js +0 -52
  198. package/dist/routes/auth/createProviders.js +0 -25
  199. package/dist/routes/auth/events/createCreateUserEvent.js +0 -41
  200. package/dist/routes/auth/events/createEvents.js +0 -56
  201. package/dist/routes/auth/events/createLinkAccountEvent.js +0 -43
  202. package/dist/routes/auth/events/createSignInEvent.js +0 -46
  203. package/dist/routes/auth/events/createSignOutEvent.js +0 -43
  204. package/dist/routes/auth/events/createUpdateUserEvent.js +0 -41
  205. package/dist/routes/auth/getAuthConfig.js +0 -86
  206. package/dist/routes/auth/resolveCookies.js +0 -37
  207. package/dist/routes/log/formatValidationError.js +0 -31
  208. /package/dist/{routes/notifications → email}/resolveThemeLogo.js +0 -0
@@ -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;
@@ -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 { type } from '@lowdefy/helpers';
16
+ import { getPossibleOperators } from '@lowdefy/operators';
17
+ import findEmbeddedUrls from './findEmbeddedUrls.js';
18
+ import isAllowedUrl from './isAllowedUrl.js';
19
+ import isUnderState from './isUnderState.js';
20
+ // How the client uses a URL value, for values no schema marks. A block schema
21
+ // marks its URL-valued properties with urlKind (collectUrlKinds), whatever they
22
+ // are called, and opts a URL-named property out with urlKind: false; every
23
+ // other value (action params, style, unmarked properties, including every
24
+ // property of a block that marks none) is judged by these key names. url and
25
+ // href navigate, and the engine's link resolver reads a colon-less url as https.
26
+ const URL_KEY_KINDS = {
27
+ action: 'src',
28
+ cover: 'src',
29
+ href: 'href',
30
+ image: 'src',
31
+ poster: 'src',
32
+ src: 'src',
33
+ srcMobile: 'src',
34
+ srcSet: 'srcSet',
35
+ url: 'url'
36
+ };
37
+ const HTML_TAG = /<[a-zA-Z/!]/;
38
+ function joinPath(path, key) {
39
+ return path ? `${path}.${key}` : `${key}`;
40
+ }
41
+ function getUrlKind({ key, path, walk }) {
42
+ if (walk.urlKinds?.has(path)) {
43
+ return walk.urlKinds.get(path);
44
+ }
45
+ return URL_KEY_KINDS[key] ?? null;
46
+ }
47
+ function listUrls({ value, urlKind }) {
48
+ // srcSet lists "url descriptor" pairs.
49
+ if (urlKind === 'srcSet') return value.split(',').map((entry)=>entry.trim().split(/\s+/)[0]);
50
+ return [
51
+ value
52
+ ];
53
+ }
54
+ function checkString({ value, key, path, walk }) {
55
+ const { errors, policy, routes } = walk;
56
+ if (!policy.html && HTML_TAG.test(value)) {
57
+ errors.push({
58
+ path,
59
+ rule: 'policy.html',
60
+ message: `String contains HTML tag syntax. Dynamic blocks policy "${policy.id}" does not allow HTML.`
61
+ });
62
+ }
63
+ if (key === 'pageId' && !policy.links.pages.includes(value)) {
64
+ errors.push({
65
+ path,
66
+ rule: 'policy.links',
67
+ message: `Page "${value}" is not in dynamic blocks policy "${policy.id}" links.pages.`
68
+ });
69
+ }
70
+ const urlKind = getUrlKind({
71
+ key,
72
+ path,
73
+ walk
74
+ });
75
+ if (urlKind !== null) {
76
+ listUrls({
77
+ value,
78
+ urlKind
79
+ }).forEach((url)=>{
80
+ const allowed = isAllowedUrl({
81
+ value: url,
82
+ policy,
83
+ navigation: urlKind === 'url' || urlKind === 'href',
84
+ schemeless: urlKind === 'url',
85
+ routes
86
+ });
87
+ if (!allowed) {
88
+ // A URL in a list (an array item) has no key of its own.
89
+ const label = key === null ? 'URL' : `"${key}" value`;
90
+ errors.push({
91
+ path,
92
+ rule: 'policy.urls',
93
+ message: `${label} "${url}" is not a page or origin dynamic blocks policy "${policy.id}" allows.`
94
+ });
95
+ }
96
+ });
97
+ return;
98
+ }
99
+ // A URL value was judged whole above; other strings are searched.
100
+ findEmbeddedUrls(value).forEach((url)=>{
101
+ if (!isAllowedUrl({
102
+ value: url,
103
+ policy,
104
+ navigation: false,
105
+ schemeless: false,
106
+ routes
107
+ })) {
108
+ errors.push({
109
+ path,
110
+ rule: 'policy.urls',
111
+ message: `URL "${url}" is not an origin dynamic blocks policy "${policy.id}" allows.`
112
+ });
113
+ }
114
+ });
115
+ }
116
+ // A _state read may only name a literal key under the policy's state, so
117
+ // content cannot read other page state and send it on (a CallAPI payload).
118
+ function isAllowedStateRead({ params, state }) {
119
+ if (type.isString(params)) {
120
+ return isUnderState({
121
+ key: params,
122
+ state
123
+ });
124
+ }
125
+ return type.isObject(params) && params.all !== true && type.isString(params.key) && isUnderState({
126
+ key: params.key,
127
+ state
128
+ });
129
+ }
130
+ function checkOperators({ value, key, path, walk }) {
131
+ const { clientOperators, errors, policy } = walk;
132
+ const possible = getPossibleOperators({
133
+ value,
134
+ operators: clientOperators
135
+ });
136
+ possible.forEach(({ key: operatorKey, operator })=>{
137
+ if (!policy.operators.includes(operator)) {
138
+ errors.push({
139
+ path,
140
+ rule: 'policy.operators',
141
+ message: `Operator "${operator}" is not in dynamic blocks policy "${policy.id}" operators.`
142
+ });
143
+ }
144
+ if (operator === '_state' && !type.isNone(policy.state) && !isAllowedStateRead({
145
+ params: value[operatorKey],
146
+ state: policy.state
147
+ })) {
148
+ errors.push({
149
+ path,
150
+ rule: 'policy.state',
151
+ message: `_state must read a literal key under "${policy.state}", the state dynamic blocks policy "${policy.id}" allows.`
152
+ });
153
+ }
154
+ });
155
+ // The client would compute this value at render time, where the policy
156
+ // cannot see it.
157
+ const urlKind = getUrlKind({
158
+ key,
159
+ path,
160
+ walk
161
+ });
162
+ if (possible.length > 0 && (urlKind !== null || key === 'pageId')) {
163
+ // A URL in a list (an array item) has no key of its own.
164
+ const label = key === null ? 'A URL' : `"${key}"`;
165
+ errors.push({
166
+ path,
167
+ rule: key === 'pageId' ? 'policy.links' : 'policy.urls',
168
+ message: `${label} must be a literal string under dynamic blocks policy "${policy.id}", not an operator.`
169
+ });
170
+ }
171
+ }
172
+ // Walks any config value: every operator must be allowed, _state reads must stay
173
+ // under the policy's state, URL-valued and pageId values must be literal and
174
+ // allowed, and strings must obey the html rule. walk carries the policy, the
175
+ // app's client operators, the error list and, inside block properties, the URL
176
+ // kinds the block's schema marks (by path).
177
+ function checkValue({ value, key = null, path, walk }) {
178
+ if (type.isString(value)) {
179
+ checkString({
180
+ value,
181
+ key,
182
+ path,
183
+ walk
184
+ });
185
+ return;
186
+ }
187
+ if (type.isArray(value)) {
188
+ value.forEach((item, index)=>checkValue({
189
+ value: item,
190
+ path: joinPath(path, index),
191
+ walk
192
+ }));
193
+ return;
194
+ }
195
+ if (!type.isObject(value)) {
196
+ return;
197
+ }
198
+ checkOperators({
199
+ value,
200
+ key,
201
+ path,
202
+ walk
203
+ });
204
+ Object.keys(value).forEach((childKey)=>{
205
+ if (childKey.startsWith('~')) return;
206
+ checkValue({
207
+ value: value[childKey],
208
+ key: childKey,
209
+ path: joinPath(path, childKey),
210
+ walk
211
+ });
212
+ });
213
+ }
214
+ export default checkValue;