@fabrika/db 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.
package/src/tables.ts CHANGED
@@ -1,11 +1,33 @@
1
1
  // @fabrika/db/tables — the table policies of `src/db/tables.ts` as data. Browser- and Worker-safe: no Bun API and no
2
2
  // driver, so `@fabrika/app/contract` and the static contract reader in `@fabrika/check` import it.
3
3
 
4
- import type { ColumnPolicyArtifact, TableActionArtifact, TablePolicyArtifact, TableScope } from '@fabrika/auth-core'
4
+ import type {
5
+ AccessArtifact,
6
+ ColumnPolicyArtifact,
7
+ ConditionArtifact,
8
+ ConfersArtifact,
9
+ MemberRevealsArtifact,
10
+ RevealsArtifact,
11
+ TableActionArtifact,
12
+ TablePolicyArtifact,
13
+ TableScope,
14
+ } from '@fabrika/auth-core'
5
15
  import { type ApplicationRowsPlan, planApplicationRows } from './application-rows'
6
16
  import { freeze, namesOf, ownEntry, ownKeys, setOwn } from './builtins'
17
+ import { conditionArtifact, type ConditionModel } from './conditions'
7
18
  import { PolicyError } from './errors'
8
- import { modelOf, type ScopeModel, type TableModel, tableModels, type Tables } from './policy'
19
+ import {
20
+ type AccessModel,
21
+ accessTablesOf,
22
+ type MemberRevealModel,
23
+ modelOf,
24
+ type RelationSource,
25
+ type RevealModel,
26
+ type ScopeModel,
27
+ type TableModel,
28
+ tableModels,
29
+ type Tables,
30
+ } from './policy'
9
31
 
10
32
  export { applicationRowRefusalText } from './application-rows'
11
33
  export type { ApplicationRowRefusal, ApplicationRowsPlan } from './application-rows'
@@ -114,6 +136,15 @@ export function applicationRowsPlan<DB, P>(
114
136
  return planApplicationRows(tableModels(tables), rows)
115
137
  }
116
138
 
139
+ /**
140
+ * The tables whose rows hand out access, lowercased: a relation source or a path reveal, a member-revealing table, and
141
+ * the tables a principal path or a relation's condition reads. Only the data layer writes them; the migration classifier
142
+ * refuses database code that does.
143
+ */
144
+ export function accessTables<DB, P>(tables: Tables<DB, P>): readonly string[] {
145
+ return accessTablesOf(tableModels(tables))
146
+ }
147
+
117
148
  /** Every table's policy in the form the contract artifact carries, by table name. */
118
149
  export type TablePolicies = Readonly<Record<string, TablePolicyArtifact>>
119
150
 
@@ -157,7 +188,117 @@ function artifactOf(model: TableModel): TablePolicyArtifact {
157
188
  columns,
158
189
  ...(ownKeys(model.files).length === 0 ? {} : { files: { ...model.files } }),
159
190
  ...(model.view ? { view: true } : {}),
191
+ ...(model.confers.length === 0 ? {} : { confers: confersArtifact(model.confers) }),
192
+ ...(ownKeys(model.when).length === 0 ? {} : { when: whenArtifact(model.when) }),
193
+ ...(ownKeys(model.relationWhen).length === 0 ? {} : { relationWhen: relationWhenArtifact(model.relationWhen) }),
194
+ ...(model.reveals.length === 0 ? {} : { reveals: revealsArtifact(model.reveals) }),
195
+ ...(model.readThrough.length === 0 ? {} : { readThrough: readThroughArtifact(model) }),
196
+ ...writeThroughArtifact(model),
197
+ ...(model.memberReveals.length === 0 ? {} : { memberReveals: memberRevealsArtifact(model.memberReveals) }),
198
+ ...(model.access.length === 0 ? {} : { access: accessArtifact(model.access) }),
199
+ }
200
+ }
201
+
202
+ function accessArtifact(access: readonly AccessModel[]): Record<string, AccessArtifact> {
203
+ const artifact: Record<string, AccessArtifact> = {}
204
+ for (let index = 0; index < access.length; index++) {
205
+ const entry = access[index]
206
+ if (entry !== undefined) {
207
+ setOwn(artifact, entry.relation, { view: entry.view, row: entry.row, principal: entry.principal ?? null, member: entry.member ?? null })
208
+ }
209
+ }
210
+ return artifact
211
+ }
212
+
213
+ function memberRevealsArtifact(reveals: readonly MemberRevealModel[]): Record<string, MemberRevealsArtifact> {
214
+ const artifact: Record<string, MemberRevealsArtifact> = {}
215
+ for (let index = 0; index < reveals.length; index++) {
216
+ const reveal = reveals[index]
217
+ if (reveal === undefined) continue
218
+ setOwn(artifact, reveal.source, {
219
+ to: reveal.dimension,
220
+ actions: [...reveal.actions],
221
+ ...(reveal.when === undefined ? {} : { when: conditionArtifact(reveal.when) }),
222
+ ...(reveal.assign === undefined ? {} : { assign: { self: reveal.assign.self } }),
223
+ })
224
+ }
225
+ return artifact
226
+ }
227
+
228
+ function readThroughArtifact(model: TableModel): Record<string, string> {
229
+ const artifact: Record<string, string> = {}
230
+ for (let index = 0; index < model.readThrough.length; index++) {
231
+ const path = model.readThrough[index]
232
+ if (path !== undefined) setOwn(artifact, path.dimension, path.via === undefined ? path.column : `${path.via.column}.${path.column}`)
233
+ }
234
+ return artifact
235
+ }
236
+
237
+ function writeThroughArtifact(model: TableModel): { readonly writeThrough: Record<string, string[]> } | undefined {
238
+ const artifact: Record<string, string[]> = {}
239
+ let declared = false
240
+ for (let index = 0; index < model.readThrough.length; index++) {
241
+ const path = model.readThrough[index]
242
+ if (path === undefined || path.writes.length === 0) continue
243
+ setOwn(artifact, path.dimension, [...path.writes])
244
+ declared = true
245
+ }
246
+ return declared ? { writeThrough: artifact } : undefined
247
+ }
248
+
249
+ function revealsArtifact(reveals: readonly RevealModel[]): Record<string, RevealsArtifact> {
250
+ const artifact: Record<string, RevealsArtifact> = {}
251
+ for (let index = 0; index < reveals.length; index++) {
252
+ const reveal = reveals[index]
253
+ if (reveal === undefined) continue
254
+ setOwn(artifact, reveal.relation, {
255
+ to: reveal.dimension,
256
+ actions: [...reveal.actions],
257
+ ...(reveal.when === undefined ? {} : { when: conditionArtifact(reveal.when) }),
258
+ ...(reveal.assign === undefined ? {} : { assign: { self: reveal.assign.self } }),
259
+ })
260
+ }
261
+ return artifact
262
+ }
263
+
264
+ function confersArtifact(sources: readonly RelationSource[]): Record<string, ConfersArtifact> {
265
+ const confers: Record<string, ConfersArtifact> = {}
266
+ for (let index = 0; index < sources.length; index++) {
267
+ const source = sources[index]
268
+ if (source === undefined) continue
269
+ setOwn(confers, source.relation, {
270
+ principal: source.principalPath === undefined ? source.principal : `${source.principal}.${source.principalPath.column}`,
271
+ node: source.node,
272
+ expires: source.expires ?? null,
273
+ ...(source.when === undefined ? {} : { when: conditionArtifact(source.when) }),
274
+ assign: source.assign === undefined ? null : { maxDays: source.assign.maxDays ?? null, self: source.assign.self },
275
+ })
276
+ }
277
+ return confers
278
+ }
279
+
280
+ function whenArtifact(when: Readonly<Record<string, ConditionModel>>): Record<string, ConditionArtifact> {
281
+ const artifact: Record<string, ConditionArtifact> = {}
282
+ const actions = ownKeys(when)
283
+ for (let index = 0; index < actions.length; index++) {
284
+ const action = actions[index] ?? ''
285
+ const condition = ownEntry(when, action)
286
+ if (condition !== undefined) setOwn(artifact, action, conditionArtifact(condition))
287
+ }
288
+ return artifact
289
+ }
290
+
291
+ function relationWhenArtifact(
292
+ relationWhen: Readonly<Record<string, Readonly<Record<string, ConditionModel>>>>,
293
+ ): Record<string, Record<string, ConditionArtifact>> {
294
+ const artifact: Record<string, Record<string, ConditionArtifact>> = {}
295
+ const relations = ownKeys(relationWhen)
296
+ for (let index = 0; index < relations.length; index++) {
297
+ const relation = relations[index] ?? ''
298
+ const conditions = ownEntry(relationWhen, relation)
299
+ if (conditions !== undefined) setOwn(artifact, relation, whenArtifact(conditions))
160
300
  }
301
+ return artifact
161
302
  }
162
303
 
163
304
  /** One action as its text, so a single-action policy keeps the artifact and digest it had; several as a list; none as `null`. */
@@ -1,12 +1,17 @@
1
1
  // The table policies of the vocabulary form, `defineTables(vocabulary, columns)`: how an application writes them, with
2
2
  // containment taken from the vocabulary, and the normalized policies the kit and the handles read. Types only.
3
3
 
4
+ import type { ConditionPolicy } from './conditions'
4
5
  import type {
6
+ AccessPolicy,
5
7
  ColumnList,
6
8
  ColumnPolicies,
9
+ ConfersPolicy,
7
10
  FilePolicies,
11
+ MemberRevealsPolicy,
8
12
  RecordActions,
9
13
  ReferencePolicy,
14
+ RevealsPolicy,
10
15
  TableAction,
11
16
  TableActions,
12
17
  Tables,
@@ -42,6 +47,7 @@ export type ColumnViews<C> = typeof viewNames extends keyof C
42
47
  export interface TableVocabulary {
43
48
  readonly actions: { readonly [action: string]: string }
44
49
  readonly dimensions: { readonly [dimension: string]: { readonly in?: string } }
50
+ readonly relations?: { readonly [relation: string]: { readonly dimension: string } }
45
51
  }
46
52
 
47
53
  export type VocabularyAction<V> = V extends { readonly actions: infer A } ? keyof A & string : never
@@ -96,6 +102,28 @@ interface WritableFields<Col extends string, A extends string, Ver extends Col,
96
102
  readonly columns?: ColumnPolicies<Col, A>
97
103
  /** The file columns, each with the file kind it holds (`c.files`): a `uuid` foreign key to `fabrika_files`. */
98
104
  readonly files?: FilePolicies<Col>
105
+ /** Relation → how a row of this table confers it: whom it names, at which node, until when. */
106
+ readonly confers?: { readonly [relation: string]: ConfersPolicy<Col> }
107
+ /** Action → the condition a row must meet for it, whoever holds it. */
108
+ readonly when?: { readonly [action in A]?: ConditionPolicy<Col> }
109
+ /** Relation → action → the condition a row that relation reaches must meet for it; IAM grants are not narrowed. */
110
+ readonly relationWhen?: { readonly [relation: string]: { readonly [action in A]?: ConditionPolicy<Col> } }
111
+ /** Relation of the table's own dimension → the ancestor node a row it reaches reveals, and for which actions. */
112
+ readonly reveals?: { readonly [relation: string]: RevealsPolicy<Col, A> }
113
+ /**
114
+ * Dimension outside the chain → the foreign key column a `Within`'s read reaches a row through, no update writes it; or
115
+ * `<nearest container column>.<its column>`, the nearest container's own path.
116
+ */
117
+ readonly readThrough?: { readonly [dimension: string]: Col | `${Col}.${string}` }
118
+ /**
119
+ * Dimension of `readThrough` → the actions a `Ref` held through that path holds, writes included; whoever inserts the
120
+ * path's column must hold each at the node it names.
121
+ */
122
+ readonly writeThrough?: { readonly [dimension: string]: readonly A[] }
123
+ /** The table's own dimension → the ancestor node a row reveals to a grant at its node, for a `Within`'s reads. */
124
+ readonly memberReveals?: { readonly [dimension: string]: MemberRevealsPolicy<Col, A> }
125
+ /** Relation → the access view that lists the rows it reaches: the escape path, decided by the view's SQL. */
126
+ readonly access?: { readonly [relation: string]: AccessPolicy }
99
127
  }
100
128
 
101
129
  /**
@@ -167,9 +195,15 @@ interface ReadOnlyFields<Col extends string, A extends string> {
167
195
  readonly columns?: { readonly [C in Col]?: { readonly read: A; readonly write?: never } }
168
196
  }
169
197
 
170
- /** A view read as a child table: its parent's `Ref` and `Within` read it; nothing writes it (ADR-0072). */
198
+ /**
199
+ * A view read as a child table: its parent's `Ref` and `Within` read it; nothing writes it (ADR-0072). Its `when` and
200
+ * `relationWhen` narrow its read actions; a path may start at its parent column, to the parent row.
201
+ */
171
202
  type AuthoredChildViewPolicy<Table extends string, Col extends string, A extends string, S, P> = ReadOnlyFields<Col, A> & {
172
203
  readonly scope: ChildScopes<Table, Col, S, P>
204
+ readonly when?: { readonly [action in A]?: ConditionPolicy<Col> }
205
+ /** Relation → action → the condition a row the relation reaches through the parent row must meet for it. */
206
+ readonly relationWhen?: { readonly [relation: string]: { readonly [action in A]?: ConditionPolicy<Col> } }
173
207
  }
174
208
 
175
209
  /** A view's policy as written: a read-only child, or a reference table every site reads. */
@@ -0,0 +1,141 @@
1
+ import { type OperationNode } from 'kysely';
2
+ import type { ContainerGrant, RefGrant, RelationHold, WithinGrant } from './capability';
3
+ import type { ConditionModel } from './conditions';
4
+ import type { ViewParentLink } from './guard';
5
+ import { type Container, type MemberRevealModel, type RelationSource, type RevealModel, type SecondaryPath, type TableModel } from './policy';
6
+ /** A relation of the layer: its source table, and the tables whose rows it reaches reveal an ancestor node. */
7
+ export interface LayerRelation extends RelationSource {
8
+ readonly kind: 'source';
9
+ readonly reveals: readonly RevealModel[];
10
+ /** The actions some table's `relationWhen` narrows the relation for: it holds them only on the rows that condition admits. */
11
+ readonly narrowed: readonly string[];
12
+ /**
13
+ * The source's and each reveal table's column for every dimension a row of it lies at, by table: where a hold inside
14
+ * a node finds whether a row that holds a destination lies inside that node.
15
+ */
16
+ readonly placed: Readonly<Record<string, Readonly<Record<string, string>>>>;
17
+ }
18
+ /** A relation no table confers: only access views decide what it reaches, so it has no source row to check or lock. */
19
+ export interface AccessRelation {
20
+ readonly kind: 'access';
21
+ readonly relation: string;
22
+ readonly dimension: string;
23
+ readonly narrowed: readonly string[];
24
+ }
25
+ /** Every relation of the layer, by name, with its source table, or the mark that only access views serve it. */
26
+ export type RelationSources = Readonly<Record<string, LayerRelation | AccessRelation>>;
27
+ /** Every member reveal of the layer, by the dimension whose grants it reveals to. */
28
+ export type MemberReveals = Readonly<Record<string, readonly MemberRevealModel[]>>;
29
+ /** What a capability is held through beyond its grants: the layer's relations and its member reveals. */
30
+ export interface LayerReach {
31
+ readonly relations: RelationSources;
32
+ readonly members: MemberReveals;
33
+ }
34
+ export declare function relationSource(relations: RelationSources, relation: string): LayerRelation;
35
+ /** The relation by name, conferred or served by access views; one the layer does not know is unenforceable, never ignored. */
36
+ export declare function knownRelation(relations: RelationSources, relation: string): LayerRelation | AccessRelation;
37
+ /** A source row that confers its relation now: unexpired, and admitted by the relation's own condition. */
38
+ export declare function activeRow(source: RelationSource, now: Date): readonly OperationNode[];
39
+ /**
40
+ * A source row naming `principal`: `S.<principal> = $me`, or through its path `S.<column> in (select P.<key> from P where
41
+ * P.<column> = $me)`. Every check of a source row's principal is built here.
42
+ */
43
+ export declare function namesPrincipal(source: RelationSource, principal: string): OperationNode;
44
+ export declare function isIn(table: string, name: string, nodes: OperationNode): OperationNode;
45
+ /**
46
+ * The rows of `table` whose `path` column names one of `nodes` of `dimension`: `T.<column> in (nodes)` at the path's own
47
+ * dimension, `T.<column> in (select D.<key> from D where D.<link> in (nodes))` at one above it; `undefined` elsewhere. A
48
+ * path through the nearest container reads the container's: `T.<link> in (select C.<key> from C where <C's term>)`.
49
+ */
50
+ export declare function throughPath(table: string, path: SecondaryPath, dimension: string, nodes: OperationNode): OperationNode | undefined;
51
+ /** `select R.<ancestor> from R where R.<key> in (<the relation's nodes>) and <when>`: the nodes a reveal holds `principal` at. */
52
+ export declare function revealedNodes(source: RelationSource, reveal: RevealModel, principal: string, now: Date): OperationNode;
53
+ /** Which secondary paths a statement follows: every one for a `Within`'s read, `heldThrough` for a `Ref`, none for a move. */
54
+ export type PathRule = (path: SecondaryPath) => boolean;
55
+ export declare const everyPath: PathRule;
56
+ export declare const noPath: PathRule;
57
+ /** The paths that hold `action` for a `Ref` (`writeThrough`). */
58
+ export declare function heldThrough(action: string): PathRule;
59
+ /**
60
+ * The rows of `model` a relation reaches for `principal` under `action`: `T.<node> in (select S.<node> from S where
61
+ * S.<principal> = $me and <active>)` where `model` lies at a node of the relation's dimension, and one
62
+ * `T.<ancestor> in (<revealed nodes>)` per reveal of `action` to an ancestor `model` lies at. Empty where neither holds.
63
+ * It also follows the secondary paths `paths` admits: the column `model` reaches the relation's dimension through, and
64
+ * the reveals matched through one. A hold inside a node narrows each term to the rows inside it, by `model`'s own
65
+ * column for the hold's dimension, and reaches none where `model` has no such column. Where `model`'s `relationWhen`
66
+ * narrows the relation for `action`, each term carries that condition too: `(<term> and (<narrowing>))`, so no builder
67
+ * of a relation's reach leaves either out.
68
+ */
69
+ export declare function relationTerms(relations: RelationSources, model: TableModel, hold: RelationHold, principal: string, action: string, now: Date, paths: PathRule): readonly OperationNode[];
70
+ /**
71
+ * The rows of `model` its access views list for `hold`, each carrying the relation's `relationWhen` for `action`. A view
72
+ * bound to the hold's node decides which rows lie inside it, so the table's own column does not narrow it; a view bound
73
+ * to the principal alone is narrowed to the node by that column, and reaches nothing where `model` has none.
74
+ */
75
+ export declare function accessReach(model: TableModel, hold: RelationHold, principal: string, action: string, now: Date): readonly OperationNode[];
76
+ /** `holds` without those of a relation `narrowed` names: the holds no `relationWhen` narrows. */
77
+ export declare function holdsBesides(holds: readonly RelationHold[], narrowed: readonly string[]): readonly RelationHold[];
78
+ /** The condition `model`'s `relationWhen` puts on the rows `relation` reaches for `action`, if any. */
79
+ export declare function relationCondition(model: TableModel, relation: string, action: string): ConditionModel | undefined;
80
+ /** `(<term> and (<narrowing>))`: one branch of a reach, narrowed; the one shape the guard admits a branch's condition in. */
81
+ export declare function narrowedTerm(term: OperationNode, narrowing: OperationNode): OperationNode;
82
+ /**
83
+ * The rows of `model` a `Within`'s read reaches through member reveals: `revealingTerms` of its grants at revealing
84
+ * dimensions.
85
+ */
86
+ export declare function memberTerms(members: MemberReveals, model: TableModel, grant: WithinGrant, now: Date): readonly OperationNode[];
87
+ /**
88
+ * The rows of `model` that `revealing`, grants of `action` at nodes of revealing dimensions, reach through member
89
+ * reveals: per grant, `T.<ancestor> in (select R.<ancestor> from R where R.<key> in (values) and <when>)` for each reveal
90
+ * of `action` to an ancestor `model` lies at, `R.<key>` the row's key or its path's column. A reveal through a path
91
+ * counts where `paths` admits it. A grant at a dimension that reveals no node for `action` is refused: the framework
92
+ * passes none.
93
+ */
94
+ export declare function revealingTerms(members: MemberReveals, model: TableModel, holder: string, action: string, revealing: readonly ContainerGrant[], now: Date, paths: PathRule): readonly OperationNode[];
95
+ /** `select R.<ancestor> from R where R.<key> in (values) and <when>`: the nodes a member reveal holds at for `values`. */
96
+ export declare function memberRevealed(reveal: MemberRevealModel, values: readonly string[], now: Date): OperationNode;
97
+ /** The condition `action` holds a row of `model` under, or `undefined` when the action is not narrowed there. */
98
+ export declare function actionCondition(model: TableModel, action: string, now: Date): OperationNode | undefined;
99
+ /**
100
+ * `branch`, narrowed by the condition of `action`: `<reach> and (<when>)`, for a global grant `true and (<when>)`, the
101
+ * one shape the guard admits a condition in, so a condition never stands in for the reach.
102
+ */
103
+ export declare function conditioned(model: TableModel, action: string, branch: OperationNode | 'all', now: Date): OperationNode;
104
+ /**
105
+ * A Ref's predicate over `links` of `model`: one equality per link of its chain (after `row`, the equality that
106
+ * addresses one row by its key), then, when the Ref is held through relations or member reveals, a row of one of them
107
+ * at the node, and its action's condition. A Ref whose relations, revealing grants and paths together reach no row of
108
+ * `model` is unenforceable there, never unconditioned.
109
+ */
110
+ export declare function refScope(reach: LayerReach, model: TableModel, links: readonly Container[], grant: RefGrant, now: Date, row?: OperationNode, paths?: PathRule): OperationNode;
111
+ /** A child view's parent reach, split by the relations the view narrows: the rest's reach, and each such relation's own. */
112
+ export interface SplitReach {
113
+ readonly rest: OperationNode | undefined;
114
+ readonly relations: readonly {
115
+ readonly reached: OperationNode;
116
+ readonly condition: ConditionModel;
117
+ }[];
118
+ }
119
+ /**
120
+ * The rows of a child view whose parent row `reached` admits: `V.<column> in (select P.<key> from P where <reached>)`,
121
+ * after `row` when it addresses one row, then the view's own condition of `action`. For `all`, every parent row, so a
122
+ * row whose parent column names none is still read by no capability. Split by the relations the view narrows
123
+ * (`relationWhen`), one such membership per part, each narrowed relation's ANDed with the view's condition for it. No
124
+ * column of the view places a row: its containment rests on the parent's foreign keys (ADR-0072).
125
+ */
126
+ export declare function viewScope(model: TableModel, parent: ViewParentLink, action: string, reached: OperationNode | 'all' | SplitReach | undefined, now: Date, row?: OperationNode, access?: readonly OperationNode[]): OperationNode;
127
+ /**
128
+ * The rows a Ref held through relations, member reveals or secondary paths needs at `model`: a relation row at the node,
129
+ * a revealing row the Ref's grants reveal it through, or a path `paths` admits naming a node its grants hold;
130
+ * `undefined` for a Ref an IAM grant holds on its chain. A part that reaches no row of `model` adds nothing; when none
131
+ * does, the Ref is unenforceable there, never unconditioned.
132
+ */
133
+ export declare function relationGate(reach: LayerReach, model: TableModel, grant: RefGrant, now: Date, paths?: PathRule): OperationNode | undefined;
134
+ /** Every term of `grant`'s relations, member reveals and paths at `model`; empty where none reaches it. */
135
+ export declare function gateTerms(reach: LayerReach, model: TableModel, grant: RefGrant, now: Date, paths: PathRule): readonly OperationNode[];
136
+ /**
137
+ * The rows of `model` whose path `paths` admits names a node `grants` hold: `T.<column> in (values)` at the path's own
138
+ * dimension, `T.<column> in (select D.<key> from D where D.<link> in (values))` above it, through the container's column
139
+ * for a path through the container.
140
+ */
141
+ export declare function pathTerms(model: TableModel, grants: readonly ContainerGrant[], paths: PathRule): readonly OperationNode[];
@@ -40,3 +40,5 @@ export declare function setOwn<V>(record: Record<string, V>, key: string, value:
40
40
  export declare function defineValue(target: object, key: string, value: unknown): void;
41
41
  /** An own property of a record, or undefined: an inherited one is never read. */
42
42
  export declare function ownEntry<V>(record: Readonly<Record<string, V>>, key: string): V | undefined;
43
+ /** A copy of a plain object's own data properties; anything else (an instance, a symbol key, an accessor) is refused. */
44
+ export declare function plainRecord(value: unknown, what: string): Readonly<Record<string, unknown>>;
@@ -47,6 +47,32 @@ export interface RefGrant {
47
47
  readonly id: string;
48
48
  /** The values of the containers this object lies in, by dimension (`workspace → w1` for a note). */
49
49
  readonly chain: ReadonlyMap<string, string>;
50
+ /**
51
+ * The relations the caller holds the action through on this object or a container, when no grant holds it: every
52
+ * statement of the Ref then also requires a row of one of them. Empty for a Ref an IAM grant holds.
53
+ */
54
+ readonly relations: readonly RelationHold[];
55
+ /**
56
+ * The caller's grants of the action at nodes whose rows reveal the object, or a container on its chain, to their
57
+ * members (`memberReveals`), when no grant holds it: every statement of the Ref then also requires such a row, as
58
+ * for `relations`. Empty for a Ref an IAM grant holds.
59
+ */
60
+ readonly revealing: readonly ContainerGrant[];
61
+ /**
62
+ * The caller's grants of the action at nodes of a dimension the object's table reads through a path that holds the
63
+ * action (`writeThrough`), or at containers of such a node, when no grant holds it on the chain: every statement then
64
+ * also requires the row to reach one of them through such a path. Empty for a Ref an IAM grant holds.
65
+ */
66
+ readonly paths: readonly ContainerGrant[];
67
+ }
68
+ /**
69
+ * A relation the caller holds the action through: anywhere (`inside: null`, a `~rel` entry), or only on rows that lie
70
+ * inside one of `inside`'s values (`~relin` entries of grants at those values): a row whose column for that dimension,
71
+ * its key at its own dimension, names one of them. A row with no such column is not inside, so the hold reaches none.
72
+ */
73
+ export interface RelationHold {
74
+ readonly relation: string;
75
+ readonly inside: ContainerGrant | null;
50
76
  }
51
77
  /** The values of one container dimension in which the caller holds the action: `organization → [o1]`. */
52
78
  export interface ContainerGrant {
@@ -75,6 +101,16 @@ export interface WithinGrant {
75
101
  * the action: a row that lies in one of their values is listed, as a single-object read of it is allowed.
76
102
  */
77
103
  readonly contained: readonly ContainerGrant[];
104
+ /**
105
+ * The relations through which the caller also holds the action (`~rel` and `~relin` entries of its token): a row lies
106
+ * in the `Within` too where a row of one of them names the caller at the row's node, read by the statement itself.
107
+ */
108
+ readonly relations: readonly RelationHold[];
109
+ /**
110
+ * The caller's grants of the action at nodes whose rows reveal the `Within`'s dimension or a container of it to their
111
+ * members (`memberReveals`): a row under a node such a row reveals is read too, the statement judging the revealing row.
112
+ */
113
+ readonly revealing: readonly ContainerGrant[];
78
114
  }
79
115
  /** An `app` endpoint's grant: the action everywhere in the application, which the proxy checked was held globally. */
80
116
  export interface AppGrant {
@@ -116,4 +152,10 @@ export interface CapabilityAuthority {
116
152
  * request. Every mutation checks it inside its own transaction.
117
153
  */
118
154
  fence(): LeaseFence | null;
155
+ /**
156
+ * What the caller of the work running now holds of `action` in `dimension`, as a `Within` of it would carry it, with
157
+ * no values when it holds none; `undefined` when the work has no caller (a job attempt, a webhook delivery). An
158
+ * insert that hands out access through a path judges its writer by it; an authority without the method has no caller.
159
+ */
160
+ standing?(dimension: string, action: string): WithinGrant | undefined;
119
161
  }
@@ -0,0 +1,9 @@
1
+ import { type OperationNode } from 'kysely';
2
+ import { type ConditionModel } from './conditions';
3
+ /** The predicate of `condition` over `table`'s rows; `now` is the statement's clock, bound as a value. */
4
+ export declare function conditionNode(table: string, condition: ConditionModel, now: Date): OperationNode;
5
+ /**
6
+ * `select table.key from table where <where>`: the one subquery shape the guard admits in a scope predicate. Without
7
+ * `where`, every row's key: only a child view's parent subquery takes that form.
8
+ */
9
+ export declare function subquery(table: string, key: string, where?: OperationNode): OperationNode;
@@ -0,0 +1,151 @@
1
+ import type { ConditionArtifact } from '@fabrika/auth-core';
2
+ import { type NameSet } from './builtins';
3
+ import type { Primitive } from './description';
4
+ /** A literal a condition compares with. `{ now: true }` is the statement's clock, never the text `now`. */
5
+ export type ConditionLiteral = string | number | boolean;
6
+ export interface NowOperand {
7
+ readonly now: true;
8
+ }
9
+ /** The parsed clock operand, compared by identity: no literal, the text `now` included, is ever it. */
10
+ export declare const NOW: NowOperand;
11
+ /** One test of a column: exactly one operator. */
12
+ export interface ColumnTest {
13
+ readonly eq?: ConditionLiteral;
14
+ readonly notEq?: ConditionLiteral;
15
+ readonly in?: readonly ConditionLiteral[];
16
+ readonly notIn?: readonly ConditionLiteral[];
17
+ readonly isNull?: boolean;
18
+ readonly lt?: ConditionLiteral | NowOperand;
19
+ readonly lte?: ConditionLiteral | NowOperand;
20
+ readonly gt?: ConditionLiteral | NowOperand;
21
+ readonly gte?: ConditionLiteral | NowOperand;
22
+ }
23
+ /** `{ some: { table: … } }` or `{ none: { table: … } }` at the end of a path: over the rows naming the row it reaches. */
24
+ export type RowsTest = {
25
+ readonly some: {
26
+ readonly [table: string]: ConditionPolicy;
27
+ };
28
+ } | {
29
+ readonly none: {
30
+ readonly [table: string]: ConditionPolicy;
31
+ };
32
+ };
33
+ /**
34
+ * A condition as a policy writes it: `{ column: test, … }` (all of them), `{ 'fk_column.column': test }` along a
35
+ * foreign key, `{ anyOf: […] }`, `{ allOf: […] }`, `{ not: … }`, or `{ some: { table: … } }` and `{ none: { table: … } }`
36
+ * over the rows of `table` whose foreign key names the row; `{ 'fk_column': { some: { table: … } } }` over the rows
37
+ * naming the row a path reaches.
38
+ */
39
+ export type ConditionPolicy<Col extends string = string> = {
40
+ readonly anyOf: readonly ConditionPolicy<Col>[];
41
+ } | {
42
+ readonly allOf: readonly ConditionPolicy<Col>[];
43
+ } | {
44
+ readonly not: ConditionPolicy<Col>;
45
+ } | {
46
+ readonly some: {
47
+ readonly [table: string]: ConditionPolicy;
48
+ };
49
+ } | {
50
+ readonly none: {
51
+ readonly [table: string]: ConditionPolicy;
52
+ };
53
+ } | {
54
+ readonly [C in Col | `${Col}.${string}`]?: ColumnTest | RowsTest;
55
+ };
56
+ export type ConditionOperator = 'eq' | 'notEq' | 'in' | 'notIn' | 'isNull' | 'lt' | 'lte' | 'gt' | 'gte';
57
+ /** One foreign-key hop of a path: `column` of the table it leaves references `key` of `table`. */
58
+ export interface ConditionHop {
59
+ readonly column: string;
60
+ readonly table: string;
61
+ readonly key: string;
62
+ }
63
+ export type ConditionModel = {
64
+ readonly kind: 'all';
65
+ readonly terms: readonly ConditionModel[];
66
+ } | {
67
+ readonly kind: 'any';
68
+ readonly terms: readonly ConditionModel[];
69
+ } | {
70
+ readonly kind: 'not';
71
+ readonly term: ConditionModel;
72
+ } | {
73
+ /**
74
+ * `key in (select table.column from table where <term>)`, or its negation for `none`, over the row `hops` reach
75
+ * from the condition's own row (none: the row itself).
76
+ */
77
+ readonly kind: 'some';
78
+ readonly hops: readonly ConditionHop[];
79
+ readonly negated: boolean;
80
+ readonly key: string;
81
+ readonly table: string;
82
+ readonly column: string;
83
+ readonly term: ConditionModel;
84
+ } | {
85
+ readonly kind: 'test';
86
+ readonly hops: readonly ConditionHop[];
87
+ readonly column: string;
88
+ readonly operator: ConditionOperator;
89
+ readonly value: ConditionLiteral | readonly ConditionLiteral[] | boolean | NowOperand;
90
+ };
91
+ /** What the parse reads of each table: its columns, its foreign keys and its typed columns. */
92
+ export interface ConditionTable {
93
+ readonly name: string;
94
+ readonly columns: NameSet;
95
+ readonly foreignKeys: readonly {
96
+ readonly columns: readonly string[];
97
+ readonly table: string;
98
+ readonly references: readonly string[];
99
+ }[];
100
+ readonly timestamps: NameSet;
101
+ readonly json: NameSet;
102
+ /** The columns the column list declares NOT NULL: a path under `not` follows only these. */
103
+ readonly notNull: NameSet;
104
+ }
105
+ /** A path follows at most this many foreign keys: each hop is one more subquery in every statement the condition scopes. */
106
+ export declare const MAX_CONDITION_HOPS = 3;
107
+ /**
108
+ * Whether a path may follow `from.column` to the row of `to` whose `key` it holds. A hop reads its target unscoped, so
109
+ * the rule admits only one that stays where the row is (its own container or parent), stays in its tenant (a foreign
110
+ * key that also holds every ancestor the two tables share), or reaches what every site reads (a reference table).
111
+ * `backward` is a `some` reading the rows of `from` that name a row of `to`: those must stay in that row's tenant, so
112
+ * a reference row, which every tenant's rows name, is no shortcut there.
113
+ */
114
+ export type HopRule = (from: string, column: string, to: string, key: string, backward: boolean) => boolean;
115
+ /** Parses `input` as a condition over `table`. `hops` is the rule a path's foreign keys are held to. */
116
+ export declare function parseCondition(input: unknown, table: ConditionTable, tables: (name: string) => ConditionTable | undefined, what: string, hops: HopRule): ConditionModel;
117
+ export declare function splitPath(path: string): readonly string[];
118
+ export declare function singleForeignKey(table: ConditionTable, name: string, what: string): ConditionHop;
119
+ /** The tables a condition's subqueries read, each with the column it selects: what the guard admits under it. */
120
+ export declare function conditionReach(condition: ConditionModel, select: (table: string, column: string) => void): void;
121
+ /** A test's single literal; a list is compared only with in or notIn. */
122
+ export declare function scalar(value: ConditionLiteral | readonly ConditionLiteral[] | boolean | NowOperand): ConditionLiteral;
123
+ /**
124
+ * One step of the rows an insert's condition reads: from the rows reached so far, the rows of `table` whose `to` column
125
+ * holds their `from` column. A path's hop goes to the row a foreign key names (`from` the key column, `to` the target's
126
+ * key); a `some` goes back to the rows naming it (`from` the referenced key, `to` the naming column).
127
+ */
128
+ export interface ReadStep {
129
+ readonly from: string;
130
+ readonly table: string;
131
+ readonly to: string;
132
+ }
133
+ /**
134
+ * Every sequence of steps from an insert's own row to the rows its condition reads, each one no other extends: the rows
135
+ * the insert locks, step by step, before it judges them. Empty when the condition reads the row alone.
136
+ */
137
+ export declare function readPaths(condition: ConditionModel): readonly (readonly ReadStep[])[];
138
+ /**
139
+ * Why `condition` cannot be judged on an inserted row, or `undefined` when it can. The insert locks every row its
140
+ * condition reads, which holds a column test and a row a `some` found until the commit, but not a row inserted meanwhile:
141
+ * that turns `none`, and a `some` under `not`, false. And no row names the inserted row before it exists.
142
+ */
143
+ export declare function insertProblem(condition: ConditionModel, table: string): string | undefined;
144
+ /**
145
+ * The value of `condition` on an insert's own row, under SQL's three-valued logic: a NULL compared is unknown, `not`
146
+ * of unknown stays unknown, and only `true` passes. A condition with a path is judged in SQL on the written row instead.
147
+ */
148
+ export declare function rowSatisfies(condition: ConditionModel, row: ReadonlyMap<string, Primitive | null>, now: Date): boolean;
149
+ export declare function hasOwnCondition(record: Readonly<Record<string, ConditionModel>>, action: string): boolean;
150
+ /** A condition as the artifact records it: the policy's own form, a path written back as `fk_column.column`. */
151
+ export declare function conditionArtifact(condition: ConditionModel): ConditionArtifact;
@@ -1,3 +1,4 @@
1
+ import type { OperationNode } from 'kysely';
1
2
  import { type NameSet } from './builtins';
2
3
  export type Primitive = string | number | bigint | boolean | Date;
3
4
  export type ComparisonOperator = '=' | '<>' | '<' | '<=' | '>' | '>=';
@@ -45,6 +46,8 @@ export interface JoinShape {
45
46
  export interface JoinState {
46
47
  readonly join: JoinShape;
47
48
  readonly select: SelectState;
49
+ /** The child's condition for the action the select holds, which the layer adds to the ON; never the builder's. */
50
+ readonly condition?: OperationNode;
48
51
  }
49
52
  export interface SelectState {
50
53
  /** Identifies the description a callback received, so it cannot return one from elsewhere. */
@@ -11,7 +11,7 @@ export type { DeliveryClaim, NewWebhookBinding, WebhookBinding, WebhookTables }
11
11
  export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases';
12
12
  export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes';
13
13
  export type { DataAccess, DataHandles, DataSite } from './orm';
14
- export type { FrameworkTables, Locator, ProvisionalBinding } from './registry';
14
+ export type { FrameworkTables, Locator, MemberRevealCheck, PathCheck, ProvisionalBinding, RelationCheck, RevealCheck } from './registry';
15
15
  export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql';
16
16
  export type { FileColumnRef, QuarantinedStoredFile, ServedFile, StagedFile, StoredFileMeta, StoredFiles, StoredFileStatus } from './stored-files';
17
17
  /** Whether `value` is an object `scoped(tables)` created, rather than a look-alike with the same fields. */