@crombolo/server 0.63.0 → 0.65.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.
@@ -5,18 +5,21 @@
5
5
  * `content` commands read `--set`; and stored values back into that shorthand,
6
6
  * as `content export` and `content show` write them.
7
7
  */
8
- import { type ContentTypeAggregate, dateFromText, normaliseUuid } from '@crombolo/core'
8
+ import {
9
+ type Block,
10
+ type ContentTypeAggregate,
11
+ dateFromText,
12
+ isBlockValue,
13
+ normaliseUuid,
14
+ readBlocks,
15
+ SINGLE_BLOCK_EDITOR_ALIAS,
16
+ } from '@crombolo/core'
9
17
  import { ContentTypeRepository, DataTypeRepository, type Db, looksLikeKey } from '@crombolo/data'
10
18
  import { blockKey, pickKey } from './keys.ts'
11
19
 
12
20
  const isRecord = (value: unknown): value is Record<string, unknown> =>
13
21
  typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date)
14
22
 
15
- const BLOCK_LAYOUT = {
16
- 'Umbraco.BlockList': 'Umbraco.BlockList',
17
- 'Umbraco.BlockGrid': 'Umbraco.BlockGrid',
18
- } as const
19
-
20
23
  /** A block's alias: a name a view or a command picks it out by (story 253). */
21
24
  export const BLOCK_ALIAS = /^[A-Za-z][A-Za-z0-9_-]*$/
22
25
 
@@ -136,58 +139,91 @@ export function valueWriter(lookup: SchemaLookup, refs: ValueRefs) {
136
139
  return { ok: true, data: { key, contentTypeKey: type.key, values: values.value } }
137
140
  }
138
141
 
142
+ /**
143
+ * Blocks from their shorthand: a list of `{ type, alias, values, settings }`,
144
+ * a grid block's `areas` as `[{ key, blocks = [ … ] }]`, and a Single Block's one
145
+ * block as a table (story 345). A value already in the stored shape passes.
146
+ */
139
147
  const blocks = async (
140
- editor: keyof typeof BLOCK_LAYOUT,
148
+ editor: string,
141
149
  raw: unknown,
142
150
  owner: string,
143
151
  where: string,
144
152
  ): Promise<Converted> => {
153
+ const single = editor === SINGLE_BLOCK_EDITOR_ALIAS
154
+ if (isRecord(raw) && 'layout' in raw) return { ok: true, value: raw }
155
+ if (single && isRecord(raw)) raw = [raw]
156
+ if (single && (raw === null || raw === undefined)) raw = []
145
157
  if (!Array.isArray(raw)) {
146
- if (isRecord(raw) && 'layout' in raw) return { ok: true, value: raw }
147
- return fail('blocks are a list of { type = "<element alias>", values = { … } }')
158
+ return fail(
159
+ single
160
+ ? 'a Single Block is one { type = "<element alias>", values = { … } }'
161
+ : 'blocks are a list of { type = "<element alias>", values = { … } }',
162
+ )
148
163
  }
149
- const layout: Record<string, unknown>[] = []
164
+ if (single && raw.length > 1) return fail('a Single Block holds one block')
150
165
  const contentData: unknown[] = []
151
166
  const settingsData: unknown[] = []
152
- const aliases = new Set<string>()
153
- for (const [index, entry] of raw.entries()) {
154
- if (!isRecord(entry)) return fail(`block ${index + 1} has no type`)
155
- const content = await element(entry, owner, `${where}/${index}`, `block ${index + 1}`)
156
- if (!content.ok) return fail(content.message)
157
- contentData.push(content.data)
158
- const item: Record<string, unknown> = { contentKey: content.data.key }
159
- if (entry.alias !== undefined) {
160
- if (typeof entry.alias !== 'string' || !BLOCK_ALIAS.test(entry.alias))
161
- return fail(
162
- `block ${index + 1}: an alias is letters, digits, - and _, starting with a letter`,
167
+ const entries = async (
168
+ list: unknown[],
169
+ path: string,
170
+ label: string,
171
+ ): Promise<Record<string, unknown>[] | string> => {
172
+ const layout: Record<string, unknown>[] = []
173
+ const aliases = new Set<string>()
174
+ for (const [index, entry] of list.entries()) {
175
+ const name = `${label}${index + 1}`
176
+ if (!isRecord(entry)) return `block ${name} has no type`
177
+ const content = await element(entry, owner, `${path}/${index}`, `block ${name}`)
178
+ if (!content.ok) return content.message
179
+ contentData.push(content.data)
180
+ const item: Record<string, unknown> = { contentKey: content.data.key }
181
+ if (entry.alias !== undefined) {
182
+ if (typeof entry.alias !== 'string' || !BLOCK_ALIAS.test(entry.alias))
183
+ return `block ${name}: an alias is letters, digits, - and _, starting with a letter`
184
+ if (aliases.has(entry.alias.toLowerCase()))
185
+ return `two blocks are called "${entry.alias}"`
186
+ aliases.add(entry.alias.toLowerCase())
187
+ item.alias = entry.alias
188
+ }
189
+ if (isRecord(entry.settings)) {
190
+ const settings = await element(
191
+ entry.settings,
192
+ owner,
193
+ `${path}/${index}/settings`,
194
+ `block ${name} settings`,
163
195
  )
164
- if (aliases.has(entry.alias.toLowerCase()))
165
- return fail(`two blocks are called "${entry.alias}"`)
166
- aliases.add(entry.alias.toLowerCase())
167
- item.alias = entry.alias
168
- }
169
- if (isRecord(entry.settings)) {
170
- const settings = await element(
171
- entry.settings,
172
- owner,
173
- `${where}/${index}/settings`,
174
- `block ${index + 1} settings`,
175
- )
176
- if (!settings.ok) return fail(settings.message)
177
- settingsData.push(settings.data)
178
- item.settingsKey = settings.data.key
179
- }
180
- if (editor === 'Umbraco.BlockGrid') {
181
- item.columnSpan = typeof entry.columns === 'number' ? entry.columns : 12
182
- item.rowSpan = typeof entry.rows === 'number' ? entry.rows : 1
183
- item.areas = Array.isArray(entry.areas) ? entry.areas : []
196
+ if (!settings.ok) return settings.message
197
+ settingsData.push(settings.data)
198
+ item.settingsKey = settings.data.key
199
+ }
200
+ if (editor === 'Umbraco.BlockGrid') {
201
+ item.columnSpan = typeof entry.columns === 'number' ? entry.columns : 12
202
+ item.rowSpan = typeof entry.rows === 'number' ? entry.rows : 1
203
+ const areas: unknown[] = []
204
+ for (const [a, area] of (Array.isArray(entry.areas) ? entry.areas : []).entries()) {
205
+ // An area already in the stored shape, as older files have it, passes.
206
+ if (!isRecord(area) || !Array.isArray(area.blocks)) {
207
+ areas.push(area)
208
+ continue
209
+ }
210
+ const items = await entries(
211
+ area.blocks,
212
+ `${path}/${index}/areas/${a}`,
213
+ `${name}.${String(area.key ?? a + 1)}.`,
214
+ )
215
+ if (typeof items === 'string') return items
216
+ areas.push({ key: area.key, items })
217
+ }
218
+ item.areas = areas
219
+ }
220
+ layout.push(item)
184
221
  }
185
- layout.push(item)
186
- }
187
- return {
188
- ok: true,
189
- value: { layout: { [BLOCK_LAYOUT[editor]]: layout }, contentData, settingsData },
222
+ return layout
190
223
  }
224
+ const layout = await entries(raw, where, '')
225
+ if (typeof layout === 'string') return fail(layout)
226
+ return { ok: true, value: { layout: { [editor]: layout }, contentData, settingsData } }
191
227
  }
192
228
 
193
229
  const elementValues = async (
@@ -352,6 +388,7 @@ export function valueWriter(lookup: SchemaLookup, refs: ValueRefs) {
352
388
  }
353
389
  case 'Umbraco.BlockList':
354
390
  case 'Umbraco.BlockGrid':
391
+ case SINGLE_BLOCK_EDITOR_ALIAS:
355
392
  return blocks(editor, raw, owner, where)
356
393
  default:
357
394
  return { ok: true, value: raw }
@@ -428,6 +465,7 @@ export function shorthandReader(
428
465
  }
429
466
  case 'Umbraco.BlockList':
430
467
  case 'Umbraco.BlockGrid':
468
+ case SINGLE_BLOCK_EDITOR_ALIAS:
431
469
  return blocks(editor, value)
432
470
  default:
433
471
  return value
@@ -453,49 +491,52 @@ export function shorthandReader(
453
491
  return link
454
492
  }
455
493
 
456
- /** Blocks as `{ type, alias, key, values, settings }`, when their layout is plain enough to say so. */
494
+ /**
495
+ * Blocks as `{ type, alias, key, values, settings }`, read through `readBlocks`
496
+ * (story 345): a grid block's areas as `[{ key, blocks }]`, and a Single Block as
497
+ * its one block, or nothing. A value whose blocks cannot all be said that way
498
+ * stays as it is stored.
499
+ */
457
500
  const blocks = async (editor: string, value: unknown): Promise<unknown> => {
458
- if (!isRecord(value) || !isRecord(value.layout) || !Array.isArray(value.contentData))
459
- return value
460
- const layout = value.layout[editor]
461
- if (!Array.isArray(layout)) return value
462
- const content = new Map(
463
- (value.contentData as unknown[]).filter(isRecord).map((d) => [String(d.key), d]),
464
- )
465
- const settings = new Map(
466
- ((value.settingsData as unknown[] | undefined) ?? [])
467
- .filter(isRecord)
468
- .map((d) => [String(d.key), d]),
469
- )
470
- const out: unknown[] = []
471
- for (const item of layout) {
472
- if (!isRecord(item)) return value
473
- const data = content.get(String(item.contentKey))
474
- if (!data || typeof data.contentTypeKey !== 'string') return value
475
- if (editor === 'Umbraco.BlockGrid' && Array.isArray(item.areas) && item.areas.length > 0)
476
- return value
477
- const entry: Record<string, unknown> = {
478
- type: await aliasOf(data.contentTypeKey),
479
- ...(typeof item.alias === 'string' ? { alias: item.alias } : {}),
480
- key: item.contentKey,
481
- values: await elementValues(data),
482
- }
483
- if (typeof item.settingsKey === 'string') {
484
- const setting = settings.get(item.settingsKey)
485
- if (!setting || typeof setting.contentTypeKey !== 'string') return value
486
- entry.settings = {
487
- type: await aliasOf(setting.contentTypeKey),
488
- key: item.settingsKey,
489
- values: await elementValues(setting),
501
+ if (!isBlockValue(value)) return value
502
+ const say = async (list: Block[]): Promise<unknown[] | undefined> => {
503
+ const out: unknown[] = []
504
+ for (const { layout, content, settings, areas } of list) {
505
+ if (!content || typeof content.contentTypeKey !== 'string') return undefined
506
+ const entry: Record<string, unknown> = {
507
+ type: await aliasOf(content.contentTypeKey),
508
+ ...(typeof layout.alias === 'string' ? { alias: layout.alias } : {}),
509
+ key: layout.contentKey,
510
+ values: await elementValues(content as unknown as Record<string, unknown>),
490
511
  }
512
+ if (typeof layout.settingsKey === 'string') {
513
+ if (!settings || typeof settings.contentTypeKey !== 'string') return undefined
514
+ entry.settings = {
515
+ type: await aliasOf(settings.contentTypeKey),
516
+ key: layout.settingsKey,
517
+ values: await elementValues(settings as unknown as Record<string, unknown>),
518
+ }
519
+ }
520
+ if (editor === 'Umbraco.BlockGrid') {
521
+ entry.columns = layout.columnSpan
522
+ entry.rows = layout.rowSpan
523
+ if (areas.length > 0) {
524
+ const said: unknown[] = []
525
+ for (const area of areas) {
526
+ const inner = await say(area.blocks)
527
+ if (!inner) return undefined
528
+ said.push({ key: area.key, blocks: inner })
529
+ }
530
+ entry.areas = said
531
+ }
532
+ }
533
+ out.push(entry)
491
534
  }
492
- if (editor === 'Umbraco.BlockGrid') {
493
- entry.columns = item.columnSpan
494
- entry.rows = item.rowSpan
495
- }
496
- out.push(entry)
535
+ return out
497
536
  }
498
- return out
537
+ const said = await say(readBlocks(value, editor))
538
+ if (!said) return value
539
+ return editor === SINGLE_BLOCK_EDITOR_ALIAS ? (said[0] ?? null) : said
499
540
  }
500
541
 
501
542
  const elementValues = async (data: Record<string, unknown>) => {
package/src/server.ts CHANGED
@@ -43,6 +43,7 @@ import {
43
43
  isSameOrigin,
44
44
  memberCookieName,
45
45
  REDACTED,
46
+ type ResolvedIdentity,
46
47
  readCookie,
47
48
  serializeCookie,
48
49
  } from '@crombolo/auth'
@@ -78,6 +79,7 @@ import {
78
79
  localReturnUrl,
79
80
  MANAGEMENT_API_PREFIX,
80
81
  managementApiPrefix,
82
+ normaliseUuid,
81
83
  ObjectTypes,
82
84
  PREVIEW_HUB_PATH,
83
85
  RemotePermissions,
@@ -85,6 +87,7 @@ import {
85
87
  } from '@crombolo/core'
86
88
  import {
87
89
  appendCacheInstruction,
90
+ currentAuditContext,
88
91
  type Db,
89
92
  ExtensionActivityLog,
90
93
  ensureFormLibraryTypes,
@@ -106,6 +109,7 @@ import {
106
109
  searchProvidersOf,
107
110
  TransferRunRepository,
108
111
  type WritesPaused,
112
+ withAuditContext,
109
113
  } from '@crombolo/data'
110
114
  import {
111
115
  BUNDLE_SCRIPT,
@@ -195,8 +199,9 @@ import { createDeliveryMemberSecurity } from './delivery-members.ts'
195
199
  import { handleDictionaryWords } from './dictionary-words-api.ts'
196
200
  import { syncDomainsFile } from './domains.ts'
197
201
  import { editorTypeLibs, siteJsxImportSource } from './editor-types.ts'
198
- import { emailAvailability } from './email.ts'
202
+ import { emailAvailability, emailReady } from './email.ts'
199
203
  import { noticeAboutEmail } from './email-notice.ts'
204
+ import { createEmailSettings, type EmailSettingsInput } from './email-settings.ts'
200
205
  import { activityCsv, readActivityQuery } from './extension-activity.ts'
201
206
  import { createBackOfficeBuilds } from './extension-backoffice.ts'
202
207
  import { warnAboutAppPlugins } from './extensions-notice.ts'
@@ -240,6 +245,7 @@ import {
240
245
  } from './preview-tokens.ts'
241
246
  import { provenanceProblem } from './provenance.ts'
242
247
  import { createRemote, may, type RestartOutcome } from './remote.ts'
248
+ import { createSchemaTransfer, UPLOAD_LIMITS } from './schema-transfer.ts'
243
249
  import { SiteAssets } from './site-assets.ts'
244
250
  import { unknownHostProvided } from './site-file.ts'
245
251
  import { PublicFiles } from './site-public.ts'
@@ -309,6 +315,7 @@ import {
309
315
  } from './status-pages.ts'
310
316
  import { TwoFactorService, USER_TWO_FACTOR_PROVIDER } from './two-factor.ts'
311
317
  import { summariseUpgrades } from './upgrade-summary.ts'
318
+ import { createViewAs } from './view-as.ts'
312
319
  import { webhookStoreView } from './webhooks.ts'
313
320
 
314
321
  export interface ServerHandle {
@@ -429,6 +436,12 @@ export async function createServer(
429
436
  ]),
430
437
  streamMemberFile: (src, search) => streamMemberFile(src, search),
431
438
  siteName: async () => (await seo.siteDefaults()).siteName,
439
+ onExtensionsChanged: () => {
440
+ // An instruction heard while this server is still being built has no hub to tell yet.
441
+ try {
442
+ events.broadcast('notify', [BUNDLES_CHANGED_EVENT])
443
+ } catch {}
444
+ },
432
445
  })
433
446
  const {
434
447
  diagnostics,
@@ -657,6 +670,21 @@ export async function createServer(
657
670
  // An extension's call through `api`, made in this process (story 308).
658
671
  const acting = actingPrincipalOf(request)
659
672
  if (acting) return acting
673
+ const identity = await identify(request)
674
+ if (!identity) return undefined
675
+ const principal = await principalFrom(identity)
676
+ // Story 314: what this session writes says whose groups it was seen as.
677
+ const context = currentAuditContext()
678
+ if (context && principal.viewingAs)
679
+ context.viewing = {
680
+ userKey: normaliseUuid(principal.id),
681
+ groups: principal.viewingAs.groups.map((g) => g.name).join(', '),
682
+ }
683
+ return principal
684
+ }
685
+
686
+ /** The signed-in session a request carries, from its cookie or a bearer token. */
687
+ async function identify(request: Request): Promise<ResolvedIdentity | undefined> {
660
688
  const header = request.headers.get('authorization')
661
689
  const bearer = header?.toLowerCase().startsWith('bearer ') ? header.slice(7).trim() : undefined
662
690
  const fromCookie = !bearer || bearer === REDACTED
@@ -676,8 +704,7 @@ export async function createServer(
676
704
  return undefined
677
705
  }
678
706
 
679
- const identity = await auth.resolveAccessToken(token)
680
- return identity && principalFrom(identity)
707
+ return auth.resolveAccessToken(token)
681
708
  }
682
709
 
683
710
  /** What a resolved user may do, as every check in the Management API reads it. */
@@ -696,7 +723,12 @@ export async function createServer(
696
723
  permissions: identity.permissions,
697
724
  groupKeys: identity.groupKeys,
698
725
  hasAccessToAllLanguages: identity.hasAccessToAllLanguages,
699
- ...(await loadAccess(db, identity.user.id)),
726
+ ...(await loadAccess(
727
+ db,
728
+ identity.user.id,
729
+ identity.viewingAs ? identity.groupKeys : undefined,
730
+ )),
731
+ ...(identity.viewingAs ? { viewingAs: identity.viewingAs } : {}),
700
732
  }
701
733
  }
702
734
 
@@ -867,6 +899,7 @@ export async function createServer(
867
899
  bundleGrants,
868
900
  failed: () => [...core.failedExtensions, ...backOfficeBuilds.failed()],
869
901
  stopExtension: (id) => core.stopExtension(id),
902
+ changed: (id) => core.extensionChanged(id),
870
903
  })
871
904
  const actorOf = (principal: Principal, request: Request): BundleActor => ({
872
905
  id: principal.id,
@@ -1284,6 +1317,13 @@ export async function createServer(
1284
1317
  showDetails: config.errors.showDetails,
1285
1318
  cors: formCors,
1286
1319
  })
1320
+ // Story 346: an extension started while the site runs adds its routes here, checked as these were.
1321
+ core.setRouteTable({
1322
+ problems: (entries) =>
1323
+ siteRouteProblems([...siteRoutes.routes, ...entries], config.backOfficePath),
1324
+ add: (entries) => siteRoutes.add(entries),
1325
+ remove: (owner) => siteRoutes.remove(owner),
1326
+ })
1287
1327
 
1288
1328
  // Story 219: the site's server actions, a module at a time.
1289
1329
  const { registry: actionList, problems: actionProblems } = actionRegistry(config.actions)
@@ -1303,7 +1343,17 @@ export async function createServer(
1303
1343
  // Whether an invitation or a reset link can reach anyone at all, which is what
1304
1344
  // gates the options rather than `emailStatus.available`: development delivers
1305
1345
  // to the console, and that is a working flow for the person using it.
1306
- const canSendUserLinks = Boolean(resolveUserLinkSender(config, email))
1346
+ // Asked each time, as e-mail set up in Settings changes without a restart (story 340).
1347
+ const canSendUserLinks = () => Boolean(resolveUserLinkSender(config, email))
1348
+ const emailSettings = createEmailSettings(db, config, { port: () => email })
1349
+ const viewAs = createViewAs(db, auth)
1350
+ const schemaTransfer = createSchemaTransfer(db, config, {
1351
+ boot: schema,
1352
+ afterApply: async (report) => {
1353
+ cache.invalidate()
1354
+ await afterSync(report)
1355
+ },
1356
+ })
1307
1357
  const images = new ImageProcessor(mediaStore)
1308
1358
  // Asked at boot, so the first AVIF request does not wait on it.
1309
1359
  void canEncodeAvif()
@@ -1516,6 +1566,12 @@ export async function createServer(
1516
1566
  const MEDIA_JOB_QUEUED_EVENT = { eventSource: 'Crombolo:MediaJob', eventType: 'Queued' } as const
1517
1567
  const hostTokenPath = `${paths.pluginPath}/api/host-token`
1518
1568
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1569
+ const viewAsPath = `${paths.pluginPath}/api/view-as`
1570
+ const selfAudited = [
1571
+ `${paths.pluginPath}/api/email/`,
1572
+ `${paths.pluginPath}/api/schema-transfer/`,
1573
+ viewAsPath,
1574
+ ]
1519
1575
  const bundleInstallPaths = new Set(
1520
1576
  ['install', 'uninstall', 'disable', 'enable', 'grant', 'settings'].flatMap((action) => [
1521
1577
  `${paths.pluginPath}/api/extensions/${action}`,
@@ -1552,6 +1608,11 @@ export async function createServer(
1552
1608
  core.setBundleDispatch((request) => fetch(request))
1553
1609
 
1554
1610
  async function fetch(request: Request): Promise<Response> {
1611
+ // A request dispatched from inside another (an extension's call) shares its audit context.
1612
+ return currentAuditContext() ? traced(request) : withAuditContext(() => traced(request))
1613
+ }
1614
+
1615
+ async function traced(request: Request): Promise<Response> {
1555
1616
  // Story 262: every request a span, continuing a trace only from a trusted proxy.
1556
1617
  const pathname = new URL(request.url).pathname
1557
1618
  const route = routeOf(pathname, paths.backOfficePath)
@@ -1933,8 +1994,10 @@ export async function createServer(
1933
1994
  if (pathname === hostTokenPath) return
1934
1995
  // A content query is a POST that reads.
1935
1996
  if (pathname === contentQueryPath) return
1936
- // Installs and removals write their own entry, with the package (story 194).
1997
+ // Installs and removals write their own entry, with the package (story 194),
1998
+ // as do e-mail settings (story 340) and schema imports (story 342).
1937
1999
  if (bundleInstallPaths.has(pathname) || pathname.startsWith(`${jobsPath}/`)) return
2000
+ if (selfAudited.some((path) => pathname.startsWith(path))) return
1938
2001
  const principal = await authenticate(request)
1939
2002
  if (!principal) return
1940
2003
  const plan = pluginAuditPlan(request.method, pathname.slice(prefix.length))
@@ -2376,7 +2439,9 @@ export async function createServer(
2376
2439
  { ok: false, message: 'Only an administrator manages trusted signers.' },
2377
2440
  { status: 403 },
2378
2441
  )
2379
- const signers = createTrustedSignersAdmin(db, config)
2442
+ const signers = createTrustedSignersAdmin(db, config, {
2443
+ checks: { extensions, grants: bundleGrants, changed: core.extensionChanged },
2444
+ })
2380
2445
  const actor = { ...actorOf(principal, request), source: 'request' as const }
2381
2446
  if (action === 'signers' && request.method === 'GET')
2382
2447
  return Response.json({ items: await signers.list() })
@@ -2467,16 +2532,107 @@ export async function createServer(
2467
2532
 
2468
2533
  if (pathname === `${paths.pluginPath}/api/email` && request.method === 'GET') {
2469
2534
  if (!(await authenticate(request))) return new Response('Unauthorized', { status: 401 })
2535
+ const status = emailAvailability(email)
2470
2536
  return Response.json({
2471
- available: emailStatus.available,
2472
- provider: emailStatus.provider,
2473
- reason: emailStatus.reason,
2474
- affects: emailStatus.affects,
2475
- canSendUserLinks,
2476
- canSendNotifications: Boolean(email),
2537
+ available: status.available,
2538
+ provider: status.provider,
2539
+ reason: status.reason,
2540
+ affects: status.affects,
2541
+ canSendUserLinks: canSendUserLinks(),
2542
+ canSendNotifications: emailReady(email),
2477
2543
  })
2478
2544
  }
2479
2545
 
2546
+ // Story 342: Settings → Schema, administrators only. An upload waits for
2547
+ // approval on the Changes dashboard; nothing changes until it is applied.
2548
+ const schemaAction = /^\/api\/schema-transfer\/(export|import|import\/apply)$/.exec(
2549
+ pathname.slice(paths.pluginPath.length),
2550
+ )?.[1]
2551
+ if (pathname.startsWith(paths.pluginPath) && schemaAction) {
2552
+ const principal = await authenticate(request)
2553
+ if (!principal) return new Response('Unauthorized', { status: 401 })
2554
+ if (!principal.isAdmin)
2555
+ return Response.json(
2556
+ { ok: false, message: 'Only an administrator imports or exports the schema.' },
2557
+ { status: 403 },
2558
+ )
2559
+ const actor = actorOf(principal, request)
2560
+ if (schemaAction === 'export' && request.method === 'GET')
2561
+ return new Response(schemaTransfer.exportZip(), {
2562
+ headers: {
2563
+ 'content-type': 'application/zip',
2564
+ 'content-disposition': 'attachment; filename="schema.zip"',
2565
+ 'cache-control': PRIVATE_NO_STORE,
2566
+ },
2567
+ })
2568
+ if (schemaAction === 'import' && request.method === 'GET')
2569
+ return Response.json({
2570
+ pending: (await schemaTransfer.pending()) ?? null,
2571
+ writable: config.schemaWritable,
2572
+ })
2573
+ let outcome: Awaited<ReturnType<typeof schemaTransfer.discard>> | undefined
2574
+ if (schemaAction === 'import' && request.method === 'POST') {
2575
+ const length = Number(request.headers.get('content-length') ?? 0)
2576
+ if (length > UPLOAD_LIMITS.maxUploadBytes)
2577
+ return Response.json(
2578
+ { ok: false, message: 'That file is too large to be a schema.' },
2579
+ { status: 413 },
2580
+ )
2581
+ const name = new URL(request.url).searchParams.get('name') ?? 'schema.zip'
2582
+ outcome = await schemaTransfer.upload(
2583
+ actor,
2584
+ name,
2585
+ new Uint8Array(await request.arrayBuffer()),
2586
+ )
2587
+ } else if (schemaAction === 'import' && request.method === 'DELETE')
2588
+ outcome = await schemaTransfer.discard(actor)
2589
+ else if (schemaAction === 'import/apply' && request.method === 'POST')
2590
+ outcome = await schemaTransfer.apply(actor)
2591
+ if (!outcome) return new Response('Method Not Allowed', { status: 405 })
2592
+ return outcome.ok
2593
+ ? Response.json(outcome)
2594
+ : Response.json(outcome, { status: outcome.status })
2595
+ }
2596
+
2597
+ // Story 314: an administrator's session seen as user groups, and back.
2598
+ if (pathname === viewAsPath) {
2599
+ const identity = await identify(request)
2600
+ if (!identity) return new Response('Unauthorized', { status: 401 })
2601
+ return viewAs.handle(request, identity, clientAddress(request))
2602
+ }
2603
+
2604
+ // Story 340: Settings → E-mail, administrators only.
2605
+ const emailAction = /^\/api\/email\/(settings|test)$/.exec(
2606
+ pathname.slice(paths.pluginPath.length),
2607
+ )?.[1]
2608
+ if (pathname.startsWith(paths.pluginPath) && emailAction) {
2609
+ const principal = await authenticate(request)
2610
+ if (!principal) return new Response('Unauthorized', { status: 401 })
2611
+ if (!principal.isAdmin)
2612
+ return Response.json(
2613
+ { ok: false, message: 'Only an administrator sets up e-mail.' },
2614
+ { status: 403 },
2615
+ )
2616
+ const actor = actorOf(principal, request)
2617
+ if (emailAction === 'settings' && request.method === 'GET')
2618
+ return Response.json(await emailSettings.view())
2619
+ const outcome =
2620
+ emailAction === 'settings' && request.method === 'PUT'
2621
+ ? await emailSettings.save(
2622
+ actor,
2623
+ ((await request.json().catch(() => ({}))) ?? {}) as EmailSettingsInput,
2624
+ )
2625
+ : emailAction === 'settings' && request.method === 'DELETE'
2626
+ ? await emailSettings.clear(actor)
2627
+ : emailAction === 'test' && request.method === 'POST'
2628
+ ? await emailSettings.test(actor)
2629
+ : undefined
2630
+ if (!outcome) return new Response('Method Not Allowed', { status: 405 })
2631
+ return outcome.ok
2632
+ ? Response.json(outcome)
2633
+ : Response.json({ ok: false, message: outcome.message }, { status: outcome.status })
2634
+ }
2635
+
2480
2636
  /**
2481
2637
  * Non-contract: forms and their entries. There is no form operation in the
2482
2638
  * vendored contract — Umbraco Forms ships its own API and its own client,
@@ -3149,7 +3305,10 @@ export async function createServer(
3149
3305
  bundles,
3150
3306
  upgrades,
3151
3307
  transfers: await pendingTransfers(db),
3308
+ // Story 342: an uploaded schema waiting for an administrator.
3309
+ schemaImport: principal.isAdmin ? ((await schemaTransfer.pending()) ?? null) : null,
3152
3310
  mayImport,
3311
+ mayApplySchema: principal.isAdmin,
3153
3312
  })
3154
3313
  }
3155
3314
 
@@ -3250,7 +3409,7 @@ export async function createServer(
3250
3409
  allowUserInvite: false,
3251
3410
  // Offering "forgot password" with no way to send the link is a dead
3252
3411
  // end that looks like a bug; without a sender the option is not there.
3253
- allowPasswordReset: config.allowPasswordReset && canSendUserLinks,
3412
+ allowPasswordReset: config.allowPasswordReset && canSendUserLinks(),
3254
3413
  disableLocalLogin: !config.allowLocalLogin,
3255
3414
  // Set by the authorize endpoint so sign-in resumes the OAuth flow. Only
3256
3415
  // a path on this site: the login page hands this to the browser once
package/src/settings.ts CHANGED
@@ -443,12 +443,13 @@ const DECLARED = [
443
443
  description: 'Whether the back office may change the schema files.',
444
444
  },
445
445
  {
446
- env: 'CROMBOLO_CONTENT_FILES_READONLY',
447
- kind: 'boolean',
448
- default: 'false',
446
+ env: 'CROMBOLO_CONTENT_MODE',
447
+ kind: 'enum',
448
+ values: ['development', 'production'],
449
+ default: 'development',
449
450
  section: 'Schema',
450
451
  description:
451
- 'Stops the back office changing templates, stylesheets and scripts, for a site whose files come from its repository.',
452
+ 'In production, the back office cannot change templates, stylesheets and scripts, for a site whose files come from its repository.',
452
453
  },
453
454
  {
454
455
  env: 'CROMBOLO_SYNC_SCHEMA_AT_BOOT',
@@ -837,9 +838,10 @@ const DECLARED = [
837
838
  {
838
839
  env: 'CROMBOLO_DELIVERY_API',
839
840
  kind: 'boolean',
840
- default: 'false',
841
+ default: 'true',
841
842
  section: 'Public site',
842
- description: 'Turns on the Delivery API, which serves content as JSON.',
843
+ description:
844
+ 'The Delivery API, which serves the published pages anyone may see as JSON. false turns it off.',
843
845
  },
844
846
  {
845
847
  env: 'CROMBOLO_DELIVERY_API_KEY',
@@ -850,11 +852,12 @@ const DECLARED = [
850
852
  secret: true,
851
853
  },
852
854
  {
853
- env: 'CROMBOLO_DELIVERY_API_PUBLIC',
855
+ env: 'CROMBOLO_DELIVERY_API_PRIVATE',
854
856
  kind: 'boolean',
855
- default: 'true',
857
+ default: 'false',
856
858
  section: 'Public site',
857
- description: 'Off, every Delivery API request needs the key.',
859
+ description:
860
+ 'Makes the Delivery API private: every request needs the key. Unset, it serves what the site publishes.',
858
861
  },
859
862
  {
860
863
  env: 'CROMBOLO_DELIVERY_API_MEDIA',
@@ -866,9 +869,10 @@ const DECLARED = [
866
869
  {
867
870
  env: 'CROMBOLO_DELIVERY_API_CORS_ORIGINS',
868
871
  kind: 'list',
872
+ default: 'any site, while the API is public',
869
873
  section: 'Public site',
870
874
  description:
871
- 'Other sites whose pages may call the Delivery API from the browser, such as https://app.example.com, separated by commas.',
875
+ 'Narrows which other sites may call the Delivery API from the browser, such as https://app.example.com, separated by commas.',
872
876
  },
873
877
  {
874
878
  env: 'CROMBOLO_CACHE_MAX_AGE',
@@ -299,7 +299,8 @@ export class PublicFiles {
299
299
  /** The servable files of a folder, which may not exist. */
300
300
  function filesFrom(root: string): string[] {
301
301
  try {
302
- return existsSync(root) ? filesIn(root).filter(isServable) : []
302
+ // Sorted: the folder's own order differs between file systems.
303
+ return existsSync(root) ? filesIn(root).filter(isServable).sort() : []
303
304
  } catch {
304
305
  return []
305
306
  }