@lowdefy/api 6.1.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 (195) 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 +8 -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/isSameOriginRequest.js +85 -0
  10. package/dist/context/isWebSocketOriginAllowed.js +63 -0
  11. package/dist/context/normalizeInjectedCaller.js +58 -0
  12. package/dist/context/parseRequestBody.js +32 -0
  13. package/dist/context/readMemberships.js +71 -0
  14. package/dist/context/resolveAuthentication.js +758 -0
  15. package/dist/context/resolveStrategyCaller.js +7 -3
  16. package/dist/csp/addNonceToElements.js +23 -0
  17. package/dist/csp/createContentSecurityPolicy.js +45 -0
  18. package/dist/csp/getWebSocketSources.js +36 -0
  19. package/dist/email/renderAuthEmail.js +99 -0
  20. package/dist/index.js +21 -5
  21. package/dist/response/formatErrorForAgent.js +35 -0
  22. package/dist/response/redactResponse.js +8 -1
  23. package/dist/routes/agent/authorizeAgent.js +17 -5
  24. package/dist/routes/agent/callAgent.js +12 -2
  25. package/dist/routes/agent/collectChatFiles.js +39 -0
  26. package/dist/routes/agent/prepareAgent.js +23 -4
  27. package/dist/routes/auth/buildAdminPlugin.js +33 -0
  28. package/dist/routes/auth/buildCaptchaPlugin.js +61 -0
  29. package/dist/routes/auth/buildMcpTokenPlugin.js +77 -0
  30. package/dist/routes/auth/buildOauthPostLogin.js +73 -0
  31. package/dist/routes/auth/buildPhoneNumberPlugin.js +57 -0
  32. package/dist/routes/auth/buildProviders.js +61 -0
  33. package/dist/routes/auth/createAsMetadataHandler.js +27 -0
  34. package/dist/routes/auth/createAuthLogger.js +31 -0
  35. package/dist/routes/auth/createMcpAccessTokenClaims.js +52 -0
  36. package/dist/routes/auth/createOnAPIError.js +41 -0
  37. package/dist/routes/auth/createSendEmail.js +54 -0
  38. package/dist/routes/auth/ensureMcpTokenIndexes.js +48 -0
  39. package/dist/routes/auth/getAuthEnforcement.js +41 -0
  40. package/dist/routes/auth/getBetterAuth.js +107 -0
  41. package/dist/routes/auth/getBetterAuthConfig.js +767 -0
  42. package/dist/routes/auth/handleAuthRequest.js +43 -0
  43. package/dist/routes/auth/hooks/authHookPoints.js +204 -0
  44. package/dist/routes/auth/hooks/buildEngineHooks.js +68 -0
  45. package/dist/routes/auth/hooks/buildHooks.js +112 -0
  46. package/dist/routes/auth/{callbacks/addUserFieldsToSession.js → hooks/composeAfterSlot.js} +11 -13
  47. package/dist/routes/auth/hooks/composeBeforeSlot.js +41 -0
  48. package/dist/routes/auth/hooks/createHookDispatch.js +59 -0
  49. package/dist/routes/auth/hooks/createUserAfterHook.js +36 -0
  50. package/dist/routes/auth/hooks/createUserBeforeHook.js +50 -0
  51. package/dist/routes/auth/hooks/findHookUser.js +27 -0
  52. package/dist/routes/auth/modelNames.js +30 -0
  53. package/dist/routes/auth/organizations/OrganizationKeyError.js +28 -0
  54. package/dist/routes/auth/organizations/authorizeRole.js +27 -0
  55. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +178 -0
  56. package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +57 -0
  57. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +120 -0
  58. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +403 -0
  59. package/dist/routes/auth/organizations/createAdmissionGateHook.js +50 -0
  60. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +90 -0
  61. package/dist/routes/auth/organizations/createAutoJoinHook.js +68 -0
  62. package/dist/routes/auth/organizations/createEmailSendGate.js +59 -0
  63. package/dist/routes/auth/organizations/createExpiredInvitationGate.js +76 -0
  64. package/dist/routes/auth/organizations/ensureAuthIndexes.js +122 -0
  65. package/dist/routes/auth/organizations/ensureOrganization.js +132 -0
  66. package/dist/routes/auth/organizations/findPendingInvitation.js +43 -0
  67. package/dist/routes/auth/organizations/getHookRequestHeaders.js +24 -0
  68. package/dist/routes/auth/organizations/getOrganizationBinding.js +65 -0
  69. package/dist/routes/auth/organizations/isEmailAdmitted.js +89 -0
  70. package/dist/routes/auth/organizations/organizationAccessControl.js +94 -0
  71. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +62 -0
  72. package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +145 -0
  73. package/dist/routes/auth/requestHooks/buildRequestHooks.js +288 -0
  74. package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +43 -0
  75. package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +59 -0
  76. package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +47 -0
  77. package/dist/routes/auth/requestHooks/redirectToChallenge.js +79 -0
  78. package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +31 -0
  79. package/dist/routes/auth/resolveCookiePrefix.js +30 -0
  80. package/dist/routes/auth/sanitizeSessionResponse.js +27 -0
  81. package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
  82. package/dist/routes/connections/checkUnwalledReach.js +37 -0
  83. package/dist/routes/connections/getConnectionConfig.js +6 -1
  84. package/dist/routes/connections/resolveTenantPreflight.js +226 -0
  85. package/dist/routes/connections/resolveUnwalledReach.js +144 -0
  86. package/dist/routes/endpoints/acceptDetachedEndpoint.js +50 -0
  87. package/dist/routes/endpoints/authorizeApiEndpoint.js +13 -4
  88. package/dist/routes/endpoints/callEndpoint.js +22 -7
  89. package/dist/routes/endpoints/control/controlParallelFor.js +61 -22
  90. package/dist/routes/endpoints/control/controlReject.js +23 -1
  91. package/dist/routes/endpoints/control/controlReturn.js +29 -1
  92. package/dist/routes/endpoints/control/controlThrow.js +3 -2
  93. package/dist/routes/endpoints/control/controlTry.js +10 -1
  94. package/dist/routes/endpoints/control/controlWhile.js +55 -0
  95. package/dist/routes/endpoints/control/handleControl.js +3 -1
  96. package/dist/routes/endpoints/createWebhookAnswer.js +78 -0
  97. package/dist/routes/endpoints/evaluateRoutineOperators.js +2 -1
  98. package/dist/routes/endpoints/forwardScheduledEndpoint.js +3 -2
  99. package/dist/routes/endpoints/getEndpointConfig.js +18 -8
  100. package/dist/routes/endpoints/getSchemaValidator.js +39 -0
  101. package/dist/routes/endpoints/handleAgentCall.js +21 -2
  102. package/dist/routes/endpoints/handleAuthStep.js +214 -0
  103. package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
  104. package/dist/routes/endpoints/handleEndpointCall.js +43 -6
  105. package/dist/routes/endpoints/handleRenderNotification.js +14 -4
  106. package/dist/routes/endpoints/handleRequest.js +12 -1
  107. package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
  108. package/dist/routes/endpoints/handleValidateSchema.js +13 -15
  109. package/dist/routes/endpoints/invokeEndpoint.js +26 -3
  110. package/dist/routes/endpoints/operatorScope.js +2 -1
  111. package/dist/routes/{auth/callbacks/createCallbackPlugins.js → endpoints/parseWebhookBody.js} +10 -6
  112. package/dist/routes/endpoints/resolveCallBinding.js +91 -0
  113. package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
  114. package/dist/routes/endpoints/runDetachedEndpoint.js +63 -18
  115. package/dist/routes/endpoints/runRoutine.js +64 -5
  116. package/dist/routes/endpoints/runScheduledEndpoint.js +18 -11
  117. package/dist/routes/endpoints/runWebhookEndpoint.js +69 -23
  118. package/dist/routes/endpoints/runWebhookVerify.js +129 -0
  119. package/dist/routes/endpoints/scheduleBackground.js +10 -0
  120. package/dist/routes/endpoints/test/runTest.js +31 -9
  121. package/dist/routes/endpoints/validatePayload.js +144 -0
  122. package/dist/routes/log/logClientError.js +7 -4
  123. package/dist/routes/mcp/createMcpServer.js +143 -82
  124. package/dist/routes/mcp/getMcpJwks.js +93 -0
  125. package/dist/routes/mcp/getMcpResourceBinding.js +41 -0
  126. package/dist/routes/mcp/getMcpUri.js +69 -0
  127. package/dist/routes/mcp/oauthResourceLifecycle.js +122 -0
  128. package/dist/routes/mcp/runAfterToolCall.js +50 -0
  129. package/dist/routes/notifications/resolveNotificationLinks.js +39 -11
  130. package/dist/routes/page/dynamic/checkDynamicContent.js +81 -0
  131. package/dist/routes/page/dynamic/checkLiteralContent.js +242 -0
  132. package/dist/routes/page/dynamic/createContentError.js +34 -0
  133. package/dist/routes/page/dynamic/flagIconsOutsidePage.js +39 -0
  134. package/dist/routes/page/dynamic/flagTypesOutsidePage.js +44 -0
  135. package/dist/routes/page/dynamic/getPropertiesSchemaErrors.js +35 -0
  136. package/dist/routes/page/dynamic/loadDynamicArtifacts.js +52 -0
  137. package/dist/routes/page/dynamic/policy/checkAction.js +204 -0
  138. package/dist/routes/page/dynamic/policy/checkEvents.js +163 -0
  139. package/dist/routes/page/dynamic/policy/checkPolicy.js +313 -0
  140. package/dist/routes/page/dynamic/policy/checkValue.js +214 -0
  141. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +117 -0
  142. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +54 -0
  143. package/dist/routes/page/dynamic/policy/findSerializerKeys.js +50 -0
  144. package/dist/routes/page/dynamic/policy/isAllowedUrl.js +53 -0
  145. package/dist/routes/{auth/createAdapter.js → page/dynamic/policy/isUnderState.js} +5 -9
  146. package/dist/routes/page/dynamic/policy/normalizeUrlText.js +25 -0
  147. package/dist/routes/page/dynamic/resolveDynamicContent.js +89 -37
  148. package/dist/routes/page/dynamic/unescapeOperators.js +21 -4
  149. package/dist/routes/page/dynamic/validateFragment.js +17 -58
  150. package/dist/routes/page/getPageConfig.js +76 -6
  151. package/dist/routes/request/authorizeRequest.js +21 -6
  152. package/dist/routes/request/callRequest.js +22 -10
  153. package/dist/routes/request/callRequestResolver.js +49 -6
  154. package/dist/routes/request/checkConnectionRead.js +1 -1
  155. package/dist/routes/request/checkConnectionWrite.js +1 -1
  156. package/dist/routes/request/createWalledResolver.js +75 -0
  157. package/dist/routes/request/getRequestConfig.js +19 -3
  158. package/dist/routes/request/maskCredentialProperties.js +34 -0
  159. package/dist/routes/request/resolveTenancy.js +223 -0
  160. package/dist/routes/request/validateSchemas.js +7 -6
  161. package/dist/routes/{auth/events/createEventPlugins.js → rootConfig/getAppEvents.js} +7 -6
  162. package/dist/routes/rootConfig/getHomeAndMenus.js +23 -16
  163. package/dist/routes/{auth/events/createSessionEvent.js → rootConfig/getPagePaths.js} +16 -18
  164. package/dist/routes/rootConfig/getRootConfig.js +9 -3
  165. package/dist/routes/rootConfig/menus/filterMenuList.js +5 -2
  166. package/dist/routes/websocket/authorizeWebsocket.js +19 -4
  167. package/dist/routes/websocket/createChannelRegistry.js +20 -9
  168. package/dist/routes/websocket/createWebSocketConnection.js +150 -28
  169. package/dist/routes/websocket/getCallerFingerprint.js +31 -0
  170. package/dist/routes/websocket/prepareChannel.js +29 -1
  171. package/dist/routes/websocket/resolveWebsocketCaller.js +40 -0
  172. package/dist/test/testContext.js +13 -10
  173. package/package.json +28 -12
  174. package/dist/context/createAuthorize.js +0 -45
  175. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +0 -30
  176. package/dist/routes/auth/callbacks/createCallbacks.js +0 -46
  177. package/dist/routes/auth/callbacks/createJWTCallback.js +0 -77
  178. package/dist/routes/auth/callbacks/createRedirectCallback.js +0 -41
  179. package/dist/routes/auth/callbacks/createSessionCallback.js +0 -81
  180. package/dist/routes/auth/callbacks/createSignInCallback.js +0 -40
  181. package/dist/routes/auth/callbacks/validateSessionRoles.js +0 -33
  182. package/dist/routes/auth/createLogger.js +0 -35
  183. package/dist/routes/auth/createPrefixedCookies.js +0 -52
  184. package/dist/routes/auth/createProviders.js +0 -25
  185. package/dist/routes/auth/defaultAuthUrl.js +0 -31
  186. package/dist/routes/auth/events/createCreateUserEvent.js +0 -41
  187. package/dist/routes/auth/events/createEvents.js +0 -56
  188. package/dist/routes/auth/events/createLinkAccountEvent.js +0 -43
  189. package/dist/routes/auth/events/createSignInEvent.js +0 -46
  190. package/dist/routes/auth/events/createSignOutEvent.js +0 -43
  191. package/dist/routes/auth/events/createUpdateUserEvent.js +0 -41
  192. package/dist/routes/auth/getAuthConfig.js +0 -90
  193. package/dist/routes/auth/resolveCookies.js +0 -37
  194. package/dist/routes/log/formatValidationError.js +0 -31
  195. /package/dist/{routes/notifications → email}/resolveThemeLogo.js +0 -0
@@ -0,0 +1,79 @@
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
+ // Last-resort base for parsing only, reached only when neither BETTER_AUTH_URL
17
+ // nor the per-request base URL yields an origin. new URL needs an absolute base
18
+ // to resolve a path-relative twoFactorPageUrl. It is never emitted: the return
19
+ // strips back to pathname + search whenever baseUrlOrigin is absent.
20
+ const PARSE_ONLY_ORIGIN = 'http://lowdefy.invalid';
21
+ // The origin the pending destination is judged same-origin against.
22
+ // BETTER_AUTH_URL pins it when set; otherwise the endpoint has already derived
23
+ // one from the request and left it on ctx.context.baseURL - the very origin it
24
+ // resolved its own redirect against, so comparing against it is exact rather
25
+ // than approximate.
26
+ //
27
+ // This is load-bearing on the zero-config path rather than a tidy-up.
28
+ // /magic-link/verify resolves its destination to an absolute URL
29
+ // (`new URL(callbackURL, ctx.context.baseURL)`) and redirects there, so judging
30
+ // that against a placeholder origin would rule every same-origin deep link
31
+ // off-origin and silently drop it - the deployment keeps its challenge and
32
+ // loses every deep link, with nothing logged.
33
+ function resolveCompareOrigin({ baseUrlOrigin, ctx }) {
34
+ if (type.isString(baseUrlOrigin)) {
35
+ return baseUrlOrigin;
36
+ }
37
+ const requestBaseUrl = ctx.context.baseURL;
38
+ if (type.isString(requestBaseUrl) && URL.canParse(requestBaseUrl)) {
39
+ return new URL(requestBaseUrl).origin;
40
+ }
41
+ return PARSE_ONLY_ORIGIN;
42
+ }
43
+ // The redirect exit for an intercepted sign-in: sends the browser to the
44
+ // challenge page carrying the destination the user was actually headed for, so
45
+ // an enrolled user clicking an emailed link to /invoices/123 is not dumped on
46
+ // whatever the challenge page defaults to.
47
+ //
48
+ // The destination is read off the pending redirect rather than the request: the
49
+ // endpoint has already resolved wherever it was going to send them - magic link
50
+ // from ctx.query.callbackURL, an OAuth callback from the OAuth state - and left
51
+ // it on the response headers, so one rule covers every redirect path.
52
+ //
53
+ // Same-origin, path-only. The challenge page is public and its query is
54
+ // attacker-suppliable, so an off-origin destination is dropped rather than
55
+ // carried: handing control to another origin after a completed challenge is not
56
+ // a capability anyone asked for. Taking pathname + search off a parsed URL also
57
+ // rules out a protocol-relative "//evil.com", which a startsWith('/') check
58
+ // would wave through.
59
+ //
60
+ // No parameter is emitted when there is nothing to carry - /magic-link/verify
61
+ // answers with JSON instead of redirecting when no callbackURL was given, so
62
+ // there is no pending location - and the challenge page then falls back to its
63
+ // own default.
64
+ function redirectToChallenge({ baseUrlOrigin, ctx, twoFactorPageUrl }) {
65
+ const compareOrigin = resolveCompareOrigin({
66
+ baseUrlOrigin,
67
+ ctx
68
+ });
69
+ const url = new URL(twoFactorPageUrl, compareOrigin);
70
+ const pending = ctx.context.responseHeaders?.get('location');
71
+ if (type.isString(pending)) {
72
+ const target = new URL(pending, compareOrigin);
73
+ if (target.origin === url.origin) {
74
+ url.searchParams.set('callbackUrl', `${target.pathname}${target.search}`);
75
+ }
76
+ }
77
+ throw ctx.redirect(type.isString(baseUrlOrigin) ? url.toString() : `${url.pathname}${url.search}`);
78
+ }
79
+ export default redirectToChallenge;
@@ -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
+ */ import { type } from '@lowdefy/helpers';
16
+ // Where a two-factor challenge sends the browser. Absolute when the auth base
17
+ // URL is pinned, path-relative otherwise - the same rule onAPIError.errorURL
18
+ // follows, so both redirect targets behave alike when no origin is known.
19
+ //
20
+ // undefined means no challenge page is configured, which build validation only
21
+ // permits when twoFactor is off - so callers read undefined as "no interception
22
+ // to register" rather than as a misconfiguration to report.
23
+ function resolveTwoFactorPageUrl({ authConfig, basePath = '', baseUrlOrigin }) {
24
+ const page = authConfig.authPages?.twoFactor;
25
+ if (!type.isString(page)) {
26
+ return undefined;
27
+ }
28
+ const path = `${basePath}${page}`;
29
+ return type.isString(baseUrlOrigin) ? `${baseUrlOrigin}${path}` : path;
30
+ }
31
+ export default resolveTwoFactorPageUrl;
@@ -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
+ */ function slugifyPrefix(value) {
16
+ return String(value).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
17
+ }
18
+ // Lowdefy sets the cookie name prefix - it is not app-configurable. In dev,
19
+ // the prefix is derived from the app so multiple local apps on different
20
+ // ports do not collide on cookies (browsers do not scope cookies by port).
21
+ function resolveCookiePrefix({ appMeta, dev }) {
22
+ if (dev) {
23
+ const appIdentifier = appMeta?.slug ?? appMeta?.name;
24
+ if (appIdentifier) {
25
+ return `lowdefy-${slugifyPrefix(appIdentifier)}`;
26
+ }
27
+ }
28
+ return 'lowdefy';
29
+ }
30
+ export default resolveCookiePrefix;
@@ -0,0 +1,27 @@
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 token is the credential half of the httpOnly session cookie. BetterAuth's
16
+ // default /get-session body ships it to client JS, which Lowdefy is cookie-based
17
+ // and never reads - so drop it and keep the rest of the session (id, expiresAt,
18
+ // activeOrganizationId, ...) intact. Fed to the customSession plugin, whose
19
+ // return value becomes the entire /get-session response.
20
+ function sanitizeSessionResponse({ user, session }) {
21
+ const { token, ...safeSession } = session ?? {};
22
+ return {
23
+ user,
24
+ session: safeSession
25
+ };
26
+ }
27
+ export default sanitizeSessionResponse;
@@ -15,7 +15,7 @@
15
15
  */ import createAuthStrategies from './createAuthStrategies.js';
16
16
  let strategies;
17
17
  // The strategy verifiers are constructed once per process at first use -
18
- // the server middleware tries them in config order on every request that
18
+ // resolveAuthentication tries them in config order on every request that
19
19
  // resolves no session.
20
20
  function getAuthStrategies({ appMeta, authJson, logger, plugins, secrets }) {
21
21
  if (strategies) return strategies;
@@ -0,0 +1,37 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { ConfigError } from '@lowdefy/errors';
16
+ import resolveUnwalledReach from './resolveUnwalledReach.js';
17
+ // Refuses a request on an unwalled connection that holds a URI to a walled
18
+ // database (resolveUnwalledReach). Only that connection's requests fail: the
19
+ // rest of the app is served.
20
+ async function checkUnwalledReach(context, { connectionConfig }) {
21
+ if (context.organization?.policy !== 'tenant') return;
22
+ if (connectionConfig.tenantCapability !== false) return;
23
+ const reach = await resolveUnwalledReach(context);
24
+ const message = reach.get(connectionConfig.connectionId);
25
+ if (!message) return;
26
+ const err = new ConfigError(message, {
27
+ configKey: connectionConfig['~k']
28
+ });
29
+ context.logger.debug({
30
+ params: {
31
+ connectionId: connectionConfig.connectionId
32
+ },
33
+ err
34
+ }, message);
35
+ throw err;
36
+ }
37
+ export default checkUnwalledReach;
@@ -13,7 +13,9 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { ConfigError } from '@lowdefy/errors';
16
- async function getConnectionConfig({ logger, readConfigFile }, { connectionId, configKey }) {
16
+ import checkUnwalledReach from './checkUnwalledReach.js';
17
+ async function getConnectionConfig(context, { connectionId, configKey }) {
18
+ const { logger, readConfigFile } = context;
17
19
  let err;
18
20
  if (!connectionId) {
19
21
  err = new ConfigError('Connection id is missing.', {
@@ -40,6 +42,9 @@ async function getConnectionConfig({ logger, readConfigFile }, { connectionId, c
40
42
  }, err.message);
41
43
  throw err;
42
44
  }
45
+ await checkUnwalledReach(context, {
46
+ connectionConfig: connection
47
+ });
43
48
  return connection;
44
49
  }
45
50
  export default getConnectionConfig;
@@ -0,0 +1,226 @@
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 { TenantIntegrityError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ import createEvaluateOperators from '../../context/createEvaluateOperators.js';
18
+ import resolveUnwalledReach from './resolveUnwalledReach.js';
19
+ // The tenant preflight: under policy: tenant, find walled collections that
20
+ // hold rows without the tenant field and report them. The wall filters every
21
+ // read on the tenant field, so those rows are invisible - a data fault, not a
22
+ // reason to take the app down. The preflight therefore only reports: one
23
+ // TenantIntegrityError log line per offending target (plus one Sentry capture),
24
+ // and the per-target verdicts stay readable through getTenantIntegrityStatus.
25
+ // It never throws into a request and never blocks one - walled reads already
26
+ // filter by organisation, so the unstamped rows are simply not served.
27
+ //
28
+ // It is lazily-run-once per config build artifact, started (not awaited) by the
29
+ // per-request middleware - the same shape as resolvePinnedOrganization.
30
+ // Memoization: a completed check (clean or offending) memoizes for the life of
31
+ // the process; a probe failure (connectivity, timeout) logs a warning and clears
32
+ // the memo so the next request retries.
33
+ //
34
+ // Enumerating the walled set reads the tenantConnections.json build artifact
35
+ // (writeConnections). Each connection's properties evaluate with the same
36
+ // caller-less operator machinery requests use - _secret resolves, caller
37
+ // operators resolve to nothing - so a connection whose properties need a
38
+ // payload can not be probed and is skipped with a warning. The probe itself
39
+ // is a connection-type capability (connection.tenantPreflight), the same
40
+ // seam as the meta.tenant contract; a tenant-capable type without one is
41
+ // skipped with a warning.
42
+ //
43
+ // Memoization is keyed on the config build artifact - one module-level
44
+ // object per process in the servers - rather than a bare module singleton,
45
+ // mirroring how the organization binding keys on the auth instance.
46
+ const preflightByConfig = new WeakMap();
47
+ const statusByConfig = new WeakMap();
48
+ async function probeTargets(context, { targets }) {
49
+ return Promise.all([
50
+ ...targets.values()
51
+ ].map(async (target)=>{
52
+ try {
53
+ const { ok } = await target.plugin.tenantPreflight({
54
+ connection: target.properties,
55
+ field: target.field
56
+ });
57
+ return {
58
+ target,
59
+ ok
60
+ };
61
+ } catch (error) {
62
+ return {
63
+ target,
64
+ error
65
+ };
66
+ }
67
+ }));
68
+ }
69
+ async function collectTargets(context, { tenantConnections }) {
70
+ // Caller-less by contract: the verdict is memoized per process, so
71
+ // connection properties must never resolve against whichever caller happens
72
+ // to hit the cold process first - _user reads resolve to nothing, exactly
73
+ // like a system-context request.
74
+ const evaluateOperators = createEvaluateOperators({
75
+ ...context,
76
+ user: null
77
+ });
78
+ const targets = new Map();
79
+ for (const entry of tenantConnections){
80
+ const plugin = context.connections[entry.type];
81
+ if (plugin?.meta?.tenant !== true) {
82
+ continue;
83
+ }
84
+ if (!type.isFunction(plugin.tenantPreflight)) {
85
+ context.logger.warn(`Tenant preflight can not probe connection "${entry.connectionId}" - connection type "${entry.type}" implements the tenant contract but no tenantPreflight capability.`);
86
+ continue;
87
+ }
88
+ const connectionConfig = await context.readConfigFile(`connections/${entry.connectionId}.json`);
89
+ if (!connectionConfig) {
90
+ context.logger.warn(`Tenant preflight can not probe connection "${entry.connectionId}" - no connection artifact found.`);
91
+ continue;
92
+ }
93
+ let properties;
94
+ try {
95
+ properties = evaluateOperators({
96
+ input: connectionConfig.properties || {},
97
+ location: entry.connectionId,
98
+ payload: {},
99
+ state: {},
100
+ steps: {}
101
+ });
102
+ } catch (error) {
103
+ context.logger.warn({
104
+ err: error
105
+ }, `Tenant preflight can not probe connection "${entry.connectionId}" - its properties do not evaluate outside a request.`);
106
+ continue;
107
+ }
108
+ const field = type.isObject(entry.tenant) ? entry.tenant.field : 'organization_id';
109
+ // Several connections usually declare the same physical collection -
110
+ // probe each evaluated target once.
111
+ const key = JSON.stringify([
112
+ entry.type,
113
+ field,
114
+ properties
115
+ ]);
116
+ const target = targets.get(key) ?? {
117
+ connectionIds: [],
118
+ field,
119
+ plugin,
120
+ properties
121
+ };
122
+ target.connectionIds.push(entry.connectionId);
123
+ targets.set(key, target);
124
+ }
125
+ return targets;
126
+ }
127
+ function describeTarget(target) {
128
+ const connections = target.connectionIds.map((id)=>`"${id}"`).join(', ');
129
+ if (type.isString(target.properties?.collection)) {
130
+ return `collection "${target.properties.collection}" (connections ${connections})`;
131
+ }
132
+ return `connections ${connections}`;
133
+ }
134
+ function reportOffender(context, { captureError, target }) {
135
+ const collection = type.isString(target.properties?.collection) ? target.properties.collection : null;
136
+ const error = new TenantIntegrityError(`Tenant integrity: ${describeTarget(target)} holds documents without the tenant field "${target.field}". The wall filters every walled read on that field, so these documents are invisible to every organisation. The app keeps serving; backfill or remove the rows.`, {
137
+ collection,
138
+ connectionId: target.connectionIds[0],
139
+ field: target.field
140
+ });
141
+ context.logger.error({
142
+ err: error,
143
+ event: 'tenant_integrity_error',
144
+ collection,
145
+ connectionIds: target.connectionIds,
146
+ field: target.field
147
+ }, error.message);
148
+ if (type.isFunction(captureError)) {
149
+ try {
150
+ captureError(error);
151
+ } catch (captureFailure) {
152
+ context.logger.warn({
153
+ err: captureFailure
154
+ }, 'Tenant integrity error could not be captured.');
155
+ }
156
+ }
157
+ }
158
+ async function runPreflight(context, { captureError }) {
159
+ const tenantConnections = await context.readConfigFile('tenantConnections.json');
160
+ if (type.isNone(tenantConnections)) {
161
+ // A build older than the preflight has no index artifact - nothing to
162
+ // enumerate, so the preflight can not protect this deployment.
163
+ context.logger.warn('Tenant preflight skipped - no tenantConnections.json build artifact. Rebuild with a matching lowdefy version to enable the unstamped-rows check.');
164
+ return [];
165
+ }
166
+ // Logs each unwalled connection that reaches a walled database at start;
167
+ // checkUnwalledReach refuses that connection's requests.
168
+ const unwalledReach = resolveUnwalledReach(context).catch((error)=>{
169
+ context.logger.warn({
170
+ err: error
171
+ }, 'Tenant preflight could not check unwalled connections.');
172
+ });
173
+ const targets = await collectTargets(context, {
174
+ tenantConnections
175
+ });
176
+ const results = await probeTargets(context, {
177
+ targets
178
+ });
179
+ await unwalledReach;
180
+ const failures = results.filter((result)=>result.error);
181
+ if (failures.length > 0) {
182
+ // A probe that could not reach the datastore is an outage, not a verdict.
183
+ throw failures[0].error;
184
+ }
185
+ const offenders = results.filter((result)=>result.ok === false);
186
+ offenders.forEach((result)=>reportOffender(context, {
187
+ captureError,
188
+ target: result.target
189
+ }));
190
+ if (offenders.length === 0) {
191
+ context.logger.info(`Tenant preflight passed - ${targets.size} walled ${targets.size === 1 ? 'target carries' : 'targets carry'} no unstamped rows.`);
192
+ }
193
+ return results.map((result)=>({
194
+ collection: result.target.properties?.collection ?? null,
195
+ connectionIds: result.target.connectionIds,
196
+ field: result.target.field,
197
+ ok: result.ok !== false
198
+ }));
199
+ }
200
+ // Resolves once the check has run. The returned promise never rejects, so a
201
+ // request can neither fail on it nor be blocked by a fault in it.
202
+ function resolveTenantPreflight(context, { captureError } = {}) {
203
+ if (context.organization?.policy !== 'tenant') {
204
+ return Promise.resolve();
205
+ }
206
+ if (!preflightByConfig.has(context.config)) {
207
+ preflightByConfig.set(context.config, runPreflight(context, {
208
+ captureError
209
+ }).then((status)=>{
210
+ statusByConfig.set(context.config, status);
211
+ }).catch((error)=>{
212
+ // Connectivity-class failure - retry on the next request.
213
+ preflightByConfig.delete(context.config);
214
+ context.logger.warn({
215
+ err: error
216
+ }, 'Tenant preflight could not probe the walled collections - it will retry on the next request.');
217
+ }));
218
+ }
219
+ return preflightByConfig.get(context.config);
220
+ }
221
+ // The per-target verdicts of the completed check, or undefined before it has run.
222
+ function getTenantIntegrityStatus(config) {
223
+ return statusByConfig.get(config);
224
+ }
225
+ export { getTenantIntegrityStatus };
226
+ export default resolveTenantPreflight;
@@ -0,0 +1,144 @@
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 { ConnectionString } from 'mongodb-connection-string-url';
16
+ import { ConfigError } from '@lowdefy/errors';
17
+ import { type } from '@lowdefy/helpers';
18
+ import createEvaluateOperators from '../../context/createEvaluateOperators.js';
19
+ import createReadConfigFile from '../../context/createReadConfigFile.js';
20
+ // Finds the unwalled connections that hold a MongoDB URI to a walled
21
+ // connection's database. A non-scopable connection (SMTP, object storage, a
22
+ // plugin's own connection type) has no tenant wall, so a URI to the walled
23
+ // database in its properties is a way around it: the plugin should name the
24
+ // walled connection (mongoConnectionId) and use the walled client
25
+ // (@lowdefy/connection-mongodb/walled). The build catches a connection that
26
+ // reads the walled connection's secret; this catches a second secret, or a
27
+ // literal, for the same database.
28
+ //
29
+ // Two URIs point at the same database when their host sets and database names
30
+ // match. A walled connection's database name is its databaseName property,
31
+ // falling back to the path of its URI.
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
35
+ // that connection's requests; every other connection is served. The check reads config and
36
+ // secrets only, so it runs once per config build artifact, independent of the
37
+ // tenant preflight's database probes. A check that throws is not memoized.
38
+ //
39
+ // The verdict is a property of the build, never of a request, so it reads the build directory
40
+ // through a fresh base reader, not context.readConfigFile. A data session or a mutant run wraps
41
+ // that reader per request; read through it, whichever request evaluated first would decide the
42
+ // verdict for every later one, journey or not.
43
+ const reachByConfig = new WeakMap();
44
+ function parseMongoUri(value) {
45
+ if (!type.isString(value) || !/^mongodb(\+srv)?:\/\//.test(value)) return null;
46
+ try {
47
+ const url = new ConnectionString(value);
48
+ return {
49
+ hosts: [
50
+ ...url.hosts
51
+ ].sort().join(','),
52
+ database: url.pathname.replace(/^\//, '')
53
+ };
54
+ } catch (error) {
55
+ return null;
56
+ }
57
+ }
58
+ function collectUris(value, uris) {
59
+ if (type.isString(value)) {
60
+ const parsed = parseMongoUri(value);
61
+ if (parsed) uris.push(parsed);
62
+ } else if (type.isArray(value)) {
63
+ value.forEach((item)=>collectUris(item, uris));
64
+ } else if (type.isObject(value)) {
65
+ Object.values(value).forEach((item)=>collectUris(item, uris));
66
+ }
67
+ return uris;
68
+ }
69
+ async function evaluateConnectionProperties({ connectionId, evaluateOperators, readConfigFile }) {
70
+ const connectionConfig = await readConfigFile(`connections/${connectionId}.json`);
71
+ if (!connectionConfig) return null;
72
+ try {
73
+ return evaluateOperators({
74
+ input: connectionConfig.properties ?? {},
75
+ location: connectionId,
76
+ payload: {},
77
+ state: {},
78
+ steps: {}
79
+ });
80
+ } catch (error) {
81
+ return null;
82
+ }
83
+ }
84
+ async function collectWalledDatabases({ evaluateOperators, readConfigFile }) {
85
+ const tenantConnections = await readConfigFile('tenantConnections.json');
86
+ const walled = new Map();
87
+ for (const entry of tenantConnections ?? []){
88
+ const properties = await evaluateConnectionProperties({
89
+ connectionId: entry.connectionId,
90
+ evaluateOperators,
91
+ readConfigFile
92
+ });
93
+ const parsed = parseMongoUri(properties?.databaseUri);
94
+ if (!parsed) continue;
95
+ const database = properties.databaseName || parsed.database;
96
+ const key = `${parsed.hosts}/${database}`;
97
+ if (!walled.has(key)) walled.set(key, entry.connectionId);
98
+ }
99
+ return walled;
100
+ }
101
+ async function findUnwalledReach(context) {
102
+ const reach = new Map();
103
+ const readConfigFile = createReadConfigFile(context);
104
+ const unwalledConnections = await readConfigFile('unwalledConnections.json');
105
+ if (!type.isArray(unwalledConnections) || unwalledConnections.length === 0) return reach;
106
+ // Caller-less, like the tenant preflight: the verdict is memoized per
107
+ // process, so it must not resolve against whichever caller arrives first.
108
+ const evaluateOperators = createEvaluateOperators({
109
+ ...context,
110
+ user: null
111
+ });
112
+ const walled = await collectWalledDatabases({
113
+ evaluateOperators,
114
+ readConfigFile
115
+ });
116
+ if (walled.size === 0) return reach;
117
+ for (const entry of unwalledConnections){
118
+ const properties = await evaluateConnectionProperties({
119
+ connectionId: entry.connectionId,
120
+ evaluateOperators,
121
+ readConfigFile
122
+ });
123
+ const reached = collectUris(properties, []).find(({ hosts, database })=>walled.has(`${hosts}/${database}`));
124
+ 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);
131
+ reach.set(entry.connectionId, error.message);
132
+ }
133
+ return reach;
134
+ }
135
+ function resolveUnwalledReach(context) {
136
+ if (!reachByConfig.has(context.config)) {
137
+ reachByConfig.set(context.config, findUnwalledReach(context).catch((error)=>{
138
+ reachByConfig.delete(context.config);
139
+ throw error;
140
+ }));
141
+ }
142
+ return reachByConfig.get(context.config);
143
+ }
144
+ export default resolveUnwalledReach;
@@ -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 runDetachedEndpoint from './runDetachedEndpoint.js';
16
+ import scheduleBackground from './scheduleBackground.js';
17
+ // Accept a detached call and run it AFTER the response. The /api/detached route
18
+ // answers 202 at once and the endpoint runs under this invocation's own
19
+ // waitUntil (bounded by its maxDuration, exactly the budget it had before).
20
+ //
21
+ // Before this, the route awaited the whole routine and only then replied - and
22
+ // the dispatcher's scheduleBackground keeps its OWN invocation alive until that
23
+ // reply arrives. So every parent stayed in flight for as long as its detached
24
+ // children ran (a cron tick that answers in milliseconds held its invocation
25
+ // for its slowest child) - on Vercel Fluid that keeps the instance's
26
+ // provisioned memory billing running (CPU billing pauses during I/O) - and a
27
+ // chain of detached hops was a chain of nested in-flight requests, a likely
28
+ // (undocumented) trigger of the platform's 508 INFINITE_LOOP_DETECTED a few
29
+ // hops down. "Detached" now means the dispatcher's fetch settles as soon as the
30
+ // target has accepted the call.
31
+ //
32
+ // The outcome exists only in the logs (`detached_run_done` with the routine's
33
+ // status, or `detached_run_failed`), as it already did for the dispatcher.
34
+ function acceptDetachedEndpoint(context, { credentials, endpointId, payload, principal }) {
35
+ // The run outlives the 202, so the request closing must not cancel it.
36
+ context.signal = undefined;
37
+ scheduleBackground(context, {
38
+ event: 'detached_run',
39
+ endpointId
40
+ }, ()=>runDetachedEndpoint(context, {
41
+ credentials,
42
+ endpointId,
43
+ payload,
44
+ principal
45
+ }));
46
+ return {
47
+ accepted: true
48
+ };
49
+ }
50
+ export default acceptDetachedEndpoint;