@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
@@ -12,11 +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 { serializer } from '@lowdefy/helpers';
16
- import { ConfigError } from '@lowdefy/errors';
17
- import addStepResult from './addStepResult.js';
15
+ */ import addStepResult from './addStepResult.js';
18
16
  import invokeEndpoint from './invokeEndpoint.js';
19
- import scheduleBackground from './scheduleBackground.js';
20
17
  async function handleEndpointCall(context, routineContext, { step }) {
21
18
  const { logger, evaluateOperators } = context;
22
19
  logger.debug({
@@ -32,64 +29,6 @@ async function handleEndpointCall(context, routineContext, { step }) {
32
29
  state: routineContext.state,
33
30
  steps: routineContext.steps
34
31
  });
35
- // detached: true — fire-and-forget the call back through the deployment's
36
- // /api/detached route, so the target runs in its OWN function invocation
37
- // with a fresh duration budget (chainable bounded work without a queue).
38
- // At-most-once, no retry: targets must be idempotent. The dispatch promise
39
- // rides the platform request context so the outgoing request always leaves
40
- // before the invocation is reaped; the target's own outcome exists only in
41
- // its logs and whatever its routine writes.
42
- if (evaluatedProperties.detached === true) {
43
- if (!process.env.CRON_SECRET) {
44
- throw new ConfigError('CallApi with "detached: true" requires the CRON_SECRET environment variable — the /api/detached route fails closed without it.');
45
- }
46
- if (!context.origin) {
47
- throw new ConfigError('Detached endpoint calls require the request origin on context.');
48
- }
49
- const targetEndpointId = evaluatedProperties.endpointId;
50
- scheduleBackground(context, {
51
- event: 'detached_dispatch',
52
- endpointId: targetEndpointId
53
- }, ()=>fetch(`${context.origin}/api/detached/${targetEndpointId}`, {
54
- method: 'POST',
55
- headers: {
56
- 'content-type': 'application/json',
57
- authorization: `Bearer ${process.env.CRON_SECRET}`
58
- },
59
- // Carry the already-resolved dispatcher identity across the hop
60
- // (Decision 4): a detached call is a fresh invocation, not a fresh
61
- // principal. The receiver rehydrates context.user / context.system from
62
- // this snapshot and authorizes nested calls against it through the
63
- // normal path - so a user-dispatched detached run reaches nothing the
64
- // user could not reach synchronously, and a cron/hook/verified-webhook
65
- // run blanket-passes like its dispatcher. Built server-side from the
66
- // resolved context, never from user input; the CRON_SECRET proves
67
- // origin, which is what lets the receiver trust the assertion.
68
- body: JSON.stringify({
69
- payload: serializer.serialize(evaluatedProperties.payload ?? {}),
70
- principal: {
71
- user: serializer.serialize(context.user ?? null),
72
- system: context.system === true
73
- }
74
- })
75
- }));
76
- addStepResult(context, routineContext, {
77
- result: {
78
- detached: true,
79
- endpointId: targetEndpointId
80
- },
81
- stepId: step.stepId
82
- });
83
- logger.debug({
84
- event: 'debug_end_endpoint_call',
85
- stepId: step.stepId,
86
- targetEndpointId,
87
- detached: true
88
- });
89
- return {
90
- status: 'continue'
91
- };
92
- }
93
32
  const result = await invokeEndpoint(context, {
94
33
  endpointId: evaluatedProperties.endpointId,
95
34
  payload: evaluatedProperties.payload,
@@ -20,7 +20,6 @@ import evaluateOperators from '../request/evaluateOperators.js';
20
20
  import getConnection from '../connections/getConnection.js';
21
21
  import getConnectionConfig from '../connections/getConnectionConfig.js';
22
22
  import getRequestResolver from '../request/getRequestResolver.js';
23
- import resolveTenant from '../request/resolveTenant.js';
24
23
  import validateSchemas from '../request/validateSchemas.js';
25
24
  async function handleRequest(context, routineContext, { request }) {
26
25
  const { logger } = context;
@@ -41,11 +40,6 @@ async function handleRequest(context, routineContext, { request }) {
41
40
  connection,
42
41
  requestConfig
43
42
  });
44
- const tenant = resolveTenant(context, {
45
- connection,
46
- connectionConfig,
47
- requestConfig
48
- });
49
43
  const { connectionProperties, requestProperties } = evaluateOperators(context, {
50
44
  connectionConfig,
51
45
  items,
@@ -78,8 +72,7 @@ async function handleRequest(context, routineContext, { request }) {
78
72
  endpointDepth: routineContext.endpointDepth,
79
73
  requestConfig,
80
74
  requestProperties,
81
- requestResolver,
82
- tenant
75
+ requestResolver
83
76
  });
84
77
  addStepResult(context, routineContext, {
85
78
  result,
@@ -51,12 +51,10 @@ async function handleValidateSchema(context, routineContext, { step }) {
51
51
  const error = new Error(buildErrorMessage(result.errors, step.stepId), {
52
52
  cause: result.errors
53
53
  });
54
- // Log under `err` — see controlThrow: only the `err` key runs the pino error
55
- // serializer, so `error` would drop the message from the log line.
56
54
  logger.error({
57
55
  event: 'error_validate_schema',
58
56
  stepId: step.stepId,
59
- err: error
57
+ error
60
58
  });
61
59
  return {
62
60
  status: 'error',
@@ -13,11 +13,8 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { type } from '@lowdefy/helpers';
16
- import handleAgentCall from './handleAgentCall.js';
17
- import handleAuthStep from './handleAuthStep.js';
18
16
  import handleControl from './control/handleControl.js';
19
17
  import handleEndpointCall from './handleEndpointCall.js';
20
- import handleRenderNotification from './handleRenderNotification.js';
21
18
  import handleRequest from './handleRequest.js';
22
19
  import handleValidateSchema from './handleValidateSchema.js';
23
20
  async function runRoutine(context, routineContext, { routine }) {
@@ -38,21 +35,6 @@ async function runRoutine(context, routineContext, { routine }) {
38
35
  step: routine
39
36
  });
40
37
  }
41
- if (routine.id?.startsWith?.('agent:')) {
42
- return await handleAgentCall(context, routineContext, {
43
- step: routine
44
- });
45
- }
46
- if (routine.id?.startsWith?.('auth:')) {
47
- return await handleAuthStep(context, routineContext, {
48
- step: routine
49
- });
50
- }
51
- if (routine.id?.startsWith?.('notification:')) {
52
- return await handleRenderNotification(context, routineContext, {
53
- step: routine
54
- });
55
- }
56
38
  return await handleControl(context, routineContext, {
57
39
  control: routine
58
40
  });
@@ -72,9 +72,10 @@ function createTextContext() {
72
72
  logger,
73
73
  readConfigFile: mockReadConfigFile,
74
74
  secrets,
75
- user: {
76
- id: 'id',
77
- roles: []
75
+ session: {
76
+ user: {
77
+ id: 'id'
78
+ }
78
79
  }
79
80
  });
80
81
  context.blockId = 'blockId';
@@ -12,50 +12,16 @@
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 { serializer, type } from '@lowdefy/helpers';
16
- import resolveDynamicContent from './dynamic/resolveDynamicContent.js';
17
- // Returns a status object so the page route can fork on the auth outcome:
18
- // - ok: render the page.
19
- // - not_found and unauthorized both collapse to the opaque /404 redirect -
20
- // wrong roles never reveal that the page exists.
21
- // - unauthenticated: a logged-out human gets the authPages.signIn redirect
22
- // with a callbackUrl back to the requested page.
23
- async function getPageConfig(context, { pageId, urlQuery }) {
24
- const pageConfig = await context.readConfigFile(`pages/${pageId}.json`);
25
- if (!pageConfig) {
26
- return {
27
- status: 'not_found'
28
- };
29
- }
30
- if (context.authorize(pageConfig)) {
15
+ */ import { serializer } from '@lowdefy/helpers';
16
+ async function getPageConfig({ authorize, readConfigFile }, { pageId }) {
17
+ const pageConfig = await readConfigFile(`pages/${pageId}.json`);
18
+ if (pageConfig && authorize(pageConfig)) {
31
19
  // eslint-disable-next-line no-unused-vars
32
20
  const { auth, ...rest } = pageConfig;
33
- if (rest.dynamic !== true) {
34
- // Use serializer.serialize to ensure ~k keys (non-enumerable after deserialize)
35
- // are made enumerable again for JSON transfer to client
36
- return {
37
- status: 'ok',
38
- pageConfig: serializer.serialize(rest)
39
- };
40
- }
41
- // readConfigFile caches parsed artifacts — deep copy before resolution so
42
- // one request's resolved content never reaches another via the cache.
43
- const resolved = await resolveDynamicContent(context, {
44
- pageConfig: serializer.copy(rest),
45
- urlQuery
46
- });
47
- return {
48
- status: 'ok',
49
- pageConfig: serializer.serialize(resolved)
50
- };
51
- }
52
- if (type.isNone(context.user)) {
53
- return {
54
- status: 'unauthenticated'
55
- };
21
+ // Use serializer.serialize to ensure ~k keys (non-enumerable after deserialize)
22
+ // are made enumerable again for JSON transfer to client
23
+ return serializer.serialize(rest);
56
24
  }
57
- return {
58
- status: 'unauthorized'
59
- };
25
+ return null;
60
26
  }
61
27
  export default getPageConfig;
@@ -12,20 +12,14 @@
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, ConfigError } from '@lowdefy/errors';
16
- import { type } from '@lowdefy/helpers';
17
- function authorizeRequest({ authorize, logger, user }, { requestConfig }) {
15
+ */ import { ConfigError } from '@lowdefy/errors';
16
+ function authorizeRequest({ authorize, logger }, { requestConfig }) {
18
17
  if (!authorize(requestConfig)) {
19
18
  logger.debug({
20
19
  event: 'debug_request_authorize',
21
20
  authorized: false,
22
21
  auth_config: requestConfig.auth
23
22
  });
24
- // Unauthenticated on a protected request - 401 tells the caller to fix
25
- // its credentials. Wrong roles stay opaque below.
26
- if (type.isNone(user)) {
27
- throw new AuthenticationError(`Authentication required for request "${requestConfig.requestId}".`);
28
- }
29
23
  // Throw does not exist error to avoid leaking information that request exists to unauthorized users
30
24
  throw new ConfigError(`Request "${requestConfig.requestId}" does not exist.`, {
31
25
  configKey: requestConfig['~k']
@@ -22,7 +22,6 @@ import getConnection from '../connections/getConnection.js';
22
22
  import getConnectionConfig from '../connections/getConnectionConfig.js';
23
23
  import getRequestConfig from './getRequestConfig.js';
24
24
  import getRequestResolver from './getRequestResolver.js';
25
- import resolveTenant from './resolveTenant.js';
26
25
  import validateSchemas from './validateSchemas.js';
27
26
  import createEvaluateOperators from '../../context/createEvaluateOperators.js';
28
27
  async function callRequest(context, { blockId, pageId, payload, requestId }) {
@@ -57,11 +56,6 @@ async function callRequest(context, { blockId, pageId, payload, requestId }) {
57
56
  connection,
58
57
  requestConfig
59
58
  });
60
- const tenant = resolveTenant(context, {
61
- connection,
62
- connectionConfig,
63
- requestConfig
64
- });
65
59
  const { connectionProperties, requestProperties } = evaluateOperators(context, {
66
60
  connectionConfig,
67
61
  payload: requestPayload,
@@ -93,8 +87,7 @@ async function callRequest(context, { blockId, pageId, payload, requestId }) {
93
87
  endpointDepth: 0,
94
88
  requestConfig,
95
89
  requestProperties,
96
- requestResolver,
97
- tenant
90
+ requestResolver
98
91
  });
99
92
  return {
100
93
  id: requestConfig.id,
@@ -14,7 +14,7 @@
14
14
  limitations under the License.
15
15
  */ import { RequestError, ServiceError } from '@lowdefy/errors';
16
16
  import invokeEndpoint from '../endpoints/invokeEndpoint.js';
17
- async function callRequestResolver(context, { connectionProperties, endpointDepth, requestConfig, requestProperties, requestResolver, tenant }) {
17
+ async function callRequestResolver(context, { connectionProperties, endpointDepth, requestConfig, requestProperties, requestResolver }) {
18
18
  const { blockId, endpointId, logger, pageId, payload } = context;
19
19
  // stepId for endpoint steps (after build), requestId for page requests
20
20
  const stepOrRequestId = requestConfig.stepId ?? requestConfig.requestId;
@@ -52,11 +52,7 @@ async function callRequestResolver(context, { connectionProperties, endpointDept
52
52
  pageId,
53
53
  payload,
54
54
  request: requestProperties,
55
- requestId: stepOrRequestId,
56
- // The tenant verdict ({ field, value } or null/undefined) computed by
57
- // resolveTenant - connection types implementing the scoping contract
58
- // enforce it (stamp writes, merge filters, inject pipeline matches).
59
- tenant: tenant ?? null
55
+ requestId: stepOrRequestId
60
56
  });
61
57
  return response;
62
58
  } catch (error) {
@@ -13,19 +13,18 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import createAuthorize from '../context/createAuthorize.js';
16
- function testContext({ appMeta = {}, auth, config = {}, connections = {}, headers = {}, logger = {
16
+ function testContext({ appMeta = {}, config = {}, connections = {}, headers = {}, logger = {
17
17
  debug: ()=>{},
18
18
  error: ()=>{},
19
19
  info: ()=>{},
20
20
  warn: ()=>{}
21
21
  }, operators = {
22
22
  _test: ()=>'test'
23
- }, readConfigFile, secrets = {}, steps = {}, user = null } = {}) {
23
+ }, readConfigFile, secrets = {}, session } = {}) {
24
24
  return {
25
25
  appMeta,
26
- auth,
27
26
  authorize: createAuthorize({
28
- user
27
+ session
29
28
  }),
30
29
  config,
31
30
  connections,
@@ -37,8 +36,9 @@ function testContext({ appMeta = {}, auth, config = {}, connections = {}, header
37
36
  operators,
38
37
  readConfigFile,
39
38
  secrets,
40
- steps,
41
- user
39
+ session,
40
+ steps: {},
41
+ user: session?.user
42
42
  };
43
43
  }
44
44
  export default testContext;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lowdefy/api",
3
- "version": "0.0.0-experimental-20260720072521",
3
+ "version": "0.0.0-experimental-20260720135014",
4
4
  "license": "Apache-2.0",
5
5
  "description": "",
6
6
  "homepage": "https://lowdefy.com",
@@ -34,24 +34,18 @@
34
34
  "dist/*"
35
35
  ],
36
36
  "dependencies": {
37
- "@better-auth/passkey": "1.6.23",
38
- "@lowdefy/ajv": "0.0.0-experimental-20260720072521",
39
- "@lowdefy/build": "0.0.0-experimental-20260720072521",
40
- "@lowdefy/connection-smtp": "0.0.0-experimental-20260720072521",
41
- "@lowdefy/email-templates": "0.0.0-experimental-20260720072521",
42
- "@lowdefy/errors": "0.0.0-experimental-20260720072521",
43
- "@lowdefy/helpers": "0.0.0-experimental-20260720072521",
44
- "@lowdefy/node-utils": "0.0.0-experimental-20260720072521",
45
- "@lowdefy/nunjucks": "0.0.0-experimental-20260720072521",
46
- "@lowdefy/operators": "0.0.0-experimental-20260720072521",
47
- "@lowdefy/operators-js": "0.0.0-experimental-20260720072521",
48
- "better-auth": "1.6.23",
49
- "nodemailer": "9.0.3"
37
+ "@lowdefy/ajv": "0.0.0-experimental-20260720135014",
38
+ "@lowdefy/errors": "0.0.0-experimental-20260720135014",
39
+ "@lowdefy/helpers": "0.0.0-experimental-20260720135014",
40
+ "@lowdefy/node-utils": "0.0.0-experimental-20260720135014",
41
+ "@lowdefy/nunjucks": "0.0.0-experimental-20260720135014",
42
+ "@lowdefy/operators": "0.0.0-experimental-20260720135014",
43
+ "@lowdefy/operators-js": "0.0.0-experimental-20260720135014"
50
44
  },
51
45
  "devDependencies": {
52
46
  "@jest/globals": "28.1.3",
53
- "@swc/cli": "0.8.1",
54
- "@swc/core": "1.15.32",
47
+ "@swc/cli": "0.8.0",
48
+ "@swc/core": "1.15.18",
55
49
  "@swc/jest": "0.2.39",
56
50
  "jest": "28.1.3"
57
51
  },
@@ -1,33 +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 createAuthorize from './createAuthorize.js';
16
- // The single writer of the trusted, caller-less system-context invariants
17
- // (Decision 1). It sets all three together on an existing context so no caller
18
- // can set one without the others:
19
- // - user: null — caller-less (detectable via type.isNone)
20
- // - system: true — the run-level trust marker every authorization layer reads
21
- // - authorize — derived from createAuthorize so it reads context.system
22
- // createSystemContext builds a FRESH context for the off-request hook path;
23
- // this applies the same state to a request context a runner already holds
24
- // (cron at construction, webhook once its verify gate passes, a detached run
25
- // whose dispatcher was itself a system context). One greppable place means a
26
- // future runner cannot reintroduce the silent-no-op bug by forgetting a line.
27
- function applySystemTrust(context) {
28
- context.user = null;
29
- context.system = true;
30
- context.authorize = createAuthorize(context);
31
- return context;
32
- }
33
- export default applySystemTrust;
@@ -1,72 +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 applySystemTrust from './applySystemTrust.js';
16
- import createEvaluateOperators from './createEvaluateOperators.js';
17
- import createReadConfigFile from './createReadConfigFile.js';
18
- import getOrganizationBinding from '../routes/auth/organizations/getOrganizationBinding.js';
19
- // Builds a fresh off-request context for a trusted, caller-less system context -
20
- // an auth hook fire. The caller is the auth engine, not a user: `user` is null
21
- // so the run is detectable as caller-less (`type.isNone(context.user)`) and
22
- // `_user` resolves to nothing (the hook's subject is in `_payload`). The run is
23
- // trusted at construction (`context.system = true`), the single trust marker
24
- // every authorization layer reads (Decision 1); its `authorize` is derived from
25
- // createAuthorize like every other layer, so endpoint auth is not re-checked
26
- // against a session (Decision 2).
27
- function createSystemContext({ agents, appMeta, auth, buildDirectory, config, configDirectory, connections, createHandleError, fileCache, i18n, jsMap, logger, notifications, operators, rid, secrets, steps, websockets }) {
28
- const context = {
29
- rid,
30
- agents,
31
- appMeta,
32
- auth,
33
- buildDirectory,
34
- config,
35
- configDirectory,
36
- connections,
37
- fileCache,
38
- headers: {},
39
- i18n: i18n?.defaultLocale ? {
40
- ...i18n,
41
- active: i18n.defaultLocale
42
- } : undefined,
43
- jsMap,
44
- logger,
45
- notifications,
46
- operators,
47
- req: {
48
- url: 'system:auth-hook',
49
- method: null,
50
- hostname: null
51
- },
52
- secrets,
53
- steps,
54
- websockets
55
- };
56
- // Hook routines read the retained organizations state too - a step or
57
- // _organization inside a hook-bound endpoint resolves the same pinned org.
58
- context.organization = getOrganizationBinding({
59
- auth: auth ?? null
60
- });
61
- // Trusted, caller-less system context (Decisions 1, 2): user: null,
62
- // system: true, and authorize derived from createAuthorize - the same
63
- // invariant bundle the caller-less runners apply, set in one place.
64
- applySystemTrust(context);
65
- context.handleError = createHandleError({
66
- context
67
- });
68
- context.readConfigFile = createReadConfigFile(context);
69
- context.evaluateOperators = createEvaluateOperators(context);
70
- return context;
71
- }
72
- export default createSystemContext;
@@ -1,41 +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
- */ // The single writer of the pre-resolved-caller shape. A dev mock user, the dev
16
- // headless renderer cookie, and the e2e test cookie each substitute for the
17
- // whole resolveAuthentication step, and must match the shape it produces. That
18
- // output always carries roles as an array and attributes as an object (a
19
- // whole-bag { _user: 'attributes' } read gives {} on a real caller), so both
20
- // are floored here. profile and activeOrganizationId are only ever produced by
21
- // a real user-row/member read, so they are left exactly as the caller carries
22
- // them - absent stays absent, and a bare _user.profile read is null-safe.
23
- // organizationId (the tenant wall's org value) mirrors resolveAuthentication,
24
- // where it always equals activeOrganizationId - an injected caller declaring
25
- // either key gets both, so mock/e2e callers pass walled connections without
26
- // duplicating the org under two names. A caller with neither stays org-less
27
- // and fails closed on walled connections, same as a strategy caller.
28
- function normalizeInjectedCaller(user) {
29
- const normalized = {
30
- ...user,
31
- roles: user.roles ?? [],
32
- attributes: user.attributes ?? {}
33
- };
34
- const organizationId = user.organizationId ?? user.activeOrganizationId;
35
- if (organizationId != null) {
36
- normalized.organizationId = organizationId;
37
- normalized.activeOrganizationId = user.activeOrganizationId ?? organizationId;
38
- }
39
- return normalized;
40
- }
41
- export default normalizeInjectedCaller;
@@ -1,107 +0,0 @@
1
- /* eslint-disable no-param-reassign */ /*
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 resolveStrategyCaller from './resolveStrategyCaller.js';
17
- // resolveAuthentication is the single writer of context.user - nothing
18
- // downstream rewrites it. The session and strategy branches are disjoint
19
- // ways to become a caller: a resolved session is terminal - it never falls
20
- // through to strategies, so a walled-out member cannot be silently
21
- // re-admitted by an apiKey/jwt strategy carrying config-granted roles. API
22
- // strategies are tried, in config order, only when no session resolves.
23
- //
24
- // The active member row is the hard membership wall and the role source in
25
- // one indexed read ({ userId, organizationId } on the member model), live on
26
- // every request so membership removal and role changes take effect
27
- // immediately - roles are deliberately not stamped onto the session. A
28
- // session whose user holds no member row in the active org resolves to
29
- // unauthenticated: an invitee's pre-accept session (the session.create
30
- // carve-out), a stale cookie from another app's deployment, and a member
31
- // removed mid-session are all treated as logged out, not logged-in with no
32
- // roles.
33
- //
34
- // member.role stores multiple roles as a comma-separated string - split back
35
- // into the array Lowdefy authorization expects. context.user.attributes is
36
- // the one merged bag of authorization inputs: user.attributes (global) and
37
- // the active member's attributes (per-org), shallow per-key merge where the
38
- // member value wins - nested objects replace, never deep-merge.
39
- //
40
- // user.profile - the opaque display-and-app-data bag - rides the
41
- // session.user spread onto the resolved caller (denormalization, not a join:
42
- // no extra lookup). A user with no profile writes carries no profile key, so
43
- // _user.profile is undefined - never a synthesized {}. Strategy callers lack
44
- // profile exactly as they lack name and image.
45
- async function resolveAuthentication(context, { auth, headers, strategies }) {
46
- if (type.isNone(auth)) {
47
- context.user = null;
48
- return;
49
- }
50
- const session = await auth.api.getSession({
51
- headers
52
- });
53
- if (type.isNone(session)) {
54
- context.user = await resolveStrategyCaller({
55
- headers,
56
- logger: context.logger,
57
- strategies
58
- });
59
- return;
60
- }
61
- const activeOrganizationId = session.session.activeOrganizationId;
62
- if (type.isNone(activeOrganizationId)) {
63
- context.user = null;
64
- return;
65
- }
66
- const { adapter } = await auth.$context;
67
- const member = await adapter.findOne({
68
- model: 'member',
69
- where: [
70
- {
71
- field: 'userId',
72
- value: session.user.id
73
- },
74
- {
75
- field: 'organizationId',
76
- value: activeOrganizationId
77
- }
78
- ]
79
- });
80
- if (type.isNone(member)) {
81
- context.user = null;
82
- return;
83
- }
84
- const roles = (member.role ?? '').split(',').map((role)=>role.trim()).filter(Boolean);
85
- context.user = {
86
- ...session.user,
87
- roles,
88
- attributes: {
89
- ...session.user.attributes ?? {},
90
- ...member.attributes ?? {}
91
- },
92
- activeOrganizationId,
93
- // organizationId is the caller's active org in its serialized string form -
94
- // the value the tenant wall stamps onto and filters walled collections with,
95
- // and the one operators read as _user: organizationId. It resolves under
96
- // both organizations policies (under pinned it always equals the pinned
97
- // org, since set-active-organization is disabled there).
98
- organizationId: activeOrganizationId
99
- };
100
- // impersonatedBy is a BetterAuth admin plugin session field - present only
101
- // while an admin is impersonating this session. Steps read it off the
102
- // settled _user surface, so it is omitted (not set to undefined) when absent.
103
- if (!type.isNone(session.session.impersonatedBy)) {
104
- context.user.impersonatedBy = session.session.impersonatedBy;
105
- }
106
- }
107
- export default resolveAuthentication;