@lowdefy/api 7.1.0 → 7.2.0

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 (119) hide show
  1. package/dist/context/createAuthorizeOutcome.js +1 -1
  2. package/dist/context/createEvaluateOperators.js +2 -1
  3. package/dist/context/isWebSocketOriginAllowed.js +3 -1
  4. package/dist/context/readMemberships.js +10 -4
  5. package/dist/context/resolveAuthentication.js +95 -21
  6. package/dist/email/renderAuthEmail.js +3 -2
  7. package/dist/index.js +7 -1
  8. package/dist/response/redactErrorResponse.js +8 -4
  9. package/dist/routes/agent/callAgent.js +20 -2
  10. package/dist/routes/agent/redactMessages.js +136 -0
  11. package/dist/routes/auth/createAuthLogger.js +23 -6
  12. package/dist/routes/auth/createMcpAccessTokenClaims.js +8 -6
  13. package/dist/routes/auth/createOnAPIError.js +15 -5
  14. package/dist/routes/auth/createSendEmail.js +15 -5
  15. package/dist/routes/auth/getBetterAuth.js +3 -3
  16. package/dist/routes/auth/getBetterAuthConfig.js +163 -92
  17. package/dist/routes/auth/hooks/buildEngineHooks.js +15 -1
  18. package/dist/routes/auth/hooks/createUserAfterHook.js +17 -2
  19. package/dist/routes/auth/hooks/createUserBeforeHook.js +20 -4
  20. package/dist/routes/auth/mobile/buildBearerPlugin.js +45 -0
  21. package/dist/routes/auth/mobile/buildOneTimeTokenPlugin.js +50 -0
  22. package/dist/routes/auth/mobile/createCodeVerifierCheck.js +57 -0
  23. package/dist/routes/auth/mobile/createKnownDeviceHook.js +76 -0
  24. package/dist/routes/auth/mobile/createMobileAuthPageResponse.js +79 -0
  25. package/dist/routes/auth/mobile/createMobileSessionCreateHook.js +41 -0
  26. package/dist/routes/auth/mobile/createMobileSessionRefreshHook.js +40 -0
  27. package/dist/routes/auth/mobile/createMobileSignInCsrfToken.js +32 -0
  28. package/dist/routes/auth/mobile/createPhoneSession.js +59 -0
  29. package/dist/routes/auth/mobile/escapeHtml.js +26 -0
  30. package/dist/routes/auth/mobile/getCodeHolderIdentifier.js +20 -0
  31. package/dist/routes/auth/mobile/getKnownDeviceIdentifier.js +20 -0
  32. package/dist/routes/auth/mobile/getMobileSessionExpiry.js +18 -0
  33. package/dist/routes/auth/mobile/getMobileSignInReturnUrl.js +31 -0
  34. package/dist/routes/auth/mobile/getOneTimeTokenIdentifiers.js +26 -0
  35. package/dist/routes/auth/mobile/handleMobileSignIn.js +303 -0
  36. package/dist/routes/auth/mobile/handleMobileSignInCallback.js +30 -0
  37. package/dist/routes/auth/mobile/isNativeAuthRequest.js +33 -0
  38. package/dist/routes/auth/mobile/matchesCodeChallenge.js +29 -0
  39. package/dist/routes/auth/mobile/mintOneTimeToken.js +41 -0
  40. package/dist/routes/auth/mobile/readDeviceKeyHash.js +34 -0
  41. package/dist/routes/auth/mobile/readMobileSignInParams.js +90 -0
  42. package/dist/routes/auth/mobile/sha256Base64Url.js +22 -0
  43. package/dist/routes/auth/mobile/storeCodeChallenge.js +29 -0
  44. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +43 -6
  45. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +7 -2
  46. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +41 -189
  47. package/dist/routes/auth/organizations/createAdmissionGateHook.js +5 -5
  48. package/dist/routes/auth/organizations/createBeforeCreateInvitationHook.js +62 -0
  49. package/dist/routes/auth/organizations/createBeforeUpdateMemberRoleHook.js +45 -0
  50. package/dist/routes/auth/organizations/createSuspendedMemberGate.js +146 -0
  51. package/dist/routes/auth/organizations/createSuspendedOrganizationsFilter.js +44 -0
  52. package/dist/routes/auth/organizations/ensureAuthIndexes.js +11 -10
  53. package/dist/routes/auth/organizations/getOrganizationBinding.js +4 -2
  54. package/dist/routes/auth/organizations/isActiveMember.js +26 -0
  55. package/dist/routes/auth/organizations/isEmailAdmitted.js +12 -5
  56. package/dist/routes/auth/organizations/memberRowsLimit.js +19 -0
  57. package/dist/routes/auth/organizations/mintOrganization.js +258 -0
  58. package/dist/routes/auth/organizations/organizationAccessControl.js +5 -1
  59. package/dist/routes/auth/organizations/provisionOrganization.js +117 -0
  60. package/dist/routes/auth/organizations/readSuspendedOrganizationIds.js +36 -0
  61. package/dist/routes/auth/requestHooks/buildRequestHooks.js +72 -0
  62. package/dist/routes/auth/requestHooks/createEmailCodeHolderGate.js +58 -0
  63. package/dist/routes/auth/requestHooks/createEmailSendLimit.js +116 -0
  64. package/dist/routes/auth/requestHooks/createSignInRefusedRedirectHook.js +75 -0
  65. package/dist/routes/auth/requestHooks/holdEmailCode.js +80 -0
  66. package/dist/routes/auth/requestHooks/reserveSendSlot.js +70 -0
  67. package/dist/routes/auth/runReportingFaults.js +32 -0
  68. package/dist/routes/connections/resolveUnwalledReach.js +14 -16
  69. package/dist/routes/endpoints/callEndpoint.js +6 -3
  70. package/dist/routes/endpoints/control/controlFor.js +9 -6
  71. package/dist/routes/endpoints/control/controlIf.js +8 -3
  72. package/dist/routes/endpoints/control/controlLog.js +3 -1
  73. package/dist/routes/endpoints/control/controlParallelFor.js +9 -6
  74. package/dist/routes/endpoints/control/controlReturn.js +3 -2
  75. package/dist/routes/endpoints/control/controlSetState.js +1 -1
  76. package/dist/routes/endpoints/control/controlSwitch.js +6 -3
  77. package/dist/routes/endpoints/control/controlWhile.js +6 -3
  78. package/dist/routes/endpoints/createLinkAnswer.js +76 -0
  79. package/dist/routes/endpoints/dispatchDetached.js +38 -0
  80. package/dist/routes/endpoints/forwardScheduledEndpoint.js +32 -11
  81. package/dist/routes/endpoints/handleAgentCall.js +1 -1
  82. package/dist/routes/endpoints/handleAuthStep.js +19 -4
  83. package/dist/routes/endpoints/handleEndpointCall.js +6 -4
  84. package/dist/routes/endpoints/handleRequest.js +3 -2
  85. package/dist/routes/endpoints/handleValidateDynamic.js +1 -1
  86. package/dist/routes/endpoints/matchLinkEndpoint.js +30 -0
  87. package/dist/routes/endpoints/runLinkEndpoint.js +148 -0
  88. package/dist/routes/endpoints/runRoutine.js +5 -5
  89. package/dist/routes/endpoints/scheduleBackground.js +13 -11
  90. package/dist/routes/endpoints/test/runTest.js +30 -11
  91. package/dist/routes/mcp/createMcpServer.js +2 -7
  92. package/dist/routes/mcp/runAfterToolCall.js +9 -3
  93. package/dist/routes/mobile/createAppleAppSiteAssociation.js +51 -0
  94. package/dist/routes/mobile/createAssetLinks.js +38 -0
  95. package/dist/routes/mobile/filterMobileMenus.js +31 -0
  96. package/dist/routes/mobile/getMobileAppEvents.js +23 -0
  97. package/dist/routes/mobile/getMobileRootConfig.js +109 -0
  98. package/dist/routes/mobile/getOpenablePageIds.js +21 -0
  99. package/dist/routes/page/dynamic/policy/checkAction.js +67 -2
  100. package/dist/routes/page/dynamic/policy/checkEvents.js +8 -2
  101. package/dist/routes/page/dynamic/policy/checkPolicy.js +86 -6
  102. package/dist/routes/page/dynamic/policy/checkValue.js +97 -6
  103. package/dist/routes/page/dynamic/policy/collectSchemaKinds.js +173 -0
  104. package/dist/routes/page/dynamic/policy/findDataRows.js +94 -0
  105. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +24 -12
  106. package/dist/routes/page/dynamic/policy/findHtmlUrls.js +64 -0
  107. package/dist/routes/page/dynamic/policy/overlapsStatePath.js +28 -0
  108. package/dist/routes/page/dynamic/resolveDynamicContent.js +23 -17
  109. package/dist/routes/page/getPageConfig.js +25 -1
  110. package/dist/routes/request/callRequestResolver.js +29 -36
  111. package/dist/routes/request/stampTypedError.js +37 -0
  112. package/dist/routes/request/summarisedError.js +62 -0
  113. package/dist/routes/request/wrapResolverError.js +61 -0
  114. package/dist/routes/websocket/createChannelRegistry.js +13 -15
  115. package/dist/routes/websocket/createWebSocketConnection.js +5 -8
  116. package/dist/test/createMemoryAuth.js +125 -0
  117. package/package.json +20 -22
  118. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +0 -117
  119. package/dist/routes/request/maskCredentialProperties.js +0 -34
@@ -36,7 +36,7 @@ import { ConfigError } from '@lowdefy/errors';
36
36
  function createAuthorizeOutcome({ authEnforcement, system, user }) {
37
37
  const authenticated = !type.isNone(user);
38
38
  // A caller awaiting an organization is signed in and holds no membership -
39
- // under tenant, the invited user before they accept (resolveAuthentication).
39
+ // the invited user before they accept (resolveAuthentication).
40
40
  // They are known so the always-public accept page can address them, and
41
41
  // refused everywhere auth.public is false, roles or not: empty roles is not a
42
42
  // wall (user-model Decision 2), so authenticated alone must not admit them to
@@ -15,10 +15,11 @@
15
15
  */ import { markCredential } from '@lowdefy/node-utils';
16
16
  import { ServerParser } from '@lowdefy/operators';
17
17
  function createEvaluateOperators(context) {
18
- const { appMeta, i18n, jsMap, operators, organization, secrets, user } = context;
18
+ const { appMeta, i18n, jsMap, logger, operators, organization, secrets, user } = context;
19
19
  const operatorsParser = new ServerParser({
20
20
  i18n,
21
21
  jsMap,
22
+ logger,
22
23
  lowdefyApp: appMeta,
23
24
  markCredential,
24
25
  operators,
@@ -36,7 +36,9 @@ function getPublicOrigins({ context }) {
36
36
  }
37
37
  // Browsers open a websocket to any host a page names, so a websocket upgrade
38
38
  // is accepted only from the app's own pages, or from a client that sends no
39
- // Origin (a server or a script). A browser cannot set headers on a websocket
39
+ // Origin (a server or a script). A phone shell's websocket sends the Origin
40
+ // React Native derives from the server URL, the app's own origin, so it passes
41
+ // as the app's pages do. A browser cannot set headers on a websocket
40
42
  // handshake, so X-Forwarded-Host is accepted here, where a proxy or CDN in
41
43
  // front of the app rewrites Host; the app's configured public origins are too.
42
44
  // A refusal is logged, since behind a proxy that passes neither it would
@@ -13,15 +13,19 @@
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
- // The adapter returns at most this many rows when asked for none; ask for more
17
- // than any one person holds, so the read is one round trip in practice.
18
- const MEMBER_ROWS_LIMIT = 1000;
16
+ import isActiveMember from '../routes/auth/organizations/isActiveMember.js';
17
+ import MEMBER_ROWS_LIMIT from '../routes/auth/organizations/memberRowsLimit.js';
19
18
  // Reads every member row the person holds in one query, served by the unique
20
19
  // { userId, organizationId } member index (ensureAuthIndexes), and picks the
21
20
  // row in the active organization. The same read gives the ids of every
22
21
  // organization they belong to, which the response stamp hashes (callerStamp),
23
22
  // so the full identity costs no extra round trip.
24
23
  //
24
+ // organizationIds leaves out organizations the person is suspended in - they
25
+ // are not a member there for anything the stamp is used for, and suspending
26
+ // someone then changes their stamp as removing them would. member is returned
27
+ // suspended or not; resolveMemberCaller refuses a suspended one.
28
+ //
25
29
  // A person holding more rows than one read returns is not cut off: the active
26
30
  // row is then read on its own, as before, and organizationIds is null - the
27
31
  // list is incomplete, so the stamp leaves memberships out rather than hash a
@@ -41,7 +45,9 @@ async function readMemberships({ adapter, organizationId, userId }) {
41
45
  if (rows.length < MEMBER_ROWS_LIMIT) {
42
46
  return {
43
47
  member,
44
- organizationIds: rows.map((row)=>row.organizationId)
48
+ organizationIds: rows.filter((row)=>isActiveMember({
49
+ member: row
50
+ })).map((row)=>row.organizationId)
45
51
  };
46
52
  }
47
53
  if (!type.isNone(member)) {
@@ -17,6 +17,7 @@ import { decodeJwt, jwtVerify } from 'jose';
17
17
  import { normalizeCaller, type } from '@lowdefy/helpers';
18
18
  import findPendingInvitation from '../routes/auth/organizations/findPendingInvitation.js';
19
19
  import { getRegisteredOrganization } from '../routes/auth/organizations/getOrganizationBinding.js';
20
+ import isActiveMember from '../routes/auth/organizations/isActiveMember.js';
20
21
  import { getAsIssuer, getMcpResourceUri } from '../routes/mcp/getMcpUri.js';
21
22
  import getMcpJwks from '../routes/mcp/getMcpJwks.js';
22
23
  import readMemberships from './readMemberships.js';
@@ -48,10 +49,11 @@ import resolveStrategyCaller from './resolveStrategyCaller.js';
48
49
  // Under policy: pinned, a session whose active organization is not this app's
49
50
  // organization is treated the same way, member row there or not.
50
51
  //
51
- // A session carrying no active organization at all differs by policy. Under
52
- // pinned it resolves to unauthenticated on the same reasoning. Under tenant it
53
- // resolves to a caller carrying identity, no membership and no roles, marked
54
- // awaitingOrganization - the invited user before they accept.
52
+ // A session carrying no active organization at all resolves to a caller
53
+ // carrying identity, no membership and no roles, marked awaitingOrganization -
54
+ // the invited user before they accept. Under pinned only while they hold a
55
+ // pending invitation to this app's organization; without one it resolves to
56
+ // unauthenticated.
55
57
  // createAuthorizeOutcome refuses that caller wherever auth.public is false, so
56
58
  // the marker widens no access; it exists so the always-public accept page can
57
59
  // tell an invited user from a stranger.
@@ -107,11 +109,22 @@ function passkeyConfigured({ auth }) {
107
109
  // memberId is passed only by the member token branch: a token works for the
108
110
  // member row it was made for, so a member who left and rejoined - a new row -
109
111
  // holds no old tokens.
112
+ //
113
+ // A suspended row resolves exactly as no row does. The row stays so the app's
114
+ // own queries still find the person and their roles (a report of everyone who
115
+ // held a role), but it admits nobody - every protected page, request, endpoint
116
+ // and MCP call sees a non-member.
110
117
  async function resolveMemberCaller(context, { adapter, auth, member, memberId, organizationId, user }) {
111
118
  if (type.isNone(member)) {
112
119
  context.logger.debug(`User "${user.id}" has no member row in organization "${organizationId}" - resolved unauthenticated.`);
113
120
  return null;
114
121
  }
122
+ if (!isActiveMember({
123
+ member
124
+ })) {
125
+ context.logger.debug(`User "${user.id}" is suspended in organization "${organizationId}" - resolved unauthenticated.`);
126
+ return null;
127
+ }
115
128
  if (!type.isUndefined(memberId) && member.id !== memberId) {
116
129
  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.`);
117
130
  return null;
@@ -598,6 +611,28 @@ async function resolveMcpCaller(context, { auth, headers }) {
598
611
  auth_method: 'mcp'
599
612
  };
600
613
  }
614
+ // A phone shell sends its session as a bearer (the bearer plugin, on for apps
615
+ // with a mobile section) and the same session branch below resolves it. The
616
+ // cookie cache is skipped for any bearer: a phone never holds the cache cookie,
617
+ // and reading the session row on every call is what makes signing out, an
618
+ // admin ending sessions or removing a member take effect on its next call. A
619
+ // bearer that is not a session token (an API strategy's) resolves no session,
620
+ // and the strategies run as before.
621
+ function getSessionInput({ headers }) {
622
+ if (readBearerToken({
623
+ headers
624
+ }) === null) {
625
+ return {
626
+ headers
627
+ };
628
+ }
629
+ return {
630
+ headers,
631
+ query: {
632
+ disableCookieCache: true
633
+ }
634
+ };
635
+ }
601
636
  // context.authSession is the session the caller was resolved from, for the
602
637
  // response's caller stamp: { id, memberOrganizationIds }. memberOrganizationIds
603
638
  // is every organization the person belongs to under tenant, this app's
@@ -620,9 +655,9 @@ async function resolveAuthentication(context, { auth, headers, strategies, mcp }
620
655
  });
621
656
  return;
622
657
  }
623
- const session = await auth.api.getSession({
658
+ const session = await auth.api.getSession(getSessionInput({
624
659
  headers
625
- });
660
+ }));
626
661
  if (type.isNone(session)) {
627
662
  if (hasMcpAudienceBearer({
628
663
  context,
@@ -638,26 +673,24 @@ async function resolveAuthentication(context, { auth, headers, strategies, mcp }
638
673
  });
639
674
  return;
640
675
  }
676
+ const registered = getRegisteredOrganization({
677
+ auth
678
+ });
641
679
  const activeOrganizationId = session.session.activeOrganizationId;
642
680
  if (type.isNone(activeOrganizationId)) {
643
- // A session with no active organization differs by policy. Under tenant it
644
- // is the invited user before they accept - their pre-accept session carries
645
- // no organization by design, because they are about to join someone else's.
681
+ // A session with no active organization is the invited user before they
682
+ // accept - their pre-accept session carries no organization by design,
683
+ // because they are about to join an organization they do not belong to yet.
646
684
  // Resolving them to null leaves the always-public accept page unable to
647
685
  // tell them from a stranger, and that page is the one page they can reach.
648
686
  // They become a caller carrying identity, no membership and no roles,
649
687
  // marked awaitingOrganization - createAuthorizeOutcome refuses that caller
650
- // wherever auth.public is false, so the marker widens no access. Under
651
- // pinned the state has no meaning: one organization exists, and someone
652
- // outside it has no reason to be known to the app.
653
- if (getRegisteredOrganization({
654
- auth
655
- })?.policy !== 'tenant') {
688
+ // wherever auth.public is false, so the marker widens no access.
689
+ if (type.isNone(registered)) {
656
690
  context.logger.debug(`Session for user "${session.user.id}" has no active organization - resolved unauthenticated.`);
657
691
  context.user = null;
658
692
  return;
659
693
  }
660
- context.logger.debug(`Session for user "${session.user.id}" has no active organization under tenant - resolved awaiting organization.`);
661
694
  // Why they are awaiting matters to the app: an invited user who signed up
662
695
  // directly (instead of via the invitation link) holds a pending invitation
663
696
  // and no member row, and without a marker the public pages cannot tell
@@ -666,10 +699,54 @@ async function resolveAuthentication(context, { auth, headers, strategies, mcp }
666
699
  // invitation is read here (only for this rare caller, one indexed read) so
667
700
  // the app can route them to the accept page and hand it the invitation id.
668
701
  // Diagnosis only - accepting stays the caller's own, explicit act.
702
+ //
703
+ // Under pinned the lookup is narrowed to this app's organization, whose id
704
+ // is its slug, as applyPinnedPolicy narrows the admission that minted this
705
+ // session: an invitation another app sent from a shared auth database is
706
+ // not this app's to accept.
707
+ const { adapter } = await auth.$context;
669
708
  const pendingInvitation = type.isString(session.user.email) ? await findPendingInvitation({
670
- adapter: (await auth.$context).adapter,
671
- email: session.user.email
709
+ adapter,
710
+ email: session.user.email,
711
+ organizationId: registered.policy === 'pinned' ? registered.slug : undefined
672
712
  }) : null;
713
+ // Under pinned one organization exists, so a session awaiting it with no
714
+ // pending invitation there - one expired or cancelled since sign-in - has
715
+ // nothing to accept and no reason to be known to the app.
716
+ if (registered.policy === 'pinned' && type.isNone(pendingInvitation)) {
717
+ context.logger.debug(`Session for user "${session.user.id}" has no active organization and no pending invitation to this app's pinned organization "${registered.slug}" - resolved unauthenticated.`);
718
+ context.user = null;
719
+ return;
720
+ }
721
+ // Under pinned a member row there means they joined some other way (an
722
+ // admin added them directly) while the invitation stayed pending. They are
723
+ // not awaiting: unauthenticated sends protected pages to the login page,
724
+ // and that sign-in re-pins the session (applyPinnedPolicy). Awaiting would
725
+ // refuse those pages with no way back. A suspended row is not one: sign-in
726
+ // would not re-pin it, so they stay awaiting, like a non-member.
727
+ if (registered.policy === 'pinned') {
728
+ const member = await adapter.findOne({
729
+ model: 'member',
730
+ where: [
731
+ {
732
+ field: 'userId',
733
+ value: session.user.id
734
+ },
735
+ {
736
+ field: 'organizationId',
737
+ value: registered.slug
738
+ }
739
+ ]
740
+ });
741
+ if (isActiveMember({
742
+ member
743
+ })) {
744
+ context.logger.debug(`Session for user "${session.user.id}" has no active organization but holds a member row in this app's pinned organization "${registered.slug}" - resolved unauthenticated.`);
745
+ context.user = null;
746
+ return;
747
+ }
748
+ }
749
+ context.logger.debug(`Session for user "${session.user.id}" has no active organization under ${registered.policy} - resolved awaiting organization.`);
673
750
  // No member row, so no per-organization attributes and no roles of either
674
751
  // kind - the global attributes ride alone.
675
752
  context.authSession = {
@@ -719,9 +796,6 @@ async function resolveAuthentication(context, { auth, headers, strategies, mcp }
719
796
  // shared session the other way and breaks the app they came from.
720
797
  //
721
798
  // Under tenant there is no pinned organization and the check does not apply.
722
- const registered = getRegisteredOrganization({
723
- auth
724
- });
725
799
  if (registered?.policy === 'pinned' && activeOrganizationId !== registered.slug) {
726
800
  context.logger.debug(`Session for user "${session.user.id}" has active organization "${activeOrganizationId}", which is not this app's pinned organization "${registered.slug}" - resolved unauthenticated.`);
727
801
  context.user = null;
@@ -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 { ConfigError } from '@lowdefy/errors';
15
+ */ import { ConfigError, LowdefyInternalError } from '@lowdefy/errors';
16
16
  import { type } from '@lowdefy/helpers';
17
17
  import { EmailOTPEmail, InvitationEmail, MagicLinkEmail, ResetPasswordEmail, VerifyEmail, interpolateProperties, renderEmail } from '@lowdefy/email-templates';
18
18
  import getNotificationConfig from '../routes/notifications/getNotificationConfig.js';
@@ -75,7 +75,8 @@ async function renderAuthEmail({ flow, vars, authEmailConfig, baseURL, context }
75
75
  }
76
76
  const Template = stockTemplates[flow];
77
77
  if (!Template) {
78
- throw new ConfigError(`Unknown auth email flow "${flow}".`);
78
+ // The flow names come from the engine's own callbacks, never from config.
79
+ throw new LowdefyInternalError(`Unknown auth email flow "${flow}".`);
79
80
  }
80
81
  const theme = resolveThemeLogo({
81
82
  theme: app.email ?? {},
package/dist/index.js CHANGED
@@ -19,7 +19,9 @@ import callEndpoint from './routes/endpoints/callEndpoint.js';
19
19
  import getEndpointConfig from './routes/endpoints/getEndpointConfig.js';
20
20
  import callRequest from './routes/request/callRequest.js';
21
21
  import createApiContext from './context/createApiContext.js';
22
+ import createAppleAppSiteAssociation from './routes/mobile/createAppleAppSiteAssociation.js';
22
23
  import createAsMetadataHandler from './routes/auth/createAsMetadataHandler.js';
24
+ import createAssetLinks from './routes/mobile/createAssetLinks.js';
23
25
  import createChannelRegistry from './routes/websocket/createChannelRegistry.js';
24
26
  import createContentSecurityPolicy from './csp/createContentSecurityPolicy.js';
25
27
  import createMcpServer from './routes/mcp/createMcpServer.js';
@@ -31,10 +33,13 @@ import getAuthStrategies from './routes/auth/strategies/getAuthStrategies.js';
31
33
  import getBetterAuth from './routes/auth/getBetterAuth.js';
32
34
  import { MCP_OAUTH_SCOPES } from './routes/auth/getBetterAuthConfig.js';
33
35
  import handleAuthRequest from './routes/auth/handleAuthRequest.js';
36
+ import handleMobileSignIn from './routes/auth/mobile/handleMobileSignIn.js';
37
+ import handleMobileSignInCallback from './routes/auth/mobile/handleMobileSignInCallback.js';
34
38
  import { getAsIssuer, getMcpResourceMetadataUri, getMcpResourceUri } from './routes/mcp/getMcpUri.js';
35
39
  import getMcpResourceBinding, { registerMcpResourceBinding } from './routes/mcp/getMcpResourceBinding.js';
36
40
  import { ensureMcpOauthResource } from './routes/mcp/oauthResourceLifecycle.js';
37
41
  import getHomeAndMenus from './routes/rootConfig/getHomeAndMenus.js';
42
+ import getMobileRootConfig from './routes/mobile/getMobileRootConfig.js';
38
43
  import getPageConfig from './routes/page/getPageConfig.js';
39
44
  import getRootConfig from './routes/rootConfig/getRootConfig.js';
40
45
  import isSameOriginRequest from './context/isSameOriginRequest.js';
@@ -50,6 +55,7 @@ import resolveTenantPreflight, { getTenantIntegrityStatus } from './routes/conne
50
55
  import forwardScheduledEndpoint from './routes/endpoints/forwardScheduledEndpoint.js';
51
56
  import acceptDetachedEndpoint from './routes/endpoints/acceptDetachedEndpoint.js';
52
57
  import runDetachedEndpoint from './routes/endpoints/runDetachedEndpoint.js';
58
+ import runLinkEndpoint from './routes/endpoints/runLinkEndpoint.js';
53
59
  import runWebhookEndpoint from './routes/endpoints/runWebhookEndpoint.js';
54
60
  import runScheduledEndpoint from './routes/endpoints/runScheduledEndpoint.js';
55
- export { addNonceToElements, buildEndpointResult, callAgent, callEndpoint, getEndpointConfig, callRequest, createApiContext, createAsMetadataHandler, createChannelRegistry, createContentSecurityPolicy, createMcpServer, createRequestSignal, createSystemContext, createWebSocketConnection, createWireProjection, ensureMcpOauthResource, getAsIssuer, getAuthStrategies, getBetterAuth, MCP_OAUTH_SCOPES, getHomeAndMenus, handleAuthRequest, getMcpResourceBinding, getMcpResourceMetadataUri, getMcpResourceUri, registerMcpResourceBinding, getPageConfig, getRootConfig, isSameOriginRequest, isWebSocketOriginAllowed, logClientError, normalizeInjectedCaller, parseRequestBody, redactErrorResponse, redactResponse, resolveAuthentication, resolvePinnedOrganization, getTenantIntegrityStatus, resolveTenantPreflight, forwardScheduledEndpoint, acceptDetachedEndpoint, runDetachedEndpoint, runWebhookEndpoint, runScheduledEndpoint };
61
+ export { addNonceToElements, buildEndpointResult, callAgent, callEndpoint, getEndpointConfig, callRequest, createApiContext, createAppleAppSiteAssociation, createAsMetadataHandler, createAssetLinks, createChannelRegistry, createContentSecurityPolicy, createMcpServer, createRequestSignal, createSystemContext, createWebSocketConnection, createWireProjection, ensureMcpOauthResource, getAsIssuer, getAuthStrategies, getBetterAuth, MCP_OAUTH_SCOPES, getHomeAndMenus, getMobileRootConfig, handleAuthRequest, handleMobileSignIn, handleMobileSignInCallback, getMcpResourceBinding, getMcpResourceMetadataUri, getMcpResourceUri, registerMcpResourceBinding, getPageConfig, getRootConfig, isSameOriginRequest, isWebSocketOriginAllowed, logClientError, normalizeInjectedCaller, parseRequestBody, redactErrorResponse, redactResponse, resolveAuthentication, resolvePinnedOrganization, getTenantIntegrityStatus, resolveTenantPreflight, forwardScheduledEndpoint, acceptDetachedEndpoint, runDetachedEndpoint, runLinkEndpoint, runWebhookEndpoint, runScheduledEndpoint };
@@ -25,15 +25,19 @@ import normalizeErrorSources from './normalizeErrorSources.js';
25
25
  // the serializer's reviver replaces any object holding `~e` with its error, so a
26
26
  // plain deserialize of the payload drops `devError` and config never sees it.
27
27
  //
28
- // `received` is left out of devError at every node: on the request path it is
29
- // the evaluated request properties, resolved _secret values included, and the
30
- // dev server can be reached over a LAN or tunnel. The terminal still logs it.
28
+ // `received` is left out of devError at every node: it holds evaluated values,
29
+ // resolved _secret values included, and the dev server can be reached over a LAN
30
+ // or tunnel.
31
+ //
32
+ // A failed request's error carries the connection's error only as a summary, so no log writes
33
+ // the inputs a driver's error can hold; the dev tools get the connection's error itself, from
34
+ // the error's non-enumerable `devCause`.
31
35
  function projectDevError(err) {
32
36
  const props = {
33
37
  message: err.message,
34
38
  name: err.name,
35
39
  stack: err.stack,
36
- cause: err.cause,
40
+ cause: err.devCause ?? err.cause,
37
41
  ...err
38
42
  };
39
43
  delete props.received;
@@ -12,9 +12,11 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import collectChatFiles from './collectChatFiles.js';
15
+ */ import { type } from '@lowdefy/helpers';
16
+ import collectChatFiles from './collectChatFiles.js';
16
17
  import createEvaluateOperators from '../../context/createEvaluateOperators.js';
17
18
  import prepareAgent from './prepareAgent.js';
19
+ import redactMessages from './redactMessages.js';
18
20
  async function callAgent(context, { agentId, pageId, messages, conversationId, pathParams, urlQuery, sharedState, sharedStateReadOnly }) {
19
21
  const { logger } = context;
20
22
  context.pageId = pageId;
@@ -46,12 +48,28 @@ async function callAgent(context, { agentId, pageId, messages, conversationId, p
46
48
  }),
47
49
  mode: 'chat'
48
50
  });
51
+ // Mask the user's text before the resolver hands it to the model, title generation, tools
52
+ // and hooks. prepareAgent reads only the file parts, which redact leaves alone.
53
+ let agentMessages = messages;
54
+ if (!type.isNone(agentConfig.redact)) {
55
+ const redacted = redactMessages({
56
+ messages,
57
+ redact: resolverContext.evaluateOperators(agentConfig.redact),
58
+ configKey: agentConfig['~k']
59
+ });
60
+ agentMessages = redacted.messages;
61
+ logger.debug({
62
+ event: 'debug_agent_redact',
63
+ agentId,
64
+ replacements: redacted.counts
65
+ });
66
+ }
49
67
  // Call the agent resolver
50
68
  const { response } = await agentType.resolver({
51
69
  connection: connectionInstance,
52
70
  properties: {
53
71
  agent: agentConfig,
54
- messages
72
+ messages: agentMessages
55
73
  },
56
74
  context: resolverContext
57
75
  });
@@ -0,0 +1,136 @@
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
+ const DEFAULT_REPLACEMENT = '[removed]';
18
+ // The build checks a literal redact config; this checks it again after operators are
19
+ // evaluated, since a pattern an operator returns is only known now. Returns the patterns as
20
+ // { name, regex }, each regex global so a replace masks every match.
21
+ function buildPatterns({ redact, configKey }) {
22
+ if (!type.isObject(redact)) {
23
+ throw new ConfigError('Agent "redact" should be an object.', {
24
+ received: redact,
25
+ configKey
26
+ });
27
+ }
28
+ if (!type.isArray(redact.patterns) || redact.patterns.length === 0) {
29
+ throw new ConfigError('Agent "redact.patterns" should be a non-empty array.', {
30
+ received: redact.patterns,
31
+ configKey
32
+ });
33
+ }
34
+ return redact.patterns.map((entry, index)=>{
35
+ const { name, pattern, flags } = type.isString(entry) ? {
36
+ pattern: entry
37
+ } : entry ?? {};
38
+ const location = `redact.patterns[${index}]`;
39
+ if (!type.isString(pattern)) {
40
+ throw new ConfigError(`Agent "${location}.pattern" should be a string.`, {
41
+ received: pattern,
42
+ configKey
43
+ });
44
+ }
45
+ if (!type.isNone(name) && !type.isString(name)) {
46
+ throw new ConfigError(`Agent "${location}.name" should be a string.`, {
47
+ received: name,
48
+ configKey
49
+ });
50
+ }
51
+ if (!type.isNone(flags) && !type.isString(flags)) {
52
+ throw new ConfigError(`Agent "${location}.flags" should be a string.`, {
53
+ received: flags,
54
+ configKey
55
+ });
56
+ }
57
+ // With the sticky flag a global replace stops at the first gap between matches.
58
+ if (type.isString(flags) && flags.includes('y')) {
59
+ throw new ConfigError(`Agent "${location}.flags" should not include "y".`, {
60
+ received: flags,
61
+ configKey
62
+ });
63
+ }
64
+ const allFlags = (flags ?? '').includes('g') ? flags : `${flags ?? ''}g`;
65
+ let regex;
66
+ try {
67
+ regex = new RegExp(pattern, allFlags);
68
+ } catch (error) {
69
+ throw new ConfigError(`Agent "${location}" is not a valid regular expression: ${error.message}`, {
70
+ cause: error,
71
+ received: pattern,
72
+ configKey
73
+ });
74
+ }
75
+ // A pattern that matches empty text would put the replacement between every character.
76
+ if (regex.test('')) {
77
+ throw new ConfigError(`Agent "${location}" matches empty text.`, {
78
+ received: pattern,
79
+ configKey
80
+ });
81
+ }
82
+ regex.lastIndex = 0;
83
+ return {
84
+ name: name ?? location,
85
+ regex
86
+ };
87
+ });
88
+ }
89
+ // Masks every match of the agent's redact patterns in the text parts of the user's messages,
90
+ // before the model, title generation, tools and hooks see them. Every user message is masked,
91
+ // not only the last: the browser sends the whole conversation each turn. Assistant and tool
92
+ // messages, and file parts, are left as they are. The messages are the client's, not yet
93
+ // validated, so a malformed message or part is passed over here and refused by the agent's
94
+ // message validation. counts holds the replacements made per pattern name, never the text.
95
+ function redactMessages({ messages, redact, configKey }) {
96
+ const patterns = buildPatterns({
97
+ redact,
98
+ configKey
99
+ });
100
+ const replacement = redact.replacement ?? DEFAULT_REPLACEMENT;
101
+ if (!type.isString(replacement)) {
102
+ throw new ConfigError('Agent "redact.replacement" should be a string.', {
103
+ received: replacement,
104
+ configKey
105
+ });
106
+ }
107
+ const counts = {};
108
+ function maskText(text) {
109
+ let masked = text;
110
+ for (const { name, regex } of patterns){
111
+ masked = masked.replace(regex, ()=>{
112
+ counts[name] = (counts[name] ?? 0) + 1;
113
+ return replacement;
114
+ });
115
+ }
116
+ return masked;
117
+ }
118
+ const redacted = messages.map((message)=>{
119
+ if (message?.role !== 'user' || !type.isArray(message.parts)) return message;
120
+ return {
121
+ ...message,
122
+ parts: message.parts.map((part)=>{
123
+ if (part?.type !== 'text' || !type.isString(part.text)) return part;
124
+ return {
125
+ ...part,
126
+ text: maskText(part.text)
127
+ };
128
+ })
129
+ };
130
+ });
131
+ return {
132
+ messages: redacted,
133
+ counts
134
+ };
135
+ }
136
+ export default redactMessages;
@@ -12,19 +12,36 @@
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
- */ // Adapts the Lowdefy logger to BetterAuth's logger contract:
15
+ */ import { type } from '@lowdefy/helpers';
16
+ // Adapts the Lowdefy logger to BetterAuth's logger contract:
16
17
  // { disabled, level, log(level, message, ...args) }.
18
+ //
19
+ // BetterAuth passes what failed as extra args - "Failed to run background task:" with the
20
+ // error from an email send. An Error goes under `err`, so the log keeps its message, stack and
21
+ // cause and the prod log's projection drops a library's own fields (nodemailer's rejected
22
+ // recipients and server response). Any other arg is a value BetterAuth was working on - a user,
23
+ // a session, a request body - so the line names its type only. An error the Lowdefy code it
24
+ // called already reported (handled, set by handleError) is written at debug.
17
25
  function createAuthLogger({ logger }) {
18
26
  return {
19
27
  disabled: false,
20
28
  level: logger?.isLevelEnabled?.('debug') === true ? 'debug' : 'warn',
21
29
  log: (level, message, ...args)=>{
22
- const log = logger?.[level] ?? logger?.info;
30
+ const err = args.find((arg)=>arg instanceof Error);
31
+ const lineLevel = err?.handled === true ? 'debug' : level;
32
+ const log = logger?.[lineLevel] ?? logger?.info;
23
33
  if (!log) return;
24
- log.call(logger, {
25
- event: 'auth_engine',
26
- args
27
- }, message);
34
+ const entry = {
35
+ event: 'auth_engine'
36
+ };
37
+ if (err) {
38
+ entry.err = err;
39
+ }
40
+ const values = args.filter((arg)=>arg !== err);
41
+ if (values.length > 0) {
42
+ entry.argTypes = values.map((arg)=>type.typeOf(arg));
43
+ }
44
+ log.call(logger, entry, message);
28
45
  }
29
46
  };
30
47
  }
@@ -13,14 +13,14 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { APIError } from 'better-auth/api';
16
- import { type } from '@lowdefy/helpers';
16
+ import isActiveMember from './organizations/isActiveMember.js';
17
17
  // Every MCP access token carries the organization its grant acts in as the
18
18
  // organization_id claim - the consent referenceId (buildOauthPostLogin). The
19
19
  // refresh grant re-stamps that reference without asking whether the user still
20
- // belongs to the organization, so a member who left or was removed would keep
21
- // refreshing into tokens the MCP route refuses: the client refreshes, retries,
22
- // gets the same 401 and gives up, and never re-runs sign-in and the
23
- // organization choice. Refusing the mint with invalid_grant is what sends an
20
+ // belongs to the organization, so a member who left, was removed or was
21
+ // suspended would keep refreshing into tokens the MCP route refuses: the client
22
+ // refreshes, retries, gets the same 401 and gives up, and never re-runs sign-in
23
+ // and the organization choice. Refusing the mint with invalid_grant is what sends an
24
24
  // OAuth client back through authorization.
25
25
  function createMcpAccessTokenClaims({ getAuth }) {
26
26
  return async function mcpAccessTokenClaims({ user, referenceId }) {
@@ -38,7 +38,9 @@ function createMcpAccessTokenClaims({ getAuth }) {
38
38
  }
39
39
  ]
40
40
  });
41
- if (type.isNone(member)) {
41
+ if (!isActiveMember({
42
+ member
43
+ })) {
42
44
  throw new APIError('BAD_REQUEST', {
43
45
  error: 'invalid_grant',
44
46
  error_description: 'The user is no longer a member of the organization this grant acts in. Authorize again to choose an organization.'
@@ -21,10 +21,14 @@
21
21
  //
22
22
  // A 4xx is the auth server rejecting the caller's attempt: expected traffic,
23
23
  // one warn line, the same treatment the server error handler gives an
24
- // AuthenticationError. Anything else is a fault in the auth engine or its
25
- // adapter and stays at error level with the error object, so the cause chain
26
- // and stack are logged.
27
- function createOnAPIError({ logger }) {
24
+ // AuthenticationError. Anything else is a fault in the auth engine, its
25
+ // adapter or a hook, and goes to the error sink of a system context - this
26
+ // callback cannot reach the request's own context - so it is located, logged
27
+ // with its cause chain and sent to error tracking. A fault a hook routine
28
+ // already reported (handled, set by handleError) is not reported twice.
29
+ //
30
+ // BetterAuth does not await onError, and handleError never rejects.
31
+ function createOnAPIError({ createSystemContext, getAuth, logger }) {
28
32
  return function onAPIError(error) {
29
33
  const statusCode = error?.statusCode;
30
34
  if (type.isInt(statusCode) && statusCode >= 400 && statusCode < 500) {
@@ -35,7 +39,13 @@ function createOnAPIError({ logger }) {
35
39
  }, `Auth request rejected (${statusCode}): ${error.message}`);
36
40
  return;
37
41
  }
38
- logger.error(error);
42
+ if (error?.handled === true) {
43
+ return;
44
+ }
45
+ const context = createSystemContext({
46
+ auth: getAuth()
47
+ });
48
+ context.handleError(error);
39
49
  };
40
50
  }
41
51
  export default createOnAPIError;