@crombolo/server 0.55.0 → 0.56.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/webhooks.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  * changes, delivered by a background job with retries, and every attempt
4
4
  * logged. A server bundle's event handlers ride the same queue. docs/webhooks.md.
5
5
  */
6
+
6
7
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
7
8
  import { join } from 'node:path'
8
9
  import { type RaisedWebhookEvent, WEBHOOK_EVENT_ALIASES } from '@crombolo/api-management/domain'
@@ -15,9 +16,18 @@ import {
15
16
  WebhookRepository,
16
17
  type WebhookRow,
17
18
  } from '@crombolo/data'
19
+ import type { SiteContentEvent } from '@crombolo/render'
18
20
  import { retryAfter, type WorkflowRunReport } from './form-workflows.ts'
19
21
  import { logger } from './logging.ts'
22
+ import {
23
+ checkedAddress,
24
+ headerVariableProblem,
25
+ type OutboundOptions,
26
+ OutboundRefused,
27
+ pinnedFetch,
28
+ } from './outbound-address.ts'
20
29
  import { openSecret, SECRET_KEY_VARIABLE, sealSecret, usableSecretKey } from './secrets.ts'
30
+ import { isOwnChange } from './site-events.ts'
21
31
  import { inSpan, recordWebhook, SpanKind, withTraceHeaders } from './telemetry.ts'
22
32
  import {
23
33
  envReference,
@@ -34,6 +44,52 @@ const log = logger('webhooks')
34
44
  /** What the backoffice shows instead of a typed-in secret, and sends back to keep it. */
35
45
  export const MASKED = '********'
36
46
 
47
+ /** The most of a receiver's text answer the delivery log keeps (story 301). */
48
+ const KEPT_ANSWER_BYTES = 1024
49
+
50
+ const TEXTUAL = /^text\/|json|xml|x-www-form-urlencoded/i
51
+
52
+ /**
53
+ * What the log keeps of an answer: its `Content-Type`, and the first 1 KB of a
54
+ * text body, read no further. Enough to see a refusal, not to read back a page.
55
+ */
56
+ async function keptAnswer(
57
+ response: Response,
58
+ ): Promise<{ responseHeaders: string; responseBody: string }> {
59
+ const type = response.headers.get('content-type')
60
+ const responseHeaders = JSON.stringify(type ? { 'content-type': type } : {})
61
+ if (!response.body) return { responseHeaders, responseBody: '' }
62
+ if (type && !TEXTUAL.test(type)) {
63
+ await response.body.cancel().catch(() => {})
64
+ return { responseHeaders, responseBody: '(a binary answer, not kept)' }
65
+ }
66
+ const reader = response.body.getReader()
67
+ const chunks: Uint8Array[] = []
68
+ let size = 0
69
+ try {
70
+ while (size < KEPT_ANSWER_BYTES) {
71
+ const { done, value } = await reader.read()
72
+ if (done) break
73
+ chunks.push(value)
74
+ size += value.length
75
+ }
76
+ } catch {
77
+ // What arrived before the answer broke off is kept.
78
+ } finally {
79
+ await reader.cancel().catch(() => {})
80
+ }
81
+ const bytes = new Uint8Array(size)
82
+ let at = 0
83
+ for (const chunk of chunks) {
84
+ bytes.set(chunk, at)
85
+ at += chunk.length
86
+ }
87
+ return {
88
+ responseHeaders,
89
+ responseBody: new TextDecoder().decode(bytes.subarray(0, KEPT_ANSWER_BYTES)),
90
+ }
91
+ }
92
+
37
93
  /** How long a delivery may take before it counts as failed and is retried. */
38
94
  const DELIVERY_TIMEOUT_MS = 30_000
39
95
 
@@ -69,6 +125,8 @@ export type BundleEventHandler = (
69
125
  export type BundleEvents = Readonly<Record<string, BundleEventHandler>>
70
126
 
71
127
  const BUNDLE = 'bundle:'
128
+ /** The site's own `events` handlers (story 298), as a subscriber. */
129
+ const SITE = 'site'
72
130
 
73
131
  /** Why these bundles' event declarations cannot be accepted. Pure. */
74
132
  export function bundleEventProblems(
@@ -87,12 +145,17 @@ export function bundleEventProblems(
87
145
  return problems
88
146
  }
89
147
 
90
- /** Who should hear about an event: the matching webhooks, then the bundles. Pure. */
148
+ /**
149
+ * Who should hear about an event: the matching webhooks, the bundles, then the
150
+ * site's own handlers, unless the event is a site handler's own change to the
151
+ * page it was called for. Pure.
152
+ */
91
153
  export function subscribersFor(
92
- event: RaisedWebhookEvent,
154
+ event: RaisedWebhookEvent & { via?: string },
93
155
  contentTypeKey: string | undefined,
94
156
  webhooks: readonly WebhookDefinition[],
95
157
  bundles: readonly { id: string; events?: BundleEvents }[],
158
+ siteHandles: (alias: string) => boolean = () => false,
96
159
  ): string[] {
97
160
  const out: string[] = []
98
161
  for (const webhook of webhooks) {
@@ -108,6 +171,7 @@ export function subscribersFor(
108
171
  out.push(webhook.key)
109
172
  }
110
173
  for (const bundle of bundles) if (bundle.events?.[event.alias]) out.push(`${BUNDLE}${bundle.id}`)
174
+ if (siteHandles(event.alias) && !isOwnChange(event)) out.push(SITE)
111
175
  return out
112
176
  }
113
177
 
@@ -140,21 +204,50 @@ export interface WebhookServiceOptions {
140
204
  secretKey?: string
141
205
  bundles?: readonly { id: string; events?: BundleEvents }[]
142
206
  fetch?: typeof fetch
207
+ /** What a delivery may reach and send (story 301): the config's `webhooks`. */
208
+ outbound?: {
209
+ headerVariables?: readonly string[]
210
+ allowPrivateAddresses?: boolean
211
+ lookup?: OutboundOptions['lookup']
212
+ }
143
213
  /** Publishes the schema directory to a shared store, when there is one. */
144
214
  onFilesChanged?: () => Promise<void>
145
215
  now?: () => Date
146
216
  /** Whether a bundle is turned on (story 222); its events are not delivered while it is off. */
147
217
  isBundleOn?(bundleId: string): boolean
218
+ /** The site's own handlers (story 298): which events it handles, and how one is handed over. */
219
+ siteEvents?: {
220
+ handles(alias: string): boolean
221
+ /** Queues the job that runs the handler; the delivery is done once it is queued. */
222
+ deliver(event: SiteContentEvent): Promise<void>
223
+ }
148
224
  }
149
225
 
150
226
  /** An event as a webhook delivers it, with the item's type and place as they were when it happened. */
151
227
  export interface WebhookFacts extends RaisedWebhookEvent {
152
228
  contentTypeKey?: string
153
229
  contentTypeAlias?: string
230
+ /** The cultures the change was about, when it was about some (story 298). */
231
+ cultures?: string[] | null
232
+ /** Who made the change, and the site code it came through. */
233
+ actor?: { kind: string; name: string; via?: string }
234
+ /** The site code a change came through, so a site handler is not called for its own. */
235
+ via?: string
154
236
  /** Its ancestors' keys, nearest first, for Crombolo's payload (story 208). */
155
237
  ancestors?: string[]
156
238
  }
157
239
 
240
+ /** An event as the site's own handler receives it (story 298). Pure. */
241
+ export function siteEventOf(facts: WebhookFacts): SiteContentEvent {
242
+ return {
243
+ alias: facts.alias,
244
+ key: facts.key,
245
+ contentType: facts.contentTypeAlias ?? null,
246
+ cultures: facts.cultures ?? null,
247
+ actor: { kind: facts.actor?.kind ?? 'unknown', name: facts.actor?.name ?? 'Unknown' },
248
+ }
249
+ }
250
+
158
251
  /** What a webhook is posted. Pure. */
159
252
  export function webhookPayload(
160
253
  facts: WebhookFacts,
@@ -325,7 +418,7 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
325
418
  where: WebhookStore,
326
419
  ): Promise<WebhookWriteResult> => {
327
420
  if (!stores()[where]) return unavailable(where)
328
- const problems = webhookProblems(webhook, where)
421
+ const problems = [...webhookProblems(webhook, where), ...(await reachProblems(webhook))]
329
422
  if (problems.length > 0)
330
423
  return { ok: false, status: 400, reason: 'The webhook is not valid.', problems }
331
424
  if (where === 'files') await writeFile(webhook)
@@ -333,6 +426,34 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
333
426
  return { ok: true, key: webhook.key }
334
427
  }
335
428
 
429
+ const outbound: OutboundOptions = {
430
+ allowPrivateAddresses: options.outbound?.allowPrivateAddresses,
431
+ lookup: options.outbound?.lookup,
432
+ fetch: options.fetch,
433
+ }
434
+
435
+ /**
436
+ * What saving a webhook refuses beyond its shape (story 301): a header naming a
437
+ * variable it may not send, and an address this site does not send to, where
438
+ * the host resolves already; one that does not yet is checked at each delivery.
439
+ */
440
+ const reachProblems = async (webhook: WebhookDefinition): Promise<string[]> => {
441
+ const problems: string[] = []
442
+ for (const [name, value] of Object.entries(webhook.headers)) {
443
+ const variable = envReference(value)
444
+ const problem =
445
+ variable && headerVariableProblem(name, variable, options.outbound?.headerVariables)
446
+ if (problem) problems.push(problem)
447
+ }
448
+ try {
449
+ await checkedAddress(new URL(webhook.url), outbound)
450
+ } catch (error) {
451
+ if (error instanceof OutboundRefused && !/has no address/.test(error.message))
452
+ problems.push(error.message)
453
+ }
454
+ return problems
455
+ }
456
+
336
457
  /** A masked value sent back means "keep what is stored". */
337
458
  const unmask = (incoming: Record<string, string>, stored: Record<string, string>) => {
338
459
  const out: Record<string, string> = {}
@@ -349,6 +470,8 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
349
470
  out[name] = value
350
471
  continue
351
472
  }
473
+ const refused = headerVariableProblem(name, variable, options.outbound?.headerVariables)
474
+ if (refused) throw new Error(refused)
352
475
  const found = Bun.env[variable]
353
476
  if (found === undefined)
354
477
  throw new Error(`The header "${name}" names ${variable}, which is not set on the server.`)
@@ -422,21 +545,17 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
422
545
  return { ok: false, error: message, retry: false }
423
546
  }
424
547
  try {
425
- const response = await (options.fetch ?? fetch)(webhook.url, {
426
- method: 'POST',
427
- headers,
428
- body,
429
- signal: AbortSignal.timeout(DELIVERY_TIMEOUT_MS),
430
- redirect: 'manual',
431
- })
432
- const responseBody = await response.text().catch(() => '')
548
+ const response = await pinnedFetch(
549
+ webhook.url,
550
+ { method: 'POST', headers, body, signal: AbortSignal.timeout(DELIVERY_TIMEOUT_MS) },
551
+ outbound,
552
+ )
433
553
  await deliveries.log({
434
554
  ...entry,
435
555
  statusCode: response.status,
436
556
  success: response.ok,
437
557
  exception: false,
438
- responseHeaders: JSON.stringify(Object.fromEntries(response.headers)),
439
- responseBody,
558
+ ...(await keptAnswer(response)),
440
559
  })
441
560
  if (response.ok) return { ok: true }
442
561
  // A refusal will refuse again; a fault or a busy receiver may not last.
@@ -452,7 +571,29 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
452
571
  responseHeaders: '{}',
453
572
  responseBody: message,
454
573
  })
455
- return { ok: false, error: message, retry: true }
574
+ return { ok: false, error: message, retry: !(error instanceof OutboundRefused) }
575
+ }
576
+ }
577
+
578
+ /** To the site's own handler: a job of its own, queued; the job runs it and retries it. */
579
+ const deliverToSite = async (
580
+ delivery: WebhookDelivery,
581
+ ): Promise<{ ok: true } | { ok: false; error: string; retry: boolean }> => {
582
+ if (!options.siteEvents?.handles(delivery.eventAlias))
583
+ return {
584
+ ok: false,
585
+ error: `The site no longer handles ${delivery.eventAlias}.`,
586
+ retry: false,
587
+ }
588
+ try {
589
+ await options.siteEvents.deliver(delivery.payload as SiteContentEvent)
590
+ return { ok: true }
591
+ } catch (error) {
592
+ return {
593
+ ok: false,
594
+ error: error instanceof Error ? error.message : String(error),
595
+ retry: true,
596
+ }
456
597
  }
457
598
  }
458
599
 
@@ -493,7 +634,7 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
493
634
  payload: delivery.payload as { Id: string },
494
635
  deliveryId: delivery.id,
495
636
  attempt: delivery.attempts,
496
- fetch: (input, init) => (options.fetch ?? fetch)(input, { signal, ...init }),
637
+ fetch: (input, init) => pinnedFetch(input, { signal, ...init }, outbound),
497
638
  log: {
498
639
  info: (message, properties) => named.info(message, properties),
499
640
  warn: (message, properties) => named.warn(message, properties),
@@ -578,10 +719,18 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
578
719
  },
579
720
  async enqueueFor(db, eventId, facts) {
580
721
  const webhooks = await all()
581
- const subscribers = subscribersFor(facts, facts.contentTypeKey, webhooks, bundles)
722
+ const subscribers = subscribersFor(
723
+ facts,
724
+ facts.contentTypeKey,
725
+ webhooks,
726
+ bundles,
727
+ (alias) => options.siteEvents?.handles(alias) ?? false,
728
+ )
582
729
  if (subscribers.length === 0) return 0
583
730
  const payloadOf = (subscriber: string) =>
584
- webhookPayload(facts, webhooks.find((webhook) => webhook.key === subscriber)?.payload)
731
+ subscriber === SITE
732
+ ? siteEventOf(facts)
733
+ : webhookPayload(facts, webhooks.find((webhook) => webhook.key === subscriber)?.payload)
585
734
  const queued = await new WebhookDeliveryRepository(db).enqueue(
586
735
  subscribers.map((subscriber) => ({
587
736
  subscriber,
@@ -610,6 +759,7 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
610
759
  let result: { ok: true } | { ok: false; error: string; retry: boolean }
611
760
  if (delivery.subscriber.startsWith(BUNDLE))
612
761
  result = await deliverToBundle(delivery, delivery.subscriber.slice(BUNDLE.length))
762
+ else if (delivery.subscriber === SITE) result = await deliverToSite(delivery)
613
763
  else {
614
764
  const webhook = await this.get(delivery.subscriber)
615
765
  result = webhook