@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
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// What the network's screens ask about accounts across sites. Accounts are the main database's
|
|
2
|
+
// users (the dashboard package's), and memberships its `tenant_members`.
|
|
3
|
+
import { In, sql } from '@cossackframework/database';
|
|
4
|
+
import { hashPassword } from '@cossackframework/auth';
|
|
5
|
+
import { ClientVisibleError } from '@cossackframework/core';
|
|
6
|
+
import { MAIN_SITE, NETWORK_ADMIN } from '@cossackframework/cms';
|
|
7
|
+
import { accounts, asMainAccount } from '#app/tenants';
|
|
8
|
+
import { uuidv7 } from '#app/lib/uuid';
|
|
9
|
+
import { changeUserPassword, deleteUser, setUserStatus } from '#app/services/users';
|
|
10
|
+
import { requireAnotherNetworkAdmin } from '#app/services/tenants';
|
|
11
|
+
import { User } from '@/models/User';
|
|
12
|
+
import { TenantMember } from '@/models/TenantMember';
|
|
13
|
+
|
|
14
|
+
const main = <T>(work: () => Promise<T>): Promise<T> => asMainAccount(() => accounts(work));
|
|
15
|
+
|
|
16
|
+
/** How many network accounts are members of each added site. */
|
|
17
|
+
export function siteMemberCounts(): Promise<Map<string, number>> {
|
|
18
|
+
return main(async () => {
|
|
19
|
+
const counts = new Map<string, number>();
|
|
20
|
+
for (const member of await TenantMember.find({ take: 50_000 })) counts.set(member.tenantId, (counts.get(member.tenantId) ?? 0) + 1);
|
|
21
|
+
return counts;
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The added sites each of these accounts is a member of. */
|
|
26
|
+
export function siteMemberships(accountIds: readonly string[]): Promise<Map<string, string[]>> {
|
|
27
|
+
return main(async () => {
|
|
28
|
+
const found = new Map<string, string[]>();
|
|
29
|
+
if (!accountIds.length) return found;
|
|
30
|
+
for (const member of await TenantMember.find({ where: { userId: In([...accountIds]) }, take: 50_000 })) found.set(member.userId, [...(found.get(member.userId) ?? []), member.tenantId]);
|
|
31
|
+
return found;
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The IDs of the network's administrators. */
|
|
36
|
+
export function networkAdminIds(): Promise<Set<string>> {
|
|
37
|
+
return main(async () => new Set((await User.find({ where: { networkAdmin: true }, take: 1000 })).map(user => user.id)));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** An account of the network, as the network's screens show it. */
|
|
41
|
+
export interface NetworkAccount {
|
|
42
|
+
id: string; email: string; name: string; status: 'active' | 'disabled';
|
|
43
|
+
networkRole: typeof NETWORK_ADMIN | null; createdAt: number; lastSignInAt: number | null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async function shaped(users: readonly User[]): Promise<NetworkAccount[]> {
|
|
48
|
+
if (!users.length) return [];
|
|
49
|
+
const ids = users.map(user => user.id);
|
|
50
|
+
const signIns = await sql<{ userId: string; at: string | null }>`SELECT user_id AS userId, MAX(created_at) AS at FROM sessions WHERE user_id IN (${ids}) AND kind = 'auth' GROUP BY user_id`;
|
|
51
|
+
const last = new Map(signIns.rows.map(row => [row.userId, row.at ? new Date(row.at).getTime() : null]));
|
|
52
|
+
return users.map(user => ({ id: user.id, email: user.email, name: user.name ?? '', status: user.status === 'active' ? 'active' as const : 'disabled' as const,
|
|
53
|
+
networkRole: user.networkAdmin ? NETWORK_ADMIN : null, createdAt: user.createdAt.getTime(), lastSignInAt: last.get(user.id) ?? null }));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The network's accounts: the main database's users. Each is a user of the main site, and a
|
|
58
|
+
* member of the added sites `tenant_members` names. For the network's screens, on the network host.
|
|
59
|
+
*/
|
|
60
|
+
export const networkAccounts = {
|
|
61
|
+
get: (id: string) => main(async () => (await shaped(await User.find({ where: { id } })))[0] ?? null),
|
|
62
|
+
findByEmail: (email: string) => main(async () => (await shaped(await User.find({ where: { email: email.trim().toLowerCase() } })))[0] ?? null),
|
|
63
|
+
count: () => main(() => User.count()),
|
|
64
|
+
/** Newest first. `search` matches a name or an email. */
|
|
65
|
+
list: (options: { search?: string; networkAdmins?: boolean; limit?: number; offset?: number } = {}) => main(async () => {
|
|
66
|
+
const like = options.search?.trim() ? `%${options.search.trim().slice(0, 100).toLowerCase()}%` : null;
|
|
67
|
+
const search = like ? sql.fragment`AND (LOWER(u.name) LIKE ${like} OR u.email LIKE ${like})` : sql.fragment``;
|
|
68
|
+
const admins = options.networkAdmins ? sql.fragment`AND u.network_admin = ${true}` : sql.fragment``;
|
|
69
|
+
const [page, count] = await Promise.all([
|
|
70
|
+
sql<{ id: string }>`SELECT u.id FROM users u WHERE 1 = 1 ${search} ${admins} ORDER BY u.created_at DESC, u.id LIMIT ${Math.min(Math.max(options.limit ?? 20, 1), 100)} OFFSET ${Math.max(options.offset ?? 0, 0)}`,
|
|
71
|
+
sql<{ total: number }>`SELECT COUNT(*) AS total FROM users u WHERE 1 = 1 ${search} ${admins}`,
|
|
72
|
+
]);
|
|
73
|
+
const ids = page.rows.map(row => row.id);
|
|
74
|
+
const found = new Map((await shaped(ids.length ? await User.find({ where: { id: In(ids) } }) : [])).map(account => [account.id, account]));
|
|
75
|
+
return { items: ids.map(id => found.get(id)).filter((account): account is NetworkAccount => account !== undefined), total: Number(count.rows[0]?.total ?? 0) };
|
|
76
|
+
}),
|
|
77
|
+
/** The sites each account is a member of: the main site, and the added sites that have it as a member. */
|
|
78
|
+
memberships: async (ids: readonly string[]) => {
|
|
79
|
+
const added = await siteMemberships(ids);
|
|
80
|
+
return new Map(ids.map(id => [id, [MAIN_SITE, ...(added.get(id) ?? [])]]));
|
|
81
|
+
},
|
|
82
|
+
create: (input: { email: string; name: string; password: string; networkRole?: typeof NETWORK_ADMIN }) => main(async () => {
|
|
83
|
+
const email = input.email.trim().toLowerCase();
|
|
84
|
+
if (!/^[^\s@]{1,64}@[^\s@]{1,190}$/.test(email)) throw new ClientVisibleError('Enter a valid email address.');
|
|
85
|
+
if (input.password.length < 8) throw new ClientVisibleError('Enter a password of at least 8 characters.');
|
|
86
|
+
if (await User.exists({ email })) throw new ClientVisibleError('An account with this email already exists.');
|
|
87
|
+
const id = uuidv7();
|
|
88
|
+
await User.insert({ id, email, name: input.name.trim() || email, passwordHash: await hashPassword(input.password), avatar: null, meta: null, status: 'active', networkAdmin: input.networkRole === NETWORK_ADMIN, createdAt: new Date() });
|
|
89
|
+
return (await shaped(await User.find({ where: { id } })))[0]!;
|
|
90
|
+
}),
|
|
91
|
+
update: (id: string, patch: { name?: string; email?: string }) => main(async () => {
|
|
92
|
+
const values: Partial<User> = {};
|
|
93
|
+
if (patch.name !== undefined && patch.name.trim()) values.name = patch.name.trim();
|
|
94
|
+
if (patch.email !== undefined && patch.email.trim()) {
|
|
95
|
+
const email = patch.email.trim().toLowerCase();
|
|
96
|
+
if ((await User.findOne({ where: { email } }))?.id !== id && await User.exists({ email })) throw new ClientVisibleError('An account with this email already exists.');
|
|
97
|
+
values.email = email;
|
|
98
|
+
}
|
|
99
|
+
if (Object.keys(values).length) await User.update({ id }, values);
|
|
100
|
+
}),
|
|
101
|
+
setPassword: (id: string, password: string) => main(() => changeUserPassword(id, password)),
|
|
102
|
+
setNetworkRole: (id: string, role: typeof NETWORK_ADMIN | null) => main(async () => {
|
|
103
|
+
if (role === null) await requireAnotherNetworkAdmin(id, 'left without the role');
|
|
104
|
+
await User.update({ id }, { networkAdmin: role === NETWORK_ADMIN });
|
|
105
|
+
}),
|
|
106
|
+
/** Suspending ends the account's sessions on the network host; a suspended account is a guest on every site. */
|
|
107
|
+
setStatus: (id: string, status: 'active' | 'disabled') => main(() => setUserStatus(id, status)),
|
|
108
|
+
/** Delete the account. Its member rows on added sites stay as rows nobody can sign in to, and are removed with the member there. */
|
|
109
|
+
delete: (id: string) => main(async () => { await deleteUser(id); return true; }),
|
|
110
|
+
};
|
|
@@ -60,6 +60,6 @@ async function mayReadNotes(cms: CmsHost, note: Note, userId: string): Promise<b
|
|
|
60
60
|
if (!principal) return false;
|
|
61
61
|
const repository = cms.resource(note.resource);
|
|
62
62
|
const record = await repository.get(note.recordId, { principal });
|
|
63
|
-
return record !== null && repository.canUpdate(record, principal);
|
|
63
|
+
return record !== null && await repository.canUpdate(record, { principal });
|
|
64
64
|
} catch { return false; }
|
|
65
65
|
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// The people port (`PeoplePort` of the CMS library) over the dashboard package's accounts:
|
|
2
|
+
// users, roles and their assignments are the ORM's tables in the site's database, read and
|
|
3
|
+
// written in the scope of the request (the site's own database on a site of a network).
|
|
4
|
+
//
|
|
5
|
+
// A role's ID is the ORM role's (`editor`), and its name what people read ("Editor").
|
|
6
|
+
import { In, sql } from '@cossackframework/database';
|
|
7
|
+
import { CmsError, type PeoplePort, type Person, type PersonRole } from '@cossackframework/cms/server';
|
|
8
|
+
import { hashPassword } from '@cossackframework/auth';
|
|
9
|
+
import { uuidv7 } from '#app/lib/uuid';
|
|
10
|
+
import { asMainAccount, accounts, currentTenant } from '#app/tenants';
|
|
11
|
+
import { User } from '@/models/User';
|
|
12
|
+
import { Role } from '@/models/Role';
|
|
13
|
+
import { UserRole } from '@/models/UserRole';
|
|
14
|
+
import { TenantMember } from '@/models/TenantMember';
|
|
15
|
+
|
|
16
|
+
const ROLE_ID = /^[a-z][a-z0-9_-]{0,63}$/;
|
|
17
|
+
|
|
18
|
+
function personRole(role: Role): PersonRole {
|
|
19
|
+
return Object.freeze({ id: role.id, name: role.name, permissions: Object.freeze([...(role.permissions ?? [])].sort()) });
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Members of this site as people: their roles here, and whether the account is a network administrator's. */
|
|
23
|
+
async function people(users: readonly User[]): Promise<Person[]> {
|
|
24
|
+
if (!users.length) return [];
|
|
25
|
+
const ids = users.map(user => user.id);
|
|
26
|
+
const [assignments, roles, signIns, admins] = await Promise.all([
|
|
27
|
+
UserRole.find({ where: { userId: In(ids) }, take: 5000 }),
|
|
28
|
+
Role.find({ take: 500 }),
|
|
29
|
+
sql<{ userId: string; at: string | null }>`SELECT user_id AS userId, MAX(created_at) AS at FROM sessions WHERE user_id IN (${ids}) AND kind = 'auth' GROUP BY user_id`,
|
|
30
|
+
// The flag is the account's, in the main database; on a site of a network the member row does not carry it.
|
|
31
|
+
currentTenant() ? asMainAccount(() => accounts(() => User.find({ where: { id: In(ids), networkAdmin: true }, take: 500 }))) : Promise.resolve(users.filter(user => user.networkAdmin)),
|
|
32
|
+
]);
|
|
33
|
+
const byId = new Map(roles.map(role => [role.id, personRole(role)]));
|
|
34
|
+
const last = new Map(signIns.rows.map(row => [row.userId, row.at ? new Date(row.at).getTime() : null]));
|
|
35
|
+
const network = new Set(admins.map(user => user.id));
|
|
36
|
+
return users.map(user => Object.freeze({
|
|
37
|
+
id: user.id, email: user.email, name: user.name ?? '', avatar: user.avatar,
|
|
38
|
+
status: user.status === 'active' ? 'active' as const : 'disabled' as const,
|
|
39
|
+
roles: Object.freeze(assignments.filter(entry => entry.userId === user.id).map(entry => byId.get(entry.roleId)).filter((role): role is PersonRole => role !== undefined).sort((a, b) => a.id < b.id ? -1 : 1)),
|
|
40
|
+
networkAdmin: network.has(user.id),
|
|
41
|
+
account: user.tenantAccount ? 'site' as const : 'network' as const,
|
|
42
|
+
createdAt: user.createdAt.getTime(),
|
|
43
|
+
lastSignInAt: last.get(user.id) ?? null,
|
|
44
|
+
}));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function roleIds(names: readonly string[]): Promise<string[]> {
|
|
48
|
+
const unique = [...new Set(names)];
|
|
49
|
+
if (!unique.length) return [];
|
|
50
|
+
const found = await Role.find({ where: { id: In(unique) } });
|
|
51
|
+
if (found.length !== unique.length) throw new CmsError('CMS_VALIDATION', 'Unknown role.');
|
|
52
|
+
return found.map(role => role.id);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const ormPeople: PeoplePort = {
|
|
56
|
+
async getMany(ids) {
|
|
57
|
+
const wanted = [...new Set(ids)].slice(0, 200);
|
|
58
|
+
if (!wanted.length) return new Map();
|
|
59
|
+
return new Map((await people(await User.find({ where: { id: In(wanted) } }))).map(person => [person.id, person]));
|
|
60
|
+
},
|
|
61
|
+
async findByEmail(email) {
|
|
62
|
+
const user = await User.findOne({ where: { email: email.trim().toLowerCase() } });
|
|
63
|
+
return user ? (await people([user]))[0]! : null;
|
|
64
|
+
},
|
|
65
|
+
async list(options = {}) {
|
|
66
|
+
const limit = Math.min(Math.max(options.limit ?? 50, 1), 200);
|
|
67
|
+
const offset = Math.max(options.offset ?? 0, 0);
|
|
68
|
+
const like = options.search?.trim() ? `%${options.search.trim().slice(0, 100).toLowerCase()}%` : null;
|
|
69
|
+
const role = options.role ? await Role.findOne({ where: { id: options.role } }) : null;
|
|
70
|
+
if (options.role && !role) return { users: [], total: 0 };
|
|
71
|
+
const search = like ? sql.fragment`AND (LOWER(u.name) LIKE ${like} OR u.email LIKE ${like})` : sql.fragment``;
|
|
72
|
+
const held = role ? sql.fragment`AND u.id IN (SELECT user_id FROM user_roles WHERE role_id = ${role.id})` : sql.fragment``;
|
|
73
|
+
const [page, count] = await Promise.all([
|
|
74
|
+
sql<{ id: string }>`SELECT u.id FROM users u WHERE 1 = 1 ${search} ${held} ORDER BY LOWER(u.name), u.id LIMIT ${limit} OFFSET ${offset}`,
|
|
75
|
+
sql<{ total: number }>`SELECT COUNT(*) AS total FROM users u WHERE 1 = 1 ${search} ${held}`,
|
|
76
|
+
]);
|
|
77
|
+
const ids = page.rows.map(row => row.id);
|
|
78
|
+
const found = new Map((await people(ids.length ? await User.find({ where: { id: In(ids) } }) : [])).map(person => [person.id, person]));
|
|
79
|
+
return { users: ids.map(id => found.get(id)).filter((person): person is Person => person !== undefined), total: Number(count.rows[0]?.total ?? 0) };
|
|
80
|
+
},
|
|
81
|
+
async count() { return User.count(); },
|
|
82
|
+
async roles() { return (await Role.find({ order: { createdAt: 'asc' }, take: 500 })).map(personRole); },
|
|
83
|
+
async role(id) {
|
|
84
|
+
const role = await Role.findOne({ where: { id } });
|
|
85
|
+
return role ? personRole(role) : null;
|
|
86
|
+
},
|
|
87
|
+
async defineRole(role) {
|
|
88
|
+
if (!ROLE_ID.test(role.id) || !role.name.trim()) throw new CmsError('CMS_VALIDATION', 'A role needs an ID of lowercase letters and a name.');
|
|
89
|
+
const permissions = [...new Set(role.permissions)].sort();
|
|
90
|
+
if (await Role.exists({ id: role.id })) await Role.update({ id: role.id }, { name: role.name.trim(), permissions });
|
|
91
|
+
else await Role.insert({ id: role.id, name: role.name.trim(), permissions, createdAt: new Date() });
|
|
92
|
+
return personRole((await Role.findOne({ where: { id: role.id } }))!);
|
|
93
|
+
},
|
|
94
|
+
async create(input) {
|
|
95
|
+
const email = input.email.trim().toLowerCase();
|
|
96
|
+
if (!/^[^\s@]{1,64}@[^\s@]{1,190}$/.test(email)) throw new CmsError('CMS_VALIDATION', 'Enter a valid email address.', { fields: { email: 'is not valid.' } });
|
|
97
|
+
if (await User.exists({ email })) throw new CmsError('CMS_CONFLICT', 'A user with this email already exists.', { fields: { email: 'is taken.' } });
|
|
98
|
+
const roles = await roleIds(input.roles ?? []);
|
|
99
|
+
const id = input.id ?? uuidv7();
|
|
100
|
+
// On a site of a network a user made here is that site's own account.
|
|
101
|
+
await User.insert({ id, email, name: input.name.trim() || email, passwordHash: input.password ? await hashPassword(input.password) : null, avatar: null, meta: null, status: 'active', tenantAccount: currentTenant() !== null, createdAt: new Date() });
|
|
102
|
+
if (roles.length) await UserRole.insert(roles.map(roleId => ({ userId: id, roleId, createdAt: new Date() })));
|
|
103
|
+
return (await people([(await User.findOne({ where: { id } }))!]))[0]!;
|
|
104
|
+
},
|
|
105
|
+
async update(id, patch) {
|
|
106
|
+
const user = await User.findOne({ where: { id } });
|
|
107
|
+
if (!user) return false;
|
|
108
|
+
const values: Partial<User> = {};
|
|
109
|
+
if (patch.name !== undefined) values.name = patch.name.trim() || user.name;
|
|
110
|
+
if (patch.avatar !== undefined) values.avatar = patch.avatar;
|
|
111
|
+
if (patch.email !== undefined) {
|
|
112
|
+
const email = patch.email.trim().toLowerCase();
|
|
113
|
+
if (email !== user.email && await User.exists({ email })) throw new CmsError('CMS_CONFLICT', 'A user with this email already exists.', { fields: { email: 'is taken.' } });
|
|
114
|
+
values.email = email;
|
|
115
|
+
}
|
|
116
|
+
if (Object.keys(values).length) await User.update({ id }, values);
|
|
117
|
+
return true;
|
|
118
|
+
},
|
|
119
|
+
async setRoles(id, names) {
|
|
120
|
+
if (!await User.exists({ id })) throw new CmsError('CMS_NOT_FOUND', 'User not found.');
|
|
121
|
+
const roles = await roleIds(names);
|
|
122
|
+
await UserRole.delete({ userId: id });
|
|
123
|
+
if (roles.length) await UserRole.insert(roles.map(roleId => ({ userId: id, roleId, createdAt: new Date() })));
|
|
124
|
+
},
|
|
125
|
+
/** A main account becomes a member of this site: its row here (no password), its roles, and the network's record of it. */
|
|
126
|
+
async join(accountId, roles) {
|
|
127
|
+
const tenant = currentTenant();
|
|
128
|
+
if (!tenant) return (await this.getMany([accountId])).get(accountId) ?? null;
|
|
129
|
+
const account = await asMainAccount(() => accounts(() => User.findOne({ where: { id: accountId } })));
|
|
130
|
+
if (!account) return null;
|
|
131
|
+
const held = await roleIds(roles);
|
|
132
|
+
if (await User.exists({ id: accountId })) await User.update({ id: accountId }, { email: account.email, name: account.name, avatar: account.avatar, status: 'active' });
|
|
133
|
+
else await User.insert({ id: accountId, email: account.email, name: account.name, passwordHash: null, avatar: account.avatar, meta: null, status: 'active', tenantAccount: false, createdAt: new Date() });
|
|
134
|
+
await UserRole.delete({ userId: accountId });
|
|
135
|
+
if (held.length) await UserRole.insert(held.map(roleId => ({ userId: accountId, roleId, createdAt: new Date() })));
|
|
136
|
+
await asMainAccount(() => accounts(() => TenantMember.upsert({ tenantId: tenant.id, userId: accountId, createdAt: new Date() }, ['tenantId', 'userId'])));
|
|
137
|
+
return (await this.getMany([accountId])).get(accountId) ?? null;
|
|
138
|
+
},
|
|
139
|
+
/** On a site of a network: its own accounts. On the main site: every account. */
|
|
140
|
+
async ownCount() {
|
|
141
|
+
return currentTenant() ? User.count({ tenantAccount: true }) : User.count();
|
|
142
|
+
},
|
|
143
|
+
/**
|
|
144
|
+
* The users an import brought into this site's table: one whose ID the network has as an
|
|
145
|
+
* account is a member with that account; the others are accounts of this site, which set a
|
|
146
|
+
* password with Forgot password. On the main site every user is an account already.
|
|
147
|
+
*/
|
|
148
|
+
async adopt() {
|
|
149
|
+
const counts = { network: 0, site: 0, pending: 0 };
|
|
150
|
+
const tenant = currentTenant();
|
|
151
|
+
const users = await User.find({ take: 20_000 });
|
|
152
|
+
if (!tenant) {
|
|
153
|
+
// An export never gives a password or the network's role.
|
|
154
|
+
for (const user of users) await User.update({ id: user.id }, { networkAdmin: false, tenantAccount: false });
|
|
155
|
+
counts.pending = users.length;
|
|
156
|
+
return counts;
|
|
157
|
+
}
|
|
158
|
+
const ids = users.map(user => user.id);
|
|
159
|
+
const known = new Set(ids.length ? (await asMainAccount(() => accounts(() => User.find({ where: { id: In(ids) }, take: 20_000 })))).map(user => user.id) : []);
|
|
160
|
+
for (const user of users) {
|
|
161
|
+
const member = known.has(user.id);
|
|
162
|
+
await User.update({ id: user.id }, { tenantAccount: !member, networkAdmin: false, passwordHash: null });
|
|
163
|
+
if (member) { await asMainAccount(() => accounts(() => TenantMember.upsert({ tenantId: tenant.id, userId: user.id, createdAt: new Date() }, ['tenantId', 'userId']))); counts.network++; }
|
|
164
|
+
else counts.site++;
|
|
165
|
+
}
|
|
166
|
+
return counts;
|
|
167
|
+
},
|
|
168
|
+
async delete(id) {
|
|
169
|
+
if (!await User.exists({ id })) return false;
|
|
170
|
+
await UserRole.delete({ userId: id });
|
|
171
|
+
await User.delete({ id });
|
|
172
|
+
// On a site of a network: a member's membership goes too; a network account itself stays.
|
|
173
|
+
const tenant = currentTenant();
|
|
174
|
+
if (tenant) await asMainAccount(() => accounts(() => TenantMember.delete({ tenantId: tenant.id, userId: id })));
|
|
175
|
+
return true;
|
|
176
|
+
},
|
|
177
|
+
};
|
package/app/src/cms/recovery.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* an email and prints the one-hour reset link this answers with. The new password is chosen in
|
|
6
6
|
* the browser, as with Forgot password, so it never passes through the command line.
|
|
7
7
|
*/
|
|
8
|
+
import { recoverAccount as recoverByCode } from '#app/auth';
|
|
8
9
|
import type { Context } from 'hono';
|
|
9
10
|
import { getClientIp } from '@cossackframework/core';
|
|
10
11
|
import { sha256Hex, timingSafeEqual, type CmsHost } from '@cossackframework/cms/server';
|
|
@@ -48,7 +49,7 @@ export async function recoverAccount(c: Context, input: { code: unknown; email:
|
|
|
48
49
|
if (expected.length < RECOVERY_CODE_MIN_LENGTH) throw new RecoveryError('CMS_RECOVERY_WEAK', `CMS_RECOVERY_CODE must be at least ${RECOVERY_CODE_MIN_LENGTH} characters.`, 403);
|
|
49
50
|
const host: CmsHost = c.get('cms');
|
|
50
51
|
const address = getClientIp(c) || 'unknown';
|
|
51
|
-
if (!(await host.
|
|
52
|
+
if (!(await host.attempts.attempt('recovery', `a:${address}`, RECOVERY_ATTEMPTS.max, RECOVERY_ATTEMPTS.windowMs)))
|
|
52
53
|
throw new RecoveryError('CMS_RATE_LIMITED', 'Too many recovery attempts. Wait fifteen minutes.', 429);
|
|
53
54
|
// Compared as digests, so the time taken says nothing about the code's length either.
|
|
54
55
|
if (typeof input.code !== 'string' || !timingSafeEqual(await sha256Hex(input.code), await sha256Hex(expected))) throw new RecoveryError('CMS_UNAUTHENTICATED', 'The recovery code is not correct.', 401);
|
|
@@ -65,18 +66,12 @@ export async function recoverAccount(c: Context, input: { code: unknown; email:
|
|
|
65
66
|
throw new RecoveryError('CMS_UNAVAILABLE', 'The recovery could not be recorded in Tools → Activity, so it was not made. Try again.', 503);
|
|
66
67
|
}
|
|
67
68
|
|
|
68
|
-
//
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
if (
|
|
72
|
-
|
|
73
|
-
|
|
69
|
+
// The reset link is the application's (the dashboard package's recovery mode): made where the
|
|
70
|
+
// account is, a site's own on the site and a network account's on the network host.
|
|
71
|
+
const result = await recoverByCode(input.code, email, secondFactorsCleared);
|
|
72
|
+
if ('error' in result) {
|
|
73
|
+
throw new RecoveryError(result.status === 404 ? 'CMS_NOT_FOUND' : result.status === 429 ? 'CMS_RATE_LIMITED' : result.status === 401 ? 'CMS_UNAUTHENTICATED' : result.status === 403 ? 'CMS_RECOVERY_OFF' : 'CMS_VALIDATION',
|
|
74
|
+
result.status === 404 ? `No active account with the email ${email} on this site.` : result.error, result.status);
|
|
74
75
|
}
|
|
75
|
-
|
|
76
|
-
const userId = reset.account.id;
|
|
77
|
-
if (secondFactorsCleared) await (await host.storesOf(userId)).security.reset(userId);
|
|
78
|
-
await host.mail?.send({ kind: 'other', to: reset.account.email, subject: 'Your account was recovered',
|
|
79
|
-
text: `Someone with the site's recovery code asked for a password reset link for your account${secondFactorsCleared ? ' and removed its two-step sign-in' : ''}, from ${address}.\n\nIf that was not you or another administrator, tell whoever runs the site: the recovery code should be removed from its environment.` })
|
|
80
|
-
.catch(error => console.error('[cms] could not send the recovery notice', error));
|
|
81
|
-
return { email: reset.account.email, resetUrl: `${origin.replace(/\/$/, '')}/auth/reset-password?token=${reset.token}`, expiresAt: Date.now() + 60 * 60_000, secondFactorsCleared };
|
|
76
|
+
return result;
|
|
82
77
|
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import { getRequestContext } from '@cossackframework/core';
|
|
3
|
+
|
|
4
|
+
declare module 'hono' {
|
|
5
|
+
interface ContextVariableMap {
|
|
6
|
+
/** Ends the database calls this request started (see `requestCallsSignal`). */
|
|
7
|
+
'cms.requestCalls'?: AbortController;
|
|
8
|
+
/** The request's answer is made: work that runs after it is left alone. */
|
|
9
|
+
'cms.answered'?: boolean;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The signal of the current request's database calls, for `requestSignal` of the CMS's
|
|
15
|
+
* databases on a runtime that cancels a request's I/O when the request ends (Workers).
|
|
16
|
+
*
|
|
17
|
+
* One database client serves every request to a site in an isolate, and it allows 32 calls in
|
|
18
|
+
* flight. A call gives its place back when it settles; on Workers it never settles when its
|
|
19
|
+
* request ends first: the visitor left, or the request failed while other calls of the same
|
|
20
|
+
* `Promise.all` were in flight. So the calls end with the request (`withRequestCalls`). Work
|
|
21
|
+
* that runs after the answer (the outbox, maintenance, under `waitUntil`) gets no signal.
|
|
22
|
+
*/
|
|
23
|
+
export function requestCallsSignal(): AbortSignal | undefined {
|
|
24
|
+
const c = getRequestContext();
|
|
25
|
+
return c && c.get('cms.answered') !== true ? c.get('cms.requestCalls')?.signal : undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Answer a request with its own database calls' lifetime: they end when the visitor leaves
|
|
30
|
+
* (the request's signal, with `enable_request_signal` on Workers) or when the request fails
|
|
31
|
+
* (it throws or answers 5xx). Call `answered(c)` once the answer is made, before starting work
|
|
32
|
+
* that outlives it.
|
|
33
|
+
*/
|
|
34
|
+
export async function withRequestCalls<T>(c: Context, run: () => Promise<T>): Promise<T> {
|
|
35
|
+
const calls = new AbortController();
|
|
36
|
+
c.set('cms.requestCalls', calls);
|
|
37
|
+
const signal = c.req.raw.signal as AbortSignal | undefined;
|
|
38
|
+
const left = () => calls.abort(new Error('The visitor left before the answer.'));
|
|
39
|
+
signal?.addEventListener('abort', left, { once: true });
|
|
40
|
+
let failed = false;
|
|
41
|
+
try {
|
|
42
|
+
return await run();
|
|
43
|
+
} catch (error) {
|
|
44
|
+
failed = true;
|
|
45
|
+
throw error;
|
|
46
|
+
} finally {
|
|
47
|
+
signal?.removeEventListener('abort', left);
|
|
48
|
+
answered(c);
|
|
49
|
+
if (failed || c.error || c.res.status >= 500) calls.abort(new Error('The request failed.'));
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The answer is made: later database calls of this request (work after the answer) take no signal. */
|
|
54
|
+
export function answered(c: Context): void {
|
|
55
|
+
c.set('cms.answered', true);
|
|
56
|
+
}
|
|
@@ -54,19 +54,20 @@ export async function settingRows(cms: CmsHost, group: SettingsGroup, principal:
|
|
|
54
54
|
return { rows, values };
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
function choicesOf(cms: CmsHost, declaration: SettingDeclaration, principal: Principal, cache: ChoiceCache): Promise<SettingRow['choices']> {
|
|
58
|
-
if (declaration.control && declaration.kind !== 'enum' || declaration.source === 'media') return
|
|
59
|
-
if (declaration.kind === 'enum') return
|
|
60
|
-
if (!declaration.source) return
|
|
57
|
+
async function choicesOf(cms: CmsHost, declaration: SettingDeclaration, principal: Principal, cache: ChoiceCache): Promise<SettingRow['choices']> {
|
|
58
|
+
if (declaration.control && declaration.kind !== 'enum' && declaration.control !== 'checklist' || declaration.source === 'media') return [];
|
|
59
|
+
if (declaration.kind === 'enum') return (declaration.values ?? []).map(value => ({ value, label: declaration.choices?.[value] ?? value }));
|
|
60
|
+
if (!declaration.source) return [];
|
|
61
61
|
let found = cache.get(declaration.source);
|
|
62
62
|
if (!found) { found = sourceChoices(cms, declaration, principal); cache.set(declaration.source, found); }
|
|
63
|
-
|
|
63
|
+
// A single role to give someone is never the administrator's; a checklist of roles lists every one.
|
|
64
|
+
return declaration.source === 'roles' && declaration.control !== 'checklist' ? (await found).filter(choice => choice.value !== 'admin') : found;
|
|
64
65
|
}
|
|
65
66
|
|
|
66
67
|
/** The choices a source offers: the site's roles, categories, published pages or the time zones. */
|
|
67
68
|
async function sourceChoices(cms: CmsHost, declaration: SettingDeclaration, principal: Principal): Promise<SettingRow['choices']> {
|
|
68
69
|
switch (declaration.source) {
|
|
69
|
-
case 'roles': return (await cms.users.roles()).
|
|
70
|
+
case 'roles': return (await cms.users.roles()).map(role => ({ value: role.id, label: role.name }));
|
|
70
71
|
case 'categories': return (await cms.taxonomies.tree('categories')).map(term => ({ value: term.id, label: `${'— '.repeat(term.depth)}${term.name}` }));
|
|
71
72
|
case 'pages': return (await cms.resource('cms/pages').list({ where: { status: 'published' }, order: { field: 'title', direction: 'asc' }, limit: 100 }, { principal }))
|
|
72
73
|
.records.map(record => ({ value: record.id, label: recordTitle(record, 'title') }));
|
|
@@ -149,6 +150,20 @@ function paletteControl(row: SettingRow, value: SettingValue | undefined, attrib
|
|
|
149
150
|
</div>`;
|
|
150
151
|
}
|
|
151
152
|
|
|
153
|
+
/** The source's choices as checkboxes; the value is the checked ones' values joined by commas, in the choices' order. */
|
|
154
|
+
function checklistControl(row: SettingRow, value: SettingValue | undefined, attributes: FieldControlAttributes, set: (value: SettingValue) => void): TemplateResult {
|
|
155
|
+
const checked = new Set(String(value ?? '').split(',').map(entry => entry.trim()).filter(Boolean));
|
|
156
|
+
const toggle = (choice: string, on: boolean) => {
|
|
157
|
+
if (on) checked.add(choice); else checked.delete(choice);
|
|
158
|
+
// Values the choices no longer list (a role deleted since) stay chosen until unchecked here.
|
|
159
|
+
set([...row.choices.map(entry => entry.value).filter(entry => checked.has(entry)), ...[...checked].filter(entry => !row.choices.some(choice => choice.value === entry))].join(','));
|
|
160
|
+
};
|
|
161
|
+
return html`<div id=${attributes.id} role="group" aria-label=${row.label} aria-describedby=${attributes['aria-describedby'] ?? null} data-checklist class="flex flex-wrap gap-x-4 gap-y-2">
|
|
162
|
+
${row.choices.map(choice => component(Checkbox, { id: `${attributes.id}-${choice.value}`, label: choice.label, checked: checked.has(choice.value), disabled: value === null,
|
|
163
|
+
'@change': (event: Event) => toggle(choice.value, (event.target as HTMLInputElement).checked) }))}
|
|
164
|
+
</div>`;
|
|
165
|
+
}
|
|
166
|
+
|
|
152
167
|
export function settingControl(row: SettingRow, value: SettingValue | undefined, error: string | undefined, set: (value: SettingValue) => void, media?: SettingsMedia): TemplateResult {
|
|
153
168
|
const id = settingControlId(row.namespace, row.name);
|
|
154
169
|
const select = row.choices.length || row.kind === 'enum';
|
|
@@ -162,6 +177,8 @@ export function settingControl(row: SettingRow, value: SettingValue | undefined,
|
|
|
162
177
|
? iconStyleControl(row, value, attributes, set)
|
|
163
178
|
: row.control === 'palette'
|
|
164
179
|
? paletteControl(row, value, attributes, set)
|
|
180
|
+
: row.control === 'checklist'
|
|
181
|
+
? checklistControl(row, value, attributes, set)
|
|
165
182
|
: row.control === 'file'
|
|
166
183
|
? component(SettingsFile, { attributes, label: row.label, value: String(value ?? ''), disabled: value === null, kinds: row.fileKinds, media, onChange: set })
|
|
167
184
|
: row.kind === 'boolean'
|
|
@@ -19,6 +19,7 @@ export interface NetworkSettingsInput {
|
|
|
19
19
|
defaultPlugins: string[];
|
|
20
20
|
defaultLanguage: string;
|
|
21
21
|
siteExports: SiteExportPolicy;
|
|
22
|
+
siteRegistration: boolean;
|
|
22
23
|
}
|
|
23
24
|
export interface NetworkSettingsData extends NetworkSettingsInput {
|
|
24
25
|
/** What new sites' addresses end with while `subdomainSuffix` is empty. */
|
|
@@ -40,7 +41,7 @@ export async function loadNetworkSettings(network: CmsNetwork): Promise<NetworkS
|
|
|
40
41
|
]);
|
|
41
42
|
return {
|
|
42
43
|
enabled, name: settings.name, subdomainSuffix: settings.subdomainSuffix, defaultTheme: settings.defaultTheme,
|
|
43
|
-
defaultPlugins: [...settings.defaultPlugins], defaultLanguage: settings.defaultLanguage, siteExports: settings.siteExports, fallbackSuffix: network.subdomainSuffix,
|
|
44
|
+
defaultPlugins: [...settings.defaultPlugins], defaultLanguage: settings.defaultLanguage, siteExports: settings.siteExports, siteRegistration: settings.siteRegistration, fallbackSuffix: network.subdomainSuffix,
|
|
44
45
|
themes: network.main.themes().filter(theme => !theme.problems.length && !policy.hiddenThemes.has(theme.name)).map(theme => ({ name: theme.name, label: theme.label })),
|
|
45
46
|
plugins: status.plugins.filter(plugin => !plugin.themeOnly && !plugin.unrestricted && plugin.network === 'available').map(plugin => plugin.name),
|
|
46
47
|
canAddSites: network.canAddSites, sites: active.total + archived.total,
|
|
@@ -51,12 +52,12 @@ export async function loadNetworkSettings(network: CmsNetwork): Promise<NetworkS
|
|
|
51
52
|
export async function saveNetworkSettings(network: CmsNetwork, principal: Principal, input: NetworkSettingsInput): Promise<NetworkSettingsResult> {
|
|
52
53
|
const text = (value: unknown) => typeof value === 'string';
|
|
53
54
|
if (!input || typeof input.enabled !== 'boolean' || ![input.name, input.subdomainSuffix, input.defaultTheme, input.defaultLanguage].every(text)
|
|
54
|
-
|| !Array.isArray(input.defaultPlugins) || !input.defaultPlugins.every(text) || (input.siteExports !== 'request' && input.siteExports !== 'self')) return { data: null, error: __('The network settings are invalid.'), fields: {} };
|
|
55
|
+
|| !Array.isArray(input.defaultPlugins) || !input.defaultPlugins.every(text) || (input.siteExports !== 'request' && input.siteExports !== 'self') || typeof input.siteRegistration !== 'boolean') return { data: null, error: __('The network settings are invalid.'), fields: {} };
|
|
55
56
|
try {
|
|
56
57
|
if (input.enabled !== await network.enabled()) await network.setEnabled(input.enabled, { principal });
|
|
57
58
|
const patch: Partial<NetworkSettings> = {
|
|
58
59
|
name: input.name, subdomainSuffix: input.subdomainSuffix.trim(), defaultTheme: input.defaultTheme,
|
|
59
|
-
defaultPlugins: input.defaultPlugins, defaultLanguage: input.defaultLanguage.trim().toLowerCase(), siteExports: input.siteExports,
|
|
60
|
+
defaultPlugins: input.defaultPlugins, defaultLanguage: input.defaultLanguage.trim().toLowerCase(), siteExports: input.siteExports, siteRegistration: input.siteRegistration,
|
|
60
61
|
};
|
|
61
62
|
const saved = await network.settings();
|
|
62
63
|
// Turning the network on or off leaves the rest alone, even when a stored value went stale.
|
|
@@ -69,7 +70,7 @@ export async function saveNetworkSettings(network: CmsNetwork, principal: Princi
|
|
|
69
70
|
|
|
70
71
|
export const networkDraft = (data: NetworkSettingsData): NetworkSettingsInput => ({
|
|
71
72
|
enabled: data.enabled, name: data.name, subdomainSuffix: data.subdomainSuffix, defaultTheme: data.defaultTheme,
|
|
72
|
-
defaultPlugins: [...data.defaultPlugins], defaultLanguage: data.defaultLanguage, siteExports: data.siteExports,
|
|
73
|
+
defaultPlugins: [...data.defaultPlugins], defaultLanguage: data.defaultLanguage, siteExports: data.siteExports, siteRegistration: data.siteRegistration,
|
|
73
74
|
});
|
|
74
75
|
|
|
75
76
|
export type NetworkSettingsProps = {
|
|
@@ -138,6 +139,9 @@ export class NetworkSettingsForm extends Cossack {
|
|
|
138
139
|
</div>` : null}
|
|
139
140
|
${input('defaultLanguage', __('Language'), __('A language code, such as en, fr or pt-br. Add site can choose another.'), 'en')}
|
|
140
141
|
</fieldset>` : null}
|
|
142
|
+
${show('siteRegistration') ? component(Checkbox, { id: 'network-siteRegistration', checked: form.siteRegistration, '@change': (event: Event) => this.set({ siteRegistration: (event.target as HTMLInputElement).checked }) },
|
|
143
|
+
html`<span><span class="block font-medium">${__('People can register a site')}</span>
|
|
144
|
+
<span class="text-xs text-muted-foreground">${__('Anyone can create an account and a site at /auth/register-site, and becomes its administrator once their email is confirmed. Each account registers at most three sites a day.')}</span></span>`) : null}
|
|
141
145
|
${show('siteExports') ? html`<fieldset class="min-w-0 space-y-2">
|
|
142
146
|
<legend class="mb-2 text-base font-semibold text-foreground">${__('Site exports')}</legend>
|
|
143
147
|
${([['request', __('Site admins request an export; a network admin approves it'), __('The site can then download it under Tools → Export for 7 days. Requests wait on the site\'s page under Network → Sites.')],
|
|
@@ -65,6 +65,7 @@ export function settingsSearchEntries(cms: CmsHost, options: { network?: boolean
|
|
|
65
65
|
network('defaultPlugins', 'Plugins enabled on new sites', 'Plugins new sites start with.', 'new sites'),
|
|
66
66
|
network('defaultLanguage', 'Language of new sites', 'The default language new sites start with.', 'new sites locale'),
|
|
67
67
|
network('siteExports', 'Site exports', 'Whether site admins export their own site or request it from a network admin.', 'database download backup export request approve'),
|
|
68
|
+
network('siteRegistration', 'People can register a site', 'Visitors create an account and a site, and become its administrator.', 'sign up signup register registration self-service new site'),
|
|
68
69
|
);
|
|
69
70
|
}
|
|
70
71
|
return entries;
|
|
@@ -19,7 +19,7 @@ export async function editableRecord(cms: CmsHost, collection: string, id: strin
|
|
|
19
19
|
const definition = cms.collection(collection);
|
|
20
20
|
const repository = cms.resource(`cms/${definition.name}`);
|
|
21
21
|
const record = await repository.get(id, { principal });
|
|
22
|
-
return record && repository.canUpdate(record, principal) ? { collection: definition, record } : null;
|
|
22
|
+
return record && await repository.canUpdate(record, { principal }) ? { collection: definition, record } : null;
|
|
23
23
|
} catch (error) {
|
|
24
24
|
if (error instanceof CmsError) return null;
|
|
25
25
|
throw error;
|
|
@@ -119,10 +119,11 @@ async function patternDocuments(cms: CmsHost, ids: readonly string[], options: r
|
|
|
119
119
|
let records: Map<string, RecordShape>;
|
|
120
120
|
try { records = await repository.getMany(ids.slice(0, 50), { principal }); }
|
|
121
121
|
catch (error) { if (error instanceof CmsError) return []; throw error; }
|
|
122
|
+
const editable = await repository.editable([...records.values()], { principal });
|
|
122
123
|
return ids.flatMap(id => {
|
|
123
124
|
const record = records.get(id);
|
|
124
125
|
if (!record || !Array.isArray(record.content)) return [];
|
|
125
|
-
return [{ key: `pattern:${id}`, kind: 'pattern' as const, name: id, label: recordTitle(record, 'title'), revision: record.rev, blocks: editorBlocks(record.content as EditorBlock[], options), editable:
|
|
126
|
+
return [{ key: `pattern:${id}`, kind: 'pattern' as const, name: id, label: recordTitle(record, 'title'), revision: record.rev, blocks: editorBlocks(record.content as EditorBlock[], options), editable: editable.has(record.id), changed: false, error: '', conflict: false }];
|
|
126
127
|
});
|
|
127
128
|
}
|
|
128
129
|
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Registering a site from the network host's sign-up page, when the network lets people
|
|
2
|
+
// register sites (Settings → Network). The account that registers it is its administrator.
|
|
3
|
+
import { ClientVisibleError, getClientIp, getRequestContext } from '@cossackframework/core';
|
|
4
|
+
import { isCmsError, userPrincipal } from '@cossackframework/cms';
|
|
5
|
+
import type { SiteRegistration } from '@cossackframework/cms/server';
|
|
6
|
+
import { loginUser, securityStatus } from '#app/auth';
|
|
7
|
+
import { mailer } from '#app/mail';
|
|
8
|
+
import { currentCms, networkFor, type CmsBindings } from './index';
|
|
9
|
+
import { networkAccounts } from './network-accounts';
|
|
10
|
+
|
|
11
|
+
/** Registrations one address sends in an hour. */
|
|
12
|
+
const SITE_REGISTRATION_REQUESTS = Object.freeze({ perAddress: 10, windowMs: 60 * 60_000 });
|
|
13
|
+
|
|
14
|
+
/** Whether this request is on the network host of a network that lets people register sites. */
|
|
15
|
+
export async function siteRegistrationOpen(): Promise<boolean> {
|
|
16
|
+
const c = getRequestContext();
|
|
17
|
+
if (!c) return false;
|
|
18
|
+
const network = networkFor(c.env as CmsBindings);
|
|
19
|
+
if (currentCms() !== network.main || !network.canAddSites) return false;
|
|
20
|
+
try { return (await network.settings()).siteRegistration && await network.enabled(); }
|
|
21
|
+
catch { return false; }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** A refusal of the network as text the page shows. */
|
|
25
|
+
async function siteError<T>(run: () => Promise<T>): Promise<T> {
|
|
26
|
+
try { return await run(); }
|
|
27
|
+
catch (error) {
|
|
28
|
+
if (isCmsError(error)) throw new ClientVisibleError(error.message);
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Register a site. A signed-in visitor (`userId`) gives the site alone. Otherwise the visitor
|
|
35
|
+
* gives an email and a password: an existing account's, checked as a sign-in is, makes the site
|
|
36
|
+
* at once; a new email gets a network account and the site, where the network cannot send a
|
|
37
|
+
* confirmation link. Where it can, a new person makes an account first (Register), confirms
|
|
38
|
+
* the email, and registers the site signed in.
|
|
39
|
+
*/
|
|
40
|
+
export async function registerSite(input: { site: SiteRegistration; name?: string; email?: string; password?: string }, userId: string | null): Promise<{ site: string; user: string; signIn: boolean }> {
|
|
41
|
+
const c = getRequestContext();
|
|
42
|
+
if (!c || !(await siteRegistrationOpen())) throw new ClientVisibleError('Site registration is closed on this network.');
|
|
43
|
+
const network = networkFor(c.env as CmsBindings);
|
|
44
|
+
if (!(await network.main.attempts.attempt('site-registration', `address:${getClientIp(c) || 'unknown'}`, SITE_REGISTRATION_REQUESTS.perAddress, SITE_REGISTRATION_REQUESTS.windowMs))) {
|
|
45
|
+
throw new ClientVisibleError('Too many sites were registered from here. Try again in an hour.');
|
|
46
|
+
}
|
|
47
|
+
const site = await siteError(() => network.checkSiteRegistration(input.site));
|
|
48
|
+
const create = async (accountId: string) => (await siteError(() => network.registerSite(site, { principal: userPrincipal(accountId, [], []) }))).id;
|
|
49
|
+
if (userId) return { site: await create(userId), user: userId, signIn: false };
|
|
50
|
+
const email = String(input.email ?? '').trim().toLowerCase();
|
|
51
|
+
const password = String(input.password ?? '');
|
|
52
|
+
if (await networkAccounts.findByEmail(email)) {
|
|
53
|
+
// An account's own password makes its site, counted as a sign-in attempt.
|
|
54
|
+
const account = await loginUser(email, password);
|
|
55
|
+
if (!account) throw new ClientVisibleError('An account with this email exists. Enter its password, or sign in first.');
|
|
56
|
+
// A password is one step: an account with a second one signs in through it first.
|
|
57
|
+
const factors = await securityStatus(account.id);
|
|
58
|
+
if (factors.totp || factors.passkeys.length) throw new ClientVisibleError('This account uses two-step sign-in. Sign in first, then register your site.');
|
|
59
|
+
return { site: await create(account.id), user: account.id, signIn: true };
|
|
60
|
+
}
|
|
61
|
+
if (mailer()) throw new ClientVisibleError('Create your account first (Register), confirm your email, then register your site.');
|
|
62
|
+
const account = await networkAccounts.create({ email, password, name: input.name?.trim() || email.split('@')[0]! });
|
|
63
|
+
return { site: await create(account.id), user: account.id, signIn: true };
|
|
64
|
+
}
|