@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
@@ -124,11 +124,9 @@ async function importInto(host: CmsHost, source: ReadableStream<Uint8Array> | As
124
124
  // Unrestricted access is granted where it runs, and network admins are the network's: an export can make neither.
125
125
  await write([
126
126
  { rql: 'DELETE FROM cms_grants WHERE permission = $permission', params: { $permission: UNRESTRICTED_GRANT } },
127
- { rql: 'DELETE FROM cms_user_roles WHERE role_id = $role', params: { $role: NETWORK_ADMIN } },
128
- { rql: 'DELETE FROM cms_roles WHERE id = $role', params: { $role: NETWORK_ADMIN } },
129
127
  ]);
130
128
  if (!collections) await openCollections(host, options);
131
- const members = await adoptMembers(host, before);
129
+ const members = await adoptPeople(host, before);
132
130
  await lease.release();
133
131
  forget(host);
134
132
  await host.ready({ force: true });
@@ -144,7 +142,7 @@ export async function siteImportState(host: CmsHost): Promise<'new' | 'stopped'
144
142
  if (!(await host.installed())) return 'new';
145
143
  const marker = (await host.db.read([{ rql: 'SELECT updated_at FROM cms_network WHERE key = $key', params: { $key: IMPORT_KEY } }])).results[0]!.rows[0];
146
144
  if (marker) return Number(marker[0] as bigint) > host.now() - IMPORT_LEASE_MS ? 'running' : 'stopped';
147
- return (await (host.siteAccounts ?? host.accounts).count()) > 0 || await hasEntries(host) ? 'used' : 'new';
145
+ return (await ownAccounts(host)) > 0 || await hasEntries(host) ? 'used' : 'new';
148
146
  }
149
147
 
150
148
  /** The imported collection and taxonomy definitions are loaded and migrated, so their tables exist. */
@@ -219,7 +217,7 @@ async function claim(host: CmsHost): Promise<Lease> {
219
217
  if (Number(marker[0] as bigint) > now - IMPORT_LEASE_MS) throw new CmsError('CMS_CONFLICT', 'An import into this site is running. Wait for it to finish.');
220
218
  } else {
221
219
  // An added site's own accounts, or on the main site any account: a fresh install has none.
222
- if ((await (host.siteAccounts ?? host.accounts).count()) > 0 || await hasEntries(host)) {
220
+ if ((await ownAccounts(host)) > 0 || await hasEntries(host)) {
223
221
  throw new CmsError('CMS_CONFLICT', 'Import into a new site: this one has entries or accounts of its own.');
224
222
  }
225
223
  }
@@ -260,38 +258,19 @@ async function hasEntries(host: CmsHost): Promise<boolean> {
260
258
  * accounts without passwords, set with Forgot password. Network members from before the
261
259
  * import that the export does not have stay members, unless their email is now taken.
262
260
  */
263
- async function adoptMembers(host: CmsHost, before: readonly { id: string; roles: readonly string[] }[]): Promise<SiteImportReport['members']> {
264
- const counts = { network: 0, site: 0, pending: 0 };
265
- const now = host.now();
266
- for (let offset = 0; ; offset += 200) {
267
- const ids = (await host.db.read([{ rql: 'SELECT id FROM cms_users ORDER BY id LIMIT 200 OFFSET $offset', params: { $offset: offset } }])).results[0]!.rows.map(row => row[0] as string);
268
- if (!ids.length) break;
269
- const network = await host.accounts.existing(ids);
270
- const local = host.siteAccounts ? await host.siteAccounts.existing(ids) : new Set<string>();
271
- for (const id of ids) if (network.has(id)) { await host.accounts.join(id, host.site); counts.network++; }
272
- const orphans = ids.filter(id => !network.has(id) && !local.has(id));
273
- if (host.siteAccounts && orphans.length) {
274
- const params = Object.fromEntries(orphans.map((id, index) => [`$u${index}`, id]));
275
- await host.db.write([{
276
- 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 IN (${orphans.map((_, index) => `$u${index}`).join(', ')}) ON CONFLICT (id) DO NOTHING`,
277
- params: { ...params, $now: now },
278
- }], WRITE);
279
- counts.site += orphans.length;
280
- } else counts.pending += orphans.length;
281
- counts.site += [...local].length;
282
- if (ids.length < 200) break;
283
- }
261
+ /** The accounts that are this site's own: an added site's site accounts, or on the main site any account. */
262
+ async function ownAccounts(host: CmsHost): Promise<number> {
263
+ return host.people.ownCount ? host.people.ownCount() : host.people.count();
264
+ }
265
+
266
+ /** With accounts kept by the application: the imported users become people of this site, and the members from before stay. */
267
+ async function adoptPeople(host: CmsHost, before: readonly { id: string; roles: readonly string[] }[]): Promise<SiteImportReport['members']> {
268
+ const counts = { ...(await host.people.adopt?.() ?? { network: 0, site: 0, pending: 0 }) };
284
269
  for (const member of before) {
285
270
  if (await host.users.get(member.id)) continue;
286
- try { await host.users.addMember(member.id); }
287
- catch {
288
- await host.accounts.leave(member.id, host.site);
289
- continue;
290
- }
291
271
  const roles = [];
292
272
  for (const role of member.roles) if (await host.users.role(role)) roles.push(role);
293
- await host.users.setRoles(member.id, roles);
294
- counts.network++;
273
+ if (await host.users.addMember(member.id, { roles }).catch(() => null)) counts.network++;
295
274
  }
296
275
  return counts;
297
276
  }
@@ -1,9 +1,10 @@
1
1
  /** Settings declarations, authorized portable documents, and atomic storage. */
2
- import { ClientError, LOCAL_REQUEST_BYTES, UncertainWriteError, encodeValue, type RomeDB, type Statement } from '@cossackframework/romedb';
2
+ import { ClientError, LOCAL_REQUEST_BYTES, UncertainWriteError, encodeValue, isClientFull, type RomeDB, type Statement } from '@cossackframework/romedb';
3
3
 
4
4
  /** Room a request needs besides its statement: its identity and work limits. */
5
5
  const REQUEST_ROOM = 4096;
6
6
  import { CmsError } from '../errors';
7
+ import { sharedRead } from './shared-read';
7
8
  import { FIELD_NAME } from '../fields';
8
9
  import { hasPermission, PERMISSIONS, principalId, type Principal } from '../permissions';
9
10
  import { OWNER_NAME } from '../resource';
@@ -79,7 +80,11 @@ export class CmsSettings {
79
80
  }
80
81
 
81
82
  /** Internal server reads, with defaults. Never expose this method directly through browser RPC. */
82
- async all(): Promise<SiteSettings> {
83
+ all(): Promise<SiteSettings> {
84
+ return sharedRead(() => this.#all());
85
+ }
86
+
87
+ async #all(): Promise<SiteSettings> {
83
88
  const now = this.#now();
84
89
  if (!this.#cache || now - this.#cache.at > this.#ttl) {
85
90
  const values = this.#read();
@@ -255,7 +260,8 @@ export class CmsSettings {
255
260
  try { result = await this.#db.read([{ rql: 'SELECT key, value FROM cms_settings WHERE key > $after ORDER BY key LIMIT $limit', params: { $after: after, $limit: pageSize } }]); }
256
261
  catch (error) {
257
262
  if (error instanceof ClientError && /cms_settings/i.test(error.message) && /no such table|not found|does not exist/i.test(error.message)) return { values: Object.freeze(values) as SiteSettings, errors };
258
- if (error instanceof ClientError && (error.code === 'RDB_LIMIT' || error.code === 'RDB_RESULT_TOO_LARGE') && pageSize > 1) { pageSize = Math.max(1, Math.floor(pageSize / 2)); continue; }
263
+ // A page too large to return comes in smaller pages. A client whose places are full says nothing about the page.
264
+ if (error instanceof ClientError && (error.code === 'RDB_LIMIT' || error.code === 'RDB_RESULT_TOO_LARGE') && !isClientFull(error) && pageSize > 1) { pageSize = Math.max(1, Math.floor(pageSize / 2)); continue; }
259
265
  throw error;
260
266
  }
261
267
  if (sequence !== undefined && sequence !== result.sequence) break;
@@ -1,12 +1,11 @@
1
1
  /**
2
- * The site registry on the network database. Each added site has its own database, named by
3
- * `database`, and answers on its domains: one primary, the rest aliases that redirect to it.
4
- * The main site is the network database itself; it has no row, but may own domains.
2
+ * A network's sites. Each added site has its own database, named by `database`, and answers
3
+ * on its domains: one primary, the rest aliases that redirect to it. The main site is the
4
+ * network database itself; it has no record, but may own domains. The registry is the
5
+ * application's (`SitesStore`).
5
6
  */
6
- import { ClientError, type RomeDB, type Value } from '@cossackframework/romedb';
7
7
  import { CmsError } from '../errors';
8
8
  import { MAIN_SITE } from '../permissions';
9
- import { inList } from './users';
10
9
 
11
10
  /** The main site: the network database, with no registry row. */
12
11
  export { MAIN_SITE };
@@ -38,11 +37,7 @@ export interface SiteRecord {
38
37
  const ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
39
38
  /** IDs no added site takes: the main site's, and `new`, the dashboard's Add site address. */
40
39
  export const RESERVED_SITE_IDS: ReadonlySet<string> = new Set([MAIN_SITE, 'new']);
41
- const DATABASE = /^[A-Za-z0-9_-]{1,80}$/;
42
40
  const HOST = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
43
- const STATUSES: readonly SiteStatus[] = ['creating', 'active', 'archived', 'deleted'];
44
- const COLUMNS = 'id, name, database, status, step, created_at, updated_at, deleted_at';
45
- const WRITE = { kind: 'cms.sites', retryConflicts: 5 } as const;
46
41
 
47
42
  /** A host as the registry stores it: lowercase, without port or trailing dot. Empty when invalid. */
48
43
  export function siteHost(host: string): string {
@@ -50,194 +45,129 @@ export function siteHost(host: string): string {
50
45
  return HOST.test(name) ? name : '';
51
46
  }
52
47
 
53
- export class CmsSites {
54
- readonly #db: RomeDB;
55
- readonly #now: () => number;
56
-
57
- constructor(db: RomeDB, options: { now?: () => number } = {}) {
58
- this.#db = db;
59
- this.#now = options.now ?? Date.now;
60
- }
61
-
48
+ /**
49
+ * The registry of a network's sites, which the application keeps (the dashboard package's
50
+ * tenants in a CMS project). The main site has no record: it is the network's own database.
51
+ */
52
+ export interface SitesStore {
62
53
  /** Added sites, deleted ones included: zero while the network is only the main site. */
63
- async count(): Promise<number> {
64
- const result = await this.#db.read([{ rql: 'SELECT count(*) FROM cms_sites' }]);
65
- return Number(result.results[0]!.rows[0]![0] as bigint);
66
- }
67
-
68
- async get(id: string): Promise<SiteRecord | null> {
69
- if (!ID.test(id) || id === MAIN_SITE) return null;
70
- return (await this.#many([id]))[0] ?? null;
71
- }
72
-
73
- /** The added sites among the IDs, in one read; unknown IDs and the main site are left out. */
74
- async getMany(ids: readonly string[]): Promise<SiteRecord[]> {
75
- const wanted = [...new Set(ids.filter(id => ID.test(id) && id !== MAIN_SITE))];
76
- return wanted.length ? this.#many(wanted) : [];
77
- }
78
-
54
+ count(): Promise<number>;
55
+ get(id: string): Promise<SiteRecord | null>;
56
+ /** The added sites among the IDs; unknown IDs and the main site are left out. */
57
+ getMany(ids: readonly string[]): Promise<SiteRecord[]>;
79
58
  /** Newest first. `search` matches the name or a domain. */
80
- async list(options: { search?: string; status?: SiteStatus; limit?: number; offset?: number } = {}): Promise<{ items: SiteRecord[]; total: number }> {
81
- const conditions: string[] = [];
82
- const params: { [key: string]: Value } = {};
83
- if (options.search?.trim()) {
84
- conditions.push("(lower(name) LIKE $q ESCAPE '\\' OR id IN (SELECT site_id FROM cms_site_domains WHERE host LIKE $q ESCAPE '\\'))");
85
- params.$q = `%${options.search.trim().toLowerCase().slice(0, 100).replace(/[\\%_]/g, character => `\\${character}`)}%`;
86
- }
87
- if (options.status) { conditions.push('status = $status'); params.$status = options.status; }
88
- const where = conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '';
89
- const result = await this.#db.read([
90
- { rql: `SELECT id FROM cms_sites${where} ORDER BY created_at DESC, id LIMIT $limit OFFSET $offset`, params: { ...params, $limit: Math.min(Math.max(options.limit ?? 20, 1), 100), $offset: Math.max(options.offset ?? 0, 0) } },
91
- { rql: `SELECT count(*) FROM cms_sites${where}`, params },
92
- ]);
93
- return { items: await this.#many(result.results[0]!.rows.map(row => row[0] as string)), total: Number(result.results[1]!.rows[0]![0] as bigint) };
94
- }
95
-
59
+ list(options?: { search?: string; status?: SiteStatus; limit?: number; offset?: number }): Promise<{ items: SiteRecord[]; total: number }>;
96
60
  /** Active and archived sites in ID order, starting after `after` and wrapping around: scheduled work visits them in turn. */
97
- async inTurn(after: string, limit = 50): Promise<SiteRecord[]> {
98
- const result = await this.#db.read([{ rql: "SELECT id FROM cms_sites WHERE status IN ('active', 'archived') ORDER BY id <= $after, id LIMIT $limit",
99
- params: { $after: after, $limit: Math.min(Math.max(limit, 1), 200) } }]);
100
- return this.#many(result.results[0]!.rows.map(row => row[0] as string));
101
- }
102
-
61
+ inTurn(after: string, limit?: number): Promise<SiteRecord[]>;
103
62
  /** The site a host belongs to, `main` for the main site's own domains, or null. */
104
- async siteOf(host: string): Promise<{ site: string; domain: SiteDomain } | null> {
105
- const name = siteHost(host);
106
- if (!name) return null;
107
- const result = await this.#db.read([{ rql: 'SELECT site_id, host, is_primary, verified_at FROM cms_site_domains WHERE host = $host', params: { $host: name } }]);
108
- const row = result.results[0]!.rows[0];
109
- return row ? { site: row[0] as string, domain: domainOf(row.slice(1)) } : null;
110
- }
111
-
112
- /**
113
- * Register a site and its domains in one write. The first domain is primary unless one
114
- * says otherwise. A domain another site has is a conflict.
115
- */
116
- async create(input: { id: string; name: string; database: string; status?: SiteStatus; step?: string | null; domains: readonly { host: string; primary?: boolean; verifiedAt?: number | null }[] }): Promise<SiteRecord> {
117
- if (!ID.test(input.id) || RESERVED_SITE_IDS.has(input.id)) throw new CmsError('CMS_VALIDATION', 'Site IDs are lowercase letters, digits and hyphens, other than main and new.', { fields: { id: 'is invalid.' } });
118
- if (!DATABASE.test(input.database)) throw new CmsError('CMS_VALIDATION', 'Invalid database ID.');
119
- checkName(input.name);
120
- const status = input.status ?? 'active';
121
- if (!STATUSES.includes(status)) throw new CmsError('CMS_VALIDATION', 'Unknown site status.');
122
- const domains = checkDomains(input.domains);
123
- const now = this.#now();
124
- try {
125
- await this.#db.write([
126
- { rql: 'INSERT INTO cms_sites (id, name, database, status, step, created_at, updated_at) VALUES ($id, $name, $database, $status, $step, $now, $now)',
127
- params: { $id: input.id, $name: input.name.trim(), $database: input.database, $status: status, $step: input.step ?? null, $now: now } },
128
- ...domains.map(domain => ({ rql: 'INSERT INTO cms_site_domains (host, site_id, is_primary, verified_at, created_at) VALUES ($host, $site, $primary, $verified, $now)',
129
- params: { $host: domain.host, $site: input.id, $primary: domain.primary ? 1 : 0, $verified: domain.verifiedAt, $now: now } })),
130
- ], WRITE);
131
- } catch (error) {
132
- if (error instanceof ClientError && error.outcome === 'rolled-back' && /UNIQUE|PRIMARY/i.test(error.message)) {
133
- throw new CmsError('CMS_CONFLICT', /cms_sites\.database/.test(error.message) ? 'Another site uses this database.' : /cms_sites/.test(error.message) ? 'A site with this ID exists.' : 'Another site answers on this domain.');
134
- }
135
- throw error;
136
- }
137
- return (await this.get(input.id))!;
138
- }
139
-
63
+ siteOf(host: string): Promise<{ site: string; domain: SiteDomain } | null>;
64
+ /** Register a site and its domains. The first domain is primary unless one says otherwise. A domain another site has is a conflict. */
65
+ create(input: { id: string; name: string; database: string; status?: SiteStatus; step?: string | null; domains: readonly { host: string; primary?: boolean; verifiedAt?: number | null }[] }): Promise<SiteRecord>;
140
66
  /** Change the name, database, status or creation step. A deleted site records when it was deleted. */
141
- async update(id: string, patch: { name?: string; database?: string; status?: SiteStatus; step?: string | null }): Promise<SiteRecord | null> {
142
- const current = await this.get(id);
143
- if (!current) return null;
144
- if (patch.name !== undefined) checkName(patch.name);
145
- if (patch.database !== undefined && !DATABASE.test(patch.database)) throw new CmsError('CMS_VALIDATION', 'Invalid database ID.');
146
- const status = patch.status ?? current.status;
147
- if (!STATUSES.includes(status)) throw new CmsError('CMS_VALIDATION', 'Unknown site status.');
148
- const now = this.#now();
149
- const deletedAt = status === 'deleted' ? current.deletedAt ?? now : null;
150
- await this.#db.write([{ rql: 'UPDATE cms_sites SET name = $name, database = $database, status = $status, step = $step, deleted_at = $deleted, updated_at = $now WHERE id = $id',
151
- params: { $id: id, $name: (patch.name ?? current.name).trim(), $database: patch.database ?? current.database, $status: status, $step: patch.step === undefined ? current.step : patch.step, $deleted: deletedAt, $now: now } }], WRITE);
152
- return this.get(id);
153
- }
154
-
67
+ update(id: string, patch: { name?: string; database?: string; status?: SiteStatus; step?: string | null }): Promise<SiteRecord | null>;
155
68
  /** Add a domain that is not checked yet; it answers as an alias until a check makes it primary. */
156
- async addDomain(id: string, host: string): Promise<SiteRecord | null> {
157
- const name = siteHost(host);
158
- if (!name) throw new CmsError('CMS_VALIDATION', 'Enter a host name, such as blog.example.com.', { fields: { host: 'is invalid.' } });
159
- if (id !== MAIN_SITE && !(await this.get(id))) return null;
160
- try {
161
- await this.#db.write([{ rql: 'INSERT INTO cms_site_domains (host, site_id, is_primary, verified_at, created_at) VALUES ($host, $site, 0, NULL, $now)', params: { $host: name, $site: id, $now: this.#now() } }], WRITE);
162
- } catch (error) {
163
- if (error instanceof ClientError && error.outcome === 'rolled-back' && /UNIQUE|PRIMARY/i.test(error.message)) throw new CmsError('CMS_CONFLICT', 'Another site answers on this domain.', { fields: { host: 'is taken.' } });
164
- throw error;
165
- }
166
- return id === MAIN_SITE ? null : this.get(id);
167
- }
168
-
69
+ addDomain(id: string, host: string): Promise<SiteRecord | null>;
169
70
  /** Record that the domain answered its check, and make it the site's primary domain when asked. */
170
- async verifyDomain(id: string, host: string, options: { primary?: boolean } = {}): Promise<boolean> {
171
- const name = siteHost(host);
172
- const now = this.#now();
173
- const result = await this.#db.write([
174
- { rql: 'UPDATE cms_site_domains SET verified_at = $now WHERE host = $host AND site_id = $site', params: { $host: name, $site: id, $now: now } },
175
- ...(options.primary ? [
176
- { rql: 'UPDATE cms_site_domains SET is_primary = 0 WHERE site_id = $site AND host != $host AND EXISTS (SELECT 1 FROM cms_site_domains WHERE host = $host AND site_id = $site)', params: { $host: name, $site: id } },
177
- { rql: 'UPDATE cms_site_domains SET is_primary = 1 WHERE host = $host AND site_id = $site', params: { $host: name, $site: id } },
178
- ] : []),
179
- ], WRITE);
180
- return result.results[0]!.affected === 1n;
181
- }
182
-
71
+ verifyDomain(id: string, host: string, options?: { primary?: boolean }): Promise<boolean>;
183
72
  /** Remove an alias. The primary domain stays until another one is primary. */
184
- async removeDomain(id: string, host: string): Promise<boolean> {
185
- const result = await this.#db.write([{ rql: 'DELETE FROM cms_site_domains WHERE host = $host AND site_id = $site AND is_primary = 0', params: { $host: siteHost(host), $site: id } }], WRITE);
186
- return result.results[0]!.affected === 1n;
187
- }
188
-
73
+ removeDomain(id: string, host: string): Promise<boolean>;
189
74
  /** Sites deleted before this time, oldest first: their 30 days to restore are over. */
190
- async deletedBefore(at: number, limit = 20): Promise<SiteRecord[]> {
191
- const result = await this.#db.read([{ rql: "SELECT id FROM cms_sites WHERE status = 'deleted' AND deleted_at < $at ORDER BY deleted_at LIMIT $limit", params: { $at: at, $limit: limit } }]);
192
- return this.#many(result.results[0]!.rows.map(row => row[0] as string));
193
- }
194
-
75
+ deletedBefore(at: number, limit?: number): Promise<SiteRecord[]>;
195
76
  /** Forget a site, its domains and its members' memberships, once its database and media are gone. */
196
- async remove(id: string): Promise<void> {
197
- await this.#db.write([
198
- { rql: 'DELETE FROM cms_site_domains WHERE site_id = $id', params: { $id: id } },
199
- { rql: 'DELETE FROM cms_memberships WHERE site_id = $id', params: { $id: id } },
200
- { rql: 'DELETE FROM cms_session_sites WHERE site_id = $id', params: { $id: id } },
201
- { rql: 'DELETE FROM cms_handoffs WHERE site_id = $id', params: { $id: id } },
202
- { rql: 'DELETE FROM cms_sites WHERE id = $id', params: { $id: id } },
203
- ], WRITE);
204
- }
205
-
206
- async #many(ids: readonly string[]): Promise<SiteRecord[]> {
207
- if (!ids.length) return [];
208
- const list = inList('s', ids);
209
- const result = await this.#db.read([
210
- { rql: `SELECT ${COLUMNS} FROM cms_sites WHERE id IN ${list.rql}`, params: list.params },
211
- { rql: `SELECT site_id, host, is_primary, verified_at FROM cms_site_domains WHERE site_id IN ${list.rql} ORDER BY is_primary DESC, host`, params: list.params },
212
- ]);
213
- const domains = new Map<string, SiteDomain[]>();
214
- for (const row of result.results[1]!.rows) {
215
- const entry = domains.get(row[0] as string) ?? [];
216
- entry.push(domainOf(row.slice(1)));
217
- domains.set(row[0] as string, entry);
218
- }
219
- const sites = new Map(result.results[0]!.rows.map(row => [row[0] as string, Object.freeze({
220
- id: row[0] as string, name: row[1] as string, database: row[2] as string, status: row[3] as SiteStatus, step: row[4] as string | null,
221
- domains: Object.freeze(domains.get(row[0] as string) ?? []), createdAt: Number(row[5] as bigint), updatedAt: Number(row[6] as bigint),
222
- deletedAt: row[7] === null ? null : Number(row[7] as bigint),
223
- })]));
224
- return ids.map(id => sites.get(id)).filter((site): site is SiteRecord => site !== undefined);
225
- }
77
+ remove(id: string): Promise<void>;
226
78
  }
227
79
 
228
- function domainOf(row: readonly Value[]): SiteDomain {
229
- return Object.freeze({ host: row[0] as string, primary: Number(row[1] as bigint) === 1, verifiedAt: row[2] === null ? null : Number(row[2] as bigint) });
230
- }
231
-
232
- function checkName(name: string): void {
233
- if (typeof name !== 'string' || !name.trim() || name.length > 120) throw new CmsError('CMS_VALIDATION', 'Enter a site name of at most 120 characters.', { fields: { name: 'is required.' } });
234
- }
235
-
236
- function checkDomains(domains: readonly { host: string; primary?: boolean; verifiedAt?: number | null }[]): { host: string; primary: boolean; verifiedAt: number | null }[] {
237
- if (!domains.length || domains.length > 20) throw new CmsError('CMS_VALIDATION', 'A site needs 1 to 20 domains.', { fields: { domains: 'are required.' } });
238
- const hosts = domains.map(domain => siteHost(domain.host));
239
- if (hosts.some(host => !host) || new Set(hosts).size !== hosts.length) throw new CmsError('CMS_VALIDATION', 'Enter each domain once, as a host name such as blog.example.com.', { fields: { domains: 'are invalid.' } });
240
- const primary = domains.findIndex(domain => domain.primary);
241
- if (domains.filter(domain => domain.primary).length > 1) throw new CmsError('CMS_VALIDATION', 'A site has one primary domain.', { fields: { domains: 'have two primaries.' } });
242
- return domains.map((domain, index) => ({ host: hosts[index]!, primary: index === (primary < 0 ? 0 : primary), verifiedAt: domain.verifiedAt ?? null }));
80
+ /**
81
+ * A registry of sites kept in memory: for tests, and for trying a network without an
82
+ * application around it. It follows the rules an application's registry must follow.
83
+ */
84
+ export function memorySites(options: { now?: () => number } = {}): SitesStore {
85
+ const now = options.now ?? Date.now;
86
+ const sites = new Map<string, { id: string; name: string; database: string; status: SiteStatus; step: string | null; createdAt: number; updatedAt: number; deletedAt: number | null }>();
87
+ const domains = new Map<string, { site: string; primary: boolean; verifiedAt: number | null }>();
88
+ const record = (id: string): SiteRecord | null => {
89
+ const site = sites.get(id);
90
+ if (!site) return null;
91
+ const own = [...domains].filter(([, domain]) => domain.site === id).map(([host, domain]): SiteDomain => Object.freeze({ host, primary: domain.primary, verifiedAt: domain.verifiedAt }))
92
+ .sort((a, b) => Number(b.primary) - Number(a.primary) || (a.host < b.host ? -1 : 1));
93
+ return Object.freeze({ ...site, domains: Object.freeze(own) });
94
+ };
95
+ const checkName = (name: string) => {
96
+ if (typeof name !== 'string' || !name.trim() || name.length > 120) throw new CmsError('CMS_VALIDATION', 'Enter a site name of at most 120 characters.', { fields: { name: 'is required.' } });
97
+ };
98
+ return {
99
+ async count() { return sites.size; },
100
+ async get(id) { return id === MAIN_SITE ? null : record(id); },
101
+ async getMany(ids) { return [...new Set(ids)].filter(id => id !== MAIN_SITE).map(record).filter((site): site is SiteRecord => site !== null); },
102
+ async list(listOptions = {}) {
103
+ const search = listOptions.search?.trim().toLowerCase();
104
+ const all = [...sites.values()].sort((a, b) => b.createdAt - a.createdAt || (a.id < b.id ? -1 : 1)).map(site => record(site.id)!)
105
+ .filter(site => !listOptions.status || site.status === listOptions.status)
106
+ .filter(site => !search || site.name.toLowerCase().includes(search) || site.domains.some(domain => domain.host.includes(search)));
107
+ const offset = Math.max(listOptions.offset ?? 0, 0);
108
+ return { items: all.slice(offset, offset + Math.min(Math.max(listOptions.limit ?? 20, 1), 100)), total: all.length };
109
+ },
110
+ async inTurn(after, limit = 50) {
111
+ const live = [...sites.values()].filter(site => site.status === 'active' || site.status === 'archived').map(site => site.id).sort();
112
+ return [...live.filter(id => id > after), ...live.filter(id => id <= after)].slice(0, Math.min(Math.max(limit, 1), 200)).map(id => record(id)!);
113
+ },
114
+ async siteOf(host) {
115
+ const name = siteHost(host);
116
+ const domain = domains.get(name);
117
+ return domain ? { site: domain.site, domain: Object.freeze({ host: name, primary: domain.primary, verifiedAt: domain.verifiedAt }) } : null;
118
+ },
119
+ async create(input) {
120
+ if (!ID.test(input.id) || RESERVED_SITE_IDS.has(input.id)) throw new CmsError('CMS_VALIDATION', 'Site IDs are lowercase letters, digits and hyphens, other than main and new.', { fields: { id: 'is invalid.' } });
121
+ checkName(input.name);
122
+ const hosts = input.domains.map(domain => siteHost(domain.host));
123
+ if (!hosts.length || hosts.length > 20 || hosts.some(host => !host) || new Set(hosts).size !== hosts.length) throw new CmsError('CMS_VALIDATION', 'Enter each domain once, as a host name such as blog.example.com.', { fields: { domains: 'are invalid.' } });
124
+ if (sites.has(input.id)) throw new CmsError('CMS_CONFLICT', 'A site with this ID exists.', { fields: { id: 'is taken.' } });
125
+ if ([...sites.values()].some(site => site.database === input.database)) throw new CmsError('CMS_CONFLICT', 'Another site uses this database.');
126
+ if (hosts.some(host => domains.has(host))) throw new CmsError('CMS_CONFLICT', 'Another site answers on this domain.', { fields: { host: 'is taken.' } });
127
+ const at = now();
128
+ sites.set(input.id, { id: input.id, name: input.name.trim(), database: input.database, status: input.status ?? 'active', step: input.step ?? null, createdAt: at, updatedAt: at, deletedAt: null });
129
+ const primary = Math.max(input.domains.findIndex(domain => domain.primary), 0);
130
+ input.domains.forEach((domain, index) => domains.set(hosts[index]!, { site: input.id, primary: index === primary, verifiedAt: domain.verifiedAt ?? null }));
131
+ return record(input.id)!;
132
+ },
133
+ async update(id, patch) {
134
+ const site = sites.get(id);
135
+ if (!site) return null;
136
+ if (patch.name !== undefined) checkName(patch.name);
137
+ const status = patch.status ?? site.status;
138
+ sites.set(id, { ...site, name: (patch.name ?? site.name).trim(), database: patch.database ?? site.database, status, step: patch.step === undefined ? site.step : patch.step,
139
+ deletedAt: status === 'deleted' ? site.deletedAt ?? now() : null, updatedAt: now() });
140
+ return record(id);
141
+ },
142
+ async addDomain(id, host) {
143
+ const name = siteHost(host);
144
+ if (!name) throw new CmsError('CMS_VALIDATION', 'Enter a host name, such as blog.example.com.', { fields: { host: 'is invalid.' } });
145
+ if (id !== MAIN_SITE && !sites.has(id)) return null;
146
+ if (domains.has(name)) throw new CmsError('CMS_CONFLICT', 'Another site answers on this domain.', { fields: { host: 'is taken.' } });
147
+ domains.set(name, { site: id, primary: false, verifiedAt: null });
148
+ return id === MAIN_SITE ? null : record(id);
149
+ },
150
+ async verifyDomain(id, host, verifyOptions = {}) {
151
+ const name = siteHost(host);
152
+ const domain = domains.get(name);
153
+ if (!domain || domain.site !== id) return false;
154
+ if (verifyOptions.primary) for (const [other, entry] of domains) if (entry.site === id) domains.set(other, { ...entry, primary: false });
155
+ domains.set(name, { site: id, primary: verifyOptions.primary ? true : domain.primary, verifiedAt: now() });
156
+ return true;
157
+ },
158
+ async removeDomain(id, host) {
159
+ const name = siteHost(host);
160
+ const domain = domains.get(name);
161
+ if (!domain || domain.site !== id || domain.primary) return false;
162
+ return domains.delete(name);
163
+ },
164
+ async deletedBefore(at, limit = 20) {
165
+ return [...sites.values()].filter(site => site.status === 'deleted' && site.deletedAt !== null && site.deletedAt <= at)
166
+ .sort((a, b) => a.deletedAt! - b.deletedAt!).slice(0, limit).map(site => record(site.id)!);
167
+ },
168
+ async remove(id) {
169
+ for (const [host, domain] of domains) if (domain.site === id) domains.delete(host);
170
+ sites.delete(id);
171
+ },
172
+ };
243
173
  }