@crombolo/server 0.55.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.
Files changed (48) hide show
  1. package/package.json +16 -13
  2. package/src/actions.ts +6 -1
  3. package/src/adapters/bundles.ts +72 -6
  4. package/src/adapters/health.ts +30 -1
  5. package/src/bundle-admin.ts +246 -23
  6. package/src/bundle-api.ts +299 -0
  7. package/src/bundle-build.ts +4 -3
  8. package/src/bundle-grants.ts +133 -18
  9. package/src/bundle-install.ts +140 -11
  10. package/src/bundle-sections.ts +49 -4
  11. package/src/bundles.ts +87 -7
  12. package/src/component-templates-api.ts +27 -6
  13. package/src/components.ts +7 -0
  14. package/src/config.ts +56 -3
  15. package/src/content-events.ts +17 -1
  16. package/src/core.ts +219 -15
  17. package/src/created-extension.ts +101 -0
  18. package/src/extension-components.ts +157 -0
  19. package/src/extension-discovery.ts +180 -0
  20. package/src/extension-process.ts +854 -0
  21. package/src/extension-sql.ts +85 -0
  22. package/src/index.ts +21 -0
  23. package/src/marketplace.ts +182 -54
  24. package/src/outbound-address.ts +182 -0
  25. package/src/owner-jobs.ts +7 -1
  26. package/src/ports.ts +8 -0
  27. package/src/provenance.ts +181 -15
  28. package/src/remote.ts +62 -10
  29. package/src/routes.ts +13 -1
  30. package/src/schema.ts +37 -6
  31. package/src/seed/compile.ts +4 -2
  32. package/src/seed/export.ts +1 -1
  33. package/src/seed/values.ts +3 -3
  34. package/src/seo.ts +13 -5
  35. package/src/server.ts +192 -45
  36. package/src/settings.ts +12 -4
  37. package/src/signing-keys.ts +155 -0
  38. package/src/site-content-values.ts +97 -0
  39. package/src/site-content.ts +292 -0
  40. package/src/site-events.ts +65 -0
  41. package/src/site-file.ts +20 -6
  42. package/src/site-public.ts +1 -1
  43. package/src/site-sections.ts +1 -1
  44. package/src/site-services.ts +4 -0
  45. package/src/site-trust.ts +238 -0
  46. package/src/transfer-dashboard.ts +6 -0
  47. package/src/trusted-signers-admin.ts +132 -0
  48. package/src/webhooks.ts +182 -17
package/src/config.ts CHANGED
@@ -30,6 +30,7 @@ import type { JobSchedule } from './owner-jobs.ts'
30
30
  import type { ProvenancePolicy, SignaturePolicy } from './provenance.ts'
31
31
  import type { SchemaStore } from './schema-store.ts'
32
32
  import { setting } from './settings.ts'
33
+ import type { SiteEventHandler } from './site-events.ts'
33
34
  import type { SiteDatabaseConfig, SiteQueryModules } from './site-queries.ts'
34
35
  import type { TelemetryOptions } from './telemetry.ts'
35
36
 
@@ -523,6 +524,39 @@ export interface CromboloConfig {
523
524
  jobs?: SiteQueryModules
524
525
  /** When the site's jobs run by themselves: cron expressions in a timezone. */
525
526
  schedules?: JobSchedule[]
527
+ /**
528
+ * `site().content` (story 298): the client id of the API user the site's code
529
+ * acts as when it writes pages. Its permissions bound what the code may do, and
530
+ * every change is audited as it. Without it, each write answers `forbidden`.
531
+ */
532
+ content?: { actAs?: string }
533
+ /**
534
+ * Handlers for content events, by the names webhooks use (story 298), each run
535
+ * as a site job on a node that owns writes: `(event, { db, site, job })`.
536
+ * docs/rendering.md, "Content events".
537
+ */
538
+ events?: Readonly<Record<string, SiteEventHandler>>
539
+ /**
540
+ * What a webhook may reach (story 301): the server variables a header's
541
+ * `env:NAME` may name besides `CROMBOLO_WEBHOOK_*`, and whether deliveries may
542
+ * go to loopback, private and link-local addresses: by default only on a
543
+ * development site. docs/webhooks.md.
544
+ */
545
+ webhooks?: { headerVariables?: readonly string[]; allowPrivateAddresses?: boolean }
546
+ /**
547
+ * Installed extensions the site's code grants and sets (story 310), by bundle
548
+ * id: what it grants, as "Developer installed", and settings, which lock them
549
+ * in the back office. Plain data: nothing is imported.
550
+ * docs/bundles.md, "Extensions run once granted".
551
+ */
552
+ extensions?: Readonly<Record<string, ExtensionEntry>>
553
+ /**
554
+ * Keys this site trusts to sign the site bundles it applies, locked in
555
+ * Settings (story 316): a person's, a CI job's or another site's public line.
556
+ */
557
+ trustedKeys?: readonly { name: string; publicKey: string; kind?: 'user' | 'site' }[]
558
+ /** CI builds this site trusts to sign them, by Sigstore: `org/repo@v*` (story 316). */
559
+ trustedSources?: readonly { name: string; source: string }[]
526
560
  /**
527
561
  * Package names this installation provides to every site it runs, rather
528
562
  * than the site choosing them (story 177): a whole-site file leaves them out
@@ -583,6 +617,25 @@ export interface CromboloConfig {
583
617
  host: HostConfig | undefined
584
618
  }
585
619
 
620
+ /** One installed extension, as the config grants and sets it (story 310). */
621
+ export interface ExtensionEntry {
622
+ /** Exactly the permissions it may use; a version asking for more is off until this names it. */
623
+ grant?: readonly string[]
624
+ /** The origins its `http.outbound` may reach, when it asks for any. */
625
+ origins?: readonly string[]
626
+ /** Whom `actAs` acts for: `caller`, or `user:<key>`. */
627
+ actAs?: string
628
+ /** Its settings' values, locked in the back office. */
629
+ settings?: Readonly<Record<string, unknown>>
630
+ /**
631
+ * On a developer's machine only: more for its process to read and reach while
632
+ * the extension is being worked on. Refused when `NODE_ENV` is `production`.
633
+ */
634
+ dev?: { allowRead?: readonly string[]; allowNet?: readonly string[] }
635
+ /** How long a route, event or workflow of it may take, in milliseconds: 30 seconds unless set. */
636
+ timeoutMs?: number
637
+ }
638
+
586
639
  export type SiteConfig = CromboloConfig
587
640
 
588
641
  export const DEFAULTS = {
@@ -620,8 +673,8 @@ export const DEFAULTS = {
620
673
  logsDir: 'logs',
621
674
  scriptsDir: 'scripts',
622
675
  publicDir: 'public',
623
- marketplaceUrl: 'https://www.npmjs.com/search?q=keywords%3Acrombolo-bundle',
624
- packageKeyword: 'crombolo-bundle',
676
+ marketplaceUrl: 'https://www.npmjs.com/search?q=keywords%3Acrombolo-extension',
677
+ packageKeyword: 'crombolo-extension',
625
678
  npmRegistry: 'https://registry.npmjs.org',
626
679
  keepAllVersionsNewerThanDays: 7,
627
680
  keepLatestVersionPerDayForDays: 90,
@@ -1091,7 +1144,7 @@ export function describeDatabase(
1091
1144
  }
1092
1145
  }
1093
1146
 
1094
- export const VERSION = '0.55.0'
1147
+ export const VERSION = '0.57.0'
1095
1148
 
1096
1149
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1097
1150
  /** A positive number from a setting, else the default. */
@@ -38,6 +38,14 @@ export interface ContentEventSinkOptions {
38
38
  const subjectOf = (event: DocumentEvent): string | null =>
39
39
  'key' in event ? event.key : 'parentKey' in event ? event.parentKey : null
40
40
 
41
+ /** The cultures an event was about, when it was about some. */
42
+ const culturesOf = (event: DocumentEvent): string[] | null =>
43
+ 'cultures' in event && event.cultures ? [...event.cultures] : null
44
+
45
+ /** The site code a change came through (story 298), when it did. */
46
+ const viaOf = (actor: MediaActor): { via?: string } =>
47
+ actor.kind !== 'member' && actor.origin.via ? { via: actor.origin.via } : {}
48
+
41
49
  /** Who made a change, as the outbox keeps it: enough to name them and leave them out. */
42
50
  export const outboxActor = (actor: MediaActor) => {
43
51
  const memberKey = actorMemberKey(actor)
@@ -70,7 +78,15 @@ export function createContentEventSink(options: ContentEventSinkOptions): EventS
70
78
  const hook = webhookFor(event)
71
79
  const change = notificationFor(event)
72
80
  const webhook =
73
- hook && options.webhooks ? await options.webhooks.factsFor(tx, hook) : undefined
81
+ hook && options.webhooks
82
+ ? {
83
+ ...(await options.webhooks.factsFor(tx, hook)),
84
+ // For the site's own handlers (story 298): what it was about, and who did it.
85
+ cultures: culturesOf(event),
86
+ actor: { kind: actor.kind, name: actorName(actor), ...viaOf(actor) },
87
+ ...viaOf(actor),
88
+ }
89
+ : undefined
74
90
  const notification =
75
91
  change && options.notifier
76
92
  ? await options.notifier.factsFor(
package/src/core.ts CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  appendCacheInstruction,
13
13
  type JobWake,
14
14
  notifyJobs,
15
+ OwnerSetupNeededError,
15
16
  RedirectRepository,
16
17
  SITE_OWNER,
17
18
  UserGroupRepository,
@@ -36,7 +37,14 @@ import { recordAudit } from './adapters/audit.ts'
36
37
  import { createMediaSource, createPublishedContentSource } from './adapters/documents.ts'
37
38
  import { backOfficeUrl, documentEditUrl } from './back-office-url.ts'
38
39
  import { BACKOFFICE_EXTERNAL_PATH } from './backoffice-external.ts'
39
- import { APPROVED_BY_CODE, createBundleGrants, declaredPermissions } from './bundle-grants.ts'
40
+ import { actAsChoice, createBundleApi, extensionPrincipal } from './bundle-api.ts'
41
+ import {
42
+ APPROVED_BY_CODE,
43
+ createBundleGrants,
44
+ declaredOrigins,
45
+ declaredPermissions,
46
+ isSchema3,
47
+ } from './bundle-grants.ts'
40
48
  import {
41
49
  type BundleMediaFactory,
42
50
  createBundleMedia,
@@ -52,6 +60,13 @@ import { databaseFor, openTables, siteTablesProblems, tablesChains } from './cus
52
60
  import { attachDatabase, bootstrapDatabase } from './database.ts'
53
61
  import { createDiagnostics } from './diagnostics.ts'
54
62
  import { resolveEmailPort } from './email.ts'
63
+ import { createExtensionComponents } from './extension-components.ts'
64
+ import {
65
+ entryCovers,
66
+ extensionEntryProblems,
67
+ readRecordedExtensions,
68
+ startExtensions,
69
+ } from './extension-discovery.ts'
55
70
  import { createFormRegistry, formSigningSecret, signFormToken } from './form-submit.ts'
56
71
  import { formTypesOf } from './form-types.ts'
57
72
  import { createWorkflowRunner } from './form-workflows.ts'
@@ -66,6 +81,7 @@ import { logger } from './logging.ts'
66
81
  import { MediaFileStore } from './media-files.ts'
67
82
  import { mediaStoreFromEnvironment } from './media-store.ts'
68
83
  import { createNodeOperations } from './node-operations.ts'
84
+ import { OutboundRefused, pinnedFetch } from './outbound-address.ts'
69
85
  import {
70
86
  CORE_JOB_OWNER,
71
87
  createJobRunner,
@@ -78,6 +94,8 @@ import { createRedirectTracker } from './redirects.ts'
78
94
  import { withRemoteMedia } from './remote-media.ts'
79
95
  import { bootSchema, CacheInstructionPoller } from './schema.ts'
80
96
  import { publishSchema, type SchemaStore, useSchemaStore } from './schema-store.ts'
97
+ import { apiUserPrincipal, createSiteContent, userPrincipalByKey } from './site-content.ts'
98
+ import { SITE_EVENT_JOB, siteEventJob, siteEventProblems } from './site-events.ts'
81
99
  import { createSiteQueries, queryProblems } from './site-queries.ts'
82
100
  import { createSiteServices } from './site-services.ts'
83
101
  import { recordCacheLookup, startTelemetry, tracedDb, tracedEmail } from './telemetry.ts'
@@ -141,7 +159,46 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
141
159
  // On every role: a bundle's form types are needed wherever forms render and
142
160
  // submit, and its member and public routes wherever the site is served. Its
143
161
  // tables are migrated only by the nodes that own the database.
144
- const bundlePackages = extensions.bundles().bundles
162
+ const discovered = extensions.bundles()
163
+ const bundlePackages = discovered.bundles
164
+ let bundleDispatch: ((request: Request) => Promise<Response>) | undefined
165
+ // An extension from before story 306 does not say what it is: it is turned
166
+ // off, not mounted, and the site starts without it.
167
+ const untyped = new Set(discovered.problems.flatMap((found) => found.untyped?.id ?? []))
168
+ if (config.bundles.some((bundle) => untyped.has(bundle.id))) {
169
+ for (const bundle of config.bundles.filter((candidate) => untyped.has(candidate.id)))
170
+ log.warning(
171
+ 'The bundle {id} is turned off: it does not say it is an extension. Install a version that does.',
172
+ { id: bundle.id },
173
+ )
174
+ config.bundles = config.bundles.filter((bundle) => !untyped.has(bundle.id))
175
+ }
176
+ // Story 310: installed extensions run once granted, with nothing imported by
177
+ // the site; one still imported the old way is the site's own code, and runs in
178
+ // this process as before. Story 311: the rest each run in a Deno process.
179
+ const wiredByImport = new Set(
180
+ config.bundles
181
+ .filter((bundle) => bundlePackages.some((pkg) => pkg.id === bundle.id))
182
+ .map((bundle) => bundle.id),
183
+ )
184
+ for (const id of wiredByImport)
185
+ log.warning(
186
+ 'The extension {id} is imported in crombolo.config.ts, so it runs inside the site, unconfined: list it under extensions instead, and it runs apart.',
187
+ { id },
188
+ )
189
+ const entryProblems = extensionEntryProblems(config.extensions, bundlePackages)
190
+ if (entryProblems.length > 0)
191
+ throw new Error(`The installed extensions cannot be started:\n- ${entryProblems.join('\n- ')}`)
192
+ const extensionsStarted = await startExtensions(
193
+ config,
194
+ bundlePackages,
195
+ await readRecordedExtensions(config),
196
+ bundleLog,
197
+ )
198
+ const extensionProcesses = extensionsStarted.processes
199
+ const failedExtensions = extensionsStarted.failed
200
+ // In place: the caller's config is the server's, and later steps set it too.
201
+ config.bundles = [...config.bundles, ...extensionsStarted.bundles]
145
202
  const formTypes = formTypesOf(config)
146
203
  {
147
204
  const problems = [
@@ -155,19 +212,44 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
155
212
  ...siteTablesProblems(config),
156
213
  ...queryProblems(config),
157
214
  ...siteJobProblems(config),
215
+ ...siteEventProblems(config.events),
158
216
  ]
159
217
  if (site.length > 0)
160
218
  throw new Error(`The site's own tables cannot be used:\n- ${site.join('\n- ')}`)
161
219
  }
162
220
  setFormFieldTypes(formTypes.types, formTypes.renderers)
163
- const chains = tablesChains(config, config.bundles, bundlePackages)
221
+ let chains = tablesChains(config, config.bundles, bundlePackages)
164
222
  // A `web` node reads the site's tables for its named queries, and nothing of a
165
223
  // bundle's; a worker runs bundles' jobs, so it opens every owner's.
224
+ let opened = config.role === 'web' ? chains.filter((chain) => chain.id === SITE_OWNER) : chains
225
+ let booted: Awaited<ReturnType<typeof bootstrapDatabase>>
226
+ for (;;) {
227
+ try {
228
+ booted = owns ? await bootstrapDatabase(config, chains) : await attachDatabase(config, opened)
229
+ break
230
+ } catch (error) {
231
+ // An extension whose role this database user may not create is left off,
232
+ // saying what to run; the site starts without it (story 311).
233
+ const process = extensionProcesses.find(
234
+ (candidate) => error instanceof OwnerSetupNeededError && candidate.id === error.owner,
235
+ )
236
+ if (!process) throw error
237
+ await process.stop()
238
+ extensionProcesses.splice(extensionProcesses.indexOf(process), 1)
239
+ failedExtensions.push({ id: process.id, reason: (error as Error).message })
240
+ bundleLog(process.id).error(
241
+ '{id} could not be started, and the site starts without it: {reason}',
242
+ {
243
+ id: process.id,
244
+ reason: (error as Error).message,
245
+ },
246
+ )
247
+ config.bundles = config.bundles.filter((bundle) => bundle.id !== process.id)
248
+ chains = tablesChains(config, config.bundles, bundlePackages)
249
+ opened = config.role === 'web' ? chains.filter((chain) => chain.id === SITE_OWNER) : chains
250
+ }
251
+ }
166
252
  const siteChains = chains.filter((chain) => chain.id === SITE_OWNER)
167
- const opened = config.role === 'web' ? siteChains : chains
168
- const booted = owns
169
- ? await bootstrapDatabase(config, chains)
170
- : await attachDatabase(config, opened)
171
253
  const { seededAdminPassword } = booted
172
254
  // Story 262: on every role, before anything reads, so each statement is a span.
173
255
  await startTelemetry({
@@ -196,11 +278,20 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
196
278
  if (!runsJobs(config)) wake('jobs')
197
279
  },
198
280
  })
199
- for (const bundle of config.bundles) {
200
- const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
201
- if (!pkg) continue
281
+ for (const pkg of bundlePackages) {
282
+ const entry = config.extensions?.[pkg.id]
283
+ // The site's code grants what it names (story 310), or what an old-style
284
+ // import wires; anything else waits for a grant recorded here.
285
+ const byCode = wiredByImport.has(pkg.id) || entryCovers(pkg, entry)
286
+ if (!byCode) continue
287
+ const bundle = { id: pkg.id }
202
288
  // Recorded where the database is written, and audited when it changes.
203
- if (owns && (await bundleGrants.grant(pkg, APPROVED_BY_CODE)))
289
+ if (
290
+ owns &&
291
+ (await bundleGrants.grant(pkg, APPROVED_BY_CODE, {
292
+ actAs: entry?.actAs ? actAsChoice(entry.actAs) : undefined,
293
+ }))
294
+ )
204
295
  await recordAudit(db, {
205
296
  category: 'system',
206
297
  action: 'Grant',
@@ -209,12 +300,31 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
209
300
  detail: `approved by the site's code: ${declaredPermissions(pkg).join(', ') || 'nothing'}`,
210
301
  source: 'boot',
211
302
  })
212
- if (!bundleGrants.isOn(bundle.id))
213
- log.warning('The bundle {bundle} is disabled by {by}; enable it in Packages → Installed.', {
303
+ const state = bundleGrants.state(pkg)
304
+ if (state.status === 'off')
305
+ log.warning('The bundle {bundle} is turned off by {by}; turn it on in Bundles → Installed.', {
306
+ bundle: bundle.id,
307
+ by: state.disabledBy ?? 'an administrator',
308
+ })
309
+ else if (state.status === 'waiting')
310
+ log.warning('The bundle {bundle} waits for a grant of {missing}.', {
214
311
  bundle: bundle.id,
215
- by: bundleGrants.state(pkg).disabledBy ?? 'an administrator',
312
+ missing: state.missing.join(', '),
216
313
  })
217
314
  }
315
+ // Story 309: a version that asks for less than was granted keeps running, its
316
+ // grant narrowed to what it asks for, audited.
317
+ if (owns)
318
+ for (const pkg of bundlePackages)
319
+ if (await bundleGrants.narrow(pkg))
320
+ await recordAudit(db, {
321
+ category: 'system',
322
+ action: 'Grant',
323
+ entityType: 'Bundle',
324
+ entityName: `${pkg.packageName}@${pkg.version}`,
325
+ detail: `narrowed to what it asks for: ${declaredPermissions(pkg).join(', ') || 'nothing'}`,
326
+ source: 'boot',
327
+ })
218
328
  // A configured schema store is copied down before anything reads `schema/`, and
219
329
  // becomes the schema directory for this boot. Everything after here — loading,
220
330
  // validation, hashing, sync, the writer — works on files exactly as it always has.
@@ -328,9 +438,19 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
328
438
  // Before the poller, which tells it to look again on a `views` instruction
329
439
  // from another node: a closure over a `const` declared later would be a
330
440
  // temporal dead zone waiting for the first instruction to land.
441
+ const extensionComponents = createExtensionComponents(
442
+ extensionProcesses.map((process) => ({
443
+ process,
444
+ granted: () => bundleGrants.granted(process.id),
445
+ layout: () =>
446
+ typeof process.settings.layout === 'string' ? process.settings.layout : undefined,
447
+ log: bundleLog(process.id),
448
+ })),
449
+ )
331
450
  const renderer = new Renderer({
332
451
  cache,
333
452
  componentsDir: config.componentsDir,
453
+ extensionComponents,
334
454
  snapshots,
335
455
  renderTimeoutMs: config.renderTimeoutMs,
336
456
  islandsManifest: (generation) =>
@@ -361,7 +481,25 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
361
481
  filesWritable: config.schemaWritable,
362
482
  secretKey: config.secretKey,
363
483
  bundles: config.bundles,
484
+ // A development site's receivers are on this machine, as the Next.js template's is.
485
+ outbound: {
486
+ ...config.webhooks,
487
+ allowPrivateAddresses: config.webhooks?.allowPrivateAddresses ?? config.development,
488
+ },
364
489
  isBundleOn: (bundleId) => bundleGrants.isOn(bundleId),
490
+ bundleOrigins: (bundleId) => {
491
+ const pkg = bundlePackages.find((candidate) => candidate.id === bundleId)
492
+ return pkg && !isSchema3(pkg) ? declaredOrigins(pkg) : undefined
493
+ },
494
+ // The site's own handlers (story 298): each event queues the job that runs one.
495
+ siteEvents: {
496
+ handles: (alias) => typeof config.events?.[alias] === 'function',
497
+ deliver: async (event) => {
498
+ await jobRunner
499
+ .jobsFor(SITE_OWNER, `${event.alias} for ${event.key}`)
500
+ .enqueue(SITE_EVENT_JOB, event)
501
+ },
502
+ },
365
503
  onFilesChanged: config.schemaStore
366
504
  ? async () => {
367
505
  await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
@@ -434,6 +572,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
434
572
  return chain ? databaseFor(chain) : undefined
435
573
  },
436
574
  isOn: (bundleId) => bundleGrants.isOn(bundleId),
575
+ granted: (bundleId) => bundleGrants.granted(bundleId),
437
576
  jobs: (bundleId, queuedBy) => jobRunner.jobsFor(bundleId, queuedBy),
438
577
  pluginApiPath: `${paths.pluginPath}/api`,
439
578
  host: {
@@ -469,6 +608,47 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
469
608
  },
470
609
  log: (id) => bundleLog(id),
471
610
  callerHost: {
611
+ // Story 308: the site's areas, as the extension or whom it acts for.
612
+ api: (caller, bundle) => {
613
+ const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
614
+ const granted = () => bundleGrants.granted(bundle.id)
615
+ return createBundleApi({
616
+ bundleId: bundle.id,
617
+ origin: (config.applicationUrl || 'http://localhost').replace(/\/+$/, ''),
618
+ backOfficePath: config.backOfficePath,
619
+ granted,
620
+ dispatch: () => bundleDispatch,
621
+ principal: async () => {
622
+ const itself = extensionPrincipal(
623
+ { id: bundle.id, name: pkg?.name ?? bundle.id },
624
+ granted(),
625
+ )
626
+ const choice =
627
+ pkg && granted().includes('actAs') ? bundleGrants.state(pkg).grant?.actAs : null
628
+ if (!choice) return itself
629
+ if (choice === 'caller')
630
+ return caller.kind === 'backoffice' ? caller.principal : itself
631
+ return userPrincipalByKey(db, choice.slice(choice.indexOf(':') + 1))
632
+ },
633
+ })
634
+ },
635
+ fetch: (_caller, bundle) => {
636
+ const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
637
+ return {
638
+ fetch: async (input, init) => {
639
+ const url = new URL(input instanceof Request ? input.url : String(input))
640
+ const origins = declaredOrigins(pkg)
641
+ if (!origins.includes(url.origin))
642
+ throw new OutboundRefused(
643
+ `${bundle.id} may not reach ${url.origin}: its http.outbound names ${origins.join(', ') || 'nothing'}.`,
644
+ )
645
+ return pinnedFetch(input, init, {
646
+ allowPrivateAddresses:
647
+ config.webhooks?.allowPrivateAddresses ?? config.development,
648
+ })
649
+ },
650
+ }
651
+ },
472
652
  media: (caller, bundle) => {
473
653
  bundleMedia ??= createBundleMedia({
474
654
  db,
@@ -550,9 +730,21 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
550
730
  })
551
731
  await poller.start(config.development ? 2_000 : 5_000)
552
732
 
733
+ // The API user `content.actAs` names must be there to act as (story 298).
734
+ if (config.content?.actAs && !(await apiUserPrincipal(db, config.content.actAs)))
735
+ throw new Error(
736
+ `The config's content.actAs names "${config.content.actAs}", which is no API user's client id.`,
737
+ )
553
738
  const siteServicesFor = createSiteServices({
554
739
  db,
555
740
  cache,
741
+ content: createSiteContent({
742
+ db,
743
+ documents: operations.documents,
744
+ actAs: config.content?.actAs,
745
+ nodeState: schema.nodeState,
746
+ nodeId: schema.nodeId,
747
+ }),
556
748
  queries: createSiteQueries({ queries: config.queries, chain: siteChains[0] }),
557
749
  jobs: (queuedBy) => ({
558
750
  enqueue: async (name, payload) =>
@@ -561,6 +753,9 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
561
753
  }),
562
754
  })
563
755
  const siteJobs = siteJobHandlers(config.jobs)
756
+ // Each content event the site handles runs as a site job (story 298).
757
+ if (config.events && Object.keys(config.events).length > 0)
758
+ siteJobs.set(SITE_EVENT_JOB, siteEventJob(config.events))
564
759
  /** Every owner with jobs: the site's given its tables and `site()` as a visitor; a bundle's, its capabilities for no caller. */
565
760
  const jobOwners = (): JobOwner[] => [
566
761
  // Core's own queued work: a large media branch's trash, move or delete (story 246).
@@ -643,6 +838,10 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
643
838
  // Where jobs are left to a worker: whether one is running them (decision 4).
644
839
  const workerWatch = createWorkerWatch({ db, config })
645
840
  return {
841
+ /** The server's own handler, which `api` calls through once the server is built (story 308). */
842
+ setBundleDispatch(dispatch: (request: Request) => Promise<Response>) {
843
+ bundleDispatch = dispatch
844
+ },
646
845
  diagnostics,
647
846
  extensions,
648
847
  paths,
@@ -700,14 +899,19 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
700
899
  else jobRunner.wake()
701
900
  })
702
901
  },
703
- /** Stops listening, the jobs and the runner, letting what is running finish or go back. */
902
+ /** Stops listening, the jobs and the runner, letting what is running finish or go back; then the extensions' processes. */
704
903
  async stopJobs(): Promise<void> {
705
904
  workerWatch.stop()
706
905
  await listening?.()
707
906
  listening = undefined
708
907
  await jobRunner.stop()
709
908
  await jobs.stop()
909
+ await Promise.all(extensionProcesses.map((process) => process.stop()))
710
910
  },
911
+ /** The extensions that are granted but could not start, and why (story 311). */
912
+ failedExtensions,
913
+ /** The extensions' components, which render in their processes (story 312). */
914
+ extensionComponents,
711
915
  }
712
916
  }
713
917
 
@@ -0,0 +1,101 @@
1
+ /**
2
+ * A Bundle Editor definition built as an extension for other sites (story 312):
3
+ * the templates and partial views it picks are its code, under `src/components/`
4
+ * with a factory that declares them, and render in its own process where it is
5
+ * installed. Its schema and pages name them by its id, `<id>/<alias>`. The rest
6
+ * is its payload, as data. docs/bundles.md, "The Bundle Editor".
7
+ */
8
+ import type { BundleFile, BundlePackageInfo, ContentSet } from '@crombolo/transfer'
9
+
10
+ const COMPONENTS = 'components/'
11
+
12
+ /** The factory the generated entry exports, which `crombolo.server` names. */
13
+ export const CREATED_EXTENSION_FACTORY = 'extension'
14
+
15
+ /** Each `"alias"` in a TOML string list or string that names a picked component, as `"<id>/alias"`. */
16
+ function renamed(text: string, id: string, aliases: ReadonlySet<string>): string {
17
+ const quoted = (value: string) =>
18
+ value.replace(/"([^"]+)"/g, (whole, alias: string) =>
19
+ aliases.has(alias) ? `"${id}/${alias}"` : whole,
20
+ )
21
+ return text
22
+ .replace(
23
+ /^(\s*components\s*=\s*\[)([^\]]*)(\])/gm,
24
+ (_, open, list, close) => `${open}${quoted(list)}${close}`,
25
+ )
26
+ .replace(
27
+ /^(\s*default-component\s*=\s*)("[^"]*")/gm,
28
+ (_, key, value) => `${key}${quoted(value)}`,
29
+ )
30
+ }
31
+
32
+ /** A component file's alias: its path under `components/`, a folder template by its folder. */
33
+ const aliasOf = (path: string) =>
34
+ path
35
+ .slice(COMPONENTS.length)
36
+ .replace(/\/page\.tsx$/, '')
37
+ .replace(/\.tsx$/, '')
38
+
39
+ /**
40
+ * The payload without its components, its schema and pages naming them under
41
+ * `id`, and the code that carries them; no code when nothing is picked.
42
+ */
43
+ export function createdExtension(
44
+ id: string,
45
+ sections: readonly BundleFile[],
46
+ set: ContentSet,
47
+ ): { payload: BundleFile[]; set: ContentSet; code?: BundlePackageInfo['code'] } {
48
+ const components = sections.filter((file) => file.path.startsWith(COMPONENTS))
49
+ if (components.length === 0) return { payload: [...sections], set }
50
+ // Each component it carries, by alias: what the picks were, whichever way they were named.
51
+ const aliases = new Set(
52
+ components.filter((file) => file.path.endsWith('.tsx')).map((file) => aliasOf(file.path)),
53
+ )
54
+ const payload = sections
55
+ .filter((file) => !file.path.startsWith(COMPONENTS))
56
+ .map((file) =>
57
+ file.path.startsWith('schema/') && file.path.endsWith('.toml') && file.text !== undefined
58
+ ? { ...file, text: renamed(file.text, id, aliases) }
59
+ : file,
60
+ )
61
+ const renamedSet: ContentSet = {
62
+ ...set,
63
+ nodes: set.nodes.map((node) =>
64
+ node.template && aliases.has(node.template)
65
+ ? { ...node, template: `${id}/${node.template}` }
66
+ : node,
67
+ ),
68
+ }
69
+ const declared = components.filter((file) => file.path.endsWith('.tsx'))
70
+ const entry = [
71
+ '// Written by the Bundle Editor (story 312): the components this extension brings.',
72
+ ...declared.map((file, index) => `import * as c${index} from './${file.path}'`),
73
+ '',
74
+ `export function ${CREATED_EXTENSION_FACTORY}() {`,
75
+ ' return {',
76
+ ` id: ${JSON.stringify(id)},`,
77
+ " section: 'content',",
78
+ ' capabilities: [],',
79
+ ' components: {',
80
+ ...declared.map((file, index) => ` ${JSON.stringify(aliasOf(file.path))}: c${index},`),
81
+ ' },',
82
+ ' }',
83
+ '}',
84
+ '',
85
+ ].join('\n')
86
+ return {
87
+ payload,
88
+ set: renamedSet,
89
+ code: {
90
+ entry: 'src/index.ts',
91
+ server: CREATED_EXTENSION_FACTORY,
92
+ permissions: {
93
+ templates: 'Renders the templates and partial views it brings in your pages',
94
+ },
95
+ files: [
96
+ { path: 'src/index.ts', text: entry },
97
+ ...components.map((file) => ({ ...file, path: `src/${file.path}` })),
98
+ ],
99
+ },
100
+ }
101
+ }