@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cossackframework/cms",
3
- "version": "0.9.2",
3
+ "version": "0.9.4",
4
4
  "type": "module",
5
5
  "description": "Cossack CMS: resources, schema planning, repositories, auth and stores on RomeDB",
6
6
  "license": "MIT",
@@ -33,19 +33,20 @@
33
33
  "markdown-it": "15.0.3",
34
34
  "prosemirror-collab": "1.3.1",
35
35
  "uqr": "0.1.3",
36
- "@cossackframework/auth": "0.9.2",
37
- "@cossackframework/romedb": "0.9.2",
38
- "@cossackframework/core": "0.9.2",
39
- "@cossackframework/renderer": "0.9.2"
36
+ "@cossackframework/auth": "0.9.4",
37
+ "@cossackframework/database": "0.9.4",
38
+ "@cossackframework/core": "0.9.4",
39
+ "@cossackframework/renderer": "0.9.4",
40
+ "@cossackframework/romedb": "0.9.4"
40
41
  },
41
42
  "peerDependencies": {
42
43
  "@aws-sdk/client-s3": "^3.1156.0",
43
44
  "hono": "^4.13.18",
44
45
  "sharp": "^0.35.5",
45
46
  "vite": "*",
46
- "@cossackframework/framework": "0.9.2",
47
- "@cossackframework/node-adapter": "0.9.2",
48
- "@cossackframework/ui": "0.9.2"
47
+ "@cossackframework/framework": "0.9.4",
48
+ "@cossackframework/node-adapter": "0.9.4",
49
+ "@cossackframework/ui": "0.9.4"
49
50
  },
50
51
  "devDependencies": {
51
52
  "@aws-sdk/client-s3": "^3.1156.0",
@@ -58,8 +59,8 @@
58
59
  "simple-icons": "16.36.0",
59
60
  "vite": "^8.1.6",
60
61
  "vitest": "^4.1.12",
61
- "@cossackframework/framework": "0.9.2",
62
- "@cossackframework/node-adapter": "0.9.2"
62
+ "@cossackframework/framework": "0.9.4",
63
+ "@cossackframework/node-adapter": "0.9.4"
63
64
  },
64
65
  "exports": {
65
66
  ".": "./src/index.ts",
@@ -98,9 +99,44 @@
98
99
  ],
99
100
  "host": [
100
101
  "cms.config.ts",
101
- "stores.client.ts"
102
+ "stores.client.ts",
103
+ "orm/factory.ts",
104
+ "models/User.ts",
105
+ "models/Session.ts",
106
+ "models/Role.ts",
107
+ "models/UserRole.ts",
108
+ "models/OAuthAccount.ts",
109
+ "models/UserSecurity.ts",
110
+ "models/Passkey.ts",
111
+ "models/AuthChallenge.ts",
112
+ "models/AuthAttempt.ts",
113
+ "models/ApiToken.ts",
114
+ "models/Tenant.ts",
115
+ "models/TenantDomain.ts",
116
+ "models/TenantMember.ts",
117
+ "models/TenantHandoff.ts",
118
+ "models/TenantNetwork.ts",
119
+ "models/TenantSession.ts"
102
120
  ],
103
- "hostTemplate": "0.9.0"
121
+ "hostTemplate": "0.9.3",
122
+ "hostSteps": {
123
+ "0.9.3": [
124
+ "src/bootstrap/middlewares.ts: import { ormRequestMiddleware } from '../middlewares/orm' and list ormRequestMiddleware first, before ...cmsMiddlewares.",
125
+ "package.json scripts: \"migrate\": \"cossack migration up\" and \"schema:check\": \"cossack schema check\".",
126
+ "Accounts, sessions and roles are the dashboard's, in ORM models on the CMS's RomeDB database: orm.config.ts, src/orm/, src/models/, src/migrations/, src/seeders/ and src/middlewares/orm.ts. cossack upgrade writes those the project lacks; a folder the project already has is left as it is, so compare it with a project that cossack create --features cms makes.",
127
+ "The CMS's own account tables are gone, and nothing moves their rows: make the first account again at /auth/setup."
128
+ ]
129
+ },
130
+ "hostFiles": {
131
+ "0.9.3": [
132
+ "orm.config.ts",
133
+ "src/orm/",
134
+ "src/models/",
135
+ "src/migrations/",
136
+ "src/seeders/",
137
+ "src/middlewares/orm.ts"
138
+ ]
139
+ }
104
140
  },
105
141
  "peerDependenciesMeta": {
106
142
  "@aws-sdk/client-s3": {
@@ -5,7 +5,7 @@
5
5
  * {{ block core/button label="Buy {{ $.title }}" url="/cart" /}} a block without a body
6
6
  * {{ block core/button }}Price is {{ $.price }}{{ /block }} a body fills the type's `body` field
7
7
  * {{ block core/group }} …blocks and text… {{ /block }} a container's body is its children
8
- * {{ pattern hero /}} a synced pattern by slug
8
+ * {{ pattern hero /}} a synced pattern by ID or title slug
9
9
  * \{{ … }} written as is
10
10
  *
11
11
  * Only block types that declare `inline: true` can be referenced. The parser turns text into
@@ -30,7 +30,7 @@ export function hasBlockReference(value: unknown): value is string {
30
30
  return typeof value === 'string' && /(?<!\\)\{\{\s*(?:block|pattern|\/block)\b/.test(value);
31
31
  }
32
32
 
33
- /** The pattern a `{{ pattern … }}` names, kept as a `core/pattern` block whose `pattern` is the slug until the site resolves it. */
33
+ /** The pattern a `{{ pattern … }}` names, kept as a `core/pattern` block whose `pattern` is the name until the site resolves it. */
34
34
  export const PATTERN_REFERENCE = 'core/pattern';
35
35
 
36
36
  type Tag =
@@ -142,7 +142,7 @@ function parseTag(inner: string): Tag | string | null {
142
142
  if (typeof tokens === 'string') return tokens;
143
143
  const [first, ...others] = tokens;
144
144
  if (keyword === 'pattern') {
145
- if (!first || first.value !== undefined || others.length) return '{{ pattern … /}} names one pattern by its slug.';
145
+ if (!first || first.value !== undefined || others.length) return '{{ pattern … /}} names one pattern by its ID or the slug of its title.';
146
146
  return { kind: 'pattern', ref: first.name };
147
147
  }
148
148
  if (!first || first.value !== undefined || !NAME.test(first.name)) return `{{ block ${rest.trim()} }} names no block type, such as core/button.`;
@@ -200,7 +200,7 @@ export const RESERVED_FIELDS = Object.freeze([...CORE_FIELDS, ...FEATURE_FIELDS]
200
200
  const FEATURES = Object.freeze(['content', 'excerpt', 'featuredImage', 'revisions', 'password', 'members'] as const);
201
201
  /** A template an editor can choose for one entry: one of the active theme's `entry-*` templates. Empty for the default. */
202
202
  export const ENTRY_TEMPLATE = 'entry-[a-z][a-z0-9_-]{0,73}';
203
- const RESERVED = new Set(['media', 'users', 'roles', 'terms', 'settings', 'collections', 'taxonomies', 'blocks', 'plugins', 'schema', 'content', 'new']);
203
+ const RESERVED = new Set(['media', 'users', 'user_fields', 'roles', 'terms', 'settings', 'collections', 'taxonomies', 'blocks', 'plugins', 'schema', 'content', 'new']);
204
204
  const PATH = /^[a-z0-9]+(?:-[a-z0-9]+)*(?:\/[a-z0-9]+(?:-[a-z0-9]+)*)*$/;
205
205
  const ICON = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
206
206
 
@@ -211,6 +211,8 @@ export function collectionProblems(definition: CollectionDefinition): string[] {
211
211
  else if (RESERVED.has(definition.name)) problems.push(`${definition.name} is reserved.`);
212
212
  // Form submissions are stored as cms/form_<form id>.
213
213
  else if (definition.name.startsWith('form_')) problems.push('Names starting with form_ are reserved for form submissions.');
214
+ // Terms' field values are stored as cms/tf_<taxonomy>.
215
+ else if (definition.name.startsWith('tf_')) problems.push('Names starting with tf_ are reserved for the field values of terms.');
214
216
  for (const key of ['label', 'singular'] as const) {
215
217
  if (typeof definition?.[key] !== 'string' || !definition[key].trim() || definition[key].length > 60) problems.push(`The ${key === 'label' ? 'plural label' : 'singular label'} must be 1-60 characters.`);
216
218
  }
package/src/forms.ts CHANGED
@@ -101,8 +101,10 @@ export function recordTitle(record: RecordShape, titleField?: string): string {
101
101
 
102
102
  /** Same-origin check for form posts. Browsers send Sec-Fetch-Site and Origin on cross-site posts. */
103
103
  export function isSameOriginPost(request: Request): boolean {
104
- const site = request.headers.get('sec-fetch-site');
105
- if (site !== null && !['same-origin', 'same-site', 'none'].includes(site.toLowerCase())) return false;
104
+ // same-origin decides alone: under Referrer-Policy: no-referrer a same-origin post sends Origin: null.
105
+ const site = request.headers.get('sec-fetch-site')?.toLowerCase();
106
+ if (site === 'same-origin' || site === 'none') return true;
107
+ if (site !== undefined && site !== 'same-site') return false;
106
108
  const origin = request.headers.get('origin');
107
109
  if (origin === null) return true;
108
110
  try { return origin === new URL(request.url).origin; } catch { return false; }
package/src/hooks.ts CHANGED
@@ -411,6 +411,24 @@ export interface UserSignedInEvent {
411
411
  */
412
412
  export const userSignedIn = defineAction<UserSignedInEvent>('cms.user.signed-in', { version: 1, timeoutMs: 10_000 });
413
413
 
414
+ export interface SiteCreatedEvent {
415
+ /** Outbox ID, stable across repeated deliveries: use it as the idempotency key. */
416
+ readonly eventId: string;
417
+ readonly topic: 'site.created';
418
+ readonly at: number;
419
+ /** The new site, as the network's registry names it. */
420
+ readonly site: { readonly id: string; readonly name: string; readonly host: string | null };
421
+ /** Its first administrator. */
422
+ readonly admin: UserRef;
423
+ }
424
+
425
+ /**
426
+ * A site of the network was just created, run from the new site's outbox before anyone uses it:
427
+ * the plugins active there (enabled for the network, or granted to new sites) prepare it, such as
428
+ * a first record or their settings. Its roles from plugin manifests exist already. Deliveries can repeat.
429
+ */
430
+ export const siteCreated = defineAction<SiteCreatedEvent>('cms.site.created', { version: 1, timeoutMs: 30_000 });
431
+
414
432
  /** A `cms.user.before-register` result the host can use: the original email, existing roles, bounded text. */
415
433
  export function registrationDraftOf(value: unknown, original: RegistrationDraft, roles: ReadonlySet<string>): RegistrationDraft {
416
434
  const draft = value && typeof value === 'object' ? value as Partial<RegistrationDraft> : {};
@@ -487,7 +505,7 @@ export function mailMessageOf(value: unknown, original: MailMessage, kind: MailK
487
505
 
488
506
  export const EXTENSION_POINTS = Object.freeze([beforeWrite, afterCommit, cachePurge, paymentEvent, formValidate, formBeforeSubmit, formPrefill, formConfirmation, formNotification, formSubmitted,
489
507
  termBeforeSave, commentBeforeSave, menuBeforeSave, entryActions, entryColumns, bulkActions, dashboardNotices, dashboardTaskbar, siteMarkdown, siteEntryView,
490
- userBeforeRegister, userRegistered, userSignedIn,
508
+ userBeforeRegister, userRegistered, userSignedIn, siteCreated,
491
509
  mailBeforeSend]);
492
510
 
493
511
  const TONES = new Set(['info', 'success', 'warning', 'error']);
package/src/index.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // Client-safe CMS declarations: resources, fields, permissions, extension points and records.
2
2
  export { defineResource, resolveResource, resourceProblems, storageName, permissionFor, declarationHash, canonicalJson, SYSTEM_FIELDS, RESOURCE_NAME, OWNER_NAME, ResourceDeclarationError,
3
- type ResourceDeclaration, type Resource, type ResourceAccess, type ResourceAction, type AccessRule, type IndexDeclaration, type MigrationStep } from './resource';
3
+ type ResourceDeclaration, type Resource, type ResourceAccess, type ResourceAction, type AccessRule, type MemberRule, memberRules, memberRuleProblems, type IndexDeclaration, type MigrationStep } from './resource';
4
4
  export { field, fieldProblems, validateValue, storageType, storageCheck, slugify, FIELD_NAME, SLUG_PATTERN, TAXONOMY_NAME, ROW_ID, ROW_LIMITS, ITEM_LIMITS, MULTIPLE_KINDS, FIELD_MEDIA_KINDS, CHOICE_SOURCES, type FieldMediaKind, type ChoiceSource, type FieldDeclaration, type FieldKind, type ListItemKind } from './fields';
5
5
  export {
6
6
  FIELD_BLOCK_TYPES, FIELD_BLOCKS, FIELD_GROUP_ID, FIELD_GROUP_LIMITS, fieldBlockFields, fieldBlockDeclaration, rowsSearchable, metaProblems, SYSTEM_META, flattenGroupFields, fieldGroupDeclarations, fieldBlockKindOf, fieldBlockOf, layoutOf, sameTarget, targetOrder, groupsForTarget, withTarget, fieldGroupProblems,
@@ -17,7 +17,7 @@ export { beforeWrite, afterCommit, cachePurge, pluginJob, paymentEvent, formVali
17
17
  type TermDraft, type TermWriteInput, type CommentDraft, type CommentWriteInput, type MenuWriteInput, type EntryAction, type BuiltinEntryAction, type EntryColumn, type EntryListInput,
18
18
  type DashboardNotice, type TaskbarItem } from './hooks';
19
19
  export { siteEntryView, ENTRY_VIEW_REFUSED_BLOCKS, type EntryViewParts } from './hooks';
20
- export { userBeforeRegister, userRegistered, userSignedIn, registrationDraftOf, type RegistrationDraft, type UserRef, type UserRegisteredEvent, type UserSignedInEvent } from './hooks';
20
+ export { userBeforeRegister, userRegistered, userSignedIn, siteCreated, registrationDraftOf, type RegistrationDraft, type UserRef, type UserRegisteredEvent, type UserSignedInEvent, type SiteCreatedEvent } from './hooks';
21
21
  export { mailBeforeSend, mailMessageOf, mailRecipientsLocked, MAIL_KINDS, MAIL_LIMITS, type MailKind, type MailMessage, type MailSendInput } from './hooks';
22
22
  export { mailHtml, mailBodyHtml, MAIL_ACCENT, type MailLayout } from './mail';
23
23
  export type { RecordShape, RecordPage, RevisionShape, FieldFilter, ListFilter, ListOptions } from './records';
@@ -44,10 +44,10 @@ export { CORE_BLOCKS, BLOCK_CATEGORIES, BLOCK_ID, BLOCK_NAME, BLOCK_LIMITS, CUST
44
44
  export { hasBinding, bindingPaths, bindingRefs, bindingValue, bindingText, bindingProblem, usesUserBinding, resolveBindings, resolveBlockBindings, withBinding, siteBindingScope, BINDING_SCOPES, type BindingScope, type BindingScopes } from './bindings';
45
45
  export { parseBlockText, hasBlockReference, textBlocks, PATTERN_REFERENCE, type TextPart, type ParsedText } from './block-references';
46
46
  export { formInput, formValue, recordTitle, isSameOriginPost, type FormInput, type SubmittedForm } from './forms';
47
- export { manifestProblems, validateManifest, RESERVED_PLUGIN_NAMES, RESERVED_PLUGIN_PREFIX, requestedGrants, commandInput, isPluginPoint, pointOwner, providedPoints, ManifestError, HOST_SLOTS, CAPABILITIES, UNRESTRICTED_GRANT, type Capability, type UserAction, type PluginSchedule, type CmsPluginManifest, type PluginAuthor, type ProvidedPoint, type PluginCommand, type CommandOption, type SlotLink, type HostSlot } from './manifest';
47
+ export { manifestProblems, validateManifest, RESERVED_PLUGIN_NAMES, RESERVED_PLUGIN_PREFIX, requestedGrants, commandInput, isPluginPoint, pointOwner, providedPoints, ManifestError, HOST_SLOTS, CAPABILITIES, UNRESTRICTED_GRANT, type Capability, type UserAction, type PluginSchedule, type CmsPluginManifest, type PluginAuthor, type ProvidedPoint, type PluginCommand, type PluginRole, PLUGIN_ROLE_PERMISSIONS, type CommandOption, type SlotLink, type HostSlot } from './manifest';
48
48
  export { MEDIA_TYPES, AVATAR_TYPES, ARCHIVE_TYPES, SVG_TYPE, MEDIA_FILTERS, MEDIA_FILTER_EXCLUDES, mediaKind, mediaUrl, formatBytes, matchesSignature, imageHasAlpha, imageSize, declaredType, sanitizeSvg, EXTENSION_TYPES, fileExtension, fileType, type MediaKind } from './media';
49
49
  export { taxonomyProblems, type TaxonomyDeclaration, type TermShape } from './taxonomy';
50
- export { general, interfaceGroup, DASHBOARD_PALETTES, DASHBOARD_ACCENTS, type DashboardPalette, type DashboardAccent, media, appearance, dashboard, writing, reading, discussion, seo, crawlers, indexnow, cache, languages, DATE_FORMATS, TIME_FORMATS, TITLE_SEPARATORS, formatSiteDate, validTimeZone, type SettingsGroup, type SettingsSection, type SettingDeclaration, type SettingSource, type SettingControl, type SiteSettings } from './settings';
50
+ export { general, settingRoles, twoFactorRequired, interfaceGroup, DASHBOARD_PALETTES, DASHBOARD_ACCENTS, type DashboardPalette, type DashboardAccent, media, appearance, dashboard, writing, reading, discussion, seo, crawlers, indexnow, cache, languages, DATE_FORMATS, TIME_FORMATS, TITLE_SEPARATORS, formatSiteDate, validTimeZone, type SettingsGroup, type SettingsSection, type SettingDeclaration, type SettingSource, type SettingControl, type SiteSettings } from './settings';
51
51
  export { validateSettingValue, settingControlProblems } from './settings-controls';
52
52
  export { pluginSettingsProblems, pluginSettingsGroupId, PLUGIN_SETTINGS_LIMITS, type PluginSettingsDeclaration, type PluginSettingDeclaration } from './plugin-settings';
53
53
  export { parseSettingsDocument, checkSettingsDocument, stringifySettingsDocument, settingsJsonSchema, isPortableSetting, SETTINGS_DOCUMENT_MAX_BYTES, SETTINGS_DOCUMENT_MAX_FIELDS, type SettingsValue, type SettingsDocument } from './settings-document';
@@ -122,7 +122,7 @@ export function createIsolateRuntime(plugin: Readonly<Record<string, unknown>>,
122
122
  commands.set(command, handler);
123
123
  },
124
124
  },
125
- cms: { resource },
125
+ cms: { resource, batch: (writes: unknown, context: unknown) => forward('cms.batch', writes, withoutSignal(context)) },
126
126
  settings: {
127
127
  get: (field: string) => forward('settings.get', field),
128
128
  all: () => forward('settings.all'),
package/src/isolation.ts CHANGED
@@ -44,6 +44,7 @@ export interface IsolateCall {
44
44
  export const ISOLATE_MEMBERS = [
45
45
  'settings.get', 'settings.all',
46
46
  'resource.get', 'resource.list', 'resource.count', 'resource.search', 'resource.create', 'resource.update', 'resource.delete',
47
+ 'cms.batch',
47
48
  'fetch',
48
49
  'files.upload', 'files.get', 'files.list', 'files.open', 'files.update', 'files.delete',
49
50
  'mail.send',
package/src/manifest.ts CHANGED
@@ -11,7 +11,7 @@ import { FIELD_BLOCKS, fieldGroupProblems, type FieldGroup } from './field-group
11
11
  import { defineAction, defineFilter, type ExtensionPoint } from '@cossackframework/core/hooks';
12
12
  import { cronProblem } from './cron';
13
13
  import { EXTENSION_POINTS } from './hooks';
14
- import { OWNER_NAME, resourceProblems, type ResourceAction, type ResourceDeclaration } from './resource';
14
+ import { memberRuleProblems, OWNER_NAME, resourceProblems, type ResourceAction, type ResourceDeclaration } from './resource';
15
15
  import { themeProblems, type ThemeManifest } from './theme';
16
16
  import { pluginSettingsProblems, type PluginSettingsDeclaration } from './plugin-settings';
17
17
 
@@ -64,6 +64,16 @@ export interface SlotLink {
64
64
  readonly icon?: string;
65
65
  }
66
66
 
67
+ /** A role a plugin's manifest defines, such as `{ id: 'acme-manager', name: 'Manager', permissions: ['cms:dashboard', 'acme:approve'] }`. */
68
+ export interface PluginRole {
69
+ readonly id: string;
70
+ readonly name: string;
71
+ readonly permissions: readonly string[];
72
+ }
73
+
74
+ /** CMS permissions a plugin's role may hold beside the plugin's own. */
75
+ export const PLUGIN_ROLE_PERMISSIONS: ReadonlySet<string> = new Set(['cms:dashboard', 'cms:upload']);
76
+
67
77
  /** A plugin's maker as its manifest names them. */
68
78
  export interface PluginAuthor {
69
79
  readonly name: string;
@@ -154,6 +164,13 @@ export interface CmsPluginManifest {
154
164
  readonly slots?: { readonly [slot: string]: readonly SlotLink[] };
155
165
  };
156
166
  readonly commands?: readonly PluginCommand[];
167
+ /**
168
+ * Roles the host defines on each site where the plugin is active: when it is granted, and on
169
+ * every site, new ones included, while the network enables it. IDs start with `<plugin>-`; a
170
+ * role holds `cms:dashboard`, `cms:upload` and the plugin's own permissions. A role the site
171
+ * has is left as the site changed it.
172
+ */
173
+ readonly roles?: readonly PluginRole[];
157
174
  /** Jobs the clock queues while the plugin is active; needs `permissions.jobs`. */
158
175
  readonly schedules?: readonly PluginSchedule[];
159
176
  /** `false` keeps the plugin in the application where it could run isolated: what `cossack add plugin --in-app` renders. */
@@ -198,7 +215,7 @@ export interface ManifestPattern {
198
215
  }
199
216
  const PATTERN_SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
200
217
 
201
- const KNOWN_FIELDS = new Set(['schemaVersion', 'name', 'version', 'description', 'author', 'compatibility', 'dependencies', 'resources', 'collections', 'blocks', 'fieldGroups', 'patterns', 'editor', 'hooks', 'permissions', 'ui', 'provides', 'commands', 'schedules', 'settings', 'theme', 'logo', 'cover', 'translations', 'package', 'source', 'isolation']);
218
+ const KNOWN_FIELDS = new Set(['schemaVersion', 'name', 'version', 'description', 'author', 'compatibility', 'dependencies', 'resources', 'collections', 'blocks', 'fieldGroups', 'patterns', 'editor', 'hooks', 'permissions', 'ui', 'provides', 'commands', 'roles', 'schedules', 'settings', 'theme', 'logo', 'cover', 'translations', 'package', 'source', 'isolation']);
202
219
  const COLLECTION_NAME = /^[a-z][a-zA-Z0-9_]{0,40}$/;
203
220
  const ARTWORK = /^assets\/[A-Za-z0-9][A-Za-z0-9._-]{0,80}\.(?:png|jpe?g|webp|gif|avif|svg)$/;
204
221
  const HOST = /^(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$|^localhost$/;
@@ -268,6 +285,14 @@ export function manifestProblems(manifest: unknown): string[] {
268
285
  if (resourceNames.has(resource.name)) problems.push(`resource ${resource.name} is declared twice.`);
269
286
  resourceNames.add(resource.name);
270
287
  }
288
+ // Membership rules name the plugin's own resources, checked once all are known.
289
+ if (Array.isArray(value.resources) && typeof name === 'string') {
290
+ const declared = (id: string) => (value.resources as ResourceDeclaration[]).find(resource => resource && typeof resource === 'object' && `${name}/${resource.name}` === id);
291
+ for (const resource of value.resources) {
292
+ if (!resource || typeof resource !== 'object' || !resource.fields || typeof resource.fields !== 'object') continue;
293
+ for (const problem of memberRuleProblems(resource, name, declared)) problems.push(`resource ${resource.name}: ${problem}`);
294
+ }
295
+ }
271
296
  const collectionNames = new Set<string>();
272
297
  for (const [index, collection] of (Array.isArray(value.collections) ? value.collections : value.collections === undefined ? [] : [null]).entries()) {
273
298
  if (!collection || typeof collection !== 'object') { problems.push(`collections[${index}] must be a collection definition.`); continue; }
@@ -400,6 +425,22 @@ export function manifestProblems(manifest: unknown): string[] {
400
425
  for (const key of ['logo', 'cover'] as const) {
401
426
  if (value[key] !== undefined && (typeof value[key] !== 'string' || !ARTWORK.test(value[key]))) problems.push(`${key} must name a PNG, JPEG, WebP, GIF, AVIF or SVG file in assets/, such as assets/${key}.png.`);
402
427
  }
428
+ const roles = Array.isArray(value.roles) ? value.roles : value.roles === undefined ? [] : [null];
429
+ if (roles.length > 10) problems.push('roles: at most 10.');
430
+ const roleIds = new Set<string>();
431
+ for (const [index, role] of roles.entries()) {
432
+ if (!role || typeof role !== 'object') { problems.push(`roles[${index}] must be a role.`); continue; }
433
+ const id = String(role.id);
434
+ if (typeof role.id !== 'string' || !role.id.startsWith(`${name}-`) || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(role.id) || role.id.length > 80) problems.push(`roles[${index}]: IDs start with ${name}- and are lowercase letters, digits and hyphens.`);
435
+ else if (roleIds.has(id)) problems.push(`roles: ${id} is declared twice.`);
436
+ roleIds.add(id);
437
+ if (typeof role.name !== 'string' || !role.name.trim() || role.name.length > 80) problems.push(`roles: ${id} needs a name of at most 80 characters.`);
438
+ if (!Array.isArray(role.permissions) || role.permissions.length > 50) { problems.push(`roles: ${id} lists at most 50 permissions.`); continue; }
439
+ for (const permission of role.permissions) {
440
+ const own = typeof permission === 'string' && (permission.startsWith(`${name}:`) || permission.startsWith(`${name}/`)) && /^[a-z0-9-]+[:/][a-z0-9:/._*-]{1,127}$/.test(permission);
441
+ if (!own && !PLUGIN_ROLE_PERMISSIONS.has(permission)) problems.push(`roles: ${id} may hold ${[...PLUGIN_ROLE_PERMISSIONS].join(', ')} and ${name}'s own permissions, not ${String(permission)}.`);
442
+ }
443
+ }
403
444
  const commandNames = new Set<string>();
404
445
  for (const command of value.commands ?? []) {
405
446
  if (typeof command?.name !== 'string' || !/^[a-z][a-z0-9-]{0,40}$/.test(command.name) || commandNames.has(command.name)) problems.push(`commands: ${String(command?.name)} needs a unique lowercase name.`);
@@ -1,4 +1,4 @@
1
- import type { AccessRule } from './resource';
1
+ import type { AccessRule, MemberRule } from './resource';
2
2
 
3
3
  /** Who is acting. Built per request from the session; never from client input. */
4
4
  export type Principal =
@@ -98,15 +98,18 @@ export function holdsAll(principal: Principal, permissions: readonly string[]):
98
98
  return permissions.every(permission => hasPermission(principal, permission));
99
99
  }
100
100
 
101
- /** Records an action is limited to: the principal's own, or those matching any of the conditions. */
101
+ /** Records an action is limited to: the principal's own, those matching any of the conditions, or those a membership links the user to. */
102
102
  export interface RecordScope {
103
103
  readonly owner: boolean;
104
104
  readonly where: readonly { readonly [field: string]: string | number | boolean }[];
105
+ /** Membership rules the host turns into query conditions; only users have memberships. */
106
+ readonly members: readonly MemberRule[];
105
107
  }
106
108
 
107
109
  /**
108
- * Evaluate a rule. `owner` means the action is allowed only on records the principal created,
109
- * which the host enforces with a query condition, not by trusting input.
110
+ * Evaluate a rule. `owner` means the action is allowed only on some records (the principal's
111
+ * own, those matching a `where`, or those a membership reaches), which the host enforces with a
112
+ * query condition, not by trusting input.
110
113
  */
111
114
  export function evaluateRule(rule: AccessRule, principal: Principal): 'allow' | 'owner' | 'deny' {
112
115
  const scope = ruleScope(rule, principal);
@@ -119,19 +122,22 @@ export function ruleScope(rule: AccessRule, principal: Principal): 'allow' | 'de
119
122
  if (rule === 'public') return 'allow';
120
123
  if (rule === 'none') return 'deny';
121
124
  if (rule === 'authenticated') return principal.kind === 'user' ? 'allow' : 'deny';
122
- if (rule === 'owner') return principal.kind === 'user' ? { owner: true, where: [] } : 'deny';
125
+ if (rule === 'owner') return principal.kind === 'user' ? { owner: true, where: [], members: [] } : 'deny';
123
126
  if ('permission' in rule) return hasPermission(principal, rule.permission) ? 'allow' : 'deny';
124
- if ('where' in rule) return { owner: false, where: [rule.where] };
127
+ if ('where' in rule) return { owner: false, where: [rule.where], members: [] };
128
+ if ('memberOf' in rule) return principal.kind === 'user' ? { owner: false, where: [], members: [rule.memberOf] } : 'deny';
125
129
  let owner = false;
126
130
  const where: RecordScope['where'][number][] = [];
131
+ const members: MemberRule[] = [];
127
132
  for (const entry of rule.any) {
128
133
  const outcome = ruleScope(entry, principal);
129
134
  if (outcome === 'allow') return 'allow';
130
135
  if (outcome === 'deny') continue;
131
136
  owner ||= outcome.owner;
132
137
  where.push(...outcome.where);
138
+ members.push(...outcome.members);
133
139
  }
134
- return owner || where.length ? { owner, where } : 'deny';
140
+ return owner || where.length || members.length ? { owner, where, members } : 'deny';
135
141
  }
136
142
 
137
143
  export function principalId(principal: Principal): string {
package/src/resource.ts CHANGED
@@ -8,11 +8,35 @@ import { field, fieldProblems, validateValue, type FieldDeclaration } from './fi
8
8
  * - `owner`: the user who created the record (requires `ownership`).
9
9
  * - `{ permission }`: users whose roles grant the permission.
10
10
  * - `{ where }`: anyone, on records whose fields equal these values, such as published posts.
11
- * - `{ any: [...] }`: the first rule that allows wins; owner and where rules combine.
11
+ * - `{ memberOf }`: signed-in users, on records that a row of a membership resource links
12
+ * them to, such as the branches a member is assigned to (`MemberRule`).
13
+ * - `{ any: [...] }`: the first rule that allows wins; owner, where and memberOf rules combine.
12
14
  * - `none`: nobody, except the system principal.
13
15
  */
14
16
  export type AccessRule = 'public' | 'authenticated' | 'owner' | 'none' | { readonly permission: string }
15
- | { readonly where: { readonly [field: string]: string | number | boolean } } | { readonly any: readonly AccessRule[] };
17
+ | { readonly where: { readonly [field: string]: string | number | boolean } } | { readonly memberOf: MemberRule } | { readonly any: readonly AccessRule[] };
18
+
19
+ /**
20
+ * Records a user reaches through a membership resource of the same owner: a resource with a
21
+ * row per member and thing, such as `acme/user_branches` with `user` and `branch`. The record
22
+ * is in scope when a row of `resource` has the user's ID in `user` and, in `field`, the record
23
+ * itself (`field` is a reference to this resource) or the value of the record's `match` field.
24
+ */
25
+ export interface MemberRule {
26
+ /** The membership resource, `<owner>/<name>`, owned by the same plugin or the application. */
27
+ readonly resource: string;
28
+ /** Its string field that holds the member's user ID. */
29
+ readonly user: string;
30
+ /** Its field that names what the member belongs to. */
31
+ readonly field: string;
32
+ /** This record's field that must equal `field`; omitted, the record itself. */
33
+ readonly match?: string;
34
+ }
35
+
36
+ const MEMBER_RULE_KEYS = new Set(['resource', 'user', 'field', 'match']);
37
+ const RESOURCE_ID = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/[a-z][a-z0-9_]{0,40}$/;
38
+ /** Field kinds a membership can compare: one value of a kind stored as itself. */
39
+ const MEMBER_KINDS = new Set(['string', 'enum', 'integer', 'reference']);
16
40
 
17
41
  export type ResourceAction = 'read' | 'create' | 'update' | 'delete';
18
42
 
@@ -62,6 +86,12 @@ export interface ResourceDeclaration {
62
86
  */
63
87
  readonly schemaless?: boolean;
64
88
  readonly migrations?: readonly MigrationStep[];
89
+ /**
90
+ * The host's own storage, such as the field values of users: the schema planner keeps its
91
+ * indexes like any resource's, but it has no repository, no permissions of its own and is
92
+ * not listed with the resources people browse.
93
+ */
94
+ readonly internal?: boolean;
65
95
  /**
66
96
  * The field groups' blocks that lay the fields out, for the conditions on them: a field a
67
97
  * condition hides is not required and is cleared on write. Set by the host for collections.
@@ -187,10 +217,63 @@ function ruleProblems(at: string, rule: AccessRule, ownership: boolean, fields:
187
217
  return error ? [`${at}: where ${name} ${error}`] : [];
188
218
  });
189
219
  }
220
+ if (typeof rule === 'object' && rule && 'memberOf' in rule) {
221
+ const member = rule.memberOf as MemberRule | null;
222
+ if (!member || typeof member !== 'object' || Object.keys(member).some(key => !MEMBER_RULE_KEYS.has(key))) return [`${at}: memberOf names resource, user, field and an optional match.`];
223
+ const problems: string[] = [];
224
+ if (typeof member.resource !== 'string' || !RESOURCE_ID.test(member.resource)) problems.push(`${at}: memberOf.resource must be a resource ID, such as acme/user_branches.`);
225
+ for (const key of ['user', 'field'] as const) if (typeof member[key] !== 'string' || !/^[a-z][a-zA-Z0-9]{0,62}$/.test(member[key])) problems.push(`${at}: memberOf.${key} must be a field name.`);
226
+ if (member.match !== undefined) {
227
+ const declared = typeof member.match === 'string' ? fields[member.match] : undefined;
228
+ if (!declared || declared.multiple || !MEMBER_KINDS.has(declared.kind)) problems.push(`${at}: memberOf.match names ${String(member.match)}, which is not a declared single string, enum, integer or reference field.`);
229
+ }
230
+ return problems;
231
+ }
190
232
  if (typeof rule === 'object' && rule && 'any' in rule && Array.isArray(rule.any) && rule.any.length) return rule.any.flatMap(entry => ruleProblems(at, entry, ownership, fields, depth + 1));
191
233
  return [`${at}: unknown rule.`];
192
234
  }
193
235
 
236
+ /** The `memberOf` rules of a rule, through `any`. */
237
+ export function memberRules(rule: AccessRule, depth = 0): MemberRule[] {
238
+ if (typeof rule !== 'object' || !rule || depth > 4) return [];
239
+ if ('memberOf' in rule) return [rule.memberOf];
240
+ if ('any' in rule && Array.isArray(rule.any)) return rule.any.flatMap(entry => memberRules(entry, depth + 1));
241
+ return [];
242
+ }
243
+
244
+ /**
245
+ * Problems of the `memberOf` rules of `resource` (owned by `owner`) against the declarations
246
+ * they name: the membership resource must belong to the same owner, hold the user's ID in a
247
+ * single string field, and compare a value of the same kind as the record or its `match` field.
248
+ */
249
+ export function memberRuleProblems(resource: ResourceDeclaration, owner: string, declared: (id: string) => ResourceDeclaration | undefined): string[] {
250
+ const problems: string[] = [];
251
+ const id = `${owner}/${resource.name}`;
252
+ for (const [action, rule] of Object.entries(resource.access ?? {})) {
253
+ for (const member of memberRules(rule as AccessRule)) {
254
+ // A rule of another shape is reported by `resourceProblems`.
255
+ if (!member || typeof member !== 'object' || typeof member.resource !== 'string' || typeof member.user !== 'string' || typeof member.field !== 'string') continue;
256
+ const at = `access.${action}: memberOf ${member.resource}`;
257
+ if (!member.resource.startsWith(`${owner}/`)) { problems.push(`${at} must be a resource of ${owner}.`); continue; }
258
+ const membership = declared(member.resource);
259
+ if (!membership) { problems.push(`${at} is not a declared resource.`); continue; }
260
+ const user = membership.fields[member.user];
261
+ if (!user || user.kind !== 'string' || user.multiple) problems.push(`${at}: ${member.user} is not a single string field of it.`);
262
+ const target = membership.fields[member.field];
263
+ if (!target || target.multiple || !MEMBER_KINDS.has(target.kind)) { problems.push(`${at}: ${member.field} is not a single string, enum, integer or reference field of it.`); continue; }
264
+ if (member.match === undefined) {
265
+ if (target.kind !== 'reference' || target.target !== id) problems.push(`${at}: ${member.field} must be a reference to ${id}, or name this record's field in match.`);
266
+ continue;
267
+ }
268
+ const own = resource.fields[member.match];
269
+ if (!own) continue;
270
+ const kind = (declaration: FieldDeclaration) => declaration.kind === 'enum' ? 'string' : declaration.kind;
271
+ if (kind(own) !== kind(target) || (own.kind === 'reference' && own.target !== target.target)) problems.push(`${at}: ${member.field} and ${member.match} must hold the same kind of value.`);
272
+ }
273
+ }
274
+ return problems;
275
+ }
276
+
194
277
  /** Collection name for a resource: `r__<owner>__<name>`, with hyphens as underscores. Injective for valid names. */
195
278
  export function storageName(owner: string, name: string): string {
196
279
  return `r__${owner.replaceAll('-', '_')}__${name}`;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Counted attempts: how often something was tried for a key within a window, for the CMS's
3
+ * own limits (a form sent again at once, comments posted too quickly, suggestions, site
4
+ * registrations, recovery). Sign-in's limits are the application's, with its accounts.
5
+ */
6
+ import type { RomeDB } from '@cossackframework/romedb';
7
+
8
+ const WRITE = { kind: 'cms.attempts', retryConflicts: 5 } as const;
9
+ const COUNT = { kind: 'cms.attempts', retryConflicts: 20 } as const;
10
+
11
+ function attemptKey(kind: string, key: string): string {
12
+ return `attempt:${kind}:${key.replace(/[^\x21-\x7e]/g, '-').slice(0, 120)}`;
13
+ }
14
+
15
+ export class CmsAttempts {
16
+ readonly #db: RomeDB;
17
+ readonly #now: () => number;
18
+
19
+ constructor(db: RomeDB, options: { now?: () => number } = {}) {
20
+ this.#db = db;
21
+ this.#now = options.now ?? Date.now;
22
+ }
23
+
24
+ /**
25
+ * Count an attempt of `kind` (such as `form`) for a key within a window; false past `max`.
26
+ * A refused attempt keeps the gate shut until the window ends. The database does the
27
+ * counting in one write (an ended window starts again, then a conditional increment), so
28
+ * attempts sent at once are each counted once and no more than `max` are let through.
29
+ */
30
+ async attempt(kind: string, key: string, max: number, windowMs: number): Promise<boolean> {
31
+ const id = attemptKey(kind, key);
32
+ const now = this.#now();
33
+ try {
34
+ const result = await this.#db.write([
35
+ { rql: 'DELETE FROM cms_attempts WHERE key = $key AND until <= $now', params: { $key: id, $now: now } },
36
+ { rql: 'INSERT INTO cms_attempts (key, count, until) VALUES ($key, 0, $until) ON CONFLICT (key) DO NOTHING', params: { $key: id, $until: now + windowMs } },
37
+ { rql: 'UPDATE cms_attempts SET count = count + 1 WHERE key = $key AND count < $max', params: { $key: id, $max: max } },
38
+ ], COUNT);
39
+ return result.results[2]!.affected === 1n;
40
+ } catch (error) {
41
+ // A key under a burst of attempts can keep conflicting past the retries: refuse this
42
+ // attempt, as the limit would, rather than fail the request.
43
+ if ((error as { code?: string }).code === 'RDB_WRITE_CONFLICT') return false;
44
+ throw error;
45
+ }
46
+ }
47
+
48
+ /** Give back an attempt `attempt()` counted, for one that did not go ahead after all. */
49
+ async release(kind: string, key: string): Promise<void> {
50
+ try { await this.#db.write([{ rql: 'UPDATE cms_attempts SET count = count - 1 WHERE key = $key AND count > 0', params: { $key: attemptKey(kind, key) } }], COUNT); }
51
+ catch (error) {
52
+ // Under a burst on the same key the attempt stays counted: the limit errs shut.
53
+ if ((error as { code?: string }).code !== 'RDB_WRITE_CONFLICT') throw error;
54
+ }
55
+ }
56
+
57
+ /** Forget the counters whose window ended, some at a time. */
58
+ async purge(): Promise<void> {
59
+ const now = this.#now();
60
+ const expired = await this.#db.read([{ rql: 'SELECT 1 FROM cms_attempts WHERE until <= $now LIMIT 1', params: { $now: now } }]);
61
+ if (!expired.results[0]!.rows.length) return;
62
+ await this.#db.write([{ rql: 'DELETE FROM cms_attempts WHERE key IN (SELECT key FROM cms_attempts WHERE until <= $now LIMIT 500)', params: { $now: now } }], WRITE);
63
+ }
64
+ }
@@ -28,7 +28,7 @@ export interface AutomationsOptions {
28
28
  /** The principal of an automation's author as of now, or null when they can no longer act (deleted, disabled). */
29
29
  readonly principal?: (userId: string) => Promise<Principal | null>;
30
30
  /** An entry as the principal may read it: without the fields they may not. */
31
- readonly redact?: (collection: string, record: Record<string, unknown>, principal: Principal) => Record<string, unknown>;
31
+ readonly redact?: (collection: string, record: Record<string, unknown>, principal: Principal) => Promise<Record<string, unknown>>;
32
32
  }
33
33
 
34
34
  export class CmsAutomations {
@@ -146,7 +146,7 @@ export class CmsAutomations {
146
146
  catch (error) { throw new AutomationSkipped((error as Error).message); }
147
147
  const { record, collection } = vars;
148
148
  if (!record || typeof record !== 'object' || typeof collection !== 'string' || !this.#options.redact) return vars;
149
- return { ...vars, record: this.#options.redact(collection, record as Record<string, unknown>, principal) };
149
+ return { ...vars, record: await this.#options.redact(collection, record as Record<string, unknown>, principal) };
150
150
  }
151
151
 
152
152
  async #perform(automation: Automation, vars: Record<string, unknown>, scopes: Omit<BindingScopes, 'entry'>): Promise<void> {