@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,65 +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
- // The engine retains the deployment's organizations declaration and the
17
- // ensured pinned organization per auth instance. Request and system contexts
18
- // read the retained state synchronously so the _organization operator and
19
- // the org-scoped admin steps can resolve the pinned org at evaluation time.
20
- // The pinned row is retained by ensureOrganization when its ensure resolves
21
- // (at startup, or on the first session fire when startup seeding failed) -
22
- // the org id is minted at creation, so no build artifact can carry it.
23
- const bindingByAuth = new WeakMap();
24
- function registerOrganizationBinding({ auth, database = false, organizations }) {
25
- bindingByAuth.set(auth, {
26
- database,
27
- policy: organizations.policy,
28
- slug: organizations.org ?? null,
29
- pinned: null
30
- });
31
- }
32
- // The raw registered entry (policy, slug, database, pinned) - used by
33
- // resolvePinnedOrganization to decide whether an ensure is needed.
34
- function getRegisteredOrganization({ auth }) {
35
- if (type.isNone(auth)) {
36
- return null;
37
- }
38
- return bindingByAuth.get(auth) ?? null;
39
- }
40
- function setPinnedOrganization({ auth, organization, slug }) {
41
- const binding = bindingByAuth.get(auth);
42
- if (!binding || binding.policy !== 'pinned' || binding.slug !== slug) {
43
- return;
44
- }
45
- binding.pinned = {
46
- id: organization.id,
47
- slug: organization.slug,
48
- name: organization.name
49
- };
50
- }
51
- function getOrganizationBinding({ auth }) {
52
- if (type.isNone(auth)) {
53
- return null;
54
- }
55
- const binding = bindingByAuth.get(auth);
56
- if (type.isNone(binding)) {
57
- return null;
58
- }
59
- return {
60
- policy: binding.policy,
61
- pinned: binding.pinned
62
- };
63
- }
64
- export { getRegisteredOrganization, registerOrganizationBinding, setPinnedOrganization };
65
- export default getOrganizationBinding;
@@ -1,48 +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 ensureOrganization from './ensureOrganization.js';
17
- import { getRegisteredOrganization } from './getOrganizationBinding.js';
18
- // Awaited by the request middleware before handlers run. The engine is
19
- // constructed lazily on the first request, so that same request would
20
- // otherwise race the startup ensure and read an unresolved pinned org.
21
- // After the first resolution this awaits an already-settled memoized
22
- // promise; the retained binding makes it a no-op read. A failed ensure is
23
- // logged but not rethrown - the binding stays unresolved and the
24
- // _organization operator / step organizationId defaulting fail with their
25
- // own clear errors, instead of every request failing in the middleware.
26
- async function resolvePinnedOrganization({ auth, logger }) {
27
- if (type.isNone(auth)) {
28
- return;
29
- }
30
- const registered = getRegisteredOrganization({
31
- auth
32
- });
33
- if (type.isNone(registered) || registered.policy !== 'pinned' || registered.database !== true || !type.isNone(registered.pinned)) {
34
- return;
35
- }
36
- try {
37
- await ensureOrganization({
38
- auth,
39
- slug: registered.slug
40
- });
41
- } catch (error) {
42
- // Retried on the next fire - ensureOrganization does not memoize failures.
43
- logger.warn({
44
- err: error
45
- }, `Failed to ensure the pinned organization "${registered.slug}" for the request.`);
46
- }
47
- }
48
- export default resolvePinnedOrganization;
@@ -1,102 +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 getOrganizationBinding from './getOrganizationBinding.js';
17
- function splitRoles(role) {
18
- return String(role ?? '').split(',').map((entry)=>entry.trim()).filter(Boolean);
19
- }
20
- // The engine maintains user.role as an internal denormalization: BetterAuth's
21
- // admin plugin resolves impersonation permissions from the user-level role
22
- // field and never reads member.role. When the user's member roles in the
23
- // pinned organization include the configured auth.userAdminRole, the engine
24
- // writes that role name to user.role; when they lose it, the engine clears
25
- // the value it wrote (a foreign value is left alone). Apps never read or
26
- // write it; it exists so BetterAuth's own check passes. Pinned policy only -
27
- // tenant semantics wait for a multi-tenant admin design. The write is
28
- // adapter-direct so no user.update database hooks fire for the internal
29
- // bookkeeping. The twin helper for the admin steps lives in
30
- // @lowdefy/plugin-better-auth (steps/support/syncUserAdminRole.js).
31
- async function syncUserAdminRole({ auth, userAdminRole, userId }) {
32
- if (type.isNone(userAdminRole) || type.isNone(userId)) {
33
- return;
34
- }
35
- const organization = getOrganizationBinding({
36
- auth
37
- });
38
- if (organization?.policy !== 'pinned') {
39
- return;
40
- }
41
- if (type.isNone(organization.pinned?.id)) {
42
- throw new Error('Could not sync the user-admin role - the pinned organization is not resolved.');
43
- }
44
- const { adapter } = await auth.$context;
45
- const member = await adapter.findOne({
46
- model: 'member',
47
- where: [
48
- {
49
- field: 'userId',
50
- value: userId
51
- },
52
- {
53
- field: 'organizationId',
54
- value: organization.pinned.id
55
- }
56
- ]
57
- });
58
- const holdsRole = !type.isNone(member) && splitRoles(member.role).includes(userAdminRole);
59
- const user = await adapter.findOne({
60
- model: 'user',
61
- where: [
62
- {
63
- field: 'id',
64
- value: userId
65
- }
66
- ]
67
- });
68
- // No user row means nothing to denormalize (the user was deleted between
69
- // the member write and this sync) - not a failure.
70
- if (type.isNone(user)) {
71
- return;
72
- }
73
- if (holdsRole && user.role !== userAdminRole) {
74
- await adapter.update({
75
- model: 'user',
76
- where: [
77
- {
78
- field: 'id',
79
- value: userId
80
- }
81
- ],
82
- update: {
83
- role: userAdminRole
84
- }
85
- });
86
- }
87
- if (!holdsRole && user.role === userAdminRole) {
88
- await adapter.update({
89
- model: 'user',
90
- where: [
91
- {
92
- field: 'id',
93
- value: userId
94
- }
95
- ],
96
- update: {
97
- role: null
98
- }
99
- });
100
- }
101
- }
102
- export default syncUserAdminRole;
@@ -1,30 +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
- */ function slugifyPrefix(value) {
16
- return String(value).toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '');
17
- }
18
- // Lowdefy sets the cookie name prefix - it is not app-configurable. In dev,
19
- // the prefix is derived from the app so multiple local apps on different
20
- // ports do not collide on cookies (browsers do not scope cookies by port).
21
- function resolveCookiePrefix({ appMeta, dev }) {
22
- if (dev) {
23
- const appIdentifier = appMeta?.slug ?? appMeta?.name;
24
- if (appIdentifier) {
25
- return `lowdefy-${slugifyPrefix(appIdentifier)}`;
26
- }
27
- }
28
- return 'lowdefy';
29
- }
30
- export default resolveCookiePrefix;
@@ -1,77 +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 { ServerParser } from '@lowdefy/operators';
16
- import { _app, _secret } from '@lowdefy/operators-js/operators/server';
17
- import { type } from '@lowdefy/helpers';
18
- import { ConfigError } from '@lowdefy/errors';
19
- // Builds the API auth strategy verifiers from the auth.json build artifact.
20
- // Build has validated the config and written all defaults, so this resolves
21
- // the _secret operators and constructs each strategy type's verifier.
22
- // Verifier factories warn on short static keys at construction, so key
23
- // strength surfaces at startup, never as a build failure.
24
- function createAuthStrategies({ appMeta, authJson, logger, plugins, secrets }) {
25
- if (!type.isArray(authJson.strategies) || authJson.strategies.length === 0) {
26
- return [];
27
- }
28
- const operatorsParser = new ServerParser({
29
- lowdefyApp: appMeta,
30
- operators: {
31
- _app,
32
- _secret
33
- },
34
- secrets,
35
- user: {}
36
- });
37
- const { output: strategiesConfig, errors: operatorErrors } = operatorsParser.parse({
38
- input: authJson.strategies,
39
- location: 'auth.strategies',
40
- payload: {}
41
- });
42
- if (operatorErrors.length > 0) {
43
- // Startup fails on the first error; log the rest so they can all be
44
- // fixed in one pass instead of one boot per error.
45
- operatorErrors.slice(1).forEach((error)=>logger.error(error));
46
- throw operatorErrors[0];
47
- }
48
- return strategiesConfig.map((strategy)=>{
49
- const strategyPlugin = plugins.strategies[strategy.type];
50
- if (type.isNone(strategyPlugin)) {
51
- throw new ConfigError(`Auth strategy type "${strategy.type}" not found at strategy "${strategy.id}".`, {
52
- configKey: strategy['~k']
53
- });
54
- }
55
- let verify;
56
- try {
57
- verify = strategyPlugin({
58
- logger,
59
- properties: strategy.properties,
60
- strategyId: strategy.id
61
- });
62
- } catch (error) {
63
- throw new ConfigError(error.message, {
64
- cause: error,
65
- configKey: strategy['~k']
66
- });
67
- }
68
- return {
69
- attributes: strategy.attributes,
70
- id: strategy.id,
71
- roles: strategy.roles,
72
- type: strategy.type,
73
- verify
74
- };
75
- });
76
- }
77
- export default createAuthStrategies;
@@ -1,83 +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 addStepResult from './addStepResult.js';
18
- import prepareAgent from '../agent/prepareAgent.js';
19
- async function handleAgentCall(context, routineContext, { step }) {
20
- const { logger, evaluateOperators } = context;
21
- logger.debug({
22
- event: 'debug_start_agent_call',
23
- step
24
- });
25
- // Evaluate operators in step.properties (resolves agentId, prompt)
26
- const evaluatedProperties = evaluateOperators({
27
- input: step.properties,
28
- items: routineContext.items,
29
- location: step.stepId,
30
- payload: routineContext.payload,
31
- state: routineContext.state,
32
- steps: routineContext.steps
33
- });
34
- const { agentId, prompt } = evaluatedProperties;
35
- if (!type.isString(agentId)) {
36
- throw new ConfigError(`CallAgent step "${step.stepId}" properties.agentId must evaluate to a string. Received ${JSON.stringify(agentId)}.`, {
37
- configKey: step['~k']
38
- });
39
- }
40
- if (!type.isString(prompt)) {
41
- throw new ConfigError(`CallAgent step "${step.stepId}" properties.prompt must evaluate to a string. Received ${JSON.stringify(prompt)}.`, {
42
- configKey: step['~k']
43
- });
44
- }
45
- // Headless agent context — no page, no conversation, no sharedState (which
46
- // also excludes the client-only update-page-state tool). userId is null
47
- // under scheduled (system) context.
48
- const agentContext = {
49
- conversationId: null,
50
- pageId: null,
51
- sharedState: undefined,
52
- urlQuery: {},
53
- userId: context.user?.sub ?? context.user?.id ?? null
54
- };
55
- const { agentConfig, connectionInstance, agentType, resolverContext } = await prepareAgent(context, {
56
- agentId,
57
- agentContext,
58
- endpointDepth: routineContext.endpointDepth,
59
- mode: 'generate'
60
- });
61
- const { result } = await agentType.resolver({
62
- connection: connectionInstance,
63
- properties: {
64
- agent: agentConfig,
65
- prompt
66
- },
67
- context: resolverContext
68
- });
69
- addStepResult(context, routineContext, {
70
- result,
71
- stepId: step.stepId
72
- });
73
- logger.debug({
74
- event: 'debug_end_agent_call',
75
- stepId: step.stepId,
76
- targetAgentId: agentId,
77
- finishReason: result?.finishReason
78
- });
79
- return {
80
- status: 'continue'
81
- };
82
- }
83
- export default handleAgentCall;
@@ -1,124 +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 addStepResult from './addStepResult.js';
18
- import getUserAdminRole from '../auth/getUserAdminRole.js';
19
- async function handleAuthStep(context, routineContext, { step }) {
20
- const { logger, evaluateOperators } = context;
21
- logger.debug({
22
- event: 'debug_start_auth_step',
23
- step
24
- });
25
- // Evaluate operators in step.properties before resolving the step type, so
26
- // a malformed properties block surfaces the same way it does for every
27
- // other step type.
28
- const evaluatedProperties = evaluateOperators({
29
- input: step.properties,
30
- items: routineContext.items,
31
- location: step.stepId,
32
- payload: routineContext.payload,
33
- state: routineContext.state,
34
- steps: routineContext.steps
35
- });
36
- const stepFn = context.steps?.[step.type];
37
- if (type.isNone(stepFn)) {
38
- throw new ConfigError(`Auth step type "${step.type}" is not defined.`, {
39
- configKey: step['~k']
40
- });
41
- }
42
- // Checked before the caller - an auth-less app should hear "no auth
43
- // engine", not a misleading missing-caller error.
44
- if (type.isNone(context.auth)) {
45
- throw new ConfigError(`Auth step "${step.stepId}" requires the auth engine - auth is not configured (or dev.mockUser is active).`, {
46
- configKey: step['~k']
47
- });
48
- }
49
- // The floor passes on either of two independent doors (Decision 1):
50
- // 1. a run-level system context (context.system === true) - a trusted,
51
- // caller-less run (cron, hook, verified webhook), or
52
- // 2. a single step marked system (step.system === true, admin's
53
- // skipUserAdminRoleCheck) - a per-step waiver in an otherwise
54
- // user/public run, which never sets context.system.
55
- // Either door makes the step act caller-less as the system.
56
- const actingAsSystem = context.system === true || step.system === true;
57
- // A resolved caller is context.user carrying an id. A caller-less run needs
58
- // no principal only when one of the two system doors is open.
59
- const hasCaller = type.isObject(context.user) && !type.isNone(context.user.id);
60
- if (!hasCaller && !actingAsSystem) {
61
- throw new ConfigError(`Auth step "${step.stepId}" requires an authenticated caller. Set system: true on the step for caller-less system routines.`, {
62
- configKey: step['~k']
63
- });
64
- }
65
- // Acting as the system is an explicit trust decision, not attribution - the
66
- // step runs caller-less as the system (even when a caller is present, for
67
- // the per-step marker).
68
- const acting = actingAsSystem ? {
69
- system: true,
70
- user: null
71
- } : {
72
- system: false,
73
- user: context.user
74
- };
75
- // The user-administration floor, enforced mechanically here so an app can
76
- // never expose member mutation by forgetting a check: every user-initiated
77
- // auth step requires the resolved caller to hold the auth.userAdminRole
78
- // member role. System invocations run caller-less and pass. A step may
79
- // declare a self-targeting exemption (meta.selfTargetExempt names the
80
- // property compared to the caller's own id) - today only UpdateUserProfile,
81
- // whose self-service profile save carries no authorization inputs.
82
- const userAdminRole = getUserAdminRole({
83
- auth: context.auth
84
- });
85
- if (acting.system !== true) {
86
- const selfTargetKey = stepFn.meta?.selfTargetExempt;
87
- const selfTargeted = !type.isNone(selfTargetKey) && evaluatedProperties?.[selfTargetKey] === context.user.id;
88
- if (!selfTargeted) {
89
- if (type.isNone(userAdminRole)) {
90
- throw new ConfigError(`Auth step "${step.stepId}" refused - "auth.userAdminRole" is not configured. The app must declare which member role administers users; caller-less system routines (system: true) are unaffected.`, {
91
- configKey: step['~k']
92
- });
93
- }
94
- if (!(context.user.roles ?? []).includes(userAdminRole)) {
95
- throw new ConfigError(`Auth step "${step.stepId}" refused - the caller does not hold the user-admin role configured in "auth.userAdminRole".`, {
96
- configKey: step['~k']
97
- });
98
- }
99
- }
100
- }
101
- // The retained organizations state ({ policy, pinned }) - org-scoped steps
102
- // default an omitted organizationId from it. The configured user-admin role
103
- // rides along for the steps that sync the user.role denormalization.
104
- const result = await stepFn({
105
- acting,
106
- auth: context.auth,
107
- organization: context.organization ?? null,
108
- properties: evaluatedProperties,
109
- userAdminRole
110
- });
111
- addStepResult(context, routineContext, {
112
- result,
113
- stepId: step.stepId
114
- });
115
- logger.debug({
116
- event: 'debug_end_auth_step',
117
- stepId: step.stepId,
118
- type: step.type
119
- });
120
- return {
121
- status: 'continue'
122
- };
123
- }
124
- export default handleAuthStep;