@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
@@ -27,10 +27,15 @@ const HEALTHY_RESET_MS = 60 * 1000;
27
27
  // last one leaves.
28
28
  function createChannelRegistry() {
29
29
  const channels = new Map();
30
- 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.
31
35
  const hash = crypto.createHash('sha1').update(serializer.serializeToString({
32
36
  connectionProperties,
33
- properties
37
+ properties,
38
+ tenant
34
39
  })).digest('base64');
35
40
  return `${websocketId}:${hash}`;
36
41
  }
@@ -156,7 +161,8 @@ function createChannelRegistry() {
156
161
  properties: channel.properties,
157
162
  publish,
158
163
  signal: abortController.signal,
159
- logger: channel.logger
164
+ logger: channel.logger,
165
+ tenant: channel.tenant ?? null
160
166
  })).catch((error)=>handleResolverError({
161
167
  channel,
162
168
  error,
@@ -164,21 +170,24 @@ function createChannelRegistry() {
164
170
  }));
165
171
  }
166
172
  async function subscribe(context, { websocketId, payload, subscriber }) {
167
- const { connectionProperties, properties, websocketConfig, websocketResolver } = await prepareChannel(context, {
168
- websocketId,
169
- payload
170
- });
171
173
  // One subscription per websocketId per connection — a re-subscribe (e.g.
172
- // 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.
173
177
  if (subscriber.subscriptions.has(websocketId)) {
174
178
  unsubscribe({
175
179
  websocketId,
176
180
  subscriber
177
181
  });
178
182
  }
183
+ const { connectionProperties, properties, tenant, websocketConfig, websocketResolver } = await prepareChannel(context, {
184
+ websocketId,
185
+ payload
186
+ });
179
187
  const key = getChannelKey({
180
188
  connectionProperties,
181
189
  properties,
190
+ tenant,
182
191
  websocketId
183
192
  });
184
193
  let channel = channels.get(key);
@@ -190,6 +199,7 @@ function createChannelRegistry() {
190
199
  resolver: websocketResolver,
191
200
  connectionProperties,
192
201
  properties,
202
+ tenant,
193
203
  subscribers: new Set(),
194
204
  abortController: null,
195
205
  restartTimer: null,
@@ -237,7 +247,7 @@ function createChannelRegistry() {
237
247
  async function publish(context, { websocketId, payload }) {
238
248
  // Publish identity is evaluated without a subscription payload — channels
239
249
  // that fragment on _payload/_user in properties are not publish targets.
240
- const { connectionProperties, properties, websocketConfig, websocketResolver } = await prepareChannel(context, {
250
+ const { connectionProperties, properties, tenant, websocketConfig, websocketResolver } = await prepareChannel(context, {
241
251
  websocketId,
242
252
  payload: {}
243
253
  });
@@ -249,6 +259,7 @@ function createChannelRegistry() {
249
259
  const key = getChannelKey({
250
260
  connectionProperties,
251
261
  properties,
262
+ tenant,
252
263
  websocketId
253
264
  });
254
265
  const channel = channels.get(key);
@@ -13,12 +13,37 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { type } from '@lowdefy/helpers';
16
+ import { runInCredentialScope } from '@lowdefy/node-utils';
17
+ import getCallerFingerprint from './getCallerFingerprint.js';
16
18
  import redactErrorResponse from '../../response/redactErrorResponse.js';
19
+ import resolveWebsocketCaller from './resolveWebsocketCaller.js';
20
+ const CALLER_CHECK_INTERVAL_MS = 60 * 1000;
21
+ const CALLER_CHANGED_CODE = 4401;
22
+ const CALLER_CHECK_FAILED_CODE = 1011;
17
23
  // Wraps one client websocket connection: parses frames, dispatches
18
24
  // subscribe/unsubscribe/publish to the channel registry, and answers every
19
25
  // frame with an ack or an error so client actions never hang.
20
- function createWebSocketConnection(context, { registry, send }) {
26
+ //
27
+ // The context, and the caller on it, is the upgrade request's. A socket can
28
+ // stay open long after that request, so the caller is resolved again from the
29
+ // upgrade's headers before every subscribe and once a minute. When it signed
30
+ // out, lost its membership, changed roles or switched organization, the socket
31
+ // closes with code 4401; the client reconnects, which authenticates afresh.
32
+ // Each check is a live session read - nothing is cached, so a revoked session
33
+ // closes the socket within a minute.
34
+ function createWebSocketConnection(context, { closeSocket, headers, registry, send, strategies }) {
21
35
  const { logger } = context;
36
+ const callerFingerprint = getCallerFingerprint({
37
+ user: context.user
38
+ });
39
+ // websocketId → the tail of that feed's frame queue. A feed's frames are
40
+ // handled one at a time, in the order they arrive. A subscribe awaits its
41
+ // channel preparation, so without this an unsubscribe sent right after it
42
+ // would run first, find nothing to remove, and leave the subscription
43
+ // running for a client that no longer wants it. Feeds have separate queues,
44
+ // so a slow publish routine on one feed does not hold up the others.
45
+ const feedQueues = new Map();
46
+ let closed = false;
22
47
  const subscriber = {
23
48
  id: context.rid,
24
49
  subscriptions: new Map(),
@@ -43,17 +68,75 @@ function createWebSocketConnection(context, { registry, send }) {
43
68
  error: redactErrorResponse(context, error)
44
69
  }));
45
70
  }
46
- async function handleFrame(frame) {
47
- const { payload, requestId, websocketId } = frame;
48
- if (!type.isString(websocketId)) {
49
- sendError({
50
- message: 'Frame "websocketId" should be a string.',
51
- requestId
52
- });
71
+ function close() {
72
+ if (closed) {
53
73
  return;
54
74
  }
75
+ closed = true;
76
+ clearInterval(callerCheckTimer);
77
+ registry.unsubscribeAll({
78
+ subscriber
79
+ });
80
+ // A subscribe still being prepared registers after this point.
81
+ Promise.all(feedQueues.values()).then(()=>registry.unsubscribeAll({
82
+ subscriber
83
+ })).catch((error)=>context.handleError(error));
84
+ logger.debug({
85
+ event: 'ws_disconnect'
86
+ });
87
+ }
88
+ function closeWith({ code, reason }) {
89
+ close();
90
+ closeSocket({
91
+ code,
92
+ reason
93
+ });
94
+ }
95
+ // Returns true while the socket still acts for the caller it was opened with.
96
+ // A check that can not complete closes the socket too: the caller can not be
97
+ // vouched for, and the client's reconnect authenticates afresh.
98
+ async function checkCaller() {
99
+ let user;
100
+ try {
101
+ user = await resolveWebsocketCaller(context, {
102
+ headers,
103
+ strategies
104
+ });
105
+ } catch (error) {
106
+ if (!closed) {
107
+ context.handleError(error);
108
+ closeWith({
109
+ code: CALLER_CHECK_FAILED_CODE,
110
+ reason: 'caller-check-failed'
111
+ });
112
+ }
113
+ return false;
114
+ }
115
+ if (closed) {
116
+ return false;
117
+ }
118
+ if (getCallerFingerprint({
119
+ user
120
+ }) !== callerFingerprint) {
121
+ logger.info({
122
+ event: 'ws_caller_changed'
123
+ }, 'WebSocket caller changed - closing.');
124
+ closeWith({
125
+ code: CALLER_CHANGED_CODE,
126
+ reason: 'caller-changed'
127
+ });
128
+ return false;
129
+ }
130
+ return true;
131
+ }
132
+ async function handleFrame(frame) {
133
+ const { payload, requestId, websocketId } = frame;
55
134
  switch(frame.type){
56
135
  case 'subscribe':
136
+ if (!await checkCaller()) {
137
+ // The socket is closing; the client resubscribes on its next one.
138
+ return;
139
+ }
57
140
  await registry.subscribe(context, {
58
141
  websocketId,
59
142
  payload,
@@ -61,7 +144,8 @@ function createWebSocketConnection(context, { registry, send }) {
61
144
  });
62
145
  send(JSON.stringify({
63
146
  type: 'subscribed',
64
- websocketId
147
+ websocketId,
148
+ requestId
65
149
  }));
66
150
  return;
67
151
  case 'unsubscribe':
@@ -93,7 +177,52 @@ function createWebSocketConnection(context, { registry, send }) {
93
177
  });
94
178
  }
95
179
  }
180
+ async function processFrame(frame) {
181
+ if (closed) {
182
+ return;
183
+ }
184
+ try {
185
+ await handleFrame(frame);
186
+ } catch (error) {
187
+ logger.debug({
188
+ err: error
189
+ }, error.message);
190
+ // Authentication and authorization refusals are expected traffic - one
191
+ // warn line, no error log or Sentry report, but the client is still told.
192
+ if ([
193
+ 'AuthenticationError',
194
+ 'AuthorizationError',
195
+ 'TwoFactorEnrolmentRequiredError'
196
+ ].includes(error.name)) {
197
+ logger.warn({
198
+ event: 'ws_refused',
199
+ frameType: frame.type
200
+ }, error.message);
201
+ } else {
202
+ context.handleError(error);
203
+ }
204
+ sendErrorPayload({
205
+ error,
206
+ requestId: frame.requestId,
207
+ websocketId: frame.websocketId
208
+ });
209
+ }
210
+ }
211
+ function enqueue(websocketId, task) {
212
+ const handled = (feedQueues.get(websocketId) ?? Promise.resolve()).then(task);
213
+ const tail = handled.catch(()=>{});
214
+ feedQueues.set(websocketId, tail);
215
+ tail.then(()=>{
216
+ if (feedQueues.get(websocketId) === tail) {
217
+ feedQueues.delete(websocketId);
218
+ }
219
+ });
220
+ return handled;
221
+ }
96
222
  async function handleMessage(raw) {
223
+ if (closed) {
224
+ return;
225
+ }
97
226
  let frame;
98
227
  try {
99
228
  frame = JSON.parse(raw);
@@ -109,28 +238,21 @@ function createWebSocketConnection(context, { registry, send }) {
109
238
  });
110
239
  return;
111
240
  }
112
- try {
113
- await handleFrame(frame);
114
- } catch (error) {
115
- logger.debug({
116
- err: error
117
- }, error.message);
118
- context.handleError(error);
119
- sendErrorPayload({
120
- error,
121
- requestId: frame.requestId,
122
- websocketId: frame.websocketId
241
+ if (!type.isString(frame.websocketId)) {
242
+ sendError({
243
+ message: 'Frame "websocketId" should be a string.',
244
+ requestId: frame.requestId
123
245
  });
246
+ return;
124
247
  }
248
+ // A frame arrives outside any HTTP request, so it gets its own credential scope for the
249
+ // routines it runs.
250
+ await enqueue(frame.websocketId, ()=>runInCredentialScope(()=>processFrame(frame)));
125
251
  }
126
- function close() {
127
- registry.unsubscribeAll({
128
- subscriber
129
- });
130
- logger.debug({
131
- event: 'ws_disconnect'
132
- });
133
- }
252
+ // One timer per connection, cleared by close. It does not keep the process
253
+ // alive on its own.
254
+ const callerCheckTimer = setInterval(checkCaller, CALLER_CHECK_INTERVAL_MS);
255
+ callerCheckTimer.unref();
134
256
  logger.debug({
135
257
  event: 'ws_connect'
136
258
  });
@@ -0,0 +1,31 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { type } from '@lowdefy/helpers';
16
+ // The parts of a caller that decide what a websocket may deliver to it: who
17
+ // they are, the organization they act in and their roles. Other caller fields
18
+ // (name, attributes) may change without the socket needing to close.
19
+ function getCallerFingerprint({ user }) {
20
+ if (type.isNone(user)) {
21
+ return null;
22
+ }
23
+ return JSON.stringify({
24
+ id: user.id ?? null,
25
+ organizationId: user.organization_id ?? null,
26
+ roles: [
27
+ ...user.roles ?? []
28
+ ].sort()
29
+ });
30
+ }
31
+ export default getCallerFingerprint;
@@ -14,10 +14,12 @@
14
14
  limitations under the License.
15
15
  */ import { type } from '@lowdefy/helpers';
16
16
  import authorizeWebsocket from './authorizeWebsocket.js';
17
+ import checkConnectionRead from '../request/checkConnectionRead.js';
17
18
  import getConnection from '../connections/getConnection.js';
18
19
  import getConnectionConfig from '../connections/getConnectionConfig.js';
19
20
  import getWebsocketConfig from './getWebsocketConfig.js';
20
21
  import getWebsocketResolver from './getWebsocketResolver.js';
22
+ import resolveTenancy from '../request/resolveTenancy.js';
21
23
  import createEvaluateOperators from '../../context/createEvaluateOperators.js';
22
24
  // Shared preparation for subscribe and publish frames: load config, authorize,
23
25
  // resolve the websocket type, and evaluate server operators per subscription.
@@ -37,6 +39,7 @@ async function prepareChannel(context, { websocketId, payload }) {
37
39
  websocketConfig
38
40
  });
39
41
  let connectionProperties = null;
42
+ let tenant = null;
40
43
  if (!type.isNone(websocketConfig.connectionId)) {
41
44
  const connectionConfig = await getConnectionConfig(context, {
42
45
  connectionId: websocketConfig.connectionId,
@@ -44,9 +47,19 @@ async function prepareChannel(context, { websocketId, payload }) {
44
47
  });
45
48
  // Validates the connection type exists — resolver lookup is on the
46
49
  // websocket type itself, not nested on the connection.
47
- getConnection(context, {
50
+ const connection = getConnection(context, {
48
51
  connectionConfig
49
52
  });
53
+ // A change stream is a read on a separate execution path — the tenant
54
+ // verdict is resolved per subscriber exactly like per request, and joins
55
+ // the channel identity so callers from different orgs never share a
56
+ // running source (see createChannelRegistry getChannelKey).
57
+ // A change stream only reads, so the write guard does not apply.
58
+ ({ tenant } = resolveTenancy(context, {
59
+ connection,
60
+ connectionConfig,
61
+ requestConfig: websocketConfig
62
+ }));
50
63
  connectionProperties = context.evaluateOperators({
51
64
  input: connectionConfig.properties ?? {},
52
65
  location: connectionConfig.connectionId,
@@ -54,6 +67,20 @@ async function prepareChannel(context, { websocketId, payload }) {
54
67
  state: {},
55
68
  steps: {}
56
69
  });
70
+ // A subscription reads the connection, so a connection that refuses reads
71
+ // refuses subscriptions, as it refuses read requests. Unlike a request
72
+ // type, a websocket type is checked unless its meta opts out with
73
+ // checkRead: false - a type that declares nothing still reads.
74
+ checkConnectionRead(context, {
75
+ connectionConfig,
76
+ connectionProperties,
77
+ requestConfig: websocketConfig,
78
+ requestResolver: {
79
+ meta: {
80
+ checkRead: websocketResolver.meta?.checkRead !== false
81
+ }
82
+ }
83
+ });
57
84
  }
58
85
  const properties = context.evaluateOperators({
59
86
  input: websocketConfig.properties ?? {},
@@ -65,6 +92,7 @@ async function prepareChannel(context, { websocketId, payload }) {
65
92
  return {
66
93
  connectionProperties,
67
94
  properties,
95
+ tenant,
68
96
  websocketConfig,
69
97
  websocketResolver
70
98
  };
@@ -0,0 +1,40 @@
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 resolveAuthentication from '../../context/resolveAuthentication.js';
17
+ // Resolves the caller a websocket is acting for now, from the headers of its
18
+ // upgrade request - the session cookie, or the credentials an API strategy
19
+ // reads. Resolution runs on a separate object, so the connection's context
20
+ // keeps the caller it was opened with and the two can be compared.
21
+ //
22
+ // A context with no auth engine has a caller that was fixed when the context
23
+ // was built: no auth is configured, or the dev or e2e server injected a
24
+ // pre-resolved caller. There is no session to follow, so the caller stays.
25
+ async function resolveWebsocketCaller(context, { headers, strategies }) {
26
+ if (type.isNone(context.auth)) {
27
+ return context.user;
28
+ }
29
+ const resolved = {
30
+ config: context.config,
31
+ logger: context.logger
32
+ };
33
+ await resolveAuthentication(resolved, {
34
+ auth: context.auth,
35
+ headers,
36
+ strategies
37
+ });
38
+ return resolved.user;
39
+ }
40
+ export default resolveWebsocketCaller;
@@ -12,24 +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 createAuthorize from '../context/createAuthorize.js';
16
- function testContext({ appMeta = {}, config = {}, configDirectory, connections = {}, headers = {}, logger = {
15
+ */ import createAuthorizeOutcome from '../context/createAuthorizeOutcome.js';
16
+ function testContext({ appMeta = {}, auth, authEnforcement = null, config = {}, configDirectory, connections = {}, headers = {}, logger = {
17
17
  debug: ()=>{},
18
18
  error: ()=>{},
19
19
  info: ()=>{},
20
20
  warn: ()=>{}
21
21
  }, mode = 'prod', operators = {
22
22
  _test: ()=>'test'
23
- }, readConfigFile, scrubSecrets = (value)=>value, secrets = {}, session, system } = {}) {
23
+ }, organization = null, readConfigFile, scrubSecrets = (value)=>value, secrets = {}, steps = {}, system, user = null } = {}) {
24
24
  return {
25
25
  appMeta,
26
- authorize: createAuthorize({
27
- session,
28
- system
26
+ auth,
27
+ authEnforcement,
28
+ authorizeOutcome: createAuthorizeOutcome({
29
+ authEnforcement,
30
+ system,
31
+ user
29
32
  }),
30
33
  config,
31
34
  configDirectory,
32
35
  connections,
36
+ organization,
37
+ system,
33
38
  // Mirrors the servers' createHandleError contract: the sink logs the error
34
39
  // and marks it handled, which is what runRoutine's guard and the client's
35
40
  // already-logged check both read.
@@ -44,10 +49,8 @@ function testContext({ appMeta = {}, config = {}, configDirectory, connections =
44
49
  readConfigFile,
45
50
  scrubSecrets,
46
51
  secrets,
47
- session,
48
- steps: {},
49
- system,
50
- user: session?.user
52
+ steps,
53
+ user
51
54
  };
52
55
  }
53
56
  export default testContext;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lowdefy/api",
3
- "version": "6.1.0",
3
+ "version": "7.1.0",
4
4
  "license": "Apache-2.0",
5
5
  "description": "",
6
6
  "homepage": "https://lowdefy.com",
@@ -28,28 +28,43 @@
28
28
  "exports": {
29
29
  ".": "./dist/index.js",
30
30
  "./context/*": "./dist/context/*",
31
+ "./csp/*": "./dist/csp/*",
31
32
  "./routes/*": "./dist/routes/*"
32
33
  },
33
34
  "files": [
34
35
  "dist/*"
35
36
  ],
36
37
  "dependencies": {
37
- "@lowdefy/ajv": "6.1.0",
38
- "@lowdefy/build": "6.1.0",
39
- "@lowdefy/errors": "6.1.0",
40
- "@lowdefy/helpers": "6.1.0",
41
- "@lowdefy/node-utils": "6.1.0",
42
- "@lowdefy/nunjucks": "6.1.0",
43
- "@lowdefy/operators": "6.1.0",
44
- "@lowdefy/operators-js": "6.1.0",
45
- "@modelcontextprotocol/sdk": "1.29.0"
38
+ "@better-auth/cimd": "1.7.7",
39
+ "@better-auth/oauth-provider": "1.7.7",
40
+ "@better-auth/passkey": "1.7.7",
41
+ "@lowdefy/ajv": "7.1.0",
42
+ "@lowdefy/build": "7.1.0",
43
+ "@lowdefy/connection-smtp": "7.1.0",
44
+ "@lowdefy/email-templates": "7.1.0",
45
+ "@lowdefy/errors": "7.1.0",
46
+ "@lowdefy/helpers": "7.1.0",
47
+ "@lowdefy/node-utils": "7.1.0",
48
+ "@lowdefy/nunjucks": "7.1.0",
49
+ "@lowdefy/operators": "7.1.0",
50
+ "@lowdefy/operators-js": "7.1.0",
51
+ "@modelcontextprotocol/sdk": "1.31.0",
52
+ "better-auth": "1.7.7",
53
+ "jose": "^6.2.3",
54
+ "mongodb-connection-string-url": "^7.0.2",
55
+ "nodemailer": "10.0.13"
46
56
  },
47
57
  "devDependencies": {
48
58
  "@jest/globals": "28.1.3",
59
+ "@lowdefy/connection-mongodb": "7.1.0",
60
+ "@lowdefy/plugin-better-auth": "7.1.0",
61
+ "@opentelemetry/api": "1.9.1",
62
+ "@shelf/jest-mongodb": "4.3.2",
49
63
  "@swc/cli": "0.8.1",
50
64
  "@swc/core": "1.15.32",
51
65
  "@swc/jest": "0.2.39",
52
- "jest": "28.1.3"
66
+ "jest": "28.1.3",
67
+ "mongodb": "7.2.0"
53
68
  },
54
69
  "publishConfig": {
55
70
  "access": "public"
@@ -57,6 +72,7 @@
57
72
  "scripts": {
58
73
  "build": "swc src --out-dir dist --config-file ../../.swcrc --cli-config-file ../../.swc-cli.json",
59
74
  "clean": "rm -rf dist",
60
- "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
75
+ "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
76
+ "test:mongodb": "node --experimental-vm-modules node_modules/jest/bin/jest.js --config jest.mongodb.config.js"
61
77
  }
62
78
  }
@@ -1,45 +0,0 @@
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
- function createAuthorize({ session, system = false }) {
17
- // Next-auth getSession provides a session object if the user is authenticated
18
- // else session will be null
19
- const authenticated = !!session;
20
- const roles = session?.user?.roles ?? [];
21
- if (!Array.isArray(roles)) {
22
- throw new ConfigError('session.user.roles must be an array of strings.', {
23
- received: roles
24
- });
25
- }
26
- function authorize(config) {
27
- // A system context (scheduled, webhook, detached runs) was authorized at the
28
- // transport layer, so nested endpoint calls are never gated on a user session.
29
- if (system === true) return true;
30
- const { auth } = config;
31
- if (auth.public === true) return true;
32
- if (auth.public === false) {
33
- if (auth.roles) {
34
- return authenticated && auth.roles.some((role)=>roles.includes(role));
35
- }
36
- return authenticated;
37
- }
38
- throw new ConfigError('auth.public must be true or false.', {
39
- received: auth.public,
40
- configKey: config['~k']
41
- });
42
- }
43
- return authorize;
44
- }
45
- export default createAuthorize;
@@ -1,30 +0,0 @@
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 { get, set } from '@lowdefy/helpers';
16
- function addUserFieldsToToken({ account, authConfig, logger, profile, token, user }) {
17
- const objects = {
18
- account,
19
- profile,
20
- user
21
- };
22
- logger.debug('Adding userFields to user. Available provider data is:');
23
- logger.debug(objects);
24
- Object.entries(authConfig.userFields).forEach(([lowdefyFieldName, providerFieldName])=>{
25
- const value = get(objects, providerFieldName);
26
- logger.debug(`Adding provider field "${providerFieldName}" with value ${JSON.stringify(value)} as "${lowdefyFieldName}"`);
27
- set(token, lowdefyFieldName, value);
28
- });
29
- }
30
- export default addUserFieldsToToken;