foldkit-guard 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +218 -44
  2. package/dist/agent.d.mts +1 -1
  3. package/dist/agent.mjs +1 -1
  4. package/dist/{attach-CRCF5XHS.mjs → attach-CEGlbWu5.mjs} +17 -2
  5. package/dist/attach-CEGlbWu5.mjs.map +1 -0
  6. package/dist/{attach-BnP9_Uca.d.mts → attach-DPgyv78F.d.mts} +87 -8
  7. package/dist/attach-DPgyv78F.d.mts.map +1 -0
  8. package/dist/{condition-Bl1UgEpM.mjs → condition-dNSbUHzE.mjs} +102 -10
  9. package/dist/condition-dNSbUHzE.mjs.map +1 -0
  10. package/dist/drizzle.d.mts +6 -4
  11. package/dist/drizzle.d.mts.map +1 -1
  12. package/dist/drizzle.mjs +18 -8
  13. package/dist/drizzle.mjs.map +1 -1
  14. package/dist/index.d.mts +1 -1
  15. package/dist/index.mjs +34 -17
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/may-DprCmMgK.mjs +200 -0
  18. package/dist/may-DprCmMgK.mjs.map +1 -0
  19. package/dist/{me-BYpuVqJE.mjs → me-C-gX1paZ.mjs} +3 -3
  20. package/dist/{me-BYpuVqJE.mjs.map → me-C-gX1paZ.mjs.map} +1 -1
  21. package/dist/media.d.mts +1 -1
  22. package/dist/{placed-BvdNmZJu.mjs → placed-CGyo-NRR.mjs} +2 -2
  23. package/dist/{placed-BvdNmZJu.mjs.map → placed-CGyo-NRR.mjs.map} +1 -1
  24. package/dist/server.d.mts +50 -17
  25. package/dist/server.d.mts.map +1 -1
  26. package/dist/server.mjs +326 -155
  27. package/dist/server.mjs.map +1 -1
  28. package/dist/sync.d.mts +5 -3
  29. package/dist/sync.d.mts.map +1 -1
  30. package/dist/sync.mjs +18 -8
  31. package/dist/sync.mjs.map +1 -1
  32. package/package.json +18 -17
  33. package/dist/attach-BnP9_Uca.d.mts.map +0 -1
  34. package/dist/attach-CRCF5XHS.mjs.map +0 -1
  35. package/dist/condition-Bl1UgEpM.mjs.map +0 -1
  36. package/dist/may-DzCAt_5M.mjs +0 -75
  37. package/dist/may-DzCAt_5M.mjs.map +0 -1
package/dist/server.mjs CHANGED
@@ -1,10 +1,29 @@
1
- import { c as readRowsRuled, i as attachedRules, l as readRuled, r as attached } from "./attach-CRCF5XHS.mjs";
2
- import { t as Condition } from "./condition-Bl1UgEpM.mjs";
3
- import "./me-BYpuVqJE.mjs";
4
- import { n as rowRules, r as writeRules, t as memberRules } from "./placed-BvdNmZJu.mjs";
5
- import { Effect, Match, Option, Schema, SchemaAST } from "effect";
6
- import { Entity, Query, supported } from "foldkit-entity";
7
- import { RemoteInvalid, RemoteServer, RemoteServerError } from "foldkit-remote-server";
1
+ import { c as readRowsRuled, d as surfaceOf, i as attachedRules, l as readRuled, r as attached } from "./attach-CEGlbWu5.mjs";
2
+ import { t as Condition } from "./condition-dNSbUHzE.mjs";
3
+ import { a as mayRules, i as mayConditions, r as answerOf } from "./may-DprCmMgK.mjs";
4
+ import "./me-C-gX1paZ.mjs";
5
+ import { n as rowRules, r as writeRules, t as memberRules } from "./placed-CGyo-NRR.mjs";
6
+ import { Effect, Match, Option, Schema, SchemaAST, identity } from "effect";
7
+ import { Entity, Expr, Query, QueryEvaluateError, Write, dependenciesOf, supported } from "foldkit-entity";
8
+ import { Diagnostics } from "foldkit-remote";
9
+ import { RemoteInvalid, RemoteServer, RemoteServerError, RowRequirement } from "foldkit-remote-server";
10
+ // src/diagnostics.ts
11
+ const source = "foldkit-guard";
12
+ const computeRefused = (entity, error) => ({
13
+ _tag: "ComputeRefused",
14
+ source,
15
+ level: "error",
16
+ message: `${entity}'s write was refused: a value it computes could not be worked out (${error.message})`,
17
+ entity,
18
+ error
19
+ });
20
+ const unpinnedWrites = (mutations) => ({
21
+ _tag: "UnpinnedWrites",
22
+ source,
23
+ level: "warning",
24
+ message: `GuardServer.validate: ${mutations.join(", ")} ${mutations.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 }`,
25
+ mutations
26
+ });
8
27
  // src/server.ts
9
28
  /**
10
29
  * A guard set's read rules as `foldkit-remote-server`'s seams: an
@@ -18,6 +37,48 @@ const noMembers = (record) => record;
18
37
  const sameStored = (left, right) => JSON.stringify(left) === JSON.stringify(right);
19
38
  /** The members of `fields` that have a Read rule, once each. */
20
39
  const hiddenOf = (attachment, fields) => [...new Set(fields.map((field) => field.key).filter((key) => readRuled(attachment, key)))];
40
+ /**
41
+ * Each member a body reads on a row it reaches rather than judges: every
42
+ * relation a path, a path from the viewer or an exists follows, the field a
43
+ * path ends at, and an exists' pointing relation and filter. SQL reads such a
44
+ * row under its `visible` rule alone, never its members'.
45
+ */
46
+ const reachedMembers = (reaches) => reaches.flatMap((reached) => {
47
+ const via = reached.via.map((relation) => ({
48
+ entity: relation.owner.name,
49
+ key: relation.key
50
+ }));
51
+ return Match.valueTags(reached, {
52
+ Path: ({ field }) => [...via, {
53
+ entity: field.owner.name,
54
+ key: field.key
55
+ }],
56
+ ViewerPath: ({ field }) => [...via, {
57
+ entity: field.owner.name,
58
+ key: field.key
59
+ }],
60
+ Exists: ({ relation, where }) => {
61
+ const filter = Option.match(where, {
62
+ onNone: () => [],
63
+ onSome: (body) => {
64
+ const read = dependenciesOf(body);
65
+ return [...read.fields.map((field) => ({
66
+ entity: field.entity,
67
+ key: field.key
68
+ })), ...reachedMembers(read.reaches)];
69
+ }
70
+ });
71
+ return [
72
+ ...via,
73
+ {
74
+ entity: relation.owner.name,
75
+ key: relation.key
76
+ },
77
+ ...filter
78
+ ];
79
+ }
80
+ });
81
+ });
21
82
  /** Each guarded writer's `revision`, or none: one a change can fall between check and write of. */
22
83
  const pins = /* @__PURE__ */ new WeakMap();
23
84
  /** A ref key's two halves, `Entity:id`; `none` for anything else. */
@@ -145,19 +206,25 @@ const GuardServer = {
145
206
  * `RemoteServer.write`. An update or a delete reads the row first under
146
207
  * the writer's own `read` (its Source's read rule): a row the writer may not
147
208
  * see is refused as one that is not there, and a delete of it changes
148
- * nothing. Then the row's rule for the command must hold over the row (an
149
- * update's over the row as it would be after it too, so a write cannot move
150
- * a row out of its writer's reach), each member it sets must allow setting
151
- * it, and each relation it points elsewhere must allow the unlink and the
152
- * link. A create's rules hold over the values it proposes, where a field the
209
+ * nothing. Then the row's rule for the command must hold over the row, each
210
+ * member it sets must allow setting it, and each relation it points
211
+ * elsewhere must allow the unlink and the link. An update's row rule holds
212
+ * over the row as it would be after it too, so a write cannot move a row out
213
+ * of its writer's reach. Each of its member and `Link` rules holds over the
214
+ * row after with that one change undone (that member's value, or where that
215
+ * relation pointed, as before): the change must be allowed given everything
216
+ * else the write does, so one write cannot set together what each change
217
+ * alone would be refused, while a rule reading its own member ("only while
218
+ * a draft") still allows the change. An increment or a computed assignment
219
+ * to a member is that member's own change. An `Unlink` rule holds over the
220
+ * row before alone. A create's rules hold over the values it proposes, where a field the
153
221
  * create leaves unset matches no guard, not even one for an empty value. A refusal is
154
222
  * `Forbidden`, with the sentence an `explain` gave; the write never runs.
155
223
  *
156
- * `presets` are fields a create takes from who is asking, never from the
157
- * client (`ownerId: user => user.id`): set before the rules are checked, so
158
- * a rule over them holds of the creator. A visitor has nothing to preset
159
- * from, and a create whose input sets a preset field is a mistake of the
160
- * server's, refused.
224
+ * What the Entity sets from the write's context (`Entity.sets`: who asks,
225
+ * when) reaches a create or an update already set by `RemoteServer.write`,
226
+ * so a rule over it holds of the creator. A member rule over such a member
227
+ * judges the server's value like any other: declare none there.
161
228
  *
162
229
  * `revision` names a field stored as a number, which the writer moves on by
163
230
  * one with each write it lands. An update or a delete then lands only on the
@@ -165,7 +232,8 @@ const GuardServer = {
165
232
  * between the check and the write is never written over; it is decided
166
233
  * again against the row as it now is, up to three times. A change that does
167
234
  * 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
235
+ * Without `revision`, none is, and `validate` warns of an update, or a delete
236
+ * of an Entity the server updates (an insert has no row). An input that expects a
169
237
  * revision the row read is not at is a `Conflict`, decided before any rule;
170
238
  * an input may expect only the field the writer pins.
171
239
  *
@@ -180,18 +248,40 @@ const GuardServer = {
180
248
  if (field === void 0) throw new Error(`[foldkit-guard] GuardServer.writer: ${entity.name} has no field "${revision}" for its revision`);
181
249
  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
250
  }
183
- const presets = Object.entries(options.presets ?? {}).map(([field, preset]) => {
184
- const declared = Object.hasOwn(entity.fields, field) ? entity.fields[field] : void 0;
185
- if (declared === void 0) throw new Error(`[foldkit-guard] GuardServer.writer: ${entity.name} has no field "${field}" to preset`);
186
- const encode = Schema.encodeUnknownSync(declared.schema);
187
- return {
188
- field,
189
- value: (user) => encode(preset(user))
190
- };
191
- });
192
251
  if (writer.entity !== entity.name) throw new Error(`[foldkit-guard] GuardServer.writer: ${entity.name}'s rules over a writer for ${writer.entity}`);
193
252
  const read = writer.read;
194
253
  if (read === void 0) throw new Error(`[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)`);
254
+ const reaching = Option.match(attached(entity), {
255
+ onNone: () => [],
256
+ onSome: ({ row }) => ["Update", "Delete"].flatMap((interaction) => (row[interaction]?.rules ?? []).flatMap(function names(rule) {
257
+ return Match.valueTags(rule, {
258
+ PrincipalGuard: () => [],
259
+ RowGuard: (guard) => Query.dependencies(guard.query).reaches.length > 0 ? [guard.name] : [],
260
+ All: ({ rules }) => rules.flatMap(names),
261
+ Inherit: () => []
262
+ });
263
+ }))
264
+ });
265
+ if (reaching.length > 0 && writer.requires !== true) throw new Error(`[foldkit-guard] GuardServer.writer: ${entity.name}'s ${reaching.join(", ")} reads another row, which only a writer judging rules in its statement can hold it to (foldkit-remote-drizzle's writer); this writer does not`);
266
+ /**
267
+ * The row rule over `values` as far as one row decides it: refused where it
268
+ * fails, and otherwise what the writer's statement must still judge.
269
+ */
270
+ const rowRule = (rule, values, principal) => {
271
+ const left = Condition.residual(rule.condition, values, policy.inputOf(principal), policy.operators);
272
+ return Match.valueTags(left, {
273
+ Always: () => Effect.succeed(Option.none()),
274
+ Never: () => Effect.fail(refused(rule.deny)),
275
+ Row: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),
276
+ Inherit: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),
277
+ And: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),
278
+ Or: () => Effect.succeed(Option.some(required(left, rule.deny, principal)))
279
+ });
280
+ };
281
+ const required = (left, deny, principal) => ({
282
+ holds: requirementOf(left, policy.inputOf(principal)),
283
+ reason: explained(deny)
284
+ });
195
285
  const holds = (rule, values, principal) => Condition.holds(rule.condition, values, policy.inputOf(principal), () => false, policy.operators);
196
286
  /** Fails with the first rule of `rules` that does not hold over `values`. */
197
287
  const require = (rules, values, principal) => Option.match(Option.fromUndefinedOr(rules.find((rule) => !holds(rule, values, principal))), {
@@ -257,11 +347,12 @@ const GuardServer = {
257
347
  }));
258
348
  const told = (error) => error instanceof RemoteInvalid && Option.exists(error.rule, (rule) => unnamed.has(rule)) ? RemoteServer.invalid("The row would be invalid") : error;
259
349
  /**
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.
350
+ * Fails a write whose `when` reads, whose `expect` names, or whose
351
+ * computed assignment reads, a member with a Read rule: Unmet or written,
352
+ * Conflict or not, and the computed value answered, would answer for it.
262
353
  * `validate` refuses the same at startup; this holds where it was not run.
263
354
  */
264
- const discloses = (expect, when) => Option.match(attachment, {
355
+ const discloses = (expect, when, assignments = {}) => Option.match(attachment, {
265
356
  onNone: () => Effect.void,
266
357
  onSome: (ruled) => {
267
358
  const read = Option.match(when, {
@@ -278,57 +369,105 @@ const GuardServer = {
278
369
  onNone: () => [],
279
370
  onSome: ({ field }) => readRuled(ruled, field) ? [field] : []
280
371
  });
281
- const hidden = [.../* @__PURE__ */ new Set([...read, ...expected])];
372
+ const computed = Write.boundReads({
373
+ increments: {},
374
+ assignments
375
+ }).filter((field) => readRuled(ruled, field));
376
+ const hidden = [.../* @__PURE__ */ new Set([
377
+ ...read,
378
+ ...expected,
379
+ ...computed
380
+ ])];
282
381
  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
382
  }
284
383
  });
285
384
  /**
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.
385
+ * The answer the writer's ledger holds for this operation, as `answered`
386
+ * makes it, or else `write`: a retry of a write that landed is answered as
387
+ * it landed, not decided again over a row, or a time, that has moved since.
289
388
  */
290
- const answeredOr = (context, write) => {
389
+ const answeredOr = (context, answered, write) => {
291
390
  const recorded = writer.recorded;
292
391
  if (recorded === void 0 || Option.isNone(context.operation)) return write();
293
392
  return Effect.flatMap(recorded({
294
393
  operation: context.operation.value,
394
+ request: context.request,
295
395
  id: context.id,
296
396
  principal: context.principal
297
397
  }), Option.match({
298
- onSome: (answer) => Effect.succeed(Option.some(answer)),
398
+ onSome: (answer) => Effect.succeed(answered(answer)),
299
399
  onNone: write
300
400
  }));
301
401
  };
302
402
  const memberRead = GuardServer.filter(entity, policy);
303
403
  /** 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);
404
+ const admitUpdate = (context) => Effect.andThen(discloses(context.expect, context.when, context.assignments), () => Object.keys(context.increments).length + Object.keys(context.assignments).length > 0 && Option.isNone(context.expect) && revision === void 0 ? Effect.fail(new RemoteServerError({ message: `${entity.name}'s write moves a field and expects no revision, and its writer pins none, so its rules would judge a value over a row that may move; give the writer a revision` })) : Effect.void);
305
405
  /** The rules an update must meet: the row's, each member it sets, each relation it points. */
306
406
  const updateRules = (context) => Effect.gen(function* () {
307
407
  return {
308
408
  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"),
409
+ members: yield* policy.writeMembers(entity, context.principal, [
410
+ ...Object.keys(context.values),
411
+ ...Object.keys(context.increments),
412
+ ...Object.keys(context.assignments)
413
+ ], "Update"),
310
414
  relating: yield* linkRules(context.principal, context.links)
311
415
  };
312
416
  });
313
- /** The row as its writer may see it, with every field the rules and the version read. */
417
+ /**
418
+ * The row as its writer may see it, with every field the rules and the
419
+ * version read, and those the write's amounts and assignments read to
420
+ * work out the row it leaves.
421
+ */
314
422
  const readBefore = (context, rules) => read({
315
423
  id: context.id,
316
424
  fields: fieldsOf([
317
425
  rules.row,
318
426
  ...rules.members,
319
427
  ...ruleOf(rules.relating)
320
- ], [...Object.keys(context.links), ...versionFields(context.expect)]),
428
+ ], [
429
+ ...Object.keys(context.links),
430
+ ...versionFields(context.expect),
431
+ ...Write.boundReads(context),
432
+ ...Condition.reachedFrom(rules.row.condition, {
433
+ entity: entity.name,
434
+ id: context.id
435
+ })
436
+ ]),
321
437
  principal: context.principal
322
438
  });
439
+ /**
440
+ * The memory table the row a write leaves is worked out by: the writer's,
441
+ * so the rules judge the value its statement writes, else the policy's.
442
+ */
443
+ const computing = writer.operators ?? policy.operators;
444
+ /**
445
+ * The row `context` would leave `before` as. An operator's refusal (text
446
+ * holding NUL, an implementation that throws) is a server error, as the
447
+ * writer answers what it cannot compile: reported here (`ComputeRefused`),
448
+ * and never sent, since an implementation's own message may say anything.
449
+ * So is a field it cannot
450
+ * work out at all: judging its old value would let a rule over it pass.
451
+ */
452
+ const leaves = (before, context) => Effect.suspend(() => {
453
+ const unworkable = Effect.fail(new RemoteServerError({ message: `${entity.name}'s write could not be worked out to judge its rules` }));
454
+ try {
455
+ const applied = Write.apply(before, context, { operators: computing });
456
+ return applied.unknown.length === 0 ? Effect.succeed(applied.row) : unworkable;
457
+ } catch (error) {
458
+ if (!(error instanceof QueryEvaluateError)) throw error;
459
+ return Diagnostics.report(computeRefused(entity.name, error)).pipe(Effect.andThen(unworkable));
460
+ }
461
+ });
323
462
  /** The rules, over the row as it is and as the write would leave it. */
324
463
  const decideUpdate = (context, rules, before) => Effect.gen(function* () {
325
- const { principal, values, increments, links } = context;
464
+ const { principal, links } = context;
326
465
  const linked = Object.keys(links);
327
466
  const stored = writer.linked === void 0 || linked.length === 0 ? Option.none() : yield* writer.linked({
328
467
  id: context.id,
329
468
  relations: linked
330
469
  });
331
- const relations = linking(rules.relating, Option.some(Option.match(stored, {
470
+ const was = Option.some(Option.match(stored, {
332
471
  onNone: () => ({
333
472
  links: before,
334
473
  exact: false
@@ -337,58 +476,75 @@ const GuardServer = {
337
476
  links,
338
477
  exact: true
339
478
  })
340
- })));
479
+ }));
480
+ const relations = linking(rules.relating, was);
481
+ const requires = yield* rowRule(rules.row, before, principal);
482
+ yield* require([...rules.members, ...relations], before, principal);
341
483
  const after = {
342
- ...before,
343
- ...values,
344
- ...Object.fromEntries(Object.entries(increments).map(([field, amount]) => [field, Number(before[field]) + amount])),
484
+ ...yield* leaves(before, context),
345
485
  ...Object.fromEntries(Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]))
346
486
  };
347
- yield* require([
348
- rules.row,
349
- ...rules.members,
350
- ...relations
351
- ], before, principal);
352
- yield* require([rules.row], after, principal);
487
+ const leaving = yield* rowRule(rules.row, after, principal);
488
+ if (Option.isSome(leaving)) {
489
+ if (Condition.reachedFrom(Condition.residual(rules.row.condition, after, policy.inputOf(principal), policy.operators), {
490
+ entity: entity.name,
491
+ id: context.id
492
+ }).some((key) => !sameStored(before[key], after[key]))) return yield* Effect.fail(refused(rules.row.deny));
493
+ }
494
+ const undone = [...rules.members.map((rule) => ({
495
+ rule,
496
+ key: rule.member
497
+ })), ...rules.relating.flatMap((rule) => linking([{
498
+ ...rule,
499
+ unlink: Option.none()
500
+ }], was).map((link) => ({
501
+ rule: link,
502
+ key: rule.relation
503
+ })))];
504
+ yield* Effect.forEach(undone, ({ rule, key }) => require([rule], {
505
+ ...after,
506
+ [key]: before[key]
507
+ }, principal), { discard: true });
508
+ return requires;
353
509
  });
354
510
  const guarded = {
355
511
  entity: writer.entity,
356
512
  ...writer.preconditions === true ? { preconditions: true } : {},
357
513
  ...writer.increments === true ? { increments: true } : {},
514
+ ...writer.assignments === true ? { assignments: true } : {},
515
+ ...revision === void 0 ? {} : { pins: true },
358
516
  ...writer.ledger === true ? { ledger: true } : {},
359
517
  ...writer.invariants === true ? { invariants: true } : {},
360
- ...writer.refuses === void 0 ? {} : { refuses: writer.refuses },
518
+ refuses: (write) => [
519
+ ...writer.refuses?.(write) ?? [],
520
+ ...write.assignments.flatMap(({ field, expr }) => Expr.unsupported([expr], {
521
+ operations: supported,
522
+ operators: computing
523
+ }).map((missing) => `its assignment to "${field.key}" calls ${missing}, which the guard cannot work out`)),
524
+ ...(write.increments.length > 0 || write.assignments.length > 0) && write.expect === void 0 && revision === void 0 ? ["it moves a field and expects no revision, and the guarded writer pins none, so its rules would judge a value over a row that may move; give the writer a revision"] : []
525
+ ],
361
526
  ...writer.recorded === void 0 ? {} : { recorded: writer.recorded },
362
527
  read: ({ id, fields, principal }) => seenRow({ filter: memberRead }, (seen) => read({
363
528
  id,
364
529
  fields: seen,
365
530
  principal
366
531
  }), principal, fields, id),
367
- update: (context) => Effect.mapError(Effect.andThen(admitUpdate(context), () => answeredOr(context, () => pinned(context.id, context.expect, Option.isNone, () => Effect.gen(function* () {
532
+ update: (context) => Effect.mapError(Effect.andThen(admitUpdate(context), () => answeredOr(context, Option.some, () => pinned(context.id, context.expect, Option.isNone, () => Effect.gen(function* () {
368
533
  const rules = yield* updateRules(context);
369
534
  const current = yield* readBefore(context, rules);
370
535
  if (Option.isNone(current)) return yield* Effect.fail(refused(rules.row.deny));
371
536
  if (moved(context.expect, current.value)) return Option.none();
372
- yield* decideUpdate(context, rules, current.value);
537
+ const requires = yield* decideUpdate(context, rules, current.value);
373
538
  return yield* writer.update({
374
539
  ...context,
375
- expect: pin(context.expect, current.value)
376
- });
377
- })))), told),
378
- insert: (given) => Effect.gen(function* () {
379
- const preset = presets.find(({ field }) => Object.hasOwn(given.values, field));
380
- 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` });
381
- if (presets.length > 0 && Option.isNone(given.principal)) return yield* Effect.fail(RemoteServer.forbid());
382
- const context = Option.match(given.principal, {
383
- onNone: () => given,
384
- onSome: (user) => ({
385
- ...given,
386
- values: {
387
- ...given.values,
388
- ...Object.fromEntries(presets.map(({ field, value }) => [field, value(user)]))
389
- }
540
+ expect: pin(context.expect, current.value),
541
+ ...Option.match(requires, {
542
+ onNone: () => ({}),
543
+ onSome: (held) => ({ requires: held })
390
544
  })
391
545
  });
546
+ })))), told),
547
+ insert: (context) => answeredOr(context, identity, () => Effect.gen(function* () {
392
548
  const { principal, values, links } = context;
393
549
  const row = yield* policy.writable(entity, principal, "Create");
394
550
  const members = yield* policy.writeMembers(entity, principal, Object.keys(values), "Create");
@@ -410,7 +566,7 @@ const GuardServer = {
410
566
  condition: Condition.unsetting(rule.condition, unset)
411
567
  })), proposed, principal);
412
568
  return yield* Effect.mapError(writer.insert(context), told);
413
- }),
569
+ })),
414
570
  delete: (context) => Effect.andThen(discloses(context.expect, context.when), () => pinned(context.id, context.expect, (outcome) => outcome === "moved", () => Effect.gen(function* () {
415
571
  const row = yield* policy.writable(entity, context.principal, "Delete");
416
572
  const current = yield* read({
@@ -420,10 +576,14 @@ const GuardServer = {
420
576
  });
421
577
  if (Option.isNone(current)) return "absent";
422
578
  if (moved(context.expect, current.value)) return "moved";
423
- yield* require([row], current.value, context.principal);
579
+ const requires = yield* rowRule(row, current.value, context.principal);
424
580
  return yield* writer.delete({
425
581
  ...context,
426
- expect: pin(context.expect, current.value)
582
+ expect: pin(context.expect, current.value),
583
+ ...Option.match(requires, {
584
+ onNone: () => ({}),
585
+ onSome: (held) => ({ requires: held })
586
+ })
427
587
  });
428
588
  })))
429
589
  };
@@ -505,11 +665,14 @@ const GuardServer = {
505
665
  * `GuardServer.memory`), its Source applies its members' and relations'
506
666
  * (`GuardServer.filter`), and each declared write of it lands through
507
667
  * `GuardServer.writer`, all built from `policy`; and that no query's body
508
- * filters or orders by a member with a Read rule, which would answer for the
509
- * value it hides. A hand-written Source over a guarded Entity would serve
668
+ * filters or orders by a member with a Read rule, its own or one of a row it
669
+ * reaches through a path or an exists, which would answer for the value it
670
+ * hides. A hand-written Source over a guarded Entity would serve
510
671
  * every row, and a bare writer would take every write; this throws instead,
511
672
  * naming each. A handler (`RemoteServer.mutation`) writes what its code
512
- * writes, which no check at startup can read.
673
+ * writes, which no check at startup can read. A write a change can come
674
+ * between, through a writer given no revision, is not refused but reported:
675
+ * `UnpinnedWrites`, a warning, to `diagnostics`.
513
676
  *
514
677
  * ```ts
515
678
  * GuardServer.validate(Policy, { entities: [Todo, Project], domain: Data, server: Server })
@@ -517,6 +680,8 @@ const GuardServer = {
517
680
  */
518
681
  validate: (policy, config) => {
519
682
  const byName = new Map(config.entities.map((entity) => [entity.name, entity]));
683
+ /** Whether a reached member has a Read rule; one of an Entity not validated has none checked. */
684
+ const hidesFromReach = ({ entity, key }) => Option.exists(Option.flatMap(Option.fromUndefinedOr(byName.get(entity)), attached), (attachment) => readRuled(attachment, key));
520
685
  /** Whether who may read the rows of `entity` depends on who is asking. */
521
686
  const rowsRuled = (entity) => Option.exists(Option.flatMap(Option.fromUndefinedOr(entity), attached), (attachment) => readRowsRuled(attachment));
522
687
  const undeclared = [...config.server.queries.keys()].filter((query) => !config.domain.registry.queries.has(query)).map((query) => `query ${query} is served, but the domain does not declare it`);
@@ -536,21 +701,38 @@ const GuardServer = {
536
701
  });
537
702
  const bodyProblems = [...config.domain.registry.queries].flatMap(([queryName, { body }]) => {
538
703
  if (body === void 0 || body.entity.name !== name) return [];
539
- const { predicate, order } = Query.dependencies(body);
540
- 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`)];
704
+ const { predicate, order, reaches } = Query.dependencies(body);
705
+ const reached = [...new Set(reachedMembers(reaches).filter(hidesFromReach).map(({ entity, key }) => `query ${queryName} reaches ${entity}'s ${key}, which has a Read rule`))];
706
+ return [
707
+ ...hiddenOf(attachment, predicate).map((member) => `query ${queryName} filters ${name} by ${member}, which has a Read rule`),
708
+ ...hiddenOf(attachment, order).map((member) => `query ${queryName} orders ${name} by ${member}, which has a Read rule`),
709
+ ...reached
710
+ ];
541
711
  });
542
712
  const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) => {
543
713
  if (source.writes === void 0 || source.writes.entity !== name) return [];
544
714
  if (!writeRules.has(source.writes.writer, policy, entity)) return [`write ${mutation} writes ${name} without its write rules`];
545
715
  const { write, writer } = source.writes;
716
+ const interaction = Match.valueTags(write, {
717
+ Insert: () => "Create",
718
+ Update: () => "Update",
719
+ Delete: () => "Delete"
720
+ });
721
+ const open = attachment.unguarded === "allow" && Option.isNone(surfaceOf(attachment, {
722
+ _tag: "Row",
723
+ interaction
724
+ })) ? [`write ${mutation} ${interaction === "Create" ? "creates" : `${interaction.toLowerCase()}s`} ${name}, which has no ${interaction} rule, so unguarded: 'allow' lets anyone; give it one, or [Guards.anyone] to say anyone may`] : [];
546
725
  const when = Option.match(write.when, {
547
726
  onNone: () => [],
548
727
  onSome: (body) => hiddenOf(attachment, Query.dependencies(body).predicate)
549
728
  });
729
+ const computed = write.assignments.flatMap((assignment) => hiddenOf(attachment, dependenciesOf(assignment.expr).fields).map((member) => `write ${mutation} computes ${name}'s ${assignment.field.key} from its ${member}, which has a Read rule`));
550
730
  const expected = write.expect?.field.key;
551
731
  const pin = typeof writer === "object" && writer !== null ? pins.get(writer) : void 0;
552
732
  return [
733
+ ...open,
553
734
  ...when.map((member) => `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`),
735
+ ...computed,
554
736
  ...expected !== void 0 && readRuled(attachment, expected) ? [`write ${mutation} expects ${name}'s ${expected}, which has a Read rule`] : [],
555
737
  ...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)}`] : []
556
738
  ];
@@ -559,15 +741,20 @@ const GuardServer = {
559
741
  onNone: () => [],
560
742
  onSome: (source) => [...source.shared ?? []]
561
743
  });
562
- const sharedProblems = [...shared.length > 0 && readRowsRuled(attachment) ? [`${name}'s Source shares ${shared.join(", ")}, but its rows have a Read rule`] : [], ...shared.flatMap((member) => {
563
- const own = readRuled(attachment, member) ? [`${name}'s Source shares ${member}, which has a Read rule`] : [];
564
- if (!Object.hasOwn(entity.relations, member)) return own;
565
- const target = entity.relations[member].target().name;
566
- if (!byName.has(target)) return [...own, `${name}'s Source shares ${member}, whose ${target} is not validated`];
567
- return rowsRuled(byName.get(target)) ? [...own, `${name}'s Source shares ${member}, whose rows have a Read rule`] : own;
568
- })];
744
+ const sharedProblems = [
745
+ ...shared.length > 0 && readRowsRuled(attachment) ? [`${name}'s Source shares ${shared.join(", ")}, but its rows have a Read rule`] : [],
746
+ ...shared.includes("may") && asksMay(entity, ["may"]) ? [`${name}'s Source shares may, which is answered for each reader`] : [],
747
+ ...shared.flatMap((member) => {
748
+ const own = readRuled(attachment, member) ? [`${name}'s Source shares ${member}, which has a Read rule`] : [];
749
+ if (!Object.hasOwn(entity.relations, member)) return own;
750
+ const target = entity.relations[member].target().name;
751
+ if (!byName.has(target)) return [...own, `${name}'s Source shares ${member}, whose ${target} is not validated`];
752
+ return rowsRuled(byName.get(target)) ? [...own, `${name}'s Source shares ${member}, whose rows have a Read rule`] : own;
753
+ })
754
+ ];
569
755
  const operatorProblems = attachedRules(attachment).flatMap((rule) => rule._tag === "RowGuard" ? Query.unsupported(rule.query, supported, policy.operators).map((missing) => `${name}'s ${rule.name} calls ${missing}, which the policy does not run`) : []);
570
- const liveProblems = config.server.live.has(name) ? [`${name} has a live Source of its own; serve its changes through a live hub`] : [];
756
+ const live = Option.fromUndefinedOr(config.server.live.get(name));
757
+ const liveProblems = Option.exists(live, ({ reads }) => !Option.exists(source, (checked) => checked === reads)) ? [`${name}'s live Source does not read through its guarded Source; poll through that Source (pollLive) or serve changes through a live hub`] : [];
571
758
  return [
572
759
  ...sourceProblems,
573
760
  ...queryProblems,
@@ -581,87 +768,71 @@ const GuardServer = {
581
768
  }));
582
769
  const problems = [...undeclared, ...entityProblems];
583
770
  if (problems.length > 0) throw new Error(`[foldkit-guard] GuardServer.validate: ${problems.join("; ")}`);
584
- const unpinnedWrites = [...config.server.mutations].flatMap(([mutation, source]) => {
585
- const writer = source.writes?.writer;
771
+ const updated = new Set([...config.server.mutations.values()].flatMap((source) => source.writes === void 0 ? [] : [source.writes]).filter((writes) => writes.write._tag === "Update").map((writes) => writes.entity));
772
+ const unpinned = [...config.server.mutations].flatMap(([mutation, source]) => {
773
+ const writes = source.writes;
774
+ if (writes === void 0) return [];
775
+ const writer = writes.writer;
586
776
  const pin = typeof writer === "object" && writer !== null ? pins.get(writer) : void 0;
587
- return pin !== void 0 && Option.isNone(pin) ? [mutation] : [];
777
+ if (pin === void 0 || Option.isSome(pin)) return [];
778
+ return Match.valueTags(writes.write, {
779
+ Update: () => true,
780
+ Delete: () => updated.has(writes.entity),
781
+ Insert: () => false
782
+ }) ? [mutation] : [];
588
783
  });
589
- 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 }`);
784
+ if (unpinned.length > 0) {
785
+ const report = Diagnostics.report(unpinnedWrites(unpinned));
786
+ const { diagnostics } = config;
787
+ Effect.runFork(diagnostics === void 0 ? report : Effect.provideService(report, Diagnostics.Reporter, diagnostics));
788
+ }
590
789
  }
591
790
  };
592
791
  /** Whether a read asks for `may`, of an Entity that has it (`Guards.may`). */
593
792
  const asksMay = (entity, fields) => fields.includes("may") && Object.hasOwn(entity.derived, "may");
594
- /** The interactions a row answers `may` for: `Update`, `Delete`, and each one the set named. */
595
- const builtInRow = /* @__PURE__ */ new Set([
596
- "Read",
597
- "Create",
598
- "Update",
599
- "Delete"
600
- ]);
601
793
  /**
602
794
  * `may` for `principal`: each row interaction's rule, each member's own
603
795
  * `Update`, each relation's `Link` and `Unlink`, decided once and held over
604
796
  * each row as a write's check would hold them over it as it is.
605
797
  */
606
- const mayOf = (entity, policy, principal) => {
607
- const attachment = attached(entity);
608
- const named = Option.match(attachment, {
609
- onNone: () => [],
610
- onSome: ({ row }) => Object.keys(row).filter((interaction) => !builtInRow.has(interaction))
611
- });
612
- const ruledMembers = Option.match(attachment, {
613
- onNone: () => [],
614
- onSome: ({ members }) => Object.keys(members)
615
- });
616
- const ruledRelations = Option.match(attachment, {
617
- onNone: () => [],
618
- onSome: ({ relations }) => Object.keys(relations)
619
- });
620
- return Effect.map(Effect.all([
621
- Effect.forEach([
622
- "Update",
623
- "Delete",
624
- ...named
625
- ], (interaction) => Effect.map(policy.writable(entity, principal, interaction), (rule) => [interaction, rule])),
626
- policy.writeMembers(entity, principal, ruledMembers, "Update"),
627
- Effect.forEach(ruledRelations, (relation) => Effect.map(Effect.all([policy.linkable(entity, principal, relation, "Link"), policy.linkable(entity, principal, relation, "Unlink")]), ([link, unlink]) => ({
628
- relation,
629
- link,
630
- unlink
631
- })))
632
- ]), ([rows, members, relations]) => {
633
- const input = policy.inputOf(principal);
634
- const holds = (condition, values) => Condition.holds(condition, values, input, () => false, policy.operators);
635
- const allows = (rule, values) => Option.match(rule, {
636
- onNone: () => true,
637
- onSome: ({ condition }) => holds(condition, values)
638
- });
639
- const conditions = [
640
- ...rows.map(([, { condition }]) => condition),
641
- ...members.map(({ condition }) => condition),
642
- ...relations.flatMap(({ link, unlink }) => [...Option.toArray(link), ...Option.toArray(unlink)].map(({ condition }) => condition))
643
- ];
644
- return {
645
- fields: ["id", ...new Set(conditions.flatMap(Condition.members))],
646
- answer: (values) => ({
647
- row: Object.fromEntries(rows.map(([interaction, { condition }]) => [interaction, holds(condition, values)])),
648
- reasons: Object.fromEntries(rows.flatMap(([interaction, { condition, deny }]) => holds(condition, values) ? [] : Match.valueTags(deny, {
649
- Explain: ({ reason }) => [[interaction, reason]],
650
- Forbidden: () => [],
651
- NotFound: () => [],
652
- Omit: () => [],
653
- Redact: () => []
654
- }))),
655
- members: Object.fromEntries(members.map(({ member, condition }) => [member, holds(condition, values)])),
656
- relations: Object.fromEntries(relations.map(({ relation, link, unlink }) => [relation, {
657
- Link: allows(link, values),
658
- Unlink: allows(unlink, values)
659
- }]))
660
- })
661
- };
662
- });
663
- };
798
+ const mayOf = (entity, policy, principal) => Effect.map(mayRules(entity, {
799
+ row: (interaction) => policy.writable(entity, principal, interaction),
800
+ members: (members) => policy.writeMembers(entity, principal, members, "Update"),
801
+ relation: (relation, interaction) => policy.linkable(entity, principal, relation, interaction)
802
+ }), (rules) => {
803
+ const input = policy.inputOf(principal);
804
+ return {
805
+ fields: ["id", ...new Set(mayConditions(rules).flatMap(Condition.members))],
806
+ answer: (values) => answerOf(rules, (condition) => Condition.decided(Condition.residual(condition, values, input, policy.operators)))
807
+ };
808
+ });
664
809
  /** A refused write as the client receives it: the sentence an `explain` gave, or none. */
810
+ /** The words a refusal gives: an `explain`'s, or none. */
811
+ const explained = (deny) => Match.valueTags(deny, {
812
+ Explain: ({ reason }) => Option.some(reason),
813
+ Forbidden: () => Option.none(),
814
+ NotFound: () => Option.none(),
815
+ Omit: () => Option.none(),
816
+ Redact: () => Option.none()
817
+ });
818
+ /**
819
+ * What is left of a condition, as a writer's statement judges it: each row
820
+ * guard a body over the row, its input the principal's (`G.inputOf`), and its
821
+ * context the one it was decided for. An inherited Read, which a writer
822
+ * refuses, requires what no row holds.
823
+ */
824
+ const requirementOf = (condition, input) => Match.valueTags(condition, {
825
+ Always: () => RowRequirement.All({ of: [] }),
826
+ Never: () => RowRequirement.Any({ of: [] }),
827
+ Row: ({ guard, context }) => RowRequirement.Body({
828
+ query: guard.query,
829
+ input,
830
+ context
831
+ }),
832
+ Inherit: () => RowRequirement.Any({ of: [] }),
833
+ And: ({ conditions }) => RowRequirement.All({ of: conditions.map((each) => requirementOf(each, input)) }),
834
+ Or: ({ conditions }) => RowRequirement.Any({ of: conditions.map((each) => requirementOf(each, input)) })
835
+ });
665
836
  const refused = (deny) => Match.valueTags(deny, {
666
837
  Explain: ({ reason }) => RemoteServer.forbid(reason),
667
838
  Forbidden: () => RemoteServer.forbid(),