@lowdefy/api 6.0.0 → 7.0.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 (208) 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 +10 -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/getCurrentEnvironment.js +27 -0
  10. package/dist/context/isSameOriginRequest.js +85 -0
  11. package/dist/context/isWebSocketOriginAllowed.js +63 -0
  12. package/dist/context/normalizeInjectedCaller.js +58 -0
  13. package/dist/context/parseRequestBody.js +32 -0
  14. package/dist/context/readMemberships.js +71 -0
  15. package/dist/context/resolveAuthentication.js +758 -0
  16. package/dist/context/resolveStrategyCaller.js +7 -3
  17. package/dist/csp/addNonceToElements.js +23 -0
  18. package/dist/csp/createContentSecurityPolicy.js +45 -0
  19. package/dist/csp/getWebSocketSources.js +36 -0
  20. package/dist/email/renderAuthEmail.js +99 -0
  21. package/dist/index.js +22 -5
  22. package/dist/response/buildEndpointResult.js +3 -1
  23. package/dist/response/createWireProjection.js +88 -0
  24. package/dist/response/formatErrorForAgent.js +35 -0
  25. package/dist/response/normalizeErrorSources.js +10 -13
  26. package/dist/response/redactErrorResponse.js +42 -8
  27. package/dist/response/redactResponse.js +17 -10
  28. package/dist/routes/agent/authorizeAgent.js +17 -5
  29. package/dist/routes/agent/callAgent.js +12 -2
  30. package/dist/routes/agent/collectChatFiles.js +39 -0
  31. package/dist/routes/agent/prepareAgent.js +29 -4
  32. package/dist/routes/auth/buildAdminPlugin.js +33 -0
  33. package/dist/routes/auth/buildCaptchaPlugin.js +61 -0
  34. package/dist/routes/auth/buildMcpTokenPlugin.js +77 -0
  35. package/dist/routes/auth/buildOauthPostLogin.js +73 -0
  36. package/dist/routes/auth/buildPhoneNumberPlugin.js +57 -0
  37. package/dist/routes/auth/buildProviders.js +61 -0
  38. package/dist/routes/auth/createAsMetadataHandler.js +27 -0
  39. package/dist/routes/auth/createAuthLogger.js +31 -0
  40. package/dist/routes/auth/createMcpAccessTokenClaims.js +52 -0
  41. package/dist/routes/auth/createOnAPIError.js +41 -0
  42. package/dist/routes/auth/createSendEmail.js +54 -0
  43. package/dist/routes/auth/ensureMcpTokenIndexes.js +48 -0
  44. package/dist/routes/auth/getAuthEnforcement.js +41 -0
  45. package/dist/routes/auth/getBetterAuth.js +107 -0
  46. package/dist/routes/auth/getBetterAuthConfig.js +767 -0
  47. package/dist/routes/auth/handleAuthRequest.js +43 -0
  48. package/dist/routes/auth/hooks/authHookPoints.js +204 -0
  49. package/dist/routes/auth/hooks/buildEngineHooks.js +68 -0
  50. package/dist/routes/auth/hooks/buildHooks.js +112 -0
  51. package/dist/routes/auth/{callbacks/addUserFieldsToSession.js → hooks/composeAfterSlot.js} +11 -13
  52. package/dist/routes/auth/hooks/composeBeforeSlot.js +41 -0
  53. package/dist/routes/auth/hooks/createHookDispatch.js +59 -0
  54. package/dist/routes/auth/hooks/createUserAfterHook.js +36 -0
  55. package/dist/routes/auth/hooks/createUserBeforeHook.js +50 -0
  56. package/dist/routes/auth/hooks/findHookUser.js +27 -0
  57. package/dist/routes/auth/modelNames.js +30 -0
  58. package/dist/routes/auth/organizations/OrganizationKeyError.js +28 -0
  59. package/dist/routes/auth/organizations/authorizeRole.js +27 -0
  60. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +178 -0
  61. package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +57 -0
  62. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +120 -0
  63. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +403 -0
  64. package/dist/routes/auth/organizations/createAdmissionGateHook.js +50 -0
  65. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +90 -0
  66. package/dist/routes/auth/organizations/createAutoJoinHook.js +68 -0
  67. package/dist/routes/auth/organizations/createEmailSendGate.js +59 -0
  68. package/dist/routes/auth/organizations/createExpiredInvitationGate.js +76 -0
  69. package/dist/routes/auth/organizations/ensureAuthIndexes.js +122 -0
  70. package/dist/routes/auth/organizations/ensureOrganization.js +132 -0
  71. package/dist/routes/auth/organizations/findPendingInvitation.js +43 -0
  72. package/dist/routes/auth/organizations/getHookRequestHeaders.js +24 -0
  73. package/dist/routes/auth/organizations/getOrganizationBinding.js +65 -0
  74. package/dist/routes/auth/organizations/isEmailAdmitted.js +89 -0
  75. package/dist/routes/auth/organizations/organizationAccessControl.js +94 -0
  76. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +62 -0
  77. package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +145 -0
  78. package/dist/routes/auth/requestHooks/buildRequestHooks.js +288 -0
  79. package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +43 -0
  80. package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +59 -0
  81. package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +47 -0
  82. package/dist/routes/auth/requestHooks/redirectToChallenge.js +79 -0
  83. package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +31 -0
  84. package/dist/routes/auth/resolveCookiePrefix.js +30 -0
  85. package/dist/routes/auth/sanitizeSessionResponse.js +27 -0
  86. package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
  87. package/dist/routes/connections/checkUnwalledReach.js +37 -0
  88. package/dist/routes/connections/getConnectionConfig.js +6 -1
  89. package/dist/routes/connections/resolveTenantPreflight.js +226 -0
  90. package/dist/routes/connections/resolveUnwalledReach.js +144 -0
  91. package/dist/routes/endpoints/acceptDetachedEndpoint.js +50 -0
  92. package/dist/routes/endpoints/authorizeApiEndpoint.js +13 -4
  93. package/dist/routes/endpoints/callEndpoint.js +23 -7
  94. package/dist/routes/endpoints/control/controlFor.js +4 -7
  95. package/dist/routes/endpoints/control/controlIf.js +4 -8
  96. package/dist/routes/endpoints/control/controlLog.js +6 -14
  97. package/dist/routes/endpoints/control/controlParallelFor.js +65 -29
  98. package/dist/routes/endpoints/control/controlReject.js +36 -16
  99. package/dist/routes/endpoints/control/controlReturn.js +32 -9
  100. package/dist/routes/endpoints/control/controlSetState.js +4 -8
  101. package/dist/routes/endpoints/control/controlSwitch.js +4 -8
  102. package/dist/routes/endpoints/control/controlThrow.js +20 -21
  103. package/dist/routes/endpoints/control/controlTry.js +30 -11
  104. package/dist/routes/endpoints/control/controlWhile.js +55 -0
  105. package/dist/routes/endpoints/control/handleControl.js +3 -1
  106. package/dist/routes/endpoints/createWebhookAnswer.js +78 -0
  107. package/dist/routes/endpoints/evaluateRoutineOperators.js +27 -0
  108. package/dist/routes/endpoints/forwardScheduledEndpoint.js +21 -15
  109. package/dist/routes/endpoints/getEndpointConfig.js +18 -8
  110. package/dist/routes/endpoints/getEnvironmentSchedules.js +5 -7
  111. package/dist/routes/endpoints/getSchemaValidator.js +39 -0
  112. package/dist/routes/endpoints/handleAgentCall.js +25 -9
  113. package/dist/routes/endpoints/handleAuthStep.js +214 -0
  114. package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
  115. package/dist/routes/endpoints/handleEndpointCall.js +46 -12
  116. package/dist/routes/endpoints/handleRenderNotification.js +29 -12
  117. package/dist/routes/endpoints/handleRequest.js +13 -6
  118. package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
  119. package/dist/routes/endpoints/handleValidateSchema.js +22 -22
  120. package/dist/routes/endpoints/invokeEndpoint.js +27 -3
  121. package/dist/routes/endpoints/operatorScope.js +28 -0
  122. package/dist/routes/{auth/events/createEventPlugins.js → endpoints/parseWebhookBody.js} +10 -6
  123. package/dist/routes/endpoints/resolveCallBinding.js +91 -0
  124. package/dist/routes/endpoints/resolveCronEnvironment.js +7 -6
  125. package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
  126. package/dist/routes/endpoints/runDetachedEndpoint.js +64 -18
  127. package/dist/routes/endpoints/runRoutine.js +64 -5
  128. package/dist/routes/endpoints/runScheduledEndpoint.js +19 -11
  129. package/dist/routes/endpoints/runWebhookEndpoint.js +70 -23
  130. package/dist/routes/endpoints/runWebhookVerify.js +129 -0
  131. package/dist/routes/endpoints/scheduleBackground.js +10 -0
  132. package/dist/routes/endpoints/test/runTest.js +48 -11
  133. package/dist/routes/endpoints/validatePayload.js +144 -0
  134. package/dist/routes/log/logClientError.js +7 -4
  135. package/dist/routes/mcp/createMcpServer.js +143 -64
  136. package/dist/routes/mcp/getMcpJwks.js +93 -0
  137. package/dist/routes/mcp/getMcpResourceBinding.js +41 -0
  138. package/dist/routes/mcp/getMcpUri.js +69 -0
  139. package/dist/routes/mcp/oauthResourceLifecycle.js +122 -0
  140. package/dist/routes/mcp/runAfterToolCall.js +50 -0
  141. package/dist/routes/notifications/resolveNotificationLinks.js +39 -11
  142. package/dist/routes/page/dynamic/checkDynamicContent.js +81 -0
  143. package/dist/routes/page/dynamic/checkLiteralContent.js +242 -0
  144. package/dist/routes/page/dynamic/createContentError.js +34 -0
  145. package/dist/routes/page/dynamic/flagIconsOutsidePage.js +39 -0
  146. package/dist/routes/page/dynamic/flagTypesOutsidePage.js +44 -0
  147. package/dist/routes/page/dynamic/getPropertiesSchemaErrors.js +35 -0
  148. package/dist/routes/page/dynamic/loadDynamicArtifacts.js +52 -0
  149. package/dist/routes/page/dynamic/policy/checkAction.js +204 -0
  150. package/dist/routes/page/dynamic/policy/checkEvents.js +163 -0
  151. package/dist/routes/page/dynamic/policy/checkPolicy.js +313 -0
  152. package/dist/routes/page/dynamic/policy/checkValue.js +214 -0
  153. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +117 -0
  154. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +54 -0
  155. package/dist/routes/page/dynamic/policy/findSerializerKeys.js +50 -0
  156. package/dist/routes/page/dynamic/policy/isAllowedUrl.js +53 -0
  157. package/dist/routes/{auth/createAdapter.js → page/dynamic/policy/isUnderState.js} +5 -9
  158. package/dist/routes/page/dynamic/policy/normalizeUrlText.js +25 -0
  159. package/dist/routes/page/dynamic/resolveDynamicContent.js +89 -37
  160. package/dist/routes/page/dynamic/unescapeOperators.js +21 -4
  161. package/dist/routes/page/dynamic/validateFragment.js +17 -58
  162. package/dist/routes/page/getPageConfig.js +76 -6
  163. package/dist/routes/request/authorizeRequest.js +21 -6
  164. package/dist/routes/request/callRequest.js +21 -3
  165. package/dist/routes/request/callRequestResolver.js +55 -6
  166. package/dist/routes/request/checkConnectionRead.js +1 -1
  167. package/dist/routes/request/checkConnectionWrite.js +1 -1
  168. package/dist/routes/request/createWalledResolver.js +75 -0
  169. package/dist/routes/request/evaluateOperators.js +8 -12
  170. package/dist/routes/request/getRequestConfig.js +19 -3
  171. package/dist/routes/request/maskCredentialProperties.js +34 -0
  172. package/dist/routes/request/resolveTenancy.js +223 -0
  173. package/dist/routes/request/validateSchemas.js +7 -6
  174. package/dist/routes/{auth/callbacks/createCallbackPlugins.js → rootConfig/getAppEvents.js} +7 -6
  175. package/dist/routes/rootConfig/getHomeAndMenus.js +23 -16
  176. package/dist/routes/{auth/events/createSessionEvent.js → rootConfig/getPagePaths.js} +16 -18
  177. package/dist/routes/rootConfig/getRootConfig.js +9 -3
  178. package/dist/routes/rootConfig/menus/filterMenuList.js +5 -2
  179. package/dist/routes/websocket/authorizeWebsocket.js +19 -4
  180. package/dist/routes/websocket/createChannelRegistry.js +39 -14
  181. package/dist/routes/websocket/createWebSocketConnection.js +162 -28
  182. package/dist/routes/websocket/getCallerFingerprint.js +31 -0
  183. package/dist/routes/websocket/prepareChannel.js +29 -1
  184. package/dist/routes/websocket/resolveWebsocketCaller.js +40 -0
  185. package/dist/test/testContext.js +16 -11
  186. package/package.json +28 -12
  187. package/dist/context/createAuthorize.js +0 -45
  188. package/dist/response/omitErrorProps.js +0 -51
  189. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +0 -30
  190. package/dist/routes/auth/callbacks/createCallbacks.js +0 -46
  191. package/dist/routes/auth/callbacks/createJWTCallback.js +0 -77
  192. package/dist/routes/auth/callbacks/createRedirectCallback.js +0 -41
  193. package/dist/routes/auth/callbacks/createSessionCallback.js +0 -81
  194. package/dist/routes/auth/callbacks/createSignInCallback.js +0 -40
  195. package/dist/routes/auth/callbacks/validateSessionRoles.js +0 -33
  196. package/dist/routes/auth/createLogger.js +0 -35
  197. package/dist/routes/auth/createPrefixedCookies.js +0 -52
  198. package/dist/routes/auth/createProviders.js +0 -25
  199. package/dist/routes/auth/events/createCreateUserEvent.js +0 -41
  200. package/dist/routes/auth/events/createEvents.js +0 -56
  201. package/dist/routes/auth/events/createLinkAccountEvent.js +0 -43
  202. package/dist/routes/auth/events/createSignInEvent.js +0 -46
  203. package/dist/routes/auth/events/createSignOutEvent.js +0 -43
  204. package/dist/routes/auth/events/createUpdateUserEvent.js +0 -41
  205. package/dist/routes/auth/getAuthConfig.js +0 -86
  206. package/dist/routes/auth/resolveCookies.js +0 -37
  207. package/dist/routes/log/formatValidationError.js +0 -31
  208. /package/dist/{routes/notifications → email}/resolveThemeLogo.js +0 -0
@@ -0,0 +1,76 @@
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, getSessionFromCtx } from 'better-auth/api';
16
+ import { type } from '@lowdefy/helpers';
17
+ const NO_LONGER_ACCEPTABLE_STATUSES = [
18
+ 'canceled',
19
+ 'rejected'
20
+ ];
21
+ function isNoLongerAcceptable(invitation) {
22
+ if (NO_LONGER_ACCEPTABLE_STATUSES.includes(invitation.status)) {
23
+ return true;
24
+ }
25
+ // Strictly before now, the same boundary as the accept route's own check.
26
+ return invitation.status === 'pending' && new Date(invitation.expiresAt) < new Date();
27
+ }
28
+ // The engine-tier request hooks.before on /organization/accept-invitation.
29
+ // BetterAuth answers an expired, cancelled and unknown invitation alike -
30
+ // INVITATION_NOT_FOUND, "Invitation not found" - which an invitee opening an
31
+ // old link reads as a broken link. When the invitation exists but can no
32
+ // longer be accepted, this answers INVITATION_EXPIRED instead, telling them to
33
+ // ask for a new one. A cancelled (or rejected) invitation reads as expired: the
34
+ // invitee's next step is the same, and why the inviter withdrew it is not
35
+ // theirs to know. An unknown id and an accepted invitation fall through to
36
+ // BetterAuth's own answer. Expiry is checked before the recipient, as
37
+ // BetterAuth itself does, so holding the id - the invitee's credential - is the
38
+ // only way to learn it expired. This hook runs before the route's own session
39
+ // check, so it answers signed-in callers only: a signed-out caller gets the
40
+ // route's 401 whether the id exists or not, and learns nothing about it.
41
+ //
42
+ // A bare handler: the request-hook assembler matches the path and owns the
43
+ // createAuthMiddleware wrapper.
44
+ function createExpiredInvitationGate({ getAuth }) {
45
+ return async function expiredInvitationGate(ctx) {
46
+ const invitationId = ctx.body?.invitationId;
47
+ // A missing id is the route's own validation error - let it answer.
48
+ if (!type.isString(invitationId)) {
49
+ return undefined;
50
+ }
51
+ // getSessionFromCtx memoizes on ctx.context, so the route's own session
52
+ // check reads the same session without a second lookup.
53
+ const session = await getSessionFromCtx(ctx);
54
+ if (type.isNone(session?.user)) {
55
+ return undefined;
56
+ }
57
+ const { adapter } = await getAuth().$context;
58
+ const invitation = await adapter.findOne({
59
+ model: 'invitation',
60
+ where: [
61
+ {
62
+ field: 'id',
63
+ value: invitationId
64
+ }
65
+ ]
66
+ });
67
+ if (type.isNone(invitation) || !isNoLongerAcceptable(invitation)) {
68
+ return undefined;
69
+ }
70
+ throw new APIError('BAD_REQUEST', {
71
+ code: 'INVITATION_EXPIRED',
72
+ message: 'This invitation has expired. Ask the person who invited you to send a new one.'
73
+ });
74
+ };
75
+ }
76
+ export default createExpiredInvitationGate;
@@ -0,0 +1,122 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { ConfigError, ServiceError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ // The auth invariants the engine's own writes rely on but BetterAuth only
18
+ // checks by reading first: one organization per slug (the pinned ensure and
19
+ // the tenant signup mint find-or-create by slug) and one member row per
20
+ // (user, organization) (the mint and the open-signup joins check for the row
21
+ // before writing it). Two concurrent writers can both pass the read; a unique
22
+ // index turns the second write into an error the caller recovers from by
23
+ // reading the winner's row. The mint refuses to run without them
24
+ // (createActiveOrgPolicyHook), so a race can never leave a user owning two
25
+ // organizations or holding two owner rows.
26
+ //
27
+ // The indexes are created at startup, by the running server against the
28
+ // database it serves, rather than by a build or CLI step: the build has no
29
+ // database access, a CLI step is one more thing each environment has to
30
+ // remember, and both would miss a database swapped under a running app. The
31
+ // adapter reads the existing indexes first and only creates missing ones.
32
+ //
33
+ // The mint awaits the same call. Once the indexes are in place the result is
34
+ // kept for the life of the process, so a mint costs no database read. When an
35
+ // attempt fails - duplicate rows block the index build, the database user may
36
+ // not create indexes, the database is unreachable - the failure is logged once
37
+ // and kept for a cool-down: every mint in that window is refused at once,
38
+ // without touching the database, so repeated sign-ins can not trigger repeated
39
+ // index builds. The first mint after the cool-down retries (read, and create
40
+ // what is still missing), so fixing the data or creating the index by hand
41
+ // recovers without a restart.
42
+ //
43
+ // The adapter owns the mapping to physical collections and fields, so this is
44
+ // an adapter capability (adapter.options.ensureUniqueIndexes, implemented by
45
+ // MongoDBAuthAdapter). An adapter without it is warned about once - its
46
+ // database must enforce the same uniqueness some other way.
47
+ const uniqueIndexes = [
48
+ {
49
+ model: 'organization',
50
+ fields: [
51
+ 'slug'
52
+ ]
53
+ },
54
+ {
55
+ model: 'member',
56
+ fields: [
57
+ 'userId',
58
+ 'organizationId'
59
+ ]
60
+ }
61
+ ];
62
+ const coolDownMs = 30000;
63
+ const stateByAuth = new WeakMap();
64
+ async function attempt({ auth, logger }) {
65
+ const { adapter } = await auth.$context;
66
+ const ensureUniqueIndexes = adapter.options?.ensureUniqueIndexes;
67
+ if (!type.isFunction(ensureUniqueIndexes)) {
68
+ logger.warn(`Auth database adapter "${adapter.id}" can not create indexes. Make sure its database enforces a unique organization slug and one member row per user and organization, or two concurrent sign-ins can create duplicate organizations or owner rows.`);
69
+ return;
70
+ }
71
+ try {
72
+ await ensureUniqueIndexes({
73
+ indexes: uniqueIndexes
74
+ });
75
+ } catch (error) {
76
+ let failure;
77
+ if (ServiceError.isServiceError(error)) {
78
+ // An unreachable database is an outage, not a missing index.
79
+ failure = new ServiceError(undefined, {
80
+ cause: error,
81
+ service: 'Auth database'
82
+ });
83
+ } else {
84
+ failure = new ConfigError(`The auth database is missing a unique index Lowdefy needs to keep organizations and memberships consistent, and it could not be created: ${error.message} Remove duplicate rows, or create the index with a database user that is allowed to. New organizations are refused until then; the server retries every ${coolDownMs / 1000} seconds while sign-ins need one.`, {
85
+ cause: error
86
+ });
87
+ }
88
+ logger.error({
89
+ err: failure
90
+ }, failure.message);
91
+ throw failure;
92
+ }
93
+ }
94
+ function ensureAuthIndexes({ auth, logger }) {
95
+ const state = stateByAuth.get(auth);
96
+ if (state?.status === 'ready') {
97
+ return Promise.resolve();
98
+ }
99
+ if (state?.status === 'pending') {
100
+ return state.promise;
101
+ }
102
+ if (state?.status === 'failed' && Date.now() - state.failedAt < coolDownMs) {
103
+ return Promise.reject(state.error);
104
+ }
105
+ const next = {
106
+ status: 'pending'
107
+ };
108
+ next.promise = attempt({
109
+ auth,
110
+ logger
111
+ }).then(()=>{
112
+ next.status = 'ready';
113
+ }, (error)=>{
114
+ next.status = 'failed';
115
+ next.failedAt = Date.now();
116
+ next.error = error;
117
+ throw error;
118
+ });
119
+ stateByAuth.set(auth, next);
120
+ return next.promise;
121
+ }
122
+ export default ensureAuthIndexes;
@@ -0,0 +1,132 @@
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 { setPinnedOrganization } from './getOrganizationBinding.js';
16
+ import OrganizationKeyError from './OrganizationKeyError.js';
17
+ // Ensure-by-slug seeding for the pinned organization: no org with the
18
+ // configured slug means create it, otherwise do nothing. Idempotent and
19
+ // self-bootstrapping - a fresh environment needs no manual seed step.
20
+ // The organization row is written through the adapter, not the plugin's
21
+ // createOrganization endpoint: at better-auth@1.7.0 that endpoint requires
22
+ // a creator user (it mints an owner member row), and a seeded org has no
23
+ // creator - membership is granted by invite. Racing instances are
24
+ // backstopped by the unique slug index.
25
+ //
26
+ // Organization id format is policy-dependent: under pinned the id is the
27
+ // configured slug, so the one configured value keys every read. Tenant
28
+ // organizations are minted lazily per user with generated slugs and keep
29
+ // generated ids.
30
+ const ensuredByAuth = new WeakMap();
31
+ async function findOrganizationBySlug({ adapter, slug }) {
32
+ return adapter.findOne({
33
+ model: 'organization',
34
+ where: [
35
+ {
36
+ field: 'slug',
37
+ value: slug
38
+ }
39
+ ]
40
+ });
41
+ }
42
+ // The ensure is find-or-create by slug and only the create path sets an id, so
43
+ // a row that predates slug ids comes back keyed by a generated uuid and cannot
44
+ // be repaired from here - MongoDB _id is immutable. Left to run,
45
+ // applyPinnedPolicy writes that stale id to session.activeOrganizationId at
46
+ // every session.create and the pinned active-organization invariant refuses the
47
+ // session it just described, so every caller in the deployment resolves
48
+ // unauthenticated forever with the app's own sign-in page as the only symptom.
49
+ // Failing here trades that for a message that names the re-key.
50
+ function assertKeyedBySlug({ organization, slug }) {
51
+ if (organization.id !== slug) {
52
+ throw new OrganizationKeyError(`The organization with slug "${slug}" is keyed by id "${organization.id}", not by its slug. ` + 'Under the "pinned" organizations policy the organization id must equal its slug. Re-key the ' + 'organization row and every member.organizationId / invitation.organizationId that references it, ' + 'and delete the user-sessions collection (session.activeOrganizationId is a stored field holding ' + 'the old id).');
53
+ }
54
+ }
55
+ async function ensure({ auth, slug }) {
56
+ const { adapter } = await auth.$context;
57
+ const existing = await findOrganizationBySlug({
58
+ adapter,
59
+ slug
60
+ });
61
+ if (existing) {
62
+ assertKeyedBySlug({
63
+ organization: existing,
64
+ slug
65
+ });
66
+ return existing;
67
+ }
68
+ try {
69
+ return await adapter.create({
70
+ model: 'organization',
71
+ data: {
72
+ // The pinned organization's id is its slug, so every consumer that
73
+ // knows the configured slug knows the id: the module's read $match,
74
+ // each step's organizationId and the bootstrap invitation document all
75
+ // key off it with no slug-to-id lookup at request time.
76
+ id: slug,
77
+ name: slug,
78
+ slug,
79
+ createdAt: new Date()
80
+ },
81
+ // Without this the adapter factory drops the id with a warning and the
82
+ // configured generateId mints a uuid in its place. The id survives as a
83
+ // slug because that generateId is function-form: the factory only holds
84
+ // an explicit id to the uuid format when generateId is the string 'uuid'.
85
+ forceAllowId: true
86
+ });
87
+ } catch (error) {
88
+ // A racing instance created the org between the find and the create -
89
+ // the unique slug index rejected this write, so read the winner's row.
90
+ const created = await findOrganizationBySlug({
91
+ adapter,
92
+ slug
93
+ });
94
+ if (created) {
95
+ assertKeyedBySlug({
96
+ organization: created,
97
+ slug
98
+ });
99
+ return created;
100
+ }
101
+ throw error;
102
+ }
103
+ }
104
+ function ensureOrganization({ auth, slug }) {
105
+ let bySlug = ensuredByAuth.get(auth);
106
+ if (!bySlug) {
107
+ bySlug = new Map();
108
+ ensuredByAuth.set(auth, bySlug);
109
+ }
110
+ if (!bySlug.has(slug)) {
111
+ const promise = ensure({
112
+ auth,
113
+ slug
114
+ }).then(async (organization)=>{
115
+ // Retain the ensured row for synchronous request-time reads - the
116
+ // _organization operator and step organizationId defaulting.
117
+ setPinnedOrganization({
118
+ auth,
119
+ organization,
120
+ slug
121
+ });
122
+ return organization;
123
+ }).catch((error)=>{
124
+ // Do not memoize a failure - the next fire retries the ensure.
125
+ bySlug.delete(slug);
126
+ throw error;
127
+ });
128
+ bySlug.set(slug, promise);
129
+ }
130
+ return bySlug.get(slug);
131
+ }
132
+ export default ensureOrganization;
@@ -0,0 +1,43 @@
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
+ // Reads the first pending, unexpired invitation for an email - mirroring the
17
+ // organization plugin's own findPendingInvitation lookup (lowercased email,
18
+ // status "pending", expiry filtered in code). organizationId narrows the
19
+ // lookup to one org for the pinned policy; the tenant policy matches any org.
20
+ async function findPendingInvitation({ adapter, email, organizationId }) {
21
+ const where = [
22
+ {
23
+ field: 'email',
24
+ value: email.toLowerCase()
25
+ },
26
+ {
27
+ field: 'status',
28
+ value: 'pending'
29
+ }
30
+ ];
31
+ if (!type.isNone(organizationId)) {
32
+ where.push({
33
+ field: 'organizationId',
34
+ value: organizationId
35
+ });
36
+ }
37
+ const invitations = await adapter.findMany({
38
+ model: 'invitation',
39
+ where
40
+ });
41
+ return invitations.find((invitation)=>new Date(invitation.expiresAt) > new Date()) ?? null;
42
+ }
43
+ export default findPendingInvitation;
@@ -0,0 +1,24 @@
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
+ */ // The engine's baseURL is dynamic (resolved per request from the request
16
+ // host), so a nested auth.api call made from inside a hook must carry the
17
+ // firing request as its source - a headerless direct call cannot resolve a
18
+ // base URL and BetterAuth rejects it. Database hooks receive the endpoint
19
+ // context when the write runs inside a request lifecycle; the headers come
20
+ // from there.
21
+ function getHookRequestHeaders(ctx) {
22
+ return ctx?.headers ?? ctx?.request?.headers ?? ctx?.context?.headers;
23
+ }
24
+ export default getHookRequestHeaders;
@@ -0,0 +1,65 @@
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 retains the deployment's organizations declaration and the
17
+ // ensured pinned organization per auth instance. Request and system contexts
18
+ // read the retained state synchronously so the _organization operator and
19
+ // the org-scoped admin steps can resolve the pinned org at evaluation time.
20
+ // The pinned row is retained by ensureOrganization when its ensure resolves
21
+ // (at startup, or on the first session fire when startup seeding failed) -
22
+ // the org id is minted at creation, so no build artifact can carry it.
23
+ const bindingByAuth = new WeakMap();
24
+ function registerOrganizationBinding({ auth, database = false, organizations }) {
25
+ bindingByAuth.set(auth, {
26
+ database,
27
+ policy: organizations.policy,
28
+ slug: organizations.org ?? null,
29
+ pinned: null
30
+ });
31
+ }
32
+ // The raw registered entry (policy, slug, database, pinned) - used by
33
+ // resolvePinnedOrganization to decide whether an ensure is needed.
34
+ function getRegisteredOrganization({ auth }) {
35
+ if (type.isNone(auth)) {
36
+ return null;
37
+ }
38
+ return bindingByAuth.get(auth) ?? null;
39
+ }
40
+ function setPinnedOrganization({ auth, organization, slug }) {
41
+ const binding = bindingByAuth.get(auth);
42
+ if (!binding || binding.policy !== 'pinned' || binding.slug !== slug) {
43
+ return;
44
+ }
45
+ binding.pinned = {
46
+ id: organization.id,
47
+ slug: organization.slug,
48
+ name: organization.name
49
+ };
50
+ }
51
+ function getOrganizationBinding({ auth }) {
52
+ if (type.isNone(auth)) {
53
+ return null;
54
+ }
55
+ const binding = bindingByAuth.get(auth);
56
+ if (type.isNone(binding)) {
57
+ return null;
58
+ }
59
+ return {
60
+ policy: binding.policy,
61
+ pinned: binding.pinned
62
+ };
63
+ }
64
+ export { getRegisteredOrganization, registerOrganizationBinding, setPinnedOrganization };
65
+ export default getOrganizationBinding;
@@ -0,0 +1,89 @@
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 ensureOrganization from './ensureOrganization.js';
17
+ import findPendingInvitation from './findPendingInvitation.js';
18
+ // The one admission predicate, shared by all three enforcement points: the
19
+ // session.create wall (which passes a userId), the user.create.before gate and
20
+ // the magic-link send gate (which pass an email, before any user exists).
21
+ //
22
+ // Admission is restrictive under invite-only (either policy). Open signup
23
+ // auto-joins under both policies, so the predicate short-circuits to true and
24
+ // leaves those flows untouched.
25
+ //
26
+ // An email is admitted when there is either a member row (keyed by the given
27
+ // userId, or by the user resolved from the email) or a pending, unexpired
28
+ // invitation for the email. Under pinned the scope is the pinned org; under
29
+ // tenant it is membership-anywhere or invitation-anywhere, since admission gates
30
+ // deployment-global account existence and there is no target org at signup time.
31
+ // The email is lowercased once at entry to match BetterAuth's lowercased-stored
32
+ // user.email and the org plugin's lowercased invitation storage, so no
33
+ // case-variant address is wrongly suppressed or wrongly admitted.
34
+ async function isEmailAdmitted({ email, userId, organizations, auth, adapter, internalAdapter }) {
35
+ if (organizations.signup !== 'invite-only') {
36
+ return true;
37
+ }
38
+ const pinned = organizations.policy === 'pinned';
39
+ const organization = pinned ? await ensureOrganization({
40
+ auth,
41
+ slug: organizations.org
42
+ }) : undefined;
43
+ const normalizedEmail = type.isString(email) ? email.toLowerCase() : undefined;
44
+ // The member row is keyed by user id. The wall holds the session userId; the
45
+ // create and send gates hold only an email, so resolve the existing user (if
46
+ // any) from it. Conversely the wall needs the email for the invitation lookup,
47
+ // so resolve it from the userId when the caller did not pass one.
48
+ let memberUserId = userId;
49
+ let invitationEmail = normalizedEmail;
50
+ if (type.isNone(memberUserId) && !type.isNone(normalizedEmail)) {
51
+ const found = await internalAdapter.findUserByEmail(normalizedEmail);
52
+ memberUserId = found?.user?.id;
53
+ }
54
+ if (type.isNone(invitationEmail) && !type.isNone(userId)) {
55
+ const user = await internalAdapter.findUserById(userId);
56
+ invitationEmail = user?.email;
57
+ }
58
+ if (!type.isNone(memberUserId)) {
59
+ const where = [
60
+ {
61
+ field: 'userId',
62
+ value: memberUserId
63
+ }
64
+ ];
65
+ if (pinned) {
66
+ where.push({
67
+ field: 'organizationId',
68
+ value: organization.id
69
+ });
70
+ }
71
+ const member = await adapter.findOne({
72
+ model: 'member',
73
+ where
74
+ });
75
+ if (member) {
76
+ return true;
77
+ }
78
+ }
79
+ if (type.isNone(invitationEmail)) {
80
+ return false;
81
+ }
82
+ const invitation = await findPendingInvitation({
83
+ adapter,
84
+ email: invitationEmail,
85
+ organizationId: pinned ? organization.id : undefined
86
+ });
87
+ return !type.isNone(invitation);
88
+ }
89
+ export default isEmailAdmitted;
@@ -0,0 +1,94 @@
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 { createAccessControl } from 'better-auth/plugins/access';
16
+ import { adminAc, defaultStatements, memberAc, ownerAc } from 'better-auth/plugins/organization/access';
17
+ // The actions the step floor asks for that BetterAuth's organization statements
18
+ // do not carry. Registered on the ORGANIZATION plugin's access control, not the
19
+ // admin plugin's: the floor asks the control that can express per-organization
20
+ // authority. The resource names are the admin design's, kept verbatim so its
21
+ // catalog table stays the contract.
22
+ const ADDED = {
23
+ member: [
24
+ 'list'
25
+ ],
26
+ user: [
27
+ 'ban',
28
+ 'delete',
29
+ 'set-attributes',
30
+ 'update',
31
+ // Credential recovery (Decision 3). TWO actions, not one shared
32
+ // manage-credentials: the two steps exist separately so an operator can
33
+ // address the incident they actually have - "I lost my authenticator" and
34
+ // "my security key was stolen" have different recovery - and collapsing them
35
+ // here would mean any deployment wanting per-passkey revocation must also
36
+ // grant TOTP reset, undoing the separation at the layer where it binds
37
+ // hardest. Distinct actions are also the escape hatch: a deployment
38
+ // registering a narrower role can grant member management without credential
39
+ // recovery.
40
+ 'reset-two-factor',
41
+ 'revoke-passkeys'
42
+ ],
43
+ session: [
44
+ 'revoke'
45
+ ]
46
+ };
47
+ const statements = {
48
+ ...defaultStatements,
49
+ member: [
50
+ ...defaultStatements.member,
51
+ ...ADDED.member
52
+ ],
53
+ user: [
54
+ ...ADDED.user
55
+ ],
56
+ session: [
57
+ ...ADDED.session
58
+ ]
59
+ };
60
+ const ac = createAccessControl(statements);
61
+ function grant(vendored) {
62
+ return {
63
+ ...vendored.statements,
64
+ member: [
65
+ ...vendored.statements.member ?? [],
66
+ ...ADDED.member
67
+ ],
68
+ user: [
69
+ ...ADDED.user
70
+ ],
71
+ session: [
72
+ ...ADDED.session
73
+ ]
74
+ };
75
+ }
76
+ // owner and admin currently differ only by organization: ["delete"], and member
77
+ // holds none of the added actions - so most of the map's distinctions are latent
78
+ // today. They go live the moment a narrower role is registered, with nothing to
79
+ // redesign: the statement set already names every action the floor asks about.
80
+ const roles = {
81
+ owner: ac.newRole(grant(ownerAc)),
82
+ admin: ac.newRole(grant(adminAc)),
83
+ // member keeps the vendored statements verbatim, including ac: ["read"], which
84
+ // is inert - dynamicAccessControl is off and the AC endpoints are unmounted.
85
+ member: ac.newRole({
86
+ ...memberAc.statements
87
+ })
88
+ };
89
+ export { ac, roles, statements };
90
+ export default {
91
+ ac,
92
+ roles,
93
+ statements
94
+ };