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

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 (89) hide show
  1. package/package.json +14 -9
  2. package/skill/SKILL.md +3 -2
  3. package/skill/references/app-setup.md +17 -9
  4. package/skill/references/endpoint.md +15 -2
  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/build-contract-child.ts +16 -0
  11. package/src/build.ts +48 -2
  12. package/src/bun.ts +10 -0
  13. package/src/client/contract.ts +6 -4
  14. package/src/cloudflare/application.ts +3 -0
  15. package/src/contract/artifact-schema.ts +367 -299
  16. package/src/contract/attachment.ts +4 -3
  17. package/src/contract/build.ts +76 -18
  18. package/src/contract/compile.ts +3 -2
  19. package/src/contract/context.ts +2 -3
  20. package/src/contract/define.ts +19 -6
  21. package/src/contract/group.ts +18 -8
  22. package/src/contract/index.ts +1 -1
  23. package/src/contract/kit.ts +4 -3
  24. package/src/contract/problems.ts +4 -0
  25. package/src/contract/schema-shape.ts +14 -2
  26. package/src/contract/token.ts +4 -3
  27. package/src/disk-assets.ts +15 -3
  28. package/src/from-row.ts +12 -6
  29. package/src/implement/approved.ts +57 -0
  30. package/src/implement/attachment.ts +2 -1
  31. package/src/implement/boot.ts +118 -17
  32. package/src/implement/capability.ts +82 -12
  33. package/src/implement/dispatch.ts +265 -45
  34. package/src/implement/egress.ts +410 -9
  35. package/src/implement/faults.ts +1 -0
  36. package/src/implement/implement.ts +23 -3
  37. package/src/implement/invocation.ts +10 -9
  38. package/src/implement/project.ts +3 -1
  39. package/src/implement/tokens.ts +3 -2
  40. package/src/implement/types.ts +33 -10
  41. package/src/implement/webhook.ts +8 -0
  42. package/src/jobs/runner.ts +7 -2
  43. package/src/react/hooks.ts +12 -11
  44. package/src/react/provider.tsx +2 -1
  45. package/src/react/types.ts +2 -2
  46. package/src/schema/builder.ts +146 -0
  47. package/src/schema/data-schema.ts +365 -0
  48. package/src/schema/index.ts +18 -0
  49. package/src/schema/replay.ts +623 -0
  50. package/src/source-map-path.ts +21 -0
  51. package/src/testing/caller.ts +20 -9
  52. package/src/testing/kit.ts +3 -3
  53. package/src/testing/membership.ts +9 -5
  54. package/types/src/build-contract-child.d.ts +1 -0
  55. package/types/src/build.d.ts +16 -1
  56. package/types/src/client/contract.d.ts +3 -4
  57. package/types/src/cloudflare/application.d.ts +2 -0
  58. package/types/src/contract/artifact-schema.d.ts +8 -0
  59. package/types/src/contract/attachment.d.ts +3 -2
  60. package/types/src/contract/context.d.ts +2 -3
  61. package/types/src/contract/define.d.ts +16 -6
  62. package/types/src/contract/group.d.ts +14 -7
  63. package/types/src/contract/index.d.ts +1 -1
  64. package/types/src/contract/kit.d.ts +4 -5
  65. package/types/src/contract/problems.d.ts +1 -0
  66. package/types/src/contract/schema-shape.d.ts +3 -2
  67. package/types/src/contract/token.d.ts +3 -3
  68. package/types/src/from-row.d.ts +9 -5
  69. package/types/src/implement/approved.d.ts +11 -0
  70. package/types/src/implement/boot.d.ts +12 -0
  71. package/types/src/implement/capability.d.ts +14 -5
  72. package/types/src/implement/dispatch.d.ts +9 -1
  73. package/types/src/implement/egress.d.ts +36 -1
  74. package/types/src/implement/faults.d.ts +1 -0
  75. package/types/src/implement/implement.d.ts +19 -3
  76. package/types/src/implement/invocation.d.ts +3 -3
  77. package/types/src/implement/project.d.ts +2 -1
  78. package/types/src/implement/types.d.ts +17 -8
  79. package/types/src/jobs/runner.d.ts +3 -0
  80. package/types/src/react/hooks.d.ts +4 -5
  81. package/types/src/react/types.d.ts +2 -2
  82. package/types/src/schema/builder.d.ts +45 -0
  83. package/types/src/schema/data-schema.d.ts +124 -0
  84. package/types/src/schema/index.d.ts +3 -0
  85. package/types/src/schema/replay.d.ts +27 -0
  86. package/types/src/source-map-path.d.ts +4 -0
  87. package/types/src/testing/caller.d.ts +6 -1
  88. package/types/src/testing/kit.d.ts +2 -3
  89. 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` and `tls`, which another runtime ignores. */
148
+ type HopInit = RequestInit & { readonly decompress?: boolean; readonly tls?: { readonly serverName: string } }
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,274 @@ 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 checks the certificate against `serverName`, not `Host`, and pools connections by address and port: a
329
+ // pooled one was checked against another name's certificate.
330
+ ...(address === null ? {} : { keepalive: false, tls: { serverName: normalizedHost(url.hostname) } }),
331
+ })
332
+ const location = REDIRECTS.has(response.status) ? response.headers.get('location') : null
333
+ if (location === null || mode === 'manual') {
334
+ return await bounded(site, response, url, hop > 0, signal).catch((error: unknown) => {
335
+ dropped.abort(error)
336
+ throw error
337
+ })
338
+ }
339
+ dropped.abort()
340
+ void response.body?.cancel().catch(() => undefined)
341
+ if (mode === 'error') {
342
+ throw new TypeError(`${site}: ${url.origin} redirects, and the request's redirect mode is 'error'`)
343
+ }
344
+ if (hop >= PUBLIC_EGRESS_LIMITS.maxRedirects) {
345
+ throw new TypeError(`${site}: more than ${PUBLIC_EGRESS_LIMITS.maxRedirects} redirects, the last from ${url.origin}`)
346
+ }
347
+ const next = new URL(location, url)
348
+ const toGet = (response.status === 303 && method !== 'GET' && method !== 'HEAD')
349
+ || ((response.status === 301 || response.status === 302) && method === 'POST')
350
+ if (toGet) {
351
+ method = 'GET'
352
+ body = null
353
+ for (const name of BODY_HEADERS) headers.delete(name)
354
+ }
355
+ if (next.origin !== url.origin) {
356
+ for (const name of CREDENTIAL_HEADERS) headers.delete(name)
357
+ }
358
+ url = next
359
+ }
360
+ }
361
+
362
+ /**
363
+ * Refuses a hop public egress does not reach: by the URL, by the installation's hosts, by what its name resolves to.
364
+ * Answers the checked address the hop must connect to, or `null` where the runtime resolves nothing (a Worker).
365
+ */
366
+ async function admit(site: string, rules: PublicEgressRules, url: URL, signal: AbortSignal): Promise<string | null> {
367
+ const refusal = publicEgressRefusal(url, rules.refusedHosts)
368
+ if (refusal !== null) {
369
+ throw new CapabilityRefusedError('refused_egress', `${site} calls ${url.origin}, which public egress refuses: ${refusal}`)
370
+ }
371
+ const resolve = rules.resolve
372
+ if (resolve === null) {
373
+ return null
374
+ }
375
+ const host = normalizedHost(url.hostname)
376
+ const addresses = await untilAborted(signal, platformCall(() => resolve(host)))
377
+ const internal = addresses.find((address) => !isPublicAddress(address))
378
+ const address = addresses.find((candidate) => !candidate.includes(':')) ?? addresses[0]
379
+ if (address === undefined || internal !== undefined) {
380
+ throw new CapabilityRefusedError(
381
+ 'refused_egress',
382
+ `${site} calls ${url.origin}, which public egress refuses: ${
383
+ internal === undefined ? `${host} resolves to no address` : `${host} resolves to ${internal}, which is not a public address`
384
+ }`,
385
+ )
386
+ }
387
+ return address
388
+ }
389
+
390
+ /**
391
+ * `url` with its host replaced by the checked `address`, so the runtime connects where the guard looked and never
392
+ * resolves the name again (DNS rebinding). IPv4 first: a container without an IPv6 route still connects.
393
+ */
394
+ function pinnedUrl(url: URL, address: string): string {
395
+ const pinned = new URL(url.href)
396
+ pinned.hostname = address.includes(':') ? `[${address}]` : address
397
+ return pinned.href
398
+ }
399
+
400
+ /**
401
+ * A hop's headers: for a pinned hop, `Host` names the checked host, which Bun sends; `follow` names it as the TLS
402
+ * `serverName` too (`public-egress-pinning.test.ts` holds the pinned Bun release to both).
403
+ */
404
+ function hopHeaders(headers: Headers, url: URL, address: string | null): Headers {
405
+ const hop = new Headers(headers)
406
+ hop.set('accept-encoding', 'identity')
407
+ if (address !== null) hop.set('host', normalizedHost(url.hostname))
408
+ return hop
409
+ }
410
+
411
+ /** The statuses from 200 up whose answer has no body (Fetch, "null body status"); `Response` refuses one with a body. */
412
+ const NULL_BODY_STATUSES: ReadonlySet<number> = new Set([204, 205, 304])
413
+
414
+ /**
415
+ * `response` read whole before the caller sees it, at most `maxResponseBytes`, within the request's deadline, with the
416
+ * URL and redirect flag of the request it answers. Bun buffers a body as it arrives whether or not anyone reads it, so
417
+ * the guard reads it at once and cancels it at the cap. An encoded body is refused unread: the guard asked for
418
+ * `identity`, and decoding it would grow it without a bound the guard controls.
419
+ */
420
+ async function bounded(site: string, response: Response, url: URL, redirected: boolean, signal: AbortSignal): Promise<Response> {
421
+ const encoding = response.headers.get('content-encoding')?.trim().toLowerCase() ?? ''
422
+ if (encoding !== '' && encoding !== 'identity') {
423
+ void response.body?.cancel().catch(() => undefined)
424
+ throw new CapabilityRefusedError(
425
+ 'encoded_egress',
426
+ `${site}: ${url.origin} answers with Content-Encoding ${encoding}, which public egress neither asks for nor decodes`,
427
+ )
428
+ }
429
+ if (response.status < 200 || response.status > 599) {
430
+ // Bun answers a status a `Response` cannot carry (600 and up); refusing it lets the caller abort the hop.
431
+ throw new TypeError(`${site}: ${url.origin} answers status ${response.status}, which public egress does not read`)
432
+ }
433
+ const init = { status: response.status, statusText: response.statusText, headers: response.headers }
434
+ const body = await readCapped(site, response, url, signal)
435
+ return withRequestUrl(new Response(NULL_BODY_STATUSES.has(response.status) ? null : body, init), url, redirected)
436
+ }
437
+
438
+ /** The bytes of `response`'s body, refused past `maxResponseBytes` by its `Content-Length` or as they arrive. */
439
+ async function readCapped(site: string, response: Response, url: URL, signal: AbortSignal): Promise<Uint8Array<ArrayBuffer>> {
440
+ const max = PUBLIC_EGRESS_LIMITS.maxResponseBytes
441
+ const tooLarge = () =>
442
+ new CapabilityRefusedError(
443
+ 'oversized_egress',
444
+ `${site}: ${url.origin} answers more than ${max} bytes, the most public egress reads of one response`,
445
+ )
446
+ if (response.body === null) {
447
+ return new Uint8Array()
448
+ }
449
+ const declared = Number(response.headers.get('content-length') ?? '0')
450
+ if (Number.isFinite(declared) && declared > max) {
451
+ void response.body.cancel().catch(() => undefined)
452
+ throw tooLarge()
453
+ }
454
+ const reader = response.body.getReader()
455
+ const chunks: Uint8Array[] = []
456
+ let seen = 0
457
+ try {
458
+ for (;;) {
459
+ const read = await untilAborted(signal, reader.read())
460
+ if (read.done) break
461
+ seen += read.value.byteLength
462
+ if (seen > max) throw tooLarge()
463
+ chunks.push(read.value)
464
+ }
465
+ } catch (error) {
466
+ void reader.cancel(error).catch(() => undefined)
467
+ throw error
468
+ }
469
+ const bytes = new Uint8Array(seen)
470
+ let offset = 0
471
+ for (const chunk of chunks) {
472
+ bytes.set(chunk, offset)
473
+ offset += chunk.byteLength
474
+ }
475
+ return bytes
476
+ }
477
+
478
+ /**
479
+ * `work`, or the signal's reason once it aborts, whichever comes first: a stage the runtime does not abort by the
480
+ * signal (a resolver, a body read) still ends at the deadline. The work itself is left to settle unobserved.
481
+ */
482
+ async function untilAborted<T>(signal: AbortSignal, work: Promise<T>): Promise<T> {
483
+ signal.throwIfAborted()
484
+ let abort = (): void => {}
485
+ const aborted = new Promise<never>((_resolve, reject) => {
486
+ abort = () => reject(signal.reason)
487
+ })
488
+ signal.addEventListener('abort', abort, { once: true })
489
+ try {
490
+ return await Promise.race([work, aborted])
491
+ } finally {
492
+ signal.removeEventListener('abort', abort)
493
+ }
494
+ }
495
+
496
+ function withRequestUrl(response: Response, url: URL, redirected: boolean): Response {
497
+ try {
498
+ Object.defineProperties(response, { url: { value: url.href }, redirected: { value: redirected } })
499
+ } catch {
500
+ // A runtime whose responses refuse own properties keeps its own `url`; the body bound holds either way.
501
+ }
502
+ return response
503
+ }
@@ -35,6 +35,7 @@ export const SERVER_FAULTS = {
35
35
  attachment_size: 'the encoded attachment is larger than it declares (maxBytes); no body was sent',
36
36
  redirect_refused:
37
37
  "the handler redirected to a target that is neither its own origin's path, an origin its redirect() lists, nor a URL a verified token of the request carries",
38
+ schema_unapproved: 'a schema the application evaluated has another shape than its approved contract holds for the endpoint',
38
39
  token_claims_refused: "the claims a site signed are not what the token purpose's claims schema admits",
39
40
  token_keys_missing: 'a site signed a token, and the environment holds no token key',
40
41
  url_unbuildable:
@@ -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
 
@@ -2,6 +2,7 @@
2
2
  // schema then validates what is left, so an undeclared field is dropped rather than leaked or refused.
3
3
 
4
4
  import { z } from 'zod/v4'
5
+ import { type DataSchema, zodSchemaOf } from '../schema/data-schema'
5
6
 
6
7
  /** No branch of a union accepts the value, whatever it is reduced to. */
7
8
  export class ProjectionRefusedError extends Error {
@@ -17,7 +18,8 @@ function isRecord(value: unknown): value is Record<string, unknown> {
17
18
  * in declaration order, whose schema accepts the value reduced to that branch. Anything else is left for
18
19
  * validation.
19
20
  */
20
- export function project(schema: z.core.$ZodType, value: unknown): unknown {
21
+ export function project(declared: z.core.$ZodType | DataSchema, value: unknown): unknown {
22
+ const schema = zodSchemaOf(declared)
21
23
  if (schema instanceof z.core.$ZodObject) {
22
24
  if (!isRecord(value)) {
23
25
  return value
@@ -10,6 +10,7 @@ import { createHmac, timingSafeEqual } from 'node:crypto'
10
10
  import { z } from 'zod/v4'
11
11
  import type { Schema } from '../contract/define'
12
12
  import { BadRequestError } from '../errors'
13
+ import { zodSchemaOf } from '../schema/data-schema'
13
14
  import { CapabilityRefusedError } from './capability'
14
15
  import { ServerFault } from './faults'
15
16
 
@@ -107,7 +108,7 @@ export class SignedTokens {
107
108
  `${site} signed a '${purpose}' token for ${String(days)} days; the purpose allows 1 to ${declared.maxDays}`,
108
109
  )
109
110
  }
110
- const parsed = z.safeParse(declared.claims, claims)
111
+ const parsed = z.safeParse(zodSchemaOf(declared.claims), claims)
111
112
  if (!parsed.success) {
112
113
  throw new ServerFault('token_claims_refused', `${site} signed a '${purpose}' token whose claims its schema refuses`)
113
114
  }
@@ -143,7 +144,7 @@ export class SignedTokens {
143
144
  if (body.x <= Math.floor(this.#now() / 1000)) {
144
145
  throw new BadRequestError('The signed token has expired')
145
146
  }
146
- const claims = z.safeParse(declared.claims, body.c)
147
+ const claims = z.safeParse(zodSchemaOf(declared.claims), body.c)
147
148
  if (!claims.success || !isRecord(claims.data)) {
148
149
  throw invalid()
149
150
  }