foldkit-guard 0.6.0 → 0.8.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 (36) hide show
  1. package/README.md +223 -46
  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-BepaL930.d.mts → attach-CJl-GtbN.d.mts} +156 -10
  7. package/dist/attach-CJl-GtbN.d.mts.map +1 -0
  8. package/dist/{condition-Dx54lL7v.mjs → condition-dNSbUHzE.mjs} +98 -10
  9. package/dist/condition-dNSbUHzE.mjs.map +1 -0
  10. package/dist/drizzle.d.mts +1 -1
  11. package/dist/drizzle.mjs +8 -6
  12. package/dist/drizzle.mjs.map +1 -1
  13. package/dist/index.d.mts +1 -1
  14. package/dist/index.mjs +34 -17
  15. package/dist/index.mjs.map +1 -1
  16. package/dist/may-DprCmMgK.mjs +200 -0
  17. package/dist/may-DprCmMgK.mjs.map +1 -0
  18. package/dist/{me-BYpuVqJE.mjs → me-C-gX1paZ.mjs} +3 -3
  19. package/dist/{me-BYpuVqJE.mjs.map → me-C-gX1paZ.mjs.map} +1 -1
  20. package/dist/media.d.mts +1 -1
  21. package/dist/{placed-BvdNmZJu.mjs → placed-CGyo-NRR.mjs} +2 -2
  22. package/dist/{placed-BvdNmZJu.mjs.map → placed-CGyo-NRR.mjs.map} +1 -1
  23. package/dist/server.d.mts +54 -20
  24. package/dist/server.d.mts.map +1 -1
  25. package/dist/server.mjs +288 -154
  26. package/dist/server.mjs.map +1 -1
  27. package/dist/sync.d.mts +5 -3
  28. package/dist/sync.d.mts.map +1 -1
  29. package/dist/sync.mjs +18 -8
  30. package/dist/sync.mjs.map +1 -1
  31. package/package.json +20 -19
  32. package/dist/attach-BepaL930.d.mts.map +0 -1
  33. package/dist/attach-CRCF5XHS.mjs.map +0 -1
  34. package/dist/condition-Dx54lL7v.mjs.map +0 -1
  35. package/dist/may-DzCAt_5M.mjs +0 -75
  36. 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,8 +120,11 @@ 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
- a placeholder (`p.role === 'admin'`) is a type error: there is no value yet.
123
+ `principal.id`), and checks it is a rule over its own Entity: a predicate
124
+ reading another Entity's field, relation or case is a type error where it
125
+ is written, and refused at runtime for a predicate typed plain `Predicate`.
126
+ Branching on a placeholder (`p.role === 'admin'`) is a type error: there is
127
+ no value yet.
124
128
  - `G.implement` is the only place a body exists. A missing or extra key is a
125
129
  type error, and refused at runtime for a caller the types do not reach.
126
130
  - `Policy.decide` is an `Effect` of a `Decision`: `true`, `false`, or
@@ -209,6 +213,33 @@ Guards.matrix([Todo])
209
213
  `'deny'` refuses it (the matrix prints `closed`), `'allow'` lets everyone
210
214
  (`open`).
211
215
 
216
+ ### What a row guard may read
217
+
218
+ A row guard is an `Expr` over its Entity's row and the principal's fields.
219
+ Beyond the row's own fields:
220
+
221
+ - A row guard may compare a `one` relation itself, the id it points at
222
+ (`guard.row(Like, p => Expr.eq(Like.relations.user, p.id))`), so no field
223
+ repeats the link. SQL reads the relation's column; a rule judged over a
224
+ row a Source read, whose link is a ref key (`'User:ada'`), reads the id.
225
+ - A set that names the Entity its principals are rows of (`{ viewer: User }`,
226
+ each by `key`) lets a rule read who asks:
227
+ `guard.row(Like, () => Expr.eq(Like.relations.user, Expr.viewer(User)))`.
228
+ `Policy.viewer(principal)` is that row's ref, the server's one viewer:
229
+ `RemoteServer.make({ viewer: Policy.viewer })`. A rule over `Expr.viewer`
230
+ in a set without one, or over `Expr.now`, is refused where it is declared.
231
+ - A rule per case of a variant Entity (`Entity.defineVariants`) is a row
232
+ guard over `Expr.is`: `guard.row(Domain, p => Expr.is(Domain, 'Available',
233
+ ({ price }) => Expr.lte(price, p.budget)))`. It is false on a row of another
234
+ case, so the row's other rules decide it, and it reads `_tag` and the
235
+ case's fields as columns of the stored row, in SQL and in memory alike.
236
+ - A row's `Read`, `Update` and `Delete` rules may reach another row
237
+ (`Expr.path`, `Expr.exists`, a path from the viewer: `Expr.eq(Note.fields.orgId,
238
+ orgOfViewer)`). A Read rule compiles to SQL; an Update or Delete rule is
239
+ judged in the write's own statement ([Rules that read another
240
+ row](#rules-that-read-another-row)). Every other surface is judged over one
241
+ row, so `Guards.attach` refuses such a rule there.
242
+
212
243
  ## Deciding reads and writes
213
244
 
214
245
  A server asks the `Policy` which rows a principal may read. Every principal
@@ -379,7 +410,17 @@ RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
379
410
  over the row as it would be after it too: a write cannot move a row out of
380
411
  its writer's reach.
381
412
  - 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
413
+ hold, and each relation it points elsewhere its `Unlink` and `Link`. An
414
+ update's member and `Link` rules hold over the row before and over the
415
+ row after with that one change undone: every other member's new value
416
+ and link, and this member's old value (or the relation pointing where it
417
+ did). So each change must be allowed given everything else the write does:
418
+ a write cannot set together what each change alone would be refused, and a
419
+ rule that reads its own member ("change `status` only while it is
420
+ `draft`") still allows the change it exists for. An increment or a
421
+ computed assignment to a member is that member's change; a value computed
422
+ from a member reads the row before, as the statement does. `Unlink` holds
423
+ over the row before alone. What
383
424
  a relation was linked to is read as stored (the writer's `linked`), since a
384
425
  link to a row hidden from its writer reads to them as none; a writer that
385
426
  cannot say treats every link it sees as none as one that may be there, so
@@ -388,7 +429,10 @@ RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
388
429
  it leaves unset does not hold, whatever it asks (`isNull` and `isNotNull`
389
430
  alike): the create never said what the field holds.
390
431
  - A refusal is `Forbidden`, with the sentence `Guards.explain` gave; the
391
- write never runs.
432
+ write never runs. A visitor is refused as `Unauthenticated` instead, with
433
+ the same sentence: no one is signed in, so the remedy is a sign-in, and a
434
+ client tells a session that ended (its cookie gone) from a person refused.
435
+ Remote's outbox keeps a durable write so answered until the sign-in.
392
436
  - The answer is read back under the binding's `visible` and the Entity's
393
437
  member Read rules: the row as its writer may now see it, with no more
394
438
  fields than the write set, and a row the write hid from them in `deleted`,
@@ -408,8 +452,11 @@ was written"; nothing is written over a version no rule saw. An input that
408
452
  rule, and not retried. An input may expect only the revision the writer pins:
409
453
  one expecting another field is refused, at startup by `GuardServer.validate`
410
454
  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.
455
+ with no `revision` keeps the window, and `GuardServer.validate` reports each
456
+ write through one that a change can come between, as an `UnpinnedWrites`
457
+ [diagnostic](#diagnostics): an update, or a delete of
458
+ an Entity the server also updates. An insert has no row before it, so an
459
+ Entity that is only inserted and deleted needs no revision.
413
460
 
414
461
  A declared write's `when` (`foldkit-entity`) is the writer's to check, in the
415
462
  statement that writes; the guarded writer passes it through and speaks first.
@@ -433,7 +480,8 @@ assignment is the same: its member's Update rule holds, the guard reads what it
433
480
  computes from, and judges the row `Write.apply` works out by the writer's own
434
481
  table (`EntityWriter.operators`, the binding's for the Drizzle writer), which is
435
482
  the row the writer writes; one it cannot work out is refused, never judged as
436
- it was. With a `revision` the guarded writer `pins`, so under a ledger a
483
+ it was, with a fixed message, and the operator's own refusal is reported as
484
+ `ComputeRefused`. With a `revision` the guarded writer `pins`, so under a ledger a
437
485
  real-number increment or a computed assignment needs no `expect` of its own (no
438
486
  writer lands one without either); `validate`
439
487
  refuses one computed from a member with a Read rule, which its answer would
@@ -454,25 +502,33 @@ Over a writer with a ledger (`foldkit-remote-drizzle`'s `writer(binding, {
454
502
  ledger })`), a retry of an operation that landed is answered from the ledger,
455
503
  before any rule: it was decided when it landed, and deciding it again over a row
456
504
  that has moved since could refuse a write that happened. A new operation is
457
- decided as any write is.
505
+ decided as any write is. A durable write that Remote's outbox sends again,
506
+ after a reload or a send nothing answered, is such a retry when its first send
507
+ landed; when it did not, it is a new write, decided as whoever the request
508
+ carrying it authenticates.
458
509
 
459
510
  The binding must have a `visible` rule, which is how the writer reads a row
460
511
  as its writer may see it; the writer refuses one without. That the rule is
461
512
  `GuardDrizzle.visible`'s is what `GuardServer.validate` checks of the
462
513
  Entity's Source, so give the writer that Source's binding.
463
514
 
464
- A client should not choose whose a new row is. `presets` sets a field from
465
- who is asking on every create, before the rules are checked, so a rule over
466
- it holds of the creator:
467
-
468
- ```ts
469
- GuardServer.writer(Todo, Policy, writer(Db.Todo), { presets: { ownerId: user => user.id } })
470
- ```
471
-
472
- The create's input leaves `ownerId` out; an input that sets it is refused as
473
- the server's own mistake. A visitor has no one to preset from, and is refused
474
- even where the rules would let anyone create. A preset must be a field of the
475
- Entity, of that field's type.
515
+ A client should not choose whose a new row is. The Entity says which fields
516
+ the write's context sets (`Entity.sets` in `foldkit-entity`), and
517
+ `RemoteServer.write` sets them before the guarded writer checks the create or
518
+ the update, so a rule over them holds of the creator: with
519
+ `Entity.sets({ ownerId: Expr.viewer(UserRow) }, { on: 'create' })` added to the
520
+ `Todo` above (`UserRow` the Entity a principal is a row of), a todo is its
521
+ creator's, and `RemoteServer.make({ viewer })` says who that is. A member rule
522
+ over such a member judges the server's value like any other: declare none there.
523
+
524
+ No input may set `ownerId`, which is refused where the write is declared. A
525
+ visitor is no one to set, and is refused (`Unauthenticated`) even where the
526
+ rules would let anyone create. A create of an id already taken is refused as
527
+ `Refusal.taken`, with one answer whatever the row there holds, so it tells
528
+ nothing the asker may not read. Only
529
+ the writer's ledger recognises a retry, by its operation and who asked, and
530
+ answers it with its row, first time kept; the same id from another account is
531
+ refused.
476
532
 
477
533
  A handler writes what its code writes, so it is guarded where it is defined:
478
534
  `GuardServer.mutation` is `RemoteServer.mutation` with the row's rule for one
@@ -502,6 +558,33 @@ GuardServer.mutation(
502
558
  shows the writer only what they may now see of the fields it named, and a
503
559
  row the handler hid from them answers as deleted.
504
560
 
561
+ ### Rules that read another row
562
+
563
+ A row's `Read`, `Update` and `Delete` rules may reach another row: a path
564
+ (`Expr.path`), an exists (`Expr.exists`), or a path from the viewer. A Read
565
+ rule compiles to SQL, which reads the rows it reaches as stored: the rule is
566
+ the server's decision, as a principal guard's body is.
567
+
568
+ An Update or Delete rule is judged in the write's own statement (`update …
569
+ where … and <rule>`), so it reads the other row as the write lands, not as it
570
+ was read a moment before. `GuardServer.writer` judges what the row alone
571
+ decides in memory and hands the rest to its writer as `requires`, which
572
+ remote-drizzle's `writer` holds the row to, refusing with `Forbidden` (and the
573
+ `explain`) where it fails, on SQLite and Postgres.
574
+
575
+ - Such a rule is judged over the row as stored, so a write that would change
576
+ what it reads of its own row (its fields, the relation its path leaves by)
577
+ is refused: a member of one team cannot move a note into a team they hold
578
+ no seat on. Where the row written is the viewer's own, a path from the
579
+ viewer leaves it too: a member whose rule reads their team's organisation
580
+ cannot move their own team.
581
+ - `may` leaves such an interaction unanswered, since one row cannot decide it.
582
+ - `GuardServer.writer` over a writer without `requires` throws where it is
583
+ made, rather than letting the rule go unchecked.
584
+ - Every other surface (`Create`, `Write`, a member, a relation, a named
585
+ interaction, `always`) is judged over one row in memory, so `Guards.attach`
586
+ refuses such a rule there and names the surfaces that may hold one.
587
+
505
588
  ## Checking a server at startup
506
589
 
507
590
  A Source written by hand over a guarded Entity serves every row, and nothing
@@ -523,16 +606,25 @@ It throws, naming each:
523
606
  `cost < $max` halved twenty times reads the cost the row hid. This holds
524
607
  whoever asks, since one body serves every principal. Where some readers
525
608
  must filter by it, give the value an Entity of its own with a row Read
526
- rule: a row a reader may not see is not in their list at all;
609
+ rule: a row a reader may not see is not in their list at all. A member of
610
+ another row the body reaches counts too (each relation a path, a path from
611
+ the viewer or an exists follows, the field it ends at, an exists' filter):
612
+ SQL reads a reached row under its `visible` rule, never its members';
527
613
  - for a declared write of such an Entity that does not land through the
528
- `GuardServer.writer` built for it;
529
- - for a live Source of its own over such an Entity, whose stream nothing can
530
- check: serve its changes through a live hub;
614
+ `GuardServer.writer` built for it, and for one whose interaction (`Create`
615
+ for an insert, `Update`, `Delete`) has no rule under `unguarded: 'allow'`,
616
+ which would let anyone make it: give it a rule, or `[Guards.anyone]` to say
617
+ that anyone may;
618
+ - for a live Source over such an Entity that does not read through the Source
619
+ checked here: `pollLive` over that Source names it (`LiveSource.reads`) and
620
+ passes, as a live hub does; a hand-written stream, or a `pollLive` over
621
+ another Source, is refused;
531
622
  - for an Entity carrying another set's guards;
532
623
  - for a field its Source declares `shared` (sent to every live subscriber as
533
624
  written) when a Read rule could tell readers apart: the rows', `always`, the
534
625
  field's own, or, for a relation, its target rows', a target not among
535
- `entities` included.
626
+ `entities` included; and for `may` declared `shared`, which is each
627
+ reader's own whoever may read the row.
536
628
 
537
629
  A rule built from another `Policy`, for another Entity, or for this one before
538
630
  its guards were attached does not count. Every guarded Entity's Source needs both its rule and its
@@ -543,6 +635,25 @@ Drizzle, each Source takes its `filter`, and each binding its `visible`.
543
635
  A handler (`RemoteServer.mutation`) writes what its code writes, which no
544
636
  check at startup can read.
545
637
 
638
+ ## Diagnostics
639
+
640
+ Two things a guarded server goes past without failing are reported through
641
+ `foldkit-surface`'s `Diagnostics` channel (re-exported by `foldkit-remote`),
642
+ by default Effect's log:
643
+
644
+ | `_tag` | `level` | When |
645
+ | --- | --- | --- |
646
+ | `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`. |
647
+ | `UnpinnedWrites` | `warning` | `GuardServer.validate` found `mutations` writing through a writer with no `revision` that a change can come between. |
648
+
649
+ `ComputeRefused` is reported inside the write, so the reporter the server
650
+ runs with applies (`serveFetch`'s `diagnostics`, or
651
+ `Layer.succeed(Diagnostics.Reporter, report)` in its layer).
652
+ `GuardServer.validate` runs before any Effect of the server's, so it takes
653
+ the reporter as an option, `diagnostics`, beside `entities`, `domain` and
654
+ `server`. In a test, pass `Diagnostics.collect().report` and assert on
655
+ `reported`.
656
+
546
657
  ## Who is asking
547
658
 
548
659
  Authentication decides who is asking; guards only read it. Give the handlers
@@ -577,12 +688,12 @@ fact the cache holds was read as someone.
577
688
 
578
689
  ## What the client may do
579
690
 
580
- The client must not run a rule: it has no bodies, its row may be stale, and it
581
- is not where a write is checked. To grey out a button for the reason the
582
- server would refuse it, it reads the server's answer instead: `Guards.may`
583
- adds a derived member, `may`, which `GuardServer.filter` answers from the row
584
- as its reader sees it. `Todo` above is piped through it after its guards, and
585
- over Drizzle its binding marks it `supplied`, since it is not a column.
691
+ The client has no principal guard's body and none of the principal's fields,
692
+ and it is not where a write is checked. To grey out a button for the reason
693
+ the server would refuse it, it reads the server's answer: `Guards.may` adds a
694
+ derived member, `may`, which `GuardServer.filter` answers from the row as its
695
+ reader sees it. `Todo` above is piped through it after its guards, and over
696
+ Drizzle its binding marks it `supplied`, since it is not a column.
586
697
 
587
698
  ```ts
588
699
  import { May } from 'foldkit-guard'
@@ -611,6 +722,63 @@ May.canLink(row.may, Todo, 'project', 'Link')
611
722
  - `foldkit-crud`'s editor locks the keys the reader may not set with
612
723
  `locks: May.locks(Todo)`, for `foldkit-mixins-form`'s `locked`.
613
724
 
725
+ For a row the client writes, which the server has not answered yet, Remote
726
+ foresees `may` from the same rules (`Derived.make`'s `predict`): a row guard
727
+ over the row, its links and `Expr.viewer` is judged over what the store holds;
728
+ a principal guard, a rule over the principal's fields, and one over a row or
729
+ field the store lacks are unknown. Every rule is an `or` of `and`s with no
730
+ negation, so it is decided where it comes out the same with every unknown part
731
+ taken to hold and taken not to. `may` is foreseen only when every part of it
732
+ is, so a new post's Edit shows at once where its author's rule allows it, and
733
+ nothing is shown where an admin's body would decide.
734
+
735
+ A held `may` also refuses a write where it is made (`Derived.make`'s
736
+ `forbids`): `Data.mutate` of an update whose row's `may.row.Update` is `false`,
737
+ or whose written member or relinked relation reads `false`, or of a delete
738
+ whose `Delete` does, is refused at once with `Forbidden` and the `explain` as
739
+ `reason`, as the server would refuse it. Each is judged over the row before the
740
+ write, which is where the server's writer judges it first. It spares a round
741
+ trip and decides nothing for the server, which judges the write again when it
742
+ arrives. `Law.check` (`foldkit-remote/testing`) runs one write through both and
743
+ compares a refusal made here with the server's, by its `refusal`, or by its
744
+ `_tag` where the mutation declares none.
745
+
746
+ ### What `may` tells a reader, and what it does not
747
+
748
+ `may` is a UI hint; enforcement is on the server only. Every write is checked
749
+ when it is made, by the rules, whatever the client holds or sends: the server
750
+ never reads a `may` from a request, and a `may` that says yes (stale after a
751
+ change of role, foreseen, or edited in the page's cache) changes nothing it
752
+ decides. These hold, each tested against the real handlers (the audit is
753
+ #284):
754
+
755
+ - **No existence oracle.** A row its reader may not see is not read, `may`
756
+ included: the answer is the one for an id that does not exist. A write to
757
+ it is refused as a write to a missing row is (`Forbidden`, or for a delete,
758
+ answered gone).
759
+ - **Its shape is the shared declaration's.** `may` names the same
760
+ interactions, members and relations for every reader and row: those the
761
+ Entity's attachment rules, which the browser bundle carries already. Only
762
+ the booleans are the reader's, and they say what the reader may do, never
763
+ why another may. There is no option to leave a member out, since its name
764
+ is public in the declaration anyway; a fact the reader should not learn
765
+ belongs in a principal guard's body, which never leaves the server.
766
+ - **A reason is the declaration's sentence.** `reasons` holds only an
767
+ `explain`'s text, for an interaction refused to this reader; a plain refusal
768
+ says nothing. The text is a constant of shared code, so it ships in the
769
+ bundle whether or not it is sent: write it for the reader, never naming
770
+ another person, an id, or how the rule decides. No type or lint rule checks
771
+ wording, so this one is review's.
772
+ - **One reader's answer is no one else's.** `GuardServer.validate` refuses a
773
+ Source that shares `may` with every live subscriber, and `serveFetch`
774
+ answers every request `cache-control: no-store`. Pages that render a
775
+ reader's rows into HTML (`foldkit-ssr`) send their own `private, no-store`
776
+ through the entry's `headers`, and a client changing principal calls
777
+ `Remote.forget`.
778
+ - **A foreseen `may` is never sent.** What the client foresees for a row it
779
+ wrote is shown until the server's answer replaces it; a write's input is its
780
+ Mutation's, and `may` is not in it.
781
+
614
782
  ## Who the client is: `Me`
615
783
 
616
784
  "Show the Admin link", "show a sign-in page rather than a 404" and "who am
@@ -644,6 +812,10 @@ const MeSource = GuardServer.me(Me, Policy)
644
812
  `validate` lets a Source share them.
645
813
  - `may` is read with the row, as any `may` is: a principal whose role
646
814
  changes sees it when `Me` is read again.
815
+ - `key` is the set's `key` of the principal, shown to that principal: make it
816
+ an id, never a session token or anything secret. `Me` is answered per
817
+ request, shares nothing with live subscribers, and goes out under
818
+ `serveFetch`'s `no-store`.
647
819
 
648
820
  ## When a rule refuses
649
821
 
@@ -654,6 +826,7 @@ const MeSource = GuardServer.me(Me, Policy)
654
826
  | A member's Read refused (`redact`) | the replacement value | `Ready` with it, by design indistinguishable |
655
827
  | A relation's Read refused | withheld, as a member's | unavailable |
656
828
  | A write refused | `Forbidden`, a 403 over JSON | `Data.mutation` is `Failed` with `_tag: 'Forbidden'`, `reason` from an `explain` |
829
+ | A visitor's write refused | `Unauthenticated`, a 401 over JSON | `Failed` with `_tag: 'Unauthenticated'`; a durable write waits for a sign-in |
657
830
  | A write moved a row out of its writer's sight | answered in `deleted` | tombstoned; it leaves every list |
658
831
  | A delete of a row its writer cannot see | nothing deleted; answered gone | tombstoned |
659
832
  | A Sync edit refused | rejected by its id, with its reason | the replica drops it, with the reason |
@@ -710,9 +883,11 @@ differ from person to person, and a document is one audience.
710
883
  the row's `Update`, and each changed member's, with an `explain`'s
711
884
  sentence. It reads no row, and its bodies must not suspend.
712
885
  - **Before the journal**, `admit` reads each row an edit names through the
713
- Entity's guarded Source: a row the principal cannot see is refused, the
714
- row's `Update` must hold over it as it is and as it would be after all of
715
- the operation's edits to it, and each changed member's rule must hold. An
886
+ Entity's guarded Source: a row the principal cannot see is refused, and
887
+ the row's `Update` must hold over it as it is and as it would be after all
888
+ of the operation's edits to it. Each changed member's rule must hold over
889
+ it as it is, and as the edits would leave it with that member's own edit
890
+ undone, as for a writer. An
716
891
  edit to a member outside the document, or a value its member cannot
717
892
  encode, is refused.
718
893
  - **A document is one audience.** Every replica that opens it receives every
@@ -808,16 +983,17 @@ const uploads = uploadLayer().pipe(
808
983
 
809
984
  ## Limits
810
985
 
811
- - **No rule runs on the client.** `may` is the server's answer for the row as
812
- it was read, as stale as the row; a live patch of a field its rules read
813
- does not answer it again.
986
+ - **`may` is as stale as its row.** It is the server's answer for the row as
987
+ it was read, or the client's reading of the rules for a row it wrote; a
988
+ live patch of a field its rules read does not answer it again.
814
989
  - **A handler's own writes are its own to check.** `GuardServer.mutation`
815
990
  checks the row's rule for its interaction; members it sets and relations
816
991
  it points are not known to it, and no startup check can read them.
817
- - **Under a guard, a create refetches the lists over its Entity.** The client
818
- cannot tell an answer read back under the writer's rule from one a plain
819
- handler made up, so it does not place a created row by the list's body
820
- alone.
992
+ - **Under a Read rule over fields, a new row is fetched into a list, not
993
+ placed.** `Guards.attach` records the members the row's Read rules read, and
994
+ the client, which runs none of them, refetches a list when a row it does not
995
+ hold changes one of them, as a create does: only the server can say whether
996
+ the rule lets it in.
821
997
  - **A Sync document is one audience.** Per-member or per-row secrecy within
822
998
  one is not something a replicated log offers: `GuardSync.document` refuses
823
999
  it where it is declared.
@@ -840,5 +1016,6 @@ const uploads = uploadLayer().pipe(
840
1016
  - **Sync's `authorize` is synchronous.** Its principal guards' bodies must not
841
1017
  suspend; row guards run in `admit`, which may.
842
1018
  - **A row guard over a field the client sets on create** reads as matching
843
- nothing while the create leaves it unset; use a preset (`presets`) for a
844
- field that should be the creator's.
1019
+ nothing while the create leaves it unset; declare a field that should be the
1020
+ creator's with `Entity.sets` (see [Serving writes](#serving-writes)), and the
1021
+ 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-BepaL930.mjs";
1
+ import { j as MayAnswer, l as InteractionKey } from "./attach-CJl-GtbN.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,MAAa,cAAc;;AAEzB,OAAkC,SAAkC;CAClE,IAAK,QAAkC,SAAS,IAAI,GAClD,MAAM,IAAI,MAAM,sCAAsC,KAAK,4BAA4B;CAEzF,OAAO,OAAO,OAAO;EAAE;EAAM,KAAK;CAA6B,CAAC;AAClE,EACF;AAyIA,MAAM,eAAqC,OAAO,OAAO,IAAI;AAE7D,MAAM,iBAAiB,MAA+B,aAAqB,UA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