@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,117 @@
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
+ // The schemas that can describe a value: the schema itself and its oneOf,
17
+ // anyOf and allOf branches, however nested.
18
+ function expandSchema(schema) {
19
+ const schemas = [];
20
+ const pending = [
21
+ schema
22
+ ];
23
+ while(pending.length > 0){
24
+ const candidate = pending.pop();
25
+ if (type.isObject(candidate)) {
26
+ schemas.push(candidate);
27
+ [
28
+ ...candidate.oneOf ?? [],
29
+ ...candidate.anyOf ?? [],
30
+ ...candidate.allOf ?? []
31
+ ].forEach((branch)=>pending.push(branch));
32
+ }
33
+ }
34
+ return schemas;
35
+ }
36
+ function childSchemas({ schemas, key }) {
37
+ return schemas.flatMap((schema)=>{
38
+ if (type.isObject(schema.properties?.[key])) {
39
+ return [
40
+ schema.properties[key]
41
+ ];
42
+ }
43
+ if (type.isObject(schema.additionalProperties)) {
44
+ return [
45
+ schema.additionalProperties
46
+ ];
47
+ }
48
+ return [];
49
+ });
50
+ }
51
+ // The urlKind the schemas give a value: a string when one marks it as a URL,
52
+ // null when one opts it out with urlKind: false, undefined when none says.
53
+ function findUrlKind(schemas) {
54
+ const marked = schemas.find((candidate)=>type.isString(candidate.urlKind));
55
+ if (marked) {
56
+ return marked.urlKind;
57
+ }
58
+ if (schemas.some((candidate)=>candidate.urlKind === false)) {
59
+ return null;
60
+ }
61
+ return undefined;
62
+ }
63
+ // Records, by path, the urlKind a block schema gives the value there. A block
64
+ // marks each URL-valued property with urlKind ('url' and 'href' navigate, 'url'
65
+ // the way the engine's link resolver does; 'src' loads; 'srcSet' lists
66
+ // sources), so the policy judges URLs by what a property is, not by what it is
67
+ // called; a marked array holds one URL per item. urlKind: false records null,
68
+ // for a property whose name looks like a URL key but whose value is not a URL.
69
+ // A value no schema marks either way is not recorded, so the policy falls back
70
+ // to judging it by its key name.
71
+ function collectUrlKinds({ value, schema, path }) {
72
+ const kinds = new Map();
73
+ const pending = [
74
+ {
75
+ value,
76
+ schema,
77
+ path
78
+ }
79
+ ];
80
+ while(pending.length > 0){
81
+ const item = pending.pop();
82
+ const schemas = expandSchema(item.schema);
83
+ const urlKind = findUrlKind(schemas);
84
+ if (urlKind === null) {
85
+ // Another schema branch may already have marked it as a URL.
86
+ if (!kinds.has(item.path)) {
87
+ kinds.set(item.path, null);
88
+ }
89
+ } else if (type.isString(urlKind)) {
90
+ if (type.isArray(item.value)) {
91
+ item.value.forEach((_, index)=>kinds.set(`${item.path}.${index}`, urlKind));
92
+ } else {
93
+ kinds.set(item.path, urlKind);
94
+ }
95
+ } else if (type.isArray(item.value)) {
96
+ const itemSchemas = schemas.map((candidate)=>candidate.items).filter(type.isObject);
97
+ item.value.forEach((child, index)=>itemSchemas.forEach((itemSchema)=>pending.push({
98
+ value: child,
99
+ schema: itemSchema,
100
+ path: `${item.path}.${index}`
101
+ })));
102
+ } else if (type.isObject(item.value)) {
103
+ Object.keys(item.value).forEach((key)=>{
104
+ childSchemas({
105
+ schemas,
106
+ key
107
+ }).forEach((childSchema)=>pending.push({
108
+ value: item.value[key],
109
+ schema: childSchema,
110
+ path: `${item.path}.${key}`
111
+ }));
112
+ });
113
+ }
114
+ }
115
+ return kinds;
116
+ }
117
+ export default collectUrlKinds;
@@ -0,0 +1,54 @@
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 normalizeUrlText from './normalizeUrlText.js';
16
+ // Returns every URL a string can make the client load or navigate to that is
17
+ // not given by its key: a scheme or protocol-relative value (read as the URL
18
+ // parser reads it), markdown link and image targets, and CSS
19
+ // url()/image-set()/src() arguments after unescaping.
20
+ const SCHEME = /^[a-zA-Z][a-zA-Z0-9+.-]*:\S/;
21
+ // Script schemes run whatever follows them, spaces included.
22
+ const SCRIPT_SCHEME = /^(javascript|vbscript):/i;
23
+ const MARKDOWN_INLINE = /\]\(\s*<?([^)\s>]+)/g;
24
+ const MARKDOWN_REFERENCE = /^\s*\[[^\]]+\]:\s*<?([^\s>]+)/gm;
25
+ const CSS_FUNCTION = /(url|src|image-set)\(([^)]*)\)/gi;
26
+ const QUOTED = /(['"])(.*?)\1/g;
27
+ function unescapeCss(value) {
28
+ return value.replace(/\\([0-9a-fA-F]{1,6})\s?/g, (_, hex)=>String.fromCodePoint(parseInt(hex, 16))).replace(/\\(.)/g, '$1');
29
+ }
30
+ function findEmbeddedUrls(value) {
31
+ const urls = [];
32
+ const text = normalizeUrlText(value);
33
+ const isUrlText = !/\s/.test(text) && (SCHEME.test(text) || text.startsWith('//') || text.startsWith('/\\'));
34
+ if (isUrlText || SCRIPT_SCHEME.test(text)) {
35
+ urls.push(text);
36
+ }
37
+ for (const match of value.matchAll(MARKDOWN_INLINE))urls.push(match[1]);
38
+ for (const match of value.matchAll(MARKDOWN_REFERENCE))urls.push(match[1]);
39
+ if (value.includes('(')) {
40
+ for (const match of unescapeCss(value).matchAll(CSS_FUNCTION)){
41
+ const argument = match[2].trim();
42
+ const quoted = [
43
+ ...argument.matchAll(QUOTED)
44
+ ].map((quote)=>quote[2]);
45
+ if (quoted.length > 0) {
46
+ urls.push(...quoted);
47
+ } else if (match[1].toLowerCase() !== 'image-set') {
48
+ urls.push(argument);
49
+ }
50
+ }
51
+ }
52
+ return urls;
53
+ }
54
+ export default findEmbeddedUrls;
@@ -0,0 +1,50 @@
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
+ // Paths of the "~" keys in serialized content. The client revives each such
17
+ // wrapper ("~e" to an Error, "~d" to a Date, "~arr" to an array) only after it
18
+ // has evaluated the operators inside it, where the policy walk does not look.
19
+ // Block config never needs one, so every "~" key is reported, except the
20
+ // { "~d": <number> } of a date, which holds no config.
21
+ function findSerializerKeys({ value, path, paths = [] }) {
22
+ if (type.isArray(value)) {
23
+ value.forEach((item, index)=>findSerializerKeys({
24
+ value: item,
25
+ path: `${path}.${index}`,
26
+ paths
27
+ }));
28
+ return paths;
29
+ }
30
+ if (!type.isObject(value)) {
31
+ return paths;
32
+ }
33
+ const keys = Object.keys(value);
34
+ if (keys.length === 1 && keys[0] === '~d' && type.isNumber(value['~d'])) {
35
+ return paths;
36
+ }
37
+ keys.forEach((key)=>{
38
+ if (key.startsWith('~')) {
39
+ paths.push(`${path}.${key}`);
40
+ return;
41
+ }
42
+ findSerializerKeys({
43
+ value: value[key],
44
+ path: `${path}.${key}`,
45
+ paths
46
+ });
47
+ });
48
+ return paths;
49
+ }
50
+ export default findSerializerKeys;
@@ -0,0 +1,53 @@
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 { matchPagePath } from '@lowdefy/node-utils';
16
+ import normalizeUrlText from './normalizeUrlText.js';
17
+ // A reserved origin: a URL that resolves to it stays on the app.
18
+ const SENTINEL = 'https://app.invalid';
19
+ // Decides one URL. Same-origin values are allowed, except that navigation
20
+ // (href, url, Link) may only name an app path that matches a page the policy
21
+ // lists.
22
+ // Anything else must be http(s) on an origin the policy lists. `schemeless`
23
+ // mirrors the engine's link resolver (engine/src/resolveTarget.js,
24
+ // classifyUrl), which reads a colon-less `url` such as `example.com` as
25
+ // `https://example.com`.
26
+ function isAllowedUrl({ value, policy, navigation, schemeless, routes }) {
27
+ const text = normalizeUrlText(value);
28
+ if (text === '' || text.startsWith('#')) {
29
+ return true;
30
+ }
31
+ const candidate = schemeless && !text.includes(':') && !text.startsWith('/') ? `https://${text}` : text;
32
+ let url;
33
+ try {
34
+ url = new URL(candidate, SENTINEL);
35
+ } catch {
36
+ return false;
37
+ }
38
+ if (url.origin === SENTINEL) {
39
+ if (!navigation) {
40
+ return true;
41
+ }
42
+ const match = matchPagePath({
43
+ routes,
44
+ path: url.pathname.slice(1)
45
+ });
46
+ return match !== null && policy.links.pages.includes(match.pageId);
47
+ }
48
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
49
+ return false;
50
+ }
51
+ return policy.links.origins.includes(url.origin);
52
+ }
53
+ export default isAllowedUrl;
@@ -12,13 +12,9 @@
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
- */ function createAdapter({ authConfig, plugins }) {
16
- const adapterConfig = authConfig.adapter;
17
- if (!adapterConfig) {
18
- return undefined;
19
- }
20
- return plugins.adapters[adapterConfig.type]({
21
- properties: adapterConfig.properties
22
- });
15
+ */ // A state path sits under the policy's state root when it is the root itself
16
+ // or a dot path below it.
17
+ function isUnderState({ key, state }) {
18
+ return key === state || key.startsWith(`${state}.`);
23
19
  }
24
- export default createAdapter;
20
+ export default isUnderState;
@@ -0,0 +1,25 @@
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
+ */ // Leading and trailing C0 control characters and spaces, and tabs and newlines
16
+ // anywhere: what the browser's URL parser drops before it reads a URL.
17
+ // eslint-disable-next-line no-control-regex
18
+ const EDGE_CONTROLS = /^[\x00-\x20]+|[\x00-\x20]+$/g;
19
+ const TABS_AND_NEWLINES = /[\t\n\r]/g;
20
+ // A URL string as the browser's URL parser reads it, so " https://x" and
21
+ // "java\tscript:" are judged as what they are to it.
22
+ function normalizeUrlText(value) {
23
+ return value.replace(EDGE_CONTROLS, '').replace(TABS_AND_NEWLINES, '');
24
+ }
25
+ export default normalizeUrlText;
@@ -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 })=>{