@lowdefy/api 7.2.0 → 7.3.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.
@@ -18,6 +18,7 @@ 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
20
  import isActiveMember from '../routes/auth/organizations/isActiveMember.js';
21
+ import isUserBanned from '../routes/auth/isUserBanned.js';
21
22
  import { getAsIssuer, getMcpResourceUri } from '../routes/mcp/getMcpUri.js';
22
23
  import getMcpJwks from '../routes/mcp/getMcpJwks.js';
23
24
  import readMemberships from './readMemberships.js';
@@ -247,15 +248,6 @@ function hasMcpAudienceBearer({ context, headers }) {
247
248
  }
248
249
  return rejected;
249
250
  }
250
- // A banned user is refused on every MCP bearer, OAuth or member token: a ban
251
- // deletes the user's sessions, but nothing else on the bearer path would read
252
- // it. A ban with an expiry in the past no longer applies.
253
- function isBanned({ user }) {
254
- if (user.banned !== true) {
255
- return false;
256
- }
257
- return type.isNone(user.banExpires) || new Date(user.banExpires) > new Date();
258
- }
259
251
  // The user read, ban check and membership wall both MCP bearers share once
260
252
  // each has settled which user and organization it acts for. Returns the
261
253
  // resolved caller, or null when the user is gone, banned or not a member.
@@ -277,7 +269,9 @@ async function resolveBearerMember(context, { adapter, auth, memberId, organizat
277
269
  }, `MCP bearer rejected: user "${userId}" has no user row.`);
278
270
  return null;
279
271
  }
280
- if (isBanned({
272
+ // A banned user is refused on every MCP bearer, OAuth or member token: a ban
273
+ // deletes the user's sessions, but nothing else on the bearer path would read it.
274
+ if (isUserBanned({
281
275
  user
282
276
  })) {
283
277
  context.logger.debug({
@@ -291,11 +291,13 @@ function getBetterAuthConfig({ appMeta, authJson, config = {}, createSystemConte
291
291
  // indexes, or reads inside it.
292
292
  //
293
293
  // contactId is the link to the app's canonical record for the human
294
- // behind this login. It carries profile's opaque contract, not
295
- // attributes' - stored, projected onto the caller, and otherwise
296
- // ignored: never validated, indexed, or read by the platform, and never
297
- // resolved to whatever it points at. That is module work, and which
298
- // record the name means is the module's business. A first-class field
294
+ // behind this login. Apps compare it in author and access checks, so it
295
+ // is an authorization input and is set once: accepting an invitation
296
+ // sets it only on a login with no link and refuses an invitation naming
297
+ // a different contact (checkInvitationContactLink), and no auth step
298
+ // writes it after that. The platform never resolves it to whatever it
299
+ // points at - that is module work, and which record the name means is
300
+ // the module's business. A first-class field
299
301
  // rather than a key inside profile, because a link to another entity is
300
302
  // a different kind of thing from an opaque attribute bag - it belongs
301
303
  // with the user's other structural facts.
@@ -723,7 +725,8 @@ function getBetterAuthConfig({ appMeta, authJson, config = {}, createSystemConte
723
725
  authConfig,
724
726
  basePath: config.basePath ?? '',
725
727
  baseUrlOrigin,
726
- getAuth
728
+ getAuth,
729
+ logger
727
730
  });
728
731
  // Phone login sends SMS through the "phone.otp.send" hook binding - there
729
732
  // is no built-in SMS transport, so build validation requires the binding
@@ -0,0 +1,28 @@
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 admin plugin's ban rule, as its session.create.before applies it: any truthy
16
+ // banned is a ban, and only a banExpires that reads as a past date lifts it. The
17
+ // truthiness checks are deliberate - a user this calls unbanned while the plugin
18
+ // refuses them would be sent an email the sign-in then rejects. They are an
19
+ // exception to the type.isNone() rule: type.isNone(banExpires) would read a
20
+ // banExpires of 0 as a 1970 expiry and lift a ban the plugin keeps.
21
+ function isUserBanned({ user }) {
22
+ if (!user.banned) {
23
+ return false;
24
+ }
25
+ const expired = Boolean(user.banExpires) && new Date(user.banExpires).getTime() < Date.now();
26
+ return !expired;
27
+ }
28
+ export default isUserBanned;
@@ -14,6 +14,7 @@
14
14
  limitations under the License.
15
15
  */ import { organization } from 'better-auth/plugins';
16
16
  import createAfterAcceptInvitationHook from './createAfterAcceptInvitationHook.js';
17
+ import createBeforeAcceptInvitationHook from './createBeforeAcceptInvitationHook.js';
17
18
  import createBeforeCreateInvitationHook from './createBeforeCreateInvitationHook.js';
18
19
  import createBeforeUpdateMemberRoleHook from './createBeforeUpdateMemberRoleHook.js';
19
20
  import modelNames from '../modelNames.js';
@@ -45,7 +46,7 @@ const DEFAULT_INVITATION_LIMIT = 1000000;
45
46
  // creator-protection guards, which key on the member's role string. With app
46
47
  // roles out of that field and the fabricated acting member claiming "owner"
47
48
  // itself, there is nothing left to defend against.
48
- function buildOrganizationPlugin({ authConfig = {}, getAuth, sendInvitationEmail }) {
49
+ function buildOrganizationPlugin({ authConfig = {}, getAuth, logger, sendInvitationEmail }) {
49
50
  const options = {
50
51
  ac,
51
52
  roles,
@@ -157,9 +158,10 @@ function buildOrganizationPlugin({ authConfig = {}, getAuth, sendInvitationEmail
157
158
  // invitation winning per key. Invite-time member attributes ride the
158
159
  // invitation the same way - accepting copies them onto the minted
159
160
  // member row, so an invited user's authorization parameters hold
160
- // from their first session. contactId rides it as a third opaque
161
- // copy, so an invitation can name the app record the invitee's login
162
- // will point at before that person has ever signed in.
161
+ // from their first session. contactId rides it too, so an invitation
162
+ // can name the app record the invitee's login will point at before
163
+ // that person has ever signed in; accept sets it only on a login with
164
+ // no link (createBeforeAcceptInvitationHook).
163
165
  //
164
166
  // appRoles is declared without the input: false its member counterpart
165
167
  // carries. toZodSchema drops input: false fields when isClientSide is
@@ -193,7 +195,14 @@ function buildOrganizationPlugin({ authConfig = {}, getAuth, sendInvitationEmail
193
195
  },
194
196
  organizationHooks: {
195
197
  afterAcceptInvitation: createAfterAcceptInvitationHook({
196
- getAuth
198
+ getAuth,
199
+ logger
200
+ }),
201
+ // Refuses an invitation naming a different contact than the login is
202
+ // linked to, before the member row is written: the link is set once.
203
+ beforeAcceptInvitation: createBeforeAcceptInvitationHook({
204
+ getAuth,
205
+ logger
197
206
  }),
198
207
  // Keeps a suspended member out of the owner tier, so the plugin's owner
199
208
  // guards, which count every owner row, stay exact (SuspendMember).
@@ -0,0 +1,60 @@
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 { APIError } from 'better-auth/api';
16
+ import { type } from '@lowdefy/helpers';
17
+ // The one check of an invitation's contactId against the accepting login's
18
+ // link, shared by both ways an accept is answered: the route's
19
+ // beforeAcceptInvitation hook and the existing-member request hook. The link
20
+ // is an authorization input apps compare in author and access checks, so it
21
+ // is set once: an invitation naming a different contact than the login holds
22
+ // is refused before anything is written. Like the other accept gates
23
+ // (createExpiredInvitationGate) the refusal is a short message for the person
24
+ // accepting, with its own code and no ids; the login, the invitation and both
25
+ // contacts go to the server log, so whoever runs the app can find the case.
26
+ // How the link gets corrected is the app's concern. The link is read from the
27
+ // stored user row, since the session user may be a cookie-cached copy. Returns true when the accept should set the link - the
28
+ // invitation names a contact and the login has none.
29
+ async function checkInvitationContactLink({ adapter, invitation, logger, userId }) {
30
+ if (!type.isString(invitation.contactId)) {
31
+ return false;
32
+ }
33
+ const userRow = await adapter.findOne({
34
+ model: 'user',
35
+ where: [
36
+ {
37
+ field: 'id',
38
+ value: userId
39
+ }
40
+ ]
41
+ });
42
+ if (type.isNone(userRow.contactId)) {
43
+ return true;
44
+ }
45
+ if (userRow.contactId === invitation.contactId) {
46
+ return false;
47
+ }
48
+ logger.warn({
49
+ event: 'invitation_contact_link_mismatch',
50
+ userId,
51
+ invitationId: invitation.id,
52
+ linkedContactId: userRow.contactId,
53
+ invitationContactId: invitation.contactId
54
+ }, `Invitation "${invitation.id}" names contact "${invitation.contactId}", but login "${userId}" is linked to contact "${userRow.contactId}" - accept refused.`);
55
+ throw new APIError('BAD_REQUEST', {
56
+ code: 'CONTACT_LINK_MISMATCH',
57
+ message: 'This invitation can not be accepted by this account.'
58
+ });
59
+ }
60
+ export default checkInvitationContactLink;
@@ -15,6 +15,7 @@
15
15
  */ import { getSessionFromCtx } from 'better-auth/api';
16
16
  import { setSessionCookie } from 'better-auth/cookies';
17
17
  import { type } from '@lowdefy/helpers';
18
+ import checkInvitationContactLink from './checkInvitationContactLink.js';
18
19
  import isActiveMember from './isActiveMember.js';
19
20
  // The engine-tier request hooks.before on /organization/accept-invitation for a
20
21
  // caller who is already a member of the invitation's organization - someone
@@ -24,8 +25,12 @@ import isActiveMember from './isActiveMember.js';
24
25
  // then reverts the invitation and fails. Accepting is answered here instead:
25
26
  // the invitation is marked accepted and the membership is left exactly as it
26
27
  // is - no second row, and nothing from the invitation (role, app roles,
27
- // attributes, profile) is applied. BetterAuth treats an invitation as the way
28
- // to join, never as a role change: it refuses to invite an existing member,
28
+ // attributes, profile) is applied - except the login's contact link, which is
29
+ // the login's, not the membership's, and is set once whatever the way in: a
30
+ // login with no link takes the invitation's, and an invitation naming a
31
+ // different contact is refused before the invitation is consumed, as the
32
+ // route's beforeAcceptInvitation hook refuses it. BetterAuth treats an
33
+ // invitation as the way to join, never as a role change: it refuses to invite an existing member,
29
34
  // and role changes go through update-member-role, which checks the caller's
30
35
  // authority at the time of the change. An invitation written before the
31
36
  // membership existed must not override what an administrator set since.
@@ -42,7 +47,7 @@ import isActiveMember from './isActiveMember.js';
42
47
  // away from an existing active organization). A suspended membership is left
43
48
  // as it is too, so the organization is never made active: it admits nobody,
44
49
  // and an org-less session at least keeps the caller awaiting an organization.
45
- function createAcceptExistingMemberHook() {
50
+ function createAcceptExistingMemberHook({ logger }) {
46
51
  return async function acceptExistingMemberHook(ctx) {
47
52
  const invitationId = ctx.body?.invitationId;
48
53
  if (!type.isString(invitationId)) {
@@ -81,6 +86,21 @@ function createAcceptExistingMemberHook() {
81
86
  if (type.isNone(member)) {
82
87
  return undefined;
83
88
  }
89
+ const setsContactLink = await checkInvitationContactLink({
90
+ adapter,
91
+ invitation,
92
+ logger,
93
+ userId: session.user.id
94
+ });
95
+ // The link is written before the invitation is consumed, so a failed write
96
+ // leaves the invitation pending and the accept can be retried. Any other
97
+ // accept of this invitation is by the same login, so it sets the same link.
98
+ let user = session.user;
99
+ if (setsContactLink) {
100
+ user = await internalAdapter.updateUser(session.user.id, {
101
+ contactId: invitation.contactId
102
+ });
103
+ }
84
104
  // The route's own compare-and-set: of two concurrent accepts only one
85
105
  // moves the invitation off pending, and the other falls through to the
86
106
  // route, which answers it as the used invitation it now is.
@@ -104,18 +124,28 @@ function createAcceptExistingMemberHook() {
104
124
  if (type.isNone(accepted)) {
105
125
  return undefined;
106
126
  }
107
- if (type.isNone(session.session.activeOrganizationId) && isActiveMember({
127
+ const setsActiveOrganization = type.isNone(session.session.activeOrganizationId) && isActiveMember({
108
128
  member
109
- })) {
110
- // Re-issued like the set-active-organization route does, so a session
111
- // cookie cache does not keep serving the org-less session.
112
- await setSessionCookie(ctx, {
113
- session: await internalAdapter.updateSession(session.session.token, {
114
- activeOrganizationId: invitation.organizationId
115
- }),
116
- user: session.user
129
+ });
130
+ if (!setsContactLink && !setsActiveOrganization) {
131
+ return {
132
+ invitation: accepted,
133
+ member
134
+ };
135
+ }
136
+ let sessionRow = session.session;
137
+ if (setsActiveOrganization) {
138
+ sessionRow = await internalAdapter.updateSession(session.session.token, {
139
+ activeOrganizationId: invitation.organizationId
117
140
  });
118
141
  }
142
+ // Re-issued like the set-active-organization route does, so a session
143
+ // cookie cache does not keep serving the org-less session or the login
144
+ // without its link.
145
+ await setSessionCookie(ctx, {
146
+ session: sessionRow,
147
+ user
148
+ });
119
149
  return {
120
150
  invitation: accepted,
121
151
  member
@@ -18,9 +18,15 @@
18
18
  // the member row is created). An invitation may carry an opaque profile bag;
19
19
  // accepting shallow-merges it onto the accepting user's user.profile,
20
20
  // invitation winning per key - an opaque copy the engine never reads inside.
21
- // The merge is in-band: a failed copy fails the accept and the user retries.
22
- // invitation.contactId - the link to the app's record for this person - is the
23
- // third opaque copy, and rides the same user-row update as the profile merge.
21
+ // The hook runs after BetterAuth has consumed the invitation and written the
22
+ // member row, and nothing reverts those when a copy here fails: the request
23
+ // fails, the membership stands without the copies, and the invitation can not
24
+ // be accepted again.
25
+ // invitation.contactId - the link to the app's record for this person - rides
26
+ // the same user-row update as the profile merge, and is set only on a login
27
+ // that has no link yet: the link is an authorization input, set once.
28
+ // createBeforeAcceptInvitationHook has already refused an invitation naming a
29
+ // different contact than the login's, before the member row was written.
24
30
  // Invite-time member attributes and app roles ride the invitation the same
25
31
  // way: accepting copies invitation.attributes and invitation.appRoles onto the
26
32
  // minted member row (one adapter-layer update, parallel to the opaque profile
@@ -34,14 +40,17 @@
34
40
  // directly (crud-invites.mjs:324), never validating it against the registered
35
41
  // set - which is what makes the bootstrap recipe's hand-inserted role: 'owner'
36
42
  // work.
37
- function createAfterAcceptInvitationHook({ getAuth }) {
43
+ function createAfterAcceptInvitationHook({ getAuth, logger }) {
38
44
  return async function afterAcceptInvitationHook({ invitation, member, user }) {
39
45
  const { adapter, internalAdapter } = await getAuth().$context;
40
46
  const userUpdate = {};
41
- if (type.isObject(invitation.profile)) {
47
+ const copiesProfile = type.isObject(invitation.profile);
48
+ const copiesContactId = type.isString(invitation.contactId);
49
+ if (copiesProfile || copiesContactId) {
42
50
  // The hook's user is the session user, which may be a cookie-cached
43
- // copy - the merge base is read from the user row so a read-merge-write
44
- // never resurrects a stale profile.
51
+ // copy - the merge base and the current link are read from the user row
52
+ // so a read-merge-write never resurrects a stale profile, and a link
53
+ // set since the session was cached is never overwritten.
45
54
  const userRow = await adapter.findOne({
46
55
  model: 'user',
47
56
  where: [
@@ -51,15 +60,30 @@ function createAfterAcceptInvitationHook({ getAuth }) {
51
60
  }
52
61
  ]
53
62
  });
54
- userUpdate.profile = {
55
- ...userRow.profile ?? {},
56
- ...invitation.profile
57
- };
58
- }
59
- // contactId is a top-level user field, so it is set outright - no read, no
60
- // merge. An invitation that names no link leaves an existing one standing.
61
- if (type.isString(invitation.contactId)) {
62
- userUpdate.contactId = invitation.contactId;
63
+ if (copiesProfile) {
64
+ userUpdate.profile = {
65
+ ...userRow.profile ?? {},
66
+ ...invitation.profile
67
+ };
68
+ }
69
+ // An invitation that names no link leaves an existing one standing, and
70
+ // the same link is not written again.
71
+ if (copiesContactId && type.isNone(userRow.contactId)) {
72
+ userUpdate.contactId = invitation.contactId;
73
+ }
74
+ // createBeforeAcceptInvitationHook refused a different link already, so
75
+ // one seen here was written while this accept ran - another accept by the
76
+ // same login, or a write to the data. The membership is already written,
77
+ // so the invitation's link is dropped and logged, not refused.
78
+ if (copiesContactId && !type.isNone(userRow.contactId) && userRow.contactId !== invitation.contactId) {
79
+ logger.warn({
80
+ event: 'invitation_contact_link_mismatch',
81
+ userId: user.id,
82
+ invitationId: invitation.id,
83
+ linkedContactId: userRow.contactId,
84
+ invitationContactId: invitation.contactId
85
+ }, `Invitation "${invitation.id}" names contact "${invitation.contactId}", but login "${user.id}" was linked to contact "${userRow.contactId}" while it was accepted - the invitation's link was not applied.`);
86
+ }
63
87
  }
64
88
  if (Object.keys(userUpdate).length > 0) {
65
89
  await internalAdapter.updateUser(user.id, userUpdate);
@@ -0,0 +1,35 @@
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 checkInvitationContactLink from './checkInvitationContactLink.js';
16
+ // The engine-tier binding on the organization plugin's beforeAcceptInvitation
17
+ // hook, which keeps the login's contactId a link that is set once
18
+ // (checkInvitationContactLink). It runs before BetterAuth moves the invitation
19
+ // off pending or writes the member row, so a refusal leaves nothing
20
+ // half-written - the invitation stays pending and no membership exists. The
21
+ // link itself is set by createAfterAcceptInvitationHook once the member row
22
+ // exists. An accept by someone already in the organization never reaches this
23
+ // hook; createAcceptExistingMemberHook makes the same check.
24
+ function createBeforeAcceptInvitationHook({ getAuth, logger }) {
25
+ return async function beforeAcceptInvitationHook({ invitation, user }) {
26
+ const { adapter } = await getAuth().$context;
27
+ await checkInvitationContactLink({
28
+ adapter,
29
+ invitation,
30
+ logger,
31
+ userId: user.id
32
+ });
33
+ };
34
+ }
35
+ export default createBeforeAcceptInvitationHook;
@@ -12,8 +12,10 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import { type } from '@lowdefy/helpers';
15
+ */ import { LowdefyInternalError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
16
17
  import isEmailAdmitted from './isEmailAdmitted.js';
18
+ import isUserBanned from '../isUserBanned.js';
17
19
  // The engine-tier request hooks.before that gates a public, unauthenticated
18
20
  // email send - the magic-link send and the one-time-code send. Both are
19
21
  // unauthenticated: without this gate anyone could make an invite-only app
@@ -31,9 +33,21 @@ import isEmailAdmitted from './isEmailAdmitted.js';
31
33
  // answers { success: true }), so the caller names it: a uniform response is what
32
34
  // makes the "check your email" screen identical whether or not anything was
33
35
  // sent, and a body that did not match the route's own would give the difference
34
- // away. When admitted it falls through and the normal send proceeds. A no-op
35
- // under open signup (isEmailAdmitted returns admitted).
36
- function createEmailSendGate({ getAuth, organizations, successBody }) {
36
+ // away. When admitted it falls through and the normal send proceeds.
37
+ //
38
+ // A banned user gets the same success body under every signup policy, open
39
+ // signup included (where isEmailAdmitted admits everyone): session creation
40
+ // would refuse them anyway, so the email could only fail. The ban is checked
41
+ // here rather than in isEmailAdmitted because the session-create wall must keep
42
+ // answering BANNED_USER, which is what shows the banned message. It is checked
43
+ // after admission, so a banned address does the same lookups as an unbanned one
44
+ // and the response time does not tell them apart.
45
+ function createEmailSendGate({ getAuth, logger, organizations, successBody }) {
46
+ // Only the banned branch logs, so a missing logger would pass every other test
47
+ // and turn a banned send into a 500 - a response that gives the ban away.
48
+ if (type.isNone(logger)) {
49
+ throw new LowdefyInternalError('No logger was provided to createEmailSendGate.');
50
+ }
37
51
  return async function emailSendGate(ctx) {
38
52
  const email = ctx.body?.email;
39
53
  // No email is the route's own validation error, not an admission decision -
@@ -43,17 +57,31 @@ function createEmailSendGate({ getAuth, organizations, successBody }) {
43
57
  }
44
58
  const auth = getAuth();
45
59
  const { adapter, internalAdapter } = await auth.$context;
60
+ const found = await internalAdapter.findUserByEmail(email.toLowerCase());
61
+ // null, not undefined, for an address with no user: it tells isEmailAdmitted
62
+ // the lookup is done, so it does not repeat it.
63
+ const user = found?.user ?? null;
46
64
  const admitted = await isEmailAdmitted({
47
65
  email,
66
+ user,
48
67
  organizations,
49
68
  auth,
50
69
  adapter,
51
70
  internalAdapter
52
71
  });
53
- if (admitted) {
54
- return undefined;
72
+ if (!admitted) {
73
+ return successBody;
74
+ }
75
+ if (!type.isNone(user) && isUserBanned({
76
+ user
77
+ })) {
78
+ logger.debug({
79
+ event: 'auth_email_send_banned',
80
+ userId: user.id
81
+ }, `Sign-in email not sent: user "${user.id}" is banned.`);
82
+ return successBody;
55
83
  }
56
- return successBody;
84
+ return undefined;
57
85
  };
58
86
  }
59
87
  export default createEmailSendGate;
@@ -18,8 +18,10 @@ import findPendingInvitation from './findPendingInvitation.js';
18
18
  import isActiveMember from './isActiveMember.js';
19
19
  import MEMBER_ROWS_LIMIT from './memberRowsLimit.js';
20
20
  // The one admission predicate, shared by all three enforcement points: the
21
- // session.create wall (which passes a userId), the user.create.before gate and
22
- // the magic-link send gate (which pass an email, before any user exists).
21
+ // session.create wall (which passes a userId), the user.create.before gate
22
+ // (which passes an email, before any user exists) and the email send gate
23
+ // (which passes the email and the user it already looked up, null when the
24
+ // address has none).
23
25
  //
24
26
  // Admission is restrictive under invite-only (either policy). Open signup
25
27
  // auto-joins under both policies, so the predicate short-circuits to true and
@@ -33,7 +35,7 @@ import MEMBER_ROWS_LIMIT from './memberRowsLimit.js';
33
35
  // The email is lowercased once at entry to match BetterAuth's lowercased-stored
34
36
  // user.email and the org plugin's lowercased invitation storage, so no
35
37
  // case-variant address is wrongly suppressed or wrongly admitted.
36
- async function isEmailAdmitted({ email, userId, organizations, auth, adapter, internalAdapter }) {
38
+ async function isEmailAdmitted({ email, user, userId, organizations, auth, adapter, internalAdapter }) {
37
39
  if (organizations.signup !== 'invite-only') {
38
40
  return true;
39
41
  }
@@ -43,13 +45,15 @@ async function isEmailAdmitted({ email, userId, organizations, auth, adapter, in
43
45
  slug: organizations.org
44
46
  }) : undefined;
45
47
  const normalizedEmail = type.isString(email) ? email.toLowerCase() : undefined;
46
- // The member row is keyed by user id. The wall holds the session userId; the
47
- // create and send gates hold only an email, so resolve the existing user (if
48
- // any) from it. Conversely the wall needs the email for the invitation lookup,
49
- // so resolve it from the userId when the caller did not pass one.
50
- let memberUserId = userId;
48
+ // The member row is keyed by user id. The wall holds the session userId and
49
+ // the send gate the user it looked up; the create gate holds only an email,
50
+ // so resolve the existing user (if any) from it. A user of null means the
51
+ // caller looked and found none, so there is nothing to resolve. Conversely the
52
+ // wall needs the email for the invitation lookup, so resolve it from the
53
+ // userId when the caller did not pass one.
54
+ let memberUserId = type.isNone(user) ? userId : user.id;
51
55
  let invitationEmail = normalizedEmail;
52
- if (type.isNone(memberUserId) && !type.isNone(normalizedEmail)) {
56
+ if (type.isNone(memberUserId) && type.isUndefined(user) && !type.isNone(normalizedEmail)) {
53
57
  const found = await internalAdapter.findUserByEmail(normalizedEmail);
54
58
  memberUserId = found?.user?.id;
55
59
  }
@@ -39,7 +39,7 @@ import resolveTwoFactorPageUrl from './resolveTwoFactorPageUrl.js';
39
39
  // for every path. Whether a registration is added stays conditional on config,
40
40
  // and those conditions live here so there is one place to read what the engine
41
41
  // hooks into.
42
- function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }) {
42
+ function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth, logger }) {
43
43
  const before = [];
44
44
  const after = [];
45
45
  // The effective trust-device lifetime, mirroring the value passed to the
@@ -56,7 +56,9 @@ function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }
56
56
  before.push({
57
57
  id: 'acceptExistingMember',
58
58
  matches: (path)=>path === '/organization/accept-invitation',
59
- handler: createAcceptExistingMemberHook()
59
+ handler: createAcceptExistingMemberHook({
60
+ logger
61
+ })
60
62
  });
61
63
  if (authConfig.magicLink?.enabled === true) {
62
64
  before.push({
@@ -64,6 +66,7 @@ function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }
64
66
  matches: (path)=>path === '/sign-in/magic-link',
65
67
  handler: createEmailSendGate({
66
68
  getAuth,
69
+ logger,
67
70
  organizations: authConfig.organizations,
68
71
  // The magic-link route's own success body.
69
72
  successBody: {
@@ -107,6 +110,7 @@ function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }
107
110
  matches: (path)=>path === '/email-otp/send-verification-otp',
108
111
  handler: createEmailSendGate({
109
112
  getAuth,
113
+ logger,
110
114
  organizations: authConfig.organizations,
111
115
  // The OTP send route's own success body - a different shape from the
112
116
  // magic-link route's, and the suppressed response has to match it.
@@ -0,0 +1,81 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { AuthorizationError, isExpectedError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ import invokeEndpoint from '../endpoints/invokeEndpoint.js';
18
+ // Role rules decide who may hear a channel at all. A channel whose payload
19
+ // names a record also needs to know whether this subscriber may see that
20
+ // record, which only the app's own data can answer - so the websocket's check
21
+ // endpoint runs as the subscriber and must answer exactly true. It runs on
22
+ // every subscribe and publish, and again on the connection's periodic caller
23
+ // check while a subscription stays open, so revoked access ends it.
24
+ //
25
+ // Every refusal reads as a missing websocket, as a role refusal does
26
+ // (authorizeWebsocket), so a subscriber can not tell a record it may not see
27
+ // from a channel that does not exist.
28
+ async function checkWebsocketAccess(context, { payload, websocketConfig }) {
29
+ const { check, websocketId } = websocketConfig;
30
+ if (type.isNone(check)) {
31
+ return;
32
+ }
33
+ const { logger } = context;
34
+ let allowed = false;
35
+ try {
36
+ const checkPayload = type.isNone(check.payload) ? payload : context.evaluateOperators({
37
+ input: check.payload,
38
+ location: websocketId,
39
+ payload,
40
+ state: {},
41
+ steps: {}
42
+ });
43
+ // The subscriber's client built the payload, so a payload the endpoint's
44
+ // schema refuses is that caller's mistake, as for a CallAPI with no page
45
+ // (validatePayload), not a fault to log at error level.
46
+ const result = await invokeEndpoint(context, {
47
+ endpointId: check.endpointId,
48
+ payload: checkPayload,
49
+ endpointDepth: 0,
50
+ outsideCaller: true
51
+ });
52
+ // A routine that errored was logged by runRoutine.
53
+ allowed = result.status === 'return' && result.response === true;
54
+ logger.debug({
55
+ event: 'debug_websocket_check',
56
+ websocketId,
57
+ allowed,
58
+ status: result.status
59
+ });
60
+ } catch (error) {
61
+ // The endpoint refusing the caller is a refusal like any other. Anything
62
+ // else is a fault in the check's config or the endpoint, which the
63
+ // developer needs to see; the subscriber is refused either way.
64
+ if (isExpectedError(error)) {
65
+ logger.debug({
66
+ event: 'debug_websocket_check_refused',
67
+ websocketId,
68
+ err: error
69
+ });
70
+ } else {
71
+ if (error instanceof Object && type.isNone(error.configKey)) {
72
+ error.configKey = check['~k'] ?? websocketConfig['~k'];
73
+ }
74
+ await context.handleError(error);
75
+ }
76
+ }
77
+ if (!allowed) {
78
+ throw new AuthorizationError(`Websocket "${websocketId}" does not exist.`);
79
+ }
80
+ }
81
+ export default checkWebsocketAccess;
@@ -13,8 +13,10 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import crypto from 'crypto';
16
- import { serializer } from '@lowdefy/helpers';
16
+ import { serializer, type } from '@lowdefy/helpers';
17
17
  import { ConfigError } from '@lowdefy/errors';
18
+ import checkWebsocketAccess from './checkWebsocketAccess.js';
19
+ import createEvaluateOperators from '../../context/createEvaluateOperators.js';
18
20
  import createWireProjection from '../../response/createWireProjection.js';
19
21
  import prepareChannel from './prepareChannel.js';
20
22
  import wrapResolverError from '../request/wrapResolverError.js';
@@ -28,6 +30,10 @@ const HEALTHY_RESET_MS = 60 * 1000;
28
30
  // last one leaves.
29
31
  function createChannelRegistry() {
30
32
  const channels = new Map();
33
+ // subscriber → (websocketId → { payload, websocketConfig }) for the open
34
+ // subscriptions whose websocket has a check, so the check can run again while
35
+ // they stay open (recheckAccess).
36
+ const checkedSubscriptions = new WeakMap();
31
37
  function getChannelKey({ connectionProperties, properties, tenant, websocketId }) {
32
38
  // The tenant verdict is part of the channel identity: two callers whose
33
39
  // evaluated properties are identical but whose organizations differ must
@@ -178,9 +184,12 @@ function createChannelRegistry() {
178
184
  subscriber
179
185
  });
180
186
  }
187
+ // The client serializes the payload, as it does for a publish and a CallAPI,
188
+ // so properties and the check endpoint read Dates as Dates.
189
+ const deserializedPayload = serializer.deserialize(payload ?? {});
181
190
  const { connectionProperties, properties, tenant, websocketConfig, websocketResolver } = await prepareChannel(context, {
182
191
  websocketId,
183
- payload
192
+ payload: deserializedPayload
184
193
  });
185
194
  const key = getChannelKey({
186
195
  connectionProperties,
@@ -211,6 +220,15 @@ function createChannelRegistry() {
211
220
  }
212
221
  channel.subscribers.add(subscriber);
213
222
  subscriber.subscriptions.set(websocketId, key);
223
+ if (!type.isNone(websocketConfig.check)) {
224
+ if (!checkedSubscriptions.has(subscriber)) {
225
+ checkedSubscriptions.set(subscriber, new Map());
226
+ }
227
+ checkedSubscriptions.get(subscriber).set(websocketId, {
228
+ payload: deserializedPayload,
229
+ websocketConfig
230
+ });
231
+ }
214
232
  context.logger.debug({
215
233
  event: 'ws_subscribe',
216
234
  websocketId,
@@ -220,6 +238,7 @@ function createChannelRegistry() {
220
238
  function unsubscribe({ websocketId, subscriber }) {
221
239
  const key = subscriber.subscriptions.get(websocketId);
222
240
  subscriber.subscriptions.delete(websocketId);
241
+ checkedSubscriptions.get(subscriber)?.delete(websocketId);
223
242
  if (!key) {
224
243
  return;
225
244
  }
@@ -242,6 +261,32 @@ function createChannelRegistry() {
242
261
  });
243
262
  });
244
263
  }
264
+ function getCheckedWebsocketIds({ subscriber }) {
265
+ return [
266
+ ...checkedSubscriptions.get(subscriber)?.keys() ?? []
267
+ ];
268
+ }
269
+ // Access to a record can be revoked while a subscription to it stays open, so
270
+ // the connection runs the check again on its periodic caller check, with the
271
+ // payload and config the subscription was opened with. A refused
272
+ // subscription is closed and the refusal thrown for the caller to be told.
273
+ // The subscription may have been closed while this waited in its feed queue.
274
+ async function recheckAccess(context, { websocketId, subscriber }) {
275
+ const subscription = checkedSubscriptions.get(subscriber)?.get(websocketId);
276
+ if (type.isUndefined(subscription)) {
277
+ return;
278
+ }
279
+ context.evaluateOperators = createEvaluateOperators(context);
280
+ try {
281
+ await checkWebsocketAccess(context, subscription);
282
+ } catch (error) {
283
+ unsubscribe({
284
+ websocketId,
285
+ subscriber
286
+ });
287
+ throw error;
288
+ }
289
+ }
245
290
  async function publish(context, { websocketId, payload }) {
246
291
  // Publish identity is evaluated without a subscription payload — channels
247
292
  // that fragment on _payload/_user in properties are not publish targets.
@@ -281,7 +326,9 @@ function createChannelRegistry() {
281
326
  });
282
327
  }
283
328
  return {
329
+ getCheckedWebsocketIds,
284
330
  publish,
331
+ recheckAccess,
285
332
  subscribe,
286
333
  unsubscribe,
287
334
  unsubscribeAll,
@@ -31,7 +31,9 @@ const CALLER_CHECK_FAILED_CODE = 1011;
31
31
  // out, lost its membership, changed roles or switched organization, the socket
32
32
  // closes with code 4401; the client reconnects, which authenticates afresh.
33
33
  // Each check is a live session read - nothing is cached, so a revoked session
34
- // closes the socket within a minute.
34
+ // closes the socket within a minute. The once-a-minute check also runs the
35
+ // websocket check of every open subscription that has one, so revoked access to
36
+ // a record ends that subscription within a minute.
35
37
  function createWebSocketConnection(context, { closeSocket, headers, registry, send, strategies }) {
36
38
  const { logger } = context;
37
39
  const callerFingerprint = getCallerFingerprint({
@@ -178,6 +180,26 @@ function createWebSocketConnection(context, { closeSocket, headers, registry, se
178
180
  });
179
181
  }
180
182
  }
183
+ function reportError({ error, frameType, requestId, websocketId }) {
184
+ logger.debug({
185
+ err: error
186
+ }, error.message);
187
+ // Expected outcomes - an auth refusal, a UserError - are one warn line, as over HTTP:
188
+ // no error log or Sentry report, but the client is still told.
189
+ if (isExpectedError(error)) {
190
+ logger.warn({
191
+ event: 'ws_refused',
192
+ frameType
193
+ }, error.message);
194
+ } else {
195
+ context.handleError(error);
196
+ }
197
+ sendErrorPayload({
198
+ error,
199
+ requestId,
200
+ websocketId
201
+ });
202
+ }
181
203
  async function processFrame(frame) {
182
204
  if (closed) {
183
205
  return;
@@ -185,26 +207,33 @@ function createWebSocketConnection(context, { closeSocket, headers, registry, se
185
207
  try {
186
208
  await handleFrame(frame);
187
209
  } catch (error) {
188
- logger.debug({
189
- err: error
190
- }, error.message);
191
- // Expected outcomes - an auth refusal, a UserError - are one warn line, as over HTTP:
192
- // no error log or Sentry report, but the client is still told.
193
- if (isExpectedError(error)) {
194
- logger.warn({
195
- event: 'ws_refused',
196
- frameType: frame.type
197
- }, error.message);
198
- } else {
199
- context.handleError(error);
200
- }
201
- sendErrorPayload({
210
+ reportError({
202
211
  error,
212
+ frameType: frame.type,
203
213
  requestId: frame.requestId,
204
214
  websocketId: frame.websocketId
205
215
  });
206
216
  }
207
217
  }
218
+ // A refused subscription is closed by the registry. The error frame carries no
219
+ // requestId, so the client reads it as the feed failing, as it does a source error.
220
+ async function recheckSubscription(websocketId) {
221
+ if (closed) {
222
+ return;
223
+ }
224
+ try {
225
+ await registry.recheckAccess(context, {
226
+ websocketId,
227
+ subscriber
228
+ });
229
+ } catch (error) {
230
+ reportError({
231
+ error,
232
+ frameType: 'recheck',
233
+ websocketId
234
+ });
235
+ }
236
+ }
208
237
  function enqueue(websocketId, task) {
209
238
  const handled = (feedQueues.get(websocketId) ?? Promise.resolve()).then(task);
210
239
  const tail = handled.catch(()=>{});
@@ -246,9 +275,21 @@ function createWebSocketConnection(context, { closeSocket, headers, registry, se
246
275
  // routines it runs.
247
276
  await enqueue(frame.websocketId, ()=>runInCredentialScope(()=>processFrame(frame)));
248
277
  }
278
+ // A websocket check answers for one record, which the caller can lose access
279
+ // to without the caller changing, so the check runs again for every open
280
+ // subscription that has one. Each runs in its feed's queue, after any frame
281
+ // for that feed already waiting.
282
+ async function checkOpenConnection() {
283
+ if (!await checkCaller()) {
284
+ return;
285
+ }
286
+ await Promise.all(registry.getCheckedWebsocketIds({
287
+ subscriber
288
+ }).map((websocketId)=>enqueue(websocketId, ()=>runInCredentialScope(()=>recheckSubscription(websocketId)))));
289
+ }
249
290
  // One timer per connection, cleared by close. It does not keep the process
250
291
  // alive on its own.
251
- const callerCheckTimer = setInterval(checkCaller, CALLER_CHECK_INTERVAL_MS);
292
+ const callerCheckTimer = setInterval(checkOpenConnection, CALLER_CHECK_INTERVAL_MS);
252
293
  callerCheckTimer.unref();
253
294
  logger.debug({
254
295
  event: 'ws_connect'
@@ -14,6 +14,7 @@
14
14
  limitations under the License.
15
15
  */ import { type } from '@lowdefy/helpers';
16
16
  import authorizeWebsocket from './authorizeWebsocket.js';
17
+ import checkWebsocketAccess from './checkWebsocketAccess.js';
17
18
  import checkConnectionRead from '../request/checkConnectionRead.js';
18
19
  import getConnection from '../connections/getConnection.js';
19
20
  import getConnectionConfig from '../connections/getConnectionConfig.js';
@@ -27,6 +28,12 @@ import createEvaluateOperators from '../../context/createEvaluateOperators.js';
27
28
  // websocket definition can produce user- or filter-specific channels. The
28
29
  // evaluated result is the channel identity — subscribers whose evaluation is
29
30
  // identical share one running source.
31
+ //
32
+ // After the role check, the websocket's check endpoint runs, before anything is
33
+ // evaluated for a caller it refuses. The check is per caller and not part of the channel
34
+ // identity, so subscribers that each pass still share a source. A publish is
35
+ // checked too, with the same empty payload its properties are evaluated with,
36
+ // so a caller the check refuses can not publish into a channel either.
30
37
  async function prepareChannel(context, { websocketId, payload }) {
31
38
  context.evaluateOperators = createEvaluateOperators(context);
32
39
  const websocketConfig = await getWebsocketConfig(context, {
@@ -35,6 +42,10 @@ async function prepareChannel(context, { websocketId, payload }) {
35
42
  authorizeWebsocket(context, {
36
43
  websocketConfig
37
44
  });
45
+ await checkWebsocketAccess(context, {
46
+ payload,
47
+ websocketConfig
48
+ });
38
49
  const websocketResolver = getWebsocketResolver(context, {
39
50
  websocketConfig
40
51
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lowdefy/api",
3
- "version": "7.2.0",
3
+ "version": "7.3.0",
4
4
  "license": "Apache-2.0",
5
5
  "description": "",
6
6
  "homepage": "https://lowdefy.com",
@@ -38,16 +38,16 @@
38
38
  "@better-auth/cimd": "1.7.7",
39
39
  "@better-auth/oauth-provider": "1.7.7",
40
40
  "@better-auth/passkey": "1.7.7",
41
- "@lowdefy/ajv": "7.2.0",
42
- "@lowdefy/build": "7.2.0",
43
- "@lowdefy/connection-smtp": "7.2.0",
44
- "@lowdefy/email-templates": "7.2.0",
45
- "@lowdefy/errors": "7.2.0",
46
- "@lowdefy/helpers": "7.2.0",
47
- "@lowdefy/node-utils": "7.2.0",
48
- "@lowdefy/nunjucks": "7.2.0",
49
- "@lowdefy/operators": "7.2.0",
50
- "@lowdefy/operators-js": "7.2.0",
41
+ "@lowdefy/ajv": "7.3.0",
42
+ "@lowdefy/build": "7.3.0",
43
+ "@lowdefy/connection-smtp": "7.3.0",
44
+ "@lowdefy/email-templates": "7.3.0",
45
+ "@lowdefy/errors": "7.3.0",
46
+ "@lowdefy/helpers": "7.3.0",
47
+ "@lowdefy/node-utils": "7.3.0",
48
+ "@lowdefy/nunjucks": "7.3.0",
49
+ "@lowdefy/operators": "7.3.0",
50
+ "@lowdefy/operators-js": "7.3.0",
51
51
  "@modelcontextprotocol/sdk": "1.32.2",
52
52
  "better-auth": "1.7.7",
53
53
  "jose": "^6.2.3",
@@ -55,8 +55,8 @@
55
55
  "nodemailer": "10.1.7"
56
56
  },
57
57
  "devDependencies": {
58
- "@lowdefy/connection-mongodb": "7.2.0",
59
- "@lowdefy/plugin-better-auth": "7.2.0",
58
+ "@lowdefy/connection-mongodb": "7.3.0",
59
+ "@lowdefy/plugin-better-auth": "7.3.0",
60
60
  "@opentelemetry/api": "1.9.1",
61
61
  "@swc/cli": "0.8.1",
62
62
  "@swc/core": "1.15.32",