@lowdefy/api 6.1.0 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/dist/context/applySystemTrust.js +45 -0
  2. package/dist/context/createApiContext.js +18 -3
  3. package/dist/context/createAuthorizeOutcome.js +91 -0
  4. package/dist/context/createBoundSystemContext.js +33 -0
  5. package/dist/context/createEvaluateOperators.js +8 -3
  6. package/dist/context/createRequestSignal.js +47 -0
  7. package/dist/context/createSystemContext.js +80 -0
  8. package/dist/context/getCanonicalUrl.js +27 -0
  9. package/dist/context/isSameOriginRequest.js +85 -0
  10. package/dist/context/isWebSocketOriginAllowed.js +63 -0
  11. package/dist/context/normalizeInjectedCaller.js +58 -0
  12. package/dist/context/parseRequestBody.js +32 -0
  13. package/dist/context/readMemberships.js +71 -0
  14. package/dist/context/resolveAuthentication.js +758 -0
  15. package/dist/context/resolveStrategyCaller.js +7 -3
  16. package/dist/csp/addNonceToElements.js +23 -0
  17. package/dist/csp/createContentSecurityPolicy.js +45 -0
  18. package/dist/csp/getWebSocketSources.js +36 -0
  19. package/dist/email/renderAuthEmail.js +99 -0
  20. package/dist/index.js +21 -5
  21. package/dist/response/formatErrorForAgent.js +35 -0
  22. package/dist/response/redactResponse.js +8 -1
  23. package/dist/routes/agent/authorizeAgent.js +17 -5
  24. package/dist/routes/agent/callAgent.js +12 -2
  25. package/dist/routes/agent/collectChatFiles.js +39 -0
  26. package/dist/routes/agent/prepareAgent.js +23 -4
  27. package/dist/routes/auth/buildAdminPlugin.js +33 -0
  28. package/dist/routes/auth/buildCaptchaPlugin.js +61 -0
  29. package/dist/routes/auth/buildMcpTokenPlugin.js +77 -0
  30. package/dist/routes/auth/buildOauthPostLogin.js +73 -0
  31. package/dist/routes/auth/buildPhoneNumberPlugin.js +57 -0
  32. package/dist/routes/auth/buildProviders.js +61 -0
  33. package/dist/routes/auth/createAsMetadataHandler.js +27 -0
  34. package/dist/routes/auth/createAuthLogger.js +31 -0
  35. package/dist/routes/auth/createMcpAccessTokenClaims.js +52 -0
  36. package/dist/routes/auth/createOnAPIError.js +41 -0
  37. package/dist/routes/auth/createSendEmail.js +54 -0
  38. package/dist/routes/auth/ensureMcpTokenIndexes.js +48 -0
  39. package/dist/routes/auth/getAuthEnforcement.js +41 -0
  40. package/dist/routes/auth/getBetterAuth.js +107 -0
  41. package/dist/routes/auth/getBetterAuthConfig.js +767 -0
  42. package/dist/routes/auth/handleAuthRequest.js +43 -0
  43. package/dist/routes/auth/hooks/authHookPoints.js +204 -0
  44. package/dist/routes/auth/hooks/buildEngineHooks.js +68 -0
  45. package/dist/routes/auth/hooks/buildHooks.js +112 -0
  46. package/dist/routes/auth/{callbacks/addUserFieldsToSession.js → hooks/composeAfterSlot.js} +11 -13
  47. package/dist/routes/auth/hooks/composeBeforeSlot.js +41 -0
  48. package/dist/routes/auth/hooks/createHookDispatch.js +59 -0
  49. package/dist/routes/auth/hooks/createUserAfterHook.js +36 -0
  50. package/dist/routes/auth/hooks/createUserBeforeHook.js +50 -0
  51. package/dist/routes/auth/hooks/findHookUser.js +27 -0
  52. package/dist/routes/auth/modelNames.js +30 -0
  53. package/dist/routes/auth/organizations/OrganizationKeyError.js +28 -0
  54. package/dist/routes/auth/organizations/authorizeRole.js +27 -0
  55. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +178 -0
  56. package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +57 -0
  57. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +120 -0
  58. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +403 -0
  59. package/dist/routes/auth/organizations/createAdmissionGateHook.js +50 -0
  60. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +90 -0
  61. package/dist/routes/auth/organizations/createAutoJoinHook.js +68 -0
  62. package/dist/routes/auth/organizations/createEmailSendGate.js +59 -0
  63. package/dist/routes/auth/organizations/createExpiredInvitationGate.js +76 -0
  64. package/dist/routes/auth/organizations/ensureAuthIndexes.js +122 -0
  65. package/dist/routes/auth/organizations/ensureOrganization.js +132 -0
  66. package/dist/routes/auth/organizations/findPendingInvitation.js +43 -0
  67. package/dist/routes/auth/organizations/getHookRequestHeaders.js +24 -0
  68. package/dist/routes/auth/organizations/getOrganizationBinding.js +65 -0
  69. package/dist/routes/auth/organizations/isEmailAdmitted.js +89 -0
  70. package/dist/routes/auth/organizations/organizationAccessControl.js +94 -0
  71. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +62 -0
  72. package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +145 -0
  73. package/dist/routes/auth/requestHooks/buildRequestHooks.js +288 -0
  74. package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +43 -0
  75. package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +59 -0
  76. package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +47 -0
  77. package/dist/routes/auth/requestHooks/redirectToChallenge.js +79 -0
  78. package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +31 -0
  79. package/dist/routes/auth/resolveCookiePrefix.js +30 -0
  80. package/dist/routes/auth/sanitizeSessionResponse.js +27 -0
  81. package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
  82. package/dist/routes/connections/checkUnwalledReach.js +37 -0
  83. package/dist/routes/connections/getConnectionConfig.js +6 -1
  84. package/dist/routes/connections/resolveTenantPreflight.js +226 -0
  85. package/dist/routes/connections/resolveUnwalledReach.js +144 -0
  86. package/dist/routes/endpoints/acceptDetachedEndpoint.js +50 -0
  87. package/dist/routes/endpoints/authorizeApiEndpoint.js +13 -4
  88. package/dist/routes/endpoints/callEndpoint.js +22 -7
  89. package/dist/routes/endpoints/control/controlParallelFor.js +61 -22
  90. package/dist/routes/endpoints/control/controlReject.js +23 -1
  91. package/dist/routes/endpoints/control/controlReturn.js +29 -1
  92. package/dist/routes/endpoints/control/controlThrow.js +3 -2
  93. package/dist/routes/endpoints/control/controlTry.js +10 -1
  94. package/dist/routes/endpoints/control/controlWhile.js +55 -0
  95. package/dist/routes/endpoints/control/handleControl.js +3 -1
  96. package/dist/routes/endpoints/createWebhookAnswer.js +78 -0
  97. package/dist/routes/endpoints/evaluateRoutineOperators.js +2 -1
  98. package/dist/routes/endpoints/forwardScheduledEndpoint.js +3 -2
  99. package/dist/routes/endpoints/getEndpointConfig.js +18 -8
  100. package/dist/routes/endpoints/getSchemaValidator.js +39 -0
  101. package/dist/routes/endpoints/handleAgentCall.js +21 -2
  102. package/dist/routes/endpoints/handleAuthStep.js +214 -0
  103. package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
  104. package/dist/routes/endpoints/handleEndpointCall.js +43 -6
  105. package/dist/routes/endpoints/handleRenderNotification.js +14 -4
  106. package/dist/routes/endpoints/handleRequest.js +12 -1
  107. package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
  108. package/dist/routes/endpoints/handleValidateSchema.js +13 -15
  109. package/dist/routes/endpoints/invokeEndpoint.js +26 -3
  110. package/dist/routes/endpoints/operatorScope.js +2 -1
  111. package/dist/routes/{auth/callbacks/createCallbackPlugins.js → endpoints/parseWebhookBody.js} +10 -6
  112. package/dist/routes/endpoints/resolveCallBinding.js +91 -0
  113. package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
  114. package/dist/routes/endpoints/runDetachedEndpoint.js +63 -18
  115. package/dist/routes/endpoints/runRoutine.js +64 -5
  116. package/dist/routes/endpoints/runScheduledEndpoint.js +18 -11
  117. package/dist/routes/endpoints/runWebhookEndpoint.js +69 -23
  118. package/dist/routes/endpoints/runWebhookVerify.js +129 -0
  119. package/dist/routes/endpoints/scheduleBackground.js +10 -0
  120. package/dist/routes/endpoints/test/runTest.js +31 -9
  121. package/dist/routes/endpoints/validatePayload.js +144 -0
  122. package/dist/routes/log/logClientError.js +7 -4
  123. package/dist/routes/mcp/createMcpServer.js +143 -82
  124. package/dist/routes/mcp/getMcpJwks.js +93 -0
  125. package/dist/routes/mcp/getMcpResourceBinding.js +41 -0
  126. package/dist/routes/mcp/getMcpUri.js +69 -0
  127. package/dist/routes/mcp/oauthResourceLifecycle.js +122 -0
  128. package/dist/routes/mcp/runAfterToolCall.js +50 -0
  129. package/dist/routes/notifications/resolveNotificationLinks.js +39 -11
  130. package/dist/routes/page/dynamic/checkDynamicContent.js +81 -0
  131. package/dist/routes/page/dynamic/checkLiteralContent.js +242 -0
  132. package/dist/routes/page/dynamic/createContentError.js +34 -0
  133. package/dist/routes/page/dynamic/flagIconsOutsidePage.js +39 -0
  134. package/dist/routes/page/dynamic/flagTypesOutsidePage.js +44 -0
  135. package/dist/routes/page/dynamic/getPropertiesSchemaErrors.js +35 -0
  136. package/dist/routes/page/dynamic/loadDynamicArtifacts.js +52 -0
  137. package/dist/routes/page/dynamic/policy/checkAction.js +204 -0
  138. package/dist/routes/page/dynamic/policy/checkEvents.js +163 -0
  139. package/dist/routes/page/dynamic/policy/checkPolicy.js +313 -0
  140. package/dist/routes/page/dynamic/policy/checkValue.js +214 -0
  141. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +117 -0
  142. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +54 -0
  143. package/dist/routes/page/dynamic/policy/findSerializerKeys.js +50 -0
  144. package/dist/routes/page/dynamic/policy/isAllowedUrl.js +53 -0
  145. package/dist/routes/{auth/createAdapter.js → page/dynamic/policy/isUnderState.js} +5 -9
  146. package/dist/routes/page/dynamic/policy/normalizeUrlText.js +25 -0
  147. package/dist/routes/page/dynamic/resolveDynamicContent.js +89 -37
  148. package/dist/routes/page/dynamic/unescapeOperators.js +21 -4
  149. package/dist/routes/page/dynamic/validateFragment.js +17 -58
  150. package/dist/routes/page/getPageConfig.js +76 -6
  151. package/dist/routes/request/authorizeRequest.js +21 -6
  152. package/dist/routes/request/callRequest.js +22 -10
  153. package/dist/routes/request/callRequestResolver.js +49 -6
  154. package/dist/routes/request/checkConnectionRead.js +1 -1
  155. package/dist/routes/request/checkConnectionWrite.js +1 -1
  156. package/dist/routes/request/createWalledResolver.js +75 -0
  157. package/dist/routes/request/getRequestConfig.js +19 -3
  158. package/dist/routes/request/maskCredentialProperties.js +34 -0
  159. package/dist/routes/request/resolveTenancy.js +223 -0
  160. package/dist/routes/request/validateSchemas.js +7 -6
  161. package/dist/routes/{auth/events/createEventPlugins.js → rootConfig/getAppEvents.js} +7 -6
  162. package/dist/routes/rootConfig/getHomeAndMenus.js +23 -16
  163. package/dist/routes/{auth/events/createSessionEvent.js → rootConfig/getPagePaths.js} +16 -18
  164. package/dist/routes/rootConfig/getRootConfig.js +9 -3
  165. package/dist/routes/rootConfig/menus/filterMenuList.js +5 -2
  166. package/dist/routes/websocket/authorizeWebsocket.js +19 -4
  167. package/dist/routes/websocket/createChannelRegistry.js +20 -9
  168. package/dist/routes/websocket/createWebSocketConnection.js +150 -28
  169. package/dist/routes/websocket/getCallerFingerprint.js +31 -0
  170. package/dist/routes/websocket/prepareChannel.js +29 -1
  171. package/dist/routes/websocket/resolveWebsocketCaller.js +40 -0
  172. package/dist/test/testContext.js +13 -10
  173. package/package.json +28 -12
  174. package/dist/context/createAuthorize.js +0 -45
  175. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +0 -30
  176. package/dist/routes/auth/callbacks/createCallbacks.js +0 -46
  177. package/dist/routes/auth/callbacks/createJWTCallback.js +0 -77
  178. package/dist/routes/auth/callbacks/createRedirectCallback.js +0 -41
  179. package/dist/routes/auth/callbacks/createSessionCallback.js +0 -81
  180. package/dist/routes/auth/callbacks/createSignInCallback.js +0 -40
  181. package/dist/routes/auth/callbacks/validateSessionRoles.js +0 -33
  182. package/dist/routes/auth/createLogger.js +0 -35
  183. package/dist/routes/auth/createPrefixedCookies.js +0 -52
  184. package/dist/routes/auth/createProviders.js +0 -25
  185. package/dist/routes/auth/defaultAuthUrl.js +0 -31
  186. package/dist/routes/auth/events/createCreateUserEvent.js +0 -41
  187. package/dist/routes/auth/events/createEvents.js +0 -56
  188. package/dist/routes/auth/events/createLinkAccountEvent.js +0 -43
  189. package/dist/routes/auth/events/createSignInEvent.js +0 -46
  190. package/dist/routes/auth/events/createSignOutEvent.js +0 -43
  191. package/dist/routes/auth/events/createUpdateUserEvent.js +0 -41
  192. package/dist/routes/auth/getAuthConfig.js +0 -90
  193. package/dist/routes/auth/resolveCookies.js +0 -37
  194. package/dist/routes/log/formatValidationError.js +0 -31
  195. /package/dist/{routes/notifications → email}/resolveThemeLogo.js +0 -0
@@ -0,0 +1,77 @@
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 modelNames from './modelNames.js';
16
+ // Member tokens for MCP scripts live in the auth database as their own model,
17
+ // so the adapter reads and writes them like every other auth row and the MCP
18
+ // route's lookup is one more indexed read beside consents, users and members.
19
+ // The plugin declares the schema only - no endpoints: tokens are created and
20
+ // revoked by the auth steps, never over BetterAuth's HTTP surface. The token
21
+ // itself is never stored, only its SHA-256 (hash) and its first characters
22
+ // (start) so people can tell tokens apart.
23
+ function buildMcpTokenPlugin() {
24
+ return {
25
+ id: 'lowdefy-mcp-token',
26
+ schema: {
27
+ mcpToken: {
28
+ modelName: modelNames.mcpToken,
29
+ fields: {
30
+ organizationId: {
31
+ type: 'string',
32
+ required: true,
33
+ index: true
34
+ },
35
+ userId: {
36
+ type: 'string',
37
+ required: true,
38
+ index: true
39
+ },
40
+ // The member row the token was made for. The route accepts the token
41
+ // only while that row stands, so leaving, removal or deletion ends
42
+ // it by any path, and a rejoined member's new row holds no old tokens.
43
+ memberId: {
44
+ type: 'string',
45
+ required: true
46
+ },
47
+ name: {
48
+ type: 'string',
49
+ required: true
50
+ },
51
+ hash: {
52
+ type: 'string',
53
+ required: true,
54
+ unique: true
55
+ },
56
+ start: {
57
+ type: 'string',
58
+ required: true
59
+ },
60
+ createdAt: {
61
+ type: 'date',
62
+ required: true
63
+ },
64
+ expiresAt: {
65
+ type: 'date',
66
+ required: false
67
+ },
68
+ lastUsedAt: {
69
+ type: 'date',
70
+ required: false
71
+ }
72
+ }
73
+ }
74
+ }
75
+ };
76
+ }
77
+ export default buildMcpTokenPlugin;
@@ -0,0 +1,73 @@
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 { APIError } from 'better-auth/api';
16
+ import { type } from '@lowdefy/helpers';
17
+ // The oauth-provider's post-login seat: after login and before consent, the
18
+ // authorization server asks which organization the grant acts in. The answer
19
+ // is the consent referenceId - it keys consent per (client, user,
20
+ // organization), rides the authorization code and the refresh-token row, and
21
+ // is what customAccessTokenClaims stamps onto every access token as
22
+ // organization_id. So the organization an MCP token acts in is never a URL
23
+ // segment or a client-supplied parameter: it is the member's own choice,
24
+ // signed into the code by the AS and re-verified against the live member row
25
+ // on every request.
26
+ //
27
+ // Under the tenant policy the member chooses on the configured page (the page
28
+ // runs SetActiveOrganization for the chosen organization, then OAuthContinue),
29
+ // and the choice is made on every authorization - a one-organization member
30
+ // sees a single preselected row. The plugin asks shouldRedirect on every
31
+ // authorize call, including the one /oauth2/continue re-enters with after the
32
+ // choice, and only its CONSENT redirect carries the "post-login done" marker
33
+ // (ba_pl) - so an unconditional true would loop back to the picker forever.
34
+ // The request hook on /oauth2/continue (createOauthPostLoginHook) stamps the
35
+ // session object cached on that request instead, and shouldRedirect reads the
36
+ // stamp: true until the choice has been posted, false on the authorize call
37
+ // that carries it. Under the pinned policy there is one organization and
38
+ // nothing to choose: the redirect is skipped and the reference is the pinned
39
+ // organization, whose id is its slug. The page is still required by the
40
+ // plugin option shape, so the consent page stands in - it is never redirected
41
+ // to.
42
+ //
43
+ // The marker lives on the in-request session object only - never persisted -
44
+ // so it cannot outlive the request that made the choice.
45
+ const OAUTH_POST_LOGIN_CONFIRMED = 'oauthPostLoginConfirmed';
46
+ function buildOauthPostLogin({ authConfig, baseUrlOrigin, basePath }) {
47
+ if (authConfig.organizations?.policy === 'pinned') {
48
+ return {
49
+ page: `${baseUrlOrigin}${basePath}${authConfig.oauthProvider.consentPage}`,
50
+ shouldRedirect: ()=>false,
51
+ consentReferenceId: ()=>authConfig.organizations.org
52
+ };
53
+ }
54
+ return {
55
+ page: `${baseUrlOrigin}${basePath}${authConfig.oauthProvider.postLoginPage}`,
56
+ shouldRedirect: ({ session })=>session?.[OAUTH_POST_LOGIN_CONFIRMED] !== true,
57
+ consentReferenceId: ({ session })=>{
58
+ const organizationId = session?.activeOrganizationId;
59
+ // The plugin's contract: fail here when the reference is missing rather
60
+ // than let a consent be recorded without one - a token minted without
61
+ // organization_id would be refused by the MCP route on every call.
62
+ if (!type.isString(organizationId) || organizationId.length === 0) {
63
+ throw new APIError('BAD_REQUEST', {
64
+ error: 'invalid_request',
65
+ error_description: 'No organization was selected for this authorization. Choose an organization and try again.'
66
+ });
67
+ }
68
+ return organizationId;
69
+ }
70
+ };
71
+ }
72
+ export { OAUTH_POST_LOGIN_CONFIRMED };
73
+ export default buildOauthPostLogin;
@@ -0,0 +1,57 @@
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 { phoneNumber } from 'better-auth/plugins';
16
+ import { type } from '@lowdefy/helpers';
17
+ import { ConfigError } from '@lowdefy/errors';
18
+ // The wire format is pinned to E.164. BetterAuth's default validator accepts
19
+ // any string, which mints several identities for one phone ("+27 83 123 4567",
20
+ // "0831234567" and "+27831234567") and spends real money on malformed sends.
21
+ // Normalization belongs in the UI's locale-aware input widgets.
22
+ const E164_REGEX = /^\+[1-9]\d{1,14}$/;
23
+ // Maps auth.phoneNumber onto BetterAuth's phoneNumber plugin. The SMS send
24
+ // callbacks are the composed "phone.otp.send" / "phone.passwordReset.send"
25
+ // hook slots - build validation guarantees the OTP send binding exists when
26
+ // the plugin is enabled, so sendPhoneOtp is always a function here.
27
+ function buildPhoneNumberPlugin({ authConfig, phoneVerified, sendPhoneOtp, sendPhonePasswordResetOtp }) {
28
+ const phoneNumberConfig = authConfig.phoneNumber;
29
+ const options = {
30
+ otpLength: phoneNumberConfig.otpLength,
31
+ expiresIn: phoneNumberConfig.expiresIn,
32
+ allowedAttempts: phoneNumberConfig.allowedAttempts,
33
+ requireVerification: phoneNumberConfig.requireVerification,
34
+ phoneNumberValidator: (value)=>E164_REGEX.test(value),
35
+ sendOTP: sendPhoneOtp,
36
+ // BetterAuth's /phone-number/request-password-reset returns
37
+ // { status: true } without sending anything when sendPasswordResetOTP is
38
+ // not configured - a user asking for a reset would get silence and a 200
39
+ // in the logs. Fail loudly naming the fix instead.
40
+ sendPasswordResetOTP: sendPhonePasswordResetOtp ?? (()=>{
41
+ throw new ConfigError('Password reset over phone is not configured. Bind an InternalApi endpoint to the "phone.passwordReset.send" auth hook point to send reset codes.');
42
+ })
43
+ };
44
+ if (!type.isNone(phoneVerified)) {
45
+ options.callbackOnVerification = phoneVerified;
46
+ }
47
+ if (!type.isNone(phoneNumberConfig.signUpOnVerification)) {
48
+ const { tempEmailDomain } = phoneNumberConfig.signUpOnVerification;
49
+ options.signUpOnVerification = {
50
+ // The E.164 digits with the "+" stripped keep the derived address
51
+ // unique per phone; uniqueness is inherited from the phone number's.
52
+ getTempEmail: (value)=>`${value.replace(/\D/g, '')}@${tempEmailDomain}`
53
+ };
54
+ }
55
+ return phoneNumber(options);
56
+ }
57
+ export default buildPhoneNumberPlugin;
@@ -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 { type } from '@lowdefy/helpers';
16
+ import { ConfigError } from '@lowdefy/errors';
17
+ // Splits the unified auth.providers array into BetterAuth's two shapes:
18
+ // built-in providers become socialProviders entries keyed by the BetterAuth
19
+ // provider key; GenericOAuth entries become genericOAuth plugin configs
20
+ // keyed by the Lowdefy provider id.
21
+ function buildProviders({ authConfig, plugins }) {
22
+ const socialProviders = {};
23
+ const genericOAuthConfigs = [];
24
+ (authConfig.providers ?? []).forEach((provider)=>{
25
+ const providerPlugin = plugins.providers[provider.type];
26
+ if (type.isNone(providerPlugin)) {
27
+ throw new ConfigError(`Auth provider type "${provider.type}" not found at provider "${provider.id}".`, {
28
+ configKey: provider['~k']
29
+ });
30
+ }
31
+ let definition;
32
+ try {
33
+ definition = providerPlugin({
34
+ id: provider.id,
35
+ properties: provider.properties ?? {}
36
+ });
37
+ } catch (error) {
38
+ // Provider plugins throw plain errors (an invalid property) - attach the
39
+ // provider's id and config location.
40
+ throw new ConfigError(`Auth provider "${provider.id}" is invalid: ${error.message}`, {
41
+ cause: error,
42
+ configKey: provider['~k']
43
+ });
44
+ }
45
+ if (definition.kind === 'generic') {
46
+ genericOAuthConfigs.push(definition.config);
47
+ return;
48
+ }
49
+ if (!type.isNone(socialProviders[definition.provider])) {
50
+ throw new ConfigError(`Auth provider "${definition.provider}" is configured more than once. BetterAuth supports one configuration per built-in provider.`, {
51
+ configKey: provider['~k']
52
+ });
53
+ }
54
+ socialProviders[definition.provider] = definition.options;
55
+ });
56
+ return {
57
+ socialProviders,
58
+ genericOAuthConfigs
59
+ };
60
+ }
61
+ export default buildProviders;
@@ -0,0 +1,27 @@
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 { oauthProviderAuthServerMetadata } from '@better-auth/oauth-provider';
16
+ // The oauth-provider plugin serves its AS metadata relative to the auth
17
+ // mount, so the RFC 8414 path-inserted location a client derives from the
18
+ // issuer (/.well-known/oauth-authorization-server/api/auth) must be mounted
19
+ // by the servers themselves. This wraps the vendor handler around the live
20
+ // auth instance - the served document, issuer included, then cannot drift
21
+ // from the plugin's own metadata - and keeps the @better-auth/oauth-provider
22
+ // import beside the plugin registration instead of in each server. Returns
23
+ // (request: Request) => Promise<Response>.
24
+ function createAsMetadataHandler({ auth }) {
25
+ return oauthProviderAuthServerMetadata(auth);
26
+ }
27
+ export default createAsMetadataHandler;
@@ -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
+ */ // Adapts the Lowdefy logger to BetterAuth's logger contract:
16
+ // { disabled, level, log(level, message, ...args) }.
17
+ function createAuthLogger({ logger }) {
18
+ return {
19
+ disabled: false,
20
+ level: logger?.isLevelEnabled?.('debug') === true ? 'debug' : 'warn',
21
+ log: (level, message, ...args)=>{
22
+ const log = logger?.[level] ?? logger?.info;
23
+ if (!log) return;
24
+ log.call(logger, {
25
+ event: 'auth_engine',
26
+ args
27
+ }, message);
28
+ }
29
+ };
30
+ }
31
+ export default createAuthLogger;
@@ -0,0 +1,52 @@
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 { APIError } from 'better-auth/api';
16
+ import { type } from '@lowdefy/helpers';
17
+ // Every MCP access token carries the organization its grant acts in as the
18
+ // organization_id claim - the consent referenceId (buildOauthPostLogin). The
19
+ // refresh grant re-stamps that reference without asking whether the user still
20
+ // belongs to the organization, so a member who left or was removed would keep
21
+ // refreshing into tokens the MCP route refuses: the client refreshes, retries,
22
+ // gets the same 401 and gives up, and never re-runs sign-in and the
23
+ // organization choice. Refusing the mint with invalid_grant is what sends an
24
+ // OAuth client back through authorization.
25
+ function createMcpAccessTokenClaims({ getAuth }) {
26
+ return async function mcpAccessTokenClaims({ user, referenceId }) {
27
+ const { adapter } = await getAuth().$context;
28
+ const member = await adapter.findOne({
29
+ model: 'member',
30
+ where: [
31
+ {
32
+ field: 'userId',
33
+ value: user.id
34
+ },
35
+ {
36
+ field: 'organizationId',
37
+ value: referenceId
38
+ }
39
+ ]
40
+ });
41
+ if (type.isNone(member)) {
42
+ throw new APIError('BAD_REQUEST', {
43
+ error: 'invalid_grant',
44
+ error_description: 'The user is no longer a member of the organization this grant acts in. Authorize again to choose an organization.'
45
+ });
46
+ }
47
+ return {
48
+ organization_id: referenceId
49
+ };
50
+ };
51
+ }
52
+ export default createMcpAccessTokenClaims;
@@ -0,0 +1,41 @@
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
+ // BetterAuth's router logs every APIError at error level when the logger level
17
+ // is warn or debug, so a wrong password, an expired link or a stale OAuth
18
+ // authorization query produced an ERROR line in the server log on every
19
+ // attempt. Supplying onAPIError.onError replaces that logging - the router
20
+ // returns right after calling it and the HTTP response is unaffected.
21
+ //
22
+ // A 4xx is the auth server rejecting the caller's attempt: expected traffic,
23
+ // one warn line, the same treatment the server error handler gives an
24
+ // AuthenticationError. Anything else is a fault in the auth engine or its
25
+ // adapter and stays at error level with the error object, so the cause chain
26
+ // and stack are logged.
27
+ function createOnAPIError({ logger }) {
28
+ return function onAPIError(error) {
29
+ const statusCode = error?.statusCode;
30
+ if (type.isInt(statusCode) && statusCode >= 400 && statusCode < 500) {
31
+ logger.warn({
32
+ event: 'auth_engine',
33
+ code: error.body?.code,
34
+ status: statusCode
35
+ }, `Auth request rejected (${statusCode}): ${error.message}`);
36
+ return;
37
+ }
38
+ logger.error(error);
39
+ };
40
+ }
41
+ export default createOnAPIError;
@@ -0,0 +1,54 @@
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 send from '@lowdefy/connection-smtp/send';
16
+ import { ServiceError } from '@lowdefy/errors';
17
+ import getConnectionConfig from '../connections/getConnectionConfig.js';
18
+ // auth.email sends every auth email (verification, password reset, magic link)
19
+ // through an SMTP connection. Resolving the connection per fire lets operators
20
+ // and the connection's delivery filter apply, so failures - and filtering -
21
+ // surface here at send time rather than at construction.
22
+ function createSendEmail({ connectionId }) {
23
+ return async function sendEmail({ to, subject, html, text, context }) {
24
+ const connectionConfig = await getConnectionConfig(context, {
25
+ connectionId
26
+ });
27
+ const connection = context.evaluateOperators({
28
+ input: connectionConfig.properties ?? {},
29
+ location: connectionId
30
+ });
31
+ try {
32
+ return await send({
33
+ connection,
34
+ mail: {
35
+ to,
36
+ subject,
37
+ html,
38
+ text
39
+ }
40
+ });
41
+ } catch (error) {
42
+ // Only an unreachable or faulty SMTP host is a service outage - a rejected
43
+ // login or a refused recipient is the deployment's own configuration.
44
+ if (ServiceError.isServiceError(error)) {
45
+ throw new ServiceError(undefined, {
46
+ cause: error,
47
+ service: 'SMTP'
48
+ });
49
+ }
50
+ throw error;
51
+ }
52
+ };
53
+ }
54
+ export default createSendEmail;
@@ -0,0 +1,48 @@
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 unique index on the member token hash, created at server start. It is
17
+ // kept out of ensureAuthIndexes on purpose: that list guards the organization
18
+ // mint, which refuses to run while it fails, and a token index problem must
19
+ // never block sign-ups. The MCP route's lookup by hash is correct without the
20
+ // index, only slower, so a failure is logged and nothing waits on it.
21
+ //
22
+ // The caller fires this without awaiting it, so everything that can reject -
23
+ // the auth context included - sits inside the try.
24
+ async function ensureMcpTokenIndexes({ auth, logger }) {
25
+ try {
26
+ const { adapter } = await auth.$context;
27
+ const ensureUniqueIndexes = adapter.options?.ensureUniqueIndexes;
28
+ if (!type.isFunction(ensureUniqueIndexes)) {
29
+ logger.warn(`Auth database adapter "${adapter.id}" can not create indexes. Create a unique index on the member token hash, or each MCP call with a member token scans the token collection.`);
30
+ return;
31
+ }
32
+ await ensureUniqueIndexes({
33
+ indexes: [
34
+ {
35
+ model: 'mcpToken',
36
+ fields: [
37
+ 'hash'
38
+ ]
39
+ }
40
+ ]
41
+ });
42
+ } catch (error) {
43
+ logger.error({
44
+ err: error
45
+ }, `Could not create the unique index on the member token hash: ${error.message} Member tokens still work, but each MCP call with one scans the token collection.`);
46
+ }
47
+ }
48
+ export default ensureMcpTokenIndexes;
@@ -0,0 +1,41 @@
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 build-time auth facts the request-time authorization layers read. The gate
17
+ // is built synchronously (createApiContext, applySystemTrust), so it cannot read
18
+ // a build artifact - the servers hand auth.json to getBetterAuth, which retains
19
+ // the three values it needs here, keyed on the auth instance exactly as the
20
+ // organizations binding is.
21
+ const enforcementByAuth = new WeakMap();
22
+ // authPages values are page paths ("/two-factor-enrol"); the gate compares
23
+ // against a page id ("two-factor-enrol", "account/two-factor-enrol"), so strip
24
+ // the leading slash once, here, rather than at every read.
25
+ function toPageId(pagePath) {
26
+ if (!type.isString(pagePath)) return null;
27
+ return pagePath.startsWith('/') ? pagePath.slice(1) : pagePath;
28
+ }
29
+ function registerAuthEnforcement({ auth, authJson }) {
30
+ enforcementByAuth.set(auth, {
31
+ pagesProtectedByDefault: authJson.pagesProtectedByDefault === true,
32
+ twoFactorEnrolPageId: toPageId(authJson.authPages?.twoFactorEnrol),
33
+ twoFactorRequired: authJson.twoFactor?.required === true
34
+ });
35
+ }
36
+ function getAuthEnforcement({ auth }) {
37
+ if (type.isNone(auth)) return null;
38
+ return enforcementByAuth.get(auth) ?? null;
39
+ }
40
+ export { registerAuthEnforcement };
41
+ export default getAuthEnforcement;