@lowdefy/api 7.1.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.
- package/dist/context/createAuthorizeOutcome.js +1 -1
- package/dist/context/createEvaluateOperators.js +2 -1
- package/dist/context/isWebSocketOriginAllowed.js +3 -1
- package/dist/context/readMemberships.js +10 -4
- package/dist/context/resolveAuthentication.js +99 -31
- package/dist/email/renderAuthEmail.js +3 -2
- package/dist/index.js +7 -1
- package/dist/response/redactErrorResponse.js +8 -4
- package/dist/routes/agent/callAgent.js +20 -2
- package/dist/routes/agent/redactMessages.js +136 -0
- package/dist/routes/auth/createAuthLogger.js +23 -6
- package/dist/routes/auth/createMcpAccessTokenClaims.js +8 -6
- package/dist/routes/auth/createOnAPIError.js +15 -5
- package/dist/routes/auth/createSendEmail.js +15 -5
- package/dist/routes/auth/getBetterAuth.js +3 -3
- package/dist/routes/auth/getBetterAuthConfig.js +172 -98
- package/dist/routes/auth/hooks/buildEngineHooks.js +15 -1
- package/dist/routes/auth/hooks/createUserAfterHook.js +17 -2
- package/dist/routes/auth/hooks/createUserBeforeHook.js +20 -4
- package/dist/routes/auth/isUserBanned.js +28 -0
- package/dist/routes/auth/mobile/buildBearerPlugin.js +45 -0
- package/dist/routes/auth/mobile/buildOneTimeTokenPlugin.js +50 -0
- package/dist/routes/auth/mobile/createCodeVerifierCheck.js +57 -0
- package/dist/routes/auth/mobile/createKnownDeviceHook.js +76 -0
- package/dist/routes/auth/mobile/createMobileAuthPageResponse.js +79 -0
- package/dist/routes/auth/mobile/createMobileSessionCreateHook.js +41 -0
- package/dist/routes/auth/mobile/createMobileSessionRefreshHook.js +40 -0
- package/dist/routes/auth/mobile/createMobileSignInCsrfToken.js +32 -0
- package/dist/routes/auth/mobile/createPhoneSession.js +59 -0
- package/dist/routes/auth/mobile/escapeHtml.js +26 -0
- package/dist/routes/auth/mobile/getCodeHolderIdentifier.js +20 -0
- package/dist/routes/auth/mobile/getKnownDeviceIdentifier.js +20 -0
- package/dist/routes/auth/mobile/getMobileSessionExpiry.js +18 -0
- package/dist/routes/auth/mobile/getMobileSignInReturnUrl.js +31 -0
- package/dist/routes/auth/mobile/getOneTimeTokenIdentifiers.js +26 -0
- package/dist/routes/auth/mobile/handleMobileSignIn.js +303 -0
- package/dist/routes/auth/mobile/handleMobileSignInCallback.js +30 -0
- package/dist/routes/auth/mobile/isNativeAuthRequest.js +33 -0
- package/dist/routes/auth/mobile/matchesCodeChallenge.js +29 -0
- package/dist/routes/auth/mobile/mintOneTimeToken.js +41 -0
- package/dist/routes/auth/mobile/readDeviceKeyHash.js +34 -0
- package/dist/routes/auth/mobile/readMobileSignInParams.js +90 -0
- package/dist/routes/auth/mobile/sha256Base64Url.js +22 -0
- package/dist/routes/auth/mobile/storeCodeChallenge.js +29 -0
- package/dist/routes/auth/organizations/buildOrganizationPlugin.js +57 -11
- package/dist/routes/auth/organizations/checkInvitationContactLink.js +60 -0
- package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +47 -12
- package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +41 -189
- package/dist/routes/auth/organizations/createAdmissionGateHook.js +5 -5
- package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +40 -16
- package/dist/routes/auth/organizations/createBeforeAcceptInvitationHook.js +35 -0
- package/dist/routes/auth/organizations/createBeforeCreateInvitationHook.js +62 -0
- package/dist/routes/auth/organizations/createBeforeUpdateMemberRoleHook.js +45 -0
- package/dist/routes/auth/organizations/createEmailSendGate.js +35 -7
- package/dist/routes/auth/organizations/createSuspendedMemberGate.js +146 -0
- package/dist/routes/auth/organizations/createSuspendedOrganizationsFilter.js +44 -0
- package/dist/routes/auth/organizations/ensureAuthIndexes.js +11 -10
- package/dist/routes/auth/organizations/getOrganizationBinding.js +4 -2
- package/dist/routes/auth/organizations/isActiveMember.js +26 -0
- package/dist/routes/auth/organizations/isEmailAdmitted.js +25 -14
- package/dist/routes/auth/organizations/memberRowsLimit.js +19 -0
- package/dist/routes/auth/organizations/mintOrganization.js +258 -0
- package/dist/routes/auth/organizations/organizationAccessControl.js +5 -1
- package/dist/routes/auth/organizations/provisionOrganization.js +117 -0
- package/dist/routes/auth/organizations/readSuspendedOrganizationIds.js +36 -0
- package/dist/routes/auth/requestHooks/buildRequestHooks.js +78 -2
- package/dist/routes/auth/requestHooks/createEmailCodeHolderGate.js +58 -0
- package/dist/routes/auth/requestHooks/createEmailSendLimit.js +116 -0
- package/dist/routes/auth/requestHooks/createSignInRefusedRedirectHook.js +75 -0
- package/dist/routes/auth/requestHooks/holdEmailCode.js +80 -0
- package/dist/routes/auth/requestHooks/reserveSendSlot.js +70 -0
- package/dist/routes/auth/runReportingFaults.js +32 -0
- package/dist/routes/connections/resolveUnwalledReach.js +14 -16
- package/dist/routes/endpoints/callEndpoint.js +6 -3
- package/dist/routes/endpoints/control/controlFor.js +9 -6
- package/dist/routes/endpoints/control/controlIf.js +8 -3
- package/dist/routes/endpoints/control/controlLog.js +3 -1
- package/dist/routes/endpoints/control/controlParallelFor.js +9 -6
- package/dist/routes/endpoints/control/controlReturn.js +3 -2
- package/dist/routes/endpoints/control/controlSetState.js +1 -1
- package/dist/routes/endpoints/control/controlSwitch.js +6 -3
- package/dist/routes/endpoints/control/controlWhile.js +6 -3
- package/dist/routes/endpoints/createLinkAnswer.js +76 -0
- package/dist/routes/endpoints/dispatchDetached.js +38 -0
- package/dist/routes/endpoints/forwardScheduledEndpoint.js +32 -11
- package/dist/routes/endpoints/handleAgentCall.js +1 -1
- package/dist/routes/endpoints/handleAuthStep.js +19 -4
- package/dist/routes/endpoints/handleEndpointCall.js +6 -4
- package/dist/routes/endpoints/handleRequest.js +3 -2
- package/dist/routes/endpoints/handleValidateDynamic.js +1 -1
- package/dist/routes/endpoints/matchLinkEndpoint.js +30 -0
- package/dist/routes/endpoints/runLinkEndpoint.js +148 -0
- package/dist/routes/endpoints/runRoutine.js +5 -5
- package/dist/routes/endpoints/scheduleBackground.js +13 -11
- package/dist/routes/endpoints/test/runTest.js +30 -11
- package/dist/routes/mcp/createMcpServer.js +2 -7
- package/dist/routes/mcp/runAfterToolCall.js +9 -3
- package/dist/routes/mobile/createAppleAppSiteAssociation.js +51 -0
- package/dist/routes/mobile/createAssetLinks.js +38 -0
- package/dist/routes/mobile/filterMobileMenus.js +31 -0
- package/dist/routes/mobile/getMobileAppEvents.js +23 -0
- package/dist/routes/mobile/getMobileRootConfig.js +109 -0
- package/dist/routes/mobile/getOpenablePageIds.js +21 -0
- package/dist/routes/page/dynamic/policy/checkAction.js +67 -2
- package/dist/routes/page/dynamic/policy/checkEvents.js +8 -2
- package/dist/routes/page/dynamic/policy/checkPolicy.js +86 -6
- package/dist/routes/page/dynamic/policy/checkValue.js +97 -6
- package/dist/routes/page/dynamic/policy/collectSchemaKinds.js +173 -0
- package/dist/routes/page/dynamic/policy/findDataRows.js +94 -0
- package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +24 -12
- package/dist/routes/page/dynamic/policy/findHtmlUrls.js +64 -0
- package/dist/routes/page/dynamic/policy/overlapsStatePath.js +28 -0
- package/dist/routes/page/dynamic/resolveDynamicContent.js +23 -17
- package/dist/routes/page/getPageConfig.js +25 -1
- package/dist/routes/request/callRequestResolver.js +29 -36
- package/dist/routes/request/stampTypedError.js +37 -0
- package/dist/routes/request/summarisedError.js +62 -0
- package/dist/routes/request/wrapResolverError.js +61 -0
- package/dist/routes/websocket/checkWebsocketAccess.js +81 -0
- package/dist/routes/websocket/createChannelRegistry.js +62 -17
- package/dist/routes/websocket/createWebSocketConnection.js +59 -21
- package/dist/routes/websocket/prepareChannel.js +11 -0
- package/dist/test/createMemoryAuth.js +125 -0
- package/package.json +20 -22
- package/dist/routes/page/dynamic/policy/collectUrlKinds.js +0 -117
- package/dist/routes/request/maskCredentialProperties.js +0 -34
|
@@ -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
|
|
22
|
-
//
|
|
23
|
-
//
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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;
|
|
@@ -0,0 +1,62 @@
|
|
|
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
|
+
// The engine-tier binding on the organization plugin's beforeCreateInvitation
|
|
17
|
+
// hook, which enforces the cap on open invitations per organization. The
|
|
18
|
+
// plugin's own invitationLimit check cannot: it reads pending invitations with
|
|
19
|
+
// an unbounded findMany, which the adapter cuts to its default page of 100 rows
|
|
20
|
+
// before expired ones are filtered out in code. A limit above 100 is never
|
|
21
|
+
// reached, and expired rows inside that page hide open ones.
|
|
22
|
+
// buildOrganizationPlugin holds that check open, and this hook counts every
|
|
23
|
+
// pending, unexpired invitation of the organization instead.
|
|
24
|
+
//
|
|
25
|
+
// The hook runs after a re-invite has cancelled the address's earlier
|
|
26
|
+
// invitation, so the invitation being replaced is not counted. That order is
|
|
27
|
+
// BetterAuth's: an organization already over its limit (the limit lowered after
|
|
28
|
+
// invitations went out) refuses the re-invite after the cancel, and the
|
|
29
|
+
// address is left with no open invitation. A resend refreshes an invitation
|
|
30
|
+
// without creating one and never reaches the hook. The count and the create are
|
|
31
|
+
// separate writes, so invitations created in parallel can pass the limit by
|
|
32
|
+
// the number in flight, as BetterAuth's own check could.
|
|
33
|
+
function createBeforeCreateInvitationHook({ getAuth, invitationLimit }) {
|
|
34
|
+
return async function beforeCreateInvitationHook({ organization }) {
|
|
35
|
+
const { adapter } = await getAuth().$context;
|
|
36
|
+
const openInvitations = await adapter.count({
|
|
37
|
+
model: 'invitation',
|
|
38
|
+
where: [
|
|
39
|
+
{
|
|
40
|
+
field: 'organizationId',
|
|
41
|
+
value: organization.id
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
field: 'status',
|
|
45
|
+
value: 'pending'
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
field: 'expiresAt',
|
|
49
|
+
operator: 'gt',
|
|
50
|
+
value: new Date()
|
|
51
|
+
}
|
|
52
|
+
]
|
|
53
|
+
});
|
|
54
|
+
if (openInvitations >= invitationLimit) {
|
|
55
|
+
throw new APIError('FORBIDDEN', {
|
|
56
|
+
code: 'INVITATION_LIMIT_REACHED',
|
|
57
|
+
message: 'This organization has reached its limit of open invitations.'
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
export default createBeforeCreateInvitationHook;
|
|
@@ -0,0 +1,45 @@
|
|
|
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 isActiveMember from './isActiveMember.js';
|
|
17
|
+
// The engine-tier binding on the organization plugin's beforeUpdateMemberRole
|
|
18
|
+
// hook, which keeps a suspended member out of the owner tier. The plugin's
|
|
19
|
+
// owner guards (an admin cannot remove or demote an owner, the last owner
|
|
20
|
+
// cannot leave, be removed or demote themselves) count every owner row and know
|
|
21
|
+
// nothing of suspension. SuspendMember refuses an owner, and this refuses the
|
|
22
|
+
// other way in, so no suspended row holds owner and those counts stay exact.
|
|
23
|
+
// It runs inside the endpoint, so it covers the UpdateMemberOrgRole step and
|
|
24
|
+
// the tenant client call alike.
|
|
25
|
+
//
|
|
26
|
+
// newRole is the plugin's parsed role string, comma-separated when the
|
|
27
|
+
// request set several.
|
|
28
|
+
function createBeforeUpdateMemberRoleHook() {
|
|
29
|
+
return async function beforeUpdateMemberRoleHook({ member, newRole }) {
|
|
30
|
+
if (isActiveMember({
|
|
31
|
+
member
|
|
32
|
+
})) {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
const roleNames = String(newRole).split(',').map((role)=>role.trim());
|
|
36
|
+
if (!roleNames.includes('owner')) {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
throw new APIError('BAD_REQUEST', {
|
|
40
|
+
code: 'SUSPENDED_MEMBER_CANNOT_BE_OWNER',
|
|
41
|
+
message: 'A suspended member cannot be made an owner. Unsuspend them first.'
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
export default createBeforeUpdateMemberRoleHook;
|
|
@@ -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 {
|
|
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.
|
|
35
|
-
//
|
|
36
|
-
|
|
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
|
|
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
|
|
84
|
+
return undefined;
|
|
57
85
|
};
|
|
58
86
|
}
|
|
59
87
|
export default createEmailSendGate;
|
|
@@ -0,0 +1,146 @@
|
|
|
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, getSessionFromCtx } from 'better-auth/api';
|
|
16
|
+
import { type } from '@lowdefy/helpers';
|
|
17
|
+
import readSuspendedOrganizationIds from './readSuspendedOrganizationIds.js';
|
|
18
|
+
// The organization plugin's client endpoints that need no membership: create
|
|
19
|
+
// (disabled by allowUserToCreateOrganization), check-slug, the server-only
|
|
20
|
+
// add-member, and the invitee's own get-invitation, list-user-invitations,
|
|
21
|
+
// reject-invitation and accept-invitation (accepting leaves an existing
|
|
22
|
+
// membership as it is, see createAcceptExistingMemberHook). /organization/list
|
|
23
|
+
// is filtered instead, by createSuspendedOrganizationsFilter.
|
|
24
|
+
//
|
|
25
|
+
// Every other /organization/* path is gated. Each one checks membership with
|
|
26
|
+
// its own adapter read, which knows nothing of member.suspended, so a person
|
|
27
|
+
// suspended in an organization would otherwise still read its members, switch
|
|
28
|
+
// to it, invite into it or leave it from the browser. Listing the exceptions
|
|
29
|
+
// rather than the gated paths keeps an endpoint the plugin adds later (or
|
|
30
|
+
// teams, should they be enabled) closed to a suspended member by default.
|
|
31
|
+
const MEMBERSHIP_FREE_PATHS = [
|
|
32
|
+
'/organization/create',
|
|
33
|
+
'/organization/check-slug',
|
|
34
|
+
'/organization/add-member',
|
|
35
|
+
'/organization/get-invitation',
|
|
36
|
+
'/organization/list-user-invitations',
|
|
37
|
+
'/organization/reject-invitation',
|
|
38
|
+
'/organization/accept-invitation',
|
|
39
|
+
'/organization/list'
|
|
40
|
+
];
|
|
41
|
+
// The endpoints fall back to the active organization on any falsy id or slug
|
|
42
|
+
// (`ctx.body.organizationId || activeOrganizationId`), so an empty string names
|
|
43
|
+
// no organization.
|
|
44
|
+
function isNamed(value) {
|
|
45
|
+
return type.isString(value) && value !== '';
|
|
46
|
+
}
|
|
47
|
+
// Every organization the request could act in. The endpoints differ in which
|
|
48
|
+
// of these they read first (get-organization prefers the slug, set-active the
|
|
49
|
+
// id), so all of them are gathered and the request is refused if the caller is
|
|
50
|
+
// suspended in any. The active organization is the endpoints' fallback, so it
|
|
51
|
+
// counts only when the request names none - a person whose active
|
|
52
|
+
// organization is one they are suspended in can still switch away from it.
|
|
53
|
+
async function readTargetOrganizationIds({ adapter, ctx, session }) {
|
|
54
|
+
const ids = [
|
|
55
|
+
ctx.body?.organizationId,
|
|
56
|
+
ctx.query?.organizationId
|
|
57
|
+
].filter(isNamed);
|
|
58
|
+
const slugs = [
|
|
59
|
+
ctx.body?.organizationSlug,
|
|
60
|
+
ctx.query?.organizationSlug
|
|
61
|
+
].filter(isNamed);
|
|
62
|
+
for (const slug of slugs){
|
|
63
|
+
const organization = await adapter.findOne({
|
|
64
|
+
model: 'organization',
|
|
65
|
+
where: [
|
|
66
|
+
{
|
|
67
|
+
field: 'slug',
|
|
68
|
+
value: slug
|
|
69
|
+
}
|
|
70
|
+
]
|
|
71
|
+
});
|
|
72
|
+
if (!type.isNone(organization)) {
|
|
73
|
+
ids.push(organization.id);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
// cancel-invitation names only the invitation; the endpoint checks the
|
|
77
|
+
// caller's membership in the invitation's organization.
|
|
78
|
+
if (isNamed(ctx.body?.invitationId)) {
|
|
79
|
+
const invitation = await adapter.findOne({
|
|
80
|
+
model: 'invitation',
|
|
81
|
+
where: [
|
|
82
|
+
{
|
|
83
|
+
field: 'id',
|
|
84
|
+
value: ctx.body.invitationId
|
|
85
|
+
}
|
|
86
|
+
]
|
|
87
|
+
});
|
|
88
|
+
if (!type.isNone(invitation)) {
|
|
89
|
+
ids.push(invitation.organizationId);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (ids.length === 0 && isNamed(session.session.activeOrganizationId)) {
|
|
93
|
+
ids.push(session.session.activeOrganizationId);
|
|
94
|
+
}
|
|
95
|
+
return ids;
|
|
96
|
+
}
|
|
97
|
+
// The engine-tier request hooks.before that refuses a member-gated
|
|
98
|
+
// organization endpoint when the caller is suspended in the organization it
|
|
99
|
+
// acts in, with the error the endpoint gives a non-member. Registered under
|
|
100
|
+
// tenant only: under pinned the organization client endpoints are disabled.
|
|
101
|
+
function createSuspendedMemberGate() {
|
|
102
|
+
return async function suspendedMemberGate(ctx) {
|
|
103
|
+
// Clearing the active organization needs no membership.
|
|
104
|
+
if (ctx.path === '/organization/set-active' && ctx.body?.organizationId === null) {
|
|
105
|
+
return undefined;
|
|
106
|
+
}
|
|
107
|
+
const session = await getSessionFromCtx(ctx);
|
|
108
|
+
// No session is the endpoint's own 401.
|
|
109
|
+
if (type.isNone(session)) {
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
const { adapter, internalAdapter } = ctx.context;
|
|
113
|
+
// Almost nobody is suspended anywhere, so this read comes first and spares
|
|
114
|
+
// the common request the slug and invitation reads.
|
|
115
|
+
const suspendedOrganizationIds = await readSuspendedOrganizationIds({
|
|
116
|
+
adapter,
|
|
117
|
+
userId: session.user.id
|
|
118
|
+
});
|
|
119
|
+
if (suspendedOrganizationIds.length === 0) {
|
|
120
|
+
return undefined;
|
|
121
|
+
}
|
|
122
|
+
const organizationIds = await readTargetOrganizationIds({
|
|
123
|
+
adapter,
|
|
124
|
+
ctx,
|
|
125
|
+
session
|
|
126
|
+
});
|
|
127
|
+
const suspended = organizationIds.some((organizationId)=>suspendedOrganizationIds.includes(organizationId));
|
|
128
|
+
if (!suspended) {
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
131
|
+
// set-active clears the active organization before refusing a non-member,
|
|
132
|
+
// so a session left in an organization the person is suspended in is not
|
|
133
|
+
// stuck there.
|
|
134
|
+
if (ctx.path === '/organization/set-active') {
|
|
135
|
+
await internalAdapter.updateSession(session.session.token, {
|
|
136
|
+
activeOrganizationId: null
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
throw new APIError('FORBIDDEN', {
|
|
140
|
+
message: 'User is not a member of the organization',
|
|
141
|
+
code: 'USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION'
|
|
142
|
+
});
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
export { MEMBERSHIP_FREE_PATHS };
|
|
146
|
+
export default createSuspendedMemberGate;
|
|
@@ -0,0 +1,44 @@
|
|
|
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 { getSessionFromCtx } from 'better-auth/api';
|
|
16
|
+
import { type } from '@lowdefy/helpers';
|
|
17
|
+
import readSuspendedOrganizationIds from './readSuspendedOrganizationIds.js';
|
|
18
|
+
// The engine-tier request hooks.after on /organization/list - the
|
|
19
|
+
// ListOrganizations action. The endpoint lists every organization the caller
|
|
20
|
+
// holds a member row in; an organization they are suspended in is one they do
|
|
21
|
+
// not belong to, so it is left out of the list, as it is left out of the
|
|
22
|
+
// caller stamp (readMemberships). Registered under tenant only: under pinned
|
|
23
|
+
// the endpoint is disabled.
|
|
24
|
+
function createSuspendedOrganizationsFilter() {
|
|
25
|
+
return async function suspendedOrganizationsFilter(ctx) {
|
|
26
|
+
const organizations = ctx.context.returned;
|
|
27
|
+
if (!type.isArray(organizations)) {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
const session = await getSessionFromCtx(ctx);
|
|
31
|
+
if (type.isNone(session)) {
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
const suspendedOrganizationIds = await readSuspendedOrganizationIds({
|
|
35
|
+
adapter: ctx.context.adapter,
|
|
36
|
+
userId: session.user.id
|
|
37
|
+
});
|
|
38
|
+
if (suspendedOrganizationIds.length === 0) {
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
return ctx.json(organizations.filter((organization)=>!suspendedOrganizationIds.includes(organization.id)));
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export default createSuspendedOrganizationsFilter;
|
|
@@ -15,14 +15,15 @@
|
|
|
15
15
|
*/ import { ConfigError, ServiceError } from '@lowdefy/errors';
|
|
16
16
|
import { type } from '@lowdefy/helpers';
|
|
17
17
|
// The auth invariants the engine's own writes rely on but BetterAuth only
|
|
18
|
-
// checks by reading first: one organization per slug (the pinned ensure
|
|
19
|
-
//
|
|
20
|
-
// (user, organization) (the
|
|
21
|
-
// before writing it). Two concurrent writers can both
|
|
22
|
-
// index turns the second write into an error the
|
|
23
|
-
// reading the winner's row. The mint
|
|
24
|
-
//
|
|
25
|
-
//
|
|
18
|
+
// checks by reading first: one organization per slug (the pinned ensure, the
|
|
19
|
+
// tenant signup mint and the CreateOrganization step find or refuse by slug)
|
|
20
|
+
// and one member row per (user, organization) (the mints and the open-signup
|
|
21
|
+
// joins check for the row before writing it). Two concurrent writers can both
|
|
22
|
+
// pass the read; a unique index turns the second write into an error the
|
|
23
|
+
// caller recovers from by reading the winner's row. The signup mint and the
|
|
24
|
+
// CreateOrganization step refuse to run without them (createActiveOrgPolicyHook,
|
|
25
|
+
// provisionOrganization), so a race can never leave two organizations with one
|
|
26
|
+
// slug, or a user holding two owner rows.
|
|
26
27
|
//
|
|
27
28
|
// The indexes are created at startup, by the running server against the
|
|
28
29
|
// database it serves, rather than by a build or CLI step: the build has no
|
|
@@ -30,7 +31,7 @@ import { type } from '@lowdefy/helpers';
|
|
|
30
31
|
// remember, and both would miss a database swapped under a running app. The
|
|
31
32
|
// adapter reads the existing indexes first and only creates missing ones.
|
|
32
33
|
//
|
|
33
|
-
// The
|
|
34
|
+
// The mints await the same call. Once the indexes are in place the result is
|
|
34
35
|
// kept for the life of the process, so a mint costs no database read. When an
|
|
35
36
|
// attempt fails - duplicate rows block the index build, the database user may
|
|
36
37
|
// not create indexes, the database is unreachable - the failure is logged once
|
|
@@ -81,7 +82,7 @@ async function attempt({ auth, logger }) {
|
|
|
81
82
|
service: 'Auth database'
|
|
82
83
|
});
|
|
83
84
|
} else {
|
|
84
|
-
failure = new ConfigError(`The auth database is missing a unique index Lowdefy needs to keep organizations and memberships consistent, and it could not be created: ${error.message} Remove duplicate rows, or create the index with a database user that is allowed to. New organizations are refused until then; the server retries every ${coolDownMs / 1000} seconds while
|
|
85
|
+
failure = new ConfigError(`The auth database is missing a unique index Lowdefy needs to keep organizations and memberships consistent, and it could not be created: ${error.message} Remove duplicate rows, or create the index with a database user that is allowed to. New organizations are refused until then; the server retries every ${coolDownMs / 1000} seconds while a new organization is needed.`, {
|
|
85
86
|
cause: error
|
|
86
87
|
});
|
|
87
88
|
}
|
|
@@ -23,14 +23,16 @@
|
|
|
23
23
|
const bindingByAuth = new WeakMap();
|
|
24
24
|
function registerOrganizationBinding({ auth, database = false, organizations }) {
|
|
25
25
|
bindingByAuth.set(auth, {
|
|
26
|
+
creatorAppRoles: organizations.creatorAppRoles,
|
|
26
27
|
database,
|
|
27
28
|
policy: organizations.policy,
|
|
28
29
|
slug: organizations.org ?? null,
|
|
29
30
|
pinned: null
|
|
30
31
|
});
|
|
31
32
|
}
|
|
32
|
-
// The raw registered entry (policy, slug, database, pinned) -
|
|
33
|
-
// resolvePinnedOrganization to decide whether an ensure is needed
|
|
33
|
+
// The raw registered entry (policy, slug, database, pinned, creatorAppRoles) -
|
|
34
|
+
// used by resolvePinnedOrganization to decide whether an ensure is needed, and
|
|
35
|
+
// by provisionOrganization for the app roles a new organization's owner gets.
|
|
34
36
|
function getRegisteredOrganization({ auth }) {
|
|
35
37
|
if (type.isNone(auth)) {
|
|
36
38
|
return null;
|
|
@@ -0,0 +1,26 @@
|
|
|
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
|
+
// A member row admits its holder only while it is not suspended. member.suspended
|
|
17
|
+
// is how an app takes someone out of one organization without banning their
|
|
18
|
+
// login (which covers every organization in the deployment) and without
|
|
19
|
+
// deleting the row, so the row - and the roles on it - stays readable to the
|
|
20
|
+
// app's own queries. Every check that asks whether a person belongs to an
|
|
21
|
+
// organization asks this, so a suspended member gets the outcome a non-member
|
|
22
|
+
// gets.
|
|
23
|
+
function isActiveMember({ member }) {
|
|
24
|
+
return !type.isNone(member) && member.suspended !== true;
|
|
25
|
+
}
|
|
26
|
+
export default isActiveMember;
|