@crombolo/server 0.56.0 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.56.0",
3
+ "version": "0.57.0",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -31,18 +31,19 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.56.0",
35
- "@crombolo/api-management": "0.56.0",
36
- "@crombolo/auth": "0.56.0",
37
- "@crombolo/backoffice-host": "0.56.0",
38
- "@crombolo/common": "0.56.0",
39
- "@crombolo/content": "0.56.0",
40
- "@crombolo/contracts": "0.56.0",
41
- "@crombolo/core": "0.56.0",
42
- "@crombolo/data": "0.56.0",
43
- "@crombolo/render": "0.56.0",
44
- "@crombolo/schema": "0.56.0",
45
- "@crombolo/transfer": "0.56.0",
34
+ "@crombolo/api-delivery": "0.57.0",
35
+ "@crombolo/api-management": "0.57.0",
36
+ "@crombolo/auth": "0.57.0",
37
+ "@crombolo/backoffice-host": "0.57.0",
38
+ "@crombolo/common": "0.57.0",
39
+ "@crombolo/content": "0.57.0",
40
+ "@crombolo/contracts": "0.57.0",
41
+ "@crombolo/core": "0.57.0",
42
+ "@crombolo/data": "0.57.0",
43
+ "@crombolo/extension": "0.57.0",
44
+ "@crombolo/render": "0.57.0",
45
+ "@crombolo/schema": "0.57.0",
46
+ "@crombolo/transfer": "0.57.0",
46
47
  "@logtape/logtape": "^2.3.8",
47
48
  "@opentelemetry/api": "1.10.0",
48
49
  "@opentelemetry/context-async-hooks": "3.0.0",
@@ -62,7 +63,9 @@
62
63
  "@sigstore/protobuf-specs": "^0.4.3",
63
64
  "@sigstore/tuf": "^3.1.1",
64
65
  "@sigstore/verify": "^2.1.1",
66
+ "deno": "2.9.6",
65
67
  "jose": "^6.2.12",
68
+ "kysely": "0.29.6",
66
69
  "sigstore": "^3.1.0"
67
70
  }
68
71
  }
@@ -20,6 +20,7 @@ import {
20
20
  import { ObjectTypes, type Page } from '@crombolo/core'
21
21
  import {
22
22
  type Bundle,
23
+ type BundleDefinitionKind,
23
24
  BundleRepository,
24
25
  type BundleSchemaPicks,
25
26
  type ComponentFileStore,
@@ -42,12 +43,16 @@ import {
42
43
  writeBundle,
43
44
  writeBundlePackage,
44
45
  } from '@crombolo/transfer'
45
- import { VERSION } from '../config.ts'
46
- import { readBlobs } from '../media-files.ts'
46
+ import { type CromboloConfig, VERSION } from '../config.ts'
47
+ import { createdExtension } from '../created-extension.ts'
48
+ import { mediaStoreFor, readBlobs } from '../media-files.ts'
47
49
  import type { MediaStore } from '../media-store.ts'
48
50
  import { carriedPicks, schemaPickFiles } from '../schema-picks.ts'
49
51
  import { siteSections } from '../site-sections.ts'
52
+ import { signedWithSiteKey } from '../site-trust.ts'
50
53
  import { writeNpmTarball } from '../tar.ts'
54
+ import { createComponentsPort, createFileSystemPort } from './file-system.ts'
55
+ import { createTemplateFileStore } from './template-files.ts'
51
56
 
52
57
  /** The npm package a definition is built as: what was set on it, or what its name gives. */
53
58
  export function bundlePackageOf(row: Bundle): { name: string; version: string } {
@@ -62,6 +67,8 @@ const CONTENT_OBJECT_TYPES = [ObjectTypes.Document, ObjectTypes.Media, ObjectTyp
62
67
 
63
68
  export interface PackagePortOptions {
64
69
  siteName: string
70
+ /** Seals this site's signing key, which signs a site bundle it builds (story 316). */
71
+ secretKey?: string
65
72
  nodeId: string
66
73
  marketplaceUrl: string
67
74
  /** Reads a template's view, which lives on disk rather than in the row. */
@@ -343,13 +350,33 @@ export function createPackagePort(db: Db, options: PackagePortOptions): PackageP
343
350
 
344
351
  const labelled: ContentSet = { ...set, manifest: { ...set.manifest, label: from.name } }
345
352
  const encoder = new TextEncoder()
346
- const files = writeBundlePackage(writeBundle(labelled, content.blobs, sections), {
353
+ const bundleId = bundleIdFor(pkg.name.replace(/^@[^/]+\//, ''))
354
+ const info = {
347
355
  name: pkg.name,
348
356
  version: pkg.version,
349
- id: bundleIdFor(pkg.name.replace(/^@[^/]+\//, '')),
357
+ id: bundleId,
350
358
  label: from.name,
351
359
  peerRange: bundlePeerRange(VERSION),
352
- })
360
+ }
361
+ // Story 312: a site bundle moves this site, its components and all, as a
362
+ // site package; an extension's picked components are its code.
363
+ const files =
364
+ row.kind === 'site'
365
+ ? await signedWithSiteKey(
366
+ db,
367
+ { secretKey: options.secretKey, siteName: options.siteName },
368
+ writeBundlePackage(
369
+ writeBundle(labelled, content.blobs, sections, { bundleType: 'site' }),
370
+ { ...info, bundleType: 'site', private: true },
371
+ ),
372
+ )
373
+ : (() => {
374
+ const built = createdExtension(bundleId, sections, labelled)
375
+ return writeBundlePackage(
376
+ writeBundle(built.set, content.blobs, built.payload, { bundleType: 'extension' }),
377
+ { ...info, bundleType: 'extension', ...(built.code ? { code: built.code } : {}) },
378
+ )
379
+ })()
353
380
  const entries = files.map((file) => ({
354
381
  path: file.path,
355
382
  bytes: file.bytes ?? encoder.encode(file.text ?? ''),
@@ -367,6 +394,8 @@ export function createPackagePort(db: Db, options: PackagePortOptions): PackageP
367
394
  export interface CreatedBundlePackage {
368
395
  name: string
369
396
  version: string
397
+ /** What it builds (story 312): an extension for other sites, or a site bundle to move this site. */
398
+ kind: BundleDefinitionKind
370
399
  /** Whether each was set, rather than derived from the definition's name. */
371
400
  set: { name: boolean; version: boolean }
372
401
  }
@@ -382,6 +411,7 @@ export async function readCreatedBundlePackage(
382
411
  if (!row) return undefined
383
412
  return {
384
413
  ...bundlePackageOf(row),
414
+ kind: row.kind,
385
415
  set: { name: row.packageName !== null, version: row.packageVersion !== null },
386
416
  }
387
417
  }
@@ -393,7 +423,7 @@ export async function readCreatedBundlePackage(
393
423
  export async function writeCreatedBundlePackage(
394
424
  db: Db,
395
425
  id: string,
396
- input: { name?: unknown; version?: unknown },
426
+ input: { name?: unknown; version?: unknown; kind?: unknown },
397
427
  ): Promise<{ ok: true; package: CreatedBundlePackage } | { ok: false; message: string }> {
398
428
  const bundles = new BundleRepository(db)
399
429
  if (!(await bundles.byId(id))) return { ok: false, message: 'That bundle no longer exists.' }
@@ -408,7 +438,10 @@ export async function writeCreatedBundlePackage(
408
438
  }
409
439
  if (version && !SEMVER.test(version))
410
440
  return { ok: false, message: 'A version is three numbers, like 1.0.0.' }
441
+ if (input.kind !== undefined && input.kind !== 'extension' && input.kind !== 'site')
442
+ return { ok: false, message: 'A bundle is an extension for other sites, or a site bundle.' }
411
443
  await bundles.setPackage(id, { name: name || null, version: version || null })
444
+ if (input.kind !== undefined) await bundles.setKind(id, input.kind)
412
445
  return { ok: true, package: (await readCreatedBundlePackage(db, id)) as CreatedBundlePackage }
413
446
  }
414
447
 
@@ -466,3 +499,36 @@ export async function writeSchemaPicks(
466
499
  const picks = schemaPicksOf(body)
467
500
  return (await new BundleRepository(db).setSchemaPicks(id, picks)) ? picks : undefined
468
501
  }
502
+
503
+ /**
504
+ * A Bundle Editor definition built as the extension package the back office's
505
+ * download gives (story 306), found by its name or its id; undefined when there
506
+ * is no such definition. For `crombolo extension build`.
507
+ */
508
+ export async function buildCreatedBundle(
509
+ db: Db,
510
+ config: CromboloConfig,
511
+ nameOrId: string,
512
+ options: { withMedia?: boolean } = {},
513
+ ): Promise<{ definition: PackageDefinition; built: BuiltPackage } | undefined> {
514
+ const port = createPackagePort(db, {
515
+ siteName: config.siteName,
516
+ secretKey: config.secretKey,
517
+ nodeId: config.nodeId,
518
+ marketplaceUrl: config.marketplaceUrl,
519
+ componentFiles: createTemplateFileStore(config.componentsDir),
520
+ mediaStore: await mediaStoreFor(config),
521
+ components: createComponentsPort(config.componentsDir),
522
+ stylesheets: createFileSystemPort(config.stylesheetsDir, { extension: '.css' }),
523
+ scripts: createFileSystemPort(config.scriptsDir, { extension: '.js' }),
524
+ schemaDir: config.schemaDir,
525
+ })
526
+ const wanted = nameOrId.trim().toLowerCase()
527
+ const definitions = (await port.list({ skip: 0, take: 10_000 })).items
528
+ const definition = definitions.find(
529
+ (candidate) => candidate.id.toLowerCase() === wanted || candidate.name.toLowerCase() === wanted,
530
+ )
531
+ if (!definition) return undefined
532
+ const built = await port.build(definition.id, options)
533
+ return built ? { definition, built } : undefined
534
+ }
@@ -114,7 +114,7 @@ const GROUPS: HealthCheckGroup[] = [
114
114
  {
115
115
  ...CHECKS.code,
116
116
  description:
117
- 'Who may install code on this site, and whether installed code is waiting for a restart.',
117
+ 'Who may install code on this site, whether installed code is waiting for a restart, and which installed extensions cannot be used.',
118
118
  },
119
119
  ],
120
120
  },
@@ -199,6 +199,12 @@ export interface HealthCheckOptions {
199
199
  siteSettingsFindings?: () => Promise<
200
200
  Array<{ kind: 'second' | 'deep'; name: string; counted?: string }>
201
201
  >
202
+ /** Dependencies that claim to be bundles and are not usable ones, and why (story 306). */
203
+ bundleProblems?: () => Array<{ packageName: string; problems: string[]; untyped?: unknown }>
204
+ /** Granted extensions that could not start, and why (story 311). */
205
+ failedExtensions?: () => readonly { id: string; reason: string }[]
206
+ /** Extensions whose `layout` setting names a layout the site no longer has (story 312). */
207
+ lostLayouts?: () => readonly { id: string; layout: string }[]
202
208
  }
203
209
 
204
210
  const result = (
@@ -447,6 +453,29 @@ export function createDiagnosticsPort(options: HealthCheckOptions): DiagnosticsP
447
453
  )
448
454
  if (results.length === 0)
449
455
  results.push(result('Success', 'Nobody may install code on this site.'))
456
+ for (const found of options.bundleProblems?.() ?? [])
457
+ results.push(
458
+ result(
459
+ 'Warning',
460
+ found.untyped
461
+ ? `${found.packageName} is turned off: it does not say it is an extension. Install a version that does.`
462
+ : `${found.packageName} is not used: ${found.problems.join('; ')}.`,
463
+ ),
464
+ )
465
+ for (const lost of options.lostLayouts?.() ?? [])
466
+ results.push(
467
+ result(
468
+ 'Warning',
469
+ `The extension ${lost.id}'s layout setting names "${lost.layout}", which the site no longer has, so its pages render on their own. Choose another in Bundles → Installed.`,
470
+ ),
471
+ )
472
+ for (const failed of options.failedExtensions?.() ?? [])
473
+ results.push(
474
+ result(
475
+ 'Warning',
476
+ `The extension ${failed.id} is granted but could not start: ${failed.reason}`,
477
+ ),
478
+ )
450
479
  const pending = restartPending(config.siteDir)
451
480
  if (pending)
452
481
  results.push(
@@ -3,12 +3,20 @@
3
3
  * uninstall, disable and enable, each audited. One implementation behind
4
4
  * Settings → Bundles, the remote protocol and the CLI on the site's own machine.
5
5
  */
6
- import type { ExtensionRegistry } from '@crombolo/backoffice-host'
7
- import { createExtensionRegistry } from '@crombolo/backoffice-host/registry'
8
- import { type Db, TransferRunRepository } from '@crombolo/data'
6
+ import type { BundlePackage, ExtensionRegistry } from '@crombolo/backoffice-host'
7
+ import {
8
+ createExtensionRegistry,
9
+ type ExtensionSetting,
10
+ readSettings,
11
+ settingValueProblem,
12
+ } from '@crombolo/backoffice-host/registry'
13
+ import { type Db, ExtensionSettingRepository, TransferRunRepository } from '@crombolo/data'
14
+ import { revertRun } from '@crombolo/transfer'
9
15
  import { recordAudit } from './adapters/audit.ts'
10
- import { type BundleGrants, createBundleGrants } from './bundle-grants.ts'
11
- import { CommandError, installBundleContent } from './bundle-install.ts'
16
+ import { type BundleGrants, createBundleGrants, declaredPermissions } from './bundle-grants.ts'
17
+ import { CommandError, installBundleContent, revertSections } from './bundle-install.ts'
18
+ import { componentsWritten } from './bundle-sections.ts'
19
+ import { siteLayouts } from './components.ts'
12
20
  import type { CromboloConfig } from './config.ts'
13
21
  import {
14
22
  createMarketplace,
@@ -19,6 +27,8 @@ import {
19
27
  } from './marketplace.ts'
20
28
  import { describeProvenance, type ProvenancePolicy } from './provenance.ts'
21
29
  import { markRestartPending, type RestartPending, restartPending } from './restart-pending.ts'
30
+ import { sealSecret } from './secrets.ts'
31
+ import { MASKED } from './webhooks.ts'
22
32
 
23
33
  /** Who acted, and from where, for the audit log. */
24
34
  export interface BundleActor {
@@ -37,17 +47,38 @@ export interface InstalledBundles {
37
47
  restartPending: RestartPending | null
38
48
  /** What this site takes of a bundle's signature (story 060). */
39
49
  policy: ProvenancePolicy
40
- items: InstalledListing[]
50
+ items: (InstalledListing & {
51
+ settings?: SettingView[]
52
+ couldNotStart?: string
53
+ /** Components an earlier install copied into the site's `components/`, to review (story 312). */
54
+ copiedComponents?: string[]
55
+ })[]
56
+ }
57
+
58
+ /** A setting as Installed shows it (story 310): its value, masked when secret, and whether the config locks it. */
59
+ export interface SettingView extends ExtensionSetting {
60
+ key: string
61
+ value: unknown
62
+ locked: boolean
41
63
  }
42
64
 
65
+ /** Settings sent with an install, as a request carries them: an object, or nothing. */
66
+ export const settingsIn = (value: unknown): Record<string, unknown> | undefined =>
67
+ value && typeof value === 'object' && !Array.isArray(value)
68
+ ? (value as Record<string, unknown>)
69
+ : undefined
70
+
43
71
  export interface InstallRequest {
44
72
  /** A package name, or with `file` a packed bundle on this machine. */
45
73
  name: string
46
74
  version?: string
47
75
  file?: boolean
48
76
  applyContent?: boolean
49
- acceptServerCode?: boolean
50
77
  grant?: readonly string[]
78
+ /** Whom it acts for, when it asks for `actAs` (story 308). */
79
+ actAs?: string | null
80
+ /** Its settings' values, saved once it is installed: the layout picked for it (story 312). */
81
+ settings?: Readonly<Record<string, unknown>>
51
82
  }
52
83
 
53
84
  export interface SwitchOutcome {
@@ -62,9 +93,33 @@ export interface BundleAdmin {
62
93
  /** What installing a version would bring, with nothing installed. */
63
94
  inspect: Marketplace['inspect']
64
95
  install(actor: BundleActor, request: InstallRequest): Promise<InstallOutcome>
65
- uninstall(actor: BundleActor, name: string): Promise<InstallOutcome>
96
+ /** `revertContent` first puts back the content its install applied (story 306). */
97
+ uninstall(
98
+ actor: BundleActor,
99
+ name: string,
100
+ options?: { revertContent?: boolean },
101
+ ): Promise<InstallOutcome>
66
102
  /** Turns a bundle's server features off or on; `id` is its bundle id or its package name. */
67
103
  setEnabled(actor: BundleActor, id: string, enabled: boolean): Promise<SwitchOutcome>
104
+ /**
105
+ * Sets an extension's settings (story 310): those the config does not lock;
106
+ * `null` takes one back to its default, and a secret's mask keeps what is stored.
107
+ */
108
+ setSettings(
109
+ actor: BundleActor,
110
+ id: string,
111
+ values: Readonly<Record<string, unknown>>,
112
+ ): Promise<SwitchOutcome>
113
+ /**
114
+ * Grants an installed extension exactly what its installed version asks for
115
+ * (story 309), naming whom `actAs` acts for when it asks to; refused, saying
116
+ * what differs, otherwise.
117
+ */
118
+ grant(
119
+ actor: BundleActor,
120
+ id: string,
121
+ request: { grant: readonly string[]; actAs?: string | null },
122
+ ): Promise<SwitchOutcome>
68
123
  }
69
124
 
70
125
  /** What restarting will make live, said after an install that changed code. */
@@ -75,7 +130,9 @@ export function createBundleAdmin(options: {
75
130
  config: CromboloConfig
76
131
  marketplace: Marketplace
77
132
  extensions: Pick<ExtensionRegistry, 'bundles'>
78
- bundleGrants: Pick<BundleGrants, 'disable' | 'enable'>
133
+ bundleGrants: Pick<BundleGrants, 'disable' | 'enable' | 'grant' | 'state'>
134
+ /** Granted extensions that could not start, and why (story 311). */
135
+ failed?: () => readonly { id: string; reason: string }[]
79
136
  }): BundleAdmin {
80
137
  const { db, config, marketplace, extensions, bundleGrants } = options
81
138
  const audit = (actor: BundleActor, action: string, entityName: string, detail: string | null) =>
@@ -94,6 +151,35 @@ export function createBundleAdmin(options: {
94
151
  const find = (name: string) =>
95
152
  extensions.bundles().bundles.find((bundle) => bundle.packageName === name || bundle.id === name)
96
153
 
154
+ /** Each setting with its value, and whether the config locks it; a secret's value masked. */
155
+ const settingsView = async (pkg: BundlePackage) => {
156
+ const declared = readSettings(pkg.field.settings)
157
+ if (!('settings' in declared)) return []
158
+ const stored = await new ExtensionSettingRepository(db).of(pkg.id).catch(() => ({}))
159
+ const locked = config.extensions?.[pkg.id]?.settings ?? {}
160
+ const layouts = siteLayouts(config.componentsDir)
161
+ return Object.entries(declared.settings).map(([key, setting]) => {
162
+ const given =
163
+ key in locked
164
+ ? locked[key]
165
+ : key in stored
166
+ ? (stored as Record<string, unknown>)[key]
167
+ : setting.default
168
+ // A layout it suggests that the site has not got is no choice at all.
169
+ const value =
170
+ setting.type === 'layout' && typeof given === 'string' && !layouts.includes(given)
171
+ ? undefined
172
+ : given
173
+ return {
174
+ key,
175
+ ...setting,
176
+ ...(setting.type === 'layout' ? { values: layouts } : {}),
177
+ value: setting.secret && value !== undefined ? MASKED : (value ?? null),
178
+ locked: key in locked,
179
+ }
180
+ })
181
+ }
182
+
97
183
  return {
98
184
  inspect: (name, version) => marketplace.inspect(name, version),
99
185
 
@@ -103,15 +189,90 @@ export function createBundleAdmin(options: {
103
189
  installsElsewhere: config.runtimeInstalls ? null : (config.installsElsewhere ?? null),
104
190
  restartPending: restartPending(config.siteDir) ?? null,
105
191
  policy: config.bundlePolicy,
106
- items: await marketplace.installed(),
192
+ items: await Promise.all(
193
+ (await marketplace.installed()).map(async (item) => {
194
+ const pkg = find(item.packageName)
195
+ if (!pkg) return item
196
+ const failed = options.failed?.().find((candidate) => candidate.id === pkg.id)
197
+ const run =
198
+ pkg.bundleType === 'extension'
199
+ ? await new TransferRunRepository(db)
200
+ .appliedForPackage(pkg.packageName)
201
+ .catch(() => undefined)
202
+ : undefined
203
+ const copied = run ? componentsWritten(config, run.id) : []
204
+ return {
205
+ ...item,
206
+ settings: await settingsView(pkg),
207
+ ...(failed ? { couldNotStart: failed.reason } : {}),
208
+ ...(copied.length > 0 ? { copiedComponents: copied } : {}),
209
+ }
210
+ }),
211
+ ),
212
+ }
213
+ },
214
+
215
+ async setSettings(actor, id, values) {
216
+ const pkg = find(id)
217
+ if (!pkg)
218
+ return { status: 404, ok: false, message: `No installed extension is called "${id}".` }
219
+ const declared = readSettings(pkg.field.settings)
220
+ const settings = 'settings' in declared ? declared.settings : {}
221
+ const locked = config.extensions?.[pkg.id]?.settings ?? {}
222
+ const problems: string[] = []
223
+ for (const [key, value] of Object.entries(values)) {
224
+ const setting = settings[key]
225
+ if (!setting) problems.push(`${pkg.name} has no setting "${key}"`)
226
+ else if (key in locked) problems.push(`${setting.label} is set in the site's config`)
227
+ else if (value !== null && value !== MASKED) {
228
+ const problem = settingValueProblem(setting, value)
229
+ if (problem) problems.push(problem)
230
+ else if (
231
+ setting.type === 'layout' &&
232
+ !siteLayouts(config.componentsDir).includes(value as string)
233
+ )
234
+ problems.push(`${setting.label}: the site has no component "${value}"`)
235
+ }
236
+ }
237
+ if (problems.length > 0) return { status: 400, ok: false, message: `${problems.join('; ')}.` }
238
+ if (Object.entries(values).some(([key]) => settings[key]?.secret) && !config.secretKey)
239
+ return {
240
+ status: 409,
241
+ ok: false,
242
+ message: 'Keeping a secret setting needs CROMBOLO_SECRET_KEY set on the server.',
243
+ }
244
+ const store = new ExtensionSettingRepository(db)
245
+ for (const [key, value] of Object.entries(values)) {
246
+ // The mask sent back keeps what is stored.
247
+ if (value === MASKED) continue
248
+ const kept =
249
+ value !== null && settings[key]?.secret
250
+ ? { sealed: sealSecret(String(value), config.secretKey as string) }
251
+ : value
252
+ await store.set(pkg.id, key, value === null ? undefined : kept, actor.email ?? actor.name)
253
+ }
254
+ await audit(
255
+ actor,
256
+ 'Settings',
257
+ `${pkg.packageName}@${pkg.version}`,
258
+ Object.keys(values).join(', '),
259
+ )
260
+ // Read when its process starts.
261
+ if (pkg.carries.server) markRestartPending(config.siteDir, `${pkg.name}'s settings changed`)
262
+ return {
263
+ status: 200,
264
+ ok: true,
265
+ message: pkg.carries.server
266
+ ? `${pkg.name}'s settings are saved. They take effect when the site restarts.`
267
+ : `${pkg.name}'s settings are saved.`,
107
268
  }
108
269
  },
109
270
 
110
271
  async install(actor, request) {
111
272
  const asked = {
112
273
  applyContent: request.applyContent !== false,
113
- acceptServerCode: request.acceptServerCode === true,
114
274
  grant: request.grant ?? [],
275
+ actAs: request.actAs ?? null,
115
276
  by: actor.email ?? actor.name,
116
277
  }
117
278
  const outcome = request.file
@@ -125,21 +286,40 @@ export function createBundleAdmin(options: {
125
286
  'Install',
126
287
  outcome.dependency ? `${name}@${outcome.dependency.version}` : name,
127
288
  [
128
- asked.acceptServerCode
129
- ? `accepted server code; granted ${asked.grant.length > 0 ? asked.grant.join(', ') : 'nothing'}`
130
- : undefined,
289
+ `granted ${asked.grant.length > 0 ? asked.grant.join(', ') : 'nothing'}${asked.actAs ? `, acting for ${asked.actAs}` : ''}`,
131
290
  outcome.provenance ? describeProvenance(outcome.provenance) : undefined,
132
291
  ]
133
292
  .filter(Boolean)
134
293
  .join('; ') || null,
135
294
  )
295
+ // The layout picked in the install panel, and any other setting given with it.
296
+ if (landed && request.settings && Object.keys(request.settings).length > 0) {
297
+ const saved = await this.setSettings(actor, landed.id, request.settings)
298
+ if (!saved.ok)
299
+ return { ...outcome, message: `${outcome.message ?? 'Installed.'} ${saved.message}` }
300
+ }
136
301
  if (!landed?.carries.server) return outcome
137
302
  markRestartPending(config.siteDir, `${name}@${landed.version} installed`)
138
303
  return { ...outcome, restartPending: true }
139
304
  },
140
305
 
141
- async uninstall(actor, name) {
306
+ async uninstall(actor, name, options = {}) {
142
307
  const before = find(name)
308
+ if (options.revertContent) {
309
+ const run = await new TransferRunRepository(db).appliedForPackage(name)
310
+ if (run) {
311
+ const reverted = await revertRun(db, run.id, {
312
+ nodeId: config.nodeId,
313
+ backOfficePath: config.backOfficePath,
314
+ })
315
+ if (!reverted.runId)
316
+ return {
317
+ ok: false,
318
+ message: `${name}'s content could not be put back, so it was not removed: ${reverted.check.findings.map((finding) => finding.message).join('; ')}`,
319
+ }
320
+ await revertSections(db, config, run.id)
321
+ }
322
+ }
143
323
  const outcome = await marketplace.uninstall(name)
144
324
  if (!outcome.ok) return outcome
145
325
  await audit(actor, 'Uninstall', name, null)
@@ -148,13 +328,54 @@ export function createBundleAdmin(options: {
148
328
  return { ...outcome, restartPending: true }
149
329
  },
150
330
 
331
+ async grant(actor, id, request) {
332
+ const pkg = find(id)
333
+ if (!pkg)
334
+ return { status: 404, ok: false, message: `No installed extension is called "${id}".` }
335
+ const asks = declaredPermissions(pkg)
336
+ const missing = asks.filter((permission) => !request.grant.includes(permission))
337
+ const extra = request.grant.filter((permission) => !asks.includes(permission))
338
+ if (missing.length > 0 || extra.length > 0)
339
+ return {
340
+ status: 409,
341
+ ok: false,
342
+ message: [
343
+ `${pkg.name} asks for other permissions than were granted.`,
344
+ missing.length > 0 ? `Not granted: ${missing.join(', ')}.` : '',
345
+ extra.length > 0 ? `Not asked for: ${extra.join(', ')}.` : '',
346
+ ]
347
+ .filter(Boolean)
348
+ .join(' '),
349
+ }
350
+ if (asks.includes('actAs') && !request.actAs)
351
+ return {
352
+ status: 409,
353
+ ok: false,
354
+ message: `${pkg.name} asks to act for a user: say whom, the installer, the caller or a named user.`,
355
+ }
356
+ await bundleGrants.grant(pkg, actor.email ?? actor.name, { actAs: request.actAs ?? null })
357
+ await audit(
358
+ actor,
359
+ 'Grant',
360
+ `${pkg.packageName}@${pkg.version}`,
361
+ `granted ${asks.join(', ') || 'nothing'}${request.actAs ? `, acting for ${request.actAs}` : ''}`,
362
+ )
363
+ const state = bundleGrants.state(pkg)
364
+ return {
365
+ status: 200,
366
+ ok: true,
367
+ on: state.on,
368
+ message: `${pkg.name} is granted what it asks for.`,
369
+ }
370
+ },
371
+
151
372
  async setEnabled(actor, id, enabled) {
152
373
  const pkg = find(id)
153
374
  if (!pkg?.carries.server)
154
375
  return {
155
376
  status: 404,
156
377
  ok: false,
157
- message: `No installed bundle with a server half is called "${id}".`,
378
+ message: `No installed extension with a server half is called "${id}".`,
158
379
  }
159
380
  const state = enabled
160
381
  ? await bundleGrants.enable(pkg)
@@ -198,6 +419,7 @@ export async function localBundleAdmin(
198
419
  registry: config.npmRegistry,
199
420
  keyword: config.packageKeyword,
200
421
  marketplaceUrl: config.marketplaceUrl,
422
+ componentsDir: config.componentsDir,
201
423
  extensions,
202
424
  siteDir: config.siteDir,
203
425
  grants: bundleGrants,
@@ -207,18 +429,19 @@ export async function localBundleAdmin(
207
429
  contentApplied: async (packageName) =>
208
430
  (await new TransferRunRepository(db).appliedForPackage(packageName))?.packageVersion ?? null,
209
431
  applyContent: async (packageName) => {
210
- const result = await installBundleContent(db, config, { bundle: packageName }).catch(
211
- (error: unknown) => {
212
- if (error instanceof CommandError) return error
213
- throw error
214
- },
215
- )
432
+ const result = await installBundleContent(db, config, {
433
+ bundle: packageName,
434
+ expects: 'extension',
435
+ }).catch((error: unknown) => {
436
+ if (error instanceof CommandError) return error
437
+ throw error
438
+ })
216
439
  if (result instanceof CommandError)
217
440
  return { applied: false, message: `Its content was not applied: ${result.message}` }
218
441
  if (!result.runId)
219
442
  return {
220
443
  applied: false,
221
- message: `Its content was not applied: ${[...result.problems, ...result.check.outstanding.map((f) => f.message)].join('; ') || 'the check refused it'}. \`crombolo bundle apply ${packageName} --dry-run\` says what it needs.`,
444
+ message: `Its content was not applied: ${[...result.problems, ...result.check.outstanding.map((f) => f.message)].join('; ') || 'the check refused it'}.`,
222
445
  }
223
446
  return { applied: true, runId: result.runId, message: 'Its content was applied.' }
224
447
  },