@crombolo/server 0.64.0 → 0.66.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 (46) hide show
  1. package/package.json +15 -14
  2. package/src/access.ts +6 -2
  3. package/src/adapters/blueprints.ts +19 -5
  4. package/src/adapters/elements.ts +49 -36
  5. package/src/adapters/members.ts +37 -3
  6. package/src/adapters/users.ts +18 -0
  7. package/src/approvals.ts +44 -15
  8. package/src/atomic-write.ts +2 -2
  9. package/src/background-jobs.ts +170 -0
  10. package/src/bundle-admin.ts +39 -3
  11. package/src/bundle-reload.ts +2 -1
  12. package/src/bundles.ts +60 -25
  13. package/src/cli-tokens-api.ts +152 -0
  14. package/src/config.ts +52 -3
  15. package/src/content-events.ts +22 -0
  16. package/src/content-operations.ts +26 -1
  17. package/src/core.ts +357 -133
  18. package/src/extension-activity.ts +121 -0
  19. package/src/extension-components.ts +20 -4
  20. package/src/extension-discovery.ts +84 -65
  21. package/src/grant-trust.ts +6 -4
  22. package/src/index.ts +14 -0
  23. package/src/media-access.ts +30 -125
  24. package/src/media-library.ts +953 -0
  25. package/src/member-admin.ts +761 -0
  26. package/src/node-operations.ts +19 -2
  27. package/src/ports.ts +2 -0
  28. package/src/principal.ts +35 -0
  29. package/src/remote-background-jobs.ts +99 -0
  30. package/src/remote-credentials.ts +114 -6
  31. package/src/remote-extension-activity.ts +66 -0
  32. package/src/remote-media-library.ts +297 -0
  33. package/src/remote-media.ts +2 -2
  34. package/src/remote-members.ts +271 -0
  35. package/src/remote-undo.ts +234 -0
  36. package/src/remote-users.ts +229 -0
  37. package/src/remote.ts +141 -3
  38. package/src/routes.ts +22 -3
  39. package/src/seed/values.ts +82 -4
  40. package/src/seo.ts +81 -61
  41. package/src/server.ts +153 -92
  42. package/src/settings.ts +95 -6
  43. package/src/trusted-signers-admin.ts +39 -3
  44. package/src/undo.ts +358 -0
  45. package/src/user-admin.ts +581 -0
  46. package/src/view-as.ts +95 -0
package/src/server.ts CHANGED
@@ -36,13 +36,16 @@ import {
36
36
  import {
37
37
  AuthService,
38
38
  AuthStore,
39
+ CliTokens,
39
40
  cookieNames,
40
41
  createAuthRoutes,
41
42
  expireCookie,
43
+ isCliToken,
42
44
  isSafeMethod,
43
45
  isSameOrigin,
44
46
  memberCookieName,
45
47
  REDACTED,
48
+ type ResolvedIdentity,
46
49
  readCookie,
47
50
  serializeCookie,
48
51
  } from '@crombolo/auth'
@@ -78,6 +81,7 @@ import {
78
81
  localReturnUrl,
79
82
  MANAGEMENT_API_PREFIX,
80
83
  managementApiPrefix,
84
+ normaliseUuid,
81
85
  ObjectTypes,
82
86
  PREVIEW_HUB_PATH,
83
87
  RemotePermissions,
@@ -85,15 +89,14 @@ import {
85
89
  } from '@crombolo/core'
86
90
  import {
87
91
  appendCacheInstruction,
92
+ currentAuditContext,
88
93
  type Db,
89
- ExtensionActivityLog,
90
94
  ensureFormLibraryTypes,
91
95
  ensureKeyValue,
92
96
  FormEntryRepository,
93
97
  FormWorkflowRepository,
94
98
  FormWorkflowSecretRepository,
95
99
  JobRepository,
96
- type JobState,
97
100
  latestContentVersionId,
98
101
  listLibraryForms,
99
102
  MediaAccessRepository,
@@ -106,6 +109,7 @@ import {
106
109
  searchProvidersOf,
107
110
  TransferRunRepository,
108
111
  type WritesPaused,
112
+ withAuditContext,
109
113
  } from '@crombolo/data'
110
114
  import {
111
115
  BUNDLE_SCRIPT,
@@ -155,7 +159,7 @@ import {
155
159
  import { loadSchemaDirectory, type SyncReport } from '@crombolo/schema'
156
160
  import { choicesFor } from '@crombolo/transfer'
157
161
  import type { Server } from 'bun'
158
- import { createNodeLookup, loadAccess } from './access.ts'
162
+ import { createNodeLookup } from './access.ts'
159
163
  import { ACTION_FLASH_COOKIE, actionRegistry, actionRoutes } from './actions.ts'
160
164
  import { createAuditHost, createAuditSink, pluginAuditPlan, recordAudit } from './adapters/audit.ts'
161
165
  import {
@@ -170,6 +174,7 @@ import {
170
174
  import { createPublishedContentSource, loadDraftNode } from './adapters/documents.ts'
171
175
  import type { Approvals } from './approvals.ts'
172
176
  import { handleApprovalsApi } from './approvals-api.ts'
177
+ import { BackgroundJobError, listJobs, readJobQuery, retryJob } from './background-jobs.ts'
173
178
  import { type BundleActor, createBundleAdmin, settingsIn } from './bundle-admin.ts'
174
179
  import { actingPrincipalOf } from './bundle-api.ts'
175
180
  import { type BundleGrants, declaredOrigins } from './bundle-grants.ts'
@@ -198,7 +203,7 @@ import { editorTypeLibs, siteJsxImportSource } from './editor-types.ts'
198
203
  import { emailAvailability, emailReady } from './email.ts'
199
204
  import { noticeAboutEmail } from './email-notice.ts'
200
205
  import { createEmailSettings, type EmailSettingsInput } from './email-settings.ts'
201
- import { activityCsv, readActivityQuery } from './extension-activity.ts'
206
+ import { activityPath, answerActivity } from './extension-activity.ts'
202
207
  import { createBackOfficeBuilds } from './extension-backoffice.ts'
203
208
  import { warnAboutAppPlugins } from './extensions-notice.ts'
204
209
  import { coerceForm, deleteForm, saveForm } from './form-files.ts'
@@ -239,6 +244,7 @@ import {
239
244
  readPreviewToken,
240
245
  signPreviewToken,
241
246
  } from './preview-tokens.ts'
247
+ import { principalOf } from './principal.ts'
242
248
  import { provenanceProblem } from './provenance.ts'
243
249
  import { createRemote, may, type RestartOutcome } from './remote.ts'
244
250
  import { createSchemaTransfer, UPLOAD_LIMITS } from './schema-transfer.ts'
@@ -270,6 +276,7 @@ export const PREVIEW_MEMBER_COOKIE = 'crombolo-preview-member'
270
276
 
271
277
  import { ACTIONS_PATH, type SiteRoute } from '@crombolo/common'
272
278
  import { backofficeAudience } from './backoffice-external.ts'
279
+ import { createCliTokensApi, tokenRefusal } from './cli-tokens-api.ts'
273
280
  import { createExternalSignIn } from './external-sign-in.ts'
274
281
  import { IdentityProviderOverrides } from './identity-provider-overrides.ts'
275
282
  import {
@@ -311,6 +318,7 @@ import {
311
318
  } from './status-pages.ts'
312
319
  import { TwoFactorService, USER_TWO_FACTOR_PROVIDER } from './two-factor.ts'
313
320
  import { summariseUpgrades } from './upgrade-summary.ts'
321
+ import { createViewAs } from './view-as.ts'
314
322
  import { webhookStoreView } from './webhooks.ts'
315
323
 
316
324
  export interface ServerHandle {
@@ -431,6 +439,12 @@ export async function createServer(
431
439
  ]),
432
440
  streamMemberFile: (src, search) => streamMemberFile(src, search),
433
441
  siteName: async () => (await seo.siteDefaults()).siteName,
442
+ onExtensionsChanged: () => {
443
+ // An instruction heard while this server is still being built has no hub to tell yet.
444
+ try {
445
+ events.broadcast('notify', [BUNDLES_CHANGED_EVENT])
446
+ } catch {}
447
+ },
434
448
  })
435
449
  const {
436
450
  diagnostics,
@@ -659,6 +673,46 @@ export async function createServer(
659
673
  // An extension's call through `api`, made in this process (story 308).
660
674
  const acting = actingPrincipalOf(request)
661
675
  if (acting) return acting
676
+ const identity = await identify(request)
677
+ if (!identity) return tokenPrincipal(request)
678
+ const principal = await principalFrom(identity)
679
+ // Story 314: what this session writes says whose groups it was seen as.
680
+ const context = currentAuditContext()
681
+ if (context && principal.viewingAs)
682
+ context.viewing = {
683
+ userKey: normaliseUuid(principal.id),
684
+ groups: principal.viewingAs.groups.map((g) => g.name).join(', '),
685
+ }
686
+ return principal
687
+ }
688
+
689
+ /** A command-line token a request carries as its bearer, never from a cookie (story 351). */
690
+ const cliTokenOf = (request: Request): string | undefined => {
691
+ const header = request.headers.get('authorization')
692
+ const bearer = header?.toLowerCase().startsWith('bearer ') ? header.slice(7).trim() : undefined
693
+ return bearer && isCliToken(bearer) ? bearer : undefined
694
+ }
695
+
696
+ /** The person a command-line token acts as, with their permissions as they are now. */
697
+ async function tokenPrincipal(request: Request): Promise<Principal | undefined> {
698
+ const token = cliTokenOf(request)
699
+ if (!token) return undefined
700
+ const resolved = await cliTokens.resolve(token)
701
+ if (!resolved.ok) return undefined
702
+ const identity = await auth.identityOf(resolved.user.id)
703
+ if (!identity) return undefined
704
+ if (resolved.firstUse) await cliTokensApi.firstUse(resolved.token, clientAddress(request))
705
+ const principal = await principalOf(db, identity, {
706
+ key: resolved.token.key,
707
+ name: resolved.token.name,
708
+ })
709
+ const context = currentAuditContext()
710
+ if (context) context.token = { userKey: normaliseUuid(principal.id), name: resolved.token.name }
711
+ return principal
712
+ }
713
+
714
+ /** The signed-in session a request carries, from its cookie or a bearer token. */
715
+ async function identify(request: Request): Promise<ResolvedIdentity | undefined> {
662
716
  const header = request.headers.get('authorization')
663
717
  const bearer = header?.toLowerCase().startsWith('bearer ') ? header.slice(7).trim() : undefined
664
718
  const fromCookie = !bearer || bearer === REDACTED
@@ -678,28 +732,14 @@ export async function createServer(
678
732
  return undefined
679
733
  }
680
734
 
681
- const identity = await auth.resolveAccessToken(token)
682
- return identity && principalFrom(identity)
735
+ return auth.resolveAccessToken(token)
683
736
  }
684
737
 
685
738
  /** What a resolved user may do, as every check in the Management API reads it. */
686
- async function principalFrom(
739
+ function principalFrom(
687
740
  identity: NonNullable<Awaited<ReturnType<typeof auth.identityOf>>>,
688
741
  ): Promise<Principal> {
689
- return {
690
- id: identity.user.key,
691
- userName: identity.user.login,
692
- name: identity.user.userName,
693
- email: identity.user.email,
694
- isAdmin: identity.isAdmin,
695
- languageIsoCode: identity.user.language ?? undefined,
696
- avatarUrls: identity.user.avatar ? [identity.user.avatar] : [],
697
- allowedSections: identity.allowedSections,
698
- permissions: identity.permissions,
699
- groupKeys: identity.groupKeys,
700
- hasAccessToAllLanguages: identity.hasAccessToAllLanguages,
701
- ...(await loadAccess(db, identity.user.id)),
702
- }
742
+ return principalOf(db, identity)
703
743
  }
704
744
 
705
745
  // Every page as last saved, for previewing in an app (story 053). Built on the
@@ -869,6 +909,7 @@ export async function createServer(
869
909
  bundleGrants,
870
910
  failed: () => [...core.failedExtensions, ...backOfficeBuilds.failed()],
871
911
  stopExtension: (id) => core.stopExtension(id),
912
+ changed: (id) => core.extensionChanged(id),
872
913
  })
873
914
  const actorOf = (principal: Principal, request: Request): BundleActor => ({
874
915
  id: principal.id,
@@ -883,7 +924,18 @@ export async function createServer(
883
924
  config,
884
925
  authenticate,
885
926
  bundles: bundleAdmin,
927
+ operations: core.operations,
928
+ nodeState: schema.nodeState,
929
+ // Read when a request comes, by which time the Management API's ports are made.
930
+ userPorts: () => {
931
+ const users = managementDeps.userManagement
932
+ const groups = managementDeps.userGroups
933
+ return users && groups ? { users, groups } : undefined
934
+ },
886
935
  restart: serverOptions.restart,
936
+ jobsWaitingSince: () => core.workerWatch.status().waitingSince,
937
+ activity: { flush: () => core.activity.flush(), days: config.extensionActivityDays },
938
+ onMediaAccessChange: (key) => mediaCache.drop([key]),
887
939
  onApplied: async () => {
888
940
  cache.invalidate()
889
941
  mediaCache.clear()
@@ -1286,6 +1338,13 @@ export async function createServer(
1286
1338
  showDetails: config.errors.showDetails,
1287
1339
  cors: formCors,
1288
1340
  })
1341
+ // Story 346: an extension started while the site runs adds its routes here, checked as these were.
1342
+ core.setRouteTable({
1343
+ problems: (entries) =>
1344
+ siteRouteProblems([...siteRoutes.routes, ...entries], config.backOfficePath),
1345
+ add: (entries) => siteRoutes.add(entries),
1346
+ remove: (owner) => siteRoutes.remove(owner),
1347
+ })
1289
1348
 
1290
1349
  // Story 219: the site's server actions, a module at a time.
1291
1350
  const { registry: actionList, problems: actionProblems } = actionRegistry(config.actions)
@@ -1308,6 +1367,12 @@ export async function createServer(
1308
1367
  // Asked each time, as e-mail set up in Settings changes without a restart (story 340).
1309
1368
  const canSendUserLinks = () => Boolean(resolveUserLinkSender(config, email))
1310
1369
  const emailSettings = createEmailSettings(db, config, { port: () => email })
1370
+ const viewAs = createViewAs(db, auth)
1371
+ const cliTokens = new CliTokens(db, {
1372
+ enabled: config.cliTokens,
1373
+ maxDays: config.cliTokenMaxDays,
1374
+ })
1375
+ const cliTokensApi = createCliTokensApi(db, cliTokens)
1311
1376
  const schemaTransfer = createSchemaTransfer(db, config, {
1312
1377
  boot: schema,
1313
1378
  afterApply: async (report) => {
@@ -1515,6 +1580,10 @@ export async function createServer(
1515
1580
  if (config.setupCode && (await setup.pending()) === false)
1516
1581
  log.warning('CROMBOLO_SETUP_CODE is still set, but the site is set up. Remove the setting.')
1517
1582
  noticeAboutEmail(emailStatus, logger('email'), { development: config.development })
1583
+ if (!config.development && config.cliAccess === 'open')
1584
+ log.warning(
1585
+ 'CROMBOLO_CLI_ACCESS is open: commands run on this site without anyone signing in, and the audit log cannot say who ran them.',
1586
+ )
1518
1587
  const hubPath = SERVER_EVENT_HUB_PATH
1519
1588
  const previewHubPath = PREVIEW_HUB_PATH
1520
1589
 
@@ -1527,7 +1596,14 @@ export async function createServer(
1527
1596
  const MEDIA_JOB_QUEUED_EVENT = { eventSource: 'Crombolo:MediaJob', eventType: 'Queued' } as const
1528
1597
  const hostTokenPath = `${paths.pluginPath}/api/host-token`
1529
1598
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1530
- const selfAudited = [`${paths.pluginPath}/api/email/`, `${paths.pluginPath}/api/schema-transfer/`]
1599
+ const viewAsPath = `${paths.pluginPath}/api/view-as`
1600
+ const cliTokensPath = `${paths.pluginPath}/api/cli-tokens`
1601
+ const selfAudited = [
1602
+ `${paths.pluginPath}/api/email/`,
1603
+ `${paths.pluginPath}/api/schema-transfer/`,
1604
+ viewAsPath,
1605
+ cliTokensPath,
1606
+ ]
1531
1607
  const bundleInstallPaths = new Set(
1532
1608
  ['install', 'uninstall', 'disable', 'enable', 'grant', 'settings'].flatMap((action) => [
1533
1609
  `${paths.pluginPath}/api/extensions/${action}`,
@@ -1564,6 +1640,11 @@ export async function createServer(
1564
1640
  core.setBundleDispatch((request) => fetch(request))
1565
1641
 
1566
1642
  async function fetch(request: Request): Promise<Response> {
1643
+ // A request dispatched from inside another (an extension's call) shares its audit context.
1644
+ return currentAuditContext() ? traced(request) : withAuditContext(() => traced(request))
1645
+ }
1646
+
1647
+ async function traced(request: Request): Promise<Response> {
1567
1648
  // Story 262: every request a span, continuing a trace only from a trusted proxy.
1568
1649
  const pathname = new URL(request.url).pathname
1569
1650
  const route = routeOf(pathname, paths.backOfficePath)
@@ -2256,35 +2337,15 @@ export async function createServer(
2256
2337
  }
2257
2338
 
2258
2339
  // Story 327: what one extension did, newest first, its counts, and the same as a file.
2259
- const watching = /^installed\/([a-z0-9][a-z0-9-]*)\/activity(\/summary|\.csv)?$/.exec(action)
2260
- if (watching && request.method === 'GET') {
2261
- const [, id, part] = watching as unknown as [string, string, string | undefined]
2262
- const read = readActivityQuery(url.searchParams)
2263
- if (typeof read === 'string')
2264
- return Response.json(
2265
- { title: 'Invalid request', status: 400, detail: read },
2266
- { status: 400 },
2267
- )
2268
- await core.activity.flush()
2269
- const store = new ExtensionActivityLog(db)
2270
- if (part === '/summary')
2271
- return Response.json({
2272
- counts: await store.counts(
2273
- id,
2274
- new Date(Date.now() - config.extensionActivityDays * 86_400_000),
2275
- ),
2276
- people: await store.people(id),
2277
- days: config.extensionActivityDays,
2278
- })
2279
- if (part === '.csv')
2280
- return new Response(await activityCsv(store, id, read.filter), {
2281
- headers: {
2282
- 'content-type': 'text/csv; charset=utf-8',
2283
- 'content-disposition': `attachment; filename="${id}-activity.csv"`,
2284
- },
2285
- })
2286
- return Response.json(await store.page(id, read.filter, read.cursor))
2287
- }
2340
+ const watching = activityPath(action)
2341
+ if (watching && request.method === 'GET')
2342
+ return answerActivity(
2343
+ db,
2344
+ { flush: () => core.activity.flush(), days: config.extensionActivityDays },
2345
+ watching.id,
2346
+ watching.part,
2347
+ url.searchParams,
2348
+ )
2288
2349
 
2289
2350
  // What this person may grant at each level here (story 324): the panel shows the button, the sentence or the snippet.
2290
2351
  const granting = mayGrant(principal.isAdmin, config.unrestrictedExtensions)
@@ -2390,7 +2451,9 @@ export async function createServer(
2390
2451
  { ok: false, message: 'Only an administrator manages trusted signers.' },
2391
2452
  { status: 403 },
2392
2453
  )
2393
- const signers = createTrustedSignersAdmin(db, config)
2454
+ const signers = createTrustedSignersAdmin(db, config, {
2455
+ checks: { extensions, grants: bundleGrants, changed: core.extensionChanged },
2456
+ })
2394
2457
  const actor = { ...actorOf(principal, request), source: 'request' as const }
2395
2458
  if (action === 'signers' && request.method === 'GET')
2396
2459
  return Response.json({ items: await signers.list() })
@@ -2543,6 +2606,31 @@ export async function createServer(
2543
2606
  : Response.json(outcome, { status: outcome.status })
2544
2607
  }
2545
2608
 
2609
+ // Story 351: a person's command-line tokens, and an administrator's view of anyone's.
2610
+ if (pathname === cliTokensPath || pathname.startsWith(`${cliTokensPath}/`)) {
2611
+ const principal = await authenticate(request)
2612
+ if (!principal) {
2613
+ const token = cliTokenOf(request)
2614
+ const why = token ? await cliTokens.resolve(token) : undefined
2615
+ return why && !why.ok
2616
+ ? tokenRefusal(why.reason)
2617
+ : new Response('Unauthorized', { status: 401 })
2618
+ }
2619
+ return cliTokensApi.handle(
2620
+ request,
2621
+ principal,
2622
+ pathname.slice(cliTokensPath.length),
2623
+ clientAddress(request),
2624
+ )
2625
+ }
2626
+
2627
+ // Story 314: an administrator's session seen as user groups, and back.
2628
+ if (pathname === viewAsPath) {
2629
+ const identity = await identify(request)
2630
+ if (!identity) return new Response('Unauthorized', { status: 401 })
2631
+ return viewAs.handle(request, identity, clientAddress(request))
2632
+ }
2633
+
2546
2634
  // Story 340: Settings → E-mail, administrators only.
2547
2635
  const emailAction = /^\/api\/email\/(settings|test)$/.exec(
2548
2636
  pathname.slice(paths.pluginPath.length),
@@ -3040,59 +3128,32 @@ export async function createServer(
3040
3128
  const principal = await authenticate(request)
3041
3129
  if (!principal) return new Response('Unauthorized', { status: 401 })
3042
3130
  if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
3043
- const queue = new JobRepository(db)
3044
3131
  if (pathname === jobsPath && request.method === 'GET') {
3045
- const url = new URL(request.url)
3046
- const state = url.searchParams.get('state')
3047
- const listed = await queue.list({
3048
- owner: url.searchParams.get('owner') || undefined,
3049
- state: ['queued', 'running', 'succeeded', 'failed'].includes(state ?? '')
3050
- ? (state as JobState)
3051
- : undefined,
3052
- skip: Math.max(0, Number(url.searchParams.get('skip')) || 0),
3053
- take: Math.min(200, Math.max(1, Number(url.searchParams.get('take')) || 50)),
3054
- })
3132
+ const listed = await listJobs(db, readJobQuery(new URL(request.url).searchParams))
3055
3133
  return Response.json({
3056
3134
  total: listed.total,
3057
3135
  // Set while this node leaves its jobs to a worker and none is running.
3058
3136
  waitingSince: core.workerWatch.status().waitingSince,
3059
- items: listed.items.map((job) => ({
3060
- id: job.id,
3061
- owner: job.owner,
3062
- name: job.name,
3063
- state: job.state,
3064
- attempts: job.attempts,
3065
- maxAttempts: job.maxAttempts,
3066
- nextAttemptAt: job.nextAttemptAt.toISOString(),
3067
- progress: job.progress,
3068
- error: job.lastError,
3069
- queuedBy: job.queuedBy,
3070
- createdAt: job.createdAt.toISOString(),
3071
- finishedAt: job.finishedAt?.toISOString() ?? null,
3072
- })),
3137
+ items: listed.items,
3073
3138
  })
3074
3139
  }
3075
3140
  const retry = /^\/([0-9a-f-]{36})\/retry$/i.exec(pathname.slice(jobsPath.length))
3076
3141
  if (retry && request.method === 'POST') {
3077
- const id = retry[1] as string
3078
- const job = await queue.get(id)
3079
- if (!job || !(await queue.retry(id)))
3142
+ try {
3143
+ const done = await retryJob(db, retry[1] as string, {
3144
+ key: principal.id,
3145
+ name: principal.name,
3146
+ source: 'request',
3147
+ address: clientAddress(request),
3148
+ })
3149
+ return Response.json({ ok: true, message: done.message })
3150
+ } catch (error) {
3151
+ if (!(error instanceof BackgroundJobError)) throw error
3080
3152
  return Response.json(
3081
3153
  { ok: false, message: 'Only a job that has failed can be run again.' },
3082
3154
  { status: 409 },
3083
3155
  )
3084
- await recordAudit(db, {
3085
- category: 'system',
3086
- action: 'Retry',
3087
- entityType: 'Job',
3088
- entityName: `${job.owner}/${job.name}`,
3089
- detail: job.lastError ? `after: ${job.lastError.slice(0, 200)}` : null,
3090
- source: 'request',
3091
- userKey: principal.id,
3092
- userName: principal.name,
3093
- ...clientAddress(request),
3094
- })
3095
- return Response.json({ ok: true, message: `${job.name} is queued to run again.` })
3156
+ }
3096
3157
  }
3097
3158
  return new Response('Not Found', { status: 404 })
3098
3159
  }
package/src/settings.ts CHANGED
@@ -838,9 +838,10 @@ const DECLARED = [
838
838
  {
839
839
  env: 'CROMBOLO_DELIVERY_API',
840
840
  kind: 'boolean',
841
- default: 'false',
841
+ default: 'true',
842
842
  section: 'Public site',
843
- description: 'Turns on the Delivery API, which serves content as JSON.',
843
+ description:
844
+ 'The Delivery API, which serves the published pages anyone may see as JSON. false turns it off.',
844
845
  },
845
846
  {
846
847
  env: 'CROMBOLO_DELIVERY_API_KEY',
@@ -851,11 +852,12 @@ const DECLARED = [
851
852
  secret: true,
852
853
  },
853
854
  {
854
- env: 'CROMBOLO_DELIVERY_API_PUBLIC',
855
+ env: 'CROMBOLO_DELIVERY_API_PRIVATE',
855
856
  kind: 'boolean',
856
- default: 'true',
857
+ default: 'false',
857
858
  section: 'Public site',
858
- description: 'Off, every Delivery API request needs the key.',
859
+ description:
860
+ 'Makes the Delivery API private: every request needs the key. Unset, it serves what the site publishes.',
859
861
  },
860
862
  {
861
863
  env: 'CROMBOLO_DELIVERY_API_MEDIA',
@@ -867,9 +869,10 @@ const DECLARED = [
867
869
  {
868
870
  env: 'CROMBOLO_DELIVERY_API_CORS_ORIGINS',
869
871
  kind: 'list',
872
+ default: 'any site, while the API is public',
870
873
  section: 'Public site',
871
874
  description:
872
- 'Other sites whose pages may call the Delivery API from the browser, such as https://app.example.com, separated by commas.',
875
+ 'Narrows which other sites may call the Delivery API from the browser, such as https://app.example.com, separated by commas.',
873
876
  },
874
877
  {
875
878
  env: 'CROMBOLO_CACHE_MAX_AGE',
@@ -1128,6 +1131,92 @@ const DECLARED = [
1128
1131
  description: 'Who the audit log records for a command, for a pipeline acting for someone.',
1129
1132
  appliesTo: 'cli',
1130
1133
  },
1134
+ {
1135
+ env: 'CROMBOLO_PROFILE',
1136
+ kind: 'string',
1137
+ section: 'Command line',
1138
+ description:
1139
+ 'The profile a command acts on when it is not given `--profile`, for a shell or a job.',
1140
+ appliesTo: 'cli',
1141
+ },
1142
+ {
1143
+ env: 'CROMBOLO_PROFILES_FILE',
1144
+ kind: 'string',
1145
+ default: '~/.crombolo/profiles',
1146
+ section: 'Command line',
1147
+ description: 'Where the profiles are kept, for tests and unusual machines.',
1148
+ appliesTo: 'cli',
1149
+ },
1150
+ {
1151
+ env: 'CROMBOLO_PROFILE_URL',
1152
+ kind: 'string',
1153
+ section: 'Command line',
1154
+ description:
1155
+ "The address of a hosted site a command acts on when neither `--profile` nor CROMBOLO_PROFILE names one: how a CI job names its site. A Next.js front end reads it as the CMS's address.",
1156
+ appliesTo: 'cli',
1157
+ },
1158
+ {
1159
+ env: 'CROMBOLO_PROFILE_ENVIRONMENT',
1160
+ kind: 'string',
1161
+ section: 'Command line',
1162
+ description: "With CROMBOLO_PROFILE_URL: that site's environment, when it has more than one.",
1163
+ appliesTo: 'cli',
1164
+ },
1165
+ {
1166
+ env: 'CROMBOLO_CREDENTIALS',
1167
+ kind: 'enum',
1168
+ values: ['keychain', 'file'],
1169
+ default: 'the keychain where there is one',
1170
+ section: 'Command line',
1171
+ description:
1172
+ "Where sign-ins are kept: the operating system's keychain, or ~/.crombolo/credentials, which only you can read. Left unset, a machine with no keychain uses the file.",
1173
+ appliesTo: 'both',
1174
+ },
1175
+ {
1176
+ env: 'CROMBOLO_CREDENTIALS_FILE',
1177
+ kind: 'string',
1178
+ default: '~/.crombolo/credentials',
1179
+ section: 'Command line',
1180
+ description:
1181
+ 'The file sign-ins are kept in when they are not in the keychain, for tests and unusual machines.',
1182
+ appliesTo: 'both',
1183
+ },
1184
+ {
1185
+ env: 'CROMBOLO_CLI_ACCESS',
1186
+ kind: 'enum',
1187
+ values: ['open', 'sign-in'],
1188
+ default: '`sign-in` in production, `open` otherwise',
1189
+ section: 'Command line',
1190
+ description:
1191
+ 'Whether a command that reads or changes the site needs someone signed in with `crombolo login`. At `open` it runs as the command line unless someone is signed in; at `sign-in` it acts as the person, with their permissions.',
1192
+ appliesTo: 'both',
1193
+ },
1194
+ {
1195
+ env: 'CROMBOLO_CLI_TOKENS',
1196
+ kind: 'boolean',
1197
+ default: 'false',
1198
+ section: 'Command line',
1199
+ description:
1200
+ 'Whether people may create command-line tokens, for a script or a CI job to run commands as them. Off, no token is made and every existing one is refused, but kept.',
1201
+ appliesTo: 'both',
1202
+ },
1203
+ {
1204
+ env: 'CROMBOLO_CLI_TOKEN_MAX_DAYS',
1205
+ kind: 'number',
1206
+ default: '90',
1207
+ section: 'Command line',
1208
+ description: 'The most days a command-line token may last.',
1209
+ appliesTo: 'both',
1210
+ },
1211
+ {
1212
+ env: 'CROMBOLO_TOKEN',
1213
+ kind: 'string',
1214
+ section: 'Command line',
1215
+ description:
1216
+ "A command-line token: commands act as the person who made it, here or on a hosted site, before anyone's stored sign-in.",
1217
+ secret: true,
1218
+ appliesTo: 'cli',
1219
+ },
1131
1220
  {
1132
1221
  env: 'CROMBOLO_BUNDLE_PASSPHRASE',
1133
1222
  kind: 'string',
@@ -5,9 +5,12 @@
5
5
  * site's own key, are shown and never removed here. Settings, the CLI and the
6
6
  * back-office endpoint share it.
7
7
  */
8
+ import { createExtensionRegistry, type ExtensionRegistry } from '@crombolo/backoffice-host/registry'
8
9
  import { type Db, TrustedSignerRepository } from '@crombolo/data'
9
10
  import { recordAudit } from './adapters/audit.ts'
11
+ import { type BundleGrants, createBundleGrants } from './bundle-grants.ts'
10
12
  import type { CromboloConfig } from './config.ts'
13
+ import { switchOffUntrusted } from './grant-trust.ts'
11
14
  import { readPublicKey } from './signing-keys.ts'
12
15
  import { type TrustEntry, trustedSigners } from './site-trust.ts'
13
16
 
@@ -21,14 +24,42 @@ export interface SignerActor {
21
24
  }
22
25
 
23
26
  export type SignerOutcome =
24
- | { ok: true; entry?: TrustEntry }
27
+ | {
28
+ ok: true
29
+ entry?: TrustEntry
30
+ /** Extensions switched off as their signer was removed, by name (story 335). */
31
+ switchedOff?: string[]
32
+ }
25
33
  | { ok: false; status: number; message: string }
26
34
 
35
+ /** What removing a signer re-checks: the server's own, or this site's, read here. */
36
+ export interface SignerChecks {
37
+ extensions: ExtensionRegistry
38
+ grants: Pick<BundleGrants, 'granted' | 'isOn' | 'state' | 'forget'>
39
+ /** Brings a switched-off extension's process to its grant, where a server runs here (story 346). */
40
+ changed?: (id: string) => Promise<unknown>
41
+ }
42
+
27
43
  /** `org/repo`, `org/*`, or either `@` a ref pattern such as `v*`. */
28
44
  const SOURCE = /^[A-Za-z0-9_.-]+\/(\*|[A-Za-z0-9_.-]+)(@[A-Za-z0-9_.*/-]+)?$/
29
45
 
30
- export function createTrustedSignersAdmin(db: Db, config: CromboloConfig) {
46
+ export function createTrustedSignersAdmin(
47
+ db: Db,
48
+ config: CromboloConfig,
49
+ options: { checks?: SignerChecks } = {},
50
+ ) {
31
51
  const repo = new TrustedSignerRepository(db)
52
+ /** The running server's registry and grants, or this site's, read from its files and database. */
53
+ const checks = async (): Promise<SignerChecks> => {
54
+ if (options.checks) return options.checks
55
+ const extensions = createExtensionRegistry(config.siteDir, { cache: false })
56
+ const grants = createBundleGrants({
57
+ db,
58
+ packages: () => new Map(extensions.bundles().bundles.map((pkg) => [pkg.id, pkg])),
59
+ })
60
+ await grants.refresh()
61
+ return { extensions, grants }
62
+ }
32
63
  const audit = (actor: SignerActor, action: string, name: string, detail: string | null) =>
33
64
  recordAudit(db, {
34
65
  category: 'system',
@@ -124,7 +155,12 @@ export function createTrustedSignersAdmin(db: Db, config: CromboloConfig) {
124
155
  found.name,
125
156
  found.fingerprint ? `${found.kind} key ${found.fingerprint}` : `builds of ${found.source}`,
126
157
  )
127
- return { ok: true }
158
+ // Story 335: what it vouched for loses its upper level now, not at the next start.
159
+ const { extensions, grants, changed } = await checks()
160
+ const ids = await switchOffUntrusted(db, config, extensions, grants, 'untrusted')
161
+ for (const switched of ids) await changed?.(switched)
162
+ const names = new Map(extensions.bundles().bundles.map((pkg) => [pkg.id, pkg.name]))
163
+ return { ok: true, switchedOff: ids.map((id) => names.get(id) ?? id) }
128
164
  },
129
165
  }
130
166
  }