foldkit-guard 0.3.1 → 0.4.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 CHANGED
@@ -349,7 +349,8 @@ Policy as it is and require its services where the write runs.
349
349
  ## Serving writes
350
350
 
351
351
  A declared write (`Mutation.write`) is served by `RemoteServer.write` with no
352
- handler. Wrap its writer, and the write rules are checked before it lands:
352
+ handler (the [declared writes guide](../../docs/declared-writes.md) shows the
353
+ whole path, client to statement). Wrap its writer, and the write rules are checked before it lands:
353
354
 
354
355
  ```ts
355
356
  import { Write } from 'foldkit-entity'
@@ -387,6 +388,59 @@ RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
387
388
  fields than the write set, and a row the write hid from them in `deleted`,
388
389
  so the client takes it out of its lists instead of placing it.
389
390
 
391
+ Reading the row and writing it are two statements, so another write can land
392
+ between the check and the write. Name a revision, a field stored as a number
393
+ that the writer moves on by one with every write it lands, and the guard closes
394
+ that window for every write that moves it: for an Entity with
395
+ a `revision` field, `GuardServer.writer(Todo, Policy, writer(Db.Todo), {
396
+ revision: 'revision' })`. Every update and delete then lands only on the
397
+ revision its rules were decided over (the writer's `expect`, one compare and
398
+ set statement). If the row moved after the check, it is decided again over
399
+ the row as it now is, up to three times, then fails with "changed while it
400
+ was written"; nothing is written over a version no rule saw. An input that
401
+ `expect`s a revision the row is not at is a `Conflict`, decided before any
402
+ rule, and not retried. An input may expect only the revision the writer pins:
403
+ one expecting another field is refused, at startup by `GuardServer.validate`
404
+ and at run time, since the pin would leave that field where it was. A writer
405
+ with no `revision` keeps the window, and `GuardServer.validate` warns of each
406
+ write through one.
407
+
408
+ A declared write's `when` (`foldkit-entity`) is the writer's to check, in the
409
+ statement that writes; the guarded writer passes it through and speaks first.
410
+ The order is: a row hidden from the writer, then a rule that does not hold
411
+ (both `Forbidden`), then a stale input revision (`Conflict`), then the
412
+ precondition (`Unmet`). So `Unmet` reaches only someone the rules let write the
413
+ row. A precondition, or an expected revision, over a member with a Read rule
414
+ would still answer for that member (Unmet or written, Conflict or not), so the
415
+ guarded writer refuses such a write before any rule, whether or not
416
+ `GuardServer.validate` ran; `validate` refuses it at startup too, as it refuses
417
+ a query body that filters by such a member. A pinned write that is unmet is not
418
+ decided again: the row did not move, it does not hold.
419
+
420
+ A declared write's `increment` is the writer's to add, in the statement that
421
+ writes. The guard requires each incremented member's Update rule, as for a
422
+ member it sets, and holds the row's rules over the sum the writer will store, so
423
+ a rule `stock >= 0` refuses a sale past zero. The row the guard summed over must
424
+ be the row the writer writes: the input's expected revision keeps it so, or the
425
+ writer's `revision` pin. An increment with neither is refused.
426
+
427
+ An Entity's invariants (`Entity.invariant`) are the writer's to judge, over the
428
+ row its statement writes; the guarded writer passes them through and speaks
429
+ first. They are not rules, and are never one of a command's alternatives:
430
+ `Update: [isOwner, isManager]` says who may, and an invariant says what every
431
+ row must hold whoever writes it, so being allowed does not make a row valid and
432
+ a valid row does not make anyone allowed. `Invalid` reaches only someone the
433
+ rules let write the row. An invariant that reads the row before (a transition
434
+ invariant) is the same: the writer's, after the rules. An invariant that reads a member with
435
+ a Read rule is enforced all the same, but its refusal names no invariant and no path ("The row
436
+ would be invalid"), since naming it would say what that member holds.
437
+
438
+ Over a writer with a ledger (`foldkit-remote-drizzle`'s `writer(binding, {
439
+ ledger })`), a retry of an operation that landed is answered from the ledger,
440
+ before any rule: it was decided when it landed, and deciding it again over a row
441
+ that has moved since could refuse a write that happened. A new operation is
442
+ decided as any write is.
443
+
390
444
  The binding must have a `visible` rule, which is how the writer reads a row
391
445
  as its writer may see it; the writer refuses one without. That the rule is
392
446
  `GuardDrizzle.visible`'s is what `GuardServer.validate` checks of the
@@ -752,10 +806,16 @@ const uploads = uploadLayer().pipe(
752
806
  - **A Sync document is one audience.** Per-member or per-row secrecy within
753
807
  one is not something a replicated log offers: `GuardSync.document` refuses
754
808
  it where it is declared.
755
- - **A write's check and the write are two statements.** The row is read and
756
- its rules decided, then it is written; a change of owner landing between
757
- them is not seen. A write that `expect`s a revision is refused once the row
758
- moved; one that does not takes that window.
809
+ - **A `revision` pins one row, against the writes that move it.** A write
810
+ rule reads the principal and the row, so pinning the row's revision makes
811
+ the check and the write one. Only the declared writes that pin or `expect`
812
+ it move it on: a handler (`RemoteServer.mutation`), raw SQL or a migration
813
+ that changes the row without moving it is not seen, unless the table carries
814
+ `foldkit-remote-drizzle`'s `revisionTrigger`, which has the database move it
815
+ on every update that does not. Sync's `applyEdits` keeps one revision for two
816
+ changes in one operation, so a table Sync writes takes no trigger, and the
817
+ pin does not see that second change. A writer given no `revision` does not
818
+ see a change landing between its check and its write.
759
819
  - **Sync's `admit` reads the table, which lags the journal.** An edit lands
760
820
  in the table when its exchange settles, so an edit admitted before another
761
821
  lands is judged against the row as it was: a concurrent change of owner
package/dist/server.d.mts CHANGED
@@ -56,12 +56,23 @@ export declare const GuardServer: {
56
56
  * from, and a create whose input sets a preset field is a mistake of the
57
57
  * server's, refused.
58
58
  *
59
+ * `revision` names a field stored as a number, which the writer moves on by
60
+ * one with each write it lands. An update or a delete then lands only on the
61
+ * revision its rules were decided over (the writer's `expect`), so a change
62
+ * between the check and the write is never written over; it is decided
63
+ * again against the row as it now is, up to three times. A change that does
64
+ * not move the revision (a handler's, `applyEdits`', raw SQL) is not seen.
65
+ * Without `revision`, none is, and `validate` warns. An input that expects a
66
+ * revision the row read is not at is a `Conflict`, decided before any rule;
67
+ * an input may expect only the field the writer pins.
68
+ *
59
69
  * ```ts
60
70
  * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
61
71
  * ```
62
72
  */
63
73
  writer: <E extends AnyEntity, User, R, RW>(entity: E, policy: Policy<User, R>, writer: EntityWriter<Option.Option<User>, RW>, options?: {
64
74
  readonly presets?: { readonly [K in keyof E['fields']]?: (user: User) => E['fields'][K]['schema']['Type']; };
75
+ readonly revision?: keyof E['fields'] & string;
65
76
  }) => EntityWriter<Option.Option<User>, R | RW>;
66
77
  /**
67
78
  * A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";;;;;;qBAyCa;;;;;;;;;;EAUX,KAAK,MAAM,GAAC,QACF,UAAQ,QACR,OAAO,MAAM,OACpB,aAAa,OAAO,OAAO,OAAO;;;;;;;;;;EA6CrC,SAAS,MAAM,GAAC,QAAU,WAAS,QAAU,OAAO,MAAM,QAAE,WAG3C,OAAO,OAAO,OAAK,8BAE7B,OAAO,OAAO,iBAAiB;;;;;;;EAoEtC,SAAS,MAAI,QAAU,OAAO,OAAK,UAAY,cAAc;IAC3D,WAAQ,WAEO,OAAO,OAAO,OAAK,MACxB,gBAAgB,eAAe,OAAO,OAAO,SAAS,8BAC3D,OAAO,OAAO;IAuCnB;OAjHY,aAAA,WAAA,OAAA,OAAA,OAAA,8BAAiB,OAAA,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;EA6I/B,SAAS,UAAU,WAAW,MAAM,GAAG,IAAE,QAC/B,GAAC,QACD,OAAO,MAAM,IAAE,QACf,aAAa,OAAO,OAAO,OAAO,KAAG;aAElC,sBACG,WAAW,gBAAgB,MAAM,SAAS,YAAY;QAGnE,aAAa,OAAO,OAAO,OAAO,IAAI;;;;;;;;;;;;;;;;;;;;;EA8OzC,WAAW,MAAM,GAAG,IAAI,IAAI,qBAAqB,OAAO,QAAQ,SAAO,UAC3D,mBAAmB,MAAM,OAAO,QAAQ,UAAQ;aAE/C,QAAQ;aACR,QAAQ,OAAO,MAAM;aACrB,8CAA8C;;;;;;aAM9C,OAAO,OAAO,mBAAmB,OAAO;;aAExC,QAAQ,aAAa,OAAO,OAAO,OAAO;;aAE1C,SAAS;KACnB,MACK;aACK,OAAO;aACP,WAAW,OAAO,OAAO;aACzB;aACA,KAAK,OAAO,OAAO,SAAS;QACjC,OAAO,OACX,gBAAgB,SAChB,oBAAoB,kBAAkB,iBACtC,QAED,e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S;KACnB,MACK;aACK,OAAO;aACP,WAAW,OAAO,OAAO;aACzB;aACA,KAAK,OAAO,OAAO,SAAS;QACjC,OAAO,OACX,gBAAgB,SAChB,oBAAoB,kBAAkB,iBACtC,QAED,eAAe,OAAO,OAAO,OAAO,IAAI,KAAK;;;;;;;;;;;;;;;;;;EA6FhD,WAAW,MAAM,GAAC,QACR,OAAO,MAAM,IAAE;aAEZ,UAAU,cAAc;;aAExB;eACE;iBACE,SAAS;mBAEL;mBAA0B,OAAO;;;;aAIzC,QAAQ"}
package/dist/server.mjs CHANGED
@@ -2,9 +2,9 @@ import { o as readRowsRuled, r as attached, s as readRuled } from "./attach-BZyV
2
2
  import { t as Condition } from "./condition-Dunujvzy.mjs";
3
3
  import "./me-DeSZOGt3.mjs";
4
4
  import { n as rowRules, r as writeRules, t as memberRules } from "./placed-CkyMqxFw.mjs";
5
- import { Effect, Match, Option, Schema } from "effect";
6
- import { Query } from "foldkit-entity";
7
- import { RemoteServer, RemoteServerError } from "foldkit-remote-server";
5
+ import { Effect, Match, Option, Schema, SchemaAST } from "effect";
6
+ import { Entity, Query } from "foldkit-entity";
7
+ import { RemoteInvalid, RemoteServer, RemoteServerError } from "foldkit-remote-server";
8
8
  //#region src/server.ts
9
9
  /**
10
10
  * A guard set's read rules as `foldkit-remote-server`'s seams: an
@@ -14,6 +14,12 @@ import { RemoteServer, RemoteServerError } from "foldkit-remote-server";
14
14
  * brings the server along.
15
15
  */
16
16
  const noMembers = (record) => record;
17
+ /** Two stored values, which are JSON: equal when they encode the same. */
18
+ const sameStored = (left, right) => JSON.stringify(left) === JSON.stringify(right);
19
+ /** The members of `fields` that have a Read rule, once each. */
20
+ const hiddenOf = (attachment, fields) => [...new Set(fields.map((field) => field.key).filter((key) => readRuled(attachment, key)))];
21
+ /** Each guarded writer's `revision`, or none: one a change can fall between check and write of. */
22
+ const pins = /* @__PURE__ */ new WeakMap();
17
23
  /** A ref key's two halves, `Entity:id`; `none` for anything else. */
18
24
  const refOf = (value) => {
19
25
  if (typeof value !== "string") return Option.none();
@@ -153,11 +159,27 @@ const GuardServer = {
153
159
  * from, and a create whose input sets a preset field is a mistake of the
154
160
  * server's, refused.
155
161
  *
162
+ * `revision` names a field stored as a number, which the writer moves on by
163
+ * one with each write it lands. An update or a delete then lands only on the
164
+ * revision its rules were decided over (the writer's `expect`), so a change
165
+ * between the check and the write is never written over; it is decided
166
+ * again against the row as it now is, up to three times. A change that does
167
+ * not move the revision (a handler's, `applyEdits`', raw SQL) is not seen.
168
+ * Without `revision`, none is, and `validate` warns. An input that expects a
169
+ * revision the row read is not at is a `Conflict`, decided before any rule;
170
+ * an input may expect only the field the writer pins.
171
+ *
156
172
  * ```ts
157
173
  * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
158
174
  * ```
159
175
  */
160
176
  writer: (entity, policy, writer, options = {}) => {
177
+ const revision = options.revision;
178
+ if (revision !== void 0) {
179
+ const field = Object.hasOwn(entity.fields, revision) ? entity.fields[revision] : void 0;
180
+ if (field === void 0) throw new Error(`[foldkit-guard] GuardServer.writer: ${entity.name} has no field "${revision}" for its revision`);
181
+ if (!SchemaAST.isNumber(Schema.toEncoded(field.schema).ast)) throw new Error(`[foldkit-guard] GuardServer.writer: ${entity.name}'s revision "${revision}" is not stored as a number`);
182
+ }
161
183
  const presets = Object.entries(options.presets ?? {}).map(([field, preset]) => {
162
184
  const declared = Object.hasOwn(entity.fields, field) ? entity.fields[field] : void 0;
163
185
  if (declared === void 0) throw new Error(`[foldkit-guard] GuardServer.writer: ${entity.name} has no field "${field}" to preset`);
@@ -204,59 +226,154 @@ const GuardServer = {
204
226
  ...more,
205
227
  ...rules.flatMap(({ condition }) => Condition.members(condition))
206
228
  ])];
229
+ /** The fields that say which version of the row was read: the revision, and the input's. */
230
+ const versionFields = (expect) => [...revision === void 0 ? [] : [revision], ...Option.match(expect, {
231
+ onNone: () => [],
232
+ onSome: ({ field }) => [field]
233
+ })];
234
+ /** Whether the row read is not at the revision the input expects. */
235
+ const moved = (expect, before) => Option.exists(expect, ({ field, revision }) => !sameStored(before[field], revision));
236
+ /** The write held to the row its rules were decided over, where there is a revision. */
237
+ const pin = (expect, before) => revision === void 0 ? expect : Option.some({
238
+ field: revision,
239
+ revision: before[revision]
240
+ });
241
+ /**
242
+ * `attempt` run again while its pinned write misses: the row moved after it
243
+ * was read, so it is decided again over the row as it now is. A write the
244
+ * input pinned misses as a conflict, and is not run again.
245
+ */
246
+ const pinned = (id, expect, missed, attempt) => {
247
+ if (revision === void 0) return attempt();
248
+ if (Option.isSome(expect)) return expect.value.field === revision ? attempt() : Effect.fail(new RemoteServerError({ message: `${entity.name}'s input expects "${expect.value.field}", but its writer pins "${revision}"` }));
249
+ const loop = (left) => Effect.flatMap(attempt(), (outcome) => !missed(outcome) ? Effect.succeed(outcome) : left > 1 ? loop(left - 1) : Effect.fail(new RemoteServerError({ message: `${entity.name} ${id} changed while it was written` })));
250
+ return loop(3);
251
+ };
252
+ const attachment = attached(entity);
253
+ const hiddenByBody = /* @__PURE__ */ new WeakMap();
254
+ const unnamed = new Set(Option.match(attachment, {
255
+ onNone: () => [],
256
+ onSome: (ruled) => Entity.invariants(entity).filter((held) => [...held.before, ...held.after].some((key) => readRuled(ruled, key))).map((held) => held.id)
257
+ }));
258
+ const told = (error) => error instanceof RemoteInvalid && Option.exists(error.rule, (rule) => unnamed.has(rule)) ? RemoteServer.invalid("The row would be invalid") : error;
259
+ /**
260
+ * Fails a write whose `when` reads, or whose `expect` names, a member with
261
+ * a Read rule: Unmet or written, Conflict or not, would answer for it.
262
+ * `validate` refuses the same at startup; this holds where it was not run.
263
+ */
264
+ const discloses = (expect, when) => Option.match(attachment, {
265
+ onNone: () => Effect.void,
266
+ onSome: (ruled) => {
267
+ const read = Option.match(when, {
268
+ onNone: () => [],
269
+ onSome: ({ body }) => {
270
+ const known = hiddenByBody.get(body);
271
+ if (known !== void 0) return known;
272
+ const hidden = hiddenOf(ruled, Query.dependencies(body).predicate);
273
+ hiddenByBody.set(body, hidden);
274
+ return hidden;
275
+ }
276
+ });
277
+ const expected = Option.match(expect, {
278
+ onNone: () => [],
279
+ onSome: ({ field }) => readRuled(ruled, field) ? [field] : []
280
+ });
281
+ const hidden = [.../* @__PURE__ */ new Set([...read, ...expected])];
282
+ return hidden.length === 0 ? Effect.void : Effect.fail(new RemoteServerError({ message: `${entity.name}'s write reads ${hidden.join(", ")}, which a Read rule hides from its writer` }));
283
+ }
284
+ });
285
+ /**
286
+ * The answer the writer's ledger holds for this operation, or else `write`:
287
+ * a retry of a write that landed is answered as it landed, not decided
288
+ * again over a row that may have moved since.
289
+ */
290
+ const answeredOr = (context, write) => {
291
+ const recorded = writer.recorded;
292
+ if (recorded === void 0 || Option.isNone(context.operation)) return write();
293
+ return Effect.flatMap(recorded({
294
+ operation: context.operation.value,
295
+ id: context.id,
296
+ principal: context.principal
297
+ }), Option.match({
298
+ onSome: (answer) => Effect.succeed(Option.some(answer)),
299
+ onNone: write
300
+ }));
301
+ };
207
302
  const memberRead = GuardServer.filter(entity, policy);
303
+ /** Refused before any rule, for what the write declares rather than what the row holds. */
304
+ const admitUpdate = (context) => Effect.andThen(discloses(context.expect, context.when), () => Object.keys(context.increments).length > 0 && Option.isNone(context.expect) && revision === void 0 ? Effect.fail(new RemoteServerError({ message: `${entity.name}'s increment expects no revision and its writer pins none, so its rules would judge a sum over a row that may move; give the writer a revision` })) : Effect.void);
305
+ /** The rules an update must meet: the row's, each member it sets, each relation it points. */
306
+ const updateRules = (context) => Effect.gen(function* () {
307
+ return {
308
+ row: yield* policy.writable(entity, context.principal, "Update"),
309
+ members: yield* policy.writeMembers(entity, context.principal, [...Object.keys(context.values), ...Object.keys(context.increments)], "Update"),
310
+ relating: yield* linkRules(context.principal, context.links)
311
+ };
312
+ });
313
+ /** The row as its writer may see it, with every field the rules and the version read. */
314
+ const readBefore = (context, rules) => read({
315
+ id: context.id,
316
+ fields: fieldsOf([
317
+ rules.row,
318
+ ...rules.members,
319
+ ...ruleOf(rules.relating)
320
+ ], [...Object.keys(context.links), ...versionFields(context.expect)]),
321
+ principal: context.principal
322
+ });
323
+ /** The rules, over the row as it is and as the write would leave it. */
324
+ const decideUpdate = (context, rules, before) => Effect.gen(function* () {
325
+ const { principal, values, increments, links } = context;
326
+ const linked = Object.keys(links);
327
+ const stored = writer.linked === void 0 || linked.length === 0 ? Option.none() : yield* writer.linked({
328
+ id: context.id,
329
+ relations: linked
330
+ });
331
+ const relations = linking(rules.relating, Option.some(Option.match(stored, {
332
+ onNone: () => ({
333
+ links: before,
334
+ exact: false
335
+ }),
336
+ onSome: (links) => ({
337
+ links,
338
+ exact: true
339
+ })
340
+ })));
341
+ const after = {
342
+ ...before,
343
+ ...values,
344
+ ...Object.fromEntries(Object.entries(increments).map(([field, amount]) => [field, Number(before[field]) + amount])),
345
+ ...Object.fromEntries(Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]))
346
+ };
347
+ yield* require([
348
+ rules.row,
349
+ ...rules.members,
350
+ ...relations
351
+ ], before, principal);
352
+ yield* require([rules.row], after, principal);
353
+ });
208
354
  const guarded = {
209
355
  entity: writer.entity,
356
+ ...writer.preconditions === true ? { preconditions: true } : {},
357
+ ...writer.increments === true ? { increments: true } : {},
358
+ ...writer.ledger === true ? { ledger: true } : {},
359
+ ...writer.invariants === true ? { invariants: true } : {},
360
+ ...writer.recorded === void 0 ? {} : { recorded: writer.recorded },
210
361
  read: ({ id, fields, principal }) => seenRow({ filter: memberRead }, (seen) => read({
211
362
  id,
212
363
  fields: seen,
213
364
  principal
214
365
  }), principal, fields, id),
215
- update: (context) => Effect.gen(function* () {
216
- const { principal, values, links } = context;
217
- const row = yield* policy.writable(entity, principal, "Update");
218
- const members = yield* policy.writeMembers(entity, principal, Object.keys(values), "Update");
219
- const relating = yield* linkRules(principal, links);
220
- const fields = fieldsOf([
221
- row,
222
- ...members,
223
- ...ruleOf(relating)
224
- ], Object.keys(links));
225
- const current = yield* read({
226
- id: context.id,
227
- fields,
228
- principal
229
- });
230
- if (Option.isNone(current)) return yield* Effect.fail(refused(row.deny));
231
- const before = current.value;
232
- const linked = Object.keys(links);
233
- const stored = writer.linked === void 0 || linked.length === 0 ? Option.none() : yield* writer.linked({
234
- id: context.id,
235
- relations: linked
366
+ update: (context) => Effect.mapError(Effect.andThen(admitUpdate(context), () => answeredOr(context, () => pinned(context.id, context.expect, Option.isNone, () => Effect.gen(function* () {
367
+ const rules = yield* updateRules(context);
368
+ const current = yield* readBefore(context, rules);
369
+ if (Option.isNone(current)) return yield* Effect.fail(refused(rules.row.deny));
370
+ if (moved(context.expect, current.value)) return Option.none();
371
+ yield* decideUpdate(context, rules, current.value);
372
+ return yield* writer.update({
373
+ ...context,
374
+ expect: pin(context.expect, current.value)
236
375
  });
237
- const relations = linking(relating, Option.some(Option.match(stored, {
238
- onNone: () => ({
239
- links: before,
240
- exact: false
241
- }),
242
- onSome: (links) => ({
243
- links,
244
- exact: true
245
- })
246
- })));
247
- const after = {
248
- ...before,
249
- ...values,
250
- ...Object.fromEntries(Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]))
251
- };
252
- yield* require([
253
- row,
254
- ...members,
255
- ...relations
256
- ], before, principal);
257
- yield* require([row], after, principal);
258
- return yield* writer.update(context);
259
- }),
376
+ })))), told),
260
377
  insert: (given) => Effect.gen(function* () {
261
378
  const preset = presets.find(({ field }) => Object.hasOwn(given.values, field));
262
379
  if (preset !== void 0) return yield* new RemoteServerError({ message: `${entity.name}'s "${preset.field}" is preset by the server; the input may not set it` });
@@ -291,20 +408,25 @@ const GuardServer = {
291
408
  ...rule,
292
409
  condition: Condition.unsetting(rule.condition, unset)
293
410
  })), proposed, principal);
294
- return yield* writer.insert(context);
411
+ return yield* Effect.mapError(writer.insert(context), told);
295
412
  }),
296
- delete: (context) => Effect.gen(function* () {
413
+ delete: (context) => Effect.andThen(discloses(context.expect, context.when), () => pinned(context.id, context.expect, (outcome) => outcome === "moved", () => Effect.gen(function* () {
297
414
  const row = yield* policy.writable(entity, context.principal, "Delete");
298
415
  const current = yield* read({
299
416
  id: context.id,
300
- fields: fieldsOf([row], []),
417
+ fields: fieldsOf([row], versionFields(context.expect)),
301
418
  principal: context.principal
302
419
  });
303
420
  if (Option.isNone(current)) return "absent";
421
+ if (moved(context.expect, current.value)) return "moved";
304
422
  yield* require([row], current.value, context.principal);
305
- return yield* writer.delete(context);
306
- })
423
+ return yield* writer.delete({
424
+ ...context,
425
+ expect: pin(context.expect, current.value)
426
+ });
427
+ })))
307
428
  };
429
+ pins.set(guarded, Option.fromUndefinedOr(revision));
308
430
  return writeRules.add(guarded, policy, [entity]);
309
431
  },
310
432
  /**
@@ -414,10 +536,24 @@ const GuardServer = {
414
536
  const bodyProblems = [...config.domain.registry.queries].flatMap(([queryName, { body }]) => {
415
537
  if (body === void 0 || body.entity.name !== name) return [];
416
538
  const { predicate, order } = Query.dependencies(body);
417
- const hidden = (fields) => [...new Set(fields.map((field) => field.key).filter((key) => readRuled(attachment, key)))];
418
- return [...hidden(predicate).map((member) => `query ${queryName} filters ${name} by ${member}, which has a Read rule`), ...hidden(order).map((member) => `query ${queryName} orders ${name} by ${member}, which has a Read rule`)];
539
+ return [...hiddenOf(attachment, predicate).map((member) => `query ${queryName} filters ${name} by ${member}, which has a Read rule`), ...hiddenOf(attachment, order).map((member) => `query ${queryName} orders ${name} by ${member}, which has a Read rule`)];
540
+ });
541
+ const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) => {
542
+ if (source.writes === void 0 || source.writes.entity !== name) return [];
543
+ if (!writeRules.has(source.writes.writer, policy, entity)) return [`write ${mutation} writes ${name} without its write rules`];
544
+ const { write, writer } = source.writes;
545
+ const when = Option.match(write.when, {
546
+ onNone: () => [],
547
+ onSome: (body) => hiddenOf(attachment, Query.dependencies(body).predicate)
548
+ });
549
+ const expected = write.expect?.field.key;
550
+ const pin = typeof writer === "object" && writer !== null ? pins.get(writer) : void 0;
551
+ return [
552
+ ...when.map((member) => `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`),
553
+ ...expected !== void 0 && readRuled(attachment, expected) ? [`write ${mutation} expects ${name}'s ${expected}, which has a Read rule`] : [],
554
+ ...expected !== void 0 && pin !== void 0 && Option.exists(pin, (field) => field !== expected) ? [`write ${mutation} expects ${name}'s ${expected}, but its writer pins ${Option.getOrThrow(pin)}`] : []
555
+ ];
419
556
  });
420
- const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) => source.writes !== void 0 && source.writes.entity === name && !writeRules.has(source.writes.writer, policy, entity) ? [`write ${mutation} writes ${name} without its write rules`] : []);
421
557
  const shared = Option.match(source, {
422
558
  onNone: () => [],
423
559
  onSome: (source) => [...source.shared ?? []]
@@ -442,6 +578,12 @@ const GuardServer = {
442
578
  }));
443
579
  const problems = [...undeclared, ...entityProblems];
444
580
  if (problems.length > 0) throw new Error(`[foldkit-guard] GuardServer.validate: ${problems.join("; ")}`);
581
+ const unpinnedWrites = [...config.server.mutations].flatMap(([mutation, source]) => {
582
+ const writer = source.writes?.writer;
583
+ const pin = typeof writer === "object" && writer !== null ? pins.get(writer) : void 0;
584
+ return pin !== void 0 && Option.isNone(pin) ? [mutation] : [];
585
+ });
586
+ if (unpinnedWrites.length > 0) console.warn(`[foldkit-guard] GuardServer.validate: ${unpinnedWrites.join(", ")} ${unpinnedWrites.length === 1 ? "writes" : "write"} through a GuardServer.writer with no revision, so a change between its check and its write is not seen; pass { revision }`);
445
587
  }
446
588
  };
447
589
  /** Whether a read asks for `may`, of an Entity that has it (`Guards.may`). */
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","names":[],"sources":["../src/server.ts"],"sourcesContent":["/**\n * A guard set's read rules as `foldkit-remote-server`'s seams: an\n * `EntitySource.filter` from each member's Read rule, and `RemoteServer.memory`'s\n * `readable` and `filter` from the row's, and a check at startup that a server\n * applies them. A subpath, so the shared declaration the browser imports never\n * brings the server along.\n */\nimport { Effect, Match, Option, Schema } from 'effect'\nimport { Query, type AnyEntity, type AnyQuery } from 'foldkit-entity'\nimport type { MutationDescriptor, RemoteForbidden } from 'foldkit-remote'\nimport {\n RemoteServer,\n RemoteServerError,\n type EntityRecord,\n type EntitySource,\n type EntityWriter,\n type MutationOutcome,\n type MutationRefused,\n type MutationSource,\n type MemoryReadable,\n type ReadPlan,\n type ServerDefinition,\n} from 'foldkit-remote-server'\nimport { attached, readRowsRuled, readRuled, type Deny, type InteractionKey } from './attach.js'\nimport { Condition, type RowRule } from './condition.js'\nimport type { Policy } from './index.js'\nimport type { MayAnswer } from './may.js'\nimport { ME, type MeEntity } from './me.js'\nimport { memberRules, rowRules, writeRules } from './placed.js'\n\nconst noMembers = (record: EntityRecord) => record\n\n/** A ref key's two halves, `Entity:id`; `none` for anything else. */\nconst refOf = (value: unknown): Option.Option<{ readonly entity: string; readonly id: string }> => {\n if (typeof value !== 'string') return Option.none()\n const split = value.indexOf(':')\n return split <= 0\n ? Option.none()\n : Option.some({ entity: value.slice(0, split), id: value.slice(split + 1) })\n}\n\nexport const GuardServer = {\n /**\n * `Guards.me`'s Source: the one row, `me`, as the asker is, with `may`\n * answered by `policy`. `signedIn` is whether the server answered as\n * someone; `key` is their `key`. Any other id is no row.\n *\n * ```ts\n * RemoteServer.make({ entities: [GuardServer.me(Me, Policy), …] })\n * ```\n */\n me: <User, R>(\n entity: MeEntity,\n policy: Policy<User, R>,\n ): EntitySource<Option.Option<User>, R> => {\n // Otherwise every read would die deciding another set's guards.\n Option.map(attached(entity), ({ set }) => {\n if (set !== policy.set) {\n throw new Error(\n `[foldkit-guard] GuardServer.me: Me carries the guards of ${set}, not ${policy.set}`,\n )\n }\n })\n return {\n ...RemoteServer.entity<Option.Option<User>, R>(entity, {\n read: ({ ids, principal }) =>\n Effect.succeed(\n ids\n .filter(id => id === ME)\n .map(id => ({\n id,\n values: {\n signedIn: Option.isSome(principal),\n // Encoded, as a Source answers: `null` for a visitor.\n key: Option.match(principal, {\n onNone: () => null,\n onSome: policy.key,\n }),\n },\n })),\n ),\n filter: GuardServer.filter(entity, policy),\n }),\n // Its Read rule as this Source applies it: only the asker's own row,\n // which `Guards.me` lets anyone read. One per call: the registry is keyed\n // by it, and another call is for another Policy.\n visible: rowRules.add(Object.freeze({ reads: 'the asker’s own row' }), policy, [entity]),\n }\n },\n\n /**\n * An `EntitySource.filter` for `entity`: each requested member with a Read\n * rule is decided per record, omitted or redacted where the rule refuses.\n * The fields a rule reads are read too, so it can be decided.\n *\n * ```ts\n * RemoteServer.entity(Todo, { read, filter: GuardServer.filter(Todo, Policy) })\n * ```\n */\n filter: <User, R>(entity: AnyEntity, policy: Policy<User, R>) =>\n memberRules.add(\n (\n principal: Option.Option<User>,\n fields: readonly string[],\n ): Effect.Effect<ReadPlan, never, R> =>\n Effect.map(\n Effect.all([\n policy.readMembers(entity, principal, fields),\n // `may` is answered here, where the row is read as its principal sees it.\n asksMay(entity, fields)\n ? Effect.map(mayOf(entity, policy, principal), Option.some)\n : Effect.succeed(Option.none<MayPlan>()),\n ]),\n ([members, may]): ReadPlan => {\n if (members.length === 0 && Option.isNone(may)) return { fields, apply: noMembers }\n const input = policy.inputOf(principal)\n const decided = members.map(member => ({\n ...member,\n // A redacted value is a decoded one; the record holds what the store holds.\n redacted:\n member.deny._tag === 'Redact'\n ? Option.some(\n Schema.encodeSync(\n (\n entity.members as Readonly<\n Record<string, { readonly schema: Schema.Top }>\n >\n )[member.member]!.schema as unknown as Schema.Codec<unknown, unknown>,\n )(member.deny.value),\n )\n : Option.none(),\n }))\n return {\n fields: [\n ...new Set([\n ...fields,\n ...members.flatMap(({ condition }) => Condition.members(condition)),\n ...Option.match(may, { onNone: () => [], onSome: ({ fields }) => fields }),\n ]),\n ],\n apply: record => {\n const values: Record<string, unknown> = { ...record.values }\n for (const { member, condition, redacted } of decided) {\n // Member rules carry no inherited Read: only a row's Read may inherit.\n if (Condition.holds(condition, record.values, input, () => false)) continue\n Option.match(redacted, {\n onNone: () => {\n delete values[member]\n },\n onSome: value => {\n values[member] = value\n },\n })\n }\n Option.map(may, ({ answer }) => {\n values.may = answer(record.values)\n })\n return { id: record.id, values }\n },\n }\n },\n ),\n policy,\n [entity],\n ),\n\n /**\n * `RemoteServer.memory`'s `readable` and `filter` for `entities`, the\n * Entities as `Guards.attach` returned them. A row's Read is decided per\n * stored row, an inherited Read by looking the related row up; an Entity\n * not listed is read by everyone.\n */\n memory: <User>(policy: Policy<User>, entities: ReadonlyArray<AnyEntity>) => ({\n readable: rowRules.add(\n (\n principal: Option.Option<User>,\n row: (entity: string, id: string) => Option.Option<Readonly<Record<string, unknown>>>,\n ): Effect.Effect<MemoryReadable> =>\n Effect.map(\n Effect.forEach(entities, entity =>\n Effect.map(\n policy.readable(entity, principal),\n condition => [entity.name, condition] as const,\n ),\n ),\n (decided): MemoryReadable => {\n const conditions = new Map(decided)\n const input = policy.inputOf(principal)\n // `seen` stops a cycle of inherited Reads, which would otherwise never end.\n const holds = (\n entity: string,\n values: Readonly<Record<string, unknown>>,\n seen: ReadonlySet<string>,\n ): boolean => {\n const condition = conditions.get(entity)\n if (condition === undefined) return true\n return Condition.holds(condition, values, input, relation =>\n Option.match(refOf(values[relation]), {\n onNone: () => false,\n onSome: ref => {\n const key = `${ref.entity}:${ref.id}`\n if (seen.has(key)) return false\n return Option.match(row(ref.entity, ref.id), {\n onNone: () => false,\n onSome: target => holds(ref.entity, target, new Set([...seen, key])),\n })\n },\n }),\n )\n }\n return (entity, values) => holds(entity, values, new Set())\n },\n ),\n policy,\n entities,\n ),\n filter: Object.fromEntries(\n entities.map(entity => [entity.name, GuardServer.filter(entity, policy)] as const),\n ),\n }),\n\n /**\n * `writer` with `entity`'s write rules checked before each write lands, for\n * `RemoteServer.write`. An update or a delete reads the row first under\n * the writer's own `read` (its Source's read rule): a row the writer may not\n * see is refused as one that is not there, and a delete of it changes\n * nothing. Then the row's rule for the command must hold over the row (an\n * update's over the row as it would be after it too, so a write cannot move\n * a row out of its writer's reach), each member it sets must allow setting\n * it, and each relation it points elsewhere must allow the unlink and the\n * link. A create's rules hold over the values it proposes, where a field the\n * create leaves unset matches no guard, not even one for an empty value. A refusal is\n * `Forbidden`, with the sentence an `explain` gave; the write never runs.\n *\n * `presets` are fields a create takes from who is asking, never from the\n * client (`ownerId: user => user.id`): set before the rules are checked, so\n * a rule over them holds of the creator. A visitor has nothing to preset\n * from, and a create whose input sets a preset field is a mistake of the\n * server's, refused.\n *\n * ```ts\n * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))\n * ```\n */\n writer: <E extends AnyEntity, User, R, RW>(\n entity: E,\n policy: Policy<User, R>,\n writer: EntityWriter<Option.Option<User>, RW>,\n options: {\n readonly presets?: {\n readonly [K in keyof E['fields']]?: (user: User) => E['fields'][K]['schema']['Type']\n }\n } = {},\n ): EntityWriter<Option.Option<User>, R | RW> => {\n const presets = Object.entries(options.presets ?? {}).map(([field, preset]) => {\n const declared = Object.hasOwn(entity.fields, field)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[field]\n : undefined\n if (declared === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${field}\" to preset`,\n )\n }\n const encode = Schema.encodeUnknownSync(\n declared.schema as unknown as Schema.Codec<unknown, unknown>,\n )\n return { field, value: (user: User) => encode((preset as (user: User) => unknown)(user)) }\n })\n if (writer.entity !== entity.name) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s rules over a writer for ${writer.entity}`,\n )\n }\n const read = writer.read\n if (read === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s writer reads no row as its writer may see it; bind it with a visible rule (GuardDrizzle.visible)`,\n )\n }\n const holds = (\n rule: { readonly condition: Condition },\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) => Condition.holds(rule.condition, values, policy.inputOf(principal), () => false)\n /** Fails with the first rule of `rules` that does not hold over `values`. */\n const require = (\n rules: ReadonlyArray<{ readonly condition: Condition; readonly deny: Deny }>,\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\n Option.match(Option.fromUndefinedOr(rules.find(rule => !holds(rule, values, principal))), {\n onNone: () => Effect.void,\n onSome: rule => Effect.fail(refused(rule.deny)),\n })\n type Links = Readonly<\n Record<string, Option.Option<{ readonly entity: string; readonly id: string }>>\n >\n /** Each relation `links` points: its rules for unlinking and for linking a row. */\n const linkRules = (principal: Option.Option<User>, links: Links) =>\n Effect.forEach(Object.entries(links), ([relation, target]) =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Unlink'),\n policy.linkable(entity, principal, relation, 'Link'),\n ]),\n ([unlink, link]) => ({ relation, now: linkKey(target), unlink, link }),\n ),\n )\n /**\n * The rules a change from what each relation was linked to, to what it now\n * points at, must meet; none `before` is a create, which unlinks nothing.\n * Where `exact` is false, `links` are the row as its writer sees it, where\n * a link to a row hidden from them reads as none: a relation seen unlinked\n * may be linked after all, so changing it unlinks too.\n */\n const linking = (\n rules: ReadonlyArray<{\n readonly relation: string\n readonly now: string | null\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n before: Option.Option<{\n readonly links: Readonly<Record<string, unknown>>\n readonly exact: boolean\n }>,\n ): ReadonlyArray<RowRule> =>\n rules.flatMap(({ relation, now, unlink, link }) =>\n Option.match(before, {\n onNone: () => (now === null ? [] : Option.toArray(link)),\n onSome: ({ links, exact }) => {\n const was = links[relation] ?? null\n if (was === now && (exact || was !== null)) return []\n return [\n ...(was === null && exact ? [] : Option.toArray(unlink)),\n ...(now === null ? [] : Option.toArray(link)),\n ]\n },\n }),\n )\n const ruleOf = (\n rules: ReadonlyArray<{\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n ) => rules.flatMap(({ unlink, link }) => [...Option.toArray(unlink), ...Option.toArray(link)])\n const fieldsOf = (\n rules: ReadonlyArray<{ readonly condition: Condition }>,\n more: Iterable<string>,\n ) => [\n ...new Set([\n 'id',\n ...more,\n ...rules.flatMap(({ condition }) => Condition.members(condition)),\n ]),\n ]\n // What an answer shows: the row as the writer may see it, members ruled.\n const memberRead = GuardServer.filter(entity, policy)\n const guarded: EntityWriter<Option.Option<User>, R | RW> = {\n entity: writer.entity,\n read: ({ id, fields, principal }) =>\n seenRow(\n { filter: memberRead },\n seen => read({ id, fields: seen, principal }),\n principal,\n fields,\n id,\n ),\n update: context =>\n Effect.gen(function* () {\n const { principal, values, links } = context\n const row = yield* policy.writable(entity, principal, 'Update')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n Object.keys(values),\n 'Update',\n )\n const relating = yield* linkRules(principal, links)\n const fields = fieldsOf([row, ...members, ...ruleOf(relating)], Object.keys(links))\n const current = yield* read({ id: context.id, fields, principal })\n if (Option.isNone(current)) return yield* Effect.fail(refused(row.deny))\n const before = current.value\n const linked = Object.keys(links)\n const stored =\n writer.linked === undefined || linked.length === 0\n ? Option.none()\n : yield* writer.linked({ id: context.id, relations: linked })\n const relations = linking(\n relating,\n Option.some(\n Option.match(stored, {\n onNone: () => ({ links: before, exact: false }),\n onSome: links => ({ links, exact: true }),\n }),\n ),\n )\n const after = {\n ...before,\n ...values,\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n yield* require([row, ...members, ...relations], before, principal)\n yield* require([row], after, principal)\n return yield* writer.update(context)\n }),\n insert: given =>\n Effect.gen(function* () {\n const preset = presets.find(({ field }) => Object.hasOwn(given.values, field))\n if (preset !== undefined) {\n return yield* new RemoteServerError({\n message: `${entity.name}'s \"${preset.field}\" is preset by the server; the input may not set it`,\n })\n }\n if (presets.length > 0 && Option.isNone(given.principal)) {\n return yield* Effect.fail(RemoteServer.forbid())\n }\n const context = Option.match(given.principal, {\n onNone: () => given,\n onSome: user => ({\n ...given,\n values: {\n ...given.values,\n ...Object.fromEntries(presets.map(({ field, value }) => [field, value(user)])),\n },\n }),\n })\n const { principal, values, links } = context\n const row = yield* policy.writable(entity, principal, 'Create')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n Object.keys(values),\n 'Create',\n )\n const relations = linking(yield* linkRules(principal, links), Option.none())\n const proposed = {\n ...values,\n id: context.id,\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n const rules = [row, ...members, ...relations]\n const ruled = rules.flatMap(({ condition }) => Condition.members(condition))\n const unset = new Set(ruled.filter(field => !Object.hasOwn(proposed, field)))\n yield* require(rules.map(rule => ({\n ...rule,\n condition: Condition.unsetting(rule.condition, unset),\n })), proposed, principal)\n return yield* writer.insert(context)\n }),\n delete: context =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Delete')\n const current = yield* read({\n id: context.id,\n fields: fieldsOf([row], []),\n principal: context.principal,\n })\n // Hidden or gone, the writer sees no row: there is nothing of theirs to delete.\n if (Option.isNone(current)) return 'absent' as const\n yield* require([row], current.value, context.principal)\n return yield* writer.delete(context)\n }),\n }\n return writeRules.add(guarded, policy, [entity])\n },\n\n /**\n * A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for\n * `interaction` checked before it runs. The row the input names (`id`) is\n * read through `source`, which must apply the Entity's Read rules, and the\n * rule must hold over it; a row its writer may not see is refused. With no\n * `id` (a create), the rule must hold of who is asking alone, a field it\n * reads matching no guard. `run` is given the row as read: its fields the\n * rule reads, its `id`, and `fields`. A refusal is `Forbidden`; `run` never\n * runs. What `run` writes is its own: check members it sets there. Each\n * row of `entity` its answer carries is read back through `source`, so the\n * answer shows its writer only what they may see, a row it hid from them\n * as deleted.\n *\n * ```ts\n * GuardServer.mutation(ArchiveTodo, {\n * entity: Todo, policy: Policy, interaction: Archive.key,\n * id: input => input.id, source: source(Db.Todo),\n * }, ({ input, row }) => …)\n * ```\n */\n mutation: <User, R, RS, RM, Name extends string, Input, Output, Refused>(\n mutation: MutationDescriptor<Name, Input, Output, Refused>,\n guard: {\n readonly entity: AnyEntity\n readonly policy: Policy<User, R>\n readonly interaction: 'Create' | 'Update' | 'Delete' | InteractionKey\n /**\n * The row the input acts on; none for a create. An input whose id may be\n * absent (`Option`, as one editor's for create and edit) creates when it\n * is, checked against `Create`.\n */\n readonly id?: ((input: Input) => string | Option.Option<string>) | undefined\n /** Reads the row as its writer may see it: the Entity's guarded Source. */\n readonly source: EntitySource<Option.Option<User>, RS>\n /** More of the row for `run`, beside what the rule reads. */\n readonly fields?: ReadonlyArray<string> | undefined\n },\n run: (context: {\n readonly input: Input\n readonly principal: Option.Option<User>\n readonly requestId: string\n readonly row: Option.Option<Readonly<Record<string, unknown>>>\n }) => Effect.Effect<\n MutationOutcome<Output>,\n RemoteServerError | MutationRefused | RemoteForbidden,\n RM\n >,\n ): MutationSource<Option.Option<User>, R | RS | RM> => {\n const { entity, policy, interaction, id, source } = guard\n if (!rowRules.has(source.visible, policy, entity)) {\n throw new Error(\n `[foldkit-guard] GuardServer.mutation: ${mutation.name}'s Source does not apply ${entity.name}'s Read rules`,\n )\n }\n /**\n * The answer as its writer may now see it: each row of `entity` it carries\n * read back through `source`, and one the handler hid from them deleted.\n */\n const shown = (outcome: MutationOutcome<Output>, principal: Option.Option<User>) =>\n Effect.map(\n Effect.forEach(outcome.entities ?? [], patch =>\n patch.entity !== entity.name\n ? Effect.succeed(Option.some(patch))\n : Effect.map(\n seenRow(\n source,\n fields =>\n Effect.map(rowOf(source, principal, fields, patch.id), Option.fromUndefinedOr),\n principal,\n Object.keys(patch.values),\n patch.id,\n ),\n Option.map(seen => ({ ...patch, values: seen })),\n ),\n ),\n read => ({\n ...outcome,\n entities: read.flatMap(Option.toArray),\n deleted: [\n ...(outcome.deleted ?? []),\n ...(outcome.entities ?? [])\n .filter((_, index) => Option.isNone(read[index]!))\n .map(({ entity, id }) => ({ entity, id })),\n ],\n }),\n )\n return RemoteServer.mutation<Option.Option<User>, R | RS | RM, Name, Input, Output, Refused>(\n mutation,\n context =>\n Effect.gen(function* () {\n const { principal } = context\n // `context.input` was decoded against the mutation's Input before this runs.\n const target = Option.flatMap(Option.fromUndefinedOr(id), of => {\n const named = of(context.input)\n return typeof named === 'string' ? Option.some(named) : named\n })\n const rule = yield* policy.writable(\n entity,\n principal,\n id !== undefined && Option.isNone(target) ? 'Create' : interaction,\n )\n const ruled = Condition.members(rule.condition)\n const input = policy.inputOf(principal)\n if (Option.isNone(target)) {\n const unset = Condition.unsetting(rule.condition, new Set(ruled))\n if (!Condition.holds(unset, {}, input, () => false)) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row: Option.none() }), principal)\n }\n const fields = [...new Set(['id', ...ruled, ...(guard.fields ?? [])])]\n const row = Option.fromUndefinedOr(yield* rowOf(source, principal, fields, target.value))\n if (\n Option.isNone(row) ||\n !Condition.holds(rule.condition, row.value, input, () => false)\n ) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row }), principal)\n }),\n )\n },\n\n /**\n * Checks, at startup, that `server` applies the guards of `entities`, the\n * Entities as `Guards.attach` returned them: each one's Source and each\n * query listing it apply its row's Read rules (`GuardDrizzle.visible`, or\n * `GuardServer.memory`), its Source applies its members' and relations'\n * (`GuardServer.filter`), and each declared write of it lands through\n * `GuardServer.writer`, all built from `policy`; and that no query's body\n * filters or orders by a member with a Read rule, which would answer for the\n * value it hides. A hand-written Source over a guarded Entity would serve\n * every row, and a bare writer would take every write; this throws instead,\n * naming each. A handler (`RemoteServer.mutation`) writes what its code\n * writes, which no check at startup can read.\n *\n * ```ts\n * GuardServer.validate(Policy, { entities: [Todo, Project], domain: Data, server: Server })\n * ```\n */\n validate: <User, R>(\n policy: Policy<User, R>,\n config: {\n readonly entities: ReadonlyArray<AnyEntity>\n /** The Remote domain the server answers, for which Entity each query lists. */\n readonly domain: {\n readonly registry: {\n readonly queries: ReadonlyMap<\n string,\n { readonly Result: unknown; readonly body?: AnyQuery | undefined }\n >\n }\n }\n readonly server: ServerDefinition<any, any>\n },\n ): void => {\n const byName = new Map(config.entities.map(entity => [entity.name, entity]))\n /** Whether who may read the rows of `entity` depends on who is asking. */\n const rowsRuled = (entity: AnyEntity | undefined) =>\n Option.exists(Option.flatMap(Option.fromUndefinedOr(entity), attached), attachment =>\n readRowsRuled(attachment),\n )\n // A query the domain does not declare lists an Entity no one can name.\n const undeclared = [...config.server.queries.keys()]\n .filter(query => !config.domain.registry.queries.has(query))\n .map(query => `query ${query} is served, but the domain does not declare it`)\n const entityProblems = config.entities.flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => {\n const name = entity.name\n if (attachment.set !== policy.set) {\n return [`${name} carries the guards of ${attachment.set}, not ${policy.set}`]\n }\n // Every guarded Entity's, whether or not it has rules there yet: a rule\n // attached later is then applied, not served past.\n const source = Option.fromUndefinedOr(config.server.entities.get(name))\n const sourceProblems = Option.match(source, {\n onNone: () => [],\n onSome: ({ visible, filter }) => [\n ...(rowRules.has(visible, policy, entity)\n ? []\n : [`${name}'s Source does not apply its Read rules`]),\n ...(memberRules.has(filter, policy, entity)\n ? []\n : [`${name}'s Source does not apply its members' Read rules`]),\n ],\n })\n const queryProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, query]) => {\n const listed = config.server.queries.get(queryName)\n return listed !== undefined &&\n lists(query.Result, name) &&\n !rowRules.has(listed.visible, policy, entity)\n ? [`query ${queryName} lists ${name} without its Read rules`]\n : []\n },\n )\n // A row the reader may see with a member it may not still answers a\n // filter or an order on that member: `cost < $max`, halved twenty\n // times, reads the cost the row came back without.\n const bodyProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, { body }]) => {\n if (body === undefined || body.entity.name !== name) return []\n const { predicate, order } = Query.dependencies(body)\n const hidden = (fields: typeof predicate) => [\n ...new Set(\n fields.map(field => field.key).filter(key => readRuled(attachment, key)),\n ),\n ]\n return [\n ...hidden(predicate).map(\n member =>\n `query ${queryName} filters ${name} by ${member}, which has a Read rule`,\n ),\n ...hidden(order).map(\n member => `query ${queryName} orders ${name} by ${member}, which has a Read rule`,\n ),\n ]\n },\n )\n const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) =>\n source.writes !== undefined &&\n source.writes.entity === name &&\n !writeRules.has(source.writes.writer, policy, entity)\n ? [`write ${mutation} writes ${name} without its write rules`]\n : [],\n )\n // A shared field goes to every live subscriber as written: no rule may tell them apart.\n const shared = Option.match(source, {\n onNone: () => [],\n onSome: source => [...(source.shared ?? [])],\n })\n const sharedProblems = [\n ...(shared.length > 0 && readRowsRuled(attachment)\n ? [`${name}'s Source shares ${shared.join(', ')}, but its rows have a Read rule`]\n : []),\n ...shared.flatMap(member => {\n const own = readRuled(attachment, member)\n ? [`${name}'s Source shares ${member}, which has a Read rule`]\n : []\n if (!Object.hasOwn(entity.relations, member)) return own\n const target = entity.relations[member]!.target().name\n if (!byName.has(target))\n return [\n ...own,\n `${name}'s Source shares ${member}, whose ${target} is not validated`,\n ]\n return rowsRuled(byName.get(target))\n ? [...own, `${name}'s Source shares ${member}, whose rows have a Read rule`]\n : own\n }),\n ]\n // A live Source of its own streams whatever it reads: nothing here can check it.\n const liveProblems = config.server.live.has(name)\n ? [`${name} has a live Source of its own; serve its changes through a live hub`]\n : []\n return [\n ...sourceProblems,\n ...queryProblems,\n ...bodyProblems,\n ...writeProblems,\n ...sharedProblems,\n ...liveProblems,\n ]\n },\n }),\n )\n const problems = [...undeclared, ...entityProblems]\n if (problems.length > 0) {\n throw new Error(`[foldkit-guard] GuardServer.validate: ${problems.join('; ')}`)\n }\n },\n}\n\n/** Whether a read asks for `may`, of an Entity that has it (`Guards.may`). */\nconst asksMay = (entity: AnyEntity, fields: ReadonlyArray<string>) =>\n fields.includes('may') && Object.hasOwn(entity.derived, 'may')\n\n/** How one principal's `may` is answered: the fields its rules read, and the answer over a row. */\ninterface MayPlan {\n readonly fields: ReadonlyArray<string>\n readonly answer: (values: Readonly<Record<string, unknown>>) => MayAnswer\n}\n\n/** The interactions a row answers `may` for: `Update`, `Delete`, and each one the set named. */\nconst builtInRow = new Set(['Read', 'Create', 'Update', 'Delete'])\n\n/**\n * `may` for `principal`: each row interaction's rule, each member's own\n * `Update`, each relation's `Link` and `Unlink`, decided once and held over\n * each row as a write's check would hold them over it as it is.\n */\nconst mayOf = <User, R>(\n entity: AnyEntity,\n policy: Policy<User, R>,\n principal: Option.Option<User>,\n): Effect.Effect<MayPlan, never, R> => {\n const attachment = attached(entity)\n const named = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ row }) => Object.keys(row).filter(interaction => !builtInRow.has(interaction)),\n })\n const ruledMembers = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ members }) => Object.keys(members),\n })\n const ruledRelations = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ relations }) => Object.keys(relations),\n })\n return Effect.map(\n Effect.all([\n Effect.forEach(['Update', 'Delete', ...named], interaction =>\n Effect.map(\n // A named one was attached as an `InteractionKey`; its key is the name.\n policy.writable(entity, principal, interaction as InteractionKey),\n rule => [interaction, rule] as const,\n ),\n ),\n policy.writeMembers(entity, principal, ruledMembers, 'Update'),\n Effect.forEach(ruledRelations, relation =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Link'),\n policy.linkable(entity, principal, relation, 'Unlink'),\n ]),\n ([link, unlink]) => ({ relation, link, unlink }),\n ),\n ),\n ]),\n ([rows, members, relations]): MayPlan => {\n const input = policy.inputOf(principal)\n const holds = (condition: Condition, values: Readonly<Record<string, unknown>>) =>\n Condition.holds(condition, values, input, () => false)\n // A relation without a rule for one direction leaves it to the row's Update.\n const allows = (rule: Option.Option<RowRule>, values: Readonly<Record<string, unknown>>) =>\n Option.match(rule, {\n onNone: () => true,\n onSome: ({ condition }) => holds(condition, values),\n })\n const conditions = [\n ...rows.map(([, { condition }]) => condition),\n ...members.map(({ condition }) => condition),\n ...relations.flatMap(({ link, unlink }) =>\n [...Option.toArray(link), ...Option.toArray(unlink)].map(({ condition }) => condition),\n ),\n ]\n return {\n // `id` too, so a row is read when its rules read none of it (an admin's).\n fields: ['id', ...new Set(conditions.flatMap(Condition.members))],\n answer: values => ({\n row: Object.fromEntries(\n rows.map(([interaction, { condition }]) => [interaction, holds(condition, values)]),\n ),\n // Only an `explain`'s sentence is for whoever asked.\n reasons: Object.fromEntries(\n rows.flatMap(([interaction, { condition, deny }]) =>\n holds(condition, values)\n ? []\n : Match.valueTags(deny, {\n Explain: ({ reason }) => [[interaction, reason] as const],\n Forbidden: () => [],\n NotFound: () => [],\n Omit: () => [],\n Redact: () => [],\n }),\n ),\n ),\n members: Object.fromEntries(\n members.map(({ member, condition }) => [member, holds(condition, values)]),\n ),\n relations: Object.fromEntries(\n relations.map(({ relation, link, unlink }) => [\n relation,\n { Link: allows(link, values), Unlink: allows(unlink, values) },\n ]),\n ),\n }),\n }\n },\n )\n}\n\n/** A refused write as the client receives it: the sentence an `explain` gave, or none. */\nconst refused = (deny: Deny) =>\n Match.valueTags(deny, {\n Explain: ({ reason }) => RemoteServer.forbid(reason),\n Forbidden: () => RemoteServer.forbid(),\n NotFound: () => RemoteServer.forbid(),\n Omit: () => RemoteServer.forbid(),\n Redact: () => RemoteServer.forbid(),\n })\n\n/** One row, by id, as `principal` may read it through `source`. */\nconst rowOf = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n) =>\n Effect.map(\n source.read({ ids: [id], fields: [...fields], principal }),\n records => records.find(record => record.id === id)?.values,\n )\n\n/**\n * Row `id` of `fields` as `principal` may see it, through `see`'s `authorize`\n * and `filter` as a Source applies them, and no more than was asked: what an\n * answer shows its writer. None when the row is not there to them.\n */\nconst seenRow = <P, R, RS>(\n see: Pick<EntitySource<P, RS>, 'authorize' | 'filter'>,\n read: (\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n): Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R | RS> =>\n Effect.gen(function* () {\n const allowed = see.authorize === undefined ? fields : see.authorize(principal, [...fields])\n const plan: ReadPlan =\n see.filter === undefined\n ? { fields: allowed, apply: noMembers }\n : yield* see.filter(principal, allowed)\n // The id too: a row asked for nothing else is still there or not.\n const row = yield* read([...new Set(['id', ...plan.fields])])\n return Option.map(row, values => {\n const shown = plan.apply({ id, values }).values\n return Object.fromEntries(\n allowed.filter(field => Object.hasOwn(shown, field)).map(field => [field, shown[field]]),\n )\n })\n })\n\n/** A link's value as a row holds it: the ref's key, or `null` for none. */\nconst linkKey = (link: Option.Option<{ readonly entity: string; readonly id: string }>) =>\n Option.match(link, { onNone: () => null, onSome: ref => `${ref.entity}:${ref.id}` })\n\n/** Whether a query's result is a connection over `entity`. */\nconst lists = (result: unknown, entity: string): boolean =>\n typeof result === 'object' && result !== null && 'entity' in result && result.entity === entity\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,MAAM,aAAa,WAAyB;;AAG5C,MAAM,SAAS,UAAoF;CACjG,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,KAAK;CAClD,MAAM,QAAQ,MAAM,QAAQ,GAAG;CAC/B,OAAO,SAAS,IACZ,OAAO,KAAK,IACZ,OAAO,KAAK;EAAE,QAAQ,MAAM,MAAM,GAAG,KAAK;EAAG,IAAI,MAAM,MAAM,QAAQ,CAAC;CAAE,CAAC;AAC/E;AAEA,MAAa,cAAc;;;;;;;;;;CAUzB,KACE,QACA,WACyC;EAEzC,OAAO,IAAI,SAAS,MAAM,IAAI,EAAE,UAAU;GACxC,IAAI,QAAQ,OAAO,KACjB,MAAM,IAAI,MACR,4DAA4D,IAAI,QAAQ,OAAO,KACjF;EAEJ,CAAC;EACD,OAAO;GACL,GAAG,aAAa,OAA+B,QAAQ;IACrD,OAAO,EAAE,KAAK,gBACZ,OAAO,QACL,IACG,QAAO,OAAM,OAAA,IAAS,CAAC,CACvB,KAAI,QAAO;KACV;KACA,QAAQ;MACN,UAAU,OAAO,OAAO,SAAS;MAEjC,KAAK,OAAO,MAAM,WAAW;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A,IACX;EAAE,QAAQ;EAAS,OAAO;CAAU,IACpC,OAAO,IAAI,OAAO,WAAW,OAAO;CAE1C,MAAM,MAAM,OAAO,KAAK,CAAC,mBAAG,IAAI,IAAI,CAAC,MAAM,GAAG,KAAK,MAAM,CAAC,CAAC,CAAC;CAC5D,OAAO,OAAO,IAAI,MAAK,WAAU;EAC/B,MAAM,QAAQ,KAAK,MAAM;GAAE;GAAI;EAAO,CAAC,CAAC,CAAC;EACzC,OAAO,OAAO,YACZ,QAAQ,QAAO,UAAS,OAAO,OAAO,OAAO,KAAK,CAAC,CAAC,CAAC,KAAI,UAAS,CAAC,OAAO,MAAM,MAAM,CAAC,CACzF;CACF,CAAC;AACH,CAAC;;AAGH,MAAM,WAAW,SACf,OAAO,MAAM,MAAM;CAAE,cAAc;CAAM,SAAQ,QAAO,GAAG,IAAI,OAAO,GAAG,IAAI;AAAK,CAAC;;AAGrF,MAAM,SAAS,QAAiB,WAC9B,OAAO,WAAW,YAAY,WAAW,QAAQ,YAAY,UAAU,OAAO,WAAW"}
1
+ {"version":3,"file":"server.mjs","names":[],"sources":["../src/server.ts"],"sourcesContent":["/**\n * A guard set's read rules as `foldkit-remote-server`'s seams: an\n * `EntitySource.filter` from each member's Read rule, and `RemoteServer.memory`'s\n * `readable` and `filter` from the row's, and a check at startup that a server\n * applies them. A subpath, so the shared declaration the browser imports never\n * brings the server along.\n */\nimport { Effect, Match, Option, Schema, SchemaAST } from 'effect'\nimport { Entity, Query, type AnyEntity, type AnyQuery } from 'foldkit-entity'\nimport type { MutationDescriptor, RemoteForbidden } from 'foldkit-remote'\nimport {\n RemoteInvalid,\n RemoteServer,\n RemoteServerError,\n type EntityRecord,\n type EntitySource,\n type EntityWriter,\n type MutationOutcome,\n type MutationRefused,\n type MutationSource,\n type MemoryReadable,\n type ReadPlan,\n type ServerDefinition,\n type WriteWhen,\n} from 'foldkit-remote-server'\nimport {\n attached,\n readRowsRuled,\n readRuled,\n type Attachment,\n type Deny,\n type InteractionKey,\n} from './attach.js'\nimport { Condition, type RowRule } from './condition.js'\nimport type { Policy } from './index.js'\nimport type { MayAnswer } from './may.js'\nimport { ME, type MeEntity } from './me.js'\nimport { memberRules, rowRules, writeRules } from './placed.js'\n\nconst noMembers = (record: EntityRecord) => record\n\n/** Two stored values, which are JSON: equal when they encode the same. */\nconst sameStored = (left: unknown, right: unknown): boolean =>\n JSON.stringify(left) === JSON.stringify(right)\n\n/** The members of `fields` that have a Read rule, once each. */\nconst hiddenOf = (\n attachment: Attachment,\n fields: ReadonlyArray<{ readonly key: string }>,\n): ReadonlyArray<string> => [\n ...new Set(fields.map(field => field.key).filter(key => readRuled(attachment, key))),\n]\n\n/** Each guarded writer's `revision`, or none: one a change can fall between check and write of. */\nconst pins = new WeakMap<object, Option.Option<string>>()\n\n/** A ref key's two halves, `Entity:id`; `none` for anything else. */\nconst refOf = (value: unknown): Option.Option<{ readonly entity: string; readonly id: string }> => {\n if (typeof value !== 'string') return Option.none()\n const split = value.indexOf(':')\n return split <= 0\n ? Option.none()\n : Option.some({ entity: value.slice(0, split), id: value.slice(split + 1) })\n}\n\nexport const GuardServer = {\n /**\n * `Guards.me`'s Source: the one row, `me`, as the asker is, with `may`\n * answered by `policy`. `signedIn` is whether the server answered as\n * someone; `key` is their `key`. Any other id is no row.\n *\n * ```ts\n * RemoteServer.make({ entities: [GuardServer.me(Me, Policy), …] })\n * ```\n */\n me: <User, R>(\n entity: MeEntity,\n policy: Policy<User, R>,\n ): EntitySource<Option.Option<User>, R> => {\n // Otherwise every read would die deciding another set's guards.\n Option.map(attached(entity), ({ set }) => {\n if (set !== policy.set) {\n throw new Error(\n `[foldkit-guard] GuardServer.me: Me carries the guards of ${set}, not ${policy.set}`,\n )\n }\n })\n return {\n ...RemoteServer.entity<Option.Option<User>, R>(entity, {\n read: ({ ids, principal }) =>\n Effect.succeed(\n ids\n .filter(id => id === ME)\n .map(id => ({\n id,\n values: {\n signedIn: Option.isSome(principal),\n // Encoded, as a Source answers: `null` for a visitor.\n key: Option.match(principal, {\n onNone: () => null,\n onSome: policy.key,\n }),\n },\n })),\n ),\n filter: GuardServer.filter(entity, policy),\n }),\n // Its Read rule as this Source applies it: only the asker's own row,\n // which `Guards.me` lets anyone read. One per call: the registry is keyed\n // by it, and another call is for another Policy.\n visible: rowRules.add(Object.freeze({ reads: 'the asker’s own row' }), policy, [entity]),\n }\n },\n\n /**\n * An `EntitySource.filter` for `entity`: each requested member with a Read\n * rule is decided per record, omitted or redacted where the rule refuses.\n * The fields a rule reads are read too, so it can be decided.\n *\n * ```ts\n * RemoteServer.entity(Todo, { read, filter: GuardServer.filter(Todo, Policy) })\n * ```\n */\n filter: <User, R>(entity: AnyEntity, policy: Policy<User, R>) =>\n memberRules.add(\n (\n principal: Option.Option<User>,\n fields: readonly string[],\n ): Effect.Effect<ReadPlan, never, R> =>\n Effect.map(\n Effect.all([\n policy.readMembers(entity, principal, fields),\n // `may` is answered here, where the row is read as its principal sees it.\n asksMay(entity, fields)\n ? Effect.map(mayOf(entity, policy, principal), Option.some)\n : Effect.succeed(Option.none<MayPlan>()),\n ]),\n ([members, may]): ReadPlan => {\n if (members.length === 0 && Option.isNone(may)) return { fields, apply: noMembers }\n const input = policy.inputOf(principal)\n const decided = members.map(member => ({\n ...member,\n // A redacted value is a decoded one; the record holds what the store holds.\n redacted:\n member.deny._tag === 'Redact'\n ? Option.some(\n Schema.encodeSync(\n (\n entity.members as Readonly<\n Record<string, { readonly schema: Schema.Top }>\n >\n )[member.member]!.schema as unknown as Schema.Codec<unknown, unknown>,\n )(member.deny.value),\n )\n : Option.none(),\n }))\n return {\n fields: [\n ...new Set([\n ...fields,\n ...members.flatMap(({ condition }) => Condition.members(condition)),\n ...Option.match(may, { onNone: () => [], onSome: ({ fields }) => fields }),\n ]),\n ],\n apply: record => {\n const values: Record<string, unknown> = { ...record.values }\n for (const { member, condition, redacted } of decided) {\n // Member rules carry no inherited Read: only a row's Read may inherit.\n if (Condition.holds(condition, record.values, input, () => false)) continue\n Option.match(redacted, {\n onNone: () => {\n delete values[member]\n },\n onSome: value => {\n values[member] = value\n },\n })\n }\n Option.map(may, ({ answer }) => {\n values.may = answer(record.values)\n })\n return { id: record.id, values }\n },\n }\n },\n ),\n policy,\n [entity],\n ),\n\n /**\n * `RemoteServer.memory`'s `readable` and `filter` for `entities`, the\n * Entities as `Guards.attach` returned them. A row's Read is decided per\n * stored row, an inherited Read by looking the related row up; an Entity\n * not listed is read by everyone.\n */\n memory: <User>(policy: Policy<User>, entities: ReadonlyArray<AnyEntity>) => ({\n readable: rowRules.add(\n (\n principal: Option.Option<User>,\n row: (entity: string, id: string) => Option.Option<Readonly<Record<string, unknown>>>,\n ): Effect.Effect<MemoryReadable> =>\n Effect.map(\n Effect.forEach(entities, entity =>\n Effect.map(\n policy.readable(entity, principal),\n condition => [entity.name, condition] as const,\n ),\n ),\n (decided): MemoryReadable => {\n const conditions = new Map(decided)\n const input = policy.inputOf(principal)\n // `seen` stops a cycle of inherited Reads, which would otherwise never end.\n const holds = (\n entity: string,\n values: Readonly<Record<string, unknown>>,\n seen: ReadonlySet<string>,\n ): boolean => {\n const condition = conditions.get(entity)\n if (condition === undefined) return true\n return Condition.holds(condition, values, input, relation =>\n Option.match(refOf(values[relation]), {\n onNone: () => false,\n onSome: ref => {\n const key = `${ref.entity}:${ref.id}`\n if (seen.has(key)) return false\n return Option.match(row(ref.entity, ref.id), {\n onNone: () => false,\n onSome: target => holds(ref.entity, target, new Set([...seen, key])),\n })\n },\n }),\n )\n }\n return (entity, values) => holds(entity, values, new Set())\n },\n ),\n policy,\n entities,\n ),\n filter: Object.fromEntries(\n entities.map(entity => [entity.name, GuardServer.filter(entity, policy)] as const),\n ),\n }),\n\n /**\n * `writer` with `entity`'s write rules checked before each write lands, for\n * `RemoteServer.write`. An update or a delete reads the row first under\n * the writer's own `read` (its Source's read rule): a row the writer may not\n * see is refused as one that is not there, and a delete of it changes\n * nothing. Then the row's rule for the command must hold over the row (an\n * update's over the row as it would be after it too, so a write cannot move\n * a row out of its writer's reach), each member it sets must allow setting\n * it, and each relation it points elsewhere must allow the unlink and the\n * link. A create's rules hold over the values it proposes, where a field the\n * create leaves unset matches no guard, not even one for an empty value. A refusal is\n * `Forbidden`, with the sentence an `explain` gave; the write never runs.\n *\n * `presets` are fields a create takes from who is asking, never from the\n * client (`ownerId: user => user.id`): set before the rules are checked, so\n * a rule over them holds of the creator. A visitor has nothing to preset\n * from, and a create whose input sets a preset field is a mistake of the\n * server's, refused.\n *\n * `revision` names a field stored as a number, which the writer moves on by\n * one with each write it lands. An update or a delete then lands only on the\n * revision its rules were decided over (the writer's `expect`), so a change\n * between the check and the write is never written over; it is decided\n * again against the row as it now is, up to three times. A change that does\n * not move the revision (a handler's, `applyEdits`', raw SQL) is not seen.\n * Without `revision`, none is, and `validate` warns. An input that expects a\n * revision the row read is not at is a `Conflict`, decided before any rule;\n * an input may expect only the field the writer pins.\n *\n * ```ts\n * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))\n * ```\n */\n writer: <E extends AnyEntity, User, R, RW>(\n entity: E,\n policy: Policy<User, R>,\n writer: EntityWriter<Option.Option<User>, RW>,\n options: {\n readonly presets?: {\n readonly [K in keyof E['fields']]?: (user: User) => E['fields'][K]['schema']['Type']\n }\n readonly revision?: keyof E['fields'] & string\n } = {},\n ): EntityWriter<Option.Option<User>, R | RW> => {\n const revision = options.revision\n if (revision !== undefined) {\n const field = Object.hasOwn(entity.fields, revision)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[revision]\n : undefined\n if (field === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${revision}\" for its revision`,\n )\n }\n // The writer moves it on by one in the statement it writes with, so it is stored as a number.\n if (!SchemaAST.isNumber(Schema.toEncoded(field.schema).ast)) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s revision \"${revision}\" is not stored as a number`,\n )\n }\n }\n const presets = Object.entries(options.presets ?? {}).map(([field, preset]) => {\n const declared = Object.hasOwn(entity.fields, field)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[field]\n : undefined\n if (declared === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${field}\" to preset`,\n )\n }\n const encode = Schema.encodeUnknownSync(\n declared.schema as unknown as Schema.Codec<unknown, unknown>,\n )\n return { field, value: (user: User) => encode((preset as (user: User) => unknown)(user)) }\n })\n if (writer.entity !== entity.name) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s rules over a writer for ${writer.entity}`,\n )\n }\n const read = writer.read\n if (read === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s writer reads no row as its writer may see it; bind it with a visible rule (GuardDrizzle.visible)`,\n )\n }\n const holds = (\n rule: { readonly condition: Condition },\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) => Condition.holds(rule.condition, values, policy.inputOf(principal), () => false)\n /** Fails with the first rule of `rules` that does not hold over `values`. */\n const require = (\n rules: ReadonlyArray<{ readonly condition: Condition; readonly deny: Deny }>,\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\n Option.match(Option.fromUndefinedOr(rules.find(rule => !holds(rule, values, principal))), {\n onNone: () => Effect.void,\n onSome: rule => Effect.fail(refused(rule.deny)),\n })\n type Links = Readonly<\n Record<string, Option.Option<{ readonly entity: string; readonly id: string }>>\n >\n /** Each relation `links` points: its rules for unlinking and for linking a row. */\n const linkRules = (principal: Option.Option<User>, links: Links) =>\n Effect.forEach(Object.entries(links), ([relation, target]) =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Unlink'),\n policy.linkable(entity, principal, relation, 'Link'),\n ]),\n ([unlink, link]) => ({ relation, now: linkKey(target), unlink, link }),\n ),\n )\n /**\n * The rules a change from what each relation was linked to, to what it now\n * points at, must meet; none `before` is a create, which unlinks nothing.\n * Where `exact` is false, `links` are the row as its writer sees it, where\n * a link to a row hidden from them reads as none: a relation seen unlinked\n * may be linked after all, so changing it unlinks too.\n */\n const linking = (\n rules: ReadonlyArray<{\n readonly relation: string\n readonly now: string | null\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n before: Option.Option<{\n readonly links: Readonly<Record<string, unknown>>\n readonly exact: boolean\n }>,\n ): ReadonlyArray<RowRule> =>\n rules.flatMap(({ relation, now, unlink, link }) =>\n Option.match(before, {\n onNone: () => (now === null ? [] : Option.toArray(link)),\n onSome: ({ links, exact }) => {\n const was = links[relation] ?? null\n if (was === now && (exact || was !== null)) return []\n return [\n ...(was === null && exact ? [] : Option.toArray(unlink)),\n ...(now === null ? [] : Option.toArray(link)),\n ]\n },\n }),\n )\n const ruleOf = (\n rules: ReadonlyArray<{\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n ) => rules.flatMap(({ unlink, link }) => [...Option.toArray(unlink), ...Option.toArray(link)])\n const fieldsOf = (\n rules: ReadonlyArray<{ readonly condition: Condition }>,\n more: Iterable<string>,\n ) => [\n ...new Set([\n 'id',\n ...more,\n ...rules.flatMap(({ condition }) => Condition.members(condition)),\n ]),\n ]\n type Expect = Option.Option<{ readonly field: string; readonly revision: unknown }>\n /** The fields that say which version of the row was read: the revision, and the input's. */\n const versionFields = (expect: Expect) => [\n ...(revision === undefined ? [] : [revision]),\n ...Option.match(expect, { onNone: () => [], onSome: ({ field }) => [field] }),\n ]\n /** Whether the row read is not at the revision the input expects. */\n const moved = (expect: Expect, before: Readonly<Record<string, unknown>>) =>\n Option.exists(expect, ({ field, revision }) => !sameStored(before[field], revision))\n /** The write held to the row its rules were decided over, where there is a revision. */\n const pin = (expect: Expect, before: Readonly<Record<string, unknown>>): Expect =>\n revision === undefined ? expect : Option.some({ field: revision, revision: before[revision] })\n /**\n * `attempt` run again while its pinned write misses: the row moved after it\n * was read, so it is decided again over the row as it now is. A write the\n * input pinned misses as a conflict, and is not run again.\n */\n const pinned = <A, E, RA>(\n id: string,\n expect: Expect,\n missed: (outcome: A) => boolean,\n attempt: () => Effect.Effect<A, E, RA>,\n ): Effect.Effect<A, E | RemoteServerError, RA> => {\n if (revision === undefined) return attempt()\n if (Option.isSome(expect)) {\n // The pin is the one revision the write moves on; another would stand still.\n return expect.value.field === revision\n ? attempt()\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s input expects \"${expect.value.field}\", but its writer pins \"${revision}\"`,\n }),\n )\n }\n const loop = (left: number): Effect.Effect<A, E | RemoteServerError, RA> =>\n Effect.flatMap(attempt(), outcome =>\n !missed(outcome)\n ? Effect.succeed(outcome)\n : left > 1\n ? loop(left - 1)\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name} ${id} changed while it was written`,\n }),\n ),\n )\n return loop(3)\n }\n const attachment = attached(entity)\n const hiddenByBody = new WeakMap<AnyQuery, ReadonlyArray<string>>()\n // An invariant reading a member a Read rule hides is still enforced, but named to no\n // one: which one failed, and where, would say what that member holds.\n const unnamed = new Set(\n Option.match(attachment, {\n onNone: () => [],\n onSome: ruled =>\n Entity.invariants(entity)\n .filter(held => [...held.before, ...held.after].some(key => readRuled(ruled, key)))\n .map(held => held.id),\n }),\n )\n const told = <E>(error: E | RemoteInvalid): E | RemoteInvalid =>\n error instanceof RemoteInvalid && Option.exists(error.rule, rule => unnamed.has(rule))\n ? RemoteServer.invalid('The row would be invalid')\n : error\n /**\n * Fails a write whose `when` reads, or whose `expect` names, a member with\n * a Read rule: Unmet or written, Conflict or not, would answer for it.\n * `validate` refuses the same at startup; this holds where it was not run.\n */\n const discloses = (\n expect: Expect,\n when: Option.Option<WriteWhen>,\n ): Effect.Effect<void, RemoteServerError> =>\n Option.match(attachment, {\n onNone: () => Effect.void,\n onSome: ruled => {\n const read = Option.match(when, {\n onNone: () => [],\n onSome: ({ body }) => {\n const known = hiddenByBody.get(body)\n if (known !== undefined) return known\n const hidden = hiddenOf(ruled, Query.dependencies(body).predicate)\n hiddenByBody.set(body, hidden)\n return hidden\n },\n })\n const expected = Option.match(expect, {\n onNone: () => [],\n onSome: ({ field }) => (readRuled(ruled, field) ? [field] : []),\n })\n const hidden = [...new Set([...read, ...expected])]\n return hidden.length === 0\n ? Effect.void\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write reads ${hidden.join(', ')}, which a Read rule hides from its writer`,\n }),\n )\n },\n })\n /**\n * The answer the writer's ledger holds for this operation, or else `write`:\n * a retry of a write that landed is answered as it landed, not decided\n * again over a row that may have moved since.\n */\n const answeredOr = <E, RA>(\n context: {\n readonly id: string\n readonly operation: Option.Option<string>\n readonly principal: Option.Option<User>\n },\n write: () => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, E, RA>,\n ) => {\n const recorded = writer.recorded\n if (recorded === undefined || Option.isNone(context.operation)) return write()\n return Effect.flatMap(\n recorded({\n operation: context.operation.value,\n id: context.id,\n principal: context.principal,\n }),\n Option.match({ onSome: answer => Effect.succeed(Option.some(answer)), onNone: write }),\n )\n }\n // What an answer shows: the row as the writer may see it, members ruled.\n const memberRead = GuardServer.filter(entity, policy)\n // An update, step by step: admitted for what it declares, its rules chosen, the\n // row they read read, the rules decided over it as it is and as it would be, then\n // written pinned to that row. Each step refuses before the next can speak.\n type UpdateContext = Parameters<EntityWriter<Option.Option<User>, RW>['update']>[0]\n interface UpdateRules {\n readonly row: RowRule\n readonly members: ReadonlyArray<RowRule>\n readonly relating: Effect.Success<ReturnType<typeof linkRules>>\n }\n /** Refused before any rule, for what the write declares rather than what the row holds. */\n const admitUpdate = (context: UpdateContext): Effect.Effect<void, RemoteServerError> =>\n Effect.andThen(discloses(context.expect, context.when), () =>\n // The rules judge a sum over the row read: unpinned, that is not the row written.\n Object.keys(context.increments).length > 0 &&\n Option.isNone(context.expect) &&\n revision === undefined\n ? Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s increment expects no revision and its writer pins none, so its rules would judge a sum over a row that may move; give the writer a revision`,\n }),\n )\n : Effect.void,\n )\n /** The rules an update must meet: the row's, each member it sets, each relation it points. */\n const updateRules = (context: UpdateContext) =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Update')\n // An incremented field is set as surely as a written one: its Update rule holds.\n const members = yield* policy.writeMembers(\n entity,\n context.principal,\n [...Object.keys(context.values), ...Object.keys(context.increments)],\n 'Update',\n )\n const relating = yield* linkRules(context.principal, context.links)\n return { row, members, relating } satisfies UpdateRules\n })\n /** The row as its writer may see it, with every field the rules and the version read. */\n const readBefore = (context: UpdateContext, rules: UpdateRules) =>\n read({\n id: context.id,\n fields: fieldsOf(\n [rules.row, ...rules.members, ...ruleOf(rules.relating)],\n [...Object.keys(context.links), ...versionFields(context.expect)],\n ),\n principal: context.principal,\n })\n /** The rules, over the row as it is and as the write would leave it. */\n const decideUpdate = (\n context: UpdateContext,\n rules: UpdateRules,\n before: Readonly<Record<string, unknown>>,\n ) =>\n Effect.gen(function* () {\n const { principal, values, increments, links } = context\n const linked = Object.keys(links)\n const stored =\n writer.linked === undefined || linked.length === 0\n ? Option.none()\n : yield* writer.linked({ id: context.id, relations: linked })\n const relations = linking(\n rules.relating,\n Option.some(\n Option.match(stored, {\n onNone: () => ({ links: before, exact: false }),\n onSome: links => ({ links, exact: true }),\n }),\n ),\n )\n // The sum the writer will store, over the row read, which the pin keeps as the row\n // written. Only a rule reads it, and `fieldsOf` read every field a rule reads.\n const after = {\n ...before,\n ...values,\n ...Object.fromEntries(\n Object.entries(increments).map(([field, amount]) => [\n field,\n Number(before[field]) + amount,\n ]),\n ),\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n yield* require([rules.row, ...rules.members, ...relations], before, principal)\n yield* require([rules.row], after, principal)\n })\n const guarded: EntityWriter<Option.Option<User>, R | RW> = {\n entity: writer.entity,\n // The precondition is the writer's to check, in the statement that writes.\n ...(writer.preconditions === true ? { preconditions: true } : {}),\n ...(writer.increments === true ? { increments: true } : {}),\n ...(writer.ledger === true ? { ledger: true } : {}),\n // Invariants are the writer's to judge, over the row its statement writes.\n ...(writer.invariants === true ? { invariants: true } : {}),\n ...(writer.recorded === undefined ? {} : { recorded: writer.recorded }),\n read: ({ id, fields, principal }) =>\n seenRow(\n { filter: memberRead },\n seen => read({ id, fields: seen, principal }),\n principal,\n fields,\n id,\n ),\n update: context =>\n Effect.mapError(\n Effect.andThen(admitUpdate(context), () =>\n answeredOr(context, () =>\n pinned(context.id, context.expect, Option.isNone, () =>\n Effect.gen(function* () {\n const rules = yield* updateRules(context)\n const current = yield* readBefore(context, rules)\n if (Option.isNone(current)) return yield* Effect.fail(refused(rules.row.deny))\n if (moved(context.expect, current.value)) return Option.none()\n yield* decideUpdate(context, rules, current.value)\n return yield* writer.update({\n ...context,\n expect: pin(context.expect, current.value),\n })\n }),\n ),\n ),\n ),\n told,\n ),\n insert: given =>\n Effect.gen(function* () {\n const preset = presets.find(({ field }) => Object.hasOwn(given.values, field))\n if (preset !== undefined) {\n return yield* new RemoteServerError({\n message: `${entity.name}'s \"${preset.field}\" is preset by the server; the input may not set it`,\n })\n }\n if (presets.length > 0 && Option.isNone(given.principal)) {\n return yield* Effect.fail(RemoteServer.forbid())\n }\n const context = Option.match(given.principal, {\n onNone: () => given,\n onSome: user => ({\n ...given,\n values: {\n ...given.values,\n ...Object.fromEntries(presets.map(({ field, value }) => [field, value(user)])),\n },\n }),\n })\n const { principal, values, links } = context\n const row = yield* policy.writable(entity, principal, 'Create')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n Object.keys(values),\n 'Create',\n )\n const relations = linking(yield* linkRules(principal, links), Option.none())\n const proposed = {\n ...values,\n id: context.id,\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n const rules = [row, ...members, ...relations]\n const ruled = rules.flatMap(({ condition }) => Condition.members(condition))\n const unset = new Set(ruled.filter(field => !Object.hasOwn(proposed, field)))\n yield* require(rules.map(rule => ({\n ...rule,\n condition: Condition.unsetting(rule.condition, unset),\n })), proposed, principal)\n return yield* Effect.mapError(writer.insert(context), told)\n }),\n delete: context =>\n Effect.andThen(discloses(context.expect, context.when), () =>\n pinned(\n context.id,\n context.expect,\n outcome => outcome === 'moved',\n () =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Delete')\n const current = yield* read({\n id: context.id,\n fields: fieldsOf([row], versionFields(context.expect)),\n principal: context.principal,\n })\n // Hidden or gone, the writer sees no row: there is nothing of theirs to delete.\n if (Option.isNone(current)) return 'absent' as const\n if (moved(context.expect, current.value)) return 'moved' as const\n yield* require([row], current.value, context.principal)\n return yield* writer.delete({\n ...context,\n expect: pin(context.expect, current.value),\n })\n }),\n ),\n ),\n }\n pins.set(guarded, Option.fromUndefinedOr(revision))\n return writeRules.add(guarded, policy, [entity])\n },\n\n /**\n * A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for\n * `interaction` checked before it runs. The row the input names (`id`) is\n * read through `source`, which must apply the Entity's Read rules, and the\n * rule must hold over it; a row its writer may not see is refused. With no\n * `id` (a create), the rule must hold of who is asking alone, a field it\n * reads matching no guard. `run` is given the row as read: its fields the\n * rule reads, its `id`, and `fields`. A refusal is `Forbidden`; `run` never\n * runs. What `run` writes is its own: check members it sets there. Each\n * row of `entity` its answer carries is read back through `source`, so the\n * answer shows its writer only what they may see, a row it hid from them\n * as deleted.\n *\n * ```ts\n * GuardServer.mutation(ArchiveTodo, {\n * entity: Todo, policy: Policy, interaction: Archive.key,\n * id: input => input.id, source: source(Db.Todo),\n * }, ({ input, row }) => …)\n * ```\n */\n mutation: <User, R, RS, RM, Name extends string, Input, Output, Refused>(\n mutation: MutationDescriptor<Name, Input, Output, Refused>,\n guard: {\n readonly entity: AnyEntity\n readonly policy: Policy<User, R>\n readonly interaction: 'Create' | 'Update' | 'Delete' | InteractionKey\n /**\n * The row the input acts on; none for a create. An input whose id may be\n * absent (`Option`, as one editor's for create and edit) creates when it\n * is, checked against `Create`.\n */\n readonly id?: ((input: Input) => string | Option.Option<string>) | undefined\n /** Reads the row as its writer may see it: the Entity's guarded Source. */\n readonly source: EntitySource<Option.Option<User>, RS>\n /** More of the row for `run`, beside what the rule reads. */\n readonly fields?: ReadonlyArray<string> | undefined\n },\n run: (context: {\n readonly input: Input\n readonly principal: Option.Option<User>\n readonly requestId: string\n readonly row: Option.Option<Readonly<Record<string, unknown>>>\n }) => Effect.Effect<\n MutationOutcome<Output>,\n RemoteServerError | MutationRefused | RemoteForbidden,\n RM\n >,\n ): MutationSource<Option.Option<User>, R | RS | RM> => {\n const { entity, policy, interaction, id, source } = guard\n if (!rowRules.has(source.visible, policy, entity)) {\n throw new Error(\n `[foldkit-guard] GuardServer.mutation: ${mutation.name}'s Source does not apply ${entity.name}'s Read rules`,\n )\n }\n /**\n * The answer as its writer may now see it: each row of `entity` it carries\n * read back through `source`, and one the handler hid from them deleted.\n */\n const shown = (outcome: MutationOutcome<Output>, principal: Option.Option<User>) =>\n Effect.map(\n Effect.forEach(outcome.entities ?? [], patch =>\n patch.entity !== entity.name\n ? Effect.succeed(Option.some(patch))\n : Effect.map(\n seenRow(\n source,\n fields =>\n Effect.map(rowOf(source, principal, fields, patch.id), Option.fromUndefinedOr),\n principal,\n Object.keys(patch.values),\n patch.id,\n ),\n Option.map(seen => ({ ...patch, values: seen })),\n ),\n ),\n read => ({\n ...outcome,\n entities: read.flatMap(Option.toArray),\n deleted: [\n ...(outcome.deleted ?? []),\n ...(outcome.entities ?? [])\n .filter((_, index) => Option.isNone(read[index]!))\n .map(({ entity, id }) => ({ entity, id })),\n ],\n }),\n )\n return RemoteServer.mutation<Option.Option<User>, R | RS | RM, Name, Input, Output, Refused>(\n mutation,\n context =>\n Effect.gen(function* () {\n const { principal } = context\n // `context.input` was decoded against the mutation's Input before this runs.\n const target = Option.flatMap(Option.fromUndefinedOr(id), of => {\n const named = of(context.input)\n return typeof named === 'string' ? Option.some(named) : named\n })\n const rule = yield* policy.writable(\n entity,\n principal,\n id !== undefined && Option.isNone(target) ? 'Create' : interaction,\n )\n const ruled = Condition.members(rule.condition)\n const input = policy.inputOf(principal)\n if (Option.isNone(target)) {\n const unset = Condition.unsetting(rule.condition, new Set(ruled))\n if (!Condition.holds(unset, {}, input, () => false)) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row: Option.none() }), principal)\n }\n const fields = [...new Set(['id', ...ruled, ...(guard.fields ?? [])])]\n const row = Option.fromUndefinedOr(yield* rowOf(source, principal, fields, target.value))\n if (\n Option.isNone(row) ||\n !Condition.holds(rule.condition, row.value, input, () => false)\n ) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row }), principal)\n }),\n )\n },\n\n /**\n * Checks, at startup, that `server` applies the guards of `entities`, the\n * Entities as `Guards.attach` returned them: each one's Source and each\n * query listing it apply its row's Read rules (`GuardDrizzle.visible`, or\n * `GuardServer.memory`), its Source applies its members' and relations'\n * (`GuardServer.filter`), and each declared write of it lands through\n * `GuardServer.writer`, all built from `policy`; and that no query's body\n * filters or orders by a member with a Read rule, which would answer for the\n * value it hides. A hand-written Source over a guarded Entity would serve\n * every row, and a bare writer would take every write; this throws instead,\n * naming each. A handler (`RemoteServer.mutation`) writes what its code\n * writes, which no check at startup can read.\n *\n * ```ts\n * GuardServer.validate(Policy, { entities: [Todo, Project], domain: Data, server: Server })\n * ```\n */\n validate: <User, R>(\n policy: Policy<User, R>,\n config: {\n readonly entities: ReadonlyArray<AnyEntity>\n /** The Remote domain the server answers, for which Entity each query lists. */\n readonly domain: {\n readonly registry: {\n readonly queries: ReadonlyMap<\n string,\n { readonly Result: unknown; readonly body?: AnyQuery | undefined }\n >\n }\n }\n readonly server: ServerDefinition<any, any>\n },\n ): void => {\n const byName = new Map(config.entities.map(entity => [entity.name, entity]))\n /** Whether who may read the rows of `entity` depends on who is asking. */\n const rowsRuled = (entity: AnyEntity | undefined) =>\n Option.exists(Option.flatMap(Option.fromUndefinedOr(entity), attached), attachment =>\n readRowsRuled(attachment),\n )\n // A query the domain does not declare lists an Entity no one can name.\n const undeclared = [...config.server.queries.keys()]\n .filter(query => !config.domain.registry.queries.has(query))\n .map(query => `query ${query} is served, but the domain does not declare it`)\n const entityProblems = config.entities.flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => {\n const name = entity.name\n if (attachment.set !== policy.set) {\n return [`${name} carries the guards of ${attachment.set}, not ${policy.set}`]\n }\n // Every guarded Entity's, whether or not it has rules there yet: a rule\n // attached later is then applied, not served past.\n const source = Option.fromUndefinedOr(config.server.entities.get(name))\n const sourceProblems = Option.match(source, {\n onNone: () => [],\n onSome: ({ visible, filter }) => [\n ...(rowRules.has(visible, policy, entity)\n ? []\n : [`${name}'s Source does not apply its Read rules`]),\n ...(memberRules.has(filter, policy, entity)\n ? []\n : [`${name}'s Source does not apply its members' Read rules`]),\n ],\n })\n const queryProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, query]) => {\n const listed = config.server.queries.get(queryName)\n return listed !== undefined &&\n lists(query.Result, name) &&\n !rowRules.has(listed.visible, policy, entity)\n ? [`query ${queryName} lists ${name} without its Read rules`]\n : []\n },\n )\n // A row the reader may see with a member it may not still answers a\n // filter or an order on that member: `cost < $max`, halved twenty\n // times, reads the cost the row came back without.\n const bodyProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, { body }]) => {\n if (body === undefined || body.entity.name !== name) return []\n const { predicate, order } = Query.dependencies(body)\n return [\n ...hiddenOf(attachment, predicate).map(\n member =>\n `query ${queryName} filters ${name} by ${member}, which has a Read rule`,\n ),\n ...hiddenOf(attachment, order).map(\n member => `query ${queryName} orders ${name} by ${member}, which has a Read rule`,\n ),\n ]\n },\n )\n const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) => {\n if (source.writes === undefined || source.writes.entity !== name) return []\n if (!writeRules.has(source.writes.writer, policy, entity)) {\n return [`write ${mutation} writes ${name} without its write rules`]\n }\n const { write, writer } = source.writes\n // Unmet or written, Conflict or not, answers for a member its writer may not read.\n const when = Option.match(write.when, {\n onNone: () => [],\n onSome: body => hiddenOf(attachment, Query.dependencies(body).predicate),\n })\n const expected = write.expect?.field.key\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n return [\n ...when.map(\n member =>\n `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`,\n ),\n ...(expected !== undefined && readRuled(attachment, expected)\n ? [`write ${mutation} expects ${name}'s ${expected}, which has a Read rule`]\n : []),\n ...(expected !== undefined &&\n pin !== undefined &&\n Option.exists(pin, field => field !== expected)\n ? [\n `write ${mutation} expects ${name}'s ${expected}, but its writer pins ${Option.getOrThrow(pin)}`,\n ]\n : []),\n ]\n })\n // A shared field goes to every live subscriber as written: no rule may tell them apart.\n const shared = Option.match(source, {\n onNone: () => [],\n onSome: source => [...(source.shared ?? [])],\n })\n const sharedProblems = [\n ...(shared.length > 0 && readRowsRuled(attachment)\n ? [`${name}'s Source shares ${shared.join(', ')}, but its rows have a Read rule`]\n : []),\n ...shared.flatMap(member => {\n const own = readRuled(attachment, member)\n ? [`${name}'s Source shares ${member}, which has a Read rule`]\n : []\n if (!Object.hasOwn(entity.relations, member)) return own\n const target = entity.relations[member]!.target().name\n if (!byName.has(target))\n return [\n ...own,\n `${name}'s Source shares ${member}, whose ${target} is not validated`,\n ]\n return rowsRuled(byName.get(target))\n ? [...own, `${name}'s Source shares ${member}, whose rows have a Read rule`]\n : own\n }),\n ]\n // A live Source of its own streams whatever it reads: nothing here can check it.\n const liveProblems = config.server.live.has(name)\n ? [`${name} has a live Source of its own; serve its changes through a live hub`]\n : []\n return [\n ...sourceProblems,\n ...queryProblems,\n ...bodyProblems,\n ...writeProblems,\n ...sharedProblems,\n ...liveProblems,\n ]\n },\n }),\n )\n const problems = [...undeclared, ...entityProblems]\n if (problems.length > 0) {\n throw new Error(`[foldkit-guard] GuardServer.validate: ${problems.join('; ')}`)\n }\n // Not refused yet: a writer given no revision is how every writer was made before it.\n const unpinnedWrites = [...config.server.mutations].flatMap(([mutation, source]) => {\n const writer = source.writes?.writer\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n return pin !== undefined && Option.isNone(pin) ? [mutation] : []\n })\n if (unpinnedWrites.length > 0) {\n console.warn(\n `[foldkit-guard] GuardServer.validate: ${unpinnedWrites.join(', ')} ${unpinnedWrites.length === 1 ? 'writes' : 'write'} through a GuardServer.writer with no revision, so a change between its check and its write is not seen; pass { revision }`,\n )\n }\n },\n}\n\n/** Whether a read asks for `may`, of an Entity that has it (`Guards.may`). */\nconst asksMay = (entity: AnyEntity, fields: ReadonlyArray<string>) =>\n fields.includes('may') && Object.hasOwn(entity.derived, 'may')\n\n/** How one principal's `may` is answered: the fields its rules read, and the answer over a row. */\ninterface MayPlan {\n readonly fields: ReadonlyArray<string>\n readonly answer: (values: Readonly<Record<string, unknown>>) => MayAnswer\n}\n\n/** The interactions a row answers `may` for: `Update`, `Delete`, and each one the set named. */\nconst builtInRow = new Set(['Read', 'Create', 'Update', 'Delete'])\n\n/**\n * `may` for `principal`: each row interaction's rule, each member's own\n * `Update`, each relation's `Link` and `Unlink`, decided once and held over\n * each row as a write's check would hold them over it as it is.\n */\nconst mayOf = <User, R>(\n entity: AnyEntity,\n policy: Policy<User, R>,\n principal: Option.Option<User>,\n): Effect.Effect<MayPlan, never, R> => {\n const attachment = attached(entity)\n const named = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ row }) => Object.keys(row).filter(interaction => !builtInRow.has(interaction)),\n })\n const ruledMembers = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ members }) => Object.keys(members),\n })\n const ruledRelations = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ relations }) => Object.keys(relations),\n })\n return Effect.map(\n Effect.all([\n Effect.forEach(['Update', 'Delete', ...named], interaction =>\n Effect.map(\n // A named one was attached as an `InteractionKey`; its key is the name.\n policy.writable(entity, principal, interaction as InteractionKey),\n rule => [interaction, rule] as const,\n ),\n ),\n policy.writeMembers(entity, principal, ruledMembers, 'Update'),\n Effect.forEach(ruledRelations, relation =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Link'),\n policy.linkable(entity, principal, relation, 'Unlink'),\n ]),\n ([link, unlink]) => ({ relation, link, unlink }),\n ),\n ),\n ]),\n ([rows, members, relations]): MayPlan => {\n const input = policy.inputOf(principal)\n const holds = (condition: Condition, values: Readonly<Record<string, unknown>>) =>\n Condition.holds(condition, values, input, () => false)\n // A relation without a rule for one direction leaves it to the row's Update.\n const allows = (rule: Option.Option<RowRule>, values: Readonly<Record<string, unknown>>) =>\n Option.match(rule, {\n onNone: () => true,\n onSome: ({ condition }) => holds(condition, values),\n })\n const conditions = [\n ...rows.map(([, { condition }]) => condition),\n ...members.map(({ condition }) => condition),\n ...relations.flatMap(({ link, unlink }) =>\n [...Option.toArray(link), ...Option.toArray(unlink)].map(({ condition }) => condition),\n ),\n ]\n return {\n // `id` too, so a row is read when its rules read none of it (an admin's).\n fields: ['id', ...new Set(conditions.flatMap(Condition.members))],\n answer: values => ({\n row: Object.fromEntries(\n rows.map(([interaction, { condition }]) => [interaction, holds(condition, values)]),\n ),\n // Only an `explain`'s sentence is for whoever asked.\n reasons: Object.fromEntries(\n rows.flatMap(([interaction, { condition, deny }]) =>\n holds(condition, values)\n ? []\n : Match.valueTags(deny, {\n Explain: ({ reason }) => [[interaction, reason] as const],\n Forbidden: () => [],\n NotFound: () => [],\n Omit: () => [],\n Redact: () => [],\n }),\n ),\n ),\n members: Object.fromEntries(\n members.map(({ member, condition }) => [member, holds(condition, values)]),\n ),\n relations: Object.fromEntries(\n relations.map(({ relation, link, unlink }) => [\n relation,\n { Link: allows(link, values), Unlink: allows(unlink, values) },\n ]),\n ),\n }),\n }\n },\n )\n}\n\n/** A refused write as the client receives it: the sentence an `explain` gave, or none. */\nconst refused = (deny: Deny) =>\n Match.valueTags(deny, {\n Explain: ({ reason }) => RemoteServer.forbid(reason),\n Forbidden: () => RemoteServer.forbid(),\n NotFound: () => RemoteServer.forbid(),\n Omit: () => RemoteServer.forbid(),\n Redact: () => RemoteServer.forbid(),\n })\n\n/** One row, by id, as `principal` may read it through `source`. */\nconst rowOf = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n) =>\n Effect.map(\n source.read({ ids: [id], fields: [...fields], principal }),\n records => records.find(record => record.id === id)?.values,\n )\n\n/**\n * Row `id` of `fields` as `principal` may see it, through `see`'s `authorize`\n * and `filter` as a Source applies them, and no more than was asked: what an\n * answer shows its writer. None when the row is not there to them.\n */\nconst seenRow = <P, R, RS>(\n see: Pick<EntitySource<P, RS>, 'authorize' | 'filter'>,\n read: (\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n): Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R | RS> =>\n Effect.gen(function* () {\n const allowed = see.authorize === undefined ? fields : see.authorize(principal, [...fields])\n const plan: ReadPlan =\n see.filter === undefined\n ? { fields: allowed, apply: noMembers }\n : yield* see.filter(principal, allowed)\n // The id too: a row asked for nothing else is still there or not.\n const row = yield* read([...new Set(['id', ...plan.fields])])\n return Option.map(row, values => {\n const shown = plan.apply({ id, values }).values\n return Object.fromEntries(\n allowed.filter(field => Object.hasOwn(shown, field)).map(field => [field, shown[field]]),\n )\n })\n })\n\n/** A link's value as a row holds it: the ref's key, or `null` for none. */\nconst linkKey = (link: Option.Option<{ readonly entity: string; readonly id: string }>) =>\n Option.match(link, { onNone: () => null, onSome: ref => `${ref.entity}:${ref.id}` })\n\n/** Whether a query's result is a connection over `entity`. */\nconst lists = (result: unknown, entity: string): boolean =>\n typeof result === 'object' && result !== null && 'entity' in result && result.entity === entity\n"],"mappings":";;;;;;;;;;;;;;;AAuCA,MAAM,aAAa,WAAyB;;AAG5C,MAAM,cAAc,MAAe,UACjC,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SACJ,QACA,WACA,QACA,OAEA,OAAO,IACL,OAAO,KAAK;CAAE,KAAK,CAAC,EAAE;CAAG,QAAQ,CAAC,GAAG,MAAM;CAAG;AAAU,CAAC,IACzD,YAAW,QAAQ,MAAK,WAAU,OAAO,OAAO,EAAE,CAAC,EAAE,MACvD;;;;;;AAOF,MAAM,WACJ,KACA,MAGA,WACA,QACA,OAEA,OAAO,IAAI,aAAa;CACtB,MAAM,UAAU,IAAI,cAAc,KAAA,IAAY,SAAS,IAAI,UAAU,WAAW,CAAC,GAAG,MAAM,CAAC;CAC3F,MAAM,OACJ,IAAI,WAAW,KAAA,IACX;EAAE,QAAQ;EAAS,OAAO;CAAU,IACpC,OAAO,IAAI,OAAO,WAAW,OAAO;CAE1C,MAAM,MAAM,OAAO,KAAK,CAAC,mBAAG,IAAI,IAAI,CAAC,MAAM,GAAG,KAAK,MAAM,CAAC,CAAC,CAAC;CAC5D,OAAO,OAAO,IAAI,MAAK,WAAU;EAC/B,MAAM,QAAQ,KAAK,MAAM;GAAE;GAAI;EAAO,CAAC,CAAC,CAAC;EACzC,OAAO,OAAO,YACZ,QAAQ,QAAO,UAAS,OAAO,OAAO,OAAO,KAAK,CAAC,CAAC,CAAC,KAAI,UAAS,CAAC,OAAO,MAAM,MAAM,CAAC,CACzF;CACF,CAAC;AACH,CAAC;;AAGH,MAAM,WAAW,SACf,OAAO,MAAM,MAAM;CAAE,cAAc;CAAM,SAAQ,QAAO,GAAG,IAAI,OAAO,GAAG,IAAI;AAAK,CAAC;;AAGrF,MAAM,SAAS,QAAiB,WAC9B,OAAO,WAAW,YAAY,WAAW,QAAQ,YAAY,UAAU,OAAO,WAAW"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-guard",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Who may do what, declared once on a Foldkit Plus domain: principal guards implemented on the server, row guards as query expressions.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -61,17 +61,17 @@
61
61
  "LICENSE"
62
62
  ],
63
63
  "dependencies": {
64
- "foldkit-entity": "0.10.0",
65
- "foldkit-metadata": "0.1.0"
64
+ "foldkit-metadata": "0.1.0",
65
+ "foldkit-entity": "0.11.0"
66
66
  },
67
67
  "peerDependencies": {
68
68
  "drizzle-orm": "1.0.0-rc.5",
69
69
  "effect": "^4.0.0",
70
70
  "foldkit-media": "^0.2.0",
71
- "foldkit-remote": "^0.18.1",
72
- "foldkit-remote-drizzle": "^0.12.4",
73
- "foldkit-sync": "^0.12.1",
74
- "foldkit-remote-server": "^0.15.1"
71
+ "foldkit-remote-server": "^0.16.0",
72
+ "foldkit-remote": "^0.19.0",
73
+ "foldkit-sync": "^0.12.2",
74
+ "foldkit-remote-drizzle": "^0.13.0"
75
75
  },
76
76
  "peerDependenciesMeta": {
77
77
  "drizzle-orm": {
@@ -100,12 +100,12 @@
100
100
  "tsdown": "^0.23.1",
101
101
  "typescript": "7.0.2",
102
102
  "foldkit-media": "0.2.0",
103
- "foldkit-remote-drizzle": "0.12.4",
104
- "foldkit-agent": "0.8.2",
105
- "foldkit-remote": "0.18.1",
106
- "foldkit-remote-server": "0.15.1",
107
- "foldkit-surface": "0.10.1",
108
- "foldkit-sync": "0.12.1"
103
+ "foldkit-remote-server": "0.16.0",
104
+ "foldkit-remote": "0.19.0",
105
+ "foldkit-agent": "0.8.3",
106
+ "foldkit-surface": "0.10.2",
107
+ "foldkit-sync": "0.12.2",
108
+ "foldkit-remote-drizzle": "0.13.0"
109
109
  },
110
110
  "scripts": {
111
111
  "build": "tsdown",