@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
@@ -0,0 +1,28 @@
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
+ */ // Whether two state paths name the same value or one holds the other. A "$"
16
+ // segment (an id inside a list) matches any segment.
17
+ function overlapsStatePath({ key, id }) {
18
+ const keyParts = key.split('.');
19
+ const idParts = id.split('.');
20
+ const length = Math.min(keyParts.length, idParts.length);
21
+ for(let index = 0; index < length; index += 1){
22
+ const keyPart = keyParts[index];
23
+ const idPart = idParts[index];
24
+ if (keyPart !== idPart && keyPart !== '$' && idPart !== '$') return false;
25
+ }
26
+ return true;
27
+ }
28
+ export default overlapsStatePath;
@@ -13,7 +13,7 @@
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 { ConfigError } from '@lowdefy/errors';
16
+ import { ConfigError, isExpectedError } from '@lowdefy/errors';
17
17
  import createEvaluateOperators from '../../../context/createEvaluateOperators.js';
18
18
  import invokeEndpoint from '../../endpoints/invokeEndpoint.js';
19
19
  import checkDynamicContent from './checkDynamicContent.js';
@@ -65,9 +65,9 @@ async function resolveDynamicBlock(context, { block, depth, shared }) {
65
65
  // blocks of a ValidateDynamic step that passed with this policy may come
66
66
  // back as config, and the policy is checked again on the final content.
67
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.
68
+ // An error the routine returns was logged and marked handled where it was raised
69
+ // (a failed ValidateDynamic step, a :reject, a :throw) or by runRoutine: an
70
+ // expected outcome as a warning, a fault through handleError.
71
71
  let loggedByRoutine = false;
72
72
  try {
73
73
  if (depth >= MAX_DYNAMIC_DEPTH) {
@@ -94,7 +94,7 @@ async function resolveDynamicBlock(context, { block, depth, shared }) {
94
94
  'error',
95
95
  'reject'
96
96
  ].includes(status)) {
97
- loggedByRoutine = error?.name === 'UserError' && error.handled === true;
97
+ loggedByRoutine = error?.handled === true;
98
98
  throw error ?? new ConfigError(`Dynamic block "${block.blockId}" on page "${shared.pageId}" endpoint "${endpointId}" failed with status "${status}".`, {
99
99
  configKey: block['~k']
100
100
  });
@@ -156,19 +156,25 @@ async function resolveDynamicBlock(context, { block, depth, shared }) {
156
156
  });
157
157
  }
158
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);
159
+ if (isExpectedError(error)) {
160
+ logger.warn({
161
+ event: 'dynamic_block_error',
162
+ blockId: block.blockId,
163
+ endpointId,
164
+ pageId: shared.pageId,
165
+ err: error
166
+ }, `Dynamic block "${block.blockId}" on page "${shared.pageId}" failed to resolve: ${error.message}`);
170
167
  } else {
171
- logger.error(entry, message);
168
+ // The fallback renders, but the failure is a fault: it is located at the Dynamic block
169
+ // and reported like any other.
170
+ if (error instanceof Object && !error.configKey) {
171
+ error.configKey = block['~k'];
172
+ }
173
+ // The log line and the Sentry tags name the block that fell back.
174
+ if (error instanceof Object && type.isNone(error.blockId)) {
175
+ error.blockId = block.blockId;
176
+ }
177
+ await context.handleError(error);
172
178
  }
173
179
  }
174
180
  const fallbackBlocks = block.slots?.fallback?.blocks ?? [];
@@ -32,11 +32,24 @@ import resolveDynamicContent from './dynamic/resolveDynamicContent.js';
32
32
  // means you are signed in - and every app's 404 page stops needing to serve a
33
33
  // signed-out visitor who was refused a protected page.
34
34
  //
35
+ // - wrong_surface: the page is for the other surface. A shell (surface
36
+ // "mobile", sent as x-lowdefy-shell) opens only pages whose target is mobile
37
+ // or both; a browser (surface "web") never opens a mobile-only page. Checked
38
+ // once access is allowed, so the gate never reveals a page the caller may not
39
+ // open. It serves the user's experience, not security: the header is set by
40
+ // the client, and page access stays with auth.pages.
41
+ //
35
42
  // The default is a build-resolved boolean, coarser than the glob lists that
36
43
  // produced it on purpose: an id absent from the build could still match a
37
44
  // declared pattern, and matching globs on the request path to change the answer
38
45
  // for URLs that are wrong anyway is a cost the artifact exists to avoid.
39
- async function getPageConfig(context, { path, urlQuery }) {
46
+ function servesSurface({ target, surface }) {
47
+ if (surface === 'mobile') {
48
+ return target === 'mobile' || target === 'both';
49
+ }
50
+ return target !== 'mobile';
51
+ }
52
+ async function getPageConfig(context, { path, urlQuery, surface = 'web' }) {
40
53
  const routes = await context.readConfigFile('routes.json');
41
54
  const match = matchPagePath({
42
55
  routes,
@@ -60,6 +73,17 @@ async function getPageConfig(context, { path, urlQuery }) {
60
73
  if (outcome === 'allow') {
61
74
  // eslint-disable-next-line no-unused-vars
62
75
  const { auth, ...rest } = pageConfig;
76
+ if (!servesSurface({
77
+ target: rest.target,
78
+ surface
79
+ })) {
80
+ return {
81
+ status: 'wrong_surface',
82
+ pageId,
83
+ pathParams,
84
+ surface: rest.target
85
+ };
86
+ }
63
87
  if (rest.dynamic !== true) {
64
88
  // Use serializer.serialize to ensure ~k keys (non-enumerable after deserialize)
65
89
  // are made enumerable again for JSON transfer to client
@@ -12,11 +12,12 @@
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 { RequestError, ServiceError, UserError } from '@lowdefy/errors';
15
+ */ import { UserError } from '@lowdefy/errors';
16
16
  import getCurrentEnvironment from '../../context/getCurrentEnvironment.js';
17
17
  import createWalledResolver from './createWalledResolver.js';
18
18
  import invokeEndpoint from '../endpoints/invokeEndpoint.js';
19
- import maskCredentialProperties from './maskCredentialProperties.js';
19
+ import stampTypedError from './stampTypedError.js';
20
+ import wrapResolverError from './wrapResolverError.js';
20
21
  async function callRequestResolver(context, { agent = null, connectionProperties, endpointDepth, requestConfig, requestProperties, requestResolver, routineContext, tenant, tenantGuard }) {
21
22
  const { blockId, endpointId, logger, pageId, payload, signal } = context;
22
23
  // stepId for endpoint steps (after build), requestId for page requests
@@ -87,13 +88,24 @@ async function callRequestResolver(context, { agent = null, connectionProperties
87
88
  });
88
89
  return response;
89
90
  } catch (error) {
90
- // Add configKey to any error for location tracing
91
- if (!error.configKey) {
91
+ // Add configKey to any error for location tracing. A thrown string or null takes no
92
+ // property, and the TypeError assigning one raises would quote the string.
93
+ if (error instanceof Object && !error.configKey) {
92
94
  error.configKey = requestConfig['~k'];
93
95
  }
94
- // Lowdefy errors pass through unchanged — re-wrapping every boundary would
95
- // nest causes and truncate the deepest (most informative) frame.
96
- if (error.isLowdefyError) {
96
+ // stepId, not requestId: on an error requestId is the HTTP request's id (context.rid)
97
+ // everywhere else.
98
+ const fields = {
99
+ endpointId: requestConfig.endpointId ?? endpointId,
100
+ stepId: stepOrRequestId,
101
+ connectionId: requestConfig.connectionId
102
+ };
103
+ // Lowdefy errors are not re-wrapped - re-wrapping every boundary would nest causes and
104
+ // truncate the deepest (most informative) frame.
105
+ if (error?.isLowdefyError) {
106
+ stampTypedError(error, {
107
+ fields
108
+ });
97
109
  logger.debug({
98
110
  params: {
99
111
  id: stepOrRequestId,
@@ -105,7 +117,7 @@ async function callRequestResolver(context, { agent = null, connectionProperties
105
117
  }
106
118
  // The client left before the resolver finished and the resolver stopped on the
107
119
  // signal: the cancellation is the caller's doing, not a fault in the request.
108
- if (signal?.reason?.name === 'AbortError' && error.name === 'AbortError') {
120
+ if (signal?.reason?.name === 'AbortError' && error?.name === 'AbortError') {
109
121
  const cancelled = new UserError(signal.reason.message, {
110
122
  cause: error
111
123
  });
@@ -118,41 +130,22 @@ async function callRequestResolver(context, { agent = null, connectionProperties
118
130
  }, cancelled.message);
119
131
  throw cancelled;
120
132
  }
121
- // Check if this is a service error (network, timeout, 5xx, 429)
122
- if (ServiceError.isServiceError(error)) {
123
- const serviceError = new ServiceError(undefined, {
124
- cause: error,
125
- service: requestConfig.connectionId,
126
- configKey: requestConfig['~k']
127
- });
128
- logger.debug({
129
- params: {
130
- id: stepOrRequestId,
131
- type: requestConfig.type
132
- },
133
- err: serviceError
134
- }, serviceError.message);
135
- throw serviceError;
136
- }
137
- // Wrap other errors in RequestError (request/connection logic error)
138
- const requestError = new RequestError(error.message, {
139
- cause: error,
140
- typeName: requestConfig.type,
141
- received: maskCredentialProperties({
142
- requestProperties,
143
- requestResolver
144
- }),
133
+ // A ServiceError for a network failure, timeout, 5xx or 429; a RequestError otherwise.
134
+ const wrapped = wrapResolverError(error, {
135
+ configKey: requestConfig['~k'],
136
+ fields,
145
137
  location: `${requestConfig.connectionId}/${stepOrRequestId}`,
146
- configKey: requestConfig['~k']
138
+ service: requestConfig.connectionId,
139
+ typeName: requestConfig.type
147
140
  });
148
141
  logger.debug({
149
142
  params: {
150
143
  id: stepOrRequestId,
151
144
  type: requestConfig.type
152
145
  },
153
- err: requestError
154
- }, requestError.message);
155
- throw requestError;
146
+ err: wrapped
147
+ }, wrapped.message);
148
+ throw wrapped;
156
149
  }
157
150
  }
158
151
  export default callRequestResolver;
@@ -0,0 +1,37 @@
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 summarisedError from './summarisedError.js';
16
+ // A connection that already typed its error (a ServiceError on a time limit, a ConfigError)
17
+ // passes through the interface layer without a new wrapper, which would nest causes. It still
18
+ // leaves with the step's ids and its cause summarised, like a wrapped error: the cause is the
19
+ // connection's own error, which can quote every document of a failed bulk write. Ids an inner
20
+ // step already set (an error from a nested CallApi) are kept, since they name where it failed,
21
+ // and a cause already summarised there keeps the devCause it was given.
22
+ function stampTypedError(error, { fields }) {
23
+ Object.entries(fields).forEach(([key, value])=>{
24
+ if (error[key] === undefined) {
25
+ error[key] = value;
26
+ }
27
+ });
28
+ if (error.devCause !== undefined || typeof error.cause?.message !== 'string') {
29
+ return;
30
+ }
31
+ Object.defineProperty(error, 'devCause', {
32
+ value: error.cause,
33
+ configurable: true
34
+ });
35
+ error.cause = summarisedError(error.cause);
36
+ }
37
+ export default stampTypedError;
@@ -0,0 +1,62 @@
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 { errorSummaryForLog, readErrorCodes } from '@lowdefy/errors';
16
+ // Stack frames name code, never data, so they are kept. The stack's opening lines repeat the
17
+ // message, so they are rebuilt from the summary's; they are dropped by count, not by shape,
18
+ // since a message can hold a line that looks like a frame.
19
+ function stackFrames(error) {
20
+ if (typeof error.stack !== 'string') return [];
21
+ const headerLineCount = String(error).split('\n').length;
22
+ return error.stack.split('\n').slice(headerLineCount).filter((line)=>/^\s+at /.test(line));
23
+ }
24
+ // An error from another realm, such as a DOMException in a VM context, fails instanceof Error.
25
+ function isError(value) {
26
+ if (value instanceof Error) return true;
27
+ return typeof value === 'object' && value !== null && typeof value.stack === 'string' && typeof value.message === 'string';
28
+ }
29
+ function fromSummary(summary, original) {
30
+ const message = summary.message ?? `${summary.name} (message withheld from logs).`;
31
+ const error = new Error(message);
32
+ error.name = summary.name;
33
+ error.stack = [
34
+ `${summary.name}: ${message}`,
35
+ ...stackFrames(original)
36
+ ].join('\n');
37
+ if (summary.code !== undefined) error.code = summary.code;
38
+ if (summary.statusCode !== undefined) error.statusCode = summary.statusCode;
39
+ const cause = original.lastError ?? original.cause;
40
+ if (summary.cause !== undefined && isError(cause)) {
41
+ error.cause = fromSummary(summary.cause, cause);
42
+ }
43
+ return error;
44
+ }
45
+ // A request resolver's error rebuilt from its log summary: the name, code, status code and
46
+ // message cut to 500 characters, with the stack frames, for the error and three causes. A
47
+ // connection's error can carry the request's inputs in its other fields - a MongoDB write
48
+ // error the document it rejected, an HTTP client's error the request body - and every log
49
+ // and error report writes the error it is given, so none of them is kept.
50
+ function summarisedError(error) {
51
+ if (!isError(error)) {
52
+ const { code, statusCode } = readErrorCodes(error);
53
+ return fromSummary({
54
+ name: 'Error',
55
+ message: `Request resolver threw a value of type ${typeof error}, not an error.`,
56
+ code,
57
+ statusCode
58
+ }, {});
59
+ }
60
+ return fromSummary(errorSummaryForLog(error), error);
61
+ }
62
+ export default summarisedError;
@@ -0,0 +1,61 @@
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 { RequestError, ServiceError } from '@lowdefy/errors';
17
+ import summarisedError from './summarisedError.js';
18
+ // The interface layer's wrap of a connection's error, for a request step and a websocket source
19
+ // alike. The error that leaves here is logged whole at error level and sent to Sentry, so it
20
+ // carries ids (`fields`) and the connection's error summarised - never the evaluated properties
21
+ // (an agent chat's save-thread step holds the whole thread there) or the connection's error
22
+ // itself, which can embed the document it rejected. The dev tools still show that error: it is
23
+ // kept as devCause, which is not enumerable, so no log or error report walks it, and only the dev
24
+ // error payload reads it.
25
+ function wrapResolverError(error, { configKey, fields, location, service, typeName }) {
26
+ const cause = summarisedError(error);
27
+ let wrapped;
28
+ if (ServiceError.isServiceError(error)) {
29
+ // ServiceError reads the code, HTTP status, Retry-After and hint from its cause, wherever the
30
+ // client put them, so it is built over the connection's error with only the message cut, then
31
+ // given the summary as its cause. A Proxy, not a copy: a DOMException's fields are getters
32
+ // that only work on the exception itself.
33
+ wrapped = new ServiceError(undefined, {
34
+ cause: new Proxy(error, {
35
+ get: (target, key)=>key === 'message' ? cause.message : target[key]
36
+ }),
37
+ service,
38
+ configKey
39
+ });
40
+ wrapped.cause = cause;
41
+ } else {
42
+ wrapped = new RequestError(cause.message, {
43
+ cause,
44
+ typeName,
45
+ location,
46
+ configKey
47
+ });
48
+ // A connection that refuses a request says what to do about it in `hint` (a MongoDB
49
+ // duplicate key), which the summary does not keep.
50
+ if (type.isString(error?.hint)) {
51
+ wrapped.hint = error.hint;
52
+ }
53
+ }
54
+ Object.assign(wrapped, fields);
55
+ Object.defineProperty(wrapped, 'devCause', {
56
+ value: error,
57
+ configurable: true
58
+ });
59
+ return wrapped;
60
+ }
61
+ export default wrapResolverError;
@@ -0,0 +1,81 @@
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 { AuthorizationError, isExpectedError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ import invokeEndpoint from '../endpoints/invokeEndpoint.js';
18
+ // Role rules decide who may hear a channel at all. A channel whose payload
19
+ // names a record also needs to know whether this subscriber may see that
20
+ // record, which only the app's own data can answer - so the websocket's check
21
+ // endpoint runs as the subscriber and must answer exactly true. It runs on
22
+ // every subscribe and publish, and again on the connection's periodic caller
23
+ // check while a subscription stays open, so revoked access ends it.
24
+ //
25
+ // Every refusal reads as a missing websocket, as a role refusal does
26
+ // (authorizeWebsocket), so a subscriber can not tell a record it may not see
27
+ // from a channel that does not exist.
28
+ async function checkWebsocketAccess(context, { payload, websocketConfig }) {
29
+ const { check, websocketId } = websocketConfig;
30
+ if (type.isNone(check)) {
31
+ return;
32
+ }
33
+ const { logger } = context;
34
+ let allowed = false;
35
+ try {
36
+ const checkPayload = type.isNone(check.payload) ? payload : context.evaluateOperators({
37
+ input: check.payload,
38
+ location: websocketId,
39
+ payload,
40
+ state: {},
41
+ steps: {}
42
+ });
43
+ // The subscriber's client built the payload, so a payload the endpoint's
44
+ // schema refuses is that caller's mistake, as for a CallAPI with no page
45
+ // (validatePayload), not a fault to log at error level.
46
+ const result = await invokeEndpoint(context, {
47
+ endpointId: check.endpointId,
48
+ payload: checkPayload,
49
+ endpointDepth: 0,
50
+ outsideCaller: true
51
+ });
52
+ // A routine that errored was logged by runRoutine.
53
+ allowed = result.status === 'return' && result.response === true;
54
+ logger.debug({
55
+ event: 'debug_websocket_check',
56
+ websocketId,
57
+ allowed,
58
+ status: result.status
59
+ });
60
+ } catch (error) {
61
+ // The endpoint refusing the caller is a refusal like any other. Anything
62
+ // else is a fault in the check's config or the endpoint, which the
63
+ // developer needs to see; the subscriber is refused either way.
64
+ if (isExpectedError(error)) {
65
+ logger.debug({
66
+ event: 'debug_websocket_check_refused',
67
+ websocketId,
68
+ err: error
69
+ });
70
+ } else {
71
+ if (error instanceof Object && type.isNone(error.configKey)) {
72
+ error.configKey = check['~k'] ?? websocketConfig['~k'];
73
+ }
74
+ await context.handleError(error);
75
+ }
76
+ }
77
+ if (!allowed) {
78
+ throw new AuthorizationError(`Websocket "${websocketId}" does not exist.`);
79
+ }
80
+ }
81
+ export default checkWebsocketAccess;
@@ -13,10 +13,13 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import crypto from 'crypto';
16
- import { serializer } from '@lowdefy/helpers';
17
- import { ConfigError, PluginError, ServiceError } from '@lowdefy/errors';
16
+ import { serializer, type } from '@lowdefy/helpers';
17
+ import { ConfigError } from '@lowdefy/errors';
18
+ import checkWebsocketAccess from './checkWebsocketAccess.js';
19
+ import createEvaluateOperators from '../../context/createEvaluateOperators.js';
18
20
  import createWireProjection from '../../response/createWireProjection.js';
19
21
  import prepareChannel from './prepareChannel.js';
22
+ import wrapResolverError from '../request/wrapResolverError.js';
20
23
  const MAX_RETRIES = 5;
21
24
  const RETRY_BASE_MS = 1000;
22
25
  const HEALTHY_RESET_MS = 60 * 1000;
@@ -27,6 +30,10 @@ const HEALTHY_RESET_MS = 60 * 1000;
27
30
  // last one leaves.
28
31
  function createChannelRegistry() {
29
32
  const channels = new Map();
33
+ // subscriber → (websocketId → { payload, websocketConfig }) for the open
34
+ // subscriptions whose websocket has a check, so the check can run again while
35
+ // they stay open (recheckAccess).
36
+ const checkedSubscriptions = new WeakMap();
30
37
  function getChannelKey({ connectionProperties, properties, tenant, websocketId }) {
31
38
  // The tenant verdict is part of the channel identity: two callers whose
32
39
  // evaluated properties are identical but whose organizations differ must
@@ -62,26 +69,23 @@ function createChannelRegistry() {
62
69
  }));
63
70
  });
64
71
  }
65
- function wrapResolverError({ channel, error }) {
72
+ // Wrapped like a request step's error: the evaluated properties stay out of it, and the
73
+ // source's own error is summarised, since both are logged and sent to Sentry.
74
+ function wrapSourceError({ channel, error }) {
66
75
  if (!error.configKey) {
67
76
  error.configKey = channel.websocketConfig['~k'];
68
77
  }
69
78
  if (error.isLowdefyError) {
70
79
  return error;
71
80
  }
72
- if (ServiceError.isServiceError(error)) {
73
- return new ServiceError(undefined, {
74
- cause: error,
75
- service: channel.websocketConfig.connectionId ?? channel.websocketConfig.type,
76
- configKey: channel.websocketConfig['~k']
77
- });
78
- }
79
- return new PluginError(error.message, {
80
- cause: error,
81
- typeName: channel.websocketConfig.type,
82
- received: channel.properties,
81
+ return wrapResolverError(error, {
82
+ configKey: channel.websocketConfig['~k'],
83
+ fields: {
84
+ connectionId: channel.websocketConfig.connectionId
85
+ },
83
86
  location: channel.websocketConfig.websocketId,
84
- configKey: channel.websocketConfig['~k']
87
+ service: channel.websocketConfig.connectionId ?? channel.websocketConfig.type,
88
+ typeName: channel.websocketConfig.type
85
89
  });
86
90
  }
87
91
  function removeChannel(channel) {
@@ -101,7 +105,7 @@ function createChannelRegistry() {
101
105
  }, error.message);
102
106
  return;
103
107
  }
104
- const wrapped = wrapResolverError({
108
+ const wrapped = wrapSourceError({
105
109
  channel,
106
110
  error
107
111
  });
@@ -180,9 +184,12 @@ function createChannelRegistry() {
180
184
  subscriber
181
185
  });
182
186
  }
187
+ // The client serializes the payload, as it does for a publish and a CallAPI,
188
+ // so properties and the check endpoint read Dates as Dates.
189
+ const deserializedPayload = serializer.deserialize(payload ?? {});
183
190
  const { connectionProperties, properties, tenant, websocketConfig, websocketResolver } = await prepareChannel(context, {
184
191
  websocketId,
185
- payload
192
+ payload: deserializedPayload
186
193
  });
187
194
  const key = getChannelKey({
188
195
  connectionProperties,
@@ -213,6 +220,15 @@ function createChannelRegistry() {
213
220
  }
214
221
  channel.subscribers.add(subscriber);
215
222
  subscriber.subscriptions.set(websocketId, key);
223
+ if (!type.isNone(websocketConfig.check)) {
224
+ if (!checkedSubscriptions.has(subscriber)) {
225
+ checkedSubscriptions.set(subscriber, new Map());
226
+ }
227
+ checkedSubscriptions.get(subscriber).set(websocketId, {
228
+ payload: deserializedPayload,
229
+ websocketConfig
230
+ });
231
+ }
216
232
  context.logger.debug({
217
233
  event: 'ws_subscribe',
218
234
  websocketId,
@@ -222,6 +238,7 @@ function createChannelRegistry() {
222
238
  function unsubscribe({ websocketId, subscriber }) {
223
239
  const key = subscriber.subscriptions.get(websocketId);
224
240
  subscriber.subscriptions.delete(websocketId);
241
+ checkedSubscriptions.get(subscriber)?.delete(websocketId);
225
242
  if (!key) {
226
243
  return;
227
244
  }
@@ -244,6 +261,32 @@ function createChannelRegistry() {
244
261
  });
245
262
  });
246
263
  }
264
+ function getCheckedWebsocketIds({ subscriber }) {
265
+ return [
266
+ ...checkedSubscriptions.get(subscriber)?.keys() ?? []
267
+ ];
268
+ }
269
+ // Access to a record can be revoked while a subscription to it stays open, so
270
+ // the connection runs the check again on its periodic caller check, with the
271
+ // payload and config the subscription was opened with. A refused
272
+ // subscription is closed and the refusal thrown for the caller to be told.
273
+ // The subscription may have been closed while this waited in its feed queue.
274
+ async function recheckAccess(context, { websocketId, subscriber }) {
275
+ const subscription = checkedSubscriptions.get(subscriber)?.get(websocketId);
276
+ if (type.isUndefined(subscription)) {
277
+ return;
278
+ }
279
+ context.evaluateOperators = createEvaluateOperators(context);
280
+ try {
281
+ await checkWebsocketAccess(context, subscription);
282
+ } catch (error) {
283
+ unsubscribe({
284
+ websocketId,
285
+ subscriber
286
+ });
287
+ throw error;
288
+ }
289
+ }
247
290
  async function publish(context, { websocketId, payload }) {
248
291
  // Publish identity is evaluated without a subscription payload — channels
249
292
  // that fragment on _payload/_user in properties are not publish targets.
@@ -283,7 +326,9 @@ function createChannelRegistry() {
283
326
  });
284
327
  }
285
328
  return {
329
+ getCheckedWebsocketIds,
286
330
  publish,
331
+ recheckAccess,
287
332
  subscribe,
288
333
  unsubscribe,
289
334
  unsubscribeAll,