@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,30 @@
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
+ */ // Fixed mapping from BetterAuth models to physical collection names - the
16
+ // user-* convention. Not configurable: modules that read auth collections
17
+ // natively are portable across apps only if these names are stable.
18
+ const modelNames = {
19
+ user: 'users',
20
+ session: 'user-sessions',
21
+ account: 'user-accounts',
22
+ verification: 'user-verifications',
23
+ organization: 'user-organizations',
24
+ member: 'user-members',
25
+ invitation: 'user-invitations',
26
+ twoFactor: 'user-two-factors',
27
+ passkey: 'user-passkeys',
28
+ mcpToken: 'user-mcp-tokens'
29
+ };
30
+ export default modelNames;
@@ -0,0 +1,28 @@
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
+ // The pinned organization row is keyed by an id that is not its slug. A
17
+ // configuration fault of that database, not a transient one: it will never fix
18
+ // itself, and only an operator re-keying the rows can clear it. It needs a
19
+ // class of its own because resolvePinnedOrganization swallows ensure failures
20
+ // to keep a briefly unreachable database from logging the whole deployment out
21
+ // - it can only rethrow this one if it can tell it apart.
22
+ let OrganizationKeyError = class OrganizationKeyError extends ConfigError {
23
+ constructor(message, options){
24
+ super(message, options);
25
+ this.name = 'OrganizationKeyError';
26
+ }
27
+ };
28
+ export default OrganizationKeyError;
@@ -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 { roles } from './organizationAccessControl.js';
16
+ // Asks the organization plugin's own access control whether a stored member.role
17
+ // satisfies a permission set. hasPermission is not exported by better-auth, so
18
+ // this mirrors hasPermissionFn (dist/plugins/organization/permission.mjs)
19
+ // exactly: split the CSV, pass if ANY role authorizes. The creator
20
+ // short-circuit is deliberately not mirrored - hasPermissionFn only takes it
21
+ // when allowCreatorAllPermissions is passed, which happens at exactly one
22
+ // endpoint, and this is not that endpoint.
23
+ function authorizeRole({ permissions, role }) {
24
+ const names = String(role ?? '').split(',').map((name)=>name.trim()).filter(Boolean);
25
+ return names.some((name)=>roles[name]?.authorize(permissions)?.success === true);
26
+ }
27
+ export default authorizeRole;
@@ -0,0 +1,178 @@
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 { organization } from 'better-auth/plugins';
16
+ import createAfterAcceptInvitationHook from './createAfterAcceptInvitationHook.js';
17
+ import modelNames from '../modelNames.js';
18
+ import { ac, roles } from './organizationAccessControl.js';
19
+ const DEFAULT_MEMBERSHIP_LIMIT = 1000000;
20
+ // Organizations are always on - the membership and boundary mechanism for every
21
+ // app. member.role carries BetterAuth's org-authority tier and nothing else, so
22
+ // the same three built-in roles - owner, admin, member - are registered under
23
+ // both policies. The statement set they are rebuilt against is extended with the
24
+ // actions the step floor's permission map asks for; see
25
+ // organizationAccessControl.js.
26
+ //
27
+ // The app's authored role catalog (auth.roles) is NOT registered here. App roles
28
+ // live on member.appRoles, a separate field, so they never need to resolve as
29
+ // plugin roles. Registering only the three built-in names is what makes the
30
+ // separation enforced rather than merely observed: validStaticRoles in
31
+ // crud-members.mjs is built from Object.keys(roles), so update-member-role and
32
+ // invite-member refuse any other value for member.role even from a hand-crafted
33
+ // request body.
34
+ //
35
+ // The only policy difference left is who may call the endpoints, and that lives
36
+ // in getBetterAuthConfig as disabledPaths - the client-facing org routes are
37
+ // disabled under pinned and enabled under tenant.
38
+ //
39
+ // creatorRole is left at its "owner" default under both policies. The plugin's
40
+ // creator short-circuit is gated on allowCreatorsAllPermissions, so it was never
41
+ // the reason to override it; what an override defended were the
42
+ // creator-protection guards, which key on the member's role string. With app
43
+ // roles out of that field and the fabricated acting member claiming "owner"
44
+ // itself, there is nothing left to defend against.
45
+ function buildOrganizationPlugin({ authConfig = {}, getAuth, sendInvitationEmail }) {
46
+ const options = {
47
+ ac,
48
+ roles,
49
+ // Organization creation is engine-only: the pinned org is seeded by
50
+ // ensure-by-slug and tenant orgs are minted lazily at session.create -
51
+ // both system actions that bypass this client-facing switch.
52
+ allowUserToCreateOrganization: false,
53
+ // Re-invite replaces: inviting an email with a pending invitation cancels
54
+ // it and creates a fresh one with the new role, attributes, and profile
55
+ // (old accept links die with the canceled row). resend: true instead
56
+ // re-sends the existing invitation unchanged with a refreshed expiry.
57
+ cancelPendingInvitationsOnReInvite: true,
58
+ // How long an invitation stays acceptable. Left to BetterAuth's 48h
59
+ // default unless auth.organizations.invitationExpiresIn (seconds, build-
60
+ // validated) says otherwise - real invitees often need longer than two days.
61
+ ...Number.isFinite(authConfig.organizations?.invitationExpiresIn) ? {
62
+ invitationExpiresIn: authConfig.organizations.invitationExpiresIn
63
+ } : {},
64
+ // The most members an organization may have. BetterAuth's default of 100
65
+ // is replaced with a cap high enough to be effectively open unless
66
+ // auth.organizations.membershipLimit (build-validated) says otherwise - a
67
+ // pinned deployment keeps every user in one organization, so past 100
68
+ // accept-invitation and addMember refuse with a 403. It stays finite
69
+ // because the plugin also passes it to the adapter as a query limit: the
70
+ // default page size of list-members and the user lookup behind
71
+ // getFullOrganization.
72
+ membershipLimit: Number.isFinite(authConfig.organizations?.membershipLimit) ? authConfig.organizations.membershipLimit : DEFAULT_MEMBERSHIP_LIMIT,
73
+ schema: {
74
+ organization: {
75
+ modelName: modelNames.organization,
76
+ additionalFields: {
77
+ // Set while a tenant signup mint has written the organization but
78
+ // not yet its owner's member row (createActiveOrgPolicyHook). Only a
79
+ // marked organization is ever joined as owner by the mint, so one
80
+ // that everyone has left is never handed back. Server-only: never
81
+ // accepted from a request body, never returned by an endpoint.
82
+ mintPending: {
83
+ type: 'boolean',
84
+ required: false,
85
+ input: false,
86
+ returned: false
87
+ }
88
+ }
89
+ },
90
+ member: {
91
+ modelName: modelNames.member,
92
+ // Per-(user, org) admin-set authorization inputs - internal, not an
93
+ // app-facing additionalFields surface. appRoles carries the app's own
94
+ // role strings; member.role is left to BetterAuth's owner/admin/member
95
+ // org-authority tier, so the two authorities never share a field.
96
+ // input: false says these are never accepted from a request body.
97
+ additionalFields: {
98
+ appRoles: {
99
+ type: 'string[]',
100
+ required: false,
101
+ input: false
102
+ },
103
+ attributes: {
104
+ type: 'json',
105
+ required: false,
106
+ input: false
107
+ },
108
+ // Per-organization display copies, denormalized by UpdateUserProfile
109
+ // when a profile is saved with that organization resolved. The user
110
+ // row's name/image are deployment-global and last-edit-wins across
111
+ // workspaces; these carry the identity as saved in THIS organization
112
+ // and resolveMemberCaller prefers them, so change stamps and the
113
+ // header identity name the workspace's identity (T18). Absent on a
114
+ // member who has never saved a profile in the organization - the
115
+ // caller then falls back to the global copies.
116
+ name: {
117
+ type: 'string',
118
+ required: false,
119
+ input: false
120
+ },
121
+ image: {
122
+ type: 'string',
123
+ required: false,
124
+ input: false
125
+ }
126
+ }
127
+ },
128
+ invitation: {
129
+ modelName: modelNames.invitation,
130
+ // An invitation may carry an opaque profile bag; accepting
131
+ // shallow-merges it onto the accepting user's user.profile,
132
+ // invitation winning per key. Invite-time member attributes ride the
133
+ // invitation the same way - accepting copies them onto the minted
134
+ // member row, so an invited user's authorization parameters hold
135
+ // from their first session. contactId rides it as a third opaque
136
+ // copy, so an invitation can name the app record the invitee's login
137
+ // will point at before that person has ever signed in.
138
+ //
139
+ // appRoles is declared without the input: false its member counterpart
140
+ // carries. toZodSchema drops input: false fields when isClientSide is
141
+ // set, and the plugin builds the /organization/invite-member body with
142
+ // isClientSide: true - an input: false appRoles would be stripped from
143
+ // that body, and no invitation could ever carry app roles. Under tenant
144
+ // that endpoint is enabled, so an org admin or owner can invite an
145
+ // address with arbitrary, unvalidated app roles. That is intended:
146
+ // inviting members with app roles is what administering your own
147
+ // organization means, and it stays inside the organization the caller
148
+ // already administers.
149
+ additionalFields: {
150
+ appRoles: {
151
+ type: 'string[]',
152
+ required: false
153
+ },
154
+ attributes: {
155
+ type: 'json',
156
+ required: false
157
+ },
158
+ contactId: {
159
+ type: 'string',
160
+ required: false
161
+ },
162
+ profile: {
163
+ type: 'json',
164
+ required: false
165
+ }
166
+ }
167
+ }
168
+ },
169
+ organizationHooks: {
170
+ afterAcceptInvitation: createAfterAcceptInvitationHook({
171
+ getAuth
172
+ })
173
+ },
174
+ sendInvitationEmail
175
+ };
176
+ return organization(options);
177
+ }
178
+ export default buildOrganizationPlugin;
@@ -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 { type } from '@lowdefy/helpers';
16
+ // The engine-tier session.update.before hook that makes the accept-invitation
17
+ // route's active-organization set conditional. BetterAuth's accept route sets
18
+ // the accepting session's active organization unconditionally after minting
19
+ // the member row (crud-invites.mjs), which silently relocates a caller who was
20
+ // working in another organization - everything they create next lands in the
21
+ // inviter's workspace. The same set is also the only repair for an org-less
22
+ // session (the invited user who signed up directly holds a session with no
23
+ // active organization until they accept), so the set cannot simply be removed:
24
+ //
25
+ // - session had no active organization -> let the set through (the rescue);
26
+ // - session already active in an organization -> veto the write, so the
27
+ // caller stays where they were. The member row is already minted by then,
28
+ // so the new organization is joined either way - it just does not steal
29
+ // focus. Switching is the caller's own, explicit act via
30
+ // SetActiveOrganization.
31
+ //
32
+ // Scoped by endpoint path so the set-active-organization route - the explicit
33
+ // switch - is never touched, and keyed on activeOrganizationId so the team
34
+ // branch's activeTeamId session write passes through untouched. The current
35
+ // active organization is read from the endpoint's own resolved session
36
+ // (orgSessionMiddleware ran before the route body), not re-read from the
37
+ // database - it is the same session row the update targets.
38
+ function createAcceptActiveOrgGuardHook({ logger }) {
39
+ return async function acceptActiveOrgGuardHook(data, ctx) {
40
+ if (ctx?.path !== '/organization/accept-invitation') {
41
+ return;
42
+ }
43
+ if (type.isNone(data?.activeOrganizationId)) {
44
+ return;
45
+ }
46
+ const currentActiveOrganizationId = ctx?.context?.session?.session?.activeOrganizationId;
47
+ if (type.isNone(currentActiveOrganizationId)) {
48
+ return;
49
+ }
50
+ if (currentActiveOrganizationId === data.activeOrganizationId) {
51
+ return;
52
+ }
53
+ logger.debug(`Invitation accept for organization "${data.activeOrganizationId}" left the session active in "${currentActiveOrganizationId}" - membership created, active organization unchanged.`);
54
+ return false;
55
+ };
56
+ }
57
+ export default createAcceptActiveOrgGuardHook;
@@ -0,0 +1,120 @@
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 { getSessionFromCtx } from 'better-auth/api';
16
+ import { setSessionCookie } from 'better-auth/cookies';
17
+ import { type } from '@lowdefy/helpers';
18
+ // The engine-tier request hooks.before on /organization/accept-invitation for a
19
+ // caller who is already a member of the invitation's organization - someone
20
+ // invited before they joined another way (the open-signup auto-join, an
21
+ // operator's AddMember). BetterAuth's accept route writes a second member row
22
+ // for them, which the unique (user, organization) index refuses, and the route
23
+ // then reverts the invitation and fails. Accepting is answered here instead:
24
+ // the invitation is marked accepted and the membership is left exactly as it
25
+ // is - no second row, and nothing from the invitation (role, app roles,
26
+ // attributes, profile) is applied. BetterAuth treats an invitation as the way
27
+ // to join, never as a role change: it refuses to invite an existing member,
28
+ // and role changes go through update-member-role, which checks the caller's
29
+ // authority at the time of the change. An invitation written before the
30
+ // membership existed must not override what an administrator set since.
31
+ //
32
+ // Only the case the route can not serve is answered. Anything the route would
33
+ // refuse first - a missing session, an unknown, expired, used or someone
34
+ // else's invitation, an unverified email - falls through so the route gives
35
+ // its own error. The email check mirrors the route's: Lowdefy sets a
36
+ // function-form generateId, which makes the organization plugin require a
37
+ // verified email to accept by invitation id.
38
+ //
39
+ // Like the route, the session gets the organization as its active one only
40
+ // when it has none (createAcceptActiveOrgGuardHook vetoes the route's switch
41
+ // away from an existing active organization).
42
+ function createAcceptExistingMemberHook() {
43
+ return async function acceptExistingMemberHook(ctx) {
44
+ const invitationId = ctx.body?.invitationId;
45
+ if (!type.isString(invitationId)) {
46
+ return undefined;
47
+ }
48
+ const session = await getSessionFromCtx(ctx);
49
+ if (type.isNone(session?.user) || session.user.emailVerified !== true) {
50
+ return undefined;
51
+ }
52
+ const { adapter, internalAdapter } = ctx.context;
53
+ const invitation = await adapter.findOne({
54
+ model: 'invitation',
55
+ where: [
56
+ {
57
+ field: 'id',
58
+ value: invitationId
59
+ }
60
+ ]
61
+ });
62
+ if (type.isNone(invitation) || invitation.status !== 'pending' || invitation.expiresAt < new Date() || invitation.email.toLowerCase() !== session.user.email.toLowerCase()) {
63
+ return undefined;
64
+ }
65
+ const member = await adapter.findOne({
66
+ model: 'member',
67
+ where: [
68
+ {
69
+ field: 'userId',
70
+ value: session.user.id
71
+ },
72
+ {
73
+ field: 'organizationId',
74
+ value: invitation.organizationId
75
+ }
76
+ ]
77
+ });
78
+ if (type.isNone(member)) {
79
+ return undefined;
80
+ }
81
+ // The route's own compare-and-set: of two concurrent accepts only one
82
+ // moves the invitation off pending, and the other falls through to the
83
+ // route, which answers it as the used invitation it now is.
84
+ const accepted = await adapter.incrementOne({
85
+ model: 'invitation',
86
+ where: [
87
+ {
88
+ field: 'id',
89
+ value: invitationId
90
+ },
91
+ {
92
+ field: 'status',
93
+ value: 'pending'
94
+ }
95
+ ],
96
+ increment: {},
97
+ set: {
98
+ status: 'accepted'
99
+ }
100
+ });
101
+ if (type.isNone(accepted)) {
102
+ return undefined;
103
+ }
104
+ if (type.isNone(session.session.activeOrganizationId)) {
105
+ // Re-issued like the set-active-organization route does, so a session
106
+ // cookie cache does not keep serving the org-less session.
107
+ await setSessionCookie(ctx, {
108
+ session: await internalAdapter.updateSession(session.session.token, {
109
+ activeOrganizationId: invitation.organizationId
110
+ }),
111
+ user: session.user
112
+ });
113
+ }
114
+ return {
115
+ invitation: accepted,
116
+ member
117
+ };
118
+ };
119
+ }
120
+ export default createAcceptExistingMemberHook;