foldkit-guard 0.7.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 CHANGED
@@ -120,8 +120,11 @@ What each call does, and does not:
120
120
 
121
121
  - `Guards.declare` reads nothing and stores nothing. It builds each row
122
122
  guard's predicate once, with placeholders (`p.id` is the input
123
- `principal.id`), and checks it is a rule over its own Entity. Branching on
124
- a placeholder (`p.role === 'admin'`) is a type error: there is no value yet.
123
+ `principal.id`), and checks it is a rule over its own Entity: a predicate
124
+ reading another Entity's field, relation or case is a type error where it
125
+ is written, and refused at runtime for a predicate typed plain `Predicate`.
126
+ Branching on a placeholder (`p.role === 'admin'`) is a type error: there is
127
+ no value yet.
125
128
  - `G.implement` is the only place a body exists. A missing or extra key is a
126
129
  type error, and refused at runtime for a caller the types do not reach.
127
130
  - `Policy.decide` is an `Effect` of a `Decision`: `true`, `false`, or
@@ -225,6 +228,11 @@ Beyond the row's own fields:
225
228
  `Policy.viewer(principal)` is that row's ref, the server's one viewer:
226
229
  `RemoteServer.make({ viewer: Policy.viewer })`. A rule over `Expr.viewer`
227
230
  in a set without one, or over `Expr.now`, is refused where it is declared.
231
+ - A rule per case of a variant Entity (`Entity.defineVariants`) is a row
232
+ guard over `Expr.is`: `guard.row(Domain, p => Expr.is(Domain, 'Available',
233
+ ({ price }) => Expr.lte(price, p.budget)))`. It is false on a row of another
234
+ case, so the row's other rules decide it, and it reads `_tag` and the
235
+ case's fields as columns of the stored row, in SQL and in memory alike.
228
236
  - A row's `Read`, `Update` and `Delete` rules may reach another row
229
237
  (`Expr.path`, `Expr.exists`, a path from the viewer: `Expr.eq(Note.fields.orgId,
230
238
  orgOfViewer)`). A Read rule compiles to SQL; an Update or Delete rule is
@@ -421,7 +429,10 @@ RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
421
429
  it leaves unset does not hold, whatever it asks (`isNull` and `isNotNull`
422
430
  alike): the create never said what the field holds.
423
431
  - A refusal is `Forbidden`, with the sentence `Guards.explain` gave; the
424
- write never runs.
432
+ write never runs. A visitor is refused as `Unauthenticated` instead, with
433
+ the same sentence: no one is signed in, so the remedy is a sign-in, and a
434
+ client tells a session that ended (its cookie gone) from a person refused.
435
+ Remote's outbox keeps a durable write so answered until the sign-in.
425
436
  - The answer is read back under the binding's `visible` and the Entity's
426
437
  member Read rules: the row as its writer may now see it, with no more
427
438
  fields than the write set, and a row the write hid from them in `deleted`,
@@ -511,8 +522,8 @@ creator's, and `RemoteServer.make({ viewer })` says who that is. A member rule
511
522
  over such a member judges the server's value like any other: declare none there.
512
523
 
513
524
  No input may set `ownerId`, which is refused where the write is declared. A
514
- visitor is no one to set, and is refused even where the rules would let
515
- anyone create. A create of an id already taken is refused as
525
+ visitor is no one to set, and is refused (`Unauthenticated`) even where the
526
+ rules would let anyone create. A create of an id already taken is refused as
516
527
  `Refusal.taken`, with one answer whatever the row there holds, so it tells
517
528
  nothing the asker may not read. Only
518
529
  the writer's ledger recognises a retry, by its operation and who asked, and
@@ -815,6 +826,7 @@ const MeSource = GuardServer.me(Me, Policy)
815
826
  | A member's Read refused (`redact`) | the replacement value | `Ready` with it, by design indistinguishable |
816
827
  | A relation's Read refused | withheld, as a member's | unavailable |
817
828
  | A write refused | `Forbidden`, a 403 over JSON | `Data.mutation` is `Failed` with `_tag: 'Forbidden'`, `reason` from an `explain` |
829
+ | A visitor's write refused | `Unauthenticated`, a 401 over JSON | `Failed` with `_tag: 'Unauthenticated'`; a durable write waits for a sign-in |
818
830
  | A write moved a row out of its writer's sight | answered in `deleted` | tombstoned; it leaves every list |
819
831
  | A delete of a row its writer cannot see | nothing deleted; answered gone | tombstoned |
820
832
  | A Sync edit refused | rejected by its id, with its reason | the replica drops it, with the reason |
package/dist/agent.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { j as MayAnswer, l as InteractionKey } from "./attach-DPgyv78F.mjs";
1
+ import { j as MayAnswer, l as InteractionKey } from "./attach-CJl-GtbN.mjs";
2
2
  import { RemoteData } from "foldkit-remote";
3
3
  /** A row read with `may`, as `Data.get(Row, id).read(model)` gives it. */
4
4
  type MayRow = RemoteData<{
@@ -1,5 +1,5 @@
1
1
  import { Context, Effect, Option, Schema } from "effect";
2
- import { AnyEntity, AnyQuery, Entity, EntityRef, ExprContext, Forbids, HeldRow, HeldRows, InputExpr, MemoryOperators, Predicate, Predict } from "foldkit-entity";
2
+ import { AnyEntity, AnyQuery, Entity, EntityRef, ExprContext, Forbids, HeldRow, HeldRows, InputExpr, Invalid, MemoryOperators, Predicate, Predict, ReadsOf } from "foldkit-entity";
3
3
  type Condition = {
4
4
  readonly _tag: 'Always';
5
5
  } | {
@@ -121,7 +121,7 @@ declare const May: {
121
121
  */
122
122
  member: <E extends AnyEntity>(entity: E & ("may" & keyof E["members"] extends never ? unknown : {
123
123
  readonly alreadyAMember: "may" & keyof E["members"];
124
- })) => E extends Entity<infer Name extends string, infer Fields extends Schema.Struct.Fields, infer R extends Readonly<Record<string, import("foldkit-entity").RelationSpec<AnyEntity, import("foldkit-entity").Cardinality, boolean>>>, infer D extends Readonly<Record<string, import("foldkit-entity").DerivedSpec<Schema.Constraint, {
124
+ })) => E extends import("foldkit-entity").VariantEntity<infer Name extends string, infer Fields extends Schema.Struct.Fields, infer R extends Readonly<Record<string, import("foldkit-entity").RelationSpec<AnyEntity, import("foldkit-entity").Cardinality, boolean>>>, infer D extends Readonly<Record<string, import("foldkit-entity").DerivedSpec<Schema.Constraint, {
125
125
  readonly _tag: "Count";
126
126
  readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
127
127
  } | {
@@ -132,7 +132,37 @@ declare const May: {
132
132
  readonly _tag: "Supplied";
133
133
  readonly predict: Option.Option<Predict>;
134
134
  readonly forbids: Option.Option<Forbids>;
135
- }>>>> ? Entity<Name, Fields, R, D & {
135
+ }>>>, infer U extends Schema.Top & {
136
+ readonly tag: '_tag';
137
+ readonly cases: Readonly<Record<string, {
138
+ readonly fields: Schema.Struct.Fields;
139
+ }>>;
140
+ }> ? import("foldkit-entity").VariantEntity<Name, Fields, R, D & {
141
+ readonly may: import("foldkit-entity").DerivedSpec<Schema.Struct<{
142
+ readonly row: Schema.$Record<Schema.String, Schema.Boolean>;
143
+ readonly reasons: Schema.$Record<Schema.String, Schema.String>;
144
+ readonly members: Schema.$Record<Schema.String, Schema.Boolean>;
145
+ readonly relations: Schema.$Record<Schema.String, Schema.Struct<{
146
+ readonly Link: Schema.Boolean;
147
+ readonly Unlink: Schema.Boolean;
148
+ }>>;
149
+ }>, {
150
+ readonly _tag: "Supplied";
151
+ readonly predict: Option.Option<Predict>;
152
+ readonly forbids: Option.Option<Forbids>;
153
+ }>;
154
+ }, U> : E extends Entity<infer Name_1 extends string, infer Fields_1 extends Schema.Struct.Fields, infer R_1 extends Readonly<Record<string, import("foldkit-entity").RelationSpec<AnyEntity, import("foldkit-entity").Cardinality, boolean>>>, infer D_1 extends Readonly<Record<string, import("foldkit-entity").DerivedSpec<Schema.Constraint, {
155
+ readonly _tag: "Count";
156
+ readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
157
+ } | {
158
+ readonly _tag: "Exists";
159
+ readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
160
+ readonly viewer: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
161
+ } | {
162
+ readonly _tag: "Supplied";
163
+ readonly predict: Option.Option<Predict>;
164
+ readonly forbids: Option.Option<Forbids>;
165
+ }>>>> ? Entity<Name_1, Fields_1, R_1, D_1 & {
136
166
  readonly may: import("foldkit-entity").DerivedSpec<Schema.Struct<{
137
167
  readonly row: Schema.$Record<Schema.String, Schema.Boolean>;
138
168
  readonly reasons: Schema.$Record<Schema.String, Schema.String>;
@@ -380,9 +410,20 @@ interface Policy<User, R = never> {
380
410
  interface Builders<User> {
381
411
  /** A guard decided from the principal alone, by a body only the server has. */
382
412
  readonly principal: () => PrincipalSpec;
383
- /** A guard over `entity`'s rows: a predicate with the principal's fields as inputs. */
384
- readonly row: <E extends AnyEntity>(entity: E, body: (principal: Placeholders<User>) => Predicate) => RowSpec<E>;
413
+ /**
414
+ * A guard over `entity`'s rows: a predicate with the principal's fields as
415
+ * inputs. A predicate reading another Entity's fields is refused where it
416
+ * is written; one typed plain `Predicate` is checked when the set is
417
+ * declared.
418
+ */
419
+ readonly row: <E extends AnyEntity, P extends RuleOver<P, E['name']>>(entity: E, body: (principal: Placeholders<User>) => P) => RowSpec<E>;
385
420
  }
421
+ /**
422
+ * What a rule over the Entity `Name` may be: a predicate reading `Name`'s
423
+ * fields and relations, inputs and the viewer, or one whose reads are unknown
424
+ * to the type (a plain `Predicate`).
425
+ */
426
+ type RuleOver<P, Name extends string> = string extends ReadsOf<P> ? Predicate : [ReadsOf<P>] extends [Name] ? Predicate : Predicate & Invalid<`foldkit-guard: a rule over ${Name} reads ${Exclude<ReadsOf<P>, Name>}`>;
386
427
  declare const Guards: {
387
428
  /**
388
429
  * Adds the `may` member, the server's answer to what a principal may do
@@ -391,7 +432,37 @@ declare const Guards: {
391
432
  */
392
433
  may: <E extends AnyEntity>(entity: E & ("may" & keyof E["members"] extends never ? unknown : {
393
434
  readonly alreadyAMember: "may" & keyof E["members"];
394
- })) => E extends import("foldkit-entity").Entity<infer Name extends string, infer Fields extends Schema.Struct.Fields, infer R extends Readonly<Record<string, import("foldkit-entity").RelationSpec<AnyEntity, import("foldkit-entity").Cardinality, boolean>>>, infer D extends Readonly<Record<string, import("foldkit-entity").DerivedSpec<Schema.Constraint, {
435
+ })) => E extends import("foldkit-entity").VariantEntity<infer Name extends string, infer Fields extends Schema.Struct.Fields, infer R extends Readonly<Record<string, import("foldkit-entity").RelationSpec<AnyEntity, import("foldkit-entity").Cardinality, boolean>>>, infer D extends Readonly<Record<string, import("foldkit-entity").DerivedSpec<Schema.Constraint, {
436
+ readonly _tag: "Count";
437
+ readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
438
+ } | {
439
+ readonly _tag: "Exists";
440
+ readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
441
+ readonly viewer: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
442
+ } | {
443
+ readonly _tag: "Supplied";
444
+ readonly predict: Option.Option<import("foldkit-entity").Predict>;
445
+ readonly forbids: Option.Option<import("foldkit-entity").Forbids>;
446
+ }>>>, infer U extends Schema.Top & {
447
+ readonly tag: '_tag';
448
+ readonly cases: Readonly<Record<string, {
449
+ readonly fields: Schema.Struct.Fields;
450
+ }>>;
451
+ }> ? import("foldkit-entity").VariantEntity<Name, Fields, R, D & {
452
+ readonly may: import("foldkit-entity").DerivedSpec<Schema.Struct<{
453
+ readonly row: Schema.$Record<Schema.String, Schema.Boolean>;
454
+ readonly reasons: Schema.$Record<Schema.String, Schema.String>;
455
+ readonly members: Schema.$Record<Schema.String, Schema.Boolean>;
456
+ readonly relations: Schema.$Record<Schema.String, Schema.Struct<{
457
+ readonly Link: Schema.Boolean;
458
+ readonly Unlink: Schema.Boolean;
459
+ }>>;
460
+ }>, {
461
+ readonly _tag: "Supplied";
462
+ readonly predict: Option.Option<import("foldkit-entity").Predict>;
463
+ readonly forbids: Option.Option<import("foldkit-entity").Forbids>;
464
+ }>;
465
+ }, U> : E extends import("foldkit-entity").Entity<infer Name_1 extends string, infer Fields_1 extends Schema.Struct.Fields, infer R_1 extends Readonly<Record<string, import("foldkit-entity").RelationSpec<AnyEntity, import("foldkit-entity").Cardinality, boolean>>>, infer D_1 extends Readonly<Record<string, import("foldkit-entity").DerivedSpec<Schema.Constraint, {
395
466
  readonly _tag: "Count";
396
467
  readonly relation: import("foldkit-entity").EntityRelation<string, string, AnyEntity, "one", boolean>;
397
468
  } | {
@@ -402,7 +473,7 @@ declare const Guards: {
402
473
  readonly _tag: "Supplied";
403
474
  readonly predict: Option.Option<import("foldkit-entity").Predict>;
404
475
  readonly forbids: Option.Option<import("foldkit-entity").Forbids>;
405
- }>>>> ? import("foldkit-entity").Entity<Name, Fields, R, D & {
476
+ }>>>> ? import("foldkit-entity").Entity<Name_1, Fields_1, R_1, D_1 & {
406
477
  readonly may: import("foldkit-entity").DerivedSpec<Schema.Struct<{
407
478
  readonly row: Schema.$Record<Schema.String, Schema.Boolean>;
408
479
  readonly reasons: Schema.$Record<Schema.String, Schema.String>;
@@ -586,4 +657,4 @@ interface Attachment {
586
657
  }
587
658
  declare const attached: (entity: AnyEntity) => Option.Option<Attachment>;
588
659
  export { May as A, PrincipalGuard as C, RowSpec as D, RowGuard as E, RowRule as F, MaySchema as M, Condition as N, ME as O, MemberRead as P, Policy as S, PrincipalSpec as T, Builders as _, Deny as a, Guards as b, Interaction as c, Redact as d, RuleFor as f, Body as g, AnyGuard as h, Attachment as i, MayAnswer as j, MeEntity as k, InteractionKey as l, About as m, AnyRule as n, Explain as o, Surface as p, Attach as r, Inherit as s, All as t, On as u, Decision as v, PrincipalOf as w, Placeholders as x, GuardSet as y };
589
- //# sourceMappingURL=attach-DPgyv78F.d.mts.map
660
+ //# sourceMappingURL=attach-CJl-GtbN.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attach-CJl-GtbN.d.mts","names":["MemberKeys","_$__attach_js0.Attach","_$__attach_js0.AnyRule","_$__attach_js0.Inherit","_$__attach_js0.All","_$__attach_js0.Redact","_$__attach_js0.Explain","_$__attach_js0.On"],"sources":["../src/condition.ts","../src/may.ts","../src/me.ts","../src/index.ts","../src/attach.ts"],"mappings":";;KAuBY;WACG;;WACA;;;;WAGA;WACA,OAAO,cAAc;WACrB,SAAS;;;;WAGT;WAA0B;;WAC1B;WAAsB,YAAY,cAAc;;WAChD;WAAqB,YAAY,cAAc;;;cAUxD,MAAG,YAAgB,cAAc,eAAa;;cAY9C,KAAE,YAAgB,cAAc,eAAa;cAWtC;;aA5CQ;;;aACA;;;;;;;;;;;;;;EA4DN,QAAA,WAAA,WAAS,QACZ,S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AAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;;WAG1C,wBACG,WAAW;aACV,OAAO,cAAc,QAAQ,MAAM,KAAK;aACxC,OAAO,UAAU,QAAQ,MAAM,KAAK;aACpC,SAAS,UAAU,QAAQ,MAAM,KAAK;;;WAI1C,SAAS,cAAc,QAAQ,MAAM,KAAK;;;UAIpC;WACN,OAAO,cAAc;WACrB,MAAM,OAAO,OAAO;;KAG1B,WAAW,SAAS,eAAe;;UAGvB;WACN;WACA;WACA,KAAK;WACL,SAAS,SAAS,eAAe;WACjC,WAAW,SAAS,eAAe;WACnC,QAAQ,cAAc;;cAoSpB,WAAQ,QAAY,cAAY,OAAO,OAAO"}
@@ -1,4 +1,4 @@
1
- import { S as Policy } from "./attach-DPgyv78F.mjs";
1
+ import { S as Policy } from "./attach-CJl-GtbN.mjs";
2
2
  import { AnyEntity } from "foldkit-entity";
3
3
  import { DrizzleOperators, Visible } from "foldkit-remote-drizzle";
4
4
  export declare const GuardDrizzle: {
package/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as May, C as PrincipalGuard, D as RowSpec, E as RowGuard, F as RowRule, M as MaySchema, N as Condition, O as ME, P as MemberRead, S as Policy, T as PrincipalSpec, _ as Builders, a as Deny, b as Guards, c as Interaction, d as Redact, f as RuleFor, g as Body, h as AnyGuard, i as Attachment, j as MayAnswer, k as MeEntity, l as InteractionKey, m as About, n as AnyRule, o as Explain, p as Surface, r as Attach, s as Inherit, t as All, u as On, v as Decision, w as PrincipalOf, x as Placeholders, y as GuardSet } from "./attach-DPgyv78F.mjs";
1
+ import { A as May, C as PrincipalGuard, D as RowSpec, E as RowGuard, F as RowRule, M as MaySchema, N as Condition, O as ME, P as MemberRead, S as Policy, T as PrincipalSpec, _ as Builders, a as Deny, b as Guards, c as Interaction, d as Redact, f as RuleFor, g as Body, h as AnyGuard, i as Attachment, j as MayAnswer, k as MeEntity, l as InteractionKey, m as About, n as AnyRule, o as Explain, p as Surface, r as Attach, s as Inherit, t as All, u as On, v as Decision, w as PrincipalOf, x as Placeholders, y as GuardSet } from "./attach-CJl-GtbN.mjs";
2
2
  export { About, type All, AnyGuard, type AnyRule, type Attach, type Attachment, Body, Builders, Condition, Decision, type Deny, type Explain, GuardSet, Guards, type Inherit, Interaction, type InteractionKey, ME, May, type MayAnswer, MaySchema, type MeEntity, type MemberRead, type On, Placeholders, Policy, PrincipalGuard, PrincipalOf, PrincipalSpec, type Redact, RowGuard, type RowRule, RowSpec, type RuleFor, type Surface };
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Who may do what, declared once on the domain.\n *\n * A guard set names its guards once, in shared code the client imports too.\n * A **principal guard** is declared by name and implemented only on the\n * server (`G.implement`), so its logic never ships. A **row guard** is an\n * `Expr` over one Entity's fields with the principal's fields as inputs: data,\n * which the SQL compiler and `evaluate` both run. See `guard-DESIGN.md`.\n */\nimport { Context, Effect, Match, Option, Schema } from 'effect'\nimport { Attaching, attached, type InteractionKey } from './attach.js'\nimport {\n deciding,\n readsPrincipal,\n type Condition,\n type MemberRead,\n type RowRule,\n} from './condition.js'\nimport { May } from './may.js'\nimport { me } from './me.js'\nimport { providedFrom } from './origin.js'\nimport {\n Expr,\n Operators,\n Query,\n evaluate,\n type AnyEntity,\n type EntityRef,\n type ExprContext,\n type MemoryOperators,\n type AnyQuery,\n type InputExpr,\n type Predicate,\n} from 'foldkit-entity'\n\n/** A guard's answer: allowed, refused, or refused with a sentence the caller may read. */\nexport type Decision = boolean | { readonly allowed: false; readonly reason: string }\n\n/** What a principal guard is asked about. */\nexport interface About {\n /** The interaction attempted: `Read`, `Update`, or one the application names. */\n readonly interaction: string\n}\n\n/**\n * The principal's fields as a row guard's body sees them: each an input named\n * `principal.<field>`, typed as the field. A body is built once, so it holds\n * these placeholders and never a value: branching on one is a type error.\n */\nexport type Placeholders<User> = {\n readonly [K in keyof User & string]: InputExpr<User[K]>\n}\n\n/** What `guard.principal()` declares: a name whose body the server supplies. */\nexport interface PrincipalSpec {\n readonly _tag: 'PrincipalSpec'\n}\n\n/** What `guard.row(entity, body)` declares: a predicate over one Entity's rows. */\nexport interface RowSpec<E extends AnyEntity> {\n readonly _tag: 'RowSpec'\n readonly entity: E\n readonly body: Predicate\n}\n\ntype AnySpec = PrincipalSpec | RowSpec<AnyEntity>\n\n/**\n * The principal a guard is for, kept in the type so a guard of one principal\n * cannot stand where another's is wanted. A function type, so it is invariant.\n */\ninterface ForPrincipal<User> {\n readonly '~principal'?: (user: User) => User\n}\n\n/** A guard whose body lives on the server, asked of the principal alone. */\nexport interface PrincipalGuard<User, Set extends string = string> extends ForPrincipal<User> {\n readonly _tag: 'PrincipalGuard'\n readonly name: string\n /** The name of the guard set it belongs to. */\n readonly set: Set\n}\n\n/** A guard over the rows of `E`: its predicate, and the query that asks it of rows. */\nexport interface RowGuard<\n User,\n E extends AnyEntity,\n Set extends string = string,\n> extends ForPrincipal<User> {\n readonly _tag: 'RowGuard'\n readonly name: string\n readonly set: Set\n readonly entity: E\n readonly body: Predicate\n /** `from(entity).where(body)`, for an interpreter that runs queries. */\n readonly query: AnyQuery\n}\n\nexport type AnyGuard<User> = PrincipalGuard<User> | RowGuard<User, AnyEntity>\n\ntype GuardOf<User, Set extends string, S> =\n S extends RowSpec<infer E> ? RowGuard<User, E, Set> : PrincipalGuard<User, Set>\n\n/** The keys of a spec record that are principal guards: what `implement` must supply. */\ntype PrincipalKeys<S> = { [K in keyof S]: S[K] extends PrincipalSpec ? K : never }[keyof S]\n\n/** A principal guard's body, on the server. */\nexport type Body<User, R = never> = (\n principal: Option.Option<User>,\n about: About,\n) => Decision | Effect.Effect<Decision, never, R>\n\n/** Names a guard set reserves for itself, which no guard may take. */\nconst reserved = [\n 'name',\n 'schema',\n 'Principal',\n 'key',\n 'unguarded',\n 'inputOf',\n 'implement',\n] as const\ntype Reserved = (typeof reserved)[number]\n\n/** Who is asking, for one guard set: a visitor is `none`. */\nexport interface PrincipalOf<Name extends string> {\n readonly '~guardSet': Name\n}\n\n/** The guard set of one application, as `Guards.declare` returns it. */\nexport type GuardSet<Name extends string, User, S> = {\n readonly [K in keyof S]: GuardOf<User, Name, S[K]>\n} & {\n readonly name: Name\n /** The principal's schema, whose fields the row guards read. */\n readonly schema: Schema.Codec<User, unknown>\n /** The server's Context key for who is asking. Authentication provides it. */\n readonly Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>\n /** A stable name for the person, whatever their claims: for what is theirs, as a cache's scope. */\n readonly key: (user: User) => string\n readonly unguarded: 'allow' | 'deny'\n /** The principal's fields as row guards' inputs, encoded as stored values are. */\n readonly inputOf: (user: User) => Readonly<Record<string, unknown>>\n /**\n * The bodies of the principal guards: every one, and nothing else. `operators`\n * runs the row guards' primitive operators in memory; `Operators.kernel` when\n * not given.\n */\n readonly implement: <R = never>(\n bodies: { readonly [K in PrincipalKeys<S>]: Body<User, R> },\n options?: { readonly operators?: MemoryOperators | undefined },\n ) => Policy<User, R>\n}\n\n/** The server's half of a guard set: every principal guard's body. */\nexport interface Policy<User, R = never> {\n readonly set: string\n /**\n * How a row guard's primitive operators are run in memory: by `decide`,\n * `Condition.holds` and every guarded server judging a row. Given to\n * `implement`; `Operators.kernel` when not.\n */\n readonly operators: MemoryOperators\n /**\n * Whether `guard` allows `principal`, for a row guard over `row` (its stored,\n * encoded values). A visitor passes no row guard that reads a principal's\n * fields; one over the row alone holds for a visitor too.\n */\n readonly decide: (\n guard: AnyGuard<User>,\n request: {\n readonly principal: Option.Option<User>\n readonly interaction: string\n readonly row?: Readonly<Record<string, unknown>> | undefined\n },\n ) => Effect.Effect<Decision, never, R>\n /**\n * Which rows of `entity` `principal` may read, as a condition over the row\n * with every principal guard already decided. An Entity without guards, or\n * of no set, reads `Always`.\n */\n readonly readable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n ) => Effect.Effect<Condition, never, R>\n /** The read rule of each of `members`, relations included, that has one, decided for `principal`. */\n readonly readMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /**\n * Which rows of `entity` `principal` may write by `interaction` (`Create`,\n * `Update`, `Delete`, or one the application named), as a condition over\n * the row, and what a refusal shows.\n */\n readonly writable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: 'Create' | 'Update' | 'Delete' | InteractionKey,\n ) => Effect.Effect<RowRule, never, R>\n /** The rule of each of `members` that has one for setting it, decided for `principal`. */\n readonly writeMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n interaction: 'Create' | 'Update',\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /** A relation's rule for linking or unlinking a row, when it has one. */\n readonly linkable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n relation: string,\n interaction: 'Link' | 'Unlink',\n ) => Effect.Effect<Option.Option<RowRule>, never, R>\n /** The principal's fields as row guards' inputs; a visitor has none. */\n readonly inputOf: (principal: Option.Option<User>) => Readonly<Record<string, unknown>>\n /**\n * Who the principal is as a row: `declare`'s `viewer` Entity, by `key`.\n * What a rule's `Expr.viewer` reads, and the server's viewer:\n * `RemoteServer.make({ viewer: Policy.viewer })`. None for a visitor, and\n * for a set that names no `viewer`.\n */\n readonly viewer: (principal: Option.Option<User>) => Option.Option<EntityRef>\n /**\n * Who the principal is: `declare`'s `key`, the same function as `G.key`,\n * here for a server seam that holds the Policy and not the set. Not\n * `keyOf`, which names a principal by every field, for sharing re-reads.\n */\n readonly key: (user: User) => string\n /**\n * Who is asking, as the rules see it: every field of the principal, encoded,\n * a visitor included. Two requests by one person with the same claims answer\n * alike, so a live hub shares their re-reads; a changed claim is not shared.\n *\n * ```ts\n * RemoteServer.liveHub(sources, { key: Policy.keyOf })\n * ```\n */\n readonly keyOf: (principal: Option.Option<User>) => string\n /**\n * Whether `value` is this set's principal, an `Option` of its schema: for a\n * seam that is handed the principal untyped.\n */\n readonly isPrincipal: (value: unknown) => value is Option.Option<User>\n /**\n * This Policy with services its bodies need provided, such as a membership\n * lookup. The read seams (`GuardDrizzle.visible`, `GuardServer.memory`,\n * `GuardSync`) take a Policy that needs nothing more: a read rule runs inside\n * a read whose requirements are its Source's. Provide what stays put here,\n * once; carry what changes per request in the principal. A seam built from\n * the result counts as built from this Policy: `validate` checks the rules,\n * not the services given them. `GuardSync.authorize` runs bodies\n * synchronously, so what it is given must answer without suspending.\n *\n * ```ts\n * const ReadPolicy = Policy.provide(Context.make(Memberships, memberships))\n * ```\n */\n readonly provide: <Provided extends R>(\n context: Context.Context<Provided>,\n ) => Policy<User, Exclude<R, Provided>>\n}\n\n/** `policy` with `context` provided to every body it runs. */\nconst provided = <User, R, Provided extends R>(\n policy: Policy<User, R>,\n context: Context.Context<Provided>,\n): Policy<User, Exclude<R, Provided>> => {\n const run = <A>(effect: Effect.Effect<A, never, R>) => Effect.provide(effect, context)\n const next: Policy<User, Exclude<R, Provided>> = {\n ...policy,\n decide: (guard, request) => run(policy.decide(guard, request)),\n readable: (entity, principal) => run(policy.readable(entity, principal)),\n readMembers: (entity, principal, members) =>\n run(policy.readMembers(entity, principal, members)),\n writable: (entity, principal, interaction) =>\n run(policy.writable(entity, principal, interaction)),\n writeMembers: (entity, principal, members, interaction) =>\n run(policy.writeMembers(entity, principal, members, interaction)),\n linkable: (entity, principal, relation, interaction) =>\n run(policy.linkable(entity, principal, relation, interaction)),\n provide: more => provided(next, more),\n }\n return providedFrom(next, policy)\n}\n\n/** The builders a guard set's declaration is given, typed by its principal. */\nexport interface Builders<User> {\n /** A guard decided from the principal alone, by a body only the server has. */\n readonly principal: () => PrincipalSpec\n /** A guard over `entity`'s rows: a predicate with the principal's fields as inputs. */\n readonly row: <E extends AnyEntity>(\n entity: E,\n body: (principal: Placeholders<User>) => Predicate,\n ) => RowSpec<E>\n}\n\nconst placeholdersOf = <User>(fields: Schema.Struct.Fields): Placeholders<User> =>\n // Built as entries, so a field named `__proto__` is a key of its own, not the prototype.\n Object.freeze(\n Object.fromEntries(\n Object.entries(fields).map(([key, schema]): [string, InputExpr<unknown>] => [\n key,\n Expr.input(`principal.${key}`, schema as unknown as Schema.Codec<unknown, unknown>),\n ]),\n ),\n ) as Placeholders<User>\n\nexport { Condition, type MemberRead, type RowRule } from './condition.js'\nexport { May, MaySchema, type MayAnswer } from './may.js'\nexport { ME, type MeEntity } from './me.js'\nexport {\n Interaction,\n type All,\n type AnyRule,\n type Attach,\n type Attachment,\n type Deny,\n type Explain,\n type Inherit,\n type InteractionKey,\n type On,\n type Redact,\n type RuleFor,\n type Surface,\n} from './attach.js'\n\nexport const Guards = {\n ...Attaching,\n /**\n * Adds the `may` member, the server's answer to what a principal may do\n * with a row, after its guards are attached:\n * `TodoFields.pipe(Guards.attach(G, { … }), Guards.may)`.\n */\n may: May.member,\n /**\n * `Me`, the visitor as an Entity: one row, `me`, that everyone reads and no\n * one writes, with `signedIn`, the principal's `key`, and `may` for the\n * interactions named here. Serve it with `GuardServer.me`.\n *\n * ```ts\n * export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })\n * ```\n */\n me,\n /**\n * One application's guards, under `name` (its principal's Context key, and\n * what the matrix prints). `principal` is a `Schema.Struct`: its fields are\n * what a row guard reads, and its codec encodes a principal's values as\n * stored values are encoded.\n *\n * ```ts\n * const G = Guards.declare('Todos', User, guard => ({\n * isAdmin: guard.principal(),\n * isOwner: guard.row(TodoFields, p => Expr.eq(TodoFields.fields.ownerId, p.id)),\n * }), { key: user => user.id })\n * ```\n */\n declare: <\n const Name extends string,\n Fields extends Schema.Struct.Fields,\n const S extends Readonly<Record<string, AnySpec>> & { readonly [K in Reserved]?: never },\n >(\n name: Name,\n principal: Schema.Struct<Fields>,\n build: (guard: Builders<Schema.Struct.Type<Fields>>) => S,\n options: {\n readonly key: (user: Schema.Struct.Type<Fields>) => string\n /**\n * What a surface of a guarded Entity with no rules decides: `'deny'`\n * refuses it, `'allow'` lets everyone. Required, so an open surface is\n * a decision written down; `Guards.matrix` prints it `closed` or `open`.\n */\n readonly unguarded: 'allow' | 'deny'\n /**\n * The Entity whose row each principal is, by `key`: what a row guard's\n * `Expr.viewer` of it reads, on the server and the client alike. A set\n * without one refuses a rule that reads the viewer.\n */\n readonly viewer?: AnyEntity | undefined\n },\n ): GuardSet<Name, Schema.Struct.Type<Fields>, S> => {\n type User = Schema.Struct.Type<Fields>\n // The type requires it; a caller without types (or one that spelled it\n // `'Allow'`) would otherwise get a set that denies, silently.\n if (options.unguarded !== 'allow' && options.unguarded !== 'deny')\n throw new Error(\n `[foldkit-guard] ${name}: unguarded must be 'allow' or 'deny', not ${JSON.stringify(options.unguarded)}`,\n )\n const placeholders = placeholdersOf<User>(principal.fields)\n const specs = build({\n principal: () => Object.freeze({ _tag: 'PrincipalSpec' }),\n row: (entity, body) => {\n const predicate = body(placeholders)\n const { operations } = Query.dependencies(Query.from(entity).pipe(Query.where(predicate)))\n // Who may is decided when asked, not at a write's time, which the rule is never given.\n if (operations.includes('now')) {\n throw new Error(\n `[foldkit-guard] ${name}: a rule over ${entity.name} reads Expr.now; who may do something does not move with the clock here`,\n )\n }\n if (operations.includes('viewer') && options.viewer === undefined) {\n throw new Error(\n `[foldkit-guard] ${name}: a rule over ${entity.name} reads Expr.viewer, but the set names no viewer Entity; declare it with { viewer }`,\n )\n }\n return Object.freeze({ _tag: 'RowSpec', entity, body: predicate })\n },\n })\n const guards: Record<string, AnyGuard<User>> = Object.create(null)\n for (const [guard, spec] of Object.entries(specs)) {\n if ((reserved as ReadonlyArray<string>).includes(guard)) {\n throw new Error(\n `[foldkit-guard] ${name}: \"${guard}\" is a name the guard set keeps for itself`,\n )\n }\n guards[guard] = Match.valueTags(spec, {\n PrincipalSpec: (): AnyGuard<User> =>\n Object.freeze({ _tag: 'PrincipalGuard', name: guard, set: name }),\n RowSpec: ({ entity, body }): AnyGuard<User> =>\n Object.freeze({\n _tag: 'RowGuard',\n name: guard,\n set: name,\n entity,\n body,\n // Checks the body reads only this Entity's fields, where it is declared.\n query: Query.from(entity).pipe(Query.where(body)),\n }),\n })\n }\n const principalNames = Object.keys(guards).filter(\n guard => guards[guard]!._tag === 'PrincipalGuard',\n )\n const encoders = Object.fromEntries(\n Object.entries(principal.fields).map(([field, schema]) => [\n field,\n Schema.encodeSync(schema as unknown as Schema.Codec<unknown, unknown>),\n ]),\n )\n const inputOf = (user: User): Readonly<Record<string, unknown>> => {\n const input: Record<string, unknown> = {}\n for (const [field, encode] of Object.entries(encoders)) {\n input[`principal.${field}`] = encode((user as Record<string, unknown>)[field])\n }\n return input\n }\n\n const viewerOf = (user: Option.Option<User>): Option.Option<EntityRef> =>\n Option.flatMap(Option.fromUndefinedOr(options.viewer), entity =>\n Option.map(user, each => ({ entity: entity.name, id: options.key(each) })),\n )\n // A rule reads who asks, never a time.\n const contextOf = (user: Option.Option<User>): ExprContext => ({\n viewer: viewerOf(user),\n now: Option.none(),\n })\n\n const isPrincipal = Schema.is(Schema.Option(principal))\n // Every claim as JSON keeps it, a set, a number past JSON's or a date\n // included: two principals that differ in one never share a key.\n const asJson = Schema.encodeSync(\n Schema.toCodecJson(principal) as unknown as Schema.Codec<unknown, unknown>,\n )\n\n const implement = <R>(\n bodies: Readonly<Record<string, Body<User, R>>>,\n implementation: { readonly operators?: MemoryOperators | undefined } = {},\n ): Policy<User, R> => {\n const operators = implementation.operators ?? Operators.kernel\n const missing = principalNames.filter(guard => !Object.hasOwn(bodies, guard))\n const extra = Object.keys(bodies).filter(guard => !principalNames.includes(guard))\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `[foldkit-guard] ${name}.implement: ${[\n missing.length > 0 ? `no body for ${missing.join(', ')}` : '',\n extra.length > 0 ? `${extra.join(', ')} is not a principal guard` : '',\n ]\n .filter(part => part !== '')\n .join('; ')}`,\n )\n }\n const decide: Policy<User, R>['decide'] = (guard, { principal, interaction, row }) => {\n if (guard.set !== name) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: \"${guard.name}\" belongs to ${guard.set}`),\n )\n }\n return Match.valueTags(guard, {\n PrincipalGuard: ({ name: body }) => {\n const decided = bodies[body]!(principal, { interaction })\n return Effect.isEffect(decided) ? decided : Effect.succeed(decided)\n },\n RowGuard: rowGuard =>\n Effect.succeed(\n row !== undefined &&\n Option.match(principal, {\n // A visitor has no fields: only a guard over the row alone can hold.\n onNone: () =>\n !readsPrincipal(rowGuard) &&\n evaluate(rowGuard.query, {}, [row], {\n operators,\n context: contextOf(principal),\n }).length === 1,\n onSome: user =>\n evaluate(rowGuard.query, inputOf(user), [row], {\n operators,\n context: contextOf(principal),\n }).length === 1,\n }),\n ),\n })\n }\n const decidingFor = (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: string,\n ) => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== name) {\n throw new Error(`[foldkit-guard] ${name}: ${entity.name} carries the guards of ${set}`)\n }\n })\n return deciding(\n guard =>\n Effect.map(decide(guard, { principal, interaction }), decision => decision === true),\n Option.isNone(principal),\n interaction,\n contextOf(principal),\n )\n }\n const policy: Policy<User, R> = {\n set: name,\n operators,\n decide,\n readable: (entity, principal) =>\n Effect.map(\n decidingFor(entity, principal, 'Read').row(entity),\n ({ condition }) => condition,\n ),\n readMembers: (entity, principal, members) =>\n decidingFor(entity, principal, 'Read').members(entity, members),\n writable: (entity, principal, interaction) =>\n decidingFor(entity, principal, interaction).row(entity),\n writeMembers: (entity, principal, members, interaction) =>\n decidingFor(entity, principal, interaction).members(entity, members),\n linkable: (entity, principal, relation, interaction) =>\n decidingFor(entity, principal, interaction).relation(entity, relation),\n inputOf: principal =>\n Option.match(principal, { onNone: () => ({}), onSome: user => inputOf(user) }),\n viewer: viewerOf,\n key: options.key,\n // Prefixed, so no user's key is the visitor's. Not `declare`'s `key`\n // alone: a re-read shared under it would read a newer request as an\n // older one's claims.\n keyOf: principal =>\n Option.match(principal, {\n onNone: () => 'visitor',\n onSome: user => `user:${JSON.stringify(asJson(user))}`,\n }),\n isPrincipal,\n provide: context => provided(policy, context),\n }\n return policy\n }\n\n return Object.freeze({\n ...guards,\n name,\n schema: principal as unknown as Schema.Codec<User, unknown>,\n Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>(\n `foldkit-guard/Principal/${name}`,\n ),\n key: options.key,\n unguarded: options.unguarded,\n inputOf,\n implement,\n }) as unknown as GuardSet<Name, User, S>\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiHA,MAAM,WAAW;CACf;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAgJA,MAAM,YACJ,QACA,YACuC;CACvC,MAAM,OAAU,WAAuC,OAAO,QAAQ,QAAQ,OAAO;CACrF,MAAM,OAA2C;EAC/C,GAAG;EACH,SAAS,OAAO,YAAY,IAAI,OAAO,OAAO,OAAO,OAAO,CAAC;EAC7D,WAAW,QAAQ,cAAc,IAAI,OAAO,SAAS,QAAQ,SAAS,CAAC;EACvE,cAAc,QAAQ,WAAW,YAC/B,IAAI,OAAO,YAAY,QAAQ,WAAW,OAAO,CAAC;EACpD,WAAW,QAAQ,WAAW,gBAC5B,IAAI,OAAO,SAAS,QAAQ,WAAW,WAAW,CAAC;EACrD,eAAe,QAAQ,WAAW,SAAS,gBACzC,IAAI,OAAO,aAAa,QAAQ,WAAW,SAAS,WAAW,CAAC;EAClE,WAAW,QAAQ,WAAW,UAAU,gBACtC,IAAI,OAAO,SAAS,QAAQ,WAAW,UAAU,WAAW,CAAC;EAC/D,UAAS,SAAQ,SAAS,MAAM,IAAI;CACtC;CACA,OAAO,aAAa,MAAM,MAAM;AAClC;AAaA,MAAM,kBAAwB,WAE5B,OAAO,OACL,OAAO,YACL,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,CAAC,KAAK,YAA0C,CAC1E,KACA,KAAK,MAAM,aAAa,OAAO,MAAmD,CACpF,CAAC,CACH,CACF;AAqBF,MAAa,SAAS;CACpB,GAAG;;;;;;CAMH,KAAK,IAAI;;;;;;;;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AC,CAAC,IAAI,MAAM,IAChD,EAAE,gBAAgB,SACrB;IACF,cAAc,QAAQ,WAAW,YAC/B,YAAY,QAAQ,WAAW,MAAM,CAAC,CAAC,QAAQ,QAAQ,OAAO;IAChE,WAAW,QAAQ,WAAW,gBAC5B,YAAY,QAAQ,WAAW,WAAW,CAAC,CAAC,IAAI,MAAM;IACxD,eAAe,QAAQ,WAAW,SAAS,gBACzC,YAAY,QAAQ,WAAW,WAAW,CAAC,CAAC,QAAQ,QAAQ,OAAO;IACrE,WAAW,QAAQ,WAAW,UAAU,gBACtC,YAAY,QAAQ,WAAW,WAAW,CAAC,CAAC,SAAS,QAAQ,QAAQ;IACvE,UAAS,cACP,OAAO,MAAM,WAAW;KAAE,eAAe,CAAC;KAAI,SAAQ,SAAQ,QAAQ,IAAI;IAAE,CAAC;IAC/E,QAAQ;IACR,KAAK,QAAQ;IAIb,QAAO,cACL,OAAO,MAAM,WAAW;KACtB,cAAc;KACd,SAAQ,SAAQ,QAAQ,KAAK,UAAU,OAAO,IAAI,CAAC;IACrD,CAAC;IACH;IACA,UAAS,YAAW,SAAS,QAAQ,OAAO;GAC9C;GACA,OAAO;EACT;EAEA,OAAO,OAAO,OAAO;GACnB,GAAG;GACH;GACA,QAAQ;GACR,WAAW,QAAQ,QACjB,2BAA2B,MAC7B;GACA,KAAK,QAAQ;GACb,WAAW,QAAQ;GACnB;GACA;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Who may do what, declared once on the domain.\n *\n * A guard set names its guards once, in shared code the client imports too.\n * A **principal guard** is declared by name and implemented only on the\n * server (`G.implement`), so its logic never ships. A **row guard** is an\n * `Expr` over one Entity's fields with the principal's fields as inputs: data,\n * which the SQL compiler and `evaluate` both run. See `guard-DESIGN.md`.\n */\nimport { Context, Effect, Match, Option, Schema } from 'effect'\nimport { Attaching, attached, type InteractionKey } from './attach.js'\nimport {\n deciding,\n readsPrincipal,\n type Condition,\n type MemberRead,\n type RowRule,\n} from './condition.js'\nimport { May } from './may.js'\nimport { me } from './me.js'\nimport { providedFrom } from './origin.js'\nimport {\n Expr,\n Operators,\n Query,\n evaluate,\n type AnyEntity,\n type EntityRef,\n type ExprContext,\n type MemoryOperators,\n type AnyQuery,\n type InputExpr,\n type Invalid,\n type Predicate,\n type ReadsOf,\n} from 'foldkit-entity'\n\n/** A guard's answer: allowed, refused, or refused with a sentence the caller may read. */\nexport type Decision = boolean | { readonly allowed: false; readonly reason: string }\n\n/** What a principal guard is asked about. */\nexport interface About {\n /** The interaction attempted: `Read`, `Update`, or one the application names. */\n readonly interaction: string\n}\n\n/**\n * The principal's fields as a row guard's body sees them: each an input named\n * `principal.<field>`, typed as the field. A body is built once, so it holds\n * these placeholders and never a value: branching on one is a type error.\n */\nexport type Placeholders<User> = {\n readonly [K in keyof User & string]: InputExpr<User[K]>\n}\n\n/** What `guard.principal()` declares: a name whose body the server supplies. */\nexport interface PrincipalSpec {\n readonly _tag: 'PrincipalSpec'\n}\n\n/** What `guard.row(entity, body)` declares: a predicate over one Entity's rows. */\nexport interface RowSpec<E extends AnyEntity> {\n readonly _tag: 'RowSpec'\n readonly entity: E\n readonly body: Predicate\n}\n\ntype AnySpec = PrincipalSpec | RowSpec<AnyEntity>\n\n/**\n * The principal a guard is for, kept in the type so a guard of one principal\n * cannot stand where another's is wanted. A function type, so it is invariant.\n */\ninterface ForPrincipal<User> {\n readonly '~principal'?: (user: User) => User\n}\n\n/** A guard whose body lives on the server, asked of the principal alone. */\nexport interface PrincipalGuard<User, Set extends string = string> extends ForPrincipal<User> {\n readonly _tag: 'PrincipalGuard'\n readonly name: string\n /** The name of the guard set it belongs to. */\n readonly set: Set\n}\n\n/** A guard over the rows of `E`: its predicate, and the query that asks it of rows. */\nexport interface RowGuard<\n User,\n E extends AnyEntity,\n Set extends string = string,\n> extends ForPrincipal<User> {\n readonly _tag: 'RowGuard'\n readonly name: string\n readonly set: Set\n readonly entity: E\n readonly body: Predicate\n /** `from(entity).where(body)`, for an interpreter that runs queries. */\n readonly query: AnyQuery\n}\n\nexport type AnyGuard<User> = PrincipalGuard<User> | RowGuard<User, AnyEntity>\n\ntype GuardOf<User, Set extends string, S> =\n S extends RowSpec<infer E> ? RowGuard<User, E, Set> : PrincipalGuard<User, Set>\n\n/** The keys of a spec record that are principal guards: what `implement` must supply. */\ntype PrincipalKeys<S> = { [K in keyof S]: S[K] extends PrincipalSpec ? K : never }[keyof S]\n\n/** A principal guard's body, on the server. */\nexport type Body<User, R = never> = (\n principal: Option.Option<User>,\n about: About,\n) => Decision | Effect.Effect<Decision, never, R>\n\n/** Names a guard set reserves for itself, which no guard may take. */\nconst reserved = [\n 'name',\n 'schema',\n 'Principal',\n 'key',\n 'unguarded',\n 'inputOf',\n 'implement',\n] as const\ntype Reserved = (typeof reserved)[number]\n\n/** Who is asking, for one guard set: a visitor is `none`. */\nexport interface PrincipalOf<Name extends string> {\n readonly '~guardSet': Name\n}\n\n/** The guard set of one application, as `Guards.declare` returns it. */\nexport type GuardSet<Name extends string, User, S> = {\n readonly [K in keyof S]: GuardOf<User, Name, S[K]>\n} & {\n readonly name: Name\n /** The principal's schema, whose fields the row guards read. */\n readonly schema: Schema.Codec<User, unknown>\n /** The server's Context key for who is asking. Authentication provides it. */\n readonly Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>\n /** A stable name for the person, whatever their claims: for what is theirs, as a cache's scope. */\n readonly key: (user: User) => string\n readonly unguarded: 'allow' | 'deny'\n /** The principal's fields as row guards' inputs, encoded as stored values are. */\n readonly inputOf: (user: User) => Readonly<Record<string, unknown>>\n /**\n * The bodies of the principal guards: every one, and nothing else. `operators`\n * runs the row guards' primitive operators in memory; `Operators.kernel` when\n * not given.\n */\n readonly implement: <R = never>(\n bodies: { readonly [K in PrincipalKeys<S>]: Body<User, R> },\n options?: { readonly operators?: MemoryOperators | undefined },\n ) => Policy<User, R>\n}\n\n/** The server's half of a guard set: every principal guard's body. */\nexport interface Policy<User, R = never> {\n readonly set: string\n /**\n * How a row guard's primitive operators are run in memory: by `decide`,\n * `Condition.holds` and every guarded server judging a row. Given to\n * `implement`; `Operators.kernel` when not.\n */\n readonly operators: MemoryOperators\n /**\n * Whether `guard` allows `principal`, for a row guard over `row` (its stored,\n * encoded values). A visitor passes no row guard that reads a principal's\n * fields; one over the row alone holds for a visitor too.\n */\n readonly decide: (\n guard: AnyGuard<User>,\n request: {\n readonly principal: Option.Option<User>\n readonly interaction: string\n readonly row?: Readonly<Record<string, unknown>> | undefined\n },\n ) => Effect.Effect<Decision, never, R>\n /**\n * Which rows of `entity` `principal` may read, as a condition over the row\n * with every principal guard already decided. An Entity without guards, or\n * of no set, reads `Always`.\n */\n readonly readable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n ) => Effect.Effect<Condition, never, R>\n /** The read rule of each of `members`, relations included, that has one, decided for `principal`. */\n readonly readMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /**\n * Which rows of `entity` `principal` may write by `interaction` (`Create`,\n * `Update`, `Delete`, or one the application named), as a condition over\n * the row, and what a refusal shows.\n */\n readonly writable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: 'Create' | 'Update' | 'Delete' | InteractionKey,\n ) => Effect.Effect<RowRule, never, R>\n /** The rule of each of `members` that has one for setting it, decided for `principal`. */\n readonly writeMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n interaction: 'Create' | 'Update',\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /** A relation's rule for linking or unlinking a row, when it has one. */\n readonly linkable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n relation: string,\n interaction: 'Link' | 'Unlink',\n ) => Effect.Effect<Option.Option<RowRule>, never, R>\n /** The principal's fields as row guards' inputs; a visitor has none. */\n readonly inputOf: (principal: Option.Option<User>) => Readonly<Record<string, unknown>>\n /**\n * Who the principal is as a row: `declare`'s `viewer` Entity, by `key`.\n * What a rule's `Expr.viewer` reads, and the server's viewer:\n * `RemoteServer.make({ viewer: Policy.viewer })`. None for a visitor, and\n * for a set that names no `viewer`.\n */\n readonly viewer: (principal: Option.Option<User>) => Option.Option<EntityRef>\n /**\n * Who the principal is: `declare`'s `key`, the same function as `G.key`,\n * here for a server seam that holds the Policy and not the set. Not\n * `keyOf`, which names a principal by every field, for sharing re-reads.\n */\n readonly key: (user: User) => string\n /**\n * Who is asking, as the rules see it: every field of the principal, encoded,\n * a visitor included. Two requests by one person with the same claims answer\n * alike, so a live hub shares their re-reads; a changed claim is not shared.\n *\n * ```ts\n * RemoteServer.liveHub(sources, { key: Policy.keyOf })\n * ```\n */\n readonly keyOf: (principal: Option.Option<User>) => string\n /**\n * Whether `value` is this set's principal, an `Option` of its schema: for a\n * seam that is handed the principal untyped.\n */\n readonly isPrincipal: (value: unknown) => value is Option.Option<User>\n /**\n * This Policy with services its bodies need provided, such as a membership\n * lookup. The read seams (`GuardDrizzle.visible`, `GuardServer.memory`,\n * `GuardSync`) take a Policy that needs nothing more: a read rule runs inside\n * a read whose requirements are its Source's. Provide what stays put here,\n * once; carry what changes per request in the principal. A seam built from\n * the result counts as built from this Policy: `validate` checks the rules,\n * not the services given them. `GuardSync.authorize` runs bodies\n * synchronously, so what it is given must answer without suspending.\n *\n * ```ts\n * const ReadPolicy = Policy.provide(Context.make(Memberships, memberships))\n * ```\n */\n readonly provide: <Provided extends R>(\n context: Context.Context<Provided>,\n ) => Policy<User, Exclude<R, Provided>>\n}\n\n/** `policy` with `context` provided to every body it runs. */\nconst provided = <User, R, Provided extends R>(\n policy: Policy<User, R>,\n context: Context.Context<Provided>,\n): Policy<User, Exclude<R, Provided>> => {\n const run = <A>(effect: Effect.Effect<A, never, R>) => Effect.provide(effect, context)\n const next: Policy<User, Exclude<R, Provided>> = {\n ...policy,\n decide: (guard, request) => run(policy.decide(guard, request)),\n readable: (entity, principal) => run(policy.readable(entity, principal)),\n readMembers: (entity, principal, members) =>\n run(policy.readMembers(entity, principal, members)),\n writable: (entity, principal, interaction) =>\n run(policy.writable(entity, principal, interaction)),\n writeMembers: (entity, principal, members, interaction) =>\n run(policy.writeMembers(entity, principal, members, interaction)),\n linkable: (entity, principal, relation, interaction) =>\n run(policy.linkable(entity, principal, relation, interaction)),\n provide: more => provided(next, more),\n }\n return providedFrom(next, policy)\n}\n\n/** The builders a guard set's declaration is given, typed by its principal. */\nexport interface Builders<User> {\n /** A guard decided from the principal alone, by a body only the server has. */\n readonly principal: () => PrincipalSpec\n /**\n * A guard over `entity`'s rows: a predicate with the principal's fields as\n * inputs. A predicate reading another Entity's fields is refused where it\n * is written; one typed plain `Predicate` is checked when the set is\n * declared.\n */\n readonly row: <E extends AnyEntity, P extends RuleOver<P, E['name']>>(\n entity: E,\n body: (principal: Placeholders<User>) => P,\n ) => RowSpec<E>\n}\n\n/**\n * What a rule over the Entity `Name` may be: a predicate reading `Name`'s\n * fields and relations, inputs and the viewer, or one whose reads are unknown\n * to the type (a plain `Predicate`).\n */\ntype RuleOver<P, Name extends string> =\n string extends ReadsOf<P>\n ? Predicate\n : [ReadsOf<P>] extends [Name]\n ? Predicate\n : Predicate & Invalid<`foldkit-guard: a rule over ${Name} reads ${Exclude<ReadsOf<P>, Name>}`>\n\nconst placeholdersOf = <User>(fields: Schema.Struct.Fields): Placeholders<User> =>\n // Built as entries, so a field named `__proto__` is a key of its own, not the prototype.\n Object.freeze(\n Object.fromEntries(\n Object.entries(fields).map(([key, schema]): [string, InputExpr<unknown>] => [\n key,\n Expr.input(`principal.${key}`, schema as unknown as Schema.Codec<unknown, unknown>),\n ]),\n ),\n ) as Placeholders<User>\n\nexport { Condition, type MemberRead, type RowRule } from './condition.js'\nexport { May, MaySchema, type MayAnswer } from './may.js'\nexport { ME, type MeEntity } from './me.js'\nexport {\n Interaction,\n type All,\n type AnyRule,\n type Attach,\n type Attachment,\n type Deny,\n type Explain,\n type Inherit,\n type InteractionKey,\n type On,\n type Redact,\n type RuleFor,\n type Surface,\n} from './attach.js'\n\nexport const Guards = {\n ...Attaching,\n /**\n * Adds the `may` member, the server's answer to what a principal may do\n * with a row, after its guards are attached:\n * `TodoFields.pipe(Guards.attach(G, { … }), Guards.may)`.\n */\n may: May.member,\n /**\n * `Me`, the visitor as an Entity: one row, `me`, that everyone reads and no\n * one writes, with `signedIn`, the principal's `key`, and `may` for the\n * interactions named here. Serve it with `GuardServer.me`.\n *\n * ```ts\n * export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })\n * ```\n */\n me,\n /**\n * One application's guards, under `name` (its principal's Context key, and\n * what the matrix prints). `principal` is a `Schema.Struct`: its fields are\n * what a row guard reads, and its codec encodes a principal's values as\n * stored values are encoded.\n *\n * ```ts\n * const G = Guards.declare('Todos', User, guard => ({\n * isAdmin: guard.principal(),\n * isOwner: guard.row(TodoFields, p => Expr.eq(TodoFields.fields.ownerId, p.id)),\n * }), { key: user => user.id })\n * ```\n */\n declare: <\n const Name extends string,\n Fields extends Schema.Struct.Fields,\n const S extends Readonly<Record<string, AnySpec>> & { readonly [K in Reserved]?: never },\n >(\n name: Name,\n principal: Schema.Struct<Fields>,\n build: (guard: Builders<Schema.Struct.Type<Fields>>) => S,\n options: {\n readonly key: (user: Schema.Struct.Type<Fields>) => string\n /**\n * What a surface of a guarded Entity with no rules decides: `'deny'`\n * refuses it, `'allow'` lets everyone. Required, so an open surface is\n * a decision written down; `Guards.matrix` prints it `closed` or `open`.\n */\n readonly unguarded: 'allow' | 'deny'\n /**\n * The Entity whose row each principal is, by `key`: what a row guard's\n * `Expr.viewer` of it reads, on the server and the client alike. A set\n * without one refuses a rule that reads the viewer.\n */\n readonly viewer?: AnyEntity | undefined\n },\n ): GuardSet<Name, Schema.Struct.Type<Fields>, S> => {\n type User = Schema.Struct.Type<Fields>\n // The type requires it; a caller without types (or one that spelled it\n // `'Allow'`) would otherwise get a set that denies, silently.\n if (options.unguarded !== 'allow' && options.unguarded !== 'deny')\n throw new Error(\n `[foldkit-guard] ${name}: unguarded must be 'allow' or 'deny', not ${JSON.stringify(options.unguarded)}`,\n )\n const placeholders = placeholdersOf<User>(principal.fields)\n const specs = build({\n principal: () => Object.freeze({ _tag: 'PrincipalSpec' }),\n row: (entity, body) => {\n const predicate: Predicate = body(placeholders)\n const { operations } = Query.dependencies(Query.from(entity).pipe(Query.where(predicate)))\n // Who may is decided when asked, not at a write's time, which the rule is never given.\n if (operations.includes('now')) {\n throw new Error(\n `[foldkit-guard] ${name}: a rule over ${entity.name} reads Expr.now; who may do something does not move with the clock here`,\n )\n }\n if (operations.includes('viewer') && options.viewer === undefined) {\n throw new Error(\n `[foldkit-guard] ${name}: a rule over ${entity.name} reads Expr.viewer, but the set names no viewer Entity; declare it with { viewer }`,\n )\n }\n return Object.freeze({ _tag: 'RowSpec', entity, body: predicate })\n },\n })\n const guards: Record<string, AnyGuard<User>> = Object.create(null)\n for (const [guard, spec] of Object.entries(specs)) {\n if ((reserved as ReadonlyArray<string>).includes(guard)) {\n throw new Error(\n `[foldkit-guard] ${name}: \"${guard}\" is a name the guard set keeps for itself`,\n )\n }\n guards[guard] = Match.valueTags(spec, {\n PrincipalSpec: (): AnyGuard<User> =>\n Object.freeze({ _tag: 'PrincipalGuard', name: guard, set: name }),\n RowSpec: ({ entity, body }): AnyGuard<User> =>\n Object.freeze({\n _tag: 'RowGuard',\n name: guard,\n set: name,\n entity,\n body,\n // Checks the body reads only this Entity's fields, where it is declared.\n query: Query.from(entity).pipe(Query.where(body)),\n }),\n })\n }\n const principalNames = Object.keys(guards).filter(\n guard => guards[guard]!._tag === 'PrincipalGuard',\n )\n const encoders = Object.fromEntries(\n Object.entries(principal.fields).map(([field, schema]) => [\n field,\n Schema.encodeSync(schema as unknown as Schema.Codec<unknown, unknown>),\n ]),\n )\n const inputOf = (user: User): Readonly<Record<string, unknown>> => {\n const input: Record<string, unknown> = {}\n for (const [field, encode] of Object.entries(encoders)) {\n input[`principal.${field}`] = encode((user as Record<string, unknown>)[field])\n }\n return input\n }\n\n const viewerOf = (user: Option.Option<User>): Option.Option<EntityRef> =>\n Option.flatMap(Option.fromUndefinedOr(options.viewer), entity =>\n Option.map(user, each => ({ entity: entity.name, id: options.key(each) })),\n )\n // A rule reads who asks, never a time.\n const contextOf = (user: Option.Option<User>): ExprContext => ({\n viewer: viewerOf(user),\n now: Option.none(),\n })\n\n const isPrincipal = Schema.is(Schema.Option(principal))\n // Every claim as JSON keeps it, a set, a number past JSON's or a date\n // included: two principals that differ in one never share a key.\n const asJson = Schema.encodeSync(\n Schema.toCodecJson(principal) as unknown as Schema.Codec<unknown, unknown>,\n )\n\n const implement = <R>(\n bodies: Readonly<Record<string, Body<User, R>>>,\n implementation: { readonly operators?: MemoryOperators | undefined } = {},\n ): Policy<User, R> => {\n const operators = implementation.operators ?? Operators.kernel\n const missing = principalNames.filter(guard => !Object.hasOwn(bodies, guard))\n const extra = Object.keys(bodies).filter(guard => !principalNames.includes(guard))\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `[foldkit-guard] ${name}.implement: ${[\n missing.length > 0 ? `no body for ${missing.join(', ')}` : '',\n extra.length > 0 ? `${extra.join(', ')} is not a principal guard` : '',\n ]\n .filter(part => part !== '')\n .join('; ')}`,\n )\n }\n const decide: Policy<User, R>['decide'] = (guard, { principal, interaction, row }) => {\n if (guard.set !== name) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: \"${guard.name}\" belongs to ${guard.set}`),\n )\n }\n return Match.valueTags(guard, {\n PrincipalGuard: ({ name: body }) => {\n const decided = bodies[body]!(principal, { interaction })\n return Effect.isEffect(decided) ? decided : Effect.succeed(decided)\n },\n RowGuard: rowGuard =>\n Effect.succeed(\n row !== undefined &&\n Option.match(principal, {\n // A visitor has no fields: only a guard over the row alone can hold.\n onNone: () =>\n !readsPrincipal(rowGuard) &&\n evaluate(rowGuard.query, {}, [row], {\n operators,\n context: contextOf(principal),\n }).length === 1,\n onSome: user =>\n evaluate(rowGuard.query, inputOf(user), [row], {\n operators,\n context: contextOf(principal),\n }).length === 1,\n }),\n ),\n })\n }\n const decidingFor = (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: string,\n ) => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== name) {\n throw new Error(`[foldkit-guard] ${name}: ${entity.name} carries the guards of ${set}`)\n }\n })\n return deciding(\n guard =>\n Effect.map(decide(guard, { principal, interaction }), decision => decision === true),\n Option.isNone(principal),\n interaction,\n contextOf(principal),\n )\n }\n const policy: Policy<User, R> = {\n set: name,\n operators,\n decide,\n readable: (entity, principal) =>\n Effect.map(\n decidingFor(entity, principal, 'Read').row(entity),\n ({ condition }) => condition,\n ),\n readMembers: (entity, principal, members) =>\n decidingFor(entity, principal, 'Read').members(entity, members),\n writable: (entity, principal, interaction) =>\n decidingFor(entity, principal, interaction).row(entity),\n writeMembers: (entity, principal, members, interaction) =>\n decidingFor(entity, principal, interaction).members(entity, members),\n linkable: (entity, principal, relation, interaction) =>\n decidingFor(entity, principal, interaction).relation(entity, relation),\n inputOf: principal =>\n Option.match(principal, { onNone: () => ({}), onSome: user => inputOf(user) }),\n viewer: viewerOf,\n key: options.key,\n // Prefixed, so no user's key is the visitor's. Not `declare`'s `key`\n // alone: a re-read shared under it would read a newer request as an\n // older one's claims.\n keyOf: principal =>\n Option.match(principal, {\n onNone: () => 'visitor',\n onSome: user => `user:${JSON.stringify(asJson(user))}`,\n }),\n isPrincipal,\n provide: context => provided(policy, context),\n }\n return policy\n }\n\n return Object.freeze({\n ...guards,\n name,\n schema: principal as unknown as Schema.Codec<User, unknown>,\n Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>(\n `foldkit-guard/Principal/${name}`,\n ),\n key: options.key,\n unguarded: options.unguarded,\n inputOf,\n implement,\n }) as unknown as GuardSet<Name, User, S>\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmHA,MAAM,WAAW;CACf;CACA;CACA;C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AW,QAAQ,WAAW,UAAU,gBACtC,YAAY,QAAQ,WAAW,WAAW,CAAC,CAAC,SAAS,QAAQ,QAAQ;IACvE,UAAS,cACP,OAAO,MAAM,WAAW;KAAE,eAAe,CAAC;KAAI,SAAQ,SAAQ,QAAQ,IAAI;IAAE,CAAC;IAC/E,QAAQ;IACR,KAAK,QAAQ;IAIb,QAAO,cACL,OAAO,MAAM,WAAW;KACtB,cAAc;KACd,SAAQ,SAAQ,QAAQ,KAAK,UAAU,OAAO,IAAI,CAAC;IACrD,CAAC;IACH;IACA,UAAS,YAAW,SAAS,QAAQ,OAAO;GAC9C;GACA,OAAO;EACT;EAEA,OAAO,OAAO,OAAO;GACnB,GAAG;GACH;GACA,QAAQ;GACR,WAAW,QAAQ,QACjB,2BAA2B,MAC7B;GACA,KAAK,QAAQ;GACb,WAAW,QAAQ;GACnB;GACA;EACF,CAAC;CACH;AACF"}
package/dist/media.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as PrincipalGuard, S as Policy } from "./attach-DPgyv78F.mjs";
1
+ import { C as PrincipalGuard, S as Policy } from "./attach-CJl-GtbN.mjs";
2
2
  import { Effect, Layer, Option } from "effect";
3
3
  import { UploadPolicy } from "foldkit-media/server";
4
4
  export interface UploadPolicyConfig<User, E, R> {
package/dist/server.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { S as Policy, k as MeEntity, l as InteractionKey } from "./attach-DPgyv78F.mjs";
1
+ import { S as Policy, k as MeEntity, l as InteractionKey } from "./attach-CJl-GtbN.mjs";
2
2
  import { Effect, Option } from "effect";
3
3
  import { AnyEntity, AnyQuery } from "foldkit-entity";
4
4
  import { Diagnostic, MutationDescriptor, RemoteForbidden, ReportDiagnostic } from "foldkit-remote";
@@ -75,7 +75,8 @@ export declare const GuardServer: {
75
75
  * to a member is that member's own change. An `Unlink` rule holds over the
76
76
  * row before alone. A create's rules hold over the values it proposes, where a field the
77
77
  * create leaves unset matches no guard, not even one for an empty value. A refusal is
78
- * `Forbidden`, with the sentence an `explain` gave; the write never runs.
78
+ * `Forbidden`, with the sentence an `explain` gave, or `Unauthenticated` for a
79
+ * visitor; the write never runs.
79
80
  *
80
81
  * What the Entity sets from the write's context (`Entity.sets`: who asks,
81
82
  * when) reaches a create or an update already set by `RemoteServer.write`,
@@ -107,8 +108,8 @@ export declare const GuardServer: {
107
108
  * rule must hold over it; a row its writer may not see is refused. With no
108
109
  * `id` (a create), the rule must hold of who is asking alone, a field it
109
110
  * reads matching no guard. `run` is given the row as read: its fields the
110
- * rule reads, its `id`, and `fields`. A refusal is `Forbidden`; `run` never
111
- * runs. What `run` writes is its own: check members it sets there. Each
111
+ * rule reads, its `id`, and `fields`. A refusal is `Forbidden`, or
112
+ * `Unauthenticated` for a visitor; `run` never runs. What `run` writes is its own: check members it sets there. Each
112
113
  * row of `entity` its answer carries is read back through `source`, so the
113
114
  * answer shows its writer only what they may see, a row it hid from them
114
115
  * as deleted.
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.mts","names":[],"sources":["../src/diagnostics.ts","../src/server.ts"],"mappings":";;;;;;;;;;UAciB,uBAAuB;WAC7B;WACA;;WAEA,OAAO;;;;;;UAOD,uBAAuB;WAC7B;WACA,WAAW;;;KAIV,kBAAkB,iBAAiB;qBC4FlC;;;;;;;;;;EAUX,KAAK,MAAM,GAAC,QACF,UAAQ,QACR,OAAO,MAAM,OACpB,aAAa,OAAO,OAAO,OAAO;;;;;;;;;;EA6CrC,SAAS,MAAM,GAAC,QAAU,WAAS,QAAU,OAAO,MAAM,QAAE,WAG3C,OAAO,OAAO,OAAK,8BAE7B,OAAO,OAAO,iBAAiB;;;;;;;EAuEtC,SAAS,MAAI,QAAU,OAAO,OAAK,UAAY,cAAc;IAC3D,WAAQ,WAEO,OAAO,OAAO,OAAK,MACxB,gBAAgB,eAAe,OAAO,OAAO,SAAS,8BAC3D,OAAO,OAAO;IA4CnB;OAzHY,aAAA,WAAA,OAAA,OAAA,OAAA,8BAAiB,OAAA,OAAA;;;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B,OAAO,OAAO,iBAAiB;;;;;;;EAuEtC,SAAS,MAAI,QAAU,OAAO,OAAK,UAAY,cAAc;IAC3D,WAAQ,WAEO,OAAO,OAAO,OAAK,MACxB,gBAAgB,eAAe,OAAO,OAAO,SAAS,8BAC3D,OAAO,OAAO;IA4CnB;OAzHY,aAAA,WAAA,OAAA,OAAA,OAAA,8BAAiB,OAAA,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAuK/B,SAAS,UAAU,WAAW,MAAM,GAAG,IAAE,QAC/B,GAAC,QACD,OAAO,MAAM,IAAE,QACf,aAAa,OAAO,OAAO,OAAO,KAAG;aAElC,iBAAiB;QAE3B,aAAa,OAAO,OAAO,OAAO,IAAI;;;;;;;;;;;;;;;;;;;;;EAymBzC,WAAW,MAAM,GAAG,IAAI,IAAI,qBAAqB,OAAO,QAAQ,SAAO,UAC3D,mBAAmB,MAAM,OAAO,QAAQ,UAAQ;aAE/C,QAAQ;aACR,QAAQ,OAAO,MAAM;aACrB,8CAA8C;;;;;;aAM9C,OAAO,OAAO,mBAAmB,OAAO;;aAExC,QAAQ,aAAa,OAAO,OAAO,OAAO;;aAE1C,SAAS;KACnB,MACK;aACK,OAAO;aACP,WAAW,OAAO,OAAO;aACzB;aACA,KAAK,OAAO,OAAO,SAAS;QACjC,OAAO,OACX,gBAAgB,SAChB,oBAAoB,kBAAkB,iBACtC,QAED,eAAe,OAAO,OAAO,OAAO,IAAI,KAAK;;;;;;;;;;;;;;;;;;;;;EAgGhD,WAAW,MAAM,GAAC,QACR,OAAO,MAAM,IAAE;aAEZ,UAAU,cAAc;;aAExB;eACE;iBACE,SAAS;mBAEL;mBAA0B,OAAO;;;;aAIzC,QAAQ;;aAER,cAAc"}
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`,
@@ -515,6 +516,7 @@ const GuardServer = {
515
516
  ...revision === void 0 ? {} : { pins: true },
516
517
  ...writer.ledger === true ? { ledger: true } : {},
517
518
  ...writer.invariants === true ? { invariants: true } : {},
519
+ ...writer.cascades === true ? { cascades: true } : {},
518
520
  refuses: (write) => [
519
521
  ...writer.refuses?.(write) ?? [],
520
522
  ...write.assignments.flatMap(({ field, expr }) => Expr.unsupported([expr], {
@@ -567,15 +569,15 @@ const GuardServer = {
567
569
  })), proposed, principal);
568
570
  return yield* Effect.mapError(writer.insert(context), told);
569
571
  })),
570
- delete: (context) => Effect.andThen(discloses(context.expect, context.when), () => pinned(context.id, context.expect, (outcome) => outcome === "moved", () => Effect.gen(function* () {
572
+ delete: (context) => Effect.andThen(discloses(context.expect, context.when), () => pinned(context.id, context.expect, DeleteOutcome.$is("Moved"), () => Effect.gen(function* () {
571
573
  const row = yield* policy.writable(entity, context.principal, "Delete");
572
574
  const current = yield* read({
573
575
  id: context.id,
574
576
  fields: fieldsOf([row], versionFields(context.expect)),
575
577
  principal: context.principal
576
578
  });
577
- if (Option.isNone(current)) return "absent";
578
- if (moved(context.expect, current.value)) return "moved";
579
+ if (Option.isNone(current)) return DeleteOutcome.Absent();
580
+ if (moved(context.expect, current.value)) return DeleteOutcome.Moved();
579
581
  const requires = yield* rowRule(row, current.value, context.principal);
580
582
  return yield* writer.delete({
581
583
  ...context,
@@ -587,8 +589,14 @@ const GuardServer = {
587
589
  });
588
590
  })))
589
591
  };
590
- pins.set(guarded, Option.fromUndefinedOr(revision));
591
- return writeRules.add(guarded, policy, [entity]);
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]);
592
600
  },
593
601
  /**
594
602
  * A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for
@@ -597,8 +605,8 @@ const GuardServer = {
597
605
  * rule must hold over it; a row its writer may not see is refused. With no
598
606
  * `id` (a create), the rule must hold of who is asking alone, a field it
599
607
  * 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
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
602
610
  * row of `entity` its answer carries is read back through `source`, so the
603
611
  * answer shows its writer only what they may see, a row it hid from them
604
612
  * as deleted.
@@ -656,7 +664,7 @@ const GuardServer = {
656
664
  ...context,
657
665
  row
658
666
  }), principal);
659
- }));
667
+ }).pipe((answered) => signInFirst(context.principal, answered)));
660
668
  },
661
669
  /**
662
670
  * Checks, at startup, that `server` applies the guards of `entities`, the
@@ -833,6 +841,13 @@ const requirementOf = (condition, input) => Match.valueTags(condition, {
833
841
  And: ({ conditions }) => RowRequirement.All({ of: conditions.map((each) => requirementOf(each, input)) }),
834
842
  Or: ({ conditions }) => RowRequirement.Any({ of: conditions.map((each) => requirementOf(each, input)) })
835
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);
836
851
  const refused = (deny) => Match.valueTags(deny, {
837
852
  Explain: ({ reason }) => RemoteServer.forbid(reason),
838
853
  Forbidden: () => RemoteServer.forbid(),
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","names":[],"sources":["../src/diagnostics.ts","../src/server.ts"],"sourcesContent":["/**\n * What a guarded server meets and answers past: a computed value an operator\n * refused, answered with a fixed message, and writes `GuardServer.validate`\n * finds unpinned. Each is reported through `Diagnostics.report`.\n */\nimport type { Diagnostic } from 'foldkit-remote'\n\nconst source = 'foldkit-guard'\n\n/**\n * An operator refused to work out a value a guarded write computes (text\n * holding NUL, an implementation that throws). The write was refused with a\n * fixed message, since the operator's own may say anything.\n */\nexport interface ComputeRefused extends Diagnostic {\n readonly _tag: 'ComputeRefused'\n readonly entity: string\n /** The operator's own refusal. */\n readonly error: Error\n}\n\n/**\n * Writes through a `GuardServer.writer` given no revision, where a change can\n * come between the check and the write, which is then not seen.\n */\nexport interface UnpinnedWrites extends Diagnostic {\n readonly _tag: 'UnpinnedWrites'\n readonly mutations: ReadonlyArray<string>\n}\n\n/** Every diagnostic `foldkit-guard` reports. */\nexport type GuardDiagnostic = ComputeRefused | UnpinnedWrites\n\nexport const computeRefused = (entity: string, error: Error): ComputeRefused => ({\n _tag: 'ComputeRefused',\n source,\n level: 'error',\n message: `${entity}'s write was refused: a value it computes could not be worked out (${error.message})`,\n entity,\n error,\n})\n\nexport const unpinnedWrites = (mutations: ReadonlyArray<string>): UnpinnedWrites => ({\n _tag: 'UnpinnedWrites',\n source,\n level: 'warning',\n 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 }`,\n mutations,\n})\n","/**\n * A guard set's read rules as `foldkit-remote-server`'s seams: an\n * `EntitySource.filter` from each member's Read rule, and `RemoteServer.memory`'s\n * `readable` and `filter` from the row's, and a check at startup that a server\n * applies them. A subpath, so the shared declaration the browser imports never\n * brings the server along.\n */\nimport { Effect, Match, Option, Schema, SchemaAST, identity } from 'effect'\nimport {\n Entity,\n Expr,\n Query,\n QueryEvaluateError,\n Write,\n dependenciesOf,\n supported,\n type AnyEntity,\n type AnyQuery,\n} from 'foldkit-entity'\nimport {\n Diagnostics,\n type MutationDescriptor,\n type RemoteForbidden,\n type ReportDiagnostic,\n} from 'foldkit-remote'\nimport {\n RemoteInvalid,\n RemoteServer,\n RemoteServerError,\n RowRequirement,\n type EntityRecord,\n type EntitySource,\n type EntityWriter,\n type MutationOutcome,\n type MutationRefused,\n type MutationSource,\n type MemoryReadable,\n type ReadPlan,\n type ServerDefinition,\n type WriteRequirement,\n type WriteWhen,\n} from 'foldkit-remote-server'\nimport {\n attached,\n attachedRules,\n readRowsRuled,\n readRuled,\n surfaceOf,\n type Attachment,\n type Deny,\n type InteractionKey,\n} from './attach.js'\nimport { Condition, type MemberRead, type RowRule } from './condition.js'\nimport type { Policy } from './index.js'\nimport { answerOf, mayConditions, mayRules, type MayAnswer } from './may.js'\nimport { ME, type MeEntity } from './me.js'\nimport { memberRules, rowRules, writeRules } from './placed.js'\nimport { computeRefused, unpinnedWrites } from './diagnostics.js'\n\nexport type { ComputeRefused, GuardDiagnostic, UnpinnedWrites } from './diagnostics.js'\n\nconst noMembers = (record: EntityRecord) => record\n\n/** Two stored values, which are JSON: equal when they encode the same. */\nconst sameStored = (left: unknown, right: unknown): boolean =>\n JSON.stringify(left) === JSON.stringify(right)\n\n/** The members of `fields` that have a Read rule, once each. */\nconst hiddenOf = (\n attachment: Attachment,\n fields: ReadonlyArray<{ readonly key: string }>,\n): ReadonlyArray<string> => [\n ...new Set(fields.map(field => field.key).filter(key => readRuled(attachment, key))),\n]\n\n/** A member of a row a body reaches: the Entity it belongs to, by name, and its key. */\ninterface ReachedMember {\n readonly entity: string\n readonly key: string\n}\n\n/**\n * Each member a body reads on a row it reaches rather than judges: every\n * relation a path, a path from the viewer or an exists follows, the field a\n * path ends at, and an exists' pointing relation and filter. SQL reads such a\n * row under its `visible` rule alone, never its members'.\n */\nconst reachedMembers = (\n reaches: ReturnType<typeof dependenciesOf>['reaches'],\n): ReadonlyArray<ReachedMember> =>\n reaches.flatMap(reached => {\n const via = reached.via.map(relation => ({ entity: relation.owner.name, key: relation.key }))\n return Match.valueTags(reached, {\n Path: ({ field }) => [...via, { entity: field.owner.name, key: field.key }],\n ViewerPath: ({ field }) => [...via, { entity: field.owner.name, key: field.key }],\n Exists: ({ relation, where }) => {\n const filter = Option.match(where, {\n onNone: () => [],\n onSome: body => {\n const read = dependenciesOf(body)\n return [\n ...read.fields.map(field => ({ entity: field.entity, key: field.key })),\n ...reachedMembers(read.reaches),\n ]\n },\n })\n return [...via, { entity: relation.owner.name, key: relation.key }, ...filter]\n },\n })\n })\n\n/** Each guarded writer's `revision`, or none: one a change can fall between check and write of. */\nconst pins = new WeakMap<object, Option.Option<string>>()\n\n/** A ref key's two halves, `Entity:id`; `none` for anything else. */\nconst refOf = (value: unknown): Option.Option<{ readonly entity: string; readonly id: string }> => {\n if (typeof value !== 'string') return Option.none()\n const split = value.indexOf(':')\n return split <= 0\n ? Option.none()\n : Option.some({ entity: value.slice(0, split), id: value.slice(split + 1) })\n}\n\nexport const GuardServer = {\n /**\n * `Guards.me`'s Source: the one row, `me`, as the asker is, with `may`\n * answered by `policy`. `signedIn` is whether the server answered as\n * someone; `key` is their `key`. Any other id is no row.\n *\n * ```ts\n * RemoteServer.make({ entities: [GuardServer.me(Me, Policy), …] })\n * ```\n */\n me: <User, R>(\n entity: MeEntity,\n policy: Policy<User, R>,\n ): EntitySource<Option.Option<User>, R> => {\n // Otherwise every read would die deciding another set's guards.\n Option.map(attached(entity), ({ set }) => {\n if (set !== policy.set) {\n throw new Error(\n `[foldkit-guard] GuardServer.me: Me carries the guards of ${set}, not ${policy.set}`,\n )\n }\n })\n return {\n ...RemoteServer.entity<Option.Option<User>, R>(entity, {\n read: ({ ids, principal }) =>\n Effect.succeed(\n ids\n .filter(id => id === ME)\n .map(id => ({\n id,\n values: {\n signedIn: Option.isSome(principal),\n // Encoded, as a Source answers: `null` for a visitor.\n key: Option.match(principal, {\n onNone: () => null,\n onSome: policy.key,\n }),\n },\n })),\n ),\n filter: GuardServer.filter(entity, policy),\n }),\n // Its Read rule as this Source applies it: only the asker's own row,\n // which `Guards.me` lets anyone read. One per call: the registry is keyed\n // by it, and another call is for another Policy.\n visible: rowRules.add(Object.freeze({ reads: 'the asker’s own row' }), policy, [entity]),\n }\n },\n\n /**\n * An `EntitySource.filter` for `entity`: each requested member with a Read\n * rule is decided per record, omitted or redacted where the rule refuses.\n * The fields a rule reads are read too, so it can be decided.\n *\n * ```ts\n * RemoteServer.entity(Todo, { read, filter: GuardServer.filter(Todo, Policy) })\n * ```\n */\n filter: <User, R>(entity: AnyEntity, policy: Policy<User, R>) =>\n memberRules.add(\n (\n principal: Option.Option<User>,\n fields: readonly string[],\n ): Effect.Effect<ReadPlan, never, R> =>\n Effect.map(\n Effect.all([\n policy.readMembers(entity, principal, fields),\n // `may` is answered here, where the row is read as its principal sees it.\n asksMay(entity, fields)\n ? Effect.map(mayOf(entity, policy, principal), Option.some)\n : Effect.succeed(Option.none<MayPlan>()),\n ]),\n ([members, may]): ReadPlan => {\n if (members.length === 0 && Option.isNone(may)) return { fields, apply: noMembers }\n const input = policy.inputOf(principal)\n const decided = members.map(member => ({\n ...member,\n // A redacted value is a decoded one; the record holds what the store holds.\n redacted:\n member.deny._tag === 'Redact'\n ? Option.some(\n Schema.encodeSync(\n (\n entity.members as Readonly<\n Record<string, { readonly schema: Schema.Top }>\n >\n )[member.member]!.schema as unknown as Schema.Codec<unknown, unknown>,\n )(member.deny.value),\n )\n : Option.none(),\n }))\n return {\n fields: [\n ...new Set([\n ...fields,\n ...members.flatMap(({ condition }) => Condition.members(condition)),\n ...Option.match(may, { onNone: () => [], onSome: ({ fields }) => fields }),\n ]),\n ],\n apply: record => {\n const values: Record<string, unknown> = { ...record.values }\n for (const { member, condition, redacted } of decided) {\n // Member rules carry no inherited Read: only a row's Read may inherit.\n if (\n Condition.holds(condition, record.values, input, () => false, policy.operators)\n )\n continue\n Option.match(redacted, {\n onNone: () => {\n delete values[member]\n },\n onSome: value => {\n values[member] = value\n },\n })\n }\n Option.map(may, ({ answer }) => {\n values.may = answer(record.values)\n })\n return { id: record.id, values }\n },\n }\n },\n ),\n policy,\n [entity],\n ),\n\n /**\n * `RemoteServer.memory`'s `readable` and `filter` for `entities`, the\n * Entities as `Guards.attach` returned them. A row's Read is decided per\n * stored row, an inherited Read by looking the related row up; an Entity\n * not listed is read by everyone.\n */\n memory: <User>(policy: Policy<User>, entities: ReadonlyArray<AnyEntity>) => ({\n readable: rowRules.add(\n (\n principal: Option.Option<User>,\n row: (entity: string, id: string) => Option.Option<Readonly<Record<string, unknown>>>,\n ): Effect.Effect<MemoryReadable> =>\n Effect.map(\n Effect.forEach(entities, entity =>\n Effect.map(\n policy.readable(entity, principal),\n condition => [entity.name, condition] as const,\n ),\n ),\n (decided): MemoryReadable => {\n const conditions = new Map(decided)\n const input = policy.inputOf(principal)\n // `seen` stops a cycle of inherited Reads, which would otherwise never end.\n const holds = (\n entity: string,\n values: Readonly<Record<string, unknown>>,\n seen: ReadonlySet<string>,\n ): boolean => {\n const condition = conditions.get(entity)\n if (condition === undefined) return true\n return Condition.holds(\n condition,\n values,\n input,\n relation =>\n Option.match(refOf(values[relation]), {\n onNone: () => false,\n onSome: ref => {\n const key = `${ref.entity}:${ref.id}`\n if (seen.has(key)) return false\n return Option.match(row(ref.entity, ref.id), {\n onNone: () => false,\n onSome: target => holds(ref.entity, target, new Set([...seen, key])),\n })\n },\n }),\n policy.operators,\n )\n }\n return (entity, values) => holds(entity, values, new Set())\n },\n ),\n policy,\n entities,\n ),\n filter: Object.fromEntries(\n entities.map(entity => [entity.name, GuardServer.filter(entity, policy)] as const),\n ),\n }),\n\n /**\n * `writer` with `entity`'s write rules checked before each write lands, for\n * `RemoteServer.write`. An update or a delete reads the row first under\n * the writer's own `read` (its Source's read rule): a row the writer may not\n * see is refused as one that is not there, and a delete of it changes\n * nothing. Then the row's rule for the command must hold over the row, each\n * member it sets must allow setting it, and each relation it points\n * elsewhere must allow the unlink and the link. An update's row rule holds\n * over the row as it would be after it too, so a write cannot move a row out\n * of its writer's reach. Each of its member and `Link` rules holds over the\n * row after with that one change undone (that member's value, or where that\n * relation pointed, as before): the change must be allowed given everything\n * else the write does, so one write cannot set together what each change\n * alone would be refused, while a rule reading its own member (\"only while\n * a draft\") still allows the change. An increment or a computed assignment\n * to a member is that member's own change. An `Unlink` rule holds over the\n * row before alone. A create's rules hold over the values it proposes, where a field the\n * create leaves unset matches no guard, not even one for an empty value. A refusal is\n * `Forbidden`, with the sentence an `explain` gave; the write never runs.\n *\n * What the Entity sets from the write's context (`Entity.sets`: who asks,\n * when) reaches a create or an update already set by `RemoteServer.write`,\n * so a rule over it holds of the creator. A member rule over such a member\n * judges the server's value like any other: declare none there.\n *\n * `revision` names a field stored as a number, which the writer moves on by\n * one with each write it lands. An update or a delete then lands only on the\n * revision its rules were decided over (the writer's `expect`), so a change\n * between the check and the write is never written over; it is decided\n * again against the row as it now is, up to three times. A change that does\n * not move the revision (a handler's, `applyEdits`', raw SQL) is not seen.\n * Without `revision`, none is, and `validate` warns of an update, or a delete\n * of an Entity the server updates (an insert has no row). An input that expects a\n * revision the row read is not at is a `Conflict`, decided before any rule;\n * an input may expect only the field the writer pins.\n *\n * ```ts\n * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))\n * ```\n */\n writer: <E extends AnyEntity, User, R, RW>(\n entity: E,\n policy: Policy<User, R>,\n writer: EntityWriter<Option.Option<User>, RW>,\n options: {\n readonly revision?: keyof E['fields'] & string\n } = {},\n ): EntityWriter<Option.Option<User>, R | RW> => {\n const revision = options.revision\n if (revision !== undefined) {\n const field = Object.hasOwn(entity.fields, revision)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[revision]\n : undefined\n if (field === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${revision}\" for its revision`,\n )\n }\n // The writer moves it on by one in the statement it writes with, so it is stored as a number.\n if (!SchemaAST.isNumber(Schema.toEncoded(field.schema).ast)) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s revision \"${revision}\" is not stored as a number`,\n )\n }\n }\n if (writer.entity !== entity.name) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s rules over a writer for ${writer.entity}`,\n )\n }\n const read = writer.read\n if (read === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s writer reads no row as its writer may see it; bind it with a visible rule (GuardDrizzle.visible)`,\n )\n }\n // A rule reading another row is judged in the statement that writes: the writer must.\n const reaching = Option.match(attached(entity), {\n onNone: () => [],\n onSome: ({ row }) =>\n (['Update', 'Delete'] as const).flatMap(interaction =>\n (row[interaction]?.rules ?? []).flatMap(function names(rule): ReadonlyArray<string> {\n return Match.valueTags(rule, {\n PrincipalGuard: () => [],\n RowGuard: guard =>\n Query.dependencies(guard.query).reaches.length > 0 ? [guard.name] : [],\n All: ({ rules }) => rules.flatMap(names),\n Inherit: () => [],\n })\n }),\n ),\n })\n if (reaching.length > 0 && writer.requires !== true) {\n throw new Error(\n `[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`,\n )\n }\n /**\n * The row rule over `values` as far as one row decides it: refused where it\n * fails, and otherwise what the writer's statement must still judge.\n */\n const rowRule = (\n rule: RowRule,\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ): Effect.Effect<Option.Option<WriteRequirement>, RemoteForbidden> => {\n const left = Condition.residual(\n rule.condition,\n values,\n policy.inputOf(principal),\n policy.operators,\n )\n return Match.valueTags(left, {\n Always: () => Effect.succeed(Option.none()),\n Never: () => Effect.fail(refused(rule.deny)),\n Row: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n Inherit: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n And: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n Or: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n })\n }\n const required = (\n left: Condition,\n deny: Deny,\n principal: Option.Option<User>,\n ): WriteRequirement => ({\n holds: requirementOf(left, policy.inputOf(principal)),\n reason: explained(deny),\n })\n const holds = (\n rule: { readonly condition: Condition },\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\n Condition.holds(\n rule.condition,\n values,\n policy.inputOf(principal),\n () => false,\n policy.operators,\n )\n /** Fails with the first rule of `rules` that does not hold over `values`. */\n const require = (\n rules: ReadonlyArray<{ readonly condition: Condition; readonly deny: Deny }>,\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\n Option.match(Option.fromUndefinedOr(rules.find(rule => !holds(rule, values, principal))), {\n onNone: () => Effect.void,\n onSome: rule => Effect.fail(refused(rule.deny)),\n })\n type Links = Readonly<\n Record<string, Option.Option<{ readonly entity: string; readonly id: string }>>\n >\n /** Each relation `links` points: its rules for unlinking and for linking a row. */\n const linkRules = (principal: Option.Option<User>, links: Links) =>\n Effect.forEach(Object.entries(links), ([relation, target]) =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Unlink'),\n policy.linkable(entity, principal, relation, 'Link'),\n ]),\n ([unlink, link]) => ({ relation, now: linkKey(target), unlink, link }),\n ),\n )\n /**\n * The rules a change from what each relation was linked to, to what it now\n * points at, must meet; none `before` is a create, which unlinks nothing.\n * Where `exact` is false, `links` are the row as its writer sees it, where\n * a link to a row hidden from them reads as none: a relation seen unlinked\n * may be linked after all, so changing it unlinks too.\n */\n const linking = (\n rules: ReadonlyArray<{\n readonly relation: string\n readonly now: string | null\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n before: Option.Option<{\n readonly links: Readonly<Record<string, unknown>>\n readonly exact: boolean\n }>,\n ): ReadonlyArray<RowRule> =>\n rules.flatMap(({ relation, now, unlink, link }) =>\n Option.match(before, {\n onNone: () => (now === null ? [] : Option.toArray(link)),\n onSome: ({ links, exact }) => {\n const was = links[relation] ?? null\n if (was === now && (exact || was !== null)) return []\n return [\n ...(was === null && exact ? [] : Option.toArray(unlink)),\n ...(now === null ? [] : Option.toArray(link)),\n ]\n },\n }),\n )\n const ruleOf = (\n rules: ReadonlyArray<{\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n ) => rules.flatMap(({ unlink, link }) => [...Option.toArray(unlink), ...Option.toArray(link)])\n const fieldsOf = (\n rules: ReadonlyArray<{ readonly condition: Condition }>,\n more: Iterable<string>,\n ) => [\n ...new Set([\n 'id',\n ...more,\n ...rules.flatMap(({ condition }) => Condition.members(condition)),\n ]),\n ]\n type Expect = Option.Option<{ readonly field: string; readonly revision: unknown }>\n /** The fields that say which version of the row was read: the revision, and the input's. */\n const versionFields = (expect: Expect) => [\n ...(revision === undefined ? [] : [revision]),\n ...Option.match(expect, { onNone: () => [], onSome: ({ field }) => [field] }),\n ]\n /** Whether the row read is not at the revision the input expects. */\n const moved = (expect: Expect, before: Readonly<Record<string, unknown>>) =>\n Option.exists(expect, ({ field, revision }) => !sameStored(before[field], revision))\n /** The write held to the row its rules were decided over, where there is a revision. */\n const pin = (expect: Expect, before: Readonly<Record<string, unknown>>): Expect =>\n revision === undefined ? expect : Option.some({ field: revision, revision: before[revision] })\n /**\n * `attempt` run again while its pinned write misses: the row moved after it\n * was read, so it is decided again over the row as it now is. A write the\n * input pinned misses as a conflict, and is not run again.\n */\n const pinned = <A, E, RA>(\n id: string,\n expect: Expect,\n missed: (outcome: A) => boolean,\n attempt: () => Effect.Effect<A, E, RA>,\n ): Effect.Effect<A, E | RemoteServerError, RA> => {\n if (revision === undefined) return attempt()\n if (Option.isSome(expect)) {\n // The pin is the one revision the write moves on; another would stand still.\n return expect.value.field === revision\n ? attempt()\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s input expects \"${expect.value.field}\", but its writer pins \"${revision}\"`,\n }),\n )\n }\n const loop = (left: number): Effect.Effect<A, E | RemoteServerError, RA> =>\n Effect.flatMap(attempt(), outcome =>\n !missed(outcome)\n ? Effect.succeed(outcome)\n : left > 1\n ? loop(left - 1)\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name} ${id} changed while it was written`,\n }),\n ),\n )\n return loop(3)\n }\n const attachment = attached(entity)\n const hiddenByBody = new WeakMap<AnyQuery, ReadonlyArray<string>>()\n // An invariant reading a member a Read rule hides is still enforced, but named to no\n // one: which one failed, and where, would say what that member holds.\n const unnamed = new Set(\n Option.match(attachment, {\n onNone: () => [],\n onSome: ruled =>\n Entity.invariants(entity)\n .filter(held => [...held.before, ...held.after].some(key => readRuled(ruled, key)))\n .map(held => held.id),\n }),\n )\n const told = <E>(error: E | RemoteInvalid): E | RemoteInvalid =>\n error instanceof RemoteInvalid && Option.exists(error.rule, rule => unnamed.has(rule))\n ? RemoteServer.invalid('The row would be invalid')\n : error\n /**\n * Fails a write whose `when` reads, whose `expect` names, or whose\n * computed assignment reads, a member with a Read rule: Unmet or written,\n * Conflict or not, and the computed value answered, would answer for it.\n * `validate` refuses the same at startup; this holds where it was not run.\n */\n const discloses = (\n expect: Expect,\n when: Option.Option<WriteWhen>,\n assignments: UpdateContext['assignments'] = {},\n ): Effect.Effect<void, RemoteServerError> =>\n Option.match(attachment, {\n onNone: () => Effect.void,\n onSome: ruled => {\n const read = Option.match(when, {\n onNone: () => [],\n onSome: ({ body }) => {\n const known = hiddenByBody.get(body)\n if (known !== undefined) return known\n const hidden = hiddenOf(ruled, Query.dependencies(body).predicate)\n hiddenByBody.set(body, hidden)\n return hidden\n },\n })\n const expected = Option.match(expect, {\n onNone: () => [],\n onSome: ({ field }) => (readRuled(ruled, field) ? [field] : []),\n })\n const computed = Write.boundReads({ increments: {}, assignments }).filter(field =>\n readRuled(ruled, field),\n )\n const hidden = [...new Set([...read, ...expected, ...computed])]\n return hidden.length === 0\n ? Effect.void\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write reads ${hidden.join(', ')}, which a Read rule hides from its writer`,\n }),\n )\n },\n })\n /**\n * The answer the writer's ledger holds for this operation, as `answered`\n * makes it, or else `write`: a retry of a write that landed is answered as\n * it landed, not decided again over a row, or a time, that has moved since.\n */\n const answeredOr = <A, E, RA>(\n context: {\n readonly id: string\n readonly operation: Option.Option<string>\n readonly request: string\n readonly principal: Option.Option<User>\n },\n answered: (answer: Readonly<Record<string, unknown>>) => A,\n write: () => Effect.Effect<A, E, RA>,\n ) => {\n const recorded = writer.recorded\n if (recorded === undefined || Option.isNone(context.operation)) return write()\n return Effect.flatMap(\n recorded({\n operation: context.operation.value,\n request: context.request,\n id: context.id,\n principal: context.principal,\n }),\n Option.match({ onSome: answer => Effect.succeed(answered(answer)), onNone: write }),\n )\n }\n // What an answer shows: the row as the writer may see it, members ruled.\n const memberRead = GuardServer.filter(entity, policy)\n // An update, step by step: admitted for what it declares, its rules chosen, the\n // row they read read, the rules decided over it as it is and as it would be, then\n // written pinned to that row. Each step refuses before the next can speak.\n type UpdateContext = Parameters<EntityWriter<Option.Option<User>, RW>['update']>[0]\n interface UpdateRules {\n readonly row: RowRule\n readonly members: ReadonlyArray<MemberRead>\n readonly relating: Effect.Success<ReturnType<typeof linkRules>>\n }\n /** Refused before any rule, for what the write declares rather than what the row holds. */\n const admitUpdate = (context: UpdateContext): Effect.Effect<void, RemoteServerError> =>\n Effect.andThen(discloses(context.expect, context.when, context.assignments), () =>\n // The rules judge a sum over the row read: unpinned, that is not the row written.\n Object.keys(context.increments).length + Object.keys(context.assignments).length > 0 &&\n Option.isNone(context.expect) &&\n revision === undefined\n ? Effect.fail(\n new RemoteServerError({\n 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`,\n }),\n )\n : Effect.void,\n )\n /** The rules an update must meet: the row's, each member it sets, each relation it points. */\n const updateRules = (context: UpdateContext) =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Update')\n // A field moved or computed is set as surely as a written one: its Update rule holds.\n const members = yield* policy.writeMembers(\n entity,\n context.principal,\n [\n ...Object.keys(context.values),\n ...Object.keys(context.increments),\n ...Object.keys(context.assignments),\n ],\n 'Update',\n )\n const relating = yield* linkRules(context.principal, context.links)\n return { row, members, relating } satisfies UpdateRules\n })\n /**\n * The row as its writer may see it, with every field the rules and the\n * version read, and those the write's amounts and assignments read to\n * work out the row it leaves.\n */\n const readBefore = (context: UpdateContext, rules: UpdateRules) =>\n read({\n id: context.id,\n fields: fieldsOf(\n [rules.row, ...rules.members, ...ruleOf(rules.relating)],\n [\n ...Object.keys(context.links),\n ...versionFields(context.expect),\n ...Write.boundReads(context),\n // What its rule reads of the row by a path is compared with the row it leaves.\n ...Condition.reachedFrom(rules.row.condition, { entity: entity.name, id: context.id }),\n ],\n ),\n principal: context.principal,\n })\n /**\n * The memory table the row a write leaves is worked out by: the writer's,\n * so the rules judge the value its statement writes, else the policy's.\n */\n const computing = writer.operators ?? policy.operators\n /**\n * The row `context` would leave `before` as. An operator's refusal (text\n * holding NUL, an implementation that throws) is a server error, as the\n * writer answers what it cannot compile: reported here (`ComputeRefused`),\n * and never sent, since an implementation's own message may say anything.\n * So is a field it cannot\n * work out at all: judging its old value would let a rule over it pass.\n */\n const leaves = (before: Readonly<Record<string, unknown>>, context: UpdateContext) =>\n Effect.suspend(() => {\n const unworkable = Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write could not be worked out to judge its rules`,\n }),\n )\n try {\n const applied = Write.apply(before, context, { operators: computing })\n return applied.unknown.length === 0 ? Effect.succeed(applied.row) : unworkable\n } catch (error) {\n if (!(error instanceof QueryEvaluateError)) throw error\n return Diagnostics.report(computeRefused(entity.name, error)).pipe(\n Effect.andThen(unworkable),\n )\n }\n })\n /** The rules, over the row as it is and as the write would leave it. */\n const decideUpdate = (\n context: UpdateContext,\n rules: UpdateRules,\n before: Readonly<Record<string, unknown>>,\n ) =>\n Effect.gen(function* () {\n const { principal, links } = context\n const linked = Object.keys(links)\n const stored =\n writer.linked === undefined || linked.length === 0\n ? Option.none()\n : yield* writer.linked({ id: context.id, relations: linked })\n const was = Option.some(\n Option.match(stored, {\n onNone: () => ({ links: before, exact: false }),\n onSome: links => ({ links, exact: true }),\n }),\n )\n const relations = linking(rules.relating, was)\n // The rules over the row as stored refuse first: a writer they refuse learns\n // nothing of what its input would compute. What the row alone cannot decide\n // of its own rule is the statement's to judge, over the row it writes.\n const requires = yield* rowRule(rules.row, before, principal)\n yield* require([...rules.members, ...relations], before, principal)\n // What the writer will store, over the row read, which the pin keeps as the row\n // written: `Write.apply`'s, as the writer works it out.\n const after = {\n ...(yield* leaves(before, context)),\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n // Over the row it leaves, a rule reading another row is the statement's too,\n // which judges the stored row: so a write may not change what such a rule\n // reads of its own row, the one difference between the two.\n const leaving = yield* rowRule(rules.row, after, principal)\n if (Option.isSome(leaving)) {\n const read = Condition.reachedFrom(\n Condition.residual(\n rules.row.condition,\n after,\n policy.inputOf(principal),\n policy.operators,\n ),\n { entity: entity.name, id: context.id },\n )\n if (read.some(key => !sameStored(before[key], after[key]))) {\n return yield* Effect.fail(refused(rules.row.deny))\n }\n }\n // Each member's rule and each link's also over the row it leaves with that one\n // change undone: may it change, given all else the write does. Over the row before\n // alone, one write could set together what each change alone may not; over the\n // whole row after, \"only while a draft\" would refuse leaving the draft. An unlink is\n // of the row before, which the row after no longer points from.\n const undone = [\n ...rules.members.map(rule => ({ rule, key: rule.member })),\n ...rules.relating.flatMap(rule =>\n linking([{ ...rule, unlink: Option.none() }], was).map(link => ({\n rule: link,\n key: rule.relation,\n })),\n ),\n ]\n yield* Effect.forEach(\n undone,\n ({ rule, key }) => require([rule], { ...after, [key]: before[key] }, principal),\n { discard: true },\n )\n return requires\n })\n const guarded: EntityWriter<Option.Option<User>, R | RW> = {\n entity: writer.entity,\n // The precondition is the writer's to check, in the statement that writes.\n ...(writer.preconditions === true ? { preconditions: true } : {}),\n ...(writer.increments === true ? { increments: true } : {}),\n ...(writer.assignments === true ? { assignments: true } : {}),\n // With a revision every update lands over the row its rules read. Without one an\n // unpinned move is refused, so what the writer would say commutes is not passed on.\n ...(revision === undefined ? {} : { pins: true }),\n ...(writer.ledger === true ? { ledger: true } : {}),\n // Invariants are the writer's to judge, over the row its statement writes.\n ...(writer.invariants === true ? { invariants: true } : {}),\n // What the store refuses, the store knows: the guard drops none of its reasons. It\n // adds one: its rules judge the row the write leaves, worked out by the policy's\n // table, so an assignment that table cannot run would be judged as its old value.\n refuses: write => [\n ...(writer.refuses?.(write) ?? []),\n ...write.assignments.flatMap(({ field, expr }) =>\n Expr.unsupported([expr], { operations: supported, operators: computing }).map(\n missing =>\n `its assignment to \"${field.key}\" calls ${missing}, which the guard cannot work out`,\n ),\n ),\n // Refused per request too (`admitUpdate`), for a caller that registers none.\n ...((write.increments.length > 0 || write.assignments.length > 0) &&\n write.expect === undefined &&\n revision === undefined\n ? [\n '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',\n ]\n : []),\n ],\n ...(writer.recorded === undefined ? {} : { recorded: writer.recorded }),\n read: ({ id, fields, principal }) =>\n seenRow(\n { filter: memberRead },\n seen => read({ id, fields: seen, principal }),\n principal,\n fields,\n id,\n ),\n update: context =>\n Effect.mapError(\n Effect.andThen(admitUpdate(context), () =>\n answeredOr(context, Option.some, () =>\n pinned(context.id, context.expect, Option.isNone, () =>\n Effect.gen(function* () {\n const rules = yield* updateRules(context)\n const current = yield* readBefore(context, rules)\n if (Option.isNone(current)) return yield* Effect.fail(refused(rules.row.deny))\n if (moved(context.expect, current.value)) return Option.none()\n const requires = yield* decideUpdate(context, rules, current.value)\n return yield* writer.update({\n ...context,\n expect: pin(context.expect, current.value),\n ...Option.match(requires, {\n onNone: () => ({}),\n onSome: held => ({ requires: held }),\n }),\n })\n }),\n ),\n ),\n ),\n told,\n ),\n insert: context =>\n answeredOr(context, identity, () =>\n Effect.gen(function* () {\n const { principal, values, links } = context\n const row = yield* policy.writable(entity, principal, 'Create')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n Object.keys(values),\n 'Create',\n )\n const relations = linking(yield* linkRules(principal, links), Option.none())\n const proposed = {\n ...values,\n id: context.id,\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n const rules = [row, ...members, ...relations]\n const ruled = rules.flatMap(({ condition }) => Condition.members(condition))\n const unset = new Set(ruled.filter(field => !Object.hasOwn(proposed, field)))\n yield* require(rules.map(rule => ({\n ...rule,\n condition: Condition.unsetting(rule.condition, unset),\n })), proposed, principal)\n return yield* Effect.mapError(writer.insert(context), told)\n }),\n ),\n delete: context =>\n Effect.andThen(discloses(context.expect, context.when), () =>\n pinned(\n context.id,\n context.expect,\n outcome => outcome === 'moved',\n () =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Delete')\n const current = yield* read({\n id: context.id,\n fields: fieldsOf([row], versionFields(context.expect)),\n principal: context.principal,\n })\n // Hidden or gone, the writer sees no row: there is nothing of theirs to delete.\n if (Option.isNone(current)) return 'absent' as const\n if (moved(context.expect, current.value)) return 'moved' as const\n const requires = yield* rowRule(row, current.value, context.principal)\n return yield* writer.delete({\n ...context,\n expect: pin(context.expect, current.value),\n ...Option.match(requires, {\n onNone: () => ({}),\n onSome: held => ({ requires: held }),\n }),\n })\n }),\n ),\n ),\n }\n pins.set(guarded, Option.fromUndefinedOr(revision))\n return writeRules.add(guarded, policy, [entity])\n },\n\n /**\n * A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for\n * `interaction` checked before it runs. The row the input names (`id`) is\n * read through `source`, which must apply the Entity's Read rules, and the\n * rule must hold over it; a row its writer may not see is refused. With no\n * `id` (a create), the rule must hold of who is asking alone, a field it\n * reads matching no guard. `run` is given the row as read: its fields the\n * rule reads, its `id`, and `fields`. A refusal is `Forbidden`; `run` never\n * runs. What `run` writes is its own: check members it sets there. Each\n * row of `entity` its answer carries is read back through `source`, so the\n * answer shows its writer only what they may see, a row it hid from them\n * as deleted.\n *\n * ```ts\n * GuardServer.mutation(ArchiveTodo, {\n * entity: Todo, policy: Policy, interaction: Archive.key,\n * id: input => input.id, source: source(Db.Todo),\n * }, ({ input, row }) => …)\n * ```\n */\n mutation: <User, R, RS, RM, Name extends string, Input, Output, Refused>(\n mutation: MutationDescriptor<Name, Input, Output, Refused>,\n guard: {\n readonly entity: AnyEntity\n readonly policy: Policy<User, R>\n readonly interaction: 'Create' | 'Update' | 'Delete' | InteractionKey\n /**\n * The row the input acts on; none for a create. An input whose id may be\n * absent (`Option`, as one editor's for create and edit) creates when it\n * is, checked against `Create`.\n */\n readonly id?: ((input: Input) => string | Option.Option<string>) | undefined\n /** Reads the row as its writer may see it: the Entity's guarded Source. */\n readonly source: EntitySource<Option.Option<User>, RS>\n /** More of the row for `run`, beside what the rule reads. */\n readonly fields?: ReadonlyArray<string> | undefined\n },\n run: (context: {\n readonly input: Input\n readonly principal: Option.Option<User>\n readonly requestId: string\n readonly row: Option.Option<Readonly<Record<string, unknown>>>\n }) => Effect.Effect<\n MutationOutcome<Output>,\n RemoteServerError | MutationRefused | RemoteForbidden,\n RM\n >,\n ): MutationSource<Option.Option<User>, R | RS | RM> => {\n const { entity, policy, interaction, id, source } = guard\n if (!rowRules.has(source.visible, policy, entity)) {\n throw new Error(\n `[foldkit-guard] GuardServer.mutation: ${mutation.name}'s Source does not apply ${entity.name}'s Read rules`,\n )\n }\n /**\n * The answer as its writer may now see it: each row of `entity` it carries\n * read back through `source`, and one the handler hid from them deleted.\n */\n const shown = (outcome: MutationOutcome<Output>, principal: Option.Option<User>) =>\n Effect.map(\n Effect.forEach(outcome.entities ?? [], patch =>\n patch.entity !== entity.name\n ? Effect.succeed(Option.some(patch))\n : Effect.map(\n seenRow(\n source,\n fields =>\n Effect.map(rowOf(source, principal, fields, patch.id), Option.fromUndefinedOr),\n principal,\n Object.keys(patch.values),\n patch.id,\n ),\n Option.map(seen => ({ ...patch, values: seen })),\n ),\n ),\n read => ({\n ...outcome,\n entities: read.flatMap(Option.toArray),\n deleted: [\n ...(outcome.deleted ?? []),\n ...(outcome.entities ?? [])\n .filter((_, index) => Option.isNone(read[index]!))\n .map(({ entity, id }) => ({ entity, id })),\n ],\n }),\n )\n return RemoteServer.mutation<Option.Option<User>, R | RS | RM, Name, Input, Output, Refused>(\n mutation,\n context =>\n Effect.gen(function* () {\n const { principal } = context\n // `context.input` was decoded against the mutation's Input before this runs.\n const target = Option.flatMap(Option.fromUndefinedOr(id), of => {\n const named = of(context.input)\n return typeof named === 'string' ? Option.some(named) : named\n })\n const rule = yield* policy.writable(\n entity,\n principal,\n id !== undefined && Option.isNone(target) ? 'Create' : interaction,\n )\n const ruled = Condition.members(rule.condition)\n const input = policy.inputOf(principal)\n if (Option.isNone(target)) {\n const unset = Condition.unsetting(rule.condition, new Set(ruled))\n if (!Condition.holds(unset, {}, input, () => false, policy.operators)) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row: Option.none() }), principal)\n }\n const fields = [...new Set(['id', ...ruled, ...(guard.fields ?? [])])]\n const row = Option.fromUndefinedOr(yield* rowOf(source, principal, fields, target.value))\n if (\n Option.isNone(row) ||\n !Condition.holds(rule.condition, row.value, input, () => false, policy.operators)\n ) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row }), principal)\n }),\n )\n },\n\n /**\n * Checks, at startup, that `server` applies the guards of `entities`, the\n * Entities as `Guards.attach` returned them: each one's Source and each\n * query listing it apply its row's Read rules (`GuardDrizzle.visible`, or\n * `GuardServer.memory`), its Source applies its members' and relations'\n * (`GuardServer.filter`), and each declared write of it lands through\n * `GuardServer.writer`, all built from `policy`; and that no query's body\n * filters or orders by a member with a Read rule, its own or one of a row it\n * reaches through a path or an exists, which would answer for the value it\n * hides. A hand-written Source over a guarded Entity would serve\n * every row, and a bare writer would take every write; this throws instead,\n * naming each. A handler (`RemoteServer.mutation`) writes what its code\n * writes, which no check at startup can read. A write a change can come\n * between, through a writer given no revision, is not refused but reported:\n * `UnpinnedWrites`, a warning, to `diagnostics`.\n *\n * ```ts\n * GuardServer.validate(Policy, { entities: [Todo, Project], domain: Data, server: Server })\n * ```\n */\n validate: <User, R>(\n policy: Policy<User, R>,\n config: {\n readonly entities: ReadonlyArray<AnyEntity>\n /** The Remote domain the server answers, for which Entity each query lists. */\n readonly domain: {\n readonly registry: {\n readonly queries: ReadonlyMap<\n string,\n { readonly Result: unknown; readonly body?: AnyQuery | undefined }\n >\n }\n }\n readonly server: ServerDefinition<any, any>\n /** Where the `UnpinnedWrites` warning goes; `Diagnostics.Reporter`'s default, the log, when not given. */\n readonly diagnostics?: ReportDiagnostic | undefined\n },\n ): void => {\n const byName = new Map(config.entities.map(entity => [entity.name, entity]))\n /** Whether a reached member has a Read rule; one of an Entity not validated has none checked. */\n const hidesFromReach = ({ entity, key }: ReachedMember) =>\n Option.exists(\n Option.flatMap(Option.fromUndefinedOr(byName.get(entity)), attached),\n attachment => readRuled(attachment, key),\n )\n /** Whether who may read the rows of `entity` depends on who is asking. */\n const rowsRuled = (entity: AnyEntity | undefined) =>\n Option.exists(Option.flatMap(Option.fromUndefinedOr(entity), attached), attachment =>\n readRowsRuled(attachment),\n )\n // A query the domain does not declare lists an Entity no one can name.\n const undeclared = [...config.server.queries.keys()]\n .filter(query => !config.domain.registry.queries.has(query))\n .map(query => `query ${query} is served, but the domain does not declare it`)\n const entityProblems = config.entities.flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => {\n const name = entity.name\n if (attachment.set !== policy.set) {\n return [`${name} carries the guards of ${attachment.set}, not ${policy.set}`]\n }\n // Every guarded Entity's, whether or not it has rules there yet: a rule\n // attached later is then applied, not served past.\n const source = Option.fromUndefinedOr(config.server.entities.get(name))\n const sourceProblems = Option.match(source, {\n onNone: () => [],\n onSome: ({ visible, filter }) => [\n ...(rowRules.has(visible, policy, entity)\n ? []\n : [`${name}'s Source does not apply its Read rules`]),\n ...(memberRules.has(filter, policy, entity)\n ? []\n : [`${name}'s Source does not apply its members' Read rules`]),\n ],\n })\n const queryProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, query]) => {\n const listed = config.server.queries.get(queryName)\n return listed !== undefined &&\n lists(query.Result, name) &&\n !rowRules.has(listed.visible, policy, entity)\n ? [`query ${queryName} lists ${name} without its Read rules`]\n : []\n },\n )\n // A row the reader may see with a member it may not still answers a\n // filter or an order on that member: `cost < $max`, halved twenty\n // times, reads the cost the row came back without.\n const bodyProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, { body }]) => {\n if (body === undefined || body.entity.name !== name) return []\n const { predicate, order, reaches } = Query.dependencies(body)\n const reached = [\n ...new Set(\n reachedMembers(reaches)\n .filter(hidesFromReach)\n .map(\n ({ entity, key }) =>\n `query ${queryName} reaches ${entity}'s ${key}, which has a Read rule`,\n ),\n ),\n ]\n return [\n ...hiddenOf(attachment, predicate).map(\n member =>\n `query ${queryName} filters ${name} by ${member}, which has a Read rule`,\n ),\n ...hiddenOf(attachment, order).map(\n member => `query ${queryName} orders ${name} by ${member}, which has a Read rule`,\n ),\n ...reached,\n ]\n },\n )\n const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) => {\n if (source.writes === undefined || source.writes.entity !== name) return []\n if (!writeRules.has(source.writes.writer, policy, entity)) {\n return [`write ${mutation} writes ${name} without its write rules`]\n }\n const { write, writer } = source.writes\n const interaction = Match.valueTags(write, {\n Insert: () => 'Create',\n Update: () => 'Update',\n Delete: () => 'Delete',\n })\n // Left without a rule under 'allow', a served write is anyone's: that is\n // written down as `Guards.anyone`, never left to a forgotten rule.\n const open =\n attachment.unguarded === 'allow' &&\n Option.isNone(surfaceOf(attachment, { _tag: 'Row', interaction }))\n ? [\n `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`,\n ]\n : []\n // Unmet or written, Conflict or not, answers for a member its writer may not read.\n const when = Option.match(write.when, {\n onNone: () => [],\n onSome: body => hiddenOf(attachment, Query.dependencies(body).predicate),\n })\n const computed = write.assignments.flatMap(assignment =>\n hiddenOf(attachment, dependenciesOf(assignment.expr).fields).map(\n member =>\n `write ${mutation} computes ${name}'s ${assignment.field.key} from its ${member}, which has a Read rule`,\n ),\n )\n const expected = write.expect?.field.key\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n return [\n ...open,\n ...when.map(\n member =>\n `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`,\n ),\n ...computed,\n ...(expected !== undefined && readRuled(attachment, expected)\n ? [`write ${mutation} expects ${name}'s ${expected}, which has a Read rule`]\n : []),\n ...(expected !== undefined &&\n pin !== undefined &&\n Option.exists(pin, field => field !== expected)\n ? [\n `write ${mutation} expects ${name}'s ${expected}, but its writer pins ${Option.getOrThrow(pin)}`,\n ]\n : []),\n ]\n })\n // A shared field goes to every live subscriber as written: no rule may tell them apart.\n const shared: ReadonlyArray<string> = Option.match(source, {\n onNone: () => [],\n onSome: source => [...(source.shared ?? [])],\n })\n const sharedProblems = [\n ...(shared.length > 0 && readRowsRuled(attachment)\n ? [`${name}'s Source shares ${shared.join(', ')}, but its rows have a Read rule`]\n : []),\n // Each reader's own answer, whoever may read the row.\n ...(shared.includes('may') && asksMay(entity, ['may'])\n ? [`${name}'s Source shares may, which is answered for each reader`]\n : []),\n ...shared.flatMap(member => {\n const own = readRuled(attachment, member)\n ? [`${name}'s Source shares ${member}, which has a Read rule`]\n : []\n if (!Object.hasOwn(entity.relations, member)) return own\n const target = entity.relations[member]!.target().name\n if (!byName.has(target))\n return [\n ...own,\n `${name}'s Source shares ${member}, whose ${target} is not validated`,\n ]\n return rowsRuled(byName.get(target))\n ? [...own, `${name}'s Source shares ${member}, whose rows have a Read rule`]\n : own\n }),\n ]\n // A rule calling an operator the policy's table does not run would fail when\n // asked, so the server does not start with one (expr-operations-DESIGN §5.6).\n const operatorProblems = attachedRules(attachment).flatMap(rule =>\n rule._tag === 'RowGuard'\n ? Query.unsupported(rule.query, supported, policy.operators).map(\n missing =>\n `${name}'s ${rule.name} calls ${missing}, which the policy does not run`,\n )\n : [],\n )\n // A live Source sends what it reads: only one reading through the Source\n // checked above is known to send what a read would.\n const live = Option.fromUndefinedOr(config.server.live.get(name))\n const liveProblems = Option.exists(\n live,\n ({ reads }) => !Option.exists(source, checked => checked === reads),\n )\n ? [\n `${name}'s live Source does not read through its guarded Source; poll through that Source (pollLive) or serve changes through a live hub`,\n ]\n : []\n return [\n ...sourceProblems,\n ...queryProblems,\n ...bodyProblems,\n ...writeProblems,\n ...sharedProblems,\n ...operatorProblems,\n ...liveProblems,\n ]\n },\n }),\n )\n const problems = [...undeclared, ...entityProblems]\n if (problems.length > 0) {\n throw new Error(`[foldkit-guard] GuardServer.validate: ${problems.join('; ')}`)\n }\n // Not refused yet: a writer given no revision is how every writer was made before it.\n // Named only where a change between the check and the write can happen: an update\n // always, a delete where the server updates that Entity, an insert, with no row, never.\n const updated = new Set(\n [...config.server.mutations.values()]\n .flatMap(source => (source.writes === undefined ? [] : [source.writes]))\n .filter(writes => writes.write._tag === 'Update')\n .map(writes => writes.entity),\n )\n const unpinned = [...config.server.mutations].flatMap(([mutation, source]) => {\n const writes = source.writes\n if (writes === undefined) return []\n const writer = writes.writer\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n if (pin === undefined || Option.isSome(pin)) return []\n const races = Match.valueTags(writes.write, {\n Update: () => true,\n Delete: () => updated.has(writes.entity),\n Insert: () => false,\n })\n return races ? [mutation] : []\n })\n if (unpinned.length > 0) {\n // A startup check runs before any Effect of the server's, so the reporter is an option.\n const report = Diagnostics.report(unpinnedWrites(unpinned))\n const { diagnostics } = config\n Effect.runFork(\n diagnostics === undefined\n ? report\n : Effect.provideService(report, Diagnostics.Reporter, diagnostics),\n )\n }\n },\n}\n\n/** Whether a read asks for `may`, of an Entity that has it (`Guards.may`). */\nconst asksMay = (entity: AnyEntity, fields: ReadonlyArray<string>) =>\n fields.includes('may') && Object.hasOwn(entity.derived, 'may')\n\n/** How one principal's `may` is answered: the fields its rules read, and the answer over a row. */\ninterface MayPlan {\n readonly fields: ReadonlyArray<string>\n readonly answer: (values: Readonly<Record<string, unknown>>) => MayAnswer\n}\n\n/**\n * `may` for `principal`: each row interaction's rule, each member's own\n * `Update`, each relation's `Link` and `Unlink`, decided once and held over\n * each row as a write's check would hold them over it as it is.\n */\nconst mayOf = <User, R>(\n entity: AnyEntity,\n policy: Policy<User, R>,\n principal: Option.Option<User>,\n): Effect.Effect<MayPlan, never, R> =>\n Effect.map(\n mayRules(entity, {\n // A named one was attached as an `InteractionKey`; its key is the name.\n row: interaction => policy.writable(entity, principal, interaction as InteractionKey),\n members: members => policy.writeMembers(entity, principal, members, 'Update'),\n relation: (relation, interaction) =>\n policy.linkable(entity, principal, relation, interaction),\n }),\n (rules): MayPlan => {\n const input = policy.inputOf(principal)\n return {\n // `id` too, so a row is read when its rules read none of it (an admin's).\n fields: ['id', ...new Set(mayConditions(rules).flatMap(Condition.members))],\n // A rule reading another row is the write's statement's to judge: not answered here.\n answer: values =>\n answerOf(rules, condition =>\n Condition.decided(Condition.residual(condition, values, input, policy.operators)),\n ),\n }\n },\n )\n\n/** A refused write as the client receives it: the sentence an `explain` gave, or none. */\n/** The words a refusal gives: an `explain`'s, or none. */\nconst explained = (deny: Deny): Option.Option<string> =>\n Match.valueTags(deny, {\n Explain: ({ reason }) => Option.some(reason),\n Forbidden: () => Option.none(),\n NotFound: () => Option.none(),\n Omit: () => Option.none(),\n Redact: () => Option.none(),\n })\n\n/**\n * What is left of a condition, as a writer's statement judges it: each row\n * guard a body over the row, its input the principal's (`G.inputOf`), and its\n * context the one it was decided for. An inherited Read, which a writer\n * refuses, requires what no row holds.\n */\nconst requirementOf = (\n condition: Condition,\n input: Readonly<Record<string, unknown>>,\n): RowRequirement =>\n Match.valueTags(condition, {\n Always: () => RowRequirement.All({ of: [] }),\n Never: () => RowRequirement.Any({ of: [] }),\n Row: ({ guard, context }) => RowRequirement.Body({ query: guard.query, input, context }),\n Inherit: () => RowRequirement.Any({ of: [] }),\n And: ({ conditions }) =>\n RowRequirement.All({ of: conditions.map(each => requirementOf(each, input)) }),\n Or: ({ conditions }) =>\n RowRequirement.Any({ of: conditions.map(each => requirementOf(each, input)) }),\n })\n\nconst refused = (deny: Deny) =>\n Match.valueTags(deny, {\n Explain: ({ reason }) => RemoteServer.forbid(reason),\n Forbidden: () => RemoteServer.forbid(),\n NotFound: () => RemoteServer.forbid(),\n Omit: () => RemoteServer.forbid(),\n Redact: () => RemoteServer.forbid(),\n })\n\n/** One row, by id, as `principal` may read it through `source`. */\nconst rowOf = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n) =>\n Effect.map(\n source.read({ ids: [id], fields: [...fields], principal }),\n records => records.find(record => record.id === id)?.values,\n )\n\n/**\n * Row `id` of `fields` as `principal` may see it, through `see`'s `authorize`\n * and `filter` as a Source applies them, and no more than was asked: what an\n * answer shows its writer. None when the row is not there to them.\n */\nconst seenRow = <P, R, RS>(\n see: Pick<EntitySource<P, RS>, 'authorize' | 'filter'>,\n read: (\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n): Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R | RS> =>\n Effect.gen(function* () {\n const allowed = see.authorize === undefined ? fields : see.authorize(principal, [...fields])\n const plan: ReadPlan =\n see.filter === undefined\n ? { fields: allowed, apply: noMembers }\n : yield* see.filter(principal, allowed)\n // The id too: a row asked for nothing else is still there or not.\n const row = yield* read([...new Set(['id', ...plan.fields])])\n return Option.map(row, values => {\n const shown = plan.apply({ id, values }).values\n return Object.fromEntries(\n allowed.filter(field => Object.hasOwn(shown, field)).map(field => [field, shown[field]]),\n )\n })\n })\n\n/** A link's value as a row holds it: the ref's key, or `null` for none. */\nconst linkKey = (link: Option.Option<{ readonly entity: string; readonly id: string }>) =>\n Option.match(link, { onNone: () => null, onSome: ref => `${ref.entity}:${ref.id}` })\n\n/** Whether a query's result is a connection over `entity`. */\nconst lists = (result: unknown, entity: string): boolean =>\n typeof result === 'object' && result !== null && 'entity' in result && result.entity === entity\n"],"mappings":";;;;;;;;;;AAOA,MAAM,SAAS;AA0Bf,MAAa,kBAAkB,QAAgB,WAAkC;CAC/E,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,OAAO,qEAAqE,MAAM,QAAQ;CACtG;CACA;AACF;AAEA,MAAa,kBAAkB,eAAsD;CACnF,MAAM;CACN;CACA,OAAO;CACP,SAAS,yBAAyB,UAAU,KAAK,IAAI,EAAE,GAAG,UAAU,WAAW,IAAI,WAAW,QAAQ;CACtG;AACF;;;;;;;;;ACaA,MAAM,aAAa,WAAyB;;AAG5C,M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,KAAK,MAAM;GAAE;GAAI;EAAO,CAAC,CAAC,CAAC;EACzC,OAAO,OAAO,YACZ,QAAQ,QAAO,UAAS,OAAO,OAAO,OAAO,KAAK,CAAC,CAAC,CAAC,KAAI,UAAS,CAAC,OAAO,MAAM,MAAM,CAAC,CACzF;CACF,CAAC;AACH,CAAC;;AAGH,MAAM,WAAW,SACf,OAAO,MAAM,MAAM;CAAE,cAAc;CAAM,SAAQ,QAAO,GAAG,IAAI,OAAO,GAAG,IAAI;AAAK,CAAC;;AAGrF,MAAM,SAAS,QAAiB,WAC9B,OAAO,WAAW,YAAY,WAAW,QAAQ,YAAY,UAAU,OAAO,WAAW"}
1
+ {"version":3,"file":"server.mjs","names":[],"sources":["../src/diagnostics.ts","../src/server.ts"],"sourcesContent":["/**\n * What a guarded server meets and answers past: a computed value an operator\n * refused, answered with a fixed message, and writes `GuardServer.validate`\n * finds unpinned. Each is reported through `Diagnostics.report`.\n */\nimport type { Diagnostic } from 'foldkit-remote'\n\nconst source = 'foldkit-guard'\n\n/**\n * An operator refused to work out a value a guarded write computes (text\n * holding NUL, an implementation that throws). The write was refused with a\n * fixed message, since the operator's own may say anything.\n */\nexport interface ComputeRefused extends Diagnostic {\n readonly _tag: 'ComputeRefused'\n readonly entity: string\n /** The operator's own refusal. */\n readonly error: Error\n}\n\n/**\n * Writes through a `GuardServer.writer` given no revision, where a change can\n * come between the check and the write, which is then not seen.\n */\nexport interface UnpinnedWrites extends Diagnostic {\n readonly _tag: 'UnpinnedWrites'\n readonly mutations: ReadonlyArray<string>\n}\n\n/** Every diagnostic `foldkit-guard` reports. */\nexport type GuardDiagnostic = ComputeRefused | UnpinnedWrites\n\nexport const computeRefused = (entity: string, error: Error): ComputeRefused => ({\n _tag: 'ComputeRefused',\n source,\n level: 'error',\n message: `${entity}'s write was refused: a value it computes could not be worked out (${error.message})`,\n entity,\n error,\n})\n\nexport const unpinnedWrites = (mutations: ReadonlyArray<string>): UnpinnedWrites => ({\n _tag: 'UnpinnedWrites',\n source,\n level: 'warning',\n 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 }`,\n mutations,\n})\n","/**\n * A guard set's read rules as `foldkit-remote-server`'s seams: an\n * `EntitySource.filter` from each member's Read rule, and `RemoteServer.memory`'s\n * `readable` and `filter` from the row's, and a check at startup that a server\n * applies them. A subpath, so the shared declaration the browser imports never\n * brings the server along.\n */\nimport { Effect, Match, Option, Schema, SchemaAST, identity } from 'effect'\nimport {\n Entity,\n Expr,\n Query,\n QueryEvaluateError,\n Write,\n dependenciesOf,\n supported,\n type AnyEntity,\n type AnyQuery,\n} from 'foldkit-entity'\nimport {\n Diagnostics,\n RemoteForbidden,\n type MutationDescriptor,\n type RemoteUnauthenticated,\n type ReportDiagnostic,\n} from 'foldkit-remote'\nimport {\n RemoteInvalid,\n RemoteServer,\n DeleteOutcome,\n RemoteServerError,\n RowRequirement,\n type EntityRecord,\n type EntitySource,\n type EntityWriter,\n type MutationOutcome,\n type MutationRefused,\n type MutationSource,\n type MemoryReadable,\n type ReadPlan,\n type ServerDefinition,\n type WriteRequirement,\n type WriteWhen,\n} from 'foldkit-remote-server'\nimport {\n attached,\n attachedRules,\n readRowsRuled,\n readRuled,\n surfaceOf,\n type Attachment,\n type Deny,\n type InteractionKey,\n} from './attach.js'\nimport { Condition, type MemberRead, type RowRule } from './condition.js'\nimport type { Policy } from './index.js'\nimport { answerOf, mayConditions, mayRules, type MayAnswer } from './may.js'\nimport { ME, type MeEntity } from './me.js'\nimport { memberRules, rowRules, writeRules } from './placed.js'\nimport { computeRefused, unpinnedWrites } from './diagnostics.js'\n\nexport type { ComputeRefused, GuardDiagnostic, UnpinnedWrites } from './diagnostics.js'\n\nconst noMembers = (record: EntityRecord) => record\n\n/** Two stored values, which are JSON: equal when they encode the same. */\nconst sameStored = (left: unknown, right: unknown): boolean =>\n JSON.stringify(left) === JSON.stringify(right)\n\n/** The members of `fields` that have a Read rule, once each. */\nconst hiddenOf = (\n attachment: Attachment,\n fields: ReadonlyArray<{ readonly key: string }>,\n): ReadonlyArray<string> => [\n ...new Set(fields.map(field => field.key).filter(key => readRuled(attachment, key))),\n]\n\n/** A member of a row a body reaches: the Entity it belongs to, by name, and its key. */\ninterface ReachedMember {\n readonly entity: string\n readonly key: string\n}\n\n/**\n * Each member a body reads on a row it reaches rather than judges: every\n * relation a path, a path from the viewer or an exists follows, the field a\n * path ends at, and an exists' pointing relation and filter. SQL reads such a\n * row under its `visible` rule alone, never its members'.\n */\nconst reachedMembers = (\n reaches: ReturnType<typeof dependenciesOf>['reaches'],\n): ReadonlyArray<ReachedMember> =>\n reaches.flatMap(reached => {\n const via = reached.via.map(relation => ({ entity: relation.owner.name, key: relation.key }))\n return Match.valueTags(reached, {\n Path: ({ field }) => [...via, { entity: field.owner.name, key: field.key }],\n ViewerPath: ({ field }) => [...via, { entity: field.owner.name, key: field.key }],\n Exists: ({ relation, where }) => {\n const filter = Option.match(where, {\n onNone: () => [],\n onSome: body => {\n const read = dependenciesOf(body)\n return [\n ...read.fields.map(field => ({ entity: field.entity, key: field.key })),\n ...reachedMembers(read.reaches),\n ]\n },\n })\n return [...via, { entity: relation.owner.name, key: relation.key }, ...filter]\n },\n })\n })\n\n/** Each guarded writer's `revision`, or none: one a change can fall between check and write of. */\nconst pins = new WeakMap<object, Option.Option<string>>()\n\n/** A ref key's two halves, `Entity:id`; `none` for anything else. */\nconst refOf = (value: unknown): Option.Option<{ readonly entity: string; readonly id: string }> => {\n if (typeof value !== 'string') return Option.none()\n const split = value.indexOf(':')\n return split <= 0\n ? Option.none()\n : Option.some({ entity: value.slice(0, split), id: value.slice(split + 1) })\n}\n\nexport const GuardServer = {\n /**\n * `Guards.me`'s Source: the one row, `me`, as the asker is, with `may`\n * answered by `policy`. `signedIn` is whether the server answered as\n * someone; `key` is their `key`. Any other id is no row.\n *\n * ```ts\n * RemoteServer.make({ entities: [GuardServer.me(Me, Policy), …] })\n * ```\n */\n me: <User, R>(\n entity: MeEntity,\n policy: Policy<User, R>,\n ): EntitySource<Option.Option<User>, R> => {\n // Otherwise every read would die deciding another set's guards.\n Option.map(attached(entity), ({ set }) => {\n if (set !== policy.set) {\n throw new Error(\n `[foldkit-guard] GuardServer.me: Me carries the guards of ${set}, not ${policy.set}`,\n )\n }\n })\n return {\n ...RemoteServer.entity<Option.Option<User>, R>(entity, {\n read: ({ ids, principal }) =>\n Effect.succeed(\n ids\n .filter(id => id === ME)\n .map(id => ({\n id,\n values: {\n signedIn: Option.isSome(principal),\n // Encoded, as a Source answers: `null` for a visitor.\n key: Option.match(principal, {\n onNone: () => null,\n onSome: policy.key,\n }),\n },\n })),\n ),\n filter: GuardServer.filter(entity, policy),\n }),\n // Its Read rule as this Source applies it: only the asker's own row,\n // which `Guards.me` lets anyone read. One per call: the registry is keyed\n // by it, and another call is for another Policy.\n visible: rowRules.add(Object.freeze({ reads: 'the asker’s own row' }), policy, [entity]),\n }\n },\n\n /**\n * An `EntitySource.filter` for `entity`: each requested member with a Read\n * rule is decided per record, omitted or redacted where the rule refuses.\n * The fields a rule reads are read too, so it can be decided.\n *\n * ```ts\n * RemoteServer.entity(Todo, { read, filter: GuardServer.filter(Todo, Policy) })\n * ```\n */\n filter: <User, R>(entity: AnyEntity, policy: Policy<User, R>) =>\n memberRules.add(\n (\n principal: Option.Option<User>,\n fields: readonly string[],\n ): Effect.Effect<ReadPlan, never, R> =>\n Effect.map(\n Effect.all([\n policy.readMembers(entity, principal, fields),\n // `may` is answered here, where the row is read as its principal sees it.\n asksMay(entity, fields)\n ? Effect.map(mayOf(entity, policy, principal), Option.some)\n : Effect.succeed(Option.none<MayPlan>()),\n ]),\n ([members, may]): ReadPlan => {\n if (members.length === 0 && Option.isNone(may)) return { fields, apply: noMembers }\n const input = policy.inputOf(principal)\n const decided = members.map(member => ({\n ...member,\n // A redacted value is a decoded one; the record holds what the store holds.\n redacted:\n member.deny._tag === 'Redact'\n ? Option.some(\n Schema.encodeSync(\n (\n entity.members as Readonly<\n Record<string, { readonly schema: Schema.Top }>\n >\n )[member.member]!.schema as unknown as Schema.Codec<unknown, unknown>,\n )(member.deny.value),\n )\n : Option.none(),\n }))\n return {\n fields: [\n ...new Set([\n ...fields,\n ...members.flatMap(({ condition }) => Condition.members(condition)),\n ...Option.match(may, { onNone: () => [], onSome: ({ fields }) => fields }),\n ]),\n ],\n apply: record => {\n const values: Record<string, unknown> = { ...record.values }\n for (const { member, condition, redacted } of decided) {\n // Member rules carry no inherited Read: only a row's Read may inherit.\n if (\n Condition.holds(condition, record.values, input, () => false, policy.operators)\n )\n continue\n Option.match(redacted, {\n onNone: () => {\n delete values[member]\n },\n onSome: value => {\n values[member] = value\n },\n })\n }\n Option.map(may, ({ answer }) => {\n values.may = answer(record.values)\n })\n return { id: record.id, values }\n },\n }\n },\n ),\n policy,\n [entity],\n ),\n\n /**\n * `RemoteServer.memory`'s `readable` and `filter` for `entities`, the\n * Entities as `Guards.attach` returned them. A row's Read is decided per\n * stored row, an inherited Read by looking the related row up; an Entity\n * not listed is read by everyone.\n */\n memory: <User>(policy: Policy<User>, entities: ReadonlyArray<AnyEntity>) => ({\n readable: rowRules.add(\n (\n principal: Option.Option<User>,\n row: (entity: string, id: string) => Option.Option<Readonly<Record<string, unknown>>>,\n ): Effect.Effect<MemoryReadable> =>\n Effect.map(\n Effect.forEach(entities, entity =>\n Effect.map(\n policy.readable(entity, principal),\n condition => [entity.name, condition] as const,\n ),\n ),\n (decided): MemoryReadable => {\n const conditions = new Map(decided)\n const input = policy.inputOf(principal)\n // `seen` stops a cycle of inherited Reads, which would otherwise never end.\n const holds = (\n entity: string,\n values: Readonly<Record<string, unknown>>,\n seen: ReadonlySet<string>,\n ): boolean => {\n const condition = conditions.get(entity)\n if (condition === undefined) return true\n return Condition.holds(\n condition,\n values,\n input,\n relation =>\n Option.match(refOf(values[relation]), {\n onNone: () => false,\n onSome: ref => {\n const key = `${ref.entity}:${ref.id}`\n if (seen.has(key)) return false\n return Option.match(row(ref.entity, ref.id), {\n onNone: () => false,\n onSome: target => holds(ref.entity, target, new Set([...seen, key])),\n })\n },\n }),\n policy.operators,\n )\n }\n return (entity, values) => holds(entity, values, new Set())\n },\n ),\n policy,\n entities,\n ),\n filter: Object.fromEntries(\n entities.map(entity => [entity.name, GuardServer.filter(entity, policy)] as const),\n ),\n }),\n\n /**\n * `writer` with `entity`'s write rules checked before each write lands, for\n * `RemoteServer.write`. An update or a delete reads the row first under\n * the writer's own `read` (its Source's read rule): a row the writer may not\n * see is refused as one that is not there, and a delete of it changes\n * nothing. Then the row's rule for the command must hold over the row, each\n * member it sets must allow setting it, and each relation it points\n * elsewhere must allow the unlink and the link. An update's row rule holds\n * over the row as it would be after it too, so a write cannot move a row out\n * of its writer's reach. Each of its member and `Link` rules holds over the\n * row after with that one change undone (that member's value, or where that\n * relation pointed, as before): the change must be allowed given everything\n * else the write does, so one write cannot set together what each change\n * alone would be refused, while a rule reading its own member (\"only while\n * a draft\") still allows the change. An increment or a computed assignment\n * to a member is that member's own change. An `Unlink` rule holds over the\n * row before alone. A create's rules hold over the values it proposes, where a field the\n * create leaves unset matches no guard, not even one for an empty value. A refusal is\n * `Forbidden`, with the sentence an `explain` gave, or `Unauthenticated` for a\n * visitor; the write never runs.\n *\n * What the Entity sets from the write's context (`Entity.sets`: who asks,\n * when) reaches a create or an update already set by `RemoteServer.write`,\n * so a rule over it holds of the creator. A member rule over such a member\n * judges the server's value like any other: declare none there.\n *\n * `revision` names a field stored as a number, which the writer moves on by\n * one with each write it lands. An update or a delete then lands only on the\n * revision its rules were decided over (the writer's `expect`), so a change\n * between the check and the write is never written over; it is decided\n * again against the row as it now is, up to three times. A change that does\n * not move the revision (a handler's, `applyEdits`', raw SQL) is not seen.\n * Without `revision`, none is, and `validate` warns of an update, or a delete\n * of an Entity the server updates (an insert has no row). An input that expects a\n * revision the row read is not at is a `Conflict`, decided before any rule;\n * an input may expect only the field the writer pins.\n *\n * ```ts\n * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))\n * ```\n */\n writer: <E extends AnyEntity, User, R, RW>(\n entity: E,\n policy: Policy<User, R>,\n writer: EntityWriter<Option.Option<User>, RW>,\n options: {\n readonly revision?: keyof E['fields'] & string\n } = {},\n ): EntityWriter<Option.Option<User>, R | RW> => {\n const revision = options.revision\n if (revision !== undefined) {\n const field = Object.hasOwn(entity.fields, revision)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[revision]\n : undefined\n if (field === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${revision}\" for its revision`,\n )\n }\n // The writer moves it on by one in the statement it writes with, so it is stored as a number.\n if (!SchemaAST.isNumber(Schema.toEncoded(field.schema).ast)) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s revision \"${revision}\" is not stored as a number`,\n )\n }\n }\n if (writer.entity !== entity.name) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s rules over a writer for ${writer.entity}`,\n )\n }\n const read = writer.read\n if (read === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s writer reads no row as its writer may see it; bind it with a visible rule (GuardDrizzle.visible)`,\n )\n }\n // A rule reading another row is judged in the statement that writes: the writer must.\n const reaching = Option.match(attached(entity), {\n onNone: () => [],\n onSome: ({ row }) =>\n (['Update', 'Delete'] as const).flatMap(interaction =>\n (row[interaction]?.rules ?? []).flatMap(function names(rule): ReadonlyArray<string> {\n return Match.valueTags(rule, {\n PrincipalGuard: () => [],\n RowGuard: guard =>\n Query.dependencies(guard.query).reaches.length > 0 ? [guard.name] : [],\n All: ({ rules }) => rules.flatMap(names),\n Inherit: () => [],\n })\n }),\n ),\n })\n if (reaching.length > 0 && writer.requires !== true) {\n throw new Error(\n `[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`,\n )\n }\n /**\n * The row rule over `values` as far as one row decides it: refused where it\n * fails, and otherwise what the writer's statement must still judge.\n */\n const rowRule = (\n rule: RowRule,\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ): Effect.Effect<Option.Option<WriteRequirement>, RemoteForbidden> => {\n const left = Condition.residual(\n rule.condition,\n values,\n policy.inputOf(principal),\n policy.operators,\n )\n return Match.valueTags(left, {\n Always: () => Effect.succeed(Option.none()),\n Never: () => Effect.fail(refused(rule.deny)),\n Row: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n Inherit: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n And: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n Or: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n })\n }\n const required = (\n left: Condition,\n deny: Deny,\n principal: Option.Option<User>,\n ): WriteRequirement => ({\n holds: requirementOf(left, policy.inputOf(principal)),\n reason: explained(deny),\n })\n const holds = (\n rule: { readonly condition: Condition },\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\n Condition.holds(\n rule.condition,\n values,\n policy.inputOf(principal),\n () => false,\n policy.operators,\n )\n /** Fails with the first rule of `rules` that does not hold over `values`. */\n const require = (\n rules: ReadonlyArray<{ readonly condition: Condition; readonly deny: Deny }>,\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\n Option.match(Option.fromUndefinedOr(rules.find(rule => !holds(rule, values, principal))), {\n onNone: () => Effect.void,\n onSome: rule => Effect.fail(refused(rule.deny)),\n })\n type Links = Readonly<\n Record<string, Option.Option<{ readonly entity: string; readonly id: string }>>\n >\n /** Each relation `links` points: its rules for unlinking and for linking a row. */\n const linkRules = (principal: Option.Option<User>, links: Links) =>\n Effect.forEach(Object.entries(links), ([relation, target]) =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Unlink'),\n policy.linkable(entity, principal, relation, 'Link'),\n ]),\n ([unlink, link]) => ({ relation, now: linkKey(target), unlink, link }),\n ),\n )\n /**\n * The rules a change from what each relation was linked to, to what it now\n * points at, must meet; none `before` is a create, which unlinks nothing.\n * Where `exact` is false, `links` are the row as its writer sees it, where\n * a link to a row hidden from them reads as none: a relation seen unlinked\n * may be linked after all, so changing it unlinks too.\n */\n const linking = (\n rules: ReadonlyArray<{\n readonly relation: string\n readonly now: string | null\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n before: Option.Option<{\n readonly links: Readonly<Record<string, unknown>>\n readonly exact: boolean\n }>,\n ): ReadonlyArray<RowRule> =>\n rules.flatMap(({ relation, now, unlink, link }) =>\n Option.match(before, {\n onNone: () => (now === null ? [] : Option.toArray(link)),\n onSome: ({ links, exact }) => {\n const was = links[relation] ?? null\n if (was === now && (exact || was !== null)) return []\n return [\n ...(was === null && exact ? [] : Option.toArray(unlink)),\n ...(now === null ? [] : Option.toArray(link)),\n ]\n },\n }),\n )\n const ruleOf = (\n rules: ReadonlyArray<{\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n ) => rules.flatMap(({ unlink, link }) => [...Option.toArray(unlink), ...Option.toArray(link)])\n const fieldsOf = (\n rules: ReadonlyArray<{ readonly condition: Condition }>,\n more: Iterable<string>,\n ) => [\n ...new Set([\n 'id',\n ...more,\n ...rules.flatMap(({ condition }) => Condition.members(condition)),\n ]),\n ]\n type Expect = Option.Option<{ readonly field: string; readonly revision: unknown }>\n /** The fields that say which version of the row was read: the revision, and the input's. */\n const versionFields = (expect: Expect) => [\n ...(revision === undefined ? [] : [revision]),\n ...Option.match(expect, { onNone: () => [], onSome: ({ field }) => [field] }),\n ]\n /** Whether the row read is not at the revision the input expects. */\n const moved = (expect: Expect, before: Readonly<Record<string, unknown>>) =>\n Option.exists(expect, ({ field, revision }) => !sameStored(before[field], revision))\n /** The write held to the row its rules were decided over, where there is a revision. */\n const pin = (expect: Expect, before: Readonly<Record<string, unknown>>): Expect =>\n revision === undefined ? expect : Option.some({ field: revision, revision: before[revision] })\n /**\n * `attempt` run again while its pinned write misses: the row moved after it\n * was read, so it is decided again over the row as it now is. A write the\n * input pinned misses as a conflict, and is not run again.\n */\n const pinned = <A, E, RA>(\n id: string,\n expect: Expect,\n missed: (outcome: A) => boolean,\n attempt: () => Effect.Effect<A, E, RA>,\n ): Effect.Effect<A, E | RemoteServerError, RA> => {\n if (revision === undefined) return attempt()\n if (Option.isSome(expect)) {\n // The pin is the one revision the write moves on; another would stand still.\n return expect.value.field === revision\n ? attempt()\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s input expects \"${expect.value.field}\", but its writer pins \"${revision}\"`,\n }),\n )\n }\n const loop = (left: number): Effect.Effect<A, E | RemoteServerError, RA> =>\n Effect.flatMap(attempt(), outcome =>\n !missed(outcome)\n ? Effect.succeed(outcome)\n : left > 1\n ? loop(left - 1)\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name} ${id} changed while it was written`,\n }),\n ),\n )\n return loop(3)\n }\n const attachment = attached(entity)\n const hiddenByBody = new WeakMap<AnyQuery, ReadonlyArray<string>>()\n // An invariant reading a member a Read rule hides is still enforced, but named to no\n // one: which one failed, and where, would say what that member holds.\n const unnamed = new Set(\n Option.match(attachment, {\n onNone: () => [],\n onSome: ruled =>\n Entity.invariants(entity)\n .filter(held => [...held.before, ...held.after].some(key => readRuled(ruled, key)))\n .map(held => held.id),\n }),\n )\n const told = <E>(error: E | RemoteInvalid): E | RemoteInvalid =>\n error instanceof RemoteInvalid && Option.exists(error.rule, rule => unnamed.has(rule))\n ? RemoteServer.invalid('The row would be invalid')\n : error\n /**\n * Fails a write whose `when` reads, whose `expect` names, or whose\n * computed assignment reads, a member with a Read rule: Unmet or written,\n * Conflict or not, and the computed value answered, would answer for it.\n * `validate` refuses the same at startup; this holds where it was not run.\n */\n const discloses = (\n expect: Expect,\n when: Option.Option<WriteWhen>,\n assignments: UpdateContext['assignments'] = {},\n ): Effect.Effect<void, RemoteServerError> =>\n Option.match(attachment, {\n onNone: () => Effect.void,\n onSome: ruled => {\n const read = Option.match(when, {\n onNone: () => [],\n onSome: ({ body }) => {\n const known = hiddenByBody.get(body)\n if (known !== undefined) return known\n const hidden = hiddenOf(ruled, Query.dependencies(body).predicate)\n hiddenByBody.set(body, hidden)\n return hidden\n },\n })\n const expected = Option.match(expect, {\n onNone: () => [],\n onSome: ({ field }) => (readRuled(ruled, field) ? [field] : []),\n })\n const computed = Write.boundReads({ increments: {}, assignments }).filter(field =>\n readRuled(ruled, field),\n )\n const hidden = [...new Set([...read, ...expected, ...computed])]\n return hidden.length === 0\n ? Effect.void\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write reads ${hidden.join(', ')}, which a Read rule hides from its writer`,\n }),\n )\n },\n })\n /**\n * The answer the writer's ledger holds for this operation, as `answered`\n * makes it, or else `write`: a retry of a write that landed is answered as\n * it landed, not decided again over a row, or a time, that has moved since.\n */\n const answeredOr = <A, E, RA>(\n context: {\n readonly id: string\n readonly operation: Option.Option<string>\n readonly request: string\n readonly principal: Option.Option<User>\n },\n answered: (answer: Readonly<Record<string, unknown>>) => A,\n write: () => Effect.Effect<A, E, RA>,\n ) => {\n const recorded = writer.recorded\n if (recorded === undefined || Option.isNone(context.operation)) return write()\n return Effect.flatMap(\n recorded({\n operation: context.operation.value,\n request: context.request,\n id: context.id,\n principal: context.principal,\n }),\n Option.match({ onSome: answer => Effect.succeed(answered(answer)), onNone: write }),\n )\n }\n // What an answer shows: the row as the writer may see it, members ruled.\n const memberRead = GuardServer.filter(entity, policy)\n // An update, step by step: admitted for what it declares, its rules chosen, the\n // row they read read, the rules decided over it as it is and as it would be, then\n // written pinned to that row. Each step refuses before the next can speak.\n type UpdateContext = Parameters<EntityWriter<Option.Option<User>, RW>['update']>[0]\n interface UpdateRules {\n readonly row: RowRule\n readonly members: ReadonlyArray<MemberRead>\n readonly relating: Effect.Success<ReturnType<typeof linkRules>>\n }\n /** Refused before any rule, for what the write declares rather than what the row holds. */\n const admitUpdate = (context: UpdateContext): Effect.Effect<void, RemoteServerError> =>\n Effect.andThen(discloses(context.expect, context.when, context.assignments), () =>\n // The rules judge a sum over the row read: unpinned, that is not the row written.\n Object.keys(context.increments).length + Object.keys(context.assignments).length > 0 &&\n Option.isNone(context.expect) &&\n revision === undefined\n ? Effect.fail(\n new RemoteServerError({\n 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`,\n }),\n )\n : Effect.void,\n )\n /** The rules an update must meet: the row's, each member it sets, each relation it points. */\n const updateRules = (context: UpdateContext) =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Update')\n // A field moved or computed is set as surely as a written one: its Update rule holds.\n const members = yield* policy.writeMembers(\n entity,\n context.principal,\n [\n ...Object.keys(context.values),\n ...Object.keys(context.increments),\n ...Object.keys(context.assignments),\n ],\n 'Update',\n )\n const relating = yield* linkRules(context.principal, context.links)\n return { row, members, relating } satisfies UpdateRules\n })\n /**\n * The row as its writer may see it, with every field the rules and the\n * version read, and those the write's amounts and assignments read to\n * work out the row it leaves.\n */\n const readBefore = (context: UpdateContext, rules: UpdateRules) =>\n read({\n id: context.id,\n fields: fieldsOf(\n [rules.row, ...rules.members, ...ruleOf(rules.relating)],\n [\n ...Object.keys(context.links),\n ...versionFields(context.expect),\n ...Write.boundReads(context),\n // What its rule reads of the row by a path is compared with the row it leaves.\n ...Condition.reachedFrom(rules.row.condition, { entity: entity.name, id: context.id }),\n ],\n ),\n principal: context.principal,\n })\n /**\n * The memory table the row a write leaves is worked out by: the writer's,\n * so the rules judge the value its statement writes, else the policy's.\n */\n const computing = writer.operators ?? policy.operators\n /**\n * The row `context` would leave `before` as. An operator's refusal (text\n * holding NUL, an implementation that throws) is a server error, as the\n * writer answers what it cannot compile: reported here (`ComputeRefused`),\n * and never sent, since an implementation's own message may say anything.\n * So is a field it cannot\n * work out at all: judging its old value would let a rule over it pass.\n */\n const leaves = (before: Readonly<Record<string, unknown>>, context: UpdateContext) =>\n Effect.suspend(() => {\n const unworkable = Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write could not be worked out to judge its rules`,\n }),\n )\n try {\n const applied = Write.apply(before, context, { operators: computing })\n return applied.unknown.length === 0 ? Effect.succeed(applied.row) : unworkable\n } catch (error) {\n if (!(error instanceof QueryEvaluateError)) throw error\n return Diagnostics.report(computeRefused(entity.name, error)).pipe(\n Effect.andThen(unworkable),\n )\n }\n })\n /** The rules, over the row as it is and as the write would leave it. */\n const decideUpdate = (\n context: UpdateContext,\n rules: UpdateRules,\n before: Readonly<Record<string, unknown>>,\n ) =>\n Effect.gen(function* () {\n const { principal, links } = context\n const linked = Object.keys(links)\n const stored =\n writer.linked === undefined || linked.length === 0\n ? Option.none()\n : yield* writer.linked({ id: context.id, relations: linked })\n const was = Option.some(\n Option.match(stored, {\n onNone: () => ({ links: before, exact: false }),\n onSome: links => ({ links, exact: true }),\n }),\n )\n const relations = linking(rules.relating, was)\n // The rules over the row as stored refuse first: a writer they refuse learns\n // nothing of what its input would compute. What the row alone cannot decide\n // of its own rule is the statement's to judge, over the row it writes.\n const requires = yield* rowRule(rules.row, before, principal)\n yield* require([...rules.members, ...relations], before, principal)\n // What the writer will store, over the row read, which the pin keeps as the row\n // written: `Write.apply`'s, as the writer works it out.\n const after = {\n ...(yield* leaves(before, context)),\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n // Over the row it leaves, a rule reading another row is the statement's too,\n // which judges the stored row: so a write may not change what such a rule\n // reads of its own row, the one difference between the two.\n const leaving = yield* rowRule(rules.row, after, principal)\n if (Option.isSome(leaving)) {\n const read = Condition.reachedFrom(\n Condition.residual(\n rules.row.condition,\n after,\n policy.inputOf(principal),\n policy.operators,\n ),\n { entity: entity.name, id: context.id },\n )\n if (read.some(key => !sameStored(before[key], after[key]))) {\n return yield* Effect.fail(refused(rules.row.deny))\n }\n }\n // Each member's rule and each link's also over the row it leaves with that one\n // change undone: may it change, given all else the write does. Over the row before\n // alone, one write could set together what each change alone may not; over the\n // whole row after, \"only while a draft\" would refuse leaving the draft. An unlink is\n // of the row before, which the row after no longer points from.\n const undone = [\n ...rules.members.map(rule => ({ rule, key: rule.member })),\n ...rules.relating.flatMap(rule =>\n linking([{ ...rule, unlink: Option.none() }], was).map(link => ({\n rule: link,\n key: rule.relation,\n })),\n ),\n ]\n yield* Effect.forEach(\n undone,\n ({ rule, key }) => require([rule], { ...after, [key]: before[key] }, principal),\n { discard: true },\n )\n return requires\n })\n const guarded: EntityWriter<Option.Option<User>, R | RW> = {\n entity: writer.entity,\n // The precondition is the writer's to check, in the statement that writes.\n ...(writer.preconditions === true ? { preconditions: true } : {}),\n ...(writer.increments === true ? { increments: true } : {}),\n ...(writer.assignments === true ? { assignments: true } : {}),\n // With a revision every update lands over the row its rules read. Without one an\n // unpinned move is refused, so what the writer would say commutes is not passed on.\n ...(revision === undefined ? {} : { pins: true }),\n ...(writer.ledger === true ? { ledger: true } : {}),\n // Invariants are the writer's to judge, over the row its statement writes.\n ...(writer.invariants === true ? { invariants: true } : {}),\n // The rows a delete takes with it are the writer's to remove; the guard judges the row named.\n ...(writer.cascades === true ? { cascades: true } : {}),\n // What the store refuses, the store knows: the guard drops none of its reasons. It\n // adds one: its rules judge the row the write leaves, worked out by the policy's\n // table, so an assignment that table cannot run would be judged as its old value.\n refuses: write => [\n ...(writer.refuses?.(write) ?? []),\n ...write.assignments.flatMap(({ field, expr }) =>\n Expr.unsupported([expr], { operations: supported, operators: computing }).map(\n missing =>\n `its assignment to \"${field.key}\" calls ${missing}, which the guard cannot work out`,\n ),\n ),\n // Refused per request too (`admitUpdate`), for a caller that registers none.\n ...((write.increments.length > 0 || write.assignments.length > 0) &&\n write.expect === undefined &&\n revision === undefined\n ? [\n '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',\n ]\n : []),\n ],\n ...(writer.recorded === undefined ? {} : { recorded: writer.recorded }),\n read: ({ id, fields, principal }) =>\n seenRow(\n { filter: memberRead },\n seen => read({ id, fields: seen, principal }),\n principal,\n fields,\n id,\n ),\n update: context =>\n Effect.mapError(\n Effect.andThen(admitUpdate(context), () =>\n answeredOr(context, Option.some, () =>\n pinned(context.id, context.expect, Option.isNone, () =>\n Effect.gen(function* () {\n const rules = yield* updateRules(context)\n const current = yield* readBefore(context, rules)\n if (Option.isNone(current)) return yield* Effect.fail(refused(rules.row.deny))\n if (moved(context.expect, current.value)) return Option.none()\n const requires = yield* decideUpdate(context, rules, current.value)\n return yield* writer.update({\n ...context,\n expect: pin(context.expect, current.value),\n ...Option.match(requires, {\n onNone: () => ({}),\n onSome: held => ({ requires: held }),\n }),\n })\n }),\n ),\n ),\n ),\n told,\n ),\n insert: context =>\n answeredOr(context, identity, () =>\n Effect.gen(function* () {\n const { principal, values, links } = context\n const row = yield* policy.writable(entity, principal, 'Create')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n Object.keys(values),\n 'Create',\n )\n const relations = linking(yield* linkRules(principal, links), Option.none())\n const proposed = {\n ...values,\n id: context.id,\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n const rules = [row, ...members, ...relations]\n const ruled = rules.flatMap(({ condition }) => Condition.members(condition))\n const unset = new Set(ruled.filter(field => !Object.hasOwn(proposed, field)))\n yield* require(rules.map(rule => ({\n ...rule,\n condition: Condition.unsetting(rule.condition, unset),\n })), proposed, principal)\n return yield* Effect.mapError(writer.insert(context), told)\n }),\n ),\n delete: context =>\n Effect.andThen(discloses(context.expect, context.when), () =>\n pinned(context.id, context.expect, DeleteOutcome.$is('Moved'), () =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Delete')\n const current = yield* read({\n id: context.id,\n fields: fieldsOf([row], versionFields(context.expect)),\n principal: context.principal,\n })\n // Hidden or gone, the writer sees no row: there is nothing of theirs to delete.\n if (Option.isNone(current)) return DeleteOutcome.Absent()\n if (moved(context.expect, current.value)) return DeleteOutcome.Moved()\n const requires = yield* rowRule(row, current.value, context.principal)\n return yield* writer.delete({\n ...context,\n expect: pin(context.expect, current.value),\n ...Option.match(requires, {\n onNone: () => ({}),\n onSome: held => ({ requires: held }),\n }),\n })\n }),\n ),\n ),\n }\n const asked: EntityWriter<Option.Option<User>, R | RW> = {\n ...guarded,\n update: context => signInFirst(context.principal, guarded.update(context)),\n insert: context => signInFirst(context.principal, guarded.insert(context)),\n delete: context => signInFirst(context.principal, guarded.delete(context)),\n }\n pins.set(asked, Option.fromUndefinedOr(revision))\n return writeRules.add(asked, policy, [entity])\n },\n\n /**\n * A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for\n * `interaction` checked before it runs. The row the input names (`id`) is\n * read through `source`, which must apply the Entity's Read rules, and the\n * rule must hold over it; a row its writer may not see is refused. With no\n * `id` (a create), the rule must hold of who is asking alone, a field it\n * reads matching no guard. `run` is given the row as read: its fields the\n * rule reads, its `id`, and `fields`. A refusal is `Forbidden`, or\n * `Unauthenticated` for a visitor; `run` never runs. What `run` writes is its own: check members it sets there. Each\n * row of `entity` its answer carries is read back through `source`, so the\n * answer shows its writer only what they may see, a row it hid from them\n * as deleted.\n *\n * ```ts\n * GuardServer.mutation(ArchiveTodo, {\n * entity: Todo, policy: Policy, interaction: Archive.key,\n * id: input => input.id, source: source(Db.Todo),\n * }, ({ input, row }) => …)\n * ```\n */\n mutation: <User, R, RS, RM, Name extends string, Input, Output, Refused>(\n mutation: MutationDescriptor<Name, Input, Output, Refused>,\n guard: {\n readonly entity: AnyEntity\n readonly policy: Policy<User, R>\n readonly interaction: 'Create' | 'Update' | 'Delete' | InteractionKey\n /**\n * The row the input acts on; none for a create. An input whose id may be\n * absent (`Option`, as one editor's for create and edit) creates when it\n * is, checked against `Create`.\n */\n readonly id?: ((input: Input) => string | Option.Option<string>) | undefined\n /** Reads the row as its writer may see it: the Entity's guarded Source. */\n readonly source: EntitySource<Option.Option<User>, RS>\n /** More of the row for `run`, beside what the rule reads. */\n readonly fields?: ReadonlyArray<string> | undefined\n },\n run: (context: {\n readonly input: Input\n readonly principal: Option.Option<User>\n readonly requestId: string\n readonly row: Option.Option<Readonly<Record<string, unknown>>>\n }) => Effect.Effect<\n MutationOutcome<Output>,\n RemoteServerError | MutationRefused | RemoteForbidden,\n RM\n >,\n ): MutationSource<Option.Option<User>, R | RS | RM> => {\n const { entity, policy, interaction, id, source } = guard\n if (!rowRules.has(source.visible, policy, entity)) {\n throw new Error(\n `[foldkit-guard] GuardServer.mutation: ${mutation.name}'s Source does not apply ${entity.name}'s Read rules`,\n )\n }\n /**\n * The answer as its writer may now see it: each row of `entity` it carries\n * read back through `source`, and one the handler hid from them deleted.\n */\n const shown = (outcome: MutationOutcome<Output>, principal: Option.Option<User>) =>\n Effect.map(\n Effect.forEach(outcome.entities ?? [], patch =>\n patch.entity !== entity.name\n ? Effect.succeed(Option.some(patch))\n : Effect.map(\n seenRow(\n source,\n fields =>\n Effect.map(rowOf(source, principal, fields, patch.id), Option.fromUndefinedOr),\n principal,\n Object.keys(patch.values),\n patch.id,\n ),\n Option.map(seen => ({ ...patch, values: seen })),\n ),\n ),\n read => ({\n ...outcome,\n entities: read.flatMap(Option.toArray),\n deleted: [\n ...(outcome.deleted ?? []),\n ...(outcome.entities ?? [])\n .filter((_, index) => Option.isNone(read[index]!))\n .map(({ entity, id }) => ({ entity, id })),\n ],\n }),\n )\n return RemoteServer.mutation<Option.Option<User>, R | RS | RM, Name, Input, Output, Refused>(\n mutation,\n context =>\n Effect.gen(function* () {\n const { principal } = context\n // `context.input` was decoded against the mutation's Input before this runs.\n const target = Option.flatMap(Option.fromUndefinedOr(id), of => {\n const named = of(context.input)\n return typeof named === 'string' ? Option.some(named) : named\n })\n const rule = yield* policy.writable(\n entity,\n principal,\n id !== undefined && Option.isNone(target) ? 'Create' : interaction,\n )\n const ruled = Condition.members(rule.condition)\n const input = policy.inputOf(principal)\n if (Option.isNone(target)) {\n const unset = Condition.unsetting(rule.condition, new Set(ruled))\n if (!Condition.holds(unset, {}, input, () => false, policy.operators)) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row: Option.none() }), principal)\n }\n const fields = [...new Set(['id', ...ruled, ...(guard.fields ?? [])])]\n const row = Option.fromUndefinedOr(yield* rowOf(source, principal, fields, target.value))\n if (\n Option.isNone(row) ||\n !Condition.holds(rule.condition, row.value, input, () => false, policy.operators)\n ) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row }), principal)\n }).pipe(answered => signInFirst(context.principal, answered)),\n )\n },\n\n /**\n * Checks, at startup, that `server` applies the guards of `entities`, the\n * Entities as `Guards.attach` returned them: each one's Source and each\n * query listing it apply its row's Read rules (`GuardDrizzle.visible`, or\n * `GuardServer.memory`), its Source applies its members' and relations'\n * (`GuardServer.filter`), and each declared write of it lands through\n * `GuardServer.writer`, all built from `policy`; and that no query's body\n * filters or orders by a member with a Read rule, its own or one of a row it\n * reaches through a path or an exists, which would answer for the value it\n * hides. A hand-written Source over a guarded Entity would serve\n * every row, and a bare writer would take every write; this throws instead,\n * naming each. A handler (`RemoteServer.mutation`) writes what its code\n * writes, which no check at startup can read. A write a change can come\n * between, through a writer given no revision, is not refused but reported:\n * `UnpinnedWrites`, a warning, to `diagnostics`.\n *\n * ```ts\n * GuardServer.validate(Policy, { entities: [Todo, Project], domain: Data, server: Server })\n * ```\n */\n validate: <User, R>(\n policy: Policy<User, R>,\n config: {\n readonly entities: ReadonlyArray<AnyEntity>\n /** The Remote domain the server answers, for which Entity each query lists. */\n readonly domain: {\n readonly registry: {\n readonly queries: ReadonlyMap<\n string,\n { readonly Result: unknown; readonly body?: AnyQuery | undefined }\n >\n }\n }\n readonly server: ServerDefinition<any, any>\n /** Where the `UnpinnedWrites` warning goes; `Diagnostics.Reporter`'s default, the log, when not given. */\n readonly diagnostics?: ReportDiagnostic | undefined\n },\n ): void => {\n const byName = new Map(config.entities.map(entity => [entity.name, entity]))\n /** Whether a reached member has a Read rule; one of an Entity not validated has none checked. */\n const hidesFromReach = ({ entity, key }: ReachedMember) =>\n Option.exists(\n Option.flatMap(Option.fromUndefinedOr(byName.get(entity)), attached),\n attachment => readRuled(attachment, key),\n )\n /** Whether who may read the rows of `entity` depends on who is asking. */\n const rowsRuled = (entity: AnyEntity | undefined) =>\n Option.exists(Option.flatMap(Option.fromUndefinedOr(entity), attached), attachment =>\n readRowsRuled(attachment),\n )\n // A query the domain does not declare lists an Entity no one can name.\n const undeclared = [...config.server.queries.keys()]\n .filter(query => !config.domain.registry.queries.has(query))\n .map(query => `query ${query} is served, but the domain does not declare it`)\n const entityProblems = config.entities.flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => {\n const name = entity.name\n if (attachment.set !== policy.set) {\n return [`${name} carries the guards of ${attachment.set}, not ${policy.set}`]\n }\n // Every guarded Entity's, whether or not it has rules there yet: a rule\n // attached later is then applied, not served past.\n const source = Option.fromUndefinedOr(config.server.entities.get(name))\n const sourceProblems = Option.match(source, {\n onNone: () => [],\n onSome: ({ visible, filter }) => [\n ...(rowRules.has(visible, policy, entity)\n ? []\n : [`${name}'s Source does not apply its Read rules`]),\n ...(memberRules.has(filter, policy, entity)\n ? []\n : [`${name}'s Source does not apply its members' Read rules`]),\n ],\n })\n const queryProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, query]) => {\n const listed = config.server.queries.get(queryName)\n return listed !== undefined &&\n lists(query.Result, name) &&\n !rowRules.has(listed.visible, policy, entity)\n ? [`query ${queryName} lists ${name} without its Read rules`]\n : []\n },\n )\n // A row the reader may see with a member it may not still answers a\n // filter or an order on that member: `cost < $max`, halved twenty\n // times, reads the cost the row came back without.\n const bodyProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, { body }]) => {\n if (body === undefined || body.entity.name !== name) return []\n const { predicate, order, reaches } = Query.dependencies(body)\n const reached = [\n ...new Set(\n reachedMembers(reaches)\n .filter(hidesFromReach)\n .map(\n ({ entity, key }) =>\n `query ${queryName} reaches ${entity}'s ${key}, which has a Read rule`,\n ),\n ),\n ]\n return [\n ...hiddenOf(attachment, predicate).map(\n member =>\n `query ${queryName} filters ${name} by ${member}, which has a Read rule`,\n ),\n ...hiddenOf(attachment, order).map(\n member => `query ${queryName} orders ${name} by ${member}, which has a Read rule`,\n ),\n ...reached,\n ]\n },\n )\n const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) => {\n if (source.writes === undefined || source.writes.entity !== name) return []\n if (!writeRules.has(source.writes.writer, policy, entity)) {\n return [`write ${mutation} writes ${name} without its write rules`]\n }\n const { write, writer } = source.writes\n const interaction = Match.valueTags(write, {\n Insert: () => 'Create',\n Update: () => 'Update',\n Delete: () => 'Delete',\n })\n // Left without a rule under 'allow', a served write is anyone's: that is\n // written down as `Guards.anyone`, never left to a forgotten rule.\n const open =\n attachment.unguarded === 'allow' &&\n Option.isNone(surfaceOf(attachment, { _tag: 'Row', interaction }))\n ? [\n `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`,\n ]\n : []\n // Unmet or written, Conflict or not, answers for a member its writer may not read.\n const when = Option.match(write.when, {\n onNone: () => [],\n onSome: body => hiddenOf(attachment, Query.dependencies(body).predicate),\n })\n const computed = write.assignments.flatMap(assignment =>\n hiddenOf(attachment, dependenciesOf(assignment.expr).fields).map(\n member =>\n `write ${mutation} computes ${name}'s ${assignment.field.key} from its ${member}, which has a Read rule`,\n ),\n )\n const expected = write.expect?.field.key\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n return [\n ...open,\n ...when.map(\n member =>\n `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`,\n ),\n ...computed,\n ...(expected !== undefined && readRuled(attachment, expected)\n ? [`write ${mutation} expects ${name}'s ${expected}, which has a Read rule`]\n : []),\n ...(expected !== undefined &&\n pin !== undefined &&\n Option.exists(pin, field => field !== expected)\n ? [\n `write ${mutation} expects ${name}'s ${expected}, but its writer pins ${Option.getOrThrow(pin)}`,\n ]\n : []),\n ]\n })\n // A shared field goes to every live subscriber as written: no rule may tell them apart.\n const shared: ReadonlyArray<string> = Option.match(source, {\n onNone: () => [],\n onSome: source => [...(source.shared ?? [])],\n })\n const sharedProblems = [\n ...(shared.length > 0 && readRowsRuled(attachment)\n ? [`${name}'s Source shares ${shared.join(', ')}, but its rows have a Read rule`]\n : []),\n // Each reader's own answer, whoever may read the row.\n ...(shared.includes('may') && asksMay(entity, ['may'])\n ? [`${name}'s Source shares may, which is answered for each reader`]\n : []),\n ...shared.flatMap(member => {\n const own = readRuled(attachment, member)\n ? [`${name}'s Source shares ${member}, which has a Read rule`]\n : []\n if (!Object.hasOwn(entity.relations, member)) return own\n const target = entity.relations[member]!.target().name\n if (!byName.has(target))\n return [\n ...own,\n `${name}'s Source shares ${member}, whose ${target} is not validated`,\n ]\n return rowsRuled(byName.get(target))\n ? [...own, `${name}'s Source shares ${member}, whose rows have a Read rule`]\n : own\n }),\n ]\n // A rule calling an operator the policy's table does not run would fail when\n // asked, so the server does not start with one (expr-operations-DESIGN §5.6).\n const operatorProblems = attachedRules(attachment).flatMap(rule =>\n rule._tag === 'RowGuard'\n ? Query.unsupported(rule.query, supported, policy.operators).map(\n missing =>\n `${name}'s ${rule.name} calls ${missing}, which the policy does not run`,\n )\n : [],\n )\n // A live Source sends what it reads: only one reading through the Source\n // checked above is known to send what a read would.\n const live = Option.fromUndefinedOr(config.server.live.get(name))\n const liveProblems = Option.exists(\n live,\n ({ reads }) => !Option.exists(source, checked => checked === reads),\n )\n ? [\n `${name}'s live Source does not read through its guarded Source; poll through that Source (pollLive) or serve changes through a live hub`,\n ]\n : []\n return [\n ...sourceProblems,\n ...queryProblems,\n ...bodyProblems,\n ...writeProblems,\n ...sharedProblems,\n ...operatorProblems,\n ...liveProblems,\n ]\n },\n }),\n )\n const problems = [...undeclared, ...entityProblems]\n if (problems.length > 0) {\n throw new Error(`[foldkit-guard] GuardServer.validate: ${problems.join('; ')}`)\n }\n // Not refused yet: a writer given no revision is how every writer was made before it.\n // Named only where a change between the check and the write can happen: an update\n // always, a delete where the server updates that Entity, an insert, with no row, never.\n const updated = new Set(\n [...config.server.mutations.values()]\n .flatMap(source => (source.writes === undefined ? [] : [source.writes]))\n .filter(writes => writes.write._tag === 'Update')\n .map(writes => writes.entity),\n )\n const unpinned = [...config.server.mutations].flatMap(([mutation, source]) => {\n const writes = source.writes\n if (writes === undefined) return []\n const writer = writes.writer\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n if (pin === undefined || Option.isSome(pin)) return []\n const races = Match.valueTags(writes.write, {\n Update: () => true,\n Delete: () => updated.has(writes.entity),\n Insert: () => false,\n })\n return races ? [mutation] : []\n })\n if (unpinned.length > 0) {\n // A startup check runs before any Effect of the server's, so the reporter is an option.\n const report = Diagnostics.report(unpinnedWrites(unpinned))\n const { diagnostics } = config\n Effect.runFork(\n diagnostics === undefined\n ? report\n : Effect.provideService(report, Diagnostics.Reporter, diagnostics),\n )\n }\n },\n}\n\n/** Whether a read asks for `may`, of an Entity that has it (`Guards.may`). */\nconst asksMay = (entity: AnyEntity, fields: ReadonlyArray<string>) =>\n fields.includes('may') && Object.hasOwn(entity.derived, 'may')\n\n/** How one principal's `may` is answered: the fields its rules read, and the answer over a row. */\ninterface MayPlan {\n readonly fields: ReadonlyArray<string>\n readonly answer: (values: Readonly<Record<string, unknown>>) => MayAnswer\n}\n\n/**\n * `may` for `principal`: each row interaction's rule, each member's own\n * `Update`, each relation's `Link` and `Unlink`, decided once and held over\n * each row as a write's check would hold them over it as it is.\n */\nconst mayOf = <User, R>(\n entity: AnyEntity,\n policy: Policy<User, R>,\n principal: Option.Option<User>,\n): Effect.Effect<MayPlan, never, R> =>\n Effect.map(\n mayRules(entity, {\n // A named one was attached as an `InteractionKey`; its key is the name.\n row: interaction => policy.writable(entity, principal, interaction as InteractionKey),\n members: members => policy.writeMembers(entity, principal, members, 'Update'),\n relation: (relation, interaction) =>\n policy.linkable(entity, principal, relation, interaction),\n }),\n (rules): MayPlan => {\n const input = policy.inputOf(principal)\n return {\n // `id` too, so a row is read when its rules read none of it (an admin's).\n fields: ['id', ...new Set(mayConditions(rules).flatMap(Condition.members))],\n // A rule reading another row is the write's statement's to judge: not answered here.\n answer: values =>\n answerOf(rules, condition =>\n Condition.decided(Condition.residual(condition, values, input, policy.operators)),\n ),\n }\n },\n )\n\n/** A refused write as the client receives it: the sentence an `explain` gave, or none. */\n/** The words a refusal gives: an `explain`'s, or none. */\nconst explained = (deny: Deny): Option.Option<string> =>\n Match.valueTags(deny, {\n Explain: ({ reason }) => Option.some(reason),\n Forbidden: () => Option.none(),\n NotFound: () => Option.none(),\n Omit: () => Option.none(),\n Redact: () => Option.none(),\n })\n\n/**\n * What is left of a condition, as a writer's statement judges it: each row\n * guard a body over the row, its input the principal's (`G.inputOf`), and its\n * context the one it was decided for. An inherited Read, which a writer\n * refuses, requires what no row holds.\n */\nconst requirementOf = (\n condition: Condition,\n input: Readonly<Record<string, unknown>>,\n): RowRequirement =>\n Match.valueTags(condition, {\n Always: () => RowRequirement.All({ of: [] }),\n Never: () => RowRequirement.Any({ of: [] }),\n Row: ({ guard, context }) => RowRequirement.Body({ query: guard.query, input, context }),\n Inherit: () => RowRequirement.Any({ of: [] }),\n And: ({ conditions }) =>\n RowRequirement.All({ of: conditions.map(each => requirementOf(each, input)) }),\n Or: ({ conditions }) =>\n RowRequirement.Any({ of: conditions.map(each => requirementOf(each, input)) }),\n })\n\n/**\n * A visitor's refused write as a sign-in it needs: `Unauthenticated`, never\n * `Forbidden`, so a client tells a session that ended (its cookie gone, it\n * asks as a visitor) from a person refused, and a durable write waits for the\n * sign-in rather than failing (#403). A refusal's words go with it.\n */\nconst signInFirst = <User, A, E, R>(\n principal: Option.Option<User>,\n write: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E | RemoteUnauthenticated, R> =>\n Option.isSome(principal)\n ? write\n : Effect.mapError(write, error =>\n error instanceof RemoteForbidden ? RemoteServer.unauthenticated(error.reason) : error,\n )\n\nconst refused = (deny: Deny) =>\n Match.valueTags(deny, {\n Explain: ({ reason }) => RemoteServer.forbid(reason),\n Forbidden: () => RemoteServer.forbid(),\n NotFound: () => RemoteServer.forbid(),\n Omit: () => RemoteServer.forbid(),\n Redact: () => RemoteServer.forbid(),\n })\n\n/** One row, by id, as `principal` may read it through `source`. */\nconst rowOf = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n) =>\n Effect.map(\n source.read({ ids: [id], fields: [...fields], principal }),\n records => records.find(record => record.id === id)?.values,\n )\n\n/**\n * Row `id` of `fields` as `principal` may see it, through `see`'s `authorize`\n * and `filter` as a Source applies them, and no more than was asked: what an\n * answer shows its writer. None when the row is not there to them.\n */\nconst seenRow = <P, R, RS>(\n see: Pick<EntitySource<P, RS>, 'authorize' | 'filter'>,\n read: (\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n): Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R | RS> =>\n Effect.gen(function* () {\n const allowed = see.authorize === undefined ? fields : see.authorize(principal, [...fields])\n const plan: ReadPlan =\n see.filter === undefined\n ? { fields: allowed, apply: noMembers }\n : yield* see.filter(principal, allowed)\n // The id too: a row asked for nothing else is still there or not.\n const row = yield* read([...new Set(['id', ...plan.fields])])\n return Option.map(row, values => {\n const shown = plan.apply({ id, values }).values\n return Object.fromEntries(\n allowed.filter(field => Object.hasOwn(shown, field)).map(field => [field, shown[field]]),\n )\n })\n })\n\n/** A link's value as a row holds it: the ref's key, or `null` for none. */\nconst linkKey = (link: Option.Option<{ readonly entity: string; readonly id: string }>) =>\n Option.match(link, { onNone: () => null, onSome: ref => `${ref.entity}:${ref.id}` })\n\n/** Whether a query's result is a connection over `entity`. */\nconst lists = (result: unknown, entity: string): boolean =>\n typeof result === 'object' && result !== null && 'entity' in result && result.entity === entity\n"],"mappings":";;;;;;;;;;AAOA,MAAM,SAAS;AA0Bf,MAAa,kBAAkB,QAAgB,WAAkC;CAC/E,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,OAAO,qEAAqE,MAAM,QAAQ;CACtG;CACA;AACF;AAEA,MAAa,kBAAkB,eAAsD;CACnF,MAAM;CACN;CACA,OAAO;CACP,SAAS,yBAAyB,UAAU,KAAK,IAAI,EAAE,GAAG,UAAU,WAAW,IAAI,WAAW,QAAQ;CACtG;AACF;;;;;;;;;ACeA,MAAM,aAAa,WAAyB;;AAG5C,MAAM,cAAc,MAAe,UACjC,KAAK,UAAU,IAAI,MAAM,KAAK,UAAU,KAAK;;AAG/C,MAAM,YACJ,YACA,WAC0B,CAC1B,GAAG,IAAI,IAAI,OAAO,KAAI,UAAS,MAAM,GAAG,CAAC,CAAC,QAAO,QAAO,UAAU,YAAY,GAAG,CAAC,CAAC,CACrF;;;;;;;AAcA,MAAM,kBACJ,YAEA,QAAQ,SAAQ,YAAW;CACzB,MAAM,MAAM,QAAQ,IAAI,KAAI,cAAa;EAAE,QAAQ,SAAS,MAAM;EAAM,KAAK,SAAS;CAAI,EAAE;CAC5F,OAAO,MAAM,UAAU,SAAS;EAC9B,OAAO,EAAE,YAAY,CAAC,GAAG,KAAK;GAAE,QAAQ,MAAM,MAAM;GAAM,KAAK,MAAM;EAAI,CAAC;EAC1E,aAAa,EAAE,YAAY,CAAC,GAAG,KAAK;GAAE,QAAQ,MAAM,MAAM;GAAM,KAAK,MAAM;EAAI,CAAC;EAChF,SAAS,EAAE,UAAU,YAAY;GAC/B,MAAM,SAAS,OAAO,MAAM,OAAO;IACjC,cAAc,CAAC;IACf,SAAQ,SAAQ;KACd,MAAM,OAAO,eAAe,IAAI;KAChC,OAAO,CACL,GAAG,KAAK,O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f,OAAO,MAAM,MAAM;CAAE,cAAc;CAAM,SAAQ,QAAO,GAAG,IAAI,OAAO,GAAG,IAAI;AAAK,CAAC;;AAGrF,MAAM,SAAS,QAAiB,WAC9B,OAAO,WAAW,YAAY,WAAW,QAAQ,YAAY,UAAU,OAAO,WAAW"}
package/dist/sync.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as PrincipalGuard, S as Policy } from "./attach-DPgyv78F.mjs";
1
+ import { C as PrincipalGuard, S as Policy } from "./attach-CJl-GtbN.mjs";
2
2
  import { Effect, Option } from "effect";
3
3
  import { AnyEntity } from "foldkit-entity";
4
4
  import { EntitySource } from "foldkit-remote-server";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-guard",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Who may do what, declared once on a Foldkit Plus domain: principal guards implemented on the server, row guards as query expressions.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -61,17 +61,17 @@
61
61
  "LICENSE"
62
62
  ],
63
63
  "dependencies": {
64
- "foldkit-entity": "0.14.0",
64
+ "foldkit-entity": "0.15.0",
65
65
  "foldkit-metadata": "0.1.0"
66
66
  },
67
67
  "peerDependencies": {
68
68
  "drizzle-orm": "1.0.0-rc.5",
69
69
  "effect": "^4.1.0",
70
- "foldkit-remote": "^0.22.0",
71
- "foldkit-media": "^0.4.0",
72
- "foldkit-remote-drizzle": "^0.16.0",
73
- "foldkit-sync": "^0.13.0",
74
- "foldkit-remote-server": "^0.19.0"
70
+ "foldkit-remote": "^0.23.0",
71
+ "foldkit-remote-drizzle": "^0.17.0",
72
+ "foldkit-remote-server": "^0.20.0",
73
+ "foldkit-media": "^0.5.0",
74
+ "foldkit-sync": "^0.14.0"
75
75
  },
76
76
  "peerDependenciesMeta": {
77
77
  "drizzle-orm": {
@@ -96,20 +96,20 @@
96
96
  "devDependencies": {
97
97
  "@electric-sql/pglite": "0.5.11",
98
98
  "drizzle-orm": "1.0.0-rc.5",
99
- "effect": "^4.1.0",
99
+ "effect": "^4.1.1",
100
100
  "foldkit": "0.170.0",
101
101
  "tsdown": "^0.23.1",
102
102
  "typescript": "7.0.2",
103
- "foldkit-agent": "0.9.0",
104
- "foldkit-remote": "0.22.0",
105
- "foldkit-surface": "0.11.0",
106
- "foldkit-media": "0.4.0",
107
- "foldkit-remote-server": "0.19.0",
108
- "foldkit-remote-drizzle": "0.16.0",
109
- "foldkit-sync": "0.13.0"
103
+ "foldkit-agent": "0.10.0",
104
+ "foldkit-remote": "0.23.0",
105
+ "foldkit-media": "0.5.0",
106
+ "foldkit-remote-drizzle": "0.17.0",
107
+ "foldkit-surface": "0.12.0",
108
+ "foldkit-remote-server": "0.20.0",
109
+ "foldkit-sync": "0.14.0"
110
110
  },
111
111
  "scripts": {
112
- "build": "tsdown",
112
+ "build": "node ../../scripts/declarations.mjs . && tsdown && node ../../scripts/declared-any.mjs .",
113
113
  "typecheck": "tsc -b"
114
114
  }
115
115
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"attach-DPgyv78F.d.mts","names":["MemberKeys","_$__attach_js0.Attach","_$__attach_js0.AnyRule","_$__attach_js0.Inherit","_$__attach_js0.All","_$__attach_js0.Redact","_$__attach_js0.Explain","_$__attach_js0.On"],"sources":["../src/condition.ts","../src/may.ts","../src/me.ts","../src/index.ts","../src/attach.ts"],"mappings":";;KAuBY;WACG;;WACA;;;;WAGA;WACA,OAAO,cAAc;WACrB,SAAS;;;;WAGT;WAA0B;;WAC1B;WAAsB,YAAY,cAAc;;WAChD;WAAqB,YAAY,cAAc;;;cAUxD,MAAG,YAAgB,cAAc,eAAa;;cAY9C,KAAE,YAAgB,cAAc,eAAa;cAWtC;;aA5CQ;;;aACA;;;;;;;;;;;;;;EA4DN,QAAA,WAAA,WAAS,QACZ,SAAS,0BAAwB,OAClC,SAAS,0BAAwB,UAC9B,8BAA4B,WAC3B;;;;;;;;EA2BA,WAAA,WAAA,WAAS,QACZ,SAAS,0BAA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