@crombolo/server 0.56.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,85 @@
1
+ /**
2
+ * What the CMS will run of an extension's queries (story 311): one statement
3
+ * that reads or writes rows, and nothing that leaves its own tables. The
4
+ * connection is already confined to them; this refuses what could undo that:
5
+ * `ATTACH` on SQLite, a role change on Postgres, or a second statement.
6
+ * docs/extensions.md, "Its own tables".
7
+ */
8
+
9
+ const ALLOWED_FIRST = new Set(['select', 'insert', 'update', 'delete', 'with', 'values', 'replace'])
10
+
11
+ /** Words that never appear in a query an extension needs, whatever they are part of. */
12
+ const REFUSED = new Set([
13
+ 'attach',
14
+ 'detach',
15
+ 'pragma',
16
+ 'vacuum',
17
+ 'load_extension',
18
+ 'set_config',
19
+ 'dblink',
20
+ 'dblink_exec',
21
+ 'lo_import',
22
+ 'lo_export',
23
+ 'pg_read_file',
24
+ 'pg_read_binary_file',
25
+ 'pg_ls_dir',
26
+ 'copy',
27
+ ])
28
+
29
+ /** The SQL with its comments, strings and quoted names taken out, so only its words are left. */
30
+ function words(sql: string): string {
31
+ let out = ''
32
+ let i = 0
33
+ while (i < sql.length) {
34
+ const c = sql[i] as string
35
+ const next = sql[i + 1]
36
+ if (c === '-' && next === '-') {
37
+ while (i < sql.length && sql[i] !== '\n') i++
38
+ out += ' '
39
+ } else if (c === '/' && next === '*') {
40
+ const end = sql.indexOf('*/', i + 2)
41
+ i = end === -1 ? sql.length : end + 2
42
+ out += ' '
43
+ } else if (c === "'" || c === '"' || c === '`') {
44
+ i++
45
+ while (i < sql.length) {
46
+ if (sql[i] === c) {
47
+ if (sql[i + 1] === c) i += 2
48
+ else break
49
+ } else i++
50
+ }
51
+ i++
52
+ out += c === "'" ? " '' " : ' _q_ '
53
+ } else if (c === '$') {
54
+ const tag = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(sql.slice(i))
55
+ if (tag) {
56
+ const end = sql.indexOf(tag[0], i + tag[0].length)
57
+ i = end === -1 ? sql.length : end + tag[0].length
58
+ out += " '' "
59
+ } else {
60
+ out += c
61
+ i++
62
+ }
63
+ } else {
64
+ out += c
65
+ i++
66
+ }
67
+ }
68
+ return out
69
+ }
70
+
71
+ /** Why the CMS will not run this for an extension, or undefined when it will. Pure. */
72
+ export function extensionSqlProblem(
73
+ sql: string,
74
+ _dialect: 'sqlite' | 'postgres',
75
+ ): string | undefined {
76
+ const bare = words(sql).trim().replace(/;\s*$/, '')
77
+ if (bare.includes(';')) return 'An extension may run one statement at a time.'
78
+ const tokens = bare.toLowerCase().match(/[a-z_][a-z0-9_]*/g) ?? []
79
+ const first = tokens[0]
80
+ if (!first || !ALLOWED_FIRST.has(first))
81
+ return `An extension may read and write rows of its own tables, not run ${first ? first.toUpperCase() : 'that'}.`
82
+ const refused = tokens.find((token) => REFUSED.has(token))
83
+ if (refused) return `An extension's query may not use ${refused.toUpperCase()}.`
84
+ return undefined
85
+ }
package/src/index.ts CHANGED
@@ -20,6 +20,13 @@ export * from './atomic-write.ts'
20
20
  export * from './backup.ts'
21
21
  export * from './boot-failure.ts'
22
22
  export * from './bundle-admin.ts'
23
+ export {
24
+ API_PERMISSIONS,
25
+ ApiRefusedError,
26
+ actAsChoice,
27
+ type BundleApi,
28
+ permissionsFor,
29
+ } from './bundle-api.ts'
23
30
  export * from './bundle-build.ts'
24
31
  export * from './bundle-code.ts'
25
32
  export * from './bundle-grants.ts'
@@ -54,6 +61,13 @@ export * from './email-postmark.ts'
54
61
  export * from './email-resend.ts'
55
62
  export * from './email-ses.ts'
56
63
  export * from './email-text.ts'
64
+ export {
65
+ entryCovers,
66
+ extensionEntryProblems,
67
+ settingsOf,
68
+ } from './extension-discovery.ts'
69
+ export { denoArguments, netHosts } from './extension-process.ts'
70
+ export { extensionSqlProblem } from './extension-sql.ts'
57
71
  export * from './extensions-notice.ts'
58
72
  export * from './external-sign-in.ts'
59
73
  export * from './file-intake.ts'
@@ -112,6 +126,7 @@ export * from './server.ts'
112
126
  export * from './server-events.ts'
113
127
  export * from './settings.ts'
114
128
  export * from './setup.ts'
129
+ export * from './signing-keys.ts'
115
130
  export * from './site-assets.ts'
116
131
  export { apiUserPrincipal, withSiteWrites } from './site-content.ts'
117
132
  export * from './site-content-values.ts'
@@ -122,11 +137,13 @@ export * from './site-public.ts'
122
137
  export * from './site-queries.ts'
123
138
  export * from './site-replace.ts'
124
139
  export * from './site-sections.ts'
140
+ export * from './site-trust.ts'
125
141
  export * from './status.ts'
126
142
  export * from './status-pages.ts'
127
143
  export * from './tar.ts'
128
144
  export * from './telemetry.ts'
129
145
  export * from './transfer-dashboard.ts'
146
+ export * from './trusted-signers-admin.ts'
130
147
  export * from './two-factor.ts'
131
148
  export * from './udt.ts'
132
149
  export * from './upgrade-summary.ts'
@@ -10,7 +10,7 @@
10
10
  *
11
11
  * An install is `bun add`, and then — unless the site or the request says not
12
12
  * to — the content the bundle carries, through the same installer as
13
- * `crombolo bundle install`. A bundle's server half is never loaded by an
13
+ * `crombolo extension install`. A bundle's server half is never loaded by an
14
14
  * install: that still takes an edit to `crombolo.config.ts` and a deploy.
15
15
  *
16
16
  * The search is proxied rather than done in the browser: it works where the
@@ -21,11 +21,18 @@ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync
21
21
  import { tmpdir } from 'node:os'
22
22
  import { join, resolve } from 'node:path'
23
23
  import {
24
+ askedPermissions,
24
25
  type BundlePackage,
26
+ type DeclaredPermission,
25
27
  describePermissions,
26
28
  EXTENSION_KEYWORD,
27
29
  type ExtensionRegistry,
30
+ isSchema3Field,
31
+ LEGACY_EXTENSION_KEYWORD,
28
32
  type PackageJson,
33
+ readSettings,
34
+ SCHEMA_3_NOT_INSTALLED,
35
+ SITE_PACKAGE_NOT_INSTALLED,
29
36
  validateBundlePackage,
30
37
  } from '@crombolo/backoffice-host'
31
38
  import {
@@ -34,7 +41,8 @@ import {
34
41
  localBundlePath,
35
42
  localBundlesNamed,
36
43
  } from '@crombolo/transfer'
37
- import { type BundleGrants, declaredPermissions } from './bundle-grants.ts'
44
+ import { type BundleGrants, declaredEntries, isSchema3 } from './bundle-grants.ts'
45
+ import { siteLayouts } from './components.ts'
38
46
  import { logger } from './logging.ts'
39
47
  import {
40
48
  type ProvenancePolicy,
@@ -111,6 +119,8 @@ export interface MarketplaceOptions {
111
119
  marketplaceUrl: string
112
120
  extensions: ExtensionRegistry
113
121
  fetch?: typeof fetch
122
+ /** The site's components, whose layouts an extension's page templates may sit in (story 312). */
123
+ componentsDir?: string
114
124
  /** Where `bun add` runs, which is the site that owns the package.json. */
115
125
  siteDir: string
116
126
  /** Overridden by tests; the real one shells out to Bun. */
@@ -153,12 +163,20 @@ export interface InstallOutcome {
153
163
  /** What happened to the content the bundle carries; absent when it carries none. */
154
164
  content?: ContentOutcome
155
165
  /**
156
- * Refused because the bundle runs code on the server and the request did not
157
- * accept that (story 194): the screen asks, and sends the install again.
166
+ * Refused because it asks for permissions the request did not grant, exactly
167
+ * (stories 222, 308): the screen shows them with their reasons, and sends the
168
+ * install again with the grant.
158
169
  */
159
- needsServerConsent?: boolean
160
- /** With `needsServerConsent`: what it asks to do with the site, to grant as a whole (story 222). */
161
- permissions?: { permission: string; allows: string }[]
170
+ needsGrant?: boolean
171
+ /** With `needsGrant`: what it asks for, each with its sentence, its reason and its origins. */
172
+ permissions?: { permission: string; allows: string; reason: string | null; origins?: string[] }[]
173
+ /** With `needsGrant`: it asks to act for a user, so the grant names whom (story 308). */
174
+ asksActAs?: boolean
175
+ /**
176
+ * With `needsGrant`: its page templates sit in a site layout, picked here
177
+ * (story 312). `suggested` is the one it names, when the site has it.
178
+ */
179
+ layout?: { key: string; label: string; values: string[]; suggested?: string }
162
180
  /** It changed the code the server loads, which runs once the site restarts (story 241). */
163
181
  restartPending?: boolean
164
182
  /** Where the version checked was built, from its signature (story 060). */
@@ -209,9 +227,10 @@ export interface Marketplace {
209
227
  version: string | undefined,
210
228
  options?: {
211
229
  applyContent?: boolean
212
- acceptServerCode?: boolean
213
- /** The permissions the administrator granted: the bundle's whole list (story 222). */
230
+ /** The permissions the administrator granted: the bundle's whole list (stories 222, 308). */
214
231
  grant?: readonly string[]
232
+ /** Whom it acts for, when it asks for `actAs`: `installer:<key>`, `caller` or `user:<key>`. */
233
+ actAs?: string | null
215
234
  /** Who is installing, recorded on the grant. */
216
235
  by?: string | null
217
236
  },
@@ -237,8 +256,8 @@ export interface Marketplace {
237
256
  file: string,
238
257
  options?: {
239
258
  applyContent?: boolean
240
- acceptServerCode?: boolean
241
259
  grant?: readonly string[]
260
+ actAs?: string | null
242
261
  by?: string | null
243
262
  },
244
263
  ): Promise<InstallOutcome>
@@ -286,7 +305,30 @@ export const bunInstaller: PackageInstaller = async (action, specifier, siteDir)
286
305
  }
287
306
  }
288
307
 
308
+ /** The layout setting a version declares, if it has page templates to place (story 312). */
309
+ type AskedLayout = { key: string; label: string; suggested?: string }
310
+
311
+ function layoutAsked(field: { settings?: unknown } | undefined): AskedLayout | undefined {
312
+ const read = readSettings(field?.settings)
313
+ if (!('settings' in read)) return undefined
314
+ const found = Object.entries(read.settings).find(([, setting]) => setting.type === 'layout')
315
+ if (!found) return undefined
316
+ const [key, setting] = found
317
+ return {
318
+ key,
319
+ label: setting.label,
320
+ ...(typeof setting.default === 'string' ? { suggested: setting.default } : {}),
321
+ }
322
+ }
323
+
289
324
  export function createMarketplace(options: MarketplaceOptions): Marketplace {
325
+ /** The site's layouts to pick from, the suggestion kept only when the site has it. */
326
+ const layoutChoice = (asked: AskedLayout | undefined): InstallOutcome['layout'] => {
327
+ if (!asked) return undefined
328
+ const values = options.componentsDir ? siteLayouts(options.componentsDir) : []
329
+ const { suggested, ...rest } = asked
330
+ return { ...rest, values, ...(suggested && values.includes(suggested) ? { suggested } : {}) }
331
+ }
290
332
  const call = options.fetch ?? fetch
291
333
  const install = options.install ?? bunInstaller
292
334
 
@@ -347,8 +389,15 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
347
389
  name: string,
348
390
  wanted?: string,
349
391
  ): Promise<
350
- | (BundlePackage['carries'] & { permissions: string[]; version: string; dist?: Dist })
392
+ | (BundlePackage['carries'] & {
393
+ permissions: DeclaredPermission[]
394
+ layout?: AskedLayout
395
+ version: string
396
+ dist?: Dist
397
+ })
351
398
  | 'not-a-bundle'
399
+ | 'site-package'
400
+ | 'schema-3'
352
401
  | 'unreachable'
353
402
  > => {
354
403
  try {
@@ -372,19 +421,26 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
372
421
  .sort(Bun.semver.order)
373
422
  .at(-1))
374
423
  const version = resolved ? versions[resolved] : undefined
424
+ // A site package is never installed, whatever a registry offers (story 306).
425
+ if ((version?.crombolo as { bundleType?: unknown } | undefined)?.bundleType === 'site')
426
+ return 'site-package'
375
427
  if (!resolved || !version || validateBundlePackage(version).length > 0) return 'not-a-bundle'
376
428
  const dist = (version as { dist?: Dist }).dist
377
429
  const field = version.crombolo as {
378
430
  extensions?: unknown[]
379
431
  content?: boolean
380
432
  server?: string
381
- permissions?: string[]
433
+ permissions?: unknown
434
+ settings?: unknown
382
435
  }
436
+ // Story 308: a version that says nothing of why it asks is not installed.
437
+ if (isSchema3Field(field)) return 'schema-3'
383
438
  return {
384
439
  extensions: Array.isArray(field.extensions) && field.extensions.length > 0,
385
440
  content: field.content === true,
386
441
  server: field.server !== undefined,
387
- permissions: Array.isArray(field.permissions) ? field.permissions : [],
442
+ permissions: askedPermissions(field),
443
+ layout: layoutAsked(field),
388
444
  version: resolved,
389
445
  ...(dist ? { dist } : {}),
390
446
  }
@@ -475,14 +531,23 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
475
531
  }
476
532
 
477
533
  /** A bundle's permissions, who approved them, and whether it is disabled, for the listing. */
478
- const grantOf = (bundle: BundlePackage) => {
479
- const declared = describePermissions(declaredPermissions(bundle))
480
- if (!bundle.carries.server || !options.grants)
481
- return { permissions: declared, on: true, disabledBy: null }
534
+ const grantOf = (bundle: BundlePackage) => ({
535
+ // Story 308: one written before permissions said why runs, flagged.
536
+ schema3: isSchema3(bundle),
537
+ ...grantStateOf(bundle),
538
+ })
539
+ const grantStateOf = (bundle: BundlePackage) => {
540
+ const declared = describePermissions(declaredEntries(bundle))
541
+ if (!options.grants)
542
+ return { permissions: declared, on: true, status: 'on', missing: [], disabledBy: null }
543
+ // Story 309: every extension runs on its grant, screens-only ones included.
482
544
  const state = options.grants.state(bundle)
483
545
  return {
484
546
  permissions: state.declared,
485
547
  on: state.on,
548
+ status: state.status,
549
+ missing: state.missing,
550
+ asksActAs: declaredEntries(bundle).some((entry) => entry.permission === 'actAs'),
486
551
  disabledBy: state.disabledBy,
487
552
  ...(state.grant?.grantedBy
488
553
  ? {
@@ -500,7 +565,9 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
500
565
  url: () => options.marketplaceUrl,
501
566
 
502
567
  async search(query) {
503
- const text = [`keywords:${options.keyword}`, query?.trim()].filter(Boolean).join(' ')
568
+ // Extensions published before 0.57 carry the old keyword, and are found too.
569
+ const keywords = [...new Set([options.keyword, LEGACY_EXTENSION_KEYWORD])]
570
+ const text = [`keywords:${keywords.join(',')}`, query?.trim()].filter(Boolean).join(' ')
504
571
  if (cached && cached.query === text && Date.now() - cached.at < CACHE_MS)
505
572
  return cached.listings.map((listing) => ({
506
573
  ...listing,
@@ -597,10 +664,12 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
597
664
  if (declared === 'not-a-bundle')
598
665
  return {
599
666
  ok: false,
600
- message: `${name} is not a bundle for this site, so it was not installed.`,
667
+ message: `${name} is not an extension for this site, so it was not installed.`,
601
668
  }
602
- if (declared.server && !consented(request, declared.permissions))
603
- return serverConsentNeeded(name, declared.permissions)
669
+ if (declared === 'site-package') return sitePackageRefused(name)
670
+ if (declared === 'schema-3') return schema3Refused(name)
671
+ if (!consented(request, declared.permissions))
672
+ return grantNeeded(name, declared.permissions, '', layoutChoice(declared.layout))
604
673
  const provenance = await provenanceAt(name, declared.dist)
605
674
  const refused = refusedBySignature(`${name}@${declared.version}`, provenance)
606
675
  if (refused) return refused
@@ -622,17 +691,24 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
622
691
  if (declared === 'unreachable')
623
692
  return { ok: false, message: `The package registry could not say what ${name} contains.` }
624
693
  if (declared === 'not-a-bundle')
625
- return { ok: false, message: `${name} is not a bundle for this site.` }
626
- const { dist, ...carries } = declared
627
- return { ok: true, ...carries, provenance: await provenanceAt(name, dist) }
694
+ return { ok: false, message: `${name} is not an extension for this site.` }
695
+ if (declared === 'site-package') return sitePackageRefused(name)
696
+ if (declared === 'schema-3') return schema3Refused(name)
697
+ const { dist, permissions, ...carries } = declared
698
+ return {
699
+ ok: true,
700
+ ...carries,
701
+ permissions: permissions.map((entry) => entry.permission),
702
+ provenance: await provenanceAt(name, dist),
703
+ }
628
704
  },
629
705
 
630
706
  async installFile(file, request = {}) {
631
707
  if (options.installs === false) return refusedHere(file, 'add', options.installsElsewhere)
632
708
  const declared = await declaresIn(file)
633
709
  if (typeof declared === 'string') return { ok: false, message: declared }
634
- if (declared.server && !consented(request, declared.permissions))
635
- return serverConsentNeeded(declared.name, declared.permissions)
710
+ if (!consented(request, declared.permissions))
711
+ return grantNeeded(declared.name, declared.permissions, '', layoutChoice(declared.layout))
636
712
  // Kept in the site's bundles/ (story 245), so it is committed and every
637
713
  // node, checkout and CI build installs the same file.
638
714
  const kept = keepInSite(file, declared)
@@ -690,8 +766,8 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
690
766
  version: string | undefined,
691
767
  request: {
692
768
  applyContent?: boolean
693
- acceptServerCode?: boolean
694
769
  grant?: readonly string[]
770
+ actAs?: string | null
695
771
  by?: string | null
696
772
  },
697
773
  checked?: { version: string },
@@ -705,12 +781,24 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
705
781
  }
706
782
 
707
783
  const range = (await rangeFor(name)) ?? version ?? 'latest'
708
- const found = options.extensions.bundles().bundles.find((bundle) => bundle.packageName === name)
784
+ const discovered = options.extensions.bundles()
785
+ const found = discovered.bundles.find((bundle) => bundle.packageName === name)
786
+ // The version that landed may turn out to be a site package: never kept (story 306).
787
+ if (
788
+ discovered.problems.some(
789
+ (problem) =>
790
+ problem.packageName === name && problem.problems.includes(SITE_PACKAGE_NOT_INSTALLED),
791
+ )
792
+ ) {
793
+ await install('remove', name, options.siteDir)
794
+ options.extensions.invalidate()
795
+ return sitePackageRefused(name)
796
+ }
709
797
  if (!found)
710
798
  return {
711
799
  ok: true,
712
800
  dependency: { name, range, version: version ?? range },
713
- message: `${name} was installed, but it is not a valid bundle, so nothing was added to the backoffice.`,
801
+ message: `${name} was installed, but it is not a valid extension, so nothing was added to the back office.`,
714
802
  }
715
803
  // The version whose signature was checked is the one that has to land
716
804
  // (story 060): one published in between was never checked.
@@ -723,18 +811,25 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
723
811
  }
724
812
  }
725
813
  // The version that landed is what counts: a release published between
726
- // reading the registry and installing may have brought server code.
727
- if (found.carries.server && !consented(request, declaredPermissions(found))) {
814
+ // reading the registry and installing may ask for more, or say nothing of why.
815
+ if (isSchema3(found)) {
728
816
  await install('remove', name, options.siteDir)
729
817
  options.extensions.invalidate()
730
- return serverConsentNeeded(
818
+ return schema3Refused(name, `${name}@${found.version} turned out to`)
819
+ }
820
+ if (!consented(request, declaredEntries(found))) {
821
+ await install('remove', name, options.siteDir)
822
+ options.extensions.invalidate()
823
+ return grantNeeded(
731
824
  name,
732
- declaredPermissions(found),
733
- `${name}@${found.version} turned out to run code on the server, or to ask for more than was granted, so it was removed again.`,
825
+ declaredEntries(found),
826
+ `${name}@${found.version} turned out to ask for more than was granted, so it was removed again.`,
827
+ layoutChoice(layoutAsked(found.field)),
734
828
  )
735
829
  }
736
- // What was granted is recorded against the version that landed.
737
- if (found.carries.server) await options.grants?.grant(found, request.by ?? null)
830
+ // What was granted is recorded against the version that landed, for every
831
+ // extension: a grant is what lets one run (story 309).
832
+ await options.grants?.grant(found, request.by ?? null, { actAs: request.actAs ?? null })
738
833
 
739
834
  // The content half lands after the dependency, so a refused check leaves
740
835
  // the package installed and says why, rather than undoing an install that
@@ -746,7 +841,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
746
841
  declined || !options.applyContent
747
842
  ? {
748
843
  applied: false,
749
- message: `Its content was not applied. Run \`crombolo bundle install ${name}\` to apply it.`,
844
+ message: `Its content was not applied. Run \`crombolo extension install ${name}\` to apply it.`,
750
845
  }
751
846
  : await options.applyContent(name).catch((error: unknown) => ({
752
847
  applied: false,
@@ -768,24 +863,43 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
768
863
  }
769
864
  }
770
865
 
866
+ /** A site package offered as a dependency: refused, saying how one is used (story 306). */
867
+ function sitePackageRefused(name: string): { ok: false; message: string } {
868
+ return {
869
+ ok: false,
870
+ message: `${name} is a site package, which is applied to a site with \`crombolo site apply\`, never installed, so it was not installed.`,
871
+ }
872
+ }
873
+
771
874
  /** What a packed bundle on this machine declares, read from its package.json, or why it cannot be installed. */
772
- async function declaresIn(
773
- file: string,
774
- ): Promise<{ name: string; version: string; server: boolean; permissions: string[] } | string> {
875
+ async function declaresIn(file: string): Promise<
876
+ | {
877
+ name: string
878
+ version: string
879
+ server: boolean
880
+ permissions: DeclaredPermission[]
881
+ layout?: AskedLayout
882
+ }
883
+ | string
884
+ > {
775
885
  const dir = mkdtempSync(join(tmpdir(), 'crombolo-bundle-file-'))
776
886
  try {
777
887
  await extractTarball(file, dir)
778
888
  const root = existsSync(join(dir, 'package', 'package.json')) ? join(dir, 'package') : dir
779
889
  const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as PackageJson
890
+ if ((json.crombolo as { bundleType?: unknown } | undefined)?.bundleType === 'site')
891
+ return sitePackageRefused(file).message
780
892
  const problems = validateBundlePackage(json)
781
893
  if (problems.length > 0 || typeof json.name !== 'string' || typeof json.version !== 'string')
782
- return `${file} is not a bundle for this site, so it was not installed.`
783
- const field = json.crombolo as { server?: string; permissions?: string[] }
894
+ return `${file} is not an extension for this site, so it was not installed.`
895
+ const field = json.crombolo as { server?: string; permissions?: unknown; settings?: unknown }
896
+ if (isSchema3Field(field)) return `${file} was not installed: ${SCHEMA_3_NOT_INSTALLED}.`
784
897
  return {
785
898
  name: json.name,
786
899
  version: json.version,
787
900
  server: field.server !== undefined,
788
- permissions: Array.isArray(field.permissions) ? field.permissions : [],
901
+ permissions: askedPermissions(field),
902
+ layout: layoutAsked(field),
789
903
  }
790
904
  } catch {
791
905
  return `${file} could not be read as a packed bundle, so it was not installed.`
@@ -810,32 +924,46 @@ function descriptionOf(directory: string): string {
810
924
  export const SCREENS_NOTICE = 'Its screens run in the browser of everyone who uses the back office.'
811
925
 
812
926
  /**
813
- * Whether an install request said yes to server code and granted exactly what
814
- * the bundle asks for (stories 194, 222): all of it, and nothing it did not ask.
927
+ * Whether an install request granted exactly what the extension asks for
928
+ * (stories 222, 308): all of it, nothing it did not ask, and whom it acts for
929
+ * when it asks for `actAs`. One that asks for nothing needs no grant.
815
930
  */
816
931
  function consented(
817
- request: { acceptServerCode?: boolean; grant?: readonly string[] },
818
- permissions: readonly string[],
932
+ request: { grant?: readonly string[]; actAs?: string | null },
933
+ asked: readonly DeclaredPermission[],
819
934
  ): boolean {
820
- if (request.acceptServerCode !== true) return false
935
+ const permissions = asked.map((entry) => entry.permission)
936
+ if (permissions.length === 0) return true
821
937
  const granted = new Set(request.grant ?? [])
938
+ if (permissions.includes('actAs') && !request.actAs) return false
822
939
  return granted.size === new Set(permissions).size && permissions.every((p) => granted.has(p))
823
940
  }
824
941
 
825
- /** A refusal the screen answers by asking for an explicit yes, and the grant (stories 194, 222). */
826
- function serverConsentNeeded(
942
+ /** A refusal the screen answers by showing what it asks for, with the reasons, and the grant. */
943
+ function grantNeeded(
827
944
  name: string,
828
- permissions: readonly string[],
945
+ asked: readonly DeclaredPermission[],
829
946
  before = '',
947
+ layout?: InstallOutcome['layout'],
830
948
  ): InstallOutcome {
831
949
  return {
832
950
  ok: false,
833
- needsServerConsent: true,
834
- permissions: describePermissions(permissions),
835
- message: `${before ? `${before} ` : ''}${name} runs code on the server, with access to the site's data, files and settings. Confirm that you trust its publisher, and approve what it asks to do, to install it.`,
951
+ needsGrant: true,
952
+ permissions: describePermissions(asked),
953
+ asksActAs: asked.some((entry) => entry.permission === 'actAs'),
954
+ ...(layout ? { layout } : {}),
955
+ message: `${before ? `${before} ` : ''}${name} asks for these permissions. Grant them, each as it asks, to install it.`,
836
956
  }
837
957
  }
838
958
 
959
+ /** A version written before permissions said why (story 308). */
960
+ function schema3Refused(
961
+ name: string,
962
+ before = `${name} was not installed:`,
963
+ ): { ok: false; message: string } {
964
+ return { ok: false, message: `${before} ${SCHEMA_3_NOT_INSTALLED}.` }
965
+ }
966
+
839
967
  /** What a site that does not install at runtime says instead, with what to do. */
840
968
  function refusedHere(
841
969
  name: string,
package/src/ports.ts CHANGED
@@ -357,6 +357,10 @@ export function resolveUserLinkSender(
357
357
  export interface DepsOptions {
358
358
  /** Published pages a site route answers in place of, for the health check (story 211). */
359
359
  hiddenByRoutes?: () => Promise<Array<{ route: string; owner: string; page: string; url: string }>>
360
+ /** Granted extensions that could not start, and why (story 311). */
361
+ failedExtensions?: () => readonly { id: string; reason: string }[]
362
+ /** Extensions whose `layout` setting names a layout the site no longer has (story 312). */
363
+ lostLayouts?: () => readonly { id: string; layout: string }[]
360
364
  siteSettingsFindings?: () => Promise<
361
365
  Array<{ kind: 'second' | 'deep'; name: string; counted?: string }>
362
366
  >
@@ -486,6 +490,9 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
486
490
  fetch: options.fetch,
487
491
  hiddenByRoutes: options.hiddenByRoutes,
488
492
  siteSettingsFindings: options.siteSettingsFindings,
493
+ bundleProblems: () => options.extensions.bundles().problems,
494
+ failedExtensions: options.failedExtensions,
495
+ lostLayouts: options.lostLayouts,
489
496
  })
490
497
  const tags = new TagRepository(options.db)
491
498
  deps.tags = { list: (filter) => tags.all(filter) }
@@ -615,6 +622,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
615
622
  siteName: options.config.siteName,
616
623
  nodeId: options.config.nodeId,
617
624
  marketplaceUrl: options.config.marketplaceUrl,
625
+ secretKey: options.config.secretKey,
618
626
  componentFiles: createTemplateFileStore(options.config.componentsDir, options.onViewsChange),
619
627
  mediaStore: mediaFiles.store,
620
628
  components: deps.components,