@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,403 @@
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
+ import ensureAuthIndexes from './ensureAuthIndexes.js';
18
+ import ensureOrganization from './ensureOrganization.js';
19
+ import findPendingInvitation from './findPendingInvitation.js';
20
+ import getHookRequestHeaders from './getHookRequestHeaders.js';
21
+ import isEmailAdmitted from './isEmailAdmitted.js';
22
+ // How long a minted organization's owner row may take to follow it. A mint
23
+ // writes both rows within one request, so a marker older than this is left
24
+ // over from a mint that failed between its writes.
25
+ const mintPendingMs = 10 * 60 * 1000;
26
+ // The engine-tier session.create hook that applies the active-org policy.
27
+ // session.create is the one provider-agnostic choke point - it fires for
28
+ // email/password, magic link and OAuth alike.
29
+ //
30
+ // pinned: a member of the pinned org gets it as the active organization; a
31
+ // non-member with a pending, unexpired invitation is admitted far enough to
32
+ // accept (the membership wall in resolveAuthentication still gates every
33
+ // protected page until then); anyone else is rejected before a session is
34
+ // minted, with a distinct error code the client surfaces inline.
35
+ //
36
+ // tenant: the active org is the user's business - the oldest membership when
37
+ // they hold several; a user with a pending invitation gets a session but no
38
+ // org (they proceed to accept); a fresh signup under create: auto mints its
39
+ // own organization lazily, as owner, through the org plugin's adapter layer
40
+ // (the endpoint cannot serve the mint - see applyTenantPolicy).
41
+ function createActiveOrgPolicyHook({ getAuth, logger, organizations }) {
42
+ async function applyPinnedPolicy({ auth, adapter, internalAdapter, session, ctx }) {
43
+ const organization = await ensureOrganization({
44
+ auth,
45
+ logger,
46
+ slug: organizations.org
47
+ });
48
+ const member = await adapter.findOne({
49
+ model: 'member',
50
+ where: [
51
+ {
52
+ field: 'userId',
53
+ value: session.userId
54
+ },
55
+ {
56
+ field: 'organizationId',
57
+ value: organization.id
58
+ }
59
+ ]
60
+ });
61
+ if (member) {
62
+ return {
63
+ data: {
64
+ ...session,
65
+ activeOrganizationId: organization.id
66
+ }
67
+ };
68
+ }
69
+ // Open signup ensures membership here as well as at user.create.after:
70
+ // BetterAuth queues after-hooks inside an endpoint's transaction scope
71
+ // and flushes them after it completes (confirmed at 1.7.0; sign-up wraps
72
+ // user and session creation in one runWithTransaction), so a signup that
73
+ // mints an immediate session reaches this hook before the auto-join has
74
+ // run. The two joins are idempotent - each skips when the member row
75
+ // already exists.
76
+ if (organizations.signup === 'open') {
77
+ await auth.api.addMember({
78
+ body: {
79
+ userId: session.userId,
80
+ organizationId: organization.id,
81
+ // The canonical no-authority org tier - createAutoJoinHook mints the
82
+ // same value, so whichever join wins the race writes the same row.
83
+ role: 'member'
84
+ },
85
+ headers: getHookRequestHeaders(ctx)
86
+ });
87
+ return {
88
+ data: {
89
+ ...session,
90
+ activeOrganizationId: organization.id
91
+ }
92
+ };
93
+ }
94
+ const admitted = await isEmailAdmitted({
95
+ userId: session.userId,
96
+ organizations,
97
+ auth,
98
+ adapter,
99
+ internalAdapter
100
+ });
101
+ if (admitted) {
102
+ // The member row was a miss above, so admission under invite-only means
103
+ // the pending-invitation carve-out: the invitee needs a session to
104
+ // accept, so the session is created without an active organization.
105
+ return;
106
+ }
107
+ throw new APIError('FORBIDDEN', {
108
+ message: 'You have not been granted access to this application.',
109
+ code: 'MEMBERSHIP_REQUIRED'
110
+ });
111
+ }
112
+ // The user's own organization under open + auto. The slugs derive from the
113
+ // user id - org-<userId>, then org-<userId>-2, -3 and on. There are no
114
+ // transactions to lean on (the adapter supports standalone MongoDB), so the
115
+ // mint is two writes made safe by unique indexes (ensureAuthIndexes) and a
116
+ // marker:
117
+ //
118
+ // - The organization row is written with mintPending: true. Only a marked
119
+ // organization whose mint is still in progress (isMintInProgress) is ever
120
+ // joined as its owner here: one minted for this user moments ago whose
121
+ // owner row was never written - a mint that failed between its two
122
+ // writes, or one a concurrent session of the same user (a double submit,
123
+ // two tabs) is finishing right now. The marker is cleared once the owner
124
+ // row exists, so an organization everyone later left - with its data and
125
+ // pending invitations - is never handed back; the user moves on to the
126
+ // next slug and gets a fresh organization.
127
+ // - Two sessions creating the same slug: the unique slug index rejects the
128
+ // second, which reads the winner's row.
129
+ // - Two sessions writing the owner row, in any order around each other's
130
+ // writes: the unique (user, organization) index rejects the second, which
131
+ // reads the winner's row. The member row is always written before the
132
+ // marker is cleared, so a session that sees the marker cleared finds the
133
+ // member row.
134
+ async function findMember({ adapter, userId, organizationId }) {
135
+ return adapter.findOne({
136
+ model: 'member',
137
+ where: [
138
+ {
139
+ field: 'userId',
140
+ value: userId
141
+ },
142
+ {
143
+ field: 'organizationId',
144
+ value: organizationId
145
+ }
146
+ ]
147
+ });
148
+ }
149
+ async function findOrCreateOrganization({ adapter, name, slug }) {
150
+ const existing = await adapter.findOne({
151
+ model: 'organization',
152
+ where: [
153
+ {
154
+ field: 'slug',
155
+ value: slug
156
+ }
157
+ ]
158
+ });
159
+ if (existing) {
160
+ return existing;
161
+ }
162
+ try {
163
+ return await adapter.create({
164
+ model: 'organization',
165
+ data: {
166
+ name,
167
+ slug,
168
+ mintPending: true,
169
+ createdAt: new Date()
170
+ }
171
+ });
172
+ } catch (error) {
173
+ const winner = await adapter.findOne({
174
+ model: 'organization',
175
+ where: [
176
+ {
177
+ field: 'slug',
178
+ value: slug
179
+ }
180
+ ]
181
+ });
182
+ if (!winner) {
183
+ throw error;
184
+ }
185
+ return winner;
186
+ }
187
+ }
188
+ async function joinAsOwner({ adapter, userId, organizationId }) {
189
+ try {
190
+ await adapter.create({
191
+ model: 'member',
192
+ data: {
193
+ userId,
194
+ organizationId,
195
+ role: 'owner',
196
+ createdAt: new Date()
197
+ }
198
+ });
199
+ } catch (error) {
200
+ const winner = await findMember({
201
+ adapter,
202
+ userId,
203
+ organizationId
204
+ });
205
+ if (type.isNone(winner)) {
206
+ throw error;
207
+ }
208
+ }
209
+ }
210
+ async function clearMintPending({ adapter, organization }) {
211
+ if (organization.mintPending !== true) {
212
+ return;
213
+ }
214
+ await adapter.update({
215
+ model: 'organization',
216
+ where: [
217
+ {
218
+ field: 'id',
219
+ value: organization.id
220
+ }
221
+ ],
222
+ update: {
223
+ mintPending: false
224
+ }
225
+ });
226
+ }
227
+ // A marked organization is joined as owner only while its mint is in
228
+ // progress: minted within mintPendingMs and with no member other than the
229
+ // user. A marker older than that, or on an organization other people belong
230
+ // to, is left over from a mint that wrote the owner row and failed before
231
+ // clearing it - the organization has had an owner, so it is never handed
232
+ // back. The stale marker is cleared and the user moves on to the next slug.
233
+ async function isMintInProgress({ adapter, organization, userId }) {
234
+ if (organization.mintPending !== true) {
235
+ return false;
236
+ }
237
+ if (Date.now() - new Date(organization.createdAt).getTime() > mintPendingMs) {
238
+ return false;
239
+ }
240
+ const otherMembers = await adapter.count({
241
+ model: 'member',
242
+ where: [
243
+ {
244
+ field: 'organizationId',
245
+ value: organization.id
246
+ },
247
+ {
248
+ field: 'userId',
249
+ value: userId,
250
+ operator: 'ne'
251
+ }
252
+ ]
253
+ });
254
+ return otherMembers === 0;
255
+ }
256
+ async function findOrMintOwnOrganization({ adapter, session, user }) {
257
+ const name = user?.name || user?.email || session.userId;
258
+ for(let suffix = 1;; suffix += 1){
259
+ const slug = suffix === 1 ? `org-${session.userId}` : `org-${session.userId}-${suffix}`;
260
+ const organization = await findOrCreateOrganization({
261
+ adapter,
262
+ name,
263
+ slug
264
+ });
265
+ const member = await findMember({
266
+ adapter,
267
+ userId: session.userId,
268
+ organizationId: organization.id
269
+ });
270
+ if (!type.isNone(member)) {
271
+ await clearMintPending({
272
+ adapter,
273
+ organization
274
+ });
275
+ return organization;
276
+ }
277
+ if (await isMintInProgress({
278
+ adapter,
279
+ organization,
280
+ userId: session.userId
281
+ })) {
282
+ await joinAsOwner({
283
+ adapter,
284
+ userId: session.userId,
285
+ organizationId: organization.id
286
+ });
287
+ await clearMintPending({
288
+ adapter,
289
+ organization
290
+ });
291
+ return organization;
292
+ }
293
+ await clearMintPending({
294
+ adapter,
295
+ organization
296
+ });
297
+ }
298
+ }
299
+ async function applyTenantPolicy({ auth, adapter, internalAdapter, session }) {
300
+ const members = await adapter.findMany({
301
+ model: 'member',
302
+ where: [
303
+ {
304
+ field: 'userId',
305
+ value: session.userId
306
+ }
307
+ ],
308
+ sortBy: {
309
+ field: 'createdAt',
310
+ direction: 'asc'
311
+ },
312
+ limit: 1
313
+ });
314
+ if (members.length > 0) {
315
+ return {
316
+ data: {
317
+ ...session,
318
+ activeOrganizationId: members[0].organizationId
319
+ }
320
+ };
321
+ }
322
+ const user = await internalAdapter.findUserById(session.userId);
323
+ const invitation = user ? await findPendingInvitation({
324
+ adapter,
325
+ email: user.email
326
+ }) : null;
327
+ if (invitation) {
328
+ // An invited user joins the inviter's tenant on accept - mint nothing.
329
+ // If the invitation expires unaccepted, the next login lands here with
330
+ // no pending invitation: invite-only refuses them at the neither branch,
331
+ // while open + operator returns an org-less session.
332
+ return;
333
+ }
334
+ // Neither a membership nor a pending invitation. What happens depends on
335
+ // the two admission knobs.
336
+ if (organizations.signup === 'invite-only') {
337
+ // Reached only by existing users - removed from their last org, or an
338
+ // invitation that expired. New uninvited users never got past the create
339
+ // gate. Same shape as applyPinnedPolicy, so client handling is
340
+ // policy-blind.
341
+ throw new APIError('FORBIDDEN', {
342
+ message: 'You have not been granted access to this application.',
343
+ code: 'MEMBERSHIP_REQUIRED'
344
+ });
345
+ }
346
+ if (organizations.create === 'operator') {
347
+ // open + operator: no membership, no invitation, orgs come only from the
348
+ // operator - return an org-less session (awaiting organization). Public
349
+ // pages see the caller; protected pages are walled until an org is
350
+ // assigned.
351
+ return;
352
+ }
353
+ // open + auto: mint the user's own org as owner.
354
+ // Written through the adapter, not the org plugin's createOrganization
355
+ // endpoint: a headerless system-action call cannot resolve the engine's
356
+ // dynamic baseURL at 1.7.0, and forwarding the firing request's headers
357
+ // makes the endpoint demand a session that does not exist yet. The mint
358
+ // is only safe behind the unique indexes, so it refuses without them.
359
+ try {
360
+ await ensureAuthIndexes({
361
+ auth,
362
+ logger
363
+ });
364
+ } catch {
365
+ // Logged once per attempt by ensureAuthIndexes, with the cause.
366
+ throw new APIError('SERVICE_UNAVAILABLE', {
367
+ message: 'Your workspace can not be created right now. Try again in a minute.',
368
+ code: 'ORGANIZATION_SETUP_UNAVAILABLE'
369
+ });
370
+ }
371
+ const organization = await findOrMintOwnOrganization({
372
+ adapter,
373
+ session,
374
+ user
375
+ });
376
+ return {
377
+ data: {
378
+ ...session,
379
+ activeOrganizationId: organization.id
380
+ }
381
+ };
382
+ }
383
+ return async function activeOrgPolicyHook(session, ctx) {
384
+ const auth = getAuth();
385
+ const { adapter, internalAdapter } = await auth.$context;
386
+ if (organizations.policy === 'tenant') {
387
+ return applyTenantPolicy({
388
+ auth,
389
+ adapter,
390
+ internalAdapter,
391
+ session
392
+ });
393
+ }
394
+ return applyPinnedPolicy({
395
+ auth,
396
+ adapter,
397
+ internalAdapter,
398
+ session,
399
+ ctx
400
+ });
401
+ };
402
+ }
403
+ export default createActiveOrgPolicyHook;
@@ -0,0 +1,50 @@
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 isEmailAdmitted from './isEmailAdmitted.js';
17
+ // The engine-tier user.create.before admission gate. Every provider mints its
18
+ // user row here at first sign-in, before any session exists - the seam this
19
+ // gate uses to refuse an unadmitted email one step ahead of the session.create
20
+ // wall, so no orphan user (and, since this runs before the merge-on-signup
21
+ // hook, no orphan contact) is ever written.
22
+ //
23
+ // It throws instead of returning false so the rejection carries the
24
+ // MEMBERSHIP_REQUIRED code and matches the wall. The message is set to the same
25
+ // machine token deliberately: the OAuth path surfaces the throw's message (not
26
+ // its code) on the error-callback redirect, so equal message and code land a
27
+ // consistent ?error=MEMBERSHIP_REQUIRED across every provider.
28
+ //
29
+ // A no-op under open (isEmailAdmitted returns admitted), so it never blocks a
30
+ // legitimate open signup.
31
+ function createAdmissionGateHook({ getAuth, organizations }) {
32
+ return async function admissionGateHook(user) {
33
+ const auth = getAuth();
34
+ const { adapter, internalAdapter } = await auth.$context;
35
+ const admitted = await isEmailAdmitted({
36
+ email: user.email,
37
+ organizations,
38
+ auth,
39
+ adapter,
40
+ internalAdapter
41
+ });
42
+ if (!admitted) {
43
+ throw new APIError('FORBIDDEN', {
44
+ message: 'MEMBERSHIP_REQUIRED',
45
+ code: 'MEMBERSHIP_REQUIRED'
46
+ });
47
+ }
48
+ };
49
+ }
50
+ export default createAdmissionGateHook;
@@ -0,0 +1,90 @@
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 binding on the organization plugin's afterAcceptInvitation
17
+ // hook (an organizationHooks callback, not a database hook - it fires after
18
+ // the member row is created). An invitation may carry an opaque profile bag;
19
+ // accepting shallow-merges it onto the accepting user's user.profile,
20
+ // invitation winning per key - an opaque copy the engine never reads inside.
21
+ // The merge is in-band: a failed copy fails the accept and the user retries.
22
+ // invitation.contactId - the link to the app's record for this person - is the
23
+ // third opaque copy, and rides the same user-row update as the profile merge.
24
+ // Invite-time member attributes and app roles ride the invitation the same
25
+ // way: accepting copies invitation.attributes and invitation.appRoles onto the
26
+ // minted member row (one adapter-layer update, parallel to the opaque profile
27
+ // merge), so an invited user's authorization parameters and app roles hold
28
+ // from their first session instead of an empty bag until an admin edits the
29
+ // member. The guard fires when either field is present - folding appRoles into
30
+ // an attributes-only guard would silently drop the roles of every invitation
31
+ // that carries roles and no attributes.
32
+ //
33
+ // invitation.role needs no copy: acceptInvitation mints the member row from it
34
+ // directly (crud-invites.mjs:324), never validating it against the registered
35
+ // set - which is what makes the bootstrap recipe's hand-inserted role: 'owner'
36
+ // work.
37
+ function createAfterAcceptInvitationHook({ getAuth }) {
38
+ return async function afterAcceptInvitationHook({ invitation, member, user }) {
39
+ const { adapter, internalAdapter } = await getAuth().$context;
40
+ const userUpdate = {};
41
+ if (type.isObject(invitation.profile)) {
42
+ // The hook's user is the session user, which may be a cookie-cached
43
+ // copy - the merge base is read from the user row so a read-merge-write
44
+ // never resurrects a stale profile.
45
+ const userRow = await adapter.findOne({
46
+ model: 'user',
47
+ where: [
48
+ {
49
+ field: 'id',
50
+ value: user.id
51
+ }
52
+ ]
53
+ });
54
+ userUpdate.profile = {
55
+ ...userRow.profile ?? {},
56
+ ...invitation.profile
57
+ };
58
+ }
59
+ // contactId is a top-level user field, so it is set outright - no read, no
60
+ // merge. An invitation that names no link leaves an existing one standing.
61
+ if (type.isString(invitation.contactId)) {
62
+ userUpdate.contactId = invitation.contactId;
63
+ }
64
+ if (Object.keys(userUpdate).length > 0) {
65
+ await internalAdapter.updateUser(user.id, userUpdate);
66
+ }
67
+ const memberUpdate = {};
68
+ if (type.isObject(invitation.attributes)) {
69
+ memberUpdate.attributes = invitation.attributes;
70
+ }
71
+ // An empty appRoles array is a copied value, not an absent field - an
72
+ // invitation that deliberately grants nothing writes [].
73
+ if (type.isArray(invitation.appRoles)) {
74
+ memberUpdate.appRoles = invitation.appRoles;
75
+ }
76
+ if (Object.keys(memberUpdate).length > 0) {
77
+ await adapter.update({
78
+ model: 'member',
79
+ where: [
80
+ {
81
+ field: 'id',
82
+ value: member.id
83
+ }
84
+ ],
85
+ update: memberUpdate
86
+ });
87
+ }
88
+ };
89
+ }
90
+ export default createAfterAcceptInvitationHook;
@@ -0,0 +1,68 @@
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 ensureOrganization from './ensureOrganization.js';
16
+ import getHookRequestHeaders from './getHookRequestHeaders.js';
17
+ // The engine-tier user.create.after hook for open signup under the pinned
18
+ // policy: auto-join the pinned org through the server-only addMember endpoint
19
+ // so the plugin's invariants and hooks run. The member row is minted with the
20
+ // no-authority org tier 'member' and no appRoles, so the user passes the
21
+ // membership wall by row existence while role-gated pages still gate them -
22
+ // _user.roles reads [] because _user.roles is member.appRoles, not because
23
+ // the org tier is empty. With requireEmailVerification the signup holds this
24
+ // member row but obtains no session until verified, so joining at user-create
25
+ // is safe.
26
+ //
27
+ // BetterAuth queues after-hooks inside an endpoint's transaction scope and
28
+ // flushes them after it completes (confirmed at 1.7.0; sign-up wraps user and
29
+ // session creation in one runWithTransaction), so a signup minting an
30
+ // immediate session runs the session.create policy hook first - that hook
31
+ // also ensures membership under open signup, and this one skips when the
32
+ // member row already exists. Both sites therefore have to agree on the value
33
+ // they mint, and createActiveOrgPolicyHook already writes 'member'.
34
+ function createAutoJoinHook({ getAuth, organizations }) {
35
+ return async function autoJoinHook(user, ctx) {
36
+ const auth = getAuth();
37
+ const organization = await ensureOrganization({
38
+ auth,
39
+ slug: organizations.org
40
+ });
41
+ const { adapter } = await auth.$context;
42
+ const member = await adapter.findOne({
43
+ model: 'member',
44
+ where: [
45
+ {
46
+ field: 'userId',
47
+ value: user.id
48
+ },
49
+ {
50
+ field: 'organizationId',
51
+ value: organization.id
52
+ }
53
+ ]
54
+ });
55
+ if (member) {
56
+ return;
57
+ }
58
+ await auth.api.addMember({
59
+ body: {
60
+ userId: user.id,
61
+ organizationId: organization.id,
62
+ role: 'member'
63
+ },
64
+ headers: getHookRequestHeaders(ctx)
65
+ });
66
+ };
67
+ }
68
+ export default createAutoJoinHook;
@@ -0,0 +1,59 @@
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 isEmailAdmitted from './isEmailAdmitted.js';
17
+ // The engine-tier request hooks.before that gates a public, unauthenticated
18
+ // email send - the magic-link send and the one-time-code send. Both are
19
+ // unauthenticated: without this gate anyone could make an invite-only app
20
+ // deliver its branded sign-in email to any address (and, absent the create
21
+ // gate, manufacture orphan records by using it).
22
+ //
23
+ // A bare handler: the request-hook assembler matches the path and owns the
24
+ // createAuthMiddleware wrapper.
25
+ //
26
+ // When the body email is not admitted the handler returns the gated route's own
27
+ // success body - short-circuiting the endpoint (a before-hook return with no
28
+ // "context" key becomes the response), so no email is dispatched and no
29
+ // verification token or code is minted. Which body that is differs per route
30
+ // (/sign-in/magic-link answers { status: true }, /email-otp/send-verification-otp
31
+ // answers { success: true }), so the caller names it: a uniform response is what
32
+ // makes the "check your email" screen identical whether or not anything was
33
+ // sent, and a body that did not match the route's own would give the difference
34
+ // away. When admitted it falls through and the normal send proceeds. A no-op
35
+ // under open signup (isEmailAdmitted returns admitted).
36
+ function createEmailSendGate({ getAuth, organizations, successBody }) {
37
+ return async function emailSendGate(ctx) {
38
+ const email = ctx.body?.email;
39
+ // No email is the route's own validation error, not an admission decision -
40
+ // fall through and let it answer.
41
+ if (!type.isString(email)) {
42
+ return undefined;
43
+ }
44
+ const auth = getAuth();
45
+ const { adapter, internalAdapter } = await auth.$context;
46
+ const admitted = await isEmailAdmitted({
47
+ email,
48
+ organizations,
49
+ auth,
50
+ adapter,
51
+ internalAdapter
52
+ });
53
+ if (admitted) {
54
+ return undefined;
55
+ }
56
+ return successBody;
57
+ };
58
+ }
59
+ export default createEmailSendGate;