foldkit-guard 0.5.0 → 0.7.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.
Files changed (37) hide show
  1. package/README.md +218 -44
  2. package/dist/agent.d.mts +1 -1
  3. package/dist/agent.mjs +1 -1
  4. package/dist/{attach-CRCF5XHS.mjs → attach-CEGlbWu5.mjs} +17 -2
  5. package/dist/attach-CEGlbWu5.mjs.map +1 -0
  6. package/dist/{attach-BnP9_Uca.d.mts → attach-DPgyv78F.d.mts} +87 -8
  7. package/dist/attach-DPgyv78F.d.mts.map +1 -0
  8. package/dist/{condition-Bl1UgEpM.mjs → condition-dNSbUHzE.mjs} +102 -10
  9. package/dist/condition-dNSbUHzE.mjs.map +1 -0
  10. package/dist/drizzle.d.mts +6 -4
  11. package/dist/drizzle.d.mts.map +1 -1
  12. package/dist/drizzle.mjs +18 -8
  13. package/dist/drizzle.mjs.map +1 -1
  14. package/dist/index.d.mts +1 -1
  15. package/dist/index.mjs +34 -17
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/may-DprCmMgK.mjs +200 -0
  18. package/dist/may-DprCmMgK.mjs.map +1 -0
  19. package/dist/{me-BYpuVqJE.mjs → me-C-gX1paZ.mjs} +3 -3
  20. package/dist/{me-BYpuVqJE.mjs.map → me-C-gX1paZ.mjs.map} +1 -1
  21. package/dist/media.d.mts +1 -1
  22. package/dist/{placed-BvdNmZJu.mjs → placed-CGyo-NRR.mjs} +2 -2
  23. package/dist/{placed-BvdNmZJu.mjs.map → placed-CGyo-NRR.mjs.map} +1 -1
  24. package/dist/server.d.mts +50 -17
  25. package/dist/server.d.mts.map +1 -1
  26. package/dist/server.mjs +326 -155
  27. package/dist/server.mjs.map +1 -1
  28. package/dist/sync.d.mts +5 -3
  29. package/dist/sync.d.mts.map +1 -1
  30. package/dist/sync.mjs +18 -8
  31. package/dist/sync.mjs.map +1 -1
  32. package/package.json +18 -17
  33. package/dist/attach-BnP9_Uca.d.mts.map +0 -1
  34. package/dist/attach-CRCF5XHS.mjs.map +0 -1
  35. package/dist/condition-Bl1UgEpM.mjs.map +0 -1
  36. package/dist/may-DzCAt_5M.mjs +0 -75
  37. package/dist/may-DzCAt_5M.mjs.map +0 -1
package/README.md CHANGED
@@ -25,11 +25,12 @@ server:
25
25
  | A principal guard's body | `G.implement`, on the server only |
26
26
  | Which rows a read returns | each binding's `visible`, compiled from the rules |
27
27
  | Enforcement | each seam of `foldkit-remote-server`, `-drizzle` and `foldkit-sync`, through this package's subpaths |
28
- | What a client shows as allowed | the server's `may` answer; no rule runs on a client |
28
+ | What a client shows as allowed | the server's `may` answer, foreseen by the client for a row it writes |
29
29
 
30
30
  It does not authenticate, and it does not trust the client: a hint the client
31
- reads (`may`) is the server's answer, and the server checks every write
32
- again when it is made.
31
+ reads (`may`) is the server's answer, or the client's reading of the shared
32
+ rules for a row it just wrote, and the server checks every write again when
33
+ it is made.
33
34
 
34
35
  ## Mental model
35
36
 
@@ -119,7 +120,7 @@ What each call does, and does not:
119
120
 
120
121
  - `Guards.declare` reads nothing and stores nothing. It builds each row
121
122
  guard's predicate once, with placeholders (`p.id` is the input
122
- `principal.id`), and checks it reads only its Entity's fields. Branching on
123
+ `principal.id`), and checks it is a rule over its own Entity. Branching on
123
124
  a placeholder (`p.role === 'admin'`) is a type error: there is no value yet.
124
125
  - `G.implement` is the only place a body exists. A missing or extra key is a
125
126
  type error, and refused at runtime for a caller the types do not reach.
@@ -209,6 +210,28 @@ Guards.matrix([Todo])
209
210
  `'deny'` refuses it (the matrix prints `closed`), `'allow'` lets everyone
210
211
  (`open`).
211
212
 
213
+ ### What a row guard may read
214
+
215
+ A row guard is an `Expr` over its Entity's row and the principal's fields.
216
+ Beyond the row's own fields:
217
+
218
+ - A row guard may compare a `one` relation itself, the id it points at
219
+ (`guard.row(Like, p => Expr.eq(Like.relations.user, p.id))`), so no field
220
+ repeats the link. SQL reads the relation's column; a rule judged over a
221
+ row a Source read, whose link is a ref key (`'User:ada'`), reads the id.
222
+ - A set that names the Entity its principals are rows of (`{ viewer: User }`,
223
+ each by `key`) lets a rule read who asks:
224
+ `guard.row(Like, () => Expr.eq(Like.relations.user, Expr.viewer(User)))`.
225
+ `Policy.viewer(principal)` is that row's ref, the server's one viewer:
226
+ `RemoteServer.make({ viewer: Policy.viewer })`. A rule over `Expr.viewer`
227
+ in a set without one, or over `Expr.now`, is refused where it is declared.
228
+ - A row's `Read`, `Update` and `Delete` rules may reach another row
229
+ (`Expr.path`, `Expr.exists`, a path from the viewer: `Expr.eq(Note.fields.orgId,
230
+ orgOfViewer)`). A Read rule compiles to SQL; an Update or Delete rule is
231
+ judged in the write's own statement ([Rules that read another
232
+ row](#rules-that-read-another-row)). Every other surface is judged over one
233
+ row, so `Guards.attach` refuses such a rule there.
234
+
212
235
  ## Deciding reads and writes
213
236
 
214
237
  A server asks the `Policy` which rows a principal may read. Every principal
@@ -379,7 +402,17 @@ RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
379
402
  over the row as it would be after it too: a write cannot move a row out of
380
403
  its writer's reach.
381
404
  - Each member the write sets needs its own `Create` or `Update` rule to
382
- hold, and each relation it points elsewhere its `Unlink` and `Link`. What
405
+ hold, and each relation it points elsewhere its `Unlink` and `Link`. An
406
+ update's member and `Link` rules hold over the row before and over the
407
+ row after with that one change undone: every other member's new value
408
+ and link, and this member's old value (or the relation pointing where it
409
+ did). So each change must be allowed given everything else the write does:
410
+ a write cannot set together what each change alone would be refused, and a
411
+ rule that reads its own member ("change `status` only while it is
412
+ `draft`") still allows the change it exists for. An increment or a
413
+ computed assignment to a member is that member's change; a value computed
414
+ from a member reads the row before, as the statement does. `Unlink` holds
415
+ over the row before alone. What
383
416
  a relation was linked to is read as stored (the writer's `linked`), since a
384
417
  link to a row hidden from its writer reads to them as none; a writer that
385
418
  cannot say treats every link it sees as none as one that may be there, so
@@ -408,8 +441,11 @@ was written"; nothing is written over a version no rule saw. An input that
408
441
  rule, and not retried. An input may expect only the revision the writer pins:
409
442
  one expecting another field is refused, at startup by `GuardServer.validate`
410
443
  and at run time, since the pin would leave that field where it was. A writer
411
- with no `revision` keeps the window, and `GuardServer.validate` warns of each
412
- write through one.
444
+ with no `revision` keeps the window, and `GuardServer.validate` reports each
445
+ write through one that a change can come between, as an `UnpinnedWrites`
446
+ [diagnostic](#diagnostics): an update, or a delete of
447
+ an Entity the server also updates. An insert has no row before it, so an
448
+ Entity that is only inserted and deleted needs no revision.
413
449
 
414
450
  A declared write's `when` (`foldkit-entity`) is the writer's to check, in the
415
451
  statement that writes; the guarded writer passes it through and speaks first.
@@ -428,7 +464,17 @@ writes. The guard requires each incremented member's Update rule, as for a
428
464
  member it sets, and holds the row's rules over the sum the writer will store, so
429
465
  a rule `stock >= 0` refuses a sale past zero. The row the guard summed over must
430
466
  be the row the writer writes: the input's expected revision keeps it so, or the
431
- writer's `revision` pin. An increment with neither is refused.
467
+ writer's `revision` pin. An increment with neither is refused. A computed
468
+ assignment is the same: its member's Update rule holds, the guard reads what it
469
+ computes from, and judges the row `Write.apply` works out by the writer's own
470
+ table (`EntityWriter.operators`, the binding's for the Drizzle writer), which is
471
+ the row the writer writes; one it cannot work out is refused, never judged as
472
+ it was, with a fixed message, and the operator's own refusal is reported as
473
+ `ComputeRefused`. With a `revision` the guarded writer `pins`, so under a ledger a
474
+ real-number increment or a computed assignment needs no `expect` of its own (no
475
+ writer lands one without either); `validate`
476
+ refuses one computed from a member with a Read rule, which its answer would
477
+ disclose.
432
478
 
433
479
  An Entity's invariants (`Entity.invariant`) are the writer's to judge, over the
434
480
  row its statement writes; the guarded writer passes them through and speaks
@@ -445,25 +491,33 @@ Over a writer with a ledger (`foldkit-remote-drizzle`'s `writer(binding, {
445
491
  ledger })`), a retry of an operation that landed is answered from the ledger,
446
492
  before any rule: it was decided when it landed, and deciding it again over a row
447
493
  that has moved since could refuse a write that happened. A new operation is
448
- decided as any write is.
494
+ decided as any write is. A durable write that Remote's outbox sends again,
495
+ after a reload or a send nothing answered, is such a retry when its first send
496
+ landed; when it did not, it is a new write, decided as whoever the request
497
+ carrying it authenticates.
449
498
 
450
499
  The binding must have a `visible` rule, which is how the writer reads a row
451
500
  as its writer may see it; the writer refuses one without. That the rule is
452
501
  `GuardDrizzle.visible`'s is what `GuardServer.validate` checks of the
453
502
  Entity's Source, so give the writer that Source's binding.
454
503
 
455
- A client should not choose whose a new row is. `presets` sets a field from
456
- who is asking on every create, before the rules are checked, so a rule over
457
- it holds of the creator:
458
-
459
- ```ts
460
- GuardServer.writer(Todo, Policy, writer(Db.Todo), { presets: { ownerId: user => user.id } })
461
- ```
462
-
463
- The create's input leaves `ownerId` out; an input that sets it is refused as
464
- the server's own mistake. A visitor has no one to preset from, and is refused
465
- even where the rules would let anyone create. A preset must be a field of the
466
- Entity, of that field's type.
504
+ A client should not choose whose a new row is. The Entity says which fields
505
+ the write's context sets (`Entity.sets` in `foldkit-entity`), and
506
+ `RemoteServer.write` sets them before the guarded writer checks the create or
507
+ the update, so a rule over them holds of the creator: with
508
+ `Entity.sets({ ownerId: Expr.viewer(UserRow) }, { on: 'create' })` added to the
509
+ `Todo` above (`UserRow` the Entity a principal is a row of), a todo is its
510
+ creator's, and `RemoteServer.make({ viewer })` says who that is. A member rule
511
+ over such a member judges the server's value like any other: declare none there.
512
+
513
+ No input may set `ownerId`, which is refused where the write is declared. A
514
+ visitor is no one to set, and is refused even where the rules would let
515
+ anyone create. A create of an id already taken is refused as
516
+ `Refusal.taken`, with one answer whatever the row there holds, so it tells
517
+ nothing the asker may not read. Only
518
+ the writer's ledger recognises a retry, by its operation and who asked, and
519
+ answers it with its row, first time kept; the same id from another account is
520
+ refused.
467
521
 
468
522
  A handler writes what its code writes, so it is guarded where it is defined:
469
523
  `GuardServer.mutation` is `RemoteServer.mutation` with the row's rule for one
@@ -493,6 +547,33 @@ GuardServer.mutation(
493
547
  shows the writer only what they may now see of the fields it named, and a
494
548
  row the handler hid from them answers as deleted.
495
549
 
550
+ ### Rules that read another row
551
+
552
+ A row's `Read`, `Update` and `Delete` rules may reach another row: a path
553
+ (`Expr.path`), an exists (`Expr.exists`), or a path from the viewer. A Read
554
+ rule compiles to SQL, which reads the rows it reaches as stored: the rule is
555
+ the server's decision, as a principal guard's body is.
556
+
557
+ An Update or Delete rule is judged in the write's own statement (`update …
558
+ where … and <rule>`), so it reads the other row as the write lands, not as it
559
+ was read a moment before. `GuardServer.writer` judges what the row alone
560
+ decides in memory and hands the rest to its writer as `requires`, which
561
+ remote-drizzle's `writer` holds the row to, refusing with `Forbidden` (and the
562
+ `explain`) where it fails, on SQLite and Postgres.
563
+
564
+ - Such a rule is judged over the row as stored, so a write that would change
565
+ what it reads of its own row (its fields, the relation its path leaves by)
566
+ is refused: a member of one team cannot move a note into a team they hold
567
+ no seat on. Where the row written is the viewer's own, a path from the
568
+ viewer leaves it too: a member whose rule reads their team's organisation
569
+ cannot move their own team.
570
+ - `may` leaves such an interaction unanswered, since one row cannot decide it.
571
+ - `GuardServer.writer` over a writer without `requires` throws where it is
572
+ made, rather than letting the rule go unchecked.
573
+ - Every other surface (`Create`, `Write`, a member, a relation, a named
574
+ interaction, `always`) is judged over one row in memory, so `Guards.attach`
575
+ refuses such a rule there and names the surfaces that may hold one.
576
+
496
577
  ## Checking a server at startup
497
578
 
498
579
  A Source written by hand over a guarded Entity serves every row, and nothing
@@ -514,16 +595,25 @@ It throws, naming each:
514
595
  `cost < $max` halved twenty times reads the cost the row hid. This holds
515
596
  whoever asks, since one body serves every principal. Where some readers
516
597
  must filter by it, give the value an Entity of its own with a row Read
517
- rule: a row a reader may not see is not in their list at all;
598
+ rule: a row a reader may not see is not in their list at all. A member of
599
+ another row the body reaches counts too (each relation a path, a path from
600
+ the viewer or an exists follows, the field it ends at, an exists' filter):
601
+ SQL reads a reached row under its `visible` rule, never its members';
518
602
  - for a declared write of such an Entity that does not land through the
519
- `GuardServer.writer` built for it;
520
- - for a live Source of its own over such an Entity, whose stream nothing can
521
- check: serve its changes through a live hub;
603
+ `GuardServer.writer` built for it, and for one whose interaction (`Create`
604
+ for an insert, `Update`, `Delete`) has no rule under `unguarded: 'allow'`,
605
+ which would let anyone make it: give it a rule, or `[Guards.anyone]` to say
606
+ that anyone may;
607
+ - for a live Source over such an Entity that does not read through the Source
608
+ checked here: `pollLive` over that Source names it (`LiveSource.reads`) and
609
+ passes, as a live hub does; a hand-written stream, or a `pollLive` over
610
+ another Source, is refused;
522
611
  - for an Entity carrying another set's guards;
523
612
  - for a field its Source declares `shared` (sent to every live subscriber as
524
613
  written) when a Read rule could tell readers apart: the rows', `always`, the
525
614
  field's own, or, for a relation, its target rows', a target not among
526
- `entities` included.
615
+ `entities` included; and for `may` declared `shared`, which is each
616
+ reader's own whoever may read the row.
527
617
 
528
618
  A rule built from another `Policy`, for another Entity, or for this one before
529
619
  its guards were attached does not count. Every guarded Entity's Source needs both its rule and its
@@ -534,6 +624,25 @@ Drizzle, each Source takes its `filter`, and each binding its `visible`.
534
624
  A handler (`RemoteServer.mutation`) writes what its code writes, which no
535
625
  check at startup can read.
536
626
 
627
+ ## Diagnostics
628
+
629
+ Two things a guarded server goes past without failing are reported through
630
+ `foldkit-surface`'s `Diagnostics` channel (re-exported by `foldkit-remote`),
631
+ by default Effect's log:
632
+
633
+ | `_tag` | `level` | When |
634
+ | --- | --- | --- |
635
+ | `ComputeRefused` | `error` | An operator refused to work out a value a guarded write computes (text holding NUL, an implementation that throws). The write was refused with a fixed message; this carries the operator's `error`. |
636
+ | `UnpinnedWrites` | `warning` | `GuardServer.validate` found `mutations` writing through a writer with no `revision` that a change can come between. |
637
+
638
+ `ComputeRefused` is reported inside the write, so the reporter the server
639
+ runs with applies (`serveFetch`'s `diagnostics`, or
640
+ `Layer.succeed(Diagnostics.Reporter, report)` in its layer).
641
+ `GuardServer.validate` runs before any Effect of the server's, so it takes
642
+ the reporter as an option, `diagnostics`, beside `entities`, `domain` and
643
+ `server`. In a test, pass `Diagnostics.collect().report` and assert on
644
+ `reported`.
645
+
537
646
  ## Who is asking
538
647
 
539
648
  Authentication decides who is asking; guards only read it. Give the handlers
@@ -568,12 +677,12 @@ fact the cache holds was read as someone.
568
677
 
569
678
  ## What the client may do
570
679
 
571
- The client must not run a rule: it has no bodies, its row may be stale, and it
572
- is not where a write is checked. To grey out a button for the reason the
573
- server would refuse it, it reads the server's answer instead: `Guards.may`
574
- adds a derived member, `may`, which `GuardServer.filter` answers from the row
575
- as its reader sees it. `Todo` above is piped through it after its guards, and
576
- over Drizzle its binding marks it `supplied`, since it is not a column.
680
+ The client has no principal guard's body and none of the principal's fields,
681
+ and it is not where a write is checked. To grey out a button for the reason
682
+ the server would refuse it, it reads the server's answer: `Guards.may` adds a
683
+ derived member, `may`, which `GuardServer.filter` answers from the row as its
684
+ reader sees it. `Todo` above is piped through it after its guards, and over
685
+ Drizzle its binding marks it `supplied`, since it is not a column.
577
686
 
578
687
  ```ts
579
688
  import { May } from 'foldkit-guard'
@@ -602,6 +711,63 @@ May.canLink(row.may, Todo, 'project', 'Link')
602
711
  - `foldkit-crud`'s editor locks the keys the reader may not set with
603
712
  `locks: May.locks(Todo)`, for `foldkit-mixins-form`'s `locked`.
604
713
 
714
+ For a row the client writes, which the server has not answered yet, Remote
715
+ foresees `may` from the same rules (`Derived.make`'s `predict`): a row guard
716
+ over the row, its links and `Expr.viewer` is judged over what the store holds;
717
+ a principal guard, a rule over the principal's fields, and one over a row or
718
+ field the store lacks are unknown. Every rule is an `or` of `and`s with no
719
+ negation, so it is decided where it comes out the same with every unknown part
720
+ taken to hold and taken not to. `may` is foreseen only when every part of it
721
+ is, so a new post's Edit shows at once where its author's rule allows it, and
722
+ nothing is shown where an admin's body would decide.
723
+
724
+ A held `may` also refuses a write where it is made (`Derived.make`'s
725
+ `forbids`): `Data.mutate` of an update whose row's `may.row.Update` is `false`,
726
+ or whose written member or relinked relation reads `false`, or of a delete
727
+ whose `Delete` does, is refused at once with `Forbidden` and the `explain` as
728
+ `reason`, as the server would refuse it. Each is judged over the row before the
729
+ write, which is where the server's writer judges it first. It spares a round
730
+ trip and decides nothing for the server, which judges the write again when it
731
+ arrives. `Law.check` (`foldkit-remote/testing`) runs one write through both and
732
+ compares a refusal made here with the server's, by its `refusal`, or by its
733
+ `_tag` where the mutation declares none.
734
+
735
+ ### What `may` tells a reader, and what it does not
736
+
737
+ `may` is a UI hint; enforcement is on the server only. Every write is checked
738
+ when it is made, by the rules, whatever the client holds or sends: the server
739
+ never reads a `may` from a request, and a `may` that says yes (stale after a
740
+ change of role, foreseen, or edited in the page's cache) changes nothing it
741
+ decides. These hold, each tested against the real handlers (the audit is
742
+ #284):
743
+
744
+ - **No existence oracle.** A row its reader may not see is not read, `may`
745
+ included: the answer is the one for an id that does not exist. A write to
746
+ it is refused as a write to a missing row is (`Forbidden`, or for a delete,
747
+ answered gone).
748
+ - **Its shape is the shared declaration's.** `may` names the same
749
+ interactions, members and relations for every reader and row: those the
750
+ Entity's attachment rules, which the browser bundle carries already. Only
751
+ the booleans are the reader's, and they say what the reader may do, never
752
+ why another may. There is no option to leave a member out, since its name
753
+ is public in the declaration anyway; a fact the reader should not learn
754
+ belongs in a principal guard's body, which never leaves the server.
755
+ - **A reason is the declaration's sentence.** `reasons` holds only an
756
+ `explain`'s text, for an interaction refused to this reader; a plain refusal
757
+ says nothing. The text is a constant of shared code, so it ships in the
758
+ bundle whether or not it is sent: write it for the reader, never naming
759
+ another person, an id, or how the rule decides. No type or lint rule checks
760
+ wording, so this one is review's.
761
+ - **One reader's answer is no one else's.** `GuardServer.validate` refuses a
762
+ Source that shares `may` with every live subscriber, and `serveFetch`
763
+ answers every request `cache-control: no-store`. Pages that render a
764
+ reader's rows into HTML (`foldkit-ssr`) send their own `private, no-store`
765
+ through the entry's `headers`, and a client changing principal calls
766
+ `Remote.forget`.
767
+ - **A foreseen `may` is never sent.** What the client foresees for a row it
768
+ wrote is shown until the server's answer replaces it; a write's input is its
769
+ Mutation's, and `may` is not in it.
770
+
605
771
  ## Who the client is: `Me`
606
772
 
607
773
  "Show the Admin link", "show a sign-in page rather than a 404" and "who am
@@ -635,6 +801,10 @@ const MeSource = GuardServer.me(Me, Policy)
635
801
  `validate` lets a Source share them.
636
802
  - `may` is read with the row, as any `may` is: a principal whose role
637
803
  changes sees it when `Me` is read again.
804
+ - `key` is the set's `key` of the principal, shown to that principal: make it
805
+ an id, never a session token or anything secret. `Me` is answered per
806
+ request, shares nothing with live subscribers, and goes out under
807
+ `serveFetch`'s `no-store`.
638
808
 
639
809
  ## When a rule refuses
640
810
 
@@ -701,9 +871,11 @@ differ from person to person, and a document is one audience.
701
871
  the row's `Update`, and each changed member's, with an `explain`'s
702
872
  sentence. It reads no row, and its bodies must not suspend.
703
873
  - **Before the journal**, `admit` reads each row an edit names through the
704
- Entity's guarded Source: a row the principal cannot see is refused, the
705
- row's `Update` must hold over it as it is and as it would be after all of
706
- the operation's edits to it, and each changed member's rule must hold. An
874
+ Entity's guarded Source: a row the principal cannot see is refused, and
875
+ the row's `Update` must hold over it as it is and as it would be after all
876
+ of the operation's edits to it. Each changed member's rule must hold over
877
+ it as it is, and as the edits would leave it with that member's own edit
878
+ undone, as for a writer. An
707
879
  edit to a member outside the document, or a value its member cannot
708
880
  encode, is refused.
709
881
  - **A document is one audience.** Every replica that opens it receives every
@@ -799,16 +971,17 @@ const uploads = uploadLayer().pipe(
799
971
 
800
972
  ## Limits
801
973
 
802
- - **No rule runs on the client.** `may` is the server's answer for the row as
803
- it was read, as stale as the row; a live patch of a field its rules read
804
- does not answer it again.
974
+ - **`may` is as stale as its row.** It is the server's answer for the row as
975
+ it was read, or the client's reading of the rules for a row it wrote; a
976
+ live patch of a field its rules read does not answer it again.
805
977
  - **A handler's own writes are its own to check.** `GuardServer.mutation`
806
978
  checks the row's rule for its interaction; members it sets and relations
807
979
  it points are not known to it, and no startup check can read them.
808
- - **Under a guard, a create refetches the lists over its Entity.** The client
809
- cannot tell an answer read back under the writer's rule from one a plain
810
- handler made up, so it does not place a created row by the list's body
811
- alone.
980
+ - **Under a Read rule over fields, a new row is fetched into a list, not
981
+ placed.** `Guards.attach` records the members the row's Read rules read, and
982
+ the client, which runs none of them, refetches a list when a row it does not
983
+ hold changes one of them, as a create does: only the server can say whether
984
+ the rule lets it in.
812
985
  - **A Sync document is one audience.** Per-member or per-row secrecy within
813
986
  one is not something a replicated log offers: `GuardSync.document` refuses
814
987
  it where it is declared.
@@ -831,5 +1004,6 @@ const uploads = uploadLayer().pipe(
831
1004
  - **Sync's `authorize` is synchronous.** Its principal guards' bodies must not
832
1005
  suspend; row guards run in `admit`, which may.
833
1006
  - **A row guard over a field the client sets on create** reads as matching
834
- nothing while the create leaves it unset; use a preset (`presets`) for a
835
- field that should be the creator's.
1007
+ nothing while the create leaves it unset; declare a field that should be the
1008
+ creator's with `Entity.sets` (see [Serving writes](#serving-writes)), and the
1009
+ server sets it before the rules are judged.
package/dist/agent.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { j as MayAnswer, l as InteractionKey } from "./attach-BnP9_Uca.mjs";
1
+ import { j as MayAnswer, l as InteractionKey } from "./attach-DPgyv78F.mjs";
2
2
  import { RemoteData } from "foldkit-remote";
3
3
  /** A row read with `may`, as `Data.get(Row, id).read(model)` gives it. */
4
4
  type MayRow = RemoteData<{
package/dist/agent.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { t as May } from "./may-DzCAt_5M.mjs";
1
+ import { t as May } from "./may-DprCmMgK.mjs";
2
2
  import { Option } from "effect";
3
3
  import { RemoteData } from "foldkit-remote";
4
4
  // src/agent.ts
@@ -178,12 +178,27 @@ const surfaceFrom = (slot) => isOn(slot) ? {
178
178
  rules: Object.freeze([...slot]),
179
179
  deny: Option.none()
180
180
  };
181
- /** Throws for a row guard over another Entity that shares the target's name. */
181
+ /**
182
+ * The row surfaces a rule that reads another row may sit on: Read, compiled
183
+ * to SQL, and Update and Delete, judged in the write's own statement. Every
184
+ * other is judged over one row in memory.
185
+ */
186
+ const reachingSurfaces = /* @__PURE__ */ new Set([
187
+ "Read",
188
+ "Update",
189
+ "Delete"
190
+ ]);
191
+ /**
192
+ * Throws for a row guard over another Entity that shares the target's name,
193
+ * and, where the surface is judged over one row in memory, for one that reads
194
+ * another row.
195
+ */
182
196
  const checkRules = (set, entity, where, rules) => {
183
197
  for (const rule of rules) Match.valueTags(rule, {
184
198
  PrincipalGuard: () => {},
185
199
  RowGuard: (guard) => {
186
200
  if (!Entity.same(guard.entity, entity)) throw new Error(`[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, a guard over another Entity named ${entity.name}`);
201
+ if (!reachingSurfaces.has(where) && Query.dependencies(guard.query).reaches.length > 0) throw new Error(`[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, which reads another row (a path or an exists); only a row's Read rule may (judged in SQL), and its Update and Delete rules (judged in the write's statement), so name those rather than Write`);
187
202
  },
188
203
  All: ({ rules }) => checkRules(set, entity, where, rules),
189
204
  Inherit: () => {}
@@ -296,4 +311,4 @@ const Attaching = {
296
311
  };
297
312
  export { defaultDeny as a, readRowsRuled as c, surfaceOf as d, attachedRules as i, readRuled as l, Interaction as n, flattenRules as o, attached as r, isAnyone as s, Attaching as t, restricts as u };
298
313
 
299
- //# sourceMappingURL=attach-CRCF5XHS.mjs.map
314
+ //# sourceMappingURL=attach-CEGlbWu5.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attach-CEGlbWu5.mjs","names":[],"sources":["../src/attach.ts"],"sourcesContent":["/**\n * Attaching a guard set's guards to an Entity, per surface and interaction,\n * as metadata only `foldkit-guard` reads. See `guard-DESIGN.md` §3.2.\n */\nimport { Match, Option, type Schema } from 'effect'\nimport { Entity, Query, ReadFilter, type AnyEntity } from 'foldkit-entity'\nimport { Metadata } from 'foldkit-metadata'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\ndeclare const InteractionBrand: unique symbol\n\n/** An interaction the application names, used as a computed key: `[Archive.key]`. */\nexport type InteractionKey<Name extends string = string> = Name & {\n readonly [InteractionBrand]: Name\n}\n\nexport interface Interaction<Name extends string> {\n readonly name: Name\n readonly key: InteractionKey<Name>\n}\n\n/** The interactions every row has, and the ones a relation member has. */\nconst builtIn = ['Read', 'Create', 'Update', 'Delete', 'Write', 'Link', 'Unlink'] as const\n\nexport const Interaction = {\n /** An interaction beyond Read, Create, Update and Delete, such as `Archive`. */\n make: <const Name extends string>(name: Name): Interaction<Name> => {\n if ((builtIn as ReadonlyArray<string>).includes(name)) {\n throw new Error(`[foldkit-guard] Interaction.make: \"${name}\" is an interaction already`)\n }\n return Object.freeze({ name, key: name as InteractionKey<Name> })\n },\n}\n\n/** Every guard of `Rules` must allow, as one guard: `Guards.all(signedIn, isOwner)`. */\nexport interface All<Rules> {\n readonly _tag: 'All'\n readonly rules: ReadonlyArray<Rules>\n}\n\n/** This row's Read is the Read of the row its `one` relation points at. */\nexport interface Inherit<Relation extends string> {\n readonly _tag: 'Inherit'\n readonly relation: Relation\n}\n\n/** What a member hidden by its Read guards reads as instead of its value. */\nexport interface Redact<A> {\n readonly _tag: 'Redact'\n readonly value: A\n}\n\n/** A refused write's sentence, for the application's own users. */\nexport interface Explain {\n readonly _tag: 'Explain'\n readonly reason: string\n}\n\n/**\n * What a refusal looks like. The defaults need no constructor: a row Read\n * answers `NotFound`, a member or relation Read `Omit`, a write `Forbidden`.\n */\nexport type Deny =\n | { readonly _tag: 'NotFound' }\n | { readonly _tag: 'Omit' }\n | Redact<unknown>\n | { readonly _tag: 'Forbidden' }\n | Explain\n\n/** A surface's guards with a refusal other than its default. */\nexport interface On<Rules, D extends Deny> {\n readonly _tag: 'On'\n readonly rules: ReadonlyArray<Rules>\n readonly deny: D\n}\n\n/** Anything a surface's list may hold, of any guard set. */\nexport type AnyRule =\n | PrincipalGuard<any, string>\n | RowGuard<any, AnyEntity, string>\n | All<any>\n | Inherit<string>\n\n/**\n * What a surface of the Entity named `Name` accepts from the guard set `Set`:\n * its principal guards, its row guards over that Entity, and conjunctions of\n * both. A row guard over another Entity, or a guard of another set, is refused.\n */\nexport type RuleFor<User, Set extends string, Name extends string> =\n | PrincipalGuard<User, Set>\n | RowGuard<User, Entity<Name, any, any, any>, Set>\n | All<RuleFor<User, Set, Name>>\n\ntype Slot<Rule, D extends Deny> = ReadonlyArray<Rule> | On<Rule, D>\n\ntype WriteSlot<Rule> = Slot<Rule, Explain>\n\ntype OneRelations<E extends AnyEntity> = {\n [K in keyof E['relations']]: E['relations'][K] extends { readonly cardinality: 'one' } ? K : never\n}[keyof E['relations']] &\n string\n\ntype MemberKeys<E extends AnyEntity> = (keyof E['fields'] | keyof E['derived']) & string\n\ntype TypeOf<E extends AnyEntity, K extends keyof E['members']> = E['members'][K]['schema']['Type']\n\n/** What `Guards.attach` takes for the Entity `E`, every key checked against it. */\nexport type Attach<User, Set extends string, E extends AnyEntity> = {\n readonly row?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']> | Inherit<OneRelations<E>>>\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Delete?: WriteSlot<RuleFor<User, Set, E['name']>>\n /** The same guards on Create, Update and Delete. */\n readonly Write?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /**\n * The row's interactions the application named, by key:\n * `{ [Archive.key]: [G.isAdmin] }`. Apart from `row`, whose `Read` may\n * inherit: a literal with a computed key is typed as an index signature,\n * which `Read`'s rules would have to fit too.\n */\n readonly interactions?: {\n readonly [K: InteractionKey]: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /** Narrow a field or derived member: a member is reachable only if its row is. */\n readonly members?: {\n readonly [K in MemberKeys<E>]?: {\n readonly Read?: Slot<RuleFor<User, Set, E['name']>, Redact<TypeOf<E, K>>>\n /** When absent, `Update`'s guards govern setting the member on creation too. */\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n readonly relations?: {\n readonly [K in keyof E['relations']]?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n readonly Link?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Unlink?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n /** ANDed with every surface's guards, and never out-voted by them. */\n readonly always?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n}\n\n/** One surface's guards as attached: a disjunction, and a refusal if one was chosen. */\nexport interface Surface {\n readonly rules: ReadonlyArray<AnyRule>\n readonly deny: Option.Option<Deny>\n}\n\ntype Surfaces = Readonly<Record<string, Surface>>\n\n/** An Entity's guards, every attachment merged. */\nexport interface Attachment {\n readonly set: string\n readonly unguarded: 'allow' | 'deny'\n readonly row: Surfaces\n readonly members: Readonly<Record<string, Surfaces>>\n readonly relations: Readonly<Record<string, Surfaces>>\n readonly always: ReadonlyArray<AnyRule>\n}\n\n/** Which surface a rule is asked about. */\ntype Target =\n | { readonly _tag: 'Row'; readonly interaction: string }\n | { readonly _tag: 'Member'; readonly member: string; readonly interaction: string }\n | { readonly _tag: 'Relation'; readonly relation: string; readonly interaction: string }\n\nconst record = <A>(): Record<string, A> => Object.create(null)\n\nconst appendSurface = (into: Record<string, Surface>, interaction: string, added: Surface) => {\n const before = into[interaction]\n into[interaction] =\n before === undefined\n ? added\n : {\n rules: [...before.rules, ...added.rules],\n deny: Option.orElse(added.deny, () => before.deny),\n }\n}\n\nconst appendSurfaces = (into: Record<string, Surface>, added: Surfaces) => {\n for (const [interaction, surface] of Object.entries(added)) {\n appendSurface(into, interaction, surface)\n }\n}\n\nconst freezeSurfaces = (surfaces: Record<string, Surfaces>) => {\n for (const key of Object.keys(surfaces)) Object.freeze(surfaces[key])\n return Object.freeze(surfaces)\n}\n\n/** Later attachments append to each surface's disjunction and replace its refusal. */\nconst mergeAttachments = (attachments: ReadonlyArray<Attachment>): Attachment => {\n const row = record<Surface>()\n const members = record<Record<string, Surface>>()\n const relations = record<Record<string, Surface>>()\n const always: Array<AnyRule> = []\n for (const attachment of attachments) {\n appendSurfaces(row, attachment.row)\n for (const [key, surfaces] of Object.entries(attachment.members)) {\n appendSurfaces((members[key] ??= record()), surfaces)\n }\n for (const [key, surfaces] of Object.entries(attachment.relations)) {\n appendSurfaces((relations[key] ??= record()), surfaces)\n }\n always.push(...attachment.always)\n }\n const { set, unguarded } = attachments[0]!\n return Object.freeze({\n set,\n unguarded,\n row: Object.freeze(row),\n members: freezeSurfaces(members),\n relations: freezeSurfaces(relations),\n always: Object.freeze(always),\n })\n}\n\nconst showRule = (rule: AnyRule): string =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => name,\n RowGuard: ({ name }) => name,\n All: ({ rules }) => (rules.length === 0 ? 'anyone' : `all(${rules.map(showRule).join(', ')})`),\n Inherit: ({ relation }) => `inherit(${relation})`,\n })\n\nconst showDeny = (deny: Deny): string =>\n Match.valueTags(deny, {\n NotFound: () => 'not_found',\n Omit: () => 'omit',\n Redact: ({ value }) => `redact(${JSON.stringify(value)})`,\n Forbidden: () => 'forbidden',\n Explain: ({ reason }) => `explain(${JSON.stringify(reason)})`,\n })\n\nconst notFound: Deny = Object.freeze({ _tag: 'NotFound' })\nconst omit: Deny = Object.freeze({ _tag: 'Omit' })\nconst forbidden: Deny = Object.freeze({ _tag: 'Forbidden' })\n\n/** The refusal a surface takes when none was chosen. */\nexport const defaultDeny = (target: Target): Deny =>\n target.interaction === 'Read'\n ? Match.valueTags(target, { Row: () => notFound, Member: () => omit, Relation: () => omit })\n : forbidden\n\n/** The guards a surface carries; `none` where it falls to the set's `unguarded`. */\nexport const surfaceOf = (attachment: Attachment, target: Target): Option.Option<Surface> =>\n Match.valueTags(target, {\n Row: ({ interaction }) => Option.fromUndefinedOr(attachment.row[interaction]),\n Member: ({ member, interaction }) => {\n const surfaces = attachment.members[member]\n if (surfaces === undefined) return Option.none()\n const own = surfaces[interaction]\n // A member a caller may not change is rarely one it may set freely on creation.\n return Option.fromUndefinedOr(\n own === undefined && interaction === 'Create' ? surfaces['Update'] : own,\n )\n },\n Relation: ({ relation, interaction }) =>\n Option.fromUndefinedOr(attachment.relations[relation]?.[interaction]),\n })\n\n/** Whether who may read the rows depends on who is asking: a row Read rule, or `always`. */\n/** `Guards.anyone`: a conjunction of nothing, which every principal passes. */\n/** The rules, each `all` opened into its parts: every guard they ask. */\nexport const flattenRules = (rules: ReadonlyArray<AnyRule>): ReadonlyArray<AnyRule> =>\n rules.flatMap(rule =>\n Match.valueTags(rule, {\n PrincipalGuard: () => [rule],\n RowGuard: () => [rule],\n All: ({ rules: parts }) => flattenRules(parts),\n Inherit: () => [rule],\n }),\n )\n\n/** Every rule attached anywhere: on the row, each member and relation, and always. */\nexport const attachedRules = (attachment: Attachment): ReadonlyArray<AnyRule> =>\n flattenRules([\n ...attachment.always,\n ...[\n attachment.row,\n ...Object.values(attachment.members),\n ...Object.values(attachment.relations),\n ]\n .flatMap(surfaces => Object.values(surfaces))\n .flatMap(surface => surface.rules),\n ])\n\nexport const isAnyone = (rule: AnyRule): boolean => rule._tag === 'All' && rule.rules.length === 0\n\n/** Whether a surface's rules restrict who passes: not when one of them is `anyone`. */\nexport const restricts = (surface: Option.Option<Surface>): boolean =>\n Option.exists(surface, ({ rules }) => !rules.some(isAnyone))\n\nexport const readRowsRuled = (attachment: Attachment): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Row', interaction: 'Read' })) ||\n attachment.always.some(rule => !isAnyone(rule))\n\n/** Whether `member`, a field or a relation, has a Read rule of its own. */\nexport const readRuled = (attachment: Attachment, member: string): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Member', member, interaction: 'Read' })) ||\n restricts(surfaceOf(attachment, { _tag: 'Relation', relation: member, interaction: 'Read' }))\n\nconst key = Metadata.key<Attachment>('foldkit-guard/attachment', {\n merge: attachments => [mergeAttachments(attachments)],\n summarize: attachment =>\n linesOf(attachment)\n .map(([where, rule]) => `${where}: ${rule}`)\n .join('; '),\n})\n\n/** The rows of an attachment's matrix: each surface it decides, and how. */\nconst linesOf = (attachment: Attachment): ReadonlyArray<readonly [string, string]> => {\n const open = attachment.unguarded === 'allow' ? 'open' : 'closed'\n const show = (target: Target) =>\n Option.match(surfaceOf(attachment, target), {\n onNone: () => open,\n onSome: ({ rules, deny }) =>\n // An empty disjunction allows no one.\n `${rules.length === 0 ? 'nobody' : rules.map(showRule).join(' | ')} → ${showDeny(Option.getOrElse(deny, () => defaultDeny(target)))}`,\n })\n const interactions = [\n 'Read',\n 'Create',\n 'Update',\n 'Delete',\n ...Object.keys(attachment.row).filter(interaction => !builtIn.includes(interaction as never)),\n ]\n return [\n ...(attachment.always.length > 0\n ? [['always', attachment.always.map(showRule).join(' & ')] as const]\n : []),\n ...interactions.map(interaction => [interaction, show({ _tag: 'Row', interaction })] as const),\n ...Object.keys(attachment.members).flatMap(member =>\n ['Read', 'Create', 'Update'].flatMap(interaction => {\n const target: Target = { _tag: 'Member', member, interaction }\n return Option.isSome(surfaceOf(attachment, target))\n ? [[`${member}.${interaction}`, show(target)] as const]\n : []\n }),\n ),\n ...Object.entries(attachment.relations).flatMap(([relation, surfaces]) =>\n Object.keys(surfaces).map(\n interaction =>\n [\n `${relation}.${interaction}`,\n show({ _tag: 'Relation', relation, interaction }),\n ] as const,\n ),\n ),\n ]\n}\n\nconst isOn = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): slot is On<AnyRule, Deny> =>\n !Array.isArray(slot)\n\nconst surfaceFrom = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): Surface =>\n isOn(slot)\n ? { rules: slot.rules, deny: Option.some(slot.deny) }\n : { rules: Object.freeze([...slot]), deny: Option.none() }\n\n/**\n * The row surfaces a rule that reads another row may sit on: Read, compiled\n * to SQL, and Update and Delete, judged in the write's own statement. Every\n * other is judged over one row in memory.\n */\nconst reachingSurfaces = new Set(['Read', 'Update', 'Delete'])\n\n/**\n * Throws for a row guard over another Entity that shares the target's name,\n * and, where the surface is judged over one row in memory, for one that reads\n * another row.\n */\nconst checkRules = (\n set: string,\n entity: AnyEntity,\n where: string,\n rules: ReadonlyArray<AnyRule>,\n): void => {\n for (const rule of rules) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n if (!Entity.same(guard.entity, entity)) {\n throw new Error(\n `[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, a guard over another Entity named ${entity.name}`,\n )\n }\n if (!reachingSurfaces.has(where) && Query.dependencies(guard.query).reaches.length > 0) {\n throw new Error(\n `[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, which reads another row (a path or an exists); only a row's Read rule may (judged in SQL), and its Update and Delete rules (judged in the write's statement), so name those rather than Write`,\n )\n }\n },\n All: ({ rules }) => checkRules(set, entity, where, rules),\n Inherit: () => {},\n })\n }\n}\n\nconst surfacesFrom = (\n set: string,\n entity: AnyEntity,\n where: string,\n slots: Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>>,\n): Surfaces => {\n const surfaces = record<Surface>()\n // `Write` goes first, whatever order the keys were written in: beside it, a\n // slot of its own adds rules to it and its refusal replaces Write's.\n const ordered = Object.entries(slots).sort(\n ([left], [right]) => Number(right === 'Write') - Number(left === 'Write'),\n )\n for (const [interaction, slot] of ordered) {\n if (slot === undefined) continue\n const added = surfaceFrom(slot)\n checkRules(set, entity, `${where}${interaction}`, added.rules)\n // Write is shorthand, so it is stored as the three it stands for.\n for (const each of interaction === 'Write' ? ['Create', 'Update', 'Delete'] : [interaction]) {\n appendSurface(surfaces, each, added)\n }\n }\n return Object.freeze(surfaces)\n}\n\nconst nested = (\n set: string,\n entity: AnyEntity,\n given: Readonly<\n Record<\n string,\n Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>> | undefined\n >\n >,\n): Readonly<Record<string, Surfaces>> => {\n const surfaces = record<Surfaces>()\n for (const [member, slots] of Object.entries(given)) {\n if (slots !== undefined) surfaces[member] = surfacesFrom(set, entity, `${member}.`, slots)\n }\n return Object.freeze(surfaces)\n}\n\n/** A row guard's own fields, and the relation an inherited Read follows. */\nconst membersRead = (rule: AnyRule): ReadonlyArray<string> =>\n Match.valueTags(rule, {\n PrincipalGuard: () => [],\n RowGuard: ({ query }) => Query.dependencies(query).predicate.map(field => field.key),\n All: ({ rules }) => rules.flatMap(membersRead),\n Inherit: ({ relation }) => [relation],\n })\n\nexport const attached = (entity: AnyEntity): Option.Option<Attachment> =>\n Option.fromUndefinedOr(key.get(entity.metadata)[0])\n\nexport const Attaching = {\n /**\n * Attaches guards to an Entity, per surface and interaction. A surface's list\n * is a disjunction; `always` is ANDed after it. Attaching twice appends to a\n * surface's list and replaces its refusal.\n */\n attach:\n <Name extends string, User, E extends AnyEntity>(\n G: {\n readonly name: Name\n readonly schema: Schema.Codec<User, unknown>\n readonly unguarded: 'allow' | 'deny'\n },\n config: Attach<NoInfer<User>, NoInfer<Name>, E>,\n ) =>\n (entity: E): E => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== G.name) {\n throw new Error(\n `[foldkit-guard] ${G.name}.attach: ${entity.name} carries the guards of ${set} already`,\n )\n }\n })\n const always = config.always ?? []\n checkRules(G.name, entity, 'always', always)\n const attachment: Attachment = Object.freeze({\n set: G.name,\n unguarded: G.unguarded,\n // A named interaction is the row's, as the matrix and the decisions read it.\n row: surfacesFrom(G.name, entity, '', { ...config.row, ...config.interactions }),\n members: nested(G.name, entity, config.members ?? {}),\n relations: nested(G.name, entity, config.relations ?? {}),\n always: Object.freeze([...always]),\n })\n // What the row's Read rules read, so a client placing rows knows it cannot judge a change to them.\n const filtered = [\n ...new Set(\n [...(attachment.row['Read']?.rules ?? []), ...attachment.always].flatMap(membersRead),\n ),\n ]\n return entity.pipe(\n Entity.annotate(Metadata.combine([key.of(attachment), ReadFilter.of(filtered)])),\n )\n },\n\n /** The guards attached to `entity`, every attachment merged. */\n attached,\n\n /** Every rule must allow, as one rule. Principal and row guards may mix. */\n all: <\n const Rules extends readonly [\n Exclude<AnyRule, Inherit<string>>,\n ...ReadonlyArray<Exclude<AnyRule, Inherit<string>>>,\n ],\n >(\n ...rules: Rules\n ): All<Rules[number]> => Object.freeze({ _tag: 'All', rules: Object.freeze([...rules]) }),\n\n /**\n * A rule everyone passes, a visitor included: a conjunction of nothing.\n * For a surface that is public under a set whose `unguarded` is `'deny'`.\n */\n anyone: Object.freeze<All<never>>({ _tag: 'All', rules: Object.freeze([]) }),\n\n /** This row's Read is the Read of the row its `one` relation points at. */\n inherit: <const Relation extends string>(relation: Relation): Inherit<Relation> =>\n Object.freeze({ _tag: 'Inherit', relation }),\n\n /** A surface's guards with a refusal other than its default. */\n on: <const Rules extends ReadonlyArray<AnyRule>, D extends Redact<unknown> | Explain>(\n rules: Rules,\n deny: D,\n ): On<Rules[number], D> => Object.freeze({ _tag: 'On', rules: Object.freeze([...rules]), deny }),\n\n /** A hidden member reads as `value`, typed by the member's schema. */\n redact: <const A>(value: A): Redact<A> => Object.freeze({ _tag: 'Redact', value }),\n\n /** A refused write tells the caller `reason`. */\n explain: (reason: string): Explain => Object.freeze({ _tag: 'Explain', reason }),\n\n /**\n * The members a row interaction's guards read, `always` included: a change\n * to one can change whether a principal may. A relation an inherited Read\n * follows counts.\n */\n guardFields: (\n entity: AnyEntity,\n interaction: 'Read' | 'Create' | 'Update' | 'Delete' | InteractionKey,\n ): ReadonlyArray<string> =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => [\n ...new Set(\n [...(attachment.row[interaction]?.rules ?? []), ...attachment.always].flatMap(\n membersRead,\n ),\n ),\n ],\n }),\n\n /** Who may do what, one line per surface, for review and for a committed snapshot. */\n matrix: (entities: ReadonlyArray<AnyEntity>): string =>\n entities\n .flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [`${entity.name}: no guards`],\n onSome: attachment =>\n linesOf(attachment).map(([where, rule]) => `${entity.name}.${where}: ${rule}`),\n }),\n )\n .join('\\n'),\n}\n"],"mappings":";;;;;;;;;AAsBA,MAAM,UAAU;CAAC;CAAQ;CAAU;CAAU;CAAU;CAAS;CAAQ;AAAQ;AAEhF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