@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
@@ -13,15 +13,44 @@
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';
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;
16
23
  // Wraps one client websocket connection: parses frames, dispatches
17
24
  // subscribe/unsubscribe/publish to the channel registry, and answers every
18
25
  // frame with an ack or an error so client actions never hang.
19
- 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 }) {
20
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;
21
47
  const subscriber = {
22
48
  id: context.rid,
23
49
  subscriptions: new Map(),
24
- send
50
+ send,
51
+ // A shared channel broadcasts to every subscriber, so each one carries its
52
+ // own locale for the error message it is sent.
53
+ i18n: context.i18n
25
54
  };
26
55
  function sendError({ message, requestId, websocketId }) {
27
56
  send(JSON.stringify({
@@ -31,17 +60,83 @@ function createWebSocketConnection(context, { registry, send }) {
31
60
  message
32
61
  }));
33
62
  }
34
- async function handleFrame(frame) {
35
- const { payload, requestId, websocketId } = frame;
36
- if (!type.isString(websocketId)) {
37
- sendError({
38
- message: 'Frame "websocketId" should be a string.',
39
- requestId
40
- });
63
+ function sendErrorPayload({ error, requestId, websocketId }) {
64
+ send(JSON.stringify({
65
+ type: 'error',
66
+ websocketId,
67
+ requestId,
68
+ error: redactErrorResponse(context, error)
69
+ }));
70
+ }
71
+ function close() {
72
+ if (closed) {
41
73
  return;
42
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;
43
134
  switch(frame.type){
44
135
  case 'subscribe':
136
+ if (!await checkCaller()) {
137
+ // The socket is closing; the client resubscribes on its next one.
138
+ return;
139
+ }
45
140
  await registry.subscribe(context, {
46
141
  websocketId,
47
142
  payload,
@@ -49,7 +144,8 @@ function createWebSocketConnection(context, { registry, send }) {
49
144
  });
50
145
  send(JSON.stringify({
51
146
  type: 'subscribed',
52
- websocketId
147
+ websocketId,
148
+ requestId
53
149
  }));
54
150
  return;
55
151
  case 'unsubscribe':
@@ -81,7 +177,52 @@ function createWebSocketConnection(context, { registry, send }) {
81
177
  });
82
178
  }
83
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
+ }
84
222
  async function handleMessage(raw) {
223
+ if (closed) {
224
+ return;
225
+ }
85
226
  let frame;
86
227
  try {
87
228
  frame = JSON.parse(raw);
@@ -97,28 +238,21 @@ function createWebSocketConnection(context, { registry, send }) {
97
238
  });
98
239
  return;
99
240
  }
100
- try {
101
- await handleFrame(frame);
102
- } catch (error) {
103
- logger.debug({
104
- err: error
105
- }, error.message);
106
- context.handleError(error);
241
+ if (!type.isString(frame.websocketId)) {
107
242
  sendError({
108
- message: error.message,
109
- requestId: frame.requestId,
110
- websocketId: frame.websocketId
243
+ message: 'Frame "websocketId" should be a string.',
244
+ requestId: frame.requestId
111
245
  });
246
+ return;
112
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)));
113
251
  }
114
- function close() {
115
- registry.unsubscribeAll({
116
- subscriber
117
- });
118
- logger.debug({
119
- event: 'ws_disconnect'
120
- });
121
- }
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();
122
256
  logger.debug({
123
257
  event: 'ws_connect'
124
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
- }, operators = {
21
+ }, mode = 'prod', operators = {
22
22
  _test: ()=>'test'
23
- }, readConfigFile, 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.
@@ -39,13 +44,13 @@ function testContext({ appMeta = {}, config = {}, configDirectory, connections =
39
44
  },
40
45
  headers,
41
46
  logger,
47
+ mode,
42
48
  operators,
43
49
  readConfigFile,
50
+ scrubSecrets,
44
51
  secrets,
45
- session,
46
- steps: {},
47
- system,
48
- user: session?.user
52
+ steps,
53
+ user
49
54
  };
50
55
  }
51
56
  export default testContext;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lowdefy/api",
3
- "version": "6.0.0",
3
+ "version": "7.0.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.0.0",
38
- "@lowdefy/build": "6.0.0",
39
- "@lowdefy/errors": "6.0.0",
40
- "@lowdefy/helpers": "6.0.0",
41
- "@lowdefy/node-utils": "6.0.0",
42
- "@lowdefy/nunjucks": "6.0.0",
43
- "@lowdefy/operators": "6.0.0",
44
- "@lowdefy/operators-js": "6.0.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.0.0",
42
+ "@lowdefy/build": "7.0.0",
43
+ "@lowdefy/connection-smtp": "7.0.0",
44
+ "@lowdefy/email-templates": "7.0.0",
45
+ "@lowdefy/errors": "7.0.0",
46
+ "@lowdefy/helpers": "7.0.0",
47
+ "@lowdefy/node-utils": "7.0.0",
48
+ "@lowdefy/nunjucks": "7.0.0",
49
+ "@lowdefy/operators": "7.0.0",
50
+ "@lowdefy/operators-js": "7.0.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.0.0",
60
+ "@lowdefy/plugin-better-auth": "7.0.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,51 +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 { UserError } from '@lowdefy/errors';
16
- import { type } from '@lowdefy/helpers';
17
- // The client-bound error policy: which fields of an error may cross the wire.
18
- // Passed to serializer.serialize as `omitErrorProps`, so extractErrorProps applies
19
- // it at EVERY error node the walk emits - the cause chain, an Error-valued own
20
- // property, and an Error nested inside a plain object or array. The policy is
21
- // stated against the emitter rather than against a response shape, so it cannot
22
- // become depth-limited.
23
- //
24
- // `received` is not merely "may be sensitive": on the request path
25
- // callRequestResolver sets it to the EVALUATED request properties, so a _secret
26
- // resolved into a request header is in it. `stack` exposes server internals,
27
- // including absolute node_modules paths. Both are unbounded runtime data nobody
28
- // chose, in every environment - the full value stays in the server log, which is
29
- // where a developer on their own machine reads it.
30
- const ALWAYS_OMITTED = [
31
- 'received',
32
- 'stack'
33
- ];
34
- const OMITTED_WITH_CAUSE = [
35
- ...ALWAYS_OMITTED,
36
- 'cause'
37
- ];
38
- function omitErrorProps(error) {
39
- // An Error cause is the trace the browser renders (name + message per level),
40
- // so it is always kept - fields are taken from causes, causes are never pruned.
41
- // A non-Error cause is internal server config: the whole endpoint routine, a
42
- // control node, ajv errors. UserError is the exception, the one class whose
43
- // payload the author wrote for the client.
44
- //
45
- // type.isError is `instanceof Error`, the same test extractErrorProps uses to
46
- // decide which branch emits the cause - the two must agree.
47
- if (type.isError(error.cause)) return ALWAYS_OMITTED;
48
- if (error instanceof UserError) return ALWAYS_OMITTED;
49
- return OMITTED_WITH_CAUSE;
50
- }
51
- export default omitErrorProps;
@@ -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;