@crombolo/server 0.60.0 → 0.61.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.60.0",
3
+ "version": "0.61.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,19 +31,19 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.60.0",
35
- "@crombolo/api-management": "0.60.0",
36
- "@crombolo/auth": "0.60.0",
37
- "@crombolo/backoffice-host": "0.60.0",
38
- "@crombolo/common": "0.60.0",
39
- "@crombolo/content": "0.60.0",
40
- "@crombolo/contracts": "0.60.0",
41
- "@crombolo/core": "0.60.0",
42
- "@crombolo/data": "0.60.0",
43
- "@crombolo/extension": "0.60.0",
44
- "@crombolo/render": "0.60.0",
45
- "@crombolo/schema": "0.60.0",
46
- "@crombolo/transfer": "0.60.0",
34
+ "@crombolo/api-delivery": "0.61.0",
35
+ "@crombolo/api-management": "0.61.0",
36
+ "@crombolo/auth": "0.61.0",
37
+ "@crombolo/backoffice-host": "0.61.0",
38
+ "@crombolo/common": "0.61.0",
39
+ "@crombolo/content": "0.61.0",
40
+ "@crombolo/contracts": "0.61.0",
41
+ "@crombolo/core": "0.61.0",
42
+ "@crombolo/data": "0.61.0",
43
+ "@crombolo/extension": "0.61.0",
44
+ "@crombolo/render": "0.61.0",
45
+ "@crombolo/schema": "0.61.0",
46
+ "@crombolo/transfer": "0.61.0",
47
47
  "@logtape/logtape": "^2.3.8",
48
48
  "@opentelemetry/api": "1.10.0",
49
49
  "@opentelemetry/context-async-hooks": "3.0.0",
@@ -13,6 +13,7 @@ import {
13
13
  auditRecord,
14
14
  type Db,
15
15
  } from '@crombolo/data'
16
+ import { callingExtensionName } from '../bundle-api.ts'
16
17
  import { logger } from '../logging.ts'
17
18
 
18
19
  const log = logger('Audit')
@@ -37,6 +38,16 @@ export async function recordAudit(
37
38
  }
38
39
  }
39
40
 
41
+ /** An entry's detail when an extension did it for a person: "Redirects, for Adam". */
42
+ export function attributed(
43
+ extension: string,
44
+ person: string | null | undefined,
45
+ detail: string | null | undefined,
46
+ ): string {
47
+ const by = `${extension}, for ${person ?? 'someone'}`
48
+ return detail ? `${by}: ${detail}` : by
49
+ }
50
+
40
51
  export function createAuditSink(db: Db): AuditSink {
41
52
  const audit = new AuditLog(db)
42
53
  return {
@@ -52,11 +63,20 @@ export function createAuditSink(db: Db): AuditSink {
52
63
  return { entityType, entityKey: key, entityName: null }
53
64
  }
54
65
  },
55
- record: (entries) =>
56
- recordAudit(
66
+ record: (entries) => {
67
+ // An extension acting for a person is told apart from them (story 325).
68
+ const extension = callingExtensionName()
69
+ return recordAudit(
57
70
  db,
58
- entries.map((entry) => ({ ...entry, source: 'request' as const })),
59
- ),
71
+ entries.map((entry) => ({
72
+ ...entry,
73
+ source: 'request' as const,
74
+ ...(extension && !String(entry.userKey ?? '').startsWith('extension:')
75
+ ? { detail: attributed(extension, entry.userName, entry.detail) }
76
+ : {}),
77
+ })),
78
+ )
79
+ },
60
80
  }
61
81
  }
62
82
 
@@ -51,9 +51,9 @@ export async function syncWorkflowFiles(db: Db, schemaDir: string) {
51
51
  }
52
52
 
53
53
  /** What saving a workflow would do to the requests in flight under it. */
54
- /** Setting up workflows, which a group can be given (story 296). Deciding on a page is separate. */
54
+ /** Setting up workflows, which Settings brings (story 322). Deciding on a page is separate. */
55
55
  const mayDesignWorkflows = (principal: Principal): boolean =>
56
- principal.isAdmin || hasSection(principal, 'workflowSetup')
56
+ principal.isAdmin || hasSection(principal, 'settings')
57
57
 
58
58
  async function changePreview(approvals: Approvals, principal: Principal, workflow: SchemaWorkflow) {
59
59
  const id = workflow.key ?? workflow.alias
@@ -3,21 +3,42 @@
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 { rmSync } from 'node:fs'
7
+ import { join } from 'node:path'
6
8
  import type { BundlePackage, ExtensionRegistry } from '@crombolo/backoffice-host'
7
9
  import {
8
10
  createExtensionRegistry,
9
11
  type ExtensionSetting,
12
+ isUpperLevel,
13
+ LEVEL_WORDS,
14
+ levelOf,
10
15
  readSettings,
11
16
  settingValueProblem,
17
+ USER_DELEGATE,
12
18
  } from '@crombolo/backoffice-host/registry'
13
- import { type Db, ExtensionSettingRepository, TransferRunRepository } from '@crombolo/data'
19
+ import {
20
+ type Db,
21
+ ExtensionSettingRepository,
22
+ ownerTablesIn,
23
+ purgeOwnerTables,
24
+ recordedOwner,
25
+ SITE_OWNER,
26
+ TransferRunRepository,
27
+ tablesStateKey,
28
+ } from '@crombolo/data'
14
29
  import { revertRun } from '@crombolo/transfer'
15
30
  import { recordAudit } from './adapters/audit.ts'
16
- import { type BundleGrants, createBundleGrants, declaredPermissions } from './bundle-grants.ts'
31
+ import {
32
+ type BundleGrants,
33
+ createBundleGrants,
34
+ DELEGATE_NEEDS_PERSON,
35
+ declaredPermissions,
36
+ } from './bundle-grants.ts'
17
37
  import { CommandError, installBundleContent, revertSections } from './bundle-install.ts'
18
38
  import { componentsWritten } from './bundle-sections.ts'
19
39
  import { siteLayouts } from './components.ts'
20
40
  import type { CromboloConfig } from './config.ts'
41
+ import { grantRefusal } from './grant-policy.ts'
21
42
  import {
22
43
  createMarketplace,
23
44
  type InstalledListing,
@@ -35,6 +56,8 @@ export interface BundleActor {
35
56
  id: string | null
36
57
  name: string
37
58
  email: string | null
59
+ /** An administrator: only one grants Acts as you and Unrestricted (story 324). */
60
+ isAdmin: boolean
38
61
  source: 'request' | 'cli'
39
62
  ipAddress?: string | null
40
63
  forwardedFor?: string | null
@@ -47,6 +70,8 @@ export interface InstalledBundles {
47
70
  restartPending: RestartPending | null
48
71
  /** What this site takes of a bundle's signature (story 060). */
49
72
  policy: ProvenancePolicy
73
+ /** The data removed extensions left behind, kept until deleted (story 328). */
74
+ left: { id: string; tables: string[] }[]
50
75
  items: (InstalledListing & {
51
76
  settings?: SettingView[]
52
77
  couldNotStart?: string
@@ -75,8 +100,11 @@ export interface InstallRequest {
75
100
  file?: boolean
76
101
  applyContent?: boolean
77
102
  grant?: readonly string[]
78
- /** Whom it acts for, when it asks for `actAs` (story 308). */
79
- actAs?: string | null
103
+ /**
104
+ * Under `user.delegate`, the user a job or an event acts for (story 325): the
105
+ * person granting it, which is the actor's own key unless named.
106
+ */
107
+ delegateTo?: string | null
80
108
  /** Its settings' values, saved once it is installed: the layout picked for it (story 312). */
81
109
  settings?: Readonly<Record<string, unknown>>
82
110
  }
@@ -93,12 +121,19 @@ export interface BundleAdmin {
93
121
  /** What installing a version would bring, with nothing installed. */
94
122
  inspect: Marketplace['inspect']
95
123
  install(actor: BundleActor, request: InstallRequest): Promise<InstallOutcome>
96
- /** `revertContent` first puts back the content its install applied (story 306). */
124
+ /**
125
+ * Removes an extension (story 328): stops it, forgets its grant and settings,
126
+ * deletes its root, its build and its line, and keeps its data unless
127
+ * `dropData`; `dropContent` first takes out the content its install applied
128
+ * (`revertContent`, its name before 0.61, still read).
129
+ */
97
130
  uninstall(
98
131
  actor: BundleActor,
99
132
  name: string,
100
- options?: { revertContent?: boolean },
101
- ): Promise<InstallOutcome>
133
+ options?: { dropData?: boolean; dropContent?: boolean; revertContent?: boolean },
134
+ ): Promise<InstallOutcome & { dropped?: string[]; roleLeft?: string; dataKept?: boolean }>
135
+ /** Deletes the data an extension removed earlier left behind: its tables and its folder. */
136
+ dropLeftData(actor: BundleActor, id: string): Promise<SwitchOutcome & { dropped?: string[] }>
102
137
  /** Turns a bundle's server features off or on; `id` is its bundle id or its package name. */
103
138
  setEnabled(actor: BundleActor, id: string, enabled: boolean): Promise<SwitchOutcome>
104
139
  /**
@@ -112,13 +147,13 @@ export interface BundleAdmin {
112
147
  ): Promise<SwitchOutcome>
113
148
  /**
114
149
  * 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.
150
+ * (story 309), and for `user.delegate` who granted it (story 325); refused,
151
+ * saying what differs, otherwise.
117
152
  */
118
153
  grant(
119
154
  actor: BundleActor,
120
155
  id: string,
121
- request: { grant: readonly string[]; actAs?: string | null },
156
+ request: { grant: readonly string[]; delegateTo?: string | null },
122
157
  ): Promise<SwitchOutcome>
123
158
  }
124
159
 
@@ -130,11 +165,51 @@ export function createBundleAdmin(options: {
130
165
  config: CromboloConfig
131
166
  marketplace: Marketplace
132
167
  extensions: Pick<ExtensionRegistry, 'bundles'>
133
- bundleGrants: Pick<BundleGrants, 'disable' | 'enable' | 'grant' | 'state'>
168
+ bundleGrants: Pick<BundleGrants, 'disable' | 'enable' | 'grant' | 'state' | 'forget'>
134
169
  /** Granted extensions that could not start, and why (story 311). */
135
170
  failed?: () => readonly { id: string; reason: string }[]
171
+ /** Stops an extension's running process, where this node runs one (story 328). */
172
+ stopExtension?: (id: string) => Promise<void>
136
173
  }): BundleAdmin {
137
174
  const { db, config, marketplace, extensions, bundleGrants } = options
175
+ const options_ = options
176
+ /**
177
+ * The data removed extensions left (story 328): an owner the tables ledger
178
+ * records that no installed package is, nor the site, nor a bundle the
179
+ * config wires, with its tables.
180
+ */
181
+ const leftData = async (): Promise<{ id: string; tables: string[] }[]> => {
182
+ const rows = await db.q
183
+ .selectFrom('key_value')
184
+ .select('key')
185
+ .where('key', 'like', 'Crombolo.Tables.%.State')
186
+ .execute()
187
+ .catch(() => [])
188
+ // What is installed, the site, and a bundle the site wires as its own code. A removed
189
+ // extension stays in the running config's bundles until the restart, so it is not one.
190
+ const discovered = extensions.bundles().bundles
191
+ const installed = new Set([
192
+ ...discovered.map((pkg) => pkg.id),
193
+ ...config.bundles
194
+ .map((bundle) => bundle.id)
195
+ .filter((id) => discovered.some((pkg) => pkg.id === id && !pkg.root)),
196
+ SITE_OWNER,
197
+ ])
198
+ const out: { id: string; tables: string[] }[] = []
199
+ for (const { key } of rows) {
200
+ const id = key.slice('Crombolo.Tables.'.length, -'.State'.length)
201
+ if (installed.has(id)) continue
202
+ const place = await recordedOwner(db, config, id)
203
+ out.push({ id, tables: place ? await ownerTablesIn(db, place).catch(() => []) : [] })
204
+ }
205
+ return out.sort((a, b) => a.id.localeCompare(b.id))
206
+ }
207
+ /** Its tables, schema and role, or its SQLite tables and ledger, without a backup (story 328). */
208
+ const dropData = async (id: string): Promise<{ tables: string[]; roleLeft?: string }> => {
209
+ const place = await recordedOwner(db, config, id)
210
+ if (!place) return { tables: [] }
211
+ return purgeOwnerTables(db, place, { by: config.nodeId, stateKey: tablesStateKey(id) })
212
+ }
138
213
  const audit = (actor: BundleActor, action: string, entityName: string, detail: string | null) =>
139
214
  recordAudit(db, {
140
215
  category: 'system',
@@ -189,6 +264,7 @@ export function createBundleAdmin(options: {
189
264
  installsElsewhere: config.runtimeInstalls ? null : (config.installsElsewhere ?? null),
190
265
  restartPending: restartPending(config.siteDir) ?? null,
191
266
  policy: config.bundlePolicy,
267
+ left: await leftData(),
192
268
  items: await Promise.all(
193
269
  (await marketplace.installed()).map(async (item) => {
194
270
  const pkg = find(item.packageName)
@@ -272,8 +348,9 @@ export function createBundleAdmin(options: {
272
348
  const asked = {
273
349
  applyContent: request.applyContent !== false,
274
350
  grant: request.grant ?? [],
275
- actAs: request.actAs ?? null,
351
+ delegateTo: request.delegateTo ?? actor.id ?? null,
276
352
  by: actor.email ?? actor.name,
353
+ isAdmin: actor.isAdmin,
277
354
  }
278
355
  const outcome = request.file
279
356
  ? await marketplace.installFile(request.name, asked)
@@ -286,7 +363,7 @@ export function createBundleAdmin(options: {
286
363
  'Install',
287
364
  outcome.dependency ? `${name}@${outcome.dependency.version}` : name,
288
365
  [
289
- `granted ${asked.grant.length > 0 ? asked.grant.join(', ') : 'nothing'}${asked.actAs ? `, acting for ${asked.actAs}` : ''}`,
366
+ `granted ${LEVEL_WORDS[levelOf(asked.grant)].label}: ${asked.grant.length > 0 ? asked.grant.join(', ') : 'nothing'}${asked.grant.includes(USER_DELEGATE) && asked.delegateTo ? `, acting for ${asked.delegateTo} when nobody is using it` : ''}`,
290
367
  outcome.provenance ? describeProvenance(outcome.provenance) : undefined,
291
368
  ]
292
369
  .filter(Boolean)
@@ -305,7 +382,16 @@ export function createBundleAdmin(options: {
305
382
 
306
383
  async uninstall(actor, name, options = {}) {
307
384
  const before = find(name)
308
- if (options.revertContent) {
385
+ const id = before?.id
386
+ const dropContent = options.dropContent ?? options.revertContent ?? false
387
+ // The site's own code wires a bundle; an extension in a root of its own never is (story 326).
388
+ if (id && !before?.root && config.bundles.some((bundle) => bundle.id === id))
389
+ return {
390
+ ok: false,
391
+ message: `${name} is wired in the site's crombolo.config.ts, as the site's own code: take it out of \`bundles\` and deploy that first.`,
392
+ }
393
+ // The order is the story's: content, stop, revoke, files, then data.
394
+ if (dropContent) {
309
395
  const run = await new TransferRunRepository(db).appliedForPackage(name)
310
396
  if (run) {
311
397
  const reverted = await revertRun(db, run.id, {
@@ -320,12 +406,82 @@ export function createBundleAdmin(options: {
320
406
  await revertSections(db, config, run.id)
321
407
  }
322
408
  }
409
+ if (id) {
410
+ await options_.stopExtension?.(id).catch(() => {})
411
+ await bundleGrants.forget(id)
412
+ await new ExtensionSettingRepository(db).forget(id).catch(() => {})
413
+ // Its build goes either way; its data folder only with its data.
414
+ const home = join(config.siteDir, '.crombolo', 'extensions', id)
415
+ if (options.dropData) rmSync(home, { recursive: true, force: true })
416
+ else
417
+ for (const part of ['build', 'backoffice'])
418
+ rmSync(join(home, part), { recursive: true, force: true })
419
+ }
323
420
  const outcome = await marketplace.uninstall(name)
324
421
  if (!outcome.ok) return outcome
325
- await audit(actor, 'Uninstall', name, null)
326
- if (!before?.carries.server) return outcome
422
+ let dropped: string[] = []
423
+ let roleLeft: string | undefined
424
+ if (id && options.dropData) {
425
+ const purged = await dropData(id)
426
+ dropped = purged.tables
427
+ roleLeft = purged.roleLeft
428
+ }
429
+ await audit(
430
+ actor,
431
+ 'Uninstall',
432
+ name,
433
+ [
434
+ options.dropData ? 'removed with its data' : 'removed; its data kept',
435
+ dropContent ? 'and the content it added' : '',
436
+ roleLeft ? `the role ${roleLeft} could not be dropped` : '',
437
+ ]
438
+ .filter(Boolean)
439
+ .join(', '),
440
+ )
441
+ const result = {
442
+ ...outcome,
443
+ ...(options.dropData ? { dropped } : { dataKept: true }),
444
+ ...(roleLeft ? { roleLeft } : {}),
445
+ message: [
446
+ outcome.message,
447
+ options.dropData
448
+ ? dropped.length > 0
449
+ ? `Its data was deleted: ${dropped.join(', ')}.`
450
+ : ''
451
+ : 'Its data was kept, under Installed, "Data left by…", in case it is installed again.',
452
+ roleLeft
453
+ ? `The role ${roleLeft} could not be dropped from here: your host made it, so ask them to.`
454
+ : '',
455
+ ]
456
+ .filter(Boolean)
457
+ .join(' '),
458
+ }
459
+ if (!before?.carries.server) return result
327
460
  markRestartPending(config.siteDir, `${name} removed`)
328
- return { ...outcome, restartPending: true }
461
+ return { ...result, restartPending: true }
462
+ },
463
+
464
+ async dropLeftData(actor, id) {
465
+ if (extensions.bundles().bundles.some((pkg) => pkg.id === id))
466
+ return {
467
+ status: 409,
468
+ ok: false,
469
+ message: `${id} is installed: remove it with its data, or keep both.`,
470
+ }
471
+ const purged = await dropData(id)
472
+ rmSync(join(config.siteDir, '.crombolo', 'extensions', id), { recursive: true, force: true })
473
+ await audit(
474
+ actor,
475
+ 'Purge',
476
+ id,
477
+ `its data deleted: ${purged.tables.join(', ') || 'no tables'}`,
478
+ )
479
+ return {
480
+ status: 200,
481
+ ok: true,
482
+ dropped: purged.tables,
483
+ message: `The data ${id} left was deleted.${purged.roleLeft ? ` The role ${purged.roleLeft} could not be dropped from here: your host made it, so ask them to.` : ''}`,
484
+ }
329
485
  },
330
486
 
331
487
  async grant(actor, id, request) {
@@ -347,18 +503,30 @@ export function createBundleAdmin(options: {
347
503
  .filter(Boolean)
348
504
  .join(' '),
349
505
  }
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 })
506
+ // The upper levels: an administrator, a package someone vouched for, and the host's rule (story 324).
507
+ const level = levelOf(asks)
508
+ const provenance = isUpperLevel(level)
509
+ ? (await marketplace.installed()).find((item) => item.id === pkg.id)?.provenance
510
+ : undefined
511
+ const refused = grantRefusal({
512
+ level,
513
+ grants: asks.length > 0,
514
+ isAdmin: actor.isAdmin,
515
+ provenance,
516
+ from: config.unrestrictedExtensions ?? 'backoffice',
517
+ })
518
+ if (refused) return { status: 403, ok: false, message: `${pkg.name}: ${refused}` }
519
+ const delegateKey = asks.includes(USER_DELEGATE)
520
+ ? (request.delegateTo ?? actor.id ?? null)
521
+ : null
522
+ if (asks.includes(USER_DELEGATE) && !delegateKey)
523
+ return { status: 409, ok: false, message: `${pkg.name}: ${DELEGATE_NEEDS_PERSON}.` }
524
+ await bundleGrants.grant(pkg, actor.email ?? actor.name, { delegateKey })
357
525
  await audit(
358
526
  actor,
359
527
  'Grant',
360
528
  `${pkg.packageName}@${pkg.version}`,
361
- `granted ${asks.join(', ') || 'nothing'}${request.actAs ? `, acting for ${request.actAs}` : ''}`,
529
+ `granted ${LEVEL_WORDS[level].label}: ${asks.join(', ') || 'nothing'}${delegateKey ? `, acting for ${delegateKey} when nobody is using it` : ''}`,
362
530
  )
363
531
  const state = bundleGrants.state(pkg)
364
532
  return {
@@ -426,6 +594,7 @@ export async function localBundleAdmin(
426
594
  installs: true,
427
595
  policy: config.bundlePolicy,
428
596
  applyContentOnInstall: true,
597
+ unrestrictedFrom: config.unrestrictedExtensions,
429
598
  contentApplied: async (packageName) =>
430
599
  (await new TransferRunRepository(db).appliedForPackage(packageName))?.packageVersion ?? null,
431
600
  applyContent: async (packageName) => {
package/src/bundle-api.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import { AsyncLocalStorage } from 'node:async_hooks'
12
12
  import type { Principal } from '@crombolo/api-management'
13
+ import { USER_DELEGATE } from '@crombolo/backoffice-host/registry'
13
14
  import {
14
15
  DocumentPermissions,
15
16
  FormPermissions,
@@ -17,6 +18,7 @@ import {
17
18
  ROOT_ACCESS,
18
19
  SECTION_ALIASES,
19
20
  } from '@crombolo/core'
21
+ import { type ActivityPerson, type ActivityRecorder, timed } from './extension-activity.ts'
20
22
 
21
23
  /** A permission's reach: the paths, under the back office, its methods may call. */
22
24
  interface Reach {
@@ -129,6 +131,12 @@ const SECTIONS: Readonly<Record<string, string>> = {
129
131
  redirects: SECTION_ALIASES.content,
130
132
  }
131
133
 
134
+ /** The section an area's permission needs, for acting as the person using it (story 325). */
135
+ export const sectionOfPermission = (permission: string): string | undefined => {
136
+ const area = permission.split('.')[0] as string
137
+ return area === 'identityProviders' ? SECTION_ALIASES.settings : SECTIONS[area]
138
+ }
139
+
132
140
  /** The verbs a set of permissions needs, for the API's own permission checks. */
133
141
  function verbsOf(granted: ReadonlySet<string>): string[] {
134
142
  const verbs = new Set<string>()
@@ -224,10 +232,34 @@ export function actingPrincipalOf(request: Request): Principal | undefined {
224
232
  return secret === SECRET && call ? acting.get(call) : undefined
225
233
  }
226
234
 
227
- const calling = new AsyncLocalStorage<string>()
235
+ const calling = new AsyncLocalStorage<{ id: string; name: string }>()
228
236
 
229
237
  /** The extension whose call to `api` is being answered, while it is. */
230
- export const callingExtension = (): string | undefined => calling.getStore()
238
+ export const callingExtension = (): string | undefined => calling.getStore()?.id
239
+
240
+ /** Its name, for the audit log's "Redirects, for Adam" (story 325). */
241
+ export const callingExtensionName = (): string | undefined => calling.getStore()?.name
242
+
243
+ /**
244
+ * What no extension may do through `api` for anyone, however wide the person's
245
+ * own access (story 325): install or grant extensions, change users or groups,
246
+ * or reach a site as a remote. Pure.
247
+ */
248
+ export function refusedForEveryone(method: string, path: string): string | undefined {
249
+ const clean = path.replace(/^\/+/, '')
250
+ if (
251
+ under(clean, `${PLUGIN}extensions`) ||
252
+ under(clean, `${PLUGIN}bundles`) ||
253
+ under(clean, 'remote')
254
+ )
255
+ return 'an extension may not install or grant extensions, or reach this site as a remote, for anyone'
256
+ if (
257
+ !READING.has(method.toUpperCase()) &&
258
+ (under(clean, `${MANAGEMENT}user`) || under(clean, `${MANAGEMENT}user-group`))
259
+ )
260
+ return 'an extension may not change users or groups, for anyone'
261
+ return undefined
262
+ }
231
263
 
232
264
  /**
233
265
  * `api` for one extension and caller: refuses what the grant does not cover,
@@ -236,6 +268,10 @@ export const callingExtension = (): string | undefined => calling.getStore()
236
268
  */
237
269
  export function createBundleApi(options: {
238
270
  bundleId: string
271
+ /** Its name, for the audit log; its id when not given. */
272
+ bundleName?: string
273
+ /** Records each request for the activity view (story 327). */
274
+ activity?: { recorder: ActivityRecorder; person: ActivityPerson }
239
275
  origin: string
240
276
  backOfficePath: string
241
277
  granted: () => readonly string[]
@@ -248,8 +284,25 @@ export function createBundleApi(options: {
248
284
  const clean = path.replace(/^\/+/, '')
249
285
  const needs = permissionsFor(verb, clean)
250
286
  const granted = new Set(options.granted())
251
- if (!needs.some((permission) => granted.has(permission)))
252
- throw new ApiRefusedError(
287
+ const area = needs[0]?.split('.')[0] ?? clean.split('/').slice(0, 4).join('/')
288
+ const event = {
289
+ extensionId: options.bundleId,
290
+ ...(options.activity?.person ?? { personKey: null, personName: null }),
291
+ kind: (READING.has(verb) ? 'read' : 'write') as 'read' | 'write',
292
+ area,
293
+ verb,
294
+ entityKey: KEY_IN_PATH.exec(clean)?.[0] ?? null,
295
+ }
296
+ const refuse = (message: string): never => {
297
+ options.activity?.recorder.record({ ...event, kind: 'refused', outcome: 'refused' })
298
+ throw new ApiRefusedError(message)
299
+ }
300
+ const never = refusedForEveryone(verb, clean)
301
+ if (never) refuse(`${options.bundleId} may not ${verb} ${clean}: ${never}.`)
302
+ // Acting for the person reaches every area; the API then holds it to their own rights (story 325).
303
+ const delegated = granted.has(USER_DELEGATE) && needs.length > 0
304
+ if (!delegated && !needs.some((permission) => granted.has(permission)))
305
+ refuse(
253
306
  needs.length > 0
254
307
  ? `${options.bundleId} may not ${verb} ${clean}: it needs ${needs.join(' or ')}, which it was not granted.`
255
308
  : `${options.bundleId} may not ${verb} ${clean}: no permission reaches it.`,
@@ -269,7 +322,12 @@ export function createBundleApi(options: {
269
322
  })
270
323
  acting.set(call, principal)
271
324
  try {
272
- return await calling.run(options.bundleId, () => dispatch(sent))
325
+ const answered = await timed(options.activity?.recorder, event, () =>
326
+ calling.run({ id: options.bundleId, name: options.bundleName ?? options.bundleId }, () =>
327
+ dispatch(sent),
328
+ ),
329
+ )
330
+ return answered
273
331
  } finally {
274
332
  acting.delete(call)
275
333
  }
@@ -284,16 +342,9 @@ export function createBundleApi(options: {
284
342
  }
285
343
 
286
344
  const KEY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
345
+ const KEY_IN_PATH = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i
287
346
 
288
- /**
289
- * Whom an `actAs` grant names, as stored: `installer` becomes the installing
290
- * user's key, `caller` stays, and `user:<key>` names a user. Null when no choice
291
- * was given, or one it cannot be.
292
- */
293
- export function actAsChoice(value: unknown, installerKey?: string): string | null {
294
- if (value === 'caller') return 'caller'
295
- if (value === 'installer') return installerKey ? `installer:${installerKey}` : null
296
- if (typeof value === 'string' && value.startsWith('user:') && KEY.test(value.slice(5)))
297
- return value.toLowerCase()
298
- return null
347
+ /** A user's key, as `--delegate-to` names one: lower case, or null when it is not one. */
348
+ export function userKeyOf(value: unknown): string | null {
349
+ return typeof value === 'string' && KEY.test(value.trim()) ? value.trim().toLowerCase() : null
299
350
  }
@@ -8,7 +8,7 @@
8
8
  */
9
9
  import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
10
10
  import { dirname, join } from 'node:path'
11
- import { CODE_DIR } from '@crombolo/transfer'
11
+ import { CODE_DIR, EXTENSION_ROOTS_DIR } from '@crombolo/transfer'
12
12
  import type { CarriedSections, FileAction, SectionFile } from './bundle-sections.ts'
13
13
  import { RUN_BACKUP_DIR } from './bundle-sections.ts'
14
14
  import type { CromboloConfig } from './config.ts'
@@ -108,6 +108,23 @@ export async function installCode(
108
108
  if (failed) result.problems.push(failed)
109
109
  else result.installed = true
110
110
  }
111
+ // Story 326: each extension's root whose files changed installs from its own lockfile.
112
+ const roots = new Set(
113
+ changed
114
+ .map((file) => sitePath(file.path).split('/'))
115
+ .filter(
116
+ (parts) =>
117
+ parts.length === 3 &&
118
+ parts[0] === EXTENSION_ROOTS_DIR &&
119
+ DEPENDENCY_FILES.has(parts[2] as string),
120
+ )
121
+ .map((parts) => parts[1] as string),
122
+ )
123
+ for (const id of roots) {
124
+ const failed = await installFromLockfile(join(config.siteDir, EXTENSION_ROOTS_DIR, id))
125
+ if (failed) result.problems.push(`${EXTENSION_ROOTS_DIR}/${id}/: ${failed}`)
126
+ else result.installed = true
127
+ }
111
128
  const record: CodeRecord = {
112
129
  files: changed.map((file) => ({ path: sitePath(file.path), action: file.action })),
113
130
  installed: dependencies,