@cossackframework/cms 0.9.2 → 0.9.4
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/agent-docs.json +8 -8
- package/app/cossack-recipe.json +12 -8
- package/app/src/auth-events.ts +33 -0
- package/app/src/auth-input.ts +3 -0
- package/app/src/auth-options.ts +39 -7
- package/app/src/auth.ts +1309 -641
- package/app/src/avatars.ts +13 -0
- package/app/src/brand.ts +24 -2
- package/app/src/cms/actor.ts +13 -0
- package/app/src/cms/collab/room.ts +1 -1
- package/app/src/cms/content-api.ts +2 -1
- package/app/src/cms/content.ts +3 -2
- package/app/src/cms/dev-mail.ts +77 -0
- package/app/src/cms/index.ts +37 -10
- package/app/src/cms/maintenance.ts +1 -6
- package/app/src/cms/manage.ts +17 -14
- package/app/src/cms/middleware.ts +58 -18
- package/app/src/cms/network-accounts.ts +110 -0
- package/app/src/cms/notes-announce.ts +1 -1
- package/app/src/cms/people.ts +177 -0
- package/app/src/cms/recovery.ts +9 -14
- package/app/src/cms/request-calls.ts +56 -0
- package/app/src/cms/settings-form.ts +23 -6
- package/app/src/cms/settings-network.ts +8 -4
- package/app/src/cms/settings-search.ts +1 -0
- package/app/src/cms/site-editing.ts +3 -2
- package/app/src/cms/site-registration.ts +64 -0
- package/app/src/cms/site.ts +30 -19
- package/app/src/cms/sites.ts +182 -0
- package/app/src/dashboard/access.ts +3 -2
- package/app/src/dashboard/modules/users.ts +1 -0
- package/app/src/lib/permissions.ts +24 -0
- package/app/src/lib/uuid.ts +6 -0
- package/app/src/mail.ts +15 -0
- package/app/src/middlewares/auth.ts +6 -2
- package/app/src/middlewares/tenant.ts +108 -0
- package/app/src/pages/(site)/[...path]/index.ts +1 -1
- package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +1 -1
- package/app/src/pages/api/cms/dev/mail.ts +19 -0
- package/app/src/pages/api/cms/forms/[slug]/index.ts +1 -1
- package/app/src/pages/api/cms/users/[id]/meta.ts +2 -1
- package/app/src/pages/auth/login/index.ts +1 -1
- package/app/src/pages/auth/magic/index.ts +1 -1
- package/app/src/pages/auth/recovery.ts +20 -0
- package/app/src/pages/auth/register-site/index.ts +146 -0
- package/app/src/pages/auth/setup/index.ts +8 -3
- package/app/src/pages/auth/tenant/callback.ts +23 -0
- package/app/src/pages/auth/tenant/redirect.ts +91 -0
- package/app/src/pages/auth/verify/index.ts +3 -7
- package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +5 -5
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/network/index.ts +4 -2
- package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +16 -13
- package/app/src/pages/dashboard/(cms)/network/sites/index.ts +4 -2
- package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +29 -10
- package/app/src/pages/dashboard/(cms)/network/users/index.ts +8 -7
- package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +2 -1
- package/app/src/pages/dashboard/(cms)/registrations/index.ts +5 -4
- package/app/src/pages/dashboard/(cms)/tools/health/index.ts +4 -1
- package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +2 -1
- package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +1 -1
- package/app/src/pages/dashboard/index.ts +3 -2
- package/app/src/pages/dashboard/roles/index.ts +2 -2
- package/app/src/pages/dashboard/users/registrations/index.ts +66 -0
- package/app/src/services/api-tokens.ts +86 -0
- package/app/src/services/rbac.ts +26 -15
- package/app/src/services/roles.ts +125 -35
- package/app/src/services/security.ts +384 -0
- package/app/src/services/tenants.ts +447 -0
- package/app/src/services/users.ts +241 -97
- package/app/src/tenants.ts +219 -0
- package/package.json +48 -12
- package/src/block-references.ts +3 -3
- package/src/collections.ts +3 -1
- package/src/forms.ts +4 -2
- package/src/hooks.ts +19 -1
- package/src/index.ts +4 -4
- package/src/isolate-core.ts +1 -1
- package/src/isolation.ts +1 -0
- package/src/manifest.ts +43 -2
- package/src/permissions.ts +13 -7
- package/src/resource.ts +85 -2
- package/src/server/attempts.ts +64 -0
- package/src/server/automations.ts +2 -2
- package/src/server/batch.ts +106 -0
- package/src/server/budget.ts +17 -0
- package/src/server/field-values.ts +207 -0
- package/src/server/forms.ts +3 -3
- package/src/server/host-schema.ts +55 -7
- package/src/server/host.ts +213 -85
- package/src/server/index.ts +9 -14
- package/src/server/isolation.ts +10 -0
- package/src/server/network.ts +129 -44
- package/src/server/outbox.ts +2 -2
- package/src/server/people.ts +191 -0
- package/src/server/reconcile.ts +5 -5
- package/src/server/repository.ts +243 -84
- package/src/server/shared-read.ts +34 -0
- package/src/server/site-export.ts +23 -13
- package/src/server/site-import.ts +12 -33
- package/src/server/site-settings.ts +9 -3
- package/src/server/sites.ts +117 -187
- package/src/server/stores.ts +3 -300
- package/src/server/taxonomies.ts +64 -13
- package/src/server/users.ts +151 -498
- package/src/settings-controls.ts +8 -4
- package/src/settings.ts +26 -3
- package/src/storage/cloudflare.ts +2 -0
- package/src/storage/index.ts +6 -0
- package/src/theme.ts +2 -2
- package/src/version.ts +1 -1
- package/app/src/cms/handoff.ts +0 -202
- package/src/server/accounts.ts +0 -418
- package/src/server/api-tokens.ts +0 -91
- package/src/server/auth.ts +0 -89
- package/src/server/handoffs.ts +0 -107
- package/src/server/security.ts +0 -391
|
@@ -1,9 +1,17 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
1
|
+
import { In, sql } from '@cossackframework/database';
|
|
2
|
+
import { ClientVisibleError } from '@cossackframework/core';
|
|
3
|
+
import { uuidv7 } from '../lib/uuid';
|
|
4
|
+
import { canInvite, hashPassword, sendInvitation, type PublicUser } from '../auth';
|
|
5
|
+
import { accounts, currentTenant } from '../tenants';
|
|
6
|
+
import { forgetMemberships, joinCurrentTenant, leaveCurrentTenant, requireAnotherNetworkAdmin, tenantOwnAccount } from './tenants';
|
|
7
|
+
import * as security from './security';
|
|
8
|
+
import * as apiTokens from './api-tokens';
|
|
9
|
+
import { defaultRole } from './roles';
|
|
10
|
+
import { authOptions } from '../auth-options';
|
|
11
|
+
import { User } from '@/models/User';
|
|
12
|
+
import { UserRole } from '@/models/UserRole';
|
|
13
|
+
import { Role } from '@/models/Role';
|
|
14
|
+
import type { RoleAssignment } from '@/models/User';
|
|
7
15
|
|
|
8
16
|
export interface UserSummary {
|
|
9
17
|
id: string;
|
|
@@ -11,17 +19,18 @@ export interface UserSummary {
|
|
|
11
19
|
name: string;
|
|
12
20
|
avatar: string | null;
|
|
13
21
|
createdAt: string;
|
|
14
|
-
/**
|
|
22
|
+
/** Start of the user's newest sign-in session; null when none is left. */
|
|
15
23
|
lastSignedInAt: string | null;
|
|
16
24
|
roles: RoleAssignment[];
|
|
17
|
-
/**
|
|
25
|
+
/** A label beside the name in lists, such as the kind of account. */
|
|
18
26
|
badge?: string;
|
|
19
27
|
}
|
|
20
28
|
|
|
21
29
|
export interface UserDetail extends UserSummary {
|
|
22
|
-
/**
|
|
23
|
-
|
|
24
|
-
|
|
30
|
+
/**
|
|
31
|
+
* Why only the user can change their profile, password and sign-in methods here, when others
|
|
32
|
+
* manage them elsewhere; this site still manages the user's roles.
|
|
33
|
+
*/
|
|
25
34
|
lockedProfile?: string;
|
|
26
35
|
}
|
|
27
36
|
|
|
@@ -43,10 +52,10 @@ export interface CreateUserInput {
|
|
|
43
52
|
email: string;
|
|
44
53
|
/** Required unless `invite` is set. */
|
|
45
54
|
password?: string;
|
|
46
|
-
/**
|
|
55
|
+
/** Email a link to set the password instead of setting one here. It needs an email sender and APP_URL. */
|
|
47
56
|
invite?: boolean;
|
|
48
57
|
name?: string;
|
|
49
|
-
/** Roles chosen by someone who may assign them; otherwise
|
|
58
|
+
/** Roles chosen by someone who may assign them; otherwise none. */
|
|
50
59
|
roleIds?: string[];
|
|
51
60
|
}
|
|
52
61
|
|
|
@@ -56,118 +65,253 @@ export interface UpdateUserInput {
|
|
|
56
65
|
avatar?: string | null;
|
|
57
66
|
}
|
|
58
67
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
68
|
+
type RoleRow = { userId?: string; id: string; name: string; permissions: string | string[] | null };
|
|
69
|
+
|
|
70
|
+
// A JSON column arrives as text from SQLite and already parsed from PostgreSQL and MySQL.
|
|
71
|
+
function safeParseStrings(raw: string | string[] | null): string[] {
|
|
72
|
+
if (!raw) return [];
|
|
73
|
+
try {
|
|
74
|
+
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
75
|
+
return Array.isArray(parsed) ? parsed.filter((value) => typeof value === 'string') : [];
|
|
76
|
+
} catch {
|
|
77
|
+
return [];
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function parseRoles(rows: readonly RoleRow[]): RoleAssignment[] {
|
|
82
|
+
return rows.map((row) => ({
|
|
83
|
+
id: row.id,
|
|
84
|
+
name: row.name,
|
|
85
|
+
permissions: safeParseStrings(row.permissions),
|
|
86
|
+
}));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Each user's newest auth session start. Sign-out deletes the session, and with it this time. */
|
|
90
|
+
async function lastSignIns(userIds: readonly string[]): Promise<Map<string, string>> {
|
|
91
|
+
if (!userIds.length) return new Map();
|
|
92
|
+
// The sessions of this host: a tenant's are in its own database.
|
|
93
|
+
const rows = (await sql<{ userId: string; lastSignedInAt: string | null }>`
|
|
94
|
+
SELECT user_id AS userId, MAX(created_at) AS lastSignedInAt
|
|
95
|
+
FROM sessions
|
|
96
|
+
WHERE user_id IN (${userIds}) AND kind = 'auth'
|
|
97
|
+
GROUP BY user_id
|
|
98
|
+
`).rows;
|
|
99
|
+
const times = new Map<string, string>();
|
|
100
|
+
for (const row of rows) {
|
|
101
|
+
const at = row.lastSignedInAt ? new Date(row.lastSignedInAt) : null;
|
|
102
|
+
if (at && !Number.isNaN(at.getTime())) times.set(row.userId, at.toISOString());
|
|
103
|
+
}
|
|
104
|
+
return times;
|
|
67
105
|
}
|
|
68
106
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
107
|
+
async function roleRowsForUsers(userIds: readonly string[]): Promise<readonly RoleRow[]> {
|
|
108
|
+
if (!userIds.length) return [];
|
|
109
|
+
return (await sql<RoleRow>`
|
|
110
|
+
SELECT ur.user_id AS userId, r.id, r.name, r.permissions
|
|
111
|
+
FROM user_roles ur
|
|
112
|
+
INNER JOIN roles r ON r.id = ur.role_id
|
|
113
|
+
WHERE ur.user_id IN (${userIds})
|
|
114
|
+
`).rows;
|
|
73
115
|
}
|
|
74
116
|
|
|
75
117
|
export async function listUsers(options: ListUsersOptions = {}): Promise<ListUsersResult> {
|
|
76
|
-
const page =
|
|
77
|
-
const
|
|
78
|
-
const
|
|
79
|
-
|
|
118
|
+
const { search, roleId, page = 1, pageSize = 20 } = options;
|
|
119
|
+
const safePage = Math.max(1, page);
|
|
120
|
+
const safeSize = Math.max(1, pageSize);
|
|
121
|
+
const like = search ? `%${search}%` : null;
|
|
122
|
+
const roleFilter = roleId
|
|
123
|
+
? sql.fragment`AND u.id IN (SELECT user_id FROM user_roles WHERE role_id = ${roleId})`
|
|
124
|
+
: sql.fragment``;
|
|
125
|
+
const searchFilter = like
|
|
126
|
+
? sql.fragment`AND (u.name LIKE ${like} OR u.email LIKE ${like})`
|
|
127
|
+
: sql.fragment``;
|
|
128
|
+
|
|
129
|
+
const [pageResult, countResult] = await Promise.all([
|
|
130
|
+
sql<{ id: string; email: string; name: string | null; avatar: string | null; createdAt: string; tenantAccount: boolean | number }>`
|
|
131
|
+
SELECT u.id, u.email, u.name, u.avatar, u.created_at AS createdAt, u.tenant_account AS tenantAccount
|
|
132
|
+
FROM users u
|
|
133
|
+
WHERE 1 = 1 ${searchFilter} ${roleFilter}
|
|
134
|
+
ORDER BY u.created_at DESC
|
|
135
|
+
LIMIT ${safeSize} OFFSET ${(safePage - 1) * safeSize}
|
|
136
|
+
`,
|
|
137
|
+
sql<{ total: number }>`
|
|
138
|
+
SELECT COUNT(*) AS total FROM users u
|
|
139
|
+
WHERE 1 = 1 ${searchFilter} ${roleFilter}
|
|
140
|
+
`,
|
|
141
|
+
]);
|
|
142
|
+
// In a tenant, members whose account every tenant shares are marked.
|
|
143
|
+
const tenant = currentTenant() !== null;
|
|
144
|
+
const items: UserSummary[] = pageResult.rows.map(({ tenantAccount, ...row }) => ({
|
|
145
|
+
...row,
|
|
146
|
+
...(tenant && !tenantAccount ? { badge: authOptions.accountLabels.shared } : {}),
|
|
147
|
+
name: row.name ?? '',
|
|
148
|
+
lastSignedInAt: null,
|
|
149
|
+
roles: [],
|
|
150
|
+
}));
|
|
151
|
+
const [roleRows, signIns] = await Promise.all([
|
|
152
|
+
roleRowsForUsers(items.map((user) => user.id)),
|
|
153
|
+
lastSignIns(items.map((user) => user.id)),
|
|
154
|
+
]);
|
|
155
|
+
const byUser = new Map<string, RoleAssignment[]>();
|
|
156
|
+
for (const row of roleRows) {
|
|
157
|
+
const roles = byUser.get(row.userId!) ?? [];
|
|
158
|
+
roles.push(...parseRoles([row]));
|
|
159
|
+
byUser.set(row.userId!, roles);
|
|
160
|
+
}
|
|
161
|
+
for (const item of items) {
|
|
162
|
+
item.roles = byUser.get(item.id) ?? [];
|
|
163
|
+
item.lastSignedInAt = signIns.get(item.id) ?? null;
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
items,
|
|
167
|
+
total: Number(countResult.rows[0]?.total ?? 0),
|
|
168
|
+
page: safePage,
|
|
169
|
+
pageSize: safeSize,
|
|
170
|
+
};
|
|
80
171
|
}
|
|
81
172
|
|
|
82
173
|
export async function getUser(id: string): Promise<UserDetail | null> {
|
|
83
|
-
const user = await
|
|
174
|
+
const user = await User.findOne({ where: { id } });
|
|
84
175
|
if (!user) return null;
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
176
|
+
return {
|
|
177
|
+
id: user.id,
|
|
178
|
+
email: user.email,
|
|
179
|
+
name: user.name ?? '',
|
|
180
|
+
avatar: user.avatar,
|
|
181
|
+
createdAt: user.createdAt.toISOString(),
|
|
182
|
+
lastSignedInAt: (await lastSignIns([id])).get(id) ?? null,
|
|
183
|
+
roles: parseRoles(await roleRowsForUsers([id])),
|
|
184
|
+
// In a tenant a member's account is shared, so only its owner changes it. The tenant's own accounts are its to manage.
|
|
185
|
+
...(currentTenant() && !user.tenantAccount ? { lockedProfile: authOptions.accountLabels.sharedNotice } : {}),
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** A password nobody knows, for an account that is invited to set its own. */
|
|
190
|
+
function unknownPassword(): string {
|
|
191
|
+
return btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32))));
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export async function createUser(input: CreateUserInput): Promise<PublicUser> {
|
|
195
|
+
// In a tenant an existing main account joins without a password; only a new account needs one.
|
|
196
|
+
if (!input.invite && !input.password && !currentTenant()) throw new ClientVisibleError('Set a password or send an invitation.');
|
|
197
|
+
if (input.invite && !canInvite()) throw new ClientVisibleError('No email sender is configured, so invitations cannot be sent. Set a password instead.');
|
|
198
|
+
if (input.invite) input = { ...input, password: unknownPassword() };
|
|
199
|
+
// In a tenant: the account with this email becomes a member; a new account is made when there is none.
|
|
200
|
+
if (currentTenant()) {
|
|
201
|
+
const joined = await joinCurrentTenant({ email: input.email, ...(input.name ? { name: input.name } : {}), passwordHash: input.password ? await hashPassword(input.password) : null });
|
|
202
|
+
const roleIds = [...new Set(input.roleIds ?? [])];
|
|
203
|
+
if (roleIds.length) {
|
|
204
|
+
const known = await Role.find({ where: { id: In(roleIds) } });
|
|
205
|
+
if (known.length !== roleIds.length) throw new ClientVisibleError('Choose roles that exist.');
|
|
206
|
+
await syncUserRoles(joined.id, roleIds);
|
|
207
|
+
}
|
|
208
|
+
// A member with a main account has its password already.
|
|
209
|
+
if (input.invite && joined.created) await sendInvitation(joined.id);
|
|
210
|
+
return { id: joined.id, email: input.email, name: input.name ?? '', avatar: null, meta: null, roles: [] };
|
|
100
211
|
}
|
|
101
|
-
if (
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
/** A network account on an added site keeps its name, email and picture unless the person or a network admin changes them. */
|
|
122
|
-
export async function updateUser(id: string, patch: UpdateUserInput): Promise<void> {
|
|
123
|
-
const cms = currentCms();
|
|
124
|
-
if (!(await manageableHere(id))) {
|
|
125
|
-
const user = await cms.users.get(id);
|
|
126
|
-
if (user && (Object.keys(patch) as (keyof UpdateUserInput)[]).some(key => patch[key] !== undefined && patch[key] !== user[key])) throw new ClientVisibleError(NETWORK_ACCOUNT_LOCKED);
|
|
127
|
-
return;
|
|
212
|
+
if (await User.exists({ email: input.email })) {
|
|
213
|
+
throw new ClientVisibleError('An account with this email already exists.');
|
|
214
|
+
}
|
|
215
|
+
const id = uuidv7();
|
|
216
|
+
await User.insert({
|
|
217
|
+
id,
|
|
218
|
+
email: input.email,
|
|
219
|
+
name: input.name ?? null,
|
|
220
|
+
passwordHash: await hashPassword(input.password!),
|
|
221
|
+
avatar: null,
|
|
222
|
+
meta: null,
|
|
223
|
+
createdAt: new Date(),
|
|
224
|
+
});
|
|
225
|
+
// Roles chosen by someone who may assign them; otherwise the default role, when one is set.
|
|
226
|
+
const fallback = input.roleIds === undefined ? await defaultRole() : null;
|
|
227
|
+
const roleIds = [...new Set(input.roleIds ?? (fallback ? [fallback.id] : []))];
|
|
228
|
+
if (roleIds.length) {
|
|
229
|
+
const known = await Role.find({ where: { id: In(roleIds) } });
|
|
230
|
+
if (known.length !== roleIds.length) throw new ClientVisibleError('Choose roles that exist.');
|
|
231
|
+
await syncUserRoles(id, roleIds);
|
|
128
232
|
}
|
|
129
|
-
|
|
233
|
+
if (input.invite) await sendInvitation(id);
|
|
234
|
+
return { id, email: input.email, name: input.name ?? '', avatar: null, meta: null, roles: [] };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const SHARED_ACCOUNT = authOptions.accountLabels.sharedNotice;
|
|
238
|
+
|
|
239
|
+
export async function updateUser(id: string, patch: UpdateUserInput): Promise<void> {
|
|
240
|
+
if (currentTenant() && !await tenantOwnAccount(id)) throw new ClientVisibleError(SHARED_ACCOUNT);
|
|
241
|
+
if (Object.keys(patch).length) await User.update({ id }, patch);
|
|
130
242
|
}
|
|
131
243
|
|
|
132
244
|
/**
|
|
133
|
-
*
|
|
134
|
-
*
|
|
245
|
+
* Let a user sign in, or stop them: a disabled account is a guest with every session it has.
|
|
246
|
+
* In a tenant a member's account is shared, so only the tenant's own accounts change here.
|
|
135
247
|
*/
|
|
248
|
+
export async function setUserStatus(id: string, status: 'active' | 'disabled'): Promise<void> {
|
|
249
|
+
if (currentTenant() && !await tenantOwnAccount(id)) throw new ClientVisibleError(SHARED_ACCOUNT);
|
|
250
|
+
if (status === 'disabled') {
|
|
251
|
+
await requireAnotherAdmin(id, 'disabled');
|
|
252
|
+
if (!currentTenant()) await requireAnotherNetworkAdmin(id, 'disabled');
|
|
253
|
+
}
|
|
254
|
+
await User.update({ id }, { status });
|
|
255
|
+
if (status === 'disabled') await sql`DELETE FROM sessions WHERE user_id = ${id} AND kind = 'auth'`;
|
|
256
|
+
}
|
|
257
|
+
|
|
136
258
|
export async function changeUserPassword(id: string, newPassword: string): Promise<void> {
|
|
137
|
-
if (!
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
const c = getRequestContext();
|
|
141
|
-
const own = c && (c.get('user') as { id?: string } | undefined)?.id === id ? getCookie(c, SESSION_COOKIE_NAME) : undefined;
|
|
142
|
-
// On an added site, a network account's sessions are the network host's; its sites' child sessions end with them.
|
|
143
|
-
const sessions = cms.siteAccounts && (await cms.storesOf(id)).kind === 'network' && c ? networkFor(c.env as CmsBindings).main.authSessions : cms.authSessions;
|
|
144
|
-
await sessions.revokeAllForUser(id, own);
|
|
259
|
+
if (currentTenant() && !await tenantOwnAccount(id)) throw new ClientVisibleError(SHARED_ACCOUNT);
|
|
260
|
+
if (!(await User.exists({ id }))) throw new ClientVisibleError('User not found.');
|
|
261
|
+
await User.update({ id }, { passwordHash: await hashPassword(newPassword) });
|
|
145
262
|
}
|
|
146
263
|
|
|
147
264
|
/**
|
|
148
|
-
*
|
|
149
|
-
*
|
|
150
|
-
* account stays. Content keeps its author ID. The last network admin cannot be deleted.
|
|
265
|
+
* Refuse a change that would leave nobody active with the admin role here (in this tenant, or
|
|
266
|
+
* in the application without tenants). `keeps` says whether the user still has the role after it.
|
|
151
267
|
*/
|
|
268
|
+
async function requireAnotherAdmin(userId: string, change: string, keeps = false): Promise<void> {
|
|
269
|
+
if (keeps) return;
|
|
270
|
+
const admin = await Role.findOne({ where: { id: 'admin' } });
|
|
271
|
+
if (!admin || !await UserRole.exists({ userId, roleId: admin.id })) return;
|
|
272
|
+
const others = (await sql<{ total: number }>`
|
|
273
|
+
SELECT COUNT(*) AS total FROM user_roles ur INNER JOIN users u ON u.id = ur.user_id
|
|
274
|
+
WHERE ur.role_id = ${admin.id} AND ur.user_id <> ${userId} AND u.status = 'active'
|
|
275
|
+
`).rows[0];
|
|
276
|
+
if (!Number(others?.total ?? 0)) throw new ClientVisibleError(`The last administrator cannot be ${change}.`);
|
|
277
|
+
}
|
|
278
|
+
|
|
152
279
|
export async function deleteUser(id: string): Promise<void> {
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
if (
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
280
|
+
await requireAnotherAdmin(id, 'removed');
|
|
281
|
+
// In a tenant: a member leaves, and the account stays. The tenant's own account goes, with what belongs to it.
|
|
282
|
+
if (currentTenant() && await tenantOwnAccount(id)) {
|
|
283
|
+
await sql`DELETE FROM sessions WHERE user_id = ${id}`;
|
|
284
|
+
await apiTokens.revokeAll(id);
|
|
285
|
+
await security.reset(id);
|
|
286
|
+
await UserRole.delete({ userId: id });
|
|
287
|
+
await User.delete({ id });
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
if (currentTenant()) return leaveCurrentTenant(id);
|
|
291
|
+
await requireAnotherNetworkAdmin(id, 'removed');
|
|
292
|
+
await UserRole.delete({ userId: id });
|
|
293
|
+
await User.delete({ id });
|
|
294
|
+
await forgetMemberships(id);
|
|
159
295
|
}
|
|
160
296
|
|
|
161
297
|
export async function assignRole(userId: string, roleId: string): Promise<void> {
|
|
162
|
-
|
|
163
|
-
|
|
298
|
+
await UserRole.upsert(
|
|
299
|
+
{ userId, roleId, createdAt: new Date() },
|
|
300
|
+
['userId', 'roleId'],
|
|
301
|
+
);
|
|
164
302
|
}
|
|
165
303
|
|
|
166
304
|
export async function removeRole(userId: string, roleId: string): Promise<void> {
|
|
167
|
-
|
|
168
|
-
|
|
305
|
+
if (roleId === 'admin') await requireAnotherAdmin(userId, 'left without the admin role');
|
|
306
|
+
await UserRole.delete({ userId, roleId });
|
|
169
307
|
}
|
|
170
308
|
|
|
171
309
|
export async function syncUserRoles(userId: string, roleIds: string[]): Promise<void> {
|
|
172
|
-
await
|
|
310
|
+
const admin = await Role.findOne({ where: { id: 'admin' } });
|
|
311
|
+
await requireAnotherAdmin(userId, 'left without the admin role', !!admin && roleIds.includes(admin.id));
|
|
312
|
+
await UserRole.delete({ userId });
|
|
313
|
+
if (roleIds.length) {
|
|
314
|
+
const createdAt = new Date();
|
|
315
|
+
await UserRole.insert(roleIds.map((roleId) => ({ userId, roleId, createdAt })));
|
|
316
|
+
}
|
|
173
317
|
}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
// Tenants (src/dashboard.config.ts: `tenants`). Each tenant has its own database; accounts,
|
|
2
|
+
// sessions and the list of tenants are in the application's own ("main") database.
|
|
3
|
+
//
|
|
4
|
+
// A request for a tenant's host runs in that tenant's ORM scope, so models and services reach
|
|
5
|
+
// the tenant's database. Account code steps back to the main database with `accounts()`.
|
|
6
|
+
// With tenants off, or on the main host, both are the same database and these do nothing.
|
|
7
|
+
import { tenantORM } from '@/orm/factory';
|
|
8
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
9
|
+
import type { Context } from 'hono';
|
|
10
|
+
import type { ORM } from '@cossackframework/database';
|
|
11
|
+
import { getRequestContext } from '@cossackframework/core';
|
|
12
|
+
import { authOptions } from './auth-options';
|
|
13
|
+
import { Tenant } from '@/models/Tenant';
|
|
14
|
+
import { TenantDomain } from '@/models/TenantDomain';
|
|
15
|
+
import { TenantNetwork } from '@/models/TenantNetwork';
|
|
16
|
+
|
|
17
|
+
/** The tenant a request is for. */
|
|
18
|
+
export interface TenantInfo {
|
|
19
|
+
readonly id: string;
|
|
20
|
+
readonly slug: string;
|
|
21
|
+
readonly name: string;
|
|
22
|
+
readonly database: string;
|
|
23
|
+
readonly status: 'creating' | 'active' | 'archived' | 'deleted';
|
|
24
|
+
/** The tenant's primary domain, when it has one: its other hosts redirect there. */
|
|
25
|
+
readonly primaryHost?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const TENANT = 'tenant';
|
|
29
|
+
const MAIN_ORM = 'tenant:main-orm';
|
|
30
|
+
const TENANT_ORM = 'tenant:orm';
|
|
31
|
+
|
|
32
|
+
export const tenantsEnabled = authOptions.tenants.enabled;
|
|
33
|
+
export const sharedSignIn = tenantsEnabled && authOptions.tenants.signIn === 'shared';
|
|
34
|
+
|
|
35
|
+
/** A tenant's slug: a DNS label. `www`, `main` and `new` are not tenants. */
|
|
36
|
+
export const TENANT_SLUG = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
37
|
+
export const RESERVED_SLUGS: readonly string[] = ['www', 'main', 'new', 'app', 'api', 'admin'];
|
|
38
|
+
|
|
39
|
+
/** A request's host name: lowercase, without the port. */
|
|
40
|
+
export function hostName(url: string): string {
|
|
41
|
+
try { return new URL(url).hostname.toLowerCase(); } catch { return ''; }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The main host, from APP_URL. Without APP_URL every request is the main tenant's. */
|
|
45
|
+
export function mainHost(): string {
|
|
46
|
+
return hostName(env('APP_URL', ''));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* What `withTenant()` sets for the work it runs. It is kept beside the work, not on the request:
|
|
51
|
+
* a request may run work for several tenants at once, and each sees its own.
|
|
52
|
+
*/
|
|
53
|
+
interface TenantScope {
|
|
54
|
+
readonly tenant: TenantInfo | null;
|
|
55
|
+
readonly main: ORM | undefined;
|
|
56
|
+
readonly orm: ORM;
|
|
57
|
+
readonly home: 'tenant' | 'main' | undefined;
|
|
58
|
+
}
|
|
59
|
+
const tenantScope = new AsyncLocalStorage<TenantScope>();
|
|
60
|
+
|
|
61
|
+
/** The tenant of this request, or null on the main host (and with tenants off). Inside `withTenant()`: the tenant of that work. */
|
|
62
|
+
export function currentTenant(c: Context | undefined = getRequestContext()): TenantInfo | null {
|
|
63
|
+
const scope = tenantScope.getStore();
|
|
64
|
+
if (scope) return scope.tenant;
|
|
65
|
+
return (c?.get(TENANT as never) as TenantInfo | undefined) ?? null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The request's marks, or those of the `withTenant()` the caller is in. */
|
|
69
|
+
function marks(): { main: ORM | undefined; orm: ORM | undefined; home: 'tenant' | 'main' | undefined } {
|
|
70
|
+
const scope = tenantScope.getStore();
|
|
71
|
+
if (scope) return scope;
|
|
72
|
+
const c = getRequestContext();
|
|
73
|
+
return { main: c?.get(MAIN_ORM as never) as ORM | undefined, orm: c?.get(TENANT_ORM as never) as ORM | undefined, home: c?.get(ACCOUNT_HOME as never) as 'tenant' | 'main' | undefined };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Run account code against the main database: accounts, sessions, second factors, tokens,
|
|
78
|
+
* the list of tenants. Inside a tenant's request it steps out of the tenant's database.
|
|
79
|
+
*/
|
|
80
|
+
export function accounts<T>(work: () => Promise<T>): Promise<T> {
|
|
81
|
+
const { main, home } = marks();
|
|
82
|
+
// A tenant's own account keeps everything in the tenant's database.
|
|
83
|
+
if ((accountHome.getStore() ?? home) === 'tenant') return inTenant(work);
|
|
84
|
+
return main ? main.run(work) : work();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Where the account that the running code is about lives: the main database, or the tenant's
|
|
88
|
+
// own for an account of that tenant only. Unset: the signed-in user's, else the main one.
|
|
89
|
+
const accountHome = new AsyncLocalStorage<'tenant' | 'main'>();
|
|
90
|
+
const ACCOUNT_HOME = 'tenant:account-home';
|
|
91
|
+
|
|
92
|
+
/** Run code about an account of this tenant only: `accounts()` inside it reaches the tenant's database. */
|
|
93
|
+
export function asTenantAccount<T>(work: () => Promise<T>): Promise<T> {
|
|
94
|
+
return currentTenant() ? accountHome.run('tenant', work) : work();
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Run code about an account of the main database, whoever is signed in. */
|
|
98
|
+
export function asMainAccount<T>(work: () => Promise<T>): Promise<T> {
|
|
99
|
+
return accountHome.run('main', work);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Whether the running code is about an account of this tenant only. */
|
|
103
|
+
export function tenantAccountHome(): boolean {
|
|
104
|
+
return currentTenant() !== null && (accountHome.getStore() ?? marks().home) === 'tenant';
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** @internal The signed-in user of this request is an account of this tenant only. */
|
|
108
|
+
export function markTenantAccountRequest(c: Context): void {
|
|
109
|
+
c.set(ACCOUNT_HOME as never, 'tenant' as never);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Run code against the request's tenant database again, from inside `accounts()`. */
|
|
113
|
+
export function inTenant<T>(work: () => Promise<T>): Promise<T> {
|
|
114
|
+
const { orm } = marks();
|
|
115
|
+
return orm ? orm.run(work) : work();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Run code against one tenant's database, whatever the request's host: the main host's Tenants screen uses it. */
|
|
119
|
+
export async function withTenant<T>(tenant: Pick<TenantInfo, 'database' | 'slug'> & Partial<TenantInfo>, work: () => Promise<T>): Promise<T> {
|
|
120
|
+
const c = getRequestContext();
|
|
121
|
+
const opened = await tenantORM(c?.env, tenant);
|
|
122
|
+
const outer = marks();
|
|
123
|
+
try {
|
|
124
|
+
return await tenantScope.run({
|
|
125
|
+
// `accounts()` inside the work still reaches the main database.
|
|
126
|
+
main: outer.main ?? (c?.get('orm' as never) as ORM | undefined),
|
|
127
|
+
orm: opened.orm,
|
|
128
|
+
// With the whole tenant given, it is the current one for the work: code that asks which
|
|
129
|
+
// tenant it is in gets this one, and the signed-in user's own home does not count there.
|
|
130
|
+
tenant: tenant.id ? tenant as TenantInfo : currentTenant(),
|
|
131
|
+
home: tenant.id ? undefined : outer.home,
|
|
132
|
+
}, () => opened.orm.run(work));
|
|
133
|
+
} finally {
|
|
134
|
+
await opened.release();
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function info(row: Tenant, primaryHost?: string): TenantInfo {
|
|
139
|
+
return { id: row.id, slug: row.slug, name: row.name, database: row.database, status: row.status, ...(primaryHost ? { primaryHost } : {}) };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Whether the network of tenants runs: a setting in the main database, remembered for half a minute.
|
|
143
|
+
let running: { at: number; value: boolean } | undefined;
|
|
144
|
+
|
|
145
|
+
/** Whether tenants' hosts answer. A network administrator turns the network off and on; off, only the main host answers. Called in the main database's scope. */
|
|
146
|
+
export async function tenantsRunning(): Promise<boolean> {
|
|
147
|
+
if (!tenantsEnabled) return false;
|
|
148
|
+
if (running && Date.now() - running.at < LOOKUP_MS) return running.value;
|
|
149
|
+
const row = await TenantNetwork.findOne({ where: { key: 'enabled' } });
|
|
150
|
+
running = { at: Date.now(), value: row?.value !== 'false' };
|
|
151
|
+
return running.value;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Turn the network of tenants on or off. Tenants keep their data while it is off. */
|
|
155
|
+
export async function setTenantsRunning(on: boolean): Promise<void> {
|
|
156
|
+
await TenantNetwork.upsert({ key: 'enabled', value: on ? 'true' : 'false', updatedAt: new Date() }, ['key']);
|
|
157
|
+
running = undefined;
|
|
158
|
+
forgetTenantHosts();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Whether a signed-in account may make a tenant of its own (the Tenants screen's setting). Off by default. */
|
|
162
|
+
export async function tenantRegistrationOn(): Promise<boolean> {
|
|
163
|
+
return (await TenantNetwork.findOne({ where: { key: 'registration' } }))?.value === 'on';
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export async function setTenantRegistrationOn(on: boolean): Promise<void> {
|
|
167
|
+
await TenantNetwork.upsert({ key: 'registration', value: on ? 'on' : 'off', updatedAt: new Date() }, ['key']);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** The tenant that asked for this host as a domain, verified or not: its ID answers `/.well-known/cossack-tenant`. */
|
|
171
|
+
export async function tenantClaimingHost(host: string): Promise<string | null> {
|
|
172
|
+
return (await TenantDomain.findOne({ where: { host } }))?.tenantId ?? null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Which tenant a host is, remembered for half a minute.
|
|
176
|
+
const lookups = new Map<string, { at: number; tenant: TenantInfo | null }>();
|
|
177
|
+
const LOOKUP_MS = 30_000;
|
|
178
|
+
|
|
179
|
+
/** Forget remembered hosts, after a tenant or a domain changed. Other servers follow within half a minute. */
|
|
180
|
+
export function forgetTenantHosts(): void {
|
|
181
|
+
lookups.clear();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The tenant a host name reaches: `<slug>.<main host>` or one of its domains. Called in the main database's scope. */
|
|
185
|
+
export async function tenantOfHost(host: string, main = mainHost()): Promise<TenantInfo | null> {
|
|
186
|
+
const known = lookups.get(host);
|
|
187
|
+
if (known && Date.now() - known.at < LOOKUP_MS) return known.tenant;
|
|
188
|
+
let row: Tenant | null = null;
|
|
189
|
+
if (main && host.endsWith(`.${main}`)) {
|
|
190
|
+
const slug = host.slice(0, -main.length - 1);
|
|
191
|
+
if (TENANT_SLUG.test(slug)) row = await Tenant.findOne({ where: { slug } });
|
|
192
|
+
}
|
|
193
|
+
if (!row) {
|
|
194
|
+
const domain = await TenantDomain.findOne({ where: { host } });
|
|
195
|
+
// A domain reaches its tenant once it was verified.
|
|
196
|
+
if (domain?.verifiedAt) row = await Tenant.findOne({ where: { id: domain.tenantId } });
|
|
197
|
+
}
|
|
198
|
+
const primary = row ? await TenantDomain.findOne({ where: { tenantId: row.id, isPrimary: true } }) : null;
|
|
199
|
+
const tenant = row ? info(row, primary?.verifiedAt ? primary.host : undefined) : null;
|
|
200
|
+
if (lookups.size > 2000) lookups.clear();
|
|
201
|
+
lookups.set(host, { at: Date.now(), tenant });
|
|
202
|
+
return tenant;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** The address of a tenant's host (or the main host for null), with APP_URL's scheme and port. */
|
|
206
|
+
export function tenantOrigin(tenant: Pick<TenantInfo, 'slug' | 'primaryHost'> | null): string | null {
|
|
207
|
+
const configured = env('APP_URL', '');
|
|
208
|
+
if (!configured) return null;
|
|
209
|
+
const url = new URL(configured);
|
|
210
|
+
if (tenant) url.hostname = tenant.primaryHost ?? `${tenant.slug}.${url.hostname}`;
|
|
211
|
+
return url.origin;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** @internal The middleware's marks on the request. */
|
|
215
|
+
export function markTenantRequest(c: Context, tenant: TenantInfo, main: ORM, orm: ORM): void {
|
|
216
|
+
c.set(TENANT as never, tenant as never);
|
|
217
|
+
c.set(MAIN_ORM as never, main as never);
|
|
218
|
+
c.set(TENANT_ORM as never, orm as never);
|
|
219
|
+
}
|