@crombolo/server 0.59.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/src/index.ts CHANGED
@@ -23,9 +23,10 @@ export * from './bundle-admin.ts'
23
23
  export {
24
24
  API_PERMISSIONS,
25
25
  ApiRefusedError,
26
- actAsChoice,
27
26
  type BundleApi,
28
27
  permissionsFor,
28
+ refusedForEveryone,
29
+ userKeyOf,
29
30
  } from './bundle-api.ts'
30
31
  export * from './bundle-build.ts'
31
32
  export * from './bundle-code.ts'
@@ -61,12 +62,19 @@ export * from './email-postmark.ts'
61
62
  export * from './email-resend.ts'
62
63
  export * from './email-ses.ts'
63
64
  export * from './email-text.ts'
65
+ export {
66
+ activityCsv,
67
+ createActivityRecorder,
68
+ personOf,
69
+ readActivityQuery,
70
+ } from './extension-activity.ts'
64
71
  export {
65
72
  entryCovers,
66
73
  extensionEntryProblems,
67
74
  settingsOf,
68
75
  } from './extension-discovery.ts'
69
76
  export { denoArguments, netHosts, processReads } from './extension-process.ts'
77
+ export { normaliseScreenResult, safeScreenHref, screenValues } from './extension-screens.ts'
70
78
  export { extensionSqlProblem } from './extension-sql.ts'
71
79
  export * from './extensions-notice.ts'
72
80
  export * from './external-sign-in.ts'
@@ -80,6 +88,7 @@ export * from './forms.ts'
80
88
  export * from './git.ts'
81
89
  export * from './git-github.ts'
82
90
  export * from './git-routes.ts'
91
+ export * from './grant-policy.ts'
83
92
  export * from './host-token.ts'
84
93
  export * from './identity-provider-overrides.ts'
85
94
  export * from './identity-providers.ts'
package/src/jobs.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  ContentEventRepository,
16
16
  type Db,
17
17
  DocumentRepository,
18
+ ExtensionActivityLog,
18
19
  pruneCacheInstructions,
19
20
  SearchIndex,
20
21
  WebhookDeliveryRepository,
@@ -34,6 +35,9 @@ import type { MediaFileStore } from './media-files.ts'
34
35
  import { tracedJob } from './telemetry.ts'
35
36
  import type { WebhookService } from './webhooks.ts'
36
37
 
38
+ /** The most rows of activity kept for one extension, oldest deleted first (story 327). */
39
+ export const ACTIVITY_CAP = 100_000
40
+
37
41
  export interface JobsOptions {
38
42
  db: Db
39
43
  cache: PublishedCache
@@ -67,6 +71,8 @@ export interface JobsOptions {
67
71
  searchIndexingMs?: number
68
72
  /** Days the audit log keeps an entry; 0 or absent keeps them forever. */
69
73
  auditRetentionDays?: number
74
+ /** How many days extension activity is kept (story 327); 0 keeps none. */
75
+ extensionActivityDays?: number
70
76
  /** Content notifications (story 045): queued by changes, sent here. Absent without e-mail. */
71
77
  contentNotifications?: ContentNotificationRunner
72
78
  contentNotificationsMs?: number
@@ -106,6 +112,8 @@ export interface BackgroundJobs {
106
112
  kickSearchIndexing(): void
107
113
  /** Deletes audit entries older than the retention period, and returns how many. */
108
114
  runAuditRetention(now?: Date): Promise<number>
115
+ /** Deletes extension activity older than the window, and past each extension's cap (story 327). */
116
+ runActivityRetention(now?: Date): Promise<number>
109
117
  /** Runs whether or not the hourly job is enabled; the policy decides what goes. */
110
118
  runVersionCleanup(now?: Date): Promise<{ nodes: number; versionsDeleted: number }>
111
119
  start(): void
@@ -228,6 +236,15 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
228
236
  return before ? new AuditLog(options.db).prune(before) : 0
229
237
  }
230
238
 
239
+ async function runActivityRetentionUntraced(now = new Date()): Promise<number> {
240
+ const store = new ExtensionActivityLog(options.db)
241
+ const days = options.extensionActivityDays ?? 14
242
+ // Nothing kept is everything older than now.
243
+ let removed = await store.prune(new Date(now.getTime() - days * 86_400_000))
244
+ for (const id of await store.extensions()) removed += await store.cap(id, ACTIVITY_CAP)
245
+ return removed
246
+ }
247
+
231
248
  async function runVersionCleanupUntraced(now = new Date()) {
232
249
  return documents.cleanupVersions(now, options.versionCleanup)
233
250
  }
@@ -306,6 +323,10 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
306
323
  runContentNotificationsUntraced,
307
324
  )
308
325
  const runAuditRetention = tracedJob('audit retention', runAuditRetentionUntraced)
326
+ const runActivityRetention = tracedJob(
327
+ 'extension activity retention',
328
+ runActivityRetentionUntraced,
329
+ )
309
330
  const runVersionCleanup = tracedJob('version cleanup', runVersionCleanupUntraced)
310
331
  const runWebhooks = tracedJob('webhooks', runWebhooksUntraced)
311
332
  const runFormWorkflows = tracedJob('form workflows', runFormWorkflowsUntraced)
@@ -314,6 +335,7 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
314
335
  runScheduledPublishing,
315
336
  runVersionCleanup,
316
337
  runAuditRetention,
338
+ runActivityRetention,
317
339
  runFormWorkflows,
318
340
  runWebhooks,
319
341
  runEvents,
@@ -351,6 +373,7 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
351
373
  }
352
374
  if (options.versionCleanup.enabled) every(60 * 60_000, runVersionCleanup)
353
375
  if (options.auditRetentionDays) every(60 * 60_000, runAuditRetention)
376
+ every(60 * 60_000, runActivityRetention)
354
377
  const files = options.mediaFiles
355
378
  if (files) every(60 * 60_000, () => files.cleanupExpired())
356
379
  },
@@ -19,20 +19,34 @@
19
19
  */
20
20
  import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
21
21
  import { tmpdir } from 'node:os'
22
- import { join, resolve } from 'node:path'
22
+ import { join, relative, resolve, sep } from 'node:path'
23
23
  import {
24
+ type AccessLevel,
24
25
  askedPermissions,
25
26
  type BundlePackage,
26
27
  type DeclaredPermission,
27
28
  describePermissions,
28
29
  EXTENSION_KEYWORD,
29
30
  type ExtensionRegistry,
31
+ forgetExtension,
32
+ groupsOf,
30
33
  isSchema3Field,
31
34
  LEGACY_EXTENSION_KEYWORD,
35
+ levelOf,
32
36
  type PackageJson,
37
+ type PermissionGroups,
38
+ packageInRoot,
39
+ prepareRoot,
40
+ RECORD_FILE,
41
+ ROOTS_DIR,
42
+ readPackageJson,
43
+ readRecord,
33
44
  readSettings,
45
+ recordExtension,
46
+ rootOf,
34
47
  SCHEMA_3_NOT_INSTALLED,
35
48
  SITE_PACKAGE_NOT_INSTALLED,
49
+ USER_DELEGATE,
36
50
  validateBundlePackage,
37
51
  } from '@crombolo/backoffice-host'
38
52
  import {
@@ -41,8 +55,15 @@ import {
41
55
  localBundlePath,
42
56
  localBundlesNamed,
43
57
  } from '@crombolo/transfer'
44
- import { type BundleGrants, declaredEntries, isSchema3 } from './bundle-grants.ts'
58
+ import {
59
+ type BundleGrants,
60
+ DELEGATE_NEEDS_PERSON,
61
+ declaredEntries,
62
+ declaredPermissions,
63
+ isSchema3,
64
+ } from './bundle-grants.ts'
45
65
  import { siteLayouts } from './components.ts'
66
+ import { grantRefusal, type UnrestrictedFrom } from './grant-policy.ts'
46
67
  import { logger } from './logging.ts'
47
68
  import {
48
69
  type ProvenancePolicy,
@@ -140,6 +161,8 @@ export interface MarketplaceOptions {
140
161
  applyContent?: (packageName: string) => Promise<ContentOutcome>
141
162
  /** The site's `applyBundleContentOnInstall`. */
142
163
  applyContentOnInstall?: boolean
164
+ /** Where an Unrestricted extension may be granted from (story 324). */
165
+ unrestrictedFrom?: UnrestrictedFrom
143
166
  /**
144
167
  * False refuses installing and removing here: the dependency belongs in
145
168
  * `package.json` and a deploy, so every node has it and it outlives a restart.
@@ -154,6 +177,12 @@ export interface MarketplaceOptions {
154
177
  }
155
178
 
156
179
  export interface InstallOutcome {
180
+ /** How far it reaches, when an install was refused for it or needs a grant (story 324). */
181
+ level?: AccessLevel
182
+ /** What it asks for, folded into the four groups the panel shows. */
183
+ groups?: PermissionGroups
184
+ /** Its extension id, which a config entry is keyed by. */
185
+ id?: string
157
186
  ok: boolean
158
187
  /**
159
188
  * The dependency line the site's `package.json` now holds, so the UI can show
@@ -180,7 +209,8 @@ export interface InstallOutcome {
180
209
  warning?: string
181
210
  }[]
182
211
  /** With `needsGrant`: it asks to act for a user, so the grant names whom (story 308). */
183
- asksActAs?: boolean
212
+ /** It asks for `user.delegate`: it acts for the person using it (story 325). */
213
+ delegates?: boolean
184
214
  /**
185
215
  * With `needsGrant`: its page templates sit in a site layout, picked here
186
216
  * (story 312). `suggested` is the one it names, when the site has it.
@@ -238,10 +268,12 @@ export interface Marketplace {
238
268
  applyContent?: boolean
239
269
  /** The permissions the administrator granted: the bundle's whole list (stories 222, 308). */
240
270
  grant?: readonly string[]
241
- /** Whom it acts for, when it asks for `actAs`: `installer:<key>`, `caller` or `user:<key>`. */
242
- actAs?: string | null
271
+ /** Under `user.delegate`, the user a job or an event acts for: whoever grants it (story 325). */
272
+ delegateTo?: string | null
243
273
  /** Who is installing, recorded on the grant. */
244
274
  by?: string | null
275
+ /** The person installing is an administrator: only one grants the upper levels (story 324). */
276
+ isAdmin?: boolean
245
277
  },
246
278
  ): Promise<InstallOutcome>
247
279
  /** What a version would bring, read from the registry and nothing installed: for a dry run. */
@@ -266,8 +298,10 @@ export interface Marketplace {
266
298
  options?: {
267
299
  applyContent?: boolean
268
300
  grant?: readonly string[]
269
- actAs?: string | null
301
+ delegateTo?: string | null
270
302
  by?: string | null
303
+ /** The person installing is an administrator: only one grants the upper levels (story 324). */
304
+ isAdmin?: boolean
271
305
  },
272
306
  ): Promise<InstallOutcome>
273
307
  uninstall(name: string): Promise<InstallOutcome>
@@ -343,6 +377,16 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
343
377
 
344
378
  /** The range `package.json` holds for a dependency, as `bun add` wrote it. */
345
379
  const rangeFor = async (name: string): Promise<string | undefined> => {
380
+ // Story 326: an extension's range is in its own root's package.json, when it names one.
381
+ const recorded = Object.entries(readRecord(options.siteDir)).find(
382
+ ([, line]) => line.name === name,
383
+ )
384
+ const inRoot = recorded
385
+ ? readPackageJson(join(rootOf(options.siteDir, recorded[0]), 'package.json'))?.dependencies?.[
386
+ name
387
+ ]
388
+ : undefined
389
+ if (inRoot) return inRoot
346
390
  try {
347
391
  const json = (await Bun.file(join(options.siteDir, 'package.json')).json()) as {
348
392
  dependencies?: Record<string, string>
@@ -403,6 +447,8 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
403
447
  layout?: AskedLayout
404
448
  version: string
405
449
  dist?: Dist
450
+ id?: string
451
+ screens?: number
406
452
  })
407
453
  | 'not-a-bundle'
408
454
  | { refused: string[] }
@@ -442,6 +488,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
442
488
  const field = version.crombolo as {
443
489
  extensions?: unknown[]
444
490
  content?: boolean
491
+ id?: string
445
492
  server?: string
446
493
  permissions?: unknown
447
494
  settings?: unknown
@@ -455,6 +502,8 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
455
502
  permissions: askedPermissions(field),
456
503
  layout: layoutAsked(field),
457
504
  version: resolved,
505
+ ...(typeof field.id === 'string' ? { id: field.id } : {}),
506
+ screens: screensOf(field),
458
507
  ...(dist ? { dist } : {}),
459
508
  }
460
509
  } catch {
@@ -515,9 +564,31 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
515
564
  : undefined
516
565
  }
517
566
 
567
+ /** Why the person may not grant what it asks for here: its level, by who they are and its signature (story 324). */
568
+ const levelRefused = (
569
+ name: string,
570
+ asked: readonly DeclaredPermission[],
571
+ provenance: ProvenanceResult,
572
+ request: { isAdmin?: boolean; grant?: readonly string[] },
573
+ ): InstallOutcome | undefined => {
574
+ const level = levelOf(asked.map((entry) => entry.permission))
575
+ const why = grantRefusal({
576
+ level,
577
+ grants: asked.length > 0,
578
+ isAdmin: request.isAdmin === true,
579
+ provenance,
580
+ from: options.unrestrictedFrom ?? 'backoffice',
581
+ })
582
+ return why
583
+ ? { ok: false, level, message: `${name} was not installed: ${why}`, provenance }
584
+ : undefined
585
+ }
586
+
518
587
  /** Each installed version's signature, checked once: a version's files do not change. */
519
588
  const installedProvenance = new Map<string, Promise<ProvenanceResult>>()
520
589
  const provenanceOfInstalled = async (bundle: BundlePackage): Promise<ProvenanceResult> => {
590
+ // Installed from a path or a workspace into its root, as a developer's own is (story 326).
591
+ if (bundle.root && readRecord(options.siteDir)[bundle.id]?.linked) return { state: 'local' }
521
592
  const range = await rangeFor(bundle.packageName)
522
593
  if (range && /^(workspace|link|file|portal):/.test(range)) return { state: 'local' }
523
594
  const key = `${bundle.packageName}@${bundle.version}`
@@ -539,7 +610,14 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
539
610
  const declares = async (name: string): Promise<BundlePackage['carries'] | undefined> => {
540
611
  const declared = await declaresAt(name)
541
612
  if (typeof declared === 'string' || 'refused' in declared) return undefined
542
- const { permissions: _, version: _version, dist: _dist, ...carries } = declared
613
+ const {
614
+ permissions: _,
615
+ version: _version,
616
+ dist: _dist,
617
+ id: _id,
618
+ screens: _screens,
619
+ ...carries
620
+ } = declared
543
621
  return carries
544
622
  }
545
623
 
@@ -549,7 +627,16 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
549
627
  schema3: isSchema3(bundle),
550
628
  ...grantStateOf(bundle),
551
629
  })
552
- const grantStateOf = (bundle: BundlePackage) => {
630
+ const grantStateOf = (bundle: BundlePackage) => ({
631
+ ...grantRows(bundle),
632
+ // How far it reaches, and what it reached when granted, for Installed's badge (story 324).
633
+ level: levelOf(declaredEntries(bundle).map((entry) => entry.permission)),
634
+ groups: groupsOf(declaredEntries(bundle), { screens: screensOf(bundle.field) }),
635
+ ...(options.grants?.state(bundle).grant?.recorded
636
+ ? { grantedLevel: levelOf(options.grants.state(bundle).grant?.permissions ?? []) }
637
+ : {}),
638
+ })
639
+ const grantRows = (bundle: BundlePackage) => {
553
640
  const declared = describePermissions(declaredEntries(bundle))
554
641
  if (!options.grants)
555
642
  return { permissions: declared, on: true, status: 'on', missing: [], disabledBy: null }
@@ -560,7 +647,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
560
647
  on: state.on,
561
648
  status: state.status,
562
649
  missing: state.missing,
563
- asksActAs: declaredEntries(bundle).some((entry) => entry.permission === 'actAs'),
650
+ delegates: declaredEntries(bundle).some((entry) => entry.permission === USER_DELEGATE),
564
651
  disabledBy: state.disabledBy,
565
652
  ...(state.grant?.grantedBy
566
653
  ? {
@@ -688,10 +775,15 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
688
775
  message: `${name} is not an extension this site takes, so it was not installed: ${declared.refused.join('; ')}.`,
689
776
  }
690
777
  if (!consented(request, declared.permissions))
691
- return grantNeeded(name, declared.permissions, '', layoutChoice(declared.layout))
778
+ return grantNeeded(name, declared.permissions, '', layoutChoice(declared.layout), {
779
+ id: declared.id,
780
+ screens: declared.screens,
781
+ })
692
782
  const provenance = await provenanceAt(name, declared.dist)
693
783
  const refused = refusedBySignature(`${name}@${declared.version}`, provenance)
694
784
  if (refused) return refused
785
+ const beyond = levelRefused(name, declared.permissions, provenance, request)
786
+ if (beyond) return beyond
695
787
  // Pinned to the version whose tarball was checked, when one was.
696
788
  const outcome = await added(
697
789
  name,
@@ -699,6 +791,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
699
791
  version,
700
792
  request,
701
793
  declared.dist?.tarball ? { version: declared.version } : undefined,
794
+ { id: declared.id ?? name, integrity: declared.dist?.integrity },
702
795
  )
703
796
  return { ...outcome, provenance }
704
797
  },
@@ -746,13 +839,17 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
746
839
  reason: error instanceof Error ? error.message : String(error),
747
840
  }),
748
841
  )
749
- const refused = refusedBySignature(declared.name, provenance)
842
+ const refused =
843
+ refusedBySignature(declared.name, provenance) ??
844
+ levelRefused(declared.name, declared.permissions, provenance, request)
750
845
  if (refused) {
751
846
  discard()
752
847
  return refused
753
848
  }
754
849
  const previous = await rangeFor(declared.name)
755
- const outcome = await added(declared.name, `./${kept.path}`, undefined, request)
850
+ const outcome = await added(declared.name, `./${kept.path}`, undefined, request, undefined, {
851
+ id: declared.id,
852
+ })
756
853
  if (!outcome.ok) {
757
854
  discard()
758
855
  return { ...outcome, provenance }
@@ -762,7 +859,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
762
859
  ...outcome,
763
860
  provenance,
764
861
  file: kept.path,
765
- message: `${outcome.message} Commit ${kept.path} with package.json and bun.lock.`,
862
+ message: `${outcome.message} Commit ${kept.path} with it.`,
766
863
  }
767
864
  },
768
865
 
@@ -770,6 +867,22 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
770
867
  if (options.installs === false) return refusedHere(name, 'remove', options.installsElsewhere)
771
868
  if (!isValidPackageName(name))
772
869
  return { ok: false, message: `'${name}' is not a package name npm would accept.` }
870
+ // Story 326: removing one is deleting its root and its line.
871
+ const recorded = Object.entries(readRecord(options.siteDir)).find(
872
+ ([, line]) => line.name === name,
873
+ )
874
+ if (recorded) {
875
+ const [id] = recorded
876
+ const previous = await rangeFor(name)
877
+ rmSync(rootOf(options.siteDir, id), { recursive: true, force: true })
878
+ forgetExtension(options.siteDir, id)
879
+ options.extensions.invalidate()
880
+ removeUnnamed(previous)
881
+ return {
882
+ ok: true,
883
+ message: `${name} was removed. Commit the removal of ${ROOTS_DIR}/${id}/ and the change to ${RECORD_FILE}.`,
884
+ }
885
+ }
773
886
  const previous = await rangeFor(name)
774
887
  const result = await install('remove', name, options.siteDir)
775
888
  options.extensions.invalidate()
@@ -791,18 +904,40 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
791
904
  request: {
792
905
  applyContent?: boolean
793
906
  grant?: readonly string[]
794
- actAs?: string | null
907
+ delegateTo?: string | null
795
908
  by?: string | null
909
+ /** The person installing is an administrator: only one grants the upper levels (story 324). */
910
+ isAdmin?: boolean
796
911
  },
797
- checked?: { version: string },
912
+ checked: { version: string } | undefined,
913
+ into: { id: string; integrity?: string },
798
914
  ): Promise<InstallOutcome> {
799
- const result = await install('add', specifier, options.siteDir)
800
- options.extensions.invalidate()
801
- if (!result.ok)
915
+ // Story 326: into a root of its own, never the site's dependencies.
916
+ const root = prepareRoot(options.siteDir, into.id)
917
+ const inRoot = specifier.startsWith('./')
918
+ ? `file:${relative(root, join(options.siteDir, specifier)).split(sep).join('/')}`
919
+ : specifier
920
+ const result = await install('add', inRoot, root)
921
+ if (!result.ok) {
922
+ options.extensions.invalidate()
802
923
  return {
803
924
  ok: false,
804
925
  message: result.output || `Installing ${specifier} failed.`,
805
926
  }
927
+ }
928
+ const landed = readPackageJson(
929
+ join(packageInRoot(options.siteDir, into.id, name), 'package.json'),
930
+ )
931
+ recordExtension(options.siteDir, into.id, {
932
+ name,
933
+ version: landed?.version ?? version ?? 'unknown',
934
+ ...(into.integrity ? { integrity: into.integrity } : {}),
935
+ })
936
+ options.extensions.invalidate()
937
+ const undo = () => {
938
+ rmSync(root, { recursive: true, force: true })
939
+ forgetExtension(options.siteDir, into.id)
940
+ }
806
941
 
807
942
  const range = (await rangeFor(name)) ?? version ?? 'latest'
808
943
  const discovered = options.extensions.bundles()
@@ -814,7 +949,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
814
949
  problem.packageName === name && problem.problems.includes(SITE_PACKAGE_NOT_INSTALLED),
815
950
  )
816
951
  ) {
817
- await install('remove', name, options.siteDir)
952
+ undo()
818
953
  options.extensions.invalidate()
819
954
  return sitePackageRefused(name)
820
955
  }
@@ -827,7 +962,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
827
962
  // The version whose signature was checked is the one that has to land
828
963
  // (story 060): one published in between was never checked.
829
964
  if (checked && found.version !== checked.version) {
830
- await install('remove', name, options.siteDir)
965
+ undo()
831
966
  options.extensions.invalidate()
832
967
  return {
833
968
  ok: false,
@@ -837,12 +972,12 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
837
972
  // The version that landed is what counts: a release published between
838
973
  // reading the registry and installing may ask for more, or say nothing of why.
839
974
  if (isSchema3(found)) {
840
- await install('remove', name, options.siteDir)
975
+ undo()
841
976
  options.extensions.invalidate()
842
977
  return schema3Refused(name, `${name}@${found.version} turned out to`)
843
978
  }
844
979
  if (!consented(request, declaredEntries(found))) {
845
- await install('remove', name, options.siteDir)
980
+ undo()
846
981
  options.extensions.invalidate()
847
982
  return grantNeeded(
848
983
  name,
@@ -853,7 +988,15 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
853
988
  }
854
989
  // What was granted is recorded against the version that landed, for every
855
990
  // extension: a grant is what lets one run (story 309).
856
- await options.grants?.grant(found, request.by ?? null, { actAs: request.actAs ?? null })
991
+ const delegates = declaredPermissions(found).includes(USER_DELEGATE)
992
+ if (delegates && !request.delegateTo) {
993
+ undo()
994
+ options.extensions.invalidate()
995
+ return { ok: false, message: `${name} was not installed: ${DELEGATE_NEEDS_PERSON}.` }
996
+ }
997
+ await options.grants?.grant(found, request.by ?? null, {
998
+ delegateKey: delegates ? request.delegateTo : null,
999
+ })
857
1000
 
858
1001
  // The content half lands after the dependency, so a refused check leaves
859
1002
  // the package installed and says why, rather than undoing an install that
@@ -877,7 +1020,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
877
1020
  dependency: { name, range, version: found.version },
878
1021
  // The install lives in this node's node_modules until the dependency is
879
1022
  // 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.${
1023
+ message: `${name}@${found.version} is installed. Commit ${ROOTS_DIR}/${into.id}/ and ${RECORD_FILE} to keep it across deployments.${
881
1024
  found.carries.server
882
1025
  ? " Its server code runs only once your site's developers turn it on and deploy the site."
883
1026
  : ''
@@ -898,6 +1041,7 @@ function sitePackageRefused(name: string): { ok: false; message: string } {
898
1041
  /** What a packed bundle on this machine declares, read from its package.json, or why it cannot be installed. */
899
1042
  async function declaresIn(file: string): Promise<
900
1043
  | {
1044
+ id: string
901
1045
  name: string
902
1046
  version: string
903
1047
  server: boolean
@@ -916,9 +1060,15 @@ async function declaresIn(file: string): Promise<
916
1060
  const problems = validateBundlePackage(json)
917
1061
  if (problems.length > 0 || typeof json.name !== 'string' || typeof json.version !== 'string')
918
1062
  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 }
1063
+ const field = json.crombolo as {
1064
+ id: string
1065
+ server?: string
1066
+ permissions?: unknown
1067
+ settings?: unknown
1068
+ }
920
1069
  if (isSchema3Field(field)) return `${file} was not installed: ${SCHEMA_3_NOT_INSTALLED}.`
921
1070
  return {
1071
+ id: field.id,
922
1072
  name: json.name,
923
1073
  version: json.version,
924
1074
  server: field.server !== undefined,
@@ -970,31 +1120,42 @@ export const SCREENS_NOTICE = 'Its screens run in the browser of everyone who us
970
1120
  /**
971
1121
  * Whether an install request granted exactly what the extension asks for
972
1122
  * (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.
1123
+ * One that asks for nothing needs no grant.
974
1124
  */
975
1125
  function consented(
976
- request: { grant?: readonly string[]; actAs?: string | null },
1126
+ request: { grant?: readonly string[] },
977
1127
  asked: readonly DeclaredPermission[],
978
1128
  ): boolean {
979
1129
  const permissions = asked.map((entry) => entry.permission)
980
1130
  if (permissions.length === 0) return true
981
1131
  const granted = new Set(request.grant ?? [])
982
- if (permissions.includes('actAs') && !request.actAs) return false
983
1132
  return granted.size === new Set(permissions).size && permissions.every((p) => granted.has(p))
984
1133
  }
985
1134
 
1135
+ /** How many screens its manifest's entries name (story 323), for what it adds. */
1136
+ const screensOf = (field: { extensions?: unknown }): number =>
1137
+ Array.isArray(field.extensions)
1138
+ ? field.extensions.filter(
1139
+ (entry) => entry && typeof entry === 'object' && 'screen' in (entry as object),
1140
+ ).length
1141
+ : 0
1142
+
986
1143
  /** A refusal the screen answers by showing what it asks for, with the reasons, and the grant. */
987
1144
  function grantNeeded(
988
1145
  name: string,
989
1146
  asked: readonly DeclaredPermission[],
990
1147
  before = '',
991
1148
  layout?: InstallOutcome['layout'],
1149
+ about: { id?: string; screens?: number } = {},
992
1150
  ): InstallOutcome {
993
1151
  return {
994
1152
  ok: false,
995
1153
  needsGrant: true,
996
1154
  permissions: describePermissions(asked),
997
- asksActAs: asked.some((entry) => entry.permission === 'actAs'),
1155
+ level: levelOf(asked.map((entry) => entry.permission)),
1156
+ groups: groupsOf(asked, { screens: about.screens }),
1157
+ ...(about.id ? { id: about.id } : {}),
1158
+ delegates: asked.some((entry) => entry.permission === USER_DELEGATE),
998
1159
  ...(layout ? { layout } : {}),
999
1160
  message: `${before ? `${before} ` : ''}${name} asks for these permissions. Grant them, each as it asks, to install it.`,
1000
1161
  }
package/src/ports.ts CHANGED
@@ -28,7 +28,6 @@ import {
28
28
  import type { EventSink } from '@crombolo/content'
29
29
  import {
30
30
  CORE_SECTION_ALIASES,
31
- clientSections,
32
31
  DEFAULT_UPLOAD_SETTINGS,
33
32
  hasAccessToSensitiveData,
34
33
  isUploadAllowed,
@@ -257,7 +256,7 @@ function createCurrentUserPort(
257
256
  hasAccessToSensitiveData: hasAccessToSensitiveData(principal.groups),
258
257
  fallbackPermissions: principal.permissions,
259
258
  permissions,
260
- allowedSections: clientSections(principal),
259
+ allowedSections: [...principal.allowedSections],
261
260
  userGroupIds: principal.groupKeys.map((id) => ({ id })),
262
261
  }
263
262
  },
package/src/remote.ts CHANGED
@@ -45,7 +45,7 @@ import {
45
45
  } from '@crombolo/transfer'
46
46
  import { readAuditPageQuery, recordAudit } from './adapters/audit.ts'
47
47
  import { type BundleAdmin, settingsIn } from './bundle-admin.ts'
48
- import { actAsChoice } from './bundle-api.ts'
48
+ import { userKeyOf } from './bundle-api.ts'
49
49
  import { codeChanges, installedCode, planCode } from './bundle-code-install.ts'
50
50
  import {
51
51
  checkBundleContent,
@@ -878,6 +878,9 @@ export function createRemote(options: RemoteOptions): Remote {
878
878
  id: principal.ci ? null : principal.id,
879
879
  name: `${principal.name}${ciRun(principal)}`,
880
880
  email: principal.ci ? null : principal.email,
881
+ // A remote reaches extensions only with "Install code on this site", which is the
882
+ // grant itself: it counts as the administrator the back office asks for (story 324).
883
+ isAdmin: true,
881
884
  source: 'request' as const,
882
885
  ipAddress: null,
883
886
  forwardedFor: request.headers.get('x-forwarded-for'),
@@ -907,7 +910,8 @@ export function createRemote(options: RemoteOptions): Remote {
907
910
  grant: Array.isArray(body.grant)
908
911
  ? body.grant.filter((p): p is string => typeof p === 'string')
909
912
  : [],
910
- actAs: actAsChoice(body.actAs),
913
+ // A CI job has no key of its own: it names whom a job or an event acts for (story 325).
914
+ delegateTo: userKeyOf(body.delegateTo),
911
915
  },
912
916
  )
913
917
  return status === 200
@@ -957,7 +961,11 @@ export function createRemote(options: RemoteOptions): Remote {
957
961
  if (removing) {
958
962
  const name = decodeURIComponent(what.slice('installed/'.length))
959
963
  const outcome = await bundles.uninstall(actor, name, {
960
- revertContent: new URL(request.url).searchParams.get('revertContent') === 'true',
964
+ // Story 328: `dropContent`, `revertContent` before 0.61, still read for one release.
965
+ dropContent: ['dropContent', 'revertContent'].some(
966
+ (key) => new URL(request.url).searchParams.get(key) === 'true',
967
+ ),
968
+ dropData: new URL(request.url).searchParams.get('dropData') === 'true',
961
969
  })
962
970
  return outcome.ok
963
971
  ? Response.json(outcome)
@@ -974,7 +982,7 @@ export function createRemote(options: RemoteOptions): Remote {
974
982
  applyContent: body.applyContent === true,
975
983
  // Naming the grant is the consent: a script that names what it grants has said yes.
976
984
  grant,
977
- actAs: typeof body.actAs === 'string' ? body.actAs : null,
985
+ delegateTo: userKeyOf(body.delegateTo),
978
986
  settings: settingsIn(body.settings),
979
987
  })
980
988
  if (outcome.ok) return Response.json(outcome)