@lowdefy/api 6.0.0 → 7.0.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 (208) hide show
  1. package/dist/context/applySystemTrust.js +45 -0
  2. package/dist/context/createApiContext.js +18 -3
  3. package/dist/context/createAuthorizeOutcome.js +91 -0
  4. package/dist/context/createBoundSystemContext.js +33 -0
  5. package/dist/context/createEvaluateOperators.js +10 -3
  6. package/dist/context/createRequestSignal.js +47 -0
  7. package/dist/context/createSystemContext.js +80 -0
  8. package/dist/context/getCanonicalUrl.js +27 -0
  9. package/dist/context/getCurrentEnvironment.js +27 -0
  10. package/dist/context/isSameOriginRequest.js +85 -0
  11. package/dist/context/isWebSocketOriginAllowed.js +63 -0
  12. package/dist/context/normalizeInjectedCaller.js +58 -0
  13. package/dist/context/parseRequestBody.js +32 -0
  14. package/dist/context/readMemberships.js +71 -0
  15. package/dist/context/resolveAuthentication.js +758 -0
  16. package/dist/context/resolveStrategyCaller.js +7 -3
  17. package/dist/csp/addNonceToElements.js +23 -0
  18. package/dist/csp/createContentSecurityPolicy.js +45 -0
  19. package/dist/csp/getWebSocketSources.js +36 -0
  20. package/dist/email/renderAuthEmail.js +99 -0
  21. package/dist/index.js +22 -5
  22. package/dist/response/buildEndpointResult.js +3 -1
  23. package/dist/response/createWireProjection.js +88 -0
  24. package/dist/response/formatErrorForAgent.js +35 -0
  25. package/dist/response/normalizeErrorSources.js +10 -13
  26. package/dist/response/redactErrorResponse.js +42 -8
  27. package/dist/response/redactResponse.js +17 -10
  28. package/dist/routes/agent/authorizeAgent.js +17 -5
  29. package/dist/routes/agent/callAgent.js +12 -2
  30. package/dist/routes/agent/collectChatFiles.js +39 -0
  31. package/dist/routes/agent/prepareAgent.js +29 -4
  32. package/dist/routes/auth/buildAdminPlugin.js +33 -0
  33. package/dist/routes/auth/buildCaptchaPlugin.js +61 -0
  34. package/dist/routes/auth/buildMcpTokenPlugin.js +77 -0
  35. package/dist/routes/auth/buildOauthPostLogin.js +73 -0
  36. package/dist/routes/auth/buildPhoneNumberPlugin.js +57 -0
  37. package/dist/routes/auth/buildProviders.js +61 -0
  38. package/dist/routes/auth/createAsMetadataHandler.js +27 -0
  39. package/dist/routes/auth/createAuthLogger.js +31 -0
  40. package/dist/routes/auth/createMcpAccessTokenClaims.js +52 -0
  41. package/dist/routes/auth/createOnAPIError.js +41 -0
  42. package/dist/routes/auth/createSendEmail.js +54 -0
  43. package/dist/routes/auth/ensureMcpTokenIndexes.js +48 -0
  44. package/dist/routes/auth/getAuthEnforcement.js +41 -0
  45. package/dist/routes/auth/getBetterAuth.js +107 -0
  46. package/dist/routes/auth/getBetterAuthConfig.js +767 -0
  47. package/dist/routes/auth/handleAuthRequest.js +43 -0
  48. package/dist/routes/auth/hooks/authHookPoints.js +204 -0
  49. package/dist/routes/auth/hooks/buildEngineHooks.js +68 -0
  50. package/dist/routes/auth/hooks/buildHooks.js +112 -0
  51. package/dist/routes/auth/{callbacks/addUserFieldsToSession.js → hooks/composeAfterSlot.js} +11 -13
  52. package/dist/routes/auth/hooks/composeBeforeSlot.js +41 -0
  53. package/dist/routes/auth/hooks/createHookDispatch.js +59 -0
  54. package/dist/routes/auth/hooks/createUserAfterHook.js +36 -0
  55. package/dist/routes/auth/hooks/createUserBeforeHook.js +50 -0
  56. package/dist/routes/auth/hooks/findHookUser.js +27 -0
  57. package/dist/routes/auth/modelNames.js +30 -0
  58. package/dist/routes/auth/organizations/OrganizationKeyError.js +28 -0
  59. package/dist/routes/auth/organizations/authorizeRole.js +27 -0
  60. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +178 -0
  61. package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +57 -0
  62. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +120 -0
  63. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +403 -0
  64. package/dist/routes/auth/organizations/createAdmissionGateHook.js +50 -0
  65. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +90 -0
  66. package/dist/routes/auth/organizations/createAutoJoinHook.js +68 -0
  67. package/dist/routes/auth/organizations/createEmailSendGate.js +59 -0
  68. package/dist/routes/auth/organizations/createExpiredInvitationGate.js +76 -0
  69. package/dist/routes/auth/organizations/ensureAuthIndexes.js +122 -0
  70. package/dist/routes/auth/organizations/ensureOrganization.js +132 -0
  71. package/dist/routes/auth/organizations/findPendingInvitation.js +43 -0
  72. package/dist/routes/auth/organizations/getHookRequestHeaders.js +24 -0
  73. package/dist/routes/auth/organizations/getOrganizationBinding.js +65 -0
  74. package/dist/routes/auth/organizations/isEmailAdmitted.js +89 -0
  75. package/dist/routes/auth/organizations/organizationAccessControl.js +94 -0
  76. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +62 -0
  77. package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +145 -0
  78. package/dist/routes/auth/requestHooks/buildRequestHooks.js +288 -0
  79. package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +43 -0
  80. package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +59 -0
  81. package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +47 -0
  82. package/dist/routes/auth/requestHooks/redirectToChallenge.js +79 -0
  83. package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +31 -0
  84. package/dist/routes/auth/resolveCookiePrefix.js +30 -0
  85. package/dist/routes/auth/sanitizeSessionResponse.js +27 -0
  86. package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
  87. package/dist/routes/connections/checkUnwalledReach.js +37 -0
  88. package/dist/routes/connections/getConnectionConfig.js +6 -1
  89. package/dist/routes/connections/resolveTenantPreflight.js +226 -0
  90. package/dist/routes/connections/resolveUnwalledReach.js +144 -0
  91. package/dist/routes/endpoints/acceptDetachedEndpoint.js +50 -0
  92. package/dist/routes/endpoints/authorizeApiEndpoint.js +13 -4
  93. package/dist/routes/endpoints/callEndpoint.js +23 -7
  94. package/dist/routes/endpoints/control/controlFor.js +4 -7
  95. package/dist/routes/endpoints/control/controlIf.js +4 -8
  96. package/dist/routes/endpoints/control/controlLog.js +6 -14
  97. package/dist/routes/endpoints/control/controlParallelFor.js +65 -29
  98. package/dist/routes/endpoints/control/controlReject.js +36 -16
  99. package/dist/routes/endpoints/control/controlReturn.js +32 -9
  100. package/dist/routes/endpoints/control/controlSetState.js +4 -8
  101. package/dist/routes/endpoints/control/controlSwitch.js +4 -8
  102. package/dist/routes/endpoints/control/controlThrow.js +20 -21
  103. package/dist/routes/endpoints/control/controlTry.js +30 -11
  104. package/dist/routes/endpoints/control/controlWhile.js +55 -0
  105. package/dist/routes/endpoints/control/handleControl.js +3 -1
  106. package/dist/routes/endpoints/createWebhookAnswer.js +78 -0
  107. package/dist/routes/endpoints/evaluateRoutineOperators.js +27 -0
  108. package/dist/routes/endpoints/forwardScheduledEndpoint.js +21 -15
  109. package/dist/routes/endpoints/getEndpointConfig.js +18 -8
  110. package/dist/routes/endpoints/getEnvironmentSchedules.js +5 -7
  111. package/dist/routes/endpoints/getSchemaValidator.js +39 -0
  112. package/dist/routes/endpoints/handleAgentCall.js +25 -9
  113. package/dist/routes/endpoints/handleAuthStep.js +214 -0
  114. package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
  115. package/dist/routes/endpoints/handleEndpointCall.js +46 -12
  116. package/dist/routes/endpoints/handleRenderNotification.js +29 -12
  117. package/dist/routes/endpoints/handleRequest.js +13 -6
  118. package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
  119. package/dist/routes/endpoints/handleValidateSchema.js +22 -22
  120. package/dist/routes/endpoints/invokeEndpoint.js +27 -3
  121. package/dist/routes/endpoints/operatorScope.js +28 -0
  122. package/dist/routes/{auth/events/createEventPlugins.js → endpoints/parseWebhookBody.js} +10 -6
  123. package/dist/routes/endpoints/resolveCallBinding.js +91 -0
  124. package/dist/routes/endpoints/resolveCronEnvironment.js +7 -6
  125. package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
  126. package/dist/routes/endpoints/runDetachedEndpoint.js +64 -18
  127. package/dist/routes/endpoints/runRoutine.js +64 -5
  128. package/dist/routes/endpoints/runScheduledEndpoint.js +19 -11
  129. package/dist/routes/endpoints/runWebhookEndpoint.js +70 -23
  130. package/dist/routes/endpoints/runWebhookVerify.js +129 -0
  131. package/dist/routes/endpoints/scheduleBackground.js +10 -0
  132. package/dist/routes/endpoints/test/runTest.js +48 -11
  133. package/dist/routes/endpoints/validatePayload.js +144 -0
  134. package/dist/routes/log/logClientError.js +7 -4
  135. package/dist/routes/mcp/createMcpServer.js +143 -64
  136. package/dist/routes/mcp/getMcpJwks.js +93 -0
  137. package/dist/routes/mcp/getMcpResourceBinding.js +41 -0
  138. package/dist/routes/mcp/getMcpUri.js +69 -0
  139. package/dist/routes/mcp/oauthResourceLifecycle.js +122 -0
  140. package/dist/routes/mcp/runAfterToolCall.js +50 -0
  141. package/dist/routes/notifications/resolveNotificationLinks.js +39 -11
  142. package/dist/routes/page/dynamic/checkDynamicContent.js +81 -0
  143. package/dist/routes/page/dynamic/checkLiteralContent.js +242 -0
  144. package/dist/routes/page/dynamic/createContentError.js +34 -0
  145. package/dist/routes/page/dynamic/flagIconsOutsidePage.js +39 -0
  146. package/dist/routes/page/dynamic/flagTypesOutsidePage.js +44 -0
  147. package/dist/routes/page/dynamic/getPropertiesSchemaErrors.js +35 -0
  148. package/dist/routes/page/dynamic/loadDynamicArtifacts.js +52 -0
  149. package/dist/routes/page/dynamic/policy/checkAction.js +204 -0
  150. package/dist/routes/page/dynamic/policy/checkEvents.js +163 -0
  151. package/dist/routes/page/dynamic/policy/checkPolicy.js +313 -0
  152. package/dist/routes/page/dynamic/policy/checkValue.js +214 -0
  153. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +117 -0
  154. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +54 -0
  155. package/dist/routes/page/dynamic/policy/findSerializerKeys.js +50 -0
  156. package/dist/routes/page/dynamic/policy/isAllowedUrl.js +53 -0
  157. package/dist/routes/{auth/createAdapter.js → page/dynamic/policy/isUnderState.js} +5 -9
  158. package/dist/routes/page/dynamic/policy/normalizeUrlText.js +25 -0
  159. package/dist/routes/page/dynamic/resolveDynamicContent.js +89 -37
  160. package/dist/routes/page/dynamic/unescapeOperators.js +21 -4
  161. package/dist/routes/page/dynamic/validateFragment.js +17 -58
  162. package/dist/routes/page/getPageConfig.js +76 -6
  163. package/dist/routes/request/authorizeRequest.js +21 -6
  164. package/dist/routes/request/callRequest.js +21 -3
  165. package/dist/routes/request/callRequestResolver.js +55 -6
  166. package/dist/routes/request/checkConnectionRead.js +1 -1
  167. package/dist/routes/request/checkConnectionWrite.js +1 -1
  168. package/dist/routes/request/createWalledResolver.js +75 -0
  169. package/dist/routes/request/evaluateOperators.js +8 -12
  170. package/dist/routes/request/getRequestConfig.js +19 -3
  171. package/dist/routes/request/maskCredentialProperties.js +34 -0
  172. package/dist/routes/request/resolveTenancy.js +223 -0
  173. package/dist/routes/request/validateSchemas.js +7 -6
  174. package/dist/routes/{auth/callbacks/createCallbackPlugins.js → rootConfig/getAppEvents.js} +7 -6
  175. package/dist/routes/rootConfig/getHomeAndMenus.js +23 -16
  176. package/dist/routes/{auth/events/createSessionEvent.js → rootConfig/getPagePaths.js} +16 -18
  177. package/dist/routes/rootConfig/getRootConfig.js +9 -3
  178. package/dist/routes/rootConfig/menus/filterMenuList.js +5 -2
  179. package/dist/routes/websocket/authorizeWebsocket.js +19 -4
  180. package/dist/routes/websocket/createChannelRegistry.js +39 -14
  181. package/dist/routes/websocket/createWebSocketConnection.js +162 -28
  182. package/dist/routes/websocket/getCallerFingerprint.js +31 -0
  183. package/dist/routes/websocket/prepareChannel.js +29 -1
  184. package/dist/routes/websocket/resolveWebsocketCaller.js +40 -0
  185. package/dist/test/testContext.js +16 -11
  186. package/package.json +28 -12
  187. package/dist/context/createAuthorize.js +0 -45
  188. package/dist/response/omitErrorProps.js +0 -51
  189. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +0 -30
  190. package/dist/routes/auth/callbacks/createCallbacks.js +0 -46
  191. package/dist/routes/auth/callbacks/createJWTCallback.js +0 -77
  192. package/dist/routes/auth/callbacks/createRedirectCallback.js +0 -41
  193. package/dist/routes/auth/callbacks/createSessionCallback.js +0 -81
  194. package/dist/routes/auth/callbacks/createSignInCallback.js +0 -40
  195. package/dist/routes/auth/callbacks/validateSessionRoles.js +0 -33
  196. package/dist/routes/auth/createLogger.js +0 -35
  197. package/dist/routes/auth/createPrefixedCookies.js +0 -52
  198. package/dist/routes/auth/createProviders.js +0 -25
  199. package/dist/routes/auth/events/createCreateUserEvent.js +0 -41
  200. package/dist/routes/auth/events/createEvents.js +0 -56
  201. package/dist/routes/auth/events/createLinkAccountEvent.js +0 -43
  202. package/dist/routes/auth/events/createSignInEvent.js +0 -46
  203. package/dist/routes/auth/events/createSignOutEvent.js +0 -43
  204. package/dist/routes/auth/events/createUpdateUserEvent.js +0 -41
  205. package/dist/routes/auth/getAuthConfig.js +0 -86
  206. package/dist/routes/auth/resolveCookies.js +0 -37
  207. package/dist/routes/log/formatValidationError.js +0 -31
  208. /package/dist/{routes/notifications → email}/resolveThemeLogo.js +0 -0
@@ -0,0 +1,41 @@
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 engine retains the MCP resource URI per auth instance. The /api/mcp
17
+ // bearer-token guard reads it synchronously at request time as the audience
18
+ // a presented token must carry, and the resource-row ensure reads it as the
19
+ // row identifier. Registered at startup only when the app is configured as an
20
+ // authorization server (auth.oauthProvider), so a null binding means the MCP
21
+ // OAuth surface is off.
22
+ const bindingByAuth = new WeakMap();
23
+ function registerMcpResourceBinding({ auth, resourceUri }) {
24
+ bindingByAuth.set(auth, {
25
+ resourceUri
26
+ });
27
+ }
28
+ function getMcpResourceBinding({ auth }) {
29
+ if (type.isNone(auth)) {
30
+ return null;
31
+ }
32
+ const binding = bindingByAuth.get(auth);
33
+ if (type.isNone(binding)) {
34
+ return null;
35
+ }
36
+ return {
37
+ resourceUri: binding.resourceUri
38
+ };
39
+ }
40
+ export { registerMcpResourceBinding };
41
+ export default getMcpResourceBinding;
@@ -0,0 +1,69 @@
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 getCanonicalUrl from '../../context/getCanonicalUrl.js';
16
+ // The OAuth URI templates for the MCP protected resource live together here
17
+ // so the resource identifier, the aud check, the RFC 9728 metadata, and the
18
+ // WWW-Authenticate challenge can never drift apart. There is ONE MCP resource
19
+ // per deployment - the organization a token acts in is a claim the
20
+ // authorization server stamps at consent time, not a path segment.
21
+ // The origin always comes from the pinned canonical URL (BETTER_AUTH_URL, else the current
22
+ // environment's url) - never a Host header, which is caller-controlled.
23
+ function getCanonicalOrigin({ config }) {
24
+ const canonicalUrl = getCanonicalUrl({
25
+ config
26
+ });
27
+ if (canonicalUrl === null) {
28
+ return null;
29
+ }
30
+ return canonicalUrl.replace(/\/$/, '');
31
+ }
32
+ // The resource identifier (RFC 8707) every MCP access token is minted for,
33
+ // and the audience the /api/mcp route verifies against.
34
+ function getMcpResourceUri({ config }) {
35
+ const canonicalUrl = getCanonicalOrigin({
36
+ config
37
+ });
38
+ if (canonicalUrl === null) {
39
+ return null;
40
+ }
41
+ return `${canonicalUrl}${config.basePath ?? ''}/api/mcp`;
42
+ }
43
+ // The authorization server's issuer identifier - what it stamps on iss and
44
+ // its metadata issuer. Carries the /api/auth suffix (BetterAuth baseURL +
45
+ // auth basePath), distinct from the MCP resource URI, and not the bare
46
+ // origin.
47
+ function getAsIssuer({ config }) {
48
+ const canonicalUrl = getCanonicalOrigin({
49
+ config
50
+ });
51
+ if (canonicalUrl === null) {
52
+ return null;
53
+ }
54
+ return `${canonicalUrl}${config.basePath ?? ''}/api/auth`;
55
+ }
56
+ // The RFC 9728 metadata location for the resource - the well-known segment
57
+ // sits after the app basePath, where the servers mount the metadata route.
58
+ // Both the WWW-Authenticate challenge and the served document derive from
59
+ // here, so the pointer and its target cannot drift apart.
60
+ function getMcpResourceMetadataUri({ config }) {
61
+ const canonicalUrl = getCanonicalOrigin({
62
+ config
63
+ });
64
+ if (canonicalUrl === null) {
65
+ return null;
66
+ }
67
+ return `${canonicalUrl}${config.basePath ?? ''}/.well-known/oauth-protected-resource/api/mcp`;
68
+ }
69
+ export { getMcpResourceUri, getMcpResourceMetadataUri, getAsIssuer };
@@ -0,0 +1,122 @@
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 getMcpResourceBinding from './getMcpResourceBinding.js';
17
+ // Lifecycle of the one oauthResource row the authorization server validates
18
+ // MCP token audiences against. The resource is a property of the deployment,
19
+ // not of an organization - which organization a token acts in is a claim
20
+ // stamped at consent time - so a single row, identified by the canonical
21
+ // resource URI, is ensured once per process. The row is owned by this code;
22
+ // the oauth-provider's HTTP resource CRUD is closed (resourcePrivileges:
23
+ // () => false). The write follows the plugin's insertOnly seed stance: insert
24
+ // a missing row, never revert an existing one, so a row an operator disabled
25
+ // stays disabled through restarts. No-ops when no MCP resource binding is
26
+ // registered (the app is not an authorization server), and never throws into
27
+ // the request path that awaits it.
28
+ const model = 'oauthResource';
29
+ // Mirrors the oauth-provider's own seed row (buildSeedRow at 1.7.0): null
30
+ // policy columns mean "inherit the plugin-level default at issuance time".
31
+ function buildResourceRow({ identifier }) {
32
+ const now = new Date();
33
+ return {
34
+ identifier,
35
+ name: identifier,
36
+ accessTokenTtl: null,
37
+ refreshTokenTtl: null,
38
+ signingAlgorithm: null,
39
+ signingKeyId: null,
40
+ allowedScopes: null,
41
+ customClaims: null,
42
+ dpopBoundAccessTokensRequired: false,
43
+ disabled: false,
44
+ policyVersion: 1,
45
+ metadata: null,
46
+ createdAt: now,
47
+ updatedAt: now
48
+ };
49
+ }
50
+ async function insertResourceRowIfMissing({ adapter, identifier }) {
51
+ const existing = await adapter.findOne({
52
+ model,
53
+ where: [
54
+ {
55
+ field: 'identifier',
56
+ value: identifier
57
+ }
58
+ ]
59
+ });
60
+ // An existing row is never reverted - re-enabling a disabled row here would
61
+ // silently undo a deliberate operator disable on every restart.
62
+ if (existing) {
63
+ return;
64
+ }
65
+ try {
66
+ await adapter.create({
67
+ model,
68
+ data: buildResourceRow({
69
+ identifier
70
+ })
71
+ });
72
+ } catch (error) {
73
+ // A racing process inserted the row between the find and the create - the
74
+ // unique identifier index rejected this write, so the wanted row exists.
75
+ const winner = await adapter.findOne({
76
+ model,
77
+ where: [
78
+ {
79
+ field: 'identifier',
80
+ value: identifier
81
+ }
82
+ ]
83
+ });
84
+ if (!winner) {
85
+ throw error;
86
+ }
87
+ }
88
+ }
89
+ const ensuredByAuth = new WeakMap();
90
+ // Awaited per request in the api-context middleware, so it is memoized like
91
+ // resolvePinnedOrganization: after the first success it awaits an
92
+ // already-settled promise.
93
+ async function ensureMcpOauthResource({ auth, logger }) {
94
+ const binding = getMcpResourceBinding({
95
+ auth
96
+ });
97
+ if (type.isNone(binding)) {
98
+ return;
99
+ }
100
+ let promise = ensuredByAuth.get(auth);
101
+ if (type.isNone(promise)) {
102
+ promise = auth.$context.then(({ adapter })=>insertResourceRowIfMissing({
103
+ adapter,
104
+ identifier: binding.resourceUri
105
+ })).catch((error)=>{
106
+ // Do not memoize a failure - the next request retries.
107
+ ensuredByAuth.delete(auth);
108
+ throw error;
109
+ });
110
+ ensuredByAuth.set(auth, promise);
111
+ }
112
+ try {
113
+ await promise;
114
+ } catch (error) {
115
+ // A briefly unreachable database must not fail every request from the
116
+ // middleware - requests keep serving and the next one retries.
117
+ logger.warn({
118
+ err: error
119
+ }, `Failed to ensure the oauthResource row "${binding.resourceUri}" for the MCP resource.`);
120
+ }
121
+ }
122
+ export { ensureMcpOauthResource };
@@ -0,0 +1,50 @@
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 invokeEndpoint from '../endpoints/invokeEndpoint.js';
16
+ // Runs the app's mcp.afterToolCall endpoint as the tool's caller, after the
17
+ // 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.
20
+ // Awaited by the caller rather than left running: a serverless platform may
21
+ // reap the invocation once the response is sent.
22
+ async function runAfterToolCall(context, { hookId, payload }) {
23
+ const { logger } = context;
24
+ try {
25
+ const result = await invokeEndpoint(context, {
26
+ endpointId: hookId,
27
+ payload,
28
+ endpointDepth: 0
29
+ });
30
+ if ([
31
+ 'error',
32
+ 'reject'
33
+ ].includes(result.status)) {
34
+ logger.warn({
35
+ event: 'warn_mcp_after_tool_call',
36
+ hook: hookId,
37
+ tool: payload.tool,
38
+ status: result.status
39
+ }, `MCP afterToolCall hook "${hookId}" failed after tool "${payload.tool}": ${result.error?.message}`);
40
+ }
41
+ } catch (error) {
42
+ logger.warn({
43
+ event: 'warn_mcp_after_tool_call',
44
+ hook: hookId,
45
+ tool: payload.tool,
46
+ err: error
47
+ }, `MCP afterToolCall hook "${hookId}" failed after tool "${payload.tool}": ${error.message}`);
48
+ }
49
+ }
50
+ export default runAfterToolCall;
@@ -12,18 +12,31 @@
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 { serializer, type, urlQuery } from '@lowdefy/helpers';
16
- function resolveLinkValue({ link, option, serverUrl, basePath, landingPage, recordId }) {
15
+ */ import { buildPagePath, serializer, type, urlQuery } from '@lowdefy/helpers';
16
+ function pagePathFor({ pageId, pathParams, routes }) {
17
+ const route = routes.find((candidate)=>candidate.pageId === pageId);
18
+ return buildPagePath({
19
+ pageId,
20
+ path: route?.path,
21
+ pathParams
22
+ });
23
+ }
24
+ function resolveLinkValue({ link, option, serverUrl, basePath, landingPath, recordId, routes }) {
17
25
  // Absolute URLs pass through — links into other apps or external destinations.
18
26
  // They skip any landing page, so they carry no mark-as-read.
19
27
  if (type.isString(link)) {
20
28
  return link;
21
29
  }
22
30
  if (type.isObject(link) && !type.isNone(link.pageId)) {
23
- if (type.isNone(landingPage)) {
31
+ if (type.isNone(landingPath)) {
24
32
  // No landing page configured — link straight to the target page.
33
+ const pagePath = pagePathFor({
34
+ pageId: link.pageId,
35
+ pathParams: link.pathParams,
36
+ routes
37
+ });
25
38
  const query = urlQuery.stringify(link.urlQuery ?? {});
26
- return `${serverUrl}${basePath}/${link.pageId}${query ? `?${query}` : ''}`;
39
+ return `${serverUrl}${basePath}/${pagePath}${query ? `?${query}` : ''}`;
27
40
  }
28
41
  // The option query param is the dot-path of the link inside the record's
29
42
  // data — the landing page reads the original target back with
@@ -32,25 +45,39 @@ function resolveLinkValue({ link, option, serverUrl, basePath, landingPage, reco
32
45
  _id: recordId,
33
46
  option
34
47
  });
35
- return `${serverUrl}${basePath}${landingPage}?${query}`;
48
+ return `${serverUrl}${basePath}/${landingPath}?${query}`;
36
49
  }
37
50
  return link;
38
51
  }
39
52
  // Resolves link values in a copy of the data item to URLs; the stored record
40
- // keeps the original { pageId, urlQuery } objects for in-app navigation.
53
+ // keeps the original { pageId, urlQuery, pathParams } objects for in-app navigation.
41
54
  // data.links is the framework convention; link fields inside arrays are
42
55
  // resolved for the data keys the template declares (Template.dataKeys), so
43
56
  // custom templates get the same treatment as the built-in ones.
44
- function resolveNotificationLinks({ item, dataKeys, serverUrl, basePath, landingPage, recordId }) {
57
+ // routes is the build's routes.json; a link's page path is its pattern there.
58
+ // landingPage is a page id, or { pageId, pathParams }; its path is built from the same table.
59
+ function resolveNotificationLinks({ item, dataKeys, serverUrl, basePath, landingPage, recordId, routes }) {
45
60
  const resolved = serializer.copy(item);
61
+ let landingPath;
62
+ if (!type.isNone(landingPage)) {
63
+ const landing = type.isString(landingPage) ? {
64
+ pageId: landingPage
65
+ } : landingPage;
66
+ landingPath = pagePathFor({
67
+ pageId: landing.pageId,
68
+ pathParams: landing.pathParams,
69
+ routes
70
+ });
71
+ }
46
72
  Object.keys(resolved.links ?? {}).forEach((key)=>{
47
73
  resolved.links[key] = resolveLinkValue({
48
74
  link: resolved.links[key],
49
75
  option: `links.${key}`,
50
76
  serverUrl,
51
77
  basePath,
52
- landingPage,
53
- recordId
78
+ landingPath,
79
+ recordId,
80
+ routes
54
81
  });
55
82
  });
56
83
  (dataKeys ?? []).forEach((arrayKey)=>{
@@ -62,8 +89,9 @@ function resolveNotificationLinks({ item, dataKeys, serverUrl, basePath, landing
62
89
  option: `${arrayKey}.${index}.link`,
63
90
  serverUrl,
64
91
  basePath,
65
- landingPage,
66
- recordId
92
+ landingPath,
93
+ recordId,
94
+ routes
67
95
  });
68
96
  });
69
97
  });
@@ -0,0 +1,81 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { ConfigError } from '@lowdefy/errors';
16
+ import checkPolicy from './policy/checkPolicy.js';
17
+ import validateFragment from './validateFragment.js';
18
+ // The one checker behind both the ValidateDynamic step and page get. Policy
19
+ // rules run first on the content as submitted and collect every violation;
20
+ // when they pass, the content goes through the same block build and fragment
21
+ // validation every Dynamic block gets. Returns { errors } on failure, or the
22
+ // built fragment. buildBlock mutates the content, so callers pass their own copy.
23
+ async function checkDynamicContent(context, { artifacts, blocks, dynamicBlockId, idPrefix, pageId, pageRequests, policy, usedTypes }) {
24
+ if (policy) {
25
+ const errors = checkPolicy({
26
+ blocks,
27
+ policy,
28
+ blockMetas: artifacts.blockMetas,
29
+ blockSchemas: artifacts.blockSchemas,
30
+ clientOperators: artifacts.clientOperators,
31
+ routes: artifacts.routes
32
+ });
33
+ if (errors.length > 0) {
34
+ return {
35
+ errors
36
+ };
37
+ }
38
+ }
39
+ try {
40
+ const built = artifacts.buildDynamicBlocks({
41
+ blocks,
42
+ pageId,
43
+ dynamicBlockId,
44
+ idPrefix,
45
+ types: artifacts.types,
46
+ blockMetas: artifacts.blockMetas,
47
+ clientOperators: artifacts.clientOperators,
48
+ dynamicPolicies: artifacts.dynamicPolicies,
49
+ policy,
50
+ usedTypes
51
+ });
52
+ await validateFragment(context, {
53
+ blocks: built.blocks,
54
+ blockSchemas: artifacts.blockSchemas,
55
+ callApiActionRefs: built.callApiActionRefs,
56
+ dynamicBlockId,
57
+ pageId,
58
+ pageRequests,
59
+ requestActionRefs: built.requestActionRefs
60
+ });
61
+ return {
62
+ errors: [],
63
+ ...built
64
+ };
65
+ } catch (error) {
66
+ if (!(error instanceof ConfigError)) {
67
+ throw error;
68
+ }
69
+ return {
70
+ errors: [
71
+ {
72
+ path: 'blocks',
73
+ rule: 'build',
74
+ message: error.message,
75
+ cause: error
76
+ }
77
+ ]
78
+ };
79
+ }
80
+ }
81
+ export default checkDynamicContent;