@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.
@@ -258,6 +258,8 @@ export class ExtensionProcess {
258
258
  #lastCrash = 0
259
259
  #idle: ReturnType<typeof setTimeout> | undefined
260
260
  #stderr: string[] = []
261
+ /** Settles once the running process's error output has been read to its end. */
262
+ #errorsRead: Promise<void> = Promise.resolve()
261
263
  #stopped = false
262
264
 
263
265
  constructor(options: ExtensionProcessOptions) {
@@ -323,7 +325,7 @@ export class ExtensionProcess {
323
325
  )
324
326
  this.#child = child
325
327
  this.#stderr = []
326
- this.#readErrors(child.stderr as ReadableStream<Uint8Array>)
328
+ this.#errorsRead = this.#readErrors(child.stderr as ReadableStream<Uint8Array>)
327
329
  const ready = new Promise<void>((resolve, reject) => {
328
330
  this.#replies.set(0, {
329
331
  resolve: (description) => {
@@ -334,6 +336,9 @@ export class ExtensionProcess {
334
336
  })
335
337
  })
336
338
  this.#listen(child)
339
+ // A process that died as it started cannot take its first message. Failing to send it is
340
+ // not the reason to report: `#listen` sees the exit and rejects `ready` with what the
341
+ // extension itself wrote on its way out.
337
342
  this.#send({ t: 'init', settings: this.#options.settings, dialect: this.#options.dialect })
338
343
  const timer = setTimeout(
339
344
  () =>
@@ -356,11 +361,15 @@ export class ExtensionProcess {
356
361
 
357
362
  async #readErrors(stream: ReadableStream<Uint8Array>) {
358
363
  const decoder = new TextDecoder()
359
- for await (const chunk of stream) {
360
- for (const line of decoder.decode(chunk).split('\n').filter(Boolean)) {
361
- this.#stderr.push(line)
362
- if (this.#stderr.length > 20) this.#stderr.shift()
364
+ try {
365
+ for await (const chunk of stream) {
366
+ for (const line of decoder.decode(chunk).split('\n').filter(Boolean)) {
367
+ this.#stderr.push(line)
368
+ if (this.#stderr.length > 20) this.#stderr.shift()
369
+ }
363
370
  }
371
+ } catch {
372
+ // A stream torn down with its process has nothing more to say.
364
373
  }
365
374
  }
366
375
 
@@ -382,6 +391,8 @@ export class ExtensionProcess {
382
391
  this.#kill()
383
392
  }
384
393
  const code = await exited
394
+ // What it wrote on its way out is the reason it stopped: read it all before saying so.
395
+ await Promise.race([this.#errorsRead, Bun.sleep(1000)])
385
396
  if (this.#child !== child) return
386
397
  this.#child = undefined
387
398
  if (!this.#stopped) {
@@ -407,12 +418,24 @@ export class ExtensionProcess {
407
418
  this.#replies.clear()
408
419
  }
409
420
 
421
+ /**
422
+ * Writes a frame to the process. A process that has exited cannot take one, and
423
+ * that is not an error to raise here: `#listen` sees the exit, and rejects every
424
+ * call waiting on it with the extension's own words.
425
+ */
410
426
  #send(frame: Frame) {
411
427
  const child = this.#child
412
428
  if (!child) return
413
429
  const sink = child.stdin as import('bun').FileSink
414
- sink.write(frameBytes(frame))
415
- sink.flush()
430
+ const quiet = (result: unknown) => {
431
+ if (result instanceof Promise) result.catch(() => {})
432
+ }
433
+ try {
434
+ quiet(sink.write(frameBytes(frame)))
435
+ quiet(sink.flush())
436
+ } catch {
437
+ // Its input is closed: the process has gone, or is going.
438
+ }
416
439
  }
417
440
 
418
441
  #kill() {
@@ -265,6 +265,16 @@ export function createExternalSignIn(
265
265
  if (!declared || rest.length > 0) return undefined
266
266
  if (request.method !== 'GET') return new Response(null, { status: 405 })
267
267
  const provider = options.resolve ? await options.resolve(declared) : declared
268
+ // Story 305: never a sign-in to an issuer without the secret meant for it.
269
+ if (provider.unavailable) {
270
+ options.log?.(provider.unavailable)
271
+ return redirect(
272
+ audience.failed(
273
+ localReturnUrl(new URL(request.url).searchParams.get('returnUrl')) ?? '/',
274
+ `${provider.oidc.name} sign-in is not available right now. Ask an administrator.`,
275
+ ),
276
+ )
277
+ }
268
278
  const client = clientFor(provider)
269
279
  if (step === undefined || step === '') return start(request, provider, client)
270
280
  if (step === 'callback') return finish(request, provider, client)
@@ -25,6 +25,7 @@ import {
25
25
  DocumentRepository,
26
26
  FormWorkflowRepository,
27
27
  type FormWorkflowRun,
28
+ FormWorkflowSecretRepository,
28
29
  type NodeSchemaState,
29
30
  } from '@crombolo/data'
30
31
  import type { EmailField, EmailProps, EmailRenderResult } from '@crombolo/render'
@@ -33,6 +34,13 @@ import { htmlToText } from './email-text.ts'
33
34
  import type { FormWorkflowTypeDefinition } from './form-types.ts'
34
35
  import { logger } from './logging.ts'
35
36
  import type { MediaFileStore } from './media-files.ts'
37
+ import {
38
+ checkedAddress,
39
+ type OutboundOptions,
40
+ OutboundRefused,
41
+ pinnedFetch,
42
+ } from './outbound-address.ts'
43
+ import { openSecret, usableSecretKey } from './secrets.ts'
36
44
 
37
45
  const log = logger('forms')
38
46
 
@@ -65,6 +73,10 @@ export interface WorkflowDeps {
65
73
  email?: EmailPort
66
74
  mediaFiles?: MediaFileStore
67
75
  fetch?: typeof fetch
76
+ /** Where a send-to-URL workflow may go (story 304); a test's own lookup. */
77
+ outbound?: Omit<OutboundOptions, 'fetch'>
78
+ /** Opens a send-to-URL workflow's secret headers. */
79
+ secretKey?: string
68
80
  nodeState?: NodeSchemaState
69
81
  nodeId?: string
70
82
  /** Told when a workflow published something, so the cache is dropped. */
@@ -436,6 +448,84 @@ async function saveAsContent(
436
448
 
437
449
  // ------------------------------------------------------------------ send to url
438
450
 
451
+ /** A header the form names as secret, its value kept sealed in the database (story 304). */
452
+ export const isSecretHeader = (value: unknown): value is { secret: true } =>
453
+ Boolean(value && typeof value === 'object' && (value as { secret?: unknown }).secret === true)
454
+
455
+ /** What a log keeps of a refusal: a short text answer, nothing of any other. */
456
+ async function answerText(response: Response): Promise<string> {
457
+ const type = response.headers.get('content-type') ?? ''
458
+ if (!/^text\/|json|xml/i.test(type)) return ''
459
+ return (await response.text().catch(() => '')).trim().slice(0, 300)
460
+ }
461
+
462
+ /** The headers to send: those written in the form, and its secrets, opened for this URL. */
463
+ async function sendHeaders(
464
+ workflow: SchemaFormWorkflow,
465
+ context: WorkflowContext,
466
+ deps: WorkflowDeps,
467
+ url: string,
468
+ ): Promise<{ headers: Record<string, string> } | { error: string }> {
469
+ const settings = workflow.settings.headers
470
+ const written =
471
+ settings && typeof settings === 'object' && !Array.isArray(settings)
472
+ ? (settings as Record<string, unknown>)
473
+ : {}
474
+ const headers: Record<string, string> = {}
475
+ const secret: string[] = []
476
+ for (const [name, value] of Object.entries(written)) {
477
+ if (isSecretHeader(value)) secret.push(name)
478
+ else if (typeof value === 'string') headers[name] = value
479
+ }
480
+ if (secret.length === 0) return { headers }
481
+ const key = usableSecretKey(deps.secretKey)
482
+ const kept =
483
+ context.form.key && workflow.key
484
+ ? await new FormWorkflowSecretRepository(deps.db).of(context.form.key, workflow.key)
485
+ : new Map()
486
+ for (const name of secret) {
487
+ const stored = kept.get(name)
488
+ if (!stored) return { error: `The secret header "${name}" has not been set.` }
489
+ if (stored.url !== url)
490
+ return {
491
+ error: `The secret header "${name}" was set for another address; set it again for this one.`,
492
+ }
493
+ try {
494
+ if (!key) throw new Error('no key')
495
+ headers[name] = openSecret(stored.sealed, key)
496
+ } catch {
497
+ return {
498
+ error: `The secret header "${name}" cannot be read with this server's CROMBOLO_SECRET_KEY; set it again.`,
499
+ }
500
+ }
501
+ }
502
+ return { headers }
503
+ }
504
+
505
+ /**
506
+ * Why a form may not be saved sending where it says: a send-to-URL workflow's
507
+ * address, where its host already resolves, that the site does not send to. A
508
+ * host that does not resolve yet is checked at each send instead.
509
+ */
510
+ export async function refusedSendAddresses(
511
+ form: SchemaForm,
512
+ allowPrivateAddresses: boolean,
513
+ lookup?: OutboundOptions['lookup'],
514
+ ): Promise<{ path: string; message: string }[]> {
515
+ const problems: { path: string; message: string }[] = []
516
+ for (const [index, workflow] of form.workflows.entries()) {
517
+ const url = workflow.type === 'sendToUrl' ? asString(workflow.settings.url) : undefined
518
+ if (!url || !URL.canParse(url)) continue
519
+ try {
520
+ await checkedAddress(new URL(url), { allowPrivateAddresses, lookup })
521
+ } catch (error) {
522
+ if (error instanceof OutboundRefused && !error.message.endsWith('has no address.'))
523
+ problems.push({ path: `workflow[${index}].settings.url`, message: error.message })
524
+ }
525
+ }
526
+ return problems
527
+ }
528
+
439
529
  async function sendToUrl(
440
530
  workflow: SchemaFormWorkflow,
441
531
  context: WorkflowContext,
@@ -445,10 +535,8 @@ async function sendToUrl(
445
535
  const url = asString(settings.url)
446
536
  if (!url) return { ok: false, retry: false, error: 'The workflow names no URL.' }
447
537
  const method = settings.method === 'PUT' ? 'PUT' : 'POST'
448
- const headers =
449
- settings.headers && typeof settings.headers === 'object' && !Array.isArray(settings.headers)
450
- ? (settings.headers as Record<string, string>)
451
- : {}
538
+ const headers = await sendHeaders(workflow, context, deps, url)
539
+ if ('error' in headers) return { ok: false, retry: false, error: headers.error }
452
540
 
453
541
  const fields: Record<string, string | string[]> = {}
454
542
  for (const value of context.values)
@@ -463,15 +551,25 @@ async function sendToUrl(
463
551
  body.submittedAt = new Date().toISOString()
464
552
  }
465
553
 
466
- const call = deps.fetch ?? fetch
467
554
  try {
468
- const response = await call(url, {
469
- method,
470
- headers: { 'content-type': 'application/json', ...headers },
471
- body: JSON.stringify(body),
472
- })
555
+ const response = await pinnedFetch(
556
+ url,
557
+ {
558
+ method,
559
+ headers: { 'content-type': 'application/json', ...headers.headers },
560
+ body: JSON.stringify(body),
561
+ },
562
+ { ...deps.outbound, fetch: deps.fetch },
563
+ )
473
564
  if (response.ok) return { ok: true, detail: String(response.status) }
474
- const detail = (await response.text().catch(() => '')).trim().slice(0, 300)
565
+ // Story 304: a redirect is the receiver's answer, never followed.
566
+ if (response.status >= 300 && response.status < 400)
567
+ return {
568
+ ok: false,
569
+ retry: false,
570
+ error: `the endpoint answered ${response.status}, a redirect, which is not followed`,
571
+ }
572
+ const detail = await answerText(response)
475
573
  // A 4xx will not fix itself; a 5xx might.
476
574
  return {
477
575
  ok: false,
@@ -481,7 +579,7 @@ async function sendToUrl(
481
579
  } catch (error) {
482
580
  return {
483
581
  ok: false,
484
- retry: true,
582
+ retry: !(error instanceof OutboundRefused),
485
583
  error: error instanceof Error ? error.message : String(error),
486
584
  }
487
585
  }
@@ -16,9 +16,26 @@ export type UnrestrictedFrom = 'backoffice' | 'config'
16
16
  export const unrestrictedFrom = (value: string | undefined): UnrestrictedFrom =>
17
17
  value?.trim().toLowerCase() === 'config' ? 'config' : 'backoffice'
18
18
 
19
- /** A package someone has vouched for: signed, vouched for by the host, or built here. */
19
+ /**
20
+ * A package someone has vouched for: signed by a signer this site trusts (story
21
+ * 335), vouched for by the host, or built here.
22
+ */
20
23
  export const vouchedFor = (provenance: ProvenanceResult | undefined): boolean =>
21
- provenance?.state === 'signed' || provenance?.state === 'vouched' || provenance?.state === 'local'
24
+ (provenance?.state === 'signed' && provenance.trusted === true) ||
25
+ provenance?.state === 'vouched' ||
26
+ provenance?.state === 'local'
27
+
28
+ /** Who signed it, in words: a key by its name and fingerprint, or the repository that built it. */
29
+ export function signerWords(provenance: ProvenanceResult): string | undefined {
30
+ if (provenance.key)
31
+ return `the key ${provenance.key.comment ? `${provenance.key.comment} ` : ''}(${provenance.key.fingerprint})`
32
+ if (provenance.source) return `a build of github.com/${provenance.source.repository}`
33
+ return undefined
34
+ }
35
+
36
+ /** Why a signature that checks out still does not vouch: its signer is not one this site trusts. */
37
+ export const untrustedSigner = (provenance: ProvenanceResult): string =>
38
+ `It is signed by ${signerWords(provenance) ?? 'someone'}, which this site doesn't trust, so it can't be turned on here. An administrator can add the signer in Settings → Trusted signers.`
22
39
 
23
40
  export const ADMINISTRATOR_GRANTS = 'An administrator can turn this on.'
24
41
  export const NOBODY_VOUCHED =
@@ -52,6 +69,9 @@ export function grantRefusal(options: {
52
69
  if (!options.grants) return undefined
53
70
  if (options.level === 'unrestricted' && options.from === 'config') return CONFIG_GRANTS
54
71
  if (!options.isAdmin) return ADMINISTRATOR_GRANTS
55
- if (isUpperLevel(options.level) && !vouchedFor(options.provenance)) return NOBODY_VOUCHED
72
+ if (isUpperLevel(options.level) && !vouchedFor(options.provenance))
73
+ return options.provenance?.state === 'signed'
74
+ ? untrustedSigner(options.provenance)
75
+ : NOBODY_VOUCHED
56
76
  return undefined
57
77
  }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Story 335: an extension granted Acts as you or Unrestricted keeps that only
3
+ * while someone this site trusts vouches for it. Checked at every start, before
4
+ * extensions run, so an upgrade, or a signer taken off Trusted signers, switches
5
+ * off what no longer qualifies.
6
+ */
7
+ import { type ExtensionRegistry, isUpperLevel, levelOf } from '@crombolo/backoffice-host/registry'
8
+ import type { Db } from '@crombolo/data'
9
+ import { recordAudit } from './adapters/audit.ts'
10
+ import { APPROVED_BY_CODE, type BundleGrants } from './bundle-grants.ts'
11
+ import type { CromboloConfig } from './config.ts'
12
+ import { signerWords, vouchedFor } from './grant-policy.ts'
13
+ import { logger } from './logging.ts'
14
+ import { createMarketplace } from './marketplace.ts'
15
+ import { signerTrusted } from './site-trust.ts'
16
+
17
+ /** Who switches them off, as the audit log records it. */
18
+ export const SWITCHED_OFF_BY = 'crombolo'
19
+
20
+ /**
21
+ * Withdraws each upper-level grant recorded here that nobody this site trusts
22
+ * vouches for, so it is granted again only by the rule; the ids withdrawn. A
23
+ * grant the site's code makes is the developer's, and kept.
24
+ */
25
+ export async function switchOffUntrusted(
26
+ db: Db,
27
+ config: CromboloConfig,
28
+ extensions: ExtensionRegistry,
29
+ grants: Pick<BundleGrants, 'granted' | 'isOn' | 'state' | 'forget'>,
30
+ ): Promise<string[]> {
31
+ const marketplace = createMarketplace({
32
+ registry: config.npmRegistry,
33
+ keyword: config.packageKeyword,
34
+ marketplaceUrl: config.marketplaceUrl,
35
+ componentsDir: config.componentsDir,
36
+ extensions,
37
+ siteDir: config.siteDir,
38
+ trustSigner: (provenance) => signerTrusted(db, config, provenance),
39
+ })
40
+ const packages = new Map(extensions.bundles().bundles.map((pkg) => [pkg.id, pkg]))
41
+ const switched: string[] = []
42
+ for (const item of await marketplace.installed()) {
43
+ const pkg = packages.get(item.id)
44
+ if (!pkg || !grants.isOn(item.id)) continue
45
+ if (grants.state(pkg).grant?.grantedBy === APPROVED_BY_CODE) continue
46
+ if (!isUpperLevel(levelOf(grants.granted(item.id)))) continue
47
+ // A signature that can't be checked right now is left alone, not judged.
48
+ if (item.provenance.state === 'unchecked' || vouchedFor(item.provenance)) continue
49
+ await grants.forget(pkg.id)
50
+ const signer = signerWords(item.provenance)
51
+ const why = signer
52
+ ? `signed by ${signer}, which this site doesn't trust`
53
+ : 'nobody has vouched for who built it'
54
+ await recordAudit(db, {
55
+ category: 'system',
56
+ action: 'Disable',
57
+ entityType: 'Bundle',
58
+ entityName: `${pkg.packageName}@${pkg.version}`,
59
+ detail: `switched off at start: it acts as you or runs unrestricted, and is ${why}; it needs granting again`,
60
+ source: 'boot',
61
+ userKey: null,
62
+ userName: SWITCHED_OFF_BY,
63
+ ipAddress: null,
64
+ forwardedFor: null,
65
+ })
66
+ logger('server').warn(
67
+ '{extension} is switched off: it acts as you or runs unrestricted, and is {why}. Trust its signer in Settings → Trusted signers, then grant it again.',
68
+ { extension: pkg.packageName, why },
69
+ )
70
+ switched.push(item.id)
71
+ }
72
+ return switched
73
+ }