@lowdefy/api 6.1.0 → 7.1.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,45 @@
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 createAuthorizeOutcome from './createAuthorizeOutcome.js';
16
+ // The single writer of the trusted system-context invariants (Decision 1). It
17
+ // sets them together on an existing context so no caller can set one without
18
+ // the others:
19
+ // - system: true — the run-level trust marker every authorization layer reads
20
+ // - boundOrganizationId — the organization the run is bound to (CallApi
21
+ // `organization`), or null. The tenant wall filters
22
+ // and stamps with it (resolveTenancy).
23
+ // - user — null (caller-less), or the named stand-in caller
24
+ // (CallApi `caller`): { id, name, organization_id,
25
+ // system: true }, with no roles and no attributes
26
+ // - authorizeOutcome — derived from createAuthorizeOutcome so it reads context.system
27
+ // createSystemContext builds a FRESH context for the off-request hook path;
28
+ // this applies the same state to a request context a runner already holds
29
+ // (cron at construction, webhook once its verify gate passes, a detached run
30
+ // whose dispatcher was itself a system context, a CallApi bound to an
31
+ // organization). One greppable place means a future runner cannot reintroduce
32
+ // the silent-no-op bug by forgetting a line.
33
+ function applySystemTrust(context, { organizationId = null, caller = null } = {}) {
34
+ context.system = true;
35
+ context.boundOrganizationId = organizationId;
36
+ context.user = caller === null ? null : {
37
+ id: caller.id,
38
+ name: caller.name,
39
+ organization_id: organizationId,
40
+ system: true
41
+ };
42
+ context.authorizeOutcome = createAuthorizeOutcome(context);
43
+ return context;
44
+ }
45
+ export default applySystemTrust;
@@ -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 createAuthorize from './createAuthorize.js';
15
+ */ import createAuthorizeOutcome from './createAuthorizeOutcome.js';
16
16
  import createReadConfigFile from './createReadConfigFile.js';
17
+ import getAuthEnforcement from '../routes/auth/getAuthEnforcement.js';
18
+ import getOrganizationBinding from '../routes/auth/organizations/getOrganizationBinding.js';
17
19
  import resolveLocale from './resolveLocale.js';
18
20
  function createApiContext(context) {
19
- context.user = context?.session?.user;
21
+ // context.user is written by resolveAuthentication (or a pre-resolved
22
+ // dev/e2e caller) before this runs - never assigned here.
20
23
  if (context.i18n?.defaultLocale) {
21
24
  const active = resolveLocale({
22
25
  i18n: context.i18n,
@@ -29,7 +32,19 @@ function createApiContext(context) {
29
32
  } else {
30
33
  context.i18n = undefined;
31
34
  }
32
- context.authorize = createAuthorize(context);
35
+ // The retained organizations state ({ policy, pinned }) - read by the
36
+ // _organization operator and the org-scoped admin steps; null when auth
37
+ // (or organizations) is not configured.
38
+ context.organization = getOrganizationBinding({
39
+ auth: context.auth ?? null
40
+ });
41
+ // The retained build-time authorization facts - the enrolment floor, the exempt
42
+ // enrolment page, and the unlisted-page-id default. null when auth is not
43
+ // configured, in which case nothing is protected and nothing is required.
44
+ context.authEnforcement = getAuthEnforcement({
45
+ auth: context.auth ?? null
46
+ });
47
+ context.authorizeOutcome = createAuthorizeOutcome(context);
33
48
  context.readConfigFile = createReadConfigFile(context);
34
49
  }
35
50
  export default createApiContext;
@@ -0,0 +1,91 @@
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 { ConfigError } from '@lowdefy/errors';
17
+ // createAuthorizeOutcome is called with the context object on every path
18
+ // (createApiContext, applySystemTrust, and the runners), so `system` is read
19
+ // straight off context.system - the single run-level trust marker every
20
+ // authorization layer reads.
21
+ //
22
+ // It returns an OUTCOME, not a boolean: 'allow', 'deny', or 'enrol_required'.
23
+ // The rename is load-bearing. Every previous caller was a truthiness test, and
24
+ // every non-empty string is truthy, so a caller left on `authorize` would read
25
+ // 'deny' as authorized and stop enforcing auth entirely on that surface. There
26
+ // is deliberately NO boolean authorize left beside this - a missed call site
27
+ // must throw TypeError, which also catches callers outside this repo.
28
+ //
29
+ // The ordering is security-critical and written here exactly once. Enrolment is
30
+ // checked LAST, after roles: checking it first hands an unenrolled caller an
31
+ // enrol redirect for every protected page that EXISTS and /404 for those that do
32
+ // not, which is a working page-enumeration oracle over pages they have no access
33
+ // to. Checked last, they see the enrol outcome only for pages they would have
34
+ // been let into - which tells them exactly what an enrolled caller learns by
35
+ // getting the page.
36
+ function createAuthorizeOutcome({ authEnforcement, system, user }) {
37
+ const authenticated = !type.isNone(user);
38
+ // A caller awaiting an organization is signed in and holds no membership -
39
+ // under tenant, the invited user before they accept (resolveAuthentication).
40
+ // They are known so the always-public accept page can address them, and
41
+ // refused everywhere auth.public is false, roles or not: empty roles is not a
42
+ // wall (user-model Decision 2), so authenticated alone must not admit them to
43
+ // a role-less protected page. Strategy callers (apiKey, jwt) also hold no
44
+ // organization but sit deliberately outside the membership boundary, so the
45
+ // test is this explicit marker, never the absence of an organization. The
46
+ // caller is the normalizeCaller-snaked record, so the key is snake_case here.
47
+ const awaitingOrganization = user?.awaiting_organization === true;
48
+ const roles = user?.roles ?? [];
49
+ if (!Array.isArray(roles) || roles.some((role)=>!type.isString(role))) {
50
+ throw new ConfigError('user.roles must be an array of strings.', {
51
+ received: roles
52
+ });
53
+ }
54
+ const enrolmentRequired = authEnforcement?.twoFactorRequired === true;
55
+ const enrolPageId = authEnforcement?.twoFactorEnrolPageId ?? null;
56
+ // pageId is passed only by the page route. Requests, endpoints, websockets and
57
+ // menu items pass none, so the enrolment-page exemption cannot be reached by a
58
+ // request id that happens to collide with the enrol page's id.
59
+ function authorizeOutcome(config, { pageId } = {}) {
60
+ // A system context has no session and no caller, so "does this caller's
61
+ // session carry the required roles?" is undefined, not denied - and it holds
62
+ // no factor either, so the enrolment floor is undefined for it too.
63
+ if (system === true) return 'allow';
64
+ const { auth } = config;
65
+ if (auth.public === true) return 'allow';
66
+ if (auth.public === false) {
67
+ if (!authenticated) return 'deny';
68
+ if (awaitingOrganization) return 'deny';
69
+ if (auth.roles && !auth.roles.some((role)=>roles.includes(role))) return 'deny';
70
+ // Enrolment last, after roles. Strictly === false: the key is present only
71
+ // on a caller resolved from a session, so API strategy callers and the
72
+ // dev/e2e injected callers pass untouched by inheritance rather than by a
73
+ // carve-out (Decision 10). `!user.two_factor_enrolled` would redirect every
74
+ // one of them.
75
+ if (enrolmentRequired && user.two_factor_enrolled === false) {
76
+ // The enrolment page itself is exempt from the enrolment check alone -
77
+ // it is a protected page and stays one; this is not a public-ness
78
+ // exemption (Decision 8).
79
+ if (!type.isNone(pageId) && pageId === enrolPageId) return 'allow';
80
+ return 'enrol_required';
81
+ }
82
+ return 'allow';
83
+ }
84
+ throw new ConfigError('auth.public must be true or false.', {
85
+ received: auth.public,
86
+ configKey: config['~k']
87
+ });
88
+ }
89
+ return authorizeOutcome;
90
+ }
91
+ export default createAuthorizeOutcome;
@@ -0,0 +1,33 @@
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 applySystemTrust from './applySystemTrust.js';
16
+ import createEvaluateOperators from './createEvaluateOperators.js';
17
+ // The context a CallApi bound to an organization runs its target in: a copy of
18
+ // the calling run's context, trusted as a system run bound to that organization
19
+ // (and stand-in caller, when one is named). A copy, so the binding holds for
20
+ // the target and every call nested in it, and the calling run carries on as
21
+ // itself once the call returns. evaluateOperators is rebuilt because the
22
+ // parser holds the user it was built with, which is what `_user` reads.
23
+ function createBoundSystemContext(context, { organizationId, caller }) {
24
+ const bound = applySystemTrust({
25
+ ...context
26
+ }, {
27
+ organizationId,
28
+ caller
29
+ });
30
+ bound.evaluateOperators = createEvaluateOperators(bound);
31
+ return bound;
32
+ }
33
+ export default createBoundSystemContext;
@@ -12,23 +12,28 @@
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 { ServerParser } from '@lowdefy/operators';
15
+ */ import { markCredential } from '@lowdefy/node-utils';
16
+ import { ServerParser } from '@lowdefy/operators';
16
17
  function createEvaluateOperators(context) {
17
- const { appMeta, i18n, jsMap, operators, secrets, user } = context;
18
+ const { appMeta, i18n, jsMap, operators, organization, secrets, user } = context;
18
19
  const operatorsParser = new ServerParser({
19
20
  i18n,
20
21
  jsMap,
21
22
  lowdefyApp: appMeta,
23
+ markCredential,
22
24
  operators,
25
+ organization,
23
26
  secrets,
24
27
  user
25
28
  });
26
- function evaluateOperators({ arrayIndices, error, input, items, location, payload, state, steps }) {
29
+ function evaluateOperators({ agent, arrayIndices, error, input, items, literalData, location, payload, state, steps }) {
27
30
  const { output, errors } = operatorsParser.parse({
31
+ agent,
28
32
  arrayIndices,
29
33
  error,
30
34
  input,
31
35
  items,
36
+ literalData,
32
37
  location,
33
38
  payload,
34
39
  state,
@@ -0,0 +1,47 @@
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 signal the work a request starts is cancelled with (context.signal). Request
17
+ // resolvers hand it to the calls they make upstream, so a request nobody is waiting
18
+ // for any more stops those calls instead of letting them run, and bill, to the end.
19
+ //
20
+ // It aborts with an AbortError when the client closes the connection before the
21
+ // response is sent (clientSignal, the incoming request's own signal), and with the
22
+ // timeout signal's TimeoutError when the server's request timeout answers first.
23
+ // callRequestResolver reads the reason: an AbortError means the caller left, which
24
+ // is not a fault. The Node adapter aborts the incoming request's signal with a plain
25
+ // string, which clients such as the AI SDK do not recognise as a cancellation, so the
26
+ // client's abort is re-raised as a DOMException.
27
+ function createRequestSignal({ clientSignal, timeoutSignal }) {
28
+ const clientClosed = new AbortController();
29
+ function onClientClose() {
30
+ clientClosed.abort(new DOMException('The client closed the connection before the response was sent.', 'AbortError'));
31
+ }
32
+ if (clientSignal.aborted) {
33
+ onClientClose();
34
+ } else {
35
+ clientSignal.addEventListener('abort', onClientClose, {
36
+ once: true
37
+ });
38
+ }
39
+ if (type.isNone(timeoutSignal)) {
40
+ return clientClosed.signal;
41
+ }
42
+ return AbortSignal.any([
43
+ clientClosed.signal,
44
+ timeoutSignal
45
+ ]);
46
+ }
47
+ export default createRequestSignal;
@@ -0,0 +1,80 @@
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 applySystemTrust from './applySystemTrust.js';
16
+ import createEvaluateOperators from './createEvaluateOperators.js';
17
+ import createReadConfigFile from './createReadConfigFile.js';
18
+ import getAuthEnforcement from '../routes/auth/getAuthEnforcement.js';
19
+ import getOrganizationBinding from '../routes/auth/organizations/getOrganizationBinding.js';
20
+ // Builds a fresh off-request context for a trusted, caller-less system context -
21
+ // an auth hook fire. The caller is the auth engine, not a user: `user` is null
22
+ // so the run is detectable as caller-less (`type.isNone(context.user)`) and
23
+ // `_user` resolves to nothing (the hook's subject is in `_payload`). The run is
24
+ // trusted at construction (`context.system = true`), the single trust marker
25
+ // every authorization layer reads (Decision 1); its `authorizeOutcome` is derived
26
+ // from createAuthorizeOutcome like every other layer, so endpoint auth is not
27
+ // re-checked against a session (Decision 2).
28
+ function createSystemContext({ agents, appMeta, auth, buildDirectory, config, configDirectory, connections, createHandleError, fileCache, i18n, jsMap, logger, mode, notifications, operators, rid, scrubSecrets, secrets, steps, websockets }) {
29
+ const context = {
30
+ rid,
31
+ agents,
32
+ appMeta,
33
+ auth,
34
+ buildDirectory,
35
+ config,
36
+ configDirectory,
37
+ connections,
38
+ fileCache,
39
+ headers: {},
40
+ i18n: i18n?.defaultLocale ? {
41
+ ...i18n,
42
+ active: i18n.defaultLocale
43
+ } : undefined,
44
+ jsMap,
45
+ logger,
46
+ mode,
47
+ notifications,
48
+ operators,
49
+ req: {
50
+ url: 'system:auth-hook',
51
+ method: null,
52
+ hostname: null
53
+ },
54
+ scrubSecrets,
55
+ secrets,
56
+ steps,
57
+ websockets
58
+ };
59
+ // Hook routines read the retained organizations state too - a step or
60
+ // _organization inside a hook-bound endpoint resolves the same pinned org.
61
+ context.organization = getOrganizationBinding({
62
+ auth: auth ?? null
63
+ });
64
+ // A system context bypasses the enrolment check outright (system === true
65
+ // returns early), so this exists for shape consistency, not a live read.
66
+ context.authEnforcement = getAuthEnforcement({
67
+ auth: auth ?? null
68
+ });
69
+ // Trusted, caller-less system context (Decisions 1, 2): user: null,
70
+ // system: true, and authorizeOutcome derived from createAuthorizeOutcome - the
71
+ // same invariant bundle the caller-less runners apply, set in one place.
72
+ applySystemTrust(context);
73
+ context.handleError = createHandleError({
74
+ context
75
+ });
76
+ context.readConfigFile = createReadConfigFile(context);
77
+ context.evaluateOperators = createEvaluateOperators(context);
78
+ return context;
79
+ }
80
+ export default createSystemContext;
@@ -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
+ */ import getCurrentEnvironment from './getCurrentEnvironment.js';
16
+ // The deployment's pinned canonical origin: BETTER_AUTH_URL when set, else the url of the current
17
+ // environment in config.environments. Both come from deployment config, never from a request's
18
+ // Host header, so auth links and the MCP resource identifier cannot be steered by a caller. Null
19
+ // when neither is set.
20
+ function getCanonicalUrl({ config }) {
21
+ const fromEnv = process.env.BETTER_AUTH_URL?.trim();
22
+ if (fromEnv) return fromEnv;
23
+ return getCurrentEnvironment({
24
+ config
25
+ })?.url ?? null;
26
+ }
27
+ export default getCanonicalUrl;
@@ -0,0 +1,85 @@
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
+ // Browser-set values of Sec-Fetch-Site that mark a request this site's own
17
+ // pages made: `same-origin`, or `none` (user initiated, no initiator document).
18
+ const ALLOWED_FETCH_SITES = new Set([
19
+ 'same-origin',
20
+ 'none'
21
+ ]);
22
+ // URL.origin lowercases the host and drops a default port, so
23
+ // `https://App.test:443` and `https://app.test` compare equal.
24
+ function normaliseOrigin(value) {
25
+ try {
26
+ const { origin } = new URL(value);
27
+ return origin === 'null' ? null : origin;
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+ // A Host header names the host and port only; the scheme is the Origin's.
33
+ function hostOrigin({ host, scheme }) {
34
+ if (type.isNone(host) || host.trim() === '') {
35
+ return null;
36
+ }
37
+ return normaliseOrigin(`${scheme}//${host.trim()}`);
38
+ }
39
+ // A proxy chain appends to X-Forwarded-Host; the first entry is the host the
40
+ // browser asked for.
41
+ function firstForwardedHost(value) {
42
+ if (type.isNone(value)) {
43
+ return null;
44
+ }
45
+ return value.split(',')[0];
46
+ }
47
+ // The one rule every server applies to routes only the app's own pages call:
48
+ // the cookie-bearing browser routes and websocket upgrades. Sec-Fetch-Site and
49
+ // Origin are set by the browser and cannot be set by page script.
50
+ // Sec-Fetch-Site `cross-site` and `same-site` are refused. The Origin must then
51
+ // be the one the request arrived on: the Host header, and where the caller
52
+ // allows them, the first X-Forwarded-Host (for a proxy that rewrites Host) or
53
+ // one of the app's configured public origins.
54
+ //
55
+ // A caller that sends no Origin is not a browser acting for another site - a
56
+ // server, curl, an agent. It passes only where the route allows it.
57
+ function isSameOriginRequest({ getHeader, allowNoOrigin = false, acceptForwardedHost = false, publicOrigins = [] }) {
58
+ const fetchSite = getHeader('sec-fetch-site');
59
+ if (!type.isNone(fetchSite) && !ALLOWED_FETCH_SITES.has(fetchSite)) {
60
+ return false;
61
+ }
62
+ const rawOrigin = getHeader('origin');
63
+ if (type.isNone(rawOrigin) || rawOrigin === '') {
64
+ return allowNoOrigin;
65
+ }
66
+ const origin = normaliseOrigin(rawOrigin);
67
+ if (origin === null) {
68
+ return false;
69
+ }
70
+ const { protocol: scheme } = new URL(origin);
71
+ const hosts = [
72
+ getHeader('host')
73
+ ];
74
+ if (acceptForwardedHost) {
75
+ hosts.push(firstForwardedHost(getHeader('x-forwarded-host')));
76
+ }
77
+ if (hosts.some((host)=>hostOrigin({
78
+ host,
79
+ scheme
80
+ }) === origin)) {
81
+ return true;
82
+ }
83
+ return publicOrigins.some((publicOrigin)=>normaliseOrigin(publicOrigin) === origin);
84
+ }
85
+ export default isSameOriginRequest;
@@ -0,0 +1,63 @@
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 getCanonicalUrl from './getCanonicalUrl.js';
17
+ import isSameOriginRequest from './isSameOriginRequest.js';
18
+ // The app's public origins: its canonical URL (BETTER_AUTH_URL, else the
19
+ // current environment's url) and the auth trusted origins - deployment config,
20
+ // never read from the request.
21
+ function getPublicOrigins({ context }) {
22
+ const origins = [];
23
+ const canonicalUrl = getCanonicalUrl({
24
+ config: context.config
25
+ });
26
+ if (!type.isNone(canonicalUrl)) {
27
+ origins.push(canonicalUrl);
28
+ }
29
+ // Exact strings only - a trustedOrigins function or pattern is not consulted,
30
+ // as in the MCP route's origin check.
31
+ const trustedOrigins = context.auth?.options?.trustedOrigins;
32
+ if (type.isArray(trustedOrigins)) {
33
+ origins.push(...trustedOrigins.filter((origin)=>type.isString(origin)));
34
+ }
35
+ return origins;
36
+ }
37
+ // Browsers open a websocket to any host a page names, so a websocket upgrade
38
+ // is accepted only from the app's own pages, or from a client that sends no
39
+ // Origin (a server or a script). A browser cannot set headers on a websocket
40
+ // handshake, so X-Forwarded-Host is accepted here, where a proxy or CDN in
41
+ // front of the app rewrites Host; the app's configured public origins are too.
42
+ // A refusal is logged, since behind a proxy that passes neither it would
43
+ // otherwise be a silent 403 on every upgrade.
44
+ function isWebSocketOriginAllowed({ context, getHeader }) {
45
+ const allowed = isSameOriginRequest({
46
+ getHeader,
47
+ allowNoOrigin: true,
48
+ acceptForwardedHost: true,
49
+ publicOrigins: getPublicOrigins({
50
+ context
51
+ })
52
+ });
53
+ if (!allowed) {
54
+ context.logger.warn({
55
+ event: 'ws_origin_refused',
56
+ origin: getHeader('origin'),
57
+ host: getHeader('host'),
58
+ forwardedHost: getHeader('x-forwarded-host')
59
+ }, `WebSocket upgrade refused: Origin ${getHeader('origin')} is not this app (Host ${getHeader('host')}). Behind a proxy, pass the original Host or set X-Forwarded-Host.`);
60
+ }
61
+ return allowed;
62
+ }
63
+ export default isWebSocketOriginAllowed;
@@ -0,0 +1,58 @@
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 { normalizeCaller, type } from '@lowdefy/helpers';
17
+ // The single writer of the pre-resolved-caller shape. A dev mock user, the dev
18
+ // headless renderer cookie, and the e2e test cookie each substitute for the
19
+ // whole resolveAuthentication step, and must match the shape it produces -
20
+ // including its snake_case keys, so an injected caller may be authored either
21
+ // way and still reads like a resolved one. That output always carries roles as
22
+ // an array and attributes as an object (a whole-bag { _user: 'attributes' }
23
+ // read gives {} on a real caller), so both are floored here. profile,
24
+ // contact_id, active_organization_id and two_factor_enrolled are only ever
25
+ // produced by a real user-row/member read, so they are left exactly as the
26
+ // caller carries them - absent stays absent, and a bare _user.profile read is
27
+ // null-safe.
28
+ // organization_id (the tenant wall's org value) mirrors resolveAuthentication,
29
+ // where it always equals active_organization_id - an injected caller declaring
30
+ // either key gets both, so mock/e2e callers pass walled connections without
31
+ // duplicating the org under two names. A caller with neither stays org-less
32
+ // and fails closed on walled connections, same as a strategy caller.
33
+ //
34
+ // The floors read the raw user: roles, attributes and profile are single words
35
+ // that snake to themselves, so an authored key and its normalized name are the
36
+ // same key. The org floor reads the normalized object, where either authored
37
+ // spelling has already collapsed onto one name.
38
+ //
39
+ // system is refused: _user.system marks the stand-in caller a bound CallApi
40
+ // names (applySystemTrust), and apps branch on it.
41
+ function normalizeInjectedCaller(user) {
42
+ const snakeCased = normalizeCaller(user);
43
+ if (Object.hasOwn(snakeCased, 'system')) {
44
+ throw new ConfigError('An injected caller (dev mock user, headless or e2e user) can not carry "system". Only the stand-in caller a CallApi "caller" names carries _user.system.');
45
+ }
46
+ const normalized = {
47
+ ...snakeCased,
48
+ roles: user.roles ?? [],
49
+ attributes: user.attributes ?? {}
50
+ };
51
+ const organizationId = normalized.organization_id ?? normalized.active_organization_id;
52
+ if (!type.isNone(organizationId)) {
53
+ normalized.organization_id = organizationId;
54
+ normalized.active_organization_id = normalized.active_organization_id ?? organizationId;
55
+ }
56
+ return normalized;
57
+ }
58
+ export default normalizeInjectedCaller;
@@ -0,0 +1,32 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { UserError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ // The Lowdefy client posts a JSON object ({ blockId, pageId, payload }). A body
18
+ // that is not one is the caller's mistake: a UserError, which the servers answer
19
+ // with 400 and log as a warning, not a 500 logged as a fault.
20
+ function parseRequestBody({ text }) {
21
+ let body;
22
+ try {
23
+ body = JSON.parse(text);
24
+ } catch {
25
+ throw new UserError('Request body is not valid JSON.');
26
+ }
27
+ if (!type.isObject(body)) {
28
+ throw new UserError('Request body must be a JSON object.');
29
+ }
30
+ return body;
31
+ }
32
+ export default parseRequestBody;