@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,75 @@
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 evaluateRoutineOperators from '../endpoints/evaluateRoutineOperators.js';
17
+ import getConnection from '../connections/getConnection.js';
18
+ import getConnectionConfig from '../connections/getConnectionConfig.js';
19
+ import resolveTenancy from './resolveTenancy.js';
20
+ // The seam a plugin uses to reach a walled MongoDB collection: the resolver
21
+ // receives `walled(connectionId)`. It resolves the named connection from the
22
+ // app config, evaluates its properties against the calling request's frame,
23
+ // and computes the tenant verdict and unscoped-write guard for THIS request
24
+ // (the same resolveTenancy the request layer runs, so tenant: none and shared
25
+ // connections behave exactly as they do for a stock request). What it returns
26
+ // is the argument bag of getWalledCollection in
27
+ // @lowdefy/connection-mongodb/walled, so the plugin never sees the raw client:
28
+ //
29
+ // const collection = getWalledCollection(await walled('mongo'));
30
+ //
31
+ // Only a connection type that implements the scoping contract (meta.tenant)
32
+ // can be named; anything else has no wall to apply.
33
+ function createWalledResolver(context, { requestConfig, routineContext }) {
34
+ const frame = routineContext ?? {
35
+ arrayIndices: [],
36
+ error: null,
37
+ items: {},
38
+ payload: context.payload ?? {},
39
+ state: {},
40
+ steps: {}
41
+ };
42
+ return async function walled(connectionId) {
43
+ const configKey = requestConfig['~k'];
44
+ const connectionConfig = await getConnectionConfig(context, {
45
+ connectionId,
46
+ configKey
47
+ });
48
+ const connection = getConnection(context, {
49
+ connectionConfig
50
+ });
51
+ if (connection.meta?.tenant !== true) {
52
+ throw new ConfigError(`Connection "${connectionId}" (${connectionConfig.type}) can not be used as a walled MongoDB client: its type does not implement the tenant scoping contract.`, {
53
+ configKey
54
+ });
55
+ }
56
+ const { tenant, tenantGuard } = resolveTenancy(context, {
57
+ connection,
58
+ connectionConfig,
59
+ requestConfig
60
+ });
61
+ const properties = evaluateRoutineOperators(context, frame, {
62
+ input: connectionConfig.properties || {},
63
+ location: connectionId
64
+ });
65
+ return {
66
+ connection: properties,
67
+ connectionId,
68
+ endpointId: context.endpointId,
69
+ requestId: requestConfig.stepId ?? requestConfig.requestId,
70
+ tenant,
71
+ tenantGuard
72
+ };
73
+ };
74
+ }
75
+ export default createWalledResolver;
@@ -12,11 +12,27 @@
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 { ConfigError } from '@lowdefy/errors';
16
- async function getRequestConfig({ logger, readConfigFile }, { pageId, requestId }) {
15
+ */ import { AuthenticationError, ConfigError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ // A missing request id answers the same as a protected one for an anonymous
18
+ // human on an auth'd app: before you authenticate, the only answer is
19
+ // authenticate. Otherwise a logged-out caller enumerates request ids by
20
+ // response difference - 500 for a miss (the handler special-cases only
21
+ // AuthenticationError) versus 401 for a protected one. An authenticated caller
22
+ // gets today's opaque "does not exist" for both a miss and a role refusal,
23
+ // unchanged.
24
+ //
25
+ // Guarded on authEnforcement != null (auth configured) and system !== true (not
26
+ // the engine talking to itself), exactly as the page fork is: "no user" is not
27
+ // "anonymous human who should sign in" - it is also "no auth here" and "this is
28
+ // a system run", and neither should be told to authenticate against nothing.
29
+ // This is NOT a per-entity apiProtectedByDefault default; no such glob surface
30
+ // exists.
31
+ async function getRequestConfig({ authEnforcement, logger, readConfigFile, system, user }, { pageId, requestId }) {
17
32
  const request = await readConfigFile(`pages/${pageId}/requests/${requestId}.json`);
18
33
  if (!request) {
19
- const err = new ConfigError(`Request "${requestId}" does not exist.`);
34
+ const unauthenticatedHuman = type.isNone(user) && !type.isNone(authEnforcement) && system !== true;
35
+ const err = unauthenticatedHuman ? new AuthenticationError(`Authentication required for request "${requestId}".`) : new ConfigError(`Request "${requestId}" does not exist.`);
20
36
  logger.debug({
21
37
  params: {
22
38
  pageId,
@@ -0,0 +1,34 @@
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
+ */ // A request type names in meta.credentialProperties the request properties that carry a
16
+ // credential the secret scrub cannot recognise, such as a presigned link, whose signature is
17
+ // derived from a secret rather than being one. Their values are masked in the request properties
18
+ // an error keeps as received, so the error log never holds them.
19
+ function maskCredentialProperties({ requestProperties, requestResolver }) {
20
+ const credentialProperties = requestResolver.meta.credentialProperties ?? [];
21
+ if (credentialProperties.length === 0) {
22
+ return requestProperties;
23
+ }
24
+ const masked = {
25
+ ...requestProperties
26
+ };
27
+ credentialProperties.forEach((property)=>{
28
+ if (Object.hasOwn(masked, property)) {
29
+ masked[property] = '[REDACTED]';
30
+ }
31
+ });
32
+ return masked;
33
+ }
34
+ export default maskCredentialProperties;
@@ -0,0 +1,223 @@
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 { AuthenticationError, ConfigError, TenantIntegrityError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ // The engine computes the tenant verdict, the connection enforces it. This is
18
+ // the compute half, for a request, step or websocket against a connection:
19
+ // resolve the verdict (the tenant field and the caller's organization id the
20
+ // connection filters and stamps with) and the write guard (the field every
21
+ // row an unscoped write leaves behind must still carry), or fail closed.
22
+ // Both come from one call so no call site can resolve the verdict and forget
23
+ // the guard - the webhook verifier did until the two were folded together.
24
+ //
25
+ // The app's auth.organizations.policy sets the scoping default for every
26
+ // connection (amendment-3). Under tenant, a connection whose type implements
27
+ // the scoping contract (meta.tenant === true) is scoped unless it declares
28
+ // tenant: shared. Under pinned (the default, including apps with no auth or
29
+ // no organizations block) no connection is scoped and none can be - no
30
+ // verdict, no guard: no filter, no stamp, no audit, no fail-closed error. The
31
+ // one check that stays on under both policies is the contract check below: a
32
+ // tenant declaration on a type that can not honour it should fail on the
33
+ // current deployment, not on the day the app flips to tenant.
34
+ //
35
+ // The connection position accepts only the exception to the default:
36
+ // - `tenant: 'shared'` -> no verdict. Data deliberately shared across
37
+ // organizations - the ONLY connection-level path out of the wall, visible
38
+ // in the connection file. (`tenant: true` was removed with the inversion;
39
+ // it restated the default and is a build error.) When the build found that
40
+ // a scoped connection reads the same collection (connectionConfig.walled,
41
+ // buildConnections markWalledSharedConnections), the shared connection's
42
+ // writes land in a walled collection, so they get the write guard.
43
+ // - `tenant: { field }` -> scoped on that field instead of organization_id.
44
+ //
45
+ // Connection types declare their capability as meta.tenant: true implements
46
+ // the scoping contract, false is non-scopable (object storage, SMTP - never
47
+ // scoped, no declaration needed on its connections). A type declaring
48
+ // neither is a build error under tenant (buildConnections validateTenant);
49
+ // the checks here are runtime belt-and-braces repeats of the build errors,
50
+ // because build artifacts and the running server can drift, and a silently
51
+ // unscoped connection must never be reachable.
52
+ //
53
+ // The request-level sentinel is unchanged by the inversion (amendment-1):
54
+ // - `tenant: 'none'` on the request/step/websocket -> no verdict, read only.
55
+ // A visible, reviewable statement at the point of use that lifts the filter
56
+ // so the request reads rows of every organization. A request type that
57
+ // writes (its resolver's meta.checkWrite, passed in as `writes`) is refused
58
+ // here, repeating the build error; the guard carries readOnly: true so the
59
+ // connection refuses the writes no request meta describes (an aggregation's
60
+ // $out/$merge, a plugin's walled client). Caller-less work writes as one
61
+ // organization instead, through CallApi `organization`.
62
+ // - `tenant: 'authored'` on the request -> the verdict resolves exactly as
63
+ // the default (an org-less caller is still rejected) and carries
64
+ // authored: true, telling the connection resolver to AUDIT the request's
65
+ // own tenant clause (stages the wall can not scope mechanically) instead
66
+ // of injecting one. Aggregation-only; other operations refuse the marker.
67
+ // - Otherwise the caller must carry an organization (context.user.organization_id,
68
+ // the active org in string form). A system run (hook routines, scheduled
69
+ // jobs, verified webhooks) has one only when a CallApi bound it to one
70
+ // (context.boundOrganizationId); unbound system runs and strategy callers
71
+ // have none, so they fail here by design - the wall never degrades to
72
+ // unscoped access. An unbound system run that writes is a data fault, not
73
+ // an authentication one: it fails that request with TenantIntegrityError,
74
+ // logged at error level and captured, since a write with no organization
75
+ // would leave a row no walled read can see.
76
+ const unscoped = {
77
+ tenant: null,
78
+ tenantGuard: null
79
+ };
80
+ // The scoping contract is enforced by the connection package itself (the
81
+ // resolvers stamp writes, merge filters and guard unscoped writes), so a stamp
82
+ // of true is only serveable when the installed package carries the runtime
83
+ // meta. A build artifact claiming the contract for a runtime that does not
84
+ // implement it is version drift between build and server: the verdict or
85
+ // guard would be computed and then silently ignored, which is exactly the
86
+ // unscoped access the wall exists to prevent - refuse instead.
87
+ function assertRuntimeContract({ runtimeCapability, connectionConfig }) {
88
+ if (runtimeCapability !== true) {
89
+ throw new ConfigError(`Connection type "${connectionConfig.type}" does not implement the tenant scoping contract in the installed version, but the build artifact for connection "${connectionConfig.connectionId}" declares it. The build and the running server have drifted - rebuild the app with the installed version, or align the versions.`, {
90
+ configKey: connectionConfig['~k']
91
+ });
92
+ }
93
+ }
94
+ // Belt-and-braces repeat of the build check: the wall stamps and matches the
95
+ // field as a single top-level document key, so a drifted artifact with a
96
+ // missing, empty, or dotted field must refuse rather than enforce on a key the
97
+ // read filters can never match.
98
+ function assertTenantField({ field, connectionConfig }) {
99
+ if (!type.isString(field) || field === '' || field.includes('.')) {
100
+ throw new ConfigError(`Connection "tenant.field" should be a non-empty top-level field name (no dots) at connection "${connectionConfig.connectionId}" — the tenant wall stamps and matches it as a single document key.`, {
101
+ received: field,
102
+ configKey: connectionConfig['~k']
103
+ });
104
+ }
105
+ }
106
+ function resolveSharedTenancy({ runtimeCapability, connectionConfig }) {
107
+ if (type.isNone(connectionConfig.walled)) {
108
+ return unscoped;
109
+ }
110
+ assertRuntimeContract({
111
+ runtimeCapability,
112
+ connectionConfig
113
+ });
114
+ const { field } = connectionConfig.walled;
115
+ assertTenantField({
116
+ field,
117
+ connectionConfig
118
+ });
119
+ return {
120
+ tenant: null,
121
+ tenantGuard: {
122
+ field,
123
+ readOnly: false
124
+ }
125
+ };
126
+ }
127
+ function resolveTenancy(context, { connection, connectionConfig, requestConfig, writes = false }) {
128
+ // Capability resolves from the runtime connection export first, then from
129
+ // the tenantCapability the build stamped onto the connection artifact
130
+ // (buildConnections) — the same types.js declaration the build check
131
+ // validated. The stamp is what lets non-scoping types (SMTP, SendGrid,
132
+ // AxiosHttp, AI connections, third-party plugins) serve under
133
+ // policy: tenant without every package mirroring meta.tenant onto its
134
+ // runtime export; the runtime meta still wins when present, so a drifted
135
+ // artifact can never downgrade a type that now enforces the contract.
136
+ const runtimeCapability = connection.meta?.tenant;
137
+ const capability = runtimeCapability ?? connectionConfig.tenantCapability;
138
+ if (!type.isNone(connectionConfig.tenant) && capability !== true) {
139
+ throw new ConfigError(`Connection type "${connectionConfig.type}" does not implement the tenant scoping contract, so "tenant" can not be declared at connection "${connectionConfig.connectionId}".`, {
140
+ configKey: connectionConfig['~k']
141
+ });
142
+ }
143
+ if ((context.organization?.policy ?? 'pinned') !== 'tenant') {
144
+ return unscoped;
145
+ }
146
+ if (connectionConfig.tenant === 'shared') {
147
+ return resolveSharedTenancy({
148
+ runtimeCapability,
149
+ connectionConfig
150
+ });
151
+ }
152
+ if (capability === false) {
153
+ return unscoped;
154
+ }
155
+ if (capability !== true) {
156
+ throw new ConfigError(`Connection type "${connectionConfig.type}" declares no tenant capability, so connection "${connectionConfig.connectionId}" can not be served under auth.organizations.policy: tenant. The type must declare meta tenant: true (implements the scoping contract) or tenant: false (non-scopable).`, {
157
+ configKey: connectionConfig['~k']
158
+ });
159
+ }
160
+ assertRuntimeContract({
161
+ runtimeCapability,
162
+ connectionConfig
163
+ });
164
+ const field = type.isObject(connectionConfig.tenant) ? connectionConfig.tenant.field : 'organization_id';
165
+ assertTenantField({
166
+ field,
167
+ connectionConfig
168
+ });
169
+ const location = requestConfig.stepId ?? requestConfig.requestId ?? requestConfig.websocketId;
170
+ if (requestConfig.tenant === 'none') {
171
+ if (writes) {
172
+ throw new ConfigError(`Request "${location}" is a ${requestConfig.type} request on tenant connection "${connectionConfig.connectionId}" with tenant: none, but tenant: none may only read. To write rows of one organization from a system run, call an endpoint with a CallApi step that names the "organization": its requests are filtered and stamped with that organization.`, {
173
+ configKey: requestConfig['~k']
174
+ });
175
+ }
176
+ return {
177
+ tenant: null,
178
+ tenantGuard: {
179
+ field,
180
+ readOnly: true
181
+ }
182
+ };
183
+ }
184
+ // A system run's organization is the one a CallApi bound it to; it has no
185
+ // other. Every other run's is the caller's.
186
+ const value = context.system === true ? context.boundOrganizationId : context.user?.organization_id;
187
+ if (!type.isString(value) || value === '') {
188
+ if (writes && context.system === true) {
189
+ const collection = connectionConfig.properties?.collection;
190
+ throw new TenantIntegrityError(`Request "${location}" writes to tenant connection "${connectionConfig.connectionId}" in a system run bound to no organization, so the row would carry no "${field}" and no walled read could see it. Call its endpoint with a CallApi step that names the "organization".`, {
191
+ collection: type.isString(collection) ? collection : null,
192
+ configKey: requestConfig['~k'],
193
+ connectionId: connectionConfig.connectionId,
194
+ endpointId: context.endpointId,
195
+ field
196
+ });
197
+ }
198
+ const verb = writes ? 'writes to' : 'reads';
199
+ let remedy = 'Strategy callers and callers with no active organization carry none - the wall fails closed for them.';
200
+ if (context.system === true) {
201
+ remedy = 'A system run carries none unless a CallApi bound it to one - the wall fails closed for it. To run this request in one organization from a system run, call its endpoint with a CallApi step that names the "organization".';
202
+ }
203
+ throw new AuthenticationError(`Request "${location}" ${verb} tenant connection "${connectionConfig.connectionId}" but no caller organization resolved. ${remedy}`);
204
+ }
205
+ if (requestConfig.tenant === 'authored') {
206
+ return {
207
+ tenant: {
208
+ field,
209
+ value,
210
+ authored: true
211
+ },
212
+ tenantGuard: null
213
+ };
214
+ }
215
+ return {
216
+ tenant: {
217
+ field,
218
+ value
219
+ },
220
+ tenantGuard: null
221
+ };
222
+ }
223
+ export default resolveTenancy;
@@ -12,10 +12,9 @@
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 { validate } from '@lowdefy/ajv';
15
+ */ import { formatSchemaError, validate } from '@lowdefy/ajv';
16
16
  import { ConfigError } from '@lowdefy/errors';
17
- import formatValidationError from '../log/formatValidationError.js';
18
- function validateSchemas({ logger }, { connection, connectionProperties, requestConfig, requestResolver, requestProperties }) {
17
+ function validateSchemas(context, { connection, connectionProperties, requestConfig, requestResolver, requestProperties }) {
19
18
  const configKey = requestConfig['~k'];
20
19
  const messages = [];
21
20
  const connectionResult = validate({
@@ -25,7 +24,7 @@ function validateSchemas({ logger }, { connection, connectionProperties, request
25
24
  });
26
25
  if (!connectionResult.valid) {
27
26
  for (const ajvError of connectionResult.errors){
28
- messages.push(formatValidationError({
27
+ messages.push(formatSchemaError({
29
28
  ajvError,
30
29
  pluginLabel: 'Connection',
31
30
  typeName: requestConfig.connectionId,
@@ -40,7 +39,7 @@ function validateSchemas({ logger }, { connection, connectionProperties, request
40
39
  });
41
40
  if (!requestResult.valid) {
42
41
  for (const ajvError of requestResult.errors){
43
- messages.push(formatValidationError({
42
+ messages.push(formatSchemaError({
44
43
  ajvError,
45
44
  pluginLabel: 'Request',
46
45
  typeName: requestConfig.type,
@@ -49,7 +48,9 @@ function validateSchemas({ logger }, { connection, connectionProperties, request
49
48
  }
50
49
  }
51
50
  if (messages.length > 0) {
52
- const message = messages.length === 1 ? messages[0] : `Request "${requestConfig.requestId}" has schema validation errors:\n${messages.map((m)=>` - ${m}`).join('\n')}`;
51
+ // Endpoint steps have a stepId, page requests a requestId.
52
+ const requestId = requestConfig.stepId ?? requestConfig.requestId;
53
+ const message = messages.length === 1 ? messages[0] : `Request "${requestId}" has schema validation errors:\n${messages.map((m)=>` - ${m}`).join('\n')}`;
53
54
  throw new ConfigError(message, {
54
55
  configKey
55
56
  });
@@ -12,10 +12,11 @@
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
- */ function createEventPlugins({ authConfig, plugins, type }) {
16
- return authConfig.events.map((eventConfig)=>({
17
- fn: plugins.events[eventConfig.type],
18
- properties: eventConfig.properties
19
- })).filter((event)=>event.fn.meta.type === type);
15
+ */ import { serializer } from '@lowdefy/helpers';
16
+ // Serialized like page config: the ~k markers, non-enumerable once the artifact
17
+ // is read, must reach the browser so app event errors resolve to their config.
18
+ async function getAppEvents({ readConfigFile }) {
19
+ const events = await readConfigFile('events.json');
20
+ return serializer.serialize(events);
20
21
  }
21
- export default createEventPlugins;
22
+ export default getAppEvents;
@@ -14,6 +14,24 @@
14
14
  limitations under the License.
15
15
  */ import { get } from '@lowdefy/helpers';
16
16
  import getMenus from './menus/getMenus.js';
17
+ // The first link of the menu the user may see, at up to three levels deep.
18
+ function findHomeLink(menu) {
19
+ for (const path of [
20
+ 'links.0',
21
+ 'links.0.links.0',
22
+ 'links.0.links.0.links.0'
23
+ ]){
24
+ const link = get(menu, path, {
25
+ default: null
26
+ });
27
+ if (get(link, 'pageId', {
28
+ default: null
29
+ })) {
30
+ return link;
31
+ }
32
+ }
33
+ return null;
34
+ }
17
35
  async function getHomeAndMenus(context) {
18
36
  const menus = await getMenus(context);
19
37
  const homePageId = get(context.config, 'homePageId');
@@ -21,7 +39,8 @@ async function getHomeAndMenus(context) {
21
39
  return {
22
40
  home: {
23
41
  configured: true,
24
- pageId: homePageId
42
+ pageId: homePageId,
43
+ pathParams: {}
25
44
  },
26
45
  menus
27
46
  };
@@ -31,24 +50,12 @@ async function getHomeAndMenus(context) {
31
50
  // eslint-disable-next-line prefer-destructuring
32
51
  defaultMenu = menus[0];
33
52
  }
34
- let pageId = null;
35
- pageId = get(defaultMenu, 'links.0.pageId', {
36
- default: null
37
- });
38
- if (!pageId) {
39
- pageId = get(defaultMenu, 'links.0.links.0.pageId', {
40
- default: null
41
- });
42
- }
43
- if (!pageId) {
44
- pageId = get(defaultMenu, 'links.0.links.0.links.0.pageId', {
45
- default: null
46
- });
47
- }
53
+ const homeLink = findHomeLink(defaultMenu);
48
54
  return {
49
55
  home: {
50
56
  configured: false,
51
- pageId
57
+ pageId: homeLink?.pageId ?? null,
58
+ pathParams: homeLink?.pathParams ?? {}
52
59
  },
53
60
  menus
54
61
  };
@@ -12,23 +12,21 @@
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 createEventPlugins from './createEventPlugins.js';
16
- function createSessionEvent({ authConfig, plugins }) {
17
- const sessionPlugins = createEventPlugins({
18
- authConfig,
19
- plugins,
20
- type: 'session'
21
- });
22
- if (sessionPlugins.length === 0) return undefined;
23
- async function sessionEvent({ session, token }) {
24
- for (const plugin of sessionPlugins){
25
- await plugin.fn({
26
- properties: plugin.properties ?? {},
27
- session,
28
- token
29
- });
15
+ */ // The path of every page with one that this caller may open, as
16
+ // { [pageId]: path }, filtered as menus are. The client builds every other
17
+ // page's URL from its id.
18
+ async function getPagePaths(context) {
19
+ const routes = await context.readConfigFile('routes.json');
20
+ const pagePaths = {};
21
+ routes.forEach((route)=>{
22
+ if (route.path === route.pageId) {
23
+ return;
24
+ }
25
+ if (context.authorizeOutcome(route) === 'deny') {
26
+ return;
30
27
  }
31
- }
32
- return sessionEvent;
28
+ pagePaths[route.pageId] = route.path;
29
+ });
30
+ return pagePaths;
33
31
  }
34
- export default createSessionEvent;
32
+ export default getPagePaths;
@@ -12,23 +12,29 @@
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 getHomeAndMenus from './getHomeAndMenus.js';
15
+ */ import getAppEvents from './getAppEvents.js';
16
+ import getHomeAndMenus from './getHomeAndMenus.js';
16
17
  import getLowdefyGlobal from './getLowdefyGlobal.js';
17
18
  import getLowdefyI18n from './getLowdefyI18n.js';
18
19
  import getLowdefyTheme from './getLowdefyTheme.js';
20
+ import getPagePaths from './getPagePaths.js';
19
21
  async function getRootConfig(context) {
20
- const [lowdefyGlobal, theme, i18n, { home, menus }] = await Promise.all([
22
+ const [events, lowdefyGlobal, theme, i18n, { home, menus }, pagePaths] = await Promise.all([
23
+ getAppEvents(context),
21
24
  getLowdefyGlobal(context),
22
25
  getLowdefyTheme(context),
23
26
  getLowdefyI18n(context),
24
- getHomeAndMenus(context)
27
+ getHomeAndMenus(context),
28
+ getPagePaths(context)
25
29
  ]);
26
30
  return {
31
+ events,
27
32
  home,
28
33
  i18n,
29
34
  lowdefyApp: context.appMeta,
30
35
  lowdefyGlobal,
31
36
  menus,
37
+ pagePaths,
32
38
  theme
33
39
  };
34
40
  }
@@ -14,10 +14,13 @@
14
14
  limitations under the License.
15
15
  */ import { get } from '@lowdefy/helpers';
16
16
  function filterMenuList(context, { menuList }) {
17
- const { authorize } = context;
17
+ const { authorizeOutcome } = context;
18
18
  const filtered = menuList.map((item)=>{
19
19
  if (item.type === 'MenuLink') {
20
- if (authorize(item)) {
20
+ // enrol_required keeps the link visible: the outcome means "authorised,
21
+ // pending enrolment", and hiding it would empty an unenrolled user's whole
22
+ // menu on the enrolment page they are sitting on. Only 'deny' hides.
23
+ if (authorizeOutcome(item) !== 'deny') {
21
24
  return item;
22
25
  }
23
26
  return null;
@@ -12,16 +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 { ConfigError } from '@lowdefy/errors';
16
- function authorizeWebsocket({ authorize, logger }, { websocketConfig }) {
17
- if (!authorize(websocketConfig)) {
15
+ */ import { AuthenticationError, AuthorizationError, TwoFactorEnrolmentRequiredError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ function authorizeWebsocket({ authorizeOutcome: authorize, logger, user }, { websocketConfig }) {
18
+ const outcome = authorize(websocketConfig);
19
+ if (outcome !== 'allow') {
18
20
  logger.debug({
19
21
  event: 'debug_websocket_authorize',
20
22
  authorized: false,
23
+ outcome,
21
24
  auth_config: websocketConfig.auth
22
25
  });
26
+ if (outcome === 'enrol_required') {
27
+ // Reached only after the role check passed, so the caller is authorised and
28
+ // this reveals nothing about what exists (Decision 6). A distinct code, not
29
+ // a 401 - a 401 reads to the client as a dead session and bounces the user
30
+ // to sign-in, which is the loop by another route.
31
+ throw new TwoFactorEnrolmentRequiredError(`Two-factor enrolment required for websocket "${websocketConfig.websocketId}".`);
32
+ }
33
+ // Unauthenticated on a protected websocket - 401 tells the caller to fix
34
+ // its credentials. Wrong roles stay opaque below.
35
+ if (type.isNone(user)) {
36
+ throw new AuthenticationError(`Authentication required for websocket "${websocketConfig.websocketId}".`);
37
+ }
23
38
  // Same message as a missing websocket so channel existence does not leak.
24
- throw new ConfigError(`Websocket "${websocketConfig.websocketId}" does not exist.`);
39
+ throw new AuthorizationError(`Websocket "${websocketConfig.websocketId}" does not exist.`);
25
40
  }
26
41
  }
27
42
  export default authorizeWebsocket;