@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/server.ts CHANGED
@@ -47,9 +47,11 @@ import {
47
47
  serializeCookie,
48
48
  } from '@crombolo/auth'
49
49
  import {
50
+ backOfficePolicy,
50
51
  collectManifests,
51
52
  type createBackOfficePaths,
52
53
  isSpaRoute,
54
+ newNonce,
53
55
  renderBackOfficeShell,
54
56
  renderDeviceShell,
55
57
  renderLoginShell,
@@ -164,14 +166,15 @@ import {
164
166
  import { createPublishedContentSource, loadDraftNode } from './adapters/documents.ts'
165
167
  import type { Approvals } from './approvals.ts'
166
168
  import { handleApprovalsApi } from './approvals-api.ts'
167
- import { type BundleActor, createBundleAdmin } from './bundle-admin.ts'
168
- import type { BundleGrants } from './bundle-grants.ts'
169
+ import { type BundleActor, createBundleAdmin, settingsIn } from './bundle-admin.ts'
170
+ import { actAsChoice, actingPrincipalOf } from './bundle-api.ts'
171
+ import { type BundleGrants, declaredOrigins } from './bundle-grants.ts'
169
172
  import { CommandError, installBundleContent } from './bundle-install.ts'
170
173
  import { BUNDLES_CHANGED_EVENT, type BundleReload, createBundleReloader } from './bundle-reload.ts'
171
174
  import { bundleRouteGroups } from './bundles.ts'
172
175
  import { busyResponse } from './busy.ts'
173
176
  import { handleComponentTemplates } from './component-templates-api.ts'
174
- import { checkTypes, listEmailTemplates } from './components.ts'
177
+ import { checkTypes, listEmailTemplates, siteLayouts } from './components.ts'
175
178
  import {
176
179
  type CromboloConfig,
177
180
  listeningBodyLimit,
@@ -245,6 +248,7 @@ import {
245
248
  stopTelemetry,
246
249
  } from './telemetry.ts'
247
250
  import { handleTransferAction, pendingTransfers } from './transfer-dashboard.ts'
251
+ import { createTrustedSignersAdmin } from './trusted-signers-admin.ts'
248
252
  import { changeUrlOptions, urlSettingEditable } from './url-settings.ts'
249
253
  import type { JobsStatus } from './worker-watch.ts'
250
254
 
@@ -272,9 +276,9 @@ import {
272
276
  runStage,
273
277
  } from './middleware.ts'
274
278
  import { CORE_JOB_OWNER, type JobRunner } from './owner-jobs.ts'
275
- import { callerAddress } from './rate-limit.ts'
279
+ import { callerAddress, RateLimiter } from './rate-limit.ts'
276
280
  import { syncConfiguredRedirects } from './redirects.ts'
277
- import { createRoutes, type DeclaredRoute, siteRouteProblems } from './routes.ts'
281
+ import { createRoutes, type DeclaredRoute, SITE_ROUTE_OWNER, siteRouteProblems } from './routes.ts'
278
282
  import { componentAliasesIn, importSchema, type SchemaBoot, watchSchema } from './schema.ts'
279
283
  import { publishSchema, type SchemaStore } from './schema-store.ts'
280
284
  import { createSeoHost, originOf, publicOrigin } from './seo.ts'
@@ -451,6 +455,9 @@ export async function createServer(
451
455
  wake,
452
456
  urlChange,
453
457
  } = core
458
+ /** The extensions that are on: granted, and not turned off (story 309). */
459
+ const onExtensions = () =>
460
+ extensions.list().filter((extension) => bundleGrants.isOn(extension.bundle.id))
454
461
  // What this process answers: only `web` serves no back office.
455
462
  const servesBackOffice = config.role !== 'web'
456
463
  // A host that installs packages itself calls `reloadBundles()` (story 181); the
@@ -465,6 +472,7 @@ export async function createServer(
465
472
  registry: config.npmRegistry,
466
473
  keyword: config.packageKeyword,
467
474
  marketplaceUrl: config.marketplaceUrl,
475
+ componentsDir: config.componentsDir,
468
476
  extensions: { ...extensions, invalidate: () => void bundleReloader.reload() },
469
477
  siteDir: config.siteDir,
470
478
  wired: () => bundles?.mounted.map((bundle) => bundle.id) ?? [],
@@ -481,12 +489,13 @@ export async function createServer(
481
489
  applyContent: async (packageName) => {
482
490
  // A package from the marketplace is for anyone, so nothing in it can be
483
491
  // sealed; one that is is refused rather than half applied.
484
- const result = await installBundleContent(db, config, { bundle: packageName }).catch(
485
- (error: unknown) => {
486
- if (error instanceof CommandError) return error
487
- throw error
488
- },
489
- )
492
+ const result = await installBundleContent(db, config, {
493
+ bundle: packageName,
494
+ expects: 'extension',
495
+ }).catch((error: unknown) => {
496
+ if (error instanceof CommandError) return error
497
+ throw error
498
+ })
490
499
  if (result instanceof CommandError)
491
500
  return { applied: false, message: `Its content was not applied: ${result.message}` }
492
501
  if (!result.runId) {
@@ -613,6 +622,9 @@ export async function createServer(
613
622
  * non-browser client may still present a real bearer token.
614
623
  */
615
624
  async function authenticate(request: Request): Promise<Principal | undefined> {
625
+ // An extension's call through `api`, made in this process (story 308).
626
+ const acting = actingPrincipalOf(request)
627
+ if (acting) return acting
616
628
  const header = request.headers.get('authorization')
617
629
  const bearer = header?.toLowerCase().startsWith('bearer ') ? header.slice(7).trim() : undefined
618
630
  const fromCookie = !bearer || bearer === REDACTED
@@ -815,7 +827,14 @@ export async function createServer(
815
827
  },
816
828
  )
817
829
  : undefined
818
- const bundleAdmin = createBundleAdmin({ db, config, marketplace, extensions, bundleGrants })
830
+ const bundleAdmin = createBundleAdmin({
831
+ db,
832
+ config,
833
+ marketplace,
834
+ extensions,
835
+ bundleGrants,
836
+ failed: () => core.failedExtensions,
837
+ })
819
838
  const actorOf = (principal: Principal, request: Request): BundleActor => ({
820
839
  id: principal.id,
821
840
  name: principal.name,
@@ -1180,6 +1199,7 @@ export async function createServer(
1180
1199
  content,
1181
1200
  contentTypeAlias: draft.contentTypeAlias,
1182
1201
  published: Boolean(published),
1202
+ ...(published ? { live: published.withValueContext(await cache.valueContext(culture)) } : {}),
1183
1203
  culture,
1184
1204
  }
1185
1205
  }
@@ -1198,7 +1218,7 @@ export async function createServer(
1198
1218
  // routes too.
1199
1219
  const declaredRoutes: DeclaredRoute[] = [
1200
1220
  ...(config.routes ?? []).map(
1201
- (route): DeclaredRoute => ({ route: route as SiteRoute, owner: 'the site' }),
1221
+ (route): DeclaredRoute => ({ route: route as SiteRoute, owner: SITE_ROUTE_OWNER }),
1202
1222
  ),
1203
1223
  ...(bundles?.siteRoutes() ?? []),
1204
1224
  ]
@@ -1254,6 +1274,36 @@ export async function createServer(
1254
1274
  // Asked at boot, so the first AVIF request does not wait on it.
1255
1275
  void canEncodeAvif()
1256
1276
  const publicMedia = mediaStore.publicUrl?.('media/file')
1277
+
1278
+ /** At most 30 reports a minute from one address. */
1279
+ const cspReports = new RateLimiter({ max: 30, windowMs: 60_000 })
1280
+
1281
+ /**
1282
+ * A back-office page, with its content security policy (story 313): its
1283
+ * inline scripts carry a nonce made for it, and it may reach the site and the
1284
+ * origins the extensions that are on declare in `http.outbound`.
1285
+ */
1286
+ const backOfficePage = (body: string): Response => {
1287
+ const nonce = newNonce()
1288
+ const connect = extensions
1289
+ .bundles()
1290
+ .bundles.filter((pkg) => bundleGrants.isOn(pkg.id))
1291
+ .flatMap((pkg) => declaredOrigins(pkg))
1292
+ return new Response(body.replaceAll('<script', `<script nonce="${nonce}"`), {
1293
+ headers: {
1294
+ 'content-type': 'text/html; charset=utf-8',
1295
+ 'content-security-policy': backOfficePolicy({
1296
+ nonce,
1297
+ connect,
1298
+ media: publicMedia ? [publicMedia] : [],
1299
+ frames: [config.seo.publicUrl, config.applicationUrl].filter(
1300
+ (url): url is string => typeof url === 'string',
1301
+ ),
1302
+ reportUri: `${paths.pluginPath}/api/csp-report`,
1303
+ }),
1304
+ },
1305
+ })
1306
+ }
1257
1307
  if (publicMedia)
1258
1308
  log.warning(
1259
1309
  'Media files are also served from {where}. Protected files are always sent by this site and never from there, but anyone with a file’s address there can open it: keep protected files in a store nothing public serves.',
@@ -1274,6 +1324,11 @@ export async function createServer(
1274
1324
  config,
1275
1325
  paths,
1276
1326
  siteSettingsFindings: () => cache.settingsFindings(),
1327
+ failedExtensions: () => core.failedExtensions,
1328
+ lostLayouts: () => {
1329
+ const layouts = siteLayouts(config.componentsDir)
1330
+ return core.extensionComponents.layouts().filter((entry) => !layouts.includes(entry.layout))
1331
+ },
1277
1332
  hiddenByRoutes: async () => {
1278
1333
  const snapshot = await cache.snapshot()
1279
1334
  const hidden: Array<{ route: string; owner: string; page: string; url: string }> = []
@@ -1289,17 +1344,8 @@ export async function createServer(
1289
1344
  }
1290
1345
  return hidden
1291
1346
  },
1292
- // A server bundle's screens show only while it is on (story 222).
1293
- extensions: {
1294
- ...extensions,
1295
- list: () =>
1296
- extensions
1297
- .list()
1298
- .filter(
1299
- (extension) =>
1300
- !extension.bundle.carries.server || bundleGrants.isOn(extension.bundle.id),
1301
- ),
1302
- },
1347
+ // An extension's screens show only while it is on: granted, and not turned off (story 309).
1348
+ extensions: { ...extensions, list: onExtensions },
1303
1349
  db,
1304
1350
  webhooks,
1305
1351
  contentEvents,
@@ -1432,9 +1478,10 @@ export async function createServer(
1432
1478
  const hostTokenPath = `${paths.pluginPath}/api/host-token`
1433
1479
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1434
1480
  const bundleInstallPaths = new Set(
1435
- ['install', 'uninstall', 'disable', 'enable'].map(
1436
- (action) => `${paths.pluginPath}/api/bundles/${action}`,
1437
- ),
1481
+ ['install', 'uninstall', 'disable', 'enable', 'grant', 'settings'].flatMap((action) => [
1482
+ `${paths.pluginPath}/api/extensions/${action}`,
1483
+ `${paths.pluginPath}/api/bundles/${action}`,
1484
+ ]),
1438
1485
  )
1439
1486
  /** Per node: ten a minute for each person, three hundred in all. */
1440
1487
  const hostTokens = new AttemptLimiter({ max: 10, maxAll: 300, windowMs: 60_000 })
@@ -1463,6 +1510,8 @@ export async function createServer(
1463
1510
  * a request on the new paths is routed as the contract names it, and an
1464
1511
  * address it is answered with points back at the new paths.
1465
1512
  */
1513
+ core.setBundleDispatch((request) => fetch(request))
1514
+
1466
1515
  async function fetch(request: Request): Promise<Response> {
1467
1516
  // Story 262: every request a span, continuing a trace only from a trusted proxy.
1468
1517
  const pathname = new URL(request.url).pathname
@@ -1930,12 +1979,34 @@ export async function createServer(
1930
1979
  }
1931
1980
 
1932
1981
  // Non-contract, signed-in: every component, for a page's template picker.
1982
+ // Story 313: what the browser blocked on a back-office page, to the site's log.
1983
+ // Taken without signing in, as browsers send it; small, and rate limited.
1984
+ if (pathname === `${paths.pluginPath}/api/csp-report` && request.method === 'POST') {
1985
+ if (cspReports.take(clientAddress(request).ipAddress ?? 'unknown') !== undefined)
1986
+ return new Response(null, { status: 429 })
1987
+ const text = await request.text().catch(() => '')
1988
+ if (text.length > 10_000) return new Response(null, { status: 413 })
1989
+ try {
1990
+ const parsed = JSON.parse(text) as { 'csp-report'?: Record<string, unknown> }
1991
+ const report = parsed['csp-report'] ?? {}
1992
+ const blocked = String(report['blocked-uri'] ?? '')
1993
+ log.warning('The back office blocked {blocked}, under {directive}', {
1994
+ blocked: /^https?:/.test(blocked) ? new URL(blocked).origin : blocked.slice(0, 40),
1995
+ directive: String(report['violated-directive'] ?? report['effective-directive'] ?? ''),
1996
+ })
1997
+ } catch {
1998
+ return new Response(null, { status: 400 })
1999
+ }
2000
+ return new Response(null, { status: 204 })
2001
+ }
2002
+
1933
2003
  if (pathname === `${paths.pluginPath}/api/templates`) {
1934
2004
  const principal = await authenticate(request)
1935
2005
  if (!principal) return new Response('Unauthorized', { status: 401 })
1936
2006
  return handleComponentTemplates(request, principal, {
1937
2007
  db,
1938
2008
  componentsDir: config.componentsDir,
2009
+ extensionComponents: () => core.extensionComponents.listed(),
1939
2010
  })
1940
2011
  }
1941
2012
 
@@ -2038,11 +2109,16 @@ export async function createServer(
2038
2109
  * marketplace is an iframe — so this is ours, and it answers to the
2039
2110
  * Packages section exactly as the operations beside it would.
2040
2111
  */
2041
- if (pathname.startsWith(`${paths.pluginPath}/api/bundles/`)) {
2112
+ // Extensions (`/api/extensions/`), and the same at `/api/bundles/`, as it was.
2113
+ const extensionsApi = [
2114
+ `${paths.pluginPath}/api/extensions/`,
2115
+ `${paths.pluginPath}/api/bundles/`,
2116
+ ].find((prefix) => pathname.startsWith(prefix))
2117
+ if (extensionsApi) {
2042
2118
  const principal = await authenticate(request)
2043
2119
  if (!principal) return new Response('Unauthorized', { status: 401 })
2044
2120
  if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
2045
- const action = pathname.slice(`${paths.pluginPath}/api/bundles/`.length)
2121
+ const action = pathname.slice(extensionsApi.length)
2046
2122
 
2047
2123
  if (action === 'marketplace' && request.method === 'GET') {
2048
2124
  return Response.json({
@@ -2134,8 +2210,9 @@ export async function createServer(
2134
2210
  name?: unknown
2135
2211
  version?: unknown
2136
2212
  applyContent?: unknown
2137
- acceptServerCode?: unknown
2138
2213
  grant?: unknown
2214
+ actAs?: unknown
2215
+ settings?: unknown
2139
2216
  }
2140
2217
  const name = typeof body.name === 'string' ? body.name : ''
2141
2218
  const actor = actorOf(principal, request)
@@ -2145,10 +2222,11 @@ export async function createServer(
2145
2222
  name,
2146
2223
  version: typeof body.version === 'string' ? body.version : undefined,
2147
2224
  applyContent: body.applyContent !== false,
2148
- acceptServerCode: body.acceptServerCode === true,
2225
+ actAs: actAsChoice(body.actAs, principal.id),
2149
2226
  grant: Array.isArray(body.grant)
2150
2227
  ? body.grant.filter((p): p is string => typeof p === 'string')
2151
2228
  : [],
2229
+ settings: settingsIn(body.settings),
2152
2230
  })
2153
2231
  : await bundleAdmin.uninstall(actor, name)
2154
2232
  log.info('{user} {action} the package {name}: {outcome}', {
@@ -2172,6 +2250,78 @@ export async function createServer(
2172
2250
  return Response.json(outcome, { status })
2173
2251
  }
2174
2252
 
2253
+ // Story 310: an extension's settings, those the config does not lock, administrators only.
2254
+ if (action === 'settings' && request.method === 'POST') {
2255
+ if (!principal.isAdmin)
2256
+ return Response.json(
2257
+ { ok: false, message: "Only an administrator changes an extension's settings." },
2258
+ { status: 403 },
2259
+ )
2260
+ const body = (await request.json().catch(() => ({}))) as { id?: unknown; values?: unknown }
2261
+ const values =
2262
+ body.values && typeof body.values === 'object' && !Array.isArray(body.values)
2263
+ ? (body.values as Record<string, unknown>)
2264
+ : {}
2265
+ const { status, ...outcome } = await bundleAdmin.setSettings(
2266
+ actorOf(principal, request),
2267
+ typeof body.id === 'string' ? body.id : '',
2268
+ values,
2269
+ )
2270
+ return Response.json(outcome, { status })
2271
+ }
2272
+
2273
+ // Story 316: the keys and builds this site trusts to sign site bundles, administrators only.
2274
+ const signerId = /^signers\/([0-9a-f-]{36})$/i.exec(action)?.[1]
2275
+ if (action === 'signers' || signerId) {
2276
+ if (!principal.isAdmin)
2277
+ return Response.json(
2278
+ { ok: false, message: 'Only an administrator manages trusted signers.' },
2279
+ { status: 403 },
2280
+ )
2281
+ const signers = createTrustedSignersAdmin(db, config)
2282
+ const actor = { ...actorOf(principal, request), source: 'request' as const }
2283
+ if (action === 'signers' && request.method === 'GET')
2284
+ return Response.json({ items: await signers.list() })
2285
+ const body = (await request.json().catch(() => ({}))) as Record<string, unknown>
2286
+ const outcome =
2287
+ action === 'signers' && request.method === 'POST'
2288
+ ? await signers.add(actor, body)
2289
+ : signerId && request.method === 'PUT'
2290
+ ? await signers.rename(actor, signerId, body.name)
2291
+ : signerId && request.method === 'DELETE'
2292
+ ? await signers.remove(actor, signerId)
2293
+ : undefined
2294
+ if (!outcome) return new Response('Method Not Allowed', { status: 405 })
2295
+ return outcome.ok
2296
+ ? Response.json(outcome)
2297
+ : Response.json({ ok: false, message: outcome.message }, { status: outcome.status })
2298
+ }
2299
+
2300
+ // Story 309: granting an installed extension what it asks for, administrators only.
2301
+ if (action === 'grant' && request.method === 'POST') {
2302
+ if (!principal.isAdmin)
2303
+ return Response.json(
2304
+ { ok: false, message: 'Only an administrator grants an extension.' },
2305
+ { status: 403 },
2306
+ )
2307
+ const body = (await request.json().catch(() => ({}))) as {
2308
+ id?: unknown
2309
+ grant?: unknown
2310
+ actAs?: unknown
2311
+ }
2312
+ const { status, ...outcome } = await bundleAdmin.grant(
2313
+ actorOf(principal, request),
2314
+ typeof body.id === 'string' ? body.id : '',
2315
+ {
2316
+ grant: Array.isArray(body.grant)
2317
+ ? body.grant.filter((p): p is string => typeof p === 'string')
2318
+ : [],
2319
+ actAs: actAsChoice(body.actAs, principal.id),
2320
+ },
2321
+ )
2322
+ return Response.json(outcome, { status })
2323
+ }
2324
+
2175
2325
  return new Response('Not Found', { status: 404 })
2176
2326
  }
2177
2327
 
@@ -2355,7 +2505,7 @@ export async function createServer(
2355
2505
  schemaDir: config.schemaDir,
2356
2506
  writable: config.schemaWritable,
2357
2507
  formTypes: formTypes.types,
2358
- componentAliases: () => componentAliasesIn(config.componentsDir),
2508
+ componentAliases: () => componentAliasesIn(config.componentsDir, config.siteDir),
2359
2509
  onChanged: config.schemaStore
2360
2510
  ? async () => {
2361
2511
  await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
@@ -2837,8 +2987,9 @@ export async function createServer(
2837
2987
  })
2838
2988
  }
2839
2989
 
2990
+ // Nor are its files served while it is off (story 309).
2840
2991
  const staticMatch = resolveStaticFile(paths, pathname, {
2841
- extensions: extensions.list(),
2992
+ extensions: onExtensions(),
2842
2993
  immutable: config.immutableAssets ?? !config.development,
2843
2994
  })
2844
2995
  if (staticMatch) {
@@ -2889,8 +3040,8 @@ export async function createServer(
2889
3040
  },
2890
3041
  })
2891
3042
  }
2892
- const { importmap } = collectManifests(paths, extensions.list())
2893
- return html(
3043
+ const { importmap } = collectManifests(paths, onExtensions())
3044
+ return backOfficePage(
2894
3045
  renderDeviceShell(paths, importmap, {
2895
3046
  title: config.siteName,
2896
3047
  userCode: url.searchParams.get('user_code') ?? undefined,
@@ -2913,8 +3064,8 @@ export async function createServer(
2913
3064
  location: `${paths.backOfficePath}/login?returnUrl=${encodeURIComponent(`${pathname}${url.search}`)}`,
2914
3065
  },
2915
3066
  })
2916
- const { importmap } = collectManifests(paths, extensions.list())
2917
- return html(
3067
+ const { importmap } = collectManifests(paths, onExtensions())
3068
+ return backOfficePage(
2918
3069
  renderRemoteApprovalShell(paths, importmap, {
2919
3070
  title: config.siteName,
2920
3071
  job: url.searchParams.get('job') ?? '',
@@ -2923,8 +3074,8 @@ export async function createServer(
2923
3074
  }
2924
3075
 
2925
3076
  if (pathname === `${paths.backOfficePath}/login`) {
2926
- const { importmap } = collectManifests(paths, extensions.list())
2927
- return html(
3077
+ const { importmap } = collectManifests(paths, onExtensions())
3078
+ return backOfficePage(
2928
3079
  renderLoginShell(paths, importmap, {
2929
3080
  defaultUiLanguage: config.defaultUiLanguage,
2930
3081
  keepUserLoggedIn: config.keepUserLoggedIn,
@@ -2953,8 +3104,8 @@ export async function createServer(
2953
3104
  }
2954
3105
 
2955
3106
  if (isSpaRoute(paths.backOfficePath, pathname)) {
2956
- const { importmap } = collectManifests(paths, extensions.list())
2957
- return html(
3107
+ const { importmap } = collectManifests(paths, onExtensions())
3108
+ return backOfficePage(
2958
3109
  renderBackOfficeShell(paths, importmap, {
2959
3110
  defaultUiLanguage: config.defaultUiLanguage,
2960
3111
  keepUserLoggedIn: config.keepUserLoggedIn,
@@ -3952,10 +4103,6 @@ export async function createServer(
3952
4103
  }
3953
4104
  }
3954
4105
 
3955
- function html(body: string): Response {
3956
- return new Response(body, { headers: { 'content-type': 'text/html; charset=utf-8' } })
3957
- }
3958
-
3959
4106
  /**
3960
4107
  * Carries the request's query string onto a redirect target, as Umbraco does, so
3961
4108
  * campaign and tracking parameters survive a rename. A target that names its own
package/src/settings.ts CHANGED
@@ -323,6 +323,14 @@ const DECLARED = [
323
323
  description:
324
324
  'The Packages section installs and removes packages on the running site. Off, they are added to `package.json` and deployed.',
325
325
  },
326
+ {
327
+ env: 'CROMBOLO_DENO',
328
+ kind: 'string',
329
+ default: 'the binary the `deno` package installed',
330
+ section: 'Back office and bundles',
331
+ description:
332
+ 'The Deno binary installed extensions run under, each in a process of its own. Set it where Deno publishes no build, such as Alpine.',
333
+ },
326
334
  {
327
335
  env: 'CROMBOLO_BUNDLE_SIGNATURES',
328
336
  kind: 'enum',
@@ -330,14 +338,14 @@ const DECLARED = [
330
338
  default: 'optional',
331
339
  section: 'Back office and bundles',
332
340
  description:
333
- '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.',
341
+ 'Whether this site installs only extensions signed in GitHub Actions with `crombolo bundle sign`. A signature that does not check out is refused either way. Site bundles have their own rule: in production, only from a signer on Settings → Trusted signers.',
334
342
  },
335
343
  {
336
344
  env: 'CROMBOLO_BUNDLE_SOURCES',
337
345
  kind: 'list',
338
346
  section: 'Back office and bundles',
339
347
  description:
340
- '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.',
348
+ 'Where a signed bundle has to come from, separated by commas: `org/*`, `org/repo`, or `org/repo@v*` for its tags. Empty takes signed extensions from anywhere. Each is also a trusted CI build for site bundles, locked on Settings → Trusted signers.',
341
349
  },
342
350
  {
343
351
  env: 'CROMBOLO_INSTALLS_ELSEWHERE_MESSAGE',
@@ -355,14 +363,14 @@ const DECLARED = [
355
363
  {
356
364
  env: 'CROMBOLO_MARKETPLACE_URL',
357
365
  kind: 'string',
358
- default: 'https://www.npmjs.com/search?q=keywords%3Acrombolo-bundle',
366
+ default: 'https://www.npmjs.com/search?q=keywords%3Acrombolo-extension',
359
367
  section: 'Back office and bundles',
360
368
  description: 'Where the Marketplace sends someone browsing for bundles.',
361
369
  },
362
370
  {
363
371
  env: 'CROMBOLO_PACKAGE_KEYWORD',
364
372
  kind: 'string',
365
- default: 'crombolo-bundle',
373
+ default: 'crombolo-extension',
366
374
  section: 'Back office and bundles',
367
375
  description: 'The npm keyword a bundle publishes under to be found by the Marketplace.',
368
376
  },
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Keys that sign site bundles (story 316): a person's own, made on their
3
+ * machine, and each site's, kept sealed in its database. Ed25519. A public key
4
+ * is one line to copy, `crombolo-ed25519 <base64> <name>`, and is known by its
5
+ * fingerprint, `SHA256:…`, as GitHub shows SSH keys. What a key signs is a
6
+ * package's digest (story 060), with its name and version.
7
+ * docs/bundles.md, "Signing a bundle".
8
+ */
9
+ import {
10
+ createPrivateKey,
11
+ createPublicKey,
12
+ generateKeyPairSync,
13
+ sign as signBytes,
14
+ verify as verifyBytes,
15
+ } from 'node:crypto'
16
+ import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
17
+ import { homedir } from 'node:os'
18
+ import { join } from 'node:path'
19
+
20
+ const KEY_TYPE = 'crombolo-ed25519'
21
+ /** The DER prefix that makes a raw Ed25519 public key an SPKI one. */
22
+ const SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex')
23
+
24
+ /** A public key as a site reads it. */
25
+ export interface PublicKey {
26
+ /** The 32 bytes, base64. */
27
+ key: string
28
+ /** What its owner called it: the line's last part. */
29
+ comment: string
30
+ /** `SHA256:` and the key's digest, base64 without padding. */
31
+ fingerprint: string
32
+ /** The line, as it is copied: `crombolo-ed25519 <key> <comment>`. */
33
+ line: string
34
+ }
35
+
36
+ /** A key pair: the public line, and the private half as PKCS#8 PEM. */
37
+ export interface KeyPair {
38
+ publicKey: PublicKey
39
+ privateKey: string
40
+ }
41
+
42
+ export function fingerprintOf(raw: Uint8Array): string {
43
+ const digest = new Bun.CryptoHasher('sha256').update(raw).digest('base64')
44
+ return `SHA256:${digest.replace(/=+$/, '')}`
45
+ }
46
+
47
+ const lineOf = (key: string, comment: string) => `${KEY_TYPE} ${key}${comment ? ` ${comment}` : ''}`
48
+
49
+ /** A public key line read, or why it is not one. Pure. */
50
+ export function readPublicKey(text: string): PublicKey | { problem: string } {
51
+ const [type, key, ...rest] = text.trim().split(/\s+/)
52
+ if (type !== KEY_TYPE || !key)
53
+ return { problem: `A key starts ${KEY_TYPE}, then the key itself: paste the whole line.` }
54
+ const raw = Buffer.from(key, 'base64')
55
+ if (raw.length !== 32 || raw.toString('base64') !== key)
56
+ return { problem: 'That is not a whole key: copy the line again.' }
57
+ const comment = rest.join(' ')
58
+ return { key, comment, fingerprint: fingerprintOf(raw), line: lineOf(key, comment) }
59
+ }
60
+
61
+ /** A new key pair, named `comment`. */
62
+ export function createKeyPair(comment: string): KeyPair {
63
+ const { publicKey, privateKey } = generateKeyPairSync('ed25519')
64
+ const raw = publicKey.export({ format: 'der', type: 'spki' }).subarray(SPKI_PREFIX.length)
65
+ const key = raw.toString('base64')
66
+ return {
67
+ publicKey: {
68
+ key,
69
+ comment,
70
+ fingerprint: fingerprintOf(raw),
71
+ line: lineOf(key, comment),
72
+ },
73
+ privateKey: privateKey.export({ format: 'pem', type: 'pkcs8' }).toString(),
74
+ }
75
+ }
76
+
77
+ /** What a key signs: the digest, the package's name and version, as one stable string. */
78
+ export function signedStatement(input: { digest: string; name: string; version: string }): Buffer {
79
+ return Buffer.from(
80
+ JSON.stringify({
81
+ type: 'https://crombolo.dev/bundle-key-signature/v1',
82
+ digest: input.digest,
83
+ name: input.name,
84
+ version: input.version,
85
+ }),
86
+ )
87
+ }
88
+
89
+ export function signWith(privateKey: string, statement: Buffer): string {
90
+ return signBytes(null, statement, createPrivateKey(privateKey)).toString('base64')
91
+ }
92
+
93
+ export function verifiedBy(publicKey: PublicKey, statement: Buffer, signature: string): boolean {
94
+ try {
95
+ const key = createPublicKey({
96
+ key: Buffer.concat([SPKI_PREFIX, Buffer.from(publicKey.key, 'base64')]),
97
+ format: 'der',
98
+ type: 'spki',
99
+ })
100
+ return verifyBytes(null, statement, key, Buffer.from(signature, 'base64'))
101
+ } catch {
102
+ return false
103
+ }
104
+ }
105
+
106
+ /** Where a person's own keys are kept: their config directory, never the site's. */
107
+ export function userKeysDir(): string {
108
+ return join(Bun.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'crombolo', 'keys')
109
+ }
110
+
111
+ const KEY_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/
112
+
113
+ /** Writes a new user key, readable by its owner alone. */
114
+ export function createUserKey(name: string, comment = name, dir = userKeysDir()): KeyPair {
115
+ if (!KEY_NAME.test(name))
116
+ throw new Error('A key is named with lowercase letters, digits, dots, hyphens and underscores.')
117
+ const file = join(dir, `${name}.json`)
118
+ if (existsSync(file)) throw new Error(`There is already a key called ${name}.`)
119
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
120
+ const pair = createKeyPair(comment)
121
+ writeFileSync(
122
+ file,
123
+ `${JSON.stringify({ publicKey: pair.publicKey.line, privateKey: pair.privateKey }, null, 2)}\n`,
124
+ {
125
+ mode: 0o600,
126
+ },
127
+ )
128
+ chmodSync(file, 0o600)
129
+ return pair
130
+ }
131
+
132
+ /** A user key by its name, or a path to its file. */
133
+ export function readUserKey(nameOrPath: string, dir = userKeysDir()): KeyPair {
134
+ const file = existsSync(nameOrPath) ? nameOrPath : join(dir, `${nameOrPath}.json`)
135
+ if (!existsSync(file))
136
+ throw new Error(`There is no key called ${nameOrPath}: make one with \`crombolo keys create\`.`)
137
+ const stored = JSON.parse(readFileSync(file, 'utf8')) as { publicKey: string; privateKey: string }
138
+ const publicKey = readPublicKey(stored.publicKey)
139
+ if ('problem' in publicKey) throw new Error(`${file} does not hold a key: ${publicKey.problem}`)
140
+ return { publicKey, privateKey: stored.privateKey }
141
+ }
142
+
143
+ /** The user keys on this machine, by name. */
144
+ export function listUserKeys(dir = userKeysDir()): { name: string; publicKey: PublicKey }[] {
145
+ if (!existsSync(dir)) return []
146
+ return readdirSync(dir)
147
+ .filter((file) => file.endsWith('.json'))
148
+ .flatMap((file) => {
149
+ try {
150
+ return [{ name: file.slice(0, -5), publicKey: readUserKey(join(dir, file)).publicKey }]
151
+ } catch {
152
+ return []
153
+ }
154
+ })
155
+ }