@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,7 +1,8 @@
1
1
  // Server-only CMS host. Import from server code; the security transform keeps it out of the client.
2
- export { CmsHost, createCMS, DEFAULT_RESERVED_PATHS, lockedCopy, PLUGIN_ENABLED, type AccountStores, type SiteLanguages, type ThemeInfo, type PluginAuthorView, type CmsOptions, type CmsProjectOptions, type CmsProjectConfig, type CmsModule, type PluginContext, type PluginUnrestricted, type PluginCms, type PluginResource, type PluginRegistrationLike, type ActivationStatus, type PluginStatus, type CommandHandler, type CommandContext, type ThemeLoader, type ThemeLoaders, type ThemeLoaderContext, type ThemeLoaderInput, type LayoutLoaderContext, type EntryLoaderContext, type ArchiveLoaderContext } from './host';
2
+ export { CmsHost, createCMS, DEFAULT_RESERVED_PATHS, lockedCopy, PLUGIN_ENABLED, type SiteLanguages, type ThemeInfo, type PluginAuthorView, type CmsOptions, type CmsProjectOptions, type CmsProjectConfig, type CmsModule, type PluginContext, type PluginUnrestricted, type PluginCms, type PluginResource, type PluginRegistrationLike, type ActivationStatus, type PluginStatus, type CommandHandler, type CommandContext, type ThemeLoader, type ThemeLoaders, type ThemeLoaderContext, type ThemeLoaderInput, type LayoutLoaderContext, type EntryLoaderContext, type ArchiveLoaderContext } from './host';
3
3
  export { isLockedRecord, lockedView, withheldFieldNames } from './locked';
4
- export { ResourceRepository, type OperationContext, type ListOptions, type ListFilter, type FieldFilter } from './repository';
4
+ export { ResourceRepository, type OperationContext, type ListOptions, type ListFilter, type FieldFilter, type BatchWrite, type BatchGuard, type PreparedWrite } from './repository';
5
+ export { writeBatch, BATCH_LIMITS } from './batch';
5
6
  export { CmsMenus, type MenuSummary } from './menus';
6
7
  export { CmsAreas, type AreaShape } from './areas';
7
8
  export { CmsFieldGroups } from './field-groups';
@@ -9,32 +10,27 @@ export { parseMeta, type MetaCheck } from './taxonomies';
9
10
  export { collectionSpec, searchTextPath, defineFieldRql, indexRql, readCatalog, planSchema, migrate, type Catalog, type SchemaPlan, type PlannedStep, type SchemaProblem, type MigrationReport, type CollectionSpec, type FieldSpec, type IndexSpec } from './schema';
10
11
  export { HOST_STEPS, HOST_TABLES, unknownHostSteps } from './host-schema';
11
12
  export { Outbox, type DispatchReport, type OutboxOptions } from './outbox';
12
- export { CmsUsers, type CmsUser, type CmsMember, type CmsRole, type UserPage } from './users';
13
- export { CmsAccounts, normalizeEmail, type CmsAccount, type AccountProfile } from './accounts';
14
- export { CmsSites, MAIN_SITE, siteHost, type SiteRecord, type SiteDomain, type SiteStatus } from './sites';
15
- export { CmsNetwork, MAIN, networkSite, prefixedStorage, type NetworkSite, type SiteResolution, type CmsNetworkOptions, type NewSite, type NetworkSettings, type SiteExportPolicy, type ExportRequest } from './network';
13
+ export { CmsUsers, normalizeEmail, type CmsUser, type CmsMember, type CmsRole, type UserPage } from './users';
14
+ export { CmsAttempts } from './attempts';
15
+ export { memoryPeople, personPermissions, type PeoplePort, type Person, type PersonRole, type PersonInput, type PeopleListOptions } from './people';
16
+ export { MAIN_SITE, memorySites, siteHost, type SiteRecord, type SiteDomain, type SiteStatus , type SitesStore } from './sites';
17
+ export { CmsNetwork, MAIN, networkSite, prefixedStorage, type NetworkSite, type SiteResolution, type CmsNetworkOptions, type NewSite, type NetworkSettings, type SiteExportPolicy, type ExportRequest, type SiteRegistration, SITE_REGISTRATIONS } from './network';
16
18
  export { siteExport, siteFile, EXPORT_SKIPPED_TABLES, EXPORT_REDACTED_COLUMNS, FILE_EXPORT_EMPTIED_TABLES, type SiteExportOptions } from './site-export';
17
19
  export { siteImport, siteImportState, type SiteImportOptions, type SiteImportReport } from './site-import';
18
20
  export { OPEN_POLICY, pluginState, readPolicy, type NetworkPluginState, type NetworkPolicy, type NetworkThemeState } from './network-policy';
19
- export { CmsHandoffs, type Handoff } from './handoffs';
20
21
  export { FileService, MAX_FILE_VARIANTS, VARIANT_ASPECTS, type CmsFile, type FileServiceOptions, type FileMetadata, type FileSummary, type ImageSettings, type PendingUpload } from './files';
21
22
  export { CmsCache, type CacheEntry } from './cache';
22
23
  export { CmsTaxonomies, freeSlug, type TermUsage, type TermInput } from './taxonomies';
23
24
  export { CmsSettings } from './site-settings';
24
25
  export { renderMarkdown, excerptOf } from './markdown';
25
26
  export { brandIcon } from './brands';
26
- export { createCmsAuth, type CmsAuth, type CmsAuthOptions, type CmsRequestUser } from './auth';
27
- export {
28
- createAuthSessionStore, createOAuthStateStore, createSessionStore, createJobStore, createNotificationStore,
29
- type CmsAuthSessionStore, type CmsOAuthStateStore, type CmsSessionStore, type CmsAuthSession, type ChildSession, type EndedSessions,
30
- } from './stores';
27
+ export { createJobStore, createNotificationStore } from './stores';
31
28
  export { cmsReconcilers } from './reconcile';
32
29
  export { CmsPreviews, type PreviewLink } from './previews';
33
30
  export { CmsAutosaves, type Autosave } from './autosaves';
34
31
  export { CmsDrafts, EDITING_WINDOW, saveBytes, type Draft, type DraftInput } from './drafts';
35
32
  export { CmsNotes, noteAnnounced, type NoteAnnouncedEvent, type NoteAnnouncement, type NoteInput } from './notes';
36
33
  export { CmsRedirects } from './redirects';
37
- export { CmsApiTokens, API_TOKEN_LIMIT, type ApiToken, type ApiTokenScope } from './api-tokens';
38
34
  export { CmsWebhooks, verifyWebhookSignature } from './webhooks';
39
35
  export { CmsIndexNow, INDEXNOW_ENDPOINT, INDEXNOW_KEY, type IndexNowOptions } from './indexnow';
40
36
  export { CmsPurge, PurgeError, type CachePurger, type CmsPurgeOptions, type PurgeContext, type PurgeRecord } from './purge';
@@ -54,6 +50,5 @@ export { CmsForms, type CmsMail, type LoadedForm, type SubmitContext, type Submi
54
50
  export { siteMailer, type CmsMailer, type MailTransport, type OutgoingMail, type SiteMailerOptions } from './mail';
55
51
  export { sha256Hex, randomToken, base64Url, timingSafeEqual } from './tokens';
56
52
  export { FORMAT_TYPES, negotiateFormat, type ImageTransformer, type ImageTransformRequest, type ImageFormat } from './images';
57
- export { CmsSecurity, SIGN_IN_ATTEMPTS, SIGN_IN_LOCK, RESET_REQUESTS, type PasskeyInfo, type StoredPasskeyRow, type SecurityStatus, type ChallengeKind } from './security';
58
53
  export * from '../index';
59
54
  export { seedStarterContent, type SeedReport } from './seed';
@@ -166,6 +166,16 @@ export async function serveIsolatedCall(context: PluginContext, member: string,
166
166
  }
167
167
  return call(context.cms.resource(String(id)), method, rest);
168
168
  }
169
+ case 'cms': {
170
+ // A batch, as a repository call: exactly the writes and the context, acting as a principal the call was given.
171
+ if (method !== 'batch' || args.length !== 2) throw new CmsError('CMS_FORBIDDEN', `Plugin ${name} asked for ${member}.`);
172
+ const operation = args[1] as { principal?: unknown } | undefined;
173
+ const own = systemPrincipal(`plugin:${name}`);
174
+ if (!operation || typeof operation !== 'object' || !(samePrincipal(operation.principal, own) || principals.some(principal => samePrincipal(operation.principal, principal)))) {
175
+ throw new CmsError('CMS_FORBIDDEN', `Plugin ${name} must act as the principal its handler was given, or as plugin:${name}.`);
176
+ }
177
+ return context.cms.batch(args[0] as never, operation as never);
178
+ }
169
179
  case 'fetch': {
170
180
  const request = args[0];
171
181
  if (!(request instanceof Request)) throw new CmsError('CMS_VALIDATION', `Plugin ${name} must fetch with a Request.`);
@@ -6,16 +6,16 @@
6
6
  import type { RomeDB } from '@cossackframework/romedb';
7
7
  import type { StorageMetadata, StorageProvider } from '@cossackframework/core/storage';
8
8
  import { CmsError } from '../errors';
9
+ import type { SiteCreatedEvent } from '../hooks';
9
10
  import { LOCALE } from '../collections';
10
11
  import { slugify } from '../fields';
11
12
  import { DEFAULT_ROLES, isNetworkAdmin, principalId, systemPrincipal, type Principal } from '../permissions';
12
13
  import { unrestrictedGrantAudit } from './audit';
13
14
  import { PLUGIN_ENABLED, type CmsHost, type PluginStatus } from './host';
14
15
  import { pluginState, POLICY_KEYS, readPolicy, type NetworkPluginState, type NetworkPolicy, type NetworkThemeState, type StoredPluginStates, type StoredThemeStates } from './network-policy';
15
- import { CmsHandoffs } from './handoffs';
16
+ import { missingTable, sharedRead } from './shared-read';
16
17
  import { seedStarterContent } from './seed';
17
- import { CmsSites, MAIN_SITE, RESERVED_SITE_IDS, siteHost, type SiteRecord, type SiteStatus } from './sites';
18
- import type { EndedSessions } from './stores';
18
+ import { MAIN_SITE, RESERVED_SITE_IDS, siteHost, type SiteRecord, type SitesStore, type SiteStatus } from './sites';
19
19
 
20
20
  /** The site a CMS host serves. */
21
21
  export interface NetworkSite {
@@ -60,15 +60,26 @@ export interface CmsNetworkOptions {
60
60
  /** How long a host's lookup is reused. Default 30 seconds. */
61
61
  readonly cacheMs?: number;
62
62
  readonly now?: () => number;
63
+ /**
64
+ * The registry of sites, which the application keeps (the dashboard package's tenants in a
65
+ * CMS project, `specs/cms-on-dashboard.md`).
66
+ */
67
+ readonly sites: SitesStore;
68
+ /**
69
+ * With accounts kept by the application (`CmsOptions.people`): run work on a site's users in
70
+ * that site's database, whichever host the request arrived at. The people port reads the
71
+ * database of the scope it is called in.
72
+ */
73
+ readonly inSite?: <T>(site: NetworkSite, work: () => Promise<T>) => Promise<T>;
74
+ /** With accounts kept by the application: the IDs of the sites an account is a member of. */
75
+ readonly memberSites?: (accountId: string) => Promise<readonly string[]>;
63
76
  }
64
77
 
65
78
  export const MAIN: NetworkSite = Object.freeze({ id: MAIN_SITE, name: null, database: MAIN_SITE, status: 'active', host: null });
66
79
 
67
80
  export class CmsNetwork {
68
81
  readonly db: RomeDB;
69
- readonly sites: CmsSites;
70
- /** One-use codes that sign a network session in on a site. */
71
- readonly handoffs: CmsHandoffs;
82
+ readonly sites: SitesStore;
72
83
  readonly #options: CmsNetworkOptions;
73
84
  readonly #now: () => number;
74
85
  readonly #hosts = new Map<string, CmsHost>();
@@ -80,22 +91,7 @@ export class CmsNetwork {
80
91
  this.db = options.db;
81
92
  this.#options = options;
82
93
  this.#now = options.now ?? Date.now;
83
- this.sites = new CmsSites(options.db, { now: this.#now });
84
- this.handoffs = new CmsHandoffs(options.db, { now: this.#now });
85
- }
86
-
87
- /**
88
- * End the child sessions sites made from these network sessions. Pass it to every host as
89
- * `sessionsEnded`: signing out, a password reset, a suspension or a new network role end
90
- * the account's sessions on every site it reached.
91
- */
92
- async endSessions(ended: EndedSessions): Promise<void> {
93
- if (!this.multisite) return;
94
- for (const id of await this.handoffs.reached(ended)) {
95
- const record = await this.sites.get(id);
96
- if (record && record.status !== 'creating') await this.hostOf(networkSite(record)).authSessions.revokeChildren(ended);
97
- }
98
- await this.handoffs.forget(ended);
94
+ this.sites = options.sites;
99
95
  }
100
96
 
101
97
  /** Whether added sites can open their databases. */
@@ -115,6 +111,17 @@ export class CmsNetwork {
115
111
  return record && record.status !== 'creating' && record.status !== 'deleted' ? this.hostOf(networkSite(record)) : null;
116
112
  }
117
113
 
114
+ /**
115
+ * A site's database by the site's ID, whatever state the site is in: the application opens its
116
+ * own tables there (accounts, on the ORM). Throws for an unknown site.
117
+ */
118
+ async databaseOf(id: string): Promise<RomeDB> {
119
+ if (id === MAIN_SITE) return this.db;
120
+ const record = await this.sites.get(id);
121
+ if (!record) throw new CmsError('CMS_NOT_FOUND', `No site with the ID ${id}.`);
122
+ return this.hostOf(networkSite(record)).db;
123
+ }
124
+
118
125
  /** The CMS host of a site, built on first use and kept while it is among the last used. */
119
126
  hostOf(site: NetworkSite): CmsHost {
120
127
  const kept = this.#hosts.get(site.database);
@@ -143,6 +150,10 @@ export class CmsNetwork {
143
150
 
144
151
  /** The site a request's host names. Lookups are reused for 30 seconds. */
145
152
  resolve(host: string): Promise<SiteResolution> {
153
+ return sharedRead(() => this.#lookup(host));
154
+ }
155
+
156
+ #lookup(host: string): Promise<SiteResolution> {
146
157
  const name = siteHost(host);
147
158
  const now = this.#now();
148
159
  const cached = this.#lookups.get(name);
@@ -159,11 +170,20 @@ export class CmsNetwork {
159
170
  * then the install is one site, and the network dashboard is hidden. Reused for 30 seconds.
160
171
  */
161
172
  enabled(): Promise<boolean> {
173
+ return sharedRead(() => this.#readEnabled());
174
+ }
175
+
176
+ #readEnabled(): Promise<boolean> {
162
177
  const now = this.#now();
163
178
  if (!this.#enabled || now - this.#enabled.at >= (this.#options.cacheMs ?? 30_000)) {
164
- // Before setup `cms_network` does not exist yet: the network is off.
165
- const value = this.state<boolean>(ENABLED).then(stored => stored === true, () => false);
179
+ // Before setup `cms_network` does not exist yet: the network is off. Any other failure is
180
+ // not kept: a refused read must not turn the network off for every later request.
181
+ const value = this.state<boolean>(ENABLED).then(stored => stored === true, error => {
182
+ if (missingTable(error, /cms_network/i)) return false;
183
+ throw error;
184
+ });
166
185
  this.#enabled = { at: now, value };
186
+ value.catch(() => { if (this.#enabled?.value === value) this.#enabled = undefined; });
167
187
  }
168
188
  return this.#enabled.value;
169
189
  }
@@ -192,13 +212,17 @@ export class CmsNetwork {
192
212
  */
193
213
  async createSite(input: NewSite, context: { principal: Principal }): Promise<SiteRecord> {
194
214
  requireNetworkAdmin(context.principal);
215
+ return this.#createSite(input);
216
+ }
217
+
218
+ async #createSite(input: NewSite): Promise<SiteRecord> {
195
219
  const directory = this.#options.directory;
196
220
  if (!directory || !this.#options.open) throw new CmsError('CMS_UNAVAILABLE', 'This network cannot add sites yet: it needs a provider for site databases.');
197
221
  if (!(await this.enabled())) throw new CmsError('CMS_UNAVAILABLE', 'Turn the network on in Settings before adding sites.');
198
222
  const slug = slugify(input.name, 40) || 'site';
199
223
  const id = input.id ?? (RESERVED_SITE_IDS.has(slug) ? `${slug}-site` : slug);
200
224
  if (input.language && !LOCALE.test(input.language)) throw new CmsError('CMS_VALIDATION', 'Enter a language code, such as en or pt-br.', { fields: { language: 'is invalid.' } });
201
- const admin = await this.main.accounts.get(input.admin);
225
+ const admin = await this.#account(input.admin);
202
226
  if (!admin || admin.status !== 'active') throw new CmsError('CMS_VALIDATION', 'Choose an active account as the first administrator.', { fields: { admin: 'is invalid.' } });
203
227
  let record = await this.sites.get(id);
204
228
  if (record && record.status !== 'creating') throw new CmsError('CMS_CONFLICT', 'A site with this ID exists.', { fields: { id: 'is taken.' } });
@@ -209,6 +233,8 @@ export class CmsNetwork {
209
233
  const done = (step: CreationStep) => record!.step !== null && CREATION_STEPS.indexOf(record!.step as CreationStep) >= CREATION_STEPS.indexOf(step);
210
234
  if (!done('database')) record = (await this.sites.update(id, { database: await directory.create(`site-${id}`), step: 'database' }))!;
211
235
  const host = this.hostOf(networkSite(record));
236
+ // From here the work is on the new site's own database: its schema, its roles and its first member.
237
+ await this.inSite(networkSite(record), async () => {
212
238
  if (!done('schema')) {
213
239
  const report = await host.migrate();
214
240
  if (report.failed) throw new CmsError('CMS_UNAVAILABLE', `The site's schema could not be applied: ${report.failed.message}`);
@@ -219,7 +245,10 @@ export class CmsNetwork {
219
245
  const system = systemPrincipal('network');
220
246
  const defaults = await this.settings();
221
247
  for (const role of DEFAULT_ROLES) await host.users.defineRole({ ...role, permissions: [...role.permissions] });
222
- await host.settings.update('general', { siteTitle: record.name, adminEmail: admin.email }, { principal: system });
248
+ // As on its first request: the plugins the network enables migrate and add their field groups, patterns and roles.
249
+ host.expire();
250
+ await host.ready();
251
+ await host.settings.update('general', { siteTitle: record!.name, adminEmail: admin.email }, { principal: system });
223
252
  const language = input.language || defaults.defaultLanguage;
224
253
  // Languages come with the content module.
225
254
  if (language && host.settings.groups.some(group => group.id === 'languages')) await host.settings.update('languages', { default: language }, { principal: system });
@@ -236,13 +265,60 @@ export class CmsNetwork {
236
265
  await host.users.setRoles(admin.id, ['admin']);
237
266
  const principal = input.starter ? await host.users.principal(admin.id) : null;
238
267
  if (principal) await seedStarterContent(host, { principal }).catch(error => console.warn(`[cms] starter content for site ${id}: ${(error as Error).message}`));
268
+ // The site's plugins hear of it from its own outbox; a resumed creation queues it once.
269
+ const event: SiteCreatedEvent = { eventId: `site.created:${id}`, topic: 'site.created', at: this.#now(),
270
+ site: { id, name: record!.name, host: networkSite(record!).host }, admin: { id: admin.id, email: admin.email, name: admin.name } };
271
+ if (await host.outbox.enqueue('site.created', event, { ignoreDuplicate: true })) host.outboxWritten();
239
272
  record = (await this.sites.update(id, { step: 'members' }))!;
240
273
  }
274
+ });
241
275
  record = (await this.sites.update(id, { status: 'active', step: null }))!;
242
276
  this.invalidate();
277
+ // Delivered now, so the site is ready when its administrator arrives; a failure is retried by maintenance.
278
+ await host.outbox.dispatch({ limit: 10 }).catch(error => console.error(`[cms] site ${id}: delivering its first events failed`, error));
243
279
  return record;
244
280
  }
245
281
 
282
+ /**
283
+ * Register a site as the person who will run it, when the network lets people register sites
284
+ * (`siteRegistration`): the principal's network account, active and so with its email
285
+ * confirmed, becomes the site's first administrator. The address is one name under the
286
+ * network's suffix, and names the site; an address or ID in use is refused. An account
287
+ * registers at most `SITE_REGISTRATIONS.perAccount` sites a day. The bot check and the
288
+ * limit per visitor are the sign-up page's.
289
+ */
290
+ async registerSite(input: SiteRegistration, context: { principal: Principal }): Promise<SiteRecord> {
291
+ const principal = context.principal;
292
+ if (principal.kind !== 'user') throw new CmsError('CMS_UNAUTHENTICATED', 'Sign in to register a site.');
293
+ const site = await this.checkSiteRegistration(input);
294
+ const account = await this.#account(principal.id);
295
+ if (!account || account.status !== 'active') throw new CmsError('CMS_FORBIDDEN', 'Confirm your email address before registering a site.');
296
+ if (!(await this.main.attempts.attempt('site-registration', `account:${account.id}`, SITE_REGISTRATIONS.perAccount, SITE_REGISTRATIONS.windowMs))) {
297
+ throw new CmsError('CMS_LIMIT', 'This account registered as many sites as a day allows. Try again tomorrow.');
298
+ }
299
+ return this.#createSite({ ...site, admin: account.id, starter: true });
300
+ }
301
+
302
+ /**
303
+ * A site registration as `registerSite` would make it, checked without making it: the network
304
+ * lets people register sites, and the name, address and language are valid and free. Throws
305
+ * `CMS_FORBIDDEN` while registration is closed, and `CMS_VALIDATION` or `CMS_CONFLICT` with the field.
306
+ */
307
+ async checkSiteRegistration(input: SiteRegistration): Promise<{ id: string; name: string; host: string; language?: string }> {
308
+ if (!(await this.settings()).siteRegistration || !this.canAddSites || !(await this.enabled())) throw new CmsError('CMS_FORBIDDEN', 'This network does not let people register sites.');
309
+ if (typeof input?.name !== 'string' || !input.name.trim() || input.name.length > 120) throw new CmsError('CMS_VALIDATION', 'Enter a site name of at most 120 characters.', { fields: { name: 'is required.' } });
310
+ if (input.language !== undefined && (typeof input.language !== 'string' || (input.language && !LOCALE.test(input.language)))) throw new CmsError('CMS_VALIDATION', 'Enter a language code, such as en or pt-br.', { fields: { language: 'is invalid.' } });
311
+ const host = await this.#address(typeof input.host === 'string' ? input.host : '');
312
+ const suffix = (await this.settings()).subdomainSuffix || this.subdomainSuffix;
313
+ const label = host.slice(0, host.length - ((host.endsWith('.localhost') ? 'localhost' : suffix).length + 1));
314
+ if (!/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/.test(label) || RESERVED_SITE_IDS.has(label) || label === 'www') {
315
+ throw new CmsError('CMS_VALIDATION', `Choose one name before .${suffix || 'localhost'}: up to 40 lowercase letters, digits and hyphens.`, { fields: { host: 'is invalid.' } });
316
+ }
317
+ // A site half made by someone else is never finished for another person.
318
+ if (await this.sites.get(label) || await this.sites.siteOf(host) || host === siteHost(this.#options.networkHost?.() ?? '')) throw new CmsError('CMS_CONFLICT', 'This address is taken. Choose another.', { fields: { host: 'is taken.' } });
319
+ return { id: label, name: input.name.trim(), host, ...(input.language ? { language: input.language } : {}) };
320
+ }
321
+
246
322
  /** Archive, delete or restore a site. A deleted site can be restored for 30 days. */
247
323
  async setSiteStatus(id: string, status: 'active' | 'archived' | 'deleted', context: { principal: Principal }): Promise<SiteRecord> {
248
324
  requireNetworkAdmin(context.principal);
@@ -319,6 +395,7 @@ export class CmsNetwork {
319
395
  name: text(stored.name), subdomainSuffix: text(stored.subdomainSuffix), defaultTheme: text(stored.defaultTheme), defaultLanguage: text(stored.defaultLanguage),
320
396
  defaultPlugins: Array.isArray(stored.defaultPlugins) ? stored.defaultPlugins.filter((name): name is string => typeof name === 'string') : [],
321
397
  siteExports: stored.siteExports === 'self' ? 'self' : 'request',
398
+ siteRegistration: stored.siteRegistration === true,
322
399
  };
323
400
  }
324
401
 
@@ -333,9 +410,11 @@ export class CmsNetwork {
333
410
  if (unknown.length) throw new CmsError('CMS_VALIDATION', `Unknown plugins: ${unknown.join(', ')}.`, { fields: { defaultPlugins: 'are unknown.' } });
334
411
  if (next.defaultLanguage && !LOCALE.test(next.defaultLanguage)) throw new CmsError('CMS_VALIDATION', 'Enter a language code, such as en or pt-br.', { fields: { defaultLanguage: 'is invalid.' } });
335
412
  if (next.siteExports !== 'request' && next.siteExports !== 'self') throw new CmsError('CMS_VALIDATION', 'Site exports are request or self.', { fields: { siteExports: 'is invalid.' } });
413
+ if (typeof next.siteRegistration !== 'boolean') throw new CmsError('CMS_VALIDATION', 'Site registration is on or off.', { fields: { siteRegistration: 'is invalid.' } });
336
414
  const saved: NetworkSettings = {
337
415
  name: next.name.trim(), subdomainSuffix: next.subdomainSuffix ? siteHost(next.subdomainSuffix) : '',
338
416
  defaultTheme: next.defaultTheme, defaultPlugins: [...new Set(next.defaultPlugins)], defaultLanguage: next.defaultLanguage, siteExports: next.siteExports,
417
+ siteRegistration: next.siteRegistration,
339
418
  };
340
419
  await this.setState('settings', saved);
341
420
  return saved;
@@ -483,9 +562,19 @@ export class CmsNetwork {
483
562
  params: { $key: key, $value: JSON.stringify(value), $now: this.#now() } }], { kind: 'cms.network', retryConflicts: 5 });
484
563
  }
485
564
 
565
+ /** An account of the network by ID: a user of the main site. */
566
+ async #account(id: string): Promise<{ id: string; email: string; name: string; status: string } | null> {
567
+ return this.main.users.get(id);
568
+ }
569
+
570
+ /** Run work on a site's users in that site's database (`CmsNetworkOptions.inSite`); as it is without one. */
571
+ inSite<T>(site: NetworkSite, work: () => Promise<T>): Promise<T> {
572
+ return this.#options.inSite ? this.#options.inSite(site, work) : work();
573
+ }
574
+
486
575
  /** The sites an account is a member of, the main site first, without opening their databases. Off, the network is its main site. */
487
576
  async memberSites(accountId: string): Promise<NetworkSite[]> {
488
- const ids = (await this.main.accounts.memberships([accountId])).get(accountId) ?? [];
577
+ const ids = [MAIN_SITE, ...await this.#options.memberSites?.(accountId) ?? []];
489
578
  const sites: NetworkSite[] = ids.includes(MAIN_SITE) ? [MAIN] : [];
490
579
  if (!(await this.enabled())) return sites;
491
580
  const records = new Map((await this.sites.getMany(ids)).map(record => [record.id, record]));
@@ -496,23 +585,6 @@ export class CmsNetwork {
496
585
  return sites;
497
586
  }
498
587
 
499
- /** Delete an account: first its membership of every site, through each site's own user deletion, then the account. */
500
- async deleteAccount(id: string, context: { principal: Principal }): Promise<boolean> {
501
- requireNetworkAdmin(context.principal);
502
- const account = await this.main.accounts.get(id);
503
- if (!account) return false;
504
- // Refuse the last network admin before anything changes.
505
- if (account.networkRole && !(await this.main.accounts.list({ networkAdmins: true, limit: 2 })).items.some(other => other.id !== id && other.status === 'active')) {
506
- throw new CmsError('CMS_FORBIDDEN', 'The last network admin cannot be deleted.');
507
- }
508
- for (const site of (await this.main.accounts.memberships([id])).get(id) ?? []) {
509
- const record = site === MAIN_SITE ? null : await this.sites.get(site);
510
- if (site === MAIN_SITE) await this.main.users.delete(id);
511
- else if (record && record.status !== 'creating') await this.hostOf(networkSite(record)).users.delete(id);
512
- }
513
- return this.main.accounts.delete(id);
514
- }
515
-
516
588
  /** Sites whose schema has steps to apply after a deploy, with how many; each site applies its own when it next loads. */
517
589
  async updates(options: { limit?: number; offset?: number } = {}): Promise<{ site: NetworkSite; name: string; pending: number }[]> {
518
590
  const records = (await this.sites.list({ status: 'active', limit: options.limit ?? 50, offset: options.offset ?? 0 })).items;
@@ -599,6 +671,19 @@ export interface NetworkSettings {
599
671
  readonly defaultLanguage: string;
600
672
  /** How added sites export their databases: `request` a network admin's approval (the default), or download them `self`. */
601
673
  readonly siteExports: SiteExportPolicy;
674
+ /** People can register a site: a person with a confirmed network account creates one and becomes its first administrator (`registerSite`). Off by default. */
675
+ readonly siteRegistration: boolean;
676
+ }
677
+
678
+ /** How many sites one account may register, in a window. */
679
+ export const SITE_REGISTRATIONS = Object.freeze({ perAccount: 3, windowMs: 24 * 60 * 60_000 });
680
+
681
+ /** What registering a site asks for: its name and address; the person asking becomes its administrator. */
682
+ export interface SiteRegistration {
683
+ readonly name: string;
684
+ /** A subdomain of the network's suffix, such as `pho.example.com`; it also names the site's ID. */
685
+ readonly host: string;
686
+ readonly language?: string;
602
687
  }
603
688
 
604
689
  export type SiteExportPolicy = 'request' | 'self';
@@ -7,7 +7,7 @@
7
7
  import type { RomeDB, Statement, Value } from '@cossackframework/romedb';
8
8
  import type { HookRegistry } from '@cossackframework/core/hooks';
9
9
  import type { ActionPoint } from '@cossackframework/core/hooks';
10
- import { afterCommit, cachePurge, formSubmitted, paymentEvent, pluginJob, userRegistered, userSignedIn } from '../hooks';
10
+ import { afterCommit, cachePurge, formSubmitted, paymentEvent, pluginJob, siteCreated, userRegistered, userSignedIn } from '../hooks';
11
11
  import { searchRebuild } from './site-search';
12
12
  import { collectionDeleted } from './comments';
13
13
  import { sharedFields } from './shared-fields';
@@ -16,7 +16,7 @@ import { pathsMoved } from './path-moves';
16
16
  import { readPaged } from './budget';
17
17
 
18
18
  /** The action an outbox row runs, by its topic; resource events run `cms.resource.after-commit`. */
19
- const POINTS: { readonly [topic: string]: ActionPoint<unknown> } = { 'form.submitted': formSubmitted as ActionPoint<unknown>, 'cache.purge': cachePurge as ActionPoint<unknown>, 'plugin.job': pluginJob as ActionPoint<unknown>, 'payment.event': paymentEvent as ActionPoint<unknown>, 'user.registered': userRegistered as ActionPoint<unknown>, 'user.signed-in': userSignedIn as ActionPoint<unknown>, 'search.rebuild': searchRebuild as ActionPoint<unknown>, 'collection.deleted': collectionDeleted as ActionPoint<unknown>, 'resource.shared': sharedFields as ActionPoint<unknown>, 'note.announced': noteAnnounced as ActionPoint<unknown>, 'paths.moved': pathsMoved as ActionPoint<unknown> };
19
+ const POINTS: { readonly [topic: string]: ActionPoint<unknown> } = { 'form.submitted': formSubmitted as ActionPoint<unknown>, 'cache.purge': cachePurge as ActionPoint<unknown>, 'plugin.job': pluginJob as ActionPoint<unknown>, 'payment.event': paymentEvent as ActionPoint<unknown>, 'user.registered': userRegistered as ActionPoint<unknown>, 'user.signed-in': userSignedIn as ActionPoint<unknown>, 'site.created': siteCreated as ActionPoint<unknown>, 'search.rebuild': searchRebuild as ActionPoint<unknown>, 'collection.deleted': collectionDeleted as ActionPoint<unknown>, 'resource.shared': sharedFields as ActionPoint<unknown>, 'note.announced': noteAnnounced as ActionPoint<unknown>, 'paths.moved': pathsMoved as ActionPoint<unknown> };
20
20
 
21
21
  export interface DispatchReport {
22
22
  readonly delivered: readonly string[];
@@ -0,0 +1,191 @@
1
+ // The people port: what the CMS needs from whoever keeps accounts, roles and sign-in.
2
+ //
3
+ // The CMS does not keep accounts itself. The application fills this port from the dashboard
4
+ // package's services (`specs/cms-on-dashboard.md`), and the CMS keeps only what is its own
5
+ // about a user, beside the port's record and under the same ID: the author slug and the
6
+ // values of the field groups attached to users.
7
+ import { CmsError } from '../errors';
8
+
9
+ /** A role as the port gives it. `id` is what settings, rules and permissions name: `admin`, `editor`. */
10
+ export interface PersonRole {
11
+ readonly id: string;
12
+ /** The name people read, such as "Editor". */
13
+ readonly name: string;
14
+ readonly permissions: readonly string[];
15
+ }
16
+
17
+ /** A user of this site, as the port gives them. */
18
+ export interface Person {
19
+ readonly id: string;
20
+ readonly email: string;
21
+ readonly name: string;
22
+ readonly avatar: string | null;
23
+ readonly status: 'active' | 'disabled';
24
+ /** The roles the user holds on this site, in ID order. */
25
+ readonly roles: readonly PersonRole[];
26
+ /** A network administrator: every permission on every site, whatever roles the site gave. */
27
+ readonly networkAdmin: boolean;
28
+ /** `site`: an account of this site only. `network`: an account every site of the network shares. */
29
+ readonly account: 'site' | 'network';
30
+ readonly createdAt: number;
31
+ /** When the user last started a session on this site, or null when never. */
32
+ readonly lastSignInAt: number | null;
33
+ }
34
+
35
+ export interface PeopleListOptions {
36
+ /** Part of a name or an email. */
37
+ readonly search?: string;
38
+ /** Only holders of this role. */
39
+ readonly role?: string;
40
+ /** Default 50, at most 200. */
41
+ readonly limit?: number;
42
+ readonly offset?: number;
43
+ }
44
+
45
+ export interface PersonInput {
46
+ readonly email: string;
47
+ readonly name: string;
48
+ /** Without one the account cannot sign in with a password until it sets one. */
49
+ readonly password?: string;
50
+ readonly roles?: readonly string[];
51
+ readonly id?: string;
52
+ }
53
+
54
+ /**
55
+ * Accounts, members and roles of one site. Every method is about this site: `list` gives its
56
+ * members, `roles` its roles. A user who is not a member of the site is not found.
57
+ */
58
+ export interface PeoplePort {
59
+ /** The users with these IDs. Unknown IDs are left out. At most 200 a call. */
60
+ getMany(ids: readonly string[]): Promise<Map<string, Person>>;
61
+ findByEmail(email: string): Promise<Person | null>;
62
+ /** By name, then ID. */
63
+ list(options?: PeopleListOptions): Promise<{ readonly users: readonly Person[]; readonly total: number }>;
64
+ count(): Promise<number>;
65
+ roles(): Promise<readonly PersonRole[]>;
66
+ role(id: string): Promise<PersonRole | null>;
67
+ /** Make the role, or give an existing one these permissions: the CMS's and plugins' default roles. */
68
+ defineRole(role: PersonRole): Promise<PersonRole>;
69
+ /** Throws `CMS_CONFLICT` when the email is taken and `CMS_VALIDATION` for an unknown role. */
70
+ create(input: PersonInput): Promise<Person>;
71
+ /** False when there is no such user. */
72
+ update(id: string, patch: { readonly name?: string; readonly email?: string; readonly avatar?: string | null }): Promise<boolean>;
73
+ setRoles(id: string, roles: readonly string[]): Promise<void>;
74
+ /** False when there is no such user. */
75
+ delete(id: string): Promise<boolean>;
76
+ /**
77
+ * Make an account that the whole network shares a member of this site, with these roles, when
78
+ * the application has such accounts. Null when there is no such account.
79
+ */
80
+ join?(accountId: string, roles: readonly string[]): Promise<Person | null>;
81
+ /**
82
+ * How many accounts are this site's own: on a site of a network the ones that exist there
83
+ * only, elsewhere every account. An import needs none. Default: `count()`.
84
+ */
85
+ ownCount?(): Promise<number>;
86
+ /**
87
+ * After a site's export was imported into this site's tables: make its users people of
88
+ * this site. Each becomes a member whose account the network already has, or an account
89
+ * of this site without a password (it sets one with Forgot password). Answers how many of each.
90
+ */
91
+ adopt?(): Promise<{ readonly network: number; readonly site: number; readonly pending: number }>;
92
+ }
93
+
94
+ const EMAIL = /^[^\s@]{1,64}@[^\s@]{1,190}$/;
95
+ const ROLE_ID = /^[a-z][a-z0-9_-]{0,63}$/;
96
+
97
+ /**
98
+ * A people port that keeps everything in memory: for tests, and for trying the CMS without
99
+ * an application around it. It follows the rules an application's port must follow.
100
+ */
101
+ export function memoryPeople(options: { now?: () => number; /** The accounts a network shares, for a site of it: `join` makes one a member here. */ network?: PeoplePort } = {}): PeoplePort & { /** Mark a user as a network administrator, or as disabled. */ set(id: string, patch: { networkAdmin?: boolean; status?: 'active' | 'disabled'; lastSignInAt?: number | null }): void } {
102
+ const now = options.now ?? Date.now;
103
+ const users = new Map<string, Omit<Person, 'roles'> & { roles: string[] }>();
104
+ const roles = new Map<string, PersonRole>();
105
+
106
+ const person = (id: string): Person | null => {
107
+ const user = users.get(id);
108
+ if (!user) return null;
109
+ const held = user.roles.map(role => roles.get(role)).filter((role): role is PersonRole => role !== undefined).sort((a, b) => a.id < b.id ? -1 : 1);
110
+ return Object.freeze({ ...user, roles: Object.freeze(held) });
111
+ };
112
+ const checkRoles = (ids: readonly string[]): string[] => {
113
+ const unique = [...new Set(ids)];
114
+ if (unique.some(id => !roles.has(id))) throw new CmsError('CMS_VALIDATION', 'Unknown role.');
115
+ return unique;
116
+ };
117
+ const email = (value: string): string => {
118
+ const normal = value.trim().toLowerCase();
119
+ if (!EMAIL.test(normal)) throw new CmsError('CMS_VALIDATION', 'Enter a valid email address.', { fields: { email: 'is not valid.' } });
120
+ return normal;
121
+ };
122
+
123
+ return {
124
+ async getMany(ids) {
125
+ return new Map([...new Set(ids)].slice(0, 200).map(id => [id, person(id)] as const).filter((entry): entry is [string, Person] => entry[1] !== null));
126
+ },
127
+ async findByEmail(value) {
128
+ const normal = value.trim().toLowerCase();
129
+ for (const user of users.values()) if (user.email === normal) return person(user.id);
130
+ return null;
131
+ },
132
+ async list(listOptions = {}) {
133
+ const search = listOptions.search?.trim().toLowerCase();
134
+ const matching = [...users.values()]
135
+ .filter(user => !search || user.name.toLowerCase().includes(search) || user.email.includes(search))
136
+ .filter(user => !listOptions.role || user.roles.includes(listOptions.role))
137
+ .sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : a.name.toLowerCase() > b.name.toLowerCase() ? 1 : a.id < b.id ? -1 : 1);
138
+ const offset = Math.max(listOptions.offset ?? 0, 0);
139
+ const limit = Math.min(Math.max(listOptions.limit ?? 50, 1), 200);
140
+ return { users: matching.slice(offset, offset + limit).map(user => person(user.id)!), total: matching.length };
141
+ },
142
+ async count() { return users.size; },
143
+ async roles() { return [...roles.values()].sort((a, b) => a.id < b.id ? -1 : 1); },
144
+ async role(id) { return roles.get(id) ?? null; },
145
+ async defineRole(role) {
146
+ if (!ROLE_ID.test(role.id) || !role.name.trim()) throw new CmsError('CMS_VALIDATION', 'A role needs an ID of lowercase letters and a name.');
147
+ const defined = Object.freeze({ id: role.id, name: role.name.trim(), permissions: Object.freeze([...new Set(role.permissions)].sort()) });
148
+ roles.set(role.id, defined);
149
+ return defined;
150
+ },
151
+ async create(input) {
152
+ const address = email(input.email);
153
+ if ([...users.values()].some(user => user.email === address)) throw new CmsError('CMS_CONFLICT', 'A user with this email already exists.', { fields: { email: 'is taken.' } });
154
+ const id = input.id ?? crypto.randomUUID();
155
+ if (users.has(id)) throw new CmsError('CMS_CONFLICT', 'A user with this ID already exists.');
156
+ users.set(id, { id, email: address, name: input.name.trim() || address, avatar: null, status: 'active', roles: checkRoles(input.roles ?? []), networkAdmin: false, account: 'site', createdAt: now(), lastSignInAt: null });
157
+ return person(id)!;
158
+ },
159
+ async update(id, patch) {
160
+ const user = users.get(id);
161
+ if (!user) return false;
162
+ const address = patch.email === undefined ? user.email : email(patch.email);
163
+ if ([...users.values()].some(other => other.id !== id && other.email === address)) throw new CmsError('CMS_CONFLICT', 'A user with this email already exists.', { fields: { email: 'is taken.' } });
164
+ users.set(id, { ...user, email: address, ...(patch.name === undefined ? {} : { name: patch.name.trim() || user.name }), ...(patch.avatar === undefined ? {} : { avatar: patch.avatar }) });
165
+ return true;
166
+ },
167
+ async setRoles(id, ids) {
168
+ const user = users.get(id);
169
+ if (!user) throw new CmsError('CMS_NOT_FOUND', 'User not found.');
170
+ users.set(id, { ...user, roles: checkRoles(ids) });
171
+ },
172
+ async delete(id) { return users.delete(id); },
173
+ async join(accountId, held) {
174
+ const account = options.network ? (await options.network.getMany([accountId])).get(accountId) : undefined;
175
+ if (!account) return person(accountId);
176
+ users.set(accountId, { id: account.id, email: account.email, name: account.name, avatar: account.avatar, status: account.status, roles: checkRoles(held), networkAdmin: account.networkAdmin, account: 'network', createdAt: now(), lastSignInAt: null });
177
+ return person(accountId);
178
+ },
179
+ async ownCount() { return [...users.values()].filter(user => user.account === 'site').length; },
180
+ set(id, patch) {
181
+ const user = users.get(id);
182
+ if (user) users.set(id, { ...user, ...patch });
183
+ },
184
+ };
185
+ }
186
+
187
+ /** The permission patterns a person holds: every role's, or everything for a network administrator. */
188
+ export function personPermissions(person: Pick<Person, 'roles' | 'networkAdmin'>): string[] {
189
+ if (person.networkAdmin) return ['*'];
190
+ return [...new Set(person.roles.flatMap(role => role.permissions))].sort();
191
+ }
@@ -25,14 +25,14 @@ export function cmsReconcilers(): { [kind: string]: Reconciler } {
25
25
  'cms.forms': drop,
26
26
  // Field group and collection writes: the dashboard action that made them is repeated.
27
27
  'cms.fieldGroups': drop, 'cms.collections': drop,
28
- 'cms.migration': drop, 'cms.session': drop, 'cms.auth.session': drop, 'cms.auth.oauth': drop, 'cms.users': drop,
28
+ 'cms.migration': drop, 'cms.users': drop,
29
29
  'cms.outbox': drop, 'cms.files': drop, 'cms.import': drop, 'cms.jobs': drop, 'cms.notifications': drop,
30
30
  // The rest are writes a person repeats (a dashboard save, a sign-in) or that are fenced by
31
31
  // their own keys; once replay is impossible, the pending write is dropped and the action runs again.
32
- 'cms.accounts': drop, 'cms.areas': drop, 'cms.audit': drop, 'cms.automations': drop, 'cms.autosaves': drop,
33
- 'cms.cache': drop, 'cms.comments': drop, 'cms.revisions': drop, 'cms.drafts': drop, 'cms.grants': drop, 'cms.handoffs': drop,
32
+ 'cms.areas': drop, 'cms.attempts': drop, 'cms.audit': drop, 'cms.automations': drop, 'cms.autosaves': drop,
33
+ 'cms.cache': drop, 'cms.comments': drop, 'cms.revisions': drop, 'cms.drafts': drop, 'cms.grants': drop,
34
34
  'cms.menus': drop, 'cms.network': drop, 'cms.notes': drop, 'cms.previews': drop, 'cms.redirects': drop,
35
- 'cms.schedules': drop, 'cms.search': drop, 'cms.security': drop, 'cms.settings': drop, 'cms.sites': drop,
36
- 'cms.terms': drop, 'cms.tokens': drop, 'cms.traffic': drop, 'cms.webhooks': drop,
35
+ 'cms.schedules': drop, 'cms.search': drop, 'cms.settings': drop,
36
+ 'cms.terms': drop, 'cms.traffic': drop, 'cms.webhooks': drop,
37
37
  };
38
38
  }