@lowdefy/api 6.1.0 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/dist/context/applySystemTrust.js +45 -0
  2. package/dist/context/createApiContext.js +18 -3
  3. package/dist/context/createAuthorizeOutcome.js +91 -0
  4. package/dist/context/createBoundSystemContext.js +33 -0
  5. package/dist/context/createEvaluateOperators.js +8 -3
  6. package/dist/context/createRequestSignal.js +47 -0
  7. package/dist/context/createSystemContext.js +80 -0
  8. package/dist/context/getCanonicalUrl.js +27 -0
  9. package/dist/context/isSameOriginRequest.js +85 -0
  10. package/dist/context/isWebSocketOriginAllowed.js +63 -0
  11. package/dist/context/normalizeInjectedCaller.js +58 -0
  12. package/dist/context/parseRequestBody.js +32 -0
  13. package/dist/context/readMemberships.js +71 -0
  14. package/dist/context/resolveAuthentication.js +758 -0
  15. package/dist/context/resolveStrategyCaller.js +7 -3
  16. package/dist/csp/addNonceToElements.js +23 -0
  17. package/dist/csp/createContentSecurityPolicy.js +45 -0
  18. package/dist/csp/getWebSocketSources.js +36 -0
  19. package/dist/email/renderAuthEmail.js +99 -0
  20. package/dist/index.js +21 -5
  21. package/dist/response/formatErrorForAgent.js +35 -0
  22. package/dist/response/redactResponse.js +8 -1
  23. package/dist/routes/agent/authorizeAgent.js +17 -5
  24. package/dist/routes/agent/callAgent.js +12 -2
  25. package/dist/routes/agent/collectChatFiles.js +39 -0
  26. package/dist/routes/agent/prepareAgent.js +23 -4
  27. package/dist/routes/auth/buildAdminPlugin.js +33 -0
  28. package/dist/routes/auth/buildCaptchaPlugin.js +61 -0
  29. package/dist/routes/auth/buildMcpTokenPlugin.js +77 -0
  30. package/dist/routes/auth/buildOauthPostLogin.js +73 -0
  31. package/dist/routes/auth/buildPhoneNumberPlugin.js +57 -0
  32. package/dist/routes/auth/buildProviders.js +61 -0
  33. package/dist/routes/auth/createAsMetadataHandler.js +27 -0
  34. package/dist/routes/auth/createAuthLogger.js +31 -0
  35. package/dist/routes/auth/createMcpAccessTokenClaims.js +52 -0
  36. package/dist/routes/auth/createOnAPIError.js +41 -0
  37. package/dist/routes/auth/createSendEmail.js +54 -0
  38. package/dist/routes/auth/ensureMcpTokenIndexes.js +48 -0
  39. package/dist/routes/auth/getAuthEnforcement.js +41 -0
  40. package/dist/routes/auth/getBetterAuth.js +107 -0
  41. package/dist/routes/auth/getBetterAuthConfig.js +767 -0
  42. package/dist/routes/auth/handleAuthRequest.js +43 -0
  43. package/dist/routes/auth/hooks/authHookPoints.js +204 -0
  44. package/dist/routes/auth/hooks/buildEngineHooks.js +68 -0
  45. package/dist/routes/auth/hooks/buildHooks.js +112 -0
  46. package/dist/routes/auth/{callbacks/addUserFieldsToSession.js → hooks/composeAfterSlot.js} +11 -13
  47. package/dist/routes/auth/hooks/composeBeforeSlot.js +41 -0
  48. package/dist/routes/auth/hooks/createHookDispatch.js +59 -0
  49. package/dist/routes/auth/hooks/createUserAfterHook.js +36 -0
  50. package/dist/routes/auth/hooks/createUserBeforeHook.js +50 -0
  51. package/dist/routes/auth/hooks/findHookUser.js +27 -0
  52. package/dist/routes/auth/modelNames.js +30 -0
  53. package/dist/routes/auth/organizations/OrganizationKeyError.js +28 -0
  54. package/dist/routes/auth/organizations/authorizeRole.js +27 -0
  55. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +178 -0
  56. package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +57 -0
  57. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +120 -0
  58. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +403 -0
  59. package/dist/routes/auth/organizations/createAdmissionGateHook.js +50 -0
  60. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +90 -0
  61. package/dist/routes/auth/organizations/createAutoJoinHook.js +68 -0
  62. package/dist/routes/auth/organizations/createEmailSendGate.js +59 -0
  63. package/dist/routes/auth/organizations/createExpiredInvitationGate.js +76 -0
  64. package/dist/routes/auth/organizations/ensureAuthIndexes.js +122 -0
  65. package/dist/routes/auth/organizations/ensureOrganization.js +132 -0
  66. package/dist/routes/auth/organizations/findPendingInvitation.js +43 -0
  67. package/dist/routes/auth/organizations/getHookRequestHeaders.js +24 -0
  68. package/dist/routes/auth/organizations/getOrganizationBinding.js +65 -0
  69. package/dist/routes/auth/organizations/isEmailAdmitted.js +89 -0
  70. package/dist/routes/auth/organizations/organizationAccessControl.js +94 -0
  71. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +62 -0
  72. package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +145 -0
  73. package/dist/routes/auth/requestHooks/buildRequestHooks.js +288 -0
  74. package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +43 -0
  75. package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +59 -0
  76. package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +47 -0
  77. package/dist/routes/auth/requestHooks/redirectToChallenge.js +79 -0
  78. package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +31 -0
  79. package/dist/routes/auth/resolveCookiePrefix.js +30 -0
  80. package/dist/routes/auth/sanitizeSessionResponse.js +27 -0
  81. package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
  82. package/dist/routes/connections/checkUnwalledReach.js +37 -0
  83. package/dist/routes/connections/getConnectionConfig.js +6 -1
  84. package/dist/routes/connections/resolveTenantPreflight.js +226 -0
  85. package/dist/routes/connections/resolveUnwalledReach.js +144 -0
  86. package/dist/routes/endpoints/acceptDetachedEndpoint.js +50 -0
  87. package/dist/routes/endpoints/authorizeApiEndpoint.js +13 -4
  88. package/dist/routes/endpoints/callEndpoint.js +22 -7
  89. package/dist/routes/endpoints/control/controlParallelFor.js +61 -22
  90. package/dist/routes/endpoints/control/controlReject.js +23 -1
  91. package/dist/routes/endpoints/control/controlReturn.js +29 -1
  92. package/dist/routes/endpoints/control/controlThrow.js +3 -2
  93. package/dist/routes/endpoints/control/controlTry.js +10 -1
  94. package/dist/routes/endpoints/control/controlWhile.js +55 -0
  95. package/dist/routes/endpoints/control/handleControl.js +3 -1
  96. package/dist/routes/endpoints/createWebhookAnswer.js +78 -0
  97. package/dist/routes/endpoints/evaluateRoutineOperators.js +2 -1
  98. package/dist/routes/endpoints/forwardScheduledEndpoint.js +3 -2
  99. package/dist/routes/endpoints/getEndpointConfig.js +18 -8
  100. package/dist/routes/endpoints/getSchemaValidator.js +39 -0
  101. package/dist/routes/endpoints/handleAgentCall.js +21 -2
  102. package/dist/routes/endpoints/handleAuthStep.js +214 -0
  103. package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
  104. package/dist/routes/endpoints/handleEndpointCall.js +43 -6
  105. package/dist/routes/endpoints/handleRenderNotification.js +14 -4
  106. package/dist/routes/endpoints/handleRequest.js +12 -1
  107. package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
  108. package/dist/routes/endpoints/handleValidateSchema.js +13 -15
  109. package/dist/routes/endpoints/invokeEndpoint.js +26 -3
  110. package/dist/routes/endpoints/operatorScope.js +2 -1
  111. package/dist/routes/{auth/callbacks/createCallbackPlugins.js → endpoints/parseWebhookBody.js} +10 -6
  112. package/dist/routes/endpoints/resolveCallBinding.js +91 -0
  113. package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
  114. package/dist/routes/endpoints/runDetachedEndpoint.js +63 -18
  115. package/dist/routes/endpoints/runRoutine.js +64 -5
  116. package/dist/routes/endpoints/runScheduledEndpoint.js +18 -11
  117. package/dist/routes/endpoints/runWebhookEndpoint.js +69 -23
  118. package/dist/routes/endpoints/runWebhookVerify.js +129 -0
  119. package/dist/routes/endpoints/scheduleBackground.js +10 -0
  120. package/dist/routes/endpoints/test/runTest.js +31 -9
  121. package/dist/routes/endpoints/validatePayload.js +144 -0
  122. package/dist/routes/log/logClientError.js +7 -4
  123. package/dist/routes/mcp/createMcpServer.js +143 -82
  124. package/dist/routes/mcp/getMcpJwks.js +93 -0
  125. package/dist/routes/mcp/getMcpResourceBinding.js +41 -0
  126. package/dist/routes/mcp/getMcpUri.js +69 -0
  127. package/dist/routes/mcp/oauthResourceLifecycle.js +122 -0
  128. package/dist/routes/mcp/runAfterToolCall.js +50 -0
  129. package/dist/routes/notifications/resolveNotificationLinks.js +39 -11
  130. package/dist/routes/page/dynamic/checkDynamicContent.js +81 -0
  131. package/dist/routes/page/dynamic/checkLiteralContent.js +242 -0
  132. package/dist/routes/page/dynamic/createContentError.js +34 -0
  133. package/dist/routes/page/dynamic/flagIconsOutsidePage.js +39 -0
  134. package/dist/routes/page/dynamic/flagTypesOutsidePage.js +44 -0
  135. package/dist/routes/page/dynamic/getPropertiesSchemaErrors.js +35 -0
  136. package/dist/routes/page/dynamic/loadDynamicArtifacts.js +52 -0
  137. package/dist/routes/page/dynamic/policy/checkAction.js +204 -0
  138. package/dist/routes/page/dynamic/policy/checkEvents.js +163 -0
  139. package/dist/routes/page/dynamic/policy/checkPolicy.js +313 -0
  140. package/dist/routes/page/dynamic/policy/checkValue.js +214 -0
  141. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +117 -0
  142. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +54 -0
  143. package/dist/routes/page/dynamic/policy/findSerializerKeys.js +50 -0
  144. package/dist/routes/page/dynamic/policy/isAllowedUrl.js +53 -0
  145. package/dist/routes/{auth/createAdapter.js → page/dynamic/policy/isUnderState.js} +5 -9
  146. package/dist/routes/page/dynamic/policy/normalizeUrlText.js +25 -0
  147. package/dist/routes/page/dynamic/resolveDynamicContent.js +89 -37
  148. package/dist/routes/page/dynamic/unescapeOperators.js +21 -4
  149. package/dist/routes/page/dynamic/validateFragment.js +17 -58
  150. package/dist/routes/page/getPageConfig.js +76 -6
  151. package/dist/routes/request/authorizeRequest.js +21 -6
  152. package/dist/routes/request/callRequest.js +22 -10
  153. package/dist/routes/request/callRequestResolver.js +49 -6
  154. package/dist/routes/request/checkConnectionRead.js +1 -1
  155. package/dist/routes/request/checkConnectionWrite.js +1 -1
  156. package/dist/routes/request/createWalledResolver.js +75 -0
  157. package/dist/routes/request/getRequestConfig.js +19 -3
  158. package/dist/routes/request/maskCredentialProperties.js +34 -0
  159. package/dist/routes/request/resolveTenancy.js +223 -0
  160. package/dist/routes/request/validateSchemas.js +7 -6
  161. package/dist/routes/{auth/events/createEventPlugins.js → rootConfig/getAppEvents.js} +7 -6
  162. package/dist/routes/rootConfig/getHomeAndMenus.js +23 -16
  163. package/dist/routes/{auth/events/createSessionEvent.js → rootConfig/getPagePaths.js} +16 -18
  164. package/dist/routes/rootConfig/getRootConfig.js +9 -3
  165. package/dist/routes/rootConfig/menus/filterMenuList.js +5 -2
  166. package/dist/routes/websocket/authorizeWebsocket.js +19 -4
  167. package/dist/routes/websocket/createChannelRegistry.js +20 -9
  168. package/dist/routes/websocket/createWebSocketConnection.js +150 -28
  169. package/dist/routes/websocket/getCallerFingerprint.js +31 -0
  170. package/dist/routes/websocket/prepareChannel.js +29 -1
  171. package/dist/routes/websocket/resolveWebsocketCaller.js +40 -0
  172. package/dist/test/testContext.js +13 -10
  173. package/package.json +28 -12
  174. package/dist/context/createAuthorize.js +0 -45
  175. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +0 -30
  176. package/dist/routes/auth/callbacks/createCallbacks.js +0 -46
  177. package/dist/routes/auth/callbacks/createJWTCallback.js +0 -77
  178. package/dist/routes/auth/callbacks/createRedirectCallback.js +0 -41
  179. package/dist/routes/auth/callbacks/createSessionCallback.js +0 -81
  180. package/dist/routes/auth/callbacks/createSignInCallback.js +0 -40
  181. package/dist/routes/auth/callbacks/validateSessionRoles.js +0 -33
  182. package/dist/routes/auth/createLogger.js +0 -35
  183. package/dist/routes/auth/createPrefixedCookies.js +0 -52
  184. package/dist/routes/auth/createProviders.js +0 -25
  185. package/dist/routes/auth/defaultAuthUrl.js +0 -31
  186. package/dist/routes/auth/events/createCreateUserEvent.js +0 -41
  187. package/dist/routes/auth/events/createEvents.js +0 -56
  188. package/dist/routes/auth/events/createLinkAccountEvent.js +0 -43
  189. package/dist/routes/auth/events/createSignInEvent.js +0 -46
  190. package/dist/routes/auth/events/createSignOutEvent.js +0 -43
  191. package/dist/routes/auth/events/createUpdateUserEvent.js +0 -41
  192. package/dist/routes/auth/getAuthConfig.js +0 -90
  193. package/dist/routes/auth/resolveCookies.js +0 -37
  194. package/dist/routes/log/formatValidationError.js +0 -31
  195. /package/dist/{routes/notifications → email}/resolveThemeLogo.js +0 -0
@@ -0,0 +1,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
+ // BetterAuth reads the client address (its rate-limit key, the session's
17
+ // ipAddress, the captcha remote IP) only from request headers. The server
18
+ // resolves the address itself - from the connection and the app's trusted
19
+ // proxies - and hands it over in this header, which getBetterAuthConfig names
20
+ // as the one BetterAuth reads. Any copy the client sent is replaced, so the
21
+ // header carries only what the server resolved.
22
+ const CLIENT_ADDRESS_HEADER = 'x-lowdefy-client-address';
23
+ // The new Request is built from the incoming one's parts rather than cloned
24
+ // from it: @hono/node-server hands the app a lightweight stand-in for a
25
+ // Request, which only its own copy's Request constructor accepts as input,
26
+ // and the dev server loads two copies.
27
+ function handleAuthRequest({ auth, request, clientAddress }) {
28
+ const headers = new Headers(request.headers);
29
+ headers.delete(CLIENT_ADDRESS_HEADER);
30
+ if (!type.isNone(clientAddress)) {
31
+ headers.set(CLIENT_ADDRESS_HEADER, clientAddress);
32
+ }
33
+ const hasBody = request.method !== 'GET' && request.method !== 'HEAD';
34
+ return auth.handler(new Request(request.url, {
35
+ method: request.method,
36
+ headers,
37
+ body: hasBody ? request.body : null,
38
+ duplex: 'half',
39
+ signal: request.signal
40
+ }));
41
+ }
42
+ export default handleAuthRequest;
43
+ export { CLIENT_ADDRESS_HEADER };
@@ -0,0 +1,204 @@
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 findHookUser from './findHookUser.js';
16
+ // The bindable auth hook points and what each hands the hook routine as
17
+ // _payload - the contract between the hook mechanism and the hook author.
18
+ // Build validation guarantees every configured point is in this catalog.
19
+ //
20
+ // The dispatch layer (createHookDispatch) injects a reserved "point" field
21
+ // onto every payload - the firing point name - so a routine bound to multiple
22
+ // points can branch on _payload.point. buildPayload definitions own the domain
23
+ // data only and must never produce a field named "point".
24
+ // Twin catalog: packages/build/src/build/buildAuth/authHookPoints.js lists
25
+ // the point names build accepts - a point accepted there without a
26
+ // definition here crashes buildHooks at startup; keep the two in sync.
27
+ //
28
+ // Database points receive BetterAuth's databaseHooks record; session and
29
+ // account writes carry only a userId, so the subject user is read through
30
+ // BetterAuth's internal adapter. user.update deviates from the catalog by
31
+ // what BetterAuth provides: the before hook receives only the changed fields
32
+ // (no way to identify the subject), the after hook only the updated record.
33
+ //
34
+ // Synthetic points are backed by BetterAuth config callbacks, not database
35
+ // hooks: "email.verified" by emailVerification.afterEmailVerification, and the
36
+ // "phone.*" points by the phoneNumber plugin's sendOTP /
37
+ // sendPasswordResetOTP / callbackOnVerification.
38
+ const authHookPoints = {
39
+ 'user.create.before': {
40
+ kind: 'database',
41
+ model: 'user',
42
+ operation: 'create',
43
+ timing: 'before',
44
+ buildPayload: (data)=>({
45
+ user: data
46
+ })
47
+ },
48
+ 'user.create.after': {
49
+ kind: 'database',
50
+ model: 'user',
51
+ operation: 'create',
52
+ timing: 'after',
53
+ buildPayload: (data)=>({
54
+ user: data
55
+ })
56
+ },
57
+ 'user.update.before': {
58
+ kind: 'database',
59
+ model: 'user',
60
+ operation: 'update',
61
+ timing: 'before',
62
+ buildPayload: (data)=>({
63
+ user: null,
64
+ changes: data
65
+ })
66
+ },
67
+ 'user.update.after': {
68
+ kind: 'database',
69
+ model: 'user',
70
+ operation: 'update',
71
+ timing: 'after',
72
+ buildPayload: (data)=>({
73
+ user: data,
74
+ changes: null
75
+ })
76
+ },
77
+ 'session.create.before': {
78
+ kind: 'database',
79
+ model: 'session',
80
+ operation: 'create',
81
+ timing: 'before',
82
+ buildPayload: async (data, ctx)=>({
83
+ session: data,
84
+ user: await findHookUser({
85
+ ctx,
86
+ userId: data.userId
87
+ })
88
+ })
89
+ },
90
+ 'session.create.after': {
91
+ kind: 'database',
92
+ model: 'session',
93
+ operation: 'create',
94
+ timing: 'after',
95
+ buildPayload: async (data, ctx)=>({
96
+ session: data,
97
+ user: await findHookUser({
98
+ ctx,
99
+ userId: data.userId
100
+ })
101
+ })
102
+ },
103
+ 'session.update.before': {
104
+ kind: 'database',
105
+ model: 'session',
106
+ operation: 'update',
107
+ timing: 'before',
108
+ // Like user.update.before: BetterAuth hands the before hook only the
109
+ // changed fields, with no way to identify the subject session.
110
+ buildPayload: (data)=>({
111
+ session: null,
112
+ changes: data
113
+ })
114
+ },
115
+ 'session.delete.after': {
116
+ kind: 'database',
117
+ model: 'session',
118
+ operation: 'delete',
119
+ timing: 'after',
120
+ buildPayload: async (data, ctx)=>({
121
+ session: data,
122
+ user: await findHookUser({
123
+ ctx,
124
+ userId: data.userId
125
+ })
126
+ })
127
+ },
128
+ 'account.create.before': {
129
+ kind: 'database',
130
+ model: 'account',
131
+ operation: 'create',
132
+ timing: 'before',
133
+ buildPayload: async (data, ctx)=>({
134
+ account: data,
135
+ user: await findHookUser({
136
+ ctx,
137
+ userId: data.userId
138
+ })
139
+ })
140
+ },
141
+ 'account.create.after': {
142
+ kind: 'database',
143
+ model: 'account',
144
+ operation: 'create',
145
+ timing: 'after',
146
+ buildPayload: async (data, ctx)=>({
147
+ account: data,
148
+ user: await findHookUser({
149
+ ctx,
150
+ userId: data.userId
151
+ })
152
+ })
153
+ },
154
+ 'verification.create.before': {
155
+ kind: 'database',
156
+ model: 'verification',
157
+ operation: 'create',
158
+ timing: 'before',
159
+ buildPayload: (data)=>({
160
+ verification: data
161
+ })
162
+ },
163
+ 'verification.create.after': {
164
+ kind: 'database',
165
+ model: 'verification',
166
+ operation: 'create',
167
+ timing: 'after',
168
+ buildPayload: (data)=>({
169
+ verification: data
170
+ })
171
+ },
172
+ 'email.verified': {
173
+ kind: 'synthetic',
174
+ timing: 'after',
175
+ buildPayload: (user)=>({
176
+ user
177
+ })
178
+ },
179
+ 'phone.otp.send': {
180
+ kind: 'synthetic',
181
+ timing: 'after',
182
+ buildPayload: (data)=>({
183
+ phoneNumber: data.phoneNumber,
184
+ code: data.code
185
+ })
186
+ },
187
+ 'phone.passwordReset.send': {
188
+ kind: 'synthetic',
189
+ timing: 'after',
190
+ buildPayload: (data)=>({
191
+ phoneNumber: data.phoneNumber,
192
+ code: data.code
193
+ })
194
+ },
195
+ 'phone.verified': {
196
+ kind: 'synthetic',
197
+ timing: 'after',
198
+ buildPayload: (data)=>({
199
+ user: data.user,
200
+ phoneNumber: data.phoneNumber
201
+ })
202
+ }
203
+ };
204
+ export default authHookPoints;
@@ -0,0 +1,68 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import createAcceptActiveOrgGuardHook from '../organizations/createAcceptActiveOrgGuardHook.js';
16
+ import createActiveOrgPolicyHook from '../organizations/createActiveOrgPolicyHook.js';
17
+ import createAdmissionGateHook from '../organizations/createAdmissionGateHook.js';
18
+ import createAutoJoinHook from '../organizations/createAutoJoinHook.js';
19
+ // Engine-tier hook bindings - hard-coded framework behavior, not entries in
20
+ // auth.hooks. Keyed by point; each point lists BetterAuth-native callbacks
21
+ // (before: (data, ctx) => false | { data } | undefined, after: (data, ctx)).
22
+ // Engine hooks run first in each composed slot, so the user hook sees the
23
+ // engine-normalized record. Config parameterizes the membership behaviors
24
+ // (policy, signup) but they are not user-pluggable.
25
+ function buildEngineHooks({ authConfig, getAuth, logger }) {
26
+ const organizations = authConfig.organizations;
27
+ const engineHooks = {
28
+ 'session.create.before': [
29
+ createActiveOrgPolicyHook({
30
+ getAuth,
31
+ logger,
32
+ organizations
33
+ })
34
+ ],
35
+ // Bound under both policies: the guard keys on the accept-invitation path
36
+ // and only ever vetoes a switch away from an existing active organization,
37
+ // so under pinned (one organization: accept re-sets the same id, or repairs
38
+ // an org-less invitee session) it never bites.
39
+ 'session.update.before': [
40
+ createAcceptActiveOrgGuardHook({
41
+ logger
42
+ })
43
+ ]
44
+ };
45
+ // The admission gate bites only under pinned + invite-only (the predicate
46
+ // admits everyone otherwise), so it is bound only there. It is the first - and
47
+ // only - engine binding on user.create.before, so it runs ahead of the
48
+ // module-contributed merge-on-signup hook: an unadmitted create is vetoed
49
+ // before merge runs, and no orphan contact is linked or created.
50
+ if (organizations.policy === 'pinned' && organizations.signup === 'invite-only') {
51
+ engineHooks['user.create.before'] = [
52
+ createAdmissionGateHook({
53
+ getAuth,
54
+ organizations
55
+ })
56
+ ];
57
+ }
58
+ if (organizations.policy === 'pinned' && organizations.signup === 'open') {
59
+ engineHooks['user.create.after'] = [
60
+ createAutoJoinHook({
61
+ getAuth,
62
+ organizations
63
+ })
64
+ ];
65
+ }
66
+ return engineHooks;
67
+ }
68
+ export default buildEngineHooks;
@@ -0,0 +1,112 @@
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 { set, type } from '@lowdefy/helpers';
16
+ import { LowdefyInternalError } from '@lowdefy/errors';
17
+ import authHookPoints from './authHookPoints.js';
18
+ import buildEngineHooks from './buildEngineHooks.js';
19
+ import composeAfterSlot from './composeAfterSlot.js';
20
+ import composeBeforeSlot from './composeBeforeSlot.js';
21
+ import createHookDispatch from './createHookDispatch.js';
22
+ import createUserAfterHook from './createUserAfterHook.js';
23
+ import createUserBeforeHook from './createUserBeforeHook.js';
24
+ // Assembles BetterAuth's databaseHooks and the synthetic points' backing
25
+ // callbacks from the engine-tier bindings and the validated auth.hooks
26
+ // entries. Each point resolves to one composed slot with engine hooks first,
27
+ // then every user hook bound to the point in array order - the build orders
28
+ // the array as module contributions first, then app entries, so array order
29
+ // IS the tier order. Build validation guarantees every entry binds a known
30
+ // point to an existing InternalApi endpoint; one endpoint may bind several
31
+ // points.
32
+ function buildHooks({ authConfig, createSystemContext, getAuth, logger }) {
33
+ const userHooks = {};
34
+ (authConfig.hooks ?? []).forEach((hook)=>{
35
+ if (type.isNone(userHooks[hook.point])) {
36
+ userHooks[hook.point] = [];
37
+ }
38
+ userHooks[hook.point].push(hook);
39
+ });
40
+ if (Object.keys(userHooks).length > 0 && type.isNone(createSystemContext)) {
41
+ throw new LowdefyInternalError('Auth hooks are configured but no createSystemContext factory was provided to getBetterAuthConfig.');
42
+ }
43
+ const engineHooks = buildEngineHooks({
44
+ authConfig,
45
+ getAuth,
46
+ logger
47
+ });
48
+ const databaseHooks = {};
49
+ let afterEmailVerification;
50
+ let phoneVerified;
51
+ let sendPhoneOtp;
52
+ let sendPhonePasswordResetOtp;
53
+ const points = new Set([
54
+ ...Object.keys(engineHooks),
55
+ ...Object.keys(userHooks)
56
+ ]);
57
+ points.forEach((point)=>{
58
+ const pointDef = authHookPoints[point];
59
+ const hooks = [
60
+ ...engineHooks[point] ?? []
61
+ ];
62
+ (userHooks[point] ?? []).forEach((userHook)=>{
63
+ const dispatch = createHookDispatch({
64
+ createSystemContext,
65
+ getAuth,
66
+ hook: userHook
67
+ });
68
+ hooks.push(pointDef.timing === 'before' ? createUserBeforeHook({
69
+ dispatch,
70
+ hook: userHook
71
+ }) : createUserAfterHook({
72
+ dispatch
73
+ }));
74
+ });
75
+ if (pointDef.kind === 'database') {
76
+ const slot = pointDef.timing === 'before' ? composeBeforeSlot({
77
+ hooks
78
+ }) : composeAfterSlot({
79
+ hooks
80
+ });
81
+ set(databaseHooks, `${pointDef.model}.${pointDef.operation}.${pointDef.timing}`, slot);
82
+ }
83
+ if (point === 'email.verified') {
84
+ afterEmailVerification = composeAfterSlot({
85
+ hooks
86
+ });
87
+ }
88
+ if (point === 'phone.otp.send') {
89
+ sendPhoneOtp = composeAfterSlot({
90
+ hooks
91
+ });
92
+ }
93
+ if (point === 'phone.passwordReset.send') {
94
+ sendPhonePasswordResetOtp = composeAfterSlot({
95
+ hooks
96
+ });
97
+ }
98
+ if (point === 'phone.verified') {
99
+ phoneVerified = composeAfterSlot({
100
+ hooks
101
+ });
102
+ }
103
+ });
104
+ return {
105
+ afterEmailVerification,
106
+ databaseHooks,
107
+ phoneVerified,
108
+ sendPhoneOtp,
109
+ sendPhonePasswordResetOtp
110
+ };
111
+ }
112
+ export default buildHooks;
@@ -12,17 +12,15 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import { get, set } from '@lowdefy/helpers';
16
- function addUserFieldsToSession({ session, token, authConfig, user }) {
17
- if (token) {
18
- Object.keys(authConfig.userFields).forEach((fieldName)=>{
19
- set(session.user, fieldName, get(token, fieldName));
20
- });
21
- }
22
- if (user) {
23
- Object.keys(authConfig.userFields).forEach((fieldName)=>{
24
- set(session.user, fieldName, get(user, fieldName));
25
- });
26
- }
15
+ */ // The composed slot for after and synthetic points - engine hooks first,
16
+ // then the user hooks in array order, sequentially. Return values are
17
+ // ignored; a thrown error propagates as an operational error on the
18
+ // underlying operation.
19
+ function composeAfterSlot({ hooks }) {
20
+ return async function afterSlot(data, ctx) {
21
+ for (const hook of hooks){
22
+ await hook(data, ctx);
23
+ }
24
+ };
27
25
  }
28
- export default addUserFieldsToSession;
26
+ export default composeAfterSlot;
@@ -0,0 +1,41 @@
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
+ // BetterAuth exposes one callback per database point, so each point resolves
17
+ // to a single composed slot - engine hooks first, then the user hooks in
18
+ // array order. The slot threads the record: what one hook returns is passed
19
+ // to the next, and the final record is handed back to BetterAuth as
20
+ // { data }. The first hook
21
+ // to veto short-circuits - a returned false aborts the write, and a thrown
22
+ // error propagates; there is no cross-hook transaction, so external
23
+ // side-effects of earlier hooks are not rolled back.
24
+ function composeBeforeSlot({ hooks }) {
25
+ return async function beforeSlot(data, ctx) {
26
+ let record = data;
27
+ for (const hook of hooks){
28
+ const result = await hook(record, ctx);
29
+ if (result === false) {
30
+ return false;
31
+ }
32
+ if (type.isObject(result) && 'data' in result) {
33
+ record = result.data;
34
+ }
35
+ }
36
+ return {
37
+ data: record
38
+ };
39
+ };
40
+ }
41
+ export default composeBeforeSlot;
@@ -0,0 +1,59 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import invokeEndpoint from '../../endpoints/invokeEndpoint.js';
16
+ import authHookPoints from './authHookPoints.js';
17
+ // Runs a user hook: builds the point's payload from the hook data, builds a
18
+ // fresh system context, and invokes the bound InternalApi endpoint. Returns
19
+ // the routine's terminal envelope ({ status, response?, error? }); the
20
+ // translation to BetterAuth's hook contract lives in createUserBeforeHook /
21
+ // createUserAfterHook.
22
+ function createHookDispatch({ createSystemContext, getAuth, hook }) {
23
+ const { buildPayload } = authHookPoints[hook.point];
24
+ return async function dispatchHook(data, ctx) {
25
+ const start = performance.now();
26
+ // point is a reserved envelope key injected onto every payload so a
27
+ // routine bound to multiple points (which may hand identical domain data,
28
+ // e.g. user.create.before and email.verified both give { user }) can tell
29
+ // which point fired. No point's buildPayload produces a "point" field, so
30
+ // the spread never collides.
31
+ const payload = {
32
+ ...await buildPayload(data, ctx),
33
+ point: hook.point
34
+ };
35
+ // getAuth resolves the BetterAuth instance lazily at fire time - hooks
36
+ // only fire after construction completes, so the accessor is always
37
+ // resolved by now. This is the same chicken-and-egg fix used by the
38
+ // engine hooks (e.g. createActiveOrgPolicyHook): the instance cannot be
39
+ // passed in directly because building it is what registers this hook.
40
+ const context = createSystemContext({
41
+ auth: getAuth()
42
+ });
43
+ const result = await invokeEndpoint(context, {
44
+ endpointId: hook.endpointId,
45
+ payload,
46
+ endpointDepth: 0
47
+ });
48
+ context.logger.debug({
49
+ event: 'debug_auth_hook',
50
+ hookId: hook.id,
51
+ point: hook.point,
52
+ endpointId: hook.endpointId,
53
+ status: result.status,
54
+ elapsed_ms: Math.round((performance.now() - start) * 100) / 100
55
+ });
56
+ return result;
57
+ };
58
+ }
59
+ export default createHookDispatch;
@@ -0,0 +1,36 @@
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
+ // Translates the routine's terminal control for after and synthetic points.
17
+ // These fire after the write committed, so `:return` data is ignored and a
18
+ // `:reject`/throw surfaces as an operational error on the underlying
19
+ // operation - hook routines wrap fallible fire-and-forget work in `:try`.
20
+ function createUserAfterHook({ dispatch }) {
21
+ return async function userAfterHook(data, ctx) {
22
+ const result = await dispatch(data, ctx);
23
+ if (result.status === 'reject') {
24
+ // Keep the rejecting UserError as the cause so the server-side trace still
25
+ // names the routine control that refused the write.
26
+ throw new APIError('BAD_REQUEST', {
27
+ cause: result.error,
28
+ message: result.error.message
29
+ });
30
+ }
31
+ if (result.status === 'error') {
32
+ throw result.error;
33
+ }
34
+ };
35
+ }
36
+ export default createUserAfterHook;
@@ -0,0 +1,50 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { APIError } from 'better-auth/api';
16
+ import { type } from '@lowdefy/helpers';
17
+ import { ConfigError } from '@lowdefy/errors';
18
+ // Translates the routine's terminal control into BetterAuth's before-hook
19
+ // contract. The routine `:return`s plain data - the ceremony lives here:
20
+ // returned data replaces the record ({ data } wrap), a fall-through leaves
21
+ // the record unchanged, and `:reject`/throw aborts the write.
22
+ function createUserBeforeHook({ dispatch, hook }) {
23
+ return async function userBeforeHook(data, ctx) {
24
+ const result = await dispatch(data, ctx);
25
+ if (result.status === 'return') {
26
+ if (!type.isObject(result.response)) {
27
+ throw new ConfigError(`Auth hook "${hook.id}" at point "${hook.point}" returned a ${type.typeOf(result.response)}. A before hook ":return" value replaces the record being written, so it should be an object.`, {
28
+ received: result.response
29
+ });
30
+ }
31
+ return {
32
+ data: result.response
33
+ };
34
+ }
35
+ if (result.status === 'reject') {
36
+ // Keep the rejecting UserError as the cause so the server-side trace still
37
+ // names the routine control that refused the write.
38
+ throw new APIError('BAD_REQUEST', {
39
+ cause: result.error,
40
+ message: result.error.message
41
+ });
42
+ }
43
+ if (result.status === 'error') {
44
+ throw result.error;
45
+ }
46
+ // The routine fell through without a terminal control - record unchanged.
47
+ return undefined;
48
+ };
49
+ }
50
+ export default createUserBeforeHook;
@@ -0,0 +1,27 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { type } from '@lowdefy/helpers';
16
+ // Fetches the subject user for points whose payload catalog includes a user
17
+ // the database hook does not receive directly (session and account writes
18
+ // carry only a userId). Reads through BetterAuth's own internal adapter from
19
+ // the hook's endpoint context; null when the write runs outside a request
20
+ // lifecycle and no context is available.
21
+ async function findHookUser({ ctx, userId }) {
22
+ if (type.isNone(userId) || type.isNone(ctx?.context?.internalAdapter?.findUserById)) {
23
+ return null;
24
+ }
25
+ return await ctx.context.internalAdapter.findUserById(userId) ?? null;
26
+ }
27
+ export default findHookUser;