@fabrika/app 0.9.0-dev.12 → 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 (48) hide show
  1. package/package.json +9 -9
  2. package/skill/SKILL.md +7 -4
  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 +682 -0
  8. package/skill/references/table-and-migration.md +18 -7
  9. package/skill/references/webhooks-links-connectors.md +2 -1
  10. package/src/bun.ts +10 -0
  11. package/src/contract/artifact-schema.ts +82 -1
  12. package/src/contract/build.ts +142 -12
  13. package/src/contract/compile.ts +1 -0
  14. package/src/contract/declaration.ts +4 -0
  15. package/src/contract/define.ts +12 -0
  16. package/src/contract/group.ts +10 -1
  17. package/src/contract/kit.ts +3 -1
  18. package/src/contract/platform.ts +1 -0
  19. package/src/contract/vocabulary.ts +3 -0
  20. package/src/disk-assets.ts +15 -3
  21. package/src/implement/boot.ts +59 -5
  22. package/src/implement/capability.ts +91 -6
  23. package/src/implement/dispatch.ts +334 -17
  24. package/src/implement/egress.ts +409 -9
  25. package/src/implement/implement.ts +28 -1
  26. package/src/implement/invocation.ts +10 -9
  27. package/src/implement/types.ts +15 -4
  28. package/src/implement/webhook.ts +8 -0
  29. package/src/jobs/runner.ts +7 -2
  30. package/src/source-map-path.ts +21 -0
  31. package/src/testing/caller.ts +20 -2
  32. package/src/testing/membership.ts +9 -5
  33. package/types/src/contract/declaration.d.ts +6 -0
  34. package/types/src/contract/define.d.ts +15 -0
  35. package/types/src/contract/group.d.ts +9 -1
  36. package/types/src/contract/kit.d.ts +2 -2
  37. package/types/src/contract/vocabulary.d.ts +4 -1
  38. package/types/src/implement/boot.d.ts +6 -0
  39. package/types/src/implement/capability.d.ts +14 -5
  40. package/types/src/implement/dispatch.d.ts +20 -1
  41. package/types/src/implement/egress.d.ts +36 -1
  42. package/types/src/implement/implement.d.ts +24 -1
  43. package/types/src/implement/invocation.d.ts +3 -3
  44. package/types/src/implement/types.d.ts +13 -3
  45. package/types/src/jobs/runner.d.ts +3 -0
  46. package/types/src/source-map-path.d.ts +4 -0
  47. package/types/src/testing/caller.d.ts +6 -1
  48. package/types/src/testing/membership.d.ts +1 -1
@@ -60,14 +60,16 @@ import { type ConnectFetch, wireImports } from './connect'
60
60
  import {
61
61
  ContractRuntime,
62
62
  type Facilities,
63
+ type HeldPath,
63
64
  NO_FACILITIES,
64
65
  type ProcedureQuery,
65
66
  proxySecretDigest,
67
+ type RevealedNode,
66
68
  type ServedEndpoint,
67
69
  type ServedSite,
68
70
  type SpaAssets,
69
71
  } from './dispatch'
70
- import { installEgressGuard, platformCall, platformFacility } from './egress'
72
+ import { type HostResolver, installEgressGuard, platformCall, platformFacility, publicEgressRules, type SiteEgress, siteEgress } from './egress'
71
73
  import type { CapturedEnvironment } from './environment'
72
74
  import { FailureReports, type HandlerErrorSink } from './failures'
73
75
  import { applicationPolicy } from './headers'
@@ -131,6 +133,11 @@ export interface BootOptions {
131
133
  * with a job or a webhook does not boot.
132
134
  */
133
135
  readonly workloadTokens?: WorkloadTokenSource
136
+ /**
137
+ * Resolves a host name to its addresses, which the Bun adapter supplies (`node:dns`): a cron job's public egress then
138
+ * refuses a public name of a private address before each hop. A Worker exposes no resolution and passes none.
139
+ */
140
+ readonly resolveHost?: HostResolver
134
141
  /** What posts a report to Operations' ingest; `fetch` by default. */
135
142
  readonly operationsFetch?: (request: Request) => Promise<Response>
136
143
  /** What asks a public procedure's challenge provider to verify a token; `fetch` by default. */
@@ -404,13 +411,18 @@ function contractDatabase(
404
411
  return null
405
412
  }
406
413
  try {
407
- const { locate, release } = bindScopedDatabaseProvisionally(database, {
414
+ const { locate, relates, reveals, holdsThrough, revealsToMembers, release } = bindScopedDatabaseProvisionally(database, {
408
415
  database: connection,
409
416
  capabilities,
410
417
  readOnly: requestIsReadOnly,
411
418
  ...(projectWakes === undefined ? {} : { projectWakes }),
412
419
  })
413
- return { database: { tables: database.tables, locate }, framework: frameworkTablesOf(database), data: dataAccessOf(database), release }
420
+ return {
421
+ database: { tables: database.tables, locate, relates, reveals, holdsThrough, revealsToMembers },
422
+ framework: frameworkTablesOf(database),
423
+ data: dataAccessOf(database),
424
+ release,
425
+ }
414
426
  } catch {
415
427
  problems.push('the data layer was bound before boot; only the framework binds it, so remove @fabrika/db/framework from the application')
416
428
  return null
@@ -460,8 +472,8 @@ function boundHandler(
460
472
  }
461
473
 
462
474
  /** The origins a staged-kit site's handler reaches, a kit without tables included; nothing for a bare handler. */
463
- function egressOf(bound: BoundHandler): { readonly egress?: readonly string[] } {
464
- return !bound.site || bound.declaration === null ? {} : { egress: bound.declaration.egress }
475
+ function egressOf(bound: BoundHandler): { readonly egress?: SiteEgress } {
476
+ return !bound.site || bound.declaration === null ? {} : { egress: siteEgress(bound.declaration.egress, null) }
465
477
  }
466
478
 
467
479
  /** A staged-kit contract's endpoint gets `ctx.links` only for the link mount it declares it `issues`. */
@@ -669,6 +681,43 @@ function bindsOf(
669
681
  return { binds: { name, path: mount.path, scheme: mount.scheme, boundTo: mount.boundTo } }
670
682
  }
671
683
 
684
+ /** Each relation's reveals, from its tables' policies: the ancestor a row it reaches reveals, and for which actions. */
685
+ function revealsOf(artifact: ContractArtifact): ReadonlyMap<string, readonly RevealedNode[]> {
686
+ const reveals = new Map<string, RevealedNode[]>()
687
+ for (const table of Object.values(artifact.tables)) {
688
+ for (const [relation, reveal] of Object.entries(table.reveals ?? {})) {
689
+ reveals.set(relation, [...(reveals.get(relation) ?? []), { dimension: reveal.to, actions: reveal.actions }])
690
+ }
691
+ }
692
+ return reveals
693
+ }
694
+
695
+ /** Each dimension's member reveals, from its table's policy: the ancestor a row reveals to a grant at it, and for which actions. */
696
+ function memberRevealsOf(artifact: ContractArtifact): ReadonlyMap<string, readonly RevealedNode[]> {
697
+ const reveals = new Map<string, RevealedNode[]>()
698
+ for (const table of Object.values(artifact.tables)) {
699
+ for (const [dimension, reveal] of Object.entries(table.memberReveals ?? {})) {
700
+ reveals.set(dimension, [...(reveals.get(dimension) ?? []), { dimension: reveal.to, actions: reveal.actions }])
701
+ }
702
+ }
703
+ return reveals
704
+ }
705
+
706
+ /**
707
+ * Each dimension's secondary paths that hold actions for a Ref, from the policy of the table that owns it: the dimension
708
+ * the path reaches and the actions it holds there (`writeThrough`).
709
+ */
710
+ function pathsOf(artifact: ContractArtifact): ReadonlyMap<string, readonly HeldPath[]> {
711
+ const paths = new Map<string, HeldPath[]>()
712
+ for (const table of Object.values(artifact.tables)) {
713
+ if (table.scope.mode !== 'dimension') continue
714
+ for (const [dimension, actions] of Object.entries(table.writeThrough ?? {})) {
715
+ paths.set(table.scope.dimension, [...(paths.get(table.scope.dimension) ?? []), { dimension, actions }])
716
+ }
717
+ }
718
+ return paths
719
+ }
720
+
672
721
  /** Each approved token purpose with the claims schema the application declared for it. */
673
722
  function runtimePurposes(contract: AnyContract, artifact: ContractArtifact): ReadonlyMap<string, RuntimePurpose> {
674
723
  const declared = contract.surface.tokens ?? {}
@@ -899,6 +948,7 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
899
948
  mail,
900
949
  tokens,
901
950
  url,
951
+ publicEgress: publicEgressRules(options.environment.framework, options.resolveHost ?? null),
902
952
  }, problems)
903
953
  for (const id of jobs.declared) {
904
954
  declared.add(id)
@@ -973,6 +1023,10 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
973
1023
  database,
974
1024
  ownedDimensions: owned,
975
1025
  containers,
1026
+ relations: new Map(Object.entries(artifact.relations ?? {}).map(([name, relation]) => [name, relation.dimension])),
1027
+ reveals: revealsOf(artifact),
1028
+ memberReveals: memberRevealsOf(artifact),
1029
+ paths: pathsOf(artifact),
976
1030
  assets: options.assets ?? null,
977
1031
  membership,
978
1032
  terminals: artifact.terminal === undefined ? null : (terminalRpc ?? null),
@@ -15,6 +15,7 @@ import {
15
15
  MAX_WITHIN_VALUES,
16
16
  type Ref as RefCapability,
17
17
  type RefGrant,
18
+ type RelationHold,
18
19
  type RowGrant,
19
20
  type RowRef as RowRefCapability,
20
21
  type Within as WithinCapability,
@@ -34,7 +35,13 @@ export const CAPABILITY_REFUSALS = {
34
35
  undeclared_binding: 'the site named a webhook it does not declare in binds',
35
36
  undeclared_signs: 'the site signed a token of a purpose it does not declare in signs, or for longer than the purpose allows',
36
37
  undeclared_egress: 'the site called an origin it does not declare in egress',
38
+ refused_egress:
39
+ "the site's public egress refused the host: an IP address, a local or internal name, a non-default port, credentials in the URL, a host of this installation, or a name that resolves to a private address",
40
+ oversized_egress: "a response to the site's public egress was larger than it reads",
41
+ encoded_egress: "a response to the site's public egress came compressed, which it neither asks for nor decodes",
37
42
  wrong_binding: 'a webhook binding was handed a capability of another kind or dimension than the webhook is bound to',
43
+ conditional_binding:
44
+ 'a webhook binding was handed a Ref held through a relation, a member reveal or a secondary path, which a binding would outlive',
38
45
  missing_id: 'the job named an object without an id',
39
46
  wrong_capability: 'an operation was handed a capability of another dimension or action than it needs',
40
47
  } as const
@@ -58,6 +65,9 @@ export class CapabilityLimitError extends Error {
58
65
  override readonly name = 'CapabilityLimitError'
59
66
  }
60
67
 
68
+ /** The caller's grants of `action` in `dimension`, as a `Within` of it would carry them; no values when it holds none. */
69
+ export type Standing = (dimension: string, action: string) => WithinGrant
70
+
61
71
  /**
62
72
  * One request's lifetime, or one job attempt's. A capability minted in it is usable only while it runs, and only
63
73
  * inside it; a job attempt's writes also need its lease (`fence`).
@@ -69,16 +79,24 @@ export class RequestFrame {
69
79
  readonly readOnly: boolean
70
80
  /** The endpoint the request is served by; `ctx.connect` checks it against each import's `usedBy`. */
71
81
  readonly endpoint: string | null
82
+ /** What the request's caller holds of an action in a dimension; none for work without a caller (a job, a webhook). */
83
+ readonly standing: Standing | null
72
84
  #ended = false
73
85
 
74
86
  constructor(
75
87
  id: string,
76
- options: { readonly fence?: LeaseFence | null; readonly readOnly?: boolean; readonly endpoint?: string | null } = {},
88
+ options: {
89
+ readonly fence?: LeaseFence | null
90
+ readonly readOnly?: boolean
91
+ readonly endpoint?: string | null
92
+ readonly standing?: Standing | null
93
+ } = {},
77
94
  ) {
78
95
  this.id = id
79
96
  this.fence = options.fence ?? null
80
97
  this.readOnly = options.readOnly ?? false
81
98
  this.endpoint = options.endpoint ?? null
99
+ this.standing = options.standing ?? null
82
100
  }
83
101
 
84
102
  get ended(): boolean {
@@ -162,12 +180,40 @@ function containerGrantsOf(containers: readonly ContainerGrant[]): readonly Cont
162
180
  return freeze(copy)
163
181
  }
164
182
 
183
+ /** A frozen copy of the relation holds, by index, each node list copied: what was minted stays what was checked. */
184
+ function relationHoldsOf(holds: readonly RelationHold[]): readonly RelationHold[] {
185
+ const copy: RelationHold[] = []
186
+ for (let index = 0; index < holds.length; index++) {
187
+ const hold = holds[index]
188
+ if (hold !== undefined) {
189
+ const inside = hold.inside === null ? null : freeze({ dimension: hold.inside.dimension, values: copyOf(hold.inside.values) })
190
+ copy[copy.length] = freeze({ relation: hold.relation, inside })
191
+ }
192
+ }
193
+ return freeze(copy)
194
+ }
195
+
196
+ /** The nodes the relation holds carry, counted against `MAX_WITHIN_VALUES` beside the grants. */
197
+ function insideCount(holds: readonly RelationHold[]): number {
198
+ let count = 0
199
+ for (let index = 0; index < holds.length; index++) {
200
+ count += holds[index]?.inside?.values.length ?? 0
201
+ }
202
+ return count
203
+ }
204
+
165
205
  interface RefFacts {
166
206
  readonly dimension: string
167
207
  readonly action: string
168
208
  readonly principal: string
169
209
  readonly id: string
170
210
  readonly chain: Chain
211
+ /** The relations through which the caller holds the action on the object; empty for an IAM grant. */
212
+ readonly relations: readonly RelationHold[]
213
+ /** The caller's grants at nodes whose rows reveal the object to their members; empty for an IAM grant. */
214
+ readonly revealing: readonly ContainerGrant[]
215
+ /** The caller's grants at nodes a path of the object's table names, which hold the action through it; empty for an IAM grant. */
216
+ readonly paths: readonly ContainerGrant[]
171
217
  }
172
218
 
173
219
  interface Bound {
@@ -200,13 +246,28 @@ export class Ref<D extends string, A extends string> implements RefCapability<D,
200
246
  principal: string,
201
247
  id: string,
202
248
  chain: ReadonlyMap<string, string>,
249
+ relations: readonly RelationHold[],
250
+ revealing: readonly ContainerGrant[],
251
+ paths: readonly ContainerGrant[],
203
252
  ) {
204
253
  if (token !== MINT) {
205
254
  throw new CapabilityRefusedError('not_minted', 'a Ref is minted by the framework only; declare the access form in fabrika.contract.ts')
206
255
  }
256
+ const revealed = containerGrantsOf(revealing)
257
+ const through = containerGrantsOf(paths)
258
+ const held = relationHoldsOf(relations)
259
+ let count = insideCount(held)
260
+ for (const grant of [...revealed, ...through]) {
261
+ count += grant.values.length
262
+ }
263
+ if (count > MAX_WITHIN_VALUES) {
264
+ throw new CapabilityLimitError(
265
+ `the caller holds '${action}' on this ${dimension} through ${count} revealing or path grants; a Ref carries at most ${MAX_WITHIN_VALUES}`,
266
+ )
267
+ }
207
268
  this.#dimension = dimension
208
269
  this.#action = action
209
- this.#facts = freeze({ dimension, action, principal, id, chain: chainOf(chain) })
270
+ this.#facts = freeze({ dimension, action, principal, id, chain: chainOf(chain), relations: held, revealing: revealed, paths: through })
210
271
  this.#frame = frame
211
272
  this.#issuer = issuer
212
273
  }
@@ -242,6 +303,9 @@ export class Ref<D extends string, A extends string> implements RefCapability<D,
242
303
  principal: facts.principal,
243
304
  id: facts.id,
244
305
  chain: mapOf(facts.chain),
306
+ relations: facts.relations,
307
+ revealing: facts.revealing,
308
+ paths: facts.paths,
245
309
  })
246
310
  return { grant, frame: value.#frame, issuer: value.#issuer }
247
311
  }
@@ -270,14 +334,18 @@ export class Within<D extends string, A extends string> implements WithinCapabil
270
334
  values: readonly string[] | 'all',
271
335
  containers: readonly ContainerGrant[],
272
336
  contained: readonly ContainerGrant[],
337
+ relations: readonly RelationHold[],
338
+ revealing: readonly ContainerGrant[],
273
339
  ) {
274
340
  if (token !== MINT) {
275
341
  throw new CapabilityRefusedError('not_minted', 'a Within is minted by the framework only; declare the access form in fabrika.contract.ts')
276
342
  }
277
343
  const held = values === 'all' ? freeze([]) : containerGrantsOf(containers)
278
344
  const inside = values === 'all' ? freeze([]) : containerGrantsOf(contained)
279
- let count = values === 'all' ? 0 : values.length
280
- for (const group of [held, inside]) {
345
+ const revealed = values === 'all' ? freeze([]) : containerGrantsOf(revealing)
346
+ const holds = values === 'all' ? freeze([]) : relationHoldsOf(relations)
347
+ let count = values === 'all' ? 0 : values.length + insideCount(holds)
348
+ for (const group of [held, inside, revealed]) {
281
349
  for (let index = 0; index < group.length; index++) {
282
350
  count += group[index]?.values.length ?? 0
283
351
  }
@@ -297,6 +365,8 @@ export class Within<D extends string, A extends string> implements WithinCapabil
297
365
  values: values === 'all' ? 'all' : copyOf(values),
298
366
  containers: held,
299
367
  contained: inside,
368
+ relations: holds,
369
+ revealing: revealed,
300
370
  })
301
371
  this.#frame = frame
302
372
  this.#issuer = issuer
@@ -436,6 +506,9 @@ export interface CapabilityMint {
436
506
  principal: string,
437
507
  id: string,
438
508
  chain: ReadonlyMap<string, string>,
509
+ relations?: readonly RelationHold[],
510
+ revealing?: readonly ContainerGrant[],
511
+ paths?: readonly ContainerGrant[],
439
512
  ): Ref<D, A>
440
513
  within<D extends string, A extends string>(
441
514
  frame: RequestFrame,
@@ -445,6 +518,8 @@ export interface CapabilityMint {
445
518
  values: readonly string[] | 'all',
446
519
  containers?: readonly ContainerGrant[],
447
520
  contained?: readonly ContainerGrant[],
521
+ relations?: readonly RelationHold[],
522
+ revealing?: readonly ContainerGrant[],
448
523
  ): Within<D, A>
449
524
  app<A extends string>(frame: RequestFrame, action: A, principal: string): AppCapability<A>
450
525
  }
@@ -470,8 +545,11 @@ export function createCapabilityIssuer(): CapabilityIssuer {
470
545
  principal: string,
471
546
  id: string,
472
547
  chain: ReadonlyMap<string, string>,
548
+ relations: readonly RelationHold[] = [],
549
+ revealing: readonly ContainerGrant[] = [],
550
+ paths: readonly ContainerGrant[] = [],
473
551
  ): Ref<D, A> {
474
- return new Ref(MINT, issuer, frame, dimension, action, principal, id, chain)
552
+ return new Ref(MINT, issuer, frame, dimension, action, principal, id, chain, relations, revealing, paths)
475
553
  },
476
554
  within<D extends string, A extends string>(
477
555
  frame: RequestFrame,
@@ -481,8 +559,10 @@ export function createCapabilityIssuer(): CapabilityIssuer {
481
559
  values: readonly string[] | 'all',
482
560
  containers: readonly ContainerGrant[] = [],
483
561
  contained: readonly ContainerGrant[] = [],
562
+ relations: readonly RelationHold[] = [],
563
+ revealing: readonly ContainerGrant[] = [],
484
564
  ): Within<D, A> {
485
- return new Within(MINT, issuer, frame, dimension, action, principal, values, containers, contained)
565
+ return new Within(MINT, issuer, frame, dimension, action, principal, values, containers, contained, relations, revealing)
486
566
  },
487
567
  app<A extends string>(frame: RequestFrame, action: A, principal: string): AppCapability<A> {
488
568
  return new AppCapability(MINT, issuer, frame, action, principal)
@@ -522,6 +602,11 @@ export function createCapabilityIssuer(): CapabilityIssuer {
522
602
  fence(): LeaseFence | null {
523
603
  return currentRequest.getStore()?.fence ?? null
524
604
  },
605
+
606
+ standing(dimension: string, action: string): WithinGrant | undefined {
607
+ const frame = currentRequest.getStore()
608
+ return frame === undefined || frame.ended ? undefined : frame.standing?.(dimension, action)
609
+ },
525
610
  })
526
611
  return freeze({ mint, authority })
527
612
  }