foldkit-guard 0.6.0 → 0.8.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 +223 -46
- 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-CJl-GtbN.d.mts} +156 -10
- package/dist/attach-CJl-GtbN.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 +54 -20
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +288 -154
- 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 +20 -19
- 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, RemoteForbidden } from "foldkit-remote";
|
|
9
|
+
import { DeleteOutcome, 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,26 @@ 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
|
-
* `Forbidden`, with the sentence an `explain` gave
|
|
222
|
+
* `Forbidden`, with the sentence an `explain` gave, or `Unauthenticated` for a
|
|
223
|
+
* visitor; the write never runs.
|
|
155
224
|
*
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
* a rule over
|
|
159
|
-
*
|
|
160
|
-
* server's, refused.
|
|
225
|
+
* What the Entity sets from the write's context (`Entity.sets`: who asks,
|
|
226
|
+
* when) reaches a create or an update already set by `RemoteServer.write`,
|
|
227
|
+
* so a rule over it holds of the creator. A member rule over such a member
|
|
228
|
+
* judges the server's value like any other: declare none there.
|
|
161
229
|
*
|
|
162
230
|
* `revision` names a field stored as a number, which the writer moves on by
|
|
163
231
|
* one with each write it lands. An update or a delete then lands only on the
|
|
@@ -165,7 +233,8 @@ const GuardServer = {
|
|
|
165
233
|
* between the check and the write is never written over; it is decided
|
|
166
234
|
* again against the row as it now is, up to three times. A change that does
|
|
167
235
|
* not move the revision (a handler's, `applyEdits`', raw SQL) is not seen.
|
|
168
|
-
* Without `revision`, none is, and `validate` warns
|
|
236
|
+
* Without `revision`, none is, and `validate` warns of an update, or a delete
|
|
237
|
+
* of an Entity the server updates (an insert has no row). An input that expects a
|
|
169
238
|
* revision the row read is not at is a `Conflict`, decided before any rule;
|
|
170
239
|
* an input may expect only the field the writer pins.
|
|
171
240
|
*
|
|
@@ -180,18 +249,40 @@ const GuardServer = {
|
|
|
180
249
|
if (field === void 0) throw new Error(`[foldkit-guard] GuardServer.writer: ${entity.name} has no field "${revision}" for its revision`);
|
|
181
250
|
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
251
|
}
|
|
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
252
|
if (writer.entity !== entity.name) throw new Error(`[foldkit-guard] GuardServer.writer: ${entity.name}'s rules over a writer for ${writer.entity}`);
|
|
193
253
|
const read = writer.read;
|
|
194
254
|
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)`);
|
|
255
|
+
const reaching = Option.match(attached(entity), {
|
|
256
|
+
onNone: () => [],
|
|
257
|
+
onSome: ({ row }) => ["Update", "Delete"].flatMap((interaction) => (row[interaction]?.rules ?? []).flatMap(function names(rule) {
|
|
258
|
+
return Match.valueTags(rule, {
|
|
259
|
+
PrincipalGuard: () => [],
|
|
260
|
+
RowGuard: (guard) => Query.dependencies(guard.query).reaches.length > 0 ? [guard.name] : [],
|
|
261
|
+
All: ({ rules }) => rules.flatMap(names),
|
|
262
|
+
Inherit: () => []
|
|
263
|
+
});
|
|
264
|
+
}))
|
|
265
|
+
});
|
|
266
|
+
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`);
|
|
267
|
+
/**
|
|
268
|
+
* The row rule over `values` as far as one row decides it: refused where it
|
|
269
|
+
* fails, and otherwise what the writer's statement must still judge.
|
|
270
|
+
*/
|
|
271
|
+
const rowRule = (rule, values, principal) => {
|
|
272
|
+
const left = Condition.residual(rule.condition, values, policy.inputOf(principal), policy.operators);
|
|
273
|
+
return Match.valueTags(left, {
|
|
274
|
+
Always: () => Effect.succeed(Option.none()),
|
|
275
|
+
Never: () => Effect.fail(refused(rule.deny)),
|
|
276
|
+
Row: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),
|
|
277
|
+
Inherit: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),
|
|
278
|
+
And: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),
|
|
279
|
+
Or: () => Effect.succeed(Option.some(required(left, rule.deny, principal)))
|
|
280
|
+
});
|
|
281
|
+
};
|
|
282
|
+
const required = (left, deny, principal) => ({
|
|
283
|
+
holds: requirementOf(left, policy.inputOf(principal)),
|
|
284
|
+
reason: explained(deny)
|
|
285
|
+
});
|
|
195
286
|
const holds = (rule, values, principal) => Condition.holds(rule.condition, values, policy.inputOf(principal), () => false, policy.operators);
|
|
196
287
|
/** Fails with the first rule of `rules` that does not hold over `values`. */
|
|
197
288
|
const require = (rules, values, principal) => Option.match(Option.fromUndefinedOr(rules.find((rule) => !holds(rule, values, principal))), {
|
|
@@ -292,19 +383,20 @@ const GuardServer = {
|
|
|
292
383
|
}
|
|
293
384
|
});
|
|
294
385
|
/**
|
|
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
|
|
386
|
+
* The answer the writer's ledger holds for this operation, as `answered`
|
|
387
|
+
* makes it, or else `write`: a retry of a write that landed is answered as
|
|
388
|
+
* it landed, not decided again over a row, or a time, that has moved since.
|
|
298
389
|
*/
|
|
299
|
-
const answeredOr = (context, write) => {
|
|
390
|
+
const answeredOr = (context, answered, write) => {
|
|
300
391
|
const recorded = writer.recorded;
|
|
301
392
|
if (recorded === void 0 || Option.isNone(context.operation)) return write();
|
|
302
393
|
return Effect.flatMap(recorded({
|
|
303
394
|
operation: context.operation.value,
|
|
395
|
+
request: context.request,
|
|
304
396
|
id: context.id,
|
|
305
397
|
principal: context.principal
|
|
306
398
|
}), Option.match({
|
|
307
|
-
onSome: (answer) => Effect.succeed(
|
|
399
|
+
onSome: (answer) => Effect.succeed(answered(answer)),
|
|
308
400
|
onNone: write
|
|
309
401
|
}));
|
|
310
402
|
};
|
|
@@ -337,7 +429,11 @@ const GuardServer = {
|
|
|
337
429
|
], [
|
|
338
430
|
...Object.keys(context.links),
|
|
339
431
|
...versionFields(context.expect),
|
|
340
|
-
...Write.boundReads(context)
|
|
432
|
+
...Write.boundReads(context),
|
|
433
|
+
...Condition.reachedFrom(rules.row.condition, {
|
|
434
|
+
entity: entity.name,
|
|
435
|
+
id: context.id
|
|
436
|
+
})
|
|
341
437
|
]),
|
|
342
438
|
principal: context.principal
|
|
343
439
|
});
|
|
@@ -349,8 +445,9 @@ const GuardServer = {
|
|
|
349
445
|
/**
|
|
350
446
|
* The row `context` would leave `before` as. An operator's refusal (text
|
|
351
447
|
* 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.
|
|
448
|
+
* writer answers what it cannot compile: reported here (`ComputeRefused`),
|
|
449
|
+
* and never sent, since an implementation's own message may say anything.
|
|
450
|
+
* So is a field it cannot
|
|
354
451
|
* work out at all: judging its old value would let a rule over it pass.
|
|
355
452
|
*/
|
|
356
453
|
const leaves = (before, context) => Effect.suspend(() => {
|
|
@@ -360,7 +457,7 @@ const GuardServer = {
|
|
|
360
457
|
return applied.unknown.length === 0 ? Effect.succeed(applied.row) : unworkable;
|
|
361
458
|
} catch (error) {
|
|
362
459
|
if (!(error instanceof QueryEvaluateError)) throw error;
|
|
363
|
-
return
|
|
460
|
+
return Diagnostics.report(computeRefused(entity.name, error)).pipe(Effect.andThen(unworkable));
|
|
364
461
|
}
|
|
365
462
|
});
|
|
366
463
|
/** The rules, over the row as it is and as the write would leave it. */
|
|
@@ -371,7 +468,7 @@ const GuardServer = {
|
|
|
371
468
|
id: context.id,
|
|
372
469
|
relations: linked
|
|
373
470
|
});
|
|
374
|
-
const
|
|
471
|
+
const was = Option.some(Option.match(stored, {
|
|
375
472
|
onNone: () => ({
|
|
376
473
|
links: before,
|
|
377
474
|
exact: false
|
|
@@ -380,17 +477,36 @@ const GuardServer = {
|
|
|
380
477
|
links,
|
|
381
478
|
exact: true
|
|
382
479
|
})
|
|
383
|
-
}))
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
...relations
|
|
388
|
-
], before, principal);
|
|
480
|
+
}));
|
|
481
|
+
const relations = linking(rules.relating, was);
|
|
482
|
+
const requires = yield* rowRule(rules.row, before, principal);
|
|
483
|
+
yield* require([...rules.members, ...relations], before, principal);
|
|
389
484
|
const after = {
|
|
390
485
|
...yield* leaves(before, context),
|
|
391
486
|
...Object.fromEntries(Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]))
|
|
392
487
|
};
|
|
393
|
-
yield*
|
|
488
|
+
const leaving = yield* rowRule(rules.row, after, principal);
|
|
489
|
+
if (Option.isSome(leaving)) {
|
|
490
|
+
if (Condition.reachedFrom(Condition.residual(rules.row.condition, after, policy.inputOf(principal), policy.operators), {
|
|
491
|
+
entity: entity.name,
|
|
492
|
+
id: context.id
|
|
493
|
+
}).some((key) => !sameStored(before[key], after[key]))) return yield* Effect.fail(refused(rules.row.deny));
|
|
494
|
+
}
|
|
495
|
+
const undone = [...rules.members.map((rule) => ({
|
|
496
|
+
rule,
|
|
497
|
+
key: rule.member
|
|
498
|
+
})), ...rules.relating.flatMap((rule) => linking([{
|
|
499
|
+
...rule,
|
|
500
|
+
unlink: Option.none()
|
|
501
|
+
}], was).map((link) => ({
|
|
502
|
+
rule: link,
|
|
503
|
+
key: rule.relation
|
|
504
|
+
})))];
|
|
505
|
+
yield* Effect.forEach(undone, ({ rule, key }) => require([rule], {
|
|
506
|
+
...after,
|
|
507
|
+
[key]: before[key]
|
|
508
|
+
}, principal), { discard: true });
|
|
509
|
+
return requires;
|
|
394
510
|
});
|
|
395
511
|
const guarded = {
|
|
396
512
|
entity: writer.entity,
|
|
@@ -400,6 +516,7 @@ const GuardServer = {
|
|
|
400
516
|
...revision === void 0 ? {} : { pins: true },
|
|
401
517
|
...writer.ledger === true ? { ledger: true } : {},
|
|
402
518
|
...writer.invariants === true ? { invariants: true } : {},
|
|
519
|
+
...writer.cascades === true ? { cascades: true } : {},
|
|
403
520
|
refuses: (write) => [
|
|
404
521
|
...writer.refuses?.(write) ?? [],
|
|
405
522
|
...write.assignments.flatMap(({ field, expr }) => Expr.unsupported([expr], {
|
|
@@ -414,31 +531,22 @@ const GuardServer = {
|
|
|
414
531
|
fields: seen,
|
|
415
532
|
principal
|
|
416
533
|
}), principal, fields, id),
|
|
417
|
-
update: (context) => Effect.mapError(Effect.andThen(admitUpdate(context), () => answeredOr(context, () => pinned(context.id, context.expect, Option.isNone, () => Effect.gen(function* () {
|
|
534
|
+
update: (context) => Effect.mapError(Effect.andThen(admitUpdate(context), () => answeredOr(context, Option.some, () => pinned(context.id, context.expect, Option.isNone, () => Effect.gen(function* () {
|
|
418
535
|
const rules = yield* updateRules(context);
|
|
419
536
|
const current = yield* readBefore(context, rules);
|
|
420
537
|
if (Option.isNone(current)) return yield* Effect.fail(refused(rules.row.deny));
|
|
421
538
|
if (moved(context.expect, current.value)) return Option.none();
|
|
422
|
-
yield* decideUpdate(context, rules, current.value);
|
|
539
|
+
const requires = yield* decideUpdate(context, rules, current.value);
|
|
423
540
|
return yield* writer.update({
|
|
424
541
|
...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
|
-
}
|
|
542
|
+
expect: pin(context.expect, current.value),
|
|
543
|
+
...Option.match(requires, {
|
|
544
|
+
onNone: () => ({}),
|
|
545
|
+
onSome: (held) => ({ requires: held })
|
|
440
546
|
})
|
|
441
547
|
});
|
|
548
|
+
})))), told),
|
|
549
|
+
insert: (context) => answeredOr(context, identity, () => Effect.gen(function* () {
|
|
442
550
|
const { principal, values, links } = context;
|
|
443
551
|
const row = yield* policy.writable(entity, principal, "Create");
|
|
444
552
|
const members = yield* policy.writeMembers(entity, principal, Object.keys(values), "Create");
|
|
@@ -460,25 +568,35 @@ const GuardServer = {
|
|
|
460
568
|
condition: Condition.unsetting(rule.condition, unset)
|
|
461
569
|
})), proposed, principal);
|
|
462
570
|
return yield* Effect.mapError(writer.insert(context), told);
|
|
463
|
-
}),
|
|
464
|
-
delete: (context) => Effect.andThen(discloses(context.expect, context.when), () => pinned(context.id, context.expect, (
|
|
571
|
+
})),
|
|
572
|
+
delete: (context) => Effect.andThen(discloses(context.expect, context.when), () => pinned(context.id, context.expect, DeleteOutcome.$is("Moved"), () => Effect.gen(function* () {
|
|
465
573
|
const row = yield* policy.writable(entity, context.principal, "Delete");
|
|
466
574
|
const current = yield* read({
|
|
467
575
|
id: context.id,
|
|
468
576
|
fields: fieldsOf([row], versionFields(context.expect)),
|
|
469
577
|
principal: context.principal
|
|
470
578
|
});
|
|
471
|
-
if (Option.isNone(current)) return
|
|
472
|
-
if (moved(context.expect, current.value)) return
|
|
473
|
-
yield*
|
|
579
|
+
if (Option.isNone(current)) return DeleteOutcome.Absent();
|
|
580
|
+
if (moved(context.expect, current.value)) return DeleteOutcome.Moved();
|
|
581
|
+
const requires = yield* rowRule(row, current.value, context.principal);
|
|
474
582
|
return yield* writer.delete({
|
|
475
583
|
...context,
|
|
476
|
-
expect: pin(context.expect, current.value)
|
|
584
|
+
expect: pin(context.expect, current.value),
|
|
585
|
+
...Option.match(requires, {
|
|
586
|
+
onNone: () => ({}),
|
|
587
|
+
onSome: (held) => ({ requires: held })
|
|
588
|
+
})
|
|
477
589
|
});
|
|
478
590
|
})))
|
|
479
591
|
};
|
|
480
|
-
|
|
481
|
-
|
|
592
|
+
const asked = {
|
|
593
|
+
...guarded,
|
|
594
|
+
update: (context) => signInFirst(context.principal, guarded.update(context)),
|
|
595
|
+
insert: (context) => signInFirst(context.principal, guarded.insert(context)),
|
|
596
|
+
delete: (context) => signInFirst(context.principal, guarded.delete(context))
|
|
597
|
+
};
|
|
598
|
+
pins.set(asked, Option.fromUndefinedOr(revision));
|
|
599
|
+
return writeRules.add(asked, policy, [entity]);
|
|
482
600
|
},
|
|
483
601
|
/**
|
|
484
602
|
* A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for
|
|
@@ -487,8 +605,8 @@ const GuardServer = {
|
|
|
487
605
|
* rule must hold over it; a row its writer may not see is refused. With no
|
|
488
606
|
* `id` (a create), the rule must hold of who is asking alone, a field it
|
|
489
607
|
* reads matching no guard. `run` is given the row as read: its fields the
|
|
490
|
-
* rule reads, its `id`, and `fields`. A refusal is `Forbidden
|
|
491
|
-
* runs. What `run` writes is its own: check members it sets there. Each
|
|
608
|
+
* rule reads, its `id`, and `fields`. A refusal is `Forbidden`, or
|
|
609
|
+
* `Unauthenticated` for a visitor; `run` never runs. What `run` writes is its own: check members it sets there. Each
|
|
492
610
|
* row of `entity` its answer carries is read back through `source`, so the
|
|
493
611
|
* answer shows its writer only what they may see, a row it hid from them
|
|
494
612
|
* as deleted.
|
|
@@ -546,7 +664,7 @@ const GuardServer = {
|
|
|
546
664
|
...context,
|
|
547
665
|
row
|
|
548
666
|
}), principal);
|
|
549
|
-
}));
|
|
667
|
+
}).pipe((answered) => signInFirst(context.principal, answered)));
|
|
550
668
|
},
|
|
551
669
|
/**
|
|
552
670
|
* Checks, at startup, that `server` applies the guards of `entities`, the
|
|
@@ -555,11 +673,14 @@ const GuardServer = {
|
|
|
555
673
|
* `GuardServer.memory`), its Source applies its members' and relations'
|
|
556
674
|
* (`GuardServer.filter`), and each declared write of it lands through
|
|
557
675
|
* `GuardServer.writer`, all built from `policy`; and that no query's body
|
|
558
|
-
* filters or orders by a member with a Read rule,
|
|
559
|
-
*
|
|
676
|
+
* filters or orders by a member with a Read rule, its own or one of a row it
|
|
677
|
+
* reaches through a path or an exists, which would answer for the value it
|
|
678
|
+
* hides. A hand-written Source over a guarded Entity would serve
|
|
560
679
|
* every row, and a bare writer would take every write; this throws instead,
|
|
561
680
|
* naming each. A handler (`RemoteServer.mutation`) writes what its code
|
|
562
|
-
* writes, which no check at startup can read.
|
|
681
|
+
* writes, which no check at startup can read. A write a change can come
|
|
682
|
+
* between, through a writer given no revision, is not refused but reported:
|
|
683
|
+
* `UnpinnedWrites`, a warning, to `diagnostics`.
|
|
563
684
|
*
|
|
564
685
|
* ```ts
|
|
565
686
|
* GuardServer.validate(Policy, { entities: [Todo, Project], domain: Data, server: Server })
|
|
@@ -567,6 +688,8 @@ const GuardServer = {
|
|
|
567
688
|
*/
|
|
568
689
|
validate: (policy, config) => {
|
|
569
690
|
const byName = new Map(config.entities.map((entity) => [entity.name, entity]));
|
|
691
|
+
/** Whether a reached member has a Read rule; one of an Entity not validated has none checked. */
|
|
692
|
+
const hidesFromReach = ({ entity, key }) => Option.exists(Option.flatMap(Option.fromUndefinedOr(byName.get(entity)), attached), (attachment) => readRuled(attachment, key));
|
|
570
693
|
/** Whether who may read the rows of `entity` depends on who is asking. */
|
|
571
694
|
const rowsRuled = (entity) => Option.exists(Option.flatMap(Option.fromUndefinedOr(entity), attached), (attachment) => readRowsRuled(attachment));
|
|
572
695
|
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 +709,27 @@ const GuardServer = {
|
|
|
586
709
|
});
|
|
587
710
|
const bodyProblems = [...config.domain.registry.queries].flatMap(([queryName, { body }]) => {
|
|
588
711
|
if (body === void 0 || body.entity.name !== name) return [];
|
|
589
|
-
const { predicate, order } = Query.dependencies(body);
|
|
590
|
-
|
|
712
|
+
const { predicate, order, reaches } = Query.dependencies(body);
|
|
713
|
+
const reached = [...new Set(reachedMembers(reaches).filter(hidesFromReach).map(({ entity, key }) => `query ${queryName} reaches ${entity}'s ${key}, which has a Read rule`))];
|
|
714
|
+
return [
|
|
715
|
+
...hiddenOf(attachment, predicate).map((member) => `query ${queryName} filters ${name} by ${member}, which has a Read rule`),
|
|
716
|
+
...hiddenOf(attachment, order).map((member) => `query ${queryName} orders ${name} by ${member}, which has a Read rule`),
|
|
717
|
+
...reached
|
|
718
|
+
];
|
|
591
719
|
});
|
|
592
720
|
const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) => {
|
|
593
721
|
if (source.writes === void 0 || source.writes.entity !== name) return [];
|
|
594
722
|
if (!writeRules.has(source.writes.writer, policy, entity)) return [`write ${mutation} writes ${name} without its write rules`];
|
|
595
723
|
const { write, writer } = source.writes;
|
|
724
|
+
const interaction = Match.valueTags(write, {
|
|
725
|
+
Insert: () => "Create",
|
|
726
|
+
Update: () => "Update",
|
|
727
|
+
Delete: () => "Delete"
|
|
728
|
+
});
|
|
729
|
+
const open = attachment.unguarded === "allow" && Option.isNone(surfaceOf(attachment, {
|
|
730
|
+
_tag: "Row",
|
|
731
|
+
interaction
|
|
732
|
+
})) ? [`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
733
|
const when = Option.match(write.when, {
|
|
597
734
|
onNone: () => [],
|
|
598
735
|
onSome: (body) => hiddenOf(attachment, Query.dependencies(body).predicate)
|
|
@@ -601,6 +738,7 @@ const GuardServer = {
|
|
|
601
738
|
const expected = write.expect?.field.key;
|
|
602
739
|
const pin = typeof writer === "object" && writer !== null ? pins.get(writer) : void 0;
|
|
603
740
|
return [
|
|
741
|
+
...open,
|
|
604
742
|
...when.map((member) => `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`),
|
|
605
743
|
...computed,
|
|
606
744
|
...expected !== void 0 && readRuled(attachment, expected) ? [`write ${mutation} expects ${name}'s ${expected}, which has a Read rule`] : [],
|
|
@@ -611,15 +749,20 @@ const GuardServer = {
|
|
|
611
749
|
onNone: () => [],
|
|
612
750
|
onSome: (source) => [...source.shared ?? []]
|
|
613
751
|
});
|
|
614
|
-
const sharedProblems = [
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
752
|
+
const sharedProblems = [
|
|
753
|
+
...shared.length > 0 && readRowsRuled(attachment) ? [`${name}'s Source shares ${shared.join(", ")}, but its rows have a Read rule`] : [],
|
|
754
|
+
...shared.includes("may") && asksMay(entity, ["may"]) ? [`${name}'s Source shares may, which is answered for each reader`] : [],
|
|
755
|
+
...shared.flatMap((member) => {
|
|
756
|
+
const own = readRuled(attachment, member) ? [`${name}'s Source shares ${member}, which has a Read rule`] : [];
|
|
757
|
+
if (!Object.hasOwn(entity.relations, member)) return own;
|
|
758
|
+
const target = entity.relations[member].target().name;
|
|
759
|
+
if (!byName.has(target)) return [...own, `${name}'s Source shares ${member}, whose ${target} is not validated`];
|
|
760
|
+
return rowsRuled(byName.get(target)) ? [...own, `${name}'s Source shares ${member}, whose rows have a Read rule`] : own;
|
|
761
|
+
})
|
|
762
|
+
];
|
|
621
763
|
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
|
|
764
|
+
const live = Option.fromUndefinedOr(config.server.live.get(name));
|
|
765
|
+
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
766
|
return [
|
|
624
767
|
...sourceProblems,
|
|
625
768
|
...queryProblems,
|
|
@@ -633,87 +776,78 @@ const GuardServer = {
|
|
|
633
776
|
}));
|
|
634
777
|
const problems = [...undeclared, ...entityProblems];
|
|
635
778
|
if (problems.length > 0) throw new Error(`[foldkit-guard] GuardServer.validate: ${problems.join("; ")}`);
|
|
636
|
-
const
|
|
637
|
-
|
|
779
|
+
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));
|
|
780
|
+
const unpinned = [...config.server.mutations].flatMap(([mutation, source]) => {
|
|
781
|
+
const writes = source.writes;
|
|
782
|
+
if (writes === void 0) return [];
|
|
783
|
+
const writer = writes.writer;
|
|
638
784
|
const pin = typeof writer === "object" && writer !== null ? pins.get(writer) : void 0;
|
|
639
|
-
|
|
785
|
+
if (pin === void 0 || Option.isSome(pin)) return [];
|
|
786
|
+
return Match.valueTags(writes.write, {
|
|
787
|
+
Update: () => true,
|
|
788
|
+
Delete: () => updated.has(writes.entity),
|
|
789
|
+
Insert: () => false
|
|
790
|
+
}) ? [mutation] : [];
|
|
640
791
|
});
|
|
641
|
-
if (
|
|
792
|
+
if (unpinned.length > 0) {
|
|
793
|
+
const report = Diagnostics.report(unpinnedWrites(unpinned));
|
|
794
|
+
const { diagnostics } = config;
|
|
795
|
+
Effect.runFork(diagnostics === void 0 ? report : Effect.provideService(report, Diagnostics.Reporter, diagnostics));
|
|
796
|
+
}
|
|
642
797
|
}
|
|
643
798
|
};
|
|
644
799
|
/** Whether a read asks for `may`, of an Entity that has it (`Guards.may`). */
|
|
645
800
|
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
801
|
/**
|
|
654
802
|
* `may` for `principal`: each row interaction's rule, each member's own
|
|
655
803
|
* `Update`, each relation's `Link` and `Unlink`, decided once and held over
|
|
656
804
|
* each row as a write's check would hold them over it as it is.
|
|
657
805
|
*/
|
|
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
|
-
};
|
|
806
|
+
const mayOf = (entity, policy, principal) => Effect.map(mayRules(entity, {
|
|
807
|
+
row: (interaction) => policy.writable(entity, principal, interaction),
|
|
808
|
+
members: (members) => policy.writeMembers(entity, principal, members, "Update"),
|
|
809
|
+
relation: (relation, interaction) => policy.linkable(entity, principal, relation, interaction)
|
|
810
|
+
}), (rules) => {
|
|
811
|
+
const input = policy.inputOf(principal);
|
|
812
|
+
return {
|
|
813
|
+
fields: ["id", ...new Set(mayConditions(rules).flatMap(Condition.members))],
|
|
814
|
+
answer: (values) => answerOf(rules, (condition) => Condition.decided(Condition.residual(condition, values, input, policy.operators)))
|
|
815
|
+
};
|
|
816
|
+
});
|
|
716
817
|
/** A refused write as the client receives it: the sentence an `explain` gave, or none. */
|
|
818
|
+
/** The words a refusal gives: an `explain`'s, or none. */
|
|
819
|
+
const explained = (deny) => Match.valueTags(deny, {
|
|
820
|
+
Explain: ({ reason }) => Option.some(reason),
|
|
821
|
+
Forbidden: () => Option.none(),
|
|
822
|
+
NotFound: () => Option.none(),
|
|
823
|
+
Omit: () => Option.none(),
|
|
824
|
+
Redact: () => Option.none()
|
|
825
|
+
});
|
|
826
|
+
/**
|
|
827
|
+
* What is left of a condition, as a writer's statement judges it: each row
|
|
828
|
+
* guard a body over the row, its input the principal's (`G.inputOf`), and its
|
|
829
|
+
* context the one it was decided for. An inherited Read, which a writer
|
|
830
|
+
* refuses, requires what no row holds.
|
|
831
|
+
*/
|
|
832
|
+
const requirementOf = (condition, input) => Match.valueTags(condition, {
|
|
833
|
+
Always: () => RowRequirement.All({ of: [] }),
|
|
834
|
+
Never: () => RowRequirement.Any({ of: [] }),
|
|
835
|
+
Row: ({ guard, context }) => RowRequirement.Body({
|
|
836
|
+
query: guard.query,
|
|
837
|
+
input,
|
|
838
|
+
context
|
|
839
|
+
}),
|
|
840
|
+
Inherit: () => RowRequirement.Any({ of: [] }),
|
|
841
|
+
And: ({ conditions }) => RowRequirement.All({ of: conditions.map((each) => requirementOf(each, input)) }),
|
|
842
|
+
Or: ({ conditions }) => RowRequirement.Any({ of: conditions.map((each) => requirementOf(each, input)) })
|
|
843
|
+
});
|
|
844
|
+
/**
|
|
845
|
+
* A visitor's refused write as a sign-in it needs: `Unauthenticated`, never
|
|
846
|
+
* `Forbidden`, so a client tells a session that ended (its cookie gone, it
|
|
847
|
+
* asks as a visitor) from a person refused, and a durable write waits for the
|
|
848
|
+
* sign-in rather than failing (#403). A refusal's words go with it.
|
|
849
|
+
*/
|
|
850
|
+
const signInFirst = (principal, write) => Option.isSome(principal) ? write : Effect.mapError(write, (error) => error instanceof RemoteForbidden ? RemoteServer.unauthenticated(error.reason) : error);
|
|
717
851
|
const refused = (deny) => Match.valueTags(deny, {
|
|
718
852
|
Explain: ({ reason }) => RemoteServer.forbid(reason),
|
|
719
853
|
Forbidden: () => RemoteServer.forbid(),
|