@crombolo/server 0.44.0 → 0.46.1

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/server.ts CHANGED
@@ -147,6 +147,7 @@ import {
147
147
  import { createPublishedContentSource, loadDraftNode } from './adapters/documents.ts'
148
148
  import type { Approvals } from './approvals.ts'
149
149
  import { handleApprovalsApi } from './approvals-api.ts'
150
+ import { type BundleActor, createBundleAdmin } from './bundle-admin.ts'
150
151
  import type { BundleGrants } from './bundle-grants.ts'
151
152
  import { CommandError, installBundleContent } from './bundle-install.ts'
152
153
  import { BUNDLES_CHANGED_EVENT, type BundleReload, createBundleReloader } from './bundle-reload.ts'
@@ -206,7 +207,8 @@ import {
206
207
  readPreviewToken,
207
208
  signPreviewToken,
208
209
  } from './preview-tokens.ts'
209
- import { createRemote } from './remote.ts'
210
+ import { provenanceProblem } from './provenance.ts'
211
+ import { createRemote, type RestartOutcome } from './remote.ts'
210
212
  import { unknownHostProvided } from './site-file.ts'
211
213
  import { handleTransferAction, pendingTransfers } from './transfer-dashboard.ts'
212
214
  import { changeUrlOptions, urlSettingEditable } from './url-settings.ts'
@@ -232,7 +234,7 @@ import {
232
234
  requestCookies,
233
235
  runStage,
234
236
  } from './middleware.ts'
235
- import type { JobRunner } from './owner-jobs.ts'
237
+ import { CORE_JOB_OWNER, type JobRunner } from './owner-jobs.ts'
236
238
  import { callerAddress } from './rate-limit.ts'
237
239
  import { syncConfiguredRedirects } from './redirects.ts'
238
240
  import { createRoutes, type DeclaredRoute, siteRouteProblems } from './routes.ts'
@@ -320,7 +322,18 @@ export interface ServerHandle {
320
322
  close(): Promise<void>
321
323
  }
322
324
 
323
- export async function createServer(config: CromboloConfig = loadConfig()): Promise<ServerHandle> {
325
+ export interface ServerOptions {
326
+ /**
327
+ * Asks the supervising `crombolo start` for a new server and waits for it
328
+ * (story 241); absent when nothing supervises this one.
329
+ */
330
+ restart?: () => Promise<RestartOutcome>
331
+ }
332
+
333
+ export async function createServer(
334
+ config: CromboloConfig = loadConfig(),
335
+ serverOptions: ServerOptions = {},
336
+ ): Promise<ServerHandle> {
324
337
  if (config.role === 'worker')
325
338
  throw new Error('A worker serves no site: start it with createWorker (story 223).')
326
339
  configureLogging({
@@ -421,6 +434,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
421
434
  applyContentOnInstall: config.applyBundleContentOnInstall,
422
435
  installs: config.runtimeInstalls,
423
436
  installsElsewhere: config.installsElsewhere,
437
+ policy: config.bundlePolicy,
424
438
  applyContent: async (packageName) => {
425
439
  // A package from the marketplace is for anyone, so nothing in it can be
426
440
  // sealed; one that is is refused rather than half applied.
@@ -758,10 +772,20 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
758
772
  },
759
773
  )
760
774
  : undefined
775
+ const bundleAdmin = createBundleAdmin({ db, config, marketplace, extensions, bundleGrants })
776
+ const actorOf = (principal: Principal, request: Request): BundleActor => ({
777
+ id: principal.id,
778
+ name: principal.name,
779
+ email: principal.email,
780
+ source: 'request',
781
+ ...clientAddress(request),
782
+ })
761
783
  const remote = createRemote({
762
784
  db,
763
785
  config,
764
786
  authenticate,
787
+ bundles: bundleAdmin,
788
+ restart: serverOptions.restart,
765
789
  onApplied: () => {
766
790
  cache.invalidate()
767
791
  mediaCache.clear()
@@ -1184,6 +1208,9 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1184
1208
  // credentials anywhere near it.
1185
1209
  const auditPath = `${paths.pluginPath}/api/audit`
1186
1210
  const jobsPath = `${paths.pluginPath}/api/jobs`
1211
+ const mediaJobsPath = `${paths.pluginPath}/api/media-jobs`
1212
+ /** What an open back office hears when a media change is queued (story 246); its key is the job's id. */
1213
+ const MEDIA_JOB_QUEUED_EVENT = { eventSource: 'Crombolo:MediaJob', eventType: 'Queued' } as const
1187
1214
  const hostTokenPath = `${paths.pluginPath}/api/host-token`
1188
1215
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1189
1216
  const bundleInstallPaths = new Set(
@@ -1283,6 +1310,10 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1283
1310
  const response = await serveBackOffice(request, url)
1284
1311
  if (response) {
1285
1312
  if (response.ok) await auditPluginWrite(request, pathname)
1313
+ // A media change too large for the request is queued (story 246): open back
1314
+ // offices hear its id from the node that took it, wherever the job runs.
1315
+ const job = response.headers.get('crombolo-job')
1316
+ if (job) events.broadcast('notify', [{ ...MEDIA_JOB_QUEUED_EVENT, key: job }])
1286
1317
  return response
1287
1318
  }
1288
1319
  }
@@ -1301,25 +1332,13 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1301
1332
  }
1302
1333
 
1303
1334
  // Islands (story 209): the loader, and each generation's browser code.
1304
- if (pathname === ISLAND_LOADER_PATH)
1305
- return new Response(ISLAND_LOADER_SCRIPT, {
1306
- headers: {
1307
- 'content-type': 'text/javascript; charset=utf-8',
1308
- 'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1309
- },
1310
- })
1335
+ if (pathname === ISLAND_LOADER_PATH) return siteScript(ISLAND_LOADER_SCRIPT)
1311
1336
  if (pathname.startsWith(`${ISLANDS_PATH}/`))
1312
1337
  return islandFile(pathname.slice(ISLANDS_PATH.length + 1))
1313
1338
 
1314
1339
  // The progressive-enhancement script. A site adds it to a layout; a form
1315
1340
  // works without it, so nothing emits it automatically.
1316
- if (pathname === FORM_SCRIPT_PATH)
1317
- return new Response(FORM_SCRIPT, {
1318
- headers: {
1319
- 'content-type': 'text/javascript; charset=utf-8',
1320
- 'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1321
- },
1322
- })
1341
+ if (pathname === FORM_SCRIPT_PATH) return siteScript(FORM_SCRIPT)
1323
1342
 
1324
1343
  // A visitor posting a form. Before the renderer, which would otherwise try
1325
1344
  // to resolve `/crombolo/forms/...` as a page.
@@ -1332,16 +1351,10 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1332
1351
  : new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST' } })
1333
1352
  }
1334
1353
 
1335
- // The script that calls the site's routes as a member, wherever the site is served.
1336
- if (config.role !== 'api') {
1337
- if (pathname === BUNDLE_SCRIPT_PATH)
1338
- return new Response(BUNDLE_SCRIPT, {
1339
- headers: {
1340
- 'content-type': 'text/javascript; charset=utf-8',
1341
- 'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1342
- },
1343
- })
1344
- }
1354
+ // The script that calls the site's routes as a member: on every node, as the
1355
+ // other site scripts are, so a proxy that sends `/crombolo/*` to the api node
1356
+ // still serves it (story 220).
1357
+ if (pathname === BUNDLE_SCRIPT_PATH) return siteScript(BUNDLE_SCRIPT)
1345
1358
 
1346
1359
  // Not on an `api` node, which serves no public site to describe.
1347
1360
  if ((pathname === '/sitemap.xml' || pathname === '/robots.txt') && config.role !== 'api')
@@ -1426,6 +1439,16 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1426
1439
  }
1427
1440
  }
1428
1441
 
1442
+ /** One of the scripts a site's pages load, answered alike on every node. */
1443
+ function siteScript(body: string): Response {
1444
+ return new Response(body, {
1445
+ headers: {
1446
+ 'content-type': 'text/javascript; charset=utf-8',
1447
+ 'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1448
+ },
1449
+ })
1450
+ }
1451
+
1429
1452
  /** The site's stylesheets and scripts, or its pages. */
1430
1453
  async function siteFiles(request: Request, run?: ChainRun): Promise<Response> {
1431
1454
  const url = new URL(request.url)
@@ -1769,11 +1792,22 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1769
1792
  }
1770
1793
  }
1771
1794
 
1772
- if (action === 'installed' && request.method === 'GET') {
1795
+ if (action === 'installed' && request.method === 'GET')
1796
+ return Response.json(await bundleAdmin.installed())
1797
+
1798
+ // Where a version was built, for the Install panel before anything is
1799
+ // installed (story 060), and whether this site would take it.
1800
+ if (action === 'signature' && request.method === 'GET') {
1801
+ const name = url.searchParams.get('name') ?? ''
1802
+ const version = url.searchParams.get('version') ?? undefined
1803
+ const inspected = await marketplace.inspect(name, version)
1804
+ if (!inspected.ok) return Response.json({ ok: false, message: inspected.message })
1773
1805
  return Response.json({
1774
- installs: config.runtimeInstalls,
1775
- installsElsewhere: config.runtimeInstalls ? null : (config.installsElsewhere ?? null),
1776
- items: await marketplace.installed(),
1806
+ ok: true,
1807
+ version: inspected.version,
1808
+ provenance: inspected.provenance,
1809
+ refused: provenanceProblem(inspected.provenance, config.bundlePolicy) ?? null,
1810
+ policy: config.bundlePolicy,
1777
1811
  })
1778
1812
  }
1779
1813
 
@@ -1786,43 +1820,25 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1786
1820
  grant?: unknown
1787
1821
  }
1788
1822
  const name = typeof body.name === 'string' ? body.name : ''
1789
- const version = typeof body.version === 'string' ? body.version : undefined
1790
- const acceptServerCode = body.acceptServerCode === true
1791
- const grant = Array.isArray(body.grant)
1792
- ? body.grant.filter((p): p is string => typeof p === 'string')
1793
- : []
1823
+ const actor = actorOf(principal, request)
1794
1824
  const outcome =
1795
1825
  action === 'install'
1796
- ? await marketplace.install(name, version, {
1826
+ ? await bundleAdmin.install(actor, {
1827
+ name,
1828
+ version: typeof body.version === 'string' ? body.version : undefined,
1797
1829
  applyContent: body.applyContent !== false,
1798
- acceptServerCode,
1799
- grant,
1800
- by: principal.email,
1830
+ acceptServerCode: body.acceptServerCode === true,
1831
+ grant: Array.isArray(body.grant)
1832
+ ? body.grant.filter((p): p is string => typeof p === 'string')
1833
+ : [],
1801
1834
  })
1802
- : await marketplace.uninstall(name)
1835
+ : await bundleAdmin.uninstall(actor, name)
1803
1836
  log.info('{user} {action} the package {name}: {outcome}', {
1804
1837
  user: principal.email,
1805
1838
  action: action === 'install' ? 'installed' : 'removed',
1806
1839
  name,
1807
1840
  outcome: outcome.ok ? 'ok' : outcome.message,
1808
1841
  })
1809
- // One entry per install, naming the package and whether server code
1810
- // was accepted (story 194); the generic plugin-write entry skips these.
1811
- if (outcome.ok)
1812
- await recordAudit(db, {
1813
- category: 'system',
1814
- action: action === 'install' ? 'Install' : 'Uninstall',
1815
- entityType: 'Bundle',
1816
- entityName: outcome.dependency ? `${name}@${outcome.dependency.version}` : name,
1817
- detail:
1818
- action === 'install' && acceptServerCode
1819
- ? `accepted server code; granted ${grant.length > 0 ? grant.join(', ') : 'nothing'}`
1820
- : null,
1821
- source: 'request',
1822
- userKey: principal.id,
1823
- userName: principal.name,
1824
- ...clientAddress(request),
1825
- })
1826
1842
  return Response.json(outcome, { status: outcome.ok ? 200 : 400 })
1827
1843
  }
1828
1844
 
@@ -1830,36 +1846,12 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1830
1846
  // administrator can disable one, and enable it again.
1831
1847
  if ((action === 'disable' || action === 'enable') && request.method === 'POST') {
1832
1848
  const body = (await request.json().catch(() => ({}))) as { id?: unknown }
1833
- const id = typeof body.id === 'string' ? body.id : ''
1834
- const pkg = extensions.bundles().bundles.find((candidate) => candidate.id === id)
1835
- if (!pkg?.carries.server)
1836
- return Response.json(
1837
- { ok: false, message: `No installed bundle with a server half is called "${id}".` },
1838
- { status: 404 },
1839
- )
1840
- const state =
1841
- action === 'disable'
1842
- ? await bundleGrants.disable(pkg, principal.email)
1843
- : await bundleGrants.enable(pkg)
1844
- await recordAudit(db, {
1845
- category: 'system',
1846
- action: action === 'disable' ? 'Disable' : 'Enable',
1847
- entityType: 'Bundle',
1848
- entityName: `${pkg.packageName}@${pkg.version}`,
1849
- detail: action === 'disable' ? 'disabled; it is off' : 'enabled; it runs again',
1850
- source: 'request',
1851
- userKey: principal.id,
1852
- userName: principal.name,
1853
- ...clientAddress(request),
1854
- })
1855
- return Response.json({
1856
- ok: true,
1857
- on: state.on,
1858
- message:
1859
- action === 'disable'
1860
- ? `${pkg.name} is turned off until it is enabled again.`
1861
- : `${pkg.name} is turned on.`,
1862
- })
1849
+ const { status, ...outcome } = await bundleAdmin.setEnabled(
1850
+ actorOf(principal, request),
1851
+ typeof body.id === 'string' ? body.id : '',
1852
+ action === 'enable',
1853
+ )
1854
+ return Response.json(outcome, { status })
1863
1855
  }
1864
1856
 
1865
1857
  return new Response('Not Found', { status: 404 })
@@ -2247,6 +2239,27 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2247
2239
  if (response) return response
2248
2240
  }
2249
2241
 
2242
+ // Non-contract, Media: how a large branch's queued trash, move or delete is
2243
+ // getting on (story 246), for anyone with the Media section, media jobs only.
2244
+ const mediaJob = /^\/([0-9a-f-]{36})$/i.exec(
2245
+ pathname.startsWith(mediaJobsPath) ? pathname.slice(mediaJobsPath.length) : '',
2246
+ )
2247
+ if (mediaJob && request.method === 'GET') {
2248
+ const principal = await authenticate(request)
2249
+ if (!principal) return new Response('Unauthorized', { status: 401 })
2250
+ if (!hasSection(principal, 'media')) return new Response('Forbidden', { status: 403 })
2251
+ const job = await new JobRepository(db).get(mediaJob[1] as string)
2252
+ if (!job || job.owner !== CORE_JOB_OWNER || !job.name.startsWith('media.'))
2253
+ return new Response('Not Found', { status: 404 })
2254
+ return Response.json({
2255
+ id: job.id,
2256
+ state: job.state,
2257
+ progress: job.progress,
2258
+ error: job.lastError,
2259
+ finishedAt: job.finishedAt?.toISOString() ?? null,
2260
+ })
2261
+ }
2262
+
2250
2263
  // Non-contract, Settings: every owner's background jobs, and retrying a
2251
2264
  // failed one by hand (story 187).
2252
2265
  if (pathname === jobsPath || pathname.startsWith(`${jobsPath}/`)) {
package/src/settings.ts CHANGED
@@ -315,6 +315,22 @@ const DECLARED = [
315
315
  description:
316
316
  'The Packages section installs and removes packages on the running site. Off, they are added to `package.json` and deployed.',
317
317
  },
318
+ {
319
+ env: 'CROMBOLO_BUNDLE_SIGNATURES',
320
+ kind: 'enum',
321
+ values: ['optional', 'required'],
322
+ default: 'optional',
323
+ section: 'Back office and bundles',
324
+ description:
325
+ 'Whether this site takes only bundles signed in GitHub Actions with `crombolo bundle sign`. A signature that does not check out is refused either way.',
326
+ },
327
+ {
328
+ env: 'CROMBOLO_BUNDLE_SOURCES',
329
+ kind: 'list',
330
+ section: 'Back office and bundles',
331
+ description:
332
+ 'Where a signed bundle has to come from, separated by commas: `org/*`, `org/repo`, or `org/repo@v*` for its tags. Empty takes signed bundles from anywhere.',
333
+ },
318
334
  {
319
335
  env: 'CROMBOLO_INSTALLS_ELSEWHERE_MESSAGE',
320
336
  kind: 'string',
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Changes to a webhook kept in the site's files (story 251): its address,
3
+ * events, content types, headers and whether it is on. Pure; the rules every
4
+ * webhook is held to are `webhookProblems`'s, which the caller runs.
5
+ */
6
+ import { envReference, type WebhookDefinition } from './webhook-files.ts'
7
+
8
+ export type WebhookEditResult =
9
+ | { ok: true; webhook: WebhookDefinition }
10
+ | { ok: false; reason: string }
11
+
12
+ export interface WebhookChanges {
13
+ name?: string
14
+ description?: string
15
+ url?: string
16
+ enabled?: boolean
17
+ addEvents?: readonly string[]
18
+ removeEvents?: readonly string[]
19
+ /** Content types by alias, as a file names them. */
20
+ addContentTypes?: readonly string[]
21
+ removeContentTypes?: readonly string[]
22
+ /** Header name to its value; in a file, only `env:NAME`. */
23
+ setHeaders?: Readonly<Record<string, string>>
24
+ removeHeaders?: readonly string[]
25
+ }
26
+
27
+ const added = (list: readonly string[], more: readonly string[] = []) => [
28
+ ...list,
29
+ ...more.filter((item) => !list.includes(item)),
30
+ ]
31
+ const without = (list: readonly string[], less: readonly string[] = []) =>
32
+ list.filter((item) => !less.includes(item))
33
+
34
+ export function updateWebhook(
35
+ webhook: WebhookDefinition,
36
+ changes: WebhookChanges,
37
+ ): WebhookEditResult {
38
+ for (const event of changes.removeEvents ?? [])
39
+ if (!webhook.events.includes(event))
40
+ return { ok: false, reason: `it is not sent on "${event}"` }
41
+ for (const type of changes.removeContentTypes ?? [])
42
+ if (!webhook.contentTypeKeys.includes(type))
43
+ return { ok: false, reason: `it is not limited to the content type "${type}"` }
44
+ for (const name of changes.removeHeaders ?? [])
45
+ if (!(name in webhook.headers)) return { ok: false, reason: `it sends no header "${name}"` }
46
+ for (const [name, value] of Object.entries(changes.setHeaders ?? {}))
47
+ if (!envReference(value))
48
+ return {
49
+ ok: false,
50
+ reason: `the header "${name}" would put its value in the site's files: give it as env:NAME and set NAME on the server`,
51
+ }
52
+ const headers = { ...webhook.headers, ...changes.setHeaders }
53
+ for (const name of changes.removeHeaders ?? []) delete headers[name]
54
+ return {
55
+ ok: true,
56
+ webhook: {
57
+ ...webhook,
58
+ ...(changes.name !== undefined ? { name: changes.name || null } : {}),
59
+ ...(changes.description !== undefined ? { description: changes.description || null } : {}),
60
+ ...(changes.url !== undefined ? { url: changes.url } : {}),
61
+ ...(changes.enabled !== undefined ? { enabled: changes.enabled } : {}),
62
+ events: without(added(webhook.events, changes.addEvents), changes.removeEvents),
63
+ contentTypeKeys: without(
64
+ added(webhook.contentTypeKeys, changes.addContentTypes),
65
+ changes.removeContentTypes,
66
+ ),
67
+ headers,
68
+ },
69
+ }
70
+ }