@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
|
@@ -15,23 +15,27 @@
|
|
|
15
15
|
*/ import { type } from '@lowdefy/helpers';
|
|
16
16
|
import ensureOrganization from './ensureOrganization.js';
|
|
17
17
|
import findPendingInvitation from './findPendingInvitation.js';
|
|
18
|
+
import isActiveMember from './isActiveMember.js';
|
|
19
|
+
import MEMBER_ROWS_LIMIT from './memberRowsLimit.js';
|
|
18
20
|
// The one admission predicate, shared by all three enforcement points: the
|
|
19
|
-
// session.create wall (which passes a userId), the user.create.before gate
|
|
20
|
-
//
|
|
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).
|
|
21
25
|
//
|
|
22
26
|
// Admission is restrictive under invite-only (either policy). Open signup
|
|
23
27
|
// auto-joins under both policies, so the predicate short-circuits to true and
|
|
24
28
|
// leaves those flows untouched.
|
|
25
29
|
//
|
|
26
|
-
// An email is admitted when there is either
|
|
27
|
-
// userId, or by the user resolved from the email) or a pending, unexpired
|
|
30
|
+
// An email is admitted when there is either an unsuspended member row (keyed by
|
|
31
|
+
// the given userId, or by the user resolved from the email) or a pending, unexpired
|
|
28
32
|
// invitation for the email. Under pinned the scope is the pinned org; under
|
|
29
33
|
// tenant it is membership-anywhere or invitation-anywhere, since admission gates
|
|
30
34
|
// deployment-global account existence and there is no target org at signup time.
|
|
31
35
|
// The email is lowercased once at entry to match BetterAuth's lowercased-stored
|
|
32
36
|
// user.email and the org plugin's lowercased invitation storage, so no
|
|
33
37
|
// case-variant address is wrongly suppressed or wrongly admitted.
|
|
34
|
-
async function isEmailAdmitted({ email, userId, organizations, auth, adapter, internalAdapter }) {
|
|
38
|
+
async function isEmailAdmitted({ email, user, userId, organizations, auth, adapter, internalAdapter }) {
|
|
35
39
|
if (organizations.signup !== 'invite-only') {
|
|
36
40
|
return true;
|
|
37
41
|
}
|
|
@@ -41,13 +45,15 @@ async function isEmailAdmitted({ email, userId, organizations, auth, adapter, in
|
|
|
41
45
|
slug: organizations.org
|
|
42
46
|
}) : undefined;
|
|
43
47
|
const normalizedEmail = type.isString(email) ? email.toLowerCase() : undefined;
|
|
44
|
-
// The member row is keyed by user id. The wall holds the session userId
|
|
45
|
-
//
|
|
46
|
-
// any) from it.
|
|
47
|
-
//
|
|
48
|
-
|
|
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;
|
|
49
55
|
let invitationEmail = normalizedEmail;
|
|
50
|
-
if (type.isNone(memberUserId) && !type.isNone(normalizedEmail)) {
|
|
56
|
+
if (type.isNone(memberUserId) && type.isUndefined(user) && !type.isNone(normalizedEmail)) {
|
|
51
57
|
const found = await internalAdapter.findUserByEmail(normalizedEmail);
|
|
52
58
|
memberUserId = found?.user?.id;
|
|
53
59
|
}
|
|
@@ -55,6 +61,8 @@ async function isEmailAdmitted({ email, userId, organizations, auth, adapter, in
|
|
|
55
61
|
const user = await internalAdapter.findUserById(userId);
|
|
56
62
|
invitationEmail = user?.email;
|
|
57
63
|
}
|
|
64
|
+
// A suspended row admits nobody, so under tenant every row is read: a
|
|
65
|
+
// person suspended in one organization is still admitted by another.
|
|
58
66
|
if (!type.isNone(memberUserId)) {
|
|
59
67
|
const where = [
|
|
60
68
|
{
|
|
@@ -68,11 +76,14 @@ async function isEmailAdmitted({ email, userId, organizations, auth, adapter, in
|
|
|
68
76
|
value: organization.id
|
|
69
77
|
});
|
|
70
78
|
}
|
|
71
|
-
const
|
|
79
|
+
const members = await adapter.findMany({
|
|
72
80
|
model: 'member',
|
|
73
|
-
where
|
|
81
|
+
where,
|
|
82
|
+
limit: MEMBER_ROWS_LIMIT
|
|
74
83
|
});
|
|
75
|
-
if (member)
|
|
84
|
+
if (members.some((member)=>isActiveMember({
|
|
85
|
+
member
|
|
86
|
+
}))) {
|
|
76
87
|
return true;
|
|
77
88
|
}
|
|
78
89
|
}
|
|
@@ -0,0 +1,19 @@
|
|
|
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
|
+
*/ // Reading every member row a person holds: the adapter returns at most a
|
|
16
|
+
// default page of rows when asked for none, so ask for more than any one person
|
|
17
|
+
// holds and the read is one round trip in practice.
|
|
18
|
+
const MEMBER_ROWS_LIMIT = 1000;
|
|
19
|
+
export default MEMBER_ROWS_LIMIT;
|
|
@@ -0,0 +1,258 @@
|
|
|
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
|
+
import isActiveMember from './isActiveMember.js';
|
|
17
|
+
// How long a minted organization's owner row may take to follow it. A mint
|
|
18
|
+
// writes both rows within one request, so a marker older than this is left
|
|
19
|
+
// over from a mint that failed between its writes.
|
|
20
|
+
const mintPendingMs = 10 * 60 * 1000;
|
|
21
|
+
// An organization and its creator's owner row, written by the engine itself:
|
|
22
|
+
// the tenant signup mint (createActiveOrgPolicyHook) and the CreateOrganization
|
|
23
|
+
// step (provisionOrganization) both write them here. Both go through the
|
|
24
|
+
// adapter rather than the org plugin's createOrganization endpoint, so none of
|
|
25
|
+
// that endpoint's options (creatorRole, organizationLimit, teams) or
|
|
26
|
+
// organizationHooks apply - buildOrganizationPlugin declares none of them, and
|
|
27
|
+
// its tests hold it to that.
|
|
28
|
+
//
|
|
29
|
+
// There are no transactions to lean on (the adapter supports standalone
|
|
30
|
+
// MongoDB), so the mint is two writes made safe by unique indexes
|
|
31
|
+
// (ensureAuthIndexes, which every caller awaits first) and a marker:
|
|
32
|
+
//
|
|
33
|
+
// - The organization row is written with mintPending: true and the creator's
|
|
34
|
+
// id in mintCreatorId. Only a marked organization whose mint is still in
|
|
35
|
+
// progress (isMintInProgress) is ever joined as its owner here: one minted
|
|
36
|
+
// for this creator moments ago whose owner row was never written - a mint
|
|
37
|
+
// that failed between its two writes, or one a concurrent run for the same
|
|
38
|
+
// creator (a double submit, two tabs) is finishing right now. The marker is
|
|
39
|
+
// cleared once the owner row exists, so an organization everyone later left -
|
|
40
|
+
// with its data and pending invitations - is never handed back.
|
|
41
|
+
// - Two runs creating the same slug: the unique slug index rejects the second,
|
|
42
|
+
// which reads the winner's row. It joins that row only if the winner's mint
|
|
43
|
+
// is for the same creator and still in progress; another creator's mint is
|
|
44
|
+
// left alone.
|
|
45
|
+
// - Two runs writing the owner row, in any order around each other's writes:
|
|
46
|
+
// the unique (user, organization) index rejects the second, which reads the
|
|
47
|
+
// winner's row. The member row is always written before the marker is
|
|
48
|
+
// cleared, so a run that sees the marker cleared finds the member row.
|
|
49
|
+
async function findOrganization({ adapter, slug }) {
|
|
50
|
+
return adapter.findOne({
|
|
51
|
+
model: 'organization',
|
|
52
|
+
where: [
|
|
53
|
+
{
|
|
54
|
+
field: 'slug',
|
|
55
|
+
value: slug
|
|
56
|
+
}
|
|
57
|
+
]
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
async function findMember({ adapter, userId, organizationId }) {
|
|
61
|
+
return adapter.findOne({
|
|
62
|
+
model: 'member',
|
|
63
|
+
where: [
|
|
64
|
+
{
|
|
65
|
+
field: 'userId',
|
|
66
|
+
value: userId
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
field: 'organizationId',
|
|
70
|
+
value: organizationId
|
|
71
|
+
}
|
|
72
|
+
]
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
async function findOrCreateOrganization({ adapter, data, userId }) {
|
|
76
|
+
const existing = await findOrganization({
|
|
77
|
+
adapter,
|
|
78
|
+
slug: data.slug
|
|
79
|
+
});
|
|
80
|
+
if (existing) {
|
|
81
|
+
return existing;
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
return await adapter.create({
|
|
85
|
+
model: 'organization',
|
|
86
|
+
data: {
|
|
87
|
+
...data,
|
|
88
|
+
mintPending: true,
|
|
89
|
+
mintCreatorId: userId,
|
|
90
|
+
createdAt: new Date()
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
} catch (error) {
|
|
94
|
+
const winner = await findOrganization({
|
|
95
|
+
adapter,
|
|
96
|
+
slug: data.slug
|
|
97
|
+
});
|
|
98
|
+
if (!winner) {
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
return winner;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async function joinAsOwner({ adapter, creatorAppRoles, userId, organizationId }) {
|
|
105
|
+
const data = {
|
|
106
|
+
userId,
|
|
107
|
+
organizationId,
|
|
108
|
+
role: 'owner',
|
|
109
|
+
createdAt: new Date()
|
|
110
|
+
};
|
|
111
|
+
// An empty list leaves the row without an appRoles field, as it was before
|
|
112
|
+
// creatorAppRoles existed. A copy, so a caller that mutates the returned row
|
|
113
|
+
// cannot change the roles every later organization's owner gets.
|
|
114
|
+
if (creatorAppRoles.length > 0) {
|
|
115
|
+
data.appRoles = [
|
|
116
|
+
...creatorAppRoles
|
|
117
|
+
];
|
|
118
|
+
}
|
|
119
|
+
try {
|
|
120
|
+
return await adapter.create({
|
|
121
|
+
model: 'member',
|
|
122
|
+
data
|
|
123
|
+
});
|
|
124
|
+
} catch (error) {
|
|
125
|
+
const winner = await findMember({
|
|
126
|
+
adapter,
|
|
127
|
+
userId,
|
|
128
|
+
organizationId
|
|
129
|
+
});
|
|
130
|
+
if (type.isNone(winner)) {
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
return winner;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
async function clearMintPending({ adapter, organization }) {
|
|
137
|
+
if (organization.mintPending !== true) {
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
await adapter.update({
|
|
141
|
+
model: 'organization',
|
|
142
|
+
where: [
|
|
143
|
+
{
|
|
144
|
+
field: 'id',
|
|
145
|
+
value: organization.id
|
|
146
|
+
}
|
|
147
|
+
],
|
|
148
|
+
update: {
|
|
149
|
+
mintPending: false
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
// A marker naming another creator belongs to that creator's mint, finished or
|
|
154
|
+
// not, so it is neither joined nor cleared here. A marker with no
|
|
155
|
+
// mintCreatorId was written before the field existed, by the signup mint,
|
|
156
|
+
// whose slug already names its creator.
|
|
157
|
+
function isOtherCreatorsMint({ organization, userId }) {
|
|
158
|
+
return organization.mintPending === true && !type.isNone(organization.mintCreatorId) && organization.mintCreatorId !== userId;
|
|
159
|
+
}
|
|
160
|
+
// A marked organization is joined as owner only while its mint is in
|
|
161
|
+
// progress: minted within mintPendingMs and with no member other than the
|
|
162
|
+
// creator. A marker older than that, or on an organization other people belong
|
|
163
|
+
// to, is left over from a mint that wrote the owner row and failed before
|
|
164
|
+
// clearing it - the organization has had an owner, so it is never handed back.
|
|
165
|
+
async function isMintInProgress({ adapter, organization, userId }) {
|
|
166
|
+
if (organization.mintPending !== true) {
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
if (Date.now() - new Date(organization.createdAt).getTime() > mintPendingMs) {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
const otherMembers = await adapter.count({
|
|
173
|
+
model: 'member',
|
|
174
|
+
where: [
|
|
175
|
+
{
|
|
176
|
+
field: 'organizationId',
|
|
177
|
+
value: organization.id
|
|
178
|
+
},
|
|
179
|
+
{
|
|
180
|
+
field: 'userId',
|
|
181
|
+
value: userId,
|
|
182
|
+
operator: 'ne'
|
|
183
|
+
}
|
|
184
|
+
]
|
|
185
|
+
});
|
|
186
|
+
return otherMembers === 0;
|
|
187
|
+
}
|
|
188
|
+
// Returns { organization, member } once userId owns the organization at
|
|
189
|
+
// organization.slug, or null when that slug belongs to an organization this
|
|
190
|
+
// mint may not take. A stale marker found on the way is cleared.
|
|
191
|
+
//
|
|
192
|
+
// keepMembership: an unmarked organization the creator already belongs to,
|
|
193
|
+
// unsuspended, counts as theirs. The signup mint needs it - a concurrent session of the
|
|
194
|
+
// same user may have finished the mint between that user's membership read and
|
|
195
|
+
// this call. The CreateOrganization step leaves it off: an organization that
|
|
196
|
+
// already exists is refused, whoever belongs to it.
|
|
197
|
+
async function mintOrganization({ adapter, creatorAppRoles, keepMembership = false, organization: data, userId }) {
|
|
198
|
+
const organization = await findOrCreateOrganization({
|
|
199
|
+
adapter,
|
|
200
|
+
data,
|
|
201
|
+
userId
|
|
202
|
+
});
|
|
203
|
+
if (isOtherCreatorsMint({
|
|
204
|
+
organization,
|
|
205
|
+
userId
|
|
206
|
+
})) {
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
const member = await findMember({
|
|
210
|
+
adapter,
|
|
211
|
+
userId,
|
|
212
|
+
organizationId: organization.id
|
|
213
|
+
});
|
|
214
|
+
// A membership the creator is suspended in is not theirs to sign in to, so
|
|
215
|
+
// the signup mint moves on to the next slug, as for an organization they
|
|
216
|
+
// left - whether or not the organization is still marked mid-mint.
|
|
217
|
+
if (!type.isNone(member) && !isActiveMember({
|
|
218
|
+
member
|
|
219
|
+
})) {
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
if (!type.isNone(member) && (keepMembership || organization.mintPending === true)) {
|
|
223
|
+
await clearMintPending({
|
|
224
|
+
adapter,
|
|
225
|
+
organization
|
|
226
|
+
});
|
|
227
|
+
return {
|
|
228
|
+
organization,
|
|
229
|
+
member
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
if (await isMintInProgress({
|
|
233
|
+
adapter,
|
|
234
|
+
organization,
|
|
235
|
+
userId
|
|
236
|
+
})) {
|
|
237
|
+
const owner = await joinAsOwner({
|
|
238
|
+
adapter,
|
|
239
|
+
creatorAppRoles,
|
|
240
|
+
userId,
|
|
241
|
+
organizationId: organization.id
|
|
242
|
+
});
|
|
243
|
+
await clearMintPending({
|
|
244
|
+
adapter,
|
|
245
|
+
organization
|
|
246
|
+
});
|
|
247
|
+
return {
|
|
248
|
+
organization,
|
|
249
|
+
member: owner
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
await clearMintPending({
|
|
253
|
+
adapter,
|
|
254
|
+
organization
|
|
255
|
+
});
|
|
256
|
+
return null;
|
|
257
|
+
}
|
|
258
|
+
export default mintOrganization;
|
|
@@ -20,8 +20,12 @@ import { adminAc, defaultStatements, memberAc, ownerAc } from 'better-auth/plugi
|
|
|
20
20
|
// authority. The resource names are the admin design's, kept verbatim so its
|
|
21
21
|
// catalog table stays the contract.
|
|
22
22
|
const ADDED = {
|
|
23
|
+
// suspend is its own action rather than update or delete: suspending takes a
|
|
24
|
+
// person out of the organization without removing the row, and a narrower
|
|
25
|
+
// role may be granted one without the other.
|
|
23
26
|
member: [
|
|
24
|
-
'list'
|
|
27
|
+
'list',
|
|
28
|
+
'suspend'
|
|
25
29
|
],
|
|
26
30
|
user: [
|
|
27
31
|
'ban',
|
|
@@ -0,0 +1,117 @@
|
|
|
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
|
+
import ensureAuthIndexes from './ensureAuthIndexes.js';
|
|
17
|
+
import { getRegisteredOrganization } from './getOrganizationBinding.js';
|
|
18
|
+
import mintOrganization from './mintOrganization.js';
|
|
19
|
+
async function findOrganization({ adapter, slug }) {
|
|
20
|
+
return adapter.findOne({
|
|
21
|
+
model: 'organization',
|
|
22
|
+
where: [
|
|
23
|
+
{
|
|
24
|
+
field: 'slug',
|
|
25
|
+
value: slug
|
|
26
|
+
}
|
|
27
|
+
]
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
// A provisioned organization has no creator - membership arrives by
|
|
31
|
+
// invitation - so it is one write. A slug that is taken, or taken by a racing
|
|
32
|
+
// write the unique slug index rejects, is refused.
|
|
33
|
+
async function createCreatorlessOrganization({ adapter, data }) {
|
|
34
|
+
if (!type.isNone(await findOrganization({
|
|
35
|
+
adapter,
|
|
36
|
+
slug: data.slug
|
|
37
|
+
}))) {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
return await adapter.create({
|
|
42
|
+
model: 'organization',
|
|
43
|
+
data: {
|
|
44
|
+
...data,
|
|
45
|
+
createdAt: new Date()
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (!type.isNone(await findOrganization({
|
|
50
|
+
adapter,
|
|
51
|
+
slug: data.slug
|
|
52
|
+
}))) {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
// The CreateOrganization step's write, handed to every auth step by
|
|
59
|
+
// handleAuthStep. With a creator, the organization and its owner row holding
|
|
60
|
+
// auth.organizations.creatorAppRoles are written by mintOrganization, the same
|
|
61
|
+
// way the tenant signup mint writes them, so a run that fails between the two
|
|
62
|
+
// writes is finished by the creator's next run for the same slug.
|
|
63
|
+
//
|
|
64
|
+
// Returns { organization, member } - member is null without a creator - or
|
|
65
|
+
// null when the slug belongs to another organization. organization is shaped
|
|
66
|
+
// the way the org plugin's endpoints return it: without the server-only marker
|
|
67
|
+
// fields, and with metadata parsed from the JSON string the row stores.
|
|
68
|
+
async function provisionOrganization({ auth, logger, organization: fields, userId }) {
|
|
69
|
+
// A refused slug is only a guarantee behind the unique slug index - a read
|
|
70
|
+
// cannot see a racing write - so nothing is written without it.
|
|
71
|
+
await ensureAuthIndexes({
|
|
72
|
+
auth,
|
|
73
|
+
logger
|
|
74
|
+
});
|
|
75
|
+
const { adapter } = await auth.$context;
|
|
76
|
+
const data = {
|
|
77
|
+
...fields
|
|
78
|
+
};
|
|
79
|
+
if (!type.isNone(fields.metadata)) {
|
|
80
|
+
data.metadata = JSON.stringify(fields.metadata);
|
|
81
|
+
}
|
|
82
|
+
let organization;
|
|
83
|
+
let member = null;
|
|
84
|
+
if (type.isNone(userId)) {
|
|
85
|
+
organization = await createCreatorlessOrganization({
|
|
86
|
+
adapter,
|
|
87
|
+
data
|
|
88
|
+
});
|
|
89
|
+
} else {
|
|
90
|
+
const minted = await mintOrganization({
|
|
91
|
+
adapter,
|
|
92
|
+
creatorAppRoles: getRegisteredOrganization({
|
|
93
|
+
auth
|
|
94
|
+
}).creatorAppRoles,
|
|
95
|
+
organization: data,
|
|
96
|
+
userId
|
|
97
|
+
});
|
|
98
|
+
organization = minted?.organization ?? null;
|
|
99
|
+
member = minted?.member ?? null;
|
|
100
|
+
}
|
|
101
|
+
if (type.isNone(organization)) {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
const result = {
|
|
105
|
+
...organization
|
|
106
|
+
};
|
|
107
|
+
delete result.mintPending;
|
|
108
|
+
delete result.mintCreatorId;
|
|
109
|
+
if (type.isString(result.metadata)) {
|
|
110
|
+
result.metadata = JSON.parse(result.metadata);
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
organization: result,
|
|
114
|
+
member
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
export default provisionOrganization;
|
|
@@ -0,0 +1,36 @@
|
|
|
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 MEMBER_ROWS_LIMIT from './memberRowsLimit.js';
|
|
16
|
+
// The organizations a person is suspended in. Only suspended rows are read - a
|
|
17
|
+
// row with no suspended field never equals true, on any adapter - so the
|
|
18
|
+
// common answer, none, reads no rows.
|
|
19
|
+
async function readSuspendedOrganizationIds({ adapter, userId }) {
|
|
20
|
+
const rows = await adapter.findMany({
|
|
21
|
+
model: 'member',
|
|
22
|
+
where: [
|
|
23
|
+
{
|
|
24
|
+
field: 'userId',
|
|
25
|
+
value: userId
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
field: 'suspended',
|
|
29
|
+
value: true
|
|
30
|
+
}
|
|
31
|
+
],
|
|
32
|
+
limit: MEMBER_ROWS_LIMIT
|
|
33
|
+
});
|
|
34
|
+
return rows.map((row)=>row.organizationId);
|
|
35
|
+
}
|
|
36
|
+
export default readSuspendedOrganizationIds;
|
|
@@ -16,8 +16,14 @@
|
|
|
16
16
|
import { type } from '@lowdefy/helpers';
|
|
17
17
|
import createAcceptExistingMemberHook from '../organizations/createAcceptExistingMemberHook.js';
|
|
18
18
|
import createEmailSendGate from '../organizations/createEmailSendGate.js';
|
|
19
|
+
import createEmailCodeHolderGate from './createEmailCodeHolderGate.js';
|
|
20
|
+
import createEmailSendLimit from './createEmailSendLimit.js';
|
|
19
21
|
import createExpiredInvitationGate from '../organizations/createExpiredInvitationGate.js';
|
|
22
|
+
import createSuspendedMemberGate, { MEMBERSHIP_FREE_PATHS } from '../organizations/createSuspendedMemberGate.js';
|
|
23
|
+
import createSuspendedOrganizationsFilter from '../organizations/createSuspendedOrganizationsFilter.js';
|
|
24
|
+
import createKnownDeviceHook from '../mobile/createKnownDeviceHook.js';
|
|
20
25
|
import createOauthPostLoginHook from './createOauthPostLoginHook.js';
|
|
26
|
+
import createSignInRefusedRedirectHook from './createSignInRefusedRedirectHook.js';
|
|
21
27
|
import createTwoFactorChallengeHook from './createTwoFactorChallengeHook.js';
|
|
22
28
|
import dispatchRequestHooks from './dispatchRequestHooks.js';
|
|
23
29
|
import redirectToChallenge from './redirectToChallenge.js';
|
|
@@ -33,7 +39,7 @@ import resolveTwoFactorPageUrl from './resolveTwoFactorPageUrl.js';
|
|
|
33
39
|
// for every path. Whether a registration is added stays conditional on config,
|
|
34
40
|
// and those conditions live here so there is one place to read what the engine
|
|
35
41
|
// hooks into.
|
|
36
|
-
function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }) {
|
|
42
|
+
function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth, logger }) {
|
|
37
43
|
const before = [];
|
|
38
44
|
const after = [];
|
|
39
45
|
// The effective trust-device lifetime, mirroring the value passed to the
|
|
@@ -50,7 +56,9 @@ function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }
|
|
|
50
56
|
before.push({
|
|
51
57
|
id: 'acceptExistingMember',
|
|
52
58
|
matches: (path)=>path === '/organization/accept-invitation',
|
|
53
|
-
handler: createAcceptExistingMemberHook(
|
|
59
|
+
handler: createAcceptExistingMemberHook({
|
|
60
|
+
logger
|
|
61
|
+
})
|
|
54
62
|
});
|
|
55
63
|
if (authConfig.magicLink?.enabled === true) {
|
|
56
64
|
before.push({
|
|
@@ -58,6 +66,7 @@ function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }
|
|
|
58
66
|
matches: (path)=>path === '/sign-in/magic-link',
|
|
59
67
|
handler: createEmailSendGate({
|
|
60
68
|
getAuth,
|
|
69
|
+
logger,
|
|
61
70
|
organizations: authConfig.organizations,
|
|
62
71
|
// The magic-link route's own success body.
|
|
63
72
|
successBody: {
|
|
@@ -72,11 +81,36 @@ function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }
|
|
|
72
81
|
// the code is minted inside sendMagicLink, which only runs after the
|
|
73
82
|
// magic-link gate has already admitted the address.
|
|
74
83
|
if (authConfig.emailOTP?.enabled === true) {
|
|
84
|
+
// Apps with phones sign in by email code by default, so codes are capped at
|
|
85
|
+
// 5 in 15 minutes, per phone and per address (createEmailSendLimit). The
|
|
86
|
+
// password reset code is another unauthenticated send to the same address.
|
|
87
|
+
// Registered ahead of the gate.
|
|
88
|
+
if (!type.isNone(authConfig.mobile)) {
|
|
89
|
+
before.push({
|
|
90
|
+
id: 'emailOtpSendLimit',
|
|
91
|
+
matches: (path)=>path === '/email-otp/send-verification-otp' || path === '/forget-password/email-otp',
|
|
92
|
+
handler: createEmailSendLimit({
|
|
93
|
+
codeSeconds: authConfig.emailOTP.expiresIn,
|
|
94
|
+
getAuth,
|
|
95
|
+
max: 5,
|
|
96
|
+
windowSeconds: 900
|
|
97
|
+
})
|
|
98
|
+
});
|
|
99
|
+
// Only the known phone holding the live code may try it (holdEmailCode).
|
|
100
|
+
before.push({
|
|
101
|
+
id: 'emailOtpCodeHolderGate',
|
|
102
|
+
matches: (path)=>path === '/sign-in/email-otp',
|
|
103
|
+
handler: createEmailCodeHolderGate({
|
|
104
|
+
getAuth
|
|
105
|
+
})
|
|
106
|
+
});
|
|
107
|
+
}
|
|
75
108
|
before.push({
|
|
76
109
|
id: 'emailOtpSendGate',
|
|
77
110
|
matches: (path)=>path === '/email-otp/send-verification-otp',
|
|
78
111
|
handler: createEmailSendGate({
|
|
79
112
|
getAuth,
|
|
113
|
+
logger,
|
|
80
114
|
organizations: authConfig.organizations,
|
|
81
115
|
// The OTP send route's own success body - a different shape from the
|
|
82
116
|
// magic-link route's, and the suppressed response has to match it.
|
|
@@ -96,6 +130,21 @@ function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }
|
|
|
96
130
|
getAuth
|
|
97
131
|
})
|
|
98
132
|
});
|
|
133
|
+
// A member suspended in an organization is a non-member to the organization
|
|
134
|
+
// plugin's own client endpoints too. Tenant only: under pinned every one of
|
|
135
|
+
// these paths is disabled.
|
|
136
|
+
if (authConfig.organizations?.policy === 'tenant') {
|
|
137
|
+
before.push({
|
|
138
|
+
id: 'suspendedMemberGate',
|
|
139
|
+
matches: (path)=>path.startsWith('/organization/') && !MEMBERSHIP_FREE_PATHS.includes(path),
|
|
140
|
+
handler: createSuspendedMemberGate()
|
|
141
|
+
});
|
|
142
|
+
after.push({
|
|
143
|
+
id: 'suspendedOrganizationsFilter',
|
|
144
|
+
matches: (path)=>path === '/organization/list',
|
|
145
|
+
handler: createSuspendedOrganizationsFilter()
|
|
146
|
+
});
|
|
147
|
+
}
|
|
99
148
|
// The post-login organization choice (buildOauthPostLogin): stamps the
|
|
100
149
|
// request's cached session when /oauth2/continue confirms the choice, so the
|
|
101
150
|
// authorize call it re-enters with does not send the member back to the
|
|
@@ -107,6 +156,22 @@ function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }
|
|
|
107
156
|
handler: createOauthPostLoginHook()
|
|
108
157
|
});
|
|
109
158
|
}
|
|
159
|
+
// A sign-in refused at session creation (banned, no membership, an app hook's
|
|
160
|
+
// :reject) answers the browser with a redirect to the error page rather than
|
|
161
|
+
// raw JSON.
|
|
162
|
+
// Registered ahead of the magic-link two-factor challenge, which has no
|
|
163
|
+
// session to act on when the refusal fires. /verify-email and
|
|
164
|
+
// /email-otp/verify-email need no counterpart: they create a session only with
|
|
165
|
+
// emailVerification.autoSignInAfterVerification or user.changeEmail, and
|
|
166
|
+
// getBetterAuthConfig sets neither, so a verification link cannot be refused
|
|
167
|
+
// this way. Setting either one would open the same gap there.
|
|
168
|
+
if (authConfig.magicLink?.enabled === true) {
|
|
169
|
+
after.push({
|
|
170
|
+
id: 'magicLinkSignInRefused',
|
|
171
|
+
matches: (path)=>path === '/magic-link/verify',
|
|
172
|
+
handler: createSignInRefusedRedirectHook()
|
|
173
|
+
});
|
|
174
|
+
}
|
|
110
175
|
const twoFactorPageUrl = resolveTwoFactorPageUrl({
|
|
111
176
|
authConfig,
|
|
112
177
|
basePath,
|
|
@@ -274,6 +339,17 @@ function buildRequestHooks({ authConfig, basePath = '', baseUrlOrigin, getAuth }
|
|
|
274
339
|
})
|
|
275
340
|
}));
|
|
276
341
|
}
|
|
342
|
+
// After the two-factor challenge, which answers first when a second factor is
|
|
343
|
+
// needed: only a sign-in that kept its session records a known phone.
|
|
344
|
+
if (!type.isNone(authConfig.mobile) && authConfig.emailOTP?.enabled === true) {
|
|
345
|
+
after.push({
|
|
346
|
+
id: 'emailOtpKnownDevice',
|
|
347
|
+
matches: (path)=>path === '/sign-in/email-otp',
|
|
348
|
+
handler: createKnownDeviceHook({
|
|
349
|
+
getAuth
|
|
350
|
+
})
|
|
351
|
+
});
|
|
352
|
+
}
|
|
277
353
|
return {
|
|
278
354
|
before: createAuthMiddleware(async (ctx)=>dispatchRequestHooks({
|
|
279
355
|
ctx,
|