@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.
@@ -17,49 +17,72 @@
17
17
  * browser cannot reach npm, and the backoffice keeps making same-origin
18
18
  * requests only.
19
19
  */
20
- import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
21
- import { tmpdir } from 'node:os'
22
- import { join, resolve } from 'node:path'
20
+ import { readFileSync, rmSync } from 'node:fs'
21
+ import { join } from 'node:path'
23
22
  import {
24
- askedPermissions,
23
+ type AccessLevel,
25
24
  type BundlePackage,
26
25
  type DeclaredPermission,
27
26
  describePermissions,
28
27
  EXTENSION_KEYWORD,
29
28
  type ExtensionRegistry,
30
- isSchema3Field,
29
+ forgetExtension,
30
+ groupsOf,
31
31
  LEGACY_EXTENSION_KEYWORD,
32
- type PackageJson,
33
- readSettings,
32
+ levelOf,
33
+ type PermissionGroups,
34
+ RECORD_FILE,
35
+ ROOTS_DIR,
36
+ readPackageJson,
37
+ readRecord,
38
+ rootOf,
34
39
  SCHEMA_3_NOT_INSTALLED,
35
40
  SITE_PACKAGE_NOT_INSTALLED,
36
- validateBundlePackage,
41
+ USER_DELEGATE,
37
42
  } from '@crombolo/backoffice-host'
43
+ import { localBundlePath, localBundlesNamed } from '@crombolo/transfer'
38
44
  import {
39
- LOCAL_BUNDLES_DIR,
40
- localBundleFileName,
41
- localBundlePath,
42
- localBundlesNamed,
43
- } from '@crombolo/transfer'
44
- import { type BundleGrants, declaredEntries, isSchema3 } from './bundle-grants.ts'
45
+ type BundleGrants,
46
+ DELEGATE_NEEDS_PERSON,
47
+ declaredEntries,
48
+ declaredPermissions,
49
+ isSchema3,
50
+ } from './bundle-grants.ts'
45
51
  import { siteLayouts } from './components.ts'
52
+ import {
53
+ type AskedLayout,
54
+ bunInstaller,
55
+ declaresAt as declaresAtRegistry,
56
+ declaresIn,
57
+ installIntoRoot,
58
+ isValidPackageName,
59
+ isValidVersion,
60
+ keepInSite,
61
+ layoutAsked,
62
+ type PackageInstaller,
63
+ provenanceAt as provenanceAtRegistry,
64
+ screensOf,
65
+ signatureRefusal,
66
+ sitePackageRefused,
67
+ } from './extension-install.ts'
68
+ import { grantRefusal, type UnrestrictedFrom } from './grant-policy.ts'
46
69
  import { logger } from './logging.ts'
47
70
  import {
48
71
  type ProvenancePolicy,
49
72
  type ProvenanceResult,
50
- provenanceProblem,
51
73
  verifyPackage,
52
74
  verifyProvenance,
53
75
  } from './provenance.ts'
54
- import { extractTarball } from './tar.ts'
55
76
 
56
- const log = logger('packages')
77
+ export {
78
+ bunInstaller,
79
+ installCommand,
80
+ isValidPackageName,
81
+ isValidVersion,
82
+ type PackageInstaller,
83
+ } from './extension-install.ts'
57
84
 
58
- /** Where a registry version's tarball is, and what it hashes to. */
59
- interface Dist {
60
- tarball?: string
61
- integrity?: string
62
- }
85
+ const log = logger('packages')
63
86
 
64
87
  /** How long a search is reused. Long enough to page a list, short enough to stay fresh. */
65
88
  const CACHE_MS = 5 * 60 * 1000
@@ -140,6 +163,8 @@ export interface MarketplaceOptions {
140
163
  applyContent?: (packageName: string) => Promise<ContentOutcome>
141
164
  /** The site's `applyBundleContentOnInstall`. */
142
165
  applyContentOnInstall?: boolean
166
+ /** Where an Unrestricted extension may be granted from (story 324). */
167
+ unrestrictedFrom?: UnrestrictedFrom
143
168
  /**
144
169
  * False refuses installing and removing here: the dependency belongs in
145
170
  * `package.json` and a deploy, so every node has it and it outlives a restart.
@@ -154,6 +179,12 @@ export interface MarketplaceOptions {
154
179
  }
155
180
 
156
181
  export interface InstallOutcome {
182
+ /** How far it reaches, when an install was refused for it or needs a grant (story 324). */
183
+ level?: AccessLevel
184
+ /** What it asks for, folded into the four groups the panel shows. */
185
+ groups?: PermissionGroups
186
+ /** Its extension id, which a config entry is keyed by. */
187
+ id?: string
157
188
  ok: boolean
158
189
  /**
159
190
  * The dependency line the site's `package.json` now holds, so the UI can show
@@ -180,7 +211,8 @@ export interface InstallOutcome {
180
211
  warning?: string
181
212
  }[]
182
213
  /** With `needsGrant`: it asks to act for a user, so the grant names whom (story 308). */
183
- asksActAs?: boolean
214
+ /** It asks for `user.delegate`: it acts for the person using it (story 325). */
215
+ delegates?: boolean
184
216
  /**
185
217
  * With `needsGrant`: its page templates sit in a site layout, picked here
186
218
  * (story 312). `suggested` is the one it names, when the site has it.
@@ -194,12 +226,6 @@ export interface InstallOutcome {
194
226
  file?: string
195
227
  }
196
228
 
197
- export type PackageInstaller = (
198
- action: 'add' | 'remove',
199
- specifier: string,
200
- siteDir: string,
201
- ) => Promise<{ ok: boolean; output: string }>
202
-
203
229
  interface SearchObject {
204
230
  package?: {
205
231
  name?: string
@@ -210,22 +236,6 @@ interface SearchObject {
210
236
  }
211
237
  }
212
238
 
213
- /** A name npm would accept, so nothing shell-ish or path-ish reaches `bun add`. */
214
- export function isValidPackageName(name: string): boolean {
215
- return /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(name) && name.length <= 214
216
- }
217
-
218
- /**
219
- * A version or range that cannot be mistaken for another argument.
220
- *
221
- * Ranges start with an operator — `^2.1`, `>=1 <2` — so those lead; `-` never
222
- * does, because `bun add` would read it as a flag. No shell is involved
223
- * (`Bun.spawn` takes an argv), so the space in a range is harmless.
224
- */
225
- export function isValidVersion(version: string): boolean {
226
- return /^[A-Za-z0-9^~>=<*][A-Za-z0-9.^~>=<| *+-]*$/.test(version) && version.length <= 64
227
- }
228
-
229
239
  export interface Marketplace {
230
240
  /** Where someone browsing should be sent, when they want more than this list. */
231
241
  url(): string
@@ -238,10 +248,12 @@ export interface Marketplace {
238
248
  applyContent?: boolean
239
249
  /** The permissions the administrator granted: the bundle's whole list (stories 222, 308). */
240
250
  grant?: readonly string[]
241
- /** Whom it acts for, when it asks for `actAs`: `installer:<key>`, `caller` or `user:<key>`. */
242
- actAs?: string | null
251
+ /** Under `user.delegate`, the user a job or an event acts for: whoever grants it (story 325). */
252
+ delegateTo?: string | null
243
253
  /** Who is installing, recorded on the grant. */
244
254
  by?: string | null
255
+ /** The person installing is an administrator: only one grants the upper levels (story 324). */
256
+ isAdmin?: boolean
245
257
  },
246
258
  ): Promise<InstallOutcome>
247
259
  /** What a version would bring, read from the registry and nothing installed: for a dry run. */
@@ -266,70 +278,15 @@ export interface Marketplace {
266
278
  options?: {
267
279
  applyContent?: boolean
268
280
  grant?: readonly string[]
269
- actAs?: string | null
281
+ delegateTo?: string | null
270
282
  by?: string | null
283
+ /** The person installing is an administrator: only one grants the upper levels (story 324). */
284
+ isAdmin?: boolean
271
285
  },
272
286
  ): Promise<InstallOutcome>
273
287
  uninstall(name: string): Promise<InstallOutcome>
274
288
  }
275
289
 
276
- /**
277
- * The argv an install runs. `add` never runs a package's install scripts,
278
- * whatever Bun's own list of trusted packages says (story 194).
279
- */
280
- export function installCommand(action: 'add' | 'remove', specifier: string): string[] {
281
- return action === 'add'
282
- ? ['bun', 'add', '--ignore-scripts', specifier]
283
- : ['bun', action, specifier]
284
- }
285
-
286
- /**
287
- * `bun add` in the site directory: Bun owns resolution and writes the lockfile.
288
- *
289
- * The spawn itself can fail rather than the command — an unreadable site
290
- * directory or a `bun` that is not on the path both throw out of `Bun.spawn` —
291
- * and that has to come back as a failed install with a reason, not as an
292
- * exception the route turns into a 500.
293
- */
294
- export const bunInstaller: PackageInstaller = async (action, specifier, siteDir) => {
295
- try {
296
- const proc = Bun.spawn(installCommand(action, specifier), {
297
- cwd: siteDir,
298
- stdout: 'pipe',
299
- stderr: 'pipe',
300
- })
301
- const [stdout, stderr, code] = await Promise.all([
302
- new Response(proc.stdout).text(),
303
- new Response(proc.stderr).text(),
304
- proc.exited,
305
- ])
306
- return { ok: code === 0, output: `${stdout}${stderr}`.trim() }
307
- } catch (error) {
308
- return {
309
- ok: false,
310
- output: `bun ${action} could not be run in ${siteDir}: ${
311
- error instanceof Error ? error.message : String(error)
312
- }`,
313
- }
314
- }
315
- }
316
-
317
- /** The layout setting a version declares, if it has page templates to place (story 312). */
318
- type AskedLayout = { key: string; label: string; suggested?: string }
319
-
320
- function layoutAsked(field: { settings?: unknown } | undefined): AskedLayout | undefined {
321
- const read = readSettings(field?.settings)
322
- if (!('settings' in read)) return undefined
323
- const found = Object.entries(read.settings).find(([, setting]) => setting.type === 'layout')
324
- if (!found) return undefined
325
- const [key, setting] = found
326
- return {
327
- key,
328
- label: setting.label,
329
- ...(typeof setting.default === 'string' ? { suggested: setting.default } : {}),
330
- }
331
- }
332
-
333
290
  export function createMarketplace(options: MarketplaceOptions): Marketplace {
334
291
  /** The site's layouts to pick from, the suggestion kept only when the site has it. */
335
292
  const layoutChoice = (asked: AskedLayout | undefined): InstallOutcome['layout'] => {
@@ -343,6 +300,16 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
343
300
 
344
301
  /** The range `package.json` holds for a dependency, as `bun add` wrote it. */
345
302
  const rangeFor = async (name: string): Promise<string | undefined> => {
303
+ // Story 326: an extension's range is in its own root's package.json, when it names one.
304
+ const recorded = Object.entries(readRecord(options.siteDir)).find(
305
+ ([, line]) => line.name === name,
306
+ )
307
+ const inRoot = recorded
308
+ ? readPackageJson(join(rootOf(options.siteDir, recorded[0]), 'package.json'))?.dependencies?.[
309
+ name
310
+ ]
311
+ : undefined
312
+ if (inRoot) return inRoot
346
313
  try {
347
314
  const json = (await Bun.file(join(options.siteDir, 'package.json')).json()) as {
348
315
  dependencies?: Record<string, string>
@@ -355,28 +322,6 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
355
322
  }
356
323
  let cached: { at: number; query: string; listings: MarketplaceListing[] } | undefined
357
324
 
358
- /**
359
- * A bundle's file at `bundles/<name>-<version>.tgz`: used in place when it is
360
- * there already, copied there otherwise. Another file under that name is
361
- * refused, since one version is one file.
362
- */
363
- const keepInSite = (
364
- file: string,
365
- declared: { name: string; version: string },
366
- ): { path: string; copied: boolean } | string => {
367
- const path = `${LOCAL_BUNDLES_DIR}/${localBundleFileName(declared.name, declared.version)}`
368
- const target = join(options.siteDir, path)
369
- if (resolve(file) === resolve(target)) return { path, copied: false }
370
- const bytes = readFileSync(file)
371
- if (existsSync(target)) {
372
- if (readFileSync(target).equals(bytes)) return { path, copied: false }
373
- 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.`
374
- }
375
- mkdirSync(join(options.siteDir, LOCAL_BUNDLES_DIR), { recursive: true })
376
- copyFileSync(file, target)
377
- return { path, copied: true }
378
- }
379
-
380
325
  /** The `bundles/` file a dependency used to name, removed once nothing names it. */
381
326
  const removeUnnamed = (previousRange: string | undefined, keep?: string) => {
382
327
  const path = localBundlePath(previousRange)
@@ -389,135 +334,46 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
389
334
  options.extensions.bundles().bundles.find((bundle) => bundle.packageName === name)?.version ??
390
335
  null
391
336
 
392
- /**
393
- * What the registry says a version carries: the version asked for (an exact
394
- * one, or the highest a range admits), or the latest. `not-a-bundle` when that
395
- * version is no valid bundle, `unreachable` when the registry could not say.
396
- */
397
- const declaresAt = async (
398
- name: string,
399
- wanted?: string,
400
- ): Promise<
401
- | (BundlePackage['carries'] & {
402
- permissions: DeclaredPermission[]
403
- layout?: AskedLayout
404
- version: string
405
- dist?: Dist
406
- })
407
- | 'not-a-bundle'
408
- | { refused: string[] }
409
- | 'site-package'
410
- | 'schema-3'
411
- | 'unreachable'
412
- > => {
413
- try {
414
- const response = await call(`${options.registry}/${encodeURIComponent(name)}`, {
415
- headers: { accept: 'application/json' },
416
- })
417
- if (!response.ok) return response.status === 404 ? 'not-a-bundle' : 'unreachable'
418
- const packument = (await response.json()) as {
419
- 'dist-tags'?: Record<string, string>
420
- versions?: Record<string, PackageJson>
421
- }
422
- const versions = packument.versions ?? {}
423
- const resolved =
424
- wanted === undefined
425
- ? packument['dist-tags']?.latest
426
- : wanted in versions
427
- ? wanted
428
- : (packument['dist-tags']?.[wanted] ??
429
- Object.keys(versions)
430
- .filter((v) => Bun.semver.satisfies(v, wanted))
431
- .sort(Bun.semver.order)
432
- .at(-1))
433
- const version = resolved ? versions[resolved] : undefined
434
- // A site package is never installed, whatever a registry offers (story 306).
435
- if ((version?.crombolo as { bundleType?: unknown } | undefined)?.bundleType === 'site')
436
- return 'site-package'
437
- if (!resolved || !version) return 'not-a-bundle'
438
- // Why it is not one, so its author knows what to change: a layout before 0.59 among them (story 320).
439
- const problems = validateBundlePackage(version)
440
- if (problems.length > 0) return { refused: problems }
441
- const dist = (version as { dist?: Dist }).dist
442
- const field = version.crombolo as {
443
- extensions?: unknown[]
444
- content?: boolean
445
- server?: string
446
- permissions?: unknown
447
- settings?: unknown
448
- }
449
- // Story 308: a version that says nothing of why it asks is not installed.
450
- if (isSchema3Field(field)) return 'schema-3'
451
- return {
452
- extensions: Array.isArray(field.extensions) && field.extensions.length > 0,
453
- content: field.content === true,
454
- server: field.server !== undefined,
455
- permissions: askedPermissions(field),
456
- layout: layoutAsked(field),
457
- version: resolved,
458
- ...(dist ? { dist } : {}),
459
- }
460
- } catch {
461
- return 'unreachable'
462
- }
463
- }
464
-
337
+ const declaresAt = (name: string, wanted?: string) =>
338
+ declaresAtRegistry(options.registry, name, wanted, call)
465
339
  const verify = options.verify ?? ((dir: string) => verifyProvenance(dir))
466
-
467
- /**
468
- * Where a registry version was built (story 060): its exact tarball fetched,
469
- * held to the registry's integrity, and its signature checked, so the bytes
470
- * checked are the bytes `bun add` then installs. A registry that gives no
471
- * tarball leaves nothing to check; one that cannot be fetched is not unsigned.
472
- */
473
- const provenanceAt = async (name: string, dist: Dist | undefined): Promise<ProvenanceResult> => {
474
- if (!dist?.tarball) return { state: 'unsigned' }
475
- const dir = mkdtempSync(join(tmpdir(), 'crombolo-bundle-check-'))
476
- try {
477
- const response = await call(dist.tarball)
478
- if (!response.ok)
479
- return {
480
- state: 'unchecked',
481
- reason: `${name} could not be fetched to check its signature (the registry answered ${response.status})`,
482
- }
483
- const bytes = new Uint8Array(await response.arrayBuffer())
484
- if (dist.integrity?.startsWith('sha512-')) {
485
- const got = `sha512-${new Bun.CryptoHasher('sha512').update(bytes).digest('base64')}`
486
- if (got !== dist.integrity)
487
- return { state: 'invalid', reason: `${name} is not the package the registry describes` }
488
- }
489
- const file = join(dir, 'bundle.tgz')
490
- await Bun.write(file, bytes)
491
- const unpacked = join(dir, 'package')
492
- await extractTarball(file, unpacked)
493
- return await verify(unpacked)
494
- } catch (error) {
495
- return {
496
- state: 'unchecked',
497
- reason: `${name} could not be checked: ${error instanceof Error ? error.message : String(error)}`,
498
- }
499
- } finally {
500
- rmSync(dir, { recursive: true, force: true })
501
- }
502
- }
340
+ const provenanceAt = (name: string, dist: Parameters<typeof provenanceAtRegistry>[1]) =>
341
+ provenanceAtRegistry(name, dist, { fetch: call, verify })
503
342
 
504
343
  /** Why the site's policy refuses a version, as an outcome, or undefined when it may be installed. */
505
344
  const refusedBySignature = (
506
345
  label: string,
507
346
  provenance: ProvenanceResult,
508
347
  ): InstallOutcome | undefined => {
509
- const problem = provenanceProblem(
348
+ const message = signatureRefusal(label, provenance, options.policy)
349
+ return message ? { ok: false, message, provenance } : undefined
350
+ }
351
+
352
+ /** Why the person may not grant what it asks for here: its level, by who they are and its signature (story 324). */
353
+ const levelRefused = (
354
+ name: string,
355
+ asked: readonly DeclaredPermission[],
356
+ provenance: ProvenanceResult,
357
+ request: { isAdmin?: boolean; grant?: readonly string[] },
358
+ ): InstallOutcome | undefined => {
359
+ const level = levelOf(asked.map((entry) => entry.permission))
360
+ const why = grantRefusal({
361
+ level,
362
+ grants: asked.length > 0,
363
+ isAdmin: request.isAdmin === true,
510
364
  provenance,
511
- options.policy ?? { signatures: 'optional', sources: [] },
512
- )
513
- return problem
514
- ? { ok: false, message: `${label} was not installed: ${problem}.`, provenance }
365
+ from: options.unrestrictedFrom ?? 'backoffice',
366
+ })
367
+ return why
368
+ ? { ok: false, level, message: `${name} was not installed: ${why}`, provenance }
515
369
  : undefined
516
370
  }
517
371
 
518
372
  /** Each installed version's signature, checked once: a version's files do not change. */
519
373
  const installedProvenance = new Map<string, Promise<ProvenanceResult>>()
520
374
  const provenanceOfInstalled = async (bundle: BundlePackage): Promise<ProvenanceResult> => {
375
+ // Installed from a path or a workspace into its root, as a developer's own is (story 326).
376
+ if (bundle.root && readRecord(options.siteDir)[bundle.id]?.linked) return { state: 'local' }
521
377
  const range = await rangeFor(bundle.packageName)
522
378
  if (range && /^(workspace|link|file|portal):/.test(range)) return { state: 'local' }
523
379
  const key = `${bundle.packageName}@${bundle.version}`
@@ -539,7 +395,14 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
539
395
  const declares = async (name: string): Promise<BundlePackage['carries'] | undefined> => {
540
396
  const declared = await declaresAt(name)
541
397
  if (typeof declared === 'string' || 'refused' in declared) return undefined
542
- const { permissions: _, version: _version, dist: _dist, ...carries } = declared
398
+ const {
399
+ permissions: _,
400
+ version: _version,
401
+ dist: _dist,
402
+ id: _id,
403
+ screens: _screens,
404
+ ...carries
405
+ } = declared
543
406
  return carries
544
407
  }
545
408
 
@@ -549,7 +412,16 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
549
412
  schema3: isSchema3(bundle),
550
413
  ...grantStateOf(bundle),
551
414
  })
552
- const grantStateOf = (bundle: BundlePackage) => {
415
+ const grantStateOf = (bundle: BundlePackage) => ({
416
+ ...grantRows(bundle),
417
+ // How far it reaches, and what it reached when granted, for Installed's badge (story 324).
418
+ level: levelOf(declaredEntries(bundle).map((entry) => entry.permission)),
419
+ groups: groupsOf(declaredEntries(bundle), { screens: screensOf(bundle.field) }),
420
+ ...(options.grants?.state(bundle).grant?.recorded
421
+ ? { grantedLevel: levelOf(options.grants.state(bundle).grant?.permissions ?? []) }
422
+ : {}),
423
+ })
424
+ const grantRows = (bundle: BundlePackage) => {
553
425
  const declared = describePermissions(declaredEntries(bundle))
554
426
  if (!options.grants)
555
427
  return { permissions: declared, on: true, status: 'on', missing: [], disabledBy: null }
@@ -560,7 +432,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
560
432
  on: state.on,
561
433
  status: state.status,
562
434
  missing: state.missing,
563
- asksActAs: declaredEntries(bundle).some((entry) => entry.permission === 'actAs'),
435
+ delegates: declaredEntries(bundle).some((entry) => entry.permission === USER_DELEGATE),
564
436
  disabledBy: state.disabledBy,
565
437
  ...(state.grant?.grantedBy
566
438
  ? {
@@ -688,10 +560,15 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
688
560
  message: `${name} is not an extension this site takes, so it was not installed: ${declared.refused.join('; ')}.`,
689
561
  }
690
562
  if (!consented(request, declared.permissions))
691
- return grantNeeded(name, declared.permissions, '', layoutChoice(declared.layout))
563
+ return grantNeeded(name, declared.permissions, '', layoutChoice(declared.layout), {
564
+ id: declared.id,
565
+ screens: declared.screens,
566
+ })
692
567
  const provenance = await provenanceAt(name, declared.dist)
693
568
  const refused = refusedBySignature(`${name}@${declared.version}`, provenance)
694
569
  if (refused) return refused
570
+ const beyond = levelRefused(name, declared.permissions, provenance, request)
571
+ if (beyond) return beyond
695
572
  // Pinned to the version whose tarball was checked, when one was.
696
573
  const outcome = await added(
697
574
  name,
@@ -699,6 +576,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
699
576
  version,
700
577
  request,
701
578
  declared.dist?.tarball ? { version: declared.version } : undefined,
579
+ { id: declared.id ?? name, integrity: declared.dist?.integrity },
702
580
  )
703
581
  return { ...outcome, provenance }
704
582
  },
@@ -735,7 +613,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
735
613
  return grantNeeded(declared.name, declared.permissions, '', layoutChoice(declared.layout))
736
614
  // Kept in the site's bundles/ (story 245), so it is committed and every
737
615
  // node, checkout and CI build installs the same file.
738
- const kept = keepInSite(file, declared)
616
+ const kept = keepInSite(options.siteDir, file, declared)
739
617
  if (typeof kept === 'string') return { ok: false, message: kept }
740
618
  const discard = () => {
741
619
  if (kept.copied) rmSync(join(options.siteDir, kept.path), { force: true })
@@ -746,13 +624,17 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
746
624
  reason: error instanceof Error ? error.message : String(error),
747
625
  }),
748
626
  )
749
- const refused = refusedBySignature(declared.name, provenance)
627
+ const refused =
628
+ refusedBySignature(declared.name, provenance) ??
629
+ levelRefused(declared.name, declared.permissions, provenance, request)
750
630
  if (refused) {
751
631
  discard()
752
632
  return refused
753
633
  }
754
634
  const previous = await rangeFor(declared.name)
755
- const outcome = await added(declared.name, `./${kept.path}`, undefined, request)
635
+ const outcome = await added(declared.name, `./${kept.path}`, undefined, request, undefined, {
636
+ id: declared.id,
637
+ })
756
638
  if (!outcome.ok) {
757
639
  discard()
758
640
  return { ...outcome, provenance }
@@ -762,7 +644,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
762
644
  ...outcome,
763
645
  provenance,
764
646
  file: kept.path,
765
- message: `${outcome.message} Commit ${kept.path} with package.json and bun.lock.`,
647
+ message: `${outcome.message} Commit ${kept.path} with it.`,
766
648
  }
767
649
  },
768
650
 
@@ -770,6 +652,22 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
770
652
  if (options.installs === false) return refusedHere(name, 'remove', options.installsElsewhere)
771
653
  if (!isValidPackageName(name))
772
654
  return { ok: false, message: `'${name}' is not a package name npm would accept.` }
655
+ // Story 326: removing one is deleting its root and its line.
656
+ const recorded = Object.entries(readRecord(options.siteDir)).find(
657
+ ([, line]) => line.name === name,
658
+ )
659
+ if (recorded) {
660
+ const [id] = recorded
661
+ const previous = await rangeFor(name)
662
+ rmSync(rootOf(options.siteDir, id), { recursive: true, force: true })
663
+ forgetExtension(options.siteDir, id)
664
+ options.extensions.invalidate()
665
+ removeUnnamed(previous)
666
+ return {
667
+ ok: true,
668
+ message: `${name} was removed. Commit the removal of ${ROOTS_DIR}/${id}/ and the change to ${RECORD_FILE}.`,
669
+ }
670
+ }
773
671
  const previous = await rangeFor(name)
774
672
  const result = await install('remove', name, options.siteDir)
775
673
  options.extensions.invalidate()
@@ -791,18 +689,23 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
791
689
  request: {
792
690
  applyContent?: boolean
793
691
  grant?: readonly string[]
794
- actAs?: string | null
692
+ delegateTo?: string | null
795
693
  by?: string | null
694
+ /** The person installing is an administrator: only one grants the upper levels (story 324). */
695
+ isAdmin?: boolean
796
696
  },
797
- checked?: { version: string },
697
+ checked: { version: string } | undefined,
698
+ into: { id: string; integrity?: string },
798
699
  ): Promise<InstallOutcome> {
799
- const result = await install('add', specifier, options.siteDir)
700
+ // Story 326: into a root of its own, never the site's dependencies.
701
+ const installed = await installIntoRoot(
702
+ options.siteDir,
703
+ { id: into.id, name, specifier, version, integrity: into.integrity },
704
+ install,
705
+ )
800
706
  options.extensions.invalidate()
801
- if (!result.ok)
802
- return {
803
- ok: false,
804
- message: result.output || `Installing ${specifier} failed.`,
805
- }
707
+ if (!installed.ok) return { ok: false, message: installed.message }
708
+ const undo = installed.undo
806
709
 
807
710
  const range = (await rangeFor(name)) ?? version ?? 'latest'
808
711
  const discovered = options.extensions.bundles()
@@ -814,7 +717,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
814
717
  problem.packageName === name && problem.problems.includes(SITE_PACKAGE_NOT_INSTALLED),
815
718
  )
816
719
  ) {
817
- await install('remove', name, options.siteDir)
720
+ undo()
818
721
  options.extensions.invalidate()
819
722
  return sitePackageRefused(name)
820
723
  }
@@ -827,7 +730,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
827
730
  // The version whose signature was checked is the one that has to land
828
731
  // (story 060): one published in between was never checked.
829
732
  if (checked && found.version !== checked.version) {
830
- await install('remove', name, options.siteDir)
733
+ undo()
831
734
  options.extensions.invalidate()
832
735
  return {
833
736
  ok: false,
@@ -837,12 +740,12 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
837
740
  // The version that landed is what counts: a release published between
838
741
  // reading the registry and installing may ask for more, or say nothing of why.
839
742
  if (isSchema3(found)) {
840
- await install('remove', name, options.siteDir)
743
+ undo()
841
744
  options.extensions.invalidate()
842
745
  return schema3Refused(name, `${name}@${found.version} turned out to`)
843
746
  }
844
747
  if (!consented(request, declaredEntries(found))) {
845
- await install('remove', name, options.siteDir)
748
+ undo()
846
749
  options.extensions.invalidate()
847
750
  return grantNeeded(
848
751
  name,
@@ -853,7 +756,15 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
853
756
  }
854
757
  // What was granted is recorded against the version that landed, for every
855
758
  // extension: a grant is what lets one run (story 309).
856
- await options.grants?.grant(found, request.by ?? null, { actAs: request.actAs ?? null })
759
+ const delegates = declaredPermissions(found).includes(USER_DELEGATE)
760
+ if (delegates && !request.delegateTo) {
761
+ undo()
762
+ options.extensions.invalidate()
763
+ return { ok: false, message: `${name} was not installed: ${DELEGATE_NEEDS_PERSON}.` }
764
+ }
765
+ await options.grants?.grant(found, request.by ?? null, {
766
+ delegateKey: delegates ? request.delegateTo : null,
767
+ })
857
768
 
858
769
  // The content half lands after the dependency, so a refused check leaves
859
770
  // the package installed and says why, rather than undoing an install that
@@ -877,7 +788,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
877
788
  dependency: { name, range, version: found.version },
878
789
  // The install lives in this node's node_modules until the dependency is
879
790
  // committed; saying so is the difference between a surprise and a plan.
880
- message: `${name}@${found.version} is installed. Commit the changed package.json and bun.lock to keep it across deployments.${
791
+ message: `${name}@${found.version} is installed. Commit ${ROOTS_DIR}/${into.id}/ and ${RECORD_FILE} to keep it across deployments.${
881
792
  found.carries.server
882
793
  ? " Its server code runs only once your site's developers turn it on and deploy the site."
883
794
  : ''
@@ -887,51 +798,6 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
887
798
  }
888
799
  }
889
800
 
890
- /** A site package offered as a dependency: refused, saying how one is used (story 306). */
891
- function sitePackageRefused(name: string): { ok: false; message: string } {
892
- return {
893
- ok: false,
894
- message: `${name} is a site package, which is applied to a site with \`crombolo site apply\`, never installed, so it was not installed.`,
895
- }
896
- }
897
-
898
- /** What a packed bundle on this machine declares, read from its package.json, or why it cannot be installed. */
899
- async function declaresIn(file: string): Promise<
900
- | {
901
- name: string
902
- version: string
903
- server: boolean
904
- permissions: DeclaredPermission[]
905
- layout?: AskedLayout
906
- }
907
- | string
908
- > {
909
- const dir = mkdtempSync(join(tmpdir(), 'crombolo-bundle-file-'))
910
- try {
911
- await extractTarball(file, dir)
912
- const root = existsSync(join(dir, 'package', 'package.json')) ? join(dir, 'package') : dir
913
- const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as PackageJson
914
- if ((json.crombolo as { bundleType?: unknown } | undefined)?.bundleType === 'site')
915
- return sitePackageRefused(file).message
916
- const problems = validateBundlePackage(json)
917
- if (problems.length > 0 || typeof json.name !== 'string' || typeof json.version !== 'string')
918
- return `${file} is not an extension for this site, so it was not installed.`
919
- const field = json.crombolo as { server?: string; permissions?: unknown; settings?: unknown }
920
- if (isSchema3Field(field)) return `${file} was not installed: ${SCHEMA_3_NOT_INSTALLED}.`
921
- return {
922
- name: json.name,
923
- version: json.version,
924
- server: field.server !== undefined,
925
- permissions: askedPermissions(field),
926
- layout: layoutAsked(field),
927
- }
928
- } catch {
929
- return `${file} could not be read as a packed bundle, so it was not installed.`
930
- } finally {
931
- rmSync(dir, { recursive: true, force: true })
932
- }
933
- }
934
-
935
801
  /** A package's own description, read leniently: anything unreadable is none. */
936
802
  /** Who made an installed package, as its `author` says: npm's publisher is not kept with it. */
937
803
  function authorOf(directory: string): string | null {
@@ -970,16 +836,15 @@ export const SCREENS_NOTICE = 'Its screens run in the browser of everyone who us
970
836
  /**
971
837
  * Whether an install request granted exactly what the extension asks for
972
838
  * (stories 222, 308): all of it, nothing it did not ask, and whom it acts for
973
- * when it asks for `actAs`. One that asks for nothing needs no grant.
839
+ * One that asks for nothing needs no grant.
974
840
  */
975
841
  function consented(
976
- request: { grant?: readonly string[]; actAs?: string | null },
842
+ request: { grant?: readonly string[] },
977
843
  asked: readonly DeclaredPermission[],
978
844
  ): boolean {
979
845
  const permissions = asked.map((entry) => entry.permission)
980
846
  if (permissions.length === 0) return true
981
847
  const granted = new Set(request.grant ?? [])
982
- if (permissions.includes('actAs') && !request.actAs) return false
983
848
  return granted.size === new Set(permissions).size && permissions.every((p) => granted.has(p))
984
849
  }
985
850
 
@@ -989,12 +854,16 @@ function grantNeeded(
989
854
  asked: readonly DeclaredPermission[],
990
855
  before = '',
991
856
  layout?: InstallOutcome['layout'],
857
+ about: { id?: string; screens?: number } = {},
992
858
  ): InstallOutcome {
993
859
  return {
994
860
  ok: false,
995
861
  needsGrant: true,
996
862
  permissions: describePermissions(asked),
997
- asksActAs: asked.some((entry) => entry.permission === 'actAs'),
863
+ level: levelOf(asked.map((entry) => entry.permission)),
864
+ groups: groupsOf(asked, { screens: about.screens }),
865
+ ...(about.id ? { id: about.id } : {}),
866
+ delegates: asked.some((entry) => entry.permission === USER_DELEGATE),
998
867
  ...(layout ? { layout } : {}),
999
868
  message: `${before ? `${before} ` : ''}${name} asks for these permissions. Grant them, each as it asks, to install it.`,
1000
869
  }