@lowdefy/api 7.0.0 → 7.2.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 (119) 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 +95 -21
  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 +163 -92
  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/mobile/buildBearerPlugin.js +45 -0
  21. package/dist/routes/auth/mobile/buildOneTimeTokenPlugin.js +50 -0
  22. package/dist/routes/auth/mobile/createCodeVerifierCheck.js +57 -0
  23. package/dist/routes/auth/mobile/createKnownDeviceHook.js +76 -0
  24. package/dist/routes/auth/mobile/createMobileAuthPageResponse.js +79 -0
  25. package/dist/routes/auth/mobile/createMobileSessionCreateHook.js +41 -0
  26. package/dist/routes/auth/mobile/createMobileSessionRefreshHook.js +40 -0
  27. package/dist/routes/auth/mobile/createMobileSignInCsrfToken.js +32 -0
  28. package/dist/routes/auth/mobile/createPhoneSession.js +59 -0
  29. package/dist/routes/auth/mobile/escapeHtml.js +26 -0
  30. package/dist/routes/auth/mobile/getCodeHolderIdentifier.js +20 -0
  31. package/dist/routes/auth/mobile/getKnownDeviceIdentifier.js +20 -0
  32. package/dist/routes/auth/mobile/getMobileSessionExpiry.js +18 -0
  33. package/dist/routes/auth/mobile/getMobileSignInReturnUrl.js +31 -0
  34. package/dist/routes/auth/mobile/getOneTimeTokenIdentifiers.js +26 -0
  35. package/dist/routes/auth/mobile/handleMobileSignIn.js +303 -0
  36. package/dist/routes/auth/mobile/handleMobileSignInCallback.js +30 -0
  37. package/dist/routes/auth/mobile/isNativeAuthRequest.js +33 -0
  38. package/dist/routes/auth/mobile/matchesCodeChallenge.js +29 -0
  39. package/dist/routes/auth/mobile/mintOneTimeToken.js +41 -0
  40. package/dist/routes/auth/mobile/readDeviceKeyHash.js +34 -0
  41. package/dist/routes/auth/mobile/readMobileSignInParams.js +90 -0
  42. package/dist/routes/auth/mobile/sha256Base64Url.js +22 -0
  43. package/dist/routes/auth/mobile/storeCodeChallenge.js +29 -0
  44. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +43 -6
  45. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +7 -2
  46. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +41 -189
  47. package/dist/routes/auth/organizations/createAdmissionGateHook.js +5 -5
  48. package/dist/routes/auth/organizations/createBeforeCreateInvitationHook.js +62 -0
  49. package/dist/routes/auth/organizations/createBeforeUpdateMemberRoleHook.js +45 -0
  50. package/dist/routes/auth/organizations/createSuspendedMemberGate.js +146 -0
  51. package/dist/routes/auth/organizations/createSuspendedOrganizationsFilter.js +44 -0
  52. package/dist/routes/auth/organizations/ensureAuthIndexes.js +11 -10
  53. package/dist/routes/auth/organizations/getOrganizationBinding.js +4 -2
  54. package/dist/routes/auth/organizations/isActiveMember.js +26 -0
  55. package/dist/routes/auth/organizations/isEmailAdmitted.js +12 -5
  56. package/dist/routes/auth/organizations/memberRowsLimit.js +19 -0
  57. package/dist/routes/auth/organizations/mintOrganization.js +258 -0
  58. package/dist/routes/auth/organizations/organizationAccessControl.js +5 -1
  59. package/dist/routes/auth/organizations/provisionOrganization.js +117 -0
  60. package/dist/routes/auth/organizations/readSuspendedOrganizationIds.js +36 -0
  61. package/dist/routes/auth/requestHooks/buildRequestHooks.js +72 -0
  62. package/dist/routes/auth/requestHooks/createEmailCodeHolderGate.js +58 -0
  63. package/dist/routes/auth/requestHooks/createEmailSendLimit.js +116 -0
  64. package/dist/routes/auth/requestHooks/createSignInRefusedRedirectHook.js +75 -0
  65. package/dist/routes/auth/requestHooks/holdEmailCode.js +80 -0
  66. package/dist/routes/auth/requestHooks/reserveSendSlot.js +70 -0
  67. package/dist/routes/auth/runReportingFaults.js +32 -0
  68. package/dist/routes/connections/resolveUnwalledReach.js +14 -16
  69. package/dist/routes/endpoints/callEndpoint.js +6 -3
  70. package/dist/routes/endpoints/control/controlFor.js +9 -6
  71. package/dist/routes/endpoints/control/controlIf.js +8 -3
  72. package/dist/routes/endpoints/control/controlLog.js +3 -1
  73. package/dist/routes/endpoints/control/controlParallelFor.js +9 -6
  74. package/dist/routes/endpoints/control/controlReturn.js +3 -2
  75. package/dist/routes/endpoints/control/controlSetState.js +1 -1
  76. package/dist/routes/endpoints/control/controlSwitch.js +6 -3
  77. package/dist/routes/endpoints/control/controlWhile.js +6 -3
  78. package/dist/routes/endpoints/createLinkAnswer.js +76 -0
  79. package/dist/routes/endpoints/dispatchDetached.js +38 -0
  80. package/dist/routes/endpoints/forwardScheduledEndpoint.js +32 -11
  81. package/dist/routes/endpoints/handleAgentCall.js +1 -1
  82. package/dist/routes/endpoints/handleAuthStep.js +19 -4
  83. package/dist/routes/endpoints/handleEndpointCall.js +6 -4
  84. package/dist/routes/endpoints/handleRequest.js +3 -2
  85. package/dist/routes/endpoints/handleValidateDynamic.js +1 -1
  86. package/dist/routes/endpoints/matchLinkEndpoint.js +30 -0
  87. package/dist/routes/endpoints/runLinkEndpoint.js +148 -0
  88. package/dist/routes/endpoints/runRoutine.js +5 -5
  89. package/dist/routes/endpoints/scheduleBackground.js +13 -11
  90. package/dist/routes/endpoints/test/runTest.js +30 -11
  91. package/dist/routes/mcp/createMcpServer.js +2 -7
  92. package/dist/routes/mcp/runAfterToolCall.js +9 -3
  93. package/dist/routes/mobile/createAppleAppSiteAssociation.js +51 -0
  94. package/dist/routes/mobile/createAssetLinks.js +38 -0
  95. package/dist/routes/mobile/filterMobileMenus.js +31 -0
  96. package/dist/routes/mobile/getMobileAppEvents.js +23 -0
  97. package/dist/routes/mobile/getMobileRootConfig.js +109 -0
  98. package/dist/routes/mobile/getOpenablePageIds.js +21 -0
  99. package/dist/routes/page/dynamic/policy/checkAction.js +67 -2
  100. package/dist/routes/page/dynamic/policy/checkEvents.js +8 -2
  101. package/dist/routes/page/dynamic/policy/checkPolicy.js +86 -6
  102. package/dist/routes/page/dynamic/policy/checkValue.js +97 -6
  103. package/dist/routes/page/dynamic/policy/collectSchemaKinds.js +173 -0
  104. package/dist/routes/page/dynamic/policy/findDataRows.js +94 -0
  105. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +24 -12
  106. package/dist/routes/page/dynamic/policy/findHtmlUrls.js +64 -0
  107. package/dist/routes/page/dynamic/policy/overlapsStatePath.js +28 -0
  108. package/dist/routes/page/dynamic/resolveDynamicContent.js +23 -17
  109. package/dist/routes/page/getPageConfig.js +25 -1
  110. package/dist/routes/request/callRequestResolver.js +29 -36
  111. package/dist/routes/request/stampTypedError.js +37 -0
  112. package/dist/routes/request/summarisedError.js +62 -0
  113. package/dist/routes/request/wrapResolverError.js +61 -0
  114. package/dist/routes/websocket/createChannelRegistry.js +13 -15
  115. package/dist/routes/websocket/createWebSocketConnection.js +5 -8
  116. package/dist/test/createMemoryAuth.js +125 -0
  117. package/package.json +20 -22
  118. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +0 -117
  119. package/dist/routes/request/maskCredentialProperties.js +0 -34
@@ -0,0 +1,109 @@
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 filterMobileMenus from './filterMobileMenus.js';
17
+ import getLowdefyGlobal from '../rootConfig/getLowdefyGlobal.js';
18
+ import getLowdefyI18n from '../rootConfig/getLowdefyI18n.js';
19
+ import getMobileAppEvents from './getMobileAppEvents.js';
20
+ import getOpenablePageIds from './getOpenablePageIds.js';
21
+ function getShellAuth({ auth, config }) {
22
+ if (type.isNone(auth)) {
23
+ return null;
24
+ }
25
+ const { emailCode, unlock, unlockAfter, sharedDevice } = config.auth;
26
+ return {
27
+ emailCode,
28
+ unlock,
29
+ unlockAfter,
30
+ sharedDevice
31
+ };
32
+ }
33
+ // What a shell syncs on start: the mobile frame, the index of the pages this
34
+ // caller may open with each page's hash and typesKey, the type set of each of
35
+ // those keys, minShellVersion, the theme ({ darkMode, light, dark }, antd's
36
+ // computed tokens per mode) and the Tailwind class map. Menu icons carry their
37
+ // node data.
38
+ //
39
+ // The app's identity (lowdefyApp, with the buildId a shell stamps its page
40
+ // requests with), its global and its i18n are what a shell's engine starts
41
+ // from, as the web root config gives them. Its app events are mobile.events,
42
+ // not the web app's events, which may use web-only actions. Their _js comes as
43
+ // _jsEntries, module text a shell evaluates, as a mobile page's does.
44
+ //
45
+ // The dev build writes the page index without hashes or typesKeys, and no type
46
+ // sets: the dev server builds pages on demand. Its class map holds the classes
47
+ // of the pages the skeleton build compiles; a page built on request carries
48
+ // its own classes' entries.
49
+ //
50
+ // auth is the mobile.auth a shell signs in and locks by (emailCode, unlock,
51
+ // unlockAfter, sharedDevice), or null for an app without auth, which a shell
52
+ // opens with no sign-in screen. sessionExpiresIn is the server's alone.
53
+ //
54
+ // notifications, share, widgets, shortcuts and background drive the shell's
55
+ // native features: push registration endpoints and notification categories,
56
+ // the share page, widget sources, icon quick actions and background fetch.
57
+ //
58
+ // Returns null for an app without a mobile key: no shell opens it.
59
+ async function getMobileRootConfig(context) {
60
+ const [config, pageIndex, typeSets, theme, classMap, appJs, openablePageIds, events, lowdefyGlobal, i18n] = await Promise.all([
61
+ context.readConfigFile('mobile/config.json'),
62
+ context.readConfigFile('mobile/pageIndex.json'),
63
+ context.readConfigFile('mobile/typeSets.json'),
64
+ context.readConfigFile('mobile/theme.json'),
65
+ context.readConfigFile('mobile/classMap.json'),
66
+ context.readConfigFile('mobile/appJs.json'),
67
+ getOpenablePageIds(context),
68
+ getMobileAppEvents(context),
69
+ getLowdefyGlobal(context),
70
+ getLowdefyI18n(context)
71
+ ]);
72
+ if (Object.keys(config).length === 0) {
73
+ return null;
74
+ }
75
+ const openablePageIndex = pageIndex.filter((entry)=>openablePageIds.has(entry.pageId));
76
+ const openableTypeSets = {};
77
+ openablePageIndex.forEach((entry)=>{
78
+ if (typeSets[entry.typesKey]) {
79
+ openableTypeSets[entry.typesKey] = typeSets[entry.typesKey];
80
+ }
81
+ });
82
+ return {
83
+ _jsEntries: appJs.jsEntries,
84
+ auth: getShellAuth({
85
+ auth: context.auth,
86
+ config
87
+ }),
88
+ events,
89
+ homePageId: config.homePageId,
90
+ i18n,
91
+ lowdefyApp: context.appMeta,
92
+ lowdefyGlobal,
93
+ minShellVersion: config.minShellVersion,
94
+ menus: filterMobileMenus({
95
+ menus: config.menus,
96
+ openablePageIds
97
+ }),
98
+ pageIndex: openablePageIndex,
99
+ typeSets: openableTypeSets,
100
+ theme,
101
+ classMap,
102
+ notifications: config.notifications,
103
+ share: config.share,
104
+ widgets: config.widgets,
105
+ shortcuts: config.shortcuts,
106
+ background: config.background
107
+ };
108
+ }
109
+ export default getMobileRootConfig;
@@ -0,0 +1,21 @@
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
+ */ // The ids of the pages this caller may open, filtered as getPagePaths and the
16
+ // web menus are: only a "deny" outcome hides a page.
17
+ async function getOpenablePageIds(context) {
18
+ const routes = await context.readConfigFile('routes.json');
19
+ return new Set(routes.filter((route)=>context.authorizeOutcome(route) !== 'deny').map((route)=>route.pageId));
20
+ }
21
+ export default getOpenablePageIds;
@@ -16,6 +16,7 @@
16
16
  import { getPossibleOperators } from '@lowdefy/operators';
17
17
  import checkValue from './checkValue.js';
18
18
  import isUnderState from './isUnderState.js';
19
+ import overlapsStatePath from './overlapsStatePath.js';
19
20
  function isLiteralObject({ value, walk }) {
20
21
  return type.isObject(value) && getPossibleOperators({
21
22
  value,
@@ -156,6 +157,59 @@ function checkSetState({ params, path, walk }) {
156
157
  }
157
158
  });
158
159
  }
160
+ // A CallAPI's params are sent to the server and an action's skip is read as a
161
+ // condition, so a _state read in them draws nothing.
162
+ function checkActionValue({ action, path, walk }) {
163
+ Object.keys(action).forEach((key)=>{
164
+ if (key.startsWith('~')) return;
165
+ const undrawn = key === 'skip' || key === 'params' && action.type === 'CallAPI';
166
+ checkValue({
167
+ value: action[key],
168
+ key,
169
+ path: `${path}.${key}`,
170
+ walk: undrawn ? {
171
+ ...walk,
172
+ undrawn: true
173
+ } : walk
174
+ });
175
+ });
176
+ }
177
+ // SetState values under the policy's state are data: the page around the
178
+ // Dynamic block owns that state and treats it as input, and no block property
179
+ // can read it back (properties are literal), so only the operator rules apply.
180
+ // A content _state read that would draw a data key is refused at the end of
181
+ // the walk (checkPolicy). Without a state path the content may write any page
182
+ // state, which the page may draw, so every value keeps every check. So does a
183
+ // value bound to a content input whose value is an object (walk.objectValueIds:
184
+ // a rich text editor, an upload, a table input), which draws it as markup,
185
+ // links or images. checkSetState has judged the keys.
186
+ function checkSetStateValues({ action, path, walk }) {
187
+ const { params, ...rest } = action;
188
+ checkActionValue({
189
+ action: rest,
190
+ path,
191
+ walk
192
+ });
193
+ Object.keys(params).forEach((key)=>{
194
+ if (key.startsWith('~')) return;
195
+ const isData = !type.isNone(walk.policy.state) && !walk.objectValueIds.some((id)=>overlapsStatePath({
196
+ key,
197
+ id
198
+ }));
199
+ if (isData) {
200
+ walk.dataStateKeys.push(key);
201
+ }
202
+ checkValue({
203
+ value: params[key],
204
+ key,
205
+ path: `${path}.params.${key}`,
206
+ walk: isData ? {
207
+ ...walk,
208
+ isData: true
209
+ } : walk
210
+ });
211
+ });
212
+ }
159
213
  const ACTION_RULES = {
160
214
  CallAPI: checkCallApi,
161
215
  Link: checkLink,
@@ -195,8 +249,19 @@ function checkAction({ action, path, walk }) {
195
249
  path: `${path}.params`,
196
250
  walk
197
251
  });
198
- checkValue({
199
- value: action,
252
+ if (action.type === 'SetState' && isLiteralObject({
253
+ value: action.params,
254
+ walk
255
+ })) {
256
+ checkSetStateValues({
257
+ action,
258
+ path,
259
+ walk
260
+ });
261
+ return;
262
+ }
263
+ checkActionValue({
264
+ action,
200
265
  path,
201
266
  walk
202
267
  });
@@ -43,7 +43,10 @@ function checkActionList({ actions, path, walk }) {
43
43
  checkValue({
44
44
  value: item[':if'],
45
45
  path: `${itemPath}.:if`,
46
- walk
46
+ walk: {
47
+ ...walk,
48
+ undrawn: true
49
+ }
47
50
  });
48
51
  count += checkActionList({
49
52
  actions: item[':then'] ?? [],
@@ -71,7 +74,10 @@ function checkActionList({ actions, path, walk }) {
71
74
  checkValue({
72
75
  value: caseObject?.[':case'],
73
76
  path: `${casePath}.:case`,
74
- walk
77
+ walk: {
78
+ ...walk,
79
+ undrawn: true
80
+ }
75
81
  });
76
82
  count += checkActionList({
77
83
  actions: caseObject?.[':then'] ?? [],
@@ -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,