@crombolo/server 0.43.1 → 0.45.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.
package/src/server.ts CHANGED
@@ -66,7 +66,10 @@ import {
66
66
  DEFAULT_UPLOAD_SETTINGS,
67
67
  DELIVERY_API_PREFIX,
68
68
  FormPermissions,
69
+ formTokenSubject,
69
70
  hasAccessToSensitiveData,
71
+ libraryFormId,
72
+ libraryFormTypeKey,
70
73
  localReturnUrl,
71
74
  MANAGEMENT_API_PREFIX,
72
75
  managementApiPrefix,
@@ -77,12 +80,14 @@ import {
77
80
  import {
78
81
  appendCacheInstruction,
79
82
  type Db,
83
+ ensureFormLibraryTypes,
80
84
  ensureKeyValue,
81
85
  FormEntryRepository,
82
86
  FormWorkflowRepository,
83
87
  JobRepository,
84
88
  type JobState,
85
89
  latestContentVersionId,
90
+ listLibraryForms,
86
91
  MediaAccessRepository,
87
92
  MemberRepository,
88
93
  PublicAccessRepository,
@@ -142,6 +147,7 @@ import {
142
147
  import { createPublishedContentSource, loadDraftNode } from './adapters/documents.ts'
143
148
  import type { Approvals } from './approvals.ts'
144
149
  import { handleApprovalsApi } from './approvals-api.ts'
150
+ import { type BundleActor, createBundleAdmin } from './bundle-admin.ts'
145
151
  import type { BundleGrants } from './bundle-grants.ts'
146
152
  import { CommandError, installBundleContent } from './bundle-install.ts'
147
153
  import { BUNDLES_CHANGED_EVENT, type BundleReload, createBundleReloader } from './bundle-reload.ts'
@@ -201,7 +207,8 @@ import {
201
207
  readPreviewToken,
202
208
  signPreviewToken,
203
209
  } from './preview-tokens.ts'
204
- import { createRemote } from './remote.ts'
210
+ import { provenanceProblem } from './provenance.ts'
211
+ import { createRemote, type RestartOutcome } from './remote.ts'
205
212
  import { unknownHostProvided } from './site-file.ts'
206
213
  import { handleTransferAction, pendingTransfers } from './transfer-dashboard.ts'
207
214
  import { changeUrlOptions, urlSettingEditable } from './url-settings.ts'
@@ -315,7 +322,18 @@ export interface ServerHandle {
315
322
  close(): Promise<void>
316
323
  }
317
324
 
318
- 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> {
319
337
  if (config.role === 'worker')
320
338
  throw new Error('A worker serves no site: start it with createWorker (story 223).')
321
339
  configureLogging({
@@ -416,6 +434,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
416
434
  applyContentOnInstall: config.applyBundleContentOnInstall,
417
435
  installs: config.runtimeInstalls,
418
436
  installsElsewhere: config.installsElsewhere,
437
+ policy: config.bundlePolicy,
419
438
  applyContent: async (packageName) => {
420
439
  // A package from the marketplace is for anyone, so nothing in it can be
421
440
  // sealed; one that is is refused rather than half applied.
@@ -753,10 +772,20 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
753
772
  },
754
773
  )
755
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
+ })
756
783
  const remote = createRemote({
757
784
  db,
758
785
  config,
759
786
  authenticate,
787
+ bundles: bundleAdmin,
788
+ restart: serverOptions.restart,
760
789
  onApplied: () => {
761
790
  cache.invalidate()
762
791
  mediaCache.clear()
@@ -866,7 +895,11 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
866
895
  apiForm(tools.resolve(form), {
867
896
  types: formTypes.types,
868
897
  action: `${origin}${formAction(form)}`,
869
- token: signFormToken(formSecret, form.key ?? form.alias, now),
898
+ token: signFormToken(
899
+ formSecret,
900
+ formTokenSubject(form.key ?? form.alias, form.library?.key),
901
+ now,
902
+ ),
870
903
  renderedAt: now,
871
904
  redirectUrl: form.redirectTo ? tools.urlOf(form.redirectTo) : undefined,
872
905
  })
@@ -1691,7 +1724,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1691
1724
  if (pathname.startsWith(`${paths.pluginPath}/api/bundles/`)) {
1692
1725
  const principal = await authenticate(request)
1693
1726
  if (!principal) return new Response('Unauthorized', { status: 401 })
1694
- if (!hasSection(principal, 'packages')) return new Response('Forbidden', { status: 403 })
1727
+ if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
1695
1728
  const action = pathname.slice(`${paths.pluginPath}/api/bundles/`.length)
1696
1729
 
1697
1730
  if (action === 'marketplace' && request.method === 'GET') {
@@ -1760,11 +1793,22 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1760
1793
  }
1761
1794
  }
1762
1795
 
1763
- if (action === 'installed' && request.method === 'GET') {
1796
+ if (action === 'installed' && request.method === 'GET')
1797
+ return Response.json(await bundleAdmin.installed())
1798
+
1799
+ // Where a version was built, for the Install panel before anything is
1800
+ // installed (story 060), and whether this site would take it.
1801
+ if (action === 'signature' && request.method === 'GET') {
1802
+ const name = url.searchParams.get('name') ?? ''
1803
+ const version = url.searchParams.get('version') ?? undefined
1804
+ const inspected = await marketplace.inspect(name, version)
1805
+ if (!inspected.ok) return Response.json({ ok: false, message: inspected.message })
1764
1806
  return Response.json({
1765
- installs: config.runtimeInstalls,
1766
- installsElsewhere: config.runtimeInstalls ? null : (config.installsElsewhere ?? null),
1767
- items: await marketplace.installed(),
1807
+ ok: true,
1808
+ version: inspected.version,
1809
+ provenance: inspected.provenance,
1810
+ refused: provenanceProblem(inspected.provenance, config.bundlePolicy) ?? null,
1811
+ policy: config.bundlePolicy,
1768
1812
  })
1769
1813
  }
1770
1814
 
@@ -1777,43 +1821,25 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1777
1821
  grant?: unknown
1778
1822
  }
1779
1823
  const name = typeof body.name === 'string' ? body.name : ''
1780
- const version = typeof body.version === 'string' ? body.version : undefined
1781
- const acceptServerCode = body.acceptServerCode === true
1782
- const grant = Array.isArray(body.grant)
1783
- ? body.grant.filter((p): p is string => typeof p === 'string')
1784
- : []
1824
+ const actor = actorOf(principal, request)
1785
1825
  const outcome =
1786
1826
  action === 'install'
1787
- ? await marketplace.install(name, version, {
1827
+ ? await bundleAdmin.install(actor, {
1828
+ name,
1829
+ version: typeof body.version === 'string' ? body.version : undefined,
1788
1830
  applyContent: body.applyContent !== false,
1789
- acceptServerCode,
1790
- grant,
1791
- by: principal.email,
1831
+ acceptServerCode: body.acceptServerCode === true,
1832
+ grant: Array.isArray(body.grant)
1833
+ ? body.grant.filter((p): p is string => typeof p === 'string')
1834
+ : [],
1792
1835
  })
1793
- : await marketplace.uninstall(name)
1836
+ : await bundleAdmin.uninstall(actor, name)
1794
1837
  log.info('{user} {action} the package {name}: {outcome}', {
1795
1838
  user: principal.email,
1796
1839
  action: action === 'install' ? 'installed' : 'removed',
1797
1840
  name,
1798
1841
  outcome: outcome.ok ? 'ok' : outcome.message,
1799
1842
  })
1800
- // One entry per install, naming the package and whether server code
1801
- // was accepted (story 194); the generic plugin-write entry skips these.
1802
- if (outcome.ok)
1803
- await recordAudit(db, {
1804
- category: 'system',
1805
- action: action === 'install' ? 'Install' : 'Uninstall',
1806
- entityType: 'Bundle',
1807
- entityName: outcome.dependency ? `${name}@${outcome.dependency.version}` : name,
1808
- detail:
1809
- action === 'install' && acceptServerCode
1810
- ? `accepted server code; granted ${grant.length > 0 ? grant.join(', ') : 'nothing'}`
1811
- : null,
1812
- source: 'request',
1813
- userKey: principal.id,
1814
- userName: principal.name,
1815
- ...clientAddress(request),
1816
- })
1817
1843
  return Response.json(outcome, { status: outcome.ok ? 200 : 400 })
1818
1844
  }
1819
1845
 
@@ -1821,36 +1847,12 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1821
1847
  // administrator can disable one, and enable it again.
1822
1848
  if ((action === 'disable' || action === 'enable') && request.method === 'POST') {
1823
1849
  const body = (await request.json().catch(() => ({}))) as { id?: unknown }
1824
- const id = typeof body.id === 'string' ? body.id : ''
1825
- const pkg = extensions.bundles().bundles.find((candidate) => candidate.id === id)
1826
- if (!pkg?.carries.server)
1827
- return Response.json(
1828
- { ok: false, message: `No installed bundle with a server half is called "${id}".` },
1829
- { status: 404 },
1830
- )
1831
- const state =
1832
- action === 'disable'
1833
- ? await bundleGrants.disable(pkg, principal.email)
1834
- : await bundleGrants.enable(pkg)
1835
- await recordAudit(db, {
1836
- category: 'system',
1837
- action: action === 'disable' ? 'Disable' : 'Enable',
1838
- entityType: 'Bundle',
1839
- entityName: `${pkg.packageName}@${pkg.version}`,
1840
- detail: action === 'disable' ? 'disabled; it is off' : 'enabled; it runs again',
1841
- source: 'request',
1842
- userKey: principal.id,
1843
- userName: principal.name,
1844
- ...clientAddress(request),
1845
- })
1846
- return Response.json({
1847
- ok: true,
1848
- on: state.on,
1849
- message:
1850
- action === 'disable'
1851
- ? `${pkg.name} is turned off until it is enabled again.`
1852
- : `${pkg.name} is turned on.`,
1853
- })
1850
+ const { status, ...outcome } = await bundleAdmin.setEnabled(
1851
+ actorOf(principal, request),
1852
+ typeof body.id === 'string' ? body.id : '',
1853
+ action === 'enable',
1854
+ )
1855
+ return Response.json(outcome, { status })
1854
1856
  }
1855
1857
 
1856
1858
  return new Response('Not Found', { status: 404 })
@@ -1946,6 +1948,17 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1946
1948
  return Response.json(webhookStoreView(webhook.store, webhooks.stores()))
1947
1949
  }
1948
1950
 
1951
+ // CI access (story 160): the trust rules, for the Settings screen, as the remote serves them.
1952
+ if (
1953
+ pathname === `${paths.pluginPath}/api/remote-trust` ||
1954
+ pathname.startsWith(`${paths.pluginPath}/api/remote-trust/`)
1955
+ ) {
1956
+ const principal = await authenticate(request)
1957
+ if (!principal) return new Response('Unauthorized', { status: 401 })
1958
+ const rest = pathname.slice(`${paths.pluginPath}/api/remote-`.length)
1959
+ return remote.trust(request, principal, rest)
1960
+ }
1961
+
1949
1962
  if (pathname.startsWith(`${paths.pluginPath}/api/forms`)) {
1950
1963
  const principal = await authenticate(request)
1951
1964
  if (!principal) return new Response('Unauthorized', { status: 401 })
@@ -1963,6 +1976,25 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1963
1976
  // Hyphenated, so no form alias (letters and digits) can be mistaken for it.
1964
1977
  if (action === 'available-types' && request.method === 'GET')
1965
1978
  return Response.json(describeFormTypes(formTypes.types))
1979
+ // The Library forms (story 239), for a page's form picker and the entries filter.
1980
+ if (action === 'library-forms' && request.method === 'GET') {
1981
+ const known = new Map(definitions.map((form) => [form.key ?? form.alias, form]))
1982
+ return Response.json({
1983
+ items: (await listLibraryForms(db)).map((item) => ({
1984
+ ...item,
1985
+ formAlias: known.get(item.formKey)?.alias ?? null,
1986
+ formName: known.get(item.formKey)?.name ?? null,
1987
+ })),
1988
+ })
1989
+ }
1990
+ // Which content types are made from a form, for the note in their editor.
1991
+ if (action === 'library-types' && request.method === 'GET')
1992
+ return Response.json({
1993
+ items: definitions.map((form) => ({
1994
+ typeKey: libraryFormTypeKey(libraryFormId(form)),
1995
+ formName: form.name,
1996
+ })),
1997
+ })
1966
1998
  // The designer's "E-mail design" picker.
1967
1999
  if (action === 'email-templates' && request.method === 'GET')
1968
2000
  return Response.json({
@@ -2016,6 +2048,10 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2016
2048
  if (next === 'approved') {
2017
2049
  const form = byKey.get(updated.formKey)
2018
2050
  const onApprove = form?.workflows.filter((workflow) => workflow.on === 'approve') ?? []
2051
+ // Through a Library form: its recipients as they are now (story 239).
2052
+ const recipients = updated.libraryKey
2053
+ ? (await cache.libraryForm(updated.libraryKey))?.library?.recipients
2054
+ : undefined
2019
2055
  if (onApprove.length > 0)
2020
2056
  await new FormWorkflowRepository(db).enqueue(
2021
2057
  onApprove.map((workflow) => ({
@@ -2029,6 +2065,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2029
2065
  fieldAlias: value.fieldAlias,
2030
2066
  values: value.values,
2031
2067
  })),
2068
+ ...(recipients ? { recipients } : {}),
2032
2069
  })),
2033
2070
  )
2034
2071
  }
@@ -2086,8 +2123,11 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2086
2123
  const key = decodeURIComponent(listMatch[1] as string)
2087
2124
  const since = url.searchParams.get('from')
2088
2125
  const until = url.searchParams.get('to')
2126
+ // `library=none` for the entries that came through no Library form.
2127
+ const library = url.searchParams.get('library')
2089
2128
  const page = await entries.list({
2090
2129
  formKey: key,
2130
+ ...(library ? { libraryKey: library === 'none' ? null : library } : {}),
2091
2131
  state: parseEntryState(url.searchParams.get('state')),
2092
2132
  from: since ? new Date(since) : undefined,
2093
2133
  to: until ? new Date(until) : undefined,
@@ -2151,6 +2191,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2151
2191
  // The memo would otherwise hold the old definition for a second, which
2152
2192
  // is exactly long enough for the designer to reload and see it.
2153
2193
  forms.invalidate()
2194
+ await ensureFormLibraryTypes(db, forms.all())
2195
+ cache.invalidate()
2154
2196
  log.info('{user} saved the form {form}', {
2155
2197
  user: principal.email,
2156
2198
  form: coerceForm(body).alias,
@@ -2169,6 +2211,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2169
2211
  { status: removed.status === 'readOnly' ? 409 : 404 },
2170
2212
  )
2171
2213
  forms.invalidate()
2214
+ await ensureFormLibraryTypes(db, forms.all())
2215
+ cache.invalidate()
2172
2216
  log.info('{user} deleted the form {form}; its entries are kept', {
2173
2217
  user: principal.email,
2174
2218
  form: form.alias,
@@ -2349,7 +2393,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2349
2393
  if (pathname.startsWith(`${paths.pluginPath}/api/transfers/`)) {
2350
2394
  const principal = await authenticate(request)
2351
2395
  if (!principal) return new Response('Unauthorized', { status: 401 })
2352
- if (!hasSection(principal, 'packages')) return new Response('Forbidden', { status: 403 })
2396
+ if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
2353
2397
  const action = pathname.slice(`${paths.pluginPath}/api/transfers/`.length)
2354
2398
  const response = await handleTransferAction(request, action, {
2355
2399
  db,
@@ -2394,7 +2438,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2394
2438
  const bundles = await tablesReport(db, chains)
2395
2439
  const upgrades = summariseUpgrades(await readLedger(db), VERSION)
2396
2440
  // The answers a finding can be given, offered only to those who may import.
2397
- const mayImport = hasSection(principal, 'packages')
2441
+ const mayImport = hasSection(principal, 'settings')
2398
2442
  const offered = findings.map((f) =>
2399
2443
  f.source === 'transfer' && f.status === 'open' && mayImport
2400
2444
  ? { ...f, choices: choicesFor(f) }
@@ -2758,6 +2802,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2758
2802
  mediaFiles,
2759
2803
  uploads: DEFAULT_UPLOAD_SETTINGS,
2760
2804
  urlOf: async (contentKey) => (await cache.byKey(contentKey))?.url,
2805
+ // A Library form's type is invariant, so any culture's view has its words.
2806
+ libraryForm: (libraryKey) => cache.libraryForm(libraryKey),
2761
2807
  // The page it was sent from names the culture; the keys a source offers
2762
2808
  // are the same in every culture, so only the stored labels depend on it.
2763
2809
  resolveForm: async (form) => {
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',
@@ -836,11 +852,12 @@ const DECLARED = [
836
852
 
837
853
  // Remote
838
854
  {
839
- env: 'CROMBOLO_REMOTE_ENABLED',
840
- kind: 'boolean',
841
- default: 'false',
855
+ env: 'CROMBOLO_REMOTE_ACCESS',
856
+ kind: 'string',
857
+ default: 'off',
842
858
  section: 'Remote',
843
- description: 'Lets `crombolo pull` and `crombolo push` reach this site.',
859
+ description:
860
+ 'What `crombolo` may do to this site from elsewhere: `off`, `read` (pull), `content` (apply bundles of content) or `all` (whole-site pushes, and bundles that change content types, views or code). Who may do it is still up to their permissions.',
844
861
  },
845
862
  {
846
863
  env: 'CROMBOLO_REMOTE_ENVIRONMENT',
@@ -873,6 +890,14 @@ const DECLARED = [
873
890
  description:
874
891
  'The largest push or media file a client may upload, in gigabytes. Every other request keeps the usual body limit.',
875
892
  },
893
+ {
894
+ env: 'CROMBOLO_REMOTE_OIDC_ISSUERS',
895
+ kind: 'string',
896
+ default: '',
897
+ section: 'Remote',
898
+ description:
899
+ "A self-managed GitLab's address, or several separated by commas, whose CI jobs may sign in beside GitHub Actions and gitlab.com. Each job still needs a trust rule in Settings.",
900
+ },
876
901
 
877
902
  // Logging
878
903
  {