@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.
@@ -16,6 +16,7 @@ import { existsSync, readFileSync, rmSync } from 'node:fs'
16
16
  import { join, resolve } from 'node:path'
17
17
  import {
18
18
  type BundlePackage,
19
+ type BundleType,
19
20
  discoverBundles,
20
21
  isDirectory,
21
22
  PAYLOAD_MANIFEST,
@@ -34,6 +35,7 @@ import {
34
35
  recordInLedger,
35
36
  resolveNodeRef,
36
37
  TransferAnswerRepository,
38
+ TrustedSignerRepository,
37
39
  writeReport,
38
40
  } from '@crombolo/data'
39
41
  import {
@@ -56,6 +58,7 @@ import {
56
58
  WrongPassphraseError,
57
59
  writeResolutions,
58
60
  } from '@crombolo/transfer'
61
+ import { recordAudit } from './adapters/audit.ts'
59
62
  import { type BackupResult, backupBefore } from './backup.ts'
60
63
  import {
61
64
  type CodeInstall,
@@ -71,6 +74,7 @@ import {
71
74
  carriedSections,
72
75
  carriesSections,
73
76
  changedFileSections,
77
+ type FileAction,
74
78
  keepDictionary,
75
79
  keptDictionary,
76
80
  migrationChanges,
@@ -106,6 +110,7 @@ import {
106
110
  recordPruned,
107
111
  requiresProblems,
108
112
  } from './site-replace.ts'
113
+ import { type SiteBundleTrust, siteBundleTrust, vouchedTrust } from './site-trust.ts'
109
114
 
110
115
  /** The trees a content selector or placement may name. */
111
116
  export const CONTENT_OBJECT_TYPES = [
@@ -185,7 +190,7 @@ export function readBundle(
185
190
  target: string,
186
191
  siteDir: string,
187
192
  passphrase?: string,
188
- options: { withoutPeople?: boolean } = {},
193
+ options: { withoutPeople?: boolean; expects?: BundleType } = {},
189
194
  ): ResolvedBundle {
190
195
  const { directory, dependency } = locate(target, siteDir)
191
196
  const json = readPackageJson(join(directory, 'package.json'))
@@ -204,6 +209,18 @@ export function readBundle(
204
209
  read.problems.length > 0 ? read.problems : ['its package.json has no "crombolo" field'],
205
210
  )
206
211
  const pkg = read.bundle
212
+ // One way in for each kind (story 306): a site package is applied from a file,
213
+ // an extension installed as a dependency.
214
+ if (pkg.bundleType === 'site' && dependency)
215
+ throw new CommandError(
216
+ `${pkg.packageName} is a site package, which is applied to a site with \`crombolo site apply\`, never installed as a dependency.`,
217
+ )
218
+ if (options.expects && pkg.bundleType !== options.expects)
219
+ throw new CommandError(
220
+ pkg.bundleType === 'site'
221
+ ? `${target} is a site package: apply it with \`crombolo site apply\`.`
222
+ : `${target} is an extension: install it with \`crombolo extension install\`.`,
223
+ )
207
224
  if (!pkg.contentDir)
208
225
  throw new CommandError(
209
226
  `${pkg.packageName} carries no content to install: its manifest names no "content".`,
@@ -286,6 +303,8 @@ function summarise(bundle: ResolvedBundle): BundleSummary {
286
303
  export interface TransferInput extends SectionOptions {
287
304
  /** A package directory on this machine, or the name of a bundle the site depends on. */
288
305
  bundle: string
306
+ /** The kind of bundle this way in takes (story 306); another is refused, saying which to use. */
307
+ expects?: BundleType
289
308
  /** Where the bundle's roots go: a path or a key. */
290
309
  under?: string
291
310
  /** Decisions by node key, on top of any the bundle carries: `"*"` and per property. */
@@ -305,19 +324,50 @@ export interface TransferInput extends SectionOptions {
305
324
  * asked, as story 192 had it. Only where runtime installs are on.
306
325
  */
307
326
  installCode?: boolean
308
- /**
309
- * `local`: the site's own content files, built here, which no one else
310
- * signed and the site's policy never refuses (story 060).
311
- */
312
- provenance?: 'local'
327
+ /** Apply a site bundle older than one this site applied from the same signer (story 316). */
328
+ allowDowngrade?: boolean
313
329
  }
314
330
 
315
- /** Where the bundle was built, checked before anything is read further (story 060). */
316
- async function bundleProvenance(
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
+
343
+ /**
344
+ * Whether a bundle's signature lets it be applied here: a site bundle only from
345
+ * a signer this site trusts (story 316), an extension by the site's policy
346
+ * (story 060).
347
+ */
348
+ async function signatureDecision(
349
+ db: Db,
350
+ config: CromboloConfig,
317
351
  bundle: ResolvedBundle,
318
- input: Pick<TransferInput, 'provenance'>,
319
- ): Promise<ProvenanceResult> {
320
- if (input.provenance === 'local') return { state: 'local' }
352
+ provenance: ProvenanceResult,
353
+ input: Pick<TransferInput, 'allowDowngrade'>,
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
+ )
361
+ if (bundle.set.manifest.bundleType === 'site')
362
+ return siteBundleTrust(db, config, provenance, { allowDowngrade: input.allowDowngrade })
363
+ const problem = provenanceProblem(provenance, config.bundlePolicy)
364
+ return problem ? { problem } : {}
365
+ }
366
+
367
+ /** Where the bundle was built, checked before anything is read further (story 060). */
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' }
321
371
  return verifyProvenance(bundle.directory)
322
372
  }
323
373
 
@@ -358,7 +408,7 @@ export async function transferOptions(
358
408
  under,
359
409
  resolutions,
360
410
  resolveAll,
361
- componentAliases: componentAliasesIn(config.componentsDir),
411
+ componentAliases: componentAliasesIn(config.componentsDir, config.siteDir),
362
412
  allowMissingBlobs: input.allowMissingBlobs ?? pending?.allowMissingBlobs ?? false,
363
413
  hasBlob: async (key: string) => Boolean(await store.get(key)),
364
414
  backOfficePath: config.backOfficePath,
@@ -379,8 +429,12 @@ export interface ContentCheckResult {
379
429
  sections: SectionPlan | undefined
380
430
  /** The code files installing it would change here; empty when it carries none, or the same. */
381
431
  code: SectionFile[]
432
+ /** For a site package (story 306): what it would replace that decides how the site runs. */
433
+ sitePackage?: SitePackageChanges
382
434
  /** Where it was built, from its signature (story 060). */
383
435
  provenance: ProvenanceResult
436
+ /** Applied, but a person should know why: unsigned or untrusted, outside production (story 316). */
437
+ signatureWarning?: string
384
438
  /** Nothing outstanding: the bundle would import cleanly. */
385
439
  clean: boolean
386
440
  /** With `publish`: the pages the import would not publish, and the reason publish gives. */
@@ -390,18 +444,69 @@ export interface ContentCheckResult {
390
444
  problems: string[]
391
445
  }
392
446
 
447
+ /** What a site package would replace that decides how the site runs: shown before the rest (story 306). */
448
+ export interface SitePackageChanges {
449
+ /** `crombolo.config.ts`: created, overwritten, or the same; null when it carries none. */
450
+ config: FileAction | null
451
+ /** `package.json`, which says what the site installs. */
452
+ packageJson: FileAction | null
453
+ /** Dependencies its `package.json` adds, removes or moves to another range. */
454
+ dependencies: { added: string[]; removed: string[]; changed: string[] }
455
+ }
456
+
457
+ const dependenciesOf = (text: string | undefined): Record<string, string> => {
458
+ try {
459
+ const json = JSON.parse(text ?? '{}') as { dependencies?: Record<string, string> }
460
+ return json.dependencies ?? {}
461
+ } catch {
462
+ return {}
463
+ }
464
+ }
465
+
466
+ /** What a site package's code half would change of the site's config and dependencies. */
467
+ export function sitePackageChanges(
468
+ config: CromboloConfig,
469
+ carried: CarriedSections,
470
+ ): SitePackageChanges {
471
+ const plan = planCode(config, carried)
472
+ const action = (file: string) =>
473
+ plan.find((entry) => entry.path === `${BUNDLE_SECTIONS.code}/${file}`)?.action ?? null
474
+ const carriedJson = carried.files.get(`${BUNDLE_SECTIONS.code}/package.json`)
475
+ const sitePackage = join(config.siteDir, 'package.json')
476
+ const incoming = dependenciesOf(carriedJson ? readFileSync(carriedJson, 'utf8') : undefined)
477
+ const current = dependenciesOf(
478
+ existsSync(sitePackage) ? readFileSync(sitePackage, 'utf8') : undefined,
479
+ )
480
+ const names = (record: Record<string, string>) => Object.keys(record).sort()
481
+ return {
482
+ config: action('crombolo.config.ts'),
483
+ packageJson: action('package.json'),
484
+ dependencies: carriedJson
485
+ ? {
486
+ added: names(incoming).filter((name) => !(name in current)),
487
+ removed: names(current).filter((name) => !(name in incoming)),
488
+ changed: names(incoming).filter(
489
+ (name) => name in current && current[name] !== incoming[name],
490
+ ),
491
+ }
492
+ : { added: [], removed: [], changed: [] },
493
+ }
494
+ }
495
+
393
496
  /** Read-only: what installing a bundle here would do. Its findings go to the Changes dashboard. */
394
497
  export async function checkBundleContent(
395
498
  db: Db,
396
499
  config: CromboloConfig,
397
500
  input: TransferInput,
501
+ vouch?: Vouch,
398
502
  ): Promise<ContentCheckResult> {
399
503
  const bundle = readBundle(input.bundle, config.siteDir, input.passphrase, {
504
+ expects: input.expects,
400
505
  withoutPeople: input.excludePeople,
401
506
  })
402
- const provenance = await bundleProvenance(bundle, input)
403
- const refused = provenanceProblem(provenance, config.bundlePolicy)
404
- if (refused) throw new CommandError(`This bundle is refused: ${refused}.`)
507
+ const provenance = await bundleProvenance(bundle, vouch)
508
+ const signature = await signatureDecision(db, config, bundle, provenance, input)
509
+ if (signature.problem) throw new CommandError(`This bundle is refused: ${signature.problem}.`)
405
510
  const set = bundle.set
406
511
  const prepared = await transferOptions(db, config, bundle, input)
407
512
  const check = await checkBundle(db, set, prepared.options)
@@ -436,7 +541,11 @@ export async function checkBundleContent(
436
541
  ? await planSections(db, config, bundle.carried, input)
437
542
  : undefined,
438
543
  code: codeChanges(planCode(config, bundle.carried)),
544
+ ...(bundle.set.manifest.bundleType === 'site'
545
+ ? { sitePackage: sitePackageChanges(config, bundle.carried) }
546
+ : {}),
439
547
  provenance,
548
+ ...(signature.warning ? { signatureWarning: signature.warning } : {}),
440
549
  clean: check.outstanding.length === 0,
441
550
  publishRefusals: refusals,
442
551
  decisions: {
@@ -486,6 +595,8 @@ export interface ContentImportResult {
486
595
  code?: CodeInstall
487
596
  /** Where it was built, from its signature (story 060); absent when refused before it was read. */
488
597
  provenance?: ProvenanceResult
598
+ /** Applied, but a person should know why: unsigned or untrusted, outside production (story 316). */
599
+ signatureWarning?: string
489
600
  }
490
601
 
491
602
  /**
@@ -560,8 +671,10 @@ export async function installBundleContent(
560
671
  db: Db,
561
672
  config: CromboloConfig,
562
673
  input: ContentImportInput,
674
+ vouch?: Vouch,
563
675
  ): Promise<ContentImportResult> {
564
676
  const bundle = readBundle(input.bundle, config.siteDir, input.passphrase, {
677
+ expects: input.expects,
565
678
  withoutPeople: input.excludePeople,
566
679
  })
567
680
  const { set, blobs, carried } = bundle
@@ -586,12 +699,12 @@ export async function installBundleContent(
586
699
  })
587
700
 
588
701
  // What has to be true before anything is backed up or written.
589
- const provenance = await bundleProvenance(bundle, input)
590
- const signatureRefused = provenanceProblem(provenance, config.bundlePolicy)
591
- if (signatureRefused)
592
- return { ...refuse([`this bundle is refused: ${signatureRefused}`]), provenance }
702
+ const provenance = await bundleProvenance(bundle, vouch)
703
+ const signature = await signatureDecision(db, config, bundle, provenance, input)
704
+ if (signature.problem)
705
+ return { ...refuse([`this bundle is refused: ${signature.problem}`]), provenance }
593
706
  if (replace && manifest.scope !== 'site')
594
- return refuse(['only a whole-site file (crombolo export --site) can replace a site'])
707
+ return refuse(['only a whole-site file (crombolo site export) can replace a site'])
595
708
  const missing = requiresProblems(manifest, config.siteDir)
596
709
  if (missing.length > 0) return refuse(missing)
597
710
  if (manifest.media === 'omitted' && !input.allowMissingBlobs)
@@ -662,7 +775,7 @@ export async function installBundleContent(
662
775
  if (code.length > 0 && !config.runtimeInstalls) return refuse([installsElsewhere], backup)
663
776
  // A bundle's value migrations are code too (story 300), unless they are the site's own.
664
777
  const migrations =
665
- input.provenance === 'local' || effective.withoutSchema ? [] : migrationChanges(config, carried)
778
+ vouch?.vouchedBy === 'site' || effective.withoutSchema ? [] : migrationChanges(config, carried)
666
779
  if (migrations.length > 0 && (!effective.installCode || !config.runtimeInstalls))
667
780
  return refuse(
668
781
  [
@@ -754,6 +867,7 @@ export async function installBundleContent(
754
867
  nodeId: config.nodeId,
755
868
  label: input.label,
756
869
  package: { name: bundle.package.packageName, version: bundle.package.version },
870
+ ...(signature.signedBy ? { signedBy: signature.signedBy } : {}),
757
871
  exact: Boolean(replace),
758
872
  })
759
873
  if (!imported.runId) throw new InstallRefused([], imported)
@@ -807,6 +921,23 @@ export async function installBundleContent(
807
921
  appliedBy: config.nodeId,
808
922
  note: `run ${runId}, ${bundle.package.packageName}@${bundle.package.version}${replace ? `, --${replace}` : ''}`,
809
923
  })
924
+ // The trusted signer's "last signed" on the Trusted signers list (story 316).
925
+ if (signature.entryId)
926
+ await new TrustedSignerRepository(db).signed(signature.entryId).catch(() => {})
927
+ // A rollback on purpose is on the record.
928
+ if (signature.downgraded)
929
+ await recordAudit(db, {
930
+ category: 'system',
931
+ action: 'Downgrade',
932
+ entityType: 'Site bundle',
933
+ entityName: `${bundle.package.packageName}@${bundle.package.version}`,
934
+ detail: `applied over ${signature.downgraded.from}, from the same signer, with --allow-downgrade`,
935
+ source: 'request',
936
+ userKey: null,
937
+ userName: input.by ?? config.nodeId,
938
+ ipAddress: null,
939
+ forwardedFor: null,
940
+ }).catch(() => {})
810
941
  return {
811
942
  bundle: summarise(bundle),
812
943
  backup,
@@ -823,6 +954,7 @@ export async function installBundleContent(
823
954
  ...(siteData ? { siteData } : {}),
824
955
  ...(codeInstalled ? { code: codeInstalled } : {}),
825
956
  provenance,
957
+ ...(signature.warning ? { signatureWarning: signature.warning } : {}),
826
958
  sections: staged
827
959
  ? {
828
960
  written: staged.written,
@@ -693,3 +693,22 @@ export function promoteStaged(config: CromboloConfig, dir: string, runId: string
693
693
  renameSync(dir, target)
694
694
  return target
695
695
  }
696
+
697
+ /**
698
+ * The components a run wrote into the site's `components/` (story 312): an
699
+ * extension's, copied before its components stayed in its package. A run that
700
+ * swapped the whole folder in names the folder.
701
+ */
702
+ export function componentsWritten(config: CromboloConfig, runId: string): string[] {
703
+ if (swappedSections(config, runId).includes('components')) return ['components/']
704
+ const record = join(config.siteDir, RUN_BACKUP_DIR, runId, RECORD_FILE)
705
+ if (!existsSync(record)) return []
706
+ try {
707
+ return (JSON.parse(readFileSync(record, 'utf8')) as FileRecord[])
708
+ .filter((entry) => entry.action !== 'unchanged' && entry.path.startsWith('components/'))
709
+ .map((entry) => entry.path)
710
+ .sort()
711
+ } catch {
712
+ return []
713
+ }
714
+ }
package/src/bundles.ts CHANGED
@@ -49,8 +49,8 @@
49
49
  import { hasCultureAccess, hasSection, type Principal } from '@crombolo/api-management/domain'
50
50
  import {
51
51
  BUNDLE_ID,
52
- BUNDLE_SCHEMA_VERSION,
53
52
  type BundlePackage,
53
+ OLDEST_BUNDLE_SCHEMA_VERSION,
54
54
  peerRangeProblem,
55
55
  schemaProblem,
56
56
  } from '@crombolo/backoffice-host/registry'
@@ -82,10 +82,13 @@ import {
82
82
  type SiteServices,
83
83
  } from '@crombolo/render'
84
84
  import { anonymiseProblems } from './anonymise-rules.ts'
85
+ import type { BundleApi } from './bundle-api.ts'
85
86
  import {
86
87
  declaredPermissions,
87
88
  disabledResponse,
88
89
  gated,
90
+ isSchema3,
91
+ PermissionRefusedError,
89
92
  permissionProblems,
90
93
  } from './bundle-grants.ts'
91
94
  import type { BundleMedia, BundleMediaDeclaration } from './bundle-media.ts'
@@ -180,6 +183,19 @@ export interface BundleHost {
180
183
  * given or the back-office user; refused on a public route (story 198).
181
184
  */
182
185
  media: BundleMedia
186
+ /**
187
+ * The site's areas through the Management API and the CMS's back-office API,
188
+ * as the extension or the user it acts for, each call held to its grant
189
+ * (story 308): `api.get('management/api/v1/document/<key>')`.
190
+ */
191
+ api: BundleApi
192
+ /** Requests out, only to the origins its `http.outbound` names, by the address rule (story 301). */
193
+ fetch: BundleFetch
194
+ }
195
+
196
+ /** `fetch`, held to the origins an extension was granted. */
197
+ export interface BundleFetch {
198
+ fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>
183
199
  }
184
200
 
185
201
  export type BundleCapability = keyof BundleHost
@@ -219,6 +235,8 @@ export const BUNDLE_CAPABILITIES: readonly BundleCapability[] = [
219
235
  'log',
220
236
  'identityProviders',
221
237
  'media',
238
+ 'api',
239
+ 'fetch',
222
240
  ]
223
241
 
224
242
  /**
@@ -436,11 +454,33 @@ export function validateServerBundles(
436
454
  problems.push(...jobProblems(`Bundle "${label}"`, bundle.jobs, bundle.schedules))
437
455
  {
438
456
  const pkg = packages.find((candidate) => candidate.id === bundle.id)
439
- if (pkg?.carries.server && Array.isArray(pkg.field.permissions))
440
- problems.push(...permissionProblems(label, bundle.capabilities, declaredPermissions(pkg)))
457
+ if (pkg?.carries.server && pkg.field.permissions !== undefined) {
458
+ const declared = declaredPermissions(pkg)
459
+ problems.push(
460
+ ...permissionProblems(label, bundle.capabilities, declared, pkg.carries.extensions),
461
+ )
462
+ // Schema 4 asks for what it does as well as what it calls (story 308).
463
+ if (!isSchema3(pkg)) {
464
+ if (
465
+ bundle.events &&
466
+ Object.keys(bundle.events).length > 0 &&
467
+ !declared.includes('events.content')
468
+ )
469
+ problems.push(
470
+ `Bundle "${label}" handles content events, and so needs "events.content" in "crombolo.permissions".`,
471
+ )
472
+ if (
473
+ (bundle.routes ?? []).some((route) => route?.options && onSite(route)) &&
474
+ !declared.includes('routes.public')
475
+ )
476
+ problems.push(
477
+ `Bundle "${label}" answers routes on the site, and so needs "routes.public" in "crombolo.permissions".`,
478
+ )
479
+ }
480
+ }
441
481
  }
442
482
  const owner = packages.find((pkg) => pkg.id === bundle.id)
443
- if (owner?.carries.server && (owner.field.schemaVersion ?? 1) < BUNDLE_SCHEMA_VERSION)
483
+ if (owner?.carries.server && (owner.field.schemaVersion ?? 1) < OLDEST_BUNDLE_SCHEMA_VERSION)
444
484
  problems.push(`Bundle "${label}": ${schemaProblem(owner.field.schemaVersion ?? 1)}.`)
445
485
  const routes = new Set<string>()
446
486
  for (const route of bundle.routes ?? []) {
@@ -689,13 +729,15 @@ export interface ServerBundlesOptions {
689
729
  coreVersion: string
690
730
  /** `<backoffice>/crombolo/api`, from `createBackOfficePaths`. */
691
731
  pluginApiPath: string
692
- host: Omit<BundleHost, 'media'> & { media?: BundleMedia }
732
+ host: Omit<BundleHost, 'media' | 'api' | 'fetch'> & { media?: BundleMedia }
693
733
  /** Capabilities built per request from the caller, in place of the ones in `host`. */
694
734
  callerHost?: CallerCapabilities
695
735
  /** Named per bundle, so a log line says which one wrote it. */
696
736
  log(bundleId: string): BundleLog
697
737
  /** A bundle's own tables, on the connection that reaches only them; absent where none are. */
698
738
  database?(bundle: ServerBundle): TablesDatabase | undefined
739
+ /** What a bundle may use now, from its grant (story 309); its declaration when absent. */
740
+ granted?(bundleId: string): readonly string[]
699
741
  /**
700
742
  * Whether a bundle is turned on: its grant covers what it declares (story
701
743
  * 222). A bundle that is off answers every route as waiting. Absent, all are on.
@@ -808,14 +850,26 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
808
850
  caller: BundleCaller,
809
851
  ): Pick<BundleHost, BundleCapability> => {
810
852
  const host: Record<string, unknown> = {}
811
- const declared = declaredPermissions(owners.get(bundle.id))
853
+ // What it was granted, not what it declares (story 309).
854
+ const declared = options.granted
855
+ ? options.granted(bundle.id)
856
+ : declaredPermissions(owners.get(bundle.id))
812
857
  for (const capability of bundle.capabilities) {
858
+ // Acting for a member needs `member.delegate`, on every call (story 309).
859
+ if (
860
+ capability === 'media' &&
861
+ caller.kind === 'member' &&
862
+ !declared.includes('member.delegate')
863
+ ) {
864
+ host[capability] = refusing(bundle.id, 'member.delegate', MEDIA_METHODS)
865
+ continue
866
+ }
813
867
  const forCaller = options.callerHost?.[capability]
814
868
  const given = forCaller
815
869
  ? forCaller(caller, bundle)
816
870
  : capability === 'log'
817
871
  ? (logs.get(bundle.id) as BundleLog)
818
- : options.host[capability]
872
+ : (options.host as Partial<BundleHost>)[capability]
819
873
  // Only what its declared permissions allow (story 222).
820
874
  host[capability] = given ? gated(bundle.id, capability, given, declared) : given
821
875
  }
@@ -825,6 +879,22 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
825
879
  return Object.freeze(host) as Pick<BundleHost, BundleCapability>
826
880
  }
827
881
 
882
+ /**
883
+ * A capability whose every method is refused, naming the permission it would
884
+ * need. Its methods are named, so an extension in its own process sees them too.
885
+ */
886
+ const refusing = (bundleId: string, permission: string, methods: readonly string[]) =>
887
+ Object.freeze(
888
+ Object.fromEntries(
889
+ methods.map((method) => [
890
+ method,
891
+ () => {
892
+ throw new PermissionRefusedError(bundleId, permission)
893
+ },
894
+ ]),
895
+ ),
896
+ )
897
+
828
898
  /** A site route that answers as waiting while its bundle is off. */
829
899
  const whileOn = (bundleId: string, route: SiteRoute): SiteRoute => {
830
900
  const isOn = options.isOn
@@ -898,3 +968,13 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
898
968
  }
899
969
 
900
970
  const PUBLIC_CALLER: BundleCaller = Object.freeze({ kind: 'public' })
971
+
972
+ /** `BundleMedia`'s methods, refused one by one without `member.delegate`. */
973
+ const MEDIA_METHODS: readonly (keyof BundleMedia)[] = [
974
+ 'create',
975
+ 'get',
976
+ 'update',
977
+ 'delete',
978
+ 'list',
979
+ 'crop',
980
+ ]
@@ -13,28 +13,49 @@ export interface ComponentTemplate {
13
13
  alias: string
14
14
  /** The template's key, or null for a component no template row names yet. */
15
15
  id: string | null
16
+ /** The extension that renders it, by name, when one does (story 312). */
17
+ extension?: string
16
18
  }
17
19
 
18
- /** Every component on disk and every template row, joined by alias, by alias. Pure. */
20
+ /**
21
+ * Every component on disk, every extension's, and every template row, joined by
22
+ * alias, by alias. The site's own file wins over an extension's of the same alias. Pure.
23
+ */
19
24
  export function componentTemplates(
20
25
  onDisk: readonly string[],
21
26
  rows: readonly { key: string; alias: string }[],
27
+ extensions: readonly { alias: string; extension: string }[] = [],
22
28
  ): ComponentTemplate[] {
23
29
  const keys = new Map(rows.map((row) => [row.alias, row.key]))
24
- const aliases = new Set([...onDisk, ...rows.map((row) => row.alias)])
25
- return [...aliases].sort().map((alias) => ({ alias, id: keys.get(alias) ?? null }))
30
+ const files = new Set(onDisk)
31
+ const owners = new Map(
32
+ extensions
33
+ .filter((entry) => !files.has(entry.alias))
34
+ .map((entry) => [entry.alias, entry.extension]),
35
+ )
36
+ const aliases = new Set([...onDisk, ...owners.keys(), ...rows.map((row) => row.alias)])
37
+ return [...aliases].sort().map((alias) => {
38
+ const extension = owners.get(alias)
39
+ return { alias, id: keys.get(alias) ?? null, ...(extension ? { extension } : {}) }
40
+ })
26
41
  }
27
42
 
28
43
  export async function handleComponentTemplates(
29
44
  request: Request,
30
45
  principal: Principal,
31
- options: { db: Db; componentsDir: string },
46
+ options: {
47
+ db: Db
48
+ componentsDir: string
49
+ /** The extensions' components, read-only, each with its extension's name. */
50
+ extensionComponents?: () => readonly { alias: string; extension: string }[]
51
+ },
32
52
  ): Promise<Response> {
33
53
  const repo = new ComponentRepository(options.db)
34
54
  const onDisk = listComponents(options.componentsDir).map((file) => file.alias)
55
+ const extensions = options.extensionComponents?.() ?? []
35
56
 
36
57
  if (request.method === 'GET')
37
- return Response.json({ items: componentTemplates(onDisk, await repo.all()) })
58
+ return Response.json({ items: componentTemplates(onDisk, await repo.all(), extensions) })
38
59
 
39
60
  if (request.method === 'POST') {
40
61
  // As changing which templates a type allows: Structure, which Settings brings.
@@ -45,7 +66,7 @@ export async function handleComponentTemplates(
45
66
  )
46
67
  const body = (await request.json().catch(() => ({}))) as { alias?: unknown }
47
68
  const alias = typeof body.alias === 'string' ? body.alias : ''
48
- if (!onDisk.includes(alias))
69
+ if (!onDisk.includes(alias) && !extensions.some((entry) => entry.alias === alias))
49
70
  return Response.json({ message: 'There is no component with that name.' }, { status: 404 })
50
71
  const existing = await repo.byAlias(alias)
51
72
  if (existing) return Response.json({ id: existing.key })
package/src/components.ts CHANGED
@@ -540,3 +540,10 @@ export function assetScaffold(kind: AssetKind, name: string): string {
540
540
  ? `/* ${name} — linked from a view with <link rel="stylesheet" href="/css/${name}"> */\n`
541
541
  : `// ${name} — loaded by a view with <script src="/scripts/${name}"></script>\n`
542
542
  }
543
+
544
+ /** The site's components a `layout` setting may name: all but blocks (story 312). */
545
+ export const siteLayouts = (componentsDir: string): string[] =>
546
+ listComponents(componentsDir)
547
+ .map((component) => component.alias)
548
+ .filter((alias) => !alias.startsWith('blocks/'))
549
+ .sort()
package/src/config.ts CHANGED
@@ -543,6 +543,20 @@ export interface CromboloConfig {
543
543
  * development site. docs/webhooks.md.
544
544
  */
545
545
  webhooks?: { headerVariables?: readonly string[]; allowPrivateAddresses?: boolean }
546
+ /**
547
+ * Installed extensions the site's code grants and sets (story 310), by bundle
548
+ * id: what it grants, as "Developer installed", and settings, which lock them
549
+ * in the back office. Plain data: nothing is imported.
550
+ * docs/bundles.md, "Extensions run once granted".
551
+ */
552
+ extensions?: Readonly<Record<string, ExtensionEntry>>
553
+ /**
554
+ * Keys this site trusts to sign the site bundles it applies, locked in
555
+ * Settings (story 316): a person's, a CI job's or another site's public line.
556
+ */
557
+ trustedKeys?: readonly { name: string; publicKey: string; kind?: 'user' | 'site' }[]
558
+ /** CI builds this site trusts to sign them, by Sigstore: `org/repo@v*` (story 316). */
559
+ trustedSources?: readonly { name: string; source: string }[]
546
560
  /**
547
561
  * Package names this installation provides to every site it runs, rather
548
562
  * than the site choosing them (story 177): a whole-site file leaves them out
@@ -603,6 +617,25 @@ export interface CromboloConfig {
603
617
  host: HostConfig | undefined
604
618
  }
605
619
 
620
+ /** One installed extension, as the config grants and sets it (story 310). */
621
+ export interface ExtensionEntry {
622
+ /** Exactly the permissions it may use; a version asking for more is off until this names it. */
623
+ grant?: readonly string[]
624
+ /** The origins its `http.outbound` may reach, when it asks for any. */
625
+ origins?: readonly string[]
626
+ /** Whom `actAs` acts for: `caller`, or `user:<key>`. */
627
+ actAs?: string
628
+ /** Its settings' values, locked in the back office. */
629
+ settings?: Readonly<Record<string, unknown>>
630
+ /**
631
+ * On a developer's machine only: more for its process to read and reach while
632
+ * the extension is being worked on. Refused when `NODE_ENV` is `production`.
633
+ */
634
+ dev?: { allowRead?: readonly string[]; allowNet?: readonly string[] }
635
+ /** How long a route, event or workflow of it may take, in milliseconds: 30 seconds unless set. */
636
+ timeoutMs?: number
637
+ }
638
+
606
639
  export type SiteConfig = CromboloConfig
607
640
 
608
641
  export const DEFAULTS = {
@@ -640,8 +673,8 @@ export const DEFAULTS = {
640
673
  logsDir: 'logs',
641
674
  scriptsDir: 'scripts',
642
675
  publicDir: 'public',
643
- marketplaceUrl: 'https://www.npmjs.com/search?q=keywords%3Acrombolo-bundle',
644
- packageKeyword: 'crombolo-bundle',
676
+ marketplaceUrl: 'https://www.npmjs.com/search?q=keywords%3Acrombolo-extension',
677
+ packageKeyword: 'crombolo-extension',
645
678
  npmRegistry: 'https://registry.npmjs.org',
646
679
  keepAllVersionsNewerThanDays: 7,
647
680
  keepLatestVersionPerDayForDays: 90,
@@ -1111,7 +1144,7 @@ export function describeDatabase(
1111
1144
  }
1112
1145
  }
1113
1146
 
1114
- export const VERSION = '0.56.0'
1147
+ export const VERSION = '0.58.0'
1115
1148
 
1116
1149
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1117
1150
  /** A positive number from a setting, else the default. */