@cossackframework/cms 0.9.2 → 0.9.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agent-docs.json +8 -8
- package/app/cossack-recipe.json +12 -8
- package/app/src/auth-events.ts +33 -0
- package/app/src/auth-input.ts +3 -0
- package/app/src/auth-options.ts +39 -7
- package/app/src/auth.ts +1309 -641
- package/app/src/avatars.ts +13 -0
- package/app/src/brand.ts +24 -2
- package/app/src/cms/actor.ts +13 -0
- package/app/src/cms/collab/room.ts +1 -1
- package/app/src/cms/content-api.ts +2 -1
- package/app/src/cms/content.ts +3 -2
- package/app/src/cms/dev-mail.ts +77 -0
- package/app/src/cms/index.ts +37 -10
- package/app/src/cms/maintenance.ts +1 -6
- package/app/src/cms/manage.ts +17 -14
- package/app/src/cms/middleware.ts +58 -18
- package/app/src/cms/network-accounts.ts +110 -0
- package/app/src/cms/notes-announce.ts +1 -1
- package/app/src/cms/people.ts +177 -0
- package/app/src/cms/recovery.ts +9 -14
- package/app/src/cms/request-calls.ts +56 -0
- package/app/src/cms/settings-form.ts +23 -6
- package/app/src/cms/settings-network.ts +8 -4
- package/app/src/cms/settings-search.ts +1 -0
- package/app/src/cms/site-editing.ts +3 -2
- package/app/src/cms/site-registration.ts +64 -0
- package/app/src/cms/site.ts +30 -19
- package/app/src/cms/sites.ts +182 -0
- package/app/src/dashboard/access.ts +3 -2
- package/app/src/dashboard/modules/users.ts +1 -0
- package/app/src/lib/permissions.ts +24 -0
- package/app/src/lib/uuid.ts +6 -0
- package/app/src/mail.ts +15 -0
- package/app/src/middlewares/auth.ts +6 -2
- package/app/src/middlewares/tenant.ts +108 -0
- package/app/src/pages/(site)/[...path]/index.ts +1 -1
- package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +1 -1
- package/app/src/pages/api/cms/dev/mail.ts +19 -0
- package/app/src/pages/api/cms/forms/[slug]/index.ts +1 -1
- package/app/src/pages/api/cms/users/[id]/meta.ts +2 -1
- package/app/src/pages/auth/login/index.ts +1 -1
- package/app/src/pages/auth/magic/index.ts +1 -1
- package/app/src/pages/auth/recovery.ts +20 -0
- package/app/src/pages/auth/register-site/index.ts +146 -0
- package/app/src/pages/auth/setup/index.ts +8 -3
- package/app/src/pages/auth/tenant/callback.ts +23 -0
- package/app/src/pages/auth/tenant/redirect.ts +91 -0
- package/app/src/pages/auth/verify/index.ts +3 -7
- package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +5 -5
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/network/index.ts +4 -2
- package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +16 -13
- package/app/src/pages/dashboard/(cms)/network/sites/index.ts +4 -2
- package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +29 -10
- package/app/src/pages/dashboard/(cms)/network/users/index.ts +8 -7
- package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +2 -1
- package/app/src/pages/dashboard/(cms)/registrations/index.ts +5 -4
- package/app/src/pages/dashboard/(cms)/tools/health/index.ts +4 -1
- package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +2 -1
- package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +1 -1
- package/app/src/pages/dashboard/index.ts +3 -2
- package/app/src/pages/dashboard/roles/index.ts +2 -2
- package/app/src/pages/dashboard/users/registrations/index.ts +66 -0
- package/app/src/services/api-tokens.ts +86 -0
- package/app/src/services/rbac.ts +26 -15
- package/app/src/services/roles.ts +125 -35
- package/app/src/services/security.ts +384 -0
- package/app/src/services/tenants.ts +447 -0
- package/app/src/services/users.ts +241 -97
- package/app/src/tenants.ts +219 -0
- package/package.json +48 -12
- package/src/block-references.ts +3 -3
- package/src/collections.ts +3 -1
- package/src/forms.ts +4 -2
- package/src/hooks.ts +19 -1
- package/src/index.ts +4 -4
- package/src/isolate-core.ts +1 -1
- package/src/isolation.ts +1 -0
- package/src/manifest.ts +43 -2
- package/src/permissions.ts +13 -7
- package/src/resource.ts +85 -2
- package/src/server/attempts.ts +64 -0
- package/src/server/automations.ts +2 -2
- package/src/server/batch.ts +106 -0
- package/src/server/budget.ts +17 -0
- package/src/server/field-values.ts +207 -0
- package/src/server/forms.ts +3 -3
- package/src/server/host-schema.ts +55 -7
- package/src/server/host.ts +213 -85
- package/src/server/index.ts +9 -14
- package/src/server/isolation.ts +10 -0
- package/src/server/network.ts +129 -44
- package/src/server/outbox.ts +2 -2
- package/src/server/people.ts +191 -0
- package/src/server/reconcile.ts +5 -5
- package/src/server/repository.ts +243 -84
- package/src/server/shared-read.ts +34 -0
- package/src/server/site-export.ts +23 -13
- package/src/server/site-import.ts +12 -33
- package/src/server/site-settings.ts +9 -3
- package/src/server/sites.ts +117 -187
- package/src/server/stores.ts +3 -300
- package/src/server/taxonomies.ts +64 -13
- package/src/server/users.ts +151 -498
- package/src/settings-controls.ts +8 -4
- package/src/settings.ts +26 -3
- package/src/storage/cloudflare.ts +2 -0
- package/src/storage/index.ts +6 -0
- package/src/theme.ts +2 -2
- package/src/version.ts +1 -1
- package/app/src/cms/handoff.ts +0 -202
- package/src/server/accounts.ts +0 -418
- package/src/server/api-tokens.ts +0 -91
- package/src/server/auth.ts +0 -89
- package/src/server/handoffs.ts +0 -107
- package/src/server/security.ts +0 -391
package/src/server/host.ts
CHANGED
|
@@ -6,7 +6,7 @@ import type { UpdatesOptions } from '../updates';
|
|
|
6
6
|
import { createHookRegistry, type ActionHandler, type ActionPoint, type ActionReport, type ExtensionPoint, type FilterContext, type FilterHandler, type FilterPoint, type HookRegistry, type InvokeOptions } from '@cossackframework/core/hooks';
|
|
7
7
|
import type { StorageProvider } from '@cossackframework/core/storage';
|
|
8
8
|
import { ClientError, MAX_STATEMENTS, type RomeDB, type Statement, type Value, type WorkLimits } from '@cossackframework/romedb';
|
|
9
|
-
import { normalizeRichText, richTextBlocks, withRichTextBlocks } from '../richtext';
|
|
9
|
+
import { normalizeRichText, richTextBlocks, richTextMedia, withRichTextBlocks, type RichTextDoc } from '../richtext';
|
|
10
10
|
import { blockId, blockMedia, blockProblems, htmlBlocksChanged, textFieldProblem, validateBlocks, type Block, type BlockDeclaration } from '../blocks';
|
|
11
11
|
import { blocksShapeProblem, type FieldDeclaration } from '../fields';
|
|
12
12
|
import { collectionProblems, collectionResource, contentBlocks, entryUrl, extendCollection, languageName, LOCALE, translationGroupOf, orderedFields, RESERVED_FIELDS, type CollectionDefinition } from '../collections';
|
|
@@ -26,9 +26,13 @@ import { taxonomyProblems, type TaxonomyDeclaration, type TermShape } from '../t
|
|
|
26
26
|
import { isPluginPoint, manifestProblems, providedPoints, requestedGrants, UNRESTRICTED_GRANT, type CmsPluginManifest, type PluginCommand, type SlotLink } from '../manifest';
|
|
27
27
|
import { ANONYMOUS, evaluateRule, hasPermission, isNetworkAdmin, PERMISSIONS, principalId, systemPrincipal, type Principal } from '../permissions';
|
|
28
28
|
import { AVATAR_TYPES, mediaUrl } from '../media';
|
|
29
|
-
import { canonicalJson, declarationHash, resolveResource, type Resource, type ResourceAction, type ResourceDeclaration } from '../resource';
|
|
29
|
+
import { canonicalJson, declarationHash, memberRuleProblems, ResourceDeclarationError, resolveResource, storageName, type Resource, type ResourceAction, type ResourceDeclaration } from '../resource';
|
|
30
30
|
import { Outbox, type OutboxOptions } from './outbox';
|
|
31
|
-
import {
|
|
31
|
+
import { FieldValues } from './field-values';
|
|
32
|
+
import { CmsAttempts } from './attempts';
|
|
33
|
+
import { memoryPeople, type PeoplePort } from './people';
|
|
34
|
+
import { groupMedia, JOIN_GROUP, ResourceRepository, type BatchGuard, type BatchWrite, type FieldFilter, type ListOptions, type OperationContext } from './repository';
|
|
35
|
+
import { batchResource, writeBatch } from './batch';
|
|
32
36
|
import { migrate, nextGenerationStatement, planSchema, readCatalog, type MigrationReport, type SchemaPlan } from './schema';
|
|
33
37
|
import { FileService, type CmsFile, type FileServiceOptions, type ImageSettings, LIBRARY_KEYS } from './files';
|
|
34
38
|
import { CmsCache } from './cache';
|
|
@@ -39,22 +43,21 @@ import { SiteSearch, SITE_SEARCH, searchRebuild } from './site-search';
|
|
|
39
43
|
import { sharedFields } from './shared-fields';
|
|
40
44
|
import { pathsMoved, pathsMovedStatement } from './path-moves';
|
|
41
45
|
import { noteAnnounced, type NoteAnnouncedEvent } from './notes';
|
|
42
|
-
import { readPaged } from './budget';
|
|
46
|
+
import { readPaged, readPagedTogether } from './budget';
|
|
47
|
+
import { sharedRead } from './shared-read';
|
|
43
48
|
import { isLockedRecord, lockedView } from './locked';
|
|
44
|
-
import {
|
|
49
|
+
import { pluginState, readPolicy, type NetworkPluginState, type NetworkPolicy } from './network-policy';
|
|
45
50
|
import { CmsSettings } from './site-settings';
|
|
46
|
-
import {
|
|
51
|
+
import { createJobStore, createNotificationStore } from './stores';
|
|
47
52
|
import { CmsMenus } from './menus';
|
|
48
53
|
import { CmsAreas } from './areas';
|
|
49
54
|
import { CmsTaxonomies } from './taxonomies';
|
|
50
55
|
import { CmsUsers } from './users';
|
|
51
|
-
import { CmsAccounts } from './accounts';
|
|
52
56
|
import { CmsPreviews, type PreviewLink } from './previews';
|
|
53
57
|
import { CmsAutosaves, type Autosave } from './autosaves';
|
|
54
58
|
import { CmsDrafts } from './drafts';
|
|
55
59
|
import { CmsNotes } from './notes';
|
|
56
60
|
import { CmsRedirects } from './redirects';
|
|
57
|
-
import { CmsApiTokens, type ApiTokenScope } from './api-tokens';
|
|
58
61
|
import { CmsWebhooks } from './webhooks';
|
|
59
62
|
import { CmsIndexNow } from './indexnow';
|
|
60
63
|
import { CmsPurge, type CachePurger } from './purge';
|
|
@@ -74,7 +77,6 @@ import type { PaymentEvent } from '../hooks';
|
|
|
74
77
|
import { siteBindingScope, type BindingScopes } from '../bindings';
|
|
75
78
|
import { CmsAutomations } from './automations';
|
|
76
79
|
import { CmsComments, collectionDeleted, collectionDeletedStatement } from './comments';
|
|
77
|
-
import { CmsSecurity } from './security';
|
|
78
80
|
import type { ImageTransformer } from './images';
|
|
79
81
|
import { checkComment, COMMENT_STATUSES, type CommentShape, type CommentStatus } from '../comments';
|
|
80
82
|
import { sha256Hex } from './tokens';
|
|
@@ -104,9 +106,30 @@ export interface PluginRegistrationLike {
|
|
|
104
106
|
|
|
105
107
|
export type { CmsModule };
|
|
106
108
|
|
|
109
|
+
/** The internal resource that stores the field values of users (`specs/cms-field-values.md`). */
|
|
110
|
+
export const USER_FIELDS = 'cms/user_fields';
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The internal resource that stores the field values of a taxonomy's terms. It exists while
|
|
114
|
+
* groups are attached to the taxonomy. A taxonomy's name may have capitals and be longer
|
|
115
|
+
* than a resource's, so such a name is shortened and told apart by a hash.
|
|
116
|
+
*/
|
|
117
|
+
export function termFieldsId(taxonomy: string): string {
|
|
118
|
+
if (/^[a-z][a-z0-9]{0,37}$/.test(taxonomy)) return `cms/tf_${taxonomy}`;
|
|
119
|
+
let hash = 0x811c9dc5;
|
|
120
|
+
for (let index = 0; index < taxonomy.length; index++) hash = Math.imul(hash ^ taxonomy.charCodeAt(index), 0x01000193) >>> 0;
|
|
121
|
+
return `cms/tf_${taxonomy.toLowerCase().slice(0, 28)}_${hash.toString(16).padStart(8, '0')}`;
|
|
122
|
+
}
|
|
123
|
+
|
|
107
124
|
export interface CmsOptions {
|
|
108
125
|
/** The site's database. */
|
|
109
126
|
readonly db: RomeDB;
|
|
127
|
+
/**
|
|
128
|
+
* Who keeps accounts, roles and sign-in: the application, on the dashboard package
|
|
129
|
+
* (`specs/cms-on-dashboard.md`). With it, `users` reads and writes people through this port
|
|
130
|
+
* and keeps only author slugs and field values. Without it, the CMS's own account tables are used.
|
|
131
|
+
*/
|
|
132
|
+
readonly people?: PeoplePort;
|
|
110
133
|
/** The site runs in development: webhooks may use plain HTTP and go to this machine or a private network. */
|
|
111
134
|
readonly localWebhooks?: boolean;
|
|
112
135
|
/**
|
|
@@ -125,8 +148,6 @@ export interface CmsOptions {
|
|
|
125
148
|
* note's write queued, so a note that was saved is announced even after a crash.
|
|
126
149
|
*/
|
|
127
150
|
readonly announceNote?: (host: CmsHost, event: NoteAnnouncedEvent) => Promise<void>;
|
|
128
|
-
/** Network sessions ended: end the child sessions that sites made from them. */
|
|
129
|
-
readonly sessionsEnded?: (ended: EndedSessions) => Promise<void>;
|
|
130
151
|
/** This site's ID in the network; default `main`. */
|
|
131
152
|
readonly site?: string;
|
|
132
153
|
/** Application resources; owner defaults to `app`. */
|
|
@@ -306,6 +327,12 @@ export interface PluginUnrestricted {
|
|
|
306
327
|
|
|
307
328
|
export interface PluginCms {
|
|
308
329
|
resource(id: string): PluginResource;
|
|
330
|
+
/**
|
|
331
|
+
* Writes that commit together or not at all, under guards that count other records in the
|
|
332
|
+
* same request (`CmsHost.batch`). Each write needs what it would alone; each guard's resource,
|
|
333
|
+
* the plugin's own or one it may read.
|
|
334
|
+
*/
|
|
335
|
+
batch(writes: readonly BatchWrite[], context: OperationContext & { readonly guards?: readonly BatchGuard[] }): Promise<(RecordShape | null)[]>;
|
|
309
336
|
}
|
|
310
337
|
|
|
311
338
|
/**
|
|
@@ -350,7 +377,10 @@ export type ThemeLoaderInput = { readonly site: SiteView } | { readonly entry: E
|
|
|
350
377
|
export type ThemeLoader = { bivarianceHack(context: LayoutLoaderContext | EntryLoaderContext | ArchiveLoaderContext): unknown }['bivarianceHack'];
|
|
351
378
|
export type ThemeLoaders = { readonly [template: string]: ThemeLoader };
|
|
352
379
|
|
|
353
|
-
export type PluginResource = Pick<ResourceRepository, 'get' | 'list' | 'count' | 'search' | 'create' | 'update' | 'delete'
|
|
380
|
+
export type PluginResource = Pick<ResourceRepository, 'get' | 'list' | 'count' | 'search' | 'create' | 'update' | 'delete'> & {
|
|
381
|
+
/** Throws unless the plugin may do this on the resource: its own, or requested and granted. */
|
|
382
|
+
checkGrant(action: ResourceAction): Promise<void>;
|
|
383
|
+
};
|
|
354
384
|
|
|
355
385
|
export interface PluginStatus {
|
|
356
386
|
readonly name: string;
|
|
@@ -419,12 +449,6 @@ interface Activation {
|
|
|
419
449
|
export const PLUGIN_ENABLED = 'plugin:enabled';
|
|
420
450
|
|
|
421
451
|
/** Where an account and what signs it in live: the site's own database, or the network's. */
|
|
422
|
-
export interface AccountStores {
|
|
423
|
-
readonly kind: 'site' | 'network';
|
|
424
|
-
readonly accounts: CmsAccounts;
|
|
425
|
-
readonly security: CmsSecurity;
|
|
426
|
-
readonly apiTokens: CmsApiTokens;
|
|
427
|
-
}
|
|
428
452
|
|
|
429
453
|
export class CmsHost {
|
|
430
454
|
readonly db: RomeDB;
|
|
@@ -433,20 +457,11 @@ export class CmsHost {
|
|
|
433
457
|
/** This site's ID in the network: `main`, or the registry ID. */
|
|
434
458
|
readonly site: string;
|
|
435
459
|
readonly hooks: HookRegistry;
|
|
436
|
-
/**
|
|
437
|
-
readonly
|
|
438
|
-
/**
|
|
439
|
-
* Site accounts: people who sign in on this site only, on its own database, with their own
|
|
440
|
-
* second factors, passkeys and application passwords. Null on the main site, whose accounts
|
|
441
|
-
* are the network's.
|
|
442
|
-
*/
|
|
443
|
-
readonly siteAccounts: CmsAccounts | null;
|
|
460
|
+
/** The field group values of users: one document per member. */
|
|
461
|
+
readonly userFields: FieldValues;
|
|
444
462
|
/** This site's members and roles. */
|
|
445
463
|
readonly users: CmsUsers;
|
|
446
464
|
readonly outbox: Outbox;
|
|
447
|
-
readonly authSessions: ReturnType<typeof createAuthSessionStore>;
|
|
448
|
-
readonly oauthStates: ReturnType<typeof createOAuthStateStore>;
|
|
449
|
-
readonly sessions: ReturnType<typeof createSessionStore>;
|
|
450
465
|
readonly taxonomies: CmsTaxonomies;
|
|
451
466
|
readonly settings: CmsSettings;
|
|
452
467
|
readonly menus: CmsMenus;
|
|
@@ -461,7 +476,6 @@ export class CmsHost {
|
|
|
461
476
|
/** Editors' review notes on entries, fields, blocks and passages. */
|
|
462
477
|
readonly notes: CmsNotes;
|
|
463
478
|
readonly redirects: CmsRedirects;
|
|
464
|
-
readonly apiTokens: CmsApiTokens;
|
|
465
479
|
readonly webhooks: CmsWebhooks;
|
|
466
480
|
readonly indexnow: CmsIndexNow;
|
|
467
481
|
/** Purges of the caches in front of the site, queued by changes and sent from the outbox. */
|
|
@@ -494,12 +508,8 @@ export class CmsHost {
|
|
|
494
508
|
readonly automations: CmsAutomations;
|
|
495
509
|
readonly #secrets: (name: string) => string | undefined;
|
|
496
510
|
readonly #env: Readonly<Record<string, unknown>>;
|
|
497
|
-
/**
|
|
498
|
-
readonly
|
|
499
|
-
/** Second factors and passkeys of site accounts; null on the main site. */
|
|
500
|
-
readonly siteSecurity: CmsSecurity | null;
|
|
501
|
-
/** Application passwords of site accounts; null on the main site. */
|
|
502
|
-
readonly siteApiTokens: CmsApiTokens | null;
|
|
511
|
+
/** Counted attempts for the CMS's own limits: forms, comments, suggestions, site registrations. */
|
|
512
|
+
readonly attempts: CmsAttempts;
|
|
503
513
|
/** Media files, when the host has object storage. */
|
|
504
514
|
readonly files: FileService | null;
|
|
505
515
|
/** A cache shared by every isolate, on RomeDB: values slow to compute, such as the library's summary. */
|
|
@@ -511,7 +521,11 @@ export class CmsHost {
|
|
|
511
521
|
/** Code-declared resources: modules, the application and plugins. */
|
|
512
522
|
readonly #static = new Map<string, Resource>();
|
|
513
523
|
/** Static resources and the current collections. */
|
|
524
|
+
/** Who keeps accounts, roles and sign-in: the application's port, or people kept in memory without one. */
|
|
525
|
+
readonly people: PeoplePort;
|
|
514
526
|
#resources = new Map<string, Resource>();
|
|
527
|
+
/** The stores of terms' field values, by taxonomy. */
|
|
528
|
+
readonly #termFields = new Map<string, FieldValues>();
|
|
515
529
|
readonly #repositories = new Map<string, ResourceRepository>();
|
|
516
530
|
readonly #plugins = new Map<string, HostedPlugin>();
|
|
517
531
|
readonly #runner: PluginRunner | null;
|
|
@@ -558,6 +572,11 @@ export class CmsHost {
|
|
|
558
572
|
const modules = options.modules ?? [];
|
|
559
573
|
for (const module of modules) for (const declaration of module.resources) this.#register(resolveResource(declaration, module.owner));
|
|
560
574
|
for (const declaration of options.resources ?? []) this.#register(resolveResource(declaration, declaration.owner ?? 'app'));
|
|
575
|
+
// Membership rules name resources of the same owner; a plugin's are checked with its manifest.
|
|
576
|
+
for (const resource of this.#static.values()) {
|
|
577
|
+
const problems = memberRuleProblems(resource, resource.owner, id => this.#static.get(id));
|
|
578
|
+
if (problems.length) throw new ResourceDeclarationError(resource.id, problems);
|
|
579
|
+
}
|
|
561
580
|
this.#runner = options.runner ?? null;
|
|
562
581
|
for (const registration of options.plugins ?? []) this.#host(registration);
|
|
563
582
|
this.#resolvePluginPoints();
|
|
@@ -587,15 +606,19 @@ export class CmsHost {
|
|
|
587
606
|
}
|
|
588
607
|
this.#apply(new Map(), new Map());
|
|
589
608
|
this.fieldGroups = new CmsFieldGroups(this.db, { now: this.#now });
|
|
590
|
-
this.accounts = new CmsAccounts(this.network, { now: this.#now, ...(options.sessionsEnded ? { sessionsEnded: options.sessionsEnded } : {}) });
|
|
591
609
|
const added = this.network !== this.db;
|
|
592
|
-
// A
|
|
593
|
-
this.
|
|
594
|
-
|
|
610
|
+
// A user's field values are a document beside the member row, in the storage of an internal resource (specs/cms-field-values.md).
|
|
611
|
+
this.userFields = new FieldValues(this.db, {
|
|
612
|
+
resource: () => this.#resources.get(USER_FIELDS)!,
|
|
613
|
+
storageOf: id => this.resourceById(id).storage,
|
|
614
|
+
media: values => this.#valuesMedia(this.#resources.get(USER_FIELDS)!.fields, values),
|
|
615
|
+
now: this.#now,
|
|
616
|
+
});
|
|
617
|
+
// Accounts, roles and sign-in are the application's (the dashboard package's in a CMS project). Without a port the host keeps people in memory: for tests, and for trying the CMS alone.
|
|
618
|
+
this.people = options.people ?? memoryPeople({ now: this.#now });
|
|
619
|
+
this.users = new CmsUsers(this.db, { people: this.people, now: this.#now, fields: this.userFields, checkMeta: (meta, previous, principal) => this.#checkMeta({ kind: 'users' }, meta, previous, principal) });
|
|
595
620
|
this.redirects = new CmsRedirects(this.db, { now: this.#now, changed: () => this.#purgeSite('redirects') });
|
|
596
621
|
this.traffic = new CmsTraffic(this.db, { now: this.#now });
|
|
597
|
-
this.apiTokens = new CmsApiTokens(this.network, { now: this.#now });
|
|
598
|
-
this.siteApiTokens = added ? new CmsApiTokens(this.db, { now: this.#now }) : null;
|
|
599
622
|
this.webhooks = new CmsWebhooks(this.db, { now: this.#now, fetch: options.webhookFetch ?? this.#fetch, local: options.localWebhooks === true });
|
|
600
623
|
this.comments = new CmsComments(this.db, { now: this.#now, changed: entries => this.#purgeLater('comments', { tags: entries.filter(entry => entry.resource.startsWith('cms/')).map(entry => this.purge.tag.entry(entry.resource.slice(4), entry.recordId)) }) });
|
|
601
624
|
this.mailFrom = options.mailFrom ?? 'no-reply@example.com';
|
|
@@ -604,8 +627,7 @@ export class CmsHost {
|
|
|
604
627
|
siteUrl: typeof options.siteUrl === 'function' ? options.siteUrl : () => options.siteUrl as string | undefined }) : null;
|
|
605
628
|
const mail = this.mail;
|
|
606
629
|
this.forms = new CmsForms(this, { ...(mail ? { mail: { send: message => mail.send({ ...message, kind: 'form' }) } } : {}), mailFrom: this.mailFrom });
|
|
607
|
-
this.
|
|
608
|
-
this.siteSecurity = added ? new CmsSecurity(this.db, { now: this.#now }) : null;
|
|
630
|
+
this.attempts = new CmsAttempts(this.db, { now: this.#now });
|
|
609
631
|
this.siteSearch = new SiteSearch(this);
|
|
610
632
|
// Rebuilds of the site's search index run from the outbox, a round of entries at a time.
|
|
611
633
|
this.hooks.addAction(searchRebuild, (event, context) => this.siteSearch.step(event, context.signal ? { signal: context.signal } : {}), { plugin: 'cms-search' });
|
|
@@ -673,15 +695,12 @@ export class CmsHost {
|
|
|
673
695
|
this.hooks.addAction(formSubmitted, event => this.forms.notify(event), { plugin: 'cms' });
|
|
674
696
|
this.hooks.addAction(formSubmitted, event => this.#queueFormWebhooks(event), { plugin: 'cms' });
|
|
675
697
|
this.outbox = new Outbox(this.db, this.hooks, { now: this.#now, ...options.outbox });
|
|
676
|
-
// The main site's sessions are the network's; another site's are child sessions handed off from them.
|
|
677
|
-
this.authSessions = createAuthSessionStore(this.db, { now: this.#now, request: requestMetadata, ...(options.sessionsEnded ? { sessionsEnded: options.sessionsEnded } : {}) });
|
|
678
|
-
this.oauthStates = createOAuthStateStore(this.network);
|
|
679
|
-
this.sessions = createSessionStore(this.db, { now: this.#now });
|
|
680
698
|
this.taxonomies = new CmsTaxonomies(this.db, {
|
|
681
699
|
taxonomies: () => this.#taxonomies,
|
|
682
700
|
now: this.#now,
|
|
683
701
|
beforeSave: (draft, input) => this.hooks.applyFilters(termBeforeSave, draft, input),
|
|
684
702
|
checkMeta: taxonomy => (meta, previous, principal) => this.#checkMeta({ kind: 'taxonomy', name: taxonomy }, meta, previous, principal),
|
|
703
|
+
fields: taxonomy => this.#termValues(taxonomy),
|
|
685
704
|
usage: name => this.resources.flatMap(resource => Object.entries(resource.fields)
|
|
686
705
|
.filter(([, declaration]) => declaration.taxonomy === name).map(([field]) => ({ resource: resource.id, storage: resource.storage, field }))),
|
|
687
706
|
canAssign: (principal, taxonomy) => this.taxonomies.usage(taxonomy.name).some(({ resource: id }) => {
|
|
@@ -731,9 +750,9 @@ export class CmsHost {
|
|
|
731
750
|
principal: id => this.users.principal(id),
|
|
732
751
|
// As the repository answers the author: without the fields their permissions do not read,
|
|
733
752
|
// and a locked entry as its readers see it unless the author may update it.
|
|
734
|
-
redact: (collection, record, principal) => {
|
|
753
|
+
redact: async (collection, record, principal) => {
|
|
735
754
|
const fields = this.#collections.has(collection) ? this.resourceById(`cms/${collection}`).fields : {};
|
|
736
|
-
const editor = this.#collections.has(collection) && this.resource(`cms/${collection}`).canUpdate(record as RecordShape, principal);
|
|
755
|
+
const editor = this.#collections.has(collection) && await this.resource(`cms/${collection}`).canUpdate(record as RecordShape, { principal });
|
|
737
756
|
const seen = editor ? record : lockedView(record as RecordShape, fields);
|
|
738
757
|
const hidden = Object.entries(fields).filter(([, field]) => field.access?.read && !hasPermission(principal, field.access.read)).map(([name]) => name);
|
|
739
758
|
return hidden.length ? Object.fromEntries(Object.entries(seen).filter(([name]) => !hidden.includes(name))) : seen;
|
|
@@ -748,7 +767,10 @@ export class CmsHost {
|
|
|
748
767
|
|
|
749
768
|
now(): number { return this.#now(); }
|
|
750
769
|
|
|
751
|
-
|
|
770
|
+
/** The resources people and plugins work with. Internal ones (a user's field values) are left out. */
|
|
771
|
+
get resources(): readonly Resource[] { return [...this.#resources.values()].filter(resource => !resource.internal); }
|
|
772
|
+
/** Every resource that has storage to plan and migrate, internal ones too. */
|
|
773
|
+
get #stored(): readonly Resource[] { return [...this.#resources.values()]; }
|
|
752
774
|
|
|
753
775
|
/** Revisions of a dropped collection's entries written up to `before`. */
|
|
754
776
|
async #deleteRevisions(resource: string, before: number): Promise<void> {
|
|
@@ -796,10 +818,20 @@ export class CmsHost {
|
|
|
796
818
|
return resource;
|
|
797
819
|
}
|
|
798
820
|
|
|
821
|
+
/**
|
|
822
|
+
* Several writes that commit together, in one request, or not at all: each prepared as it
|
|
823
|
+
* would be alone, with `guards` (counts of other records) and each record's revision checked
|
|
824
|
+
* in the same request. See `writeBatch`.
|
|
825
|
+
*/
|
|
826
|
+
batch(writes: readonly BatchWrite[], context: OperationContext & { readonly guards?: readonly BatchGuard[] }): Promise<(RecordShape | null)[]> {
|
|
827
|
+
return writeBatch(this, writes, context);
|
|
828
|
+
}
|
|
829
|
+
|
|
799
830
|
resource(id: string): ResourceRepository {
|
|
800
831
|
let repository = this.#repositories.get(id);
|
|
801
832
|
if (!repository) {
|
|
802
|
-
|
|
833
|
+
// The host's own storage has no repository: its rows are not records with revisions, owners and events.
|
|
834
|
+
if (this.resourceById(id).internal) throw new CmsError('CMS_NOT_FOUND', `Unknown resource ${id}.`);
|
|
803
835
|
repository = new ResourceRepository(this, id);
|
|
804
836
|
this.#repositories.set(id, repository);
|
|
805
837
|
}
|
|
@@ -811,6 +843,10 @@ export class CmsHost {
|
|
|
811
843
|
* request middleware awaits this so `resource()` sees current collections.
|
|
812
844
|
*/
|
|
813
845
|
ready(options: { force?: boolean } = {}): Promise<void> {
|
|
846
|
+
return sharedRead(() => this.#ready(options));
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
#ready(options: { force?: boolean }): Promise<void> {
|
|
814
850
|
const now = this.#now();
|
|
815
851
|
if (options.force || !this.#definitions || now - this.#definitions.at > this.#activationTtl) {
|
|
816
852
|
// The activation state and the settings are read by the steps that need them, not started here
|
|
@@ -1025,7 +1061,7 @@ export class CmsHost {
|
|
|
1025
1061
|
const repository = this.resource(resourceId);
|
|
1026
1062
|
const record = await repository.get(id, { principal });
|
|
1027
1063
|
if (!record) throw new CmsError('CMS_NOT_FOUND', 'Record not found.');
|
|
1028
|
-
if (!repository.canUpdate(record, principal)) throw new CmsError(principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', 'Not allowed to edit this entry.');
|
|
1064
|
+
if (!await repository.canUpdate(record, { principal })) throw new CmsError(principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', 'Not allowed to edit this entry.');
|
|
1029
1065
|
return record;
|
|
1030
1066
|
}
|
|
1031
1067
|
|
|
@@ -1037,23 +1073,6 @@ export class CmsHost {
|
|
|
1037
1073
|
* The stores that sign people in on this host: the site's own on an added site, the
|
|
1038
1074
|
* network's on the main site. Sign-in by email, passkey or reset token starts here.
|
|
1039
1075
|
*/
|
|
1040
|
-
get signIn(): AccountStores {
|
|
1041
|
-
return this.siteAccounts ? { kind: 'site', accounts: this.siteAccounts, security: this.siteSecurity!, apiTokens: this.siteApiTokens! }
|
|
1042
|
-
: { kind: 'network', accounts: this.accounts, security: this.security, apiTokens: this.apiTokens };
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
/** The stores holding a user's account: the site's for a site account, the network's otherwise. */
|
|
1046
|
-
async storesOf(userId: string): Promise<AccountStores> {
|
|
1047
|
-
return this.siteAccounts && await this.siteAccounts.get(userId) ? this.signIn
|
|
1048
|
-
: { kind: 'network', accounts: this.accounts, security: this.security, apiTokens: this.apiTokens };
|
|
1049
|
-
}
|
|
1050
|
-
|
|
1051
|
-
async tokenPrincipal(token: string): Promise<{ principal: Principal; scope: ApiTokenScope; userId: string } | null> {
|
|
1052
|
-
const verified = await this.siteApiTokens?.verify(token) ?? await this.apiTokens.verify(token);
|
|
1053
|
-
if (!verified) return null;
|
|
1054
|
-
const user = await this.users.resolve(verified.userId);
|
|
1055
|
-
return user ? { principal: user.principal, scope: verified.scope, userId: user.id } : null;
|
|
1056
|
-
}
|
|
1057
1076
|
|
|
1058
1077
|
/** Whether the site has discussions at all (Settings → Discussion → Allow discussions). Off hides every comment; stored ones are kept. */
|
|
1059
1078
|
discussions(settings: SiteSettings): boolean {
|
|
@@ -1097,7 +1116,7 @@ export class CmsHost {
|
|
|
1097
1116
|
}
|
|
1098
1117
|
const ipHash = context.ip ? await sha256Hex(`cms-comment:${context.ip}`) : null;
|
|
1099
1118
|
// One comment per address in 15 seconds, counted in one conditional write so a burst gets one through.
|
|
1100
|
-
if (ipHash && !(await this.
|
|
1119
|
+
if (ipHash && !(await this.attempts.attempt('comment', ipHash, 1, 15_000))) throw new CmsError('CMS_LIMIT', 'You are posting comments too quickly. Wait a moment and try again.');
|
|
1101
1120
|
// "An earlier approved comment" counts for signed-in users only: an anonymous commenter types any email.
|
|
1102
1121
|
const status: CommentStatus = input.trap ? 'spam' : hasPermission(context.principal, PERMISSIONS.moderateComments) ? 'approved'
|
|
1103
1122
|
: await commentStatus(fields, settings, async () => user !== null && await this.comments.hasApproved(fields.authorEmail));
|
|
@@ -1496,7 +1515,7 @@ export class CmsHost {
|
|
|
1496
1515
|
const source = await repository.get(id, { principal });
|
|
1497
1516
|
if (!source) throw new CmsError('CMS_NOT_FOUND', 'Entry not found.');
|
|
1498
1517
|
// A translation starts as a copy: a reader the entry is locked for gets none to open.
|
|
1499
|
-
if (lockedCopy(source, repository.canUpdate(source, principal))) throw new CmsError('CMS_FORBIDDEN', 'Only its editors can translate a protected or members-only entry.');
|
|
1518
|
+
if (lockedCopy(source, await repository.canUpdate(source, { principal }))) throw new CmsError('CMS_FORBIDDEN', 'Only its editors can translate a protected or members-only entry.');
|
|
1500
1519
|
// A translation the principal cannot read still exists: never start a second one.
|
|
1501
1520
|
const existing = (await this.translations(collection, source, { principal: systemPrincipal('translations') })).get(locale);
|
|
1502
1521
|
if (existing) {
|
|
@@ -1807,10 +1826,18 @@ export class CmsHost {
|
|
|
1807
1826
|
this.taxonomies.declaration(name);
|
|
1808
1827
|
const users = this.collections().filter(collection => collection.taxonomies?.includes(name));
|
|
1809
1828
|
if (users.length) throw new CmsError('CMS_CONFLICT', `${users.map(collection => collection.label).join(', ')} use this taxonomy.`);
|
|
1829
|
+
// Its terms' field values go with it, whether or not groups are attached now.
|
|
1830
|
+
const fields = termFieldsId(name);
|
|
1831
|
+
const storage = storageName('cms', fields.slice(4));
|
|
1832
|
+
const info = await this.db.read([{ rql: 'INFO FOR DB' }]);
|
|
1833
|
+
const exists = ((info.results[0]!.rows[0]![0] as { tables?: { name: string }[] }).tables ?? []).some(table => table.name === storage);
|
|
1834
|
+
const at = this.#now();
|
|
1810
1835
|
await this.db.write([
|
|
1811
1836
|
{ rql: 'DELETE FROM cms_terms WHERE taxonomy = $name', params: { $name: name } },
|
|
1812
1837
|
{ rql: 'DELETE FROM cms_taxonomies WHERE name = $name', params: { $name: name } },
|
|
1838
|
+
...(exists ? [{ rql: `DROP TABLE ${storage}` }, { rql: 'DELETE FROM cms_schema_state WHERE resource = $id', params: { $id: fields } }, nextGenerationStatement(at)] : []),
|
|
1813
1839
|
], { kind: 'cms.collections' });
|
|
1840
|
+
this.#termFields.delete(name);
|
|
1814
1841
|
await this.ready({ force: true });
|
|
1815
1842
|
}
|
|
1816
1843
|
|
|
@@ -1820,11 +1847,11 @@ export class CmsHost {
|
|
|
1820
1847
|
}
|
|
1821
1848
|
|
|
1822
1849
|
async plan(options: { signal?: AbortSignal } = {}): Promise<SchemaPlan> {
|
|
1823
|
-
return planSchema(this
|
|
1850
|
+
return planSchema(this.#stored, await readCatalog(this.db, this.#stored.map(resource => resource.storage), options));
|
|
1824
1851
|
}
|
|
1825
1852
|
|
|
1826
1853
|
async migrate(options: { signal?: AbortSignal } = {}): Promise<MigrationReport> {
|
|
1827
|
-
const report = await migrate(this.db, this
|
|
1854
|
+
const report = await migrate(this.db, this.#stored, { ...options, now: this.#now });
|
|
1828
1855
|
this.#activation = undefined;
|
|
1829
1856
|
return report;
|
|
1830
1857
|
}
|
|
@@ -1905,9 +1932,24 @@ export class CmsHost {
|
|
|
1905
1932
|
await this.#purgeSite('plugins');
|
|
1906
1933
|
await this.#seedFieldGroups(plugin, principal);
|
|
1907
1934
|
await this.#seedPatterns(plugin, principal);
|
|
1935
|
+
await this.#seedRoles(plugin);
|
|
1908
1936
|
return this.#pluginStatus(plugin, await this.#state());
|
|
1909
1937
|
}
|
|
1910
1938
|
|
|
1939
|
+
/**
|
|
1940
|
+
* Define the roles a plugin's manifest ships. A role the site has is left as it is, changed or
|
|
1941
|
+
* not; with `onlyIfNone`, nothing is added while the site has any of them, so a role it
|
|
1942
|
+
* deleted stays deleted, and comes back with the plugin's next grant.
|
|
1943
|
+
*/
|
|
1944
|
+
async #seedRoles(plugin: HostedPlugin, options: { onlyIfNone?: boolean } = {}): Promise<void> {
|
|
1945
|
+
const declared = plugin.manifest.roles ?? [];
|
|
1946
|
+
if (!declared.length) return;
|
|
1947
|
+
const existing = new Set<string>();
|
|
1948
|
+
for (const role of declared) if (await this.users.role(role.id)) existing.add(role.id);
|
|
1949
|
+
if (options.onlyIfNone && existing.size) return;
|
|
1950
|
+
for (const role of declared) if (!existing.has(role.id)) await this.users.defineRole({ id: role.id, name: role.name, permissions: [...role.permissions] });
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1911
1953
|
/**
|
|
1912
1954
|
* Store the patterns a plugin's manifest ships, as `<plugin>-<slug>`: sections a theme or a
|
|
1913
1955
|
* plugin offers in the pattern picker. A pattern the site already has is left as it is, edited
|
|
@@ -2010,7 +2052,18 @@ export class CmsHost {
|
|
|
2010
2052
|
|
|
2011
2053
|
/** Repositories limited to a plugin's own resources and its granted ones. */
|
|
2012
2054
|
pluginCms(name: string): PluginCms {
|
|
2013
|
-
|
|
2055
|
+
const cms: PluginCms = {
|
|
2056
|
+
batch: async (writes, context) => {
|
|
2057
|
+
// The same grant checks as each call alone: a write's action, a guard's read.
|
|
2058
|
+
if (!Array.isArray(writes)) throw new CmsError('CMS_VALIDATION', 'A batch is a list of writes.');
|
|
2059
|
+
for (const write of writes) {
|
|
2060
|
+
const id = write && typeof write === 'object' ? batchResource(write) : undefined;
|
|
2061
|
+
if (typeof id !== 'string') throw new CmsError('CMS_VALIDATION', 'A write creates, updates or deletes a record.');
|
|
2062
|
+
await cms.resource(id).checkGrant('create' in write ? 'create' : 'update' in write ? 'update' : 'delete');
|
|
2063
|
+
}
|
|
2064
|
+
for (const guard of context?.guards ?? []) await cms.resource(String(guard?.resource)).checkGrant('read');
|
|
2065
|
+
return this.batch(writes, context);
|
|
2066
|
+
},
|
|
2014
2067
|
resource: id => {
|
|
2015
2068
|
const plugin = this.#plugins.get(name);
|
|
2016
2069
|
// Its own resources and the collections it ships.
|
|
@@ -2036,9 +2089,11 @@ export class CmsHost {
|
|
|
2036
2089
|
create: (input, context) => check('create').then(() => repository.create(input, context)),
|
|
2037
2090
|
update: (key, patch, context) => check('update').then(() => repository.update(key, patch, context)),
|
|
2038
2091
|
delete: (key, context) => check('delete').then(() => repository.delete(key, context)),
|
|
2092
|
+
checkGrant: async (action: ResourceAction) => { await check(action); },
|
|
2039
2093
|
};
|
|
2040
2094
|
},
|
|
2041
2095
|
};
|
|
2096
|
+
return cms;
|
|
2042
2097
|
}
|
|
2043
2098
|
|
|
2044
2099
|
/** Called after each committed mutation. Menus link to entries, so their cache is dropped. */
|
|
@@ -2094,6 +2149,10 @@ export class CmsHost {
|
|
|
2094
2149
|
const resource = this.#resources.get(`cms/${collection.name}`);
|
|
2095
2150
|
if (resource && state.hashes.get(resource.id) !== await declarationHash(resource)) stale.push(resource.id);
|
|
2096
2151
|
}
|
|
2152
|
+
// The host's own storage follows the groups attached to it, as a collection does.
|
|
2153
|
+
for (const resource of this.#resources.values()) {
|
|
2154
|
+
if (resource.internal && state.hashes.get(resource.id) !== await declarationHash(resource)) stale.push(resource.id);
|
|
2155
|
+
}
|
|
2097
2156
|
// A plugin the network activates is migrated on every site as the site loads.
|
|
2098
2157
|
const networkActive = [...this.#plugins.values()].filter(plugin => !plugin.problems.length && pluginState(state.policy, plugin.manifest.name) === 'network');
|
|
2099
2158
|
for (const id of networkActive.flatMap(plugin => plugin.resources)) {
|
|
@@ -2101,7 +2160,7 @@ export class CmsHost {
|
|
|
2101
2160
|
if (resource && !stale.includes(id) && state.hashes.get(id) !== await declarationHash(resource)) stale.push(id);
|
|
2102
2161
|
}
|
|
2103
2162
|
if (hostPending || stale.length) {
|
|
2104
|
-
this.#upgrading ??= migrate(this.db, this
|
|
2163
|
+
this.#upgrading ??= migrate(this.db, this.#stored, { now: this.#now, only: stale }).then(report => {
|
|
2105
2164
|
if (report.failed) console.error(`[cms] could not upgrade the schema: ${report.failed.message}`);
|
|
2106
2165
|
}).catch(error => console.error('[cms] could not upgrade the schema', error)).finally(() => {
|
|
2107
2166
|
this.#upgrading = undefined;
|
|
@@ -2114,6 +2173,7 @@ export class CmsHost {
|
|
|
2114
2173
|
for (const plugin of networkActive) {
|
|
2115
2174
|
if (plugin.manifest.fieldGroups?.length && !this.#groups.some(group => group.plugin === plugin.manifest.name)) await this.#seedFieldGroups(plugin, systemPrincipal('network')).catch(error => console.error(`[cms] could not add the field groups of ${plugin.manifest.name}`, error));
|
|
2116
2175
|
await this.#seedPatterns(plugin, systemPrincipal('network'), { onlyIfNone: true }).catch(error => console.error(`[cms] could not add the patterns of ${plugin.manifest.name}`, error));
|
|
2176
|
+
await this.#seedRoles(plugin, { onlyIfNone: true }).catch(error => console.error(`[cms] could not add the roles of ${plugin.manifest.name}`, error));
|
|
2117
2177
|
}
|
|
2118
2178
|
}
|
|
2119
2179
|
|
|
@@ -2131,11 +2191,13 @@ export class CmsHost {
|
|
|
2131
2191
|
// Awaited below; when the definitions fail first, its own failure is not left unhandled.
|
|
2132
2192
|
groups.catch(() => undefined);
|
|
2133
2193
|
try {
|
|
2134
|
-
// Definitions are JSON of many fields: forty large collections may come in smaller reads. Collections
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2194
|
+
// Definitions are JSON of many fields: forty large collections may come in smaller reads. Collections and
|
|
2195
|
+
// taxonomies come in one request, beside the field groups' own: each read in flight takes one of the
|
|
2196
|
+
// database client's places, which every request of the isolate shares.
|
|
2197
|
+
[collections = [], taxonomies = []] = await readPagedTogether(this.db, [
|
|
2198
|
+
(size, at) => ({ rql: 'SELECT name, definition FROM cms_collections ORDER BY name LIMIT $limit OFFSET $offset', params: { $limit: size, $offset: at } }),
|
|
2199
|
+
(size, at) => ({ rql: 'SELECT name, definition FROM cms_taxonomies ORDER BY name LIMIT $limit OFFSET $offset', params: { $limit: size, $offset: at } }),
|
|
2200
|
+
], 200);
|
|
2139
2201
|
} catch (error) {
|
|
2140
2202
|
// Before setup the tables do not exist; built-ins apply.
|
|
2141
2203
|
if (!(error instanceof ClientError) || !/cms_collections|cms_taxonomies|no such table|not found/i.test(error.message)) throw error;
|
|
@@ -2152,7 +2214,53 @@ export class CmsHost {
|
|
|
2152
2214
|
return groupsForTarget(this.#groups, target);
|
|
2153
2215
|
}
|
|
2154
2216
|
|
|
2155
|
-
/**
|
|
2217
|
+
/** Where a taxonomy's terms keep their field values, or null while no group is attached to it. */
|
|
2218
|
+
#termValues(taxonomy: string): FieldValues | null {
|
|
2219
|
+
const id = termFieldsId(taxonomy);
|
|
2220
|
+
if (!this.#resources.has(id)) return null;
|
|
2221
|
+
let store = this.#termFields.get(taxonomy);
|
|
2222
|
+
if (!store) {
|
|
2223
|
+
store = new FieldValues(this.db, {
|
|
2224
|
+
resource: () => this.#resources.get(id)!,
|
|
2225
|
+
storageOf: target => this.resourceById(target).storage,
|
|
2226
|
+
media: values => this.#valuesMedia(this.#resources.get(id)!.fields, values),
|
|
2227
|
+
now: this.#now,
|
|
2228
|
+
});
|
|
2229
|
+
this.#termFields.set(taxonomy, store);
|
|
2230
|
+
}
|
|
2231
|
+
return store;
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
/** The internal resource of a taxonomy's term fields, or null when its groups give none. */
|
|
2235
|
+
#termFieldsResource(taxonomy: TaxonomyDeclaration): Resource | null {
|
|
2236
|
+
let fields: { [name: string]: FieldDeclaration } = {};
|
|
2237
|
+
try { fields = this.#groupFields({ kind: 'taxonomy', name: taxonomy.name }).fields; } catch { return null; }
|
|
2238
|
+
if (!Object.keys(fields).length) return null;
|
|
2239
|
+
return resolveResource({ name: termFieldsId(taxonomy.name).slice(4), label: `${taxonomy.label} fields`, schemaless: true, internal: true, revisions: false, fields }, 'cms');
|
|
2240
|
+
}
|
|
2241
|
+
|
|
2242
|
+
/** The users' fields: the author profile and the fields of the groups attached to users. */
|
|
2243
|
+
#userFieldsResource(): Resource {
|
|
2244
|
+
// A group whose blocks no longer validate adds no fields, as on a collection.
|
|
2245
|
+
let fields: { [name: string]: FieldDeclaration } = {};
|
|
2246
|
+
try { fields = this.#groupFields({ kind: 'users' }).fields; } catch { /* the author profile alone */ }
|
|
2247
|
+
return resolveResource({ name: USER_FIELDS.slice(4), label: 'User fields', schemaless: true, internal: true, revisions: false, fields: { ...AUTHOR_FIELDS, ...fields } }, 'cms');
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
/** The media files that values of these fields name: media fields, and files inside blocks, rich text and groups. */
|
|
2251
|
+
#valuesMedia(fields: { readonly [name: string]: FieldDeclaration }, values: { readonly [field: string]: unknown }): string[] {
|
|
2252
|
+
const files: string[] = [];
|
|
2253
|
+
for (const [name, value] of Object.entries(values)) {
|
|
2254
|
+
const declaration = Object.hasOwn(fields, name) ? fields[name] : undefined;
|
|
2255
|
+
if (!declaration || value === null || value === undefined) continue;
|
|
2256
|
+
files.push(...(declaration.media ? (Array.isArray(value) ? value as string[] : [value as string])
|
|
2257
|
+
: declaration.kind === 'blocks' ? blockMedia(value as Block[], this.#blocks)
|
|
2258
|
+
: declaration.kind === 'richtext' ? [...richTextMedia(value as RichTextDoc), ...blockMedia(richTextBlocks(value as RichTextDoc), this.#blocks)]
|
|
2259
|
+
: declaration.fields ? groupMedia(declaration, value as { [key: string]: unknown }) : []));
|
|
2260
|
+
}
|
|
2261
|
+
return files.filter(file => typeof file === 'string' && file);
|
|
2262
|
+
}
|
|
2263
|
+
|
|
2156
2264
|
#groupFields(target: FieldGroupTarget): { fields: { [name: string]: FieldDeclaration }; layout: Block[] } {
|
|
2157
2265
|
const fields: { [name: string]: FieldDeclaration } = {};
|
|
2158
2266
|
const layout: Block[] = [];
|
|
@@ -2277,7 +2385,7 @@ export class CmsHost {
|
|
|
2277
2385
|
async #migrateTargets(group: FieldGroup, principal: Principal): Promise<void> {
|
|
2278
2386
|
this.#activation = undefined;
|
|
2279
2387
|
await this.ready({ force: true });
|
|
2280
|
-
const ids = group.targets.
|
|
2388
|
+
const ids = group.targets.flatMap(target => target.kind === 'collection' ? [`cms/${target.name}`] : target.kind === 'users' ? [USER_FIELDS] : target.kind === 'taxonomy' ? [termFieldsId(target.name)] : []).filter(id => this.#resources.has(id));
|
|
2281
2389
|
if (!ids.length) return;
|
|
2282
2390
|
const resources = [...this.#resources.values()];
|
|
2283
2391
|
const plan = await planSchema(resources, await readCatalog(this.db, resources.filter(entry => ids.includes(entry.id)).map(entry => entry.storage)));
|
|
@@ -2306,6 +2414,17 @@ export class CmsHost {
|
|
|
2306
2414
|
for (const [name, stored] of storedCollections) if (!this.#builtinCollections.has(name)) collections.set(name, { ...stored, builtin: false });
|
|
2307
2415
|
const labels = Object.fromEntries([...taxonomies.values()].map(taxonomy => [taxonomy.name, taxonomy.label]));
|
|
2308
2416
|
const resources = new Map(this.#static);
|
|
2417
|
+
// Users' fields: the author profile and the groups attached to users.
|
|
2418
|
+
const userFields = this.#userFieldsResource();
|
|
2419
|
+
const sameFields = this.#resources.get(USER_FIELDS);
|
|
2420
|
+
resources.set(USER_FIELDS, sameFields && canonicalJson(sameFields) === canonicalJson(userFields) && sameKeyOrder(sameFields.fields, userFields.fields) ? sameFields : userFields);
|
|
2421
|
+
// Terms' fields: one resource for each taxonomy that has groups attached.
|
|
2422
|
+
for (const taxonomy of taxonomies.values()) {
|
|
2423
|
+
const termFields = this.#termFieldsResource(taxonomy);
|
|
2424
|
+
if (!termFields) continue;
|
|
2425
|
+
const previous = this.#resources.get(termFields.id);
|
|
2426
|
+
resources.set(termFields.id, previous && canonicalJson(previous) === canonicalJson(termFields) && sameKeyOrder(previous.fields, termFields.fields) ? previous : termFields);
|
|
2427
|
+
}
|
|
2309
2428
|
const effective = new Map<string, CollectionDefinition>();
|
|
2310
2429
|
for (const definition of collections.values()) {
|
|
2311
2430
|
const known = { ...definition, taxonomies: (definition.taxonomies ?? []).filter(name => taxonomies.has(name)) };
|
|
@@ -2733,7 +2852,9 @@ export class CmsHost {
|
|
|
2733
2852
|
/** What `$site` and `$user` read in an automation's templates: the site's public settings and the account that acted, when a user did. */
|
|
2734
2853
|
async #automationScopes(actor?: WriteActor): Promise<Omit<BindingScopes, 'entry'>> {
|
|
2735
2854
|
const settings = await this.settings.all().catch(() => null);
|
|
2736
|
-
|
|
2855
|
+
// The user who acted: a member of the site, or with the CMS's own accounts a network account that is none.
|
|
2856
|
+
const account = actor?.kind !== 'user' ? null
|
|
2857
|
+
: await this.users.get(actor.id).catch(() => null);
|
|
2737
2858
|
return { site: settings ? siteBindingScope(settings) : null, user: account ? { name: account.name, email: account.email } : null };
|
|
2738
2859
|
}
|
|
2739
2860
|
|
|
@@ -2760,9 +2881,16 @@ export class CmsHost {
|
|
|
2760
2881
|
}
|
|
2761
2882
|
|
|
2762
2883
|
#state(): Promise<Activation> {
|
|
2884
|
+
return sharedRead(() => this.#readState());
|
|
2885
|
+
}
|
|
2886
|
+
|
|
2887
|
+
#readState(): Promise<Activation> {
|
|
2763
2888
|
const now = this.#now();
|
|
2764
2889
|
if (!this.#activation || now - this.#activation.at > this.#activationTtl) {
|
|
2765
|
-
|
|
2890
|
+
// A policy that cannot be read fails the state, which is not kept: an open policy in its
|
|
2891
|
+
// place would show the network's hidden plugins and themes until the state expires.
|
|
2892
|
+
const policy = readPolicy(this.network);
|
|
2893
|
+
policy.catch(() => undefined);
|
|
2766
2894
|
const state = this.db.read([
|
|
2767
2895
|
{ rql: 'SELECT resource, declaration_hash FROM cms_schema_state ORDER BY resource LIMIT 1000' },
|
|
2768
2896
|
{ rql: "SELECT subject, permission FROM cms_grants WHERE subject LIKE 'plugin:%' ORDER BY subject, permission LIMIT 1000" },
|