@fabrika/app 0.9.0-dev.13 → 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 (42) hide show
  1. package/package.json +9 -9
  2. package/skill/SKILL.md +2 -1
  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 +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/bun.ts +10 -0
  11. package/src/contract/artifact-schema.ts +17 -3
  12. package/src/contract/build.ts +76 -18
  13. package/src/contract/define.ts +2 -1
  14. package/src/contract/group.ts +10 -1
  15. package/src/contract/kit.ts +2 -1
  16. package/src/disk-assets.ts +15 -3
  17. package/src/implement/boot.ts +28 -5
  18. package/src/implement/capability.ts +82 -12
  19. package/src/implement/dispatch.ts +251 -35
  20. package/src/implement/egress.ts +409 -9
  21. package/src/implement/implement.ts +23 -3
  22. package/src/implement/invocation.ts +10 -9
  23. package/src/implement/types.ts +15 -4
  24. package/src/implement/webhook.ts +8 -0
  25. package/src/jobs/runner.ts +7 -2
  26. package/src/source-map-path.ts +21 -0
  27. package/src/testing/caller.ts +20 -9
  28. package/src/testing/membership.ts +9 -5
  29. package/types/src/contract/define.d.ts +2 -1
  30. package/types/src/contract/group.d.ts +9 -1
  31. package/types/src/contract/kit.d.ts +2 -2
  32. package/types/src/implement/boot.d.ts +6 -0
  33. package/types/src/implement/capability.d.ts +14 -5
  34. package/types/src/implement/dispatch.d.ts +9 -1
  35. package/types/src/implement/egress.d.ts +36 -1
  36. package/types/src/implement/implement.d.ts +19 -3
  37. package/types/src/implement/invocation.d.ts +3 -3
  38. package/types/src/implement/types.d.ts +13 -3
  39. package/types/src/jobs/runner.d.ts +3 -0
  40. package/types/src/source-map-path.d.ts +4 -0
  41. package/types/src/testing/caller.d.ts +6 -1
  42. package/types/src/testing/membership.d.ts +1 -1
@@ -18,6 +18,7 @@ import {
18
18
  type ContractArtifact,
19
19
  type CspExtensions,
20
20
  type CspSource,
21
+ type DeclaredEgress,
21
22
  type DeclaredReach,
22
23
  type DimensionArtifact,
23
24
  directoryReach,
@@ -54,6 +55,7 @@ import {
54
55
  planEndpoint,
55
56
  type ProcedureArtifact,
56
57
  type ProcedureChallenge,
58
+ PUBLIC_EGRESS,
57
59
  type RoleArtifact,
58
60
  type SchemaShape,
59
61
  type ScopeBinding,
@@ -150,7 +152,7 @@ const FRAMEWORK_TABLE_PREFIX = 'fabrika_'
150
152
  /** The most origins one site calls: a site that reaches more is an integration hub, which a connector import serves. */
151
153
  const MAX_EGRESS_ORIGINS = 16
152
154
  const DECLARED_ALLOWED =
153
- "sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', mailer: 'installation' | 'own', kicks: ['<cron job>'], binds: '<webhook>', signs: ['<token purpose>'], egress: ['https://<host>' | 'https://*.<domain>']"
155
+ "sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', mailer: 'installation' | 'own', kicks: ['<cron job>'], binds: '<webhook>', signs: ['<token purpose>'], egress: ['https://<host>' | 'https://*.<domain>'] | 'public' (a cron job)"
154
156
  const CSP_FIELDS = ['connectSrc', 'imgSrc', 'frameAncestors', 'scriptSrc', 'frameSrc', 'styleSrc', 'fontSrc']
155
157
  /** An environment variable an application reads; a challenge names its secret by one. */
156
158
  const APPLICATION_VARIABLE = /^[A-Z][A-Z0-9_]*$/
@@ -498,7 +500,10 @@ class ArtifactBuilder {
498
500
  return roles
499
501
  }
500
502
 
501
- /** Each relation names a dimension of the contract, and exactly one table's rows confer it. */
503
+ /**
504
+ * Each relation names a dimension of the contract, and is reached through at most one table's rows that confer it,
505
+ * through access views (ADR-0076), or both; never through neither.
506
+ */
502
507
  #relations(): Record<string, { readonly dimension: string }> {
503
508
  const relations: Record<string, { readonly dimension: string }> = {}
504
509
  for (const [name, relation] of Object.entries(this.#contract.relations ?? {})) {
@@ -508,8 +513,12 @@ class ArtifactBuilder {
508
513
  this.#problem(where, `names the dimension '${relation.dimension}', which is not a dimension of the contract`)
509
514
  }
510
515
  const sources = Object.entries(this.#tables).filter(([, table]) => table.confers !== undefined && Object.hasOwn(table.confers, name))
511
- if (sources.length !== 1) {
512
- this.#problem(where, `is conferred by ${sources.length} tables; exactly one table declares confers.${name}`)
516
+ const viewed = Object.values(this.#tables).some((table) => table.access !== undefined && Object.hasOwn(table.access, name))
517
+ if (sources.length > 1 || (sources.length === 0 && !viewed)) {
518
+ this.#problem(
519
+ where,
520
+ `is conferred by ${sources.length} tables; exactly one table declares confers.${name}, or a table names an access view for it`,
521
+ )
513
522
  }
514
523
  relations[name] = { dimension: relation.dimension }
515
524
  }
@@ -519,23 +528,39 @@ class ArtifactBuilder {
519
528
  this.#problem(`table '${table}'`, `confers '${relation}', which is not a relation of the vocabulary`)
520
529
  }
521
530
  }
531
+ for (const relation of Object.keys(policy.access ?? {})) {
532
+ if (!Object.hasOwn(relations, relation)) {
533
+ this.#problem(`table '${table}'`, `names an access view for '${relation}', which is not a relation of the vocabulary`)
534
+ }
535
+ }
522
536
  }
523
537
  return relations
524
538
  }
525
539
 
526
540
  /**
527
- * A role's `via`: known relations and actions, on an application-wide internal role only (ADR-0051 keeps an
528
- * external principal to its membership roles), and never an action that inserts a relation's rows, so a relation
529
- * never delegates itself onward.
541
+ * A role's `via`: known relations and actions, on an internal role only (ADR-0051 keeps an external principal to its
542
+ * membership roles' own grants), and never an action that inserts a relation's rows, so a relation never delegates
543
+ * itself onward. A membership role holds a relation inside the value it is held in, so the relation's dimension is
544
+ * the role's or lies inside it.
530
545
  */
531
546
  #via(where: string, role: RoleDeclaration): Record<string, readonly string[]> | undefined {
532
547
  if (role.via === undefined) {
533
548
  return undefined
534
549
  }
535
- if (role.member !== undefined || role.external === true) {
536
- this.#problem(where, 'holds actions via a relation and is a membership or external role: only an application-wide role declares via')
550
+ if (role.external === true) {
551
+ this.#problem(where, 'holds actions via a relation and is an external role: an external principal holds no relation')
537
552
  }
538
553
  const relations = this.#contract.relations ?? {}
554
+ const member = role.member?.scope
555
+ for (const relation of Object.keys(role.via)) {
556
+ const dimension = relations[relation]?.dimension
557
+ if (member !== undefined && dimension !== undefined && !this.#lies(dimension, member)) {
558
+ this.#problem(
559
+ where,
560
+ `holds actions via '${relation}', whose dimension '${dimension}' is not '${member}' and does not lie inside it: a membership role holds a relation inside the value it is held in`,
561
+ )
562
+ }
563
+ }
539
564
  const assigning = new Set<string>()
540
565
  for (const policy of Object.values(this.#tables)) {
541
566
  if (policy.confers === undefined) continue
@@ -562,6 +587,18 @@ class ArtifactBuilder {
562
587
  return via
563
588
  }
564
589
 
590
+ /** Whether `dimension` is `ancestor` or lies inside it, by the contract's declared containment. */
591
+ #lies(dimension: string, ancestor: string): boolean {
592
+ const seen: string[] = []
593
+ let at: string | undefined = dimension
594
+ while (at !== undefined && !seen.includes(at)) {
595
+ if (at === ancestor) return true
596
+ seen.push(at)
597
+ at = this.#contract.dimensions[at]?.in
598
+ }
599
+ return false
600
+ }
601
+
565
602
  // ── Mounts ──────────────────────────────────────────────────────────────────────────────────
566
603
 
567
604
  #mount(name: string, mount: MountDeclaration<SchemaShape>): MountArtifact | null {
@@ -2215,7 +2252,7 @@ class ArtifactBuilder {
2215
2252
  ...(kicks.length === 0 ? {} : { kicks }),
2216
2253
  ...(binds === undefined ? {} : { binds }),
2217
2254
  ...(signs.length === 0 ? {} : { signs }),
2218
- ...(egress.length === 0 ? {} : { egress }),
2255
+ ...(egress === null ? {} : { egress }),
2219
2256
  }
2220
2257
  if (place.kind !== 'rpc') {
2221
2258
  this.#rpcOnly(where, 'connect', value['connect'])
@@ -2419,12 +2456,13 @@ class ArtifactBuilder {
2419
2456
 
2420
2457
  /**
2421
2458
  * The HTTPS origins a site's code calls: a credentialed procedure of an RPC mount, a webhook or a job, never a public,
2422
- * export or link procedure. Each is an exact origin or a one-label pattern (`parseEgressEntry`), once; `[]` when it
2423
- * declares none or after a problem.
2459
+ * export or link procedure. Each is an exact origin or a one-label pattern (`parseEgressEntry`), once. Or `'public'`,
2460
+ * every public host (ADR-0075), which only a cron job declares: it calls outside any transaction, and its schedule,
2461
+ * not a caller, decides when. `null` when it declares none or after a problem.
2424
2462
  */
2425
- #egress(where: string, value: unknown, place: DeclaringSite): string[] {
2463
+ #egress(where: string, value: unknown, place: DeclaringSite): DeclaredEgress | null {
2426
2464
  if (value === undefined) {
2427
- return []
2465
+ return null
2428
2466
  }
2429
2467
  const refusedBy = place.kind === 'export'
2430
2468
  ? 'an export procedure'
@@ -2435,15 +2473,35 @@ class ArtifactBuilder {
2435
2473
  : null
2436
2474
  if (refusedBy !== null) {
2437
2475
  this.#problem(where, `declares egress, which ${refusedBy} never does: a credentialed procedure, a webhook or a job calls out`)
2438
- return []
2476
+ return null
2477
+ }
2478
+ if (value === PUBLIC_EGRESS) {
2479
+ if (place.kind !== 'job') {
2480
+ this.#problem(
2481
+ where,
2482
+ `declares egress: '${PUBLIC_EGRESS}', which only a cron job declares: a procedure or a webhook names its origins (allowed: egress: ['https://api.example.com'])`,
2483
+ )
2484
+ return null
2485
+ }
2486
+ return PUBLIC_EGRESS
2439
2487
  }
2440
2488
  if (!Array.isArray(value) || value.length === 0 || !value.every((origin) => typeof origin === 'string')) {
2441
- this.#problem(where, "egress is not a list of origins (allowed: egress: ['https://api.example.com'])")
2442
- return []
2489
+ this.#problem(
2490
+ where,
2491
+ place.kind === 'job'
2492
+ ? "egress is not a list of origins or 'public' (allowed: egress: ['https://api.example.com'] or egress: 'public')"
2493
+ : "egress is not a list of origins (allowed: egress: ['https://api.example.com'])",
2494
+ )
2495
+ return null
2443
2496
  }
2444
2497
  const origins: string[] = value.filter((origin) => typeof origin === 'string')
2445
2498
  if (origins.length > MAX_EGRESS_ORIGINS) {
2446
- this.#problem(where, `${origins.length} egress origins exceed the limit of ${MAX_EGRESS_ORIGINS}`)
2499
+ this.#problem(
2500
+ where,
2501
+ `${origins.length} egress origins exceed the limit of ${MAX_EGRESS_ORIGINS}${
2502
+ place.kind === 'job' ? " (a cron job that calls the websites its operators name declares egress: 'public')" : ''
2503
+ }`,
2504
+ )
2447
2505
  }
2448
2506
  for (const origin of origins) {
2449
2507
  const parsed = parseEgressEntry(origin)
@@ -97,7 +97,8 @@ export interface RoleDef<A extends string, D extends string, R extends string> {
97
97
  readonly external?: true
98
98
  /**
99
99
  * Relation → actions: a holder of this role, granted globally, holds them at each node a row of the relation's
100
- * source names them at (`via: { owner: ['projects.edit'] }`). A scoped grant of the role carries none of them.
100
+ * source names them at (`via: { owner: ['projects.edit'] }`). A grant at a value holds them only on rows inside that
101
+ * value, so a membership role's relation has the role's dimension or one inside it. An external role takes none.
101
102
  */
102
103
  readonly via?: { readonly [relation: string]: readonly A[] }
103
104
  }
@@ -115,7 +115,16 @@ export type SignsField<Sg, Purposes extends string> =
115
115
  * guard on the global `fetch` refuses any other while the site runs; a public procedure declares none.
116
116
  */
117
117
  export interface EgressField {
118
- readonly egress?: readonly `https://${string}`[]
118
+ readonly egress?: readonly `https://${string}`[] | Unavailable<"egress: 'public' is a cron job's only: record a row and kick a job that declares it">
119
+ }
120
+
121
+ /**
122
+ * A cron job's `egress`: its exact HTTPS origins, or `'public'`, every public host over HTTPS or HTTP on its default
123
+ * port, for a job that calls the websites its operators name (ADR-0075). The guard refuses IP addresses, local and
124
+ * internal names and the installation's own hosts, checks each redirect, and bounds each request's time and body.
125
+ */
126
+ export interface JobEgressField {
127
+ readonly egress?: readonly `https://${string}`[] | 'public'
119
128
  }
120
129
 
121
130
  /** Each purpose `signs` names is one of `defineApp`'s `tokens`. */
@@ -57,6 +57,7 @@ import type {
57
57
  GroupBuild,
58
58
  GroupInput,
59
59
  GroupKit,
60
+ JobEgressField,
60
61
  KicksField,
61
62
  LimitsOption,
62
63
  LinkGroupKit,
@@ -96,7 +97,7 @@ export type CronOptions<Acts, S, U, Is, Ix extends AnyDbIndex, M = never, Ks = n
96
97
  & MailerField<M>
97
98
  & KicksField<Ks>
98
99
  & SignsField<Sg, Purposes>
99
- & EgressField
100
+ & JobEgressField
100
101
 
101
102
  /** The mail transport a job reaches, inferred from its optional field and then required, like a declared field. */
102
103
  type MailerField<M> =
@@ -2,8 +2,10 @@
2
2
  // test kit serves a built directory the same way.
3
3
 
4
4
  import { rawRequestTarget } from '@fabrika/auth-core'
5
- import { join, resolve, sep } from 'node:path'
5
+ import type { BunFile } from 'bun'
6
+ import { basename, join, resolve, sep } from 'node:path'
6
7
  import type { SpaAssets } from './implement/dispatch.js'
8
+ import { isSourceMapName } from './source-map-path.js'
7
9
  import { isPageRoute } from './spa-fallback.js'
8
10
 
9
11
  /**
@@ -18,8 +20,8 @@ export function diskAssets(root: string): SpaAssets {
18
20
  const relative = mount.prefix === '/' ? pathname.slice(1) : pathname.slice(mount.prefix.length + 1)
19
21
  // The path is canonical, so every segment decodes and none is `.` or `..`.
20
22
  const file = join(dir, ...relative.split('/').filter((segment) => segment !== '').map((segment) => decodeURIComponent(segment)))
21
- const candidate = file.startsWith(`${dir}${sep}`) ? Bun.file(file) : null
22
- const found = candidate !== null && (await candidate.exists()) ? candidate : null
23
+ // The mount refuses a source map before it asks; this holds for any caller that serves through it directly.
24
+ const found = file.startsWith(`${dir}${sep}`) && !isSourceMapName(basename(file)) ? await existing(file) : null
23
25
  const served = found ?? (isPageRoute(request) ? Bun.file(join(dir, 'index.html')) : null)
24
26
  if (served === null || !(await served.exists())) {
25
27
  return new Response('Not found', { status: 404 })
@@ -28,3 +30,13 @@ export function diskAssets(root: string): SpaAssets {
28
30
  },
29
31
  }
30
32
  }
33
+
34
+ /** The file at `path` when it exists. A name no file can have (a decoded control character) is a missing asset, not a fault. */
35
+ async function existing(path: string): Promise<BunFile | null> {
36
+ try {
37
+ const file = Bun.file(path)
38
+ return (await file.exists()) ? file : null
39
+ } catch {
40
+ return null
41
+ }
42
+ }
@@ -60,6 +60,7 @@ import { type ConnectFetch, wireImports } from './connect'
60
60
  import {
61
61
  ContractRuntime,
62
62
  type Facilities,
63
+ type HeldPath,
63
64
  NO_FACILITIES,
64
65
  type ProcedureQuery,
65
66
  proxySecretDigest,
@@ -68,7 +69,7 @@ import {
68
69
  type ServedSite,
69
70
  type SpaAssets,
70
71
  } from './dispatch'
71
- import { installEgressGuard, platformCall, platformFacility } from './egress'
72
+ import { type HostResolver, installEgressGuard, platformCall, platformFacility, publicEgressRules, type SiteEgress, siteEgress } from './egress'
72
73
  import type { CapturedEnvironment } from './environment'
73
74
  import { FailureReports, type HandlerErrorSink } from './failures'
74
75
  import { applicationPolicy } from './headers'
@@ -132,6 +133,11 @@ export interface BootOptions {
132
133
  * with a job or a webhook does not boot.
133
134
  */
134
135
  readonly workloadTokens?: WorkloadTokenSource
136
+ /**
137
+ * Resolves a host name to its addresses, which the Bun adapter supplies (`node:dns`): a cron job's public egress then
138
+ * refuses a public name of a private address before each hop. A Worker exposes no resolution and passes none.
139
+ */
140
+ readonly resolveHost?: HostResolver
135
141
  /** What posts a report to Operations' ingest; `fetch` by default. */
136
142
  readonly operationsFetch?: (request: Request) => Promise<Response>
137
143
  /** What asks a public procedure's challenge provider to verify a token; `fetch` by default. */
@@ -405,14 +411,14 @@ function contractDatabase(
405
411
  return null
406
412
  }
407
413
  try {
408
- const { locate, relates, reveals, release } = bindScopedDatabaseProvisionally(database, {
414
+ const { locate, relates, reveals, holdsThrough, revealsToMembers, release } = bindScopedDatabaseProvisionally(database, {
409
415
  database: connection,
410
416
  capabilities,
411
417
  readOnly: requestIsReadOnly,
412
418
  ...(projectWakes === undefined ? {} : { projectWakes }),
413
419
  })
414
420
  return {
415
- database: { tables: database.tables, locate, relates, reveals },
421
+ database: { tables: database.tables, locate, relates, reveals, holdsThrough, revealsToMembers },
416
422
  framework: frameworkTablesOf(database),
417
423
  data: dataAccessOf(database),
418
424
  release,
@@ -466,8 +472,8 @@ function boundHandler(
466
472
  }
467
473
 
468
474
  /** 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 }
475
+ function egressOf(bound: BoundHandler): { readonly egress?: SiteEgress } {
476
+ return !bound.site || bound.declaration === null ? {} : { egress: siteEgress(bound.declaration.egress, null) }
471
477
  }
472
478
 
473
479
  /** A staged-kit contract's endpoint gets `ctx.links` only for the link mount it declares it `issues`. */
@@ -697,6 +703,21 @@ function memberRevealsOf(artifact: ContractArtifact): ReadonlyMap<string, readon
697
703
  return reveals
698
704
  }
699
705
 
706
+ /**
707
+ * Each dimension's secondary paths that hold actions for a Ref, from the policy of the table that owns it: the dimension
708
+ * the path reaches and the actions it holds there (`writeThrough`).
709
+ */
710
+ function pathsOf(artifact: ContractArtifact): ReadonlyMap<string, readonly HeldPath[]> {
711
+ const paths = new Map<string, HeldPath[]>()
712
+ for (const table of Object.values(artifact.tables)) {
713
+ if (table.scope.mode !== 'dimension') continue
714
+ for (const [dimension, actions] of Object.entries(table.writeThrough ?? {})) {
715
+ paths.set(table.scope.dimension, [...(paths.get(table.scope.dimension) ?? []), { dimension, actions }])
716
+ }
717
+ }
718
+ return paths
719
+ }
720
+
700
721
  /** Each approved token purpose with the claims schema the application declared for it. */
701
722
  function runtimePurposes(contract: AnyContract, artifact: ContractArtifact): ReadonlyMap<string, RuntimePurpose> {
702
723
  const declared = contract.surface.tokens ?? {}
@@ -927,6 +948,7 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
927
948
  mail,
928
949
  tokens,
929
950
  url,
951
+ publicEgress: publicEgressRules(options.environment.framework, options.resolveHost ?? null),
930
952
  }, problems)
931
953
  for (const id of jobs.declared) {
932
954
  declared.add(id)
@@ -1004,6 +1026,7 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
1004
1026
  relations: new Map(Object.entries(artifact.relations ?? {}).map(([name, relation]) => [name, relation.dimension])),
1005
1027
  reveals: revealsOf(artifact),
1006
1028
  memberReveals: memberRevealsOf(artifact),
1029
+ paths: pathsOf(artifact),
1007
1030
  assets: options.assets ?? null,
1008
1031
  membership,
1009
1032
  terminals: artifact.terminal === undefined ? null : (terminalRpc ?? null),
@@ -15,6 +15,7 @@ import {
15
15
  MAX_WITHIN_VALUES,
16
16
  type Ref as RefCapability,
17
17
  type RefGrant,
18
+ type RelationHold,
18
19
  type RowGrant,
19
20
  type RowRef as RowRefCapability,
20
21
  type Within as WithinCapability,
@@ -34,7 +35,13 @@ export const CAPABILITY_REFUSALS = {
34
35
  undeclared_binding: 'the site named a webhook it does not declare in binds',
35
36
  undeclared_signs: 'the site signed a token of a purpose it does not declare in signs, or for longer than the purpose allows',
36
37
  undeclared_egress: 'the site called an origin it does not declare in egress',
38
+ refused_egress:
39
+ "the site's public egress refused the host: an IP address, a local or internal name, a non-default port, credentials in the URL, a host of this installation, or a name that resolves to a private address",
40
+ oversized_egress: "a response to the site's public egress was larger than it reads",
41
+ encoded_egress: "a response to the site's public egress came compressed, which it neither asks for nor decodes",
37
42
  wrong_binding: 'a webhook binding was handed a capability of another kind or dimension than the webhook is bound to',
43
+ conditional_binding:
44
+ 'a webhook binding was handed a Ref held through a relation, a member reveal or a secondary path, which a binding would outlive',
38
45
  missing_id: 'the job named an object without an id',
39
46
  wrong_capability: 'an operation was handed a capability of another dimension or action than it needs',
40
47
  } as const
@@ -58,6 +65,9 @@ export class CapabilityLimitError extends Error {
58
65
  override readonly name = 'CapabilityLimitError'
59
66
  }
60
67
 
68
+ /** The caller's grants of `action` in `dimension`, as a `Within` of it would carry them; no values when it holds none. */
69
+ export type Standing = (dimension: string, action: string) => WithinGrant
70
+
61
71
  /**
62
72
  * One request's lifetime, or one job attempt's. A capability minted in it is usable only while it runs, and only
63
73
  * inside it; a job attempt's writes also need its lease (`fence`).
@@ -69,16 +79,24 @@ export class RequestFrame {
69
79
  readonly readOnly: boolean
70
80
  /** The endpoint the request is served by; `ctx.connect` checks it against each import's `usedBy`. */
71
81
  readonly endpoint: string | null
82
+ /** What the request's caller holds of an action in a dimension; none for work without a caller (a job, a webhook). */
83
+ readonly standing: Standing | null
72
84
  #ended = false
73
85
 
74
86
  constructor(
75
87
  id: string,
76
- options: { readonly fence?: LeaseFence | null; readonly readOnly?: boolean; readonly endpoint?: string | null } = {},
88
+ options: {
89
+ readonly fence?: LeaseFence | null
90
+ readonly readOnly?: boolean
91
+ readonly endpoint?: string | null
92
+ readonly standing?: Standing | null
93
+ } = {},
77
94
  ) {
78
95
  this.id = id
79
96
  this.fence = options.fence ?? null
80
97
  this.readOnly = options.readOnly ?? false
81
98
  this.endpoint = options.endpoint ?? null
99
+ this.standing = options.standing ?? null
82
100
  }
83
101
 
84
102
  get ended(): boolean {
@@ -162,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
  }