@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.
Files changed (120) hide show
  1. package/agent-docs.json +8 -8
  2. package/app/cossack-recipe.json +12 -8
  3. package/app/src/auth-events.ts +33 -0
  4. package/app/src/auth-input.ts +3 -0
  5. package/app/src/auth-options.ts +39 -7
  6. package/app/src/auth.ts +1309 -641
  7. package/app/src/avatars.ts +13 -0
  8. package/app/src/brand.ts +24 -2
  9. package/app/src/cms/actor.ts +13 -0
  10. package/app/src/cms/collab/room.ts +1 -1
  11. package/app/src/cms/content-api.ts +2 -1
  12. package/app/src/cms/content.ts +3 -2
  13. package/app/src/cms/dev-mail.ts +77 -0
  14. package/app/src/cms/index.ts +37 -10
  15. package/app/src/cms/maintenance.ts +1 -6
  16. package/app/src/cms/manage.ts +17 -14
  17. package/app/src/cms/middleware.ts +58 -18
  18. package/app/src/cms/network-accounts.ts +110 -0
  19. package/app/src/cms/notes-announce.ts +1 -1
  20. package/app/src/cms/people.ts +177 -0
  21. package/app/src/cms/recovery.ts +9 -14
  22. package/app/src/cms/request-calls.ts +56 -0
  23. package/app/src/cms/settings-form.ts +23 -6
  24. package/app/src/cms/settings-network.ts +8 -4
  25. package/app/src/cms/settings-search.ts +1 -0
  26. package/app/src/cms/site-editing.ts +3 -2
  27. package/app/src/cms/site-registration.ts +64 -0
  28. package/app/src/cms/site.ts +30 -19
  29. package/app/src/cms/sites.ts +182 -0
  30. package/app/src/dashboard/access.ts +3 -2
  31. package/app/src/dashboard/modules/users.ts +1 -0
  32. package/app/src/lib/permissions.ts +24 -0
  33. package/app/src/lib/uuid.ts +6 -0
  34. package/app/src/mail.ts +15 -0
  35. package/app/src/middlewares/auth.ts +6 -2
  36. package/app/src/middlewares/tenant.ts +108 -0
  37. package/app/src/pages/(site)/[...path]/index.ts +1 -1
  38. package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +1 -1
  39. package/app/src/pages/api/cms/dev/mail.ts +19 -0
  40. package/app/src/pages/api/cms/forms/[slug]/index.ts +1 -1
  41. package/app/src/pages/api/cms/users/[id]/meta.ts +2 -1
  42. package/app/src/pages/auth/login/index.ts +1 -1
  43. package/app/src/pages/auth/magic/index.ts +1 -1
  44. package/app/src/pages/auth/recovery.ts +20 -0
  45. package/app/src/pages/auth/register-site/index.ts +146 -0
  46. package/app/src/pages/auth/setup/index.ts +8 -3
  47. package/app/src/pages/auth/tenant/callback.ts +23 -0
  48. package/app/src/pages/auth/tenant/redirect.ts +91 -0
  49. package/app/src/pages/auth/verify/index.ts +3 -7
  50. package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +1 -1
  51. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +5 -5
  52. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +1 -1
  53. package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +1 -1
  54. package/app/src/pages/dashboard/(cms)/network/index.ts +4 -2
  55. package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +16 -13
  56. package/app/src/pages/dashboard/(cms)/network/sites/index.ts +4 -2
  57. package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +1 -1
  58. package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +29 -10
  59. package/app/src/pages/dashboard/(cms)/network/users/index.ts +8 -7
  60. package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +2 -1
  61. package/app/src/pages/dashboard/(cms)/registrations/index.ts +5 -4
  62. package/app/src/pages/dashboard/(cms)/tools/health/index.ts +4 -1
  63. package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +2 -1
  64. package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +1 -1
  65. package/app/src/pages/dashboard/index.ts +3 -2
  66. package/app/src/pages/dashboard/roles/index.ts +2 -2
  67. package/app/src/pages/dashboard/users/registrations/index.ts +66 -0
  68. package/app/src/services/api-tokens.ts +86 -0
  69. package/app/src/services/rbac.ts +26 -15
  70. package/app/src/services/roles.ts +125 -35
  71. package/app/src/services/security.ts +384 -0
  72. package/app/src/services/tenants.ts +447 -0
  73. package/app/src/services/users.ts +241 -97
  74. package/app/src/tenants.ts +219 -0
  75. package/package.json +48 -12
  76. package/src/block-references.ts +3 -3
  77. package/src/collections.ts +3 -1
  78. package/src/forms.ts +4 -2
  79. package/src/hooks.ts +19 -1
  80. package/src/index.ts +4 -4
  81. package/src/isolate-core.ts +1 -1
  82. package/src/isolation.ts +1 -0
  83. package/src/manifest.ts +43 -2
  84. package/src/permissions.ts +13 -7
  85. package/src/resource.ts +85 -2
  86. package/src/server/attempts.ts +64 -0
  87. package/src/server/automations.ts +2 -2
  88. package/src/server/batch.ts +106 -0
  89. package/src/server/budget.ts +17 -0
  90. package/src/server/field-values.ts +207 -0
  91. package/src/server/forms.ts +3 -3
  92. package/src/server/host-schema.ts +55 -7
  93. package/src/server/host.ts +213 -85
  94. package/src/server/index.ts +9 -14
  95. package/src/server/isolation.ts +10 -0
  96. package/src/server/network.ts +129 -44
  97. package/src/server/outbox.ts +2 -2
  98. package/src/server/people.ts +191 -0
  99. package/src/server/reconcile.ts +5 -5
  100. package/src/server/repository.ts +243 -84
  101. package/src/server/shared-read.ts +34 -0
  102. package/src/server/site-export.ts +23 -13
  103. package/src/server/site-import.ts +12 -33
  104. package/src/server/site-settings.ts +9 -3
  105. package/src/server/sites.ts +117 -187
  106. package/src/server/stores.ts +3 -300
  107. package/src/server/taxonomies.ts +64 -13
  108. package/src/server/users.ts +151 -498
  109. package/src/settings-controls.ts +8 -4
  110. package/src/settings.ts +26 -3
  111. package/src/storage/cloudflare.ts +2 -0
  112. package/src/storage/index.ts +6 -0
  113. package/src/theme.ts +2 -2
  114. package/src/version.ts +1 -1
  115. package/app/src/cms/handoff.ts +0 -202
  116. package/src/server/accounts.ts +0 -418
  117. package/src/server/api-tokens.ts +0 -91
  118. package/src/server/auth.ts +0 -89
  119. package/src/server/handoffs.ts +0 -107
  120. package/src/server/security.ts +0 -391
@@ -1,18 +1,22 @@
1
1
  /**
2
- * A site's users and roles on relational host tables. Each user is a member: an account, with
3
- * the account's name, email, avatar and status copied in, and the site's own roles, slug and
4
- * profile fields. Sign-in and passwords are the account's. The account is a network account
5
- * (see accounts.ts), or on an added site a site account, in the site's own database.
2
+ * A site's users. Who they are, the roles they hold and how they sign in are the
3
+ * application's, through the people port (`people.ts`): the dashboard package's accounts in a
4
+ * CMS project. The CMS keeps what is its own about a user, under the user's ID: the author
5
+ * slug (`cms_authors`) and the values of the field groups attached to users (`cms/user_fields`).
6
6
  */
7
- import { ClientError, type RomeDB, type Statement, type Value } from '@cossackframework/romedb';
8
- import { CmsError, isCmsError } from '../errors';
7
+ import { ClientError, type RomeDB, type Value } from '@cossackframework/romedb';
8
+ import { CmsError } from '../errors';
9
9
  import { SYSTEM_META } from '../field-groups';
10
10
  import { slugify } from '../fields';
11
- import { holdsAll, NETWORK_ADMIN, userPrincipal, type Principal } from '../permissions';
12
- import { parseMeta, type MetaCheck } from './taxonomies';
13
- import { ACCOUNT_ID, normalizeEmail, type AccountProfile, type CmsAccount, type CmsAccounts } from './accounts';
14
- import { MAIN_SITE } from './sites';
15
- import { readByIds, readPaged } from './budget';
11
+ import { NETWORK_ADMIN, userPrincipal, type Principal } from '../permissions';
12
+ import type { MetaCheck } from './taxonomies';
13
+ import { uniqueFieldOf, type FieldValues } from './field-values';
14
+ import { personPermissions, type PeoplePort, type Person, type PersonRole } from './people';
15
+
16
+ /** An email as accounts keep it: trimmed and lowercase. */
17
+ export function normalizeEmail(email: string): string {
18
+ return String(email ?? '').trim().toLowerCase();
19
+ }
16
20
 
17
21
  export interface CmsUser {
18
22
  readonly id: string;
@@ -51,10 +55,6 @@ export interface UserPage {
51
55
  readonly total: number;
52
56
  }
53
57
 
54
- const ID = ACCOUNT_ID;
55
- const PERMISSION = /^(?:\*|[a-z][a-z0-9:/._*-]{0,127})$/;
56
- const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
57
- const WRITE = { kind: 'cms.users', retryConflicts: 5 } as const;
58
58
 
59
59
  /** `($p0, $p1, …)` with its parameters, for a bounded `IN` list. */
60
60
  export function inList(prefix: string, values: readonly Value[]): { rql: string; params: { [key: string]: Value } } {
@@ -71,583 +71,236 @@ export function containsPattern(text: string): string {
71
71
  /** The request user: a member whose account is active, with the principal it acts as. */
72
72
  export type CmsMember = CmsUser & { readonly principal: Principal };
73
73
 
74
- /** The most users one `getMany` reads, and so the page size of `after`. */
75
- const USERS_PER_READ = 200;
74
+ const NO_VALUES: { readonly [field: string]: unknown } = Object.freeze({});
75
+ const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
76
+ const WRITE = { kind: 'cms.users', retryConflicts: 5 } as const;
77
+ const PER_READ = 200;
76
78
 
77
79
  export class CmsUsers {
78
80
  readonly #db: RomeDB;
79
- readonly #accounts: CmsAccounts;
80
- readonly #siteAccounts: CmsAccounts | null;
81
- readonly #site: string;
82
- readonly #now: () => number;
81
+ readonly #people: PeoplePort;
82
+ readonly #fields: FieldValues;
83
83
  readonly #checkMeta: MetaCheck | undefined;
84
84
 
85
- /**
86
- * `accounts` are the network's; `siteAccounts`, on an added site, its own. `site` is this
87
- * site's ID in the network (default `main`), for the network's record of memberships.
88
- */
89
- constructor(db: RomeDB, options: { accounts: CmsAccounts; siteAccounts?: CmsAccounts; site?: string; now?: () => number; checkMeta?: MetaCheck }) {
85
+ constructor(db: RomeDB, options: { people: PeoplePort; fields: FieldValues; checkMeta?: MetaCheck; now?: () => number }) {
90
86
  this.#db = db;
91
- this.#accounts = options.accounts;
92
- this.#siteAccounts = options.siteAccounts ?? null;
93
- this.#site = options.site ?? MAIN_SITE;
94
- this.#now = options.now ?? Date.now;
87
+ this.#people = options.people;
88
+ this.#fields = options.fields;
95
89
  this.#checkMeta = options.checkMeta;
96
90
  }
97
91
 
98
- /**
99
- * A new account that is a member of this site with these roles: a site account on an added
100
- * site, unless `network` asks for a network account, and a network account on the main site.
101
- */
102
- /**
103
- * Create an account and its membership. With `approval`, the account starts disabled and waits
104
- * for approval: its registrations row is written with its member row, so no failure leaves an
105
- * active account that skipped approval, or a disabled one missing from the queue.
106
- */
107
- async create(input: AccountProfile & { email: string; name: string; password?: string; roles?: readonly string[]; id?: string; meta?: unknown; networkRole?: typeof NETWORK_ADMIN; network?: boolean; status?: 'active' | 'disabled'; approval?: { verified: boolean } }): Promise<CmsUser> {
108
- const meta = await this.#meta(input.meta, null);
109
- for (const role of input.roles ?? []) if (!ID.test(role)) throw new CmsError('CMS_VALIDATION', `Invalid role ${role}.`);
110
- const store = input.network || !this.#siteAccounts ? this.#accounts : this.#siteAccounts;
111
- if (store === this.#siteAccounts && input.networkRole) throw new CmsError('CMS_VALIDATION', 'Network admins have network accounts.');
112
- // Members' emails are unique on a site, whichever kind their account is.
113
- if (await this.findByEmail(input.email).catch(() => null)) throw new CmsError('CMS_CONFLICT', 'An account with this email already exists.', { fields: { email: 'is taken.' } });
114
- const { network: _network, approval, ...profile } = input;
115
- const account = await store.create(approval ? { ...profile, status: 'disabled', held: true } : profile);
116
- try { return await this.#join(account, input.roles ?? [], meta, store === this.#accounts, approval); }
117
- catch (error) {
118
- await store.delete(account.id).catch(() => undefined);
119
- throw error;
120
- }
92
+ async #meta(meta: unknown, previous: { readonly [field: string]: unknown } | null, principal?: Principal): Promise<{ readonly [field: string]: unknown }> {
93
+ if (this.#checkMeta) return this.#checkMeta(meta, previous, principal);
94
+ if (meta === undefined) return previous ?? {};
95
+ if (meta === null || typeof meta !== 'object' || Array.isArray(meta)) throw new CmsError('CMS_VALIDATION', 'Meta must be an object of fields.', { fields: { meta: 'must be an object of fields.' } });
96
+ return { ...previous, ...(meta as { [field: string]: unknown }) };
121
97
  }
122
98
 
123
- /** Make an existing account a member of this site, with these roles. */
124
- async addMember(accountId: string, options: { roles?: readonly string[]; meta?: unknown } = {}): Promise<CmsUser | null> {
125
- const account = await this.#accounts.get(accountId);
126
- if (!account) return null;
127
- const existing = await this.get(accountId);
128
- if (existing) return existing;
129
- return this.#join(account, options.roles ?? [], await this.#meta(options.meta, null), true);
99
+ async #slugs(ids: readonly string[]): Promise<Map<string, string>> {
100
+ if (!ids.length) return new Map();
101
+ const params = Object.fromEntries(ids.map((id, index) => [`$u${index}`, id])) as { [key: string]: Value };
102
+ const result = await this.#db.read([{ rql: `SELECT user_id, slug FROM cms_authors WHERE user_id IN (${ids.map((_, index) => `$u${index}`).join(', ')})`, params }]);
103
+ return new Map(result.results[0]!.rows.map(row => [row[0] as string, row[1] as string]));
130
104
  }
131
105
 
132
- /** Copy the account in as a member with these roles. The network records the memberships of its own accounts. */
133
- async #join(account: CmsAccount, roles: readonly string[], meta: { readonly [field: string]: unknown }, network: boolean, approval?: { verified: boolean }): Promise<CmsUser> {
134
- const now = this.#now();
135
- const slug = await this.#freeSlug(account.name, account.id);
136
- try {
137
- await this.#db.write([{
138
- rql: 'INSERT INTO cms_users (id, email, name, avatar, status, created_at, updated_at, meta, slug) VALUES ($id, $email, $name, $avatar, $status, $now, $now, $meta, $slug)',
139
- params: { $id: account.id, $email: account.email, $name: account.name, $avatar: account.avatar, $status: approval ? 'disabled' : account.status, $now: now, $meta: JSON.stringify(meta), $slug: slug },
140
- }, ...roleStatements(account.id, roles),
141
- ...(approval ? [{ rql: 'INSERT INTO cms_registrations (user_id, verified, created_at) VALUES ($id, $verified, $now)', params: { $id: account.id, $verified: approval.verified ? 1 : 0, $now: now } }] : [])], WRITE);
142
- } catch (error) { throw memberError(error); }
143
- if (network) {
144
- // Without the network's record of the membership the member row is an orphan that
145
- // blocks the email: take it back out.
146
- try { await this.#accounts.join(account.id, this.#site); }
147
- catch (error) {
148
- await this.#db.write([
149
- { rql: 'DELETE FROM cms_registrations WHERE user_id = $id', params: { $id: account.id } },
150
- { rql: 'DELETE FROM cms_user_roles WHERE user_id = $id', params: { $id: account.id } },
151
- { rql: 'DELETE FROM cms_users WHERE id = $id', params: { $id: account.id } },
152
- ], WRITE).catch(() => undefined);
153
- throw error;
154
- }
155
- }
156
- return (await this.get(account.id))!;
106
+ /** A slug from the text, made unique among authors other than `id` by a numeric suffix. */
107
+ async #freeSlug(text: string, id: string): Promise<string> {
108
+ const base = slugify(String(text ?? ''), 60) || 'author';
109
+ const result = await this.#db.read([{ rql: "SELECT slug FROM cms_authors WHERE user_id <> $id AND (slug = $slug OR slug LIKE $prefix ESCAPE '\\') LIMIT 1000",
110
+ params: { $id: id, $slug: base, $prefix: `${base.replace(/[\\%_]/g, character => `\\${character}`)}-%` } }]);
111
+ const taken = new Set(result.results[0]!.rows.map(row => row[0] as string));
112
+ if (!taken.has(base)) return base;
113
+ for (let n = 2; n < 10_000; n++) if (!taken.has(`${base}-${n}`)) return `${base}-${n}`;
114
+ return `${base}-${crypto.randomUUID().slice(0, 8)}`;
157
115
  }
158
116
 
159
- /** The meta to store: the field groups' check, or the input as given when users have no groups. */
160
- async #meta(meta: unknown, previous: { readonly [field: string]: unknown } | null, principal?: Principal): Promise<{ readonly [field: string]: unknown }> {
161
- if (this.#checkMeta) return this.#checkMeta(meta, previous, principal);
162
- if (meta === undefined) return previous ?? {};
163
- if (meta === null || typeof meta !== 'object' || Array.isArray(meta)) throw new CmsError('CMS_VALIDATION', 'Meta must be an object of fields.', { fields: { meta: 'must be an object of fields.' } });
164
- return { ...previous, ...(meta as { [field: string]: unknown }) };
117
+ #user(person: Person, meta: { readonly [field: string]: unknown }, slug: string | null): CmsUser {
118
+ const assignments = [...person.roles].sort((a, b) => a.id < b.id ? -1 : 1);
119
+ return Object.freeze({
120
+ id: person.id, email: person.email, name: person.name, avatar: person.avatar, status: person.status,
121
+ createdAt: person.createdAt, lastSignInAt: person.lastSignInAt, meta, slug,
122
+ roles: Object.freeze(assignments.map(role => role.id)), assignments: Object.freeze(assignments),
123
+ permissions: Object.freeze([...new Set(assignments.flatMap(role => role.permissions))].sort()),
124
+ account: person.account,
125
+ });
126
+ }
127
+
128
+ async #users(people: ReadonlyMap<string, Person>): Promise<Map<string, CmsUser>> {
129
+ const ids = [...people.keys()];
130
+ const [values, slugs] = await Promise.all([ids.length ? this.#fields.read(ids) : new Map<string, { readonly [field: string]: unknown }>(), this.#slugs(ids)]);
131
+ return new Map(ids.map(id => [id, this.#user(people.get(id)!, values.get(id) ?? NO_VALUES, slugs.get(id) ?? null)]));
165
132
  }
166
133
 
167
134
  async get(id: string): Promise<CmsUser | null> {
168
- if (!ID.test(id)) return null;
169
135
  return (await this.getMany([id])).get(id) ?? null;
170
136
  }
171
137
 
172
- /** Users by ID, in reads that fit the result budget. Missing IDs are absent from the map. */
173
138
  async getMany(ids: readonly string[]): Promise<Map<string, CmsUser>> {
174
- const wanted = [...new Set(ids.filter(id => ID.test(id)))].slice(0, USERS_PER_READ);
139
+ const wanted = [...new Set(ids.filter(id => typeof id === 'string' && id.length > 0))].slice(0, PER_READ);
175
140
  if (!wanted.length) return new Map();
176
- const list = inList('u', wanted);
177
- // Profiles hold their meta (bio, links) and roles their permission lists: many may come in smaller reads.
178
- // The users, which roles they hold, and those roles are read side by side, not one after another.
179
- const [userRows, result, roleRows] = await Promise.all([
180
- readByIds(this.#db, wanted, slice => {
181
- const part = inList('u', slice);
182
- return { rql: `SELECT id, email, name, avatar, status, created_at, last_sign_in_at, meta, slug FROM cms_users WHERE id IN ${part.rql}`, params: part.params };
183
- }),
184
- this.#db.read([
185
- // network_admin comes from the account alone (resolve): a site role row of that name, as a crafted import could add, grants nothing.
186
- { rql: `SELECT user_id, role_id FROM cms_user_roles WHERE user_id IN ${list.rql} AND role_id <> $networkAdmin ORDER BY role_id`, params: { ...list.params, $networkAdmin: NETWORK_ADMIN } },
187
- // On an added site, accounts in its own database are site accounts.
188
- ...(this.#siteAccounts ? [{ rql: `SELECT id FROM cms_accounts WHERE id IN ${list.rql}`, params: list.params }] : []),
189
- ]),
190
- // Each role's permissions come once, not once per user who holds it.
191
- readPaged(this.#db, (size, at) => ({
192
- rql: `SELECT id, name, permissions FROM cms_roles WHERE id IN (SELECT role_id FROM cms_user_roles WHERE user_id IN ${list.rql} AND role_id <> $networkAdmin) ORDER BY id LIMIT $limit OFFSET $offset`,
193
- params: { ...list.params, $networkAdmin: NETWORK_ADMIN, $limit: size, $offset: at },
194
- }), 1000, 0),
195
- ]);
196
- const local = new Set((result.results[1]?.rows ?? []).map(row => row[0] as string));
197
- const pairs = result.results[0]!.rows.map(([user, role]) => [user as string, role as string] as const);
198
- const byId = new Map(roleRows.map(([id, name, permissions]) => [id as string, Object.freeze({ id: id as string, name: name as string, permissions: Object.freeze(JSON.parse(permissions as string) as string[]) })]));
199
- const roles = new Map<string, CmsUser['assignments'][number][]>();
200
- for (const [user, role] of pairs) {
201
- const assignment = byId.get(role);
202
- if (!assignment) continue;
203
- const entry = roles.get(user) ?? [];
204
- entry.push(assignment);
205
- roles.set(user, entry);
206
- }
207
- const users = new Map<string, CmsUser>();
208
- for (const row of userRows) {
209
- const assignments = roles.get(row[0] as string) ?? [];
210
- users.set(row[0] as string, Object.freeze({
211
- id: row[0] as string, email: row[1] as string, name: row[2] as string, avatar: row[3] as string | null,
212
- status: row[4] as CmsUser['status'], createdAt: Number(row[5] as bigint), lastSignInAt: row[6] === null ? null : Number(row[6] as bigint), meta: parseMeta(row[7]), slug: (row[8] as string | null) ?? null,
213
- roles: Object.freeze(assignments.map(role => role.id)), assignments: Object.freeze(assignments),
214
- permissions: Object.freeze([...new Set(assignments.flatMap(role => role.permissions))].sort()),
215
- account: local.has(row[0] as string) ? 'site' : 'network',
216
- }));
217
- }
218
- return users;
141
+ return this.#users(await this.#people.getMany(wanted));
219
142
  }
220
143
 
221
- /** Users whose avatar is this media file or whose profile fields name it, newest first, 50 at most. */
222
- async usingFile(fileId: string): Promise<CmsUser[]> {
223
- if (!ID.test(fileId)) return [];
224
- const escaped = fileId.replace(/[\\%_]/g, character => `\\${character}`);
225
- const result = await this.#db.read([{
226
- rql: "SELECT id FROM cms_users WHERE avatar LIKE $avatar ESCAPE '\\' OR meta LIKE $meta ESCAPE '\\' ORDER BY created_at DESC LIMIT 50",
227
- params: { $avatar: `/media/${escaped}/%`, $meta: `%"${escaped}"%` },
228
- }]);
229
- const ids = result.results[0]!.rows.map(row => row[0] as string);
230
- const users = await this.getMany(ids);
231
- return ids.map(id => users.get(id)).filter((user): user is CmsUser => user !== undefined);
144
+ async findByEmail(email: string): Promise<CmsUser | null> {
145
+ const person = await this.#people.findByEmail(email);
146
+ return person ? (await this.#users(new Map([[person.id, person]]))).get(person.id)! : null;
232
147
  }
233
148
 
234
- async findByEmail(email: string): Promise<CmsUser | null> {
235
- const result = await this.#db.read([{ rql: 'SELECT id FROM cms_users WHERE email = $email', params: { $email: normalizeEmail(email) } }]);
236
- const id = result.results[0]!.rows[0]?.[0] as string | undefined;
237
- return id ? this.get(id) : null;
149
+ async list(options: { search?: string; role?: string; limit?: number; offset?: number } = {}): Promise<UserPage> {
150
+ const page = await this.#people.list({ ...options, limit: Math.min(Math.max(options.limit ?? 20, 1), 100) });
151
+ const users = await this.#users(new Map(page.users.map(person => [person.id, person])));
152
+ return { items: page.users.map(person => users.get(person.id)!), total: page.total };
238
153
  }
239
154
 
240
- /**
241
- * Every user, by ID, a page after the cursor of the one before: for work that goes through them
242
- * all. `next` is the last ID read (null once there are no more), so a page whose rows don't all
243
- * resolve to a user still moves on.
244
- */
245
- async after(after: string | null, limit = 100): Promise<{ users: CmsUser[]; next: string | null }> {
246
- const size = Math.min(Math.max(limit, 1), USERS_PER_READ);
247
- const result = await this.#db.read([{
248
- rql: `SELECT id FROM cms_users${after === null ? '' : ' WHERE id > $after'} ORDER BY id LIMIT $limit`,
249
- params: { ...(after === null ? {} : { $after: after }), $limit: size },
250
- }]);
251
- const ids = result.results[0]!.rows.map(row => row[0] as string);
155
+ async count(): Promise<number> { return this.#people.count(); }
156
+
157
+ /** The file IDs users' profile fields name. A picture a user uploaded as an avatar is the application's to find. */
158
+ async usingFile(fileId: string): Promise<CmsUser[]> {
159
+ const ids = (await this.#fields.usingFile(fileId)).slice(0, 50);
252
160
  const users = await this.getMany(ids);
253
- return {
254
- users: ids.map(id => users.get(id)).filter((user): user is CmsUser => user !== undefined),
255
- next: ids.length === size ? ids[ids.length - 1]! : null,
256
- };
161
+ return ids.map(id => users.get(id)).filter((user): user is CmsUser => user !== undefined);
257
162
  }
258
163
 
259
- /** Newest first. `search` matches name or email; `role` limits to one role ID. */
260
- async list(options: { search?: string; role?: string; limit?: number; offset?: number } = {}): Promise<UserPage> {
261
- const limit = Math.min(Math.max(options.limit ?? 20, 1), 100);
262
- const offset = Math.min(Math.max(options.offset ?? 0, 0), 100_000);
263
- const conditions: string[] = [];
264
- const params: { [key: string]: Value } = {};
265
- if (options.search?.trim()) {
266
- conditions.push("(lower(name) LIKE $q ESCAPE '\\' OR email LIKE $q ESCAPE '\\')");
267
- params.$q = containsPattern(options.search.trim().slice(0, 100));
268
- }
269
- if (options.role) {
270
- conditions.push('id IN (SELECT user_id FROM cms_user_roles WHERE role_id = $role)');
271
- params.$role = options.role;
164
+ async create(input: { email: string; name: string; password?: string; roles?: readonly string[]; id?: string; meta?: unknown }): Promise<CmsUser> {
165
+ const meta = await this.#meta(input.meta, null);
166
+ const person = await this.#people.create({ email: input.email, name: input.name, ...(input.password === undefined ? {} : { password: input.password }), ...(input.roles ? { roles: input.roles } : {}), ...(input.id ? { id: input.id } : {}) });
167
+ try {
168
+ await this.#db.write([
169
+ { rql: 'INSERT INTO cms_authors (user_id, slug) VALUES ($id, $slug)', params: { $id: person.id, $slug: await this.#freeSlug(person.name, person.id) } },
170
+ ...this.#fields.save(person.id, meta, null, crypto.randomUUID()),
171
+ ], WRITE);
172
+ } catch (error) {
173
+ // Without their document the user would be half made: take the account back out.
174
+ await this.#people.delete(person.id).catch(() => undefined);
175
+ throw fieldError(error);
272
176
  }
273
- const where = conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '';
274
- const result = await this.#db.read([
275
- { rql: `SELECT id FROM cms_users${where} ORDER BY created_at DESC, id DESC LIMIT $limit OFFSET $offset`, params: { ...params, $limit: limit, $offset: offset } },
276
- conditions.length ? { rql: `SELECT count(*) FROM cms_users${where}`, params } : { rql: 'SELECT count(*) FROM cms_users' },
277
- ]);
278
- const ids = result.results[0]!.rows.map(row => row[0] as string);
279
- const users = await this.getMany(ids);
280
- return { items: ids.map(id => users.get(id)).filter((user): user is CmsUser => user !== undefined), total: Number(result.results[1]!.rows[0]![0] as bigint) };
177
+ return (await this.get(person.id))!;
281
178
  }
282
179
 
283
- /**
284
- * Change the name, email or avatar (on the account first, then the copy here), the profile
285
- * meta or the author slug.
286
- */
287
- async update(id: string, patch: AccountProfile & { meta?: unknown; slug?: string }, options: { principal?: Principal } = {}): Promise<boolean> {
180
+ async update(id: string, patch: { name?: string; email?: string; avatar?: string | null; meta?: unknown; slug?: string }, options: { principal?: Principal } = {}): Promise<boolean> {
288
181
  const current = await this.get(id);
289
182
  if (!current) return false;
290
183
  const meta = patch.meta === undefined ? current.meta : await this.#meta(patch.meta, current.meta, options.principal);
291
- const profile = patch.name !== undefined || patch.email !== undefined || patch.avatar !== undefined
292
- ? await this.#store(current).update(id, { ...(patch.name === undefined ? {} : { name: patch.name }), ...(patch.email === undefined ? {} : { email: patch.email }), ...(patch.avatar === undefined ? {} : { avatar: patch.avatar }) })
293
- : current;
294
- if (!profile) return false;
295
- // A slug is chosen once, from the name, and kept: author URLs stay stable through renames. A given slug is checked and made unique.
296
- const slug = patch.slug !== undefined ? await this.#freeSlug(patch.slug, id) : current.slug ?? await this.#freeSlug(profile.name, id);
184
+ if (patch.avatar !== undefined && patch.avatar !== null && (typeof patch.avatar !== 'string' || patch.avatar.length > 2048 || !/^(?:https:\/\/|\/)[^\s]*$/.test(patch.avatar))) {
185
+ throw new CmsError('CMS_VALIDATION', 'The avatar must be an https URL or a site path.', { fields: { avatar: 'is invalid.' } });
186
+ }
187
+ if (patch.name !== undefined || patch.email !== undefined || patch.avatar !== undefined) {
188
+ const { meta: _meta, slug: _slug, ...profile } = patch;
189
+ if (!await this.#people.update(id, profile)) return false;
190
+ }
191
+ // A slug is chosen once, from the name, and kept: author URLs stay stable through renames.
192
+ const slug = patch.slug !== undefined ? await this.#freeSlug(patch.slug, id) : current.slug ?? await this.#freeSlug(patch.name ?? current.name, id);
297
193
  try {
298
- const result = await this.#db.write([{ rql: 'UPDATE cms_users SET name = $name, email = $email, avatar = $avatar, meta = $meta, slug = $slug, updated_at = $now WHERE id = $id',
299
- params: { $name: profile.name, $email: profile.email, $avatar: profile.avatar, $meta: JSON.stringify(meta), $slug: slug, $now: this.#now(), $id: id } }], WRITE);
300
- return result.results[0]!.affected === 1n;
301
- } catch (error) { throw memberError(error); }
194
+ await this.#db.write([
195
+ { rql: 'INSERT INTO cms_authors (user_id, slug) VALUES ($id, $slug) ON CONFLICT (user_id) DO UPDATE SET slug = excluded.slug', params: { $id: id, $slug: slug } },
196
+ ...(patch.meta === undefined ? [] : this.#fields.save(id, meta, current.meta, crypto.randomUUID())),
197
+ ], WRITE);
198
+ } catch (error) { throw fieldError(error); }
199
+ return true;
302
200
  }
303
201
 
304
- /**
305
- * Keep a value of the host's own in the user's meta, such as `_recent_blocks`, beside the
306
- * profile fields and without their checks; null removes it. False when there is no such user.
307
- */
308
202
  async setSystemMeta(id: string, key: string, value: unknown): Promise<boolean> {
309
203
  if (!SYSTEM_META.test(key)) throw new CmsError('CMS_VALIDATION', `${key} is not a system meta key.`);
310
- const current = await this.get(id);
311
- if (!current) return false;
312
- const meta: { [field: string]: unknown } = { ...current.meta, [key]: value };
313
- if (value === null || value === undefined) delete meta[key];
314
- const json = JSON.stringify(meta);
315
- if (json.length > 256 * 1024) throw new CmsError('CMS_LIMIT', 'The user\'s meta is too large.');
316
- const result = await this.#db.write([{ rql: 'UPDATE cms_users SET meta = $meta WHERE id = $id', params: { $meta: json, $id: id } }], WRITE);
317
- return result.results[0]!.affected === 1n;
204
+ if (value !== null && value !== undefined && JSON.stringify(value).length > 256 * 1024) throw new CmsError('CMS_LIMIT', 'The value is too large.');
205
+ if (!(await this.#people.getMany([id])).has(id)) return false;
206
+ await this.#db.write(this.#fields.setOne(id, key, value, crypto.randomUUID()), WRITE);
207
+ return true;
318
208
  }
319
209
 
320
- /** The user with this author slug, or null. */
321
210
  async bySlug(slug: string): Promise<CmsUser | null> {
322
211
  if (!SLUG.test(slug)) return null;
323
- const result = await this.#db.read([{ rql: 'SELECT id FROM cms_users WHERE slug = $slug LIMIT 1', params: { $slug: slug } }]);
212
+ const result = await this.#db.read([{ rql: 'SELECT user_id FROM cms_authors WHERE slug = $slug LIMIT 1', params: { $slug: slug } }]);
324
213
  const id = result.results[0]!.rows[0]?.[0] as string | undefined;
325
214
  return id ? this.get(id) : null;
326
215
  }
327
216
 
328
- /**
329
- * These users with slugs: users from before author pages get one from their name, written
330
- * once. For the site's pages, which link authors; dashboards read `slug` as is.
331
- */
332
217
  async withSlugs(users: ReadonlyMap<string, CmsUser>): Promise<Map<string, CmsUser>> {
333
218
  const result = new Map(users);
334
219
  for (const [id, user] of users) {
335
220
  if (user.slug) continue;
336
221
  const slug = await this.#freeSlug(user.name, id);
337
- await this.#db.write([{ rql: 'UPDATE cms_users SET slug = $slug WHERE id = $id AND slug IS NULL', params: { $slug: slug, $id: id } }], WRITE).catch(() => undefined);
222
+ await this.#db.write([{ rql: 'INSERT INTO cms_authors (user_id, slug) VALUES ($id, $slug) ON CONFLICT (user_id) DO NOTHING', params: { $id: id, $slug: slug } }], WRITE).catch(() => undefined);
338
223
  result.set(id, Object.freeze({ ...user, slug }));
339
224
  }
340
225
  return result;
341
226
  }
342
227
 
343
- /** Users who own entries, for author sitemaps and lists: those with a slug, oldest first. */
228
+ /** Users who have an author page, oldest slug first; only the active ones. */
344
229
  async authors(options: { limit?: number; offset?: number } = {}): Promise<CmsUser[]> {
345
230
  const limit = Math.min(Math.max(options.limit ?? 200, 1), 1000);
346
- const result = await this.#db.read([{ rql: 'SELECT id FROM cms_users WHERE slug IS NOT NULL AND status = $active ORDER BY created_at, id LIMIT $limit OFFSET $offset', params: { $active: 'active', $limit: limit, $offset: Math.max(options.offset ?? 0, 0) } }]);
231
+ const result = await this.#db.read([{ rql: 'SELECT user_id FROM cms_authors ORDER BY rowid LIMIT $limit OFFSET $offset', params: { $limit: limit, $offset: Math.max(options.offset ?? 0, 0) } }]);
347
232
  const ids = result.results[0]!.rows.map(row => row[0] as string);
348
- const users = await this.getMany(ids);
349
- return ids.map(id => users.get(id)).filter((user): user is CmsUser => user !== undefined);
350
- }
351
-
352
- /** A slug from the text, made unique among users other than `id` by a numeric suffix. */
353
- async #freeSlug(text: string, id: string): Promise<string> {
354
- const base = slugify(String(text ?? ''), 60) || 'author';
355
- const result = await this.#db.read([{ rql: "SELECT slug FROM cms_users WHERE id <> $id AND (slug = $slug OR slug LIKE $prefix ESCAPE '\\') LIMIT 1000", params: { $id: id, $slug: base, $prefix: `${base.replace(/[\\%_]/g, character => `\\${character}`)}-%` } }]);
356
- const taken = new Set(result.results[0]!.rows.map(row => row[0] as string));
357
- if (!taken.has(base)) return base;
358
- for (let n = 2; n < 10_000; n++) if (!taken.has(`${base}-${n}`)) return `${base}-${n}`;
359
- return `${base}-${crypto.randomUUID().slice(0, 8)}`;
233
+ const found = new Map<string, CmsUser>();
234
+ for (let at = 0; at < ids.length; at += PER_READ) for (const [id, user] of await this.getMany(ids.slice(at, at + PER_READ))) found.set(id, user);
235
+ return ids.map(id => found.get(id)).filter((user): user is CmsUser => user !== undefined && user.status === 'active');
360
236
  }
361
237
 
362
- /**
363
- * Remove the member and their roles from this site. A network account stays, unless it was
364
- * made for a registration turned down here; a site account is deleted with what signs it
365
- * in. Their records keep their owner ID.
366
- */
367
238
  async delete(id: string): Promise<boolean> {
368
- if (!ID.test(id)) return false;
369
- const user = await this.get(id);
370
- const params = { $id: id };
371
- const result = await this.#db.write([
372
- { rql: 'DELETE FROM cms_user_roles WHERE user_id = $id', params },
373
- { rql: 'DELETE FROM cms_users WHERE id = $id', params },
374
- { rql: 'DELETE FROM cms_registrations WHERE user_id = $id', params },
375
- ], WRITE);
376
- if (user?.account === 'site') await this.#siteAccounts!.delete(id);
377
- else {
378
- await this.#accounts.leave(id, this.#site);
379
- // A turned-down registration: the account was made for it, never used, and belongs to
380
- // no other site, so it goes too, and the email can register again. The delete checks
381
- // all of that itself, so a site adding the account meanwhile keeps it.
382
- if (result.results[2]!.affected === 1n) await this.#accounts.deleteUnused(id);
383
- }
384
- return result.results[1]!.affected === 1n;
385
- }
386
-
387
- /** Whether a member waits for approval. */
388
- async awaitingApproval(id: string): Promise<boolean> {
389
- const result = await this.#db.read([{ rql: 'SELECT user_id FROM cms_registrations WHERE user_id = $id', params: { $id: id } }]);
390
- return result.results[0]!.rows.length > 0;
391
- }
392
-
393
- /** A held member opened their email link: they still wait for approval. */
394
- async confirmRegistration(id: string): Promise<boolean> {
395
- const result = await this.#db.write([{ rql: 'UPDATE cms_registrations SET verified = 1 WHERE user_id = $id', params: { $id: id } }], WRITE);
396
- return result.results[0]!.affected === 1n;
397
- }
398
-
399
- /** Members waiting for approval, oldest first, with whether their email is confirmed. */
400
- async registrations(options: { limit?: number } = {}): Promise<{ user: CmsUser; verified: boolean; createdAt: number }[]> {
401
- const result = await this.#db.read([{ rql: 'SELECT user_id, verified, created_at FROM cms_registrations ORDER BY created_at, user_id LIMIT $limit', params: { $limit: Math.min(Math.max(options.limit ?? 50, 1), 200) } }]);
402
- const rows = result.results[0]!.rows;
403
- const users = await Promise.all(rows.map(([id]) => this.get(String(id))));
404
- return rows.flatMap(([, verified, createdAt], index) => users[index] ? [{ user: users[index]!, verified: Number(verified as bigint) === 1, createdAt: Number(createdAt as bigint) }] : []);
405
- }
406
-
407
- /** How many members wait for approval. */
408
- async registrationCount(): Promise<number> {
409
- const result = await this.#db.read([{ rql: 'SELECT count(*) FROM cms_registrations' }]);
410
- return Number(result.results[0]!.rows[0]![0] as bigint);
411
- }
412
-
413
- /**
414
- * Approve a held member: their account is active, once their email is confirmed. False when
415
- * they were not waiting; `CMS_VALIDATION` while their email link was not opened yet.
416
- */
417
- async approve(id: string): Promise<boolean> {
418
- const result = await this.#db.read([{ rql: 'SELECT verified FROM cms_registrations WHERE user_id = $id', params: { $id: id } }]);
419
- const row = result.results[0]!.rows[0];
420
- if (!row) return false;
421
- if (Number(row[0] as bigint) !== 1) throw new CmsError('CMS_VALIDATION', 'This member has not confirmed their email address yet.');
422
- // Active first, then out of the queue: a failure between the two leaves the member
423
- // waiting, and approving again finishes it.
424
- if (!(await this.setStatus(id, 'active'))) return false;
425
- await this.#db.write([{ rql: 'DELETE FROM cms_registrations WHERE user_id = $id', params: { $id: id } }], WRITE);
239
+ if (!await this.#people.delete(id)) return false;
240
+ await this.#db.write([{ rql: 'DELETE FROM cms_authors WHERE user_id = $id', params: { $id: id } }, this.#fields.remove(id)], WRITE);
426
241
  return true;
427
242
  }
428
243
 
429
- /**
430
- * Make a member's site account a network account, or a network account a site account of
431
- * this site, under the same ID: roles, profile and authorship stay. Only on an added site. A
432
- * network account must belong to this site alone and not run the network. The account's
433
- * sessions end, and its passkeys go with the host they were made on.
434
- */
435
- async convert(id: string, to: 'site' | 'network'): Promise<CmsUser> {
436
- if (!this.#siteAccounts) throw new CmsError('CMS_VALIDATION', 'Only added sites have site accounts.');
437
- const user = await this.get(id);
438
- if (!user) throw new CmsError('CMS_NOT_FOUND', 'There is no such member.');
439
- if (to === 'network') {
440
- if (user.account === 'site') {
441
- try { await this.#siteAccounts.moveTo(this.#accounts, id, { site: this.#site }); }
442
- catch (error) {
443
- if (isCmsError(error, 'CMS_CONFLICT')) throw new CmsError('CMS_CONFLICT', 'A network account already has this email.', { fields: { email: 'is taken on the network.' } });
444
- throw error;
445
- }
446
- }
447
- } else if (to === 'site') {
448
- // Also finishes a move that copied the account here but did not delete it on the network.
449
- const account = await this.#accounts.get(id);
450
- if (account) {
451
- if (account.networkRole) throw new CmsError('CMS_VALIDATION', 'Network admins keep network accounts.');
452
- if (((await this.#accounts.memberships([id])).get(id) ?? []).some(site => site !== this.#site)) {
453
- throw new CmsError('CMS_VALIDATION', 'The account belongs to other sites too. Remove it from them first.');
454
- }
455
- await this.#accounts.moveTo(this.#siteAccounts, id);
456
- }
457
- } else throw new CmsError('CMS_VALIDATION', 'Choose a site or network account.');
458
- return (await this.get(id))!;
459
- }
460
-
461
- /** Replace a user's roles in one atomic batch. */
462
244
  async setRoles(id: string, roles: readonly string[]): Promise<void> {
463
- await this.#db.write([{ rql: 'DELETE FROM cms_user_roles WHERE user_id = $id', params: { $id: id } }, ...roleStatements(id, roles)], WRITE);
464
- }
465
-
466
- /** Allow or stop the account's sign-in, and copy the status here. */
467
- async setStatus(id: string, status: 'active' | 'disabled'): Promise<boolean> {
468
- const user = await this.get(id);
469
- if (!user || !(await this.#store(user).setStatus(id, status))) return false;
470
- const result = await this.#db.write([{ rql: 'UPDATE cms_users SET status = $status, updated_at = $now WHERE id = $id', params: { $status: status, $now: this.#now(), $id: id } }], WRITE);
471
- return result.results[0]!.affected === 1n;
472
- }
473
-
474
- /** Set the account's password. */
475
- async setPassword(id: string, password: string): Promise<boolean> {
476
- const user = await this.get(id);
477
- return user !== null && this.#store(user).setPassword(id, password);
478
- }
479
-
480
- /** The store of a member's account: this site's for a site account, the network's otherwise. */
481
- #store(user: CmsUser): CmsAccounts {
482
- return user.account === 'site' ? this.#siteAccounts! : this.#accounts;
483
- }
484
-
485
- async count(): Promise<number> {
486
- const result = await this.#db.read([{ rql: 'SELECT count(*) FROM cms_users' }]);
487
- return Number(result.results[0]!.rows[0]![0] as bigint);
245
+ await this.#people.setRoles(id, roles);
488
246
  }
489
247
 
490
- /**
491
- * The member as the request user, or null unless their account is active. A network admin
492
- * also acts with `*` and holds the `network_admin` role. A child session passes the network
493
- * role it copied, so the account is not read: the network ends child sessions of an account
494
- * it suspends.
495
- */
496
- async resolve(id: string, session?: { networkRole: string | null }): Promise<CmsMember | null> {
497
- const [user, account] = await Promise.all([this.get(id), session ? null : (async () => await this.#siteAccounts?.get(id) ?? await this.#accounts.get(id))()]);
498
- if (!user || (!session && (!account || account.status !== 'active'))) return null;
499
- const admin = (session ? session.networkRole : account!.networkRole) === NETWORK_ADMIN;
500
- return Object.freeze({ ...user, principal: userPrincipal(user.id, admin ? [...user.roles, NETWORK_ADMIN] : user.roles, admin ? [...user.permissions, '*'] : user.permissions) });
248
+ /** The member as the request user, or null unless active. A network administrator also acts with `*` and holds `network_admin`. */
249
+ async resolve(id: string): Promise<CmsMember | null> {
250
+ const person = (await this.#people.getMany([id])).get(id);
251
+ if (!person || person.status !== 'active') return null;
252
+ const user = (await this.#users(new Map([[id, person]]))).get(id)!;
253
+ return Object.freeze({ ...user, principal: userPrincipal(user.id, person.networkAdmin ? [...user.roles, NETWORK_ADMIN] : user.roles, personPermissions(person).includes('*') ? [...user.permissions, '*'] : user.permissions) });
501
254
  }
502
255
 
503
- /** The request principal for an active member, or null. */
504
256
  async principal(id: string): Promise<Principal | null> {
505
257
  return (await this.resolve(id))?.principal ?? null;
506
258
  }
507
259
 
508
- /** Create or replace a role by ID. */
509
260
  async defineRole(role: { id: string; name: string; permissions: readonly string[] }): Promise<CmsRole> {
510
- const permissions = checkRole(role);
511
- await this.#db.write([{
512
- rql: 'INSERT INTO cms_roles (id, name, permissions, created_at) VALUES ($id, $name, $permissions, $now) ON CONFLICT (id) DO UPDATE SET name = excluded.name, permissions = excluded.permissions',
513
- params: { $id: role.id, $name: role.name.trim(), $permissions: JSON.stringify(permissions), $now: this.#now() },
514
- }], WRITE);
515
- return (await this.role(role.id))!;
516
- }
517
-
518
- /**
519
- * A new role; its ID is derived from the name when omitted. With an `actor`, the role may
520
- * hold only permissions the actor holds, so a role manager cannot make a stronger role.
521
- */
522
- async createRole(role: { name: string; permissions: readonly string[]; id?: string }, options: { actor?: Principal } = {}): Promise<CmsRole> {
523
- const id = role.id ?? (slugify(role.name, 60) || crypto.randomUUID());
524
- const permissions = checkRole({ ...role, id });
525
- if (options.actor) checkGrant(options.actor, permissions);
526
- try {
527
- await this.#db.write([{ rql: 'INSERT INTO cms_roles (id, name, permissions, created_at) VALUES ($id, $name, $permissions, $now)',
528
- params: { $id: id, $name: role.name.trim(), $permissions: JSON.stringify(permissions), $now: this.#now() } }], WRITE);
529
- } catch (error) {
530
- if (error instanceof ClientError && error.outcome === 'rolled-back' && /UNIQUE|PRIMARY|constraint/i.test(error.message)) throw new CmsError('CMS_CONFLICT', 'A role with this name already exists.', { fields: { name: 'is taken.' } });
531
- throw error;
532
- }
533
- return (await this.role(id))!;
534
- }
535
-
536
- /**
537
- * Change a role's name or permissions. The administrator role stays as it is. With an
538
- * `actor`, both the role as it is and as it becomes may hold only permissions the actor holds.
539
- */
540
- async updateRole(id: string, patch: { name?: string; permissions?: readonly string[] }, options: { actor?: Principal } = {}): Promise<boolean> {
541
- if (id === 'admin') throw new CmsError('CMS_FORBIDDEN', 'The administrator role cannot be changed.');
542
- const read = await this.#storedRole(id);
543
- if (!read) return false;
544
- const { role: current, stored } = read;
545
- const permissions = checkRole({ id, name: patch.name ?? current.name, permissions: patch.permissions ?? current.permissions });
546
- if (options.actor) {
547
- if (!holdsAll(options.actor, current.permissions)) throw new CmsError('CMS_FORBIDDEN', 'This role has permissions you do not have, so you cannot change it.');
548
- checkGrant(options.actor, permissions);
549
- }
550
- try {
551
- // Only over the permissions checked above: a role raised meanwhile is not overwritten.
552
- const result = await this.#db.write([{ rql: 'UPDATE cms_roles SET name = $name, permissions = $permissions WHERE id = $id AND permissions = $previous',
553
- params: { $id: id, $name: (patch.name ?? current.name).trim(), $permissions: JSON.stringify(permissions), $previous: stored } }], WRITE);
554
- if (result.results[0]!.affected === 1n) return true;
555
- if (await this.role(id)) throw new CmsError('CMS_CONFLICT', 'The role changed since it was read. Reload and try again.');
556
- return false;
557
- } catch (error) {
558
- if (error instanceof ClientError && error.outcome === 'rolled-back' && /UNIQUE|constraint/i.test(error.message)) throw new CmsError('CMS_CONFLICT', 'A role with this name already exists.', { fields: { name: 'is taken.' } });
559
- throw error;
560
- }
261
+ return cmsRole(await this.#people.defineRole(role));
561
262
  }
562
263
 
563
- /** Remove a role and its assignments. The administrator role stays, and an actor deletes only roles within their own permissions. */
564
- async deleteRole(id: string, options: { actor?: Principal } = {}): Promise<boolean> {
565
- if (id === 'admin') throw new CmsError('CMS_FORBIDDEN', 'The administrator role cannot be deleted.');
566
- let guard = '';
567
- let params: { [key: string]: Value } = { $id: id };
568
- if (options.actor) {
569
- const read = await this.#storedRole(id);
570
- if (!read) return false;
571
- if (!holdsAll(options.actor, read.role.permissions)) throw new CmsError('CMS_FORBIDDEN', 'This role has permissions you do not have, so you cannot delete it.');
572
- // Only the role as checked: one raised meanwhile stays.
573
- guard = ' AND EXISTS (SELECT 1 FROM cms_roles WHERE id = $id AND permissions = $previous)';
574
- params = { $id: id, $previous: read.stored };
575
- }
576
- const result = await this.#db.write([
577
- { rql: `DELETE FROM cms_user_roles WHERE role_id = $id${guard}`, params },
578
- { rql: `DELETE FROM cms_roles WHERE id = $id${guard ? ' AND permissions = $previous' : ''}`, params },
579
- ], WRITE);
580
- if (result.results[1]!.affected === 1n) return true;
581
- if (guard && await this.role(id)) throw new CmsError('CMS_CONFLICT', 'The role changed since it was read. Reload and try again.');
582
- return false;
583
- }
584
-
585
- /** The role and its permissions as stored, for a write guarded on them. */
586
- async #storedRole(id: string): Promise<{ role: CmsRole; stored: string } | null> {
587
- if (!ID.test(id)) return null;
588
- const result = await this.#db.read([{ rql: 'SELECT id, name, permissions, created_at FROM cms_roles WHERE id = $id', params: { $id: id } }]);
589
- const row = result.results[0]!.rows[0];
590
- return row ? { role: roleOf(row), stored: row[2] as string } : null;
264
+ async role(id: string): Promise<CmsRole | null> {
265
+ const role = await this.#people.role(id);
266
+ return role ? cmsRole(role) : null;
591
267
  }
592
268
 
593
- async role(id: string): Promise<CmsRole | null> {
594
- if (!ID.test(id)) return null;
595
- const result = await this.#db.read([{ rql: 'SELECT id, name, permissions, created_at FROM cms_roles WHERE id = $id', params: { $id: id } }]);
596
- const row = result.results[0]!.rows[0];
597
- return row ? roleOf(row) : null;
598
- }
599
-
600
- /** Roles in creation order, each with its user count. */
601
269
  async roles(options: { search?: string; limit?: number; offset?: number } = {}): Promise<CmsRole[]> {
602
- const params: { [key: string]: Value } = {};
603
- let where = '';
604
- if (options.search?.trim()) { where = " WHERE lower(r.name) LIKE $q ESCAPE '\\'"; params.$q = containsPattern(options.search.trim().slice(0, 100)); }
605
- // Roles hold their permission lists: many roles may come in smaller reads.
606
- const rows = await readPaged(this.#db, (limit, offset) => ({
607
- rql: `SELECT r.id, r.name, r.permissions, r.created_at, (SELECT count(*) FROM cms_user_roles ur WHERE ur.role_id = r.id) FROM cms_roles r${where} ORDER BY r.created_at, r.id LIMIT $limit OFFSET $offset`,
608
- params: { ...params, $limit: limit, $offset: offset },
609
- }), Math.min(Math.max(options.limit ?? 200, 1), 200), Math.max(options.offset ?? 0, 0));
610
- return rows.map(row => ({ ...roleOf(row), userCount: Number(row[4] as bigint) }));
270
+ const search = options.search?.trim().toLowerCase();
271
+ const all = (await this.#people.roles()).filter(role => !search || role.name.toLowerCase().includes(search));
272
+ const offset = Math.max(options.offset ?? 0, 0);
273
+ return all.slice(offset, offset + Math.min(Math.max(options.limit ?? 200, 1), 200)).map(cmsRole);
611
274
  }
612
275
 
613
276
  async countRoles(options: { search?: string } = {}): Promise<number> {
614
- const result = await this.#db.read([options.search?.trim()
615
- ? { rql: "SELECT count(*) FROM cms_roles WHERE lower(name) LIKE $q ESCAPE '\\'", params: { $q: containsPattern(options.search.trim().slice(0, 100)) } }
616
- : { rql: 'SELECT count(*) FROM cms_roles' }]);
617
- return Number(result.results[0]!.rows[0]![0] as bigint);
277
+ return (await this.roles({ ...options, limit: 200 })).length;
618
278
  }
619
- }
620
-
621
- function roleOf(row: readonly Value[]): CmsRole {
622
- return { id: row[0] as string, name: row[1] as string, permissions: JSON.parse(row[2] as string) as string[], createdAt: Number(row[3] as bigint) };
623
- }
624
279
 
625
- function roleStatements(userId: string, roles: readonly string[]): Statement[] {
626
- return [...new Set(roles)].map(role => {
627
- if (!ID.test(role)) throw new CmsError('CMS_VALIDATION', `Invalid role ${role}.`);
628
- // Insert only roles that exist; the caller checks the outcome through get().
629
- return { rql: 'INSERT INTO cms_user_roles (user_id, role_id) SELECT $user, id FROM cms_roles WHERE id = $role', params: { $user: userId, $role: role } as { [key: string]: Value } };
630
- });
631
- }
280
+ /** Make a network account a member of this site, with the roles named. Null when there is no such account. */
281
+ async addMember(accountId: string, options: { roles?: readonly string[]; meta?: unknown } = {}): Promise<CmsUser | null> {
282
+ if (!this.#people.join) throw new CmsError('CMS_UNAVAILABLE', 'This application has no accounts that sites share, so a member is made with create().', { lasting: true });
283
+ const person = await this.#people.join(accountId, options.roles ?? []);
284
+ return person ? this.get(person.id) : null;
285
+ }
632
286
 
633
- /** A role manager gives only permissions they hold. */
634
- function checkGrant(actor: Principal, permissions: readonly string[]): void {
635
- const missing = permissions.filter(permission => !holdsAll(actor, [permission]));
636
- if (missing.length) throw new CmsError('CMS_FORBIDDEN', `You cannot give a role permissions you do not have: ${missing.join(', ')}.`, { fields: { permissions: 'include permissions you do not have.' } });
287
+ /** Every user, a page at a time. The cursor is the place in the port's list. */
288
+ async after(after: string | null, limit = 100): Promise<{ users: CmsUser[]; next: string | null }> {
289
+ const offset = after === null ? 0 : Math.max(Number(after) || 0, 0);
290
+ const size = Math.min(Math.max(limit, 1), 200);
291
+ const page = await this.#people.list({ limit: size, offset });
292
+ const users = await this.#users(new Map(page.users.map(person => [person.id, person])));
293
+ return { users: page.users.map(person => users.get(person.id)!), next: offset + page.users.length < page.total && page.users.length > 0 ? String(offset + page.users.length) : null };
294
+ }
637
295
  }
638
296
 
639
- function checkRole(role: { id: string; name: string; permissions: readonly string[] }): string[] {
640
- if (!ID.test(role.id) || typeof role.name !== 'string' || !role.name.trim() || role.name.length > 80) throw new CmsError('CMS_VALIDATION', 'Enter a role name of at most 80 characters.', { fields: { name: 'is required.' } });
641
- if (role.id === NETWORK_ADMIN) throw new CmsError('CMS_VALIDATION', 'network_admin is the network\'s role; choose another name.', { fields: { name: 'is reserved.' } });
642
- const invalid = role.permissions.filter(permission => !PERMISSION.test(permission));
643
- if (invalid.length) throw new CmsError('CMS_VALIDATION', `Unknown permission ${invalid.join(', ')}.`, { fields: { permissions: 'are invalid.' } });
644
- return [...new Set(role.permissions)].sort();
297
+ function cmsRole(role: PersonRole): CmsRole {
298
+ return { id: role.id, name: role.name, permissions: [...role.permissions], createdAt: 0 };
645
299
  }
646
300
 
647
- function memberError(error: unknown): unknown {
648
- if (error instanceof ClientError && error.outcome === 'rolled-back' && /UNIQUE/i.test(error.message)) return new CmsError('CMS_CONFLICT', 'A user with this email already exists.', { fields: { email: 'is taken.' } });
649
- if (error instanceof ClientError && error.outcome === 'rolled-back' && /FOREIGN|role/i.test(error.message)) return new CmsError('CMS_VALIDATION', 'Unknown role.');
301
+ /** A unique field of the user's document that another user's value holds. */
302
+ function fieldError(error: unknown): unknown {
303
+ const name = error instanceof ClientError && error.outcome === 'rolled-back' ? uniqueFieldOf(error.message) : undefined;
304
+ if (name !== undefined) return new CmsError('CMS_CONFLICT', 'Another user has the same value in a unique field.', name ? { fields: { [name]: 'is taken.' } } : {});
650
305
  return error;
651
306
  }
652
-
653
- export { normalizeEmail };