@lowdefy/api 7.1.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,32 @@
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 { isExpectedError } from '@lowdefy/errors';
16
+ // Runs work BetterAuth calls back into (an auth email send) in a system context, and reports
17
+ // a fault through that context's error sink before it propagates. BetterAuth runs some of these
18
+ // as background tasks, where it only writes its own "Failed to run background task" line; the
19
+ // sink resolves the config location and sends the fault to error tracking. The error is marked
20
+ // handled, so that line and createOnAPIError do not report it again. An expected outcome
21
+ // propagates without a report.
22
+ async function runReportingFaults({ context, run }) {
23
+ try {
24
+ return await run();
25
+ } catch (error) {
26
+ if (!isExpectedError(error)) {
27
+ await context.handleError(error);
28
+ }
29
+ throw error;
30
+ }
31
+ }
32
+ export default runReportingFaults;
@@ -30,8 +30,8 @@ import createReadConfigFile from '../../context/createReadConfigFile.js';
30
30
  // match. A walled connection's database name is its databaseName property,
31
31
  // falling back to the path of its URI.
32
32
  //
33
- // The result maps each reaching connection id to the refusal message, logged
34
- // once when the check runs. checkUnwalledReach throws it as a ConfigError on
33
+ // The result maps each reaching connection id to the refusal message, reported
34
+ // once, through handleError at the connection's config location, when the check runs. checkUnwalledReach throws it as a ConfigError on
35
35
  // that connection's requests; every other connection is served. The check reads config and
36
36
  // secrets only, so it runs once per config build artifact, independent of the
37
37
  // tenant preflight's database probes. A check that throws is not memoized.
@@ -66,9 +66,9 @@ function collectUris(value, uris) {
66
66
  }
67
67
  return uris;
68
68
  }
69
- async function evaluateConnectionProperties({ connectionId, evaluateOperators, readConfigFile }) {
70
- const connectionConfig = await readConfigFile(`connections/${connectionId}.json`);
69
+ async function evaluateConnectionProperties({ connectionConfig, evaluateOperators }) {
71
70
  if (!connectionConfig) return null;
71
+ const { connectionId } = connectionConfig;
72
72
  try {
73
73
  return evaluateOperators({
74
74
  input: connectionConfig.properties ?? {},
@@ -86,9 +86,8 @@ async function collectWalledDatabases({ evaluateOperators, readConfigFile }) {
86
86
  const walled = new Map();
87
87
  for (const entry of tenantConnections ?? []){
88
88
  const properties = await evaluateConnectionProperties({
89
- connectionId: entry.connectionId,
90
- evaluateOperators,
91
- readConfigFile
89
+ connectionConfig: await readConfigFile(`connections/${entry.connectionId}.json`),
90
+ evaluateOperators
92
91
  });
93
92
  const parsed = parseMongoUri(properties?.databaseUri);
94
93
  if (!parsed) continue;
@@ -115,19 +114,18 @@ async function findUnwalledReach(context) {
115
114
  });
116
115
  if (walled.size === 0) return reach;
117
116
  for (const entry of unwalledConnections){
117
+ const connectionConfig = await readConfigFile(`connections/${entry.connectionId}.json`);
118
118
  const properties = await evaluateConnectionProperties({
119
- connectionId: entry.connectionId,
120
- evaluateOperators,
121
- readConfigFile
119
+ connectionConfig,
120
+ evaluateOperators
122
121
  });
123
122
  const reached = collectUris(properties, []).find(({ hosts, database })=>walled.has(`${hosts}/${database}`));
124
123
  if (!reached) continue;
125
- const error = new ConfigError(`Connection "${entry.connectionId}" (${entry.type}) holds a URI to the database of walled connection "${walled.get(`${reached.hosts}/${reached.database}`)}". Unwalled connections must not reach walled data: give the plugin a mongoConnectionId and use the walled MongoDB client (@lowdefy/connection-mongodb/walled). Requests on this connection are refused.`);
126
- context.logger.error({
127
- err: error,
128
- event: 'unwalled_reach',
129
- connectionId: entry.connectionId
130
- }, error.message);
124
+ const error = new ConfigError(`Connection "${entry.connectionId}" (${entry.type}) holds a URI to the database of walled connection "${walled.get(`${reached.hosts}/${reached.database}`)}". Unwalled connections must not reach walled data: give the plugin a mongoConnectionId and use the walled MongoDB client (@lowdefy/connection-mongodb/walled). Requests on this connection are refused.`, {
125
+ configKey: connectionConfig['~k']
126
+ });
127
+ error.connectionId = entry.connectionId;
128
+ await context.handleError(error);
131
129
  reach.set(entry.connectionId, error.message);
132
130
  }
133
131
  return reach;
@@ -27,12 +27,13 @@ async function callEndpoint(context, { blockId, endpointId, outsideCaller = fals
27
27
  context.endpointId = endpointId;
28
28
  context.pageId = pageId;
29
29
  context.evaluateOperators = createEvaluateOperators(context);
30
+ // Ids only: a payload can carry chat text or other personal information (an agent
31
+ // chat's save-thread call sends the whole thread), which no log level may hold.
30
32
  logger.debug({
31
33
  event: 'debug_endpoint',
32
34
  blockId,
33
35
  endpointId,
34
- pageId,
35
- payload
36
+ pageId
36
37
  });
37
38
  const endpointConfig = await getEndpointConfig(context, {
38
39
  endpointId
@@ -40,7 +41,9 @@ async function callEndpoint(context, { blockId, endpointId, outsideCaller = fals
40
41
  // Block HTTP access to InternalApi endpoints - same error as a missing
41
42
  // endpoint, including the guarded unauthenticated fork, so an internal
42
43
  // endpoint is indistinguishable from one that does not exist on both paths.
43
- if (endpointConfig.type === 'InternalApi') {
44
+ // A link endpoint answers only the GET route (runLinkEndpoint), so a POST or
45
+ // MCP call to it is refused the same way.
46
+ if (endpointConfig.type === 'InternalApi' || endpointConfig.link === true) {
44
47
  const unauthenticatedHuman = type.isNone(context.user) && !type.isNone(context.authEnforcement) && context.system !== true;
45
48
  const err = unauthenticatedHuman ? new AuthenticationError(`Authentication required for API endpoint "${endpointId}".`) : new ConfigError(`API Endpoint "${endpointId}" does not exist.`);
46
49
  logger.debug({
@@ -20,7 +20,9 @@ async function controlFor(context, routineContext, { control }) {
20
20
  const { items } = routineContext;
21
21
  const itemName = control[':for'];
22
22
  if (!itemName) {
23
- throw new Error(`Invalid :for in endpoint "${endpointId}" - missing variable name in :for.`);
23
+ throw new ConfigError(`Invalid :for in endpoint "${endpointId}" - missing variable name in :for.`, {
24
+ configKey: control['~k']
25
+ });
24
26
  }
25
27
  const array = evaluateRoutineOperators(context, routineContext, {
26
28
  input: control[':in'],
@@ -28,7 +30,7 @@ async function controlFor(context, routineContext, { control }) {
28
30
  });
29
31
  logger.debug({
30
32
  event: 'debug_control_for',
31
- array,
33
+ itemCount: Array.isArray(array) ? array.length : null,
32
34
  itemName
33
35
  });
34
36
  if (!Array.isArray(array)) {
@@ -38,7 +40,9 @@ async function controlFor(context, routineContext, { control }) {
38
40
  });
39
41
  }
40
42
  if (!control[':do']) {
41
- throw new Error(`Invalid :for in endpoint "${endpointId}" - missing :do.`);
43
+ throw new ConfigError(`Invalid :for in endpoint "${endpointId}" - missing :do.`, {
44
+ configKey: control['~k']
45
+ });
42
46
  }
43
47
  for (const [index, item] of array.entries()){
44
48
  const updatedItems = {
@@ -47,9 +51,8 @@ async function controlFor(context, routineContext, { control }) {
47
51
  };
48
52
  logger.debug({
49
53
  event: 'debug_control_for_iteration',
50
- itemName: itemName,
51
- value: item,
52
- items: updatedItems
54
+ itemName,
55
+ index
53
56
  });
54
57
  const res = await runRoutine(context, {
55
58
  ...routineContext,
@@ -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 controlIf(context, routineContext, { control }) {
18
19
  const { endpointId, logger } = context;
@@ -20,11 +21,13 @@ async function controlIf(context, routineContext, { control }) {
20
21
  input: control[':if'],
21
22
  location: control['~k'] ?? ':if'
22
23
  });
24
+ // No evaluated values: they can carry chat text or other personal information,
25
+ // which no log level may hold.
23
26
  logger.debug({
24
27
  event: 'debug_control_if',
25
28
  condition: {
26
29
  input: control[':if'],
27
- evaluated: evaluatedIf
30
+ result: Boolean(evaluatedIf)
28
31
  }
29
32
  });
30
33
  if (evaluatedIf) {
@@ -32,7 +35,9 @@ async function controlIf(context, routineContext, { control }) {
32
35
  event: 'debug_control_if_run_then'
33
36
  });
34
37
  if (!control[':then']) {
35
- throw new Error(`Invalid :if in endpoint "${endpointId}" - missing :then.`);
38
+ throw new ConfigError(`Invalid :if in endpoint "${endpointId}" - missing :then.`, {
39
+ configKey: control['~k']
40
+ });
36
41
  }
37
42
  return runRoutine(context, routineContext, {
38
43
  routine: control[':then']
@@ -36,7 +36,9 @@ async function controlLog(context, routineContext, { control }) {
36
36
  });
37
37
  }
38
38
  if (!logger[logLevel]) {
39
- throw new Error(`Invalid :log in endpoint "${endpointId}" - unrecognised log level. Received "${logLevel}".`);
39
+ throw new ConfigError(`Invalid :log in endpoint "${endpointId}" - unrecognised log level. Received "${logLevel}".`, {
40
+ configKey: control['~k']
41
+ });
40
42
  }
41
43
  logger[logLevel](log);
42
44
  return {
@@ -43,7 +43,9 @@ async function controlParallelFor(context, routineContext, { control }) {
43
43
  const { items } = routineContext;
44
44
  const itemName = control[':parallel_for'];
45
45
  if (!itemName) {
46
- throw new Error(`Invalid :parallel_for in endpoint "${endpointId}" - missing variable name in :parallel_for.`);
46
+ throw new ConfigError(`Invalid :parallel_for in endpoint "${endpointId}" - missing variable name in :parallel_for.`, {
47
+ configKey: control['~k']
48
+ });
47
49
  }
48
50
  const array = evaluateRoutineOperators(context, routineContext, {
49
51
  input: control[':in'],
@@ -51,7 +53,7 @@ async function controlParallelFor(context, routineContext, { control }) {
51
53
  });
52
54
  logger.debug({
53
55
  event: 'debug_control_parallel',
54
- array,
56
+ itemCount: Array.isArray(array) ? array.length : null,
55
57
  itemName
56
58
  });
57
59
  if (!Array.isArray(array)) {
@@ -61,7 +63,9 @@ async function controlParallelFor(context, routineContext, { control }) {
61
63
  });
62
64
  }
63
65
  if (!control[':do']) {
64
- throw new Error(`Invalid :parallel_for in endpoint "${endpointId}" - missing :do.`);
66
+ throw new ConfigError(`Invalid :parallel_for in endpoint "${endpointId}" - missing :do.`, {
67
+ configKey: control['~k']
68
+ });
65
69
  }
66
70
  const concurrency = evaluateRoutineOperators(context, routineContext, {
67
71
  input: control[':concurrency'],
@@ -86,9 +90,8 @@ async function controlParallelFor(context, routineContext, { control }) {
86
90
  };
87
91
  logger.debug({
88
92
  event: 'debug_control_parallel_iteration',
89
- itemName: itemName,
90
- value: item,
91
- items: updatedItems
93
+ itemName,
94
+ index
92
95
  });
93
96
  return runRoutine(context, {
94
97
  ...routineContext,
@@ -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'