@lowdefy/api 7.1.0 → 7.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +95 -21
- 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 +163 -92
- 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/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 +43 -6
- package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +7 -2
- package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +41 -189
- package/dist/routes/auth/organizations/createAdmissionGateHook.js +5 -5
- package/dist/routes/auth/organizations/createBeforeCreateInvitationHook.js +62 -0
- package/dist/routes/auth/organizations/createBeforeUpdateMemberRoleHook.js +45 -0
- 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 +12 -5
- 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 +72 -0
- 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/createChannelRegistry.js +13 -15
- package/dist/routes/websocket/createWebSocketConnection.js +5 -8
- 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
|
@@ -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;
|
|
@@ -15,6 +15,8 @@
|
|
|
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
21
|
// session.create wall (which passes a userId), the user.create.before gate and
|
|
20
22
|
// the magic-link send gate (which pass an email, before any user exists).
|
|
@@ -23,8 +25,8 @@ import findPendingInvitation from './findPendingInvitation.js';
|
|
|
23
25
|
// auto-joins under both policies, so the predicate short-circuits to true and
|
|
24
26
|
// leaves those flows untouched.
|
|
25
27
|
//
|
|
26
|
-
// An email is admitted when there is either
|
|
27
|
-
// userId, or by the user resolved from the email) or a pending, unexpired
|
|
28
|
+
// An email is admitted when there is either an unsuspended member row (keyed by
|
|
29
|
+
// the given userId, or by the user resolved from the email) or a pending, unexpired
|
|
28
30
|
// invitation for the email. Under pinned the scope is the pinned org; under
|
|
29
31
|
// tenant it is membership-anywhere or invitation-anywhere, since admission gates
|
|
30
32
|
// deployment-global account existence and there is no target org at signup time.
|
|
@@ -55,6 +57,8 @@ async function isEmailAdmitted({ email, userId, organizations, auth, adapter, in
|
|
|
55
57
|
const user = await internalAdapter.findUserById(userId);
|
|
56
58
|
invitationEmail = user?.email;
|
|
57
59
|
}
|
|
60
|
+
// A suspended row admits nobody, so under tenant every row is read: a
|
|
61
|
+
// person suspended in one organization is still admitted by another.
|
|
58
62
|
if (!type.isNone(memberUserId)) {
|
|
59
63
|
const where = [
|
|
60
64
|
{
|
|
@@ -68,11 +72,14 @@ async function isEmailAdmitted({ email, userId, organizations, auth, adapter, in
|
|
|
68
72
|
value: organization.id
|
|
69
73
|
});
|
|
70
74
|
}
|
|
71
|
-
const
|
|
75
|
+
const members = await adapter.findMany({
|
|
72
76
|
model: 'member',
|
|
73
|
-
where
|
|
77
|
+
where,
|
|
78
|
+
limit: MEMBER_ROWS_LIMIT
|
|
74
79
|
});
|
|
75
|
-
if (member)
|
|
80
|
+
if (members.some((member)=>isActiveMember({
|
|
81
|
+
member
|
|
82
|
+
}))) {
|
|
76
83
|
return true;
|
|
77
84
|
}
|
|
78
85
|
}
|
|
@@ -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',
|