@lowdefy/api 7.1.0 → 7.3.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 (126) hide show
  1. package/dist/context/createAuthorizeOutcome.js +1 -1
  2. package/dist/context/createEvaluateOperators.js +2 -1
  3. package/dist/context/isWebSocketOriginAllowed.js +3 -1
  4. package/dist/context/readMemberships.js +10 -4
  5. package/dist/context/resolveAuthentication.js +99 -31
  6. package/dist/email/renderAuthEmail.js +3 -2
  7. package/dist/index.js +7 -1
  8. package/dist/response/redactErrorResponse.js +8 -4
  9. package/dist/routes/agent/callAgent.js +20 -2
  10. package/dist/routes/agent/redactMessages.js +136 -0
  11. package/dist/routes/auth/createAuthLogger.js +23 -6
  12. package/dist/routes/auth/createMcpAccessTokenClaims.js +8 -6
  13. package/dist/routes/auth/createOnAPIError.js +15 -5
  14. package/dist/routes/auth/createSendEmail.js +15 -5
  15. package/dist/routes/auth/getBetterAuth.js +3 -3
  16. package/dist/routes/auth/getBetterAuthConfig.js +172 -98
  17. package/dist/routes/auth/hooks/buildEngineHooks.js +15 -1
  18. package/dist/routes/auth/hooks/createUserAfterHook.js +17 -2
  19. package/dist/routes/auth/hooks/createUserBeforeHook.js +20 -4
  20. package/dist/routes/auth/isUserBanned.js +28 -0
  21. package/dist/routes/auth/mobile/buildBearerPlugin.js +45 -0
  22. package/dist/routes/auth/mobile/buildOneTimeTokenPlugin.js +50 -0
  23. package/dist/routes/auth/mobile/createCodeVerifierCheck.js +57 -0
  24. package/dist/routes/auth/mobile/createKnownDeviceHook.js +76 -0
  25. package/dist/routes/auth/mobile/createMobileAuthPageResponse.js +79 -0
  26. package/dist/routes/auth/mobile/createMobileSessionCreateHook.js +41 -0
  27. package/dist/routes/auth/mobile/createMobileSessionRefreshHook.js +40 -0
  28. package/dist/routes/auth/mobile/createMobileSignInCsrfToken.js +32 -0
  29. package/dist/routes/auth/mobile/createPhoneSession.js +59 -0
  30. package/dist/routes/auth/mobile/escapeHtml.js +26 -0
  31. package/dist/routes/auth/mobile/getCodeHolderIdentifier.js +20 -0
  32. package/dist/routes/auth/mobile/getKnownDeviceIdentifier.js +20 -0
  33. package/dist/routes/auth/mobile/getMobileSessionExpiry.js +18 -0
  34. package/dist/routes/auth/mobile/getMobileSignInReturnUrl.js +31 -0
  35. package/dist/routes/auth/mobile/getOneTimeTokenIdentifiers.js +26 -0
  36. package/dist/routes/auth/mobile/handleMobileSignIn.js +303 -0
  37. package/dist/routes/auth/mobile/handleMobileSignInCallback.js +30 -0
  38. package/dist/routes/auth/mobile/isNativeAuthRequest.js +33 -0
  39. package/dist/routes/auth/mobile/matchesCodeChallenge.js +29 -0
  40. package/dist/routes/auth/mobile/mintOneTimeToken.js +41 -0
  41. package/dist/routes/auth/mobile/readDeviceKeyHash.js +34 -0
  42. package/dist/routes/auth/mobile/readMobileSignInParams.js +90 -0
  43. package/dist/routes/auth/mobile/sha256Base64Url.js +22 -0
  44. package/dist/routes/auth/mobile/storeCodeChallenge.js +29 -0
  45. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +57 -11
  46. package/dist/routes/auth/organizations/checkInvitationContactLink.js +60 -0
  47. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +47 -12
  48. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +41 -189
  49. package/dist/routes/auth/organizations/createAdmissionGateHook.js +5 -5
  50. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +40 -16
  51. package/dist/routes/auth/organizations/createBeforeAcceptInvitationHook.js +35 -0
  52. package/dist/routes/auth/organizations/createBeforeCreateInvitationHook.js +62 -0
  53. package/dist/routes/auth/organizations/createBeforeUpdateMemberRoleHook.js +45 -0
  54. package/dist/routes/auth/organizations/createEmailSendGate.js +35 -7
  55. package/dist/routes/auth/organizations/createSuspendedMemberGate.js +146 -0
  56. package/dist/routes/auth/organizations/createSuspendedOrganizationsFilter.js +44 -0
  57. package/dist/routes/auth/organizations/ensureAuthIndexes.js +11 -10
  58. package/dist/routes/auth/organizations/getOrganizationBinding.js +4 -2
  59. package/dist/routes/auth/organizations/isActiveMember.js +26 -0
  60. package/dist/routes/auth/organizations/isEmailAdmitted.js +25 -14
  61. package/dist/routes/auth/organizations/memberRowsLimit.js +19 -0
  62. package/dist/routes/auth/organizations/mintOrganization.js +258 -0
  63. package/dist/routes/auth/organizations/organizationAccessControl.js +5 -1
  64. package/dist/routes/auth/organizations/provisionOrganization.js +117 -0
  65. package/dist/routes/auth/organizations/readSuspendedOrganizationIds.js +36 -0
  66. package/dist/routes/auth/requestHooks/buildRequestHooks.js +78 -2
  67. package/dist/routes/auth/requestHooks/createEmailCodeHolderGate.js +58 -0
  68. package/dist/routes/auth/requestHooks/createEmailSendLimit.js +116 -0
  69. package/dist/routes/auth/requestHooks/createSignInRefusedRedirectHook.js +75 -0
  70. package/dist/routes/auth/requestHooks/holdEmailCode.js +80 -0
  71. package/dist/routes/auth/requestHooks/reserveSendSlot.js +70 -0
  72. package/dist/routes/auth/runReportingFaults.js +32 -0
  73. package/dist/routes/connections/resolveUnwalledReach.js +14 -16
  74. package/dist/routes/endpoints/callEndpoint.js +6 -3
  75. package/dist/routes/endpoints/control/controlFor.js +9 -6
  76. package/dist/routes/endpoints/control/controlIf.js +8 -3
  77. package/dist/routes/endpoints/control/controlLog.js +3 -1
  78. package/dist/routes/endpoints/control/controlParallelFor.js +9 -6
  79. package/dist/routes/endpoints/control/controlReturn.js +3 -2
  80. package/dist/routes/endpoints/control/controlSetState.js +1 -1
  81. package/dist/routes/endpoints/control/controlSwitch.js +6 -3
  82. package/dist/routes/endpoints/control/controlWhile.js +6 -3
  83. package/dist/routes/endpoints/createLinkAnswer.js +76 -0
  84. package/dist/routes/endpoints/dispatchDetached.js +38 -0
  85. package/dist/routes/endpoints/forwardScheduledEndpoint.js +32 -11
  86. package/dist/routes/endpoints/handleAgentCall.js +1 -1
  87. package/dist/routes/endpoints/handleAuthStep.js +19 -4
  88. package/dist/routes/endpoints/handleEndpointCall.js +6 -4
  89. package/dist/routes/endpoints/handleRequest.js +3 -2
  90. package/dist/routes/endpoints/handleValidateDynamic.js +1 -1
  91. package/dist/routes/endpoints/matchLinkEndpoint.js +30 -0
  92. package/dist/routes/endpoints/runLinkEndpoint.js +148 -0
  93. package/dist/routes/endpoints/runRoutine.js +5 -5
  94. package/dist/routes/endpoints/scheduleBackground.js +13 -11
  95. package/dist/routes/endpoints/test/runTest.js +30 -11
  96. package/dist/routes/mcp/createMcpServer.js +2 -7
  97. package/dist/routes/mcp/runAfterToolCall.js +9 -3
  98. package/dist/routes/mobile/createAppleAppSiteAssociation.js +51 -0
  99. package/dist/routes/mobile/createAssetLinks.js +38 -0
  100. package/dist/routes/mobile/filterMobileMenus.js +31 -0
  101. package/dist/routes/mobile/getMobileAppEvents.js +23 -0
  102. package/dist/routes/mobile/getMobileRootConfig.js +109 -0
  103. package/dist/routes/mobile/getOpenablePageIds.js +21 -0
  104. package/dist/routes/page/dynamic/policy/checkAction.js +67 -2
  105. package/dist/routes/page/dynamic/policy/checkEvents.js +8 -2
  106. package/dist/routes/page/dynamic/policy/checkPolicy.js +86 -6
  107. package/dist/routes/page/dynamic/policy/checkValue.js +97 -6
  108. package/dist/routes/page/dynamic/policy/collectSchemaKinds.js +173 -0
  109. package/dist/routes/page/dynamic/policy/findDataRows.js +94 -0
  110. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +24 -12
  111. package/dist/routes/page/dynamic/policy/findHtmlUrls.js +64 -0
  112. package/dist/routes/page/dynamic/policy/overlapsStatePath.js +28 -0
  113. package/dist/routes/page/dynamic/resolveDynamicContent.js +23 -17
  114. package/dist/routes/page/getPageConfig.js +25 -1
  115. package/dist/routes/request/callRequestResolver.js +29 -36
  116. package/dist/routes/request/stampTypedError.js +37 -0
  117. package/dist/routes/request/summarisedError.js +62 -0
  118. package/dist/routes/request/wrapResolverError.js +61 -0
  119. package/dist/routes/websocket/checkWebsocketAccess.js +81 -0
  120. package/dist/routes/websocket/createChannelRegistry.js +62 -17
  121. package/dist/routes/websocket/createWebSocketConnection.js +59 -21
  122. package/dist/routes/websocket/prepareChannel.js +11 -0
  123. package/dist/test/createMemoryAuth.js +125 -0
  124. package/package.json +20 -22
  125. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +0 -117
  126. package/dist/routes/request/maskCredentialProperties.js +0 -34
@@ -17,9 +17,11 @@ import { getPossibleOperators, isNestedDeeperThan, MAX_DATA_DEPTH } from '@lowde
17
17
  import getPropertiesSchemaErrors from '../getPropertiesSchemaErrors.js';
18
18
  import checkEvents from './checkEvents.js';
19
19
  import checkValue from './checkValue.js';
20
- import collectUrlKinds from './collectUrlKinds.js';
20
+ import collectSchemaKinds from './collectSchemaKinds.js';
21
+ import findDataRows from './findDataRows.js';
21
22
  import findSerializerKeys from './findSerializerKeys.js';
22
23
  import isUnderState from './isUnderState.js';
24
+ import overlapsStatePath from './overlapsStatePath.js';
23
25
  // Block keys walked by a dedicated rule rather than checkValue.
24
26
  const STRUCTURAL_KEYS = new Set([
25
27
  'areas',
@@ -170,12 +172,33 @@ function checkBlock({ block, path, depth, walk }) {
170
172
  });
171
173
  }
172
174
  });
173
- // The block schema marks which properties hold URLs.
174
- const urlKinds = collectUrlKinds({
175
+ // The block schema marks which properties hold URLs and how it draws text.
176
+ const propertiesSchema = blockSchemas[block.type]?.properties?.properties;
177
+ const propertiesPath = `${path}.properties`;
178
+ const { urlKind: urlKinds, textKind: textKinds } = collectSchemaKinds({
175
179
  value: block.properties,
176
- schema: blockSchemas[block.type]?.properties?.properties,
177
- path: `${path}.properties`
180
+ schema: propertiesSchema,
181
+ path: propertiesPath,
182
+ keywords: [
183
+ 'urlKind',
184
+ 'textKind'
185
+ ]
178
186
  });
187
+ findDataRows({
188
+ properties: block.properties,
189
+ schema: propertiesSchema,
190
+ path: propertiesPath
191
+ }).forEach((rowsPath)=>textKinds.set(rowsPath, 'data'));
192
+ // An input whose properties hold data (option values, rows) can put that
193
+ // data in state at its id.
194
+ if (bindsState({
195
+ block,
196
+ blockMetas
197
+ }) && [
198
+ ...textKinds.values()
199
+ ].includes('data')) {
200
+ walk.dataStateKeys.push(block.id);
201
+ }
179
202
  Object.keys(block).forEach((key)=>{
180
203
  if (key.startsWith('~') || STRUCTURAL_KEYS.has(key)) return;
181
204
  checkValue({
@@ -184,7 +207,8 @@ function checkBlock({ block, path, depth, walk }) {
184
207
  path: `${path}.${key}`,
185
208
  walk: {
186
209
  ...walk,
187
- urlKinds
210
+ urlKinds,
211
+ textKinds
188
212
  }
189
213
  });
190
214
  });
@@ -225,6 +249,53 @@ function checkBlock({ block, path, depth, walk }) {
225
249
  });
226
250
  });
227
251
  }
252
+ // The ids of content inputs whose value is an object, such as a rich text
253
+ // editor, an upload or a table input: they draw parts of their value as markup,
254
+ // links or images, so a SetState value bound to one keeps every check.
255
+ function collectObjectValueIds({ blocks, blockMetas, ids = [] }) {
256
+ if (!type.isArray(blocks)) return ids;
257
+ blocks.forEach((block)=>{
258
+ if (!type.isObject(block) || !type.isString(block.id)) return;
259
+ if (blockMetas[block.type]?.valueType === 'object') {
260
+ ids.push(block.id);
261
+ }
262
+ if (type.isObject(block.skeleton)) {
263
+ collectObjectValueIds({
264
+ blocks: [
265
+ block.skeleton
266
+ ],
267
+ blockMetas,
268
+ ids
269
+ });
270
+ }
271
+ childBlockLists(block).forEach((list)=>{
272
+ collectObjectValueIds({
273
+ blocks: list.blocks,
274
+ blockMetas,
275
+ ids
276
+ });
277
+ });
278
+ });
279
+ return ids;
280
+ }
281
+ // A _state read the content may draw must not name state the content fills
282
+ // with data (SetState values, input option values and rows), which no rule
283
+ // checked. A read with no literal key may name any of it.
284
+ function checkDrawnStateReads({ walk }) {
285
+ const { dataStateKeys, drawnStateReads, errors, policy } = walk;
286
+ drawnStateReads.forEach(({ path, key })=>{
287
+ const dataKey = dataStateKeys.find((dataStateKey)=>key === null || overlapsStatePath({
288
+ key,
289
+ id: dataStateKey
290
+ }));
291
+ if (type.isUndefined(dataKey)) return;
292
+ errors.push({
293
+ path,
294
+ rule: 'policy.state',
295
+ message: `_state reads "${dataKey}", which the content fills with data, where the content may draw it. Under dynamic blocks policy "${policy.id}", read it only in a CallAPI payload, a SetState value or a condition.`
296
+ });
297
+ });
298
+ }
228
299
  function checkBlockList({ blocks, path, depth, walk }) {
229
300
  if (!type.isArray(blocks)) {
230
301
  walk.errors.push(structureError({
@@ -281,8 +352,14 @@ function checkPolicy({ blocks, policy, blockMetas, blockSchemas, clientOperators
281
352
  blockSchemas,
282
353
  clientOperators,
283
354
  count: 0,
355
+ dataStateKeys: [],
356
+ drawnStateReads: [],
284
357
  errors: [],
285
358
  ids: new Set(),
359
+ objectValueIds: collectObjectValueIds({
360
+ blocks: content,
361
+ blockMetas
362
+ }),
286
363
  policy,
287
364
  routes
288
365
  };
@@ -292,6 +369,9 @@ function checkPolicy({ blocks, policy, blockMetas, blockSchemas, clientOperators
292
369
  depth: 1,
293
370
  walk
294
371
  });
372
+ checkDrawnStateReads({
373
+ walk
374
+ });
295
375
  findSerializerKeys({
296
376
  value: content,
297
377
  path: 'blocks'
@@ -15,10 +15,11 @@
15
15
  */ import { type } from '@lowdefy/helpers';
16
16
  import { getPossibleOperators } from '@lowdefy/operators';
17
17
  import findEmbeddedUrls from './findEmbeddedUrls.js';
18
+ import findHtmlUrls from './findHtmlUrls.js';
18
19
  import isAllowedUrl from './isAllowedUrl.js';
19
20
  import isUnderState from './isUnderState.js';
20
21
  // 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
+ // marks its URL-valued properties with urlKind (collectSchemaKinds), whatever they
22
23
  // are called, and opts a URL-named property out with urlKind: false; every
23
24
  // other value (action params, style, unmarked properties, including every
24
25
  // property of a block that marks none) is judged by these key names. url and
@@ -51,9 +52,44 @@ function listUrls({ value, urlKind }) {
51
52
  value
52
53
  ];
53
54
  }
55
+ // Which URLs a string can carry depends on how its block draws it (textKind,
56
+ // from the block schema). A value is a URL where it is used as a link (a URL
57
+ // key or urlKind mark, judged whole above); text and HTML a block draws are no
58
+ // link and render no markdown, so a whole value, a markdown target or a
59
+ // protocol-relative word in them is words. HTML can carry a style, a link or a
60
+ // source attribute only when the policy allows tags (findHtmlUrls). A value no schema marks may be drawn as
61
+ // markdown, a style or a link the schema does not mark, so every scan applies.
62
+ function getUrlScans({ textKind, policy }) {
63
+ if (textKind === 'text') {
64
+ return {
65
+ wholeValue: false,
66
+ markdown: false,
67
+ css: false
68
+ };
69
+ }
70
+ if (textKind === 'html') {
71
+ return {
72
+ wholeValue: false,
73
+ markdown: false,
74
+ css: policy.html === true
75
+ };
76
+ }
77
+ return {
78
+ wholeValue: true,
79
+ markdown: true,
80
+ css: true
81
+ };
82
+ }
54
83
  function checkString({ value, key, path, walk }) {
55
84
  const { errors, policy, routes } = walk;
56
- if (!policy.html && HTML_TAG.test(value)) {
85
+ // Data is stored or sent, never drawn or followed by the content, so every
86
+ // string in it is text.
87
+ if (walk.isData) {
88
+ return;
89
+ }
90
+ const textKind = walk.textKinds?.get(path) ?? null;
91
+ // A string drawn as escaped text shows tag syntax as written.
92
+ if (!policy.html && textKind !== 'text' && HTML_TAG.test(value)) {
57
93
  errors.push({
58
94
  path,
59
95
  rule: 'policy.html',
@@ -97,7 +133,13 @@ function checkString({ value, key, path, walk }) {
97
133
  return;
98
134
  }
99
135
  // A URL value was judged whole above; other strings are searched.
100
- findEmbeddedUrls(value).forEach((url)=>{
136
+ findEmbeddedUrls({
137
+ value,
138
+ ...getUrlScans({
139
+ textKind,
140
+ policy
141
+ })
142
+ }).forEach((url)=>{
101
143
  if (!isAllowedUrl({
102
144
  value: url,
103
145
  policy,
@@ -112,6 +154,27 @@ function checkString({ value, key, path, walk }) {
112
154
  });
113
155
  }
114
156
  });
157
+ // With tags allowed, any string a block may draw as HTML can carry a link or
158
+ // a source in an attribute.
159
+ if (policy.html === true && textKind !== 'text') {
160
+ findHtmlUrls({
161
+ value
162
+ }).forEach(({ url, navigation })=>{
163
+ if (!isAllowedUrl({
164
+ value: url,
165
+ policy,
166
+ navigation,
167
+ schemeless: false,
168
+ routes
169
+ })) {
170
+ errors.push({
171
+ path,
172
+ rule: 'policy.urls',
173
+ message: `HTML attribute URL "${url}" is not a page or origin dynamic blocks policy "${policy.id}" allows.`
174
+ });
175
+ }
176
+ });
177
+ }
115
178
  }
116
179
  // A _state read may only name a literal key under the policy's state, so
117
180
  // content cannot read other page state and send it on (a CallAPI payload).
@@ -127,6 +190,15 @@ function isAllowedStateRead({ params, state }) {
127
190
  state
128
191
  });
129
192
  }
193
+ // The state key a _state read names, or null when it is not a literal key
194
+ // (only a policy without a state path allows that).
195
+ function getStateReadKey(params) {
196
+ if (type.isString(params)) return params;
197
+ if (type.isObject(params) && params.all !== true && type.isString(params.key)) {
198
+ return params.key;
199
+ }
200
+ return null;
201
+ }
130
202
  function checkOperators({ value, key, path, walk }) {
131
203
  const { clientOperators, errors, policy } = walk;
132
204
  const possible = getPossibleOperators({
@@ -151,9 +223,20 @@ function checkOperators({ value, key, path, walk }) {
151
223
  message: `_state must read a literal key under "${policy.state}", the state dynamic blocks policy "${policy.id}" allows.`
152
224
  });
153
225
  }
226
+ // Content may draw what it reads, so a read of state it fills with data
227
+ // is judged against those keys once the walk has found them all.
228
+ if (operator === '_state' && !walk.isData && !walk.undrawn) {
229
+ walk.drawnStateReads.push({
230
+ path,
231
+ key: getStateReadKey(value[operatorKey])
232
+ });
233
+ }
154
234
  });
155
235
  // The client would compute this value at render time, where the policy
156
- // cannot see it.
236
+ // cannot see it. In data nothing is a URL or a page link.
237
+ if (walk.isData) {
238
+ return;
239
+ }
157
240
  const urlKind = getUrlKind({
158
241
  key,
159
242
  path,
@@ -173,8 +256,16 @@ function checkOperators({ value, key, path, walk }) {
173
256
  // under the policy's state, URL-valued and pageId values must be literal and
174
257
  // allowed, and strings must obey the html rule. walk carries the policy, the
175
258
  // 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 }) {
259
+ // and text kinds the block's schema marks (by path). Under a value marked
260
+ // textKind 'data', and in walk.isData (SetState values), only the operator
261
+ // rules apply: the content stores the value and never draws or follows it.
262
+ // walk.undrawn marks a value the content sends or tests but never draws (a
263
+ // CallAPI payload, a condition), where a _state read draws nothing.
264
+ function checkValue({ value, key = null, path, walk: parentWalk }) {
265
+ const walk = !parentWalk.isData && parentWalk.textKinds?.get(path) === 'data' ? {
266
+ ...parentWalk,
267
+ isData: true
268
+ } : parentWalk;
178
269
  if (type.isString(value)) {
179
270
  checkString({
180
271
  value,
@@ -0,0 +1,173 @@
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 kind the schemas give a value under keyword: a string when one marks it,
52
+ // null when one opts it out with false, undefined when none says.
53
+ function findKind({ schemas, keyword }) {
54
+ const marked = schemas.find((candidate)=>type.isString(candidate[keyword]));
55
+ if (marked) {
56
+ return marked[keyword];
57
+ }
58
+ if (schemas.some((candidate)=>candidate[keyword] === false)) {
59
+ return null;
60
+ }
61
+ return undefined;
62
+ }
63
+ // A 'data' value with dataWith is data only beside a string at that sibling
64
+ // key: an option value is drawn in place of a missing label. Without it the
65
+ // value is unmarked, so it keeps every check.
66
+ function applyDataWith({ kind, schemas, parent }) {
67
+ if (kind !== 'data') {
68
+ return kind;
69
+ }
70
+ const withKey = schemas.find((candidate)=>type.isString(candidate.dataWith))?.dataWith;
71
+ if (type.isUndefined(withKey) || type.isString(parent?.[withKey])) {
72
+ return kind;
73
+ }
74
+ return undefined;
75
+ }
76
+ // Records, by path, the kind a block schema gives the value there under each
77
+ // keyword, so the policy judges a value by what its property is, not by what it
78
+ // is called. A marked array holds one value of that kind per item; false records
79
+ // null; a value no schema marks either way is not recorded. Returns a Map per
80
+ // keyword; one walk reads them all, since it runs on every Dynamic block.
81
+ //
82
+ // urlKind marks URL-valued properties ('url' and 'href' navigate, 'url' the way
83
+ // the engine's link resolver does; 'src' loads; 'srcSet' lists sources), and
84
+ // urlKind: false a property whose name looks like a URL key but whose value is
85
+ // not a URL. textKind marks how a block draws a string: 'html' through
86
+ // renderHtml (sanitised HTML, never markdown or a link), 'text' as escaped
87
+ // text, and 'data' a value the block stores or compares but never draws (an
88
+ // option value), so every string in it, however nested, is text. dataWith
89
+ // names a sibling key the value is data only beside (applyDataWith). Values
90
+ // neither marks fall back to the key-name and text rules.
91
+ function collectSchemaKinds({ value, schema, path, keywords }) {
92
+ const kindsByKeyword = Object.fromEntries(keywords.map((keyword)=>[
93
+ keyword,
94
+ new Map()
95
+ ]));
96
+ const pending = [
97
+ {
98
+ value,
99
+ schema,
100
+ path,
101
+ keywords
102
+ }
103
+ ];
104
+ while(pending.length > 0){
105
+ const item = pending.pop();
106
+ const schemas = expandSchema(item.schema);
107
+ // The keywords a mark has not settled here, read again in the children.
108
+ const open = item.keywords.filter((keyword)=>{
109
+ const kinds = kindsByKeyword[keyword];
110
+ const kind = applyDataWith({
111
+ kind: findKind({
112
+ schemas,
113
+ keyword
114
+ }),
115
+ schemas,
116
+ parent: item.parent
117
+ });
118
+ if (kind === null) {
119
+ // Another schema branch may already have marked it.
120
+ if (!kinds.has(item.path)) {
121
+ kinds.set(item.path, null);
122
+ }
123
+ return false;
124
+ }
125
+ if (type.isString(kind) && type.isArray(item.value)) {
126
+ item.value.forEach((_, index)=>kinds.set(`${item.path}.${index}`, kind));
127
+ return false;
128
+ }
129
+ if (type.isString(kind) && !type.isObject(item.value)) {
130
+ kinds.set(item.path, kind);
131
+ return false;
132
+ }
133
+ if (type.isObject(item.value)) {
134
+ // An object under a branch that marks strings is an operator, which the
135
+ // policy judges by a urlKind mark (it must be literal), or an object
136
+ // whose properties other branches mark (an option that is a string or a
137
+ // { label, value } object), so it is walked too.
138
+ if (type.isString(kind)) {
139
+ kinds.set(item.path, kind);
140
+ }
141
+ return true;
142
+ }
143
+ return type.isArray(item.value);
144
+ });
145
+ if (open.length === 0) {
146
+ continue;
147
+ }
148
+ if (type.isArray(item.value)) {
149
+ const itemSchemas = schemas.map((candidate)=>candidate.items).filter(type.isObject);
150
+ item.value.forEach((child, index)=>itemSchemas.forEach((itemSchema)=>pending.push({
151
+ value: child,
152
+ schema: itemSchema,
153
+ path: `${item.path}.${index}`,
154
+ keywords: open
155
+ })));
156
+ } else {
157
+ Object.keys(item.value).forEach((key)=>{
158
+ childSchemas({
159
+ schemas,
160
+ key
161
+ }).forEach((childSchema)=>pending.push({
162
+ value: item.value[key],
163
+ schema: childSchema,
164
+ path: `${item.path}.${key}`,
165
+ parent: item.value,
166
+ keywords: open
167
+ }));
168
+ });
169
+ }
170
+ }
171
+ return kindsByKeyword;
172
+ }
173
+ export default collectSchemaKinds;
@@ -0,0 +1,94 @@
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 { get, type } from '@lowdefy/helpers';
16
+ // Every column a columns list holds, column groups' children included.
17
+ function flattenColumns({ columns, mark }) {
18
+ return (columns ?? []).flatMap((column)=>{
19
+ if (type.isObject(column) && type.isArray(column[mark.children])) {
20
+ return [
21
+ column,
22
+ ...flattenColumns({
23
+ columns: column[mark.children],
24
+ mark
25
+ })
26
+ ];
27
+ }
28
+ return [
29
+ column
30
+ ];
31
+ });
32
+ }
33
+ function drawsAsText({ column, mark }) {
34
+ if (type.isString(column)) {
35
+ return mark.textTypes.includes(mark.defaultType);
36
+ }
37
+ if (!type.isObject(column)) {
38
+ return false;
39
+ }
40
+ // A column group draws no cells of its own.
41
+ if (type.isArray(column[mark.children]) && type.isNone(column[mark.type])) {
42
+ return true;
43
+ }
44
+ // A cell option that reads another row field into the cell, such as a
45
+ // colour, draws that field as more than text.
46
+ const cell = column[mark.cell];
47
+ if (type.isObject(cell) && mark.cellRowKeys.some((key)=>!type.isNone(cell[key]))) {
48
+ return false;
49
+ }
50
+ return mark.textTypes.includes(column[mark.type] ?? mark.defaultType);
51
+ }
52
+ function isDataRows({ properties, key, mark }) {
53
+ if (!type.isArray(properties[key])) {
54
+ return false;
55
+ }
56
+ if (mark.drawnBy.some((drawnBy)=>!type.isNone(get(properties, drawnBy)))) {
57
+ return false;
58
+ }
59
+ const columns = properties[mark.columns];
60
+ if (!type.isNone(columns) && !type.isArray(columns)) {
61
+ return false;
62
+ }
63
+ return flattenColumns({
64
+ columns,
65
+ mark
66
+ }).every((column)=>drawsAsText({
67
+ column,
68
+ mark
69
+ }));
70
+ }
71
+ // Returns the paths of row lists that are data: a top-level property whose
72
+ // schema marks it with rowsKind, holding an array, where every column of the
73
+ // sibling columns property draws its cell as text and nothing else draws the
74
+ // rows. A column whose type draws a link, an image or HTML, or whose cell
75
+ // options read a row field into the cell, leaves the rows to every check.
76
+ // rowsKind names the columns property; a column's type, children and cell
77
+ // options keys; the type a column without one has; the text types; the cell
78
+ // options that read a row field; and the properties (dot paths) that draw rows
79
+ // themselves when set:
80
+ // { columns, type, children, cell, cellRowKeys, drawnBy, defaultType, textTypes }.
81
+ function findDataRows({ properties, schema, path }) {
82
+ if (!type.isObject(properties) || !type.isObject(schema?.properties)) {
83
+ return [];
84
+ }
85
+ return Object.keys(schema.properties).filter((key)=>{
86
+ const mark = schema.properties[key].rowsKind;
87
+ return type.isObject(mark) && isDataRows({
88
+ properties,
89
+ key,
90
+ mark
91
+ });
92
+ }).map((key)=>`${path}.${key}`);
93
+ }
94
+ export default findDataRows;
@@ -14,12 +14,22 @@
14
14
  limitations under the License.
15
15
  */ import normalizeUrlText from './normalizeUrlText.js';
16
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;
17
+ // not given by its key: a whole value with a scheme the browser loads or runs,
18
+ // or a protocol-relative one (read as the URL parser reads it), markdown link
19
+ // and image targets, and CSS url()/image-set()/src() arguments after
20
+ // unescaping. A word such as "INC:42" or "HH:mm" has the shape of a scheme but
21
+ // names none the browser acts on, so it is text.
22
+ //
23
+ // The caller turns off the scans that cannot apply to how the value is drawn: a
24
+ // property drawn as text or HTML renders no markdown, and is no link, so neither
25
+ // the whole value, a markdown target nor a protocol-relative word in it is a URL;
26
+ // CSS url() only loads in text that can carry a style.
27
+ // An allowlist of schemes, not a scheme-shaped pattern: any word may hold a colon.
28
+ const LOADED_SCHEME = /^(https?|ftp|wss?|file|blob|filesystem):\S/i;
29
+ // Script and data schemes keep whatever follows them, spaces included.
30
+ const SCRIPT_SCHEME = /^(javascript|vbscript|data):/i;
31
+ // The URL parser reads a backslash as a slash, so "\\host" is protocol-relative too.
32
+ const PROTOCOL_RELATIVE = /^[\\/][\\/]/;
23
33
  const MARKDOWN_INLINE = /\]\(\s*<?([^)\s>]+)/g;
24
34
  const MARKDOWN_REFERENCE = /^\s*\[[^\]]+\]:\s*<?([^\s>]+)/gm;
25
35
  const CSS_FUNCTION = /(url|src|image-set)\(([^)]*)\)/gi;
@@ -27,16 +37,18 @@ const QUOTED = /(['"])(.*?)\1/g;
27
37
  function unescapeCss(value) {
28
38
  return value.replace(/\\([0-9a-fA-F]{1,6})\s?/g, (_, hex)=>String.fromCodePoint(parseInt(hex, 16))).replace(/\\(.)/g, '$1');
29
39
  }
30
- function findEmbeddedUrls(value) {
40
+ function findEmbeddedUrls({ value, wholeValue = true, markdown = true, css = true }) {
31
41
  const urls = [];
32
42
  const text = normalizeUrlText(value);
33
- const isUrlText = !/\s/.test(text) && (SCHEME.test(text) || text.startsWith('//') || text.startsWith('/\\'));
34
- if (isUrlText || SCRIPT_SCHEME.test(text)) {
43
+ const isUrlText = !/\s/.test(text) && (LOADED_SCHEME.test(text) || PROTOCOL_RELATIVE.test(text));
44
+ if (wholeValue && (isUrlText || SCRIPT_SCHEME.test(text))) {
35
45
  urls.push(text);
36
46
  }
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('(')) {
47
+ if (markdown) {
48
+ for (const match of value.matchAll(MARKDOWN_INLINE))urls.push(match[1]);
49
+ for (const match of value.matchAll(MARKDOWN_REFERENCE))urls.push(match[1]);
50
+ }
51
+ if (css && value.includes('(')) {
40
52
  for (const match of unescapeCss(value).matchAll(CSS_FUNCTION)){
41
53
  const argument = match[2].trim();
42
54
  const quoted = [
@@ -0,0 +1,64 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ // Returns every URL an HTML string can make the client load or navigate to
16
+ // through an attribute, as { url, navigation }. With tags allowed, DOMPurify
17
+ // keeps <a href> and <img src>, so these are judged as links and sources.
18
+ //
19
+ // Attributes are matched anywhere in the string, not only inside a tag: a ">"
20
+ // in a quoted attribute value would end a tag pattern early and hide the
21
+ // attributes after it, and text that only looks like an attribute fails safe.
22
+ const ATTRIBUTE = /(?:^|[\s/"'])(href|xlink:href|action|formaction|src|poster|background|srcset)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi;
23
+ const NAVIGATION_ATTRIBUTES = new Set([
24
+ 'href',
25
+ 'xlink:href',
26
+ 'action',
27
+ 'formaction'
28
+ ]);
29
+ // The named references that spell the characters a URL's scheme and host turn
30
+ // on; the browser decodes these before it reads the URL.
31
+ const NAMED_REFERENCES = {
32
+ amp: '&',
33
+ colon: ':',
34
+ sol: '/',
35
+ bsol: '\\',
36
+ tab: '\t',
37
+ newline: '\n'
38
+ };
39
+ const REFERENCE = /&(?:#x([0-9a-f]+)|#(\d+)|([a-z]+));?/gi;
40
+ function decodeReferences(value) {
41
+ return value.replace(REFERENCE, (match, hex, decimal, name)=>{
42
+ if (hex) return String.fromCodePoint(parseInt(hex, 16));
43
+ if (decimal) return String.fromCodePoint(parseInt(decimal, 10));
44
+ return NAMED_REFERENCES[name.toLowerCase()] ?? match;
45
+ });
46
+ }
47
+ function findHtmlUrls({ value }) {
48
+ const urls = [];
49
+ for (const match of value.matchAll(ATTRIBUTE)){
50
+ const name = match[1].toLowerCase();
51
+ const attribute = decodeReferences(match[2] ?? match[3] ?? match[4]);
52
+ const navigation = NAVIGATION_ATTRIBUTES.has(name);
53
+ // srcset lists "url descriptor" pairs.
54
+ const entries = name === 'srcset' ? attribute.split(',').map((entry)=>entry.trim().split(/\s+/)[0]) : [
55
+ attribute
56
+ ];
57
+ entries.forEach((url)=>urls.push({
58
+ url,
59
+ navigation
60
+ }));
61
+ }
62
+ return urls;
63
+ }
64
+ export default findHtmlUrls;