@lowdefy/api 6.0.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/dist/context/applySystemTrust.js +45 -0
  2. package/dist/context/createApiContext.js +18 -3
  3. package/dist/context/createAuthorizeOutcome.js +91 -0
  4. package/dist/context/createBoundSystemContext.js +33 -0
  5. package/dist/context/createEvaluateOperators.js +10 -3
  6. package/dist/context/createRequestSignal.js +47 -0
  7. package/dist/context/createSystemContext.js +80 -0
  8. package/dist/context/getCanonicalUrl.js +27 -0
  9. package/dist/context/getCurrentEnvironment.js +27 -0
  10. package/dist/context/isSameOriginRequest.js +85 -0
  11. package/dist/context/isWebSocketOriginAllowed.js +63 -0
  12. package/dist/context/normalizeInjectedCaller.js +58 -0
  13. package/dist/context/parseRequestBody.js +32 -0
  14. package/dist/context/readMemberships.js +71 -0
  15. package/dist/context/resolveAuthentication.js +758 -0
  16. package/dist/context/resolveStrategyCaller.js +7 -3
  17. package/dist/csp/addNonceToElements.js +23 -0
  18. package/dist/csp/createContentSecurityPolicy.js +45 -0
  19. package/dist/csp/getWebSocketSources.js +36 -0
  20. package/dist/email/renderAuthEmail.js +99 -0
  21. package/dist/index.js +22 -5
  22. package/dist/response/buildEndpointResult.js +3 -1
  23. package/dist/response/createWireProjection.js +88 -0
  24. package/dist/response/formatErrorForAgent.js +35 -0
  25. package/dist/response/normalizeErrorSources.js +10 -13
  26. package/dist/response/redactErrorResponse.js +42 -8
  27. package/dist/response/redactResponse.js +17 -10
  28. package/dist/routes/agent/authorizeAgent.js +17 -5
  29. package/dist/routes/agent/callAgent.js +12 -2
  30. package/dist/routes/agent/collectChatFiles.js +39 -0
  31. package/dist/routes/agent/prepareAgent.js +29 -4
  32. package/dist/routes/auth/buildAdminPlugin.js +33 -0
  33. package/dist/routes/auth/buildCaptchaPlugin.js +61 -0
  34. package/dist/routes/auth/buildMcpTokenPlugin.js +77 -0
  35. package/dist/routes/auth/buildOauthPostLogin.js +73 -0
  36. package/dist/routes/auth/buildPhoneNumberPlugin.js +57 -0
  37. package/dist/routes/auth/buildProviders.js +61 -0
  38. package/dist/routes/auth/createAsMetadataHandler.js +27 -0
  39. package/dist/routes/auth/createAuthLogger.js +31 -0
  40. package/dist/routes/auth/createMcpAccessTokenClaims.js +52 -0
  41. package/dist/routes/auth/createOnAPIError.js +41 -0
  42. package/dist/routes/auth/createSendEmail.js +54 -0
  43. package/dist/routes/auth/ensureMcpTokenIndexes.js +48 -0
  44. package/dist/routes/auth/getAuthEnforcement.js +41 -0
  45. package/dist/routes/auth/getBetterAuth.js +107 -0
  46. package/dist/routes/auth/getBetterAuthConfig.js +767 -0
  47. package/dist/routes/auth/handleAuthRequest.js +43 -0
  48. package/dist/routes/auth/hooks/authHookPoints.js +204 -0
  49. package/dist/routes/auth/hooks/buildEngineHooks.js +68 -0
  50. package/dist/routes/auth/hooks/buildHooks.js +112 -0
  51. package/dist/routes/auth/{callbacks/addUserFieldsToSession.js → hooks/composeAfterSlot.js} +11 -13
  52. package/dist/routes/auth/hooks/composeBeforeSlot.js +41 -0
  53. package/dist/routes/auth/hooks/createHookDispatch.js +59 -0
  54. package/dist/routes/auth/hooks/createUserAfterHook.js +36 -0
  55. package/dist/routes/auth/hooks/createUserBeforeHook.js +50 -0
  56. package/dist/routes/auth/hooks/findHookUser.js +27 -0
  57. package/dist/routes/auth/modelNames.js +30 -0
  58. package/dist/routes/auth/organizations/OrganizationKeyError.js +28 -0
  59. package/dist/routes/auth/organizations/authorizeRole.js +27 -0
  60. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +178 -0
  61. package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +57 -0
  62. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +120 -0
  63. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +403 -0
  64. package/dist/routes/auth/organizations/createAdmissionGateHook.js +50 -0
  65. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +90 -0
  66. package/dist/routes/auth/organizations/createAutoJoinHook.js +68 -0
  67. package/dist/routes/auth/organizations/createEmailSendGate.js +59 -0
  68. package/dist/routes/auth/organizations/createExpiredInvitationGate.js +76 -0
  69. package/dist/routes/auth/organizations/ensureAuthIndexes.js +122 -0
  70. package/dist/routes/auth/organizations/ensureOrganization.js +132 -0
  71. package/dist/routes/auth/organizations/findPendingInvitation.js +43 -0
  72. package/dist/routes/auth/organizations/getHookRequestHeaders.js +24 -0
  73. package/dist/routes/auth/organizations/getOrganizationBinding.js +65 -0
  74. package/dist/routes/auth/organizations/isEmailAdmitted.js +89 -0
  75. package/dist/routes/auth/organizations/organizationAccessControl.js +94 -0
  76. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +62 -0
  77. package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +145 -0
  78. package/dist/routes/auth/requestHooks/buildRequestHooks.js +288 -0
  79. package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +43 -0
  80. package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +59 -0
  81. package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +47 -0
  82. package/dist/routes/auth/requestHooks/redirectToChallenge.js +79 -0
  83. package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +31 -0
  84. package/dist/routes/auth/resolveCookiePrefix.js +30 -0
  85. package/dist/routes/auth/sanitizeSessionResponse.js +27 -0
  86. package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
  87. package/dist/routes/connections/checkUnwalledReach.js +37 -0
  88. package/dist/routes/connections/getConnectionConfig.js +6 -1
  89. package/dist/routes/connections/resolveTenantPreflight.js +226 -0
  90. package/dist/routes/connections/resolveUnwalledReach.js +144 -0
  91. package/dist/routes/endpoints/acceptDetachedEndpoint.js +50 -0
  92. package/dist/routes/endpoints/authorizeApiEndpoint.js +13 -4
  93. package/dist/routes/endpoints/callEndpoint.js +23 -7
  94. package/dist/routes/endpoints/control/controlFor.js +4 -7
  95. package/dist/routes/endpoints/control/controlIf.js +4 -8
  96. package/dist/routes/endpoints/control/controlLog.js +6 -14
  97. package/dist/routes/endpoints/control/controlParallelFor.js +65 -29
  98. package/dist/routes/endpoints/control/controlReject.js +36 -16
  99. package/dist/routes/endpoints/control/controlReturn.js +32 -9
  100. package/dist/routes/endpoints/control/controlSetState.js +4 -8
  101. package/dist/routes/endpoints/control/controlSwitch.js +4 -8
  102. package/dist/routes/endpoints/control/controlThrow.js +20 -21
  103. package/dist/routes/endpoints/control/controlTry.js +30 -11
  104. package/dist/routes/endpoints/control/controlWhile.js +55 -0
  105. package/dist/routes/endpoints/control/handleControl.js +3 -1
  106. package/dist/routes/endpoints/createWebhookAnswer.js +78 -0
  107. package/dist/routes/endpoints/evaluateRoutineOperators.js +27 -0
  108. package/dist/routes/endpoints/forwardScheduledEndpoint.js +21 -15
  109. package/dist/routes/endpoints/getEndpointConfig.js +18 -8
  110. package/dist/routes/endpoints/getEnvironmentSchedules.js +5 -7
  111. package/dist/routes/endpoints/getSchemaValidator.js +39 -0
  112. package/dist/routes/endpoints/handleAgentCall.js +25 -9
  113. package/dist/routes/endpoints/handleAuthStep.js +214 -0
  114. package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
  115. package/dist/routes/endpoints/handleEndpointCall.js +46 -12
  116. package/dist/routes/endpoints/handleRenderNotification.js +29 -12
  117. package/dist/routes/endpoints/handleRequest.js +13 -6
  118. package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
  119. package/dist/routes/endpoints/handleValidateSchema.js +22 -22
  120. package/dist/routes/endpoints/invokeEndpoint.js +27 -3
  121. package/dist/routes/endpoints/operatorScope.js +28 -0
  122. package/dist/routes/{auth/events/createEventPlugins.js → endpoints/parseWebhookBody.js} +10 -6
  123. package/dist/routes/endpoints/resolveCallBinding.js +91 -0
  124. package/dist/routes/endpoints/resolveCronEnvironment.js +7 -6
  125. package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
  126. package/dist/routes/endpoints/runDetachedEndpoint.js +64 -18
  127. package/dist/routes/endpoints/runRoutine.js +64 -5
  128. package/dist/routes/endpoints/runScheduledEndpoint.js +19 -11
  129. package/dist/routes/endpoints/runWebhookEndpoint.js +70 -23
  130. package/dist/routes/endpoints/runWebhookVerify.js +129 -0
  131. package/dist/routes/endpoints/scheduleBackground.js +10 -0
  132. package/dist/routes/endpoints/test/runTest.js +48 -11
  133. package/dist/routes/endpoints/validatePayload.js +144 -0
  134. package/dist/routes/log/logClientError.js +7 -4
  135. package/dist/routes/mcp/createMcpServer.js +143 -64
  136. package/dist/routes/mcp/getMcpJwks.js +93 -0
  137. package/dist/routes/mcp/getMcpResourceBinding.js +41 -0
  138. package/dist/routes/mcp/getMcpUri.js +69 -0
  139. package/dist/routes/mcp/oauthResourceLifecycle.js +122 -0
  140. package/dist/routes/mcp/runAfterToolCall.js +50 -0
  141. package/dist/routes/notifications/resolveNotificationLinks.js +39 -11
  142. package/dist/routes/page/dynamic/checkDynamicContent.js +81 -0
  143. package/dist/routes/page/dynamic/checkLiteralContent.js +242 -0
  144. package/dist/routes/page/dynamic/createContentError.js +34 -0
  145. package/dist/routes/page/dynamic/flagIconsOutsidePage.js +39 -0
  146. package/dist/routes/page/dynamic/flagTypesOutsidePage.js +44 -0
  147. package/dist/routes/page/dynamic/getPropertiesSchemaErrors.js +35 -0
  148. package/dist/routes/page/dynamic/loadDynamicArtifacts.js +52 -0
  149. package/dist/routes/page/dynamic/policy/checkAction.js +204 -0
  150. package/dist/routes/page/dynamic/policy/checkEvents.js +163 -0
  151. package/dist/routes/page/dynamic/policy/checkPolicy.js +313 -0
  152. package/dist/routes/page/dynamic/policy/checkValue.js +214 -0
  153. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +117 -0
  154. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +54 -0
  155. package/dist/routes/page/dynamic/policy/findSerializerKeys.js +50 -0
  156. package/dist/routes/page/dynamic/policy/isAllowedUrl.js +53 -0
  157. package/dist/routes/{auth/createAdapter.js → page/dynamic/policy/isUnderState.js} +5 -9
  158. package/dist/routes/page/dynamic/policy/normalizeUrlText.js +25 -0
  159. package/dist/routes/page/dynamic/resolveDynamicContent.js +89 -37
  160. package/dist/routes/page/dynamic/unescapeOperators.js +21 -4
  161. package/dist/routes/page/dynamic/validateFragment.js +17 -58
  162. package/dist/routes/page/getPageConfig.js +76 -6
  163. package/dist/routes/request/authorizeRequest.js +21 -6
  164. package/dist/routes/request/callRequest.js +21 -3
  165. package/dist/routes/request/callRequestResolver.js +55 -6
  166. package/dist/routes/request/checkConnectionRead.js +1 -1
  167. package/dist/routes/request/checkConnectionWrite.js +1 -1
  168. package/dist/routes/request/createWalledResolver.js +75 -0
  169. package/dist/routes/request/evaluateOperators.js +8 -12
  170. package/dist/routes/request/getRequestConfig.js +19 -3
  171. package/dist/routes/request/maskCredentialProperties.js +34 -0
  172. package/dist/routes/request/resolveTenancy.js +223 -0
  173. package/dist/routes/request/validateSchemas.js +7 -6
  174. package/dist/routes/{auth/callbacks/createCallbackPlugins.js → rootConfig/getAppEvents.js} +7 -6
  175. package/dist/routes/rootConfig/getHomeAndMenus.js +23 -16
  176. package/dist/routes/{auth/events/createSessionEvent.js → rootConfig/getPagePaths.js} +16 -18
  177. package/dist/routes/rootConfig/getRootConfig.js +9 -3
  178. package/dist/routes/rootConfig/menus/filterMenuList.js +5 -2
  179. package/dist/routes/websocket/authorizeWebsocket.js +19 -4
  180. package/dist/routes/websocket/createChannelRegistry.js +39 -14
  181. package/dist/routes/websocket/createWebSocketConnection.js +162 -28
  182. package/dist/routes/websocket/getCallerFingerprint.js +31 -0
  183. package/dist/routes/websocket/prepareChannel.js +29 -1
  184. package/dist/routes/websocket/resolveWebsocketCaller.js +40 -0
  185. package/dist/test/testContext.js +16 -11
  186. package/package.json +28 -12
  187. package/dist/context/createAuthorize.js +0 -45
  188. package/dist/response/omitErrorProps.js +0 -51
  189. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +0 -30
  190. package/dist/routes/auth/callbacks/createCallbacks.js +0 -46
  191. package/dist/routes/auth/callbacks/createJWTCallback.js +0 -77
  192. package/dist/routes/auth/callbacks/createRedirectCallback.js +0 -41
  193. package/dist/routes/auth/callbacks/createSessionCallback.js +0 -81
  194. package/dist/routes/auth/callbacks/createSignInCallback.js +0 -40
  195. package/dist/routes/auth/callbacks/validateSessionRoles.js +0 -33
  196. package/dist/routes/auth/createLogger.js +0 -35
  197. package/dist/routes/auth/createPrefixedCookies.js +0 -52
  198. package/dist/routes/auth/createProviders.js +0 -25
  199. package/dist/routes/auth/events/createCreateUserEvent.js +0 -41
  200. package/dist/routes/auth/events/createEvents.js +0 -56
  201. package/dist/routes/auth/events/createLinkAccountEvent.js +0 -43
  202. package/dist/routes/auth/events/createSignInEvent.js +0 -46
  203. package/dist/routes/auth/events/createSignOutEvent.js +0 -43
  204. package/dist/routes/auth/events/createUpdateUserEvent.js +0 -41
  205. package/dist/routes/auth/getAuthConfig.js +0 -86
  206. package/dist/routes/auth/resolveCookies.js +0 -37
  207. package/dist/routes/log/formatValidationError.js +0 -31
  208. /package/dist/{routes/notifications → email}/resolveThemeLogo.js +0 -0
@@ -0,0 +1,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 createCallbackPlugins({ authConfig, plugins, type }) {
16
- return authConfig.callbacks.map((callbackConfig)=>({
17
- fn: plugins.callbacks[callbackConfig.type],
18
- properties: callbackConfig.properties
19
- })).filter((callback)=>callback.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 createCallbackPlugins;
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;
@@ -15,6 +15,7 @@
15
15
  */ import crypto from 'crypto';
16
16
  import { serializer } from '@lowdefy/helpers';
17
17
  import { ConfigError, PluginError, ServiceError } from '@lowdefy/errors';
18
+ import createWireProjection from '../../response/createWireProjection.js';
18
19
  import prepareChannel from './prepareChannel.js';
19
20
  const MAX_RETRIES = 5;
20
21
  const RETRY_BASE_MS = 1000;
@@ -26,10 +27,15 @@ const HEALTHY_RESET_MS = 60 * 1000;
26
27
  // last one leaves.
27
28
  function createChannelRegistry() {
28
29
  const channels = new Map();
29
- function getChannelKey({ connectionProperties, properties, websocketId }) {
30
+ function getChannelKey({ connectionProperties, properties, tenant, websocketId }) {
31
+ // The tenant verdict is part of the channel identity: two callers whose
32
+ // evaluated properties are identical but whose organizations differ must
33
+ // never share a running source, or one org would receive the other's
34
+ // change events.
30
35
  const hash = crypto.createHash('sha1').update(serializer.serializeToString({
31
36
  connectionProperties,
32
- properties
37
+ properties,
38
+ tenant
33
39
  })).digest('base64');
34
40
  return `${websocketId}:${hash}`;
35
41
  }
@@ -39,6 +45,23 @@ function createChannelRegistry() {
39
45
  subscriber.send(message);
40
46
  });
41
47
  }
48
+ // Config reads a broadcast error only as a message string, so it gets the wire
49
+ // message alone - no requestId, since no single request raised it, and no
50
+ // devError, since the dev terminal already logs it in full. The channel's
51
+ // context belongs to whoever subscribed first, so the message is translated
52
+ // with each subscriber's own locale.
53
+ function broadcastError(channel, error) {
54
+ channel.subscribers.forEach((subscriber)=>{
55
+ const { message } = createWireProjection({
56
+ i18n: subscriber.i18n
57
+ })(error);
58
+ subscriber.send(JSON.stringify({
59
+ type: 'error',
60
+ websocketId: channel.websocketId,
61
+ message
62
+ }));
63
+ });
64
+ }
42
65
  function wrapResolverError({ channel, error }) {
43
66
  if (!error.configKey) {
44
67
  error.configKey = channel.websocketConfig['~k'];
@@ -86,11 +109,7 @@ function createChannelRegistry() {
86
109
  err: wrapped
87
110
  }, wrapped.message);
88
111
  channel.context.handleError(wrapped);
89
- broadcast(channel, {
90
- type: 'error',
91
- websocketId: channel.websocketId,
92
- message: wrapped.message
93
- });
112
+ broadcastError(channel, wrapped);
94
113
  // A run that stayed healthy resets the backoff window.
95
114
  if (Date.now() - startedAt > HEALTHY_RESET_MS) {
96
115
  channel.retryCount = 0;
@@ -142,7 +161,8 @@ function createChannelRegistry() {
142
161
  properties: channel.properties,
143
162
  publish,
144
163
  signal: abortController.signal,
145
- logger: channel.logger
164
+ logger: channel.logger,
165
+ tenant: channel.tenant ?? null
146
166
  })).catch((error)=>handleResolverError({
147
167
  channel,
148
168
  error,
@@ -150,21 +170,24 @@ function createChannelRegistry() {
150
170
  }));
151
171
  }
152
172
  async function subscribe(context, { websocketId, payload, subscriber }) {
153
- const { connectionProperties, properties, websocketConfig, websocketResolver } = await prepareChannel(context, {
154
- websocketId,
155
- payload
156
- });
157
173
  // One subscription per websocketId per connection — a re-subscribe (e.g.
158
- // with a new payload) replaces the previous one.
174
+ // with a new payload) replaces the previous one. The client stops reading
175
+ // the previous one when it sends the re-subscribe, so it is removed before
176
+ // the new one is prepared: a re-subscribe that fails leaves nothing open.
159
177
  if (subscriber.subscriptions.has(websocketId)) {
160
178
  unsubscribe({
161
179
  websocketId,
162
180
  subscriber
163
181
  });
164
182
  }
183
+ const { connectionProperties, properties, tenant, websocketConfig, websocketResolver } = await prepareChannel(context, {
184
+ websocketId,
185
+ payload
186
+ });
165
187
  const key = getChannelKey({
166
188
  connectionProperties,
167
189
  properties,
190
+ tenant,
168
191
  websocketId
169
192
  });
170
193
  let channel = channels.get(key);
@@ -176,6 +199,7 @@ function createChannelRegistry() {
176
199
  resolver: websocketResolver,
177
200
  connectionProperties,
178
201
  properties,
202
+ tenant,
179
203
  subscribers: new Set(),
180
204
  abortController: null,
181
205
  restartTimer: null,
@@ -223,7 +247,7 @@ function createChannelRegistry() {
223
247
  async function publish(context, { websocketId, payload }) {
224
248
  // Publish identity is evaluated without a subscription payload — channels
225
249
  // that fragment on _payload/_user in properties are not publish targets.
226
- const { connectionProperties, properties, websocketConfig, websocketResolver } = await prepareChannel(context, {
250
+ const { connectionProperties, properties, tenant, websocketConfig, websocketResolver } = await prepareChannel(context, {
227
251
  websocketId,
228
252
  payload: {}
229
253
  });
@@ -235,6 +259,7 @@ function createChannelRegistry() {
235
259
  const key = getChannelKey({
236
260
  connectionProperties,
237
261
  properties,
262
+ tenant,
238
263
  websocketId
239
264
  });
240
265
  const channel = channels.get(key);