@crombolo/server 0.62.0 → 0.64.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.62.0",
3
+ "version": "0.64.0",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -31,19 +31,19 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.62.0",
35
- "@crombolo/api-management": "0.62.0",
36
- "@crombolo/auth": "0.62.0",
37
- "@crombolo/backoffice-host": "0.62.0",
38
- "@crombolo/common": "0.62.0",
39
- "@crombolo/content": "0.62.0",
40
- "@crombolo/contracts": "0.62.0",
41
- "@crombolo/core": "0.62.0",
42
- "@crombolo/data": "0.62.0",
43
- "@crombolo/extension": "0.62.0",
44
- "@crombolo/render": "0.62.0",
45
- "@crombolo/schema": "0.62.0",
46
- "@crombolo/transfer": "0.62.0",
34
+ "@crombolo/api-delivery": "0.64.0",
35
+ "@crombolo/api-management": "0.64.0",
36
+ "@crombolo/auth": "0.64.0",
37
+ "@crombolo/backoffice-host": "0.64.0",
38
+ "@crombolo/common": "0.64.0",
39
+ "@crombolo/content": "0.64.0",
40
+ "@crombolo/contracts": "0.64.0",
41
+ "@crombolo/core": "0.64.0",
42
+ "@crombolo/data": "0.64.0",
43
+ "@crombolo/extension": "0.64.0",
44
+ "@crombolo/render": "0.64.0",
45
+ "@crombolo/schema": "0.64.0",
46
+ "@crombolo/transfer": "0.64.0",
47
47
  "@logtape/logtape": "^2.3.8",
48
48
  "@opentelemetry/api": "1.10.0",
49
49
  "@opentelemetry/context-async-hooks": "3.0.0",
package/src/access.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * and each signed-in user's combined start nodes, group verbs and languages.
4
4
  */
5
5
  import type { NodeChain, NodeLookup, Principal } from '@crombolo/api-management/domain'
6
- import { combineStartNodes, normaliseUuid, ObjectTypes } from '@crombolo/core'
6
+ import { normaliseUuid, ObjectTypes, unionStartNodes } from '@crombolo/core'
7
7
  import { type Db, fromDbBool, UserRepository } from '@crombolo/data'
8
8
 
9
9
  async function chains(
@@ -98,7 +98,7 @@ export function createNodeLookup(db: Db): NodeLookup {
98
98
  }
99
99
  }
100
100
 
101
- /** A user's languages, combined start nodes per tree, and group verbs. */
101
+ /** A user's languages, their groups' start nodes per tree (story 339), and group verbs. */
102
102
  export async function loadAccess(
103
103
  db: Db,
104
104
  userId: number,
@@ -108,9 +108,9 @@ export async function loadAccess(
108
108
  languages: data.languages,
109
109
  groups: data.groups,
110
110
  startNodes: {
111
- document: combineStartNodes(data.groupStartNodes.document, data.userStartNodes.document),
112
- media: combineStartNodes(data.groupStartNodes.media, data.userStartNodes.media),
113
- element: combineStartNodes(data.groupStartNodes.element, data.userStartNodes.element),
111
+ document: unionStartNodes(data.groupStartNodes.document),
112
+ media: unionStartNodes(data.groupStartNodes.media),
113
+ element: unionStartNodes(data.groupStartNodes.element),
114
114
  },
115
115
  }
116
116
  }
@@ -14,6 +14,7 @@ import type {
14
14
  TemplatePort,
15
15
  TreePage,
16
16
  } from '@crombolo/api-management/domain'
17
+ import { CONTENT_FILES_READ_ONLY } from '@crombolo/api-management/domain'
17
18
  import {
18
19
  type ComponentModel,
19
20
  type ContentTypeAggregate,
@@ -42,7 +43,7 @@ import { aliasFromName } from '@crombolo/schema'
42
43
  import { readContentTypeUdt, writeContentTypeUdt } from '../content-type-udt.ts'
43
44
  import { classifyTypeChange } from '../schema-classify.ts'
44
45
  import { contentTypeJsonSchema, schemaForStorage, valueTypeName } from '../value-schemas.ts'
45
- import { createSchemaFileWriter, type SchemaFiles } from './schema-files.ts'
46
+ import { createSchemaFileWriter, type SchemaFiles, schemaProblems } from './schema-files.ts'
46
47
 
47
48
  async function toTreeItems(
48
49
  nodes: NodeRepository,
@@ -149,6 +150,43 @@ export function underSchemaLock<P extends object>(
149
150
  return locked
150
151
  }
151
152
 
153
+ class InvalidSchemaSave extends Error {
154
+ constructor(readonly problems: readonly string[]) {
155
+ super(problems.join('; '))
156
+ }
157
+ }
158
+
159
+ /**
160
+ * A save of a type or data type, in a transaction kept only when it leaves the
161
+ * definitions the schema files are written from no worse than it found them.
162
+ * Otherwise nothing is kept, and the save is refused saying why, so a file is
163
+ * never left behind its row. Problems that were there before are not its own.
164
+ */
165
+ export async function savedIfValid<T>(
166
+ db: Db,
167
+ files: SchemaFiles | undefined,
168
+ work: (tx: Db) => Promise<T>,
169
+ ): Promise<{ ok: true; value: T } | PortFailure> {
170
+ if (!files) return { ok: true, value: await work(db) }
171
+ const before = new Set(await schemaProblems(db, files))
172
+ try {
173
+ const value = await db.transaction(async (tx) => {
174
+ const value = await work(tx)
175
+ const added = (await schemaProblems(tx, files)).filter((p) => !before.has(p))
176
+ if (added.length > 0) throw new InvalidSchemaSave(added)
177
+ return value
178
+ })
179
+ return { ok: true, value }
180
+ } catch (error) {
181
+ if (!(error instanceof InvalidSchemaSave)) throw error
182
+ return {
183
+ ok: false,
184
+ status: 400,
185
+ reason: `This wasn't saved, because the site's definitions would no longer be valid: ${error.problems.join('; ')}`,
186
+ }
187
+ }
188
+ }
189
+
152
190
  export function createFolderPort(
153
191
  folders: FolderRepository,
154
192
  tree: ReturnType<typeof createSettingsTree>,
@@ -220,6 +258,9 @@ export function createContentTypePort(
220
258
  ): ContentTypePort {
221
259
  const kind = options.kind ?? 'document'
222
260
  const repo = new ContentTypeRepository(db, { nodeState: options.nodeState, kind })
261
+ /** The same repository over a transaction's handle, for a checked save. */
262
+ const repoOn = (handle: Db) =>
263
+ new ContentTypeRepository(handle, { nodeState: options.nodeState, kind })
223
264
  const nodes = repo.nodes
224
265
  const objectType = repo.objectType
225
266
  const containerType = CONTENT_TYPE_OBJECT_TYPES[kind].container
@@ -252,10 +293,11 @@ export function createContentTypePort(
252
293
  }
253
294
  const refused = files?.refuse(aggregate)
254
295
  if (refused) return refused
255
- // A new type can only be additive, and the version moves before the write so
256
- // the file that lands carries the version it belongs to.
296
+ const saved = await savedIfValid(db, schemaFiles, (tx) => repoOn(tx).save(aggregate))
297
+ if (!saved.ok) return saved
298
+ // A new type can only be additive, and the version moves before the file is
299
+ // written so the file that lands carries the version it belongs to.
257
300
  await files?.bumpVersion('additive')
258
- await repo.save(aggregate)
259
301
  await files?.write(aggregate)
260
302
  void principal
261
303
  return { ok: true as const }
@@ -270,10 +312,17 @@ export function createContentTypePort(
270
312
  const before = await repo.byKey(key)
271
313
  // Classified here, while the database still holds the old type: once it is
272
314
  // saved there is nothing left to compare it with.
273
- if (files)
274
- await files.bumpVersion(await classifyTypeChange(db, before, { ...aggregate, key }))
315
+ const change = files ? await classifyTypeChange(db, before, { ...aggregate, key }) : 'none'
275
316
  // The editor does not send tree placement; keep what the type has.
276
- await repo.save({ ...aggregate, key, parentKey: before?.parentKey ?? aggregate.parentKey })
317
+ const saved = await savedIfValid(db, schemaFiles, (tx) =>
318
+ repoOn(tx).save({
319
+ ...aggregate,
320
+ key,
321
+ parentKey: before?.parentKey ?? aggregate.parentKey,
322
+ }),
323
+ )
324
+ if (!saved.ok) return saved
325
+ await files?.bumpVersion(change)
277
326
  await files?.write({ ...aggregate, key }, before?.alias)
278
327
  void principal
279
328
  return { ok: true as const }
@@ -330,8 +379,18 @@ export function createContentTypePort(
330
379
  if (refused) return refused
331
380
  const alias = template.alias || aggregate.alias
332
381
  const name = template.name || aggregate.name
382
+ const existing = await templates.byAlias(alias)
383
+ // Story 337: a site that keeps its templates read-only adds them in its code.
384
+ if (!existing && options.componentFiles?.readOnly) {
385
+ const failure: PortFailure = {
386
+ ok: false,
387
+ reason: `${CONTENT_FILES_READ_ONLY} Add the template to the site's code.`,
388
+ status: 403,
389
+ }
390
+ return failure
391
+ }
333
392
  const saved =
334
- (await templates.byAlias(alias)) ??
393
+ existing ??
335
394
  (await templates.save({
336
395
  key: crypto.randomUUID(),
337
396
  name,
@@ -349,7 +408,8 @@ export function createContentTypePort(
349
408
  ? saved.key
350
409
  : aggregate.defaultComponentKey,
351
410
  }
352
- await repo.save(updated)
411
+ const kept = await savedIfValid(db, schemaFiles, (tx) => repoOn(tx).save(updated))
412
+ if (!kept.ok) return kept
353
413
  await files?.write(updated)
354
414
  void principal
355
415
  return { ok: true as const, key: saved.key }
@@ -494,7 +554,8 @@ export function createContentTypePort(
494
554
 
495
555
  if (!existing && (await repo.aliasExists(aggregate.alias)))
496
556
  return { status: 'invalid', reason: `The alias '${aggregate.alias}' is already in use.` }
497
- await repo.save(aggregate)
557
+ const saved = await savedIfValid(db, schemaFiles, (tx) => repoOn(tx).save(aggregate))
558
+ if (!saved.ok) return { status: 'invalid', reason: saved.reason }
498
559
  await files?.write(aggregate)
499
560
  return { status: 'ok', key: aggregate.key }
500
561
  },
@@ -597,8 +658,13 @@ export function createDataTypePort(db: Db, schemaFiles?: SchemaFiles): DataTypeP
597
658
  }
598
659
  },
599
660
  async save(model: DataTypeModel) {
600
- const saved = await repo.save(await withAlias(model))
601
- await files?.writeDataType(saved)
661
+ const aliased = await withAlias(model)
662
+ const saved = await savedIfValid(db, schemaFiles, (tx) =>
663
+ new DataTypeRepository(tx).save(aliased),
664
+ )
665
+ if (!saved.ok) return saved
666
+ await files?.writeDataType(saved.value)
667
+ return undefined
602
668
  },
603
669
  async remove(key) {
604
670
  const before = await repo.byKey(key)
@@ -733,6 +799,7 @@ export function createTemplatePort(db: Db, files: ComponentFileStore): TemplateP
733
799
  })
734
800
 
735
801
  return {
802
+ readOnly: files.readOnly === true,
736
803
  async byKey(key) {
737
804
  const model = await repo.byKey(key)
738
805
  if (!model) return undefined
@@ -96,7 +96,7 @@ export function createDocumentPort(
96
96
  /** The site's own directory: where `domains.toml` is, when the site keeps one. */
97
97
  siteDir?: string,
98
98
  /** Whether the site can send the e-mails a subscription asks for (story 045). */
99
- notificationsAvailable = true,
99
+ notificationsAvailable: boolean | (() => boolean) = true,
100
100
  ): DocumentPort {
101
101
  const repo = new DocumentRepository(db, options)
102
102
  const domains = new DomainRepository(db)
@@ -442,7 +442,11 @@ export function createDocumentPort(
442
442
  const userId = await userIdOf(principal)
443
443
  if (!node || node.objectType !== repo.objectType || userId === undefined) return 'notFound'
444
444
  // Clearing is always allowed; asking for something the site cannot send is not.
445
- if (!notificationsAvailable) {
445
+ if (
446
+ !(typeof notificationsAvailable === 'function'
447
+ ? notificationsAvailable()
448
+ : notificationsAvailable)
449
+ ) {
446
450
  const had = new Set(await notifications.subscribed(userId, node.id))
447
451
  if (actionIds.some((id) => !had.has(id))) return 'unavailable'
448
452
  }
@@ -15,6 +15,8 @@ export interface FileAreaOptions {
15
15
  rewrites?: readonly string[]
16
16
  /** Other extensions a file here may have, kept as they are. */
17
17
  also?: readonly string[]
18
+ /** The site keeps these files read-only in the back office (story 337). */
19
+ readOnly?: boolean
18
20
  }
19
21
 
20
22
  const INVALID_CHARACTERS = /[<>:"|?*\\/]/
@@ -93,7 +95,7 @@ export function createFileSystemPort(root: string, options: FileAreaOptions): Fi
93
95
  return (await kindOf(parent.file)) === 'folder' ? parent : undefined
94
96
  }
95
97
 
96
- return {
98
+ const port: FileSystemPort = {
97
99
  async children(parentPath) {
98
100
  const parent = locate(parentPath)
99
101
  if (!parent) return undefined
@@ -194,8 +196,30 @@ export function createFileSystemPort(root: string, options: FileAreaOptions): Fi
194
196
  return { ok: true, path: entry.path }
195
197
  },
196
198
  }
199
+ return options.readOnly ? readOnlyPort(port) : port
200
+ }
201
+
202
+ /** Reads as `port` does, and refuses every change (story 337). */
203
+ function readOnlyPort(port: FileSystemPort): FileSystemPort {
204
+ const refused = async (): Promise<FileResult> => ({ ok: false, status: 'ReadOnly' })
205
+ return {
206
+ children: (path) => port.children(path),
207
+ entry: (path) => port.entry(path),
208
+ read: (path) => port.read(path),
209
+ create: refused,
210
+ update: refused,
211
+ rename: refused,
212
+ delete: refused,
213
+ createFolder: refused,
214
+ deleteFolder: refused,
215
+ }
197
216
  }
198
217
 
199
218
  /** The components tree: its views, and the plain modules they import. */
200
- export const createComponentsPort = (root: string): FileSystemPort =>
201
- createFileSystemPort(root, { extension: '.tsx', also: ['.ts'], rewrites: ['.cshtml'] })
219
+ export const createComponentsPort = (root: string, readOnly = false): FileSystemPort =>
220
+ createFileSystemPort(root, {
221
+ extension: '.tsx',
222
+ also: ['.ts'],
223
+ rewrites: ['.cshtml'],
224
+ readOnly,
225
+ })
@@ -72,6 +72,23 @@ export interface SchemaFileWriter {
72
72
  * `schema/content-types/`, media types `schema/media-types/`. Data types,
73
73
  * languages and the rewrite are the same whichever kind asks.
74
74
  */
75
+ /**
76
+ * What is wrong with the definitions as the files would be written from the
77
+ * database `db` sees. A save compares it before and after, inside its
78
+ * transaction, and refuses what it adds, so a file is never left behind its row.
79
+ */
80
+ export async function schemaProblems(db: Db, files: SchemaFiles): Promise<string[]> {
81
+ if (!existsSync(files.schemaDir) || !files.writable) return []
82
+ const set = await exportSchemaSet(
83
+ db,
84
+ loadSchemaDirectory(files.schemaDir, { formTypes: files.formTypes }).set.version,
85
+ )
86
+ return validateSchemaSet(set, {
87
+ componentAliases: files.componentAliases(),
88
+ types: files.formTypes,
89
+ }).map((p) => `${p.file}${p.path ? ` (${p.path})` : ''}: ${p.message}`)
90
+ }
91
+
75
92
  export function createSchemaFileWriter(
76
93
  db: Db,
77
94
  files: SchemaFiles,
@@ -134,18 +151,8 @@ export function createSchemaFileWriter(
134
151
  : (set.memberTypes ?? [])
135
152
  const type = list.find((t) => t.key === aggregate.key)
136
153
  if (!type) return
137
- const problems = validateSchemaSet(set, {
138
- componentAliases: files.componentAliases(),
139
- types: files.formTypes,
140
- })
141
- if (problems.length > 0) {
142
- const detail = problems.map((p) => `${p.file}: ${p.message}`).join('; ')
143
- logger('schema').error('Not writing {file}: {detail}', {
144
- file: fileNameFor(aggregate.alias),
145
- detail,
146
- })
147
- return
148
- }
154
+ // Checked before the save, which `schemaProblems` refuses, so the file always
155
+ // follows the database.
149
156
  mkdirSync(dir, { recursive: true })
150
157
  if (previousAlias && previousAlias !== aggregate.alias)
151
158
  rmSync(fileFor(previousAlias), { force: true })
@@ -172,21 +179,6 @@ export function createSchemaFileWriter(
172
179
  await settle()
173
180
  return
174
181
  }
175
- // The same guard `write` applies to a content type: a set that does not
176
- // validate never reaches the disk, because the file is what every other
177
- // node reads and what a deploy boots from.
178
- const problems = validateSchemaSet(set, {
179
- componentAliases: files.componentAliases(),
180
- types: files.formTypes,
181
- })
182
- if (problems.length > 0) {
183
- const detail = problems.map((p) => `${p.file}: ${p.message}`).join('; ')
184
- logger('schema').error('Not writing {file}: {detail}', {
185
- file: fileNameFor(model.alias),
186
- detail,
187
- })
188
- return
189
- }
190
182
  mkdirSync(join(files.schemaDir, 'data-types'), { recursive: true })
191
183
  writeFileSync(
192
184
  join(files.schemaDir, 'data-types', fileNameFor(model.alias)),
@@ -7,6 +7,7 @@
7
7
  import { existsSync } from 'node:fs'
8
8
  import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
9
9
  import { join } from 'node:path'
10
+ import { CONTENT_FILES_READ_ONLY } from '@crombolo/api-management/domain'
10
11
  import type { ComponentFileStore } from '@crombolo/data'
11
12
 
12
13
  /** Aliases become filenames, so they must not be able to escape the directory. */
@@ -24,6 +25,7 @@ function safeAlias(alias: string): string | undefined {
24
25
  export function createTemplateFileStore(
25
26
  dir: string,
26
27
  onChange?: (alias: string) => void | Promise<void>,
28
+ readOnly = false,
27
29
  ): ComponentFileStore {
28
30
  const fileFor = (alias: string): string | undefined => {
29
31
  const safe = safeAlias(alias)
@@ -34,7 +36,13 @@ export function createTemplateFileStore(
34
36
  return !existsSync(file) && existsSync(folder) ? folder : file
35
37
  }
36
38
 
39
+ // Callers check `readOnly` first; this is the backstop (story 337).
40
+ const refuse = () => {
41
+ if (readOnly) throw new Error(CONTENT_FILES_READ_ONLY)
42
+ }
43
+
37
44
  return {
45
+ readOnly,
38
46
  async read(alias) {
39
47
  const file = fileFor(alias)
40
48
  if (!file) return undefined
@@ -45,6 +53,7 @@ export function createTemplateFileStore(
45
53
  }
46
54
  },
47
55
  async write(alias, content) {
56
+ refuse()
48
57
  const file = fileFor(alias)
49
58
  if (!file) throw new Error(`Unsafe template alias '${alias}'.`)
50
59
  await mkdir(dir, { recursive: true })
@@ -54,6 +63,7 @@ export function createTemplateFileStore(
54
63
  await onChange?.(alias)
55
64
  },
56
65
  async remove(alias) {
66
+ refuse()
57
67
  const file = fileFor(alias)
58
68
  if (!file) return
59
69
  await rm(file, { force: true })