foldkit-guard 0.3.0 → 0.4.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
@@ -1,8 +1,7 @@
1
1
  # foldkit-guard
2
2
 
3
3
  Who may do what, declared once on a Foldkit Plus domain, and enforced on every
4
- path a row is read or written by. [`guard-DESIGN.md`](../../docs/design/guard-DESIGN.md)
5
- explains the design and why.
4
+ path a row is read or written by.
6
5
 
7
6
  ## What it is
8
7
 
@@ -62,8 +61,8 @@ pnpm add effect foldkit-entity foldkit-guard
62
61
  `foldkit-guard` is the shared declaration. Its subpaths bring their packages
63
62
  as optional peers: `foldkit-guard/server` needs `foldkit-remote` and
64
63
  `foldkit-remote-server`, `/drizzle` also `foldkit-remote-drizzle` and
65
- `drizzle-orm`, `/sync` `foldkit-sync` and `foldkit-remote-server`, and
66
- `/agent` `foldkit-remote`.
64
+ `drizzle-orm`, `/sync` `foldkit-sync` and `foldkit-remote-server`,
65
+ `/agent` `foldkit-remote`, and `/media` `foldkit-media`.
67
66
 
68
67
  ## Sixty seconds
69
68
 
@@ -350,7 +349,8 @@ Policy as it is and require its services where the write runs.
350
349
  ## Serving writes
351
350
 
352
351
  A declared write (`Mutation.write`) is served by `RemoteServer.write` with no
353
- handler. Wrap its writer, and the write rules are checked before it lands:
352
+ handler (the [declared writes guide](../../docs/declared-writes.md) shows the
353
+ whole path, client to statement). Wrap its writer, and the write rules are checked before it lands:
354
354
 
355
355
  ```ts
356
356
  import { Write } from 'foldkit-entity'
@@ -388,6 +388,59 @@ RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
388
388
  fields than the write set, and a row the write hid from them in `deleted`,
389
389
  so the client takes it out of its lists instead of placing it.
390
390
 
391
+ Reading the row and writing it are two statements, so another write can land
392
+ between the check and the write. Name a revision, a field stored as a number
393
+ that the writer moves on by one with every write it lands, and the guard closes
394
+ that window for every write that moves it: for an Entity with
395
+ a `revision` field, `GuardServer.writer(Todo, Policy, writer(Db.Todo), {
396
+ revision: 'revision' })`. Every update and delete then lands only on the
397
+ revision its rules were decided over (the writer's `expect`, one compare and
398
+ set statement). If the row moved after the check, it is decided again over
399
+ the row as it now is, up to three times, then fails with "changed while it
400
+ was written"; nothing is written over a version no rule saw. An input that
401
+ `expect`s a revision the row is not at is a `Conflict`, decided before any
402
+ rule, and not retried. An input may expect only the revision the writer pins:
403
+ one expecting another field is refused, at startup by `GuardServer.validate`
404
+ and at run time, since the pin would leave that field where it was. A writer
405
+ with no `revision` keeps the window, and `GuardServer.validate` warns of each
406
+ write through one.
407
+
408
+ A declared write's `when` (`foldkit-entity`) is the writer's to check, in the
409
+ statement that writes; the guarded writer passes it through and speaks first.
410
+ The order is: a row hidden from the writer, then a rule that does not hold
411
+ (both `Forbidden`), then a stale input revision (`Conflict`), then the
412
+ precondition (`Unmet`). So `Unmet` reaches only someone the rules let write the
413
+ row. A precondition, or an expected revision, over a member with a Read rule
414
+ would still answer for that member (Unmet or written, Conflict or not), so the
415
+ guarded writer refuses such a write before any rule, whether or not
416
+ `GuardServer.validate` ran; `validate` refuses it at startup too, as it refuses
417
+ a query body that filters by such a member. A pinned write that is unmet is not
418
+ decided again: the row did not move, it does not hold.
419
+
420
+ A declared write's `increment` is the writer's to add, in the statement that
421
+ writes. The guard requires each incremented member's Update rule, as for a
422
+ member it sets, and holds the row's rules over the sum the writer will store, so
423
+ a rule `stock >= 0` refuses a sale past zero. The row the guard summed over must
424
+ be the row the writer writes: the input's expected revision keeps it so, or the
425
+ writer's `revision` pin. An increment with neither is refused.
426
+
427
+ An Entity's invariants (`Entity.invariant`) are the writer's to judge, over the
428
+ row its statement writes; the guarded writer passes them through and speaks
429
+ first. They are not rules, and are never one of a command's alternatives:
430
+ `Update: [isOwner, isManager]` says who may, and an invariant says what every
431
+ row must hold whoever writes it, so being allowed does not make a row valid and
432
+ a valid row does not make anyone allowed. `Invalid` reaches only someone the
433
+ rules let write the row. An invariant that reads the row before (a transition
434
+ invariant) is the same: the writer's, after the rules. An invariant that reads a member with
435
+ a Read rule is enforced all the same, but its refusal names no invariant and no path ("The row
436
+ would be invalid"), since naming it would say what that member holds.
437
+
438
+ Over a writer with a ledger (`foldkit-remote-drizzle`'s `writer(binding, {
439
+ ledger })`), a retry of an operation that landed is answered from the ledger,
440
+ before any rule: it was decided when it landed, and deciding it again over a row
441
+ that has moved since could refuse a write that happened. A new operation is
442
+ decided as any write is.
443
+
391
444
  The binding must have a `visible` rule, which is how the writer reads a row
392
445
  as its writer may see it; the writer refuses one without. That the rule is
393
446
  `GuardDrizzle.visible`'s is what `GuardServer.validate` checks of the
@@ -696,6 +749,48 @@ has a `RequestedArchive` with the todo's `id`.
696
749
  - It is the agent's gate, not the check: the Message's mutation is checked on
697
750
  the server, under the same principal.
698
751
 
752
+ ## Uploads
753
+
754
+ `foldkit-media`'s upload routes ask one question of an `UploadPolicy`
755
+ before reading a byte: may this request upload (`Upload`), or have an image
756
+ named by URL described (`DescribeUrl`)? `foldkit-guard/media` answers it with
757
+ principal guards, for who your resolver says is asking:
758
+
759
+ ```ts
760
+ import { Layer } from 'effect'
761
+ import { uploadLayer, uploadsKeyValueStore } from 'foldkit-media/server'
762
+ import { GuardMedia } from 'foldkit-guard/media'
763
+
764
+ const uploads = uploadLayer().pipe(
765
+ Layer.provide(
766
+ Layer.mergeAll(
767
+ uploadsKeyValueStore(),
768
+ inspector,
769
+ GuardMedia.uploadPolicy(Policy, { resolve, Upload: [G.isAdmin], DescribeUrl: [G.isAdmin] }),
770
+ ),
771
+ ),
772
+ )
773
+ ```
774
+
775
+ `resolve` is the resolver your Remote server is given:
776
+ `(request: Request) => Effect<Option<User>, E, R>`, which
777
+ `AuthServer.resolver` from `foldkit-auth/server` is. `inspector` is
778
+ `foldkit-media`'s `Inspector` for where you run (`inspectorSharp()`,
779
+ `inspectorImages(env.IMAGES)`).
780
+
781
+ - Only principal guards: no row exists before an upload, so a row guard is a
782
+ type error. A route admits when any one of its guards allows, and a route
783
+ given no guards admits nobody.
784
+ - The resolver gets the request's URL, method and headers and never its
785
+ body, so the route still reads no byte before the policy answers.
786
+ - A resolver that fails (an untrusted origin, a session that ended) is a
787
+ `401`; a principal the guards refuse is a `403`. Either says only its kind:
788
+ an `explain` sentence stays on the server.
789
+ - `Policy` must need no service; give it what its bodies need with
790
+ `Policy.provide`, as the other seams take it.
791
+ - Beside a deployment's secret for scripts:
792
+ `uploadPolicyAny(uploadPolicyBearer(secret), GuardMedia.uploadPolicy(…))`.
793
+
699
794
  ## Limits
700
795
 
701
796
  - **No rule runs on the client.** `may` is the server's answer for the row as
@@ -711,10 +806,16 @@ has a `RequestedArchive` with the todo's `id`.
711
806
  - **A Sync document is one audience.** Per-member or per-row secrecy within
712
807
  one is not something a replicated log offers: `GuardSync.document` refuses
713
808
  it where it is declared.
714
- - **A write's check and the write are two statements.** The row is read and
715
- its rules decided, then it is written; a change of owner landing between
716
- them is not seen. A write that `expect`s a revision is refused once the row
717
- moved; one that does not takes that window.
809
+ - **A `revision` pins one row, against the writes that move it.** A write
810
+ rule reads the principal and the row, so pinning the row's revision makes
811
+ the check and the write one. Only the declared writes that pin or `expect`
812
+ it move it on: a handler (`RemoteServer.mutation`), raw SQL or a migration
813
+ that changes the row without moving it is not seen, unless the table carries
814
+ `foldkit-remote-drizzle`'s `revisionTrigger`, which has the database move it
815
+ on every update that does not. Sync's `applyEdits` keeps one revision for two
816
+ changes in one operation, so a table Sync writes takes no trigger, and the
817
+ pin does not see that second change. A writer given no `revision` does not
818
+ see a change landing between its check and its write.
718
819
  - **Sync's `admit` reads the table, which lags the journal.** An edit lands
719
820
  in the table when its exchange settles, so an edit admitted before another
720
821
  lands is judged against the row as it was: a concurrent change of owner
@@ -1 +1 @@
1
- {"version":3,"file":"attach-BVG6LsFf.d.mts","names":["MemberKeys","_$__attach_js0.Attach","_$__attach_js0.AnyRule","_$__attach_js0.Inherit","_$__attach_js0.All","_$__attach_js0.Redact","_$__attach_js0.Explain","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;KAG1B,WAAW,SAAS,eAAe;;UAGvB;WACN;WACA;WACA,KAAK;WACL,SAAS,SAAS,eAAe;WACjC,WAAW,SAAS,eAAe;WACnC,QAAQ,cAAc;;cA4PpB,WAAQ,QAAY,cAAY,OAAO,OAAO"}
1
+ {"version":3,"file":"attach-BVG6LsFf.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":";;;KAWY;WACG;;WACA;;WACA;WAAsB,OAAO,cAAc;;;;WAE3C;WAA0B;;WAC1B;WAAsB,YAAY,cAAc;;WAChD;WAAqB,YAAY,cAAc;;;cAMxD,MAAG,YAAgB,cAAc,eAAa;;cAY9C,KAAE,YAAgB,cAAc,eAAa;cAWtC;;aAnCQ;;;aACA;;;;;;;;;EA8CN,QAAA,WAAA,WAAS,QACZ,SAAS,0BAAwB,OAClC,SAAS,0BAAwB,UAC9B;;;;;;;EAoBW,YAAA,WAAA,WAAS,OAAS,wBAAsB;;EAiB1C,UAAA,WAAA,cAAY;;;UAelB;WACN;WACA,WAAW;WACX,MAAM;;;UAwDA;WACN,WAAW;WACX,MAAM;;;;;;;;;;cC/JJ,WAAS,OAAA;;;;;;;;;KASV,mBAAmB,UAAU;KAEpCA,aAAW,UAAU,oBAAoB,oBAAoB;cAerD;;;;;;EAMX,SAAM,UAAA,WAAA,QAAA,mBAAA;;;;;;;;;;;;;;;;;;EAON,MAAG,KAAQ,WAAS,mCAAqC;;;;;;EAQzD,SAAM,KACC,WAAS,mCACqB,mBAClC,OAAO;;EAGV,SAAS,UAAU,WAAS,KAAO,WAAS,SAAW,GAAC,QAAUA,aAAW;;EAI7E,UAAU,UAAU,WAAS,KACtB,WAAS,SACL,GAAC,gBACM,yBAAuB;;;;;;;;;;;EAczC,QAAK,QAAW;IACd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AG;;aAE5D,SAAS,UAAU,QAAQ,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;;cA4PpB,WAAQ,QAAY,cAAY,OAAO,OAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"attach-BZyVvs7H.mjs","names":[],"sources":["../src/attach.ts"],"sourcesContent":["/**\n * Attaching a guard set's guards to an Entity, per surface and interaction,\n * as metadata only `foldkit-guard` reads. See `guard-DESIGN.md` §3.2.\n */\nimport { Match, Option, type Schema } from 'effect'\nimport { Entity, Query, ReadFilter, type AnyEntity } from 'foldkit-entity'\nimport { Metadata } from 'foldkit-metadata'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\ndeclare const InteractionBrand: unique symbol\n\n/** An interaction the application names, used as a computed key: `[Archive.key]`. */\nexport type InteractionKey<Name extends string = string> = Name & {\n readonly [InteractionBrand]: Name\n}\n\nexport interface Interaction<Name extends string> {\n readonly name: Name\n readonly key: InteractionKey<Name>\n}\n\n/** The interactions every row has, and the ones a relation member has. */\nconst builtIn = ['Read', 'Create', 'Update', 'Delete', 'Write', 'Link', 'Unlink'] as const\n\nexport const Interaction = {\n /** An interaction beyond Read, Create, Update and Delete, such as `Archive`. */\n make: <const Name extends string>(name: Name): Interaction<Name> => {\n if ((builtIn as ReadonlyArray<string>).includes(name)) {\n throw new Error(`[foldkit-guard] Interaction.make: \"${name}\" is an interaction already`)\n }\n return Object.freeze({ name, key: name as InteractionKey<Name> })\n },\n}\n\n/** Every guard of `Rules` must allow, as one guard: `Guards.all(signedIn, isOwner)`. */\nexport interface All<Rules> {\n readonly _tag: 'All'\n readonly rules: ReadonlyArray<Rules>\n}\n\n/** This row's Read is the Read of the row its `one` relation points at. */\nexport interface Inherit<Relation extends string> {\n readonly _tag: 'Inherit'\n readonly relation: Relation\n}\n\n/** What a member hidden by its Read guards reads as instead of its value. */\nexport interface Redact<A> {\n readonly _tag: 'Redact'\n readonly value: A\n}\n\n/** A refused write's sentence, for the application's own users. */\nexport interface Explain {\n readonly _tag: 'Explain'\n readonly reason: string\n}\n\n/**\n * What a refusal looks like. The defaults need no constructor: a row Read\n * answers `NotFound`, a member or relation Read `Omit`, a write `Forbidden`.\n */\nexport type Deny =\n | { readonly _tag: 'NotFound' }\n | { readonly _tag: 'Omit' }\n | Redact<unknown>\n | { readonly _tag: 'Forbidden' }\n | Explain\n\n/** A surface's guards with a refusal other than its default. */\nexport interface On<Rules, D extends Deny> {\n readonly _tag: 'On'\n readonly rules: ReadonlyArray<Rules>\n readonly deny: D\n}\n\n/** Anything a surface's list may hold, of any guard set. */\nexport type AnyRule =\n PrincipalGuard<any, string> | RowGuard<any, AnyEntity, string> | All<any> | Inherit<string>\n\n/**\n * What a surface of the Entity named `Name` accepts from the guard set `Set`:\n * its principal guards, its row guards over that Entity, and conjunctions of\n * both. A row guard over another Entity, or a guard of another set, is refused.\n */\nexport type RuleFor<User, Set extends string, Name extends string> =\n | PrincipalGuard<User, Set>\n | RowGuard<User, Entity<Name, any, any, any>, Set>\n | All<RuleFor<User, Set, Name>>\n\ntype Slot<Rule, D extends Deny> = ReadonlyArray<Rule> | On<Rule, D>\n\ntype WriteSlot<Rule> = Slot<Rule, Explain>\n\ntype OneRelations<E extends AnyEntity> = {\n [K in keyof E['relations']]: E['relations'][K] extends { readonly cardinality: 'one' } ? K : never\n}[keyof E['relations']] &\n string\n\ntype MemberKeys<E extends AnyEntity> = (keyof E['fields'] | keyof E['derived']) & string\n\ntype TypeOf<E extends AnyEntity, K extends keyof E['members']> = E['members'][K]['schema']['Type']\n\n/** What `Guards.attach` takes for the Entity `E`, every key checked against it. */\nexport type Attach<User, Set extends string, E extends AnyEntity> = {\n readonly row?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']> | Inherit<OneRelations<E>>>\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Delete?: WriteSlot<RuleFor<User, Set, E['name']>>\n /** The same guards on Create, Update and Delete. */\n readonly Write?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /**\n * The row's interactions the application named, by key:\n * `{ [Archive.key]: [G.isAdmin] }`. Apart from `row`, whose `Read` may\n * inherit: a literal with a computed key is typed as an index signature,\n * which `Read`'s rules would have to fit too.\n */\n readonly interactions?: {\n readonly [K: InteractionKey]: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /** Narrow a field or derived member: a member is reachable only if its row is. */\n readonly members?: {\n readonly [K in MemberKeys<E>]?: {\n readonly Read?: Slot<RuleFor<User, Set, E['name']>, Redact<TypeOf<E, K>>>\n /** When absent, `Update`'s guards govern setting the member on creation too. */\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n readonly relations?: {\n readonly [K in keyof E['relations']]?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n readonly Link?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Unlink?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n /** ANDed with every surface's guards, and never out-voted by them. */\n readonly always?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n}\n\n/** One surface's guards as attached: a disjunction, and a refusal if one was chosen. */\nexport interface Surface {\n readonly rules: ReadonlyArray<AnyRule>\n readonly deny: Option.Option<Deny>\n}\n\ntype Surfaces = Readonly<Record<string, Surface>>\n\n/** An Entity's guards, every attachment merged. */\nexport interface Attachment {\n readonly set: string\n readonly unguarded: 'allow' | 'deny'\n readonly row: Surfaces\n readonly members: Readonly<Record<string, Surfaces>>\n readonly relations: Readonly<Record<string, Surfaces>>\n readonly always: ReadonlyArray<AnyRule>\n}\n\n/** Which surface a rule is asked about. */\ntype Target =\n | { readonly _tag: 'Row'; readonly interaction: string }\n | { readonly _tag: 'Member'; readonly member: string; readonly interaction: string }\n | { readonly _tag: 'Relation'; readonly relation: string; readonly interaction: string }\n\nconst record = <A>(): Record<string, A> => Object.create(null)\n\nconst appendSurface = (into: Record<string, Surface>, interaction: string, added: Surface) => {\n const before = into[interaction]\n into[interaction] =\n before === undefined\n ? added\n : {\n rules: [...before.rules, ...added.rules],\n deny: Option.orElse(added.deny, () => before.deny),\n }\n}\n\nconst appendSurfaces = (into: Record<string, Surface>, added: Surfaces) => {\n for (const [interaction, surface] of Object.entries(added)) {\n appendSurface(into, interaction, surface)\n }\n}\n\nconst freezeSurfaces = (surfaces: Record<string, Surfaces>) => {\n for (const key of Object.keys(surfaces)) Object.freeze(surfaces[key])\n return Object.freeze(surfaces)\n}\n\n/** Later attachments append to each surface's disjunction and replace its refusal. */\nconst mergeAttachments = (attachments: ReadonlyArray<Attachment>): Attachment => {\n const row = record<Surface>()\n const members = record<Record<string, Surface>>()\n const relations = record<Record<string, Surface>>()\n const always: Array<AnyRule> = []\n for (const attachment of attachments) {\n appendSurfaces(row, attachment.row)\n for (const [key, surfaces] of Object.entries(attachment.members)) {\n appendSurfaces((members[key] ??= record()), surfaces)\n }\n for (const [key, surfaces] of Object.entries(attachment.relations)) {\n appendSurfaces((relations[key] ??= record()), surfaces)\n }\n always.push(...attachment.always)\n }\n const { set, unguarded } = attachments[0]!\n return Object.freeze({\n set,\n unguarded,\n row: Object.freeze(row),\n members: freezeSurfaces(members),\n relations: freezeSurfaces(relations),\n always: Object.freeze(always),\n })\n}\n\nconst showRule = (rule: AnyRule): string =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => name,\n RowGuard: ({ name }) => name,\n All: ({ rules }) => (rules.length === 0 ? 'anyone' : `all(${rules.map(showRule).join(', ')})`),\n Inherit: ({ relation }) => `inherit(${relation})`,\n })\n\nconst showDeny = (deny: Deny): string =>\n Match.valueTags(deny, {\n NotFound: () => 'not_found',\n Omit: () => 'omit',\n Redact: ({ value }) => `redact(${JSON.stringify(value)})`,\n Forbidden: () => 'forbidden',\n Explain: ({ reason }) => `explain(${JSON.stringify(reason)})`,\n })\n\nconst notFound: Deny = Object.freeze({ _tag: 'NotFound' })\nconst omit: Deny = Object.freeze({ _tag: 'Omit' })\nconst forbidden: Deny = Object.freeze({ _tag: 'Forbidden' })\n\n/** The refusal a surface takes when none was chosen. */\nexport const defaultDeny = (target: Target): Deny =>\n target.interaction === 'Read'\n ? Match.valueTags(target, { Row: () => notFound, Member: () => omit, Relation: () => omit })\n : forbidden\n\n/** The guards a surface carries; `none` where it falls to the set's `unguarded`. */\nexport const surfaceOf = (attachment: Attachment, target: Target): Option.Option<Surface> =>\n Match.valueTags(target, {\n Row: ({ interaction }) => Option.fromUndefinedOr(attachment.row[interaction]),\n Member: ({ member, interaction }) => {\n const surfaces = attachment.members[member]\n if (surfaces === undefined) return Option.none()\n const own = surfaces[interaction]\n // A member a caller may not change is rarely one it may set freely on creation.\n return Option.fromUndefinedOr(\n own === undefined && interaction === 'Create' ? surfaces['Update'] : own,\n )\n },\n Relation: ({ relation, interaction }) =>\n Option.fromUndefinedOr(attachment.relations[relation]?.[interaction]),\n })\n\n/** Whether who may read the rows depends on who is asking: a row Read rule, or `always`. */\n/** `Guards.anyone`: a conjunction of nothing, which every principal passes. */\nexport const isAnyone = (rule: AnyRule): boolean => rule._tag === 'All' && rule.rules.length === 0\n\n/** Whether a surface's rules restrict who passes: not when one of them is `anyone`. */\nexport const restricts = (surface: Option.Option<Surface>): boolean =>\n Option.exists(surface, ({ rules }) => !rules.some(isAnyone))\n\nexport const readRowsRuled = (attachment: Attachment): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Row', interaction: 'Read' })) ||\n attachment.always.some(rule => !isAnyone(rule))\n\n/** Whether `member`, a field or a relation, has a Read rule of its own. */\nexport const readRuled = (attachment: Attachment, member: string): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Member', member, interaction: 'Read' })) ||\n restricts(surfaceOf(attachment, { _tag: 'Relation', relation: member, interaction: 'Read' }))\n\nconst key = Metadata.key<Attachment>('foldkit-guard/attachment', {\n merge: attachments => [mergeAttachments(attachments)],\n summarize: attachment =>\n linesOf(attachment)\n .map(([where, rule]) => `${where}: ${rule}`)\n .join('; '),\n})\n\n/** The rows of an attachment's matrix: each surface it decides, and how. */\nconst linesOf = (attachment: Attachment): ReadonlyArray<readonly [string, string]> => {\n const open = attachment.unguarded === 'allow' ? 'open' : 'closed'\n const show = (target: Target) =>\n Option.match(surfaceOf(attachment, target), {\n onNone: () => open,\n onSome: ({ rules, deny }) =>\n // An empty disjunction allows no one.\n `${rules.length === 0 ? 'nobody' : rules.map(showRule).join(' | ')} → ${showDeny(Option.getOrElse(deny, () => defaultDeny(target)))}`,\n })\n const interactions = [\n 'Read',\n 'Create',\n 'Update',\n 'Delete',\n ...Object.keys(attachment.row).filter(interaction => !builtIn.includes(interaction as never)),\n ]\n return [\n ...(attachment.always.length > 0\n ? [['always', attachment.always.map(showRule).join(' & ')] as const]\n : []),\n ...interactions.map(interaction => [interaction, show({ _tag: 'Row', interaction })] as const),\n ...Object.keys(attachment.members).flatMap(member =>\n ['Read', 'Create', 'Update'].flatMap(interaction => {\n const target: Target = { _tag: 'Member', member, interaction }\n return Option.isSome(surfaceOf(attachment, target))\n ? [[`${member}.${interaction}`, show(target)] as const]\n : []\n }),\n ),\n ...Object.entries(attachment.relations).flatMap(([relation, surfaces]) =>\n Object.keys(surfaces).map(\n interaction =>\n [\n `${relation}.${interaction}`,\n show({ _tag: 'Relation', relation, interaction }),\n ] as const,\n ),\n ),\n ]\n}\n\nconst isOn = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): slot is On<AnyRule, Deny> =>\n !Array.isArray(slot)\n\nconst surfaceFrom = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): Surface =>\n isOn(slot)\n ? { rules: slot.rules, deny: Option.some(slot.deny) }\n : { rules: Object.freeze([...slot]), deny: Option.none() }\n\n/** Throws for a row guard over another Entity that shares the target's name. */\nconst checkRules = (\n set: string,\n entity: AnyEntity,\n where: string,\n rules: ReadonlyArray<AnyRule>,\n): void => {\n for (const rule of rules) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n if (!Entity.same(guard.entity, entity)) {\n throw new Error(\n `[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, a guard over another Entity named ${entity.name}`,\n )\n }\n },\n All: ({ rules }) => checkRules(set, entity, where, rules),\n Inherit: () => {},\n })\n }\n}\n\nconst surfacesFrom = (\n set: string,\n entity: AnyEntity,\n where: string,\n slots: Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>>,\n): Surfaces => {\n const surfaces = record<Surface>()\n // `Write` goes first, whatever order the keys were written in: beside it, a\n // slot of its own adds rules to it and its refusal replaces Write's.\n const ordered = Object.entries(slots).sort(\n ([left], [right]) => Number(right === 'Write') - Number(left === 'Write'),\n )\n for (const [interaction, slot] of ordered) {\n if (slot === undefined) continue\n const added = surfaceFrom(slot)\n checkRules(set, entity, `${where}${interaction}`, added.rules)\n // Write is shorthand, so it is stored as the three it stands for.\n for (const each of interaction === 'Write' ? ['Create', 'Update', 'Delete'] : [interaction]) {\n appendSurface(surfaces, each, added)\n }\n }\n return Object.freeze(surfaces)\n}\n\nconst nested = (\n set: string,\n entity: AnyEntity,\n given: Readonly<\n Record<\n string,\n Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>> | undefined\n >\n >,\n): Readonly<Record<string, Surfaces>> => {\n const surfaces = record<Surfaces>()\n for (const [member, slots] of Object.entries(given)) {\n if (slots !== undefined) surfaces[member] = surfacesFrom(set, entity, `${member}.`, slots)\n }\n return Object.freeze(surfaces)\n}\n\n/** A row guard's own fields, and the relation an inherited Read follows. */\nconst membersRead = (rule: AnyRule): ReadonlyArray<string> =>\n Match.valueTags(rule, {\n PrincipalGuard: () => [],\n RowGuard: ({ query }) => Query.dependencies(query).predicate.map(field => field.key),\n All: ({ rules }) => rules.flatMap(membersRead),\n Inherit: ({ relation }) => [relation],\n })\n\nexport const attached = (entity: AnyEntity): Option.Option<Attachment> =>\n Option.fromUndefinedOr(key.get(entity.metadata)[0])\n\nexport const Attaching = {\n /**\n * Attaches guards to an Entity, per surface and interaction. A surface's list\n * is a disjunction; `always` is ANDed after it. Attaching twice appends to a\n * surface's list and replaces its refusal.\n */\n attach:\n <Name extends string, User, E extends AnyEntity>(\n G: {\n readonly name: Name\n readonly schema: Schema.Codec<User, unknown>\n readonly unguarded: 'allow' | 'deny'\n },\n config: Attach<NoInfer<User>, NoInfer<Name>, E>,\n ) =>\n (entity: E): E => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== G.name) {\n throw new Error(\n `[foldkit-guard] ${G.name}.attach: ${entity.name} carries the guards of ${set} already`,\n )\n }\n })\n const always = config.always ?? []\n checkRules(G.name, entity, 'always', always)\n const attachment: Attachment = Object.freeze({\n set: G.name,\n unguarded: G.unguarded,\n // A named interaction is the row's, as the matrix and the decisions read it.\n row: surfacesFrom(G.name, entity, '', { ...config.row, ...config.interactions }),\n members: nested(G.name, entity, config.members ?? {}),\n relations: nested(G.name, entity, config.relations ?? {}),\n always: Object.freeze([...always]),\n })\n // What the row's Read rules read, so a client placing rows knows it cannot judge a change to them.\n const filtered = [\n ...new Set(\n [...(attachment.row['Read']?.rules ?? []), ...attachment.always].flatMap(membersRead),\n ),\n ]\n return entity.pipe(\n Entity.annotate(Metadata.combine([key.of(attachment), ReadFilter.of(filtered)])),\n )\n },\n\n /** The guards attached to `entity`, every attachment merged. */\n attached,\n\n /** Every rule must allow, as one rule. Principal and row guards may mix. */\n all: <\n const Rules extends readonly [\n Exclude<AnyRule, Inherit<string>>,\n ...ReadonlyArray<Exclude<AnyRule, Inherit<string>>>,\n ],\n >(\n ...rules: Rules\n ): All<Rules[number]> => Object.freeze({ _tag: 'All', rules: Object.freeze([...rules]) }),\n\n /**\n * A rule everyone passes, a visitor included: a conjunction of nothing.\n * For a surface that is public under a set whose `unguarded` is `'deny'`.\n */\n anyone: Object.freeze<All<never>>({ _tag: 'All', rules: Object.freeze([]) }),\n\n /** This row's Read is the Read of the row its `one` relation points at. */\n inherit: <const Relation extends string>(relation: Relation): Inherit<Relation> =>\n Object.freeze({ _tag: 'Inherit', relation }),\n\n /** A surface's guards with a refusal other than its default. */\n on: <const Rules extends ReadonlyArray<AnyRule>, D extends Redact<unknown> | Explain>(\n rules: Rules,\n deny: D,\n ): On<Rules[number], D> => Object.freeze({ _tag: 'On', rules: Object.freeze([...rules]), deny }),\n\n /** A hidden member reads as `value`, typed by the member's schema. */\n redact: <const A>(value: A): Redact<A> => Object.freeze({ _tag: 'Redact', value }),\n\n /** A refused write tells the caller `reason`. */\n explain: (reason: string): Explain => Object.freeze({ _tag: 'Explain', reason }),\n\n /**\n * The members a row interaction's guards read, `always` included: a change\n * to one can change whether a principal may. A relation an inherited Read\n * follows counts.\n */\n guardFields: (\n entity: AnyEntity,\n interaction: 'Read' | 'Create' | 'Update' | 'Delete' | InteractionKey,\n ): ReadonlyArray<string> =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => [\n ...new Set(\n [...(attachment.row[interaction]?.rules ?? []), ...attachment.always].flatMap(\n membersRead,\n ),\n ),\n ],\n }),\n\n /** Who may do what, one line per surface, for review and for a committed snapshot. */\n matrix: (entities: ReadonlyArray<AnyEntity>): string =>\n entities\n .flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [`${entity.name}: no guards`],\n onSome: attachment =>\n linesOf(attachment).map(([where, rule]) => `${entity.name}.${where}: ${rule}`),\n }),\n )\n .join('\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CAG7C,KACE,OACA,SACyB,OAAO,OAAO;EAAE,MAAM;EAAM,OAAO,OAAO,OAAO,CAAC,GAAG,KAAK,CAAC;EAAG;CAAK,CAAC;;CAG/F,SAAkB,UAAwB,OAAO,OAAO;EAAE,MAAM;EAAU;CAAM,CAAC;;CAGjF,UAAU,WAA4B,OAAO,OAAO;EAAE,MAAM;EAAW;CAAO,CAAC;;;;;;CAO/E,cACE,QACA,gBAEA,OAAO,MAAM,SAAS,MAAM,GAAG;EAC7B,cAAc,CAAC;EACf,SAAQ,eAAc,CACpB,GAAG,IAAI,IACL,CAAC,GAAI,WAAW,IAAI,YAAY,EAAE,SAAS,CAAC,GAAI,GAAG,WAAW,MAAM,CAAC,CAAC,QACpE,WACF,CACF,CACF;CACF,CAAC;;CAGH,SAAS,aACP,SACG,SAAQ,WACP,OAAO,MAAM,SAAS,MAAM,GAAG;EAC7B,cAAc,CAAC,GAAG,OAAO,KAAK,YAAY;EAC1C,SAAQ,eACN,QAAQ,UAAU,CAAC,CAAC,KAAK,CAAC,OAAO,UAAU,GAAG,OAAO,KAAK,GAAG,MAAM,IAAI,MAAM;CACjF,CAAC,CACH,CAAC,CACA,KAAK,IAAI;AAChB"}
1
+ {"version":3,"file":"attach-BZyVvs7H.mjs","names":[],"sources":["../src/attach.ts"],"sourcesContent":["/**\n * Attaching a guard set's guards to an Entity, per surface and interaction,\n * as metadata only `foldkit-guard` reads. See `guard-DESIGN.md` §3.2.\n */\nimport { Match, Option, type Schema } from 'effect'\nimport { Entity, Query, ReadFilter, type AnyEntity } from 'foldkit-entity'\nimport { Metadata } from 'foldkit-metadata'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\ndeclare const InteractionBrand: unique symbol\n\n/** An interaction the application names, used as a computed key: `[Archive.key]`. */\nexport type InteractionKey<Name extends string = string> = Name & {\n readonly [InteractionBrand]: Name\n}\n\nexport interface Interaction<Name extends string> {\n readonly name: Name\n readonly key: InteractionKey<Name>\n}\n\n/** The interactions every row has, and the ones a relation member has. */\nconst builtIn = ['Read', 'Create', 'Update', 'Delete', 'Write', 'Link', 'Unlink'] as const\n\nexport const Interaction = {\n /** An interaction beyond Read, Create, Update and Delete, such as `Archive`. */\n make: <const Name extends string>(name: Name): Interaction<Name> => {\n if ((builtIn as ReadonlyArray<string>).includes(name)) {\n throw new Error(`[foldkit-guard] Interaction.make: \"${name}\" is an interaction already`)\n }\n return Object.freeze({ name, key: name as InteractionKey<Name> })\n },\n}\n\n/** Every guard of `Rules` must allow, as one guard: `Guards.all(signedIn, isOwner)`. */\nexport interface All<Rules> {\n readonly _tag: 'All'\n readonly rules: ReadonlyArray<Rules>\n}\n\n/** This row's Read is the Read of the row its `one` relation points at. */\nexport interface Inherit<Relation extends string> {\n readonly _tag: 'Inherit'\n readonly relation: Relation\n}\n\n/** What a member hidden by its Read guards reads as instead of its value. */\nexport interface Redact<A> {\n readonly _tag: 'Redact'\n readonly value: A\n}\n\n/** A refused write's sentence, for the application's own users. */\nexport interface Explain {\n readonly _tag: 'Explain'\n readonly reason: string\n}\n\n/**\n * What a refusal looks like. The defaults need no constructor: a row Read\n * answers `NotFound`, a member or relation Read `Omit`, a write `Forbidden`.\n */\nexport type Deny =\n | { readonly _tag: 'NotFound' }\n | { readonly _tag: 'Omit' }\n | Redact<unknown>\n | { readonly _tag: 'Forbidden' }\n | Explain\n\n/** A surface's guards with a refusal other than its default. */\nexport interface On<Rules, D extends Deny> {\n readonly _tag: 'On'\n readonly rules: ReadonlyArray<Rules>\n readonly deny: D\n}\n\n/** Anything a surface's list may hold, of any guard set. */\nexport type AnyRule =\n | PrincipalGuard<any, string>\n | RowGuard<any, AnyEntity, string>\n | All<any>\n | Inherit<string>\n\n/**\n * What a surface of the Entity named `Name` accepts from the guard set `Set`:\n * its principal guards, its row guards over that Entity, and conjunctions of\n * both. A row guard over another Entity, or a guard of another set, is refused.\n */\nexport type RuleFor<User, Set extends string, Name extends string> =\n | PrincipalGuard<User, Set>\n | RowGuard<User, Entity<Name, any, any, any>, Set>\n | All<RuleFor<User, Set, Name>>\n\ntype Slot<Rule, D extends Deny> = ReadonlyArray<Rule> | On<Rule, D>\n\ntype WriteSlot<Rule> = Slot<Rule, Explain>\n\ntype OneRelations<E extends AnyEntity> = {\n [K in keyof E['relations']]: E['relations'][K] extends { readonly cardinality: 'one' } ? K : never\n}[keyof E['relations']] &\n string\n\ntype MemberKeys<E extends AnyEntity> = (keyof E['fields'] | keyof E['derived']) & string\n\ntype TypeOf<E extends AnyEntity, K extends keyof E['members']> = E['members'][K]['schema']['Type']\n\n/** What `Guards.attach` takes for the Entity `E`, every key checked against it. */\nexport type Attach<User, Set extends string, E extends AnyEntity> = {\n readonly row?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']> | Inherit<OneRelations<E>>>\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Delete?: WriteSlot<RuleFor<User, Set, E['name']>>\n /** The same guards on Create, Update and Delete. */\n readonly Write?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /**\n * The row's interactions the application named, by key:\n * `{ [Archive.key]: [G.isAdmin] }`. Apart from `row`, whose `Read` may\n * inherit: a literal with a computed key is typed as an index signature,\n * which `Read`'s rules would have to fit too.\n */\n readonly interactions?: {\n readonly [K: InteractionKey]: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /** Narrow a field or derived member: a member is reachable only if its row is. */\n readonly members?: {\n readonly [K in MemberKeys<E>]?: {\n readonly Read?: Slot<RuleFor<User, Set, E['name']>, Redact<TypeOf<E, K>>>\n /** When absent, `Update`'s guards govern setting the member on creation too. */\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n readonly relations?: {\n readonly [K in keyof E['relations']]?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n readonly Link?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Unlink?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n /** ANDed with every surface's guards, and never out-voted by them. */\n readonly always?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n}\n\n/** One surface's guards as attached: a disjunction, and a refusal if one was chosen. */\nexport interface Surface {\n readonly rules: ReadonlyArray<AnyRule>\n readonly deny: Option.Option<Deny>\n}\n\ntype Surfaces = Readonly<Record<string, Surface>>\n\n/** An Entity's guards, every attachment merged. */\nexport interface Attachment {\n readonly set: string\n readonly unguarded: 'allow' | 'deny'\n readonly row: Surfaces\n readonly members: Readonly<Record<string, Surfaces>>\n readonly relations: Readonly<Record<string, Surfaces>>\n readonly always: ReadonlyArray<AnyRule>\n}\n\n/** Which surface a rule is asked about. */\ntype Target =\n | { readonly _tag: 'Row'; readonly interaction: string }\n | { readonly _tag: 'Member'; readonly member: string; readonly interaction: string }\n | { readonly _tag: 'Relation'; readonly relation: string; readonly interaction: string }\n\nconst record = <A>(): Record<string, A> => Object.create(null)\n\nconst appendSurface = (into: Record<string, Surface>, interaction: string, added: Surface) => {\n const before = into[interaction]\n into[interaction] =\n before === undefined\n ? added\n : {\n rules: [...before.rules, ...added.rules],\n deny: Option.orElse(added.deny, () => before.deny),\n }\n}\n\nconst appendSurfaces = (into: Record<string, Surface>, added: Surfaces) => {\n for (const [interaction, surface] of Object.entries(added)) {\n appendSurface(into, interaction, surface)\n }\n}\n\nconst freezeSurfaces = (surfaces: Record<string, Surfaces>) => {\n for (const key of Object.keys(surfaces)) Object.freeze(surfaces[key])\n return Object.freeze(surfaces)\n}\n\n/** Later attachments append to each surface's disjunction and replace its refusal. */\nconst mergeAttachments = (attachments: ReadonlyArray<Attachment>): Attachment => {\n const row = record<Surface>()\n const members = record<Record<string, Surface>>()\n const relations = record<Record<string, Surface>>()\n const always: Array<AnyRule> = []\n for (const attachment of attachments) {\n appendSurfaces(row, attachment.row)\n for (const [key, surfaces] of Object.entries(attachment.members)) {\n appendSurfaces((members[key] ??= record()), surfaces)\n }\n for (const [key, surfaces] of Object.entries(attachment.relations)) {\n appendSurfaces((relations[key] ??= record()), surfaces)\n }\n always.push(...attachment.always)\n }\n const { set, unguarded } = attachments[0]!\n return Object.freeze({\n set,\n unguarded,\n row: Object.freeze(row),\n members: freezeSurfaces(members),\n relations: freezeSurfaces(relations),\n always: Object.freeze(always),\n })\n}\n\nconst showRule = (rule: AnyRule): string =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => name,\n RowGuard: ({ name }) => name,\n All: ({ rules }) => (rules.length === 0 ? 'anyone' : `all(${rules.map(showRule).join(', ')})`),\n Inherit: ({ relation }) => `inherit(${relation})`,\n })\n\nconst showDeny = (deny: Deny): string =>\n Match.valueTags(deny, {\n NotFound: () => 'not_found',\n Omit: () => 'omit',\n Redact: ({ value }) => `redact(${JSON.stringify(value)})`,\n Forbidden: () => 'forbidden',\n Explain: ({ reason }) => `explain(${JSON.stringify(reason)})`,\n })\n\nconst notFound: Deny = Object.freeze({ _tag: 'NotFound' })\nconst omit: Deny = Object.freeze({ _tag: 'Omit' })\nconst forbidden: Deny = Object.freeze({ _tag: 'Forbidden' })\n\n/** The refusal a surface takes when none was chosen. */\nexport const defaultDeny = (target: Target): Deny =>\n target.interaction === 'Read'\n ? Match.valueTags(target, { Row: () => notFound, Member: () => omit, Relation: () => omit })\n : forbidden\n\n/** The guards a surface carries; `none` where it falls to the set's `unguarded`. */\nexport const surfaceOf = (attachment: Attachment, target: Target): Option.Option<Surface> =>\n Match.valueTags(target, {\n Row: ({ interaction }) => Option.fromUndefinedOr(attachment.row[interaction]),\n Member: ({ member, interaction }) => {\n const surfaces = attachment.members[member]\n if (surfaces === undefined) return Option.none()\n const own = surfaces[interaction]\n // A member a caller may not change is rarely one it may set freely on creation.\n return Option.fromUndefinedOr(\n own === undefined && interaction === 'Create' ? surfaces['Update'] : own,\n )\n },\n Relation: ({ relation, interaction }) =>\n Option.fromUndefinedOr(attachment.relations[relation]?.[interaction]),\n })\n\n/** Whether who may read the rows depends on who is asking: a row Read rule, or `always`. */\n/** `Guards.anyone`: a conjunction of nothing, which every principal passes. */\nexport const isAnyone = (rule: AnyRule): boolean => rule._tag === 'All' && rule.rules.length === 0\n\n/** Whether a surface's rules restrict who passes: not when one of them is `anyone`. */\nexport const restricts = (surface: Option.Option<Surface>): boolean =>\n Option.exists(surface, ({ rules }) => !rules.some(isAnyone))\n\nexport const readRowsRuled = (attachment: Attachment): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Row', interaction: 'Read' })) ||\n attachment.always.some(rule => !isAnyone(rule))\n\n/** Whether `member`, a field or a relation, has a Read rule of its own. */\nexport const readRuled = (attachment: Attachment, member: string): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Member', member, interaction: 'Read' })) ||\n restricts(surfaceOf(attachment, { _tag: 'Relation', relation: member, interaction: 'Read' }))\n\nconst key = Metadata.key<Attachment>('foldkit-guard/attachment', {\n merge: attachments => [mergeAttachments(attachments)],\n summarize: attachment =>\n linesOf(attachment)\n .map(([where, rule]) => `${where}: ${rule}`)\n .join('; '),\n})\n\n/** The rows of an attachment's matrix: each surface it decides, and how. */\nconst linesOf = (attachment: Attachment): ReadonlyArray<readonly [string, string]> => {\n const open = attachment.unguarded === 'allow' ? 'open' : 'closed'\n const show = (target: Target) =>\n Option.match(surfaceOf(attachment, target), {\n onNone: () => open,\n onSome: ({ rules, deny }) =>\n // An empty disjunction allows no one.\n `${rules.length === 0 ? 'nobody' : rules.map(showRule).join(' | ')} → ${showDeny(Option.getOrElse(deny, () => defaultDeny(target)))}`,\n })\n const interactions = [\n 'Read',\n 'Create',\n 'Update',\n 'Delete',\n ...Object.keys(attachment.row).filter(interaction => !builtIn.includes(interaction as never)),\n ]\n return [\n ...(attachment.always.length > 0\n ? [['always', attachment.always.map(showRule).join(' & ')] as const]\n : []),\n ...interactions.map(interaction => [interaction, show({ _tag: 'Row', interaction })] as const),\n ...Object.keys(attachment.members).flatMap(member =>\n ['Read', 'Create', 'Update'].flatMap(interaction => {\n const target: Target = { _tag: 'Member', member, interaction }\n return Option.isSome(surfaceOf(attachment, target))\n ? [[`${member}.${interaction}`, show(target)] as const]\n : []\n }),\n ),\n ...Object.entries(attachment.relations).flatMap(([relation, surfaces]) =>\n Object.keys(surfaces).map(\n interaction =>\n [\n `${relation}.${interaction}`,\n show({ _tag: 'Relation', relation, interaction }),\n ] as const,\n ),\n ),\n ]\n}\n\nconst isOn = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): slot is On<AnyRule, Deny> =>\n !Array.isArray(slot)\n\nconst surfaceFrom = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): Surface =>\n isOn(slot)\n ? { rules: slot.rules, deny: Option.some(slot.deny) }\n : { rules: Object.freeze([...slot]), deny: Option.none() }\n\n/** Throws for a row guard over another Entity that shares the target's name. */\nconst checkRules = (\n set: string,\n entity: AnyEntity,\n where: string,\n rules: ReadonlyArray<AnyRule>,\n): void => {\n for (const rule of rules) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n if (!Entity.same(guard.entity, entity)) {\n throw new Error(\n `[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, a guard over another Entity named ${entity.name}`,\n )\n }\n },\n All: ({ rules }) => checkRules(set, entity, where, rules),\n Inherit: () => {},\n })\n }\n}\n\nconst surfacesFrom = (\n set: string,\n entity: AnyEntity,\n where: string,\n slots: Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>>,\n): Surfaces => {\n const surfaces = record<Surface>()\n // `Write` goes first, whatever order the keys were written in: beside it, a\n // slot of its own adds rules to it and its refusal replaces Write's.\n const ordered = Object.entries(slots).sort(\n ([left], [right]) => Number(right === 'Write') - Number(left === 'Write'),\n )\n for (const [interaction, slot] of ordered) {\n if (slot === undefined) continue\n const added = surfaceFrom(slot)\n checkRules(set, entity, `${where}${interaction}`, added.rules)\n // Write is shorthand, so it is stored as the three it stands for.\n for (const each of interaction === 'Write' ? ['Create', 'Update', 'Delete'] : [interaction]) {\n appendSurface(surfaces, each, added)\n }\n }\n return Object.freeze(surfaces)\n}\n\nconst nested = (\n set: string,\n entity: AnyEntity,\n given: Readonly<\n Record<\n string,\n Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>> | undefined\n >\n >,\n): Readonly<Record<string, Surfaces>> => {\n const surfaces = record<Surfaces>()\n for (const [member, slots] of Object.entries(given)) {\n if (slots !== undefined) surfaces[member] = surfacesFrom(set, entity, `${member}.`, slots)\n }\n return Object.freeze(surfaces)\n}\n\n/** A row guard's own fields, and the relation an inherited Read follows. */\nconst membersRead = (rule: AnyRule): ReadonlyArray<string> =>\n Match.valueTags(rule, {\n PrincipalGuard: () => [],\n RowGuard: ({ query }) => Query.dependencies(query).predicate.map(field => field.key),\n All: ({ rules }) => rules.flatMap(membersRead),\n Inherit: ({ relation }) => [relation],\n })\n\nexport const attached = (entity: AnyEntity): Option.Option<Attachment> =>\n Option.fromUndefinedOr(key.get(entity.metadata)[0])\n\nexport const Attaching = {\n /**\n * Attaches guards to an Entity, per surface and interaction. A surface's list\n * is a disjunction; `always` is ANDed after it. Attaching twice appends to a\n * surface's list and replaces its refusal.\n */\n attach:\n <Name extends string, User, E extends AnyEntity>(\n G: {\n readonly name: Name\n readonly schema: Schema.Codec<User, unknown>\n readonly unguarded: 'allow' | 'deny'\n },\n config: Attach<NoInfer<User>, NoInfer<Name>, E>,\n ) =>\n (entity: E): E => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== G.name) {\n throw new Error(\n `[foldkit-guard] ${G.name}.attach: ${entity.name} carries the guards of ${set} already`,\n )\n }\n })\n const always = config.always ?? []\n checkRules(G.name, entity, 'always', always)\n const attachment: Attachment = Object.freeze({\n set: G.name,\n unguarded: G.unguarded,\n // A named interaction is the row's, as the matrix and the decisions read it.\n row: surfacesFrom(G.name, entity, '', { ...config.row, ...config.interactions }),\n members: nested(G.name, entity, config.members ?? {}),\n relations: nested(G.name, entity, config.relations ?? {}),\n always: Object.freeze([...always]),\n })\n // What the row's Read rules read, so a client placing rows knows it cannot judge a change to them.\n const filtered = [\n ...new Set(\n [...(attachment.row['Read']?.rules ?? []), ...attachment.always].flatMap(membersRead),\n ),\n ]\n return entity.pipe(\n Entity.annotate(Metadata.combine([key.of(attachment), ReadFilter.of(filtered)])),\n )\n },\n\n /** The guards attached to `entity`, every attachment merged. */\n attached,\n\n /** Every rule must allow, as one rule. Principal and row guards may mix. */\n all: <\n const Rules extends readonly [\n Exclude<AnyRule, Inherit<string>>,\n ...ReadonlyArray<Exclude<AnyRule, Inherit<string>>>,\n ],\n >(\n ...rules: Rules\n ): All<Rules[number]> => Object.freeze({ _tag: 'All', rules: Object.freeze([...rules]) }),\n\n /**\n * A rule everyone passes, a visitor included: a conjunction of nothing.\n * For a surface that is public under a set whose `unguarded` is `'deny'`.\n */\n anyone: Object.freeze<All<never>>({ _tag: 'All', rules: Object.freeze([]) }),\n\n /** This row's Read is the Read of the row its `one` relation points at. */\n inherit: <const Relation extends string>(relation: Relation): Inherit<Relation> =>\n Object.freeze({ _tag: 'Inherit', relation }),\n\n /** A surface's guards with a refusal other than its default. */\n on: <const Rules extends ReadonlyArray<AnyRule>, D extends Redact<unknown> | Explain>(\n rules: Rules,\n deny: D,\n ): On<Rules[number], D> => Object.freeze({ _tag: 'On', rules: Object.freeze([...rules]), deny }),\n\n /** A hidden member reads as `value`, typed by the member's schema. */\n redact: <const A>(value: A): Redact<A> => Object.freeze({ _tag: 'Redact', value }),\n\n /** A refused write tells the caller `reason`. */\n explain: (reason: string): Explain => Object.freeze({ _tag: 'Explain', reason }),\n\n /**\n * The members a row interaction's guards read, `always` included: a change\n * to one can change whether a principal may. A relation an inherited Read\n * follows counts.\n */\n guardFields: (\n entity: AnyEntity,\n interaction: 'Read' | 'Create' | 'Update' | 'Delete' | InteractionKey,\n ): ReadonlyArray<string> =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => [\n ...new Set(\n [...(attachment.row[interaction]?.rules ?? []), ...attachment.always].flatMap(\n membersRead,\n ),\n ),\n ],\n }),\n\n /** Who may do what, one line per surface, for review and for a committed snapshot. */\n matrix: (entities: ReadonlyArray<AnyEntity>): string =>\n entities\n .flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [`${entity.name}: no guards`],\n onSome: attachment =>\n linesOf(attachment).map(([where, rule]) => `${entity.name}.${where}: ${rule}`),\n }),\n )\n .join('\\n'),\n}\n"],"mappings":";;;;;;;;;AAsBA,MAAM,UAAU;CAAC;CAAQ;CAAU;CAAU;CAAU;CAAS;CAAQ;AAAQ;AAEhF,MAAa,cAAc;;AAEzB,OAAkC,SAAkC;CAClE,IAAK,QAAkC,SAAS,IAAI,GAClD,MAAM,IAAI,MAAM,sCAAsC,KAAK,4BAA4B;CAEzF,OAAO,OAAO,OAAO;EAAE;EAAM,KAAK;CAA6B,CAAC;AAClE,EACF;AAyIA,MAAM,eAAqC,OAAO,OAAO,IAAI;AAE7D,MAAM,iBAAiB,MAA+B,aAAqB,UAAmB;CAC5F,MAAM,SAAS,KAAK;CACpB,KAAK,eACH,WAAW,KAAA,IACP,QACA;EACE,OAAO,CAAC,GAAG,OAAO,OAAO,GAAG,MAAM,KAAK;EACvC,MAAM,OAAO,OAAO,MAAM,YAAY,OAAO,IAAI;CACnD;AACR;AAEA,MAAM,kBAAkB,MAA+B,UAAoB;CACzE,KAAK,MAAM,CAAC,aAAa,YAAY,OAAO,QAAQ,KAAK,GACvD,cAAc,MAAM,aAAa,OAAO;AAE5C;AAEA,MAAM,kBAAkB,aAAuC;CAC7D,KAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,OAAO,SAAS,IAAI;CACpE,OAAO,OAAO,OAAO,QAAQ;AAC/B;;AAGA,MAAM,oBAAoB,gBAAuD;CAC/E,MAAM,MAAM,OAAgB;CAC5B,MAAM,UAAU,OAAgC;CAChD,MAAM,YAAY,OAAgC;CAClD,MAAM,SAAyB,CAAC;CAChC,KAAK,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CAGF;;CAGA,MAME,GAAG,UACoB,OAAO,OAAO;EAAE,MAAM;EAAO,OAAO,OAAO,OAAO,CAAC,GAAG,KAAK,CAAC;CAAE,CAAC;;;;;CAMxF,QAAQ,OAAO,OAAmB;EAAE,MAAM;EAAO,OAAO,OAAO,OAAO,CAAC,CAAC;CAAE,CAAC;;CAG3E,UAAyC,aACvC,OAAO,OAAO;EAAE,MAAM;EAAW;CAAS,CAAC;;CAG7C,KACE,OACA,SACyB,OAAO,OAAO;EAAE,MAAM;EAAM,OAAO,OAAO,OAAO,CAAC,GAAG,KAAK,CAAC;EAAG;CAAK,CAAC;;CAG/F,SAAkB,UAAwB,OAAO,OAAO;EAAE,MAAM;EAAU;CAAM,CAAC;;CAGjF,UAAU,WAA4B,OAAO,OAAO;EAAE,MAAM;EAAW;CAAO,CAAC;;;;;;CAO/E,cACE,QACA,gBAEA,OAAO,MAAM,SAAS,MAAM,GAAG;EAC7B,cAAc,CAAC;EACf,SAAQ,eAAc,CACpB,GAAG,IAAI,IACL,CAAC,GAAI,WAAW,IAAI,YAAY,EAAE,SAAS,CAAC,GAAI,GAAG,WAAW,MAAM,CAAC,CAAC,QACpE,WACF,CACF,CACF;CACF,CAAC;;CAGH,SAAS,aACP,SACG,SAAQ,WACP,OAAO,MAAM,SAAS,MAAM,GAAG;EAC7B,cAAc,CAAC,GAAG,OAAO,KAAK,YAAY;EAC1C,SAAQ,eACN,QAAQ,UAAU,CAAC,CAAC,KAAK,CAAC,OAAO,UAAU,GAAG,OAAO,KAAK,GAAG,MAAM,IAAI,MAAM;CACjF,CAAC,CACH,CAAC,CACA,KAAK,IAAI;AAChB"}
@@ -0,0 +1,30 @@
1
+ import { C as PrincipalGuard, S as Policy } from "./attach-BVG6LsFf.mjs";
2
+ import { Effect, Layer, Option } from "effect";
3
+ import { UploadPolicy } from "foldkit-media/server";
4
+ //#region src/media.d.ts
5
+ export interface UploadPolicyConfig<User, E, R> {
6
+ /**
7
+ * Who is asking, from a request holding the upload's URL, method and
8
+ * headers, and no body. A failure means it could not tell (an untrusted
9
+ * origin, a session that ended), answered `401`; none is a visitor.
10
+ */
11
+ readonly resolve: (request: Request) => Effect.Effect<Option.Option<User>, E, R>;
12
+ /** Who may upload: any one of these principal guards. Omitted, nobody. */
13
+ readonly Upload?: ReadonlyArray<PrincipalGuard<User>>;
14
+ /** Who may have an image named by URL described. Omitted, nobody. */
15
+ readonly DescribeUrl?: ReadonlyArray<PrincipalGuard<User>>;
16
+ }
17
+ /**
18
+ * An `UploadPolicy` deciding each route by `policy`'s principal guards for who
19
+ * `resolve` says is asking. A route admits when any one of its guards allows;
20
+ * a refusal's reason stays on the server, as every media refusal says only
21
+ * its kind. `policy` must need no service of its own: give it what its bodies
22
+ * need with `Policy.provide`, as the other seams take it.
23
+ */
24
+ declare const uploadPolicy: <User, E, R>(policy: Policy<User>, config: UploadPolicyConfig<User, E, R>) => Layer.Layer<UploadPolicy, never, R>;
25
+ export declare const GuardMedia: {
26
+ readonly uploadPolicy: typeof uploadPolicy;
27
+ };
28
+ //#endregion
29
+ export {};
30
+ //# sourceMappingURL=media.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media.d.mts","names":[],"sources":["../src/media.ts"],"mappings":";;;;iBAkBiB,mBAAmB,MAAM,GAAG;;;;;;WAMlC,UAAU,SAAS,YAAY,OAAO,OAAO,OAAO,OAAO,OAAO,GAAG;;WAErE,SAAS,cAAc,eAAe;;WAEtC,cAAc,cAAc,eAAe;;;;;;;;;cAyBhD,eAAgB,MAAM,GAAG,GAAC,QACtB,OAAO,OAAK,QACZ,mBAAmB,MAAM,GAAG,OACnC,MAAM,MAAM,qBAAqB;qBAqBvB;gCAAA"}
package/dist/media.mjs ADDED
@@ -0,0 +1,41 @@
1
+ import { Effect, Layer, Option } from "effect";
2
+ import { HttpServerRequest } from "effect/http";
3
+ import { UploadForbidden, UploadPolicy, UploadUnauthenticated } from "foldkit-media/server";
4
+ //#region src/media.ts
5
+ /**
6
+ * `foldkit-guard/media`: `foldkit-media`'s `UploadPolicy` decided by a guard
7
+ * set. Who is asking comes from the application's resolver, the one its
8
+ * Remote server is given (`AuthServer.resolver` from `foldkit-auth/server` has
9
+ * the shape), read from the request's headers alone, so the upload route
10
+ * still reads no byte before the policy has answered. Each route is decided by
11
+ * principal guards, since no row exists yet; a route not named is refused.
12
+ */
13
+ const urlOf = (request) => URL.canParse(request.originalUrl) ? Option.some(new URL(request.originalUrl)) : HttpServerRequest.toURL(request);
14
+ const headersOnly = (request) => Option.map(urlOf(request), (url) => new Request(url, {
15
+ method: request.method,
16
+ headers: request.headers
17
+ }));
18
+ /**
19
+ * An `UploadPolicy` deciding each route by `policy`'s principal guards for who
20
+ * `resolve` says is asking. A route admits when any one of its guards allows;
21
+ * a refusal's reason stays on the server, as every media refusal says only
22
+ * its kind. `policy` must need no service of its own: give it what its bodies
23
+ * need with `Policy.provide`, as the other seams take it.
24
+ */
25
+ const uploadPolicy = (policy, config) => Layer.effect(UploadPolicy, Effect.map(Effect.context(), (context) => ({ admit: (request, route) => Effect.gen(function* () {
26
+ const asked = yield* Option.match(headersOnly(request), {
27
+ onNone: () => Effect.fail(new UploadUnauthenticated({})),
28
+ onSome: Effect.succeed
29
+ });
30
+ const principal = yield* config.resolve(asked).pipe(Effect.mapError(() => new UploadUnauthenticated({})));
31
+ for (const guard of config[route] ?? []) if ((yield* policy.decide(guard, {
32
+ principal,
33
+ interaction: route
34
+ })) === true) return;
35
+ return yield* new UploadForbidden({});
36
+ }).pipe(Effect.provideContext(context)) })));
37
+ const GuardMedia = { uploadPolicy };
38
+ //#endregion
39
+ export { GuardMedia };
40
+
41
+ //# sourceMappingURL=media.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media.mjs","names":[],"sources":["../src/media.ts"],"sourcesContent":["/**\n * `foldkit-guard/media`: `foldkit-media`'s `UploadPolicy` decided by a guard\n * set. Who is asking comes from the application's resolver, the one its\n * Remote server is given (`AuthServer.resolver` from `foldkit-auth/server` has\n * the shape), read from the request's headers alone, so the upload route\n * still reads no byte before the policy has answered. Each route is decided by\n * principal guards, since no row exists yet; a route not named is refused.\n */\nimport { Effect, Layer, Option } from 'effect'\nimport { HttpServerRequest } from 'effect/http'\nimport {\n UploadForbidden,\n UploadPolicy,\n UploadUnauthenticated,\n type UploadRoute,\n} from 'foldkit-media/server'\nimport type { Policy, PrincipalGuard } from './index.js'\n\nexport interface UploadPolicyConfig<User, E, R> {\n /**\n * Who is asking, from a request holding the upload's URL, method and\n * headers, and no body. A failure means it could not tell (an untrusted\n * origin, a session that ended), answered `401`; none is a visitor.\n */\n readonly resolve: (request: Request) => Effect.Effect<Option.Option<User>, E, R>\n /** Who may upload: any one of these principal guards. Omitted, nobody. */\n readonly Upload?: ReadonlyArray<PrincipalGuard<User>>\n /** Who may have an image named by URL described. Omitted, nobody. */\n readonly DescribeUrl?: ReadonlyArray<PrincipalGuard<User>>\n}\n\n// The URL a request arrived at. On the web its `originalUrl` is whole; on a Node server it is a\n// path, and `toURL` rebuilds it from the `Host` header (else `http://localhost`).\nconst urlOf = (request: HttpServerRequest.HttpServerRequest): Option.Option<URL> =>\n URL.canParse(request.originalUrl)\n ? Option.some(new URL(request.originalUrl))\n : HttpServerRequest.toURL(request)\n\n// The URL, method and headers the resolver reads, and never the body: in a Worker,\n// `HttpServerRequest.toWeb` would hand back the request itself, stream and all.\nconst headersOnly = (request: HttpServerRequest.HttpServerRequest): Option.Option<Request> =>\n Option.map(\n urlOf(request),\n url => new Request(url, { method: request.method, headers: request.headers }),\n )\n\n/**\n * An `UploadPolicy` deciding each route by `policy`'s principal guards for who\n * `resolve` says is asking. A route admits when any one of its guards allows;\n * a refusal's reason stays on the server, as every media refusal says only\n * its kind. `policy` must need no service of its own: give it what its bodies\n * need with `Policy.provide`, as the other seams take it.\n */\nconst uploadPolicy = <User, E, R>(\n policy: Policy<User>,\n config: UploadPolicyConfig<User, E, R>,\n): Layer.Layer<UploadPolicy, never, R> =>\n Layer.effect(\n UploadPolicy,\n Effect.map(Effect.context<R>(), context => ({\n admit: (request: HttpServerRequest.HttpServerRequest, route: UploadRoute) =>\n Effect.gen(function* () {\n const asked = yield* Option.match(headersOnly(request), {\n onNone: () => Effect.fail(new UploadUnauthenticated({})),\n onSome: Effect.succeed,\n })\n const principal = yield* config\n .resolve(asked)\n .pipe(Effect.mapError(() => new UploadUnauthenticated({})))\n for (const guard of config[route] ?? []) {\n if ((yield* policy.decide(guard, { principal, interaction: route })) === true) return\n }\n return yield* new UploadForbidden({})\n }).pipe(Effect.provideContext(context)),\n })),\n )\n\nexport const GuardMedia = { uploadPolicy } as const\n"],"mappings":";;;;;;;;;;;;AAiCA,MAAM,SAAS,YACb,IAAI,SAAS,QAAQ,WAAW,IAC5B,OAAO,KAAK,IAAI,IAAI,QAAQ,WAAW,CAAC,IACxC,kBAAkB,MAAM,OAAO;AAIrC,MAAM,eAAe,YACnB,OAAO,IACL,MAAM,OAAO,IACb,QAAO,IAAI,QAAQ,KAAK;CAAE,QAAQ,QAAQ;CAAQ,SAAS,QAAQ;AAAQ,CAAC,CAC9E;;;;;;;;AASF,MAAM,gBACJ,QACA,WAEA,MAAM,OACJ,cACA,OAAO,IAAI,OAAO,QAAW,IAAG,aAAY,EAC1C,QAAQ,SAA8C,UACpD,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,OAAO,MAAM,YAAY,OAAO,GAAG;EACtD,cAAc,OAAO,KAAK,IAAI,sBAAsB,CAAC,CAAC,CAAC;EACvD,QAAQ,OAAO;CACjB,CAAC;CACD,MAAM,YAAY,OAAO,OACtB,QAAQ,KAAK,CAAC,CACd,KAAK,OAAO,eAAe,IAAI,sBAAsB,CAAC,CAAC,CAAC,CAAC;CAC5D,KAAK,MAAM,SAAS,OAAO,UAAU,CAAC,GACpC,KAAK,OAAO,OAAO,OAAO,OAAO;EAAE;EAAW,aAAa;CAAM,CAAC,OAAO,MAAM;CAEjF,OAAO,OAAO,IAAI,gBAAgB,CAAC,CAAC;AACtC,CAAC,CAAC,CAAC,KAAK,OAAO,eAAe,OAAO,CAAC,EAC1C,EAAE,CACJ;AAEF,MAAa,aAAa,EAAE,aAAa"}
package/dist/server.d.mts CHANGED
@@ -56,12 +56,23 @@ export declare const GuardServer: {
56
56
  * from, and a create whose input sets a preset field is a mistake of the
57
57
  * server's, refused.
58
58
  *
59
+ * `revision` names a field stored as a number, which the writer moves on by
60
+ * one with each write it lands. An update or a delete then lands only on the
61
+ * revision its rules were decided over (the writer's `expect`), so a change
62
+ * between the check and the write is never written over; it is decided
63
+ * again against the row as it now is, up to three times. A change that does
64
+ * not move the revision (a handler's, `applyEdits`', raw SQL) is not seen.
65
+ * Without `revision`, none is, and `validate` warns. An input that expects a
66
+ * revision the row read is not at is a `Conflict`, decided before any rule;
67
+ * an input may expect only the field the writer pins.
68
+ *
59
69
  * ```ts
60
70
  * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
61
71
  * ```
62
72
  */
63
73
  writer: <E extends AnyEntity, User, R, RW>(entity: E, policy: Policy<User, R>, writer: EntityWriter<Option.Option<User>, RW>, options?: {
64
74
  readonly presets?: { readonly [K in keyof E['fields']]?: (user: User) => E['fields'][K]['schema']['Type']; };
75
+ readonly revision?: keyof E['fields'] & string;
65
76
  }) => EntityWriter<Option.Option<User>, R | RW>;
66
77
  /**
67
78
  * A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";;;;;;qBAyCa;;;;;;;;;;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;;;;;;;EAoEtC,SAAS,MAAI,QAAU,OAAO,OAAK,UAAY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
2
  import { t as Condition } from "./condition-Dunujvzy.mjs";
3
3
  import "./me-DeSZOGt3.mjs";
4
4
  import { n as rowRules, r as writeRules, t as memberRules } from "./placed-CkyMqxFw.mjs";
5
- import { Effect, Match, Option, Schema } from "effect";
6
- import { Query } from "foldkit-entity";
7
- import { RemoteServer, RemoteServerError } from "foldkit-remote-server";
5
+ import { Effect, Match, Option, Schema, SchemaAST } from "effect";
6
+ import { Entity, Query } from "foldkit-entity";
7
+ import { RemoteInvalid, RemoteServer, RemoteServerError } from "foldkit-remote-server";
8
8
  //#region src/server.ts
9
9
  /**
10
10
  * A guard set's read rules as `foldkit-remote-server`'s seams: an
@@ -14,6 +14,12 @@ import { RemoteServer, RemoteServerError } from "foldkit-remote-server";
14
14
  * brings the server along.
15
15
  */
16
16
  const noMembers = (record) => record;
17
+ /** Two stored values, which are JSON: equal when they encode the same. */
18
+ const sameStored = (left, right) => JSON.stringify(left) === JSON.stringify(right);
19
+ /** The members of `fields` that have a Read rule, once each. */
20
+ const hiddenOf = (attachment, fields) => [...new Set(fields.map((field) => field.key).filter((key) => readRuled(attachment, key)))];
21
+ /** Each guarded writer's `revision`, or none: one a change can fall between check and write of. */
22
+ const pins = /* @__PURE__ */ new WeakMap();
17
23
  /** A ref key's two halves, `Entity:id`; `none` for anything else. */
18
24
  const refOf = (value) => {
19
25
  if (typeof value !== "string") return Option.none();
@@ -153,11 +159,27 @@ const GuardServer = {
153
159
  * from, and a create whose input sets a preset field is a mistake of the
154
160
  * server's, refused.
155
161
  *
162
+ * `revision` names a field stored as a number, which the writer moves on by
163
+ * one with each write it lands. An update or a delete then lands only on the
164
+ * revision its rules were decided over (the writer's `expect`), so a change
165
+ * between the check and the write is never written over; it is decided
166
+ * again against the row as it now is, up to three times. A change that does
167
+ * not move the revision (a handler's, `applyEdits`', raw SQL) is not seen.
168
+ * Without `revision`, none is, and `validate` warns. An input that expects a
169
+ * revision the row read is not at is a `Conflict`, decided before any rule;
170
+ * an input may expect only the field the writer pins.
171
+ *
156
172
  * ```ts
157
173
  * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
158
174
  * ```
159
175
  */
160
176
  writer: (entity, policy, writer, options = {}) => {
177
+ const revision = options.revision;
178
+ if (revision !== void 0) {
179
+ const field = Object.hasOwn(entity.fields, revision) ? entity.fields[revision] : void 0;
180
+ if (field === void 0) throw new Error(`[foldkit-guard] GuardServer.writer: ${entity.name} has no field "${revision}" for its revision`);
181
+ if (!SchemaAST.isNumber(Schema.toEncoded(field.schema).ast)) throw new Error(`[foldkit-guard] GuardServer.writer: ${entity.name}'s revision "${revision}" is not stored as a number`);
182
+ }
161
183
  const presets = Object.entries(options.presets ?? {}).map(([field, preset]) => {
162
184
  const declared = Object.hasOwn(entity.fields, field) ? entity.fields[field] : void 0;
163
185
  if (declared === void 0) throw new Error(`[foldkit-guard] GuardServer.writer: ${entity.name} has no field "${field}" to preset`);
@@ -204,59 +226,154 @@ const GuardServer = {
204
226
  ...more,
205
227
  ...rules.flatMap(({ condition }) => Condition.members(condition))
206
228
  ])];
229
+ /** The fields that say which version of the row was read: the revision, and the input's. */
230
+ const versionFields = (expect) => [...revision === void 0 ? [] : [revision], ...Option.match(expect, {
231
+ onNone: () => [],
232
+ onSome: ({ field }) => [field]
233
+ })];
234
+ /** Whether the row read is not at the revision the input expects. */
235
+ const moved = (expect, before) => Option.exists(expect, ({ field, revision }) => !sameStored(before[field], revision));
236
+ /** The write held to the row its rules were decided over, where there is a revision. */
237
+ const pin = (expect, before) => revision === void 0 ? expect : Option.some({
238
+ field: revision,
239
+ revision: before[revision]
240
+ });
241
+ /**
242
+ * `attempt` run again while its pinned write misses: the row moved after it
243
+ * was read, so it is decided again over the row as it now is. A write the
244
+ * input pinned misses as a conflict, and is not run again.
245
+ */
246
+ const pinned = (id, expect, missed, attempt) => {
247
+ if (revision === void 0) return attempt();
248
+ if (Option.isSome(expect)) return expect.value.field === revision ? attempt() : Effect.fail(new RemoteServerError({ message: `${entity.name}'s input expects "${expect.value.field}", but its writer pins "${revision}"` }));
249
+ const loop = (left) => Effect.flatMap(attempt(), (outcome) => !missed(outcome) ? Effect.succeed(outcome) : left > 1 ? loop(left - 1) : Effect.fail(new RemoteServerError({ message: `${entity.name} ${id} changed while it was written` })));
250
+ return loop(3);
251
+ };
252
+ const attachment = attached(entity);
253
+ const hiddenByBody = /* @__PURE__ */ new WeakMap();
254
+ const unnamed = new Set(Option.match(attachment, {
255
+ onNone: () => [],
256
+ onSome: (ruled) => Entity.invariants(entity).filter((held) => [...held.before, ...held.after].some((key) => readRuled(ruled, key))).map((held) => held.id)
257
+ }));
258
+ const told = (error) => error instanceof RemoteInvalid && Option.exists(error.rule, (rule) => unnamed.has(rule)) ? RemoteServer.invalid("The row would be invalid") : error;
259
+ /**
260
+ * Fails a write whose `when` reads, or whose `expect` names, a member with
261
+ * a Read rule: Unmet or written, Conflict or not, would answer for it.
262
+ * `validate` refuses the same at startup; this holds where it was not run.
263
+ */
264
+ const discloses = (expect, when) => Option.match(attachment, {
265
+ onNone: () => Effect.void,
266
+ onSome: (ruled) => {
267
+ const read = Option.match(when, {
268
+ onNone: () => [],
269
+ onSome: ({ body }) => {
270
+ const known = hiddenByBody.get(body);
271
+ if (known !== void 0) return known;
272
+ const hidden = hiddenOf(ruled, Query.dependencies(body).predicate);
273
+ hiddenByBody.set(body, hidden);
274
+ return hidden;
275
+ }
276
+ });
277
+ const expected = Option.match(expect, {
278
+ onNone: () => [],
279
+ onSome: ({ field }) => readRuled(ruled, field) ? [field] : []
280
+ });
281
+ const hidden = [.../* @__PURE__ */ new Set([...read, ...expected])];
282
+ return hidden.length === 0 ? Effect.void : Effect.fail(new RemoteServerError({ message: `${entity.name}'s write reads ${hidden.join(", ")}, which a Read rule hides from its writer` }));
283
+ }
284
+ });
285
+ /**
286
+ * The answer the writer's ledger holds for this operation, or else `write`:
287
+ * a retry of a write that landed is answered as it landed, not decided
288
+ * again over a row that may have moved since.
289
+ */
290
+ const answeredOr = (context, write) => {
291
+ const recorded = writer.recorded;
292
+ if (recorded === void 0 || Option.isNone(context.operation)) return write();
293
+ return Effect.flatMap(recorded({
294
+ operation: context.operation.value,
295
+ id: context.id,
296
+ principal: context.principal
297
+ }), Option.match({
298
+ onSome: (answer) => Effect.succeed(Option.some(answer)),
299
+ onNone: write
300
+ }));
301
+ };
207
302
  const memberRead = GuardServer.filter(entity, policy);
303
+ /** Refused before any rule, for what the write declares rather than what the row holds. */
304
+ const admitUpdate = (context) => Effect.andThen(discloses(context.expect, context.when), () => Object.keys(context.increments).length > 0 && Option.isNone(context.expect) && revision === void 0 ? Effect.fail(new RemoteServerError({ message: `${entity.name}'s increment expects no revision and its writer pins none, so its rules would judge a sum over a row that may move; give the writer a revision` })) : Effect.void);
305
+ /** The rules an update must meet: the row's, each member it sets, each relation it points. */
306
+ const updateRules = (context) => Effect.gen(function* () {
307
+ return {
308
+ row: yield* policy.writable(entity, context.principal, "Update"),
309
+ members: yield* policy.writeMembers(entity, context.principal, [...Object.keys(context.values), ...Object.keys(context.increments)], "Update"),
310
+ relating: yield* linkRules(context.principal, context.links)
311
+ };
312
+ });
313
+ /** The row as its writer may see it, with every field the rules and the version read. */
314
+ const readBefore = (context, rules) => read({
315
+ id: context.id,
316
+ fields: fieldsOf([
317
+ rules.row,
318
+ ...rules.members,
319
+ ...ruleOf(rules.relating)
320
+ ], [...Object.keys(context.links), ...versionFields(context.expect)]),
321
+ principal: context.principal
322
+ });
323
+ /** The rules, over the row as it is and as the write would leave it. */
324
+ const decideUpdate = (context, rules, before) => Effect.gen(function* () {
325
+ const { principal, values, increments, links } = context;
326
+ const linked = Object.keys(links);
327
+ const stored = writer.linked === void 0 || linked.length === 0 ? Option.none() : yield* writer.linked({
328
+ id: context.id,
329
+ relations: linked
330
+ });
331
+ const relations = linking(rules.relating, Option.some(Option.match(stored, {
332
+ onNone: () => ({
333
+ links: before,
334
+ exact: false
335
+ }),
336
+ onSome: (links) => ({
337
+ links,
338
+ exact: true
339
+ })
340
+ })));
341
+ const after = {
342
+ ...before,
343
+ ...values,
344
+ ...Object.fromEntries(Object.entries(increments).map(([field, amount]) => [field, Number(before[field]) + amount])),
345
+ ...Object.fromEntries(Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]))
346
+ };
347
+ yield* require([
348
+ rules.row,
349
+ ...rules.members,
350
+ ...relations
351
+ ], before, principal);
352
+ yield* require([rules.row], after, principal);
353
+ });
208
354
  const guarded = {
209
355
  entity: writer.entity,
356
+ ...writer.preconditions === true ? { preconditions: true } : {},
357
+ ...writer.increments === true ? { increments: true } : {},
358
+ ...writer.ledger === true ? { ledger: true } : {},
359
+ ...writer.invariants === true ? { invariants: true } : {},
360
+ ...writer.recorded === void 0 ? {} : { recorded: writer.recorded },
210
361
  read: ({ id, fields, principal }) => seenRow({ filter: memberRead }, (seen) => read({
211
362
  id,
212
363
  fields: seen,
213
364
  principal
214
365
  }), principal, fields, id),
215
- update: (context) => Effect.gen(function* () {
216
- const { principal, values, links } = context;
217
- const row = yield* policy.writable(entity, principal, "Update");
218
- const members = yield* policy.writeMembers(entity, principal, Object.keys(values), "Update");
219
- const relating = yield* linkRules(principal, links);
220
- const fields = fieldsOf([
221
- row,
222
- ...members,
223
- ...ruleOf(relating)
224
- ], Object.keys(links));
225
- const current = yield* read({
226
- id: context.id,
227
- fields,
228
- principal
229
- });
230
- if (Option.isNone(current)) return yield* Effect.fail(refused(row.deny));
231
- const before = current.value;
232
- const linked = Object.keys(links);
233
- const stored = writer.linked === void 0 || linked.length === 0 ? Option.none() : yield* writer.linked({
234
- id: context.id,
235
- relations: linked
366
+ update: (context) => Effect.mapError(Effect.andThen(admitUpdate(context), () => answeredOr(context, () => pinned(context.id, context.expect, Option.isNone, () => Effect.gen(function* () {
367
+ const rules = yield* updateRules(context);
368
+ const current = yield* readBefore(context, rules);
369
+ if (Option.isNone(current)) return yield* Effect.fail(refused(rules.row.deny));
370
+ if (moved(context.expect, current.value)) return Option.none();
371
+ yield* decideUpdate(context, rules, current.value);
372
+ return yield* writer.update({
373
+ ...context,
374
+ expect: pin(context.expect, current.value)
236
375
  });
237
- const relations = linking(relating, Option.some(Option.match(stored, {
238
- onNone: () => ({
239
- links: before,
240
- exact: false
241
- }),
242
- onSome: (links) => ({
243
- links,
244
- exact: true
245
- })
246
- })));
247
- const after = {
248
- ...before,
249
- ...values,
250
- ...Object.fromEntries(Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]))
251
- };
252
- yield* require([
253
- row,
254
- ...members,
255
- ...relations
256
- ], before, principal);
257
- yield* require([row], after, principal);
258
- return yield* writer.update(context);
259
- }),
376
+ })))), told),
260
377
  insert: (given) => Effect.gen(function* () {
261
378
  const preset = presets.find(({ field }) => Object.hasOwn(given.values, field));
262
379
  if (preset !== void 0) return yield* new RemoteServerError({ message: `${entity.name}'s "${preset.field}" is preset by the server; the input may not set it` });
@@ -291,20 +408,25 @@ const GuardServer = {
291
408
  ...rule,
292
409
  condition: Condition.unsetting(rule.condition, unset)
293
410
  })), proposed, principal);
294
- return yield* writer.insert(context);
411
+ return yield* Effect.mapError(writer.insert(context), told);
295
412
  }),
296
- delete: (context) => Effect.gen(function* () {
413
+ delete: (context) => Effect.andThen(discloses(context.expect, context.when), () => pinned(context.id, context.expect, (outcome) => outcome === "moved", () => Effect.gen(function* () {
297
414
  const row = yield* policy.writable(entity, context.principal, "Delete");
298
415
  const current = yield* read({
299
416
  id: context.id,
300
- fields: fieldsOf([row], []),
417
+ fields: fieldsOf([row], versionFields(context.expect)),
301
418
  principal: context.principal
302
419
  });
303
420
  if (Option.isNone(current)) return "absent";
421
+ if (moved(context.expect, current.value)) return "moved";
304
422
  yield* require([row], current.value, context.principal);
305
- return yield* writer.delete(context);
306
- })
423
+ return yield* writer.delete({
424
+ ...context,
425
+ expect: pin(context.expect, current.value)
426
+ });
427
+ })))
307
428
  };
429
+ pins.set(guarded, Option.fromUndefinedOr(revision));
308
430
  return writeRules.add(guarded, policy, [entity]);
309
431
  },
310
432
  /**
@@ -414,10 +536,24 @@ const GuardServer = {
414
536
  const bodyProblems = [...config.domain.registry.queries].flatMap(([queryName, { body }]) => {
415
537
  if (body === void 0 || body.entity.name !== name) return [];
416
538
  const { predicate, order } = Query.dependencies(body);
417
- const hidden = (fields) => [...new Set(fields.map((field) => field.key).filter((key) => readRuled(attachment, key)))];
418
- return [...hidden(predicate).map((member) => `query ${queryName} filters ${name} by ${member}, which has a Read rule`), ...hidden(order).map((member) => `query ${queryName} orders ${name} by ${member}, which has a Read rule`)];
539
+ return [...hiddenOf(attachment, predicate).map((member) => `query ${queryName} filters ${name} by ${member}, which has a Read rule`), ...hiddenOf(attachment, order).map((member) => `query ${queryName} orders ${name} by ${member}, which has a Read rule`)];
540
+ });
541
+ const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) => {
542
+ if (source.writes === void 0 || source.writes.entity !== name) return [];
543
+ if (!writeRules.has(source.writes.writer, policy, entity)) return [`write ${mutation} writes ${name} without its write rules`];
544
+ const { write, writer } = source.writes;
545
+ const when = Option.match(write.when, {
546
+ onNone: () => [],
547
+ onSome: (body) => hiddenOf(attachment, Query.dependencies(body).predicate)
548
+ });
549
+ const expected = write.expect?.field.key;
550
+ const pin = typeof writer === "object" && writer !== null ? pins.get(writer) : void 0;
551
+ return [
552
+ ...when.map((member) => `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`),
553
+ ...expected !== void 0 && readRuled(attachment, expected) ? [`write ${mutation} expects ${name}'s ${expected}, which has a Read rule`] : [],
554
+ ...expected !== void 0 && pin !== void 0 && Option.exists(pin, (field) => field !== expected) ? [`write ${mutation} expects ${name}'s ${expected}, but its writer pins ${Option.getOrThrow(pin)}`] : []
555
+ ];
419
556
  });
420
- const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) => source.writes !== void 0 && source.writes.entity === name && !writeRules.has(source.writes.writer, policy, entity) ? [`write ${mutation} writes ${name} without its write rules`] : []);
421
557
  const shared = Option.match(source, {
422
558
  onNone: () => [],
423
559
  onSome: (source) => [...source.shared ?? []]
@@ -442,6 +578,12 @@ const GuardServer = {
442
578
  }));
443
579
  const problems = [...undeclared, ...entityProblems];
444
580
  if (problems.length > 0) throw new Error(`[foldkit-guard] GuardServer.validate: ${problems.join("; ")}`);
581
+ const unpinnedWrites = [...config.server.mutations].flatMap(([mutation, source]) => {
582
+ const writer = source.writes?.writer;
583
+ const pin = typeof writer === "object" && writer !== null ? pins.get(writer) : void 0;
584
+ return pin !== void 0 && Option.isNone(pin) ? [mutation] : [];
585
+ });
586
+ if (unpinnedWrites.length > 0) console.warn(`[foldkit-guard] GuardServer.validate: ${unpinnedWrites.join(", ")} ${unpinnedWrites.length === 1 ? "writes" : "write"} through a GuardServer.writer with no revision, so a change between its check and its write is not seen; pass { revision }`);
445
587
  }
446
588
  };
447
589
  /** Whether a read asks for `may`, of an Entity that has it (`Guards.may`). */
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","names":[],"sources":["../src/server.ts"],"sourcesContent":["/**\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 } from 'effect'\nimport { Query, type AnyEntity, type AnyQuery } from 'foldkit-entity'\nimport type { MutationDescriptor, RemoteForbidden } from 'foldkit-remote'\nimport {\n RemoteServer,\n RemoteServerError,\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} from 'foldkit-remote-server'\nimport { attached, readRowsRuled, readRuled, type Deny, type InteractionKey } from './attach.js'\nimport { Condition, type RowRule } from './condition.js'\nimport type { Policy } from './index.js'\nimport type { MayAnswer } from './may.js'\nimport { ME, type MeEntity } from './me.js'\nimport { memberRules, rowRules, writeRules } from './placed.js'\n\nconst noMembers = (record: EntityRecord) => record\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 (Condition.holds(condition, record.values, input, () => false)) 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(condition, values, input, 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 )\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 (an\n * update's over the row as it would be after it too, so a write cannot move\n * a row out of its writer's reach), each member it sets must allow setting\n * it, and each relation it points elsewhere must allow the unlink and the\n * link. 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 * `presets` are fields a create takes from who is asking, never from the\n * client (`ownerId: user => user.id`): set before the rules are checked, so\n * a rule over them holds of the creator. A visitor has nothing to preset\n * from, and a create whose input sets a preset field is a mistake of the\n * server's, refused.\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 presets?: {\n readonly [K in keyof E['fields']]?: (user: User) => E['fields'][K]['schema']['Type']\n }\n } = {},\n ): EntityWriter<Option.Option<User>, R | RW> => {\n const presets = Object.entries(options.presets ?? {}).map(([field, preset]) => {\n const declared = Object.hasOwn(entity.fields, field)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[field]\n : undefined\n if (declared === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${field}\" to preset`,\n )\n }\n const encode = Schema.encodeUnknownSync(\n declared.schema as unknown as Schema.Codec<unknown, unknown>,\n )\n return { field, value: (user: User) => encode((preset as (user: User) => unknown)(user)) }\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 const holds = (\n rule: { readonly condition: Condition },\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) => Condition.holds(rule.condition, values, policy.inputOf(principal), () => false)\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 // What an answer shows: the row as the writer may see it, members ruled.\n const memberRead = GuardServer.filter(entity, policy)\n const guarded: EntityWriter<Option.Option<User>, R | RW> = {\n entity: writer.entity,\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.gen(function* () {\n const { principal, values, links } = context\n const row = yield* policy.writable(entity, principal, 'Update')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n Object.keys(values),\n 'Update',\n )\n const relating = yield* linkRules(principal, links)\n const fields = fieldsOf([row, ...members, ...ruleOf(relating)], Object.keys(links))\n const current = yield* read({ id: context.id, fields, principal })\n if (Option.isNone(current)) return yield* Effect.fail(refused(row.deny))\n const before = current.value\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 relations = linking(\n relating,\n Option.some(\n Option.match(stored, {\n onNone: () => ({ links: before, exact: false }),\n onSome: links => ({ links, exact: true }),\n }),\n ),\n )\n const after = {\n ...before,\n ...values,\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n yield* require([row, ...members, ...relations], before, principal)\n yield* require([row], after, principal)\n return yield* writer.update(context)\n }),\n insert: given =>\n Effect.gen(function* () {\n const preset = presets.find(({ field }) => Object.hasOwn(given.values, field))\n if (preset !== undefined) {\n return yield* new RemoteServerError({\n message: `${entity.name}'s \"${preset.field}\" is preset by the server; the input may not set it`,\n })\n }\n if (presets.length > 0 && Option.isNone(given.principal)) {\n return yield* Effect.fail(RemoteServer.forbid())\n }\n const context = Option.match(given.principal, {\n onNone: () => given,\n onSome: user => ({\n ...given,\n values: {\n ...given.values,\n ...Object.fromEntries(presets.map(({ field, value }) => [field, value(user)])),\n },\n }),\n })\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* writer.insert(context)\n }),\n delete: context =>\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], []),\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 yield* require([row], current.value, context.principal)\n return yield* writer.delete(context)\n }),\n }\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)) {\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)\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, which would answer for the\n * value it 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.\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 },\n ): void => {\n const byName = new Map(config.entities.map(entity => [entity.name, entity]))\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 } = Query.dependencies(body)\n const hidden = (fields: typeof predicate) => [\n ...new Set(\n fields.map(field => field.key).filter(key => readRuled(attachment, key)),\n ),\n ]\n return [\n ...hidden(predicate).map(\n member =>\n `query ${queryName} filters ${name} by ${member}, which has a Read rule`,\n ),\n ...hidden(order).map(\n member => `query ${queryName} orders ${name} by ${member}, which has a Read rule`,\n ),\n ]\n },\n )\n const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) =>\n source.writes !== undefined &&\n source.writes.entity === name &&\n !writeRules.has(source.writes.writer, policy, entity)\n ? [`write ${mutation} writes ${name} without its write rules`]\n : [],\n )\n // A shared field goes to every live subscriber as written: no rule may tell them apart.\n const shared = 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 ...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 live Source of its own streams whatever it reads: nothing here can check it.\n const liveProblems = config.server.live.has(name)\n ? [`${name} has a live Source of its own; serve its changes through a live hub`]\n : []\n return [\n ...sourceProblems,\n ...queryProblems,\n ...bodyProblems,\n ...writeProblems,\n ...sharedProblems,\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 },\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/** The interactions a row answers `may` for: `Update`, `Delete`, and each one the set named. */\nconst builtInRow = new Set(['Read', 'Create', 'Update', 'Delete'])\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 const attachment = attached(entity)\n const named = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ row }) => Object.keys(row).filter(interaction => !builtInRow.has(interaction)),\n })\n const ruledMembers = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ members }) => Object.keys(members),\n })\n const ruledRelations = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ relations }) => Object.keys(relations),\n })\n return Effect.map(\n Effect.all([\n Effect.forEach(['Update', 'Delete', ...named], interaction =>\n Effect.map(\n // A named one was attached as an `InteractionKey`; its key is the name.\n policy.writable(entity, principal, interaction as InteractionKey),\n rule => [interaction, rule] as const,\n ),\n ),\n policy.writeMembers(entity, principal, ruledMembers, 'Update'),\n Effect.forEach(ruledRelations, relation =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Link'),\n policy.linkable(entity, principal, relation, 'Unlink'),\n ]),\n ([link, unlink]) => ({ relation, link, unlink }),\n ),\n ),\n ]),\n ([rows, members, relations]): MayPlan => {\n const input = policy.inputOf(principal)\n const holds = (condition: Condition, values: Readonly<Record<string, unknown>>) =>\n Condition.holds(condition, values, input, () => false)\n // A relation without a rule for one direction leaves it to the row's Update.\n const allows = (rule: Option.Option<RowRule>, values: Readonly<Record<string, unknown>>) =>\n Option.match(rule, {\n onNone: () => true,\n onSome: ({ condition }) => holds(condition, values),\n })\n const conditions = [\n ...rows.map(([, { condition }]) => condition),\n ...members.map(({ condition }) => condition),\n ...relations.flatMap(({ link, unlink }) =>\n [...Option.toArray(link), ...Option.toArray(unlink)].map(({ condition }) => condition),\n ),\n ]\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(conditions.flatMap(Condition.members))],\n answer: values => ({\n row: Object.fromEntries(\n rows.map(([interaction, { condition }]) => [interaction, holds(condition, values)]),\n ),\n // Only an `explain`'s sentence is for whoever asked.\n reasons: Object.fromEntries(\n rows.flatMap(([interaction, { condition, deny }]) =>\n holds(condition, values)\n ? []\n : Match.valueTags(deny, {\n Explain: ({ reason }) => [[interaction, reason] as const],\n Forbidden: () => [],\n NotFound: () => [],\n Omit: () => [],\n Redact: () => [],\n }),\n ),\n ),\n members: Object.fromEntries(\n members.map(({ member, condition }) => [member, holds(condition, values)]),\n ),\n relations: Object.fromEntries(\n relations.map(({ relation, link, unlink }) => [\n relation,\n { Link: allows(link, values), Unlink: allows(unlink, values) },\n ]),\n ),\n }),\n }\n },\n )\n}\n\n/** A refused write as the client receives it: the sentence an `explain` gave, or none. */\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":";;;;;;;;;;;;;;;AA8BA,MAAM,aAAa,WAAyB;;AAG5C,MAAM,SAAS,UAAoF;CACjG,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,KAAK;CAClD,MAAM,QAAQ,MAAM,QAAQ,GAAG;CAC/B,OAAO,SAAS,IACZ,OAAO,KAAK,IACZ,OAAO,KAAK;EAAE,QAAQ,MAAM,MAAM,GAAG,KAAK;EAAG,IAAI,MAAM,MAAM,QAAQ,CAAC;CAAE,CAAC;AAC/E;AAEA,MAAa,cAAc;;;;;;;;;;CAUzB,KACE,QACA,WACyC;EAEzC,OAAO,IAAI,SAAS,MAAM,IAAI,EAAE,UAAU;GACxC,IAAI,QAAQ,OAAO,KACjB,MAAM,IAAI,MACR,4DAA4D,IAAI,QAAQ,OAAO,KACjF;EAEJ,CAAC;EACD,OAAO;GACL,GAAG,aAAa,OAA+B,QAAQ;IACrD,OAAO,EAAE,KAAK,gBACZ,OAAO,QACL,IACG,QAAO,OAAM,OAAA,IAAS,CAAC,CACvB,KAAI,QAAO;KACV;KACA,QAAQ;MACN,UAAU,OAAO,OAAO,SAAS;MAEjC,KAAK,OAAO,MAAM,WAAW;OAC3B,cAAc;OACd,QAAQ,OAAO;MACjB,CAAC;KACH;IACF,EAAE,CACN;IACF,QAAQ,YAAY,OAAO,QAAQ,MAAM;GAC3C,CAAC;GAID,SAAS,SAAS,IAAI,OAAO,OAAO,EAAE,OAAO,sBAAsB,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC;EACzF;CACF;;;;;;;;;;CAWA,SAAkB,QAAmB,WACnC,YAAY,KAER,WACA,WAEA,OAAO,IACL,OAAO,IAAI,CACT,OAAO,YAAY,QAAQ,WAAW,MAAM,GAE5C,QAAQ,QAAQ,MAAM,IAClB,OAAO,IAAI,MAAM,QAAQ,QAAQ,SAAS,GAAG,O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zF;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/server.ts"],"sourcesContent":["/**\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 } from 'effect'\nimport { Entity, Query, type AnyEntity, type AnyQuery } from 'foldkit-entity'\nimport type { MutationDescriptor, RemoteForbidden } from 'foldkit-remote'\nimport {\n RemoteInvalid,\n RemoteServer,\n RemoteServerError,\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 WriteWhen,\n} from 'foldkit-remote-server'\nimport {\n attached,\n readRowsRuled,\n readRuled,\n type Attachment,\n type Deny,\n type InteractionKey,\n} from './attach.js'\nimport { Condition, type RowRule } from './condition.js'\nimport type { Policy } from './index.js'\nimport type { MayAnswer } from './may.js'\nimport { ME, type MeEntity } from './me.js'\nimport { memberRules, rowRules, writeRules } from './placed.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/** 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 (Condition.holds(condition, record.values, input, () => false)) 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(condition, values, input, 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 )\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 (an\n * update's over the row as it would be after it too, so a write cannot move\n * a row out of its writer's reach), each member it sets must allow setting\n * it, and each relation it points elsewhere must allow the unlink and the\n * link. 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 * `presets` are fields a create takes from who is asking, never from the\n * client (`ownerId: user => user.id`): set before the rules are checked, so\n * a rule over them holds of the creator. A visitor has nothing to preset\n * from, and a create whose input sets a preset field is a mistake of the\n * server's, refused.\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. 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 presets?: {\n readonly [K in keyof E['fields']]?: (user: User) => E['fields'][K]['schema']['Type']\n }\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 const presets = Object.entries(options.presets ?? {}).map(([field, preset]) => {\n const declared = Object.hasOwn(entity.fields, field)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[field]\n : undefined\n if (declared === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${field}\" to preset`,\n )\n }\n const encode = Schema.encodeUnknownSync(\n declared.schema as unknown as Schema.Codec<unknown, unknown>,\n )\n return { field, value: (user: User) => encode((preset as (user: User) => unknown)(user)) }\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 const holds = (\n rule: { readonly condition: Condition },\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) => Condition.holds(rule.condition, values, policy.inputOf(principal), () => false)\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, or whose `expect` names, a member with\n * a Read rule: Unmet or written, Conflict or not, 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 ): 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 hidden = [...new Set([...read, ...expected])]\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, or else `write`:\n * a retry of a write that landed is answered as it landed, not decided\n * again over a row that may have moved since.\n */\n const answeredOr = <E, RA>(\n context: {\n readonly id: string\n readonly operation: Option.Option<string>\n readonly principal: Option.Option<User>\n },\n write: () => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, 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 id: context.id,\n principal: context.principal,\n }),\n Option.match({ onSome: answer => Effect.succeed(Option.some(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<RowRule>\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), () =>\n // The rules judge a sum over the row read: unpinned, that is not the row written.\n Object.keys(context.increments).length > 0 &&\n Option.isNone(context.expect) &&\n revision === undefined\n ? Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s increment expects no revision and its writer pins none, so its rules would judge a sum over a row that may move; give the writer a revision`,\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 // An incremented field is set as surely as a written one: its Update rule holds.\n const members = yield* policy.writeMembers(\n entity,\n context.principal,\n [...Object.keys(context.values), ...Object.keys(context.increments)],\n 'Update',\n )\n const relating = yield* linkRules(context.principal, context.links)\n return { row, members, relating } satisfies UpdateRules\n })\n /** The row as its writer may see it, with every field the rules and the version read. */\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 [...Object.keys(context.links), ...versionFields(context.expect)],\n ),\n principal: context.principal,\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, values, increments, 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 relations = linking(\n rules.relating,\n Option.some(\n Option.match(stored, {\n onNone: () => ({ links: before, exact: false }),\n onSome: links => ({ links, exact: true }),\n }),\n ),\n )\n // The sum the writer will store, over the row read, which the pin keeps as the row\n // written. Only a rule reads it, and `fieldsOf` read every field a rule reads.\n const after = {\n ...before,\n ...values,\n ...Object.fromEntries(\n Object.entries(increments).map(([field, amount]) => [\n field,\n Number(before[field]) + amount,\n ]),\n ),\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n yield* require([rules.row, ...rules.members, ...relations], before, principal)\n yield* require([rules.row], after, principal)\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.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 ...(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, () =>\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 yield* decideUpdate(context, rules, current.value)\n return yield* writer.update({\n ...context,\n expect: pin(context.expect, current.value),\n })\n }),\n ),\n ),\n ),\n told,\n ),\n insert: given =>\n Effect.gen(function* () {\n const preset = presets.find(({ field }) => Object.hasOwn(given.values, field))\n if (preset !== undefined) {\n return yield* new RemoteServerError({\n message: `${entity.name}'s \"${preset.field}\" is preset by the server; the input may not set it`,\n })\n }\n if (presets.length > 0 && Option.isNone(given.principal)) {\n return yield* Effect.fail(RemoteServer.forbid())\n }\n const context = Option.match(given.principal, {\n onNone: () => given,\n onSome: user => ({\n ...given,\n values: {\n ...given.values,\n ...Object.fromEntries(presets.map(({ field, value }) => [field, value(user)])),\n },\n }),\n })\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 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 yield* require([row], current.value, context.principal)\n return yield* writer.delete({\n ...context,\n expect: pin(context.expect, current.value),\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)) {\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)\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, which would answer for the\n * value it 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.\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 },\n ): void => {\n const byName = new Map(config.entities.map(entity => [entity.name, entity]))\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 } = Query.dependencies(body)\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 ]\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 // 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 expected = write.expect?.field.key\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n return [\n ...when.map(\n member =>\n `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`,\n ),\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 = 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 ...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 live Source of its own streams whatever it reads: nothing here can check it.\n const liveProblems = config.server.live.has(name)\n ? [`${name} has a live Source of its own; serve its changes through a live hub`]\n : []\n return [\n ...sourceProblems,\n ...queryProblems,\n ...bodyProblems,\n ...writeProblems,\n ...sharedProblems,\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 const unpinnedWrites = [...config.server.mutations].flatMap(([mutation, source]) => {\n const writer = source.writes?.writer\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n return pin !== undefined && Option.isNone(pin) ? [mutation] : []\n })\n if (unpinnedWrites.length > 0) {\n console.warn(\n `[foldkit-guard] GuardServer.validate: ${unpinnedWrites.join(', ')} ${unpinnedWrites.length === 1 ? 'writes' : 'write'} through a GuardServer.writer with no revision, so a change between its check and its write is not seen; pass { revision }`,\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/** The interactions a row answers `may` for: `Update`, `Delete`, and each one the set named. */\nconst builtInRow = new Set(['Read', 'Create', 'Update', 'Delete'])\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 const attachment = attached(entity)\n const named = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ row }) => Object.keys(row).filter(interaction => !builtInRow.has(interaction)),\n })\n const ruledMembers = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ members }) => Object.keys(members),\n })\n const ruledRelations = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ relations }) => Object.keys(relations),\n })\n return Effect.map(\n Effect.all([\n Effect.forEach(['Update', 'Delete', ...named], interaction =>\n Effect.map(\n // A named one was attached as an `InteractionKey`; its key is the name.\n policy.writable(entity, principal, interaction as InteractionKey),\n rule => [interaction, rule] as const,\n ),\n ),\n policy.writeMembers(entity, principal, ruledMembers, 'Update'),\n Effect.forEach(ruledRelations, relation =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Link'),\n policy.linkable(entity, principal, relation, 'Unlink'),\n ]),\n ([link, unlink]) => ({ relation, link, unlink }),\n ),\n ),\n ]),\n ([rows, members, relations]): MayPlan => {\n const input = policy.inputOf(principal)\n const holds = (condition: Condition, values: Readonly<Record<string, unknown>>) =>\n Condition.holds(condition, values, input, () => false)\n // A relation without a rule for one direction leaves it to the row's Update.\n const allows = (rule: Option.Option<RowRule>, values: Readonly<Record<string, unknown>>) =>\n Option.match(rule, {\n onNone: () => true,\n onSome: ({ condition }) => holds(condition, values),\n })\n const conditions = [\n ...rows.map(([, { condition }]) => condition),\n ...members.map(({ condition }) => condition),\n ...relations.flatMap(({ link, unlink }) =>\n [...Option.toArray(link), ...Option.toArray(unlink)].map(({ condition }) => condition),\n ),\n ]\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(conditions.flatMap(Condition.members))],\n answer: values => ({\n row: Object.fromEntries(\n rows.map(([interaction, { condition }]) => [interaction, holds(condition, values)]),\n ),\n // Only an `explain`'s sentence is for whoever asked.\n reasons: Object.fromEntries(\n rows.flatMap(([interaction, { condition, deny }]) =>\n holds(condition, values)\n ? []\n : Match.valueTags(deny, {\n Explain: ({ reason }) => [[interaction, reason] as const],\n Forbidden: () => [],\n NotFound: () => [],\n Omit: () => [],\n Redact: () => [],\n }),\n ),\n ),\n members: Object.fromEntries(\n members.map(({ member, condition }) => [member, holds(condition, values)]),\n ),\n relations: Object.fromEntries(\n relations.map(({ relation, link, unlink }) => [\n relation,\n { Link: allows(link, values), Unlink: allows(unlink, values) },\n ]),\n ),\n }),\n }\n },\n )\n}\n\n/** A refused write as the client receives it: the sentence an `explain` gave, or none. */\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":";;;;;;;;;;;;;;;AAuCA,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;;AAGA,MAAM,uBAAO,IAAI,QAAuC;;AAGxD,MAAM,SAAS,UAAoF;CACjG,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,KAAK;CAClD,MAAM,QAAQ,MAAM,QAAQ,GAAG;CAC/B,OAAO,SAAS,IACZ,OAAO,KAAK,IACZ,OAAO,KAAK;EAAE,QAAQ,MAAM,MA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;CAAU,IACpC,OAAO,IAAI,OAAO,WAAW,OAAO;CAE1C,MAAM,MAAM,OAAO,KAAK,CAAC,mBAAG,IAAI,IAAI,CAAC,MAAM,GAAG,KAAK,MAAM,CAAC,CAAC,CAAC;CAC5D,OAAO,OAAO,IAAI,MAAK,WAAU;EAC/B,MAAM,QAAQ,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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-guard",
3
- "version": "0.3.0",
3
+ "version": "0.4.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",
@@ -48,6 +48,11 @@
48
48
  "foldkit-plus:source": "./src/sync.ts",
49
49
  "types": "./dist/sync.d.mts",
50
50
  "import": "./dist/sync.mjs"
51
+ },
52
+ "./media": {
53
+ "foldkit-plus:source": "./src/media.ts",
54
+ "types": "./dist/media.d.mts",
55
+ "import": "./dist/media.mjs"
51
56
  }
52
57
  },
53
58
  "files": [
@@ -57,20 +62,24 @@
57
62
  ],
58
63
  "dependencies": {
59
64
  "foldkit-metadata": "0.1.0",
60
- "foldkit-entity": "0.10.0"
65
+ "foldkit-entity": "0.11.0"
61
66
  },
62
67
  "peerDependencies": {
63
- "drizzle-orm": "1.0.0-rc.4",
68
+ "drizzle-orm": "1.0.0-rc.5",
64
69
  "effect": "^4.0.0",
65
- "foldkit-remote-drizzle": "^0.12.2",
66
- "foldkit-remote-server": "^0.14.0",
67
- "foldkit-remote": "^0.18.0",
68
- "foldkit-sync": "^0.12.0"
70
+ "foldkit-media": "^0.2.0",
71
+ "foldkit-remote-server": "^0.16.0",
72
+ "foldkit-remote": "^0.19.0",
73
+ "foldkit-sync": "^0.12.2",
74
+ "foldkit-remote-drizzle": "^0.13.0"
69
75
  },
70
76
  "peerDependenciesMeta": {
71
77
  "drizzle-orm": {
72
78
  "optional": true
73
79
  },
80
+ "foldkit-media": {
81
+ "optional": true
82
+ },
74
83
  "foldkit-remote": {
75
84
  "optional": true
76
85
  },
@@ -85,17 +94,18 @@
85
94
  }
86
95
  },
87
96
  "devDependencies": {
88
- "drizzle-orm": "1.0.0-rc.4",
89
- "effect": "^4.0.4",
90
- "foldkit": "0.168.0",
97
+ "drizzle-orm": "1.0.0-rc.5",
98
+ "effect": "^4.0.5",
99
+ "foldkit": "0.169.0",
91
100
  "tsdown": "^0.23.1",
92
101
  "typescript": "7.0.2",
93
- "foldkit-remote": "0.18.0",
94
- "foldkit-agent": "0.8.1",
95
- "foldkit-remote-server": "0.14.0",
96
- "foldkit-remote-drizzle": "0.12.2",
97
- "foldkit-sync": "0.12.0",
98
- "foldkit-surface": "0.10.0"
102
+ "foldkit-media": "0.2.0",
103
+ "foldkit-remote-server": "0.16.0",
104
+ "foldkit-remote": "0.19.0",
105
+ "foldkit-agent": "0.8.3",
106
+ "foldkit-surface": "0.10.2",
107
+ "foldkit-sync": "0.12.2",
108
+ "foldkit-remote-drizzle": "0.13.0"
99
109
  },
100
110
  "scripts": {
101
111
  "build": "tsdown",