@crombolo/server 0.56.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/seo.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  */
9
9
  import type { Principal } from '@crombolo/api-management/domain'
10
10
  import { hasSection } from '@crombolo/api-management/domain'
11
- import { SYSTEM_CONTENT_TYPE_KEYS } from '@crombolo/core'
11
+ import { SEO_MAPPING_FIELDS, type SeoMapping, SYSTEM_CONTENT_TYPE_KEYS } from '@crombolo/core'
12
12
  import { ContentTypeRepository, type Db, readKeyValue, writeKeyValue } from '@crombolo/data'
13
13
  import {
14
14
  effectiveMeta,
@@ -21,6 +21,8 @@ import {
21
21
  sitemapEntries,
22
22
  urlsIn,
23
23
  } from '@crombolo/render'
24
+ import { exportSchemaSet, seoMappingProblems, seoMappingProperties } from '@crombolo/schema'
25
+ import { createSchemaFileWriter, schemaFiles } from './adapters/schema-files.ts'
24
26
  import type { CromboloConfig, NotFoundRule } from './config.ts'
25
27
 
26
28
  export const SEO_SETTINGS_KEY = 'Crombolo.Seo.Settings'
@@ -175,6 +177,8 @@ export interface DraftModel {
175
177
  content: PublishedContent
176
178
  contentTypeAlias: string
177
179
  published: boolean
180
+ /** The page as visitors see it now, when it is published. */
181
+ live?: PublishedContent
178
182
  culture: string | null
179
183
  }
180
184
 
@@ -284,6 +288,23 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
284
288
  return (await cache.media?.byKey(trimmed))?.url
285
289
  }
286
290
 
291
+ let typesMemo: { at: number; types: Record<string, SeoMapping> } | undefined
292
+ /** Each type's `[seo]` values (story 317), a fixed image as its address. */
293
+ const typeMappings = async (): Promise<Record<string, SeoMapping>> => {
294
+ if (typesMemo && Date.now() - typesMemo.at < SETTINGS_TTL_MS) return typesMemo.types
295
+ const stored = await new ContentTypeRepository(db).seoMappings().catch(() => ({}))
296
+ const types: Record<string, SeoMapping> = {}
297
+ for (const [alias, mapping] of Object.entries(stored)) {
298
+ const image =
299
+ mapping.image && UUID.test(mapping.image)
300
+ ? await imageAddress(mapping.image)
301
+ : mapping.image
302
+ types[alias] = { ...mapping, ...(image ? { image } : { image: undefined }) }
303
+ }
304
+ typesMemo = { at: Date.now(), types }
305
+ return types
306
+ }
307
+
287
308
  const siteDefaults: SeoHost['siteDefaults'] = async () => {
288
309
  const { effective } = await settings()
289
310
  return {
@@ -291,6 +312,7 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
291
312
  titleSuffix: effective.titleSuffix || undefined,
292
313
  defaultImage: await imageAddress(effective.defaultImage),
293
314
  indexable: effective.indexable,
315
+ types: await typeMappings(),
294
316
  }
295
317
  }
296
318
 
@@ -404,6 +426,71 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
404
426
  return false
405
427
  }
406
428
 
429
+ /** What the card needs to set a value for every page of the type (story 317). */
430
+ const mappingFor = async (alias: string, principal: Principal) => {
431
+ const repo = new ContentTypeRepository(db)
432
+ const type = await repo.byAlias(alias)
433
+ if (!type) return null
434
+ const canEdit = hasSection(principal, 'settings')
435
+ const schemaType = canEdit
436
+ ? await exportSchemaSet(db, '0').then((set) => {
437
+ const found = set.contentTypes.find((t) => t.alias === type.alias)
438
+ return found ? seoMappingProperties(set, found) : []
439
+ })
440
+ : []
441
+ return {
442
+ canEdit,
443
+ properties: schemaType,
444
+ type: {
445
+ alias: type.alias,
446
+ name: type.name,
447
+ seo: type.seo ?? {},
448
+ // Not where the files are read-only: a type changes there with a deploy.
449
+ editable: createSchemaFileWriter(db, schemaFiles(config)).refuse(type) === undefined,
450
+ pages: await repo.contentCount(type.key),
451
+ },
452
+ }
453
+ }
454
+
455
+ /** `PUT seo/type`: a type's `[seo]` values, in the database and its schema file. */
456
+ const saveType = async (request: Request, principal: Principal): Promise<Response> => {
457
+ if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
458
+ const body = (await request.json().catch(() => undefined)) as
459
+ | { contentType?: unknown; seo?: unknown }
460
+ | undefined
461
+ if (typeof body?.contentType !== 'string' || typeof body.seo !== 'object' || !body.seo)
462
+ return Response.json({ message: 'Say which type, and its values.' }, { status: 400 })
463
+ const repo = new ContentTypeRepository(db)
464
+ const type = await repo.byAlias(body.contentType)
465
+ if (!type) return Response.json({ message: 'That type could not be found.' }, { status: 404 })
466
+ const writer = createSchemaFileWriter(db, schemaFiles(config))
467
+ if (writer.refuse(type))
468
+ return Response.json(
469
+ {
470
+ message: `Every ${type.name} page's values are kept with this site's files, so they change with a deploy rather than here.`,
471
+ },
472
+ { status: 409 },
473
+ )
474
+ const seo: SeoMapping = {}
475
+ for (const field of SEO_MAPPING_FIELDS) {
476
+ const value = (body.seo as Record<string, unknown>)[field]
477
+ if (typeof value === 'string' && value.trim()) seo[field] = value.trim()
478
+ }
479
+ const set = await exportSchemaSet(db, '0')
480
+ const schemaType = set.contentTypes.find((t) => t.alias === type.alias)
481
+ const problems = schemaType ? seoMappingProblems(set, { ...schemaType, seo }) : []
482
+ if (problems.length > 0)
483
+ return Response.json(
484
+ { message: problems.map((p) => p.message).join('; '), problems },
485
+ { status: 400 },
486
+ )
487
+ const mapping = Object.keys(seo).length > 0 ? seo : null
488
+ await repo.setSeo(type.key, mapping)
489
+ await writer.write({ ...type, seo: mapping })
490
+ typesMemo = undefined
491
+ return Response.json({ seo: mapping ?? {}, pages: await repo.contentCount(type.key) })
492
+ }
493
+
407
494
  const preview = async (request: Request, principal: Principal): Promise<Response> => {
408
495
  const url = new URL(request.url)
409
496
  const key = url.searchParams.get('document') ?? ''
@@ -412,17 +499,24 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
412
499
  if (!draft) return Response.json({ message: 'That page could not be found.' }, { status: 404 })
413
500
  const origin = publicOrigin(request, config)
414
501
  const snapshot = await cache.snapshot()
415
- const meta = await effectiveMeta(draft.content, {
416
- origin,
417
- alternates: urlsIn(snapshot, key),
418
- site: await siteDefaults(),
419
- })
502
+ const context = { origin, alternates: urlsIn(snapshot, key), site: await siteDefaults() }
503
+ const meta = await effectiveMeta(draft.content, context)
504
+ // Said only when what search engines see now is not this: unpublished, or changed since.
505
+ const live = draft.live ? await effectiveMeta(draft.live, context) : undefined
506
+ const differs = !draft.published
507
+ ? 'unpublished'
508
+ : live && JSON.stringify(live) !== JSON.stringify(meta)
509
+ ? 'changed'
510
+ : null
420
511
  return Response.json({
421
512
  hasSeoFields: await composesSeoFields(draft.contentTypeAlias),
513
+ mapping: await mappingFor(draft.contentTypeAlias, principal),
422
514
  published: draft.published,
515
+ differs,
423
516
  culture: draft.culture,
424
517
  meta,
425
518
  snippet: {
519
+ name: draft.content.name,
426
520
  title: meta.fullTitle,
427
521
  url: meta.canonical.value ?? '',
428
522
  description: meta.description.value ?? '',
@@ -432,6 +526,7 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
432
526
 
433
527
  const handle: SeoHost['handle'] = async (request, subpath, principal) => {
434
528
  if (subpath === '/preview' && request.method === 'GET') return preview(request, principal)
529
+ if (subpath === '/type' && request.method === 'PUT') return saveType(request, principal)
435
530
  if (subpath !== '/settings') return undefined
436
531
  if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
437
532
  if (request.method === 'GET') return Response.json(await settings())
package/src/server.ts CHANGED
@@ -47,9 +47,11 @@ import {
47
47
  serializeCookie,
48
48
  } from '@crombolo/auth'
49
49
  import {
50
+ backOfficePolicy,
50
51
  collectManifests,
51
52
  type createBackOfficePaths,
52
53
  isSpaRoute,
54
+ newNonce,
53
55
  renderBackOfficeShell,
54
56
  renderDeviceShell,
55
57
  renderLoginShell,
@@ -164,14 +166,15 @@ import {
164
166
  import { createPublishedContentSource, loadDraftNode } from './adapters/documents.ts'
165
167
  import type { Approvals } from './approvals.ts'
166
168
  import { handleApprovalsApi } from './approvals-api.ts'
167
- import { type BundleActor, createBundleAdmin } from './bundle-admin.ts'
168
- import type { BundleGrants } from './bundle-grants.ts'
169
+ import { type BundleActor, createBundleAdmin, settingsIn } from './bundle-admin.ts'
170
+ import { actAsChoice, actingPrincipalOf } from './bundle-api.ts'
171
+ import { type BundleGrants, declaredOrigins } from './bundle-grants.ts'
169
172
  import { CommandError, installBundleContent } from './bundle-install.ts'
170
173
  import { BUNDLES_CHANGED_EVENT, type BundleReload, createBundleReloader } from './bundle-reload.ts'
171
174
  import { bundleRouteGroups } from './bundles.ts'
172
175
  import { busyResponse } from './busy.ts'
173
176
  import { handleComponentTemplates } from './component-templates-api.ts'
174
- import { checkTypes, listEmailTemplates } from './components.ts'
177
+ import { checkTypes, listEmailTemplates, siteLayouts } from './components.ts'
175
178
  import {
176
179
  type CromboloConfig,
177
180
  listeningBodyLimit,
@@ -245,6 +248,7 @@ import {
245
248
  stopTelemetry,
246
249
  } from './telemetry.ts'
247
250
  import { handleTransferAction, pendingTransfers } from './transfer-dashboard.ts'
251
+ import { createTrustedSignersAdmin } from './trusted-signers-admin.ts'
248
252
  import { changeUrlOptions, urlSettingEditable } from './url-settings.ts'
249
253
  import type { JobsStatus } from './worker-watch.ts'
250
254
 
@@ -272,7 +276,7 @@ import {
272
276
  runStage,
273
277
  } from './middleware.ts'
274
278
  import { CORE_JOB_OWNER, type JobRunner } from './owner-jobs.ts'
275
- import { callerAddress } from './rate-limit.ts'
279
+ import { callerAddress, RateLimiter } from './rate-limit.ts'
276
280
  import { syncConfiguredRedirects } from './redirects.ts'
277
281
  import { createRoutes, type DeclaredRoute, SITE_ROUTE_OWNER, siteRouteProblems } from './routes.ts'
278
282
  import { componentAliasesIn, importSchema, type SchemaBoot, watchSchema } from './schema.ts'
@@ -451,6 +455,9 @@ export async function createServer(
451
455
  wake,
452
456
  urlChange,
453
457
  } = core
458
+ /** The extensions that are on: granted, and not turned off (story 309). */
459
+ const onExtensions = () =>
460
+ extensions.list().filter((extension) => bundleGrants.isOn(extension.bundle.id))
454
461
  // What this process answers: only `web` serves no back office.
455
462
  const servesBackOffice = config.role !== 'web'
456
463
  // A host that installs packages itself calls `reloadBundles()` (story 181); the
@@ -465,6 +472,7 @@ export async function createServer(
465
472
  registry: config.npmRegistry,
466
473
  keyword: config.packageKeyword,
467
474
  marketplaceUrl: config.marketplaceUrl,
475
+ componentsDir: config.componentsDir,
468
476
  extensions: { ...extensions, invalidate: () => void bundleReloader.reload() },
469
477
  siteDir: config.siteDir,
470
478
  wired: () => bundles?.mounted.map((bundle) => bundle.id) ?? [],
@@ -481,12 +489,13 @@ export async function createServer(
481
489
  applyContent: async (packageName) => {
482
490
  // A package from the marketplace is for anyone, so nothing in it can be
483
491
  // sealed; one that is is refused rather than half applied.
484
- const result = await installBundleContent(db, config, { bundle: packageName }).catch(
485
- (error: unknown) => {
486
- if (error instanceof CommandError) return error
487
- throw error
488
- },
489
- )
492
+ const result = await installBundleContent(db, config, {
493
+ bundle: packageName,
494
+ expects: 'extension',
495
+ }).catch((error: unknown) => {
496
+ if (error instanceof CommandError) return error
497
+ throw error
498
+ })
490
499
  if (result instanceof CommandError)
491
500
  return { applied: false, message: `Its content was not applied: ${result.message}` }
492
501
  if (!result.runId) {
@@ -613,6 +622,9 @@ export async function createServer(
613
622
  * non-browser client may still present a real bearer token.
614
623
  */
615
624
  async function authenticate(request: Request): Promise<Principal | undefined> {
625
+ // An extension's call through `api`, made in this process (story 308).
626
+ const acting = actingPrincipalOf(request)
627
+ if (acting) return acting
616
628
  const header = request.headers.get('authorization')
617
629
  const bearer = header?.toLowerCase().startsWith('bearer ') ? header.slice(7).trim() : undefined
618
630
  const fromCookie = !bearer || bearer === REDACTED
@@ -815,7 +827,14 @@ export async function createServer(
815
827
  },
816
828
  )
817
829
  : undefined
818
- const bundleAdmin = createBundleAdmin({ db, config, marketplace, extensions, bundleGrants })
830
+ const bundleAdmin = createBundleAdmin({
831
+ db,
832
+ config,
833
+ marketplace,
834
+ extensions,
835
+ bundleGrants,
836
+ failed: () => core.failedExtensions,
837
+ })
819
838
  const actorOf = (principal: Principal, request: Request): BundleActor => ({
820
839
  id: principal.id,
821
840
  name: principal.name,
@@ -1180,6 +1199,7 @@ export async function createServer(
1180
1199
  content,
1181
1200
  contentTypeAlias: draft.contentTypeAlias,
1182
1201
  published: Boolean(published),
1202
+ ...(published ? { live: published.withValueContext(await cache.valueContext(culture)) } : {}),
1183
1203
  culture,
1184
1204
  }
1185
1205
  }
@@ -1254,6 +1274,40 @@ export async function createServer(
1254
1274
  // Asked at boot, so the first AVIF request does not wait on it.
1255
1275
  void canEncodeAvif()
1256
1276
  const publicMedia = mediaStore.publicUrl?.('media/file')
1277
+
1278
+ /** At most 30 reports a minute from one address. */
1279
+ const cspReports = new RateLimiter({ max: 30, windowMs: 60_000 })
1280
+
1281
+ /**
1282
+ * A back-office page, with its content security policy (story 313): its
1283
+ * inline scripts carry a nonce made for it, and it may reach the site and the
1284
+ * origins the extensions that are on declare in `http.outbound`, and the
1285
+ * host's origin, which it vouches its user to (story 318).
1286
+ */
1287
+ const backOfficePage = (body: string): Response => {
1288
+ const nonce = newNonce()
1289
+ const connect = [
1290
+ ...extensions
1291
+ .bundles()
1292
+ .bundles.filter((pkg) => bundleGrants.isOn(pkg.id))
1293
+ .flatMap((pkg) => declaredOrigins(pkg)),
1294
+ ...(config.host ? [config.host.origin] : []),
1295
+ ]
1296
+ return new Response(body.replaceAll('<script', `<script nonce="${nonce}"`), {
1297
+ headers: {
1298
+ 'content-type': 'text/html; charset=utf-8',
1299
+ 'content-security-policy': backOfficePolicy({
1300
+ nonce,
1301
+ connect,
1302
+ media: publicMedia ? [publicMedia] : [],
1303
+ frames: [config.seo.publicUrl, config.applicationUrl].filter(
1304
+ (url): url is string => typeof url === 'string',
1305
+ ),
1306
+ reportUri: `${paths.pluginPath}/api/csp-report`,
1307
+ }),
1308
+ },
1309
+ })
1310
+ }
1257
1311
  if (publicMedia)
1258
1312
  log.warning(
1259
1313
  'Media files are also served from {where}. Protected files are always sent by this site and never from there, but anyone with a file’s address there can open it: keep protected files in a store nothing public serves.',
@@ -1274,6 +1328,11 @@ export async function createServer(
1274
1328
  config,
1275
1329
  paths,
1276
1330
  siteSettingsFindings: () => cache.settingsFindings(),
1331
+ failedExtensions: () => core.failedExtensions,
1332
+ lostLayouts: () => {
1333
+ const layouts = siteLayouts(config.componentsDir)
1334
+ return core.extensionComponents.layouts().filter((entry) => !layouts.includes(entry.layout))
1335
+ },
1277
1336
  hiddenByRoutes: async () => {
1278
1337
  const snapshot = await cache.snapshot()
1279
1338
  const hidden: Array<{ route: string; owner: string; page: string; url: string }> = []
@@ -1289,17 +1348,8 @@ export async function createServer(
1289
1348
  }
1290
1349
  return hidden
1291
1350
  },
1292
- // A server bundle's screens show only while it is on (story 222).
1293
- extensions: {
1294
- ...extensions,
1295
- list: () =>
1296
- extensions
1297
- .list()
1298
- .filter(
1299
- (extension) =>
1300
- !extension.bundle.carries.server || bundleGrants.isOn(extension.bundle.id),
1301
- ),
1302
- },
1351
+ // An extension's screens show only while it is on: granted, and not turned off (story 309).
1352
+ extensions: { ...extensions, list: onExtensions },
1303
1353
  db,
1304
1354
  webhooks,
1305
1355
  contentEvents,
@@ -1432,9 +1482,10 @@ export async function createServer(
1432
1482
  const hostTokenPath = `${paths.pluginPath}/api/host-token`
1433
1483
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1434
1484
  const bundleInstallPaths = new Set(
1435
- ['install', 'uninstall', 'disable', 'enable'].map(
1436
- (action) => `${paths.pluginPath}/api/bundles/${action}`,
1437
- ),
1485
+ ['install', 'uninstall', 'disable', 'enable', 'grant', 'settings'].flatMap((action) => [
1486
+ `${paths.pluginPath}/api/extensions/${action}`,
1487
+ `${paths.pluginPath}/api/bundles/${action}`,
1488
+ ]),
1438
1489
  )
1439
1490
  /** Per node: ten a minute for each person, three hundred in all. */
1440
1491
  const hostTokens = new AttemptLimiter({ max: 10, maxAll: 300, windowMs: 60_000 })
@@ -1463,6 +1514,8 @@ export async function createServer(
1463
1514
  * a request on the new paths is routed as the contract names it, and an
1464
1515
  * address it is answered with points back at the new paths.
1465
1516
  */
1517
+ core.setBundleDispatch((request) => fetch(request))
1518
+
1466
1519
  async function fetch(request: Request): Promise<Response> {
1467
1520
  // Story 262: every request a span, continuing a trace only from a trusted proxy.
1468
1521
  const pathname = new URL(request.url).pathname
@@ -1930,12 +1983,34 @@ export async function createServer(
1930
1983
  }
1931
1984
 
1932
1985
  // Non-contract, signed-in: every component, for a page's template picker.
1986
+ // Story 313: what the browser blocked on a back-office page, to the site's log.
1987
+ // Taken without signing in, as browsers send it; small, and rate limited.
1988
+ if (pathname === `${paths.pluginPath}/api/csp-report` && request.method === 'POST') {
1989
+ if (cspReports.take(clientAddress(request).ipAddress ?? 'unknown') !== undefined)
1990
+ return new Response(null, { status: 429 })
1991
+ const text = await request.text().catch(() => '')
1992
+ if (text.length > 10_000) return new Response(null, { status: 413 })
1993
+ try {
1994
+ const parsed = JSON.parse(text) as { 'csp-report'?: Record<string, unknown> }
1995
+ const report = parsed['csp-report'] ?? {}
1996
+ const blocked = String(report['blocked-uri'] ?? '')
1997
+ log.warning('The back office blocked {blocked}, under {directive}', {
1998
+ blocked: /^https?:/.test(blocked) ? new URL(blocked).origin : blocked.slice(0, 40),
1999
+ directive: String(report['violated-directive'] ?? report['effective-directive'] ?? ''),
2000
+ })
2001
+ } catch {
2002
+ return new Response(null, { status: 400 })
2003
+ }
2004
+ return new Response(null, { status: 204 })
2005
+ }
2006
+
1933
2007
  if (pathname === `${paths.pluginPath}/api/templates`) {
1934
2008
  const principal = await authenticate(request)
1935
2009
  if (!principal) return new Response('Unauthorized', { status: 401 })
1936
2010
  return handleComponentTemplates(request, principal, {
1937
2011
  db,
1938
2012
  componentsDir: config.componentsDir,
2013
+ extensionComponents: () => core.extensionComponents.listed(),
1939
2014
  })
1940
2015
  }
1941
2016
 
@@ -2038,11 +2113,16 @@ export async function createServer(
2038
2113
  * marketplace is an iframe — so this is ours, and it answers to the
2039
2114
  * Packages section exactly as the operations beside it would.
2040
2115
  */
2041
- if (pathname.startsWith(`${paths.pluginPath}/api/bundles/`)) {
2116
+ // Extensions (`/api/extensions/`), and the same at `/api/bundles/`, as it was.
2117
+ const extensionsApi = [
2118
+ `${paths.pluginPath}/api/extensions/`,
2119
+ `${paths.pluginPath}/api/bundles/`,
2120
+ ].find((prefix) => pathname.startsWith(prefix))
2121
+ if (extensionsApi) {
2042
2122
  const principal = await authenticate(request)
2043
2123
  if (!principal) return new Response('Unauthorized', { status: 401 })
2044
2124
  if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
2045
- const action = pathname.slice(`${paths.pluginPath}/api/bundles/`.length)
2125
+ const action = pathname.slice(extensionsApi.length)
2046
2126
 
2047
2127
  if (action === 'marketplace' && request.method === 'GET') {
2048
2128
  return Response.json({
@@ -2134,8 +2214,9 @@ export async function createServer(
2134
2214
  name?: unknown
2135
2215
  version?: unknown
2136
2216
  applyContent?: unknown
2137
- acceptServerCode?: unknown
2138
2217
  grant?: unknown
2218
+ actAs?: unknown
2219
+ settings?: unknown
2139
2220
  }
2140
2221
  const name = typeof body.name === 'string' ? body.name : ''
2141
2222
  const actor = actorOf(principal, request)
@@ -2145,10 +2226,11 @@ export async function createServer(
2145
2226
  name,
2146
2227
  version: typeof body.version === 'string' ? body.version : undefined,
2147
2228
  applyContent: body.applyContent !== false,
2148
- acceptServerCode: body.acceptServerCode === true,
2229
+ actAs: actAsChoice(body.actAs, principal.id),
2149
2230
  grant: Array.isArray(body.grant)
2150
2231
  ? body.grant.filter((p): p is string => typeof p === 'string')
2151
2232
  : [],
2233
+ settings: settingsIn(body.settings),
2152
2234
  })
2153
2235
  : await bundleAdmin.uninstall(actor, name)
2154
2236
  log.info('{user} {action} the package {name}: {outcome}', {
@@ -2172,6 +2254,78 @@ export async function createServer(
2172
2254
  return Response.json(outcome, { status })
2173
2255
  }
2174
2256
 
2257
+ // Story 310: an extension's settings, those the config does not lock, administrators only.
2258
+ if (action === 'settings' && request.method === 'POST') {
2259
+ if (!principal.isAdmin)
2260
+ return Response.json(
2261
+ { ok: false, message: "Only an administrator changes an extension's settings." },
2262
+ { status: 403 },
2263
+ )
2264
+ const body = (await request.json().catch(() => ({}))) as { id?: unknown; values?: unknown }
2265
+ const values =
2266
+ body.values && typeof body.values === 'object' && !Array.isArray(body.values)
2267
+ ? (body.values as Record<string, unknown>)
2268
+ : {}
2269
+ const { status, ...outcome } = await bundleAdmin.setSettings(
2270
+ actorOf(principal, request),
2271
+ typeof body.id === 'string' ? body.id : '',
2272
+ values,
2273
+ )
2274
+ return Response.json(outcome, { status })
2275
+ }
2276
+
2277
+ // Story 316: the keys and builds this site trusts to sign site bundles, administrators only.
2278
+ const signerId = /^signers\/([0-9a-f-]{36})$/i.exec(action)?.[1]
2279
+ if (action === 'signers' || signerId) {
2280
+ if (!principal.isAdmin)
2281
+ return Response.json(
2282
+ { ok: false, message: 'Only an administrator manages trusted signers.' },
2283
+ { status: 403 },
2284
+ )
2285
+ const signers = createTrustedSignersAdmin(db, config)
2286
+ const actor = { ...actorOf(principal, request), source: 'request' as const }
2287
+ if (action === 'signers' && request.method === 'GET')
2288
+ return Response.json({ items: await signers.list() })
2289
+ const body = (await request.json().catch(() => ({}))) as Record<string, unknown>
2290
+ const outcome =
2291
+ action === 'signers' && request.method === 'POST'
2292
+ ? await signers.add(actor, body)
2293
+ : signerId && request.method === 'PUT'
2294
+ ? await signers.rename(actor, signerId, body.name)
2295
+ : signerId && request.method === 'DELETE'
2296
+ ? await signers.remove(actor, signerId)
2297
+ : undefined
2298
+ if (!outcome) return new Response('Method Not Allowed', { status: 405 })
2299
+ return outcome.ok
2300
+ ? Response.json(outcome)
2301
+ : Response.json({ ok: false, message: outcome.message }, { status: outcome.status })
2302
+ }
2303
+
2304
+ // Story 309: granting an installed extension what it asks for, administrators only.
2305
+ if (action === 'grant' && request.method === 'POST') {
2306
+ if (!principal.isAdmin)
2307
+ return Response.json(
2308
+ { ok: false, message: 'Only an administrator grants an extension.' },
2309
+ { status: 403 },
2310
+ )
2311
+ const body = (await request.json().catch(() => ({}))) as {
2312
+ id?: unknown
2313
+ grant?: unknown
2314
+ actAs?: unknown
2315
+ }
2316
+ const { status, ...outcome } = await bundleAdmin.grant(
2317
+ actorOf(principal, request),
2318
+ typeof body.id === 'string' ? body.id : '',
2319
+ {
2320
+ grant: Array.isArray(body.grant)
2321
+ ? body.grant.filter((p): p is string => typeof p === 'string')
2322
+ : [],
2323
+ actAs: actAsChoice(body.actAs, principal.id),
2324
+ },
2325
+ )
2326
+ return Response.json(outcome, { status })
2327
+ }
2328
+
2175
2329
  return new Response('Not Found', { status: 404 })
2176
2330
  }
2177
2331
 
@@ -2355,7 +2509,7 @@ export async function createServer(
2355
2509
  schemaDir: config.schemaDir,
2356
2510
  writable: config.schemaWritable,
2357
2511
  formTypes: formTypes.types,
2358
- componentAliases: () => componentAliasesIn(config.componentsDir),
2512
+ componentAliases: () => componentAliasesIn(config.componentsDir, config.siteDir),
2359
2513
  onChanged: config.schemaStore
2360
2514
  ? async () => {
2361
2515
  await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
@@ -2837,8 +2991,9 @@ export async function createServer(
2837
2991
  })
2838
2992
  }
2839
2993
 
2994
+ // Nor are its files served while it is off (story 309).
2840
2995
  const staticMatch = resolveStaticFile(paths, pathname, {
2841
- extensions: extensions.list(),
2996
+ extensions: onExtensions(),
2842
2997
  immutable: config.immutableAssets ?? !config.development,
2843
2998
  })
2844
2999
  if (staticMatch) {
@@ -2889,8 +3044,8 @@ export async function createServer(
2889
3044
  },
2890
3045
  })
2891
3046
  }
2892
- const { importmap } = collectManifests(paths, extensions.list())
2893
- return html(
3047
+ const { importmap } = collectManifests(paths, onExtensions())
3048
+ return backOfficePage(
2894
3049
  renderDeviceShell(paths, importmap, {
2895
3050
  title: config.siteName,
2896
3051
  userCode: url.searchParams.get('user_code') ?? undefined,
@@ -2913,8 +3068,8 @@ export async function createServer(
2913
3068
  location: `${paths.backOfficePath}/login?returnUrl=${encodeURIComponent(`${pathname}${url.search}`)}`,
2914
3069
  },
2915
3070
  })
2916
- const { importmap } = collectManifests(paths, extensions.list())
2917
- return html(
3071
+ const { importmap } = collectManifests(paths, onExtensions())
3072
+ return backOfficePage(
2918
3073
  renderRemoteApprovalShell(paths, importmap, {
2919
3074
  title: config.siteName,
2920
3075
  job: url.searchParams.get('job') ?? '',
@@ -2923,8 +3078,8 @@ export async function createServer(
2923
3078
  }
2924
3079
 
2925
3080
  if (pathname === `${paths.backOfficePath}/login`) {
2926
- const { importmap } = collectManifests(paths, extensions.list())
2927
- return html(
3081
+ const { importmap } = collectManifests(paths, onExtensions())
3082
+ return backOfficePage(
2928
3083
  renderLoginShell(paths, importmap, {
2929
3084
  defaultUiLanguage: config.defaultUiLanguage,
2930
3085
  keepUserLoggedIn: config.keepUserLoggedIn,
@@ -2953,8 +3108,8 @@ export async function createServer(
2953
3108
  }
2954
3109
 
2955
3110
  if (isSpaRoute(paths.backOfficePath, pathname)) {
2956
- const { importmap } = collectManifests(paths, extensions.list())
2957
- return html(
3111
+ const { importmap } = collectManifests(paths, onExtensions())
3112
+ return backOfficePage(
2958
3113
  renderBackOfficeShell(paths, importmap, {
2959
3114
  defaultUiLanguage: config.defaultUiLanguage,
2960
3115
  keepUserLoggedIn: config.keepUserLoggedIn,
@@ -3952,10 +4107,6 @@ export async function createServer(
3952
4107
  }
3953
4108
  }
3954
4109
 
3955
- function html(body: string): Response {
3956
- return new Response(body, { headers: { 'content-type': 'text/html; charset=utf-8' } })
3957
- }
3958
-
3959
4110
  /**
3960
4111
  * Carries the request's query string onto a redirect target, as Umbraco does, so
3961
4112
  * campaign and tracking parameters survive a rename. A target that names its own
package/src/settings.ts CHANGED
@@ -323,6 +323,14 @@ const DECLARED = [
323
323
  description:
324
324
  'The Packages section installs and removes packages on the running site. Off, they are added to `package.json` and deployed.',
325
325
  },
326
+ {
327
+ env: 'CROMBOLO_DENO',
328
+ kind: 'string',
329
+ default: 'the binary the `deno` package installed',
330
+ section: 'Back office and bundles',
331
+ description:
332
+ 'The Deno binary installed extensions run under, each in a process of its own. Set it where Deno publishes no build, such as Alpine.',
333
+ },
326
334
  {
327
335
  env: 'CROMBOLO_BUNDLE_SIGNATURES',
328
336
  kind: 'enum',
@@ -330,14 +338,14 @@ const DECLARED = [
330
338
  default: 'optional',
331
339
  section: 'Back office and bundles',
332
340
  description:
333
- 'Whether this site takes only bundles signed in GitHub Actions with `crombolo bundle sign`. A signature that does not check out is refused either way.',
341
+ 'Whether this site installs only extensions signed in GitHub Actions with `crombolo bundle sign`. A signature that does not check out is refused either way. Site bundles have their own rule: in production, only from a signer on Settings → Trusted signers.',
334
342
  },
335
343
  {
336
344
  env: 'CROMBOLO_BUNDLE_SOURCES',
337
345
  kind: 'list',
338
346
  section: 'Back office and bundles',
339
347
  description:
340
- 'Where a signed bundle has to come from, separated by commas: `org/*`, `org/repo`, or `org/repo@v*` for its tags. Empty takes signed bundles from anywhere.',
348
+ 'Where a signed bundle has to come from, separated by commas: `org/*`, `org/repo`, or `org/repo@v*` for its tags. Empty takes signed extensions from anywhere. Each is also a trusted CI build for site bundles, locked on Settings → Trusted signers.',
341
349
  },
342
350
  {
343
351
  env: 'CROMBOLO_INSTALLS_ELSEWHERE_MESSAGE',
@@ -355,14 +363,14 @@ const DECLARED = [
355
363
  {
356
364
  env: 'CROMBOLO_MARKETPLACE_URL',
357
365
  kind: 'string',
358
- default: 'https://www.npmjs.com/search?q=keywords%3Acrombolo-bundle',
366
+ default: 'https://www.npmjs.com/search?q=keywords%3Acrombolo-extension',
359
367
  section: 'Back office and bundles',
360
368
  description: 'Where the Marketplace sends someone browsing for bundles.',
361
369
  },
362
370
  {
363
371
  env: 'CROMBOLO_PACKAGE_KEYWORD',
364
372
  kind: 'string',
365
- default: 'crombolo-bundle',
373
+ default: 'crombolo-extension',
366
374
  section: 'Back office and bundles',
367
375
  description: 'The npm keyword a bundle publishes under to be found by the Marketplace.',
368
376
  },