@fabrika/app 0.9.0-dev.13 → 0.9.0-dev.14

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 (42) hide show
  1. package/package.json +9 -9
  2. package/skill/SKILL.md +2 -1
  3. package/skill/references/app-setup.md +15 -8
  4. package/skill/references/endpoint.md +7 -1
  5. package/skill/references/errors.md +7 -6
  6. package/skill/references/jobs.md +10 -0
  7. package/skill/references/relations.md +145 -21
  8. package/skill/references/table-and-migration.md +4 -1
  9. package/skill/references/webhooks-links-connectors.md +2 -1
  10. package/src/bun.ts +10 -0
  11. package/src/contract/artifact-schema.ts +17 -3
  12. package/src/contract/build.ts +76 -18
  13. package/src/contract/define.ts +2 -1
  14. package/src/contract/group.ts +10 -1
  15. package/src/contract/kit.ts +2 -1
  16. package/src/disk-assets.ts +15 -3
  17. package/src/implement/boot.ts +28 -5
  18. package/src/implement/capability.ts +82 -12
  19. package/src/implement/dispatch.ts +251 -35
  20. package/src/implement/egress.ts +409 -9
  21. package/src/implement/implement.ts +23 -3
  22. package/src/implement/invocation.ts +10 -9
  23. package/src/implement/types.ts +15 -4
  24. package/src/implement/webhook.ts +8 -0
  25. package/src/jobs/runner.ts +7 -2
  26. package/src/source-map-path.ts +21 -0
  27. package/src/testing/caller.ts +20 -9
  28. package/src/testing/membership.ts +9 -5
  29. package/types/src/contract/define.d.ts +2 -1
  30. package/types/src/contract/group.d.ts +9 -1
  31. package/types/src/contract/kit.d.ts +2 -2
  32. package/types/src/implement/boot.d.ts +6 -0
  33. package/types/src/implement/capability.d.ts +14 -5
  34. package/types/src/implement/dispatch.d.ts +9 -1
  35. package/types/src/implement/egress.d.ts +36 -1
  36. package/types/src/implement/implement.d.ts +19 -3
  37. package/types/src/implement/invocation.d.ts +3 -3
  38. package/types/src/implement/types.d.ts +13 -3
  39. package/types/src/jobs/runner.d.ts +3 -0
  40. package/types/src/source-map-path.d.ts +4 -0
  41. package/types/src/testing/caller.d.ts +6 -1
  42. package/types/src/testing/membership.d.ts +1 -1
@@ -1,17 +1,56 @@
1
1
  // `egress`: while a site's handler runs, the global `fetch` reaches only the HTTPS origins the site declares, exactly or
2
- // by a one-label pattern (`egressAdmits` of `@fabrika/auth-core`). It stops a mistake and makes a bypass conspicuous; it
3
- // is not a sandbox (ADR-0012 §8): code that kept the `fetch` it found before boot, or opens its own sockets, escapes it.
4
- // The framework's own facilities (mail, connectors, IAM, the object store) run outside the site's scope, under their own
5
- // declarations.
2
+ // by a one-label pattern (`egressAdmits` of `@fabrika/auth-core`), or, for a cron job that declares `egress: 'public'`,
3
+ // only public hosts (ADR-0075). It stops a mistake and makes a bypass conspicuous; it is not a sandbox (ADR-0012 §8):
4
+ // code that kept the `fetch` it found before boot, or opens its own sockets, escapes it. The framework's own facilities
5
+ // (mail, connectors, IAM, the object store) run outside the site's scope, under their own declarations.
6
6
 
7
- import { egressAdmits, type EgressEntry, parseEgressEntry } from '@fabrika/auth-core'
7
+ import {
8
+ type DeclaredEgress,
9
+ egressAdmits,
10
+ type EgressEntry,
11
+ FABRIKA_EGRESS_REFUSED_HOSTS,
12
+ isPublicAddress,
13
+ normalizedHost,
14
+ parseEgressEntry,
15
+ PUBLIC_EGRESS,
16
+ publicEgressRefusal,
17
+ } from '@fabrika/auth-core'
8
18
  import { AsyncLocalStorage } from 'node:async_hooks'
9
19
  import { CapabilityRefusedError } from './capability'
10
20
 
21
+ /** The addresses a host name resolves to, where the runtime exposes resolution: Bun's `node:dns`, never a Worker. */
22
+ export type HostResolver = (hostname: string) => Promise<readonly string[]>
23
+
24
+ /** What public egress refuses beyond what a URL alone shows (`publicEgressRefusal`). */
25
+ export interface PublicEgressRules {
26
+ /** The installation's own hosts, normalized: every host a framework variable names, and `FABRIKA_EGRESS_REFUSED_HOSTS`. */
27
+ readonly refusedHosts: ReadonlySet<string>
28
+ /** Resolves each hop's host once, before it is sent to an address checked here; `null` on Cloudflare. */
29
+ readonly resolve: HostResolver | null
30
+ }
31
+
32
+ /** What one site's `fetch` reaches: its declared origins, or the rules of public egress. */
33
+ export type SiteEgress = readonly string[] | PublicEgressRules
34
+
35
+ /**
36
+ * The bounds of one request under public egress, the redirects it follows included. The handler's own signal still
37
+ * aborts it sooner (`ctx.signal`, an `AbortSignal.timeout` of its own).
38
+ */
39
+ export const PUBLIC_EGRESS_LIMITS = {
40
+ /** One request, its redirects and the reading of its body included: the abort also stops a body still streaming. */
41
+ timeoutMs: 60_000,
42
+ /** One response's body as the handler reads it; a larger one is refused, by its `Content-Length` or while it streams. */
43
+ maxResponseBytes: 16 * 1024 * 1024,
44
+ /** The redirects one request follows when its `redirect` mode is `follow`, each hop checked again. */
45
+ maxRedirects: 10,
46
+ } as const
47
+
11
48
  interface EgressScope {
12
49
  /** The site, as a refusal names it. */
13
50
  readonly site: string
14
51
  readonly entries: readonly EgressEntry[]
52
+ /** Public egress: `null` for a site that declares origins, or none. */
53
+ readonly open: PublicEgressRules | null
15
54
  }
16
55
 
17
56
  const scope = new AsyncLocalStorage<EgressScope>()
@@ -19,8 +58,10 @@ const guards = new WeakSet<object>()
19
58
  const parsed = new WeakMap<readonly string[], readonly EgressEntry[]>()
20
59
 
21
60
  /** Runs a site's handler: every `fetch` it starts reaches only `egress`. */
22
- export function runAsSite<T>(site: string, egress: readonly string[], work: () => Promise<T>): Promise<T> {
23
- return scope.run({ site, entries: entriesOf(egress) }, work)
61
+ export function runAsSite<T>(site: string, egress: SiteEgress, work: () => Promise<T>): Promise<T> {
62
+ return isOrigins(egress)
63
+ ? scope.run({ site, entries: entriesOf(egress), open: null }, work)
64
+ : scope.run({ site, entries: [], open: egress }, work)
24
65
  }
25
66
 
26
67
  /**
@@ -38,6 +79,50 @@ function entriesOf(egress: readonly string[]): readonly EgressEntry[] {
38
79
  return entries
39
80
  }
40
81
 
82
+ /**
83
+ * The egress a site runs with: its declared origins, or `rules` for `'public'`. Only a cron job's runner holds rules; a
84
+ * site run without them reaches nothing, though the build lets no other site declare `'public'`.
85
+ */
86
+ export function siteEgress(declared: DeclaredEgress, rules: PublicEgressRules | null): SiteEgress {
87
+ return declared === PUBLIC_EGRESS ? (rules ?? []) : declared
88
+ }
89
+
90
+ function isOrigins(egress: SiteEgress): egress is readonly string[] {
91
+ return Array.isArray(egress)
92
+ }
93
+
94
+ /**
95
+ * The rules of public egress in one environment: the hosts its framework variables name (IAM, Operations, its own
96
+ * origin, the platform's receivers, the object store), the installation hosts Control hands it, and the resolver the
97
+ * runtime adapter supplies.
98
+ */
99
+ export function publicEgressRules(framework: Readonly<Record<string, string>>, resolve: HostResolver | null): PublicEgressRules {
100
+ const hosts = new Set<string>()
101
+ for (const [name, value] of Object.entries(framework)) {
102
+ if (name === FABRIKA_EGRESS_REFUSED_HOSTS) {
103
+ for (const host of value.split(',')) {
104
+ const normalized = normalizedHost(host.trim())
105
+ if (normalized !== '') hosts.add(normalized)
106
+ }
107
+ continue
108
+ }
109
+ const host = urlHost(value)
110
+ if (host !== null) hosts.add(host)
111
+ }
112
+ return { refusedHosts: hosts, resolve }
113
+ }
114
+
115
+ /** The host of a framework variable's value when it is an http(s) URL, such as an origin or a DSN; `null` otherwise. */
116
+ function urlHost(value: string): string | null {
117
+ const text = value.trim()
118
+ if (!/^https?:\/\//i.test(text)) return null
119
+ try {
120
+ return normalizedHost(new URL(text).hostname)
121
+ } catch {
122
+ return null
123
+ }
124
+ }
125
+
41
126
  /**
42
127
  * `facility` with each of its methods run outside any site's scope: a framework facility a handler calls, whose own
43
128
  * requests are the platform's, not the site's.
@@ -59,6 +144,11 @@ export function platformCall<T>(work: () => T): T {
59
144
  return scope.exit(work)
60
145
  }
61
146
 
147
+ /** A hop's `init`: the standard fields, and Bun's `decompress`, which another runtime ignores. */
148
+ type HopInit = RequestInit & { readonly decompress?: boolean }
149
+
150
+ type Fetch = (input: string, init: HopInit) => Promise<Response>
151
+
62
152
  /**
63
153
  * Wraps the global `fetch` in the guard, once: a `fetch` that is already a guard stays. A test that replaces `fetch`
64
154
  * after boot replaces the guard with it.
@@ -68,15 +158,20 @@ export function installEgressGuard(): void {
68
158
  if (guards.has(current)) {
69
159
  return
70
160
  }
161
+ const send: Fetch = (input, init) => current(input, init)
71
162
  const guarded = Object.assign(
72
163
  (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
73
164
  const running = scope.getStore()
74
165
  if (running === undefined) {
75
166
  return current(input, init)
76
167
  }
168
+ if (running.open !== null) {
169
+ return publicFetch(send, running.site, running.open, input, init)
170
+ }
77
171
  const url = urlOf(input)
78
172
  if (url !== null && egressAdmits(running.entries, url)) {
79
- return current(input, init)
173
+ // Only the standard fields: a runtime's own (Bun's `unix`, `proxy`, `tls`) would send the request elsewhere.
174
+ return current(input, standardInit(init))
80
175
  }
81
176
  return Promise.reject(
82
177
  new CapabilityRefusedError(
@@ -87,12 +182,47 @@ export function installEgressGuard(): void {
87
182
  ),
88
183
  )
89
184
  },
90
- { preconnect: current.preconnect },
185
+ {
186
+ // Inside a site's scope a preconnect reaches only a declared origin; public egress, which cannot check a hop
187
+ // before it connects, refuses every one.
188
+ preconnect: (...args: Parameters<typeof current.preconnect>): void => {
189
+ const running = scope.getStore()
190
+ if (running !== undefined) {
191
+ const url = urlOf(args[0])
192
+ if (running.open !== null || url === null || !egressAdmits(running.entries, url)) {
193
+ throw new CapabilityRefusedError(
194
+ running.open === null ? 'undeclared_egress' : 'refused_egress',
195
+ `${running.site} preconnects to ${url?.origin ?? 'a URL that is not absolute'}, which its egress does not reach`,
196
+ )
197
+ }
198
+ }
199
+ if (typeof current.preconnect === 'function') current.preconnect(...args)
200
+ },
201
+ },
91
202
  )
92
203
  guards.add(guarded)
93
204
  globalThis.fetch = guarded
94
205
  }
95
206
 
207
+ /** `init` with the fields of the Fetch standard only. */
208
+ function standardInit(init: RequestInit | undefined): RequestInit | undefined {
209
+ if (init === undefined) return undefined
210
+ return {
211
+ ...(init.method === undefined ? {} : { method: init.method }),
212
+ ...(init.headers === undefined ? {} : { headers: init.headers }),
213
+ ...(init.body === undefined ? {} : { body: init.body }),
214
+ ...(init.redirect === undefined ? {} : { redirect: init.redirect }),
215
+ ...(init.signal === undefined ? {} : { signal: init.signal }),
216
+ ...(init.keepalive === undefined ? {} : { keepalive: init.keepalive }),
217
+ ...(init.integrity === undefined ? {} : { integrity: init.integrity }),
218
+ ...(init.referrer === undefined ? {} : { referrer: init.referrer }),
219
+ ...(init.referrerPolicy === undefined ? {} : { referrerPolicy: init.referrerPolicy }),
220
+ ...(init.cache === undefined ? {} : { cache: init.cache }),
221
+ ...(init.credentials === undefined ? {} : { credentials: init.credentials }),
222
+ ...(init.mode === undefined ? {} : { mode: init.mode }),
223
+ }
224
+ }
225
+
96
226
  function urlOf(input: string | URL | Request): URL | null {
97
227
  try {
98
228
  return new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url)
@@ -100,3 +230,273 @@ function urlOf(input: string | URL | Request): URL | null {
100
230
  return null
101
231
  }
102
232
  }
233
+
234
+ const REDIRECTS: ReadonlySet<number> = new Set([301, 302, 303, 307, 308])
235
+ /** The headers a redirect that turns a request into a `GET` drops with its body (Fetch, "HTTP-redirect fetch"). */
236
+ const BODY_HEADERS = ['content-type', 'content-length', 'content-encoding', 'content-language', 'content-location']
237
+ /**
238
+ * The request headers public egress never sends, on any hop: the Fetch standard's forbidden request headers (`Host`
239
+ * among them, which would route a request for a public name to another site at the same address), the forwarding
240
+ * headers a proxy trusts, and the platform's own `X-Fabrika-*`.
241
+ */
242
+ const FORBIDDEN_HEADERS = [
243
+ 'accept-charset',
244
+ 'accept-encoding',
245
+ 'access-control-request-headers',
246
+ 'access-control-request-method',
247
+ 'connection',
248
+ 'content-length',
249
+ 'cookie2',
250
+ 'date',
251
+ 'dnt',
252
+ 'expect',
253
+ 'forwarded',
254
+ 'host',
255
+ 'keep-alive',
256
+ 'origin',
257
+ 'referer',
258
+ 'set-cookie',
259
+ 'te',
260
+ 'trailer',
261
+ 'transfer-encoding',
262
+ 'upgrade',
263
+ 'via',
264
+ 'x-http-method',
265
+ 'x-http-method-override',
266
+ 'x-method-override',
267
+ 'x-real-ip',
268
+ ]
269
+ const FORBIDDEN_HEADER_PREFIXES = ['proxy-', 'sec-', 'x-forwarded-', 'x-fabrika-']
270
+
271
+ function withoutForbiddenHeaders(headers: Headers): Headers {
272
+ for (const name of [...headers.keys()]) {
273
+ if (FORBIDDEN_HEADERS.includes(name) || FORBIDDEN_HEADER_PREFIXES.some((prefix) => name.startsWith(prefix))) {
274
+ headers.delete(name)
275
+ }
276
+ }
277
+ return headers
278
+ }
279
+
280
+ /** The credentials a redirect to another origin drops. */
281
+ const CREDENTIAL_HEADERS = ['authorization', 'proxy-authorization', 'cookie']
282
+
283
+ /**
284
+ * One request under public egress. Every hop is sent with `redirect: 'manual'`, so the runtime follows no redirect the
285
+ * guard has not checked: the caller's `follow` is done here, at most `maxRedirects` hops, each host checked again;
286
+ * `manual` hands the caller the redirect, whose next `fetch` passes the guard again; `error` refuses one. The request
287
+ * is bounded in time and its answer's body in size.
288
+ */
289
+ async function publicFetch(
290
+ send: Fetch,
291
+ site: string,
292
+ rules: PublicEgressRules,
293
+ input: string | URL | Request,
294
+ init?: RequestInit,
295
+ ): Promise<Response> {
296
+ const request = new Request(input, init)
297
+ // A timer the guard clears once the body is read, not `AbortSignal.timeout`: on workerd an uncleared timer keeps the
298
+ // Durable Object awake until it fires.
299
+ const deadline = new AbortController()
300
+ const timer = setTimeout(() => deadline.abort(new DOMException('public egress request timed out', 'TimeoutError')), PUBLIC_EGRESS_LIMITS.timeoutMs)
301
+ try {
302
+ return await follow(send, site, rules, request, AbortSignal.any([request.signal, deadline.signal]))
303
+ } finally {
304
+ clearTimeout(timer)
305
+ }
306
+ }
307
+
308
+ /** The hops of one request, its last answer's body read whole. */
309
+ async function follow(send: Fetch, site: string, rules: PublicEgressRules, request: Request, signal: AbortSignal): Promise<Response> {
310
+ const mode = request.redirect
311
+ let url = new URL(request.url)
312
+ let method = request.method
313
+ const headers = withoutForbiddenHeaders(new Headers(request.headers))
314
+ // Read once, so that a 307 or a 308 sends it again.
315
+ let body: ArrayBuffer | null = request.body === null ? null : await untilAborted(signal, request.arrayBuffer())
316
+ for (let hop = 0;; hop++) {
317
+ const address = await admit(site, rules, url, signal)
318
+ // Cancelling a body leaves Bun downloading it into memory; only aborting the request closes the connection.
319
+ const dropped = new AbortController()
320
+ const response = await send(address === null ? url.href : pinnedUrl(url, address), {
321
+ method,
322
+ headers: hopHeaders(headers, url, address),
323
+ body,
324
+ redirect: 'manual',
325
+ signal: AbortSignal.any([signal, dropped.signal]),
326
+ // Bun decompresses natively and unbounded: the guard asks for `identity` and reads the bytes as they came.
327
+ decompress: false,
328
+ // Bun pools connections by address and port: a pooled one was checked against another name's certificate.
329
+ ...(address === null ? {} : { keepalive: false }),
330
+ })
331
+ const location = REDIRECTS.has(response.status) ? response.headers.get('location') : null
332
+ if (location === null || mode === 'manual') {
333
+ return await bounded(site, response, url, hop > 0, signal).catch((error: unknown) => {
334
+ dropped.abort(error)
335
+ throw error
336
+ })
337
+ }
338
+ dropped.abort()
339
+ void response.body?.cancel().catch(() => undefined)
340
+ if (mode === 'error') {
341
+ throw new TypeError(`${site}: ${url.origin} redirects, and the request's redirect mode is 'error'`)
342
+ }
343
+ if (hop >= PUBLIC_EGRESS_LIMITS.maxRedirects) {
344
+ throw new TypeError(`${site}: more than ${PUBLIC_EGRESS_LIMITS.maxRedirects} redirects, the last from ${url.origin}`)
345
+ }
346
+ const next = new URL(location, url)
347
+ const toGet = (response.status === 303 && method !== 'GET' && method !== 'HEAD')
348
+ || ((response.status === 301 || response.status === 302) && method === 'POST')
349
+ if (toGet) {
350
+ method = 'GET'
351
+ body = null
352
+ for (const name of BODY_HEADERS) headers.delete(name)
353
+ }
354
+ if (next.origin !== url.origin) {
355
+ for (const name of CREDENTIAL_HEADERS) headers.delete(name)
356
+ }
357
+ url = next
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Refuses a hop public egress does not reach: by the URL, by the installation's hosts, by what its name resolves to.
363
+ * Answers the checked address the hop must connect to, or `null` where the runtime resolves nothing (a Worker).
364
+ */
365
+ async function admit(site: string, rules: PublicEgressRules, url: URL, signal: AbortSignal): Promise<string | null> {
366
+ const refusal = publicEgressRefusal(url, rules.refusedHosts)
367
+ if (refusal !== null) {
368
+ throw new CapabilityRefusedError('refused_egress', `${site} calls ${url.origin}, which public egress refuses: ${refusal}`)
369
+ }
370
+ const resolve = rules.resolve
371
+ if (resolve === null) {
372
+ return null
373
+ }
374
+ const host = normalizedHost(url.hostname)
375
+ const addresses = await untilAborted(signal, platformCall(() => resolve(host)))
376
+ const internal = addresses.find((address) => !isPublicAddress(address))
377
+ const address = addresses.find((candidate) => !candidate.includes(':')) ?? addresses[0]
378
+ if (address === undefined || internal !== undefined) {
379
+ throw new CapabilityRefusedError(
380
+ 'refused_egress',
381
+ `${site} calls ${url.origin}, which public egress refuses: ${
382
+ internal === undefined ? `${host} resolves to no address` : `${host} resolves to ${internal}, which is not a public address`
383
+ }`,
384
+ )
385
+ }
386
+ return address
387
+ }
388
+
389
+ /**
390
+ * `url` with its host replaced by the checked `address`, so the runtime connects where the guard looked and never
391
+ * resolves the name again (DNS rebinding). IPv4 first: a container without an IPv6 route still connects.
392
+ */
393
+ function pinnedUrl(url: URL, address: string): string {
394
+ const pinned = new URL(url.href)
395
+ pinned.hostname = address.includes(':') ? `[${address}]` : address
396
+ return pinned.href
397
+ }
398
+
399
+ /**
400
+ * A hop's headers: for a pinned hop, `Host` names the checked host, which Bun sends and checks the server's certificate
401
+ * against (`public-egress-pinning.test.ts` holds the pinned Bun release to it).
402
+ */
403
+ function hopHeaders(headers: Headers, url: URL, address: string | null): Headers {
404
+ const hop = new Headers(headers)
405
+ hop.set('accept-encoding', 'identity')
406
+ if (address !== null) hop.set('host', normalizedHost(url.hostname))
407
+ return hop
408
+ }
409
+
410
+ /** The statuses from 200 up whose answer has no body (Fetch, "null body status"); `Response` refuses one with a body. */
411
+ const NULL_BODY_STATUSES: ReadonlySet<number> = new Set([204, 205, 304])
412
+
413
+ /**
414
+ * `response` read whole before the caller sees it, at most `maxResponseBytes`, within the request's deadline, with the
415
+ * URL and redirect flag of the request it answers. Bun buffers a body as it arrives whether or not anyone reads it, so
416
+ * the guard reads it at once and cancels it at the cap. An encoded body is refused unread: the guard asked for
417
+ * `identity`, and decoding it would grow it without a bound the guard controls.
418
+ */
419
+ async function bounded(site: string, response: Response, url: URL, redirected: boolean, signal: AbortSignal): Promise<Response> {
420
+ const encoding = response.headers.get('content-encoding')?.trim().toLowerCase() ?? ''
421
+ if (encoding !== '' && encoding !== 'identity') {
422
+ void response.body?.cancel().catch(() => undefined)
423
+ throw new CapabilityRefusedError(
424
+ 'encoded_egress',
425
+ `${site}: ${url.origin} answers with Content-Encoding ${encoding}, which public egress neither asks for nor decodes`,
426
+ )
427
+ }
428
+ if (response.status < 200 || response.status > 599) {
429
+ // Bun answers a status a `Response` cannot carry (600 and up); refusing it lets the caller abort the hop.
430
+ throw new TypeError(`${site}: ${url.origin} answers status ${response.status}, which public egress does not read`)
431
+ }
432
+ const init = { status: response.status, statusText: response.statusText, headers: response.headers }
433
+ const body = await readCapped(site, response, url, signal)
434
+ return withRequestUrl(new Response(NULL_BODY_STATUSES.has(response.status) ? null : body, init), url, redirected)
435
+ }
436
+
437
+ /** The bytes of `response`'s body, refused past `maxResponseBytes` by its `Content-Length` or as they arrive. */
438
+ async function readCapped(site: string, response: Response, url: URL, signal: AbortSignal): Promise<Uint8Array<ArrayBuffer>> {
439
+ const max = PUBLIC_EGRESS_LIMITS.maxResponseBytes
440
+ const tooLarge = () =>
441
+ new CapabilityRefusedError(
442
+ 'oversized_egress',
443
+ `${site}: ${url.origin} answers more than ${max} bytes, the most public egress reads of one response`,
444
+ )
445
+ if (response.body === null) {
446
+ return new Uint8Array()
447
+ }
448
+ const declared = Number(response.headers.get('content-length') ?? '0')
449
+ if (Number.isFinite(declared) && declared > max) {
450
+ void response.body.cancel().catch(() => undefined)
451
+ throw tooLarge()
452
+ }
453
+ const reader = response.body.getReader()
454
+ const chunks: Uint8Array[] = []
455
+ let seen = 0
456
+ try {
457
+ for (;;) {
458
+ const read = await untilAborted(signal, reader.read())
459
+ if (read.done) break
460
+ seen += read.value.byteLength
461
+ if (seen > max) throw tooLarge()
462
+ chunks.push(read.value)
463
+ }
464
+ } catch (error) {
465
+ void reader.cancel(error).catch(() => undefined)
466
+ throw error
467
+ }
468
+ const bytes = new Uint8Array(seen)
469
+ let offset = 0
470
+ for (const chunk of chunks) {
471
+ bytes.set(chunk, offset)
472
+ offset += chunk.byteLength
473
+ }
474
+ return bytes
475
+ }
476
+
477
+ /**
478
+ * `work`, or the signal's reason once it aborts, whichever comes first: a stage the runtime does not abort by the
479
+ * signal (a resolver, a body read) still ends at the deadline. The work itself is left to settle unobserved.
480
+ */
481
+ async function untilAborted<T>(signal: AbortSignal, work: Promise<T>): Promise<T> {
482
+ signal.throwIfAborted()
483
+ let abort = (): void => {}
484
+ const aborted = new Promise<never>((_resolve, reject) => {
485
+ abort = () => reject(signal.reason)
486
+ })
487
+ signal.addEventListener('abort', abort, { once: true })
488
+ try {
489
+ return await Promise.race([work, aborted])
490
+ } finally {
491
+ signal.removeEventListener('abort', abort)
492
+ }
493
+ }
494
+
495
+ function withRequestUrl(response: Response, url: URL, redirected: boolean): Response {
496
+ try {
497
+ Object.defineProperties(response, { url: { value: url.href }, redirected: { value: redirected } })
498
+ } catch {
499
+ // A runtime whose responses refuse own properties keeps its own `url`; the body bound holds either way.
500
+ }
501
+ return response
502
+ }
@@ -3,7 +3,7 @@
3
3
 
4
4
  import type { TablePolicyArtifact } from '@fabrika/auth-core'
5
5
  import type { DataLayer } from '@fabrika/db'
6
- import type { CapabilityAuthority } from '@fabrika/db/capability'
6
+ import type { CapabilityAuthority, ContainerGrant, RelationHold } from '@fabrika/db/capability'
7
7
  import type { Session } from '@fabrika/db/framework'
8
8
  import type { EmailSender } from '@fabrika/email'
9
9
  import type { ConnectSnapshot } from '../contract/connect'
@@ -27,8 +27,28 @@ export interface ContractDatabase {
27
27
  * own has none, so no Ref is ever held through a relation there.
28
28
  */
29
29
  relates?(relation: string, node: string, principal: string): Promise<boolean>
30
- /** Whether a row `relation` reaches for `principal` reveals `node` of `dimension` now; none in a layer of the application's own. */
31
- reveals?(relation: string, dimension: string, node: string, principal: string): Promise<boolean>
30
+ /**
31
+ * Whether a row `relation` reaches for `principal` reveals `node` of `dimension` for `action` now; none in a layer of
32
+ * the application's own.
33
+ */
34
+ reveals?(relation: string, dimension: string, node: string, principal: string, action: string): Promise<boolean>
35
+ /**
36
+ * Of `relations` and `paths`, the caller's relations and grants of `action` that reach the object through a secondary
37
+ * path that holds the action for a Ref (`writeThrough`); none in a layer of the application's own.
38
+ */
39
+ holdsThrough?(
40
+ dimension: string,
41
+ id: string,
42
+ action: string,
43
+ principal: string,
44
+ relations: readonly RelationHold[],
45
+ paths: readonly ContainerGrant[],
46
+ ): Promise<{ readonly relations: readonly RelationHold[]; readonly paths: readonly ContainerGrant[] }>
47
+ /**
48
+ * Of `values`, the caller's grants of `action` at nodes of `revealing`, those whose row reveals `node` of `dimension`
49
+ * to its members now; none in a layer of the application's own.
50
+ */
51
+ revealsToMembers?(revealing: string, values: readonly string[], dimension: string, node: string, action: string): Promise<readonly string[]>
32
52
  }
33
53
 
34
54
  /** `scoped(tables)` of `@fabrika/db`, which `boot` binds, or a `ContractDatabase` of the application's own. */
@@ -3,7 +3,7 @@
3
3
  // commits it after the handler returned and its output passed validation, and rolls it back otherwise. Every handle
4
4
  // is bound to the invocation: called from another request, another `boot`, or after it ended, it refuses.
5
5
 
6
- import { type ContractArtifact, JOB_MAILERS, type JobMailer } from '@fabrika/auth-core'
6
+ import { type ContractArtifact, type DeclaredEgress, JOB_MAILERS, type JobMailer, PUBLIC_EGRESS } from '@fabrika/auth-core'
7
7
  import {
8
8
  type DataAccess,
9
9
  type DataHandles,
@@ -35,8 +35,8 @@ export interface SiteDeclaration {
35
35
  readonly binds: string | null
36
36
  /** The token purposes `ctx.tokens.sign` may sign. */
37
37
  readonly signs: readonly string[]
38
- /** The HTTPS origins the global `fetch` reaches while the site's handler runs. */
39
- readonly egress: readonly string[]
38
+ /** The HTTPS origins the global `fetch` reaches while the site's handler runs, or `'public'`: every public host (a cron job). */
39
+ readonly egress: DeclaredEgress
40
40
  }
41
41
 
42
42
  /** A public procedure's reach: the texts the verified signed tokens of its request carry, which name the rows it changes. */
@@ -167,10 +167,11 @@ export function parseDeclaration(where: string, declared: unknown, kind: DataKin
167
167
  problems.push(`${where}: signs is not a list of token purposes`)
168
168
  }
169
169
  const egressField = ownField(declared, 'egress')
170
- const egress = Array.isArray(egressField) ? egressField.filter((origin): origin is string => typeof origin === 'string') : []
171
- if (egressField !== undefined && (!Array.isArray(egressField) || egress.length !== egressField.length)) {
172
- problems.push(`${where}: egress is not a list of origins`)
170
+ const origins = Array.isArray(egressField) ? egressField.filter((origin): origin is string => typeof origin === 'string') : []
171
+ if (egressField !== undefined && egressField !== PUBLIC_EGRESS && (!Array.isArray(egressField) || origins.length !== egressField.length)) {
172
+ problems.push(`${where}: egress is not a list of origins or '${PUBLIC_EGRESS}'`)
173
173
  }
174
+ const egress: DeclaredEgress = egressField === PUBLIC_EGRESS ? PUBLIC_EGRESS : Object.freeze([...new Set(origins)].sort())
174
175
  return Object.freeze({
175
176
  sql: sql === 'read' || sql === 'write' ? sql : null,
176
177
  unscoped: Object.freeze(unscoped),
@@ -180,7 +181,7 @@ export function parseDeclaration(where: string, declared: unknown, kind: DataKin
180
181
  kicks: Object.freeze([...new Set(kicks)].sort()),
181
182
  binds: typeof binds === 'string' ? binds : null,
182
183
  signs: Object.freeze([...new Set(signs)].sort()),
183
- egress: Object.freeze([...new Set(egress)].sort()),
184
+ egress,
184
185
  })
185
186
  }
186
187
 
@@ -225,7 +226,7 @@ export function approvedReach(site: string, artifact: ContractArtifact): SiteDec
225
226
  kicks: Object.freeze([...(reach.kicks ?? [])]),
226
227
  binds: reach.binds ?? null,
227
228
  signs: Object.freeze([...(reach.signs ?? [])]),
228
- egress: Object.freeze([...(reach.egress ?? [])]),
229
+ egress: reach.egress === PUBLIC_EGRESS ? PUBLIC_EGRESS : Object.freeze([...(reach.egress ?? [])]),
229
230
  })
230
231
  }
231
232
 
@@ -244,7 +245,7 @@ function describeDeclaration(declaration: SiteDeclaration): string {
244
245
  ...(declaration.kicks.length === 0 ? {} : { kicks: declaration.kicks }),
245
246
  ...(declaration.binds === null ? {} : { binds: declaration.binds }),
246
247
  ...(declaration.signs.length === 0 ? {} : { signs: declaration.signs }),
247
- ...(declaration.egress.length === 0 ? {} : { egress: declaration.egress }),
248
+ ...(declaration.egress !== PUBLIC_EGRESS && declaration.egress.length === 0 ? {} : { egress: declaration.egress }),
248
249
  })
249
250
  }
250
251
 
@@ -215,13 +215,24 @@ export type HandlersOf<C, Snap = unknown> =
215
215
  /** An `any` comes from an error elsewhere in the handler; reporting it here too would only add noise. */
216
216
  export type IsAny<T> = 0 extends 1 & T ? true : false
217
217
 
218
- /** Fields of `R` that the output `O` does not declare. When `O` is a union, a value that fits one branch has none. */
218
+ /**
219
+ * Fields of `R` that the output `O` does not declare. Each member of a union `R` is paired with `O` on its own, and a
220
+ * member that fits one branch of a union `O` has none.
221
+ */
219
222
  export type ExtraKeys<R, O> = IsAny<R> extends true ? never
220
- : true extends (O extends unknown ? ([ExtraKeysOf<R, O>] extends [never] ? true : false) : never) ? never
221
- : ExtraKeysOf<R, O>
223
+ : R extends unknown ? true extends (O extends unknown ? ([ExtraKeysOf<R, O>] extends [never] ? true : false) : never) ? never
224
+ : ExtraKeysOf<R, O>
225
+ : never
226
+
227
+ /**
228
+ * Optional keys that can hold only `undefined`: TypeScript adds them when it widens object literals of different
229
+ * shapes to one type (`{ x } | { x, y }` read as `{ x, y?: undefined }`). They carry no value, and projection drops them.
230
+ */
231
+ type EmptyKeys<R> = { [K in keyof R]-?: object extends Pick<R, K> ? ([Exclude<R[K], undefined>] extends [never] ? K : never) : never }[keyof R]
222
232
 
223
233
  type ExtraKeysOf<R, O> = R extends readonly (infer RE)[] ? (O extends readonly (infer OE)[] ? ExtraKeys<RE, OE> : never)
224
- : R extends object ? O extends object ? Exclude<keyof R, keyof O> | { [Q in keyof R & keyof O]: ExtraKeys<R[Q], O[Q]> }[keyof R & keyof O]
234
+ : R extends object
235
+ ? O extends object ? Exclude<keyof R, keyof O | EmptyKeys<R>> | { [Q in keyof R & keyof O]: ExtraKeys<R[Q], O[Q]> }[keyof R & keyof O]
225
236
  : never
226
237
  : never
227
238
 
@@ -110,6 +110,14 @@ export function webhookBindings(site: BindingSite): (name: string) => WebhookBin
110
110
  return APP_BINDING_SCOPE
111
111
  }
112
112
  if (webhook.boundTo.kind === 'dimension' && grant.kind === 'ref' && grant.dimension === webhook.boundTo.dimension) {
113
+ // A binding outlives every statement, so it takes no reach that a statement re-reads: a relation row, a
114
+ // member reveal or a secondary path may end before the next delivery.
115
+ if (grant.relations.length > 0 || grant.revealing.length > 0 || grant.paths.length > 0) {
116
+ throw new CapabilityRefusedError(
117
+ 'conditional_binding',
118
+ `${site.site}: webhook '${webhook.name}' binds only with a Ref an IAM grant holds, and it was handed one held through a relation, a member reveal or a secondary path`,
119
+ )
120
+ }
113
121
  return { type: grant.dimension, value: grant.id }
114
122
  }
115
123
  const wanted = webhook.boundTo.kind === 'app' ? 'an app capability (ctx.app)' : `a Ref of ${webhook.boundTo.dimension}`
@@ -34,7 +34,7 @@ import {
34
34
  type Within,
35
35
  } from '../implement/capability'
36
36
  import { admitInvocation, type InvocationAdmission } from '../implement/dispatch'
37
- import { runAsSite } from '../implement/egress'
37
+ import { type PublicEgressRules, runAsSite, siteEgress } from '../implement/egress'
38
38
  import { failureCode, type FailureReason, failureReason, type HandlerErrorSink, reveal } from '../implement/failures'
39
39
  import { ServerFault } from '../implement/faults'
40
40
  import type { ContractDatabase } from '../implement/implement'
@@ -274,6 +274,8 @@ interface RunnerContext {
274
274
  /** The environment's signed tokens: `ctx.tokens` of a job that declares `signs`. */
275
275
  readonly tokens: SignedTokens | null
276
276
  readonly url: AppUrl
277
+ /** What a job that declares `egress: 'public'` reaches; such a job reaches nothing without it. */
278
+ readonly publicEgress: PublicEgressRules | null
277
279
  }
278
280
 
279
281
  export interface JobBindingInput {
@@ -310,6 +312,8 @@ export interface JobBindingInput {
310
312
  readonly tokens?: SignedTokens
311
313
  /** `ctx.url`: absolute links to the application's own procedures; without it every link is refused. */
312
314
  readonly url?: AppUrl
315
+ /** The rules of public egress, which `boot` reads from the environment; without them a public job reaches nothing. */
316
+ readonly publicEgress?: PublicEgressRules
313
317
  }
314
318
 
315
319
  interface BoundFrameworkJob {
@@ -420,6 +424,7 @@ export function bindJobs(input: JobBindingInput, problems: string[]): BoundJobs
420
424
  mail: input.mail,
421
425
  tokens: input.tokens ?? null,
422
426
  url: input.url ?? appUrl(input.artifact, null),
427
+ publicEgress: input.publicEgress ?? null,
423
428
  // A job's kicks run only after the job is bound, so `kick` below is defined by then.
424
429
  kick: (name: string) => kick(name),
425
430
  })
@@ -1252,7 +1257,7 @@ async function attemptOnce(
1252
1257
  if (site === null) {
1253
1258
  await job.handler({ ctx })
1254
1259
  } else {
1255
- await runAsSite(`job '${job.name}'`, site.egress, async () => await job.handler({ ctx }))
1260
+ await runAsSite(`job '${job.name}'`, siteEgress(site.egress, context.publicEgress), async () => await job.handler({ ctx }))
1256
1261
  }
1257
1262
  kicked.recorder = kicks
1258
1263
  }).then(() => null, (error: unknown) => {