@crombolo/server 0.43.1 → 0.45.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.
@@ -17,7 +17,8 @@
17
17
  * browser cannot reach npm, and the backoffice keeps making same-origin
18
18
  * requests only.
19
19
  */
20
- import { readFileSync } from 'node:fs'
20
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
21
+ import { tmpdir } from 'node:os'
21
22
  import { join } from 'node:path'
22
23
  import {
23
24
  type BundlePackage,
@@ -29,9 +30,23 @@ import {
29
30
  } from '@crombolo/backoffice-host'
30
31
  import { type BundleGrants, declaredPermissions } from './bundle-grants.ts'
31
32
  import { logger } from './logging.ts'
33
+ import {
34
+ type ProvenancePolicy,
35
+ type ProvenanceResult,
36
+ provenanceProblem,
37
+ verifyPackage,
38
+ verifyProvenance,
39
+ } from './provenance.ts'
40
+ import { extractTarball } from './tar.ts'
32
41
 
33
42
  const log = logger('packages')
34
43
 
44
+ /** Where a registry version's tarball is, and what it hashes to. */
45
+ interface Dist {
46
+ tarball?: string
47
+ integrity?: string
48
+ }
49
+
35
50
  /** How long a search is reused. Long enough to page a list, short enough to stay fresh. */
36
51
  const CACHE_MS = 5 * 60 * 1000
37
52
 
@@ -72,6 +87,8 @@ export interface InstalledListing {
72
87
  disabledBy: string | null
73
88
  /** Who approved it, and when: an administrator at install, or the site's code. */
74
89
  granted?: { by: string | null; at: string; version: string }
90
+ /** Where it was built, from its signature (story 060); `local` for a workspace or linked one. */
91
+ provenance: ProvenanceResult
75
92
  }
76
93
 
77
94
  /** What became of the content half of an install. */
@@ -112,6 +129,10 @@ export interface MarketplaceOptions {
112
129
  installs?: boolean
113
130
  /** A host's own word on where installs happen, said in place of a deploy (story 181). */
114
131
  installsElsewhere?: { message: string; url?: string }
132
+ /** What the site takes of a bundle's signature (story 060); anything signed or not, when absent. */
133
+ policy?: ProvenancePolicy
134
+ /** Checks a package directory's signature; `verifyProvenance`, unless a test stands in. */
135
+ verify?: (dir: string) => Promise<ProvenanceResult>
115
136
  }
116
137
 
117
138
  export interface InstallOutcome {
@@ -132,6 +153,10 @@ export interface InstallOutcome {
132
153
  needsServerConsent?: boolean
133
154
  /** With `needsServerConsent`: what it asks to do with the site, to grant as a whole (story 222). */
134
155
  permissions?: { permission: string; allows: string }[]
156
+ /** It changed the code the server loads, which runs once the site restarts (story 241). */
157
+ restartPending?: boolean
158
+ /** Where the version checked was built, from its signature (story 060). */
159
+ provenance?: ProvenanceResult
135
160
  }
136
161
 
137
162
  export type PackageInstaller = (
@@ -183,6 +208,32 @@ export interface Marketplace {
183
208
  by?: string | null
184
209
  },
185
210
  ): Promise<InstallOutcome>
211
+ /** What a version would bring, read from the registry and nothing installed: for a dry run. */
212
+ inspect(
213
+ name: string,
214
+ version?: string,
215
+ ): Promise<
216
+ | {
217
+ ok: true
218
+ server: boolean
219
+ content: boolean
220
+ extensions: boolean
221
+ permissions: string[]
222
+ version: string
223
+ provenance: ProvenanceResult
224
+ }
225
+ | { ok: false; message: string }
226
+ >
227
+ /** A packed bundle on this machine (a `.tgz`), installed as `install` installs one from the registry. */
228
+ installFile(
229
+ file: string,
230
+ options?: {
231
+ applyContent?: boolean
232
+ acceptServerCode?: boolean
233
+ grant?: readonly string[]
234
+ by?: string | null
235
+ },
236
+ ): Promise<InstallOutcome>
186
237
  uninstall(name: string): Promise<InstallOutcome>
187
238
  }
188
239
 
@@ -258,7 +309,9 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
258
309
  name: string,
259
310
  wanted?: string,
260
311
  ): Promise<
261
- (BundlePackage['carries'] & { permissions: string[] }) | 'not-a-bundle' | 'unreachable'
312
+ | (BundlePackage['carries'] & { permissions: string[]; version: string; dist?: Dist })
313
+ | 'not-a-bundle'
314
+ | 'unreachable'
262
315
  > => {
263
316
  try {
264
317
  const response = await call(`${options.registry}/${encodeURIComponent(name)}`, {
@@ -281,7 +334,8 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
281
334
  .sort(Bun.semver.order)
282
335
  .at(-1))
283
336
  const version = resolved ? versions[resolved] : undefined
284
- if (!version || validateBundlePackage(version).length > 0) return 'not-a-bundle'
337
+ if (!resolved || !version || validateBundlePackage(version).length > 0) return 'not-a-bundle'
338
+ const dist = (version as { dist?: Dist }).dist
285
339
  const field = version.crombolo as {
286
340
  extensions?: unknown[]
287
341
  content?: boolean
@@ -293,17 +347,89 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
293
347
  content: field.content === true,
294
348
  server: field.server !== undefined,
295
349
  permissions: Array.isArray(field.permissions) ? field.permissions : [],
350
+ version: resolved,
351
+ ...(dist ? { dist } : {}),
296
352
  }
297
353
  } catch {
298
354
  return 'unreachable'
299
355
  }
300
356
  }
301
357
 
358
+ const verify = options.verify ?? ((dir: string) => verifyProvenance(dir))
359
+
360
+ /**
361
+ * Where a registry version was built (story 060): its exact tarball fetched,
362
+ * held to the registry's integrity, and its signature checked, so the bytes
363
+ * checked are the bytes `bun add` then installs. A registry that gives no
364
+ * tarball leaves nothing to check; one that cannot be fetched is not unsigned.
365
+ */
366
+ const provenanceAt = async (name: string, dist: Dist | undefined): Promise<ProvenanceResult> => {
367
+ if (!dist?.tarball) return { state: 'unsigned' }
368
+ const dir = mkdtempSync(join(tmpdir(), 'crombolo-bundle-check-'))
369
+ try {
370
+ const response = await call(dist.tarball)
371
+ if (!response.ok)
372
+ return {
373
+ state: 'invalid',
374
+ reason: `${name} could not be fetched to check its signature (the registry answered ${response.status})`,
375
+ }
376
+ const bytes = new Uint8Array(await response.arrayBuffer())
377
+ if (dist.integrity?.startsWith('sha512-')) {
378
+ const got = `sha512-${new Bun.CryptoHasher('sha512').update(bytes).digest('base64')}`
379
+ if (got !== dist.integrity)
380
+ return { state: 'invalid', reason: `${name} is not the package the registry describes` }
381
+ }
382
+ const file = join(dir, 'bundle.tgz')
383
+ await Bun.write(file, bytes)
384
+ const unpacked = join(dir, 'package')
385
+ await extractTarball(file, unpacked)
386
+ return await verify(unpacked)
387
+ } catch (error) {
388
+ return {
389
+ state: 'invalid',
390
+ reason: `${name} could not be checked: ${error instanceof Error ? error.message : String(error)}`,
391
+ }
392
+ } finally {
393
+ rmSync(dir, { recursive: true, force: true })
394
+ }
395
+ }
396
+
397
+ /** Why the site's policy refuses a version, as an outcome, or undefined when it may be installed. */
398
+ const refusedBySignature = (
399
+ label: string,
400
+ provenance: ProvenanceResult,
401
+ ): InstallOutcome | undefined => {
402
+ const problem = provenanceProblem(
403
+ provenance,
404
+ options.policy ?? { signatures: 'optional', sources: [] },
405
+ )
406
+ return problem
407
+ ? { ok: false, message: `${label} was not installed: ${problem}.`, provenance }
408
+ : undefined
409
+ }
410
+
411
+ /** Each installed version's signature, checked once: a version's files do not change. */
412
+ const installedProvenance = new Map<string, Promise<ProvenanceResult>>()
413
+ const provenanceOfInstalled = async (bundle: BundlePackage): Promise<ProvenanceResult> => {
414
+ const range = await rangeFor(bundle.packageName)
415
+ if (range && /^(workspace|link|file|portal):/.test(range)) return { state: 'local' }
416
+ const key = `${bundle.packageName}@${bundle.version}`
417
+ let found = installedProvenance.get(key)
418
+ if (!found) {
419
+ found = verify(bundle.directory).catch((error: unknown) => ({
420
+ state: 'invalid' as const,
421
+ reason: error instanceof Error ? error.message : String(error),
422
+ }))
423
+ installedProvenance.set(key, found)
424
+ }
425
+ return found
426
+ }
427
+
302
428
  /** What the registry says this package's latest version carries, when it is a valid bundle. */
303
429
  const declares = async (name: string): Promise<BundlePackage['carries'] | undefined> => {
304
430
  const declared = await declaresAt(name)
305
431
  if (typeof declared === 'string') return undefined
306
- const { permissions: _, ...carries } = declared
432
+ const { permissions: _, version: _version, dist: _dist, ...carries } = declared
307
433
  return carries
308
434
  }
309
435
 
@@ -406,6 +532,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
406
532
  description: descriptionOf(bundle.directory),
407
533
  peerRange: bundle.peerRange,
408
534
  ...grantOf(bundle),
535
+ provenance: await provenanceOfInstalled(bundle),
409
536
  })),
410
537
  )
411
538
  },
@@ -433,69 +560,45 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
433
560
  }
434
561
  if (declared.server && !consented(request, declared.permissions))
435
562
  return serverConsentNeeded(name, declared.permissions)
563
+ const provenance = await provenanceAt(name, declared.dist)
564
+ const refused = refusedBySignature(`${name}@${declared.version}`, provenance)
565
+ if (refused) return refused
566
+ // Pinned to the version whose tarball was checked, when one was.
567
+ const outcome = await added(
568
+ name,
569
+ version ? `${name}@${version}` : name,
570
+ version,
571
+ request,
572
+ declared.dist?.tarball ? { version: declared.version } : undefined,
573
+ )
574
+ return { ...outcome, provenance }
575
+ },
436
576
 
437
- const specifier = version ? `${name}@${version}` : name
438
- const result = await install('add', specifier, options.siteDir)
439
- options.extensions.invalidate()
440
- if (!result.ok)
441
- return {
442
- ok: false,
443
- message: result.output || `Installing ${specifier} failed.`,
444
- }
577
+ async inspect(name, version) {
578
+ if (!isValidPackageName(name))
579
+ return { ok: false, message: `'${name}' is not a package name npm would accept.` }
580
+ const declared = await declaresAt(name, version)
581
+ if (declared === 'unreachable')
582
+ return { ok: false, message: `The package registry could not say what ${name} contains.` }
583
+ if (declared === 'not-a-bundle')
584
+ return { ok: false, message: `${name} is not a bundle for this site.` }
585
+ const { dist, ...carries } = declared
586
+ return { ok: true, ...carries, provenance: await provenanceAt(name, dist) }
587
+ },
445
588
 
446
- const range = (await rangeFor(name)) ?? version ?? 'latest'
447
- const found = options.extensions
448
- .bundles()
449
- .bundles.find((bundle) => bundle.packageName === name)
450
- if (!found)
451
- return {
452
- ok: true,
453
- dependency: { name, range, version: version ?? range },
454
- message: `${name} was installed, but it is not a valid bundle, so nothing was added to the backoffice.`,
455
- }
456
- // The version that landed is what counts: a release published between
457
- // reading the registry and installing may have brought server code.
458
- if (found.carries.server && !consented(request, declaredPermissions(found))) {
459
- await install('remove', name, options.siteDir)
460
- options.extensions.invalidate()
461
- return serverConsentNeeded(
462
- name,
463
- declaredPermissions(found),
464
- `${name}@${found.version} turned out to run code on the server, or to ask for more than was granted, so it was removed again.`,
465
- )
466
- }
467
- // What was granted is recorded against the version that landed.
468
- if (found.carries.server) await options.grants?.grant(found, request.by ?? null)
469
-
470
- // The content half lands after the dependency, so a refused check leaves
471
- // the package installed and says why, rather than undoing an install that
472
- // succeeded.
473
- let content: ContentOutcome | undefined
474
- if (found.carries.content) {
475
- const declined = request.applyContent === false || options.applyContentOnInstall === false
476
- content =
477
- declined || !options.applyContent
478
- ? {
479
- applied: false,
480
- message: `Its content was not applied. Run \`crombolo bundle install ${name}\` to apply it.`,
481
- }
482
- : await options.applyContent(name).catch((error: unknown) => ({
483
- applied: false,
484
- message: `Its content could not be applied: ${error instanceof Error ? error.message : String(error)}`,
485
- }))
486
- }
487
- return {
488
- ok: true,
489
- dependency: { name, range, version: found.version },
490
- // The install lives in this node's node_modules until the dependency is
491
- // committed; saying so is the difference between a surprise and a plan.
492
- message: `${name}@${found.version} is installed. Commit the changed package.json and bun.lock to keep it across deployments.${
493
- found.carries.server
494
- ? " Its server code runs only once your site's developers turn it on and deploy the site."
495
- : ''
496
- }${found.carries.extensions ? ` ${SCREENS_NOTICE}` : ''}`,
497
- ...(content ? { content } : {}),
498
- }
589
+ async installFile(file, request = {}) {
590
+ if (options.installs === false) return refusedHere(file, 'add', options.installsElsewhere)
591
+ const declared = await declaresIn(file)
592
+ if (typeof declared === 'string') return { ok: false, message: declared }
593
+ if (declared.server && !consented(request, declared.permissions))
594
+ return serverConsentNeeded(declared.name, declared.permissions)
595
+ const provenance = await verifyPackage(file).catch((error: unknown) => ({
596
+ state: 'invalid' as const,
597
+ reason: error instanceof Error ? error.message : String(error),
598
+ }))
599
+ const refused = refusedBySignature(declared.name, provenance)
600
+ if (refused) return refused
601
+ return { ...(await added(declared.name, file, undefined, request)), provenance }
499
602
  },
500
603
 
501
604
  async uninstall(name) {
@@ -512,6 +615,115 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
512
615
  : { ok: false, message: result.output || `Removing ${name} failed.` }
513
616
  },
514
617
  }
618
+
619
+ /** `bun add`, then the checks on what landed, the grant, and the content half. */
620
+ async function added(
621
+ name: string,
622
+ specifier: string,
623
+ version: string | undefined,
624
+ request: {
625
+ applyContent?: boolean
626
+ acceptServerCode?: boolean
627
+ grant?: readonly string[]
628
+ by?: string | null
629
+ },
630
+ checked?: { version: string },
631
+ ): Promise<InstallOutcome> {
632
+ const result = await install('add', specifier, options.siteDir)
633
+ options.extensions.invalidate()
634
+ if (!result.ok)
635
+ return {
636
+ ok: false,
637
+ message: result.output || `Installing ${specifier} failed.`,
638
+ }
639
+
640
+ const range = (await rangeFor(name)) ?? version ?? 'latest'
641
+ const found = options.extensions.bundles().bundles.find((bundle) => bundle.packageName === name)
642
+ if (!found)
643
+ return {
644
+ ok: true,
645
+ dependency: { name, range, version: version ?? range },
646
+ message: `${name} was installed, but it is not a valid bundle, so nothing was added to the backoffice.`,
647
+ }
648
+ // The version whose signature was checked is the one that has to land
649
+ // (story 060): one published in between was never checked.
650
+ if (checked && found.version !== checked.version) {
651
+ await install('remove', name, options.siteDir)
652
+ options.extensions.invalidate()
653
+ return {
654
+ ok: false,
655
+ message: `${name}@${found.version} was published while ${checked.version} was being checked, so it was removed again. Try the install again.`,
656
+ }
657
+ }
658
+ // The version that landed is what counts: a release published between
659
+ // reading the registry and installing may have brought server code.
660
+ if (found.carries.server && !consented(request, declaredPermissions(found))) {
661
+ await install('remove', name, options.siteDir)
662
+ options.extensions.invalidate()
663
+ return serverConsentNeeded(
664
+ name,
665
+ declaredPermissions(found),
666
+ `${name}@${found.version} turned out to run code on the server, or to ask for more than was granted, so it was removed again.`,
667
+ )
668
+ }
669
+ // What was granted is recorded against the version that landed.
670
+ if (found.carries.server) await options.grants?.grant(found, request.by ?? null)
671
+
672
+ // The content half lands after the dependency, so a refused check leaves
673
+ // the package installed and says why, rather than undoing an install that
674
+ // succeeded.
675
+ let content: ContentOutcome | undefined
676
+ if (found.carries.content) {
677
+ const declined = request.applyContent === false || options.applyContentOnInstall === false
678
+ content =
679
+ declined || !options.applyContent
680
+ ? {
681
+ applied: false,
682
+ message: `Its content was not applied. Run \`crombolo bundle install ${name}\` to apply it.`,
683
+ }
684
+ : await options.applyContent(name).catch((error: unknown) => ({
685
+ applied: false,
686
+ message: `Its content could not be applied: ${error instanceof Error ? error.message : String(error)}`,
687
+ }))
688
+ }
689
+ return {
690
+ ok: true,
691
+ dependency: { name, range, version: found.version },
692
+ // The install lives in this node's node_modules until the dependency is
693
+ // committed; saying so is the difference between a surprise and a plan.
694
+ message: `${name}@${found.version} is installed. Commit the changed package.json and bun.lock to keep it across deployments.${
695
+ found.carries.server
696
+ ? " Its server code runs only once your site's developers turn it on and deploy the site."
697
+ : ''
698
+ }${found.carries.extensions ? ` ${SCREENS_NOTICE}` : ''}`,
699
+ ...(content ? { content } : {}),
700
+ }
701
+ }
702
+ }
703
+
704
+ /** What a packed bundle on this machine declares, read from its package.json, or why it cannot be installed. */
705
+ async function declaresIn(
706
+ file: string,
707
+ ): Promise<{ name: string; server: boolean; permissions: string[] } | string> {
708
+ const dir = mkdtempSync(join(tmpdir(), 'crombolo-bundle-file-'))
709
+ try {
710
+ await extractTarball(file, dir)
711
+ const root = existsSync(join(dir, 'package', 'package.json')) ? join(dir, 'package') : dir
712
+ const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as PackageJson
713
+ const problems = validateBundlePackage(json)
714
+ if (problems.length > 0 || typeof json.name !== 'string')
715
+ return `${file} is not a bundle for this site, so it was not installed.`
716
+ const field = json.crombolo as { server?: string; permissions?: string[] }
717
+ return {
718
+ name: json.name,
719
+ server: field.server !== undefined,
720
+ permissions: Array.isArray(field.permissions) ? field.permissions : [],
721
+ }
722
+ } catch {
723
+ return `${file} could not be read as a packed bundle, so it was not installed.`
724
+ } finally {
725
+ rmSync(dir, { recursive: true, force: true })
726
+ }
515
727
  }
516
728
 
517
729
  /** A package's own description, read leniently: anything unreadable is none. */
package/src/no-nodes.ts CHANGED
@@ -169,7 +169,7 @@ export default function Article({ model }: PageProps) {
169
169
  <table>
170
170
  <tr><td><code>schema/</code></td><td>content types, data types and languages, as TOML files</td></tr>
171
171
  <tr><td><code>components/</code></td><td>templates and the components they share, as <code>.tsx</code></td></tr>
172
- <tr><td><code>seed/</code></td><td>starting pages and media, as files</td></tr>
172
+ <tr><td><code>content/</code></td><td>starting pages and media, as files</td></tr>
173
173
  <tr><td><code>crombolo.config.ts</code></td><td>the site's settings: its name, its database, its addresses</td></tr>
174
174
  </table>
175
175
  </section>