@lowdefy/api 7.1.0 → 7.3.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 (126) 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 +99 -31
  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 +172 -98
  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/isUserBanned.js +28 -0
  21. package/dist/routes/auth/mobile/buildBearerPlugin.js +45 -0
  22. package/dist/routes/auth/mobile/buildOneTimeTokenPlugin.js +50 -0
  23. package/dist/routes/auth/mobile/createCodeVerifierCheck.js +57 -0
  24. package/dist/routes/auth/mobile/createKnownDeviceHook.js +76 -0
  25. package/dist/routes/auth/mobile/createMobileAuthPageResponse.js +79 -0
  26. package/dist/routes/auth/mobile/createMobileSessionCreateHook.js +41 -0
  27. package/dist/routes/auth/mobile/createMobileSessionRefreshHook.js +40 -0
  28. package/dist/routes/auth/mobile/createMobileSignInCsrfToken.js +32 -0
  29. package/dist/routes/auth/mobile/createPhoneSession.js +59 -0
  30. package/dist/routes/auth/mobile/escapeHtml.js +26 -0
  31. package/dist/routes/auth/mobile/getCodeHolderIdentifier.js +20 -0
  32. package/dist/routes/auth/mobile/getKnownDeviceIdentifier.js +20 -0
  33. package/dist/routes/auth/mobile/getMobileSessionExpiry.js +18 -0
  34. package/dist/routes/auth/mobile/getMobileSignInReturnUrl.js +31 -0
  35. package/dist/routes/auth/mobile/getOneTimeTokenIdentifiers.js +26 -0
  36. package/dist/routes/auth/mobile/handleMobileSignIn.js +303 -0
  37. package/dist/routes/auth/mobile/handleMobileSignInCallback.js +30 -0
  38. package/dist/routes/auth/mobile/isNativeAuthRequest.js +33 -0
  39. package/dist/routes/auth/mobile/matchesCodeChallenge.js +29 -0
  40. package/dist/routes/auth/mobile/mintOneTimeToken.js +41 -0
  41. package/dist/routes/auth/mobile/readDeviceKeyHash.js +34 -0
  42. package/dist/routes/auth/mobile/readMobileSignInParams.js +90 -0
  43. package/dist/routes/auth/mobile/sha256Base64Url.js +22 -0
  44. package/dist/routes/auth/mobile/storeCodeChallenge.js +29 -0
  45. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +57 -11
  46. package/dist/routes/auth/organizations/checkInvitationContactLink.js +60 -0
  47. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +47 -12
  48. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +41 -189
  49. package/dist/routes/auth/organizations/createAdmissionGateHook.js +5 -5
  50. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +40 -16
  51. package/dist/routes/auth/organizations/createBeforeAcceptInvitationHook.js +35 -0
  52. package/dist/routes/auth/organizations/createBeforeCreateInvitationHook.js +62 -0
  53. package/dist/routes/auth/organizations/createBeforeUpdateMemberRoleHook.js +45 -0
  54. package/dist/routes/auth/organizations/createEmailSendGate.js +35 -7
  55. package/dist/routes/auth/organizations/createSuspendedMemberGate.js +146 -0
  56. package/dist/routes/auth/organizations/createSuspendedOrganizationsFilter.js +44 -0
  57. package/dist/routes/auth/organizations/ensureAuthIndexes.js +11 -10
  58. package/dist/routes/auth/organizations/getOrganizationBinding.js +4 -2
  59. package/dist/routes/auth/organizations/isActiveMember.js +26 -0
  60. package/dist/routes/auth/organizations/isEmailAdmitted.js +25 -14
  61. package/dist/routes/auth/organizations/memberRowsLimit.js +19 -0
  62. package/dist/routes/auth/organizations/mintOrganization.js +258 -0
  63. package/dist/routes/auth/organizations/organizationAccessControl.js +5 -1
  64. package/dist/routes/auth/organizations/provisionOrganization.js +117 -0
  65. package/dist/routes/auth/organizations/readSuspendedOrganizationIds.js +36 -0
  66. package/dist/routes/auth/requestHooks/buildRequestHooks.js +78 -2
  67. package/dist/routes/auth/requestHooks/createEmailCodeHolderGate.js +58 -0
  68. package/dist/routes/auth/requestHooks/createEmailSendLimit.js +116 -0
  69. package/dist/routes/auth/requestHooks/createSignInRefusedRedirectHook.js +75 -0
  70. package/dist/routes/auth/requestHooks/holdEmailCode.js +80 -0
  71. package/dist/routes/auth/requestHooks/reserveSendSlot.js +70 -0
  72. package/dist/routes/auth/runReportingFaults.js +32 -0
  73. package/dist/routes/connections/resolveUnwalledReach.js +14 -16
  74. package/dist/routes/endpoints/callEndpoint.js +6 -3
  75. package/dist/routes/endpoints/control/controlFor.js +9 -6
  76. package/dist/routes/endpoints/control/controlIf.js +8 -3
  77. package/dist/routes/endpoints/control/controlLog.js +3 -1
  78. package/dist/routes/endpoints/control/controlParallelFor.js +9 -6
  79. package/dist/routes/endpoints/control/controlReturn.js +3 -2
  80. package/dist/routes/endpoints/control/controlSetState.js +1 -1
  81. package/dist/routes/endpoints/control/controlSwitch.js +6 -3
  82. package/dist/routes/endpoints/control/controlWhile.js +6 -3
  83. package/dist/routes/endpoints/createLinkAnswer.js +76 -0
  84. package/dist/routes/endpoints/dispatchDetached.js +38 -0
  85. package/dist/routes/endpoints/forwardScheduledEndpoint.js +32 -11
  86. package/dist/routes/endpoints/handleAgentCall.js +1 -1
  87. package/dist/routes/endpoints/handleAuthStep.js +19 -4
  88. package/dist/routes/endpoints/handleEndpointCall.js +6 -4
  89. package/dist/routes/endpoints/handleRequest.js +3 -2
  90. package/dist/routes/endpoints/handleValidateDynamic.js +1 -1
  91. package/dist/routes/endpoints/matchLinkEndpoint.js +30 -0
  92. package/dist/routes/endpoints/runLinkEndpoint.js +148 -0
  93. package/dist/routes/endpoints/runRoutine.js +5 -5
  94. package/dist/routes/endpoints/scheduleBackground.js +13 -11
  95. package/dist/routes/endpoints/test/runTest.js +30 -11
  96. package/dist/routes/mcp/createMcpServer.js +2 -7
  97. package/dist/routes/mcp/runAfterToolCall.js +9 -3
  98. package/dist/routes/mobile/createAppleAppSiteAssociation.js +51 -0
  99. package/dist/routes/mobile/createAssetLinks.js +38 -0
  100. package/dist/routes/mobile/filterMobileMenus.js +31 -0
  101. package/dist/routes/mobile/getMobileAppEvents.js +23 -0
  102. package/dist/routes/mobile/getMobileRootConfig.js +109 -0
  103. package/dist/routes/mobile/getOpenablePageIds.js +21 -0
  104. package/dist/routes/page/dynamic/policy/checkAction.js +67 -2
  105. package/dist/routes/page/dynamic/policy/checkEvents.js +8 -2
  106. package/dist/routes/page/dynamic/policy/checkPolicy.js +86 -6
  107. package/dist/routes/page/dynamic/policy/checkValue.js +97 -6
  108. package/dist/routes/page/dynamic/policy/collectSchemaKinds.js +173 -0
  109. package/dist/routes/page/dynamic/policy/findDataRows.js +94 -0
  110. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +24 -12
  111. package/dist/routes/page/dynamic/policy/findHtmlUrls.js +64 -0
  112. package/dist/routes/page/dynamic/policy/overlapsStatePath.js +28 -0
  113. package/dist/routes/page/dynamic/resolveDynamicContent.js +23 -17
  114. package/dist/routes/page/getPageConfig.js +25 -1
  115. package/dist/routes/request/callRequestResolver.js +29 -36
  116. package/dist/routes/request/stampTypedError.js +37 -0
  117. package/dist/routes/request/summarisedError.js +62 -0
  118. package/dist/routes/request/wrapResolverError.js +61 -0
  119. package/dist/routes/websocket/checkWebsocketAccess.js +81 -0
  120. package/dist/routes/websocket/createChannelRegistry.js +62 -17
  121. package/dist/routes/websocket/createWebSocketConnection.js +59 -21
  122. package/dist/routes/websocket/prepareChannel.js +11 -0
  123. package/dist/test/createMemoryAuth.js +125 -0
  124. package/package.json +20 -22
  125. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +0 -117
  126. package/dist/routes/request/maskCredentialProperties.js +0 -34
@@ -14,9 +14,13 @@
14
14
  limitations under the License.
15
15
  */ import { organization } from 'better-auth/plugins';
16
16
  import createAfterAcceptInvitationHook from './createAfterAcceptInvitationHook.js';
17
+ import createBeforeAcceptInvitationHook from './createBeforeAcceptInvitationHook.js';
18
+ import createBeforeCreateInvitationHook from './createBeforeCreateInvitationHook.js';
19
+ import createBeforeUpdateMemberRoleHook from './createBeforeUpdateMemberRoleHook.js';
17
20
  import modelNames from '../modelNames.js';
18
21
  import { ac, roles } from './organizationAccessControl.js';
19
22
  const DEFAULT_MEMBERSHIP_LIMIT = 1000000;
23
+ const DEFAULT_INVITATION_LIMIT = 1000000;
20
24
  // Organizations are always on - the membership and boundary mechanism for every
21
25
  // app. member.role carries BetterAuth's org-authority tier and nothing else, so
22
26
  // the same three built-in roles - owner, admin, member - are registered under
@@ -42,7 +46,7 @@ const DEFAULT_MEMBERSHIP_LIMIT = 1000000;
42
46
  // creator-protection guards, which key on the member's role string. With app
43
47
  // roles out of that field and the fabricated acting member claiming "owner"
44
48
  // itself, there is nothing left to defend against.
45
- function buildOrganizationPlugin({ authConfig = {}, getAuth, sendInvitationEmail }) {
49
+ function buildOrganizationPlugin({ authConfig = {}, getAuth, logger, sendInvitationEmail }) {
46
50
  const options = {
47
51
  ac,
48
52
  roles,
@@ -70,20 +74,32 @@ function buildOrganizationPlugin({ authConfig = {}, getAuth, sendInvitationEmail
70
74
  // default page size of list-members and the user lookup behind
71
75
  // getFullOrganization.
72
76
  membershipLimit: Number.isFinite(authConfig.organizations?.membershipLimit) ? authConfig.organizations.membershipLimit : DEFAULT_MEMBERSHIP_LIMIT,
77
+ // BetterAuth's own cap of 100 open invitations is held open: its count
78
+ // never goes past the adapter's default page of 100 rows, so it cannot
79
+ // enforce a larger limit. createBeforeCreateInvitationHook enforces
80
+ // auth.organizations.invitationLimit instead.
81
+ invitationLimit: DEFAULT_INVITATION_LIMIT,
73
82
  schema: {
74
83
  organization: {
75
84
  modelName: modelNames.organization,
76
85
  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.
86
+ // Set while an engine mint has written the organization but not yet
87
+ // its owner's member row (mintOrganization). Only a marked
88
+ // organization is ever joined as owner by a mint, and only by the
89
+ // creator in mintCreatorId, so one that everyone has left is never
90
+ // handed back. Server-only: never accepted from a request body,
91
+ // never returned by an endpoint.
82
92
  mintPending: {
83
93
  type: 'boolean',
84
94
  required: false,
85
95
  input: false,
86
96
  returned: false
97
+ },
98
+ mintCreatorId: {
99
+ type: 'string',
100
+ required: false,
101
+ input: false,
102
+ returned: false
87
103
  }
88
104
  }
89
105
  },
@@ -122,6 +138,16 @@ function buildOrganizationPlugin({ authConfig = {}, getAuth, sendInvitationEmail
122
138
  type: 'string',
123
139
  required: false,
124
140
  input: false
141
+ },
142
+ // A suspended member keeps their row - roles, attributes and all, so
143
+ // the app's own queries still find them - but holds no membership:
144
+ // every check that admits a member reads it (isActiveMember). Written
145
+ // only by the SuspendMember and UnsuspendMember steps. Absent means
146
+ // not suspended, so rows written before it existed need no migration.
147
+ suspended: {
148
+ type: 'boolean',
149
+ required: false,
150
+ input: false
125
151
  }
126
152
  }
127
153
  },
@@ -132,9 +158,10 @@ function buildOrganizationPlugin({ authConfig = {}, getAuth, sendInvitationEmail
132
158
  // invitation winning per key. Invite-time member attributes ride the
133
159
  // invitation the same way - accepting copies them onto the minted
134
160
  // 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.
161
+ // from their first session. contactId rides it too, so an invitation
162
+ // can name the app record the invitee's login will point at before
163
+ // that person has ever signed in; accept sets it only on a login with
164
+ // no link (createBeforeAcceptInvitationHook).
138
165
  //
139
166
  // appRoles is declared without the input: false its member counterpart
140
167
  // carries. toZodSchema drops input: false fields when isClientSide is
@@ -168,8 +195,27 @@ function buildOrganizationPlugin({ authConfig = {}, getAuth, sendInvitationEmail
168
195
  },
169
196
  organizationHooks: {
170
197
  afterAcceptInvitation: createAfterAcceptInvitationHook({
171
- getAuth
172
- })
198
+ getAuth,
199
+ logger
200
+ }),
201
+ // Refuses an invitation naming a different contact than the login is
202
+ // linked to, before the member row is written: the link is set once.
203
+ beforeAcceptInvitation: createBeforeAcceptInvitationHook({
204
+ getAuth,
205
+ logger
206
+ }),
207
+ // Keeps a suspended member out of the owner tier, so the plugin's owner
208
+ // guards, which count every owner row, stay exact (SuspendMember).
209
+ beforeUpdateMemberRole: createBeforeUpdateMemberRoleHook(),
210
+ // Registered only when a limit is set: unset, the cap is the
211
+ // effectively open DEFAULT_INVITATION_LIMIT above, and every invite
212
+ // would pay for a count that can never refuse.
213
+ ...Number.isFinite(authConfig.organizations?.invitationLimit) ? {
214
+ beforeCreateInvitation: createBeforeCreateInvitationHook({
215
+ getAuth,
216
+ invitationLimit: authConfig.organizations.invitationLimit
217
+ })
218
+ } : {}
173
219
  },
174
220
  sendInvitationEmail
175
221
  };
@@ -0,0 +1,60 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { APIError } from 'better-auth/api';
16
+ import { type } from '@lowdefy/helpers';
17
+ // The one check of an invitation's contactId against the accepting login's
18
+ // link, shared by both ways an accept is answered: the route's
19
+ // beforeAcceptInvitation hook and the existing-member request hook. The link
20
+ // is an authorization input apps compare in author and access checks, so it
21
+ // is set once: an invitation naming a different contact than the login holds
22
+ // is refused before anything is written. Like the other accept gates
23
+ // (createExpiredInvitationGate) the refusal is a short message for the person
24
+ // accepting, with its own code and no ids; the login, the invitation and both
25
+ // contacts go to the server log, so whoever runs the app can find the case.
26
+ // How the link gets corrected is the app's concern. The link is read from the
27
+ // stored user row, since the session user may be a cookie-cached copy. Returns true when the accept should set the link - the
28
+ // invitation names a contact and the login has none.
29
+ async function checkInvitationContactLink({ adapter, invitation, logger, userId }) {
30
+ if (!type.isString(invitation.contactId)) {
31
+ return false;
32
+ }
33
+ const userRow = await adapter.findOne({
34
+ model: 'user',
35
+ where: [
36
+ {
37
+ field: 'id',
38
+ value: userId
39
+ }
40
+ ]
41
+ });
42
+ if (type.isNone(userRow.contactId)) {
43
+ return true;
44
+ }
45
+ if (userRow.contactId === invitation.contactId) {
46
+ return false;
47
+ }
48
+ logger.warn({
49
+ event: 'invitation_contact_link_mismatch',
50
+ userId,
51
+ invitationId: invitation.id,
52
+ linkedContactId: userRow.contactId,
53
+ invitationContactId: invitation.contactId
54
+ }, `Invitation "${invitation.id}" names contact "${invitation.contactId}", but login "${userId}" is linked to contact "${userRow.contactId}" - accept refused.`);
55
+ throw new APIError('BAD_REQUEST', {
56
+ code: 'CONTACT_LINK_MISMATCH',
57
+ message: 'This invitation can not be accepted by this account.'
58
+ });
59
+ }
60
+ export default checkInvitationContactLink;
@@ -15,6 +15,8 @@
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 checkInvitationContactLink from './checkInvitationContactLink.js';
19
+ import isActiveMember from './isActiveMember.js';
18
20
  // The engine-tier request hooks.before on /organization/accept-invitation for a
19
21
  // caller who is already a member of the invitation's organization - someone
20
22
  // invited before they joined another way (the open-signup auto-join, an
@@ -23,8 +25,12 @@ import { type } from '@lowdefy/helpers';
23
25
  // then reverts the invitation and fails. Accepting is answered here instead:
24
26
  // the invitation is marked accepted and the membership is left exactly as it
25
27
  // 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
+ // attributes, profile) is applied - except the login's contact link, which is
29
+ // the login's, not the membership's, and is set once whatever the way in: a
30
+ // login with no link takes the invitation's, and an invitation naming a
31
+ // different contact is refused before the invitation is consumed, as the
32
+ // route's beforeAcceptInvitation hook refuses it. BetterAuth treats an
33
+ // invitation as the way to join, never as a role change: it refuses to invite an existing member,
28
34
  // and role changes go through update-member-role, which checks the caller's
29
35
  // authority at the time of the change. An invitation written before the
30
36
  // membership existed must not override what an administrator set since.
@@ -38,8 +44,10 @@ import { type } from '@lowdefy/helpers';
38
44
  //
39
45
  // Like the route, the session gets the organization as its active one only
40
46
  // when it has none (createAcceptActiveOrgGuardHook vetoes the route's switch
41
- // away from an existing active organization).
42
- function createAcceptExistingMemberHook() {
47
+ // away from an existing active organization). A suspended membership is left
48
+ // as it is too, so the organization is never made active: it admits nobody,
49
+ // and an org-less session at least keeps the caller awaiting an organization.
50
+ function createAcceptExistingMemberHook({ logger }) {
43
51
  return async function acceptExistingMemberHook(ctx) {
44
52
  const invitationId = ctx.body?.invitationId;
45
53
  if (!type.isString(invitationId)) {
@@ -78,6 +86,21 @@ function createAcceptExistingMemberHook() {
78
86
  if (type.isNone(member)) {
79
87
  return undefined;
80
88
  }
89
+ const setsContactLink = await checkInvitationContactLink({
90
+ adapter,
91
+ invitation,
92
+ logger,
93
+ userId: session.user.id
94
+ });
95
+ // The link is written before the invitation is consumed, so a failed write
96
+ // leaves the invitation pending and the accept can be retried. Any other
97
+ // accept of this invitation is by the same login, so it sets the same link.
98
+ let user = session.user;
99
+ if (setsContactLink) {
100
+ user = await internalAdapter.updateUser(session.user.id, {
101
+ contactId: invitation.contactId
102
+ });
103
+ }
81
104
  // The route's own compare-and-set: of two concurrent accepts only one
82
105
  // moves the invitation off pending, and the other falls through to the
83
106
  // route, which answers it as the used invitation it now is.
@@ -101,16 +124,28 @@ function createAcceptExistingMemberHook() {
101
124
  if (type.isNone(accepted)) {
102
125
  return undefined;
103
126
  }
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
127
+ const setsActiveOrganization = type.isNone(session.session.activeOrganizationId) && isActiveMember({
128
+ member
129
+ });
130
+ if (!setsContactLink && !setsActiveOrganization) {
131
+ return {
132
+ invitation: accepted,
133
+ member
134
+ };
135
+ }
136
+ let sessionRow = session.session;
137
+ if (setsActiveOrganization) {
138
+ sessionRow = await internalAdapter.updateSession(session.session.token, {
139
+ activeOrganizationId: invitation.organizationId
112
140
  });
113
141
  }
142
+ // Re-issued like the set-active-organization route does, so a session
143
+ // cookie cache does not keep serving the org-less session or the login
144
+ // without its link.
145
+ await setSessionCookie(ctx, {
146
+ session: sessionRow,
147
+ user
148
+ });
114
149
  return {
115
150
  invitation: accepted,
116
151
  member
@@ -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
  }