@crombolo/server 0.69.1 → 0.71.0

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 (51) hide show
  1. package/package.json +15 -14
  2. package/src/adapters/blueprints.ts +51 -5
  3. package/src/adapters/change-recording.ts +140 -0
  4. package/src/adapters/content.ts +132 -21
  5. package/src/adapters/documents.ts +26 -5
  6. package/src/adapters/elements.ts +3 -0
  7. package/src/adapters/media.ts +7 -1
  8. package/src/adapters/schema-files.ts +89 -1
  9. package/src/adapters/users.ts +17 -12
  10. package/src/adapters/workspace-dictionary.ts +287 -0
  11. package/src/adapters/workspace-file-port.ts +160 -0
  12. package/src/adapters/workspace-languages.ts +94 -0
  13. package/src/approvals-api.ts +16 -7
  14. package/src/bundle-api.ts +19 -16
  15. package/src/bundle-install.ts +4 -0
  16. package/src/change-transfer.ts +676 -0
  17. package/src/changes-api.ts +258 -0
  18. package/src/component-templates-api.ts +2 -2
  19. package/src/config.ts +195 -21
  20. package/src/content-events.ts +65 -1
  21. package/src/content-operations.ts +22 -3
  22. package/src/core.ts +2 -0
  23. package/src/environment-values-api.ts +161 -0
  24. package/src/external-sign-in.ts +9 -2
  25. package/src/index.ts +1 -0
  26. package/src/managed-users.ts +122 -0
  27. package/src/node-operations.ts +150 -2
  28. package/src/ports.ts +174 -52
  29. package/src/principal.ts +1 -0
  30. package/src/remote-changes.ts +279 -0
  31. package/src/remote-schema.ts +126 -0
  32. package/src/remote-workspaces.ts +82 -0
  33. package/src/remote.ts +289 -192
  34. package/src/schema-transfer.ts +240 -41
  35. package/src/schema.ts +7 -2
  36. package/src/seed/compile.ts +13 -1
  37. package/src/seed/values.ts +3 -0
  38. package/src/server.ts +965 -364
  39. package/src/settings.ts +137 -5
  40. package/src/site-sections.ts +1 -1
  41. package/src/user-admin.ts +2 -0
  42. package/src/workspace-access.ts +152 -0
  43. package/src/workspace-checks.ts +299 -0
  44. package/src/workspace-losses.ts +95 -0
  45. package/src/workspace-processes.ts +306 -0
  46. package/src/workspace-render-child.ts +168 -0
  47. package/src/workspace-schema-dir.ts +100 -0
  48. package/src/workspace-schema.ts +598 -0
  49. package/src/workspace-sites.ts +179 -0
  50. package/src/workspace-views.ts +121 -0
  51. package/src/workspaces.ts +1031 -0
@@ -0,0 +1,258 @@
1
+ /**
2
+ * The site's changes over HTTP (story 381), at `<plugin>/api/changes`: every
3
+ * merged workspace, direct edit, applied bundle and revert, newest first; one
4
+ * change with each file's text before and after and its pages; a file's
5
+ * versions, each a change that touched it, compared with the file now; and a
6
+ * revert, which is a change of its own, refused where something later touched
7
+ * the same file or page, and which can reopen the work as a workspace.
8
+ */
9
+ import type { Principal } from '@crombolo/api-management/domain'
10
+ import { normaliseUuid } from '@crombolo/core'
11
+ import {
12
+ ChangeRepository,
13
+ type Db,
14
+ DocumentRepository,
15
+ type NodeSchemaState,
16
+ TransferRunRepository,
17
+ WorkspaceFileRepository,
18
+ WorkspaceRepository,
19
+ } from '@crombolo/data'
20
+ import { revertRun } from '@crombolo/transfer'
21
+ import { recordAudit } from './adapters/audit.ts'
22
+ import type { WorkspaceSchema } from './workspace-schema.ts'
23
+
24
+ const json = (body: unknown, status = 200) => Response.json(body, { status })
25
+ const refused = (message: string, status: number, extra: Record<string, unknown> = {}) =>
26
+ json({ message, ...extra }, status)
27
+
28
+ type Client = { ipAddress: string | null; forwardedFor: string | null }
29
+
30
+ export function createChangesApi(
31
+ db: Db,
32
+ options: {
33
+ schema: () => WorkspaceSchema | undefined
34
+ nodeState?: NodeSchemaState
35
+ /** Told after a revert that changed what is served. */
36
+ onReverted?: () => void | Promise<void>
37
+ },
38
+ ) {
39
+ const changes = new ChangeRepository(db)
40
+
41
+ /** A change with what it holds: its files, and its pages with what each did. */
42
+ async function detail(id: string) {
43
+ const change = await changes.byId(id)
44
+ if (!change) return undefined
45
+ const items = await changes.itemsOf(id)
46
+ const pages = await new TransferRunRepository(db).changes(id)
47
+ return {
48
+ ...change,
49
+ pageEdits:
50
+ change.kind === 'edit' && change.madeBy
51
+ ? await changes.pageEditsBy(
52
+ change.madeBy,
53
+ change.startedAt,
54
+ // An open edit gathers the person's page saves up to now.
55
+ change.closedAt ?? new Date(),
56
+ )
57
+ : undefined,
58
+ files: items.map((i) => ({
59
+ path: i.path,
60
+ kind: i.kind,
61
+ class: i.class,
62
+ before: i.before,
63
+ after: i.after,
64
+ })),
65
+ pageChanges: pages.map((p) => ({ key: p.nodeKey, action: p.action })),
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Puts a change back, as a change of its own: its pages through a run's revert,
71
+ * its files as they were before it, all or nothing; then, when asked, its work
72
+ * reopened as a workspace to carry on with.
73
+ */
74
+ async function revert(id: string, principal: Principal, toWorkspace: boolean, client: Client) {
75
+ const change = await changes.byId(id)
76
+ if (!change) return refused('There is no such change.', 404)
77
+ if (change.kind === 'bundle')
78
+ return refused('An applied bundle is reverted with `crombolo content revert`.', 409)
79
+ if (change.status !== 'applied') return refused('This change was reverted already.', 409)
80
+ const later = await changes.laterTouching(id)
81
+ const laterPages = await new TransferRunRepository(db).laterRunsTouching(id)
82
+ if (later.length > 0 || laterPages.length > 0)
83
+ return refused('Something changed later touches the same things; revert that first.', 409, {
84
+ files: [...new Set(later.map((l) => l.path))],
85
+ changes: [...new Set([...later.map((l) => l.changeId), ...laterPages])],
86
+ })
87
+ const items = await changes.itemsOf(id)
88
+ const schema = options.schema()
89
+ const pages = await new TransferRunRepository(db).changes(id)
90
+
91
+ // Its pages first, through the revert a run has; it refuses where one was edited since.
92
+ let revertId: string | undefined
93
+ if (pages.length > 0) {
94
+ const result = await revertRun(db, id)
95
+ if (!result.runId)
96
+ return refused('A page it changed was edited since.', 409, {
97
+ findings: result.check.outstanding.map((f) => f.message),
98
+ })
99
+ revertId = result.runId
100
+ await db.q
101
+ .updateTable('content_transfer_run')
102
+ .set({
103
+ change_kind: 'revert',
104
+ name: `Revert of ${change.name ?? 'a change'}`,
105
+ made_by: principal.id,
106
+ change_key: revertId,
107
+ })
108
+ .where('id', '=', revertId)
109
+ .execute()
110
+ } else {
111
+ revertId = await changes.begin({
112
+ kind: 'revert',
113
+ name: `Revert of ${change.name ?? 'a change'}`,
114
+ madeBy: principal.id,
115
+ revertsId: id,
116
+ })
117
+ await changes.setStatus(id, 'reverted')
118
+ }
119
+
120
+ // Then its files, each as it was before the change.
121
+ if (items.length > 0 && schema) {
122
+ const writes: Record<string, string | null> = {}
123
+ const befores: Record<string, string | null> = {}
124
+ for (const item of items) {
125
+ writes[item.path] = item.before
126
+ befores[item.path] = item.after
127
+ }
128
+ const applied = await db.transaction((tx) =>
129
+ schema.apply(tx, {
130
+ writes,
131
+ befores,
132
+ conflicts: [],
133
+ problems: [],
134
+ change: 'breaking',
135
+ items: [],
136
+ }),
137
+ )
138
+ await applied.after()
139
+ const recorded = new ChangeRepository(db)
140
+ for (const item of items)
141
+ await recorded.item(revertId, {
142
+ path: item.path,
143
+ kind: item.kind,
144
+ class: item.class,
145
+ before: item.after,
146
+ after: item.before,
147
+ })
148
+ }
149
+
150
+ let reopened: string | undefined
151
+ if (toWorkspace) reopened = await reopen(change.name ?? 'A change', items, pages, principal)
152
+ await recordAudit(db, {
153
+ category: 'content',
154
+ action: 'Revert',
155
+ source: 'request',
156
+ userKey: principal.id,
157
+ userName: principal.name,
158
+ entityType: 'Change',
159
+ entityKey: id,
160
+ entityName: change.name,
161
+ detail: `Reverted "${change.name ?? id}"${reopened ? ', its work reopened as a workspace' : ''}`,
162
+ ipAddress: client.ipAddress,
163
+ forwardedFor: client.forwardedFor,
164
+ })
165
+ await options.onReverted?.()
166
+ return json({ revertId, ...(reopened ? { workspace: reopened } : {}) })
167
+ }
168
+
169
+ /** A workspace holding what a change held: its files as it left them, its pages likewise. */
170
+ async function reopen(
171
+ name: string,
172
+ items: Awaited<ReturnType<ChangeRepository['itemsOf']>>,
173
+ pages: Awaited<ReturnType<TransferRunRepository['changes']>>,
174
+ principal: Principal,
175
+ ): Promise<string> {
176
+ const workspaces = new WorkspaceRepository(db)
177
+ const opened = await workspaces.open({ name: `Reopened: ${name}`, ownerKey: principal.id })
178
+ await options.schema()?.snapshot(opened.id)
179
+ const store = new WorkspaceFileRepository(db)
180
+ for (const item of items) await store.write(opened.id, item.path, item.after, item.class)
181
+ const shared = new DocumentRepository(db, { nodeState: options.nodeState })
182
+ const own = shared.inWorkspace(opened.id)
183
+ for (const page of pages) {
184
+ if (page.eventId === null) continue
185
+ const held = await shared.atVersion(String(page.eventId))
186
+ if (!held) continue
187
+ const document = held.document
188
+ await own.update({
189
+ key: document.key,
190
+ contentTypeKey: document.contentTypeKey,
191
+ componentKey: document.componentKey,
192
+ parentKey: document.parentKey,
193
+ values: document.values,
194
+ variants: document.variants.map((v) => ({
195
+ culture: v.culture,
196
+ segment: v.segment,
197
+ name: v.name,
198
+ })),
199
+ })
200
+ }
201
+ return opened.key
202
+ }
203
+
204
+ return {
205
+ async handle(
206
+ request: Request,
207
+ principal: Principal,
208
+ rest: string,
209
+ client: Client,
210
+ ): Promise<Response> {
211
+ const url = new URL(request.url)
212
+ const parts = rest.split('/').filter(Boolean).map(decodeURIComponent)
213
+ if (parts.length === 0 && request.method === 'GET') {
214
+ const skip = Math.max(0, Number(url.searchParams.get('skip') ?? 0) || 0)
215
+ const take = Math.min(200, Math.max(1, Number(url.searchParams.get('take') ?? 50) || 50))
216
+ return json(await changes.list(skip, take))
217
+ }
218
+ if (parts[0] === 'versions' && parts.length === 1 && request.method === 'GET') {
219
+ const path = url.searchParams.get('path') ?? ''
220
+ if (!path) return refused('Name the file, by its path.', 400)
221
+ const versions = await changes.versions(path)
222
+ const out = []
223
+ for (const v of versions) {
224
+ const change = await changes.byId(v.changeId)
225
+ out.push({
226
+ changeId: v.changeId,
227
+ name: change?.name ?? null,
228
+ kind: change?.kind,
229
+ madeBy: change?.madeBy ?? null,
230
+ at: change?.startedAt,
231
+ class: v.class,
232
+ removed: v.after === null,
233
+ })
234
+ }
235
+ return json({ path, versions: out })
236
+ }
237
+ const id = parts[0] ? normaliseUuid(parts[0]) : ''
238
+ if (parts.length === 1 && request.method === 'GET') {
239
+ const found = await detail(id)
240
+ return found ? json(found) : refused('There is no such change.', 404)
241
+ }
242
+ // An earlier version of one file against the file now.
243
+ if (parts[1] === 'compare' && parts.length === 2 && request.method === 'GET') {
244
+ const path = url.searchParams.get('path') ?? ''
245
+ const item = (await changes.itemsOf(id)).find((i) => i.path === path)
246
+ if (!item) return refused('That change did not touch that file.', 404)
247
+ const now = (await options.schema()?.textNow(path)) ?? null
248
+ return json({ path, version: item.after, current: now, same: item.after === now })
249
+ }
250
+ if (parts[1] === 'revert' && parts.length === 2 && request.method === 'POST') {
251
+ if (!principal.isAdmin) return refused('Only an administrator reverts a change.', 403)
252
+ const asked = ((await request.json().catch(() => ({}))) ?? {}) as Record<string, unknown>
253
+ return revert(id, principal, asked.toWorkspace === true, client)
254
+ }
255
+ return refused('There is nothing here.', 404)
256
+ },
257
+ }
258
+ }
@@ -58,8 +58,8 @@ export async function handleComponentTemplates(
58
58
  return Response.json({ items: componentTemplates(onDisk, await repo.all(), extensions) })
59
59
 
60
60
  if (request.method === 'POST') {
61
- // As changing which templates a type allows: Settings.
62
- if (!hasSection(principal, 'settings'))
61
+ // As changing which templates a type allows: Structure (story 385).
62
+ if (!hasSection(principal, 'structure'))
63
63
  return Response.json(
64
64
  { message: 'Making a component a template needs access to Structure.' },
65
65
  { status: 403 },
package/src/config.ts CHANGED
@@ -112,18 +112,26 @@ export function agentsGuideProblem(guide: string): string | undefined {
112
112
  : `The remote's agentsGuide, ${guide}, is not https: a guide is fetched only over https.`
113
113
  }
114
114
 
115
- export type ContentMode = 'development' | 'production'
115
+ /** Whether the back office may change the site's code: its templates, stylesheets and scripts. */
116
+ export type CodeSetting = 'editable' | 'locked'
116
117
 
117
- /** `CROMBOLO_CONTENT_MODE`, refusing the switch it replaced so locked files never quietly unlock. */
118
- function contentModeSetting(): ContentMode {
119
- // Read directly: it is no longer a setting, only a name to refuse.
118
+ /** `CROMBOLO_CODE`, refusing the names it replaced so locked code never quietly unlocks. */
119
+ function codeSetting(): CodeSetting {
120
+ // Read directly: they are no longer settings, only names to refuse.
120
121
  if (Bun.env.CROMBOLO_CONTENT_FILES_READONLY !== undefined)
121
122
  throw new Error(
122
- 'CROMBOLO_CONTENT_FILES_READONLY has gone: set CROMBOLO_CONTENT_MODE to production to keep templates, stylesheets and scripts read-only, or to development (story 343).',
123
+ 'CROMBOLO_CONTENT_FILES_READONLY has gone: set CROMBOLO_CODE=locked to keep templates, stylesheets and scripts read-only, or CROMBOLO_CODE=editable (story 391).',
124
+ )
125
+ const old = Bun.env.CROMBOLO_CONTENT_MODE
126
+ if (old !== undefined) {
127
+ const now = old.trim().toLowerCase() === 'production' ? 'locked' : 'editable'
128
+ throw new Error(
129
+ `CROMBOLO_CONTENT_MODE has gone: set CROMBOLO_CODE=${now} instead of CROMBOLO_CONTENT_MODE=${old} (story 391).`,
123
130
  )
124
- const value = (setting('CROMBOLO_CONTENT_MODE') ?? 'development').trim().toLowerCase()
125
- if (value !== 'development' && value !== 'production')
126
- throw new Error(`CROMBOLO_CONTENT_MODE is "${value}": it is development or production.`)
131
+ }
132
+ const value = (setting('CROMBOLO_CODE') ?? 'editable').trim().toLowerCase()
133
+ if (value !== 'editable' && value !== 'locked')
134
+ throw new Error(`CROMBOLO_CODE is "${value}": it is editable or locked.`)
127
135
  return value
128
136
  }
129
137
 
@@ -154,9 +162,51 @@ function cliAccessSetting(): CliAccess | undefined {
154
162
  return value
155
163
  }
156
164
 
157
- /** Whether the back office must leave templates, stylesheets and scripts alone. */
158
- export const contentFilesLocked = (config: Pick<CromboloConfig, 'contentMode'>) =>
159
- config.contentMode === 'production'
165
+ /** `CROMBOLO_ENVIRONMENT`, or `local` in development and `production` otherwise (story 387). */
166
+ function environmentName(): string {
167
+ const value =
168
+ setting('CROMBOLO_ENVIRONMENT')?.trim().toLowerCase() ||
169
+ (setting('NODE_ENV') === 'production' ? 'production' : 'local')
170
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(value))
171
+ throw new Error(
172
+ `CROMBOLO_ENVIRONMENT is "${value}": an environment's name is lower-case letters, digits and hyphens.`,
173
+ )
174
+ return value
175
+ }
176
+
177
+ /** Whether pages, media, types and code arrive only by a change (story 388). */
178
+ export type ContentSetting = 'editable' | 'locked'
179
+
180
+ /** `CROMBOLO_CONTENT`: `editable` unless set. */
181
+ function contentSetting(): ContentSetting {
182
+ const value = (setting('CROMBOLO_CONTENT') ?? 'editable').trim().toLowerCase()
183
+ if (value !== 'editable' && value !== 'locked')
184
+ throw new Error(`CROMBOLO_CONTENT is "${value}": it is editable or locked.`)
185
+ return value
186
+ }
187
+
188
+ /** Whether the back office must leave templates, stylesheets and scripts alone: locked content locks them too. */
189
+ export const contentFilesLocked = (config: Pick<CromboloConfig, 'code' | 'contentEditing'>) =>
190
+ config.code === 'locked' || config.contentEditing === 'locked'
191
+
192
+ /** Whether workspaces are on: turned on, or a locked site's, for the changes staged on it (story 388). */
193
+ export const workspacesOn = (config: Pick<CromboloConfig, 'workspaces' | 'contentEditing'>) =>
194
+ config.workspaces || config.contentEditing === 'locked'
195
+
196
+ /** Who looks after the site's back-office people (story 389). */
197
+ export interface UsersSetting {
198
+ /** The API clients a directory signs in as; none leaves users to the site. */
199
+ managedBy: readonly string[]
200
+ managedAt?: string | undefined
201
+ }
202
+
203
+ /** Whether users come only from a directory outside the site (story 389). */
204
+ export const usersManaged = (config: { users?: UsersSetting }) =>
205
+ (config.users?.managedBy.length ?? 0) > 0
206
+
207
+ /** Whether the site takes its pages, media, types and code only by a change (story 388). */
208
+ export const contentLocked = (config: Pick<CromboloConfig, 'contentEditing'>) =>
209
+ config.contentEditing === 'locked'
160
210
 
161
211
  /** `CROMBOLO_REMOTE_ACCESS`, refusing the switch it replaced so a site does not quietly stop being a remote. */
162
212
  function remoteAccessSetting(): RemoteAccess {
@@ -241,6 +291,17 @@ export interface CromboloConfig {
241
291
  */
242
292
  signalRSkipNegotiation: boolean
243
293
  development: boolean
294
+ /**
295
+ * Which copy of the site this is (story 387): the environment whose own value a
296
+ * property varying by environment serves. `CROMBOLO_ENVIRONMENT`; `local` in
297
+ * development, `production` otherwise. The remote environment defaults to it.
298
+ */
299
+ environment: string
300
+ /**
301
+ * This environment's own values arrive only by a change (story 387): the editor and
302
+ * the API refuse to set them here. `CROMBOLO_ENVIRONMENT_VALUES_READONLY`, off.
303
+ */
304
+ environmentValuesReadOnly: boolean
244
305
  /**
245
306
  * Open pages reload when the views, the schema or the content change, and
246
307
  * show the background type check's findings (story 214). On in development,
@@ -415,11 +476,22 @@ export interface CromboloConfig {
415
476
  */
416
477
  schemaWritable: boolean
417
478
  /**
418
- * `production` keeps templates, stylesheets and scripts read-only in the back
419
- * office, for a site whose files come from its repository (stories 337, 343).
420
- * `development` unless set, in production too. `CROMBOLO_CONTENT_MODE`.
479
+ * `locked` keeps templates, stylesheets and scripts read-only in the back office,
480
+ * for a site whose files come from its repository (stories 337, 343, 391).
481
+ * `editable` unless set, in production too. `CROMBOLO_CODE`.
482
+ */
483
+ code: CodeSetting
484
+ /**
485
+ * `locked` makes pages, media, the Library, types, data types and code read-only in
486
+ * the back office and the API: they arrive only by a change applied here (story
487
+ * 388). `editable` unless set. `CROMBOLO_CONTENT`.
421
488
  */
422
- contentMode: ContentMode
489
+ contentEditing: ContentSetting
490
+ /**
491
+ * Where a locked site's content is edited: the other site's back office, for the
492
+ * line and link an item opened here shows. `CROMBOLO_CONTENT_EDITED_AT`.
493
+ */
494
+ contentEditedAt?: string
423
495
  /**
424
496
  * Whether a command that reads or changes the site needs a signed-in person
425
497
  * (story 350): `sign-in` unless `development`, where it is `open`.
@@ -431,8 +503,56 @@ export interface CromboloConfig {
431
503
  * `CROMBOLO_CLI_TOKENS`, off unless set.
432
504
  */
433
505
  cliTokens: boolean
506
+ /**
507
+ * Story 389: back-office people kept in a directory outside the site. With `managedBy`
508
+ * naming API clients, only they create, change, disable or delete a user, or change
509
+ * whom a group holds; `managedAt` is the directory's address for one user, with
510
+ * `{email}`, `{key}` or `{userName}`. `CROMBOLO_USERS_MANAGED_BY`, `CROMBOLO_USERS_MANAGED_AT`.
511
+ */
512
+ users: UsersSetting
434
513
  /** The most days a command-line token may last. `CROMBOLO_CLI_TOKEN_MAX_DAYS`, 90. */
435
514
  cliTokenMaxDays: number
515
+ /**
516
+ * Whether people may open workspaces, to change pages apart from Shared
517
+ * (story 375). `CROMBOLO_WORKSPACES`, off unless set.
518
+ */
519
+ workspaces: boolean
520
+ /**
521
+ * Whether every change to a page is made in a workspace (story 380): Shared
522
+ * takes it only by a merge. `CROMBOLO_WORKSPACES_REQUIRED`, off unless set; it
523
+ * needs workspaces on.
524
+ */
525
+ workspacesRequired: boolean
526
+ /**
527
+ * How many workspaces with changed views render at once on a node, each in a
528
+ * process of its own (story 378); past it the least recently used is stopped.
529
+ * `CROMBOLO_WORKSPACE_PROCESSES`, 10.
530
+ */
531
+ workspaceProcesses: number
532
+ /** A workspace's process is stopped after this long unused. `CROMBOLO_WORKSPACE_PROCESS_IDLE_MINUTES`, 30. */
533
+ workspaceProcessIdleMinutes: number
534
+ /** A workspace's process is stopped past this much memory. `CROMBOLO_WORKSPACE_PROCESS_MEMORY_MB`, 1024. */
535
+ workspaceProcessMemoryMb: number
536
+ /** How long a page may take in a workspace's process. `CROMBOLO_WORKSPACE_RENDER_SECONDS`, 30. */
537
+ workspaceRenderSeconds: number
538
+ /**
539
+ * The fewest days between retiring a property and purging it, with its values
540
+ * (story 382). `CROMBOLO_PURGE_AFTER_DAYS`, 0.
541
+ */
542
+ purgeAfterDays: number
543
+ /**
544
+ * Where a workspace's site is served (story 379): a host pattern with
545
+ * `{workspace}` for its key's 32 hex digits, and `{host}` for one of the site's
546
+ * hosts, such as `{workspace}.preview.example.com`. Unset, a workspace is
547
+ * opened by a cookie on the site's own host. `CROMBOLO_WORKSPACES_HOST`.
548
+ */
549
+ workspacesHost: string | undefined
550
+ /** The longest a link to a workspace's site may last, in days; 0 turns links off. `CROMBOLO_WORKSPACE_LINK_MAX_DAYS`, 30. */
551
+ workspaceLinkMaxDays: number
552
+ /** How many workspaces' sites one node keeps ready. `CROMBOLO_WORKSPACE_SITES`, 3. */
553
+ workspaceSites: number
554
+ /** How long a workspace's site is kept without a visit. `CROMBOLO_WORKSPACE_SITE_IDLE_MINUTES`, 15. */
555
+ workspaceSiteIdleMinutes: number
436
556
  /** Sync `schema/` at boot; a pipeline that runs `crombolo types sync` turns this off. */
437
557
  syncSchemaAtBoot: boolean
438
558
  /** Which database engine; from CROMBOLO_DB. */
@@ -936,6 +1056,8 @@ export function loadConfig(
936
1056
  umbracoCssPath: DEFAULTS.umbracoCssPath,
937
1057
  signalRSkipNegotiation: DEFAULTS.signalRSkipNegotiation,
938
1058
  development: setting('NODE_ENV') !== 'production',
1059
+ environment: environmentName(),
1060
+ environmentValuesReadOnly: envFlag(setting('CROMBOLO_ENVIRONMENT_VALUES_READONLY')) === true,
939
1061
  sqliteFile: setting('CROMBOLO_SQLITE_FILE') ?? DEFAULTS.sqliteFile,
940
1062
  adminLogin: setting('CROMBOLO_ADMIN_LOGIN') ?? DEFAULTS.adminLogin,
941
1063
  adminPassword: setting('CROMBOLO_ADMIN_PASSWORD'),
@@ -990,11 +1112,36 @@ export function loadConfig(
990
1112
  ? setting('CROMBOLO_SCHEMA_WRITABLE') === 'true'
991
1113
  : setting('NODE_ENV') !== 'production',
992
1114
  syncSchemaAtBoot: setting('CROMBOLO_SYNC_SCHEMA_AT_BOOT') !== 'false',
993
- contentMode: contentModeSetting(),
1115
+ code: codeSetting(),
1116
+ contentEditing: contentSetting(),
1117
+ contentEditedAt: setting('CROMBOLO_CONTENT_EDITED_AT') || undefined,
994
1118
  // Resolved again below, once it is known whether this is development.
995
1119
  cliAccess: cliAccessSetting() as CliAccess,
996
1120
  cliTokens: setting('CROMBOLO_CLI_TOKENS') === 'true',
1121
+ users: {
1122
+ managedBy: (setting('CROMBOLO_USERS_MANAGED_BY') ?? '')
1123
+ .split(',')
1124
+ .map((id) => id.trim())
1125
+ .filter(Boolean),
1126
+ managedAt: setting('CROMBOLO_USERS_MANAGED_AT') || undefined,
1127
+ },
997
1128
  cliTokenMaxDays: Math.floor(positiveNumber(setting('CROMBOLO_CLI_TOKEN_MAX_DAYS'), 90)),
1129
+ workspaces: setting('CROMBOLO_WORKSPACES') === 'true',
1130
+ workspacesRequired: setting('CROMBOLO_WORKSPACES_REQUIRED') === 'true',
1131
+ purgeAfterDays: Math.floor(nonNegativeNumber(setting('CROMBOLO_PURGE_AFTER_DAYS'), 0)),
1132
+ workspacesHost: setting('CROMBOLO_WORKSPACES_HOST') || undefined,
1133
+ workspaceLinkMaxDays: Math.floor(
1134
+ nonNegativeNumber(setting('CROMBOLO_WORKSPACE_LINK_MAX_DAYS'), 30),
1135
+ ),
1136
+ workspaceSites: Math.floor(positiveNumber(setting('CROMBOLO_WORKSPACE_SITES'), 3)),
1137
+ workspaceSiteIdleMinutes: positiveNumber(setting('CROMBOLO_WORKSPACE_SITE_IDLE_MINUTES'), 15),
1138
+ workspaceProcesses: Math.floor(positiveNumber(setting('CROMBOLO_WORKSPACE_PROCESSES'), 10)),
1139
+ workspaceProcessIdleMinutes: positiveNumber(
1140
+ setting('CROMBOLO_WORKSPACE_PROCESS_IDLE_MINUTES'),
1141
+ 30,
1142
+ ),
1143
+ workspaceProcessMemoryMb: positiveNumber(setting('CROMBOLO_WORKSPACE_PROCESS_MEMORY_MB'), 1024),
1144
+ workspaceRenderSeconds: positiveNumber(setting('CROMBOLO_WORKSPACE_RENDER_SECONDS'), 30),
998
1145
  dialect: setting('CROMBOLO_DB') === 'postgres' ? 'postgres' : 'sqlite',
999
1146
  pgDump: setting('CROMBOLO_PG_DUMP'),
1000
1147
  upgradePolicy:
@@ -1064,7 +1211,7 @@ export function loadConfig(
1064
1211
  remote: {
1065
1212
  enabled: remoteAccessSetting() !== 'off',
1066
1213
  access: remoteAccessSetting(),
1067
- environment: setting('CROMBOLO_REMOTE_ENVIRONMENT') || 'production',
1214
+ environment: setting('CROMBOLO_REMOTE_ENVIRONMENT') || environmentName(),
1068
1215
  protected: setting('CROMBOLO_REMOTE_PROTECTED') !== 'false',
1069
1216
  approvals: setting('CROMBOLO_REMOTE_APPROVALS') === 'true',
1070
1217
  maxUploadBytes: Number(setting('CROMBOLO_REMOTE_MAX_UPLOAD_GB') ?? 50) * 1024 ** 3,
@@ -1152,16 +1299,37 @@ export function loadConfig(
1152
1299
  host: undefined,
1153
1300
  }
1154
1301
  const merged: CromboloConfig = { ...fromEnv, ...stripUndefined(overrides) }
1155
- // The file is checked as the environment is: an unknown mode must not fall back to editable.
1156
- if (merged.contentMode !== 'development' && merged.contentMode !== 'production')
1302
+ // The file is checked as the environment is: an unknown value must not fall back to editable.
1303
+ if ('contentMode' in overrides)
1304
+ throw new Error(
1305
+ `contentMode has gone from crombolo.config.ts: set code: '${(overrides as { contentMode?: string }).contentMode === 'production' ? 'locked' : 'editable'}' instead (story 391).`,
1306
+ )
1307
+ if (merged.contentEditing !== 'editable' && merged.contentEditing !== 'locked')
1157
1308
  throw new Error(
1158
- `contentMode is "${String(merged.contentMode)}" in crombolo.config.ts: it is development or production.`,
1309
+ `contentEditing is "${String(merged.contentEditing)}" in crombolo.config.ts: it is editable or locked.`,
1310
+ )
1311
+ if (merged.code !== 'editable' && merged.code !== 'locked')
1312
+ throw new Error(
1313
+ `code is "${String(merged.code)}" in crombolo.config.ts: it is editable or locked.`,
1159
1314
  )
1160
1315
  merged.cliAccess ??= merged.development ? 'open' : 'sign-in'
1161
1316
  if (merged.cliAccess !== 'open' && merged.cliAccess !== 'sign-in')
1162
1317
  throw new Error(
1163
1318
  `cliAccess is "${String(merged.cliAccess)}" in crombolo.config.ts: it is open or sign-in.`,
1164
1319
  )
1320
+ if (
1321
+ !Array.isArray(merged.users?.managedBy) ||
1322
+ merged.users.managedBy.some((id) => typeof id !== 'string' || !id.trim())
1323
+ )
1324
+ throw new Error('users.managedBy in crombolo.config.ts is a list of API client ids.')
1325
+ if (merged.users.managedAt !== undefined && !/^https?:\/\//.test(merged.users.managedAt))
1326
+ throw new Error(
1327
+ `users.managedAt is "${merged.users.managedAt}": it is an http or https address, with {email}, {key} or {userName}.`,
1328
+ )
1329
+ if (merged.workspacesRequired && !merged.workspaces)
1330
+ throw new Error(
1331
+ 'Workspaces are required (CROMBOLO_WORKSPACES_REQUIRED) but not turned on: set CROMBOLO_WORKSPACES=true as well.',
1332
+ )
1165
1333
  checkIdentityProviders(merged.memberIdentityProviders, 'member')
1166
1334
  checkIdentityProviders(merged.backofficeIdentityProviders, 'backoffice')
1167
1335
  for (const clash of exchangeAudienceClashes(
@@ -1314,7 +1482,7 @@ export function describeDatabase(
1314
1482
  }
1315
1483
  }
1316
1484
 
1317
- export const VERSION = '0.69.1'
1485
+ export const VERSION = '0.71.0'
1318
1486
 
1319
1487
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1320
1488
  /** A positive number from a setting, else the default. */
@@ -1323,6 +1491,12 @@ function positiveNumber(raw: string | undefined, fallback: number): number {
1323
1491
  return raw !== undefined && raw !== '' && Number.isFinite(value) && value > 0 ? value : fallback
1324
1492
  }
1325
1493
 
1494
+ /** Zero or more from a setting, else the default. */
1495
+ function nonNegativeNumber(raw: string | undefined, fallback: number): number {
1496
+ const value = Number(raw)
1497
+ return raw !== undefined && raw !== '' && Number.isFinite(value) && value >= 0 ? value : fallback
1498
+ }
1499
+
1326
1500
  function validatorSetting(name: Parameters<typeof setting>[0]): Validator | undefined {
1327
1501
  const raw = setting(name)?.trim()
1328
1502
  return raw === 'published' || raw === 'body' ? raw : undefined
@@ -5,7 +5,10 @@
5
5
  * live backoffice, and a nudge so the dispatcher sends it now rather than at
6
6
  * its next tick. The command line wires the same sink without the live part.
7
7
  */
8
+
9
+ import { CHANGE_PUBLISHED } from '@crombolo/api-management'
8
10
  import {
11
+ type Actor,
9
12
  actorMemberKey,
10
13
  actorName,
11
14
  actorNote,
@@ -23,7 +26,7 @@ import {
23
26
  notificationFor,
24
27
  webhookFor,
25
28
  } from '@crombolo/content'
26
- import { AuditLog, ContentEventRepository, type Db } from '@crombolo/data'
29
+ import { AuditLog, ChangeRepository, ContentEventRepository, type Db } from '@crombolo/data'
27
30
  import type { ContentNotifier } from './content-notifications.ts'
28
31
  import type { WebhookService } from './webhooks.ts'
29
32
 
@@ -34,8 +37,21 @@ export interface ContentEventSinkOptions {
34
37
  live?(event: ReturnType<typeof liveEventsFor>[number]): void
35
38
  /** Called after a commit that left work in the outbox. */
36
39
  nudge?(): void
40
+ /**
41
+ * Story 388: a person's own saves join their change, and a publish closes it and
42
+ * raises `Crombolo.ChangePublished` naming it, for a host to pass on.
43
+ */
44
+ changes?: boolean
37
45
  }
38
46
 
47
+ const SAVES = new Set(['created', 'saved', 'createdAndPublished', 'savedAndPublished'])
48
+ const PUBLISHES = new Set([
49
+ 'published',
50
+ 'createdAndPublished',
51
+ 'savedAndPublished',
52
+ 'branchPublished',
53
+ ])
54
+
39
55
  /** The page an event is about, for the outbox row. */
40
56
  const subjectOf = (event: DocumentEvent): string | null =>
41
57
  'key' in event ? event.key : 'parentKey' in event ? event.parentKey : null
@@ -60,8 +76,37 @@ export const outboxActor = (actor: MediaActor) => {
60
76
  }
61
77
 
62
78
  export function createContentEventSink(options: ContentEventSinkOptions): EventSink {
79
+ /** A person's own write in the back office or the API, not a merge's nor the site's code. */
80
+ const ownEdit = (actor: Actor) => actor.kind === 'user' && !actor.origin.via
81
+
82
+ /** Story 388: the page in its writer's change, and on a publish the change closed and announced. */
83
+ async function recordInChange(tx: Db, event: DocumentEvent, actor: Actor) {
84
+ const key = subjectOf(event)
85
+ const userKey = actorUserKey(actor)
86
+ if (!key || !userKey || !ownEdit(actor)) return
87
+ const changes = new ChangeRepository(tx)
88
+ if (SAVES.has(event.type)) await changes.pageSavedBy(userKey, { key, kind: 'document' })
89
+ if (!PUBLISHES.has(event.type)) return
90
+ const change = await changes.publishedBy(userKey, { key, kind: 'document' })
91
+ if (!change) return
92
+ const hook = { alias: CHANGE_PUBLISHED, key }
93
+ await new ContentEventRepository(tx).record({
94
+ kind: 'change-published',
95
+ entityType: 'Document',
96
+ entityKey: key,
97
+ facts: {
98
+ v: 1,
99
+ ...(options.webhooks
100
+ ? { webhook: { ...(await options.webhooks.factsFor(tx, hook)), change } }
101
+ : {}),
102
+ },
103
+ actor: outboxActor(actor),
104
+ })
105
+ }
106
+
63
107
  return {
64
108
  async record(tx: Db, event, actor) {
109
+ if (options.changes) await recordInChange(tx, event, actor as Actor)
65
110
  const entry = auditEntryFor(event, actor)
66
111
  const audit = new AuditLog(tx)
67
112
  // A deleted page cannot be named after it went: the operation read its name first.
@@ -175,3 +220,22 @@ export function createElementEventSink(): ElementEventSink {
175
220
  },
176
221
  }
177
222
  }
223
+
224
+ /** A workspace's Library writes (story 390): audited, naming the workspace, and announced nowhere else. */
225
+ export function workspaceElementEventSink(name: string): ElementEventSink {
226
+ return {
227
+ async record(tx: Db, event, actor) {
228
+ const entry = elementAuditEntryFor(event, actor)
229
+ const audit = new AuditLog(tx)
230
+ const subject = await audit.describe(entry.entityType, entry.entityKey)
231
+ const where = `In the workspace "${name}"`
232
+ await audit.record({
233
+ ...entry,
234
+ entityType: subject.entityType,
235
+ entityKey: subject.entityKey,
236
+ entityName: subject.entityName,
237
+ detail: entry.detail ? `${where}. ${entry.detail}` : where,
238
+ })
239
+ },
240
+ }
241
+ }