foldkit-guard 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +209 -44
  2. package/dist/agent.d.mts +1 -1
  3. package/dist/agent.mjs +1 -1
  4. package/dist/{attach-CRCF5XHS.mjs → attach-CEGlbWu5.mjs} +17 -2
  5. package/dist/attach-CEGlbWu5.mjs.map +1 -0
  6. package/dist/{attach-BepaL930.d.mts → attach-DPgyv78F.d.mts} +83 -8
  7. package/dist/attach-DPgyv78F.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 +50 -17
  24. package/dist/server.d.mts.map +1 -1
  25. package/dist/server.mjs +264 -145
  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 +19 -18
  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
@@ -1,12 +1,15 @@
1
1
  import { Context, Effect, Option, Schema } from "effect";
2
- import { AnyEntity, AnyQuery, Entity, InputExpr, MemoryOperators, Predicate } from "foldkit-entity";
2
+ import { AnyEntity, AnyQuery, Entity, EntityRef, ExprContext, Forbids, HeldRow, HeldRows, InputExpr, MemoryOperators, Predicate, Predict } from "foldkit-entity";
3
3
  type Condition = {
4
4
  readonly _tag: 'Always';
5
5
  } | {
6
6
  readonly _tag: 'Never';
7
- } | {
7
+ } |
8
+ /** A row guard, and what its `Expr.viewer` reads: the principal it was decided for. */
9
+ {
8
10
  readonly _tag: 'Row';
9
11
  readonly guard: RowGuard<any, AnyEntity>;
12
+ readonly context: ExprContext;
10
13
  } |
11
14
  /** The row its `one` relation points at is readable. */
12
15
  {
@@ -43,6 +46,34 @@ declare const Condition: {
43
46
  * can deny it, never end the request.
44
47
  */
45
48
  holds: (condition: Condition, values: Readonly<Record<string, unknown>>, input: Readonly<Record<string, unknown>>, inherit: (relation: string) => boolean, operators: MemoryOperators) => boolean;
49
+ /**
50
+ * `condition` decided over one row as far as one row can: each row guard
51
+ * over the row alone judged (`holds`), an inherited Read refused, as a
52
+ * writer refuses one, and each row guard that reads another row (a path, an
53
+ * exists) kept for a statement to judge. `Always` or `Never` when the row
54
+ * alone decides it.
55
+ */
56
+ residual: (condition: Condition, values: Readonly<Record<string, unknown>>, input: Readonly<Record<string, unknown>>, operators: MemoryOperators) => Condition;
57
+ /** `Always` and `Never` as what one row decided; none where a statement must judge the rest. */
58
+ decided: (condition: Condition) => Option.Option<boolean>;
59
+ /**
60
+ * The members of `written`, the row a write changes, that a condition's
61
+ * guards reading another row start from: each one's fields, the relation
62
+ * each path leaves by, and, where `written` is the viewer's own row, what a
63
+ * path from the viewer leaves it by. A write that changes one would need the
64
+ * guard judged over the row it leaves, which a statement over the stored row
65
+ * does not do.
66
+ */
67
+ reachedFrom: (condition: Condition, written: EntityRef) => ReadonlyArray<string>;
68
+ /**
69
+ * Whether a row a client holds meets `condition`, a part it cannot decide
70
+ * taken to be `assumed`: a row guard over the principal's fields, which a
71
+ * client is not given, an inherited Read, and a rule over a row or field
72
+ * the holder lacks. A row guard reads the holder's rows (`rows`) where it
73
+ * follows a path from the viewer. Run once assuming each way, it is decided
74
+ * where both agree, since no part of a condition is negated.
75
+ */
76
+ judge: (condition: Condition, row: HeldRow, rows: HeldRows, assumed: boolean) => boolean;
46
77
  /**
47
78
  * `condition` with every row guard that reads one of `unset`, and every
48
79
  * relation of them it follows, refused: a field a create leaves unset
@@ -85,11 +116,23 @@ declare const May: {
85
116
  /**
86
117
  * Adds the `may` member to an Entity, after its guards are attached:
87
118
  * `TodoFields.pipe(Guards.attach(G, { … }), Guards.may)`. Select it as any
88
- * member (`may: true`); `GuardServer.filter` answers it.
119
+ * member (`may: true`); `GuardServer.filter` answers it. A client holding it
120
+ * refuses, where it is made, a write it says no to (`Forbidden`).
89
121
  */
90
122
  member: <E extends AnyEntity>(entity: E & ("may" & keyof E["members"] extends never ? unknown : {
91
123
  readonly alreadyAMember: "may" & keyof E["members"];
92
- })) => E extends Entity<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>>>> ? Entity<Name, Fields, R, D & {
124
+ })) => E extends Entity<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
+ readonly _tag: "Count";
126
+ readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
127
+ } | {
128
+ readonly _tag: "Exists";
129
+ readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
130
+ readonly viewer: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
131
+ } | {
132
+ readonly _tag: "Supplied";
133
+ readonly predict: Option.Option<Predict>;
134
+ readonly forbids: Option.Option<Forbids>;
135
+ }>>>> ? Entity<Name, Fields, R, D & {
93
136
  readonly may: import("foldkit-entity").DerivedSpec<Schema.Struct<{
94
137
  readonly row: Schema.$Record<Schema.String, Schema.Boolean>;
95
138
  readonly reasons: Schema.$Record<Schema.String, Schema.String>;
@@ -98,7 +141,11 @@ declare const May: {
98
141
  readonly Link: Schema.Boolean;
99
142
  readonly Unlink: Schema.Boolean;
100
143
  }>>;
101
- }>>;
144
+ }>, {
145
+ readonly _tag: "Supplied";
146
+ readonly predict: Option.Option<Predict>;
147
+ readonly forbids: Option.Option<Forbids>;
148
+ }>;
102
149
  }> : never;
103
150
  /**
104
151
  * Whether the row's rule for `interaction` let the principal, when it was
@@ -285,6 +332,13 @@ interface Policy<User, R = never> {
285
332
  readonly linkable: (entity: AnyEntity, principal: Option.Option<User>, relation: string, interaction: 'Link' | 'Unlink') => Effect.Effect<Option.Option<RowRule>, never, R>;
286
333
  /** The principal's fields as row guards' inputs; a visitor has none. */
287
334
  readonly inputOf: (principal: Option.Option<User>) => Readonly<Record<string, unknown>>;
335
+ /**
336
+ * Who the principal is as a row: `declare`'s `viewer` Entity, by `key`.
337
+ * What a rule's `Expr.viewer` reads, and the server's viewer:
338
+ * `RemoteServer.make({ viewer: Policy.viewer })`. None for a visitor, and
339
+ * for a set that names no `viewer`.
340
+ */
341
+ readonly viewer: (principal: Option.Option<User>) => Option.Option<EntityRef>;
288
342
  /**
289
343
  * Who the principal is: `declare`'s `key`, the same function as `G.key`,
290
344
  * here for a server seam that holds the Policy and not the set. Not
@@ -337,7 +391,18 @@ declare const Guards: {
337
391
  */
338
392
  may: <E extends AnyEntity>(entity: E & ("may" & keyof E["members"] extends never ? unknown : {
339
393
  readonly alreadyAMember: "may" & keyof E["members"];
340
- })) => E extends import("foldkit-entity").Entity<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>>>> ? import("foldkit-entity").Entity<Name, Fields, R, D & {
394
+ })) => E extends import("foldkit-entity").Entity<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, {
395
+ readonly _tag: "Count";
396
+ readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
397
+ } | {
398
+ readonly _tag: "Exists";
399
+ readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
400
+ readonly viewer: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
401
+ } | {
402
+ readonly _tag: "Supplied";
403
+ readonly predict: Option.Option<import("foldkit-entity").Predict>;
404
+ readonly forbids: Option.Option<import("foldkit-entity").Forbids>;
405
+ }>>>> ? import("foldkit-entity").Entity<Name, Fields, R, D & {
341
406
  readonly may: import("foldkit-entity").DerivedSpec<Schema.Struct<{
342
407
  readonly row: Schema.$Record<Schema.String, Schema.Boolean>;
343
408
  readonly reasons: Schema.$Record<Schema.String, Schema.String>;
@@ -346,7 +411,11 @@ declare const Guards: {
346
411
  readonly Link: Schema.Boolean;
347
412
  readonly Unlink: Schema.Boolean;
348
413
  }>>;
349
- }>>;
414
+ }>, {
415
+ readonly _tag: "Supplied";
416
+ readonly predict: Option.Option<import("foldkit-entity").Predict>;
417
+ readonly forbids: Option.Option<import("foldkit-entity").Forbids>;
418
+ }>;
350
419
  }> : never;
351
420
  /**
352
421
  * `Me`, the visitor as an Entity: one row, `me`, that everyone reads and no
@@ -379,6 +448,12 @@ declare const Guards: {
379
448
  * a decision written down; `Guards.matrix` prints it `closed` or `open`.
380
449
  */
381
450
  readonly unguarded: 'allow' | 'deny';
451
+ /**
452
+ * The Entity whose row each principal is, by `key`: what a row guard's
453
+ * `Expr.viewer` of it reads, on the server and the client alike. A set
454
+ * without one refuses a rule that reads the viewer.
455
+ */
456
+ readonly viewer?: AnyEntity | undefined;
382
457
  }) => GuardSet<Name, Schema.Struct.Type<Fields>, S>;
383
458
  attach: <Name extends string, User, E extends AnyEntity>(G: {
384
459
  readonly name: Name;
@@ -511,4 +586,4 @@ interface Attachment {
511
586
  }
512
587
  declare const attached: (entity: AnyEntity) => Option.Option<Attachment>;
513
588
  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 };
514
- //# sourceMappingURL=attach-BepaL930.d.mts.map
589
+ //# sourceMappingURL=attach-DPgyv78F.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attach-DPgyv78F.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,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,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"}
@@ -1,6 +1,6 @@
1
- import { a as defaultDeny, d as surfaceOf, r as attached } from "./attach-CRCF5XHS.mjs";
1
+ import { a as defaultDeny, d as surfaceOf, r as attached } from "./attach-CEGlbWu5.mjs";
2
2
  import { Effect, Match, Option } from "effect";
3
- import { Query, evaluateEach } from "foldkit-entity";
3
+ import { Held, Judge, Query, evaluateEach, viewerIdOf } from "foldkit-entity";
4
4
  // src/condition.ts
5
5
  /**
6
6
  * What an attachment's read rules come to for one principal, once its
@@ -8,6 +8,8 @@ import { Query, evaluateEach } from "foldkit-entity";
8
8
  * interpreter runs (`evaluate` in memory, SQL in a binding). Principal guards
9
9
  * never reach it, so their bodies stay on the server that decided them.
10
10
  */
11
+ /** Whether a row guard reads another row: one row cannot judge it. */
12
+ const reachesOther = (guard) => Query.dependencies(guard.query).reaches.length > 0;
11
13
  const always = Object.freeze({ _tag: "Always" });
12
14
  const never = Object.freeze({ _tag: "Never" });
13
15
  /** A conjunction, with what it settles already folded away. */
@@ -57,7 +59,10 @@ const Condition = {
57
59
  const holds = (each) => Match.valueTags(each, {
58
60
  Always: () => true,
59
61
  Never: () => false,
60
- Row: ({ guard }) => evaluateEach(guard.query, input, [values], { operators }).matched.length === 1,
62
+ Row: ({ guard, context }) => evaluateEach(guard.query, input, [Held.fromRefs(guard.query, values)], {
63
+ operators,
64
+ context
65
+ }).matched.length === 1,
61
66
  Inherit: ({ relation }) => inherit(relation),
62
67
  And: ({ conditions }) => conditions.every(holds),
63
68
  Or: ({ conditions }) => conditions.some(holds)
@@ -65,6 +70,88 @@ const Condition = {
65
70
  return holds(condition);
66
71
  },
67
72
  /**
73
+ * `condition` decided over one row as far as one row can: each row guard
74
+ * over the row alone judged (`holds`), an inherited Read refused, as a
75
+ * writer refuses one, and each row guard that reads another row (a path, an
76
+ * exists) kept for a statement to judge. `Always` or `Never` when the row
77
+ * alone decides it.
78
+ */
79
+ residual: (condition, values, input, operators) => {
80
+ const decided = (each) => Match.valueTags(each, {
81
+ Always: () => each,
82
+ Never: () => each,
83
+ Row: (row) => reachesOther(row.guard) ? each : Condition.holds(each, values, input, () => false, operators) ? always : never,
84
+ Inherit: () => never,
85
+ And: ({ conditions }) => and(conditions.map(decided)),
86
+ Or: ({ conditions }) => or(conditions.map(decided))
87
+ });
88
+ return decided(condition);
89
+ },
90
+ /** `Always` and `Never` as what one row decided; none where a statement must judge the rest. */
91
+ decided: (condition) => Match.valueTags(condition, {
92
+ Always: () => Option.some(true),
93
+ Never: () => Option.some(false),
94
+ Row: () => Option.none(),
95
+ Inherit: () => Option.none(),
96
+ And: () => Option.none(),
97
+ Or: () => Option.none()
98
+ }),
99
+ /**
100
+ * The members of `written`, the row a write changes, that a condition's
101
+ * guards reading another row start from: each one's fields, the relation
102
+ * each path leaves by, and, where `written` is the viewer's own row, what a
103
+ * path from the viewer leaves it by. A write that changes one would need the
104
+ * guard judged over the row it leaves, which a statement over the stored row
105
+ * does not do.
106
+ */
107
+ reachedFrom: (condition, written) => {
108
+ const read = (each) => Match.valueTags(each, {
109
+ Always: () => [],
110
+ Never: () => [],
111
+ Row: ({ guard, context }) => {
112
+ if (!reachesOther(guard)) return [];
113
+ const dependencies = Query.dependencies(guard.query);
114
+ return [...dependencies.predicate.map((field) => field.key), ...dependencies.reaches.flatMap((reach) => Match.valueTags(reach, {
115
+ Path: ({ via }) => [via[0].key],
116
+ Exists: ({ via }) => via.slice(0, 1).map((relation) => relation.key),
117
+ ViewerPath: ({ viewer, via, field }) => {
118
+ const start = viewer.target();
119
+ return start.name === written.entity && Option.exists(viewerIdOf(start, context), (id) => id === written.id) ? [via[0]?.key ?? field.key] : [];
120
+ }
121
+ }))];
122
+ },
123
+ Inherit: () => [],
124
+ And: ({ conditions }) => conditions.flatMap(read),
125
+ Or: ({ conditions }) => conditions.flatMap(read)
126
+ });
127
+ return [...new Set(read(condition))];
128
+ },
129
+ /**
130
+ * Whether a row a client holds meets `condition`, a part it cannot decide
131
+ * taken to be `assumed`: a row guard over the principal's fields, which a
132
+ * client is not given, an inherited Read, and a rule over a row or field
133
+ * the holder lacks. A row guard reads the holder's rows (`rows`) where it
134
+ * follows a path from the viewer. Run once assuming each way, it is decided
135
+ * where both agree, since no part of a condition is negated.
136
+ */
137
+ judge: (condition, row, rows, assumed) => {
138
+ const judge = (each) => Match.valueTags(each, {
139
+ Always: () => true,
140
+ Never: () => false,
141
+ Row: ({ guard, context }) => readsPrincipal(guard) ? assumed : Judge.match(Judge.predicate(guard.body, row, {
142
+ context,
143
+ rows
144
+ }), {
145
+ onKnown: (truth) => truth === true,
146
+ onUnknown: () => assumed
147
+ }),
148
+ Inherit: () => assumed,
149
+ And: ({ conditions }) => conditions.every(judge),
150
+ Or: ({ conditions }) => conditions.some(judge)
151
+ });
152
+ return judge(condition);
153
+ },
154
+ /**
68
155
  * `condition` with every row guard that reads one of `unset`, and every
69
156
  * relation of them it follows, refused: a field a create leaves unset
70
157
  * matches no guard, `isNull` and `isNotNull` alike, since the create never
@@ -117,13 +204,14 @@ const principalGuardsIn = (rules) => {
117
204
  * decided once, however many rules name it; a visitor passes no row guard
118
205
  * that reads the principal.
119
206
  */
120
- const conditionsFor = (rules, decide, visitor) => Effect.map(Effect.forEach(principalGuardsIn(rules), (guard) => Effect.map(decide(guard), (allowed) => [guard.name, allowed])), (decisions) => {
207
+ const conditionsFor = (rules, decide, visitor, context) => Effect.map(Effect.forEach(principalGuardsIn(rules), (guard) => Effect.map(decide(guard), (allowed) => [guard.name, allowed])), (decisions) => {
121
208
  const allowed = new Map(decisions);
122
209
  const conditionOf = (rule) => Match.valueTags(rule, {
123
210
  PrincipalGuard: ({ name }) => allowed.get(name) === true ? always : never,
124
211
  RowGuard: (guard) => visitor && readsPrincipal(guard) ? never : Object.freeze({
125
212
  _tag: "Row",
126
- guard
213
+ guard,
214
+ context
127
215
  }),
128
216
  All: ({ rules }) => and(rules.map(conditionOf)),
129
217
  Inherit: ({ relation }) => Object.freeze({
@@ -137,7 +225,7 @@ const conditionsFor = (rules, decide, visitor) => Effect.map(Effect.forEach(prin
137
225
  * How a Policy decides one interaction, given the set's principal guards as
138
226
  * decided for it.
139
227
  */
140
- const deciding = (decide, visitor, interaction) => ({
228
+ const deciding = (decide, visitor, interaction, context) => ({
141
229
  /** Who may do it to which rows of `entity`: `always`, then the row's rules for it. */
142
230
  row: (entity) => Option.match(attached(entity), {
143
231
  onNone: () => Effect.succeed({
@@ -152,7 +240,7 @@ const deciding = (decide, visitor, interaction) => ({
152
240
  onSome: ({ rules }) => rules
153
241
  });
154
242
  const unguarded = attachment.unguarded === "allow" ? always : never;
155
- return Effect.map(conditionsFor([...attachment.always, ...rules], decide, visitor), (condition) => ({
243
+ return Effect.map(conditionsFor([...attachment.always, ...rules], decide, visitor, context), (condition) => ({
156
244
  condition: and([condition(attachment.always, and), Option.isSome(row) ? condition(rules, or) : unguarded]),
157
245
  deny: Option.getOrElse(Option.flatMap(row, ({ deny }) => deny), () => defaultDeny(target))
158
246
  }));
@@ -185,7 +273,7 @@ const deciding = (decide, visitor, interaction) => ({
185
273
  }]
186
274
  });
187
275
  });
188
- return Effect.map(conditionsFor(surfaces.flatMap(({ rules }) => rules), decide, visitor), (condition) => surfaces.map(({ member, rules, deny }) => ({
276
+ return Effect.map(conditionsFor(surfaces.flatMap(({ rules }) => rules), decide, visitor, context), (condition) => surfaces.map(({ member, rules, deny }) => ({
189
277
  member,
190
278
  condition: condition(rules, or),
191
279
  deny
@@ -201,7 +289,7 @@ const deciding = (decide, visitor, interaction) => ({
201
289
  };
202
290
  return Option.match(Option.flatMap(attached(entity), (attachment) => surfaceOf(attachment, target)), {
203
291
  onNone: () => Effect.succeed(Option.none()),
204
- onSome: ({ rules, deny }) => Effect.map(conditionsFor(rules, decide, visitor), (condition) => Option.some({
292
+ onSome: ({ rules, deny }) => Effect.map(conditionsFor(rules, decide, visitor, context), (condition) => Option.some({
205
293
  condition: condition(rules, or),
206
294
  deny: Option.getOrElse(deny, () => defaultDeny(target))
207
295
  }))
@@ -214,4 +302,4 @@ const rowTarget = (interaction) => ({
214
302
  });
215
303
  export { deciding as n, readsPrincipal as r, Condition as t };
216
304
 
217
- //# sourceMappingURL=condition-Dx54lL7v.mjs.map
305
+ //# sourceMappingURL=condition-dNSbUHzE.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"condition-dNSbUHzE.mjs","names":[],"sources":["../src/condition.ts"],"sourcesContent":["/**\n * What an attachment's read rules come to for one principal, once its\n * principal guards are decided: a condition over the row, which an\n * interpreter runs (`evaluate` in memory, SQL in a binding). Principal guards\n * never reach it, so their bodies stay on the server that decided them.\n */\nimport { Effect, Match, Option } from 'effect'\nimport {\n Held,\n Judge,\n Query,\n evaluateEach,\n viewerIdOf,\n type AnyEntity,\n type EntityRef,\n type ExprContext,\n type HeldRow,\n type HeldRows,\n type MemoryOperators,\n} from 'foldkit-entity'\nimport { attached, defaultDeny, surfaceOf, type AnyRule, type Deny } from './attach.js'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\nexport type Condition =\n | { readonly _tag: 'Always' }\n | { readonly _tag: 'Never' }\n /** A row guard, and what its `Expr.viewer` reads: the principal it was decided for. */\n | {\n readonly _tag: 'Row'\n readonly guard: RowGuard<any, AnyEntity>\n readonly context: ExprContext\n }\n /** The row its `one` relation points at is readable. */\n | { readonly _tag: 'Inherit'; readonly relation: string }\n | { readonly _tag: 'And'; readonly conditions: ReadonlyArray<Condition> }\n | { readonly _tag: 'Or'; readonly conditions: ReadonlyArray<Condition> }\n\n/** Whether a row guard reads another row: one row cannot judge it. */\nconst reachesOther = (guard: RowGuard<any, AnyEntity>): boolean =>\n Query.dependencies(guard.query).reaches.length > 0\n\nconst always: Condition = Object.freeze({ _tag: 'Always' })\nconst never: Condition = Object.freeze({ _tag: 'Never' })\n\n/** A conjunction, with what it settles already folded away. */\nconst and = (conditions: ReadonlyArray<Condition>): Condition => {\n const kept: Array<Condition> = []\n for (const condition of conditions) {\n if (condition._tag === 'Never') return never\n if (condition._tag !== 'Always') kept.push(condition)\n }\n if (kept.length === 0) return always\n if (kept.length === 1) return kept[0]!\n return Object.freeze({ _tag: 'And', conditions: Object.freeze(kept) })\n}\n\n/** A disjunction, with what it settles already folded away. */\nconst or = (conditions: ReadonlyArray<Condition>): Condition => {\n const kept: Array<Condition> = []\n for (const condition of conditions) {\n if (condition._tag === 'Always') return always\n if (condition._tag !== 'Never') kept.push(condition)\n }\n if (kept.length === 0) return never\n if (kept.length === 1) return kept[0]!\n return Object.freeze({ _tag: 'Or', conditions: Object.freeze(kept) })\n}\n\nexport const Condition = {\n always,\n never,\n and,\n or,\n\n /**\n * Whether a row's stored values meet `condition`, its row guards read with\n * `input` (the principal's, from `G.inputOf`). `inherit` answers whether the\n * row a relation points at is readable, which only the caller can look up.\n * `operators` runs the guards' primitive operators: the policy's.\n *\n * A row guard the row's own values make an operator refuse (text holding a\n * NUL, an implementation that throws) does not hold: what a write supplies\n * can deny it, never end the request.\n */\n holds: (\n condition: Condition,\n values: Readonly<Record<string, unknown>>,\n input: Readonly<Record<string, unknown>>,\n inherit: (relation: string) => boolean,\n operators: MemoryOperators,\n ): boolean => {\n const holds = (each: Condition): boolean =>\n Match.valueTags(each, {\n Always: () => true,\n Never: () => false,\n // A row as a Source reads it holds its links as ref keys; the rule reads ids.\n Row: ({ guard, context }) =>\n evaluateEach(guard.query, input, [Held.fromRefs(guard.query, values)], {\n operators,\n context,\n }).matched.length === 1,\n Inherit: ({ relation }) => inherit(relation),\n And: ({ conditions }) => conditions.every(holds),\n Or: ({ conditions }) => conditions.some(holds),\n })\n return holds(condition)\n },\n\n /**\n * `condition` decided over one row as far as one row can: each row guard\n * over the row alone judged (`holds`), an inherited Read refused, as a\n * writer refuses one, and each row guard that reads another row (a path, an\n * exists) kept for a statement to judge. `Always` or `Never` when the row\n * alone decides it.\n */\n residual: (\n condition: Condition,\n values: Readonly<Record<string, unknown>>,\n input: Readonly<Record<string, unknown>>,\n operators: MemoryOperators,\n ): Condition => {\n const decided = (each: Condition): Condition =>\n Match.valueTags(each, {\n Always: () => each,\n Never: () => each,\n Row: row =>\n reachesOther(row.guard)\n ? each\n : Condition.holds(each, values, input, () => false, operators)\n ? always\n : never,\n Inherit: () => never,\n And: ({ conditions }) => and(conditions.map(decided)),\n Or: ({ conditions }) => or(conditions.map(decided)),\n })\n return decided(condition)\n },\n\n /** `Always` and `Never` as what one row decided; none where a statement must judge the rest. */\n decided: (condition: Condition): Option.Option<boolean> =>\n Match.valueTags(condition, {\n Always: () => Option.some(true),\n Never: () => Option.some(false),\n Row: () => Option.none(),\n Inherit: () => Option.none(),\n And: () => Option.none(),\n Or: () => Option.none(),\n }),\n\n /**\n * The members of `written`, the row a write changes, that a condition's\n * guards reading another row start from: each one's fields, the relation\n * each path leaves by, and, where `written` is the viewer's own row, what a\n * path from the viewer leaves it by. A write that changes one would need the\n * guard judged over the row it leaves, which a statement over the stored row\n * does not do.\n */\n reachedFrom: (condition: Condition, written: EntityRef): ReadonlyArray<string> => {\n const read = (each: Condition): ReadonlyArray<string> =>\n Match.valueTags(each, {\n Always: () => [],\n Never: () => [],\n Row: ({ guard, context }) => {\n if (!reachesOther(guard)) return []\n const dependencies = Query.dependencies(guard.query)\n return [\n ...dependencies.predicate.map(field => field.key),\n // An exists reached through a path leaves by its first relation as surely\n // as a path does; one over the row itself reads only its id. A path from the\n // viewer leaves the row written the same way when that row is the viewer's.\n ...dependencies.reaches.flatMap(reach =>\n Match.valueTags(reach, {\n Path: ({ via }) => [via[0]!.key],\n Exists: ({ via }) => via.slice(0, 1).map(relation => relation.key),\n ViewerPath: ({ viewer, via, field }) => {\n const start = viewer.target()\n return start.name === written.entity &&\n Option.exists(viewerIdOf(start, context), id => id === written.id)\n ? [via[0]?.key ?? field.key]\n : []\n },\n }),\n ),\n ]\n },\n Inherit: () => [],\n And: ({ conditions }) => conditions.flatMap(read),\n Or: ({ conditions }) => conditions.flatMap(read),\n })\n return [...new Set(read(condition))]\n },\n\n /**\n * Whether a row a client holds meets `condition`, a part it cannot decide\n * taken to be `assumed`: a row guard over the principal's fields, which a\n * client is not given, an inherited Read, and a rule over a row or field\n * the holder lacks. A row guard reads the holder's rows (`rows`) where it\n * follows a path from the viewer. Run once assuming each way, it is decided\n * where both agree, since no part of a condition is negated.\n */\n judge: (condition: Condition, row: HeldRow, rows: HeldRows, assumed: boolean): boolean => {\n const judge = (each: Condition): boolean =>\n Match.valueTags(each, {\n Always: () => true,\n Never: () => false,\n Row: ({ guard, context }) =>\n readsPrincipal(guard)\n ? assumed\n : Judge.match(Judge.predicate(guard.body, row, { context, rows }), {\n // SQL's null leaves a row out, as false does.\n onKnown: truth => truth === true,\n onUnknown: () => assumed,\n }),\n Inherit: () => assumed,\n And: ({ conditions }) => conditions.every(judge),\n Or: ({ conditions }) => conditions.some(judge),\n })\n return judge(condition)\n },\n\n /**\n * `condition` with every row guard that reads one of `unset`, and every\n * relation of them it follows, refused: a field a create leaves unset\n * matches no guard, `isNull` and `isNotNull` alike, since the create never\n * said what it holds.\n */\n unsetting: (condition: Condition, unset: ReadonlySet<string>): Condition => {\n const kept = (each: Condition): Condition =>\n Match.valueTags(each, {\n Always: () => each,\n Never: () => each,\n Row: ({ guard }) =>\n Query.dependencies(guard.query).predicate.some(field => unset.has(field.key))\n ? never\n : each,\n Inherit: ({ relation }) => (unset.has(relation) ? never : each),\n And: ({ conditions }) => and(conditions.map(kept)),\n Or: ({ conditions }) => or(conditions.map(kept)),\n })\n return kept(condition)\n },\n\n /** The members a condition reads: its row guards' fields, and each relation it follows. */\n members: (condition: Condition): ReadonlyArray<string> => {\n const read = (each: Condition): ReadonlyArray<string> =>\n Match.valueTags(each, {\n Always: () => [],\n Never: () => [],\n Row: ({ guard }) => Query.dependencies(guard.query).predicate.map(field => field.key),\n Inherit: ({ relation }) => [relation],\n And: ({ conditions }) => conditions.flatMap(read),\n Or: ({ conditions }) => conditions.flatMap(read),\n })\n return [...new Set(read(condition))]\n },\n}\n\n/** A member's read rule for one principal: the condition, and what a refusal shows. */\nexport interface MemberRead {\n readonly member: string\n readonly condition: Condition\n readonly deny: Deny\n}\n\n/**\n * Whether a row guard reads the principal's fields. A visitor has none, so\n * passes no guard that does; one over the row alone (`publishedAt` is set)\n * holds for a visitor as for anyone.\n */\nexport const readsPrincipal = (guard: RowGuard<any, AnyEntity>): boolean =>\n Query.dependencies(guard.query).inputs.length > 0\n\n/** Every principal guard the rules name, each once. */\nconst principalGuardsIn = (rules: ReadonlyArray<AnyRule>): ReadonlyArray<PrincipalGuard<any>> => {\n const found = new Map<string, PrincipalGuard<any>>()\n const visit = (rule: AnyRule): void =>\n Match.valueTags(rule, {\n PrincipalGuard: guard => void found.set(guard.name, guard),\n RowGuard: () => {},\n All: ({ rules }) => rules.forEach(visit),\n Inherit: () => {},\n })\n rules.forEach(visit)\n return [...found.values()]\n}\n\n/**\n * Turns `rules` into a condition for one principal. Each principal guard is\n * decided once, however many rules name it; a visitor passes no row guard\n * that reads the principal.\n */\nconst conditionsFor = <R>(\n rules: ReadonlyArray<AnyRule>,\n decide: (guard: PrincipalGuard<any>) => Effect.Effect<boolean, never, R>,\n visitor: boolean,\n context: ExprContext,\n): Effect.Effect<(rules: ReadonlyArray<AnyRule>, join: typeof and) => Condition, never, R> =>\n Effect.map(\n Effect.forEach(principalGuardsIn(rules), guard =>\n Effect.map(decide(guard), allowed => [guard.name, allowed] as const),\n ),\n decisions => {\n const allowed = new Map(decisions)\n const conditionOf = (rule: AnyRule): Condition =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => (allowed.get(name) === true ? always : never),\n RowGuard: guard =>\n visitor && readsPrincipal(guard)\n ? never\n : Object.freeze({ _tag: 'Row' as const, guard, context }),\n All: ({ rules }) => and(rules.map(conditionOf)),\n Inherit: ({ relation }) => Object.freeze({ _tag: 'Inherit' as const, relation }),\n })\n return (rules, join) => join(rules.map(conditionOf))\n },\n )\n\n/** A row's rule for one interaction and principal: the condition, and what a refusal shows. */\nexport interface RowRule {\n readonly condition: Condition\n readonly deny: Deny\n}\n\n/**\n * How a Policy decides one interaction, given the set's principal guards as\n * decided for it.\n */\nexport const deciding = <R>(\n decide: (guard: PrincipalGuard<any>) => Effect.Effect<boolean, never, R>,\n visitor: boolean,\n interaction: string,\n context: ExprContext,\n) => ({\n /** Who may do it to which rows of `entity`: `always`, then the row's rules for it. */\n row: (entity: AnyEntity): Effect.Effect<RowRule, never, R> =>\n Option.match(attached(entity), {\n onNone: () =>\n Effect.succeed({ condition: always, deny: defaultDeny(rowTarget(interaction)) }),\n onSome: attachment => {\n const target = rowTarget(interaction)\n const row = surfaceOf(attachment, target)\n const rules = Option.match(row, {\n onNone: (): ReadonlyArray<AnyRule> => [],\n onSome: ({ rules }) => rules,\n })\n // An interaction left without rules falls to the set's default.\n const unguarded = attachment.unguarded === 'allow' ? always : never\n return Effect.map(\n conditionsFor([...attachment.always, ...rules], decide, visitor, context),\n condition => ({\n condition: and([\n condition(attachment.always, and),\n Option.isSome(row) ? condition(rules, or) : unguarded,\n ]),\n deny: Option.getOrElse(\n Option.flatMap(row, ({ deny }) => deny),\n () => defaultDeny(target),\n ),\n }),\n )\n },\n }),\n\n /**\n * The rule of each of `members` that has one for this interaction. One\n * without follows its row. A relation key's Read is its relation's, decided\n * over the parent row as a member's is.\n */\n members: (\n entity: AnyEntity,\n members: ReadonlyArray<string>,\n ): Effect.Effect<ReadonlyArray<MemberRead>, never, R> =>\n Option.match(attached(entity), {\n onNone: () => Effect.succeed([]),\n onSome: attachment => {\n const surfaces = members.flatMap(member => {\n const target = Object.hasOwn(entity.relations, member)\n ? ({ _tag: 'Relation', relation: member, interaction } as const)\n : ({ _tag: 'Member', member, interaction } as const)\n return Option.match(surfaceOf(attachment, target), {\n onNone: () => [],\n onSome: ({ rules, deny }) => [\n { member, rules, deny: Option.getOrElse(deny, () => defaultDeny(target)) },\n ],\n })\n })\n return Effect.map(\n conditionsFor(\n surfaces.flatMap(({ rules }) => rules),\n decide,\n visitor,\n context,\n ),\n condition =>\n surfaces.map(({ member, rules, deny }) => ({\n member,\n condition: condition(rules, or),\n deny,\n })),\n )\n },\n }),\n\n /** A relation's rule for this interaction (`Link`, `Unlink`), when it has one. */\n relation: (\n entity: AnyEntity,\n relation: string,\n ): Effect.Effect<Option.Option<RowRule>, never, R> => {\n const target = { _tag: 'Relation', relation, interaction } as const\n return Option.match(\n Option.flatMap(attached(entity), attachment => surfaceOf(attachment, target)),\n {\n onNone: () => Effect.succeed(Option.none()),\n onSome: ({ rules, deny }) =>\n Effect.map(conditionsFor(rules, decide, visitor, context), condition =>\n Option.some({\n condition: condition(rules, or),\n deny: Option.getOrElse(deny, () => defaultDeny(target)),\n }),\n ),\n },\n )\n },\n})\n\nconst rowTarget = (interaction: string) => ({ _tag: 'Row', interaction }) as const\n"],"mappings":";;;;;;;;;;;AAsCA,MAAM,gBAAgB,UACpB,MAAM,aAAa,MAAM,KAAK,CAAC,CAAC,QAAQ,SAAS;AAEnD,MAAM,SAAoB,OAAO,OAAO,EAAE,MAAM,SAAS,CAAC;AAC1D,MAAM,QAAmB,OAAO,OAAO,EAAE,MAAM,QAAQ,CAAC;;AAGxD,MAAM,OAAO,eAAoD;CAC/D,MAAM,OAAyB,CAAC;CAChC,KAAK,MAAM,aAAa,YAAY;EAClC,IAAI,UAAU,SAAS,SAAS,OAAO;EACvC,IAAI,UAAU,SAAS,UAAU,KAAK,KAAK,SAAS;CACtD;CACA,IAAI,KAAK,WAAW,GAAG,OAAO;CAC9B,IAAI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,MAAM,SAAS;GAAE,MAAM;GAAY;GAAU;EAAY;EACzD,OAAO,OAAO,MACZ,OAAO,QAAQ,SAAS,MAAM,IAAG,eAAc,UAAU,YAAY,MAAM,CAAC,GAC5E;GACE,cAAc,OAAO,QAAQ,OAAO,KAAK,CAAC;GAC1C,SAAS,EAAE,OAAO,WAChB,OAAO,IAAI,cAAc,OAAO,QAAQ,SAAS,OAAO,IAAG,cACzD,OAAO,KAAK;IACV,WAAW,UAAU,OAAO,EAAE;IAC9B,MAAM,OAAO,UAAU,YAAY,YAAY,MAAM,CAAC;GACxD,CAAC,CACH;EACJ,CACF;CACF;AACF;AAEA,MAAM,aAAa,iBAAyB;CAAE,MAAM;CAAO;AAAY"}
@@ -1,4 +1,4 @@
1
- import { S as Policy } from "./attach-BepaL930.mjs";
1
+ import { S as Policy } from "./attach-DPgyv78F.mjs";
2
2
  import { AnyEntity } from "foldkit-entity";
3
3
  import { DrizzleOperators, Visible } from "foldkit-remote-drizzle";
4
4
  export declare const GuardDrizzle: {
package/dist/drizzle.mjs CHANGED
@@ -1,10 +1,10 @@
1
- import { o as flattenRules, r as attached } from "./attach-CRCF5XHS.mjs";
2
- import { n as rowRules } from "./placed-BvdNmZJu.mjs";
1
+ import { o as flattenRules, r as attached } from "./attach-CEGlbWu5.mjs";
2
+ import { n as rowRules } from "./placed-CGyo-NRR.mjs";
3
3
  import { Effect, Match, Option } from "effect";
4
4
  import { Query } from "foldkit-entity";
5
5
  import { RemoteServerError } from "foldkit-remote-server";
6
6
  import { and, or, sql } from "drizzle-orm";
7
- import { DrizzleOperators, compileWhere, idColumn, supported as supported$1 } from "foldkit-remote-drizzle";
7
+ import { DrizzleOperators, bodyOperations, compileWhere, idColumn } from "foldkit-remote-drizzle";
8
8
  // src/drizzle.ts
9
9
  /**
10
10
  * A guard set's read rules as `foldkit-remote-drizzle` bindings' `visible`:
@@ -46,7 +46,7 @@ visible: (policy, entities, options = {}) => {
46
46
  for (const rule of flattenRules(readRules(entity))) Match.valueTags(rule, {
47
47
  PrincipalGuard: () => {},
48
48
  RowGuard: (guard) => {
49
- const missing = Query.unsupported(guard.query, supported$1, sqlOperators);
49
+ const missing = Query.unsupported(guard.query, bodyOperations, sqlOperators);
50
50
  if (missing.length > 0) fail(`${entity.name}'s ${guard.name} needs ${missing.join(", ")}, which SQL here does not run`);
51
51
  },
52
52
  All: () => {},
@@ -69,12 +69,14 @@ visible: (policy, entities, options = {}) => {
69
69
  const of = (condition) => Match.valueTags(condition, {
70
70
  Always: () => void 0,
71
71
  Never: () => nothing,
72
- Row: ({ guard }) => and(...compileWhere(guard.query, {
72
+ Row: ({ guard, context }) => and(...compileWhere(guard.query, {
73
73
  ...binding,
74
74
  operators: {
75
75
  memory: policy.operators,
76
76
  sql: sqlOperators
77
- }
77
+ },
78
+ context,
79
+ visibleOf: () => Option.none()
78
80
  }, input, `${name}.${guard.name}`)),
79
81
  And: ({ conditions: parts }) => and(...parts.map(of)),
80
82
  Or: ({ conditions: parts }) => or(...parts.map(of)),
@@ -1 +1 @@
1
- {"version":3,"file":"drizzle.mjs","names":["supported"],"sources":["../src/drizzle.ts"],"sourcesContent":["/**\n * A guard set's read rules as `foldkit-remote-drizzle` bindings' `visible`:\n * each principal guard decided, what is left compiled to SQL over the table,\n * and an inherited Read a subquery over the related table's own rule.\n */\nimport { and, or, sql, type SQL } from 'drizzle-orm'\nimport { Effect, Match, Option } from 'effect'\nimport { Query, type AnyEntity } from 'foldkit-entity'\nimport {\n DrizzleOperators,\n compileWhere,\n idColumn,\n supported,\n type AnyEntityBinding,\n type Visible,\n} from 'foldkit-remote-drizzle'\nimport { RemoteServerError } from 'foldkit-remote-server'\nimport { attached, flattenRules, type AnyRule } from './attach.js'\nimport type { Condition } from './condition.js'\nimport type { Policy } from './index.js'\nimport { rowRules } from './placed.js'\n\n// A declaration, not an arrow, so a call narrows what follows it.\nfunction fail(message: string): never {\n throw new Error(`[foldkit-guard] GuardDrizzle.visible: ${message}`)\n}\n\n/** Every rule that decides who may read a row of `entity`. */\nconst readRules = (entity: AnyEntity): ReadonlyArray<AnyRule> =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => [...attachment.always, ...(attachment.row['Read']?.rules ?? [])],\n })\n\nconst nothing = sql`1 = 0`\n\nexport const GuardDrizzle = {\n /**\n * The `visible` rule of each of `entities`, the Entities as `Guards.attach`\n * returned them, by name, for `bind`'s storage. Checked here, before any\n * request: a row guard this compiler cannot run, and an inherited Read whose\n * Entity is not listed, has no Read rule, or leads back to itself, throw.\n * `operators` is the SQL table each rule is checked against here and compiled\n * by (the kernel's when not given), and the policy's table decides what a rule\n * reads from the input alone, so a server that starts can compile every rule\n * whatever table its bindings were given. Give it the bindings' SQL table, so\n * a rule and a query over one operator compile it alike.\n *\n * ```ts\n * const visible = GuardDrizzle.visible(Policy, [Todo, Project])\n * bind(Domain, { Todo: { table: todos, visible: visible.Todo, … }, … })\n * ```\n */\n visible: <User, const Es extends ReadonlyArray<AnyEntity>>(\n policy: Policy<User>,\n entities: Es,\n options: { readonly operators?: DrizzleOperators | undefined } = {},\n ): { readonly [K in Es[number]['name']]: Visible } => {\n const sqlOperators = options.operators ?? DrizzleOperators.kernel\n const byName = new Map(entities.map(entity => [entity.name, entity] as const))\n const inherits = new Map<string, ReadonlyArray<string>>()\n for (const entity of entities) {\n const targets: Array<string> = []\n for (const rule of flattenRules(readRules(entity))) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n const missing = Query.unsupported(guard.query, supported, sqlOperators)\n if (missing.length > 0) {\n fail(\n `${entity.name}'s ${guard.name} needs ${missing.join(', ')}, which SQL here does not run`,\n )\n }\n },\n All: () => {},\n Inherit: ({ relation }) => {\n const target = entity.relations[relation]!.target().name\n const guarded = byName.get(target)\n if (guarded === undefined) {\n fail(`${entity.name} inherits ${target}'s Read, but ${target} is not listed`)\n }\n if (readRules(guarded).length === 0) {\n fail(`${entity.name} inherits ${target}'s Read, but ${target} has no Read rule`)\n }\n targets.push(target)\n },\n })\n }\n inherits.set(entity.name, targets)\n }\n // A loop of inherited Reads would be a subquery that never ends.\n const closure = (name: string, path: ReadonlyArray<string>): ReadonlyArray<string> => {\n if (path.includes(name)) fail(`inherited Reads loop: ${[...path, name].join(' → ')}`)\n return [name, ...(inherits.get(name) ?? []).flatMap(next => closure(next, [...path, name]))]\n }\n const reaches = new Map(\n entities.map(entity => [entity.name, [...new Set(closure(entity.name, []))]]),\n )\n\n const compile = (\n name: string,\n binding: AnyEntityBinding,\n conditions: ReadonlyMap<string, Condition>,\n input: Readonly<Record<string, unknown>>,\n ): SQL | undefined => {\n const of = (condition: Condition): SQL | undefined =>\n Match.valueTags(condition, {\n Always: () => undefined,\n Never: () => nothing,\n // By the tables the rule was checked against: the SQL one given here, and\n // the policy's for what is decided from the input alone, as Guard judges.\n Row: ({ guard }) =>\n and(\n ...compileWhere(\n guard.query,\n { ...binding, operators: { memory: policy.operators, sql: sqlOperators } },\n input,\n `${name}.${guard.name}`,\n ),\n ),\n And: ({ conditions: parts }) => and(...parts.map(of)),\n // `Condition.or` folds away a part that admits every row, so each part here is SQL.\n Or: ({ conditions: parts }) => or(...parts.map(of)),\n Inherit: ({ relation }) => {\n const storage = binding.relations[relation]\n if (storage === undefined || storage.kind !== 'one') {\n return fail(\n `${name}.${relation} is inherited, so it must be stored as a foreign key here`,\n )\n }\n const target = storage.entity\n const where = compile(target.name, target, conditions, input) ?? sql`1 = 1`\n return sql`${storage.field} in (select ${idColumn(target)} from ${target.table} where ${where})`\n },\n })\n return of(conditions.get(name)!)\n }\n\n const visible =\n (name: string): Visible =>\n (principal, self) => {\n if (!policy.isPrincipal(principal)) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: the principal is not an Option of the guard set's`),\n )\n }\n return Effect.flatMap(\n Effect.forEach(reaches.get(name)!, each =>\n Effect.map(\n policy.readable(byName.get(each)!, principal),\n condition => [each, condition] as const,\n ),\n ),\n decided =>\n Effect.try({\n try: () => compile(name, self, new Map(decided), policy.inputOf(principal)),\n catch: error =>\n new RemoteServerError({\n message: error instanceof Error ? error.message : String(error),\n }),\n }),\n )\n }\n return Object.fromEntries(\n entities.map(entity => [entity.name, rowRules.add(visible(entity.name), policy, [entity])]),\n ) as {\n readonly [K in Es[number]['name']]: Visible\n }\n },\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,SAAS,KAAK,SAAwB;CACpC,MAAM,IAAI,MAAM,yCAAyC,SAAS;AACpE;;AAGA,MAAM,aAAa,WACjB,OAAO,MAAM,SAAS,MAAM,GAAG;CAC7B,cAAc,CAAC;CACf,SAAQ,eAAc,CAAC,GAAG,WAAW,QAAQ,GAAI,WAAW,IAAI,OAAO,EAAE,SAAS,CAAC,CAAE;AACvF,CAAC;AAEH,MAAM,UAAU,GAAG;AAEnB,MAAa,eAAe;;;;;;;;;;;;;;;;;AAiB1B,UACE,QACA,UACA,UAAiE,CAAC,MACd;CACpD,MAAM,eAAe,QAAQ,aAAa,iBAAiB;CAC3D,MAAM,SAAS,IAAI,IAAI,SAAS,KAAI,WAAU,CAAC,OAAO,MAAM,MAAM,CAAU,CAAC;CAC7E,MAAM,2BAAW,IAAI,IAAmC;CACxD,KAAK,MAAM,UAAU,UAAU;EAC7B,MAAM,UAAyB,CAAC;EAChC,KAAK,MAAM,QAAQ,aAAa,UAAU,MAAM,CAAC,GAC/C,MAAM,UAAU,MAAM;GACpB,sBAAsB,CAAC;GACvB,WAAU,UAAS;IACjB,MAAM,UAAU,MAAM,YAAY,MAAM,OAAOA,aAAW,YAAY;IACtE,IAAI,QAAQ,SAAS,GACnB,KACE,GAAG,OAAO,KAAK,KAAK,MAAM,KAAK,SAAS,QAAQ,KAAK,IAAI,EAAE,8BAC7D;GAEJ;GACA,WAAW,CAAC;GACZ,UAAU,EAAE,eAAe;IACzB,MAAM,SAAS,OAAO,UAAU,SAAS,CAAE,OAAO,CAAC,CAAC;IACpD,MAAM,UAAU,OAAO,IAAI,MAAM;IACjC,IAAI,YAAY,KAAA,GACd,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;IAEF,MAAM,SAAS,QAAQ;IACvB,MAAM,QAAQ,QAAQ,OAAO,MAAM,QAAQ,YAAY,KAAK,KAAK,GAAG;IACpE,OAAO,GAAG,GAAG,QAAQ,MAAM,cAAc,SAAS,MAAM,EAAE,QAAQ,OAAO,MAAM,SAAS,MAAM;GAChG;EACF,CAAC;EACH,OAAO,GAAG,WAAW,IAAI,IAAI,CAAE;CACjC;CAEA,MAAM,WACH,UACA,WAAW,SAAS;EACnB,IAAI,CAAC,OAAO,YAAY,SAAS,GAC/B,OAAO,OAAO,oBACZ,IAAI,MAAM,mBAAmB,KAAK,oDAAoD,CACxF;EAEF,OAAO,OAAO,QACZ,OAAO,QAAQ,QAAQ,IAAI,IAAI,IAAI,SACjC,OAAO,IACL,OAAO,SAAS,OAAO,IAAI,IAAI,GAAI,SAAS,IAC5C,cAAa,CAAC,MAAM,SAAS,CAC/B,CACF,IACA,YACE,OAAO,IAAI;GACT,WAAW,QAAQ,MAAM,MAAM,IAAI,IAAI,OAAO,GAAG,OAAO,QAAQ,SAAS,CAAC;GAC1E,QAAO,UACL,IAAI,kBAAkB,EACpB,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAChE,CAAC;EACL,CAAC,CACL;CACF;CACF,OAAO,OAAO,YACZ,SAAS,KAAI,WAAU,CAAC,OAAO,MAAM,SAAS,IAAI,QAAQ,OAAO,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAC5F;AAGF,EACF"}
1
+ {"version":3,"file":"drizzle.mjs","names":[],"sources":["../src/drizzle.ts"],"sourcesContent":["/**\n * A guard set's read rules as `foldkit-remote-drizzle` bindings' `visible`:\n * each principal guard decided, what is left compiled to SQL over the table,\n * and an inherited Read a subquery over the related table's own rule.\n */\nimport { and, or, sql, type SQL } from 'drizzle-orm'\nimport { Effect, Match, Option } from 'effect'\nimport { Query, type AnyEntity } from 'foldkit-entity'\nimport {\n DrizzleOperators,\n bodyOperations,\n compileWhere,\n idColumn,\n type AnyEntityBinding,\n type Visible,\n} from 'foldkit-remote-drizzle'\nimport { RemoteServerError } from 'foldkit-remote-server'\nimport { attached, flattenRules, type AnyRule } from './attach.js'\nimport type { Condition } from './condition.js'\nimport type { Policy } from './index.js'\nimport { rowRules } from './placed.js'\n\n// A declaration, not an arrow, so a call narrows what follows it.\nfunction fail(message: string): never {\n throw new Error(`[foldkit-guard] GuardDrizzle.visible: ${message}`)\n}\n\n/** Every rule that decides who may read a row of `entity`. */\nconst readRules = (entity: AnyEntity): ReadonlyArray<AnyRule> =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => [...attachment.always, ...(attachment.row['Read']?.rules ?? [])],\n })\n\nconst nothing = sql`1 = 0`\n\nexport const GuardDrizzle = {\n /**\n * The `visible` rule of each of `entities`, the Entities as `Guards.attach`\n * returned them, by name, for `bind`'s storage. Checked here, before any\n * request: a row guard this compiler cannot run, and an inherited Read whose\n * Entity is not listed, has no Read rule, or leads back to itself, throw.\n * `operators` is the SQL table each rule is checked against here and compiled\n * by (the kernel's when not given), and the policy's table decides what a rule\n * reads from the input alone, so a server that starts can compile every rule\n * whatever table its bindings were given. Give it the bindings' SQL table, so\n * a rule and a query over one operator compile it alike.\n *\n * ```ts\n * const visible = GuardDrizzle.visible(Policy, [Todo, Project])\n * bind(Domain, { Todo: { table: todos, visible: visible.Todo, … }, … })\n * ```\n */\n visible: <User, const Es extends ReadonlyArray<AnyEntity>>(\n policy: Policy<User>,\n entities: Es,\n options: { readonly operators?: DrizzleOperators | undefined } = {},\n ): { readonly [K in Es[number]['name']]: Visible } => {\n const sqlOperators = options.operators ?? DrizzleOperators.kernel\n const byName = new Map(entities.map(entity => [entity.name, entity] as const))\n const inherits = new Map<string, ReadonlyArray<string>>()\n for (const entity of entities) {\n const targets: Array<string> = []\n for (const rule of flattenRules(readRules(entity))) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n const missing = Query.unsupported(guard.query, bodyOperations, sqlOperators)\n if (missing.length > 0) {\n fail(\n `${entity.name}'s ${guard.name} needs ${missing.join(', ')}, which SQL here does not run`,\n )\n }\n },\n All: () => {},\n Inherit: ({ relation }) => {\n const target = entity.relations[relation]!.target().name\n const guarded = byName.get(target)\n if (guarded === undefined) {\n fail(`${entity.name} inherits ${target}'s Read, but ${target} is not listed`)\n }\n if (readRules(guarded).length === 0) {\n fail(`${entity.name} inherits ${target}'s Read, but ${target} has no Read rule`)\n }\n targets.push(target)\n },\n })\n }\n inherits.set(entity.name, targets)\n }\n // A loop of inherited Reads would be a subquery that never ends.\n const closure = (name: string, path: ReadonlyArray<string>): ReadonlyArray<string> => {\n if (path.includes(name)) fail(`inherited Reads loop: ${[...path, name].join(' → ')}`)\n return [name, ...(inherits.get(name) ?? []).flatMap(next => closure(next, [...path, name]))]\n }\n const reaches = new Map(\n entities.map(entity => [entity.name, [...new Set(closure(entity.name, []))]]),\n )\n\n const compile = (\n name: string,\n binding: AnyEntityBinding,\n conditions: ReadonlyMap<string, Condition>,\n input: Readonly<Record<string, unknown>>,\n ): SQL | undefined => {\n const of = (condition: Condition): SQL | undefined =>\n Match.valueTags(condition, {\n Always: () => undefined,\n Never: () => nothing,\n // By the tables the rule was checked against: the SQL one given here, and\n // the policy's for what is decided from the input alone, as Guard judges.\n // A rule reads the rows it reaches as they are stored: it is the server's\n // decision, as a principal guard's body is, not a read by the principal.\n Row: ({ guard, context }) =>\n and(\n ...compileWhere(\n guard.query,\n {\n ...binding,\n operators: { memory: policy.operators, sql: sqlOperators },\n context,\n visibleOf: () => Option.none(),\n },\n input,\n `${name}.${guard.name}`,\n ),\n ),\n And: ({ conditions: parts }) => and(...parts.map(of)),\n // `Condition.or` folds away a part that admits every row, so each part here is SQL.\n Or: ({ conditions: parts }) => or(...parts.map(of)),\n Inherit: ({ relation }) => {\n const storage = binding.relations[relation]\n if (storage === undefined || storage.kind !== 'one') {\n return fail(\n `${name}.${relation} is inherited, so it must be stored as a foreign key here`,\n )\n }\n const target = storage.entity\n const where = compile(target.name, target, conditions, input) ?? sql`1 = 1`\n return sql`${storage.field} in (select ${idColumn(target)} from ${target.table} where ${where})`\n },\n })\n return of(conditions.get(name)!)\n }\n\n const visible =\n (name: string): Visible =>\n (principal, self) => {\n if (!policy.isPrincipal(principal)) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: the principal is not an Option of the guard set's`),\n )\n }\n return Effect.flatMap(\n Effect.forEach(reaches.get(name)!, each =>\n Effect.map(\n policy.readable(byName.get(each)!, principal),\n condition => [each, condition] as const,\n ),\n ),\n decided =>\n Effect.try({\n try: () => compile(name, self, new Map(decided), policy.inputOf(principal)),\n catch: error =>\n new RemoteServerError({\n message: error instanceof Error ? error.message : String(error),\n }),\n }),\n )\n }\n return Object.fromEntries(\n entities.map(entity => [entity.name, rowRules.add(visible(entity.name), policy, [entity])]),\n ) as {\n readonly [K in Es[number]['name']]: Visible\n }\n },\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,SAAS,KAAK,SAAwB;CACpC,MAAM,IAAI,MAAM,yCAAyC,SAAS;AACpE;;AAGA,MAAM,aAAa,WACjB,OAAO,MAAM,SAAS,MAAM,GAAG;CAC7B,cAAc,CAAC;CACf,SAAQ,eAAc,CAAC,GAAG,WAAW,QAAQ,GAAI,WAAW,IAAI,OAAO,EAAE,SAAS,CAAC,CAAE;AACvF,CAAC;AAEH,MAAM,UAAU,GAAG;AAEnB,MAAa,eAAe;;;;;;;;;;;;;;;;;AAiB1B,UACE,QACA,UACA,UAAiE,CAAC,MACd;CACpD,MAAM,eAAe,QAAQ,aAAa,iBAAiB;CAC3D,MAAM,SAAS,IAAI,IAAI,SAAS,KAAI,WAAU,CAAC,OAAO,MAAM,MAAM,CAAU,CAAC;CAC7E,MAAM,2BAAW,IAAI,IAAmC;CACxD,KAAK,MAAM,UAAU,UAAU;EAC7B,MAAM,UAAyB,CAAC;EAChC,KAAK,MAAM,QAAQ,aAAa,UAAU,MAAM,CAAC,GAC/C,MAAM,UAAU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AAU,CAAC,OAAO,MAAM,SAAS,IAAI,QAAQ,OAAO,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAC5F;AAGF,EACF"}
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-BepaL930.mjs";
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-DPgyv78F.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 CHANGED
@@ -1,7 +1,7 @@
1
- import { n as Interaction, r as attached, t as Attaching } from "./attach-CRCF5XHS.mjs";
2
- import { n as deciding, r as readsPrincipal, t as Condition } from "./condition-Dx54lL7v.mjs";
3
- import { n as MaySchema, t as May } from "./may-DzCAt_5M.mjs";
4
- import { n as me, t as ME } from "./me-BYpuVqJE.mjs";
1
+ import { n as Interaction, r as attached, t as Attaching } from "./attach-CEGlbWu5.mjs";
2
+ import { n as deciding, r as readsPrincipal, t as Condition } from "./condition-dNSbUHzE.mjs";
3
+ import { n as MaySchema, t as May } from "./may-DprCmMgK.mjs";
4
+ import { n as me, t as ME } from "./me-C-gX1paZ.mjs";
5
5
  import { n as providedFrom } from "./origin-igJoiz74.mjs";
6
6
  import { Context, Effect, Match, Option, Schema } from "effect";
7
7
  import { Expr, Operators, Query, evaluate } from "foldkit-entity";
@@ -40,11 +40,7 @@ const provided = (policy, context) => {
40
40
  };
41
41
  return providedFrom(next, policy);
42
42
  };
43
- const placeholdersOf = (fields) => {
44
- const inputs = {};
45
- for (const key of Object.keys(fields)) inputs[key] = Expr.input(`principal.${key}`, fields[key]);
46
- return Object.freeze(inputs);
47
- };
43
+ const placeholdersOf = (fields) => Object.freeze(Object.fromEntries(Object.entries(fields).map(([key, schema]) => [key, Expr.input(`principal.${key}`, schema)])));
48
44
  const Guards = {
49
45
  ...Attaching,
50
46
  /**
@@ -81,11 +77,17 @@ const Guards = {
81
77
  const placeholders = placeholdersOf(principal.fields);
82
78
  const specs = build({
83
79
  principal: () => Object.freeze({ _tag: "PrincipalSpec" }),
84
- row: (entity, body) => Object.freeze({
85
- _tag: "RowSpec",
86
- entity,
87
- body: body(placeholders)
88
- })
80
+ row: (entity, body) => {
81
+ const predicate = body(placeholders);
82
+ const { operations } = Query.dependencies(Query.from(entity).pipe(Query.where(predicate)));
83
+ if (operations.includes("now")) throw new Error(`[foldkit-guard] ${name}: a rule over ${entity.name} reads Expr.now; who may do something does not move with the clock here`);
84
+ if (operations.includes("viewer") && options.viewer === void 0) throw new Error(`[foldkit-guard] ${name}: a rule over ${entity.name} reads Expr.viewer, but the set names no viewer Entity; declare it with { viewer }`);
85
+ return Object.freeze({
86
+ _tag: "RowSpec",
87
+ entity,
88
+ body: predicate
89
+ });
90
+ }
89
91
  });
90
92
  const guards = Object.create(null);
91
93
  for (const [guard, spec] of Object.entries(specs)) {
@@ -113,6 +115,14 @@ const Guards = {
113
115
  for (const [field, encode] of Object.entries(encoders)) input[`principal.${field}`] = encode(user[field]);
114
116
  return input;
115
117
  };
118
+ const viewerOf = (user) => Option.flatMap(Option.fromUndefinedOr(options.viewer), (entity) => Option.map(user, (each) => ({
119
+ entity: entity.name,
120
+ id: options.key(each)
121
+ })));
122
+ const contextOf = (user) => ({
123
+ viewer: viewerOf(user),
124
+ now: Option.none()
125
+ });
116
126
  const isPrincipal = Schema.is(Schema.Option(principal));
117
127
  const asJson = Schema.encodeSync(Schema.toCodecJson(principal));
118
128
  const implement = (bodies, implementation = {}) => {
@@ -128,8 +138,14 @@ const Guards = {
128
138
  return Effect.isEffect(decided) ? decided : Effect.succeed(decided);
129
139
  },
130
140
  RowGuard: (rowGuard) => Effect.succeed(row !== void 0 && Option.match(principal, {
131
- onNone: () => !readsPrincipal(rowGuard) && evaluate(rowGuard.query, {}, [row], { operators }).length === 1,
132
- onSome: (user) => evaluate(rowGuard.query, inputOf(user), [row], { operators }).length === 1
141
+ onNone: () => !readsPrincipal(rowGuard) && evaluate(rowGuard.query, {}, [row], {
142
+ operators,
143
+ context: contextOf(principal)
144
+ }).length === 1,
145
+ onSome: (user) => evaluate(rowGuard.query, inputOf(user), [row], {
146
+ operators,
147
+ context: contextOf(principal)
148
+ }).length === 1
133
149
  }))
134
150
  });
135
151
  };
@@ -140,7 +156,7 @@ const Guards = {
140
156
  return deciding((guard) => Effect.map(decide(guard, {
141
157
  principal,
142
158
  interaction
143
- }), (decision) => decision === true), Option.isNone(principal), interaction);
159
+ }), (decision) => decision === true), Option.isNone(principal), interaction, contextOf(principal));
144
160
  };
145
161
  const policy = {
146
162
  set: name,
@@ -155,6 +171,7 @@ const Guards = {
155
171
  onNone: () => ({}),
156
172
  onSome: (user) => inputOf(user)
157
173
  }),
174
+ viewer: viewerOf,
158
175
  key: options.key,
159
176
  keyOf: (principal) => Option.match(principal, {
160
177
  onNone: () => "visitor",