@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/provenance.ts CHANGED
@@ -13,6 +13,14 @@ import { bundleFromJSON, type SerializedBundle } from '@sigstore/bundle'
13
13
  import { X509Certificate } from '@sigstore/core'
14
14
  import { TrustedRoot } from '@sigstore/protobuf-specs'
15
15
  import { toSignedEntity, toTrustMaterial, Verifier } from '@sigstore/verify'
16
+ import {
17
+ type KeyPair,
18
+ type PublicKey,
19
+ readPublicKey,
20
+ signedStatement,
21
+ signWith,
22
+ verifiedBy,
23
+ } from './signing-keys.ts'
16
24
 
17
25
  /** The file in a package that holds its signature, and the one file the digest leaves out. */
18
26
  export const PROVENANCE_FILE = 'provenance.json'
@@ -67,30 +75,54 @@ export interface ProvenanceLinks {
67
75
  log: string | null
68
76
  }
69
77
 
70
- /** `provenance.json`. */
78
+ /** A key's signature (story 316): its public line, over the digest, name and version. */
79
+ export interface KeySignatureFile {
80
+ publicKey: string
81
+ signature: string
82
+ name: string
83
+ version: string
84
+ }
85
+
86
+ /** `provenance.json`: a Sigstore signature from CI, a key's, or both. */
71
87
  export interface ProvenanceFile {
72
88
  format: 1
73
89
  digest: string
74
- signature: SerializedBundle
75
- source: ProvenanceSource
76
- links: ProvenanceLinks
90
+ signature?: SerializedBundle
91
+ source?: ProvenanceSource
92
+ links?: ProvenanceLinks
93
+ key?: KeySignatureFile
77
94
  }
78
95
 
79
96
  /**
80
97
  * `unchecked`: Sigstore's trusted root could not be had, so the signature was not
81
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).
82
100
  */
83
- export type ProvenanceState = 'signed' | 'unsigned' | 'invalid' | 'unchecked' | 'local'
101
+ export type ProvenanceState = 'signed' | 'unsigned' | 'invalid' | 'unchecked' | 'local' | 'vouched'
84
102
 
85
103
  export interface ProvenanceResult {
86
104
  state: ProvenanceState
87
105
  digest?: string
106
+ /** The CI build that signed it, by Sigstore. */
88
107
  source?: ProvenanceSource
89
108
  links?: ProvenanceLinks
109
+ /** The key that signed it (story 316). */
110
+ key?: PublicKey
111
+ /** The package it is, from its own signed `package.json`, for the downgrade check. */
112
+ package?: { name: string; version: string }
90
113
  /** Why a signature was not accepted, in words a person can act on. */
91
114
  reason?: string
92
115
  }
93
116
 
117
+ /** A package's `provenance.json`, when it has one that reads. */
118
+ function readProvenance(dir: string): ProvenanceFile | undefined {
119
+ try {
120
+ return JSON.parse(readFileSync(join(dir, PROVENANCE_FILE), 'utf8')) as ProvenanceFile
121
+ } catch {
122
+ return undefined
123
+ }
124
+ }
125
+
94
126
  /** Every file a package's digest covers: all of it but its signature, installs and history. */
95
127
  function packageFiles(dir: string): string[] {
96
128
  const out: string[] = []
@@ -113,16 +145,73 @@ function packageFiles(dir: string): string[] {
113
145
  * integrity does not: `package.json` and an extension bundle's code.
114
146
  */
115
147
  export function packageDigest(dir: string): string {
148
+ return digestOfFiles(
149
+ packageFiles(dir).map((path) => ({ path, bytes: readFileSync(join(dir, path)) })),
150
+ )
151
+ }
152
+
153
+ /** The same digest, of files held in memory: a package not yet written out. */
154
+ export function digestOfFiles(files: readonly { path: string; bytes: Uint8Array }[]): string {
116
155
  const hasher = new Bun.CryptoHasher('sha256')
117
- for (const path of packageFiles(dir)) {
118
- hasher.update(path)
156
+ for (const file of files
157
+ .filter((entry) => entry.path !== PROVENANCE_FILE)
158
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))) {
159
+ hasher.update(file.path)
119
160
  hasher.update('\0')
120
- hasher.update(readFileSync(join(dir, path)))
161
+ hasher.update(file.bytes)
121
162
  hasher.update('\n')
122
163
  }
123
164
  return `sha256-${hasher.digest('hex')}`
124
165
  }
125
166
 
167
+ /** A package's name and version, from its `package.json`. */
168
+ function packageOf(dir: string): { name: string; version: string } | undefined {
169
+ try {
170
+ const json = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as {
171
+ name?: unknown
172
+ version?: unknown
173
+ }
174
+ return typeof json.name === 'string' && typeof json.version === 'string'
175
+ ? { name: json.name, version: json.version }
176
+ : undefined
177
+ } catch {
178
+ return undefined
179
+ }
180
+ }
181
+
182
+ /**
183
+ * A key's signature over a package's files (story 316), as `provenance.json`
184
+ * holds it; a Sigstore signature already there is kept beside it.
185
+ */
186
+ export function keySignatureOver(
187
+ files: readonly { path: string; bytes: Uint8Array }[],
188
+ pair: KeyPair,
189
+ existing?: ProvenanceFile,
190
+ ): ProvenanceFile {
191
+ const json = files.find((file) => file.path === 'package.json')
192
+ const pkg = json
193
+ ? (JSON.parse(new TextDecoder().decode(json.bytes)) as { name?: string; version?: string })
194
+ : {}
195
+ if (!pkg.name || !pkg.version) throw new Error('A bundle is signed once it is a package.')
196
+ const digest = digestOfFiles(files)
197
+ if (existing?.digest && existing.digest !== digest)
198
+ throw new Error('The bundle changed after its CI signature: sign it with its key first.')
199
+ return {
200
+ ...(existing ?? {}),
201
+ format: 1,
202
+ digest,
203
+ key: {
204
+ publicKey: pair.publicKey.line,
205
+ signature: signWith(
206
+ pair.privateKey,
207
+ signedStatement({ digest, name: pkg.name, version: pkg.version }),
208
+ ),
209
+ name: pkg.name,
210
+ version: pkg.version,
211
+ },
212
+ }
213
+ }
214
+
126
215
  const hexOf = (digest: string) => digest.replace(/^sha256-/, '')
127
216
 
128
217
  /** The statement signed: the digest alone, so the public log learns nothing of the bundle but it. */
@@ -189,13 +278,22 @@ export const refName = (ref: string): string => ref.replace(/^refs\/(tags|heads)
189
278
  export function describeProvenance(result: ProvenanceResult): string {
190
279
  switch (result.state) {
191
280
  case 'signed': {
192
- const source = result.source as ProvenanceSource
193
- return `Signed: built from github.com/${source.repository} at ${refName(source.ref)} (${source.commit.slice(0, 7)})`
281
+ const source = result.source
282
+ const built = source
283
+ ? `built from github.com/${source.repository} at ${refName(source.ref)} (${source.commit.slice(0, 7)})`
284
+ : undefined
285
+ const key = result.key
286
+ ? `signed by ${result.key.comment || 'a key'} (${result.key.fingerprint})`
287
+ : undefined
288
+ const said = [built, key].filter(Boolean).join(', and ')
289
+ return `Signed: ${said}`
194
290
  }
195
291
  case 'unsigned':
196
292
  return 'Not signed'
197
293
  case 'local':
198
294
  return 'Local: from this machine, not a registry'
295
+ case 'vouched':
296
+ return 'Vouched for by the host'
199
297
  case 'invalid':
200
298
  return `Signature not accepted: ${result.reason ?? 'it does not check out'}`
201
299
  case 'unchecked':
@@ -237,7 +335,17 @@ export function repositoryVisibility(): 'public' | 'private' | 'internal' | unde
237
335
  * job needs `id-token: write`; Sigstore turns its identity token into a
238
336
  * short-lived certificate naming the repository, ref, commit and workflow.
239
337
  */
240
- export async function signPackage(dir: string, options: SignOptions = {}): Promise<ProvenanceFile> {
338
+ /** What a Sigstore signing writes: its source and links always there. */
339
+ export type SigstoreProvenance = ProvenanceFile & {
340
+ signature: SerializedBundle
341
+ source: ProvenanceSource
342
+ links: ProvenanceLinks
343
+ }
344
+
345
+ export async function signPackage(
346
+ dir: string,
347
+ options: SignOptions = {},
348
+ ): Promise<SigstoreProvenance> {
241
349
  if (Bun.env.GITHUB_ACTIONS !== 'true' || !Bun.env.ACTIONS_ID_TOKEN_REQUEST_URL)
242
350
  throw new Error(
243
351
  'A bundle is signed in GitHub Actions, by a job with `permissions: id-token: write`: run `crombolo bundle sign` there.',
@@ -252,7 +360,10 @@ export async function signPackage(dir: string, options: SignOptions = {}): Promi
252
360
  const signature = await attest(statement(digest), IN_TOTO)
253
361
  const source = sourceOf(signature)
254
362
  if (!source) throw new Error('The signature Sigstore returned names no GitHub repository.')
255
- const file: ProvenanceFile = {
363
+ // A key's signature already there is over the same digest, and kept (story 316).
364
+ const existing = readProvenance(dir)
365
+ const file: SigstoreProvenance = {
366
+ ...(existing?.digest === digest && existing.key ? { key: existing.key } : {}),
256
367
  format: 1,
257
368
  digest,
258
369
  signature,
@@ -338,11 +449,33 @@ export async function verifyProvenanceWith(
338
449
  } catch {
339
450
  return invalid(`${PROVENANCE_FILE} is not JSON`)
340
451
  }
341
- if (provenance.format !== 1 || !provenance.signature)
452
+ if (provenance.format !== 1 || (!provenance.signature && !provenance.key))
342
453
  return invalid(`${PROVENANCE_FILE} is not a format this release reads`)
343
454
  const digest = packageDigest(dir)
344
455
  if (provenance.digest !== digest)
345
456
  return invalid('the bundle has changed since it was signed', digest)
457
+ const pkg = packageOf(dir)
458
+
459
+ // A key's signature (story 316), checked on its own terms.
460
+ let key: PublicKey | undefined
461
+ if (provenance.key) {
462
+ const read = readPublicKey(provenance.key.publicKey)
463
+ if ('problem' in read) return invalid(`its key is not one: ${read.problem}`, digest)
464
+ if (
465
+ !pkg ||
466
+ provenance.key.name !== pkg.name ||
467
+ provenance.key.version !== pkg.version ||
468
+ !verifiedBy(
469
+ read,
470
+ signedStatement({ digest, name: pkg.name, version: pkg.version }),
471
+ provenance.key.signature,
472
+ )
473
+ )
474
+ return invalid('the key signature does not check out', digest)
475
+ key = read
476
+ }
477
+ if (!provenance.signature)
478
+ return { state: 'signed', digest, key, ...(pkg ? { package: pkg } : {}) }
346
479
 
347
480
  let check = seams.verifySignature
348
481
  if (!check) {
@@ -403,7 +536,14 @@ export async function verifyProvenanceWith(
403
536
  `${PROVENANCE_FILE} says ${key} ${claimed?.[key] ?? '(none)'}, and the certificate says ${source[key]}`,
404
537
  digest,
405
538
  )
406
- return { state: 'signed', digest, source, links: linksFor(source, provenance.signature) }
539
+ return {
540
+ state: 'signed',
541
+ digest,
542
+ source,
543
+ links: linksFor(source, provenance.signature),
544
+ ...(key ? { key } : {}),
545
+ ...(pkg ? { package: pkg } : {}),
546
+ }
407
547
  }
408
548
 
409
549
  export type SignaturePolicy = 'optional' | 'required'
@@ -434,12 +574,14 @@ export function provenanceProblem(
434
574
  return `its signature was not accepted: ${result.reason ?? 'it does not check out'}`
435
575
  if (result.state === 'unchecked')
436
576
  return `its signature could not be checked right now (${result.reason ?? 'try again'}); try again`
437
- if (result.state === 'local') return undefined
577
+ if (result.state === 'local' || result.state === 'vouched') return undefined
438
578
  if (result.state === 'unsigned')
439
579
  return policy.signatures === 'required'
440
580
  ? 'this site takes only signed bundles (CROMBOLO_BUNDLE_SIGNATURES=required); the producer signs it with `crombolo bundle sign` in GitHub Actions'
441
581
  : undefined
442
- const source = result.source as ProvenanceSource
582
+ const source = result.source
583
+ // A bundle signed by a key alone is a site bundle's matter (story 316).
584
+ if (!source) return undefined
443
585
  if (policy.sources.length > 0 && !policy.sources.some((entry) => sourceAllowed(source, entry)))
444
586
  return `it was built from github.com/${source.repository} at ${refName(source.ref)}, and this site takes signed bundles only from ${policy.sources.join(', ')} (CROMBOLO_BUNDLE_SOURCES)`
445
587
  return undefined
@@ -479,7 +621,10 @@ export async function verifyPackage(
479
621
  }
480
622
 
481
623
  /** Signs a package directory, or a `.tgz` in place with `provenance.json` added to it. */
482
- export async function signPath(path: string, options: SignOptions = {}): Promise<ProvenanceFile> {
624
+ export async function signPath(
625
+ path: string,
626
+ options: SignOptions = {},
627
+ ): Promise<SigstoreProvenance> {
483
628
  if (!isTarball(path)) return signPackage(path, options)
484
629
  const { writeNpmTarball } = await import('./tar.ts')
485
630
  return withUnpacked(path, async (dir) => {
@@ -492,3 +637,27 @@ export async function signPath(path: string, options: SignOptions = {}): Promise
492
637
  return signed
493
638
  })
494
639
  }
640
+
641
+ /** Signs a package directory, or a `.tgz` in place, with a key (story 316). */
642
+ export async function signPathWithKey(path: string, pair: KeyPair): Promise<ProvenanceFile> {
643
+ const sign = (dir: string) => {
644
+ const files = packageFiles(dir).map((file) => ({
645
+ path: file,
646
+ bytes: new Uint8Array(readFileSync(join(dir, file))),
647
+ }))
648
+ const signed = keySignatureOver(files, pair, readProvenance(dir))
649
+ writeFileSync(join(dir, PROVENANCE_FILE), `${JSON.stringify(signed, null, 2)}\n`)
650
+ return signed
651
+ }
652
+ if (!isTarball(path)) return sign(path)
653
+ const { writeNpmTarball } = await import('./tar.ts')
654
+ return withUnpacked(path, async (dir) => {
655
+ const signed = sign(dir)
656
+ const entries = [...packageFiles(dir), PROVENANCE_FILE].map((file) => ({
657
+ path: file,
658
+ bytes: new Uint8Array(readFileSync(join(dir, file))),
659
+ }))
660
+ writeFileSync(path, writeNpmTarball(entries))
661
+ return signed
662
+ })
663
+ }
package/src/remote.ts CHANGED
@@ -34,14 +34,17 @@ import {
34
34
  type TrustRule,
35
35
  } from '@crombolo/data'
36
36
  import {
37
+ BUNDLE_FORMAT_VERSION,
37
38
  type ContentSet,
38
39
  isResolution,
39
40
  type NodeResolutions,
41
+ OLDEST_BUNDLE_FORMAT_VERSION,
40
42
  type Resolution,
41
43
  revertRun,
42
44
  } from '@crombolo/transfer'
43
45
  import { readAuditPageQuery, recordAudit } from './adapters/audit.ts'
44
- import type { BundleAdmin } from './bundle-admin.ts'
46
+ import { type BundleAdmin, settingsIn } from './bundle-admin.ts'
47
+ import { actAsChoice } from './bundle-api.ts'
45
48
  import { codeChanges, installedCode, planCode } from './bundle-code-install.ts'
46
49
  import {
47
50
  checkBundleContent,
@@ -197,6 +200,8 @@ export function createRemote(options: RemoteOptions): Remote {
197
200
  const discovery = (origin: string) => ({
198
201
  protocol: 'crombolo-remote',
199
202
  versions: [REMOTE_PROTOCOL_VERSION],
203
+ // The bundle formats this site reads, oldest and newest (story 306).
204
+ bundleFormats: [OLDEST_BUNDLE_FORMAT_VERSION, BUNDLE_FORMAT_VERSION],
200
205
  name: config.siteName,
201
206
  api: `${origin}${REMOTE_API_PATH}`,
202
207
  auth: {
@@ -512,6 +517,7 @@ export function createRemote(options: RemoteOptions): Remote {
512
517
  const canBackUp = config.dialect === 'sqlite' || Boolean(config.pgDump)
513
518
  const result = await installBundleContent(db, config, {
514
519
  bundle: dir,
520
+ expects: 'site' as const,
515
521
  replace: 'replace',
516
522
  passphrase,
517
523
  backupTaken: !canBackUp,
@@ -636,7 +642,7 @@ export function createRemote(options: RemoteOptions): Remote {
636
642
  return { sha256: hasher.digest('hex'), size }
637
643
  }
638
644
 
639
- /** The options a bundle apply was sent with, in `Crombolo-Options` (story 167). */
645
+ /** The options a site apply was sent with, in `Crombolo-Options` (story 167). */
640
646
  const applyOptions = (request: Request) => {
641
647
  let raw: Record<string, unknown> = {}
642
648
  try {
@@ -656,6 +662,7 @@ export function createRemote(options: RemoteOptions): Remote {
656
662
  dryRun: raw.dryRun === true,
657
663
  publish: raw.publish === true,
658
664
  replaceFiles: raw.replaceFiles === true,
665
+ allowDowngrade: raw.allowDowngrade === true,
659
666
  label: typeof raw.label === 'string' ? raw.label.slice(0, 200) : undefined,
660
667
  resolutions,
661
668
  resolveAll,
@@ -664,7 +671,7 @@ export function createRemote(options: RemoteOptions): Remote {
664
671
 
665
672
  /**
666
673
  * A bundle applied here (story 167): checked, and unless a dry run backed up
667
- * and applied in one transaction as `bundle apply` does on a site's own
674
+ * and applied in one transaction as `site apply` does on a site's own
668
675
  * machine. Content needs the `content` level and the right to change this
669
676
  * site; schema, views or code need `all` and Crombolo.Remote.ApplyStructure.
670
677
  */
@@ -750,11 +757,13 @@ export function createRemote(options: RemoteOptions): Remote {
750
757
  })
751
758
  const input = {
752
759
  bundle: dir,
760
+ expects: 'site' as const,
753
761
  publish: asked.publish,
754
762
  replaceFiles: asked.replaceFiles,
755
763
  installCode: code.length > 0,
756
764
  resolutions: asked.resolutions,
757
765
  resolveAll: asked.resolveAll,
766
+ allowDowngrade: asked.allowDowngrade,
758
767
  by: principal.name,
759
768
  }
760
769
  const report = (check: {
@@ -778,6 +787,7 @@ export function createRemote(options: RemoteOptions): Remote {
778
787
  structural,
779
788
  provenance,
780
789
  code: code.map((file) => ({ path: file.path, action: file.action })),
790
+ sitePackage: checked.sitePackage ?? null,
781
791
  bundle: checked.bundle,
782
792
  ...report(checked.check),
783
793
  clean: checked.clean,
@@ -823,7 +833,7 @@ export function createRemote(options: RemoteOptions): Remote {
823
833
  }
824
834
  }
825
835
 
826
- /** The applies on this site, newest first: for `bundle runs --remote`. */
836
+ /** The applies on this site, newest first: for `site runs --remote`. */
827
837
  async function listRuns(url: URL, principal: Principal): Promise<Response> {
828
838
  if (!atLeast('read')) return notAtLevel('read', 'reads')
829
839
  if (!may(principal, RemotePermissions.Pull) && !mayChange(principal))
@@ -843,6 +853,7 @@ export function createRemote(options: RemoteOptions): Remote {
843
853
  bundleId: run.bundleId,
844
854
  bundleLabel: run.bundleLabel ?? null,
845
855
  appliedBy: run.appliedBy ?? null,
856
+ bundleType: run.bundleType,
846
857
  })),
847
858
  })
848
859
  }
@@ -878,6 +889,30 @@ export function createRemote(options: RemoteOptions): Remote {
878
889
  }
879
890
  if (!fromThisSiteOrBearer(request)) return new Response('Forbidden', { status: 403 })
880
891
  if (!atLeast('all')) return notAtLevel('all', 'installing and switching bundles')
892
+ // Story 309: granting an installed extension what it asks for.
893
+ const granting = /^installed\/(.+)\/grant$/.exec(what)
894
+ if (granting && request.method === 'POST') {
895
+ if (!may(principal, RemotePermissions.InstallCode))
896
+ return problem(403, {
897
+ code: 'forbidden-code',
898
+ title: 'You may not grant an extension on this site',
899
+ detail: 'Granting one needs Crombolo.Remote.InstallCode, given by a group.',
900
+ })
901
+ const body = (await request.json().catch(() => ({}))) as Record<string, unknown>
902
+ const { status, ...outcome } = await bundles.grant(
903
+ actor,
904
+ decodeURIComponent(granting[1] as string),
905
+ {
906
+ grant: Array.isArray(body.grant)
907
+ ? body.grant.filter((p): p is string => typeof p === 'string')
908
+ : [],
909
+ actAs: actAsChoice(body.actAs),
910
+ },
911
+ )
912
+ return status === 200
913
+ ? Response.json(outcome)
914
+ : problem(status, { code: 'grant-mismatch', title: outcome.message })
915
+ }
881
916
  const switched = /^installed\/(.+)\/(disable|enable)$/.exec(what)
882
917
  if (switched && request.method === 'POST') {
883
918
  if (principal.ci ? !may(principal, RemotePermissions.ApplyStructure) : !principal.isAdmin)
@@ -920,7 +955,9 @@ export function createRemote(options: RemoteOptions): Remote {
920
955
  })
921
956
  if (removing) {
922
957
  const name = decodeURIComponent(what.slice('installed/'.length))
923
- const outcome = await bundles.uninstall(actor, name)
958
+ const outcome = await bundles.uninstall(actor, name, {
959
+ revertContent: new URL(request.url).searchParams.get('revertContent') === 'true',
960
+ })
924
961
  return outcome.ok
925
962
  ? Response.json(outcome)
926
963
  : problem(409, { code: 'uninstall-refused', title: outcome.message })
@@ -935,11 +972,12 @@ export function createRemote(options: RemoteOptions): Remote {
935
972
  version: typeof body.version === 'string' ? body.version : undefined,
936
973
  applyContent: body.applyContent === true,
937
974
  // Naming the grant is the consent: a script that names what it grants has said yes.
938
- acceptServerCode: true,
939
975
  grant,
976
+ actAs: typeof body.actAs === 'string' ? body.actAs : null,
977
+ settings: settingsIn(body.settings),
940
978
  })
941
979
  if (outcome.ok) return Response.json(outcome)
942
- if (outcome.needsServerConsent) {
980
+ if (outcome.needsGrant) {
943
981
  const asked = (outcome.permissions ?? []).map((p) => p.permission)
944
982
  const missing = asked.filter((p) => !grant.includes(p))
945
983
  const extra = grant.filter((p) => !asked.includes(p))
@@ -956,7 +994,7 @@ export function createRemote(options: RemoteOptions): Remote {
956
994
  return problem(409, { code: 'install-refused', title: outcome.message })
957
995
  }
958
996
 
959
- /** Undoes an apply (story 167), as `bundle revert` does here; files it replaced come back too. */
997
+ /** Undoes an apply (story 167), as `site revert` does here; files it replaced come back too. */
960
998
  async function revertBundleRun(
961
999
  request: Request,
962
1000
  principal: Principal,
@@ -967,6 +1005,14 @@ export function createRemote(options: RemoteOptions): Remote {
967
1005
  return problem(403, { code: 'forbidden', title: 'You may not change this environment' })
968
1006
  if (!fromThisSiteOrBearer(request)) return new Response('Forbidden', { status: 403 })
969
1007
  const body = (await request.json().catch(() => ({}))) as { force?: unknown }
1008
+ // An extension's content is put back by uninstalling it (story 306).
1009
+ const run = await new TransferRunRepository(db).byId(runId)
1010
+ if (run?.bundleType === 'extension')
1011
+ return problem(409, {
1012
+ code: 'extension-run',
1013
+ title: "That run brought an extension's content",
1014
+ detail: `It is put back by uninstalling ${run.packageName ?? 'the extension'}, with its content reverted.`,
1015
+ })
970
1016
  // A run that installed code changes code back, which needs what it did.
971
1017
  if (
972
1018
  installedCode(config, runId) &&
package/src/schema.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  import { existsSync, watch } from 'node:fs'
8
+ import { discoverBundles } from '@crombolo/backoffice-host/registry'
8
9
  import {
9
10
  CACHE_INSTRUCTION_CHANNEL,
10
11
  type CacheInstructionKind,
@@ -108,16 +109,42 @@ export class SchemaBootError extends Error {
108
109
 
109
110
  /**
110
111
  * The components a schema may name as templates: every one of them, at any
111
- * depth, keyed by the path that is its alias.
112
+ * depth, keyed by the path that is its alias. With the site's directory, an
113
+ * installed extension's too, as `<id>/<name>` (story 312): its own components
114
+ * are known only once it has started, so any name under its id is accepted, and
115
+ * one it does not offer is logged when a page renders it.
112
116
  */
113
- export function componentAliasesIn(componentsDir: string): Set<string> {
114
- return new Set(listComponents(componentsDir).map((component) => component.alias))
117
+ export function componentAliasesIn(componentsDir: string, siteDir?: string): ReadonlySet<string> {
118
+ const files = new Set(listComponents(componentsDir).map((component) => component.alias))
119
+ if (!siteDir) return files
120
+ const ids = new Set(
121
+ discoverBundles(siteDir)
122
+ .bundles.filter((pkg) => pkg.bundleType === 'extension' && pkg.carries.server)
123
+ .map((pkg) => pkg.id),
124
+ )
125
+ return new ComponentAliases(files, ids)
126
+ }
127
+
128
+ /** The site's component files, and any name under an installed extension's id. */
129
+ class ComponentAliases extends Set<string> {
130
+ readonly #extensions: ReadonlySet<string>
131
+ constructor(files: Iterable<string>, extensions: ReadonlySet<string>) {
132
+ super(files)
133
+ this.#extensions = extensions
134
+ }
135
+ override has(alias: string): boolean {
136
+ const slash = alias.indexOf('/')
137
+ return (
138
+ super.has(alias) ||
139
+ (slash > 0 && slash < alias.length - 1 && this.#extensions.has(alias.slice(0, slash)))
140
+ )
141
+ }
115
142
  }
116
143
 
117
144
  export function syncOptionsFor(config: CromboloConfig): SyncOptions {
118
145
  return {
119
146
  mode: config.development ? 'development' : 'production',
120
- componentAliases: componentAliasesIn(config.componentsDir),
147
+ componentAliases: componentAliasesIn(config.componentsDir, config.siteDir),
121
148
  formTypes: formTypesFor(config),
122
149
  }
123
150
  }
@@ -581,7 +581,7 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
581
581
  id,
582
582
  label: 'Content files',
583
583
  createdAt: new Date(0).toISOString(),
584
- createdBy: 'crombolo bundle apply',
584
+ createdBy: 'crombolo site apply',
585
585
  integrity: '',
586
586
  snapshot: 'drafts',
587
587
  provenance: {
@@ -622,15 +622,17 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
622
622
  },
623
623
  ]
624
624
  : [],
625
+ { bundleType: 'site' },
625
626
  )
626
627
  const files = writeBundlePackage(payload, {
627
628
  name: 'crombolo-site-seed',
628
629
  version: '0.0.0',
629
630
  id: 'site-seed',
630
631
  label: 'Content files',
631
- description: `The content files of ${config.siteName}, built by crombolo bundle build`,
632
+ description: `The content files of ${config.siteName}, built by crombolo site build`,
632
633
  private: true,
633
634
  peerRange: `>=${VERSION}`,
635
+ bundleType: 'site',
634
636
  })
635
637
  return { findings, set, blobs, files, counts, ...(dictionary ? { dictionary: entries } : {}) }
636
638
  }
@@ -4,7 +4,7 @@
4
4
  * `content/pages/`, Library elements to `content/library/`, and media, files and
5
5
  * all, to `content/media/`.
6
6
  *
7
- * Values are written in the shorthand `bundle apply` reads back — rich text as
7
+ * Values are written in the shorthand `site apply` reads back — rich text as
8
8
  * `{ html }`, pickers and links as paths to what the export carries, blocks as
9
9
  * `{ type, key, values }` — and in their editor's stored shape where there is
10
10
  * none. A node keeps its key in its file wherever it is not the one its path
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * Values in the shorthand a person writes, both ways (stories 163, 253):
3
3
  * Markdown, paths and `{ type, alias, values }` blocks into each property
4
- * editor's stored shape, as `bundle apply` reads content files and the
4
+ * editor's stored shape, as `site apply` reads content files and the
5
5
  * `content` commands read `--set`; and stored values back into that shorthand,
6
- * as `bundle export --source` and `content show` write them.
6
+ * as `content export` and `content show` write them.
7
7
  */
8
8
  import { type ContentTypeAggregate, dateFromText, normaliseUuid } from '@crombolo/core'
9
9
  import { ContentTypeRepository, DataTypeRepository, type Db, looksLikeKey } from '@crombolo/data'
@@ -314,7 +314,7 @@ export function valueWriter(lookup: SchemaLookup, refs: ValueRefs) {
314
314
  const link = typeof entry === 'string' ? { path: entry } : entry
315
315
  if (!isRecord(link))
316
316
  return fail('a link is a path, a URL, or { path | url, name, target }')
317
- // A link as the editor stores it, as `bundle export --source` writes one.
317
+ // A link as the editor stores it, as `content export` writes one.
318
318
  if ('unique' in link || 'type' in link) {
319
319
  links.push(link)
320
320
  continue