@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
@@ -21,7 +21,9 @@ import {
21
21
  isFileShape,
22
22
  isRedirectShape,
23
23
  type LinkTokenClaims,
24
+ matchAction,
24
25
  parseEndpointHeader,
26
+ parseRelationInside,
25
27
  type PermissionEntry,
26
28
  permits,
27
29
  planEndpoint,
@@ -29,6 +31,8 @@ import {
29
31
  PROXY_TOKEN_HEADER,
30
32
  rawRequestTarget,
31
33
  type RedirectShape,
34
+ RELATION_INSIDE_SCOPE_TYPE,
35
+ RELATION_SCOPE_TYPE,
32
36
  sameOriginTarget,
33
37
  satisfies,
34
38
  type SchemaShape,
@@ -38,7 +42,7 @@ import {
38
42
  type WebhookScheme,
39
43
  } from '@fabrika/auth-core'
40
44
  import { DatabaseError } from '@fabrika/db'
41
- 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'
42
46
  import type { DataAccess, FileBinding, FrameworkTables } from '@fabrika/db/framework'
43
47
  import type { DataKind } from '@fabrika/db/tables'
44
48
  import type { TokenVerifier } from '@fabrika/jwks'
@@ -72,6 +76,7 @@ import {
72
76
  import type { RequestExecutionContext } from '../fetch'
73
77
  import { FileWork, type StoredFileKinds, storedFilesHandle } from '../files/kinds'
74
78
  import { FileDownload, fileResponse, withFileTreatment } from '../files/treatment'
79
+ import { namesSourceMap } from '../source-map-path'
75
80
  import { abortedBody, bootstrapPath, bootstrapResponse, readBodyInTime, withBootstrap } from './anonymous'
76
81
  import { attachmentResponse } from './attachment'
77
82
  import { boundedStream, type Deadline, deadline, handlerSignal, readBoundedBytes } from './bounded'
@@ -88,7 +93,7 @@ import {
88
93
  } from './capability'
89
94
  import type { ChallengeIssuer, ChallengeVerifier } from './challenge'
90
95
  import { connectContext, type ImportWire } from './connect'
91
- import { runAsSite } from './egress'
96
+ import { runAsSite, type SiteEgress, siteEgress } from './egress'
92
97
  import type { FailureReports } from './failures'
93
98
  import { ServerFault } from './faults'
94
99
  import { type HeaderPolicy, withHeaderPolicy } from './headers'
@@ -251,7 +256,7 @@ export type ServedEndpoint =
251
256
  /** A staged-kit site, which gets `ctx.db`; a handler `implement` bound has none. */
252
257
  readonly site?: ServedSite
253
258
  /** The origins a staged-kit site's `fetch` reaches while its handler runs; absent for a handler `implement` bound. */
254
- readonly egress?: readonly string[]
259
+ readonly egress?: SiteEgress
255
260
  /** Its buckets and time limit; without them (a generated endpoint) no bucket and the request budget. */
256
261
  readonly admission?: ProcedureAdmission
257
262
  /** A POST's `query`, parsed from the URL beside the body: its schema and its shape. */
@@ -308,6 +313,39 @@ export interface ProcedureQuery {
308
313
  readonly shape: SchemaShape
309
314
  }
310
315
 
316
+ /** A relation's reveal: a row it reaches reveals its node in `dimension` for `actions`. */
317
+ export interface RevealedNode {
318
+ readonly dimension: string
319
+ readonly actions: readonly string[]
320
+ }
321
+
322
+ /** The relations and grants a Ref is held through by a secondary path. */
323
+ interface HeldThrough {
324
+ readonly relations: readonly RelationHold[]
325
+ readonly paths: readonly ContainerGrant[]
326
+ }
327
+
328
+ const NONE_THROUGH: HeldThrough = Object.freeze({ relations: Object.freeze([]), paths: Object.freeze([]) })
329
+
330
+ /** `first` and `second` without a hold twice: the relations a Ref carries. */
331
+ function holdsOf(first: readonly RelationHold[], second: readonly RelationHold[]): RelationHold[] {
332
+ const seen = new Set<string>()
333
+ const holds: RelationHold[] = []
334
+ for (const hold of [...first, ...second]) {
335
+ const key = JSON.stringify([hold.relation, hold.inside?.dimension ?? null, hold.inside?.values ?? null])
336
+ if (seen.has(key)) continue
337
+ seen.add(key)
338
+ holds.push(hold)
339
+ }
340
+ return holds
341
+ }
342
+
343
+ /** A secondary path of a dimension's table: the dimension it reaches, and the actions a Ref holds through it. */
344
+ export interface HeldPath {
345
+ readonly dimension: string
346
+ readonly actions: readonly string[]
347
+ }
348
+
311
349
  export interface RuntimeParts {
312
350
  readonly table: CompiledEndpointTable
313
351
  readonly endpoints: ReadonlyMap<string, ServedEndpoint>
@@ -324,6 +362,14 @@ export interface RuntimeParts {
324
362
  readonly ownedDimensions: ReadonlySet<string>
325
363
  /** Each dimension's containers, nearest first; a grant on one reaches every value inside it. */
326
364
  readonly containers: ReadonlyMap<string, readonly string[]>
365
+ /** Each relation of the contract with its dimension: a `~rel` entry holds its action at that dimension's nodes. */
366
+ readonly relations: ReadonlyMap<string, string>
367
+ /** Each relation's reveals: a `~rel` entry of one of their actions also holds it at the ancestor nodes they reveal. */
368
+ readonly reveals: ReadonlyMap<string, readonly RevealedNode[]>
369
+ /** Each dimension's member reveals: a grant of one of their actions at its node also reads under the ancestor they reveal. */
370
+ readonly memberReveals: ReadonlyMap<string, readonly RevealedNode[]>
371
+ /** Each dimension's secondary paths that hold actions for a Ref: a grant of one at the node a path names reaches the object. */
372
+ readonly paths: ReadonlyMap<string, readonly HeldPath[]>
327
373
  readonly assets: SpaAssets | null
328
374
  /** IAM's membership operations; `boot` refuses a contract that needs them when the adapter supplies none. */
329
375
  readonly membership: IamMembership | null
@@ -529,9 +575,12 @@ export class ContractRuntime {
529
575
  return await this.#asset(served, request)
530
576
  }
531
577
 
532
- /** A file of the mount's directory. A source map goes to Operations at build and is never served: it holds the source. */
578
+ /**
579
+ * A file of the mount's directory. A source map goes to Operations at build and is never served: it holds the source.
580
+ * The check reads the path as the asset servers resolve it (`namesSourceMap`), so no spelling of one reaches them.
581
+ */
533
582
  async #asset(served: { readonly prefix: string; readonly dir: string }, request: Request): Promise<Response> {
534
- if (rawRequestTarget(request.url).pathname.endsWith('.map')) {
583
+ if (namesSourceMap(rawRequestTarget(request.url).pathname)) {
535
584
  throw new NotFoundError('A source map is not served')
536
585
  }
537
586
  return await this.#assets().serve({ prefix: served.prefix, dir: served.dir }, request)
@@ -651,7 +700,11 @@ export class ContractRuntime {
651
700
  const carried = new Set<string>()
652
701
  const fields = this.#parts.tokens.verifyFields(served.row.input, body.multipart === null ? body.input : body.multipart.json, carried)
653
702
  const query = this.#verifiedQuery(served.row, served.query, request, carried)
654
- const frame = new RequestFrame(crypto.randomUUID(), { readOnly: served.readOnly === true, endpoint: served.row.id })
703
+ const frame = new RequestFrame(crypto.randomUUID(), {
704
+ readOnly: served.readOnly === true,
705
+ endpoint: served.row.id,
706
+ standing: (dimension, action) => this.#standing(caller, action, dimension),
707
+ })
655
708
  const work = new FileWork(frame, frame.id)
656
709
  const site = served.site
657
710
  const invocation = site === undefined ? null : new Invocation(frame, this.#data(), site.kind === 'query' || served.readOnly === true)
@@ -931,35 +984,287 @@ export class ContractRuntime {
931
984
  }
932
985
  const held = this.#heldContainers(caller.perms, action, dimension)
933
986
  const inside = this.#heldContained(caller.perms, action, dimension)
934
- if (direct.length === 0 && held.length === 0 && inside.length === 0) {
987
+ const related = this.#heldRelations(caller.perms, action, [dimension, ...(this.#parts.containers.get(dimension) ?? [])])
988
+ const revealing = this.#heldRevealing(caller.perms, action, [dimension, ...(this.#parts.containers.get(dimension) ?? [])])
989
+ if (direct.length === 0 && held.length === 0 && inside.length === 0 && related.length === 0 && revealing.length === 0) {
935
990
  throw new ForbiddenError(`The caller holds '${action}' in no ${dimension}`)
936
991
  }
937
- return this.#parts.mint.within(frame, dimension, action, caller.subject, direct, held, inside)
992
+ return this.#parts.mint.within(frame, dimension, action, caller.subject, direct, held, inside, related, revealing)
938
993
  }
939
994
 
940
995
  /** A scope value the caller acts in: without a grant on it or on a container of it, 403 whether it exists or not. */
941
996
  async #inRef(caller: Caller, action: string, dimension: string, value: string, frame: RequestFrame): Promise<Ref<string, string>> {
942
997
  const direct = permits(caller.perms, action, { type: dimension, value })
943
- if (!direct && this.#heldContainers(caller.perms, action, dimension).length === 0) {
998
+ const dimensions = [dimension, ...(this.#parts.containers.get(dimension) ?? [])]
999
+ const candidates = this.#heldRelations(caller.perms, action, dimensions)
1000
+ const revealing = this.#heldRevealing(caller.perms, action, dimensions)
1001
+ const through = this.#throughCandidates(caller.perms, action, dimension)
1002
+ const none = candidates.length === 0 && revealing.length === 0 && through.relations.length === 0 && through.paths.length === 0
1003
+ if (!direct && this.#heldContainers(caller.perms, action, dimension).length === 0 && none) {
944
1004
  throw new ForbiddenError(`The caller does not hold '${action}' in this ${dimension}`)
945
1005
  }
946
1006
  const chain = await this.#chain(dimension, value)
947
- if (!holdsOnChain(caller.perms, action, dimension, value, chain ?? new Map())) {
948
- throw new ForbiddenError(`The caller does not hold '${action}' in this ${dimension}`)
1007
+ if (holdsOnChain(caller.perms, action, dimension, value, chain ?? new Map())) {
1008
+ if (chain === null) {
1009
+ throw new NotFoundError('Not found')
1010
+ }
1011
+ return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain)
949
1012
  }
950
1013
  if (chain === null) {
951
- throw new NotFoundError('Not found')
1014
+ throw new ForbiddenError(`The caller does not hold '${action}' in this ${dimension}`)
952
1015
  }
953
- return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain)
1016
+ const related = await this.#relatedOn(caller.subject, this.#atObject(candidates, dimension, chain), action, dimension, value, chain)
1017
+ const revealed = await this.#revealedOn(revealing, action, dimension, value, chain)
1018
+ const asked = { relations: this.#atObject(through.relations, dimension, chain), paths: through.paths }
1019
+ const paths = await this.#heldThrough(caller.subject, asked, action, dimension, value)
1020
+ if (related.length === 0 && revealed.length === 0 && paths.relations.length === 0 && paths.paths.length === 0) {
1021
+ throw new ForbiddenError(`The caller does not hold '${action}' in this ${dimension}`)
1022
+ }
1023
+ return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain, holdsOf(related, paths.relations), revealed, paths.paths)
954
1024
  }
955
1025
 
956
1026
  /** An object the caller acts on; one it may not act on is indistinguishable from a missing one. */
957
1027
  async #onRef(caller: Caller, action: string, dimension: string, value: string, frame: RequestFrame): Promise<Ref<string, string>> {
958
1028
  const chain = await this.#chain(dimension, value)
959
- if (chain === null || !holdsOnChain(caller.perms, action, dimension, value, chain)) {
1029
+ if (chain === null) {
960
1030
  throw new NotFoundError('Not found')
961
1031
  }
962
- return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain)
1032
+ if (holdsOnChain(caller.perms, action, dimension, value, chain)) {
1033
+ return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain)
1034
+ }
1035
+ const dimensions = [dimension, ...chain.keys()]
1036
+ const candidates = this.#atObject(this.#heldRelations(caller.perms, action, dimensions), dimension, chain)
1037
+ const related = await this.#relatedOn(caller.subject, candidates, action, dimension, value, chain)
1038
+ const revealed = await this.#revealedOn(this.#heldRevealing(caller.perms, action, dimensions), action, dimension, value, chain)
1039
+ const through = this.#throughCandidates(caller.perms, action, dimension)
1040
+ const asked = { relations: this.#atObject(through.relations, dimension, chain), paths: through.paths }
1041
+ const paths = await this.#heldThrough(caller.subject, asked, action, dimension, value)
1042
+ if (related.length === 0 && revealed.length === 0 && paths.relations.length === 0 && paths.paths.length === 0) {
1043
+ throw new NotFoundError('Not found')
1044
+ }
1045
+ return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain, holdsOf(related, paths.relations), revealed, paths.paths)
1046
+ }
1047
+
1048
+ /**
1049
+ * The caller's relations and grants of `action` at the nodes the secondary paths of `dimension`'s table reach, where a
1050
+ * path holds the action for a Ref (`writeThrough`), at the path's dimension or a container of it: what a Ref held
1051
+ * through a path may carry, before the database says which reach the object.
1052
+ */
1053
+ #throughCandidates(perms: PermissionEntry[], action: string, dimension: string): HeldThrough {
1054
+ const dimensions: string[] = []
1055
+ for (const path of this.#parts.paths.get(dimension) ?? []) {
1056
+ if (!path.actions.includes(action)) continue
1057
+ for (const at of [path.dimension, ...(this.#parts.containers.get(path.dimension) ?? [])]) {
1058
+ if (!dimensions.includes(at)) dimensions.push(at)
1059
+ }
1060
+ }
1061
+ if (dimensions.length === 0) {
1062
+ return NONE_THROUGH
1063
+ }
1064
+ const paths = dimensions.flatMap((at) => {
1065
+ const values = scopedValues(perms, action, at) ?? []
1066
+ return values.length === 0 ? [] : [{ dimension: at, values }]
1067
+ })
1068
+ return { relations: this.#heldRelations(perms, action, dimensions), paths }
1069
+ }
1070
+
1071
+ /**
1072
+ * Of `candidates`, those that reach the object `value` of `dimension` through a path holding `action`, or through a
1073
+ * relation held inside a node, now; such a relation comes back narrowed to the node the database matched. The grants
1074
+ * and the nodes go to the database in batches of at most `MAX_WITHIN_VALUES` values, as one statement binds them; the
1075
+ * relations held anywhere with the first.
1076
+ */
1077
+ async #heldThrough(principal: string, candidates: HeldThrough, action: string, dimension: string, value: string): Promise<HeldThrough> {
1078
+ const check = this.#parts.database?.holdsThrough
1079
+ if (check === undefined || (candidates.relations.length === 0 && candidates.paths.length === 0)) {
1080
+ return NONE_THROUGH
1081
+ }
1082
+ const batches: { relations: RelationHold[]; paths: ContainerGrant[]; size: number }[] = [{ relations: [], paths: [], size: 0 }]
1083
+ const add = (values: readonly string[], put: (batch: { relations: RelationHold[]; paths: ContainerGrant[] }, chunk: string[]) => void) => {
1084
+ for (let start = 0; start < values.length; start += MAX_WITHIN_VALUES) {
1085
+ const chunk = values.slice(start, start + MAX_WITHIN_VALUES)
1086
+ let batch = batches[batches.length - 1] ?? { relations: [], paths: [], size: 0 }
1087
+ if (batch.size + chunk.length > MAX_WITHIN_VALUES) {
1088
+ batch = { relations: [], paths: [], size: 0 }
1089
+ batches.push(batch)
1090
+ }
1091
+ put(batch, chunk)
1092
+ batch.size += chunk.length
1093
+ }
1094
+ }
1095
+ for (const hold of candidates.relations) {
1096
+ const inside = hold.inside
1097
+ if (inside === null) {
1098
+ batches[0]?.relations.push(hold)
1099
+ continue
1100
+ }
1101
+ add(inside.values, (batch, chunk) => batch.relations.push({ relation: hold.relation, inside: { dimension: inside.dimension, values: chunk } }))
1102
+ }
1103
+ for (const grant of candidates.paths) {
1104
+ add(grant.values, (batch, chunk) => batch.paths.push({ dimension: grant.dimension, values: chunk }))
1105
+ }
1106
+ let relations: RelationHold[] = []
1107
+ const paths = new Map<string, Set<string>>()
1108
+ for (const batch of batches) {
1109
+ if (batch.relations.length === 0 && batch.paths.length === 0) continue
1110
+ const held = await check(dimension, value, action, principal, batch.relations, batch.paths)
1111
+ relations = holdsOf(relations, held.relations)
1112
+ for (const grant of held.paths) {
1113
+ const values = paths.get(grant.dimension) ?? new Set<string>()
1114
+ for (const at of grant.values) values.add(at)
1115
+ paths.set(grant.dimension, values)
1116
+ }
1117
+ }
1118
+ return { relations, paths: [...paths].map(([at, values]) => ({ dimension: at, values: [...values] })) }
1119
+ }
1120
+
1121
+ /**
1122
+ * What the caller holds of `action` in `dimension`, as a `Within` of it would carry it, without the grants inside it:
1123
+ * the standing an insert that hands out access through a path judges its writer by; empty when it holds none.
1124
+ */
1125
+ #standing(caller: Caller, action: string, dimension: string): WithinGrant {
1126
+ const dimensions = [dimension, ...(this.#parts.containers.get(dimension) ?? [])]
1127
+ const containers = this.#heldContainers(caller.perms, action, dimension)
1128
+ const relations = this.#heldRelations(caller.perms, action, dimensions)
1129
+ const revealing = this.#heldRevealing(caller.perms, action, dimensions)
1130
+ const values = scopedValues(caller.perms, action, dimension) ?? 'all'
1131
+ return { kind: 'within', dimension, action, principal: caller.subject, values, containers, contained: [], relations, revealing }
1132
+ }
1133
+
1134
+ /**
1135
+ * Of `revealing`, the caller's grants of `action` at nodes of revealing dimensions, those whose row reveals the object
1136
+ * or a container on its chain to its members for `action`, now: what a Ref held through member reveals carries.
1137
+ */
1138
+ async #revealedOn(
1139
+ revealing: readonly ContainerGrant[],
1140
+ action: string,
1141
+ dimension: string,
1142
+ value: string,
1143
+ chain: ReadonlyMap<string, string>,
1144
+ ): Promise<ContainerGrant[]> {
1145
+ const check = this.#parts.database?.revealsToMembers
1146
+ if (check === undefined || revealing.length === 0) {
1147
+ return []
1148
+ }
1149
+ const nodeOf = (at: string) => (at === dimension ? value : chain.get(at))
1150
+ const held: ContainerGrant[] = []
1151
+ for (const grant of revealing) {
1152
+ const found = new Set<string>()
1153
+ for (const reveal of this.#parts.memberReveals.get(grant.dimension) ?? []) {
1154
+ const node = reveal.actions.includes(action) ? nodeOf(reveal.dimension) : undefined
1155
+ for (let start = 0; node !== undefined && start < grant.values.length; start += MAX_WITHIN_VALUES) {
1156
+ for (const at of await check(grant.dimension, grant.values.slice(start, start + MAX_WITHIN_VALUES), reveal.dimension, node, action)) {
1157
+ found.add(at)
1158
+ }
1159
+ }
1160
+ }
1161
+ if (found.size > 0) held.push({ dimension: grant.dimension, values: [...found] })
1162
+ }
1163
+ return held
1164
+ }
1165
+
1166
+ /**
1167
+ * The relations through which the caller holds `action` at a node of one of `dimensions`, at the relation's own
1168
+ * dimension or at an ancestor a reveal of `action` names: a `~rel` entry (a global grant of a role with `via`) holds it
1169
+ * anywhere, a `~relin` entry (a scoped grant of one) only inside its node, so only where the relation's dimension and
1170
+ * the reveal's are the node's dimension or lie inside it. The nodes of one relation and dimension are one hold; a
1171
+ * relation held anywhere needs none. An entry of a relation the contract does not declare counts for none.
1172
+ */
1173
+ #heldRelations(perms: PermissionEntry[], action: string, dimensions: readonly string[]): RelationHold[] {
1174
+ const anywhere: string[] = []
1175
+ const inside = new Map<string, { relation: string; dimension: string; values: string[] }>()
1176
+ for (const entry of perms) {
1177
+ const scope = entry.scope
1178
+ if (scope === null || !matchAction(entry.action, action)) continue
1179
+ if (scope.type === RELATION_SCOPE_TYPE) {
1180
+ if (this.#relationReaches(scope.value, action, dimensions, null) && !anywhere.includes(scope.value)) anywhere.push(scope.value)
1181
+ continue
1182
+ }
1183
+ const held = scope.type === RELATION_INSIDE_SCOPE_TYPE ? parseRelationInside(scope) : null
1184
+ if (held === null || !this.#relationReaches(held.relation, action, dimensions, held.dimension)) continue
1185
+ const key = JSON.stringify([held.relation, held.dimension])
1186
+ const hold = inside.get(key) ?? { relation: held.relation, dimension: held.dimension, values: [] }
1187
+ if (!hold.values.includes(held.node)) hold.values.push(held.node)
1188
+ inside.set(key, hold)
1189
+ }
1190
+ const holds: RelationHold[] = anywhere.map((relation) => ({ relation, inside: null }))
1191
+ for (const hold of inside.values()) {
1192
+ if (!anywhere.includes(hold.relation)) holds.push({ relation: hold.relation, inside: { dimension: hold.dimension, values: hold.values } })
1193
+ }
1194
+ return holds
1195
+ }
1196
+
1197
+ /**
1198
+ * Whether `relation` holds `action` at a node of one of `dimensions`: at its own dimension, or at an ancestor a reveal
1199
+ * of `action` names. Held inside a node of `within`, only where that dimension is `within` or lies inside it.
1200
+ */
1201
+ #relationReaches(relation: string, action: string, dimensions: readonly string[], within: string | null): boolean {
1202
+ const at = this.#parts.relations.get(relation)
1203
+ const lies = (dimension: string) => within === null || dimension === within || (this.#parts.containers.get(dimension) ?? []).includes(within)
1204
+ if (at === undefined || !lies(at)) return false
1205
+ return dimensions.includes(at) || this.#revealed(relation, action).some((dimension) => dimensions.includes(dimension) && lies(dimension))
1206
+ }
1207
+
1208
+ /**
1209
+ * Of `holds`, those that may reach an object of `dimension` whose chain is `chain`: every one held anywhere, and one
1210
+ * held inside nodes only where its dimension is the object's or lies on its chain. Its nodes stay as held: the database
1211
+ * compares the object's column with them (`holdsThrough`), as a `Within` of them would, never this process.
1212
+ */
1213
+ #atObject(holds: readonly RelationHold[], dimension: string, chain: ReadonlyMap<string, string>): RelationHold[] {
1214
+ return holds.filter((hold) => hold.inside === null || hold.inside.dimension === dimension || chain.has(hold.inside.dimension))
1215
+ }
1216
+
1217
+ /** The ancestor dimensions a reveal of `relation` holds `action` at. */
1218
+ #revealed(relation: string, action: string): string[] {
1219
+ return (this.#parts.reveals.get(relation) ?? []).filter((reveal) => reveal.actions.includes(action)).map((reveal) => reveal.dimension)
1220
+ }
1221
+
1222
+ /**
1223
+ * Of `candidates`, the relations a row of which names the caller at the object or at a container on its chain, or
1224
+ * reaches a row that reveals one of them for `action`, now. One held inside a node is judged by the database on the
1225
+ * object's row (`holdsThrough`), which compares its column for the node's dimension too; a dimension no table owns
1226
+ * has no such row, so there it holds nothing.
1227
+ */
1228
+ async #relatedOn(
1229
+ principal: string,
1230
+ candidates: readonly RelationHold[],
1231
+ action: string,
1232
+ dimension: string,
1233
+ value: string,
1234
+ chain: ReadonlyMap<string, string>,
1235
+ ): Promise<RelationHold[]> {
1236
+ const relates = this.#parts.database?.relates
1237
+ const reveals = this.#parts.database?.reveals
1238
+ if (relates === undefined) {
1239
+ return []
1240
+ }
1241
+ const nodeOf = (at: string | undefined) => (at === dimension ? value : at === undefined ? undefined : chain.get(at))
1242
+ const related: RelationHold[] = []
1243
+ const inside: RelationHold[] = []
1244
+ for (const hold of candidates) {
1245
+ if (hold.inside !== null) {
1246
+ inside.push(hold)
1247
+ continue
1248
+ }
1249
+ const relation = hold.relation
1250
+ const node = nodeOf(this.#parts.relations.get(relation))
1251
+ if (node !== undefined && (await relates(relation, node, principal))) {
1252
+ related.push(hold)
1253
+ continue
1254
+ }
1255
+ if (reveals === undefined) continue
1256
+ for (const revealed of this.#revealed(relation, action)) {
1257
+ const at = nodeOf(revealed)
1258
+ if (at !== undefined && (await reveals(relation, revealed, at, principal, action))) {
1259
+ related.push(hold)
1260
+ break
1261
+ }
1262
+ }
1263
+ }
1264
+ if (inside.length > 0 && this.#parts.ownedDimensions.has(dimension)) {
1265
+ related.push(...(await this.#heldThrough(principal, { relations: inside, paths: [] }, action, dimension, value)).relations)
1266
+ }
1267
+ return related
963
1268
  }
964
1269
 
965
1270
  /**
@@ -1221,7 +1526,7 @@ export class ContractRuntime {
1221
1526
  kick: kicks.kick,
1222
1527
  })
1223
1528
  const args = { input, ctx, ...(query === undefined ? {} : { query }) }
1224
- return await runAsSite(`'${served.row.id}'`, served.site.declaration.egress, async () => await served.handler(args))
1529
+ return await runAsSite(`'${served.row.id}'`, siteEgress(served.site.declaration.egress, null), async () => await served.handler(args))
1225
1530
  })
1226
1531
  } finally {
1227
1532
  frame.end()
@@ -1375,7 +1680,7 @@ export class ContractRuntime {
1375
1680
  if (site === undefined) {
1376
1681
  await served.handler(args)
1377
1682
  } else {
1378
- await runAsSite(`webhook '${served.webhook}'`, site.egress, async () => await served.handler(args))
1683
+ await runAsSite(`webhook '${served.webhook}'`, siteEgress(site.egress, null), async () => await served.handler(args))
1379
1684
  }
1380
1685
  })
1381
1686
  } finally {
@@ -1466,6 +1771,18 @@ export class ContractRuntime {
1466
1771
  })
1467
1772
  }
1468
1773
 
1774
+ /**
1775
+ * The caller's grants of `action` at nodes of a dimension whose rows reveal one of `dimensions` for it to their
1776
+ * members; a grant at a container of such a node is not one at the node.
1777
+ */
1778
+ #heldRevealing(perms: PermissionEntry[], action: string, dimensions: readonly string[]): ContainerGrant[] {
1779
+ return [...this.#parts.memberReveals].flatMap(([source, revealed]) => {
1780
+ const reveals = revealed.some((reveal) => reveal.actions.includes(action) && dimensions.includes(reveal.dimension))
1781
+ const values = reveals ? scopedValues(perms, action, source) ?? [] : []
1782
+ return values.length === 0 ? [] : [{ dimension: source, values }]
1783
+ })
1784
+ }
1785
+
1469
1786
  /** The caller's grants of `action` on every dimension that lies inside `dimension`. */
1470
1787
  #heldContained(perms: PermissionEntry[], action: string, dimension: string): ContainerGrant[] {
1471
1788
  return [...this.#parts.containers].flatMap(([inner, containers]) => {