foldkit-guard 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +209 -44
- package/dist/agent.d.mts +1 -1
- package/dist/agent.mjs +1 -1
- package/dist/{attach-CRCF5XHS.mjs → attach-CEGlbWu5.mjs} +17 -2
- package/dist/attach-CEGlbWu5.mjs.map +1 -0
- package/dist/{attach-BepaL930.d.mts → attach-DPgyv78F.d.mts} +83 -8
- package/dist/attach-DPgyv78F.d.mts.map +1 -0
- package/dist/{condition-Dx54lL7v.mjs → condition-dNSbUHzE.mjs} +98 -10
- package/dist/condition-dNSbUHzE.mjs.map +1 -0
- package/dist/drizzle.d.mts +1 -1
- package/dist/drizzle.mjs +8 -6
- package/dist/drizzle.mjs.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +34 -17
- package/dist/index.mjs.map +1 -1
- package/dist/may-DprCmMgK.mjs +200 -0
- package/dist/may-DprCmMgK.mjs.map +1 -0
- package/dist/{me-BYpuVqJE.mjs → me-C-gX1paZ.mjs} +3 -3
- package/dist/{me-BYpuVqJE.mjs.map → me-C-gX1paZ.mjs.map} +1 -1
- package/dist/media.d.mts +1 -1
- package/dist/{placed-BvdNmZJu.mjs → placed-CGyo-NRR.mjs} +2 -2
- package/dist/{placed-BvdNmZJu.mjs.map → placed-CGyo-NRR.mjs.map} +1 -1
- package/dist/server.d.mts +50 -17
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +264 -145
- package/dist/server.mjs.map +1 -1
- package/dist/sync.d.mts +5 -3
- package/dist/sync.d.mts.map +1 -1
- package/dist/sync.mjs +18 -8
- package/dist/sync.mjs.map +1 -1
- package/package.json +19 -18
- package/dist/attach-BepaL930.d.mts.map +0 -1
- package/dist/attach-CRCF5XHS.mjs.map +0 -1
- package/dist/condition-Dx54lL7v.mjs.map +0 -1
- package/dist/may-DzCAt_5M.mjs +0 -75
- 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-
|
|
2
|
-
import { t as Condition } from "./condition-
|
|
3
|
-
import "./
|
|
4
|
-
import
|
|
5
|
-
import {
|
|
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";
|
|
6
7
|
import { Entity, Expr, Query, QueryEvaluateError, Write, dependenciesOf, supported } from "foldkit-entity";
|
|
7
|
-
import {
|
|
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
|
|
149
|
-
*
|
|
150
|
-
*
|
|
151
|
-
* it
|
|
152
|
-
*
|
|
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
|
-
*
|
|
157
|
-
*
|
|
158
|
-
* a rule over
|
|
159
|
-
*
|
|
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
|
|
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))), {
|
|
@@ -292,19 +382,20 @@ const GuardServer = {
|
|
|
292
382
|
}
|
|
293
383
|
});
|
|
294
384
|
/**
|
|
295
|
-
* The answer the writer's ledger holds for this operation,
|
|
296
|
-
* a retry of a write that landed is answered as
|
|
297
|
-
* again over a row that
|
|
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.
|
|
298
388
|
*/
|
|
299
|
-
const answeredOr = (context, write) => {
|
|
389
|
+
const answeredOr = (context, answered, write) => {
|
|
300
390
|
const recorded = writer.recorded;
|
|
301
391
|
if (recorded === void 0 || Option.isNone(context.operation)) return write();
|
|
302
392
|
return Effect.flatMap(recorded({
|
|
303
393
|
operation: context.operation.value,
|
|
394
|
+
request: context.request,
|
|
304
395
|
id: context.id,
|
|
305
396
|
principal: context.principal
|
|
306
397
|
}), Option.match({
|
|
307
|
-
onSome: (answer) => Effect.succeed(
|
|
398
|
+
onSome: (answer) => Effect.succeed(answered(answer)),
|
|
308
399
|
onNone: write
|
|
309
400
|
}));
|
|
310
401
|
};
|
|
@@ -337,7 +428,11 @@ const GuardServer = {
|
|
|
337
428
|
], [
|
|
338
429
|
...Object.keys(context.links),
|
|
339
430
|
...versionFields(context.expect),
|
|
340
|
-
...Write.boundReads(context)
|
|
431
|
+
...Write.boundReads(context),
|
|
432
|
+
...Condition.reachedFrom(rules.row.condition, {
|
|
433
|
+
entity: entity.name,
|
|
434
|
+
id: context.id
|
|
435
|
+
})
|
|
341
436
|
]),
|
|
342
437
|
principal: context.principal
|
|
343
438
|
});
|
|
@@ -349,8 +444,9 @@ const GuardServer = {
|
|
|
349
444
|
/**
|
|
350
445
|
* The row `context` would leave `before` as. An operator's refusal (text
|
|
351
446
|
* holding NUL, an implementation that throws) is a server error, as the
|
|
352
|
-
* writer answers what it cannot compile:
|
|
353
|
-
* an implementation's own message may say anything.
|
|
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
|
|
354
450
|
* work out at all: judging its old value would let a rule over it pass.
|
|
355
451
|
*/
|
|
356
452
|
const leaves = (before, context) => Effect.suspend(() => {
|
|
@@ -360,7 +456,7 @@ const GuardServer = {
|
|
|
360
456
|
return applied.unknown.length === 0 ? Effect.succeed(applied.row) : unworkable;
|
|
361
457
|
} catch (error) {
|
|
362
458
|
if (!(error instanceof QueryEvaluateError)) throw error;
|
|
363
|
-
return
|
|
459
|
+
return Diagnostics.report(computeRefused(entity.name, error)).pipe(Effect.andThen(unworkable));
|
|
364
460
|
}
|
|
365
461
|
});
|
|
366
462
|
/** The rules, over the row as it is and as the write would leave it. */
|
|
@@ -371,7 +467,7 @@ const GuardServer = {
|
|
|
371
467
|
id: context.id,
|
|
372
468
|
relations: linked
|
|
373
469
|
});
|
|
374
|
-
const
|
|
470
|
+
const was = Option.some(Option.match(stored, {
|
|
375
471
|
onNone: () => ({
|
|
376
472
|
links: before,
|
|
377
473
|
exact: false
|
|
@@ -380,17 +476,36 @@ const GuardServer = {
|
|
|
380
476
|
links,
|
|
381
477
|
exact: true
|
|
382
478
|
})
|
|
383
|
-
}))
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
...relations
|
|
388
|
-
], before, principal);
|
|
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);
|
|
389
483
|
const after = {
|
|
390
484
|
...yield* leaves(before, context),
|
|
391
485
|
...Object.fromEntries(Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]))
|
|
392
486
|
};
|
|
393
|
-
yield*
|
|
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;
|
|
394
509
|
});
|
|
395
510
|
const guarded = {
|
|
396
511
|
entity: writer.entity,
|
|
@@ -414,31 +529,22 @@ const GuardServer = {
|
|
|
414
529
|
fields: seen,
|
|
415
530
|
principal
|
|
416
531
|
}), principal, fields, id),
|
|
417
|
-
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* () {
|
|
418
533
|
const rules = yield* updateRules(context);
|
|
419
534
|
const current = yield* readBefore(context, rules);
|
|
420
535
|
if (Option.isNone(current)) return yield* Effect.fail(refused(rules.row.deny));
|
|
421
536
|
if (moved(context.expect, current.value)) return Option.none();
|
|
422
|
-
yield* decideUpdate(context, rules, current.value);
|
|
537
|
+
const requires = yield* decideUpdate(context, rules, current.value);
|
|
423
538
|
return yield* writer.update({
|
|
424
539
|
...context,
|
|
425
|
-
expect: pin(context.expect, current.value)
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
const preset = presets.find(({ field }) => Object.hasOwn(given.values, field));
|
|
430
|
-
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` });
|
|
431
|
-
if (presets.length > 0 && Option.isNone(given.principal)) return yield* Effect.fail(RemoteServer.forbid());
|
|
432
|
-
const context = Option.match(given.principal, {
|
|
433
|
-
onNone: () => given,
|
|
434
|
-
onSome: (user) => ({
|
|
435
|
-
...given,
|
|
436
|
-
values: {
|
|
437
|
-
...given.values,
|
|
438
|
-
...Object.fromEntries(presets.map(({ field, value }) => [field, value(user)]))
|
|
439
|
-
}
|
|
540
|
+
expect: pin(context.expect, current.value),
|
|
541
|
+
...Option.match(requires, {
|
|
542
|
+
onNone: () => ({}),
|
|
543
|
+
onSome: (held) => ({ requires: held })
|
|
440
544
|
})
|
|
441
545
|
});
|
|
546
|
+
})))), told),
|
|
547
|
+
insert: (context) => answeredOr(context, identity, () => Effect.gen(function* () {
|
|
442
548
|
const { principal, values, links } = context;
|
|
443
549
|
const row = yield* policy.writable(entity, principal, "Create");
|
|
444
550
|
const members = yield* policy.writeMembers(entity, principal, Object.keys(values), "Create");
|
|
@@ -460,7 +566,7 @@ const GuardServer = {
|
|
|
460
566
|
condition: Condition.unsetting(rule.condition, unset)
|
|
461
567
|
})), proposed, principal);
|
|
462
568
|
return yield* Effect.mapError(writer.insert(context), told);
|
|
463
|
-
}),
|
|
569
|
+
})),
|
|
464
570
|
delete: (context) => Effect.andThen(discloses(context.expect, context.when), () => pinned(context.id, context.expect, (outcome) => outcome === "moved", () => Effect.gen(function* () {
|
|
465
571
|
const row = yield* policy.writable(entity, context.principal, "Delete");
|
|
466
572
|
const current = yield* read({
|
|
@@ -470,10 +576,14 @@ const GuardServer = {
|
|
|
470
576
|
});
|
|
471
577
|
if (Option.isNone(current)) return "absent";
|
|
472
578
|
if (moved(context.expect, current.value)) return "moved";
|
|
473
|
-
yield*
|
|
579
|
+
const requires = yield* rowRule(row, current.value, context.principal);
|
|
474
580
|
return yield* writer.delete({
|
|
475
581
|
...context,
|
|
476
|
-
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
|
+
})
|
|
477
587
|
});
|
|
478
588
|
})))
|
|
479
589
|
};
|
|
@@ -555,11 +665,14 @@ const GuardServer = {
|
|
|
555
665
|
* `GuardServer.memory`), its Source applies its members' and relations'
|
|
556
666
|
* (`GuardServer.filter`), and each declared write of it lands through
|
|
557
667
|
* `GuardServer.writer`, all built from `policy`; and that no query's body
|
|
558
|
-
* filters or orders by a member with a Read rule,
|
|
559
|
-
*
|
|
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
|
|
560
671
|
* every row, and a bare writer would take every write; this throws instead,
|
|
561
672
|
* naming each. A handler (`RemoteServer.mutation`) writes what its code
|
|
562
|
-
* 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`.
|
|
563
676
|
*
|
|
564
677
|
* ```ts
|
|
565
678
|
* GuardServer.validate(Policy, { entities: [Todo, Project], domain: Data, server: Server })
|
|
@@ -567,6 +680,8 @@ const GuardServer = {
|
|
|
567
680
|
*/
|
|
568
681
|
validate: (policy, config) => {
|
|
569
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));
|
|
570
685
|
/** Whether who may read the rows of `entity` depends on who is asking. */
|
|
571
686
|
const rowsRuled = (entity) => Option.exists(Option.flatMap(Option.fromUndefinedOr(entity), attached), (attachment) => readRowsRuled(attachment));
|
|
572
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`);
|
|
@@ -586,13 +701,27 @@ const GuardServer = {
|
|
|
586
701
|
});
|
|
587
702
|
const bodyProblems = [...config.domain.registry.queries].flatMap(([queryName, { body }]) => {
|
|
588
703
|
if (body === void 0 || body.entity.name !== name) return [];
|
|
589
|
-
const { predicate, order } = Query.dependencies(body);
|
|
590
|
-
|
|
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
|
+
];
|
|
591
711
|
});
|
|
592
712
|
const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) => {
|
|
593
713
|
if (source.writes === void 0 || source.writes.entity !== name) return [];
|
|
594
714
|
if (!writeRules.has(source.writes.writer, policy, entity)) return [`write ${mutation} writes ${name} without its write rules`];
|
|
595
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`] : [];
|
|
596
725
|
const when = Option.match(write.when, {
|
|
597
726
|
onNone: () => [],
|
|
598
727
|
onSome: (body) => hiddenOf(attachment, Query.dependencies(body).predicate)
|
|
@@ -601,6 +730,7 @@ const GuardServer = {
|
|
|
601
730
|
const expected = write.expect?.field.key;
|
|
602
731
|
const pin = typeof writer === "object" && writer !== null ? pins.get(writer) : void 0;
|
|
603
732
|
return [
|
|
733
|
+
...open,
|
|
604
734
|
...when.map((member) => `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`),
|
|
605
735
|
...computed,
|
|
606
736
|
...expected !== void 0 && readRuled(attachment, expected) ? [`write ${mutation} expects ${name}'s ${expected}, which has a Read rule`] : [],
|
|
@@ -611,15 +741,20 @@ const GuardServer = {
|
|
|
611
741
|
onNone: () => [],
|
|
612
742
|
onSome: (source) => [...source.shared ?? []]
|
|
613
743
|
});
|
|
614
|
-
const sharedProblems = [
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
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
|
+
];
|
|
621
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`) : []);
|
|
622
|
-
const
|
|
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`] : [];
|
|
623
758
|
return [
|
|
624
759
|
...sourceProblems,
|
|
625
760
|
...queryProblems,
|
|
@@ -633,87 +768,71 @@ const GuardServer = {
|
|
|
633
768
|
}));
|
|
634
769
|
const problems = [...undeclared, ...entityProblems];
|
|
635
770
|
if (problems.length > 0) throw new Error(`[foldkit-guard] GuardServer.validate: ${problems.join("; ")}`);
|
|
636
|
-
const
|
|
637
|
-
|
|
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;
|
|
638
776
|
const pin = typeof writer === "object" && writer !== null ? pins.get(writer) : void 0;
|
|
639
|
-
|
|
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] : [];
|
|
640
783
|
});
|
|
641
|
-
if (
|
|
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
|
+
}
|
|
642
789
|
}
|
|
643
790
|
};
|
|
644
791
|
/** Whether a read asks for `may`, of an Entity that has it (`Guards.may`). */
|
|
645
792
|
const asksMay = (entity, fields) => fields.includes("may") && Object.hasOwn(entity.derived, "may");
|
|
646
|
-
/** The interactions a row answers `may` for: `Update`, `Delete`, and each one the set named. */
|
|
647
|
-
const builtInRow = /* @__PURE__ */ new Set([
|
|
648
|
-
"Read",
|
|
649
|
-
"Create",
|
|
650
|
-
"Update",
|
|
651
|
-
"Delete"
|
|
652
|
-
]);
|
|
653
793
|
/**
|
|
654
794
|
* `may` for `principal`: each row interaction's rule, each member's own
|
|
655
795
|
* `Update`, each relation's `Link` and `Unlink`, decided once and held over
|
|
656
796
|
* each row as a write's check would hold them over it as it is.
|
|
657
797
|
*/
|
|
658
|
-
const mayOf = (entity, policy, principal) => {
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
}
|
|
668
|
-
|
|
669
|
-
onNone: () => [],
|
|
670
|
-
onSome: ({ relations }) => Object.keys(relations)
|
|
671
|
-
});
|
|
672
|
-
return Effect.map(Effect.all([
|
|
673
|
-
Effect.forEach([
|
|
674
|
-
"Update",
|
|
675
|
-
"Delete",
|
|
676
|
-
...named
|
|
677
|
-
], (interaction) => Effect.map(policy.writable(entity, principal, interaction), (rule) => [interaction, rule])),
|
|
678
|
-
policy.writeMembers(entity, principal, ruledMembers, "Update"),
|
|
679
|
-
Effect.forEach(ruledRelations, (relation) => Effect.map(Effect.all([policy.linkable(entity, principal, relation, "Link"), policy.linkable(entity, principal, relation, "Unlink")]), ([link, unlink]) => ({
|
|
680
|
-
relation,
|
|
681
|
-
link,
|
|
682
|
-
unlink
|
|
683
|
-
})))
|
|
684
|
-
]), ([rows, members, relations]) => {
|
|
685
|
-
const input = policy.inputOf(principal);
|
|
686
|
-
const holds = (condition, values) => Condition.holds(condition, values, input, () => false, policy.operators);
|
|
687
|
-
const allows = (rule, values) => Option.match(rule, {
|
|
688
|
-
onNone: () => true,
|
|
689
|
-
onSome: ({ condition }) => holds(condition, values)
|
|
690
|
-
});
|
|
691
|
-
const conditions = [
|
|
692
|
-
...rows.map(([, { condition }]) => condition),
|
|
693
|
-
...members.map(({ condition }) => condition),
|
|
694
|
-
...relations.flatMap(({ link, unlink }) => [...Option.toArray(link), ...Option.toArray(unlink)].map(({ condition }) => condition))
|
|
695
|
-
];
|
|
696
|
-
return {
|
|
697
|
-
fields: ["id", ...new Set(conditions.flatMap(Condition.members))],
|
|
698
|
-
answer: (values) => ({
|
|
699
|
-
row: Object.fromEntries(rows.map(([interaction, { condition }]) => [interaction, holds(condition, values)])),
|
|
700
|
-
reasons: Object.fromEntries(rows.flatMap(([interaction, { condition, deny }]) => holds(condition, values) ? [] : Match.valueTags(deny, {
|
|
701
|
-
Explain: ({ reason }) => [[interaction, reason]],
|
|
702
|
-
Forbidden: () => [],
|
|
703
|
-
NotFound: () => [],
|
|
704
|
-
Omit: () => [],
|
|
705
|
-
Redact: () => []
|
|
706
|
-
}))),
|
|
707
|
-
members: Object.fromEntries(members.map(({ member, condition }) => [member, holds(condition, values)])),
|
|
708
|
-
relations: Object.fromEntries(relations.map(({ relation, link, unlink }) => [relation, {
|
|
709
|
-
Link: allows(link, values),
|
|
710
|
-
Unlink: allows(unlink, values)
|
|
711
|
-
}]))
|
|
712
|
-
})
|
|
713
|
-
};
|
|
714
|
-
});
|
|
715
|
-
};
|
|
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
|
+
});
|
|
716
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
|
+
});
|
|
717
836
|
const refused = (deny) => Match.valueTags(deny, {
|
|
718
837
|
Explain: ({ reason }) => RemoteServer.forbid(reason),
|
|
719
838
|
Forbidden: () => RemoteServer.forbid(),
|