foldkit-guard 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -6
- package/dist/agent.d.mts +1 -1
- package/dist/{attach-DPgyv78F.d.mts → attach-CJl-GtbN.d.mts} +79 -8
- package/dist/attach-CJl-GtbN.d.mts.map +1 -0
- package/dist/drizzle.d.mts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/media.d.mts +1 -1
- package/dist/server.d.mts +20 -4
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +73 -12
- package/dist/server.mjs.map +1 -1
- package/dist/sync.d.mts +1 -1
- package/package.json +16 -16
- package/dist/attach-DPgyv78F.d.mts.map +0 -1
package/README.md
CHANGED
|
@@ -120,8 +120,11 @@ What each call does, and does not:
|
|
|
120
120
|
|
|
121
121
|
- `Guards.declare` reads nothing and stores nothing. It builds each row
|
|
122
122
|
guard's predicate once, with placeholders (`p.id` is the input
|
|
123
|
-
`principal.id`), and checks it is a rule over its own Entity
|
|
124
|
-
|
|
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.
|
|
125
128
|
- `G.implement` is the only place a body exists. A missing or extra key is a
|
|
126
129
|
type error, and refused at runtime for a caller the types do not reach.
|
|
127
130
|
- `Policy.decide` is an `Effect` of a `Decision`: `true`, `false`, or
|
|
@@ -225,6 +228,11 @@ Beyond the row's own fields:
|
|
|
225
228
|
`Policy.viewer(principal)` is that row's ref, the server's one viewer:
|
|
226
229
|
`RemoteServer.make({ viewer: Policy.viewer })`. A rule over `Expr.viewer`
|
|
227
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.
|
|
228
236
|
- A row's `Read`, `Update` and `Delete` rules may reach another row
|
|
229
237
|
(`Expr.path`, `Expr.exists`, a path from the viewer: `Expr.eq(Note.fields.orgId,
|
|
230
238
|
orgOfViewer)`). A Read rule compiles to SQL; an Update or Delete rule is
|
|
@@ -375,6 +383,18 @@ A seam built from `ReadPolicy` counts as built from `Checked`, so
|
|
|
375
383
|
runs the declared rules, not which services they were given. The write seams take the
|
|
376
384
|
Policy as it is and require its services where the write runs.
|
|
377
385
|
|
|
386
|
+
### Guarded reads are never kept at the edge
|
|
387
|
+
|
|
388
|
+
`foldkit-remote-server`'s `serveFetch` keeps a read only when it can prove
|
|
389
|
+
the answer is the same for whoever asks (its `cache`, #428). Every read seam
|
|
390
|
+
above becomes a rule on the Source (`visible`, `filter` or `readable`), a
|
|
391
|
+
function of the principal the server cannot read, so a read of a guarded
|
|
392
|
+
Entity is never kept, and a page that made one is never kept either
|
|
393
|
+
(`foldkit-ssr`'s `cache`). This holds for a rule over the row alone
|
|
394
|
+
(`published = true`) too: the server cannot tell it from one over the
|
|
395
|
+
principal. To cache such rows, serve them from an Entity no guard reads
|
|
396
|
+
restrict.
|
|
397
|
+
|
|
378
398
|
## Serving writes
|
|
379
399
|
|
|
380
400
|
A declared write (`Mutation.write`) is served by `RemoteServer.write` with no
|
|
@@ -421,11 +441,27 @@ RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
|
|
|
421
441
|
it leaves unset does not hold, whatever it asks (`isNull` and `isNotNull`
|
|
422
442
|
alike): the create never said what the field holds.
|
|
423
443
|
- A refusal is `Forbidden`, with the sentence `Guards.explain` gave; the
|
|
424
|
-
write never runs.
|
|
444
|
+
write never runs. A visitor is refused as `Unauthenticated` instead, with
|
|
445
|
+
the same sentence: no one is signed in, so the remedy is a sign-in, and a
|
|
446
|
+
client tells a session that ended (its cookie gone) from a person refused.
|
|
447
|
+
Remote's outbox keeps a durable write so answered until the sign-in.
|
|
425
448
|
- The answer is read back under the binding's `visible` and the Entity's
|
|
426
449
|
member Read rules: the row as its writer may now see it, with no more
|
|
427
450
|
fields than the write set, and a row the write hid from them in `deleted`,
|
|
428
451
|
so the client takes it out of its lists instead of placing it.
|
|
452
|
+
- A delete that cascades (`Relation.one(Post, { onDelete: 'cascade' })`)
|
|
453
|
+
takes no row its deleter may not delete. Each row it takes is held to its
|
|
454
|
+
own `Delete` rule, for the same person, in the statement that deletes the
|
|
455
|
+
row named, before anything is removed (on D1, in the same batch): one
|
|
456
|
+
refused, and the whole delete is `Forbidden`, nothing removed, saying
|
|
457
|
+
"It would delete a Like you may not delete" with the like's `explain`.
|
|
458
|
+
The refusal names the Entity, never which row or whose. The rules come
|
|
459
|
+
from each child's guarded Entity, given as `children`:
|
|
460
|
+
`GuardServer.writer(Post, Policy, writer(Db.Post), { children: [Like] })`;
|
|
461
|
+
one missing, or one given that no cascade judges, is refused where the
|
|
462
|
+
writer is made. A relation declared `authorizedBy: 'parent'` lets whoever
|
|
463
|
+
may delete the post take those rows unjudged, which is a choice the domain
|
|
464
|
+
states: a post's author removing everyone's likes of it.
|
|
429
465
|
|
|
430
466
|
Reading the row and writing it are two statements, so another write can land
|
|
431
467
|
between the check and the write. Name a revision, a field stored as a number
|
|
@@ -511,8 +547,8 @@ creator's, and `RemoteServer.make({ viewer })` says who that is. A member rule
|
|
|
511
547
|
over such a member judges the server's value like any other: declare none there.
|
|
512
548
|
|
|
513
549
|
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
|
|
515
|
-
anyone create. A create of an id already taken is refused as
|
|
550
|
+
visitor is no one to set, and is refused (`Unauthenticated`) even where the
|
|
551
|
+
rules would let anyone create. A create of an id already taken is refused as
|
|
516
552
|
`Refusal.taken`, with one answer whatever the row there holds, so it tells
|
|
517
553
|
nothing the asker may not read. Only
|
|
518
554
|
the writer's ledger recognises a retry, by its operation and who asked, and
|
|
@@ -725,7 +761,10 @@ A held `may` also refuses a write where it is made (`Derived.make`'s
|
|
|
725
761
|
`forbids`): `Data.mutate` of an update whose row's `may.row.Update` is `false`,
|
|
726
762
|
or whose written member or relinked relation reads `false`, or of a delete
|
|
727
763
|
whose `Delete` does, is refused at once with `Forbidden` and the `explain` as
|
|
728
|
-
`reason`, as the server would refuse it.
|
|
764
|
+
`reason`, as the server would refuse it. So is a delete that would take a
|
|
765
|
+
held row whose own `may` refuses `Delete` (under `authorizedBy: 'child'`), in
|
|
766
|
+
the server's words; a row taken whose `may` the page does not hold is shown
|
|
767
|
+
gone, and the server's refusal brings it back. Each is judged over the row before the
|
|
729
768
|
write, which is where the server's writer judges it first. It spares a round
|
|
730
769
|
trip and decides nothing for the server, which judges the write again when it
|
|
731
770
|
arrives. `Law.check` (`foldkit-remote/testing`) runs one write through both and
|
|
@@ -815,6 +854,7 @@ const MeSource = GuardServer.me(Me, Policy)
|
|
|
815
854
|
| A member's Read refused (`redact`) | the replacement value | `Ready` with it, by design indistinguishable |
|
|
816
855
|
| A relation's Read refused | withheld, as a member's | unavailable |
|
|
817
856
|
| A write refused | `Forbidden`, a 403 over JSON | `Data.mutation` is `Failed` with `_tag: 'Forbidden'`, `reason` from an `explain` |
|
|
857
|
+
| A visitor's write refused | `Unauthenticated`, a 401 over JSON | `Failed` with `_tag: 'Unauthenticated'`; a durable write waits for a sign-in |
|
|
818
858
|
| A write moved a row out of its writer's sight | answered in `deleted` | tombstoned; it leaves every list |
|
|
819
859
|
| A delete of a row its writer cannot see | nothing deleted; answered gone | tombstoned |
|
|
820
860
|
| A Sync edit refused | rejected by its id, with its reason | the replica drops it, with the reason |
|
package/dist/agent.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { j as MayAnswer, l as InteractionKey } from "./attach-
|
|
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<{
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Context, Effect, Option, Schema } from "effect";
|
|
2
|
-
import { AnyEntity, AnyQuery, Entity, EntityRef, ExprContext, Forbids, HeldRow, HeldRows, InputExpr, MemoryOperators, Predicate, Predict } from "foldkit-entity";
|
|
2
|
+
import { AnyEntity, AnyQuery, Entity, EntityRef, ExprContext, Forbids, HeldRow, HeldRows, InputExpr, Invalid, MemoryOperators, Predicate, Predict, ReadsOf } from "foldkit-entity";
|
|
3
3
|
type Condition = {
|
|
4
4
|
readonly _tag: 'Always';
|
|
5
5
|
} | {
|
|
@@ -121,7 +121,7 @@ declare const May: {
|
|
|
121
121
|
*/
|
|
122
122
|
member: <E extends AnyEntity>(entity: E & ("may" & keyof E["members"] extends never ? unknown : {
|
|
123
123
|
readonly alreadyAMember: "may" & keyof E["members"];
|
|
124
|
-
})) => E extends
|
|
124
|
+
})) => E extends import("foldkit-entity").VariantEntity<infer Name extends string, infer Fields extends Schema.Struct.Fields, infer R extends Readonly<Record<string, import("foldkit-entity").RelationSpec<AnyEntity, import("foldkit-entity").Cardinality, boolean>>>, infer D extends Readonly<Record<string, import("foldkit-entity").DerivedSpec<Schema.Constraint, {
|
|
125
125
|
readonly _tag: "Count";
|
|
126
126
|
readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
|
|
127
127
|
} | {
|
|
@@ -132,7 +132,37 @@ declare const May: {
|
|
|
132
132
|
readonly _tag: "Supplied";
|
|
133
133
|
readonly predict: Option.Option<Predict>;
|
|
134
134
|
readonly forbids: Option.Option<Forbids>;
|
|
135
|
-
}
|
|
135
|
+
}>>>, infer U extends Schema.Top & {
|
|
136
|
+
readonly tag: '_tag';
|
|
137
|
+
readonly cases: Readonly<Record<string, {
|
|
138
|
+
readonly fields: Schema.Struct.Fields;
|
|
139
|
+
}>>;
|
|
140
|
+
}> ? import("foldkit-entity").VariantEntity<Name, Fields, R, D & {
|
|
141
|
+
readonly may: import("foldkit-entity").DerivedSpec<Schema.Struct<{
|
|
142
|
+
readonly row: Schema.$Record<Schema.String, Schema.Boolean>;
|
|
143
|
+
readonly reasons: Schema.$Record<Schema.String, Schema.String>;
|
|
144
|
+
readonly members: Schema.$Record<Schema.String, Schema.Boolean>;
|
|
145
|
+
readonly relations: Schema.$Record<Schema.String, Schema.Struct<{
|
|
146
|
+
readonly Link: Schema.Boolean;
|
|
147
|
+
readonly Unlink: Schema.Boolean;
|
|
148
|
+
}>>;
|
|
149
|
+
}>, {
|
|
150
|
+
readonly _tag: "Supplied";
|
|
151
|
+
readonly predict: Option.Option<Predict>;
|
|
152
|
+
readonly forbids: Option.Option<Forbids>;
|
|
153
|
+
}>;
|
|
154
|
+
}, U> : E extends Entity<infer Name_1 extends string, infer Fields_1 extends Schema.Struct.Fields, infer R_1 extends Readonly<Record<string, import("foldkit-entity").RelationSpec<AnyEntity, import("foldkit-entity").Cardinality, boolean>>>, infer D_1 extends Readonly<Record<string, import("foldkit-entity").DerivedSpec<Schema.Constraint, {
|
|
155
|
+
readonly _tag: "Count";
|
|
156
|
+
readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
|
|
157
|
+
} | {
|
|
158
|
+
readonly _tag: "Exists";
|
|
159
|
+
readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
|
|
160
|
+
readonly viewer: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
|
|
161
|
+
} | {
|
|
162
|
+
readonly _tag: "Supplied";
|
|
163
|
+
readonly predict: Option.Option<Predict>;
|
|
164
|
+
readonly forbids: Option.Option<Forbids>;
|
|
165
|
+
}>>>> ? Entity<Name_1, Fields_1, R_1, D_1 & {
|
|
136
166
|
readonly may: import("foldkit-entity").DerivedSpec<Schema.Struct<{
|
|
137
167
|
readonly row: Schema.$Record<Schema.String, Schema.Boolean>;
|
|
138
168
|
readonly reasons: Schema.$Record<Schema.String, Schema.String>;
|
|
@@ -380,9 +410,20 @@ interface Policy<User, R = never> {
|
|
|
380
410
|
interface Builders<User> {
|
|
381
411
|
/** A guard decided from the principal alone, by a body only the server has. */
|
|
382
412
|
readonly principal: () => PrincipalSpec;
|
|
383
|
-
/**
|
|
384
|
-
|
|
413
|
+
/**
|
|
414
|
+
* A guard over `entity`'s rows: a predicate with the principal's fields as
|
|
415
|
+
* inputs. A predicate reading another Entity's fields is refused where it
|
|
416
|
+
* is written; one typed plain `Predicate` is checked when the set is
|
|
417
|
+
* declared.
|
|
418
|
+
*/
|
|
419
|
+
readonly row: <E extends AnyEntity, P extends RuleOver<P, E['name']>>(entity: E, body: (principal: Placeholders<User>) => P) => RowSpec<E>;
|
|
385
420
|
}
|
|
421
|
+
/**
|
|
422
|
+
* What a rule over the Entity `Name` may be: a predicate reading `Name`'s
|
|
423
|
+
* fields and relations, inputs and the viewer, or one whose reads are unknown
|
|
424
|
+
* to the type (a plain `Predicate`).
|
|
425
|
+
*/
|
|
426
|
+
type RuleOver<P, Name extends string> = string extends ReadsOf<P> ? Predicate : [ReadsOf<P>] extends [Name] ? Predicate : Predicate & Invalid<`foldkit-guard: a rule over ${Name} reads ${Exclude<ReadsOf<P>, Name>}`>;
|
|
386
427
|
declare const Guards: {
|
|
387
428
|
/**
|
|
388
429
|
* Adds the `may` member, the server's answer to what a principal may do
|
|
@@ -391,7 +432,37 @@ declare const Guards: {
|
|
|
391
432
|
*/
|
|
392
433
|
may: <E extends AnyEntity>(entity: E & ("may" & keyof E["members"] extends never ? unknown : {
|
|
393
434
|
readonly alreadyAMember: "may" & keyof E["members"];
|
|
394
|
-
})) => E extends import("foldkit-entity").
|
|
435
|
+
})) => E extends import("foldkit-entity").VariantEntity<infer Name extends string, infer Fields extends Schema.Struct.Fields, infer R extends Readonly<Record<string, import("foldkit-entity").RelationSpec<AnyEntity, import("foldkit-entity").Cardinality, boolean>>>, infer D extends Readonly<Record<string, import("foldkit-entity").DerivedSpec<Schema.Constraint, {
|
|
436
|
+
readonly _tag: "Count";
|
|
437
|
+
readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
|
|
438
|
+
} | {
|
|
439
|
+
readonly _tag: "Exists";
|
|
440
|
+
readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
|
|
441
|
+
readonly viewer: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
|
|
442
|
+
} | {
|
|
443
|
+
readonly _tag: "Supplied";
|
|
444
|
+
readonly predict: Option.Option<import("foldkit-entity").Predict>;
|
|
445
|
+
readonly forbids: Option.Option<import("foldkit-entity").Forbids>;
|
|
446
|
+
}>>>, infer U extends Schema.Top & {
|
|
447
|
+
readonly tag: '_tag';
|
|
448
|
+
readonly cases: Readonly<Record<string, {
|
|
449
|
+
readonly fields: Schema.Struct.Fields;
|
|
450
|
+
}>>;
|
|
451
|
+
}> ? import("foldkit-entity").VariantEntity<Name, Fields, R, D & {
|
|
452
|
+
readonly may: import("foldkit-entity").DerivedSpec<Schema.Struct<{
|
|
453
|
+
readonly row: Schema.$Record<Schema.String, Schema.Boolean>;
|
|
454
|
+
readonly reasons: Schema.$Record<Schema.String, Schema.String>;
|
|
455
|
+
readonly members: Schema.$Record<Schema.String, Schema.Boolean>;
|
|
456
|
+
readonly relations: Schema.$Record<Schema.String, Schema.Struct<{
|
|
457
|
+
readonly Link: Schema.Boolean;
|
|
458
|
+
readonly Unlink: Schema.Boolean;
|
|
459
|
+
}>>;
|
|
460
|
+
}>, {
|
|
461
|
+
readonly _tag: "Supplied";
|
|
462
|
+
readonly predict: Option.Option<import("foldkit-entity").Predict>;
|
|
463
|
+
readonly forbids: Option.Option<import("foldkit-entity").Forbids>;
|
|
464
|
+
}>;
|
|
465
|
+
}, U> : E extends import("foldkit-entity").Entity<infer Name_1 extends string, infer Fields_1 extends Schema.Struct.Fields, infer R_1 extends Readonly<Record<string, import("foldkit-entity").RelationSpec<AnyEntity, import("foldkit-entity").Cardinality, boolean>>>, infer D_1 extends Readonly<Record<string, import("foldkit-entity").DerivedSpec<Schema.Constraint, {
|
|
395
466
|
readonly _tag: "Count";
|
|
396
467
|
readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
|
|
397
468
|
} | {
|
|
@@ -402,7 +473,7 @@ declare const Guards: {
|
|
|
402
473
|
readonly _tag: "Supplied";
|
|
403
474
|
readonly predict: Option.Option<import("foldkit-entity").Predict>;
|
|
404
475
|
readonly forbids: Option.Option<import("foldkit-entity").Forbids>;
|
|
405
|
-
}>>>> ? import("foldkit-entity").Entity<
|
|
476
|
+
}>>>> ? import("foldkit-entity").Entity<Name_1, Fields_1, R_1, D_1 & {
|
|
406
477
|
readonly may: import("foldkit-entity").DerivedSpec<Schema.Struct<{
|
|
407
478
|
readonly row: Schema.$Record<Schema.String, Schema.Boolean>;
|
|
408
479
|
readonly reasons: Schema.$Record<Schema.String, Schema.String>;
|
|
@@ -586,4 +657,4 @@ interface Attachment {
|
|
|
586
657
|
}
|
|
587
658
|
declare const attached: (entity: AnyEntity) => Option.Option<Attachment>;
|
|
588
659
|
export { May as A, PrincipalGuard as C, RowSpec as D, RowGuard as E, RowRule as F, MaySchema as M, Condition as N, ME as O, MemberRead as P, Policy as S, PrincipalSpec as T, Builders as _, Deny as a, Guards as b, Interaction as c, Redact as d, RuleFor as f, Body as g, AnyGuard as h, Attachment as i, MayAnswer as j, MeEntity as k, InteractionKey as l, About as m, AnyRule as n, Explain as o, Surface as p, Attach as r, Inherit as s, All as t, On as u, Decision as v, PrincipalOf as w, Placeholders as x, GuardSet as y };
|
|
589
|
-
//# sourceMappingURL=attach-
|
|
660
|
+
//# sourceMappingURL=attach-CJl-GtbN.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attach-CJl-GtbN.d.mts","names":["MemberKeys","_$__attach_js0.Attach","_$__attach_js0.AnyRule","_$__attach_js0.Inherit","_$__attach_js0.All","_$__attach_js0.Redact","_$__attach_js0.Explain","_$__attach_js0.On"],"sources":["../src/condition.ts","../src/may.ts","../src/me.ts","../src/index.ts","../src/attach.ts"],"mappings":";;KAuBY;WACG;;WACA;;;;WAGA;WACA,OAAO,cAAc;WACrB,SAAS;;;;WAGT;WAA0B;;WAC1B;WAAsB,YAAY,cAAc;;WAChD;WAAqB,YAAY,cAAc;;;cAUxD,MAAG,YAAgB,cAAc,eAAa;;cAY9C,KAAE,YAAgB,cAAc,eAAa;cAWtC;;aA5CQ;;;aACA;;;;;;;;;;;;;;EA4DN,QAAA,WAAA,WAAS,QACZ,SAAS,0BAAwB,OAClC,SAAS,0BAAwB,UAC9B,8BAA4B,WAC3B;;;;;;;;EA2BA,WAAA,WAAA,WAAS,QACZ,SAAS,0BAAwB,OAClC,SAAS,0BAAwB,WAC7B,oBACV;;EAmBkB,UAAA,WAAA,cAAY,OAAO;;;;;;;;;EAkBf,cAAA,WAAA,WAAS,SAAW,cAAY;;;;;;;;;EA2CtC,QAAA,WAAA,WAAS,KAAO,SAAO,MAAQ,UAAQ;;;;;;;EA0BnC,YAAA,WAAA,WAAS,OAAS,wBAAsB;;EAiB1C,UAAA,WAAA,cAAY;;;UAelB;WACN;WACA,WAAW;WACX,MAAM;;;UAyDA;WACN,WAAW;WACX,MAAM;;;;;;;;cC9SJ,WAAS,OAAA;;;;;;;;;KASV,mBAAmB,UAAU;KAEpCA,aAAW,UAAU,oBAAoB,oBAAoB;cA+LrD;;;;;;;EAOX,SAAM,UAAA,WAAA,QAAA,mBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAON,MAAG,KAA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aAAa,UAAU,gBACzB,WAAW,iBAAiB,eAAe;WAAsB;IAAuB,mBACnF;KAGH,WAAW,UAAU,oBAAoB,oBAAoB;KAE7D,OAAO,UAAU,WAAW,gBAAgB,gBAAgB,aAAa;;KAGlE,OAAO,MAAM,oBAAoB,UAAU;WAC5C;aACE,OAAO,cAAc,QAAQ,MAAM,KAAK,aAAa,QAAQ,aAAa;aAC1E,SAAS,UAAU,QAAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;;aAEtC,QAAQ,UAAU,QAAQ,MAAM,KAAK;;;;;;;;WAQvC;cACG,GAAG,iBAAiB,UAAU,QAAQ,MAAM,KAAK;;;WAGpD,sBACG,KAAK,WAAW;aACf,OAAO,KAAK,QAAQ,MAAM,KAAK,YAAY,OAAO,OAAO,GAAG;;aAE5D,SAAS,UAAU,QAAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;;WAG1C,wBACG,WAAW;aACV,OAAO,cAAc,QAAQ,MAAM,KAAK;aACxC,OAAO,UAAU,QAAQ,MAAM,KAAK;aACpC,SAAS,UAAU,QAAQ,MAAM,KAAK;;;WAI1C,SAAS,cAAc,QAAQ,MAAM,KAAK;;;UAIpC;WACN,OAAO,cAAc;WACrB,MAAM,OAAO,OAAO;;KAG1B,WAAW,SAAS,eAAe;;UAGvB;WACN;WACA;WACA,KAAK;WACL,SAAS,SAAS,eAAe;WACjC,WAAW,SAAS,eAAe;WACnC,QAAQ,cAAc;;cAoSpB,WAAQ,QAAY,cAAY,OAAO,OAAO"}
|
package/dist/drizzle.d.mts
CHANGED
package/dist/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as May, C as PrincipalGuard, D as RowSpec, E as RowGuard, F as RowRule, M as MaySchema, N as Condition, O as ME, P as MemberRead, S as Policy, T as PrincipalSpec, _ as Builders, a as Deny, b as Guards, c as Interaction, d as Redact, f as RuleFor, g as Body, h as AnyGuard, i as Attachment, j as MayAnswer, k as MeEntity, l as InteractionKey, m as About, n as AnyRule, o as Explain, p as Surface, r as Attach, s as Inherit, t as All, u as On, v as Decision, w as PrincipalOf, x as Placeholders, y as GuardSet } from "./attach-
|
|
1
|
+
import { A as May, C as PrincipalGuard, D as RowSpec, E as RowGuard, F as RowRule, M as MaySchema, N as Condition, O as ME, P as MemberRead, S as Policy, T as PrincipalSpec, _ as Builders, a as Deny, b as Guards, c as Interaction, d as Redact, f as RuleFor, g as Body, h as AnyGuard, i as Attachment, j as MayAnswer, k as MeEntity, l as InteractionKey, m as About, n as AnyRule, o as Explain, p as Surface, r as Attach, s as Inherit, t as All, u as On, v as Decision, w as PrincipalOf, x as Placeholders, y as GuardSet } from "./attach-CJl-GtbN.mjs";
|
|
2
2
|
export { About, type All, AnyGuard, type AnyRule, type Attach, type Attachment, Body, Builders, Condition, Decision, type Deny, type Explain, GuardSet, Guards, type Inherit, Interaction, type InteractionKey, ME, May, type MayAnswer, MaySchema, type MeEntity, type MemberRead, type On, Placeholders, Policy, PrincipalGuard, PrincipalOf, PrincipalSpec, type Redact, RowGuard, type RowRule, RowSpec, type RuleFor, type Surface };
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Who may do what, declared once on the domain.\n *\n * A guard set names its guards once, in shared code the client imports too.\n * A **principal guard** is declared by name and implemented only on the\n * server (`G.implement`), so its logic never ships. A **row guard** is an\n * `Expr` over one Entity's fields with the principal's fields as inputs: data,\n * which the SQL compiler and `evaluate` both run. See `guard-DESIGN.md`.\n */\nimport { Context, Effect, Match, Option, Schema } from 'effect'\nimport { Attaching, attached, type InteractionKey } from './attach.js'\nimport {\n deciding,\n readsPrincipal,\n type Condition,\n type MemberRead,\n type RowRule,\n} from './condition.js'\nimport { May } from './may.js'\nimport { me } from './me.js'\nimport { providedFrom } from './origin.js'\nimport {\n Expr,\n Operators,\n Query,\n evaluate,\n type AnyEntity,\n type EntityRef,\n type ExprContext,\n type MemoryOperators,\n type AnyQuery,\n type InputExpr,\n type Predicate,\n} from 'foldkit-entity'\n\n/** A guard's answer: allowed, refused, or refused with a sentence the caller may read. */\nexport type Decision = boolean | { readonly allowed: false; readonly reason: string }\n\n/** What a principal guard is asked about. */\nexport interface About {\n /** The interaction attempted: `Read`, `Update`, or one the application names. */\n readonly interaction: string\n}\n\n/**\n * The principal's fields as a row guard's body sees them: each an input named\n * `principal.<field>`, typed as the field. A body is built once, so it holds\n * these placeholders and never a value: branching on one is a type error.\n */\nexport type Placeholders<User> = {\n readonly [K in keyof User & string]: InputExpr<User[K]>\n}\n\n/** What `guard.principal()` declares: a name whose body the server supplies. */\nexport interface PrincipalSpec {\n readonly _tag: 'PrincipalSpec'\n}\n\n/** What `guard.row(entity, body)` declares: a predicate over one Entity's rows. */\nexport interface RowSpec<E extends AnyEntity> {\n readonly _tag: 'RowSpec'\n readonly entity: E\n readonly body: Predicate\n}\n\ntype AnySpec = PrincipalSpec | RowSpec<AnyEntity>\n\n/**\n * The principal a guard is for, kept in the type so a guard of one principal\n * cannot stand where another's is wanted. A function type, so it is invariant.\n */\ninterface ForPrincipal<User> {\n readonly '~principal'?: (user: User) => User\n}\n\n/** A guard whose body lives on the server, asked of the principal alone. */\nexport interface PrincipalGuard<User, Set extends string = string> extends ForPrincipal<User> {\n readonly _tag: 'PrincipalGuard'\n readonly name: string\n /** The name of the guard set it belongs to. */\n readonly set: Set\n}\n\n/** A guard over the rows of `E`: its predicate, and the query that asks it of rows. */\nexport interface RowGuard<\n User,\n E extends AnyEntity,\n Set extends string = string,\n> extends ForPrincipal<User> {\n readonly _tag: 'RowGuard'\n readonly name: string\n readonly set: Set\n readonly entity: E\n readonly body: Predicate\n /** `from(entity).where(body)`, for an interpreter that runs queries. */\n readonly query: AnyQuery\n}\n\nexport type AnyGuard<User> = PrincipalGuard<User> | RowGuard<User, AnyEntity>\n\ntype GuardOf<User, Set extends string, S> =\n S extends RowSpec<infer E> ? RowGuard<User, E, Set> : PrincipalGuard<User, Set>\n\n/** The keys of a spec record that are principal guards: what `implement` must supply. */\ntype PrincipalKeys<S> = { [K in keyof S]: S[K] extends PrincipalSpec ? K : never }[keyof S]\n\n/** A principal guard's body, on the server. */\nexport type Body<User, R = never> = (\n principal: Option.Option<User>,\n about: About,\n) => Decision | Effect.Effect<Decision, never, R>\n\n/** Names a guard set reserves for itself, which no guard may take. */\nconst reserved = [\n 'name',\n 'schema',\n 'Principal',\n 'key',\n 'unguarded',\n 'inputOf',\n 'implement',\n] as const\ntype Reserved = (typeof reserved)[number]\n\n/** Who is asking, for one guard set: a visitor is `none`. */\nexport interface PrincipalOf<Name extends string> {\n readonly '~guardSet': Name\n}\n\n/** The guard set of one application, as `Guards.declare` returns it. */\nexport type GuardSet<Name extends string, User, S> = {\n readonly [K in keyof S]: GuardOf<User, Name, S[K]>\n} & {\n readonly name: Name\n /** The principal's schema, whose fields the row guards read. */\n readonly schema: Schema.Codec<User, unknown>\n /** The server's Context key for who is asking. Authentication provides it. */\n readonly Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>\n /** A stable name for the person, whatever their claims: for what is theirs, as a cache's scope. */\n readonly key: (user: User) => string\n readonly unguarded: 'allow' | 'deny'\n /** The principal's fields as row guards' inputs, encoded as stored values are. */\n readonly inputOf: (user: User) => Readonly<Record<string, unknown>>\n /**\n * The bodies of the principal guards: every one, and nothing else. `operators`\n * runs the row guards' primitive operators in memory; `Operators.kernel` when\n * not given.\n */\n readonly implement: <R = never>(\n bodies: { readonly [K in PrincipalKeys<S>]: Body<User, R> },\n options?: { readonly operators?: MemoryOperators | undefined },\n ) => Policy<User, R>\n}\n\n/** The server's half of a guard set: every principal guard's body. */\nexport interface Policy<User, R = never> {\n readonly set: string\n /**\n * How a row guard's primitive operators are run in memory: by `decide`,\n * `Condition.holds` and every guarded server judging a row. Given to\n * `implement`; `Operators.kernel` when not.\n */\n readonly operators: MemoryOperators\n /**\n * Whether `guard` allows `principal`, for a row guard over `row` (its stored,\n * encoded values). A visitor passes no row guard that reads a principal's\n * fields; one over the row alone holds for a visitor too.\n */\n readonly decide: (\n guard: AnyGuard<User>,\n request: {\n readonly principal: Option.Option<User>\n readonly interaction: string\n readonly row?: Readonly<Record<string, unknown>> | undefined\n },\n ) => Effect.Effect<Decision, never, R>\n /**\n * Which rows of `entity` `principal` may read, as a condition over the row\n * with every principal guard already decided. An Entity without guards, or\n * of no set, reads `Always`.\n */\n readonly readable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n ) => Effect.Effect<Condition, never, R>\n /** The read rule of each of `members`, relations included, that has one, decided for `principal`. */\n readonly readMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /**\n * Which rows of `entity` `principal` may write by `interaction` (`Create`,\n * `Update`, `Delete`, or one the application named), as a condition over\n * the row, and what a refusal shows.\n */\n readonly writable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: 'Create' | 'Update' | 'Delete' | InteractionKey,\n ) => Effect.Effect<RowRule, never, R>\n /** The rule of each of `members` that has one for setting it, decided for `principal`. */\n readonly writeMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n interaction: 'Create' | 'Update',\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /** A relation's rule for linking or unlinking a row, when it has one. */\n readonly linkable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n relation: string,\n interaction: 'Link' | 'Unlink',\n ) => Effect.Effect<Option.Option<RowRule>, never, R>\n /** The principal's fields as row guards' inputs; a visitor has none. */\n readonly inputOf: (principal: Option.Option<User>) => Readonly<Record<string, unknown>>\n /**\n * Who the principal is as a row: `declare`'s `viewer` Entity, by `key`.\n * What a rule's `Expr.viewer` reads, and the server's viewer:\n * `RemoteServer.make({ viewer: Policy.viewer })`. None for a visitor, and\n * for a set that names no `viewer`.\n */\n readonly viewer: (principal: Option.Option<User>) => Option.Option<EntityRef>\n /**\n * Who the principal is: `declare`'s `key`, the same function as `G.key`,\n * here for a server seam that holds the Policy and not the set. Not\n * `keyOf`, which names a principal by every field, for sharing re-reads.\n */\n readonly key: (user: User) => string\n /**\n * Who is asking, as the rules see it: every field of the principal, encoded,\n * a visitor included. Two requests by one person with the same claims answer\n * alike, so a live hub shares their re-reads; a changed claim is not shared.\n *\n * ```ts\n * RemoteServer.liveHub(sources, { key: Policy.keyOf })\n * ```\n */\n readonly keyOf: (principal: Option.Option<User>) => string\n /**\n * Whether `value` is this set's principal, an `Option` of its schema: for a\n * seam that is handed the principal untyped.\n */\n readonly isPrincipal: (value: unknown) => value is Option.Option<User>\n /**\n * This Policy with services its bodies need provided, such as a membership\n * lookup. The read seams (`GuardDrizzle.visible`, `GuardServer.memory`,\n * `GuardSync`) take a Policy that needs nothing more: a read rule runs inside\n * a read whose requirements are its Source's. Provide what stays put here,\n * once; carry what changes per request in the principal. A seam built from\n * the result counts as built from this Policy: `validate` checks the rules,\n * not the services given them. `GuardSync.authorize` runs bodies\n * synchronously, so what it is given must answer without suspending.\n *\n * ```ts\n * const ReadPolicy = Policy.provide(Context.make(Memberships, memberships))\n * ```\n */\n readonly provide: <Provided extends R>(\n context: Context.Context<Provided>,\n ) => Policy<User, Exclude<R, Provided>>\n}\n\n/** `policy` with `context` provided to every body it runs. */\nconst provided = <User, R, Provided extends R>(\n policy: Policy<User, R>,\n context: Context.Context<Provided>,\n): Policy<User, Exclude<R, Provided>> => {\n const run = <A>(effect: Effect.Effect<A, never, R>) => Effect.provide(effect, context)\n const next: Policy<User, Exclude<R, Provided>> = {\n ...policy,\n decide: (guard, request) => run(policy.decide(guard, request)),\n readable: (entity, principal) => run(policy.readable(entity, principal)),\n readMembers: (entity, principal, members) =>\n run(policy.readMembers(entity, principal, members)),\n writable: (entity, principal, interaction) =>\n run(policy.writable(entity, principal, interaction)),\n writeMembers: (entity, principal, members, interaction) =>\n run(policy.writeMembers(entity, principal, members, interaction)),\n linkable: (entity, principal, relation, interaction) =>\n run(policy.linkable(entity, principal, relation, interaction)),\n provide: more => provided(next, more),\n }\n return providedFrom(next, policy)\n}\n\n/** The builders a guard set's declaration is given, typed by its principal. */\nexport interface Builders<User> {\n /** A guard decided from the principal alone, by a body only the server has. */\n readonly principal: () => PrincipalSpec\n /** A guard over `entity`'s rows: a predicate with the principal's fields as inputs. */\n readonly row: <E extends AnyEntity>(\n entity: E,\n body: (principal: Placeholders<User>) => Predicate,\n ) => RowSpec<E>\n}\n\nconst placeholdersOf = <User>(fields: Schema.Struct.Fields): Placeholders<User> =>\n // Built as entries, so a field named `__proto__` is a key of its own, not the prototype.\n Object.freeze(\n Object.fromEntries(\n Object.entries(fields).map(([key, schema]): [string, InputExpr<unknown>] => [\n key,\n Expr.input(`principal.${key}`, schema as unknown as Schema.Codec<unknown, unknown>),\n ]),\n ),\n ) as Placeholders<User>\n\nexport { Condition, type MemberRead, type RowRule } from './condition.js'\nexport { May, MaySchema, type MayAnswer } from './may.js'\nexport { ME, type MeEntity } from './me.js'\nexport {\n Interaction,\n type All,\n type AnyRule,\n type Attach,\n type Attachment,\n type Deny,\n type Explain,\n type Inherit,\n type InteractionKey,\n type On,\n type Redact,\n type RuleFor,\n type Surface,\n} from './attach.js'\n\nexport const Guards = {\n ...Attaching,\n /**\n * Adds the `may` member, the server's answer to what a principal may do\n * with a row, after its guards are attached:\n * `TodoFields.pipe(Guards.attach(G, { … }), Guards.may)`.\n */\n may: May.member,\n /**\n * `Me`, the visitor as an Entity: one row, `me`, that everyone reads and no\n * one writes, with `signedIn`, the principal's `key`, and `may` for the\n * interactions named here. Serve it with `GuardServer.me`.\n *\n * ```ts\n * export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })\n * ```\n */\n me,\n /**\n * One application's guards, under `name` (its principal's Context key, and\n * what the matrix prints). `principal` is a `Schema.Struct`: its fields are\n * what a row guard reads, and its codec encodes a principal's values as\n * stored values are encoded.\n *\n * ```ts\n * const G = Guards.declare('Todos', User, guard => ({\n * isAdmin: guard.principal(),\n * isOwner: guard.row(TodoFields, p => Expr.eq(TodoFields.fields.ownerId, p.id)),\n * }), { key: user => user.id })\n * ```\n */\n declare: <\n const Name extends string,\n Fields extends Schema.Struct.Fields,\n const S extends Readonly<Record<string, AnySpec>> & { readonly [K in Reserved]?: never },\n >(\n name: Name,\n principal: Schema.Struct<Fields>,\n build: (guard: Builders<Schema.Struct.Type<Fields>>) => S,\n options: {\n readonly key: (user: Schema.Struct.Type<Fields>) => string\n /**\n * What a surface of a guarded Entity with no rules decides: `'deny'`\n * refuses it, `'allow'` lets everyone. Required, so an open surface is\n * a decision written down; `Guards.matrix` prints it `closed` or `open`.\n */\n readonly unguarded: 'allow' | 'deny'\n /**\n * The Entity whose row each principal is, by `key`: what a row guard's\n * `Expr.viewer` of it reads, on the server and the client alike. A set\n * without one refuses a rule that reads the viewer.\n */\n readonly viewer?: AnyEntity | undefined\n },\n ): GuardSet<Name, Schema.Struct.Type<Fields>, S> => {\n type User = Schema.Struct.Type<Fields>\n // The type requires it; a caller without types (or one that spelled it\n // `'Allow'`) would otherwise get a set that denies, silently.\n if (options.unguarded !== 'allow' && options.unguarded !== 'deny')\n throw new Error(\n `[foldkit-guard] ${name}: unguarded must be 'allow' or 'deny', not ${JSON.stringify(options.unguarded)}`,\n )\n const placeholders = placeholdersOf<User>(principal.fields)\n const specs = build({\n principal: () => Object.freeze({ _tag: 'PrincipalSpec' }),\n row: (entity, body) => {\n const predicate = body(placeholders)\n const { operations } = Query.dependencies(Query.from(entity).pipe(Query.where(predicate)))\n // Who may is decided when asked, not at a write's time, which the rule is never given.\n if (operations.includes('now')) {\n throw new Error(\n `[foldkit-guard] ${name}: a rule over ${entity.name} reads Expr.now; who may do something does not move with the clock here`,\n )\n }\n if (operations.includes('viewer') && options.viewer === undefined) {\n throw new Error(\n `[foldkit-guard] ${name}: a rule over ${entity.name} reads Expr.viewer, but the set names no viewer Entity; declare it with { viewer }`,\n )\n }\n return Object.freeze({ _tag: 'RowSpec', entity, body: predicate })\n },\n })\n const guards: Record<string, AnyGuard<User>> = Object.create(null)\n for (const [guard, spec] of Object.entries(specs)) {\n if ((reserved as ReadonlyArray<string>).includes(guard)) {\n throw new Error(\n `[foldkit-guard] ${name}: \"${guard}\" is a name the guard set keeps for itself`,\n )\n }\n guards[guard] = Match.valueTags(spec, {\n PrincipalSpec: (): AnyGuard<User> =>\n Object.freeze({ _tag: 'PrincipalGuard', name: guard, set: name }),\n RowSpec: ({ entity, body }): AnyGuard<User> =>\n Object.freeze({\n _tag: 'RowGuard',\n name: guard,\n set: name,\n entity,\n body,\n // Checks the body reads only this Entity's fields, where it is declared.\n query: Query.from(entity).pipe(Query.where(body)),\n }),\n })\n }\n const principalNames = Object.keys(guards).filter(\n guard => guards[guard]!._tag === 'PrincipalGuard',\n )\n const encoders = Object.fromEntries(\n Object.entries(principal.fields).map(([field, schema]) => [\n field,\n Schema.encodeSync(schema as unknown as Schema.Codec<unknown, unknown>),\n ]),\n )\n const inputOf = (user: User): Readonly<Record<string, unknown>> => {\n const input: Record<string, unknown> = {}\n for (const [field, encode] of Object.entries(encoders)) {\n input[`principal.${field}`] = encode((user as Record<string, unknown>)[field])\n }\n return input\n }\n\n const viewerOf = (user: Option.Option<User>): Option.Option<EntityRef> =>\n Option.flatMap(Option.fromUndefinedOr(options.viewer), entity =>\n Option.map(user, each => ({ entity: entity.name, id: options.key(each) })),\n )\n // A rule reads who asks, never a time.\n const contextOf = (user: Option.Option<User>): ExprContext => ({\n viewer: viewerOf(user),\n now: Option.none(),\n })\n\n const isPrincipal = Schema.is(Schema.Option(principal))\n // Every claim as JSON keeps it, a set, a number past JSON's or a date\n // included: two principals that differ in one never share a key.\n const asJson = Schema.encodeSync(\n Schema.toCodecJson(principal) as unknown as Schema.Codec<unknown, unknown>,\n )\n\n const implement = <R>(\n bodies: Readonly<Record<string, Body<User, R>>>,\n implementation: { readonly operators?: MemoryOperators | undefined } = {},\n ): Policy<User, R> => {\n const operators = implementation.operators ?? Operators.kernel\n const missing = principalNames.filter(guard => !Object.hasOwn(bodies, guard))\n const extra = Object.keys(bodies).filter(guard => !principalNames.includes(guard))\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `[foldkit-guard] ${name}.implement: ${[\n missing.length > 0 ? `no body for ${missing.join(', ')}` : '',\n extra.length > 0 ? `${extra.join(', ')} is not a principal guard` : '',\n ]\n .filter(part => part !== '')\n .join('; ')}`,\n )\n }\n const decide: Policy<User, R>['decide'] = (guard, { principal, interaction, row }) => {\n if (guard.set !== name) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: \"${guard.name}\" belongs to ${guard.set}`),\n )\n }\n return Match.valueTags(guard, {\n PrincipalGuard: ({ name: body }) => {\n const decided = bodies[body]!(principal, { interaction })\n return Effect.isEffect(decided) ? decided : Effect.succeed(decided)\n },\n RowGuard: rowGuard =>\n Effect.succeed(\n row !== undefined &&\n Option.match(principal, {\n // A visitor has no fields: only a guard over the row alone can hold.\n onNone: () =>\n !readsPrincipal(rowGuard) &&\n evaluate(rowGuard.query, {}, [row], {\n operators,\n context: contextOf(principal),\n }).length === 1,\n onSome: user =>\n evaluate(rowGuard.query, inputOf(user), [row], {\n operators,\n context: contextOf(principal),\n }).length === 1,\n }),\n ),\n })\n }\n const decidingFor = (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: string,\n ) => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== name) {\n throw new Error(`[foldkit-guard] ${name}: ${entity.name} carries the guards of ${set}`)\n }\n })\n return deciding(\n guard =>\n Effect.map(decide(guard, { principal, interaction }), decision => decision === true),\n Option.isNone(principal),\n interaction,\n contextOf(principal),\n )\n }\n const policy: Policy<User, R> = {\n set: name,\n operators,\n decide,\n readable: (entity, principal) =>\n Effect.map(\n decidingFor(entity, principal, 'Read').row(entity),\n ({ condition }) => condition,\n ),\n readMembers: (entity, principal, members) =>\n decidingFor(entity, principal, 'Read').members(entity, members),\n writable: (entity, principal, interaction) =>\n decidingFor(entity, principal, interaction).row(entity),\n writeMembers: (entity, principal, members, interaction) =>\n decidingFor(entity, principal, interaction).members(entity, members),\n linkable: (entity, principal, relation, interaction) =>\n decidingFor(entity, principal, interaction).relation(entity, relation),\n inputOf: principal =>\n Option.match(principal, { onNone: () => ({}), onSome: user => inputOf(user) }),\n viewer: viewerOf,\n key: options.key,\n // Prefixed, so no user's key is the visitor's. Not `declare`'s `key`\n // alone: a re-read shared under it would read a newer request as an\n // older one's claims.\n keyOf: principal =>\n Option.match(principal, {\n onNone: () => 'visitor',\n onSome: user => `user:${JSON.stringify(asJson(user))}`,\n }),\n isPrincipal,\n provide: context => provided(policy, context),\n }\n return policy\n }\n\n return Object.freeze({\n ...guards,\n name,\n schema: principal as unknown as Schema.Codec<User, unknown>,\n Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>(\n `foldkit-guard/Principal/${name}`,\n ),\n key: options.key,\n unguarded: options.unguarded,\n inputOf,\n implement,\n }) as unknown as GuardSet<Name, User, S>\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiHA,MAAM,WAAW;CACf;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAgJA,MAAM,YACJ,QACA,YACuC;CACvC,MAAM,OAAU,WAAuC,OAAO,QAAQ,QAAQ,OAAO;CACrF,MAAM,OAA2C;EAC/C,GAAG;EACH,SAAS,OAAO,YAAY,IAAI,OAAO,OAAO,OAAO,OAAO,CAAC;EAC7D,WAAW,QAAQ,cAAc,IAAI,OAAO,SAAS,QAAQ,SAAS,CAAC;EACvE,cAAc,QAAQ,WAAW,YAC/B,IAAI,OAAO,YAAY,QAAQ,WAAW,OAAO,CAAC;EACpD,WAAW,QAAQ,WAAW,gBAC5B,IAAI,OAAO,SAAS,QAAQ,WAAW,WAAW,CAAC;EACrD,eAAe,QAAQ,WAAW,SAAS,gBACz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R,WAAW,QAAQ,QACjB,2BAA2B,MAC7B;GACA,KAAK,QAAQ;GACb,WAAW,QAAQ;GACnB;GACA;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Who may do what, declared once on the domain.\n *\n * A guard set names its guards once, in shared code the client imports too.\n * A **principal guard** is declared by name and implemented only on the\n * server (`G.implement`), so its logic never ships. A **row guard** is an\n * `Expr` over one Entity's fields with the principal's fields as inputs: data,\n * which the SQL compiler and `evaluate` both run. See `guard-DESIGN.md`.\n */\nimport { Context, Effect, Match, Option, Schema } from 'effect'\nimport { Attaching, attached, type InteractionKey } from './attach.js'\nimport {\n deciding,\n readsPrincipal,\n type Condition,\n type MemberRead,\n type RowRule,\n} from './condition.js'\nimport { May } from './may.js'\nimport { me } from './me.js'\nimport { providedFrom } from './origin.js'\nimport {\n Expr,\n Operators,\n Query,\n evaluate,\n type AnyEntity,\n type EntityRef,\n type ExprContext,\n type MemoryOperators,\n type AnyQuery,\n type InputExpr,\n type Invalid,\n type Predicate,\n type ReadsOf,\n} from 'foldkit-entity'\n\n/** A guard's answer: allowed, refused, or refused with a sentence the caller may read. */\nexport type Decision = boolean | { readonly allowed: false; readonly reason: string }\n\n/** What a principal guard is asked about. */\nexport interface About {\n /** The interaction attempted: `Read`, `Update`, or one the application names. */\n readonly interaction: string\n}\n\n/**\n * The principal's fields as a row guard's body sees them: each an input named\n * `principal.<field>`, typed as the field. A body is built once, so it holds\n * these placeholders and never a value: branching on one is a type error.\n */\nexport type Placeholders<User> = {\n readonly [K in keyof User & string]: InputExpr<User[K]>\n}\n\n/** What `guard.principal()` declares: a name whose body the server supplies. */\nexport interface PrincipalSpec {\n readonly _tag: 'PrincipalSpec'\n}\n\n/** What `guard.row(entity, body)` declares: a predicate over one Entity's rows. */\nexport interface RowSpec<E extends AnyEntity> {\n readonly _tag: 'RowSpec'\n readonly entity: E\n readonly body: Predicate\n}\n\ntype AnySpec = PrincipalSpec | RowSpec<AnyEntity>\n\n/**\n * The principal a guard is for, kept in the type so a guard of one principal\n * cannot stand where another's is wanted. A function type, so it is invariant.\n */\ninterface ForPrincipal<User> {\n readonly '~principal'?: (user: User) => User\n}\n\n/** A guard whose body lives on the server, asked of the principal alone. */\nexport interface PrincipalGuard<User, Set extends string = string> extends ForPrincipal<User> {\n readonly _tag: 'PrincipalGuard'\n readonly name: string\n /** The name of the guard set it belongs to. */\n readonly set: Set\n}\n\n/** A guard over the rows of `E`: its predicate, and the query that asks it of rows. */\nexport interface RowGuard<\n User,\n E extends AnyEntity,\n Set extends string = string,\n> extends ForPrincipal<User> {\n readonly _tag: 'RowGuard'\n readonly name: string\n readonly set: Set\n readonly entity: E\n readonly body: Predicate\n /** `from(entity).where(body)`, for an interpreter that runs queries. */\n readonly query: AnyQuery\n}\n\nexport type AnyGuard<User> = PrincipalGuard<User> | RowGuard<User, AnyEntity>\n\ntype GuardOf<User, Set extends string, S> =\n S extends RowSpec<infer E> ? RowGuard<User, E, Set> : PrincipalGuard<User, Set>\n\n/** The keys of a spec record that are principal guards: what `implement` must supply. */\ntype PrincipalKeys<S> = { [K in keyof S]: S[K] extends PrincipalSpec ? K : never }[keyof S]\n\n/** A principal guard's body, on the server. */\nexport type Body<User, R = never> = (\n principal: Option.Option<User>,\n about: About,\n) => Decision | Effect.Effect<Decision, never, R>\n\n/** Names a guard set reserves for itself, which no guard may take. */\nconst reserved = [\n 'name',\n 'schema',\n 'Principal',\n 'key',\n 'unguarded',\n 'inputOf',\n 'implement',\n] as const\ntype Reserved = (typeof reserved)[number]\n\n/** Who is asking, for one guard set: a visitor is `none`. */\nexport interface PrincipalOf<Name extends string> {\n readonly '~guardSet': Name\n}\n\n/** The guard set of one application, as `Guards.declare` returns it. */\nexport type GuardSet<Name extends string, User, S> = {\n readonly [K in keyof S]: GuardOf<User, Name, S[K]>\n} & {\n readonly name: Name\n /** The principal's schema, whose fields the row guards read. */\n readonly schema: Schema.Codec<User, unknown>\n /** The server's Context key for who is asking. Authentication provides it. */\n readonly Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>\n /** A stable name for the person, whatever their claims: for what is theirs, as a cache's scope. */\n readonly key: (user: User) => string\n readonly unguarded: 'allow' | 'deny'\n /** The principal's fields as row guards' inputs, encoded as stored values are. */\n readonly inputOf: (user: User) => Readonly<Record<string, unknown>>\n /**\n * The bodies of the principal guards: every one, and nothing else. `operators`\n * runs the row guards' primitive operators in memory; `Operators.kernel` when\n * not given.\n */\n readonly implement: <R = never>(\n bodies: { readonly [K in PrincipalKeys<S>]: Body<User, R> },\n options?: { readonly operators?: MemoryOperators | undefined },\n ) => Policy<User, R>\n}\n\n/** The server's half of a guard set: every principal guard's body. */\nexport interface Policy<User, R = never> {\n readonly set: string\n /**\n * How a row guard's primitive operators are run in memory: by `decide`,\n * `Condition.holds` and every guarded server judging a row. Given to\n * `implement`; `Operators.kernel` when not.\n */\n readonly operators: MemoryOperators\n /**\n * Whether `guard` allows `principal`, for a row guard over `row` (its stored,\n * encoded values). A visitor passes no row guard that reads a principal's\n * fields; one over the row alone holds for a visitor too.\n */\n readonly decide: (\n guard: AnyGuard<User>,\n request: {\n readonly principal: Option.Option<User>\n readonly interaction: string\n readonly row?: Readonly<Record<string, unknown>> | undefined\n },\n ) => Effect.Effect<Decision, never, R>\n /**\n * Which rows of `entity` `principal` may read, as a condition over the row\n * with every principal guard already decided. An Entity without guards, or\n * of no set, reads `Always`.\n */\n readonly readable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n ) => Effect.Effect<Condition, never, R>\n /** The read rule of each of `members`, relations included, that has one, decided for `principal`. */\n readonly readMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /**\n * Which rows of `entity` `principal` may write by `interaction` (`Create`,\n * `Update`, `Delete`, or one the application named), as a condition over\n * the row, and what a refusal shows.\n */\n readonly writable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: 'Create' | 'Update' | 'Delete' | InteractionKey,\n ) => Effect.Effect<RowRule, never, R>\n /** The rule of each of `members` that has one for setting it, decided for `principal`. */\n readonly writeMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n interaction: 'Create' | 'Update',\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /** A relation's rule for linking or unlinking a row, when it has one. */\n readonly linkable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n relation: string,\n interaction: 'Link' | 'Unlink',\n ) => Effect.Effect<Option.Option<RowRule>, never, R>\n /** The principal's fields as row guards' inputs; a visitor has none. */\n readonly inputOf: (principal: Option.Option<User>) => Readonly<Record<string, unknown>>\n /**\n * Who the principal is as a row: `declare`'s `viewer` Entity, by `key`.\n * What a rule's `Expr.viewer` reads, and the server's viewer:\n * `RemoteServer.make({ viewer: Policy.viewer })`. None for a visitor, and\n * for a set that names no `viewer`.\n */\n readonly viewer: (principal: Option.Option<User>) => Option.Option<EntityRef>\n /**\n * Who the principal is: `declare`'s `key`, the same function as `G.key`,\n * here for a server seam that holds the Policy and not the set. Not\n * `keyOf`, which names a principal by every field, for sharing re-reads.\n */\n readonly key: (user: User) => string\n /**\n * Who is asking, as the rules see it: every field of the principal, encoded,\n * a visitor included. Two requests by one person with the same claims answer\n * alike, so a live hub shares their re-reads; a changed claim is not shared.\n *\n * ```ts\n * RemoteServer.liveHub(sources, { key: Policy.keyOf })\n * ```\n */\n readonly keyOf: (principal: Option.Option<User>) => string\n /**\n * Whether `value` is this set's principal, an `Option` of its schema: for a\n * seam that is handed the principal untyped.\n */\n readonly isPrincipal: (value: unknown) => value is Option.Option<User>\n /**\n * This Policy with services its bodies need provided, such as a membership\n * lookup. The read seams (`GuardDrizzle.visible`, `GuardServer.memory`,\n * `GuardSync`) take a Policy that needs nothing more: a read rule runs inside\n * a read whose requirements are its Source's. Provide what stays put here,\n * once; carry what changes per request in the principal. A seam built from\n * the result counts as built from this Policy: `validate` checks the rules,\n * not the services given them. `GuardSync.authorize` runs bodies\n * synchronously, so what it is given must answer without suspending.\n *\n * ```ts\n * const ReadPolicy = Policy.provide(Context.make(Memberships, memberships))\n * ```\n */\n readonly provide: <Provided extends R>(\n context: Context.Context<Provided>,\n ) => Policy<User, Exclude<R, Provided>>\n}\n\n/** `policy` with `context` provided to every body it runs. */\nconst provided = <User, R, Provided extends R>(\n policy: Policy<User, R>,\n context: Context.Context<Provided>,\n): Policy<User, Exclude<R, Provided>> => {\n const run = <A>(effect: Effect.Effect<A, never, R>) => Effect.provide(effect, context)\n const next: Policy<User, Exclude<R, Provided>> = {\n ...policy,\n decide: (guard, request) => run(policy.decide(guard, request)),\n readable: (entity, principal) => run(policy.readable(entity, principal)),\n readMembers: (entity, principal, members) =>\n run(policy.readMembers(entity, principal, members)),\n writable: (entity, principal, interaction) =>\n run(policy.writable(entity, principal, interaction)),\n writeMembers: (entity, principal, members, interaction) =>\n run(policy.writeMembers(entity, principal, members, interaction)),\n linkable: (entity, principal, relation, interaction) =>\n run(policy.linkable(entity, principal, relation, interaction)),\n provide: more => provided(next, more),\n }\n return providedFrom(next, policy)\n}\n\n/** The builders a guard set's declaration is given, typed by its principal. */\nexport interface Builders<User> {\n /** A guard decided from the principal alone, by a body only the server has. */\n readonly principal: () => PrincipalSpec\n /**\n * A guard over `entity`'s rows: a predicate with the principal's fields as\n * inputs. A predicate reading another Entity's fields is refused where it\n * is written; one typed plain `Predicate` is checked when the set is\n * declared.\n */\n readonly row: <E extends AnyEntity, P extends RuleOver<P, E['name']>>(\n entity: E,\n body: (principal: Placeholders<User>) => P,\n ) => RowSpec<E>\n}\n\n/**\n * What a rule over the Entity `Name` may be: a predicate reading `Name`'s\n * fields and relations, inputs and the viewer, or one whose reads are unknown\n * to the type (a plain `Predicate`).\n */\ntype RuleOver<P, Name extends string> =\n string extends ReadsOf<P>\n ? Predicate\n : [ReadsOf<P>] extends [Name]\n ? Predicate\n : Predicate & Invalid<`foldkit-guard: a rule over ${Name} reads ${Exclude<ReadsOf<P>, Name>}`>\n\nconst placeholdersOf = <User>(fields: Schema.Struct.Fields): Placeholders<User> =>\n // Built as entries, so a field named `__proto__` is a key of its own, not the prototype.\n Object.freeze(\n Object.fromEntries(\n Object.entries(fields).map(([key, schema]): [string, InputExpr<unknown>] => [\n key,\n Expr.input(`principal.${key}`, schema as unknown as Schema.Codec<unknown, unknown>),\n ]),\n ),\n ) as Placeholders<User>\n\nexport { Condition, type MemberRead, type RowRule } from './condition.js'\nexport { May, MaySchema, type MayAnswer } from './may.js'\nexport { ME, type MeEntity } from './me.js'\nexport {\n Interaction,\n type All,\n type AnyRule,\n type Attach,\n type Attachment,\n type Deny,\n type Explain,\n type Inherit,\n type InteractionKey,\n type On,\n type Redact,\n type RuleFor,\n type Surface,\n} from './attach.js'\n\nexport const Guards = {\n ...Attaching,\n /**\n * Adds the `may` member, the server's answer to what a principal may do\n * with a row, after its guards are attached:\n * `TodoFields.pipe(Guards.attach(G, { … }), Guards.may)`.\n */\n may: May.member,\n /**\n * `Me`, the visitor as an Entity: one row, `me`, that everyone reads and no\n * one writes, with `signedIn`, the principal's `key`, and `may` for the\n * interactions named here. Serve it with `GuardServer.me`.\n *\n * ```ts\n * export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })\n * ```\n */\n me,\n /**\n * One application's guards, under `name` (its principal's Context key, and\n * what the matrix prints). `principal` is a `Schema.Struct`: its fields are\n * what a row guard reads, and its codec encodes a principal's values as\n * stored values are encoded.\n *\n * ```ts\n * const G = Guards.declare('Todos', User, guard => ({\n * isAdmin: guard.principal(),\n * isOwner: guard.row(TodoFields, p => Expr.eq(TodoFields.fields.ownerId, p.id)),\n * }), { key: user => user.id })\n * ```\n */\n declare: <\n const Name extends string,\n Fields extends Schema.Struct.Fields,\n const S extends Readonly<Record<string, AnySpec>> & { readonly [K in Reserved]?: never },\n >(\n name: Name,\n principal: Schema.Struct<Fields>,\n build: (guard: Builders<Schema.Struct.Type<Fields>>) => S,\n options: {\n readonly key: (user: Schema.Struct.Type<Fields>) => string\n /**\n * What a surface of a guarded Entity with no rules decides: `'deny'`\n * refuses it, `'allow'` lets everyone. Required, so an open surface is\n * a decision written down; `Guards.matrix` prints it `closed` or `open`.\n */\n readonly unguarded: 'allow' | 'deny'\n /**\n * The Entity whose row each principal is, by `key`: what a row guard's\n * `Expr.viewer` of it reads, on the server and the client alike. A set\n * without one refuses a rule that reads the viewer.\n */\n readonly viewer?: AnyEntity | undefined\n },\n ): GuardSet<Name, Schema.Struct.Type<Fields>, S> => {\n type User = Schema.Struct.Type<Fields>\n // The type requires it; a caller without types (or one that spelled it\n // `'Allow'`) would otherwise get a set that denies, silently.\n if (options.unguarded !== 'allow' && options.unguarded !== 'deny')\n throw new Error(\n `[foldkit-guard] ${name}: unguarded must be 'allow' or 'deny', not ${JSON.stringify(options.unguarded)}`,\n )\n const placeholders = placeholdersOf<User>(principal.fields)\n const specs = build({\n principal: () => Object.freeze({ _tag: 'PrincipalSpec' }),\n row: (entity, body) => {\n const predicate: Predicate = body(placeholders)\n const { operations } = Query.dependencies(Query.from(entity).pipe(Query.where(predicate)))\n // Who may is decided when asked, not at a write's time, which the rule is never given.\n if (operations.includes('now')) {\n throw new Error(\n `[foldkit-guard] ${name}: a rule over ${entity.name} reads Expr.now; who may do something does not move with the clock here`,\n )\n }\n if (operations.includes('viewer') && options.viewer === undefined) {\n throw new Error(\n `[foldkit-guard] ${name}: a rule over ${entity.name} reads Expr.viewer, but the set names no viewer Entity; declare it with { viewer }`,\n )\n }\n return Object.freeze({ _tag: 'RowSpec', entity, body: predicate })\n },\n })\n const guards: Record<string, AnyGuard<User>> = Object.create(null)\n for (const [guard, spec] of Object.entries(specs)) {\n if ((reserved as ReadonlyArray<string>).includes(guard)) {\n throw new Error(\n `[foldkit-guard] ${name}: \"${guard}\" is a name the guard set keeps for itself`,\n )\n }\n guards[guard] = Match.valueTags(spec, {\n PrincipalSpec: (): AnyGuard<User> =>\n Object.freeze({ _tag: 'PrincipalGuard', name: guard, set: name }),\n RowSpec: ({ entity, body }): AnyGuard<User> =>\n Object.freeze({\n _tag: 'RowGuard',\n name: guard,\n set: name,\n entity,\n body,\n // Checks the body reads only this Entity's fields, where it is declared.\n query: Query.from(entity).pipe(Query.where(body)),\n }),\n })\n }\n const principalNames = Object.keys(guards).filter(\n guard => guards[guard]!._tag === 'PrincipalGuard',\n )\n const encoders = Object.fromEntries(\n Object.entries(principal.fields).map(([field, schema]) => [\n field,\n Schema.encodeSync(schema as unknown as Schema.Codec<unknown, unknown>),\n ]),\n )\n const inputOf = (user: User): Readonly<Record<string, unknown>> => {\n const input: Record<string, unknown> = {}\n for (const [field, encode] of Object.entries(encoders)) {\n input[`principal.${field}`] = encode((user as Record<string, unknown>)[field])\n }\n return input\n }\n\n const viewerOf = (user: Option.Option<User>): Option.Option<EntityRef> =>\n Option.flatMap(Option.fromUndefinedOr(options.viewer), entity =>\n Option.map(user, each => ({ entity: entity.name, id: options.key(each) })),\n )\n // A rule reads who asks, never a time.\n const contextOf = (user: Option.Option<User>): ExprContext => ({\n viewer: viewerOf(user),\n now: Option.none(),\n })\n\n const isPrincipal = Schema.is(Schema.Option(principal))\n // Every claim as JSON keeps it, a set, a number past JSON's or a date\n // included: two principals that differ in one never share a key.\n const asJson = Schema.encodeSync(\n Schema.toCodecJson(principal) as unknown as Schema.Codec<unknown, unknown>,\n )\n\n const implement = <R>(\n bodies: Readonly<Record<string, Body<User, R>>>,\n implementation: { readonly operators?: MemoryOperators | undefined } = {},\n ): Policy<User, R> => {\n const operators = implementation.operators ?? Operators.kernel\n const missing = principalNames.filter(guard => !Object.hasOwn(bodies, guard))\n const extra = Object.keys(bodies).filter(guard => !principalNames.includes(guard))\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `[foldkit-guard] ${name}.implement: ${[\n missing.length > 0 ? `no body for ${missing.join(', ')}` : '',\n extra.length > 0 ? `${extra.join(', ')} is not a principal guard` : '',\n ]\n .filter(part => part !== '')\n .join('; ')}`,\n )\n }\n const decide: Policy<User, R>['decide'] = (guard, { principal, interaction, row }) => {\n if (guard.set !== name) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: \"${guard.name}\" belongs to ${guard.set}`),\n )\n }\n return Match.valueTags(guard, {\n PrincipalGuard: ({ name: body }) => {\n const decided = bodies[body]!(principal, { interaction })\n return Effect.isEffect(decided) ? decided : Effect.succeed(decided)\n },\n RowGuard: rowGuard =>\n Effect.succeed(\n row !== undefined &&\n Option.match(principal, {\n // A visitor has no fields: only a guard over the row alone can hold.\n onNone: () =>\n !readsPrincipal(rowGuard) &&\n evaluate(rowGuard.query, {}, [row], {\n operators,\n context: contextOf(principal),\n }).length === 1,\n onSome: user =>\n evaluate(rowGuard.query, inputOf(user), [row], {\n operators,\n context: contextOf(principal),\n }).length === 1,\n }),\n ),\n })\n }\n const decidingFor = (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: string,\n ) => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== name) {\n throw new Error(`[foldkit-guard] ${name}: ${entity.name} carries the guards of ${set}`)\n }\n })\n return deciding(\n guard =>\n Effect.map(decide(guard, { principal, interaction }), decision => decision === true),\n Option.isNone(principal),\n interaction,\n contextOf(principal),\n )\n }\n const policy: Policy<User, R> = {\n set: name,\n operators,\n decide,\n readable: (entity, principal) =>\n Effect.map(\n decidingFor(entity, principal, 'Read').row(entity),\n ({ condition }) => condition,\n ),\n readMembers: (entity, principal, members) =>\n decidingFor(entity, principal, 'Read').members(entity, members),\n writable: (entity, principal, interaction) =>\n decidingFor(entity, principal, interaction).row(entity),\n writeMembers: (entity, principal, members, interaction) =>\n decidingFor(entity, principal, interaction).members(entity, members),\n linkable: (entity, principal, relation, interaction) =>\n decidingFor(entity, principal, interaction).relation(entity, relation),\n inputOf: principal =>\n Option.match(principal, { onNone: () => ({}), onSome: user => inputOf(user) }),\n viewer: viewerOf,\n key: options.key,\n // Prefixed, so no user's key is the visitor's. Not `declare`'s `key`\n // alone: a re-read shared under it would read a newer request as an\n // older one's claims.\n keyOf: principal =>\n Option.match(principal, {\n onNone: () => 'visitor',\n onSome: user => `user:${JSON.stringify(asJson(user))}`,\n }),\n isPrincipal,\n provide: context => provided(policy, context),\n }\n return policy\n }\n\n return Object.freeze({\n ...guards,\n name,\n schema: principal as unknown as Schema.Codec<User, unknown>,\n Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>(\n `foldkit-guard/Principal/${name}`,\n ),\n key: options.key,\n unguarded: options.unguarded,\n inputOf,\n implement,\n }) as unknown as GuardSet<Name, User, S>\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmHA,MAAM,WAAW;CACf;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAgJA,MAAM,YACJ,QACA,YACuC;CACvC,MAAM,OAAU,WAAuC,OAAO,QAAQ,QAAQ,OAAO;CACrF,MAAM,OAA2C;EAC/C,GAAG;EACH,SAAS,OAAO,YAAY,IAAI,OAAO,OAAO,OAAO,OAAO,CAAC;EAC7D,WAAW,QAAQ,cAAc,IAAI,OAAO,SAAS,QAAQ,SAAS,CAAC;EACvE,cAAc,QAAQ,WAAW,YAC/B,IAAI,OAAO,YAAY,QAAQ,WAAW,OAAO,CAAC;EACpD,WAAW,QAAQ,WAAW,gBAC5B,IAAI,OAAO,SAAS,QAAQ,WAAW,WAAW,CAAC;EACrD,eAAe,QAAQ,WAAW,SAAS,gBACzC,IAAI,OAAO,aAAa,QAAQ,WAAW,SAAS,WAAW,CAAC;EAClE,WAAW,QAAQ,WAAW,UAAU,gBACtC,IAAI,OAAO,SAAS,QAAQ,WAAW,UAAU,WAAW,CAAC;EAC/D,UAAS,SAAQ,SAAS,MAAM,IAAI;CACtC;CACA,OAAO,aAAa,MAAM,MAAM;AAClC;AA8BA,MAAM,kBAAwB,WAE5B,OAAO,OACL,OAAO,YACL,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,CAAC,KAAK,YA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ACvB,aACA,UAAU,SAAS,CACrB;GACF;GACA,MAAM,SAA0B;IAC9B,KAAK;IACL;IACA;IACA,WAAW,QAAQ,cACjB,OAAO,IACL,YAAY,QAAQ,WAAW,MAAM,CAAC,CAAC,IAAI,MAAM,IAChD,EAAE,gBAAgB,SACrB;IACF,cAAc,QAAQ,WAAW,YAC/B,YAAY,QAAQ,WAAW,MAAM,CAAC,CAAC,QAAQ,QAAQ,OAAO;IAChE,WAAW,QAAQ,WAAW,gBAC5B,YAAY,QAAQ,WAAW,WAAW,CAAC,CAAC,IAAI,MAAM;IACxD,eAAe,QAAQ,WAAW,SAAS,gBACzC,YAAY,QAAQ,WAAW,WAAW,CAAC,CAAC,QAAQ,QAAQ,OAAO;IACrE,WAAW,QAAQ,WAAW,UAAU,gBACtC,YAAY,QAAQ,WAAW,WAAW,CAAC,CAAC,SAAS,QAAQ,QAAQ;IACvE,UAAS,cACP,OAAO,MAAM,WAAW;KAAE,eAAe,CAAC;KAAI,SAAQ,SAAQ,QAAQ,IAAI;IAAE,CAAC;IAC/E,QAAQ;IACR,KAAK,QAAQ;IAIb,QAAO,cACL,OAAO,MAAM,WAAW;KACtB,cAAc;KACd,SAAQ,SAAQ,QAAQ,KAAK,UAAU,OAAO,IAAI,CAAC;IACrD,CAAC;IACH;IACA,UAAS,YAAW,SAAS,QAAQ,OAAO;GAC9C;GACA,OAAO;EACT;EAEA,OAAO,OAAO,OAAO;GACnB,GAAG;GACH;GACA,QAAQ;GACR,WAAW,QAAQ,QACjB,2BAA2B,MAC7B;GACA,KAAK,QAAQ;GACb,WAAW,QAAQ;GACnB;GACA;EACF,CAAC;CACH;AACF"}
|
package/dist/media.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as PrincipalGuard, S as Policy } from "./attach-
|
|
1
|
+
import { C as PrincipalGuard, S as Policy } from "./attach-CJl-GtbN.mjs";
|
|
2
2
|
import { Effect, Layer, Option } from "effect";
|
|
3
3
|
import { UploadPolicy } from "foldkit-media/server";
|
|
4
4
|
export interface UploadPolicyConfig<User, E, R> {
|
package/dist/server.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as Policy, k as MeEntity, l as InteractionKey } from "./attach-
|
|
1
|
+
import { S as Policy, k as MeEntity, l as InteractionKey } from "./attach-CJl-GtbN.mjs";
|
|
2
2
|
import { Effect, Option } from "effect";
|
|
3
3
|
import { AnyEntity, AnyQuery } from "foldkit-entity";
|
|
4
4
|
import { Diagnostic, MutationDescriptor, RemoteForbidden, ReportDiagnostic } from "foldkit-remote";
|
|
@@ -75,7 +75,8 @@ export declare const GuardServer: {
|
|
|
75
75
|
* to a member is that member's own change. An `Unlink` rule holds over the
|
|
76
76
|
* row before alone. A create's rules hold over the values it proposes, where a field the
|
|
77
77
|
* create leaves unset matches no guard, not even one for an empty value. A refusal is
|
|
78
|
-
* `Forbidden`, with the sentence an `explain` gave
|
|
78
|
+
* `Forbidden`, with the sentence an `explain` gave, or `Unauthenticated` for a
|
|
79
|
+
* visitor; the write never runs.
|
|
79
80
|
*
|
|
80
81
|
* What the Entity sets from the write's context (`Entity.sets`: who asks,
|
|
81
82
|
* when) reaches a create or an update already set by `RemoteServer.write`,
|
|
@@ -93,12 +94,27 @@ export declare const GuardServer: {
|
|
|
93
94
|
* revision the row read is not at is a `Conflict`, decided before any rule;
|
|
94
95
|
* an input may expect only the field the writer pins.
|
|
95
96
|
*
|
|
97
|
+
* A delete that cascades (`Relation.one(…, { onDelete: 'cascade' })`) holds
|
|
98
|
+
* each row it takes to that row's own `Delete` rule, for the same person, in
|
|
99
|
+
* the statement that deletes (#348): one refused, and the whole delete is
|
|
100
|
+
* `Forbidden`, naming the Entity, and nothing is removed. A relation declared
|
|
101
|
+
* `authorizedBy: 'parent'` lets whoever may delete the row take the rows
|
|
102
|
+
* pointing at it through that relation unjudged. The rules of an Entity
|
|
103
|
+
* taken under its own are read from its guarded descriptor, given as
|
|
104
|
+
* `children`; one missing is refused where the writer is made.
|
|
105
|
+
*
|
|
96
106
|
* ```ts
|
|
97
107
|
* RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
|
|
108
|
+
* GuardServer.writer(Post, Policy, writer(Db.Post), { children: [Like] })
|
|
98
109
|
* ```
|
|
99
110
|
*/
|
|
100
111
|
writer: <E extends AnyEntity, User, R, RW>(entity: E, policy: Policy<User, R>, writer: EntityWriter<Option.Option<User>, RW>, options?: {
|
|
101
112
|
readonly revision?: keyof E['fields'] & string;
|
|
113
|
+
/**
|
|
114
|
+
* The guarded descriptor of each Entity a delete takes rows of under
|
|
115
|
+
* their own `Delete` rule (`authorizedBy: 'child'`), whose rules judge them.
|
|
116
|
+
*/
|
|
117
|
+
readonly children?: ReadonlyArray<AnyEntity>;
|
|
102
118
|
}) => EntityWriter<Option.Option<User>, R | RW>;
|
|
103
119
|
/**
|
|
104
120
|
* A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for
|
|
@@ -107,8 +123,8 @@ export declare const GuardServer: {
|
|
|
107
123
|
* rule must hold over it; a row its writer may not see is refused. With no
|
|
108
124
|
* `id` (a create), the rule must hold of who is asking alone, a field it
|
|
109
125
|
* reads matching no guard. `run` is given the row as read: its fields the
|
|
110
|
-
* rule reads, its `id`, and `fields`. A refusal is `Forbidden
|
|
111
|
-
* runs. What `run` writes is its own: check members it sets there. Each
|
|
126
|
+
* rule reads, its `id`, and `fields`. A refusal is `Forbidden`, or
|
|
127
|
+
* `Unauthenticated` for a visitor; `run` never runs. What `run` writes is its own: check members it sets there. Each
|
|
112
128
|
* row of `entity` its answer carries is read back through `source`, so the
|
|
113
129
|
* answer shows its writer only what they may see, a row it hid from them
|
|
114
130
|
* as deleted.
|
package/dist/server.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.mts","names":[],"sources":["../src/diagnostics.ts","../src/server.ts"],"mappings":";;;;;;;;;;UAciB,uBAAuB;WAC7B;WACA;;WAEA,OAA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