@lowdefy/api 7.1.0 → 7.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/dist/context/createAuthorizeOutcome.js +1 -1
  2. package/dist/context/createEvaluateOperators.js +2 -1
  3. package/dist/context/isWebSocketOriginAllowed.js +3 -1
  4. package/dist/context/readMemberships.js +10 -4
  5. package/dist/context/resolveAuthentication.js +99 -31
  6. package/dist/email/renderAuthEmail.js +3 -2
  7. package/dist/index.js +7 -1
  8. package/dist/response/redactErrorResponse.js +8 -4
  9. package/dist/routes/agent/callAgent.js +20 -2
  10. package/dist/routes/agent/redactMessages.js +136 -0
  11. package/dist/routes/auth/createAuthLogger.js +23 -6
  12. package/dist/routes/auth/createMcpAccessTokenClaims.js +8 -6
  13. package/dist/routes/auth/createOnAPIError.js +15 -5
  14. package/dist/routes/auth/createSendEmail.js +15 -5
  15. package/dist/routes/auth/getBetterAuth.js +3 -3
  16. package/dist/routes/auth/getBetterAuthConfig.js +172 -98
  17. package/dist/routes/auth/hooks/buildEngineHooks.js +15 -1
  18. package/dist/routes/auth/hooks/createUserAfterHook.js +17 -2
  19. package/dist/routes/auth/hooks/createUserBeforeHook.js +20 -4
  20. package/dist/routes/auth/isUserBanned.js +28 -0
  21. package/dist/routes/auth/mobile/buildBearerPlugin.js +45 -0
  22. package/dist/routes/auth/mobile/buildOneTimeTokenPlugin.js +50 -0
  23. package/dist/routes/auth/mobile/createCodeVerifierCheck.js +57 -0
  24. package/dist/routes/auth/mobile/createKnownDeviceHook.js +76 -0
  25. package/dist/routes/auth/mobile/createMobileAuthPageResponse.js +79 -0
  26. package/dist/routes/auth/mobile/createMobileSessionCreateHook.js +41 -0
  27. package/dist/routes/auth/mobile/createMobileSessionRefreshHook.js +40 -0
  28. package/dist/routes/auth/mobile/createMobileSignInCsrfToken.js +32 -0
  29. package/dist/routes/auth/mobile/createPhoneSession.js +59 -0
  30. package/dist/routes/auth/mobile/escapeHtml.js +26 -0
  31. package/dist/routes/auth/mobile/getCodeHolderIdentifier.js +20 -0
  32. package/dist/routes/auth/mobile/getKnownDeviceIdentifier.js +20 -0
  33. package/dist/routes/auth/mobile/getMobileSessionExpiry.js +18 -0
  34. package/dist/routes/auth/mobile/getMobileSignInReturnUrl.js +31 -0
  35. package/dist/routes/auth/mobile/getOneTimeTokenIdentifiers.js +26 -0
  36. package/dist/routes/auth/mobile/handleMobileSignIn.js +303 -0
  37. package/dist/routes/auth/mobile/handleMobileSignInCallback.js +30 -0
  38. package/dist/routes/auth/mobile/isNativeAuthRequest.js +33 -0
  39. package/dist/routes/auth/mobile/matchesCodeChallenge.js +29 -0
  40. package/dist/routes/auth/mobile/mintOneTimeToken.js +41 -0
  41. package/dist/routes/auth/mobile/readDeviceKeyHash.js +34 -0
  42. package/dist/routes/auth/mobile/readMobileSignInParams.js +90 -0
  43. package/dist/routes/auth/mobile/sha256Base64Url.js +22 -0
  44. package/dist/routes/auth/mobile/storeCodeChallenge.js +29 -0
  45. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +57 -11
  46. package/dist/routes/auth/organizations/checkInvitationContactLink.js +60 -0
  47. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +47 -12
  48. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +41 -189
  49. package/dist/routes/auth/organizations/createAdmissionGateHook.js +5 -5
  50. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +40 -16
  51. package/dist/routes/auth/organizations/createBeforeAcceptInvitationHook.js +35 -0
  52. package/dist/routes/auth/organizations/createBeforeCreateInvitationHook.js +62 -0
  53. package/dist/routes/auth/organizations/createBeforeUpdateMemberRoleHook.js +45 -0
  54. package/dist/routes/auth/organizations/createEmailSendGate.js +35 -7
  55. package/dist/routes/auth/organizations/createSuspendedMemberGate.js +146 -0
  56. package/dist/routes/auth/organizations/createSuspendedOrganizationsFilter.js +44 -0
  57. package/dist/routes/auth/organizations/ensureAuthIndexes.js +11 -10
  58. package/dist/routes/auth/organizations/getOrganizationBinding.js +4 -2
  59. package/dist/routes/auth/organizations/isActiveMember.js +26 -0
  60. package/dist/routes/auth/organizations/isEmailAdmitted.js +25 -14
  61. package/dist/routes/auth/organizations/memberRowsLimit.js +19 -0
  62. package/dist/routes/auth/organizations/mintOrganization.js +258 -0
  63. package/dist/routes/auth/organizations/organizationAccessControl.js +5 -1
  64. package/dist/routes/auth/organizations/provisionOrganization.js +117 -0
  65. package/dist/routes/auth/organizations/readSuspendedOrganizationIds.js +36 -0
  66. package/dist/routes/auth/requestHooks/buildRequestHooks.js +78 -2
  67. package/dist/routes/auth/requestHooks/createEmailCodeHolderGate.js +58 -0
  68. package/dist/routes/auth/requestHooks/createEmailSendLimit.js +116 -0
  69. package/dist/routes/auth/requestHooks/createSignInRefusedRedirectHook.js +75 -0
  70. package/dist/routes/auth/requestHooks/holdEmailCode.js +80 -0
  71. package/dist/routes/auth/requestHooks/reserveSendSlot.js +70 -0
  72. package/dist/routes/auth/runReportingFaults.js +32 -0
  73. package/dist/routes/connections/resolveUnwalledReach.js +14 -16
  74. package/dist/routes/endpoints/callEndpoint.js +6 -3
  75. package/dist/routes/endpoints/control/controlFor.js +9 -6
  76. package/dist/routes/endpoints/control/controlIf.js +8 -3
  77. package/dist/routes/endpoints/control/controlLog.js +3 -1
  78. package/dist/routes/endpoints/control/controlParallelFor.js +9 -6
  79. package/dist/routes/endpoints/control/controlReturn.js +3 -2
  80. package/dist/routes/endpoints/control/controlSetState.js +1 -1
  81. package/dist/routes/endpoints/control/controlSwitch.js +6 -3
  82. package/dist/routes/endpoints/control/controlWhile.js +6 -3
  83. package/dist/routes/endpoints/createLinkAnswer.js +76 -0
  84. package/dist/routes/endpoints/dispatchDetached.js +38 -0
  85. package/dist/routes/endpoints/forwardScheduledEndpoint.js +32 -11
  86. package/dist/routes/endpoints/handleAgentCall.js +1 -1
  87. package/dist/routes/endpoints/handleAuthStep.js +19 -4
  88. package/dist/routes/endpoints/handleEndpointCall.js +6 -4
  89. package/dist/routes/endpoints/handleRequest.js +3 -2
  90. package/dist/routes/endpoints/handleValidateDynamic.js +1 -1
  91. package/dist/routes/endpoints/matchLinkEndpoint.js +30 -0
  92. package/dist/routes/endpoints/runLinkEndpoint.js +148 -0
  93. package/dist/routes/endpoints/runRoutine.js +5 -5
  94. package/dist/routes/endpoints/scheduleBackground.js +13 -11
  95. package/dist/routes/endpoints/test/runTest.js +30 -11
  96. package/dist/routes/mcp/createMcpServer.js +2 -7
  97. package/dist/routes/mcp/runAfterToolCall.js +9 -3
  98. package/dist/routes/mobile/createAppleAppSiteAssociation.js +51 -0
  99. package/dist/routes/mobile/createAssetLinks.js +38 -0
  100. package/dist/routes/mobile/filterMobileMenus.js +31 -0
  101. package/dist/routes/mobile/getMobileAppEvents.js +23 -0
  102. package/dist/routes/mobile/getMobileRootConfig.js +109 -0
  103. package/dist/routes/mobile/getOpenablePageIds.js +21 -0
  104. package/dist/routes/page/dynamic/policy/checkAction.js +67 -2
  105. package/dist/routes/page/dynamic/policy/checkEvents.js +8 -2
  106. package/dist/routes/page/dynamic/policy/checkPolicy.js +86 -6
  107. package/dist/routes/page/dynamic/policy/checkValue.js +97 -6
  108. package/dist/routes/page/dynamic/policy/collectSchemaKinds.js +173 -0
  109. package/dist/routes/page/dynamic/policy/findDataRows.js +94 -0
  110. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +24 -12
  111. package/dist/routes/page/dynamic/policy/findHtmlUrls.js +64 -0
  112. package/dist/routes/page/dynamic/policy/overlapsStatePath.js +28 -0
  113. package/dist/routes/page/dynamic/resolveDynamicContent.js +23 -17
  114. package/dist/routes/page/getPageConfig.js +25 -1
  115. package/dist/routes/request/callRequestResolver.js +29 -36
  116. package/dist/routes/request/stampTypedError.js +37 -0
  117. package/dist/routes/request/summarisedError.js +62 -0
  118. package/dist/routes/request/wrapResolverError.js +61 -0
  119. package/dist/routes/websocket/checkWebsocketAccess.js +81 -0
  120. package/dist/routes/websocket/createChannelRegistry.js +62 -17
  121. package/dist/routes/websocket/createWebSocketConnection.js +59 -21
  122. package/dist/routes/websocket/prepareChannel.js +11 -0
  123. package/dist/test/createMemoryAuth.js +125 -0
  124. package/package.json +20 -22
  125. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +0 -117
  126. package/dist/routes/request/maskCredentialProperties.js +0 -34
@@ -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;
@@ -0,0 +1,32 @@
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 { isExpectedError } from '@lowdefy/errors';
16
+ // Runs work BetterAuth calls back into (an auth email send) in a system context, and reports
17
+ // a fault through that context's error sink before it propagates. BetterAuth runs some of these
18
+ // as background tasks, where it only writes its own "Failed to run background task" line; the
19
+ // sink resolves the config location and sends the fault to error tracking. The error is marked
20
+ // handled, so that line and createOnAPIError do not report it again. An expected outcome
21
+ // propagates without a report.
22
+ async function runReportingFaults({ context, run }) {
23
+ try {
24
+ return await run();
25
+ } catch (error) {
26
+ if (!isExpectedError(error)) {
27
+ await context.handleError(error);
28
+ }
29
+ throw error;
30
+ }
31
+ }
32
+ export default runReportingFaults;
@@ -30,8 +30,8 @@ import createReadConfigFile from '../../context/createReadConfigFile.js';
30
30
  // match. A walled connection's database name is its databaseName property,
31
31
  // falling back to the path of its URI.
32
32
  //
33
- // The result maps each reaching connection id to the refusal message, logged
34
- // once when the check runs. checkUnwalledReach throws it as a ConfigError on
33
+ // The result maps each reaching connection id to the refusal message, reported
34
+ // once, through handleError at the connection's config location, when the check runs. checkUnwalledReach throws it as a ConfigError on
35
35
  // that connection's requests; every other connection is served. The check reads config and
36
36
  // secrets only, so it runs once per config build artifact, independent of the
37
37
  // tenant preflight's database probes. A check that throws is not memoized.
@@ -66,9 +66,9 @@ function collectUris(value, uris) {
66
66
  }
67
67
  return uris;
68
68
  }
69
- async function evaluateConnectionProperties({ connectionId, evaluateOperators, readConfigFile }) {
70
- const connectionConfig = await readConfigFile(`connections/${connectionId}.json`);
69
+ async function evaluateConnectionProperties({ connectionConfig, evaluateOperators }) {
71
70
  if (!connectionConfig) return null;
71
+ const { connectionId } = connectionConfig;
72
72
  try {
73
73
  return evaluateOperators({
74
74
  input: connectionConfig.properties ?? {},
@@ -86,9 +86,8 @@ async function collectWalledDatabases({ evaluateOperators, readConfigFile }) {
86
86
  const walled = new Map();
87
87
  for (const entry of tenantConnections ?? []){
88
88
  const properties = await evaluateConnectionProperties({
89
- connectionId: entry.connectionId,
90
- evaluateOperators,
91
- readConfigFile
89
+ connectionConfig: await readConfigFile(`connections/${entry.connectionId}.json`),
90
+ evaluateOperators
92
91
  });
93
92
  const parsed = parseMongoUri(properties?.databaseUri);
94
93
  if (!parsed) continue;
@@ -115,19 +114,18 @@ async function findUnwalledReach(context) {
115
114
  });
116
115
  if (walled.size === 0) return reach;
117
116
  for (const entry of unwalledConnections){
117
+ const connectionConfig = await readConfigFile(`connections/${entry.connectionId}.json`);
118
118
  const properties = await evaluateConnectionProperties({
119
- connectionId: entry.connectionId,
120
- evaluateOperators,
121
- readConfigFile
119
+ connectionConfig,
120
+ evaluateOperators
122
121
  });
123
122
  const reached = collectUris(properties, []).find(({ hosts, database })=>walled.has(`${hosts}/${database}`));
124
123
  if (!reached) continue;
125
- const error = new ConfigError(`Connection "${entry.connectionId}" (${entry.type}) holds a URI to the database of walled connection "${walled.get(`${reached.hosts}/${reached.database}`)}". Unwalled connections must not reach walled data: give the plugin a mongoConnectionId and use the walled MongoDB client (@lowdefy/connection-mongodb/walled). Requests on this connection are refused.`);
126
- context.logger.error({
127
- err: error,
128
- event: 'unwalled_reach',
129
- connectionId: entry.connectionId
130
- }, error.message);
124
+ const error = new ConfigError(`Connection "${entry.connectionId}" (${entry.type}) holds a URI to the database of walled connection "${walled.get(`${reached.hosts}/${reached.database}`)}". Unwalled connections must not reach walled data: give the plugin a mongoConnectionId and use the walled MongoDB client (@lowdefy/connection-mongodb/walled). Requests on this connection are refused.`, {
125
+ configKey: connectionConfig['~k']
126
+ });
127
+ error.connectionId = entry.connectionId;
128
+ await context.handleError(error);
131
129
  reach.set(entry.connectionId, error.message);
132
130
  }
133
131
  return reach;
@@ -27,12 +27,13 @@ async function callEndpoint(context, { blockId, endpointId, outsideCaller = fals
27
27
  context.endpointId = endpointId;
28
28
  context.pageId = pageId;
29
29
  context.evaluateOperators = createEvaluateOperators(context);
30
+ // Ids only: a payload can carry chat text or other personal information (an agent
31
+ // chat's save-thread call sends the whole thread), which no log level may hold.
30
32
  logger.debug({
31
33
  event: 'debug_endpoint',
32
34
  blockId,
33
35
  endpointId,
34
- pageId,
35
- payload
36
+ pageId
36
37
  });
37
38
  const endpointConfig = await getEndpointConfig(context, {
38
39
  endpointId
@@ -40,7 +41,9 @@ async function callEndpoint(context, { blockId, endpointId, outsideCaller = fals
40
41
  // Block HTTP access to InternalApi endpoints - same error as a missing
41
42
  // endpoint, including the guarded unauthenticated fork, so an internal
42
43
  // endpoint is indistinguishable from one that does not exist on both paths.
43
- if (endpointConfig.type === 'InternalApi') {
44
+ // A link endpoint answers only the GET route (runLinkEndpoint), so a POST or
45
+ // MCP call to it is refused the same way.
46
+ if (endpointConfig.type === 'InternalApi' || endpointConfig.link === true) {
44
47
  const unauthenticatedHuman = type.isNone(context.user) && !type.isNone(context.authEnforcement) && context.system !== true;
45
48
  const err = unauthenticatedHuman ? new AuthenticationError(`Authentication required for API endpoint "${endpointId}".`) : new ConfigError(`API Endpoint "${endpointId}" does not exist.`);
46
49
  logger.debug({
@@ -20,7 +20,9 @@ async function controlFor(context, routineContext, { control }) {
20
20
  const { items } = routineContext;
21
21
  const itemName = control[':for'];
22
22
  if (!itemName) {
23
- throw new Error(`Invalid :for in endpoint "${endpointId}" - missing variable name in :for.`);
23
+ throw new ConfigError(`Invalid :for in endpoint "${endpointId}" - missing variable name in :for.`, {
24
+ configKey: control['~k']
25
+ });
24
26
  }
25
27
  const array = evaluateRoutineOperators(context, routineContext, {
26
28
  input: control[':in'],
@@ -28,7 +30,7 @@ async function controlFor(context, routineContext, { control }) {
28
30
  });
29
31
  logger.debug({
30
32
  event: 'debug_control_for',
31
- array,
33
+ itemCount: Array.isArray(array) ? array.length : null,
32
34
  itemName
33
35
  });
34
36
  if (!Array.isArray(array)) {
@@ -38,7 +40,9 @@ async function controlFor(context, routineContext, { control }) {
38
40
  });
39
41
  }
40
42
  if (!control[':do']) {
41
- throw new Error(`Invalid :for in endpoint "${endpointId}" - missing :do.`);
43
+ throw new ConfigError(`Invalid :for in endpoint "${endpointId}" - missing :do.`, {
44
+ configKey: control['~k']
45
+ });
42
46
  }
43
47
  for (const [index, item] of array.entries()){
44
48
  const updatedItems = {
@@ -47,9 +51,8 @@ async function controlFor(context, routineContext, { control }) {
47
51
  };
48
52
  logger.debug({
49
53
  event: 'debug_control_for_iteration',
50
- itemName: itemName,
51
- value: item,
52
- items: updatedItems
54
+ itemName,
55
+ index
53
56
  });
54
57
  const res = await runRoutine(context, {
55
58
  ...routineContext,
@@ -12,7 +12,8 @@
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 runRoutine from '../runRoutine.js';
15
+ */ import { ConfigError } from '@lowdefy/errors';
16
+ import runRoutine from '../runRoutine.js';
16
17
  import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
17
18
  async function controlIf(context, routineContext, { control }) {
18
19
  const { endpointId, logger } = context;
@@ -20,11 +21,13 @@ async function controlIf(context, routineContext, { control }) {
20
21
  input: control[':if'],
21
22
  location: control['~k'] ?? ':if'
22
23
  });
24
+ // No evaluated values: they can carry chat text or other personal information,
25
+ // which no log level may hold.
23
26
  logger.debug({
24
27
  event: 'debug_control_if',
25
28
  condition: {
26
29
  input: control[':if'],
27
- evaluated: evaluatedIf
30
+ result: Boolean(evaluatedIf)
28
31
  }
29
32
  });
30
33
  if (evaluatedIf) {
@@ -32,7 +35,9 @@ async function controlIf(context, routineContext, { control }) {
32
35
  event: 'debug_control_if_run_then'
33
36
  });
34
37
  if (!control[':then']) {
35
- throw new Error(`Invalid :if in endpoint "${endpointId}" - missing :then.`);
38
+ throw new ConfigError(`Invalid :if in endpoint "${endpointId}" - missing :then.`, {
39
+ configKey: control['~k']
40
+ });
36
41
  }
37
42
  return runRoutine(context, routineContext, {
38
43
  routine: control[':then']
@@ -36,7 +36,9 @@ async function controlLog(context, routineContext, { control }) {
36
36
  });
37
37
  }
38
38
  if (!logger[logLevel]) {
39
- throw new Error(`Invalid :log in endpoint "${endpointId}" - unrecognised log level. Received "${logLevel}".`);
39
+ throw new ConfigError(`Invalid :log in endpoint "${endpointId}" - unrecognised log level. Received "${logLevel}".`, {
40
+ configKey: control['~k']
41
+ });
40
42
  }
41
43
  logger[logLevel](log);
42
44
  return {
@@ -43,7 +43,9 @@ async function controlParallelFor(context, routineContext, { control }) {
43
43
  const { items } = routineContext;
44
44
  const itemName = control[':parallel_for'];
45
45
  if (!itemName) {
46
- throw new Error(`Invalid :parallel_for in endpoint "${endpointId}" - missing variable name in :parallel_for.`);
46
+ throw new ConfigError(`Invalid :parallel_for in endpoint "${endpointId}" - missing variable name in :parallel_for.`, {
47
+ configKey: control['~k']
48
+ });
47
49
  }
48
50
  const array = evaluateRoutineOperators(context, routineContext, {
49
51
  input: control[':in'],
@@ -51,7 +53,7 @@ async function controlParallelFor(context, routineContext, { control }) {
51
53
  });
52
54
  logger.debug({
53
55
  event: 'debug_control_parallel',
54
- array,
56
+ itemCount: Array.isArray(array) ? array.length : null,
55
57
  itemName
56
58
  });
57
59
  if (!Array.isArray(array)) {
@@ -61,7 +63,9 @@ async function controlParallelFor(context, routineContext, { control }) {
61
63
  });
62
64
  }
63
65
  if (!control[':do']) {
64
- throw new Error(`Invalid :parallel_for in endpoint "${endpointId}" - missing :do.`);
66
+ throw new ConfigError(`Invalid :parallel_for in endpoint "${endpointId}" - missing :do.`, {
67
+ configKey: control['~k']
68
+ });
65
69
  }
66
70
  const concurrency = evaluateRoutineOperators(context, routineContext, {
67
71
  input: control[':concurrency'],
@@ -86,9 +90,8 @@ async function controlParallelFor(context, routineContext, { control }) {
86
90
  };
87
91
  logger.debug({
88
92
  event: 'debug_control_parallel_iteration',
89
- itemName: itemName,
90
- value: item,
91
- items: updatedItems
93
+ itemName,
94
+ index
92
95
  });
93
96
  return runRoutine(context, {
94
97
  ...routineContext,