@lowdefy/api 0.0.0-experimental-20260909201552 → 0.0.0-experimental-20260911113654

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 (123) hide show
  1. package/dist/context/createApiContext.js +3 -18
  2. package/dist/context/createAuthorize.js +45 -0
  3. package/dist/context/createEvaluateOperators.js +1 -2
  4. package/dist/context/resolveStrategyCaller.js +3 -7
  5. package/dist/index.js +4 -12
  6. package/dist/response/omitErrorProps.js +3 -11
  7. package/dist/routes/agent/authorizeAgent.js +5 -17
  8. package/dist/routes/agent/prepareAgent.js +0 -1
  9. package/dist/routes/auth/{organizations/getHookRequestHeaders.js → callbacks/addUserFieldsToSession.js} +13 -9
  10. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +30 -0
  11. package/dist/routes/auth/{hooks/composeAfterSlot.js → callbacks/createCallbackPlugins.js} +6 -11
  12. package/dist/routes/auth/callbacks/createCallbacks.js +46 -0
  13. package/dist/routes/auth/callbacks/createJWTCallback.js +77 -0
  14. package/dist/routes/auth/callbacks/createRedirectCallback.js +41 -0
  15. package/dist/routes/auth/callbacks/createSessionCallback.js +81 -0
  16. package/dist/routes/auth/callbacks/createSignInCallback.js +40 -0
  17. package/dist/routes/auth/callbacks/validateSessionRoles.js +33 -0
  18. package/dist/routes/auth/{modelNames.js → createAdapter.js} +10 -15
  19. package/dist/routes/auth/createLogger.js +35 -0
  20. package/dist/routes/auth/createPrefixedCookies.js +52 -0
  21. package/dist/routes/auth/createProviders.js +25 -0
  22. package/dist/routes/auth/events/createCreateUserEvent.js +41 -0
  23. package/dist/routes/auth/{createAuthLogger.js → events/createEventPlugins.js} +6 -16
  24. package/dist/routes/auth/events/createEvents.js +56 -0
  25. package/dist/routes/auth/events/createLinkAccountEvent.js +43 -0
  26. package/dist/routes/auth/events/createSessionEvent.js +34 -0
  27. package/dist/routes/auth/events/createSignInEvent.js +46 -0
  28. package/dist/routes/auth/events/createSignOutEvent.js +43 -0
  29. package/dist/routes/auth/events/createUpdateUserEvent.js +41 -0
  30. package/dist/routes/auth/getAuthConfig.js +86 -0
  31. package/dist/routes/auth/resolveCookies.js +37 -0
  32. package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
  33. package/dist/routes/endpoints/authorizeApiEndpoint.js +4 -13
  34. package/dist/routes/endpoints/callEndpoint.js +5 -5
  35. package/dist/routes/endpoints/control/controlThrow.js +2 -2
  36. package/dist/routes/endpoints/control/handleControl.js +1 -3
  37. package/dist/routes/endpoints/getEndpointConfig.js +8 -18
  38. package/dist/routes/endpoints/handleEndpointCall.js +3 -16
  39. package/dist/routes/endpoints/handleRenderNotification.js +1 -1
  40. package/dist/routes/endpoints/handleRequest.js +1 -8
  41. package/dist/routes/endpoints/handleValidateSchema.js +3 -6
  42. package/dist/routes/endpoints/runDetachedEndpoint.js +18 -31
  43. package/dist/routes/endpoints/runRoutine.js +2 -17
  44. package/dist/routes/endpoints/runScheduledEndpoint.js +13 -8
  45. package/dist/routes/endpoints/runWebhookEndpoint.js +19 -48
  46. package/dist/routes/endpoints/test/runTest.js +4 -3
  47. package/dist/routes/mcp/createMcpServer.js +47 -100
  48. package/dist/routes/page/dynamic/resolveDynamicContent.js +1 -7
  49. package/dist/routes/page/getPageConfig.js +5 -55
  50. package/dist/routes/request/authorizeRequest.js +6 -21
  51. package/dist/routes/request/callRequest.js +1 -8
  52. package/dist/routes/request/callRequestResolver.js +9 -5
  53. package/dist/routes/request/createApp.js +97 -0
  54. package/dist/routes/request/getRequestConfig.js +3 -19
  55. package/dist/routes/rootConfig/menus/filterMenuList.js +2 -5
  56. package/dist/routes/websocket/authorizeWebsocket.js +4 -19
  57. package/dist/routes/websocket/createChannelRegistry.js +5 -14
  58. package/dist/routes/websocket/createWebSocketConnection.js +1 -14
  59. package/dist/routes/websocket/prepareChannel.js +1 -13
  60. package/dist/test/testContext.js +10 -13
  61. package/package.json +10 -18
  62. package/dist/context/applySystemTrust.js +0 -33
  63. package/dist/context/createAuthorizeOutcome.js +0 -91
  64. package/dist/context/createSystemContext.js +0 -78
  65. package/dist/context/normalizeInjectedCaller.js +0 -50
  66. package/dist/context/resolveAuthentication.js +0 -526
  67. package/dist/email/renderAuthEmail.js +0 -99
  68. package/dist/response/formatErrorForAgent.js +0 -35
  69. package/dist/routes/auth/buildAdminPlugin.js +0 -33
  70. package/dist/routes/auth/buildCaptchaPlugin.js +0 -61
  71. package/dist/routes/auth/buildOauthPostLogin.js +0 -73
  72. package/dist/routes/auth/buildPhoneNumberPlugin.js +0 -57
  73. package/dist/routes/auth/buildProviders.js +0 -51
  74. package/dist/routes/auth/createAsMetadataHandler.js +0 -27
  75. package/dist/routes/auth/createOnAPIError.js +0 -41
  76. package/dist/routes/auth/createSendEmail.js +0 -54
  77. package/dist/routes/auth/getAuthEnforcement.js +0 -41
  78. package/dist/routes/auth/getBetterAuth.js +0 -87
  79. package/dist/routes/auth/getBetterAuthConfig.js +0 -715
  80. package/dist/routes/auth/hooks/authHookPoints.js +0 -204
  81. package/dist/routes/auth/hooks/buildEngineHooks.js +0 -68
  82. package/dist/routes/auth/hooks/buildHooks.js +0 -112
  83. package/dist/routes/auth/hooks/composeBeforeSlot.js +0 -41
  84. package/dist/routes/auth/hooks/createHookDispatch.js +0 -59
  85. package/dist/routes/auth/hooks/createUserAfterHook.js +0 -36
  86. package/dist/routes/auth/hooks/createUserBeforeHook.js +0 -50
  87. package/dist/routes/auth/hooks/findHookUser.js +0 -27
  88. package/dist/routes/auth/organizations/OrganizationKeyError.js +0 -28
  89. package/dist/routes/auth/organizations/authorizeRole.js +0 -27
  90. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +0 -155
  91. package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +0 -57
  92. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +0 -240
  93. package/dist/routes/auth/organizations/createAdmissionGateHook.js +0 -50
  94. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +0 -90
  95. package/dist/routes/auth/organizations/createAutoJoinHook.js +0 -68
  96. package/dist/routes/auth/organizations/createEmailSendGate.js +0 -59
  97. package/dist/routes/auth/organizations/ensureOrganization.js +0 -132
  98. package/dist/routes/auth/organizations/findPendingInvitation.js +0 -43
  99. package/dist/routes/auth/organizations/getOrganizationBinding.js +0 -65
  100. package/dist/routes/auth/organizations/isEmailAdmitted.js +0 -89
  101. package/dist/routes/auth/organizations/organizationAccessControl.js +0 -94
  102. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +0 -62
  103. package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +0 -145
  104. package/dist/routes/auth/requestHooks/buildRequestHooks.js +0 -242
  105. package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +0 -43
  106. package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +0 -59
  107. package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +0 -45
  108. package/dist/routes/auth/requestHooks/matchOAuthCallback.js +0 -47
  109. package/dist/routes/auth/requestHooks/redirectToChallenge.js +0 -79
  110. package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +0 -31
  111. package/dist/routes/auth/resolveCookiePrefix.js +0 -30
  112. package/dist/routes/auth/sanitizeSessionResponse.js +0 -27
  113. package/dist/routes/connections/resolveTenantPreflight.js +0 -182
  114. package/dist/routes/endpoints/control/controlWhile.js +0 -59
  115. package/dist/routes/endpoints/handleAuthStep.js +0 -212
  116. package/dist/routes/endpoints/resolveStepOrganizationId.js +0 -64
  117. package/dist/routes/endpoints/runWebhookVerify.js +0 -116
  118. package/dist/routes/mcp/getMcpJwks.js +0 -93
  119. package/dist/routes/mcp/getMcpResourceBinding.js +0 -41
  120. package/dist/routes/mcp/getMcpUri.js +0 -60
  121. package/dist/routes/mcp/oauthResourceLifecycle.js +0 -122
  122. package/dist/routes/request/resolveTenant.js +0 -132
  123. /package/dist/{email → routes/notifications}/resolveThemeLogo.js +0 -0
@@ -12,14 +12,11 @@
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 createAuthorizeOutcome from './createAuthorizeOutcome.js';
15
+ */ import createAuthorize from './createAuthorize.js';
16
16
  import createReadConfigFile from './createReadConfigFile.js';
17
- import getAuthEnforcement from '../routes/auth/getAuthEnforcement.js';
18
- import getOrganizationBinding from '../routes/auth/organizations/getOrganizationBinding.js';
19
17
  import resolveLocale from './resolveLocale.js';
20
18
  function createApiContext(context) {
21
- // context.user is written by resolveAuthentication (or a pre-resolved
22
- // dev/e2e caller) before this runs - never assigned here.
19
+ context.user = context?.session?.user;
23
20
  if (context.i18n?.defaultLocale) {
24
21
  const active = resolveLocale({
25
22
  i18n: context.i18n,
@@ -32,19 +29,7 @@ function createApiContext(context) {
32
29
  } else {
33
30
  context.i18n = undefined;
34
31
  }
35
- // The retained organizations state ({ policy, pinned }) - read by the
36
- // _organization operator and the org-scoped admin steps; null when auth
37
- // (or organizations) is not configured.
38
- context.organization = getOrganizationBinding({
39
- auth: context.auth ?? null
40
- });
41
- // The retained build-time authorization facts - the enrolment floor, the exempt
42
- // enrolment page, and the unlisted-page-id default. null when auth is not
43
- // configured, in which case nothing is protected and nothing is required.
44
- context.authEnforcement = getAuthEnforcement({
45
- auth: context.auth ?? null
46
- });
47
- context.authorizeOutcome = createAuthorizeOutcome(context);
32
+ context.authorize = createAuthorize(context);
48
33
  context.readConfigFile = createReadConfigFile(context);
49
34
  }
50
35
  export default createApiContext;
@@ -0,0 +1,45 @@
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
+ function createAuthorize({ session, system = false }) {
17
+ // Next-auth getSession provides a session object if the user is authenticated
18
+ // else session will be null
19
+ const authenticated = !!session;
20
+ const roles = session?.user?.roles ?? [];
21
+ if (!Array.isArray(roles)) {
22
+ throw new ConfigError('session.user.roles must be an array of strings.', {
23
+ received: roles
24
+ });
25
+ }
26
+ function authorize(config) {
27
+ // A system context (scheduled, webhook, detached runs) was authorized at the
28
+ // transport layer, so nested endpoint calls are never gated on a user session.
29
+ if (system === true) return true;
30
+ const { auth } = config;
31
+ if (auth.public === true) return true;
32
+ if (auth.public === false) {
33
+ if (auth.roles) {
34
+ return authenticated && auth.roles.some((role)=>roles.includes(role));
35
+ }
36
+ return authenticated;
37
+ }
38
+ throw new ConfigError('auth.public must be true or false.', {
39
+ received: auth.public,
40
+ configKey: config['~k']
41
+ });
42
+ }
43
+ return authorize;
44
+ }
45
+ export default createAuthorize;
@@ -14,13 +14,12 @@
14
14
  limitations under the License.
15
15
  */ import { ServerParser } from '@lowdefy/operators';
16
16
  function createEvaluateOperators(context) {
17
- const { appMeta, i18n, jsMap, operators, organization, secrets, user } = context;
17
+ const { appMeta, i18n, jsMap, operators, secrets, user } = context;
18
18
  const operatorsParser = new ServerParser({
19
19
  i18n,
20
20
  jsMap,
21
21
  lowdefyApp: appMeta,
22
22
  operators,
23
- organization,
24
23
  secrets,
25
24
  user
26
25
  });
@@ -12,17 +12,13 @@
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 { normalizeCaller, type } from '@lowdefy/helpers';
15
+ */ import { type } from '@lowdefy/helpers';
16
16
  // Tries the configured API auth strategies in config order; the first
17
17
  // verifier match wins. A strategy caller is a config-derived, org-less
18
18
  // principal: roles are the strategy's static grant unioned with any
19
19
  // claim-derived roles, and attributes are the static bag shallow-merged
20
20
  // with claim-mapped values (claim wins), so _user.attributes reads the same
21
21
  // for session and strategy callers.
22
- //
23
- // normalizeCaller gives it the same snake_case key shape as the session
24
- // caller, over the verifier's user fields as well as the two stamped here -
25
- // app config reads one caller shape whichever branch resolved it.
26
22
  async function resolveStrategyCaller({ headers, logger, strategies }) {
27
23
  for (const strategy of strategies ?? []){
28
24
  const match = await strategy.verify({
@@ -47,13 +43,13 @@ async function resolveStrategyCaller({ headers, logger, strategies }) {
47
43
  authMethod: strategy.type,
48
44
  strategyId: strategy.id
49
45
  }, `Request authenticated by auth strategy "${strategy.id}" (${strategy.type}).`);
50
- return normalizeCaller({
46
+ return {
51
47
  ...match.user,
52
48
  authMethod: strategy.type,
53
49
  strategyId: strategy.id,
54
50
  roles,
55
51
  attributes
56
- });
52
+ };
57
53
  }
58
54
  return null;
59
55
  }
package/dist/index.js CHANGED
@@ -18,29 +18,21 @@ import callEndpoint from './routes/endpoints/callEndpoint.js';
18
18
  import getEndpointConfig from './routes/endpoints/getEndpointConfig.js';
19
19
  import callRequest from './routes/request/callRequest.js';
20
20
  import createApiContext from './context/createApiContext.js';
21
- import createAsMetadataHandler from './routes/auth/createAsMetadataHandler.js';
22
21
  import createChannelRegistry from './routes/websocket/createChannelRegistry.js';
23
22
  import createMcpServer from './routes/mcp/createMcpServer.js';
24
- import createSystemContext from './context/createSystemContext.js';
25
23
  import createWebSocketConnection from './routes/websocket/createWebSocketConnection.js';
24
+ import createSessionCallback from './routes/auth/callbacks/createSessionCallback.js';
25
+ import getAuthConfig from './routes/auth/getAuthConfig.js';
26
26
  import getAuthStrategies from './routes/auth/strategies/getAuthStrategies.js';
27
- import getBetterAuth from './routes/auth/getBetterAuth.js';
28
- import { MCP_OAUTH_SCOPES } from './routes/auth/getBetterAuthConfig.js';
29
- import { getAsIssuer, getMcpResourceMetadataUri, getMcpResourceUri } from './routes/mcp/getMcpUri.js';
30
- import getMcpResourceBinding, { registerMcpResourceBinding } from './routes/mcp/getMcpResourceBinding.js';
31
- import { ensureMcpOauthResource } from './routes/mcp/oauthResourceLifecycle.js';
32
27
  import getHomeAndMenus from './routes/rootConfig/getHomeAndMenus.js';
28
+ import resolveStrategyCaller from './context/resolveStrategyCaller.js';
33
29
  import getPageConfig from './routes/page/getPageConfig.js';
34
30
  import getRootConfig from './routes/rootConfig/getRootConfig.js';
35
31
  import logClientError from './routes/log/logClientError.js';
36
- import normalizeInjectedCaller from './context/normalizeInjectedCaller.js';
37
32
  import redactErrorResponse from './response/redactErrorResponse.js';
38
33
  import redactResponse from './response/redactResponse.js';
39
- import resolveAuthentication from './context/resolveAuthentication.js';
40
- import resolvePinnedOrganization from './routes/auth/organizations/resolvePinnedOrganization.js';
41
- import resolveTenantPreflight from './routes/connections/resolveTenantPreflight.js';
42
34
  import forwardScheduledEndpoint from './routes/endpoints/forwardScheduledEndpoint.js';
43
35
  import runDetachedEndpoint from './routes/endpoints/runDetachedEndpoint.js';
44
36
  import runWebhookEndpoint from './routes/endpoints/runWebhookEndpoint.js';
45
37
  import runScheduledEndpoint from './routes/endpoints/runScheduledEndpoint.js';
46
- export { buildEndpointResult, callAgent, callEndpoint, getEndpointConfig, callRequest, createApiContext, createAsMetadataHandler, createChannelRegistry, createMcpServer, createSystemContext, createWebSocketConnection, ensureMcpOauthResource, getAsIssuer, getAuthStrategies, getBetterAuth, MCP_OAUTH_SCOPES, getHomeAndMenus, getMcpResourceBinding, getMcpResourceMetadataUri, getMcpResourceUri, registerMcpResourceBinding, getPageConfig, getRootConfig, logClientError, normalizeInjectedCaller, redactErrorResponse, redactResponse, resolveAuthentication, resolvePinnedOrganization, resolveTenantPreflight, forwardScheduledEndpoint, runDetachedEndpoint, runWebhookEndpoint, runScheduledEndpoint };
38
+ export { buildEndpointResult, callAgent, callEndpoint, getEndpointConfig, callRequest, createApiContext, createChannelRegistry, createMcpServer, createSessionCallback, createWebSocketConnection, getAuthConfig, getAuthStrategies, getHomeAndMenus, getPageConfig, getRootConfig, logClientError, redactErrorResponse, redactResponse, resolveStrategyCaller, forwardScheduledEndpoint, runDetachedEndpoint, runWebhookEndpoint, runScheduledEndpoint };
@@ -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 { type } from '@lowdefy/helpers';
15
+ */ import { UserError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
16
17
  // The client-bound error policy: which fields of an error may cross the wire.
17
18
  // Passed to serializer.serialize as `omitErrorProps`, so extractErrorProps applies
18
19
  // it at EVERY error node the walk emits - the cause chain, an Error-valued own
@@ -43,17 +44,8 @@ function omitErrorProps(error) {
43
44
  //
44
45
  // type.isError is `instanceof Error`, the same test extractErrorProps uses to
45
46
  // decide which branch emits the cause - the two must agree.
46
- // A ServiceError's cause is the driver's or the service's own error, whose raw
47
- // message the plugin deliberately did not put in the ServiceError message - it
48
- // can carry server internals and caller data (a duplicate key error quotes the
49
- // document's values). The cause stays on the error in-process, so
50
- // createHandleError logs it and createCliLogger prints
51
- // `Caused by: MongoServerError: <raw text>` in the server terminal.
52
- if (error.name === 'ServiceError') return OMITTED_WITH_CAUSE;
53
47
  if (type.isError(error.cause)) return ALWAYS_OMITTED;
54
- // Keyed on the name, not instanceof - the error may cross a package boundary
55
- // or a serializer round trip and still be a UserError.
56
- if (error.name === 'UserError') return ALWAYS_OMITTED;
48
+ if (error instanceof UserError) return ALWAYS_OMITTED;
57
49
  return OMITTED_WITH_CAUSE;
58
50
  }
59
51
  export default omitErrorProps;
@@ -12,29 +12,17 @@
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 { AuthenticationError, AuthorizationError, TwoFactorEnrolmentRequiredError } from '@lowdefy/errors';
16
- import { translate, type } from '@lowdefy/helpers';
17
- function authorizeAgent({ authorizeOutcome, i18n, logger, user }, { agentConfig }) {
18
- const outcome = authorizeOutcome(agentConfig);
19
- if (outcome !== 'allow') {
15
+ */ import { ConfigError } from '@lowdefy/errors';
16
+ import { translate } from '@lowdefy/helpers';
17
+ function authorizeAgent({ authorize, i18n, logger }, { agentConfig }) {
18
+ if (!authorize(agentConfig)) {
20
19
  logger.debug({
21
20
  event: 'debug_agent_authorize',
22
21
  authorized: false,
23
- outcome,
24
22
  auth_config: agentConfig.auth
25
23
  });
26
- if (outcome === 'enrol_required') {
27
- // Reached only after the role check passed, so the caller is authorised and
28
- // this reveals nothing about which agents exist.
29
- throw new TwoFactorEnrolmentRequiredError(`Two-factor enrolment required for agent "${agentConfig.agentId}".`);
30
- }
31
- // Unauthenticated on a protected agent - 401 tells the caller to fix
32
- // its credentials. Wrong roles stay opaque below.
33
- if (type.isNone(user)) {
34
- throw new AuthenticationError(`Authentication required for agent "${agentConfig.agentId}".`);
35
- }
36
24
  // Same message as an unknown agentId so responses do not reveal which agents exist.
37
- throw new AuthorizationError(translate({
25
+ throw new ConfigError(translate({
38
26
  key: 'agent.runtime.agentNotFound',
39
27
  values: {
40
28
  agentId: agentConfig.agentId
@@ -71,7 +71,6 @@ async function prepareAgent(context, { agentId, agentContext, endpointDepth = 0,
71
71
  const resolverContext = {
72
72
  agentContext,
73
73
  i18n: context.i18n,
74
- logger: context.logger,
75
74
  mode,
76
75
  evaluateOperators: (input)=>context.evaluateOperators({
77
76
  input,
@@ -12,13 +12,17 @@
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
- */ // The engine's baseURL is dynamic (resolved per request from the request
16
- // host), so a nested auth.api call made from inside a hook must carry the
17
- // firing request as its source - a headerless direct call cannot resolve a
18
- // base URL and BetterAuth rejects it. Database hooks receive the endpoint
19
- // context when the write runs inside a request lifecycle; the headers come
20
- // from there.
21
- function getHookRequestHeaders(ctx) {
22
- return ctx?.headers ?? ctx?.request?.headers ?? ctx?.context?.headers;
15
+ */ import { get, set } from '@lowdefy/helpers';
16
+ function addUserFieldsToSession({ session, token, authConfig, user }) {
17
+ if (token) {
18
+ Object.keys(authConfig.userFields).forEach((fieldName)=>{
19
+ set(session.user, fieldName, get(token, fieldName));
20
+ });
21
+ }
22
+ if (user) {
23
+ Object.keys(authConfig.userFields).forEach((fieldName)=>{
24
+ set(session.user, fieldName, get(user, fieldName));
25
+ });
26
+ }
23
27
  }
24
- export default getHookRequestHeaders;
28
+ export default addUserFieldsToSession;
@@ -0,0 +1,30 @@
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 { get, set } from '@lowdefy/helpers';
16
+ function addUserFieldsToToken({ account, authConfig, logger, profile, token, user }) {
17
+ const objects = {
18
+ account,
19
+ profile,
20
+ user
21
+ };
22
+ logger.debug('Adding userFields to user. Available provider data is:');
23
+ logger.debug(objects);
24
+ Object.entries(authConfig.userFields).forEach(([lowdefyFieldName, providerFieldName])=>{
25
+ const value = get(objects, providerFieldName);
26
+ logger.debug(`Adding provider field "${providerFieldName}" with value ${JSON.stringify(value)} as "${lowdefyFieldName}"`);
27
+ set(token, lowdefyFieldName, value);
28
+ });
29
+ }
30
+ export default addUserFieldsToToken;
@@ -12,15 +12,10 @@
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
- */ // The composed slot for after and synthetic points - engine hooks first,
16
- // then the user hooks in array order, sequentially. Return values are
17
- // ignored; a thrown error propagates as an operational error on the
18
- // underlying operation.
19
- function composeAfterSlot({ hooks }) {
20
- return async function afterSlot(data, ctx) {
21
- for (const hook of hooks){
22
- await hook(data, ctx);
23
- }
24
- };
15
+ */ function createCallbackPlugins({ authConfig, plugins, type }) {
16
+ return authConfig.callbacks.map((callbackConfig)=>({
17
+ fn: plugins.callbacks[callbackConfig.type],
18
+ properties: callbackConfig.properties
19
+ })).filter((callback)=>callback.fn.meta.type === type);
25
20
  }
26
- export default composeAfterSlot;
21
+ export default createCallbackPlugins;
@@ -0,0 +1,46 @@
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 createJWTCallback from './createJWTCallback.js';
16
+ import createRedirectCallback from './createRedirectCallback.js';
17
+ import createSessionCallback from './createSessionCallback.js';
18
+ import createSignInCallback from './createSignInCallback.js';
19
+ function createCallbacks({ authConfig, logger, plugins }) {
20
+ const callbacks = {
21
+ session: createSessionCallback({
22
+ authConfig,
23
+ logger,
24
+ plugins
25
+ })
26
+ };
27
+ const jwt = createJWTCallback({
28
+ authConfig,
29
+ logger,
30
+ plugins
31
+ });
32
+ if (jwt) callbacks.jwt = jwt;
33
+ const redirect = createRedirectCallback({
34
+ authConfig,
35
+ logger,
36
+ plugins
37
+ });
38
+ if (redirect) callbacks.redirect = redirect;
39
+ const signIn = createSignInCallback({
40
+ authConfig,
41
+ plugins
42
+ });
43
+ if (signIn) callbacks.signIn = signIn;
44
+ return callbacks;
45
+ }
46
+ export default createCallbacks;
@@ -0,0 +1,77 @@
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 addUserFieldsToToken from './addUserFieldsToToken.js';
16
+ import createCallbackPlugins from './createCallbackPlugins.js';
17
+ function createJWTCallback({ authConfig, logger, plugins }) {
18
+ const jwtCallbackPlugins = createCallbackPlugins({
19
+ authConfig,
20
+ plugins,
21
+ type: 'jwt'
22
+ });
23
+ async function jwtCallback({ token, user, account, profile, isNewUser }) {
24
+ if (profile) {
25
+ const { id, sub, name, given_name, family_name, middle_name, nickname, preferred_username, profile: profile_claim, picture, website, email, email_verified, gender, birthdate, zoneinfo, locale, phone_number, phone_number_verified, address, updated_at } = profile;
26
+ token = {
27
+ id,
28
+ sub,
29
+ name,
30
+ given_name,
31
+ family_name,
32
+ middle_name,
33
+ nickname,
34
+ preferred_username,
35
+ profile: profile_claim,
36
+ picture,
37
+ website,
38
+ email,
39
+ email_verified,
40
+ gender,
41
+ birthdate,
42
+ zoneinfo,
43
+ locale,
44
+ phone_number,
45
+ phone_number_verified,
46
+ address,
47
+ updated_at,
48
+ ...token
49
+ };
50
+ }
51
+ if (profile || user) {
52
+ if (authConfig.userFields) {
53
+ addUserFieldsToToken({
54
+ authConfig,
55
+ account,
56
+ logger,
57
+ profile,
58
+ token,
59
+ user
60
+ });
61
+ }
62
+ }
63
+ for (const plugin of jwtCallbackPlugins){
64
+ token = await plugin.fn({
65
+ properties: plugin.properties ?? {},
66
+ account,
67
+ isNewUser,
68
+ profile,
69
+ token,
70
+ user
71
+ });
72
+ }
73
+ return token;
74
+ }
75
+ return jwtCallback;
76
+ }
77
+ export default createJWTCallback;
@@ -0,0 +1,41 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import createCallbackPlugins from './createCallbackPlugins.js';
16
+ function defaultRedirect({ url, baseUrl }) {
17
+ if (url.startsWith('/')) return `${baseUrl}${url}`;
18
+ else if (new URL(url).origin === baseUrl) return url;
19
+ return baseUrl;
20
+ }
21
+ function createRedirectCallback({ authConfig, plugins }) {
22
+ const redirectCallbackPlugins = createCallbackPlugins({
23
+ authConfig,
24
+ plugins,
25
+ type: 'redirect'
26
+ });
27
+ if (redirectCallbackPlugins.length === 0) return defaultRedirect;
28
+ if (redirectCallbackPlugins.length !== 1) {
29
+ throw new Error('More than one auth redirect callbacks are configured. Only one is allowed.');
30
+ }
31
+ const [plugin] = redirectCallbackPlugins;
32
+ function redirectCallback({ url, baseUrl }) {
33
+ return plugin.fn({
34
+ properties: plugin.properties ?? {},
35
+ baseUrl,
36
+ url
37
+ });
38
+ }
39
+ return redirectCallback;
40
+ }
41
+ export default createRedirectCallback;
@@ -0,0 +1,81 @@
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 crypto from 'crypto';
16
+ import addUserFieldsToSession from './addUserFieldsToSession.js';
17
+ import createCallbackPlugins from './createCallbackPlugins.js';
18
+ import validateSessionRoles from './validateSessionRoles.js';
19
+ function createSessionCallback({ authConfig, plugins }) {
20
+ const sessionCallbackPlugins = createCallbackPlugins({
21
+ authConfig,
22
+ plugins,
23
+ type: 'session'
24
+ });
25
+ async function sessionCallback({ session, token, user }) {
26
+ const identifier = user ? user.id ?? user.sub ?? user.email : token.id ?? token.sub ?? token.email;
27
+ if (token) {
28
+ const { id, sub, name, given_name, family_name, middle_name, nickname, preferred_username, profile, picture, website, email, email_verified, gender, birthdate, zoneinfo, locale, phone_number, phone_number_verified, address, updated_at } = token;
29
+ session.user = {
30
+ id,
31
+ sub,
32
+ name,
33
+ given_name,
34
+ family_name,
35
+ middle_name,
36
+ nickname,
37
+ preferred_username,
38
+ profile,
39
+ picture,
40
+ website,
41
+ email,
42
+ email_verified,
43
+ gender,
44
+ birthdate,
45
+ zoneinfo,
46
+ locale,
47
+ phone_number,
48
+ phone_number_verified,
49
+ address,
50
+ updated_at,
51
+ ...session.user
52
+ };
53
+ }
54
+ if (authConfig.userFields) {
55
+ addUserFieldsToSession({
56
+ authConfig,
57
+ session,
58
+ token,
59
+ user
60
+ });
61
+ }
62
+ for (const plugin of sessionCallbackPlugins){
63
+ // eslint-disable-next-line no-param-reassign
64
+ session = await plugin.fn({
65
+ properties: plugin.properties ?? {},
66
+ session,
67
+ token,
68
+ user
69
+ });
70
+ }
71
+ validateSessionRoles({
72
+ session
73
+ });
74
+ // TODO: Should this be session.hashed_id or session.user.hashed_id
75
+ // Only session.user will be available using the _user operator
76
+ session.hashed_id = crypto.createHash('sha256').update(identifier ?? '').digest('base64');
77
+ return session;
78
+ }
79
+ return sessionCallback;
80
+ }
81
+ export default createSessionCallback;
@@ -0,0 +1,40 @@
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 createCallbackPlugins from './createCallbackPlugins.js';
16
+ function createSignInCallback({ authConfig, plugins }) {
17
+ const signInCallbackPlugins = createCallbackPlugins({
18
+ authConfig,
19
+ plugins,
20
+ type: 'signIn'
21
+ });
22
+ if (signInCallbackPlugins.length === 0) return undefined;
23
+ async function signInCallback({ account, credentials, email, profile, user }) {
24
+ let allowSignIn = true;
25
+ for (const plugin of signInCallbackPlugins){
26
+ allowSignIn = await plugin.fn({
27
+ properties: plugin.properties ?? {},
28
+ account,
29
+ credentials,
30
+ email,
31
+ profile,
32
+ user
33
+ });
34
+ if (allowSignIn === false) break;
35
+ }
36
+ return allowSignIn;
37
+ }
38
+ return signInCallback;
39
+ }
40
+ export default createSignInCallback;
@@ -0,0 +1,33 @@
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
+ function validateSessionRoles({ session }) {
18
+ const roles = session?.user?.roles;
19
+ if (type.isNone(roles)) return;
20
+ if (!Array.isArray(roles)) {
21
+ throw new ConfigError('session.user.roles must be an array of strings. Check auth.userFields configuration and custom session callback plugins.', {
22
+ received: roles
23
+ });
24
+ }
25
+ for (const role of roles){
26
+ if (!type.isString(role)) {
27
+ throw new ConfigError('session.user.roles must be an array of strings. Check auth.userFields configuration and custom session callback plugins.', {
28
+ received: roles
29
+ });
30
+ }
31
+ }
32
+ }
33
+ export default validateSessionRoles;