@lowdefy/api 7.0.0 → 7.2.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 (119) hide show
  1. package/dist/context/createAuthorizeOutcome.js +1 -1
  2. package/dist/context/createEvaluateOperators.js +2 -1
  3. package/dist/context/isWebSocketOriginAllowed.js +3 -1
  4. package/dist/context/readMemberships.js +10 -4
  5. package/dist/context/resolveAuthentication.js +95 -21
  6. package/dist/email/renderAuthEmail.js +3 -2
  7. package/dist/index.js +7 -1
  8. package/dist/response/redactErrorResponse.js +8 -4
  9. package/dist/routes/agent/callAgent.js +20 -2
  10. package/dist/routes/agent/redactMessages.js +136 -0
  11. package/dist/routes/auth/createAuthLogger.js +23 -6
  12. package/dist/routes/auth/createMcpAccessTokenClaims.js +8 -6
  13. package/dist/routes/auth/createOnAPIError.js +15 -5
  14. package/dist/routes/auth/createSendEmail.js +15 -5
  15. package/dist/routes/auth/getBetterAuth.js +3 -3
  16. package/dist/routes/auth/getBetterAuthConfig.js +163 -92
  17. package/dist/routes/auth/hooks/buildEngineHooks.js +15 -1
  18. package/dist/routes/auth/hooks/createUserAfterHook.js +17 -2
  19. package/dist/routes/auth/hooks/createUserBeforeHook.js +20 -4
  20. package/dist/routes/auth/mobile/buildBearerPlugin.js +45 -0
  21. package/dist/routes/auth/mobile/buildOneTimeTokenPlugin.js +50 -0
  22. package/dist/routes/auth/mobile/createCodeVerifierCheck.js +57 -0
  23. package/dist/routes/auth/mobile/createKnownDeviceHook.js +76 -0
  24. package/dist/routes/auth/mobile/createMobileAuthPageResponse.js +79 -0
  25. package/dist/routes/auth/mobile/createMobileSessionCreateHook.js +41 -0
  26. package/dist/routes/auth/mobile/createMobileSessionRefreshHook.js +40 -0
  27. package/dist/routes/auth/mobile/createMobileSignInCsrfToken.js +32 -0
  28. package/dist/routes/auth/mobile/createPhoneSession.js +59 -0
  29. package/dist/routes/auth/mobile/escapeHtml.js +26 -0
  30. package/dist/routes/auth/mobile/getCodeHolderIdentifier.js +20 -0
  31. package/dist/routes/auth/mobile/getKnownDeviceIdentifier.js +20 -0
  32. package/dist/routes/auth/mobile/getMobileSessionExpiry.js +18 -0
  33. package/dist/routes/auth/mobile/getMobileSignInReturnUrl.js +31 -0
  34. package/dist/routes/auth/mobile/getOneTimeTokenIdentifiers.js +26 -0
  35. package/dist/routes/auth/mobile/handleMobileSignIn.js +303 -0
  36. package/dist/routes/auth/mobile/handleMobileSignInCallback.js +30 -0
  37. package/dist/routes/auth/mobile/isNativeAuthRequest.js +33 -0
  38. package/dist/routes/auth/mobile/matchesCodeChallenge.js +29 -0
  39. package/dist/routes/auth/mobile/mintOneTimeToken.js +41 -0
  40. package/dist/routes/auth/mobile/readDeviceKeyHash.js +34 -0
  41. package/dist/routes/auth/mobile/readMobileSignInParams.js +90 -0
  42. package/dist/routes/auth/mobile/sha256Base64Url.js +22 -0
  43. package/dist/routes/auth/mobile/storeCodeChallenge.js +29 -0
  44. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +43 -6
  45. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +7 -2
  46. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +41 -189
  47. package/dist/routes/auth/organizations/createAdmissionGateHook.js +5 -5
  48. package/dist/routes/auth/organizations/createBeforeCreateInvitationHook.js +62 -0
  49. package/dist/routes/auth/organizations/createBeforeUpdateMemberRoleHook.js +45 -0
  50. package/dist/routes/auth/organizations/createSuspendedMemberGate.js +146 -0
  51. package/dist/routes/auth/organizations/createSuspendedOrganizationsFilter.js +44 -0
  52. package/dist/routes/auth/organizations/ensureAuthIndexes.js +11 -10
  53. package/dist/routes/auth/organizations/getOrganizationBinding.js +4 -2
  54. package/dist/routes/auth/organizations/isActiveMember.js +26 -0
  55. package/dist/routes/auth/organizations/isEmailAdmitted.js +12 -5
  56. package/dist/routes/auth/organizations/memberRowsLimit.js +19 -0
  57. package/dist/routes/auth/organizations/mintOrganization.js +258 -0
  58. package/dist/routes/auth/organizations/organizationAccessControl.js +5 -1
  59. package/dist/routes/auth/organizations/provisionOrganization.js +117 -0
  60. package/dist/routes/auth/organizations/readSuspendedOrganizationIds.js +36 -0
  61. package/dist/routes/auth/requestHooks/buildRequestHooks.js +72 -0
  62. package/dist/routes/auth/requestHooks/createEmailCodeHolderGate.js +58 -0
  63. package/dist/routes/auth/requestHooks/createEmailSendLimit.js +116 -0
  64. package/dist/routes/auth/requestHooks/createSignInRefusedRedirectHook.js +75 -0
  65. package/dist/routes/auth/requestHooks/holdEmailCode.js +80 -0
  66. package/dist/routes/auth/requestHooks/reserveSendSlot.js +70 -0
  67. package/dist/routes/auth/runReportingFaults.js +32 -0
  68. package/dist/routes/connections/resolveUnwalledReach.js +14 -16
  69. package/dist/routes/endpoints/callEndpoint.js +6 -3
  70. package/dist/routes/endpoints/control/controlFor.js +9 -6
  71. package/dist/routes/endpoints/control/controlIf.js +8 -3
  72. package/dist/routes/endpoints/control/controlLog.js +3 -1
  73. package/dist/routes/endpoints/control/controlParallelFor.js +9 -6
  74. package/dist/routes/endpoints/control/controlReturn.js +3 -2
  75. package/dist/routes/endpoints/control/controlSetState.js +1 -1
  76. package/dist/routes/endpoints/control/controlSwitch.js +6 -3
  77. package/dist/routes/endpoints/control/controlWhile.js +6 -3
  78. package/dist/routes/endpoints/createLinkAnswer.js +76 -0
  79. package/dist/routes/endpoints/dispatchDetached.js +38 -0
  80. package/dist/routes/endpoints/forwardScheduledEndpoint.js +32 -11
  81. package/dist/routes/endpoints/handleAgentCall.js +1 -1
  82. package/dist/routes/endpoints/handleAuthStep.js +19 -4
  83. package/dist/routes/endpoints/handleEndpointCall.js +6 -4
  84. package/dist/routes/endpoints/handleRequest.js +3 -2
  85. package/dist/routes/endpoints/handleValidateDynamic.js +1 -1
  86. package/dist/routes/endpoints/matchLinkEndpoint.js +30 -0
  87. package/dist/routes/endpoints/runLinkEndpoint.js +148 -0
  88. package/dist/routes/endpoints/runRoutine.js +5 -5
  89. package/dist/routes/endpoints/scheduleBackground.js +13 -11
  90. package/dist/routes/endpoints/test/runTest.js +30 -11
  91. package/dist/routes/mcp/createMcpServer.js +2 -7
  92. package/dist/routes/mcp/runAfterToolCall.js +9 -3
  93. package/dist/routes/mobile/createAppleAppSiteAssociation.js +51 -0
  94. package/dist/routes/mobile/createAssetLinks.js +38 -0
  95. package/dist/routes/mobile/filterMobileMenus.js +31 -0
  96. package/dist/routes/mobile/getMobileAppEvents.js +23 -0
  97. package/dist/routes/mobile/getMobileRootConfig.js +109 -0
  98. package/dist/routes/mobile/getOpenablePageIds.js +21 -0
  99. package/dist/routes/page/dynamic/policy/checkAction.js +67 -2
  100. package/dist/routes/page/dynamic/policy/checkEvents.js +8 -2
  101. package/dist/routes/page/dynamic/policy/checkPolicy.js +86 -6
  102. package/dist/routes/page/dynamic/policy/checkValue.js +97 -6
  103. package/dist/routes/page/dynamic/policy/collectSchemaKinds.js +173 -0
  104. package/dist/routes/page/dynamic/policy/findDataRows.js +94 -0
  105. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +24 -12
  106. package/dist/routes/page/dynamic/policy/findHtmlUrls.js +64 -0
  107. package/dist/routes/page/dynamic/policy/overlapsStatePath.js +28 -0
  108. package/dist/routes/page/dynamic/resolveDynamicContent.js +23 -17
  109. package/dist/routes/page/getPageConfig.js +25 -1
  110. package/dist/routes/request/callRequestResolver.js +29 -36
  111. package/dist/routes/request/stampTypedError.js +37 -0
  112. package/dist/routes/request/summarisedError.js +62 -0
  113. package/dist/routes/request/wrapResolverError.js +61 -0
  114. package/dist/routes/websocket/createChannelRegistry.js +13 -15
  115. package/dist/routes/websocket/createWebSocketConnection.js +5 -8
  116. package/dist/test/createMemoryAuth.js +125 -0
  117. package/package.json +20 -22
  118. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +0 -117
  119. package/dist/routes/request/maskCredentialProperties.js +0 -34
@@ -14,9 +14,12 @@
14
14
  limitations under the License.
15
15
  */ import { organization } from 'better-auth/plugins';
16
16
  import createAfterAcceptInvitationHook from './createAfterAcceptInvitationHook.js';
17
+ import createBeforeCreateInvitationHook from './createBeforeCreateInvitationHook.js';
18
+ import createBeforeUpdateMemberRoleHook from './createBeforeUpdateMemberRoleHook.js';
17
19
  import modelNames from '../modelNames.js';
18
20
  import { ac, roles } from './organizationAccessControl.js';
19
21
  const DEFAULT_MEMBERSHIP_LIMIT = 1000000;
22
+ const DEFAULT_INVITATION_LIMIT = 1000000;
20
23
  // Organizations are always on - the membership and boundary mechanism for every
21
24
  // app. member.role carries BetterAuth's org-authority tier and nothing else, so
22
25
  // the same three built-in roles - owner, admin, member - are registered under
@@ -70,20 +73,32 @@ function buildOrganizationPlugin({ authConfig = {}, getAuth, sendInvitationEmail
70
73
  // default page size of list-members and the user lookup behind
71
74
  // getFullOrganization.
72
75
  membershipLimit: Number.isFinite(authConfig.organizations?.membershipLimit) ? authConfig.organizations.membershipLimit : DEFAULT_MEMBERSHIP_LIMIT,
76
+ // BetterAuth's own cap of 100 open invitations is held open: its count
77
+ // never goes past the adapter's default page of 100 rows, so it cannot
78
+ // enforce a larger limit. createBeforeCreateInvitationHook enforces
79
+ // auth.organizations.invitationLimit instead.
80
+ invitationLimit: DEFAULT_INVITATION_LIMIT,
73
81
  schema: {
74
82
  organization: {
75
83
  modelName: modelNames.organization,
76
84
  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.
85
+ // Set while an engine mint has written the organization but not yet
86
+ // its owner's member row (mintOrganization). Only a marked
87
+ // organization is ever joined as owner by a mint, and only by the
88
+ // creator in mintCreatorId, so one that everyone has left is never
89
+ // handed back. Server-only: never accepted from a request body,
90
+ // never returned by an endpoint.
82
91
  mintPending: {
83
92
  type: 'boolean',
84
93
  required: false,
85
94
  input: false,
86
95
  returned: false
96
+ },
97
+ mintCreatorId: {
98
+ type: 'string',
99
+ required: false,
100
+ input: false,
101
+ returned: false
87
102
  }
88
103
  }
89
104
  },
@@ -122,6 +137,16 @@ function buildOrganizationPlugin({ authConfig = {}, getAuth, sendInvitationEmail
122
137
  type: 'string',
123
138
  required: false,
124
139
  input: false
140
+ },
141
+ // A suspended member keeps their row - roles, attributes and all, so
142
+ // the app's own queries still find them - but holds no membership:
143
+ // every check that admits a member reads it (isActiveMember). Written
144
+ // only by the SuspendMember and UnsuspendMember steps. Absent means
145
+ // not suspended, so rows written before it existed need no migration.
146
+ suspended: {
147
+ type: 'boolean',
148
+ required: false,
149
+ input: false
125
150
  }
126
151
  }
127
152
  },
@@ -169,7 +194,19 @@ function buildOrganizationPlugin({ authConfig = {}, getAuth, sendInvitationEmail
169
194
  organizationHooks: {
170
195
  afterAcceptInvitation: createAfterAcceptInvitationHook({
171
196
  getAuth
172
- })
197
+ }),
198
+ // Keeps a suspended member out of the owner tier, so the plugin's owner
199
+ // guards, which count every owner row, stay exact (SuspendMember).
200
+ beforeUpdateMemberRole: createBeforeUpdateMemberRoleHook(),
201
+ // Registered only when a limit is set: unset, the cap is the
202
+ // effectively open DEFAULT_INVITATION_LIMIT above, and every invite
203
+ // would pay for a count that can never refuse.
204
+ ...Number.isFinite(authConfig.organizations?.invitationLimit) ? {
205
+ beforeCreateInvitation: createBeforeCreateInvitationHook({
206
+ getAuth,
207
+ invitationLimit: authConfig.organizations.invitationLimit
208
+ })
209
+ } : {}
173
210
  },
174
211
  sendInvitationEmail
175
212
  };
@@ -15,6 +15,7 @@
15
15
  */ import { getSessionFromCtx } from 'better-auth/api';
16
16
  import { setSessionCookie } from 'better-auth/cookies';
17
17
  import { type } from '@lowdefy/helpers';
18
+ import isActiveMember from './isActiveMember.js';
18
19
  // The engine-tier request hooks.before on /organization/accept-invitation for a
19
20
  // caller who is already a member of the invitation's organization - someone
20
21
  // invited before they joined another way (the open-signup auto-join, an
@@ -38,7 +39,9 @@ import { type } from '@lowdefy/helpers';
38
39
  //
39
40
  // Like the route, the session gets the organization as its active one only
40
41
  // when it has none (createAcceptActiveOrgGuardHook vetoes the route's switch
41
- // away from an existing active organization).
42
+ // away from an existing active organization). A suspended membership is left
43
+ // as it is too, so the organization is never made active: it admits nobody,
44
+ // and an org-less session at least keeps the caller awaiting an organization.
42
45
  function createAcceptExistingMemberHook() {
43
46
  return async function acceptExistingMemberHook(ctx) {
44
47
  const invitationId = ctx.body?.invitationId;
@@ -101,7 +104,9 @@ function createAcceptExistingMemberHook() {
101
104
  if (type.isNone(accepted)) {
102
105
  return undefined;
103
106
  }
104
- if (type.isNone(session.session.activeOrganizationId)) {
107
+ if (type.isNone(session.session.activeOrganizationId) && isActiveMember({
108
+ member
109
+ })) {
105
110
  // Re-issued like the set-active-organization route does, so a session
106
111
  // cookie cache does not keep serving the org-less session.
107
112
  await setSessionCookie(ctx, {
@@ -18,11 +18,10 @@ import ensureAuthIndexes from './ensureAuthIndexes.js';
18
18
  import ensureOrganization from './ensureOrganization.js';
19
19
  import findPendingInvitation from './findPendingInvitation.js';
20
20
  import getHookRequestHeaders from './getHookRequestHeaders.js';
21
+ import isActiveMember from './isActiveMember.js';
21
22
  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;
23
+ import MEMBER_ROWS_LIMIT from './memberRowsLimit.js';
24
+ import mintOrganization from './mintOrganization.js';
26
25
  // The engine-tier session.create hook that applies the active-org policy.
27
26
  // session.create is the one provider-agnostic choke point - it fires for
28
27
  // email/password, magic link and OAuth alike.
@@ -36,8 +35,9 @@ const mintPendingMs = 10 * 60 * 1000;
36
35
  // tenant: the active org is the user's business - the oldest membership when
37
36
  // they hold several; a user with a pending invitation gets a session but no
38
37
  // 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).
38
+ // own organization lazily, as owner, through mintOrganization (the endpoint
39
+ // cannot serve the mint - see applyTenantPolicy), holding the app roles
40
+ // auth.organizations.creatorAppRoles lists.
41
41
  function createActiveOrgPolicyHook({ getAuth, logger, organizations }) {
42
42
  async function applyPinnedPolicy({ auth, adapter, internalAdapter, session, ctx }) {
43
43
  const organization = await ensureOrganization({
@@ -58,7 +58,9 @@ function createActiveOrgPolicyHook({ getAuth, logger, organizations }) {
58
58
  }
59
59
  ]
60
60
  });
61
- if (member) {
61
+ if (isActiveMember({
62
+ member
63
+ })) {
62
64
  return {
63
65
  data: {
64
66
  ...session,
@@ -73,7 +75,7 @@ function createActiveOrgPolicyHook({ getAuth, logger, organizations }) {
73
75
  // mints an immediate session reaches this hook before the auto-join has
74
76
  // run. The two joins are idempotent - each skips when the member row
75
77
  // already exists.
76
- if (organizations.signup === 'open') {
78
+ if (type.isNone(member) && organizations.signup === 'open') {
77
79
  await auth.api.addMember({
78
80
  body: {
79
81
  userId: session.userId,
@@ -91,7 +93,12 @@ function createActiveOrgPolicyHook({ getAuth, logger, organizations }) {
91
93
  }
92
94
  };
93
95
  }
94
- const admitted = await isEmailAdmitted({
96
+ // A suspended member is refused under either signup mode, with the code a
97
+ // refused non-member gets: open signup must not join them (the row they
98
+ // hold is the suspension), and an invitation cannot let them in either -
99
+ // accepting one leaves an existing membership as it is
100
+ // (createAcceptExistingMemberHook).
101
+ const admitted = type.isNone(member) && await isEmailAdmitted({
95
102
  userId: session.userId,
96
103
  organizations,
97
104
  auth,
@@ -110,193 +117,35 @@ function createActiveOrgPolicyHook({ getAuth, logger, organizations }) {
110
117
  });
111
118
  }
112
119
  // 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
- }
120
+ // user id - org-<userId>, then org-<userId>-2, -3 and on. Each slug is tried
121
+ // with mintOrganization, which takes it only when it is the user's own: new,
122
+ // already theirs, or a mint of theirs that stopped between its two writes.
123
+ // An organization everyone later left - with its data and pending
124
+ // invitations - is never handed back; the user moves on to the next slug and
125
+ // gets a fresh organization.
256
126
  async function findOrMintOwnOrganization({ adapter, session, user }) {
257
127
  const name = user?.name || user?.email || session.userId;
258
128
  for(let suffix = 1;; suffix += 1){
259
129
  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({
130
+ const minted = await mintOrganization({
266
131
  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,
132
+ creatorAppRoles: organizations.creatorAppRoles,
133
+ keepMembership: true,
134
+ organization: {
135
+ name,
136
+ slug
137
+ },
280
138
  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
139
  });
140
+ if (!type.isNone(minted)) {
141
+ return minted.organization;
142
+ }
297
143
  }
298
144
  }
299
145
  async function applyTenantPolicy({ auth, adapter, internalAdapter, session }) {
146
+ // Every row, not the oldest one: the oldest may be suspended, and the
147
+ // filter runs here rather than in the query so it means the same on every
148
+ // adapter (a row written before suspension existed has no suspended field).
300
149
  const members = await adapter.findMany({
301
150
  model: 'member',
302
151
  where: [
@@ -309,13 +158,16 @@ function createActiveOrgPolicyHook({ getAuth, logger, organizations }) {
309
158
  field: 'createdAt',
310
159
  direction: 'asc'
311
160
  },
312
- limit: 1
161
+ limit: MEMBER_ROWS_LIMIT
313
162
  });
314
- if (members.length > 0) {
163
+ const activeMember = members.find((member)=>isActiveMember({
164
+ member
165
+ }));
166
+ if (!type.isNone(activeMember)) {
315
167
  return {
316
168
  data: {
317
169
  ...session,
318
- activeOrganizationId: members[0].organizationId
170
+ activeOrganizationId: activeMember.organizationId
319
171
  }
320
172
  };
321
173
  }
@@ -21,10 +21,10 @@ import isEmailAdmitted from './isEmailAdmitted.js';
21
21
  // hook, no orphan contact) is ever written.
22
22
  //
23
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.
24
+ // MEMBERSHIP_REQUIRED code and matches the wall, message included: the magic
25
+ // link and OAuth callbacks redirect a refusal with the code in ?error= and the
26
+ // message in error_description, so a new user refused here and an existing one
27
+ // refused at the wall land on the error page with the same text.
28
28
  //
29
29
  // A no-op under open (isEmailAdmitted returns admitted), so it never blocks a
30
30
  // legitimate open signup.
@@ -41,7 +41,7 @@ function createAdmissionGateHook({ getAuth, organizations }) {
41
41
  });
42
42
  if (!admitted) {
43
43
  throw new APIError('FORBIDDEN', {
44
- message: 'MEMBERSHIP_REQUIRED',
44
+ message: 'You have not been granted access to this application.',
45
45
  code: 'MEMBERSHIP_REQUIRED'
46
46
  });
47
47
  }
@@ -0,0 +1,62 @@
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
+ // The engine-tier binding on the organization plugin's beforeCreateInvitation
17
+ // hook, which enforces the cap on open invitations per organization. The
18
+ // plugin's own invitationLimit check cannot: it reads pending invitations with
19
+ // an unbounded findMany, which the adapter cuts to its default page of 100 rows
20
+ // before expired ones are filtered out in code. A limit above 100 is never
21
+ // reached, and expired rows inside that page hide open ones.
22
+ // buildOrganizationPlugin holds that check open, and this hook counts every
23
+ // pending, unexpired invitation of the organization instead.
24
+ //
25
+ // The hook runs after a re-invite has cancelled the address's earlier
26
+ // invitation, so the invitation being replaced is not counted. That order is
27
+ // BetterAuth's: an organization already over its limit (the limit lowered after
28
+ // invitations went out) refuses the re-invite after the cancel, and the
29
+ // address is left with no open invitation. A resend refreshes an invitation
30
+ // without creating one and never reaches the hook. The count and the create are
31
+ // separate writes, so invitations created in parallel can pass the limit by
32
+ // the number in flight, as BetterAuth's own check could.
33
+ function createBeforeCreateInvitationHook({ getAuth, invitationLimit }) {
34
+ return async function beforeCreateInvitationHook({ organization }) {
35
+ const { adapter } = await getAuth().$context;
36
+ const openInvitations = await adapter.count({
37
+ model: 'invitation',
38
+ where: [
39
+ {
40
+ field: 'organizationId',
41
+ value: organization.id
42
+ },
43
+ {
44
+ field: 'status',
45
+ value: 'pending'
46
+ },
47
+ {
48
+ field: 'expiresAt',
49
+ operator: 'gt',
50
+ value: new Date()
51
+ }
52
+ ]
53
+ });
54
+ if (openInvitations >= invitationLimit) {
55
+ throw new APIError('FORBIDDEN', {
56
+ code: 'INVITATION_LIMIT_REACHED',
57
+ message: 'This organization has reached its limit of open invitations.'
58
+ });
59
+ }
60
+ };
61
+ }
62
+ export default createBeforeCreateInvitationHook;
@@ -0,0 +1,45 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { APIError } from 'better-auth/api';
16
+ import isActiveMember from './isActiveMember.js';
17
+ // The engine-tier binding on the organization plugin's beforeUpdateMemberRole
18
+ // hook, which keeps a suspended member out of the owner tier. The plugin's
19
+ // owner guards (an admin cannot remove or demote an owner, the last owner
20
+ // cannot leave, be removed or demote themselves) count every owner row and know
21
+ // nothing of suspension. SuspendMember refuses an owner, and this refuses the
22
+ // other way in, so no suspended row holds owner and those counts stay exact.
23
+ // It runs inside the endpoint, so it covers the UpdateMemberOrgRole step and
24
+ // the tenant client call alike.
25
+ //
26
+ // newRole is the plugin's parsed role string, comma-separated when the
27
+ // request set several.
28
+ function createBeforeUpdateMemberRoleHook() {
29
+ return async function beforeUpdateMemberRoleHook({ member, newRole }) {
30
+ if (isActiveMember({
31
+ member
32
+ })) {
33
+ return undefined;
34
+ }
35
+ const roleNames = String(newRole).split(',').map((role)=>role.trim());
36
+ if (!roleNames.includes('owner')) {
37
+ return undefined;
38
+ }
39
+ throw new APIError('BAD_REQUEST', {
40
+ code: 'SUSPENDED_MEMBER_CANNOT_BE_OWNER',
41
+ message: 'A suspended member cannot be made an owner. Unsuspend them first.'
42
+ });
43
+ };
44
+ }
45
+ export default createBeforeUpdateMemberRoleHook;