@crombolo/server 0.44.0 → 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.
@@ -57,6 +57,14 @@ import {
57
57
  writeResolutions,
58
58
  } from '@crombolo/transfer'
59
59
  import { type BackupResult, backupBefore } from './backup.ts'
60
+ import {
61
+ type CodeInstall,
62
+ type CodeRevert,
63
+ codeChanges,
64
+ installCode,
65
+ planCode,
66
+ revertCode,
67
+ } from './bundle-code-install.ts'
60
68
  import {
61
69
  type CarriedSections,
62
70
  carriedSections,
@@ -82,6 +90,7 @@ import { type CromboloConfig, VERSION } from './config.ts'
82
90
  import { dictionaryToUdt, importDictionaryUdt, writeDictionaryUdt } from './dictionary-transfer.ts'
83
91
  import { syncDomainsFile } from './domains.ts'
84
92
  import { mediaStoreFor, placeBlobs } from './media-files.ts'
93
+ import { type ProvenanceResult, provenanceProblem, verifyProvenance } from './provenance.ts'
85
94
  import { componentAliasesIn, syncSchemaDirectory } from './schema.ts'
86
95
  import { publishSchema } from './schema-store.ts'
87
96
  import { applySiteData, type SiteDataApplied } from './site-data.ts'
@@ -282,6 +291,25 @@ export interface TransferInput extends SectionOptions {
282
291
  passphrase?: string
283
292
  /** Leave the file's members, users and their groups out: this site's own are untouched. */
284
293
  excludePeople?: boolean
294
+ /**
295
+ * Install the code the bundle carries here (story 241); left alone unless
296
+ * asked, as story 192 had it. Only where runtime installs are on.
297
+ */
298
+ installCode?: boolean
299
+ /**
300
+ * `local`: the site's own content files, built here, which no one else
301
+ * signed and the site's policy never refuses (story 060).
302
+ */
303
+ provenance?: 'local'
304
+ }
305
+
306
+ /** Where the bundle was built, checked before anything is read further (story 060). */
307
+ async function bundleProvenance(
308
+ bundle: ResolvedBundle,
309
+ input: Pick<TransferInput, 'provenance'>,
310
+ ): Promise<ProvenanceResult> {
311
+ if (input.provenance === 'local') return { state: 'local' }
312
+ return verifyProvenance(bundle.directory)
285
313
  }
286
314
 
287
315
  /**
@@ -340,6 +368,10 @@ export interface ContentCheckResult {
340
368
  check: TransferCheck
341
369
  /** What the carried sections would do here; undefined for a content-only bundle. */
342
370
  sections: SectionPlan | undefined
371
+ /** The code files installing it would change here; empty when it carries none, or the same. */
372
+ code: SectionFile[]
373
+ /** Where it was built, from its signature (story 060). */
374
+ provenance: ProvenanceResult
343
375
  /** Nothing outstanding: the bundle would import cleanly. */
344
376
  clean: boolean
345
377
  /** With `publish`: the pages the import would not publish, and the reason publish gives. */
@@ -358,6 +390,9 @@ export async function checkBundleContent(
358
390
  const bundle = readBundle(input.bundle, config.siteDir, input.passphrase, {
359
391
  withoutPeople: input.excludePeople,
360
392
  })
393
+ const provenance = await bundleProvenance(bundle, input)
394
+ const refused = provenanceProblem(provenance, config.bundlePolicy)
395
+ if (refused) throw new CommandError(`This bundle is refused: ${refused}.`)
361
396
  const set = bundle.set
362
397
  const prepared = await transferOptions(db, config, bundle, input)
363
398
  const check = await checkBundle(db, set, prepared.options)
@@ -391,6 +426,8 @@ export async function checkBundleContent(
391
426
  sections: carriesSections(bundle.carried)
392
427
  ? await planSections(db, config, bundle.carried, input)
393
428
  : undefined,
429
+ code: codeChanges(planCode(config, bundle.carried)),
430
+ provenance,
394
431
  clean: check.outstanding.length === 0,
395
432
  publishRefusals: refusals,
396
433
  decisions: {
@@ -436,6 +473,10 @@ export interface ContentImportResult {
436
473
  problems: string[]
437
474
  /** What the file's site data did here, when it carried any (story 189). */
438
475
  siteData?: SiteDataApplied
476
+ /** The code it installed, when asked to and it changed any: live after a restart. */
477
+ code?: CodeInstall
478
+ /** Where it was built, from its signature (story 060); absent when refused before it was read. */
479
+ provenance?: ProvenanceResult
439
480
  }
440
481
 
441
482
  /**
@@ -536,6 +577,10 @@ export async function installBundleContent(
536
577
  })
537
578
 
538
579
  // What has to be true before anything is backed up or written.
580
+ const provenance = await bundleProvenance(bundle, input)
581
+ const signatureRefused = provenanceProblem(provenance, config.bundlePolicy)
582
+ if (signatureRefused)
583
+ return { ...refuse([`this bundle is refused: ${signatureRefused}`]), provenance }
539
584
  if (replace && manifest.scope !== 'site')
540
585
  return refuse(['only a whole-site file (crombolo export --site) can replace a site'])
541
586
  const missing = requiresProblems(manifest, config.siteDir)
@@ -600,7 +645,20 @@ export async function installBundleContent(
600
645
  ],
601
646
  backup,
602
647
  )
603
- const needingPermission = plan ? replacementsNeedingPermission(plan, effective) : []
648
+ // The code half (story 241): only when asked, only where installs happen here.
649
+ const code = effective.installCode ? codeChanges(planCode(config, carried)) : []
650
+ if (code.length > 0 && !config.runtimeInstalls)
651
+ return refuse(
652
+ [
653
+ config.installsElsewhere?.message ??
654
+ "this site does not install code while it runs: add the bundle's code to the site and deploy it",
655
+ ],
656
+ backup,
657
+ )
658
+ const needingPermission = [
659
+ ...(plan ? replacementsNeedingPermission(plan, effective) : []),
660
+ ...(effective.replaceFiles ? [] : code.filter((file) => file.action === 'overwrite')),
661
+ ]
604
662
  if (needingPermission.length > 0)
605
663
  return refuse(
606
664
  [
@@ -701,6 +759,15 @@ export async function installBundleContent(
701
759
  await publishSchema(config.schemaStore, config.schemaDir)
702
760
  }
703
761
  const kept = promoteStaged(config, runDir, runId)
762
+ const codeInstalled =
763
+ code.length > 0
764
+ ? await installCode(
765
+ config,
766
+ carried,
767
+ kept,
768
+ `${bundle.package.packageName}@${bundle.package.version}`,
769
+ )
770
+ : undefined
704
771
  // On the owners' own connections, so after crombolo's transaction rather than
705
772
  // in it: each owner is replaced in a transaction of its own.
706
773
  const siteData = set.siteData ? await applySiteData(db, config, set.siteData) : undefined
@@ -727,8 +794,11 @@ export async function installBundleContent(
727
794
  problems: [
728
795
  ...prepared.problems,
729
796
  ...(siteData?.failed ?? []).map((failure) => `site data not written for ${failure}`),
797
+ ...(codeInstalled?.problems ?? []).map((problem) => `its code: ${problem}`),
730
798
  ],
731
799
  ...(siteData ? { siteData } : {}),
800
+ ...(codeInstalled ? { code: codeInstalled } : {}),
801
+ provenance,
732
802
  sections: staged
733
803
  ? {
734
804
  written: staged.written,
@@ -746,6 +816,8 @@ export interface RevertedSections extends RestoredFiles {
746
816
  schema: string | undefined
747
817
  /** Whether the dictionary was put back as the run found it. */
748
818
  dictionary: boolean
819
+ /** The code the run installed, put back: live after a restart. */
820
+ code?: CodeRevert
749
821
  }
750
822
 
751
823
  /**
@@ -780,5 +852,11 @@ export async function revertSections(
780
852
  for (const root of await repo.children(null)) await repo.delete(root.key)
781
853
  await importDictionaryUdt(tx, kept)
782
854
  })
783
- return { ...files, schema, dictionary: kept !== undefined }
855
+ const code = await revertCode(config, runId)
856
+ return {
857
+ ...files,
858
+ schema,
859
+ dictionary: kept !== undefined,
860
+ ...(code.restored.length + code.removed.length > 0 ? { code } : {}),
861
+ }
784
862
  }
package/src/config.ts CHANGED
@@ -23,6 +23,7 @@ import { checkHost, type HostConfig } from './host-token.ts'
23
23
  import { checkIdentityProviders, type IdentityProvider } from './identity-providers.ts'
24
24
  import type { MediaStore } from './media-store.ts'
25
25
  import type { JobSchedule } from './owner-jobs.ts'
26
+ import type { ProvenancePolicy, SignaturePolicy } from './provenance.ts'
26
27
  import type { SchemaStore } from './schema-store.ts'
27
28
  import { setting } from './settings.ts'
28
29
  import type { SiteDatabaseConfig, SiteQueryModules } from './site-queries.ts'
@@ -516,6 +517,11 @@ export interface CromboloConfig {
516
517
  * and `CROMBOLO_INSTALLS_ELSEWHERE_URL`.
517
518
  */
518
519
  installsElsewhere?: { message: string; url?: string }
520
+ /**
521
+ * What this site takes of a bundle's signature (story 060):
522
+ * `CROMBOLO_BUNDLE_SIGNATURES` and `CROMBOLO_BUNDLE_SOURCES`.
523
+ */
524
+ bundlePolicy: ProvenancePolicy
519
525
  /**
520
526
  * Where the Packages section's Marketplace sends someone browsing for
521
527
  * extensions. Never framed — npm refuses to be framed — so the native view
@@ -604,6 +610,12 @@ function roleFromEnvironment(value: string | undefined): ServerRole {
604
610
  return value
605
611
  }
606
612
 
613
+ function bundleSignatures(value: string | undefined): SignaturePolicy {
614
+ if (value === undefined || value === '' || value === 'optional') return 'optional'
615
+ if (value === 'required') return 'required'
616
+ throw new Error(`CROMBOLO_BUNDLE_SIGNATURES must be optional or required, not '${value}'.`)
617
+ }
618
+
607
619
  function jobsFromEnvironment(value: string | undefined): boolean {
608
620
  if (value === undefined || value === '' || value === 'on') return true
609
621
  if (value === 'off') return false
@@ -846,6 +858,13 @@ export function loadConfig(
846
858
  applyBundleContentOnInstall: setting('CROMBOLO_APPLY_BUNDLE_CONTENT') !== 'false',
847
859
  // Resolved again below, once it is known whether a store was configured.
848
860
  runtimeInstalls: setting('CROMBOLO_RUNTIME_INSTALLS') !== 'false',
861
+ bundlePolicy: {
862
+ signatures: bundleSignatures(setting('CROMBOLO_BUNDLE_SIGNATURES')),
863
+ sources: (setting('CROMBOLO_BUNDLE_SOURCES') ?? '')
864
+ .split(',')
865
+ .map((source) => source.trim())
866
+ .filter(Boolean),
867
+ },
849
868
  // Resolved again below, once it is known whether this is development.
850
869
  errors: { showDetails: envFlag(setting('CROMBOLO_SHOW_ERROR_DETAILS')) ?? false },
851
870
  liveReload: envFlag(setting('CROMBOLO_LIVE_RELOAD')) ?? false,
@@ -1022,7 +1041,7 @@ export function describeDatabase(
1022
1041
  }
1023
1042
  }
1024
1043
 
1025
- export const VERSION = '0.44.0'
1044
+ export const VERSION = '0.45.0'
1026
1045
 
1027
1046
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1028
1047
  /** A positive number from a setting, else the default. */
package/src/index.ts CHANGED
@@ -19,6 +19,7 @@ export * from './api-client.ts'
19
19
  export * from './atomic-write.ts'
20
20
  export * from './backup.ts'
21
21
  export * from './boot-failure.ts'
22
+ export * from './bundle-admin.ts'
22
23
  export * from './bundle-build.ts'
23
24
  export * from './bundle-code.ts'
24
25
  export * from './bundle-grants.ts'
@@ -87,12 +88,14 @@ export * from './no-nodes.ts'
87
88
  export * from './oembed.ts'
88
89
  export * from './owner-jobs.ts'
89
90
  export * from './ports.ts'
91
+ export * from './provenance.ts'
90
92
  export * from './rate-limit.ts'
91
93
  export * from './redirects.ts'
92
94
  export * from './remote.ts'
93
95
  export * from './remote-ci.ts'
94
96
  export * from './remote-credentials.ts'
95
97
  export * from './remote-media.ts'
98
+ export * from './restart-pending.ts'
96
99
  export * from './routes.ts'
97
100
  export * from './schema.ts'
98
101
  export * from './schema-picks.ts'
@@ -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. */