@crombolo/server 0.55.0 → 0.57.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.
Files changed (48) hide show
  1. package/package.json +16 -13
  2. package/src/actions.ts +6 -1
  3. package/src/adapters/bundles.ts +72 -6
  4. package/src/adapters/health.ts +30 -1
  5. package/src/bundle-admin.ts +246 -23
  6. package/src/bundle-api.ts +299 -0
  7. package/src/bundle-build.ts +4 -3
  8. package/src/bundle-grants.ts +133 -18
  9. package/src/bundle-install.ts +140 -11
  10. package/src/bundle-sections.ts +49 -4
  11. package/src/bundles.ts +87 -7
  12. package/src/component-templates-api.ts +27 -6
  13. package/src/components.ts +7 -0
  14. package/src/config.ts +56 -3
  15. package/src/content-events.ts +17 -1
  16. package/src/core.ts +219 -15
  17. package/src/created-extension.ts +101 -0
  18. package/src/extension-components.ts +157 -0
  19. package/src/extension-discovery.ts +180 -0
  20. package/src/extension-process.ts +854 -0
  21. package/src/extension-sql.ts +85 -0
  22. package/src/index.ts +21 -0
  23. package/src/marketplace.ts +182 -54
  24. package/src/outbound-address.ts +182 -0
  25. package/src/owner-jobs.ts +7 -1
  26. package/src/ports.ts +8 -0
  27. package/src/provenance.ts +181 -15
  28. package/src/remote.ts +62 -10
  29. package/src/routes.ts +13 -1
  30. package/src/schema.ts +37 -6
  31. package/src/seed/compile.ts +4 -2
  32. package/src/seed/export.ts +1 -1
  33. package/src/seed/values.ts +3 -3
  34. package/src/seo.ts +13 -5
  35. package/src/server.ts +192 -45
  36. package/src/settings.ts +12 -4
  37. package/src/signing-keys.ts +155 -0
  38. package/src/site-content-values.ts +97 -0
  39. package/src/site-content.ts +292 -0
  40. package/src/site-events.ts +65 -0
  41. package/src/site-file.ts +20 -6
  42. package/src/site-public.ts +1 -1
  43. package/src/site-sections.ts +1 -1
  44. package/src/site-services.ts +4 -0
  45. package/src/site-trust.ts +238 -0
  46. package/src/transfer-dashboard.ts +6 -0
  47. package/src/trusted-signers-admin.ts +132 -0
  48. package/src/webhooks.ts +182 -17
@@ -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,8 +74,10 @@ import {
71
74
  carriedSections,
72
75
  carriesSections,
73
76
  changedFileSections,
77
+ type FileAction,
74
78
  keepDictionary,
75
79
  keptDictionary,
80
+ migrationChanges,
76
81
  planSections,
77
82
  promoteStaged,
78
83
  type RestoredFiles,
@@ -105,6 +110,7 @@ import {
105
110
  recordPruned,
106
111
  requiresProblems,
107
112
  } from './site-replace.ts'
113
+ import { type SiteBundleTrust, siteBundleTrust } from './site-trust.ts'
108
114
 
109
115
  /** The trees a content selector or placement may name. */
110
116
  export const CONTENT_OBJECT_TYPES = [
@@ -184,7 +190,7 @@ export function readBundle(
184
190
  target: string,
185
191
  siteDir: string,
186
192
  passphrase?: string,
187
- options: { withoutPeople?: boolean } = {},
193
+ options: { withoutPeople?: boolean; expects?: BundleType } = {},
188
194
  ): ResolvedBundle {
189
195
  const { directory, dependency } = locate(target, siteDir)
190
196
  const json = readPackageJson(join(directory, 'package.json'))
@@ -203,6 +209,18 @@ export function readBundle(
203
209
  read.problems.length > 0 ? read.problems : ['its package.json has no "crombolo" field'],
204
210
  )
205
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
+ )
206
224
  if (!pkg.contentDir)
207
225
  throw new CommandError(
208
226
  `${pkg.packageName} carries no content to install: its manifest names no "content".`,
@@ -285,6 +303,8 @@ function summarise(bundle: ResolvedBundle): BundleSummary {
285
303
  export interface TransferInput extends SectionOptions {
286
304
  /** A package directory on this machine, or the name of a bundle the site depends on. */
287
305
  bundle: string
306
+ /** The kind of bundle this way in takes (story 306); another is refused, saying which to use. */
307
+ expects?: BundleType
288
308
  /** Where the bundle's roots go: a path or a key. */
289
309
  under?: string
290
310
  /** Decisions by node key, on top of any the bundle carries: `"*"` and per property. */
@@ -309,6 +329,26 @@ export interface TransferInput extends SectionOptions {
309
329
  * signed and the site's policy never refuses (story 060).
310
330
  */
311
331
  provenance?: 'local'
332
+ /** Apply a site bundle older than one this site applied from the same signer (story 316). */
333
+ allowDowngrade?: boolean
334
+ }
335
+
336
+ /**
337
+ * Whether a bundle's signature lets it be applied here: a site bundle only from
338
+ * a signer this site trusts (story 316), an extension by the site's policy
339
+ * (story 060).
340
+ */
341
+ async function signatureDecision(
342
+ db: Db,
343
+ config: CromboloConfig,
344
+ bundle: ResolvedBundle,
345
+ provenance: ProvenanceResult,
346
+ input: Pick<TransferInput, 'allowDowngrade'>,
347
+ ): Promise<SiteBundleTrust> {
348
+ if (bundle.set.manifest.bundleType === 'site')
349
+ return siteBundleTrust(db, config, provenance, { allowDowngrade: input.allowDowngrade })
350
+ const problem = provenanceProblem(provenance, config.bundlePolicy)
351
+ return problem ? { problem } : {}
312
352
  }
313
353
 
314
354
  /** Where the bundle was built, checked before anything is read further (story 060). */
@@ -357,7 +397,7 @@ export async function transferOptions(
357
397
  under,
358
398
  resolutions,
359
399
  resolveAll,
360
- componentAliases: componentAliasesIn(config.componentsDir),
400
+ componentAliases: componentAliasesIn(config.componentsDir, config.siteDir),
361
401
  allowMissingBlobs: input.allowMissingBlobs ?? pending?.allowMissingBlobs ?? false,
362
402
  hasBlob: async (key: string) => Boolean(await store.get(key)),
363
403
  backOfficePath: config.backOfficePath,
@@ -378,8 +418,12 @@ export interface ContentCheckResult {
378
418
  sections: SectionPlan | undefined
379
419
  /** The code files installing it would change here; empty when it carries none, or the same. */
380
420
  code: SectionFile[]
421
+ /** For a site package (story 306): what it would replace that decides how the site runs. */
422
+ sitePackage?: SitePackageChanges
381
423
  /** Where it was built, from its signature (story 060). */
382
424
  provenance: ProvenanceResult
425
+ /** Applied, but a person should know why: unsigned or untrusted, outside production (story 316). */
426
+ signatureWarning?: string
383
427
  /** Nothing outstanding: the bundle would import cleanly. */
384
428
  clean: boolean
385
429
  /** With `publish`: the pages the import would not publish, and the reason publish gives. */
@@ -389,6 +433,55 @@ export interface ContentCheckResult {
389
433
  problems: string[]
390
434
  }
391
435
 
436
+ /** What a site package would replace that decides how the site runs: shown before the rest (story 306). */
437
+ export interface SitePackageChanges {
438
+ /** `crombolo.config.ts`: created, overwritten, or the same; null when it carries none. */
439
+ config: FileAction | null
440
+ /** `package.json`, which says what the site installs. */
441
+ packageJson: FileAction | null
442
+ /** Dependencies its `package.json` adds, removes or moves to another range. */
443
+ dependencies: { added: string[]; removed: string[]; changed: string[] }
444
+ }
445
+
446
+ const dependenciesOf = (text: string | undefined): Record<string, string> => {
447
+ try {
448
+ const json = JSON.parse(text ?? '{}') as { dependencies?: Record<string, string> }
449
+ return json.dependencies ?? {}
450
+ } catch {
451
+ return {}
452
+ }
453
+ }
454
+
455
+ /** What a site package's code half would change of the site's config and dependencies. */
456
+ export function sitePackageChanges(
457
+ config: CromboloConfig,
458
+ carried: CarriedSections,
459
+ ): SitePackageChanges {
460
+ const plan = planCode(config, carried)
461
+ const action = (file: string) =>
462
+ plan.find((entry) => entry.path === `${BUNDLE_SECTIONS.code}/${file}`)?.action ?? null
463
+ const carriedJson = carried.files.get(`${BUNDLE_SECTIONS.code}/package.json`)
464
+ const sitePackage = join(config.siteDir, 'package.json')
465
+ const incoming = dependenciesOf(carriedJson ? readFileSync(carriedJson, 'utf8') : undefined)
466
+ const current = dependenciesOf(
467
+ existsSync(sitePackage) ? readFileSync(sitePackage, 'utf8') : undefined,
468
+ )
469
+ const names = (record: Record<string, string>) => Object.keys(record).sort()
470
+ return {
471
+ config: action('crombolo.config.ts'),
472
+ packageJson: action('package.json'),
473
+ dependencies: carriedJson
474
+ ? {
475
+ added: names(incoming).filter((name) => !(name in current)),
476
+ removed: names(current).filter((name) => !(name in incoming)),
477
+ changed: names(incoming).filter(
478
+ (name) => name in current && current[name] !== incoming[name],
479
+ ),
480
+ }
481
+ : { added: [], removed: [], changed: [] },
482
+ }
483
+ }
484
+
392
485
  /** Read-only: what installing a bundle here would do. Its findings go to the Changes dashboard. */
393
486
  export async function checkBundleContent(
394
487
  db: Db,
@@ -396,11 +489,12 @@ export async function checkBundleContent(
396
489
  input: TransferInput,
397
490
  ): Promise<ContentCheckResult> {
398
491
  const bundle = readBundle(input.bundle, config.siteDir, input.passphrase, {
492
+ expects: input.expects,
399
493
  withoutPeople: input.excludePeople,
400
494
  })
401
495
  const provenance = await bundleProvenance(bundle, input)
402
- const refused = provenanceProblem(provenance, config.bundlePolicy)
403
- if (refused) throw new CommandError(`This bundle is refused: ${refused}.`)
496
+ const signature = await signatureDecision(db, config, bundle, provenance, input)
497
+ if (signature.problem) throw new CommandError(`This bundle is refused: ${signature.problem}.`)
404
498
  const set = bundle.set
405
499
  const prepared = await transferOptions(db, config, bundle, input)
406
500
  const check = await checkBundle(db, set, prepared.options)
@@ -435,7 +529,11 @@ export async function checkBundleContent(
435
529
  ? await planSections(db, config, bundle.carried, input)
436
530
  : undefined,
437
531
  code: codeChanges(planCode(config, bundle.carried)),
532
+ ...(bundle.set.manifest.bundleType === 'site'
533
+ ? { sitePackage: sitePackageChanges(config, bundle.carried) }
534
+ : {}),
438
535
  provenance,
536
+ ...(signature.warning ? { signatureWarning: signature.warning } : {}),
439
537
  clean: check.outstanding.length === 0,
440
538
  publishRefusals: refusals,
441
539
  decisions: {
@@ -485,6 +583,8 @@ export interface ContentImportResult {
485
583
  code?: CodeInstall
486
584
  /** Where it was built, from its signature (story 060); absent when refused before it was read. */
487
585
  provenance?: ProvenanceResult
586
+ /** Applied, but a person should know why: unsigned or untrusted, outside production (story 316). */
587
+ signatureWarning?: string
488
588
  }
489
589
 
490
590
  /**
@@ -561,6 +661,7 @@ export async function installBundleContent(
561
661
  input: ContentImportInput,
562
662
  ): Promise<ContentImportResult> {
563
663
  const bundle = readBundle(input.bundle, config.siteDir, input.passphrase, {
664
+ expects: input.expects,
564
665
  withoutPeople: input.excludePeople,
565
666
  })
566
667
  const { set, blobs, carried } = bundle
@@ -586,11 +687,11 @@ export async function installBundleContent(
586
687
 
587
688
  // What has to be true before anything is backed up or written.
588
689
  const provenance = await bundleProvenance(bundle, input)
589
- const signatureRefused = provenanceProblem(provenance, config.bundlePolicy)
590
- if (signatureRefused)
591
- return { ...refuse([`this bundle is refused: ${signatureRefused}`]), provenance }
690
+ const signature = await signatureDecision(db, config, bundle, provenance, input)
691
+ if (signature.problem)
692
+ return { ...refuse([`this bundle is refused: ${signature.problem}`]), provenance }
592
693
  if (replace && manifest.scope !== 'site')
593
- return refuse(['only a whole-site file (crombolo export --site) can replace a site'])
694
+ return refuse(['only a whole-site file (crombolo site export) can replace a site'])
594
695
  const missing = requiresProblems(manifest, config.siteDir)
595
696
  if (missing.length > 0) return refuse(missing)
596
697
  if (manifest.media === 'omitted' && !input.allowMissingBlobs)
@@ -655,11 +756,20 @@ export async function installBundleContent(
655
756
  )
656
757
  // The code half (story 241): only when asked, only where installs happen here.
657
758
  const code = effective.installCode ? codeChanges(planCode(config, carried)) : []
658
- if (code.length > 0 && !config.runtimeInstalls)
759
+ const installsElsewhere =
760
+ config.installsElsewhere?.message ??
761
+ "this site does not install code while it runs: add the bundle's code to the site and deploy it"
762
+ if (code.length > 0 && !config.runtimeInstalls) return refuse([installsElsewhere], backup)
763
+ // A bundle's value migrations are code too (story 300), unless they are the site's own.
764
+ const migrations =
765
+ input.provenance === 'local' || effective.withoutSchema ? [] : migrationChanges(config, carried)
766
+ if (migrations.length > 0 && (!effective.installCode || !config.runtimeInstalls))
659
767
  return refuse(
660
768
  [
661
- config.installsElsewhere?.message ??
662
- "this site does not install code while it runs: add the bundle's code to the site and deploy it",
769
+ effective.installCode
770
+ ? installsElsewhere
771
+ : 'this bundle brings schema migrations, which are code: install its code to bring them',
772
+ ...migrations.map((file) => file.path),
663
773
  ],
664
774
  backup,
665
775
  )
@@ -744,6 +854,7 @@ export async function installBundleContent(
744
854
  nodeId: config.nodeId,
745
855
  label: input.label,
746
856
  package: { name: bundle.package.packageName, version: bundle.package.version },
857
+ ...(signature.signedBy ? { signedBy: signature.signedBy } : {}),
747
858
  exact: Boolean(replace),
748
859
  })
749
860
  if (!imported.runId) throw new InstallRefused([], imported)
@@ -797,6 +908,23 @@ export async function installBundleContent(
797
908
  appliedBy: config.nodeId,
798
909
  note: `run ${runId}, ${bundle.package.packageName}@${bundle.package.version}${replace ? `, --${replace}` : ''}`,
799
910
  })
911
+ // The trusted signer's "last signed" on the Trusted signers list (story 316).
912
+ if (signature.entryId)
913
+ await new TrustedSignerRepository(db).signed(signature.entryId).catch(() => {})
914
+ // A rollback on purpose is on the record.
915
+ if (signature.downgraded)
916
+ await recordAudit(db, {
917
+ category: 'system',
918
+ action: 'Downgrade',
919
+ entityType: 'Site bundle',
920
+ entityName: `${bundle.package.packageName}@${bundle.package.version}`,
921
+ detail: `applied over ${signature.downgraded.from}, from the same signer, with --allow-downgrade`,
922
+ source: 'request',
923
+ userKey: null,
924
+ userName: input.by ?? config.nodeId,
925
+ ipAddress: null,
926
+ forwardedFor: null,
927
+ }).catch(() => {})
800
928
  return {
801
929
  bundle: summarise(bundle),
802
930
  backup,
@@ -813,6 +941,7 @@ export async function installBundleContent(
813
941
  ...(siteData ? { siteData } : {}),
814
942
  ...(codeInstalled ? { code: codeInstalled } : {}),
815
943
  provenance,
944
+ ...(signature.warning ? { signatureWarning: signature.warning } : {}),
816
945
  sections: staged
817
946
  ? {
818
947
  written: staged.written,
@@ -58,6 +58,11 @@ export interface SectionPlan {
58
58
  * site: `none` when the bundle carries no schema.
59
59
  */
60
60
  schema: { classification: string; findings: string[] } | undefined
61
+ /**
62
+ * The value migrations the bundle carries, `schema/migrations/<name>`: code,
63
+ * listed and never run by a check; they run only at install (story 300).
64
+ */
65
+ migrations: string[]
61
66
  /** Sections present in the bundle, for a caller that only wants to say so. */
62
67
  sections: BundleSection[]
63
68
  }
@@ -120,6 +125,21 @@ const FILE_SECTIONS: readonly BundleSection[] = ['components', 'styles', 'script
120
125
  const withinSection = (path: string, section: BundleSection): string =>
121
126
  path.slice(`${BUNDLE_SECTIONS[section]}/`.length)
122
127
 
128
+ /** A value migration a bundle carries: code, run when the schema syncs. */
129
+ export const isMigration = (path: string): boolean =>
130
+ /^migrations\/[^/]+\.(ts|js)$/.test(withinSection(path, 'schema'))
131
+
132
+ /** The value migrations a bundle would add or change here: code, as its `code/` is. */
133
+ export function migrationChanges(config: CromboloConfig, carried: CarriedSections): SectionFile[] {
134
+ return (carried.carries.schema ?? [])
135
+ .filter(isMigration)
136
+ .map((path) => {
137
+ const target = join(config.schemaDir, withinSection(path, 'schema'))
138
+ return { path, target, action: actionFor(target, sourceOf(carried, path)) }
139
+ })
140
+ .filter((file) => file.action !== 'unchanged')
141
+ }
142
+
123
143
  /** Compared as bytes: a public file is an image as often as it is text. */
124
144
  function actionFor(target: string, source: string): FileAction {
125
145
  if (!existsSync(target)) return 'create'
@@ -185,6 +205,7 @@ export async function planSections(
185
205
  return {
186
206
  files,
187
207
  dictionaryItems: (carried.carries.dictionary ?? []).length,
208
+ migrations: schemaPaths.filter(isMigration),
188
209
  schema:
189
210
  schemaPaths.length > 0
190
211
  ? await checkSchemaOverlay(db, config, carried, schemaPaths)
@@ -215,15 +236,20 @@ async function checkSchemaOverlay(
215
236
  mkdirSync(dirname(target), { recursive: true })
216
237
  writeFileSync(target, read(carried, path))
217
238
  }
239
+ // The site's own migrations only: a check never imports a module the bundle brings.
218
240
  const report = await checkSchemaDirectory(
219
241
  db,
220
242
  { ...config, schemaDir: overlay },
221
243
  { nodeId: config.nodeId, revision: config.schemaRevision },
244
+ { migrationsDir: config.schemaDir },
222
245
  )
223
- return {
224
- classification: report.classification,
225
- findings: report.outstanding.map((finding) => finding.message),
226
- }
246
+ const carriedMigrations = paths.filter(isMigration).map((path) => withinSection(path, 'schema'))
247
+ const findings = report.outstanding.map((finding) => finding.message)
248
+ if (carriedMigrations.length > 0 && report.outstanding.length > 0)
249
+ findings.push(
250
+ `The bundle brings ${carriedMigrations.map((m) => `schema/${m}`).join(', ')}, which runs only at install, so this check could not count on it.`,
251
+ )
252
+ return { classification: report.classification, findings }
227
253
  } finally {
228
254
  rmSync(overlay, { recursive: true, force: true })
229
255
  }
@@ -667,3 +693,22 @@ export function promoteStaged(config: CromboloConfig, dir: string, runId: string
667
693
  renameSync(dir, target)
668
694
  return target
669
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()