@lowdefy/api 0.0.0-experimental-20261007124348 → 0.0.0-experimental-20261009120232

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.
@@ -12,13 +12,15 @@
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 { ServerParser } from '@lowdefy/operators';
15
+ */ import { markCredential } from '@lowdefy/node-utils';
16
+ import { ServerParser } from '@lowdefy/operators';
16
17
  function createEvaluateOperators(context) {
17
18
  const { appMeta, i18n, jsMap, operators, organization, secrets, user } = context;
18
19
  const operatorsParser = new ServerParser({
19
20
  i18n,
20
21
  jsMap,
21
22
  lowdefyApp: appMeta,
23
+ markCredential,
22
24
  operators,
23
25
  organization,
24
26
  secrets,
@@ -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 { decodeJwt, jwtVerify } from 'jose';
15
+ */ import { createHash } from 'node:crypto';
16
+ import { decodeJwt, jwtVerify } from 'jose';
16
17
  import { normalizeCaller, type } from '@lowdefy/helpers';
17
18
  import findPendingInvitation from '../routes/auth/organizations/findPendingInvitation.js';
18
19
  import { getRegisteredOrganization } from '../routes/auth/organizations/getOrganizationBinding.js';
@@ -94,7 +95,11 @@ function passkeyConfigured({ auth }) {
94
95
  // The membership wall and the caller assembly, shared verbatim by the session
95
96
  // and MCP bearer branches so the two ways to become a member caller cannot
96
97
  // drift - one member read, one role source, one caller shape.
97
- async function resolveMemberCaller(context, { adapter, auth, organizationId, user }) {
98
+ //
99
+ // memberId is passed only by the member token branch: a token works for the
100
+ // member row it was made for, so a member who left and rejoined - a new row -
101
+ // holds no old tokens.
102
+ async function resolveMemberCaller(context, { adapter, auth, memberId, organizationId, user }) {
98
103
  const member = await adapter.findOne({
99
104
  model: 'member',
100
105
  where: [
@@ -112,6 +117,10 @@ async function resolveMemberCaller(context, { adapter, auth, organizationId, use
112
117
  context.logger.debug(`User "${user.id}" has no member row in organization "${organizationId}" - resolved unauthenticated.`);
113
118
  return null;
114
119
  }
120
+ if (!type.isUndefined(memberId) && member.id !== memberId) {
121
+ context.logger.debug(`User "${user.id}" holds member row "${member.id}" in organization "${organizationId}", not the row "${memberId}" the token was made for - resolved unauthenticated.`);
122
+ return null;
123
+ }
115
124
  // member.role is a CSV BetterAuth writes over a closed three-name set the
116
125
  // platform itself writes, so no comma can appear inside a name.
117
126
  const orgRoles = (member.role ?? '').split(',').map((role)=>role.trim()).filter(Boolean);
@@ -230,10 +239,186 @@ function hasMcpAudienceBearer({ context, headers }) {
230
239
  }
231
240
  return rejected;
232
241
  }
233
- // The MCP bearer branch. The route accepts exactly one credential kind: an
234
- // access token this app's authorization server minted for the MCP resource -
235
- // a session cookie or a strategy credential never authenticates here. The
236
- // token is verified in-process with jose against the AS's own signing keys.
242
+ // A banned user is refused on every MCP bearer, OAuth or member token: a ban
243
+ // deletes the user's sessions, but nothing else on the bearer path would read
244
+ // it. A ban with an expiry in the past no longer applies.
245
+ function isBanned({ user }) {
246
+ if (user.banned !== true) {
247
+ return false;
248
+ }
249
+ return type.isNone(user.banExpires) || new Date(user.banExpires) > new Date();
250
+ }
251
+ // The user read, ban check and membership wall both MCP bearers share once
252
+ // each has settled which user and organization it acts for. Returns the
253
+ // resolved caller, or null when the user is gone, banned or not a member.
254
+ async function resolveBearerMember(context, { adapter, auth, memberId, organizationId, userId }) {
255
+ // The bearer carries only the user id - the caller's user fields are read live.
256
+ const user = await adapter.findOne({
257
+ model: 'user',
258
+ where: [
259
+ {
260
+ field: 'id',
261
+ value: userId
262
+ }
263
+ ]
264
+ });
265
+ if (type.isNone(user)) {
266
+ context.logger.debug({
267
+ event: 'auth_mcp_no_user',
268
+ organizationId
269
+ }, `MCP bearer rejected: user "${userId}" has no user row.`);
270
+ return null;
271
+ }
272
+ if (isBanned({
273
+ user
274
+ })) {
275
+ context.logger.debug({
276
+ event: 'auth_mcp_user_banned',
277
+ organizationId
278
+ }, `MCP bearer rejected: user "${userId}" is banned.`);
279
+ return null;
280
+ }
281
+ const member = await resolveMemberCaller(context, {
282
+ adapter,
283
+ auth,
284
+ memberId,
285
+ organizationId,
286
+ user
287
+ });
288
+ if (type.isNone(member)) {
289
+ context.logger.debug({
290
+ event: 'auth_mcp_no_membership',
291
+ organizationId
292
+ }, `MCP bearer rejected: user "${userId}" is not a member of organization "${organizationId}".`);
293
+ return null;
294
+ }
295
+ return member;
296
+ }
297
+ // Member tokens are the long-lived bearer a script sends in place of an OAuth
298
+ // access token. The prefix tells them apart from a JWT without parsing, and
299
+ // lets secret scanners and people recognise a leaked one.
300
+ const MEMBER_TOKEN_PREFIX = 'ldf_mcp_';
301
+ // lastUsedAt is display data, not an audit trail: written at most once an hour
302
+ // per token so a script calling several times a minute costs no write per call.
303
+ const LAST_USED_INTERVAL_MS = 60 * 60 * 1000;
304
+ function refuseMemberToken(context, { description }) {
305
+ context.user = null;
306
+ context.mcpAuth = {
307
+ tokenStatus: 'invalid',
308
+ memberToken: true,
309
+ description
310
+ };
311
+ }
312
+ const MEMBER_GONE = "This token's member can no longer use it.";
313
+ async function touchMemberToken(context, { adapter, row }) {
314
+ const lastUsedAt = type.isNone(row.lastUsedAt) ? 0 : new Date(row.lastUsedAt).getTime();
315
+ if (Date.now() - lastUsedAt < LAST_USED_INTERVAL_MS) {
316
+ return;
317
+ }
318
+ try {
319
+ await adapter.update({
320
+ model: 'mcpToken',
321
+ where: [
322
+ {
323
+ field: 'id',
324
+ value: row.id
325
+ }
326
+ ],
327
+ update: {
328
+ lastUsedAt: new Date()
329
+ }
330
+ });
331
+ } catch (error) {
332
+ context.logger.warn({
333
+ event: 'auth_mcp_token_last_used_failed',
334
+ err: error,
335
+ tokenId: row.id
336
+ }, `Could not record when member token "${row.id}" was last used: ${error.message}`);
337
+ }
338
+ }
339
+ // The member token branch. The token is looked up by its SHA-256 - the token
340
+ // itself is never stored - and acts as the member row it was made for, in the
341
+ // organization it was made in. Every refusal carries a description the route
342
+ // returns in the challenge, since a script cannot sign in and needs to know
343
+ // why: switched off, expired, or its member can no longer use it.
344
+ async function resolveMemberTokenCaller(context, { auth, token }) {
345
+ const { adapter } = await auth.$context;
346
+ const row = await adapter.findOne({
347
+ model: 'mcpToken',
348
+ where: [
349
+ {
350
+ field: 'hash',
351
+ value: createHash('sha256').update(token).digest('hex')
352
+ }
353
+ ]
354
+ });
355
+ if (type.isNone(row)) {
356
+ context.logger.debug({
357
+ event: 'auth_mcp_member_token_rejected'
358
+ }, 'MCP member token rejected: no token matches.');
359
+ refuseMemberToken(context, {
360
+ description: 'This token was switched off or does not exist.'
361
+ });
362
+ return;
363
+ }
364
+ if (!type.isNone(row.expiresAt) && new Date(row.expiresAt) <= new Date()) {
365
+ context.logger.debug({
366
+ event: 'auth_mcp_member_token_rejected',
367
+ tokenId: row.id
368
+ }, `MCP member token "${row.id}" rejected: it expired at ${new Date(row.expiresAt).toISOString()}.`);
369
+ refuseMemberToken(context, {
370
+ description: 'This token has expired.'
371
+ });
372
+ return;
373
+ }
374
+ const registered = getRegisteredOrganization({
375
+ auth
376
+ });
377
+ if (registered?.policy === 'pinned' && row.organizationId !== registered.slug) {
378
+ context.logger.debug({
379
+ event: 'auth_mcp_member_token_rejected',
380
+ tokenId: row.id
381
+ }, `MCP member token "${row.id}" rejected: its organization "${row.organizationId}" is not this app's pinned organization "${registered.slug}".`);
382
+ refuseMemberToken(context, {
383
+ description: MEMBER_GONE
384
+ });
385
+ return;
386
+ }
387
+ const member = await resolveBearerMember(context, {
388
+ adapter,
389
+ auth,
390
+ memberId: row.memberId,
391
+ organizationId: row.organizationId,
392
+ userId: row.userId
393
+ });
394
+ if (type.isNone(member)) {
395
+ refuseMemberToken(context, {
396
+ description: MEMBER_GONE
397
+ });
398
+ return;
399
+ }
400
+ await touchMemberToken(context, {
401
+ adapter,
402
+ row
403
+ });
404
+ context.mcpAuth = {
405
+ tokenStatus: 'valid',
406
+ tokenId: row.id,
407
+ organizationId: row.organizationId,
408
+ // Every MCP scope: the token acts as the member who made it, and the
409
+ // member's roles still gate every tool.
410
+ grantedScopes: MCP_SCOPES
411
+ };
412
+ context.user = {
413
+ ...member,
414
+ auth_method: 'mcp'
415
+ };
416
+ }
417
+ // The MCP bearer branch. The route accepts two credential kinds: an access
418
+ // token this app's authorization server minted for the MCP resource, and a
419
+ // member token (see resolveMemberTokenCaller) - a session cookie or a strategy
420
+ // credential never authenticates here. The access token is verified in-process
421
+ // with jose against the AS's own signing keys.
237
422
  // The organization the token acts in is its organization_id claim - the
238
423
  // consent referenceId the member chose at authorization, stamped by the AS
239
424
  // (buildOauthPostLogin) - never a path segment or a request parameter. The
@@ -255,6 +440,13 @@ async function resolveMcpCaller(context, { auth, headers }) {
255
440
  };
256
441
  return;
257
442
  }
443
+ if (token.startsWith(MEMBER_TOKEN_PREFIX)) {
444
+ await resolveMemberTokenCaller(context, {
445
+ auth,
446
+ token
447
+ });
448
+ return;
449
+ }
258
450
  let payload;
259
451
  try {
260
452
  ({ payload } = await jwtVerify(token, getMcpJwks({
@@ -367,52 +559,26 @@ async function resolveMcpCaller(context, { auth, headers }) {
367
559
  context.mcpAuth = validMcpAuth;
368
560
  return;
369
561
  }
370
- // A token whose subject is no longer a member of its organization - removed,
371
- // left, or the user deleted - resolves invalid, not to the anonymous caller:
372
- // the route answers invalid with the sign-in challenge, so the client
373
- // re-runs authorization and its organization choice instead of holding a
374
- // token that works for nothing.
375
- const invalidNoMembership = {
376
- clientId,
377
- organizationId,
378
- tokenStatus: 'invalid',
379
- parseableJwt: true,
380
- noMembership: true
381
- };
382
- // The bearer carries only sub - the caller's user fields are read live.
383
- const user = await adapter.findOne({
384
- model: 'user',
385
- where: [
386
- {
387
- field: 'id',
388
- value: payload.sub
389
- }
390
- ]
391
- });
392
- if (type.isNone(user)) {
393
- context.logger.debug({
394
- event: 'auth_mcp_no_membership',
395
- clientId,
396
- organizationId
397
- }, `MCP bearer token rejected: subject "${payload.sub}" has no user row.`);
398
- context.user = null;
399
- context.mcpAuth = invalidNoMembership;
400
- return;
401
- }
402
- const member = await resolveMemberCaller(context, {
562
+ const member = await resolveBearerMember(context, {
403
563
  adapter,
404
564
  auth,
405
565
  organizationId,
406
- user
566
+ userId: payload.sub
407
567
  });
408
568
  if (type.isNone(member)) {
409
- context.logger.debug({
410
- event: 'auth_mcp_no_membership',
411
- clientId,
412
- organizationId
413
- }, `MCP bearer token rejected: user "${user.id}" is not a member of organization "${organizationId}".`);
569
+ // A token whose subject is no longer a member of its organization -
570
+ // removed, left, banned, or the user deleted - resolves invalid, not to the
571
+ // anonymous caller: the route answers invalid with the sign-in challenge,
572
+ // so the client re-runs authorization and its organization choice instead
573
+ // of holding a token that works for nothing.
414
574
  context.user = null;
415
- context.mcpAuth = invalidNoMembership;
575
+ context.mcpAuth = {
576
+ clientId,
577
+ organizationId,
578
+ tokenStatus: 'invalid',
579
+ parseableJwt: true,
580
+ noMembership: true
581
+ };
416
582
  return;
417
583
  }
418
584
  context.mcpAuth = validMcpAuth;
@@ -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 modelNames from './modelNames.js';
16
+ // Member tokens for MCP scripts live in the auth database as their own model,
17
+ // so the adapter reads and writes them like every other auth row and the MCP
18
+ // route's lookup is one more indexed read beside consents, users and members.
19
+ // The plugin declares the schema only - no endpoints: tokens are created and
20
+ // revoked by the auth steps, never over BetterAuth's HTTP surface. The token
21
+ // itself is never stored, only its SHA-256 (hash) and its first characters
22
+ // (start) so people can tell tokens apart.
23
+ function buildMcpTokenPlugin() {
24
+ return {
25
+ id: 'lowdefy-mcp-token',
26
+ schema: {
27
+ mcpToken: {
28
+ modelName: modelNames.mcpToken,
29
+ fields: {
30
+ organizationId: {
31
+ type: 'string',
32
+ required: true,
33
+ index: true
34
+ },
35
+ userId: {
36
+ type: 'string',
37
+ required: true,
38
+ index: true
39
+ },
40
+ // The member row the token was made for. The route accepts the token
41
+ // only while that row stands, so leaving, removal or deletion ends
42
+ // it by any path, and a rejoined member's new row holds no old tokens.
43
+ memberId: {
44
+ type: 'string',
45
+ required: true
46
+ },
47
+ name: {
48
+ type: 'string',
49
+ required: true
50
+ },
51
+ hash: {
52
+ type: 'string',
53
+ required: true,
54
+ unique: true
55
+ },
56
+ start: {
57
+ type: 'string',
58
+ required: true
59
+ },
60
+ createdAt: {
61
+ type: 'date',
62
+ required: true
63
+ },
64
+ expiresAt: {
65
+ type: 'date',
66
+ required: false
67
+ },
68
+ lastUsedAt: {
69
+ type: 'date',
70
+ required: false
71
+ }
72
+ }
73
+ }
74
+ }
75
+ };
76
+ }
77
+ export default buildMcpTokenPlugin;
@@ -0,0 +1,48 @@
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 unique index on the member token hash, created at server start. It is
17
+ // kept out of ensureAuthIndexes on purpose: that list guards the organization
18
+ // mint, which refuses to run while it fails, and a token index problem must
19
+ // never block sign-ups. The MCP route's lookup by hash is correct without the
20
+ // index, only slower, so a failure is logged and nothing waits on it.
21
+ //
22
+ // The caller fires this without awaiting it, so everything that can reject -
23
+ // the auth context included - sits inside the try.
24
+ async function ensureMcpTokenIndexes({ auth, logger }) {
25
+ try {
26
+ const { adapter } = await auth.$context;
27
+ const ensureUniqueIndexes = adapter.options?.ensureUniqueIndexes;
28
+ if (!type.isFunction(ensureUniqueIndexes)) {
29
+ logger.warn(`Auth database adapter "${adapter.id}" can not create indexes. Create a unique index on the member token hash, or each MCP call with a member token scans the token collection.`);
30
+ return;
31
+ }
32
+ await ensureUniqueIndexes({
33
+ indexes: [
34
+ {
35
+ model: 'mcpToken',
36
+ fields: [
37
+ 'hash'
38
+ ]
39
+ }
40
+ ]
41
+ });
42
+ } catch (error) {
43
+ logger.error({
44
+ err: error
45
+ }, `Could not create the unique index on the member token hash: ${error.message} Member tokens still work, but each MCP call with one scans the token collection.`);
46
+ }
47
+ }
48
+ export default ensureMcpTokenIndexes;
@@ -14,6 +14,7 @@
14
14
  limitations under the License.
15
15
  */ import { betterAuth } from 'better-auth';
16
16
  import ensureAuthIndexes from './organizations/ensureAuthIndexes.js';
17
+ import ensureMcpTokenIndexes from './ensureMcpTokenIndexes.js';
17
18
  import ensureOrganization from './organizations/ensureOrganization.js';
18
19
  import getBetterAuthConfig from './getBetterAuthConfig.js';
19
20
  import { getMcpResourceUri } from '../mcp/getMcpUri.js';
@@ -77,6 +78,14 @@ function getBetterAuth({ appMeta, authJson, config, createSystemContext, dev, lo
77
78
  logger
78
79
  }).catch(()=>{});
79
80
  }
81
+ // Member tokens exist only beside the MCP authorization server. Their index
82
+ // ensure logs its own failure and never throws.
83
+ if (authJson.database && authJson.oauthProvider) {
84
+ ensureMcpTokenIndexes({
85
+ auth: instance,
86
+ logger
87
+ });
88
+ }
80
89
  // Ensure the pinned organization exists at startup - created if missing,
81
90
  // untouched otherwise. The engine hooks await the same memoized ensure per
82
91
  // fire, so a failure here only defers seeding to the first sign-in. A
@@ -25,6 +25,7 @@ import { ConfigError, LowdefyInternalError } from '@lowdefy/errors';
25
25
  import getCanonicalUrl from '../../context/getCanonicalUrl.js';
26
26
  import buildAdminPlugin from './buildAdminPlugin.js';
27
27
  import buildCaptchaPlugin from './buildCaptchaPlugin.js';
28
+ import buildMcpTokenPlugin from './buildMcpTokenPlugin.js';
28
29
  import buildHooks from './hooks/buildHooks.js';
29
30
  import buildOrganizationPlugin from './organizations/buildOrganizationPlugin.js';
30
31
  import buildOauthPostLogin from './buildOauthPostLogin.js';
@@ -632,7 +633,10 @@ function getBetterAuthConfig({ appMeta, authJson, config = {}, createSystemConte
632
633
  // client_id_metadata_document_supported in the AS metadata.
633
634
  cimd({
634
635
  fetchClientMetadataResource
635
- }));
636
+ }), // Member tokens - the long-lived bearer a script sends to /api/mcp in
637
+ // place of an OAuth access token. Only meaningful beside the AS: without
638
+ // it the route authenticates nobody.
639
+ buildMcpTokenPlugin());
636
640
  }
637
641
  // The admin plugin is framework-controlled - it owns the user row's ban fields
638
642
  // and the endpoints the ban, delete and revoke-sessions steps call. Its whole
@@ -24,6 +24,7 @@ const modelNames = {
24
24
  member: 'user-members',
25
25
  invitation: 'user-invitations',
26
26
  twoFactor: 'user-two-factors',
27
- passkey: 'user-passkeys'
27
+ passkey: 'user-passkeys',
28
+ mcpToken: 'user-mcp-tokens'
28
29
  };
29
30
  export default modelNames;
@@ -31,13 +31,14 @@ import scheduleBackground from './scheduleBackground.js';
31
31
  //
32
32
  // The outcome exists only in the logs (`detached_run_done` with the routine's
33
33
  // status, or `detached_run_failed`), as it already did for the dispatcher.
34
- function acceptDetachedEndpoint(context, { endpointId, payload, principal }) {
34
+ function acceptDetachedEndpoint(context, { credentials, endpointId, payload, principal }) {
35
35
  // The run outlives the 202, so the request closing must not cancel it.
36
36
  context.signal = undefined;
37
37
  scheduleBackground(context, {
38
38
  event: 'detached_run',
39
39
  endpointId
40
40
  }, ()=>runDetachedEndpoint(context, {
41
+ credentials,
41
42
  endpointId,
42
43
  payload,
43
44
  principal
@@ -12,7 +12,9 @@
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 checkLiteralContent from '../../page/dynamic/checkLiteralContent.js';
15
+ */ import { ConfigError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ import checkLiteralContent from '../../page/dynamic/checkLiteralContent.js';
16
18
  import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
17
19
  async function controlReturn(context, routineContext, { control }) {
18
20
  const literalData = routineContext.literalData ?? null;
@@ -33,6 +35,21 @@ async function controlReturn(context, routineContext, { control }) {
33
35
  event: 'debug_control_return',
34
36
  response
35
37
  });
38
+ // :content_type sends a webhook's answer as text (createWebhookAnswer). The build allows it only
39
+ // in a webhook endpoint, and only as text/plain.
40
+ if (':content_type' in control) {
41
+ if (!type.isString(response)) {
42
+ throw new ConfigError(':return with :content_type text/plain must evaluate to a string.', {
43
+ received: response,
44
+ configKey: control['~k']
45
+ });
46
+ }
47
+ return {
48
+ status: 'return',
49
+ response,
50
+ contentType: control[':content_type']
51
+ };
52
+ }
36
53
  return {
37
54
  status: 'return',
38
55
  response
@@ -31,8 +31,9 @@ function errorBody({ code, message }) {
31
31
  // The HTTP status and body a webhook route answers with, from the routine's outcome. A :reject
32
32
  // answers the :status and :body it set (400 and an error body by default), also when it was
33
33
  // raised in an endpoint the routine called. A failed ValidateSchema step answers 400. Any other
34
- // failure answers 500 with a fixed message, so nothing from the error reaches the caller.
35
- function createWebhookAnswer(context, { error, response, status }) {
34
+ // failure answers 500 with a fixed message, so nothing from the error reaches the caller. A :return
35
+ // with :content_type answers its string as is, for a handshake that wants a text reply.
36
+ function createWebhookAnswer(context, { contentType, error, response, status }) {
36
37
  if (status === 'reject') {
37
38
  return {
38
39
  status: error.webhookStatus ?? 400,
@@ -60,6 +61,13 @@ function createWebhookAnswer(context, { error, response, status }) {
60
61
  })
61
62
  };
62
63
  }
64
+ if (contentType === 'text/plain') {
65
+ return {
66
+ status: 200,
67
+ body: response,
68
+ contentType
69
+ };
70
+ }
63
71
  return {
64
72
  status: 200,
65
73
  body: toPlainJson(context, response) ?? {
@@ -14,6 +14,7 @@
14
14
  limitations under the License.
15
15
  */ import { serializer } from '@lowdefy/helpers';
16
16
  import { ConfigError, LowdefyInternalError } from '@lowdefy/errors';
17
+ import { getMarkedCredentials } from '@lowdefy/node-utils';
17
18
  import addStepResult from './addStepResult.js';
18
19
  import createBoundSystemContext from '../../context/createBoundSystemContext.js';
19
20
  import evaluateRoutineOperators from './evaluateRoutineOperators.js';
@@ -85,7 +86,10 @@ async function handleEndpointCall(context, routineContext, { step }) {
85
86
  system: callContext.system === true,
86
87
  organizationId: callContext.boundOrganizationId ?? null,
87
88
  agent: routineContext.agent ?? null
88
- }
89
+ },
90
+ // The values this request marked with _credential, so the target's logs scrub them
91
+ // too: the target runs as a new request with a scope of its own.
92
+ credentials: getMarkedCredentials()
89
93
  })
90
94
  }));
91
95
  addStepResult(context, routineContext, {
@@ -43,7 +43,8 @@ async function handleRequest(context, routineContext, { request }) {
43
43
  const { tenant, tenantGuard } = resolveTenancy(context, {
44
44
  connection,
45
45
  connectionConfig,
46
- requestConfig
46
+ requestConfig,
47
+ writes: requestResolver.meta.checkWrite === true
47
48
  });
48
49
  const { connectionProperties, requestProperties } = evaluateOperators(context, {
49
50
  connectionConfig,
@@ -13,6 +13,7 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { serializer, type } from '@lowdefy/helpers';
16
+ import { markCredential } from '@lowdefy/node-utils';
16
17
  import applySystemTrust from '../../context/applySystemTrust.js';
17
18
  import authorizeApiEndpoint from './authorizeApiEndpoint.js';
18
19
  import buildEndpointResult from '../../response/buildEndpointResult.js';
@@ -33,8 +34,12 @@ import validatePayload from './validatePayload.js';
33
34
  // carried identity, exactly as a synchronous CallApi would.
34
35
  // Payload arrives serialized (dates etc. survive the HTTP hop via
35
36
  // @lowdefy/helpers serializer).
36
- async function runDetachedEndpoint(context, { endpointId, outsideCaller = false, payload, principal }) {
37
+ async function runDetachedEndpoint(context, { credentials = [], endpointId, outsideCaller = false, payload, principal }) {
37
38
  const { logger } = context;
39
+ // Marked before anything is logged: the payload can hold what the dispatcher marked.
40
+ if (credentials.length > 0) {
41
+ markCredential(credentials);
42
+ }
38
43
  context.endpointId = endpointId;
39
44
  // Rehydrate the dispatcher's identity carried across the CRON_SECRET-gated
40
45
  // hop BEFORE deriving authorizeOutcome and evaluateOperators, so both the auth check
@@ -28,7 +28,8 @@ import runWebhookVerify from './runWebhookVerify.js';
28
28
  // Lowdefy's { payload } envelope, so the routine receives
29
29
  // { body, query, headers } as its payload and its return value is sent back
30
30
  // verbatim (handshakes require exact response shapes). It returns the HTTP
31
- // answer, { status, body }, that the route sends (see createWebhookAnswer).
31
+ // answer, { status, body, contentType? }, that the route sends (see
32
+ // createWebhookAnswer): JSON, or text when contentType is text/plain.
32
33
  // Only endpoints that opt in are runnable here (a missing flag reads as a
33
34
  // missing endpoint — no probing).
34
35
  //
@@ -116,10 +117,11 @@ async function runWebhookEndpoint(context, { endpointId, rawBody, query, headers
116
117
  state: {},
117
118
  endpointDepth: 0
118
119
  };
119
- const { error, response, status } = await runRoutine(context, routineContext, {
120
+ const { contentType, error, response, status } = await runRoutine(context, routineContext, {
120
121
  routine: endpointConfig.routine
121
122
  });
122
123
  return createWebhookAnswer(context, {
124
+ contentType,
123
125
  error,
124
126
  response,
125
127
  status
@@ -54,9 +54,11 @@ async function runWebhookVerify(context, { verify, body, rawBody, query, headers
54
54
  connectionId: verify.connectionId,
55
55
  requestId: 'webhook.verify',
56
56
  properties: verify.properties ?? {},
57
- // Webhooks run in system context, so a verifier on a tenant connection
58
- // fails closed (caught at resolveTenancy below, verdict false) unless the
59
- // verify config opts out with tenant: none.
57
+ // The verifier runs before the run earns trust, with no caller
58
+ // organization, so a verifier on a tenant connection fails closed (caught
59
+ // at resolveTenancy below, verdict false) unless the verify config opts
60
+ // out with tenant: none - which may only read, like any tenant: none
61
+ // request.
60
62
  tenant: verify.tenant,
61
63
  '~k': verify['~k']
62
64
  };
@@ -69,13 +71,16 @@ async function runWebhookVerify(context, { verify, body, rawBody, query, headers
69
71
  tenancy = resolveTenancy(context, {
70
72
  connection,
71
73
  connectionConfig,
72
- requestConfig
74
+ requestConfig,
75
+ writes: requestResolver.meta.checkWrite === true
73
76
  });
74
77
  } catch (error) {
75
78
  // Only the org-less-caller refusal is a gate outcome - it must not reach
76
79
  // the unauthenticated webhook sender as an error body. Config errors
77
- // (tenant declared on a type without the contract) still throw: a
78
- // misconfigured verifier breaks loudly, per the contract above.
80
+ // (tenant declared on a type without the contract, a writing verifier
81
+ // under tenant: none) still throw: a misconfigured verifier breaks
82
+ // loudly, per the contract above, rather than failing every webhook as
83
+ // an unverified one inside the resolver call below.
79
84
  if (error.name !== 'AuthenticationError') {
80
85
  throw error;
81
86
  }
@@ -62,7 +62,8 @@ async function callRequest(context, { blockId, pageId, payload, requestId }) {
62
62
  const { tenant, tenantGuard } = resolveTenancy(context, {
63
63
  connection,
64
64
  connectionConfig,
65
- requestConfig
65
+ requestConfig,
66
+ writes: requestResolver.meta.checkWrite === true
66
67
  });
67
68
  // A page request runs outside any routine, so it evaluates against an empty frame.
68
69
  const routineContext = {
@@ -78,10 +78,11 @@ async function callRequestResolver(context, { agent = null, connectionProperties
78
78
  // resolveTenancy - connection types implementing the scoping contract
79
79
  // enforce it (stamp writes, merge filters, inject pipeline matches).
80
80
  tenant: tenant ?? null,
81
- // The unscoped write guard ({ field, stampChangeLog } or null) computed
82
- // by resolveTenancy for tenant: none requests and for shared connections
83
- // over a walled collection - scoping connection types assert every row
84
- // the request writes still carries a real organization id.
81
+ // The unscoped guard ({ field, readOnly } or null) computed by
82
+ // resolveTenancy: readOnly for tenant: none requests, which scoping
83
+ // connection types refuse to write under, and the write guard for shared
84
+ // connections over a walled collection, under which they assert every
85
+ // row the request writes still carries a real organization id.
85
86
  tenantGuard: tenantGuard ?? null
86
87
  });
87
88
  return response;
@@ -12,7 +12,7 @@
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';
15
+ */ import { AuthenticationError, ConfigError, TenantIntegrityError } from '@lowdefy/errors';
16
16
  import { type } from '@lowdefy/helpers';
17
17
  // The engine computes the tenant verdict, the connection enforces it. This is
18
18
  // the compute half, for a request, step or websocket against a connection:
@@ -51,13 +51,14 @@ import { type } from '@lowdefy/helpers';
51
51
  // unscoped connection must never be reachable.
52
52
  //
53
53
  // The request-level sentinel is unchanged by the inversion (amendment-1):
54
- // - `tenant: 'none'` on the request/step/websocket -> no verdict, and the
55
- // write guard. A visible, reviewable statement at the point of use - the
56
- // request-level opt-out for caller-less contexts. The opt-out lifts the
57
- // filter and the stamp, not the invariant that every walled row carries an
58
- // organization: the connection refuses a write that would leave a row
59
- // without one, and stamps the change-log record with the organization of
60
- // the row it records (stampChangeLog).
54
+ // - `tenant: 'none'` on the request/step/websocket -> no verdict, read only.
55
+ // A visible, reviewable statement at the point of use that lifts the filter
56
+ // so the request reads rows of every organization. A request type that
57
+ // writes (its resolver's meta.checkWrite, passed in as `writes`) is refused
58
+ // here, repeating the build error; the guard carries readOnly: true so the
59
+ // connection refuses the writes no request meta describes (an aggregation's
60
+ // $out/$merge, a plugin's walled client). Caller-less work writes as one
61
+ // organization instead, through CallApi `organization`.
61
62
  // - `tenant: 'authored'` on the request -> the verdict resolves exactly as
62
63
  // the default (an org-less caller is still rejected) and carries
63
64
  // authored: true, telling the connection resolver to AUDIT the request's
@@ -68,7 +69,10 @@ import { type } from '@lowdefy/helpers';
68
69
  // jobs, verified webhooks) has one only when a CallApi bound it to one
69
70
  // (context.boundOrganizationId); unbound system runs and strategy callers
70
71
  // have none, so they fail here by design - the wall never degrades to
71
- // unscoped access.
72
+ // unscoped access. An unbound system run that writes is a data fault, not
73
+ // an authentication one: it fails that request with TenantIntegrityError,
74
+ // logged at error level and captured, since a write with no organization
75
+ // would leave a row no walled read can see.
72
76
  const unscoped = {
73
77
  tenant: null,
74
78
  tenantGuard: null
@@ -112,18 +116,15 @@ function resolveSharedTenancy({ runtimeCapability, connectionConfig }) {
112
116
  field,
113
117
  connectionConfig
114
118
  });
115
- // A shared connection's change log is kept out of walled collections by the
116
- // build (validateSharedChangeLog), and its records belong to no
117
- // organization - so they are not stamped.
118
119
  return {
119
120
  tenant: null,
120
121
  tenantGuard: {
121
122
  field,
122
- stampChangeLog: false
123
+ readOnly: false
123
124
  }
124
125
  };
125
126
  }
126
- function resolveTenancy(context, { connection, connectionConfig, requestConfig }) {
127
+ function resolveTenancy(context, { connection, connectionConfig, requestConfig, writes = false }) {
127
128
  // Capability resolves from the runtime connection export first, then from
128
129
  // the tenantCapability the build stamped onto the connection artifact
129
130
  // (buildConnections) — the same types.js declaration the build check
@@ -165,12 +166,18 @@ function resolveTenancy(context, { connection, connectionConfig, requestConfig }
165
166
  field,
166
167
  connectionConfig
167
168
  });
169
+ const location = requestConfig.stepId ?? requestConfig.requestId ?? requestConfig.websocketId;
168
170
  if (requestConfig.tenant === 'none') {
171
+ if (writes) {
172
+ throw new ConfigError(`Request "${location}" is a ${requestConfig.type} request on tenant connection "${connectionConfig.connectionId}" with tenant: none, but tenant: none may only read. To write rows of one organization from a system run, call an endpoint with a CallApi step that names the "organization": its requests are filtered and stamped with that organization.`, {
173
+ configKey: requestConfig['~k']
174
+ });
175
+ }
169
176
  return {
170
177
  tenant: null,
171
178
  tenantGuard: {
172
179
  field,
173
- stampChangeLog: true
180
+ readOnly: true
174
181
  }
175
182
  };
176
183
  }
@@ -178,8 +185,22 @@ function resolveTenancy(context, { connection, connectionConfig, requestConfig }
178
185
  // other. Every other run's is the caller's.
179
186
  const value = context.system === true ? context.boundOrganizationId : context.user?.organization_id;
180
187
  if (!type.isString(value) || value === '') {
181
- const location = requestConfig.stepId ?? requestConfig.requestId ?? requestConfig.websocketId;
182
- throw new AuthenticationError(`Request "${location}" reads tenant connection "${connectionConfig.connectionId}" but no caller organization resolved. System-context and strategy callers carry no organization - the wall fails closed for them. To run this request in one organization from a system run, call its endpoint with a CallApi step that names the "organization". To run it outside the wall, declare tenant: none on it and author the organization value explicitly.`);
188
+ if (writes && context.system === true) {
189
+ const collection = connectionConfig.properties?.collection;
190
+ throw new TenantIntegrityError(`Request "${location}" writes to tenant connection "${connectionConfig.connectionId}" in a system run bound to no organization, so the row would carry no "${field}" and no walled read could see it. Call its endpoint with a CallApi step that names the "organization".`, {
191
+ collection: type.isString(collection) ? collection : null,
192
+ configKey: requestConfig['~k'],
193
+ connectionId: connectionConfig.connectionId,
194
+ endpointId: context.endpointId,
195
+ field
196
+ });
197
+ }
198
+ const verb = writes ? 'writes to' : 'reads';
199
+ let remedy = 'Strategy callers and callers with no active organization carry none - the wall fails closed for them.';
200
+ if (context.system === true) {
201
+ remedy = 'A system run carries none unless a CallApi bound it to one - the wall fails closed for it. To run this request in one organization from a system run, call its endpoint with a CallApi step that names the "organization".';
202
+ }
203
+ throw new AuthenticationError(`Request "${location}" ${verb} tenant connection "${connectionConfig.connectionId}" but no caller organization resolved. ${remedy}`);
183
204
  }
184
205
  if (requestConfig.tenant === 'authored') {
185
206
  return {
@@ -13,6 +13,7 @@
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 { runInCredentialScope } from '@lowdefy/node-utils';
16
17
  import redactErrorResponse from '../../response/redactErrorResponse.js';
17
18
  // Wraps one client websocket connection: parses frames, dispatches
18
19
  // subscribe/unsubscribe/publish to the channel registry, and answers every
@@ -163,7 +164,9 @@ function createWebSocketConnection(context, { registry, send }) {
163
164
  });
164
165
  return;
165
166
  }
166
- await enqueue(frame.websocketId, ()=>processFrame(frame));
167
+ // A frame arrives outside any HTTP request, so it gets its own credential scope for the
168
+ // routines it runs.
169
+ await enqueue(frame.websocketId, ()=>runInCredentialScope(()=>processFrame(frame)));
167
170
  }
168
171
  function close() {
169
172
  closed = true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lowdefy/api",
3
- "version": "0.0.0-experimental-20261007124348",
3
+ "version": "0.0.0-experimental-20261009120232",
4
4
  "license": "Apache-2.0",
5
5
  "description": "",
6
6
  "homepage": "https://lowdefy.com",
@@ -37,16 +37,16 @@
37
37
  "@better-auth/cimd": "1.7.7",
38
38
  "@better-auth/oauth-provider": "1.7.7",
39
39
  "@better-auth/passkey": "1.7.7",
40
- "@lowdefy/ajv": "0.0.0-experimental-20261007124348",
41
- "@lowdefy/build": "0.0.0-experimental-20261007124348",
42
- "@lowdefy/connection-smtp": "0.0.0-experimental-20261007124348",
43
- "@lowdefy/email-templates": "0.0.0-experimental-20261007124348",
44
- "@lowdefy/errors": "0.0.0-experimental-20261007124348",
45
- "@lowdefy/helpers": "0.0.0-experimental-20261007124348",
46
- "@lowdefy/node-utils": "0.0.0-experimental-20261007124348",
47
- "@lowdefy/nunjucks": "0.0.0-experimental-20261007124348",
48
- "@lowdefy/operators": "0.0.0-experimental-20261007124348",
49
- "@lowdefy/operators-js": "0.0.0-experimental-20261007124348",
40
+ "@lowdefy/ajv": "0.0.0-experimental-20261009120232",
41
+ "@lowdefy/build": "0.0.0-experimental-20261009120232",
42
+ "@lowdefy/connection-smtp": "0.0.0-experimental-20261009120232",
43
+ "@lowdefy/email-templates": "0.0.0-experimental-20261009120232",
44
+ "@lowdefy/errors": "0.0.0-experimental-20261009120232",
45
+ "@lowdefy/helpers": "0.0.0-experimental-20261009120232",
46
+ "@lowdefy/node-utils": "0.0.0-experimental-20261009120232",
47
+ "@lowdefy/nunjucks": "0.0.0-experimental-20261009120232",
48
+ "@lowdefy/operators": "0.0.0-experimental-20261009120232",
49
+ "@lowdefy/operators-js": "0.0.0-experimental-20261009120232",
50
50
  "@modelcontextprotocol/sdk": "1.31.0",
51
51
  "better-auth": "1.7.7",
52
52
  "jose": "^6.2.3",
@@ -55,7 +55,7 @@
55
55
  },
56
56
  "devDependencies": {
57
57
  "@jest/globals": "28.1.3",
58
- "@lowdefy/connection-mongodb": "0.0.0-experimental-20261007124348",
58
+ "@lowdefy/connection-mongodb": "0.0.0-experimental-20261009120232",
59
59
  "@opentelemetry/api": "1.9.1",
60
60
  "@shelf/jest-mongodb": "4.3.2",
61
61
  "@swc/cli": "0.8.1",