@crombolo/server 0.55.0 → 0.57.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.
Files changed (48) hide show
  1. package/package.json +16 -13
  2. package/src/actions.ts +6 -1
  3. package/src/adapters/bundles.ts +72 -6
  4. package/src/adapters/health.ts +30 -1
  5. package/src/bundle-admin.ts +246 -23
  6. package/src/bundle-api.ts +299 -0
  7. package/src/bundle-build.ts +4 -3
  8. package/src/bundle-grants.ts +133 -18
  9. package/src/bundle-install.ts +140 -11
  10. package/src/bundle-sections.ts +49 -4
  11. package/src/bundles.ts +87 -7
  12. package/src/component-templates-api.ts +27 -6
  13. package/src/components.ts +7 -0
  14. package/src/config.ts +56 -3
  15. package/src/content-events.ts +17 -1
  16. package/src/core.ts +219 -15
  17. package/src/created-extension.ts +101 -0
  18. package/src/extension-components.ts +157 -0
  19. package/src/extension-discovery.ts +180 -0
  20. package/src/extension-process.ts +854 -0
  21. package/src/extension-sql.ts +85 -0
  22. package/src/index.ts +21 -0
  23. package/src/marketplace.ts +182 -54
  24. package/src/outbound-address.ts +182 -0
  25. package/src/owner-jobs.ts +7 -1
  26. package/src/ports.ts +8 -0
  27. package/src/provenance.ts +181 -15
  28. package/src/remote.ts +62 -10
  29. package/src/routes.ts +13 -1
  30. package/src/schema.ts +37 -6
  31. package/src/seed/compile.ts +4 -2
  32. package/src/seed/export.ts +1 -1
  33. package/src/seed/values.ts +3 -3
  34. package/src/seo.ts +13 -5
  35. package/src/server.ts +192 -45
  36. package/src/settings.ts +12 -4
  37. package/src/signing-keys.ts +155 -0
  38. package/src/site-content-values.ts +97 -0
  39. package/src/site-content.ts +292 -0
  40. package/src/site-events.ts +65 -0
  41. package/src/site-file.ts +20 -6
  42. package/src/site-public.ts +1 -1
  43. package/src/site-sections.ts +1 -1
  44. package/src/site-services.ts +4 -0
  45. package/src/site-trust.ts +238 -0
  46. package/src/transfer-dashboard.ts +6 -0
  47. package/src/trusted-signers-admin.ts +132 -0
  48. package/src/webhooks.ts +182 -17
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,55 @@ 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
216
+ /**
217
+ * The origins a bundle's event `fetch` may reach (story 308); undefined for a
218
+ * bundle written before schema 4, which the address rule alone holds.
219
+ */
220
+ bundleOrigins?(bundleId: string): readonly string[] | undefined
146
221
  /** Whether a bundle is turned on (story 222); its events are not delivered while it is off. */
147
222
  isBundleOn?(bundleId: string): boolean
223
+ /** The site's own handlers (story 298): which events it handles, and how one is handed over. */
224
+ siteEvents?: {
225
+ handles(alias: string): boolean
226
+ /** Queues the job that runs the handler; the delivery is done once it is queued. */
227
+ deliver(event: SiteContentEvent): Promise<void>
228
+ }
148
229
  }
149
230
 
150
231
  /** An event as a webhook delivers it, with the item's type and place as they were when it happened. */
151
232
  export interface WebhookFacts extends RaisedWebhookEvent {
152
233
  contentTypeKey?: string
153
234
  contentTypeAlias?: string
235
+ /** The cultures the change was about, when it was about some (story 298). */
236
+ cultures?: string[] | null
237
+ /** Who made the change, and the site code it came through. */
238
+ actor?: { kind: string; name: string; via?: string }
239
+ /** The site code a change came through, so a site handler is not called for its own. */
240
+ via?: string
154
241
  /** Its ancestors' keys, nearest first, for Crombolo's payload (story 208). */
155
242
  ancestors?: string[]
156
243
  }
157
244
 
245
+ /** An event as the site's own handler receives it (story 298). Pure. */
246
+ export function siteEventOf(facts: WebhookFacts): SiteContentEvent {
247
+ return {
248
+ alias: facts.alias,
249
+ key: facts.key,
250
+ contentType: facts.contentTypeAlias ?? null,
251
+ cultures: facts.cultures ?? null,
252
+ actor: { kind: facts.actor?.kind ?? 'unknown', name: facts.actor?.name ?? 'Unknown' },
253
+ }
254
+ }
255
+
158
256
  /** What a webhook is posted. Pure. */
159
257
  export function webhookPayload(
160
258
  facts: WebhookFacts,
@@ -325,7 +423,7 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
325
423
  where: WebhookStore,
326
424
  ): Promise<WebhookWriteResult> => {
327
425
  if (!stores()[where]) return unavailable(where)
328
- const problems = webhookProblems(webhook, where)
426
+ const problems = [...webhookProblems(webhook, where), ...(await reachProblems(webhook))]
329
427
  if (problems.length > 0)
330
428
  return { ok: false, status: 400, reason: 'The webhook is not valid.', problems }
331
429
  if (where === 'files') await writeFile(webhook)
@@ -333,6 +431,34 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
333
431
  return { ok: true, key: webhook.key }
334
432
  }
335
433
 
434
+ const outbound: OutboundOptions = {
435
+ allowPrivateAddresses: options.outbound?.allowPrivateAddresses,
436
+ lookup: options.outbound?.lookup,
437
+ fetch: options.fetch,
438
+ }
439
+
440
+ /**
441
+ * What saving a webhook refuses beyond its shape (story 301): a header naming a
442
+ * variable it may not send, and an address this site does not send to, where
443
+ * the host resolves already; one that does not yet is checked at each delivery.
444
+ */
445
+ const reachProblems = async (webhook: WebhookDefinition): Promise<string[]> => {
446
+ const problems: string[] = []
447
+ for (const [name, value] of Object.entries(webhook.headers)) {
448
+ const variable = envReference(value)
449
+ const problem =
450
+ variable && headerVariableProblem(name, variable, options.outbound?.headerVariables)
451
+ if (problem) problems.push(problem)
452
+ }
453
+ try {
454
+ await checkedAddress(new URL(webhook.url), outbound)
455
+ } catch (error) {
456
+ if (error instanceof OutboundRefused && !/has no address/.test(error.message))
457
+ problems.push(error.message)
458
+ }
459
+ return problems
460
+ }
461
+
336
462
  /** A masked value sent back means "keep what is stored". */
337
463
  const unmask = (incoming: Record<string, string>, stored: Record<string, string>) => {
338
464
  const out: Record<string, string> = {}
@@ -349,6 +475,8 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
349
475
  out[name] = value
350
476
  continue
351
477
  }
478
+ const refused = headerVariableProblem(name, variable, options.outbound?.headerVariables)
479
+ if (refused) throw new Error(refused)
352
480
  const found = Bun.env[variable]
353
481
  if (found === undefined)
354
482
  throw new Error(`The header "${name}" names ${variable}, which is not set on the server.`)
@@ -422,21 +550,17 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
422
550
  return { ok: false, error: message, retry: false }
423
551
  }
424
552
  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(() => '')
553
+ const response = await pinnedFetch(
554
+ webhook.url,
555
+ { method: 'POST', headers, body, signal: AbortSignal.timeout(DELIVERY_TIMEOUT_MS) },
556
+ outbound,
557
+ )
433
558
  await deliveries.log({
434
559
  ...entry,
435
560
  statusCode: response.status,
436
561
  success: response.ok,
437
562
  exception: false,
438
- responseHeaders: JSON.stringify(Object.fromEntries(response.headers)),
439
- responseBody,
563
+ ...(await keptAnswer(response)),
440
564
  })
441
565
  if (response.ok) return { ok: true }
442
566
  // A refusal will refuse again; a fault or a busy receiver may not last.
@@ -452,7 +576,29 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
452
576
  responseHeaders: '{}',
453
577
  responseBody: message,
454
578
  })
455
- return { ok: false, error: message, retry: true }
579
+ return { ok: false, error: message, retry: !(error instanceof OutboundRefused) }
580
+ }
581
+ }
582
+
583
+ /** To the site's own handler: a job of its own, queued; the job runs it and retries it. */
584
+ const deliverToSite = async (
585
+ delivery: WebhookDelivery,
586
+ ): Promise<{ ok: true } | { ok: false; error: string; retry: boolean }> => {
587
+ if (!options.siteEvents?.handles(delivery.eventAlias))
588
+ return {
589
+ ok: false,
590
+ error: `The site no longer handles ${delivery.eventAlias}.`,
591
+ retry: false,
592
+ }
593
+ try {
594
+ await options.siteEvents.deliver(delivery.payload as SiteContentEvent)
595
+ return { ok: true }
596
+ } catch (error) {
597
+ return {
598
+ ok: false,
599
+ error: error instanceof Error ? error.message : String(error),
600
+ retry: true,
601
+ }
456
602
  }
457
603
  }
458
604
 
@@ -493,7 +639,17 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
493
639
  payload: delivery.payload as { Id: string },
494
640
  deliveryId: delivery.id,
495
641
  attempt: delivery.attempts,
496
- fetch: (input, init) => (options.fetch ?? fetch)(input, { signal, ...init }),
642
+ fetch: (input, init) => {
643
+ const origins = options.bundleOrigins?.(bundleId)
644
+ const url = new URL(input instanceof Request ? input.url : String(input))
645
+ if (origins && !origins.includes(url.origin))
646
+ return Promise.reject(
647
+ new OutboundRefused(
648
+ `${bundleId} may not reach ${url.origin}: its http.outbound names ${origins.join(', ') || 'nothing'}.`,
649
+ ),
650
+ )
651
+ return pinnedFetch(input, { signal, ...init }, outbound)
652
+ },
497
653
  log: {
498
654
  info: (message, properties) => named.info(message, properties),
499
655
  warn: (message, properties) => named.warn(message, properties),
@@ -578,10 +734,18 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
578
734
  },
579
735
  async enqueueFor(db, eventId, facts) {
580
736
  const webhooks = await all()
581
- const subscribers = subscribersFor(facts, facts.contentTypeKey, webhooks, bundles)
737
+ const subscribers = subscribersFor(
738
+ facts,
739
+ facts.contentTypeKey,
740
+ webhooks,
741
+ bundles,
742
+ (alias) => options.siteEvents?.handles(alias) ?? false,
743
+ )
582
744
  if (subscribers.length === 0) return 0
583
745
  const payloadOf = (subscriber: string) =>
584
- webhookPayload(facts, webhooks.find((webhook) => webhook.key === subscriber)?.payload)
746
+ subscriber === SITE
747
+ ? siteEventOf(facts)
748
+ : webhookPayload(facts, webhooks.find((webhook) => webhook.key === subscriber)?.payload)
585
749
  const queued = await new WebhookDeliveryRepository(db).enqueue(
586
750
  subscribers.map((subscriber) => ({
587
751
  subscriber,
@@ -610,6 +774,7 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
610
774
  let result: { ok: true } | { ok: false; error: string; retry: boolean }
611
775
  if (delivery.subscriber.startsWith(BUNDLE))
612
776
  result = await deliverToBundle(delivery, delivery.subscriber.slice(BUNDLE.length))
777
+ else if (delivery.subscriber === SITE) result = await deliverToSite(delivery)
613
778
  else {
614
779
  const webhook = await this.get(delivery.subscriber)
615
780
  result = webhook