@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
@@ -15,16 +15,17 @@ import { blockId, blockMedia, blocksPlain, flattenBlocks, htmlBlocksChanged, tex
15
15
  import { fieldVisibility, indexedRowField, rowIndexPath, rowsPlain, rowsSearchable, rowUniqueProblem, withRowIds } from '../field-groups';
16
16
  import { normalizeRichText, richTextBlocks, richTextMedia, richTextPlain, withRichTextBlocks, type RichTextDoc } from '../richtext';
17
17
  import { searchedAsText, searchTextPath } from './schema';
18
+ import { publicValue, storedJson, storedValue } from './field-values';
18
19
  import { isSearchSyntaxError, searchQuery } from '../search';
19
20
  import { afterCommit, beforeWrite, type Draft, type ResourceEvent, type WriteActor } from '../hooks';
20
21
  import { sharedOp, type SharedFieldsEvent } from './shared-fields';
21
22
  import { readByIds, readPaged } from './budget';
22
23
  import { isLockedRecord, lockedView } from './locked';
23
- import { ANONYMOUS, evaluateRule, hasPermission, PERMISSIONS, principalId, ruleScope, type Principal, type RecordScope } from '../permissions';
24
+ import { ANONYMOUS, evaluateRule, hasPermission, PERMISSIONS, principalId, ruleScope, systemPrincipal, type Principal, type RecordScope } from '../permissions';
24
25
  import type { FieldFilter, ListFilter, ListOptions, RecordPage, RecordShape, RevisionShape } from '../records';
25
26
 
26
27
  export type { FieldFilter, ListFilter, ListOptions };
27
- import type { AccessRule, Resource, ResourceAction } from '../resource';
28
+ import type { AccessRule, MemberRule, Resource, ResourceAction } from '../resource';
28
29
  import type { CmsHost } from './host';
29
30
  import { uuidv7 } from '@cossackframework/core';
30
31
 
@@ -40,6 +41,70 @@ export interface OperationContext {
40
41
  export const JOIN_GROUP: unique symbol = Symbol('cms.joinGroup');
41
42
 
42
43
  const KEY = /^[A-Za-z0-9_-]{1,80}$/;
44
+ /** Guards read filters over every field: they are written by code, and answer only whether they hold. */
45
+ const SYSTEM = systemPrincipal('guard');
46
+
47
+ /** One write of a batch (`CmsHost.batch`), on a resource by its ID. */
48
+ export type BatchWrite =
49
+ | { readonly create: string; readonly input: { readonly [field: string]: unknown }; readonly id?: string }
50
+ | { readonly update: string; readonly id: string; readonly patch: { readonly [field: string]: unknown }; readonly expectedRevision: number }
51
+ | { readonly delete: string; readonly id: string; readonly expectedRevision: number };
52
+
53
+ /**
54
+ * A condition a batch commits under: how many records of `resource` match `where` (and `id`),
55
+ * counted in the same request as the writes, before any of them. `{ max: 4 }` holds while at
56
+ * most four match; `{ min: 1 }`, the default, while one exists.
57
+ */
58
+ export interface BatchGuard {
59
+ /** Names the guard in the refusal, such as `capacity`. */
60
+ readonly name: string;
61
+ readonly resource: string;
62
+ readonly where?: ListFilter['where'];
63
+ /** One record by ID. */
64
+ readonly id?: string;
65
+ readonly count?: { readonly min?: number; readonly max?: number };
66
+ }
67
+
68
+ /** A write ready to send, from `ResourceRepository.prepare`. */
69
+ export interface PreparedWrite {
70
+ readonly resource: string;
71
+ /** The record's ID. */
72
+ readonly id: string;
73
+ /** The write's operation ID: its audit row and outbox event. */
74
+ readonly op: string;
75
+ readonly action: 'create' | 'update' | 'delete';
76
+ /** Conditions the write needs when it runs, whether alone or in a batch: a membership. */
77
+ readonly assertions: readonly Statement[];
78
+ /** In a batch only: the record is still as it was read (its revision and the access rules). Alone, the write's own statement checks it. */
79
+ readonly precondition?: Statement;
80
+ readonly statements: readonly Statement[];
81
+ /** The statement whose affected count says whether the record was written. */
82
+ readonly statement: number;
83
+ /** The record as the principal reads it after the write; null for a delete. */
84
+ readonly record: RecordShape | null;
85
+ }
86
+
87
+ /** Whether a rolled-back write failed one of its `cms_assertions` conditions. */
88
+ export function isAssertionFailure(error: ClientError): boolean {
89
+ return error.code === 'RDB_CONSTRAINT' && /CHECK constraint failed: held = 1/.test(error.message);
90
+ }
91
+
92
+ /**
93
+ * The statements that check conditions in a write request: one `cms_assertions` row per
94
+ * condition before the writes (held = 1, or the CHECK fails and the request rolls back), and
95
+ * their removal after, so none outlives the request.
96
+ */
97
+ export function assertionStatements(conditions: readonly Statement[], op: string): { insert: Statement[]; remove: Statement[] } {
98
+ if (!conditions.length) return { insert: [], remove: [] };
99
+ const ids = conditions.map((_, index) => `${op}:${index}`);
100
+ return {
101
+ insert: conditions.map((condition, index) => ({
102
+ rql: `INSERT INTO cms_assertions (id, held) SELECT $assertion, CASE WHEN ${condition.rql} THEN 1 ELSE 0 END WHERE 1 = 1`,
103
+ params: { ...condition.params, $assertion: ids[index]! },
104
+ })),
105
+ remove: [{ rql: `DELETE FROM cms_assertions WHERE id IN (${ids.map((_, index) => `$a${index}`).join(', ')})`, params: Object.fromEntries(ids.map((id, index) => [`$a${index}`, id])) }],
106
+ };
107
+ }
43
108
  /** Fields a restored revision does not change: where and whether the entry is published, and its translations. */
44
109
  const KEPT_ON_RESTORE = new Set(['status', 'publishedAt', 'parent', 'menuOrder', 'locale', 'translationGroup', 'commentsOpen']);
45
110
 
@@ -164,7 +229,7 @@ export class ResourceRepository {
164
229
  // Hits are checked again in the outer query; fetch more when some may be filtered out.
165
230
  const params: { [key: string]: Value } = { $query: text, $hits: Math.min(filtered ? (offset + limit) * 4 : offset + limit, 10_000) };
166
231
  let source = `search::text('${this.resource.storage}__text', $query, $hits)`;
167
- if (access !== 'allow' && access.owner && !access.where.length) {
232
+ if (access !== 'allow' && access.owner && !access.where.length && !access.members.length) {
168
233
  const owned = await this.#host.db.read([{ rql: `SELECT id FROM ${this.resource.storage} WHERE "_owner" = $owner LIMIT 4097`, params: { $owner: principalId(context.principal) } }], this.#readOptions(context));
169
234
  if (owned.results[0]!.rows.length > 4096) throw new CmsError('CMS_LIMIT', 'Search over more than 4096 owned records needs a separate collection per owner.');
170
235
  params.$allowed = owned.results[0]!.rows.map(row => row[0]!);
@@ -206,7 +271,7 @@ export class ResourceRepository {
206
271
  const record = await this.get(id, context);
207
272
  if (!record) throw new CmsError('CMS_NOT_FOUND', 'Record not found.');
208
273
  const since = record.createdAt;
209
- if (this.canUpdate(record, context.principal)) return { editor: true, since };
274
+ if (await this.canUpdate(record, context)) return { editor: true, since };
210
275
  if (!hasPermission(context.principal, `${this.resource.id}:read`) || isLockedRecord(record)) {
211
276
  throw new CmsError('CMS_FORBIDDEN', 'Only editors read this record\'s revisions.');
212
277
  }
@@ -251,19 +316,56 @@ export class ResourceRepository {
251
316
  return this.update(id, patch, context);
252
317
  }
253
318
 
254
- /** Whether the principal may update the record: its rule allows, or the record is in the rule's scope. */
255
- /** The record as this principal may read it outside the site's gate: whole for those who may update it, else the reader's view (`lockedView`). */
256
- readerView(record: RecordShape, principal: Principal): RecordShape {
257
- return this.canUpdate(record, principal) ? record : lockedView(record, this.resource.fields);
319
+ /** The records as this principal may read them outside the site's gate: whole for those who may update them, else the reader's view (`lockedView`). */
320
+ async readerViews(records: readonly RecordShape[], context: OperationContext): Promise<RecordShape[]> {
321
+ const editable = await this.editable(records, context);
322
+ return records.map(record => editable.has(record.id) ? record : lockedView(record, this.resource.fields));
323
+ }
324
+
325
+ /** Whether the principal may update the stored record (`editable`). */
326
+ async canUpdate(record: RecordShape, context: OperationContext): Promise<boolean> {
327
+ return (await this.editable([record], context)).has(record.id);
328
+ }
329
+
330
+ /** Whether the principal may read the stored record (`readable`). */
331
+ async canRead(record: RecordShape, context: OperationContext): Promise<boolean> {
332
+ return (await this.readable([record], context)).has(record.id);
333
+ }
334
+
335
+ /**
336
+ * The IDs of the records the principal may update: the update rule allows, or the record is
337
+ * in its scope. Owner and `where` rules are judged on the records; membership rules on the
338
+ * stored records and memberships, in one read for all records the others leave out. For IDs
339
+ * alone, `updatable` reads every one.
340
+ */
341
+ editable(records: readonly RecordShape[], context: OperationContext): Promise<Set<string>> {
342
+ return this.#allowed(this.resource.access.update, records, context);
258
343
  }
259
344
 
260
- canUpdate(record: RecordShape, principal: Principal): boolean {
261
- return this.#inScope(this.resource.access.update, record, principal);
345
+ /** The IDs of the records the principal may read, by the read rule (as `editable`). */
346
+ readable(records: readonly RecordShape[], context: OperationContext): Promise<Set<string>> {
347
+ return this.#allowed(this.resource.access.read, records, context);
262
348
  }
263
349
 
264
- /** Whether the principal may read this record: the read rule, evaluated on the record itself. */
265
- canRead(record: RecordShape, principal: Principal): boolean {
266
- return this.#inScope(this.resource.access.read, record, principal);
350
+ async #allowed(rule: AccessRule, records: readonly RecordShape[], context: OperationContext): Promise<Set<string>> {
351
+ const { principal } = context;
352
+ const scope = ruleScope(rule, principal);
353
+ if (scope === 'allow') return new Set(records.map(record => record.id));
354
+ if (scope === 'deny') return new Set();
355
+ const allowed = new Set(records.filter(record => this.#onRecord(scope, record, principal)).map(record => record.id));
356
+ if (!scope.members.length || principal.kind !== 'user') return allowed;
357
+ const rest = [...new Set(records.map(record => record.id).filter(id => !allowed.has(id) && typeof id === 'string' && KEY.test(id)))];
358
+ if (!rest.length) return allowed;
359
+ // The same condition lists and writes use, on the stored records: what the memberships reach now.
360
+ const members: Access = { owner: false, where: [], members: scope.members };
361
+ const rows = await readByIds(this.#host.db, rest, slice => {
362
+ const keys: { [key: string]: Value } = {};
363
+ const list = slice.map((id, index) => { keys[`$k${index}`] = id; return `type::record('${this.resource.storage}', $k${index})`; }).join(', ');
364
+ const { rql, params } = this.#conditions(members, principal, [`id IN (${list})`], keys);
365
+ return { rql: `SELECT record::id(id) FROM ${this.resource.storage} WHERE ${rql} LIMIT ${slice.length}`, params };
366
+ }, this.#readOptions(context));
367
+ for (const row of rows) allowed.add(String(row[0]));
368
+ return allowed;
267
369
  }
268
370
 
269
371
  /**
@@ -289,9 +391,14 @@ export class ResourceRepository {
289
391
  return co !== undefined && Array.isArray(record[co]) && (record[co] as unknown[]).includes(user);
290
392
  }
291
393
 
292
- #inScope(rule: AccessRule, record: RecordShape, principal: Principal): boolean {
293
- const scope = ruleScope(rule, principal);
294
- if (scope === 'allow' || scope === 'deny') return scope === 'allow';
394
+ /** Whether a visitor who is not signed in reads the record: no memberships, so the record alone decides. */
395
+ #readByAnyone(record: RecordShape): boolean {
396
+ const scope = ruleScope(this.resource.access.read, ANONYMOUS);
397
+ return scope === 'allow' || (scope !== 'deny' && this.#onRecord(scope, record, ANONYMOUS));
398
+ }
399
+
400
+ /** Owner and `where` rules, judged on the record. Membership rules need the database (`#allowed`). */
401
+ #onRecord(scope: RecordScope, record: RecordShape, principal: Principal): boolean {
295
402
  if (scope.owner && principal.kind === 'user' && this.#owns(record, principal.id)) return true;
296
403
  return scope.where.some(rule => Object.entries(rule).every(([name, value]) => record[name] === value));
297
404
  }
@@ -315,32 +422,81 @@ export class ResourceRepository {
315
422
  const result = await this.#host.db.read([{
316
423
  rql: `SELECT id, ${levels.map((path, index) => `${path} AS l${index}`).join(', ')} FROM ${this.resource.storage} WHERE id IN (${list}) LIMIT ${wanted.length}`, params,
317
424
  }], this.#readOptions(context));
425
+ const found: [string, RecordShape[]][] = [];
318
426
  for (const row of result.results[0]!.rows) {
319
427
  const chain: RecordShape[] = [];
320
428
  for (let index = 1; index < row.length; index++) {
321
429
  const document = row[index];
322
430
  if (!document || typeof document !== 'object' || document instanceof RecordId || !(document as Document).id) break;
323
- const record = this.#public(document as Document, context.principal);
324
- if (!this.canRead(record, context.principal)) break;
325
- chain.push(record);
431
+ chain.push(this.#public(document as Document, context.principal));
326
432
  }
327
- chains.set(String((row[0] as RecordId).key), chain);
433
+ found.push([String((row[0] as RecordId).key), chain]);
434
+ }
435
+ const readable = await this.readable(found.flatMap(([, chain]) => chain), context);
436
+ for (const [id, chain] of found) {
437
+ const end = chain.findIndex(record => !readable.has(record.id));
438
+ chains.set(id, end < 0 ? chain : chain.slice(0, end));
328
439
  }
329
440
  return chains;
330
441
  }
331
442
 
332
443
  async create(input: { readonly [field: string]: unknown }, context: OperationContext & { readonly id?: string }): Promise<RecordShape> {
444
+ const prepared = await this.prepare({ create: this.#id, input, ...(context.id !== undefined ? { id: context.id } : {}) }, context);
445
+ await this.#send(prepared, context);
446
+ return prepared.record!;
447
+ }
448
+
449
+ /**
450
+ * A write ready to send, alone or in a batch (`CmsHost.batch`): its statements, the
451
+ * conditions it needs at the moment it runs, and its record as the principal reads it.
452
+ * Everything a write checks before sending (access, validation, write filters, references)
453
+ * runs here.
454
+ */
455
+ async prepare(write: BatchWrite, context: OperationContext): Promise<PreparedWrite> {
456
+ if ('create' in write) return this.#prepareCreate(write.input, { ...context, ...(write.id !== undefined ? { id: write.id } : {}) });
457
+ if ('update' in write) return this.#prepareUpdate(write.id, write.patch, { ...context, expectedRevision: write.expectedRevision });
458
+ if ('delete' in write) return this.#prepareDelete(write.id, { ...context, expectedRevision: write.expectedRevision });
459
+ throw new CmsError('CMS_VALIDATION', 'A write creates, updates or deletes a record.');
460
+ }
461
+
462
+ /**
463
+ * A condition of the batch: how many records match a filter, read in the same request as the
464
+ * writes. Counted over every record, whoever writes: guards are written by code, and they
465
+ * answer only whether they hold.
466
+ */
467
+ guardCondition(guard: Omit<BatchGuard, 'resource'>): Statement {
468
+ const params: { [key: string]: Value } = {};
469
+ const conditions = this.#filters({ ...(guard.where ? { where: guard.where } : {}) }, SYSTEM, params);
470
+ if (guard.id !== undefined) {
471
+ checkKey(guard.id);
472
+ params.$guardKey = guard.id;
473
+ conditions.push(`id = type::record('${this.resource.storage}', $guardKey)`);
474
+ }
475
+ const { min, max } = guard.count ?? { min: 1 };
476
+ if ((min !== undefined && (!Number.isSafeInteger(min) || min < 0)) || (max !== undefined && (!Number.isSafeInteger(max) || max < 0)) || (min === undefined && max === undefined)) {
477
+ throw new CmsError('CMS_VALIDATION', `Guard ${guard.name} counts with a whole min, max or both.`);
478
+ }
479
+ const counted = `(SELECT count(*) FROM ${this.resource.storage}${conditions.length ? ` WHERE ${conditions.map(condition => `(${condition})`).join(' AND ')}` : ''})`;
480
+ const bounds = [...(min !== undefined ? [`${counted} >= ${min}`] : []), ...(max !== undefined ? [`${counted} <= ${max}`] : [])];
481
+ return bound(bounds.join(' AND '), params);
482
+ }
483
+
484
+ async #prepareCreate(input: { readonly [field: string]: unknown }, context: OperationContext & { readonly id?: string }): Promise<PreparedWrite> {
333
485
  const access = await this.#authorize('create', context.principal);
334
- // Only an owner rule lets a user create; a record condition cannot be checked before the record exists.
335
- if (access !== 'allow' && !(access.owner && context.principal.kind === 'user')) {
336
- throw new CmsError(context.principal.kind === 'user' ? 'CMS_FORBIDDEN' : 'CMS_UNAUTHENTICATED', `Not allowed to create ${this.resource.id}.`);
486
+ const user = context.principal.kind === 'user';
487
+ // A record condition cannot be checked before the record exists: an owner rule lets a user
488
+ // create, and so does a membership rule on a field the new record sets (checked as it is written).
489
+ const members = access === 'allow' || !user ? [] : access.members.filter(rule => rule.match !== undefined);
490
+ if (access !== 'allow' && !(access.owner && user) && !members.length) {
491
+ throw new CmsError(user ? 'CMS_FORBIDDEN' : 'CMS_UNAUTHENTICATED', `Not allowed to create ${this.resource.id}.`);
337
492
  }
338
493
  const key = context.id ?? uuidv7();
339
494
  checkKey(key);
340
495
  const draft = await this.#prepareDraft('create', null, input, null, context);
496
+ const assertions = access !== 'allow' && !(access.owner && user) ? [this.#memberAssertion(members, draft, context.principal, true)!] : [];
341
497
  const now = this.#host.now();
342
498
  const op = uuidv7();
343
- const owner = this.resource.ownership && context.principal.kind === 'user' ? context.principal.id : null;
499
+ const owner = this.resource.ownership && user ? (context.principal as { id: string }).id : null;
344
500
  const record = this.#shape(key, 1, now, now, owner, draft);
345
501
  const document: { [field: string]: Value } = { id: new RecordId(this.resource.storage, key), _rev: 1, _op: op, _createdAt: now, _updatedAt: now, _owner: owner };
346
502
  for (const [name, value] of Object.entries(draft)) if (value !== undefined) document[name] = this.#store(name, this.resource.fields[name]!, value);
@@ -348,10 +504,7 @@ export class ResourceRepository {
348
504
  const statements: Statement[] = [{ rql: `INSERT INTO ${this.resource.storage} DOCUMENT $document`, params: { $document: document } }];
349
505
  const guard = `EXISTS (SELECT 1 FROM ${this.resource.storage} WHERE id = type::record('${this.resource.storage}', $key) AND "_op" = $op)`;
350
506
  statements.push(...this.#sideEffects(guard, op, key, 1, 'create', record, actor(context.principal), now));
351
- await this.#write(statements, op, context, error => {
352
- if (error.code === 'RDB_CONSTRAINT') throw new CmsError('CMS_CONFLICT', 'A record with the same unique value already exists.', { cause: error });
353
- });
354
- return this.#redact(record, context.principal);
507
+ return { resource: this.resource.id, id: key, op, action: 'create', assertions, statements, statement: 0, record: this.#redact(record, context.principal) };
355
508
  }
356
509
 
357
510
  /**
@@ -384,6 +537,13 @@ export class ResourceRepository {
384
537
 
385
538
  /** Edit with an expected revision. A stale revision or lost access is a conflict, and nothing is written. */
386
539
  async update(id: string, patch: { readonly [field: string]: unknown }, context: OperationContext & { readonly expectedRevision: number }): Promise<RecordShape> {
540
+ const prepared = await this.#prepareUpdate(id, patch, context);
541
+ const result = await this.#send(prepared, context);
542
+ if (result.affected !== 1) throw new CmsError('CMS_CONFLICT', 'The record changed since it was read. Reload and try again.');
543
+ return prepared.record!;
544
+ }
545
+
546
+ async #prepareUpdate(id: string, patch: { readonly [field: string]: unknown }, context: OperationContext & { readonly expectedRevision: number }): Promise<PreparedWrite> {
387
547
  const access = await this.#authorize('update', context.principal);
388
548
  checkKey(id);
389
549
  if (!Number.isSafeInteger(context.expectedRevision) || context.expectedRevision < 1) throw new CmsError('CMS_VALIDATION', 'expectedRevision must be a positive integer.');
@@ -425,9 +585,11 @@ export class ResourceRepository {
425
585
  // A published entry whose URL changes keeps answering at the old one. The audit row,
426
586
  // written only when the change commits, guards these relational statements.
427
587
  statements.push(...await this.#host.redirectStatements(this.resource, previous, record, { rql: 'EXISTS (SELECT 1 FROM cms_audit WHERE id = $rOp)', params: { $rOp: op } }, principalId(context.principal)));
428
- const result = await this.#write(statements, op, context);
429
- if (result.affected !== 1) throw new CmsError('CMS_CONFLICT', 'The record changed since it was read. Reload and try again.');
430
- return this.#redact(record, context.principal);
588
+ // In a batch the record must still be as read when the batch runs; a membership field set to
589
+ // another value must name one the user is a member of.
590
+ const moved = access === 'allow' ? null : this.#memberAssertion(access.members, draft, context.principal, false);
591
+ const current = bound(`EXISTS (SELECT 1 FROM ${this.resource.storage} WHERE ${condition.rql})`, condition.params);
592
+ return { resource: this.resource.id, id, op, action: 'update', assertions: moved ? [moved] : [], precondition: current, statements, statement: 0, record: this.#redact(record, context.principal) };
431
593
  }
432
594
 
433
595
  /**
@@ -529,7 +691,7 @@ export class ResourceRepository {
529
691
  await flush();
530
692
  }
531
693
 
532
- /** The IDs among these the principal may update. */
694
+ /** The IDs among these the principal may update, read for every ID (`editable` judges records it holds). */
533
695
  async updatable(ids: readonly string[], context: OperationContext): Promise<Set<string>> {
534
696
  let access: Access;
535
697
  try { access = await this.#authorize('update', context.principal); } catch (error) { if (error instanceof CmsError) return new Set(); throw error; }
@@ -543,6 +705,12 @@ export class ResourceRepository {
543
705
  }
544
706
 
545
707
  async delete(id: string, context: OperationContext & { readonly expectedRevision: number }): Promise<void> {
708
+ const prepared = await this.#prepareDelete(id, context);
709
+ const deleted = await this.#send(prepared, context);
710
+ if (deleted.affected !== 1) throw new CmsError('CMS_CONFLICT', 'The record changed or was deleted since it was read.');
711
+ }
712
+
713
+ async #prepareDelete(id: string, context: OperationContext & { readonly expectedRevision: number }): Promise<PreparedWrite> {
546
714
  const access = await this.#authorize('delete', context.principal);
547
715
  checkKey(id);
548
716
  if (!Number.isSafeInteger(context.expectedRevision) || context.expectedRevision < 1) throw new CmsError('CMS_VALIDATION', 'expectedRevision must be a positive integer.');
@@ -554,8 +722,37 @@ export class ResourceRepository {
554
722
  const previous = this.resource.fields.status ? await this.#current(id, access, context) : null;
555
723
  const statements = this.#sideEffects(guard, op, id, context.expectedRevision, 'delete', null, actor(context.principal), now, condition.params, previous);
556
724
  statements.push(bound(`DELETE FROM ${this.resource.storage} WHERE ${condition.rql}`, condition.params));
557
- const deleted = await this.#write(statements, op, context, undefined, statements.length - 1);
558
- if (deleted.affected !== 1) throw new CmsError('CMS_CONFLICT', 'The record changed or was deleted since it was read.');
725
+ return { resource: this.resource.id, id, op, action: 'delete', assertions: [], precondition: bound(guard, condition.params), statements, statement: statements.length - 1, record: null };
726
+ }
727
+
728
+ /**
729
+ * The condition that the record sets a membership field (`MemberRule.match`) to a value the
730
+ * user is a member of, by any of the rules: always on create, on update when it changes.
731
+ * Null when an update leaves those fields alone.
732
+ */
733
+ #memberAssertion(members: readonly MemberRule[], draft: Draft, principal: Principal, creating: boolean): Statement | null {
734
+ const rules = members.filter(rule => rule.match !== undefined && (creating || draft[rule.match] !== undefined));
735
+ if (!rules.length) return null;
736
+ const params: { [key: string]: Value } = { $member: principalId(principal) };
737
+ const parts = rules.flatMap((rule, index) => {
738
+ const value = draft[rule.match!];
739
+ if (value === null || value === undefined) return [];
740
+ params[`$mv${index}`] = this.#store(rule.match!, this.resource.fields[rule.match!]!, value);
741
+ return [`EXISTS (SELECT 1 FROM ${this.#host.resourceById(rule.resource).storage} WHERE ${quote(rule.user)} = $member AND ${quote(rule.field)} = $mv${index})`];
742
+ });
743
+ return bound(parts.length ? parts.join(' OR ') : '1 = 0', params);
744
+ }
745
+
746
+ /**
747
+ * Send one prepared write: its conditions as rows of `cms_assertions`, which roll the whole
748
+ * request back when one does not hold, then its statements.
749
+ */
750
+ async #send(prepared: PreparedWrite, context: OperationContext): Promise<{ affected: number; sequence: number }> {
751
+ const assertions = assertionStatements(prepared.assertions, prepared.op);
752
+ return this.#write([...assertions.insert, ...prepared.statements, ...assertions.remove], prepared.op, context, error => {
753
+ if (assertions.insert.length && isAssertionFailure(error)) throw new CmsError('CMS_FORBIDDEN', `Not allowed to ${prepared.action} ${this.resource.id} there: you are not a member.`, { cause: error });
754
+ if (prepared.action === 'create' && error.code === 'RDB_CONSTRAINT') throw new CmsError('CMS_CONFLICT', 'A record with the same unique value already exists.', { cause: error });
755
+ }, assertions.insert.length + prepared.statement);
559
756
  }
560
757
 
561
758
  async #authorize(action: ResourceAction, principal: Principal): Promise<Access> {
@@ -588,6 +785,14 @@ export class ResourceRepository {
588
785
  });
589
786
  scope.push(parts.length > 1 ? `(${parts.join(' AND ')})` : parts[0]!);
590
787
  });
788
+ // Records a row of the membership resource links the user to: the record itself, or its `match` field's value.
789
+ if (access.members.length && principal.kind === 'user') {
790
+ params.$member = principalId(principal);
791
+ for (const rule of access.members) {
792
+ const storage = this.#host.resourceById(rule.resource).storage;
793
+ scope.push(`${prefix}${rule.match ? quote(rule.match) : 'id'} IN (SELECT ${quote(rule.field)} FROM ${storage} WHERE ${quote(rule.user)} = $member)`);
794
+ }
795
+ }
591
796
  conditions = [...conditions, scope.length ? scope.join(' OR ') : '1 = 0'];
592
797
  }
593
798
  return { rql: conditions.map(condition => conditions.length > 1 ? `(${condition})` : condition).join(' AND '), params };
@@ -926,7 +1131,7 @@ export class ResourceRepository {
926
1131
  // A deleted record's revisions, drafts, notes and preview links go in an outbox job
927
1132
  // (`entryDeleted` in the host), a page at a time: an entry saved a thousand times still deletes.
928
1133
  // The site's search index, guarded by the audit row above.
929
- statements.push(...this.#host.siteSearch.statements(this.resource, key, op, record && this.canRead(record, ANONYMOUS) ? record : null));
1134
+ statements.push(...this.#host.siteSearch.statements(this.resource, key, op, record && this.#readByAnyone(record) ? record : null));
930
1135
  const event: ResourceEvent = {
931
1136
  eventId: op, topic: action === 'create' ? 'resource.created' : action === 'update' ? 'resource.updated' : 'resource.deleted',
932
1137
  // Webhooks, plugins and automations get the reader's view: a locked entry's password and content stay here.
@@ -963,18 +1168,8 @@ export class ResourceRepository {
963
1168
  return { ...(context.signal ? { signal: context.signal } : {}), workLimits: this.#host.readLimits };
964
1169
  }
965
1170
 
966
- #store(name: string, declaration: FieldDeclaration, value: unknown): Value {
967
- if (value === null) return null;
968
- // A multiple field stores its items as the kind stores one.
969
- if (declaration.multiple) return (value as unknown[]).map(item => this.#store(name, { ...declaration, multiple: false }, item));
970
- switch (declaration.kind) {
971
- case 'bigint': return BigInt(value as string | bigint);
972
- case 'number': return new Float64(value as number);
973
- case 'reference': return new RecordId(this.#host.resourceById(declaration.target!).storage, value as string);
974
- case 'vector': return Vector.float32(value as number[]);
975
- case 'json': case 'blocks': case 'richtext': case 'rows': return storedJson(value);
976
- default: return value as Value;
977
- }
1171
+ #store(_name: string, declaration: FieldDeclaration, value: unknown): Value {
1172
+ return storedValue(declaration, value, id => this.#host.resourceById(id).storage);
978
1173
  }
979
1174
 
980
1175
  /** Plain text of the draft's searchable rich text, blocks, rows and multiple fields, at their search paths. */
@@ -1035,44 +1230,8 @@ export class ResourceRepository {
1035
1230
 
1036
1231
  type Document = { [field: string]: Value };
1037
1232
 
1038
- function publicValue(declaration: FieldDeclaration, value: Value): unknown {
1039
- if (value === null) return null;
1040
- if (declaration.multiple) return Array.isArray(value) ? value.map(item => publicValue({ ...declaration, multiple: false }, item)) : [];
1041
- switch (declaration.kind) {
1042
- case 'integer': case 'datetime': return Number(value as bigint);
1043
- case 'bigint': return String(value);
1044
- case 'number': return value instanceof Float64 ? value.value : Number(value as bigint);
1045
- case 'reference': return value instanceof RecordId ? String(value.key) : null;
1046
- case 'json': case 'blocks': case 'richtext': case 'rows': return toJson(value);
1047
- case 'vector': {
1048
- const bytes = (value as Vector).bytes;
1049
- return [...new Float32Array(bytes.buffer, bytes.byteOffset, Math.floor(bytes.byteLength / 4))];
1050
- }
1051
- default: return value;
1052
- }
1053
- }
1054
-
1055
- /** Plain JSON for storage: fractional numbers become explicit floats, integers stay int64. */
1056
- function storedJson(value: unknown): Value {
1057
- if (typeof value === 'number') return Number.isInteger(value) ? value : new Float64(value);
1058
- if (Array.isArray(value)) return value.map(storedJson);
1059
- if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, storedJson(entry)]));
1060
- return value as Value;
1061
- }
1062
-
1063
- function toJson(value: Value): unknown {
1064
- if (typeof value === 'bigint') return Number(value);
1065
- if (value instanceof Float64) return value.value;
1066
- if (value instanceof RecordId) return `${value.table}:${String(value.key)}`;
1067
- if (Array.isArray(value)) return value.map(toJson);
1068
- if (value && typeof value === 'object' && !(value instanceof Uint8Array) && !(value instanceof Vector)) {
1069
- return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, toJson(entry)]));
1070
- }
1071
- return value;
1072
- }
1073
-
1074
1233
  /** Media IDs in a group field's media subfields. */
1075
- function groupMedia(declaration: FieldDeclaration, value: { readonly [key: string]: unknown }): string[] {
1234
+ export function groupMedia(declaration: FieldDeclaration, value: { readonly [key: string]: unknown }): string[] {
1076
1235
  return Object.entries(declaration.fields ?? {}).filter(([, nested]) => nested.media).flatMap(([key]) => {
1077
1236
  const entry = value[key];
1078
1237
  return typeof entry === 'string' && entry ? [entry] : Array.isArray(entry) ? entry.filter((item): item is string => typeof item === 'string') : [];
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Reads that requests share through a per-isolate cache: settings, the site a host names, the
3
+ * activation state, definitions.
4
+ *
5
+ * On Workers a request's database calls end with it (the CMS passes the request's signal to
6
+ * its database; see `requestSignal` in `@cossackframework/romedb`): when its visitor leaves or
7
+ * it fails, a read it started ends with `RDB_CANCELLED`, and so does every request that waits
8
+ * on the same cached read. Those requests did not end, so they read again for themselves.
9
+ */
10
+ import { ClientError } from '@cossackframework/romedb';
11
+
12
+ /** A database call that ended because its signal aborted or its deadline passed. */
13
+ export function cancelled(error: unknown): boolean {
14
+ return error instanceof ClientError && error.code === 'RDB_CANCELLED';
15
+ }
16
+
17
+ /**
18
+ * Run a cached read; when it ended with the request that started it, run it once more. The
19
+ * cache must forget a read that failed (a `.catch` it attaches when it starts the read), so the
20
+ * second run starts a new read under this request's own signal.
21
+ */
22
+ export async function sharedRead<T>(read: () => Promise<T>): Promise<T> {
23
+ try {
24
+ return await read();
25
+ } catch (error) {
26
+ if (!cancelled(error)) throw error;
27
+ return read();
28
+ }
29
+ }
30
+
31
+ /** The table a read names does not exist: the site is not set up yet. */
32
+ export function missingTable(error: unknown, table: RegExp): boolean {
33
+ return error instanceof ClientError && table.test(error.message) && /no such table|not found|does not exist/i.test(error.message);
34
+ }
@@ -4,7 +4,7 @@
4
4
  * binary values come back exactly with `decodeValue`. Media files are not included: `cms_files`
5
5
  * rows name their storage keys.
6
6
  */
7
- import { ClientError, encodeValue, type DatabaseFile, type RecordId, type RomeDB, type Statement, type Value } from '@cossackframework/romedb';
7
+ import { ClientError, encodeValue, isClientFull, type DatabaseFile, type RecordId, type RomeDB, type Statement, type Value } from '@cossackframework/romedb';
8
8
  import { HOST_TABLES } from './host-schema';
9
9
 
10
10
  /**
@@ -13,19 +13,21 @@ import { HOST_TABLES } from './host-schema';
13
13
  * tables, which hold accounts and the site registry on the main site.
14
14
  */
15
15
  export const EXPORT_SKIPPED_TABLES: ReadonlySet<string> = new Set([
16
- 'cms_auth_sessions', 'cms_sessions', 'cms_session_values', 'cms_session_sites', 'cms_oauth_states', 'cms_password_resets', 'cms_auth_challenges',
17
- 'cms_user_security', 'cms_passkeys', 'cms_api_tokens', 'cms_preview_tokens', 'cms_handoffs', 'cms_cache', 'cms_attempts', 'cms_schedules',
18
- 'cms_accounts', 'cms_sites', 'cms_site_domains', 'cms_memberships', 'cms_network',
16
+ 'cms_preview_tokens', 'cms_cache', 'cms_attempts', 'cms_schedules', 'cms_network',
19
17
  // The search index is built from the entries; an import rebuilds it.
20
18
  'cms_search',
21
19
  // Resized copies are made again on request; an imported row could name any stored object.
22
20
  'cms_file_variants',
23
21
  // Each database counts its own schema changes.
24
22
  'cms_schema_generations',
23
+ // The application's account tables (the dashboard package's, on the ORM) besides users and roles:
24
+ // credentials and sign-in state, the network's sites and members, the cache, and the ORM's own record of migrations.
25
+ 'sessions', 'user_security', 'passkeys', 'api_tokens', 'auth_challenges', 'auth_attempts', 'oauth_accounts',
26
+ 'tenants', 'tenant_domains', 'tenant_members', 'tenant_handoffs', 'tenant_network', 'tenant_sessions', 'cache_items', '_cossack_migrations',
25
27
  ]);
26
28
 
27
- /** Columns exported as null: webhook signing secrets. */
28
- export const EXPORT_REDACTED_COLUMNS: Readonly<Record<string, readonly string[]>> = Object.freeze({ cms_webhooks: ['secret'] });
29
+ /** Columns exported as null: webhook signing secrets, and the password hashes of the application's accounts. */
30
+ export const EXPORT_REDACTED_COLUMNS: Readonly<Record<string, readonly string[]>> = Object.freeze({ cms_webhooks: ['secret'], users: ['password_hash'] });
29
31
 
30
32
  /**
31
33
  * Tables a `.romedb` file leaves empty: sign-in state (sessions are keyed by their tokens, so a
@@ -37,12 +39,17 @@ export const EXPORT_REDACTED_COLUMNS: Readonly<Record<string, readonly string[]>
37
39
  * set up an authenticator app and application passwords again.
38
40
  */
39
41
  export const FILE_EXPORT_EMPTIED_TABLES: readonly string[] = [
40
- 'cms_user_security', 'cms_api_tokens',
41
- 'cms_auth_sessions', 'cms_sessions', 'cms_session_values', 'cms_session_sites', 'cms_oauth_states', 'cms_password_resets', 'cms_auth_challenges',
42
- 'cms_preview_tokens', 'cms_handoffs', 'cms_cache', 'cms_attempts', 'cms_outbox', 'cms_webhooks', 'cms_webhook_deliveries', 'cossack_jobs', 'cms_schedules',
42
+ 'cms_preview_tokens', 'cms_cache', 'cms_attempts', 'cms_outbox', 'cms_webhooks', 'cms_webhook_deliveries', 'cossack_jobs', 'cms_schedules',
43
43
  'cms_file_variants',
44
44
  ];
45
45
 
46
+ /**
47
+ * The same for the application's account tables, which the dashboard package keeps through the
48
+ * ORM: sessions (keyed by their tokens), second factors, application passwords, sign-in
49
+ * challenges and counters, one-time codes, and the cache. Accounts, roles and passkeys stay.
50
+ */
51
+ export const ACCOUNT_SECRET_TABLES: readonly string[] = ['sessions', 'user_security', 'api_tokens', 'auth_challenges', 'auth_attempts', 'tenant_handoffs', 'tenant_sessions', 'cache_items'];
52
+
46
53
  /** RomeDB's longest wait for a copy to start arriving. On Cloud a job builds it first. */
47
54
  const FILE_EXPORT_TIMEOUT = 120_000;
48
55
 
@@ -53,8 +60,11 @@ const FILE_EXPORT_TIMEOUT = 120_000;
53
60
  */
54
61
  export async function siteFile(db: RomeDB, options: { signal?: AbortSignal } = {}): Promise<DatabaseFile> {
55
62
  const signal = options.signal ? { signal: options.signal } : {};
56
- // Every site's database has every host table, so each named table exists.
57
- return db.exportFile({ ...signal, timeoutMs: FILE_EXPORT_TIMEOUT, emptyTables: [...FILE_EXPORT_EMPTIED_TABLES] });
63
+ // Every site's database has every host table. The application's account tables (the
64
+ // dashboard package's, on the ORM) are there once it applied its migrations.
65
+ const info = await db.read([{ rql: 'INFO FOR DB' }], signal);
66
+ const present = new Set(((info.results[0]!.rows[0]![0] as { tables?: { name: string }[] }).tables ?? []).map(table => table.name));
67
+ return db.exportFile({ ...signal, timeoutMs: FILE_EXPORT_TIMEOUT, emptyTables: [...FILE_EXPORT_EMPTIED_TABLES, ...ACCOUNT_SECRET_TABLES.filter(table => present.has(table))] });
58
68
  }
59
69
 
60
70
  /** A new webhook secret, for one that comes from a copy or an export. */
@@ -121,8 +131,8 @@ export async function* siteExport(db: RomeDB, options: SiteExportOptions): Async
121
131
  let page;
122
132
  try { page = (await read([{ rql: `SELECT ${select} FROM ${name} ${after} ORDER BY ${order} LIMIT $limit`, params }], sequence)).results[0]!; }
123
133
  catch (error) {
124
- // A page of large rows can pass the limit on one response: read fewer.
125
- if (error instanceof ClientError && (error.code === 'RDB_LIMIT' || error.code === 'RDB_RESULT_TOO_LARGE') && size > 1) { size = Math.max(1, Math.floor(size / 2)); continue; }
134
+ // A page of large rows can pass the limit on one response: read fewer. A full client is not about the page.
135
+ if (error instanceof ClientError && (error.code === 'RDB_LIMIT' || error.code === 'RDB_RESULT_TOO_LARGE') && !isClientFull(error) && size > 1) { size = Math.max(1, Math.floor(size / 2)); continue; }
126
136
  throw error;
127
137
  }
128
138
  const rows = page.rows.map(row => table.model === 'relational'