@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,418 +0,0 @@
1
- /**
2
- * Accounts on the network database: who can sign in. The account holds the email, password
3
- * hash, status, profile and network role; sessions, second factors, reset tokens and
4
- * application passwords belong to it and live in the same database. Sites keep their members
5
- * in `cms_users` under the account's ID. Emails are normalized to lowercase.
6
- */
7
- import { createCredentialVerifier, createPasswordHasher, type CredentialVerifier, type PasswordHasher } from '@cossackframework/auth';
8
- import { ClientError, type RomeDB, type Value } from '@cossackframework/romedb';
9
- import { uuidv7 } from '@cossackframework/core';
10
- import { CmsError } from '../errors';
11
- import { NETWORK_ADMIN } from '../permissions';
12
- import type { EndedSessions } from './stores';
13
-
14
- export interface CmsAccount {
15
- readonly id: string;
16
- readonly email: string;
17
- readonly name: string;
18
- readonly avatar: string | null;
19
- readonly status: 'active' | 'disabled';
20
- /** `network_admin`, or null for everyone else. */
21
- readonly networkRole: typeof NETWORK_ADMIN | null;
22
- readonly createdAt: number;
23
- /** When the account last started a session, or null when never. */
24
- readonly lastSignInAt: number | null;
25
- /**
26
- * Registered and waiting for its email's confirmation: created disabled and not changed since,
27
- * never signed in. An account an administrator disabled, or changed in any way, is not.
28
- */
29
- readonly unconfirmed: boolean;
30
- }
31
-
32
- export interface AccountProfile {
33
- name?: string;
34
- email?: string;
35
- avatar?: string | null;
36
- }
37
-
38
- const EMAIL = /^[^\s@]{1,64}@[^\s@]{1,190}$/;
39
- export const ACCOUNT_ID = /^[A-Za-z0-9_-]{1,80}$/;
40
- const TOKEN = /^[A-Za-z0-9_-]{32,128}$/;
41
- const COLUMNS = 'id, email, name, avatar, status, network_role, created_at, last_sign_in_at, updated_at, held';
42
- const WRITE = { kind: 'cms.accounts', retryConflicts: 5 } as const;
43
- /** What moves with an account to another database: the row, second factors and application passwords. */
44
- const MOVED = {
45
- cms_accounts: ['id', 'email', 'name', 'password_hash', 'avatar', 'status', 'network_role', 'created_at', 'updated_at', 'last_sign_in_at', 'held'],
46
- cms_user_security: ['user_id', 'totp_secret', 'totp_confirmed_at', 'totp_last_step', 'recovery', 'updated_at'],
47
- cms_api_tokens: ['id', 'user_id', 'name', 'secret_hash', 'scope', 'created_at', 'last_used_at', 'expires_at'],
48
- } as const;
49
- /** Another active network admin remains, so this account may stop being one. */
50
- const ANOTHER_ADMIN = `EXISTS (SELECT 1 FROM cms_accounts WHERE network_role = '${NETWORK_ADMIN}' AND status = 'active' AND id <> $id)`;
51
-
52
- const sha256 = async (text: string) => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))]
53
- .map(byte => byte.toString(16).padStart(2, '0')).join('');
54
-
55
- export class CmsAccounts {
56
- readonly #db: RomeDB;
57
- readonly #hasher: PasswordHasher;
58
- readonly #now: () => number;
59
- readonly #ended: (ended: EndedSessions) => Promise<void>;
60
- readonly verifier: CredentialVerifier<CmsAccount>;
61
-
62
- /** `sessionsEnded` hears when the account's sessions end, so sites can end the child sessions they handed off. */
63
- constructor(db: RomeDB, options: { hasher?: PasswordHasher; now?: () => number; sessionsEnded?: (ended: EndedSessions) => Promise<void> } = {}) {
64
- this.#db = db;
65
- this.#hasher = options.hasher ?? createPasswordHasher();
66
- this.#now = options.now ?? Date.now;
67
- this.#ended = ended => (options.sessionsEnded?.(ended) ?? Promise.resolve()).catch(error => console.error('[cms] could not end child sessions', error));
68
- type Row = { id: string; hash: string | null; status: string };
69
- this.verifier = createCredentialVerifier<Row, CmsAccount>({
70
- find: async email => {
71
- const result = await this.#db.read([{ rql: 'SELECT id, password_hash, status FROM cms_accounts WHERE email = $email', params: { $email: normalizeEmail(email) } }]);
72
- const row = result.results[0]!.rows[0];
73
- return row ? { id: row[0] as string, hash: row[1] as string | null, status: row[2] as string } : null;
74
- },
75
- passwordHash: row => row.status === 'active' ? row.hash : null,
76
- user: async row => (await this.get(row.id))!,
77
- hasher: this.#hasher,
78
- replacePasswordHash: async (row, expected, replacement) => {
79
- const result = await this.#db.write([{ rql: 'UPDATE cms_accounts SET password_hash = $next, updated_at = $now WHERE id = $id AND password_hash = $expected',
80
- params: { $next: replacement, $now: this.#now(), $id: row.id, $expected: expected } }], WRITE);
81
- return result.results[0]!.affected === 1n;
82
- },
83
- });
84
- }
85
-
86
- /**
87
- * The disabled account this email and password name, or null: for telling someone whose
88
- * account waits for approval that it does, only once they proved it is theirs. Active
89
- * accounts sign in through `verifier`.
90
- */
91
- async disabledWithPassword(email: string, password: string): Promise<CmsAccount | null> {
92
- const result = await this.#db.read([{ rql: "SELECT id, password_hash FROM cms_accounts WHERE email = $email AND status = 'disabled'", params: { $email: normalizeEmail(email) } }]);
93
- const row = result.results[0]!.rows[0];
94
- if (!row || typeof row[1] !== 'string' || !(await this.#hasher.verify(password, row[1]))) return null;
95
- return this.get(row[0] as string);
96
- }
97
-
98
- /**
99
- * A new account; `status: 'disabled'` for one that waits for its email's confirmation
100
- * (`unconfirmed`), and `held` as well for one that waits for a site's approval.
101
- */
102
- async create(input: AccountProfile & { email: string; name: string; password?: string; id?: string; networkRole?: typeof NETWORK_ADMIN | null; status?: 'active' | 'disabled'; held?: boolean }): Promise<CmsAccount> {
103
- const email = normalizeEmail(input.email);
104
- checkProfile({ email, name: input.name, avatar: input.avatar ?? null });
105
- if (input.password !== undefined) checkPassword(input.password);
106
- const id = input.id ?? uuidv7();
107
- if (!ACCOUNT_ID.test(id)) throw new CmsError('CMS_VALIDATION', 'Invalid user ID.');
108
- const hash = input.password === undefined ? null : await this.#hasher.hash(input.password);
109
- const now = this.#now();
110
- try {
111
- await this.#db.write([{
112
- rql: 'INSERT INTO cms_accounts (id, email, name, password_hash, avatar, status, network_role, created_at, updated_at, held) VALUES ($id, $email, $name, $hash, $avatar, $status, $role, $now, $now, $held)',
113
- params: { $id: id, $email: email, $name: input.name.trim(), $hash: hash, $avatar: input.avatar ?? null, $status: input.status === 'disabled' || input.held ? 'disabled' : 'active', $role: input.networkRole ?? null, $now: now, $held: input.held ? 1 : null },
114
- }], WRITE);
115
- } catch (error) { throw uniqueEmail(error); }
116
- return (await this.get(id))!;
117
- }
118
-
119
- async get(id: string): Promise<CmsAccount | null> {
120
- if (!ACCOUNT_ID.test(id)) return null;
121
- const result = await this.#db.read([{ rql: `SELECT ${COLUMNS} FROM cms_accounts WHERE id = $id`, params: { $id: id } }]);
122
- const row = result.results[0]!.rows[0];
123
- return row ? accountOf(row) : null;
124
- }
125
-
126
- async findByEmail(email: string): Promise<CmsAccount | null> {
127
- const result = await this.#db.read([{ rql: `SELECT ${COLUMNS} FROM cms_accounts WHERE email = $email`, params: { $email: normalizeEmail(email) } }]);
128
- const row = result.results[0]!.rows[0];
129
- return row ? accountOf(row) : null;
130
- }
131
-
132
- async count(): Promise<number> {
133
- const result = await this.#db.read([{ rql: 'SELECT count(*) FROM cms_accounts' }]);
134
- return Number(result.results[0]!.rows[0]![0] as bigint);
135
- }
136
-
137
- /** Whether an active network admin exists. Until one does, the install needs setup, or a takeover of a site's database. */
138
- async hasNetworkAdmin(): Promise<boolean> {
139
- const result = await this.#db.read([{ rql: `SELECT 1 FROM cms_accounts WHERE network_role = '${NETWORK_ADMIN}' AND status = 'active' LIMIT 1` }]);
140
- return result.results[0]!.rows.length > 0;
141
- }
142
-
143
- /** Newest first. `search` matches name or email; `networkAdmins` keeps only them. */
144
- async list(options: { search?: string; networkAdmins?: boolean; limit?: number; offset?: number } = {}): Promise<{ items: CmsAccount[]; total: number }> {
145
- const conditions: string[] = [];
146
- const params: { [key: string]: Value } = {};
147
- if (options.search?.trim()) {
148
- conditions.push("(lower(name) LIKE $q ESCAPE '\\' OR email LIKE $q ESCAPE '\\')");
149
- params.$q = `%${options.search.trim().toLowerCase().slice(0, 100).replace(/[\\%_]/g, character => `\\${character}`)}%`;
150
- }
151
- if (options.networkAdmins) conditions.push(`network_role = '${NETWORK_ADMIN}'`);
152
- const where = conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '';
153
- const result = await this.#db.read([
154
- { rql: `SELECT ${COLUMNS} FROM cms_accounts${where} ORDER BY created_at DESC, id DESC LIMIT $limit OFFSET $offset`, params: { ...params, $limit: Math.min(Math.max(options.limit ?? 20, 1), 100), $offset: Math.max(options.offset ?? 0, 0) } },
155
- { rql: `SELECT count(*) FROM cms_accounts${where}`, params },
156
- ]);
157
- return { items: result.results[0]!.rows.map(accountOf), total: Number(result.results[1]!.rows[0]![0] as bigint) };
158
- }
159
-
160
- /** Which of these IDs, 200 at most, are accounts here. */
161
- async existing(ids: readonly string[]): Promise<Set<string>> {
162
- const wanted = [...new Set(ids.filter(id => ACCOUNT_ID.test(id)))].slice(0, 200);
163
- if (!wanted.length) return new Set();
164
- const params = Object.fromEntries(wanted.map((id, index) => [`$a${index}`, id]));
165
- const result = await this.#db.read([{ rql: `SELECT id FROM cms_accounts WHERE id IN (${wanted.map((_, index) => `$a${index}`).join(', ')})`, params }]);
166
- return new Set(result.results[0]!.rows.map(row => row[0] as string));
167
- }
168
-
169
- /** The sites each account is a member of, by account. */
170
- async memberships(ids: readonly string[]): Promise<Map<string, string[]>> {
171
- const wanted = [...new Set(ids.filter(id => ACCOUNT_ID.test(id)))].slice(0, 200);
172
- const sites = new Map<string, string[]>(wanted.map(id => [id, []]));
173
- if (!wanted.length) return sites;
174
- const params = Object.fromEntries(wanted.map((id, index) => [`$a${index}`, id]));
175
- const result = await this.#db.read([{ rql: `SELECT account_id, site_id FROM cms_memberships WHERE account_id IN (${wanted.map((_, index) => `$a${index}`).join(', ')}) ORDER BY site_id`, params }]);
176
- for (const [account, site] of result.results[0]!.rows) sites.get(account as string)!.push(site as string);
177
- return sites;
178
- }
179
-
180
- /** How many members each site has, by site. */
181
- async memberCounts(): Promise<Map<string, number>> {
182
- const result = await this.#db.read([{ rql: 'SELECT site_id, count(*) FROM cms_memberships GROUP BY site_id' }]);
183
- return new Map(result.results[0]!.rows.map(row => [row[0] as string, Number(row[1] as bigint)]));
184
- }
185
-
186
- /** Record that the account is a member of the site; sites call this when they add or remove members. */
187
- async join(id: string, site: string): Promise<void> {
188
- // Only while the account exists: one deleted meanwhile (a turned-down registration) gets no membership.
189
- const result = await this.#db.write([{ rql: 'INSERT INTO cms_memberships (account_id, site_id, created_at) SELECT $id, $site, $now WHERE EXISTS (SELECT 1 FROM cms_accounts WHERE id = $id) ON CONFLICT (account_id, site_id) DO NOTHING', params: { $id: id, $site: site, $now: this.#now() } }], WRITE);
190
- if (result.results[0]!.affected === 1n) return;
191
- const found = await this.#db.read([{ rql: 'SELECT 1 FROM cms_accounts WHERE id = $id', params: { $id: id } }]);
192
- if (!found.results[0]!.rows.length) throw new CmsError('CMS_NOT_FOUND', 'The account no longer exists.');
193
- }
194
-
195
- async leave(id: string, site: string): Promise<void> {
196
- await this.#db.write([{ rql: 'DELETE FROM cms_memberships WHERE account_id = $id AND site_id = $site', params: { $id: id, $site: site } }], WRITE);
197
- }
198
-
199
- /** Change the name, email or avatar. Sites copy them to their member rows. */
200
- async update(id: string, patch: AccountProfile): Promise<CmsAccount | null> {
201
- const current = await this.get(id);
202
- if (!current) return null;
203
- const next = { name: patch.name ?? current.name, email: patch.email === undefined ? current.email : normalizeEmail(patch.email), avatar: patch.avatar === undefined ? current.avatar : patch.avatar || null };
204
- checkProfile(next);
205
- try {
206
- await this.#db.write([{ rql: 'UPDATE cms_accounts SET name = $name, email = $email, avatar = $avatar, updated_at = $now WHERE id = $id',
207
- params: { $name: next.name.trim(), $email: next.email, $avatar: next.avatar, $now: this.#now(), $id: id } }], WRITE);
208
- } catch (error) { throw uniqueEmail(error); }
209
- return this.get(id);
210
- }
211
-
212
- async setPassword(id: string, password: string): Promise<boolean> {
213
- checkPassword(password);
214
- const result = await this.#db.write([{ rql: 'UPDATE cms_accounts SET password_hash = $hash, updated_at = $now WHERE id = $id', params: { $hash: await this.#hasher.hash(password), $now: this.#now(), $id: id } }], WRITE);
215
- return result.results[0]!.affected === 1n;
216
- }
217
-
218
- /** Allow or stop sign-in. The last active network admin cannot be disabled. */
219
- async setStatus(id: string, status: 'active' | 'disabled'): Promise<boolean> {
220
- if (status !== 'active' && status !== 'disabled') throw new CmsError('CMS_VALIDATION', 'Unknown account status.');
221
- const guard = status === 'disabled' ? ` AND (network_role IS NULL OR ${ANOTHER_ADMIN})` : '';
222
- const result = await this.#db.write([{ rql: `UPDATE cms_accounts SET status = $status, updated_at = $now WHERE id = $id${guard}`, params: { $status: status, $now: this.#now(), $id: id } }], WRITE);
223
- if (result.results[0]!.affected !== 1n) return this.#refuseLastAdmin(id, 'disabled');
224
- // A suspended account is signed out of every site.
225
- if (status === 'disabled') await this.#ended({ user: id });
226
- return true;
227
- }
228
-
229
- /** Make the account a network admin, or stop it being one. The network keeps at least one. */
230
- async setNetworkRole(id: string, role: typeof NETWORK_ADMIN | null): Promise<boolean> {
231
- if (role !== null && role !== NETWORK_ADMIN) throw new CmsError('CMS_VALIDATION', 'Unknown network role.');
232
- const guard = role === null ? ` AND (network_role IS NULL OR ${ANOTHER_ADMIN})` : '';
233
- const result = await this.#db.write([{ rql: `UPDATE cms_accounts SET network_role = $role, updated_at = $now WHERE id = $id${guard}`, params: { $role: role, $now: this.#now(), $id: id } }], WRITE);
234
- if (result.results[0]!.affected !== 1n) return this.#refuseLastAdmin(id, 'removed from the network role');
235
- // Sites' child sessions copied the old role; the next handoff copies the new one.
236
- await this.#ended({ user: id });
237
- return true;
238
- }
239
-
240
- /**
241
- * A site's database becomes its own install: every member without an account gets one
242
- * without a password, recorded as a member of `site`; `admin`, a member, gets this password
243
- * and the network role. Sessions copied with the database end. One write; returns how many
244
- * accounts it made.
245
- */
246
- async adoptMembers(site: string, admin: string, password: string): Promise<number> {
247
- checkPassword(password);
248
- const member = await this.#db.read([{ rql: 'SELECT 1 FROM cms_users WHERE id = $admin', params: { $admin: admin } }]);
249
- if (!member.results[0]!.rows.length) throw new CmsError('CMS_VALIDATION', 'The administrator must be a member of the site.', { fields: { email: 'is not a member.' } });
250
- const now = this.#now();
251
- const result = await this.#db.write([
252
- { rql: 'INSERT INTO cms_accounts (id, email, name, password_hash, avatar, status, network_role, created_at, updated_at) SELECT id, email, name, NULL, avatar, status, NULL, created_at, $now FROM cms_users WHERE id NOT IN (SELECT id FROM cms_accounts)', params: { $now: now } },
253
- { rql: "UPDATE cms_accounts SET password_hash = $hash, network_role = $role, status = 'active', updated_at = $now WHERE id = $admin",
254
- params: { $hash: await this.#hasher.hash(password), $role: NETWORK_ADMIN, $now: now, $admin: admin } },
255
- { rql: 'INSERT INTO cms_memberships (account_id, site_id, created_at) SELECT id, $site, $now FROM cms_users WHERE 1 = 1 ON CONFLICT (account_id, site_id) DO NOTHING', params: { $site: site, $now: now } },
256
- { rql: 'DELETE FROM cms_auth_sessions' },
257
- ], WRITE);
258
- return Number(result.results[0]!.affected);
259
- }
260
-
261
- /**
262
- * Remove the account with everything that signs it in: sessions, reset tokens, second
263
- * factors, pending sign-ins and application passwords. Site members are removed by their sites.
264
- */
265
- async delete(id: string): Promise<boolean> {
266
- if (!ACCOUNT_ID.test(id)) return false;
267
- const params = { $id: id };
268
- // Credentials go only when the account row went: the last network admin stays whole.
269
- const gone = 'NOT EXISTS (SELECT 1 FROM cms_accounts WHERE id = $id)';
270
- const result = await this.#db.write([
271
- { rql: `DELETE FROM cms_accounts WHERE id = $id AND (network_role IS NULL OR ${ANOTHER_ADMIN})`, params },
272
- ...['cms_auth_sessions', 'cms_password_resets', 'cms_user_security', 'cms_passkeys', 'cms_auth_challenges', 'cms_api_tokens']
273
- .map(table => ({ rql: `DELETE FROM ${table} WHERE user_id = $id AND ${gone}`, params })),
274
- { rql: `DELETE FROM cms_memberships WHERE account_id = $id AND ${gone}`, params },
275
- ], WRITE);
276
- if (result.results[0]!.affected !== 1n) return this.#refuseLastAdmin(id, 'deleted');
277
- await this.#ended({ user: id });
278
- return true;
279
- }
280
-
281
- /**
282
- * Delete an account made for a registration that was turned down: only while it is still
283
- * disabled, never signed in, no network admin, and a member of no site, all checked in the
284
- * delete itself, so a site that adds it meanwhile keeps it. False when it stays.
285
- */
286
- async deleteUnused(id: string): Promise<boolean> {
287
- if (!ACCOUNT_ID.test(id)) return false;
288
- const params = { $id: id };
289
- const gone = 'NOT EXISTS (SELECT 1 FROM cms_accounts WHERE id = $id)';
290
- const result = await this.#db.write([
291
- { rql: `DELETE FROM cms_accounts WHERE id = $id AND status = 'disabled' AND last_sign_in_at IS NULL AND network_role IS NULL
292
- AND NOT EXISTS (SELECT 1 FROM cms_memberships WHERE account_id = $id)`, params },
293
- ...['cms_auth_sessions', 'cms_password_resets', 'cms_user_security', 'cms_passkeys', 'cms_auth_challenges', 'cms_api_tokens']
294
- .map(table => ({ rql: `DELETE FROM ${table} WHERE user_id = $id AND ${gone}`, params })),
295
- ], WRITE);
296
- if (result.results[0]!.affected !== 1n) return false;
297
- await this.#ended({ user: id });
298
- return true;
299
- }
300
-
301
- /**
302
- * Move the account to another database's accounts under the same ID: its row with the
303
- * password hash, its second factors and application passwords, and with `site`, its
304
- * membership there. Then it is deleted here with what else signs it in, and its sessions
305
- * end. Passkeys go: they are bound to the host they were made on. A retry after a failure
306
- * between the two writes finishes the move. Throws CMS_CONFLICT when the other database
307
- * has another account with the email.
308
- */
309
- async moveTo(target: CmsAccounts, id: string, options: { site?: string } = {}): Promise<boolean> {
310
- if (!ACCOUNT_ID.test(id) || target === this) return false;
311
- const params = { $id: id };
312
- const found = await this.#db.read([
313
- { rql: `SELECT ${MOVED.cms_accounts.join(', ')} FROM cms_accounts WHERE id = $id`, params },
314
- { rql: `SELECT ${MOVED.cms_user_security.join(', ')} FROM cms_user_security WHERE user_id = $id`, params },
315
- { rql: `SELECT ${MOVED.cms_api_tokens.join(', ')} FROM cms_api_tokens WHERE user_id = $id`, params },
316
- ]);
317
- if (!found.results[0]!.rows.length) return false;
318
- const copy = (table: keyof typeof MOVED, key: string, row: readonly Value[], index: number) => ({
319
- rql: `INSERT INTO ${table} (${MOVED[table].join(', ')}) VALUES (${MOVED[table].map((_, column) => `$v${index}_${column}`).join(', ')}) ON CONFLICT (${key}) DO NOTHING`,
320
- params: Object.fromEntries(row.map((value, column) => [`$v${index}_${column}`, value])),
321
- });
322
- try {
323
- await target.#db.write([
324
- copy('cms_accounts', 'id', found.results[0]!.rows[0]!, 0),
325
- ...found.results[1]!.rows.map(row => copy('cms_user_security', 'user_id', row, 1)),
326
- ...found.results[2]!.rows.map((row, index) => copy('cms_api_tokens', 'id', row, 2 + index)),
327
- ...(options.site ? [{ rql: 'INSERT INTO cms_memberships (account_id, site_id, created_at) VALUES ($id, $site, $now) ON CONFLICT (account_id, site_id) DO NOTHING', params: { $id: id, $site: options.site, $now: this.#now() } }] : []),
328
- ], WRITE);
329
- } catch (error) { throw uniqueEmail(error); }
330
- return this.delete(id);
331
- }
332
-
333
- /** False for an unknown account; throws when the account is the last network admin. */
334
- async #refuseLastAdmin(id: string, change: string): Promise<false> {
335
- if (await this.get(id)) throw new CmsError('CMS_FORBIDDEN', `The last network admin cannot be ${change}.`);
336
- return false;
337
- }
338
-
339
- /**
340
- * A one-time reset token for an active account, or null for an unknown email. The token is
341
- * returned once; the table keeps only its SHA-256, and earlier tokens for the account end.
342
- */
343
- async createPasswordReset(email: string, options: { ttlMs?: number } = {}): Promise<{ token: string; account: CmsAccount } | null> {
344
- const account = await this.findByEmail(email);
345
- if (!account || account.status !== 'active') return null;
346
- const token = [...crypto.getRandomValues(new Uint8Array(32))].map(byte => byte.toString(16).padStart(2, '0')).join('');
347
- const now = this.#now();
348
- await this.#db.write([
349
- { rql: 'DELETE FROM cms_password_resets WHERE user_id = $user', params: { $user: account.id } },
350
- { rql: 'INSERT INTO cms_password_resets (id, user_id, created_at, expires_at) VALUES ($id, $user, $now, $expires)',
351
- params: { $id: await sha256(token), $user: account.id, $now: now, $expires: now + (options.ttlMs ?? 60 * 60_000) } },
352
- ], WRITE);
353
- return { token, account };
354
- }
355
-
356
- /**
357
- * Set a new password with a reset token. One conditional delete consumes the token, so
358
- * only one request can use it; the account's sessions end with the change.
359
- */
360
- async resetPassword(token: string, password: string): Promise<boolean> {
361
- if (typeof token !== 'string' || !TOKEN.test(token)) return false;
362
- checkPassword(password);
363
- const id = await sha256(token);
364
- const found = await this.#db.read([{ rql: 'SELECT user_id FROM cms_password_resets WHERE id = $id AND expires_at > $now', params: { $id: id, $now: this.#now() } }]);
365
- const account = found.results[0]!.rows[0]?.[0] as string | undefined;
366
- if (!account) return false;
367
- const hash = await this.#hasher.hash(password);
368
- const guard = 'EXISTS (SELECT 1 FROM cms_password_resets WHERE id = $id AND user_id = $user AND expires_at > $now)';
369
- const params = { $id: id, $user: account, $now: this.#now() };
370
- // The password and sessions change only if this request still holds the token.
371
- const result = await this.#db.write([
372
- { rql: `UPDATE cms_accounts SET password_hash = $hash, updated_at = $now WHERE id = $user AND ${guard}`, params: { ...params, $hash: hash } },
373
- { rql: `DELETE FROM cms_auth_sessions WHERE user_id = $user AND ${guard}`, params },
374
- { rql: 'DELETE FROM cms_password_resets WHERE id = $id AND user_id = $user AND expires_at > $now', params },
375
- ], WRITE);
376
- if (result.results[2]!.affected !== 1n || result.results[0]!.affected !== 1n) return false;
377
- await this.#ended({ user: account });
378
- return true;
379
- }
380
-
381
- async purgeExpiredResets(): Promise<number> {
382
- const expired = await this.#db.read([{ rql: 'SELECT 1 FROM cms_password_resets WHERE expires_at <= $now LIMIT 1', params: { $now: this.#now() } }]);
383
- if (!expired.results[0]!.rows.length) return 0;
384
- const result = await this.#db.write([{ rql: 'DELETE FROM cms_password_resets WHERE id IN (SELECT id FROM cms_password_resets WHERE expires_at <= $now LIMIT 500)', params: { $now: this.#now() } }], WRITE);
385
- return Number(result.results[0]!.affected);
386
- }
387
- }
388
-
389
- function accountOf(row: readonly Value[]): CmsAccount {
390
- return Object.freeze({
391
- id: row[0] as string, email: row[1] as string, name: row[2] as string, avatar: row[3] as string | null, status: row[4] as CmsAccount['status'],
392
- networkRole: row[5] === NETWORK_ADMIN ? NETWORK_ADMIN : null, createdAt: Number(row[6] as bigint), lastSignInAt: row[7] === null ? null : Number(row[7] as bigint),
393
- // Held for approval is not unconfirmed: another registration of the email never replaces it.
394
- unconfirmed: row[4] === 'disabled' && row[7] === null && row[8] !== undefined && Number(row[8] as bigint) === Number(row[6] as bigint) && !row[9],
395
- });
396
- }
397
-
398
- export function checkProfile(profile: { email: string; name: string; avatar: string | null }): void {
399
- if (!EMAIL.test(profile.email)) throw new CmsError('CMS_VALIDATION', 'Enter a valid email address.', { fields: { email: 'is invalid.' } });
400
- if (typeof profile.name !== 'string' || !profile.name.trim() || profile.name.length > 120) throw new CmsError('CMS_VALIDATION', 'Enter a name of at most 120 characters.', { fields: { name: 'is required.' } });
401
- if (profile.avatar !== null && (typeof profile.avatar !== 'string' || profile.avatar.length > 2048 || !/^(?:https:\/\/|\/)[^\s]*$/.test(profile.avatar))) {
402
- throw new CmsError('CMS_VALIDATION', 'The avatar must be an https URL or a site path.', { fields: { avatar: 'is invalid.' } });
403
- }
404
- }
405
-
406
- function checkPassword(password: string): void {
407
- if (typeof password !== 'string' || password.length < 8) throw new CmsError('CMS_VALIDATION', 'Passwords need at least 8 characters.', { fields: { password: 'is too short.' } });
408
- if (new TextEncoder().encode(password).length > 1024) throw new CmsError('CMS_VALIDATION', 'Passwords can be at most 1024 bytes.', { fields: { password: 'is too long.' } });
409
- }
410
-
411
- export function uniqueEmail(error: unknown): unknown {
412
- 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.' } });
413
- return error;
414
- }
415
-
416
- export function normalizeEmail(email: string): string {
417
- return typeof email === 'string' ? email.trim().toLowerCase() : '';
418
- }
@@ -1,91 +0,0 @@
1
- /**
2
- * Application passwords: named tokens a user creates for apps and scripts that call the
3
- * content API. A token is `cms_<id>.<secret>`; only the secret's SHA-256 is stored. Requests
4
- * act as the user with their current roles; `read` tokens may only read.
5
- */
6
- import type { RomeDB } from '@cossackframework/romedb';
7
- import { CmsError } from '../errors';
8
- import { randomToken, sha256Hex, timingSafeEqual } from './tokens';
9
-
10
- export type ApiTokenScope = 'read' | 'write';
11
-
12
- export interface ApiToken {
13
- readonly id: string;
14
- readonly userId: string;
15
- readonly name: string;
16
- readonly scope: ApiTokenScope;
17
- readonly createdAt: number;
18
- readonly lastUsedAt: number | null;
19
- readonly expiresAt: number | null;
20
- }
21
-
22
- const WRITE = { kind: 'cms.tokens', retryConflicts: 5 } as const;
23
- const FORMAT = /^cms_([A-Za-z0-9_-]{16})\.([A-Za-z0-9_-]{43})$/;
24
- const COLUMNS = 'id, user_id, name, scope, created_at, last_used_at, expires_at';
25
- /** Tokens a user can hold. */
26
- export const API_TOKEN_LIMIT = 20;
27
-
28
- export class CmsApiTokens {
29
- readonly #db: RomeDB;
30
- readonly #now: () => number;
31
-
32
- constructor(db: RomeDB, options: { now?: () => number } = {}) {
33
- this.#db = db;
34
- this.#now = options.now ?? Date.now;
35
- }
36
-
37
- /** A new token for the user. The returned `token` is shown once and cannot be read again. */
38
- async create(userId: string, input: { name: string; scope?: ApiTokenScope; expiresAt?: number | null }): Promise<{ token: string; record: ApiToken }> {
39
- const name = typeof input.name === 'string' ? input.name.trim() : '';
40
- if (!name || name.length > 80) throw new CmsError('CMS_VALIDATION', 'Name the application password in 1-80 characters.', { fields: { name: 'must be 1-80 characters.' } });
41
- const scope = input.scope ?? 'write';
42
- if (scope !== 'read' && scope !== 'write') throw new CmsError('CMS_VALIDATION', 'Access is read or write.');
43
- const now = this.#now();
44
- if (input.expiresAt !== undefined && input.expiresAt !== null && (!Number.isSafeInteger(input.expiresAt) || input.expiresAt <= now)) throw new CmsError('CMS_VALIDATION', 'The expiry must be in the future.');
45
- if ((await this.list(userId)).length >= API_TOKEN_LIMIT) throw new CmsError('CMS_LIMIT', `A user can have at most ${API_TOKEN_LIMIT} application passwords.`);
46
- const id = randomToken(12);
47
- const secret = randomToken(32);
48
- await this.#db.write([{
49
- rql: 'INSERT INTO cms_api_tokens (id, user_id, name, secret_hash, scope, created_at, expires_at) VALUES ($id, $user, $name, $hash, $scope, $now, $expires)',
50
- params: { $id: id, $user: userId, $name: name, $hash: await sha256Hex(secret), $scope: scope, $now: now, $expires: input.expiresAt ?? null },
51
- }], WRITE);
52
- return { token: `cms_${id}.${secret}`, record: { id, userId, name, scope, createdAt: now, lastUsedAt: null, expiresAt: input.expiresAt ?? null } };
53
- }
54
-
55
- async list(userId: string): Promise<ApiToken[]> {
56
- const result = await this.#db.read([{ rql: `SELECT ${COLUMNS} FROM cms_api_tokens WHERE user_id = $user ORDER BY created_at DESC LIMIT 100`, params: { $user: userId } }]);
57
- return result.results[0]!.rows.map(tokenOf);
58
- }
59
-
60
- async revoke(userId: string, id: string): Promise<void> {
61
- const result = await this.#db.write([{ rql: 'DELETE FROM cms_api_tokens WHERE id = $id AND user_id = $user', params: { $id: id, $user: userId } }], WRITE);
62
- if (result.results[0]!.affected === 0n) throw new CmsError('CMS_NOT_FOUND', 'Application password not found.');
63
- }
64
-
65
- async revokeAll(userId: string): Promise<void> {
66
- await this.#db.write([{ rql: 'DELETE FROM cms_api_tokens WHERE user_id = $user', params: { $user: userId } }], WRITE);
67
- }
68
-
69
- /** The token's owner and access, or null for an unknown, wrong or expired token. Use is recorded at most every five minutes. */
70
- async verify(token: string): Promise<{ id: string; userId: string; scope: ApiTokenScope } | null> {
71
- const match = typeof token === 'string' ? FORMAT.exec(token) : null;
72
- if (!match) return null;
73
- const [, id, secret] = match;
74
- const result = await this.#db.read([{ rql: 'SELECT user_id, secret_hash, scope, expires_at, last_used_at FROM cms_api_tokens WHERE id = $id', params: { $id: id! } }]);
75
- const row = result.results[0]!.rows[0];
76
- if (!row || !timingSafeEqual(row[1] as string, await sha256Hex(secret!))) return null;
77
- const now = this.#now();
78
- if (row[3] !== null && Number(row[3] as bigint) <= now) return null;
79
- if (row[4] === null || now - Number(row[4] as bigint) > 5 * 60_000) {
80
- await this.#db.write([{ rql: 'UPDATE cms_api_tokens SET last_used_at = $now WHERE id = $id', params: { $now: now, $id: id! } }], WRITE).catch(() => undefined);
81
- }
82
- return { id: id!, userId: row[0] as string, scope: row[2] as ApiTokenScope };
83
- }
84
- }
85
-
86
- function tokenOf(row: readonly unknown[]): ApiToken {
87
- return Object.freeze({
88
- id: row[0] as string, userId: row[1] as string, name: row[2] as string, scope: row[3] as ApiTokenScope, createdAt: Number(row[4] as bigint),
89
- lastUsedAt: row[5] === null ? null : Number(row[5] as bigint), expiresAt: row[6] === null ? null : Number(row[6] as bigint),
90
- });
91
- }
@@ -1,89 +0,0 @@
1
- /**
2
- * Auth integration: `@cossackframework/auth` primitives backed by CMS users and RomeDB
3
- * auth sessions. The request user is a CMS principal resolved from current storage.
4
- */
5
- import { createAuth, createSessionManager, type AuthKit, type AuthRealtimeProvider, type AuthSessionManager } from '@cossackframework/auth';
6
- import type { Context } from 'hono';
7
- import { getCookie } from 'hono/cookie';
8
- import { ANONYMOUS, type Principal } from '../permissions';
9
- import type { CmsHost } from './host';
10
- import type { CmsUser } from './users';
11
-
12
- /** The user placed on the request context by the auth middleware. */
13
- export interface CmsRequestUser extends CmsUser {
14
- readonly principal: Principal;
15
- }
16
-
17
- export interface CmsAuth {
18
- readonly sessions: AuthSessionManager;
19
- /** Realtime descriptor provider: a stable session reference plus a token fingerprint. */
20
- readonly realtime: AuthRealtimeProvider;
21
- readonly auth: AuthKit<CmsRequestUser>;
22
- readonly cookieName: string;
23
- /** Sign in with email and password; returns the cookie headers to apply, or null. */
24
- signIn(email: string, password: string, c: Context): Promise<{ user: CmsRequestUser; headers: Headers } | null>;
25
- signOut(c: Context): Promise<Headers>;
26
- /** The principal of the current request: the signed-in user, or anonymous. */
27
- principal(c: Context): Principal;
28
- }
29
-
30
- export interface CmsAuthOptions {
31
- /** Session lifetime in seconds. Default 7 days. */
32
- ttlSeconds?: number;
33
- cookieName?: string;
34
- secure?: boolean;
35
- }
36
-
37
- const sha256 = async (text: string) => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))]
38
- .map(byte => byte.toString(16).padStart(2, '0')).join('');
39
-
40
- export function createCmsAuth(cms: CmsHost, options: CmsAuthOptions = {}): CmsAuth {
41
- const cookieName = options.cookieName ?? 'cms_session';
42
- const sessions = createSessionManager({
43
- store: cms.authSessions,
44
- ttlSeconds: options.ttlSeconds ?? 7 * 24 * 60 * 60,
45
- cookie: { name: cookieName, ...(options.secure === undefined ? {} : { secure: options.secure }) },
46
- now: () => cms.now(),
47
- });
48
- const resolve = (userId: string): Promise<CmsRequestUser | null> => cms.users.resolve(userId);
49
- const realtime: AuthRealtimeProvider = {
50
- key: 'cossack.session',
51
- // The public reference survives rotation; the fingerprint does not.
52
- capture: async sessionId => ({ reference: await cms.authSessions.publicReference(sessionId), fingerprint: await sha256(sessionId) }),
53
- validate: async data => {
54
- const descriptor = data as { reference?: unknown; fingerprint?: unknown };
55
- if (typeof descriptor?.reference !== 'string' || typeof descriptor.fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(descriptor.fingerprint)) return null;
56
- const row = await cms.authSessions.findByReference(descriptor.reference);
57
- if (!row || row.expiresAt <= cms.now() || await sha256(row.id) !== descriptor.fingerprint) return null;
58
- return row.userId;
59
- },
60
- };
61
- const auth = createAuth<CmsRequestUser>({
62
- extractSessionId: c => getCookie(c, cookieName),
63
- validateSessionId: async (id, c) => (await sessions.validate(id, c))?.userId ?? null,
64
- resolveUserById: id => resolve(id),
65
- createSession: async (user, c) => ({ headers: (await sessions.create(user.id, c)).headers }),
66
- realtime,
67
- });
68
- return {
69
- sessions,
70
- realtime,
71
- auth,
72
- cookieName,
73
- async signIn(email, password, c) {
74
- const verified = await cms.accounts.verifier.verify(email, password);
75
- if (!verified || verified.status !== 'active') return null;
76
- // An account signs in where it is a member.
77
- const user = await resolve(verified.id);
78
- if (!user) return null;
79
- return { user, headers: (await sessions.create(user.id, c)).headers };
80
- },
81
- async signOut(c) {
82
- const id = getCookie(c, cookieName);
83
- return id ? sessions.revoke(id, c) : sessions.expiredCookie();
84
- },
85
- principal(c) {
86
- return (c.get('user') as CmsRequestUser | undefined)?.principal ?? ANONYMOUS;
87
- },
88
- };
89
- }