@crombolo/server 0.57.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.57.0",
3
+ "version": "0.58.0",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -31,19 +31,19 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.57.0",
35
- "@crombolo/api-management": "0.57.0",
36
- "@crombolo/auth": "0.57.0",
37
- "@crombolo/backoffice-host": "0.57.0",
38
- "@crombolo/common": "0.57.0",
39
- "@crombolo/content": "0.57.0",
40
- "@crombolo/contracts": "0.57.0",
41
- "@crombolo/core": "0.57.0",
42
- "@crombolo/data": "0.57.0",
43
- "@crombolo/extension": "0.57.0",
44
- "@crombolo/render": "0.57.0",
45
- "@crombolo/schema": "0.57.0",
46
- "@crombolo/transfer": "0.57.0",
34
+ "@crombolo/api-delivery": "0.58.0",
35
+ "@crombolo/api-management": "0.58.0",
36
+ "@crombolo/auth": "0.58.0",
37
+ "@crombolo/backoffice-host": "0.58.0",
38
+ "@crombolo/common": "0.58.0",
39
+ "@crombolo/content": "0.58.0",
40
+ "@crombolo/contracts": "0.58.0",
41
+ "@crombolo/core": "0.58.0",
42
+ "@crombolo/data": "0.58.0",
43
+ "@crombolo/extension": "0.58.0",
44
+ "@crombolo/render": "0.58.0",
45
+ "@crombolo/schema": "0.58.0",
46
+ "@crombolo/transfer": "0.58.0",
47
47
  "@logtape/logtape": "^2.3.8",
48
48
  "@opentelemetry/api": "1.10.0",
49
49
  "@opentelemetry/context-async-hooks": "3.0.0",
@@ -110,7 +110,7 @@ import {
110
110
  recordPruned,
111
111
  requiresProblems,
112
112
  } from './site-replace.ts'
113
- import { type SiteBundleTrust, siteBundleTrust } from './site-trust.ts'
113
+ import { type SiteBundleTrust, siteBundleTrust, vouchedTrust } from './site-trust.ts'
114
114
 
115
115
  /** The trees a content selector or placement may name. */
116
116
  export const CONTENT_OBJECT_TYPES = [
@@ -324,15 +324,22 @@ export interface TransferInput extends SectionOptions {
324
324
  * asked, as story 192 had it. Only where runtime installs are on.
325
325
  */
326
326
  installCode?: boolean
327
- /**
328
- * `local`: the site's own content files, built here, which no one else
329
- * signed and the site's policy never refuses (story 060).
330
- */
331
- provenance?: 'local'
332
327
  /** Apply a site bundle older than one this site applied from the same signer (story 316). */
333
328
  allowDowngrade?: boolean
334
329
  }
335
330
 
331
+ /**
332
+ * Who vouches for a bundle's source in place of a signer, given only by code in
333
+ * this process and never from a request (story 319):
334
+ * - `site`: the site's own content files, built here (story 060), which skip the
335
+ * signer, downgrade and value-migration checks;
336
+ * - `host`: a platform that authenticated the bundle itself, which skips the
337
+ * signer check only, and is recorded as `signed_by: 'host'`.
338
+ */
339
+ export interface Vouch {
340
+ vouchedBy: 'site' | 'host'
341
+ }
342
+
336
343
  /**
337
344
  * Whether a bundle's signature lets it be applied here: a site bundle only from
338
345
  * a signer this site trusts (story 316), an extension by the site's policy
@@ -345,6 +352,12 @@ async function signatureDecision(
345
352
  provenance: ProvenanceResult,
346
353
  input: Pick<TransferInput, 'allowDowngrade'>,
347
354
  ): Promise<SiteBundleTrust> {
355
+ if (provenance.state === 'vouched')
356
+ return vouchedTrust(
357
+ db,
358
+ { name: bundle.package.packageName, version: bundle.package.version },
359
+ { allowDowngrade: input.allowDowngrade },
360
+ )
348
361
  if (bundle.set.manifest.bundleType === 'site')
349
362
  return siteBundleTrust(db, config, provenance, { allowDowngrade: input.allowDowngrade })
350
363
  const problem = provenanceProblem(provenance, config.bundlePolicy)
@@ -352,11 +365,9 @@ async function signatureDecision(
352
365
  }
353
366
 
354
367
  /** Where the bundle was built, checked before anything is read further (story 060). */
355
- async function bundleProvenance(
356
- bundle: ResolvedBundle,
357
- input: Pick<TransferInput, 'provenance'>,
358
- ): Promise<ProvenanceResult> {
359
- if (input.provenance === 'local') return { state: 'local' }
368
+ async function bundleProvenance(bundle: ResolvedBundle, vouch?: Vouch): Promise<ProvenanceResult> {
369
+ if (vouch?.vouchedBy === 'site') return { state: 'local' }
370
+ if (vouch?.vouchedBy === 'host') return { state: 'vouched' }
360
371
  return verifyProvenance(bundle.directory)
361
372
  }
362
373
 
@@ -487,12 +498,13 @@ export async function checkBundleContent(
487
498
  db: Db,
488
499
  config: CromboloConfig,
489
500
  input: TransferInput,
501
+ vouch?: Vouch,
490
502
  ): Promise<ContentCheckResult> {
491
503
  const bundle = readBundle(input.bundle, config.siteDir, input.passphrase, {
492
504
  expects: input.expects,
493
505
  withoutPeople: input.excludePeople,
494
506
  })
495
- const provenance = await bundleProvenance(bundle, input)
507
+ const provenance = await bundleProvenance(bundle, vouch)
496
508
  const signature = await signatureDecision(db, config, bundle, provenance, input)
497
509
  if (signature.problem) throw new CommandError(`This bundle is refused: ${signature.problem}.`)
498
510
  const set = bundle.set
@@ -659,6 +671,7 @@ export async function installBundleContent(
659
671
  db: Db,
660
672
  config: CromboloConfig,
661
673
  input: ContentImportInput,
674
+ vouch?: Vouch,
662
675
  ): Promise<ContentImportResult> {
663
676
  const bundle = readBundle(input.bundle, config.siteDir, input.passphrase, {
664
677
  expects: input.expects,
@@ -686,7 +699,7 @@ export async function installBundleContent(
686
699
  })
687
700
 
688
701
  // What has to be true before anything is backed up or written.
689
- const provenance = await bundleProvenance(bundle, input)
702
+ const provenance = await bundleProvenance(bundle, vouch)
690
703
  const signature = await signatureDecision(db, config, bundle, provenance, input)
691
704
  if (signature.problem)
692
705
  return { ...refuse([`this bundle is refused: ${signature.problem}`]), provenance }
@@ -762,7 +775,7 @@ export async function installBundleContent(
762
775
  if (code.length > 0 && !config.runtimeInstalls) return refuse([installsElsewhere], backup)
763
776
  // A bundle's value migrations are code too (story 300), unless they are the site's own.
764
777
  const migrations =
765
- input.provenance === 'local' || effective.withoutSchema ? [] : migrationChanges(config, carried)
778
+ vouch?.vouchedBy === 'site' || effective.withoutSchema ? [] : migrationChanges(config, carried)
766
779
  if (migrations.length > 0 && (!effective.installCode || !config.runtimeInstalls))
767
780
  return refuse(
768
781
  [
package/src/config.ts CHANGED
@@ -1144,7 +1144,7 @@ export function describeDatabase(
1144
1144
  }
1145
1145
  }
1146
1146
 
1147
- export const VERSION = '0.57.0'
1147
+ export const VERSION = '0.58.0'
1148
1148
 
1149
1149
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1150
1150
  /** A positive number from a setting, else the default. */
package/src/provenance.ts CHANGED
@@ -96,8 +96,9 @@ export interface ProvenanceFile {
96
96
  /**
97
97
  * `unchecked`: Sigstore's trusted root could not be had, so the signature was not
98
98
  * checked either way (story 244). Refused like `invalid`, and worth trying again.
99
+ * `vouched`: the host applied it, having authenticated it itself (story 319).
99
100
  */
100
- export type ProvenanceState = 'signed' | 'unsigned' | 'invalid' | 'unchecked' | 'local'
101
+ export type ProvenanceState = 'signed' | 'unsigned' | 'invalid' | 'unchecked' | 'local' | 'vouched'
101
102
 
102
103
  export interface ProvenanceResult {
103
104
  state: ProvenanceState
@@ -291,6 +292,8 @@ export function describeProvenance(result: ProvenanceResult): string {
291
292
  return 'Not signed'
292
293
  case 'local':
293
294
  return 'Local: from this machine, not a registry'
295
+ case 'vouched':
296
+ return 'Vouched for by the host'
294
297
  case 'invalid':
295
298
  return `Signature not accepted: ${result.reason ?? 'it does not check out'}`
296
299
  case 'unchecked':
@@ -571,7 +574,7 @@ export function provenanceProblem(
571
574
  return `its signature was not accepted: ${result.reason ?? 'it does not check out'}`
572
575
  if (result.state === 'unchecked')
573
576
  return `its signature could not be checked right now (${result.reason ?? 'try again'}); try again`
574
- if (result.state === 'local') return undefined
577
+ if (result.state === 'local' || result.state === 'vouched') return undefined
575
578
  if (result.state === 'unsigned')
576
579
  return policy.signatures === 'required'
577
580
  ? 'this site takes only signed bundles (CROMBOLO_BUNDLE_SIGNATURES=required); the producer signs it with `crombolo bundle sign` in GitHub Actions'
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'
@@ -286,6 +288,23 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
286
288
  return (await cache.media?.byKey(trimmed))?.url
287
289
  }
288
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
+
289
308
  const siteDefaults: SeoHost['siteDefaults'] = async () => {
290
309
  const { effective } = await settings()
291
310
  return {
@@ -293,6 +312,7 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
293
312
  titleSuffix: effective.titleSuffix || undefined,
294
313
  defaultImage: await imageAddress(effective.defaultImage),
295
314
  indexable: effective.indexable,
315
+ types: await typeMappings(),
296
316
  }
297
317
  }
298
318
 
@@ -406,6 +426,71 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
406
426
  return false
407
427
  }
408
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
+
409
494
  const preview = async (request: Request, principal: Principal): Promise<Response> => {
410
495
  const url = new URL(request.url)
411
496
  const key = url.searchParams.get('document') ?? ''
@@ -425,6 +510,7 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
425
510
  : null
426
511
  return Response.json({
427
512
  hasSeoFields: await composesSeoFields(draft.contentTypeAlias),
513
+ mapping: await mappingFor(draft.contentTypeAlias, principal),
428
514
  published: draft.published,
429
515
  differs,
430
516
  culture: draft.culture,
@@ -440,6 +526,7 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
440
526
 
441
527
  const handle: SeoHost['handle'] = async (request, subpath, principal) => {
442
528
  if (subpath === '/preview' && request.method === 'GET') return preview(request, principal)
529
+ if (subpath === '/type' && request.method === 'PUT') return saveType(request, principal)
443
530
  if (subpath !== '/settings') return undefined
444
531
  if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
445
532
  if (request.method === 'GET') return Response.json(await settings())
package/src/server.ts CHANGED
@@ -1281,14 +1281,18 @@ export async function createServer(
1281
1281
  /**
1282
1282
  * A back-office page, with its content security policy (story 313): its
1283
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`.
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).
1285
1286
  */
1286
1287
  const backOfficePage = (body: string): Response => {
1287
1288
  const nonce = newNonce()
1288
- const connect = extensions
1289
- .bundles()
1290
- .bundles.filter((pkg) => bundleGrants.isOn(pkg.id))
1291
- .flatMap((pkg) => declaredOrigins(pkg))
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
+ ]
1292
1296
  return new Response(body.replaceAll('<script', `<script nonce="${nonce}"`), {
1293
1297
  headers: {
1294
1298
  'content-type': 'text/html; charset=utf-8',
package/src/site-trust.ts CHANGED
@@ -187,31 +187,60 @@ export async function siteBundleTrust(
187
187
  ...(signedBy ? { signedBy } : {}),
188
188
  }
189
189
  }
190
- // An older version from the same signer is an old bundle put back.
191
190
  const pkg = result.package
192
- let downgraded: SiteBundleTrust['downgraded']
193
- if (pkg && signedBy) {
194
- const applied = await new TransferRunRepository(db)
195
- .versionsSignedBy(signedBy, pkg.name)
196
- .catch(() => [] as string[])
197
- const newer = applied
198
- .filter((version) => Bun.semver.order(version, pkg.version) > 0)
199
- .sort(Bun.semver.order)
200
- .at(-1)
201
- if (newer && !options.allowDowngrade)
202
- return {
203
- problem: `it is version ${pkg.version}, older than ${newer}, which this site already applied from the same signer. To roll back on purpose, apply it with --allow-downgrade`,
204
- signedBy,
205
- }
206
- if (newer) downgraded = { from: newer, to: pkg.version }
207
- }
191
+ const downgrade = pkg && signedBy ? await downgradeCheck(db, signedBy, pkg, options) : {}
192
+ if (downgrade.problem) return { problem: downgrade.problem, signedBy }
208
193
  return {
209
194
  signedBy,
210
195
  ...(trusted.id ? { entryId: trusted.id } : {}),
211
- ...(downgraded ? { downgraded } : {}),
196
+ ...(downgrade.downgraded ? { downgraded: downgrade.downgraded } : {}),
212
197
  }
213
198
  }
214
199
 
200
+ /** An older version from the same signer is an old bundle put back. */
201
+ async function downgradeCheck(
202
+ db: Db,
203
+ signedBy: string,
204
+ pkg: { name: string; version: string },
205
+ options: { allowDowngrade?: boolean },
206
+ ): Promise<Pick<SiteBundleTrust, 'problem' | 'downgraded'>> {
207
+ const applied = await new TransferRunRepository(db)
208
+ .versionsSignedBy(signedBy, pkg.name)
209
+ .catch(() => [] as string[])
210
+ const newer = applied
211
+ .filter((version) => Bun.semver.order(version, pkg.version) > 0)
212
+ .sort(Bun.semver.order)
213
+ .at(-1)
214
+ if (!newer) return {}
215
+ if (!options.allowDowngrade)
216
+ return {
217
+ problem: `it is version ${pkg.version}, older than ${newer}, which this site already applied from the same ${signedBy === HOST_SIGNER ? 'host' : 'signer'}. To roll back on purpose, apply it with --allow-downgrade`,
218
+ }
219
+ return { downgraded: { from: newer, to: pkg.version } }
220
+ }
221
+
222
+ /** What a run vouched for by the host records as its signer (story 319). */
223
+ export const HOST_SIGNER = 'host'
224
+
225
+ /**
226
+ * A bundle the host vouched for (story 319): no signer is asked for, but an
227
+ * older version than one the host already vouched for, by package name, is
228
+ * still refused without `allowDowngrade`.
229
+ */
230
+ export async function vouchedTrust(
231
+ db: Db,
232
+ pkg: { name: string; version: string },
233
+ options: { allowDowngrade?: boolean } = {},
234
+ ): Promise<SiteBundleTrust> {
235
+ const downgrade = await downgradeCheck(db, HOST_SIGNER, pkg, options)
236
+ return downgrade.problem
237
+ ? { problem: downgrade.problem, signedBy: HOST_SIGNER }
238
+ : {
239
+ signedBy: HOST_SIGNER,
240
+ ...(downgrade.downgraded ? { downgraded: downgrade.downgraded } : {}),
241
+ }
242
+ }
243
+
215
244
  /**
216
245
  * A package's files with this site's key signature added as `provenance.json`
217
246
  * (story 316); as they were where the site has no key.