@crombolo/server 0.60.0 → 0.62.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.
@@ -0,0 +1,631 @@
1
+ /**
2
+ * Putting an extension into its root (stories 326, 332): what a registry
3
+ * version or a kept file declares, its signature held to a policy, `bun add` in
4
+ * its root, what landed checked against its integrity, and its line in the
5
+ * record. The Marketplace installs through it, and so does `installExtension`,
6
+ * a host's own way to install. docs/bundles.md, "The record and the roots".
7
+ */
8
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
9
+ import { tmpdir } from 'node:os'
10
+ import { join, relative, resolve, sep } from 'node:path'
11
+ import {
12
+ askedPermissions,
13
+ type BundlePackage,
14
+ type DeclaredPermission,
15
+ forgetExtension,
16
+ isSchema3Field,
17
+ type PackageJson,
18
+ packageInRoot,
19
+ prepareRoot,
20
+ type RecordedExtension,
21
+ readBundlePackage,
22
+ readPackageJson,
23
+ readRecord,
24
+ readSettings,
25
+ recordExtension,
26
+ rootOf,
27
+ SCHEMA_3_NOT_INSTALLED,
28
+ validateBundlePackage,
29
+ } from '@crombolo/backoffice-host'
30
+ import { LOCAL_BUNDLES_DIR, localBundleFileName } from '@crombolo/transfer'
31
+ import { loadConfig } from './config.ts'
32
+ import {
33
+ type ProvenancePolicy,
34
+ type ProvenanceResult,
35
+ provenanceProblem,
36
+ verifyPackage,
37
+ verifyProvenance,
38
+ } from './provenance.ts'
39
+ import { extractTarball } from './tar.ts'
40
+
41
+ /** Where a registry version's tarball is, and what it hashes to. */
42
+ export interface Dist {
43
+ tarball?: string
44
+ integrity?: string
45
+ }
46
+
47
+ /** A name npm would accept, so nothing shell-ish or path-ish reaches `bun add`. */
48
+ export function isValidPackageName(name: string): boolean {
49
+ return /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(name) && name.length <= 214
50
+ }
51
+
52
+ /**
53
+ * A version or range that cannot be mistaken for another argument.
54
+ *
55
+ * Ranges start with an operator — `^2.1`, `>=1 <2` — so those lead; `-` never
56
+ * does, because `bun add` would read it as a flag. No shell is involved
57
+ * (`Bun.spawn` takes an argv), so the space in a range is harmless.
58
+ */
59
+ export function isValidVersion(version: string): boolean {
60
+ return /^[A-Za-z0-9^~>=<*][A-Za-z0-9.^~>=<| *+-]*$/.test(version) && version.length <= 64
61
+ }
62
+
63
+ export type PackageInstaller = (
64
+ action: 'add' | 'remove',
65
+ specifier: string,
66
+ siteDir: string,
67
+ ) => Promise<{ ok: boolean; output: string }>
68
+
69
+ /**
70
+ * The argv an install runs. `add` never runs a package's install scripts,
71
+ * whatever Bun's own list of trusted packages says (story 194).
72
+ */
73
+ export function installCommand(
74
+ action: 'add' | 'remove',
75
+ specifier: string,
76
+ registry?: string,
77
+ ): string[] {
78
+ const from = registry ? ['--registry', registry] : []
79
+ return action === 'add'
80
+ ? ['bun', 'add', '--ignore-scripts', ...from, specifier]
81
+ : ['bun', action, ...from, specifier]
82
+ }
83
+
84
+ /**
85
+ * `bun add` in a directory, from the registry given or Bun's own: Bun owns
86
+ * resolution and writes the lockfile.
87
+ *
88
+ * The spawn itself can fail rather than the command — an unreadable directory
89
+ * or a `bun` that is not on the path both throw out of `Bun.spawn` — and that
90
+ * has to come back as a failed install with a reason, not as an exception.
91
+ */
92
+ export function installerFrom(registry?: string): PackageInstaller {
93
+ return async (action, specifier, siteDir) => {
94
+ try {
95
+ const proc = Bun.spawn(installCommand(action, specifier, registry), {
96
+ cwd: siteDir,
97
+ stdout: 'pipe',
98
+ stderr: 'pipe',
99
+ })
100
+ const [stdout, stderr, code] = await Promise.all([
101
+ new Response(proc.stdout).text(),
102
+ new Response(proc.stderr).text(),
103
+ proc.exited,
104
+ ])
105
+ return { ok: code === 0, output: `${stdout}${stderr}`.trim() }
106
+ } catch (error) {
107
+ return {
108
+ ok: false,
109
+ output: `bun ${action} could not be run in ${siteDir}: ${
110
+ error instanceof Error ? error.message : String(error)
111
+ }`,
112
+ }
113
+ }
114
+ }
115
+ }
116
+
117
+ /** `bun add` from Bun's own registry. */
118
+ export const bunInstaller: PackageInstaller = installerFrom()
119
+
120
+ /** The layout setting a version declares, if it has page templates to place (story 312). */
121
+ export type AskedLayout = { key: string; label: string; suggested?: string }
122
+
123
+ export function layoutAsked(field: { settings?: unknown } | undefined): AskedLayout | undefined {
124
+ const read = readSettings(field?.settings)
125
+ if (!('settings' in read)) return undefined
126
+ const found = Object.entries(read.settings).find(([, setting]) => setting.type === 'layout')
127
+ if (!found) return undefined
128
+ const [key, setting] = found
129
+ return {
130
+ key,
131
+ label: setting.label,
132
+ ...(typeof setting.default === 'string' ? { suggested: setting.default } : {}),
133
+ }
134
+ }
135
+
136
+ /** How many screens its manifest's entries name (story 323), for what it adds. */
137
+ export const screensOf = (field: { extensions?: unknown }): number =>
138
+ Array.isArray(field.extensions)
139
+ ? field.extensions.filter(
140
+ (entry) => entry && typeof entry === 'object' && 'screen' in (entry as object),
141
+ ).length
142
+ : 0
143
+
144
+ /** What a registry version declares, read from its packument. */
145
+ export type RegistryDeclaration = BundlePackage['carries'] & {
146
+ permissions: DeclaredPermission[]
147
+ layout?: AskedLayout
148
+ version: string
149
+ dist?: Dist
150
+ id?: string
151
+ screens?: number
152
+ }
153
+
154
+ /**
155
+ * What the registry says a version carries: the version asked for (an exact
156
+ * one, or the highest a range admits), or the latest. `not-a-bundle` when that
157
+ * version is no valid bundle, `unreachable` when the registry could not say.
158
+ */
159
+ export async function declaresAt(
160
+ registry: string,
161
+ name: string,
162
+ wanted?: string,
163
+ call: typeof fetch = fetch,
164
+ ): Promise<
165
+ | RegistryDeclaration
166
+ | 'not-a-bundle'
167
+ | { refused: string[] }
168
+ | 'site-package'
169
+ | 'schema-3'
170
+ | 'unreachable'
171
+ > {
172
+ try {
173
+ const response = await call(`${registry}/${encodeURIComponent(name)}`, {
174
+ headers: { accept: 'application/json' },
175
+ })
176
+ if (!response.ok) return response.status === 404 ? 'not-a-bundle' : 'unreachable'
177
+ const packument = (await response.json()) as {
178
+ 'dist-tags'?: Record<string, string>
179
+ versions?: Record<string, PackageJson>
180
+ }
181
+ const versions = packument.versions ?? {}
182
+ const resolved =
183
+ wanted === undefined
184
+ ? packument['dist-tags']?.latest
185
+ : wanted in versions
186
+ ? wanted
187
+ : (packument['dist-tags']?.[wanted] ??
188
+ Object.keys(versions)
189
+ .filter((v) => Bun.semver.satisfies(v, wanted))
190
+ .sort(Bun.semver.order)
191
+ .at(-1))
192
+ const version = resolved ? versions[resolved] : undefined
193
+ // A site package is never installed, whatever a registry offers (story 306).
194
+ if ((version?.crombolo as { bundleType?: unknown } | undefined)?.bundleType === 'site')
195
+ return 'site-package'
196
+ if (!resolved || !version) return 'not-a-bundle'
197
+ // Why it is not one, so its author knows what to change: a layout before 0.59 among them (story 320).
198
+ const problems = validateBundlePackage(version)
199
+ if (problems.length > 0) return { refused: problems }
200
+ const dist = (version as { dist?: Dist }).dist
201
+ const field = version.crombolo as {
202
+ extensions?: unknown[]
203
+ content?: boolean
204
+ id?: string
205
+ server?: string
206
+ permissions?: unknown
207
+ settings?: unknown
208
+ }
209
+ // Story 308: a version that says nothing of why it asks is not installed.
210
+ if (isSchema3Field(field)) return 'schema-3'
211
+ return {
212
+ extensions: Array.isArray(field.extensions) && field.extensions.length > 0,
213
+ content: field.content === true,
214
+ server: field.server !== undefined,
215
+ permissions: askedPermissions(field),
216
+ layout: layoutAsked(field),
217
+ version: resolved,
218
+ ...(typeof field.id === 'string' ? { id: field.id } : {}),
219
+ screens: screensOf(field),
220
+ ...(dist ? { dist } : {}),
221
+ }
222
+ } catch {
223
+ return 'unreachable'
224
+ }
225
+ }
226
+
227
+ /** A site package offered as a dependency: refused, saying how one is used (story 306). */
228
+ export function sitePackageRefused(name: string): { ok: false; message: string } {
229
+ return {
230
+ ok: false,
231
+ message: `${name} is a site package, which is applied to a site with \`crombolo site apply\`, never installed, so it was not installed.`,
232
+ }
233
+ }
234
+
235
+ /** What a packed bundle on this machine declares, read from its package.json. */
236
+ export interface FileDeclaration {
237
+ id: string
238
+ name: string
239
+ version: string
240
+ server: boolean
241
+ permissions: DeclaredPermission[]
242
+ layout?: AskedLayout
243
+ }
244
+
245
+ /** What a packed bundle on this machine declares, or why it cannot be installed. */
246
+ export async function declaresIn(file: string): Promise<FileDeclaration | string> {
247
+ const dir = mkdtempSync(join(tmpdir(), 'crombolo-bundle-file-'))
248
+ try {
249
+ await extractTarball(file, dir)
250
+ const root = existsSync(join(dir, 'package', 'package.json')) ? join(dir, 'package') : dir
251
+ const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as PackageJson
252
+ if ((json.crombolo as { bundleType?: unknown } | undefined)?.bundleType === 'site')
253
+ return sitePackageRefused(file).message
254
+ const problems = validateBundlePackage(json)
255
+ if (problems.length > 0 || typeof json.name !== 'string' || typeof json.version !== 'string')
256
+ return `${file} is not an extension for this site, so it was not installed.`
257
+ const field = json.crombolo as {
258
+ id: string
259
+ server?: string
260
+ permissions?: unknown
261
+ settings?: unknown
262
+ }
263
+ if (isSchema3Field(field)) return `${file} was not installed: ${SCHEMA_3_NOT_INSTALLED}.`
264
+ return {
265
+ id: field.id,
266
+ name: json.name,
267
+ version: json.version,
268
+ server: field.server !== undefined,
269
+ permissions: askedPermissions(field),
270
+ layout: layoutAsked(field),
271
+ }
272
+ } catch {
273
+ return `${file} could not be read as a packed bundle, so it was not installed.`
274
+ } finally {
275
+ rmSync(dir, { recursive: true, force: true })
276
+ }
277
+ }
278
+
279
+ /** A tarball's integrity, as npm writes one. */
280
+ export const integrityOf = (bytes: Uint8Array): string =>
281
+ `sha512-${new Bun.CryptoHasher('sha512').update(bytes).digest('base64')}`
282
+
283
+ /**
284
+ * Where a registry version was built (story 060): its exact tarball fetched,
285
+ * held to the registry's integrity, and its signature checked, so the bytes
286
+ * checked are the bytes `bun add` then installs. A registry that gives no
287
+ * tarball leaves nothing to check; one that cannot be fetched is not unsigned.
288
+ */
289
+ export async function provenanceAt(
290
+ name: string,
291
+ dist: Dist | undefined,
292
+ options: { fetch?: typeof fetch; verify?: (dir: string) => Promise<ProvenanceResult> } = {},
293
+ ): Promise<ProvenanceResult> {
294
+ if (!dist?.tarball) return { state: 'unsigned' }
295
+ const call = options.fetch ?? fetch
296
+ const verify = options.verify ?? ((dir: string) => verifyProvenance(dir))
297
+ const dir = mkdtempSync(join(tmpdir(), 'crombolo-bundle-check-'))
298
+ try {
299
+ const response = await call(dist.tarball)
300
+ if (!response.ok)
301
+ return {
302
+ state: 'unchecked',
303
+ reason: `${name} could not be fetched to check its signature (the registry answered ${response.status})`,
304
+ }
305
+ const bytes = new Uint8Array(await response.arrayBuffer())
306
+ if (dist.integrity?.startsWith('sha512-') && integrityOf(bytes) !== dist.integrity)
307
+ return { state: 'invalid', reason: `${name} is not the package the registry describes` }
308
+ const file = join(dir, 'bundle.tgz')
309
+ await Bun.write(file, bytes)
310
+ const unpacked = join(dir, 'package')
311
+ await extractTarball(file, unpacked)
312
+ return await verify(unpacked)
313
+ } catch (error) {
314
+ return {
315
+ state: 'unchecked',
316
+ reason: `${name} could not be checked: ${error instanceof Error ? error.message : String(error)}`,
317
+ }
318
+ } finally {
319
+ rmSync(dir, { recursive: true, force: true })
320
+ }
321
+ }
322
+
323
+ /** Why a policy refuses a version, or undefined when it may be installed. Pure. */
324
+ export function signatureRefusal(
325
+ label: string,
326
+ provenance: ProvenanceResult,
327
+ policy: ProvenancePolicy = { signatures: 'optional', sources: [] },
328
+ ): string | undefined {
329
+ const problem = provenanceProblem(provenance, policy)
330
+ return problem ? `${label} was not installed: ${problem}.` : undefined
331
+ }
332
+
333
+ /**
334
+ * A bundle's file at `bundles/<name>-<version>.tgz` (story 245): used in place
335
+ * when it is there already, copied there otherwise. Another file under that
336
+ * name is refused, since one version is one file.
337
+ */
338
+ export function keepInSite(
339
+ siteDir: string,
340
+ file: string,
341
+ declared: { name: string; version: string },
342
+ ): { path: string; copied: boolean } | string {
343
+ const path = `${LOCAL_BUNDLES_DIR}/${localBundleFileName(declared.name, declared.version)}`
344
+ const target = join(siteDir, path)
345
+ if (resolve(file) === resolve(target)) return { path, copied: false }
346
+ const bytes = readFileSync(file)
347
+ if (existsSync(target)) {
348
+ if (readFileSync(target).equals(bytes)) return { path, copied: false }
349
+ return `${path} already holds a different ${declared.name}@${declared.version} than ${file}, so it was not installed: one version is one file. Remove ${path} first if ${file} is the one to keep.`
350
+ }
351
+ mkdirSync(join(siteDir, LOCAL_BUNDLES_DIR), { recursive: true })
352
+ copyFileSync(file, target)
353
+ return { path, copied: true }
354
+ }
355
+
356
+ /**
357
+ * The integrity a root's `bun.lock` holds for a package, or undefined when it
358
+ * holds none. The lockfile is JSON with trailing commas.
359
+ */
360
+ export function lockedIntegrity(root: string, name: string): string | undefined {
361
+ try {
362
+ const text = readFileSync(join(root, 'bun.lock'), 'utf8').replace(/,(\s*[}\]])/g, '$1')
363
+ const entry = (JSON.parse(text) as { packages?: Record<string, unknown> }).packages?.[name]
364
+ return Array.isArray(entry)
365
+ ? entry.find((part): part is string => typeof part === 'string' && /^sha\d+-/.test(part))
366
+ : undefined
367
+ } catch {
368
+ return undefined
369
+ }
370
+ }
371
+
372
+ /** An install into a root that landed, with the line it recorded and how to take it out again. */
373
+ export interface RootInstall {
374
+ ok: true
375
+ root: string
376
+ line: RecordedExtension
377
+ undo: () => void
378
+ }
379
+
380
+ /**
381
+ * `bun add` into the extension's own root (story 326), never the site's
382
+ * dependencies, then the line in the record. A `./` specifier is a site path,
383
+ * read from the root. What landed is held to the integrity given, by the
384
+ * root's lockfile; on a failure a root made here is taken out again.
385
+ */
386
+ export async function installIntoRoot(
387
+ siteDir: string,
388
+ into: { id: string; name: string; specifier: string; version?: string; integrity?: string },
389
+ install: PackageInstaller,
390
+ ): Promise<RootInstall | { ok: false; message: string }> {
391
+ const existed = existsSync(rootOf(siteDir, into.id))
392
+ const root = prepareRoot(siteDir, into.id)
393
+ const undo = () => {
394
+ rmSync(root, { recursive: true, force: true })
395
+ forgetExtension(siteDir, into.id)
396
+ }
397
+ const inRoot = into.specifier.startsWith('./')
398
+ ? `file:${relative(root, join(siteDir, into.specifier)).split(sep).join('/')}`
399
+ : into.specifier
400
+ const result = await install('add', inRoot, root)
401
+ if (!result.ok) {
402
+ if (!existed) undo()
403
+ return { ok: false, message: result.output || `Installing ${into.specifier} failed.` }
404
+ }
405
+ const locked = lockedIntegrity(root, into.name)
406
+ if (into.integrity && locked && locked !== into.integrity) {
407
+ undo()
408
+ return {
409
+ ok: false,
410
+ message: `${into.name} installed as ${locked}, not the ${into.integrity} it was to be, so it was removed again.`,
411
+ }
412
+ }
413
+ const landed = readPackageJson(join(packageInRoot(siteDir, into.id, into.name), 'package.json'))
414
+ const line: RecordedExtension = {
415
+ name: into.name,
416
+ version: landed?.version ?? into.version ?? 'unknown',
417
+ ...(into.integrity ? { integrity: into.integrity } : {}),
418
+ }
419
+ recordExtension(siteDir, into.id, line)
420
+ return { ok: true, root, line, undo }
421
+ }
422
+
423
+ /** What a host asks `installExtension` for. */
424
+ export interface InstallExtensionOptions {
425
+ /** Its npm package name. */
426
+ name: string
427
+ /** A version, a range or a dist-tag; the latest when absent. */
428
+ version?: string
429
+ /** What its tarball must hash to; the registry's is recorded when absent. */
430
+ integrity?: string
431
+ /** A packed `.tgz` to install in place of the registry's, kept in the site's `bundles/`. */
432
+ file?: string
433
+ /** What the site takes of a signature; the site's `CROMBOLO_BUNDLE_SIGNATURES` and `CROMBOLO_BUNDLE_SOURCES` when absent. */
434
+ policy?: ProvenancePolicy
435
+ /** The registry to install from; the site's `CROMBOLO_NPM_REGISTRY` when absent. */
436
+ registry?: string
437
+ }
438
+
439
+ export type InstallExtensionResult =
440
+ | {
441
+ ok: true
442
+ id: string
443
+ root: string
444
+ line: RecordedExtension
445
+ provenance: ProvenanceResult
446
+ }
447
+ | { ok: false; problems: string[] }
448
+
449
+ const refused = (...problems: string[]): { ok: false; problems: string[] } => ({
450
+ ok: false,
451
+ problems,
452
+ })
453
+
454
+ /** Why the package that landed in a root is not one the site takes, or undefined. */
455
+ function landedProblem(
456
+ siteDir: string,
457
+ id: string,
458
+ name: string,
459
+ expected: string,
460
+ ): string | undefined {
461
+ const dir = packageInRoot(siteDir, id, name)
462
+ const json = readPackageJson(join(dir, 'package.json'))
463
+ if ((json?.crombolo as { bundleType?: unknown } | undefined)?.bundleType === 'site')
464
+ return sitePackageRefused(name).message
465
+ const read = readBundlePackage(dir)
466
+ if (!read.bundle)
467
+ return `${name} is not an extension this site takes, so it was removed again${read.problems.length > 0 ? `: ${read.problems.join('; ')}` : ''}.`
468
+ if (read.bundle.bundleType !== 'extension' || read.bundle.id !== id)
469
+ return `${name} is not the extension "${id}" it said it was, so it was removed again.`
470
+ if (read.bundle.version !== expected)
471
+ return `${name}@${read.bundle.version} landed where ${expected} was checked, so it was removed again. Try the install again.`
472
+ if (isSchema3Field(read.bundle.field))
473
+ return `${name}@${read.bundle.version} was removed again: ${SCHEMA_3_NOT_INSTALLED}.`
474
+ return undefined
475
+ }
476
+
477
+ /**
478
+ * Installs an extension into its root and records it, as the Marketplace does
479
+ * (story 332): from the registry, or a packed file. It is refused when the
480
+ * site's signature policy, or the one passed, refuses it, and when it is not an
481
+ * extension this release takes. It grants nothing and applies no content.
482
+ */
483
+ export async function installExtension(
484
+ siteDir: string,
485
+ options: InstallExtensionOptions,
486
+ ): Promise<InstallExtensionResult> {
487
+ const { name } = options
488
+ if (!isValidPackageName(name)) return refused(`'${name}' is not a package name npm would accept.`)
489
+ if (options.version !== undefined && !isValidVersion(options.version))
490
+ return refused(`'${options.version}' is not a version npm would accept.`)
491
+ let site: { policy: ProvenancePolicy; registry: string }
492
+ try {
493
+ const config = loadConfig({ siteDir }, siteDir)
494
+ site = { policy: config.bundlePolicy, registry: config.npmRegistry }
495
+ } catch (error) {
496
+ return refused(error instanceof Error ? error.message : String(error))
497
+ }
498
+ const policy = options.policy ?? site.policy
499
+ const registry = (options.registry ?? site.registry).replace(/\/+$/, '')
500
+ return options.file
501
+ ? installFromFile(siteDir, options, options.file, policy, registry)
502
+ : installFromRegistry(siteDir, options, policy, registry)
503
+ }
504
+
505
+ async function installFromRegistry(
506
+ siteDir: string,
507
+ options: InstallExtensionOptions,
508
+ policy: ProvenancePolicy,
509
+ registry: string,
510
+ ): Promise<InstallExtensionResult> {
511
+ const { name } = options
512
+ const declared = await declaresAt(registry, name, options.version)
513
+ if (declared === 'unreachable')
514
+ return refused(
515
+ `The package registry could not say what ${name} contains, so it was not installed.`,
516
+ )
517
+ if (declared === 'not-a-bundle')
518
+ return refused(`${name} is not an extension for this site, so it was not installed.`)
519
+ if (declared === 'site-package') return refused(sitePackageRefused(name).message)
520
+ if (declared === 'schema-3')
521
+ return refused(`${name} was not installed: ${SCHEMA_3_NOT_INSTALLED}.`)
522
+ if ('refused' in declared)
523
+ return refused(
524
+ `${name} is not an extension this site takes, so it was not installed: ${declared.refused.join('; ')}.`,
525
+ )
526
+ if (!declared.id)
527
+ return refused(`${name} is not an extension for this site, so it was not installed.`)
528
+ const label = `${name}@${declared.version}`
529
+ const integrity = declared.dist?.integrity
530
+ if (options.integrity && options.integrity !== integrity)
531
+ return refused(
532
+ `${label} was not installed: the registry gives its integrity as ${integrity ?? 'nothing'}, not ${options.integrity}.`,
533
+ )
534
+ const provenance = await provenanceAt(name, declared.dist)
535
+ const unsigned = signatureRefusal(label, provenance, policy)
536
+ if (unsigned) return refused(unsigned)
537
+ return landed(siteDir, {
538
+ id: declared.id,
539
+ name,
540
+ specifier: `${name}@${declared.version}`,
541
+ version: declared.version,
542
+ integrity,
543
+ registry,
544
+ provenance,
545
+ })
546
+ }
547
+
548
+ async function installFromFile(
549
+ siteDir: string,
550
+ options: InstallExtensionOptions,
551
+ file: string,
552
+ policy: ProvenancePolicy,
553
+ registry: string,
554
+ ): Promise<InstallExtensionResult> {
555
+ const declared = await declaresIn(file)
556
+ if (typeof declared === 'string') return refused(declared)
557
+ if (declared.name !== options.name)
558
+ return refused(`${file} holds ${declared.name}, not ${options.name}, so it was not installed.`)
559
+ if (options.version !== undefined && options.version !== declared.version)
560
+ return refused(
561
+ `${file} holds ${declared.name}@${declared.version}, not ${options.version}, so it was not installed.`,
562
+ )
563
+ const integrity = integrityOf(new Uint8Array(readFileSync(file)))
564
+ if (options.integrity && options.integrity !== integrity)
565
+ return refused(
566
+ `${file} was not installed: its integrity is ${integrity}, not ${options.integrity}.`,
567
+ )
568
+ const provenance = await verifyPackage(file).catch((error: unknown) => ({
569
+ state: 'unchecked' as const,
570
+ reason: error instanceof Error ? error.message : String(error),
571
+ }))
572
+ const unsigned = signatureRefusal(declared.name, provenance, policy)
573
+ if (unsigned) return refused(unsigned)
574
+ const kept = keepInSite(siteDir, file, declared)
575
+ if (typeof kept === 'string') return refused(kept)
576
+ const outcome = await landed(siteDir, {
577
+ id: declared.id,
578
+ name: declared.name,
579
+ specifier: `./${kept.path}`,
580
+ version: declared.version,
581
+ integrity,
582
+ registry,
583
+ provenance,
584
+ })
585
+ if (!outcome.ok && kept.copied) rmSync(join(siteDir, kept.path), { force: true })
586
+ return outcome
587
+ }
588
+
589
+ /** The install into the root, and what landed checked; taken out again when it is refused. */
590
+ async function landed(
591
+ siteDir: string,
592
+ into: {
593
+ id: string
594
+ name: string
595
+ specifier: string
596
+ version: string
597
+ integrity?: string
598
+ registry: string
599
+ provenance: ProvenanceResult
600
+ },
601
+ ): Promise<InstallExtensionResult> {
602
+ const result = await installIntoRoot(siteDir, into, installerFrom(into.registry))
603
+ if (!result.ok) return refused(result.message)
604
+ const problem = landedProblem(siteDir, into.id, into.name, into.version)
605
+ if (problem) {
606
+ result.undo()
607
+ return refused(problem)
608
+ }
609
+ return {
610
+ ok: true,
611
+ id: into.id,
612
+ root: result.root,
613
+ line: result.line,
614
+ provenance: into.provenance,
615
+ }
616
+ }
617
+
618
+ /**
619
+ * Deletes an extension's root and its line in the record, and nothing else:
620
+ * its data, grant and settings stay, for the host to decide with the site, as
621
+ * story 328 says of an administrator's removal.
622
+ */
623
+ export function removeExtension(siteDir: string, id: string): { removed: boolean } {
624
+ if (!/^[a-z0-9][a-z0-9._-]*$/i.test(id)) return { removed: false }
625
+ const root = rootOf(siteDir, id)
626
+ const recorded = id in readRecord(siteDir)
627
+ const rooted = existsSync(root)
628
+ if (rooted) rmSync(root, { recursive: true, force: true })
629
+ if (recorded) forgetExtension(siteDir, id)
630
+ return { removed: rooted || recorded }
631
+ }