@lowdefy/api 6.1.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 (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
@@ -12,13 +12,17 @@
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 { type } from '@lowdefy/helpers';
15
+ */ import { normalizeCaller, type } from '@lowdefy/helpers';
16
16
  // Tries the configured API auth strategies in config order; the first
17
17
  // verifier match wins. A strategy caller is a config-derived, org-less
18
18
  // principal: roles are the strategy's static grant unioned with any
19
19
  // claim-derived roles, and attributes are the static bag shallow-merged
20
20
  // with claim-mapped values (claim wins), so _user.attributes reads the same
21
21
  // for session and strategy callers.
22
+ //
23
+ // normalizeCaller gives it the same snake_case key shape as the session
24
+ // caller, over the verifier's user fields as well as the two stamped here -
25
+ // app config reads one caller shape whichever branch resolved it.
22
26
  async function resolveStrategyCaller({ headers, logger, strategies }) {
23
27
  for (const strategy of strategies ?? []){
24
28
  const match = await strategy.verify({
@@ -43,13 +47,13 @@ async function resolveStrategyCaller({ headers, logger, strategies }) {
43
47
  authMethod: strategy.type,
44
48
  strategyId: strategy.id
45
49
  }, `Request authenticated by auth strategy "${strategy.id}" (${strategy.type}).`);
46
- return {
50
+ return normalizeCaller({
47
51
  ...match.user,
48
52
  authMethod: strategy.type,
49
53
  strategyId: strategy.id,
50
54
  roles,
51
55
  attributes
52
- };
56
+ });
53
57
  }
54
58
  return null;
55
59
  }
@@ -0,0 +1,23 @@
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
+ */ // Each script and style element in app.html.appendHead / appendBody gets the
16
+ // render's nonce, so author snippets keep running under the policy. Matching
17
+ // whole elements (up to the first closing tag, as the HTML parser does) leaves
18
+ // "<script" text inside a script body untouched.
19
+ const ELEMENT_PATTERN = /<(script|style)\b([^>]*)>([\s\S]*?)<\/\1(\s*)>/gi;
20
+ function addNonceToElements({ html, nonce }) {
21
+ return html.replace(ELEMENT_PATTERN, (_, tag, attributes, body, closingSpace)=>`<${tag} nonce="${nonce}"${attributes}>${body}</${tag}${closingSpace}>`);
22
+ }
23
+ export default addNonceToElements;
@@ -0,0 +1,45 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import crypto from 'node:crypto';
16
+ import getWebSocketSources from './getWebSocketSources.js';
17
+ // Builds the header for one page render from the policy the build resolved
18
+ // (build/security.json). Each call draws a new 128-bit nonce, which the page's
19
+ // inline scripts and styles carry.
20
+ function createContentSecurityPolicy({ policy, requestUrl, allowWebSocket }) {
21
+ const nonce = crypto.randomBytes(16).toString('base64');
22
+ const directives = Object.entries(policy.directives).map(([directive, sources])=>{
23
+ const directiveSources = [
24
+ ...sources
25
+ ];
26
+ if (policy.nonceDirectives.includes(directive)) {
27
+ directiveSources.push(`'nonce-${nonce}'`);
28
+ }
29
+ if (directive === 'connect-src' && allowWebSocket) {
30
+ directiveSources.push(...getWebSocketSources({
31
+ requestUrl
32
+ }));
33
+ }
34
+ return [
35
+ directive,
36
+ ...directiveSources
37
+ ].join(' ');
38
+ });
39
+ return {
40
+ name: policy.reportOnly ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy',
41
+ nonce,
42
+ value: directives.join('; ')
43
+ };
44
+ }
45
+ export default createContentSecurityPolicy;
@@ -0,0 +1,36 @@
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
+ */ // The page's websocket (and in dev, Vite's hot reload socket) connects to the host the page
16
+ // was served from. Older browsers do not match 'self' against ws: and wss:, so the policy
17
+ // names that host. ws: is listed only when the request itself arrived over plain http.
18
+ // A host that is not a plain hostname, IPv4 or bracketed IPv6 address with an optional
19
+ // port is not written into the header.
20
+ const HOST_PATTERN = /^([a-z0-9.-]+|\[[0-9a-f:.]+\])(:\d+)?$/i;
21
+ function getWebSocketSources({ requestUrl }) {
22
+ const { host, protocol } = new URL(requestUrl);
23
+ if (!HOST_PATTERN.test(host)) {
24
+ return [];
25
+ }
26
+ if (protocol === 'http:') {
27
+ return [
28
+ `ws://${host}`,
29
+ `wss://${host}`
30
+ ];
31
+ }
32
+ return [
33
+ `wss://${host}`
34
+ ];
35
+ }
36
+ export default getWebSocketSources;
@@ -0,0 +1,99 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { ConfigError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ import { EmailOTPEmail, InvitationEmail, MagicLinkEmail, ResetPasswordEmail, VerifyEmail, interpolateProperties, renderEmail } from '@lowdefy/email-templates';
18
+ import getNotificationConfig from '../routes/notifications/getNotificationConfig.js';
19
+ import resolveThemeLogo from './resolveThemeLogo.js';
20
+ const stockTemplates = {
21
+ verifyEmail: VerifyEmail,
22
+ resetPassword: ResetPasswordEmail,
23
+ magicLink: MagicLinkEmail,
24
+ invitation: InvitationEmail,
25
+ emailOTP: EmailOTPEmail
26
+ };
27
+ // Single render path for the auth email flows. Resolves the flow's template
28
+ // (a stock component by default, or an app-configured override notification when
29
+ // auth.email.templates[flow] names one), applies the app.email brand, and returns
30
+ // { subject, html, text }. Pure render — it never sends.
31
+ async function renderAuthEmail({ flow, vars, authEmailConfig, baseURL, context }) {
32
+ const app = await context.readConfigFile('app.json') ?? {};
33
+ const basePath = context.config?.basePath ?? '';
34
+ // baseURL is the pinned origin the caller resolved; without a usable origin
35
+ // string relative logos cannot be fetched by an email client, so they drop.
36
+ const serverUrl = type.isString(baseURL) ? baseURL : undefined;
37
+ const notificationId = authEmailConfig?.templates?.[flow];
38
+ if (type.isString(notificationId)) {
39
+ const notificationConfig = await getNotificationConfig(context, {
40
+ notificationId
41
+ });
42
+ const Template = context.notifications?.[notificationConfig.type];
43
+ if (!Template) {
44
+ throw new ConfigError(`Notification template type "${notificationConfig.type}" can not be found.`, {
45
+ configKey: notificationConfig['~k']
46
+ });
47
+ }
48
+ // Resolve after the merge so a per-notification theme.logo override also
49
+ // resolves; precedence stays notification theme over app.email.
50
+ const theme = resolveThemeLogo({
51
+ theme: {
52
+ ...app.email ?? {},
53
+ ...notificationConfig.theme ?? {}
54
+ },
55
+ serverUrl,
56
+ basePath
57
+ });
58
+ const interpolated = interpolateProperties({
59
+ properties: notificationConfig.properties,
60
+ data: vars,
61
+ markdownProperties: Template.markdownProperties ?? []
62
+ });
63
+ const { html, text } = await renderEmail({
64
+ Template,
65
+ properties: interpolated,
66
+ data: vars,
67
+ theme,
68
+ links: {}
69
+ });
70
+ return {
71
+ subject: interpolated.subject,
72
+ html,
73
+ text
74
+ };
75
+ }
76
+ const Template = stockTemplates[flow];
77
+ if (!Template) {
78
+ throw new ConfigError(`Unknown auth email flow "${flow}".`);
79
+ }
80
+ const theme = resolveThemeLogo({
81
+ theme: app.email ?? {},
82
+ serverUrl,
83
+ basePath
84
+ });
85
+ const { html, text } = await renderEmail({
86
+ Template,
87
+ properties: vars,
88
+ data: vars,
89
+ theme,
90
+ links: {}
91
+ });
92
+ const subject = type.isFunction(Template.subject) ? Template.subject(vars) : Template.subject;
93
+ return {
94
+ subject,
95
+ html,
96
+ text
97
+ };
98
+ }
99
+ export default renderAuthEmail;
package/dist/index.js CHANGED
@@ -12,28 +12,44 @@
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 buildEndpointResult from './response/buildEndpointResult.js';
15
+ */ import addNonceToElements from './csp/addNonceToElements.js';
16
+ import buildEndpointResult from './response/buildEndpointResult.js';
16
17
  import callAgent from './routes/agent/callAgent.js';
17
18
  import callEndpoint from './routes/endpoints/callEndpoint.js';
18
19
  import getEndpointConfig from './routes/endpoints/getEndpointConfig.js';
19
20
  import callRequest from './routes/request/callRequest.js';
20
21
  import createApiContext from './context/createApiContext.js';
22
+ import createAsMetadataHandler from './routes/auth/createAsMetadataHandler.js';
21
23
  import createChannelRegistry from './routes/websocket/createChannelRegistry.js';
24
+ import createContentSecurityPolicy from './csp/createContentSecurityPolicy.js';
22
25
  import createMcpServer from './routes/mcp/createMcpServer.js';
26
+ import createRequestSignal from './context/createRequestSignal.js';
27
+ import createSystemContext from './context/createSystemContext.js';
23
28
  import createWebSocketConnection from './routes/websocket/createWebSocketConnection.js';
24
29
  import createWireProjection from './response/createWireProjection.js';
25
- import createSessionCallback from './routes/auth/callbacks/createSessionCallback.js';
26
- import getAuthConfig from './routes/auth/getAuthConfig.js';
27
30
  import getAuthStrategies from './routes/auth/strategies/getAuthStrategies.js';
31
+ import getBetterAuth from './routes/auth/getBetterAuth.js';
32
+ import { MCP_OAUTH_SCOPES } from './routes/auth/getBetterAuthConfig.js';
33
+ import handleAuthRequest from './routes/auth/handleAuthRequest.js';
34
+ import { getAsIssuer, getMcpResourceMetadataUri, getMcpResourceUri } from './routes/mcp/getMcpUri.js';
35
+ import getMcpResourceBinding, { registerMcpResourceBinding } from './routes/mcp/getMcpResourceBinding.js';
36
+ import { ensureMcpOauthResource } from './routes/mcp/oauthResourceLifecycle.js';
28
37
  import getHomeAndMenus from './routes/rootConfig/getHomeAndMenus.js';
29
- import resolveStrategyCaller from './context/resolveStrategyCaller.js';
30
38
  import getPageConfig from './routes/page/getPageConfig.js';
31
39
  import getRootConfig from './routes/rootConfig/getRootConfig.js';
40
+ import isSameOriginRequest from './context/isSameOriginRequest.js';
41
+ import isWebSocketOriginAllowed from './context/isWebSocketOriginAllowed.js';
32
42
  import logClientError from './routes/log/logClientError.js';
43
+ import normalizeInjectedCaller from './context/normalizeInjectedCaller.js';
44
+ import parseRequestBody from './context/parseRequestBody.js';
33
45
  import redactErrorResponse from './response/redactErrorResponse.js';
34
46
  import redactResponse from './response/redactResponse.js';
47
+ import resolveAuthentication from './context/resolveAuthentication.js';
48
+ import resolvePinnedOrganization from './routes/auth/organizations/resolvePinnedOrganization.js';
49
+ import resolveTenantPreflight, { getTenantIntegrityStatus } from './routes/connections/resolveTenantPreflight.js';
35
50
  import forwardScheduledEndpoint from './routes/endpoints/forwardScheduledEndpoint.js';
51
+ import acceptDetachedEndpoint from './routes/endpoints/acceptDetachedEndpoint.js';
36
52
  import runDetachedEndpoint from './routes/endpoints/runDetachedEndpoint.js';
37
53
  import runWebhookEndpoint from './routes/endpoints/runWebhookEndpoint.js';
38
54
  import runScheduledEndpoint from './routes/endpoints/runScheduledEndpoint.js';
39
- export { buildEndpointResult, callAgent, callEndpoint, getEndpointConfig, callRequest, createApiContext, createChannelRegistry, createMcpServer, createSessionCallback, createWebSocketConnection, createWireProjection, getAuthConfig, getAuthStrategies, getHomeAndMenus, getPageConfig, getRootConfig, logClientError, redactErrorResponse, redactResponse, resolveStrategyCaller, forwardScheduledEndpoint, runDetachedEndpoint, runWebhookEndpoint, runScheduledEndpoint };
55
+ export { addNonceToElements, buildEndpointResult, callAgent, callEndpoint, getEndpointConfig, callRequest, createApiContext, createAsMetadataHandler, createChannelRegistry, createContentSecurityPolicy, createMcpServer, createRequestSignal, createSystemContext, createWebSocketConnection, createWireProjection, ensureMcpOauthResource, getAsIssuer, getAuthStrategies, getBetterAuth, MCP_OAUTH_SCOPES, getHomeAndMenus, handleAuthRequest, getMcpResourceBinding, getMcpResourceMetadataUri, getMcpResourceUri, registerMcpResourceBinding, getPageConfig, getRootConfig, isSameOriginRequest, isWebSocketOriginAllowed, logClientError, normalizeInjectedCaller, parseRequestBody, redactErrorResponse, redactResponse, resolveAuthentication, resolvePinnedOrganization, getTenantIntegrityStatus, resolveTenantPreflight, forwardScheduledEndpoint, acceptDetachedEndpoint, runDetachedEndpoint, runWebhookEndpoint, runScheduledEndpoint };
@@ -0,0 +1,35 @@
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 createWireProjection from './createWireProjection.js';
17
+ // The text an MCP tool caller reads when an endpoint fails. A dev MCP client is a
18
+ // coding agent, a dev tool: the message carries the resolved config location and
19
+ // any hint so it can go straight to the yaml. A prod MCP client is an end-user
20
+ // reader and gets the wire message - the author's message or the generic one -
21
+ // so no library text or server path reaches it.
22
+ function formatErrorForAgent(context, error) {
23
+ if (context.mode !== 'dev') {
24
+ return createWireProjection(context)(error).message;
25
+ }
26
+ let text = error.message;
27
+ if (!type.isNone(error.source)) {
28
+ text = `${text} (at ${error.source})`;
29
+ }
30
+ if (!type.isNone(error.hint)) {
31
+ text = `${text} Hint: ${error.hint}`;
32
+ }
33
+ return text;
34
+ }
35
+ export default formatErrorForAgent;
@@ -23,9 +23,16 @@ import createWireProjection from './createWireProjection.js';
23
23
  // Same wire projection as the error field, because it reaches the same audience.
24
24
  // No devError, in any mode: an Error in a response value is data the routine
25
25
  // returned, not a failure of this request.
26
+ //
27
+ // A response built from config (a :return literal, a :set_state value read back)
28
+ // keeps the config's ~k, ~r and ~l markers as hidden properties. They are
29
+ // dropped here: the response is data, and a caller that is not the Lowdefy
30
+ // client (the third party calling a webhook endpoint, a dev tool, any HTTP
31
+ // client) reads the wire as it is.
26
32
  function redactResponse(context, response) {
27
33
  return serializer.serialize(response, {
28
- projectError: createWireProjection(context)
34
+ projectError: createWireProjection(context),
35
+ skipMarkers: true
29
36
  });
30
37
  }
31
38
  export default redactResponse;
@@ -12,17 +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 { ConfigError } from '@lowdefy/errors';
16
- import { translate } from '@lowdefy/helpers';
17
- function authorizeAgent({ authorize, i18n, logger }, { agentConfig }) {
18
- if (!authorize(agentConfig)) {
15
+ */ import { AuthenticationError, AuthorizationError, TwoFactorEnrolmentRequiredError } from '@lowdefy/errors';
16
+ import { translate, type } from '@lowdefy/helpers';
17
+ function authorizeAgent({ authorizeOutcome, i18n, logger, user }, { agentConfig }) {
18
+ const outcome = authorizeOutcome(agentConfig);
19
+ if (outcome !== 'allow') {
19
20
  logger.debug({
20
21
  event: 'debug_agent_authorize',
21
22
  authorized: false,
23
+ outcome,
22
24
  auth_config: agentConfig.auth
23
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 which agents exist.
29
+ throw new TwoFactorEnrolmentRequiredError(`Two-factor enrolment required for agent "${agentConfig.agentId}".`);
30
+ }
31
+ // Unauthenticated on a protected agent - 401 tells the caller to fix
32
+ // its credentials. Wrong roles stay opaque below.
33
+ if (type.isNone(user)) {
34
+ throw new AuthenticationError(`Authentication required for agent "${agentConfig.agentId}".`);
35
+ }
24
36
  // Same message as an unknown agentId so responses do not reveal which agents exist.
25
- throw new ConfigError(translate({
37
+ throw new AuthorizationError(translate({
26
38
  key: 'agent.runtime.agentNotFound',
27
39
  values: {
28
40
  agentId: agentConfig.agentId
@@ -12,12 +12,17 @@
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 createEvaluateOperators from '../../context/createEvaluateOperators.js';
15
+ */ import collectChatFiles from './collectChatFiles.js';
16
+ import createEvaluateOperators from '../../context/createEvaluateOperators.js';
16
17
  import prepareAgent from './prepareAgent.js';
17
- async function callAgent(context, { agentId, pageId, messages, conversationId, urlQuery, sharedState }) {
18
+ async function callAgent(context, { agentId, pageId, messages, conversationId, pathParams, urlQuery, sharedState, sharedStateReadOnly }) {
18
19
  const { logger } = context;
19
20
  context.pageId = pageId;
20
21
  context.evaluateOperators = createEvaluateOperators(context);
22
+ // A chat run is not cancelled when the client disconnects: it runs to its end so the
23
+ // onFinish hooks still persist the whole conversation, bounded by the agent's timeout
24
+ // and maxSteps. Its tool endpoints' requests are not cancelled either.
25
+ context.signal = undefined;
21
26
  logger.debug({
22
27
  event: 'debug_agent',
23
28
  agentId,
@@ -26,7 +31,9 @@ async function callAgent(context, { agentId, pageId, messages, conversationId, u
26
31
  const agentContext = {
27
32
  conversationId: conversationId ?? undefined,
28
33
  pageId,
34
+ pathParams: pathParams ?? {},
29
35
  sharedState: sharedState ?? {},
36
+ sharedStateReadOnly: sharedStateReadOnly ?? false,
30
37
  urlQuery: urlQuery ?? {},
31
38
  userId: context.user?.sub ?? context.user?.id ?? null
32
39
  };
@@ -34,6 +41,9 @@ async function callAgent(context, { agentId, pageId, messages, conversationId, u
34
41
  agentId,
35
42
  agentContext,
36
43
  endpointDepth: 0,
44
+ files: collectChatFiles({
45
+ messages
46
+ }),
37
47
  mode: 'chat'
38
48
  });
39
49
  // Call the agent resolver
@@ -0,0 +1,39 @@
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 files the person attached in the conversation the chat request carried: every file part
17
+ // that holds a storage key (AgentChat sets providerMetadata.lowdefy.key on an upload), in message
18
+ // order. A tool endpoint reads them with `_agent: files`. They come from the request, not from a
19
+ // tool call, so the model can only name a file of this conversation. The messages are the
20
+ // client's, not yet validated, so a malformed message or part is passed over here and refused
21
+ // by the agent's message validation.
22
+ function collectChatFiles({ messages }) {
23
+ const files = [];
24
+ for (const message of messages){
25
+ if (!type.isArray(message?.parts)) continue;
26
+ for (const part of message.parts){
27
+ const key = part?.providerMetadata?.lowdefy?.key;
28
+ if (part?.type === 'file' && type.isString(key)) {
29
+ files.push({
30
+ key,
31
+ filename: part.filename ?? null,
32
+ mediaType: part.mediaType
33
+ });
34
+ }
35
+ }
36
+ }
37
+ return files;
38
+ }
39
+ export default collectChatFiles;
@@ -27,14 +27,25 @@ import getConnection from '../connections/getConnection.js';
27
27
  // config, evaluates operators, creates the provider connection, and builds the
28
28
  // resolver context. mode ('chat' | 'generate') selects the resolver's execution
29
29
  // path; endpointDepth threads the endpoint call depth cap through agent tool
30
- // and hook endpoint calls.
31
- async function prepareAgent(context, { agentId, agentContext, endpointDepth = 0, mode = 'chat' }) {
30
+ // and hook endpoint calls; files are the chat's attached files `_agent: files` reads.
31
+ async function prepareAgent(context, { agentId, agentContext, endpointDepth = 0, files, mode = 'chat' }) {
32
32
  const agentConfig = await getAgentConfig(context, {
33
33
  agentId
34
34
  });
35
35
  authorizeAgent(context, {
36
36
  agentConfig
37
37
  });
38
+ // What `_agent` reads in the tool and hook endpoints this agent calls. Built here from the
39
+ // agent being run, its conversation and the files of the chat request, so no tool input can
40
+ // set or change it.
41
+ // sharedState is the chat's shared state the browser sent with the request, the same value
42
+ // the agent's own context reads.
43
+ const agent = {
44
+ id: agentId,
45
+ conversationId: agentContext.conversationId ?? null,
46
+ files,
47
+ sharedState: agentContext.sharedState ?? null
48
+ };
38
49
  // Evaluate operators in agent properties (e.g. _user, _secret, _payload)
39
50
  agentConfig.properties = context.evaluateOperators({
40
51
  input: agentConfig.properties ?? {},
@@ -72,7 +83,11 @@ async function prepareAgent(context, { agentId, agentContext, endpointDepth = 0,
72
83
  const resolverContext = {
73
84
  agentContext,
74
85
  i18n: context.i18n,
86
+ logger: context.logger,
75
87
  mode,
88
+ // Cancels a headless (CallAgent) run when the request that started it closes;
89
+ // undefined for chat runs and background routines (see callAgent).
90
+ signal: context.signal,
76
91
  // The agent stream's error text reaches the end user and AgentChat config, so it takes
77
92
  // the wire policy. Built here because the agent plugins cannot import @lowdefy/api.
78
93
  // The AI SDK types onError's argument as unknown: a tool can reject with null or a
@@ -85,11 +100,15 @@ async function prepareAgent(context, { agentId, agentContext, endpointDepth = 0,
85
100
  state: {},
86
101
  steps: {}
87
102
  }),
88
- callEndpoint: async (endpointId, { payload })=>{
103
+ // outsideCaller marks a tool call, whose input the model built; a hook's
104
+ // payload is built by Lowdefy for the hook endpoint the config names.
105
+ callEndpoint: async (endpointId, { payload, outsideCaller = false })=>{
89
106
  const { error, response, status } = await invokeEndpoint(context, {
107
+ agent,
90
108
  endpointId,
91
109
  payload,
92
- endpointDepth
110
+ endpointDepth,
111
+ outsideCaller
93
112
  });
94
113
  return buildEndpointResult(context, {
95
114
  error,
@@ -0,0 +1,33 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { admin } from 'better-auth/plugins';
16
+ // The admin plugin is registered for two things: it owns the
17
+ // banned/banReason/banExpires fields on the user row, and it owns the endpoints
18
+ // the BanUser, UnbanUser, DeleteUser and RevokeUserSessions steps call. Those
19
+ // calls carry server authority - callPluginEndpoint injects an acting user with
20
+ // role: 'admin', which the vendor's built-in admin role satisfies - and the
21
+ // step floor is what authorizes them, per organization and bounded by the
22
+ // target's membership there.
23
+ //
24
+ // So the vendor's default roles are all this needs. Nothing in Lowdefy writes
25
+ // user.role, so no real browser session holds a role in adminRoles and no
26
+ // browser caller can satisfy any /admin/* check; the whole surface is disabled
27
+ // at the router besides (see ADMIN_PATHS_DISABLED in getBetterAuthConfig).
28
+ // A custom access control would only exist to grant a real user authority the
29
+ // platform has none to grant.
30
+ function buildAdminPlugin() {
31
+ return admin();
32
+ }
33
+ export default buildAdminPlugin;
@@ -0,0 +1,61 @@
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 { captcha } from 'better-auth/plugins';
16
+ import { type } from '@lowdefy/helpers';
17
+ import { ConfigError } from '@lowdefy/errors';
18
+ // The protected set is computed from the enabled login methods - the union
19
+ // of each method's public initiate endpoints, including the message-send
20
+ // endpoints that spend money. This deliberately deviates from BetterAuth's
21
+ // static default (three email paths), which would leave
22
+ // /phone-number/send-otp - the most expensive endpoint and the reason this
23
+ // plugin exists - unprotected. Verify/consume endpoints stay uncovered: they
24
+ // are guarded by their own single-use, attempt-limited codes, and captcha
25
+ // tokens are single-use, so covering them would demand a second token per
26
+ // flow.
27
+ function computeCaptchaEndpoints({ authConfig }) {
28
+ const endpoints = [
29
+ '/sign-up/email',
30
+ '/sign-in/email',
31
+ '/request-password-reset',
32
+ '/send-verification-email'
33
+ ];
34
+ if (authConfig.magicLink?.enabled === true) {
35
+ endpoints.push('/sign-in/magic-link');
36
+ }
37
+ if (authConfig.phoneNumber?.enabled === true) {
38
+ endpoints.push('/phone-number/send-otp', '/sign-in/phone-number', '/phone-number/request-password-reset');
39
+ }
40
+ return endpoints;
41
+ }
42
+ // Maps auth.captcha onto BetterAuth's captcha plugin - a self-contained
43
+ // onRequest middleware that verifies the x-captcha-response header against
44
+ // the provider's siteverify API and fails closed. An explicit
45
+ // auth.captcha.endpoints replaces the computed set entirely.
46
+ function buildCaptchaPlugin({ authConfig }) {
47
+ const captchaConfig = authConfig.captcha;
48
+ if (!type.isString(captchaConfig.secretKey)) {
49
+ throw new ConfigError('Auth "captcha.secretKey" did not resolve to a string. Check the _secret operator reference and that the secret is set.', {
50
+ received: type.typeOf(captchaConfig.secretKey)
51
+ });
52
+ }
53
+ return captcha({
54
+ provider: captchaConfig.provider,
55
+ secretKey: captchaConfig.secretKey,
56
+ endpoints: captchaConfig.endpoints ?? computeCaptchaEndpoints({
57
+ authConfig
58
+ })
59
+ });
60
+ }
61
+ export default buildCaptchaPlugin;