@lowdefy/api 0.0.0-experimental-20260720072521 → 0.0.0-experimental-20260720135014

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 (97) hide show
  1. package/dist/context/createApiContext.js +1 -9
  2. package/dist/context/createAuthorize.js +8 -19
  3. package/dist/context/createEvaluateOperators.js +1 -2
  4. package/dist/index.js +3 -13
  5. package/dist/routes/agent/callAgent.js +180 -7
  6. package/dist/routes/{websocket/authorizeWebsocket.js → auth/callbacks/addUserFieldsToSession.js} +11 -10
  7. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +30 -0
  8. package/dist/routes/auth/{hooks/composeAfterSlot.js → callbacks/createCallbackPlugins.js} +6 -11
  9. package/dist/routes/auth/callbacks/createCallbacks.js +46 -0
  10. package/dist/routes/auth/callbacks/createJWTCallback.js +77 -0
  11. package/dist/routes/auth/callbacks/createRedirectCallback.js +41 -0
  12. package/dist/routes/auth/callbacks/createSessionCallback.js +81 -0
  13. package/dist/routes/auth/callbacks/createSignInCallback.js +40 -0
  14. package/dist/routes/auth/callbacks/validateSessionRoles.js +33 -0
  15. package/dist/routes/{websocket/getWebsocketConfig.js → auth/createAdapter.js} +8 -14
  16. package/dist/routes/auth/createLogger.js +38 -0
  17. package/dist/routes/auth/createProviders.js +25 -0
  18. package/dist/routes/auth/events/createCreateUserEvent.js +41 -0
  19. package/dist/routes/auth/{organizations/getHookRequestHeaders.js → events/createEventPlugins.js} +6 -9
  20. package/dist/routes/auth/events/createEvents.js +56 -0
  21. package/dist/routes/auth/events/createLinkAccountEvent.js +43 -0
  22. package/dist/routes/auth/{strategies/getAuthStrategies.js → events/createSessionEvent.js} +17 -14
  23. package/dist/routes/auth/events/createSignInEvent.js +46 -0
  24. package/dist/routes/auth/events/createSignOutEvent.js +43 -0
  25. package/dist/routes/auth/events/createUpdateUserEvent.js +41 -0
  26. package/dist/routes/auth/getNextAuthConfig.js +75 -0
  27. package/dist/routes/endpoints/authorizeApiEndpoint.js +2 -8
  28. package/dist/routes/endpoints/callEndpoint.js +0 -20
  29. package/dist/routes/endpoints/control/controlReject.js +1 -3
  30. package/dist/routes/endpoints/control/controlThrow.js +1 -4
  31. package/dist/routes/endpoints/handleEndpointCall.js +1 -62
  32. package/dist/routes/endpoints/handleRequest.js +1 -8
  33. package/dist/routes/endpoints/handleValidateSchema.js +1 -3
  34. package/dist/routes/endpoints/runRoutine.js +0 -18
  35. package/dist/routes/endpoints/test/runTest.js +4 -3
  36. package/dist/routes/page/getPageConfig.js +8 -42
  37. package/dist/routes/request/authorizeRequest.js +2 -8
  38. package/dist/routes/request/callRequest.js +1 -8
  39. package/dist/routes/request/callRequestResolver.js +2 -6
  40. package/dist/test/testContext.js +6 -6
  41. package/package.json +10 -16
  42. package/dist/context/applySystemTrust.js +0 -33
  43. package/dist/context/createSystemContext.js +0 -72
  44. package/dist/context/normalizeInjectedCaller.js +0 -41
  45. package/dist/context/resolveAuthentication.js +0 -107
  46. package/dist/context/resolveStrategyCaller.js +0 -56
  47. package/dist/email/renderAuthEmail.js +0 -98
  48. package/dist/email/resolveThemeLogo.js +0 -35
  49. package/dist/routes/agent/prepareAgent.js +0 -169
  50. package/dist/routes/auth/buildAdminPlugin.js +0 -55
  51. package/dist/routes/auth/buildCaptchaPlugin.js +0 -61
  52. package/dist/routes/auth/buildPhoneNumberPlugin.js +0 -57
  53. package/dist/routes/auth/buildProviders.js +0 -51
  54. package/dist/routes/auth/createAuthLogger.js +0 -31
  55. package/dist/routes/auth/createSendEmail.js +0 -49
  56. package/dist/routes/auth/getBetterAuth.js +0 -72
  57. package/dist/routes/auth/getBetterAuthConfig.js +0 -439
  58. package/dist/routes/auth/getUserAdminRole.js +0 -32
  59. package/dist/routes/auth/hooks/authHookPoints.js +0 -192
  60. package/dist/routes/auth/hooks/buildEngineHooks.js +0 -43
  61. package/dist/routes/auth/hooks/buildHooks.js +0 -111
  62. package/dist/routes/auth/hooks/composeBeforeSlot.js +0 -41
  63. package/dist/routes/auth/hooks/createHookDispatch.js +0 -59
  64. package/dist/routes/auth/hooks/createUserAfterHook.js +0 -33
  65. package/dist/routes/auth/hooks/createUserBeforeHook.js +0 -47
  66. package/dist/routes/auth/hooks/findHookUser.js +0 -27
  67. package/dist/routes/auth/modelNames.js +0 -29
  68. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +0 -136
  69. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +0 -211
  70. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +0 -75
  71. package/dist/routes/auth/organizations/createAutoJoinHook.js +0 -63
  72. package/dist/routes/auth/organizations/ensureOrganization.js +0 -95
  73. package/dist/routes/auth/organizations/findPendingInvitation.js +0 -43
  74. package/dist/routes/auth/organizations/getOrganizationBinding.js +0 -65
  75. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +0 -48
  76. package/dist/routes/auth/organizations/syncUserAdminRole.js +0 -102
  77. package/dist/routes/auth/resolveCookiePrefix.js +0 -30
  78. package/dist/routes/auth/strategies/createAuthStrategies.js +0 -77
  79. package/dist/routes/endpoints/handleAgentCall.js +0 -83
  80. package/dist/routes/endpoints/handleAuthStep.js +0 -124
  81. package/dist/routes/endpoints/handleRenderNotification.js +0 -189
  82. package/dist/routes/endpoints/runDetachedEndpoint.js +0 -85
  83. package/dist/routes/endpoints/runScheduledEndpoint.js +0 -102
  84. package/dist/routes/endpoints/runWebhookEndpoint.js +0 -118
  85. package/dist/routes/endpoints/runWebhookVerify.js +0 -94
  86. package/dist/routes/endpoints/scheduleBackground.js +0 -48
  87. package/dist/routes/notifications/derivePreview.js +0 -30
  88. package/dist/routes/notifications/getNotificationConfig.js +0 -32
  89. package/dist/routes/notifications/resolveNotificationLinks.js +0 -72
  90. package/dist/routes/page/dynamic/resolveDynamicContent.js +0 -172
  91. package/dist/routes/page/dynamic/unescapeOperators.js +0 -36
  92. package/dist/routes/page/dynamic/validateFragment.js +0 -104
  93. package/dist/routes/request/resolveTenant.js +0 -57
  94. package/dist/routes/websocket/createChannelRegistry.js +0 -278
  95. package/dist/routes/websocket/createWebSocketConnection.js +0 -131
  96. package/dist/routes/websocket/getWebsocketResolver.js +0 -33
  97. package/dist/routes/websocket/prepareChannel.js +0 -84
@@ -1,56 +0,0 @@
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
- // Tries the configured API auth strategies in config order; the first
17
- // verifier match wins. A strategy caller is a config-derived, org-less
18
- // principal: roles are the strategy's static grant unioned with any
19
- // claim-derived roles, and attributes are the static bag shallow-merged
20
- // with claim-mapped values (claim wins), so _user.attributes reads the same
21
- // for session and strategy callers.
22
- async function resolveStrategyCaller({ headers, logger, strategies }) {
23
- for (const strategy of strategies ?? []){
24
- const match = await strategy.verify({
25
- headers,
26
- logger
27
- });
28
- if (type.isNone(match)) {
29
- continue;
30
- }
31
- const roles = [
32
- ...new Set([
33
- ...strategy.roles,
34
- ...match.roles ?? []
35
- ])
36
- ];
37
- const attributes = {
38
- ...strategy.attributes,
39
- ...match.attributes ?? {}
40
- };
41
- logger.debug({
42
- event: 'auth_strategy_authenticated',
43
- authMethod: strategy.type,
44
- strategyId: strategy.id
45
- }, `Request authenticated by auth strategy "${strategy.id}" (${strategy.type}).`);
46
- return {
47
- ...match.user,
48
- authMethod: strategy.type,
49
- strategyId: strategy.id,
50
- roles,
51
- attributes
52
- };
53
- }
54
- return null;
55
- }
56
- export default resolveStrategyCaller;
@@ -1,98 +0,0 @@
1
- /*
2
- Copyright 2020-2026 Lowdefy, Inc
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */ import { ConfigError } from '@lowdefy/errors';
16
- import { type } from '@lowdefy/helpers';
17
- import { InvitationEmail, MagicLinkEmail, ResetPasswordEmail, VerifyEmail, interpolateProperties, renderEmail } from '@lowdefy/email-templates';
18
- import getNotificationConfig from '../routes/notifications/getNotificationConfig.js';
19
- import resolveThemeLogo from './resolveThemeLogo.js';
20
- const stockTemplates = {
21
- verifyEmail: VerifyEmail,
22
- resetPassword: ResetPasswordEmail,
23
- magicLink: MagicLinkEmail,
24
- invitation: InvitationEmail
25
- };
26
- // Single render path for the four auth email flows. Resolves the flow's template
27
- // (a stock component by default, or an app-configured override notification when
28
- // auth.email.templates[flow] names one), applies the app.email brand, and returns
29
- // { subject, html, text }. Pure render — it never sends.
30
- async function renderAuthEmail({ flow, vars, authEmailConfig, baseURL, context }) {
31
- const app = await context.readConfigFile('app.json') ?? {};
32
- const basePath = context.config?.basePath ?? '';
33
- // baseURL is the pinned origin the caller resolved; without a usable origin
34
- // string relative logos cannot be fetched by an email client, so they drop.
35
- const serverUrl = type.isString(baseURL) ? baseURL : undefined;
36
- const notificationId = authEmailConfig?.templates?.[flow];
37
- if (type.isString(notificationId)) {
38
- const notificationConfig = await getNotificationConfig(context, {
39
- notificationId
40
- });
41
- const Template = context.notifications?.[notificationConfig.type];
42
- if (!Template) {
43
- throw new ConfigError(`Notification template type "${notificationConfig.type}" can not be found.`, {
44
- configKey: notificationConfig['~k']
45
- });
46
- }
47
- // Resolve after the merge so a per-notification theme.logo override also
48
- // resolves; precedence stays notification theme over app.email.
49
- const theme = resolveThemeLogo({
50
- theme: {
51
- ...app.email ?? {},
52
- ...notificationConfig.theme ?? {}
53
- },
54
- serverUrl,
55
- basePath
56
- });
57
- const interpolated = interpolateProperties({
58
- properties: notificationConfig.properties,
59
- data: vars,
60
- markdownProperties: Template.markdownProperties ?? []
61
- });
62
- const { html, text } = await renderEmail({
63
- Template,
64
- properties: interpolated,
65
- data: vars,
66
- theme,
67
- links: {}
68
- });
69
- return {
70
- subject: interpolated.subject,
71
- html,
72
- text
73
- };
74
- }
75
- const Template = stockTemplates[flow];
76
- if (!Template) {
77
- throw new ConfigError(`Unknown auth email flow "${flow}".`);
78
- }
79
- const theme = resolveThemeLogo({
80
- theme: app.email ?? {},
81
- serverUrl,
82
- basePath
83
- });
84
- const { html, text } = await renderEmail({
85
- Template,
86
- properties: vars,
87
- data: vars,
88
- theme,
89
- links: {}
90
- });
91
- const subject = type.isFunction(Template.subject) ? Template.subject(vars) : Template.subject;
92
- return {
93
- subject,
94
- html,
95
- text
96
- };
97
- }
98
- export default renderAuthEmail;
@@ -1,35 +0,0 @@
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
- // A theme logo written as an app-relative path ("/logo.png", a public/ asset)
17
- // resolves against the deployment's serverUrl + basePath, so one config works
18
- // across environments. Absolute ("https://...") and protocol-relative ("//...")
19
- // URLs pass through. Without a serverUrl an email client can never fetch a
20
- // relative path, so the logo is dropped — EmailLayout falls back to the
21
- // companyName text header, which beats a broken image.
22
- function resolveThemeLogo({ theme, serverUrl, basePath }) {
23
- const { logo, ...rest } = theme;
24
- if (!type.isString(logo) || !logo.startsWith('/') || logo.startsWith('//')) {
25
- return theme;
26
- }
27
- if (type.isNone(serverUrl)) {
28
- return rest;
29
- }
30
- return {
31
- ...rest,
32
- logo: `${serverUrl}${basePath}${logo}`
33
- };
34
- }
35
- export default resolveThemeLogo;
@@ -1,169 +0,0 @@
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 { serializer, type } from '@lowdefy/helpers';
16
- import getEndpointConfig from '../endpoints/getEndpointConfig.js';
17
- import invokeEndpoint from '../endpoints/invokeEndpoint.js';
18
- import getAgentConfig from './getAgentConfig.js';
19
- import getAgentResolver from './getAgentResolver.js';
20
- import getConnectionConfig from '../connections/getConnectionConfig.js';
21
- import getConnection from '../connections/getConnection.js';
22
- // Shared agent invocation construction for the streaming chat route (callAgent)
23
- // and the headless CallAgent routine step (handleAgentCall): loads the agent
24
- // config, evaluates operators, creates the provider connection, and builds the
25
- // resolver context. mode ('chat' | 'generate') selects the resolver's execution
26
- // path; endpointDepth threads the endpoint call depth cap through agent tool
27
- // and hook endpoint calls.
28
- async function prepareAgent(context, { agentId, agentContext, endpointDepth = 0, mode = 'chat' }) {
29
- const agentConfig = await getAgentConfig(context, {
30
- agentId
31
- });
32
- // Evaluate operators in agent properties (e.g. _user, _secret, _payload)
33
- agentConfig.properties = context.evaluateOperators({
34
- input: agentConfig.properties ?? {},
35
- location: agentConfig.agentId,
36
- payload: agentContext,
37
- state: {},
38
- steps: {}
39
- });
40
- // Load connection config from build artifacts using agent's connectionId
41
- const connectionConfig = await getConnectionConfig(context, {
42
- connectionId: agentConfig.connectionId,
43
- configKey: agentConfig['~k']
44
- });
45
- // Get connection plugin from registry
46
- const connection = getConnection(context, {
47
- connectionConfig
48
- });
49
- // Evaluate operators in connection properties
50
- const connectionProperties = context.evaluateOperators({
51
- input: connectionConfig.properties || {},
52
- location: connectionConfig.connectionId,
53
- payload: {},
54
- state: {},
55
- steps: {}
56
- });
57
- // Create connection instance (e.g., Anthropic provider)
58
- const connectionInstance = connection.create({
59
- connection: connectionProperties
60
- });
61
- // Get agent type from plugin registry
62
- const agentType = getAgentResolver(context, {
63
- agentConfig
64
- });
65
- // Build resolver context with callEndpoint that allows InternalApi endpoints
66
- const resolverContext = {
67
- agentContext,
68
- i18n: context.i18n,
69
- mode,
70
- evaluateOperators: (input)=>context.evaluateOperators({
71
- input,
72
- location: agentConfig.agentId,
73
- payload: agentContext,
74
- state: {},
75
- steps: {}
76
- }),
77
- callEndpoint: async (endpointId, { payload })=>{
78
- const { error, response, status } = await invokeEndpoint(context, {
79
- endpointId,
80
- payload,
81
- endpointDepth
82
- });
83
- const success = ![
84
- 'error',
85
- 'reject'
86
- ].includes(status);
87
- return {
88
- error: serializer.serialize(error),
89
- response: serializer.serialize(response),
90
- status: success ? 'success' : status,
91
- success
92
- };
93
- },
94
- getEndpointConfig: async ({ endpointId })=>{
95
- return getEndpointConfig(context, {
96
- endpointId
97
- });
98
- },
99
- getAgentConfig: async ({ agentId: subAgentId })=>{
100
- return getAgentConfig(context, {
101
- agentId: subAgentId
102
- });
103
- },
104
- getConnectionForAgent: async ({ agentConfig: subAgentConfig })=>{
105
- const subConnectionConfig = await getConnectionConfig(context, {
106
- connectionId: subAgentConfig.connectionId,
107
- configKey: subAgentConfig['~k']
108
- });
109
- const subConnection = getConnection(context, {
110
- connectionConfig: subConnectionConfig
111
- });
112
- const subConnectionProperties = context.evaluateOperators({
113
- input: subConnectionConfig.properties || {},
114
- location: subConnectionConfig.connectionId,
115
- payload: {},
116
- state: {},
117
- steps: {}
118
- });
119
- return subConnection.create({
120
- connection: subConnectionProperties
121
- });
122
- },
123
- resolveMcpSources: async ({ agentConfig: subAgentConfig })=>{
124
- const resolvedMcp = [];
125
- for (const mcpSource of subAgentConfig.mcp ?? []){
126
- if (!type.isNone(mcpSource.connectionId)) {
127
- const mcpConnConfig = await getConnectionConfig(context, {
128
- connectionId: mcpSource.connectionId,
129
- configKey: subAgentConfig['~k']
130
- });
131
- const mcpConnection = getConnection(context, {
132
- connectionConfig: mcpConnConfig
133
- });
134
- const mcpConnProps = context.evaluateOperators({
135
- input: mcpConnConfig.properties || {},
136
- location: mcpConnConfig.connectionId,
137
- payload: {},
138
- state: {},
139
- steps: {}
140
- });
141
- const mcpConfig = mcpConnection.create({
142
- connection: mcpConnProps
143
- });
144
- const { connectionId: _, ...overrides } = mcpSource;
145
- resolvedMcp.push({
146
- ...mcpConfig,
147
- ...overrides
148
- });
149
- } else {
150
- resolvedMcp.push(mcpSource);
151
- }
152
- }
153
- return resolvedMcp;
154
- }
155
- };
156
- // Resolve MCP connection references to inline config.
157
- // Agent-level overrides (like confirm) may still contain operators —
158
- // handleAgentChat evaluates those via its existing evaluateOperators call.
159
- agentConfig.mcp = await resolverContext.resolveMcpSources({
160
- agentConfig
161
- });
162
- return {
163
- agentConfig,
164
- connectionInstance,
165
- agentType,
166
- resolverContext
167
- };
168
- }
169
- export default prepareAgent;
@@ -1,55 +0,0 @@
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 { admin } from 'better-auth/plugins';
16
- import { createAccessControl } from 'better-auth/plugins/access';
17
- import { adminAc, defaultStatements, userAc } from 'better-auth/plugins/admin/access';
18
- import { type } from '@lowdefy/helpers';
19
- // The admin plugin is framework-controlled - it backs the admin steps and
20
- // impersonation; its banned/banReason/banExpires fields land on the user
21
- // record. When auth.userAdminRole is configured, the plugin registers a
22
- // curated access control in which the user-admin role holds exactly the
23
- // statements backing the shipped client actions - today user: ['impersonate'].
24
- // The full admin statement set (set-password, set-email, ban, delete) is not
25
- // granted, so those /api/auth/admin/* endpoints stay unreachable for the
26
- // role, and impersonate-admins is deliberately excluded - a user-admin cannot
27
- // impersonate another user-admin.
28
- // The built-in "admin" and "user" roles keep their default statements: the
29
- // plugin's roles option replaces rather than merges the defaults, and the
30
- // admin steps inject acting sessions with role "admin" whose authority must
31
- // hold. adminRoles extends to the user-admin role so impersonating a
32
- // user-admin demands the excluded impersonate-admins statement.
33
- function buildAdminPlugin({ authConfig }) {
34
- if (type.isNone(authConfig.userAdminRole)) {
35
- return admin();
36
- }
37
- const ac = createAccessControl(defaultStatements);
38
- return admin({
39
- ac,
40
- adminRoles: [
41
- 'admin',
42
- authConfig.userAdminRole
43
- ],
44
- roles: {
45
- admin: adminAc,
46
- user: userAc,
47
- [authConfig.userAdminRole]: ac.newRole({
48
- user: [
49
- 'impersonate'
50
- ]
51
- })
52
- }
53
- });
54
- }
55
- export default buildAdminPlugin;
@@ -1,61 +0,0 @@
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 { captcha } from 'better-auth/plugins';
16
- import { type } from '@lowdefy/helpers';
17
- import { ConfigError } from '@lowdefy/errors';
18
- // The protected set is computed from the enabled login methods - the union
19
- // of each method's public initiate endpoints, including the message-send
20
- // endpoints that spend money. This deliberately deviates from BetterAuth's
21
- // static default (three email paths), which would leave
22
- // /phone-number/send-otp - the most expensive endpoint and the reason this
23
- // plugin exists - unprotected. Verify/consume endpoints stay uncovered: they
24
- // are guarded by their own single-use, attempt-limited codes, and captcha
25
- // tokens are single-use, so covering them would demand a second token per
26
- // flow.
27
- function computeCaptchaEndpoints({ authConfig }) {
28
- const endpoints = [
29
- '/sign-up/email',
30
- '/sign-in/email',
31
- '/request-password-reset',
32
- '/send-verification-email'
33
- ];
34
- if (authConfig.magicLink?.enabled === true) {
35
- endpoints.push('/sign-in/magic-link');
36
- }
37
- if (authConfig.phoneNumber?.enabled === true) {
38
- endpoints.push('/phone-number/send-otp', '/sign-in/phone-number', '/phone-number/request-password-reset');
39
- }
40
- return endpoints;
41
- }
42
- // Maps auth.captcha onto BetterAuth's captcha plugin - a self-contained
43
- // onRequest middleware that verifies the x-captcha-response header against
44
- // the provider's siteverify API and fails closed. An explicit
45
- // auth.captcha.endpoints replaces the computed set entirely.
46
- function buildCaptchaPlugin({ authConfig }) {
47
- const captchaConfig = authConfig.captcha;
48
- if (!type.isString(captchaConfig.secretKey)) {
49
- throw new ConfigError('Auth "captcha.secretKey" did not resolve to a string. Check the _secret operator reference and that the secret is set.', {
50
- received: type.typeOf(captchaConfig.secretKey)
51
- });
52
- }
53
- return captcha({
54
- provider: captchaConfig.provider,
55
- secretKey: captchaConfig.secretKey,
56
- endpoints: captchaConfig.endpoints ?? computeCaptchaEndpoints({
57
- authConfig
58
- })
59
- });
60
- }
61
- export default buildCaptchaPlugin;
@@ -1,57 +0,0 @@
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 { phoneNumber } from 'better-auth/plugins';
16
- import { type } from '@lowdefy/helpers';
17
- import { ConfigError } from '@lowdefy/errors';
18
- // The wire format is pinned to E.164. BetterAuth's default validator accepts
19
- // any string, which mints several identities for one phone ("+27 83 123 4567",
20
- // "0831234567" and "+27831234567") and spends real money on malformed sends.
21
- // Normalization belongs in the UI's locale-aware input widgets.
22
- const E164_REGEX = /^\+[1-9]\d{1,14}$/;
23
- // Maps auth.phoneNumber onto BetterAuth's phoneNumber plugin. The SMS send
24
- // callbacks are the composed "phone.otp.send" / "phone.passwordReset.send"
25
- // hook slots - build validation guarantees the OTP send binding exists when
26
- // the plugin is enabled, so sendPhoneOtp is always a function here.
27
- function buildPhoneNumberPlugin({ authConfig, phoneVerified, sendPhoneOtp, sendPhonePasswordResetOtp }) {
28
- const phoneNumberConfig = authConfig.phoneNumber;
29
- const options = {
30
- otpLength: phoneNumberConfig.otpLength,
31
- expiresIn: phoneNumberConfig.expiresIn,
32
- allowedAttempts: phoneNumberConfig.allowedAttempts,
33
- requireVerification: phoneNumberConfig.requireVerification,
34
- phoneNumberValidator: (value)=>E164_REGEX.test(value),
35
- sendOTP: sendPhoneOtp,
36
- // BetterAuth's /phone-number/request-password-reset returns
37
- // { status: true } without sending anything when sendPasswordResetOTP is
38
- // not configured - a user asking for a reset would get silence and a 200
39
- // in the logs. Fail loudly naming the fix instead.
40
- sendPasswordResetOTP: sendPhonePasswordResetOtp ?? (()=>{
41
- throw new ConfigError('Password reset over phone is not configured. Bind an InternalApi endpoint to the "phone.passwordReset.send" auth hook point to send reset codes.');
42
- })
43
- };
44
- if (!type.isNone(phoneVerified)) {
45
- options.callbackOnVerification = phoneVerified;
46
- }
47
- if (!type.isNone(phoneNumberConfig.signUpOnVerification)) {
48
- const { tempEmailDomain } = phoneNumberConfig.signUpOnVerification;
49
- options.signUpOnVerification = {
50
- // The E.164 digits with the "+" stripped keep the derived address
51
- // unique per phone; uniqueness is inherited from the phone number's.
52
- getTempEmail: (value)=>`${value.replace(/\D/g, '')}@${tempEmailDomain}`
53
- };
54
- }
55
- return phoneNumber(options);
56
- }
57
- export default buildPhoneNumberPlugin;
@@ -1,51 +0,0 @@
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 { ConfigError } from '@lowdefy/errors';
17
- // Splits the unified auth.providers array into BetterAuth's two shapes:
18
- // built-in providers become socialProviders entries keyed by the BetterAuth
19
- // provider key; GenericOAuth entries become genericOAuth plugin configs
20
- // keyed by the Lowdefy provider id.
21
- function buildProviders({ authConfig, plugins }) {
22
- const socialProviders = {};
23
- const genericOAuthConfigs = [];
24
- (authConfig.providers ?? []).forEach((provider)=>{
25
- const providerPlugin = plugins.providers[provider.type];
26
- if (type.isNone(providerPlugin)) {
27
- throw new ConfigError(`Auth provider type "${provider.type}" not found at provider "${provider.id}".`, {
28
- configKey: provider['~k']
29
- });
30
- }
31
- const definition = providerPlugin({
32
- id: provider.id,
33
- properties: provider.properties ?? {}
34
- });
35
- if (definition.kind === 'generic') {
36
- genericOAuthConfigs.push(definition.config);
37
- return;
38
- }
39
- if (!type.isNone(socialProviders[definition.provider])) {
40
- throw new ConfigError(`Auth provider "${definition.provider}" is configured more than once. BetterAuth supports one configuration per built-in provider.`, {
41
- configKey: provider['~k']
42
- });
43
- }
44
- socialProviders[definition.provider] = definition.options;
45
- });
46
- return {
47
- socialProviders,
48
- genericOAuthConfigs
49
- };
50
- }
51
- export default buildProviders;
@@ -1,31 +0,0 @@
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
- */ // Adapts the Lowdefy logger to BetterAuth's logger contract:
16
- // { disabled, level, log(level, message, ...args) }.
17
- function createAuthLogger({ logger }) {
18
- return {
19
- disabled: false,
20
- level: logger?.isLevelEnabled?.('debug') === true ? 'debug' : 'warn',
21
- log: (level, message, ...args)=>{
22
- const log = logger?.[level] ?? logger?.info;
23
- if (!log) return;
24
- log.call(logger, {
25
- event: 'auth_engine',
26
- args
27
- }, message);
28
- }
29
- };
30
- }
31
- export default createAuthLogger;
@@ -1,49 +0,0 @@
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 send from '@lowdefy/connection-smtp/send';
16
- import { ServiceError } from '@lowdefy/errors';
17
- import getConnectionConfig from '../connections/getConnectionConfig.js';
18
- // auth.email sends every auth email (verification, password reset, magic link)
19
- // through an SMTP connection. Resolving the connection per fire lets operators
20
- // and the connection's delivery filter apply, so failures - and filtering -
21
- // surface here at send time rather than at construction.
22
- function createSendEmail({ connectionId }) {
23
- return async function sendEmail({ to, subject, html, text, context }) {
24
- const connectionConfig = await getConnectionConfig(context, {
25
- connectionId
26
- });
27
- const connection = context.evaluateOperators({
28
- input: connectionConfig.properties ?? {},
29
- location: connectionId
30
- });
31
- try {
32
- return await send({
33
- connection,
34
- mail: {
35
- to,
36
- subject,
37
- html,
38
- text
39
- }
40
- });
41
- } catch (error) {
42
- throw new ServiceError(undefined, {
43
- cause: error,
44
- service: 'SMTP'
45
- });
46
- }
47
- };
48
- }
49
- export default createSendEmail;