@crombolo/server 0.39.1 → 0.41.1

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.39.1",
3
+ "version": "0.41.1",
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,18 +31,18 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.39.1",
35
- "@crombolo/api-management": "0.39.1",
36
- "@crombolo/auth": "0.39.1",
37
- "@crombolo/backoffice-host": "0.39.1",
38
- "@crombolo/common": "0.39.1",
39
- "@crombolo/content": "0.39.1",
40
- "@crombolo/contracts": "0.39.1",
41
- "@crombolo/core": "0.39.1",
42
- "@crombolo/data": "0.39.1",
43
- "@crombolo/render": "0.39.1",
44
- "@crombolo/schema": "0.39.1",
45
- "@crombolo/transfer": "0.39.1",
34
+ "@crombolo/api-delivery": "0.41.1",
35
+ "@crombolo/api-management": "0.41.1",
36
+ "@crombolo/auth": "0.41.1",
37
+ "@crombolo/backoffice-host": "0.41.1",
38
+ "@crombolo/common": "0.41.1",
39
+ "@crombolo/content": "0.41.1",
40
+ "@crombolo/contracts": "0.41.1",
41
+ "@crombolo/core": "0.41.1",
42
+ "@crombolo/data": "0.41.1",
43
+ "@crombolo/render": "0.41.1",
44
+ "@crombolo/schema": "0.41.1",
45
+ "@crombolo/transfer": "0.41.1",
46
46
  "@logtape/logtape": "^2.3.8",
47
47
  "jose": "^6.2.12"
48
48
  }
package/src/actions.ts ADDED
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Server actions (story 219): `POST /crombolo/actions/{id}`, through route
3
+ * handlers' pipeline, so CSRF, the rate limit, the time limit and the signal
4
+ * are theirs. A form post is answered with a 303 back, its result in a signed
5
+ * flash cookie; a call asking for JSON with the result itself.
6
+ * docs/rendering.md, "Server actions".
7
+ */
8
+ import {
9
+ ACTIONS_PATH,
10
+ type ActionState,
11
+ isOutcome,
12
+ Ok,
13
+ type Outcome,
14
+ type RouteContext,
15
+ route,
16
+ type ServerAction,
17
+ } from '@crombolo/common'
18
+ import { readSignedFlash, writeSignedFlash } from './form-submit.ts'
19
+ import type { DeclaredRoute } from './routes.ts'
20
+
21
+ /** The cookie an action's result returns to the page in. */
22
+ export const ACTION_FLASH_COOKIE = 'crombolo-action'
23
+
24
+ /** The fields an action's form carries for Crombolo, taken out before the action sees them. */
25
+ export const RETURN_FIELD = '__return'
26
+ export const ANTIFORGERY_FIELD = '__antiforgery'
27
+
28
+ /** Fields whose values are never sent back to the page: what a password field is called. */
29
+ const SECRET_FIELD = /pass(word)?|secret|pin$/i
30
+
31
+ /** The site's actions, by id and by function. */
32
+ export interface ActionRegistry {
33
+ ids: readonly string[]
34
+ /** The id a listed function answers at, or undefined for one the config does not list. */
35
+ idOf(action: unknown): string | undefined
36
+ byId(id: string): ServerAction | undefined
37
+ }
38
+
39
+ /** A flash: which action answered, and what. */
40
+ export interface ActionFlash {
41
+ id: string
42
+ state: ActionState
43
+ }
44
+
45
+ /**
46
+ * The config's action modules as a registry, and why any of it cannot be
47
+ * mounted: an export that is not a function, a module key with a dot in it,
48
+ * or one function listed twice.
49
+ */
50
+ export function actionRegistry(modules: Record<string, Record<string, unknown>> | undefined): {
51
+ registry: ActionRegistry
52
+ problems: string[]
53
+ } {
54
+ const byId = new Map<string, ServerAction>()
55
+ const ids = new Map<unknown, string>()
56
+ const problems: string[] = []
57
+ for (const [moduleKey, exports] of Object.entries(modules ?? {})) {
58
+ if (moduleKey.includes('.')) {
59
+ problems.push(
60
+ `The action module "${moduleKey}" has a dot in its key; an action's id is the key, a dot, and the export's name.`,
61
+ )
62
+ continue
63
+ }
64
+ for (const [name, action] of Object.entries(exports ?? {})) {
65
+ const id = `${moduleKey}.${name}`
66
+ if (typeof action !== 'function') {
67
+ problems.push(
68
+ `"${id}" is not a function: every export of an action module is an action, so move anything else to a module of its own.`,
69
+ )
70
+ continue
71
+ }
72
+ const listed = ids.get(action)
73
+ if (listed) {
74
+ problems.push(`One function is listed as two actions, "${listed}" and "${id}".`)
75
+ continue
76
+ }
77
+ ids.set(action, id)
78
+ byId.set(id, action as ServerAction)
79
+ }
80
+ }
81
+ return {
82
+ registry: {
83
+ ids: [...byId.keys()],
84
+ idOf: (action) => ids.get(action),
85
+ byId: (id) => byId.get(id),
86
+ },
87
+ problems,
88
+ }
89
+ }
90
+
91
+ /** Where an action's form returns: a path on this site, else the home page. */
92
+ export function returnPath(value: FormDataEntryValue | null): string {
93
+ if (typeof value !== 'string') return '/'
94
+ if (!value.startsWith('/') || value.startsWith('//') || value.startsWith('/\\')) return '/'
95
+ return value
96
+ }
97
+
98
+ const wantsJson = (request: Request) =>
99
+ (request.headers.get('accept') ?? '').includes('application/json')
100
+
101
+ /** What was submitted, to fill the form again: strings only, secrets left out. */
102
+ function submitted(form: FormData): Record<string, string> {
103
+ const values: Record<string, string> = {}
104
+ for (const [name, value] of form)
105
+ if (typeof value === 'string' && !SECRET_FIELD.test(name)) values[name] = value
106
+ return values
107
+ }
108
+
109
+ /** The route each action answers at, through the site's route pipeline. */
110
+ export function actionRoutes(
111
+ registry: ActionRegistry,
112
+ flashSecret: string,
113
+ secureCookies: boolean,
114
+ ) {
115
+ const flashCookie = (flash: ActionFlash) => {
116
+ const value = writeSignedFlash(flashSecret, flash, [
117
+ { state: { ...flash.state, values: {} } },
118
+ { state: { ...flash.state, values: {}, value: undefined } },
119
+ ])
120
+ return `${ACTION_FLASH_COOKIE}=${value}; Path=/; Max-Age=60; HttpOnly; SameSite=Lax${secureCookies ? '; Secure' : ''}`
121
+ }
122
+ const back = (location: string, flash: ActionFlash) =>
123
+ new Response(null, {
124
+ status: 303,
125
+ headers: { location, 'set-cookie': flashCookie(flash), 'cache-control': 'no-store' },
126
+ })
127
+
128
+ const entries = new Map<string, DeclaredRoute>()
129
+ for (const id of registry.ids) {
130
+ const action = registry.byId(id) as ServerAction
131
+ const handler = async (request: Request, context: RouteContext): Promise<Response> => {
132
+ const json = wantsJson(request)
133
+ const form = await request.formData().catch(() => undefined)
134
+ if (!form)
135
+ return Response.json(
136
+ { ok: false, status: 400, message: 'An action is posted as a form.' },
137
+ { status: 400 },
138
+ )
139
+ const to = returnPath(form.get(RETURN_FIELD))
140
+ form.delete(RETURN_FIELD)
141
+ form.delete(ANTIFORGERY_FIELD)
142
+ const { params: _, ...actionContext } = context
143
+ let answer: Response | Ok<unknown> | Outcome | unknown
144
+ try {
145
+ answer = await action(form, actionContext)
146
+ } catch (error) {
147
+ // `redirect()` and `notFound()` throw their outcome, as in a page.
148
+ if (!isOutcome(error)) throw error
149
+ answer = error
150
+ }
151
+ if (answer instanceof Response) return answer
152
+ if (isOutcome(answer)) {
153
+ if (answer.isRedirect)
154
+ return json
155
+ ? Response.json({ ok: true, redirect: answer.location })
156
+ : back(answer.location as string, { id, state: { ok: true } })
157
+ const state: ActionState = {
158
+ ok: false,
159
+ status: answer.status,
160
+ message: answer.message,
161
+ errors: answer.errors,
162
+ values: submitted(form),
163
+ }
164
+ return json
165
+ ? Response.json(
166
+ { ok: false, status: answer.status, message: answer.message, errors: answer.errors },
167
+ { status: answer.status },
168
+ )
169
+ : back(to, { id, state })
170
+ }
171
+ const value = answer instanceof Ok ? answer.value : answer
172
+ return json
173
+ ? Response.json({ ok: true, value })
174
+ : back(to, { id, state: { ok: true, value } })
175
+ }
176
+ entries.set(id, {
177
+ route: route(`${ACTIONS_PATH}/${id}`, { POST: handler as never }),
178
+ owner: `the action ${id}`,
179
+ })
180
+ }
181
+
182
+ return {
183
+ /** The action a path names, or undefined when it names none. */
184
+ match(pathname: string): DeclaredRoute | undefined {
185
+ if (!pathname.startsWith(`${ACTIONS_PATH}/`)) return undefined
186
+ return entries.get(decodeURIComponent(pathname.slice(ACTIONS_PATH.length + 1)))
187
+ },
188
+ /** The flash a page returned to holds, when its signature holds and it is fresh. */
189
+ readFlash(cookie: string | undefined): ActionFlash | undefined {
190
+ return readSignedFlash<ActionFlash>(flashSecret, cookie)
191
+ },
192
+ }
193
+ }
@@ -21,11 +21,13 @@ import { ObjectTypes, type Page } from '@crombolo/core'
21
21
  import {
22
22
  type Bundle,
23
23
  BundleRepository,
24
+ type BundleSchemaPicks,
24
25
  type ComponentFileStore,
25
26
  type Db,
26
27
  type NodeRow,
27
28
  resolveNodeRef,
28
29
  } from '@crombolo/data'
30
+ import { loadSchemaDirectory, type SchemaSet } from '@crombolo/schema'
29
31
  import {
30
32
  type BundleBlob,
31
33
  type BundleDependency,
@@ -43,6 +45,7 @@ import {
43
45
  import { VERSION } from '../config.ts'
44
46
  import { readBlobs } from '../media-files.ts'
45
47
  import type { MediaStore } from '../media-store.ts'
48
+ import { carriedPicks, schemaPickFiles } from '../schema-picks.ts'
46
49
  import { siteSections } from '../site-sections.ts'
47
50
  import { writeNpmTarball } from '../tar.ts'
48
51
 
@@ -67,6 +70,8 @@ export interface PackagePortOptions {
67
70
  components?: FileSystemPort
68
71
  stylesheets?: FileSystemPort
69
72
  scripts?: FileSystemPort
73
+ /** Where the site's forms, workflows and user groups are read from (story 226). */
74
+ schemaDir?: string
70
75
  }
71
76
 
72
77
  const definition = (row: Bundle): PackageDefinition => ({
@@ -278,6 +283,13 @@ export function createPackagePort(db: Db, options: PackagePortOptions): PackageP
278
283
  if (!row) return undefined
279
284
  const from = definition(row)
280
285
  const pkg = bundlePackageOf(row)
286
+ const declared = options.schemaDir
287
+ ? loadSchemaDirectory(options.schemaDir)
288
+ : { set: undefined, files: new Map<string, string>() }
289
+ const carried = declared.set ? carriedPicks(declared.set, await bundles.schemaPicks(id)) : []
290
+ const broughtTypes = carried
291
+ .filter((pick) => pick.kind === 'documentType' && !pick.excluded)
292
+ .map((pick) => pick.alias)
281
293
 
282
294
  const sections = await siteSections(
283
295
  {
@@ -288,7 +300,7 @@ export function createPackagePort(db: Db, options: PackagePortOptions): PackageP
288
300
  scripts: options.scripts,
289
301
  },
290
302
  {
291
- contentTypes: from.contentTypes,
303
+ contentTypes: [...from.contentTypes, ...broughtTypes],
292
304
  mediaTypes: from.mediaTypes,
293
305
  dataTypes: from.dataTypes,
294
306
  languages: from.languages,
@@ -299,6 +311,17 @@ export function createPackagePort(db: Db, options: PackagePortOptions): PackageP
299
311
  },
300
312
  )
301
313
 
314
+ // Document types go through the picked-type path above; the rest are the
315
+ // site's own files, which the database does not hold.
316
+ if (options.schemaDir)
317
+ sections.push(
318
+ ...schemaPickFiles(
319
+ declared,
320
+ options.schemaDir,
321
+ carried.filter((pick) => pick.kind !== 'documentType'),
322
+ ),
323
+ )
324
+
302
325
  const content = await contentEntries(from, buildOptions.withMedia === true)
303
326
  // A package with nothing picked is still a bundle: an empty selection
304
327
  // produces an empty set rather than throwing, which is what gives a
@@ -388,3 +411,58 @@ export async function writeCreatedBundlePackage(
388
411
  await bundles.setPackage(id, { name: name || null, version: version || null })
389
412
  return { ok: true, package: (await readCreatedBundlePackage(db, id)) as CreatedBundlePackage }
390
413
  }
414
+
415
+ /** The forms, workflows and user groups a created bundle can pick: the site's files. */
416
+ export interface SchemaPickChoices {
417
+ forms: { alias: string; name: string }[]
418
+ workflows: { alias: string; name: string }[]
419
+ userGroups: { alias: string; name: string }[]
420
+ }
421
+
422
+ const declaredSet = (schemaDir: string): SchemaSet => loadSchemaDirectory(schemaDir).set
423
+
424
+ export function schemaPickChoices(schemaDir: string): SchemaPickChoices {
425
+ const set = declaredSet(schemaDir)
426
+ const named = (list: readonly { alias: string; name: string }[] | undefined) =>
427
+ (list ?? []).map(({ alias, name }) => ({ alias, name }))
428
+ return {
429
+ forms: named(set.forms),
430
+ workflows: named(set.workflows),
431
+ userGroups: named(set.userGroups),
432
+ }
433
+ }
434
+
435
+ const aliases = (value: unknown): string[] =>
436
+ Array.isArray(value)
437
+ ? [...new Set(value.filter((v): v is string => typeof v === 'string' && v.trim() !== ''))]
438
+ : []
439
+
440
+ /** Picks as a request sends them, keeping only lists of names. */
441
+ export function schemaPicksOf(body: Record<string, unknown>): BundleSchemaPicks {
442
+ return {
443
+ forms: aliases(body.forms),
444
+ workflows: aliases(body.workflows),
445
+ userGroups: aliases(body.userGroups),
446
+ excluded: aliases(body.excluded),
447
+ }
448
+ }
449
+
450
+ /** What a set of picks carries, against the site's files as they stand. */
451
+ export function carriedSchemaPicks(schemaDir: string, picks: BundleSchemaPicks) {
452
+ return carriedPicks(declaredSet(schemaDir), picks)
453
+ }
454
+
455
+ /** A created bundle's forms, workflows and user groups, or undefined when it is gone. */
456
+ export async function readSchemaPicks(db: Db, id: string): Promise<BundleSchemaPicks | undefined> {
457
+ const bundles = new BundleRepository(db)
458
+ return (await bundles.byId(id)) ? bundles.schemaPicks(id) : undefined
459
+ }
460
+
461
+ export async function writeSchemaPicks(
462
+ db: Db,
463
+ id: string,
464
+ body: Record<string, unknown>,
465
+ ): Promise<BundleSchemaPicks | undefined> {
466
+ const picks = schemaPicksOf(body)
467
+ return (await new BundleRepository(db).setSchemaPicks(id, picks)) ? picks : undefined
468
+ }
@@ -582,6 +582,7 @@ export function createPublishedContentSource(
582
582
  return out
583
583
  },
584
584
  loadContentTypeAliases: () => new ContentTypeRepository(db).aliasesByKey(),
585
+ loadSiteSettingsTypes: () => new ContentTypeRepository(db).siteSettingsAliases(),
585
586
  loadUrlOptions: () => readUrlOptions(db),
586
587
 
587
588
  async loadRedirects() {
@@ -41,6 +41,7 @@ const CHECKS = {
41
41
  nodes: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000005', name: 'Servers' },
42
42
  outgoing: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000006', name: 'Outgoing changes' },
43
43
  routes: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000007', name: 'Routes and pages' },
44
+ settings: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000008', name: 'Site settings' },
44
45
  } as const
45
46
 
46
47
  /** Waiting longer than this means nothing is sending: no server is running its jobs, or one is stuck. */
@@ -87,6 +88,11 @@ const GROUPS: HealthCheckGroup[] = [
87
88
  description:
88
89
  "Whether a route in the site's code answers at an address a published page also has, which hides the page.",
89
90
  },
91
+ {
92
+ ...CHECKS.settings,
93
+ description:
94
+ "Whether each site has at most one settings page, kept directly below the site's top page.",
95
+ },
90
96
  ],
91
97
  },
92
98
  ]
@@ -166,6 +172,10 @@ export interface HealthCheckOptions {
166
172
  now?: () => Date
167
173
  /** Published pages a route answers in place of (story 211). */
168
174
  hiddenByRoutes?: () => Promise<Array<{ route: string; owner: string; page: string; url: string }>>
175
+ /** Settings pages that are not, or not alone, their site's settings (story 058). */
176
+ siteSettingsFindings?: () => Promise<
177
+ Array<{ kind: 'second' | 'deep'; name: string; counted?: string }>
178
+ >
169
179
  }
170
180
 
171
181
  const result = (
@@ -351,6 +361,19 @@ export function createDiagnosticsPort(options: HealthCheckOptions): DiagnosticsP
351
361
  ),
352
362
  )
353
363
  },
364
+ [CHECKS.settings.id]: async () => {
365
+ const findings = (await options.siteSettingsFindings?.()) ?? []
366
+ if (findings.length === 0)
367
+ return [result('Success', 'Every settings page is where its site reads it.')]
368
+ return findings.map((f) =>
369
+ result(
370
+ 'Warning',
371
+ f.kind === 'second'
372
+ ? `"${f.name}" is a second settings page for its site, so it is not used: "${f.counted}" is.`
373
+ : `"${f.name}" is a settings page below another page, so no site reads it. Move it directly below its site's top page.`,
374
+ ),
375
+ )
376
+ },
354
377
  [CHECKS.outgoing.id]: async () =>
355
378
  outgoingResults(
356
379
  {
@@ -4,6 +4,7 @@
4
4
  * a non-admin may only hand out groups and start nodes they hold themselves,
5
5
  * and nobody deletes or disables their own account.
6
6
  */
7
+
7
8
  import type {
8
9
  NodeLookup,
9
10
  Principal,
@@ -51,6 +52,7 @@ import {
51
52
  UserRepository,
52
53
  userState,
53
54
  } from '@crombolo/data'
55
+ import type { SchemaUserGroup } from '@crombolo/schema'
54
56
  import { loadAccess } from '../access.ts'
55
57
  import type { CromboloConfig } from '../config.ts'
56
58
  import type { MediaFileStore } from '../media-files.ts'
@@ -117,6 +119,8 @@ export interface UserPortOptions {
117
119
  >
118
120
  mediaFiles: MediaFileStore
119
121
  nodes: NodeLookup
122
+ /** The groups the site's files declare (story 228). */
123
+ declaredGroups?: () => DeclaredGroups
120
124
  /** Signs a user out everywhere, as a password change set by someone else does. */
121
125
  endSessions: (userId: number) => Promise<void>
122
126
  /** A group save changed what it may do on these pages (story 045: the "rights" notification). */
@@ -665,6 +669,7 @@ export function createUserPorts(
665
669
  adminKey,
666
670
  nodes,
667
671
  onPagePermissionsChanged: options.onPagePermissionsChanged,
672
+ declared: options.declaredGroups,
668
673
  }),
669
674
  userData: createUserDataPort(db),
670
675
  }
@@ -765,21 +770,63 @@ function fromPermissions(permissions: UserGroupInput['permissions']): GranularPe
765
770
  return rows
766
771
  }
767
772
 
773
+ /** The user groups the site's files declare (story 228), and whether a save may write one back. */
774
+ export interface DeclaredGroups {
775
+ /** By lower-case alias. */
776
+ groups: ReadonlyMap<string, SchemaUserGroup>
777
+ /** Development: a save writes the file. Elsewhere the files' fields are read-only. */
778
+ writable: boolean
779
+ write(group: SchemaUserGroup): void
780
+ }
781
+
782
+ /** What a group's file holds, from what the Users section sent. */
783
+ function fileFieldsOf(input: UserGroupInput): SchemaUserGroup {
784
+ return {
785
+ alias: input.alias,
786
+ name: input.name,
787
+ ...(input.description ? { description: input.description } : {}),
788
+ ...(input.icon ? { icon: input.icon } : {}),
789
+ sections: input.sections.map(sectionAppAlias),
790
+ permissions: [...input.fallbackPermissions],
791
+ languages: input.hasAccessToAllLanguages ? 'all' : [...input.languages],
792
+ }
793
+ }
794
+
795
+ const sameMembers = (a: readonly string[], b: readonly string[]) =>
796
+ a.length === b.length && a.every((item) => b.includes(item))
797
+
798
+ /** Whether two groups' file-owned fields agree. */
799
+ function sameFileFields(a: SchemaUserGroup, b: SchemaUserGroup): boolean {
800
+ return (
801
+ a.name === b.name &&
802
+ (a.description ?? '') === (b.description ?? '') &&
803
+ (a.icon ?? '') === (b.icon ?? '') &&
804
+ sameMembers(a.sections, b.sections) &&
805
+ sameMembers(a.permissions, b.permissions) &&
806
+ (a.languages === 'all' || b.languages === 'all'
807
+ ? a.languages === b.languages
808
+ : sameMembers(a.languages, b.languages))
809
+ )
810
+ }
811
+
768
812
  function createUserGroupPort(
769
813
  db: Db,
770
814
  deps: {
771
815
  adminKey: () => Promise<string | undefined>
772
816
  nodes: NodeLookup
773
817
  onPagePermissionsChanged?: UserPortOptions['onPagePermissionsChanged']
818
+ declared?: () => DeclaredGroups
774
819
  },
775
820
  ): UserGroupPort {
821
+ const fileOf = (alias: string) => deps.declared?.().groups.get(alias.toLowerCase())
776
822
  const groups = new UserGroupRepository(db)
777
823
  const users = new UserRepository(db)
778
824
 
779
825
  const toResponse = async (group: Awaited<ReturnType<UserGroupRepository['byKey']>> & object) => ({
780
826
  id: group.key,
781
- isDeletable: !SYSTEM_GROUPS.has(group.alias),
782
- aliasCanBeChanged: !SYSTEM_GROUPS.has(group.alias),
827
+ // A group from the site's files is the files' to rename or remove (story 228).
828
+ isDeletable: !SYSTEM_GROUPS.has(group.alias) && !fileOf(group.alias),
829
+ aliasCanBeChanged: !SYSTEM_GROUPS.has(group.alias) && !fileOf(group.alias),
783
830
  name: group.name,
784
831
  alias: group.alias,
785
832
  description: group.description,
@@ -954,9 +1001,18 @@ function createUserGroupPort(
954
1001
  if (!isMember(principal, group.key)) return 'Forbidden'
955
1002
  const valid = await validate(principal, input, group)
956
1003
  if (valid !== 'Success') return valid
1004
+ // Story 228: its file owns what it is; where it starts is this environment's.
1005
+ const file = fileOf(group.alias)
1006
+ const owned = fileFieldsOf(input)
1007
+ const rewrite = file !== undefined && !sameFileFields(owned, file)
1008
+ if (file && (input.alias !== group.alias || (rewrite && !deps.declared?.().writable)))
1009
+ return 'DeclaredInFiles'
957
1010
  const before = pageVerbs(group)
958
1011
  const saved = await save(input, group.key)
959
- if (saved === 'Success') await announcePermissions(principal, before, group.key)
1012
+ if (saved === 'Success') {
1013
+ if (rewrite) deps.declared?.().write(owned)
1014
+ await announcePermissions(principal, before, group.key)
1015
+ }
960
1016
  return saved
961
1017
  },
962
1018
 
@@ -965,6 +1021,7 @@ function createUserGroupPort(
965
1021
  if (found.length !== new Set(keys.map(normaliseUuid)).size) return 'NotFound'
966
1022
  if (!found.every((g) => isMember(principal, g.key))) return 'Forbidden'
967
1023
  if (found.some((g) => SYSTEM_GROUPS.has(g.alias))) return 'IsSystemUserGroup'
1024
+ if (found.some((g) => fileOf(g.alias))) return 'DeclaredInFiles'
968
1025
  for (const group of found) await groups.delete(group.key)
969
1026
  return 'Success'
970
1027
  },
package/src/config.ts CHANGED
@@ -216,6 +216,12 @@ export interface CromboloConfig {
216
216
  * finding. docs/rendering.md, "Route handlers".
217
217
  */
218
218
  routes?: SiteRoute<SiteServices, RequestMember>[]
219
+ /**
220
+ * The site's server actions (story 219), a module at a time:
221
+ * `actions: { profile }` after `import * as profile from '#actions/profile.ts'`.
222
+ * Each export is an action, `profile.save`. docs/rendering.md, "Server actions".
223
+ */
224
+ actions?: Record<string, Record<string, unknown>>
219
225
  /** How long a route handler may take before it answers 504; 0 for no limit. */
220
226
  routeTimeoutMs: number
221
227
  /** Requests a minute each caller may make to the site's routes, on each server; 0 for no limit. */
@@ -976,7 +982,7 @@ export function describeDatabase(
976
982
  }
977
983
  }
978
984
 
979
- export const VERSION = '0.39.1'
985
+ export const VERSION = '0.41.1'
980
986
 
981
987
  /** A whole number of seconds from the environment; undefined when unset or not one. */
982
988
  /** A positive number from a setting, else the default. */
@@ -166,39 +166,62 @@ interface Flash extends FormSubmissionState {
166
166
  }
167
167
 
168
168
  export function writeFlash(secret: string, state: FormSubmissionState): string {
169
- const payload: Flash = { ...state, at: Date.now() }
170
- let json = JSON.stringify(payload)
171
- if (json.length > MAX_FLASH_BYTES)
172
- // The messages matter more than redisplaying what was typed, and a cookie
173
- // the browser silently drops would lose both.
174
- json = JSON.stringify({ ...payload, values: {} })
169
+ // The messages matter more than redisplaying what was typed, and a cookie
170
+ // the browser silently drops would lose both.
171
+ return writeSignedFlash(secret, state, [{ values: {} }])
172
+ }
173
+
174
+ /**
175
+ * A signed, timestamped flash cookie's value, trimmed by each of `fallbacks`
176
+ * in turn while it is over the size a cookie can safely hold. Core forms' and
177
+ * server actions' (story 219).
178
+ */
179
+ export function writeSignedFlash(
180
+ secret: string,
181
+ payload: object,
182
+ fallbacks: readonly object[] = [],
183
+ ): string {
184
+ let current = { ...payload, at: Date.now() }
185
+ let json = JSON.stringify(current)
186
+ for (const trim of fallbacks) {
187
+ if (json.length <= MAX_FLASH_BYTES) break
188
+ current = { ...current, ...trim }
189
+ json = JSON.stringify(current)
190
+ }
175
191
  const body = Buffer.from(json).toString('base64url')
176
192
  return `${body}.${hmac(secret, body)}`
177
193
  }
178
194
 
179
- export function readFlash(
180
- secret: string,
181
- cookie: string | undefined,
182
- ): FormSubmissionState | undefined {
195
+ /** A flash cookie's payload when its signature holds and it is fresh. */
196
+ export function readSignedFlash<T>(secret: string, cookie: string | undefined): T | undefined {
183
197
  if (!cookie) return undefined
184
198
  const [body, signature] = cookie.split('.')
185
199
  if (!body || !signature) return undefined
186
200
  if (!sameSignature(hmac(secret, body), signature)) return undefined
187
201
  try {
188
- const parsed = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as Flash
202
+ const parsed = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as T & { at: number }
189
203
  if (Date.now() - parsed.at > FLASH_SECONDS * 1000) return undefined
190
- return {
191
- formKey: parsed.formKey,
192
- formAlias: parsed.formAlias,
193
- values: parsed.values ?? {},
194
- errors: parsed.errors ?? [],
195
- message: parsed.message,
196
- }
204
+ return parsed
197
205
  } catch {
198
206
  return undefined
199
207
  }
200
208
  }
201
209
 
210
+ export function readFlash(
211
+ secret: string,
212
+ cookie: string | undefined,
213
+ ): FormSubmissionState | undefined {
214
+ const parsed = readSignedFlash<Flash>(secret, cookie)
215
+ if (!parsed) return undefined
216
+ return {
217
+ formKey: parsed.formKey,
218
+ formAlias: parsed.formAlias,
219
+ values: parsed.values ?? {},
220
+ errors: parsed.errors ?? [],
221
+ message: parsed.message,
222
+ }
223
+ }
224
+
202
225
  // ------------------------------------------------------------------ the submission
203
226
 
204
227
  export interface FormSubmitDeps {
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { createNodeLookup } from './access.ts'
2
+ export * from './actions.ts'
2
3
  export * from './adapters/audit.ts'
3
4
  export * from './adapters/blueprints.ts'
4
5
  export * from './adapters/bundles.ts'
@@ -93,6 +94,7 @@ export * from './remote-credentials.ts'
93
94
  export * from './remote-media.ts'
94
95
  export * from './routes.ts'
95
96
  export * from './schema.ts'
97
+ export * from './schema-picks.ts'
96
98
  export * from './schema-store.ts'
97
99
  export * from './secrets.ts'
98
100
  export * from './seed/index.ts'
package/src/islands.ts CHANGED
@@ -10,7 +10,7 @@ import { ISLANDS_DIR, ISLANDS_PATH, type IslandManifest } from '@crombolo/render
10
10
 
11
11
  /** What a client module may not import: code that only runs on the server. */
12
12
  const SERVER_ONLY =
13
- /^(@crombolo\/(crombolo|render|server|core|data|content|auth|schema|transfer|api-delivery|api-management)(\/.*)?|node:.*|bun(:.*)?)$/
13
+ /^(@crombolo\/(crombolo|render|server|core|data|content|auth|schema|transfer|api-delivery|api-management)(\/.*)?|#actions\/.*|node:.*|bun(:.*)?)$/
14
14
  /** Whether a client module importing this would pull server code into the browser. */
15
15
  export const isServerOnly = (specifier: string): boolean =>
16
16
  SERVER_ONLY.test(specifier) && specifier !== BROWSER_ENTRY
package/src/ports.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  /** Implementations of the Management API ports. */
2
2
 
3
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
4
+ import { join } from 'node:path'
3
5
  import { resolveDeliveryApiSettings } from '@crombolo/api-delivery'
4
6
  import type {
5
7
  CurrentUserPort,
@@ -40,6 +42,7 @@ import {
40
42
  UserRepository,
41
43
  } from '@crombolo/data'
42
44
  import type { PublishedCache } from '@crombolo/render'
45
+ import { fileNameFor, parseUserGroup, type SchemaUserGroup, writeUserGroup } from '@crombolo/schema'
43
46
  import { createNodeLookup } from './access.ts'
44
47
  import { createAuditHistory } from './adapters/audit.ts'
45
48
  import { createBlueprintPort } from './adapters/blueprints.ts'
@@ -70,7 +73,7 @@ import {
70
73
  import { createSearchIndexPort } from './adapters/search-index.ts'
71
74
  import { createTemplateFileStore } from './adapters/template-files.ts'
72
75
  import { createTemplateQueryPort } from './adapters/template-query.ts'
73
- import { avatarUrls, createUserPorts } from './adapters/users.ts'
76
+ import { avatarUrls, createUserPorts, type DeclaredGroups } from './adapters/users.ts'
74
77
  import { createWebhookPort } from './adapters/webhooks.ts'
75
78
  import { backOfficeUrl } from './back-office-url.ts'
76
79
  import { COMPONENT_SNIPPETS } from './component-snippets.ts'
@@ -353,6 +356,9 @@ export function resolveUserLinkSender(
353
356
  export interface DepsOptions {
354
357
  /** Published pages a site route answers in place of, for the health check (story 211). */
355
358
  hiddenByRoutes?: () => Promise<Array<{ route: string; owner: string; page: string; url: string }>>
359
+ siteSettingsFindings?: () => Promise<
360
+ Array<{ kind: 'second' | 'deep'; name: string; counted?: string }>
361
+ >
356
362
  config: CromboloConfig
357
363
  paths: BackOfficePaths
358
364
  /** The site's installed npm extensions, which contribute their manifests. */
@@ -481,6 +487,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
481
487
  nodeState: options.schema?.nodeState,
482
488
  fetch: options.fetch,
483
489
  hiddenByRoutes: options.hiddenByRoutes,
490
+ siteSettingsFindings: options.siteSettingsFindings,
484
491
  })
485
492
  const tags = new TagRepository(options.db)
486
493
  deps.tags = { list: (filter) => tags.all(filter) }
@@ -493,6 +500,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
493
500
  },
494
501
  mediaFiles,
495
502
  nodes: createNodeLookup(options.db),
503
+ declaredGroups: () => declaredGroups(options.config),
496
504
  endSessions: async (userId) => {
497
505
  await store.endAllSessionsForUser(userId)
498
506
  },
@@ -613,6 +621,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
613
621
  components: deps.components,
614
622
  stylesheets: deps.stylesheets,
615
623
  scripts: deps.scripts,
624
+ schemaDir: options.config.schemaDir,
616
625
  })
617
626
  deps.auditHistory = createAuditHistory(options.db, options.config.auditRetentionDays)
618
627
  if (options.cache) {
@@ -703,3 +712,32 @@ function userTwoFactorPort(service: TwoFactorService): UserTwoFactorPort {
703
712
 
704
713
  export { schemaFiles } from './adapters/schema-files.ts'
705
714
  export { backOfficeUrl, documentEditUrl } from './back-office-url.ts'
715
+
716
+ /**
717
+ * The user groups `schema/user-groups/` declares (story 228), read when a group
718
+ * is saved, and written back where the schema files are writable.
719
+ */
720
+ function declaredGroups(
721
+ config: Pick<CromboloConfig, 'schemaDir' | 'schemaWritable'>,
722
+ ): DeclaredGroups {
723
+ const dir = join(config.schemaDir, 'user-groups')
724
+ const groups = new Map<string, SchemaUserGroup>()
725
+ const fileOf = new Map<string, string>()
726
+ if (existsSync(dir))
727
+ for (const name of readdirSync(dir).filter((file) => file.endsWith('.toml'))) {
728
+ const parsed = parseUserGroup(name, readFileSync(join(dir, name), 'utf8'))
729
+ if (!parsed.value) continue
730
+ groups.set(parsed.value.alias.toLowerCase(), parsed.value)
731
+ fileOf.set(parsed.value.alias.toLowerCase(), name)
732
+ }
733
+ return {
734
+ groups,
735
+ writable: config.schemaWritable,
736
+ write(group) {
737
+ mkdirSync(dir, { recursive: true })
738
+ // Back into the file it came from, whatever that file is called.
739
+ const name = fileOf.get(group.alias.toLowerCase()) ?? fileNameFor(group.alias)
740
+ writeFileSync(join(dir, name), writeUserGroup(group))
741
+ },
742
+ }
743
+ }
package/src/routes.ts CHANGED
@@ -117,10 +117,10 @@ const prefersHtml = (request: Request) => {
117
117
  return html >= 0 && (json < 0 || html < json)
118
118
  }
119
119
 
120
- /** Builds the site's route pipeline over its routes and its bundles'. */
121
120
  /** Why a route's signal is aborted once its answer has been sent. */
122
121
  const ANSWERED = new Error('The answer has been sent.')
123
122
 
123
+ /** Builds the site's route pipeline over its routes and its bundles'. */
124
124
  export function createRoutes<Member extends RouteMember>(
125
125
  declared: readonly DeclaredRoute[],
126
126
  deps: RouteDeps<Member>,
@@ -0,0 +1,87 @@
1
+ /**
2
+ * What a created bundle carries of the site's forms, approval workflows and
3
+ * user groups (story 226): what its author picked, and what those bring. A
4
+ * workflow brings the document types it covers and the groups its stages
5
+ * name; a form brings the document type its "save as content" step creates.
6
+ * What its author unticked stays out. docs/bundles.md, "The Bundle Editor".
7
+ */
8
+ import { readFileSync } from 'node:fs'
9
+ import { relative, sep } from 'node:path'
10
+ import type { BundleSchemaPicks } from '@crombolo/data'
11
+ import type { LoadedSchema, SchemaSet } from '@crombolo/schema'
12
+ import type { BundleFile } from '@crombolo/transfer'
13
+
14
+ export type SchemaPickKind = 'form' | 'workflow' | 'userGroup' | 'documentType'
15
+
16
+ /** One thing a bundle carries, and why: picked, or brought by a pick. */
17
+ export interface CarriedPick {
18
+ kind: SchemaPickKind
19
+ alias: string
20
+ /** Absent for what was picked; the pick that brought it, otherwise. */
21
+ for?: { kind: SchemaPickKind; alias: string; name: string }
22
+ /** Brought by a pick and unticked: it is not carried. */
23
+ excluded?: boolean
24
+ }
25
+
26
+ const id = (kind: SchemaPickKind, alias: string) => `${kind}:${alias}`.toLowerCase()
27
+
28
+ /** Everything the picks carry, and what they would have brought and were unticked. Pure. */
29
+ export function carriedPicks(set: SchemaSet, picks: BundleSchemaPicks): CarriedPick[] {
30
+ const out: CarriedPick[] = []
31
+ const seen = new Set<string>()
32
+ const excluded = new Set(picks.excluded.map((entry) => entry.toLowerCase()))
33
+ const add = (pick: CarriedPick) => {
34
+ const key = id(pick.kind, pick.alias)
35
+ if (seen.has(key)) return
36
+ seen.add(key)
37
+ out.push(pick.for && excluded.has(key) ? { ...pick, excluded: true } : pick)
38
+ }
39
+ for (const alias of picks.forms) add({ kind: 'form', alias })
40
+ for (const alias of picks.workflows) add({ kind: 'workflow', alias })
41
+ for (const alias of picks.userGroups) add({ kind: 'userGroup', alias })
42
+ for (const alias of picks.workflows) {
43
+ const workflow = (set.workflows ?? []).find(
44
+ (w) => w.alias.toLowerCase() === alias.toLowerCase(),
45
+ )
46
+ if (!workflow) continue
47
+ const by = { kind: 'workflow' as const, alias: workflow.alias, name: workflow.name }
48
+ for (const type of workflow.appliesTo.contentTypes)
49
+ add({ kind: 'documentType', alias: type, for: by })
50
+ for (const stage of workflow.stages)
51
+ for (const group of stage.approvers) add({ kind: 'userGroup', alias: group, for: by })
52
+ }
53
+ for (const alias of picks.forms) {
54
+ const form = (set.forms ?? []).find((f) => f.alias.toLowerCase() === alias.toLowerCase())
55
+ if (!form) continue
56
+ const by = { kind: 'form' as const, alias: form.alias, name: form.name }
57
+ for (const step of form.workflows)
58
+ if (step.type === 'saveAsContent' && typeof step.settings['content-type'] === 'string')
59
+ add({ kind: 'documentType', alias: step.settings['content-type'], for: by })
60
+ }
61
+ return out
62
+ }
63
+
64
+ const FILE_KEY: Record<SchemaPickKind, (alias: string) => string> = {
65
+ form: (alias) => `form:${alias}`,
66
+ workflow: (alias) => `workflow:${alias}`,
67
+ userGroup: (alias) => `user-group:${alias}`,
68
+ documentType: (alias) => alias,
69
+ }
70
+
71
+ /** The site's own files for what is carried, at their `schema/` paths. */
72
+ export function schemaPickFiles(
73
+ loaded: Pick<LoadedSchema, 'files'>,
74
+ schemaDir: string,
75
+ carried: readonly CarriedPick[],
76
+ read: (file: string) => string = (file) => readFileSync(file, 'utf8'),
77
+ ): BundleFile[] {
78
+ const files: BundleFile[] = []
79
+ for (const pick of carried) {
80
+ if (pick.excluded) continue
81
+ const file = loaded.files.get(FILE_KEY[pick.kind](pick.alias))
82
+ if (!file?.startsWith(schemaDir)) continue
83
+ const rel = relative(schemaDir, file).split(sep).join('/')
84
+ files.push({ path: `schema/${rel}`, text: read(file) })
85
+ }
86
+ return files
87
+ }
@@ -321,11 +321,30 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
321
321
  case 'Umbraco.Slider':
322
322
  return typeof raw === 'number' ? { ok: true, value: raw } : fail('a number is a number')
323
323
  case 'Umbraco.DateTime':
324
- case 'Umbraco.DateTimeWithTimeZone':
325
- if (raw instanceof Date) return { ok: true, value: raw.toISOString() }
326
- return typeof raw === 'string' && !Number.isNaN(new Date(raw).getTime())
327
- ? { ok: true, value: raw }
328
- : fail('a date is a TOML date or an ISO 8601 string')
324
+ case 'Umbraco.DateTimeWithTimeZone': {
325
+ // Bun's TOML gives a Temporal value (a PlainDate, an Instant) for a TOML
326
+ // date, which writes itself as ISO 8601.
327
+ const text =
328
+ raw instanceof Date
329
+ ? raw.toISOString()
330
+ : isTemporalDate(raw)
331
+ ? String(raw)
332
+ : typeof raw === 'string'
333
+ ? raw
334
+ : undefined
335
+ const at = text === undefined ? Number.NaN : new Date(text).getTime()
336
+ if (text === undefined || Number.isNaN(at))
337
+ return fail('a date is a TOML date or an ISO 8601 string')
338
+ // A date picker stores Umbraco's wall clock, as a save does, so a seed
339
+ // exported and applied again is unchanged; one with a zone keeps ISO.
340
+ return {
341
+ ok: true,
342
+ value:
343
+ editor === 'Umbraco.DateTime'
344
+ ? new Date(at).toISOString().slice(0, 19).replace('T', ' ')
345
+ : text,
346
+ }
347
+ }
329
348
  case 'Umbraco.Tags':
330
349
  return list(raw).every((tag) => typeof tag === 'string')
331
350
  ? { ok: true, value: list(raw) }
@@ -746,3 +765,10 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
746
765
  })
747
766
  return { findings, set, blobs, files, counts }
748
767
  }
768
+
769
+ /** A TOML date as Bun's parser gives it: a Temporal value whose ISO form is a date. */
770
+ function isTemporalDate(raw: unknown): boolean {
771
+ if (typeof raw !== 'object' || raw === null || raw instanceof Date) return false
772
+ const text = String(raw)
773
+ return /^\d{4}-\d{2}-\d{2}/.test(text) && !Number.isNaN(new Date(text).getTime())
774
+ }
package/src/server.ts CHANGED
@@ -128,8 +128,17 @@ import type { SyncReport } from '@crombolo/schema'
128
128
  import { choicesFor } from '@crombolo/transfer'
129
129
  import type { Server } from 'bun'
130
130
  import { createNodeLookup, loadAccess } from './access.ts'
131
+ import { ACTION_FLASH_COOKIE, actionRegistry, actionRoutes } from './actions.ts'
131
132
  import { createAuditHost, createAuditSink, pluginAuditPlan, recordAudit } from './adapters/audit.ts'
132
- import { readCreatedBundlePackage, writeCreatedBundlePackage } from './adapters/bundles.ts'
133
+ import {
134
+ carriedSchemaPicks,
135
+ readCreatedBundlePackage,
136
+ readSchemaPicks,
137
+ schemaPickChoices,
138
+ schemaPicksOf,
139
+ writeCreatedBundlePackage,
140
+ writeSchemaPicks,
141
+ } from './adapters/bundles.ts'
133
142
  import { createPublishedContentSource, loadDraftNode } from './adapters/documents.ts'
134
143
  import type { Approvals } from './approvals.ts'
135
144
  import { handleApprovalsApi } from './approvals-api.ts'
@@ -199,7 +208,7 @@ import type { JobsStatus } from './worker-watch.ts'
199
208
 
200
209
  export { PREVIEW_COOKIE }
201
210
 
202
- import type { SiteRoute } from '@crombolo/common'
211
+ import { ACTIONS_PATH, type SiteRoute } from '@crombolo/common'
203
212
  import { backofficeAudience } from './backoffice-external.ts'
204
213
  import { createExternalSignIn } from './external-sign-in.ts'
205
214
  import { IdentityProviderOverrides } from './identity-provider-overrides.ts'
@@ -970,6 +979,12 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
970
979
  cors: formCors,
971
980
  })
972
981
 
982
+ // Story 219: the site's server actions, a module at a time.
983
+ const { registry: actionList, problems: actionProblems } = actionRegistry(config.actions)
984
+ if (actionProblems.length > 0)
985
+ throw new Error(`The site's actions cannot be mounted:\n- ${actionProblems.join('\n- ')}`)
986
+ const siteActions = actionRoutes(actionList, formSecret, config.secureCookies)
987
+
973
988
  const notImplementedLog = logger('not-implemented')
974
989
  const notImplemented = new NotImplementedLog((line, entry) => {
975
990
  // The console line is the development aid; the file keeps it for the log viewer
@@ -1006,6 +1021,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1006
1021
  const managementDeps = createDeps({
1007
1022
  config,
1008
1023
  paths,
1024
+ siteSettingsFindings: () => cache.settingsFindings(),
1009
1025
  hiddenByRoutes: async () => {
1010
1026
  const snapshot = await cache.snapshot()
1011
1027
  const hidden: Array<{ route: string; owner: string; page: string; url: string }> = []
@@ -1266,6 +1282,14 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1266
1282
  if (response) return response
1267
1283
  }
1268
1284
 
1285
+ // Story 219: a server action, answered where the site is, through the routes' pipeline.
1286
+ if (pathname.startsWith(`${ACTIONS_PATH}/`)) {
1287
+ const action = config.role === 'api' ? undefined : siteActions.match(pathname)
1288
+ return action
1289
+ ? siteRoutes.invoke(action, request, url, {})
1290
+ : new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } })
1291
+ }
1292
+
1269
1293
  // Islands (story 209): the loader, and each generation's browser code.
1270
1294
  if (pathname === ISLAND_LOADER_PATH)
1271
1295
  return new Response(ISLAND_LOADER_SCRIPT, {
@@ -1713,6 +1737,28 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1713
1737
  }
1714
1738
  }
1715
1739
 
1740
+ // A created bundle's forms, workflows and user groups (story 226): the
1741
+ // site's files to choose from, what a choice brings, and the choice.
1742
+ if (action === 'schema' && request.method === 'GET')
1743
+ return Response.json(schemaPickChoices(config.schemaDir))
1744
+ if (action === 'schema/carried' && request.method === 'POST') {
1745
+ const body = (await request.json().catch(() => ({}))) as Record<string, unknown>
1746
+ return Response.json({ carried: carriedSchemaPicks(config.schemaDir, schemaPicksOf(body)) })
1747
+ }
1748
+ const picked = /^created\/([0-9a-f-]{36})\/schema$/i.exec(action)
1749
+ if (picked) {
1750
+ const id = picked[1] as string
1751
+ if (request.method === 'GET') {
1752
+ const found = await readSchemaPicks(db, id)
1753
+ return found ? Response.json(found) : new Response('Not Found', { status: 404 })
1754
+ }
1755
+ if (request.method === 'PUT') {
1756
+ const body = (await request.json().catch(() => ({}))) as Record<string, unknown>
1757
+ const saved = await writeSchemaPicks(db, id, body)
1758
+ return saved ? Response.json(saved) : new Response('Not Found', { status: 404 })
1759
+ }
1760
+ }
1761
+
1716
1762
  if (action === 'installed' && request.method === 'GET') {
1717
1763
  return Response.json({
1718
1764
  installs: config.runtimeInstalls,
@@ -2863,7 +2909,25 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2863
2909
  })
2864
2910
  }
2865
2911
 
2912
+ /** A page, and an action's flash cleared once it has been read (story 219). */
2866
2913
  async function renderPage(request: Request, pathname: string, host: string): Promise<Response> {
2914
+ const response = await renderPageOnce(request, pathname, host)
2915
+ if (!readCookie(request, ACTION_FLASH_COOKIE)) return response
2916
+ // Rebuilt rather than changed: a redirect's headers cannot be.
2917
+ const headers = new Headers(response.headers)
2918
+ headers.append('set-cookie', expireCookie(ACTION_FLASH_COOKIE, config.secureCookies))
2919
+ return new Response(response.body, {
2920
+ status: response.status,
2921
+ statusText: response.statusText,
2922
+ headers,
2923
+ })
2924
+ }
2925
+
2926
+ async function renderPageOnce(
2927
+ request: Request,
2928
+ pathname: string,
2929
+ host: string,
2930
+ ): Promise<Response> {
2867
2931
  const preview = await renderPreview(request, pathname, host)
2868
2932
  // An `api` node renders for preview and nothing else. The backoffice opens a
2869
2933
  // site URL to preview a draft, so the renderer has to be here; serving the
@@ -2880,18 +2944,22 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2880
2944
  // cleared, so a reload shows the page rather than the thank-you again.
2881
2945
  const cookie = readCookie(request, FORM_FLASH_COOKIE)
2882
2946
  const submission = cookie ? readFlash(formSecret, cookie) : undefined
2947
+ // What a server action answered the visitor with (story 219), read once as well.
2948
+ const actionCookie = readCookie(request, ACTION_FLASH_COOKIE)
2949
+ const actionFlash = siteActions.readFlash(actionCookie)
2883
2950
  // A page that is not the same for everyone is never kept: a member's, a
2884
2951
  // preview, a form's answer, or anything in a members-only branch — which a
2885
2952
  // visitor sees as the login page, at the same address.
2886
2953
  // Whether the page itself read anything personal, the member included, it
2887
2954
  // says in its result (story 206).
2888
- let personal = Boolean(preview || submission || cookie)
2955
+ let personal = Boolean(preview || submission || cookie || actionCookie)
2889
2956
  const result =
2890
2957
  preview ??
2891
2958
  (await renderer.render(pathname, host, {
2892
2959
  member,
2893
2960
  antiforgery: session?.antiforgery,
2894
2961
  submission,
2962
+ actions: { idOf: actionList.idOf, flash: actionFlash },
2895
2963
  access: async (content) => {
2896
2964
  if ((await members.decide(content, undefined)).status !== 'allowed') personal = true
2897
2965
  return members.decide(content, member)