@lowdefy/api 7.0.0 → 7.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/dist/context/createAuthorizeOutcome.js +1 -1
  2. package/dist/context/createEvaluateOperators.js +2 -1
  3. package/dist/context/isWebSocketOriginAllowed.js +3 -1
  4. package/dist/context/readMemberships.js +10 -4
  5. package/dist/context/resolveAuthentication.js +95 -21
  6. package/dist/email/renderAuthEmail.js +3 -2
  7. package/dist/index.js +7 -1
  8. package/dist/response/redactErrorResponse.js +8 -4
  9. package/dist/routes/agent/callAgent.js +20 -2
  10. package/dist/routes/agent/redactMessages.js +136 -0
  11. package/dist/routes/auth/createAuthLogger.js +23 -6
  12. package/dist/routes/auth/createMcpAccessTokenClaims.js +8 -6
  13. package/dist/routes/auth/createOnAPIError.js +15 -5
  14. package/dist/routes/auth/createSendEmail.js +15 -5
  15. package/dist/routes/auth/getBetterAuth.js +3 -3
  16. package/dist/routes/auth/getBetterAuthConfig.js +163 -92
  17. package/dist/routes/auth/hooks/buildEngineHooks.js +15 -1
  18. package/dist/routes/auth/hooks/createUserAfterHook.js +17 -2
  19. package/dist/routes/auth/hooks/createUserBeforeHook.js +20 -4
  20. package/dist/routes/auth/mobile/buildBearerPlugin.js +45 -0
  21. package/dist/routes/auth/mobile/buildOneTimeTokenPlugin.js +50 -0
  22. package/dist/routes/auth/mobile/createCodeVerifierCheck.js +57 -0
  23. package/dist/routes/auth/mobile/createKnownDeviceHook.js +76 -0
  24. package/dist/routes/auth/mobile/createMobileAuthPageResponse.js +79 -0
  25. package/dist/routes/auth/mobile/createMobileSessionCreateHook.js +41 -0
  26. package/dist/routes/auth/mobile/createMobileSessionRefreshHook.js +40 -0
  27. package/dist/routes/auth/mobile/createMobileSignInCsrfToken.js +32 -0
  28. package/dist/routes/auth/mobile/createPhoneSession.js +59 -0
  29. package/dist/routes/auth/mobile/escapeHtml.js +26 -0
  30. package/dist/routes/auth/mobile/getCodeHolderIdentifier.js +20 -0
  31. package/dist/routes/auth/mobile/getKnownDeviceIdentifier.js +20 -0
  32. package/dist/routes/auth/mobile/getMobileSessionExpiry.js +18 -0
  33. package/dist/routes/auth/mobile/getMobileSignInReturnUrl.js +31 -0
  34. package/dist/routes/auth/mobile/getOneTimeTokenIdentifiers.js +26 -0
  35. package/dist/routes/auth/mobile/handleMobileSignIn.js +303 -0
  36. package/dist/routes/auth/mobile/handleMobileSignInCallback.js +30 -0
  37. package/dist/routes/auth/mobile/isNativeAuthRequest.js +33 -0
  38. package/dist/routes/auth/mobile/matchesCodeChallenge.js +29 -0
  39. package/dist/routes/auth/mobile/mintOneTimeToken.js +41 -0
  40. package/dist/routes/auth/mobile/readDeviceKeyHash.js +34 -0
  41. package/dist/routes/auth/mobile/readMobileSignInParams.js +90 -0
  42. package/dist/routes/auth/mobile/sha256Base64Url.js +22 -0
  43. package/dist/routes/auth/mobile/storeCodeChallenge.js +29 -0
  44. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +43 -6
  45. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +7 -2
  46. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +41 -189
  47. package/dist/routes/auth/organizations/createAdmissionGateHook.js +5 -5
  48. package/dist/routes/auth/organizations/createBeforeCreateInvitationHook.js +62 -0
  49. package/dist/routes/auth/organizations/createBeforeUpdateMemberRoleHook.js +45 -0
  50. package/dist/routes/auth/organizations/createSuspendedMemberGate.js +146 -0
  51. package/dist/routes/auth/organizations/createSuspendedOrganizationsFilter.js +44 -0
  52. package/dist/routes/auth/organizations/ensureAuthIndexes.js +11 -10
  53. package/dist/routes/auth/organizations/getOrganizationBinding.js +4 -2
  54. package/dist/routes/auth/organizations/isActiveMember.js +26 -0
  55. package/dist/routes/auth/organizations/isEmailAdmitted.js +12 -5
  56. package/dist/routes/auth/organizations/memberRowsLimit.js +19 -0
  57. package/dist/routes/auth/organizations/mintOrganization.js +258 -0
  58. package/dist/routes/auth/organizations/organizationAccessControl.js +5 -1
  59. package/dist/routes/auth/organizations/provisionOrganization.js +117 -0
  60. package/dist/routes/auth/organizations/readSuspendedOrganizationIds.js +36 -0
  61. package/dist/routes/auth/requestHooks/buildRequestHooks.js +72 -0
  62. package/dist/routes/auth/requestHooks/createEmailCodeHolderGate.js +58 -0
  63. package/dist/routes/auth/requestHooks/createEmailSendLimit.js +116 -0
  64. package/dist/routes/auth/requestHooks/createSignInRefusedRedirectHook.js +75 -0
  65. package/dist/routes/auth/requestHooks/holdEmailCode.js +80 -0
  66. package/dist/routes/auth/requestHooks/reserveSendSlot.js +70 -0
  67. package/dist/routes/auth/runReportingFaults.js +32 -0
  68. package/dist/routes/connections/resolveUnwalledReach.js +14 -16
  69. package/dist/routes/endpoints/callEndpoint.js +6 -3
  70. package/dist/routes/endpoints/control/controlFor.js +9 -6
  71. package/dist/routes/endpoints/control/controlIf.js +8 -3
  72. package/dist/routes/endpoints/control/controlLog.js +3 -1
  73. package/dist/routes/endpoints/control/controlParallelFor.js +9 -6
  74. package/dist/routes/endpoints/control/controlReturn.js +3 -2
  75. package/dist/routes/endpoints/control/controlSetState.js +1 -1
  76. package/dist/routes/endpoints/control/controlSwitch.js +6 -3
  77. package/dist/routes/endpoints/control/controlWhile.js +6 -3
  78. package/dist/routes/endpoints/createLinkAnswer.js +76 -0
  79. package/dist/routes/endpoints/dispatchDetached.js +38 -0
  80. package/dist/routes/endpoints/forwardScheduledEndpoint.js +32 -11
  81. package/dist/routes/endpoints/handleAgentCall.js +1 -1
  82. package/dist/routes/endpoints/handleAuthStep.js +19 -4
  83. package/dist/routes/endpoints/handleEndpointCall.js +6 -4
  84. package/dist/routes/endpoints/handleRequest.js +3 -2
  85. package/dist/routes/endpoints/handleValidateDynamic.js +1 -1
  86. package/dist/routes/endpoints/matchLinkEndpoint.js +30 -0
  87. package/dist/routes/endpoints/runLinkEndpoint.js +148 -0
  88. package/dist/routes/endpoints/runRoutine.js +5 -5
  89. package/dist/routes/endpoints/scheduleBackground.js +13 -11
  90. package/dist/routes/endpoints/test/runTest.js +30 -11
  91. package/dist/routes/mcp/createMcpServer.js +2 -7
  92. package/dist/routes/mcp/runAfterToolCall.js +9 -3
  93. package/dist/routes/mobile/createAppleAppSiteAssociation.js +51 -0
  94. package/dist/routes/mobile/createAssetLinks.js +38 -0
  95. package/dist/routes/mobile/filterMobileMenus.js +31 -0
  96. package/dist/routes/mobile/getMobileAppEvents.js +23 -0
  97. package/dist/routes/mobile/getMobileRootConfig.js +109 -0
  98. package/dist/routes/mobile/getOpenablePageIds.js +21 -0
  99. package/dist/routes/page/dynamic/policy/checkAction.js +67 -2
  100. package/dist/routes/page/dynamic/policy/checkEvents.js +8 -2
  101. package/dist/routes/page/dynamic/policy/checkPolicy.js +86 -6
  102. package/dist/routes/page/dynamic/policy/checkValue.js +97 -6
  103. package/dist/routes/page/dynamic/policy/collectSchemaKinds.js +173 -0
  104. package/dist/routes/page/dynamic/policy/findDataRows.js +94 -0
  105. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +24 -12
  106. package/dist/routes/page/dynamic/policy/findHtmlUrls.js +64 -0
  107. package/dist/routes/page/dynamic/policy/overlapsStatePath.js +28 -0
  108. package/dist/routes/page/dynamic/resolveDynamicContent.js +23 -17
  109. package/dist/routes/page/getPageConfig.js +25 -1
  110. package/dist/routes/request/callRequestResolver.js +29 -36
  111. package/dist/routes/request/stampTypedError.js +37 -0
  112. package/dist/routes/request/summarisedError.js +62 -0
  113. package/dist/routes/request/wrapResolverError.js +61 -0
  114. package/dist/routes/websocket/createChannelRegistry.js +13 -15
  115. package/dist/routes/websocket/createWebSocketConnection.js +5 -8
  116. package/dist/test/createMemoryAuth.js +125 -0
  117. package/package.json +20 -22
  118. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +0 -117
  119. package/dist/routes/request/maskCredentialProperties.js +0 -34
@@ -0,0 +1,117 @@
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 ensureAuthIndexes from './ensureAuthIndexes.js';
17
+ import { getRegisteredOrganization } from './getOrganizationBinding.js';
18
+ import mintOrganization from './mintOrganization.js';
19
+ async function findOrganization({ adapter, slug }) {
20
+ return adapter.findOne({
21
+ model: 'organization',
22
+ where: [
23
+ {
24
+ field: 'slug',
25
+ value: slug
26
+ }
27
+ ]
28
+ });
29
+ }
30
+ // A provisioned organization has no creator - membership arrives by
31
+ // invitation - so it is one write. A slug that is taken, or taken by a racing
32
+ // write the unique slug index rejects, is refused.
33
+ async function createCreatorlessOrganization({ adapter, data }) {
34
+ if (!type.isNone(await findOrganization({
35
+ adapter,
36
+ slug: data.slug
37
+ }))) {
38
+ return null;
39
+ }
40
+ try {
41
+ return await adapter.create({
42
+ model: 'organization',
43
+ data: {
44
+ ...data,
45
+ createdAt: new Date()
46
+ }
47
+ });
48
+ } catch (error) {
49
+ if (!type.isNone(await findOrganization({
50
+ adapter,
51
+ slug: data.slug
52
+ }))) {
53
+ return null;
54
+ }
55
+ throw error;
56
+ }
57
+ }
58
+ // The CreateOrganization step's write, handed to every auth step by
59
+ // handleAuthStep. With a creator, the organization and its owner row holding
60
+ // auth.organizations.creatorAppRoles are written by mintOrganization, the same
61
+ // way the tenant signup mint writes them, so a run that fails between the two
62
+ // writes is finished by the creator's next run for the same slug.
63
+ //
64
+ // Returns { organization, member } - member is null without a creator - or
65
+ // null when the slug belongs to another organization. organization is shaped
66
+ // the way the org plugin's endpoints return it: without the server-only marker
67
+ // fields, and with metadata parsed from the JSON string the row stores.
68
+ async function provisionOrganization({ auth, logger, organization: fields, userId }) {
69
+ // A refused slug is only a guarantee behind the unique slug index - a read
70
+ // cannot see a racing write - so nothing is written without it.
71
+ await ensureAuthIndexes({
72
+ auth,
73
+ logger
74
+ });
75
+ const { adapter } = await auth.$context;
76
+ const data = {
77
+ ...fields
78
+ };
79
+ if (!type.isNone(fields.metadata)) {
80
+ data.metadata = JSON.stringify(fields.metadata);
81
+ }
82
+ let organization;
83
+ let member = null;
84
+ if (type.isNone(userId)) {
85
+ organization = await createCreatorlessOrganization({
86
+ adapter,
87
+ data
88
+ });
89
+ } else {
90
+ const minted = await mintOrganization({
91
+ adapter,
92
+ creatorAppRoles: getRegisteredOrganization({
93
+ auth
94
+ }).creatorAppRoles,
95
+ organization: data,
96
+ userId
97
+ });
98
+ organization = minted?.organization ?? null;
99
+ member = minted?.member ?? null;
100
+ }
101
+ if (type.isNone(organization)) {
102
+ return null;
103
+ }
104
+ const result = {
105
+ ...organization
106
+ };
107
+ delete result.mintPending;
108
+ delete result.mintCreatorId;
109
+ if (type.isString(result.metadata)) {
110
+ result.metadata = JSON.parse(result.metadata);
111
+ }
112
+ return {
113
+ organization: result,
114
+ member
115
+ };
116
+ }
117
+ export default provisionOrganization;
@@ -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 MEMBER_ROWS_LIMIT from './memberRowsLimit.js';
16
+ // The organizations a person is suspended in. Only suspended rows are read - a
17
+ // row with no suspended field never equals true, on any adapter - so the
18
+ // common answer, none, reads no rows.
19
+ async function readSuspendedOrganizationIds({ adapter, userId }) {
20
+ const rows = await adapter.findMany({
21
+ model: 'member',
22
+ where: [
23
+ {
24
+ field: 'userId',
25
+ value: userId
26
+ },
27
+ {
28
+ field: 'suspended',
29
+ value: true
30
+ }
31
+ ],
32
+ limit: MEMBER_ROWS_LIMIT
33
+ });
34
+ return rows.map((row)=>row.organizationId);
35
+ }
36
+ export default readSuspendedOrganizationIds;
@@ -16,8 +16,14 @@
16
16
  import { type } from '@lowdefy/helpers';
17
17
  import createAcceptExistingMemberHook from '../organizations/createAcceptExistingMemberHook.js';
18
18
  import createEmailSendGate from '../organizations/createEmailSendGate.js';
19
+ import createEmailCodeHolderGate from './createEmailCodeHolderGate.js';
20
+ import createEmailSendLimit from './createEmailSendLimit.js';
19
21
  import createExpiredInvitationGate from '../organizations/createExpiredInvitationGate.js';
22
+ import createSuspendedMemberGate, { MEMBERSHIP_FREE_PATHS } from '../organizations/createSuspendedMemberGate.js';
23
+ import createSuspendedOrganizationsFilter from '../organizations/createSuspendedOrganizationsFilter.js';
24
+ import createKnownDeviceHook from '../mobile/createKnownDeviceHook.js';
20
25
  import createOauthPostLoginHook from './createOauthPostLoginHook.js';
26
+ import createSignInRefusedRedirectHook from './createSignInRefusedRedirectHook.js';
21
27
  import createTwoFactorChallengeHook from './createTwoFactorChallengeHook.js';
22
28
  import dispatchRequestHooks from './dispatchRequestHooks.js';
23
29
  import redirectToChallenge from './redirectToChallenge.js';
@@ -72,6 +78,30 @@ function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }
72
78
  // the code is minted inside sendMagicLink, which only runs after the
73
79
  // magic-link gate has already admitted the address.
74
80
  if (authConfig.emailOTP?.enabled === true) {
81
+ // Apps with phones sign in by email code by default, so codes are capped at
82
+ // 5 in 15 minutes, per phone and per address (createEmailSendLimit). The
83
+ // password reset code is another unauthenticated send to the same address.
84
+ // Registered ahead of the gate.
85
+ if (!type.isNone(authConfig.mobile)) {
86
+ before.push({
87
+ id: 'emailOtpSendLimit',
88
+ matches: (path)=>path === '/email-otp/send-verification-otp' || path === '/forget-password/email-otp',
89
+ handler: createEmailSendLimit({
90
+ codeSeconds: authConfig.emailOTP.expiresIn,
91
+ getAuth,
92
+ max: 5,
93
+ windowSeconds: 900
94
+ })
95
+ });
96
+ // Only the known phone holding the live code may try it (holdEmailCode).
97
+ before.push({
98
+ id: 'emailOtpCodeHolderGate',
99
+ matches: (path)=>path === '/sign-in/email-otp',
100
+ handler: createEmailCodeHolderGate({
101
+ getAuth
102
+ })
103
+ });
104
+ }
75
105
  before.push({
76
106
  id: 'emailOtpSendGate',
77
107
  matches: (path)=>path === '/email-otp/send-verification-otp',
@@ -96,6 +126,21 @@ function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }
96
126
  getAuth
97
127
  })
98
128
  });
129
+ // A member suspended in an organization is a non-member to the organization
130
+ // plugin's own client endpoints too. Tenant only: under pinned every one of
131
+ // these paths is disabled.
132
+ if (authConfig.organizations?.policy === 'tenant') {
133
+ before.push({
134
+ id: 'suspendedMemberGate',
135
+ matches: (path)=>path.startsWith('/organization/') && !MEMBERSHIP_FREE_PATHS.includes(path),
136
+ handler: createSuspendedMemberGate()
137
+ });
138
+ after.push({
139
+ id: 'suspendedOrganizationsFilter',
140
+ matches: (path)=>path === '/organization/list',
141
+ handler: createSuspendedOrganizationsFilter()
142
+ });
143
+ }
99
144
  // The post-login organization choice (buildOauthPostLogin): stamps the
100
145
  // request's cached session when /oauth2/continue confirms the choice, so the
101
146
  // authorize call it re-enters with does not send the member back to the
@@ -107,6 +152,22 @@ function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }
107
152
  handler: createOauthPostLoginHook()
108
153
  });
109
154
  }
155
+ // A sign-in refused at session creation (banned, no membership, an app hook's
156
+ // :reject) answers the browser with a redirect to the error page rather than
157
+ // raw JSON.
158
+ // Registered ahead of the magic-link two-factor challenge, which has no
159
+ // session to act on when the refusal fires. /verify-email and
160
+ // /email-otp/verify-email need no counterpart: they create a session only with
161
+ // emailVerification.autoSignInAfterVerification or user.changeEmail, and
162
+ // getBetterAuthConfig sets neither, so a verification link cannot be refused
163
+ // this way. Setting either one would open the same gap there.
164
+ if (authConfig.magicLink?.enabled === true) {
165
+ after.push({
166
+ id: 'magicLinkSignInRefused',
167
+ matches: (path)=>path === '/magic-link/verify',
168
+ handler: createSignInRefusedRedirectHook()
169
+ });
170
+ }
110
171
  const twoFactorPageUrl = resolveTwoFactorPageUrl({
111
172
  authConfig,
112
173
  basePath,
@@ -274,6 +335,17 @@ function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }
274
335
  })
275
336
  }));
276
337
  }
338
+ // After the two-factor challenge, which answers first when a second factor is
339
+ // needed: only a sign-in that kept its session records a known phone.
340
+ if (!type.isNone(authConfig.mobile) && authConfig.emailOTP?.enabled === true) {
341
+ after.push({
342
+ id: 'emailOtpKnownDevice',
343
+ matches: (path)=>path === '/sign-in/email-otp',
344
+ handler: createKnownDeviceHook({
345
+ getAuth
346
+ })
347
+ });
348
+ }
277
349
  return {
278
350
  before: createAuthMiddleware(async (ctx)=>dispatchRequestHooks({
279
351
  ctx,
@@ -0,0 +1,58 @@
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 getCodeHolderIdentifier from '../mobile/getCodeHolderIdentifier.js';
18
+ import readDeviceKeyHash from '../mobile/readDeviceKeyHash.js';
19
+ // The engine-tier request hooks.before on /sign-in/email-otp for apps with a
20
+ // mobile section. While a known phone holds the address's live code
21
+ // (holdEmailCode), a try from anything else is refused before BetterAuth counts
22
+ // it as a wrong attempt, so nobody but that phone can use up the code. It is
23
+ // refused as BetterAuth refuses a wrong code, so it says nothing about the hold.
24
+ function createEmailCodeHolderGate({ getAuth }) {
25
+ return async function emailCodeHolderGate(ctx) {
26
+ const rawEmail = ctx.body?.email;
27
+ if (!type.isString(rawEmail)) {
28
+ return undefined;
29
+ }
30
+ const { adapter } = await getAuth().$context;
31
+ const hold = await adapter.findOne({
32
+ model: 'verification',
33
+ where: [
34
+ {
35
+ field: 'identifier',
36
+ value: getCodeHolderIdentifier({
37
+ email: rawEmail.trim().toLowerCase()
38
+ })
39
+ },
40
+ {
41
+ field: 'expiresAt',
42
+ operator: 'gt',
43
+ value: new Date()
44
+ }
45
+ ]
46
+ });
47
+ if (hold === null || readDeviceKeyHash({
48
+ request: ctx.request
49
+ }) === hold.value) {
50
+ return undefined;
51
+ }
52
+ throw new APIError('BAD_REQUEST', {
53
+ code: 'INVALID_OTP',
54
+ message: 'Invalid OTP'
55
+ });
56
+ };
57
+ }
58
+ export default createEmailCodeHolderGate;
@@ -0,0 +1,116 @@
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 getKnownDeviceIdentifier from '../mobile/getKnownDeviceIdentifier.js';
18
+ import holdEmailCode from './holdEmailCode.js';
19
+ import readDeviceKeyHash from '../mobile/readDeviceKeyHash.js';
20
+ import reserveSendSlot from './reserveSendSlot.js';
21
+ const IDENTIFIER_PREFIX = 'email-send-limit:';
22
+ // The engine-tier request hooks.before that caps how many codes are sent: max
23
+ // per windowSeconds, counted in the auth database's verification records so
24
+ // every server instance shares the count. BetterAuth's own rate limiter counts
25
+ // per client address and per instance, which a phone network's shared
26
+ // addresses and several instances both defeat.
27
+ //
28
+ // A per-address cap alone lets anyone who knows an address keep its person
29
+ // out of code sign-in. So a phone that sends its device key (a secret only it
30
+ // holds, x-lowdefy-device-key) counts against its own cap for the address,
31
+ // and a phone that has signed in with the address before (createKnownDeviceHook)
32
+ // skips the address's cap. Every other send - a browser, a new phone, a guess
33
+ // at a key - counts against the address's cap. A known phone's sign-in code is
34
+ // then held for it (holdEmailCode), so a stranger can neither replace the code
35
+ // nor use it up with wrong tries.
36
+ //
37
+ // Registered ahead of the send gate, so an address the app would not mail
38
+ // counts and is refused the same way as one it would: the refusal never tells
39
+ // whether an account exists. A refused send keeps no slot, so the window runs
40
+ // from the sends that went through.
41
+ function createEmailSendLimit({ codeSeconds, getAuth, max, windowSeconds }) {
42
+ return async function emailSendLimit(ctx) {
43
+ const rawEmail = ctx.body?.email;
44
+ // No email is the route's own validation error.
45
+ if (!type.isString(rawEmail)) {
46
+ return undefined;
47
+ }
48
+ const email = rawEmail.trim().toLowerCase();
49
+ const deviceKeyHash = readDeviceKeyHash({
50
+ request: ctx.request
51
+ });
52
+ const { adapter } = await getAuth().$context;
53
+ const now = new Date();
54
+ const identifiers = [];
55
+ if (deviceKeyHash !== null) {
56
+ identifiers.push(`${IDENTIFIER_PREFIX}${email}:${deviceKeyHash}`);
57
+ }
58
+ const known = deviceKeyHash !== null && await adapter.count({
59
+ model: 'verification',
60
+ where: [
61
+ {
62
+ field: 'identifier',
63
+ value: getKnownDeviceIdentifier({
64
+ deviceKeyHash,
65
+ email
66
+ })
67
+ },
68
+ {
69
+ field: 'expiresAt',
70
+ operator: 'gt',
71
+ value: now
72
+ }
73
+ ]
74
+ }) > 0;
75
+ if (!known) {
76
+ identifiers.push(`${IDENTIFIER_PREFIX}${email}`);
77
+ }
78
+ const taken = [];
79
+ for (const identifier of identifiers){
80
+ const record = await reserveSendSlot({
81
+ adapter,
82
+ identifier,
83
+ max,
84
+ now,
85
+ windowSeconds
86
+ });
87
+ if (record === null) {
88
+ await Promise.all(taken.map(({ id })=>adapter.delete({
89
+ model: 'verification',
90
+ where: [
91
+ {
92
+ field: 'id',
93
+ value: id
94
+ }
95
+ ]
96
+ })));
97
+ throw new APIError('TOO_MANY_REQUESTS', {
98
+ message: 'Too many sign-in codes were requested for this email. Try again later.'
99
+ });
100
+ }
101
+ taken.push(record);
102
+ }
103
+ if (ctx.path === '/email-otp/send-verification-otp' && ctx.body?.type === 'sign-in') {
104
+ await holdEmailCode({
105
+ adapter,
106
+ codeSeconds,
107
+ deviceKeyHash,
108
+ email,
109
+ known,
110
+ now
111
+ });
112
+ }
113
+ return undefined;
114
+ };
115
+ }
116
+ export default createEmailSendLimit;
@@ -0,0 +1,75 @@
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 { isAPIError } from 'better-auth/api';
16
+ import { type } from '@lowdefy/helpers';
17
+ // /magic-link/verify redirects to errorCallbackURL?error= for token and
18
+ // user-creation failures, but calls createSession without a catch, so a refusal
19
+ // thrown there - a ban, the active-organization wall, an app's
20
+ // session.create.before :reject - comes back as JSON. The browser navigated to
21
+ // this endpoint from the emailed link (or MagicLinkVerify), so nothing reads
22
+ // that JSON and the person sees it raw. This sends them to the error page
23
+ // instead, resolving the URL exactly as the endpoint does.
24
+ function createSignInRefusedRedirectHook() {
25
+ return async function signInRefusedRedirectHook(ctx) {
26
+ // Only a browser has anywhere to be redirected. BetterAuth clears the
27
+ // caller's asResponse before after hooks run, so the request is what is
28
+ // left to tell the two apart: the router always passes one, and a
29
+ // server-side auth.api.magicLinkVerify() without one keeps its thrown
30
+ // APIError.
31
+ if (!(ctx.request instanceof Request)) {
32
+ return undefined;
33
+ }
34
+ // A coded APIError, the rule BetterAuth applies where it does redirect
35
+ // refusals (this endpoint's createUser catch, the OAuth callback). The
36
+ // endpoint's own redirects - success and INVALID_TOKEN alike - are bodiless
37
+ // 302 APIErrors, so they pass through untouched.
38
+ const returned = ctx.context.returned;
39
+ if (!isAPIError(returned) || !type.isString(returned.body?.code)) {
40
+ return undefined;
41
+ }
42
+ // Truthiness, as the endpoint reads them: an empty errorCallbackURL= falls
43
+ // back to callbackURL, and an empty callbackURL= to '/'.
44
+ const callbackURL = ctx.query.callbackURL ? decodeURIComponent(ctx.query.callbackURL) : '/';
45
+ const errorCallbackURL = ctx.query.errorCallbackURL ? decodeURIComponent(ctx.query.errorCallbackURL) : callbackURL;
46
+ // The endpoint's origin checks are its own middleware, so their failures
47
+ // reach this hook too, and when errorCallbackURL (or the callbackURL it
48
+ // falls back to) is the URL that failed, the destination is untrusted. The
49
+ // code cannot tell which URL failed: verify reports all three as
50
+ // INVALID_CALLBACK_URL. Every other refusal fires after those checks
51
+ // passed, so this changes nothing for them. BetterAuth skips the checks
52
+ // only under disableOriginCheck, which getBetterAuthConfig never sets, or
53
+ // in its test environment.
54
+ if (!ctx.context.isTrustedOrigin(errorCallbackURL, {
55
+ allowRelativePaths: true
56
+ })) {
57
+ return undefined;
58
+ }
59
+ const url = new URL(errorCallbackURL, ctx.context.baseURL);
60
+ url.searchParams.set('error', returned.body.code);
61
+ if (type.isString(returned.body.message)) {
62
+ url.searchParams.set('error_description', returned.body.message);
63
+ }
64
+ // A Response, not `throw ctx.redirect(...)`: the dispatcher answers with the
65
+ // endpoint's own status, so a thrown redirect would go out as a 403 with a
66
+ // Location header the browser does not follow.
67
+ return new Response(null, {
68
+ status: 302,
69
+ headers: {
70
+ location: url.toString()
71
+ }
72
+ });
73
+ };
74
+ }
75
+ export default createSignInRefusedRedirectHook;
@@ -0,0 +1,80 @@
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 getCodeHolderIdentifier from '../mobile/getCodeHolderIdentifier.js';
16
+ // An address has one live sign-in code, and a few wrong tries at it kill it. So
17
+ // a known phone that asks for the code holds it: until the code expires only
18
+ // that phone may try it (createEmailCodeHolderGate), and a stranger cannot kill
19
+ // it with wrong tries. Codes are resent rather than replaced (resendStrategy
20
+ // reuse), so another send keeps the same code and moves its expiry on; the hold
21
+ // moves with it.
22
+ async function holdEmailCode({ adapter, codeSeconds, deviceKeyHash, email, known, now }) {
23
+ const identifier = getCodeHolderIdentifier({
24
+ email
25
+ });
26
+ const expiresAt = new Date(now.getTime() + codeSeconds * 1000);
27
+ if (known) {
28
+ await adapter.deleteMany({
29
+ model: 'verification',
30
+ where: [
31
+ {
32
+ field: 'identifier',
33
+ value: identifier
34
+ }
35
+ ]
36
+ });
37
+ await adapter.create({
38
+ model: 'verification',
39
+ data: {
40
+ identifier,
41
+ value: deviceKeyHash,
42
+ expiresAt,
43
+ createdAt: now,
44
+ updatedAt: now
45
+ }
46
+ });
47
+ return;
48
+ }
49
+ const hold = await adapter.findOne({
50
+ model: 'verification',
51
+ where: [
52
+ {
53
+ field: 'identifier',
54
+ value: identifier
55
+ },
56
+ {
57
+ field: 'expiresAt',
58
+ operator: 'gt',
59
+ value: now
60
+ }
61
+ ]
62
+ });
63
+ if (hold === null) {
64
+ return;
65
+ }
66
+ await adapter.update({
67
+ model: 'verification',
68
+ where: [
69
+ {
70
+ field: 'id',
71
+ value: hold.id
72
+ }
73
+ ],
74
+ update: {
75
+ expiresAt,
76
+ updatedAt: now
77
+ }
78
+ });
79
+ }
80
+ export default holdEmailCode;
@@ -0,0 +1,70 @@
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
+ */ // Takes one of max send slots under an identifier, in the auth database's
16
+ // verification records so every server instance shares the count. The record
17
+ // is written first and the count read after, so parallel sends never get more
18
+ // than max slots between them: one that counts past max takes its record back
19
+ // and is refused. Records expire windowSeconds after their send.
20
+ //
21
+ // Returns the record taken, or null when the slots are full.
22
+ async function reserveSendSlot({ adapter, identifier, max, now, windowSeconds }) {
23
+ await adapter.deleteMany({
24
+ model: 'verification',
25
+ where: [
26
+ {
27
+ field: 'identifier',
28
+ value: identifier
29
+ },
30
+ {
31
+ field: 'expiresAt',
32
+ operator: 'lt',
33
+ value: now
34
+ }
35
+ ]
36
+ });
37
+ const record = await adapter.create({
38
+ model: 'verification',
39
+ data: {
40
+ identifier,
41
+ value: 'sent',
42
+ expiresAt: new Date(now.getTime() + windowSeconds * 1000),
43
+ createdAt: now,
44
+ updatedAt: now
45
+ }
46
+ });
47
+ const taken = await adapter.count({
48
+ model: 'verification',
49
+ where: [
50
+ {
51
+ field: 'identifier',
52
+ value: identifier
53
+ }
54
+ ]
55
+ });
56
+ if (taken <= max) {
57
+ return record;
58
+ }
59
+ await adapter.delete({
60
+ model: 'verification',
61
+ where: [
62
+ {
63
+ field: 'id',
64
+ value: record.id
65
+ }
66
+ ]
67
+ });
68
+ return null;
69
+ }
70
+ export default reserveSendSlot;