@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
@@ -23,6 +23,7 @@ import {
23
23
  type LinkTokenClaims,
24
24
  matchAction,
25
25
  parseEndpointHeader,
26
+ parseRelationInside,
26
27
  type PermissionEntry,
27
28
  permits,
28
29
  planEndpoint,
@@ -30,6 +31,7 @@ import {
30
31
  PROXY_TOKEN_HEADER,
31
32
  rawRequestTarget,
32
33
  type RedirectShape,
34
+ RELATION_INSIDE_SCOPE_TYPE,
33
35
  RELATION_SCOPE_TYPE,
34
36
  sameOriginTarget,
35
37
  satisfies,
@@ -40,7 +42,7 @@ import {
40
42
  type WebhookScheme,
41
43
  } from '@fabrika/auth-core'
42
44
  import { DatabaseError } from '@fabrika/db'
43
- import { type CapabilityAuthority, type ContainerGrant, MAX_WITHIN_VALUES } from '@fabrika/db/capability'
45
+ import { type CapabilityAuthority, type ContainerGrant, MAX_WITHIN_VALUES, type RelationHold, type WithinGrant } from '@fabrika/db/capability'
44
46
  import type { DataAccess, FileBinding, FrameworkTables } from '@fabrika/db/framework'
45
47
  import type { DataKind } from '@fabrika/db/tables'
46
48
  import type { TokenVerifier } from '@fabrika/jwks'
@@ -74,7 +76,10 @@ import {
74
76
  import type { RequestExecutionContext } from '../fetch'
75
77
  import { FileWork, type StoredFileKinds, storedFilesHandle } from '../files/kinds'
76
78
  import { FileDownload, fileResponse, withFileTreatment } from '../files/treatment'
79
+ import { zodSchemaOf } from '../schema/data-schema'
80
+ import { namesSourceMap } from '../source-map-path'
77
81
  import { abortedBody, bootstrapPath, bootstrapResponse, readBodyInTime, withBootstrap } from './anonymous'
82
+ import { approvedInput, approvedOutput } from './approved'
78
83
  import { attachmentResponse } from './attachment'
79
84
  import { boundedStream, type Deadline, deadline, handlerSignal, readBoundedBytes } from './bounded'
80
85
  import type { BrowserConfig } from './browser-config'
@@ -90,7 +95,7 @@ import {
90
95
  } from './capability'
91
96
  import type { ChallengeIssuer, ChallengeVerifier } from './challenge'
92
97
  import { connectContext, type ImportWire } from './connect'
93
- import { runAsSite } from './egress'
98
+ import { runAsSite, type SiteEgress, siteEgress } from './egress'
94
99
  import type { FailureReports } from './failures'
95
100
  import { ServerFault } from './faults'
96
101
  import { type HeaderPolicy, withHeaderPolicy } from './headers'
@@ -157,8 +162,6 @@ export interface InvocationGate {
157
162
 
158
163
  const invocationGate = new AsyncLocalStorage<InvocationGate>()
159
164
 
160
- const UNGATED: InvocationAdmission = Object.freeze({ signal: new AbortController().signal, track: () => {}, release: () => {} })
161
-
162
165
  /** Runs `work` with `gate` admitting every invocation it starts, the background work it hands on included. */
163
166
  export function runGated<T>(gate: InvocationGate, work: () => T): T {
164
167
  return invocationGate.run(gate, work)
@@ -167,7 +170,11 @@ export function runGated<T>(gate: InvocationGate, work: () => T): T {
167
170
  /** Admits an invocation of `kind` at the current event's gate; outside an object every invocation is admitted, uncounted. */
168
171
  export function admitInvocation(kind: InvocationKind): InvocationAdmission | null {
169
172
  const gate = invocationGate.getStore()
170
- return gate === undefined ? UNGATED : gate.admit(kind)
173
+ if (gate !== undefined) {
174
+ return gate.admit(kind)
175
+ }
176
+ // One per call: workerd refuses an `AbortController` at a module's top level and ties a signal to its request.
177
+ return Object.freeze({ signal: new AbortController().signal, track: () => {}, release: () => {} })
171
178
  }
172
179
 
173
180
  /** How long a refused caller waits before it tries again, in seconds. */
@@ -253,7 +260,7 @@ export type ServedEndpoint =
253
260
  /** A staged-kit site, which gets `ctx.db`; a handler `implement` bound has none. */
254
261
  readonly site?: ServedSite
255
262
  /** The origins a staged-kit site's `fetch` reaches while its handler runs; absent for a handler `implement` bound. */
256
- readonly egress?: readonly string[]
263
+ readonly egress?: SiteEgress
257
264
  /** Its buckets and time limit; without them (a generated endpoint) no bucket and the request budget. */
258
265
  readonly admission?: ProcedureAdmission
259
266
  /** A POST's `query`, parsed from the URL beside the body: its schema and its shape. */
@@ -316,6 +323,33 @@ export interface RevealedNode {
316
323
  readonly actions: readonly string[]
317
324
  }
318
325
 
326
+ /** The relations and grants a Ref is held through by a secondary path. */
327
+ interface HeldThrough {
328
+ readonly relations: readonly RelationHold[]
329
+ readonly paths: readonly ContainerGrant[]
330
+ }
331
+
332
+ const NONE_THROUGH: HeldThrough = Object.freeze({ relations: Object.freeze([]), paths: Object.freeze([]) })
333
+
334
+ /** `first` and `second` without a hold twice: the relations a Ref carries. */
335
+ function holdsOf(first: readonly RelationHold[], second: readonly RelationHold[]): RelationHold[] {
336
+ const seen = new Set<string>()
337
+ const holds: RelationHold[] = []
338
+ for (const hold of [...first, ...second]) {
339
+ const key = JSON.stringify([hold.relation, hold.inside?.dimension ?? null, hold.inside?.values ?? null])
340
+ if (seen.has(key)) continue
341
+ seen.add(key)
342
+ holds.push(hold)
343
+ }
344
+ return holds
345
+ }
346
+
347
+ /** A secondary path of a dimension's table: the dimension it reaches, and the actions a Ref holds through it. */
348
+ export interface HeldPath {
349
+ readonly dimension: string
350
+ readonly actions: readonly string[]
351
+ }
352
+
319
353
  export interface RuntimeParts {
320
354
  readonly table: CompiledEndpointTable
321
355
  readonly endpoints: ReadonlyMap<string, ServedEndpoint>
@@ -338,6 +372,8 @@ export interface RuntimeParts {
338
372
  readonly reveals: ReadonlyMap<string, readonly RevealedNode[]>
339
373
  /** Each dimension's member reveals: a grant of one of their actions at its node also reads under the ancestor they reveal. */
340
374
  readonly memberReveals: ReadonlyMap<string, readonly RevealedNode[]>
375
+ /** Each dimension's secondary paths that hold actions for a Ref: a grant of one at the node a path names reaches the object. */
376
+ readonly paths: ReadonlyMap<string, readonly HeldPath[]>
341
377
  readonly assets: SpaAssets | null
342
378
  /** IAM's membership operations; `boot` refuses a contract that needs them when the adapter supplies none. */
343
379
  readonly membership: IamMembership | null
@@ -543,9 +579,12 @@ export class ContractRuntime {
543
579
  return await this.#asset(served, request)
544
580
  }
545
581
 
546
- /** A file of the mount's directory. A source map goes to Operations at build and is never served: it holds the source. */
582
+ /**
583
+ * A file of the mount's directory. A source map goes to Operations at build and is never served: it holds the source.
584
+ * The check reads the path as the asset servers resolve it (`namesSourceMap`), so no spelling of one reaches them.
585
+ */
547
586
  async #asset(served: { readonly prefix: string; readonly dir: string }, request: Request): Promise<Response> {
548
- if (rawRequestTarget(request.url).pathname.endsWith('.map')) {
587
+ if (namesSourceMap(rawRequestTarget(request.url).pathname)) {
549
588
  throw new NotFoundError('A source map is not served')
550
589
  }
551
590
  return await this.#assets().serve({ prefix: served.prefix, dir: served.dir }, request)
@@ -665,7 +704,11 @@ export class ContractRuntime {
665
704
  const carried = new Set<string>()
666
705
  const fields = this.#parts.tokens.verifyFields(served.row.input, body.multipart === null ? body.input : body.multipart.json, carried)
667
706
  const query = this.#verifiedQuery(served.row, served.query, request, carried)
668
- const frame = new RequestFrame(crypto.randomUUID(), { readOnly: served.readOnly === true, endpoint: served.row.id })
707
+ const frame = new RequestFrame(crypto.randomUUID(), {
708
+ readOnly: served.readOnly === true,
709
+ endpoint: served.row.id,
710
+ standing: (dimension, action) => this.#standing(caller, action, dimension),
711
+ })
669
712
  const work = new FileWork(frame, frame.id)
670
713
  const site = served.site
671
714
  const invocation = site === undefined ? null : new Invocation(frame, this.#data(), site.kind === 'query' || served.readOnly === true)
@@ -754,7 +797,7 @@ export class ContractRuntime {
754
797
  if (served.input === null) {
755
798
  throw new ServerFault('contract_inconsistent', `'${served.row.id}' takes files and declares no input`)
756
799
  }
757
- return strictInput(served.row, served.input, { ...multipart.json, ...files })
800
+ return strictInput(served.row, approvedInput(served.row, served.input), { ...multipart.json, ...files })
758
801
  }
759
802
 
760
803
  /**
@@ -776,7 +819,7 @@ export class ContractRuntime {
776
819
  if (file !== null) {
777
820
  return attachmentResponse(served.row.id, file, served.output, result)
778
821
  }
779
- return outputResponse(served.row, served.output, result, request, carried)
822
+ return outputResponse(served.row, approvedOutput(served.row, served.output), result, request, carried)
780
823
  }
781
824
 
782
825
  /** A POST's `query`, parsed from the URL, each signed token in it verified; `undefined` without one. */
@@ -956,8 +999,12 @@ export class ContractRuntime {
956
999
  /** A scope value the caller acts in: without a grant on it or on a container of it, 403 whether it exists or not. */
957
1000
  async #inRef(caller: Caller, action: string, dimension: string, value: string, frame: RequestFrame): Promise<Ref<string, string>> {
958
1001
  const direct = permits(caller.perms, action, { type: dimension, value })
959
- const candidates = this.#heldRelations(caller.perms, action, [dimension, ...(this.#parts.containers.get(dimension) ?? [])])
960
- if (!direct && this.#heldContainers(caller.perms, action, dimension).length === 0 && candidates.length === 0) {
1002
+ const dimensions = [dimension, ...(this.#parts.containers.get(dimension) ?? [])]
1003
+ const candidates = this.#heldRelations(caller.perms, action, dimensions)
1004
+ const revealing = this.#heldRevealing(caller.perms, action, dimensions)
1005
+ const through = this.#throughCandidates(caller.perms, action, dimension)
1006
+ const none = candidates.length === 0 && revealing.length === 0 && through.relations.length === 0 && through.paths.length === 0
1007
+ if (!direct && this.#heldContainers(caller.perms, action, dimension).length === 0 && none) {
961
1008
  throw new ForbiddenError(`The caller does not hold '${action}' in this ${dimension}`)
962
1009
  }
963
1010
  const chain = await this.#chain(dimension, value)
@@ -967,11 +1014,17 @@ export class ContractRuntime {
967
1014
  }
968
1015
  return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain)
969
1016
  }
970
- const related = chain === null ? [] : await this.#relatedOn(caller.subject, candidates, action, dimension, value, chain)
971
- if (chain === null || related.length === 0) {
1017
+ if (chain === null) {
1018
+ throw new ForbiddenError(`The caller does not hold '${action}' in this ${dimension}`)
1019
+ }
1020
+ const related = await this.#relatedOn(caller.subject, this.#atObject(candidates, dimension, chain), action, dimension, value, chain)
1021
+ const revealed = await this.#revealedOn(revealing, action, dimension, value, chain)
1022
+ const asked = { relations: this.#atObject(through.relations, dimension, chain), paths: through.paths }
1023
+ const paths = await this.#heldThrough(caller.subject, asked, action, dimension, value)
1024
+ if (related.length === 0 && revealed.length === 0 && paths.relations.length === 0 && paths.paths.length === 0) {
972
1025
  throw new ForbiddenError(`The caller does not hold '${action}' in this ${dimension}`)
973
1026
  }
974
- return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain, related)
1027
+ return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain, holdsOf(related, paths.relations), revealed, paths.paths)
975
1028
  }
976
1029
 
977
1030
  /** An object the caller acts on; one it may not act on is indistinguishable from a missing one. */
@@ -983,30 +1036,186 @@ export class ContractRuntime {
983
1036
  if (holdsOnChain(caller.perms, action, dimension, value, chain)) {
984
1037
  return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain)
985
1038
  }
986
- const candidates = this.#heldRelations(caller.perms, action, [dimension, ...chain.keys()])
1039
+ const dimensions = [dimension, ...chain.keys()]
1040
+ const candidates = this.#atObject(this.#heldRelations(caller.perms, action, dimensions), dimension, chain)
987
1041
  const related = await this.#relatedOn(caller.subject, candidates, action, dimension, value, chain)
988
- if (related.length === 0) {
1042
+ const revealed = await this.#revealedOn(this.#heldRevealing(caller.perms, action, dimensions), action, dimension, value, chain)
1043
+ const through = this.#throughCandidates(caller.perms, action, dimension)
1044
+ const asked = { relations: this.#atObject(through.relations, dimension, chain), paths: through.paths }
1045
+ const paths = await this.#heldThrough(caller.subject, asked, action, dimension, value)
1046
+ if (related.length === 0 && revealed.length === 0 && paths.relations.length === 0 && paths.paths.length === 0) {
989
1047
  throw new NotFoundError('Not found')
990
1048
  }
991
- return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain, related)
1049
+ return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain, holdsOf(related, paths.relations), revealed, paths.paths)
992
1050
  }
993
1051
 
994
1052
  /**
995
- * The relations through which the caller holds `action` at a node of one of `dimensions` (a `~rel` entry, which IAM
996
- * gives a global grant of a role with `via`), at the relation's own dimension or at an ancestor a reveal of `action`
997
- * names. An entry of a relation the contract does not declare counts for none.
1053
+ * The caller's relations and grants of `action` at the nodes the secondary paths of `dimension`'s table reach, where a
1054
+ * path holds the action for a Ref (`writeThrough`), at the path's dimension or a container of it: what a Ref held
1055
+ * through a path may carry, before the database says which reach the object.
998
1056
  */
999
- #heldRelations(perms: PermissionEntry[], action: string, dimensions: readonly string[]): string[] {
1000
- const held: string[] = []
1057
+ #throughCandidates(perms: PermissionEntry[], action: string, dimension: string): HeldThrough {
1058
+ const dimensions: string[] = []
1059
+ for (const path of this.#parts.paths.get(dimension) ?? []) {
1060
+ if (!path.actions.includes(action)) continue
1061
+ for (const at of [path.dimension, ...(this.#parts.containers.get(path.dimension) ?? [])]) {
1062
+ if (!dimensions.includes(at)) dimensions.push(at)
1063
+ }
1064
+ }
1065
+ if (dimensions.length === 0) {
1066
+ return NONE_THROUGH
1067
+ }
1068
+ const paths = dimensions.flatMap((at) => {
1069
+ const values = scopedValues(perms, action, at) ?? []
1070
+ return values.length === 0 ? [] : [{ dimension: at, values }]
1071
+ })
1072
+ return { relations: this.#heldRelations(perms, action, dimensions), paths }
1073
+ }
1074
+
1075
+ /**
1076
+ * Of `candidates`, those that reach the object `value` of `dimension` through a path holding `action`, or through a
1077
+ * relation held inside a node, now; such a relation comes back narrowed to the node the database matched. The grants
1078
+ * and the nodes go to the database in batches of at most `MAX_WITHIN_VALUES` values, as one statement binds them; the
1079
+ * relations held anywhere with the first.
1080
+ */
1081
+ async #heldThrough(principal: string, candidates: HeldThrough, action: string, dimension: string, value: string): Promise<HeldThrough> {
1082
+ const check = this.#parts.database?.holdsThrough
1083
+ if (check === undefined || (candidates.relations.length === 0 && candidates.paths.length === 0)) {
1084
+ return NONE_THROUGH
1085
+ }
1086
+ const batches: { relations: RelationHold[]; paths: ContainerGrant[]; size: number }[] = [{ relations: [], paths: [], size: 0 }]
1087
+ const add = (values: readonly string[], put: (batch: { relations: RelationHold[]; paths: ContainerGrant[] }, chunk: string[]) => void) => {
1088
+ for (let start = 0; start < values.length; start += MAX_WITHIN_VALUES) {
1089
+ const chunk = values.slice(start, start + MAX_WITHIN_VALUES)
1090
+ let batch = batches[batches.length - 1] ?? { relations: [], paths: [], size: 0 }
1091
+ if (batch.size + chunk.length > MAX_WITHIN_VALUES) {
1092
+ batch = { relations: [], paths: [], size: 0 }
1093
+ batches.push(batch)
1094
+ }
1095
+ put(batch, chunk)
1096
+ batch.size += chunk.length
1097
+ }
1098
+ }
1099
+ for (const hold of candidates.relations) {
1100
+ const inside = hold.inside
1101
+ if (inside === null) {
1102
+ batches[0]?.relations.push(hold)
1103
+ continue
1104
+ }
1105
+ add(inside.values, (batch, chunk) => batch.relations.push({ relation: hold.relation, inside: { dimension: inside.dimension, values: chunk } }))
1106
+ }
1107
+ for (const grant of candidates.paths) {
1108
+ add(grant.values, (batch, chunk) => batch.paths.push({ dimension: grant.dimension, values: chunk }))
1109
+ }
1110
+ let relations: RelationHold[] = []
1111
+ const paths = new Map<string, Set<string>>()
1112
+ for (const batch of batches) {
1113
+ if (batch.relations.length === 0 && batch.paths.length === 0) continue
1114
+ const held = await check(dimension, value, action, principal, batch.relations, batch.paths)
1115
+ relations = holdsOf(relations, held.relations)
1116
+ for (const grant of held.paths) {
1117
+ const values = paths.get(grant.dimension) ?? new Set<string>()
1118
+ for (const at of grant.values) values.add(at)
1119
+ paths.set(grant.dimension, values)
1120
+ }
1121
+ }
1122
+ return { relations, paths: [...paths].map(([at, values]) => ({ dimension: at, values: [...values] })) }
1123
+ }
1124
+
1125
+ /**
1126
+ * What the caller holds of `action` in `dimension`, as a `Within` of it would carry it, without the grants inside it:
1127
+ * the standing an insert that hands out access through a path judges its writer by; empty when it holds none.
1128
+ */
1129
+ #standing(caller: Caller, action: string, dimension: string): WithinGrant {
1130
+ const dimensions = [dimension, ...(this.#parts.containers.get(dimension) ?? [])]
1131
+ const containers = this.#heldContainers(caller.perms, action, dimension)
1132
+ const relations = this.#heldRelations(caller.perms, action, dimensions)
1133
+ const revealing = this.#heldRevealing(caller.perms, action, dimensions)
1134
+ const values = scopedValues(caller.perms, action, dimension) ?? 'all'
1135
+ return { kind: 'within', dimension, action, principal: caller.subject, values, containers, contained: [], relations, revealing }
1136
+ }
1137
+
1138
+ /**
1139
+ * Of `revealing`, the caller's grants of `action` at nodes of revealing dimensions, those whose row reveals the object
1140
+ * or a container on its chain to its members for `action`, now: what a Ref held through member reveals carries.
1141
+ */
1142
+ async #revealedOn(
1143
+ revealing: readonly ContainerGrant[],
1144
+ action: string,
1145
+ dimension: string,
1146
+ value: string,
1147
+ chain: ReadonlyMap<string, string>,
1148
+ ): Promise<ContainerGrant[]> {
1149
+ const check = this.#parts.database?.revealsToMembers
1150
+ if (check === undefined || revealing.length === 0) {
1151
+ return []
1152
+ }
1153
+ const nodeOf = (at: string) => (at === dimension ? value : chain.get(at))
1154
+ const held: ContainerGrant[] = []
1155
+ for (const grant of revealing) {
1156
+ const found = new Set<string>()
1157
+ for (const reveal of this.#parts.memberReveals.get(grant.dimension) ?? []) {
1158
+ const node = reveal.actions.includes(action) ? nodeOf(reveal.dimension) : undefined
1159
+ for (let start = 0; node !== undefined && start < grant.values.length; start += MAX_WITHIN_VALUES) {
1160
+ for (const at of await check(grant.dimension, grant.values.slice(start, start + MAX_WITHIN_VALUES), reveal.dimension, node, action)) {
1161
+ found.add(at)
1162
+ }
1163
+ }
1164
+ }
1165
+ if (found.size > 0) held.push({ dimension: grant.dimension, values: [...found] })
1166
+ }
1167
+ return held
1168
+ }
1169
+
1170
+ /**
1171
+ * The relations through which the caller holds `action` at a node of one of `dimensions`, at the relation's own
1172
+ * dimension or at an ancestor a reveal of `action` names: a `~rel` entry (a global grant of a role with `via`) holds it
1173
+ * anywhere, a `~relin` entry (a scoped grant of one) only inside its node, so only where the relation's dimension and
1174
+ * the reveal's are the node's dimension or lie inside it. The nodes of one relation and dimension are one hold; a
1175
+ * relation held anywhere needs none. An entry of a relation the contract does not declare counts for none.
1176
+ */
1177
+ #heldRelations(perms: PermissionEntry[], action: string, dimensions: readonly string[]): RelationHold[] {
1178
+ const anywhere: string[] = []
1179
+ const inside = new Map<string, { relation: string; dimension: string; values: string[] }>()
1001
1180
  for (const entry of perms) {
1002
1181
  const scope = entry.scope
1003
- if (scope === null || scope.type !== RELATION_SCOPE_TYPE || !matchAction(entry.action, action)) continue
1004
- const relation = scope.value
1005
- const at = this.#parts.relations.get(relation)
1006
- const revealed = this.#revealed(relation, action).some((dimension) => dimensions.includes(dimension))
1007
- if (at !== undefined && (dimensions.includes(at) || revealed) && !held.includes(relation)) held.push(relation)
1182
+ if (scope === null || !matchAction(entry.action, action)) continue
1183
+ if (scope.type === RELATION_SCOPE_TYPE) {
1184
+ if (this.#relationReaches(scope.value, action, dimensions, null) && !anywhere.includes(scope.value)) anywhere.push(scope.value)
1185
+ continue
1186
+ }
1187
+ const held = scope.type === RELATION_INSIDE_SCOPE_TYPE ? parseRelationInside(scope) : null
1188
+ if (held === null || !this.#relationReaches(held.relation, action, dimensions, held.dimension)) continue
1189
+ const key = JSON.stringify([held.relation, held.dimension])
1190
+ const hold = inside.get(key) ?? { relation: held.relation, dimension: held.dimension, values: [] }
1191
+ if (!hold.values.includes(held.node)) hold.values.push(held.node)
1192
+ inside.set(key, hold)
1008
1193
  }
1009
- return held
1194
+ const holds: RelationHold[] = anywhere.map((relation) => ({ relation, inside: null }))
1195
+ for (const hold of inside.values()) {
1196
+ if (!anywhere.includes(hold.relation)) holds.push({ relation: hold.relation, inside: { dimension: hold.dimension, values: hold.values } })
1197
+ }
1198
+ return holds
1199
+ }
1200
+
1201
+ /**
1202
+ * Whether `relation` holds `action` at a node of one of `dimensions`: at its own dimension, or at an ancestor a reveal
1203
+ * of `action` names. Held inside a node of `within`, only where that dimension is `within` or lies inside it.
1204
+ */
1205
+ #relationReaches(relation: string, action: string, dimensions: readonly string[], within: string | null): boolean {
1206
+ const at = this.#parts.relations.get(relation)
1207
+ const lies = (dimension: string) => within === null || dimension === within || (this.#parts.containers.get(dimension) ?? []).includes(within)
1208
+ if (at === undefined || !lies(at)) return false
1209
+ return dimensions.includes(at) || this.#revealed(relation, action).some((dimension) => dimensions.includes(dimension) && lies(dimension))
1210
+ }
1211
+
1212
+ /**
1213
+ * Of `holds`, those that may reach an object of `dimension` whose chain is `chain`: every one held anywhere, and one
1214
+ * held inside nodes only where its dimension is the object's or lies on its chain. Its nodes stay as held: the database
1215
+ * compares the object's column with them (`holdsThrough`), as a `Within` of them would, never this process.
1216
+ */
1217
+ #atObject(holds: readonly RelationHold[], dimension: string, chain: ReadonlyMap<string, string>): RelationHold[] {
1218
+ return holds.filter((hold) => hold.inside === null || hold.inside.dimension === dimension || chain.has(hold.inside.dimension))
1010
1219
  }
1011
1220
 
1012
1221
  /** The ancestor dimensions a reveal of `relation` holds `action` at. */
@@ -1016,38 +1225,49 @@ export class ContractRuntime {
1016
1225
 
1017
1226
  /**
1018
1227
  * Of `candidates`, the relations a row of which names the caller at the object or at a container on its chain, or
1019
- * reaches a row that reveals one of them for `action`, now.
1228
+ * reaches a row that reveals one of them for `action`, now. One held inside a node is judged by the database on the
1229
+ * object's row (`holdsThrough`), which compares its column for the node's dimension too; a dimension no table owns
1230
+ * has no such row, so there it holds nothing.
1020
1231
  */
1021
1232
  async #relatedOn(
1022
1233
  principal: string,
1023
- candidates: readonly string[],
1234
+ candidates: readonly RelationHold[],
1024
1235
  action: string,
1025
1236
  dimension: string,
1026
1237
  value: string,
1027
1238
  chain: ReadonlyMap<string, string>,
1028
- ): Promise<string[]> {
1239
+ ): Promise<RelationHold[]> {
1029
1240
  const relates = this.#parts.database?.relates
1030
1241
  const reveals = this.#parts.database?.reveals
1031
1242
  if (relates === undefined) {
1032
1243
  return []
1033
1244
  }
1034
1245
  const nodeOf = (at: string | undefined) => (at === dimension ? value : at === undefined ? undefined : chain.get(at))
1035
- const related: string[] = []
1036
- for (const relation of candidates) {
1246
+ const related: RelationHold[] = []
1247
+ const inside: RelationHold[] = []
1248
+ for (const hold of candidates) {
1249
+ if (hold.inside !== null) {
1250
+ inside.push(hold)
1251
+ continue
1252
+ }
1253
+ const relation = hold.relation
1037
1254
  const node = nodeOf(this.#parts.relations.get(relation))
1038
1255
  if (node !== undefined && (await relates(relation, node, principal))) {
1039
- related.push(relation)
1256
+ related.push(hold)
1040
1257
  continue
1041
1258
  }
1042
1259
  if (reveals === undefined) continue
1043
1260
  for (const revealed of this.#revealed(relation, action)) {
1044
1261
  const at = nodeOf(revealed)
1045
- if (at !== undefined && (await reveals(relation, revealed, at, principal))) {
1046
- related.push(relation)
1262
+ if (at !== undefined && (await reveals(relation, revealed, at, principal, action))) {
1263
+ related.push(hold)
1047
1264
  break
1048
1265
  }
1049
1266
  }
1050
1267
  }
1268
+ if (inside.length > 0 && this.#parts.ownedDimensions.has(dimension)) {
1269
+ related.push(...(await this.#heldThrough(principal, { relations: inside, paths: [] }, action, dimension, value)).relations)
1270
+ }
1051
1271
  return related
1052
1272
  }
1053
1273
 
@@ -1310,7 +1530,7 @@ export class ContractRuntime {
1310
1530
  kick: kicks.kick,
1311
1531
  })
1312
1532
  const args = { input, ctx, ...(query === undefined ? {} : { query }) }
1313
- return await runAsSite(`'${served.row.id}'`, served.site.declaration.egress, async () => await served.handler(args))
1533
+ return await runAsSite(`'${served.row.id}'`, siteEgress(served.site.declaration.egress, null), async () => await served.handler(args))
1314
1534
  })
1315
1535
  } finally {
1316
1536
  frame.end()
@@ -1319,7 +1539,7 @@ export class ContractRuntime {
1319
1539
  const output = served.row.output
1320
1540
  const answer = output !== null && isFileShape(output)
1321
1541
  ? await this.#fileKinds(served.row.id).download(work, served.row.id, output.kind, result)
1322
- : outputResponse(served.row, served.output, result, request, carried)
1542
+ : outputResponse(served.row, approvedOutput(served.row, served.output), result, request, carried)
1323
1543
  outcome = 'committing'
1324
1544
  await commitAnswer(invocation, signal, answer)
1325
1545
  return answer
@@ -1386,7 +1606,7 @@ export class ContractRuntime {
1386
1606
  if (served.scheme === 'github-sha256' && !githubAccounts(payload).includes(binding.account)) {
1387
1607
  throw new ForbiddenError('The delivery names another account than its binding accepts')
1388
1608
  }
1389
- const input = strictInput(served.row, served.input, stripped(served, payload))
1609
+ const input = strictInput(served.row, approvedInput(served.row, served.input), stripped(served, payload))
1390
1610
  const bound = served.boundTo.kind === 'app' ? APP_BINDING_SCOPE.type : served.boundTo.dimension
1391
1611
  if (binding.scope.type !== bound) {
1392
1612
  throw new ServerFault(
@@ -1464,7 +1684,7 @@ export class ContractRuntime {
1464
1684
  if (site === undefined) {
1465
1685
  await served.handler(args)
1466
1686
  } else {
1467
- await runAsSite(`webhook '${served.webhook}'`, site.egress, async () => await served.handler(args))
1687
+ await runAsSite(`webhook '${served.webhook}'`, siteEgress(site.egress, null), async () => await served.handler(args))
1468
1688
  }
1469
1689
  })
1470
1690
  } finally {
@@ -1606,7 +1826,7 @@ function holdsOnChain(perms: PermissionEntry[], action: string, dimension: strin
1606
1826
  * request's verified tokens carry: a URL among them is a target the application signed.
1607
1827
  */
1608
1828
  function outputResponse(row: EndpointRow, schema: Schema, result: unknown, request: Request, carried: ReadonlySet<string>): Response {
1609
- const output = z.safeParse(schema, projectSchema(row.id, schema, result))
1829
+ const output = z.safeParse(zodSchemaOf(schema), projectSchema(row.id, schema, result))
1610
1830
  if (!output.success) {
1611
1831
  throw new ServerFault('output_refused', `'${row.id}' returned a value its output schema refuses`)
1612
1832
  }
@@ -1729,7 +1949,7 @@ function stripped(served: Extract<ServedEndpoint, { kind: 'webhook' }>, payload:
1729
1949
 
1730
1950
  /** `value` parsed with the endpoint's strict input schema; a refusal is a 400 naming each issue. */
1731
1951
  function strictInput(row: EndpointRow, schema: Schema, value: unknown): Readonly<Record<string, unknown>> {
1732
- const parsed = z.safeParse(schema, value)
1952
+ const parsed = z.safeParse(zodSchemaOf(schema), value)
1733
1953
  if (!parsed.success) {
1734
1954
  const issues = parsed.error.issues.map((issue) => ({ path: issue.path.map(String).join('.'), code: issue.code, message: issue.message }))
1735
1955
  const first = issues[0]
@@ -1809,7 +2029,7 @@ async function readInput(
1809
2029
  }
1810
2030
  return {}
1811
2031
  }
1812
- return strictInput(served.row, served.input, body)
2032
+ return strictInput(served.row, approvedInput(served.row, served.input), body)
1813
2033
  }
1814
2034
 
1815
2035
  /**