@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
@@ -31,9 +31,10 @@ async function controlReturn(context, routineContext, { control }) {
31
31
  literalData
32
32
  });
33
33
  }
34
+ // No evaluated values: they can carry chat text or other personal information,
35
+ // which no log level may hold.
34
36
  context.logger.debug({
35
- event: 'debug_control_return',
36
- response
37
+ event: 'debug_control_return'
37
38
  });
38
39
  // :content_type sends a webhook's answer as text (createWebhookAnswer). The build allows it only
39
40
  // in a webhook endpoint, and only as text/plain.
@@ -24,7 +24,7 @@ function controlSetState(context, routineContext, { control }) {
24
24
  logger.debug({
25
25
  event: 'debug_control_set_state',
26
26
  input: control[':set_state'],
27
- evaluated: evaluatedSetState
27
+ keys: Object.keys(evaluatedSetState ?? {})
28
28
  });
29
29
  Object.entries(evaluatedSetState).forEach(([key, value])=>{
30
30
  try {
@@ -12,7 +12,8 @@
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 runRoutine from '../runRoutine.js';
15
+ */ import { ConfigError } from '@lowdefy/errors';
16
+ import runRoutine from '../runRoutine.js';
16
17
  import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
17
18
  async function controlSwitch(context, routineContext, { control }) {
18
19
  const { endpointId, logger } = context;
@@ -29,7 +30,7 @@ async function controlSwitch(context, routineContext, { control }) {
29
30
  event: 'debug_control_switch_case',
30
31
  case: {
31
32
  input: caseObj[':case'],
32
- evaluated: evaluatedCase
33
+ result: Boolean(evaluatedCase)
33
34
  }
34
35
  });
35
36
  if (evaluatedCase) {
@@ -37,7 +38,9 @@ async function controlSwitch(context, routineContext, { control }) {
37
38
  event: 'debug_control_switch_run_then'
38
39
  });
39
40
  if (!caseObj[':then']) {
40
- throw new Error(`Invalid :switch :case in endpoint "${endpointId}" - missing :then.`);
41
+ throw new ConfigError(`Invalid :switch :case in endpoint "${endpointId}" - missing :then.`, {
42
+ configKey: caseObj['~k'] ?? control['~k']
43
+ });
41
44
  }
42
45
  return runRoutine(context, routineContext, {
43
46
  routine: caseObj[':then']
@@ -12,12 +12,15 @@
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 evaluateRoutineOperators from '../evaluateRoutineOperators.js';
15
+ */ import { ConfigError } from '@lowdefy/errors';
16
+ import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
16
17
  import runRoutine from '../runRoutine.js';
17
18
  async function controlWhile(context, routineContext, { control }) {
18
19
  const { endpointId, logger } = context;
19
20
  if (!control[':do']) {
20
- throw new Error(`Invalid :while in endpoint "${endpointId}" - missing :do.`);
21
+ throw new ConfigError(`Invalid :while in endpoint "${endpointId}" - missing :do.`, {
22
+ configKey: control['~k']
23
+ });
21
24
  }
22
25
  // No array index is pushed onto routineContext.arrayIndices. A :while has no item to
23
26
  // index, so each iteration overwrites the previous iteration's step results, and
@@ -34,7 +37,7 @@ async function controlWhile(context, routineContext, { control }) {
34
37
  event: 'debug_control_while',
35
38
  condition: {
36
39
  input: control[':while'],
37
- evaluated
40
+ result: Boolean(evaluated)
38
41
  },
39
42
  iteration
40
43
  });
@@ -0,0 +1,76 @@
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 { ConfigError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ // A control character in a Location header would split or break the response.
18
+ function hasControlCharacter(value) {
19
+ return Array.from(value).some((character)=>{
20
+ const code = character.charCodeAt(0);
21
+ return code < 32 || code === 127;
22
+ });
23
+ }
24
+ const absoluteUrlPattern = /^https?:\/\/[^/]/i;
25
+ // A path on this origin. "//host" and "/\host" are refused: a browser reads both as another host.
26
+ function isOriginPath(value) {
27
+ return value.startsWith('/') && !value.startsWith('//') && !value.startsWith('/\\');
28
+ }
29
+ function isLinkTarget(value) {
30
+ if (!type.isString(value) || value === '' || hasControlCharacter(value)) {
31
+ return false;
32
+ }
33
+ return absoluteUrlPattern.test(value) || isOriginPath(value);
34
+ }
35
+ // The HTTP answer a link route sends, from the routine's outcome: a 302 to the URL the :return
36
+ // gives, or a status with no body. A browser loads the link as an image or a download, so a body
37
+ // would never be read. Any failure but a :reject or a failed ValidateSchema step answers 500
38
+ // with a fixed message, so nothing from the error reaches the caller. A :return that is not a
39
+ // link target is a config fault: it is logged as a ConfigError naming the endpoint.
40
+ async function createLinkAnswer(context, { endpointConfig, error, response, status }) {
41
+ if (status === 'reject') {
42
+ return {
43
+ status: error.webhookStatus ?? 400
44
+ };
45
+ }
46
+ if (status === 'error' && error?.isInvalidRequest === true) {
47
+ return {
48
+ status: 400
49
+ };
50
+ }
51
+ if (status === 'error') {
52
+ return {
53
+ status: 500,
54
+ body: {
55
+ error: 'Link failed.'
56
+ }
57
+ };
58
+ }
59
+ if (!isLinkTarget(response)) {
60
+ await context.handleError(new ConfigError(`Link endpoint "${endpointConfig.endpointId}" must return a URL: an absolute http(s) URL or a path starting with "/".`, {
61
+ received: response,
62
+ configKey: endpointConfig['~k']
63
+ }));
64
+ return {
65
+ status: 500,
66
+ body: {
67
+ error: 'Link failed.'
68
+ }
69
+ };
70
+ }
71
+ return {
72
+ status: 302,
73
+ location: response
74
+ };
75
+ }
76
+ export default createLinkAnswer;
@@ -0,0 +1,38 @@
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 { ServiceError } from '@lowdefy/errors';
16
+ // /api/detached answers 202 once it has accepted the run. Anything else - a 401 for a CRON_SECRET
17
+ // the deployment does not share, a 500 - means the target never ran, which is a fault, not a
18
+ // completed dispatch.
19
+ async function dispatchDetached(url, init) {
20
+ const response = await fetch(url, init);
21
+ // Drain the body so the connection is released; the route's own log holds the detail.
22
+ await response.arrayBuffer();
23
+ if (!response.ok) {
24
+ const message = `Detached call to ${url} answered ${response.status}, so the target endpoint did not run.`;
25
+ // A failing or throttled server passes with time; any other answer (a 401 for a CRON_SECRET
26
+ // the deployment does not share) repeats until config changes. As forwardScheduledEndpoint.
27
+ if (response.status === 429 || response.status >= 500) {
28
+ throw new ServiceError(message, {
29
+ statusCode: response.status
30
+ });
31
+ }
32
+ const error = new Error(message);
33
+ error.statusCode = response.status;
34
+ throw error;
35
+ }
36
+ return response;
37
+ }
38
+ export default dispatchDetached;
@@ -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 { serializer, type } from '@lowdefy/helpers';
16
- import { ConfigError } from '@lowdefy/errors';
16
+ import { ConfigError, ServiceError } from '@lowdefy/errors';
17
17
  import findSchedule from './findSchedule.js';
18
18
  import getEndpointConfig from './getEndpointConfig.js';
19
19
  import getEnvironmentSchedules from './getEnvironmentSchedules.js';
@@ -29,21 +29,31 @@ async function forwardScheduledEndpoint(context, { environment, endpointId, cron
29
29
  const { config, logger, secrets } = context;
30
30
  const target = config?.environments?.[environment];
31
31
  if (!type.isObject(target)) {
32
- throw new ConfigError(`Cron environment "${environment}" is not declared in config.environments.`);
32
+ throw new ConfigError(`Cron environment "${environment}" is not declared in config.environments.`, {
33
+ configKey: config?.environments?.['~k']
34
+ });
33
35
  }
34
36
  if (environment === config.environment) {
35
- throw new ConfigError(`Cron environment "${environment}" is this deployment's own environment: its crons run here, not forwarded.`);
37
+ throw new ConfigError(`Cron environment "${environment}" is this deployment's own environment: its crons run here, not forwarded.`, {
38
+ configKey: target['~k']
39
+ });
36
40
  }
37
41
  if (target.cron?.enabled === false) {
38
- throw new ConfigError(`Cron environment "${environment}" is disabled.`);
42
+ throw new ConfigError(`Cron environment "${environment}" is disabled.`, {
43
+ configKey: target['~k']
44
+ });
39
45
  }
40
46
  const secretName = target.cron?.secret;
41
47
  if (type.isUndefined(secretName)) {
42
- throw new ConfigError(`Cron environment "${environment}" has no cron.secret: crons are only forwarded to environments with one.`);
48
+ throw new ConfigError(`Cron environment "${environment}" has no cron.secret: crons are only forwarded to environments with one.`, {
49
+ configKey: target['~k']
50
+ });
43
51
  }
44
52
  const secret = secrets?.[secretName];
45
53
  if (!type.isString(secret) || secret === '') {
46
- throw new ConfigError(`Secret "${secretName}" holding the CRON_SECRET of cron environment "${environment}" is not set. Set the LOWDEFY_SECRET_${secretName} environment variable on this deployment.`);
54
+ throw new ConfigError(`Secret "${secretName}" holding the CRON_SECRET of cron environment "${environment}" is not set. Set the LOWDEFY_SECRET_${secretName} environment variable on this deployment.`, {
55
+ configKey: target.cron['~k'] ?? target['~k']
56
+ });
47
57
  }
48
58
  // Every environment builds from the same config, so the local artifact says whether the target
49
59
  // declares the firing schedule: fail here with a config error instead of having the target 500.
@@ -91,12 +101,23 @@ async function forwardScheduledEndpoint(context, { environment, endpointId, cron
91
101
  });
92
102
  // Drain the body so the connection is released; the target logs its own outcome.
93
103
  await response.arrayBuffer();
94
- if (!response.ok) {
95
- throw new Error(`Forwarded cron for environment "${environment}" at ${url} responded ${response.status}.`);
104
+ if (response.ok) {
105
+ return {
106
+ status: response.status
107
+ };
108
+ }
109
+ const message = `Forwarded cron for environment "${environment}" at ${url} responded ${response.status}.`;
110
+ // A failing or throttled environment passes with time. Any other answer - a 401 for a
111
+ // secret the environment does not share, a 404 for a url or basePath that does not serve
112
+ // the app - repeats until this deployment's config changes.
113
+ if (response.status === 429 || response.status >= 500) {
114
+ throw new ServiceError(message, {
115
+ statusCode: response.status
116
+ });
96
117
  }
97
- return {
98
- status: response.status
99
- };
118
+ throw new ConfigError(message, {
119
+ configKey: target['~k']
120
+ });
100
121
  });
101
122
  return {
102
123
  error: null,
@@ -36,7 +36,7 @@ async function handleAgentCall(context, routineContext, { step }) {
36
36
  });
37
37
  }
38
38
  if (!type.isString(prompt)) {
39
- throw new ConfigError(`CallAgent step "${step.stepId}" properties.prompt must evaluate to a string. Received ${JSON.stringify(prompt)}.`, {
39
+ throw new ConfigError(`CallAgent step "${step.stepId}" properties.prompt must evaluate to a string. Received a value of type "${prompt === null ? 'null' : typeof prompt}".`, {
40
40
  configKey: step['~k']
41
41
  });
42
42
  }
@@ -18,6 +18,8 @@ import { markCredential } from '@lowdefy/node-utils';
18
18
  import addStepResult from './addStepResult.js';
19
19
  import authorizeRole from '../auth/organizations/authorizeRole.js';
20
20
  import evaluateRoutineOperators from './evaluateRoutineOperators.js';
21
+ import isActiveMember from '../auth/organizations/isActiveMember.js';
22
+ import provisionOrganization from '../auth/organizations/provisionOrganization.js';
21
23
  import resolveStepOrganizationId from './resolveStepOrganizationId.js';
22
24
  // Refusals name what was asked for, because "refused" with no subject is the
23
25
  // failure people report: { member: ['update'] } reads as "member: [update]".
@@ -133,7 +135,8 @@ async function handleAuthStep(context, routineContext, { step }) {
133
135
  // The caller's authority is their member row in the TARGET organization,
134
136
  // which is the same question the organization endpoint would ask, asked
135
137
  // one layer earlier so the adapter-direct and admin-plugin steps get it
136
- // too.
138
+ // too. A suspended row holds no authority - the caller may be active in
139
+ // another organization and name this one.
137
140
  const callerMember = await adapter.findOne({
138
141
  model: 'member',
139
142
  where: [
@@ -147,7 +150,9 @@ async function handleAuthStep(context, routineContext, { step }) {
147
150
  }
148
151
  ]
149
152
  });
150
- if (type.isNone(callerMember) || !authorizeRole({
153
+ if (!isActiveMember({
154
+ member: callerMember
155
+ }) || !authorizeRole({
151
156
  permissions: authority.permissions,
152
157
  role: callerMember.role
153
158
  })) {
@@ -156,7 +161,8 @@ async function handleAuthStep(context, routineContext, { step }) {
156
161
  // A step that writes the user row reaches a row shared by the whole
157
162
  // deployment, so org authority alone would let an administrator of any
158
163
  // organization reach any user. Membership in the same organization is
159
- // what makes the target the caller's business. Steps that write a member
164
+ // what makes the target the caller's business, suspended or not - an
165
+ // administrator still manages a suspended member. Steps that write a member
160
166
  // row declare no targetUser - their target is already a row there. An
161
167
  // absent property is the step's own required-property error, so leave it
162
168
  // to the step.
@@ -189,6 +195,9 @@ async function handleAuthStep(context, routineContext, { step }) {
189
195
  // caller-scoped grant steps read it to find the grant behind the call.
190
196
  // markCredential lets a step that makes a credential (a member token) keep
191
197
  // it out of every log line for the rest of the request.
198
+ // provisionOrganization is the engine's organization-and-owner write, which
199
+ // CreateOrganization makes through it so the signup mint and the step write
200
+ // the owner row one way, behind the same unique indexes.
192
201
  const result = await stepFn({
193
202
  acting,
194
203
  auth: context.auth,
@@ -196,7 +205,13 @@ async function handleAuthStep(context, routineContext, { step }) {
196
205
  mcp: context.mcpAuth ?? null,
197
206
  organization: context.organization ?? null,
198
207
  organizationId,
199
- properties: evaluatedProperties
208
+ properties: evaluatedProperties,
209
+ provisionOrganization: ({ organization, userId })=>provisionOrganization({
210
+ auth: context.auth,
211
+ logger,
212
+ organization,
213
+ userId
214
+ })
200
215
  });
201
216
  addStepResult(context, routineContext, {
202
217
  result,
@@ -17,6 +17,7 @@ import { ConfigError, LowdefyInternalError } from '@lowdefy/errors';
17
17
  import { getMarkedCredentials } from '@lowdefy/node-utils';
18
18
  import addStepResult from './addStepResult.js';
19
19
  import createBoundSystemContext from '../../context/createBoundSystemContext.js';
20
+ import dispatchDetached from './dispatchDetached.js';
20
21
  import evaluateRoutineOperators from './evaluateRoutineOperators.js';
21
22
  import invokeEndpoint from './invokeEndpoint.js';
22
23
  import resolveCallBinding from './resolveCallBinding.js';
@@ -51,7 +52,9 @@ async function handleEndpointCall(context, routineContext, { step }) {
51
52
  // its logs and whatever its routine writes.
52
53
  if (evaluatedProperties.detached === true) {
53
54
  if (!process.env.CRON_SECRET) {
54
- throw new ConfigError('CallApi with "detached: true" requires the CRON_SECRET environment variable — the /api/detached route fails closed without it.');
55
+ throw new ConfigError('CallApi with "detached: true" requires the CRON_SECRET environment variable — the /api/detached route fails closed without it.', {
56
+ configKey: step['~k']
57
+ });
55
58
  }
56
59
  if (!context.origin) {
57
60
  throw new LowdefyInternalError('Detached endpoint calls require the request origin on context.');
@@ -60,7 +63,7 @@ async function handleEndpointCall(context, routineContext, { step }) {
60
63
  scheduleBackground(context, {
61
64
  event: 'detached_dispatch',
62
65
  endpointId: targetEndpointId
63
- }, ()=>fetch(`${context.origin}/api/detached/${targetEndpointId}`, {
66
+ }, ()=>dispatchDetached(`${context.origin}/api/detached/${targetEndpointId}`, {
64
67
  method: 'POST',
65
68
  headers: {
66
69
  // The dev server's journey cookies (data set, mutant) ride the hop
@@ -129,8 +132,7 @@ async function handleEndpointCall(context, routineContext, { step }) {
129
132
  logger.debug({
130
133
  event: 'debug_end_endpoint_call',
131
134
  stepId: step.stepId,
132
- targetEndpointId: evaluatedProperties.endpointId,
133
- response
135
+ targetEndpointId: evaluatedProperties.endpointId
134
136
  });
135
137
  return {
136
138
  status: 'continue'
@@ -85,10 +85,11 @@ async function handleRequest(context, routineContext, { request }) {
85
85
  result,
86
86
  stepId: request.stepId
87
87
  });
88
+ // No evaluated values: they can carry chat text or other personal information,
89
+ // which no log level may hold.
88
90
  context.logger.debug({
89
91
  event: 'debug_end_request',
90
- id: requestConfig.id,
91
- result
92
+ id: requestConfig.id
92
93
  });
93
94
  return {
94
95
  status: 'continue'
@@ -39,7 +39,7 @@ async function handleValidateDynamic(context, routineContext, { step }) {
39
39
  {
40
40
  path: 'blocks',
41
41
  rule: 'shape',
42
- message: `Content should be an array of blocks. Received ${JSON.stringify(blocks)}.`
42
+ message: `Content should be an array of blocks. Received a value of type "${blocks === null ? 'null' : typeof blocks}".`
43
43
  }
44
44
  ];
45
45
  } else {
@@ -0,0 +1,30 @@
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
+ // Finds the link endpoint a GET path names. linkEndpoints is the build's linkEndpoints.json,
17
+ // longest id first, so a nested id ("a/b") wins over a shorter id it starts with ("a"). The
18
+ // segments after the id, joined with "/", are the path the routine receives; it may be empty.
19
+ // Only link endpoints are listed, so a GET never reaches any other endpoint.
20
+ function matchLinkEndpoint({ linkEndpoints, segments }) {
21
+ const match = linkEndpoints.find((linkEndpoint)=>linkEndpoint.segments.every((segment, index)=>segments[index] === segment));
22
+ if (type.isNone(match)) {
23
+ return null;
24
+ }
25
+ return {
26
+ endpointId: match.endpointId,
27
+ path: segments.slice(match.segments.length).join('/')
28
+ };
29
+ }
30
+ export default matchLinkEndpoint;
@@ -0,0 +1,148 @@
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 authorizeApiEndpoint from './authorizeApiEndpoint.js';
17
+ import createEvaluateOperators from '../../context/createEvaluateOperators.js';
18
+ import createLinkAnswer from './createLinkAnswer.js';
19
+ import getEndpointConfig from './getEndpointConfig.js';
20
+ import matchLinkEndpoint from './matchLinkEndpoint.js';
21
+ import runRoutine from './runRoutine.js';
22
+ import validatePayload from './validatePayload.js';
23
+ const refusalStatuses = {
24
+ AuthenticationError: 401,
25
+ AuthorizationError: 403,
26
+ TwoFactorEnrolmentRequiredError: 403
27
+ };
28
+ // The caller's auth refused as a status with no body: an image load cannot read one. It goes
29
+ // through authorizeApiEndpoint, as every endpoint route does, so the refusal rules (roles,
30
+ // two-factor enrolment) stay in one place; only the errors it throws are read as statuses here.
31
+ function getRefusalStatus(context, { endpointConfig }) {
32
+ try {
33
+ authorizeApiEndpoint(context, {
34
+ endpointConfig
35
+ });
36
+ return null;
37
+ } catch (error) {
38
+ if (Object.hasOwn(refusalStatuses, error.name)) {
39
+ return refusalStatuses[error.name];
40
+ }
41
+ throw error;
42
+ }
43
+ }
44
+ // A payload the endpoint's payloadSchema refuses is the caller's own mistake (the URL is theirs),
45
+ // answered 400 with no body like the other refusals, and logged without the path.
46
+ function getPayloadRefusalStatus(context, { endpointConfig, payload }) {
47
+ try {
48
+ validatePayload({
49
+ endpointConfig,
50
+ payload,
51
+ outsideCaller: true
52
+ });
53
+ return null;
54
+ } catch (error) {
55
+ if (error.name !== 'UserError') {
56
+ throw error;
57
+ }
58
+ context.logger.debug({
59
+ event: 'debug_link_payload_refused',
60
+ endpointId: endpointConfig.endpointId
61
+ }, error.message);
62
+ return 400;
63
+ }
64
+ }
65
+ // A GET that names no link endpoint. An anonymous human on an app with auth gets the same 401 a
66
+ // protected link answers, as getEndpointConfig does for an unknown endpoint, so a signed-out
67
+ // caller cannot tell which link ids exist.
68
+ function answerUnmatched({ authEnforcement, system, user }) {
69
+ if (type.isNone(user) && !type.isNone(authEnforcement) && system !== true) {
70
+ return {
71
+ status: 401
72
+ };
73
+ }
74
+ return {
75
+ status: 404,
76
+ body: {
77
+ error: 'Not found.'
78
+ }
79
+ };
80
+ }
81
+ // Runs an endpoint declared `link: true` for a GET on /api/endpoints/<endpointId>/<path...>,
82
+ // typically an <img src> or a download link, so a private file is served at a URL that does
83
+ // not expire. The routine runs as the session caller, with the endpoint's auth applied as on a
84
+ // CallAPI call, and receives { path, query } as payload. It returns the HTTP answer the route
85
+ // sends: { status, location } for the 302 to the URL the routine returned, else { status, body? }
86
+ // (see createLinkAnswer). segments are the decoded path segments after /api/endpoints/.
87
+ async function runLinkEndpoint(context, { segments, query }) {
88
+ const linkEndpoints = await context.readConfigFile('linkEndpoints.json');
89
+ const match = matchLinkEndpoint({
90
+ linkEndpoints,
91
+ segments
92
+ });
93
+ if (type.isNone(match)) {
94
+ return answerUnmatched(context);
95
+ }
96
+ const { endpointId, path } = match;
97
+ context.endpointId = endpointId;
98
+ context.evaluateOperators = createEvaluateOperators(context);
99
+ // The id only: the path can be a file name. (The request log line still records the URL path,
100
+ // as it does on every route.)
101
+ context.logger.info({
102
+ event: 'call_link_endpoint',
103
+ endpointId
104
+ });
105
+ const endpointConfig = await getEndpointConfig(context, {
106
+ endpointId
107
+ });
108
+ const refusalStatus = getRefusalStatus(context, {
109
+ endpointConfig
110
+ });
111
+ if (!type.isNone(refusalStatus)) {
112
+ return {
113
+ status: refusalStatus
114
+ };
115
+ }
116
+ const payload = {
117
+ path,
118
+ query
119
+ };
120
+ const payloadRefusalStatus = getPayloadRefusalStatus(context, {
121
+ endpointConfig,
122
+ payload
123
+ });
124
+ if (!type.isNone(payloadRefusalStatus)) {
125
+ return {
126
+ status: payloadRefusalStatus
127
+ };
128
+ }
129
+ const routineContext = {
130
+ steps: {},
131
+ payload,
132
+ arrayIndices: [],
133
+ error: null,
134
+ items: {},
135
+ state: {},
136
+ endpointDepth: 0
137
+ };
138
+ const { error, response, status } = await runRoutine(context, routineContext, {
139
+ routine: endpointConfig.routine
140
+ });
141
+ return createLinkAnswer(context, {
142
+ endpointConfig,
143
+ error,
144
+ response,
145
+ status
146
+ });
147
+ }
148
+ export default runLinkEndpoint;
@@ -12,7 +12,7 @@
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 { LowdefyInternalError } from '@lowdefy/errors';
15
+ */ import { isExpectedError, LowdefyInternalError } from '@lowdefy/errors';
16
16
  import { type } from '@lowdefy/helpers';
17
17
  import handleAgentCall from './handleAgentCall.js';
18
18
  import handleAuthStep from './handleAuthStep.js';
@@ -124,10 +124,10 @@ async function runRoutine(context, routineContext, { routine }) {
124
124
  error
125
125
  };
126
126
  }
127
- // A UserError is an expected outcome, not a fault: it is logged once, as a
128
- // warning. A step or control that logs one marks it handled; one thrown
129
- // without being logged is logged here.
130
- if (error.name === 'UserError') {
127
+ // An expected outcome (a UserError, or an auth refusal from a nested CallApi) is not a
128
+ // fault: it is logged once, as a warning. A step or control that logs one marks it
129
+ // handled; one thrown without being logged is logged here.
130
+ if (isExpectedError(error)) {
131
131
  if (!error.handled) {
132
132
  context.logger.warn({
133
133
  event: 'warn_routine_user_error',