@crombolo/server 0.61.0 → 0.62.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/index.ts CHANGED
@@ -73,6 +73,12 @@ export {
73
73
  extensionEntryProblems,
74
74
  settingsOf,
75
75
  } from './extension-discovery.ts'
76
+ export {
77
+ type InstallExtensionOptions,
78
+ type InstallExtensionResult,
79
+ installExtension,
80
+ removeExtension,
81
+ } from './extension-install.ts'
76
82
  export { denoArguments, netHosts, processReads } from './extension-process.ts'
77
83
  export { normaliseScreenResult, safeScreenHref, screenValues } from './extension-screens.ts'
78
84
  export { extensionSqlProblem } from './extension-sql.ts'
@@ -17,12 +17,10 @@
17
17
  * browser cannot reach npm, and the backoffice keeps making same-origin
18
18
  * requests only.
19
19
  */
20
- import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
21
- import { tmpdir } from 'node:os'
22
- import { join, relative, resolve, sep } from 'node:path'
20
+ import { readFileSync, rmSync } from 'node:fs'
21
+ import { join } from 'node:path'
23
22
  import {
24
23
  type AccessLevel,
25
- askedPermissions,
26
24
  type BundlePackage,
27
25
  type DeclaredPermission,
28
26
  describePermissions,
@@ -30,31 +28,19 @@ import {
30
28
  type ExtensionRegistry,
31
29
  forgetExtension,
32
30
  groupsOf,
33
- isSchema3Field,
34
31
  LEGACY_EXTENSION_KEYWORD,
35
32
  levelOf,
36
- type PackageJson,
37
33
  type PermissionGroups,
38
- packageInRoot,
39
- prepareRoot,
40
34
  RECORD_FILE,
41
35
  ROOTS_DIR,
42
36
  readPackageJson,
43
37
  readRecord,
44
- readSettings,
45
- recordExtension,
46
38
  rootOf,
47
39
  SCHEMA_3_NOT_INSTALLED,
48
40
  SITE_PACKAGE_NOT_INSTALLED,
49
41
  USER_DELEGATE,
50
- validateBundlePackage,
51
42
  } from '@crombolo/backoffice-host'
52
- import {
53
- LOCAL_BUNDLES_DIR,
54
- localBundleFileName,
55
- localBundlePath,
56
- localBundlesNamed,
57
- } from '@crombolo/transfer'
43
+ import { localBundlePath, localBundlesNamed } from '@crombolo/transfer'
58
44
  import {
59
45
  type BundleGrants,
60
46
  DELEGATE_NEEDS_PERSON,
@@ -63,24 +49,40 @@ import {
63
49
  isSchema3,
64
50
  } from './bundle-grants.ts'
65
51
  import { siteLayouts } from './components.ts'
52
+ import {
53
+ type AskedLayout,
54
+ bunInstaller,
55
+ declaresAt as declaresAtRegistry,
56
+ declaresIn,
57
+ installIntoRoot,
58
+ isValidPackageName,
59
+ isValidVersion,
60
+ keepInSite,
61
+ layoutAsked,
62
+ type PackageInstaller,
63
+ provenanceAt as provenanceAtRegistry,
64
+ screensOf,
65
+ signatureRefusal,
66
+ sitePackageRefused,
67
+ } from './extension-install.ts'
66
68
  import { grantRefusal, type UnrestrictedFrom } from './grant-policy.ts'
67
69
  import { logger } from './logging.ts'
68
70
  import {
69
71
  type ProvenancePolicy,
70
72
  type ProvenanceResult,
71
- provenanceProblem,
72
73
  verifyPackage,
73
74
  verifyProvenance,
74
75
  } from './provenance.ts'
75
- import { extractTarball } from './tar.ts'
76
76
 
77
- const log = logger('packages')
77
+ export {
78
+ bunInstaller,
79
+ installCommand,
80
+ isValidPackageName,
81
+ isValidVersion,
82
+ type PackageInstaller,
83
+ } from './extension-install.ts'
78
84
 
79
- /** Where a registry version's tarball is, and what it hashes to. */
80
- interface Dist {
81
- tarball?: string
82
- integrity?: string
83
- }
85
+ const log = logger('packages')
84
86
 
85
87
  /** How long a search is reused. Long enough to page a list, short enough to stay fresh. */
86
88
  const CACHE_MS = 5 * 60 * 1000
@@ -224,12 +226,6 @@ export interface InstallOutcome {
224
226
  file?: string
225
227
  }
226
228
 
227
- export type PackageInstaller = (
228
- action: 'add' | 'remove',
229
- specifier: string,
230
- siteDir: string,
231
- ) => Promise<{ ok: boolean; output: string }>
232
-
233
229
  interface SearchObject {
234
230
  package?: {
235
231
  name?: string
@@ -240,22 +236,6 @@ interface SearchObject {
240
236
  }
241
237
  }
242
238
 
243
- /** A name npm would accept, so nothing shell-ish or path-ish reaches `bun add`. */
244
- export function isValidPackageName(name: string): boolean {
245
- return /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(name) && name.length <= 214
246
- }
247
-
248
- /**
249
- * A version or range that cannot be mistaken for another argument.
250
- *
251
- * Ranges start with an operator — `^2.1`, `>=1 <2` — so those lead; `-` never
252
- * does, because `bun add` would read it as a flag. No shell is involved
253
- * (`Bun.spawn` takes an argv), so the space in a range is harmless.
254
- */
255
- export function isValidVersion(version: string): boolean {
256
- return /^[A-Za-z0-9^~>=<*][A-Za-z0-9.^~>=<| *+-]*$/.test(version) && version.length <= 64
257
- }
258
-
259
239
  export interface Marketplace {
260
240
  /** Where someone browsing should be sent, when they want more than this list. */
261
241
  url(): string
@@ -307,63 +287,6 @@ export interface Marketplace {
307
287
  uninstall(name: string): Promise<InstallOutcome>
308
288
  }
309
289
 
310
- /**
311
- * The argv an install runs. `add` never runs a package's install scripts,
312
- * whatever Bun's own list of trusted packages says (story 194).
313
- */
314
- export function installCommand(action: 'add' | 'remove', specifier: string): string[] {
315
- return action === 'add'
316
- ? ['bun', 'add', '--ignore-scripts', specifier]
317
- : ['bun', action, specifier]
318
- }
319
-
320
- /**
321
- * `bun add` in the site directory: Bun owns resolution and writes the lockfile.
322
- *
323
- * The spawn itself can fail rather than the command — an unreadable site
324
- * directory or a `bun` that is not on the path both throw out of `Bun.spawn` —
325
- * and that has to come back as a failed install with a reason, not as an
326
- * exception the route turns into a 500.
327
- */
328
- export const bunInstaller: PackageInstaller = async (action, specifier, siteDir) => {
329
- try {
330
- const proc = Bun.spawn(installCommand(action, specifier), {
331
- cwd: siteDir,
332
- stdout: 'pipe',
333
- stderr: 'pipe',
334
- })
335
- const [stdout, stderr, code] = await Promise.all([
336
- new Response(proc.stdout).text(),
337
- new Response(proc.stderr).text(),
338
- proc.exited,
339
- ])
340
- return { ok: code === 0, output: `${stdout}${stderr}`.trim() }
341
- } catch (error) {
342
- return {
343
- ok: false,
344
- output: `bun ${action} could not be run in ${siteDir}: ${
345
- error instanceof Error ? error.message : String(error)
346
- }`,
347
- }
348
- }
349
- }
350
-
351
- /** The layout setting a version declares, if it has page templates to place (story 312). */
352
- type AskedLayout = { key: string; label: string; suggested?: string }
353
-
354
- function layoutAsked(field: { settings?: unknown } | undefined): AskedLayout | undefined {
355
- const read = readSettings(field?.settings)
356
- if (!('settings' in read)) return undefined
357
- const found = Object.entries(read.settings).find(([, setting]) => setting.type === 'layout')
358
- if (!found) return undefined
359
- const [key, setting] = found
360
- return {
361
- key,
362
- label: setting.label,
363
- ...(typeof setting.default === 'string' ? { suggested: setting.default } : {}),
364
- }
365
- }
366
-
367
290
  export function createMarketplace(options: MarketplaceOptions): Marketplace {
368
291
  /** The site's layouts to pick from, the suggestion kept only when the site has it. */
369
292
  const layoutChoice = (asked: AskedLayout | undefined): InstallOutcome['layout'] => {
@@ -399,28 +322,6 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
399
322
  }
400
323
  let cached: { at: number; query: string; listings: MarketplaceListing[] } | undefined
401
324
 
402
- /**
403
- * A bundle's file at `bundles/<name>-<version>.tgz`: used in place when it is
404
- * there already, copied there otherwise. Another file under that name is
405
- * refused, since one version is one file.
406
- */
407
- const keepInSite = (
408
- file: string,
409
- declared: { name: string; version: string },
410
- ): { path: string; copied: boolean } | string => {
411
- const path = `${LOCAL_BUNDLES_DIR}/${localBundleFileName(declared.name, declared.version)}`
412
- const target = join(options.siteDir, path)
413
- if (resolve(file) === resolve(target)) return { path, copied: false }
414
- const bytes = readFileSync(file)
415
- if (existsSync(target)) {
416
- if (readFileSync(target).equals(bytes)) return { path, copied: false }
417
- return `${path} already holds a different ${declared.name}@${declared.version} than ${file}, so it was not installed: one version is one file. Remove ${path} first if ${file} is the one to keep.`
418
- }
419
- mkdirSync(join(options.siteDir, LOCAL_BUNDLES_DIR), { recursive: true })
420
- copyFileSync(file, target)
421
- return { path, copied: true }
422
- }
423
-
424
325
  /** The `bundles/` file a dependency used to name, removed once nothing names it. */
425
326
  const removeUnnamed = (previousRange: string | undefined, keep?: string) => {
426
327
  const path = localBundlePath(previousRange)
@@ -433,135 +334,19 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
433
334
  options.extensions.bundles().bundles.find((bundle) => bundle.packageName === name)?.version ??
434
335
  null
435
336
 
436
- /**
437
- * What the registry says a version carries: the version asked for (an exact
438
- * one, or the highest a range admits), or the latest. `not-a-bundle` when that
439
- * version is no valid bundle, `unreachable` when the registry could not say.
440
- */
441
- const declaresAt = async (
442
- name: string,
443
- wanted?: string,
444
- ): Promise<
445
- | (BundlePackage['carries'] & {
446
- permissions: DeclaredPermission[]
447
- layout?: AskedLayout
448
- version: string
449
- dist?: Dist
450
- id?: string
451
- screens?: number
452
- })
453
- | 'not-a-bundle'
454
- | { refused: string[] }
455
- | 'site-package'
456
- | 'schema-3'
457
- | 'unreachable'
458
- > => {
459
- try {
460
- const response = await call(`${options.registry}/${encodeURIComponent(name)}`, {
461
- headers: { accept: 'application/json' },
462
- })
463
- if (!response.ok) return response.status === 404 ? 'not-a-bundle' : 'unreachable'
464
- const packument = (await response.json()) as {
465
- 'dist-tags'?: Record<string, string>
466
- versions?: Record<string, PackageJson>
467
- }
468
- const versions = packument.versions ?? {}
469
- const resolved =
470
- wanted === undefined
471
- ? packument['dist-tags']?.latest
472
- : wanted in versions
473
- ? wanted
474
- : (packument['dist-tags']?.[wanted] ??
475
- Object.keys(versions)
476
- .filter((v) => Bun.semver.satisfies(v, wanted))
477
- .sort(Bun.semver.order)
478
- .at(-1))
479
- const version = resolved ? versions[resolved] : undefined
480
- // A site package is never installed, whatever a registry offers (story 306).
481
- if ((version?.crombolo as { bundleType?: unknown } | undefined)?.bundleType === 'site')
482
- return 'site-package'
483
- if (!resolved || !version) return 'not-a-bundle'
484
- // Why it is not one, so its author knows what to change: a layout before 0.59 among them (story 320).
485
- const problems = validateBundlePackage(version)
486
- if (problems.length > 0) return { refused: problems }
487
- const dist = (version as { dist?: Dist }).dist
488
- const field = version.crombolo as {
489
- extensions?: unknown[]
490
- content?: boolean
491
- id?: string
492
- server?: string
493
- permissions?: unknown
494
- settings?: unknown
495
- }
496
- // Story 308: a version that says nothing of why it asks is not installed.
497
- if (isSchema3Field(field)) return 'schema-3'
498
- return {
499
- extensions: Array.isArray(field.extensions) && field.extensions.length > 0,
500
- content: field.content === true,
501
- server: field.server !== undefined,
502
- permissions: askedPermissions(field),
503
- layout: layoutAsked(field),
504
- version: resolved,
505
- ...(typeof field.id === 'string' ? { id: field.id } : {}),
506
- screens: screensOf(field),
507
- ...(dist ? { dist } : {}),
508
- }
509
- } catch {
510
- return 'unreachable'
511
- }
512
- }
513
-
337
+ const declaresAt = (name: string, wanted?: string) =>
338
+ declaresAtRegistry(options.registry, name, wanted, call)
514
339
  const verify = options.verify ?? ((dir: string) => verifyProvenance(dir))
515
-
516
- /**
517
- * Where a registry version was built (story 060): its exact tarball fetched,
518
- * held to the registry's integrity, and its signature checked, so the bytes
519
- * checked are the bytes `bun add` then installs. A registry that gives no
520
- * tarball leaves nothing to check; one that cannot be fetched is not unsigned.
521
- */
522
- const provenanceAt = async (name: string, dist: Dist | undefined): Promise<ProvenanceResult> => {
523
- if (!dist?.tarball) return { state: 'unsigned' }
524
- const dir = mkdtempSync(join(tmpdir(), 'crombolo-bundle-check-'))
525
- try {
526
- const response = await call(dist.tarball)
527
- if (!response.ok)
528
- return {
529
- state: 'unchecked',
530
- reason: `${name} could not be fetched to check its signature (the registry answered ${response.status})`,
531
- }
532
- const bytes = new Uint8Array(await response.arrayBuffer())
533
- if (dist.integrity?.startsWith('sha512-')) {
534
- const got = `sha512-${new Bun.CryptoHasher('sha512').update(bytes).digest('base64')}`
535
- if (got !== dist.integrity)
536
- return { state: 'invalid', reason: `${name} is not the package the registry describes` }
537
- }
538
- const file = join(dir, 'bundle.tgz')
539
- await Bun.write(file, bytes)
540
- const unpacked = join(dir, 'package')
541
- await extractTarball(file, unpacked)
542
- return await verify(unpacked)
543
- } catch (error) {
544
- return {
545
- state: 'unchecked',
546
- reason: `${name} could not be checked: ${error instanceof Error ? error.message : String(error)}`,
547
- }
548
- } finally {
549
- rmSync(dir, { recursive: true, force: true })
550
- }
551
- }
340
+ const provenanceAt = (name: string, dist: Parameters<typeof provenanceAtRegistry>[1]) =>
341
+ provenanceAtRegistry(name, dist, { fetch: call, verify })
552
342
 
553
343
  /** Why the site's policy refuses a version, as an outcome, or undefined when it may be installed. */
554
344
  const refusedBySignature = (
555
345
  label: string,
556
346
  provenance: ProvenanceResult,
557
347
  ): InstallOutcome | undefined => {
558
- const problem = provenanceProblem(
559
- provenance,
560
- options.policy ?? { signatures: 'optional', sources: [] },
561
- )
562
- return problem
563
- ? { ok: false, message: `${label} was not installed: ${problem}.`, provenance }
564
- : undefined
348
+ const message = signatureRefusal(label, provenance, options.policy)
349
+ return message ? { ok: false, message, provenance } : undefined
565
350
  }
566
351
 
567
352
  /** Why the person may not grant what it asks for here: its level, by who they are and its signature (story 324). */
@@ -828,7 +613,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
828
613
  return grantNeeded(declared.name, declared.permissions, '', layoutChoice(declared.layout))
829
614
  // Kept in the site's bundles/ (story 245), so it is committed and every
830
615
  // node, checkout and CI build installs the same file.
831
- const kept = keepInSite(file, declared)
616
+ const kept = keepInSite(options.siteDir, file, declared)
832
617
  if (typeof kept === 'string') return { ok: false, message: kept }
833
618
  const discard = () => {
834
619
  if (kept.copied) rmSync(join(options.siteDir, kept.path), { force: true })
@@ -913,31 +698,14 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
913
698
  into: { id: string; integrity?: string },
914
699
  ): Promise<InstallOutcome> {
915
700
  // Story 326: into a root of its own, never the site's dependencies.
916
- const root = prepareRoot(options.siteDir, into.id)
917
- const inRoot = specifier.startsWith('./')
918
- ? `file:${relative(root, join(options.siteDir, specifier)).split(sep).join('/')}`
919
- : specifier
920
- const result = await install('add', inRoot, root)
921
- if (!result.ok) {
922
- options.extensions.invalidate()
923
- return {
924
- ok: false,
925
- message: result.output || `Installing ${specifier} failed.`,
926
- }
927
- }
928
- const landed = readPackageJson(
929
- join(packageInRoot(options.siteDir, into.id, name), 'package.json'),
701
+ const installed = await installIntoRoot(
702
+ options.siteDir,
703
+ { id: into.id, name, specifier, version, integrity: into.integrity },
704
+ install,
930
705
  )
931
- recordExtension(options.siteDir, into.id, {
932
- name,
933
- version: landed?.version ?? version ?? 'unknown',
934
- ...(into.integrity ? { integrity: into.integrity } : {}),
935
- })
936
706
  options.extensions.invalidate()
937
- const undo = () => {
938
- rmSync(root, { recursive: true, force: true })
939
- forgetExtension(options.siteDir, into.id)
940
- }
707
+ if (!installed.ok) return { ok: false, message: installed.message }
708
+ const undo = installed.undo
941
709
 
942
710
  const range = (await rangeFor(name)) ?? version ?? 'latest'
943
711
  const discovered = options.extensions.bundles()
@@ -1030,58 +798,6 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
1030
798
  }
1031
799
  }
1032
800
 
1033
- /** A site package offered as a dependency: refused, saying how one is used (story 306). */
1034
- function sitePackageRefused(name: string): { ok: false; message: string } {
1035
- return {
1036
- ok: false,
1037
- message: `${name} is a site package, which is applied to a site with \`crombolo site apply\`, never installed, so it was not installed.`,
1038
- }
1039
- }
1040
-
1041
- /** What a packed bundle on this machine declares, read from its package.json, or why it cannot be installed. */
1042
- async function declaresIn(file: string): Promise<
1043
- | {
1044
- id: string
1045
- name: string
1046
- version: string
1047
- server: boolean
1048
- permissions: DeclaredPermission[]
1049
- layout?: AskedLayout
1050
- }
1051
- | string
1052
- > {
1053
- const dir = mkdtempSync(join(tmpdir(), 'crombolo-bundle-file-'))
1054
- try {
1055
- await extractTarball(file, dir)
1056
- const root = existsSync(join(dir, 'package', 'package.json')) ? join(dir, 'package') : dir
1057
- const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as PackageJson
1058
- if ((json.crombolo as { bundleType?: unknown } | undefined)?.bundleType === 'site')
1059
- return sitePackageRefused(file).message
1060
- const problems = validateBundlePackage(json)
1061
- if (problems.length > 0 || typeof json.name !== 'string' || typeof json.version !== 'string')
1062
- return `${file} is not an extension for this site, so it was not installed.`
1063
- const field = json.crombolo as {
1064
- id: string
1065
- server?: string
1066
- permissions?: unknown
1067
- settings?: unknown
1068
- }
1069
- if (isSchema3Field(field)) return `${file} was not installed: ${SCHEMA_3_NOT_INSTALLED}.`
1070
- return {
1071
- id: field.id,
1072
- name: json.name,
1073
- version: json.version,
1074
- server: field.server !== undefined,
1075
- permissions: askedPermissions(field),
1076
- layout: layoutAsked(field),
1077
- }
1078
- } catch {
1079
- return `${file} could not be read as a packed bundle, so it was not installed.`
1080
- } finally {
1081
- rmSync(dir, { recursive: true, force: true })
1082
- }
1083
- }
1084
-
1085
801
  /** A package's own description, read leniently: anything unreadable is none. */
1086
802
  /** Who made an installed package, as its `author` says: npm's publisher is not kept with it. */
1087
803
  function authorOf(directory: string): string | null {
@@ -1132,14 +848,6 @@ function consented(
1132
848
  return granted.size === new Set(permissions).size && permissions.every((p) => granted.has(p))
1133
849
  }
1134
850
 
1135
- /** How many screens its manifest's entries name (story 323), for what it adds. */
1136
- const screensOf = (field: { extensions?: unknown }): number =>
1137
- Array.isArray(field.extensions)
1138
- ? field.extensions.filter(
1139
- (entry) => entry && typeof entry === 'object' && 'screen' in (entry as object),
1140
- ).length
1141
- : 0
1142
-
1143
851
  /** A refusal the screen answers by showing what it asks for, with the reasons, and the grant. */
1144
852
  function grantNeeded(
1145
853
  name: string,
@@ -282,7 +282,11 @@ export function createMemberAuth(
282
282
  applicationUrl: config.applicationUrl,
283
283
  secureCookies: config.secureCookies,
284
284
  resolve: (provider) =>
285
- new IdentityProviderOverrides(db, config.secretKey).apply('member', provider),
285
+ new IdentityProviderOverrides(
286
+ db,
287
+ config.secretKey,
288
+ config.lockedIdentityProviders,
289
+ ).apply('member', provider),
286
290
  },
287
291
  )
288
292
 
@@ -122,7 +122,7 @@ export async function checkedAddress(
122
122
  const reason = refusedAddress(address)
123
123
  if (reason)
124
124
  throw new OutboundRefused(
125
- `${host === address ? host : `${host} (${address})`} is ${reason}, which this site does not send to. The config's webhooks.allowPrivateAddresses allows it.`,
125
+ `${host === address ? host : `${host} (${address})`} is ${reason}, which this site does not send to. CROMBOLO_ALLOW_PRIVATE_ADDRESSES allows it.`,
126
126
  )
127
127
  }
128
128
  return addresses[0]
package/src/server.ts CHANGED
@@ -90,6 +90,7 @@ import {
90
90
  ensureKeyValue,
91
91
  FormEntryRepository,
92
92
  FormWorkflowRepository,
93
+ FormWorkflowSecretRepository,
93
94
  JobRepository,
94
95
  type JobState,
95
96
  latestContentVersionId,
@@ -208,6 +209,7 @@ import {
208
209
  writeFlash,
209
210
  } from './form-submit.ts'
210
211
  import { describeFormTypes, formTypesFor } from './form-types.ts'
212
+ import { isSecretHeader, refusedSendAddresses } from './form-workflows.ts'
211
213
  import {
212
214
  entriesCsv,
213
215
  formDetail,
@@ -286,6 +288,7 @@ import { syncConfiguredRedirects } from './redirects.ts'
286
288
  import { createRoutes, type DeclaredRoute, SITE_ROUTE_OWNER, siteRouteProblems } from './routes.ts'
287
289
  import { componentAliasesIn, importSchema, type SchemaBoot, watchSchema } from './schema.ts'
288
290
  import { publishSchema, type SchemaStore } from './schema-store.ts'
291
+ import { SECRET_KEY_VARIABLE, sealSecret, usableSecretKey } from './secrets.ts'
289
292
  import { createSeoHost, originOf, publicOrigin } from './seo.ts'
290
293
  import {
291
294
  combineHubs,
@@ -634,7 +637,11 @@ export async function createServer(
634
637
  secureCookies: config.secureCookies,
635
638
  log: (message) => log.warning('Backoffice sign-in: {message}', { message }),
636
639
  resolve: (provider) =>
637
- new IdentityProviderOverrides(db, config.secretKey).apply('user', provider),
640
+ new IdentityProviderOverrides(
641
+ db,
642
+ config.secretKey,
643
+ config.lockedIdentityProviders,
644
+ ).apply('user', provider),
638
645
  },
639
646
  )
640
647
 
@@ -2726,11 +2733,74 @@ export async function createServer(
2726
2733
  })
2727
2734
  }
2728
2735
 
2736
+ // A send-to-URL workflow's secret header (story 304): sealed here, never
2737
+ // in the form's file, and never shown back. Set on any site, schema
2738
+ // writable or not, since it is the site's own and not the form's.
2739
+ const secretMatch = /^([^/]+)\/workflows\/([^/]+)\/secrets\/([^/]+)$/.exec(action)
2740
+ if (secretMatch && (request.method === 'PUT' || request.method === 'DELETE')) {
2741
+ if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
2742
+ const [, formKey, workflowKey, header] = secretMatch.map((part) =>
2743
+ decodeURIComponent(part),
2744
+ ) as [string, string, string, string]
2745
+ const form = byKey.get(formKey)
2746
+ const workflow = form?.workflows.find((candidate) => candidate.key === workflowKey)
2747
+ const headers = workflow?.settings.headers as Record<string, unknown> | undefined
2748
+ if (!form?.key || !workflow || !isSecretHeader(headers?.[header]))
2749
+ return Response.json(
2750
+ { message: 'The form names no such secret header; save the form first.' },
2751
+ { status: 404 },
2752
+ )
2753
+ const secrets = new FormWorkflowSecretRepository(db)
2754
+ let set: { sealed: string; url: string } | undefined
2755
+ if (request.method === 'PUT') {
2756
+ const body = (await request.json().catch(() => ({}))) as { value?: unknown }
2757
+ if (typeof body.value !== 'string' || body.value === '')
2758
+ return Response.json({ message: 'Give the header a value.' }, { status: 400 })
2759
+ const key = usableSecretKey(config.secretKey)
2760
+ if (!key)
2761
+ return Response.json(
2762
+ {
2763
+ message: `Keeping a secret header needs ${SECRET_KEY_VARIABLE} set on the server.`,
2764
+ },
2765
+ { status: 409 },
2766
+ )
2767
+ set = { sealed: sealSecret(body.value, key), url: String(workflow.settings.url ?? '') }
2768
+ }
2769
+ await secrets.set(form.key, workflowKey, header, set, principal.name ?? null)
2770
+ await recordAudit(db, {
2771
+ category: 'settings',
2772
+ action: set ? 'secret header set' : 'secret header removed',
2773
+ source: 'request',
2774
+ userKey: principal.id,
2775
+ userName: principal.name,
2776
+ entityType: 'form',
2777
+ entityKey: form.key,
2778
+ entityName: form.name,
2779
+ detail: `${workflow.name}: ${header}`,
2780
+ ...clientAddress(request),
2781
+ })
2782
+ return Response.json({ ok: true })
2783
+ }
2784
+
2729
2785
  if (action && request.method === 'GET') {
2730
2786
  const form = byKey.get(decodeURIComponent(action))
2731
2787
  if (!form) return new Response('Not Found', { status: 404 })
2788
+ // Which secret headers are set for the address each workflow sends to, never their values.
2789
+ const secrets: { workflow: string; header: string; set: boolean }[] = []
2790
+ for (const workflow of form.workflows) {
2791
+ const headers = workflow.settings.headers as Record<string, unknown> | undefined
2792
+ const named = Object.keys(headers ?? {}).filter((name) => isSecretHeader(headers?.[name]))
2793
+ if (named.length === 0 || !workflow.key || !form.key) continue
2794
+ const kept = await new FormWorkflowSecretRepository(db).of(form.key, workflow.key)
2795
+ for (const header of named)
2796
+ secrets.push({
2797
+ workflow: workflow.key,
2798
+ header,
2799
+ set: kept.get(header)?.url === workflow.settings.url,
2800
+ })
2801
+ }
2732
2802
  // The whole definition, which is what the designer edits.
2733
- return Response.json({ ...formDetail(form), definition: form })
2803
+ return Response.json({ ...formDetail(form), definition: form, secrets })
2734
2804
  }
2735
2805
 
2736
2806
  // What a choice source offers now, in the default language, for the
@@ -2769,6 +2839,9 @@ export async function createServer(
2769
2839
  if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
2770
2840
  const body = await request.json().catch(() => ({}))
2771
2841
  const folder = url.searchParams.get('folder') ?? undefined
2842
+ const refused = await refusedSendAddresses(coerceForm(body), config.allowPrivateAddresses)
2843
+ if (refused.length > 0)
2844
+ return Response.json({ status: 'invalid', problems: refused }, { status: 400 })
2772
2845
  const written = await saveForm(coerceForm(body), { ...formFiles, folder })
2773
2846
  if (!written.ok) {
2774
2847
  log.warning('{user} could not save a form: {detail}', {
@@ -2785,6 +2858,12 @@ export async function createServer(
2785
2858
  forms.invalidate()
2786
2859
  await ensureFormLibraryTypes(db, forms.all())
2787
2860
  cache.invalidate()
2861
+ const saved = coerceForm(body)
2862
+ if (saved.key)
2863
+ await new FormWorkflowSecretRepository(db).forget(
2864
+ saved.key,
2865
+ saved.workflows.flatMap((workflow) => (workflow.key ? [workflow.key] : [])),
2866
+ )
2788
2867
  log.info('{user} saved the form {form}', {
2789
2868
  user: principal.email,
2790
2869
  form: coerceForm(body).alias,
@@ -2805,6 +2884,7 @@ export async function createServer(
2805
2884
  forms.invalidate()
2806
2885
  await ensureFormLibraryTypes(db, forms.all())
2807
2886
  cache.invalidate()
2887
+ if (form.key) await new FormWorkflowSecretRepository(db).forget(form.key)
2808
2888
  log.info('{user} deleted the form {form}; its entries are kept', {
2809
2889
  user: principal.email,
2810
2890
  form: form.alias,