@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,3 +1,4 @@
|
|
|
1
|
+
import { networkAccounts } from '#app/cms/network-accounts';
|
|
1
2
|
import { Cossack, Page, State, flash, flashed, type HeadValue } from '@cossackframework/core';
|
|
2
3
|
import { Badge, Card, CardBody, CardHeader, Field, NativeSelect } from '@cossackframework/ui';
|
|
3
4
|
import { html, component, type TemplateResult } from '@cossackframework/renderer';
|
|
@@ -34,20 +35,21 @@ export default class NetworkUser extends Cossack {
|
|
|
34
35
|
|
|
35
36
|
async init() {
|
|
36
37
|
const net = network(this.c);
|
|
37
|
-
const account = await
|
|
38
|
+
const account = await networkAccounts.get(this.c.req.param('id') ?? '');
|
|
38
39
|
if (!account) { this.error = __('There is no such account.'); this.c.status(404); return; }
|
|
39
40
|
const principal = this.c.get('principal');
|
|
40
41
|
Object.assign(this, {
|
|
41
42
|
id: account.id, name: account.name, email: account.email, status: account.status, admin: account.networkRole === NETWORK_ADMIN,
|
|
42
43
|
self: principal.kind === 'user' && principal.id === account.id, createdAt: account.createdAt, lastSignInAt: account.lastSignInAt,
|
|
43
44
|
});
|
|
44
|
-
const ids = (await
|
|
45
|
+
const ids = (await networkAccounts.memberships([account.id])).get(account.id) ?? [];
|
|
45
46
|
const names = await siteNames(this.c, ids);
|
|
46
47
|
const memberships: Membership[] = [];
|
|
47
48
|
for (const site of ids) {
|
|
48
49
|
const host = await this.hostOf(site);
|
|
49
50
|
if (!host) continue;
|
|
50
|
-
|
|
51
|
+
// A site's users are in its own database.
|
|
52
|
+
const member = await this.onSite(site, () => host.users.get(account.id));
|
|
51
53
|
const record = site === MAIN_SITE ? null : await net.sites.get(site);
|
|
52
54
|
memberships.push({ id: site, name: names.get(site) ?? site, roles: member?.assignments.map(role => role.name).join(', ') || __('No role'),
|
|
53
55
|
dashboard: siteLinks(this.c, { host: record?.domains.find(domain => domain.primary)?.host ?? null }).dashboard });
|
|
@@ -68,6 +70,15 @@ export default class NetworkUser extends Cossack {
|
|
|
68
70
|
return record && record.status !== 'creating' ? net.hostOf(networkSite(record)) : null;
|
|
69
71
|
}
|
|
70
72
|
|
|
73
|
+
/** Run work on a site's users in that site's database. */
|
|
74
|
+
private async onSite<T>(site: string, work: () => Promise<T>): Promise<T> {
|
|
75
|
+
const net = network(this.c);
|
|
76
|
+
if (site === MAIN_SITE) return work();
|
|
77
|
+
const record = await net.sites.get(site);
|
|
78
|
+
if (!record) throw new Error(__('There is no such site.'));
|
|
79
|
+
return net.inSite(networkSite(record), work);
|
|
80
|
+
}
|
|
81
|
+
|
|
71
82
|
async post() {
|
|
72
83
|
if (!isSameOriginPost(this.c.req.raw)) return this.c.text('Forbidden', 403);
|
|
73
84
|
const id = this.c.req.param('id') ?? '';
|
|
@@ -75,7 +86,7 @@ export default class NetworkUser extends Cossack {
|
|
|
75
86
|
const value = (name: string) => String(form.get(name) ?? '').trim();
|
|
76
87
|
const net = network(this.c);
|
|
77
88
|
const principal = this.c.get('principal');
|
|
78
|
-
const accounts =
|
|
89
|
+
const accounts = networkAccounts;
|
|
79
90
|
try {
|
|
80
91
|
const account = await accounts.get(id);
|
|
81
92
|
if (!account) throw new Error(__('There is no such account.'));
|
|
@@ -85,7 +96,10 @@ export default class NetworkUser extends Cossack {
|
|
|
85
96
|
if (action === 'profile') {
|
|
86
97
|
await accounts.update(id, { name: value('name'), email: value('email') });
|
|
87
98
|
// Sites keep a copy of the name and email in their member rows.
|
|
88
|
-
for (const site of (await accounts.memberships([id])).get(id) ?? [])
|
|
99
|
+
for (const site of (await accounts.memberships([id])).get(id) ?? []) {
|
|
100
|
+
const host = await this.hostOf(site);
|
|
101
|
+
if (host && site !== MAIN_SITE) await this.onSite(site, () => host.users.update(id, { name: value('name'), email: value('email') }));
|
|
102
|
+
}
|
|
89
103
|
if (value('password')) await accounts.setPassword(id, value('password'));
|
|
90
104
|
flash('network.message', __('Saved.'));
|
|
91
105
|
} else if (action === 'make-admin' || action === 'remove-admin') {
|
|
@@ -98,15 +112,20 @@ export default class NetworkUser extends Cossack {
|
|
|
98
112
|
const host = await this.hostOf(value('site'));
|
|
99
113
|
if (!host) throw new Error(__('There is no such site.'));
|
|
100
114
|
const role = value('role');
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
115
|
+
await this.onSite(value('site'), async () => {
|
|
116
|
+
if (role && !(await host.users.roles()).some(entry => entry.id === role)) throw new Error(__('That site has no such role.'));
|
|
117
|
+
// On the main site every account is a user already: it gets the role there.
|
|
118
|
+
if (value('site') === MAIN_SITE) await host.users.setRoles(id, role ? [role] : []);
|
|
119
|
+
else await host.users.addMember(id, { roles: role ? [role] : [] });
|
|
120
|
+
});
|
|
104
121
|
flash('network.message', `${account.name} ${__('is a member now.')}`);
|
|
105
122
|
} else if (action === 'remove-site') {
|
|
106
|
-
|
|
123
|
+
const host = await this.hostOf(value('site'));
|
|
124
|
+
if (value('site') === MAIN_SITE) throw new Error(__('Every account is a user of the main site. Change its roles there, or delete the account.'));
|
|
125
|
+
if (host) await this.onSite(value('site'), async () => { await host.users.delete(id); });
|
|
107
126
|
flash('network.message', __('Removed from the site.'));
|
|
108
127
|
} else if (action === 'delete') {
|
|
109
|
-
await
|
|
128
|
+
await accounts.delete(id);
|
|
110
129
|
flash('network.message', __('Deleted from every site.'));
|
|
111
130
|
return this.redirect('/dashboard/network/users');
|
|
112
131
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { networkAccounts } from '#app/cms/network-accounts';
|
|
1
2
|
import { Client, Cossack, Page, Server, State, flashed, type HeadValue } from '@cossackframework/core';
|
|
2
3
|
import { AlertDialog, Badge } from '@cossackframework/ui';
|
|
3
4
|
import { html, component } from '@cossackframework/renderer';
|
|
@@ -45,11 +46,11 @@ export default class NetworkUsers extends Cossack {
|
|
|
45
46
|
const net = network(this.c);
|
|
46
47
|
const search = this.search ? { search: this.search } : {};
|
|
47
48
|
const [found, all, admins] = await Promise.all([
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
49
|
+
networkAccounts.list({ ...search, networkAdmins: this.admins, limit: PAGE_SIZE, offset: (this.page - 1) * PAGE_SIZE }),
|
|
50
|
+
networkAccounts.list({ ...search, limit: 1 }),
|
|
51
|
+
networkAccounts.list({ ...search, networkAdmins: true, limit: 1 }),
|
|
51
52
|
]);
|
|
52
|
-
const memberships = await
|
|
53
|
+
const memberships = await networkAccounts.memberships(found.items.map(account => account.id));
|
|
53
54
|
const names = await siteNames(this.c, [...memberships.values()].flat());
|
|
54
55
|
const principal = this.c.get('principal');
|
|
55
56
|
this.counts = { all: all.total, admins: admins.total };
|
|
@@ -71,14 +72,14 @@ export default class NetworkUsers extends Cossack {
|
|
|
71
72
|
try {
|
|
72
73
|
if (principal.kind === 'user' && principal.id === id) throw new Error(__('Change your own account from your profile.'));
|
|
73
74
|
if (action === 'make-admin' || action === 'remove-admin') {
|
|
74
|
-
await
|
|
75
|
+
await networkAccounts.setNetworkRole(id, action === 'make-admin' ? NETWORK_ADMIN : null);
|
|
75
76
|
this.message = __('Saved.');
|
|
76
77
|
} else if (action === 'suspend' || action === 'activate') {
|
|
77
78
|
// Suspension signs the account out of every site.
|
|
78
|
-
await
|
|
79
|
+
await networkAccounts.setStatus(id, action === 'suspend' ? 'disabled' : 'active');
|
|
79
80
|
this.message = action === 'suspend' ? __('Suspended and signed out everywhere.') : __('Active again.');
|
|
80
81
|
} else if (action === 'delete') {
|
|
81
|
-
await
|
|
82
|
+
await networkAccounts.delete(id);
|
|
82
83
|
this.message = __('Deleted from every site.');
|
|
83
84
|
}
|
|
84
85
|
} catch (error) {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { networkAccounts } from '#app/cms/network-accounts';
|
|
1
2
|
import { Cossack, Page, State, flash, flashed, type HeadValue } from '@cossackframework/core';
|
|
2
3
|
import { Card, CardBody } from '@cossackframework/ui';
|
|
3
4
|
import { html, component } from '@cossackframework/renderer';
|
|
@@ -31,7 +32,7 @@ export default class NewNetworkUser extends Cossack {
|
|
|
31
32
|
const value = (name: string) => String(data.get(name) ?? '').trim();
|
|
32
33
|
const form: NewAccountForm = { name: value('name'), email: value('email'), admin: data.get('admin') === 'on' };
|
|
33
34
|
try {
|
|
34
|
-
const account = await
|
|
35
|
+
const account = await networkAccounts.create({ email: form.email, name: form.name || form.email.split('@')[0]!, password: String(data.get('password') ?? ''),
|
|
35
36
|
...(form.admin ? { networkRole: NETWORK_ADMIN } : {}) });
|
|
36
37
|
flash('network.message', `${account.name} ${__('can sign in now. Add them to sites below.')}`);
|
|
37
38
|
return this.redirect(`/dashboard/network/users/${account.id}`);
|
|
@@ -2,7 +2,7 @@ import { Cossack, Page, State, flash, flashed, type HeadValue } from '@cossackfr
|
|
|
2
2
|
import { Badge, Card, CardBody } from '@cossackframework/ui';
|
|
3
3
|
import { html, component } from '@cossackframework/renderer';
|
|
4
4
|
import { isCmsError, isSameOriginPost, PERMISSIONS } from '@cossackframework/cms';
|
|
5
|
-
import { approveRegistration } from '#app/auth';
|
|
5
|
+
import { approveRegistration, deleteRegistration, registrations } from '#app/auth';
|
|
6
6
|
import { requireAny } from '#app/cms/guards';
|
|
7
7
|
import { notice, pageHeader, shortDate } from '#app/cms/ui';
|
|
8
8
|
import { actionButton } from '#app/cms/network-view';
|
|
@@ -27,7 +27,8 @@ export default class RegistrationsPage extends Cossack {
|
|
|
27
27
|
async init() {
|
|
28
28
|
const cms = this.c.get('cms');
|
|
29
29
|
this.required = await cms.settings.get('general.approveRegistrations');
|
|
30
|
-
|
|
30
|
+
// Accounts and their approval are the dashboard package's.
|
|
31
|
+
this.waiting = await registrations();
|
|
31
32
|
this.message = flashed<string>('registrations.message') ?? '';
|
|
32
33
|
this.error = flashed<string>('registrations.error') ?? '';
|
|
33
34
|
}
|
|
@@ -39,12 +40,12 @@ export default class RegistrationsPage extends Cossack {
|
|
|
39
40
|
const id = String(form.get('id') ?? '');
|
|
40
41
|
const cms = this.c.get('cms');
|
|
41
42
|
try {
|
|
42
|
-
if (!(await
|
|
43
|
+
if (!(await registrations()).some(entry => entry.id === id && entry.verified)) throw new Error(__('This account does not wait for approval.'));
|
|
43
44
|
if (action === 'approve') {
|
|
44
45
|
await approveRegistration(id);
|
|
45
46
|
flash('registrations.message', __('Approved. They can sign in now and got an email saying so.'));
|
|
46
47
|
} else if (action === 'delete') {
|
|
47
|
-
await
|
|
48
|
+
await deleteRegistration(id);
|
|
48
49
|
flash('registrations.message', __('Deleted the account.'));
|
|
49
50
|
} else throw new Error(__('Unknown action.'));
|
|
50
51
|
} catch (error) {
|
|
@@ -7,6 +7,7 @@ import { ANONYMOUS, ARTICLE_TYPES, CmsError, CRAWLER_GROUPS, hasPermission, isCm
|
|
|
7
7
|
import type { CrawlerVisits, NotFoundRow } from '@cossackframework/cms/server';
|
|
8
8
|
import { requireAny } from '#app/cms/guards';
|
|
9
9
|
import { siteOrigin } from '#app/cms/seo';
|
|
10
|
+
import { mailKeptOnly } from '#app/cms/dev-mail';
|
|
10
11
|
import { notice, pageHeader, shortDate } from '#app/cms/ui';
|
|
11
12
|
|
|
12
13
|
interface Finding { id: string; tone: 'ok' | 'warn' | 'info'; title: string; detail: string; href?: string; items?: { title: string; href: string }[] }
|
|
@@ -63,7 +64,9 @@ export default class HealthPage extends Cossack {
|
|
|
63
64
|
const findings: Finding[] = [];
|
|
64
65
|
const origin = siteOrigin(this.c);
|
|
65
66
|
if (settings['reading.discourageSearchEngines']) findings.push({ id: 'hidden', tone: 'warn', title: __('The site is hidden from search engines'), detail: __('Settings → Reading asks every engine to stay away; nothing below matters until that is off.'), href: settingsSectionHref('reading') });
|
|
66
|
-
|
|
67
|
+
// In development the mail is kept and printed without a sender: say what a deployment would lack.
|
|
68
|
+
if (mailKeptOnly(cms)) findings.push({ id: 'mail', tone: 'warn', title: __('No email sender'), detail: __('Emails are kept for development only (GET /api/cms/dev/mail and the terminal) and reach nobody. Bind EMAIL (Cloudflare Email Service), or set SMTP_HOST, SMTP_USER and SMTP_PASS on Node, and MAIL_FROM for the sender.') });
|
|
69
|
+
else if (!cms.mail) findings.push({ id: 'mail', tone: 'warn', title: __('No email sender'), detail: __('Password resets, form notifications, comment and note emails are not sent. Bind EMAIL (Cloudflare Email Service), or set SMTP_HOST, SMTP_USER and SMTP_PASS on Node, and MAIL_FROM for the sender.') });
|
|
67
70
|
else if (cms.mailFrom === 'no-reply@example.com') findings.push({ id: 'mail-from', tone: 'info', title: __('MAIL_FROM is not set'), detail: __('Emails go out from no-reply@example.com, which receivers may refuse. Set MAIL_FROM to an address on a domain you send from.') });
|
|
68
71
|
if (!cms.ai) findings.push({ id: 'ai', tone: 'info', title: __('No AI provider'), detail: __('Set ANTHROPIC_API_KEY (and ANTHROPIC_MODEL), or bind Workers AI as AI, for the editor\'s Assistant and for plugins that ask for ai.') });
|
|
69
72
|
if (!env('APP_URL', '')) findings.push({ id: 'app-url', tone: 'warn', title: __('APP_URL is not set'), detail: `${__('Canonical URLs, structured data and IndexNow pings use the request\'s origin instead; set APP_URL to the public address')} (${origin}).` });
|
|
@@ -66,10 +66,11 @@ export default class ReplacePage extends Cossack {
|
|
|
66
66
|
try {
|
|
67
67
|
for (let offset = 0; offset < 1000; offset += 100) {
|
|
68
68
|
const page = await resource.list({ limit: 100, offset, order: { field: 'updatedAt', direction: 'desc' } }, { principal });
|
|
69
|
+
const editable = await resource.editable(page.records, { principal });
|
|
69
70
|
for (const record of page.records) {
|
|
70
71
|
// Only entries this user may change are searched: a count over one they may not would
|
|
71
72
|
// tell what a protected or members-only entry says.
|
|
72
|
-
if (!
|
|
73
|
+
if (!editable.has(record.id)) continue;
|
|
73
74
|
this.scanned++;
|
|
74
75
|
const changed: Record<string, unknown> = {};
|
|
75
76
|
const touched: string[] = [];
|
|
@@ -71,7 +71,7 @@ export default class SeoEditorPage extends Cossack {
|
|
|
71
71
|
const urls = await cms.entryUrls(collection, slice);
|
|
72
72
|
this.total = total;
|
|
73
73
|
// A locked entry's summary is written from its content: only its editors see it.
|
|
74
|
-
this.rows =
|
|
74
|
+
this.rows = (await repository.readerViews(slice, { principal })).map(record => {
|
|
75
75
|
const seo = (record.seo ?? {}) as { title?: string; description?: string };
|
|
76
76
|
return { id: record.id, title: recordTitle(record, 'title'), url: urls.get(record.id) ?? null, status: String(record.status ?? ''), seoTitle: seo.title ?? '', description: seo.description ?? '', summary: typeof record.summary === 'string' ? record.summary : '', rev: record.rev, saved: false };
|
|
77
77
|
});
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { recentSignIns } from '#app/auth';
|
|
1
2
|
import { Cossack, Page, State, Server, type HeadValue } from '@cossackframework/core';
|
|
2
3
|
import { Avatar, Badge, Icon } from '@cossackframework/ui';
|
|
3
4
|
import { html, component, type TemplateResult } from '@cossackframework/renderer';
|
|
@@ -119,7 +120,7 @@ export default class DashboardPage extends Cossack {
|
|
|
119
120
|
for (const note of threads) {
|
|
120
121
|
const [owner, name] = note.resource.split('/');
|
|
121
122
|
const record = await cms.resource(note.resource).get(note.recordId, context).catch(() => null);
|
|
122
|
-
if (!record || !cms.resource(note.resource).canUpdate(record,
|
|
123
|
+
if (!record || !await cms.resource(note.resource).canUpdate(record, context)) continue;
|
|
123
124
|
const author = authors.get(note.userId);
|
|
124
125
|
const excerpt = note.quote ? `“${note.quote.slice(0, 80)}”` : note.body.replace(/@\[([^\]]+)\]\([^)]+\)/g, '@$1').slice(0, 80);
|
|
125
126
|
items.push({ title: recordTitle(record, cms.resourceById(note.resource).titleField), href: `/dashboard/content/${owner === 'cms' ? name : `${owner}.${name}`}/${record.id}?notes=open`, at: note.updatedAt, meta: excerpt,
|
|
@@ -130,7 +131,7 @@ export default class DashboardPage extends Cossack {
|
|
|
130
131
|
// Who signed in lately: sessions end at sign-out, so these are the accounts signed in now.
|
|
131
132
|
this.canSeeSignIns = hasPermission(principal, PERMISSIONS.manageUsers);
|
|
132
133
|
if (this.canSeeSignIns) {
|
|
133
|
-
const sessions = await
|
|
134
|
+
const sessions = await recentSignIns(8).catch(() => []);
|
|
134
135
|
const users = await cms.users.getMany([...new Set(sessions.map(session => session.userId))]);
|
|
135
136
|
this.signIns = sessions.map(session => {
|
|
136
137
|
const user = users.get(session.userId);
|
|
@@ -71,7 +71,7 @@ export default class RolesPage extends Cossack {
|
|
|
71
71
|
/** Open the delete-confirmation dialog for a role (client-side). */
|
|
72
72
|
@Client()
|
|
73
73
|
requestDelete(r: RoleDetail) {
|
|
74
|
-
if (r.
|
|
74
|
+
if (r.id === 'admin') return;
|
|
75
75
|
this.pendingDelete = r;
|
|
76
76
|
}
|
|
77
77
|
|
|
@@ -108,7 +108,7 @@ export default class RolesPage extends Cossack {
|
|
|
108
108
|
${rowActions([
|
|
109
109
|
{ id: `role-${role.id}-edit`, label: __('Edit'), href: `/dashboard/roles/${role.id}` },
|
|
110
110
|
{ id: `role-${role.id}-users`, label: __('View users'), href: `/dashboard/users?role=${encodeURIComponent(role.name)}` },
|
|
111
|
-
...(role.
|
|
111
|
+
...(role.id !== 'admin' ? [{ id: `role-${role.id}-delete`, label: __('Delete'), danger: true, run: () => this.requestDelete(role) }] : []),
|
|
112
112
|
])}` },
|
|
113
113
|
{ label: __('Users'), class: 'text-muted-foreground', cell: role => html`<a href="/dashboard/users?role=${encodeURIComponent(role.name)}" class="text-muted-foreground no-underline hover:text-primary">${role.userCount ?? 0}</a>` },
|
|
114
114
|
],
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { Cossack, Page, Server, State, type HeadValue } from '@cossackframework/core';
|
|
2
|
+
import { Badge, Button, Card, CardBody } from '@cossackframework/ui';
|
|
3
|
+
import { html, component } from '@cossackframework/renderer';
|
|
4
|
+
import { approveRegistration, deleteRegistration, registrationApproval, registrations, type Registration } from '#app/auth';
|
|
5
|
+
import { guard } from '#app/services/rbac';
|
|
6
|
+
import { timeAgo } from '#app/dashboard/time-ago';
|
|
7
|
+
import { notice, pageHeader } from '@cossackframework/ui/blocks';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Users → Registrations: the accounts that wait before they can sign in, for their email's
|
|
11
|
+
* confirmation or for an administrator's approval (src/dashboard.config.ts: `registration`).
|
|
12
|
+
* Approve one to let them sign in (they get an email), or delete it.
|
|
13
|
+
*/
|
|
14
|
+
@Page({ transport: 'http', middlewares: [guard.requireRole('admin')] })
|
|
15
|
+
export default class RegistrationsPage extends Cossack {
|
|
16
|
+
@State() waiting: Registration[] = [];
|
|
17
|
+
@State() required = false;
|
|
18
|
+
@State() message = '';
|
|
19
|
+
@State() error = '';
|
|
20
|
+
/** The request's time, so the server and the browser render the same ages. */
|
|
21
|
+
@State() now = 0;
|
|
22
|
+
|
|
23
|
+
head(): HeadValue {
|
|
24
|
+
return { title: 'Registrations' };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async init() {
|
|
28
|
+
this.now = Date.now();
|
|
29
|
+
this.required = await registrationApproval();
|
|
30
|
+
this.waiting = await registrations();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
@Server()
|
|
34
|
+
async approve(id: string) {
|
|
35
|
+
this.message = ''; this.error = '';
|
|
36
|
+
if (await approveRegistration(String(id))) this.message = 'Approved. They can sign in now and got an email saying so.';
|
|
37
|
+
else this.error = 'This account does not wait for approval.';
|
|
38
|
+
this.waiting = await registrations();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
@Server()
|
|
42
|
+
async remove(id: string) {
|
|
43
|
+
this.message = ''; this.error = '';
|
|
44
|
+
if (await deleteRegistration(String(id))) this.message = 'Deleted the account.';
|
|
45
|
+
else this.error = 'This account does not wait any more.';
|
|
46
|
+
this.waiting = await registrations();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
render() {
|
|
50
|
+
return html`<div class="space-y-6">
|
|
51
|
+
${pageHeader(__('Registrations'), { description: __('New accounts that wait before they can sign in.') })}
|
|
52
|
+
${this.message ? notice(this.message, 'success') : null}
|
|
53
|
+
${this.error ? notice(this.error, 'error') : null}
|
|
54
|
+
${!this.required ? notice(__('The project does not ask for approval now: new accounts are active once their email is confirmed. Accounts below still wait.'), 'info') : null}
|
|
55
|
+
${component(Card, {}, component(CardBody, { class: 'p-0' }, this.waiting.length ? html`<ul class="divide-y divide-border" data-testid="registrations">${this.waiting.map(entry => html`<li class="flex flex-wrap items-center justify-between gap-3 px-4 py-3 text-sm">
|
|
56
|
+
<span><span class="font-medium text-foreground">${entry.name}</span> <span class="text-muted-foreground">${entry.email}</span>
|
|
57
|
+
<span class="mt-0.5 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">${__('Registered')} ${timeAgo(new Date(entry.createdAt).toISOString(), this.now)}
|
|
58
|
+
${entry.verified ? component(Badge, { variant: 'secondary' }, __('Email confirmed')) : component(Badge, { variant: 'outline' }, __('Email not confirmed yet'))}</span></span>
|
|
59
|
+
<span class="flex gap-2">
|
|
60
|
+
${entry.verified ? component(Button, { size: 'sm', '@click': () => this.approve(entry.id) }, __('Approve')) : null}
|
|
61
|
+
${component(Button, { size: 'sm', variant: 'outline', '@click': () => this.remove(entry.id) }, __('Delete'))}
|
|
62
|
+
</span>
|
|
63
|
+
</li>`)}</ul>` : html`<p class="px-4 py-6 text-sm text-muted-foreground">${__('No account waits.')}</p>`))}
|
|
64
|
+
</div>`;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Application passwords on the ORM: named tokens a user creates for apps and scripts. A token
|
|
2
|
+
// is `app_<id>.<secret>`; only the secret's SHA-256 is stored. A request with one acts as the
|
|
3
|
+
// user with their current roles; `read` tokens may only read.
|
|
4
|
+
import { authOptions } from '../auth-options';
|
|
5
|
+
import { ClientVisibleError } from '@cossackframework/core';
|
|
6
|
+
import { ApiToken as ApiTokenRow } from '@/models/ApiToken';
|
|
7
|
+
import { clock, randomToken, sha256Hex } from './security';
|
|
8
|
+
|
|
9
|
+
export type ApiTokenScope = 'read' | 'write';
|
|
10
|
+
|
|
11
|
+
export interface ApiToken {
|
|
12
|
+
id: string;
|
|
13
|
+
userId: string;
|
|
14
|
+
name: string;
|
|
15
|
+
scope: ApiTokenScope;
|
|
16
|
+
createdAt: number;
|
|
17
|
+
lastUsedAt: number | null;
|
|
18
|
+
expiresAt: number | null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** `<prefix>_<id>.<secret>`; the prefix is the project's (`app`), or the package's that serves these pages. */
|
|
22
|
+
const format = () => new RegExp(`^${authOptions.tokenPrefix}_([A-Za-z0-9_-]{16})\\.([A-Za-z0-9_-]{43})$`);
|
|
23
|
+
/** Tokens a user can hold. */
|
|
24
|
+
export const API_TOKEN_LIMIT = 20;
|
|
25
|
+
|
|
26
|
+
function tokenOf(row: ApiTokenRow): ApiToken {
|
|
27
|
+
return { id: row.id, userId: row.userId, name: row.name, scope: row.scope, createdAt: row.createdAt.getTime(),
|
|
28
|
+
lastUsedAt: row.lastUsedAt?.getTime() ?? null, expiresAt: row.expiresAt?.getTime() ?? null };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Compare two hashes without stopping at the first difference. */
|
|
32
|
+
function sameHash(left: string, right: string): boolean {
|
|
33
|
+
if (left.length !== right.length) return false;
|
|
34
|
+
let difference = 0;
|
|
35
|
+
for (let index = 0; index < left.length; index++) difference |= left.charCodeAt(index) ^ right.charCodeAt(index);
|
|
36
|
+
return difference === 0;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function list(userId: string): Promise<ApiToken[]> {
|
|
40
|
+
return (await ApiTokenRow.find({ where: { userId }, order: { createdAt: 'desc' }, take: 100 })).map(tokenOf);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A new token for the user. The returned `token` is shown once and cannot be read again. */
|
|
44
|
+
export async function create(userId: string, input: { name: string; scope?: ApiTokenScope; expiresAt?: number | null }): Promise<{ token: string; record: ApiToken }> {
|
|
45
|
+
const name = typeof input.name === 'string' ? input.name.trim() : '';
|
|
46
|
+
if (!name || name.length > 80) throw new ClientVisibleError('Name the application password in 1-80 characters.');
|
|
47
|
+
const scope = input.scope ?? 'write';
|
|
48
|
+
if (scope !== 'read' && scope !== 'write') throw new ClientVisibleError('Access is read or write.');
|
|
49
|
+
const now = clock.now();
|
|
50
|
+
if (input.expiresAt !== undefined && input.expiresAt !== null && (!Number.isSafeInteger(input.expiresAt) || input.expiresAt <= now)) {
|
|
51
|
+
throw new ClientVisibleError('The expiry must be in the future.');
|
|
52
|
+
}
|
|
53
|
+
if ((await ApiTokenRow.count({ userId })) >= API_TOKEN_LIMIT) throw new ClientVisibleError(`A user can have at most ${API_TOKEN_LIMIT} application passwords.`);
|
|
54
|
+
const id = randomToken(12);
|
|
55
|
+
const secret = randomToken(32);
|
|
56
|
+
const expiresAt = input.expiresAt ?? null;
|
|
57
|
+
await ApiTokenRow.insert({ id, userId, name, secretHash: await sha256Hex(secret), scope, createdAt: new Date(now), lastUsedAt: null,
|
|
58
|
+
expiresAt: expiresAt === null ? null : new Date(expiresAt) });
|
|
59
|
+
return { token: `${authOptions.tokenPrefix}_${id}.${secret}`, record: { id, userId, name, scope, createdAt: now, lastUsedAt: null, expiresAt } };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** False when the user has no such token. */
|
|
63
|
+
export async function revoke(userId: string, id: string): Promise<boolean> {
|
|
64
|
+
// A missing ID must not widen the delete to every token of the user.
|
|
65
|
+
if (typeof id !== 'string' || !id) return false;
|
|
66
|
+
return (await ApiTokenRow.delete({ id, userId })).meta.rowsAffected === 1;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function revokeAll(userId: string): Promise<void> {
|
|
70
|
+
await ApiTokenRow.delete({ userId });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The token's owner and access, or null for an unknown, wrong or expired token. Use is recorded at most every five minutes. */
|
|
74
|
+
export async function verify(token: string): Promise<{ id: string; userId: string; scope: ApiTokenScope } | null> {
|
|
75
|
+
const match = typeof token === 'string' ? format().exec(token) : null;
|
|
76
|
+
if (!match) return null;
|
|
77
|
+
const [, id, secret] = match;
|
|
78
|
+
const row = await ApiTokenRow.findOne({ where: { id: id! } });
|
|
79
|
+
if (!row || !sameHash(row.secretHash, await sha256Hex(secret!))) return null;
|
|
80
|
+
const now = clock.now();
|
|
81
|
+
if (row.expiresAt && row.expiresAt.getTime() <= now) return null;
|
|
82
|
+
if (!row.lastUsedAt || now - row.lastUsedAt.getTime() > 5 * 60_000) {
|
|
83
|
+
await ApiTokenRow.update({ id: row.id }, { lastUsedAt: new Date(now) }).catch(() => undefined);
|
|
84
|
+
}
|
|
85
|
+
return { id: row.id, userId: row.userId, scope: row.scope };
|
|
86
|
+
}
|
package/app/src/services/rbac.ts
CHANGED
|
@@ -4,19 +4,31 @@
|
|
|
4
4
|
// opt into checks with `@Page({ middlewares: [guard.requireRole('admin')] })`.
|
|
5
5
|
//
|
|
6
6
|
// With the CMS, permissions are patterns such as `cms:users` or `cms/posts:*`, and the
|
|
7
|
-
// shared dashboard's `admin` role means "may manage users".
|
|
7
|
+
// shared dashboard's `admin` role means "may manage users". Users, roles and their
|
|
8
|
+
// permissions are the dashboard package's (auth.ts); this module says what they allow here.
|
|
8
9
|
|
|
9
10
|
import { createAuthorizer } from '@cossackframework/auth';
|
|
10
|
-
import {
|
|
11
|
+
import { PERMISSIONS } from '@cossackframework/cms';
|
|
11
12
|
import { isTransportPath } from '@cossackframework/core/transport-routes';
|
|
12
13
|
import type { PublicUser } from '../auth';
|
|
14
|
+
import { holds, holdsAll } from '../lib/permissions';
|
|
13
15
|
import type { MiddlewareHandler } from 'hono';
|
|
14
16
|
|
|
15
|
-
export type { RoleAssignment } from '
|
|
17
|
+
export type { RoleAssignment } from '@/models/User';
|
|
18
|
+
|
|
19
|
+
/** The ID of the role whose holders may do everything. It cannot be changed or deleted. */
|
|
20
|
+
export const ADMIN_ROLE = 'admin';
|
|
21
|
+
|
|
22
|
+
/** The permission patterns a user holds, from every role. A network administrator holds everything. */
|
|
23
|
+
export function permissionsOf(user: { roles: readonly { id?: string; name: string; permissions: readonly string[] }[]; networkAdmin?: boolean } | null | undefined): string[] {
|
|
24
|
+
if (!user) return [];
|
|
25
|
+
if (user.networkAdmin || user.roles.some(role => role.id === ADMIN_ROLE)) return ['*'];
|
|
26
|
+
return [...new Set(user.roles.flatMap(role => role.permissions))];
|
|
27
|
+
}
|
|
16
28
|
|
|
17
29
|
export const guard = createAuthorizer<PublicUser>({
|
|
18
|
-
hasRole: (user, role) => role === 'admin' ?
|
|
19
|
-
hasPermission: (user, permission) =>
|
|
30
|
+
hasRole: (user, role) => role === 'admin' ? holds(permissionsOf(user), PERMISSIONS.manageUsers) : user.roles.some(entry => entry.id === role || entry.name === role),
|
|
31
|
+
hasPermission: (user, permission) => holds(permissionsOf(user), permission),
|
|
20
32
|
// Unauthenticated → login page. Forbidden → the dashboard, friendlier than a bare 403.
|
|
21
33
|
onUnauthorized: (c, reason) => {
|
|
22
34
|
if (isTransportPath(c.req.path, 'rpc', 'upload', 'websocket')) {
|
|
@@ -29,18 +41,17 @@ export const guard = createAuthorizer<PublicUser>({
|
|
|
29
41
|
|
|
30
42
|
/** Who may define roles and choose users' roles: holders of `cms:roles`, administrators by default. */
|
|
31
43
|
export function canAssignRoles(user: PublicUser | null | undefined): boolean {
|
|
32
|
-
return
|
|
44
|
+
return holds(permissionsOf(user), PERMISSIONS.manageRoles);
|
|
33
45
|
}
|
|
34
46
|
|
|
35
47
|
/**
|
|
36
48
|
* Who may see and end a user's sessions and application passwords: the user, and role managers
|
|
37
|
-
* who may change the account
|
|
38
|
-
*
|
|
49
|
+
* who may change the account, so nobody mints a token for a stronger account or reads and ends
|
|
50
|
+
* its sessions. An account shared with other sites (`lockedProfile`) stays with its owner.
|
|
39
51
|
*/
|
|
40
|
-
export function canManageAccess(user: PublicUser | null | undefined, target: { id: string; roles: readonly { permissions: readonly string[] }[]; networkAdmin?: boolean; lockedProfile?: string }): boolean {
|
|
52
|
+
export function canManageAccess(user: PublicUser | null | undefined, target: { id: string; roles: readonly { name?: string; permissions: readonly string[] }[]; networkAdmin?: boolean; lockedProfile?: string }): boolean {
|
|
41
53
|
if (!user) return false;
|
|
42
54
|
if (user.id === target.id) return true;
|
|
43
|
-
// A network account this request may not change (`manageableHere`): its sessions show where it signs in on every site.
|
|
44
55
|
if (target.lockedProfile) return false;
|
|
45
56
|
return canAssignRoles(user) && canManageUser(user, target);
|
|
46
57
|
}
|
|
@@ -51,15 +62,15 @@ export const requireRoleManager: MiddlewareHandler = guard.requirePermission(PER
|
|
|
51
62
|
/**
|
|
52
63
|
* Whether the user may change another account: one whose roles hold no permission the user
|
|
53
64
|
* lacks, so nobody takes over a stronger account by setting its password or email; a network
|
|
54
|
-
*
|
|
65
|
+
* administrator's account stays with network administrators.
|
|
55
66
|
*/
|
|
56
|
-
export function canManageUser(user: PublicUser | null | undefined, target: { roles: readonly { permissions
|
|
67
|
+
export function canManageUser(user: PublicUser | null | undefined, target: { roles: readonly { name?: string; permissions?: readonly string[] }[]; networkAdmin?: boolean }): boolean {
|
|
57
68
|
if (!user) return false;
|
|
58
|
-
if (target.networkAdmin && !
|
|
59
|
-
return holdsAll(user
|
|
69
|
+
if (target.networkAdmin && !user.networkAdmin) return false;
|
|
70
|
+
return holdsAll(permissionsOf(user), target.roles.flatMap(role => role.permissions ?? []));
|
|
60
71
|
}
|
|
61
72
|
|
|
62
73
|
/** Whether the user may give these roles: a role manager, holding every permission the roles hold. */
|
|
63
74
|
export function canGrantRoles(user: PublicUser | null | undefined, roles: readonly { permissions: readonly string[] }[]): boolean {
|
|
64
|
-
return canAssignRoles(user) && holdsAll(user
|
|
75
|
+
return canAssignRoles(user) && holdsAll(permissionsOf(user), roles.flatMap(role => role.permissions));
|
|
65
76
|
}
|