foldkit-guard 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +659 -2
- package/dist/agent.d.mts +39 -0
- package/dist/agent.d.mts.map +1 -0
- package/dist/agent.mjs +56 -0
- package/dist/agent.mjs.map +1 -0
- package/dist/attach-COgJIox7.mjs +272 -0
- package/dist/attach-COgJIox7.mjs.map +1 -0
- package/dist/attach-q8S9tsHk.d.mts +435 -0
- package/dist/attach-q8S9tsHk.d.mts.map +1 -0
- package/dist/condition-C6Czs2Xn.mjs +213 -0
- package/dist/condition-C6Czs2Xn.mjs.map +1 -0
- package/dist/drizzle.d.mts +20 -0
- package/dist/drizzle.d.mts.map +1 -0
- package/dist/drizzle.mjs +97 -0
- package/dist/drizzle.mjs.map +1 -0
- package/dist/index.d.mts +2 -0
- package/dist/index.mjs +150 -0
- package/dist/index.mjs.map +1 -0
- package/dist/may-DK-2lomO.mjs +76 -0
- package/dist/may-DK-2lomO.mjs.map +1 -0
- package/dist/placed-Bs_mnBTF.mjs +39 -0
- package/dist/placed-Bs_mnBTF.mjs.map +1 -0
- package/dist/server.d.mts +125 -0
- package/dist/server.d.mts.map +1 -0
- package/dist/server.mjs +522 -0
- package/dist/server.mjs.map +1 -0
- package/dist/sync.d.mts +81 -0
- package/dist/sync.d.mts.map +1 -0
- package/dist/sync.mjs +174 -0
- package/dist/sync.mjs.map +1 -0
- package/package.json +101 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Patrick Glenn
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,660 @@
|
|
|
1
|
-
#
|
|
1
|
+
# foldkit-guard
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Who may do what, declared once on a Foldkit Plus domain, and enforced on every
|
|
4
|
+
path a row is read or written by. [`guard-DESIGN.md`](../../docs/design/guard-DESIGN.md)
|
|
5
|
+
explains the design and why.
|
|
6
|
+
|
|
7
|
+
## What it is
|
|
8
|
+
|
|
9
|
+
Authorization in an application is usually several callbacks, one per seam,
|
|
10
|
+
each with its own idea of who is asking. A guard set says it once, in the
|
|
11
|
+
shared domain code the client imports too, and keeps the rule's logic on the
|
|
12
|
+
server:
|
|
13
|
+
|
|
14
|
+
- a **principal guard** is declared by name; its body is supplied only on the
|
|
15
|
+
server, so it never ships to the browser;
|
|
16
|
+
- a **row guard** is an `Expr` over one Entity's fields, with the principal's
|
|
17
|
+
fields as inputs. It is data, so the SQL compiler and `evaluate` run it, and
|
|
18
|
+
the client may hold it without learning anything a query does not.
|
|
19
|
+
|
|
20
|
+
## What it owns, and what it does not
|
|
21
|
+
|
|
22
|
+
| Fact | Owner |
|
|
23
|
+
| --- | --- |
|
|
24
|
+
| Who is asking | your authentication, which provides it as `G.Principal` |
|
|
25
|
+
| Who may do what | the guard set: declared once, in the shared domain code |
|
|
26
|
+
| A principal guard's body | `G.implement`, on the server only |
|
|
27
|
+
| Which rows a read returns | each binding's `visible`, compiled from the rules |
|
|
28
|
+
| Enforcement | each seam of `foldkit-remote-server`, `-drizzle` and `foldkit-sync`, through this package's subpaths |
|
|
29
|
+
| What a client shows as allowed | the server's `may` answer; no rule runs on a client |
|
|
30
|
+
|
|
31
|
+
It does not authenticate, and it does not trust the client: a hint the client
|
|
32
|
+
reads (`may`) is the server's answer, and the server checks every write
|
|
33
|
+
again when it is made.
|
|
34
|
+
|
|
35
|
+
## Mental model
|
|
36
|
+
|
|
37
|
+
```text
|
|
38
|
+
shared (client and server) server only
|
|
39
|
+
Guards.declare names and Exprs G.implement principal guards' bodies ──> Policy
|
|
40
|
+
Guards.attach the rules on an Entity
|
|
41
|
+
│
|
|
42
|
+
└─> every seam reads the same rules, decided by the same Policy:
|
|
43
|
+
reads GuardDrizzle.visible, GuardServer.memory which rows
|
|
44
|
+
GuardServer.filter members, relations, may
|
|
45
|
+
writes GuardServer.writer, GuardServer.mutation checked before, read back after
|
|
46
|
+
Sync GuardSync.authorize, admit, opens edits through the journal
|
|
47
|
+
agents GuardAgent reads may
|
|
48
|
+
startup GuardServer.validate every guarded Source is guarded
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
A rule is decided in two steps: each principal guard by its body, once per
|
|
52
|
+
request, then what is left, row guards, as a condition over the row that SQL
|
|
53
|
+
or an evaluator runs. That split is why row guards are data and principal
|
|
54
|
+
guards are names.
|
|
55
|
+
|
|
56
|
+
## Install
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
pnpm add effect foldkit-entity foldkit-guard
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
`foldkit-guard` is the shared declaration. Its subpaths bring their packages
|
|
63
|
+
as optional peers: `foldkit-guard/server` needs `foldkit-remote` and
|
|
64
|
+
`foldkit-remote-server`, `/drizzle` also `foldkit-remote-drizzle` and
|
|
65
|
+
`drizzle-orm`, `/sync` `foldkit-sync` and `foldkit-remote-server`, and
|
|
66
|
+
`/agent` `foldkit-remote`.
|
|
67
|
+
|
|
68
|
+
## Sixty seconds
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
import { Effect, Option, Schema } from 'effect'
|
|
72
|
+
import { Entity, Expr } from 'foldkit-entity'
|
|
73
|
+
import { Guards } from 'foldkit-guard'
|
|
74
|
+
|
|
75
|
+
const User = Schema.Struct({
|
|
76
|
+
id: Schema.String,
|
|
77
|
+
role: Schema.Literals(['admin', 'member']),
|
|
78
|
+
projectIds: Schema.Array(Schema.String),
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
const TodoFields = Entity.define(
|
|
82
|
+
'Todo',
|
|
83
|
+
Schema.Struct({
|
|
84
|
+
id: Schema.String,
|
|
85
|
+
ownerId: Schema.String,
|
|
86
|
+
projectId: Schema.String,
|
|
87
|
+
title: Schema.String,
|
|
88
|
+
}),
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
// Shared: names and predicates, which are data.
|
|
92
|
+
const G = Guards.declare(
|
|
93
|
+
'Todos',
|
|
94
|
+
User,
|
|
95
|
+
guard => ({
|
|
96
|
+
isAdmin: guard.principal(),
|
|
97
|
+
isOwner: guard.row(TodoFields, p => Expr.eq(TodoFields.fields.ownerId, p.id)),
|
|
98
|
+
inProject: guard.row(TodoFields, p => Expr.in(TodoFields.fields.projectId, p.projectIds)),
|
|
99
|
+
}),
|
|
100
|
+
{ key: user => user.id },
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
// Server: the body of every principal guard, and nothing else.
|
|
104
|
+
const Policy = G.implement({
|
|
105
|
+
isAdmin: principal => Option.exists(principal, user => user.role === 'admin'),
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
Effect.runSync(
|
|
109
|
+
Policy.decide(G.isOwner, {
|
|
110
|
+
principal: Option.some({ id: 'ada', role: 'member', projectIds: [] }),
|
|
111
|
+
interaction: 'Read',
|
|
112
|
+
row: { id: 't1', ownerId: 'ada', projectId: 'p1', title: 'Write the README' },
|
|
113
|
+
}),
|
|
114
|
+
) // true
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
What each call does, and does not:
|
|
118
|
+
|
|
119
|
+
- `Guards.declare` reads nothing and stores nothing. It builds each row
|
|
120
|
+
guard's predicate once, with placeholders (`p.id` is the input
|
|
121
|
+
`principal.id`), and checks it reads only its Entity's fields. Branching on
|
|
122
|
+
a placeholder (`p.role === 'admin'`) is a type error: there is no value yet.
|
|
123
|
+
- `G.implement` is the only place a body exists. A missing or extra key is a
|
|
124
|
+
type error, and refused at runtime for a caller the types do not reach.
|
|
125
|
+
- `Policy.decide` is an `Effect` of a `Decision`: `true`, `false`, or
|
|
126
|
+
`{ allowed: false, reason }` for a refusal the caller may read. A visitor
|
|
127
|
+
is `Option.none()`, and passes no row guard that reads a principal's
|
|
128
|
+
fields; one over the row alone (`isPublished`) holds for a visitor too.
|
|
129
|
+
- `G.Principal` is the server's Context key for who is asking, an
|
|
130
|
+
`Option` of the principal; `G.key(user)` names the person, for what is
|
|
131
|
+
theirs whatever their claims, such as a cache snapshot (see
|
|
132
|
+
[Who is asking](#who-is-asking)).
|
|
133
|
+
|
|
134
|
+
## Attaching guards to an Entity
|
|
135
|
+
|
|
136
|
+
A guard set names rules; attaching says where each one applies, per surface
|
|
137
|
+
(the row, a member, a relation) and per interaction. Here a todo also has a
|
|
138
|
+
relation, `project`, which a client follows to its `Project`; it is stored as
|
|
139
|
+
the same `projectId` the row guard reads, and `Project` has no guards, so
|
|
140
|
+
anyone may read one:
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
import { Relation } from 'foldkit-entity'
|
|
144
|
+
import { Interaction } from 'foldkit-guard'
|
|
145
|
+
|
|
146
|
+
const ProjectFields = Entity.define(
|
|
147
|
+
'Project',
|
|
148
|
+
Schema.Struct({ id: Schema.String, name: Schema.String }),
|
|
149
|
+
)
|
|
150
|
+
const Related = Entity.relate(
|
|
151
|
+
{ Todo: TodoFields, Project: ProjectFields },
|
|
152
|
+
{ Todo: { project: Relation.one(ProjectFields) } },
|
|
153
|
+
)
|
|
154
|
+
const Project = Related.Project
|
|
155
|
+
|
|
156
|
+
const Archive = Interaction.make('Archive')
|
|
157
|
+
|
|
158
|
+
const Todo = Related.Todo.pipe(
|
|
159
|
+
Guards.attach(G, {
|
|
160
|
+
row: {
|
|
161
|
+
Read: [G.isOwner, G.inProject, G.isAdmin],
|
|
162
|
+
Write: [G.isOwner],
|
|
163
|
+
},
|
|
164
|
+
interactions: {
|
|
165
|
+
[Archive.key]: Guards.on([G.isAdmin], Guards.explain('Only an admin may archive.')),
|
|
166
|
+
},
|
|
167
|
+
members: { ownerId: { Update: [G.isAdmin] } },
|
|
168
|
+
}),
|
|
169
|
+
Guards.may, // the server's answer to what a reader may do: see What the client may do
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
Guards.matrix([Todo])
|
|
173
|
+
// Todo.Read: isOwner | inProject | isAdmin → not_found
|
|
174
|
+
// Todo.Create: isOwner → forbidden
|
|
175
|
+
// Todo.Update: isOwner → forbidden
|
|
176
|
+
// Todo.Delete: isOwner → forbidden
|
|
177
|
+
// Todo.Archive: isAdmin → explain("Only an admin may archive.")
|
|
178
|
+
// Todo.ownerId.Create: isAdmin → forbidden
|
|
179
|
+
// Todo.ownerId.Update: isAdmin → forbidden
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
- A surface's list is a disjunction: "owner, or project member, or admin".
|
|
183
|
+
`Guards.all(a, b)` is a conjunction as one guard. `always: [...]` is ANDed
|
|
184
|
+
after every surface's list and cannot be out-voted: a tenant boundary or
|
|
185
|
+
"signed in" belongs there.
|
|
186
|
+
- `Write` is shorthand for Create, Update and Delete. Beside it, a slot of its
|
|
187
|
+
own (`Delete`) adds its rules to Write's, and its refusal replaces Write's,
|
|
188
|
+
whichever is written first. A member's `Update` governs setting it on
|
|
189
|
+
creation too, unless the member names a `Create`.
|
|
190
|
+
- An interaction the application names (`Interaction.make('Archive')`) is
|
|
191
|
+
the row's, under `interactions`, keyed by `[Archive.key]`, so a misspelling
|
|
192
|
+
is a type error. Only a Read inherits.
|
|
193
|
+
- Each surface refuses its own way by default: a row Read answers not found,
|
|
194
|
+
so existence does not leak; a member or relation Read omits the value; a
|
|
195
|
+
write is forbidden. `Guards.on(guards, Guards.redact(value))` shows a hidden
|
|
196
|
+
member as `value` instead, typed by the member's schema;
|
|
197
|
+
`Guards.on(guards, Guards.explain(reason))` gives a refused write a sentence.
|
|
198
|
+
- `Guards.inherit('project')` makes a row's Read its `one` relation's Read.
|
|
199
|
+
- Every key is checked against the Entity: a member it lacks, a row guard over
|
|
200
|
+
another Entity, a guard of another set, or a misspelled interaction is a type
|
|
201
|
+
error where it is written.
|
|
202
|
+
- Attaching is metadata: the result is the same Entity (`Entity.same`), and
|
|
203
|
+
attaching twice appends to each surface's list and replaces its refusal.
|
|
204
|
+
- `Guards.guardFields(Todo, 'Read')` names the members a row interaction's
|
|
205
|
+
guards read, so a change to one is known to change who may.
|
|
206
|
+
- A surface with no guards on a guarded Entity falls to the set's
|
|
207
|
+
`unguarded` (`'allow'` by default); the matrix prints it `open`, or
|
|
208
|
+
`closed` under `unguarded: 'deny'`.
|
|
209
|
+
|
|
210
|
+
## Deciding reads and writes
|
|
211
|
+
|
|
212
|
+
A server asks the `Policy` which rows a principal may read. Every principal
|
|
213
|
+
guard is decided by its body (once, however many rules name it); what is
|
|
214
|
+
left is a `Condition` over the row, which an interpreter runs:
|
|
215
|
+
|
|
216
|
+
```ts
|
|
217
|
+
import { Condition } from 'foldkit-guard'
|
|
218
|
+
|
|
219
|
+
const ada = Option.some({ id: 'ada', role: 'member' as const, projectIds: ['p1'] })
|
|
220
|
+
const readable = Effect.runSync(Policy.readable(Todo, ada))
|
|
221
|
+
// isAdmin was false, so: isOwner or inProject, over each row
|
|
222
|
+
|
|
223
|
+
const t1 = { id: 't1', ownerId: 'ada', projectId: 'p9', title: 'Write the README' }
|
|
224
|
+
Condition.holds(readable, t1, Policy.inputOf(ada), () => false)
|
|
225
|
+
// true
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
- `Condition.always` and `Condition.never` are a read settled without
|
|
229
|
+
looking at rows: an admin, or a visitor whose rules all read the principal.
|
|
230
|
+
- `Condition.holds` is how an interpreter that has the rows runs it; a
|
|
231
|
+
database compiles it instead. Its last argument answers an inherited Read,
|
|
232
|
+
which only the caller can look up.
|
|
233
|
+
- `Policy.readMembers(Todo, principal, members)` decides each member's own
|
|
234
|
+
Read rule, with the refusal it shows (`Omit` or `Redact`).
|
|
235
|
+
- Writes are decided alike, each principal guard's body told the interaction:
|
|
236
|
+
`Policy.writable(Todo, principal, 'Update')` is the row's rule for it,
|
|
237
|
+
`{ condition, deny }` (`Forbidden`, or `Explain` with its sentence);
|
|
238
|
+
`Policy.writeMembers(Todo, principal, members, 'Update')` each member's;
|
|
239
|
+
`Policy.linkable(Todo, principal, 'project', 'Link')` a relation's, when it
|
|
240
|
+
has one.
|
|
241
|
+
|
|
242
|
+
## Serving reads
|
|
243
|
+
|
|
244
|
+
`foldkit-guard/server` turns the rules into `foldkit-remote-server`'s seams.
|
|
245
|
+
It is a subpath, so the shared declaration the browser imports never brings
|
|
246
|
+
the server along.
|
|
247
|
+
|
|
248
|
+
```ts
|
|
249
|
+
import { GuardServer } from 'foldkit-guard/server'
|
|
250
|
+
import { Remote } from 'foldkit-remote'
|
|
251
|
+
import { RemoteServer } from 'foldkit-remote-server'
|
|
252
|
+
|
|
253
|
+
const visitor: Option.Option<typeof User.Type> = Option.none()
|
|
254
|
+
|
|
255
|
+
const Data = Remote.define({ entities: [Todo, Project] })
|
|
256
|
+
const backend = RemoteServer.memory({
|
|
257
|
+
domain: Data,
|
|
258
|
+
rows: {
|
|
259
|
+
Todo: [{ id: 't1', ownerId: 'ada', projectId: 'p1', title: 'Write', project: 'Project:p1' }],
|
|
260
|
+
Project: [{ id: 'p1', name: 'Borealis' }],
|
|
261
|
+
},
|
|
262
|
+
principal: visitor, // reads no todo: every Read rule here needs a principal
|
|
263
|
+
...GuardServer.memory(Policy, [Todo]),
|
|
264
|
+
})
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
- A row its Read rules refuse is absent: from a read by id (the client reads
|
|
268
|
+
it as not found), from every query, and from relations, where a `one` ref
|
|
269
|
+
reads `null`. An inherited Read looks the related row up and decides it by
|
|
270
|
+
its own rules; a loop of them reads as refused.
|
|
271
|
+
- A member its own Read rule refuses is withheld (settled, so the client
|
|
272
|
+
reads it as unavailable) or shows its `redact` value. The fields the rule
|
|
273
|
+
reads are read too, so it can be decided.
|
|
274
|
+
- A relation's Read rule is decided over its parent row, as a member's is:
|
|
275
|
+
where it refuses, the relation is withheld. The rows it leads to are still
|
|
276
|
+
narrowed by their own Read rules.
|
|
277
|
+
- An Entity not listed has no guards to apply and is read by everyone.
|
|
278
|
+
- A Source of your own cannot be shown to apply the row's Read rules:
|
|
279
|
+
`GuardServer.validate` refuses one, as it refuses a `RemoteServer.entity`
|
|
280
|
+
without `GuardServer.memory`'s or `GuardDrizzle.visible`'s rule. Serve a
|
|
281
|
+
guarded Entity through one of those.
|
|
282
|
+
|
|
283
|
+
Over Drizzle, `foldkit-guard/drizzle` compiles the row's Read rules into each
|
|
284
|
+
binding's `visible`, which the binding applies on every path its table is
|
|
285
|
+
read by (by id, as a relation's target and children, counted, through a
|
|
286
|
+
query). Here `todos` and `projects` are your Drizzle tables for `Todo` and
|
|
287
|
+
`Project`; a fixture with a guarded `Project` too, run over SQLite, is
|
|
288
|
+
[`test/drizzle.test.ts`](test/drizzle.test.ts):
|
|
289
|
+
|
|
290
|
+
```ts
|
|
291
|
+
import { GuardDrizzle } from 'foldkit-guard/drizzle'
|
|
292
|
+
import { bind, source } from 'foldkit-remote-drizzle'
|
|
293
|
+
|
|
294
|
+
const visible = GuardDrizzle.visible(Policy, [Todo])
|
|
295
|
+
const Db = bind(
|
|
296
|
+
{ Todo, Project },
|
|
297
|
+
{
|
|
298
|
+
Todo: {
|
|
299
|
+
table: todos,
|
|
300
|
+
relations: { project: { field: todos.projectId } },
|
|
301
|
+
derived: { may: { supplied: true } }, // not a column: `GuardServer.filter` answers it
|
|
302
|
+
visible: visible.Todo,
|
|
303
|
+
},
|
|
304
|
+
Project: { table: projects },
|
|
305
|
+
},
|
|
306
|
+
)
|
|
307
|
+
const TodoSource = source(Db.Todo, { filter: GuardServer.filter(Todo, Policy) })
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
- Each principal guard is decided first; what is left is SQL. An inherited
|
|
311
|
+
Read is `project_id in (select id from projects where …)`, the related
|
|
312
|
+
table's own rule inside.
|
|
313
|
+
- It is checked when built, before any request: an inherited Read whose
|
|
314
|
+
Entity is not listed or has no Read rule, or a loop of them, throws. An
|
|
315
|
+
inherited relation must be stored as a foreign key on this table; one that
|
|
316
|
+
is not fails its first read, which is when the binding is first known.
|
|
317
|
+
- The principal reaches a binding untyped, so it is checked: one that is not
|
|
318
|
+
an `Option` of the set's schema is a defect, never read as a visitor.
|
|
319
|
+
- `visible` is the row's Read. Member and relation Reads are the Source's
|
|
320
|
+
`filter`, as `TodoSource` has it.
|
|
321
|
+
|
|
322
|
+
## Serving writes
|
|
323
|
+
|
|
324
|
+
A declared write (`Mutation.write`) is served by `RemoteServer.write` with no
|
|
325
|
+
handler. Wrap its writer, and the write rules are checked before it lands:
|
|
326
|
+
|
|
327
|
+
```ts
|
|
328
|
+
import { Write } from 'foldkit-entity'
|
|
329
|
+
import { Mutation } from 'foldkit-remote'
|
|
330
|
+
import { writer } from 'foldkit-remote-drizzle'
|
|
331
|
+
|
|
332
|
+
const EditTodo = Mutation.write(
|
|
333
|
+
'EditTodo',
|
|
334
|
+
Write.update(Entity.input(Todo, Schema.Struct({ id: Schema.String, title: Schema.String })), {
|
|
335
|
+
id: 'id',
|
|
336
|
+
}),
|
|
337
|
+
)
|
|
338
|
+
RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
- An update or a delete reads the row first, as its writer may see it. An
|
|
342
|
+
update of a row they may not see is refused; a delete of one changes
|
|
343
|
+
nothing and answers it gone, as for a row already deleted.
|
|
344
|
+
- The row's rule for the command must hold over the row, and an update's
|
|
345
|
+
over the row as it would be after it too: a write cannot move a row out of
|
|
346
|
+
its writer's reach.
|
|
347
|
+
- Each member the write sets needs its own `Create` or `Update` rule to
|
|
348
|
+
hold, and each relation it points elsewhere its `Unlink` and `Link`. What
|
|
349
|
+
a relation was linked to is read as stored (the writer's `linked`), since a
|
|
350
|
+
link to a row hidden from its writer reads to them as none; a writer that
|
|
351
|
+
cannot say treats every link it sees as none as one that may be there, so
|
|
352
|
+
changing it needs `Unlink` too.
|
|
353
|
+
- A create is checked over the values it proposes. A guard that reads a field
|
|
354
|
+
it leaves unset does not hold, whatever it asks (`isNull` and `isNotNull`
|
|
355
|
+
alike): the create never said what the field holds.
|
|
356
|
+
- A refusal is `Forbidden`, with the sentence `Guards.explain` gave; the
|
|
357
|
+
write never runs.
|
|
358
|
+
- The answer is read back under the binding's `visible` and the Entity's
|
|
359
|
+
member Read rules: the row as its writer may now see it, with no more
|
|
360
|
+
fields than the write set, and a row the write hid from them in `deleted`,
|
|
361
|
+
so the client takes it out of its lists instead of placing it.
|
|
362
|
+
|
|
363
|
+
The binding must have a `visible` rule, which is how the writer reads a row
|
|
364
|
+
as its writer may see it; the writer refuses one without. That the rule is
|
|
365
|
+
`GuardDrizzle.visible`'s is what `GuardServer.validate` checks of the
|
|
366
|
+
Entity's Source, so give the writer that Source's binding.
|
|
367
|
+
|
|
368
|
+
A client should not choose whose a new row is. `presets` sets a field from
|
|
369
|
+
who is asking on every create, before the rules are checked, so a rule over
|
|
370
|
+
it holds of the creator:
|
|
371
|
+
|
|
372
|
+
```ts
|
|
373
|
+
GuardServer.writer(Todo, Policy, writer(Db.Todo), { presets: { ownerId: user => user.id } })
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
The create's input leaves `ownerId` out; an input that sets it is refused as
|
|
377
|
+
the server's own mistake. A visitor has no one to preset from, and is refused
|
|
378
|
+
even where the rules would let anyone create. A preset must be a field of the
|
|
379
|
+
Entity, of that field's type.
|
|
380
|
+
|
|
381
|
+
A handler writes what its code writes, so it is guarded where it is defined:
|
|
382
|
+
`GuardServer.mutation` is `RemoteServer.mutation` with the row's rule for one
|
|
383
|
+
interaction checked before the handler runs.
|
|
384
|
+
|
|
385
|
+
```ts
|
|
386
|
+
const ArchiveTodo = Mutation.make('ArchiveTodo', { Input: { id: Schema.String }, Output: {} })
|
|
387
|
+
|
|
388
|
+
GuardServer.mutation(
|
|
389
|
+
ArchiveTodo,
|
|
390
|
+
{ entity: Todo, policy: Policy, interaction: Archive.key, id: input => input.id, source: TodoSource },
|
|
391
|
+
({ input, row }) => Effect.succeed({ output: {} }), // `row`: the todo, as its writer sees it
|
|
392
|
+
)
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
- The row `id` names is read through `source`, which must apply the
|
|
396
|
+
Entity's Read rules (it is refused where it is defined otherwise); a row
|
|
397
|
+
the writer may not see is refused, and the rule must hold over the rest.
|
|
398
|
+
- With no `id` (a create), the rule must hold of who is asking alone. An
|
|
399
|
+
`id` that answers an `Option` serves create and edit in one mutation (one
|
|
400
|
+
`Crud.editor` for both): `Option.none()` is a create, checked against the
|
|
401
|
+
row's `Create` rule.
|
|
402
|
+
- What the handler writes is its own to check: members it sets, relations it
|
|
403
|
+
points. `fields` reads more of the row for it.
|
|
404
|
+
- Each row of the Entity its answer carries is read back through `source`,
|
|
405
|
+
its `authorize` and `filter` applied, as a declared write's is: the answer
|
|
406
|
+
shows the writer only what they may now see of the fields it named, and a
|
|
407
|
+
row the handler hid from them answers as deleted.
|
|
408
|
+
|
|
409
|
+
## Checking a server at startup
|
|
410
|
+
|
|
411
|
+
A Source written by hand over a guarded Entity serves every row, and nothing
|
|
412
|
+
at request time can tell. `GuardServer.validate` looks before any request:
|
|
413
|
+
|
|
414
|
+
```ts
|
|
415
|
+
GuardServer.validate(Policy, { entities: [Todo], domain: Data, server: backend.server })
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
It throws, naming each:
|
|
419
|
+
|
|
420
|
+
- for an Entity of `entities` whose Source lacks the rule `GuardDrizzle.visible`
|
|
421
|
+
or `GuardServer.memory` built for it, or the `GuardServer.filter` built for
|
|
422
|
+
it;
|
|
423
|
+
- for a query listing such an Entity without the rule, and a query the server
|
|
424
|
+
serves that the domain does not declare, whose Entity no one can name;
|
|
425
|
+
- for a declared write of such an Entity that does not land through the
|
|
426
|
+
`GuardServer.writer` built for it;
|
|
427
|
+
- for a live Source of its own over such an Entity, whose stream nothing can
|
|
428
|
+
check: serve its changes through a live hub;
|
|
429
|
+
- for an Entity carrying another set's guards;
|
|
430
|
+
- for a field its Source declares `shared` (sent to every live subscriber as
|
|
431
|
+
written) when a Read rule could tell readers apart: the rows', `always`, the
|
|
432
|
+
field's own, or, for a relation, its target rows', a target not among
|
|
433
|
+
`entities` included.
|
|
434
|
+
|
|
435
|
+
A rule built from another `Policy`, for another Entity, or for this one before
|
|
436
|
+
its guards were attached does not count. Every guarded Entity's Source needs both its rule and its
|
|
437
|
+
filter, even one with no member rules yet, so a rule attached later is
|
|
438
|
+
applied rather than served past. `GuardServer.memory` gives both; over
|
|
439
|
+
Drizzle, each Source takes its `filter`, and each binding its `visible`.
|
|
440
|
+
|
|
441
|
+
A handler (`RemoteServer.mutation`) writes what its code writes, which no
|
|
442
|
+
check at startup can read.
|
|
443
|
+
|
|
444
|
+
## Who is asking
|
|
445
|
+
|
|
446
|
+
Authentication decides who is asking; guards only read it. Give the handlers
|
|
447
|
+
`G.Principal` instead of a principal, and each call reads it, so one handler
|
|
448
|
+
set answers every request, and whatever authenticates a request provides it:
|
|
449
|
+
|
|
450
|
+
```ts
|
|
451
|
+
const handlers = RemoteServer.handlers(backend.server, G.Principal)
|
|
452
|
+
|
|
453
|
+
// per request: `body` is what it sent, and authentication resolved `principal`
|
|
454
|
+
RemoteServer.answer(handlers, body).pipe(Effect.provideService(G.Principal, principal))
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
A live hub shares a re-read between subscribers with one principal. Two
|
|
458
|
+
requests by one person each decode a principal of their own, so give the hub
|
|
459
|
+
`Policy.keyOf`, which names a principal by every field, as JSON keeps it (a
|
|
460
|
+
set, a bigint, a date included; a visitor too), and they share one:
|
|
461
|
+
|
|
462
|
+
```ts
|
|
463
|
+
const hub = yield* RemoteServer.liveHub([...backend.server.entities.values()], {
|
|
464
|
+
key: Policy.keyOf,
|
|
465
|
+
})
|
|
466
|
+
```
|
|
467
|
+
|
|
468
|
+
Two principals with one key are read as the first of them, so a key that
|
|
469
|
+
named only the person (`G.key`) would read a request made after their
|
|
470
|
+
projects changed as an older request's claims; `Policy.keyOf` changes with
|
|
471
|
+
any field. On the client, a cache snapshot is scoped by the person
|
|
472
|
+
(`RemotePersistence`'s `scope: G.key(user)`), and a sign-in or sign-out is
|
|
473
|
+
`Remote.forget` (`forget` on a domain made with `Remote.make`), since every
|
|
474
|
+
fact the cache holds was read as someone.
|
|
475
|
+
|
|
476
|
+
## What the client may do
|
|
477
|
+
|
|
478
|
+
The client must not run a rule: it has no bodies, its row may be stale, and it
|
|
479
|
+
is not where a write is checked. To grey out a button for the reason the
|
|
480
|
+
server would refuse it, it reads the server's answer instead: `Guards.may`
|
|
481
|
+
adds a derived member, `may`, which `GuardServer.filter` answers from the row
|
|
482
|
+
as its reader sees it. `Todo` above is piped through it after its guards, and
|
|
483
|
+
over Drizzle its binding marks it `supplied`, since it is not a column.
|
|
484
|
+
|
|
485
|
+
```ts
|
|
486
|
+
import { May } from 'foldkit-guard'
|
|
487
|
+
|
|
488
|
+
// Select it as any member, and read it with `May`; `row` is a Todo read through `Row`.
|
|
489
|
+
const Row = Entity.select(Todo, { title: true, may: true })
|
|
490
|
+
May.can(row.may, Archive.key) // the row's rule for Archive
|
|
491
|
+
May.canSet(row.may, Todo, 'ownerId') // the row's Update, and ownerId's own
|
|
492
|
+
May.canLink(row.may, Todo, 'project', 'Link')
|
|
493
|
+
```
|
|
494
|
+
|
|
495
|
+
- It answers the row's `Update`, `Delete` and each named interaction, each
|
|
496
|
+
member with its own `Update` rule, and each relation with a `Link` or
|
|
497
|
+
`Unlink` rule, all held over the row as a write's check would hold them
|
|
498
|
+
over it as it is.
|
|
499
|
+
- A member or relation without its own rule follows the row's `Update`; an
|
|
500
|
+
interaction the answer does not name reads `false`.
|
|
501
|
+
- `May.reason(row.may, 'Delete')` is the sentence an `explain` gave a
|
|
502
|
+
refusal, `Option.none()` where the interaction is allowed or was refused
|
|
503
|
+
without one: as for a write, only an `explain` says why.
|
|
504
|
+
- It is a hint, read when the row was: a live patch of the fields its rules
|
|
505
|
+
read does not answer it again, so it is stale until the row is read again.
|
|
506
|
+
The write is checked when it is made, whatever `may` said.
|
|
507
|
+
- A Source without the filter does not answer it: the client reads it as
|
|
508
|
+
unavailable.
|
|
509
|
+
- `foldkit-crud`'s editor locks the keys the reader may not set with
|
|
510
|
+
`locks: May.locks(Todo)`, for `foldkit-mixins-form`'s `locked`.
|
|
511
|
+
|
|
512
|
+
## When a rule refuses
|
|
513
|
+
|
|
514
|
+
| Cause | Server | Client |
|
|
515
|
+
| --- | --- | --- |
|
|
516
|
+
| A row's Read refused | not returned, not settled | not found; a tombstone |
|
|
517
|
+
| A member's Read refused (`omit`) | the field settled, unread | that field `Unavailable` |
|
|
518
|
+
| A member's Read refused (`redact`) | the replacement value | `Ready` with it, by design indistinguishable |
|
|
519
|
+
| A relation's Read refused | withheld, as a member's | unavailable |
|
|
520
|
+
| A write refused | `Forbidden`, a 403 over JSON | `Data.mutation` is `Failed` with `_tag: 'Forbidden'`, `reason` from an `explain` |
|
|
521
|
+
| A write moved a row out of its writer's sight | answered in `deleted` | tombstoned; it leaves every list |
|
|
522
|
+
| A delete of a row its writer cannot see | nothing deleted; answered gone | tombstoned |
|
|
523
|
+
| A Sync edit refused | rejected by its id, with its reason | the replica drops it, with the reason |
|
|
524
|
+
| An agent's capability refused | — | `AgentAuthorizationError` before dispatch, its message an `explain`'s; not offered while `available` says no |
|
|
525
|
+
| A Source left unguarded | `GuardServer.validate` throws at startup | — |
|
|
526
|
+
|
|
527
|
+
A refusal says why only through `Guards.explain`: a plain one is `forbidden`,
|
|
528
|
+
so a probing caller learns only "no", and a row a principal may not read is
|
|
529
|
+
not found rather than forbidden, so its existence does not leak.
|
|
530
|
+
|
|
531
|
+
## Sync
|
|
532
|
+
|
|
533
|
+
A `foldkit-sync/entity` cell edit is a write to a member of a row, through the
|
|
534
|
+
journal instead of a mutation, so it answers to the same rules.
|
|
535
|
+
`foldkit-guard/sync` checks it in two halves, by where each can run, and
|
|
536
|
+
keeps a document's edits from reaching anyone the rows would hide them from:
|
|
537
|
+
|
|
538
|
+
```ts
|
|
539
|
+
import { GuardSync } from 'foldkit-guard/sync'
|
|
540
|
+
import { databaseLayer } from 'foldkit-remote-drizzle'
|
|
541
|
+
import { EditableEntity } from 'foldkit-sync/entity'
|
|
542
|
+
import { journalExchange } from 'foldkit-sync/journal'
|
|
543
|
+
|
|
544
|
+
// Edits to titles: a member with a Read rule of its own could not be one.
|
|
545
|
+
const TodoEdits = EditableEntity.make(Todo, { members: ['title'] })
|
|
546
|
+
|
|
547
|
+
// Who may open it: its readers, each in the rows' Read rule. Only an admin reads every todo.
|
|
548
|
+
const Edits = GuardSync.document(TodoEdits, { readers: [G.isAdmin] })
|
|
549
|
+
|
|
550
|
+
// Under the journal's lock: the principal's own guards, for the Sync contract's authorize.
|
|
551
|
+
const authorize = { EditedTodos: GuardSync.authorize(Policy, Edits) }
|
|
552
|
+
|
|
553
|
+
// Each exchange, as its principal: whether they may open it, and each edit against its row.
|
|
554
|
+
journalExchange({
|
|
555
|
+
sync,
|
|
556
|
+
journal,
|
|
557
|
+
principal,
|
|
558
|
+
opens: GuardSync.opens(Policy, Edits, principal),
|
|
559
|
+
admit: operation =>
|
|
560
|
+
GuardSync.admit(Policy, Edits, { principal, source: TodoSource, changesOf })(operation).pipe(
|
|
561
|
+
Effect.provide(databaseLayer(db)),
|
|
562
|
+
),
|
|
563
|
+
})
|
|
564
|
+
```
|
|
565
|
+
|
|
566
|
+
`sync` and `journal` are the document's Sync contract and journal
|
|
567
|
+
(`foldkit-sync/journal`), here with the principal as `G.Principal` holds it;
|
|
568
|
+
`changesOf` reads an operation's cell edits, and `db` is the database
|
|
569
|
+
`TodoSource` reads. A document's readers are principal guards, so of
|
|
570
|
+
`Todo`'s Read rule only `isAdmin` can be one: the rows anyone else reads
|
|
571
|
+
differ from person to person, and a document is one audience.
|
|
572
|
+
|
|
573
|
+
- **Under the lock**, `authorize` refuses what the principal guards settle:
|
|
574
|
+
the row's `Update`, and each changed member's, with an `explain`'s
|
|
575
|
+
sentence. It reads no row, and its bodies must not suspend.
|
|
576
|
+
- **Before the journal**, `admit` reads each row an edit names through the
|
|
577
|
+
Entity's guarded Source: a row the principal cannot see is refused, the
|
|
578
|
+
row's `Update` must hold over it as it is and as it would be after all of
|
|
579
|
+
the operation's edits to it, and each changed member's rule must hold. An
|
|
580
|
+
edit to a member outside the document, or a value its member cannot
|
|
581
|
+
encode, is refused.
|
|
582
|
+
- **A document is one audience.** Every replica that opens it receives every
|
|
583
|
+
edit, so `document` refuses where it is declared an edited member that is
|
|
584
|
+
not a field or has a Read rule of its own, a reader the rows' Read rule
|
|
585
|
+
does not name among its top-level guards (one inside `Guards.all` is not
|
|
586
|
+
enough: all of it must hold), rows with a Read rule and no readers named,
|
|
587
|
+
and `always` rules over the row. `opens` lets any
|
|
588
|
+
reader (anyone, when it names none) who passes the Entity's `always`.
|
|
589
|
+
- Presence on the same socket is stamped by the server with the connection's
|
|
590
|
+
peer id, and joins only who may open the document:
|
|
591
|
+
`Sync.presence.serve(socket, hub, { peerId, opens: GuardSync.opens(Policy, Edits, principal) })`.
|
|
592
|
+
What a presence value carries is the application's.
|
|
593
|
+
|
|
594
|
+
## Agents
|
|
595
|
+
|
|
596
|
+
An agent should not be offered, or attempt, what the server would refuse.
|
|
597
|
+
`foldkit-guard/agent` reads `may` from the row the Model holds, for a
|
|
598
|
+
`foldkit-agent` capability's `authorize` and `available`:
|
|
599
|
+
|
|
600
|
+
```ts
|
|
601
|
+
import { Agent } from 'foldkit-agent'
|
|
602
|
+
import { GuardAgent } from 'foldkit-guard/agent'
|
|
603
|
+
|
|
604
|
+
const TodoAgent = Agent.forApplication(App).withPrincipal(G.Principal)
|
|
605
|
+
// The Todo an id names, read through `Row` from the client's Model.
|
|
606
|
+
const todo = Remote.select(Remote.at(Data, App.model.remote), Row)
|
|
607
|
+
|
|
608
|
+
TodoAgent.expose(Message, {
|
|
609
|
+
RequestedArchive: {
|
|
610
|
+
description: 'Archive a todo',
|
|
611
|
+
authorize: GuardAgent.authorize(Archive.key, ({ input, model }) => todo(input.id).read(model)),
|
|
612
|
+
available: GuardAgent.available(Archive.key, model => todo(model.selected).read(model)),
|
|
613
|
+
},
|
|
614
|
+
})
|
|
615
|
+
```
|
|
616
|
+
|
|
617
|
+
`App` and `Message` are the client application's: its Model holds Remote's
|
|
618
|
+
store at `remote` and the selected todo's id at `selected`, and `Message`
|
|
619
|
+
has a `RequestedArchive` with the todo's `id`.
|
|
620
|
+
|
|
621
|
+
- `Row` selects `may`. A row not read yet, or whose read failed, refuses:
|
|
622
|
+
there is no answer to go on. One being read again answers as it last did.
|
|
623
|
+
A refusal its rule explained is the agent's error message.
|
|
624
|
+
- `available` is for a capability over a row the Model alone names (the one
|
|
625
|
+
selected): a visitor is then not offered it at all.
|
|
626
|
+
- `withPrincipal(G.Principal)` makes the agent's principal the server's
|
|
627
|
+
type.
|
|
628
|
+
- It is the agent's gate, not the check: the Message's mutation is checked on
|
|
629
|
+
the server, under the same principal.
|
|
630
|
+
|
|
631
|
+
## Limits
|
|
632
|
+
|
|
633
|
+
- **No rule runs on the client.** `may` is the server's answer for the row as
|
|
634
|
+
it was read, as stale as the row; a live patch of a field its rules read
|
|
635
|
+
does not answer it again.
|
|
636
|
+
- **A handler's own writes are its own to check.** `GuardServer.mutation`
|
|
637
|
+
checks the row's rule for its interaction; members it sets and relations
|
|
638
|
+
it points are not known to it, and no startup check can read them.
|
|
639
|
+
- **Under a guard, a create refetches the lists over its Entity.** The client
|
|
640
|
+
cannot tell an answer read back under the writer's rule from one a plain
|
|
641
|
+
handler made up, so it does not place a created row by the list's body
|
|
642
|
+
alone.
|
|
643
|
+
- **A Sync document is one audience.** Per-member or per-row secrecy within
|
|
644
|
+
one is not something a replicated log offers: `GuardSync.document` refuses
|
|
645
|
+
it where it is declared.
|
|
646
|
+
- **A write's check and the write are two statements.** The row is read and
|
|
647
|
+
its rules decided, then it is written; a change of owner landing between
|
|
648
|
+
them is not seen. A write that `expect`s a revision is refused once the row
|
|
649
|
+
moved; one that does not takes that window.
|
|
650
|
+
- **Sync's `admit` reads the table, which lags the journal.** An edit lands
|
|
651
|
+
in the table when its exchange settles, so an edit admitted before another
|
|
652
|
+
lands is judged against the row as it was: a concurrent change of owner
|
|
653
|
+
can let its old owner's edit through. Where that matters, keep the fields
|
|
654
|
+
a row rule reads out of the document and change them through a guarded
|
|
655
|
+
Remote write.
|
|
656
|
+
- **Sync's `authorize` is synchronous.** Its principal guards' bodies must not
|
|
657
|
+
suspend; row guards run in `admit`, which may.
|
|
658
|
+
- **A row guard over a field the client sets on create** reads as matching
|
|
659
|
+
nothing while the create leaves it unset; use a preset (`presets`) for a
|
|
660
|
+
field that should be the creator's.
|