@crombolo/server 0.63.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.
@@ -0,0 +1,472 @@
1
+ /**
2
+ * Settings → Developers → Schema (story 342): the site's schema folder
3
+ * downloaded as TOML, and schema files uploaded from elsewhere, held until an
4
+ * administrator approves them on the Changes dashboard.
5
+ *
6
+ * An upload changes nothing. It is checked against the site, laid over a copy
7
+ * of `schema/`, and kept in `key_value` with its findings in the change report,
8
+ * so any node can show and apply it. Applying writes the files into `schema/`
9
+ * and runs the sync a deploy runs, putting the files back if the sync refuses.
10
+ * Only TOML in the folder's own layout is taken: `migrations/` is code, and an
11
+ * upload never brings code.
12
+ */
13
+ import {
14
+ cpSync,
15
+ existsSync,
16
+ mkdirSync,
17
+ mkdtempSync,
18
+ readdirSync,
19
+ readFileSync,
20
+ rmSync,
21
+ writeFileSync,
22
+ } from 'node:fs'
23
+ import { tmpdir } from 'node:os'
24
+ import { dirname, join, relative, sep } from 'node:path'
25
+ import {
26
+ type Db,
27
+ type Finding,
28
+ Locks,
29
+ type NodeSchemaState,
30
+ now,
31
+ readReport,
32
+ writeReport,
33
+ } from '@crombolo/data'
34
+ import {
35
+ loadSchemaDirectory,
36
+ nextSchemaVersion,
37
+ parseSchemaSettings,
38
+ type SyncReport,
39
+ TYPE_KIND_FILES,
40
+ validateSchemaSet,
41
+ writeSchemaVersion,
42
+ } from '@crombolo/schema'
43
+ import { recordAudit } from './adapters/audit.ts'
44
+ import type { CromboloConfig } from './config.ts'
45
+ import { formTypesFor } from './form-types.ts'
46
+ import { checkSchemaDirectory, importSchema } from './schema.ts'
47
+ import { publishSchema, type SchemaStore } from './schema-store.ts'
48
+ import { parseWebhookFile } from './webhook-files.ts'
49
+ import { readZip, writeZip, ZipError } from './zip.ts'
50
+
51
+ const KEY = 'crombolo:schema-import'
52
+ const SCOPE = 'schema'
53
+
54
+ /** Bounds on an upload, well past any real site's schema. */
55
+ export const UPLOAD_LIMITS = {
56
+ maxUploadBytes: 10 * 1024 * 1024,
57
+ maxEntries: 2000,
58
+ maxEntryBytes: 1024 * 1024,
59
+ maxTotalBytes: 20 * 1024 * 1024,
60
+ }
61
+
62
+ /** Folders whose files sit directly inside them, by the table each file starts with. */
63
+ const FLAT: Record<string, string> = {
64
+ [TYPE_KIND_FILES.document.dir]: TYPE_KIND_FILES.document.header,
65
+ [TYPE_KIND_FILES.media.dir]: TYPE_KIND_FILES.media.header,
66
+ [TYPE_KIND_FILES.member.dir]: TYPE_KIND_FILES.member.header,
67
+ 'data-types': 'data-type',
68
+ 'user-groups': 'user-group',
69
+ webhooks: 'webhook',
70
+ }
71
+ /** Forms and workflows may sit in folders of their own (story 289). */
72
+ const DEEP: Record<string, string> = { forms: 'form', workflows: 'workflow' }
73
+ const TOP = ['schema.toml', 'languages.toml']
74
+
75
+ const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
76
+
77
+ /** Where a file belongs in `schema/`, or undefined when the layout has no place for it. */
78
+ export function schemaPathOf(path: string): string | undefined {
79
+ const parts = path.replaceAll('\\', '/').split('/').filter(Boolean)
80
+ if (parts[0] === 'schema') parts.shift()
81
+ if (parts.length === 0 || !parts.every((part) => SEGMENT.test(part))) return undefined
82
+ const name = parts.at(-1) as string
83
+ if (!name.endsWith('.toml')) return undefined
84
+ if (parts.length === 1) return TOP.includes(name) ? name : undefined
85
+ const [folder = ''] = parts
86
+ if (folder in FLAT && parts.length === 2) return parts.join('/')
87
+ if (folder in DEEP) return parts.join('/')
88
+ return undefined
89
+ }
90
+
91
+ /**
92
+ * Where a lone `.toml` goes: the folder its first table names, as the file
93
+ * already there with the same alias, or under its own name when it is new.
94
+ */
95
+ function placeLoose(
96
+ fileName: string,
97
+ text: string,
98
+ current: ReadonlyMap<string, string>,
99
+ ): string | undefined {
100
+ const name = fileName.replaceAll('\\', '/').split('/').at(-1) ?? ''
101
+ if (TOP.includes(name)) return name
102
+ const table = /^\s*\[([a-z-]+)\]/m.exec(text)?.[1]
103
+ const folder = Object.entries({ ...FLAT, ...DEEP }).find(([, header]) => header === table)?.[0]
104
+ if (!folder) return undefined
105
+ const alias = aliasOf(text)
106
+ const same = alias
107
+ ? [...current].find(
108
+ ([path, existing]) => path.startsWith(`${folder}/`) && aliasOf(existing) === alias,
109
+ )
110
+ : undefined
111
+ if (same) return same[0]
112
+ return SEGMENT.test(name) && name.endsWith('.toml') ? `${folder}/${name}` : undefined
113
+ }
114
+
115
+ const aliasOf = (text: string) => /^\s*alias\s*=\s*"([^"]+)"/m.exec(text)?.[1]
116
+
117
+ /** Every TOML file under `dir`, by its `/`-separated path in it. */
118
+ function schemaFiles(dir: string): Map<string, string> {
119
+ const out = new Map<string, string>()
120
+ const walk = (at: string) => {
121
+ if (!existsSync(at)) return
122
+ for (const entry of readdirSync(at, { withFileTypes: true })) {
123
+ if (entry.name.startsWith('.')) continue
124
+ const path = join(at, entry.name)
125
+ if (entry.isDirectory()) walk(path)
126
+ else {
127
+ const rel = relative(dir, path).split(sep).join('/')
128
+ if (schemaPathOf(rel) === rel) out.set(rel, readFileSync(path, 'utf8'))
129
+ }
130
+ }
131
+ }
132
+ walk(dir)
133
+ return out
134
+ }
135
+
136
+ export interface SchemaActor {
137
+ id: string | null
138
+ name: string
139
+ ipAddress?: string | null
140
+ }
141
+
142
+ interface Pending {
143
+ fileName: string
144
+ files: Record<string, string>
145
+ added: string[]
146
+ changed: string[]
147
+ uploadedBy: string
148
+ uploadedAt: string
149
+ }
150
+
151
+ /** A waiting import, as the Changes dashboard shows it. */
152
+ export interface PendingSchemaImportView {
153
+ fileName: string
154
+ added: string[]
155
+ changed: string[]
156
+ uploadedBy: string
157
+ uploadedAt: string
158
+ /** A finding stops it until the files change. */
159
+ blocked: boolean
160
+ }
161
+
162
+ export type SchemaOutcome<T = object> =
163
+ | ({ ok: true } & T)
164
+ | { ok: false; status: number; message: string; problems?: string[] }
165
+
166
+ const refused = (status: number, message: string, problems?: string[]) =>
167
+ ({ ok: false, status, message, ...(problems ? { problems } : {}) }) as const
168
+
169
+ export function createSchemaTransfer(
170
+ db: Db,
171
+ config: CromboloConfig,
172
+ options: {
173
+ boot: { nodeId: string; nodeState: NodeSchemaState }
174
+ /** What the server does after any schema sync: caches, redirects. */
175
+ afterApply?: (report: SyncReport | undefined) => Promise<void>
176
+ },
177
+ ) {
178
+ const audit = (actor: SchemaActor, action: string, detail: string) =>
179
+ recordAudit(db, {
180
+ category: 'schema',
181
+ action,
182
+ entityType: 'Schema',
183
+ entityName: 'Schema',
184
+ detail,
185
+ source: 'request',
186
+ userKey: actor.id,
187
+ userName: actor.name,
188
+ ipAddress: actor.ipAddress ?? null,
189
+ forwardedFor: null,
190
+ })
191
+
192
+ async function read(): Promise<Pending | undefined> {
193
+ const row = await db.q
194
+ .selectFrom('key_value')
195
+ .select('value')
196
+ .where('key', '=', KEY)
197
+ .executeTakeFirst()
198
+ try {
199
+ return row?.value ? (JSON.parse(row.value) as Pending) : undefined
200
+ } catch {
201
+ return undefined
202
+ }
203
+ }
204
+
205
+ async function write(pending: Pending | undefined): Promise<void> {
206
+ await db.q.deleteFrom('key_value').where('key', '=', KEY).execute()
207
+ if (pending)
208
+ await db.q
209
+ .insertInto('key_value')
210
+ .values({ key: KEY, value: JSON.stringify(pending), update_date: now(db) })
211
+ .execute()
212
+ }
213
+
214
+ /** The site's schema version and its `schema.toml` as it stands. */
215
+ function currentSettings() {
216
+ const file = join(config.schemaDir, 'schema.toml')
217
+ const text = existsSync(file) ? readFileSync(file, 'utf8') : undefined
218
+ const parsed = text ? parseSchemaSettings('schema.toml', text).value : undefined
219
+ return { text, version: parsed?.version ?? '1.0.0', urls: parsed?.urls }
220
+ }
221
+
222
+ /**
223
+ * An uploaded `schema.toml` brings its URL settings, never its version: another
224
+ * site's number says nothing about this one. Undefined when it changes nothing.
225
+ */
226
+ function settingsFrom(text: string): string | undefined {
227
+ const current = currentSettings()
228
+ const parsed = parseSchemaSettings('schema.toml', text)
229
+ if (!parsed.value) return text
230
+ const written = writeSchemaVersion(current.version, parsed.value.urls)
231
+ return written === writeSchemaVersion(current.version, current.urls) ? undefined : written
232
+ }
233
+
234
+ /**
235
+ * The upload's files laid over a copy of `schema/`, checked as a deploy would
236
+ * check them. A change needs a new version, so the version is raised as far as
237
+ * the change needs, as the back office raises it for a type it saves, and
238
+ * `schemaToml` is the file to write with it.
239
+ */
240
+ async function check(files: Record<string, string>) {
241
+ const dir = mkdtempSync(join(tmpdir(), 'crombolo-import-'))
242
+ try {
243
+ if (existsSync(config.schemaDir)) cpSync(config.schemaDir, dir, { recursive: true })
244
+ for (const [path, text] of Object.entries(files)) {
245
+ mkdirSync(dirname(join(dir, path)), { recursive: true })
246
+ writeFileSync(join(dir, path), text)
247
+ }
248
+ const formTypes = formTypesFor(config)
249
+ const loaded = loadSchemaDirectory(dir, { formTypes })
250
+ const problems = [...loaded.problems, ...validateSchemaSet(loaded.set, { types: formTypes })]
251
+ .map((p) => `${p.file}${p.path ? ` (${p.path})` : ''}: ${p.message}`)
252
+ .map((line) => line.replaceAll(dir, 'schema'))
253
+ for (const [path, text] of Object.entries(files))
254
+ if (path.startsWith('webhooks/'))
255
+ problems.push(...parseWebhookFile(path, text).problems.map((p) => `${path}: ${p}`))
256
+ if (problems.length > 0) return { problems, findings: [] as Finding[], schemaToml: undefined }
257
+ const run = () =>
258
+ checkSchemaDirectory(
259
+ db,
260
+ { ...config, schemaDir: dir },
261
+ { nodeId: options.boot.nodeId, revision: config.schemaRevision },
262
+ { migrationsDir: config.schemaDir },
263
+ )
264
+ // The sync refuses a change that keeps its version, and then says nothing of
265
+ // how big it is, so the first pass is under a provisional raise.
266
+ const current = currentSettings()
267
+ const settings = (version: string) => {
268
+ const text = writeSchemaVersion(version, loaded.set.urls)
269
+ writeFileSync(join(dir, 'schema.toml'), text)
270
+ return text
271
+ }
272
+ settings(nextSchemaVersion(current.version, 'additive'))
273
+ const first = await run()
274
+ const next = nextSchemaVersion(current.version, first.classification)
275
+ const schemaToml = settings(next)
276
+ const findings =
277
+ next === nextSchemaVersion(current.version, 'additive')
278
+ ? first.findings
279
+ : (await run()).findings
280
+ return {
281
+ problems: [] as string[],
282
+ findings,
283
+ schemaToml: schemaToml === current.text ? undefined : schemaToml,
284
+ }
285
+ } finally {
286
+ rmSync(dir, { recursive: true, force: true })
287
+ }
288
+ }
289
+
290
+ const blocking = (findings: readonly Finding[]) => findings.some((f) => f.kind === 'blocking')
291
+
292
+ return {
293
+ /** Every TOML file in `schema/`, as a zip that unpacks to a `schema` folder. */
294
+ exportZip(): Uint8Array<ArrayBuffer> {
295
+ const encoder = new TextEncoder()
296
+ return writeZip(
297
+ [...schemaFiles(config.schemaDir)]
298
+ .sort(([a], [b]) => a.localeCompare(b))
299
+ .map(([path, text]) => ({ path: `schema/${path}`, bytes: encoder.encode(text) })),
300
+ )
301
+ },
302
+
303
+ async pending(): Promise<PendingSchemaImportView | undefined> {
304
+ const pending = await read()
305
+ if (!pending) return undefined
306
+ const open = await readReport(db, { source: 'import', scope: SCOPE })
307
+ return {
308
+ fileName: pending.fileName,
309
+ added: pending.added,
310
+ changed: pending.changed,
311
+ uploadedBy: pending.uploadedBy,
312
+ uploadedAt: pending.uploadedAt,
313
+ blocked: open.some((f) => f.status === 'open' && f.kind === 'blocking'),
314
+ }
315
+ },
316
+
317
+ /** Checks an upload and keeps it for approval; nothing in `schema/` changes. */
318
+ async upload(
319
+ actor: SchemaActor,
320
+ fileName: string,
321
+ bytes: Uint8Array,
322
+ ): Promise<SchemaOutcome<{ added: string[]; changed: string[] }>> {
323
+ if (!config.schemaWritable)
324
+ return refused(
325
+ 409,
326
+ "This site's schema changes only with a deploy, so it can't be imported here.",
327
+ )
328
+ if (bytes.length > UPLOAD_LIMITS.maxUploadBytes)
329
+ return refused(413, 'That file is too large to be a schema.')
330
+ const files: Record<string, string> = {}
331
+ const outside: string[] = []
332
+ const decoder = new TextDecoder('utf-8', { fatal: true })
333
+ try {
334
+ if (/\.toml$/i.test(fileName)) {
335
+ const text = decoder.decode(bytes)
336
+ const path = placeLoose(fileName, text, schemaFiles(config.schemaDir))
337
+ if (!path) outside.push(fileName)
338
+ else files[path] = text
339
+ } else {
340
+ for (const entry of readZip(bytes, UPLOAD_LIMITS)) {
341
+ const path = schemaPathOf(entry.path)
342
+ if (!path) outside.push(entry.path)
343
+ else files[path] = decoder.decode(entry.bytes)
344
+ }
345
+ }
346
+ } catch (error) {
347
+ if (error instanceof ZipError) return refused(400, error.message)
348
+ return refused(400, 'A file in it is not readable text.')
349
+ }
350
+ if (outside.length > 0)
351
+ return refused(
352
+ 400,
353
+ 'Only schema files can be imported: TOML, in the folders a schema folder has.',
354
+ outside.slice(0, 20).map((path) => `${path}: not a schema file`),
355
+ )
356
+
357
+ if ('schema.toml' in files) {
358
+ const settings = settingsFrom(files['schema.toml'] as string)
359
+ if (settings === undefined) delete files['schema.toml']
360
+ else files['schema.toml'] = settings
361
+ }
362
+ const current = schemaFiles(config.schemaDir)
363
+ const added = Object.keys(files).filter((path) => !current.has(path))
364
+ const changed = Object.keys(files).filter(
365
+ (path) => current.has(path) && current.get(path) !== files[path],
366
+ )
367
+ if (added.length + changed.length === 0)
368
+ return refused(
369
+ 400,
370
+ 'Every file in it is already the same here, so there is nothing to import.',
371
+ )
372
+ const kept = Object.fromEntries([...added, ...changed].map((path) => [path, files[path]]))
373
+ const { problems, findings } = await check(kept as Record<string, string>)
374
+ if (problems.length > 0)
375
+ return refused(400, "These files can't be used as they are.", problems.slice(0, 50))
376
+
377
+ await write({
378
+ fileName,
379
+ files: kept as Record<string, string>,
380
+ added: added.sort(),
381
+ changed: changed.sort(),
382
+ uploadedBy: actor.name,
383
+ uploadedAt: new Date().toISOString(),
384
+ })
385
+ await writeReport(db, findings, { source: 'import', scope: SCOPE })
386
+ await audit(
387
+ actor,
388
+ 'Upload',
389
+ `${fileName}: ${describe(added, changed)}, waiting for approval${blocking(findings) ? ' (blocked)' : ''}`,
390
+ )
391
+ return { ok: true, added: added.sort(), changed: changed.sort() }
392
+ },
393
+
394
+ /** Writes the waiting files into `schema/` and syncs them, once nothing blocks it. */
395
+ async apply(actor: SchemaActor): Promise<SchemaOutcome<{ action?: string }>> {
396
+ const pending = await read()
397
+ if (!pending) return refused(404, 'There is no schema import waiting.')
398
+ if (!config.schemaWritable)
399
+ return refused(
400
+ 409,
401
+ "This site's schema changes only with a deploy, so it can't be imported here.",
402
+ )
403
+ // Checked again: the site may have changed since the upload.
404
+ const { problems, findings, schemaToml } = await check(pending.files)
405
+ if (problems.length > 0)
406
+ return refused(409, 'The site has changed, and these files no longer fit it.', problems)
407
+ await writeReport(db, findings, { source: 'import', scope: SCOPE })
408
+ if (blocking(findings))
409
+ return refused(
410
+ 409,
411
+ 'Something on the Changes dashboard stops this import. Discard it, or fix the files and upload them again.',
412
+ )
413
+
414
+ const before = new Map<string, string | undefined>()
415
+ await db.locks.withLock(Locks.Schema, async () => {
416
+ const writes = { ...pending.files, ...(schemaToml ? { 'schema.toml': schemaToml } : {}) }
417
+ for (const [path, text] of Object.entries(writes)) {
418
+ const target = join(config.schemaDir, path)
419
+ before.set(path, existsSync(target) ? readFileSync(target, 'utf8') : undefined)
420
+ mkdirSync(dirname(target), { recursive: true })
421
+ writeFileSync(target, text)
422
+ }
423
+ })
424
+ const result = await importSchema(db, config, options.boot, { materialise: false })
425
+ if (result.report?.action === 'refused') {
426
+ await db.locks.withLock(Locks.Schema, async () => {
427
+ for (const [path, text] of before) {
428
+ const target = join(config.schemaDir, path)
429
+ if (text === undefined) rmSync(target, { force: true })
430
+ else writeFileSync(target, text)
431
+ }
432
+ })
433
+ return refused(
434
+ 409,
435
+ `The import was refused, and the schema is as it was: ${result.report.reason ?? 'see the server log'}.`,
436
+ )
437
+ }
438
+ if (config.schemaStore)
439
+ await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
440
+ await options.afterApply?.(result.report)
441
+ await write(undefined)
442
+ await writeReport(db, [], { source: 'import', scope: SCOPE })
443
+ await audit(
444
+ actor,
445
+ 'Apply',
446
+ `${pending.fileName}: ${describe(pending.added, pending.changed)} (${[...pending.added, ...pending.changed].join(', ')})`,
447
+ )
448
+ return { ok: true, action: result.report?.action }
449
+ },
450
+
451
+ async discard(actor: SchemaActor): Promise<SchemaOutcome> {
452
+ const pending = await read()
453
+ if (!pending) return refused(404, 'There is no schema import waiting.')
454
+ await write(undefined)
455
+ await writeReport(db, [], { source: 'import', scope: SCOPE })
456
+ await audit(
457
+ actor,
458
+ 'Discard',
459
+ `${pending.fileName}: ${describe(pending.added, pending.changed)}`,
460
+ )
461
+ return { ok: true }
462
+ },
463
+ }
464
+ }
465
+
466
+ const describe = (added: readonly string[], changed: readonly string[]) =>
467
+ [
468
+ added.length > 0 ? `${added.length} new file${added.length === 1 ? '' : 's'}` : '',
469
+ changed.length > 0 ? `${changed.length} changed file${changed.length === 1 ? '' : 's'}` : '',
470
+ ]
471
+ .filter(Boolean)
472
+ .join(' and ')