foldkit-guard 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.mjs CHANGED
@@ -5,8 +5,8 @@ import "./me-C-gX1paZ.mjs";
5
5
  import { n as rowRules, r as writeRules, t as memberRules } from "./placed-CGyo-NRR.mjs";
6
6
  import { Effect, Match, Option, Schema, SchemaAST, identity } from "effect";
7
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";
8
+ import { Diagnostics, RemoteForbidden } from "foldkit-remote";
9
+ import { DeleteOutcome, RemoteInvalid, RemoteServer, RemoteServerError, RowRequirement } from "foldkit-remote-server";
10
10
  // src/diagnostics.ts
11
11
  const source = "foldkit-guard";
12
12
  const computeRefused = (entity, error) => ({
@@ -219,7 +219,8 @@ const GuardServer = {
219
219
  * to a member is that member's own change. An `Unlink` rule holds over the
220
220
  * row before alone. A create's rules hold over the values it proposes, where a field the
221
221
  * create leaves unset matches no guard, not even one for an empty value. A refusal is
222
- * `Forbidden`, with the sentence an `explain` gave; the write never runs.
222
+ * `Forbidden`, with the sentence an `explain` gave, or `Unauthenticated` for a
223
+ * visitor; the write never runs.
223
224
  *
224
225
  * What the Entity sets from the write's context (`Entity.sets`: who asks,
225
226
  * when) reaches a create or an update already set by `RemoteServer.write`,
@@ -237,8 +238,18 @@ const GuardServer = {
237
238
  * revision the row read is not at is a `Conflict`, decided before any rule;
238
239
  * an input may expect only the field the writer pins.
239
240
  *
241
+ * A delete that cascades (`Relation.one(…, { onDelete: 'cascade' })`) holds
242
+ * each row it takes to that row's own `Delete` rule, for the same person, in
243
+ * the statement that deletes (#348): one refused, and the whole delete is
244
+ * `Forbidden`, naming the Entity, and nothing is removed. A relation declared
245
+ * `authorizedBy: 'parent'` lets whoever may delete the row take the rows
246
+ * pointing at it through that relation unjudged. The rules of an Entity
247
+ * taken under its own are read from its guarded descriptor, given as
248
+ * `children`; one missing is refused where the writer is made.
249
+ *
240
250
  * ```ts
241
251
  * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
252
+ * GuardServer.writer(Post, Policy, writer(Db.Post), { children: [Like] })
242
253
  * ```
243
254
  */
244
255
  writer: (entity, policy, writer, options = {}) => {
@@ -263,6 +274,8 @@ const GuardServer = {
263
274
  }))
264
275
  });
265
276
  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`);
277
+ const judging = cascadeJudges(entity, options.children ?? []);
278
+ if (judging.length > 0 && (writer.requires !== true || writer.cascades !== true)) throw new Error(`[foldkit-guard] GuardServer.writer: a delete of ${entity.name} takes ${judging.map((child) => child.name).join(", ")} rows under their own Delete rule, which only a writer judging rules in its statement and removing what cascades can hold it to (foldkit-remote-drizzle's writer); this writer does not`);
266
279
  /**
267
280
  * The row rule over `values` as far as one row decides it: refused where it
268
281
  * fails, and otherwise what the writer's statement must still judge.
@@ -515,6 +528,7 @@ const GuardServer = {
515
528
  ...revision === void 0 ? {} : { pins: true },
516
529
  ...writer.ledger === true ? { ledger: true } : {},
517
530
  ...writer.invariants === true ? { invariants: true } : {},
531
+ ...writer.cascades === true ? { cascades: true } : {},
518
532
  refuses: (write) => [
519
533
  ...writer.refuses?.(write) ?? [],
520
534
  ...write.assignments.flatMap(({ field, expr }) => Expr.unsupported([expr], {
@@ -567,28 +581,39 @@ const GuardServer = {
567
581
  })), proposed, principal);
568
582
  return yield* Effect.mapError(writer.insert(context), told);
569
583
  })),
570
- delete: (context) => Effect.andThen(discloses(context.expect, context.when), () => pinned(context.id, context.expect, (outcome) => outcome === "moved", () => Effect.gen(function* () {
584
+ delete: (context) => Effect.andThen(discloses(context.expect, context.when), () => pinned(context.id, context.expect, DeleteOutcome.$is("Moved"), () => Effect.gen(function* () {
571
585
  const row = yield* policy.writable(entity, context.principal, "Delete");
572
586
  const current = yield* read({
573
587
  id: context.id,
574
588
  fields: fieldsOf([row], versionFields(context.expect)),
575
589
  principal: context.principal
576
590
  });
577
- if (Option.isNone(current)) return "absent";
578
- if (moved(context.expect, current.value)) return "moved";
591
+ if (Option.isNone(current)) return DeleteOutcome.Absent();
592
+ if (moved(context.expect, current.value)) return DeleteOutcome.Moved();
579
593
  const requires = yield* rowRule(row, current.value, context.principal);
594
+ const cascading = yield* Effect.forEach(judging, (child) => Effect.map(policy.writable(child, context.principal, "Delete"), ({ condition, deny }) => ({
595
+ entity: child.name,
596
+ requires: required(condition, deny, context.principal)
597
+ })));
580
598
  return yield* writer.delete({
581
599
  ...context,
582
600
  expect: pin(context.expect, current.value),
583
601
  ...Option.match(requires, {
584
602
  onNone: () => ({}),
585
603
  onSome: (held) => ({ requires: held })
586
- })
604
+ }),
605
+ ...judging.length === 0 ? {} : { cascading }
587
606
  });
588
607
  })))
589
608
  };
590
- pins.set(guarded, Option.fromUndefinedOr(revision));
591
- return writeRules.add(guarded, policy, [entity]);
609
+ const asked = {
610
+ ...guarded,
611
+ update: (context) => signInFirst(context.principal, guarded.update(context)),
612
+ insert: (context) => signInFirst(context.principal, guarded.insert(context)),
613
+ delete: (context) => signInFirst(context.principal, guarded.delete(context))
614
+ };
615
+ pins.set(asked, Option.fromUndefinedOr(revision));
616
+ return writeRules.add(asked, policy, [entity]);
592
617
  },
593
618
  /**
594
619
  * A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for
@@ -597,8 +622,8 @@ const GuardServer = {
597
622
  * rule must hold over it; a row its writer may not see is refused. With no
598
623
  * `id` (a create), the rule must hold of who is asking alone, a field it
599
624
  * reads matching no guard. `run` is given the row as read: its fields the
600
- * rule reads, its `id`, and `fields`. A refusal is `Forbidden`; `run` never
601
- * runs. What `run` writes is its own: check members it sets there. Each
625
+ * rule reads, its `id`, and `fields`. A refusal is `Forbidden`, or
626
+ * `Unauthenticated` for a visitor; `run` never runs. What `run` writes is its own: check members it sets there. Each
602
627
  * row of `entity` its answer carries is read back through `source`, so the
603
628
  * answer shows its writer only what they may see, a row it hid from them
604
629
  * as deleted.
@@ -656,7 +681,7 @@ const GuardServer = {
656
681
  ...context,
657
682
  row
658
683
  }), principal);
659
- }));
684
+ }).pipe((answered) => signInFirst(context.principal, answered)));
660
685
  },
661
686
  /**
662
687
  * Checks, at startup, that `server` applies the guards of `entities`, the
@@ -816,6 +841,35 @@ const explained = (deny) => Match.valueTags(deny, {
816
841
  Redact: () => Option.none()
817
842
  });
818
843
  /**
844
+ * The guarded descriptor of each Entity a delete of `root`'s row takes rows of
845
+ * under their own `Delete` rule (`authorizedBy: 'child'`), followed through
846
+ * every cascade, `root` itself for a cascade into its own Entity. Refused
847
+ * where one is not among `children`, and where a child is given that no
848
+ * such cascade reaches, so the option cannot quietly say nothing.
849
+ */
850
+ const cascadeJudges = (root, children) => {
851
+ const given = new Map(children.map((child) => [child.identity.token, child]));
852
+ given.set(root.identity.token, root);
853
+ const judged = /* @__PURE__ */ new Map();
854
+ const seen = /* @__PURE__ */ new Set([root.identity.token]);
855
+ const queue = [root];
856
+ for (let next = queue.shift(); next !== void 0; next = queue.shift()) for (const { relation, owner } of Entity.cascading(next)) {
857
+ const token = owner.identity.token;
858
+ if (Option.getOrElse(relation.authorizedBy, () => "child") === "child" && !judged.has(token)) {
859
+ const guarded = given.get(token);
860
+ if (guarded === void 0) throw new Error(`[foldkit-guard] GuardServer.writer: a delete of ${root.name} takes ${owner.name} rows under their own Delete rule (${owner.name}.${relation.key}); give ${owner.name}'s guarded Entity as children: [${owner.name}], or declare the relation authorizedBy: 'parent'`);
861
+ judged.set(token, guarded);
862
+ }
863
+ if (!seen.has(token)) {
864
+ seen.add(token);
865
+ queue.push(owner);
866
+ }
867
+ }
868
+ const unused = children.filter((child) => !judged.has(child.identity.token));
869
+ if (unused.length > 0) throw new Error(`[foldkit-guard] GuardServer.writer: a delete of ${root.name} takes no ${unused.map((child) => child.name).join(", ")} rows under their own Delete rule, so children has nothing to judge them by`);
870
+ return [...judged.values()];
871
+ };
872
+ /**
819
873
  * What is left of a condition, as a writer's statement judges it: each row
820
874
  * guard a body over the row, its input the principal's (`G.inputOf`), and its
821
875
  * context the one it was decided for. An inherited Read, which a writer
@@ -833,6 +887,13 @@ const requirementOf = (condition, input) => Match.valueTags(condition, {
833
887
  And: ({ conditions }) => RowRequirement.All({ of: conditions.map((each) => requirementOf(each, input)) }),
834
888
  Or: ({ conditions }) => RowRequirement.Any({ of: conditions.map((each) => requirementOf(each, input)) })
835
889
  });
890
+ /**
891
+ * A visitor's refused write as a sign-in it needs: `Unauthenticated`, never
892
+ * `Forbidden`, so a client tells a session that ended (its cookie gone, it
893
+ * asks as a visitor) from a person refused, and a durable write waits for the
894
+ * sign-in rather than failing (#403). A refusal's words go with it.
895
+ */
896
+ const signInFirst = (principal, write) => Option.isSome(principal) ? write : Effect.mapError(write, (error) => error instanceof RemoteForbidden ? RemoteServer.unauthenticated(error.reason) : error);
836
897
  const refused = (deny) => Match.valueTags(deny, {
837
898
  Explain: ({ reason }) => RemoteServer.forbid(reason),
838
899
  Forbidden: () => RemoteServer.forbid(),