@crombolo/server 0.61.0 → 0.63.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/remote.ts CHANGED
@@ -55,6 +55,7 @@ import {
55
55
  } from './bundle-install.ts'
56
56
  import {
57
57
  carriesSections,
58
+ componentChanges,
58
59
  migrationChanges,
59
60
  type SectionFile,
60
61
  swappedSections,
@@ -524,6 +525,8 @@ export function createRemote(options: RemoteOptions): Remote {
524
525
  backupTaken: !canBackUp,
525
526
  label: `push from ${by}`,
526
527
  by,
528
+ // Whoever pushed was held to InstallCode when the push was sent (story 336).
529
+ installTemplates: true,
527
530
  })
528
531
  if (!result.runId) {
529
532
  const items = [
@@ -712,8 +715,12 @@ export function createRemote(options: RemoteOptions): Remote {
712
715
  try {
713
716
  const carried = readBundle(dir, config.siteDir).carried
714
717
  structural = carriesSections(carried)
715
- // A bundle's value migrations are code too (story 300).
716
- code = [...codeChanges(planCode(config, carried)), ...migrationChanges(config, carried)]
718
+ // A bundle's value migrations are code too (story 300), and so are its templates (336).
719
+ code = [
720
+ ...codeChanges(planCode(config, carried)),
721
+ ...migrationChanges(config, carried),
722
+ ...componentChanges(config, carried),
723
+ ]
717
724
  } catch (error) {
718
725
  return problem(400, {
719
726
  code: 'not-a-bundle',
@@ -745,9 +752,7 @@ export function createRemote(options: RemoteOptions): Remote {
745
752
  return problem(409, {
746
753
  code: 'installs-elsewhere',
747
754
  title: 'This site does not install code while it runs',
748
- detail:
749
- config.installsElsewhere?.message ??
750
- "Add the bundle's code to the site and deploy it the way this site is deployed.",
755
+ detail: 'Installing code while the site runs is turned off on this site.',
751
756
  })
752
757
  if (code.length > 0 && !may(principal, RemotePermissions.InstallCode))
753
758
  return problem(403, {
@@ -1026,9 +1031,9 @@ export function createRemote(options: RemoteOptions): Remote {
1026
1031
  title: "That run brought an extension's content",
1027
1032
  detail: `It is put back by uninstalling ${run.packageName ?? 'the extension'}, with its content reverted.`,
1028
1033
  })
1029
- // A run that installed code changes code back, which needs what it did.
1034
+ // A run that installed code or changed templates changes code back, which needs what it did.
1030
1035
  if (
1031
- installedCode(config, runId) &&
1036
+ (installedCode(config, runId) || swappedSections(config, runId).includes('components')) &&
1032
1037
  (!atLeast('all') ||
1033
1038
  !may(principal, RemotePermissions.ApplyStructure) ||
1034
1039
  !may(principal, RemotePermissions.InstallCode))
@@ -1442,10 +1447,12 @@ export function createRemote(options: RemoteOptions): Remote {
1442
1447
  pull: atLeast('read') && may(principal, RemotePermissions.Pull),
1443
1448
  pullFull: atLeast('read') && may(principal, RemotePermissions.PullFull),
1444
1449
  // A whole-site push changes structure, so it needs that right and the top level.
1450
+ // A push replaces templates too, which are code (story 336).
1445
1451
  push:
1446
1452
  atLeast('all') &&
1447
1453
  mayChange(principal) &&
1448
- may(principal, RemotePermissions.ApplyStructure),
1454
+ may(principal, RemotePermissions.ApplyStructure) &&
1455
+ may(principal, RemotePermissions.InstallCode),
1449
1456
  apply: atLeast('content') && mayChange(principal),
1450
1457
  applyStructure:
1451
1458
  atLeast('all') &&
@@ -1518,6 +1525,14 @@ export function createRemote(options: RemoteOptions): Remote {
1518
1525
  detail:
1519
1526
  "A push replaces the site's content types, views and code, which needs Crombolo.Remote.ApplyStructure.",
1520
1527
  })
1528
+ // Its templates are code, and what a push will change is not known until it is uploaded (story 336).
1529
+ if (pushing && mayChange(principal) && !may(principal, RemotePermissions.InstallCode))
1530
+ return problem(403, {
1531
+ code: 'forbidden-code',
1532
+ title: 'You may not push a whole site here',
1533
+ detail:
1534
+ 'A push replaces the site\'s templates, which are code, so it needs "Install code on this site" (Crombolo.Remote.InstallCode).',
1535
+ })
1521
1536
  if (what === 'bundles' && request.method === 'PUT') return applyBundle(request, principal)
1522
1537
  if (what === 'runs' && request.method === 'GET') return listRuns(url, principal)
1523
1538
  const revert = /^runs\/([0-9a-f-]{36})\/revert$/.exec(what)
package/src/server.ts CHANGED
@@ -80,6 +80,7 @@ import {
80
80
  managementApiPrefix,
81
81
  ObjectTypes,
82
82
  PREVIEW_HUB_PATH,
83
+ RemotePermissions,
83
84
  SERVER_EVENT_HUB_PATH,
84
85
  } from '@crombolo/core'
85
86
  import {
@@ -90,6 +91,7 @@ import {
90
91
  ensureKeyValue,
91
92
  FormEntryRepository,
92
93
  FormWorkflowRepository,
94
+ FormWorkflowSecretRepository,
93
95
  JobRepository,
94
96
  type JobState,
95
97
  latestContentVersionId,
@@ -208,6 +210,7 @@ import {
208
210
  writeFlash,
209
211
  } from './form-submit.ts'
210
212
  import { describeFormTypes, formTypesFor } from './form-types.ts'
213
+ import { isSecretHeader, refusedSendAddresses } from './form-workflows.ts'
211
214
  import {
212
215
  entriesCsv,
213
216
  formDetail,
@@ -236,10 +239,11 @@ import {
236
239
  signPreviewToken,
237
240
  } from './preview-tokens.ts'
238
241
  import { provenanceProblem } from './provenance.ts'
239
- import { createRemote, type RestartOutcome } from './remote.ts'
242
+ import { createRemote, may, type RestartOutcome } from './remote.ts'
240
243
  import { SiteAssets } from './site-assets.ts'
241
244
  import { unknownHostProvided } from './site-file.ts'
242
245
  import { PublicFiles } from './site-public.ts'
246
+ import { signerTrusted } from './site-trust.ts'
243
247
  import {
244
248
  activeSpan,
245
249
  inSpan,
@@ -286,6 +290,7 @@ import { syncConfiguredRedirects } from './redirects.ts'
286
290
  import { createRoutes, type DeclaredRoute, SITE_ROUTE_OWNER, siteRouteProblems } from './routes.ts'
287
291
  import { componentAliasesIn, importSchema, type SchemaBoot, watchSchema } from './schema.ts'
288
292
  import { publishSchema, type SchemaStore } from './schema-store.ts'
293
+ import { SECRET_KEY_VARIABLE, sealSecret, usableSecretKey } from './secrets.ts'
289
294
  import { createSeoHost, originOf, publicOrigin } from './seo.ts'
290
295
  import {
291
296
  combineHubs,
@@ -494,6 +499,7 @@ export async function createServer(
494
499
  keyword: config.packageKeyword,
495
500
  marketplaceUrl: config.marketplaceUrl,
496
501
  componentsDir: config.componentsDir,
502
+ trustSigner: (provenance) => signerTrusted(db, config, provenance),
497
503
  extensions: { ...extensions, invalidate: () => void bundleReloader.reload() },
498
504
  siteDir: config.siteDir,
499
505
  wired: () => bundles?.mounted.map((bundle) => bundle.id) ?? [],
@@ -634,7 +640,11 @@ export async function createServer(
634
640
  secureCookies: config.secureCookies,
635
641
  log: (message) => log.warning('Backoffice sign-in: {message}', { message }),
636
642
  resolve: (provider) =>
637
- new IdentityProviderOverrides(db, config.secretKey).apply('user', provider),
643
+ new IdentityProviderOverrides(
644
+ db,
645
+ config.secretKey,
646
+ config.lockedIdentityProviders,
647
+ ).apply('user', provider),
638
648
  },
639
649
  )
640
650
 
@@ -2726,11 +2736,74 @@ export async function createServer(
2726
2736
  })
2727
2737
  }
2728
2738
 
2739
+ // A send-to-URL workflow's secret header (story 304): sealed here, never
2740
+ // in the form's file, and never shown back. Set on any site, schema
2741
+ // writable or not, since it is the site's own and not the form's.
2742
+ const secretMatch = /^([^/]+)\/workflows\/([^/]+)\/secrets\/([^/]+)$/.exec(action)
2743
+ if (secretMatch && (request.method === 'PUT' || request.method === 'DELETE')) {
2744
+ if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
2745
+ const [, formKey, workflowKey, header] = secretMatch.map((part) =>
2746
+ decodeURIComponent(part),
2747
+ ) as [string, string, string, string]
2748
+ const form = byKey.get(formKey)
2749
+ const workflow = form?.workflows.find((candidate) => candidate.key === workflowKey)
2750
+ const headers = workflow?.settings.headers as Record<string, unknown> | undefined
2751
+ if (!form?.key || !workflow || !isSecretHeader(headers?.[header]))
2752
+ return Response.json(
2753
+ { message: 'The form names no such secret header; save the form first.' },
2754
+ { status: 404 },
2755
+ )
2756
+ const secrets = new FormWorkflowSecretRepository(db)
2757
+ let set: { sealed: string; url: string } | undefined
2758
+ if (request.method === 'PUT') {
2759
+ const body = (await request.json().catch(() => ({}))) as { value?: unknown }
2760
+ if (typeof body.value !== 'string' || body.value === '')
2761
+ return Response.json({ message: 'Give the header a value.' }, { status: 400 })
2762
+ const key = usableSecretKey(config.secretKey)
2763
+ if (!key)
2764
+ return Response.json(
2765
+ {
2766
+ message: `Keeping a secret header needs ${SECRET_KEY_VARIABLE} set on the server.`,
2767
+ },
2768
+ { status: 409 },
2769
+ )
2770
+ set = { sealed: sealSecret(body.value, key), url: String(workflow.settings.url ?? '') }
2771
+ }
2772
+ await secrets.set(form.key, workflowKey, header, set, principal.name ?? null)
2773
+ await recordAudit(db, {
2774
+ category: 'settings',
2775
+ action: set ? 'secret header set' : 'secret header removed',
2776
+ source: 'request',
2777
+ userKey: principal.id,
2778
+ userName: principal.name,
2779
+ entityType: 'form',
2780
+ entityKey: form.key,
2781
+ entityName: form.name,
2782
+ detail: `${workflow.name}: ${header}`,
2783
+ ...clientAddress(request),
2784
+ })
2785
+ return Response.json({ ok: true })
2786
+ }
2787
+
2729
2788
  if (action && request.method === 'GET') {
2730
2789
  const form = byKey.get(decodeURIComponent(action))
2731
2790
  if (!form) return new Response('Not Found', { status: 404 })
2791
+ // Which secret headers are set for the address each workflow sends to, never their values.
2792
+ const secrets: { workflow: string; header: string; set: boolean }[] = []
2793
+ for (const workflow of form.workflows) {
2794
+ const headers = workflow.settings.headers as Record<string, unknown> | undefined
2795
+ const named = Object.keys(headers ?? {}).filter((name) => isSecretHeader(headers?.[name]))
2796
+ if (named.length === 0 || !workflow.key || !form.key) continue
2797
+ const kept = await new FormWorkflowSecretRepository(db).of(form.key, workflow.key)
2798
+ for (const header of named)
2799
+ secrets.push({
2800
+ workflow: workflow.key,
2801
+ header,
2802
+ set: kept.get(header)?.url === workflow.settings.url,
2803
+ })
2804
+ }
2732
2805
  // The whole definition, which is what the designer edits.
2733
- return Response.json({ ...formDetail(form), definition: form })
2806
+ return Response.json({ ...formDetail(form), definition: form, secrets })
2734
2807
  }
2735
2808
 
2736
2809
  // What a choice source offers now, in the default language, for the
@@ -2769,6 +2842,9 @@ export async function createServer(
2769
2842
  if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
2770
2843
  const body = await request.json().catch(() => ({}))
2771
2844
  const folder = url.searchParams.get('folder') ?? undefined
2845
+ const refused = await refusedSendAddresses(coerceForm(body), config.allowPrivateAddresses)
2846
+ if (refused.length > 0)
2847
+ return Response.json({ status: 'invalid', problems: refused }, { status: 400 })
2772
2848
  const written = await saveForm(coerceForm(body), { ...formFiles, folder })
2773
2849
  if (!written.ok) {
2774
2850
  log.warning('{user} could not save a form: {detail}', {
@@ -2785,6 +2861,12 @@ export async function createServer(
2785
2861
  forms.invalidate()
2786
2862
  await ensureFormLibraryTypes(db, forms.all())
2787
2863
  cache.invalidate()
2864
+ const saved = coerceForm(body)
2865
+ if (saved.key)
2866
+ await new FormWorkflowSecretRepository(db).forget(
2867
+ saved.key,
2868
+ saved.workflows.flatMap((workflow) => (workflow.key ? [workflow.key] : [])),
2869
+ )
2788
2870
  log.info('{user} saved the form {form}', {
2789
2871
  user: principal.email,
2790
2872
  form: coerceForm(body).alias,
@@ -2805,6 +2887,7 @@ export async function createServer(
2805
2887
  forms.invalidate()
2806
2888
  await ensureFormLibraryTypes(db, forms.all())
2807
2889
  cache.invalidate()
2890
+ if (form.key) await new FormWorkflowSecretRepository(db).forget(form.key)
2808
2891
  log.info('{user} deleted the form {form}; its entries are kept', {
2809
2892
  user: principal.email,
2810
2893
  form: form.alias,
@@ -3012,6 +3095,7 @@ export async function createServer(
3012
3095
  db,
3013
3096
  config,
3014
3097
  user: principal.email,
3098
+ mayInstallCode: may(principal, RemotePermissions.InstallCode),
3015
3099
  onApplied: () => {
3016
3100
  cache.invalidate()
3017
3101
  mediaCache.clear()
package/src/settings.ts CHANGED
@@ -222,6 +222,13 @@ const DECLARED = [
222
222
  },
223
223
 
224
224
  // Sign-in and secrets
225
+ {
226
+ env: 'CROMBOLO_ALLOW_PRIVATE_ADDRESSES',
227
+ kind: 'boolean',
228
+ section: 'Sign-in and secrets',
229
+ description:
230
+ "Lets webhooks, a form's send-to-URL workflow and an identity provider's test reach loopback, private and link-local addresses, for an intranet. On in development, off otherwise.",
231
+ },
225
232
  {
226
233
  env: 'CROMBOLO_ADMIN_LOGIN',
227
234
  kind: 'string',
@@ -270,6 +277,13 @@ const DECLARED = [
270
277
  description:
271
278
  'Creates the password administrator even when an API client is set. Honoured only on localhost.',
272
279
  },
280
+ {
281
+ env: 'CROMBOLO_LOCKED_IDENTITY_PROVIDERS',
282
+ kind: 'list',
283
+ section: 'Sign-in and secrets',
284
+ description:
285
+ "Identity providers nobody can change in the back office, by id, separated by commas, or `all`: they sign in by the site's configuration alone. A provider declared `locked: true` is locked too.",
286
+ },
273
287
  {
274
288
  env: 'CROMBOLO_SECRET_KEY',
275
289
  kind: 'string',
@@ -428,6 +442,14 @@ const DECLARED = [
428
442
  section: 'Schema',
429
443
  description: 'Whether the back office may change the schema files.',
430
444
  },
445
+ {
446
+ env: 'CROMBOLO_CONTENT_FILES_READONLY',
447
+ kind: 'boolean',
448
+ default: 'false',
449
+ section: 'Schema',
450
+ description:
451
+ 'Stops the back office changing templates, stylesheets and scripts, for a site whose files come from its repository.',
452
+ },
431
453
  {
432
454
  env: 'CROMBOLO_SYNC_SCHEMA_AT_BOOT',
433
455
  kind: 'boolean',
package/src/site-trust.ts CHANGED
@@ -119,6 +119,22 @@ export async function trustedSigners(db: Db, config: CromboloConfig): Promise<Tr
119
119
  return entries
120
120
  }
121
121
 
122
+ /** Whether a signature's key, or the repository that built it, is on this site's list (story 335). */
123
+ export async function signerTrusted(
124
+ db: Db,
125
+ config: CromboloConfig,
126
+ result: ProvenanceResult,
127
+ ): Promise<boolean> {
128
+ if (result.state !== 'signed') return false
129
+ const entries = await trustedSigners(db, config)
130
+ if (result.key) return entries.some((entry) => entry.fingerprint === result.key?.fingerprint)
131
+ const source = result.source
132
+ if (!source) return false
133
+ return entries.some(
134
+ (entry) => entry.kind === 'source' && entry.source && sourceAllowed(source, entry.source),
135
+ )
136
+ }
137
+
122
138
  /** What a site bundle's check decided: refused, or applied, flagged or not, and who signed it. */
123
139
  export interface SiteBundleTrust {
124
140
  problem?: string
@@ -84,6 +84,8 @@ export interface TransferActionContext {
84
84
  config: CromboloConfig
85
85
  /** Who is acting, recorded with each answer. */
86
86
  user: string
87
+ /** They were given "Install code on this site", so a bundle's templates may come in (story 336). */
88
+ mayInstallCode?: boolean
87
89
  /** After an import lands: the published cache was built before it. */
88
90
  onApplied(): void
89
91
  }
@@ -185,6 +187,7 @@ export async function handleTransferAction(
185
187
  label: pending.label ?? undefined,
186
188
  by: ctx.user,
187
189
  passphrase,
190
+ installTemplates: ctx.mayInstallCode === true,
188
191
  })
189
192
  if (result.runId) ctx.onApplied()
190
193
  const names = new Map(result.check.plan.map((entry) => [entry.key, entry.name] as const))