@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
@@ -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',
@@ -12,16 +12,18 @@
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
- */ // Run work after the response is sent. Platforms that reap the invocation once
15
+ */ import { isExpectedError } from '@lowdefy/errors';
16
+ // Run work after the response is sent. Platforms that reap the invocation once
16
17
  // the response is flushed (Vercel fluid compute) inject context.waitUntil in
17
18
  // their server's apiContext middleware to keep the invocation alive until the
18
19
  // promise settles (bounded by the function's maxDuration); locally /
19
20
  // self-hosted there is no waitUntil and the promise simply runs detached on
20
21
  // the still-alive Node process.
21
22
  //
22
- // The outcome only exists in logs — completion and failure are logged through
23
- // the request logger so they reach the platform log stream (and any log
24
- // drains); a background failure must never surface as an unhandled rejection.
23
+ // The outcome only exists in logs - completion is logged through the request logger so it
24
+ // reaches the platform log stream (and any log drains). A failure is logged like a failure in
25
+ // the request: an expected outcome as a warning, a fault through handleError, so it carries its
26
+ // config location and reaches error tracking. It must never surface as an unhandled rejection.
25
27
  function scheduleBackground(context, { event, endpointId }, fn) {
26
28
  const { logger } = context;
27
29
  const promise = (async ()=>{
@@ -33,9 +35,7 @@ function scheduleBackground(context, { event, endpointId }, fn) {
33
35
  status: result?.status
34
36
  });
35
37
  } catch (err) {
36
- // A UserError is the caller's mistake, not a fault: warn level, as on
37
- // every other call path.
38
- if (err.name === 'UserError') {
38
+ if (isExpectedError(err)) {
39
39
  logger.warn({
40
40
  event: `${event}_failed`,
41
41
  endpointId,
@@ -43,11 +43,13 @@ function scheduleBackground(context, { event, endpointId }, fn) {
43
43
  }, err.message);
44
44
  return;
45
45
  }
46
- logger.error({
46
+ logger.info({
47
47
  event: `${event}_failed`,
48
- endpointId,
49
- err
50
- }, err.message);
48
+ endpointId
49
+ });
50
+ if (err?.handled !== true) {
51
+ await context.handleError(err);
52
+ }
51
53
  }
52
54
  })();
53
55
  if (context.waitUntil) {
@@ -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 { jest } from '@jest/globals';
15
+ */ import { vi } from 'vitest';
16
16
  import { wait } from '@lowdefy/helpers';
17
17
  import { operatorsServer } from '@lowdefy/operators-js';
18
18
  import createEvaluateOperators from '../../../context/createEvaluateOperators.js';
@@ -39,30 +39,44 @@ const defaultReadConfigImp = ({ connectionConfig = {
39
39
  }
40
40
  return null;
41
41
  };
42
- const mockReadConfigFile = jest.fn().mockImplementation(defaultReadConfigImp());
43
- const mockTestRequest = jest.fn((request)=>{
42
+ const mockReadConfigFile = vi.fn().mockImplementation(defaultReadConfigImp());
43
+ const mockTestRequest = vi.fn((request)=>{
44
44
  return request.request.response;
45
45
  });
46
- const mockTestRequestError = jest.fn((request)=>{
46
+ const mockTestRequestError = vi.fn((request)=>{
47
47
  throw new Error(request.request.message);
48
48
  });
49
- const mockTestRequestWait = jest.fn((request)=>wait(request.request.ms));
49
+ const mockTestRequestWait = vi.fn((request)=>wait(request.request.ms));
50
50
  // Waits `ms` and records how many of these requests were in flight at once (inFlight.max).
51
51
  const inFlight = {
52
52
  current: 0,
53
53
  max: 0
54
54
  };
55
- const mockTestRequestInFlight = jest.fn(async (request)=>{
55
+ const mockTestRequestInFlight = vi.fn(async (request)=>{
56
56
  inFlight.current += 1;
57
57
  inFlight.max = Math.max(inFlight.max, inFlight.current);
58
58
  await wait(request.request.ms);
59
59
  inFlight.current -= 1;
60
60
  return request.request.response;
61
61
  });
62
+ // Fails as a MongoDB write fails schema validation: the driver's error carries the document it
63
+ // rejected.
64
+ const mockTestRequestRejectDocument = vi.fn((request)=>{
65
+ const error = new Error('Document failed validation');
66
+ error.name = 'MongoServerError';
67
+ error.code = 121;
68
+ error.errInfo = {
69
+ details: {
70
+ document: request.request.document
71
+ }
72
+ };
73
+ throw error;
74
+ });
62
75
  mockTestRequest.schema = {};
63
76
  mockTestRequestError.schema = {};
64
77
  mockTestRequestWait.schema = {};
65
78
  mockTestRequestInFlight.schema = {};
79
+ mockTestRequestRejectDocument.schema = {};
66
80
  mockTestRequest.meta = {
67
81
  checkRead: false,
68
82
  checkWrite: false
@@ -79,6 +93,10 @@ mockTestRequestInFlight.meta = {
79
93
  checkRead: false,
80
94
  checkWrite: false
81
95
  };
96
+ mockTestRequestRejectDocument.meta = {
97
+ checkRead: false,
98
+ checkWrite: false
99
+ };
82
100
  const connections = {
83
101
  TestConnection: {
84
102
  schema: {},
@@ -86,16 +104,17 @@ const connections = {
86
104
  TestRequest: mockTestRequest,
87
105
  TestRequestError: mockTestRequestError,
88
106
  TestRequestWait: mockTestRequestWait,
89
- TestRequestInFlight: mockTestRequestInFlight
107
+ TestRequestInFlight: mockTestRequestInFlight,
108
+ TestRequestRejectDocument: mockTestRequestRejectDocument
90
109
  }
91
110
  }
92
111
  };
93
112
  const logger = {
94
- debug: jest.fn(),
95
- info: jest.fn(),
96
- warn: jest.fn(),
113
+ debug: vi.fn(),
114
+ info: vi.fn(),
115
+ warn: vi.fn(),
97
116
  // error: console.error,
98
- error: jest.fn()
117
+ error: vi.fn()
99
118
  };
100
119
  function createTextContext({ user = {
101
120
  id: 'id',
@@ -15,6 +15,7 @@
15
15
  */ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
16
16
  import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
17
17
  import { cleanBuildArtifact, serializer, type } from '@lowdefy/helpers';
18
+ import { isExpectedError } from '@lowdefy/errors';
18
19
  import formatErrorForAgent from '../../response/formatErrorForAgent.js';
19
20
  import callEndpoint from '../endpoints/callEndpoint.js';
20
21
  import runAfterToolCall from './runAfterToolCall.js';
@@ -211,13 +212,7 @@ async function createMcpServer({ context }) {
211
212
  // model needs to retry, not a structured error log. Everything else
212
213
  // goes through the server's error sink, which resolves the config
213
214
  // source, logs it and collects it for the dev feedback channel.
214
- if ([
215
- 'AuthenticationError',
216
- 'AuthorizationError',
217
- 'TwoFactorEnrolmentRequiredError'
218
- ].includes(error.name)) {
219
- context.logger.warn(`Refused MCP tool call: ${name} - ${error.message}`);
220
- } else if (error.name === 'UserError') {
215
+ if (isExpectedError(error)) {
221
216
  context.logger.warn(`Refused MCP tool call: ${name} - ${error.message}`);
222
217
  } else {
223
218
  await context.handleError(error);
@@ -12,11 +12,14 @@
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 invokeEndpoint from '../endpoints/invokeEndpoint.js';
15
+ */ import { isExpectedError } from '@lowdefy/errors';
16
+ import invokeEndpoint from '../endpoints/invokeEndpoint.js';
16
17
  // Runs the app's mcp.afterToolCall endpoint as the tool's caller, after the
17
18
  // reply to the agent is built. The hook observes the call; it can never change
18
- // the reply, so every failure (a refused caller, a payload its schema rejects,
19
- // a routine that errors or rejects) ends as one warning and nothing else.
19
+ // the reply, so every failure ends as one warning naming the hook and the tool.
20
+ // A fault the routine did not reach (a missing endpoint, a payload its schema
21
+ // rejects) is also reported through handleError, like any other fault; the
22
+ // routine's own faults already were, by runRoutine.
20
23
  // Awaited by the caller rather than left running: a serverless platform may
21
24
  // reap the invocation once the response is sent.
22
25
  async function runAfterToolCall(context, { hookId, payload }) {
@@ -45,6 +48,9 @@ async function runAfterToolCall(context, { hookId, payload }) {
45
48
  tool: payload.tool,
46
49
  err: error
47
50
  }, `MCP afterToolCall hook "${hookId}" failed after tool "${payload.tool}": ${error.message}`);
51
+ if (!isExpectedError(error) && error?.handled !== true) {
52
+ await context.handleError(error);
53
+ }
48
54
  }
49
55
  }
50
56
  export default runAfterToolCall;
@@ -0,0 +1,51 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { type } from '@lowdefy/helpers';
16
+ // The apple-app-site-association document that lets the app's iOS shells open
17
+ // its links (universal links), built from mobile.shells in mobile/config.json.
18
+ // A shell needs both a team id and a bundle id to be named here.
19
+ //
20
+ // Every page path under basePath opens in the shell, not only the mobile
21
+ // pages: listing those paths in a public file would tell a signed-out visitor
22
+ // which pages exist. A shell asked for a web page gets the surface gate's
23
+ // 404 { surface: 'web' } and opens it in the browser. API routes, auth
24
+ // callbacks among them, always reach the server.
25
+ //
26
+ // Returns null when no shell takes iOS links.
27
+ function createAppleAppSiteAssociation({ mobileConfig, basePath }) {
28
+ const appIDs = (mobileConfig.shells ?? []).filter((shell)=>type.isString(shell.ios?.teamId) && type.isString(shell.ios?.bundleId)).map((shell)=>`${shell.ios.teamId}.${shell.ios.bundleId}`);
29
+ if (appIDs.length === 0) {
30
+ return null;
31
+ }
32
+ return {
33
+ applinks: {
34
+ details: [
35
+ {
36
+ appIDs,
37
+ components: [
38
+ {
39
+ '/': `${basePath}/api/*`,
40
+ exclude: true
41
+ },
42
+ {
43
+ '/': `${basePath}/*`
44
+ }
45
+ ]
46
+ }
47
+ ]
48
+ }
49
+ };
50
+ }
51
+ export default createAppleAppSiteAssociation;
@@ -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 { type } from '@lowdefy/helpers';
16
+ // The Digital Asset Links statement that lets the app's Android shells open
17
+ // its links (app links), built from mobile.shells in mobile/config.json. A
18
+ // shell needs a package name and at least one signing certificate fingerprint
19
+ // to be named here. Android filters link paths in the shell's manifest.
20
+ //
21
+ // Returns null when no shell takes Android links.
22
+ function createAssetLinks({ mobileConfig }) {
23
+ const statements = (mobileConfig.shells ?? []).filter((shell)=>type.isString(shell.android?.package) && shell.android.sha256?.length > 0).map((shell)=>({
24
+ relation: [
25
+ 'delegate_permission/common.handle_all_urls'
26
+ ],
27
+ target: {
28
+ namespace: 'android_app',
29
+ package_name: shell.android.package,
30
+ sha256_cert_fingerprints: shell.android.sha256
31
+ }
32
+ }));
33
+ if (statements.length === 0) {
34
+ return null;
35
+ }
36
+ return statements;
37
+ }
38
+ export default createAssetLinks;
@@ -0,0 +1,31 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ // The mobile frame with the items this caller may open. A stack frame has no
16
+ // items. A mobile menu item carries no auth of its own: it shows when the
17
+ // caller may open its page.
18
+ function filterMobileMenus({ menus, openablePageIds }) {
19
+ if (menus.stack === true) {
20
+ return menus;
21
+ }
22
+ if (menus.tabs) {
23
+ return {
24
+ tabs: menus.tabs.filter((item)=>openablePageIds.has(item.pageId))
25
+ };
26
+ }
27
+ return {
28
+ drawer: menus.drawer.filter((item)=>openablePageIds.has(item.pageId))
29
+ };
30
+ }
31
+ export default filterMobileMenus;
@@ -0,0 +1,23 @@
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 { serializer } from '@lowdefy/helpers';
16
+ // mobile.events, the app events a shell runs in place of the web app's events.
17
+ // Serialized like the web's (getAppEvents): their ~k markers reach the shell so
18
+ // app event errors resolve to their config.
19
+ async function getMobileAppEvents({ readConfigFile }) {
20
+ const events = await readConfigFile('mobile/events.json');
21
+ return serializer.serialize(events);
22
+ }
23
+ export default getMobileAppEvents;