@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
@@ -0,0 +1,57 @@
1
+ // Validation by the approved shapes: an endpoint validates with the application's own schema (its messages and
2
+ // defaults), once that schema's shape is the one the approved contract holds for the endpoint. Boot checks only the
3
+ // contract's digest, so each endpoint's schemas are read and compared the first time it uses them.
4
+
5
+ import {
6
+ canonicalJson,
7
+ canonicalShape,
8
+ type EndpointRow,
9
+ isAttachmentShape,
10
+ isFileShape,
11
+ isRedirectShape,
12
+ type SchemaShape,
13
+ } from '@fabrika/auth-core'
14
+ import type { Schema } from '../contract/define'
15
+ import { Problems } from '../contract/problems'
16
+ import { describeSchema } from '../contract/schema-shape'
17
+ import { ServerFault } from './faults'
18
+
19
+ type Slot = 'input' | 'output'
20
+
21
+ const approved = new WeakMap<EndpointRow, Map<Slot, Schema>>()
22
+
23
+ /** `schema`, the endpoint's input, once its shape is the row's. */
24
+ export function approvedInput(row: EndpointRow, schema: Schema): Schema {
25
+ return approvedIn(row, 'input', row.input, schema)
26
+ }
27
+
28
+ /**
29
+ * `schema`, the endpoint's JSON output, once its shape is the row's. A redirect's target, an attachment's rows and a
30
+ * file stand in the row in a form of their own, so their schemas are not compared.
31
+ */
32
+ export function approvedOutput(row: EndpointRow, schema: Schema): Schema {
33
+ const output = row.output
34
+ if (output === null || isRedirectShape(output) || isAttachmentShape(output) || isFileShape(output)) {
35
+ return schema
36
+ }
37
+ return approvedIn(row, 'output', output, schema)
38
+ }
39
+
40
+ function approvedIn(row: EndpointRow, slot: Slot, expected: SchemaShape | null, schema: Schema): Schema {
41
+ const checked = approved.get(row)
42
+ if (checked?.get(slot) === schema) {
43
+ return schema
44
+ }
45
+ if (expected === null || !hasShape(schema, expected, `'${row.id}' ${slot}`)) {
46
+ throw new ServerFault('schema_unapproved', `'${row.id}': the ${slot} schema the application evaluated is not the one its approved contract holds`)
47
+ }
48
+ approved.set(row, (checked ?? new Map<Slot, Schema>()).set(slot, schema))
49
+ return schema
50
+ }
51
+
52
+ /** Whether `schema` reads to the canonical shape `expected`; a schema outside the subset never does. */
53
+ export function hasShape(schema: Schema, expected: SchemaShape, where: string): boolean {
54
+ const problems = new Problems()
55
+ const actual = describeSchema(schema, where, problems)
56
+ return actual !== null && problems.isEmpty() && canonicalJson(canonicalShape(actual)) === canonicalJson(canonicalShape(expected))
57
+ }
@@ -9,6 +9,7 @@ import { attachmentOf } from '../contract/attachment'
9
9
  import { ATTACHMENT_LIMITS, CSV_CONTENT_TYPE, XLSX_CONTENT_TYPE } from '../contract/defaults'
10
10
  import type { Schema } from '../contract/define'
11
11
  import { contentDisposition } from '../files/treatment'
12
+ import { zodSchemaOf } from '../schema/data-schema'
12
13
  import { ServerFault } from './faults'
13
14
  import { project, ProjectionRefusedError } from './project'
14
15
  import { encodeXlsx } from './xlsx'
@@ -58,7 +59,7 @@ function validRow(endpoint: string, schema: Schema, row: unknown): unknown {
58
59
  }
59
60
  throw error
60
61
  }
61
- const parsed = z.safeParse(schema, projected)
62
+ const parsed = z.safeParse(zodSchemaOf(schema), projected)
62
63
  if (!parsed.success) {
63
64
  throw new ServerFault('output_refused', `'${endpoint}' returned a row its row schema refuses`)
64
65
  }
@@ -1,9 +1,11 @@
1
1
  // `boot(app, { environment, iam })`: called once, by the generated entrypoint through its runtime adapter, after the
2
- // adapter captured the framework's variables and scrubbed them from the process. It compiles the contract, binds
3
- // every handler to its endpoint and refuses to start when anything declared cannot be served.
2
+ // adapter captured the framework's variables and scrubbed them from the process. It reads the approved contract (the
3
+ // artifact the build compiled, or compiles it), binds every handler to its endpoint and refuses to start when anything
4
+ // declared cannot be served.
4
5
 
5
6
  import { IamMembership } from '@fabrika/auth'
6
7
  import {
8
+ canonicalArtifactDigest,
7
9
  compileEndpointTable,
8
10
  type ContractArtifact,
9
11
  contractDigest,
@@ -38,6 +40,7 @@ import type { EmailProviderRegistry } from '@fabrika/email'
38
40
  import { builtinEmailProviders } from '@fabrika/email/providers'
39
41
  import { TokenVerifier } from '@fabrika/jwks'
40
42
  import type { FileObjectStore } from '@fabrika/platform'
43
+ import { parseEncodedArtifact } from '../contract/artifact-schema'
41
44
  import { compileContract } from '../contract/compile'
42
45
  import { exportDescription } from '../contract/connect'
43
46
  import { containersOf } from '../contract/containers'
@@ -53,6 +56,7 @@ import { type MailStandIn, resolveMailTransports } from '../jobs/mail'
53
56
  import { logReporter, type OperationsReporter, operationsReporter, operationsSettings, type ReportSource } from '../jobs/report'
54
57
  import { bindJobs, type ContractJobs } from '../jobs/runner'
55
58
  import { environmentScrubber } from '../jobs/scrub'
59
+ import { hasShape } from './approved'
56
60
  import { browserConfigs } from './browser-config'
57
61
  import { createCapabilityIssuer, requestIsReadOnly } from './capability'
58
62
  import type { ChallengeFetch, ChallengeWork } from './challenge'
@@ -60,6 +64,7 @@ import { type ConnectFetch, wireImports } from './connect'
60
64
  import {
61
65
  ContractRuntime,
62
66
  type Facilities,
67
+ type HeldPath,
63
68
  NO_FACILITIES,
64
69
  type ProcedureQuery,
65
70
  proxySecretDigest,
@@ -68,7 +73,7 @@ import {
68
73
  type ServedSite,
69
74
  type SpaAssets,
70
75
  } from './dispatch'
71
- import { installEgressGuard, platformCall, platformFacility } from './egress'
76
+ import { type HostResolver, installEgressGuard, platformCall, platformFacility, publicEgressRules, type SiteEgress, siteEgress } from './egress'
72
77
  import type { CapturedEnvironment } from './environment'
73
78
  import { FailureReports, type HandlerErrorSink } from './failures'
74
79
  import { applicationPolicy } from './headers'
@@ -90,6 +95,12 @@ export interface BootOptions {
90
95
  /** The variables `captureEnvironment` took before the application's modules loaded. */
91
96
  readonly environment: CapturedEnvironment
92
97
  readonly iam: IamKeySource
98
+ /**
99
+ * The contract artifact the build compiled, as the text of its shared encoding (`fabrika/contract.generated.ts`). Boot
100
+ * decodes it, checks its digest against `FABRIKA_CONTRACT_DIGEST` and reads it instead of compiling the contract;
101
+ * without it, boot compiles.
102
+ */
103
+ readonly approvedContract?: string
93
104
  /** Serves the SPA mounts. Without it, a contract that declares one does not boot. */
94
105
  readonly assets?: SpaAssets
95
106
  /** The application's Postgres connection, which the Bun adapter opens. Without it, an application on `@fabrika/db` does not boot. */
@@ -132,6 +143,11 @@ export interface BootOptions {
132
143
  * with a job or a webhook does not boot.
133
144
  */
134
145
  readonly workloadTokens?: WorkloadTokenSource
146
+ /**
147
+ * Resolves a host name to its addresses, which the Bun adapter supplies (`node:dns`): a cron job's public egress then
148
+ * refuses a public name of a private address before each hop. A Worker exposes no resolution and passes none.
149
+ */
150
+ readonly resolveHost?: HostResolver
135
151
  /** What posts a report to Operations' ingest; `fetch` by default. */
136
152
  readonly operationsFetch?: (request: Request) => Promise<Response>
137
153
  /** What asks a public procedure's challenge provider to verify a token; `fetch` by default. */
@@ -243,10 +259,38 @@ function readFramework(framework: Readonly<Record<string, string>>, contractApp:
243
259
  return { iamAppId, issuer: issuer ?? '', operationsOrigin }
244
260
  }
245
261
 
262
+ /** The contract compiled from the evaluated one, which must be the approved one. */
263
+ function compiledArtifact(app: ContractImplementation, framework: Readonly<Record<string, string>>, problems: string[]): ContractArtifact {
264
+ const artifact = compileContract(app.contract, app.database?.tables ?? {})
265
+ checkContractDigest(framework, contractDigest(artifact), problems)
266
+ return artifact
267
+ }
268
+
269
+ /**
270
+ * The artifact the build compiled, decoded from its shared encoding. Decoding yields the canonical artifact with each
271
+ * shared shape one object, and its digest is taken as it is serialized, so neither the expanded artifact nor its text
272
+ * is ever built.
273
+ */
274
+ function approvedArtifact(text: string, framework: Readonly<Record<string, string>>, problems: string[]): ContractArtifact {
275
+ let json: unknown
276
+ try {
277
+ json = JSON.parse(text)
278
+ } catch {
279
+ throw new BootError([...problems, 'the bundled contract is not JSON; rebuild the application with `fabrika app build`'])
280
+ }
281
+ let artifact: ContractArtifact
282
+ try {
283
+ artifact = parseEncodedArtifact(json)
284
+ } catch {
285
+ throw new BootError([...problems, 'the bundled contract is not an encoded contract artifact; rebuild the application with `fabrika app build`'])
286
+ }
287
+ checkContractDigest(framework, canonicalArtifactDigest(artifact), problems)
288
+ return artifact
289
+ }
290
+
246
291
  /** The deploy was approved with one contract; this build must be that contract, or it does not start (ADR-0022 rule 5). */
247
- function checkContractDigest(framework: Readonly<Record<string, string>>, artifact: ContractArtifact, problems: string[]): void {
292
+ function checkContractDigest(framework: Readonly<Record<string, string>>, actual: string, problems: string[]): void {
248
293
  const expected = framework[FABRIKA_CONTRACT_DIGEST]?.trim() ?? ''
249
- const actual = contractDigest(artifact)
250
294
  if (expected === '') {
251
295
  problems.push(`${FABRIKA_CONTRACT_DIGEST} is not set; it is the digest of the contract the deploy was approved with`)
252
296
  } else if (expected !== actual) {
@@ -405,14 +449,14 @@ function contractDatabase(
405
449
  return null
406
450
  }
407
451
  try {
408
- const { locate, relates, reveals, release } = bindScopedDatabaseProvisionally(database, {
452
+ const { locate, relates, reveals, holdsThrough, revealsToMembers, release } = bindScopedDatabaseProvisionally(database, {
409
453
  database: connection,
410
454
  capabilities,
411
455
  readOnly: requestIsReadOnly,
412
456
  ...(projectWakes === undefined ? {} : { projectWakes }),
413
457
  })
414
458
  return {
415
- database: { tables: database.tables, locate, relates, reveals },
459
+ database: { tables: database.tables, locate, relates, reveals, holdsThrough, revealsToMembers },
416
460
  framework: frameworkTablesOf(database),
417
461
  data: dataAccessOf(database),
418
462
  release,
@@ -466,8 +510,8 @@ function boundHandler(
466
510
  }
467
511
 
468
512
  /** The origins a staged-kit site's handler reaches, a kit without tables included; nothing for a bare handler. */
469
- function egressOf(bound: BoundHandler): { readonly egress?: readonly string[] } {
470
- return !bound.site || bound.declaration === null ? {} : { egress: bound.declaration.egress }
513
+ function egressOf(bound: BoundHandler): { readonly egress?: SiteEgress } {
514
+ return !bound.site || bound.declaration === null ? {} : { egress: siteEgress(bound.declaration.egress, null) }
471
515
  }
472
516
 
473
517
  /** A staged-kit contract's endpoint gets `ctx.links` only for the link mount it declares it `issues`. */
@@ -697,19 +741,52 @@ function memberRevealsOf(artifact: ContractArtifact): ReadonlyMap<string, readon
697
741
  return reveals
698
742
  }
699
743
 
744
+ /**
745
+ * Each dimension's secondary paths that hold actions for a Ref, from the policy of the table that owns it: the dimension
746
+ * the path reaches and the actions it holds there (`writeThrough`).
747
+ */
748
+ function pathsOf(artifact: ContractArtifact): ReadonlyMap<string, readonly HeldPath[]> {
749
+ const paths = new Map<string, HeldPath[]>()
750
+ for (const table of Object.values(artifact.tables)) {
751
+ if (table.scope.mode !== 'dimension') continue
752
+ for (const [dimension, actions] of Object.entries(table.writeThrough ?? {})) {
753
+ paths.set(table.scope.dimension, [...(paths.get(table.scope.dimension) ?? []), { dimension, actions }])
754
+ }
755
+ }
756
+ return paths
757
+ }
758
+
700
759
  /** Each approved token purpose with the claims schema the application declared for it. */
701
- function runtimePurposes(contract: AnyContract, artifact: ContractArtifact): ReadonlyMap<string, RuntimePurpose> {
760
+ function runtimePurposes(contract: AnyContract, artifact: ContractArtifact, problems: string[]): ReadonlyMap<string, RuntimePurpose> {
702
761
  const declared = contract.surface.tokens ?? {}
703
762
  const purposes = new Map<string, RuntimePurpose>()
704
763
  for (const [purpose, approved] of Object.entries(artifact.tokens ?? {})) {
705
764
  const own = Object.hasOwn(declared, purpose) ? declared[purpose] : undefined
706
- if (own !== undefined) {
707
- purposes.set(purpose, { claims: own.claims, maxDays: approved.maxDays })
765
+ if (own === undefined) {
766
+ continue
708
767
  }
768
+ if (!hasShape(own.claims, approved.claims, `token '${purpose}' claims`)) {
769
+ problems.push(unapproved(`token '${purpose}'`, 'claims schema'))
770
+ }
771
+ purposes.set(purpose, { claims: own.claims, maxDays: approved.maxDays })
709
772
  }
710
773
  return purposes
711
774
  }
712
775
 
776
+ /**
777
+ * A fact the evaluated contract states again, which differs from the approved artifact. Boot reads the artifact the build
778
+ * compiled, so it compares what it still takes from the evaluated contract instead of compiling it.
779
+ */
780
+ function unapproved(where: string, fact: string): string {
781
+ return `${where}: its ${fact} is not the approved one; this build is not the contract the deploy was approved with`
782
+ }
783
+
784
+ /** Whether two action lists hold the same actions, in any order. */
785
+ function sameActions(left: readonly string[], right: readonly string[]): boolean {
786
+ const sorted = [...right].sort()
787
+ return left.length === right.length && [...left].sort().every((action, index) => action === sorted[index])
788
+ }
789
+
713
790
  export function boot(app: ContractImplementation, options: BootOptions): ContractApp {
714
791
  const binding: Binding = { release: null }
715
792
  try {
@@ -735,10 +812,11 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
735
812
  const terminalRpc = options.terminals === undefined ? undefined : platformFacility(options.terminals)
736
813
  const workloadTokens = options.workloadTokens === undefined ? undefined : platformFacility(options.workloadTokens)
737
814
  const variables = readFramework(options.environment.framework, app.contract.vocabulary.app, problems)
738
- const artifact = compileContract(app.contract, app.database?.tables ?? {})
739
- checkContractDigest(options.environment.framework, artifact, problems)
815
+ const artifact = options.approvedContract === undefined
816
+ ? compiledArtifact(app, options.environment.framework, problems)
817
+ : approvedArtifact(options.approvedContract, options.environment.framework, problems)
740
818
  const proxySecret = readProxySecret(options.environment.framework, options.requireProxySecret === true, problems)
741
- const tokens = new SignedTokens(runtimePurposes(app.contract, artifact), readTokenKeys(options.environment.framework, artifact, problems))
819
+ const tokens = new SignedTokens(runtimePurposes(app.contract, artifact, problems), readTokenKeys(options.environment.framework, artifact, problems))
742
820
  const origin = readAppOrigin(options.environment.framework, problems)
743
821
  const url = appUrl(artifact, origin)
744
822
  const operations = operationsSettings(options.environment.framework, problems)
@@ -813,6 +891,10 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
813
891
  endpoints.set(name, { kind: 'health', row })
814
892
  }
815
893
  } else if (mount.kind === 'spa') {
894
+ const approvedSpa = artifact.mounts[name]
895
+ if (approvedSpa?.kind !== 'spa' || approvedSpa.prefix !== mount.prefix || approvedSpa.dir !== mount.dir) {
896
+ problems.push(unapproved(`mount '${name}'`, 'prefix or directory'))
897
+ }
816
898
  const row = rows.get(name)
817
899
  const config = configs.get(name)
818
900
  if (config !== undefined && isCredentialed(row)) {
@@ -825,7 +907,14 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
825
907
  endpoints.set(bare.id, { kind: 'spa-prefix', row: bare, prefix: mount.prefix })
826
908
  }
827
909
  } else if (mount.kind === 'rpc' || mount.kind === 'link') {
910
+ const approvedMount = artifact.mounts[name]
911
+ if (approvedMount?.kind !== mount.kind || approvedMount.prefix !== mount.prefix) {
912
+ problems.push(unapproved(`mount '${name}'`, 'kind or prefix'))
913
+ }
828
914
  if (mount.kind === 'link') {
915
+ if (approvedMount?.kind === 'link' && approvedMount.spa !== mount.spa) {
916
+ problems.push(unapproved(`mount '${name}'`, 'directory'))
917
+ }
829
918
  const row = rows.get(name)
830
919
  if (row !== undefined) {
831
920
  endpoints.set(name, { kind: 'link-spa', row, prefix: mount.prefix, dir: mount.spa })
@@ -834,6 +923,14 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
834
923
  for (const { id, path, procedure } of declaredProcedures(name, mount.procedures)) {
835
924
  declared.add(id)
836
925
  const row = rows.get(id)
926
+ if (isCredentialed(row)) {
927
+ if (row.kind !== procedure.type) {
928
+ problems.push(unapproved(`procedure '${id}'`, `kind (${procedure.type})`))
929
+ }
930
+ if ((procedure.input === null) !== (row.input === null) || (procedure.output === null) !== (row.output === null)) {
931
+ problems.push(unapproved(`procedure '${id}'`, 'input or output'))
932
+ }
933
+ }
837
934
  const bound = boundHandler(path.reduce<unknown>(childAt, handlers), id, `procedure '${id}'`, procedure.type, artifact, problems)
838
935
  if (row?.kind === 'public') {
839
936
  const served = publicEndpoint(row, procedure, bound, artifact, workloads, options, problems)
@@ -875,7 +972,9 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
875
972
  const approved = artifact.mounts[name]
876
973
  if (row === undefined || bound === null) {
877
974
  problems.push(`webhook '${name}' has no handler; add handlers.${name}: ({ input, ctx }) => …`)
878
- } else if (credential !== undefined && approved?.kind === 'webhook') {
975
+ } else if (approved?.kind !== 'webhook' || !sameActions(approved.actions, mount.actions)) {
976
+ problems.push(unapproved(`webhook '${name}'`, 'actions'))
977
+ } else if (credential !== undefined) {
879
978
  endpoints.set(name, {
880
979
  kind: 'webhook',
881
980
  row,
@@ -883,7 +982,7 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
883
982
  scheme: approved.scheme,
884
983
  boundTo: approved.boundTo,
885
984
  timeoutMs: approved.timeoutMs,
886
- actions: mount.actions,
985
+ actions: approved.actions,
887
986
  input: mount.input,
888
987
  handler: bound.handler,
889
988
  credential,
@@ -927,6 +1026,7 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
927
1026
  mail,
928
1027
  tokens,
929
1028
  url,
1029
+ publicEgress: publicEgressRules(options.environment.framework, options.resolveHost ?? null),
930
1030
  }, problems)
931
1031
  for (const id of jobs.declared) {
932
1032
  declared.add(id)
@@ -1004,6 +1104,7 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
1004
1104
  relations: new Map(Object.entries(artifact.relations ?? {}).map(([name, relation]) => [name, relation.dimension])),
1005
1105
  reveals: revealsOf(artifact),
1006
1106
  memberReveals: memberRevealsOf(artifact),
1107
+ paths: pathsOf(artifact),
1007
1108
  assets: options.assets ?? null,
1008
1109
  membership,
1009
1110
  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,6 +180,28 @@ 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
@@ -169,7 +209,11 @@ interface RefFacts {
169
209
  readonly id: string
170
210
  readonly chain: Chain
171
211
  /** The relations through which the caller holds the action on the object; empty for an IAM grant. */
172
- readonly relations: readonly string[]
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[]
173
217
  }
174
218
 
175
219
  interface Bound {
@@ -202,14 +246,28 @@ export class Ref<D extends string, A extends string> implements RefCapability<D,
202
246
  principal: string,
203
247
  id: string,
204
248
  chain: ReadonlyMap<string, string>,
205
- relations: readonly string[],
249
+ relations: readonly RelationHold[],
250
+ revealing: readonly ContainerGrant[],
251
+ paths: readonly ContainerGrant[],
206
252
  ) {
207
253
  if (token !== MINT) {
208
254
  throw new CapabilityRefusedError('not_minted', 'a Ref is minted by the framework only; declare the access form in fabrika.contract.ts')
209
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
+ }
210
268
  this.#dimension = dimension
211
269
  this.#action = action
212
- this.#facts = freeze({ dimension, action, principal, id, chain: chainOf(chain), relations: copyOf(relations) })
270
+ this.#facts = freeze({ dimension, action, principal, id, chain: chainOf(chain), relations: held, revealing: revealed, paths: through })
213
271
  this.#frame = frame
214
272
  this.#issuer = issuer
215
273
  }
@@ -246,6 +304,8 @@ export class Ref<D extends string, A extends string> implements RefCapability<D,
246
304
  id: facts.id,
247
305
  chain: mapOf(facts.chain),
248
306
  relations: facts.relations,
307
+ revealing: facts.revealing,
308
+ paths: facts.paths,
249
309
  })
250
310
  return { grant, frame: value.#frame, issuer: value.#issuer }
251
311
  }
@@ -274,7 +334,7 @@ export class Within<D extends string, A extends string> implements WithinCapabil
274
334
  values: readonly string[] | 'all',
275
335
  containers: readonly ContainerGrant[],
276
336
  contained: readonly ContainerGrant[],
277
- relations: readonly string[],
337
+ relations: readonly RelationHold[],
278
338
  revealing: readonly ContainerGrant[],
279
339
  ) {
280
340
  if (token !== MINT) {
@@ -283,7 +343,8 @@ export class Within<D extends string, A extends string> implements WithinCapabil
283
343
  const held = values === 'all' ? freeze([]) : containerGrantsOf(containers)
284
344
  const inside = values === 'all' ? freeze([]) : containerGrantsOf(contained)
285
345
  const revealed = values === 'all' ? freeze([]) : containerGrantsOf(revealing)
286
- let count = values === 'all' ? 0 : values.length
346
+ const holds = values === 'all' ? freeze([]) : relationHoldsOf(relations)
347
+ let count = values === 'all' ? 0 : values.length + insideCount(holds)
287
348
  for (const group of [held, inside, revealed]) {
288
349
  for (let index = 0; index < group.length; index++) {
289
350
  count += group[index]?.values.length ?? 0
@@ -304,7 +365,7 @@ export class Within<D extends string, A extends string> implements WithinCapabil
304
365
  values: values === 'all' ? 'all' : copyOf(values),
305
366
  containers: held,
306
367
  contained: inside,
307
- relations: values === 'all' ? freeze([]) : copyOf(relations),
368
+ relations: holds,
308
369
  revealing: revealed,
309
370
  })
310
371
  this.#frame = frame
@@ -445,7 +506,9 @@ export interface CapabilityMint {
445
506
  principal: string,
446
507
  id: string,
447
508
  chain: ReadonlyMap<string, string>,
448
- relations?: readonly string[],
509
+ relations?: readonly RelationHold[],
510
+ revealing?: readonly ContainerGrant[],
511
+ paths?: readonly ContainerGrant[],
449
512
  ): Ref<D, A>
450
513
  within<D extends string, A extends string>(
451
514
  frame: RequestFrame,
@@ -455,7 +518,7 @@ export interface CapabilityMint {
455
518
  values: readonly string[] | 'all',
456
519
  containers?: readonly ContainerGrant[],
457
520
  contained?: readonly ContainerGrant[],
458
- relations?: readonly string[],
521
+ relations?: readonly RelationHold[],
459
522
  revealing?: readonly ContainerGrant[],
460
523
  ): Within<D, A>
461
524
  app<A extends string>(frame: RequestFrame, action: A, principal: string): AppCapability<A>
@@ -482,9 +545,11 @@ export function createCapabilityIssuer(): CapabilityIssuer {
482
545
  principal: string,
483
546
  id: string,
484
547
  chain: ReadonlyMap<string, string>,
485
- relations: readonly string[] = [],
548
+ relations: readonly RelationHold[] = [],
549
+ revealing: readonly ContainerGrant[] = [],
550
+ paths: readonly ContainerGrant[] = [],
486
551
  ): Ref<D, A> {
487
- return new Ref(MINT, issuer, frame, dimension, action, principal, id, chain, relations)
552
+ return new Ref(MINT, issuer, frame, dimension, action, principal, id, chain, relations, revealing, paths)
488
553
  },
489
554
  within<D extends string, A extends string>(
490
555
  frame: RequestFrame,
@@ -494,7 +559,7 @@ export function createCapabilityIssuer(): CapabilityIssuer {
494
559
  values: readonly string[] | 'all',
495
560
  containers: readonly ContainerGrant[] = [],
496
561
  contained: readonly ContainerGrant[] = [],
497
- relations: readonly string[] = [],
562
+ relations: readonly RelationHold[] = [],
498
563
  revealing: readonly ContainerGrant[] = [],
499
564
  ): Within<D, A> {
500
565
  return new Within(MINT, issuer, frame, dimension, action, principal, values, containers, contained, relations, revealing)
@@ -537,6 +602,11 @@ export function createCapabilityIssuer(): CapabilityIssuer {
537
602
  fence(): LeaseFence | null {
538
603
  return currentRequest.getStore()?.fence ?? null
539
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
+ },
540
610
  })
541
611
  return freeze({ mint, authority })
542
612
  }